(function($) {                                          // Compliant with jquery.noConflict()
$.fn.jCarouselLite = function(o) {   
    o = $.extend({
        auto: null,

        speed: 0,
        easing: null,

		vertical: false,
        visible: 1,
        start: 0
		
    }, o || {});

    return this.each(function() {                           // Returns the element collection. Chainable.
            
        var running = false, animCss=o.vertical?"top":"left", sizeCss=o.vertical?"height":"width";
        var div = $(this), ul = $("ul", div), tLi = $("li", ul), tl = tLi.size(), v = o.visible;
		

		ul.prepend(tLi.slice(tl-v).clone()).append(tLi.slice(0, v).clone());
		o.start += v;
        
        var li = $("li", ul), itemLength = li.size(), curr = o.start;
		var img = $("img", li);
        div.css("visibility", "visible");

        li.css("overflow", "hidden")                        // If the list item size is bigger than required
            .css("float", o.vertical ? "none" : "left")     // Horizontal list
            .children().css("overflow", "hidden");          // If the item within li overflows its size, hide'em

        ul.css("margin", "0")                               // Browsers apply default margin 
            .css("padding", "0")                            // and padding. It is reset here.
            .css("position", "relative")                    // IE BUG - width as min-width
            .css("list-style-type", "none")                 // We dont need any icons representing each list item.
            .css("z-index", "1");                           // IE doesnt respect width. So z-index smaller than div

        div.css("overflow", "hidden")                       // Overflows - works in FF
            .css("position", "relative")                    // position relative and z-index for IE
            .css("z-index", "2")                            // more than ul so that div displays on top of ul
            .css("left", "0px");                            // after creating carousel show it on screen
                
        var liSize = o.vertical ? height(li) : width(li);   // Full li size(incl margin)-Used for animation
        var ulSize = liSize * itemLength;                   // size of full ul(total length, not just for the visible items)
        var divSize = liSize * v;                           // size of entire div(total length for just the visible items)

        var imgSize = width(img);
		//li.css("width", width(li))                         // inner li width. this is the box model width
            //.css("height", height(li));                    // inner li height. this is the box model height

        ul.css(sizeCss, ulSize+"px")                        // Width of the UL is the full length for all the images
            .css(animCss, -(o.start*liSize));                  // Set the starting item

        div.css(sizeCss, divSize+"px");                     // Width of the DIV. length of visible images

        
        // Attach flowscroll mouseover event to containing div
		$(div).mouseover(
		  function (e) {
			scrollOnOver(e, this);
		  }
		);
		
		$(li).mouseout(
		  function () {
			stopLoop();
			return false;
		  }
		);
		
		// Flowscroll variable declaration
		var tO;
		var direction;							// Indicates which side (left/right) of the carousel the cursor is on
		
		var increment = 5;						// Indicates how many pixels to animate by per iteration of the go() function
		
		var zoneStart 		= imgSize/2 - 5;				// with zoneEnd: delineates mouse "-insensitive" and "-sensitive" areas of the carousel
		var zoneEnd 		= this.offsetWidth/2;
		var scrX			= findLeft(this) + zoneEnd;  	// Find the x-position of the center of the carousel
		var zoneSize 		= zoneEnd - zoneStart;
		var zoneDivision 	= zoneSize/5;					// Divides the sensitive zone into five parts based on distance from the carousel's y-axis
		var zoneOne			= zoneStart+zoneDivision;
		var zoneTwo			= zoneStart+(zoneDivision*2);
		var zoneThree		= zoneStart+(zoneDivision*3);
		var zoneFour		= zoneStart+(zoneDivision*4);
		
		
		var loopOn = true;						// Tracks whether animation loop is turned on or off
		var loopRunning;						// Tracks whether the animation itself is currently running
		
		var movesCounter 	= 0;					// Indicate animation states within the go() function
		curr 				= o.start-1;
		var next 			= curr+1;
		
		// On mouseover, determines direction and speed for the animation based on cursor position
		function scrollOnOver(e, el){ //mouseEventHandler e, element holding the carousel el// 			
			// Find the current x-position of the cursor
			var mouseX = e.clientX;			
			var distance = mouseX - scrX;
						
			// Set variables to indicate the cursor's direction and absolute distance from the y-axis of the carousel
			if (distance<0){
				direction = "left";
			}
			else{
				direction = "right";
			}
			
			distance = Math.abs(distance);
			// If the cursor is on a sensitive zone, set the animation speed according to its distance from the y-axis
			if (distance>zoneStart && distance<zoneEnd){
				if(distance<zoneOne){
					o.speed = 150;
				}
				else if(distance>=zoneOne && distance<zoneTwo){
					o.speed = 65;
				}
				else if(distance>=zoneTwo && distance<zoneThree){
					o.speed = 30;
				}
				else if(distance>=zoneThree && distance<zoneFour){
					o.speed = 10;
				}
				else if(distance>=zoneFour){
					o.speed = 5;
				}
				
				// If the animation loop is turned off, start it
				if(!loopRunning){loopOn = true;loop();}
			}
			// If the cursor is on an insensitive zone, stop the animation loop
			else{
				stopLoop();
			}
			
		}
		
		// Invokes the animation function and calls itself recursively, until the animation loop is turned off 
		function loop(){
			if (loopOn){
				go(direction);
				loopRunning = true;
				tO = setTimeout(loop, o.auto+o.speed)
			}
		}
		
		
		// Turns off the animation loop
		function stopLoop(){
			loopOn = false;
			loopRunning = false;
		}

		if (direction == "right" && curr < next){
			
		}
		else if (direction == "left" && curr > next){
			
		}
		
        
		// Animates x pixels to the left or right, where x is the static variable "increment", and "to" is the direction
		function go(to) {
            if(!running) {
				running = true;
				var vector;
				
				// If the direction is "right", set the animation to move in the correct direction				
				if (direction == "right"){				
					vector = "-="+increment+"px";
					// If we have moved one full image to the right, increment the curr and next variables
					if(movesCounter>= liSize){
						if(next>curr) curr++;
						else curr--;
						next = curr + o.visible;
						movesCounter = 0;
						
					}
					// Track how many pixels we have moved, so we know when we have cycled to the next image
					movesCounter += increment;
				}
				//If the direction is "left", set the animation to move in the correct direction
				else if (direction == "left"){
					vector = "+="+increment+"px";
					// If we have moved one full image to the deft, decrement the curr and next variables
					if(movesCounter<= -liSize){
						if(next<curr) curr--;
						else curr++;
						next = curr - o.visible;
						
						movesCounter = 0;
						
					}
					// Track how many pixels we have moved, so we know when we have cycled to the next image
					movesCounter -= increment;
				}
				
				
				
				// Make the list circular:
				// If we are at the first image, animating in a negative direction...
				if(next<=o.start-v && direction == "left") {
						// ... reposition the list to the beginning...
						ul.css(animCss, -((itemLength-(v*2))*liSize )+"px");  
						// ...and set the curr and next variables to the end of the list.
						curr = itemLength-v;
						next = curr - v;
				} 
				// If we are at the last image, animating in a positive direction...
				else if(next>=itemLength-v && direction == "right") { 
					// ... reposition the list to the beginning...
					ul.css(animCss, -( (v) * liSize) + "px" );
					// ...and set the curr and next variables to the start of the list.
				   	curr = 0;
				   	next = curr + v;
				}
                

				// Perform the animation
                ul.animate(
                    animCss == "left" ? { left: vector } : { top: vector } , o.speed, 
                    function() {
                        // Indicate the animation has finished
                        running = false;
                    }
                );
            }
            return false;
        };
    });
};

function findLeft(obj) {
	var curleft = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
		}
	}
	return curleft;
}

function css(el, prop) {
    return parseInt($.css(el[0], prop)) || 0;
};
function width(el) {
    return  el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight');
};
function height(el) {
    return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom');
};

})(jQuery);