/**
 * Funzione di animazione news stile ansa.
 * @author Stefano Dal Pra
*/
(function($){
	$.fn.extend({
		
        ansanews: function(options) {
		
	        var settings = $.extend({
	            hideInterval: 60, // temporizzazione dello spostamento
	            step: 2 // px spostati alla volta nello scrolling
	        }, options);
	        
	        return this.each(function() {
	        	var wrapper = $(this);
	        	var interval;
	        	
                function stopAnimation() { 
                	clearInterval(interval); 
                }
                function startAnimation() { 
                	interval = setInterval(hideNews, settings.hideInterval); 
                }

                // spaziamo correttamente le news presenti
                var left = 0;
            	$('.news-item', wrapper).each(function() {
            		$(this).css({'left': left});
            		left += $(this).outerWidth();
            	});
	        	
            	// procediamo con l'animazione
                interval = setInterval(hideNews, settings.hideInterval);
	        	
                wrapper.mouseenter(function(e) {
                    stopAnimation();
                });

                wrapper.mouseleave(function(e) {
                    startAnimation();
                });                
                
                
                /**
                 * Cancella via via i caratteri della prima news, 
                 * riportandoli nell'ultima posizione e 
                 * creando l'effetto ansa.
                 */
                function hideNews() {
                	var news = $('.news-item', wrapper);
                	var firstNews = $('.news-item:first', wrapper);
                	var lastNews = $('.news-item:last', wrapper);
                	news.each(function(){
                		// ricavo la posizione di ogni news
                		var left = ($(this).css('left') == 'auto')?0: parseInt($(this).css('left'));
                		// sposto di 1xp verso sinistra
                		$(this).css({
                			'left': (left - settings.step) + 'px'
                		});
                		// se è la prima news
                		if ($(this).is(firstNews)) {
                			// quando non è più visible
                			if (left < -firstNews.outerWidth()) {
                				// la sposto in coda
                				var lastLeft = lastNews.outerWidth() +  
                					((lastNews.css('left') == 'auto')?0:parseInt(lastNews.css('left')));
                				firstNews.css({'left': lastLeft + 'px'});
                				firstNews.appendTo($('.news-items', wrapper));
                			}
                		}
                	});
                }
	        });
		}
	});
})
(jQuery);
