var mynav = new ajaxnav();

var myrules = {	
	
	'#current-urlsupp' : function(c)
	{
		if($('current-url') && $('current-rewritesupp') && $('current-rewrite') && $('current-title') &&  $('current-titlesupp'))
		{
			$('current-url').value = c.value;
			$('current-rewrite').value = $('current-rewritesupp').value
			$('current-title').value = $('current-titlesupp').value
			mynav.send = true;
			mynav.setState(c.value, $('current-rewrite').value, $('current-title').value);
		}
	},
	
	'#current-url' : function(c)
	{
		if($('current-rewrite') && !mynav.send && $('current-title'))
			mynav.setState(c.value, $('current-rewrite').value, $('current-title').value);
		mynav.send = false;
	}
};

Behaviour.register(myrules);

var logajaxnav = false;

function ajaxnav()
{
	this.first_call = true;
	this.History = window.History;
	this.State = History.getState();
	this.phx_nav = true;
	this.send = false;
	if(logajaxnav)
		$log = $('log');
	
	var hash = this.History.getHash();
	if(hash != '')
	{
		window.location.replace(hash);
	}
	
	// Log Initial State
	if(logajaxnav)
		this.History.log('initial:', this.State.data, this.State.title, this.State.url);
	
	var oNav = this;
	// Bind to State Change
	this.History.Adapter.bind(window,'statechange',function(){ // Note: We are using statechange instead of popstate
		// Log the State
		
		var State = oNav.History.getState(); // Note: We are using History.getState() instead of event.state
		if(logajaxnav)
			oNav.History.log("OBJET STATE");
		if(!oNav.phx_nav)
		{		
			var CHPOST = "";
			var first = true;
			for(var i in State.data)
			{
				if(first)
					first = false;
				else
					CHPOST += ",";
				CHPOST += i +","+State.data[i];
			}
			if(logajaxnav)
				oNav.History.log(CHPOST);
			phxAjaxCall(true,urltask,'tache=~/mods/ajaxnav/task/ajaxnav&url='+CHPOST,displayPage_callback,STD_error_handler);
		}
		oNav.phx_nav = false;
	});
				
	this.setState = function(url, rewrite, title)
	{
		url = url.replace('index.php?', '');
		var tab = url.split('&');
		var param = {};
		for(var i = 0; i < tab.length; i++)
		{
			var tabV = tab[i].split('=');
			param[tabV[0]] = tabV[1];
		}
		if(this.first_call)
		{
			this.History.replaceState(param, title, rewrite);
			this.first_call = false;
		}
		else
			this.History.pushState(param, title, rewrite);
	}
}

function displayPage_callback(res,param)
{
	var ret = eval("(" + res + ")");
	$('content').update(ret.content);
	PHX_reloadRules('content');
	mynav.phx_nav = false;
}
