// externally defined variables
var i18n_notitle = 'Tune In!';
var i18n_serverdown = 'Server is currently down.';

// constants
var now_playing_url = 'x-now-playing.cgi?';

// internal variables
var cycle_start_time;
var max_time_to_wait = 15000;
var min_time_to_wait = 5000;
var max_title_length = 40;
var serverdown = '_SERVERDOWN_';

//
function updateAllStreams() {
    if ($("a.htrack").size() > 0) {
	updateNextStream(0);
    }
}

//
function updateNextStream(next_i) {
    if (next_i == 0) {
	cycle_start_time = new Date().getTime();
    }
    if (next_i >= $("a.htrack").size()) {
	var time_to_wait = max_time_to_wait - (new Date().getTime() - cycle_start_time);
	if (time_to_wait < min_time_to_wait) {
	    time_to_wait = min_time_to_wait;
	}
	setTimeout(function() { updateNextStream(0); }, time_to_wait);
    }
    else {
	var s = $("a.htrack").eq(next_i).attr('href');
	var i = s.indexOf(';');
	if (i > 0) {
	    $.post(now_playing_url, {
		tracker_url: s.substr(0, i),
	    }, function(xml) {
		//$("a.htrack").eq(next_i).find('span').html(xml);
		var o = $("a.htrack").eq(next_i).find('span').eq(0);
		var newt = trim_to_length(max_title_length, xml.trim());
		if (newt == '') newt = i18n_notitle;
		else if (newt == serverdown) newt = i18n_serverdown;
		if (newt != o.html()) {
		    o.fadeOut('slow', function() { o.html(newt); o.fadeIn(); });
		}
		updateNextStream(++next_i);
	    });
	}
	else {
	    updateNextStream(++next_i);
	}
    }
}

function trim_to_length(max_length, txt) {
    var l = txt.length;
    if (l > max_length) {
	txt = txt.substr(0, max_length) + '...';
    }
    return txt;
}

$(document).ready(function() {
    updateAllStreams();
});

// eof
