(function($) {                                          // Compliant with jquery.noConflict()
$.fn.jCarouselLite = function(o) {   
    o = $.extend({
        btnPrev: null,
        btnNext: null,
        btnDoubleNext: null,
        btnGo: null,
        mouseWheel: false,
        auto: 5000,

        speed: 200,
        easing: null,

        vertical: false,
        circular: true,
        visible: 3,
        start: 0,
        scroll: 1,

        beforeStart: null,
        afterEnd: null,
        onBuild: null,
        onClick: null
    }, 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;
		var tmpHtml = "";
		
        if(o.circular) {
            ul.prepend(tLi.gt(tl-v-1).clone()).append(tLi.lt(v).clone());
            o.start += v;
        }
        
        var li = $("li", ul), itemLength = li.size(), curr = o.start;                       
        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
		
		//x=1;
		//li.each(function(){
		//	$(this).append(x);		
		//	x++
		//});
		
        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)

        li.css("width", li.width())                         // inner li width. this is the box model width
            .css("height", li.height());                    // 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, -(curr*liSize));                  // Set the starting item

        div.css(sizeCss, divSize+"px");                     // Width of the DIV. length of visible images

		if(o.onBuild)
        	o.onBuild.call(this, vis());
		
        if(o.btnPrev)                 
            $(o.btnPrev).click(function() {
				if (o.onClick) o.onClick.call(this);
                return go(curr-o.scroll); 
            });
        
        if(o.btnNext) {
			$(o.btnNext).click(function(){
				if (o.onClick) o.onClick.call(this);
				return go(curr+o.scroll);
			});
		}

		if (o.btnDoubleNext){
            $(o.btnDoubleNext).click(function() {
			   // increase the scroll # to 2 momentarily
			   o.scroll++;
			   o.speed -= 500;
               go(curr+o.scroll,true);
			   o.scroll--;
			   o.speed += 500;
			   	return false;
 		   });
		}

        if(o.btnGo)
            $.each(o.btnGo, function(i, val) {
                $(val).click(function() {
                    return go(o.circular ? o.visible+i : i);
                });
            });

        if(o.mouseWheel && div.mousewheel)
            div.mousewheel(function(e, d) { 
                return d>0 ? go(curr-o.scroll) : go(curr+o.scroll);
            });

        if(o.auto)
            setInterval(function() { 
                go(curr+o.scroll); 
            }, o.auto+o.speed);

        function vis() {
            return li.gt(curr-1).lt(v);
        };  

        function go(to,isDouble) {
            if(!running) {

                if(o.beforeStart)
                    o.beforeStart.call(this, vis());

                if(o.circular) {            // If circular we are in first or last, then goto the other end
                    if(to<=o.start-v-1) {           // If first, then goto last
                        ul.css(animCss, -((itemLength-(v*2))*liSize)+"px");
                        // If "scroll" > 1, then the "to" might not be equal to the condition; it can be lesser depending on the number of elements. 
                        curr = to==o.start-v-1 ? itemLength-(v*2)-1 : itemLength-(v*2)-o.scroll;

					} else if(to>=itemLength-v+1) { // If last, then goto first
						
						if (isDouble && o.visible == 1)
							{
								tmpHtml = $(li).eq(v).html();
								$(li).eq(v).html($(li).eq(li.length -1).html());
							}
						ul.css(animCss, -( (v) * liSize ) + "px" );
						
						//	
						//} else {
						//	//console.log($(li[curr]).prev().attr('class'));
						//	tmpHTML = $(li).eq(1).html();
						//	console.log("here");
						//	$(li).eq(1).html($(li).eq(curr+1).html());
						//	
						//	ul.css(animCss, -( ((v) * liSize) ) + "px" );
						//	return;
						//}
						
						// If "scroll" > 1, then the "to" might not be equal to the condition; it can be greater depending on the number of elements. 
                        curr = to==itemLength-v+1 ? v+1 : v+o.scroll;
                    } else curr = to;
                } else {                    // If non-circular and to points to first or last, we just return.
                    if(to<0 || to>itemLength-v) return;
                    else curr = to;
                }                           // If neither overrides it, the curr will still be "to" and we can proceed.

                running = true;

				if (!isDouble) {
					tmpSpeed = o.speed;	
				} else {
					tmpSpeed = o.speed;	
				}

                ul.animate(
                    animCss == "left" ? { left: -(curr*liSize) } : { top: -(curr*liSize) } , tmpSpeed, o.easing,
                    function() {
						if (isDouble && tmpHtml != "")
							{
								//console.log(tmpHtml);
								$(li).eq(v).html(tmpHtml);
								tmpHtml = "";
							}
                        if(o.afterEnd)
                            o.afterEnd.call(this, vis());
                        running = false;
                    }
                );


                // Disable buttons when the carousel reaches the last/first, and enable when not
                if(!o.circular) {
                    $(o.btnPrev + "," + o.btnNext).removeClass("disabled");
                    $( (curr-o.scroll<0 && o.btnPrev) 
                        || 
                       (curr+o.scroll > itemLength-v && o.btnNext)
                        ||
                       []
                     ).addClass("disabled");
                }

            }
            return false;
        };
    });
};

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);
