var MyPhone, incomingSession, outgoingSession, mediaStreamOptions;

function startRingTone() {
    try {
        document.getElementById('ringtone').play();
    }
    catch (e) {
    }
}

function stopRingTone() {
    try {
        document.getElementById('ringtone').pause();
    }
    catch (e) {
    }
}

function startRingbackTone() {
    try {
        document.getElementById('ringbacktone').play();
    }
    catch (e) {
    }
}

function stopRingbackTone() {
    try {
        document.getElementById('ringbacktone').pause();
    }
    catch (e) {
    }
}

var statusJsCall = "none";

function endJsCall() {
    if (statusJsCall == "accepted") {
        outgoingSession.bye();
    }
    if (statusJsCall == "incoming") {
        incomingSession.reject();
        if (document.getElementById("buttonAnswerCall"))
            document.getElementById("buttonAnswerCall").style.visibility = 'visible';
        if (document.getElementById("buttonRejectCall"))
            document.getElementById("buttonRejectCall").style.visibility = 'visible';
    }
    if (statusJsCall == "answered") {
        console.log('terminate')
        incomingSession.terminate();
    }
    if (statusJsCall == "outgoing") {
        outgoingSession.cancel();
    }
    statusJsCall = "none";
}

function startJsCall(phone) {
    startRingbackTone();
    statusJsCall = "outgoing";
    outgoingSession = MyPhone.invite(phone, mediaStreamOptions);

    outgoingSession.on('bye', function (request) {
        stopRingbackTone();
        console.log("outgoingSession bye");
    });

    outgoingSession.on('cancel', function (request) {
        stopRingbackTone();
        console.log("outgoingSession cancel");
    });

    outgoingSession.on('terminated', function (request) {
        stopRingbackTone();
        asterisk_window_ended();
        console.log("outgoingSession terminated");
    });

    outgoingSession.on('failed', function (request) {
        stopRingbackTone();
        console.log("outgoingSession failed");
    });

    outgoingSession.on('rejected', function (request) {
        stopRingbackTone();
        cbNotifyObject.closeEventTooltip(999, 'asterisk');
        console.log("outgoingSession rejected");
    });

    outgoingSession.on('accepted', function (request) {
        stopRingbackTone();
        statusJsCall = "accepted";
        asterisk_window_active('outgoing');
        console.log("outgoingSession accepted");
    });

    outgoingSession.on('progress', function (request) {
        console.log("outgoingSession progress");
    });
}

function answerJsCall() {
    stopRingTone();
    statusJsCall = "answered"
    incomingSession.accept(mediaStreamOptions);
}

$(document).ready(function () {

    mediaStreamOptions = {
        media: {
            constraints: {
                audio: true,
                video: false
            },
            render: {
                remote: document.getElementById('remoteAudio'),
                local: document.getElementById('localAudio')
            }
        }
    };

    var configuration = {
        'wsServers': ['wss://' + asterisk_server + ':8089/ws'],
        'authorizationUser': main_server + '_' + asterisk_login,
        'uri': 'sip:' + main_server + '_' + asterisk_login + '@' + asterisk_server,
        'password': asterisk_password,
        'stunServers': ['stun:stun.l.google.com:19302', 'stun:stun.ekiga.net', 'stun:stun.sipnet.ru'],
        'hackWssInTransport': true,
        'registerExpires': 50,
        'rtcpMuxPolicy': 'negotiate',
        'log': {'level': 2}
    };

    MyPhone = new SIP.UA(configuration);

    MyPhone.on('invite', function (session) {
        startRingTone();
        statusJsCall = "incoming";
        incomingSession = session;

        var phone = incomingSession.request.from.uri.user;
        if (phone.substring(0, main_server.length) == main_server) { // internal number.
            phone = phone.substring(main_server.length + 1)
        }
        $.ajax({
            type: "POST",
            url: "modules/asterisk/asterisk_functions.php",
            data: {sel: 'open', type: 'client', phone: phone, csrf: csrf},
            success: function (msg) {
                if (msg) {
                    asterisk_window_connecting(phone, msg, 'incoming')
                }
            }
        });

        incomingSession.on('bye', function (request) {
            stopRingTone();
            console.log("incomingSession bye");
        });

        incomingSession.on('cancel', function (request) {
            stopRingTone();
            console.log("incomingSession cancel");
        });

        incomingSession.on('terminated', function (request) {
            stopRingTone();
            asterisk_window_ended();
            console.log("incomingSession terminated");
        });

        incomingSession.on('failed', function (request) {
            stopRingTone();
            console.log("incomingSession failed");
        });

        incomingSession.on('rejected', function (request) {
            stopRingTone();
            cbNotifyObject.closeEventTooltip(999, 'asterisk');
            console.log("incomingSession rejected");
        });

        incomingSession.on('accepted', function (request) {
            stopRingTone();
            asterisk_window_active('incoming');
            console.log("incomingSession accepted");
        });

        incomingSession.on('progress', function (request) {
            stopRingTone();
            console.log("incomingSession progress");
        });
    });
});