
var GRID_PUBLIC_ID
    ,KNOWN_VERSION = 0
    ,GRID;

function doGet(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function(e) {
        if (xhr.readyState === 4) {
            var resp = null;

            if (xhr.status === 200) {
                resp = xhr.response;
                try {
                    resp = JSON.parse(/** @type {string} */ (resp));
                } catch (e) {
                    resp = null;
                }
            }
            callback(resp);
        }
    };
    xhr.open('GET', url, true);
    xhr.send(null);
}

function initPolling() {
    doGet("/api/poll?grid=" +GRID_PUBLIC_ID +"&v=" +KNOWN_VERSION, function(resp) {
        GRID = new Grid(resp);
        if (resp["grid"]) {
            KNOWN_VERSION = Math.max(GRID.update(resp["grid"]) || 0, KNOWN_VERSION);
            uiCreateGrid();
        }
    });
}

document.addEventListener('DOMContentLoaded', function() {
    GRID_PUBLIC_ID = (document.location.hash.substr(1));

    if (GRID_PUBLIC_ID == "") {
        document.location.href = "/";
        return;
    }
    initPolling();
});

