/*
news.js
	Creates the news carousel.
By Luca De Angelis
	lucaDOTdeangelisATgmailDOTcom
	For Elettra Progetti e Servizi S.p.A.
*/

$(document).ready(function(){
	// To-do:
	// - stop the timer on hover
	// Gobal vars
	ul = $('#news ul');
	li = ul.children();
	lis = li.length;
	liWidth = 164;
	liMargin = 10;
	// Local var
	var maxHeight = 0;

	// Checking the max-height of the lis to set the ul container's height
	li.each(function(){
		if ($(this).height() > maxHeight) maxHeight = $(this).height();
	});

	// Container's width equal to the sum of the lis width
	ul.css({ 'width': lis * ul.width() + liMargin * lis, 'position': 'absolute'})
	.parent().css({ 'height': maxHeight, 'overflow': 'hidden', 'position': 'relative' })
	.hover(function(){
		// handlerIn
		clearTimeout(timer);
	},
	function(){
		// handlerOut
		coreTimer();
	});
	// Floating the lis to the left and hiding them except the first one
	li.css({ 'width': liWidth, 'margin-right': liMargin, 'float': 'left' })
	.filter(':first').addClass('visible-news');
	// Starting the first timer
	coreTimer();
});

// Sets the timer for the next scroll taking into account the quantity of the text
function coreTimer(){
	timer = setTimeout('move()', Math.round(li.filter('.visible-news').text().length / 22 * 1000));
}

// Moves the ul to the next li or returns back if at last
function move(){
	var if_statement = li.filter('.visible-news').index() != (lis - 1);
	ul.animate({
		marginLeft: if_statement ? eval(ul.css('margin-left').replace("px", "")) - liWidth - liMargin : 0
	}, if_statement ? 300 : 600, function(){
		if_statement ? li.filter('.visible-news').removeClass('visible-news').next().addClass('visible-news') : li.removeClass('visible-news').first().addClass('visible-news');
		coreTimer();
	});
}

