addWindowOnLoadListener( setup );


function setup() {
	//addOkButtonsToDialogs(getElementsWithMatchingID( "-confirmation-dialog" ));
	if (getElementById("dialog").innerHTML != "") {
		if (getElementById("error-details").innerHTML!="")
			getElementById("wge-details").innerHTML=getElementById("error-details").innerHTML;
		showDialog( getElementById("dialog").innerHTML+"-confirmation-dialog" );
	}
    fetchData();
    setInterval( fetchData, 3000 );
}

function fetchData() {
    invokeRemoteAction( "getGames", parseGamesList );
}

function parseGamesList( text ) {
    var jsonExpression = "(" + text + ")";
    var games = eval( jsonExpression );
    
    if ( games.length == 0 ) {
        getElementById("no-games").style.display = "block";
        getElementById("games").style.display = "none";
    } else {
        var table = getElementById("games-table");
        var tableBody = getElementById("games-body");
        if ( tableBody != null ) {
            table.removeChild( tableBody );            
        }
        tableBody = document.createElement("tbody");
        tableBody.id = "games-body";

        var row, cell, button;
        for ( var i=0; i<games.length; i++ ) {
            row = document.createElement("tr");
            // ID
            cell = document.createElement("td");
            cell.innerHTML = i+1;//games[i][0];
            cell.height = "43px";
            cell.style.height = "43px";
            row.appendChild(cell);
            // Game's host
            cell = document.createElement("td");
            cell.innerHTML = games[i][1];
            row.appendChild(cell);
            // Number of players
            cell = document.createElement("td");
            cell.innerHTML = games[i][3] + "/" + games[i][2];
            row.appendChild(cell);
            // Actions
            cell = document.createElement("td");
			button = document.createElement("a");
			button.className = "button";
			button.id = "join-game-" + games[i][0];
			button.href = "newGame.jsp?gameId=" + games[i][0];
			if (games[i][4]) 
				button.innerHTML = getElementById( "rejoin" ).innerHTML;
			else
				button.innerHTML = getElementById( "join" ).innerHTML;
			cell.appendChild( button );
			button = document.createElement("a");
			button.className = "button";
			button.id = "game-details-" + games[i][0];
			button.href = "javascript:void(0)";//gameDetails.jsp?gameId=" + games[i][0];
			button.innerHTML = getElementById( "details" ).innerHTML;
			//cell.appendChild( button );
            row.appendChild(cell);
            tableBody.appendChild(row);
        }
        table.appendChild( tableBody );
        refreshTable();
        getElementById("no-games").style.display = "none";
        getElementById("games").style.display = "block";
    }
}

function refreshTable() {
    var rows = getElementsByTagName("tr");
    var i;
    for ( i=0; i<rows.length; i++ ) {
        rows[i].className = (i%2==0) ? "even" : "odd";
    }
}
