(function($) {
    
    $.fn.carousel = function(prev, next, start) {
        var prevButton = $('#'+prev);
        var nextButton = $('#'+next);
        var listItems = this;
        var childLen = listItems.children().length;
        var childWidth = listItems.children().width();
        var lock = false;
        setWidth(listItems, childLen, childWidth);
		moveToStartPosition();
        
        prevButton.click(function() {
            var pos = listItems.position().left;
            var newPos = parseFloat(pos) + parseFloat(childWidth);
            if(lock) return;
            if(pos >= 0) return;
            lock = true;
            listItems.animate({left: newPos + 'px'}, 'normal', function() {
                lock = false;
            });
        });
        
        nextButton.click(function() {
            var pos = listItems.position().left;
            var newPos = parseFloat(pos) - parseFloat(childWidth);
            var lastPos = childWidth * childLen * (-1);
            if(lock) return;
            if(newPos <= lastPos) return;
            lock = true;
            listItems.animate({left: newPos+'px'}, 'normal', function() {
                lock = false;
            });
        });
        
        function setWidth(obj, len, wid) {
            var newWid = wid * len;
            obj.css('width', newWid + 'px');
        }
		
		function moveToStartPosition() {
			var newPos = (start - 1) * childWidth * (-1);
			listItems.animate({left: newPos+'px'}, 'normal', function() {
                lock = false;
            });
		}
    };
    
})(jQuery);
