/* */
var slideshowTimer = null;
var animating = false;

/**
 * Show a slide
 * @param slideElem The DOM element you wish to show
 * @param afterShow Function to call after the slide has been shown
 * @returns void
 */
var showSlide = function(slideElem, afterShow) {
	if(!animating)
	{
		var toShow = $(slideElem);
		var toHide = toShow.siblings(":visible");
		animating = true;

		var i = toShow.prevAll().length;

		var toShowCaption = $(".caption", toShow);
		if(toShowCaption.length > 0)
		{
			toShowCaption.hide();
		}

		var toHideCaption = $(".caption", toHide);
		if(toHideCaption.length > 0)
		{
			toHideCaption.slideUp(300, function() {
				// hmm
				var p = $("#homepage #slideshow .pagination");
				$(".on", p).removeClass("on");
				$(":nth-child("+(i+1)+")", p).addClass("on");

				toHide.fadeOut(500);
				toShow.fadeIn(500, function() {
					$(".caption", this).slideDown(300, afterShow);
					animating = false;
				});
			});
		}
		else
		{
			var p = $("#homepage #slideshow .pagination");
			$(".on", p).removeClass("on");
			$(":nth-child("+(i+1)+")", p).addClass("on");

			toHide.fadeOut(500);
			toShow.fadeIn(500, function() {
				$(".caption", this).slideDown(300, afterShow);
				animating = false;
			});
		}
	}
};

/**
 * Advances the slideshow
 * @returns void
 */
var advanceSlide = function() {
	var toHide = $("#homepage #slideshow .slides li:visible");
	var toShow = toHide.next();
	toShow = (toShow.length != toHide.length) ? toHide.siblings().first() : toShow;

	showSlide(toShow);
};

$("#homepage #slideshow .slides li").hide().first().show();

$("#homepage #slideshow").
	append($('<ul class="pagination"></ul>').append(function() {
		var l = $("#homepage #slideshow .slides li").length;
		var r = "";
		for(i = 1; i <= l; i++)
		{
			r += "<li>"+i+"</li>";
		}
		return r;
	}));

$("#homepage #slideshow .pagination li").click(function(evt) {
	evt.stopPropagation();
	clearInterval(slideshowTimer);

	var i = $(this).prevAll().length;
	var s = $("#homepage #slideshow .slides li");
	showSlide(s[i], function() { slideshowTimer = setInterval(advanceSlide, 8000); });
}).first().addClass("on");

slideshowTimer = setInterval(advanceSlide, 8000);
