
/////////////////// Is called whenever the url bar changes (FROM SWFAddress below) or from a link click (via hijax.js) ////////////
function handleChange(event) {
	
	//Take the event from SWFAddress below
	var pathToContent = event.path; //The value of the clicked on link
	
	//If the back button was pressed and results in a page w/o hash, we need to set a pathToContent (which would be the index page since that's our root)
	if(pathToContent.length == 1) { 
		pathToContent = getPathToContent();
	} else {
		pathToContent = formatFullUrl(pathToContent);
	}
	
	//Get the new content and fill and replace the old	
	getNewContent(0,pathToContent); 
	
	
}

//////////////// Get the new content via ajax and display with html ////////////////////////////////////////////////////////////////////
function getNewContent(counter,path) {
	// Wait for this flag to be set to true via flash actionscript call (readyForNewContentDisplay flashcommunciton.js), if it's still false recursively recall
	//it's self every .5 seconds
	if(counter > 10 || neverLoadContent) {
		//alert('Never load Content');
		neverLoadContent = false;
		return false;
	} else if(!loadNewContent) {
		return setTimeout(function() {getNewContent(counter++,path);},500); ////////If not loaded, wait 500 milliseconds and try again ///////
	
	} else {
		//The content is ready to load
		//alert('loading Content for: '+path);
		
		//If the back button is pressed from the portfolio viewer being on
		//if(currentPage == "jsp" || currentPage == "secant-medical" || currentPage == "victrex" || currentPage == "elsevier" || currentPage == "tunnell" || currentPage == "invibio") { hideFlash(); tellFlashToStop();}
		
		////////////////////// Path Formatting /////////////////////////////////////////////
		path = path.replace(/\//, ''); //Remove first backslash
		var pathArray = path.split("/"); //An array of the path seperated by the backslash
		var pathPage = pathArray.pop(); //The page with the extension
		currentMainSection = pathArray[0]; //The current main section
		pathPage = pathPage.slice(0,pathPage.lastIndexOf(".")); //Take off the extension
		currentPage = pathPage; //Assign the current page to the path, need this here to handle back button presses as well as clicks
		
		if(pathArray.length > 0) {var pathMainSection = pathArray[0];} //The section 
		
		if(pathArray.length == 2 && pathArray[0] == "portfolio-results" && pathArray[1] == "visuals" && currentPage != "visuals") { currentPage = "visuals-detail";} //This is the individual visual pages, rename to a common file for flash transition
		//////////////////////////////////////////////////////////////////////////////////
		
		/////////////////// Content Handling ////////////////////////////////////////////////
		$('#content').load(path,"sid="+Math.random(),function(){validateImgLoad();}); // Load the content, and on completion verify image load before send message to flash
		
		////// Update the body class ///////
		$('body').removeClass();
		$('body').addClass(pathMainSection);
		$('body').addClass(pathPage);
		
		//////////// Page specific functions ///////////////////
			
			///////////// Active State on top navigation ///////
			handleActiveLinkForHistory(pathMainSection);
			
			///////////// Arrows First //////////
			if(path == 'agency-employment/agency-employment.php' || (pathMainSection == 'agency-interactive' && currentPage != "agency-interactive")) {
				$('#arrow-left,#arrow-right').addClass('arrows-show'); //Show arrows 
			} else {
				$('#arrow-left,#arrow-right').removeClass('arrows-show'); //Hide arrows
			}	
			
			////////////// Footer Content /////////////////////
		
			if(path == 'agency-employment/agency-employment.php') {
				$('#rightFooterSpan').load("include/templateFiles/footerBucketEmployment.php","sid="+Math.random()); // Load the employment footer
				$('#openEmploymentImage').css('display','inline');
			} else {
				$('#rightFooterSpan').load("include/templateFiles/footerBucketLogin.php","sid="+Math.random()); // Load the login footer
				$('#openEmploymentImage').css('display','none');
			}
			
			/////////// Handle open avatars //////////////////////////
			if(currentPage == "agency-employment" || currentPage == "agency-thinking" || currentPage == "agency-interactive")  {openAvatarMenu(pathMainSection);} else {closeAvatarMenu();}
	}
}

//#################################################################### IMAGE VALIDATION #################################################//
////////////// Validate images to ensure they were loaded ////////////////////////////////////////////
function validateImgLoad() {
	var widths = '';
	var numberOfImages = $('#content img.checkForLoad').size();
	var tempImageCounter = 1;
	
	if(numberOfImages > 0) {
		$('#content img.checkForLoad').each(function() {  
			checkImgWidth($(this),tempImageCounter,numberOfImages);
			tempImageCounter++;
		});
	} else {
		contentLoaded = true;
	}
}

////////////// A recursive functions that keeps checking an image until it returns a width ///////////
function checkImgWidth(img,counter,totalImages) {
	if($(img).width() == $(img).attr('rel')) {
		//alert(counter);
		if(counter == totalImages) {
			//if(confirm('display content?')) {
				setTimeout(function() {contentLoaded = true;},100);
			//}
		}
	} else if (!contentLoaded) {
		//alert($(img).attr('src') + " Failed, check again");
		return setTimeout(function() {checkImgWidth(img,counter,totalImages);},100); ////////If no width, call function again after 100 milliseconds
	}
}

//#################################################################### PATH HANDLING #################################################//
/////////////// If no hash was provided, determine which page we are on and load that content /////////////////////////////////////////////////////////////
function getPathToContent() {
	//Take the current url, and keep everything after the domain
	var browserUrl = window.location.href;
	browserUrl = formatFullUrl(browserUrl); //Strip out the domain
	if(browserUrl == '') {browserUrl = 'index.php';} //This handles the case of a user going to the root of the site, without entering index.php
	
	//Now we inspect that url, if it's not index.php, we reroute them to index.php#browserURL
	if(browserUrl != "index.php") {
		sendToIndex(browserUrl);
	} else {
		return "index.php";
	}
}

///////////// Check the url and remove the domain, only leaving the path to content (ie http://www.test.com/path/to/content will be reduced to path/to/content) /////
function formatFullUrl(url) {
	var formattedUrl = '';
	
	formattedUrl = url.replace(currentDomainForSWFAddress,''); //Remove the domain and leave the path
	
	return formattedUrl;
}

/////////////// If the main url page is not the index, send reroute them to index.php#browserURL //////////////////////////////////////////
function sendToIndex(browserUrl) {
	window.location.href = currentDomainForSWFAddress + 'index.php#/'+browserUrl;
}

////////############ Constructors ##################################////////////////////////////////////////////////////////////////////////
SWFAddress.addEventListener(SWFAddressEvent.CHANGE, handleChange);
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////