(function() {

	slideshow = function() {

		var slideTimer = null;
		var slideshow = null;
		var currentIndex = 0;
		var first = true;

		var getNextIndex = function() {
			var nbImages = $("ul.images li", slideshow).length;
			if(currentIndex >= nbImages - 1) return 0;
			else return ++currentIndex;
		};

		var pager = function() {
			$(".footer", slideshow).empty();
			var index = 0;
			$("ul.images li", slideshow).each(function() {
				var html =
					'<a href="javascript:;" index="' + (index++) + '">' +
						'<img src="/public/images/page' + ($(this).hasClass("cursor") ? "-on" : "") + '.png" />' +
					'</a>';
				$(".footer", slideshow).append(html);
			});
		};

		var slide = function(index) {
			if(!first) {
				$("ul.images li:eq(" + currentIndex + ")", slideshow).removeClass("cursor");
				if(index !== null) currentIndex = index;
				else currentIndex = getNextIndex();
			}
			var li = $("ul.images li:eq(" + currentIndex + ")", slideshow).addClass("cursor");
			if($("ul.images li", slideshow).length <= 1) {
				$(".mainImage", slideshow).append($("a", li).clone().show());
				pager();
				return;
			}
			else if($("ul.images li", slideshow).length == 0) {
				return;
			}
			else {
				$(".mainImage", slideshow).append($("a", li).clone().hide());
			}
			if(!first) $(".mainImage a:last", slideshow).fadeIn("slow");
			else $(".mainImage a:last", slideshow).show();
			if($(".mainImage a", slideshow).length > 1) {
				$(".mainImage a:first", slideshow).fadeOut("slow", function() {
					$(this).remove();
				});
			}
			pager();
			if(index === null) {
				slideTimer = setTimeout(function() { slide(null); }, 3000);
			}
			first = false;
		};

		return {
			init: function() {
				var index = 0;
				slideshow = $("#slideshow");
				slide(null);
				$(".footer a", slideshow).live("click", function() {
					clearTimeout(slideTimer);
					slide(parseInt($(this).attr("index")));
				});
			}
		}
	}();

	$().ready(slideshow.init);

})();

