/**
 * Keeps track of interval that updates the portfolio image
 */
var portfolioImageCycleInterval;

/**
 * Defines whether the sidebar panels should be animated on page load
 */
var shouldAnimateSidebar;

/**
 * Keeps track of the sidebar width as specified in the css file (so we can extend them to the right length)
 */
var sidebarWidth;


/**
 * Keeps track of page loading statusses
 * pageLoadingCompleted indicates whether the new page has been loading in the temp div using ajax
 * contentFadeOutCompleted indicates whether the old content has been completely faded out
 */
var pageLoadingCompleted = false;
var contentFadeOutCompleted = false;


/**
 * Keeps track of loaded content
 */
var contentFromAjax;
var headerFromAjax;
var sidebarFromAjax;

/**
 * IE version
 */
var internetExplorerVersion = -1; //-1 indicates browser other than IE



/**
 * Hooks up any ajax links, determines IE version and stores the sidebar width
 */
$(document).ready(function(){
	//Get IE version
	if (navigator.appName == 'Microsoft Internet Explorer')
	{
		var userAgent = navigator.userAgent;
		var ieExpression  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
		if (ieExpression.exec(userAgent) != null)
			internetExplorerVersion = parseFloat( RegExp.$1 );
	}
	
	hookUpAjaxLinks();
	hookUpContactHover();
	
	//TODO: Make this dynamic (css returns 117 istead of 115 for some reason)
	//sidebarWidth = 115;
	sidebarWidth = $('#sidebar .nav').css('width');
	
	//Start portfolio image cycle if needed
	startPortfolioImageCycle();


});



/**
 * Loads a page using ajax
 * @param {Object} linkElement the <a> element that called the function
 */
function loadPage(linkElement) {
	//Stop any intervals
	clearInterval(portfolioImageCycleInterval);
	
	//Reset loading bools
	pageLoadingCompleted = false;
	contentFadeOutCompleted = false;
	
	//Determine if sidebar should be animated
	if($(linkElement).hasClass('staticsidebar') == true) {
		shouldAnimateSidebar = false;
	} else {
		shouldAnimateSidebar = true;
	}
		
	//Get url
	var url = $(linkElement).attr('href');

	//Load the new content in the temporary div
	$.get(url,{ajaxRequest: 0},function(data){
		contentFromAjax = $('#content',data);
		headerFromAjax = $('#header',data);
		sidebarFromAjax = $('#sidebar',data);
		ajaxLoadingComplete();
	});
	
	//Lock content height
	$('#contentbck').css('height',$('#contentbck').height());
	
	//Fade out content
	$('#content').fadeTo('normal', 0, contentFadeOutComplete);
	
	//Retract sidebar panels if needed
	if(shouldAnimateSidebar) {
		if(internetExplorerVersion == -1) {
			$('#sidebar .contentsub').fadeTo('fast', 0); //Fade out text
			}
		$('#sidebar .nav').animate({'width': '0px'}, 'normal') //Slide to left
		$('#sidebar').delay(230).fadeTo('fast', 0); //Fade out complete sidebar
	}
	
	return false;
}

/**
 * Fired when ajax page load completed
 */
function ajaxLoadingComplete() {
	  
	pageLoadingCompleted = true;
	
	//If the page is loaded and the content is faded out, we can start the transition
	if (pageLoadingCompleted == true && contentFadeOutCompleted == true) {
		startPageTransition();
	}
}

/**
 * Fired when content is completely faded out
 */
function contentFadeOutComplete() {
	contentFadeOutCompleted = true;
	
	//If the page is loaded and the content is faded out, we can start the transition
	if (pageLoadingCompleted == true && contentFadeOutCompleted == true) {
		startPageTransition();
	}
}

/**
 * Starts the behind the scenes page transition
 */
function startPageTransition() {	
	//Replace content
	$("#content").html(contentFromAjax.html());
	
	//Get new content height and animate the content div
	var newContentHeight = $("#content").innerHeight();
	$('#contentbck').animate({'height':newContentHeight},'normal');

	//Replace header
	$("#header").html(headerFromAjax.html());
	
	//Replace sidebar
	$("#sidebar").html(sidebarFromAjax.html());
	
	//Make sure new sidebaritems are hidden if needed
	if(shouldAnimateSidebar) {
		$('#sidebar').css('opacity', 0);
		$('#sidebar .nav').css('width', '0px');
		if(internetExplorerVersion == -1) {
			$('#sidebar .contentsub').css('opacity', 0)
		}
	}
	
	hookUpAjaxLinks();
	hookUpContactHover();
	startPortfolioImageCycle();
	
	//Show interface after the content has been replaced	
	//Fade in the content div
	$("#content").fadeTo('normal',1);
	
	//Extend sidebar panels
	if (shouldAnimateSidebar) {
		$('#sidebar').fadeTo('fast', 1);
		if(internetExplorerVersion == -1) {
			$('#sidebar .contentsub').fadeTo('fast', 1);
		}
		$('#sidebar .nav').animate({'width': sidebarWidth}, 'normal');
	}
}



/**
 * Finds all <a> elements on the page that need an ajax link
 * 
 * A link is considered ajax-able if the href is not (empty or '#' or starts with 'mailto:') and
 * when it links to an internal page and if it doens't have the class 'noajax'
 */
function hookUpAjaxLinks() {
	//alert('hookUpAjaxLinks');
	
	//A tags where href contains an internal link, except those with a noajax class
	var baseURL = document.location.href.split('/')[2];
	$('a').not('[href=""]').not('[href="#"]').not('[href^="mailto:"]').not('[href^="http://"]').add('[href^="http://'+baseURL+'"]').not('[class~="noajax"]').click(function(){
		loadPage(this);
		return false;
	});
}


/**
 * Shows a popup with given index at the mouse position
 * @param {Object} popupIndex	index of popup to show
 */
function showPopup(popupIndex, e) {
	//Hide all popups
	$('.popup').fadeOut('fast');
	
	//Set popup position
	//$('#popup'+popupIndex).css('top',event.pageY-260);
	//$('#popup'+popupIndex).css('left',event.pageX-75);
	
	//Show popup
	$('#popup'+popupIndex).fadeIn('fast');
}

/**
 * Hides a popup with given index
 * @param {Object} popupIndex	index of popup to hide
 */
function hidePopup(popupIndex) {
	$('#popup'+popupIndex).fadeOut('fast');		
}



/**
 * Starts the portfolio image cycle if needed
 */
function startPortfolioImageCycle() {
	if($("#portfolioImg img").length == 1 && $("#imageURLs").length == 1) {
		var images = $("#imageURLs:first").attr('value').split(',');
		if (images.length > 1) {
			portfolioImageCycleInterval = setInterval(function(){
				updatePortfolioImage(images);
			}, 5000);
		}
	}
	
}

/**
 * Updates portfolio image tag by randomly picking an image from the urlArray
 * @param {Object} urlArray		array of images to randomly pick from
 */
function updatePortfolioImage(urlArray) {
	randomIndex = Math.floor ( Math.random() * urlArray.length );
	
	$('#portfolioImg img').fadeOut('slow',function(){
		$('#portfolioImg img').attr('src',urlArray[randomIndex]);
		$('#portfolioImg img').fadeIn('slow');
	});
}




/**
 * Hooks up the mouseenter and mouseleave events for the contact page
 */
function hookUpContactHover(){
    $('#contacts li').mouseenter(function(event){
        $(this).children('div').slideDown('fast'); //show('slow');
    });
	
	$('#contacts li').mouseleave(function(event){
		 $(this).children('div').slideUp('fast'); //hide('slow');
    });
}

