(function($) {

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

	var opts = {
		start: 0,
		duration: 1000,
		delay: 5000,
		autostart: true,
		after: null
	};

	var methods = {
		init: function(options) {

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

			//console.log(this);
			var els = this;

			return els.each(function() {

				var $this = $(this), data = {curr: 0, running: false, paused: false};

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

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


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

				$this.data('slideshow', data);

			});
		},

	}

	function _go2(els, index) {

		return els.each(function() {
			
			var $this = $(this), data = $this.data('slideshow');

			if(!data.running && index != data.curr) {

				var $that = $this;

				data.running = true;
				$this.data('slideshow', data);

				if(index >= data.slides.length) {
					index = index % data.slides.length;
				}
				else if(index < 0) {
					index = data.slides.length - 1;
				}

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

					var data = $that.data('slideshow');

					data.curr = index;
					data.running = false;
					$that.data('slideshow', data);

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


				setTimeout(function() {
					var data = $that.data('slideshow');

					_go2(els, data.curr + 1);
				}, opts.delay);

			}

		});
	}

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

