(function($){
	$(document).ready(function(){
		var siteURL = "http://" + top.location.host.toString();
		
		var setHash = function(href) {
			if (href.indexOf(siteURL+window.location.pathname)!==-1) {
				href = href.substring((siteURL+window.location.pathname).length);
			}
			window.location.hash = '!/'+href;
		}
		
		var handlers = function() {
			
			var internalLinks = $("a[href^='"+siteURL+"'], a[href^='/'], a[href^='./'], a[href^='../'], a[href^='#']");

			

			$(internalLinks).click(function(e){
				if (! $(this).hasClass('noAjax')) {
					e.preventDefault();
					var href = $(this).attr('href');
					setHash(href);
				}
			});
			
			$('form').submit(function(e){
				if (! $(this).hasClass('noAjax')) {
					e.preventDefault();
					var href = $(this).attr('action') + '?' + $(this).serialize();

				}
			});
			
			if (window['player_object'] && window['player_object'].player_handlers) {
				player_object.player_handlers();
			}
			
			$('a').click(function(e){
				var href = $(this).attr('href');
				if (href.substring(0,4)=='http'&&href.substr(0,29)!='http://www.thekevinscott.com/booking') {
					$(this).attr('target','_blank');
				}
				
			});
			
		}
		handlers();
		
		
		var old_url = '';
		var old_content;
		var timerCount = 50;
		var cache = {};
		var cache_setting = true;
		var ajaxTimer;
		var ajaxLimit = 5000; // 5 seconds
		var loop = function() {
			var url = window.location.hash.substring(3);
			if (url!==old_url) {
				//console.log('change it');
				old_url = url;
				if (cache[url] && cache_setting) {
					$('#content').replaceWith(cache[url]);
				} else {
					
					old_content = $('#content').html();
					$('#content').html('<img src="'+template_directory+'/images/loading.gif" class="loading" />');
					
					var ajaxAllow = true;
					ajaxTimer = setInterval(function(){
						if (ajaxAllow) {
							ajaxAllow = false;
							$('#content').html(old_content);
							alert("There was an error; please try again later.");
						}
					},ajaxLimit);
					
					$.post(url,{ajax:1},function(data){
						if (data && ajaxAllow) {
							//console.log(data);
							//console.log($('#content'));
							ajaxAllow = false;
							cache[url] = data;
							$('#content').replaceWith(data);
							handlers();
						}
					});
				}
			}
		}
		var timer = setInterval(loop,timerCount);
		loop();
		
	});
})(jQuery);
