

var slideshow = {
	
	auto: true,
	direction:"forward",

	init: function(settings) {

		slideshow.config = {
			$images: $(".slideshow img"),
			interval: 3000
		}
		$.extend( slideshow.config, settings );	

		if (slideshow.getImages().length <= 1) return;

		slideshow.getImages().parent().addClass("loading");
		slideshow.getImages().hide();
	
		slideshow.getImages().imagesLoaded(function() {
			slideshow.start();
		});
	},

	getImages: function() {
		return slideshow.config.$images;
	},

	loop: function() {
		if (!slideshow.auto) return;
		slideshow.blend();
		setTimeout(slideshow.loop, slideshow.config.interval );
	},
	blend: function() {
		var current = slideshow.getImages().filter(".current")
			.fadeOut("slow")
			.removeClass("current");
			if (slideshow.direction == "forward") {
				current = (current.next().length) ? current.next() : slideshow.getImages().first();
			}
			if (slideshow.direction == "back") {
				current = (current.prev().length) ? current.prev() : slideshow.getImages().last();
			}

		current.fadeIn("slow").addClass("current");
	},
	getLargest: function(array) {
		return Math.max.apply( Math, array );
	},
	

	start: function() {
		var array = [];
		slideshow.getImages().hide();
		slideshow.getImages().each(function() {
			array.push($(this).height());
		});
		slideshow.getImages().parent().animate({height:slideshow.getLargest(array)},"fast");
		slideshow.getImages().parent().removeClass("loading");
		slideshow.getImages().first().fadeIn("slow",function() {
			setTimeout(slideshow.loop,slideshow.config.interval);
		}).addClass("current");
	
		$(".controls a.start-stop").click(function(e) {
			e.preventDefault();
			slideshow.getImages().stop(true,true);
			slideshow.auto = slideshow.auto ? false : true;
			slideshow.direction = "forward";
			if (slideshow.auto) {slideshow.loop(); $(this).html("Stop"); }
			else { $(this).html("Play"); }
		});
	
		$(".controls a.forward").click(function(e) {
			e.preventDefault();
			slideshow.getImages().stop(true,true);
			slideshow.auto = false;
			slideshow.direction = "forward";
			$(this).parent().find("a.start-stop").html("Play");
			slideshow.blend();
		});
	
		$(".controls a.back").click(function(e) {
			e.preventDefault();
			slideshow.getImages().stop(true,true);
			slideshow.auto = false;
			slideshow.direction = "back";
			$(this).parent().find("a.start-stop").html("Play");
			slideshow.blend();
		});
	}

}
	


$(document).ready(function() {
	slideshow.init({ 
		$images: $(".slideshow img"),
		interval: 4000
	});
});