// remote search scripts
var url;
var query = {};
var itemsloaded;
var itemstotal;

function ShowStatus(status) {
  $("#waitID").text(status);
  $("#infowindow").show();
}

function HideStatus(){
  $("#waitID").text('');
  $("#infowindow").hide();
}

function ShowLiners(){
  $("#linersID").show();
}

function HideLiners(){
  $("#linersID").hide();
}

function ResetForm(){
  query = {};
  LoadInfo();
}

function OnMouseMove1(id){
}

function MouseOver(id,href,src){
  var tooltip = $("#shiptooltip");
  var img = $("#shiptooltip img")[0];
  if(img.id != "img"+id){
      img.src = src;
      img.id = "img"+id;
      var element = $("#"+id);
      tooltip.css({ "left": element.offset().left - tooltip.width() + "px", "top": element.offset().top + "px" } );
      $("#shiptooltip a")[0].href=href;
  }  
  tooltip.show();
}

function MouseOut(){
  $("#shiptooltip").hide();
}

function FadeOut(){
  HideLiners(); 
  ShowStatus("Пожалуйста, подождите");
  $("#cruises").html("");
  $(".search_table").show();
  $(".search_background").show();
}

function LoadData(url, onsuccessfulget){
  $.get(url,query,
    function(data){
      onsuccessfulget(data);
      $("a[href*='/pages/']").each(function() {
        //this.href = this.href.replace(/:\/\/[^\/]+\//,"://www.viamaris.ru/");
        el = document.createElement("span");
        el.innerHTML = this.innerHTML;
        this.parentNode.insertBefore(el,this);
        this.parentNode.removeChild(this);         
      });
      $("img[src*='/UserFiles/']").each(function() {
        this.src = this.src.replace(/:\/\/[^\/]+\//,"://www.viamaris.ru/");
      });
      $("a[rel='history'][href^='#-']").each(function(){
        var hash = this.href.replace(/^.*#/, '');
        var q = decodequery(hash);
        if(q.action == "show")
          this.href = '#'+ encodequery(hash);
      });
      $("a[rel='history']").click(LinkClicked);
    }
  ,"jsonp");
}

function LoadInfo() {
  FadeOut();
  LoadData(url,
    function(data){
      $(".search_table").fadeOut("fast");
      $.each(data, function(){
        if(this.id=="selected") {
          query = eval("({"+this.text+"})");
          }
        else
          $("#"+this.id).html(this.text);
      });
      $(".search_table").fadeIn("fast");
      HideStatus();
      $("#show_button,#clear_button").click(ButtonClicked);
    });
}

function LoadIDs(){
  //load cruises table
  ShowStatus("Загружается Список Круизов");
  query.action = "getids";
  LoadData(url, function(data){
    $(".search_table").fadeOut("fast");
    $(".search_table").hide();
    $(".search_background").hide();
    $("#cruises").html(data.template);
    MouseOut();
    line = data.line;
    ids = data.ids;

    itemsloaded = 0;
    itemstotal = ids.totalids;
    /*$.each(ids.blocks, function(){
      $.each(this,function(){
        $("#cruiselines").append("<tr id=\"row"+ this +"\" style=\"boder-style:solid\"><td>&nbsp;</td></tr>");
      });
    });*/
      
    LoadCruises(ids.blocks,line,0);
    HideStatus();
  });
}

function LoadCruises(blocks, line, i) {
  query.action = "getcruises";
  query.ids = blocks[i].toString();
  LoadData(url, function(data){
    num = 0;
    $.each(data, function() {
        if(num % 2) 
          style = "cru1";
        else
          style = "cru2"; 
      htmlline = MakeLine(line,this);
      //$("#row"+this.id).replaceWith("<tr class=\""+style+ "\" id=\"row"+ this.id +"\">"+htmlline+"</tr>");
      $("#cruiselines").append("<tr class=\""+style+ "\" id=\"row"+ this.id +"\">"+htmlline+"</tr>");
      num++;
      itemsloaded++;
      ShowStatus("Загружено "+ itemsloaded + " из " + itemstotal + " круизов");
    });
    if(itemsloaded >= itemstotal)
      HideStatus();
    if ((i < blocks.length-1))
      setTimeout("LoadCruises(ids.blocks, line, "+(i+1)+")",20);
  }); 
}

function MakeLine(template,data){
  var line = new String(template); 
  for(var name in data) {
  line = line.replace(RegExp("%"+ name + "%","gi"),data[name]);
  }
  return line;  
}

function ShowCruise(id){
  query.action = "showcruise";
  query.id = id;
  LoadData(url, function(data){
    $("#cruises").html(data);
  });
}

function ShowLiner(id){
  query.action = "showliner";
  query.id = id;
  LoadData(url+"?"+id, function(data){
    $("#cruises").html(data);
    HideStatus();
  });
} 

function ShowCompany(id){
  query.action = "showcompany";
  query.id = id;
  LoadData(url+"?"+id, function(data){
    $("#cruises").html(data);
    HideStatus();
  });
}

function ShowRegion(id){
  query.action = "showregion";
  query.id = id;
  LoadData(url+"?"+id, function(data){
    $("#cruises").html(data);
    HideStatus();
  });
}

function encodequery(hash){
  var q = decodequery(hash);
  var s = "";
  $.each(q , function(prop,val){
    s = s + '-' + prop +'/' + val;  
  });
  return encodeURIComponent(s);
}

function decodequery(hash){
  var q = query;
  hash = decodeURIComponent(hash);
  if(hash.charAt(0) == '-'){
    var pairs = hash.split("-");
    clicked_prop = "";
    $.each(pairs,function(){
      if(this != ""){
        var nv = this.toString().split("/");
        if(nv[1] != "" && nv[0].search(/_clicked/))
          clicked_prop = nv[0];
        q[nv[0]] = nv[1];
      }
    });
    if(clicked_prop != "")
      $.each(q,function(prop,val){
        if( prop.search(/_clicked/) >= 0 && prop != clicked_prop)
          delete q[prop]; 
      });
    return q;
  }
}

function pageload(hash) {
    // alert("pageload: " + hash);
    // hash doesn't contain the first # character.
    if(hash) {
      // restore ajax loaded state
      if($.browser.msie) {
        // jquery's $.load() function does't work when hash include special characters
        hash = encodeURIComponent(hash);
      }
      query = decodequery(hash);
      if(query.action == 'getids'){
        LoadIDs();
      }else if(query.action == 'showcruise'){
        ShowCruise(query.id);
      }else if(query.action == 'showliner'){
        ShowLiner(query.id);
      }else if(query.action == 'showcompany'){
        ShowCompany(query.id);
      }else if(query.action == 'showregion'){
        ShowRegion(query.id);
      }else if(query.action == 'showliners'){
        ShowLiners(); 
      }else if(query.action == 'hideliners'){
        HideLiners(); 
      }else {
        LoadInfo();
      }
    } else {
      // start page
      LoadInfo();
    }
  }

function ButtonClicked(){
      // 
      var hash = this.name.replace(/^.*#/, '');
      // moves to a new page. 
      // pageload is called at once. 
      // hash don't contain "#", "?"
      $.historyLoad(encodequery(hash));
      return false;
    }

function LinkClicked(){
      // 
      var hash = this.href.replace(/^.*#/, '');
      // moves to a new page. 
      // pageload is called at once. 
      // hash don't contain "#", "?"
      $.historyLoad(hash);
      return false;
    }
$(document).ready( function(){
  // Initialize history plugin.
  // The callback is called at once by present location.hash. 
  $.historyInit(pageload);
  
  site= "www.viamaris.ru";
  //site= "192.168.172.2";
  url = "http://" +site + "/queryjson.php";
  query = {};

  //$("#show_button").click(LoadIDs); 
  //$("#clear_button").click(ResetForm);
  
    
    // set onlick event for buttons
  pageload(location.hash.replace(/^.*#/, ''));
} );

