/*
*	jQuery plugin: jMarquee
*	http://www.fusionweb.it/
*
*	Written by Dario Cancelliere from http://www.fusionweb.it/
*	Release date: 10/06/2011
*	Version: 0.1
*
*	Licensed under the GNU GPL license.
*	http://www.gnu.org/licenses/gpl.txt
*/

(function($)
{  
	$.fn.marquee = function(options)
	{
		var defaults = {
		speed: 2,
		sense: "left",
		easeMode: "linear"
		};

		var options = $.extend(defaults, options);
		var parent = $(this).parent();

		var endPosition = 0;
		var duration = 0;

		return this.each(function()
		{
			$(parent).append("<div class=\"marquee_container\"></div>");

			var container = $(parent).children(".marquee_container");

			$(container).append($(this));

			var containerWidth = parseInt($(container).width());
			var containerHeight = parseInt($(container).height());

			$(this).show();

			var entireWidth = 0;
			var entireHieght = 0;

			$("li", this).each(function()
			{
				entireWidth += parseInt($(this).width());

				if (!entireHieght || (parseInt($(this).height()) > entireHieght))
				{
					entireHieght = parseInt($(this).height());
				}

				duration++;
			});

			duration *= (options.speed * 1000);

			$("li", this).height(entireHieght);
			$(this).width(entireWidth);

			endPosition = parseInt(entireWidth - containerWidth);

			if (options.sense == "left")
			{
				$(this).css("left", "0px");
			}

			else if (options.sense == "right")
			{
				$(this).css("left", "-" + endPosition +  "px");
			}

			startCallback($(this));

			$(this).hover(function()
			{
				$(this).stop();
			},
			function()
			{
				startCallback($(this), false);
			});
		});

		function startCallback(object, reset)
		{
			if (options.sense == "left")
			{
				if (reset)
				{
					$(object).fadeOut(500, function()
					{
						$(this).animate({"left": "0px"}, 1000, options.easeMode, function()
						{
							$(this).fadeIn(500);
						});
					});
				}

				else
				{
					duration -= Math.abs(options.speed * parseInt(parseInt($(object).css("left")) / 3.6));
				}

				$(object).animate({"left": "-" + endPosition +  "px"}, duration, options.easeMode, endCallback);
			}

			else if (options.sense == "right")
			{
				if (reset)
				{
					$(object).fadeOut(500, function()
					{
						$(this).animate({"left": "-" + endPosition +  "px"}, 1000, options.easeMode, function()
						{
							$(this).fadeIn(500, function()
							{
								$(this).animate({"left": "0px"}, duration, options.easeMode, endCallback);
							});
						});
					});
				}

				else
				{
					duration -= Math.abs(options.speed * parseInt(parseInt($(object).css("left")) / 3.6));

					$(object).animate({"left": "0px"}, duration, options.easeMode, endCallback);
				}
			}
		}

		function endCallback()
		{
			steps = 0;

			startCallback($(this), true);
		}
	};
})(jQuery);
