
(function($) {

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

	var opts = {
		start: 0,
		duration: 1000,
		delay: 5000,
		autostart: true,
		after: null,
		before: 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;
				}
				else if(index < 0) {
					index = slides.length - 1;
				}

				if(opts.before) {
					opts.before(index);
				}

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

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

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

			}
		},

		next: function() {
			paused = true;
			methods._go2(curr + 1);
		},

		prev: function() {
			paused = true;
			methods._go2(curr - 1);
		},

		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);

