﻿var g_thumbs = new Array();
var g_photos = new Array();

$.fn.doSlideShow = function(settings) {
	var options = jQuery.extend({
			thumbnailSelector: ".thumbs",
			slideshowSelector: ".picframe",
			captionSelector: ".captions",
			maxHeight: 480,
			maxWidth: 640,
			timeBetween: 8000
		}, settings);
		
	var resizeAndCenter = function(loadedImg)
	{
		var w = loadedImg.width();
		var h = loadedImg.height();
		
		if (w > options.maxWidth || h > options.maxHeight)
		{
			var wR = w / options.maxWidth;
			var wH = h / options.maxHeight;
			
			if (wR > wH)
			{
				loadedImg.width(w / wR);
				loadedImg.height(h / wR);
			}
			else
			{
				loadedImg.width(w / wH);
				loadedImg.height(h / wH);
			}
			
			w = loadedImg.width();
			h = loadedImg.height();
		}
		
		var top = (options.maxHeight - h) / 2;
		var left = (options.maxWidth - w) / 2;
		loadedImg.css("position", "relative");
		loadedImg.css("top", top);
		loadedImg.css("left", left);
	}
	
	var onloaded = function()
	{
	}
	
	var loadImage = function(ssIdx, photoIdx, img)
	{
		if (g_photos[ssIdx][photoIdx] == null)
		{
			var toLoad = new Image();
			
			$(toLoad).load(function() {
					var theImg = $(toLoad);
					theImg.hide();
					g_photos[ssIdx][photoIdx] = toLoad;
					//alert(toLoad.outerHTML);
					$(options.slideshowSelector).empty().append(toLoad);
					resizeAndCenter(theImg);
					//debugger;
					theImg.fadeIn(1000);
					$(options.captionSelector).text(img.attr("title"));
					
					window.setTimeout(
						function() {
							if (photoIdx == g_thumbs[ssIdx].length - 1)
								photoIdx = -1;
							photoIdx++;
							
							loadImage(ssIdx, photoIdx, g_thumbs[ssIdx][photoIdx])
						}, options.timeBetween);
				})
				.error(function() {
					if (photoIdx == g_thumbs[ssIdx].length - 1)
						photoIdx = -1;
					photoIdx++;
					
					window.setTimeout(function() {loadImage(ssIdx, photoIdx, g_thumbs[ssIdx][photoIdx]);}, 1);
				})
				.attr("src", img.attr("href"));
		}
		else
		{
			var temp = $(g_photos[ssIdx][photoIdx]);
			$(options.slideshowSelector).empty().append(temp);
			temp.hide().fadeIn(1000);
			
			$(options.captionSelector).text(img.attr("title"));
			
			window.setTimeout(
				function() {
					if (photoIdx == g_thumbs[ssIdx].length - 1)
						photoIdx = -1;
					photoIdx++;
					
					loadImage(ssIdx, photoIdx, g_thumbs[ssIdx][photoIdx])
				}, options.timeBetween);	
		}
	}
	
	return this.each(function() {
		var i = g_photos.length;
		g_photos[i] = new Array();
		g_thumbs[i] = new Array();
		var jObj = this;
		
		$(this).find("li a").each(function(idx) {
			g_photos[i][idx] = null;
			g_thumbs[i][idx] = $(this);
			
		}).appendTo(options.thumbnailSelector);
		
		window.setTimeout(function() { loadImage(0, 0, g_thumbs[0][0]) }, 1);
	});
};

