$(document).ready(pageLoaderInit);

var div_id_to_fill = 'content';

function div_slide_up(){
    return "<div id=\"slideup\" onclick=\"javascript:$(\'#" + div_id_to_fill + "\').slideUp(\'slow\')\">затвори<\/div>";
}

function trim(str){
  return str.replace(/^\s*|\s*$/g,"");
}

function validateAddStory(){
  valid = true;
  namevalue = trim(document.getElementById('addstory-form').Name.value);
  catidx = document.getElementById('addstory-form').cat.selectedIndex;
  msgvalue = trim(document.getElementById('addstory-form').Message.value);

  document.getElementById( 'errname'    ).innerHTML = "";
  document.getElementById( 'errcat'     ).innerHTML = "";
  document.getElementById( 'errmessage' ).innerHTML = "";

  if (namevalue.length <= 0){
    document.getElementById('errname').innerHTML = "Моля, въведете име!";
    valid = false;
  }

  if (catidx <= 0){
    document.getElementById('errcat').innerHTML = "Моля, изберете категория!";
    valid = false;
  }

  if (msgvalue.length <= 0){
    document.getElementById('errmessage').innerHTML = "Моля, въведете текст на съобщението!";
    valid = false;
  }

  if (msgvalue.length > 500){
    document.getElementById('errmessage').innerHTML = "Въведеният текст е твърде голям (максимум 500 знака)!";
    valid = false;
  }

  return valid;
}

function formtool_count_chars(textField, countField, maxlen, show_alert) {
    if(textField != null && textField.value != null) {
	    if (textField.value.length > maxlen){
            if(show_alert)
               alert('Позволени са максимум ' +  maxlen + ' символа.');
            textField.value = textField.value.substring(0, maxlen);
	    } else {
            countField.value = maxlen - textField.value.length;
	    }
    }
}

function pageLoaderInit(){

  $("#addstory-form").submit(function(event) {
    if (!validateAddStory()){
      return false;
    }
    event.preventDefault();
    var strdata = $(this).serialize();
    var submiturl = $("#addstory-form").attr("action");
    document.getElementById(div_id_to_fill).innerHTML = '<center><img src="' + loadingIMG.src + '" /></center>';

    $.ajax({
        type: "POST",
        url: submiturl,
        data: strdata,
        success: function(msg){
            $("#"+div_id_to_fill).ajaxComplete(function(event, request, settings){
                var content = msg;
                content = content.split('id="content"')[1];
                content = content.substring(content.indexOf('>')+1);
                var depth=1;
                var output='';
                while(depth>0){
                  temp = content.split('</div>')[0];
                  //count occurrences
                  i=0;
                  pos = temp.indexOf("<div");
                  while(pos!=-1){
                    i++;
                    pos = temp.indexOf("<div",pos+1);
                  }
                  //end count
                  depth=depth+i-1;
                  output=output+content.split('</div>')[0]+'</div>';
                  content = content.substring(content.indexOf('</div>')+6);
                }

                $("#"+div_id_to_fill).hide();
                document.getElementById(div_id_to_fill).innerHTML = output + div_slide_up();
                //$("#addStory").html(output);
                $("#"+div_id_to_fill).slideDown("slow");
                //$(this).innerHTML=output;
            });
        }
    });

    //return false;
  })


  $("a").click(function(event){
    if((this.href.indexOf(home)>=0)&&(this.href.indexOf('/wp-')<0)&&((this.href.indexOf('page_id=4')>=0)||(this.href.indexOf('add-new-story')>=0))){
    /*if(this.href.split('?')[1].split('=')[0]=='m'||
       this.href.split('?')[1].split('=')[0]=='p'||
       this.href.split('?')[1].split('=')[0]=='cat'||
       this.href.split('?')[1].split('=')[0]=='page_id'){*/
      // stop default behaviour
      event.preventDefault();
      // remove click border
      this.blur();
      // get caption: either title or name attribute
      var caption = this.title || this.name || "";
      // get rel attribute for image groups
      var group = this.rel || false;

      div_id_to_fill = 'addStory';
      loadPage(this.href);                                              
    }
  });
  //document.getElementById('searchform').name='searchform';
  //document.searchform.action="javascript:submitSearch('?s='+document.getElementById('s').value)";
}
function getHTTPObject() {
  var xmlhttp;
  if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
    try {
      xmlhttp = new XMLHttpRequest();
    } catch (e) {
      xmlhttp = false;
    }
  }
  return xmlhttp;
}
var isWorking = false;
var http = getHTTPObject();
function loadPage(url){
  if(!isWorking){
    scroll(0,0);
    $("#"+div_id_to_fill).slideUp("slow");
    document.getElementById(div_id_to_fill).innerHTML='<center><img src="' + loadingIMG.src + '" /></center>';
    http.open('GET',url,true);
    isWorking=true;
    http.onreadystatechange=showPage;
    http.send(null);
  }
}
function submitSearch(param){
  if(!isWorking){
    scroll(0,0);
    document.getElementById('content').innerHTML='<center><img src="' + loadingIMG.src + '" /></center>';
    http.open('GET',window.location+param,true);
    isWorking=true;
    http.onreadystatechange=showPage;
    http.send(null);
  }
}
function showPage(){
  if(http.readyState==4){
    if(http.status==200){
      isWorking=false;
      var content = http.responseText;
      content = content.split('id="content"')[1];
      content = content.substring(content.indexOf('>')+1);
      var depth=1;
      var output='';
      while(depth>0){
        temp = content.split('</div>')[0];
        //count occurrences
        i=0;
        pos = temp.indexOf("<div");
        while(pos!=-1){
          i++;
          pos = temp.indexOf("<div",pos+1);
        }
        //end count
        depth = depth+i-1;
        output=output+content.split('</div>')[0]+'</div>';
        content = content.substring(content.indexOf('</div>')+6);
      }
      $("#"+div_id_to_fill).hide();
      document.getElementById(div_id_to_fill).innerHTML = output + div_slide_up();
      $("#"+div_id_to_fill).slideDown("slow");
      pageLoaderInit();
    }else{
      alert(http.status);
    }
  }
}
