var defaultOnMessage = ws.onmessage;
ws.onmessage = function (e) {
    var msg = jQuery.parseJSON(e.data);
    switch (msg.name) {
        case "login":
            console.log(msg);
            if (typeof initDraggable === "function") {
                initCallOverview();
                initDraggable();
            }
            
            if (typeof requestQueueAgents === "function") {
                initQueueOverview();
            }
            break;
        case "requestQueueCalls":
            console.log(msg);
            if (typeof updateCallGrid === "function") {
                $.each(msg.data.items, function (i, item) {
                    updateCallGrid(item);
                });
            }
            if (typeof setCallCount === "function") {
                
                setCallCount(msg.data.items);
            }
            break;
        case "queueCallChanged":
            console.log(msg);
            if (typeof updateCallGrid === "function") {
                updateCallGrid(msg.data);
            }
            break;
        case "requestQueueAgents":
            console.log(msg);
            if (typeof updateAgentGrid === "function") {
                $.each(msg.data.items, function (i, item) {
                    updateAgentGrid(item);
                });
            }
            if (typeof setAgentCount === "function") {
                setAgentCount(msg.data.items);
            }
            break;
        case "agentChanged":
            console.log(msg);
            if (typeof updateDisplayedAgent === "function") {
                updateDisplayedAgent(msg.data.agent);
            }
            break;
        case"agentDeleted":
            console.log(msg);
            if (typeof removeDisplayedAgentFromQueue === "function") {
                removeDisplayedAgentFromQueue(msg.data.agent);
            }
            break;
        case "updateUserPresence":
            if (typeof updateAgentPhonePresence === "function") {
                updateAgentPhonePresence(msg.data);
            }
            defaultOnMessage(e);
        break;
        case "":
            console.log("login failed !");

        default:
            defaultOnMessage(e);
    }
};

function initCallOverview()
{
    var timeout = 50;
    $.each(queue_ids, function (i, queue_id) {
        subscribeForQueueEvents(queue_id);
        setTimeout(function () {
            initCallGrid(queue_id);
        }, timeout);
        timeout = timeout + 50;
        setTimeout(function () {
            initAgentGrid(queue_id);
        }, timeout);
        timeout = timeout + 50;
    });
}

function initQueueOverview()
{
    requestQueueAgents(queue_id);
    requestQueueCalls(queue_id);
}