(function($) {

	$.fn.carousel = function(options) {
		
		var dontSpazzClick = false,
			triggers = this,
			config = {
				cTarget: '',
				shift: 171,
				startPos: 0
			},
			opts = $.extend({}, config, options),
			speed = 'normal',
			easing = 'swing',
			count = $('li', opts.cTarget).length,
			frameWidth = $(opts.cTarget).parent().outerWidth(),
			itemWidth = $('li', opts.cTarget).outerWidth(true),
			numVisible = Math.ceil(frameWidth / itemWidth);
		
		var gotoPrev = function() {
			dontSpazzClick = true;
			 
			var oldPos = opts.startPos;
			
			if(oldPos > 0) {
				opts.startPos -= 1;
			} else {
				opts.startPos = 0;
				$('li:last', opts.cTarget).clone().prependTo(opts.cTarget);
				$(opts.cTarget).css({ 'left': opts.shift*-1 });
			}
			
			var newPos = opts.startPos*opts.shift*-1;
			
			$(opts.cTarget).animate({
				left: newPos
			}, speed, easing, function() {
				dontSpazzClick = false;
				if(oldPos == 0) {
					$("li:last", opts.cTarget).detach();
				}
			});
		};
		
		var gotoNext = function() {
			dontSpazzClick = true;
			
			var oldPos = opts.startPos;
			opts.startPos += 1;
			var newPos = opts.startPos*opts.shift*-1;
			
			if(oldPos == count - numVisible) {
				for(i = 0; i < count; i++) {
					$("li:eq(" + i + ")", opts.cTarget).clone().appendTo(opts.cTarget); //quick and dirty, appends all items so the previous case grabs the right end
				}
			}
	
			//Where the actual animation takes place
			$(opts.cTarget).animate({
				left: newPos
			}, speed, easing, function() {
				dontSpazzClick = false;
				if(oldPos == count - 1) {
					$(opts.cTarget).css({ 'left': 0 });
			
					var highestIndex = $('li', opts.cTarget).length - 1;
					for(j = highestIndex; j > count -1; j--) {
						$("li:eq(" + j + ")", opts.cTarget).detach(); //quick and dirty, removes all appended items
					}
			
					opts.startPos = 0;
				}
			});	
		};
	
		//Load everything in its starting Position
		$(opts.cTarget).css({
			'left': opts.startPos*opts.shift*-1,
			'width': (count * itemWidth) + (itemWidth * numVisible)
		});
		
		return triggers.each(function(i) {
			$(this).click(function() {
				if(!dontSpazzClick) {
					i == 0 ? gotoPrev() : gotoNext();
				}
				return false;
			});
		});
	};

})(jQuery);	
