// Slideshow Plugin
(function($) {

  var container, nextButton, prevButton, carousel, slides, slideCount, positionDisplay, width, options, activeSlide, timer;
	
	var methods = {
		//
		slideTo: function(slideIndex) {
			if (slideIndex < 0) {
				activeSlide = slideCount - 1;
			}
			else {
				activeSlide = slideIndex % slideCount;
			}			
			positionDisplay.text((activeSlide + 1) + ' of ' + slideCount);
			carousel.animate({ left: - width * activeSlide });    
			return this;
		},		
		//
		slideNext: function() {
			methods.slideTo.call(this, activeSlide + 1);			
			return this;
		},
		//
		startAutoRotate: function() {
			if (options.autoRotate) {
				timer = window.setInterval(function(){ methods.slideNext.call(container); }, options.autoRotate);				
			}
			return this;
		},
		//
		stopAutoRotate: function() {
			if (options.autoRotate) {
				window.clearInterval(timer);
			}
			return this;
		},
		//
		init: function(opt) {			
			var defaults  = { autoRotate:false, randomStart:false }
			options = $.extend(defaults, opt);
			
			container          = this;
			nextButton         = this.find('.next');
			prevButton         = this.find('.prev');
			carousel           = this.find('.carousel');
			slides             = this.find('.slide');
			slideCount         = slides.size();
			positionDisplay    = this.find('.position');
			width              = this.width();
			
			if (options.randomStart) {
			  var initialSlide = Math.floor(Math.random() * slideCount);
			} else {
			  var initialSlide = 0;
			}
			
			activeSlide = initialSlide;
			//
			carousel.css({'left':- this.width() * initialSlide });
					
			if (options.autoRotate) {
				methods.startAutoRotate.call(container);
			}

			nextButton.click(function(){ methods.slideTo.call(container, activeSlide + 1); return false; });			
			prevButton.click(function(){ methods.slideTo.call(container, activeSlide - 1); return false; });
			
			// Stop auto-rotation on mouse over, continue on mouse out
			container.hover(function(){ methods.stopAutoRotate.call(container); }, function(){ methods.startAutoRotate.call(container); });
			// Stop auto-rotation if a slide is clicked (for videos and such);
			slides.click(function(){ methods.stopAutoRotate.call(container); options.autoRotate = false; });			
			//
			positionDisplay.text((initialSlide + 1) + ' of ' + slideCount);
			//
			slides.css({visibility:'visible'});
			
			return this;
		}
	}
	
	$.fn.slideshow = function(method) {
		// Method calling logic
		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);
