(function($) {

	$.fn.carousel = function(options) {
		
		var dontSpazzClick = false;
		var triggers = this;
		
		var config = {
			cTarget: '',
			cWidth: 760,
			startPos: 0,
			count: 10
		};
		var opts = $.extend({}, config, options);
		
		var gotoPrev = function() {
			dontSpazzClick = true;
			 
			var oldPos = opts.startPos;
			
			if(oldPos > 0) {
				opts.startPos -= 1;
				var speed = "normal";
			} else {
				opts.startPos = 1;
				var speed = 0;
				$(opts.cTarget + " li:last").clone().prependTo(opts.cTarget);
			}
			var newPos = opts.startPos*opts.cWidth*-1;
			
			//Where the actual animation takes place
			$(opts.cTarget).animate({
				left: newPos
			}, speed, function() {
				dontSpazzClick = false;
				if(oldPos == 0) {
					$(opts.cTarget).animate({
						left: 0
					}, 'normal', function() {
						$(opts.cTarget).animate({
							left: (opts.count - 1)*opts.cWidth*-1
						}, 0, function() {
							$(opts.cTarget + " li:first").detach();
							opts.startPos = opts.count - 1;
						});
					});
				}
				$("li", opts.cTarget).removeClass('on');
				$("li:eq("+opts.startPos+")", opts.cTarget)[0].className = "on";
			});
		};
		
		var gotoNext = function() {
			dontSpazzClick = true;
			
			var oldPos = opts.startPos;
			opts.startPos += 1;
			var newPos = opts.startPos*opts.cWidth*-1;
			
			if(oldPos == opts.count - 1) {
				$(opts.cTarget + " li:first").clone().appendTo(opts.cTarget);
			}
			
			//Where the actual animation takes place
			$(opts.cTarget).animate({
				left: newPos
			}, "normal", function() {
				dontSpazzClick = false;
				if(oldPos == opts.count - 1) {
					$(opts.cTarget).animate({
						left: 0
					}, 0);
					$(opts.cTarget + " li:last").detach();
					opts.startPos = 0;
				}
				$("li", opts.cTarget).removeClass('on');
				$("li:eq("+opts.startPos+")", opts.cTarget)[0].className = "on";
			});	
		};
		
		//Load everything in its starting Position
		$(opts.cTarget).css('left', opts.startPos*opts.cWidth*-1);
		$("li:eq("+opts.startPos+")", opts.cTarget)[0].className = "on";
		
		return triggers.each(function(i) {
			$(this).click(function() {
				if(i == 0) {
					gotoPrev();
				} else {
					gotoNext();
				}
				return false;
			});
		});
	};

})(jQuery);	
