/*
*
* Copyright (c) 2008 Yusuf Akyol
* 
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* * 
*
*
* conv2ajax
* http://code.google.com/p/conv2ajax/
* Yusuf Akyol
* Version 6.0 (2009-12-23)
*
* 
*/

var currentdivs = [];
var currenturls = [];
var previousdivs = [];
var previousurls = [];
var initials = [];

String.prototype.trim = function() {
   return this.replace(/^\s+|\s+$/g,"");
};

function ToHex(str){
    var r="";
    var e=str.length;
    var c=0;
    var h;
    while(c<e){
        h=str.charCodeAt(c++).toString(16);
        while(h.length<3) h="0"+h;
        r+=h;
    }
    return r;
}
function FromHex(str){
    var r="";
    var e=str.length;
    var s;
    while(e>=0){
        s=e-3;
        r=String.fromCharCode("0x"+str.substring(s,e))+r;
        e=s;
    }
    return r;
}

function pageTop() {
   window.scrollTo(0,0);
}

function _submit(url,div) {
   var divobj = "#"+div;
   $(divobj).html("<img src='images/loading.gif' border='0' />");
   $.get(url, function(resp) {
	      $(divobj).html(resp);
	      if ($(divobj).attr("title") > " ")
                 document.title = $(divobj).attr("title");
              _initdiv(div);
	   }
   );
}

function _clearhref(href) {
   myhref = href;
   while (myhref.indexOf('/') > -1) {
      inx = myhref.indexOf('/');
      myhref = myhref.substr(inx+1,myhref.length-inx-1);
   };
   while (myhref.indexOf('\\') > -1) {
      inx = myhref.indexOf('\\');
      myhref = myhref.substr(inx+1,myhref.length-inx-1);
   };
   return myhref;
}

function _initdivin(div) {
   var myhref = "";
   var inx = 0;

   var divobj = "#" + div;
    $(divobj + " a")
    .filter( function(){ 
      return $(this).parents('div:first').is( '#'+div );
     })
     .each(function() {
      if ( this.href.indexOf(location.hostname) != -1  && this.href.indexOf("javascript:") == -1 && !this.onclick )       { 
	 if (this.href == "#" || this.href.substr(0,3) == "#no") {
	    this.href = "javascript:void(0);";
         }
	 var rel = div;
	 if ($(this).attr("rel")) rel = $(this).attr("rel");
         if (rel.toLowerCase() != "omit") {
            if ($(this).click)  
               $(this).unbind("click");
            $(this).click ( function(e) {
               var url = _clearhref(this.href);
               if ($(this).attr("title"))
                  document.title = $(this).attr("title");
               _newhistory(rel,url);
               e.preventDefault();
            });
         }
      }
   });

   $(divobj +" form")
    .filter( function(){ 
      return $(this).parents('div:first').is( '#'+div );
     })
     .each(function() {
         if (!this.id) 
            this.id = this.name;
         var formid = "#"+this.id;
         $(formid).ajaxForm({target:divobj, success: function() { _initdiv(div); }});
   });
}

function _initdiv(div) {
   var rel = "";
   _initdivin(div);
    $("#"+div).children("div").each(function () {
      rel = "";
      if ($(this).attr("rel")) {
         rel = $(this).attr("rel").toLowerCase();
      }
      if (rel != "omit") {
         if ($(this).attr("id") > "") {
            if ($("#"+this.id).attr("src")) {
               _setdiv(this.id);
            } else  {
               _initdiv(this.id);
            }
         }
      }
   });
}

function _setdiv(div) {
   var divobj = "#"+div;
   var url =  $(divobj).attr("src");
   $.ajax({
     type: "GET",
     url: url,
     dataType: "text",
     success: function(resp){
        $(divobj).html(resp);
        _initdiv(div);
     } 
   });
}

function _setdivin(div) {
   var divobj = "#"+div;
   var url =  $(divobj).attr("src");
   $.ajax({
     type: "GET",
     url: url,
     dataType: "text",
     success: function(resp){
        $(divobj).html(resp);
        _initdivin(div);
     } 
   });
}

function _loaddiv(div,src,div2,ptitle) {
   var divobj = "#"+div;
   $(divobj).removeAttr("src"); 
   var args = arguments.length;
   if (args == 4)
      $(divobj).attr("title",ptitle);
   if (args == 3 && div2 > " ") {
      $(divobj).attr("rel",div2);     
   } else {
      $(divobj).removeAttr("rel");   
   }
   _newhistory(div,src);
}

function loaddiv(div,src,div2,ptitle) {
   var args = arguments.length;
   if (args == 4) _loaddiv(div,src,div2,ptitle)
   else if (args == 3) _loaddiv(div,src,div2);
   else _loaddiv(div,src);
}

function _initconv2ajax() {
   var rel = "";
   $("div").each(function () {
      rel = "";
      if ($(this).attr("rel")) {
         rel = $(this).attr("rel").toLowerCase();
      }
      if (rel != "omit") {
         if ($(this).attr("id") > "") {
            if ($("#"+this.id).attr("src")) {
               _setdivin(this.id);
            } else  {
               _initdivin(this.id);
            }
         }
      }
   });
}

function _checkurl(current) {
   current = current.replace("[","?");
   var i=0;
   var j=0;
   var k=0;
   var historyurl = [];
   
   currentdivs = [];
   currenturls = [];
   
   if (current > "") {
      historyurl = current.split("/");
      for (i=0; i < historyurl.length; i=i+2) {
         currentdivs[k] = historyurl[i];
         currenturls[k] = unescape(historyurl[i+1]);
         k++;
      } 
   }

   for (i=0; i<currentdivs.length; i++) {
      for(j=0; j<previousdivs.length; j++) {
         if (currentdivs[i] == previousdivs[j] && currenturls[i] != previousurls[i]) {
            _submit(currenturls[i],currentdivs[i]);
            break;
         }
      }
   }  
   
   if (currentdivs.length > previousdivs.length) {
      for(i=previousdivs.length; i < currentdivs.length; i++) {
         initials[currentdivs[i]] = $("#"+currentdivs[i]).html();
         _submit(currenturls[i],currentdivs[i]);
      }         
   }
   
   if (previousdivs.length > currentdivs.length) {
      for (i=0; i<previousdivs.length; i++) {
         for (j=0; j<currentdivs.length; j++) {
            if (previousdivs[i] == currentdivs[j]) break;
         }
         if (previousdivs[i] != currentdivs[j]) {
            $("#"+previousdivs[i]).html(initials[previousdivs[i]]);
         }
      }
   }
   
   previousdivs = [];
   previousurls = []; 
   for (i=0; i<currentdivs.length; i++) {
      previousdivs[i] = currentdivs[i];
      previousurls[i] = currenturls[i];
   }
}

function _createurl() {
   var i=0;
   var historyurl = "";
   for (i in currentdivs) {
      historyurl += "/" + currentdivs[i] + "/" + currenturls[i];
   }
   historyurl = historyurl.substr(1);
   historyurl = historyurl.replace("?","[");
   $.history.load(historyurl); 
}

function _newhistory(div, url) {
   var i=0;
   var div2 = div;
   if ($("#"+div).attr("rel") > " ") 
      div2 = $("#"+div).attr("rel");
   
   for ( i=0; i < currentdivs.length; i++) {
      if (currentdivs[i] == div2) break;
   } 
   if (i==currentdivs.length) {
      currentdivs[i] = div2; 
      currenturls[i] = url;
   } else {
      if (currenturls[i] != url) {
         currenturls[i] = url;
      } else return;
   }
   _createurl();
}

function _pageload(hash) {
   if (previousdivs.length == 0) _initconv2ajax();
   _checkurl(hash);
}

$(function() {
	$.history.init(_pageload);
});