/*
 * jQuery Scroller
 * (c) 2010 pz 
 * v.1.0.2
 */

jQuery.fn.scroller = function(options)
{
	return this.each(function()
	{

		// default options
		var opt = $.extend({
			stepPeriod: 1000,
			waitPeriod: 1000,
			linear: false
		}, options || {}
		);

		var container = $(this);
		if (container.children().length < 2) return;

		var scrollingContainer = container.wrapInner('<div class="scrollingContainer" />').children();
		scrollingContainer.children().css({ 'display': 'block', 'float': 'left' });
		scrollingContainer.css({ 'width': getScrollingContainerWidth() });

		step();

		function getScrollingContainerWidth()
		{
			var minWidth = 2 * scrollingContainer.width();
			var items = scrollingContainer.children();
			var prevItemW = items.last().width();
			var currW;
			scrollingContainer.children().each(function()
			{
				currW = $(this).width();
				if (currW + prevItemW > minWidth) minWidth = currW + prevItemW;
				prevItemW = currW;
			});

			return minWidth;
		}

		function step()
		{
			var hInterval = setInterval(function()
			{
				clearInterval(hInterval);
				stepLeft();
			}, opt.waitPeriod);
		}

		function stepLeft()
		{
			var first = $(scrollingContainer.children()[0]);
			var w = first.width();
			var pos = Math.abs(parseInt(first.css("marginLeft")));
			var period = opt.linear ? opt.stepPeriod * w / container.width() : opt.stepPeriod;
			//alert(period + ' - ' + opt.stepPeriod + ' - ' + w  + ' - ' + container.width());
			first.animate({ 'marginLeft': '-' + w + 'px' }, period, opt.linear ? 'linear' : 'swing', function()
			{
				scrollingContainer.append(first);
				first.css('marginLeft', '0px');
				step();
			});
		}
	});
};

