//Time to fix retarded, broken Internet Explorer.
if(!Array.indexOf)
{
    Array.prototype.indexOf = function(obj){
        for(var i=0; i<this.length; i++){
            if(this[i]==obj){
                return i;
            }
        }
        return -1;
    }
}

(function()
{
	$.fn.simpleSlideshow = function(options)
	{		
		var parent = $(this);
		var slideOrder = new Array();
		var slideOrderCaptions = new Array();
		var orderIndexes = new Array();
				
		parent.setWorking("Loading Slides");		
		
		//Any of these options can be sent in via the options parameter of the constructor - leaving blank will default to these below.
		//NOTE: ajaxSource can be overridden here to get custom slides, and if it is NOT, you MUST pass a showcaseID in the options or it will error out below.
		var defOptions = {
			showcaseID: 0, //This must be defined in the options parameter if using the default ajaxSource!
			ajaxSource: "includes/js/jquery/proteus/getSlides.php?scID=" + options.showcaseID,
			showCaptions: false,
			slideDelay: 5000,
			slidesElement: 'div.slide',
			slidesHeightOverride: 0, //Set this to a px value to override getting the actual image height (good for when you aren't sure if all images will have the same height)
			slidesOrder: 'randomFixed',
			slideCallback: null
		};		
		
		//slidesOrder can be one of the following:
		// random - all random, evaluated on each pass
		// ordered - slides run in the order returned (ordered by position index for showcases)
		// randomFixed - default; randomized once, then run in the same order
		
		if (!options.showcaseID && !options.ajaxSource)
		{
			alert("Error, no showcase defined - must use alternate 'ajaxSource' option if not providing a showcase ID!");
			return;
		}
		
		//Merge the default options with the options sent in the constructor
		options = $.extend(defOptions, options);				
		
		//Call the specified 'getter' to fill in the slides and captions
		$.ajax({
			url: options.ajaxSource,
			cache: false,
			dataType: 'json',
			success: function(output)
			{
				//Error / sanity checking
				if (output.error)
				{
					$(body).append(output.error);
					return;
				}
				
				//Store the slides and captions in this element (So we can have multiple slide shows on one page...)
				parent.data("slides", output.files);
				parent.data("captions", output.captions);				
				
				//Cache all the slides (making sure subsequent slides load immediately!)
				for(var i = 0; i < output.files.length; i++)
				{
					//Loop through all the images and CACHE it so it's quickly displayed when the image swap routine runs.
					var img = new Image();
					img.src = output.files[i];	
				}
				
				//Can call this here before defining it because the .ajax call is asynchronous (the code keeps running, this function 'success' is only called
				//after the .ajax call has completed).
				swapFunc();
			}
		});		
		
		//Define the function used for swapping out the slides
		var swapFunc = function()
		{
			var slides = parent.data("slides");
			var captions = parent.data("captions");			
			
			var idx;
			
			switch(options.slidesOrder)
			{
				case "random":
					idx = Math.floor(Math.random() * slides.length);					
					break;
				case "ordered":
					curIdx = parseInt(parent.data("currentSlide"));
					if (isNaN(curIdx)) curIdx = -1;
					
					//Reset the pointer to 0, or the next index in the array
					idx = (curIdx + 1 > (slides.length-1) ? 0 : curIdx + 1);
					
					//Set the current slide
					parent.data("currentSlide", idx);
					break;
				case "randomFixed":
					if (slideOrder.length == slides.length)
					{
						//No more randomizing - now grab them in order stored!
						curIdx = parseInt(parent.data("currentSlide"));				
						if (isNaN(curIdx)) curIdx = -1;
						
						//Reset the pointer to 0, or the next index in the array
						idx = (curIdx + 1 > (slideOrder.length-1) ? 0 : curIdx + 1);
						
						//Set the current slide
						parent.data("currentSlide", idx);
						
						//Set the array to the internally randomized array
						slides = slideOrder;
						captions = slideOrderCaptions;
					}
					else
					{
						//Build the slideOrder array as they are randomized						
						do
						{
							idx = Math.floor(Math.random() * slides.length);
						} while(orderIndexes.indexOf(idx) != -1);
						
						orderIndexes[orderIndexes.length] = idx;
						slideOrder[slideOrder.length] = slides[idx];
						slideOrderCaptions[slideOrderCaptions.length] = captions[idx];
					}
					break;
			}
			
			$(options.slidesElement).addClass('cycled').css({				
				zIndex: 1
			});			
			
			var cap = parent.find("span");
			var slideHeight;			
			
			//Set the load function first for mother-effing IE			
			var img = new Image();
			
			$(img).load(function()
			{
				parent.clearWorking();
				
				slideHeight = this.height;
			
				//Create the element and add essential styles
				var elem = $("<div></div>").css({
					position: 'absolute',			
					width: '100%',
					backgroundRepeat: 'no-repeat',
					overflow: 'visible',			
					zIndex: 5,
					height: (options.slideHeightOverride ? options.slideHeightOverride : slideHeight)
				});		
				
				elem.addClass('slide').css({
					display: "none",
					backgroundImage: "url('" + slides[idx] + "')"			
				}).prependTo(parent).fadeIn('slow', function() 
				{ 			
					$("div.cycled").remove();				
					setTimeout(swapFunc, options.slideDelay);
				});				
				
				if (options.showCaptions)
				{
					//append the caption element if it doesn't exist, and then refresh the 'cap' variable
					if (options.showCaptions && cap.get(0) == undefined)
					{				
						cap = $(parent.append("<span data-slideindex=" + idx + "></span>").find("span").css("display", "block").get(0));
					}
					if (captions[idx] != '') 
					{
						cap.fadeTo('fast', .1, function(){
							cap.html(captions[idx]);
							cap.fadeTo('fast', 1);				
						});
						
					}
					else
					{
						cap.hide();	
					}
				}
				
				if (options.slideCallback) options.slideCallback(idx, elem, slides[idx]);
				
			}).error(function()
			{
				alert("We're sorry, but the slide '" + + "' could not be loaded. Stopping slideshow.");
			});			
			
			//Cache the image and get the actual height of the slide so we can set it
			img.src = slides[idx];
		}		
	}
})();
