/**
*	@author: Marcelo de Souza - 02/2009
*/

(function($) {

	$.fn.extend({
		scrolllist: function (upElement, downElement, options) {

			var defaults = {
				auto: false
			}

			var opts = $.extend(defaults,options);

			if (opts.auto)
				autoStart(this, 'slow', opts);

			return this.each(function () {
				var listElement = this;

				$(downElement).mouseover(function () { stop(listElement); Up(listElement, 'fast', opts); });
				$(upElement).mouseover(function () { stop(listElement); Down(listElement, 'fast', opts); });

				if (opts.auto) {
					$(listElement).mouseover(function () { stop(listElement); });
					$(listElement).mouseout(function () { stop(listElement); Up(listElement, 'slow', opts); });

					$(upElement).mouseout(function () {
						stop(listElement);
						Up(listElement, 'slow', opts);
					});
					$(downElement).mouseout(function () {
						stop(listElement);
						Up(listElement, 'slow', opts);
					});
				}
				else {
					$(upElement).mouseout(function () {
						stop(listElement);
					});
					$(downElement).mouseout(function () {
						stop(listElement);
					});
				}

			});
		}
	});

	function Up(listElement, duration, opts) {
		//console.log('Up');
		if ($(listElement).css("marginTop") == 'auto')
			$(listElement).css("marginTop", "0px");

		var h = pxToNumber($(listElement).parent().height()) - pxToNumber($(listElement).height());

		if (pxToNumber($(listElement).css("marginTop")) >= h)
			$(listElement).animate({"marginTop": "-=20px"}, duration, "linear", function () { Up(listElement, duration, opts); } );

		else if (opts.auto == true && duration == 'slow')
			restart(listElement, opts);
	}

	function Down(listElement, duration, opts) {
		//console.log('Down');
		if (pxToNumber($(listElement).css("marginTop")) <= 0)
			$(listElement).animate({"marginTop": "+=20px"}, duration, "linear", function () { Down(listElement, duration, opts); } );

	}

	function stop(listElement) {
		//console.log('stop');
		$(listElement).stop();
	}

	function autoStart(listElement, duration, opts) {
		//console.log('autoStart');
		Up(listElement, duration, opts);
	}

	function restart(listElement, opts) {
		//console.log('restart');
		$(listElement).css("marginTop", "0px");
		autoStart(listElement, 'slow', opts);
	}

	function pxToNumber(value) {
		if (!isNaN(value))
			return parseFloat(value);
		else
			return parseFloat(value.replace('px', ''));
	}

})(jQuery);
