var ACTUALITZANT = false;

$(function() {
	
	// Carreguem les noticies en el ticker
	actualitzarTicker();
	
	//~ setInterval(showHideNoticies, 6 * 1000);
	
	$('#actualitzar_ticker')
		.click(actualitzarTicker);
	
	$('#div_ticker')
		.hover(function() {$('#content_ticker').stop()}, function() {scroll()})
		.mousewheel(function(event, delta) {
					var ct = $('#content_ticker');
					ct.stop();
					if (delta > 0) {
						var top = parseInt(ct.css('top')) + 10;
						ct.css('top', top);
					} else {
						var top = parseInt(ct.css('top')) - 10;
						ct.css('top', top);
					}
					return false;
				});
	
});

function actualitzarTicker() {
	ACTUALITZANT = true;
	
	$('#content_ticker')
		.stop(); // Aturem l'animació
	
	$.ajax({ type: "GET", url: "/canalesplai/tickerNoticias.asp", dataType: "xml",
			success: function(xml) {
				
				var ticker = $('#content_ticker');
				ticker.empty();
				
				$(xml)
					.find("item")
						.each(function() {
							var title = $(this).find("title").text();
							var link = $(this).find("link").text();
							var strdate = $(this).find("dc\\:date").text();
							/(\d\d\d\d)-(\d\d)-(\d\d)T.*/.exec(strdate);
							var date = RegExp.$3 + "/" + RegExp.$2 + "/" + RegExp.$1;
							
							var html = ""
								+ "<a href='" + link + "' target='_blank'>"
								+ "<span class='data_noticia'>"
								+ "Not&iacute;cia"
								+ "</span>"
								+ " - "
								+ "<span class='span_titular'>"
								+ title
								+ "</span>"
								+ "</a>"
							
							$("<div></div>")
								.html(html)
								.appendTo(ticker);
						});
				$('#content_ticker').stop();
				ACTUALITZANT = false;
				
				scroll();
			},
			error : function(XMLHttpRequest, textStatus, errorThrown) {
				//~ console.info(XMLHttpRequest);
				//~ console.info(textStatus);
				//~ console.info(errorThrown);
			}
		});
}

function scroll() {
	// Scroll a 20px / segons
	var height = 0;
	$('#content_ticker div').each(function() {
		height += $(this).height();
	});
	
	// Distancia entre la posició actual de content_ticker i la seva destinació
	var distancia = ($('#content_ticker').offset().top - $('#div_ticker').offset().top) + height;
	
	var durada = (distancia / 20) * 1000;
		
	$('#content_ticker')
		.animate(
				{top	: -1 * height}, 
				durada, 
				'linear',
				function() {
					$('#content_ticker').css({top : ($('#div_ticker').height() + 10) + 'px'});
					scroll();
				});
				
}
