

$(document).ready(function(){
  var images = $(".slideshow img");
  images.parent().addClass("loading");
  images.hide();
  images.imagesLoaded(function() {
		slideShow($(this),8000);
  },true);
});




function slideShow(obj,speed) {
	if (!obj.length) return;
	if (obj.length <= 1) return;
	var array = [];
	var auto = true;
	var direction = "forward";
	var fn = {
		loop: function() {
			if (!auto) return;
			fn.blend();
			setTimeout(fn.loop, speed );
		},
		blend: function() {
			var current = obj.filter(".current").fadeOut(2000).removeClass("current");
			if (direction == "forward") current = (current.next().length) ? current.next() : obj.first();
			if (direction == "back") current = (current.prev().length) ? current.prev() : obj.last();
			current.fadeIn(2000).addClass("current");
		},
		getLargest: function(array){ 
			return Math.max.apply( Math, array ); 
		}
	}
	obj.hide();
	obj.each(function() {
		array.push($(this).height());
	});
	obj.parent().animate({height:fn.getLargest(array)},"slow");		
	obj.parent().removeClass("loading");
	obj.first().fadeIn("slow",function() {
		setTimeout(fn.loop, speed );
	}).addClass("current");

	
	$(".controls a.start-stop").click(function(e) {
		e.preventDefault();
		obj.stop(true,true);
		auto = auto ? false : true;
		direction = "forward";
		if (auto) {
			fn.loop();
			$(this).html("Stop");
		}
		else {
			$(this).html("Play");
		}
	});

	$(".controls a.forward").click(function(e) {
		e.preventDefault();
		obj.stop(true,true);
		auto = false;
		direction = "forward";
		$(this).parent().find("a.start-stop").html("Play");
		fn.blend();
	});

	$(".controls a.back").click(function(e) {
		e.preventDefault();
		obj.stop(true,true);
		auto = false;
		direction = "back";
		$(this).parent().find("a.start-stop").html("Play");
		fn.blend();
	});


}










