﻿
var htmlItems = new Array();
var widthItems = new Array();

$(document).ready
(
	function()
	{		
		if($('div.rotator').length > 0)
		{
			//Render
			$.each($('div.rotator div.item'), function(key, item) 
			{
				htmlItems.push($(this).html());
				widthItems.push($(this).width());
			});
			$('div.rotator').html('');
			renderItems();
			
			//Animacion
			var rotatorTimer = 7000; 			
			$('div.rotator').cycle
			(
				{		
					fx:      'scrollLeft', 
					//easing:  'bounceout', 
					//delay:   -4000, 
					easing:  'backinout', 
					pager:   'div.botonera',
					timeout: rotatorTimer
				}
			);
		}
	}
);

function renderItems()
{
	var html = $("<div class='item' style='width:600px'></div>");
	recursiveWidthItems(0, 447, 0, html);
}

function recursiveWidthItems(index, maxWidth, acumulateWidth, html)
{
    if(!widthItems[index]) 
	{
		if(acumulateWidth > 0)
		{
			$('div.rotator').append(html);
		}
		return;
	}
	
	if(widthItems[index] < maxWidth && widthItems[index] + acumulateWidth <= maxWidth)
    {
        acumulateWidth += widthItems[index];
		html.append(htmlItems[index]);
        recursiveWidthItems(index + 1, maxWidth, acumulateWidth, html);
    }  
	else
	{
		if(acumulateWidth > 0)
		{
			$('div.rotator').append(html);
			acumulateWidth = 0;
			html = $("<div class='item'></div>");
		}
		$('div.rotator').append("<div class='item'>" + htmlItems[index] + "</div>");
		recursiveWidthItems(index + 1, maxWidth, acumulateWidth, html);
	}	
}



