// If History doesn't need to handle the initial state it returns false so the code of the page can execute.
// The first argument is the base path of your application. Usually it defaults to / but in the case of this
// demo it likely only runs inside of a subtree. Please note that the handleState plugin is purely optional.
if (!History.handleInitialState(location.pathname.substr(0, location.pathname.lastIndexOf('/') + 1))) (function(){

//Main handler that loads content from any URL
var loadPage = function(url){
	//console.log('History.myURLHandler');
	new Request.HTML({
		url: url,
		/*data: {
			xhr: 'yes'
		},*/
		evalScripts: false,
		onSuccess: function(tree, elements, html, javascript){
			document.id('containerPages').set('html', html);
			if (javascript) Browser.exec(javascript);
			Element.applyFilters();
			//(function(){
				//alert('done');
				update(); //Add the listeners again
			//}).delay(3000);
			mySite.fireEvent('changePage', url);
		}
	}).get();
};

History.addEvent('change', loadPage);

var listener = function(event){
	event.preventDefault();
	//alert(this.get('href'));
	History.push(this.get('href'));
};

//Update all links on the page
var update = function(){
	//Even if we execute this method more than once, the listeners only get added once per element
	document.getElements('a:not([href^=http://]):not([data-noxhr])').addEvent('click', listener);
};

//Call update initially to add the listener to all elements present on the initial page load
window.addEvent('domready', update);

//Handle the initial load of the page if the browser does not support pushState, check if the hash is set
if (!History.hasPushState()) window.addEvent('domready', function(){
	//Check if there is a hash
	var hash = document.location.hash.substr(1);
	if (!hash) return;
	
	//If the hash equals the current page, don't do anything
	var path = document.location.pathname.split('/');
	path = path[path.length - 1];
	if (hash == path) return;
	
	//Load the page specified in the hash
	loadPage(hash);
});

})();
