/**
 * Quick 'n' easy jQuery slideshow
 * Based on (but somewhat simpler than) 
 * - jquery.innerfade.js by Torsten Baldes http://medienfreunde.com
 * - based on work of Matt Oakes http://portfolio.gizone.co.uk/applications/slideshow/
 * - based on work of Ralf S. Engelschall http://trainofthoughts.org/
 */
(function($) {
	$.fn.slideshow = function(options) 
	{
		return this.each(function()
		{ 
			$(this).data('slideshow', new Slideshow(this, options));
		});
	};
	$.fn.slideshow_change_item = function(new_item)
	{
		return this.each(function()
		{ 
			if ( typeof $(this).data('slideshow') == 'object' )
			{
				$(this).data('slideshow').change_item(new_item);
			}
		});
	}

	function Slideshow(container, options)
	{
		// Default settings
		var settings = {
			animation_speed:	'normal',
			timeout:		2000,
			child_selector:		'*',
			random_start:		false,
			on_change_callback:	function(old_item_index, new_item_index) {}
		};
		
		// Over-ride in-place
		if (options)
		{
			$.extend(settings, options);
		}
		
		// Force height of container, because it's children are about to disappear from flow
		$(container).css(
			'height',
			$(container).height()
		);
		
		var $elements = $(container).children(settings.child_selector);
		$elements
			.css('display', 'block')
			.css('position', 'absolute')
			.hide();
		
		if ( settings.random_start )
		{
			var current_item = Math.floor ( Math.random () * ( $elements.length ) );
		}
		else
		{
			var current_item = 0;
		}
		
		var timer = setTimeout(next_item, settings.timeout);
		
		// We don't want to animate the first "change", but we do want to trigger a callback
		$elements.eq(current_item).show();
		settings.on_change_callback(current_item);
		
		function next_item()
		{
			change_item((current_item + 1) % $elements.length);
		}
		
		function change_item(new_item)
		{
			$elements.eq(current_item)
				.fadeOut(settings.animation_speed);
			
			current_item = new_item;	
				
			$elements.eq(current_item)
				.fadeIn(settings.animation_speed);
				
			settings.on_change_callback(current_item);	
			
			// Reset the timer, whether or not it was what called us
			clearTimeout(timer);
			timer = setTimeout(next_item, settings.timeout);
		}
		
		// Export some functions to the outside world
		this.next_item = next_item;
		this.change_item = change_item;
	}
})(jQuery);

