var counter;
var countDownTime;
var lastID;
var currentID;
var maxRows;
var maxUpcoming;
var numRows;
var numUpcoming;
var oddeven;

function countDown() {
	countDownTime--;
	if (countDownTime <= -1) {
		$("span#remaining").html("Updating...");
		setTimeout("updateList()", 4000);
		return;
	}
	if(currentID == lastID)
		$("span#remaining").html(formatSeconds(countDownTime));
	clearTimeout(counter);
	counter = setTimeout("countDown()", 1000);
}
function getSong(id) {
	$.getJSON("/json.php?type=songid&id="+id,
		function(data){
			updateCurrent(data);
		});
}

function makeRow(data, picture) {
	output = '<tr><td>';
	if(picture)
		output += '<div class="song"><a href="'+data.buycd+'" target="_blank"><img width="100px" height="100px" src="/pictures/'+data.picture+'" alt="Cover" /></a><a href="" onclick="getSong('+data.id+'); return false;">'+data.artist+'<br />'+data.title+'</a></div>';
	else
		output += '<a href="" onclick="getSong('+data.id+'); return false;">'+data.artist+'<br />'+data.title+'</a>';
	output += "</td><td>";
	if(data.userrating != undefined)
		output += "["+data.userrating+"]<br />";
	output += data.rating+"/10";
	output += "</td><td>";
	output += data.album;
	output += "</td><td>";
	output += formatSeconds(data.length);
	output += "</td></tr>";
	return output;
}
function getUpcoming() {
	numUpcoming++;
	$.getJSON("/json.php?type=upcoming&offset="+numUpcoming,
		function(data){
			$("table#upcoming tbody:first").append(makeRow(data, false));
			if((data.count >= numUpcoming)&&(numUpcoming < maxUpcoming))
				getUpcoming();
		});
}
function updateList() {
	$.getJSON("/json.php?type=nowplaying",
		function(data){
			if(lastID == data.id) {
				countDownTime = 10;
				countDown();
				return;
			}
			lastID = data.id;
			numRows++;
			numUpcoming--;
			updateCurrent(data);
			$("table#list tbody:first").prepend(makeRow(data, true));
			$("table#list tbody:first > tr:last-child").remove();
			$("table#upcoming tbody:first > tr:first-child").remove();
			$("span#upcomingcount").html(data.count);
			$("span#listenercount").html(data.listeners);
			
			getUpcoming();
		});	
}