function subscribeForQueueEvents(queue_id)
{
    ws.command({
        name: "subscribeQueueEvents",
        type:"command",
        data:{queue_id:queue_id},
        uuid: ws.generateUUID()
    });
}

function initCallGrid(queue_id)
{
    ws.command({
        name:"requestQueueCalls",
        type:"command",
        data:{queue_id:queue_id},
        uuid: ws.generateUUID()
    });
}

function updateCallGrid(call)
{
    if (isDisplayedCall(call)) {
        updateDisplayedCall(call);
    } else {
        addCallToGrid(call);
    }
}

function isDisplayedCall(call) 
{
    if ($("#call-grid tbody tr[data-callid='"+call.callid+"']").length > 0) {
        return true;
    }
    return false;
}

function addCallToGrid(call)
{
    if (parseInt(call.state) > 2) {
        return;
    }
    
    call.timestamp = convertDatetimeToUserFormat(call.timestamp);
    
    var prototypeRow = $("#call-grid tbody tr:first-child").clone();
    prototypeRow.removeClass("hideRow");
    prototypeRow.attr("data-callid",call.callid);
    $.each(call, function (key, value) {
        prototypeRow.find("."+key).text(value);
    });
    setCallState(prototypeRow,call);
    if(parseInt(call.state) === 1) {
        if (transferCallFromPermissions.indexOf(call.queue_extension) !== -1) {
            initDraggable(prototypeRow);
        }
    }
    
    $("#call-grid tbody").append(prototypeRow);
}

function updateDisplayedCall(call)
{
    var row = $("#call-grid tbody tr[data-callid='"+call.callid+"']");
    
    if (parseInt(call.state) > 2 ) {
        removeDisplayedCall(row, call);
        return;
    }
    
    call.timestamp = convertDatetimeToUserFormat(call.timestamp);
    
    $.each(call, function (key, value) {
        row.find("." + key).text(value);
    });
    setCallState(row,call);
    if(parseInt(call.state) === 1) {
        disableDraggable(row);
    }
}

function removeDisplayedCall(row, call)
{
    setCallState(row, call);
    setTimeout(function () {
        row.addClass("fade").addClass("out");

        var agentUserId = $("#agent-grid tbody .icon-phone[data-callid='" + call.callid + "']").closest("tr").data("userid");
        var agentExtension = $("#agent-grid tbody .icon-phone[data-callid='" + call.callid + "']").closest("div").data("target");
        var agentCallIcon = $("#agent-grid tbody .icon-phone[data-callid='" + call.callid + "']").parent().removeClass("in").addClass("out");

        setTimeout(function () {
            agentCallIcon.remove();
            setDefaultCallStatus(
                    $("#agent-grid tbody tr[data-userid='" + agentUserId + "']"),
                    {
                        userId: agentUserId,
                        agent_extension: agentExtension
                    }
            );
            row.remove();
        }, 300);
    }, 1000);
}

function setCallState(row, call)
{
    row.find(".state").text("");
    var stateIconContainer = row.find(".state div");
    stateIconContainer = $("<div />");
    stateIconContainer.addClass("draggable");
    
    setIconColorClass(stateIconContainer,call);
    
    setIconColorClass($("#agent-grid tbody .icon-phone[data-callid='"+call.callid+"']").parent(),call);
    row.find(".state").append(stateIconContainer);
}

function setIconColorClass(iconContainer,call) 
{
    var icon  = $("<i />");
    iconContainer.find("i").remove();
    
    icon.addClass("icon-phone");
    icon.css("font-size","25px");
    icon.attr("data-callid", call.callid);
    icon.attr("data-queueid", call.queue_id);
    
    switch(parseInt(call.state)) {
        //case "0": // Unkown
        case 1: // Ringing
            icon.addClass("pickedCall");            
        break;  
//        case 3: // Hangedup
//        case 4:  // Forwarded
//        case 5:  // Blindtransfered
//        case 6:  // Attendedtransfered
        case 7:  // Missed
            icon.addClass("missedCall");
        case 8:  // Success
        case 2: // Answered
            icon.addClass("successCall");
            break;
        case 9:  // Picked
            icon.addClass("forwardedCall");
            break;
        default:
            icon.css("color","gray");
    }
    
    iconContainer.append(icon);
}

function initDraggable(row) 
{
    if (typeof row !== "undefined") { // hidden row fix
        row.find(".draggable").draggable({ helper: "clone" });
    }
}

function disableDraggable(row)
{
    if (typeof row !== "undefined") { // hidden row fix
        row.find(".draggable").draggable( "disable" );
    }
}

function convertDatetimeToUserFormat(datetime) {

    if (typeof timezoneInSec === 'undefined' || timezoneInSec === '') {
        timezoneInSec = 0;
    }

    if (typeof userTimeFormat === 'undefined' || userTimeFormat === '') {
        userTimeFormat = 'd.m.Y';
    }

    var callDateTime = datetime.split(' ');
    var callDate = callDateTime[0].split('-');
    var callTime = callDateTime[1].split(':');
    var currentDateObj = new Date(callDate[0], parseInt(callDate[1]) - 1 , callDate[2], callTime[0], callTime[1], callTime[2], '0');
    var timestamp = (currentDateObj.getTime() / 1000) + parseInt(timezoneInSec);
    var newDateObj = new Date(timestamp * 1000);

    var time = addZero(newDateObj.getHours()) + ":" + addZero(newDateObj.getMinutes()) + ":" + addZero(newDateObj.getSeconds());
    var day = addZero(newDateObj.getDate());
    var month = addZero(parseInt(newDateObj.getMonth() + 1));
    var year = newDateObj.getFullYear();

    var result = day + "." + month + "." + year + " " + time;

    if (userTimeFormat === 'Y-m-d') {
        result = year + "-" + month + "-" + day + " " + time;
    } else if (userTimeFormat === 'm/d/Y') {
        result = month + "/" + day + "/" + year + " " + time;
    }
    return result;
}

function addZero(i) {
    if (i < 10) {
        i = "0" + i;
    }
    return i;
}