function EdaHistory(){}

EdaHistory.init = function() {
	var me = EdaHistory;
	window.EdaHistory = me;
	Utils.browserVersion.init();
	var fB = Utils.browser;
	var fV = Utils.version;
	if (fB == "Explorer" && fV >= 5.5) {
		me.withFrame = true;
	} else if (fB == "Mozilla" || fB == "Firefox" || (fB == "Opera" && fV >= 9.5) || (fB == "Safari" && fV >= 500)) {
		me.withTicker = true;
	} else {
		me.unsupported = true;
		return false;
	}
	return true;
}

EdaHistory.start = function(pCallback) {
	var me = EdaHistory;
	if (me.unsupported) return;
	me.started = true;
	me.baseurl = Utils.splitPath(top.document.location.toString()) [0];
	me.history = {};
	
	if (me.withFrame) {
		me.frame = document.createElement("iframe");
		me.frame.style.visibility = "hidden";
		me.frame.style.position = "absolute";
		document.body.appendChild(me.frame);
		this.intervalId = setInterval(me.checkFrame, 200);
	} else if (me.withTicker) {
		this.intervalId = setInterval(me.checkHistory, 200);
	} else return false; // means unsupported
	me.callback = pCallback;
}

EdaHistory.set = function(pUrl, pTitle) {
	var me = EdaHistory;
	if (me.unsupported) return;
	var fUrl = Utils.relativePath(pUrl, me.baseurl);
	me.setHash(fUrl);
	me.setTitle(pTitle);
	me.history[fUrl] = pTitle;
	if (me.withFrame) {
		var fDoc = me.frame.contentWindow.document;
		fDoc.open();
		fDoc.write('<html><title>'+pTitle+'</title><body><div id="url">' + fUrl + '</div></body></html>');
		fDoc.close();
	}
}

EdaHistory.checkFrame = function() {
	var me = EdaHistory;
	var fFrame = me.frame;
	if (!fFrame.contentWindow || !fFrame.contentWindow.document) {
		return;
	}
	var fUrl = fFrame.contentWindow.document.getElementById("url").innerText;
	if (fUrl == me.url) return;
	me.url = fUrl;
	var fTitle = me.history[fUrl];
	if (fTitle == null) return;
	me.setHash(fUrl);
	me.setTitle(fTitle);
	me.callback(fUrl);
}

EdaHistory.setHash = function(pUrl) {
	window.top.location.hash = encodeURIComponent(pUrl);
	this.url = pUrl;
}

EdaHistory.getHash = function() {
	var fHref = window.top.location.href.toString().split("#");
	if (fHref.length > 1) return decodeURIComponent(fHref[1]);
	else return null;
}

EdaHistory.setTitle = function(pTitle) {
	window.top.document.title = pTitle;
}

EdaHistory.checkHistory = function() {
	var me = EdaHistory;
	var fUrl = me.getHash();
	if (fUrl == me.url) return;
	me.url = fUrl;
	var fTitle = me.history[fUrl];
	if (fTitle == null) return;
	me.setTitle(fTitle);
	me.callback(fUrl);
}

if (EdaHistory.init()) {
	var fNewloc = EdaHistory.getHash();
	if (fNewloc != null) {
		document.location = fNewloc;
	}
}
