/*
*
* 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 3.2 (2009-03-21)
*
* 
*/

var currentdivs = [];
var currenturls = [];
var previousdivs = [];
var previousurls = [];
var initdivs = [];
var initials = [];

String.prototype.trim = function() {
   return this.replace(/^\s+|\s+$/g,"");
};

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 _submitForm(obj,div) {
   if (!$(obj.form).attr("id"))
      $(obj.form).attr("id",$(obj.form).attr("name"));
   var myform = "#"+$(obj.form).attr("id");
   var url = $(obj.form).attr("action");
   var formdata = $(myform).serialize() + "&" + $(obj).attr("id") + "=" +  $(obj).val();
   $("#"+div).html("<img src='images/loading.gif' border='0' />");
   $.post(url, 
	formdata, 
	function(resp) {
	   $("#"+div).html(resp);
           _initdiv(div);
	}
   );
}

function _initonclick(objid,div) {
   _submitForm(objid,div);
}

function _setclick(obj,div) {
   var ob = "#"+$(obj).attr("name");
   if (!$(obj).attr("id"))
      $(obj).attr("id",$(obj).attr("name"));
   if ($(ob).click)  
       $(ob).unbind("click");
   if (!$(ob).onclick) { 
      $(ob).click ( function(e) {
         _initonclick(this,div);
         e.preventDefault();
      });
   } 
}

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 ($(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 + " :image").each(function() {
         _setclick(this,div);
      });

      $(formid + " :submit").each(function() {
         _setclick(this,div);
      });

      $(formid + " :button").each(function() {
         _setclick(this,div);
      }); 
   });
}

function _initdiv(div) {
   _initdivin(div);
    $("#"+div).children("div").each(function () {
      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 _changesrc(div,src,div2,ptitle) {
   var divobj = "#"+div;
   $(divobj).attr("src",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 changesrc(div,src,div2,ptitle) {
   var args = arguments.length;
   if (args == 4) _changesrc(div,src,div2,ptitle);
   else if (args == 3) _changesrc(div,src,div2);
   else _changesrc(div,src);
}

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() {
   $("div").each(function () {
      if ($(this).attr("id") > "") {
         if ($("#"+this.id).attr("src")) {
            _setdivin(this.id);
         } else  {
            _initdivin(this.id);
         }
      }
   });
}

function _checkurl(current, previous) {
if (current == previous && current > " ") return;
   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++;
      } 
   }

   if (previous > "") {
      previous = previous.replace("[","?");
      previousdivs = [];
      previousurls = [];
      k=0;
      historyurl = [];
      historyurl = previous.split("/");
      for (j=0; j < historyurl.length; j=j+2) {
         previousdivs[k] = historyurl[j];
         previousurls[k] = unescape(historyurl[j+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.add(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() {

	$(window).historyadd(function(e, currentHash, previousHash) {
	   _checkurl(currentHash, previousHash);		
	});

	$(window).history(function(e, currentHash, previousHash) {
           _checkurl(currentHash, previousHash);	
	});

	var initialHash = $.history.getCurrent();
	if (initialHash == '') {
   	   _initconv2ajax();
	} else {
   	   _initconv2ajax();
	   _checkurl(initialHash, "");
        }
});