
var UI_PLAYERS = {};

function uiCreatePlayer(player) {
    var dom = dCreate("li")
        ,playerName = dCreate("span");

    playerName.className = R.klass.scoreboard.player.name;
    playerName.textContent = player.name;
    dom.appendChild(playerName);
    dom.score = dCreate("span");
    dom.score.className = R.klass.scoreboard.player.score;
    dom.appendChild(dom.score);
    dom.style.color = player.color;
    return dom;
}

function onPlayersUpdated() {
    var container
        ,playerIds = [];

    for (var i in GRID.players) {
        var uiPlayer = UI_PLAYERS[i];

        if (!uiPlayer) {
            uiPlayer = UI_PLAYERS[i] = uiCreatePlayer(GRID.players[i]);
            if (i === GRID.playerSelf.id)
                uiPlayer.classList.add(R.klass.scoreboard.player.isMe);
            if (!container)
                container = dGet(R.id.scoreboard.players);
            container.appendChild(uiPlayer);
        }
        uiPlayer.score.textContent = GRID.players[i].score;
        playerIds.push(i);
    }
    playerIds.sort(function(a, b) {
        return GRID.players[b].score - GRID.players[a].score;
    });
    for (var i =0, nbPlayers = playerIds.length; i <nbPlayers; i++) {
        UI_PLAYERS[playerIds[i]].style.order = i;
    }
}

(function() {
var timeInterval = setInterval(function() {
    if (GRID) {
        var ellapsed = (GRID.gridTime !== null ? GRID.gridTime : (Date.now() -GRID.startTime)) / 1000;

        var seconds = Math.floor(ellapsed % 60);
        ellapsed = (ellapsed - seconds) / 60;
        var minutes = Math.floor(ellapsed % 60);
        ellapsed = Math.floor((ellapsed - minutes) / 60);

        var text = ellapsed ? (ellapsed +":") : ''; //hours
        text += (minutes < 10 ? '0' : '') +minutes +":";
        text += (seconds < 10 ? '0' : '') +seconds;

        dGet(R.id.scoreboard.header.time).textContent = text;

        if (GRID.gridTime) {
            clearInterval(timeInterval);
            timeInterval = null;
        }
    }
}, 1000);
})();
