(function($) {
	/**
	 * @param Array images
	 * @param Boolean should images be rotated?
	 * @param Number scale defaults to 1 (100%)
	 */
	$.fn.immobilis_slider = function( images, rotate, scale )
	{
		if (typeof(scale)==undefined) scale = 1;
		
		var texts = [];
		
		this.find("ul.texts li").each( function()
		{	
			texts.push( $(this).html() );		
		} );
		/*
		this.find("ul.images li").each( function()
		{	
			images.push( $(this).find("img").attr("src") );		
		} );
		*/
		
		// shuffle images
		// NOTE: images is a global variable
		images.sort( function() { return 0.5-Math.random(); } );
		
		this.empty();
		
		// DOM setup
		var quote = "<div id='quote'><h1></h1></div>";
		var counter = "<div id='counter'><ul></ul></div>";
		var slimage = "<div id='sliderimage'><img src='' /></div>";
		
		this.append(quote);
		this.append(counter);
		this.append(slimage);
		
		quote = $('#quote h1');
		counter = $('#counter ul');
		slimage = $('#sliderimage img');
		
		if (scale != 1)
		{
			// scale both #sliderimage and the img it contains
			var width = Math.round( 589 * scale );
			var height = Math.round( 400 * scale );
			$('#sliderimage').css('width',width+'px').css('height',height+'px');
			slimage.css('width',width+'px').css('height',height+'px');
		}
		
		// add a counter button for each text
		$.each(
			texts, 
			function( index, value )
			{
				counter.append("<li class='white' id="+index+"></li>");
			}		
		);
		
		// functions
		var activetxt = -1;
		var showNextText = function()
		{
			var next = activetxt + 1;
			if (next >= texts.length) next = 0;
			quote.hide().html(texts[next]).fadeIn(800);
			counter.find('li').removeClass("red").addClass("white");
			var number = parseInt(next) + 1;
			counter.find('li:nth-child('+number+')').removeClass("white").addClass("red");
			activetxt = next;
		};
		
		var activeimg = -1;
		var showNextImage = function()
		{
			var next = activeimg + 1;
			if (next >= images.length) next = 0;
			var src = images[next];
			
			slimage.fadeOut(800, function(){
				$(this).attr("src", src).load(function(){
					$(this).fadeIn(800);
					});				
				
			});
			
			activeimg = next;
		};
		
		// set counter click handlers
		var stopped = false;
		counter.find('li').click(function(event)
		{
			var index = $(this).attr("id");
			stopped = true;
			// TODO: bit of a dodgy workaround
			activetxt = index-1;
			showNextText();
		});
			
		setInterval( function() { if (!stopped) showNextText(); }, 4000);
		
		if (rotate) setInterval( function() { showNextImage(); }, 12000);
		
		showNextText();
		showNextImage();
	};	
})( jQuery );

$(document).ready(function() 
{
 	$('#slider').immobilis_slider( images, false, 0.95 );
});
