/*
*
* Copyright (c) 2008 Yusuf Akyol
* 
* Conv2Ajax JavaScript Library v6.2 (2010-11-3)
* http://conv2ajax.com/
*
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
* http://conv2ajax.com/ItemDetail.php?id=6
* 
*/

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

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

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

function parse(page) {
	page = page.replace(/\<\!\[CDATA\[\/\/\>\<\!\-\-/gi,'');
	page = page.replace(/\/\/\-\-\>\<\!\]\]\>/gi,'');

	var pageHead = page.match(/<\s*head.*>[\s\S]*<\s*\/head\s*>/ig); 
	var pageTitle = page.match(/<\s*title.*>[\s\S]*<\s*\/title\s*>/ig);
	var pageBody = page.match(/<\s*body.*>[\s\S]*<\s*\/body\s*>/ig);

	var commentPattern = /\<\!\-\-([\s\S]*?)\-\-\>/ig;
	
	if (pageHead) {
		pageHead = pageHead.join("");
		pageHead = pageHead.replace(/<\s*head/gi,"<div");
		pageHead = pageHead.replace(/<\s*\/head/gi,"</div");	
		pageHead = pageHead.replace(commentPattern,"");
	}
	
	if (pageTitle) {
		pageTitle = pageTitle.join("");
		pageTitle = pageTitle.replace(/<\s*title/gi,"<div");
		pageTitle = pageTitle.replace(/<\s*\/title/gi,"</div");	
	}
	
	if (pageBody) {
		pageBody = pageBody.join("");
		pageBody = pageBody.replace(/<\s*body/gi,"<div");
		pageBody = pageBody.replace(/<\s*\/body/gi,"</div");	
		pageBody = pageBody.replace(commentPattern,"");
	}

	var $pageHead  = $(pageHead); 
	var $pageTitle = $(pageTitle);
	var $pageBody  = $(pageBody);

	if (pageTitle)
		 document.title = $pageTitle.html();

	if (pageHead) {
		scripts = pageHead.match(/<script(.|\s)*?\/script>/g);
		
		if (scripts) {
			for (i=0; i<scripts.length; i++) {
				$script = $(scripts[i]);
				if ($script.attr("rel")) {
					var attrrel = $script.attr("rel");
					if (attrrel.indexOf("omit") == -1) {
						$pageBody.html($pageBody.html() + scripts[i] + "\n");
					}
				} else {
					$pageBody.html($pageBody.html() + scripts[i] + "\n");				
				}
			}
		}		
		
		$pageHead.find("style,link[rel*='style']").each(function(){
			if ($(this).attr("rel")) {
				var attrrel = $(this).attr("rel");
				if (attrrel.indexOf("omit") == -1){
					$pageBody.append(this);
				}
			} else {
				$pageBody.append(this);		
			}
		});	
	}

	if (pageBody)
		return $pageBody.html();
	else
		return page;
}

function _submit(url,div) {
	var divobj = "#"+div;
	$(divobj).html("<img src='images/loading.gif' border='0' />");
	$.get(url, function(resp) {
		$(divobj).html(parse(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;
				var target = "";
				if ($(this).attr("rel")) rel = $(this).attr("rel");
				if ($(this).attr("target")) target = $(this).attr("target");
				if (rel.toLowerCase() != "omit" && target.toLowerCase() != "_blank") {
					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(parse(resp));
			_initdiv(div);
		} 
	});
}

function _setdivin(div) {
	var divobj = "#"+div;
	var url =  $(divobj).attr("src");
	$.ajax({
		type: "GET",
		async: false,
		url: url,
		dataType: "text",
		success: function(resp){
			$(divobj).html(parse(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) {
	_checkurl(hash);
}

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