var slideDuration = 15; // number of seconds after which next slide is displayed

var numSlides;
var imageWidth;
var currentSlide = 0;
var timer;

function autoForward() {
	forward();
	timer = setTimeout("autoForward()", slideDuration * 1000);
}

function forward() {
	if (currentSlide < numSlides-1) {
		showSlide(currentSlide+1);
	} else {
		showSlide(0);
	}
}

function backward() {
	if (currentSlide > 0) {
		showSlide(currentSlide-1);
	} else {
		showSlide(numSlides-1);
	}
}

function showSlide(slideIndex, animate) {
	animate = (typeof argu == 'undefined') ? true : animate;
	if (slideIndex < numSlides) {
		leftPx = -1*slideIndex*imageWidth;
		if (Math.abs(slideIndex - currentSlide)==1 && animate) {
			$("#slides ul").animate({left: leftPx}, "fast");
		} else {
			$("#slides ul").css("left", leftPx);
		}
		currentSlide = slideIndex;
	}
}

$(document).ready(function() {
	// count the number of slides and width
	numSlides = $("#slides ul").find("li").length;
	imageWidth = $("#slides").width();
	
	// create a div for the links
	$("#slides").after("<div id=\"slides_menu\"><ul><li id=\"snapback\"><a href=\"#\" title=\"Back\">&laquo;</a></li><li id=\"snapmore\"><a href=\"#\" title=\"Next\">&raquo;</a></li></ul></div>");

	// set initial slide to a random one
	currentSlide = Math.floor(Math.random() * numSlides);
	showSlide(currentSlide, false)
	
	// assign event handlers to slide navigation buttons
	$("#snapback a").bind("click", function() {
		clearTimeout(timer);
		backward();
		return false;
	});
	
	$("#snapmore a").bind("click", function() {
		clearTimeout(timer);
		forward();
		return false;
	});

	// Start the automatic changing of slides
	timer = setTimeout("autoForward()", slideDuration * 1000);
	
});
