// create closure
(function($) {
	// plugin definition
	$.fn.slideshow = function(options) {
		// build main options before element iteration
		var opts = $.extend({}, $.fn.slideshow.defaults, options);
		
		// iterate and reformat each matched element
		return this.each(function() {
			// build element specific options
			var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
			
			var $slideshow = $(this);
			var $slides = $('.slide', this);
			
			var currentPosition = 0;
			var slideWidth = $slideshow.width();
			var numberOfSlides = $slides.length;
			
			$slideshow.css('overflow', 'hidden');
			
			// Wrap all .slides with div.slideInner
			$slides
				.wrapAll('<div class="slideInner"></div>')
				// Float left to display horizontally, readjust .slides width
				.css({
					'float' : 'left',
					'width' : slideWidth
				});
			
			// Set .slideInner width equal to total width of all slides
			var $slideInner = $('.slideInner', this);
			$slideInner.css('width', slideWidth * numberOfSlides);
			
			// Insert controls in the DOM
			$slideshow
				.prepend('<span class="control leftControl">Previous</span>')
				.append('<span class="control rightControl">Next</span>');
				
			var $leftControl = $(".leftControl", this);
			var $rightControl = $(".rightControl", this);
			
			// Hide left arrow control on first load
			manageControls();
			
			// Create event listeners for .controls clicks
			$('.control', this).bind('click', function(){
				// Determine new position
				currentPosition = $(this).hasClass('rightControl') ? currentPosition+1 : currentPosition-1;
			
				// Hide / show controls
				manageControls();
			
				// Move slideInner using margin-left
				$slideInner.animate({
					'marginLeft' : slideWidth*(-currentPosition)
				});
			});
			
			// manageControls: Hides and Shows controls depending on currentPosition
			function manageControls() {
				// Hide left arrow if position is first slide
				if(currentPosition==0) { $leftControl.hide() } else{ $leftControl.show() }
				// Hide right arrow if position is last slide
				if(currentPosition==numberOfSlides-1){ $rightControl.hide() } else{ $rightControl.show() }
			}

		});
	};
	
	$(function() {
		$(".slideshow").slideshow();
	});
})(jQuery);

