/*
 * 	Slider - jQuery plugin
 *	written by David Brown
 *
 *	Copyright (c) 2009 David Brown (http://builtforpeople.com)
 *
 *	Built for jQuery
 *	http://jquery.com
 *
 */
(function($) {

jQuery.fn.slider = function slider(images,options) 
{
	if (images.length == 1) return;
	el = this;
	var options = $.extend({},{
		showControls:true,
		slideShow:false,
		slideShowInterval:5000,
		animateSpeed:'slow',
		animateEase:'swing',
		url:false
	},options);
	
	var timeout = false;
	
	var currentImg = 0;
	
	//preload images that aren't currently showing in the static html
	var staticImg = $('img', el).attr('src');
	$(images).each( function(i,im) {
		if (im == staticImg)
		{
			currentImg = i;
		}
		else
		{
			$("<img>").attr("src", im);
		}
	});
	
	function nextSlide(dir) {
		
		var img = $("img[src$='"+ images[currentImg] + "']",el);
		
		if (!dir) dir = -1;
		currentImg++;
		if ( currentImg == images.length )
		{
			currentImg = 0;
		}

		var newImg = $('<img>')
			.css({
				position:'absolute',
				left : -1 * dir * img.width(),
				top : 0
			}).load(function(event) {
				$(event.target).animate({left:0}, options.animateSpeed,options.animateEase);
				img.animate({left:dir * img.width()}, options.animateSpeed,options.animateEase, function() {
					$(this).remove();
				});
			});
			
		img.after(
			newImg
		).css({
			position : 'absolute',
			top:0,
			left:0
		});
		// set the src right at the end to fix IE onload
		newImg.attr('src',images[currentImg]);
	}
	
	function timedNextSlide () {
		clearTimeout(timeout);
		timeout = setTimeout(function() { nextSlide();timedNextSlide();},options.slideShowInterval);
	}
	
	if (options.slideShow)
	{
		timedNextSlide();
	}
	
	if (options.showControls) {
		$('img',el)
		.before(
			$('<a id="leftarrow" href="#"><span>Previous</span></a>').click(function(event) {
				nextSlide(1);
				event.preventDefault();
			})
		)
		.before(
			$('<a id="rightarrow" href="#"><span>Next</span></a>').click(function(event) {
				nextSlide(0);
				event.preventDefault();
			})
		);
	}
}

})(jQuery);