var imageList = new Array();

jQuery.preloadImages = function()
{
	for(var i = 0; i<arguments.length; i++)
	{
		jQuery("<img>").attr("src", arguments[i]);
		imageList[i] = arguments[i];
	}
}

function showImage(src)
{
	if(!$('#loader div.loading').length)
	{
		clearTimeout( cycleTimerId );
		$("#loader div ").addClass("loading");
	
		$("#loader div img").fadeOut("normal").remove();
	
		var largeImage = new Image();
		$(largeImage).load(function()
		{
			$(this).hide();
			$("#loader div").append(this);
		
			var width = $(this).width();
			var height = $(this).height();
			
			var ratio = (height / width );
			
			if(width > height)
			{
				var new_width = 500;
				var new_height = (new_width * ratio);
				var left_margin = 5;
			}
			else
			{
				var new_height = 500;
				var new_width = (new_height / ratio);
				var left_margin = (580 - new_width) / 2;
			}

			//Shrink the image and add link to full-sized image
			$(this).height(new_height).width(new_width);
	
			$(this).css( 'border', "1px solid black");
			$(this).css( 'margin-left', left_margin + "px");
			$(this).fadeIn("slow");
			$("#loader div").removeClass("loading");
		});    
		$(largeImage).attr("src", src);                                                                               
	}
}

var cycleTimerId = 0;
var imageIndex = 1;

function cycleImage()
{
	if(!$('#loader div.loading').length)
	{
		showImage(imageList[imageIndex++]);
		if(imageIndex >= imageList.length)
		{
			imageIndex = 0;
		}
		cycleTimerId = setTimeout( "cycleImage()", 8000 );
	}
}

function advanceImage(dir)
{
	clearTimeout( cycleTimerId );
	$("#loader div").removeClass("loading");

	imageIndex += dir;

	if(imageIndex < 0)
		imageIndex = imageList.length - 1;
	
	if(imageIndex >= imageList.length)
		imageIndex = 0;
	
	showImage(imageList[imageIndex]);
	return false;
}

$(document).ready( cycleTimerId = setTimeout( "cycleImage()", 8000 ) );
