/*
	jq.tw-slideshow.js v0.1
	By: Todd Williams
	March 2010
	
	Example markup:
		<div id="slideshow">
			<img src="images/home_slide1.jpg" alt="The Village At Ironwood Slideshow" />
			<!-- START Slideshow Images -->
			<a href="images/home_slide2.jpg">Slide 2</a>
			<a href="images/home_slide3.jpg">Slide 3</a>
			<a href="images/home_slide4.jpg">Slide 4</a>
			<a href="images/home_slide5.jpg">Slide 5</a>
			<a href="images/home_slide6.jpg">Slide 6</a>
			<!-- END Slideshow Images -->
		</div>
		
	Example usage:
		$("#slideshow").tw-slideshow();
		// or
		$("#slideshow").tw-slideshow({interval: 4000, duration: 800});
		
	Tip:
		Hide lines inside slideshow holder with css
		#slideshow a { display: none }
*/
(function ($) {
	$.fn.tw_slideshow = function (options) {
		var slideshow, image, settings;
		slideshow = $(this);
		image = slideshow.find('img:first');
		
		settings = $.extend({
			interval: 3000, //time in between images
			duration: 1000 // time spent during transition
		}, options);
		
		// take visible image and add it to the list of links
		slideshow.find('a:first').before('<a href="' + image.attr('src') + '" class="current">Initial Image</a>');
		
		// hide links in case didn't do it with css
		slideshow.find('a').hide();
		
		// preload all of the images
		slideshow.find('a').each(function () {
			$('body').append('<img class="tw-slideshow-hidden" style="display: none" src="' + $(this).attr('href') + '" />');
		});
		
		// add a holder for the image to maintain space
		image.wrap('<div style="float: left; width: ' + image.width() + 'px; height: ' + image.height() + 'px"></div>');
		image.css({position: 'absolute'});
		
		// fade in next image
		setInterval(function () { next(slideshow, settings.interval, settings.duration); }, settings.interval);
	};
	
	function next(slideshow, interval, duration) {
		var image = slideshow.find('img:first');
		
		// keep track of what image we are showing
		slideshow.find('a.current:first').removeClass('current').next().addClass('current');
		
		// start back at begginning once we get to the end
		if(!slideshow.find('a.current').length) {
			slideshow.find('a:first').addClass('current');
		}
		
		// add new image then fade it in
		image.after('<img style="position: absolute; display: none" class="tw-slideshow-image" src="' + slideshow.find('a.current:first').attr('href') + '" />');
		slideshow.find('img:last').fadeIn(duration, function () {
			// after fading in remove all other images accept this one
			slideshow.find('img').not('img:last').remove();
		});	
	}
})(jQuery);
