(function(jQuery){
	jQuery.fn.frCarousel = function(options)
		{
		    var options = jQuery.extend(jQuery.fn.frCarousel.defaults, options || {});

			return this.each(
				function()
				{
					var container = jQuery(this);
					container.append('<div class="frcarousel-scroll-container"><div class="frcarousel-scroll-area"></div></div>');

					var scrollContainer = container.find('div.frcarousel-scroll-container');
					var scrollArea = scrollContainer.find('div.frcarousel-scroll-area');
					
					var scrollAreaWidth = 0;

					container.find('> div.frcarousel-item').show().appendTo(scrollArea);

					var items = scrollArea.find('div.frcarousel-item');
					
					items.each( function () {
						
						scrollAreaWidth += jQuery(this).outerWidth();
						
					});

					var itemCount = items.size();

					if(itemCount < 0)
						return;

					container.options = options;
					container.speed = 0;

					if(scrollAreaWidth > scrollContainer.outerWidth())
					{
						items.clone().appendTo(scrollArea);
						items = scrollArea.find('div.frcarousel-item');
						
						scrollAreaWidth += scrollAreaWidth;
					}

					container.css( { position: 'relative' } );
					scrollContainer.css( { position: 'absolute', top: 0, overflow: 'hidden', width: container.width() + 'px' } );
					scrollArea.css( { position: 'relative', left: 0, width: scrollAreaWidth + 'px' } );
					items.css( { position: 'relative', float: 'left' } );

					if(scrollAreaWidth > scrollContainer.width())
					{
						container.mousemove(
							function(e)
							{
								var containerWidth = container.width();
								var maxSpeed = (options.scrollSpeedMax > 0) ? options.scrollSpeedMax : 1;

								var posX = Math.floor((e.pageX - container.offset().left) - (containerWidth / 2));
								posX *= -1;

								container.speed = ((maxSpeed / containerWidth) * posX) * 1.5;
								
								if(container.speed >= options.scrollSpeedMax)
									container.speed = options.scrollSpeedMax;
								else if(container.speed <= -options.scrollSpeedMax)
									container.speed = -options.scrollSpeedMax;
							}
							);

						setInterval(function() { jQuery.fn.frCarousel.update(container); }, options.scrollDelay);
					}
				}
				);
		};

	jQuery.fn.frCarousel.update = function(element)
		{
			var scrollArea = element.find('div.frcarousel-scroll-area');

			var xPos = scrollArea.position().left;

			var realWidth = scrollArea.width() / 2;

			if(xPos >= 1)
				xPos = 1 - realWidth;
			else if(xPos < -realWidth)
				xPos = 0;

			xPos += Math.ceil(element.speed);

			scrollArea.css('left', xPos);
		};

	// Default options
	jQuery.fn.frCarousel.defaults =
		{
			scrollDelay: 40,
	        scrollSpeedMax: 6
		};
})(jQuery);
