(function($, undefined) {
	var URL;
	function getPage() {
		var location = window.location.toString();
		var hash = window.location.hash;
		var url = location.replace(hash, '');
		var page = url.split('/').pop();
		var url_parts = url.split('/');
		url_parts.pop();
		URL = url_parts.join('/');
		
		if (!window.location.hash && page == "")
			page = "home.php";
		if (page.indexOf('.php') > -1) {
			// redirect to hash version of page
			window.location = URL+"/#/"+page.split('.')[0];
		}
		
		return getPageFromHash();
	}
	var CURRENT_PAGE = getPage();
	
	function changePage(page) {
		
		var href = URL+"/"+page+".php";
		CURRENT_PAGE = page;
		window.location.hash = "#/"+page;
		document.title = 'fresh media - ' + page;
		
		
		// change page
		
		$.get(href, function(response,status) {
			if (status == 'success') {
				response = $(response);
				$(".container").fadeOut(500, function() {
					$(".container").html(response.find(".container").html());
					$(".container").fadeIn(500);
				});
			}
		});
		
		pageTracker._trackPageview("/" + page + ".php");
	}
	
	function getPageFromHash() {
		return window.location.hash.toString().split('/').pop();
	}
	
	setInterval(function() {
		var page = getPageFromHash();
		if (page != CURRENT_PAGE) {
			changePage(page);
		}
	}, 200);
	
	$(document).ready(function() {
		// get new page content if not home page
		if (CURRENT_PAGE == 'home') {
			$(".container").fadeIn(500);
		} else {
			document.title = 'fresh media - '+CURRENT_PAGE;
			$.get(URL+'/'+CURRENT_PAGE+'.php',function(response) {
				response = $(response);
				$(".container").html(response.find(".container").html()).fadeIn(500);
			});
		}
		
		// a on click event looks like this
		$(".pagelink").live('click', function (e) {	// a.pagelink targets all anchor tags with the class pagelink (whereas a .pagelink targets all elements as a decendent of anchor tags)
			e.preventDefault();		// this ensure the page doesnt change to the link (default browser behaviour)
			
			changePage($(this).attr('href').split('/').pop().split('.')[0])
		});
		
		
	});
})(jQuery);
