jQuery(function()
{ 
	image      = null;
	viewerImg  = null;
	thumbs     = null;
	thumbsList = null;
	current    = null;
	timerId    = null;

	$(document).ready(function()
	{
		viewerImg  = $(".view");
		thumbs     = $(".thumbs").find("a");
		thumbsList = $(".thumbs");

		screenSetup();
		show(thumbs.eq(0));
		thumbs.click(function(event)
		{
			clearInterval(timerId);
			event.preventDefault();
			show($(this));
			goTimer();
		});
		viewerImg.noContext();
	
		goTimer();
	});
	
	$(window).resize(function()
	{
		screenSetup();
		resize();
	});
	
	function goTimer()
	{
		timerId = setInterval(function()
		{
			next();
		}, 5000);
	}
	
	function next()
	{
		for(i = 0; i < thumbs.length; ++i)
		{
			if (thumbs.eq(i).attr("href") == current.attr("href"))
			{
				new_i = i + 1;
				if (new_i == thumbs.length) new_i = 0;

				show(thumbs.eq(new_i));
				return;
			}
		}
	}

	function show(thumbElt)
	{
		current  = thumbElt;
		imageRef = thumbElt.attr("href");

		thumbs  .find("img").removeClass("active");
		thumbElt.find("img").addClass("active");
		
		// need to load the image in an independent object
		// so that we can query the "pure" image size
		// indeed: the size of the viewerImg element has been forced
		// already in the css generated by prevous "resize" calls
		image = $(new Image());
		image.attr("src", imageRef)
		.load(function()
		{
			imageWidth  = image.attr("width");
			imageHeight = image.attr("height");
			imageRatio = imageWidth / imageHeight;

			// now we have the size of the "currently active" image
			// show it + resize it
			viewerImg.fadeOut("normal", function()
			{
				viewerImg.attr("src", imageRef);
				resize();
				viewerImg.fadeIn("normal");
			});
		});
	}
	
	function resize()
	{
		if (imageWidth < 50) return;

		if (imageRatio > screenRatio)
		{
			// viewerImg is wider than screen
			elementWidth  = imageWidth  * screenWidth / imageWidth;
			elementHeight = imageHeight * screenWidth / imageWidth;
		}
		else
		{
			// viewerImg is taller than screen
			elementWidth  = imageWidth  * screenHeight / imageHeight;
			elementHeight = imageHeight * screenHeight / imageHeight;
		}
		
		x = (screenWidth  - elementWidth ) / 2;
		y = (screenHeight - elementHeight) / 2;
		
		//alert("screen: " + screenWidth + "x" + screenHeight + " image: " + imageWidth + "x" + imageHeight);
		
		viewerImg.css({
			"width"    : elementWidth + "px",
			"height"   : elementHeight + "px",
		  "left"     : x + "px",
			"top"      : y + "px",
		});
	}
	
	function screenSetup()
	{
		screenWidth  = $(window).width();
		screenHeight = $(window).height();
		screenRatio  = screenWidth / screenHeight;

		thumbsWidth  = thumbsList.width();
		thumbsHeight = thumbsList.height();

		list_x = 0;
		list_y = screenHeight - thumbsHeight;
		thumbsList.css({
		  "left"     : list_x + "px",
			"top"      : list_y + "px",
		});
	}
});
