(function($){
	$.fn.slideshow = function(options){
		var defaults = {pauseSeconds: 8, fadeSpeed: 0.5, width: 495, height: 150, caption: true, cssClass: 'slideshowlite'
		};

		var options = $.extend(defaults, options);
		var target = this;
		var items = $(target).children("a");
		var instance;
		if ( ! $(this).hasClass(options.cssClass)) $(this).addClass(options.cssClass);
		$(this).css({
			width: options.width + "px",
			height: options.height + "px"
		});

		$(this).children("img").wrap(document.createElement("a"));
		$(this).children("a").attr("target", "_self");

		var i = 1;
		$(this).children("a").each(function(){$(this).attr("rel", i++);});

		$(this).append("<ul></ul>");
		$(this).append("<ol></ol>");
		var pagination = $(this).children("ul");
		var caption = $(this).children("ol");
		var i = 1;
		var j = 0;
		$(this).children("a").each(function(){
			pagination.append("<li><a href=\"#\">" + i++ + "</a></li>");
			caption.append("<li>" + $("#" + $(target).attr("id") + " img:nth(" + j++ + ")").attr("alt") + "</li>");
		});
		pagination.fadeTo(0, 1);
		caption.fadeTo(0, 0.6);
		caption.hide();

		var firstItem   = $(target).children("a:first");
		var lastItem    = $(target).children("a:last");
		var currentItem = firstItem;

		var paginationHighlight = function(sequence){
			pagination.children("li").children("a").removeClass("current");
			pagination.children("li").children("a:nth(" + sequence + ")").addClass("current");
		}

		var showCaption = function(sequence){
			caption.show();
			caption.children("li").hide();
			caption.children("li:nth(" + sequence + ")").fadeIn();
		}

		var makeSlideshow = function(){
			pagination.children("li").children("a").click(function(){
				if ( ! $(this).hasClass("current")){
					currentItem = $(target).children("a:nth(" + ($(this).text()-1) + ")");
					currentItem.show();
					startSlideshow();
				}
			});

			paginationHighlight(currentItem.attr("rel")-1);

			if (options.caption == true){showCaption(currentItem.attr("rel")-1);}

			currentItem.fadeIn(options.fadeSpeed*1000, function(){
				$(target).children("a").hide();
				$(this).show().css("z-index", 1);
			});

			if (currentItem.children("img").attr("src") == lastItem.children("img").attr("src")){
				currentItem = firstItem;
				currentItem.css("z-index", 2);
			} else {
				currentItem = currentItem.next();
			}
		};
		var startSlideshow = function(){
			clearInterval(instance);
			makeSlideshow();
			instance = setInterval(makeSlideshow, options.pauseSeconds*1000);
		};

		startSlideshow();
	};
})(jQuery);
