/** GLOBAL VARIABLES **/

var animated = false; //Trigger to prevent stacked animation
var thumbnailIndex = 1; //Index for the gallery
var imageSequenceIndex = 0; //Check for the current position in image sequence 
var projectSequenceIndex = 0; //Check for the current position in project sequence
var curSlideIndex = 0; //Indexing feature for the slideshow
var curDisplay;
var curFooter;
var requests=new Object();
var cache=new Object();
var currProject=new Object();
var currProjectImage=0;
var projectIdRequest=0;
var newFooter;
var shiftWidth;
var animatingGallery = false;

/** FUNCTIONALITY FOR LANDING PAGE - SLIDESHOW **/

var slideTimer = window.setInterval(autoSlideshow, 6000); //TIMER for slideshow

//CONTROLLER for slideshow, if the index shows last, then go back to beginning
function autoSlideshow() {
	if(curSlideIndex+1 < $('.landing-slideshow li').size()){
		slideshowSwitch(curSlideIndex+1);
	} else {
		slideshowSwitch(0);
	}
}

//SWITCHER for slideshow, pass the index, then fade in the li based of parameter, hide others
function slideshowSwitch(newSlideIndex) {
	$slideshow = $('ul.landing-slideshow');
	$slideshow.children('li').eq(newSlideIndex).hide();
	$slideshow.children('li').eq(newSlideIndex).children('img').show();
	$slideshow.children('li').eq(curSlideIndex).fadeOut(500,function(){
		$slideshow.children('li').eq(curSlideIndex).addClass('nodisplay');
		$slideshow.children('li').eq(newSlideIndex).fadeIn(500);
		$slideshow.children('li').eq(newSlideIndex).removeClass('nodisplay');
		$slideshow.children('li').eq(newSlideIndex).show();
		curSlideIndex = newSlideIndex;
	});
	$('.pagination a').each(function(){
		$(this).removeClass('on');
	});
	$('.pagination a').eq(newSlideIndex).addClass('on');
}

/******************************************************/

/** FUNCTIONALITY FOR FOOTER NAVIGATION **/

//Slide down the footer - slide back up if parameter is passed
function slidingNavAnimateOff(attribute) {
	var distance = $slidingcontainer.innerHeight();
	$slidingcontainer.animate({
		bottom: '-='+ distance
	}, 500, function(){
		if(attribute != undefined) {
			slidingNavAnimateOn(attribute);
		} else {
			animated = false;
			offStateNav($('.footer .leftcol ul.nav'));
		}
	});
}

//Slide up the footer - check parameter type, hide/show elements, then slide up
function slidingNavAnimateOn(attribute) {
	var distance = $slidingchildren.height();
	if(attribute != undefined) {
		if(attribute == "word") {
			toggleInWord();
			$slidingchildren = $('.inword');
		} else if(attribute == "pict"){
			toggleInPict();
			$slidingchildren = $('.inpict');
		} else {
			toggleCompact();
			$slidingchildren = $('.inpict-compact');
		}
		var newHeight = -1*$slidingcontainer.height()+$('.footer').outerHeight();
		$slidingcontainer.css("bottom",newHeight);
		distance = $slidingcontainer.height();
	}
	$slidingcontainer.animate({
		bottom: '+='+distance
	}, 500, function(){
		animated = false;
	});
}

//Check footer position (i.e.: on or off screen)
function isSlidingNavOn(){
	var position = parseInt($slidingcontainer.css('bottom'));
	if(position>=0){
		return true;
	} else {
		return false;
	}
}

//The controller for footer - CALL THIS FUNCTION to use the footer
function slidingContainerToggle(attribute) {
	if(isSlidingNavOn() == false){
		slidingNavAnimateOn(attribute);
	} else {
		slidingNavAnimateOff(attribute);
	}
}

//SHOW - in words element for footer
function toggleInWord() {
	$slidingcontainer.children('.inword').removeClass('nodisplay');
	resizeTextContainer(true);
	$slidingcontainer.children('.inpict').addClass('nodisplay');
	$slidingcontainer.children('.inpict-compact').addClass('nodisplay');
	$('.job-description').fadeOut(200);
}

//SHOW - in picture element for footer
function toggleInPict() {
	$slidingcontainer.children('.inpict').removeClass('nodisplay');
	$slidingcontainer.children('.inword').addClass('nodisplay');
	$slidingcontainer.children('.inpict-compact').addClass('nodisplay');	
	//$('.job-description').fadeOut(200);
}

//SHOW - the compact version (When gallery is enlarged)
function toggleCompact(){
	$slidingcontainer.children('.inpict-compact').removeClass('nodisplay');
	$slidingcontainer.children('.inword').addClass('nodisplay');
	$slidingcontainer.children('.inpict').addClass('nodisplay');
}

/******************************************************/

/** OTHER FUNCTIONALITY **/

//STATE CONTROLLER for navigation - pass parent ul as parameter - switch off all 'on-state', if li is defined, then turn 'on-state' for passed li
function offStateNav(parentul,parentli){
	if(!$(parentul).hasClass('nostate')) {
		$(parentul).children('li').each(function(){
			if($(this).hasClass('on')){
				$(this).removeClass('on');
			}
		});
		if(parentli != undefined){
			$(parentli).addClass('on');
		}
	}
}

//SLIDER - for the body text in navigation footer
function slideBodyText(forceResize) {
	var newPos = $('.inword ul.nav li.on').index()*$('.viewfinder').width();
	var curPos = $('.bodycopy').position().left;
	if(forceResize == true) {
		if(newPos != curPos) {
			$('.bodycopy').animate({
				left: newPos*-1
			},0);
		}
	} else {
		if(newPos != curPos) {
			$('.bodycopy').animate({
				left: newPos*-1
			},500);
		}
	}	
}

//SLIDER - for the thumbnails in navigation footer
function slideGallery(pressedBtn) {
	var curPos = $('.thumbnails').position().left;
	
	var eachWidth = $('.thumbnails div').width();
	var totalWidth = $('.thumbnails').find('div.feed').length*eachWidth;
	var totalIndex = Math.ceil(totalWidth / $('.inpict').width());
	var addition = $('.inpict').width()%eachWidth;
	
	if(pressedBtn == 'next' && animatingGallery == false) {
		if(thumbnailIndex < totalIndex) {
			animatingGallery = true;
			if(((thumbnailIndex+1) * $('.inpict').width()) > totalWidth) {
				$('.thumbnails').animate({
					left: "-="+((totalWidth % $('.inpict').width())+(thumbnailIndex*addition))
				},500, function(){
					animatingGallery = false;
				});	
			} else {
				$('.thumbnails').animate({
					left: "-="+($('.inpict').width()-addition)
				},500, function(){
					animatingGallery = false;
				});

			}
			thumbnailIndex++;
		}
	} else {
		if(animatingGallery == false) {
			if(thumbnailIndex >= totalIndex) {
				animatingGallery = true;
				thumbnailIndex--;
				$('.thumbnails').animate({
					left: "+="+(((totalWidth - (thumbnailIndex * $('.inpict').width())))+(thumbnailIndex*addition))
				},500, function(){
					animatingGallery = false;
				});
			} else {
				if(curPos != 0) {
					animatingGallery = true;
					shiftWidth -= $('.inpict').width();
					$('.thumbnails').animate({
						left: "+="+($('.inpict').width()-addition)
					},500,function(){
						animatingGallery = false;
					});
					thumbnailIndex--;
				}
			}
		}
	}
}

//Force text container width to be window width
function resizeTextContainer(forceResize) {
	$('.txtcontainer').hide();
	$('.txtcontainer').width($('.viewfinder').width()+2);
	if(forceResize == true){
		slideBodyText(forceResize);
	}
	$('.txtcontainer').show();
}

//ENLARGE IMAGE - Set to fullscreen image
function supersizeImage(image) {
	var imagewidth = 1400;
	var imageheight = 840;
	var browserwidth = $(window).width();
	var browserheight = $(window).height();

	var ratio = imageheight/imagewidth;

	if ((browserheight/browserwidth) > ratio){
		$(image).height(browserheight);
		$(image).width(browserheight / ratio);
	} else {
		$(image).width(browserwidth);
		$(image).height(browserwidth * ratio);
	}
	$(image).css('left', (browserwidth - $(image).width())/2);
	$(image).css('top', (browserheight - $(image).height())/2);
}

//Force resize all the fullscreen image
function forceSupersize(){
	$('img.supersize').each(function(){
		if($(this).parent().is(':visible')) {
			supersizeImage($(this));
		} else {
			$(this).parent().removeClass('nodisplay');
			$(this).parent().show();
			supersizeImage($(this));
			$(this).parent().hide();
		}
	});
	resizeTextContainer(true);
	$('.thumbnails').animate({
		 left: 0 
	},0,function(){
		thumbnailIndex=1;
	});
}

//KILL SLIDESHOW - stop and remove slideshow
function killSlideshow() {
	if($('.landing-page').is(":visible") == true) {
		$('.slideshow-control').remove();
		window.clearInterval(slideTimer);
		$('.landing-page').fadeOut(300,function(){
			$('.landing-page').remove();
		});
	}
}

function showSlideshow() {
	$loadingAnim.hide();
	$('.landing-page').css("visibility","visible");
}

/******************************************************/

/** GALLERY FUNCTIONALITY **/

function setProjectImage(number){
	if(number<0){
		number=(currProject['Images'].length-1);
	}
	if(!currProject['Images'][number]){
		number=0;
	}
	currProjectImage=number;
			
	if(currProject['Images'][number]['Fullscreen']){
		var newImageType = "fullscreen";
		//curDisplay = $fullscreen;		
	}
	else {
		var newImageType = "laptop";
		//curDisplay = $laptop;
	}
	var newImageSrc = currProject['Images'][number]['Image'];
	changeImageSeq(newImageSrc, newImageType);	
}

//CHANGING IMAGE sequence, parameter: New image source and Image type
//Will determine what to do with the new image
function changeImageSeq(newImageSrc,newImageType){
	
	$loadingAnim.show();
	
	if(isIE()){
		var randomnumber=Math.floor(Math.random()*200)
		var randomVar='?rand='+(new Date()).getTime()+'-'+randomnumber;	
	}
	else {
		var randomVar='';
	}
	
	newImageSrc=newImageSrc+randomVar;

	if(newImageType == "fullscreen") {
		if(curDisplay == $fullscreen) {
			curDisplay.fadeOut(300,function(){
				forceSupersize();
				$fullscreen.children('img.supersize').attr('src',newImageSrc).load(function(){
					$loadingAnim.hide();
					curDisplay.fadeIn(300);	
				});
			});
		} else {
			curDisplay.fadeOut(300,function(){
				forceSupersize();
				curDisplay = $fullscreen;			
				$fullscreen.children('img.supersize').attr('src',newImageSrc).load(function(){
					$loadingAnim.hide();
					curDisplay.fadeIn(300);
				});
			});
		}
	} else if (newImageType == "laptop"){
		if(curDisplay == $fullscreen) {
			curDisplay.fadeOut(300,function(){
				curDisplay = $laptop;
				$('#laptopScreen').attr('src',newImageSrc).load(function(){
					$loadingAnim.hide();
					curDisplay.fadeIn(300);
				});
			});
		} else {
			$laptop.show();
			$('#laptopScreen').hide();
			$('#laptopScreen').fadeOut(300,function(){
				$('#laptopScreen').attr('src',newImageSrc).load(function(){
					$loadingAnim.hide();
					$('#laptopScreen').fadeIn(300);
				});
			});
		}
	}
	/*
	if(curDisplay == $fullscreen) {
		$laptop.hide();
		curDisplay.fadeOut(300,function(){
			if(newImageType == "fullscreen"){
				changeFullscreenImage(newImageSrc);
			} else {
				changeLaptopImage(newImageSrc);
				curDisplay = $laptop;
			}
			curDisplay.fadeIn(300);
		});
	} else if(curDisplay == $laptop){
		$fullscreen.hide();
		if(newImageType == "laptop") {
			$('#laptopScreen').fadeOut(300,function(){
				changeLaptopImage(newImageSrc);
				$('#laptopScreen').fadeIn(300);
			});
		} else {
			curDisplay.fadeOut(300,function(){
				changeFullscreenImage(newImageSrc);
				curDisplay = $fullscreen;
				curDisplay.fadeIn(300);
			});
		}
	}
	*/
}

//Function to change image if new type is fullscreen
function changeFullscreenImage(newImageSrc){
	$fullscreen.children('img').attr('src',newImageSrc);
	forceSupersize();
}

//Function to change image if new type is laptop
function changeLaptopImage(newImageSrc){
	$('#laptopScreen').attr('src',newImageSrc);
}

//FUNCTION EDIT - handler for left arrow click
function prevImageSeq(){
	setProjectImage(currProjectImage-1);
}

//FUNCTION EDIT - handler for right arrow click
function nextImageSeq(){
	setProjectImage(currProjectImage+1);
}

//Functiont that will load new project
function loadProject(projectId,allowFirstSkip){
	projectIdRequest=projectId;
	killSlideshow();
	slidingContainerToggle('compact');
	
	killAll();
	$loadingAnim.show();
	
	if(!cache['Projects']){
		cache['Projects']=new Object();	
	}

	if(cache['Projects'][projectId]){
		loadProjectData(cache['Projects'][projectId]);
	}
	else {
		if(requests['loadProject']){
			requests['loadProject'].abort();	
		}
		requests['loadProject']=$.ajax({
			type: "POST",
			url: "projects",
			data:({"json":true,"ProjectId":projectId}),
			dataType:"json",
			error: function(){
				document.location.href=$('base').attr("href");
			},
			success: function(resp){	
				cacheProjectImages(projectId,resp,allowFirstSkip);
			}
		});
	}
}

function loadProjectData(data,allowFirstSkip){
	if(!data['Info'] || !data['Info']['Id']){
		alert('Failed to load project. Please try again');
		return false;
	}
	
	currProject=data;
	document.location.href=currUrl()+'#'+data['Location'];
	
	//Update the job detail
	if($jobdescription.is(":visible") == true) {
		$jobdescription.fadeOut(200, function(){
			refreshJobInfo(data['Info']['Title'],data['Info']['Description'],data['Info']['Client'],data['Info']['Website']);
			$jobdescription.fadeIn(200);
		});
	} else {
		refreshJobInfo(data['Info']['Title'],data['Info']['Description'],data['Info']['Client'],data['Info']['Website']);
		$jobdescription.fadeIn(200);
	}
	
	$('.content-fullscreen').children('img.desc').remove();
	if(data.Info.Feature_Overlay){
		$('.content-fullscreen').append('<img alt="'+data.Info.Title+'" src="'+data.Info.Feature_Overlay+'" class="desc">');
	}

	$loadingAnim.hide();

	if(data.Info.Featured && allowFirstSkip){
		setProjectImage(1);
	}
	else {
		setProjectImage(0);
	}
}

//Function that handles the update for job description - top left hand corner
function refreshJobInfo(Title,Description,Client,Website) {
	//Replace the job-detail with new text and re-render non-standard fonts
	$('#topText h2 span').html(Title);
	$('#topText h3.worktype .outerwrap .innerwrap').html(Description);
	
	$('#bottomText h3.grey .outerwrap .innerwrap').html('Client: '+Client);	
	$('a.hyperlink').attr('href',Website);
	if(Website){
		$('a.hyperlink').show();
	}
	else {
		$('a.hyperlink').hide();	
	}
	$('.job-description').show();
	$('#bottomText').css('left',$('#topText').width()-30);
	$('.job-description').hide();
	//Cufon.replace('h2 span');
}

//Button handler for next project
function nextProject(){

	killAll();
	$loadingAnim.show();
	
	if(requests['nextProject']){
		requests['nextProject'].abort();	
	}
		
	requests['nextProject']=$.ajax({
		type: "POST",
		url: "projects",
		data:({"json":true,"ProjectId":projectIdRequest,"Method":"nextProject"}),
		dataType:"json",
		error: function(){
			document.location.href=$('base').attr("href");
		},
		success: function(resp){
			if(resp){		
				projectId=resp['Info']['Id'];	
				projectIdRequest=projectId;
			
				cacheProjectImages(projectId,resp);
			}
		}
	});
}

//Button handler for prev project
function prevProject(){
	killAll();
	$loadingAnim.show();
	
	if(requests['prevProject']){
		requests['prevProject'].abort();	
	}
	requests['prevProject']=$.ajax({
		type: "POST",
		url: "projects",
		data:({"json":true,"ProjectId":projectIdRequest,"Method":"prevProject"}),
		dataType:"json",
		error: function(){
			document.location.href=$('base').attr("href");
		},
		success: function(resp){		
			projectId=resp['Info']['Id'];	
			projectIdRequest=projectId;
			
			cacheProjectImages(projectId,resp);
		}
	});
}

function cacheProjectImages(projectId,resp,allowFirstSkip){
	cache['Projects'][projectId]=resp; //cache the response

	cache['Projects'][projectId]=resp; //cache the response
	
	if(!cache['ImageCount']){
		cache['ImageCount']=new Object();	
	}		
	
//loadProjectData(cache['Projects'][projectId]);
	
	cache['ImageCount'][projectId]=resp.Images.length;
	if(resp.Images.length>1){
		$('.middleArrow').show();
	}
	else {
		$('.middleArrow').hide();
	}
	
	
	if(isIE()){
		var randomnumber=Math.floor(Math.random()*200)
		var randomVar='?rand='+(new Date()).getTime()+'-'+randomnumber;	
	}
	else {
		var randomVar='';
	}
	
	for(i in resp.Images){
		$('<img />')
			.attr('src',resp.Images[i]['Image']+randomVar).attr('rel',projectId)
			.load(function(){
				imageProjectId=$(this).attr("rel");
				cache['ImageCount'][imageProjectId]--;
				if(cache['ImageCount'][imageProjectId]<1){
					if(imageProjectId==projectIdRequest){
						//only load this if user is still on the same project								
						loadProjectData(cache['Projects'][imageProjectId],allowFirstSkip);
					}
				}
			}
		);
	}
}

/******************************************************/

/** START HERE FOR BODY CONTENT & TRIGGERS **/

$(document).ready(
	function() {
		
		//Define the variables for navigation footer, will be referred globally
		$slidingcontainer = $('.slidingcontainer');
		$slidingchildren = $('.slidingcontainer div');
		
		//Define the fullscreen, loading animation, laptop and job-description - will be referred globally
		$fullscreen = $('.content-fullscreen');
		$laptop = $('.content-centered');
		$jobdescription = $('.job-description');
		$loadingAnim = $('#loadingAnim'); 
		
		//Hide everything on initialisation
		$slidingcontainer.css('visibility','visible');
		$slidingcontainer.css("bottom","-331px");
		$fullscreen.css('visibility','visible');
		$fullscreen.hide();
		$laptop.css('visibility','visible');
		$laptop.hide();
		$jobdescription.css('visibility','visible');
		$jobdescription.hide();
		
		curDisplay = $laptop;
		
		//RESIZE - all fullscreen image to be fullscreen
		$('img.supersize').each(function(){
			supersizeImage($(this));
		});
		
		//LISTENER - in window that will resize, reposition everything
		$(window).bind("resize", forceSupersize);

		//On-off state for all buttons across site 
		$('ul.nav li a').click(function() {
			$parentli = $(this).parent().parent();
			$parentul = $(this).parent().parent().parent();
			offStateNav($parentul,$parentli);
		});
		
		/* -- FUNCTIONALITY FOR LANDING PAGE -- */
		
			//JUMP - into specific project based on index
			$('.pagination a').click(function(){
				slideTimer = window.clearInterval(slideTimer);
				slideshowSwitch(parseInt($(this).html())-1);
				$('.slideshow-control a.pause').addClass("start");
				return false;
			});
			
			//PAUSE - slideshow and resume toggle
			$('.slideshow-control a.pause').click(function(){
				if($(this).hasClass('start')) {
					$(this).removeClass("start");
					slideTimer = window.setInterval(autoSlideshow, 6000);
				} else {
					$(this).addClass("start");
					slideTimer = window.clearInterval(slideTimer);
				}
				return false;
			});
			
			$('.landing-slideshow img.supersize').each(function(){
				if($(this).parent().index()>0){
					$(this).parent().addClass('nodisplay');
				};
			});
			
			//ENLARGE - featured in the gallery mode
			$('a.project-link').click(function(){
				projectId=$(this).attr("rel");
				
				allowFirstSkip=0;
				if($(this).hasClass('allowFirstSkip')){
					allowFirstSkip=1;	
				}
				
				loadProject(projectId,allowFirstSkip);
				return false;
			});
					
		/* -- FUNCTIONALITY FOR FOOTER BTN -- */
		
			//Functionality to switch from 'in-words' and 'in-pictures'
			$('.staticfooter .leftcol ul.nav li a').click(function(){
				if(animated == false) {
					animated = true;
					newFooter = $(this).attr("class");
					if(curFooter == newFooter) {
						if($('.landing-page').is(":visible") == true) {
							slidingContainerToggle();
							offStateNav($('.footer .leftcol ul.nav'));
						} else {
							if($(this).attr("class").split(' ').slice(0,1) == 'word'){
								slidingContainerToggle('compact');
								$jobdescription.fadeIn(300);
								offStateNav($('.footer .leftcol ul.nav'),$('.footer .leftcol ul.nav li.last'));
								curFooter = $('.footer .leftcol ul.nav li.last a').attr("class");
							} else {	
								slidingContainerToggle();
								curFooter = undefined;
							}
						}
					} else {
						slidingContainerToggle($(this).attr("class").split(' ').slice(0,1));
						curFooter = newFooter;
					}
				}
				return false;
			});
			
			//Close button that will close navigation footer from 'in word' content
			$("#closeBtn").click(function() {
				if($('.landing-page').is(":visible") == true) {
					slidingContainerToggle();
					offStateNav($('.footer .leftcol ul.nav'));
				} else {
					slidingContainerToggle('compact');
					$jobdescription.fadeIn(300);
					offStateNav($('.footer .leftcol ul.nav'),$('.footer .leftcol ul.nav li.last'));
					curFooter = $('.footer .leftcol ul.nav li.last a').attr("class");
				}
				return false;
			});
			
			//Hide thumbnail and switch to compact mode
			$("#hideThumbnail").click(function() {
				slidingContainerToggle('compact');
				return false;
			});
			
			//Hide compact mode and switch to full thumbnail mode
			$("#showThumbnail").click(function() {
				slidingContainerToggle('pict');
				return false;
			});
		
		/* -- FUNCTIONALITY FOR IN-WORDS CONTENT -- */
			
			//Resize the textbox to be window width
			resizeTextContainer(false);
			
			//Slide the text across
			$('.inword ul.nav li a').click(function(){
				slideBodyText();
				return false;
			});

		
		/* -- FUNCTIONALITY FOR IN-PICTURES CONTENT -- */
		
			//Slide the gallery across
			$('.inpict ul.nav li a').click(function(){
				slideGallery($(this).attr('class'));
				return false;
			});
			
			//Trigger to kill slideshow and load project from thumbnail click
			$('.feed a').click(function(){
				document.location.href=$(this).attr('href');							
			});
		
		/* -- FUNCTIONALITY FOR IN-PICTURES COMPACT CONTENT -- */		
		
			//Trigger to switch image sequences back and forth
			$('#leftArrow').click(function(){
				prevImageSeq();
				return false;
			});
			$('#rightArrow').click(function(){
				nextImageSeq();
				return false;
			});
			//Trigger that will call previous project on compact mode
			$('.prevProject').click(function() {
				prevProject();
				return false;
			});
			
			//Trigger that will call new project on compact mode
			$('.nextProject').click(function() {
				nextProject();
				return false;
			});
			
			$('.page-info').click(function(){
				id='page-'+$(this).attr('rel');
				if($(id)){
					$(id).addClass('on');	
					slideBodyText(true);
				}
			});
			
			$('.showjob').click(function(){
				rel=$(this).attr('rel');
				$('.jobinfo').fadeOut(200);
				setTimeout("$('.jobinfo."+rel+"').fadeIn('fast');",300);
				return false;
			});

			$('.pageHref').click(function(){
				document.location.href=currUrl()+'#'+$(this).attr('href');
				return false;
			});
			
	}
);

function currUrl(){
	url=document.location.href.split("#");
	return url[0];
}

function isIE(){
	IE=false;
	jQuery.each(jQuery.browser, function(i, val) {
		if(i=="msie"){
			IE=true;
		}
	});	
	return IE;
}

/******************************************************/
