var savedlogs = '';
function log()
{
	var a = new Array();
	for(var i=1; i<arguments.length; i++) a[a.length]=arguments[i];
	savedlogs += arguments[0]+'('+a.join(',')+')<br>\n';
	
	flushlog();
};
function flushlog()
{
	var div = document.getElementById('debugdiv');
	if (div)
	{
		div.innerHTML += savedlogs;
		savedlogs = '';
	}
	else setTimeout('flushlog()', 1000);
}

function AjaxHistory()
{
	this.state = '';
	this.isIE = (navigator.appName == 'Microsoft Internet Explorer');
}

AjaxHistory.prototype.init = function(defaultstate, callback)
{
//	log('init', this.serialize(defaultstate), 'callback');
	this.defaultstate = this.serialize(defaultstate);
	this.callback = callback;

	var style = 'position:absolute; left:-10000px; width:0px; height:0px;';
	if(window.opera)
	{
		document.write("<img src=\"javascript:location.href='javascript:History.operafix();';\" style='"+style+"'>");
		if (history.navigationMode) history.navigationMode="fast";
	}
	if(this.isIE)
	{
		document.write("<IFRAME STYLE='"+style+"'>-</IFRAME>");
		this.syncState(window.location.hash.substring(1),false,true);
	}
	
	setTimeout("setInterval('History.monitor()', 50);", 1000);
}

AjaxHistory.prototype.add = function(paramArray)
{
//	log('add', this.serialize(paramArray))
	this.syncState(this.serialize(paramArray), false, false);
}

AjaxHistory.prototype.syncState = function(state, restoring_state, loading)
{
//	log('syncState', state, restoring_state, loading);
	if(this.isIE)
	{
		var doc = document.frames[0].document;
		if (!restoring_state || (doc.body.innerHTML != state))
		{
			doc.open();
			doc.write("<BODY>"+state+"</BODY>");
			doc.close();
		}
		window.location.replace('#'+state);
	}
	else if (!restoring_state)
	{
		window.location.hash = '#'+state;
	}
	this.state = state;

	if (restoring_state || (loading && (state != this.defaultstate))) 
	{
		if (state == '') state = this.defaultstate;
		this.callback(this.unserialize(state));
	}
}

AjaxHistory.prototype.serialize = function(ary)
{
	var tmp = Array();
	for (var key in ary)
	{
		tmp[tmp.length] = encodeURIComponent(key) + '=' + encodeURIComponent(ary[key]);
	}
	return tmp.join('+');
}

AjaxHistory.prototype.unserialize = function(str)
{
	var ary = Array();
	var tmp = str.split('+');
	for (var i in tmp)
	{
		var param = tmp[i].split('=');
		ary[decodeURIComponent(param[0])] = decodeURIComponent(param[1]);
	}
	return ary;
}

AjaxHistory.prototype.monitor = function()
{
	var state = window.location.hash.substring(1);
	
	if ((this.state == state) && this.isIE)
		var state = document.frames[0].document.body.innerHTML;

	if (this.state != state)
	{
		this.syncState(state, true, false);
	}
}

AjaxHistory.prototype.operafix = function(){}

var History = new AjaxHistory();
