$(document).ready(function () {

	$('#master').prepend('<div id="loading"></div>');
	// Set all non-ajax links to open in new window
	
	$( "a[rel=ajax]" ).each(function(){ 
		var href = $(this).attr('href'); 
		if (href != undefined) { 
			$(this).attr(  'href', "#" + href.substring(0, href.indexOf('.php') )  ); 
			}
		$(this).bind({
		  click: function(){
			clicka($(this));
		  }
		});
	}); 
	
	
	$('a:not([rel=ajax])').attr('target', '_blank');
	
	//Check if url hash value exists (for bookmark)
	$.history.init(pageload);	
	    
	//highlight the selected link
	$('a[href=' + document.location.hash.substring(1) + '.php]').addClass('selected');

	//for back button
 	$.history.load(hash);
	
	//Seearch for link with REL set to ajax
	//$('a[rel=ajax]').click();	
	
	function clicka(e) {
		
		//grab the full url
		var hash = e.href;
		
		//remove the # value
		hash = hash.replace(/^.*#/, '');	
	 	
	 	//clear the selected class and add the class class to the selected link
	 	$('a[rel=ajax]').removeClass('selected');
	 	e.addClass('selected');
	 	
	 	//hide the content and show the progress bar
	 	// $('#content').slideUp();
	 	$('#loading').fadeIn('slow');
	 	
	 	//run the ajax
		getPage();
	
		//cancel the anchor tag behaviour
		return false;
	}
	
});

function pageload(hash) {
	//if hash value exists, run the ajax
	getPage();    //if (hash) 
}
	
function getPage() {
	
	//generate the parameter for the php script
	var loadpage = document.location.hash;
	
	// Default to main page if none specified
	if (!loadpage) loadpage = "#main";
	
	$('#loading').fadeIn('slow');	

	loadpage = loadpage.replace(/^.*#/, '');
	var data = 'page=' + encodeURIComponent(loadpage);
	$.ajax({
		url: "loader.php",	
		type: "GET",		
		data: data,		
		cache: false,
		success: function (html) {	
		
			_gaq.push(['_trackPageview', loadpage+'.inc.php']);
		
			//hide the progress bar //add the content retrieved from ajax and put it in the #content div
			$('#loading').fadeOut('slow');	
		 	$('#content').fadeOut('slow', function() {$('#content').html(html);});
			//display the body with fadeIn transition
			$('#content').fadeIn('slow');

			if (loadpage != "main") {
			$("#background").animate({ marginTop: "-272px" }, 1500 );
			} else {
			$("#background").animate({ marginTop: "12px" }, 1500 );
			}
			
			$('body,html').animate({ scrollTop: 0 }, 800);
		}		
	});
}
