/**
 * Class providing ajax/flash navigation history
 * 
 * @requires MochiKit
 */
History = function(func,home) {
	// create initialize function as partial of init
	// for which arguments are preset
	// 
	// this function is invoked in page.js after deeplink
	// has been examined
	this.initialize = bind(this.init, this, func, home);
}
/** 
 * Initialize history watcher. Should be invoked
 * after the url's current hash has been examined
 * as this definitely sets a hash
 *
 * @param {function} func - function to be called 
 * when history watcher discovers change
 * @param {string} home - initial hash/path
 */
History.prototype.init = function(func, home) {
	this.change = func;
	this.curent = null;
	this.add(home);
	this.title = document.title;
	setInterval(bind(this.historyChange,this), 100);
};
/** 
 * Add page to history, change url hash

 * @param {string} hash  - page hash  
 */
History.prototype.add = function(hash) {
	this.curent = "#" + hash;
	//browser back support FX - url hash, IE - iframe
	if (this.isIE()) {
		// iframe script calls changeQuery function 
		// automatically (via top.hist)
		$('hist_frame').src = "resources/frame.html?" + hash; 
	} else {
		changeQuery(hash);
	}
};
/** @private
 * 
 * Check for hash changes and navigate over history
 */
History.prototype.historyChange = function() {
	if (this.curent != window.location.hash) {
		this.change(window.location.hash);
	}
	//IE title fix / replace #hashed title with last one 
	if (document.title.indexOf('#') != -1 ) {
		document.title = this.title;
	} else {
		this.title = document.title; 
	}
};
/**
 * Detrmine if browser is Internet Explorer
 * 
 * @return: true - if browser is Internet Explorer, false - otherwise
 * @type boolean
 */
History.prototype.isIE = function() {
	return navigator.userAgent.toLowerCase().indexOf("msie") != -1;
};
/** @private
 * Change URL hash
 * 
 * @param {string} query - hash to set
 */
function changeQuery(query) {
	//exit if query empty or same 
	if(!query) return;
	if (window.location.hash == ("#" + query)) return;
	window.location.hash = ("#" + query);
}

addLoadEvent(function () {
	// set initial page to either
	// - hash if present
	// - search string if preset (js=t removed if present)
	// - or default to action=frontpage
	var home = (window.location.hash == "" && (window.location.search == "" || window.location.search == "?js=t")) 
					? "action=frontpage"
					: (window.location.hash == ""
						?(window.location.search.indexOf("?js=t") == -1
							? window.location.search.substring(1)
							: window.location.search.substring(5)) 
						: window.location.hash.substring(1)
					);
	hist = new History(
		function(hash) {
			thepage.processLoadPage(parseQueryString(hash.substring(1)));
		},
		home
	);
});
