
(function($) {

	var slides, curr, running = false, paused = false;

	var opts = {
		start: 0,
		delay: 5000,
		autostart: true,
		finishedCallback: null
	};

	var methods = {
		init: function(options) {

			if(options) {
				$.extend(opts, options);
			}

			return this.each(function() {

				var $this = $(this);

				slides = $this.children().each(function() {
					var $slide = $(this);

					if($slide.index() == opts.start) {
						curr = $slide.index();
						$slide.css('display', 'block');
					}
					else {
						$slide.css('display', 'none');
					}
				});


				if(opts.autostart) {
					setTimeout(function() {
						methods._go2(curr + 1);
					}, opts.delay);
				}

			});
		},

		_go2: function(index) {
			
			if(!running && index != curr) {

				running = true;

				if(index >= slides.length) {
					index = index % slides.length;
				}

				slides.filter(':nth-child(' + (curr + 1) + ')').fadeOut();
				slides.filter(':nth-child(' + (index + 1) + ')').fadeIn(function() {
					curr = index;
					running = false;

					if(opts.finishedCallback) {
						opts.finishedCallback(curr);
					}
				});

				if(!paused) {
					setTimeout(function() {
						if(!paused) {
							methods._go2(curr + 1);
						}
					}, opts.delay);
				}

			}
		},

		go2: function(index) {
			paused = true;
			methods._go2(index);
		}
	}

	$.fn.slideshow = function(method) {

		if(methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		}
		else if(typeof method === 'object' || !method) {
			return methods.init.apply(this, arguments);
		}
		else {
			$.error('Method ' + method + ' does not exist on jQuery.slideshow');
		}
	}

})(jQuery);

