(function($) {

	var methods = {
	
		init: function(options) {
			var data = {
				current_slide: 0,
				slide_width: options.slide_width,
				total_slides: $(this).find('.slide').length,
				slideshow: $(this)
			};
			
			$(this).data('store', data);
			
			$(this).find('.slide:gt(0)').css('left', (0 - data.slide_width));
			
			$(this).find('a.arrow').data('slideshow', this).click(function() {
						
				if($(this).hasClass('right')) { 
					$($(this).data('slideshow')).slideshow('gotoNextSlide');
				}
				else {
					$($(this).data('slideshow')).slideshow('gotoPrevSlide');
				}	

			});
						
			$(this).parent().find('.controls a').data('slideshow', this).click(function() {
				$($(this).data('slideshow')).slideshow('gotoSlide', null, $(this).index());
			});
		},
		
		gotoNextSlide: function() {
			$(this).slideshow('gotoSlide', 1);
		},
		
		gotoPrevSlide: function() {
			$(this).slideshow('gotoSlide', -1);
		},
		
		gotoSlide: function(direction, index) {				
			var data = $(this).data('store');
			var current_slide = $(this).find('.slide:eq(' + data.current_slide + ')');
			var old_index = data.current_slide;
						
			data.current_slide = (direction == null ? index : data.current_slide + direction);
									
			if(data.current_slide < 0) {
				data.current_slide = (data.total_slides - 1);
			}
			else if(data.current_slide == data.total_slides) {
				data.current_slide = 0;
			}
						
			var new_slide = $(this).find('.slide:eq(' + data.current_slide + ')');
			
			if(direction == null) {
				direction = (data.current_slide > old_index ? 1 : -1);
			}
						
			new_slide.css({
				left: (data.slide_width * direction)
			});
			
			new_slide.stop().animate({
				left: 0
			});
			
			current_slide.stop().animate({
				left: (data.slide_width * (direction == 1 ? -1 : 1))
			});
			
			$(this).parent().find('.controls a').removeClass('current');
			$(this).parent().find('.controls a:eq(' + data.current_slide + ')').addClass('current');
			
			$(this).data('store', data);
		}
		
	};
			
	$.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' );
		}   
		
		return this;
	}

})(jQuery);
