var integrationEnabled = true;

$(function () {
    c2c();
    drawOperatorStatus();
});

OperatorStatus = {
    End: 0,
    Start: 1,
    Unpause: 2,
    Pause: 3
}

function drawOperatorStatus() {
    if ($("#opstatus").size()) {
        $.ajax({
            type: "GET",
            url: base + "api/asterisk/getstatus",
            contentType: 'application/json; charset=utf-8',
            dataType: "json",
            success: function (response) {
                if (response === OperatorStatus.Start || response === OperatorStatus.Unpause) {
                    $("#opstatus").html('<i class="fa fa-play-circle-o" aria-hidden="true"></i>')
                    $("#opstatus").css('color', "#29913c");
                } else {
                    $("#opstatus").css('color', "#bf3d30");
                    if (response === OperatorStatus.End) {
                        $("#opstatus").html('<i class="fa fa-stop-circle-o"></i>')
                    }
                    if (response === OperatorStatus.Pause) {
                        $("#opstatus").html('<i class="fa fa-pause-circle-o"></i>')
                    }
                }
            }
        }).fail(function (jqXHR, textStatus, errorTrown) {
            $("#opstatus").html('<i class="fa fa-question" aria-hidden="true"></i>');
            $("#opstatus").css('color', "#bf3d30");
        });
    }
}

function formatPhoneNumber(phone){
	if (phone === null || phone === undefined || phone === "" || phone.startsWith("ext"))
		return phone;
	if(!/(^(8|\+\d{1,3})\d{10}$)/.test(phone))
		return phone;
	var regex = /(^(8|\+\d{1,3})(\d{3})(\d{3})(\d{2})(\d{2})$)/gm;
	return phone.replace(regex, '$2($3)$4-$5-$6');
}

function phoneReplacer(number){
    return '<a class="clicktocall" onclick="return callAsterisk(\'' + number + '\')"><i class="fa fa-phone-square big"><span>' + formatPhoneNumber(number) + '</span></i></a>';
}

function c2c(selector) {
    if (!integrationEnabled)
        return false;

    var regex = /(?:(?:8|\+\d{1,3})\d{10})(?!.+\"|["'_\]\w])|(?:\bext\d+)(?!["'_\]\w])/gmi

    if (selector === null || selector === undefined)
        selector = "#wrapper";

    $selector = $(selector);
    if ($selector.length === 0) //Мы пришли не из _Layout...
        return false;

    var taContent = [];
    var inputValues = [];
    $(selector + " textarea").each(function (idx, elem) {
        taContent.push($(elem).html());
        $(elem).html("");
    })

    $(selector + " input").each(function (idx, elem) {
        inputValues.push($(elem).val());
        $(elem).val("");
    })

    var text = $selector.html();
    text = text.replace(regex, phoneReplacer);
    $selector.html(text);

    $(selector + " textarea").each(function (idx, elem) {
        $(elem).html(taContent[idx]);
    })

    $(selector + " input").each(function (idx, elem) {
        $(elem).val(inputValues[idx]);
    })
    return false;
}

function loadOperatorMenu() {
    $("#operatorMenu").load(base + "asterisk.ivp/operatormenu", function () {
        if (!$('#operatorMenuOverlay').length) {
            $('body').append('<div id="operatorMenuOverlay" style="position: fixed;width: 100%;height: 100%;top: 0px;left: 0px; background: rgba(0,0,0,.4)"></div>');
            $('#operatorMenuOverlay').click(function (e) {
                e.preventDefault();
                $("#operatorMenuOverlay").fadeOut(500);
                $("#operatorMenu").fadeOut(500);
                drawOperatorStatus();
            })
            $("body").on("change","#mainphone", setMainPhone);
        }
    });
}

function showOperatorMenu() {
    loadOperatorMenu();
    $("#operatorMenuOverlay").fadeIn(500);
    $("#operatorMenu").fadeIn(500);
}

function setMainPhone() {
    var params = JSON.stringify($("#mainphone").val());

    $.ajax({
        type: "POST",
        url: base + "api/asterisk/setmainphone",
        data: params,
        contentType: 'application/json; charset=utf-8',
        dataType: "json",
        success: function (response) {
            if (response.hasOwnProperty("IsOK") && !response.IsOK) {
                $('#mainphone').css('border', "solid 1px red");
                alert(response.Description);
                return;
            }
            $("#operatorMenu").data("loaded", false);
            $("#operatorMenuOverlay").fadeOut(500);
            $("#operatorMenu").fadeOut(1000);
        }
    }).fail(function (jqXHR, textStatus, errorTrown) {
        $('#mainphone').css('border', "solid 1px red");
        if (jqXHR.hasOwnProperty("responseText")) {
            var result = JSON.parse(jqXHR.responseText);
            if (result.hasOwnProperty("Message")) {
                alert(result.Message);
                return;
            }
        }
        alert(errorTrown);
    });
}

function changeOperatorStatus(that) {
    var $that = $(that);
    if ($that.is(":disabled"))
        return;

    var params = ""

    if ($that.is(":checked")) {
        params = JSON.stringify(OperatorStatus.Start); 
        $("#calltr").removeClass("disabled");
        $("#playpause").removeAttr("disabled");
        $("#playpause").prop("checked", true);
    }
    else {
        params = JSON.stringify(OperatorStatus.End);
        $("#calltr").addClass("disabled");
        $("#playpause").prop("checked", false);
        $("#playpause").attr("disabled", 1);
    }
    $.ajax({
        type: "POST",
        url: base + "api/asterisk/changestatus",
        data: params,
        contentType: 'application/json; charset=utf-8',
        dataType: "json",
        success: function (response) {
            if (response.hasOwnProperty("IsOK") && !response.IsOK) {
                alert(response.Description);
            }
            loadOperatorMenu();
        }

    }).fail(function (jqXHR, textStatus, errorTrown) {
        if (jqXHR.hasOwnProperty("responseText")) {
            var result = JSON.parse(jqXHR.responseText);
            if (result.hasOwnProperty("Message")) {
                alert(result.Message);
                loadOperatorMenu();
                return;
            }
        }
        alert(errorTrown);
        loadOperatorMenu();
    });
}

function changeWorkStatus(that) {
    var $that = $(that);
    if ($that.is(":disabled"))
        return;
    var params = "";
    if ($that.is(":checked"))
        //Если нужно будет вести статистику переходов статусов,
        //здесь нужно будет передавать Unpause
        params = JSON.stringify(OperatorStatus.Start); 
    else
        params = JSON.stringify(OperatorStatus.Pause); 

    $.ajax({
        type: "POST",
        url: base + "api/asterisk/changestatus",
        data: params,
        contentType: 'application/json; charset=utf-8',
        dataType: "json",
        success: function (response) {
            if (response.hasOwnProperty("IsOK") && !response.IsOK) {
                alert(response.Description);
            }
            loadOperatorMenu();
        }

    }).fail(function (jqXHR, textStatus, errorTrown) {
        if (jqXHR.hasOwnProperty("responseText")) {
            var result = JSON.parse(jqXHR.responseText);
            if (result.hasOwnProperty("Message")) {
                alert(result.Message);
                loadOperatorMenu();
                return;
            }
        }
        alert(errorTrown);
        loadOperatorMenu();
    });
}

function callAsterisk(phoneNumber) {
    if (confirm(AsteriskResources.CallNumber + phoneNumber + "?") == false)
        return;
    params = JSON.stringify(phoneNumber);
    $.ajax({
        type: "POST",
        url: base + "api/asterisk/call",
        data: params,
        contentType: 'application/json; charset=utf-8',
        dataType: "json",
        success: function (response) {
            if (response.hasOwnProperty("IsOK") && !response.IsOK) {
                alert(response.Description);
                return;
            }
        }
    }).fail(function (jqXHR, textStatus, errorTrown) {
        if (jqXHR.hasOwnProperty("responseText")) {
            var result = JSON.parse(jqXHR.responseText);
            if (result.hasOwnProperty("Message")) {
                alert(result.Message);
                return;
            }
        }
        alert(errorTrown);
    });
    return false;
}