/*
 * jQuery history plugin
 *
 * Copyright (c) 2006 Taku Sano (Mikage Sawatari)
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Modified by Lincoln Cooper to add Safari support and only call the callback once during initialization
 * for msie when no initial hash supplied.
 */
(function(loc) {
	
	var uri_re = /^(?:(?:[^:\/?#]+):)?(?:\/\/(?:[^\/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?/;
	
	loc.href.replace(uri_re, 
		function(all, path, query, frag) {
			
			if (frag) {
				url = frag;
				
				pos = url.lastIndexOf("/");
				if (pos >= 0) url = url.substr(pos+1);
				
				if (url.indexOf("index.php") == -1) {
					url = url.replace(".php", "");
					url = url.replace("?", "&");
									
					url = "index.php?sel=" + url;
				}
				location.href = url;
			}//if (frag) {
		}
	);
})(window.location);


jQuery.extend({
	
	historyCurrentHash: undefined,
	historyCallback: undefined,
	
	removeHash: function(hashValue){
		return hashValue.replace(/^#/, '');
	},
	
	cleanUrl: function(url){
		
		pos = url.lastIndexOf("/");
		if (pos >= 0) url = url.substr(pos+1);
		
		return url;
	},
	
	removeIndex: function(url) {
		var lang = "ba";
		var file = "";
		var fileVars = "";

		url = jQuery.cleanUrl(url);

		url = url.replace("index.php?", "");
		url = url.replace("index.php", "");
		
		var vars = url.split("&");
		
		for (var i in vars) {
			curVar = vars[i].split("=");
			
			if (curVar[0] == "lang") {
				lang = curVar[1];
			} else if (curVar[0] == "sel") {
				file = curVar[1];
			} else {
				fileVars += "&" + curVar[0] + "=" + curVar[1];
			}
		}
		
		if (file.length == 0) file = "home";
		
		url = file + ".php?lang=" + lang + fileVars;
		
		return url;
	},
	
	historyInit: function(callback){
		jQuery.historyCallback = callback;
		
		var current_hash = jQuery.removeHash(location.hash);
		
		jQuery.historyCurrentHash = current_hash;
	
		if ((jQuery.browser.msie) && (jQuery.browser.version < 8)) {
						
			// add hidden iframe for IE
			$("body").prepend('<iframe id="jQuery_history" style="display: none;"></iframe>');
			var ihistory = $("#jQuery_history")[0];
			var iframe = ihistory.contentDocument || ihistory.contentWindow.document;

			iframe.open();
			iframe.close();
			iframe.location.hash = "#";
		} else if ($.browser.safari) {
			// etablish back/forward stacks
			jQuery.historyBackStack = [];
			jQuery.historyBackStack.length = history.length;
			jQuery.historyForwardStack = [];
			
			jQuery.isFirst = true;
		}
		jQuery.dontCheck = false;
		setInterval(jQuery.historyCheck, 100);
			
	},
	
	loadHash: function(url) {
		
		if (url) {
			var href = $("a[href*=" + url + "]");
			
			if ( href.length > 0 ) {
				
				if (href.attr("div")) {
					if (href.attr("div") == "parents") {
						href.parents("div").click();
					} else if (href.attr("div") == "children") {
						href.children("div").click();
					}
				}
				if (href.attr("t")) {
					var target = href.attr("t");
				} else {
					var target = "mainContent";
				}
				if (href.attr("url")) {
					url = href.attr("url");
				} else {
					url = jQuery.removeIndex(url);
				}
				
				jQuery.historyCallback(url,target);
				
			} else {
				jQuery.historyCallback(jQuery.removeIndex(url));
			}
		} else {
			location.reload();
		}
		
	},
	
	historyAddHistory: function(hash) {
		// This makes the looping function do something
		jQuery.historyBackStack.push(hash);
		
		jQuery.historyForwardStack.length = 0; // clear forwardStack (true click occured)
		this.isFirst = true;
	},
	
	historyCheck: function(){
		if (!jQuery.dontCheck) {
			if ((jQuery.browser.msie) && (jQuery.browser.version < 8)) {
				// On IE, check for location.hash of iframe
				var ihistory = $("#jQuery_history")[0];
				var iframe = ihistory.contentDocument || ihistory.contentWindow.document;
				var current_hash = unescape(jQuery.removeHash(iframe.location.hash));
				
				if (current_hash != jQuery.historyCurrentHash) {
					location.hash = "#" + current_hash;
					jQuery.historyCurrentHash = current_hash;
					jQuery.loadHash(current_hash);
				}
			} else if ($.browser.safari) {			
				var historyDelta = history.length - jQuery.historyBackStack.length;
				
				if (historyDelta) { // back or forward button has been pushed
					jQuery.isFirst = false;
					if (historyDelta < 0) { // back button has been pushed
						// move items to forward stack
						for (var i = 0; i < Math.abs(historyDelta); i++) jQuery.historyForwardStack.unshift(jQuery.historyBackStack.pop());
					} else { // forward button has been pushed
						// move items to back stack
						for (var i = 0; i < historyDelta; i++) jQuery.historyBackStack.push(jQuery.historyForwardStack.shift());
					}
					var cachedHash = jQuery.historyBackStack[jQuery.historyBackStack.length - 1];
					if (cachedHash != undefined) {
						jQuery.historyCurrentHash = jQuery.removeHash(location.hash);
						jQuery.loadHash(cachedHash);
					}
				} else if (jQuery.historyBackStack[jQuery.historyBackStack.length - 1] == undefined && !jQuery.isFirst) {
					// back button has been pushed to beginning and URL already pointed to hash (e.g. a bookmark)
					// document.URL doesn't change in Safari
					if (document.URL.indexOf('#') >= 0) {
						jQuery.loadHash(document.URL.split('#')[1]);
					} else {
						jQuery.loadHash("");
					}
					jQuery.isFirst = true;
				}
			} else {
				// otherwise, check for location.hash
				var current_hash = jQuery.removeHash(location.hash);
				if (current_hash != jQuery.historyCurrentHash) {
					jQuery.historyCurrentHash = current_hash;
					jQuery.loadHash(current_hash);
				}
			}
		}
	},
	historyLoad: function(hash){
		
		hash = jQuery.cleanUrl(hash);
		
		jQuery.dontCheck = true;
		var fn = function() {jQuery.dontCheck = false;};
		window.setTimeout(fn, 200);
		
		if (!jQuery.browser.safari) {
			location.hash = "#" + hash;
		}
		jQuery.historyCurrentHash = hash;
		
		if ((jQuery.browser.msie) && (jQuery.browser.version < 8)) {
			
			var ihistory = $("#jQuery_history")[0];
			var iframe = ihistory.contentDocument || ihistory.contentWindow.document;

			iframe.open();
			iframe.close();
			iframe.location.hash = "#" + escape(hash);
			jQuery.loadHash(hash);
			
		} else if (jQuery.browser.safari) {
			// Manually keep track of the history values for Safari
			this.historyAddHistory(hash);
						
			jQuery.loadHash(hash);
			// N.B. "location.hash=" must be the last line of code for Safari as execution stops afterwards.
			//      By explicitly using the "location.hash" command (instead of using a variable set to "location.hash") the
			//      URL in the browser and the "history" object are both updated correctly.
			location.hash = hash;
		} else {
			jQuery.loadHash(hash);
		}
	}
});
