//CHECK FOR LOCATION CHANGE
// Keep checking to see if user has tried to change location (E.g. using 
// back button in browser).. Load tab specified by new anchor hash value
var first = true;
var animating = true;

$(function(){ 

	$("#background_1").css({ opacity: 0 });
	
	$.ajax({
		 url: '/site/getBG/i/'+randomString(5),
		 type: "GET",
		 success: function(html){
			var img = new Image();
			jQuery(img).load( function() {
				//jQuery(img).hide();
				$("#background_1").css("background-image", "url(/images/bg/"+html+")");
				$('#background_1').animate({
				opacity: 1
				}, 1000, function() {
					// Animation complete.
					$('#background_2').css('z-index', '10');
					$('#background_1').css('z-index', '20');
					animating = false;
				});
			}).attr({ "src": '/images/bg/'+html });
		}
						
	}); 
	
	
	$('.mp_body').jScrollPane();
})

var LocationChecker = {

	initialize: function()
	{
		//alert(document.getElementById('history').src);
		
		this.location = window.location.href;
		that = this;
		this.interval = setInterval(function()
		{
			if (that.location != window.location.href)
			{
				if (window.location.hash.length > 1)
				{
					that.anchor_changed(window.location.hash.substring(1)); // Default to home (if no # val)
					that.location = window.location.href;
				} else {
					loadIntoDiv('ajax_content', '/site/index?ajax_call=1', false, true, true);	
				}
			}
		}, 400); // check at regular intervals*/

	},

	anchor_changed: function(hash)
	{
		// New anchor, move user to correct tab if not there already
		// (check is neccesary since this func will be hit even when
		// user clicks onto a tab themselves)
		if (!ajaxLoaded)
		{
			//var str = document.getElementById('history').src;
			var ary = hash.split('?');
			var page = '/site/'+ary[0];
			var ajaxstr = '?ajax_call=1';
			var hashstr = '';
			
			if (ary.length > 1)
				hashstr = page+ajaxstr+'&'+ary[1];
			else
				hashstr = page+ajaxstr;
			
			loadIntoDiv('ajax_content', hashstr, false, true, true);
			///window.frames['history'].location.hash = hash;   
		} else {
			ajaxLoaded = false;
		}
	}

};
loc_checker = LocationChecker.initialize();


function loadIntoDiv(divID, link, scrollup, hashvar, ajax)
{
	if (!ajax)
		ajaxLoaded = true;
	
	scrollup = false;
	if (hashvar != false) hashvar = true;
	
	var ajaxRequest; // ajax variable
	var ajaxDisplay = document.getElementById(divID);
	
	try{
		// Opera 8.0+, Firefox, Safari
		ajaxRequest = new XMLHttpRequest();
	} catch (e){
		// Internet Explorer Browsers
		try{
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try{
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e){
				// Something went wrong
				alert("Your browser is not compatible, try using Firefox");
				return false;
			}
		}
	}
	
	// receive data sent from the server
	ajaxRequest.onreadystatechange = function(){
		if(ajaxRequest.readyState == 4){
			
			ajaxDisplay.innerHTML = ajaxRequest.responseText;  
			
			var x = ajaxDisplay.getElementsByTagName("script");   
			for(var i=0;i<x.length;i++)  
			{  
				eval(x[i].text);  
			} 
			
			//document.getElementById('history').src = '/mo/js/blank.html';  
			if (hashvar)
			{
				var str = link.split('?');
				var page = str.shift();
				page = page.replace( "/site/", "" );
				page = page.replace( "getBlogPage", "index" );
				
				if (page == 'work') hideMedia();
				if (page == 'contact') initialize();
				
				var hashvars = str[0].replace( "ajax_call=1&", "" );
				hashvars = hashvars.replace( "ajax_call=1", "" );
				
				if (hashvars.length > 0)
				{
					window.location.hash = page+'?'+hashvars;
				}
				else
					window.location.hash = page;
					
			}
			
			$('.mp_body').jScrollPane();
			Froogaloop.init();
		}
	}
	
	ajaxRequest.open("GET", link, true);
	ajaxRequest.send(null); 
	
	if (scrollup) 
		if (window.pageYOffset > 0)
			$('html, body').animate({scrollTop: '0px'}, 600, 'easeOutBounce');
	
}


function changeBG()
{
	if (animating) return;
			if (first)
			{
				first = false;
				animating = true;
				$.ajax({
					 url: '/site/getBG/i/'+randomString(5),
					 type: "GET",
					 success: function(html){
						var img = new Image();
						jQuery(img).load( function() {
							//jQuery(img).hide();
							$("#background_2").css("background-image", "url(/images/bg/"+html+")");
							$('#background_1').animate({
							opacity: 0
							}, 1000, function() {
								// Animation complete.
								$('#background_1').css('z-index', '10');
								$("#background_1").css({ opacity: 1 });
								$('#background_2').css('z-index', '20');
								animating = false;
							});
						}).attr({ "src": '/images/bg/'+html });
					}
									
					}); 
				} 
			else
			{
				first = true;
				animating = true;
					$.ajax({
					 url: '/site/getBG/i/'+randomString(5),
					 type: "GET",
					 success: function(html){
						var img = new Image();
						jQuery(img).load( function() {
							//jQuery(img).hide();
							$("#background_1").css("background-image", "url(/images/bg/"+html+")");
							$('#background_2').animate({
							opacity: 0
							}, 1000, function() {
								// Animation complete.
								$('#background_2').css('z-index', '10');
								$("#background_2").css({ opacity: 1 });
								$('#background_1').css('z-index', '20');
								animating = false;
							});
						}).attr({ "src": '/images/bg/'+html });
					}
									
				}); 
			}
	
}

function switchMenu(obj)
{
	$("div#"+obj).children(".text_exposed_hide").css("display", "none");
	$("div#"+obj).children(".text_exposed_show").css("display", "inline");
	$("div#"+obj).children(".read_more").css("display", "none");
	
}

function randomString(num) {
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var string_length = num;
	var randomstring = '';
	for (var i=0; i<string_length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
	return randomstring;
}

// google maps

var ajaxLoaded = false;

function initialize() {
	if (GBrowserIsCompatible()) {
		if (document.getElementById("map_canvas"))
		{
			var map = new GMap2(document.getElementById("map_canvas"));
			map.setCenter(new GLatLng(50.82632474882324, -0.13840198516845703), 16);
			map.setUIToDefault();
			map.disableScrollWheelZoom()
			
			// Create a base icon for all of our markers that specifies the
			// shadow, icon dimensions, etc.
			var baseIcon = new GIcon(G_DEFAULT_ICON);
			baseIcon.image = "http://www.mindorchard.com/images/MOMarker.png";
			baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
			baseIcon.iconSize = new GSize(25, 34);
			baseIcon.shadowSize = new GSize(37, 34);
			baseIcon.iconAnchor = new GPoint(9, 34);
			baseIcon.infoWindowAnchor = new GPoint(9, 2);
			
			// Set up our GMarkerOptions object
			markerOptions = { icon:baseIcon };
			
			var point = new GLatLng(50.82632474882324, -0.13840198516845703);
			var marker = new GMarker(point, markerOptions);
			
			GEvent.addListener(marker, "click", function() {
				marker.openInfoWindowHtml("Mind Orchard");
			});
			
			map.addOverlay(marker);

		}
	}
}

