﻿var imageArray = new Array(),
    currentIndex = 0,
    imageElement,
    btnNext,
    btnPrevious,
    imageCount;
function resetImage() {
	//make sure the current image is preloaded
	//set the src and longdesc(id) of the image
	preload(jQuery.makeArray(imageArray[currentIndex]), function() {
		$(imageElement).fadeOut('slow', function() {
			$('div#photoCounter').html('Photo ' + (currentIndex + 1) + ' of ' + imageCount);
			$(this)
			.attr('src', imageArray[currentIndex])
			.fadeIn('slow');
		});
	});

	//make sure the the next/previous five images are preloaded
	preload(imageArray.slice(currentIndex > 4 ? currentIndex - 5 : 0, currentIndex + 5 >= imageCount ? imageCount : currentIndex + 5), function() { return true; });
}
function preload(imagesToPreload, functionToCallWhenFinished) {
	$.preload(imagesToPreload, {
		onFinish: functionToCallWhenFinished
	});
}
$(document).ready(function() {
	//Initiate the image array and fill it with the urls stored in PhotoContainer
	imageElement = $('img#PhotoImage');
	btnNext = $('div#photoNext');
	btnPrevious = $('div#photoPrevious');

	//while iterating, return the index of the currently displayed image
	$('div#PhotoContainer input:hidden').each(function(index) {
		imageArray[imageArray.length] = $(this).attr('value');
	});

	//set the image array length
	imageCount = imageArray.length;

	//if imageArray is empty, don't do anything
	if (imageCount == 0)
		return;

	//initialize the photo counter
	$('div#photoCounter').html('Photo 1 of ' + imageCount);

	//set the click events of the next and previous links
	$(btnNext).click(function() {
		//increment the current index
		currentIndex++;

		//reset the image
		resetImage();

		//if we just reached the end of our gallery, hide this button
		if (currentIndex == imageCount - 1) {
			$(this).css('visibility', 'hidden');
		}

		//if we just made it to position '1', make sure to make the "PreviousPhotoLink" visible
		if (currentIndex == 1) {
			$(btnPrevious).css('visibility', 'visible');
		}
	});
	$(btnPrevious).click(function() {
		//decrement the current index
		currentIndex--;

		//reset the image
		resetImage();

		//if we just reached the beginning of our gallery, hide this button
		if (currentIndex == 0) {
			$(this).css('visibility', 'hidden');
		}

		//if we just made it to position '1', make sure to make the "PreviousPhotoLink" visible
		if (currentIndex == imageCount - 2) {
			$(btnNext).css('visibility', 'visible');
		}
	});

	//preload the first five images
	preload(imageArray.slice(0, 5 >= imageCount ? imageCount : 5), function() { return true; });
});