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") {

        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();
    });

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

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

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

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

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

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

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();
        });

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

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

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

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

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

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