﻿$(document).ready(function(){
	var images = $(".slideshow img");
	images.parent().addClass("loading");
	images.hide();
	images.imagesLoaded(function() {
		slideShow($(this),4000);
	},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("slow").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)},"fast");
	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('<div class="con_back"><img src="img/slide_stop.gif" /></div>'); }
		else { $(this).html('<div class="con_back"><img src="img/slide_play.gif" /></div>'); }
	});
	
	$(".controls a.forward").click(function(e) {
		e.preventDefault();
		obj.stop(true,true);
		auto = false;
		direction = "forward";
		$(this).parent().find("a.start-stop").html('<div class="con_back"><img src="img/slide_play.gif" /></div>');
		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('<div class="con_back"><img src="img/slide_play.gif" /></div>');
		fn.blend();
	});
}
