$(document).ready(function() {	
	
	//fading effects on next button				
	$(".slideshowbutton").hover(function(){
		 $(this).fadeTo(300, 0.25);
		 },function(){
		 $(this).fadeTo(300, 0.70);
	}).fadeTo(300, 0.70);
	
	//next
	$(".ffwd").click(function(){
		next();
	});
	
	//prev
	$(".fbwd").click(function(){
		prev();
	});
	
	//stop/play
	$(".toggleplay").click(function(){
		stopped ? start(0) : stop();
	});
	
	//fancy on demand loading of pictures
	$(".slideshowimage").load(function() {if($(this).attr("src").indexOf("1x1spacer.gif") == -1) doFade();});
	
	image = $(".slideshowactive");
	image = image.prev();
	if(!image.html()) {
		image = $(".slideshowimages:last");
	}
	start(0);
});

var fadeintime = 1000;
var waittime = 7000;
var timer;
var image;
var imageprev = false;
var stopped = false;
var forward = true;

function slideshow() {
	if(forward) {
		image = image.next();
		if(!image.html()) {
			imageprev = $(".slideshowimages:last");
			image = $(".slideshowimages:first");
		} else {
			imageprev = image.prev();
		}
	} else {
		image = image.prev();
		if(!image.html()) {
			imageprev = $(".slideshowimages:first");
			image = $(".slideshowimages:last");
		} else {
			imageprev = image.next();
		}
	}

	if(image.find("img").attr("src") == image.find("input").attr("value")) {
		doFade();
	} else {
		image.find("img").attr("src", image.find("input").attr("value"));
	}
}

function doFade() {
	$(".slideshowimages").hide(0);
	if(imageprev.html() && imageprev.html() != image.html()) {
		$(".outerselector").show();
	}
	image.show();
	image.find("img").hide().fadeIn(fadeintime);
	
	
	if(!stopped && imageprev.html() && imageprev.html() != image.html())
		start(waittime);
}

function next() {
	stop();
	forward = true;
	slideshow();
}

function prev() {
	stop();
	forward = false;
	slideshow();
}

function start(waittime) {
	$(".toggleplay").html("[]");
	forward = true;
	stopped = false;
	
	timer = window.setTimeout(slideshow, waittime);
}

function stop() {
	$(".toggleplay").html("&gt;");
	window.clearTimeout(timer);
	stopped = true;
}