(function ($) {
	$.fn.extend({
		easyslideshow: function (config) {
			var gConfig = $.extend({
				autoPlay: true,
				interval: 5000,
				showControls: true
			}, config);
			var gSlideshow = $(this);
			var gItems = gSlideshow.children("li");
			var gControls;
			var gTimer;
			var gPlaying;
			var prev = function () {
				if (gTimer) {
					window.clearTimeout(gTimer);
				}
				var prevItem = gItems.filter(".default");
				var nextItem = prevItem.prev().length ? prevItem.prev() : gItems.last();
				anim(prevItem, nextItem);
				if (gPlaying) {
					gTimer = window.setTimeout(next, gConfig.interval);
				}
			};
			var next = function () {
				if (gTimer) {
					window.clearTimeout(gTimer);
				}
				var prevItem = gItems.filter(".default");
				var nextItem = prevItem.next().length ? prevItem.next() : gItems.first();
				anim(prevItem, nextItem);
				if (gPlaying) {
					gTimer = window.setTimeout(next, gConfig.interval);
				}
			};
			var play = function () {
				if (gTimer) {
					window.clearTimeout(gTimer);
				}
				if (gControls) {
					gControls.find(".play").hide();
					gControls.find(".stop").show();
				}
				gPlaying = true;
				gTimer = window.setTimeout(next, gConfig.interval);
			};
			var stop = function () {
				if (gTimer) {
					window.clearTimeout(gTimer);
				}
				if (gControls) {
					gControls.find(".play").show();
					gControls.find(".stop").hide();
				}
				gPlaying = false;
			};
			var anim = function (a, b) {
				a.animate({
					opacity: 0
				}, "fast", function () {
					b.css({
						opacity: 0
					});
					$([a, b]).toggleClass("default");
					b.animate({
						opacity: 1
					}, "fast");
				});
			};
			if (gItems.length > 1) {
				if (gConfig.showControls) {
					gControls = $('<div class="easyslideshow-controls"></div>').css({
						opacity: 0.8
					}).insertAfter(gSlideshow);
					$('<a href="#" class="prev">&lsaquo; Prev</a>').click(function () {
						prev();
						return false;
					}).appendTo(gControls);
					$('<a href="#" class="play">Play</a>').click(function () {
						play();
						return false;
					}).appendTo(gControls);
					$('<a href="#" class="stop">Stop</a>').click(function () {
						stop();
						return false;
					}).appendTo(gControls);
					$('<a href="#" class="next">Next &rsaquo;</a>').click(function () {
						next();
						return false;
					}).appendTo(gControls);
				}
				if (gConfig.autoPlay) {
					play();
				}
			}
			return this;
		}
	});
})(jQuery);

