$(document).ready(function(){	
		$("#decodeSlider").decodeSlider( { sliderWidth: 390, perView: 3 } );
	});	

(function($) {

	$.fn.decodeSlider = function(options){
	  
		// default configuration properties
		var defaults = {			
			prevId:          '#slideBack',
			nextId:          '#slideForward',
			perView:         1,
			sliderWidth:     0,
			vertical:        false,
			speed:           1000,
			auto:            false,
			pause:           2000,
			continuous:      true
		}; 
		
		var options = $.extend(defaults, options);  
				
		this.each(function() {  
			var slider = $(this); 				
			var n = $("li", slider).length;
			var w = $("li", slider).width(); 
			var h = $("li", slider).height(); 
			slider.width( (options.sliderWidth > 0 ? options.sliderWidth : options.perView*w) );
			slider.height(h);
			slider.css({overflow: 'hidden'});
			var ts = Math.ceil(n/options.perView) -1;
			$('#decodeDebug').append('<p>ts = '+ ts +'</p>');
			var ls = n - (Math.floor(n/options.perView) * options.perView);
			$('#decodeDebug').append('<p>ls = '+ ls +'</p>');
			var lm = (slider.width()/options.perView)*ls*-1;
			$('#decodeDebug').append('<p>lm = '+ lm +'</p>');
			var t = 0;
			$("ul", slider).css('width',(options.sliderWidth > 0 ? n*(slider.width()/options.perView) : n*w));			
			if(!options.vertical) $("li", slider).css('float','left');
			
			$("a"+options.nextId).click(function(){		
				animate("next",true);
				return false;
			});
			$("a"+options.prevId).click(function(){		
				animate("prev",true);				
				return false;
			});	
			
			function animate(dir,clicked){
				var ot = t;		
				switch(dir){
					case "next":
						t = (ot>=ts) ? (options.continuous ? 0 : ts) : t+1;						
						break; 
					case "prev":
						t = (t<=0) ? (options.continuous ? ts : 0) : t-1;
						break; 
					case "first":
						t = 0;
						break; 
					case "last":
						t = ts;
						break; 
					default:
						break; 
				};	
			    
			    $('#decodeDebug').css({ 'clear': 'both', 'width': '100%', 'display': 'block' }).append('<p>t = '+ t +'</p>');
				
				var diff = Math.abs(ot-t);
				var speed = diff*options.speed;						
				if(n > options.perView) {
    				if(!options.vertical) {
    					p = (t*slider.width()*-1);
    					if(t==ts && lm<0) {
    					   p = (((t-1)*slider.width())*-1)+lm;
    					}
    			         $('#decodeDebug').append('<p>p = '+ p +'</p>');
    					$("ul",slider).animate(
    						{ marginLeft: p }, 
    						speed
    					);				
    				} else {
    					p = (t*slider.height()*-1);
    					$("ul",slider).animate(
    						{ marginTop: p }, 
    						speed
    					);					
    				};
				}
				
			};

		});
    	      	  
        if(this.children('ul').children().length <= 3) {
            $('#sliderNavigation').hide();
            $('#decodeSlider').hide();
        }

	};

})(jQuery);
