var loadingImage = '/images/loadingAnimation.gif';			//The image that should be display when the photo is not loaded yet
var timeoutPhotoLoad = false;								//Global defined timeout, false when there isnt a current timeout
var slideshowTimeout = false;								//Global defined timeout, false when there isnt a current timeout
var slideShow = false;										//True when the script is running the slideShow
var locked = false;											//Will be true when a function is busy displaying a photo
var currentPhoto = 1;										//The current photo
var totalPhotos = 30;										//Total photos that should be displayed
var loadedPhotosSequence = new Array();						//The sequence in which the photos should be loaded
var loadingPhotos = new Array();							//Array containing all the photos that are loaded
var loadedPhotos = new Array();								//Array containing all the photos that are loaded
var photos = new Array();									//Contains all the photos that should be display, keys
															//'filename'	contains the photo filename
															//'width'		the width of the photo
															//'height'		the heigth of the photo
var photoDisplayWidth = false;								//The maximum with available for the photos to load


/**
@description				displays a photo in the overlay. Uses the function waitLoadingPhoto to 
							handle a photo that are not loaded yet
@param integer photo		the key of the photo in the photos array
@return boolean				true when the photo could be displayed, false when the photo is not loaded
							yet. If so it will continue with the function waitLoadingPhoto to load the photo
*/
function photoDisplay(photo) {

	if(locked===true)
		return false;

	//Put the photo lock on it so other functions dont mess with the photo
	locked = true;

	//Building the overlay in which the photo is displayed
	buildBlockUI();

	//Recalculates the last shown image, just to be sure
	resizePhoto(currentPhoto);

	//Sets the currentPhoto pointer to this photo
	currentPhoto = photo;

	//Check if the currentPhoto is inside the photo array
	if(currentPhoto>totalPhotos) 	currentPhoto = 1;
	if(currentPhoto<1) 				currentPhoto = totalPhotos;	

	//Make sure all the photo displays are set to none
	hideAll();

	//Resize the current image to the right porportions
	resizePhoto(currentPhoto);

	//Reset the current location of blockUI
	resetPositionBlockUI();
	
	//Checks if the photo is loaded als the function checkPhotoLoad takes care of from this point on
	if(checkPhotoLoaded(currentPhoto)===false) {
		prioriticyLoadingPhotos(currentPhoto);
		waitLoadingPhoto(currentPhoto);
		return false;
	}


	//Fade in the current photo
	$(("#photo"+currentPhoto)).fadeIn(900);	

	//Set the photo status tekst
	photoDisplayStatus();
	
	//Remove the lock
	locked = false;	

	//Return true because of succes
	return true;

}


/**
@description				puts the diplay on none for all photos
*/
function hideAll() {

	//Make sure all the displays are set to none
	for(var i=1; i<=totalPhotos; i++)
		$(("#photo"+i)).css('display', 'none');
	$("#photoLoad").css('display', 'none');

}

/**
@description						switch the photo from one to the other
@param string/integer action		'backward' one photo back
									'forward' one photo forward
									integer the key of the photo in the photos array
@return boolean						true when the photo could be displayed, false when the photo is not loaded
									yet. If so it will continue with the function waitLoadingPhoto to load the photo
*/
function photoSwitch(action) {

	if(locked===true)
		return false;
	
	//Put the photo lock on it so other functions dont mess with the photo
	locked = true;

	//Fadeout the old photo
	$(("#photo"+currentPhoto)).fadeOut(900, function() {
		
		//Make sure all the displays are set to none
		hideAll();	

		//Determine which action needs to be taken
		switch(action) {
			
			//One backward
			case 'backward':
				currentPhoto--;
				break;
			
			//One forward
			case 'forward':
				currentPhoto++;
				break;
			
			//Keep the photo specified in action
			default:				
				currentPhoto = action;
				break;

		}
		
		//Check if the currentPhoto is inside the photo array
		if(currentPhoto>totalPhotos) 	currentPhoto = 1;
		if(currentPhoto<1) 				currentPhoto = totalPhotos;	
		resizePhoto(currentPhoto);
		
		//Checks if the photo is loaded else the function checkPhotoLoad takes care of from this point on
		if(checkPhotoLoaded(currentPhoto)===false) {	
			prioriticyLoadingPhotos(currentPhoto);			
			waitLoadingPhoto(currentPhoto);
			return false;
		}
		
		//Load the currentPhoto
		$(("#photo"+currentPhoto)).fadeIn(900);	

		//Remove the lock
		locked = false;	

		//Set the photo status tekst
		photoDisplayStatus();
		return true;

	});
}


/**
@description				waits for the photo to be loaded into the users cache and then displays it
							shows a loading image while waiting
@param integer photo		the key of the photo in the photos array
*/
function waitLoadingPhoto(photo) {
	
	photoDisplayStatus();
	if(checkPhotoLoaded(currentPhoto)===false) {

		if(timeoutPhotoLoad===false) {
			$(("#photoLoad")).fadeIn(900);
			loadPhoto('userDefined');
		} else	
			clearTimeout(timeoutPhotoLoad);		
		timeoutPhotoLoad = setTimeout("waitLoadingPhoto("+photo+")",1000);		
		return false;

	}	
	timeoutPhotoLoad = false;
	resizePhoto(photo);

	$(("#photoLoad")).fadeOut(900, function() {
		$(("#photo"+photo)).fadeIn(900);
		locked = false;		
	});
}


/**
@description			loads all the photos into the  loadedPhotosSequence array when the photo
						is not yet in the loadedPhotos array
@note					after filling the array it will start loading the photos with the function loadPhoto
*/
function loadPhotos() {

	for(var i=0; i<totalPhotos; i++) { 
		if(searchArray(loadedPhotos, (i+1))===false
		&& searchArray(loadedPhotosSequence, (i+1))===false)
			loadedPhotosSequence[i] = (i+1);
	}
	loadPhoto('system');

}


/**
@description				search in the array for the value and will return the key of 
							the first match
@param array array			the array that should be searched for the value
@param string value			the value that needs to be found
@return boolean, integer	false when the value was not found, the key when it was
*/
function searchArray(array, value) {
	
	for(var i in array) {
		if(array[i]==value)		return i;
	}
	return false;
}


/**
@description			prioriticy a photo in the loadedPhotos array, which will be loaded then as
						the first one in the line. 
@param integer photo	the key of the photo in the photos array
@note					replace the global array loadedPhotosSequence with the new created sequence
*/
function prioriticyLoadingPhotos(photo) {

	var counter = 0;
	prioriticyPhotos = new Array();
	prioriticyPhotos[counter] = photo;
	counter++;

   //Load the images after
   if((photo+1)>totalPhotos) {
	   photo = 1;
	   prioriticyPhotos[counter] = photo;
	   counter++;
   } 

	//Adds all the photos after the current selected photo as prioriticied photo
	for(var i=(photo+1); i<=totalPhotos; i++) {
		prioriticyPhotos[counter] = i;
		counter++;
	}
	
	
	//Add the prioriticied photos to the prioriticyPhotos array
	var counter = 0;
	var sortedArray = new Array();
	for(var i in prioriticyPhotos){
		if(checkPhotoLoaded(prioriticyPhotos[i])===false
		&& checkPhotoLoad(prioriticyPhotos[i])===false) {
			sortedArray[counter] = prioriticyPhotos[i];
			counter++;
		}
	} 

	//Add all the other photos that are still in the loadedPhotosSequence
	for(var i=1; i<=totalPhotos; i++) { 
		if(searchArray(prioriticyPhotos, i)===false 
		&& checkPhotoLoaded(i)===false
		&& checkPhotoLoad(prioriticyPhotos[i])===false) {
			sortedArray[counter] = i;
			counter++;
		}
	} 


	//Overwrite the global array
	loadedPhotosSequence = sortedArray;

}


/**
@description				loads the next photo in the loadedPhotosSequence array
@param string reference		'system'		will reload this function till all the photos are loaded
							'userDefined'	will load the first photo in line and stops then
*/
function loadPhoto(reference) {

	if(loadedPhotosSequence.length>0) {

		var photo = loadedPhotosSequence[0];

		//Make sure the photo isn't loaded yet, otherwise remove it
		//and get the following one
		while(checkPhotoLoaded(photo)===true && checkPhotoLoad(photo)===true) {

			//Removed the photo from the loadedPhotosSequence
			loadedPhotosSequence.splice(0, 1);
			if(loadedPhotosSequence.length==0)
				return false;

			var photo = loadedPhotosSequence[0];

		}
		
		//Removed the photo from the loadedPhotosSequence
		loadedPhotosSequence.splice(0, 1);
		
		//Add the photo to the loadPhoto array
		loadingPhotos[loadingPhotos.length] = photo;

		//Add the img element with the photo to the layer #photoDisplay
		$('#photoDisplay').append('<img src="' + photos[photo].filename + '"'
								  + ' id="photo'+ photo +'" alt="" border="0" class="displayNone photoDisplay">');
		$('#photo'+ photo).attr('src', photos[photo].filename).load(function() {
			
			//Remove from loadPhoto array
			var key = searchArray(loadingPhotos, photo);
			if(key!==false) 
				loadingPhotos.splice(key, 1);

				
			//Add to loaded photo to the loadedPhotos array
			loadedPhotos[loadedPhotos.length] = photo;
			
			//photo is loaded and the system made the call, load an other photo
			if(reference=='system')		loadPhoto('system'); 	
			
		});
	} 
}


/**
@description					overwrites some of the standard setting of the jqyery BlockUI plugin
*/
function buildBlockUI() {
	
	setPhotoDisplayWidth();

	$.blockUI({ 
		message: $('div#photoDisplayBox'), 
	    css: { 
		   top:  '4px', 
	       left: ($(window).width() - photoDisplayWidth) /2 + 'px', 
		   width: photoDisplayWidth + 'px', 
	       cursor: 'default',
		   border: '1px solid #FFF',
		   backgroundColor: '#480001'
		},
	    overlayCSS:  { 
		    cursor: 'default',
	        backgroundColor: '#000',
			opacity: 0.8
		} 
	}); 
	
	//Setting the removeBlockUI() function when clicked on the overlay
	$('.blockOverlay').click(removeBlockUI); 

   $("#photoDisplay").width(photoDisplayWidth);

}


/**
@description				recalculates the position of the photo and adjust it so it horizontale aligned
*/
function resetPositionBlockUI() {

	setPhotoDisplayWidth();

	$("div.blockMsg").css("left", ($(window).width() - photoDisplayWidth) /2 + 'px');
	$("div.blockMsg").width(photoDisplayWidth);
	$("#photoDisplay").width((photoDisplayWidth-2));

}


function setPhotoDisplayWidth() {
	
	var maxWidth = $(window).width() - 50;
	
	var maxWidthPhotos = 0;
	for(var i=1; i<=totalPhotos; i++) {
		if(maxWidthPhotos<photos[i].width)
			maxWidthPhotos = photos[i].width;
	}

	if(maxWidthPhotos<maxWidth)
		photoDisplayWidth = maxWidthPhotos;
	else	photoDisplayWidth = maxWidth;

}


/**
@description			removes the blockUI overlays and return the website in normal mode
*/
function removeBlockUI() {

	slideShow = false;
	$("#slideShow").html('Start slideshow');
	$.unblockUI();

}


/**
@description				show which photo the current one is out of the totalPhotos
*/
function photoDisplayStatus() {
	
	if($('#photoDisplayStatus').length>0)
		$('#photoDisplayStatus').html('photo '+currentPhoto+' of '+totalPhotos);

}


/**
@description			check if a photo is already loaded or not
@param integer photo	the key of the photo in the photos array
@return boolean			true when the photo is loaded, false on not
*/
function checkPhotoLoaded(photo) {

	if(searchArray(loadedPhotos, photo)===false)
		return false;
	return true;

}


/**
@description			check if a photo is already loaded or not
@param integer photo	the key of the photo in the photos array
@return boolean			true when the photo is loaded, false on not
*/
function checkPhotoLoad(photo) {

	if(searchArray(loadingPhotos, photo)===false)
		return false;
	return true;

}


/**
@description			controls the slideshow if it should stop or play. 
						determines the action based on the current status
						when it's stop it plays and visa versa
*/
function controlSlideShow() {
	
	if(slideshowTimeout!==false)
		clearTimeout(slideshowTimeout);

	if(slideShow===true) {
		photoSwitch('forward');
		var slideshowTimeout = setTimeout('controlSlideShow();', 5000); 
	} 
}


/**
@description			calculates the new photo size so it fits the screen mainting the ratio and
						resize the current image with the width and height attributes of the img tags
@param integer photo	the key of the photo in the photos array
*/
function resizePhoto(photo) {
	
	var maxHeight = $(window).height() - 50;
	var photoWidth = photos[photo].width;
    var photoHeight = photos[photo].height;   

    if(photoDisplayWidth<photoWidth) {	 
		var heightForEachPixel = photoHeight/photoWidth;
		var photoHeight = photoDisplayWidth * heightForEachPixel;
		var photoWidth = photoDisplayWidth;	 	
    }	

	if(maxHeight<photoHeight) {		 
		var widthForEachPixel = photoWidth/photoHeight;
		var photoWidth = maxHeight * widthForEachPixel;
		var photoHeight = maxHeight;	 	
    }
	photoHeight = Math.floor(photoHeight);
    photoWidth = Math.floor(photoWidth);
	

	$('#photo'+photo).css("height", photoHeight + 'px');   		
    $('#photo'+photo).css("width", photoWidth + 'px'); 

}


/**
@description			the functions that should be executed after the loading of the page is done
*/
$(document).ready(function() { 
	
	//When the backward and forward button when a photo is clicked
	if($("#backward").length>0) {
		$("#backward").click(function () {
			photoSwitch('backward');
			return false;
	    });
	}

	if($("#forward").length>0) {
	    $("#forward").click(function () {
			photoSwitch('forward');
			return false;
	    });
	}

	//When the slideshow link is clicked
    $("#slideShow").click(function () {
		if(slideShow===true) {
			slideShow = false;
			$("#slideShow").html('Start slideshow');
		} else {
			slideShow = true;
			$("#slideShow").html('Stop slideshow');
		}
		var slideshowTimeout = setTimeout('controlSlideShow();', 2000); 
		return false;  
    });

	
	//When the window gets resize it will use this
	$(window).resize(function(){
		resetPositionBlockUI();
		resizePhoto(currentPhoto);
	});
	
	//Insert the loadingImage
	$('#photoDisplay').append('<img src="' + loadingImage + '" id="photoLoad" alt="" border="0" class="displayNone photoDisplay loadingImage">');

	loadPhotos();

});
