// Copyright (c) 20011 REDF (jhulbert AT redf DOT com || http://www.redf.com)
// Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
// and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
(function($) {
	
	var opts,
		curr = 0,
		prev = -1,
		currPanel = null,
		prevPanel = null,
		timer = null;
	
	var methods = {
		
		init: function(options) {
			opts = $.extend({
				sliderWrap:"#slider-fld",
				slider:"#slider",
				sliderPanel:".slider-panel",
				prevBtn:".arrow#left",
				nextBtn:".arrow#right",
				delay:7,
				transition:.7
			}, options);
			
			methods.setup();
		},
		
		setup: function() {
			$(opts.sliderPanel).each(function() {
				$(this).css({
					"left":$(opts.sliderWrap).width()
				});
			});
			
			$(opts.nextBtn).bind("click", function() {
				if(timer != null) clearInterval(timer);
				methods.slideNext();
			});
			
			$(opts.prevBtn).bind("click", function() {
				if(timer != null) clearInterval(timer);
				methods.slidePrev();
			});
			
			timer = setInterval(methods.slideNext, opts.delay * 1000);
			methods.slideNext();
		},
		
		slideNext:function() {
			if(prev == -1) {
				prev = 0;
				curr += 1;
			} else if(curr < $(opts.sliderPanel).length - 1) {
				prev = curr;
				curr+=1;
			} else {
				prev = $(opts.sliderPanel).length - 1;
				curr = 0;
			}
			currPanel = $(opts.sliderPanel).eq(curr);
			prevPanel = $(opts.sliderPanel).eq(prev);
			currPanel.css({"left":$(opts.slider).width()});
			currPanel.animate({
				left:-((currPanel.width() - $(opts.slider).width()) / 2),
				opacity:1
			}, { queue:true, duration:opts.transition * 1000, easing:"easeOutExpo" });
			prevPanel.animate({
				left:-$(opts.sliderWrap).width(),
				opacity:0
			}, { queue:true, duration:opts.transition * 1000, easing:"easeOutExpo" });
		},
		
		slidePrev:function() {
			if(curr > 0) {
				prev = curr;
				curr-=1;
			} else {
				prev = 0;
				curr = $(opts.sliderPanel).length - 1;	
			}
			
			currPanel = $(opts.sliderPanel).eq(curr);
			prevPanel = $(opts.sliderPanel).eq(prev);
			currPanel.css({"left":-$(opts.slider).width()});
			currPanel.animate({
				left:-((currPanel.width() - $(opts.slider).width()) / 2),
				opacity:1
			}, { queue:true, duration:opts.transition * 1000, easing:"easeOutExpo" });
			prevPanel.animate({
				left:$(opts.sliderWrap).width(),
				opacity:0
			}, { queue:true, duration:opts.transition * 1000, easing:"easeOutExpo"} );
		}
		
	}
	
	$.fn.imageSlider = 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('The method "' + method + '" does not exist in jquery.imageSlider');
		}
	}
	
})(jQuery);
