jQuery('document').ready(function(){
    var hlive = jQuery('#header-live-container');
    var total_width = hlive.width();
    var speed = 0.05;
	var newslive = null;
	var liveThread = null;
	
	var process_entries = function(entries) {
		var width = total_width;
		if( newslive != entries ) {
			newslive = entries;
			var time_to_refresh = 5500;
			if ( entries.length > 0 ) {
				for ( var i = 0; i < entries.length ;  i++ ) {
					var entry = entries[i];
					var li =  jQuery('<li class="newsitem"><a href="'+entry.link+'" title="'+entry.title+'" >'+entry.summary+'</a></li>');
					hlive.append(li);
					var current_width = li.width();
					var current_duration = ( current_width + width ) / speed;
					li.css('left', width+'px' ).animate({'left':-current_width+'px'}, current_duration, 'linear', function() {
						jQuery(this).remove();
					} );
					width += current_width + 30;
				}
				var refreshing_time = (( width - total_width ) / speed);
				time_to_refresh = (refreshing_time > 5000) ? refreshing_time : 5500 ;
			}
			liveThread = setTimeout(refreshLive, time_to_refresh - 500 );
		}
	};
	
    var refreshLive = function(){
		jQuery.ajax({
			url: '/live.rss',
			type: 'GET',
			dataType: 'xml',
			context: hlive,
			error: function(jqXHR, textStatus, errorThrown){
				if ( textStatus == 'parsererror' ) {
					var list = jQuery(jqXHR.responseText.substring( jqXHR.responseText.indexOf('?>')+2 )).get(0).childNodes;
					var entries = [];
					for ( var i = 0; i < list.length ;  i++ ) {
						var entry = list[i];
						if ( entry.nodeName == 'entry' ) {
							var link = null;
							var title = null;
							var summary = null;
							for ( var j = 0; j < entry.childNodes.length ;  j++ ) {
								var n = entry.childNodes[j];
								switch ( n.nodeName ) {
									case 'link':
									case 'LINK':
										link = n.getAttribute('href');
										break;
									case 'title':
										title = n.firstChild.nodeValue;
										break;
									case 'summary':
										summary = n.firstChild.nodeValue;
										break;
								}
							}
							entries.push({
								link: link,
								title: title,
								summary: summary
							});
						}
					}
					process_entries(entries);
				}
			},
			success: function(data){
				var entries = [];
				jQuery('feed entry', data).each(function(){
					entries.push({
						link: jQuery('link, LINK',this).attr('href'),
						title: jQuery('title',this).text(),
						summary: jQuery('summary',this).text()
					});
				});
				process_entries(entries);
			}
		});
    };
    refreshLive();
});
