//on page load set up the Popup Layer Pic links
$(document).ready(function(){
	//hide our debug mode immediately if we aren't debugging anything
	if ( !bDebugMode ) {
		$("#debugmode")[0].hide;
	}

	//show our first image div as it was previously hidden
	$("#mainimage > div:first").show();

	CheckImages(1);

});

var iNextImage = 1;
var bDebugMode = false;
var bAllComplete = false;

function WriteDebug (sMessage) {
	if ( bDebugMode ) {
		$("#debugmode")[0].innerHTML = $("#debugmode")[0].innerHTML + sMessage + "<br />";
	}
}

function CheckImages() {
	WriteDebug('CheckImages :: ' + iNextImage);

	//check to see if we have an image in the dom
	if ( $("#mainimage > div:eq(" + iNextImage + ") > img")[0] ) {
		//check to see if the next image to fade to has fully downloaded or not
		if ( $("#mainimage > div:eq(" + iNextImage + ") > img")[0].complete || bAllComplete ) {
			//check to see if all of our images have been loaded
			if ( iNextImage == $("#mainimage > div").length ) {
				bAllComplete = true;
			}

			WriteDebug('CheckImages :: ' + iNextImage + ' is complete. Fading');
			WaitForFadeImages(iNextImage);
		}
		else {
			WriteDebug('CheckImages :: ' + iNextImage + ' is not complete. Waiting');

			setTimeout('CheckImages()',500);
		}
	}
}

//wait between fading images
function WaitForFadeImages ( iImageNum ) {
	WriteDebug('WaitForFadeImages. Waiting 2000...');
	setTimeout("FadeImages (" + iImageNum + ");",2000);
}

//fade the images
function FadeImages ( iImageNum ) {
	WriteDebug('FadeImages....');
	var iNumImages = $("#mainimage > div").length-1;

	//check to see if we are meant to be fading the first image
	if ( iImageNum == 0 ) {
		//hide the previous images that we have shown except for the last one
		for (var i=1;i<iNumImages;i++){
			$("#mainimage > div:eq(" + i + ")").hide();
		}

		//set the next image that we should fade in
		iNextImage = iImageNum+1;

		//fade out the last one, leaving behind the first one as the rest are hidden
		$("#mainimage > div:last").fadeOut(3000,function() {CheckImages();});
	}
	else {
		//set the next image that we should fade in
		iNextImage = iImageNum+1;

		//check to see if our current image is our last one
		if ( iNextImage == iNumImages+1 ) {
			iNextImage = 0;
		}

		//fade in the next image over the top of the current one
		$("#mainimage > div:eq(" + iImageNum + ")").fadeIn(3000,function() {CheckImages();});
	}
}
