(function($) {

	$.fn.SlideShow = function(options) {

		var defaults = {
			interval: 10000,
			duration: 1000,
			container: ".slideshow"
		};
		var options = $.extend(defaults, options);

		var slides = $(options.container + " .slide");
		var nSlides = slides.length;
		//var nSlide = Math.floor(Math.random()*nSlides);
		var nSlide = 0;
		slides.not(":eq("+nSlide+")").hide();

		var bUpdating = false;
		function update() {
			if (bUpdating) return;
			bUpdating = true;
			slides.eq(nSlide).fadeToggle(options.duration, function() {
				if (++nSlide >= nSlides) nSlide = 0;
				slides.eq(nSlide).fadeToggle(options.duration);
			});
			bUpdating = false;
		};

		var timer = null;
		StartSlideShow();
		function StartSlideShow() {
			if (timer == null) {
				timer = setInterval(update, options.interval);
				$(options.container + " .startslideshow").hide();
				$(options.container + " .stopslideshow").show();
			}
		};

		function StopSlideShow() {
			if (timer != null) {
				clearInterval(timer);
				timer = null;
				$(options.container + " .stopslideshow").hide();
				$(options.container + " .startslideshow").show();
			}
		};

		$(options.container + " .nextslide").click(function() {
			var bPlaying = timer;
			if (bPlaying) StopSlideShow();
			slides.eq(nSlide).toggle(0, function() {
				if (++nSlide >= nSlides) nSlide = 0;
				slides.eq(nSlide).toggle(0, function() {
					if (bPlaying) StartSlideShow();
				});
			});
		});

		$(options.container + " .prevslide").click(function() {
			var bPlaying = timer;
			if (bPlaying) StopSlideShow();
			slides.eq(nSlide).toggle(0, function() {
				if (--nSlide < 0) nSlide = nSlides-1;
				slides.eq(nSlide).toggle(0, function() {
					if (bPlaying) StartSlideShow();
				});
			});
		});

		$(options.container + " .stopslideshow").click(function() {
			StopSlideShow();
		});

		$(options.container + " .startslideshow").click(function() {
			StartSlideShow();
		});

		return this;
	};

})(jQuery);

$(document).ready(function(){
	$(this).SlideShow();
});

