/**
 *  Copyright (C) 2021  Double Bastion LLC
 *
 *  This file is part of Roundpin, which is licensed under the
 *  GNU Affero General Public License Version 3.0. The license terms
 *  are detailed in the "LICENSE.txt" file located in the root directory.
 *
 *  This is a modified version of the original file
 *  "phone.js", first modified in 2020.
 *
 *  The original "phone.js" file was written by Conrad de Wet.
 *  We thank Conrad de Wet for his work and we list below
 *  the copyright notice of the original "phone.js" file:

/*
-------------------------------------------------------------
 Copyright (c) 2020  - Conrad de Wet - All Rights Reserved.
=============================================================
File: phone.js
License: GNU Affero General Public License v3.0
Version: 0.1.0
Owner: Conrad de Wet
Date: April 2020
Git: https://github.com/InnovateAsterisk/Browser-Phone
*/

// Global Settings
// ===============
var enabledExtendedServices = false;
var enabledGroupServices = false;

// Lanaguage Packs (lang/xx.json)
// ===============
// Note: The following should correspond to files on your server.
// eg: If you list "fr" then you need to add the file "fr.json".
// Use the "en.json" as a template.
// More specific lanagauge must be first. ie: "zh-hans" should be before "zh".
// "en.json" is always loaded by default
const availableLang = ["ja", "zh-hans", "zh", "ru", "tr", "nl"];

// User Settings & Defaults
// ========================
var wssServer = getDbItem("wssServer", null);
var profileUserID = getDbItem("profileUserID", null);
var profileUser = getDbItem("profileUser", null);
var profileName = getDbItem("profileName", null);
var WebSocketPort = getDbItem("WebSocketPort", null);
var ServerPath = getDbItem("ServerPath", null);
var SipUsername = getDbItem("SipUsername", null);
var SipPassword = getDbItem("SipPassword", null);
var StunServer = getDbItem("StunServer", "");

var TransportConnectionTimeout = parseInt(getDbItem("TransportConnectionTimeout", 15));        // The timeout in seconds for the initial connection to make on the web socket port
var TransportReconnectionAttempts = parseInt(getDbItem("TransportReconnectionAttempts", 99));  // The number of times to attempt to reconnect to a WebSocket when the connection drops.
var TransportReconnectionTimeout = parseInt(getDbItem("TransportReconnectionTimeout", 15));    // The time in seconds to wait between WebSocket reconnection attempts.

var userAgentStr = getDbItem("UserAgentStr", "Roundpin (SipJS - 0.11.6)");          // Set this to whatever you want.
var hostingPrefex = getDbItem("HostingPrefex", "");                                 // Use if hosting off root directiory. eg: "/phone/" or "/static/"
var RegisterExpires = parseInt(getDbItem("RegisterExpires", 300));                  // Registration expiry time (in seconds)
var WssInTransport = (getDbItem("WssInTransport", "1") == "1");                     // Set the transport parameter to wss when used in SIP URIs. (Required for Asterisk as it doesnt support Path)
var IpInContact = (getDbItem("IpInContact", "1") == "1");                           // Set a random IP address as the host value in the Contact header field and Via sent-by parameter. (Suggested for Asterisk)
var IceStunCheckTimeout = parseInt(getDbItem("IceStunCheckTimeout", 500));  // Set amount of time in milliseconds to wait for the ICE/STUN server
var AutoAnswerEnabled = (getDbItem("AutoAnswerEnabled", "0") == "1");       // Automatically answers the phone when the call comes in, if you are not on a call already
var DoNotDisturbEnabled = (getDbItem("DoNotDisturbEnabled", "0") == "1");   // Rejects any inbound call, while allowing outbound calls
var CallWaitingEnabled = (getDbItem("CallWaitingEnabled", "1") == "1");     // Rejects any inbound call if you are on a call already.
var RecordAllCalls = (getDbItem("RecordAllCalls", "0") == "1");             // Starts Call Recording when a call is established.
var StartVideoFullScreen = (getDbItem("StartVideoFullScreen", "1") == "0"); // Starts a vdeo call in the full screen (browser screen, not dektop)
var AutoGainControl = (getDbItem("AutoGainControl", "1") == "1");           // Attempts to adjust the microphone volume to a good audio level. (OS may be better at this)
var EchoCancellation = (getDbItem("EchoCancellation", "1") == "1");         // Attemots to remove echo over the line.
var NoiseSuppression = (getDbItem("NoiseSuppression", "1") == "1");         // Attempts to clear the call qulity of noise.
var MirrorVideo = getDbItem("VideoOrientation", "rotateY(180deg)");         // Displays the self-preview in normal or mirror view, to better present the preview. 
var maxFrameRate = getDbItem("FrameRate", "");                              // Suggests a frame rate to your webcam if possible.
var videoHeight = getDbItem("VideoHeight", "");                             // Suggests a video height (and therefore picture quality) to your webcam.
var videoAspectRatio = getDbItem("AspectRatio", "");                        // Suggests an aspect ratio (1:1 | 4:3 | 16:9) to your webcam.
var NotificationsActive = (getDbItem("Notifications", "0") == "1");
var StreamBuffer = parseInt(getDbItem("StreamBuffer", 50));                 // The amount of rows to buffer in the Buddy Stream
var PosterJpegQuality = parseFloat(getDbItem("PosterJpegQuality", 0.6));    // The image quality of the Video Poster images
var VideoResampleSize = getDbItem("VideoResampleSize", "HD");               // The resample size (height) to re-render video that gets presented (sent). (SD = ???x360 | HD = ???x720 | FHD = ???x1080)
var RecordingVideoSize = getDbItem("RecordingVideoSize", "HD");             // The size/quality of the video track in the recodings (SD = 640x360 | HD = 1280x720 | FHD = 1920x1080)
var RecordingVideoFps = parseInt(getDbItem("RecordingVideoFps", 12));       // The Frame Per Second of the Video Track recording
var RecordingLayout = getDbItem("RecordingLayout", "them-pnp");             // The Layout of the Recording Video Track (side-by-side | us-pnp | them-pnp | us-only | them-only)
var DidLength = parseInt(getDbItem("DidLength", 6));                        // DID length from which to decide if an incoming caller is a "contact" or an "extension".
var MaxDidLength = parseInt(getDbItem("maximumNumberLength", 16));          // Maximum langth of any DID number including international dialled numbers.
var DisplayDateFormat = getDbItem("DateFormat", "YYYY-MM-DD");              // The display format for all dates. https://momentjs.com/docs/#/displaying/
var DisplayTimeFormat = getDbItem("TimeFormat", "h:mm:ss A");               // The display format for all times. https://momentjs.com/docs/#/displaying/
var Language = getDbItem("Language", "auto");                               // Overrides the langauage selector or "automatic". Must be one of availableLang[]. If not defaults to en. Testing: zh-Hans-CN, zh-cmn-Hans-CN, zh-Hant, de, de-DE, en-US, fr, fr-FR, es-ES, sl-IT-nedis, hy-Latn-IT-arevela

// Permission Settings
var EnableTextMessaging = (getDbItem("EnableTextMessaging", "1") == "1");               // Enables the Text Messaging
var DisableFreeDial = (getDbItem("DisableFreeDial", "0") == "1");                       // Removes the Dial icon in the profile area, users will need to add buddies in order to dial.
var DisableBuddies = (getDbItem("DisableBuddies", "0") == "1");                         // Removes the Add Someone menu item and icon from the profile area. Buddies will still be created automatically. 
var EnableTransfer = (getDbItem("EnableTransfer", "1") == "1");                         // Controls Transfering during a call
var EnableConference = (getDbItem("EnableConference", "1") == "1");                     // Controls Conference during a call
var AutoAnswerPolicy = getDbItem("AutoAnswerPolicy", "allow");                          // allow = user can choose | disabled = feature is disabled | enabled = feature is always on
var DoNotDisturbPolicy = getDbItem("DoNotDisturbPolicy", "allow");                      // allow = user can choose | disabled = feature is disabled | enabled = feature is always on
var CallWaitingPolicy = getDbItem("CallWaitingPolicy", "allow");                        // allow = user can choose | disabled = feature is disabled | enabled = feature is always on
var CallRecordingPolicy = getDbItem("CallRecordingPolicy", "allow");                    // allow = user can choose | disabled = feature is disabled | enabled = feature is always on
var EnableAccountSettings = (getDbItem("EnableAccountSettings", "1") == "1");           // Controls the Account tab in Settings
var EnableAudioVideoSettings = (getDbItem("EnableAudioVideoSettings", "1") == "1");     // Controls the Audio & Video tab in Settings
var EnableAppearanceSettings = (getDbItem("EnableAppearanceSettings", "1") == "1");     // Controls the Appearance tab in Settings
var EnableChangeUserPasswordSettings = (getDbItem("EnableChangeUserPasswordSettings", "1") == "1"); // Controls the 'Change Password' tab in Settings
var EnableChangeUserEmailSettings = (getDbItem("EnableChangeUserEmailSettings", "1") == "1");       // Controls the 'Change Email' tab in Settings
var EnableCloseUserAccount = (getDbItem("EnableCloseUserAccount", "1") == "1");                     // Controls the 'Close Account' tab in Settings
var EnableAlphanumericDial = (getDbItem("EnableAlphanumericDial", "1") == "1");                     // Allows calling /[^\da-zA-Z\*\#\+]/g default is /[^\d\*\#\+]/g
var EnableVideoCalling = (getDbItem("EnableVideoCalling", "1") == "1");                             // Enables Video during a call
var winVideoConf = null;
var winVideoConfCheck = 0;

// System variables
// ================
var localDB = window.localStorage;
var userAgent = null;
var voicemailSubs = null;
var BlfSubs = [];
var CanvasCollection = [];
var Buddies = [];
var isReRegister = false;
var dhtmlxPopup = null;
var selectedBuddy = null;
var selectedLine = null;
var alertObj = null;
var confirmObj = null;
var promptObj = null;
var windowsCollection = null;
var messagingCollection = null;
var HasVideoDevice = false;
var HasAudioDevice = false;
var HasSpeakerDevice = false;
var AudioinputDevices = [];
var VideoinputDevices = [];
var SpeakerDevices = [];
var Lines = [];
var lang = {};
var audioBlobs = {};
var newLineNumber = 0;
var videoAudioCheck = 0;
var RCLoginCheck = 0;
var decSipPass = '';
var currentChatPrivKey = '';
var sendFileCheck = 0;
var upFileName = '';
var sendFileChatErr = '';
var pubKeyCheck = 0;
var splitMessage = {};

// Utilities
// =========
function uID(){
    return Date.now()+Math.floor(Math.random()*10000).toString(16).toUpperCase();
}
function utcDateNow(){
    return moment().utc().format("YYYY-MM-DD HH:mm:ss UTC");
}
function getDbItem(itemIndex, defaultValue){
    var localDB = window.localStorage;
    if(localDB.getItem(itemIndex) != null) return localDB.getItem(itemIndex);
    return defaultValue;
}
function getAudioSrcID(){
    var id = localDB.getItem("AudioSrcId");
    return (id != null)? id : "default";
}
function getAudioOutputID(){
    var id = localDB.getItem("AudioOutputId");
    return (id != null)? id : "default";
}
function getVideoSrcID(){
    var id = localDB.getItem("VideoSrcId");
    return (id != null)? id : "default";
}
function getRingerOutputID(){
    var id = localDB.getItem("RingOutputId");
    return (id != null)? id : "default";
}
function formatDuration(seconds){
    var sec = Math.floor(parseFloat(seconds));
    if(sec < 0){
        return sec;
    }
    else if(sec >= 0 && sec < 60){
         return sec + " " + ((sec != 1) ? lang.seconds_plural : lang.second_single);
    } 
    else if(sec >= 60 && sec < 60 * 60){ // greater then a minute and less then an hour
        var duration = moment.duration(sec, 'seconds');
        return duration.minutes() + " "+ ((duration.minutes() != 1) ? lang.minutes_plural: lang.minute_single) +" " + duration.seconds() +" "+ ((duration.seconds() != 1) ? lang.seconds_plural : lang.second_single);
    } 
    else if(sec >= 60 * 60 && sec < 24 * 60 * 60){ // greater than an hour and less then a day
        var duration = moment.duration(sec, 'seconds');
        return duration.hours() + " "+ ((duration.hours() != 1) ? lang.hours_plural : lang.hour_single) +" " + duration.minutes() + " "+ ((duration.minutes() != 1) ? lang.minutes_plural: lang.minute_single) +" " + duration.seconds() +" "+ ((duration.seconds() != 1) ? lang.seconds_plural : lang.second_single);
    } 
    //  Otherwise.. this is just too long
}
function formatShortDuration(seconds) {
    var sec = Math.floor(parseFloat(seconds));
    if(sec < 0){
        return sec;
    } 
    else if(sec >= 0 && sec < 60){
        return "00:"+ ((sec > 9)? sec : "0"+sec );
    } 
    else if(sec >= 60 && sec < 60 * 60){ // greater then a minute and less then an hour
        var duration = moment.duration(sec, 'seconds');
        return ((duration.minutes() > 9)? duration.minutes() : "0"+duration.minutes()) + ":" + ((duration.seconds() > 9)? duration.seconds() : "0"+duration.seconds());
    } 
    else if(sec >= 60 * 60 && sec < 24 * 60 * 60){ // greater than an hour and less then a day
        var duration = moment.duration(sec, 'seconds');
        return ((duration.hours() > 9)? duration.hours() : "0"+duration.hours())  + ":" + ((duration.minutes() > 9)? duration.minutes() : "0"+duration.minutes())  + ":" + ((duration.seconds() > 9)? duration.seconds() : "0"+duration.seconds());
    } 
    //  Otherwise.. this is just too long
}
function formatBytes(bytes, decimals) {
    if (bytes === 0) return "0 "+ lang.bytes;
    var k = 1024;
    var dm = (decimals && decimals >= 0)? decimals : 2;
    var sizes = [lang.bytes, lang.kb, lang.mb, lang.gb, lang.tb, lang.pb, lang.eb, lang.zb, lang.yb];
    var i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + " " + sizes[i];
}
function UserLocale(){
    var language = window.navigator.userLanguage || window.navigator.language; // "en", "en-US", "fr", "fr-FR", "es-ES", etc.

    langtag = language.split('-');
    if(langtag.length == 1){
        return ""; 
    } 
    else if(langtag.length == 2) {
        return langtag[1].toLowerCase();  // en-US => us
    }
    else if(langtag.length >= 3) {
        return langtag[1].toLowerCase();  // en-US => us
    }
}
function GetAlternateLanguage() {
    var userLanguage = window.navigator.userLanguage || window.navigator.language; // "en", "en-US", "fr", "fr-FR", "es-ES", etc.

    if(Language != "auto") userLanguage = Language;
    userLanguage = userLanguage.toLowerCase();
    if(userLanguage == "en" || userLanguage.indexOf("en-") == 0) return "";  // English is already loaded

    for(l = 0; l < availableLang.length; l++) {
        if(userLanguage.indexOf(availableLang[l].toLowerCase()) == 0) {
            console.log("Alternate Language detected: ", userLanguage);
            // Set up Moment with the same langugae settings
            moment.locale(userLanguage);
            return availableLang[l].toLowerCase();
        }
    }
    return "";
}
function getFilter(filter, keyword) {
    if(filter.indexOf(",", filter.indexOf(keyword +": ") + keyword.length + 2) != -1) {
        return filter.substring(filter.indexOf(keyword +": ") + keyword.length + 2, filter.indexOf(",", filter.indexOf(keyword +": ") + keyword.length + 2));
    }
    else {
        return filter.substring(filter.indexOf(keyword +": ") + keyword.length + 2);
    }
}
function base64toBlob(base64Data, contentType) {
    if(base64Data.indexOf("," != -1)) base64Data = base64Data.split(",")[1]; // [data:image/png;base64] , [xxx...]
    var byteCharacters = atob(base64Data);
    var slicesCount = Math.ceil(byteCharacters.length / 1024);
    var byteArrays = new Array(slicesCount);
    for (var s = 0; s < slicesCount; ++s) {
        var begin = s * 1024;
        var end = Math.min(begin + 1024, byteCharacters.length);
        var bytes = new Array(end - begin);
        for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
            bytes[i] = byteCharacters[offset].charCodeAt(0);
        }
        byteArrays[s] = new Uint8Array(bytes);
    }
    return new Blob(byteArrays, { type: contentType });
}
function MakeDataArray(defaultValue, count) {
    var rtnArray = new Array(count);
    for(var i=0; i< rtnArray.length; i++) {
        rtnArray[i] = defaultValue;
    }
    return rtnArray;
}
// Save account configuration data to SQL database
function saveConfToSqldb() {

    wssServer = $("#Configure_Account_wssServer").val();
    WebSocketPort = parseInt($("#Configure_Account_WebSocketPort").val());
    ServerPath = $("#Configure_Account_ServerPath").val();
    profileName = $("#Configure_Account_profileName").val();
    SipUsername = $("#Configure_Account_SipUsername").val();
    SipPassword = $("#Configure_Account_SipPassword").val();

    var STUNServer = $("#Configure_Account_StunServer").val();
    var AUDIOOutputId = $("#playbackSrc").val();
    var VIDEOSrcId = $("#previewVideoSrc").val();
    var VIDEOHeight = $("input[name=Settings_Quality]:checked").val(); 
    var FRAMERate = parseInt($("input[name=Settings_FrameRate]:checked").val());
    var ASPECTRatio = $("input[name=Settings_AspectRatio]:checked").val();
    var VIDEOOrientation = $("input[name=Settings_Oriteation]:checked").val();
    var AUDIOSrcId = $("#microphoneSrc").val();
    var AUTOGainControl = ($("#Settings_AutoGainControl").is(':checked'))? "1" : "0";
    var ECHOCancellation = ($("#Settings_EchoCancellation").is(':checked'))? "1" : "0";
    var NOISESuppression = ($("#Settings_NoiseSuppression").is(':checked'))? "1" : "0";
    var RINGOutputId = $("#ringDevice").val();
    var VideoConfExtension = $("#Video_Conf_Extension").val();
    var VideoConfWindowWidth = $("#Video_Conf_Window_Width").val();
    var PROFILEpicture = (typeof getDbItem("profilePicture", "") === 'undefined') ? "" : getDbItem("profilePicture", "");
    var NOTIFYCheck = ($("#Settings_Notifications").is(":checked"))? 1 : 0;
    var EMAILIntegration = ($("#emailIntegration").is(":checked"))? 1 : 0;
    var RCDomain = $("#RoundcubeDomain").val();
    var RCbasicauthuser = $("#rcBasicAuthUser").val();
    var RCbasicauthpass = $("#rcBasicAuthPass").val();
    var RCuser = $("#RoundcubeUser").val();
    var RCpassword = $("#RoundcubePass").val();

    if (userName != '') {

       if (wssServer != '' && WebSocketPort != '' && ServerPath != '' && SipUsername != '' && SipPassword != '') {

          $.ajax({
             type: "POST",
             url: "save-update-settings.php",
             dataType: "JSON",
             data: {
                     username: userName,
                     wss_server: wssServer,
                     web_socket_port: WebSocketPort,
                     server_path: ServerPath,
                     profile_name: profileName,
                     sip_username: SipUsername,
                     sip_password: SipPassword,
                     stun_server: STUNServer,
                     audio_output_id: AUDIOOutputId,
                     video_src_id: VIDEOSrcId,
                     video_height: VIDEOHeight,
                     frame_rate: FRAMERate,
                     aspect_ratio: ASPECTRatio,
                     video_orientation: VIDEOOrientation,
                     audio_src_id: AUDIOSrcId,
                     auto_gain_control: AUTOGainControl,
                     echo_cancellation: ECHOCancellation,
                     noise_suppression: NOISESuppression,
                     ring_output_id: RINGOutputId,
                     video_conf_extension: VideoConfExtension,
                     video_conf_window_width: VideoConfWindowWidth,
                     profile_picture: PROFILEpicture,
                     notifications: NOTIFYCheck,
                     use_roundcube: EMAILIntegration,
                     rcdomain: RCDomain,
                     rcbasicauthuser: RCbasicauthuser,
                     rcbasicauthpass: RCbasicauthpass,
                     rcuser: RCuser,
                     rcpassword: RCpassword,
                     s_ajax_call: validateSToken
             },
             success: function(response) {
                             window.location.reload();
                      },
             error: function(response) {
                             alert("An error occurred while attempting to save the account configuration data!");
             }
          });

       } else { alert("Fields: 'WebSocket Domain', 'WebSocket Port', 'WebSocket Path', 'SIP Username' and 'SIP Password' are required ! Please fill in all these fields !"); }

    } else { alert("An error occurred while attempting to save the data!"); }
}
// Get account configuration data from SQL database
function getConfFromSqldb() {

          $.ajax({
             type: "POST",
             url: "get-settings.php",
             dataType: "JSON",
             data: {
                     username: userName,
                     s_ajax_call: validateSToken
             },
             success: function(datafromdb) {

                        // Get configuration data from SQL database
                        if (datafromdb.wss_server == null || datafromdb.web_socket_port == null || datafromdb.server_path == null ||
                            datafromdb.sip_username == null || datafromdb.sip_password == null) {

                            ConfigureExtensionWindow();

                        } else {

				if (!localStorage.getItem('firstReLoad')) {
				     localStorage['firstReLoad'] = true;
				     window.setTimeout(function() { window.location.reload(); }, 200);
				}

                                if (datafromdb.stun_server == null || typeof datafromdb.stun_server == 'undefined') {
                                    var stunData = '';
                                } else { var stunData = datafromdb.stun_server; }

		                localDB.setItem("profileUserID", uID());
				localDB.setItem("userrole", datafromdb.userrole);
				localDB.setItem("wssServer", datafromdb.wss_server);
				localDB.setItem("WebSocketPort", datafromdb.web_socket_port);
				localDB.setItem("ServerPath", datafromdb.server_path);
				localDB.setItem("profileUser", datafromdb.sip_username);
				localDB.setItem("profileName", datafromdb.profile_name);
				localDB.setItem("SipUsername", datafromdb.sip_username);
				localDB.setItem("SipPassword", datafromdb.sip_password);
				localDB.setItem("StunServer", stunData);
				localDB.setItem("AudioOutputId", datafromdb.audio_output_id);
				localDB.setItem("VideoSrcId", datafromdb.video_src_id);
				localDB.setItem("VideoHeight", datafromdb.video_height);
				localDB.setItem("FrameRate", datafromdb.frame_rate);
				localDB.setItem("AspectRatio", datafromdb.aspect_ratio);
				localDB.setItem("VideoOrientation", datafromdb.video_orientation);
				localDB.setItem("AudioSrcId", datafromdb.audio_src_id);
				localDB.setItem("AutoGainControl", datafromdb.auto_gain_control);
				localDB.setItem("EchoCancellation", datafromdb.echo_cancellation);
				localDB.setItem("NoiseSuppression", datafromdb.noise_suppression);
				localDB.setItem("RingOutputId", datafromdb.ring_output_id);
                                localDB.setItem("VidConfExtension", datafromdb.video_conf_extension);
                                localDB.setItem("VidConfWindowWidth", datafromdb.video_conf_window_width);
				localDB.setItem("profilePicture", datafromdb.profile_picture);
				localDB.setItem("Notifications", datafromdb.notifications);
                                localDB.setItem("useRoundcube", datafromdb.use_roundcube);
                                localDB.setItem("rcDomain", (datafromdb.rcdomain != '' && datafromdb.rcdomain != null && typeof datafromdb.rcdomain != 'undefined')? datafromdb.rcdomain : "");
                                localDB.setItem("rcBasicAuthUser", datafromdb.rcbasicauthuser);
                                localDB.setItem("rcBasicAuthPass", datafromdb.rcbasicauthpass);
                                localDB.setItem("RoundcubeUser", datafromdb.rcuser);
                                localDB.setItem("RoundcubePass", datafromdb.rcpassword);

		                Register();
                        }
                      },
             error: function(datafromdb) {
                           alert("An error occurred while attempting to retrieve account configuration data from the database!");
             }
          });
}

// Save contact data to SQL database
function saveContactToSQLDB(newPerson) {

    if (newPerson.length != 0) {
             $.ajax({
                type: "POST",
                url: "save-contact.php",
                dataType: "JSON",
                data: {
                     username: userName,
                     contact_name: newPerson[0],
                     contact_desc: newPerson[1],
                     extension_number: newPerson[2],
                     contact_mobile: newPerson[3],
                     contact_num1: newPerson[4],
                     contact_num2: newPerson[5],
                     contact_email: newPerson[6],
                     s_ajax_call: validateSToken
                },
                success: function(response) {
                         if (response.result != 'success') { alert(response.result); }
                },
                error: function(response) {
                         alert("An error occurred while attempting to save the contact to the database!");
                }
          });
    } else { alert("An error occurred while attempting to save the data!"); }
}

// Update contact data in SQL database
function updateContactToSQLDB(newPerson) {

    if (newPerson.length != 0) {
        if (newPerson[7] != '' && newPerson[7] != null && typeof newPerson[7] != 'undefined') {
            $.ajax({
                type: "POST",
                url: "update-contact.php",
                dataType: "JSON",
                data: {
                     contact_name: newPerson[0],
                     contact_desc: newPerson[1],
                     extension_number: newPerson[2],
                     contact_mobile: newPerson[3],
                     contact_num1: newPerson[4],
                     contact_num2: newPerson[5],
                     contact_email: newPerson[6],
                     contactDBID: newPerson[7],
                     s_ajax_call: validateSToken
                },
                success: function(response) {
                         if (response.result != 'success') { alert(response.result); }
                },
                error: function(response) {
                         alert("An error occurred while attempting to save the data!");
                }
            });
        } else { alert("Error while attempting to retrieve contact data from the database!"); }
    } else { alert("An error occurred while attempting to save the data!"); }
}
// Save contact picture data to SQL database
function saveContactPicToSQLDB(newPic) {

    if (newPic.length != 0) {
        $.ajax({
             type: "POST",
             url: "save-update-contact-picture.php",
             dataType: "JSON",
             data: {
                     username: userName,
                     contact_name: newPic[0],
                     profile_picture_c: newPic[1],
                     s_ajax_call: validateSToken
             },
             success: function(response) {
                      },
             error: function(response) {
                          alert("An error occurred while attempting to save contact picture!");
             }
        });
    } else { alert("An error occurred while attempting to save contact picture!"); }
}
// Get contact data from SQL database
function getContactsFromSQLDB() {

          $.ajax({
             type: "POST",
             url: "get-contacts.php",
             dataType: "JSON",
             data: {
                     username: userName,
                     s_ajax_call: validateSToken
             },
             success: function(contactsfromdb) {

                        // Get contacts from SQL database and save them to localDB
                        var jsonCon = InitUserBuddies();

                        $.each(contactsfromdb.contactsinfo, function(ind, contactrow) {
			       var id = uID();
			       var dateNow = utcDateNow();

                               if (contactsfromdb.contactsinfo[ind].extension_number == '' || contactsfromdb.contactsinfo[ind].extension_number == null) {
 
				    jsonCon.DataCollection.push(
					{
					    Type: "contact",
					    LastActivity: dateNow,
					    ExtensionNumber: "",
					    MobileNumber: contactsfromdb.contactsinfo[ind].contact_mobile,
					    ContactNumber1: contactsfromdb.contactsinfo[ind].contact_num1,
					    ContactNumber2: contactsfromdb.contactsinfo[ind].contact_num2,
					    uID: null,
					    cID: id,
					    gID: null,
					    DisplayName: contactsfromdb.contactsinfo[ind].contact_name,
					    Position: "",
					    Description: contactsfromdb.contactsinfo[ind].contact_desc, 
					    Email: contactsfromdb.contactsinfo[ind].contact_email,
					    MemberCount: 0
					}
				    );

                                    if (contactsfromdb.contactsinfo[ind].profile_picture_c != '' && contactsfromdb.contactsinfo[ind].profile_picture_c != null) {
                                        localDB.setItem("img-"+id+"-contact", contactsfromdb.contactsinfo[ind].profile_picture_c);
                                    }

			            var buddyObj = new Buddy("contact", id, contactsfromdb.contactsinfo[ind].contact_name, "", contactsfromdb.contactsinfo[ind].contact_mobile, contactsfromdb.contactsinfo[ind].contact_num1, contactsfromdb.contactsinfo[ind].contact_num2, dateNow, contactsfromdb.contactsinfo[ind].contact_desc, contactsfromdb.contactsinfo[ind].contact_email);
			            AddBuddy(buddyObj, true, false, false);

                               } else {

				    jsonCon.DataCollection.push(
					{
					    Type: "extension",
					    LastActivity: dateNow,
					    ExtensionNumber: contactsfromdb.contactsinfo[ind].extension_number,
					    MobileNumber: contactsfromdb.contactsinfo[ind].contact_mobile,
					    ContactNumber1: contactsfromdb.contactsinfo[ind].contact_num1,
					    ContactNumber2: contactsfromdb.contactsinfo[ind].contact_num2,
					    uID: id,
					    cID: null,
					    gID: null,
					    DisplayName: contactsfromdb.contactsinfo[ind].contact_name,
					    Position: contactsfromdb.contactsinfo[ind].contact_desc,
					    Description: "", 
					    Email: contactsfromdb.contactsinfo[ind].contact_email,
					    MemberCount: 0
					}
				    );

                                    if (contactsfromdb.contactsinfo[ind].profile_picture_c != '' && contactsfromdb.contactsinfo[ind].profile_picture_c != null) {
                                        localDB.setItem("img-"+id+"-extension", contactsfromdb.contactsinfo[ind].profile_picture_c);
                                    }

			            var buddyObj = new Buddy("extension", id, contactsfromdb.contactsinfo[ind].contact_name, contactsfromdb.contactsinfo[ind].extension_number, contactsfromdb.contactsinfo[ind].contact_mobile, contactsfromdb.contactsinfo[ind].contact_num1, contactsfromdb.contactsinfo[ind].contact_num2, dateNow, contactsfromdb.contactsinfo[ind].contact_desc, contactsfromdb.contactsinfo[ind].contact_email);
			            AddBuddy(buddyObj, true, false, true);
                               } 
                        });

		        jsonCon.TotalRows = jsonCon.DataCollection.length;
		        localDB.setItem(profileUserID + "-Buddies", JSON.stringify(jsonCon));

                        UpdateUI();
                        PopulateBuddyList();

                      },
             error: function(contactsfromdb) {
                           alert("An error occurred while attempting to retrieve contacts data from the database!");
             }
          });
}

// Get external users data from SQL database
function getExternalUserConfFromSqldb() {

         $.ajax({
             type: "POST",
             url: "get-external-users-conf.php",
             dataType: "JSON",
             data: {
                     username: userName, 
                     s_ajax_call: validateSToken
             },
             success: function(extdatafromdb) {

                        var extdatafromdbstr = JSON.stringify(extdatafromdb);

                        if (extdatafromdbstr.length > 0) {

                            localDB.setItem("externalUserConfElem", extdatafromdb.length);

                            for (var t = 0; t < extdatafromdb.length; t++) {
				 localDB.setItem("extUserExtension-"+t, extdatafromdb[t]['exten_for_external']);
                                 localDB.setItem("extUserExtensionPass-"+t, extdatafromdb[t]['exten_for_ext_pass']);
                                 localDB.setItem("confAccessLink-"+t, extdatafromdb[t]['conf_access_link']);
                            }
                        }
                      },
             error: function(extdatafromdb) {
                           alert("An error occurred while attempting to retrieve external users configuration data from the database!");
             }
         });
}

// Check if there are any links for external access associated with the current username
function checkExternalLinks() {

        if (confirm("Links that can allow external users to access the video conferences are stored in the database. If you don\'t need them anymore, it\'s recommended to remove them in order to prevent unwanted access to your conferences. Press OK to remove all the links for external access associated with your username from the database and then exit Roundpin, or press Cancel to leave the links in the database and just exit.")) {

             $.ajax({
                 type: "POST",
                 url: "remove-links-for-external-access.php",
                 dataType: "JSON",
                 data: {
                        username: userName,
                        s_ajax_call: validateSToken
                       },
                 success: function(response) {
                            alert("All the links for external access to conferences associated with your username have been successfully removed from the database!");

		            Unregister();
			    console.log("Signing Out ...");
			    localStorage.clear();
			    if (winVideoConf != null) {
			        winVideoConf.close();
			    }
			    window.open('https://' + window.location.host + '/logout.php', '_self');
                 },
                 error: function(response) {
                            alert("An error occurred while trying to remove the data from the database!");

		            Unregister();
			    console.log("Signing Out ...");
			    localStorage.clear();
			    if (winVideoConf != null) {
			        winVideoConf.close();
			    }
			    window.open('https://' + window.location.host + '/logout.php', '_self');
                 }
             });

        } else {
                 Unregister();
		 console.log("Signing Out ...");
		 localStorage.clear();
		 if (winVideoConf != null) {
		     winVideoConf.close();
		 }
		 window.open('https://' + window.location.host + '/logout.php', '_self');
        }
}

// Remove contact from SQL database
function deleteBuddyFromSqldb(buddyDisplayName) {

          $.ajax({
             type: "POST",
             url: "remove-contact.php",
             dataType: "JSON",
             data: {
                     username: userName,
                     contact_name: buddyDisplayName,
                     s_ajax_call: validateSToken
             },
             success: function(delresult) {
             },
             error: function(delresult) {
                        alert("An error occurred while attempting to remove the contact from the database!");
             }
          });
}

// Save new Roundpin user password
function saveNewUserPassword() {

      var currentPassword = $("#Current_User_Password").val();
      var newPassword = $("#New_User_Password").val();
      var repeatPassword = $("#Repeat_New_User_Password").val();

      if (currentPassword == '' || newPassword == '' || repeatPassword == '') { alert("Please fill in all the fields!"); return; }

      // Verify if the new password meets constraints
      if (/^((?=.*\d)(?=.*[a-z])(?=.*\W).{10,})$/.test(newPassword)) {

          if (repeatPassword == newPassword) {
		  $.ajax({
		     type: "POST",
		     url: "save-new-user-password.php",
		     dataType: "JSON",
		     data: {
		             username: userName,
		             current_password: currentPassword,
                             new_password: newPassword,
		             s_ajax_call: validateSToken
		     },
		     success: function(passchangemessage) {
                                       alert(passchangemessage);
		     },
		     error: function(passchangemessage) {
		                alert("An error occurred while attempting to change the user password!");
		     }
		  });
          } else { alert("The passwords entered in the new password fields don't match!"); }

      } else {
          alert("The new password does not meet the requirements (to be at least 10 characters long, to contain at least one letter, at least one digit and at least one special character). Please choose a different password ! ");
        }
}

// Save new Roundpin user email
function saveNewUserEmail() {

      var currentEmail = $("#Current_User_Email").val();
      var newEmail = $("#New_User_Email").val();
      var repeatEmail = $("#Repeat_New_User_Email").val();

      if (currentEmail == '' || newEmail == '' || repeatEmail == '') { alert("Please fill in all the fields!"); return; }

      // Verify if the new email is a valid email address
      if (/^[A-Za-z0-9\_\.\-\~\%\+\!\?\&\*\^\=\#\$\{\}\|\/]+@[A-Za-z0-9\.\-]+\.[A-Za-z0-9\-]{2,63}$/.test(newEmail)) {

          if (repeatEmail == newEmail) {
		  $.ajax({
		     type: "POST",
		     url: "save-new-user-email.php",
		     dataType: "JSON",
		     data: {
		             username: userName,
		             current_email: currentEmail,
                             new_email: newEmail,
		             s_ajax_call: validateSToken
		     },
		     success: function(emailchangemessage) {
                                       alert(emailchangemessage);
		     },
		     error: function(emailchangemessage) {
		                alert("An error occurred while attempting to change the user email address!");
		     }
		  });
          } else { alert("The email addresses entered in the new email fields don't match!"); }

      } else {
            alert("The new email address is not a valid email address. Please enter a valid email address!");
        }
}

// Close Roundpin user account
function closeUserAccount() {

      closeVideoAudio();

      ConfirmConfigExtWindow(lang.confirm_close_account, lang.close_roundpin_user_account, function() {

		  $.ajax({
		     type: "POST",
		     url: "close-user-account.php",
		     dataType: "JSON",
		     data: {
		             username: userName,
		             s_ajax_call: validateSToken
		     },
		     success: function(closeaccountmessage) {
                                       alert(closeaccountmessage);
                                       SignOut();
		     },
		     error: function(closeaccountmessage) {
		                alert("An error occurred while attempting to close your user account!");
		     }
		  });
      });
}

// Launch video conference
function LaunchVideoConference() {
     if (winVideoConfCheck == 0) {
	    winVideoConf = window.open('https://' + window.location.host + '/videoconference/index.php');
	    winVideoConfCheck = 1;
     } else { alert("The video conference has been launched. If you want to launch it again refresh the page, then click \"Launch Video Conference\"."); }
}
// Generate a new text chat key
function generateChatRSAKeys(currentSIPusername) {

          var crypto = new JSEncrypt({default_key_size: 1024});
          crypto.getKey();
          var currentChatPubKey = crypto.getPublicKey();
          currentChatPrivKey = crypto.getPrivateKey();

	  $.ajax({
	     type: "POST",
	     url: "save-text-chat-pub-key.php",
	     dataType: "JSON",
	     data: {
	             currentextension: currentSIPusername,
                     currentchatpubkey: currentChatPubKey,
	             s_ajax_call: validateSToken
	     },
	     success: function() {
	     },
	     error: function() {
	                alert("An error occurred while trying to save the new text chat public key!");
	     }
	  });
}

// Remove the 'uploads' directory used to temporarily store files received during text chat
function removeTextChatUploads(currentSIPUser) {
	$.ajax({
             'async': false,
             'global': false,
	     type: "POST",
	     url: "text-chat-remove-uploaded-files.php",
	     dataType: "JSON",
	     data: {
		     sipusername: currentSIPUser,
		     s_ajax_call: validateSToken
	     },
	     success: function(resresult) {
                          if (resresult.note != 'success') {
                              alert("An error occurred while trying to remove the text chat 'uploads' directory!");
                          }
             },
             error: function(resresult) {
                              alert("An error occurred while attempting to remove the text chat 'uploads' directory!");
             }
        });
}

// On page reload, close the video conference tab if it is opened
function closeVideoConfTab() {
         if (winVideoConf) { winVideoConf.close(); }
}

// Show Email window
function ShowEmailWindow() {

   if (getDbItem("useRoundcube", "") == 1) {

      $("#roundcubeFrame").remove();
      $("#rightContent").show();
      $(".streamSelected").each(function() { $(this).css("display", "none"); });
      $("#rightContent").append('<iframe id="roundcubeFrame" name="displayFrame"></iframe>');

      var rcDomain = '';
      var rcBasicAuthUser = '';
      var rcBasicAuthPass = '';
      var rcUsername = '';
      var rcPasswd = '';

      $.ajax({
             'async': false,
             'global': false,
             type: "POST",
             url: "get-email-info.php",
             dataType: "JSON",
             data: {
                     username: userName,
                     s_ajax_call: validateSToken
             },
             success: function(datafromdb) {
                               rcDomain = datafromdb.rcdomain;
                               rcBasicAuthUser = encodeURIComponent(datafromdb.rcbasicauthuser);
                               rcBasicAuthPass = encodeURIComponent(datafromdb.rcbasicauthpass);
                               rcUsername = datafromdb.rcuser;
                               rcPasswd = datafromdb.rcpassword;
             },
             error: function(datafromdb) {
                             alert("An error occurred while trying to retrieve data from the database!");
             }
      });

      if (rcBasicAuthUser != '' && rcBasicAuthPass != '') { 
          var actionURL = "https://"+ rcBasicAuthUser +":"+ rcBasicAuthPass +"@"+ rcDomain +"/"; 
      } else { var actionURL = "https://"+ rcDomain +"/"; }

      var form = '<form id="rcForm" method="POST" action="'+ actionURL +'" target="displayFrame">'; 
      form += '<input type="hidden" name="_action" value="login" />';
      form += '<input type="hidden" name="_task" value="login" />';
      form += '<input type="hidden" name="_autologin" value="1" />';
      form += '<input name="_user" value="'+ rcUsername +'" type="text" />';
      form += '<input name="_pass" value="'+ rcPasswd +'" type="password" />';
      form += '<input id="submitButton" type="submit" value="Login" />';
      form += '</form>';

      $("#roundcubeFrame").append(form);

      if (RCLoginCheck == 0) {
          $("#submitButton").click();
          RCLoginCheck = 1;
      } else { $("#roundcubeFrame").attr("src", actionURL); }

   } else { alert("Email Integration is not enabled ! You can enable Roundcube email integration by clicking on the 'Settings' wheel in the user profile section from below > 'Settings' > 'Email Integration' > 'Enable Roundcube email integration'"); }
}

// Shrink the left panel
function CollapseLeftPanel() {
    if ($(window).width() >= 920) {
        if ($("#leftContent").hasClass("shrinkLeftContent")) {
            $("#leftContent").removeClass("shrinkLeftContent");
            $("#rightContent").removeClass("widenRightContent");
            $('#aboutImg').css("margin-right", "-3px");
        } else {
            $("#leftContent").addClass("shrinkLeftContent");
            $("#rightContent").addClass("widenRightContent");
            $('#aboutImg').css("margin-right", "3px");
        }
    }
}

// Show the 'About' window
function ShowAboutWindow() {

   $.jeegoopopup.close();
   var aboutHtml = '<div>';
   aboutHtml += '<div id="windowCtrls"><img id="minimizeImg" src="images/1_minimize.svg" title="Restore" /><img id="maximizeImg" src="images/2_maximize.svg" title="Maximize" /><img id="closeImg" src="images/3_close.svg" title="Close" /></div>';
   aboutHtml += '<div class="UiWindowField scroller">';
   aboutHtml += '<div><img id="AboutLogoImg" src="images/login-logo.svg"/></div>';
   aboutHtml += '<div id="aboutPopup">'+lang.about_text+'</div>';
   aboutHtml += '</div></div>';

   $.jeegoopopup.open({
                title: 'About Roundpin',
                html: aboutHtml,
                width: '640',
                height: '500',
                center: true,
                scrolling: 'no',
                skinClass: 'jg_popup_basic',
                overlay: true,
                opacity: 50,
                draggable: true,
                resizable: false,
                fadeIn: 0
   });

   $("#jg_popup_b").append('<button id="ok_button">'+ lang.ok +'</button>');

   var maxWidth = $(window).width() - 12;
   var maxHeight = $(window).height() - 88;

   if (maxWidth < 656 || maxHeight < 500) { 
       $.jeegoopopup.width(maxWidth).height(maxHeight);
       $.jeegoopopup.center();
       $("#maximizeImg").hide();
       $("#minimizeImg").hide();
   } else { 
       $.jeegoopopup.width(640).height(500);
       $.jeegoopopup.center();
       $("#minimizeImg").hide();
       $("#maximizeImg").show();
   }

   $(window).resize(function() {
       maxWidth = $(window).width() - 12;
       maxHeight = $(window).height() - 88;

       $.jeegoopopup.center();
       if (maxWidth < 656 || maxHeight < 500) { 
           $.jeegoopopup.width(maxWidth).height(maxHeight);
           $.jeegoopopup.center();
           $("#maximizeImg").hide();
           $("#minimizeImg").hide();
       } else { 
           $.jeegoopopup.width(640).height(500);
           $.jeegoopopup.center();
           $("#minimizeImg").hide();
           $("#maximizeImg").show();
       }
   });

   
   $("#minimizeImg").click(function() { $.jeegoopopup.width(640).height(500); $.jeegoopopup.center(); $("#maximizeImg").show(); $("#minimizeImg").hide(); });
   $("#maximizeImg").click(function() { $.jeegoopopup.width(maxWidth).height(maxHeight); $.jeegoopopup.center(); $("#minimizeImg").show(); $("#maximizeImg").hide(); });

   $("#closeImg").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
   $("#ok_button").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
   $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
   $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); $("#jg_popup_b").empty(); } });
}

// Show system notifications on incoming calls
function incomingCallNote() {
   var incomingCallNotify = new Notification(lang.incomming_call, { icon: "../images/notification-logo.svg", body: "New incoming call !!!" });
   incomingCallNotify.onclick = function (event) {
       return;
   };

   if (document.hasFocus()) {
       return;
   } else { setTimeout(incomingCallNote, 8000); }
}

// Change page title on incoming calls
function changePageTitle() {
    if ($(document).attr("title") == "Roundpin") { $(document).prop("title", "New call !!!"); } else { $(document).prop("title", "Roundpin"); }
    if (document.hasFocus()) {
        $(document).prop("title", "Roundpin");
        return;
    } else { setTimeout(changePageTitle, 460); }
}

// Window and Document Events
// ==========================
$(window).on("beforeunload", function() {
    Unregister();
});
$(window).on("resize", function() {
    UpdateUI();
});

// User Interface
// ==============
function UpdateUI(){
    if($(window).outerWidth() < 920){
        // Narrow Layout
        if(selectedBuddy == null & selectedLine == null) {
            // Nobody Selected
            $("#rightContent").hide();

            $("#leftContent").css("width", "100%");
            $("#leftContent").show();
        }
        else {
            $("#rightContent").css("margin-left", "0px");
            $("#rightContent").show();

            $("#leftContent").hide();

            if(selectedBuddy != null) updateScroll(selectedBuddy.identity);
        }
    }
    else {
        // Wide Screen Layout
        if(selectedBuddy == null & selectedLine == null) {
            $("#leftContent").css("width", "320px");
            $("#rightContent").css("margin-left", "0px");
            $("#leftContent").show();
            $("#rightContent").hide();
        }
        else{
            $("#leftContent").css("width", "320px");
            $("#rightContent").css("margin-left", "320px");
            $("#leftContent").show();
            $("#rightContent").show();

            if(selectedBuddy != null) updateScroll(selectedBuddy.identity);
        }
    }
    for(var l=0; l<Lines.length; l++){
        updateLineScroll(Lines[l].LineNumber);
    }
}

// UI Windows
// ==========
function AddSomeoneWindow(numberStr){

    $("#userMenu").hide();
    $.jeegoopopup.close();

    var html = "<div id='AddNewContact'>";

    html += "<div id='windowCtrls'><img id='minimizeImg' src='images/1_minimize.svg' title='Restore' /><img id='maximizeImg' src='images/2_maximize.svg' title='Maximize' /><img id='closeImg' src='images/3_close.svg' title='Close' /></div>";

    html += "<div class='UiWindowField scroller'>";

    html += "<div class=UiText>"+ lang.display_name +":</div>";
    html += "<div><input id=AddSomeone_Name class=UiInputText type=text placeholder='"+ lang.eg_display_name +"'></div>";

    html += "<div class=UiText>"+ lang.title_description +":</div>";
    html += "<div><input id=AddSomeone_Desc class=UiInputText type=text placeholder='"+ lang.eg_general_manager +"'></div>";

    html += "<div class=UiText>"+ lang.internal_subscribe_extension +":</div>";
    if(numberStr && numberStr.length > 1 && numberStr.length < DidLength && numberStr.substring(0,1) != "*"){
        html += "<div><input id=AddSomeone_Exten class=UiInputText type=text value="+ numberStr +" placeholder='"+ lang.eg_internal_subscribe_extension +"'></div>";
    }
    else{
        html += "<div><input id=AddSomeone_Exten class=UiInputText type=text placeholder='"+ lang.eg_internal_subscribe_extension +"'></div>";
    }

    html += "<div class=UiText>"+ lang.mobile_number +":</div>";
    html += "<div><input id=AddSomeone_Mobile class=UiInputText type=text placeholder='"+ lang.eg_mobile_number +"'></div>";

    html += "<div class=UiText>"+ lang.contact_number_1 +":</div>";
    if(numberStr && numberStr.length > 1){
        html += "<div><input id=AddSomeone_Num1 class=UiInputText type=text value="+ numberStr +" placeholder='"+ lang.eg_contact_number_1 +"'></div>";
    }
    else {
        html += "<div><input id=AddSomeone_Num1 class=UiInputText type=text placeholder='"+ lang.eg_contact_number_1 +"'></div>";
    }

    html += "<div class=UiText>"+ lang.contact_number_2 +":</div>";
    html += "<div><input id=AddSomeone_Num2 class=UiInputText type=text placeholder='"+ lang.eg_contact_number_2 +"'></div>";

    html += "<div class=UiText>"+ lang.email +":</div>";
    html += "<div><input id=AddSomeone_Email class=UiInputText type=text placeholder='"+ lang.eg_email +"'></div>";

    html += "</div></div>"

    $.jeegoopopup.open({
                title: 'Add Contact',
                html: html,
                width: '640',
                height: '500',
                center: true,
                scrolling: 'no',
                skinClass: 'jg_popup_basic',
                contentClass: 'addContactPopup',
                overlay: true,
                opacity: 50,
                draggable: true,
                resizable: false,
                fadeIn: 0
    });

    $("#jg_popup_b").append("<div id=bottomButtons><button id=save_button>Save</button><button id=cancel_button>Cancel</button></div>");

    $("#save_button").click(function() {

      var currentASName = $("#AddSomeone_Name").val();

      if (currentASName != null && currentASName.trim() !== '') {

        if (/^[A-Za-z0-9\s\-\'\[\]\(\)]+$/.test(currentASName)) {

	   var currentDesc = $("#AddSomeone_Desc").val();
	   if (currentDesc != null && currentDesc.trim() !== '') {
	       if (/^[A-Za-z0-9\s\-\.\'\"\[\]\(\)\{\}\_\!\?\~\@\%\^\&\*\+\>\<\;\:\=]+$/.test(currentDesc)) { var finCurrentDesc = currentDesc; } else { 
		   var finCurrentDesc = ''; alert('The title/description that you entered is not valid!'); }
	   } else { var finCurrentDesc = ''; }

	   var currentExtension = $("#AddSomeone_Exten").val();
	   if (currentExtension != null && currentExtension.trim() !== '') {
	       if (/^[a-zA-Z0-9\*\#]+$/.test(currentExtension)) { var finCurrentExtension = currentExtension; } else { 
		   var finCurrentExtension = ''; alert("The extension that you entered in the 'Extension (Internal)' field is not a valid extension!"); }
	   } else { var finCurrentExtension = ''; }

	   var currentMobile = $("#AddSomeone_Mobile").val();
	   if (currentMobile != null && currentMobile.trim() !== '') {
	       if (/^[0-9\s\+\#]+$/.test(currentMobile)) { var finCurrentMobile = currentMobile; } else {
		   var finCurrentMobile = ''; alert("The phone number that you entered in the 'Mobile Number' field is not valid! The only allowed characters are: digits, spaces, plus signs and pound signs."); }
	   } else { var finCurrentMobile = ''; }

	   var currentNum1 = $("#AddSomeone_Num1").val();
	   if (currentNum1 != null && currentNum1.trim() !== '') {
	       if (/^[0-9\s\+\#]+$/.test(currentNum1)) { var finCurrentNum1 = currentNum1; } else {
		   var finCurrentNum1 = ''; alert("The phone number that you entered in the 'Contact Number 1' field is not valid! The only allowed characters are: digits, spaces, plus signs and pound signs."); }
	   } else { var finCurrentNum1 = ''; }

	   var currentNum2 = $("#AddSomeone_Num2").val();
	   if (currentNum2 != null && currentNum2.trim() !== '') {
	       if (/^[0-9\s\+\#]+$/.test(currentNum2)) { var finCurrentNum2 = currentNum2; } else {
		   var finCurrentNum2 = ''; alert("The phone number that you entered in the 'Contact Number 2' field is not valid! The only allowed characters are: digits, spaces, plus signs and pound signs."); }
           } else { var finCurrentNum2 = ''; }

	   var currentEmail = $("#AddSomeone_Email").val();
	   if (currentEmail != null && currentEmail.trim() !== '') {
	       if (/^[A-Za-z0-9\_\.\-\~\%\+\!\?\&\*\^\=\#\$\{\}\|\/]+@[A-Za-z0-9\.\-]+\.[A-Za-z0-9\-]{2,63}$/.test(currentEmail)) { var finCurrentEmail = currentEmail; } else {
		   var finCurrentEmail = ''; alert("The email that you entered is not a valid email address!"); }
	   } else { var finCurrentEmail = ''; }


           // Add Contact / Extension
           var json = JSON.parse(localDB.getItem(profileUserID + "-Buddies"));
           if(json == null) json = InitUserBuddies();

           if(finCurrentExtension == ''){
               // Add Regular Contact
               var id = uID();
               var dateNow = utcDateNow();
               json.DataCollection.push(
                   {
                    Type: "contact",
                    LastActivity: dateNow,
                    ExtensionNumber: "",
                    MobileNumber: finCurrentMobile,
                    ContactNumber1: finCurrentNum1,
                    ContactNumber2: finCurrentNum2,
                    uID: null,
                    cID: id,
                    gID: null,
                    DisplayName: currentASName,
                    Position: "",
                    Description: finCurrentDesc,
                    Email: finCurrentEmail,
                    MemberCount: 0
                   }
               );
               var newPerson = [];
               newPerson = [currentASName, finCurrentDesc, "", finCurrentMobile, finCurrentNum1, finCurrentNum2, finCurrentEmail];
               saveContactToSQLDB(newPerson);

               var buddyObj = new Buddy("contact", id, currentASName, "", finCurrentMobile, finCurrentNum1, finCurrentNum2, dateNow, finCurrentDesc, finCurrentEmail);
               AddBuddy(buddyObj, false, false, false);

           } else {
               // Add Extension
               var id = uID();
               var dateNow = utcDateNow();
               json.DataCollection.push(
                   {
                    Type: "extension",
                    LastActivity: dateNow,
                    ExtensionNumber: finCurrentExtension,
                    MobileNumber: finCurrentMobile,
                    ContactNumber1: finCurrentNum1,
                    ContactNumber2: finCurrentNum2,
                    uID: id,
                    cID: null,
                    gID: null,
                    DisplayName: currentASName,
                    Position: finCurrentDesc,
                    Description: "",
                    Email: finCurrentEmail,
                    MemberCount: 0
                   }
               );

               var newPerson = [];

               newPerson = [currentASName, finCurrentDesc, finCurrentExtension, finCurrentMobile, finCurrentNum1, finCurrentNum2, finCurrentEmail];
               saveContactToSQLDB(newPerson);

               var buddyObj = new Buddy("extension", id, currentASName, finCurrentExtension, finCurrentMobile, finCurrentNum1, finCurrentNum2, dateNow, finCurrentDesc, finCurrentEmail);
               AddBuddy(buddyObj, false, false, true);

           }
           // Update Size:
           json.TotalRows = json.DataCollection.length;

           // Save To Local DB
           localDB.setItem(profileUserID + "-Buddies", JSON.stringify(json));
           UpdateBuddyList();

           $.jeegoopopup.close();
           $("#jg_popup_b").empty();

        } else { alert('The display name that you entered is not a valid display name!'); }

      } else { alert("'Display Name' cannot be empty!"); }
       
   });

   var maxWidth = $(window).width() - 12;
   var maxHeight = $(window).height() - 110;

   if (maxWidth < 656 || maxHeight < 500) { 
       $.jeegoopopup.width(maxWidth).height(maxHeight);
       $.jeegoopopup.center();
       $("#maximizeImg").hide();
       $("#minimizeImg").hide();
   } else { 
       $.jeegoopopup.width(640).height(500);
       $.jeegoopopup.center();
       $("#minimizeImg").hide();
       $("#maximizeImg").show();
   }

   $(window).resize(function() {
       maxWidth = $(window).width() - 16;
       maxHeight = $(window).height() - 110;
       $.jeegoopopup.center();
       if (maxWidth < 656 || maxHeight < 500) { 
           $.jeegoopopup.width(maxWidth).height(maxHeight);
           $.jeegoopopup.center();
           $("#maximizeImg").hide();
           $("#minimizeImg").hide();
       } else { 
           $.jeegoopopup.width(640).height(500);
           $.jeegoopopup.center();
           $("#minimizeImg").hide();
           $("#maximizeImg").show();
       }
   });

   $("#minimizeImg").click(function() { $.jeegoopopup.width(640).height(500); $.jeegoopopup.center(); $("#maximizeImg").show(); $("#minimizeImg").hide(); });
   $("#maximizeImg").click(function() { $.jeegoopopup.width(maxWidth).height(maxHeight); $.jeegoopopup.center(); $("#minimizeImg").show(); $("#maximizeImg").hide(); });

   $("#closeImg").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
   $("#cancel_button").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
   $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
   $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); $("#jg_popup_b").empty(); } });
}

function CreateGroupWindow(){
}

function closeVideoAudio() {

        var localVideo = $("#local-video-preview").get(0);
        try{
            var tracks = localVideo.srcObject.getTracks();
            tracks.forEach(function(track) {
                track.stop();
            });
            localVideo.srcObject = null;
        }
        catch(e){}

        try{
            var tracks = window.SettingsMicrophoneStream.getTracks();
            tracks.forEach(function(track) {
                track.stop();
            });
        }
        catch(e){}
        window.SettingsMicrophoneStream = null;

        try{
            var soundMeter = window.SettingsMicrophoneSoundMeter;
            soundMeter.stop();
        }
        catch(e){}
        window.SettingsMicrophoneSoundMeter = null;

        try{
            window.SettingsOutputAudio.pause();
        }
        catch(e){}
        window.SettingsOutputAudio = null;

        try{
            var tracks = window.SettingsOutputStream.getTracks();
            tracks.forEach(function(track) {
                track.stop();
            });
        }
        catch(e){}
        window.SettingsOutputStream = null;

        try{
            var soundMeter = window.SettingsOutputStreamMeter;
            soundMeter.stop();
        }
        catch(e){}
        window.SettingsOutputStreamMeter = null;

        return true;
}
function ConfigureExtensionWindow() {

    $("#settingsCMenu").hide();
    $.jeegoopopup.close();

    var configWindow = "<div id=\"mainConfWindow\">";
    configWindow += "<div id='windowCtrls'><img id='minimizeImg' src='images/1_minimize.svg' title='Restore' /><img id='maximizeImg' src='images/2_maximize.svg' title='Maximize' /><img id='closeImg' src='images/3_close.svg' title='Close' /></div>"; 
    configWindow += "<div id=\"mainRightConf\">";
    configWindow += "<div id=\"rightMainConfWindow\">";

    configWindow +=  "<div id=\"AccountHtml\" class=\"settingsSubSection\" style=\"display:block;\">";
    configWindow += "<div class=UiText>"+ lang.asterisk_server_address +": *</div>";
    configWindow += "<div><input id=Configure_Account_wssServer class=UiInputText type=text placeholder='"+ lang.eg_asterisk_server_address +"' value='"+ getDbItem("wssServer", "") +"'></div>";
    configWindow += "<div class=UiText>"+ lang.websocket_port +": *</div>";
    configWindow += "<div><input id=Configure_Account_WebSocketPort class=UiInputText type=text placeholder='"+ lang.eg_websocket_port +"' value='"+ getDbItem("WebSocketPort", "") +"'></div>";
    configWindow += "<div class=UiText>"+ lang.websocket_path +": *</div>";
    configWindow += "<div><input id=Configure_Account_ServerPath class=UiInputText type=text placeholder='"+ lang.eg_websocket_path +"' value='"+ getDbItem("ServerPath", "") +"'></div>";
    configWindow += "<div class=UiText>"+ lang.display_name +": *</div>";

    var escapedDisplayName = 'value="' + getDbItem("profileName", "").replace("'","\'") + '"';
    configWindow += "<div><input id=Configure_Account_profileName class=UiInputText type=text placeholder='"+ lang.eg_display_name +"' "+ escapedDisplayName +"></div>";
    configWindow += "<div class=UiText>"+ lang.sip_username +": *</div>";
    configWindow += "<div><input id=Configure_Account_SipUsername class=UiInputText type=text placeholder='"+ lang.eg_sip_username +"' value='"+ getDbItem("SipUsername", "") +"'></div>";
    configWindow += "<div class=UiText>"+ lang.sip_password +": *</div>";
    configWindow += "<div><input id=Configure_Account_SipPassword class=UiInputText type=password placeholder='"+ lang.eg_sip_password +"' value='"+ getDbItem("SipPassword", "") +"'></div>";
    configWindow += "<div class=UiText>"+ lang.stun_server +":</div>";
    configWindow += "<div><input id=Configure_Account_StunServer class=UiInputText type=text placeholder='Eg: 123.123.123.123:8443' value='"+ getDbItem("StunServer", "") +"'></div>";
    configWindow += "<p style=\"color:#363636;\">* Required field.</p><br><br></div>";

    configWindow += "<div id=\"AudioVideoHtml\" class=\"settingsSubSection\" style=\"display:none;\">";
    configWindow += "<div class=UiText>"+ lang.speaker +":</div>";
    configWindow += "<div style=\"text-align:center\"><select id=playbackSrc style=\"width:100%\"></select></div>";
    configWindow += "<div class=Settings_VolumeOutput_Container><div id=Settings_SpeakerOutput class=Settings_VolumeOutput></div></div>";
    configWindow += "<div><button class=on_white id=preview_output_play><i class=\"fa fa-play\"></i></button><button class=on_white id=preview_output_pause><i class=\"fa fa-pause\"></i></button></div>";

    configWindow += "<br><div class=UiText>"+ lang.ring_device +":</div>";
    configWindow += "<div style=\"text-align:center\"><select id=ringDevice style=\"width:100%\"></select></div>";
    configWindow += "<div class=Settings_VolumeOutput_Container><div id=Settings_RingerOutput class=Settings_VolumeOutput></div></div>";
    configWindow += "<div><button class=on_white id=preview_ringer_play><i class=\"fa fa-play\"></i></button></div>";

    configWindow += "<br><div class=UiText>"+ lang.microphone +":</div>";
    configWindow += "<div style=\"text-align:center\"><select id=microphoneSrc style=\"width:100%\"></select></div>";
    configWindow += "<div class=Settings_VolumeOutput_Container><div id=Settings_MicrophoneOutput class=Settings_VolumeOutput></div></div>";
    configWindow += "<br><br><div><input type=checkbox id=Settings_AutoGainControl><label for=Settings_AutoGainControl> "+ lang.auto_gain_control +"<label></div>";
    configWindow += "<div><input type=checkbox id=Settings_EchoCancellation><label for=Settings_EchoCancellation> "+ lang.echo_cancellation +"<label></div>";
    configWindow += "<div><input type=checkbox id=Settings_NoiseSuppression><label for=Settings_NoiseSuppression> "+ lang.noise_suppression +"<label></div>";
    configWindow += "<br><div class=UiText>"+ lang.camera +":</div>";
    configWindow += "<div style=\"text-align:center\"><select id=previewVideoSrc style=\"width:100%\"></select></div>";
    configWindow += "<br><div class=UiText>"+ lang.frame_rate +":</div>"
    configWindow += "<div class=pill-nav>";
    configWindow += "<input name=Settings_FrameRate id=r40 type=radio value=\"2\"><label class=radio_pill for=r40>2</label>";
    configWindow += "<input name=Settings_FrameRate id=r41 type=radio value=\"5\"><label class=radio_pill for=r41>5</label>";
    configWindow += "<input name=Settings_FrameRate id=r42 type=radio value=\"10\"><label class=radio_pill for=r42>10</label>";
    configWindow += "<input name=Settings_FrameRate id=r43 type=radio value=\"15\"><label class=radio_pill for=r43>15</label>";
    configWindow += "<input name=Settings_FrameRate id=r44 type=radio value=\"20\"><label class=radio_pill for=r44>20</label>";
    configWindow += "<input name=Settings_FrameRate id=r45 type=radio value=\"25\"><label class=radio_pill for=r45>25</label>";
    configWindow += "<input name=Settings_FrameRate id=r46 type=radio value=\"30\"><label class=radio_pill for=r46>30</label>";
    configWindow += "<input name=Settings_FrameRate id=r47 type=radio value=\"\"><label class=radio_pill for=r47><i class=\"fa fa-trash\"></i></label>";
    configWindow += "</div>";
    configWindow += "<br><br><div class=UiText>"+ lang.quality +":</div>";
    configWindow += "<div class=pill-nav>";
    configWindow += "<input name=Settings_Quality id=r30 type=radio value=\"160\"><label class=radio_pill for=r30><i class=\"fa fa-video-camera\" style=\"transform: scale(0.4)\"></i> HQVGA</label>";
    configWindow += "<input name=Settings_Quality id=r31 type=radio value=\"240\"><label class=radio_pill for=r31><i class=\"fa fa-video-camera\" style=\"transform: scale(0.6)\"></i> QVGA</label>";
    configWindow += "<input name=Settings_Quality id=r32 type=radio value=\"480\"><label class=radio_pill for=r32><i class=\"fa fa-video-camera\" style=\"transform: scale(0.8)\"></i> VGA</label>";
    configWindow += "<input name=Settings_Quality id=r33 type=radio value=\"720\"><label class=radio_pill for=r33><i class=\"fa fa-video-camera\" style=\"transform: scale(1)\"></i> HD</label>";
    configWindow += "<input name=Settings_Quality id=r34 type=radio value=\"\"><label class=radio_pill for=r34><i class=\"fa fa-trash\"></i></label>";
    configWindow += "</div>";
    configWindow += "<br><br><div class=UiText>"+ lang.image_orientation +":</div>";
    configWindow += "<div class=pill-nav>";
    configWindow += "<input name=Settings_Oriteation id=r20 type=radio value=\"rotateY(0deg)\"><label class=radio_pill for=r20><i class=\"fa fa-address-card\" style=\"transform: rotateY(0deg)\"></i> Normal</label>";
    configWindow += "<input name=Settings_Oriteation id=r21 type=radio value=\"rotateY(180deg)\"><label class=radio_pill for=r21><i class=\"fa fa-address-card\" style=\"transform: rotateY(180deg)\"></i> Mirror</label>";
    configWindow += "</div>";
    configWindow += "<br><br><div class=UiText>"+ lang.aspect_ratio +":</div>";
    configWindow += "<div class=pill-nav>";
    configWindow += "<input name=Settings_AspectRatio id=r10 type=radio value=\"1\"><label class=radio_pill for=r10><i class=\"fa fa-square-o\" style=\"transform: scaleX(1); margin-left: 7px; margin-right: 7px\"></i> 1:1</label>";
    configWindow += "<input name=Settings_AspectRatio id=r11 type=radio value=\"1.33\"><label class=radio_pill for=r11><i class=\"fa fa-square-o\" style=\"transform: scaleX(1.33); margin-left: 5px; margin-right: 5px;\"></i> 4:3</label>";
    configWindow += "<input name=Settings_AspectRatio id=r12 type=radio value=\"1.77\"><label class=radio_pill for=r12><i class=\"fa fa-square-o\" style=\"transform: scaleX(1.77); margin-right: 3px;\"></i> 16:9</label>";
    configWindow += "<input name=Settings_AspectRatio id=r13 type=radio value=\"\"><label class=radio_pill for=r13><i class=\"fa fa-trash\"></i></label>";
    configWindow += "</div>";
    configWindow += "<br><br><div class=UiText>"+ lang.preview +":</div>";
    configWindow += "<div style=\"text-align:center; margin-top:10px\"><video id=\"local-video-preview\" class=\"previewVideo\"></video></div>";
    configWindow += "<br><div class=UiText>"+ lang.video_conference_extension +":</div>";
    configWindow += "<div><input id=Video_Conf_Extension class=UiInputText type=text placeholder='"+ lang.video_conference_extension_example +"' value='"+ getDbItem("VidConfExtension", "") +"'></div>";
    configWindow += "<br><div class=UiText>"+ lang.video_conference_window_width +":</div>";
    configWindow += "<div><input id=Video_Conf_Window_Width class=UiInputText type=text placeholder='"+ lang.video_conf_window_width_explanation +"' value='"+ getDbItem("VidConfWindowWidth", "") +"'></div>";
    if (getDbItem("userrole", "") == "superadmin") {

	configWindow += "<div id=confTableSection>"+ lang.external_conf_users +"</div>";
        configWindow += "<div class=confTable><table id=vidConfExternalTable>";
        configWindow += "<tr class=btnTableRow><td><label for=extConfExtension id=extensionThLabel class=confExtLabels>Extension</label></td><td><label for=extConfExtensionPass id=extPassThLabel class=confExtLabels>SIP Password</label></td><td><label for=extConfExtensionLink id=extLinkThLabel class=confExtLabels>Link</label></td></tr>";

        for (var cqt = 0; cqt < getDbItem("externalUserConfElem", ""); cqt++) {
	     configWindow += "<tr class=btnTableRow><td><input type=text class=extConfExtension name=extConfExtension value='"+ getDbItem('extUserExtension-'+cqt, '') +"' disabled=\"disabled\" /></td><td><input type=password class=extConfExtensionPass name=extConfExtensionPass value='"+ getDbItem('extUserExtensionPass-'+cqt, '') +"' disabled=\"disabled\"/></td><td><input type=text class=extConfExtensionLink name=extConfExtensionLink value='"+ getDbItem('confAccessLink-'+cqt, '') +"' /></td><td><span class=\"copyToClipboard\"><i class=\"fa fa-clipboard\" aria-hidden=\"true\" title=\"Copy link to clipboard.\"></i></span></td><td><span class=\"deleteExtRow\" title=\"Delete extension data from database.\">X</span></td><td><input type=submit class=saveExtConfExtension value=\"Edit\" title=\"Edit this row.\" /></td></tr>";
        }

	configWindow += "<tr id=emptyExtRow class=btnTableRow><td><input type=text class=extConfExtension name=extConfExtension placeholder=\"Eg: 711\" /></td><td><input type=password class=extConfExtensionPass name=extConfExtensionPass placeholder=\"Eg: d5?W?9q?8rg*R9!eFrVth?9\" /></td><td><input type=text class=extConfExtensionLink name=extConfExtensionLink placeholder=\"Generated on 'Save'\"  disabled=\"disabled\" /></td><td><span class=\"copyToClipboard\"><i class=\"fa fa-clipboard\" aria-hidden=\"true\" title=\"Copy link to clipboard.\"></i></span></td><td><span class=\"deleteExtRow deleteExtRowDisabled\" title=\"Delete extension data from database.\">X</span></td><td><input type=submit class=saveExtConfExtension value=Save title=\"Save this row.\" /></td></tr>";
        configWindow += "</table></div>";
	configWindow += "<button id=add_New_External_User>Add External User</button>";
    }
    configWindow += "<br><br></div>";

    configWindow += "<div id=\"AppearanceHtml\" class=\"settingsSubSection\" style=\"display:none;\">";
    configWindow += "<div id=ImageCanvas style=\"width:150px; height:150px;\"></div>";
    configWindow += "<label for=fileUploader class=customBrowseButton style=\"margin-left: 200px; margin-top: -2px;\">Select File</label>";
    configWindow += "<div><input id=fileUploader type=file></div>";
    configWindow += "<div style=\"margin-top: 50px\"></div>";
    configWindow += "</div>";

    configWindow += "<div id=\"NotificationsHtml\" class=\"settingsSubSection\" style=\"display:none;\">";
    configWindow += "<div class=UiText>"+ lang.notifications +":</div>";
    configWindow += "<div id=\"notificationsCheck\"><input type=checkbox id=Settings_Notifications><label for=Settings_Notifications> "+ lang.enable_onscreen_notifications +"<label></div>";
    configWindow += "</div>";

    configWindow += "<div id=\"RoundcubeEmailHtml\" class=\"settingsSubSection\" style=\"display:none;\">";
    configWindow += "<div class=UiText>"+ lang.email_integration +":</div>";
    configWindow += "<div id=\"enableRCcheck\"><input id=emailIntegration type=checkbox ><label for=emailIntegration> "+ lang.enable_roundcube_integration +"<label></div>";
    configWindow += "<div class=UiText>"+ lang.roundcube_domain +":</div>";
    configWindow += "<div><input id=RoundcubeDomain class=UiInputText type=text placeholder='Roundcube domain (Eg: mail.example.com).' value='"+ getDbItem("rcDomain", "") +"'></div>";
    configWindow += "<div class=UiText>"+ lang.roundcube_user +":</div>";
    configWindow += "<div><input id=RoundcubeUser class=UiInputText type=text placeholder='Roundcube login user (Eg: john.doe@example.com or john_doe).' value='"+ getDbItem("RoundcubeUser", "") +"'></div>";
    configWindow += "<div class=UiText>"+ lang.roundcube_password +":</div>";
    configWindow += "<div><input id=RoundcubePass class=UiInputText type=password placeholder='Roundcube login password.' value='"+ getDbItem("RoundcubePass", "") +"'></div>";
    configWindow += "<div class=UiText>"+ lang.rc_basic_auth_user +":</div>";
    configWindow += "<div><input id=rcBasicAuthUser class=UiInputText type=text placeholder='If you have a Roundcube basic auth user, enter it here.' value='"+ getDbItem("rcBasicAuthUser", "") +"'></div>";
    configWindow += "<div class=UiText>"+ lang.rc_basic_auth_password +":</div>";
    configWindow += "<div><input id=rcBasicAuthPass class=UiInputText type=password placeholder='If you have a Roundcube basic auth password, enter it here.' value='"+ getDbItem("rcBasicAuthPass", "") +"'></div>";

    configWindow += "<br><br></div>";

    configWindow += "<div id=\"ChangePasswordHtml\" class=\"settingsSubSection\" style=\"display:none;\">";
    configWindow += "<div class=UiText>"+ lang.current_user_password +":</div>";
    configWindow += "<div><input id=Current_User_Password class=UiInputText type=password placeholder='Enter your current Roundpin user password.' value=''></div>";
    configWindow += "<div class=UiText>"+ lang.new_user_password +":</div>";
    configWindow += "<div><input id=New_User_Password class=UiInputText type=password placeholder='Enter your new Roundpin user password.' value=''></div>";
    configWindow += "<div class=UiText>"+ lang.repeat_new_user_password +":</div>";
    configWindow += "<div><input id=Repeat_New_User_Password class=UiInputText type=password placeholder='Enter your new Roundpin user password again.' value=''></div><br>";
    configWindow += "<div><input id=Save_New_User_Password type=button value='Save New Password' onclick='saveNewUserPassword()' ></div>";
    configWindow += "<br><br></div>";

    configWindow += "<div id=\"ChangeEmailHtml\" class=\"settingsSubSection\" style=\"display:none;\">";
    configWindow += "<div class=UiText>"+ lang.current_user_email +":</div>";
    configWindow += "<div><input id=Current_User_Email class=UiInputText type=text placeholder='Enter your current Roundpin email address.' value=''></div>";
    configWindow += "<div class=UiText>"+ lang.new_user_email +":</div>";
    configWindow += "<div><input id=New_User_Email class=UiInputText type=text placeholder='Enter your new email address.' value=''></div>";
    configWindow += "<div class=UiText>"+ lang.repeat_new_user_email +":</div>";
    configWindow += "<div><input id=Repeat_New_User_Email class=UiInputText type=text placeholder='Enter your new email address again.' value=''></div><br>";
    configWindow += "<div><input id=Save_New_User_Email type=button value='Save New Email' onclick='saveNewUserEmail()' ></div>";
    configWindow += "<br><br></div>";

    configWindow += "<div id=\"CloseAccountHtml\" class=\"settingsSubSection\" style=\"display:none;\">";
    configWindow += "<div class=UiText>"+ lang.if_you_want_to_close_account +":</div><br><br>";
    configWindow += "<div><input id=Close_User_Account type=button value='Close User Account' onclick='closeUserAccount()' ></div>";
    configWindow += "<br><br></div>";

    configWindow += "</div></div></div>";

    var settingsSections = "<table id=leftPanelSettings cellspacing=14 cellpadding=0 style=\"width:184px;margin-left:8px;margin-top:14px;font-size:15px;\">";
    settingsSections += "<tr id=ConnectionSettingsRow><td class=SettingsSection>Connection Settings</td></tr>";
    settingsSections += "<tr id=AudioAndVideoRow><td class=SettingsSection>Audio & Video</td></tr>";
    settingsSections += "<tr id=ProfilePictureRow><td class=SettingsSection>Profile Picture</td></tr>";
    settingsSections += "<tr id=NotificationsRow><td class=SettingsSection>Notifications</td></tr>";
    settingsSections += "<tr id=RoundcubeEmailRow><td class=SettingsSection>Email Integration</td></tr>";
    settingsSections += "<tr id=ChangePasswordRow><td class=SettingsSection>Change Password</td></tr>";
    settingsSections += "<tr id=ChangeEmailRow><td class=SettingsSection>Change Email</td></tr>";
    settingsSections += "<tr id=CloseAccountRow><td class=SettingsSection>Close Account</td></tr></table>";

    $.jeegoopopup.open({
                title: '<span id=settingsTitle>Settings</span>',
                html: configWindow,
                width: '520',
                height: '500',
                center: true,
                scrolling: 'no',
                skinClass: 'jg_popup_basic',
                contentClass: 'configPopup',
                overlay: true,
                opacity: 50,
                draggable: true,
                resizable: false,
                fadeIn: 0
    });

    $("#jg_popup_b").append('<div id="bottomButtonsConf"><button id="save_button_conf">Save</button><button id="cancel_button_conf">Cancel</button></div>');
    $("#jg_popup_l").append(settingsSections);

    if (getDbItem("useRoundcube", "") == 1) { $("#emailIntegration").prop("checked", true); } else { $("#emailIntegration").prop("checked", false); }

    $("#ConnectionSettingsRow td").addClass("selectedSettingsSection");

    $("#ConnectionSettingsRow").click(function() {
        $(".settingsSubSection").each(function() { $(this).css("display", "none"); });
        $("#AccountHtml").css("display", "block");
        $(".SettingsSection").each(function() { $(this).removeClass("selectedSettingsSection"); });
        $("#ConnectionSettingsRow td").addClass("selectedSettingsSection");
    });

    $("#ProfilePictureRow").click(function() {
        $(".settingsSubSection").each(function() { $(this).css("display", "none"); });
        $("#AppearanceHtml").css("display", "block");
        $(".SettingsSection").each(function() { $(this).removeClass("selectedSettingsSection"); });
        $("#ProfilePictureRow td").addClass("selectedSettingsSection");
    });

    $("#NotificationsRow").click(function() {
        $(".settingsSubSection").each(function() { $(this).css("display", "none"); });
        $("#NotificationsHtml").css("display", "block");
        $(".SettingsSection").each(function() { $(this).removeClass("selectedSettingsSection"); });
        $("#NotificationsRow td").addClass("selectedSettingsSection");
    });

    $("#RoundcubeEmailRow").click(function() {
        $(".settingsSubSection").each(function() { $(this).css("display", "none"); });
        $("#RoundcubeEmailHtml").css("display", "block");
        $(".SettingsSection").each(function() { $(this).removeClass("selectedSettingsSection"); });
        $("#RoundcubeEmailRow td").addClass("selectedSettingsSection");
    });

    $("#ChangePasswordRow").click(function() {
        $(".settingsSubSection").each(function() { $(this).css("display", "none"); });
        $("#ChangePasswordHtml").css("display", "block");
        $(".SettingsSection").each(function() { $(this).removeClass("selectedSettingsSection"); });
        $("#ChangePasswordRow td").addClass("selectedSettingsSection");
    });

    $("#ChangeEmailRow").click(function() {
        $(".settingsSubSection").each(function() { $(this).css("display", "none"); });
        $("#ChangeEmailHtml").css("display", "block");
        $(".SettingsSection").each(function() { $(this).removeClass("selectedSettingsSection"); });
        $("#ChangeEmailRow td").addClass("selectedSettingsSection");
    });

    $("#CloseAccountRow").click(function() {
        $(".settingsSubSection").each(function() { $(this).css("display", "none"); });
        $("#CloseAccountHtml").css("display", "block");
        $(".SettingsSection").each(function() { $(this).removeClass("selectedSettingsSection"); });
        $("#CloseAccountRow td").addClass("selectedSettingsSection");
    });

    var maxWidth = $(window).width() - 192;
    var maxHeight = $(window).height() - 98;

    if (maxWidth < 520 || maxHeight < 500) { 
       $.jeegoopopup.width(maxWidth).height(maxHeight);
       $.jeegoopopup.center();
       $("#maximizeImg").hide();
       $("#minimizeImg").hide();
    } else { 
       $.jeegoopopup.width(520).height(500);
       $.jeegoopopup.center();
       $("#minimizeImg").hide();
       $("#maximizeImg").show();
    }

    $(window).resize(function() {
       maxWidth = $(window).width() - 192;
       maxHeight = $(window).height() - 98;
       $.jeegoopopup.center();
       if (maxWidth < 520 || maxHeight < 500) { 
           $.jeegoopopup.width(maxWidth).height(maxHeight);
           $.jeegoopopup.center();
           $("#maximizeImg").hide();
           $("#minimizeImg").hide();
       } else { 
           $.jeegoopopup.width(520).height(500);
           $.jeegoopopup.center();
           $("#minimizeImg").hide();
           $("#maximizeImg").show();
       }
    });

    $("#minimizeImg").click(function() { $.jeegoopopup.width(520).height(500); $.jeegoopopup.center(); $("#maximizeImg").show(); $("#minimizeImg").hide(); });
    $("#maximizeImg").click(function() { $.jeegoopopup.width(maxWidth).height(maxHeight); $.jeegoopopup.center(); $("#minimizeImg").show(); $("#maximizeImg").hide(); });


    // Output
    var selectAudioScr = $("#playbackSrc");

    var playButton = $("#preview_output_play");

    var playRingButton = $("#preview_ringer_play");

    var pauseButton = $("#preview_output_pause");

    // Microphone
    var selectMicScr = $("#microphoneSrc");
    $("#Settings_AutoGainControl").prop("checked", AutoGainControl);
    $("#Settings_EchoCancellation").prop("checked", EchoCancellation);
    $("#Settings_NoiseSuppression").prop("checked", NoiseSuppression);

    // Webcam
    var selectVideoScr = $("#previewVideoSrc");

    // Orientation
    var OrientationSel = $("input[name=Settings_Oriteation]");
    OrientationSel.each(function(){
        if(this.value == MirrorVideo) $(this).prop("checked", true);
    });
    $("#local-video-preview").css("transform", MirrorVideo);

    // Frame Rate
    var frameRateSel = $("input[name=Settings_FrameRate]");
    frameRateSel.each(function(){
        if(this.value == maxFrameRate) $(this).prop("checked", true);
    });

    // Quality
    var QualitySel = $("input[name=Settings_Quality]");
    QualitySel.each(function(){
        if(this.value == videoHeight) $(this).prop("checked", true);
    });

    // Aspect Ratio
    var AspectRatioSel = $("input[name=Settings_AspectRatio]");
    AspectRatioSel.each(function(){
        if(this.value == videoAspectRatio) $(this).prop("checked", true);
    });

    // Ring Tone
    var selectRingTone = $("#ringTone");

    // Ring Device
    var selectRingDevice = $("#ringDevice");

    // Handle Aspect Ratio Change
    AspectRatioSel.change(function(){
        console.log("Call to change Aspect Ratio ("+ this.value +")");

        var localVideo = $("#local-video-preview").get(0);
        localVideo.muted = true;
        localVideo.playsinline = true;
        localVideo.autoplay = true;

        var tracks = localVideo.srcObject.getTracks();
        tracks.forEach(function(track) {
            track.stop();
        });

        var constraints = {
            audio: false,
            video: {
                deviceId: (selectVideoScr.val() != "default")? { exact: selectVideoScr.val() } : "default"
            }
        }
        if($("input[name=Settings_FrameRate]:checked").val() != ""){
            constraints.video.frameRate = $("input[name=Settings_FrameRate]:checked").val();
        }
        if($("input[name=Settings_Quality]:checked").val() != ""){
            constraints.video.height = $("input[name=Settings_Quality]:checked").val();
        }
        if(this.value != ""){
            constraints.video.aspectRatio = this.value;
        }        
        console.log("Constraints:", constraints);
        var localStream = new MediaStream();
        if(navigator.mediaDevices){
            navigator.mediaDevices.getUserMedia(constraints).then(function(newStream){
                var videoTrack = newStream.getVideoTracks()[0];
                localStream.addTrack(videoTrack);
                localVideo.srcObject = localStream;
                localVideo.onloadedmetadata = function(e) {
                    localVideo.play();
                }
            }).catch(function(e){
                console.error(e);
                AlertConfigExtWindow(lang.alert_error_user_media, lang.error);
            });
        }
    });

    // Handle Video Height Change
    QualitySel.change(function(){    
        console.log("Call to change Video Height ("+ this.value +")");

        var localVideo = $("#local-video-preview").get(0);
        localVideo.muted = true;
        localVideo.playsinline = true;
        localVideo.autoplay = true;

        var tracks = localVideo.srcObject.getTracks();
        tracks.forEach(function(track) {
            track.stop();
        });

        var constraints = {
            audio: false,
            video: {
                deviceId: (selectVideoScr.val() != "default")? { exact: selectVideoScr.val() } : "default" ,
            }
        }
        if($("input[name=Settings_FrameRate]:checked").val() != ""){
            constraints.video.frameRate = $("input[name=Settings_FrameRate]:checked").val();
        }
        if(this.value){
            constraints.video.height = this.value;
        }
        if($("input[name=Settings_AspectRatio]:checked").val() != ""){
            constraints.video.aspectRatio = $("input[name=Settings_AspectRatio]:checked").val();
        } 
        console.log("Constraints:", constraints);
        var localStream = new MediaStream();
        if(navigator.mediaDevices){
            navigator.mediaDevices.getUserMedia(constraints).then(function(newStream){
                var videoTrack = newStream.getVideoTracks()[0];
                localStream.addTrack(videoTrack);
                localVideo.srcObject = localStream;
                localVideo.onloadedmetadata = function(e) {
                    localVideo.play();
                }
            }).catch(function(e){
                console.error(e);
                AlertConfigExtWindow(lang.alert_error_user_media, lang.error);
            });
        }
    });    

    // Handle Frame Rate Change 
    frameRateSel.change(function(){
        console.log("Call to change Frame Rate ("+ this.value +")");

        var localVideo = $("#local-video-preview").get(0);
        localVideo.muted = true;
        localVideo.playsinline = true;
        localVideo.autoplay = true;

        var tracks = localVideo.srcObject.getTracks();
        tracks.forEach(function(track) {
            track.stop();
        });

        var constraints = {
            audio: false,
            video: {
                deviceId: (selectVideoScr.val() != "default")? { exact: selectVideoScr.val() } : "default" ,
            }
        }
        if(this.value != ""){
            constraints.video.frameRate = this.value;
        }
        if($("input[name=Settings_Quality]:checked").val() != ""){
            constraints.video.height = $("input[name=Settings_Quality]:checked").val();
        }
        if($("input[name=Settings_AspectRatio]:checked").val() != ""){
            constraints.video.aspectRatio = $("input[name=Settings_AspectRatio]:checked").val();
        } 
        console.log("Constraints:", constraints);
        var localStream = new MediaStream();
        if(navigator.mediaDevices){
            navigator.mediaDevices.getUserMedia(constraints).then(function(newStream){
                var videoTrack = newStream.getVideoTracks()[0];
                localStream.addTrack(videoTrack);
                localVideo.srcObject = localStream;
                localVideo.onloadedmetadata = function(e) {
                    localVideo.play();
                }
            }).catch(function(e){
                console.error(e);
                AlertConfigExtWindow(lang.alert_error_user_media, lang.error);
            });
        }
    });

    // Handle Audio Source changes (Microphone)
    selectMicScr.change(function(){
        console.log("Call to change Microphone ("+ this.value +")");

        // Change and update visual preview
        try{
            var tracks = window.SettingsMicrophoneStream.getTracks();
            tracks.forEach(function(track) {
                track.stop();
            });
            window.SettingsMicrophoneStream = null;
        }
        catch(e){}

        try{
            soundMeter = window.SettingsMicrophoneSoundMeter;
            soundMeter.stop();
            window.SettingsMicrophoneSoundMeter = null;
        }
        catch(e){}

        // Get Microphone
        var constraints = { 
            audio: {
                deviceId: { exact: this.value }
            }, 
            video: false 
        }
        var localMicrophoneStream = new MediaStream();
        navigator.mediaDevices.getUserMedia(constraints).then(function(mediaStream){
            var audioTrack = mediaStream.getAudioTracks()[0];
            if(audioTrack != null){
                // Display Microphone Levels
                localMicrophoneStream.addTrack(audioTrack);
                window.SettingsMicrophoneStream = localMicrophoneStream;
                window.SettingsMicrophoneSoundMeter = MeterSettingsOutput(localMicrophoneStream, "Settings_MicrophoneOutput", "width", 50);
            }
        }).catch(function(e){
            console.log("Failed to getUserMedia", e);
        });
    });

    // Handle output change (speaker)
    selectAudioScr.change(function(){
        console.log("Call to change Speaker ("+ this.value +")");

        var audioObj = window.SettingsOutputAudio;
        if(audioObj != null) {
            if (typeof audioObj.sinkId !== 'undefined') {
                audioObj.setSinkId(this.value).then(function() {
                    console.log("sinkId applied to audioObj:", this.value);
                }).catch(function(e){
                    console.warn("Failed not apply setSinkId.", e);
                });
            }
        }
    });

    // Play button press
    playButton.click(function(){

        try{
            window.SettingsOutputAudio.pause();
        } 
        catch(e){}
        window.SettingsOutputAudio = null;

        try{
            var tracks = window.SettingsOutputStream.getTracks();
            tracks.forEach(function(track) {
                track.stop();
            });
        }
        catch(e){}
        window.SettingsOutputStream = null;

        try{
            var soundMeter = window.SettingsOutputStreamMeter;
            soundMeter.stop();
        }
        catch(e){}
        window.SettingsOutputStreamMeter = null;

        // Load Sample
        console.log("Audio:", audioBlobs.speaker_test.url);
        var audioObj = new Audio(audioBlobs.speaker_test.blob);
        audioObj.preload = "auto";
        audioObj.onplay = function(){
            var outputStream = new MediaStream();
            if (typeof audioObj.captureStream !== 'undefined') {
                outputStream = audioObj.captureStream();
            } 
            else if (typeof audioObj.mozCaptureStream !== 'undefined') {
                return;
            }
            else if (typeof audioObj.webkitCaptureStream !== 'undefined') {
                outputStream = audioObj.webkitCaptureStream();
            }
            else {
                console.warn("Cannot display Audio Levels")
                return;
            }

            // Display Speaker Levels
            window.SettingsOutputStream = outputStream;
            window.SettingsOutputStreamMeter = MeterSettingsOutput(outputStream, "Settings_SpeakerOutput", "width", 50);
        }
        audioObj.oncanplaythrough = function(e) {
            if (typeof audioObj.sinkId !== 'undefined') {
                audioObj.setSinkId(selectAudioScr.val()).then(function() {
                    console.log("Set sinkId to:", selectAudioScr.val());
                }).catch(function(e){
                    console.warn("Failed not apply setSinkId.", e);
                });
            }
            // Play
            audioObj.play().then(function(){
                // Audio Is Playing
            }).catch(function(e){
                console.warn("Unable to play audio file", e);
            });
            console.log("Playing sample audio file... ");
        }

        window.SettingsOutputAudio = audioObj;
    });

    // Pause button press
    pauseButton.click(function() {
       if (window.SettingsOutputAudio.paused) {
           window.SettingsOutputAudio.play();
       } else { 
           window.SettingsOutputAudio.pause();
         }
    });


    playRingButton.click(function(){

        try{
            window.SettingsRingerAudio.pause();
        } 
        catch(e){}
        window.SettingsRingerAudio = null;

        try{
            var tracks = window.SettingsRingerStream.getTracks();
            tracks.forEach(function(track) {
                track.stop();
            });
        }
        catch(e){}
        window.SettingsRingerStream = null;

        try{
            var soundMeter = window.SettingsRingerStreamMeter;
            soundMeter.stop();
        }
        catch(e){}
        window.SettingsRingerStreamMeter = null;

        // Load Sample
        console.log("Audio:", audioBlobs.Ringtone.url);
        var audioObj = new Audio(audioBlobs.Ringtone.blob);
        audioObj.preload = "auto";
        audioObj.onplay = function(){
            var outputStream = new MediaStream();
            if (typeof audioObj.captureStream !== 'undefined') {
                outputStream = audioObj.captureStream();
            } 
            else if (typeof audioObj.mozCaptureStream !== 'undefined') {
                return;
                // BUG: mozCaptureStream() in Firefox does not work the same way as captureStream()
                // the actual sound does not play out to the speakers... its as if the mozCaptureStream
                // removes the stream from the <audio> object.
                outputStream = audioObj.mozCaptureStream();
            }
            else if (typeof audioObj.webkitCaptureStream !== 'undefined') {
                outputStream = audioObj.webkitCaptureStream();
            }
            else {
                console.warn("Cannot display Audio Levels")
                return;
            }
            // Monitor Output
            window.SettingsRingerStream = outputStream;
            window.SettingsRingerStreamMeter = MeterSettingsOutput(outputStream, "Settings_RingerOutput", "width", 50);
        }
        audioObj.oncanplaythrough = function(e) {
            if (typeof audioObj.sinkId !== 'undefined') {
                audioObj.setSinkId(selectRingDevice.val()).then(function() {
                    console.log("Set sinkId to:", selectRingDevice.val());
                }).catch(function(e){
                    console.warn("Failed not apply setSinkId.", e);
                });
            }
            // Play
            audioObj.play().then(function(){
                // Audio Is Playing
            }).catch(function(e){
                console.warn("Unable to play audio file", e);
            });
            console.log("Playing sample audio file... ");
        }

        window.SettingsRingerAudio = audioObj;
    });

    // Change Video Image
    OrientationSel.change(function(){
        console.log("Call to change Orientation ("+ this.value +")");
        $("#local-video-preview").css("transform", this.value);
    });

    // Handle video input change (WebCam)
    selectVideoScr.change(function(){
        console.log("Call to change WebCam ("+ this.value +")");

        var localVideo = $("#local-video-preview").get(0);
        localVideo.muted = true;
        localVideo.playsinline = true;
        localVideo.autoplay = true;

        var tracks = localVideo.srcObject.getTracks();
        tracks.forEach(function(track) {
            track.stop();
        });

        var constraints = {
            audio: false,
            video: {
                deviceId: (this.value != "default")? { exact: this.value } : "default"
            }
        }
        if($("input[name=Settings_FrameRate]:checked").val() != ""){
            constraints.video.frameRate = $("input[name=Settings_FrameRate]:checked").val();
        }
        if($("input[name=Settings_Quality]:checked").val() != ""){
            constraints.video.height = $("input[name=Settings_Quality]:checked").val();
        }
        if($("input[name=Settings_AspectRatio]:checked").val() != ""){
            constraints.video.aspectRatio = $("input[name=Settings_AspectRatio]:checked").val();
        } 
        console.log("Constraints:", constraints);
        var localStream = new MediaStream();
        if(navigator.mediaDevices){
            navigator.mediaDevices.getUserMedia(constraints).then(function(newStream){
                var videoTrack = newStream.getVideoTracks()[0];
                localStream.addTrack(videoTrack);
                localVideo.srcObject = localStream;
                localVideo.onloadedmetadata = function(e) {
                    localVideo.play();
                }
            }).catch(function(e){
                console.error(e);
                AlertConfigExtWindow(lang.alert_error_user_media, lang.error);
            });
        }
    });

    $("#AudioAndVideoRow").click(function() {

       $(".settingsSubSection").each(function() { $(this).css("display", "none"); });
       $("#AudioVideoHtml").css("display", "block");
       $(".SettingsSection").each(function() { $(this).removeClass("selectedSettingsSection"); });
       $("#AudioAndVideoRow td").addClass("selectedSettingsSection");

       if (videoAudioCheck == 0) {

            videoAudioCheck = 1;

	    // Note: Only works over HTTPS or via localhost!!
	    var localVideo = $("#local-video-preview").get(0);
	    localVideo.muted = true;
	    localVideo.playsinline = true;
	    localVideo.autoplay = true;

	    var localVideoStream = new MediaStream();
	    var localMicrophoneStream = new MediaStream();
	    
	    if(navigator.mediaDevices){
		navigator.mediaDevices.enumerateDevices().then(function(deviceInfos){
		    var savedVideoDevice = getVideoSrcID();
		    var videoDeviceFound = false;

		    var savedAudioDevice = getAudioSrcID();
		    var audioDeviceFound = false;

		    var MicrophoneFound = false;
		    var SpeakerFound = false;
		    var VideoFound = false;

		    for (var i = 0; i < deviceInfos.length; ++i) {
		        console.log("Found Device ("+ deviceInfos[i].kind +"): ", deviceInfos[i].label);

		        // Check Devices
		        if (deviceInfos[i].kind === "audioinput") {
		            MicrophoneFound = true;
		            if(savedAudioDevice != "default" && deviceInfos[i].deviceId == savedAudioDevice) {
		                audioDeviceFound = true;
		            }                   
		        }
		        else if (deviceInfos[i].kind === "audiooutput") {
		            SpeakerFound = true;
		        }
		        else if (deviceInfos[i].kind === "videoinput") {
		            VideoFound = true;
		            if(savedVideoDevice != "default" && deviceInfos[i].deviceId == savedVideoDevice) {
		                videoDeviceFound = true;
		            }
		        }
		    }

		    var contraints = {
		        audio: MicrophoneFound,
		        video: VideoFound
		    }

		    if(MicrophoneFound){
		        contraints.audio = { deviceId: "default" }
		        if(audioDeviceFound) contraints.audio.deviceId = { exact: savedAudioDevice }
		    }
		    if(VideoFound){
		        contraints.video = { deviceId: "default" }
		        if(videoDeviceFound) contraints.video.deviceId = { exact: savedVideoDevice }
		    }
		    // Additional
		    if($("input[name=Settings_FrameRate]:checked").val() != ""){
		        contraints.video.frameRate = $("input[name=Settings_FrameRate]:checked").val();
		    }
		    if($("input[name=Settings_Quality]:checked").val() != ""){
		        contraints.video.height = $("input[name=Settings_Quality]:checked").val();
		    }
		    if($("input[name=Settings_AspectRatio]:checked").val() != ""){
		        contraints.video.aspectRatio = $("input[name=Settings_AspectRatio]:checked").val();
		    } 
		    console.log("Get User Media", contraints);
		    // Get User Media
		    navigator.mediaDevices.getUserMedia(contraints).then(function(mediaStream){
		        // Handle Video
		        var videoTrack = (mediaStream.getVideoTracks().length >= 1)? mediaStream.getVideoTracks()[0] : null;
		        if(VideoFound && videoTrack != null){
		            localVideoStream.addTrack(videoTrack);
		            // Display Preview Video
		            localVideo.srcObject = localVideoStream;
		            localVideo.onloadedmetadata = function(e) {
		                localVideo.play();
		            }
		        }
		        else {
		            console.warn("No video / webcam devices found. Video Calling will not be possible.")
		        }

		        // Handle Audio
		        var audioTrack = (mediaStream.getAudioTracks().length >= 1)? mediaStream.getAudioTracks()[0] : null ;
		        if(MicrophoneFound && audioTrack != null){
		            localMicrophoneStream.addTrack(audioTrack);
		            // Display Micrphone Levels
		            window.SettingsMicrophoneStream = localMicrophoneStream;
		            window.SettingsMicrophoneSoundMeter = MeterSettingsOutput(localMicrophoneStream, "Settings_MicrophoneOutput", "width", 50);
		        }
		        else {
		            console.warn("No microphone devices found. Calling will not be possible.")
		        }

		        // Display Output Levels
		        $("#Settings_SpeakerOutput").css("width", "0%");
		        if(!SpeakerFound){
		            console.log("No speaker devices found, make sure one is plugged in.")
		            $("#playbackSrc").hide();
		            $("#RingDeviceSection").hide();
		        }

		       // Return .then()
		       return navigator.mediaDevices.enumerateDevices();
		    }).then(function(deviceInfos){
		        for (var i = 0; i < deviceInfos.length; ++i) {
		            console.log("Found Device ("+ deviceInfos[i].kind +") Again: ", deviceInfos[i].label, deviceInfos[i].deviceId);

		            var deviceInfo = deviceInfos[i];
		            var devideId = deviceInfo.deviceId;
		            var DisplayName = deviceInfo.label;
		            if(DisplayName.indexOf("(") > 0) DisplayName = DisplayName.substring(0,DisplayName.indexOf("("));

		            var option = $('<option/>');
		            option.prop("value", devideId);

		            if (deviceInfo.kind === "audioinput") {
		                option.text((DisplayName != "")? DisplayName : "Microphone");
		                if(getAudioSrcID() == devideId) option.prop("selected", true);
		                selectMicScr.append(option);
		            }
		            else if (deviceInfo.kind === "audiooutput") {
		                option.text((DisplayName != "")? DisplayName : "Speaker");
		                if(getAudioOutputID() == devideId) option.prop("selected", true);
		                selectAudioScr.append(option);
		                selectRingDevice.append(option.clone());
		            }
		            else if (deviceInfo.kind === "videoinput") {
		                if(getVideoSrcID() == devideId) option.prop("selected", true);
		                option.text((DisplayName != "")? DisplayName : "Webcam");
		                selectVideoScr.append(option);
		            }
		        }
		        // Add "Default" option
		        if(selectVideoScr.children('option').length > 0){
		            var option = $('<option/>');
		            option.prop("value", "default");
		            if(getVideoSrcID() == "default" || getVideoSrcID() == "" || getVideoSrcID() == "null") option.prop("selected", true);
		            option.text("(Default)");
		            selectVideoScr.append(option);
		        }
		    }).catch(function(e){
		        console.error(e);
		        AlertConfigExtWindow(lang.alert_error_user_media, lang.error);
		    });
		}).catch(function(e){
		    console.error("Error getting Media Devices", e);
		});

	    } else {
		AlertConfigExtWindow(lang.alert_error_user_media, lang.error);
	    }
        }
    });

    var NotificationsCheck = $("#Settings_Notifications");
    NotificationsCheck.prop("checked", NotificationsActive);
    NotificationsCheck.change(function(){
        if(this.checked){
            if(Notification.permission != "granted"){
                if(checkNotificationPromise()){
                    Notification.requestPermission().then(function(p){
                        console.log(p);
                        HandleNotifyPermission(p);
                    });
                }
                else {
                    Notification.requestPermission(function(p){
                        console.log(p);
                        HandleNotifyPermission(p)
                    });
                }
            }
        }
    });


    // Save configration data for external video conference users
    $("#vidConfExternalTable").on("click", ".saveExtConfExtension", function() {

      if ($(this).val() == "Save") {

        var extUserExtension = $(this).closest('tr').find('input.extConfExtension').val();
        var extUserExtensionPass = $(this).closest('tr').find('input.extConfExtensionPass').val();

        var WSSServer = localDB.getItem("wssServer");

        if (extUserExtension != '' && extUserExtensionPass != '') {
          if (extUserExtension.length < 200 && extUserExtensionPass.length < 400) {
            // Check if the extension that has been entered is valid
            if (/^[a-zA-Z0-9]+$/.test(extUserExtension)) {

              $.ajax({
                 type: "POST",
                 url: "save-update-external-user-conf.php",
                 dataType: "JSON",
                 data: {
                        username: userName,
                        exten_for_external: extUserExtension,
                        exten_for_ext_pass: extUserExtensionPass,
                        wss_server: WSSServer,
                        s_ajax_call: validateSToken
                     },
                 success: function(response) {

                                 if (response.result == 'The data has been successfully saved to the database !') {

                                     getExternalUserConfFromSqldb();
                                     alert("The data has been successfully saved to the database ! To see the result, please reopen this window !");

                                     $("#jg_popup_b").empty(); $("#jg_popup_l").empty(); $("#windowCtrls").empty(); closeVideoAudio(); $.jeegoopopup.close();

                                 } else { alert(response.result); }

                 },
                 error: function(response) {
                                 alert("An error occurred while trying to save the data to the database !");
                 }
              });

              $(this).closest('[class="btnTableRow"]').find('[class="extConfExtension"]').attr("disabled", true);
              $(this).closest('[class="btnTableRow"]').find('[class="extConfExtensionPass"]').attr("disabled", true);
              $(this).attr("value", "Edit");
              $(this).prop("title", "Edit this row.");

            } else { alert("The extension should contain only numbers and letters."); }
          } else { alert("The extension and/or the SIP password don't have a reasonable length."); }
        } else { alert("Please fill in both the \"Extension\" and the \"SIP Password\" fields !"); }
      } else {
          $(this).closest('[class="btnTableRow"]').find('[class="extConfExtension"]').attr("disabled", false);
          $(this).closest('[class="btnTableRow"]').find('[class="extConfExtensionPass"]').attr("disabled", false);
          $(this).attr("value", "Save");
          $(this).prop("title", "Save this row.");
      }
    });

    // Delete extension data from the database
    $("#vidConfExternalTable").on("click", ".deleteExtRow", function() {

      var targetExtension = $(this).closest('[class="btnTableRow"]').find('[class="extConfExtension"]').val();

      if (targetExtension != '') {

         if (confirm("Do you really want to delete this row from this window and from the database ?")) {

             $.ajax({
                 type: "POST",
                 url: "remove-external-user-ext-data.php",
                 dataType: "JSON",
                 data: {
                        username: userName,
                        exten_for_external: targetExtension,
                        s_ajax_call: validateSToken
                       },
                 success: function(response) {
                                   $(this).closest('tr').find('input.extConfExtension').empty();
                                   $(this).closest('tr').find('input.extConfExtensionPass').empty();
                                   $(this).closest('tr').find('input.extConfExtensionLink').empty();
                                   getExternalUserConfFromSqldb();
                                   alert("The data has been permanently removed !");
                 },
                 error: function(response) {
                             alert("An error occurred while trying to remove the data !");
                 }
             });

             $(this).closest('[class="btnTableRow"]').hide();
         }
      }
    });

    $(".copyToClipboard").mouseenter(function() {
        if ($(this).closest('[class="btnTableRow"]').find('[class="extConfExtensionLink"]').val() != '') {
            $(this).css("color", "#424242");
            $(this).css("cursor", "pointer");
        }
    });

    $(".copyToClipboard").mouseleave(function() {
        $(this).css("color", "#cccccc");
    });

    $(".copyToClipboard").click(function() {
        if ($(this).closest('[class="btnTableRow"]').find('[class="extConfExtensionLink"]').val() != '') {
	      var $tempEl = $("<input>");
	      $("body").append($tempEl);
	      $tempEl.val($(this).closest('[class="btnTableRow"]').find('[class="extConfExtensionLink"]').val()).select();
	      document.execCommand("Copy");
	      $tempEl.remove();
	      alert("The link has been copied to your clipboard!");
        }
    });

    var externUserData = getDbItem("externalUserConfElem", "");
    if (externUserData !== 'undefined' && externUserData != 'null' && externUserData != 0) {
        $("#emptyExtRow").hide();
    }

    $("#add_New_External_User").click(function() {
       $("#vidConfExternalTable").append("<tr class=btnTableRow><td><input type=text class=extConfExtension name=extConfExtension placeholder=\"Eg: 711\" /></td><td><input type=password class=extConfExtensionPass name=extConfExtensionPass placeholder=\"Eg: d5?W?9q?8rg*R9!eFrVth?9\" /></td><td><input type=text class=\"extConfExtensionLink\" name=extConfExtensionLink  placeholder=\"Generated on 'Save'\" disabled=\"disabled\" /></td><td><span class=\"copyToClipboard\"><i class=\"fa fa-clipboard\" aria-hidden=\"true\" title=\"Copy link to clipboard.\"></i></span></td><td><span class=\"deleteExtRow deleteExtRowDisabled\" title=\"Delete extension data from database.\">X</span></td><td><input type=submit class=\"saveExtConfExtension\" value=\"Save\" title=\"Save this row.\" /></td></tr>");
    });


    // Profile Picture
    cropper = $("#ImageCanvas").croppie({
        viewport: { width: 150, height: 150, type: 'circle' }
    });

    // Preview Existing Image
    $("#ImageCanvas").croppie('bind', { url: getPicture("profilePicture") }).then(function() {
       $('.cr-slider').attr({ min: 0.5, max: 3 });
    });

    // Wireup File Change
    $("#fileUploader").change(function () {
        var filesArray = $(this).prop('files');
    
        if (filesArray.length == 1) {
            var uploadId = Math.floor(Math.random() * 1000000000);
            var fileObj = filesArray[0];
            var fileName = fileObj.name;
            var fileSize = fileObj.size;
    
            if (fileSize <= 52428800) {
                console.log("Adding (" + uploadId + "): " + fileName + " of size: " + fileSize + "bytes");
    
                var reader = new FileReader();
                reader.Name = fileName;
                reader.UploadId = uploadId;
                reader.Size = fileSize;
                reader.onload = function (event) {
                    $("#ImageCanvas").croppie('bind', {
                        url: event.target.result
                    });
                }

                // Use onload for this
                reader.readAsDataURL(fileObj);
            }
            else {
                Alert(lang.alert_file_size, lang.error);
            }
        }
        else {
            Alert(lang.alert_single_file, lang.error);
        }
    });


    $("#save_button_conf").click(function() {

        if(localDB.getItem("profileUserID") == null) localDB.setItem("profileUserID", uID()); // For first time only

        var confAccWssServer = $("#Configure_Account_wssServer").val();
        if (/^[A-Za-z0-9\.\-]+\.[A-Za-z0-9\-]{2,63}$/.test(confAccWssServer)) { var finconfAccWssServer = confAccWssServer; } else { 
            var finconfAccWssServer = ''; alert('The WebSocket domain that you entered is not a valid domain name!'); }

        var confAccWSPort = $("#Configure_Account_WebSocketPort").val();
        if (/^[0-9]+$/.test(confAccWSPort)) { var finConfAccWSPort = confAccWSPort; } else { 
            var finConfAccWSPort = ''; alert('The web socket port that you entered is not a valid port!'); }

        var confAccServerPath = $("#Configure_Account_ServerPath").val();
        if (/^[A-Za-z0-9\/]+$/.test(confAccServerPath)) { var finConfAccServerPath = confAccServerPath; } else { 
            var finConfAccServerPath = ''; alert('The server path that you entered is not a valid server path!');}

        var confAccProfileName = $("#Configure_Account_profileName").val();
        if (/^[A-Za-z0-9\s\-\'\[\]\(\)]+$/.test(confAccProfileName)) { var finConfAccProfileName = confAccProfileName; } else { 
            var finConfAccProfileName = ''; alert('The profile name that you entered is not a valid profile name!'); }

        var confAccSipUsername = $("#Configure_Account_SipUsername").val();
        if (/^[A-Za-z0-9\-\.\_\@\*\!\?\&\~\(\)\[\]]+$/.test(confAccSipUsername)) { var finConfAccSipUsername = confAccSipUsername; } else { 
            var finConfAccSipUsername = ''; alert('The SIP username that you entered is not a valid SIP username!'); }

        var confAccSipPassword = $("#Configure_Account_SipPassword").val();
        if (confAccSipPassword.length < 400) { var finConfAccSipPassword = confAccSipPassword; } else { 
            var finConfAccSipPassword = ''; alert('The SIP password that you entered is too long!'); }

        var confAccStun = $("#Configure_Account_StunServer").val();
        if (confAccStun != null && confAccStun.trim() !== '') {
            if (/^(\d+\.\d+\.\d+\.\d+:\d+)$|^([A-Za-z0-9\.\-]+\.[A-Za-z0-9\-]{2,63}:\d+)/.test(confAccStun)) { var finConfAccStun = confAccStun; } else { 
                var finConfAccStun = ''; alert('The domain or IP or port number of the STUN server is not valid!'); }
        } else { var finConfAccStun = ''; }

        if (finconfAccWssServer != null && finconfAccWssServer.trim() !== '' &&
            finConfAccWSPort != null && finConfAccWSPort.trim() !== '' &&
            finConfAccServerPath != null && finConfAccServerPath.trim() !== '' &&
            finConfAccProfileName != null && finConfAccProfileName.trim() !== '' &&
            finConfAccSipUsername != null && finConfAccSipUsername.trim() !== '' &&
            finConfAccSipPassword != null && finConfAccSipPassword.trim() !== '') {

            // OK

        } else { alert('All fields marked with an asterisk are required!'); return; }


        // Audio & Video
        localDB.setItem("AudioOutputId", $("#playbackSrc").val());
        localDB.setItem("VideoSrcId", $("#previewVideoSrc").val());
        localDB.setItem("VideoHeight", $("input[name=Settings_Quality]:checked").val());
        localDB.setItem("FrameRate", $("input[name=Settings_FrameRate]:checked").val());
        localDB.setItem("AspectRatio", $("input[name=Settings_AspectRatio]:checked").val());
        localDB.setItem("VideoOrientation", $("input[name=Settings_Oriteation]:checked").val());
        localDB.setItem("AudioSrcId", $("#microphoneSrc").val());
        localDB.setItem("AutoGainControl", ($("#Settings_AutoGainControl").is(':checked'))? "1" : "0");
        localDB.setItem("EchoCancellation", ($("#Settings_EchoCancellation").is(':checked'))? "1" : "0");
        localDB.setItem("NoiseSuppression", ($("#Settings_NoiseSuppression").is(':checked'))? "1" : "0");
        localDB.setItem("RingOutputId", $("#ringDevice").val());

        // Check if the extension that has been entered is valid
        var videoConfExten = $("#Video_Conf_Extension").val();
        if (/^[a-zA-Z0-9\*\#]+$/.test(videoConfExten)) { var finVideoConfExten = videoConfExten; } else { 
            var finVideoConfExten = ''; alert("The extension that you entered in the 'Video Conference Extension' field is not a valid extension!");}

        localDB.setItem("VidConfExtension", finVideoConfExten);

        var videoConfWinWidth = $("#Video_Conf_Window_Width").val();
        if ((/^[0-9]+$/.test(videoConfWinWidth)) && Math.abs(videoConfWinWidth) <= 100) { var finVideoConfWinWidth = Math.abs(videoConfWinWidth); } else { 
             var finVideoConfWinWidth = ''; alert("The percent value that you entered in the 'Percent of screen width ...' field is not valid!"); }

        localDB.setItem("VidConfWindowWidth", finVideoConfWinWidth);

        localDB.setItem("Notifications", ($("#Settings_Notifications").is(":checked"))? "1" : "0");

        if ($("#emailIntegration").is(":checked")) {

            if (/^[A-Za-z0-9\.\-]+\.[A-Za-z0-9\-]{2,63}$/.test($("#RoundcubeDomain").val())) {} else {
                $("#emailIntegration").prop("checked", false);
                $("#RoundcubeDomain").val("");
                alert("The Roundcube domain is not valid. After entering a valid Roundcube domain, please remember to check the checkbox 'Enable Roundcube email integration' again !");
                return;
            }

            if (/^[A-Za-z0-9\_\.\-\@\~\%\+\!\?\&\*\^\=\#\$\{\}\|\/]{1,300}$/.test($("#RoundcubeUser").val())) {} else {
                $("#emailIntegration").prop("checked", false);
                $("#RoundcubeUser").val("");
                alert("The Roundcube user is not valid. After entering a valid Roundcube user, please remember to check the checkbox 'Enable Roundcube email integration' again !");
                return;
            }

            if ($("#RoundcubePass").val() == '' || $("#RoundcubePass").val().length > 300) { 
                $("#emailIntegration").prop("checked", false); 
                $("#RoundcubePass").val("");
                alert("The Roundcube password is not valid. After entering a valid Roundcube password, please remember to check the checkbox 'Enable Roundcube email integration' again !");
                return;
            }

            if ($("#rcBasicAuthUser").val().length > 300) { $("#rcBasicAuthUser").val(""); alert("The Roundcube basic authentication user is not valid."); return; }

            if ($("#rcBasicAuthPass").val().length > 300) { $("#rcBasicAuthPass").val(""); alert("The Roundcube basic authentication password is not valid."); return; }
        }

        // The profile picture can't be saved if the style of its section is 'display: none;'
        $("#AppearanceHtml").css({ 'display' : 'block', 'visibility' : 'hidden', 'margin-top' : '-228px' });


        // Convert the profile picture to base64
        $("#ImageCanvas").croppie('result', {
            type: 'base64',
            size: 'viewport',
            format: 'png',
            quality: 1,
            circle: false
        }).then(function(base64) {
            localDB.setItem("profilePicture", base64);
        });

        setTimeout(function() {
            saveConfToSqldb();
        }, 600);

    });

    $("#closeImg").click(function() { $("#jg_popup_b").empty(); $("#jg_popup_l").empty(); $("#windowCtrls").empty(); closeVideoAudio(); $.jeegoopopup.close(); });
    $("#cancel_button_conf").click(function() { $("#jg_popup_b").empty(); $("#jg_popup_l").empty(); $("#windowCtrls").empty(); closeVideoAudio(); $.jeegoopopup.close(); });
    $("#jg_popup_overlay").click(function() { $("#jg_popup_b").empty(); $("#jg_popup_l").empty(); $("#windowCtrls").empty(); closeVideoAudio(); $.jeegoopopup.close(); });
    $(window).on('keydown', function(event) { if (event.key == "Escape") { $("#jg_popup_b").empty(); $("#jg_popup_l").empty(); $("#windowCtrls").empty(); closeVideoAudio(); $.jeegoopopup.close(); } });

}

function checkNotificationPromise() {
    try {
        Notification.requestPermission().then();
    }
    catch(e) {
        return false;
    }
    return true;
}
function HandleNotifyPermission(p){

    if(p == "granted") {
       // Good
    } else {
        Alert(lang.alert_notification_permission, lang.permission, function(){
            console.log("Attempting to uncheck the checkbox...");
            $("#Settings_Notifications").prop("checked", false);
        });
    }
}
function EditBuddyWindow(buddy){

    $.jeegoopopup.close();

    var buddyObj = null;
    var itemId = -1;
    var json = JSON.parse(localDB.getItem(profileUserID + "-Buddies"));
    $.each(json.DataCollection, function (i, item) {
        if(item.uID == buddy || item.cID == buddy || item.gID == buddy){
            buddyObj = item;
            itemId = i;
            return false;
        }
    });

    if(buddyObj == null){
        Alert(lang.alert_not_found, lang.error);
        return;
    }

    var html = "<div id='EditContact'>";

    html += "<div id='windowCtrls'><img id='minimizeImg' src='images/1_minimize.svg' title='Restore' /><img id='maximizeImg' src='images/2_maximize.svg' title='Maximize' /><img id='closeImg' src='images/3_close.svg' title='Close' /></div>";

    html += "<div class='UiWindowField scroller'>";

    html += "<div id=ImageCanvas style=\"width:150px; height:150px\"></div>";
    html += "<label for=ebFileUploader class=customBrowseButton style=\"margin-left: 200px; margin-top: -9px;\">Select File</label>";
    html += "<div><input type=file id=ebFileUploader /></div>";
    html += "<div style=\"margin-top: 50px\"></div>";

    html += "<div class=UiText>"+ lang.display_name +":</div>";

    html += "<div><input id=AddSomeone_Name class=UiInputText type=text placeholder='"+ lang.eg_display_name +"' value='"+ ((buddyObj.DisplayName && buddyObj.DisplayName != "null" && buddyObj.DisplayName != "undefined")? buddyObj.DisplayName : "") +"'></div>";

    html += "<div class=UiText>"+ lang.title_description +":</div>";

    if(buddyObj.Type == "extension"){
        html += "<div><input id=AddSomeone_Desc class=UiInputText type=text placeholder='"+ lang.eg_general_manager +"' value='"+ ((buddyObj.Position && buddyObj.Position != "null" && buddyObj.Position != "undefined")? buddyObj.Position : "") +"'></div>";
    }
    else {
        html += "<div><input id=AddSomeone_Desc class=UiInputText type=text placeholder='"+ lang.eg_general_manager +"' value='"+ ((buddyObj.Description && buddyObj.Description != "null" && buddyObj.Description != "undefined")? buddyObj.Description : "") +"'></div>";
    }

    html += "<div class=UiText>"+ lang.internal_subscribe_extension +":</div>";
    html += "<div><input id=AddSomeone_Exten class=UiInputText type=text placeholder='"+ lang.eg_internal_subscribe_extension +"' value='"+ ((buddyObj.ExtensionNumber && buddyObj.ExtensionNumber != "null" && buddyObj.ExtensionNumber != "undefined")? buddyObj.ExtensionNumber : "") +"'></div>";

    html += "<div class=UiText>"+ lang.mobile_number +":</div>";
    html += "<div><input id=AddSomeone_Mobile class=UiInputText type=text placeholder='"+ lang.eg_mobile_number +"' value='"+ ((buddyObj.MobileNumber && buddyObj.MobileNumber != "null" && buddyObj.MobileNumber != "undefined")? buddyObj.MobileNumber : "") +"'></div>";

    html += "<div class=UiText>"+ lang.contact_number_1 +":</div>";
    html += "<div><input id=AddSomeone_Num1 class=UiInputText type=text placeholder='"+ lang.eg_contact_number_1 +"' value='"+((buddyObj.ContactNumber1 && buddyObj.ContactNumber1 != "null" && buddyObj.ContactNumber1 != "undefined")? buddyObj.ContactNumber1 : "") +"'></div>";

    html += "<div class=UiText>"+ lang.contact_number_2 +":</div>";
    html += "<div><input id=AddSomeone_Num2 class=UiInputText type=text placeholder='"+ lang.eg_contact_number_2 +"' value='"+ ((buddyObj.ContactNumber2 && buddyObj.ContactNumber2 != "null" && buddyObj.ContactNumber2 != "undefined")? buddyObj.ContactNumber2 : "") +"'></div>";

    html += "<div class=UiText>"+ lang.email +":</div>";
    html += "<div><input id=AddSomeone_Email class=UiInputText type=text placeholder='"+ lang.email +"' value='"+ ((buddyObj.Email && buddyObj.Email != "null" && buddyObj.Email != "undefined")? buddyObj.Email : "") +"'></div>";

    html += "</div></div>"

    $.jeegoopopup.open({
                title: 'Edit Contact',
                html: html,
                width: '640',
                height: '500',
                center: true,
                scrolling: 'no',
                skinClass: 'jg_popup_basic',
                contentClass: 'editContactPopup',
                overlay: true,
                opacity: 50,
                draggable: true,
                resizable: false,
                fadeIn: 0
    });

    $("#jg_popup_b").append("<div id=bottomButtons><button id=save_button>Save</button><button id=cancel_button>Cancel</button></div>");


    var contactDatabaseId = '';

    $.ajax({
        type: "POST",
        url: "get-contact-dbid.php",
        dataType: "JSON",
        data: {
            username: userName,
            contact_name: buddyObj.DisplayName,
            s_ajax_call: validateSToken
        },
        success: function(response) {
                 if (response.successorfailure == 'success') {
                     contactDatabaseId = response.cntctDatabaseID;
                 } else { alert("Error while attempting to retrieve contact data from the database!"); }
        },
        error: function(response) {
                 alert("Error while attempting to retrieve contact data from the database!");
        }
    });

    // DoOnLoad
    var cropper = $("#ImageCanvas").croppie({
              viewport: { width: 150, height: 150, type: 'circle' }
    });

    // Preview Existing Image
    if(buddyObj.Type == "extension"){
       $("#ImageCanvas").croppie('bind', { url: getPicture(buddyObj.uID, "extension") }).then(function() {
          $('.cr-slider').attr({ min: 0.5, max: 3 });
       });
    } else if(buddyObj.Type == "contact") {
            $("#ImageCanvas").croppie('bind', { url: getPicture(buddyObj.cID, "contact") }).then(function() {
               $('.cr-slider').attr({ min: 0.5, max: 3 });
            });
    } else if(buddyObj.Type == "group") {
            $("#ImageCanvas").croppie('bind', { url: getPicture(buddyObj.gID, "group") }).then(function() {
               $('.cr-slider').attr({ min: 0.5, max: 3 });
            });
    }

    // Wireup File Change
    $("#ebFileUploader").change(function () {

        var filesArray = $(this).prop('files');
        
        if (filesArray.length == 1) {
            var uploadId = Math.floor(Math.random() * 1000000000);
            var fileObj = filesArray[0];
            var fileName = fileObj.name;
            var fileSize = fileObj.size;
        
            if (fileSize <= 52428800) {
                console.log("Adding (" + uploadId + "): " + fileName + " of size: " + fileSize + "bytes");
      
                var reader = new FileReader();
                reader.Name = fileName;
                reader.UploadId = uploadId;
                reader.Size = fileSize;
                reader.onload = function (event) {
                    $("#ImageCanvas").croppie('bind', {
                       url: event.target.result
                    });
                }
                reader.readAsDataURL(fileObj);
            } else {
                Alert(lang.alert_file_size, lang.error);
            }
        } else {
                Alert(lang.alert_single_file, lang.error);
        }
    });

    $("#save_button").click(function() {

      var currentCtctName = $("#AddSomeone_Name").val();

      if (currentCtctName != null && currentCtctName.trim() !== '') {

        if (/^[A-Za-z0-9\s\-\'\[\]\(\)]+$/.test(currentCtctName)) {

            buddyObj.LastActivity = utcDateNow();
            buddyObj.DisplayName = currentCtctName;

	    var currentDesc = $("#AddSomeone_Desc").val();
	    if (currentDesc != null && currentDesc.trim() !== '') {
	        if (/^[A-Za-z0-9\s\-\.\'\"\[\]\(\)\{\}\_\!\?\~\@\%\^\&\*\+\>\<\;\:\=]+$/.test(currentDesc)) { var finCurrentDesc = currentDesc; } else { 
		    var finCurrentDesc = ''; alert('The title/description that you entered is not valid!'); }
	    } else { var finCurrentDesc = ''; }

            if(buddyObj.Type == "extension") {
                buddyObj.Position = finCurrentDesc;

            } else {
                buddyObj.Description = finCurrentDesc;
            }

	    var currentExtension = $("#AddSomeone_Exten").val();
	    if (currentExtension != null && currentExtension.trim() !== '') {
	        if (/^[a-zA-Z0-9\*\#]+$/.test(currentExtension)) { var finCurrentExtension = currentExtension; } else { 
		    var finCurrentExtension = ''; alert("The extension that you entered in the 'Extension (Internal)' field is not a valid extension!"); }
	    } else { var finCurrentExtension = ''; }

            buddyObj.ExtensionNumber = finCurrentExtension;

	    var currentMobile = $("#AddSomeone_Mobile").val();
	    if (currentMobile != null && currentMobile.trim() !== '') {
	        if (/^[0-9\s\+\#]+$/.test(currentMobile)) { var finCurrentMobile = currentMobile; } else {
		    var finCurrentMobile = ''; alert("The phone number that you entered in the 'Mobile Number' field is not valid! The only allowed characters are: digits, spaces, plus signs and pound signs."); }
	    } else { var finCurrentMobile = ''; }

            buddyObj.MobileNumber = finCurrentMobile;

	    var currentNum1 = $("#AddSomeone_Num1").val();
	    if (currentNum1 != null && currentNum1.trim() !== '') {
	        if (/^[0-9\s\+\#]+$/.test(currentNum1)) { var finCurrentNum1 = currentNum1; } else {
		    var finCurrentNum1 = ''; alert("The phone number that you entered in the 'Contact Number 1' field is not valid! The only allowed characters are: digits, spaces, plus signs and pound signs."); }
	    } else { var finCurrentNum1 = ''; }

            buddyObj.ContactNumber1 = finCurrentNum1;

	    var currentNum2 = $("#AddSomeone_Num2").val();
	    if (currentNum2 != null && currentNum2.trim() !== '') {
	        if (/^[0-9\s\+\#]+$/.test(currentNum2)) { var finCurrentNum2 = currentNum2; } else {
		    var finCurrentNum2 = ''; alert("The phone number that you entered in the 'Contact Number 2' field is not valid! The only allowed characters are: digits, spaces, plus signs and pound signs."); }
            } else { var finCurrentNum2 = ''; }

            buddyObj.ContactNumber2 = finCurrentNum2;

	    var currentEmail = $("#AddSomeone_Email").val();
	    if (currentEmail != null && currentEmail.trim() !== '') {
	        if (/^[A-Za-z0-9\_\.\-\~\%\+\!\?\&\*\^\=\#\$\{\}\|\/]+@[A-Za-z0-9\.\-]+\.[A-Za-z0-9\-]{2,63}$/.test(currentEmail)) { var finCurrentEmail = currentEmail; } else {
		    var finCurrentEmail = ''; alert("The email that you entered is not a valid email address!"); }
	    } else { var finCurrentEmail = ''; }

            buddyObj.Email = finCurrentEmail;


            // Update Image
            var constraints = { 
                type: 'base64', 
                size: 'viewport', 
                format: 'png', 
                quality: 1, 
                circle: false 
            }

            $("#ImageCanvas").croppie('result', constraints).then(function(base64) {
                if(buddyObj.Type == "extension"){
                    localDB.setItem("img-"+ buddyObj.uID +"-extension", base64);
                    $("#contact-"+ buddyObj.uID +"-picture-main").css("background-image", 'url('+ getPicture(buddyObj.uID, 'extension') +')');
                    $("#contact-"+ buddyObj.uID +"-presence-main").html(buddyObj.Position);

                    // Save contact picture to SQL database
		    var newPic = [];
                    newPic = [buddyObj.DisplayName, localDB.getItem("img-"+ buddyObj.uID +"-extension", base64)];
		    saveContactPicToSQLDB(newPic);
                }
                else if(buddyObj.Type == "contact") {
                    localDB.setItem("img-"+ buddyObj.cID +"-contact", base64);
                    $("#contact-"+ buddyObj.cID +"-picture-main").css("background-image", 'url('+ getPicture(buddyObj.cID, 'contact') +')');
                    $("#contact-"+ buddyObj.cID +"-presence-main").html(buddyObj.Description);

                    // Save contact picture to SQL database
		    var newPic = [];
		    newPic = [buddyObj.DisplayName, localDB.getItem("img-"+ buddyObj.cID +"-contact", base64)];
		    saveContactPicToSQLDB(newPic);
                }
                else if(buddyObj.Type == "group") {
                    localDB.setItem("img-"+ buddyObj.gID +"-group", base64);
                    $("#contact-"+ buddyObj.gID +"-picture-main").css("background-image", 'url('+ getPicture(buddyObj.gID, 'group') +')');
                    $("#contact-"+ buddyObj.gID +"-presence-main").html(buddyObj.Description);

                    // Save contact picture to SQL database
		    var newPic = [];
		    newPic = [buddyObj.DisplayName, localDB.getItem("img-"+ buddyObj.gID +"-group", base64)];
		    saveContactPicToSQLDB(newPic);
                }

                // Update
                UpdateBuddyList();
            });

            // Update: 
            json.DataCollection[itemId] = buddyObj;

            // Save To DB
            localDB.setItem(profileUserID + "-Buddies", JSON.stringify(json));

            var newPerson = [];

            newPerson = [currentCtctName, finCurrentDesc, finCurrentExtension, finCurrentMobile, finCurrentNum1, finCurrentNum2, finCurrentEmail, contactDatabaseId];

            updateContactToSQLDB(newPerson);

            // Update the Memory Array, so that the UpdateBuddyList can make the changes
            for(var b = 0; b < Buddies.length; b++) {
                if(buddyObj.Type == "extension"){
                    if(buddyObj.uID == Buddies[b].identity){
                        Buddies[b].lastActivity = buddyObj.LastActivity;
                        Buddies[b].CallerIDName = buddyObj.DisplayName;
                        Buddies[b].Desc = buddyObj.Position;
                    }                
                }
                else if(buddyObj.Type == "contact") {
                    if(buddyObj.cID == Buddies[b].identity){
                        Buddies[b].lastActivity = buddyObj.LastActivity;
                        Buddies[b].CallerIDName = buddyObj.DisplayName;
                        Buddies[b].Desc = buddyObj.Description;
                    }                
                }
                else if(buddyObj.Type == "group") {
                
                }
            }

            UpdateBuddyList();

            $.jeegoopopup.close();
            $("#jg_popup_b").empty();

        } else { alert('The display name that you entered is not a valid display name!'); }

      } else { alert("'Display Name' cannot be empty!"); }

    });

    var maxWidth = $(window).width() - 16;
    var maxHeight = $(window).height() - 110;

    if (maxWidth < 656 || maxHeight < 500) { 
        $.jeegoopopup.width(maxWidth).height(maxHeight);
        $.jeegoopopup.center();
        $("#maximizeImg").hide();
        $("#minimizeImg").hide();
    } else { 
        $.jeegoopopup.width(640).height(500);
        $.jeegoopopup.center();
        $("#minimizeImg").hide();
        $("#maximizeImg").show();
    }

    $(window).resize(function() {
        maxWidth = $(window).width() - 16;
        maxHeight = $(window).height() - 110;
        $.jeegoopopup.center();
        if (maxWidth < 656 || maxHeight < 500) { 
            $.jeegoopopup.width(maxWidth).height(maxHeight);
            $.jeegoopopup.center();
            $("#maximizeImg").hide();
            $("#minimizeImg").hide();
        } else { 
            $.jeegoopopup.width(640).height(500);
            $.jeegoopopup.center();
            $("#minimizeImg").hide();
            $("#maximizeImg").show();
        }
    });

    $("#minimizeImg").click(function() { $.jeegoopopup.width(640).height(500); $.jeegoopopup.center(); $("#maximizeImg").show(); $("#minimizeImg").hide(); });
    $("#maximizeImg").click(function() { $.jeegoopopup.width(maxWidth).height(maxHeight); $.jeegoopopup.center(); $("#minimizeImg").show(); $("#maximizeImg").hide(); });

    $("#closeImg").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
    $("#cancel_button").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); $("#jg_popup_b").empty(); } });
}

// Document Ready
// ==============
$(document).ready(function () {
    
    // Load Langauge File
    // ==================
    $.getJSON(hostingPrefex + "lang/en.json", function (data){
        lang = data;
        var userLang = GetAlternateLanguage();
        if(userLang != ""){
            $.getJSON(hostingPrefex +"lang/"+ userLang +".json", function (altdata){
                lang = altdata;
            }).always(function() {
                console.log("Alternate Lanaguage Pack loaded: ", lang);
                InitUi();
            });
        }
        else {
            console.log("Lanaguage Pack already loaded: ", lang);
            InitUi();
        }
    });

    // Get configuration data from SQL database
    getConfFromSqldb();
    getExternalUserConfFromSqldb();
});

// Init UI
// =======
function InitUi(){

    var phone = $("#Phone");
    phone.empty();
    phone.attr("class", "pageContainer");

    // Left Section
    var leftSection = $("<div>");
    leftSection.attr("id", "leftContent");
    leftSection.attr("style", "float:left; height: 100%; width:320px");

    var leftHTML = "<table style=\"height:100%; width:100%\" cellspacing=5 cellpadding=0>";
    leftHTML += "<tr><td class=logoSection style=\"height: 50px\"><div id=\"smallLogo\"><img src=\"images/small-logo.svg\" /></div><div id=\"inLogoSection\"><div id=\"emailInLogoSection\" onclick=\"ShowEmailWindow()\" title=\"Email\"><i class=\"fa fa-envelope-o\" aria-hidden=\"true\"></i></div><div id=\"aboutInLogoSection\" onclick=\"ShowAboutWindow()\" title=\"About\"><button id=\"aboutImg\"></button></div><div id=\"shrinkLeftPanel\" onclick=\"CollapseLeftPanel()\" title=\"Collapse\"><button id=\"collapseLeftPanel\"></button></div></div></td></tr>";
    leftHTML += "<tr><td class=streamSection style=\"height: 82px\">";

    // Profile User
    leftHTML += "<div class=profileContainer>";
    leftHTML += "<div class=contact id=UserProfile style=\"margin-bottom:12px;\">";
    leftHTML += "<div id=UserProfilePic class=buddyIcon title=\"Status\"></div>";
    leftHTML += "<span id=reglink class=dotOffline></span>";
    leftHTML += "<span id=dereglink class=dotOnline style=\"display:none\"><i class=\"fa fa-wifi\" style=\"line-height: 14px; text-align: center; display: block;\"></i></span>";
    leftHTML += "<span id=WebRtcFailed class=dotFailed style=\"display:none\"><i class=\"fa fa-cross\" style=\"line-height: 14px; text-align: center; display: block;\"></i></span>";
    leftHTML += "<div class=contactNameText style=\"margin-right: 0px;\"><i class=\"fa fa-phone-square\"></i> <span id=UserDID></span> - <span id=UserCallID></span></div>";
    leftHTML += "<div id=regStatus class=presenceText>&nbsp;</div>";
    leftHTML += "</div>";
    // Search / Add Buddies
    leftHTML += "<div id=searchBoxAndIcons>";
    leftHTML += "<span class=searchClean><INPUT id=txtFindBuddy type=text autocomplete=none style=\"width:142px;\" title=\"Find Contact\"></span>";
    leftHTML += "<div id=ButtonsOnSearchLine>";
    leftHTML += "<button id=BtnFreeDial title='"+ lang.dial_number +"'></button>";
    leftHTML += "<button id=LaunchVideoConf title='"+ lang.launch_video_conference +"'><i class=\"fa fa-users\"></i></button>";
    leftHTML += "<button id=BtnSettings title='"+ lang.account_settings +"'><i class=\"fa fa-cog\"></i></button>";
    leftHTML += "</div>";
    leftHTML += "</div>";
    leftHTML += "</div>";
    leftHTML += "</td></tr>";
    // Lines & Buddies
    leftHTML += "<tr><td class=streamSection><div id=myContacts class=\"contactArea cleanScroller\"></div></td></tr>";
    leftHTML += "</table>";

    leftSection.html(leftHTML);
    
    // Right Section
    var rightSection = $("<div>");
    rightSection.attr("id", "rightContent");
    rightSection.attr("style", "margin-left: 320px; height: 100%; overflow: auto;");

    phone.append(leftSection);
    phone.append(rightSection);

    // Setup Windows
    windowsCollection = '';
    messagingCollection = '';

    if(DisableFreeDial == true) $("#BtnFreeDial").hide();
    if(DisableBuddies == true) $("#BtnAddSomeone").hide();
    if(enabledGroupServices == false) $("#BtnCreateGroup").hide();

    $("#UserDID").html(profileUser);
    $("#UserCallID").html(profileName);
    $("#UserProfilePic").css("background-image", "url('"+ getPicture("profilePicture") +"')");
    
    $("#txtFindBuddy").attr("placeholder", lang.find_someone);
    $("#txtFindBuddy").on('keyup', function(event){
        UpdateBuddyList();
    });

    $("#BtnFreeDial").on('click', function(event){
        ShowDial(this);
    });

    $("#BtnAddSomeone").attr("title", lang.add_contact);
    $("#BtnAddSomeone").on('click', function(event){
        AddSomeoneWindow();
    });

    $("#BtnCreateGroup").attr("title", lang.create_group);
    $("#BtnCreateGroup").on('click', function(event){
        CreateGroupWindow();
    });

    $("#LaunchVideoConf").on('click', function(event){
       ShowLaunchVidConfMenu(this);
    });

    $("#BtnSettings").on('click', function(event){
       ShowAccountSettingsMenu(this);
    });

    $("#UserProfile").on('click', function(event){
        ShowMyProfileMenu(this);
    });

    UpdateUI();
    
    PopulateBuddyList();

    // Select Last user
    if(localDB.getItem("SelectedBuddy") != null){
        console.log("Selecting previously selected buddy...", localDB.getItem("SelectedBuddy"));
        SelectBuddy(localDB.getItem("SelectedBuddy"));
        UpdateUI();
    }

    PreloadAudioFiles();

    CreateUserAgent();

    getContactsFromSQLDB();

    generateChatRSAKeys(getDbItem("SipUsername", ""));

    removeTextChatUploads(getDbItem("SipUsername", ""));
}

function PreloadAudioFiles(){
    audioBlobs.Alert = { file : "Alert.mp3", url : hostingPrefex +"sounds/Alert.mp3" }
    audioBlobs.Ringtone = { file : "Ringtone_1.mp3", url : hostingPrefex +"sounds/Ringtone_1.mp3" }
    audioBlobs.speaker_test = { file : "Speaker_test.mp3", url : hostingPrefex +"sounds/Speaker_test.mp3" }
    audioBlobs.Busy_UK = { file : "Tone_Busy-UK.mp3", url : hostingPrefex +"sounds/Tone_Busy-UK.mp3" }
    audioBlobs.Busy_US = { file : "Tone_Busy-US.mp3", url : hostingPrefex +"sounds/Tone_Busy-US.mp3" }
    audioBlobs.CallWaiting = { file : "Tone_CallWaiting.mp3", url : hostingPrefex +"sounds/Tone_CallWaiting.mp3" }
    audioBlobs.Congestion_UK = { file : "Tone_Congestion-UK.mp3", url : hostingPrefex +"sounds/Tone_Congestion-UK.mp3" }
    audioBlobs.Congestion_US = { file : "Tone_Congestion-US.mp3", url : hostingPrefex +"sounds/Tone_Congestion-US.mp3" }
    audioBlobs.EarlyMedia_Australia = { file : "Tone_EarlyMedia-Australia.mp3", url : hostingPrefex +"sounds/Tone_EarlyMedia-Australia.mp3" }
    audioBlobs.EarlyMedia_European = { file : "Tone_EarlyMedia-European.mp3", url : hostingPrefex +"sounds/Tone_EarlyMedia-European.mp3" }
    audioBlobs.EarlyMedia_Japan = { file : "Tone_EarlyMedia-Japan.mp3", url : hostingPrefex +"sounds/Tone_EarlyMedia-Japan.mp3" }
    audioBlobs.EarlyMedia_UK = { file : "Tone_EarlyMedia-UK.mp3", url : hostingPrefex +"sounds/Tone_EarlyMedia-UK.mp3" }
    audioBlobs.EarlyMedia_US = { file : "Tone_EarlyMedia-US.mp3", url : hostingPrefex +"sounds/Tone_EarlyMedia-US.mp3" }
    
    $.each(audioBlobs, function (i, item) {
        var oReq = new XMLHttpRequest();
        oReq.open("GET", item.url, true);
        oReq.responseType = "blob";
        oReq.onload = function(oEvent) {
            var reader = new FileReader();
            reader.readAsDataURL(oReq.response);
            reader.onload = function() {
                item.blob = reader.result;
            }
        }
        oReq.send();
    });
}
// Create User Agent
// =================
function CreateUserAgent() {

    $.ajax({
        'async': false,
        'global': false,
        type: "POST",
        url: "get-sippass.php",
        dataType: "JSON",
        data: {
                username: userName,
                s_ajax_call: validateSToken
        },
        success: function (sipdatafromdb) {
                       decSipPass = sipdatafromdb;
        },
        error: function(sipdatafromdb) {
                 alert("An error occurred while attempting to retrieve data from the database!");
        }
    });

    try {
        console.log("Creating User Agent...");
        var options = {
            displayName: profileName,
            uri: SipUsername + "@" + wssServer,
            transportOptions: {
                wsServers: "wss://" + wssServer + ":"+ WebSocketPort +""+ ServerPath,
                traceSip: false,
                connectionTimeout: TransportConnectionTimeout,
                maxReconnectionAttempts: TransportReconnectionAttempts,
                reconnectionTimeout: TransportReconnectionTimeout,
            },
            sessionDescriptionHandlerFactoryOptions:{
                peerConnectionOptions :{
                    alwaysAcquireMediaFirst: true, // Better for firefox, but seems to have no effect on others
                    iceCheckingTimeout: IceStunCheckTimeout,
                    rtcConfiguration: {}
                }
            },
            authorizationUser: SipUsername,
//            password: SipPassword,
            password: decSipPass,
            registerExpires: RegisterExpires,
            hackWssInTransport: WssInTransport,
            hackIpInContact: IpInContact,
            userAgentString: userAgentStr,
            autostart: false,
            register: false,
        }

        decSipPass = '';

        var currentStunServer = getDbItem("StunServer", "");

        if (currentStunServer == '' || currentStunServer == null || typeof currentStunServer == 'undefined') { 
            var IceStunServersList = '';
        } else { var IceStunServersList = '[{"urls":"stun:'+currentStunServer+'"}]'; }

        if (IceStunServersList != "") {
            options.sessionDescriptionHandlerFactoryOptions.peerConnectionOptions.rtcConfiguration.iceServers = JSON.parse(IceStunServersList);
        }

        userAgent = new SIP.UA(options);
        console.log("Creating User Agent... Done");
    }
    catch (e) {
        console.error("Error creating User Agent: "+ e);
        $("#regStatus").html(lang.error_user_agant);
        alert(e.message);
        return;
    }

    // UA Register events
    userAgent.on('registered', function () {
        // This code fires on re-regiter after session timeout
        // to ensure that events are not fired multiple times
        // an isReRegister state is kept.
        if(!isReRegister) {
            console.log("Registered!");

            $("#reglink").hide();
            $("#dereglink").show();
            if(DoNotDisturbEnabled || DoNotDisturbPolicy == "enabled") {
                $("#dereglink").attr("class", "dotDoNotDisturb");
            }

            // Start Subscribe Loop
            SubscribeAll();

            // Output to status
            $("#regStatus").html(lang.registered);

            // Custom Web hook
            if(typeof web_hook_on_register !== 'undefined') web_hook_on_register(userAgent);
        }
        isReRegister = true;
    });

    userAgent.on('registrationFailed', function (response, cause) {
        console.log("Registration Failed: " + cause);
        $("#regStatus").html(lang.registration_failed);

        $("#reglink").show();
        $("#dereglink").hide();

        // We set this flag here so that the re-register attepts are fully completed.
        isReRegister = false;

        // Custom Web hook
        if(typeof web_hook_on_registrationFailed !== 'undefined') web_hook_on_registrationFailed(cause);
    });
    userAgent.on('unregistered', function () {
        console.log("Unregistered, bye!");
        $("#regStatus").html(lang.unregistered);

        $("#reglink").show();
        $("#dereglink").hide();

        // Custom Web hook
        if(typeof web_hook_on_unregistered !== 'undefined') web_hook_on_unregistered();
    });

    // UA transport
    userAgent.on('transportCreated', function (transport) {
        console.log("Transport Object Created");
        
        // Transport Events
        transport.on('connected', function () {
            console.log("Connected to Web Socket!");
            $("#regStatus").html(lang.connected_to_web_socket);

            $("#WebRtcFailed").hide();

            window.setTimeout(function (){
                Register();
            }, 500);

        });
        transport.on('disconnected', function () {
            console.log("Disconnected from Web Socket!");
            $("#regStatus").html(lang.disconnected_from_web_socket);

            // We set this flag here so that the re-register attepts are fully completed.
            isReRegister = false;
        });
        transport.on('transportError', function () {
            console.log("Web Socket error!");
            $("#regStatus").html(lang.web_socket_error);

            $("#WebRtcFailed").show();

            // Custom Web hook
            if(typeof web_hook_on_transportError !== 'undefined') web_hook_on_transportError(transport, userAgent);
        });
    });

    // Inbound Calls
    userAgent.on("invite", function (session) {

        ReceiveCall(session);

        // Show a system notification when the phone rings
        if (getDbItem("Notifications", "") == 1) {
            incomingCallNote();
        }

        changePageTitle();

        // Custom Web hook
        if(typeof web_hook_on_invite !== 'undefined') web_hook_on_invite(session);
    });

    // Inbound Text Message
    userAgent.on('message', function (message) {
        ReceiveMessage(message);

        // Custom Web hook
        if(typeof web_hook_on_message !== 'undefined') web_hook_on_message(message);
    });

    // Start the WebService Connection loop
    console.log("Connecting to Web Socket...");
    $("#regStatus").html(lang.connecting_to_web_socket);
    userAgent.start();
    
    // Register Buttons
    $("#reglink").on('click', Register);

    // WebRTC Error Page
    $("#WebRtcFailed").on('click', function(){
        Confirm(lang.error_connecting_web_socket, lang.web_socket_error, function(){
            window.open("https://"+ wssServer +":"+ WebSocketPort +"/httpstatus");
        }, null);
    });
}


// Registration
// ============
function Register() {

    if (userAgent == null || userAgent.isRegistered()) return;

    console.log("Sending Registration...");
    $("#regStatus").html(lang.sending_registration);
    userAgent.register();

    if (getDbItem("Notifications", "") == 1) {
          if (Notification.permission != "granted") {
              Notification.requestPermission();
          }
    }
}
function Unregister() {
    if (userAgent == null || !userAgent.isRegistered()) return;

    console.log("Unsubscribing...");
    $("#regStatus").html(lang.unsubscribing);
    try {
        UnsubscribeAll();
    } catch (e) { }

    console.log("Disconnecting...");
    $("#regStatus").html(lang.disconnecting);
    userAgent.unregister();

    isReRegister = false;
}

// Inbound Calls
// =============
function ReceiveCall(session) {
    var callerID = session.remoteIdentity.displayName;
    var did = session.remoteIdentity.uri.user;

    if ( typeof callerID == 'undefined') { callerID = ""; }

    console.log("New Incoming Call!", callerID +" <"+ did +">");

    var CurrentCalls = countSessions(session.id);
    console.log("Current Call Count:", CurrentCalls);

    var buddyObj = FindBuddyByDid(did);
    // Make new contact if it's not there
    if(buddyObj == null) {
        var buddyType = (did.length > DidLength)? "contact" : "extension";
        var focusOnBuddy = (CurrentCalls==0);
        buddyObj = MakeBuddy(buddyType, true, focusOnBuddy, true, callerID, did);
    } else {
        // Double check that the buddy has the same caller ID as the incoming call
        // With Buddies that are contacts, eg +441234567890 <+441234567890> leave as is
        if(buddyObj.type == "extension" && buddyObj.CallerIDName != callerID){
            UpdateBuddyCalerID(buddyObj, callerID);
        }
        else if(buddyObj.type == "contact" && callerID != did && buddyObj.CallerIDName != callerID){
            UpdateBuddyCalerID(buddyObj, callerID);
        }
    }
    var buddy = buddyObj.identity;

    // Time Stamp
    window.clearInterval(session.data.callTimer);
    var startTime = moment.utc();
    session.data.callstart = startTime.format("YYYY-MM-DD HH:mm:ss UTC");
    $("#contact-" + buddy + "-timer").show();
    session.data.callTimer = window.setInterval(function(){
        var now = moment.utc();
        var duration = moment.duration(now.diff(startTime)); 
        $("#contact-" + buddy + "-timer").html(formatShortDuration(duration.asSeconds()));
    }, 1000);
    session.data.buddyId = buddy;
    session.data.calldirection = "inbound";
    session.data.terminateby = "them";
    session.data.withvideo = false;
    var videoInvite = false;
    if (session.request.body) {
        // Asterisk 13 PJ_SIP always sends m=video if endpoint has video codec,
        // even if origional invite does not specify video.
        if (session.request.body.indexOf("m=video") > -1) {
           videoInvite = true;
           if (buddyObj.type == "contact"){
                videoInvite = false;
           }
        }
    }

    // Inbound You or They Rejected
    session.on('rejected', function (response, cause) {
        console.log("Call rejected: " + cause);

        session.data.reasonCode = response.status_code
        session.data.reasonText = cause
    
        AddCallMessage(buddy, session, response.status_code, cause);

        // Custom Web hook
        if(typeof web_hook_on_terminate !== 'undefined') web_hook_on_terminate(session);
    });
    // They cancelled (Gets called regardless)
    session.on('terminated', function(response, cause) {

        // Stop the ringtone
        if(session.data.rinngerObj){
            session.data.rinngerObj.pause();
            session.data.rinngerObj.removeAttribute('src');
            session.data.rinngerObj.load();
            session.data.rinngerObj = null;
        }

        $.jeegoopopup.close();
        console.log("Call terminated");

        window.clearInterval(session.data.callTimer);

        $("#contact-" + buddy + "-timer").html("");
        $("#contact-" + buddy + "-timer").hide();
        $("#contact-" + buddy + "-msg").html("");
        $("#contact-" + buddy + "-msg").hide();
        $("#contact-" + buddy + "-AnswerCall").hide();

        RefreshStream(buddyObj);
        updateScroll(buddyObj.identity);
        UpdateBuddyList();
    });

    // Start Handle Call
    if(DoNotDisturbEnabled || DoNotDisturbPolicy == "enabled") {
        console.log("Do Not Disturb Enabled, rejecting call.");
        RejectCall(buddyObj.identity);
        return;
    }
    if(CurrentCalls >= 1){
        if(CallWaitingEnabled == false || CallWaitingEnabled == "disabled"){
            console.log("Call Waiting Disabled, rejecting call.");
            RejectCall(buddyObj.identity);
            return;
        }
    }
    if(AutoAnswerEnabled || AutoAnswerPolicy == "enabled"){
        if(CurrentCalls == 0){ // There are no other calls, so you can answer
            console.log("Auto Answer Call...");
            var buddyId = buddyObj.identity;
            window.setTimeout(function(){
                // If the call is with video, assume the auto answer is also
                // In order for this to work nicely, the recipient must be "ready" to accept video calls
                // In order to ensure video call compatibility (i.e. the recipient must have their web cam in, and working)
                // The NULL video should be configured
                // https://github.com/InnovateAsterisk/Browser-Phone/issues/26
                if(videoInvite) {
                    AnswerVideoCall(buddyId)
                }
                else {
                    AnswerAudioCall(buddyId);
                }
            }, 1000);

            // Select Buddy
            SelectBuddy(buddyObj.identity);
            return;
        }
        else {
            console.warn("Could not auto answer call, already on a call.");
        }
    }
    
    // Show the Answer Thingy
    $("#contact-" + buddyObj.identity + "-msg").html(lang.incomming_call_from +" " + callerID +" &lt;"+ did +"&gt;");
    $("#contact-" + buddyObj.identity + "-msg").show();
    if(videoInvite){
        $("#contact-"+ buddyObj.identity +"-answer-video").show();
    }
    else {
        $("#contact-"+ buddyObj.identity +"-answer-video").hide();
    }
    $("#contact-" + buddyObj.identity + "-AnswerCall").show();
    updateScroll(buddyObj.identity);

    // Play Ring Tone if not on the phone
    if(CurrentCalls >= 1){

        // Play Alert
        console.log("Audio:", audioBlobs.CallWaiting.url);
        var rinnger = new Audio(audioBlobs.CallWaiting.blob);
        rinnger.preload = "auto";
        rinnger.loop = false;
        rinnger.oncanplaythrough = function(e) {
            if (typeof rinnger.sinkId !== 'undefined' && getRingerOutputID() != "default") {
                rinnger.setSinkId(getRingerOutputID()).then(function() {
                    console.log("Set sinkId to:", getRingerOutputID());
                }).catch(function(e){
                    console.warn("Failed not apply setSinkId.", e);
                });
            }
            // If there has been no interaction with the page at all... this page will not work
            rinnger.play().then(function(){
               // Audio Is Playing
            }).catch(function(e){
                console.warn("Unable to play audio file.", e);
            }); 
        }
        session.data.rinngerObj = rinnger;
    } else {
        // Play Ring Tone
        console.log("Audio:", audioBlobs.Ringtone.url);
        var rinnger = new Audio(audioBlobs.Ringtone.blob);
        rinnger.preload = "auto";
        rinnger.loop = true;
        rinnger.oncanplaythrough = function(e) {
            if (typeof rinnger.sinkId !== 'undefined' && getRingerOutputID() != "default") {
                rinnger.setSinkId(getRingerOutputID()).then(function() {
                    console.log("Set sinkId to:", getRingerOutputID());
                }).catch(function(e){
                    console.warn("Failed not apply setSinkId.", e);
                });
            }
            // If there has been no interaction with the page at all... this page will not work
            rinnger.play().then(function(){
               // Audio Is Playing
            }).catch(function(e){
                console.warn("Unable to play audio file.", e);
            }); 
        }
        session.data.rinngerObj = rinnger;
    }

    $.jeegoopopup.close();

    // Show Call Answer Window
    var callAnswerHtml = '<div id="windowCtrls"><img id="closeImg" src="images/3_close.svg" title="Close" /></div>';
    callAnswerHtml += "<div class=\"UiWindowField scroller\" style=\"text-align:center\">";
    callAnswerHtml += "<div style=\"font-size: 18px; margin-top:1px\">"+ callerID + "<div>";
    if(callerID != did) {
            callAnswerHtml += "<div style=\"font-size: 18px; margin-top:1px\">&lt;"+ did + "&gt;<div>";
    }
    callAnswerHtml += "<div class=callAnswerBuddyIcon style=\"background-image: url("+ getPicture(buddyObj.identity) +"); margin-top:6px\"></div>";
    callAnswerHtml += "<div style=\"margin-top:14px\"><button onclick=\"AnswerAudioCall('"+ buddyObj.identity +"')\" class=answerButton><i class=\"fa fa-phone\"></i>&nbsp;&nbsp;"+ lang.answer_call +"</button></div>";
    if(videoInvite) {
            callAnswerHtml += "<div style=\"margin-top:11px\"><button onclick=\"AnswerVideoCall('"+ buddyObj.identity +"')\" class=answerButton><i class=\"fa fa-video-camera\"></i>&nbsp;&nbsp;"+ lang.answer_call_with_video +"</button></div>";
    }
    callAnswerHtml += "<div style=\"margin-top:11px\"><button onclick=\"RejectCall('"+ buddyObj.identity +"')\" class=hangupButton><i class=\"fa fa-phone\"></i>&nbsp;&nbsp;"+ lang.reject_call +"</button></div>";
    callAnswerHtml += "</div>";

    $.jeegoopopup.open({
                title: 'Incoming Call',
                html: callAnswerHtml,
                width: '290',
                height: '300',
                center: true,
                scrolling: 'no',
                skinClass: 'jg_popup_basic',
                overlay: true,
                opacity: 50,
                draggable: true,
                resizable: false,
                fadeIn: 0
    });

    $("#closeImg").click(function() { $.jeegoopopup.close(); });
    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); });
    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); } });

    // Add a notification badge
    IncreaseMissedBadge(buddyObj.identity);

    // Show notification
    // =================
    if ("Notification" in window) {
        if (getDbItem("Notifications", "") == 1) {
            var noticeOptions = { body: lang.incomming_call_from +" " + callerID +" \""+ did +"\"", icon: getPicture(buddyObj.identity) }
            var inComingCallNotification = new Notification(lang.incomming_call, noticeOptions);
            inComingCallNotification.onclick = function (event) {

                var buddyId = buddyObj.identity;
                window.setTimeout(function() {
                    // https://github.com/InnovateAsterisk/Browser-Phone/issues/26
                    if(videoInvite) {
                            AnswerVideoCall(buddyId)
                    } else {
                            AnswerAudioCall(buddyId);
                    }
                }, 4000);

                // Select Buddy
                SelectBuddy(buddyObj.identity);

                return;
            }
        }
    }

}

function AnswerAudioCall(buddy) {

    $.jeegoopopup.close();

    var buddyObj = FindBuddyByIdentity(buddy);
    if(buddyObj == null) {
        console.warn("Audio Answer failed, null buddy");
        $("#contact-" + buddy + "-msg").html(lang.call_failed);
        $("#contact-" + buddy + "-AnswerCall").hide();
        return;
    }

    var session = getSession(buddy);
    if (session == null) {
        console.warn("Audio Answer failed, null session");
        $("#contact-" + buddy + "-msg").html(lang.call_failed);
        $("#contact-" + buddy + "-AnswerCall").hide();
        return;
    }
    
    // Stop the ringtone
    if(session.data.rinngerObj){
        session.data.rinngerObj.pause();
        session.data.rinngerObj.removeAttribute('src');
        session.data.rinngerObj.load();
        session.data.rinngerObj = null;
    }

    // Check vitals
    if(HasAudioDevice == false){
        Alert(lang.alert_no_microphone);
        $("#contact-" + buddy + "-msg").html(lang.call_failed);
        $("#contact-" + buddy + "-AnswerCall").hide();
        return;
    }
    $("#contact-" + buddy + "-timer").html("");
    $("#contact-" + buddy + "-timer").hide();
    $("#contact-" + buddy + "-msg").html("");
    $("#contact-" + buddy + "-msg").hide();
    $("#contact-" + buddy + "-AnswerCall").hide();

    // Create a new Line and move the session over to the line
    var callerID = session.remoteIdentity.displayName;
    var did = session.remoteIdentity.uri.user;
    newLineNumber = newLineNumber + 1;
    lineObj = new Line(newLineNumber, callerID, did, buddyObj);
    lineObj.SipSession = session;
    lineObj.SipSession.data.line = lineObj.LineNumber;
    lineObj.SipSession.data.buddyId = lineObj.BuddyObj.identity;
    Lines.push(lineObj);
    AddLineHtml(lineObj);
    SelectLine(newLineNumber);
    UpdateBuddyList();

    var supportedConstraints = navigator.mediaDevices.getSupportedConstraints();
    var spdOptions = {
        sessionDescriptionHandlerOptions: {
            constraints: {
                audio: { deviceId : "default" },
                video: false
            }
        }
    }

    // Configure Audio
    var currentAudioDevice = getAudioSrcID();
    if(currentAudioDevice != "default"){
        var confirmedAudioDevice = false;
        for (var i = 0; i < AudioinputDevices.length; ++i) {
            if(currentAudioDevice == AudioinputDevices[i].deviceId) {
                confirmedAudioDevice = true;
                break;
            }
        }
        if(confirmedAudioDevice) {
            spdOptions.sessionDescriptionHandlerOptions.constraints.audio.deviceId = { exact: currentAudioDevice }
        }
        else {
            console.warn("The audio device you used before is no longer available, default settings applied.");
            localDB.setItem("AudioSrcId", "default");
        }
    }
    // Add additional Constraints
    if(supportedConstraints.autoGainControl) {
        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.autoGainControl = AutoGainControl;
    }
    if(supportedConstraints.echoCancellation) {
        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.echoCancellation = EchoCancellation;
    }
    if(supportedConstraints.noiseSuppression) {
        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.noiseSuppression = NoiseSuppression;
    }

    // Send Answer
    lineObj.SipSession.accept(spdOptions);
    lineObj.SipSession.data.withvideo = false;
    lineObj.SipSession.data.VideoSourceDevice = null;
    lineObj.SipSession.data.AudioSourceDevice = getAudioSrcID();
    lineObj.SipSession.data.AudioOutputDevice = getAudioOutputID();

    // Wire up UI
    wireupAudioSession(lineObj);
    $("#contact-" + buddy + "-msg").html(lang.call_in_progress);

    // Clear Answer Buttons
    $("#contact-" + buddy + "-AnswerCall").hide();
}

function AnswerVideoCall(buddy) {

    $.jeegoopopup.close();

    var buddyObj = FindBuddyByIdentity(buddy);
    if(buddyObj == null) {
        console.warn("Audio Answer failed, null buddy");
        $("#contact-" + buddy + "-msg").html(lang.call_failed);
        $("#contact-" + buddy + "-AnswerCall").hide();
        return;
    }

    var session = getSession(buddy);
    if (session == null) {
        console.warn("Video Answer failed, null session");
        $("#contact-" + buddy + "-msg").html(lang.call_failed);
        $("#contact-" + buddy + "-AnswerCall").hide();
        return;
    }

    // Stop the ringtone
    if(session.data.rinngerObj){
        session.data.rinngerObj.pause();
        session.data.rinngerObj.removeAttribute('src');
        session.data.rinngerObj.load();
        session.data.rinngerObj = null;
    }

    // Check vitals
    if(HasAudioDevice == false){
        Alert(lang.alert_no_microphone);
        $("#contact-" + buddy + "-msg").html(lang.call_failed);
        $("#contact-" + buddy + "-AnswerCall").hide();
        return;
    }
    if(HasVideoDevice == false){
        console.warn("No video devices (webcam) found, switching to audio call.");
        AnswerAudioCall(buddy);
        return;
    }
    $("#contact-" + buddy + "-timer").html("");
    $("#contact-" + buddy + "-timer").hide();
    $("#contact-" + buddy + "-msg").html("");
    $("#contact-" + buddy + "-msg").hide();
    $("#contact-" + buddy + "-AnswerCall").hide();

    // Create a new Line and move the session over to the line
    var callerID = session.remoteIdentity.displayName;
    var did = session.remoteIdentity.uri.user;
    newLineNumber = newLineNumber + 1;
    lineObj = new Line(newLineNumber, callerID, did, buddyObj);
    lineObj.SipSession = session;
    lineObj.SipSession.data.line = lineObj.LineNumber;
    lineObj.SipSession.data.buddyId = lineObj.BuddyObj.identity;
    Lines.push(lineObj);
    AddLineHtml(lineObj);
    SelectLine(newLineNumber);
    UpdateBuddyList();

    var supportedConstraints = navigator.mediaDevices.getSupportedConstraints();
    var spdOptions = {
        sessionDescriptionHandlerOptions: {
            constraints: {
                audio: { deviceId : "default" },
                video: { deviceId : "default" }
            }
        }
    }

    // Configure Audio
    var currentAudioDevice = getAudioSrcID();
    if(currentAudioDevice != "default"){
        var confirmedAudioDevice = false;
        for (var i = 0; i < AudioinputDevices.length; ++i) {
            if(currentAudioDevice == AudioinputDevices[i].deviceId) {
                confirmedAudioDevice = true;
                break;
            }
        }
        if(confirmedAudioDevice) {
            spdOptions.sessionDescriptionHandlerOptions.constraints.audio.deviceId = { exact: currentAudioDevice }
        }
        else {
            console.warn("The audio device you used before is no longer available, default settings applied.");
            localDB.setItem("AudioSrcId", "default");
        }
    }
    // Add additional Constraints
    if(supportedConstraints.autoGainControl) {
        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.autoGainControl = AutoGainControl;
    }
    if(supportedConstraints.echoCancellation) {
        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.echoCancellation = EchoCancellation;
    }
    if(supportedConstraints.noiseSuppression) {
        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.noiseSuppression = NoiseSuppression;
    }

    // Configure Video
    var currentVideoDevice = getVideoSrcID();
    if(currentVideoDevice != "default"){
        var confirmedVideoDevice = false;
        for (var i = 0; i < VideoinputDevices.length; ++i) {
            if(currentVideoDevice == VideoinputDevices[i].deviceId) {
                confirmedVideoDevice = true;
                break;
            }
        }
        if(confirmedVideoDevice){
            spdOptions.sessionDescriptionHandlerOptions.constraints.video.deviceId = { exact: currentVideoDevice }
        }
        else {
            console.warn("The video device you used before is no longer available, default settings applied.");
            localDB.setItem("VideoSrcId", "default"); // resets for later and subsequent calls
        }
    }
    // Add additional Constraints
    if(supportedConstraints.frameRate && maxFrameRate != "") {
        spdOptions.sessionDescriptionHandlerOptions.constraints.video.frameRate = maxFrameRate;
    }
    if(supportedConstraints.height && videoHeight != "") {
        spdOptions.sessionDescriptionHandlerOptions.constraints.video.height = videoHeight;
    }
    if(supportedConstraints.aspectRatio && videoAspectRatio != "") {
        spdOptions.sessionDescriptionHandlerOptions.constraints.video.aspectRatio = videoAspectRatio;
    }

    // Send Answer
    lineObj.SipSession.data.withvideo = true;
    lineObj.SipSession.data.VideoSourceDevice = getVideoSrcID();
    lineObj.SipSession.data.AudioSourceDevice = getAudioSrcID();
    lineObj.SipSession.data.AudioOutputDevice = getAudioOutputID();

    // Send Answer
    // If this fails, it must still wireup the call so we can manually close it
    $("#contact-" + buddy + "-msg").html(lang.call_in_progress);
    // Wire up UI
    wireupVideoSession(lineObj);

    try{
        lineObj.SipSession.accept(spdOptions);
        if(StartVideoFullScreen) ExpandVideoArea(lineObj.LineNumber);
        $("#contact-" + buddy + "-AnswerCall").hide();
    }
    catch(e){
        console.warn("Failed to answer call", e, lineObj.SipSession);
        teardownSession(lineObj, 500, "Client Error");
    }

}

function RejectCall(buddy) {
    var session = getSession(buddy);
    if (session == null) {
        console.warn("Reject failed, null session");
        $("#contact-" + buddy + "-msg").html(lang.call_failed);
        $("#contact-" + buddy + "-AnswerCall").hide();
    }
    session.data.terminateby = "us";
    session.reject({ 
        statusCode: 486, 
        reasonPhrase: "Rejected by us"
    });
    $("#contact-" + buddy + "-msg").html(lang.call_rejected);
}

// Session Wireup
// ==============
function wireupAudioSession(lineObj) {
    if (lineObj == null) return;

    var MessageObjId = "#line-" + lineObj.LineNumber + "-msg";
    var session = lineObj.SipSession;

    session.on('progress', function (response) {
        // Provisional 1xx
        if(response.status_code == 100){
            $(MessageObjId).html(lang.trying);
        } else if(response.status_code == 180){
            $(MessageObjId).html(lang.ringing);
            
            var soundFile = audioBlobs.EarlyMedia_European;
            if(UserLocale().indexOf("us") > -1) soundFile = audioBlobs.EarlyMedia_US;
            if(UserLocale().indexOf("gb") > -1) soundFile = audioBlobs.EarlyMedia_UK;
            if(UserLocale().indexOf("au") > -1) soundFile = audioBlobs.EarlyMedia_Australia;
            if(UserLocale().indexOf("jp") > -1) soundFile = audioBlobs.EarlyMedia_Japan;

            // Play Early Media
            console.log("Audio:", soundFile.url);
            var earlyMedia = new Audio(soundFile.blob);
            earlyMedia.preload = "auto";
            earlyMedia.loop = true;
            earlyMedia.oncanplaythrough = function(e) {
                if (typeof earlyMedia.sinkId !== 'undefined' && getAudioOutputID() != "default") {
                    earlyMedia.setSinkId(getAudioOutputID()).then(function() {
                        console.log("Set sinkId to:", getAudioOutputID());
                    }).catch(function(e){
                        console.warn("Failed not apply setSinkId.", e);
                    });
                }
                earlyMedia.play().then(function(){
                   // Audio Is Playing
                }).catch(function(e){
                    console.warn("Unable to play audio file.", e);
                }); 
            }
            session.data.earlyMedia = earlyMedia;
        } else {
            $(MessageObjId).html(response.reason_phrase + "...");
        }

        // Custom Web hook
        if(typeof web_hook_on_modify !== 'undefined') web_hook_on_modify("progress", session);
    });
    session.on('trackAdded', function () {
        var pc = session.sessionDescriptionHandler.peerConnection;

        // Gets Remote Audio Track (Local audio is setup via initial GUM)
        var remoteStream = new MediaStream();
        pc.getReceivers().forEach(function (receiver) {
            if(receiver.track && receiver.track.kind == "audio"){
               remoteStream.addTrack(receiver.track);
            } 
        });
        var remoteAudio = $("#line-" + lineObj.LineNumber + "-remoteAudio").get(0);
        remoteAudio.srcObject = remoteStream;
        remoteAudio.onloadedmetadata = function(e) {
            if (typeof remoteAudio.sinkId !== 'undefined') {
                remoteAudio.setSinkId(getAudioOutputID()).then(function(){
                    console.log("sinkId applied: "+ getAudioOutputID());
                }).catch(function(e){
                    console.warn("Error using setSinkId: ", e);
                });
            }
            remoteAudio.play();
        }

        // Custom Web hook
        if(typeof web_hook_on_modify !== 'undefined') web_hook_on_modify("trackAdded", session);
    });
    session.on('accepted', function (data) {

        if(session.data.earlyMedia){
            session.data.earlyMedia.pause();
            session.data.earlyMedia.removeAttribute('src');
            session.data.earlyMedia.load();
            session.data.earlyMedia = null;
        }

        window.clearInterval(session.data.callTimer);
        var startTime = moment.utc();
        session.data.callTimer = window.setInterval(function(){
            var now = moment.utc();
            var duration = moment.duration(now.diff(startTime)); 
            $("#line-" + lineObj.LineNumber + "-timer").html(formatShortDuration(duration.asSeconds()));
        }, 1000);

        if(RecordAllCalls || CallRecordingPolicy == "enabled") {
            StartRecording(lineObj.LineNumber);
        }

        $("#line-" + lineObj.LineNumber + "-progress").hide();
        $("#line-" + lineObj.LineNumber + "-VideoCall").hide();
        $("#line-" + lineObj.LineNumber + "-ActiveCall").show();

        // Audo Monitoring
        lineObj.LocalSoundMeter = StartLocalAudioMediaMonitoring(lineObj.LineNumber, session);
        lineObj.RemoteSoundMeter = StartRemoteAudioMediaMonitoring(lineObj.LineNumber, session);
        
        $(MessageObjId).html(lang.call_in_progress);

        updateLineScroll(lineObj.LineNumber);

        UpdateBuddyList();

        // Custom Web hook
        if(typeof web_hook_on_modify !== 'undefined') web_hook_on_modify("accepted", session);
    });
    session.on('rejected', function (response, cause) {
        // Should only apply befor answer
        $(MessageObjId).html(lang.call_rejected +": " + cause);
        console.log("Call rejected: " + cause);
        teardownSession(lineObj, response.status_code, response.reason_phrase);
    });
    session.on('failed', function (response, cause) {
        $(MessageObjId).html(lang.call_failed + ": " + cause);
        console.log("Call failed: " + cause);
        teardownSession(lineObj, 0, "Call failed");
    });
    session.on('cancel', function () {
        $(MessageObjId).html(lang.call_cancelled);
        console.log("Call Cancelled");
        teardownSession(lineObj, 0, "Cancelled by caller");
    });
    // referRequested
    // replaced
    session.on('bye', function () {
        $(MessageObjId).html(lang.call_ended);
        console.log("Call ended, bye!");
        teardownSession(lineObj, 16, "Normal Call clearing");
    });
    session.on('terminated', function (message, cause) {
        $(MessageObjId).html(lang.call_ended);
        console.log("Session terminated");
        teardownSession(lineObj, 16, "Normal Call clearing");
    });
    session.on('reinvite', function (session) {
        console.log("Session reinvited!");
    });
    //dtmf
    session.on('directionChanged', function() {
        var direction = session.sessionDescriptionHandler.getDirection();
        console.log("Direction Change: ", direction);

        // Custom Web hook
        if(typeof web_hook_on_modify !== 'undefined') web_hook_on_modify("directionChanged", session);
    });

    $("#line-" + lineObj.LineNumber + "-btn-settings").removeAttr('disabled');
    $("#line-" + lineObj.LineNumber + "-btn-audioCall").prop('disabled','disabled');
    $("#line-" + lineObj.LineNumber + "-btn-videoCall").prop('disabled','disabled');
    $("#line-" + lineObj.LineNumber + "-btn-search").removeAttr('disabled');
    $("#line-" + lineObj.LineNumber + "-btn-remove").prop('disabled','disabled');

    $("#line-" + lineObj.LineNumber + "-progress").show();
    $("#line-" + lineObj.LineNumber + "-msg").show();

    if(lineObj.BuddyObj.type == "group") {
        $("#line-" + lineObj.LineNumber + "-conference").show();
    } 
    else {
        $("#line-" + lineObj.LineNumber + "-conference").hide();
    }

    updateLineScroll(lineObj.LineNumber);

    UpdateUI();
}

function wireupVideoSession(lineObj) {
    if (lineObj == null) return;

    var MessageObjId = "#line-" + lineObj.LineNumber + "-msg";
    var session = lineObj.SipSession;

    session.on('trackAdded', function () {
        // Gets remote tracks
        var pc = session.sessionDescriptionHandler.peerConnection;
        var remoteAudioStream = new MediaStream();
        var remoteVideoStream = new MediaStream();
        pc.getReceivers().forEach(function (receiver) {
            if(receiver.track){
                if(receiver.track.kind == "audio"){
                    remoteAudioStream.addTrack(receiver.track);
                }
                if(receiver.track.kind == "video"){
                    remoteVideoStream.addTrack(receiver.track);
                }
            }
        });

        if (remoteAudioStream.getAudioTracks().length >= 1) {
            var remoteAudio = $("#line-" + lineObj.LineNumber + "-remoteAudio").get(0);
            remoteAudio.srcObject = remoteAudioStream;
            remoteAudio.onloadedmetadata = function(e) {
               if (typeof remoteAudio.sinkId !== 'undefined') {
                   remoteAudio.setSinkId(getAudioOutputID()).then(function(){
                       console.log("sinkId applied: "+ getAudioOutputID());
                   }).catch(function(e){
                       console.warn("Error using setSinkId: ", e);
                   });
               }
               remoteAudio.play();
            }
        }

        if (remoteVideoStream.getVideoTracks().length >= 1) {
            var remoteVideo = $("#line-" + lineObj.LineNumber + "-remoteVideo").get(0);
            remoteVideo.srcObject = remoteVideoStream;
            remoteVideo.onloadedmetadata = function(e) {
                remoteVideo.play();
            }
        }

        // Note: There appears to be a bug in the peerConnection.getSenders()
        // The array returns but may or may not be fully populated by the RTCRtpSender
        // The track property appears to be null initially and then moments later populated.
        // This does not appear to be the case when originating a call, mostly when receiving a call.
        window.setTimeout(function(){
            var localVideoStream = new MediaStream();
            var pc = session.sessionDescriptionHandler.peerConnection;
            pc.getSenders().forEach(function (sender) {
                if(sender.track && sender.track.kind == "video"){
                    localVideoStream.addTrack(sender.track);
                }
            });
            var localVideo = $("#line-" + lineObj.LineNumber + "-localVideo").get(0);
            localVideo.srcObject = localVideoStream;
            localVideo.onloadedmetadata = function(e) {
                localVideo.play();
            }
        }, 1000);

        // Custom Web hook
        if(typeof web_hook_on_modify !== 'undefined') web_hook_on_modify("trackAdded", session);
    });
    session.on('progress', function (response) {
        // Provisional 1xx
        if(response.status_code == 100){
            $(MessageObjId).html(lang.trying);
        } else if(response.status_code == 180){
            $(MessageObjId).html(lang.ringing);

            var soundFile = audioBlobs.EarlyMedia_European;
            if(UserLocale().indexOf("us") > -1) soundFile = audioBlobs.EarlyMedia_US;
            if(UserLocale().indexOf("gb") > -1) soundFile = audioBlobs.EarlyMedia_UK;
            if(UserLocale().indexOf("au") > -1) soundFile = audioBlobs.EarlyMedia_Australia;
            if(UserLocale().indexOf("jp") > -1) soundFile = audioBlobs.EarlyMedia_Japan;

            // Play Early Media
            console.log("Audio:", soundFile.url);
            var earlyMedia = new Audio(soundFile.blob);
            earlyMedia.preload = "auto";
            earlyMedia.loop = true;
            earlyMedia.oncanplaythrough = function(e) {
                if (typeof earlyMedia.sinkId !== 'undefined' && getAudioOutputID() != "default") {
                    earlyMedia.setSinkId(getAudioOutputID()).then(function() {
                        console.log("Set sinkId to:", getAudioOutputID());
                    }).catch(function(e){
                        console.warn("Failed not apply setSinkId.", e);
                    });
                }
                earlyMedia.play().then(function(){
                   // Audio Is Playing
                }).catch(function(e){
                    console.warn("Unable to play audio file.", e);
                }); 
            }
            session.data.earlyMedia = earlyMedia;
        } else {
            $(MessageObjId).html(response.reason_phrase + "...");
        }

        // Custom Web hook
        if(typeof web_hook_on_modify !== 'undefined') web_hook_on_modify("progress", session);
    });
    session.on('accepted', function (data) {
        
        if(session.data.earlyMedia){
            session.data.earlyMedia.pause();
            session.data.earlyMedia.removeAttribute('src');
            session.data.earlyMedia.load();
            session.data.earlyMedia = null;
        }

        window.clearInterval(session.data.callTimer);
        $("#line-" + lineObj.LineNumber + "-timer").show();
        var startTime = moment.utc();
        session.data.callTimer = window.setInterval(function(){
            var now = moment.utc();
            var duration = moment.duration(now.diff(startTime)); 
            $("#line-" + lineObj.LineNumber + "-timer").html(formatShortDuration(duration.asSeconds()));
        }, 1000);

        if(RecordAllCalls || CallRecordingPolicy == "enabled") {
            StartRecording(lineObj.LineNumber);
        }

        $("#line-"+ lineObj.LineNumber +"-progress").hide();
        $("#line-"+ lineObj.LineNumber +"-VideoCall").show();
        $("#line-"+ lineObj.LineNumber +"-ActiveCall").show();

        $("#line-"+ lineObj.LineNumber +"-btn-Conference").hide(); // Cannot conference a Video Call (Yet...)
        $("#line-"+ lineObj.LineNumber +"-btn-CancelConference").hide();
        $("#line-"+ lineObj.LineNumber +"-Conference").hide();

        $("#line-"+ lineObj.LineNumber +"-btn-Transfer").hide(); // Cannot transfer a Video Call (Yet...)
        $("#line-"+ lineObj.LineNumber +"-btn-CancelTransfer").hide();
        $("#line-"+ lineObj.LineNumber +"-Transfer").hide();

        // Default to use Camera
        $("#line-"+ lineObj.LineNumber +"-src-camera").prop("disabled", true);
        $("#line-"+ lineObj.LineNumber +"-src-canvas").prop("disabled", false);
        $("#line-"+ lineObj.LineNumber +"-src-desktop").prop("disabled", false);
        $("#line-"+ lineObj.LineNumber +"-src-video").prop("disabled", false);

        updateLineScroll(lineObj.LineNumber);

        // Start Audio Monitoring
        lineObj.LocalSoundMeter = StartLocalAudioMediaMonitoring(lineObj.LineNumber, session);
        lineObj.RemoteSoundMeter = StartRemoteAudioMediaMonitoring(lineObj.LineNumber, session);

        $(MessageObjId).html(lang.call_in_progress);

        if(StartVideoFullScreen) ExpandVideoArea(lineObj.LineNumber);

        // Custom Web hook
        if(typeof web_hook_on_modify !== 'undefined') web_hook_on_modify("accepted", session);
    });
    session.on('rejected', function (response, cause) {
        // Should only apply before answer
        $(MessageObjId).html(lang.call_rejected +": "+ cause);
        console.log("Call rejected: "+ cause);
        teardownSession(lineObj, response.status_code, response.reason_phrase);
    });
    session.on('failed', function (response, cause) {
        $(MessageObjId).html(lang.call_failed +": "+ cause);
        console.log("Call failed: "+ cause);
        teardownSession(lineObj, 0, "call failed");
    });
    session.on('cancel', function () {
        $(MessageObjId).html(lang.call_cancelled);
        console.log("Call Cancelled");
        teardownSession(lineObj, 0, "Cancelled by caller");
    });
    // referRequested
    // replaced
    session.on('bye', function () {
        $(MessageObjId).html(lang.call_ended);
        console.log("Call ended, bye!");
        teardownSession(lineObj, 16, "Normal Call clearing");
    });
    session.on('terminated', function (message, cause) {
        $(MessageObjId).html(lang.call_ended);
        console.log("Session terminated");
        teardownSession(lineObj, 16, "Normal Call clearing");
    });
    session.on('reinvite', function (session) {
        console.log("Session reinvited!");
    });
    // dtmf
    session.on('directionChanged', function() {
        var direction = session.sessionDescriptionHandler.getDirection();
        console.log("Direction Change: ", direction);

        // Custom Web hook
        if(typeof web_hook_on_modify !== 'undefined') web_hook_on_modify("directionChanged", session);
    });

    $("#line-" + lineObj.LineNumber + "-btn-settings").removeAttr('disabled');
    $("#line-" + lineObj.LineNumber + "-btn-audioCall").prop('disabled','disabled');
    $("#line-" + lineObj.LineNumber + "-btn-videoCall").prop('disabled','disabled');
    $("#line-" + lineObj.LineNumber + "-btn-search").removeAttr('disabled');
    $("#line-" + lineObj.LineNumber + "-btn-remove").prop('disabled','disabled');

    $("#line-" + lineObj.LineNumber + "-progress").show();
    $("#line-" + lineObj.LineNumber + "-msg").show();
    
    updateLineScroll(lineObj.LineNumber);

    UpdateUI();
}
function teardownSession(lineObj, reasonCode, reasonText) {
    if(lineObj == null || lineObj.SipSession == null) return;

    var session = lineObj.SipSession;
    if(session.data.teardownComplete == true) return;
    session.data.teardownComplete = true; // Run this code only once

    session.data.reasonCode = reasonCode
    session.data.reasonText = reasonText

    // Call UI
    $.jeegoopopup.close();

    // End any child calls
    if(session.data.childsession){
        try{
            if(session.data.childsession.status == SIP.Session.C.STATUS_CONFIRMED){
                session.data.childsession.bye();
            } 
            else{
                session.data.childsession.cancel();
            }
        } catch(e){}
    }
    session.data.childsession = null;

    // Mixed Tracks
    if(session.data.AudioSourceTrack && session.data.AudioSourceTrack.kind == "audio"){
        session.data.AudioSourceTrack.stop();
        session.data.AudioSourceTrack = null;
    }
    // Stop any Early Media
    if(session.data.earlyMedia){
        session.data.earlyMedia.pause();
        session.data.earlyMedia.removeAttribute('src');
        session.data.earlyMedia.load();
        session.data.earlyMedia = null;
    }

    // Stop Recording if we are
    StopRecording(lineObj.LineNumber,true);

    // Audio Meters
    if(lineObj.LocalSoundMeter != null){
        lineObj.LocalSoundMeter.stop();
        lineObj.LocalSoundMeter = null;
    }
    if(lineObj.RemoteSoundMeter != null){
        lineObj.RemoteSoundMeter.stop();
        lineObj.RemoteSoundMeter = null;
    }

    // End timers
    window.clearInterval(session.data.videoResampleInterval);
    window.clearInterval(session.data.callTimer);

    // Add to stream
    AddCallMessage(lineObj.BuddyObj.identity, session, reasonCode, reasonText);

    // Close up the UI
    window.setTimeout(function () {
        RemoveLine(lineObj);
    }, 1000);

    UpdateBuddyList();
    UpdateUI();

    // Custom Web hook
    if(typeof web_hook_on_terminate !== 'undefined') web_hook_on_terminate(session);
}

// Mic and Speaker Levels
// ======================
function StartRemoteAudioMediaMonitoring(lineNum, session) {
    console.log("Creating RemoteAudio AudioContext on Line:" + lineNum);

    // Create local SoundMeter
    var soundMeter = new SoundMeter(session.id, lineNum);
    if(soundMeter == null){
        console.warn("AudioContext() RemoteAudio not available... it fine.");
        return null;
    }

    // Ready the getStats request
    var remoteAudioStream = new MediaStream();
    var audioReceiver = null;
    var pc = session.sessionDescriptionHandler.peerConnection;
    pc.getReceivers().forEach(function (RTCRtpReceiver) {
        if(RTCRtpReceiver.track && RTCRtpReceiver.track.kind == "audio"){
            if(audioReceiver == null) {
                remoteAudioStream.addTrack(RTCRtpReceiver.track);
                audioReceiver = RTCRtpReceiver;
            }
            else {
                console.log("Found another Track, but audioReceiver not null");
                console.log(RTCRtpReceiver);
                console.log(RTCRtpReceiver.track);
            }
        }
    });

    // Setup Charts
    var maxDataLength = 100;
    soundMeter.startTime = Date.now();
    Chart.defaults.global.defaultFontSize = 12;

    var ChatHistoryOptions = { 
        responsive: false,
        maintainAspectRatio: false,
        devicePixelRatio: 1,
        animation: false,
        scales: {
            yAxes: [{
                ticks: { beginAtZero: true } //, min: 0, max: 100
            }]
        }, 
    }

    // Receive Kilobits per second
    soundMeter.ReceiveBitRateChart = new Chart($("#line-"+ lineNum +"-AudioReceiveBitRate"), {
        type: 'line',
        data: {
            labels: MakeDataArray("", maxDataLength),
            datasets: [{
                label: lang.receive_kilobits_per_second,
                data: MakeDataArray(0, maxDataLength),
                backgroundColor: 'rgba(168, 0, 0, 0.5)',
                borderColor: 'rgba(168, 0, 0, 1)',
                borderWidth: 1,
                pointRadius: 1
            }]
        },
        options: ChatHistoryOptions
    });
    soundMeter.ReceiveBitRateChart.lastValueBytesReceived = 0;
    soundMeter.ReceiveBitRateChart.lastValueTimestamp = 0;

    // Receive Packets per second
    soundMeter.ReceivePacketRateChart = new Chart($("#line-"+ lineNum +"-AudioReceivePacketRate"), {
        type: 'line',
        data: {
            labels: MakeDataArray("", maxDataLength),
            datasets: [{
                label: lang.receive_packets_per_second,
                data: MakeDataArray(0, maxDataLength),
                backgroundColor: 'rgba(168, 0, 0, 0.5)',
                borderColor: 'rgba(168, 0, 0, 1)',
                borderWidth: 1,
                pointRadius: 1
            }]
        },
        options: ChatHistoryOptions
    });
    soundMeter.ReceivePacketRateChart.lastValuePacketReceived = 0;
    soundMeter.ReceivePacketRateChart.lastValueTimestamp = 0;

    // Receive Packet Loss
    soundMeter.ReceivePacketLossChart = new Chart($("#line-"+ lineNum +"-AudioReceivePacketLoss"), {
        type: 'line',
        data: {
            labels: MakeDataArray("", maxDataLength),
            datasets: [{
                label: lang.receive_packet_loss,
                data: MakeDataArray(0, maxDataLength),
                backgroundColor: 'rgba(168, 99, 0, 0.5)',
                borderColor: 'rgba(168, 99, 0, 1)',
                borderWidth: 1,
                pointRadius: 1
            }]
        },
        options: ChatHistoryOptions
    });
    soundMeter.ReceivePacketLossChart.lastValuePacketLoss = 0;
    soundMeter.ReceivePacketLossChart.lastValueTimestamp = 0;

    // Receive Jitter
    soundMeter.ReceiveJitterChart = new Chart($("#line-"+ lineNum +"-AudioReceiveJitter"), {
        type: 'line',
        data: {
            labels: MakeDataArray("", maxDataLength),
            datasets: [{
                label: lang.receive_jitter,
                data: MakeDataArray(0, maxDataLength),
                backgroundColor: 'rgba(0, 38, 168, 0.5)',
                borderColor: 'rgba(0, 38, 168, 1)',
                borderWidth: 1,
                pointRadius: 1
            }]
        },
        options: ChatHistoryOptions
    });

    // Receive Audio Levels
    soundMeter.ReceiveLevelsChart = new Chart($("#line-"+ lineNum +"-AudioReceiveLevels"), {
        type: 'line',
        data: {
            labels: MakeDataArray("", maxDataLength),
            datasets: [{
                label: lang.receive_audio_levels,
                data: MakeDataArray(0, maxDataLength),
                backgroundColor: 'rgba(140, 0, 168, 0.5)',
                borderColor: 'rgba(140, 0, 168, 1)',
                borderWidth: 1,
                pointRadius: 1
            }]
        },
        options: ChatHistoryOptions
    });

    // Connect to Source
    soundMeter.connectToSource(remoteAudioStream, function (e) {
        if (e != null) return;

        // Create remote SoundMeter
        console.log("SoundMeter for RemoteAudio Connected, displaying levels for Line: " + lineNum);
        soundMeter.levelsInterval = window.setInterval(function () {
            // Calculate Levels
            //value="0" max="1" high="0.25" (this seems low... )
            var level = soundMeter.instant * 4.0;
            if (level > 1) level = 1;
            var instPercent = level * 100;

            $("#line-" + lineNum + "-Speaker").css("height", instPercent.toFixed(2) +"%");
        }, 50);
        soundMeter.networkInterval = window.setInterval(function (){
            // Calculate Network Conditions
            if(audioReceiver != null) {
                audioReceiver.getStats().then(function(stats) {
                    stats.forEach(function(report){

                        var theMoment = utcDateNow();
                        var ReceiveBitRateChart = soundMeter.ReceiveBitRateChart;
                        var ReceivePacketRateChart = soundMeter.ReceivePacketRateChart;
                        var ReceivePacketLossChart = soundMeter.ReceivePacketLossChart;
                        var ReceiveJitterChart = soundMeter.ReceiveJitterChart;
                        var ReceiveLevelsChart = soundMeter.ReceiveLevelsChart;
                        var elapsedSec = Math.floor((Date.now() - soundMeter.startTime)/1000);

                        if(report.type == "inbound-rtp"){

                            if(ReceiveBitRateChart.lastValueTimestamp == 0) {
                                ReceiveBitRateChart.lastValueTimestamp = report.timestamp;
                                ReceiveBitRateChart.lastValueBytesReceived = report.bytesReceived;

                                ReceivePacketRateChart.lastValueTimestamp = report.timestamp;
                                ReceivePacketRateChart.lastValuePacketReceived = report.packetsReceived;

                                ReceivePacketLossChart.lastValueTimestamp = report.timestamp;
                                ReceivePacketLossChart.lastValuePacketLoss = report.packetsLost;

                                return;
                            }
                            // Receive Kilobits Per second
                            var kbitsPerSec = (8 * (report.bytesReceived - ReceiveBitRateChart.lastValueBytesReceived))/1000;

                            ReceiveBitRateChart.lastValueTimestamp = report.timestamp;
                            ReceiveBitRateChart.lastValueBytesReceived = report.bytesReceived;

                            soundMeter.ReceiveBitRate.push({ value: kbitsPerSec, timestamp : theMoment});
                            ReceiveBitRateChart.data.datasets[0].data.push(kbitsPerSec);
                            ReceiveBitRateChart.data.labels.push("");
                            if(ReceiveBitRateChart.data.datasets[0].data.length > maxDataLength) {
                                ReceiveBitRateChart.data.datasets[0].data.splice(0,1);
                                ReceiveBitRateChart.data.labels.splice(0,1);
                            }
                            ReceiveBitRateChart.update();

                            // Receive Packets Per Second
                            var PacketsPerSec = (report.packetsReceived - ReceivePacketRateChart.lastValuePacketReceived);

                            ReceivePacketRateChart.lastValueTimestamp = report.timestamp;
                            ReceivePacketRateChart.lastValuePacketReceived = report.packetsReceived;

                            soundMeter.ReceivePacketRate.push({ value: PacketsPerSec, timestamp : theMoment});
                            ReceivePacketRateChart.data.datasets[0].data.push(PacketsPerSec);
                            ReceivePacketRateChart.data.labels.push("");
                            if(ReceivePacketRateChart.data.datasets[0].data.length > maxDataLength) {
                                ReceivePacketRateChart.data.datasets[0].data.splice(0,1);
                                ReceivePacketRateChart.data.labels.splice(0,1);
                            }
                            ReceivePacketRateChart.update();

                            // Receive Packet Loss
                            var PacketsLost = (report.packetsLost - ReceivePacketLossChart.lastValuePacketLoss);

                            ReceivePacketLossChart.lastValueTimestamp = report.timestamp;
                            ReceivePacketLossChart.lastValuePacketLoss = report.packetsLost;

                            soundMeter.ReceivePacketLoss.push({ value: PacketsLost, timestamp : theMoment});
                            ReceivePacketLossChart.data.datasets[0].data.push(PacketsLost);
                            ReceivePacketLossChart.data.labels.push("");
                            if(ReceivePacketLossChart.data.datasets[0].data.length > maxDataLength) {
                                ReceivePacketLossChart.data.datasets[0].data.splice(0,1);
                                ReceivePacketLossChart.data.labels.splice(0,1);
                            }
                            ReceivePacketLossChart.update();

                            // Receive Jitter
                            soundMeter.ReceiveJitter.push({ value: report.jitter, timestamp : theMoment});
                            ReceiveJitterChart.data.datasets[0].data.push(report.jitter);
                            ReceiveJitterChart.data.labels.push("");
                            if(ReceiveJitterChart.data.datasets[0].data.length > maxDataLength) {
                                ReceiveJitterChart.data.datasets[0].data.splice(0,1);
                                ReceiveJitterChart.data.labels.splice(0,1);
                            }
                            ReceiveJitterChart.update();
                        }
                        if(report.type == "track") {

                            // Receive Audio Levels
                            var levelPercent = (report.audioLevel * 100);
                            soundMeter.ReceiveLevels.push({ value: levelPercent, timestamp : theMoment});
                            ReceiveLevelsChart.data.datasets[0].data.push(levelPercent);
                            ReceiveLevelsChart.data.labels.push("");
                            if(ReceiveLevelsChart.data.datasets[0].data.length > maxDataLength)
                            {
                                ReceiveLevelsChart.data.datasets[0].data.splice(0,1);
                                ReceiveLevelsChart.data.labels.splice(0,1);
                            }
                            ReceiveLevelsChart.update();
                        }
                    });
                });
            }
        } ,1000);
    });

    return soundMeter;
}
function StartLocalAudioMediaMonitoring(lineNum, session) {
    console.log("Creating LocalAudio AudioContext on line " + lineNum);

    // Create local SoundMeter
    var soundMeter = new SoundMeter(session.id, lineNum);
    if(soundMeter == null){
        console.warn("AudioContext() LocalAudio not available... its fine.")
        return null;
    }

    // Ready the getStats request
    var localAudioStream = new MediaStream();
    var audioSender = null;
    var pc = session.sessionDescriptionHandler.peerConnection;
    pc.getSenders().forEach(function (RTCRtpSender) {
        if(RTCRtpSender.track && RTCRtpSender.track.kind == "audio"){
            if(audioSender == null){
                console.log("Adding Track to Monitor: ", RTCRtpSender.track.label);
                localAudioStream.addTrack(RTCRtpSender.track);
                audioSender = RTCRtpSender;
            }
            else {
                console.log("Found another Track, but audioSender not null");
                console.log(RTCRtpSender);
                console.log(RTCRtpSender.track);
            }
        }
    });

    // Setup Charts
    var maxDataLength = 100;
    soundMeter.startTime = Date.now();
    Chart.defaults.global.defaultFontSize = 12;
    var ChatHistoryOptions = { 
        responsive: false,    
        maintainAspectRatio: false,
        devicePixelRatio: 1,
        animation: false,
        scales: {
            yAxes: [{
                ticks: { beginAtZero: true }
            }]
        }, 
    }

    // Send Kilobits Per Second
    soundMeter.SendBitRateChart = new Chart($("#line-"+ lineNum +"-AudioSendBitRate"), {
        type: 'line',
        data: {
            labels: MakeDataArray("", maxDataLength),
            datasets: [{
                label: lang.send_kilobits_per_second,
                data: MakeDataArray(0, maxDataLength),
                backgroundColor: 'rgba(0, 121, 19, 0.5)',
                borderColor: 'rgba(0, 121, 19, 1)',
                borderWidth: 1,
                pointRadius: 1
            }]
        },
        options: ChatHistoryOptions
    });
    soundMeter.SendBitRateChart.lastValueBytesSent = 0;
    soundMeter.SendBitRateChart.lastValueTimestamp = 0;

    // Send Packets Per Second
    soundMeter.SendPacketRateChart = new Chart($("#line-"+ lineNum +"-AudioSendPacketRate"), {
        type: 'line',
        data: {
            labels: MakeDataArray("", maxDataLength),
            datasets: [{
                label: lang.send_packets_per_second,
                data: MakeDataArray(0, maxDataLength),
                backgroundColor: 'rgba(0, 121, 19, 0.5)',
                borderColor: 'rgba(0, 121, 19, 1)',
                borderWidth: 1,
                pointRadius: 1
            }]
        },
        options: ChatHistoryOptions
    });
    soundMeter.SendPacketRateChart.lastValuePacketSent = 0;
    soundMeter.SendPacketRateChart.lastValueTimestamp = 0;    

    // Connect to Source
    soundMeter.connectToSource(localAudioStream, function (e) {
        if (e != null) return;

        console.log("SoundMeter for LocalAudio Connected, displaying levels for Line: " + lineNum);
        soundMeter.levelsInterval = window.setInterval(function () {
            // Calculate Levels
            //value="0" max="1" high="0.25" (this seems low... )
            var level = soundMeter.instant * 4.0;
            if (level > 1) level = 1;
            var instPercent = level * 100;
            $("#line-" + lineNum + "-Mic").css("height", instPercent.toFixed(2) +"%");
        }, 50);
        soundMeter.networkInterval = window.setInterval(function (){
            // Calculate Network Conditions
            // Sending Audio Track
            if(audioSender != null) {
                audioSender.getStats().then(function(stats) {
                    stats.forEach(function(report){

                        var theMoment = utcDateNow();
                        var SendBitRateChart = soundMeter.SendBitRateChart;
                        var SendPacketRateChart = soundMeter.SendPacketRateChart;
                        var elapsedSec = Math.floor((Date.now() - soundMeter.startTime)/1000);

                        if(report.type == "outbound-rtp"){
                            if(SendBitRateChart.lastValueTimestamp == 0) {
                                SendBitRateChart.lastValueTimestamp = report.timestamp;
                                SendBitRateChart.lastValueBytesSent = report.bytesSent;

                                SendPacketRateChart.lastValueTimestamp = report.timestamp;
                                SendPacketRateChart.lastValuePacketSent = report.packetsSent;
                                return;
                            }

                            // Send Kilobits Per second
                            var kbitsPerSec = (8 * (report.bytesSent - SendBitRateChart.lastValueBytesSent))/1000;

                            SendBitRateChart.lastValueTimestamp = report.timestamp;
                            SendBitRateChart.lastValueBytesSent = report.bytesSent;

                            soundMeter.SendBitRate.push({ value: kbitsPerSec, timestamp : theMoment});
                            SendBitRateChart.data.datasets[0].data.push(kbitsPerSec);
                            SendBitRateChart.data.labels.push("");
                            if(SendBitRateChart.data.datasets[0].data.length > maxDataLength) {
                                SendBitRateChart.data.datasets[0].data.splice(0,1);
                                SendBitRateChart.data.labels.splice(0,1);
                            }
                            SendBitRateChart.update();

                            // Send Packets Per Second
                            var PacketsPerSec = report.packetsSent - SendPacketRateChart.lastValuePacketSent;

                            SendPacketRateChart.lastValueTimestamp = report.timestamp;
                            SendPacketRateChart.lastValuePacketSent = report.packetsSent;

                            soundMeter.SendPacketRate.push({ value: PacketsPerSec, timestamp : theMoment});
                            SendPacketRateChart.data.datasets[0].data.push(PacketsPerSec);
                            SendPacketRateChart.data.labels.push("");
                            if(SendPacketRateChart.data.datasets[0].data.length > maxDataLength) {
                                SendPacketRateChart.data.datasets[0].data.splice(0,1);
                                SendPacketRateChart.data.labels.splice(0,1);
                            }
                            SendPacketRateChart.update();
                        }
                        if(report.type == "track") {
                            // Bug/security consern... this seems always to report "0"
                            // Possible reason: When applied to isolated streams, media metrics may allow an application to infer some characteristics of the isolated stream, such as if anyone is speaking (by watching the audioLevel statistic).
                            // console.log("Audio Sender: " + report.audioLevel);
                        }
                    });
                });
            }
        } ,1000);
    });

    return soundMeter;
}

// Sounds Meter Class
// ==================
class SoundMeter {
    constructor(sessionId, lineNum) {
        var audioContext = null;
        try {
            window.AudioContext = window.AudioContext || window.webkitAudioContext;
            audioContext = new AudioContext();
        }
        catch(e) {
            console.warn("AudioContext() LocalAudio not available... its fine.");
        }
        if (audioContext == null) return null;

        this.lineNum = lineNum;
        this.sessionId = sessionId;
        this.levelsInterval = null;
        this.networkInterval = null;
        this.startTime = 0;
        this.ReceiveBitRateChart = null;
        this.ReceiveBitRate = [];
        this.ReceivePacketRateChart = null;
        this.ReceivePacketRate = [];
        this.ReceivePacketLossChart = null;
        this.ReceivePacketLoss = [];
        this.ReceiveJitterChart = null;
        this.ReceiveJitter = [];
        this.ReceiveLevelsChart = null;
        this.ReceiveLevels = [];
        this.SendBitRateChart = null;
        this.SendBitRate = [];
        this.SendPacketRateChart = null;
        this.SendPacketRate = [];
        this.context = audioContext;
        this.instant = 0.0;
        this.script = audioContext.createScriptProcessor(2048, 1, 1);
        const that = this;
        this.script.onaudioprocess = function (event) {
            const input = event.inputBuffer.getChannelData(0);
            let i;
            let sum = 0.0;
            for (i = 0; i < input.length; ++i) {
                sum += input[i] * input[i];
            }
            that.instant = Math.sqrt(sum / input.length);
        }
    }
    connectToSource(stream, callback) {
        console.log("SoundMeter connecting...");
        try {
            this.mic = this.context.createMediaStreamSource(stream);
            this.mic.connect(this.script);
            // necessary to make sample run, but should not be.
            this.script.connect(this.context.destination);
            callback(null);
        }
        catch(e) {
            console.error(e); // Probably not audio track
            callback(e);
        }
    }
    stop() {
        console.log("Disconnecting SoundMeter...");
        try {
            window.clearInterval(this.levelsInterval);
            this.levelsInterval = null;
        }
        catch(e) { }
        try {
            window.clearInterval(this.networkInterval);
            this.networkInterval = null;
        }
        catch(e) { }
        this.mic.disconnect();
        this.script.disconnect();
        this.mic = null;
        this.script = null;
        try {
            this.context.close();
        }
        catch(e) { }
        this.context = null;

        // Save to IndexDb
        var lineObj = FindLineByNumber(this.lineNum);
        var QosData = {
            ReceiveBitRate: this.ReceiveBitRate,
            ReceivePacketRate: this.ReceivePacketRate,
            ReceivePacketLoss: this.ReceivePacketLoss,
            ReceiveJitter: this.ReceiveJitter,
            ReceiveLevels: this.ReceiveLevels,
            SendBitRate: this.SendBitRate,
            SendPacketRate: this.SendPacketRate,
        }
        SaveQosData(QosData, this.sessionId, lineObj.BuddyObj.identity);
    }
}
function MeterSettingsOutput(audioStream, objectId, direction, interval){
    var soundMeter = new SoundMeter(null, null);
    soundMeter.startTime = Date.now();
    soundMeter.connectToSource(audioStream, function (e) {
        if (e != null) return;

        console.log("SoundMeter Connected, displaying levels to:"+ objectId);
        soundMeter.levelsInterval = window.setInterval(function () {
            // Calculate Levels
            //value="0" max="1" high="0.25" (this seems low... )
            var level = soundMeter.instant * 4.0;
            if (level > 1) level = 1;
            var instPercent = level * 100;

            $("#"+objectId).css(direction, instPercent.toFixed(2) +"%"); // Settings_MicrophoneOutput "width" 50
        }, interval);
    });

    return soundMeter;
}

// QOS
// ===
function SaveQosData(QosData, sessionId, buddy){
    var indexedDB = window.indexedDB;
    var request = indexedDB.open("CallQosData");
    request.onerror = function(event) {
        console.error("IndexDB Request Error:", event);
    }
    request.onupgradeneeded = function(event) {
        console.warn("Upgrade Required for IndexDB... probably because of first time use.");
        var IDB = event.target.result;

        // Create Object Store
        if(IDB.objectStoreNames.contains("CallQos") == false){
            var objectStore = IDB.createObjectStore("CallQos", { keyPath: "uID" });
            objectStore.createIndex("sessionid", "sessionid", { unique: false });
            objectStore.createIndex("buddy", "buddy", { unique: false });
            objectStore.createIndex("QosData", "QosData", { unique: false });
        }
        else {
            console.warn("IndexDB requested upgrade, but object store was in place");
        }
    }
    request.onsuccess = function(event) {
        console.log("IndexDB connected to CallQosData");

        var IDB = event.target.result;
        if(IDB.objectStoreNames.contains("CallQos") == false){
            console.warn("IndexDB CallQosData.CallQos does not exists");
            return;
        }
        IDB.onerror = function(event) {
            console.error("IndexDB Error:", event);
        }

        // Prepare data to write
        var data = {
            uID: uID(),
            sessionid: sessionId,
            buddy: buddy,
            QosData: QosData
        }
        // Commit Transaction
        var transaction = IDB.transaction(["CallQos"], "readwrite");
        var objectStoreAdd = transaction.objectStore("CallQos").add(data);
        objectStoreAdd.onsuccess = function(event) {
            console.log("Call CallQos Sucess: ", sessionId);
        }
    }
}
function DisplayQosData(sessionId){
    var indexedDB = window.indexedDB;
    var request = indexedDB.open("CallQosData");
    request.onerror = function(event) {
        console.error("IndexDB Request Error:", event);
    }
    request.onupgradeneeded = function(event) {
        console.warn("Upgrade Required for IndexDB... probably because of first time use.");
    }
    request.onsuccess = function(event) {
        console.log("IndexDB connected to CallQosData");

        var IDB = event.target.result;
        if(IDB.objectStoreNames.contains("CallQos") == false){
            console.warn("IndexDB CallQosData.CallQos does not exists");
            return;
        } 

        var transaction = IDB.transaction(["CallQos"]);
        var objectStoreGet = transaction.objectStore("CallQos").index('sessionid').getAll(sessionId);
        objectStoreGet.onerror = function(event) {
            console.error("IndexDB Get Error:", event);
        }
        objectStoreGet.onsuccess = function(event) {
            if(event.target.result && event.target.result.length == 2){
                // This is the correct data

                var QosData0 = event.target.result[0].QosData;
                // ReceiveBitRate: (8) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
                // ReceiveJitter: (8) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
                // ReceiveLevels: (9) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
                // ReceivePacketLoss: (8) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
                // ReceivePacketRate: (8) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
                // SendBitRate: []
                // SendPacketRate: []
                var QosData1 = event.target.result[1].QosData;
                // ReceiveBitRate: []
                // ReceiveJitter: []
                // ReceiveLevels: []
                // ReceivePacketLoss: []
                // ReceivePacketRate: []
                // SendBitRate: (9) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
                // SendPacketRate: (9) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

                Chart.defaults.global.defaultFontSize = 12;

                var ChatHistoryOptions = { 
                    responsive: true,
                    maintainAspectRatio: false,
                    animation: false,
                    scales: {
                        yAxes: [{
                            ticks: { beginAtZero: true } //, min: 0, max: 100
                        }],
                        xAxes: [{
                            display: false
                        }]
                    }, 
                }

                // ReceiveBitRateChart
                var labelset = [];
                var dataset = [];
                var data = (QosData0.ReceiveBitRate.length > 0)? QosData0.ReceiveBitRate : QosData1.ReceiveBitRate;
                $.each(data, function(i,item){
                    labelset.push(moment.utc(item.timestamp.replace(" UTC", "")).local().format(DisplayDateFormat +" "+ DisplayTimeFormat));
                    dataset.push(item.value);
                });
                var ReceiveBitRateChart = new Chart($("#cdr-AudioReceiveBitRate"), {
                    type: 'line',
                    data: {
                        labels: labelset,
                        datasets: [{
                            label: lang.receive_kilobits_per_second,
                            data: dataset,
                            backgroundColor: 'rgba(168, 0, 0, 0.5)',
                            borderColor: 'rgba(168, 0, 0, 1)',
                            borderWidth: 1,
                            pointRadius: 1
                        }]
                    },
                    options: ChatHistoryOptions
                });

                // ReceivePacketRateChart
                var labelset = [];
                var dataset = [];
                var data = (QosData0.ReceivePacketRate.length > 0)? QosData0.ReceivePacketRate : QosData1.ReceivePacketRate;
                $.each(data, function(i,item){
                    labelset.push(moment.utc(item.timestamp.replace(" UTC", "")).local().format(DisplayDateFormat +" "+ DisplayTimeFormat));
                    dataset.push(item.value);
                });
                var ReceivePacketRateChart = new Chart($("#cdr-AudioReceivePacketRate"), {
                    type: 'line',
                    data: {
                        labels: labelset,
                        datasets: [{
                            label: lang.receive_packets_per_second,
                            data: dataset,
                            backgroundColor: 'rgba(168, 0, 0, 0.5)',
                            borderColor: 'rgba(168, 0, 0, 1)',
                            borderWidth: 1,
                            pointRadius: 1
                        }]
                    },
                    options: ChatHistoryOptions
                });

                // AudioReceivePacketLossChart
                var labelset = [];
                var dataset = [];
                var data = (QosData0.ReceivePacketLoss.length > 0)? QosData0.ReceivePacketLoss : QosData1.ReceivePacketLoss;
                $.each(data, function(i,item){
                    labelset.push(moment.utc(item.timestamp.replace(" UTC", "")).local().format(DisplayDateFormat +" "+ DisplayTimeFormat));
                    dataset.push(item.value);
                });
                var AudioReceivePacketLossChart = new Chart($("#cdr-AudioReceivePacketLoss"), {
                    type: 'line',
                    data: {
                        labels: labelset,
                        datasets: [{
                            label: lang.receive_packet_loss,
                            data: dataset,
                            backgroundColor: 'rgba(168, 99, 0, 0.5)',
                            borderColor: 'rgba(168, 99, 0, 1)',
                            borderWidth: 1,
                            pointRadius: 1
                        }]
                    },
                    options: ChatHistoryOptions
                });

                // AudioReceiveJitterChart
                var labelset = [];
                var dataset = [];
                var data = (QosData0.ReceiveJitter.length > 0)? QosData0.ReceiveJitter : QosData1.ReceiveJitter;
                $.each(data, function(i,item){
                    labelset.push(moment.utc(item.timestamp.replace(" UTC", "")).local().format(DisplayDateFormat +" "+ DisplayTimeFormat));
                    dataset.push(item.value);
                });
                var AudioReceiveJitterChart = new Chart($("#cdr-AudioReceiveJitter"), {
                    type: 'line',
                    data: {
                        labels: labelset,
                        datasets: [{
                            label: lang.receive_jitter,
                            data: dataset,
                            backgroundColor: 'rgba(0, 38, 168, 0.5)',
                            borderColor: 'rgba(0, 38, 168, 1)',
                            borderWidth: 1,
                            pointRadius: 1
                        }]
                    },
                    options: ChatHistoryOptions
                });
              
                // AudioReceiveLevelsChart
                var labelset = [];
                var dataset = [];
                var data = (QosData0.ReceiveLevels.length > 0)? QosData0.ReceiveLevels : QosData1.ReceiveLevels;
                $.each(data, function(i,item){
                    labelset.push(moment.utc(item.timestamp.replace(" UTC", "")).local().format(DisplayDateFormat +" "+ DisplayTimeFormat));
                    dataset.push(item.value);
                });
                var AudioReceiveLevelsChart = new Chart($("#cdr-AudioReceiveLevels"), {
                    type: 'line',
                    data: {
                        labels: labelset,
                        datasets: [{
                            label: lang.receive_audio_levels,
                            data: dataset,
                            backgroundColor: 'rgba(140, 0, 168, 0.5)',
                            borderColor: 'rgba(140, 0, 168, 1)',
                            borderWidth: 1,
                            pointRadius: 1
                        }]
                    },
                    options: ChatHistoryOptions
                });
                 
                // SendPacketRateChart
                var labelset = [];
                var dataset = [];
                var data = (QosData0.SendPacketRate.length > 0)? QosData0.SendPacketRate : QosData1.SendPacketRate;
                $.each(data, function(i,item){
                    labelset.push(moment.utc(item.timestamp.replace(" UTC", "")).local().format(DisplayDateFormat +" "+ DisplayTimeFormat));
                    dataset.push(item.value);
                });
                var SendPacketRateChart = new Chart($("#cdr-AudioSendPacketRate"), {
                    type: 'line',
                    data: {
                        labels: labelset,
                        datasets: [{
                            label: lang.send_packets_per_second,
                            data: dataset,
                            backgroundColor: 'rgba(0, 121, 19, 0.5)',
                            borderColor: 'rgba(0, 121, 19, 1)',
                            borderWidth: 1,
                            pointRadius: 1
                        }]
                    },
                    options: ChatHistoryOptions
                });

                // AudioSendBitRateChart
                var labelset = [];
                var dataset = [];
                var data = (QosData0.SendBitRate.length > 0)? QosData0.SendBitRate : QosData1.SendBitRate;
                $.each(data, function(i,item){
                    labelset.push(moment.utc(item.timestamp.replace(" UTC", "")).local().format(DisplayDateFormat +" "+ DisplayTimeFormat));
                    dataset.push(item.value);
                });
                var AudioSendBitRateChart = new Chart($("#cdr-AudioSendBitRate"), {
                    type: 'line',
                    data: {
                        labels: labelset,
                        datasets: [{
                            label: lang.send_kilobits_per_second,
                            data: dataset,
                            backgroundColor: 'rgba(0, 121, 19, 0.5)',
                            borderColor: 'rgba(0, 121, 19, 1)',
                            borderWidth: 1,
                            pointRadius: 1
                        }]
                    },
                    options: ChatHistoryOptions
                });
            } else {
                console.warn("Result not expected", event.target.result);
            }
        }
    }
}
function DeleteQosData(buddy){
    var indexedDB = window.indexedDB;
    var request = indexedDB.open("CallQosData");
    request.onerror = function(event) {
        console.error("IndexDB Request Error:", event);
    }
    request.onupgradeneeded = function(event) {
        console.warn("Upgrade Required for IndexDB... probably because of first time use.");
        // If this is the case, there will be no call recordings
    }
    request.onsuccess = function(event) {
        console.log("IndexDB connected to CallQosData");

        var IDB = event.target.result;
        if(IDB.objectStoreNames.contains("CallQos") == false){
            console.warn("IndexDB CallQosData.CallQos does not exists");
            return;
        }
        IDB.onerror = function(event) {
            console.error("IndexDB Error:", event);
        }

        // Loop and Delete
        console.log("Deleting CallQosData: ", buddy);
        var transaction = IDB.transaction(["CallQos"], "readwrite");
        var objectStore = transaction.objectStore("CallQos");
        var objectStoreGet = objectStore.index('buddy').getAll(buddy);

        objectStoreGet.onerror = function(event) {
            console.error("IndexDB Get Error:", event);
        }
        objectStoreGet.onsuccess = function(event) {
            if(event.target.result && event.target.result.length > 0){
                // There sre some rows to delete
                $.each(event.target.result, function(i, item){
                    // console.log("Delete: ", item.uID);
                    try{
                        objectStore.delete(item.uID);
                    } catch(e){
                        console.log("Call CallQosData Delete failed: ", e);
                    }
                });
            }
        }

    }
}

// Presence / Subscribe
// ====================
function SubscribeAll() {
    console.log("Subscribe to voicemail Messages...");

    // conference, message-summary, dialog, presence, presence.winfo, xcap-diff, dialog.winfo, refer

    // Voicemail notice
    var vmOptions = { expires: 300 }
    voicemailSubs = userAgent.subscribe(SipUsername + "@" + wssServer, 'message-summary', vmOptions); // message-summary = voicemail messages
    voicemailSubs.on('notify', function (notification) {

        // You have voicemail: 
        // Message-Account: sip:alice@example.com
        // Messages-Waiting: no
        // Fax-Message: 2/4
        // Voice-Message: 0/0 (0/0)   <-- new/old (new & urgent/ old & urgent)

        var messagesWaitng = false;
        $.each(notification.request.body.split("\n"), function (i, line) {
            if(line.indexOf("Messages-Waiting:") != -1){
                messagesWaitng = ($.trim(line.replace("Messages-Waiting:", "")) == "yes");
            }
        });

        if(messagesWaitng){
            // Notify user of voicemail
            console.log("You have voicemail!");
        }
    });

    // Dialog Subscription (This version isnt as nice as PIDF)
    // var dialogOptions = { expires: 300, extraHeaders: ['Accept: application/dialog-info+xml'] }

    // PIDF Subscription
    var dialogOptions = { expires: 300, extraHeaders: ['Accept: application/pidf+xml'] }
    // var dialogOptions = { expires: 300, extraHeaders: ['Accept: application/pidf+xml', 'application/xpidf+xml', 'application/simple-message-summary', 'application/im-iscomposing+xml'] }

    // Start subscribe all
    console.log("Starting Subscribe of all ("+ Buddies.length +") Extension Buddies...");
    for(var b=0; b<Buddies.length; b++) {
        var buddyObj = Buddies[b];
        if(buddyObj.type == "extension") {
            console.log("SUBSCRIBE: "+ buddyObj.ExtNo +"@" + wssServer);
            var blfObj = userAgent.subscribe(buddyObj.ExtNo +"@" + wssServer, 'presence', dialogOptions); 
            blfObj.data.buddyId = buddyObj.identity;
            blfObj.on('notify', function (notification) {
                RecieveBlf(notification);
            });
            BlfSubs.push(blfObj);
        }
    }
}
function SubscribeBuddy(buddyObj) {
    var dialogOptions = { expires: 300, extraHeaders: ['Accept: application/pidf+xml'] }

    if(buddyObj.type == "extension") {
        console.log("SUBSCRIBE: "+ buddyObj.ExtNo +"@" + wssServer);
        var blfObj = userAgent.subscribe(buddyObj.ExtNo +"@" + wssServer, 'presence', dialogOptions);
        blfObj.data.buddyId = buddyObj.identity;
        blfObj.on('notify', function (notification) {
            RecieveBlf(notification);
        });
        BlfSubs.push(blfObj);
    }
}
function RecieveBlf(notification) {
    if (userAgent == null || !userAgent.isRegistered()) return;

    var ContentType = notification.request.headers["Content-Type"][0].parsed;
    if (ContentType == "application/pidf+xml") {

        var xml = $($.parseXML(notification.request.body));

        var Entity = xml.find("presence").attr("entity");
        var Contact = xml.find("presence").find("tuple").find("contact").text();
        if (SipUsername == Entity.split("@")[0].split(":")[1] || SipUsername == Contact.split("@")[0].split(":")[1]){
            // Message is for you.
        } 
        else {
            console.warn("presence message not for you.", xml);
            return;
        }

        var buddy = xml.find("presence").find("tuple").attr("id");

        var statusObj = xml.find("presence").find("tuple").find("status");
        var availability = xml.find("presence").find("tuple").find("status").find("basic").text();
        var friendlyState = xml.find("presence").find("note").text();
        var dotClass = "dotOffline";

        if (friendlyState == "Not online") dotClass = "dotOffline";
        if (friendlyState == "Ready") dotClass = "dotOnline";
        if (friendlyState == "On the phone") dotClass = "dotInUse";
        if (friendlyState == "Ringing") dotClass = "dotRinging";
        if (friendlyState == "On hold") dotClass = "dotOnHold";
        if (friendlyState == "Unavailable") dotClass = "dotOffline";

        // dotOnline | dotOffline | dotRinging | dotInUse | dotReady | dotOnHold
        var buddyObj = FindBuddyByExtNo(buddy);
        if(buddyObj != null)
        {
            console.log("Setting Presence for "+ buddyObj.identity +" to "+ friendlyState);
            $("#contact-" + buddyObj.identity + "-devstate").prop("class", dotClass);
            $("#contact-" + buddyObj.identity + "-devstate-main").prop("class", dotClass);
            buddyObj.devState = dotClass;
            buddyObj.presence = friendlyState;

            if (friendlyState == "Not online") friendlyState = lang.state_not_online;
            if (friendlyState == "Ready") friendlyState = lang.state_ready;
            if (friendlyState == "On the phone") friendlyState = lang.state_on_the_phone;
            if (friendlyState == "Ringing") friendlyState = lang.state_ringing;
            if (friendlyState == "On hold") friendlyState = lang.state_on_hold;
            if (friendlyState == "Unavailable") friendlyState = lang.state_unavailable;
            $("#contact-" + buddyObj.identity + "-presence").html(friendlyState);
            $("#contact-" + buddyObj.identity + "-presence-main").html(friendlyState);
        }
    }
    else if (ContentType == "application/dialog-info+xml")
    {
        // Handle "Dialog" State

        var xml = $($.parseXML(notification.request.body));

        var ObservedUser = xml.find("dialog-info").attr("entity");
        var buddy = ObservedUser.split("@")[0].split(":")[1];

        var version = xml.find("dialog-info").attr("version");

        var DialogState = xml.find("dialog-info").attr("state");
        if (DialogState != "full") return;

        var extId = xml.find("dialog-info").find("dialog").attr("id");
        if (extId != buddy) return;

        var state = xml.find("dialog-info").find("dialog").find("state").text();
        var friendlyState = "Unknown";
        if (state == "terminated") friendlyState = "Ready";
        if (state == "trying") friendlyState = "On the phone";
        if (state == "proceeding") friendlyState = "On the phone";
        if (state == "early") friendlyState = "Ringing";
        if (state == "confirmed") friendlyState = "On the phone";

        var dotClass = "dotOffline";
        if (friendlyState == "Not online") dotClass = "dotOffline";
        if (friendlyState == "Ready") dotClass = "dotOnline";
        if (friendlyState == "On the phone") dotClass = "dotInUse";
        if (friendlyState == "Ringing") dotClass = "dotRinging";
        if (friendlyState == "On hold") dotClass = "dotOnHold";
        if (friendlyState == "Unavailable") dotClass = "dotOffline";

        // The dialog states only report devices states, and cant say online or offline.
        // dotOnline | dotOffline | dotRinging | dotInUse | dotReady | dotOnHold
        var buddyObj = FindBuddyByExtNo(buddy);
        if(buddyObj != null)
        {
            console.log("Setting Presence for "+ buddyObj.identity +" to "+ friendlyState);
            $("#contact-" + buddyObj.identity + "-devstate").prop("class", dotClass);
            $("#contact-" + buddyObj.identity + "-devstate-main").prop("class", dotClass);
            buddyObj.devState = dotClass;
            buddyObj.presence = friendlyState;

            if (friendlyState == "Unknown") friendlyState = lang.state_unknown;
            if (friendlyState == "Not online") friendlyState = lang.state_not_online;
            if (friendlyState == "Ready") friendlyState = lang.state_ready;
            if (friendlyState == "On the phone") friendlyState = lang.state_on_the_phone;
            if (friendlyState == "Ringing") friendlyState = lang.state_ringing;
            if (friendlyState == "On hold") friendlyState = lang.state_on_hold;
            if (friendlyState == "Unavailable") friendlyState = lang.state_unavailable;
            $("#contact-" + buddyObj.identity + "-presence").html(friendlyState);
            $("#contact-" + buddyObj.identity + "-presence-main").html(friendlyState);
        }
    }
}
function UnsubscribeAll() {
    console.log("Unsubscribing "+ BlfSubs.length + " subscriptions...");
    for (var blf = 0; blf < BlfSubs.length; blf++) {
        BlfSubs[blf].unsubscribe();
        BlfSubs[blf].close();
    }
    BlfSubs = new Array();

    for(var b=0; b<Buddies.length; b++) {
        var buddyObj = Buddies[b];
        if(buddyObj.type == "extension") {
            $("#contact-" + buddyObj.identity + "-devstate").prop("class", "dotOffline");
            $("#contact-" + buddyObj.identity + "-devstate-main").prop("class", "dotOffline");
            $("#contact-" + buddyObj.identity + "-presence").html(lang.state_unknown);
            $("#contact-" + buddyObj.identity + "-presence-main").html(lang.state_unknown);
        }
    }
}
function UnsubscribeBuddy(buddyObj) {
    if(buddyObj.type != "extension") return;

    for (var blf = 0; blf < BlfSubs.length; blf++) {
        var blfObj = BlfSubs[blf];
        if(blfObj.data.buddyId == buddyObj.identity){
        console.log("Unsubscribing:", buddyObj.identity);
            if(blfObj.dialog != null){
                blfObj.unsubscribe();
                blfObj.close();
            }
            BlfSubs.splice(blf, 1);
            break;
        }
    }
}

// Buddy: Chat / Instant Message / XMPP
// ====================================
function InitinaliseStream(buddy){
    var template = { TotalRows:0, DataCollection:[] }
    localDB.setItem(buddy + "-stream", JSON.stringify(template));
    return JSON.parse(localDB.getItem(buddy + "-stream"));
}
function splitString(str, size) {
    const mPieces = Math.ceil(str.length / size);
    const piecesArr = [];

    for (let i = 0, s = 0; i < mPieces; ++i, s += size) {
      piecesArr[i] = str.substr(s, size);
    }
    return piecesArr;
}
function generateAESKey(passphrase) {
    const salt = CryptoJS.lib.WordArray.random(128 / 8);
    const key256Bits = CryptoJS.PBKDF2(passphrase, salt, {
      keySize: 256 / 32,
      iterations: 100,
    });
    return key256Bits;
}
function encryptAES(message, key) {
    var message = CryptoJS.AES.encrypt(message, key);
    return message.toString();
}
function decryptAES(message, key) {
    var code = CryptoJS.AES.decrypt(message, key);
    var decryptedMessage = code.toString(CryptoJS.enc.Utf8);
    return decryptedMessage;
}
function getChatRSAPubKey(recsendSIPuser) {
    var chatPubKey = '';
    $.ajax({
	     'async': false,
	     'global': false,
	     type: "POST",
	     url: "get-text-chat-pub-key.php",
	     dataType: "JSON",
	     data: { 
		     recsendsipuser: recsendSIPuser,
                     s_ajax_call: validateSToken
             },
	     success: function(result) {
                            if (result.resmessage == 'success') {
                                chatPubKey = "`" + result.chatkey.join("") + "`";
                            } else {
                                pubKeyCheck = 1;
                                alert('An error occurred while retrieving the public key for text chat!');
                            }
             },
             error: function(result) {
                    alert('An error occurred while attempting to retrieve the public key for text chat!');
             }
    });
    return chatPubKey;
}

function SendChatMessage(buddy) {

    if (userAgent == null) return;
    if (!userAgent.isRegistered()) return;

    var messageraw = $("#contact-" + buddy + "-ChatMessage").val();
    messagetrim = $.trim(messageraw);

    if (messagetrim == "" && (sendFileCheck == 0 || (sendFileCheck == 1 && $("#selectedFile").val() == ""))) { 
        Alert(lang.alert_empty_text_message, lang.no_message);
        return;
    }

    var buddyObj = FindBuddyByIdentity(buddy);

    if ($.inArray(buddyObj.presence, ["Ready", "On the phone", "Ringing", "On hold"]) == -1) {
        alert("You cannot send a message or a file to a contact who is not online!");
        $("#sendFileLoader").remove();
        $("#selectedFile").val("");
        $("#sendFileFormChat").remove();
        sendFileCheck = 0;
        return; 
    }

    var genPassphr = Date.now() + Math.floor(Math.random()*10000).toString(6).toUpperCase();
    var aesKey = String(generateAESKey(genPassphr));
    var encryptedMes = encryptAES(messagetrim, aesKey);

    // Split the encrypted message into smaller pieces to fit the 1024 byte limit for SIP messages, which is hard-coded in Asterisk
    var messageprearr = [];
    var messageprearr = splitString(encryptedMes, 900);

    var genMessageId =  Date.now() + Math.floor(Math.random()*10000).toString(16).toUpperCase();
    var messageIdent = genMessageId + profileUser;
    var firstPieceCheck = [];
    firstPieceCheck = [messageIdent, 1];
    var lastPieceCheck = [];
    lastPieceCheck = [messageIdent, 0];

    // Get the public key of the extension to which we send the message
    var destExtChatRSAPubKey = getChatRSAPubKey(buddyObj.ExtNo);

    // Encrypt the AES key with RSA
    var newencrypt = new JSEncrypt();
    newencrypt.setPublicKey(destExtChatRSAPubKey);
    var encmIdAesKey = newencrypt.encrypt(aesKey);

    // Add the encrypted AES key as the first element of the array of message pieces
    messageprearr.unshift(encmIdAesKey);

    $("#contact-"+ buddy +"-ChatHistory").after("<span id='sendFileLoader'></span>");

    for (var k = 0; k < messageprearr.length; k++) {

         if (k == 0) {
             // Send the RSA-encrypted AES key as first piece of the message
             var messagePiece = messageIdent + "|" + messageprearr.length + "|" + parseInt(k) + "||" + messageprearr[k];
	 } else if (sendFileCheck == 0 && messageprearr[k] != '') {
	     var messagePiece = messageIdent + "|" + messageprearr.length + "|" + parseInt(k) + "||" + messageprearr[k];
	 } else if (sendFileCheck == 1 && sendFileChatErr == '') {
	     var messagePiece = messageIdent + "|" + messageprearr.length + "|" + parseInt(k) + "|" + upFileName + "|" + messageprearr[k];
	 } else if (sendFileCheck == 1 && sendFileChatErr != '') {
	     $("#sendFileFormChat").remove();
             sendFileChatErr = '';
	     sendFileCheck = 0;
	     return;
	 }

         if (k == 1) { firstPieceCheck = [messageIdent, 0]; }

         if (k == (messageprearr.length - 1)) { lastPieceCheck = [messageIdent, 1]; }

         SendChatMessageProc(buddy, buddyObj, messageIdent, messagePiece, messagetrim, firstPieceCheck, lastPieceCheck);
    }
}

function SendChatMessageProc(buddy, buddyObj, messageIdent, messagePiece, messagetrim, firstPieceCheck, lastPieceCheck) {

    var messageId = uID();

    if (pubKeyCheck == 1) { pubKeyCheck = 0; $("#selectedFile").val(""); $("#sendFileLoader").remove(); return; }

    sendFileChatErr = '';

    $("#sendFileFormChat").on('submit', function(ev) {
             ev.preventDefault();

             $.ajax({
                'async': false,
                'global': false,
                type: 'POST',
                url: 'text-chat-upload-file.php',
                data: new FormData(this),
                dataType: "JSON",
                contentType: false,
                cache: false,
                processData:false,
                success: function(respdata) {
                            if (respdata.error != '') { 
                                sendFileChatErr = respdata.error;
                                $("#sendFileFormChat").remove();
                                $("#sendFileLoader").remove();
                                alert("Error: " + respdata.error);
                            }
                },
                error: function(respdata) {
                            alert("An error occurred while sending the file!");
                }          
             });
    });

    if (sendFileCheck == 1 && (firstPieceCheck[0] == messageIdent && firstPieceCheck[1] == 1)) {
        $("#submitFileChat").click();
    }

    if (lastPieceCheck[0] == messageIdent && lastPieceCheck[1] == 1 && sendFileCheck == 1 && sendFileChatErr != '') {
        $("#sendFileFormChat").remove();
        $("#sendFileLoader").remove();
        sendFileChatErr = '';
        sendFileCheck = 0;
        return;
    }

    if (buddyObj.type == "extension" || buddyObj.type == "group") {

          var chatBuddy = buddyObj.ExtNo + "@" + wssServer;
          console.log("MESSAGE: "+ chatBuddy + " (extension)");

          var messageObj = userAgent.message(chatBuddy, messagePiece);

            messageObj.data.direction = "outbound";
            messageObj.data.messageId = messageId;

            messageObj.on("accepted", function (response, cause){

                if(response.status_code == 202) {
                    console.log("Message Accepted:", messageId);

                    // Update DB
                    var currentStream = JSON.parse(localDB.getItem(buddy + "-stream"));
                    if(currentStream != null || currentStream.DataCollection != null){
                        $.each(currentStream.DataCollection, function (i, item) {
                            if (item.ItemType == "MSG" && item.ItemId == messageId) {
                                // Found
                                item.Sent = true;
                                return false;
                            }
                        });
                        localDB.setItem(buddy + "-stream", JSON.stringify(currentStream));

                        RefreshStream(buddyObj);
                    }
                } else {
                    console.warn("Message Error", response.status_code, cause);

                    // Update DB
                    var currentStream = JSON.parse(localDB.getItem(buddy + "-stream"));
                    if(currentStream != null || currentStream.DataCollection != null){
                        $.each(currentStream.DataCollection, function (i, item) {
                            if (item.ItemType == "MSG" && item.ItemId == messageId) {
                                // Found
                                item.Sent = false;
                                return false;
                            }
                        });
                        localDB.setItem(buddy + "-stream", JSON.stringify(currentStream));

                        RefreshStream(buddyObj);
                    }                
                }
            });

          // Custom Web hook
          if (typeof web_hook_on_message !== 'undefined') web_hook_on_message(messageObj); 
    }

    if (lastPieceCheck[0] == messageIdent && lastPieceCheck[1] == 1) {

       // Update Stream
       var DateTime = moment.utc().format("YYYY-MM-DD HH:mm:ss UTC");
       var currentStream = JSON.parse(localDB.getItem(buddy + "-stream"));
       if(currentStream == null) currentStream = InitinaliseStream(buddy);

       // Add New Message
       var newMessageJson = {
           ItemId: messageId,
           ItemType: "MSG",
           ItemDate: DateTime,
           SrcUserId: profileUserID,
           Src: "\""+ profileName +"\" <"+ profileUser +">",
           DstUserId: buddy,
           Dst: "",
           MessageData: messagetrim
       }

       // If a file is sent, add the sent file section
       if (sendFileCheck == 1) {

           $("#sendFileFormChat").remove();
           sendFileCheck = 0;

           var newMessageId = uID();
           var newDateTime = moment.utc().format("YYYY-MM-DD HH:mm:ss UTC");

	   var newFileMessageJson = {
	        ItemId: newMessageId,
	        ItemType: "FILE",
	        ItemDate: newDateTime,
	        SrcUserId: profileUserID,
	        Src: "\""+ profileName +"\" <"+ profileUser +">",
	        DstUserId: buddy,
	        Dst: buddyObj.ExtNo,
                SentFileName: upFileName,
	        MessageData: "Download file"
	   }

           if (sendFileChatErr == '') {
               currentStream.DataCollection.push(newFileMessageJson);
           }

       } else { $("#sendFileFormChat").remove(); }

       currentStream.DataCollection.push(newMessageJson);

       currentStream.TotalRows = currentStream.DataCollection.length;
       localDB.setItem(buddy + "-stream", JSON.stringify(currentStream));

    }

    // Post Add Activity
    if (lastPieceCheck[0] == messageIdent && lastPieceCheck[1] == 1) {
        $("#sendFileLoader").remove();
        $("#contact-" + buddy + "-ChatMessage").val("");
    }
    $("#contact-" + buddy + "-emoji-menu").hide();

    if(buddyObj.recognition != null){
       buddyObj.recognition.abort();
       buddyObj.recognition = null;
    }

    RefreshStream(buddyObj);
}

function ReceiveMessage(message) {

    var callerID = message.remoteIdentity.displayName;
    var did = message.remoteIdentity.uri.user;

    console.log("New Incoming Message!", "\""+ callerID +"\" <"+ did +">");

    message.data.direction = "inbound";

    if(did.length > DidLength) {
        // Contacts cannot receive Text Messages, because they cannot reply
        // This may change with FAX, Email, WhatsApp etc
        console.warn("DID length greater then extensions length")
        return;
    }

    var CurrentCalls = countSessions("0");

    var buddyObj = FindBuddyByDid(did);
    // Make new contact if it's not there
    if(buddyObj == null) {
        var json = JSON.parse(localDB.getItem(profileUserID + "-Buddies"));
        if(json == null) json = InitUserBuddies();

        // Add Extension
        var id = uID();
        var dateNow = utcDateNow();
        json.DataCollection.push({
            Type: "extension",
            LastActivity: dateNow,
            ExtensionNumber: did,
            MobileNumber: "",
            ContactNumber1: "",
            ContactNumber2: "",
            uID: id,
            cID: null,
            gID: null,
            DisplayName: callerID,
            Position: "",
            Description: "",
            Email: "",
            MemberCount: 0
        });
        buddyObj = new Buddy("extension", id, callerID, did, "", "", "", dateNow, "", "");
        AddBuddy(buddyObj, true, (CurrentCalls==0), true);

        // Update Size
        json.TotalRows = json.DataCollection.length;

        // Save To DB
        localDB.setItem(profileUserID + "-Buddies", JSON.stringify(json));
    }

    var encryptedtext = message.body;
    var originalMessageArr = encryptedtext.split("|");

    if (originalMessageArr[3] != '' && typeof originalMessageArr[3] != 'undefined' && originalMessageArr[3] != null) {
        var fileSentDuringChat = 1;
	var recFileName = originalMessageArr[3];
    } else {
	var fileSentDuringChat = 0;
        var recFileName = '';
    }

    var currentMId = originalMessageArr[0];
    var totalPieceNo = parseInt(originalMessageArr[1]);
    var currentPieceNo = parseInt(originalMessageArr[2]);

    // Reassemble the original message and decrypt it
    if (currentPieceNo == 0) {

       if (splitMessage.hasOwnProperty(currentMId)) {

          if (currentPieceNo == 0) {
              var aesPayload = originalMessageArr[4];
              var newdecrypt = new JSEncrypt();
              newdecrypt.setPrivateKey(currentChatPrivKey);
              var decAESKeyCon = newdecrypt.decrypt(aesPayload);
              splitMessage[currentMId].aeskeyandiv = decAESKeyCon;

          } else {
             splitMessage[currentMId][currentPieceNo] = originalMessageArr[4];
          }

       } else {

          if (currentPieceNo == 0) {
              var aesPayload = originalMessageArr[4];
              var newdecrypt = new JSEncrypt();
              newdecrypt.setPrivateKey(currentChatPrivKey);
              var decAESKeyCon = newdecrypt.decrypt(aesPayload);
              splitMessage[currentMId] = { "aeskeyandiv": decAESKeyCon };

          } else {
             splitMessage[currentMId] = { [currentPieceNo]: originalMessageArr[4] };
          }

       }

       return;

    } else if (currentPieceNo < (totalPieceNo - 1)) {

        if (splitMessage.hasOwnProperty(currentMId)) {
            splitMessage[currentMId][currentPieceNo] = originalMessageArr[4];
        } else {
	    splitMessage[currentMId] = { [currentPieceNo]: originalMessageArr[4] };
        }

        return;

    } else if (currentPieceNo == (totalPieceNo - 1)) {

        if (splitMessage.hasOwnProperty(currentMId)) {
            splitMessage[currentMId][currentPieceNo] = originalMessageArr[4];
        } else {
	    splitMessage[currentMId] = { [currentPieceNo]: originalMessageArr[4] };
        }

        if (Object.keys(splitMessage[currentMId]).length == totalPieceNo) {

            var decryptAesKey = splitMessage[currentMId]["aeskeyandiv"];

            delete splitMessage[currentMId]["aeskeyandiv"];
            var origMessageEnc = '';
            var orderedMPieces = Object.keys(splitMessage[currentMId]).sort().reduce(function(obj, key) { 
                obj[key] = splitMessage[currentMId][key]; 
                return obj;
            },{});

            Object.keys(orderedMPieces).forEach(function(key, index) {
                origMessageEnc += splitMessage[currentMId][key];
            });

            var originalMessage = decryptAES(origMessageEnc, decryptAesKey);

	    delete splitMessage[currentMId];

        } else { return; }
    }

    var messageId = uID();
    var DateTime = utcDateNow();

    // Get the actual person sending (since all group messages come from the group)
    var ActualSender = "";
    if(buddyObj.type == "group") {
        var assertedIdentity = message.request.headers["P-Asserted-Identity"][0].raw; // Name Surname <ExtNo> 
        var bits = assertedIdentity.split(" <");
        var CallerID = bits[0];
        var CallerIDNum = bits[1].replace(">", "");

        ActualSender = CallerID; // P-Asserted-Identity;
    }

    // Current stream
    var currentStream = JSON.parse(localDB.getItem(buddyObj.identity + "-stream"));
    if(currentStream == null) currentStream = InitinaliseStream(buddyObj.identity);

    // Add new message
    var newMessageJson = {
        ItemId: messageId,
        ItemType: "MSG",
        ItemDate: DateTime,
        SrcUserId: buddyObj.identity,
        Src: "\""+ buddyObj.CallerIDName +"\" <"+ buddyObj.ExtNo +">",
        DstUserId: profileUserID,
        Dst: "",
        MessageData: originalMessage
    }

    // If a file is received, add the received file section
    if (fileSentDuringChat == 1 && recFileName != '') {

        fileSentDuringChat = 0;

        var newMessageId = uID();
        var newDateTime = moment.utc().format("YYYY-MM-DD HH:mm:ss UTC");

	var newFileMessageJson = {
	        ItemId: newMessageId,
	        ItemType: "FILE",
	        ItemDate: newDateTime,
	        SrcUserId: buddyObj.identity,
                Src: "\""+ buddyObj.CallerIDName +"\" <"+ buddyObj.ExtNo +">",
	        DstUserId: profileUserID,
	        Dst: profileUser,
                ReceivedFileName: recFileName,
	        MessageData: "Download file"
	}

        currentStream.DataCollection.push(newFileMessageJson);
    }

    currentStream.DataCollection.push(newMessageJson);

    currentStream.TotalRows = currentStream.DataCollection.length;
    localDB.setItem(buddyObj.identity + "-stream", JSON.stringify(currentStream));

    // Update Last Activity
    // ====================
    UpdateBuddyActivity(buddyObj.identity);
    RefreshStream(buddyObj);

    // Handle Stream Not visible
    // =========================
    var streamVisible = $("#stream-"+ buddyObj.identity).is(":visible");
    if (!streamVisible) {
        // Add or Increase the Badge
        IncreaseMissedBadge(buddyObj.identity);
        if ("Notification" in window) {
            if (Notification.permission === "granted") {
                var imageUrl = getPicture(buddyObj.identity);
                var noticeOptions = { body: originalMessage.substring(0, 250), icon: imageUrl }
                var inComingChatNotification = new Notification(lang.message_from + " : " + buddyObj.CallerIDName, noticeOptions);
                inComingChatNotification.onclick = function (event) {
                    // Show Message
                    SelectBuddy(buddyObj.identity);
                }
            }
        }
        // Play Alert
        console.log("Audio:", audioBlobs.Alert.url);
        var rinnger = new Audio(audioBlobs.Alert.blob);
        rinnger.preload = "auto";
        rinnger.loop = false;
        rinnger.oncanplaythrough = function(e) {
            if (typeof rinnger.sinkId !== 'undefined' && getRingerOutputID() != "default") {
                rinnger.setSinkId(getRingerOutputID()).then(function() {
                    console.log("Set sinkId to:", getRingerOutputID());
                }).catch(function(e){
                    console.warn("Failed not apply setSinkId.", e);
                });
            }
            // If there has been no interaction with the page at all... this page will not work
            rinnger.play().then(function(){
               // Audio Is Playing
            }).catch(function(e){
                console.warn("Unable to play audio file.", e);
            });
        }
        message.data.rinngerObj = rinnger; // Will be attached to this object until its disposed.
    } else {
        // Message window is active.
    }
}
function AddCallMessage(buddy, session, reasonCode, reasonText) {

    var currentStream = JSON.parse(localDB.getItem(buddy + "-stream"));
    if(currentStream == null) currentStream = InitinaliseStream(buddy);

    var CallEnd = moment.utc(); // Take Now as the Hangup Time
    var callDuration = 0;
    var totalDuration = 0;
    var ringTime = 0;

    var CallStart = moment.utc(session.data.callstart.replace(" UTC", "")); // Actual start (both inbound and outbound)
    var CallAnswer = null; // On Accept when inbound, Remote Side when Outbound
    if(session.startTime){
        // The time when WE answered the call (May be null - no answer)
        // or
        // The time when THEY answered the call (May be null - no answer)
        CallAnswer = moment.utc(session.startTime);  // Local Time gets converted to UTC 

        callDuration = moment.duration(CallEnd.diff(CallAnswer));
        ringTime = moment.duration(CallAnswer.diff(CallStart));
    }
    totalDuration = moment.duration(CallEnd.diff(CallStart));

    console.log(session.data.reasonCode + "("+ session.data.reasonText +")")

    var srcId = "";
    var srcCallerID = "";
    var dstId = ""
    var dstCallerID = "";
    if(session.data.calldirection == "inbound") {
        srcId = buddy;
        dstId = profileUserID;
        srcCallerID = "<"+ session.remoteIdentity.uri.user +"> "+ session.remoteIdentity.displayName;
        dstCallerID = "<"+ profileUser+"> "+ profileName;
    } else if(session.data.calldirection == "outbound") {
        srcId = profileUserID;
        dstId = buddy;
        srcCallerID = "<"+ profileUser+"> "+ profileName;
        dstCallerID = session.remoteIdentity.uri.user;
    }

    var callDirection = session.data.calldirection;
    var withVideo = session.data.withvideo;
    var sessionId = session.id;
    var hanupBy = session.data.terminateby;

    var newMessageJson = {
        CdrId: uID(),
        ItemType: "CDR",
        ItemDate: CallStart.format("YYYY-MM-DD HH:mm:ss UTC"),
        CallAnswer: (CallAnswer)? CallAnswer.format("YYYY-MM-DD HH:mm:ss UTC") : null,
        CallEnd: CallEnd.format("YYYY-MM-DD HH:mm:ss UTC"),
        SrcUserId: srcId,
        Src: srcCallerID,
        DstUserId: dstId,
        Dst: dstCallerID,
        RingTime: (ringTime != 0)? ringTime.asSeconds() : 0,
        Billsec: (callDuration != 0)? callDuration.asSeconds() : 0,
        TotalDuration: (totalDuration != 0)? totalDuration.asSeconds() : 0,
        ReasonCode: reasonCode,
        ReasonText: reasonText,
        WithVideo: withVideo,
        SessionId: sessionId,
        CallDirection: callDirection,
        Terminate: hanupBy,
        // CRM
        MessageData: null,
        Tags: [],
        //Reporting
        Transfers: (session.data.transfer)? session.data.transfer : [],
        Mutes: (session.data.mute)? session.data.mute : [],
        Holds: (session.data.hold)? session.data.hold : [],
        Recordings: (session.data.recordings)? session.data.recordings : [],
        ConfCalls: (session.data.confcalls)? session.data.confcalls : [],
        QOS: []
    }

    console.log("New CDR", newMessageJson);

    currentStream.DataCollection.push(newMessageJson);
    currentStream.TotalRows = currentStream.DataCollection.length;
    localDB.setItem(buddy + "-stream", JSON.stringify(currentStream));

    UpdateBuddyActivity(buddy);
}

function SendImageDataMessage(buddy, ImgDataUrl) {
    if (userAgent == null) return;
    if (!userAgent.isRegistered()) return;

    // Ajax Upload
    // ===========

    var DateTime = moment.utc().format("YYYY-MM-DD HH:mm:ss UTC");
    var formattedMessage = '<IMG class=previewImage onClick="PreviewImage(this)" src="'+ ImgDataUrl +'">';
    var messageString = "<table class=\"ourChatMessage chatMessageTable\" cellspacing=0 cellpadding=0><tr><td style=\"width: 80px\">"
        + "<div class=messageDate>" + DateTime + "</div>"
        + "</td><td>"
        + "<div class=ourChatMessageText>" + formattedMessage + "</div>"
        + "</td></tr></table>";
    $("#contact-" + buddy + "-ChatHistory").append(messageString);
    updateScroll(buddy);

    ImageEditor_Cancel(buddy);

    UpdateBuddyActivity(buddy);
}

function SendFileDataMessage(buddy, FileDataUrl, fileName, fileSize) {
    if (userAgent == null) return;
    if (!userAgent.isRegistered()) return;

    var fileID = uID();

    // Ajax Upload
    // ===========
    $.ajax({
        type:'POST',
        url: '/api/',
        data: "<XML>"+ FileDataUrl +"</XML>",
        xhr: function(e) {
            var myXhr = $.ajaxSettings.xhr();
            if(myXhr.upload){
                myXhr.upload.addEventListener('progress',function(event){
                    var percent = (event.loaded / event.total) * 100;
                    console.log("Progress for upload to "+ buddy +" ("+ fileID +"):"+ percent);
                    $("#FileProgress-Bar-"+ fileID).css("width", percent +"%");
                }, false);
            }
            return myXhr;
        },
        success:function(data, status, jqXHR){
            // console.log(data);
            $("#FileUpload-"+ fileID).html("Sent");
            $("#FileProgress-"+ fileID).hide();
            $("#FileProgress-Bar-"+ fileID).css("width", "0%");
        },
        error: function(data, status, error){
            // console.log(data);
            $("#FileUpload-"+ fileID).html("Failed ("+ data.status +")");
            $("#FileProgress-"+ fileID).hide();
            $("#FileProgress-Bar-"+ fileID).css("width", "100%");
        }
    });

    // Add To Message Stream
    // =====================
    var DateTime = utcDateNow();

    var showReview = false;
    var fileIcon = '<i class="fa fa-file"></i>';
    // Image Icons
    if(fileName.toLowerCase().endsWith(".png")) {
        fileIcon =  '<i class="fa fa-file-image-o"></i>';
        showReview = true;
    }
    if(fileName.toLowerCase().endsWith(".jpg")) {
        fileIcon =  '<i class="fa fa-file-image-o"></i>';
        showReview = true;
    }
    if(fileName.toLowerCase().endsWith(".jpeg")) {
        fileIcon =  '<i class="fa fa-file-image-o"></i>';
        showReview = true;
    }
    if(fileName.toLowerCase().endsWith(".bmp")) {
        fileIcon =  '<i class="fa fa-file-image-o"></i>';
        showReview = true;
    }
    if(fileName.toLowerCase().endsWith(".gif")) {
        fileIcon =  '<i class="fa fa-file-image-o"></i>';
        showReview = true;
    }
    // video Icons
    if(fileName.toLowerCase().endsWith(".mov")) fileIcon =  '<i class="fa fa-file-video-o"></i>';
    if(fileName.toLowerCase().endsWith(".avi")) fileIcon =  '<i class="fa fa-file-video-o"></i>';
    if(fileName.toLowerCase().endsWith(".mpeg")) fileIcon =  '<i class="fa fa-file-video-o"></i>';
    if(fileName.toLowerCase().endsWith(".mp4")) fileIcon =  '<i class="fa fa-file-video-o"></i>';
    if(fileName.toLowerCase().endsWith(".mvk")) fileIcon =  '<i class="fa fa-file-video-o"></i>';
    if(fileName.toLowerCase().endsWith(".webm")) fileIcon =  '<i class="fa fa-file-video-o"></i>';
    // Audio Icons
    if(fileName.toLowerCase().endsWith(".wav")) fileIcon =  '<i class="fa fa-file-audio-o"></i>';
    if(fileName.toLowerCase().endsWith(".mp3")) fileIcon =  '<i class="fa fa-file-audio-o"></i>';
    if(fileName.toLowerCase().endsWith(".ogg")) fileIcon =  '<i class="fa fa-file-audio-o"></i>';
    // Compressed Icons
    if(fileName.toLowerCase().endsWith(".zip")) fileIcon =  '<i class="fa fa-file-archive-o"></i>';
    if(fileName.toLowerCase().endsWith(".rar")) fileIcon =  '<i class="fa fa-file-archive-o"></i>';
    if(fileName.toLowerCase().endsWith(".tar.gz")) fileIcon =  '<i class="fa fa-file-archive-o"></i>';
    // Pdf Icons
    if(fileName.toLowerCase().endsWith(".pdf")) fileIcon =  '<i class="fa fa-file-pdf-o"></i>';

    var formattedMessage = "<DIV><SPAN id=\"FileUpload-"+ fileID +"\">Sending</SPAN>: "+ fileIcon +" "+ fileName +"</DIV>"
    formattedMessage += "<DIV id=\"FileProgress-"+ fileID +"\" class=\"progressBarContainer\"><DIV id=\"FileProgress-Bar-"+ fileID +"\" class=\"progressBarTrack\"></DIV></DIV>"
    if(showReview){
        formattedMessage += "<DIV><IMG class=previewImage onClick=\"PreviewImage(this)\" src=\""+ FileDataUrl +"\"></DIV>";
    }

    var messageString = "<table class=\"ourChatMessage chatMessageTable\" cellspacing=0 cellpadding=0><tr><td style=\"width: 80px\">"
        + "<div class=messageDate>" + DateTime + "</div>"
        + "</td><td>"
        + "<div class=ourChatMessageText>" + formattedMessage + "</div>"
        + "</td></tr></table>";
    $("#contact-" + buddy + "-ChatHistory").append(messageString);
    updateScroll(buddy);

    ImageEditor_Cancel(buddy);

    // Update Last Activity
    // ====================
    UpdateBuddyActivity(buddy);
}
function updateLineScroll(lineNum) {
    RefreshLineActivity(lineNum);

    var element = $("#line-"+ lineNum +"-CallDetails").get(0);
    element.scrollTop = element.scrollHeight;
}
function updateScroll(buddy) {
    var history = $("#contact-"+ buddy +"-ChatHistory");
    if(history.children().length > 0) history.children().last().get(0).scrollIntoView(false);
    history.get(0).scrollTop = history.get(0).scrollHeight;
}
function PreviewImage(obj){

    $.jeegoopopup.close();
    var previewimgHtml = '<div>';
    previewimgHtml += '<div class="UiWindowField scroller">';
    previewimgHtml += '<div><img src="'+ obj.src +'"/></div>';
    previewimgHtml += '</div></div>';

    $.jeegoopopup.open({
                title: 'Preview Image',
                html: previewimgHtml,
                width: '800',
                height: '600',
                center: true,
                scrolling: 'no',
                skinClass: 'jg_popup_basic',
                overlay: true,
                opacity: 50,
                draggable: true,
                resizable: false,
                fadeIn: 0
    });
    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); });
    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); } });
}

// Missed Item Notification
// ========================
function IncreaseMissedBadge(buddy) {
    var buddyObj = FindBuddyByIdentity(buddy);
    if(buddyObj == null) return;

    // Up the Missed Count
    // ===================
    buddyObj.missed += 1;

    // Take Out
    var json = JSON.parse(localDB.getItem(profileUserID + "-Buddies"));
    if(json != null) {
        $.each(json.DataCollection, function (i, item) {
            if(item.uID == buddy || item.cID == buddy || item.gID == buddy){
                item.missed = item.missed +1;
                return false;
            }
        });
        // Put Back
        localDB.setItem(profileUserID + "-Buddies", JSON.stringify(json));
    }

    // Update Badge
    // ============
    $("#contact-" + buddy + "-missed").text(buddyObj.missed);
    $("#contact-" + buddy + "-missed").show();
    console.log("Set Missed badge for "+ buddy +" to: "+ buddyObj.missed);
}
function UpdateBuddyActivity(buddy){
    var buddyObj = FindBuddyByIdentity(buddy);
    if(buddyObj == null) return;

    // Update Last Activity Time
    // =========================
    var timeStamp = utcDateNow();
    buddyObj.lastActivity = timeStamp;
    console.log("Last Activity is now: "+ timeStamp);

    // Take Out
    var json = JSON.parse(localDB.getItem(profileUserID + "-Buddies"));
    if(json != null) {
        $.each(json.DataCollection, function (i, item) {
            if(item.uID == buddy || item.cID == buddy || item.gID == buddy){
                item.LastActivity = timeStamp;
                return false;
            }
        });
        // Put Back
        localDB.setItem(profileUserID + "-Buddies", JSON.stringify(json));
    }

    // List Update
    // ===========
    UpdateBuddyList();
}
function ClearMissedBadge(buddy) {
    var buddyObj = FindBuddyByIdentity(buddy);
    if(buddyObj == null) return;

    buddyObj.missed = 0;

    // Take Out
    var json = JSON.parse(localDB.getItem(profileUserID + "-Buddies"));
    if(json != null) {
        $.each(json.DataCollection, function (i, item) {
            if(item.uID == buddy || item.cID == buddy || item.gID == buddy){
                item.missed = 0;
                return false;
            }
        });
        // Put Back
        localDB.setItem(profileUserID + "-Buddies", JSON.stringify(json));
    }

    $("#contact-" + buddy + "-missed").text(buddyObj.missed);
    $("#contact-" + buddy + "-missed").hide(400);
}

// Outbound Calling
// ================
function VideoCall(lineObj, dialledNumber) {
    if (userAgent == null) return;
    if (!userAgent.isRegistered()) return;
    if(lineObj == null) return;

    if(HasAudioDevice == false){
        Alert(lang.alert_no_microphone);
        return;
    }

    if(HasVideoDevice == false){
        console.warn("No video devices (webcam) found, switching to audio call.");
        AudioCall(lineObj, dialledNumber);
        return;
    }

    var supportedConstraints = navigator.mediaDevices.getSupportedConstraints();
    var spdOptions = {
        sessionDescriptionHandlerOptions: {
            constraints: {
                audio: { deviceId : "default" },
                video: { deviceId : "default" }
            }
        }
    }

    // Configure Audio
    var currentAudioDevice = getAudioSrcID();
    if(currentAudioDevice != "default"){
        var confirmedAudioDevice = false;
        for (var i = 0; i < AudioinputDevices.length; ++i) {
            if(currentAudioDevice == AudioinputDevices[i].deviceId) {
                confirmedAudioDevice = true;
                break;
            }
        }
        if(confirmedAudioDevice) {
            spdOptions.sessionDescriptionHandlerOptions.constraints.audio.deviceId = { exact: currentAudioDevice }
        }
        else {
            console.warn("The audio device you used before is no longer available, default settings applied.");
            localDB.setItem("AudioSrcId", "default");
        }
    }
    // Add additional Constraints
    if(supportedConstraints.autoGainControl) {
        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.autoGainControl = AutoGainControl;
    }
    if(supportedConstraints.echoCancellation) {
        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.echoCancellation = EchoCancellation;
    }
    if(supportedConstraints.noiseSuppression) {
        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.noiseSuppression = NoiseSuppression;
    }

    // Configure Video
    var currentVideoDevice = getVideoSrcID();
    if(currentVideoDevice != "default"){
        var confirmedVideoDevice = false;
        for (var i = 0; i < VideoinputDevices.length; ++i) {
            if(currentVideoDevice == VideoinputDevices[i].deviceId) {
                confirmedVideoDevice = true;
                break;
            }
        }
        if(confirmedVideoDevice){
            spdOptions.sessionDescriptionHandlerOptions.constraints.video.deviceId = { exact: currentVideoDevice }
        }
        else {
            console.warn("The video device you used before is no longer available, default settings applied.");
            localDB.setItem("VideoSrcId", "default"); // resets for later and subsequent calls
        }
    }
    // Add additional Constraints
    if(supportedConstraints.frameRate && maxFrameRate != "") {
        spdOptions.sessionDescriptionHandlerOptions.constraints.video.frameRate = maxFrameRate;
    }
    if(supportedConstraints.height && videoHeight != "") {
        spdOptions.sessionDescriptionHandlerOptions.constraints.video.height = videoHeight;
    }
    console.log(supportedConstraints)
    console.log(supportedConstraints.aspectRatio)
    console.log(videoAspectRatio)
    if(supportedConstraints.aspectRatio && videoAspectRatio != "") {
        spdOptions.sessionDescriptionHandlerOptions.constraints.video.aspectRatio = videoAspectRatio;
    }

    $("#line-" + lineObj.LineNumber + "-msg").html(lang.starting_video_call);
    $("#line-" + lineObj.LineNumber + "-timer").show();

    // Invite
    console.log("INVITE (video): " + dialledNumber + "@" + wssServer, spdOptions);
    lineObj.SipSession = userAgent.invite("sip:" + dialledNumber + "@" + wssServer, spdOptions);

    var startTime = moment.utc();
    lineObj.SipSession.data.line = lineObj.LineNumber;
    lineObj.SipSession.data.buddyId = lineObj.BuddyObj.identity;
    lineObj.SipSession.data.calldirection = "outbound";
    lineObj.SipSession.data.dst = dialledNumber;
    lineObj.SipSession.data.callstart = startTime.format("YYYY-MM-DD HH:mm:ss UTC");
    lineObj.SipSession.data.callTimer = window.setInterval(function(){
        var now = moment.utc();
        var duration = moment.duration(now.diff(startTime)); 
        $("#line-" + lineObj.LineNumber + "-timer").html(formatShortDuration(duration.asSeconds()));
    }, 1000);
    lineObj.SipSession.data.VideoSourceDevice = getVideoSrcID();
    lineObj.SipSession.data.AudioSourceDevice = getAudioSrcID();
    lineObj.SipSession.data.AudioOutputDevice = getAudioOutputID();
    lineObj.SipSession.data.terminateby = "them";
    lineObj.SipSession.data.withvideo = true;

    updateLineScroll(lineObj.LineNumber);

    // Do Necessary UI Wireup
    wireupVideoSession(lineObj);

    // Custom Web hook
    if(typeof web_hook_on_invite !== 'undefined') web_hook_on_invite(lineObj.SipSession);
}

function ComposeEmail(buddy, obj, event) {

        event.stopPropagation();
        SelectBuddy(buddy);

        var buddyObj = FindBuddyByIdentity(buddy);

	$("#roundcubeFrame").remove();
	$("#rightContent").show();
	$(".streamSelected").each(function() { $(this).css("display", "none"); });
	$("#rightContent").append('<iframe id="roundcubeFrame" name="displayFrame"></iframe>');

	var rcDomain = '';
	var rcBasicAuthUser = '';
	var rcBasicAuthPass = '';
	var rcUsername = '';
	var rcPasswd = '';

	$.ajax({
	     'async': false,
	     'global': false,
	     type: "POST",
	     url: "get-email-info.php",
	     dataType: "JSON",
	     data: {
		     username: userName,
		     s_ajax_call: validateSToken
	     },
	     success: function(datafromdb) {
		               rcDomain = datafromdb.rcdomain;
		               rcBasicAuthUser = encodeURIComponent(datafromdb.rcbasicauthuser);                              
		               rcBasicAuthPass = encodeURIComponent(datafromdb.rcbasicauthpass);
		               rcUsername = datafromdb.rcuser;
		               rcPasswd = datafromdb.rcpassword;
	     },
	     error: function(datafromdb) {
		             alert("An error occurred while trying to retrieve data from the database!");
	     }
	});

	if (rcBasicAuthUser != '' && rcBasicAuthPass != '') { 
	    var loginURL = "https://"+ rcBasicAuthUser +":"+ rcBasicAuthPass +"@"+ rcDomain +"/";
            var composeURL = "https://"+ rcBasicAuthUser +":"+ rcBasicAuthPass +"@"+ rcDomain +"/?_task=mail&_action=compose&_to="+ encodeURIComponent(buddyObj.Email) +"";
	} else { 
            var loginURL = "https://"+ rcDomain +"/";
            var composeURL = "https://"+ rcDomain +"/?_task=mail&_action=compose&_to="+ encodeURIComponent(buddyObj.Email) +"";
        }

	var form = '<form id="rcForm" method="POST" action="'+ loginURL +'" target="displayFrame">'; 
	form += '<input type="hidden" name="_action" value="login" />';
	form += '<input type="hidden" name="_task" value="login" />';
	form += '<input type="hidden" name="_autologin" value="1" />';
	form += '<input name="_user" value="'+ rcUsername +'" type="text" />';
	form += '<input name="_pass" value="'+ rcPasswd +'" type="password" />';
	form += '<input id="submitButton" type="submit" value="Login" />';
	form += '</form>';

	$("#roundcubeFrame").append(form);

        if (RCLoginCheck == 0) {
            $("#submitButton").click();
            RCLoginCheck = 1;

            if (rcBasicAuthUser != '' && rcBasicAuthPass != '') {
                if (confirm('You are about to log in to the site "'+ rcDomain +'" with the username "'+ rcBasicAuthUser +'".')) {
                    $("#roundcubeFrame").attr("src", composeURL);
                }
            } else { setTimeout(function() { $("#roundcubeFrame").attr("src", composeURL); }, 1000); }

        } else { $("#roundcubeFrame").attr("src", composeURL); }
}
function AudioCallMenu(buddy, obj){

    if (($(window).width() - event.pageX) > 54) { var leftPos = event.pageX - 222; } else { var leftPos = event.pageX - 276; }
    if (($(window).height() - event.pageY) > 140) { var topPos = event.pageY + 27; } else { var topPos = event.pageY - 80; }

    var buddyObj = FindBuddyByIdentity(buddy);

    if(buddyObj.type == "extension") {

        // Extension
        var menu = "<div id=quickCallMenu>";
        menu += "<table id=quickCallTable cellspacing=10 cellpadding=0 style=\"margin-left:auto; margin-right: auto\">";

        menu += "<tr class=quickNumDialRow><td><i class=\"fa fa-phone-square\"></i></td><td>"+ lang.call_extension + "</td><td><span class=quickNumToDial>" + buddyObj.ExtNo + "</span></td></tr>";

        if (buddyObj.MobileNumber != null && buddyObj.MobileNumber != "") {
            menu += "<tr class=quickNumDialRow><td><i class=\"fa fa-mobile\"></i></td><td>"+ lang.call_mobile + "</td><td><span class=quickNumToDial>" + buddyObj.MobileNumber + "</span></td></tr>";
        }

        if (buddyObj.ContactNumber1 != null && buddyObj.ContactNumber1 != "") {
            menu += "<tr class=quickNumDialRow><td><i class=\"fa fa-phone\"></i></td><td>"+ lang.call_number + "</td><td><span class=quickNumToDial>" + buddyObj.ContactNumber1 + "</span></td></tr>";
        }

        if (buddyObj.ContactNumber2 != null && buddyObj.ContactNumber2 != "") {
            menu += "<tr class=quickNumDialRow><td><i class=\"fa fa-phone\"></i></td><td>"+ lang.call_number + "</td><td><span class=quickNumToDial>" + buddyObj.ContactNumber2 + "</span></td></tr>";
        }

        menu += "</table>";
        menu += "</div>";

        var consoleLogContent = "Menu click AudioCall("+ buddy +", ";

    } else if (buddyObj.type == "contact") {

        // Contact
        var menu = "<div id=quickCallMenu>";
        menu += "<table id=quickCallTable cellspacing=10 cellpadding=0 style=\"margin-left:auto; margin-right: auto\">";

        if (buddyObj.MobileNumber != null && buddyObj.MobileNumber != "") {
            menu += "<tr class=quickNumDialRow><td><i class=\"fa fa-mobile\"></i></td><td>"+ lang.call_mobile + "</td><td><span class=quickNumToDial>" + buddyObj.MobileNumber + "</span></td></tr>";
        }

        if (buddyObj.ContactNumber1 != null && buddyObj.ContactNumber1 != "") {
            menu += "<tr class=quickNumDialRow><td><i class=\"fa fa-phone\"></i></td><td>"+ lang.call_number + "</td><td><span class=quickNumToDial>" + buddyObj.ContactNumber1 + "</span></td></tr>";
        }

        if (buddyObj.ContactNumber2 != null && buddyObj.ContactNumber2 != "") {
            menu += "<tr class=quickNumDialRow><td><i class=\"fa fa-phone\"></i></td><td>"+ lang.call_number + "</td><td><span class=quickNumToDial>" + buddyObj.ContactNumber2 + "</span></td></tr>";
        }

        menu += "</table>";
        menu += "</div>";

        var consoleLogContent = "Menu click AudioCall("+ buddy +", ";

    } else if(buddyObj.type == "group") {

        var menu = "<div id=quickCallMenu>";
        menu += "<table id=quickCallTable cellspacing=10 cellpadding=0 style=\"margin-left:auto; margin-right: auto\">";
        menu += "<tr class=quickNumDialRow><td><i class=\"fa fa-users\"></i></td><td>"+ lang.call_group + "</td><td><span class=quickNumToDial>" + buddyObj.ExtNo + "</span></td></tr>";
        menu += "</table>";
        menu += "</div>";

        var consoleLogContent = "Menu click AudioCallGroup("+ buddy +", ";

    }

    $.jeegoopopup.open({
                html: menu,
                width: 'auto',
                height: 'auto',
                left: leftPos,
                top: topPos,
                scrolling: 'no',
                skinClass: 'jg_popup_basic',
                overlay: true,
                opacity: 0,
                draggable: false,
                resizable: false,
                fadeIn: 0
    });

    $("#quickCallTable").on("click", ".quickNumDialRow", function() {
       var NumberToDial = $(this).closest("tr").find("span.quickNumToDial").html();
       console.log(consoleLogContent + NumberToDial +")");
       DialByLine("audio", buddy, NumberToDial);
    });

    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); });
    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); } });
}
function AudioCall(lineObj, dialledNumber) {
    if(userAgent == null) return;
    if(userAgent.isRegistered() == false) return;
    if(lineObj == null) return;

    if(HasAudioDevice == false){
        Alert(lang.alert_no_microphone);
        return;
    }

    var supportedConstraints = navigator.mediaDevices.getSupportedConstraints();

    var spdOptions = {
        sessionDescriptionHandlerOptions: {
            constraints: {
                audio: { deviceId : "default" },
                video: false
            }
        }
    }
    // Configure Audio
    var currentAudioDevice = getAudioSrcID();
    if(currentAudioDevice != "default"){
        var confirmedAudioDevice = false;
        for (var i = 0; i < AudioinputDevices.length; ++i) {
            if(currentAudioDevice == AudioinputDevices[i].deviceId) {
                confirmedAudioDevice = true;
                break;
            }
        }
        if(confirmedAudioDevice) {
            spdOptions.sessionDescriptionHandlerOptions.constraints.audio.deviceId = { exact: currentAudioDevice }
        }
        else {
            console.warn("The audio device you used before is no longer available, default settings applied.");
            localDB.setItem("AudioSrcId", "default");
        }
    }
    // Add additional Constraints
    if(supportedConstraints.autoGainControl) {
        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.autoGainControl = AutoGainControl;
    }
    if(supportedConstraints.echoCancellation) {
        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.echoCancellation = EchoCancellation;
    }
    if(supportedConstraints.noiseSuppression) {
        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.noiseSuppression = NoiseSuppression;
    }

    $("#line-" + lineObj.LineNumber + "-msg").html(lang.starting_audio_call);
    $("#line-" + lineObj.LineNumber + "-timer").show();

    // Invite
    console.log("INVITE (audio): " + dialledNumber + "@" + wssServer);
    lineObj.SipSession = userAgent.invite("sip:" + dialledNumber + "@" + wssServer, spdOptions);

    var startTime = moment.utc();
    lineObj.SipSession.data.line = lineObj.LineNumber;
    lineObj.SipSession.data.buddyId = lineObj.BuddyObj.identity;
    lineObj.SipSession.data.calldirection = "outbound";
    lineObj.SipSession.data.dst = dialledNumber;
    lineObj.SipSession.data.callstart = startTime.format("YYYY-MM-DD HH:mm:ss UTC");
    lineObj.SipSession.data.callTimer = window.setInterval(function(){
        var now = moment.utc();
        var duration = moment.duration(now.diff(startTime)); 
        $("#line-" + lineObj.LineNumber + "-timer").html(formatShortDuration(duration.asSeconds()));
    }, 1000);
    lineObj.SipSession.data.VideoSourceDevice = null;
    lineObj.SipSession.data.AudioSourceDevice = getAudioSrcID();
    lineObj.SipSession.data.AudioOutputDevice = getAudioOutputID();
    lineObj.SipSession.data.terminateby = "them";
    lineObj.SipSession.data.withvideo = false;

    updateLineScroll(lineObj.LineNumber);

    // Do Necessary UI Wireup
    wireupAudioSession(lineObj);

    // Custom Web hook
    if(typeof web_hook_on_invite !== 'undefined') web_hook_on_invite(lineObj.SipSession);
}

// Sessions & During Call Activity
// ===============================
function getSession(buddy) {
    if(userAgent == null) {
        console.warn("userAgent is null");
        return;
    }
    if(userAgent.isRegistered() == false) {
        console.warn("userAgent is not registered");
        return;
    }

    var rtnSession = null;
    $.each(userAgent.sessions, function (i, session) {
        if(session.data.buddyId == buddy) {
           rtnSession = session;
           return false;
        }
    });
    return rtnSession;
}
function countSessions(id){
    var rtn = 0;
    if(userAgent == null) {
       console.warn("userAgent is null");
       return 0;
    }
    $.each(userAgent.sessions, function (i, session) {
        if(id != session.id) rtn ++;
    });
    return rtn;
}
function StartRecording(lineNum){
    if(CallRecordingPolicy == "disabled") {
        console.warn("Policy Disabled: Call Recording");
        return;
    }
    var lineObj = FindLineByNumber(lineNum);
    if(lineObj == null) return;

    $("#line-"+ lineObj.LineNumber +"-btn-start-recording").hide();
    $("#line-"+ lineObj.LineNumber +"-btn-stop-recording").show();

    var session = lineObj.SipSession;
    if(session == null){
        console.warn("Could not find session");
        return;
    }

    var id = uID();

    if(!session.data.recordings) session.data.recordings = [];
    session.data.recordings.push({
        uID: id,
        startTime: utcDateNow(),
        stopTime: utcDateNow(),
    });

    if(!session.data.mediaRecorder){
        console.log("Creating call recorder...");
        var recordStream = new MediaStream();
        var pc = session.sessionDescriptionHandler.peerConnection;
        pc.getSenders().forEach(function (RTCRtpSender) {
            if(RTCRtpSender.track && RTCRtpSender.track.kind == "audio") {
                console.log("Adding sender audio track to record:", RTCRtpSender.track.label);
                recordStream.addTrack(RTCRtpSender.track);
            }
        });
        pc.getReceivers().forEach(function (RTCRtpReceiver) {
            if(RTCRtpReceiver.track && RTCRtpReceiver.track.kind == "audio") {
                console.log("Adding receiver audio track to record:", RTCRtpReceiver.track.label);
                recordStream.addTrack(RTCRtpReceiver.track);
            }
            if(session.data.withvideo){
                if(RTCRtpReceiver.track && RTCRtpReceiver.track.kind == "video") {
                    console.log("Adding receiver video track to record:", RTCRtpReceiver.track.label);
                    recordStream.addTrack(RTCRtpReceiver.track);
                }
            }
        });

        // Resample the Video Recording
        if(session.data.withvideo){
            var recordingWidth = 640;
            var recordingHeight = 360;
            var pnpVideSize = 100;
            if(RecordingVideoSize == "HD"){
                recordingWidth = 1280;
                recordingHeight = 720;
                pnpVideSize = 144;
            }
            if(RecordingVideoSize == "FHD"){
                recordingWidth = 1920;
                recordingHeight = 1080;
                pnpVideSize = 240;
            }

            // them-pnp
            var pnpVideo = $("#line-" + lineObj.LineNumber + "-localVideo").get(0);
            var mainVideo = $("#line-" + lineObj.LineNumber + "-remoteVideo").get(0);
            if(RecordingLayout == "us-pnp"){
                pnpVideo = $("#line-" + lineObj.LineNumber + "-remoteVideo").get(0);
                mainVideo = $("#line-" + lineObj.LineNumber + "-localVideo").get(0);
            }
            var recordingCanvas = $('<canvas/>').get(0);
            recordingCanvas.width = (RecordingLayout == "side-by-side")? (recordingWidth * 2) + 5: recordingWidth;
            recordingCanvas.height = recordingHeight;
            var recordingContext = recordingCanvas.getContext("2d");

            window.clearInterval(session.data.recordingRedrawInterval);
            session.data.recordingRedrawInterval = window.setInterval(function(){

                // Main Video
                var videoWidth = (mainVideo.videoWidth > 0)? mainVideo.videoWidth : recordingWidth ;
                var videoHeight = (mainVideo.videoHeight > 0)? mainVideo.videoHeight : recordingHeight ;

                if(videoWidth >= videoHeight){
                    // Landscape / Square
                    var scale = recordingWidth / videoWidth;
                    videoWidth = recordingWidth;
                    videoHeight = videoHeight * scale;
                    if(videoHeight > recordingHeight){
                        var scale = recordingHeight / videoHeight;
                        videoHeight = recordingHeight;
                        videoWidth = videoWidth * scale;
                    }
                } 
                else {
                    // Portrait
                    var scale = recordingHeight / videoHeight;
                    videoHeight = recordingHeight;
                    videoWidth = videoWidth * scale;
                }
                var offsetX = (videoWidth < recordingWidth)? (recordingWidth - videoWidth) / 2 : 0;
                var offsetY = (videoHeight < recordingHeight)? (recordingHeight - videoHeight) / 2 : 0;
                if(RecordingLayout == "side-by-side") offsetX = recordingWidth + 5 + offsetX;

                // Picture-in-Picture Video
                var pnpVideoHeight = pnpVideo.videoHeight;
                var pnpVideoWidth = pnpVideo.videoWidth;
                if(pnpVideoHeight > 0){
                    if(pnpVideoWidth >= pnpVideoHeight){
                        var scale = pnpVideSize / pnpVideoHeight;
                        pnpVideoHeight = pnpVideSize;
                        pnpVideoWidth = pnpVideoWidth * scale;
                    } 
                    else{
                        var scale = pnpVideSize / pnpVideoWidth;
                        pnpVideoWidth = pnpVideSize;
                        pnpVideoHeight = pnpVideoHeight * scale;
                    }
                }
                var pnpOffsetX = 10;
                var pnpOffsetY = 10;
                if(RecordingLayout == "side-by-side"){
                    pnpVideoWidth = pnpVideo.videoWidth;
                    pnpVideoHeight = pnpVideo.videoHeight;
                    if(pnpVideoWidth >= pnpVideoHeight){
                        // Landscape / Square
                        var scale = recordingWidth / pnpVideoWidth;
                        pnpVideoWidth = recordingWidth;
                        pnpVideoHeight = pnpVideoHeight * scale;
                        if(pnpVideoHeight > recordingHeight){
                            var scale = recordingHeight / pnpVideoHeight;
                            pnpVideoHeight = recordingHeight;
                            pnpVideoWidth = pnpVideoWidth * scale;
                        }
                    } 
                    else {
                        // Portrait
                        var scale = recordingHeight / pnpVideoHeight;
                        pnpVideoHeight = recordingHeight;
                        pnpVideoWidth = pnpVideoWidth * scale;
                    }
                    pnpOffsetX = (pnpVideoWidth < recordingWidth)? (recordingWidth - pnpVideoWidth) / 2 : 0;
                    pnpOffsetY = (pnpVideoHeight < recordingHeight)? (recordingHeight - pnpVideoHeight) / 2 : 0;
                }

                // Draw Elements
                recordingContext.fillRect(0, 0, recordingCanvas.width, recordingCanvas.height);
                if(mainVideo.videoHeight > 0){
                    recordingContext.drawImage(mainVideo, offsetX, offsetY, videoWidth, videoHeight);
                }
                if(pnpVideo.videoHeight > 0 && (RecordingLayout == "side-by-side" || RecordingLayout == "us-pnp" || RecordingLayout == "them-pnp")){
                    // Only Draw the Pnp Video when needed
                    recordingContext.drawImage(pnpVideo, pnpOffsetX, pnpOffsetY, pnpVideoWidth, pnpVideoHeight);
                }
            }, Math.floor(1000/RecordingVideoFps));
            var recordingVideoMediaStream = recordingCanvas.captureStream(RecordingVideoFps);
        }

        var mixedAudioVideoRecordStream = new MediaStream();
        mixedAudioVideoRecordStream.addTrack(MixAudioStreams(recordStream).getAudioTracks()[0]);
        if(session.data.withvideo){
           mixedAudioVideoRecordStream.addTrack(recordingVideoMediaStream.getVideoTracks()[0]);
        }

        var mediaType = "audio/webm";
        if(session.data.withvideo) mediaType = "video/webm";
        var options = {
            mimeType : mediaType
        }
        var mediaRecorder = new MediaRecorder(mixedAudioVideoRecordStream, options);
        mediaRecorder.data = {}
        mediaRecorder.data.id = ""+ id;
        mediaRecorder.data.sessionId = ""+ session.id;
        mediaRecorder.data.buddyId = ""+ lineObj.BuddyObj.identity;
        mediaRecorder.ondataavailable = function(event) {
            console.log("Got Call Recording Data: ", event.data.size +"Bytes", this.data.id, this.data.buddyId, this.data.sessionId);
            // Save the Audio/Video file
            SaveCallRecording(event.data, this.data.id, this.data.buddyId, this.data.sessionId);
        }

        console.log("Starting Call Recording", id);
        session.data.mediaRecorder = mediaRecorder;
        session.data.mediaRecorder.start(); // Safari does not support timeslice
        session.data.recordings[session.data.recordings.length-1].startTime = utcDateNow();

        $("#line-" + lineObj.LineNumber + "-msg").html(lang.call_recording_started);

        updateLineScroll(lineNum);
    }
    else if(session.data.mediaRecorder.state == "inactive") {
        session.data.mediaRecorder.data = {}
        session.data.mediaRecorder.data.id = ""+ id;
        session.data.mediaRecorder.data.sessionId = ""+ session.id;
        session.data.mediaRecorder.data.buddyId = ""+ lineObj.BuddyObj.identity;

        console.log("Starting Call Recording", id);
        session.data.mediaRecorder.start();
        session.data.recordings[session.data.recordings.length-1].startTime = utcDateNow();

        $("#line-" + lineObj.LineNumber + "-msg").html(lang.call_recording_started);

        updateLineScroll(lineNum);
    } 
    else {
        console.warn("Recorder is in an unknown state");
    }
}
function SaveCallRecording(blob, id, buddy, sessionid){
    var indexedDB = window.indexedDB;
    var request = indexedDB.open("CallRecordings");
    request.onerror = function(event) {
        console.error("IndexDB Request Error:", event);
    }
    request.onupgradeneeded = function(event) {
        console.warn("Upgrade Required for IndexDB... probably because of first time use.");
        var IDB = event.target.result;

        // Create Object Store
        if(IDB.objectStoreNames.contains("Recordings") == false){
            var objectStore = IDB.createObjectStore("Recordings", { keyPath: "uID" });
            objectStore.createIndex("sessionid", "sessionid", { unique: false });
            objectStore.createIndex("bytes", "bytes", { unique: false });
            objectStore.createIndex("type", "type", { unique: false });
            objectStore.createIndex("mediaBlob", "mediaBlob", { unique: false });
        }
        else {
            console.warn("IndexDB requested upgrade, but object store was in place");
        }
    }
    request.onsuccess = function(event) {
        console.log("IndexDB connected to CallRecordings");

        var IDB = event.target.result;
        if(IDB.objectStoreNames.contains("Recordings") == false){
            console.warn("IndexDB CallRecordings.Recordings does not exists");
            return;
        }
        IDB.onerror = function(event) {
            console.error("IndexDB Error:", event);
        }
    
        // Prepare data to write
        var data = {
            uID: id,
            sessionid: sessionid,
            bytes: blob.size,
            type: blob.type,
            mediaBlob: blob
        }
        // Commit Transaction
        var transaction = IDB.transaction(["Recordings"], "readwrite");
        var objectStoreAdd = transaction.objectStore("Recordings").add(data);
        objectStoreAdd.onsuccess = function(event) {
            console.log("Call Recording Sucess: ", id, blob.size, blob.type, buddy, sessionid);
        }
    }
}
function StopRecording(lineNum, noConfirm){
    var lineObj = FindLineByNumber(lineNum);
    if(lineObj == null || lineObj.SipSession == null) return;

    var session = lineObj.SipSession;
    if(noConfirm == true){
        // Called at the end of a call
        $("#line-"+ lineObj.LineNumber +"-btn-start-recording").show();
        $("#line-"+ lineObj.LineNumber +"-btn-stop-recording").hide();

        if(session.data.mediaRecorder){
            if(session.data.mediaRecorder.state == "recording"){
                console.log("Stopping Call Recording");
                session.data.mediaRecorder.stop();
                session.data.recordings[session.data.recordings.length-1].stopTime = utcDateNow();
                window.clearInterval(session.data.recordingRedrawInterval);

                $("#line-" + lineObj.LineNumber + "-msg").html(lang.call_recording_stopped);

                updateLineScroll(lineNum);
            } 
            else{
                console.warn("Recorder is in an unknow state");
            }
        }
        return;
    } 
    else {
        // User attempts to end call recording
        if(CallRecordingPolicy == "enabled"){
            console.log("Policy Enabled: Call Recording");
        }

        Confirm(lang.confirm_stop_recording, lang.stop_recording, function(){
            $("#line-"+ lineObj.LineNumber +"-btn-start-recording").show();
            $("#line-"+ lineObj.LineNumber +"-btn-stop-recording").hide();
    
            if(session.data.mediaRecorder){
                if(session.data.mediaRecorder.state == "recording"){
                    console.log("Stopping Call Recording");
                    session.data.mediaRecorder.stop();
                    session.data.recordings[session.data.recordings.length-1].stopTime = utcDateNow();
                    window.clearInterval(session.data.recordingRedrawInterval);

                    $("#line-" + lineObj.LineNumber + "-msg").html(lang.call_recording_stopped);

                    updateLineScroll(lineNum);
                }
                else{
                    console.warn("Recorder is in an unknow state");
                }
            }
        });
    }
}
function PlayAudioCallRecording(obj, cdrId, uID){
    var container = $(obj).parent();
    container.empty();

    var audioObj = new Audio();
    audioObj.autoplay = false;
    audioObj.controls = true;

    // Make sure you are playing out via the correct device
    var sinkId = getAudioOutputID();
    if (typeof audioObj.sinkId !== 'undefined') {
        audioObj.setSinkId(sinkId).then(function(){
            console.log("sinkId applied: "+ sinkId);
        }).catch(function(e){
            console.warn("Error using setSinkId: ", e);
        });
    } else {
        console.warn("setSinkId() is not possible using this browser.")
    }

    container.append(audioObj);

    // Get Call Recording
    var indexedDB = window.indexedDB;
    var request = indexedDB.open("CallRecordings");
    request.onerror = function(event) {
        console.error("IndexDB Request Error:", event);
    }
    request.onupgradeneeded = function(event) {
        console.warn("Upgrade Required for IndexDB... probably because of first time use.");
    }
    request.onsuccess = function(event) {
        console.log("IndexDB connected to CallRecordings");

        var IDB = event.target.result;
        if(IDB.objectStoreNames.contains("Recordings") == false){
            console.warn("IndexDB CallRecordings.Recordings does not exists");
            return;
        } 

        var transaction = IDB.transaction(["Recordings"]);
        var objectStoreGet = transaction.objectStore("Recordings").get(uID);
        objectStoreGet.onerror = function(event) {
            console.error("IndexDB Get Error:", event);
        }
        objectStoreGet.onsuccess = function(event) {
            $("#cdr-media-meta-size-"+ cdrId +"-"+ uID).html(" Size: "+ formatBytes(event.target.result.bytes));
            $("#cdr-media-meta-codec-"+ cdrId +"-"+ uID).html(" Codec: "+ event.target.result.type);

            // Play
            audioObj.src = window.URL.createObjectURL(event.target.result.mediaBlob);
            audioObj.oncanplaythrough = function(){
                audioObj.play().then(function(){
                    console.log("Playback started");
                }).catch(function(e){
                    console.error("Error playing back file: ", e);
                });
            }
        }
    }
}
function PlayVideoCallRecording(obj, cdrId, uID, buddy){
    var container = $(obj).parent();
    container.empty();

    var videoObj = $("<video>").get(0);
    videoObj.id = "callrecording-video-"+ cdrId;
    videoObj.autoplay = false;
    videoObj.controls = true;
    videoObj.ontimeupdate = function(event){
        $("#cdr-video-meta-width-"+ cdrId +"-"+ uID).html(lang.width + " : "+ event.target.videoWidth +"px");
        $("#cdr-video-meta-height-"+ cdrId +"-"+ uID).html(lang.height +" : "+ event.target.videoHeight +"px");
    }

    var sinkId = getAudioOutputID();
    if (typeof videoObj.sinkId !== 'undefined') {
        videoObj.setSinkId(sinkId).then(function(){
            console.log("sinkId applied: "+ sinkId);
        }).catch(function(e){
            console.warn("Error using setSinkId: ", e);
        });
    } else {
        console.warn("setSinkId() is not possible using this browser.")
    }

    container.append(videoObj);

    // Get Call Recording
    var indexedDB = window.indexedDB;
    var request = indexedDB.open("CallRecordings");
    request.onerror = function(event) {
        console.error("IndexDB Request Error:", event);
    }
    request.onupgradeneeded = function(event) {
        console.warn("Upgrade Required for IndexDB... probably because of first time use.");
    }
    request.onsuccess = function(event) {
        console.log("IndexDB connected to CallRecordings");

        var IDB = event.target.result;
        if(IDB.objectStoreNames.contains("Recordings") == false){
            console.warn("IndexDB CallRecordings.Recordings does not exists");
            return;
        } 

        var transaction = IDB.transaction(["Recordings"]);
        var objectStoreGet = transaction.objectStore("Recordings").get(uID);
        objectStoreGet.onerror = function(event) {
            console.error("IndexDB Get Error:", event);
        }
        objectStoreGet.onsuccess = function(event) {
            $("#cdr-media-meta-size-"+ cdrId +"-"+ uID).html(" Size: "+ formatBytes(event.target.result.bytes));
            $("#cdr-media-meta-codec-"+ cdrId +"-"+ uID).html(" Codec: "+ event.target.result.type);

            // Play
            videoObj.src = window.URL.createObjectURL(event.target.result.mediaBlob);
            videoObj.oncanplaythrough = function(){
                try{
                    videoObj.scrollIntoViewIfNeeded(false);
                } catch(e){}
                videoObj.play().then(function(){
                    console.log("Playback started");
                }).catch(function(e){
                    console.error("Error playing back file: ", e);
                });

                // Create a Post Image after a second
                if(buddy){
                    window.setTimeout(function(){
                        var canvas = $("<canvas>").get(0);
                        var videoWidth = videoObj.videoWidth;
                        var videoHeight = videoObj.videoHeight;
                        if(videoWidth > videoHeight){
                            // Landscape
                            if(videoHeight > 225){
                                var p = 225 / videoHeight;
                                videoHeight = 225;
                                videoWidth = videoWidth * p;
                            }
                        }
                        else {
                            // Portrait
                            if(videoHeight > 225){
                                var p = 225 / videoWidth;
                                videoWidth = 225;
                                videoHeight = videoHeight * p;
                            }
                        }
                        canvas.width = videoWidth;
                        canvas.height = videoHeight;
                        canvas.getContext('2d').drawImage(videoObj, 0, 0, videoWidth, videoHeight);  
                        canvas.toBlob(function(blob) {
                            var reader = new FileReader();
                            reader.readAsDataURL(blob);
                            reader.onloadend = function() {
                                var Poster = { width: videoWidth, height: videoHeight, posterBase64: reader.result }
                                console.log("Capturing Video Poster...");
    
                                // Update DB
                                var currentStream = JSON.parse(localDB.getItem(buddy + "-stream"));
                                if(currentStream != null || currentStream.DataCollection != null){
                                    $.each(currentStream.DataCollection, function(i, item) {
                                        if (item.ItemType == "CDR" && item.CdrId == cdrId) {
                                            // Found
                                            if(item.Recordings && item.Recordings.length >= 1){
                                                $.each(item.Recordings, function(r, recording) {
                                                    if(recording.uID == uID) recording.Poster = Poster;
                                                });
                                            }
                                            return false;
                                        }
                                    });
                                    localDB.setItem(buddy + "-stream", JSON.stringify(currentStream));
                                    console.log("Capturing Video Poster, Done");
                                }
                            }
                        }, 'image/jpeg', PosterJpegQuality);
                    }, 1000);
                }
            }
        }
    }
}

// Stream Manipulations
// ====================
function MixAudioStreams(MultiAudioTackStream){
    // Takes in a MediaStream with any number of audio tracks and mixes them together

    var audioContext = null;
    try {
        window.AudioContext = window.AudioContext || window.webkitAudioContext;
        audioContext = new AudioContext();
    }
    catch(e){
        console.warn("AudioContext() not available, cannot record");
        return MultiAudioTackStream;
    }
    var mixedAudioStream = audioContext.createMediaStreamDestination();
    MultiAudioTackStream.getAudioTracks().forEach(function(audioTrack){
        var srcStream = new MediaStream();
        srcStream.addTrack(audioTrack);
        var streamSourceNode = audioContext.createMediaStreamSource(srcStream);
        streamSourceNode.connect(mixedAudioStream);
    });

    return mixedAudioStream.stream;
}

// Call Transfer & Conference
// ============================
function QuickFindBuddy(obj){

    $.jeegoopopup.close();

    var leftPos = obj.offsetWidth + 178;
    var topPos = obj.offsetHeight + 68;

    if($(window).width() < 1467) {
        topPos = obj.offsetHeight + 164;
        if ($(window).width() < 918) {
            leftPos = obj.offsetWidth - 140;
            if($(window).width() < 690) {
               leftPos = obj.offsetWidth - 70;
               topPos = obj.offsetHeight + 164;
            }
        }
    }

    var filter = obj.value;
    if(filter == "") return;

    console.log("Find Buddy: ", filter);

    Buddies.sort(function(a, b){
        if(a.CallerIDName < b.CallerIDName) return -1;
        if(a.CallerIDName > b.CallerIDName) return 1;
        return 0;
    });

    var visibleItems = 0;

    var menu = "<div id=\"quickSearchBuddy\">";
    menu += "<table id=\"quickSearchBdTable\" cellspacing=10 cellpadding=0 style=\"margin-left:auto; margin-right: auto\">";

    for(var b = 0; b < Buddies.length; b++){
        var buddyObj = Buddies[b];

        // Perform Filter Display
        var display = false;
        if(buddyObj.CallerIDName.toLowerCase().indexOf(filter.toLowerCase()) > -1) display = true;
        if(buddyObj.ExtNo.toLowerCase().indexOf(filter.toLowerCase()) > -1) display = true;
        if(buddyObj.Desc.toLowerCase().indexOf(filter.toLowerCase()) > -1) display = true;
        if(buddyObj.MobileNumber.toLowerCase().indexOf(filter.toLowerCase()) > -1) display = true;
        if(buddyObj.ContactNumber1.toLowerCase().indexOf(filter.toLowerCase()) > -1) display = true;
        if(buddyObj.ContactNumber2.toLowerCase().indexOf(filter.toLowerCase()) > -1) display = true;
        if(display) {
            // Filtered Results
            var iconColor = "#404040";
            if(buddyObj.presence == "Unknown" || buddyObj.presence == "Not online" || buddyObj.presence == "Unavailable") iconColor = "#666666";
            if(buddyObj.presence == "Ready") iconColor = "#3fbd3f";
            if(buddyObj.presence == "On the phone" || buddyObj.presence == "Ringing" || buddyObj.presence == "On hold") iconColor = "#c99606";

            menu += "<tr class=\"quickFindBdTagRow\"><td></td><td><b>"+ buddyObj.CallerIDName +"</b></td><td></td></tr>";

            if (buddyObj.ExtNo != "") {
                menu += "<tr class=\"quickFindBdRow\"><td><i class=\"fa fa-phone-square\" style=\"color:"+ iconColor +"\"></i></td><td>"+ lang.extension +" ("+ buddyObj.presence + ")" +"</td><td><span class=\"quickNumFound\">"+ buddyObj.ExtNo +"</span></td></tr>";
            }
            if (buddyObj.MobileNumber != "") {
                menu += "<tr class=\"quickFindBdRow\"><td><i class=\"fa fa-mobile\"></i></td><td>"+ lang.mobile +"</td><td><span class=\"quickNumFound\">"+ buddyObj.MobileNumber +"</span></td></tr>";
            }

            if (buddyObj.ContactNumber1 != "") {
                menu += "<tr class=\"quickFindBdRow\"><td><i class=\"fa fa-phone\"></i></td><td>"+ lang.contact_number_1 +"</td><td><span class=\"quickNumFound\">"+ buddyObj.ContactNumber1 +"</span></td></tr>";
            }
            if (buddyObj.ContactNumber2 != "") {
                menu += "<tr class=\"quickFindBdRow\"><td><i class=\"fa fa-phone\"></i></td><td>"+ lang.contact_number_2 +"</td><td><span class=\"quickNumFound\">"+ buddyObj.ContactNumber2 +"</span></td></tr>";
            }

            visibleItems++;
        }
        if(visibleItems >= 5) break;
    }

    menu += "</table></div>";

    if(menu.length > 1) {
       $.jeegoopopup.open({
                html: menu,
                width: 'auto',
                height: 'auto',
                left: leftPos,
                top: topPos,
                scrolling: 'no',
                skinClass: 'jg_popup_basic',
                overlay: true,
                opacity: 0,
                draggable: false,
                resizable: false,
                fadeIn: 0
       });

       $("#jg_popup_inner").focus();
       $("#jg_popup_inner #jg_popup_content #quickSearchBuddy #quickSearchBdTable").on("click", ".quickFindBdRow", function() {

          var quickFoundNum = $(this).closest("tr").find("span.quickNumFound").html();

          $.jeegoopopup.close();
          $(document).find("input[id*='-txt-FindTransferBuddy']").focus();
          $(document).find("input[id*='-txt-FindTransferBuddy']").val(quickFoundNum);
       });

       $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); });
       $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); } });
    }
}

// Call Transfer
// =============
function StartTransferSession(lineNum){
    $("#line-"+ lineNum +"-btn-Transfer").hide();
    $("#line-"+ lineNum +"-btn-CancelTransfer").show();

    holdSession(lineNum);
    $("#line-"+ lineNum +"-txt-FindTransferBuddy").val("");
    $("#line-"+ lineNum +"-txt-FindTransferBuddy").parent().show();

    $("#line-"+ lineNum +"-btn-blind-transfer").show();
    $("#line-"+ lineNum +"-btn-attended-transfer").show();
    $("#line-"+ lineNum +"-btn-complete-transfer").hide();
    $("#line-"+ lineNum +"-btn-cancel-transfer").hide();

    $("#line-"+ lineNum +"-transfer-status").hide();

    $("#line-"+ lineNum +"-Transfer").show();

    updateLineScroll(lineNum);
}
function CancelTransferSession(lineNum){
    var lineObj = FindLineByNumber(lineNum);
    if(lineObj == null || lineObj.SipSession == null){
        console.warn("Null line or session");
        return;
    }
    var session = lineObj.SipSession;
    if(session.data.childsession){
        console.log("Child Transfer call detected:", session.data.childsession.status)
        try{
            if(session.data.childsession.status == SIP.Session.C.STATUS_CONFIRMED){
                session.data.childsession.bye();
            } 
            else{
                session.data.childsession.cancel();
            }
        } catch(e){}
    }

    $("#line-"+ lineNum +"-btn-Transfer").show();
    $("#line-"+ lineNum +"-btn-CancelTransfer").hide();

    unholdSession(lineNum);
    $("#line-"+ lineNum +"-Transfer").hide();

    updateLineScroll(lineNum);
}
function BlindTransfer(lineNum) {
    var dstNo = $("#line-"+ lineNum +"-txt-FindTransferBuddy").val().replace(/[^0-9\*\#\+]/g,'');
    if(dstNo == ""){
        console.warn("Cannot transfer, must be [0-9*+#]");
        return;
    }

    var lineObj = FindLineByNumber(lineNum);
    if(lineObj == null || lineObj.SipSession == null){
        console.warn("Null line or session");
        return;
    }
    var session = lineObj.SipSession;

    if(!session.data.transfer) session.data.transfer = [];
    session.data.transfer.push({ 
        type: "Blind", 
        to: dstNo, 
        transferTime: utcDateNow(), 
        disposition: "refer",
        dispositionTime: utcDateNow(), 
        accept : {
            complete: null,
            eventTime: null,
            disposition: ""
        }
    });
    var transferid = session.data.transfer.length-1;

    var transferOptions  = { 
        receiveResponse: function doReceiveResponse(response){
            console.log("Blind transfer response: ", response.reason_phrase);

            session.data.terminateby = "refer";
            session.data.transfer[transferid].accept.disposition = response.reason_phrase;
            session.data.transfer[transferid].accept.eventTime = utcDateNow();

            $("#line-" + lineNum + "-msg").html("Call Blind Transfered (Accepted)");

            updateLineScroll(lineNum);
        }
    }
    console.log("REFER: ", dstNo + "@" + wssServer);
    session.refer("sip:" + dstNo + "@" + wssServer, transferOptions);
    $("#line-" + lineNum + "-msg").html(lang.call_blind_transfered);

    updateLineScroll(lineNum);
}
function AttendedTransfer(lineNum){
    var dstNo = $("#line-"+ lineNum +"-txt-FindTransferBuddy").val().replace(/[^0-9\*\#\+]/g,'');
    if(dstNo == ""){
        console.warn("Cannot transfer, must be [0-9*+#]");
        return;
    }
    
    var lineObj = FindLineByNumber(lineNum);
    if(lineObj == null || lineObj.SipSession == null){
        console.warn("Null line or session");
        return;
    }
    var session = lineObj.SipSession;

    $.jeegoopopup.close();

    $("#line-"+ lineNum +"-txt-FindTransferBuddy").parent().hide();
    $("#line-"+ lineNum +"-btn-blind-transfer").hide();
    $("#line-"+ lineNum +"-btn-attended-transfer").hide();

    $("#line-"+ lineNum +"-btn-complete-attended-transfer").hide();
    $("#line-"+ lineNum +"-btn-cancel-attended-transfer").hide();
    $("#line-"+ lineNum +"-btn-terminate-attended-transfer").hide();

    var newCallStatus = $("#line-"+ lineNum +"-transfer-status");
    newCallStatus.html(lang.connecting);
    newCallStatus.show();

    if(!session.data.transfer) session.data.transfer = [];
    session.data.transfer.push({ 
        type: "Attended", 
        to: dstNo, 
        transferTime: utcDateNow(), 
        disposition: "invite",
        dispositionTime: utcDateNow(), 
        accept : {
            complete: null,
            eventTime: null,
            disposition: ""
        }
    });
    var transferid = session.data.transfer.length-1;

    updateLineScroll(lineNum);

    // SDP options
    var supportedConstraints = navigator.mediaDevices.getSupportedConstraints();
    var spdOptions = {
        sessionDescriptionHandlerOptions: {
            constraints: {
                audio: { deviceId : "default" },
                video: false
            }
        }
    }
    if(session.data.AudioSourceDevice != "default"){
        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.deviceId = { exact: session.data.AudioSourceDevice }
    }
    // Add additional Constraints
    if(supportedConstraints.autoGainControl) {
        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.autoGainControl = AutoGainControl;
    }
    if(supportedConstraints.echoCancellation) {
        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.echoCancellation = EchoCancellation;
    }
    if(supportedConstraints.noiseSuppression) {
        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.noiseSuppression = NoiseSuppression;
    }

    if(session.data.withvideo){
        spdOptions.sessionDescriptionHandlerOptions.constraints.video = true;
        if(session.data.VideoSourceDevice != "default"){
            spdOptions.sessionDescriptionHandlerOptions.constraints.video.deviceId = { exact: session.data.VideoSourceDevice }
        }
        // Add additional Constraints
        if(supportedConstraints.frameRate && maxFrameRate != "") {
            spdOptions.sessionDescriptionHandlerOptions.constraints.video.frameRate = maxFrameRate;
        }
        if(supportedConstraints.height && videoHeight != "") {
            spdOptions.sessionDescriptionHandlerOptions.constraints.video.height = videoHeight;
        }
        if(supportedConstraints.aspectRatio && videoAspectRatio != "") {
            spdOptions.sessionDescriptionHandlerOptions.constraints.video.aspectRatio = videoAspectRatio;
        }
    }

    // Create new call session
    console.log("INVITE: ", "sip:" + dstNo + "@" + wssServer);
    var newSession = userAgent.invite("sip:" + dstNo + "@" + wssServer, spdOptions);
    session.data.childsession = newSession;
    newSession.on('progress', function (response) {
        newCallStatus.html(lang.ringing);
        session.data.transfer[transferid].disposition = "progress";
        session.data.transfer[transferid].dispositionTime = utcDateNow();

        $("#line-" + lineNum + "-msg").html(lang.attended_transfer_call_started);
        
        var CancelAttendedTransferBtn = $("#line-"+ lineNum +"-btn-cancel-attended-transfer");
        CancelAttendedTransferBtn.off('click');
        CancelAttendedTransferBtn.on('click', function(){
            newSession.cancel();
            newCallStatus.html(lang.call_cancelled);
            console.log("New call session canceled");

            session.data.transfer[transferid].accept.complete = false;
            session.data.transfer[transferid].accept.disposition = "cancel";
            session.data.transfer[transferid].accept.eventTime = utcDateNow();

            $("#line-" + lineNum + "-msg").html(lang.attended_transfer_call_cancelled);

            updateLineScroll(lineNum);
        });
        CancelAttendedTransferBtn.show();

        updateLineScroll(lineNum);
    });
    newSession.on('accepted', function (response) {
        newCallStatus.html(lang.call_in_progress);
        $("#line-"+ lineNum +"-btn-cancel-attended-transfer").hide();
        session.data.transfer[transferid].disposition = "accepted";
        session.data.transfer[transferid].dispositionTime = utcDateNow();

        var CompleteTransferBtn = $("#line-"+ lineNum +"-btn-complete-attended-transfer");
        CompleteTransferBtn.off('click');
        CompleteTransferBtn.on('click', function(){
            var transferOptions  = { 
                receiveResponse: function doReceiveResponse(response){
                    console.log("Attended transfer response: ", response.reason_phrase);

                    session.data.terminateby = "refer";
                    session.data.transfer[transferid].accept.disposition = response.reason_phrase;
                    session.data.transfer[transferid].accept.eventTime = utcDateNow();

                    $("#line-" + lineNum + "-msg").html(lang.attended_transfer_complete_accepted);

                    updateLineScroll(lineNum);
                }
            }

            // Send REFER
            session.refer(newSession, transferOptions);

            newCallStatus.html(lang.attended_transfer_complete);
            console.log("Attended transfer complete");
            // Call will now teardown...

            session.data.transfer[transferid].accept.complete = true;
            session.data.transfer[transferid].accept.disposition = "refer";
            session.data.transfer[transferid].accept.eventTime = utcDateNow();

            $("#line-" + lineNum + "-msg").html(lang.attended_transfer_complete);

            updateLineScroll(lineNum);
        });
        CompleteTransferBtn.show();

        updateLineScroll(lineNum);

        var TerminateAttendedTransferBtn = $("#line-"+ lineNum +"-btn-terminate-attended-transfer");
        TerminateAttendedTransferBtn.off('click');
        TerminateAttendedTransferBtn.on('click', function(){
            newSession.bye();
            newCallStatus.html(lang.call_ended);
            console.log("New call session end");

            session.data.transfer[transferid].accept.complete = false;
            session.data.transfer[transferid].accept.disposition = "bye";
            session.data.transfer[transferid].accept.eventTime = utcDateNow();

            $("#line-" + lineNum + "-msg").html(lang.attended_transfer_call_ended);

            updateLineScroll(lineNum);
        });
        TerminateAttendedTransferBtn.show();

        updateLineScroll(lineNum);
    });
    newSession.on('trackAdded', function () {
        var pc = newSession.sessionDescriptionHandler.peerConnection;

        // Gets Remote Audio Track (Local audio is setup via initial GUM)
        var remoteStream = new MediaStream();
        pc.getReceivers().forEach(function (receiver) {
            if(receiver.track && receiver.track.kind == "audio"){
                remoteStream.addTrack(receiver.track);
            }
        });
        var remoteAudio = $("#line-" + lineNum + "-transfer-remoteAudio").get(0);
        remoteAudio.srcObject = remoteStream;
        remoteAudio.onloadedmetadata = function(e) {
            if (typeof remoteAudio.sinkId !== 'undefined') {
                remoteAudio.setSinkId(session.data.AudioOutputDevice).then(function(){
                    console.log("sinkId applied: "+ session.data.AudioOutputDevice);
                }).catch(function(e){
                    console.warn("Error using setSinkId: ", e);
                });            
            }
            remoteAudio.play();
        }
    });
    newSession.on('rejected', function (response, cause) {
        console.log("New call session rejected: ", cause);
        newCallStatus.html(lang.call_rejected);
        session.data.transfer[transferid].disposition = "rejected";
        session.data.transfer[transferid].dispositionTime = utcDateNow();

        $("#line-"+ lineNum +"-txt-FindTransferBuddy").parent().show();
        $("#line-"+ lineNum +"-btn-blind-transfer").show();
        $("#line-"+ lineNum +"-btn-attended-transfer").show();

        $("#line-"+ lineNum +"-btn-complete-attended-transfer").hide();
        $("#line-"+ lineNum +"-btn-cancel-attended-transfer").hide();
        $("#line-"+ lineNum +"-btn-terminate-attended-transfer").hide();

        $("#line-"+ lineNum +"-msg").html(lang.attended_transfer_call_rejected);

        updateLineScroll(lineNum);

        window.setTimeout(function(){
            newCallStatus.hide();
            updateLineScroll(lineNum);
        }, 1000);
    });
    newSession.on('terminated', function (response, cause) {
        console.log("New call session terminated: ", cause);
        newCallStatus.html(lang.call_ended);
        session.data.transfer[transferid].disposition = "terminated";
        session.data.transfer[transferid].dispositionTime = utcDateNow();

        $("#line-"+ lineNum +"-txt-FindTransferBuddy").parent().show();
        $("#line-"+ lineNum +"-btn-blind-transfer").show();
        $("#line-"+ lineNum +"-btn-attended-transfer").show();

        $("#line-"+ lineNum +"-btn-complete-attended-transfer").hide();
        $("#line-"+ lineNum +"-btn-cancel-attended-transfer").hide();
        $("#line-"+ lineNum +"-btn-terminate-attended-transfer").hide();

        $("#line-"+ lineNum +"-msg").html(lang.attended_transfer_call_terminated);

        updateLineScroll(lineNum);

        window.setTimeout(function(){
            newCallStatus.hide();
            updateLineScroll(lineNum);
        }, 1000);
    });
}

// Conference Calls
// ================
function StartConferenceCall(lineNum){
    $("#line-"+ lineNum +"-btn-Conference").hide();
    $("#line-"+ lineNum +"-btn-CancelConference").show();

    holdSession(lineNum);
    $("#line-"+ lineNum +"-txt-FindConferenceBuddy").val("");
    $("#line-"+ lineNum +"-txt-FindConferenceBuddy").parent().show();

    $("#line-"+ lineNum +"-btn-conference-dial").show();
    $("#line-"+ lineNum +"-btn-cancel-conference-dial").hide();
    $("#line-"+ lineNum +"-btn-join-conference-call").hide();
    $("#line-"+ lineNum +"-btn-terminate-conference-call").hide();

    $("#line-"+ lineNum +"-conference-status").hide();

    $("#line-"+ lineNum +"-Conference").show();

    updateLineScroll(lineNum);
}
function CancelConference(lineNum){
    var lineObj = FindLineByNumber(lineNum);
    if(lineObj == null || lineObj.SipSession == null){
        console.warn("Null line or session");
        return;
    }
    var session = lineObj.SipSession;
    if(session.data.childsession){
        try{
            if(session.data.childsession.status == SIP.Session.C.STATUS_CONFIRMED){
                session.data.childsession.bye();
            } 
            else{
                session.data.childsession.cancel();
            }
        } catch(e){}
    }

    $("#line-"+ lineNum +"-btn-Conference").show();
    $("#line-"+ lineNum +"-btn-CancelConference").hide();

    unholdSession(lineNum);
    $("#line-"+ lineNum +"-Conference").hide();

    updateLineScroll(lineNum);
}
function ConferenceDial(lineNum){
    var dstNo = $("#line-"+ lineNum +"-txt-FindConferenceBuddy").val().replace(/[^0-9\*\#\+]/g,'');
    if(dstNo == ""){
        console.warn("Cannot transfer, must be [0-9*+#]");
        return;
    }
    
    var lineObj = FindLineByNumber(lineNum);
    if(lineObj == null || lineObj.SipSession == null){
        console.warn("Null line or session");
        return;
    }
    var session = lineObj.SipSession;

    $.jeegoopopup.close();

    $("#line-"+ lineNum +"-txt-FindConferenceBuddy").parent().hide();

    $("#line-"+ lineNum +"-btn-conference-dial").hide();
    $("#line-"+ lineNum +"-btn-cancel-conference-dial")
    $("#line-"+ lineNum +"-btn-join-conference-call").hide();
    $("#line-"+ lineNum +"-btn-terminate-conference-call").hide();

    var newCallStatus = $("#line-"+ lineNum +"-conference-status");
    newCallStatus.html(lang.connecting);
    newCallStatus.show();

    if(!session.data.confcalls) session.data.confcalls = [];
    session.data.confcalls.push({ 
        to: dstNo, 
        startTime: utcDateNow(), 
        disposition: "invite",
        dispositionTime: utcDateNow(), 
        accept : {
            complete: null,
            eventTime: null,
            disposition: ""
        }
    });
    var confcallid = session.data.confcalls.length-1;

    updateLineScroll(lineNum);

    // SDP options
    var supportedConstraints = navigator.mediaDevices.getSupportedConstraints();
    var spdOptions = {
        sessionDescriptionHandlerOptions: {
            constraints: {
                audio: { deviceId : "default" },
                video: false
            }
        }
    }
    if(session.data.AudioSourceDevice != "default"){
        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.deviceId = { exact: session.data.AudioSourceDevice }
    }
    // Add additional Constraints
    if(supportedConstraints.autoGainControl) {
        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.autoGainControl = AutoGainControl;
    }
    if(supportedConstraints.echoCancellation) {
        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.echoCancellation = EchoCancellation;
    }
    if(supportedConstraints.noiseSuppression) {
        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.noiseSuppression = NoiseSuppression;
    }

    // Unlikely this will work
    if(session.data.withvideo){
        spdOptions.sessionDescriptionHandlerOptions.constraints.video = true;
        if(session.data.VideoSourceDevice != "default"){
            spdOptions.sessionDescriptionHandlerOptions.constraints.video.deviceId = { exact: session.data.VideoSourceDevice }
        }
        // Add additional Constraints
        if(supportedConstraints.frameRate && maxFrameRate != "") {
            spdOptions.sessionDescriptionHandlerOptions.constraints.video.frameRate = maxFrameRate;
        }
        if(supportedConstraints.height && videoHeight != "") {
            spdOptions.sessionDescriptionHandlerOptions.constraints.video.height = videoHeight;
        }
        if(supportedConstraints.aspectRatio && videoAspectRatio != "") {
            spdOptions.sessionDescriptionHandlerOptions.constraints.video.aspectRatio = videoAspectRatio;
        }
    }

    // Create new call session
    console.log("INVITE: ", "sip:" + dstNo + "@" + wssServer);
    var newSession = userAgent.invite("sip:" + dstNo + "@" + wssServer, spdOptions);
    session.data.childsession = newSession;
    newSession.on('progress', function (response) {
        newCallStatus.html(lang.ringing);
        session.data.confcalls[confcallid].disposition = "progress";
        session.data.confcalls[confcallid].dispositionTime = utcDateNow();

        $("#line-" + lineNum + "-msg").html(lang.conference_call_started);

        var CancelConferenceDialBtn = $("#line-"+ lineNum +"-btn-cancel-conference-dial");
        CancelConferenceDialBtn.off('click');
        CancelConferenceDialBtn.on('click', function(){
            newSession.cancel();
            newCallStatus.html(lang.call_cancelled);
            console.log("New call session canceled");

            session.data.confcalls[confcallid].accept.complete = false;
            session.data.confcalls[confcallid].accept.disposition = "cancel";
            session.data.confcalls[confcallid].accept.eventTime = utcDateNow();

            $("#line-" + lineNum + "-msg").html(lang.canference_call_cancelled);

            updateLineScroll(lineNum);
        });
        CancelConferenceDialBtn.show();

        updateLineScroll(lineNum);
    });
    newSession.on('accepted', function (response) {
        newCallStatus.html(lang.call_in_progress);
        $("#line-"+ lineNum +"-btn-cancel-conference-dial").hide();
        session.data.confcalls[confcallid].complete = true;
        session.data.confcalls[confcallid].disposition = "accepted";
        session.data.confcalls[confcallid].dispositionTime = utcDateNow();

        // Join Call
        var JoinCallBtn = $("#line-"+ lineNum +"-btn-join-conference-call");
        JoinCallBtn.off('click');
        JoinCallBtn.on('click', function(){
            // Merge Call Audio
            if(!session.data.childsession){
                console.warn("Conference session lost");
                return;
            }

            var outputStreamForSession = new MediaStream();
            var outputStreamForConfSession = new MediaStream();

            var pc = session.sessionDescriptionHandler.peerConnection;
            var confPc = session.data.childsession.sessionDescriptionHandler.peerConnection;

            // Get conf call input channel
            confPc.getReceivers().forEach(function (RTCRtpReceiver) {
                if(RTCRtpReceiver.track && RTCRtpReceiver.track.kind == "audio") {
                    console.log("Adding conference session:", RTCRtpReceiver.track.label);
                    outputStreamForSession.addTrack(RTCRtpReceiver.track);
                }
            });

            // Get session input channel
            pc.getReceivers().forEach(function (RTCRtpReceiver) {
                if(RTCRtpReceiver.track && RTCRtpReceiver.track.kind == "audio") {
                    console.log("Adding conference session:", RTCRtpReceiver.track.label);
                    outputStreamForConfSession.addTrack(RTCRtpReceiver.track);
                }
            });

            // Replace tracks of Parent Call
            pc.getSenders().forEach(function (RTCRtpSender) {
                if(RTCRtpSender.track && RTCRtpSender.track.kind == "audio") {
                    console.log("Switching to mixed Audio track on session");

                    session.data.AudioSourceTrack = RTCRtpSender.track;
                    outputStreamForSession.addTrack(RTCRtpSender.track);
                    var mixedAudioTrack = MixAudioStreams(outputStreamForSession).getAudioTracks()[0];
                    mixedAudioTrack.IsMixedTrack = true;

                    RTCRtpSender.replaceTrack(mixedAudioTrack);
                }
            });
            // Replace tracks of Child Call
            confPc.getSenders().forEach(function (RTCRtpSender) {
                if(RTCRtpSender.track && RTCRtpSender.track.kind == "audio") {
                    console.log("Switching to mixed Audio track on conf call");

                    session.data.childsession.data.AudioSourceTrack = RTCRtpSender.track;
                    outputStreamForConfSession.addTrack(RTCRtpSender.track);
                    var mixedAudioTrackForConf = MixAudioStreams(outputStreamForConfSession).getAudioTracks()[0];
                    mixedAudioTrackForConf.IsMixedTrack = true;

                    RTCRtpSender.replaceTrack(mixedAudioTrackForConf);
                }
            });

            newCallStatus.html(lang.call_in_progress);
            console.log("Conference Call In Progress");

            session.data.confcalls[confcallid].accept.complete = true;
            session.data.confcalls[confcallid].accept.disposition = "join";
            session.data.confcalls[confcallid].accept.eventTime = utcDateNow();

            $("#line-"+ lineNum +"-btn-terminate-conference-call").show();

            $("#line-" + lineNum + "-msg").html(lang.conference_call_in_progress);

            // Take the parent call off hold
            unholdSession(lineNum);

            JoinCallBtn.hide();

            updateLineScroll(lineNum);
        });
        JoinCallBtn.show();

        updateLineScroll(lineNum);

        // End Call
        var TerminateAttendedTransferBtn = $("#line-"+ lineNum +"-btn-terminate-conference-call");
        TerminateAttendedTransferBtn.off('click');
        TerminateAttendedTransferBtn.on('click', function(){
            newSession.bye();
            newCallStatus.html(lang.call_ended);
            console.log("New call session end");

            session.data.confcalls[confcallid].accept.disposition = "bye";
            session.data.confcalls[confcallid].accept.eventTime = utcDateNow();

            $("#line-" + lineNum + "-msg").html(lang.conference_call_ended);

            updateLineScroll(lineNum);
        });
        TerminateAttendedTransferBtn.show();

        updateLineScroll(lineNum);
    });
    newSession.on('trackAdded', function () {

        var pc = newSession.sessionDescriptionHandler.peerConnection;

        // Gets Remote Audio Track (Local audio is setup via initial GUM)
        var remoteStream = new MediaStream();
        pc.getReceivers().forEach(function (receiver) {
            if(receiver.track && receiver.track.kind == "audio"){
                remoteStream.addTrack(receiver.track);
            }
        });
        var remoteAudio = $("#line-" + lineNum + "-conference-remoteAudio").get(0);
        remoteAudio.srcObject = remoteStream;
        remoteAudio.onloadedmetadata = function(e) {
            if (typeof remoteAudio.sinkId !== 'undefined') {
                remoteAudio.setSinkId(session.data.AudioOutputDevice).then(function(){
                    console.log("sinkId applied: "+ session.data.AudioOutputDevice);
                }).catch(function(e){
                    console.warn("Error using setSinkId: ", e);
                });
            }
            remoteAudio.play();
        }
    });
    newSession.on('rejected', function (response, cause) {
        console.log("New call session rejected: ", cause);
        newCallStatus.html(lang.call_rejected);
        session.data.confcalls[confcallid].disposition = "rejected";
        session.data.confcalls[confcallid].dispositionTime = utcDateNow();

        $("#line-"+ lineNum +"-txt-FindConferenceBuddy").parent().show();
        $("#line-"+ lineNum +"-btn-conference-dial").show();

        $("#line-"+ lineNum +"-btn-cancel-conference-dial").hide();
        $("#line-"+ lineNum +"-btn-join-conference-call").hide();
        $("#line-"+ lineNum +"-btn-terminate-conference-call").hide();

        $("#line-"+ lineNum +"-msg").html(lang.conference_call_rejected);

        updateLineScroll(lineNum);

        window.setTimeout(function(){
            newCallStatus.hide();
            updateLineScroll(lineNum);
        }, 1000);
    });
    newSession.on('terminated', function (response, cause) {
        console.log("New call session terminated: ", cause);
        newCallStatus.html(lang.call_ended);
        session.data.confcalls[confcallid].disposition = "terminated";
        session.data.confcalls[confcallid].dispositionTime = utcDateNow();

        // Ends the mixed audio, and releases the mic
        if(session.data.childsession.data.AudioSourceTrack && session.data.childsession.data.AudioSourceTrack.kind == "audio"){
            session.data.childsession.data.AudioSourceTrack.stop();
        }
        // Restore Audio Stream if it was changed
        if(session.data.AudioSourceTrack && session.data.AudioSourceTrack.kind == "audio"){
            var pc = session.sessionDescriptionHandler.peerConnection;
            pc.getSenders().forEach(function (RTCRtpSender) {
                if(RTCRtpSender.track && RTCRtpSender.track.kind == "audio") {
                    RTCRtpSender.replaceTrack(session.data.AudioSourceTrack).then(function(){
                        if(session.data.ismute){
                            RTCRtpSender.track.enabled = false;
                        }
                    }).catch(function(){
                        console.error(e);
                    });
                    session.data.AudioSourceTrack = null;
                }
            });
        }
        $("#line-"+ lineNum +"-txt-FindConferenceBuddy").parent().show();
        $("#line-"+ lineNum +"-btn-conference-dial").show();

        $("#line-"+ lineNum +"-btn-cancel-conference-dial").hide();
        $("#line-"+ lineNum +"-btn-join-conference-call").hide();
        $("#line-"+ lineNum +"-btn-terminate-conference-call").hide();

        $("#line-"+ lineNum +"-msg").html(lang.conference_call_terminated);

        updateLineScroll(lineNum);

        window.setTimeout(function(){
            newCallStatus.hide();
            updateLineScroll(lineNum);
        }, 1000);
    });
}


function cancelSession(lineNum) {
    var lineObj = FindLineByNumber(lineNum);
    if(lineObj == null || lineObj.SipSession == null) return;

    lineObj.SipSession.data.terminateby = "us";

    console.log("Cancelling session : "+ lineNum);
    lineObj.SipSession.cancel();

    $("#line-" + lineNum + "-msg").html(lang.call_cancelled);
}
function holdSession(lineNum) {
    var lineObj = FindLineByNumber(lineNum);
    if(lineObj == null || lineObj.SipSession == null) return;

    console.log("Putting Call on hold: "+ lineNum);
    if(lineObj.SipSession.local_hold == false){
        lineObj.SipSession.hold();
    }
    // Log Hold
    if(!lineObj.SipSession.data.hold) lineObj.SipSession.data.hold = [];
    lineObj.SipSession.data.hold.push({ event: "hold", eventTime: utcDateNow() });

    $("#line-" + lineNum + "-btn-Hold").hide();
    $("#line-" + lineNum + "-btn-Unhold").show();
    $("#line-" + lineNum + "-msg").html(lang.call_on_hold);

    updateLineScroll(lineNum);
}
function unholdSession(lineNum) {
    var lineObj = FindLineByNumber(lineNum);
    if(lineObj == null || lineObj.SipSession == null) return;

    console.log("Taking call off hold: "+ lineNum);
    if(lineObj.SipSession.local_hold == true){
        lineObj.SipSession.unhold();
    }
    // Log Hold
    if(!lineObj.SipSession.data.hold) lineObj.SipSession.data.hold = [];
    lineObj.SipSession.data.hold.push({ event: "unhold", eventTime: utcDateNow() });

    $("#line-" + lineNum + "-msg").html(lang.call_in_progress);
    $("#line-" + lineNum + "-btn-Hold").show();
    $("#line-" + lineNum + "-btn-Unhold").hide();

    updateLineScroll(lineNum);
}
function endSession(lineNum) {
    var lineObj = FindLineByNumber(lineNum);
    if(lineObj == null || lineObj.SipSession == null) return;

    console.log("Ending call with: "+ lineNum);
    lineObj.SipSession.data.terminateby = "us";
    lineObj.SipSession.bye();

    $("#line-" + lineNum + "-msg").html(lang.call_ended);
    $("#line-" + lineNum + "-ActiveCall").hide();

    updateLineScroll(lineNum);
}
function sendDTMF(lineNum, itemStr) {
    var lineObj = FindLineByNumber(lineNum);
    if(lineObj == null || lineObj.SipSession == null) return;

    console.log("Sending DTMF ("+ itemStr +"): "+ lineNum);
    lineObj.SipSession.dtmf(itemStr);

    $("#line-" + lineNum + "-msg").html(lang.send_dtmf + ": "+ itemStr);

    updateLineScroll(lineNum);

    // Custom Web hook
    if(typeof web_hook_on_dtmf !== 'undefined') web_hook_on_dtmf(itemStr, lineObj.SipSession);
}
function switchVideoSource(lineNum, srcId){
    var lineObj = FindLineByNumber(lineNum);
    if(lineObj == null || lineObj.SipSession == null){
        console.warn("Line or Session is Null");
        return;
    }
    var session = lineObj.SipSession;

    $("#line-" + lineNum + "-msg").html(lang.switching_video_source);

    var supportedConstraints = navigator.mediaDevices.getSupportedConstraints();
    var constraints = { 
        audio: false, 
        video: { deviceId: "default" }
    }
    if(srcId != "default"){
        constraints.video.deviceId = { exact: srcId }
    }

    // Add additional Constraints
    if(supportedConstraints.frameRate && maxFrameRate != "") {
        constraints.video.frameRate = maxFrameRate;
    }
    if(supportedConstraints.height && videoHeight != "") {
        constraints.video.height = videoHeight;
    }
    if(supportedConstraints.aspectRatio && videoAspectRatio != "") {
        constraints.video.aspectRatio = videoAspectRatio;
    }

    session.data.VideoSourceDevice = srcId;

    var pc = session.sessionDescriptionHandler.peerConnection;

    var localStream = new MediaStream();
    navigator.mediaDevices.getUserMedia(constraints).then(function(newStream){
        var newMediaTrack = newStream.getVideoTracks()[0];
        pc.getSenders().forEach(function (RTCRtpSender) {
            if(RTCRtpSender.track && RTCRtpSender.track.kind == "video") {
                console.log("Switching Video Track : "+ RTCRtpSender.track.label + " to "+ newMediaTrack.label);
                RTCRtpSender.track.stop();
                RTCRtpSender.replaceTrack(newMediaTrack);
                localStream.addTrack(newMediaTrack);
            }
        });
    }).catch(function(e){
        console.error("Error on getUserMedia", e, constraints);
    });

    // Restore Audio Stream is it was changed
    if(session.data.AudioSourceTrack && session.data.AudioSourceTrack.kind == "audio"){
        pc.getSenders().forEach(function (RTCRtpSender) {
            if(RTCRtpSender.track && RTCRtpSender.track.kind == "audio") {
                RTCRtpSender.replaceTrack(session.data.AudioSourceTrack).then(function(){
                    if(session.data.ismute){
                        RTCRtpSender.track.enabled = false;
                    }
                }).catch(function(){
                    console.error(e);
                });
                session.data.AudioSourceTrack = null;
            }
        });
    }

    // Set Preview
    console.log("Showing as preview...");
    var localVideo = $("#line-" + lineNum + "-localVideo").get(0);
    localVideo.srcObject = localStream;
    localVideo.onloadedmetadata = function(e) {
        localVideo.play();
    }
}
function SendCanvas(lineNum){
    var lineObj = FindLineByNumber(lineNum);
    if(lineObj == null || lineObj.SipSession == null){
        console.warn("Line or Session is Null");
        return;
    }
    var session = lineObj.SipSession;

    $("#line-" + lineNum + "-msg").html(lang.switching_to_canvas);

    // Create scratch Pad
    RemoveScratchpad(lineNum);

    var newCanvas = $('<canvas/>');
    newCanvas.prop("id", "line-" + lineNum + "-scratchpad");
    $("#line-" + lineNum + "-scratchpad-container").append(newCanvas);
    $("#line-" + lineNum + "-scratchpad").css("display", "inline-block");
    $("#line-" + lineNum + "-scratchpad").css("width", "640px"); // SD
    $("#line-" + lineNum + "-scratchpad").css("height", "360px"); // SD
    $("#line-" + lineNum + "-scratchpad").prop("width", 640); // SD
    $("#line-" + lineNum + "-scratchpad").prop("height", 360); // SD
    $("#line-" + lineNum + "-scratchpad-container").show();

    console.log("Canvas for Scratchpad created...");

    scratchpad = new fabric.Canvas("line-" + lineNum + "-scratchpad");
    scratchpad.id = "line-" + lineNum + "-scratchpad";
    scratchpad.backgroundColor = "#FFFFFF";
    scratchpad.isDrawingMode = true;
    scratchpad.renderAll();
    scratchpad.redrawIntrtval = window.setInterval(function(){
        scratchpad.renderAll();
    }, 1000);

    CanvasCollection.push(scratchpad);

    // Get The Canvas Stream
    var canvasMediaStream = $("#line-"+ lineNum +"-scratchpad").get(0).captureStream(25);
    var canvasMediaTrack = canvasMediaStream.getVideoTracks()[0];

    // Switch Tracks
    var pc = session.sessionDescriptionHandler.peerConnection;
    pc.getSenders().forEach(function (RTCRtpSender) {
        if(RTCRtpSender.track && RTCRtpSender.track.kind == "video") {
            console.log("Switching Track : "+ RTCRtpSender.track.label + " to Scratchpad Canvas");
            RTCRtpSender.track.stop();
            RTCRtpSender.replaceTrack(canvasMediaTrack);
        }
    });

    // Restore Audio Stream if it was changed
    if(session.data.AudioSourceTrack && session.data.AudioSourceTrack.kind == "audio"){
        pc.getSenders().forEach(function (RTCRtpSender) {
            if(RTCRtpSender.track && RTCRtpSender.track.kind == "audio") {
                RTCRtpSender.replaceTrack(session.data.AudioSourceTrack).then(function(){
                    if(session.data.ismute){
                        RTCRtpSender.track.enabled = false;
                    }
                }).catch(function(){
                    console.error(e);
                });
                session.data.AudioSourceTrack = null;
            }
        });
    }

    // Set Preview
    // ===========
    console.log("Showing as preview...");
    var localVideo = $("#line-" + lineNum + "-localVideo").get(0);
    localVideo.srcObject = canvasMediaStream;
    localVideo.onloadedmetadata = function(e) {
        localVideo.play();
    }
}
function SendVideo(lineNum, src){
    var lineObj = FindLineByNumber(lineNum);
    if(lineObj == null || lineObj.SipSession == null){
        console.warn("Line or Session is Null");
        return;
    }
    var session = lineObj.SipSession;

    $("#line-"+ lineNum +"-src-camera").prop("disabled", false);
    $("#line-"+ lineNum +"-src-canvas").prop("disabled", false);
    $("#line-"+ lineNum +"-src-desktop").prop("disabled", false);
    $("#line-"+ lineNum +"-src-video").prop("disabled", true);
    $("#line-"+ lineNum +"-src-blank").prop("disabled", false);

    $("#line-" + lineNum + "-msg").html(lang.switching_to_shared_video);

    $("#line-" + lineNum + "-scratchpad-container").hide();
    RemoveScratchpad(lineNum);
    $("#line-"+ lineNum +"-sharevideo").hide();
    $("#line-"+ lineNum +"-sharevideo").get(0).pause();
    $("#line-"+ lineNum +"-sharevideo").get(0).removeAttribute('src');
    $("#line-"+ lineNum +"-sharevideo").get(0).load();

    $("#line-"+ lineNum +"-localVideo").hide();
    $("#line-"+ lineNum +"-remoteVideo").appendTo("#line-" + lineNum + "-preview-container");

    // Create Video Object
    var newVideo = $("#line-" + lineNum + "-sharevideo");
    newVideo.prop("src", src);
    newVideo.off("loadedmetadata");
    newVideo.on("loadedmetadata", function () {
        console.log("Video can play now... ");

        // Resample Video
        var ResampleSize = 360;
        if(VideoResampleSize == "HD") ResampleSize = 720;
        if(VideoResampleSize == "FHD") ResampleSize = 1080;

        var videoObj = newVideo.get(0);
        var resampleCanvas = $('<canvas/>').get(0);

        var videoWidth = videoObj.videoWidth;
        var videoHeight = videoObj.videoHeight;
        if(videoWidth >= videoHeight){
            // Landscape / Square
            if(videoHeight > ResampleSize){
                var p = ResampleSize / videoHeight;
                videoHeight = ResampleSize;
                videoWidth = videoWidth * p;
            }
        }
        else {
            // Portrate... (phone turned on its side)
            if(videoWidth > ResampleSize){
                var p = ResampleSize / videoWidth;
                videoWidth = ResampleSize;
                videoHeight = videoHeight * p;
            }
        }

        resampleCanvas.width = videoWidth;
        resampleCanvas.height = videoHeight;
        var resampleContext = resampleCanvas.getContext("2d");

        window.clearInterval(session.data.videoResampleInterval);
        session.data.videoResampleInterval = window.setInterval(function(){
            resampleContext.drawImage(videoObj, 0, 0, videoWidth, videoHeight);
        }, 40); // 25frames per second

        // Capture the streams
        var videoMediaStream = null;
        if('captureStream' in videoObj) {
            videoMediaStream = videoObj.captureStream();
        }
        else if('mozCaptureStream' in videoObj) {
            // This doesn't really work
            // see: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/captureStream
            videoMediaStream = videoObj.mozCaptureStream();
        }
        else {
            // This is not supported.
            // videoMediaStream = videoObj.webkitCaptureStream();
            console.warn("Cannot capture stream from video, this will result in no audio being transmitted.")
        }
        var resampleVideoMediaStream = resampleCanvas.captureStream(25);

        // Get the Tracks
        var videoMediaTrack = resampleVideoMediaStream.getVideoTracks()[0];

        var audioTrackFromVideo = (videoMediaStream != null )? videoMediaStream.getAudioTracks()[0] : null;

        // Switch & Merge Tracks
        var pc = session.sessionDescriptionHandler.peerConnection;
        pc.getSenders().forEach(function (RTCRtpSender) {
            if(RTCRtpSender.track && RTCRtpSender.track.kind == "video") {
                console.log("Switching Track : "+ RTCRtpSender.track.label);
                RTCRtpSender.track.stop();
                RTCRtpSender.replaceTrack(videoMediaTrack);
            }
            if(RTCRtpSender.track && RTCRtpSender.track.kind == "audio") {
                console.log("Switching to mixed Audio track on session");

                session.data.AudioSourceTrack = RTCRtpSender.track;

                var mixedAudioStream = new MediaStream();
                if(audioTrackFromVideo) mixedAudioStream.addTrack(audioTrackFromVideo);
                mixedAudioStream.addTrack(RTCRtpSender.track);
                var mixedAudioTrack = MixAudioStreams(mixedAudioStream).getAudioTracks()[0];
                mixedAudioTrack.IsMixedTrack = true;

                RTCRtpSender.replaceTrack(mixedAudioTrack);
            }
        });

        // Set Preview
        console.log("Showing as preview...");
        var localVideo = $("#line-" + lineNum + "-localVideo").get(0);
        localVideo.srcObject = videoMediaStream;
        localVideo.onloadedmetadata = function(e) {
            localVideo.play().then(function(){
                console.log("Playing Preview Video File");
            }).catch(function(e){
                console.error("Cannot play back video", e);
            });
        }
        // Play the video
        console.log("Starting Video...");
        $("#line-"+ lineNum +"-sharevideo").get(0).play();
    });

    $("#line-"+ lineNum +"-sharevideo").show();
    console.log("Video for Sharing created...");
}
function ShareScreen(lineNum){
    var lineObj = FindLineByNumber(lineNum);
    if(lineObj == null || lineObj.SipSession == null){
        console.warn("Line or Session is Null");
        return;
    }
    var session = lineObj.SipSession;

    $("#line-" + lineNum + "-msg").html(lang.switching_to_shared_screeen);

    var localStream = new MediaStream();
    var pc = session.sessionDescriptionHandler.peerConnection;

    if (navigator.getDisplayMedia) {
        // EDGE, legacy support
        var screenShareConstraints = { video: true, audio: false }
        navigator.getDisplayMedia(screenShareConstraints).then(function(newStream) {
            console.log("navigator.getDisplayMedia")
            var newMediaTrack = newStream.getVideoTracks()[0];
            pc.getSenders().forEach(function (RTCRtpSender) {
                if(RTCRtpSender.track && RTCRtpSender.track.kind == "video") {
                    console.log("Switching Video Track : "+ RTCRtpSender.track.label + " to Screen");
                    RTCRtpSender.track.stop();
                    RTCRtpSender.replaceTrack(newMediaTrack);
                    localStream.addTrack(newMediaTrack);
                }
            });

            // Set Preview
            // ===========
            console.log("Showing as preview...");
            var localVideo = $("#line-" + lineNum + "-localVideo").get(0);
            localVideo.srcObject = localStream;
            localVideo.onloadedmetadata = function(e) {
                localVideo.play();
            }
        }).catch(function (err) {
            console.error("Error on getUserMedia");
        });
    }
    else if (navigator.mediaDevices.getDisplayMedia) {
        // New standard
        var screenShareConstraints = { video: true, audio: false }
        navigator.mediaDevices.getDisplayMedia(screenShareConstraints).then(function(newStream) {
            console.log("navigator.mediaDevices.getDisplayMedia")
            var newMediaTrack = newStream.getVideoTracks()[0];
            pc.getSenders().forEach(function (RTCRtpSender) {
                if(RTCRtpSender.track && RTCRtpSender.track.kind == "video") {
                    console.log("Switching Video Track : "+ RTCRtpSender.track.label + " to Screen");
                    RTCRtpSender.track.stop();
                    RTCRtpSender.replaceTrack(newMediaTrack);
                    localStream.addTrack(newMediaTrack);
                }
            });

            // Set Preview
            // ===========
            console.log("Showing as preview...");
            var localVideo = $("#line-" + lineNum + "-localVideo").get(0);
            localVideo.srcObject = localStream;
            localVideo.onloadedmetadata = function(e) {
                localVideo.play();
            }
        }).catch(function (err) {
            console.error("Error on getUserMedia");
        });
    } 
    else {
        // Firefox, apparently
        var screenShareConstraints = { video: { mediaSource: 'screen' }, audio: false }
        navigator.mediaDevices.getUserMedia(screenShareConstraints).then(function(newStream) {
            console.log("navigator.mediaDevices.getUserMedia")
            var newMediaTrack = newStream.getVideoTracks()[0];
            pc.getSenders().forEach(function (RTCRtpSender) {
                if(RTCRtpSender.track && RTCRtpSender.track.kind == "video") {
                    console.log("Switching Video Track : "+ RTCRtpSender.track.label + " to Screen");
                    RTCRtpSender.track.stop();
                    RTCRtpSender.replaceTrack(newMediaTrack);
                    localStream.addTrack(newMediaTrack);
                }
            });

            // Set Preview
            console.log("Showing as preview...");
            var localVideo = $("#line-" + lineNum + "-localVideo").get(0);
            localVideo.srcObject = localStream;
            localVideo.onloadedmetadata = function(e) {
                localVideo.play();
            }
        }).catch(function (err) {
            console.error("Error on getUserMedia");
        });
    }

    // Restore Audio Stream if it was changed
    if(session.data.AudioSourceTrack && session.data.AudioSourceTrack.kind == "audio"){
        pc.getSenders().forEach(function (RTCRtpSender) {
            if(RTCRtpSender.track && RTCRtpSender.track.kind == "audio") {
                RTCRtpSender.replaceTrack(session.data.AudioSourceTrack).then(function(){
                    if(session.data.ismute){
                        RTCRtpSender.track.enabled = false;
                    }
                }).catch(function(){
                    console.error(e);
                });
                session.data.AudioSourceTrack = null;
            }
        });
    }

}
function DisableVideoStream(lineNum){
    var lineObj = FindLineByNumber(lineNum);
    if(lineObj == null || lineObj.SipSession == null){
        console.warn("Line or Session is Null");
        return;
    }
    var session = lineObj.SipSession;

    var pc = session.sessionDescriptionHandler.peerConnection;
    pc.getSenders().forEach(function (RTCRtpSender) {
        if(RTCRtpSender.track && RTCRtpSender.track.kind == "video") {
            console.log("Disable Video Track : "+ RTCRtpSender.track.label + "");
            RTCRtpSender.track.enabled = false; //stop();
        }
        if(RTCRtpSender.track && RTCRtpSender.track.kind == "audio") {
            if(session.data.AudioSourceTrack && session.data.AudioSourceTrack.kind == "audio"){
                RTCRtpSender.replaceTrack(session.data.AudioSourceTrack).then(function(){
                    if(session.data.ismute){
                        RTCRtpSender.track.enabled = false;
                    }
                }).catch(function(){
                    console.error(e);
                });
                session.data.AudioSourceTrack = null;
            }
        }
    });

    // Set Preview
    console.log("Showing as preview...");
    var localVideo = $("#line-" + lineNum + "-localVideo").get(0);
    localVideo.pause();
    localVideo.removeAttribute('src');
    localVideo.load();

    $("#line-" + lineNum + "-msg").html(lang.video_disabled);
}

// Phone Lines
// ===========
var Line = function(lineNumber, displayName, displayNumber, buddyObj){
    this.LineNumber = lineNumber;
    this.DisplayName = displayName;
    this.DisplayNumber = displayNumber;
    this.IsSelected = false;
    this.BuddyObj = buddyObj;
    this.SipSession = null;
    this.LocalSoundMeter = null;
    this.RemoteSoundMeter = null;
}
function ShowDial(obj){

    var leftPos = obj.offsetWidth + 104;
    var rightPos = 0;
    var topPos = obj.offsetHeight + 117;

    if ($(window).width() <= 915) {
        leftPos = event.pageX + obj.offsetWidth - 120;
        rightPos = 0;
        topPos = event.pageY + obj.offsetHeight - 11;
    }

    var html = "<div id=mainDialPad><div><input id=dialText class=dialTextInput oninput=\"handleDialInput(this, event)\" onkeydown=\"dialOnkeydown(event, this)\"></div>";
    html += "<table cellspacing=10 cellpadding=0 style=\"margin-left:auto; margin-right: auto\">";
    html += "<tr><td><button class=dtmfButtons onclick=\"KeyPress('1');new Audio('sounds/dtmf.mp3').play();\"><div>1</div><span>&nbsp;</span></button></td>"
    html += "<td><button class=dtmfButtons onclick=\"KeyPress('2');new Audio('sounds/dtmf.mp3').play();\"><div>2</div><span>ABC</span></button></td>"
    html += "<td><button class=dtmfButtons onclick=\"KeyPress('3');new Audio('sounds/dtmf.mp3').play();\"><div>3</div><span>DEF</span></button></td></tr>";
    html += "<tr><td><button class=dtmfButtons onclick=\"KeyPress('4');new Audio('sounds/dtmf.mp3').play();\"><div>4</div><span>GHI</span></button></td>"
    html += "<td><button class=dtmfButtons onclick=\"KeyPress('5');new Audio('sounds/dtmf.mp3').play();\"><div>5</div><span>JKL</span></button></td>"
    html += "<td><button class=dtmfButtons onclick=\"KeyPress('6');new Audio('sounds/dtmf.mp3').play();\"><div>6</div><span>MNO</span></button></td></tr>";
    html += "<tr><td><button class=dtmfButtons onclick=\"KeyPress('7');new Audio('sounds/dtmf.mp3').play();\"><div>7</div><span>PQRS</span></button></td>"
    html += "<td><button class=dtmfButtons onclick=\"KeyPress('8');new Audio('sounds/dtmf.mp3').play();\"><div>8</div><span>TUV</span></button></td>"
    html += "<td><button class=dtmfButtons onclick=\"KeyPress('9');new Audio('sounds/dtmf.mp3').play();\"><div>9</div><span>WXYZ</span></button></td></tr>";
    html += "<tr><td><button class=dtmfButtons onclick=\"KeyPress('*');new Audio('sounds/dtmf.mp3').play();\">*</button></td>"
    html += "<td><button class=dtmfButtons onclick=\"KeyPress('0');new Audio('sounds/dtmf.mp3').play();\">0</button></td>"
    html += "<td><button class=dtmfButtons onclick=\"KeyPress('#');new Audio('sounds/dtmf.mp3').play();\">#</button></td></tr>";
    html += "</table>";
    html += "<div style=\"text-align: center;\">";
    html += "<button class=\"roundButtons dialButtons\" id=dialAudio style=\"width:48px; height:48px;\" title=\""+ lang.audio_call  +"\" onclick=\"DialByLine('audio')\"><i class=\"fa fa-phone\"></i></button>";
    if(EnableVideoCalling){
        html += "<button class=\"roundButtons dialButtons\" id=dialVideo style=\"width:48px; height:48px; margin-left:20px\" title=\""+ lang.video_call +"\" onclick=\"DialByLine('video')\"><i class=\"fa fa-video-camera\"></i></button>";
    }
    html += "</div></div>";

    $.jeegoopopup.open({
                html: html,
                width: "auto",
                height: "auto",
                left: leftPos,
                right: rightPos,
                top: topPos,
                scrolling: 'no',
                skinClass: 'jg_popup_basic',
//                innerClass: 'showDialInner',
                overlay: true,
                opacity: 0,
                draggable: true,
                resizable: false,
                fadeIn: 0
    });

    $("#dialText").focus();

    if ($(window).width() <= 915) { $.jeegoopopup.right(6); } else { $.jeegoopopup.width('auto').height('auto').left(leftPos).top(topPos); }

    $("#jg_popup_overlay").click(function() { $("#jg_popup_b").empty(); $("#jg_popup_l").empty(); $("#windowCtrls").empty(); $.jeegoopopup.close(); });
    $(window).on('keydown', function(event) { if (event.key == "Escape") { $("#jg_popup_b").empty(); $("#jg_popup_l").empty(); $("#windowCtrls").empty(); $.jeegoopopup.close(); } });
}

function handleDialInput(obj, event){
    if(EnableAlphanumericDial){
        $("#dialText").val($("#dialText").val().replace(/[^\da-zA-Z\*\#\+]/g, "").substring(0,MaxDidLength));
    }
    else {
        $("#dialText").val($("#dialText").val().replace(/[^\d\*\#\+]/g, "").substring(0,MaxDidLength));
    }
    $("#dialVideo").prop('disabled', ($("#dialText").val().length >= DidLength));
}
function dialOnkeydown(event, obj, buddy) {
    var keycode = (event.keyCode ? event.keyCode : event.which);
    if (keycode == '13'){

        event.preventDefault();

        // Defaults to audio dial
        DialByLine('audio');

        $("#jg_popup_b").empty(); $("#jg_popup_l").empty(); $("#windowCtrls").empty(); $.jeegoopopup.close();

        return false;
    }
}
function KeyPress(num){
    $("#dialText").val(($("#dialText").val()+num).substring(0,MaxDidLength));
    $("#dialVideo").prop('disabled', ($("#dialText").val().length >= DidLength));
}
function DialByLine(type, buddy, numToDial, CallerID){
    $.jeegoopopup.close();
    if(userAgent == null || userAgent.isRegistered()==false){
        ConfigureExtensionWindow();
        return;
    }

    var numDial = (numToDial)? numToDial : $("#dialText").val();
    if(EnableAlphanumericDial){
        numDial = numDial.replace(/[^\da-zA-Z\*\#\+]/g, "").substring(0,MaxDidLength);
    }
    else {
        numDial = numDial.replace(/[^\d\*\#\+]/g, "").substring(0,MaxDidLength);
    }
    if(numDial.length == 0) {
        console.warn("Enter number to dial");
        return;
    }

    // Create a Buddy if one is not already existing
    var buddyObj = (buddy)? FindBuddyByIdentity(buddy) : FindBuddyByDid(numDial);
    if(buddyObj == null) {
        var buddyType = (numDial.length > DidLength)? "contact" : "extension";
        // Assumption but anyway: If the number starts with a * or # then its probably not a subscribable DID,
        // and is probably a feature code.
        if(buddyType.substring(0,1) == "*" || buddyType.substring(0,1) == "#") buddyType = "contact";
        buddyObj = MakeBuddy(buddyType, true, false, true, (CallerID)? CallerID : numDial, numDial);
    }

    // Create a Line
    newLineNumber = newLineNumber + 1;
    lineObj = new Line(newLineNumber, buddyObj.CallerIDName, numDial, buddyObj);
    Lines.push(lineObj);
    AddLineHtml(lineObj);
    SelectLine(newLineNumber);
    UpdateBuddyList();

    // Start Call Invite
    if(type == "audio"){
        AudioCall(lineObj, numDial);
    }
    else {
        VideoCall(lineObj, numDial);
    }

    try{
        $("#line-" + newLineNumber).get(0).scrollIntoViewIfNeeded();
    } catch(e){}
}
function SelectLine(lineNum){

    $("#roundcubeFrame").remove();

    var lineObj = FindLineByNumber(lineNum);
    if(lineObj == null) return;

    var displayLineNumber = 0;
    for(var l = 0; l < Lines.length; l++) {
        if(Lines[l].LineNumber == lineObj.LineNumber) displayLineNumber = l+1;
        if(Lines[l].IsSelected == true && Lines[l].LineNumber == lineObj.LineNumber){
            // Nothing to do, you re-selected the same buddy;
            return;
        }
    }

    console.log("Selecting Line : "+ lineObj.LineNumber);

    // Can only display one thing on the right
    $(".streamSelected").each(function () {
        $(this).prop('class', 'stream');
    });
    $("#line-ui-" + lineObj.LineNumber).prop('class', 'streamSelected');

    $("#line-ui-" + lineObj.LineNumber + "-DisplayLineNo").html("<i class=\"fa fa-phone\"></i> "+ lang.line +" "+ displayLineNumber);
    $("#line-ui-" + lineObj.LineNumber + "-LineIcon").html(displayLineNumber);

    // Switch the SIP Sessions
    SwitchLines(lineObj.LineNumber);

    // Update Lines List
    for(var l = 0; l < Lines.length; l++) {
        var classStr = (Lines[l].LineNumber == lineObj.LineNumber)? "buddySelected" : "buddy";
        if(Lines[l].SipSession != null) classStr = (Lines[l].SipSession.local_hold)? "buddyActiveCallHollding" : "buddyActiveCall";

        $("#line-" + Lines[l].LineNumber).prop('class', classStr);
        Lines[l].IsSelected = (Lines[l].LineNumber == lineObj.LineNumber);
    }
    // Update Buddy List
    for(var b = 0; b < Buddies.length; b++) {
        $("#contact-" + Buddies[b].identity).prop("class", "buddy");
        Buddies[b].IsSelected = false;
    }

    // Change to Stream if in Narrow view
    UpdateUI();
}
function FindLineByNumber(lineNum) {
    for(var l = 0; l < Lines.length; l++) {
        if(Lines[l].LineNumber == lineNum) return Lines[l];
    }
    return null;
}
function AddLineHtml(lineObj) {

    var html = "<table id=\"line-ui-"+ lineObj.LineNumber +"\" class=\"stream\" cellspacing=\"5\" cellpadding=\"0\">";
    html += "<tr><td class=streamSection>";

    // Close|Return|Back Button
    html += "<div style=\"float:left; margin:0px; padding:5px; height:38px; line-height:38px\">"
    html += "<button id=\"line-"+ lineObj.LineNumber +"-btn-back\" onclick=\"CloseLine('"+ lineObj.LineNumber +"')\" class=roundButtons title=\""+ lang.back +"\"><i class=\"fa fa-chevron-left\"></i></button> ";
    html += "</div>"

    // Profile UI
    html += "<div class=contact style=\"float: left;\">";
    html += "<div id=\"line-ui-"+ lineObj.LineNumber +"-LineIcon\" class=lineIcon>"+ lineObj.LineNumber +"</div>";
    html += "<div id=\"line-ui-"+ lineObj.LineNumber +"-DisplayLineNo\" class=contactNameText><i class=\"fa fa-phone\"></i> "+ lang.line +" "+ lineObj.LineNumber +"</div>";

    html += "<div class=presenceText>"+ lineObj.DisplayName +" <"+ lineObj.DisplayNumber +"></div>";
    html += "</div>";

    // Action Buttons
    html += "<div style=\"float:right; line-height: 46px;\">";
    html += "</div>";

    // Separator --------------------------------------------------------------------------
    html += "<div style=\"clear:both; height:0px\"></div>"

    // Calling UI --------------------------------------------------------------------------
    html += "<div id=\"line-"+ lineObj.LineNumber +"-calling\">";

    // Gneral Messages
    html += "<div id=\"line-"+ lineObj.LineNumber +"-timer\" style=\"float: right; margin-top: 4px; margin-right: 10px; color: #575757; display:none;\"></div>";
    html += "<div id=\"line-"+ lineObj.LineNumber +"-msg\" class=callStatus style=\"display:none\">...</div>";

    // Dialing Out Progress
    html += "<div id=\"line-"+ lineObj.LineNumber +"-progress\" style=\"display:none; margin-top: 10px\">";
    html += "<div class=progressCall>";
    html += "<button onclick=\"cancelSession('"+ lineObj.LineNumber +"')\" class=hangupButton><i class=\"fa fa-phone\"></i>&nbsp;&nbsp;"+ lang.cancel +"</button>";
    html += "</div>";
    html += "</div>";

    // Active Call UI
    html += "<div id=\"line-"+ lineObj.LineNumber +"-ActiveCall\" style=\"display:none; margin-top: 10px;\">";

    // Group Call
    html += "<div id=\"line-"+ lineObj.LineNumber +"-conference\" style=\"display:none;\"></div>";

    // Video UI
    if(lineObj.BuddyObj.type == "extension") {
        html += "<div id=\"line-"+ lineObj.LineNumber +"-VideoCall\" class=videoCall style=\"display:none;\">";

        // Presentation
        html += "<div style=\"height:35px; line-height:35px; text-align: right\">"+ lang.present +": ";
        html += "<div class=pill-nav style=\"border-color:#333333\">";
        html += "<button id=\"line-"+ lineObj.LineNumber +"-src-camera\" onclick=\"PresentCamera('"+ lineObj.LineNumber +"')\" title=\""+ lang.camera +"\" disabled><i class=\"fa fa-video-camera\"></i></button>";
        html += "<button id=\"line-"+ lineObj.LineNumber +"-src-canvas\" onclick=\"PresentScratchpad('"+ lineObj.LineNumber +"')\" title=\""+ lang.scratchpad +"\"><i class=\"fa fa-pencil-square\"></i></button>";
        html += "<button id=\"line-"+ lineObj.LineNumber +"-src-desktop\" onclick=\"PresentScreen('"+ lineObj.LineNumber +"')\" title=\""+ lang.screen +"\"><i class=\"fa fa-desktop\"></i></button>";
        html += "<button id=\"line-"+ lineObj.LineNumber +"-src-video\" onclick=\"PresentVideo('"+ lineObj.LineNumber +"')\" title=\""+ lang.video +"\"><i class=\"fa fa-file-video-o\"></i></button>";
        html += "<button id=\"line-"+ lineObj.LineNumber +"-src-blank\" onclick=\"PresentBlank('"+ lineObj.LineNumber +"')\" title=\""+ lang.blank +"\"><i class=\"fa fa-ban\"></i></button>";
        html += "</div>";
        html += "&nbsp;<button id=\"line-"+ lineObj.LineNumber +"-expand\" onclick=\"ExpandVideoArea('"+ lineObj.LineNumber +"')\"><i class=\"fa fa-expand\"></i></button>";
        html += "<button id=\"line-"+ lineObj.LineNumber +"-restore\" onclick=\"RestoreVideoArea('"+ lineObj.LineNumber +"')\" style=\"display:none\"><i class=\"fa fa-compress\"></i></button>";
        html += "</div>";

        // Preview
        html += "<div id=\"line-"+ lineObj.LineNumber +"-preview-container\" class=PreviewContainer>";
        html += "<video id=\"line-"+ lineObj.LineNumber +"-localVideo\" muted></video>"; // Default Display
        html += "</div>";

        // Stage
        html += "<div id=\"line-"+ lineObj.LineNumber +"-stage-container\" class=StageContainer>";
        html += "<video id=\"line-"+ lineObj.LineNumber +"-remoteVideo\" muted></video>"; // Default Display
        html += "<div id=\"line-"+ lineObj.LineNumber +"-scratchpad-container\" style=\"display:none\"></div>";
        html += "<video id=\"line-"+ lineObj.LineNumber +"-sharevideo\" controls muted style=\"display:none; object-fit: contain;\"></video>";
        html += "</div>";

        html += "</div>";
    }

    // Audio Call
    html += "<div id=\"line-"+ lineObj.LineNumber +"-AudioCall\" style=\"display:none;\">";
    html += "<audio id=\"line-"+ lineObj.LineNumber+"-remoteAudio\"></audio>";
    html += "</div>";

    // In Call Buttons
    html += "<div style=\"text-align:center\">";
    html += "<div style=\"margin-top:10px\">";
    html += "<button id=\"line-"+ lineObj.LineNumber +"-btn-ShowDtmf\" onclick=\"ShowDtmfMenu(this, '"+ lineObj.LineNumber +"')\" class=\"roundButtons inCallButtons\" title=\""+ lang.show_key_pad +"\"><i class=\"fa fa-keyboard-o\"></i></button>";
    html += "<button id=\"line-"+ lineObj.LineNumber +"-btn-Mute\" onclick=\"MuteSession('"+ lineObj.LineNumber +"')\" class=\"roundButtons inCallButtons\" title=\""+ lang.mute +"\"><i class=\"fa fa-microphone-slash\"></i></button>";
    html += "<button id=\"line-"+ lineObj.LineNumber +"-btn-Unmute\" onclick=\"UnmuteSession('"+ lineObj.LineNumber +"')\" class=\"roundButtons inCallButtons\" title=\""+ lang.unmute +"\" style=\"color: red; display:none\"><i class=\"fa fa-microphone\"></i></button>";
    if(typeof MediaRecorder != "undefined" && (CallRecordingPolicy == "allow" || CallRecordingPolicy == "enabled")){
        // Safari: must enable in Develop > Experimental Features > MediaRecorder
        html += "<button id=\"line-"+ lineObj.LineNumber +"-btn-start-recording\" onclick=\"StartRecording('"+ lineObj.LineNumber +"')\" class=\"roundButtons inCallButtons\" title=\""+ lang.start_call_recording +"\"><i class=\"fa fa-dot-circle-o\"></i></button>";
        html += "<button id=\"line-"+ lineObj.LineNumber +"-btn-stop-recording\" onclick=\"StopRecording('"+ lineObj.LineNumber +"')\" class=\"roundButtons inCallButtons\" title=\""+ lang.stop_call_recording +"\" style=\"color: red; display:none\"><i class=\"fa fa-circle\"></i></button>";
    }
    if(EnableTransfer){
        html += "<button id=\"line-"+ lineObj.LineNumber +"-btn-Transfer\" onclick=\"StartTransferSession('"+ lineObj.LineNumber +"')\" class=\"roundButtons inCallButtons\" title=\""+ lang.transfer_call +"\"><i class=\"fa fa-reply\" style=\"transform: rotateY(180deg)\"></i></button>";
        html += "<button id=\"line-"+ lineObj.LineNumber+"-btn-CancelTransfer\" onclick=\"CancelTransferSession('"+ lineObj.LineNumber +"')\" class=\"roundButtons inCallButtons\" title=\""+ lang.cancel_transfer +"\" style=\"color: red; display:none\"><i class=\"fa fa-reply\" style=\"transform: rotateY(180deg)\"></i></button>";
    }

    html += "<button id=\"line-"+ lineObj.LineNumber +"-btn-Hold\" onclick=\"holdSession('"+ lineObj.LineNumber +"')\" class=\"roundButtons inCallButtons\"  title=\""+ lang.hold_call +"\"><i class=\"fa fa-pause-circle\"></i></button>";
    html += "<button id=\"line-"+ lineObj.LineNumber +"-btn-Unhold\" onclick=\"unholdSession('"+ lineObj.LineNumber +"')\" class=\"roundButtons inCallButtons\" title=\""+ lang.resume_call +"\" style=\"color: red; display:none\"><i class=\"fa fa-play-circle\"></i></button>";
    html += "<button id=\"line-"+ lineObj.LineNumber +"-btn-End\" onclick=\"endSession('"+ lineObj.LineNumber +"')\" class=\"roundButtons inCallButtons hangupButton\" title=\""+ lang.end_call +"\"><i class=\"fa fa-phone\"></i></button>";
    html += "</div>";
    // Call Transfer
    html += "<div id=\"line-"+ lineObj.LineNumber +"-Transfer\" style=\"display:none\">";
    html += "<div style=\"margin-top:10px\">";
    html += "<span class=searchClean><input id=\"line-"+ lineObj.LineNumber +"-txt-FindTransferBuddy\" oninput=\"QuickFindBuddy(this,'"+ lineObj.LineNumber +"')\" type=text autocomplete=none style=\"width:150px;\" autocomplete=none placeholder=\""+ lang.search_or_enter_number +"\"></span>";
    html += " <button id=\"line-"+ lineObj.LineNumber +"-btn-blind-transfer\" onclick=\"BlindTransfer('"+ lineObj.LineNumber +"')\"><i class=\"fa fa-reply\" style=\"transform: rotateY(180deg)\"></i> "+ lang.blind_transfer +"</button>"
    html += " <button id=\"line-"+ lineObj.LineNumber +"-btn-attended-transfer\" onclick=\"AttendedTransfer('"+ lineObj.LineNumber +"')\"><i class=\"fa fa-reply-all\" style=\"transform: rotateY(180deg)\"></i> "+ lang.attended_transfer +"</button>";
    html += " <button id=\"line-"+ lineObj.LineNumber +"-btn-complete-attended-transfer\" style=\"display:none\"><i class=\"fa fa-reply-all\" style=\"transform: rotateY(180deg)\"></i> "+ lang.complete_transfer +"</buuton>";
    html += " <button id=\"line-"+ lineObj.LineNumber +"-btn-cancel-attended-transfer\" style=\"display:none\"><i class=\"fa fa-phone\" style=\"transform: rotate(135deg);\"></i> "+ lang.cancel_transfer +"</buuton>";
    html += " <button id=\"line-"+ lineObj.LineNumber +"-btn-terminate-attended-transfer\" style=\"display:none\"><i class=\"fa fa-phone\" style=\"transform: rotate(135deg);\"></i> "+ lang.end_transfer_call +"</buuton>";
    html += "</div>";
    html += "<div id=\"line-"+ lineObj.LineNumber +"-transfer-status\" class=callStatus style=\"margin-top:10px; display:none\">...</div>";
    html += "<audio id=\"line-"+ lineObj.LineNumber +"-transfer-remoteAudio\" style=\"display:none\"></audio>";
    html += "</div>";
    // Call Conference
    html += "<div id=\"line-"+ lineObj.LineNumber +"-Conference\" style=\"display:none\">";
    html += "<div style=\"margin-top:10px\">";
    html += "<span class=searchClean><input id=\"line-"+ lineObj.LineNumber +"-txt-FindConferenceBuddy\" oninput=\"QuickFindBuddy(this,'"+ lineObj.LineNumber +"')\" type=text autocomplete=none style=\"width:150px;\" autocomplete=none placeholder=\""+ lang.search_or_enter_number +"\"></span>";
    html += " <button id=\"line-"+ lineObj.LineNumber +"-btn-conference-dial\" onclick=\"ConferenceDial('"+ lineObj.LineNumber +"')\"><i class=\"fa fa-phone\"></i> "+ lang.call +"</button>";
    html += " <button id=\"line-"+ lineObj.LineNumber +"-btn-cancel-conference-dial\" style=\"display:none\"><i class=\"fa fa-phone\"></i> "+ lang.cancel_call +"</buuton>";
    html += " <button id=\"line-"+ lineObj.LineNumber +"-btn-join-conference-call\" style=\"display:none\"><i class=\"fa fa-users\"></i> "+ lang.join_conference_call +"</buuton>";
    html += " <button id=\"line-"+ lineObj.LineNumber +"-btn-terminate-conference-call\" style=\"display:none\"><i class=\"fa fa-phone\"></i> "+ lang.end_conference_call +"</buuton>";
    html += "</div>";
    html += "<div id=\"line-"+ lineObj.LineNumber +"-conference-status\" class=callStatus style=\"margin-top:10px; display:none\">...</div>";
    html += "<audio id=\"line-"+ lineObj.LineNumber +"-conference-remoteAudio\" style=\"display:none\"></audio>";
    html += "</div>";
    
    // Monitoring
    html += "<div  id=\"line-"+ lineObj.LineNumber +"-monitoring\" style=\"margin-top:10px;margin-bottom:10px;\">";
    html += "<span style=\"vertical-align: middle\"><i class=\"fa fa-microphone\"></i></span> ";
    html += "<span class=meterContainer title=\""+ lang.microphone_levels +"\">";
    html += "<span id=\"line-"+ lineObj.LineNumber +"-Mic\" class=meterLevel style=\"height:0%\"></span>";
    html += "</span> ";
    html += "<span style=\"vertical-align: middle\"><i class=\"fa fa-volume-up\"></i></span> ";
    html += "<span class=meterContainer title=\""+ lang.speaker_levels +"\">";
    html += "<span id=\"line-"+ lineObj.LineNumber +"-Speaker\" class=meterLevel style=\"height:0%\"></span>";
    html += "</span> ";
    html += "<button id=\"line-"+ lineObj.LineNumber +"-btn-settings\" onclick=\"ChangeSettings('"+ lineObj.LineNumber +"', this)\"><i class=\"fa fa-cogs\"></i> "+ lang.device_settings +"</button>";
    html += "<button id=\"line-"+ lineObj.LineNumber +"-call-stats\" onclick=\"ShowCallStats('"+ lineObj.LineNumber +"', this)\"><i class=\"fa fa-area-chart\"></i> "+ lang.call_stats +"</button>";
    html += "</div>";

    html += "<div id=\"line-"+ lineObj.LineNumber +"-AudioStats\" class=\"audioStats cleanScroller\" style=\"display:none\">";
    html += "<div style=\"text-align:right\"><button onclick=\"HideCallStats('"+ lineObj.LineNumber +"', this)\"><i class=\"fa fa-times\" style=\"font-size:20px;\"></i></button></div>";
    html += "<fieldset class=audioStatsSet onclick=\"HideCallStats('"+ lineObj.LineNumber +"', this)\">";
    html += "<legend>"+ lang.send_statistics +"</legend>";
    html += "<canvas id=\"line-"+ lineObj.LineNumber +"-AudioSendBitRate\" class=audioGraph width=600 height=160 style=\"width:600px; height:160px\"></canvas>";
    html += "<canvas id=\"line-"+ lineObj.LineNumber +"-AudioSendPacketRate\" class=audioGraph width=600 height=160 style=\"width:600px; height:160px\"></canvas>";
    html += "</fieldset>";
    html += "<fieldset class=audioStatsSet onclick=\"HideCallStats('"+ lineObj.LineNumber +"', this)\">";
    html += "<legend>"+ lang.receive_statistics +"</legend>";
    html += "<canvas id=\"line-"+ lineObj.LineNumber +"-AudioReceiveBitRate\" class=audioGraph width=600 height=160 style=\"width:600px; height:160px\"></canvas>";
    html += "<canvas id=\"line-"+ lineObj.LineNumber +"-AudioReceivePacketRate\" class=audioGraph width=600 height=160 style=\"width:600px; height:160px\"></canvas>";
    html += "<canvas id=\"line-"+ lineObj.LineNumber +"-AudioReceivePacketLoss\" class=audioGraph width=600 height=160 style=\"width:600px; height:160px\"></canvas>";
    html += "<canvas id=\"line-"+ lineObj.LineNumber +"-AudioReceiveJitter\" class=audioGraph width=600 height=160 style=\"width:600px; height:160px\"></canvas>";
    html += "<canvas id=\"line-"+ lineObj.LineNumber +"-AudioReceiveLevels\" class=audioGraph width=600 height=160 style=\"width:600px; height:160px\"></canvas>";
    html += "</fieldset>";
    html += "</div>";

    html += "</div>";
    html += "</div>";
    html += "</div>";
    html += "</td></tr>";
    html += "<tr><td class=\"streamSection streamSectionBackground\">";
    
    html += "<div id=\"line-"+ lineObj.LineNumber +"-CallDetails\" class=\"chatHistory cleanScroller\">";
    // In Call Activity
    html += "</div>";

    html += "</td></tr>";
    html += "</table>";

    $("#rightContent").append(html);
}
function RemoveLine(lineObj){
    if(lineObj == null) return;

    for(var l = 0; l < Lines.length; l++) {
        if(Lines[l].LineNumber == lineObj.LineNumber) {
            Lines.splice(l,1);
            break;
        }
    }

    CloseLine(lineObj.LineNumber);
    $("#line-ui-"+ lineObj.LineNumber).remove();

    UpdateBuddyList();

    // Rather than showing nothing, go to the last buddy selected
    // Select last user
    if(localDB.getItem("SelectedBuddy") != null){
        console.log("Selecting previously selected buddy...", localDB.getItem("SelectedBuddy"));
        SelectBuddy(localDB.getItem("SelectedBuddy"));
        UpdateUI();
    }
}
function CloseLine(lineNum){
    // Lines and Buddies (Left)
    $(".buddySelected").each(function () {
        $(this).prop('class', 'buddy');
    });
    // Streams (Right)
    $(".streamSelected").each(function () {
        $(this).prop('class', 'stream');
    });

    SwitchLines(0);

    console.log("Closing Line: "+ lineNum);
    for(var l = 0; l < Lines.length; l++){
        Lines[l].IsSelected = false;
    }
    selectedLine = null;
    for(var b = 0; b < Buddies.length; b++){
        Buddies[b].IsSelected = false;
    }
    selectedBuddy = null;

    $.jeegoopopup.close();

    // Change to Stream if in Narrow view
    UpdateUI();
}
function SwitchLines(lineNum){
    $.each(userAgent.sessions, function (i, session) {
        // All the other calls, not on hold
        if(session.local_hold == false && session.data.line != lineNum) {
            console.log("Putting an active call on hold: Line: "+ session.data.line +" buddy: "+ session.data.buddyId);
            session.hold(); // Check state

            // Log Hold
            if(!session.data.hold) session.data.hold = [];
            session.data.hold.push({ event: "hold", eventTime: utcDateNow() });
        }
        $("#line-" + session.data.line + "-btn-Hold").hide();
        $("#line-" + session.data.line + "-btn-Unhold").show();
        session.data.IsCurrentCall = false;
    });

    var lineObj = FindLineByNumber(lineNum);
    if(lineObj != null && lineObj.SipSession != null) {
        var session = lineObj.SipSession;
        if(session.local_hold == true) {
            console.log("Taking call off hold:  Line: "+ lineNum +" buddy: "+ session.data.buddyId);
            session.unhold();

            // Log Hold
            if(!session.data.hold) session.data.hold = [];
            session.data.hold.push({ event: "unhold", eventTime: utcDateNow() });
        }
        $("#line-" + lineNum + "-btn-Hold").show();
        $("#line-" + lineNum + "-btn-Unhold").hide();
        session.data.IsCurrentCall = true;
    }
    selectedLine = lineNum;

    RefreshLineActivity(lineNum);
}
function RefreshLineActivity(lineNum){
    var lineObj = FindLineByNumber(lineNum);
    if(lineObj == null || lineObj.SipSession == null) {
        return;
    }
    var session = lineObj.SipSession;

    $("#line-"+ lineNum +"-CallDetails").empty();

    var callDetails = [];

    var ringTime = 0;
    var CallStart = moment.utc(session.data.callstart.replace(" UTC", ""));
    var CallAnswer = null;
    if(session.startTime){
        CallAnswer = moment.utc(session.startTime);
        ringTime = moment.duration(CallAnswer.diff(CallStart));
    }
    CallStart = CallStart.format("YYYY-MM-DD HH:mm:ss UTC")
    CallAnswer = (CallAnswer)? CallAnswer.format("YYYY-MM-DD HH:mm:ss UTC") : null,
    ringTime = (ringTime != 0)? ringTime.asSeconds() : 0

    var srcCallerID = "";
    var dstCallerID = "";
    if(session.data.calldirection == "inbound") {
        srcCallerID = "<"+ session.remoteIdentity.uri.user +"> "+ session.remoteIdentity.displayName;
    } 
    else if(session.data.calldirection == "outbound") {
        dstCallerID = session.remoteIdentity.uri.user;
    }

    var withVideo = (session.data.withvideo)? "("+ lang.with_video +")" : "";
    var startCallMessage = (session.data.calldirection == "inbound")? lang.you_received_a_call_from + " " + srcCallerID  +" "+ withVideo : lang.you_made_a_call_to + " " + dstCallerID +" "+ withVideo;
    callDetails.push({ 
        Message: startCallMessage,
        TimeStr : CallStart
    });
    if(CallAnswer){
        var answerCallMessage = (session.data.calldirection == "inbound")? lang.you_answered_after + " " + ringTime + " " + lang.seconds_plural : lang.they_answered_after + " " + ringTime + " " + lang.seconds_plural;
        callDetails.push({ 
            Message: answerCallMessage,
            TimeStr : CallAnswer
        });
    }

    var Transfers = (session.data.transfer)? session.data.transfer : [];
    $.each(Transfers, function(item, transfer){
        var msg = (transfer.type == "Blind")? lang.you_started_a_blind_transfer_to +" "+ transfer.to +". " : lang.you_started_an_attended_transfer_to + " "+ transfer.to +". ";
        if(transfer.accept && transfer.accept.complete == true){
            msg += lang.the_call_was_completed
        }
        else if(transfer.accept.disposition != "") {
            msg += lang.the_call_was_not_completed +" ("+ transfer.accept.disposition +")"
        }
        callDetails.push({
            Message : msg,
            TimeStr : transfer.transferTime
        });
    });
    var Mutes = (session.data.mute)? session.data.mute : []
    $.each(Mutes, function(item, mute){
        callDetails.push({
            Message : (mute.event == "mute")? lang.you_put_the_call_on_mute : lang.you_took_the_call_off_mute,
            TimeStr : mute.eventTime
        });
    });
    var Holds = (session.data.hold)? session.data.hold : []
    $.each(Holds, function(item, hold){
        callDetails.push({
            Message : (hold.event == "hold")? lang.you_put_the_call_on_hold : lang.you_took_the_call_off_hold,
            TimeStr : hold.eventTime
        });
    });
    var Recordings = (session.data.recordings)? session.data.recordings : []
    $.each(Recordings, function(item, recording){
        var msg = lang.call_is_being_recorded;
        if(recording.startTime != recording.stopTime){
            msg += "("+ lang.now_stopped +")"
        }
        callDetails.push({
            Message : msg,
            TimeStr : recording.startTime
        });
    });
    var ConfCalls = (session.data.confcalls)? session.data.confcalls : []
    $.each(ConfCalls, function(item, confCall){
        var msg = lang.you_started_a_conference_call_to +" "+ confCall.to +". ";
        if(confCall.accept && confCall.accept.complete == true){
            msg += lang.the_call_was_completed
        }
        else if(confCall.accept.disposition != "") {
            msg += lang.the_call_was_not_completed +" ("+ confCall.accept.disposition +")"
        }
        callDetails.push({
            Message : msg,
            TimeStr : confCall.startTime
        });
    });

    callDetails.sort(function(a, b){
        var aMo = moment.utc(a.TimeStr.replace(" UTC", ""));
        var bMo = moment.utc(b.TimeStr.replace(" UTC", ""));
        if (aMo.isSameOrAfter(bMo, "second")) {
            return -1;
        } else return 1;
        return 0;
    });

    $.each(callDetails, function(item, detail){
        var Time = moment.utc(detail.TimeStr.replace(" UTC", "")).local().format(DisplayTimeFormat);
        var messageString = "<table class=timelineMessage cellspacing=0 cellpadding=0><tr>"
        messageString += "<td class=timelineMessageArea>"
        messageString += "<div class=timelineMessageDate><i class=\"fa fa-circle timelineMessageDot\"></i>"+ Time +"</div>"
        messageString += "<div class=timelineMessageText>"+ detail.Message +"</div>"
        messageString += "</td>"
        messageString += "</tr></table>";
        $("#line-"+ lineNum +"-CallDetails").prepend(messageString);
    });
}

// Buddy & Contacts
// ================
var Buddy = function(type, identity, CallerIDName, ExtNo, MobileNumber, ContactNumber1, ContactNumber2, lastActivity, desc, Email){
    this.type = type; // extension | contact | group
    this.identity = identity;
    this.CallerIDName = CallerIDName;
    this.Email = Email;
    this.Desc = desc;
    this.ExtNo = ExtNo;
    this.MobileNumber = MobileNumber;
    this.ContactNumber1 = ContactNumber1;
    this.ContactNumber2 = ContactNumber2;
    this.lastActivity = lastActivity; // Full Date as string eg "1208-03-21 15:34:23 UTC"
    this.devState = "dotOffline";
    this.presence = "Unknown";
    this.missed = 0;
    this.IsSelected = false;
    this.imageObjectURL = "";
}
function InitUserBuddies(){
    var template = { TotalRows:0, DataCollection:[] }
    localDB.setItem(profileUserID + "-Buddies", JSON.stringify(template));
    return JSON.parse(localDB.getItem(profileUserID + "-Buddies"));
}
function MakeBuddy(type, update, focus, subscribe, callerID, did){
    var json = JSON.parse(localDB.getItem(profileUserID + "-Buddies"));
    if(json == null) json = InitUserBuddies();

    var buddyObj = null;
    if(type == "contact"){
        var id = uID();
        var dateNow = utcDateNow();
        json.DataCollection.push({
            Type: "contact", 
            LastActivity: dateNow,
            ExtensionNumber: "", 
            MobileNumber: "",
            ContactNumber1: did,
            ContactNumber2: "",
            uID: null,
            cID: id,
            gID: null,
            DisplayName: callerID,
            Position: "",
            Description: "",
            Email: "",
            MemberCount: 0
        });
        buddyObj = new Buddy("contact", id, callerID, "", "", did, "", dateNow, "", "");
        AddBuddy(buddyObj, update, focus);
    }
    else {
        var id = uID();
        var dateNow = utcDateNow();
        json.DataCollection.push({
            Type: "extension",
            LastActivity: dateNow,
            ExtensionNumber: did,
            MobileNumber: "",
            ContactNumber1: "",
            ContactNumber2: "",
            uID: id,
            cID: null,
            gID: null,
            DisplayName: callerID,
            Position: "",
            Description: "", 
            Email: "",
            MemberCount: 0
        });
        buddyObj = new Buddy("extension", id, callerID, did, "", "", "", dateNow, "", "");
        AddBuddy(buddyObj, update, focus, subscribe);
    }
    // Update Size: 
    json.TotalRows = json.DataCollection.length;

    // Save To DB
    localDB.setItem(profileUserID + "-Buddies", JSON.stringify(json));

    // Return new buddy
    return buddyObj;
}
function UpdateBuddyCalerID(buddyObj, callerID){
    buddyObj.CallerIDName = callerID;

    var buddy = buddyObj.identity;
    // Update DB
    var json = JSON.parse(localDB.getItem(profileUserID + "-Buddies"));
    if(json != null){
        $.each(json.DataCollection, function (i, item) {
            if(item.uID == buddy || item.cID == buddy || item.gID == buddy){
                item.DisplayName = callerID;
                return false;
            }
        });
        // Save To DB
        localDB.setItem(profileUserID + "-Buddies", JSON.stringify(json));
    }

    UpdateBuddyList();
}
function AddBuddy(buddyObj, update, focus, subscribe){
    Buddies.push(buddyObj);
    if(update == true) UpdateBuddyList();
    AddBuddyMessageStream(buddyObj);
    if(subscribe == true) SubscribeBuddy(buddyObj);
    if(focus == true) SelectBuddy(buddyObj.identity);
}
function PopulateBuddyList() {
    console.log("Clearing Buddies...");
    Buddies = new Array();
    console.log("Adding Buddies...");
    var json = JSON.parse(localDB.getItem(profileUserID + "-Buddies"));
    if(json == null) return;

    console.log("Total Buddies: " + json.TotalRows);
    $.each(json.DataCollection, function (i, item) {
        if(item.Type == "extension"){
            // extension
            var buddy = new Buddy("extension", item.uID, item.DisplayName, item.ExtensionNumber, item.MobileNumber, item.ContactNumber1, item.ContactNumber2, item.LastActivity, item.Position, item.Email);
            AddBuddy(buddy, false, false);
        }
        else if(item.Type == "contact"){
            // contact
            var buddy = new Buddy("contact", item.cID, item.DisplayName, "", item.MobileNumber, item.ContactNumber1, item.ContactNumber2, item.LastActivity, item.Description, item.Email);
            AddBuddy(buddy, false, false);
        }
        else if(item.Type == "group"){
            // group
            var buddy = new Buddy("group", item.gID, item.DisplayName, item.ExtensionNumber, "", "", "", item.LastActivity, item.MemberCount + " member(s)", item.Email);
            AddBuddy(buddy, false, false);
        }
    });

    // Update List (after add)
    console.log("Updating Buddy List...");
    UpdateBuddyList();
}
function UpdateBuddyList(){
    var filter = $("#txtFindBuddy").val();

    $("#myContacts").empty();

    var callCount = 0
    for(var l = 0; l < Lines.length; l++) {

        var classStr = (Lines[l].IsSelected)? "buddySelected" : "buddy";
        if(Lines[l].SipSession != null) classStr = (Lines[l].SipSession.local_hold)? "buddyActiveCallHollding" : "buddyActiveCall";

        var html = "<div id=\"line-"+ Lines[l].LineNumber +"\" class="+ classStr +" onclick=\"SelectLine('"+ Lines[l].LineNumber +"')\">";
        html += "<div class=lineIcon>"+ (l + 1) +"</div>";
        html += "<div class=contactNameText><i class=\"fa fa-phone\"></i> "+ lang.line +" "+ (l + 1) +"</div>";
        html += "<div id=\"Line-"+ Lines[l].ExtNo +"-datetime\" class=contactDate>&nbsp;</div>";
        html += "<div class=presenceText>"+ Lines[l].DisplayName +" <"+ Lines[l].DisplayNumber +">" +"</div>";
        html += "</div>";
        // SIP.Session.C.STATUS_TERMINATED
        if(Lines[l].SipSession && Lines[l].SipSession.data.earlyReject != true){
            $("#myContacts").append(html);
            callCount ++;
        }
    }

    // Sort and shuffle Buddy List
    // ===========================
    Buddies.sort(function(a, b){
        var aMo = moment.utc(a.lastActivity.replace(" UTC", ""));
        var bMo = moment.utc(b.lastActivity.replace(" UTC", ""));
        if (aMo.isSameOrAfter(bMo, "second")) {
            return -1;
        } else return 1;
        return 0;
    });


    for(var b = 0; b < Buddies.length; b++) {
        var buddyObj = Buddies[b];

        if(filter && filter.length >= 1){
            // Perform Filter Display
            var display = false;
            if(buddyObj.CallerIDName.toLowerCase().indexOf(filter.toLowerCase()) > -1 ) display = true;
            if(buddyObj.ExtNo.toLowerCase().indexOf(filter.toLowerCase()) > -1 ) display = true;
            if(buddyObj.Desc.toLowerCase().indexOf(filter.toLowerCase()) > -1 ) display = true;
            if(!display) continue;
        }

        var today = moment.utc();
        var lastActivity = moment.utc(buddyObj.lastActivity.replace(" UTC", ""));
        var displayDateTime = "";
        if(lastActivity.isSame(today, 'day'))
        {
            displayDateTime = lastActivity.local().format(DisplayTimeFormat);
        } 
        else {
            displayDateTime = lastActivity.local().format(DisplayDateFormat);
        }

        var classStr = (buddyObj.IsSelected)? "buddySelected" : "buddy";
        if(buddyObj.type == "extension") {
            var friendlyState = buddyObj.presence;
            if (friendlyState == "Unknown") friendlyState = lang.state_unknown;
            if (friendlyState == "Not online") friendlyState = lang.state_not_online;
            if (friendlyState == "Ready") friendlyState = lang.state_ready;
            if (friendlyState == "On the phone") friendlyState = lang.state_on_the_phone;
            if (friendlyState == "Ringing") friendlyState = lang.state_ringing;
            if (friendlyState == "On hold") friendlyState = lang.state_on_hold;
            if (friendlyState == "Unavailable") friendlyState = lang.state_unavailable;

            // An extension on the same system
            var html = "<div id=\"contact-"+ buddyObj.identity +"\" class="+ classStr +" onmouseenter=\"ShowBuddyDial(this, '"+ buddyObj.identity +"')\" onmouseleave=\"HideBuddyDial(this, '"+ buddyObj.identity +"')\" onclick=\"SelectBuddy('"+ buddyObj.identity +"', 'extension')\">";
            html += "<span id=\"contact-"+ buddyObj.identity +"-devstate\" class=\""+ buddyObj.devState +"\"></span>";
            if (getDbItem("useRoundcube", "") == 1 && buddyObj.Email != '' && buddyObj.Email != null && typeof buddyObj.Email != 'undefined') {
                html += "<span id=\"contact-"+ buddyObj.identity +"-email\" class=quickDial style=\"right: 66px; display:none\" title='"+ lang.send_email +"' onclick=\"ComposeEmail('"+ buddyObj.identity +"', this, event)\"><i class=\"fa fa-envelope-o\" aria-hidden=\"true\"></i></span>";
            }
            if (EnableVideoCalling) {
                html += "<span id=\"contact-"+ buddyObj.identity +"-audio-dial\" class=quickDial style=\"right: 44px; display:none\" title='"+ lang.audio_call +"' onclick=\"QuickDialAudio('"+ buddyObj.identity +"', this, event)\"><i class=\"fa fa-phone\"></i></span>";
                html += "<span id=\"contact-"+ buddyObj.identity +"-video-dial\" class=quickDial style=\"right: 23px; display:none\" title='"+ lang.video_call +"' onclick=\"QuickDialVideo('"+ buddyObj.identity +"', '"+ buddyObj.ExtNo +"', event)\"><i class=\"fa fa-video-camera\"></i></span>";
            } else {
                html += "<span id=\"contact-"+ buddyObj.identity +"-audio-dial\" class=quickDial style=\"right: 23px; display:none\" title='"+ lang.audio_call +"' onclick=\"QuickDialAudio('"+ buddyObj.identity +"', this, event)\"><i class=\"fa fa-phone\"></i></span>";
            }
            if(buddyObj.missed && buddyObj.missed > 0){
                html += "<span id=\"contact-"+ buddyObj.identity +"-missed\" class=missedNotifyer>"+ buddyObj.missed +"</span>";
            }
            else{
                html += "<span id=\"contact-"+ buddyObj.identity +"-missed\" class=missedNotifyer style=\"display:none\">"+ buddyObj.missed +"</span>";
            }
            html += "<div class=buddyIcon onclick=\"EditBuddyWindow('"+ buddyObj.identity +"')\" style=\"background-image: url('"+ getPicture(buddyObj.identity) +"')\" title=\"Edit Contact\"><i class=\"fa fa-pencil-square-o\" aria-hidden=\"true\"></i></div>";
            html += "<div class=contactNameText><i class=\"fa fa-phone-square\"></i> "+ buddyObj.ExtNo +" - "+ buddyObj.CallerIDName +"</div>";
            html += "<div id=\"contact-"+ buddyObj.identity +"-datetime\" class=contactDate>"+ displayDateTime +"</div>";
            html += "<div id=\"contact-"+ buddyObj.identity +"-presence\" class=presenceText>"+ friendlyState +"</div>";
            html += "</div>";
            $("#myContacts").append(html);
        } else if(buddyObj.type == "contact") { 
            // An Addressbook Contact
            var html = "<div id=\"contact-"+ buddyObj.identity +"\" class="+ classStr +" onmouseenter=\"ShowBuddyDial(this, '"+ buddyObj.identity +"')\" onmouseleave=\"HideBuddyDial(this, '"+ buddyObj.identity +"')\" onclick=\"SelectBuddy('"+ buddyObj.identity +"', 'contact')\">";
            if (getDbItem("useRoundcube", "") == 1 && buddyObj.Email != '' && buddyObj.Email != null && typeof buddyObj.Email != 'undefined') {
                html += "<span id=\"contact-"+ buddyObj.identity +"-email\" class=quickDial style=\"right: 44px; display:none\" title='"+ lang.send_email +"' onclick=\"ComposeEmail('"+ buddyObj.identity +"', this, event)\"><i class=\"fa fa-envelope-o\" aria-hidden=\"true\"></i></span>";
            }
            html += "<span id=\"contact-"+ buddyObj.identity +"-audio-dial\" class=quickDial style=\"right: 23px; display:none\" title='"+ lang.audio_call +"' onclick=\"QuickDialAudio('"+ buddyObj.identity +"', this, event)\"><i class=\"fa fa-phone\"></i></span>";
            if(buddyObj.missed && buddyObj.missed > 0){
                html += "<span id=\"contact-"+ buddyObj.identity +"-missed\" class=missedNotifyer>"+ buddyObj.missed +"</span>";
            }
            else{
                html += "<span id=\"contact-"+ buddyObj.identity +"-missed\" class=missedNotifyer style=\"display:none\">"+ buddyObj.missed +"</span>";
            }
            html += "<div class=buddyIcon onclick=\"EditBuddyWindow('"+ buddyObj.identity +"')\" style=\"background-image: url('"+ getPicture(buddyObj.identity,"contact") +"')\" title=\"Edit Contact\"><i class=\"fa fa-pencil-square-o\" aria-hidden=\"true\"></i></div>";
            html += "<div class=contactNameText><i class=\"fa fa-address-card\"></i> "+ buddyObj.CallerIDName +"</div>";
            html += "<div id=\"contact-"+ buddyObj.identity +"-datetime\" class=contactDate>"+ displayDateTime +"</div>";
            html += "<div class=presenceText>"+ buddyObj.Desc +"</div>";
            html += "</div>";
            $("#myContacts").append(html);
        } else if(buddyObj.type == "group"){ 
            // A collection of extensions and contacts
            var html = "<div id=\"contact-"+ buddyObj.identity +"\" class="+ classStr +" onmouseenter=\"ShowBuddyDial(this, '"+ buddyObj.identity +"')\" onmouseleave=\"HideBuddyDial(this, '"+ buddyObj.identity +"')\" onclick=\"SelectBuddy('"+ buddyObj.identity +"', 'group')\">";
            if (getDbItem("useRoundcube", "") == 1 && buddyObj.Email != '' && buddyObj.Email != null && typeof buddyObj.Email != 'undefined') {
                html += "<span id=\"contact-"+ buddyObj.identity +"-email\" class=quickDial style=\"right: 44px; display:none\" title='"+ lang.send_email +"' onclick=\"ComposeEmail('"+ buddyObj.identity +"', this, event)\"><i class=\"fa fa-envelope-o\" aria-hidden=\"true\"></i></span>";
            }
            html += "<span id=\"contact-"+ buddyObj.identity +"-audio-dial\" class=quickDial style=\"right: 23px; display:none\" title='"+ lang.audio_call +"' onclick=\"QuickDialAudio('"+ buddyObj.identity +"', this, event)\"><i class=\"fa fa-phone\"></i></span>";
            if(buddyObj.missed && buddyObj.missed > 0){
                html += "<span id=\"contact-"+ buddyObj.identity +"-missed\" class=missedNotifyer>"+ buddyObj.missed +"</span>";
            }
            else{
                html += "<span id=\"contact-"+ buddyObj.identity +"-missed\" class=missedNotifyer style=\"display:none\">"+ buddyObj.missed +"</span>";
            }
            html += "<div class=buddyIcon onclick=\"EditBuddyWindow('"+ buddyObj.identity +"')\" style=\"background-image: url('"+ getPicture(buddyObj.identity,"group") +"')\" title=\"Edit Contact\"><i class=\"fa fa-pencil-square-o\" aria-hidden=\"true\"></i></div>";
            html += "<div class=contactNameText><i class=\"fa fa-users\"></i> "+ buddyObj.CallerIDName +"</div>";
            html += "<div id=\"contact-"+ buddyObj.identity +"-datetime\" class=contactDate>"+ displayDateTime +"</div>";
            html += "<div class=presenceText>"+ buddyObj.Desc +"</div>";
            html += "</div>";
            $("#myContacts").append(html);
        }
    }
}
function AddBuddyMessageStream(buddyObj) {
    var html = "<table id=\"stream-"+ buddyObj.identity +"\" class=stream cellspacing=5 cellpadding=0>";
    html += "<tr><td class=streamSection style=\"height: 48px;\">";

    // Close|Return|Back Button
    html += "<div style=\"float:left; margin:8.7px 0px 0px 8.7px; width: 38px; height:38px; line-height:38px;\">"

    html += "<button id=\"contact-"+ buddyObj.identity +"-btn-back\" onclick=\"CloseBuddy('"+ buddyObj.identity +"')\" class=roundButtons title=\""+ lang.back +"\"><i class=\"fa fa-chevron-left\"></i></button> ";
    html += "</div>"
    
    // Profile UI
    html += "<div class=contact style=\"float: left; position: absolute; left: 47px; right: 190px;\" onclick=\"ShowBuddyProfileMenu('"+ buddyObj.identity +"', this, '"+ buddyObj.type +"')\">";
    if(buddyObj.type == "extension") {
        html += "<span id=\"contact-"+ buddyObj.identity +"-devstate-main\" class=\""+ buddyObj.devState +"\"></span>";
    }
    if(buddyObj.type == "extension") {
        html += "<div id=\"contact-"+ buddyObj.identity +"-picture-main\" class=buddyIcon style=\"background-image: url('"+ getPicture(buddyObj.identity) +"')\"></div>";
    }
    else if(buddyObj.type == "contact") {
        html += "<div class=buddyIcon style=\"background-image: url('"+ getPicture(buddyObj.identity,"contact") +"')\"></div>";
    }
    else if(buddyObj.type == "group") {
        html += "<div class=buddyIcon style=\"background-image: url('"+ getPicture(buddyObj.identity,"group") +"')\"></div>";
    }
    if(buddyObj.type == "extension") {
        html += "<div class=contactNameText style=\"margin-right: 0px;\"><i class=\"fa fa-phone-square\"></i> "+ buddyObj.ExtNo +" - "+ buddyObj.CallerIDName +"</div>";
    }
    else if(buddyObj.type == "contact") {
        html += "<div class=contactNameText style=\"margin-right: 0px;\"><i class=\"fa fa-address-card\"></i> "+ buddyObj.CallerIDName +"</div>";
    } 
    else if(buddyObj.type == "group") {
        html += "<div class=contactNameText style=\"margin-right: 0px;\"><i class=\"fa fa-users\"></i> "+ buddyObj.CallerIDName +"</div>";
    }
    if(buddyObj.type == "extension") {
        var friendlyState = buddyObj.presence;
        if (friendlyState == "Unknown") friendlyState = lang.state_unknown;
        if (friendlyState == "Not online") friendlyState = lang.state_not_online;
        if (friendlyState == "Ready") friendlyState = lang.state_ready;
        if (friendlyState == "On the phone") friendlyState = lang.state_on_the_phone;
        if (friendlyState == "Ringing") friendlyState = lang.state_ringing;
        if (friendlyState == "On hold") friendlyState = lang.state_on_hold;
        if (friendlyState == "Unavailable") friendlyState = lang.state_unavailable;

        html += "<div id=\"contact-"+ buddyObj.identity +"-presence-main\" class=presenceText>"+ friendlyState +"</div>";
    } else{
        html += "<div id=\"contact-"+ buddyObj.identity +"-presence-main\" class=presenceText>"+ buddyObj.Desc +"</div>";
    }
    html += "</div>";

    // Action Buttons
    html += "<div style=\"float:right; line-height:46px; margin:3.2px 5px 0px 0px;\">";
    html += "<button id=\"contact-"+ buddyObj.identity +"-btn-audioCall\" onclick=\"AudioCallMenu('"+ buddyObj.identity +"', this)\" class=roundButtons title=\""+ lang.audio_call +"\"><i class=\"fa fa-phone\"></i></button> ";
    if(buddyObj.type == "extension" && EnableVideoCalling) {
        html += "<button id=\"contact-"+ buddyObj.identity +"-btn-videoCall\" onclick=\"DialByLine('video', '"+ buddyObj.identity +"', '"+ buddyObj.ExtNo +"');\" class=roundButtons title=\""+ lang.video_call +"\"><i class=\"fa fa-video-camera\"></i></button> ";
    }
    html += "<button id=\"contact-"+ buddyObj.identity +"-btn-search\" onclick=\"FindSomething('"+ buddyObj.identity +"')\" class=roundButtons title=\""+ lang.find_something +"\"><i class=\"fa fa-search\"></i></button> ";
    if(buddyObj.type == "extension") {
        html += "<button id=\"contact-"+ buddyObj.identity +"-btn-download-chat\" onclick=\"DownloadChatText('"+ buddyObj.identity +"')\" class=roundButtons title=\""+ lang.save_chat_text +"\"><i class=\"fa fa-download\" aria-hidden=\"true\"></i></button> ";
    }
    html += "<button id=\"contact-"+ buddyObj.identity +"-btn-remove\" onclick=\"RemoveBuddy('"+ buddyObj.identity +"')\" class=roundButtons title=\""+ lang.remove_contact +"\"><i class=\"fa fa-trash\"></i></button> ";
    html += "</div>";

    // Separator --------------------------------------------------------------------------
    html += "<div style=\"clear:both; height:0px\"></div>"

    // Calling UI --------------------------------------------------------------------------
    html += "<div id=\"contact-"+ buddyObj.identity +"-calling\">";

    // Gneral Messages
    html += "<div id=\"contact-"+ buddyObj.identity +"-timer\" style=\"float: right; margin-top: 4px; margin-right: 10px; color: #575757; display:none;\"></div>";
    html += "<div id=\"contact-"+ buddyObj.identity +"-msg\" class=callStatus style=\"display:none\">...</div>";

    // Call Answer UI
    html += "<div id=\"contact-"+ buddyObj.identity +"-AnswerCall\" class=answerCall style=\"display:none\">";
    html += "<div>";
    html += "<button onclick=\"AnswerAudioCall('"+ buddyObj.identity +"')\" class=answerButton><i class=\"fa fa-phone\"></i>&nbsp;&nbsp;"+ lang.answer_call +"</button> ";
    if(buddyObj.type == "extension" && EnableVideoCalling) {
        html += "<button id=\"contact-"+ buddyObj.identity +"-answer-video\" onclick=\"AnswerVideoCall('"+ buddyObj.identity +"')\" class=answerButton><i class=\"fa fa-video-camera\"></i>&nbsp;&nbsp;"+ lang.answer_call_with_video +"</button> ";
    }
    html += "<button onclick=\"RejectCall('"+ buddyObj.identity +"')\" class=hangupButton><i class=\"fa fa-phone\"></i>&nbsp;&nbsp;"+ lang.reject_call +"</button> ";
    html += "</div>";
    html += "</div>";

    html += "</div>";

    // Search & Related Elements
    html += "<div id=\"contact-"+ buddyObj.identity +"-search\" style=\"margin-top:6px; display:none\">";
    html += "<span class=searchClean style=\"width:100%; margin-left:9px;\"><input type=text style=\"width:40%;margin-bottom:5px;\" autocomplete=none oninput=SearchStream(this,'"+ buddyObj.identity +"') placeholder=\""+ lang.find_something_in_the_message_stream +"\"></span>";

    html += "</div>";

    html += "</td></tr>";
    html += "<tr><td class=\"streamSection streamSectionBackground\">";

    html += "<div id=\"contact-"+ buddyObj.identity +"-ChatHistory\" class=\"chatHistory cleanScroller\" ondragenter=\"setupDragDrop(event, '"+ buddyObj.identity +"')\" ondragover=\"setupDragDrop(event, '"+ buddyObj.identity +"')\" ondragleave=\"cancelDragDrop(event, '"+ buddyObj.identity +"')\" ondrop=\"onFileDragDrop(event, '"+ buddyObj.identity +"')\">";
    // Previous Chat messages
    html += "</div>";

    html += "</td></tr>";

    if ((buddyObj.type == "extension" || buddyObj.type == "group") && EnableTextMessaging) {

        html += "<tr><td  id=sendChatMessageSection class=streamSection style=\"height:110px\">";

        // Send Paste Image
        html += "<div id=\"contact-"+ buddyObj.identity +"-imagePastePreview\" class=sendImagePreview style=\"display:none\" tabindex=0></div>";

        // Send File
        html += "<div id=\"contact-"+ buddyObj.identity +"-fileShare\" style=\"display:none\">";
        html += "<input type=file multiple onchange=\"console.log(this)\" />";
        html += "</div>";

        // Send Audio Recording
        html += "<div id=\"contact-"+ buddyObj.identity +"-audio-recording\" style=\"display:none\"></div>";

        // Send Video Recording
        html += "<div id=\"contact-"+ buddyObj.identity +"-video-recording\" style=\"display:none\"></div>";

        // Dictate Message
        // html += "<div id=\"contact-"+ buddyObj.identity +"-dictate-message\" style=\"display:none\"></div>";

        // Emoji Menu Bar
        html += "<div id=\"contact-"+ buddyObj.identity +"-emoji-menu\" style=\"display:none\" class=\"EmojiMenu\"></div>";

        // =====================================
        // Type Area
        html += "<table class=sendMessageContainer cellpadding=0 cellspacing=0><tr>";
        html += "<td><textarea id=\"contact-"+ buddyObj.identity +"-ChatMessage\" class=\"chatMessage\" placeholder=\""+ lang.type_your_message_here +"\" onkeydown=\"chatOnkeydown(event, this,'"+ buddyObj.identity +"')\" onpaste=\"chatOnbeforepaste(event, this,'"+ buddyObj.identity +"')\"></textarea></td>";
        html += "<td style=\"width:40px;padding-top:4px;\"><button onclick=\"SendChatMessage('"+ buddyObj.identity +"')\" class=roundButtonsSpec title=\""+ lang.send_chat_message +"\"><i class=\"fa fa-paper-plane-o\" aria-hidden=\"true\"></i></button>";
        html += "<button onclick=\"ShowEmojiBar('"+ buddyObj.identity +"')\" class=roundButtonsSpec title=\""+ lang.select_expression + "\"><i class=\"fa fa-smile-o\"></i></button>";
        html += "<button onclick=\"SendFile('"+ buddyObj.identity +"')\" class=roundButtonsSpec title=\""+ lang.send_file + "\"><i class=\"fa fa-file-text-o\"></i></button></td>";
        html += "</tr></table>";
        html += "</td></tr>";
    }

    html += "</table>";

    $("#rightContent").append(html);
}
function RemoveBuddyMessageStream(buddyObj){
    CloseBuddy(buddyObj.identity);

    UpdateBuddyList();

    // Remove Stream
    $("#stream-"+ buddyObj.identity).remove();
    var stream = JSON.parse(localDB.getItem(buddyObj.identity + "-stream"));
    localDB.removeItem(buddyObj.identity + "-stream");

    // Remove Buddy
    var json = JSON.parse(localDB.getItem(profileUserID + "-Buddies"));
    var x = 0;
    $.each(json.DataCollection, function (i, item) {
        if(item.uID == buddyObj.identity || item.cID == buddyObj.identity || item.gID == buddyObj.identity){
            x = i;
            return false;
        }
    });
    json.DataCollection.splice(x,1);
    json.TotalRows = json.DataCollection.length;
    localDB.setItem(profileUserID + "-Buddies", JSON.stringify(json));

    // Remove Images
    localDB.removeItem("img-"+ buddyObj.identity +"-extension");
    localDB.removeItem("img-"+ buddyObj.identity +"-contact");
    localDB.removeItem("img-"+ buddyObj.identity +"-group");

    // Remove Call Recordings
    if(stream && stream.DataCollection && stream.DataCollection.length >= 1){
        DeleteCallRecordings(buddyObj.identity, stream);
    }
    
    // Remove QOS Data
    DeleteQosData(buddyObj.identity);
}
function DeleteCallRecordings(buddy, stream){
    var indexedDB = window.indexedDB;
    var request = indexedDB.open("CallRecordings");
    request.onerror = function(event) {
        console.error("IndexDB Request Error:", event);
    }
    request.onupgradeneeded = function(event) {
        console.warn("Upgrade Required for IndexDB... probably because of first time use.");
        // If this is the case, there will be no call recordings
    }
    request.onsuccess = function(event) {
        console.log("IndexDB connected to CallRecordings");

        var IDB = event.target.result;
        if(IDB.objectStoreNames.contains("Recordings") == false){
            console.warn("IndexDB CallRecordings.Recordings does not exists");
            return;
        }
        IDB.onerror = function(event) {
            console.error("IndexDB Error:", event);
        }

        // Loop and Delete
        $.each(stream.DataCollection, function (i, item) {
            if (item.Recordings && item.Recordings.length) {
                $.each(item.Recordings, function (i, recording) {
                    console.log("Deleting Call Recording: ", recording.uID);
                    var objectStore = IDB.transaction(["Recordings"], "readwrite").objectStore("Recordings");
                    try{
                        var deleteRequest = objectStore.delete(recording.uID);
                        deleteRequest.onsuccess = function(event) {
                            console.log("Call Recording Deleted: ", recording.uID);
                        }
                    } catch(e){
                        console.log("Call Recording Delete failed: ", e);
                    }
                });
            }
        });
    }
}

function MakeUpName(){
    var shortname = 4;
    var longName = 12;
    var letters = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
    var rtn = "";
    rtn += letters[Math.floor(Math.random() * letters.length)];
    for(var n=0; n<Math.floor(Math.random() * longName) + shortname; n++){
        rtn += letters[Math.floor(Math.random() * letters.length)].toLowerCase();
    }
    rtn += " ";
    rtn += letters[Math.floor(Math.random() * letters.length)];
    for(var n=0; n<Math.floor(Math.random() * longName) + shortname; n++){
        rtn += letters[Math.floor(Math.random() * letters.length)].toLowerCase();
    }
    return rtn;
}
function MakeUpNumber(){
    var numbers = ["0","1","2","3","4","5","6","7","8","9","0"];
    var rtn = "0";
    for(var n=0; n<9; n++){
        rtn += numbers[Math.floor(Math.random() * numbers.length)];
    }
    return rtn;
}
function MakeUpBuddies(int){
    for(var i=0; i<int; i++){
        var buddyObj = new Buddy("contact", uID(), MakeUpName(), "", "", MakeUpNumber(), "", utcDateNow(), "Testing", "");
        AddBuddy(buddyObj, false, false);
    }
    UpdateBuddyList();
}

function SelectBuddy(buddy) {

    $("#roundcubeFrame").remove();
    $(".streamSelected").each(function() { $(this).show(); });

    var buddyObj = FindBuddyByIdentity(buddy);
    if(buddyObj == null) return;

    for(var b = 0; b < Buddies.length; b++) {
        if(Buddies[b].IsSelected == true && Buddies[b].identity == buddy){
            // Nothing to do, you re-selected the same buddy;
            return;
        }
    }

    console.log("Selecting Buddy: "+ buddy);

    selectedBuddy = buddyObj;

    // Can only display one thing on the right
    $(".streamSelected").each(function () {
        $(this).prop('class', 'stream');
    });
    $("#stream-" + buddy).prop('class', 'streamSelected');

    // Update Lines List
    for(var l = 0; l < Lines.length; l++) {
        var classStr = "buddy";
        if(Lines[l].SipSession != null) classStr = (Lines[l].SipSession.local_hold)? "buddyActiveCallHollding" : "buddyActiveCall";
        $("#line-" + Lines[l].LineNumber).prop('class', classStr);
        Lines[l].IsSelected = false;
    }

    ClearMissedBadge(buddy);
    // Update Buddy List
    for(var b = 0; b < Buddies.length; b++) {
        var classStr = (Buddies[b].identity == buddy)? "buddySelected" : "buddy";
        $("#contact-" + Buddies[b].identity).prop('class', classStr);

        $("#contact-"+ Buddies[b].identity +"-ChatHistory").empty();

        Buddies[b].IsSelected = (Buddies[b].identity == buddy);
    }

    // Change to Stream if in Narrow view
    UpdateUI();
    
    // Refresh Stream
    RefreshStream(buddyObj);

    try{
        $("#contact-" + buddy).get(0).scrollIntoViewIfNeeded();
    } catch(e){}

    // Save Selected
    localDB.setItem("SelectedBuddy", buddy);
}
function CloseBuddy(buddy){
    // Lines and Buddies (Left)
    $(".buddySelected").each(function () {
        $(this).prop('class', 'buddy');
    });
    // Streams (Right)
    $(".streamSelected").each(function () {
        $(this).prop('class', 'stream');
    });

    console.log("Closing Buddy: "+ buddy);
    for(var b = 0; b < Buddies.length; b++){
        Buddies[b].IsSelected = false;
    }
    selectedBuddy = null;
    for(var l = 0; l < Lines.length; l++){
        Lines[l].IsSelected = false;
    }
    selectedLine = null;

    // Save Selected
    localDB.setItem("SelectedBuddy", null);

    // Change to Stream if in Narrow view
    UpdateUI();
}
function DownloadChatText(buddy) {

    var buddyInfo = FindBuddyByIdentity(buddy);
    var DispNamePre = buddyInfo.CallerIDName;
    var DispName = DispNamePre.replace(" ", "_");
    var buddyExt = buddyInfo.ExtNo;
    var presDate = moment().format("YYYY-MM-DD_HH-mm-ss");

    var wholeChatTextTitle = "\n" + "Roundpin Chat With " + DispNamePre + " (extension " + buddyExt + "), saved on " + moment().format("YYYY-MM-DD HH:mm:ss") + "\n\n\n\n";
    var wholeChatText = "";

    $("#contact-"+buddy+"-ChatHistory .chatMessageTable").each(function() {
       if ($(this).hasClass("theirChatMessage")) {
           wholeChatText += "\n" + DispNamePre + "\n" + $(this).text() + "\n\n";
       } else {
           wholeChatText += "\n" + "Me" + "\n" + $(this).text() + "\n\n";
       }
    });

    if (wholeChatText == "") { alert("There is no chat text to save ! "); return; }
    var wholeChatTextConc = wholeChatTextTitle + wholeChatText;
    var downFilename = 'Roundpin_Chat-' + DispName + "_" + presDate;
    var downlink = document.createElement('a');
    var mimeType = 'text/plain';

    downlink.setAttribute('download', downFilename);
    downlink.setAttribute('href', 'data:' + mimeType + ';charset=utf-8,' + encodeURIComponent(wholeChatTextConc));
    downlink.click(); 
}
function RemoveBuddy(buddy){

    var buddyData = FindBuddyByIdentity(buddy);
    var buddyDisplayName = buddyData.CallerIDName;

    // Check if you are on the phone, etc.
    Confirm(lang.confirm_remove_buddy, lang.remove_buddy, function(){
        for(var b = 0; b < Buddies.length; b++) {
            if(Buddies[b].identity == buddy) {
                RemoveBuddyMessageStream(Buddies[b]);
                UnsubscribeBuddy(Buddies[b])
                Buddies.splice(b, 1);
                break;
            }
        }
        // Remove contact from SQL database
        deleteBuddyFromSqldb(buddyDisplayName);

        UpdateBuddyList();
    });
}
function FindBuddyByDid(did){
    // Used only in Inboud
    for(var b = 0; b < Buddies.length; b++){
        if(Buddies[b].ExtNo == did || Buddies[b].MobileNumber == did || Buddies[b].ContactNumber1 == did || Buddies[b].ContactNumber2 == did) {
            return Buddies[b];
        }
    }
    return null;
}
function FindBuddyByExtNo(ExtNo){
    for(var b = 0; b < Buddies.length; b++){
        if(Buddies[b].type == "extension" && Buddies[b].ExtNo == ExtNo) return Buddies[b];
    }
    return null;
}
function FindBuddyByNumber(number){
    // Number could be: +XXXXXXXXXX
    // Any special characters must be removed prior to adding
    for(var b = 0; b < Buddies.length; b++){
        if(Buddies[b].MobileNumber == number || Buddies[b].ContactNumber1 == number || Buddies[b].ContactNumber2 == number) {
            return Buddies[b];
        }
    }
    return null;
}
function FindBuddyByIdentity(identity){
    for(var b = 0; b < Buddies.length; b++){
        if(Buddies[b].identity == identity) return Buddies[b];
    }
    return null;
}
function SearchStream(obj, buddy){
    var q = obj.value;

    var buddyObj = FindBuddyByIdentity(buddy);
    if(q == ""){
        console.log("Restore Stream");
        RefreshStream(buddyObj);
    }
    else{
        RefreshStream(buddyObj, q);
    }
}
function RefreshStream(buddyObj, filter) {
    $("#contact-" + buddyObj.identity + "-ChatHistory").empty();

    var json = JSON.parse(localDB.getItem(buddyObj.identity +"-stream"));
    if(json == null || json.DataCollection == null) return;

    // Sort DataCollection (Newest items first)
    json.DataCollection.sort(function(a, b){
        var aMo = moment.utc(a.ItemDate.replace(" UTC", ""));
        var bMo = moment.utc(b.ItemDate.replace(" UTC", ""));
        if (aMo.isSameOrAfter(bMo, "second")) {
            return -1;
        } else return 1;
        return 0;
    });

    // Filter
    if(filter && filter != ""){

        console.log("Rows without filter ("+ filter +"): ", json.DataCollection.length);
        json.DataCollection = json.DataCollection.filter(function(item){
            if(filter.indexOf("date: ") != -1){
                // Apply Date Filter
                var dateFilter = getFilter(filter, "date");
                if(dateFilter != "" && item.ItemDate.indexOf(dateFilter) != -1) return true;
            }
            if(item.MessageData && item.MessageData.length > 1){
                if(item.MessageData.toLowerCase().indexOf(filter.toLowerCase()) != -1) return true;
                if(filter.toLowerCase().indexOf(item.MessageData.toLowerCase()) != -1) return true;
            }
            if (item.ItemType == "MSG") {
                // Special search
            } 
            else if (item.ItemType == "CDR") {
                // Tag search
                if(item.Tags && item.Tags.length > 1){
                    var tagFilter = getFilter(filter, "tag");
                    if(tagFilter != "") {
                        if(item.Tags.some(function(i){
                            if(tagFilter.toLowerCase().indexOf(i.value.toLowerCase()) != -1) return true;
                            if(i.value.toLowerCase().indexOf(tagFilter.toLowerCase()) != -1) return true;
                            return false;
                        }) == true) return true;
                    }
                }
            }
            else if(item.ItemType == "FILE"){

            } 
            else if(item.ItemType == "SMS"){
                 // Not yet implemented
            }
            // return true to keep;
            return false;
        });
        console.log("Rows After Filter: ", json.DataCollection.length);
    }

    // Create Buffer
    if(json.DataCollection.length > StreamBuffer){
        console.log("Rows:", json.DataCollection.length, " (will be trimed to "+ StreamBuffer +")");
        // Always limit the Stream to {StreamBuffer}, users must search for messages further back
        json.DataCollection.splice(StreamBuffer);
    }

    $.each(json.DataCollection, function (i, item) {

        var IsToday = moment.utc(item.ItemDate.replace(" UTC", "")).isSame(moment.utc(), "day");
        var DateTime = "  " + moment.utc(item.ItemDate.replace(" UTC", "")).local().calendar(null, { sameElse: DisplayDateFormat });
        if(IsToday) DateTime = "  " + moment.utc(item.ItemDate.replace(" UTC", "")).local().format(DisplayTimeFormat);

        if (item.ItemType == "MSG") {
            // Add Chat Message
            // ===================
            var deliveryStatus = "<i class=\"fa fa-question-circle-o SendingMessage\"></i>";
            if(item.Sent == true) deliveryStatus = "<i class=\"fa fa-check SentMessage\"></i>";
            if(item.Sent == false) deliveryStatus = "<i class=\"fa fa-exclamation-circle FailedMessage\"></i>";
            if(item.Delivered) deliveryStatus += "<i class=\"fa fa-check DeliveredMessage\"></i>";

            var formattedMessage = ReformatMessage(item.MessageData);
            var longMessage = (formattedMessage.length > 1000);

            if (item.SrcUserId == profileUserID) {
                // You are the source (sending)
                if (formattedMessage.length != 0) {
                    var messageString = "<table class=\"ourChatMessage chatMessageTable\" cellspacing=0 cellpadding=0><tr>";
                    messageString += "<td class=ourChatMessageText onmouseenter=\"ShowChatMenu(this)\" onmouseleave=\"HideChatMenu(this)\">";
                    messageString += "<span onclick=\"ShowMessgeMenu(this,'MSG','"+  item.ItemId +"', '"+ buddyObj.identity +"')\" class=chatMessageDropdown style=\"display:none\"><i class=\"fa fa-chevron-down\"></i></span>";
                    messageString += "<div id=msg-text-"+ item.ItemId +" class=messageText style=\""+ ((longMessage)? "max-height:190px; overflow:hidden" : "") +"\">" + formattedMessage + "</div>";
                    if(longMessage){
                       messageString += "<div id=msg-readmore-"+  item.ItemId +" class=messageReadMore><span onclick=\"ExpandMessage(this,'"+ item.ItemId +"', '"+ buddyObj.identity +"')\">"+ lang.read_more +"</span></div>";
                    }

                    messageString += "<div class=messageDate>" + DateTime + " " + deliveryStatus +"</div>";
                    messageString += "</td>";
                    messageString += "</tr></table>";
                }
            } 
            else {
                // You are the destination (receiving)
                var ActualSender = "";
                if (formattedMessage.length != 0) {
                    var messageString = "<table class=\"theirChatMessage chatMessageTable\" cellspacing=0 cellpadding=0><tr>";
                    messageString += "<td class=theirChatMessageText onmouseenter=\"ShowChatMenu(this)\" onmouseleave=\"HideChatMenu(this)\">";
                    messageString += "<span onclick=\"ShowMessgeMenu(this,'MSG','"+  item.ItemId +"', '"+ buddyObj.identity +"')\" class=chatMessageDropdown style=\"display:none\"><i class=\"fa fa-chevron-down\"></i></span>";

                    if(buddyObj.type == "group"){
                       messageString += "<div class=messageDate>" + ActualSender + "</div>";
                    }
                    messageString += "<div id=msg-text-"+ item.ItemId +" class=messageText style=\""+ ((longMessage)? "max-height:190px; overflow:hidden" : "") +"\">" + formattedMessage + "</div>";
                    if(longMessage){
                       messageString += "<div id=msg-readmore-"+  item.ItemId +" class=messageReadMore><span onclick=\"ExpandMessage(this,'"+ item.ItemId +"', '"+ buddyObj.identity +"')\">"+ lang.read_more +"</span></div>";
                    }
                    messageString += "<div class=messageDate>"+ DateTime + "</div>";
                    messageString += "</td>";
                    messageString += "</tr></table>";
                }
            }
            if (formattedMessage.length != 0) {
                $("#contact-" + buddyObj.identity + "-ChatHistory").prepend(messageString);
            }
        } 
        else if (item.ItemType == "CDR") {
            // Add CDR 
            // =======
            var iconColor = (item.Billsec > 0)? "green" : "red";
            var formattedMessage = "";

            // Flagged
            var flag = "<span id=cdr-flagged-"+  item.CdrId +" style=\""+ ((item.Flagged)? "" : "display:none") +"\">";
            flag += "<i class=\"fa fa-flag FlagCall\"></i> ";
            flag += "</span>";

            // Comment
            var callComment = "";
            if(item.MessageData) callComment = item.MessageData;

            // Tags
            if(!item.Tags) item.Tags = [];
            var CallTags = "<ul id=cdr-tags-"+  item.CdrId +" class=tags style=\""+ ((item.Tags && item.Tags.length > 0)? "" : "display:none" ) +"\">"
            $.each(item.Tags, function (i, tag) {
                CallTags += "<li onclick=\"TagClick(this, '"+ item.CdrId +"', '"+ buddyObj.identity +"')\">"+ tag.value +"</li>";
            });
            CallTags += "<li class=tagText><input maxlength=24 type=text onkeypress=\"TagKeyPress(event, this, '"+ item.CdrId +"', '"+ buddyObj.identity +"')\" onfocus=\"TagFocus(this)\"></li>";
            CallTags += "</ul>";

            // Call Type
            var callIcon = (item.WithVideo)? "fa-video-camera" :  "fa-phone";
            formattedMessage += "<i class=\"fa "+ callIcon +"\" style=\"color:"+ iconColor +"\"></i>";
            var audioVideo = (item.WithVideo)? lang.a_video_call :  lang.an_audio_call;

            // Recordings
            var recordingsHtml = "";
            if(item.Recordings && item.Recordings.length >= 1){
                $.each(item.Recordings, function (i, recording) {
                    if(recording.uID){
                        var StartTime = moment.utc(recording.startTime.replace(" UTC", "")).local();
                        var StopTime = moment.utc(recording.stopTime.replace(" UTC", "")).local();
                        var recordingDuration = moment.duration(StopTime.diff(StartTime));
                        recordingsHtml += "<div class=callRecording>";
                        if(item.WithVideo){
                            if(recording.Poster){
                                var posterWidth = recording.Poster.width;
                                var posterHeight = recording.Poster.height;
                                var posterImage = recording.Poster.posterBase64;
                                recordingsHtml += "<div><IMG src=\""+ posterImage +"\"><button onclick=\"PlayVideoCallRecording(this, '"+ item.CdrId +"', '"+ recording.uID +"')\" class=videoPoster><i class=\"fa fa-play\"></i></button></div>";
                            }
                            else {
                                recordingsHtml += "<div><button onclick=\"PlayVideoCallRecording(this, '"+ item.CdrId +"', '"+ recording.uID +"', '"+ buddyObj.identity +"')\"><i class=\"fa fa-video-camera\"></i></button></div>";
                            }
                        } 
                        else {
                            recordingsHtml += "<div><button onclick=\"PlayAudioCallRecording(this, '"+ item.CdrId +"', '"+ recording.uID +"', '"+ buddyObj.identity +"')\"><i class=\"fa fa-play\"></i></button></div>";
                        } 
                        recordingsHtml += "<div>"+ lang.started +": "+ StartTime.format(DisplayTimeFormat) +" <i class=\"fa fa-long-arrow-right\"></i> "+ lang.stopped +": "+ StopTime.format(DisplayTimeFormat) +"</div>";
                        recordingsHtml += "<div>"+ lang.recording_duration +": "+ formatShortDuration(recordingDuration.asSeconds()) +"</div>";
                        recordingsHtml += "<div>";
                        recordingsHtml += "<span id=\"cdr-video-meta-width-"+ item.CdrId +"-"+ recording.uID +"\"></span>";
                        recordingsHtml += "<span id=\"cdr-video-meta-height-"+ item.CdrId +"-"+ recording.uID +"\"></span>";
                        recordingsHtml += "<span id=\"cdr-media-meta-size-"+ item.CdrId +"-"+ recording.uID +"\"></span>";
                        recordingsHtml += "<span id=\"cdr-media-meta-codec-"+ item.CdrId +"-"+ recording.uID +"\"></span>";
                        recordingsHtml += "</div>";
                        recordingsHtml += "</div>";
                    }
                });
            }

            if (item.SrcUserId == profileUserID) {
                // (Outbound) You(profileUserID) initiated a call
                if(item.Billsec == "0") {
                    formattedMessage += " "+ lang.you_tried_to_make +" "+ audioVideo +" ("+ item.ReasonText +").";
                } 
                else {
                    formattedMessage += " "+ lang.you_made + " "+ audioVideo +", "+ lang.and_spoke_for +" " + formatDuration(item.Billsec) + ".";
                }
                var messageString = "<table class=\"ourChatMessage chatMessageTable\" cellspacing=0 cellpadding=0><tr>"
                messageString += "<td style=\"padding-right:4px;\">" + flag + "</td>"
                messageString += "<td class=ourChatMessageText onmouseenter=\"ShowChatMenu(this)\" onmouseleave=\"HideChatMenu(this)\">";
                messageString += "<span onClick=\"ShowMessgeMenu(this,'CDR','"+  item.CdrId +"', '"+ buddyObj.identity +"')\" class=chatMessageDropdown style=\"display:none\"><i class=\"fa fa-chevron-down\"></i></span>";
                messageString += "<div>" + formattedMessage + "</div>";
                messageString += "<div>" + CallTags + "</div>";
                messageString += "<div id=cdr-comment-"+  item.CdrId +" class=cdrComment>" + callComment + "</div>";
                messageString += "<div class=callRecordings>" + recordingsHtml + "</div>";
                messageString += "<div class=messageDate>" + DateTime  + "</div>";
                messageString += "</td>"
                messageString += "</tr></table>";
            } 
            else {
                // (Inbound) you(profileUserID) received a call
                if(item.Billsec == "0"){
                    formattedMessage += " "+ lang.you_missed_a_call + " ("+ item.ReasonText +").";
                } 
                else {
                    formattedMessage += " "+ lang.you_recieved + " "+ audioVideo +", "+ lang.and_spoke_for +" " + formatDuration(item.Billsec) + ".";
                }

                var messageString = "<table class=\"theirChatMessage chatMessageTable\" cellspacing=0 cellpadding=0><tr>";
                messageString += "<td class=theirChatMessageText onmouseenter=\"ShowChatMenu(this)\" onmouseleave=\"HideChatMenu(this)\">";
                messageString += "<span onClick=\"ShowMessgeMenu(this,'CDR','"+  item.CdrId +"', '"+ buddyObj.identity +"')\" class=chatMessageDropdown style=\"display:none\"><i class=\"fa fa-chevron-down\"></i></span>";
                messageString += "<div style=\"text-align:left\">" + formattedMessage + "</div>";
                messageString += "<div>" + CallTags + "</div>";
                messageString += "<div id=cdr-comment-"+  item.CdrId +" class=cdrComment>" + callComment + "</div>";
                messageString += "<div class=callRecordings>" + recordingsHtml + "</div>";
                messageString += "<div class=messageDate> " + DateTime + "</div>";
                messageString += "</td>";
                messageString += "<td style=\"padding-left:4px\">" + flag + "</td>";
                messageString += "</tr></table>";
            }
            // Messges are reappended here, and appended when logging
            $("#contact-" + buddyObj.identity + "-ChatHistory").prepend(messageString);
        } 
        else if (item.ItemType == "FILE") {

            if (item.SrcUserId == profileUserID) {
                // File is sent
                var sentFileSection = "<table class=\"ourChatMessage chatMessageTable\" cellspacing=0 cellpadding=0><tr>"
                sentFileSection += "<td><div class='sentFileChatRect'>Download file<br><a href='download-sent-chat-file.php?s_ajax_call="+ validateSToken +"&destSipUser="+ item.Dst +"&sentFlNm="+ item.SentFileName +"' target='_blank'>"+ item.SentFileName +"</a>";
                sentFileSection += "<span style=\"display:block;width:100%;height:10px;\"></span><div class=\"messageDate\">"+ DateTime + "</div></div>";
                sentFileSection += "</td>";
                sentFileSection += "</tr></table>";

                $("#contact-" + buddyObj.identity + "-ChatHistory").prepend(sentFileSection);
                $("#sendFileLoader").remove();

            } else {
                // File is received
                var recFileSection = "<table class=\"theirChatMessage chatMessageTable\" cellspacing=0 cellpadding=0><tr>"
                recFileSection += "<td><div class='recFileChatRect'>Download file<br><a href='download-rec-chat-file.php?s_ajax_call="+ validateSToken +"&recSipUser="+ item.Dst +"&recFlNm="+ item.ReceivedFileName +"' target='_blank'>"+ item.ReceivedFileName +"</a>";

                recFileSection += "<span style=\"display:block;width:100%;height:10px;\"></span><div class=\"messageDate\">"+ DateTime + "</div></div>";
                recFileSection += "</td>";
                recFileSection += "</tr></table>";

                $("#contact-" + buddyObj.identity + "-ChatHistory").prepend(recFileSection);
            }
        } 
        else if(item.ItemType == "SMS"){

        }
    });

    // For some reason, the first time this fires, it doesn't always work
    updateScroll(buddyObj.identity);
    window.setTimeout(function(){
        updateScroll(buddyObj.identity);
    }, 300);
}
function ShowChatMenu(obj){
    $(obj).children("span").show();
}
function HideChatMenu(obj){
    $(obj).children("span").hide();
}
function ExpandMessage(obj, ItemId, buddy){
    $("#msg-text-" + ItemId).css("max-height", "");
    $("#msg-text-" + ItemId).css("overflow", "");
    $("#msg-readmore-" + ItemId).remove();

    $.jeegoopopup.close();
}
function ShowBuddyDial(obj, buddy){
    $("#contact-"+ buddy +"-email").show();
    $("#contact-"+ buddy +"-audio-dial").show();
    $("#contact-"+ buddy +"-video-dial").show();
}
function HideBuddyDial(obj, buddy){
    $("#contact-"+ buddy +"-email").hide();
    $("#contact-"+ buddy +"-audio-dial").hide();
    $("#contact-"+ buddy +"-video-dial").hide();
}
function QuickDialAudio(buddy, obj, event){
    AudioCallMenu(buddy, obj);
    event.stopPropagation();
}
function QuickDialVideo(buddy, ExtNo, event){
    event.stopPropagation();
    window.setTimeout(function(){
        DialByLine('video', buddy, ExtNo);
    }, 300);
}

// Sessions
// ========
function ExpandVideoArea(lineNum){
    $("#line-" + lineNum + "-ActiveCall").prop("class","FullScreenVideo");
    $("#line-" + lineNum + "-VideoCall").css("height", "calc(100% - 100px)");
    $("#line-" + lineNum + "-VideoCall").css("margin-top", "0px");

    $("#line-" + lineNum + "-preview-container").prop("class","PreviewContainer PreviewContainer_FS");
    $("#line-" + lineNum + "-stage-container").prop("class","StageContainer StageContainer_FS");

    $("#line-" + lineNum + "-restore").show();
    $("#line-" + lineNum + "-expand").hide();

    $("#line-" + lineNum + "-monitoring").hide();    
}
function RestoreVideoArea(lineNum){

    $("#line-" + lineNum + "-ActiveCall").prop("class","");
    $("#line-" + lineNum + "-VideoCall").css("height", "");
    $("#line-" + lineNum + "-VideoCall").css("margin-top", "10px");

    $("#line-" + lineNum + "-preview-container").prop("class","PreviewContainer");
    $("#line-" + lineNum + "-stage-container").prop("class","StageContainer");

    $("#line-" + lineNum + "-restore").hide();
    $("#line-" + lineNum + "-expand").show();

    $("#line-" + lineNum + "-monitoring").show();
}
function MuteSession(lineNum){
    $("#line-"+ lineNum +"-btn-Unmute").show();
    $("#line-"+ lineNum +"-btn-Mute").hide();

    var lineObj = FindLineByNumber(lineNum);
    if(lineObj == null || lineObj.SipSession == null) return;

    var session = lineObj.SipSession;
    var pc = session.sessionDescriptionHandler.peerConnection;
    pc.getSenders().forEach(function (RTCRtpSender) {
        if(RTCRtpSender.track.kind == "audio") {
            if(RTCRtpSender.track.IsMixedTrack == true){
                if(session.data.AudioSourceTrack && session.data.AudioSourceTrack.kind == "audio"){
                    console.log("Muting Audio Track : "+ session.data.AudioSourceTrack.label);
                    session.data.AudioSourceTrack.enabled = false;
                }
            }
            else {
                console.log("Muting Audio Track : "+ RTCRtpSender.track.label);
                RTCRtpSender.track.enabled = false;
            }
        }
    });

    if(!session.data.mute) session.data.mute = [];
    session.data.mute.push({ event: "mute", eventTime: utcDateNow() });
    session.data.ismute = true;

    $("#line-" + lineNum + "-msg").html(lang.call_on_mute);

    updateLineScroll(lineNum);

    // Custom Web hook
    if(typeof web_hook_on_modify !== 'undefined') web_hook_on_modify("mute", session);
}
function UnmuteSession(lineNum){
    $("#line-"+ lineNum +"-btn-Unmute").hide();
    $("#line-"+ lineNum +"-btn-Mute").show();

    var lineObj = FindLineByNumber(lineNum);
    if(lineObj == null || lineObj.SipSession == null) return;

    var session = lineObj.SipSession;
    var pc = session.sessionDescriptionHandler.peerConnection;
    pc.getSenders().forEach(function (RTCRtpSender) {
        if(RTCRtpSender.track.kind == "audio") {
            if(RTCRtpSender.track.IsMixedTrack == true){
                if(session.data.AudioSourceTrack && session.data.AudioSourceTrack.kind == "audio"){
                    console.log("Unmuting Audio Track : "+ session.data.AudioSourceTrack.label);
                    session.data.AudioSourceTrack.enabled = true;
                }
            }
            else {
                console.log("Unmuting Audio Track : "+ RTCRtpSender.track.label);
                RTCRtpSender.track.enabled = true;
            }
        }
    });

    if(!session.data.mute) session.data.mute = [];
    session.data.mute.push({ event: "unmute", eventTime: utcDateNow() });
    session.data.ismute = false;

    $("#line-" + lineNum + "-msg").html(lang.call_off_mute);

    updateLineScroll(lineNum);

    // Custom Web hook
    if(typeof web_hook_on_modify !== 'undefined') web_hook_on_modify("unmute", session);
}
function ShowDtmfMenu(obj, lineNum){

    var leftPos = event.pageX - 90;
    var topPos = event.pageY + 30;

    var html = "<div id=mainDtmfDialPad>";
    html += "<table cellspacing=10 cellpadding=0 style=\"margin-left:auto; margin-right: auto\">";
    html += "<tr><td><button class=dtmfButtons onclick=\"sendDTMF('"+ lineNum +"', '1');new Audio('sounds/dtmf.mp3').play();\"><div>1</div><span>&nbsp;</span></button></td>"
    html += "<td><button class=dtmfButtons onclick=\"sendDTMF('"+ lineNum +"', '2');new Audio('sounds/dtmf.mp3').play();\"><div>2</div><span>ABC</span></button></td>"
    html += "<td><button class=dtmfButtons onclick=\"sendDTMF('"+ lineNum +"', '3');new Audio('sounds/dtmf.mp3').play();\"><div>3</div><span>DEF</span></button></td></tr>";
    html += "<tr><td><button class=dtmfButtons onclick=\"sendDTMF('"+ lineNum +"', '4');new Audio('sounds/dtmf.mp3').play();\"><div>4</div><span>GHI</span></button></td>"
    html += "<td><button class=dtmfButtons onclick=\"sendDTMF('"+ lineNum +"', '5');new Audio('sounds/dtmf.mp3').play();\"><div>5</div><span>JKL</span></button></td>"
    html += "<td><button class=dtmfButtons onclick=\"sendDTMF('"+ lineNum +"', '6');new Audio('sounds/dtmf.mp3').play();\"><div>6</div><span>MNO</span></button></td></tr>";
    html += "<tr><td><button class=dtmfButtons onclick=\"sendDTMF('"+ lineNum +"', '7');new Audio('sounds/dtmf.mp3').play();\"><div>7</div><span>PQRS</span></button></td>"
    html += "<td><button class=dtmfButtons onclick=\"sendDTMF('"+ lineNum +"', '8');new Audio('sounds/dtmf.mp3').play();\"><div>8</div><span>TUV</span></button></td>"
    html += "<td><button class=dtmfButtons onclick=\"sendDTMF('"+ lineNum +"', '9');new Audio('sounds/dtmf.mp3').play();\"><div>9</div><span>WXYZ</span></button></td></tr>";
    html += "<tr><td><button class=dtmfButtons onclick=\"sendDTMF('"+ lineNum +"', '*');new Audio('sounds/dtmf.mp3').play();\">*</button></td>"
    html += "<td><button class=dtmfButtons onclick=\"sendDTMF('"+ lineNum +"', '0');new Audio('sounds/dtmf.mp3').play();\">0</button></td>"
    html += "<td><button class=dtmfButtons onclick=\"sendDTMF('"+ lineNum +"', '#');new Audio('sounds/dtmf.mp3').play();\">#</button></td></tr>";
    html += "</table>";
    html += "</div>";

    $.jeegoopopup.open({
                html: html,
                width: "auto",
                height: "auto",
                left: leftPos,
                top: topPos,
                scrolling: 'no',
                skinClass: 'jg_popup_basic',
                overlay: true,
                opacity: 0,
                draggable: true,
                resizable: false,
                fadeIn: 0
    });

    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); });
    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); } });
}

// Stream Functionality
// =====================
function ShowMessgeMenu(obj, typeStr, cdrId, buddy) {

    $.jeegoopopup.close();

    var leftPos = event.pageX;
    var topPos = event.pageY;

    if (($(window).width() - event.pageX) < (obj.offsetWidth + 50)) { leftPos = event.pageX - 200; }

    var menu = "<div id=\"messageMenu\">";
    menu += "<table id=\"messageMenuTable\" cellspacing=10 cellpadding=0 style=\"margin-left:auto; margin-right: auto\">";

    // CDR's Menu
    if (typeStr == "CDR") {
        var TagState = $("#cdr-flagged-"+ cdrId).is(":visible");
        var TagText = (TagState)? lang.clear_flag : lang.flag_call;
        menu += "<tr id=\"CMDetails_1\"><td><i class=\"fa fa-external-link\"></i></td><td class=\"callDetails\">"+ lang.show_call_detail_record +"</td></tr>";
        menu += "<tr id=\"CMDetails_2\"><td><i class=\"fa fa-tags\"></i></td><td class=\"callDetails\">"+ lang.tag_call +"</td></tr>";
        menu += "<tr id=\"CMDetails_3\"><td><i class=\"fa fa-flag\"></i></td><td class=\"callDetails\">"+ TagText +"</td></tr>";
        menu += "<tr id=\"CMDetails_4\"><td><i class=\"fa fa-quote-left\"></i></td><td class=\"callDetails\">"+ lang.edit_comment +"</td></tr>";
    }
    if (typeStr == "MSG") {
        menu += "<tr id=\"CMDetails_5\"><td><i class=\"fa fa-clipboard\"></i></td><td class=\"callDetails\">"+ lang.copy_message +"</td></tr>";
        menu += "<tr id=\"CMDetails_6\"><td><i class=\"fa fa-quote-left\"></i></td><td class=\"callDetails\">"+ lang.quote_message +"</td></tr>";
    }

    menu += "</table></div>";

    $.jeegoopopup.open({
                html: menu,
                width: 'auto',
                height: 'auto',
                left: leftPos,
                top: topPos,
                scrolling: 'no',
                skinClass: 'jg_popup_basic',
                overlay: true,
                opacity: 0,
                draggable: false,
                resizable: false,
                fadeIn: 0
    });

    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); });
    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); } });

    // CDR messages
    $("#CMDetails_1").click(function(event) {

            var cdr = null;
            var currentStream = JSON.parse(localDB.getItem(buddy + "-stream"));
            if(currentStream != null || currentStream.DataCollection != null){
                $.each(currentStream.DataCollection, function (i, item) {
                    if (item.ItemType == "CDR" && item.CdrId == cdrId) {
                        // Found
                        cdr = item;
                        return false;
                    }
                });
            }
            if(cdr == null) return;

            var callDetails = [];

            var html = '<div id="windowCtrls"><img id="minimizeImg" src="images/1_minimize.svg" title="Restore" /><img id="maximizeImg" src="images/2_maximize.svg" title="Maximize" /><img id="closeImg" src="images/3_close.svg" title="Close" /></div>';
            html += "<div class=\"UiWindowField scroller\">";

            var CallDate = moment.utc(cdr.ItemDate.replace(" UTC", "")).local().format(DisplayDateFormat +" "+ DisplayTimeFormat);
            var CallAnswer = (cdr.CallAnswer)? moment.utc(cdr.CallAnswer.replace(" UTC", "")).local().format(DisplayDateFormat +" "+ DisplayTimeFormat) : null ;
            var ringTime = (cdr.RingTime)? cdr.RingTime : 0 ;
            var CallEnd = moment.utc(cdr.CallEnd.replace(" UTC", "")).local().format(DisplayDateFormat +" "+ DisplayTimeFormat);

            var srcCallerID = "";
            var dstCallerID = "";
            if(cdr.CallDirection == "inbound") {
                srcCallerID = cdr.Src;
            } 
            else if(cdr.CallDirection == "outbound") {
                dstCallerID = cdr.Dst;
            }
            html += "<div class=UiText><b>SIP CallID</b> : "+ cdr.SessionId +"</div>";
            html += "<div class=UiText><b>"+ lang.call_direction +"</b> : "+ cdr.CallDirection +"</div>";
            html += "<div class=UiText><b>"+ lang.call_date_and_time +"</b> : "+ CallDate +"</div>";
            html += "<div class=UiText><b>"+ lang.ring_time +"</b> : "+ formatDuration(ringTime) +" ("+ ringTime +")</div>";
            html += "<div class=UiText><b>"+ lang.talk_time +"</b> : " + formatDuration(cdr.Billsec) +" ("+ cdr.Billsec +")</div>";
            html += "<div class=UiText><b>"+ lang.call_duration +"</b> : "+ formatDuration(cdr.TotalDuration) +" ("+ cdr.TotalDuration +")</div>";
            html += "<div class=UiText><b>"+ lang.video_call +"</b> : "+ ((cdr.WithVideo)? lang.yes : lang.no) +"</div>";
            html += "<div class=UiText><b>"+ lang.flagged +"</b> : "+ ((cdr.Flagged)? "<i class=\"fa fa-flag FlagCall\"></i> " + lang.yes : lang.no)  +"</div>";
            html += "<hr>";
            html += "<h2 style=\"font-size: 16px\">"+ lang.call_tags +"</h2>";
            html += "<hr>";
            $.each(cdr.Tags, function(item, tag){
                html += "<span class=cdrTag>"+ tag.value +"</span>"
            });

            html += "<h2 style=\"font-size: 16px\">"+ lang.call_notes +"</h2>";
            html += "<hr>";
            if(cdr.MessageData){
                html += "\"" + cdr.MessageData + "\"";
            }

            html += "<h2 style=\"font-size: 16px\">"+ lang.activity_timeline +"</h2>";
            html += "<hr>";

            var withVideo = (cdr.WithVideo)? "("+ lang.with_video +")" : "";
            var startCallMessage = (cdr.CallDirection == "inbound")? lang.you_received_a_call_from + " " + srcCallerID  +" "+ withVideo : lang.you_made_a_call_to + " " + dstCallerID +" "+ withVideo;
            callDetails.push({ 
                Message: startCallMessage,
                TimeStr: cdr.ItemDate
            });
            if(CallAnswer){
                var answerCallMessage = (cdr.CallDirection == "inbound")? lang.you_answered_after + " " + ringTime + " " + lang.seconds_plural : lang.they_answered_after + " " + ringTime + " " + lang.seconds_plural;
                callDetails.push({ 
                    Message: answerCallMessage,
                    TimeStr: cdr.CallAnswer
                });
            }
            $.each(cdr.Transfers, function(item, transfer){
                var msg = (transfer.type == "Blind")? lang.you_started_a_blind_transfer_to +" "+ transfer.to +". " : lang.you_started_an_attended_transfer_to + " "+ transfer.to +". ";
                if(transfer.accept && transfer.accept.complete == true){
                    msg += lang.the_call_was_completed
                }
                else if(transfer.accept.disposition != "") {
                    msg += lang.the_call_was_not_completed +" ("+ transfer.accept.disposition +")"
                }
                callDetails.push({
                    Message : msg,
                    TimeStr : transfer.transferTime
                });
            });
            $.each(cdr.Mutes, function(item, mute){
                callDetails.push({
                    Message : (mute.event == "mute")? lang.you_put_the_call_on_mute : lang.you_took_the_call_off_mute,
                    TimeStr : mute.eventTime
                });
            });
            $.each(cdr.Holds, function(item, hold){
                callDetails.push({
                    Message : (hold.event == "hold")? lang.you_put_the_call_on_hold : lang.you_took_the_call_off_hold,
                    TimeStr : hold.eventTime
                });
            });
            $.each(cdr.ConfCalls, function(item, confCall){
                var msg = lang.you_started_a_conference_call_to +" "+ confCall.to +". ";
                if(confCall.accept && confCall.accept.complete == true){
                    msg += lang.the_call_was_completed
                }
                else if(confCall.accept.disposition != "") {
                    msg += lang.the_call_was_not_completed +" ("+ confCall.accept.disposition +")"
                }
                callDetails.push({
                    Message : msg,
                    TimeStr : confCall.startTime
                });
            });
            $.each(cdr.Recordings, function(item, recording){
                var StartTime = moment.utc(recording.startTime.replace(" UTC", "")).local();
                var StopTime = moment.utc(recording.stopTime.replace(" UTC", "")).local();
                var recordingDuration = moment.duration(StopTime.diff(StartTime));

                var msg = lang.call_is_being_recorded;
                if(recording.startTime != recording.stopTime){
                    msg += "("+ formatShortDuration(recordingDuration.asSeconds()) +")"
                }
                callDetails.push({
                    Message : msg,
                    TimeStr : recording.startTime
                });
            });
            callDetails.push({
                Message: (cdr.Terminate == "us")? "You ended the call." : "They ended the call",
                TimeStr : cdr.CallEnd
            });

            callDetails.sort(function(a, b){
                var aMo = moment.utc(a.TimeStr.replace(" UTC", ""));
                var bMo = moment.utc(b.TimeStr.replace(" UTC", ""));
                if (aMo.isSameOrAfter(bMo, "second")) {
                    return 1;
                } else return -1;
                return 0;
            });
            $.each(callDetails, function(item, detail){
                var Time = moment.utc(detail.TimeStr.replace(" UTC", "")).local().format(DisplayTimeFormat);
                var messageString = "<table class=timelineMessage cellspacing=0 cellpadding=0><tr>"
                messageString += "<td class=timelineMessageArea>"
                messageString += "<div class=timelineMessageDate style=\"color: #333333\"><i class=\"fa fa-circle timelineMessageDot\"></i>"+ Time +"</div>"
                messageString += "<div class=timelineMessageText style=\"color: #000000\">"+ detail.Message +"</div>"
                messageString += "</td>"
                messageString += "</tr></table>";
                html += messageString;
            });

            html += "<h2 style=\"font-size: 16px\">"+ lang.call_recordings +"</h2>";
            html += "<hr>";
            var recordingsHtml = "";
            $.each(cdr.Recordings, function(r, recording){
                if(recording.uID){
                    var StartTime = moment.utc(recording.startTime.replace(" UTC", "")).local();
                    var StopTime = moment.utc(recording.stopTime.replace(" UTC", "")).local();
                    var recordingDuration = moment.duration(StopTime.diff(StartTime));
                    recordingsHtml += "<div>";
                    if(cdr.WithVideo){
                        recordingsHtml += "<div><video id=\"callrecording-video-"+ recording.uID +"\" controls style=\"width: 100%\"></div>";
                    } 
                    else {
                        recordingsHtml += "<div><audio id=\"callrecording-audio-"+ recording.uID +"\" controls style=\"width: 100%\"></div>";
                    } 
                    recordingsHtml += "<div>"+ lang.started +": "+ StartTime.format(DisplayTimeFormat) +" <i class=\"fa fa-long-arrow-right\"></i> "+ lang.stopped +": "+ StopTime.format(DisplayTimeFormat) +"</div>";
                    recordingsHtml += "<div>"+ lang.recording_duration +": "+ formatShortDuration(recordingDuration.asSeconds()) +"</div>";
                    recordingsHtml += "<div><a id=\"download-"+ recording.uID +"\">"+ lang.save_as +"</a> ("+ lang.right_click_and_select_save_link_as +")</div>";
                    recordingsHtml += "</div>";
                }
            });
            html += recordingsHtml;

            html += "<h2 style=\"font-size: 16px\">"+ lang.send_statistics +"</h2>";
            html += "<hr>";

            html += "<div style=\"position: relative; margin: auto; height: 160px; width: 100%;\"><canvas id=\"cdr-AudioSendBitRate\"></canvas></div>";
            html += "<div style=\"position: relative; margin: auto; height: 160px; width: 100%;\"><canvas id=\"cdr-AudioSendPacketRate\"></canvas></div>";

            html += "<h2 style=\"font-size: 16px\">"+ lang.receive_statistics +"</h2>";
            html += "<hr>";

            html += "<div style=\"position: relative; margin: auto; height: 160px; width: 100%;\"><canvas id=\"cdr-AudioReceiveBitRate\"></canvas></div>";
            html += "<div style=\"position: relative; margin: auto; height: 160px; width: 100%;\"><canvas id=\"cdr-AudioReceivePacketRate\"></canvas></div>";
            html += "<div style=\"position: relative; margin: auto; height: 160px; width: 100%;\"><canvas id=\"cdr-AudioReceivePacketLoss\"></canvas></div>";
            html += "<div style=\"position: relative; margin: auto; height: 160px; width: 100%;\"><canvas id=\"cdr-AudioReceiveJitter\"></canvas></div>";
            html += "<div style=\"position: relative; margin: auto; height: 160px; width: 100%;\"><canvas id=\"cdr-AudioReceiveLevels\"></canvas></div>";

            html += "<br><br></div>";

            $.jeegoopopup.close();

            $.jeegoopopup.open({
                title: 'Call Statistics',
                html: html,
                width: '640',
                height: '500',
                center: true,
                scrolling: 'no',
                skinClass: 'jg_popup_basic',
                overlay: true,
                opacity: 50,
                draggable: true,
                resizable: false,
                fadeIn: 0
            });

            $("#jg_popup_b").append('<button id="ok_button">'+ lang.ok +'</button>');

            // Display QOS data
            DisplayQosData(cdr.SessionId);


	    var maxWidth = $(window).width() - 12;
	    var maxHeight = $(window).height() - 88;

	    if (maxWidth < 656 || maxHeight < 500) { 
	       $.jeegoopopup.width(maxWidth).height(maxHeight);
	       $.jeegoopopup.center();
	       $("#maximizeImg").hide();
	       $("#minimizeImg").hide();
	    } else { 
	       $.jeegoopopup.width(640).height(500);
	       $.jeegoopopup.center();
	       $("#minimizeImg").hide();
	       $("#maximizeImg").show();
	    }

	    $(window).resize(function() {
	       maxWidth = $(window).width() - 12;
	       maxHeight = $(window).height() - 88;
	       $.jeegoopopup.center();
	       if (maxWidth < 656 || maxHeight < 500) { 
		   $.jeegoopopup.width(maxWidth).height(maxHeight);
		   $.jeegoopopup.center();
		   $("#maximizeImg").hide();
		   $("#minimizeImg").hide();
	       } else { 
		   $.jeegoopopup.width(640).height(500);
		   $.jeegoopopup.center();
		   $("#minimizeImg").hide();
		   $("#maximizeImg").show();
	       }
	    });

	   
	    $("#minimizeImg").click(function() { $.jeegoopopup.width(640).height(500); $.jeegoopopup.center(); $("#maximizeImg").show(); $("#minimizeImg").hide(); });
	    $("#maximizeImg").click(function() { $.jeegoopopup.width(maxWidth).height(maxHeight); $.jeegoopopup.center(); $("#minimizeImg").show(); $("#maximizeImg").hide(); });

	    $("#closeImg").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
	    $("#ok_button").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
	    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
	    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); $("#jg_popup_b").empty(); } });


            // Queue video and audio
            $.each(cdr.Recordings, function(r, recording){
                    var mediaObj = null;
                    if(cdr.WithVideo){
                        mediaObj = $("#callrecording-video-"+ recording.uID).get(0);
                    }
                    else {
                        mediaObj = $("#callrecording-audio-"+ recording.uID).get(0);
                    }
                    var downloadURL = $("#download-"+ recording.uID);

                    // Playback device
                    var sinkId = getAudioOutputID();
                    if (typeof mediaObj.sinkId !== 'undefined') {
                        mediaObj.setSinkId(sinkId).then(function(){
                            console.log("sinkId applied: "+ sinkId);
                        }).catch(function(e){
                            console.warn("Error using setSinkId: ", e);
                        });
                    } else {
                        console.warn("setSinkId() is not possible using this browser.")
                    }

                    // Get Call Recording
                    var indexedDB = window.indexedDB;
                    var request = indexedDB.open("CallRecordings");
                    request.onerror = function(event) {
                        console.error("IndexDB Request Error:", event);
                    }
                    request.onupgradeneeded = function(event) {
                        console.warn("Upgrade Required for IndexDB... probably because of first time use.");
                    }
                    request.onsuccess = function(event) {
                        console.log("IndexDB connected to CallRecordings");

                        var IDB = event.target.result;
                        if(IDB.objectStoreNames.contains("Recordings") == false){
                            console.warn("IndexDB CallRecordings.Recordings does not exists");
                            return;
                        } 

                        var transaction = IDB.transaction(["Recordings"]);
                        var objectStoreGet = transaction.objectStore("Recordings").get(recording.uID);
                        objectStoreGet.onerror = function(event) {
                            console.error("IndexDB Get Error:", event);
                        }
                        objectStoreGet.onsuccess = function(event) {
                            var mediaBlobUrl = window.URL.createObjectURL(event.target.result.mediaBlob);
                            mediaObj.src = mediaBlobUrl;

                            // Download Link
                            if(cdr.WithVideo){
                                downloadURL.prop("download",  "Video-Call-Recording-"+ recording.uID +".webm");
                            }
                            else {
                                downloadURL.prop("download",  "Audio-Call-Recording-"+ recording.uID +".webm");
                            }
                            downloadURL.prop("href", mediaBlobUrl);
                        }
                    }

            });

    });

    $("#CMDetails_2").click(function(event) {
            $("#cdr-tags-"+ cdrId).show();

            $.jeegoopopup.close();
    });

    $("#CMDetails_3").click(function(event) {
            // Tag / Untag Call
            var TagState = $("#cdr-flagged-"+ cdrId).is(":visible");
            if(TagState){
                console.log("Clearing Flag from: ", cdrId);
                $("#cdr-flagged-"+ cdrId).hide();

                // Update DB
                var currentStream = JSON.parse(localDB.getItem(buddy + "-stream"));
                if(currentStream != null || currentStream.DataCollection != null){
                    $.each(currentStream.DataCollection, function (i, item) {
                        if (item.ItemType == "CDR" && item.CdrId == cdrId) {
                            // Found
                            item.Flagged = false;
                            return false;
                        }
                    });
                    localDB.setItem(buddy + "-stream", JSON.stringify(currentStream));
                }
            }
            else {
                console.log("Flag Call: ", cdrId);
                $("#cdr-flagged-"+ cdrId).show();

                // Update DB
                var currentStream = JSON.parse(localDB.getItem(buddy + "-stream"));
                if(currentStream != null || currentStream.DataCollection != null){
                    $.each(currentStream.DataCollection, function (i, item) {
                        if (item.ItemType == "CDR" && item.CdrId == cdrId) {
                            // Found
                            item.Flagged = true;
                            return false;
                        }
                    });
                    localDB.setItem(buddy + "-stream", JSON.stringify(currentStream));
                }
            }

            $.jeegoopopup.close();
    });

    $("#CMDetails_4").click(function(event) {

            var currentText = $("#cdr-comment-"+ cdrId).text();
            $("#cdr-comment-"+ cdrId).empty();

            var textboxObj = $("<input maxlength=500 type=text>").appendTo("#cdr-comment-"+ cdrId);
            textboxObj.on("focus", function(){
                $.jeegoopopup.close();
            });
            textboxObj.on("blur", function(){
                var newText = $(this).val();
                SaveComment(cdrId, buddy, newText);
            });
            textboxObj.keypress(function(event){
                window.setTimeout(function(){

                      $.jeegoopopup.close();

                }, 500);

                var keycode = (event.keyCode ? event.keyCode : event.which);
                if (keycode == '13') {
                    event.preventDefault();

                    var newText = $(this).val();
                    SaveComment(cdrId, buddy, newText);
                }
            });
            textboxObj.val(currentText);
            textboxObj.focus();

            $.jeegoopopup.close();
    });

    $("#CMDetails_5").click(function(event) {
        // Text Messages
            var msgtext = $("#msg-text-"+ cdrId).text();
            navigator.clipboard.writeText(msgtext).then(function(){
                console.log("Text coppied to the clipboard:", msgtext);
            }).catch(function(){
                console.error("Error writing to the clipboard:", e);
            });

            $.jeegoopopup.close();
    });

    $("#CMDetails_6").click(function(event) {

            var msgtext = $("#msg-text-"+ cdrId).text();
            msgtext = "\""+ msgtext + "\"";
            var textarea = $("#contact-"+ buddy +"-ChatMessage");
            console.log("Quote Message:", msgtext);
            textarea.val(msgtext +"\n" + textarea.val());

            $.jeegoopopup.close();
    });

}
function SaveComment(cdrId, buddy, newText){
    console.log("Setting Comment:", newText);

    $("#cdr-comment-"+ cdrId).empty();
    $("#cdr-comment-"+ cdrId).append(newText);

    // Update DB
    var currentStream = JSON.parse(localDB.getItem(buddy + "-stream"));
    if(currentStream != null || currentStream.DataCollection != null){
        $.each(currentStream.DataCollection, function (i, item) {
            if (item.ItemType == "CDR" && item.CdrId == cdrId) {
                // Found
                item.MessageData = newText;
                return false;
            }
        });
        localDB.setItem(buddy + "-stream", JSON.stringify(currentStream));
    }
}
function TagKeyPress(event, obj, cdrId, buddy){

    $.jeegoopopup.close();

    var keycode = (event.keyCode ? event.keyCode : event.which);
    if (keycode == '13' || keycode == '44') {
        event.preventDefault();

        if ($(obj).val() == "") return;

        console.log("Adding Tag:", $(obj).val());

        $("#cdr-tags-"+ cdrId+" li:last").before("<li onclick=\"TagClick(this, '"+ cdrId +"', '"+ buddy +"')\">"+ $(obj).val() +"</li>");
        $(obj).val("");

        // Update DB
        UpdateTags(cdrId, buddy);
    }
}
function TagClick(obj, cdrId, buddy){
    window.setTimeout(function(){
       $.jeegoopopup.close();
    }, 500);

    console.log("Removing Tag:", $(obj).text());
    $(obj).remove();

    // Dpdate DB
    UpdateTags(cdrId, buddy);
}
function UpdateTags(cdrId, buddy){
    var currentStream = JSON.parse(localDB.getItem(buddy + "-stream"));
    if(currentStream != null || currentStream.DataCollection != null){
        $.each(currentStream.DataCollection, function (i, item) {
            if (item.ItemType == "CDR" && item.CdrId == cdrId) {
                // Found
                item.Tags = [];
                $("#cdr-tags-"+ cdrId).children('li').each(function () {
                    if($(this).prop("class") != "tagText") item.Tags.push({ value: $(this).text() });
                });
                return false;
            }
        });
        localDB.setItem(buddy + "-stream", JSON.stringify(currentStream));
    }
}

function TagFocus(obj){
      $.jeegoopopup.close();
}
function SendFile(buddy) {

      $('#selectedFile').val('');
      $("#upFile").empty();

      var buddyObj = FindBuddyByIdentity(buddy);
      var uploadfile = '<form id="sendFileFormChat" enctype="multipart/form-data">';
      uploadfile += '<input type="hidden" name="MAX_FILE_SIZE" value="786432000" />';
      uploadfile += '<input type="hidden" name="sipUser" value="'+ buddyObj.ExtNo +'" />';
      uploadfile += '<input type="hidden" name="s_ajax_call" value="'+ validateSToken +'" />';
      uploadfile += '<label for="selectedFile" class="customBrowseButton">Select File</label>';
      uploadfile += '<span id="upFile"></span>';
      uploadfile += '<input type="file" id="selectedFile" name="uploadedFile" />';
      uploadfile += '<input type="submit" id="submitFileChat" value="Send File" style="visibility:hidden;"/>';
      uploadfile += '</form>';

      if ($("#sendFileFormChat").is(":visible")) {
          $("#sendFileFormChat").remove();
          sendFileCheck = 0;
      } else {
          sendFileCheck = 1;
          $("#contact-"+ buddy +"-ChatMessage").before(uploadfile);
          $("#sendFileFormChat").css("display", "block");

          $("#selectedFile").bind("change", function() {
             upFileName = $(this).val().split('\\').pop();
             if (/^[a-zA-Z0-9\-\_\.]+$/.test(upFileName)) {
                 $("#upFile").html(upFileName);
             } else { 
                   $("#sendFileFormChat").remove();
                   sendFileCheck = 0;
                   alert("The name of the uploaded file is not valid!");
             }
          });
      }
}

function ShowEmojiBar(buddy) {

    var messageContainer = $("#contact-"+ buddy +"-emoji-menu");
    var textarea = $("#contact-"+ buddy +"-ChatMessage");

    if (messageContainer.is(":visible")) { messageContainer.hide(); } else { messageContainer.show(); }

    var menuBar = $("<div>");
    menuBar.prop("class", "emojiButton")
    var emojis = ["😀","😁","😂","😃","😄","😅","😆","😊","😦","😉","😊","😋","😌","😍","😎","😏","😐","😑","😒","😓","😔","😕","😖","😗","😘","😙","😚","😛","😜","😝","😞","😟","😠","😡","😢","😣","😤","😥","😦","😧","😨","😩","😪","😫","😬","😭","😮","😯","😰","😱","😲","😳","😴","😵","😶","😷","🙁","🙂","🙃","🙄","🤐","🤑","🤒","🤓","🤔","🤕","🤠","🤡","🤢","🤣","🤤","🤥","🤧","🤨","🤩","🤪","🤫","🤬","🥺","🤭","🤯","🧐"];
    $.each(emojis, function(i,e){
        var emoji = $("<button>");
        emoji.html(e);
        emoji.on('click', function() {
            var i = textarea.prop('selectionStart');
            var v = textarea.val();
            textarea.val(v.substring(0, i) + " " + $(this).html() + v.substring(i, v.length) + " ");

            messageContainer.hide();
            textarea.focus();
            updateScroll(buddy);
        });
        menuBar.append(emoji);
    });

    $(".chatMessage,.chatHistory").on('click', function(){
        messageContainer.hide();
    });

    messageContainer.empty();
    messageContainer.append(menuBar);

    updateScroll(buddy);
}

// My Profile
// ==========
function ShowMyProfileMenu(obj){

    var leftPos = obj.offsetWidth - 254;
    var topPos = obj.offsetHeight + 56 ;

    var usrRoleFromDB = getDbItem("userrole", "");
    if (usrRoleFromDB == "superadmin") { var usrRole = "(superadmin)"; } else { var usrRole = ""; }
    var currentUser = '<font style=\'color:#000000;cursor:auto;\'>' + userName + ' ' + usrRole + '</font>';

    var autoAnswerCheck = AutoAnswerEnabled ? "<i class='fa fa-check' style='float:right;'></i>" : "";
    var doNotDisturbCheck = DoNotDisturbEnabled ? "<i class='fa fa-check' style='float:right;'></i>" : "";
    var callWaitingCheck = CallWaitingEnabled ? "<i class='fa fa-check' style='float:right;'></i>" : "";

    var menu = "<div id=userMenu>";
    menu += "<table id=userMenuTable cellspacing=10 cellpadding=0 style=\"margin-left:auto; margin-right: auto\">";
    menu += "<tr id=userMenu_1><td><i class=\"fa fa-phone\"></i>&nbsp; "+ lang.auto_answer + "<span id=\"autoAnswerTick\">" + autoAnswerCheck + "</span></td></tr>";
    menu += "<tr id=userMenu_2><td><i class=\"fa fa-ban\"></i>&nbsp; "+ lang.do_not_disturb + "<span id=\"doNotDisturbTick\">" + doNotDisturbCheck + "</span></td></tr>";
    menu += "<tr id=userMenu_3><td><i class=\"fa fa-volume-control-phone\"></i>&nbsp; "+ lang.call_waiting + "<span id=\"callWaitingTick\">" + callWaitingCheck + "</span></td></tr>";
    menu += "<tr id=userMenu_4><td><i class=\"fa fa-refresh\"></i>&nbsp; "+ lang.refresh_registration + "</td></tr>";
    menu += "<tr id=userMenu_5><td><i class=\"fa fa-user-plus\"></i>&nbsp; "+ lang.add_contact + "</td></tr>";
    menu += "<tr id=userMenu_6><td><font style=\'color:#000000;cursor:auto;\'>"+ lang.logged_in_as + "</font></td></tr>";
    menu += "<tr id=userMenu_7><td><span style='width:20px;'></span>" + currentUser + "</td></tr>";
    menu += "<tr id=userMenu_8><td><i class=\"fa fa-power-off\"></i>&nbsp; "+ lang.log_out + "</td></tr>";
    menu += "</table>";
    menu += "</div>";  

    $.jeegoopopup.open({
                html: menu,
                width: 'auto',
                height: 'auto',
                left: '56',
                top: topPos,
                scrolling: 'no',
                skinClass: 'jg_popup_basic',
                innerClass: 'userMenuInner',
                contentClass: 'userMenuContent',
                overlay: true,
                opacity: 0,
                draggable: false,
                resizable: false,
                fadeIn: 0
    });

    $(window).resize(function() {
      $.jeegoopopup.width('auto').height('auto').left('56').top(topPos);   
    });

    $("#userMenu_1").click(function() {
      ToggleAutoAnswer();
      if (AutoAnswerEnabled) {
          $("#autoAnswerTick").append("<i class='fa fa-check' style='float:right;'></i>");
      } else {
          $("#autoAnswerTick").empty();
      } 
    });
    $("#userMenu_2").click(function() {
      ToggleDoNoDisturb();
      if (DoNotDisturbEnabled) {
          $("#doNotDisturbTick").append("<i class='fa fa-check' style='float:right;'></i>");
      } else {
          $("#doNotDisturbTick").empty();
      } 
    });
    $("#userMenu_3").click(function() {
      ToggleCallWaiting();
      if (CallWaitingEnabled) {
          $("#callWaitingTick").append("<i class='fa fa-check' style='float:right;'></i>");
      } else {
          $("#callWaitingTick").empty();
      }
    });
    $("#userMenu_4").click(function() { RefreshRegistration(); });
    $("#userMenu_5").click(function() { AddSomeoneWindow(); });
    $("#userMenu_8").click(function() { SignOut(); });

    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); });
    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); } });
}

function ShowLaunchVidConfMenu(obj){

    var leftPos = obj.offsetWidth + 121;
    var rightPos = 0;
    var topPos = obj.offsetHeight + 117;

    if ($(window).width() <= 915) {
        leftPos = event.pageX + obj.offsetWidth - 113;
        rightPos = 0;
        topPos = event.pageY + obj.offsetHeight - 11;
    }

    var vcmenu = "<div id=videoConfMenu>";
    vcmenu += "<table id=lauchVConfTable cellspacing=0 cellpadding=0 style=\"margin: 0px\">";
    vcmenu += "<tr id=launchVConfMenu_1><td><i class=\"fa fa-users\"></i>&nbsp; "+ lang.launch_video_conference + "</td></tr>";
    vcmenu += "</table>";
    vcmenu += "</div>";

    $.jeegoopopup.open({
                html: vcmenu,
                width: '228',
                height: '22',
                left: leftPos,
                right: rightPos,
                top: topPos,
                scrolling: 'no',
                skinClass: 'jg_popup_basic',
                overlay: true,
                opacity: 0,
                draggable: false,
                resizable: false,
                fadeIn: 0
    });

    $(window).resize(function() {
      $.jeegoopopup.width('228').height('22').left(leftPos).top(topPos);   
    });

    if ($(window).width() <= 915) { $.jeegoopopup.right(6); } else { $.jeegoopopup.width('228').height('22').left(leftPos).top(topPos); }

    $("#launchVConfMenu_1").click(function() { LaunchVideoConference(); $.jeegoopopup.close(); });
    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); });
    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); } });
}

function ShowAccountSettingsMenu(obj) {

    $.jeegoopopup.close();

    var leftPos = obj.offsetWidth + 212;
    var rightPos = 0;
    var topPos = obj.offsetHeight + 117;

    if ($(window).width() <= 915) {

        leftPos = event.pageX - 32;
        rightPos = 0;
        topPos = event.pageY + 11;
    }

    var setconfmenu = "<div id=settingsCMenu>";
    setconfmenu += "<table id=lauchSetConfTable cellspacing=0 cellpadding=0 style=\"margin: 0px\">";
    setconfmenu += "<tr id=settingsCMenu_1><td><i class=\"fa fa-wrench\"></i>&nbsp; "+ lang.account_settings + "</td></tr>";
    setconfmenu += "</table>";
    setconfmenu += "</div>";

    $.jeegoopopup.open({
                html: setconfmenu,
                width: '94',
                height: '22',
                left: leftPos,
                right: rightPos,
                top: topPos,
                scrolling: 'no',
                skinClass: 'jg_popup_basic',
                overlay: true,
                opacity: 0,
                draggable: false,
                resizable: false,
                fadeIn: 0
    });

    $(window).resize(function() {
      $.jeegoopopup.width('94').height('22').left(leftPos).top(topPos);   
    });

    if ($(window).width() <= 915) { $.jeegoopopup.right(6); } else { $.jeegoopopup.width('94').height('22').left(leftPos).top(topPos); }

    $("#settingsCMenu_1").click(function() { ConfigureExtensionWindow(); });
    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); });
    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); } });
}

function RefreshRegistration(){
    Unregister();
    console.log("Unregister complete...");
    window.setTimeout(function(){
        console.log("Starting registration...");
        Register();
    }, 1000);
}

function SignOut() {

    if (getDbItem("useRoundcube", "") == 1 && RCLoginCheck == 1) {

        // Log out from Roundcube
        $("#roundcubeFrame").remove();
        $("#rightContent").show();
        $(".streamSelected").each(function() { $(this).css("display", "none"); });
        $("#rightContent").append('<iframe id="rcLogoutFrame" name="logoutFrame"></iframe>');


        var logoutURL = "https://"+ getDbItem("rcDomain", "") +"/";

        var logoutform = '<form id="rcloForm" method="POST" action="'+ logoutURL +'" target="logoutFrame">'; 
        logoutform += '<input type="hidden" name="_action" value="logout" />';
        logoutform += '<input type="hidden" name="_task" value="logout" />';
        logoutform += '<input type="hidden" name="_autologout" value="1" />';
        logoutform += '<input id="submitloButton" type="submit" value="Logout" />';
        logoutform += '</form>';

        $("#rcLogoutFrame").append(logoutform);
        $("#submitloButton").click();
        RCLoginCheck == 0;
    }

    // Remove the 'uploads' directory used to temporarily store files received during text chat
    removeTextChatUploads(getDbItem("SipUsername", ""));

    setTimeout(function() {

       // Check if there are any configured external video conference users
       var externalLinks = getDbItem("externalUserConfElem", "");

       if (typeof externalLinks !== 'undefined' && externalLinks != null && externalLinks != 0) {

           checkExternalLinks();

       } else {
           Unregister();
           console.log("Signing Out ...");
           localStorage.clear();
           if (winVideoConf != null) {
               winVideoConf.close();
           }
           window.open('https://' + window.location.host + '/logout.php', '_self');
       }
    }, 100);
}

function ToggleAutoAnswer(){
    if(AutoAnswerPolicy == "disabled"){
        AutoAnswerEnabled = false;
        console.warn("Policy AutoAnswer: Disabled");
        return;
    }
    AutoAnswerEnabled = (AutoAnswerEnabled == true)? false : true;
    if(AutoAnswerPolicy == "enabled") AutoAnswerEnabled = true;
    localDB.setItem("AutoAnswerEnabled", (AutoAnswerEnabled == true)? "1" : "0");
    console.log("AutoAnswer:", AutoAnswerEnabled);
}
function ToggleDoNoDisturb(){
    if(DoNotDisturbPolicy == "disabled"){
        DoNotDisturbEnabled = false;
        console.warn("Policy DoNotDisturb: Disabled");
        return;
    }
    DoNotDisturbEnabled = (DoNotDisturbEnabled == true)? false : true;
    if(DoNotDisturbPolicy == "enabled") DoNotDisturbEnabled = true;
    localDB.setItem("DoNotDisturbEnabled", (DoNotDisturbEnabled == true)? "1" : "0");
    $("#dereglink").attr("class", (DoNotDisturbEnabled == true)? "dotDoNotDisturb" : "dotOnline" );
    console.log("DoNotDisturb", DoNotDisturbEnabled);
}
function ToggleCallWaiting(){
    if(CallWaitingPolicy == "disabled"){
        CallWaitingEnabled = false;
        console.warn("Policy CallWaiting: Disabled");
        return;
    }
    CallWaitingEnabled = (CallWaitingEnabled == true)? false : true;
    if(CallWaitingPolicy == "enabled") CallWaitingPolicy = true;
    localDB.setItem("CallWaitingEnabled", (CallWaitingEnabled == true)? "1" : "0");
    console.log("CallWaiting", CallWaitingEnabled);
}
function ToggleRecordAllCalls(){
    if(CallRecordingPolicy == "disabled"){
        RecordAllCalls = false;
        console.warn("Policy CallRecording: Disabled");
        return;
    }
    RecordAllCalls = (RecordAllCalls == true)? false : true;
    if(CallRecordingPolicy == "enabled") RecordAllCalls = true;
    localDB.setItem("RecordAllCalls", (RecordAllCalls == true)? "1" : "0");
    console.log("RecordAllCalls", RecordAllCalls);
}

function ShowBuddyProfileMenu(buddy, obj, typeStr){

    $.jeegoopopup.close();

    leftPos = event.pageX - 60;
    topPos = event.pageY + 45;

    var buddyObj = FindBuddyByIdentity(buddy);

    if (typeStr == "extension") {

        var html = "<div style=\"width:200px; cursor:pointer\" onclick=\"EditBuddyWindow('"+ buddy +"')\">";
        html += "<div class=\"buddyProfilePic\" style=\"background-image:url('"+ getPicture(buddy, "extension") +"')\"></div>";
        html += "<div id=ProfileInfo style=\"text-align:center\"><i class=\"fa fa-spinner fa-spin\"></i></div>"
        html += "</div>";

        $.jeegoopopup.open({
                html: html,
                width: '200',
                height: 'auto',
                left: leftPos,
                top: topPos,
                scrolling: 'no',
                skinClass: 'jg_popup_basic',
                contentClass: 'showContactDetails',
                overlay: true,
                opacity: 0,
                draggable: true,
                resizable: false,
                fadeIn: 0
        });
      
        // Done
        $("#ProfileInfo").html("");

        $("#ProfileInfo").append("<div class=ProfileTextLarge style=\"margin-top:15px\">"+ buddyObj.CallerIDName +"</div>");
        $("#ProfileInfo").append("<div class=ProfileTextMedium>"+ buddyObj.Desc +"</div>");

        $("#ProfileInfo").append("<div class=ProfileTextSmall style=\"margin-top:15px\">"+ lang.extension_number +":</div>");
        $("#ProfileInfo").append("<div class=ProfileTextMedium>"+ buddyObj.ExtNo +" </div>");

        if(buddyObj.Email && buddyObj.Email != "null" && buddyObj.Email != "undefined"){
            $("#ProfileInfo").append("<div class=ProfileTextSmall style=\"margin-top:15px\">"+ lang.email +":</div>");
            $("#ProfileInfo").append("<div class=ProfileTextMedium>"+ buddyObj.Email +" </div>");
        }
        if(buddyObj.MobileNumber && buddyObj.MobileNumber != "null" && buddyObj.MobileNumber != "undefined"){
            $("#ProfileInfo").append("<div class=ProfileTextSmall style=\"margin-top:15px\">"+ lang.mobile +":</div>");
            $("#ProfileInfo").append("<div class=ProfileTextMedium>"+ buddyObj.MobileNumber +" </div>");
        }
        if(buddyObj.ContactNumber1 && buddyObj.ContactNumber1 != "null" && buddyObj.ContactNumber1 != "undefined"){
            $("#ProfileInfo").append("<div class=ProfileTextSmall style=\"margin-top:15px\">"+ lang.alternative_contact +":</div>");
            $("#ProfileInfo").append("<div class=ProfileTextMedium>"+ buddyObj.ContactNumber1 +" </div>");
        }
        if(buddyObj.ContactNumber2 && buddyObj.ContactNumber2 != "null" && buddyObj.ContactNumber2 != "undefined"){
            $("#ProfileInfo").append("<div class=ProfileTextSmall style=\"margin-top:15px\">"+ lang.alternative_contact +":</div>");
            $("#ProfileInfo").append("<div class=ProfileTextMedium>"+ buddyObj.ContactNumber2 +" </div>");
        }

    } else if (typeStr == "contact") {

        var html = "<div style=\"width:200px; cursor:pointer\" onclick=\"EditBuddyWindow('"+ buddy +"')\">";
        html += "<div class=\"buddyProfilePic\" style=\"background-image:url('"+ getPicture(buddy, "contact") +"')\"></div>";
        html += "<div id=ProfileInfo style=\"text-align:center\"><i class=\"fa fa-spinner fa-spin\"></i></div>"
        html += "</div>";

        $.jeegoopopup.open({
                html: html,
                width: '200',
                height: 'auto',
                left: leftPos,
                top: topPos,
                scrolling: 'no',
                skinClass: 'jg_popup_basic',
                contentClass: 'showContactDetails',
                overlay: true,
                opacity: 0,
                draggable: true,
                resizable: false,
                fadeIn: 0
        });

        $("#ProfileInfo").html("");
        $("#ProfileInfo").append("<div class=ProfileTextLarge style=\"margin-top:15px\">"+ buddyObj.CallerIDName +"</div>");
        $("#ProfileInfo").append("<div class=ProfileTextMedium>"+ buddyObj.Desc +"</div>");

        if(buddyObj.Email && buddyObj.Email != "null" && buddyObj.Email != "undefined"){
            $("#ProfileInfo").append("<div class=ProfileTextSmall style=\"margin-top:15px\">"+ lang.email +":</div>");
            $("#ProfileInfo").append("<div class=ProfileTextMedium>"+ buddyObj.Email +" </div>");
        }
        if(buddyObj.MobileNumber && buddyObj.MobileNumber != "null" && buddyObj.MobileNumber != "undefined"){
            $("#ProfileInfo").append("<div class=ProfileTextSmall style=\"margin-top:15px\">"+ lang.mobile +":</div>");
            $("#ProfileInfo").append("<div class=ProfileTextMedium>"+ buddyObj.MobileNumber +" </div>");
        }
        if(buddyObj.ContactNumber1 && buddyObj.ContactNumber1 != "null" && buddyObj.ContactNumber1 != "undefined"){
            $("#ProfileInfo").append("<div class=ProfileTextSmall style=\"margin-top:15px\">"+ lang.alternative_contact +":</div>");
            $("#ProfileInfo").append("<div class=ProfileTextMedium>"+ buddyObj.ContactNumber1 +" </div>");
        }
        if(buddyObj.ContactNumber2 && buddyObj.ContactNumber2 != "null" && buddyObj.ContactNumber2 != "undefined"){
            $("#ProfileInfo").append("<div class=ProfileTextSmall style=\"margin-top:15px\">"+ lang.alternative_contact +":</div>");
            $("#ProfileInfo").append("<div class=ProfileTextMedium>"+ buddyObj.ContactNumber2 +" </div>");
        }

    } else if (typeStr == "group") {

        var html = "<div style=\"width:200px; cursor:pointer\" onclick=\"EditBuddyWindow('"+ buddy +"')\">";
        html += "<div class=\"buddyProfilePic\" style=\"background-image:url('"+ getPicture(buddy, "group") +"')\"></div>";
        html += "<div id=ProfileInfo style=\"text-align:center\"><i class=\"fa fa-spinner fa-spin\"></i></div>"
        html += "</div>";

        $.jeegoopopup.open({
                html: html,
                width: '200',
                height: 'auto',
                left: leftPos,
                top: topPos,
                scrolling: 'no',
                skinClass: 'jg_popup_basic',
                contentClass: 'showContactDetails',
                overlay: true,
                opacity: 0,
                draggable: true,
                resizable: false,
                fadeIn: 0
        });

        $("#ProfileInfo").html("");

        $("#ProfileInfo").append("<div class=ProfileTextLarge style=\"margin-top:15px\">"+ buddyObj.CallerIDName +"</div>");
        $("#ProfileInfo").append("<div class=ProfileTextMedium>"+ buddyObj.Desc +"</div>");
    }

    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); });
    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); } });
}

// Device and Settings
// ===================
function ChangeSettings(lineNum, obj){

    var leftPos = event.pageX - 138;
    var topPos = event.pageY + 28;

    if (($(window).height() - event.pageY) < 300) { topPos = event.pageY - 170; }

    // Check if you are in a call
    var lineObj = FindLineByNumber(lineNum);
    if(lineObj == null || lineObj.SipSession == null) return;
    var session = lineObj.SipSession;

    var html = "<div id=DeviceSelector style=\"width:250px\"></div>";

    $.jeegoopopup.open({
                html: html,
                width: "auto",
                height: "auto",
                left: leftPos,
                top: topPos,
                scrolling: 'no',
                skinClass: 'jg_popup_basic',
                contentClass: 'callSettingsContent',
                overlay: true,
                opacity: 0,
                draggable: true,
                resizable: false,
                fadeIn: 0
    });

    var audioSelect = $('<select/>');
    audioSelect.prop("id", "audioSrcSelect");
    audioSelect.css("width", "100%");

    var videoSelect = $('<select/>');
    videoSelect.prop("id", "videoSrcSelect");
    videoSelect.css("width", "100%");

    var speakerSelect = $('<select/>');
    speakerSelect.prop("id", "audioOutputSelect");
    speakerSelect.css("width", "100%");

    var ringerSelect = $('<select/>');
    ringerSelect.prop("id", "ringerSelect");
    ringerSelect.css("width", "100%");

    // Handle Audio Source changes (Microphone)
    audioSelect.change(function() {

        console.log("Call to change Microphone: ", this.value);

        // First Stop Recording the call
        var mustRestartRecording = false;
        if(session.data.mediaRecorder && session.data.mediaRecorder.state == "recording"){
            StopRecording(lineNum, true);
            mustRestartRecording = true;
        }

        // Stop Monitoring
        if(lineObj.LocalSoundMeter) lineObj.LocalSoundMeter.stop();

        // Save Setting
        session.data.AudioSourceDevice = this.value;

        var constraints = {
            audio: {
                deviceId: (this.value != "default")? { exact: this.value } : "default"
            },
            video: false
        }
        navigator.mediaDevices.getUserMedia(constraints).then(function(newStream){
            // Assume that since we are selecting from a dropdown, this is possible
            var newMediaTrack = newStream.getAudioTracks()[0];
            var pc = session.sessionDescriptionHandler.peerConnection;
            pc.getSenders().forEach(function (RTCRtpSender) {
                if(RTCRtpSender.track && RTCRtpSender.track.kind == "audio") {
                    console.log("Switching Audio Track : "+ RTCRtpSender.track.label + " to "+ newMediaTrack.label);
                    RTCRtpSender.track.stop(); // Must stop, or this mic will stay in use
                    RTCRtpSender.replaceTrack(newMediaTrack).then(function(){
                        // Start recording again
                        if(mustRestartRecording) StartRecording(lineNum);
                        // Monitor audio stream
                        lineObj.LocalSoundMeter = StartLocalAudioMediaMonitoring(lineNum, session);
                    }).catch(function(e){
                        console.error("Error replacing track: ", e);
                    });
                }
            });
        }).catch(function(e){
            console.error("Error on getUserMedia");
        });
    });

    // Handle output change (speaker)
    speakerSelect.change(function() {
        console.log("Call to change Speaker: ", this.value);

        // Save Setting
        session.data.AudioOutputDevice = this.value;

        // Also change the sinkId
        // ======================
        var sinkId = this.value;
        console.log("Attempting to set Audio Output SinkID for line "+ lineNum +" [" + sinkId + "]");

        // Remote audio
        var element = $("#line-"+ lineNum +"-remoteAudio").get(0);
        if (element) {
            if (typeof element.sinkId !== 'undefined') {
                element.setSinkId(sinkId).then(function(){
                    console.log("sinkId applied: "+ sinkId);
                }).catch(function(e){
                    console.warn("Error using setSinkId: ", e);
                });
            } else {
                console.warn("setSinkId() is not possible using this browser.")
            }
        }
    });

    // Handle video input change (WebCam)
    videoSelect.change(function(){
        console.log("Call to change WebCam");

        switchVideoSource(lineNum, this.value);
    });

    // Load Devices
    if(!navigator.mediaDevices) {
        console.warn("navigator.mediaDevices not possible.");
        return;
    }

    for (var i = 0; i < AudioinputDevices.length; ++i) {
        var deviceInfo = AudioinputDevices[i];
        var devideId = deviceInfo.deviceId;
        var DisplayName = (deviceInfo.label)? deviceInfo.label : "";
        if(DisplayName.indexOf("(") > 0) DisplayName = DisplayName.substring(0,DisplayName.indexOf("("));

        // Create Option
        var option = $('<option/>');
        option.prop("value", devideId);
        option.text((DisplayName != "")? DisplayName : "Microphone");
        if(session.data.AudioSourceDevice == devideId) option.prop("selected", true);
        audioSelect.append(option);
    }
    for (var i = 0; i < VideoinputDevices.length; ++i) {
        var deviceInfo = VideoinputDevices[i];
        var devideId = deviceInfo.deviceId;
        var DisplayName = (deviceInfo.label)? deviceInfo.label : "";
        if(DisplayName.indexOf("(") > 0) DisplayName = DisplayName.substring(0,DisplayName.indexOf("("));

        // Create Option
        var option = $('<option/>');
        option.prop("value", devideId);
        option.text((DisplayName != "")? DisplayName : "Webcam");
        if(session.data.VideoSourceDevice == devideId) option.prop("selected", true);
        videoSelect.append(option);
    }
    if(HasSpeakerDevice){
        for (var i = 0; i < SpeakerDevices.length; ++i) {
            var deviceInfo = SpeakerDevices[i];
            var devideId = deviceInfo.deviceId;
            var DisplayName = (deviceInfo.label)? deviceInfo.label : "";
            if(DisplayName.indexOf("(") > 0) DisplayName = DisplayName.substring(0,DisplayName.indexOf("("));

            // Create Option
            var option = $('<option/>');
            option.prop("value", devideId);
            option.text((DisplayName != "")? DisplayName : "Speaker"); 
            if(session.data.AudioOutputDevice == devideId) option.prop("selected", true);
            speakerSelect.append(option);
        }
    }

    // Mic Serttings
    $("#DeviceSelector").append("<div class=callSettingsDvs>"+ lang.microphone +": </div>");
    $("#DeviceSelector").append(audioSelect);
    
    // Speaker
    if(HasSpeakerDevice){
        $("#DeviceSelector").append("<div class=callSettingsDvs>"+ lang.speaker +": </div>");
        $("#DeviceSelector").append(speakerSelect);
    }
    // Camera
    if(session.data.withvideo == true){
        $("#DeviceSelector").append("<div class=callSettingsDvs>"+ lang.camera +": </div>");
        $("#DeviceSelector").append(videoSelect);
    }

    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); });
    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); } });
}

// Media Presentation
// ==================
function PresentCamera(lineNum){
    var lineObj = FindLineByNumber(lineNum);
    if(lineObj == null || lineObj.SipSession == null){
        console.warn("Line or Session is Null.");
        return;
    }
    var session = lineObj.SipSession;

    $("#line-"+ lineNum +"-src-camera").prop("disabled", true);
    $("#line-"+ lineNum +"-src-canvas").prop("disabled", false);
    $("#line-"+ lineNum +"-src-desktop").prop("disabled", false);
    $("#line-"+ lineNum +"-src-video").prop("disabled", false);
    $("#line-"+ lineNum +"-src-blank").prop("disabled", false);

    $("#line-"+ lineNum + "-scratchpad-container").hide();
    RemoveScratchpad(lineNum);
    $("#line-"+ lineNum +"-sharevideo").hide();
    $("#line-"+ lineNum +"-sharevideo").get(0).pause();
    $("#line-"+ lineNum +"-sharevideo").get(0).removeAttribute('src');
    $("#line-"+ lineNum +"-sharevideo").get(0).load();
    window.clearInterval(session.data.videoResampleInterval);

    $("#line-"+ lineNum + "-localVideo").show();
    $("#line-"+ lineNum + "-remoteVideo").appendTo("#line-"+ lineNum + "-stage-container");

    switchVideoSource(lineNum, session.data.VideoSourceDevice);
}
function PresentScreen(lineNum){
    var lineObj = FindLineByNumber(lineNum);
    if(lineObj == null || lineObj.SipSession == null){
        console.warn("Line or Session is Null.");
        return;
    }
    var session = lineObj.SipSession;

    $("#line-"+ lineNum +"-src-camera").prop("disabled", false);
    $("#line-"+ lineNum +"-src-canvas").prop("disabled", false);
    $("#line-"+ lineNum +"-src-desktop").prop("disabled", true);
    $("#line-"+ lineNum +"-src-video").prop("disabled", false);
    $("#line-"+ lineNum +"-src-blank").prop("disabled", false);

    $("#line-"+ lineNum + "-scratchpad-container").hide();
    RemoveScratchpad(lineNum);
    $("#line-"+ lineNum +"-sharevideo").hide();
    $("#line-"+ lineNum +"-sharevideo").get(0).pause();
    $("#line-"+ lineNum +"-sharevideo").get(0).removeAttribute('src');
    $("#line-"+ lineNum +"-sharevideo").get(0).load();
    window.clearInterval(session.data.videoResampleInterval);

    $("#line-"+ lineNum + "-localVideo").hide();
    $("#line-"+ lineNum + "-remoteVideo").appendTo("#line-"+ lineNum + "-stage-container");

    ShareScreen(lineNum);
}
function PresentScratchpad(lineNum){
    var lineObj = FindLineByNumber(lineNum);
    if(lineObj == null || lineObj.SipSession == null){
        console.warn("Line or Session is Null.");
        return;
    }
    var session = lineObj.SipSession;

    $("#line-"+ lineNum +"-src-camera").prop("disabled", false);
    $("#line-"+ lineNum +"-src-canvas").prop("disabled", true);
    $("#line-"+ lineNum +"-src-desktop").prop("disabled", false);
    $("#line-"+ lineNum +"-src-video").prop("disabled", false);
    $("#line-"+ lineNum +"-src-blank").prop("disabled", false);

    $("#line-"+ lineNum + "-scratchpad-container").hide();
    RemoveScratchpad(lineNum);
    $("#line-"+ lineNum +"-sharevideo").hide();
    $("#line-"+ lineNum +"-sharevideo").get(0).pause();
    $("#line-"+ lineNum +"-sharevideo").get(0).removeAttribute('src');
    $("#line-"+ lineNum +"-sharevideo").get(0).load();
    window.clearInterval(session.data.videoResampleInterval);

    $("#line-"+ lineNum + "-localVideo").hide();
    $("#line-"+ lineNum + "-remoteVideo").appendTo("#line-"+ lineNum + "-preview-container");

    SendCanvas(lineNum);
}
function PresentVideo(lineNum){

    var lineObj = FindLineByNumber(lineNum);
    if(lineObj == null || lineObj.SipSession == null){
        console.warn("Line or Session is Null.");
        return;
    }
    var session = lineObj.SipSession;

    $.jeegoopopup.close();

    var presentVideoHtml = "<div>";
    presentVideoHtml += '<div id="windowCtrls"><img id="closeImg" src="images/3_close.svg" title="Close" /></div>';
    presentVideoHtml += "<label for=SelectVideoToSend class=customBrowseButton style=\"display: block; margin: 26px auto;\">Select File</label>";
    presentVideoHtml += "<div class=\"UiWindowField\"><input type=file  accept=\"video/*\" id=SelectVideoToSend></div>";
    presentVideoHtml += "</div>";

    $.jeegoopopup.open({
                html: presentVideoHtml,
                width: '180',
                height: '80',
                center: true,
                scrolling: 'no',
                skinClass: 'jg_popup_basic',
                overlay: true,
                opacity: 0,
                draggable: true,
                resizable: false,
                fadeIn: 0
    });

    $("#SelectVideoToSend").on('change', function(event){
            var input = event.target;
            if(input.files.length >= 1){

                $.jeegoopopup.close();

                // Send Video (Can only send one file)
                SendVideo(lineNum, URL.createObjectURL(input.files[0]));
            }
            else {
                console.warn("Please Select a file to present.");
            }
    });

    $("#closeImg").click(function() { $.jeegoopopup.close(); });
    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); });
    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); } });
}
function PresentBlank(lineNum){
    var lineObj = FindLineByNumber(lineNum);
    if(lineObj == null || lineObj.SipSession == null){
        console.warn("Line or Session is Null.");
        return;
    }
    var session = lineObj.SipSession;

    $("#line-"+ lineNum +"-src-camera").prop("disabled", false);
    $("#line-"+ lineNum +"-src-canvas").prop("disabled", false);
    $("#line-"+ lineNum +"-src-desktop").prop("disabled", false);
    $("#line-"+ lineNum +"-src-video").prop("disabled", false);
    $("#line-"+ lineNum +"-src-blank").prop("disabled", true);
    
    $("#line-"+ lineNum + "-scratchpad-container").hide();
    RemoveScratchpad(lineNum);
    $("#line-"+ lineNum +"-sharevideo").hide();
    $("#line-"+ lineNum +"-sharevideo").get(0).pause();
    $("#line-"+ lineNum +"-sharevideo").get(0).removeAttribute('src');
    $("#line-"+ lineNum +"-sharevideo").get(0).load();
    window.clearInterval(session.data.videoResampleInterval);

    $("#line-"+ lineNum + "-localVideo").hide();
    $("#line-"+ lineNum + "-remoteVideo").appendTo("#line-"+ lineNum + "-stage-container");

    DisableVideoStream(lineNum);
}
function RemoveScratchpad(lineNum){
    var scratchpad = GetCanvas("line-" + lineNum + "-scratchpad");
    if(scratchpad != null){
        window.clearInterval(scratchpad.redrawIntrtval);

        RemoveCanvas("line-" + lineNum + "-scratchpad");
        $("#line-"+ lineNum + "-scratchpad-container").empty();

        scratchpad = null;
    }
}

// Call Statistics
// ===============
function ShowCallStats(lineNum, obj){
    console.log("Show Call Stats");
    $("#line-"+ lineNum +"-AudioStats").show(300);
}
function HideCallStats(lineNum, obj){
    console.log("Hide Call Stats");
    $("#line-"+ lineNum +"-AudioStats").hide(300);
}

// Chatting
// ========
function chatOnbeforepaste(event, obj, buddy){
    console.log("Handle paste, checking for Images...");
    var items = (event.clipboardData || event.originalEvent.clipboardData).items;

    // Find pasted image among pasted items
    var preventDefault = false;
    for (var i = 0; i < items.length; i++) {
        if (items[i].type.indexOf("image") === 0) {
            console.log("Image found! Opening image editor...");

            var blob = items[i].getAsFile();

            // Read the image in
            var reader = new FileReader();
            reader.onload = function (event) {

                // Image has loaded, open Image Preview Editor
                // ===========================================
                console.log("Image loaded... setting placeholder...");
                var placeholderImage = new Image();
                placeholderImage.onload = function () {

                    console.log("Placeholder loaded... CreateImageEditor...");

                    CreateImageEditor(buddy, placeholderImage);
                }
                placeholderImage.src = event.target.result;
            }
            reader.readAsDataURL(blob);

            preventDefault = true;
            continue;
        }
    }

    // Pevent default if you found an image
    if (preventDefault) event.preventDefault();
}
function chatOnkeydown(event, obj, buddy) {

    var keycode = (event.keyCode ? event.keyCode : event.which);
    if (keycode == '13'){
        if(event.ctrlKey) {
            SendChatMessage(buddy);
            return false;
        }
    }
}

function ReformatMessage(str) {
    var msg = str;
    // Simple tex=>HTML 
    msg = msg.replace(/</gi, "&lt;");
    msg = msg.replace(/>/gi, "&gt;");
    msg = msg.replace(/\n/gi, "<br>");
    // Emojy
    // Skype: :) :( :D :O ;) ;( (:| :| :P :$ :^) |-) |-( :x ]:)
    // (cool) (hearteyes) (stareyes) (like) (unamused) (cwl) (xd) (pensive) (weary) (hysterical) (flushed) (sweatgrinning) (disappointed) (loudlycrying) (shivering) (expressionless) (relieved) (inlove) (kiss) (yawn) (puke) (doh) (angry) (wasntme) (worry) (confused) (veryconfused) (mm) (nerd) (rainbowsmile) (devil) (angel) (envy) (makeup) (think) (rofl) (happy) (smirk) (nod) (shake) (waiting) (emo) (donttalk) (idea) (talk) (swear) (headbang) (learn) (headphones) (morningafter) (selfie) (shock) (ttm) (dream)
    msg = msg.replace(/(:\)|:\-\)|:o\))/g, String.fromCodePoint(0x1F642));     // :) :-) :o)
    msg = msg.replace(/(:\(|:\-\(|:o\()/g, String.fromCodePoint(0x1F641));     // :( :-( :o(
    msg = msg.replace(/(;\)|;\-\)|;o\))/g, String.fromCodePoint(0x1F609));     // ;) ;-) ;o)
    msg = msg.replace(/(:'\(|:'\-\()/g, String.fromCodePoint(0x1F62A));        // :'( :'‑(
    msg = msg.replace(/(:'\(|:'\-\()/g, String.fromCodePoint(0x1F602));        // :') :'‑)
    msg = msg.replace(/(:\$)/g, String.fromCodePoint(0x1F633));                // :$
    msg = msg.replace(/(>:\()/g, String.fromCodePoint(0x1F623));               // >:(
    msg = msg.replace(/(:\×)/g, String.fromCodePoint(0x1F618));                // :×
    msg = msg.replace(/(:\O|:\‑O)/g, String.fromCodePoint(0x1F632));             // :O :‑O
    msg = msg.replace(/(:P|:\-P|:p|:\-p)/g, String.fromCodePoint(0x1F61B));      // :P :-P :p :-p
    msg = msg.replace(/(;P|;\-P|;p|;\-p)/g, String.fromCodePoint(0x1F61C));      // ;P ;-P ;p ;-p
    msg = msg.replace(/(:D|:\-D)/g, String.fromCodePoint(0x1F60D));             // :D :-D

    msg = msg.replace(/(\(like\))/g, String.fromCodePoint(0x1F44D));           // (like)

    // Make clickable Hyperlinks
    msg = msg.replace(/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/gi, function (x) {
          var niceLink = (x.length > 50) ? x.substring(0, 47) + "..." : x;
          var rtn = "<A target=_blank class=previewHyperlink href=\"" + x + "\">" + niceLink + "</A>";
          return rtn;
    });
    return msg;
}
function getPicture(buddy, typestr){
    if(buddy == "profilePicture"){
        // Special handling for profile image
        var dbImg = localDB.getItem("profilePicture");
        if(dbImg == null){
            return hostingPrefex + "images/default.png";
        }
        else {
            return dbImg; 
        }
    }

    typestr = (typestr)? typestr : "extension";

    var buddyObj = FindBuddyByIdentity(buddy);
    if(buddyObj.imageObjectURL != ""){
        // Use Cache
        return buddyObj.imageObjectURL;
    }

    var dbImg = localDB.getItem("img-"+ buddy +"-"+ typestr);

    if(dbImg == null){
        return hostingPrefex + "images/default.png";
    } else {
        buddyObj.imageObjectURL = URL.createObjectURL(base64toBlob(dbImg, 'image/png'));
        return buddyObj.imageObjectURL;
    }
}

// Image Editor
// ============
function CreateImageEditor(buddy, placeholderImage){
    // Show Interface
    // ==============
    console.log("Setting Up ImageEditor...");
    if($("#contact-" + buddy + "-imagePastePreview").is(":visible")) {
        console.log("Resetting ImageEditor...");
        $("#contact-" + buddy + "-imagePastePreview").empty();
        RemoveCanvas("contact-" + buddy + "-imageCanvas")
    } else {
        $("#contact-" + buddy + "-imagePastePreview").show();
    }
    // Create UI
    // =========
    var toolBarDiv = $('<div/>');
    toolBarDiv.css("margin-bottom", "5px")
    toolBarDiv.append('<button class="toolBarButtons" title="Select" onclick="ImageEditor_Select(\''+ buddy +'\')"><i class="fa fa-mouse-pointer"></i></button>');
    toolBarDiv.append('&nbsp;|&nbsp;');
    toolBarDiv.append('<button class="toolBarButtons" title="Draw" onclick="ImageEditor_FreedrawPen(\''+ buddy +'\')"><i class="fa fa-pencil"></i></button>');
    toolBarDiv.append('<button class="toolBarButtons" title="Paint" onclick="ImageEditor_FreedrawPaint(\''+ buddy +'\')"><i class="fa fa-paint-brush"></i></button>');
    toolBarDiv.append('&nbsp;|&nbsp;');
    toolBarDiv.append('<button class="toolBarButtons" title="Select Line Color" onclick="ImageEditor_SetectLineColor(\''+ buddy +'\')"><i class="fa fa-pencil-square-o" style="color:rgb(255, 0, 0)"></i></button>');
    toolBarDiv.append('<button class="toolBarButtons" title="Select Fill Color" onclick="ImageEditor_SetectFillColor(\''+ buddy +'\')"><i class="fa fa-pencil-square" style="color:rgb(255, 0, 0)"></i></button>');
    toolBarDiv.append('&nbsp;|&nbsp;');
    toolBarDiv.append('<button class="toolBarButtons" title="Add Circle" onclick="ImageEditor_AddCircle(\''+ buddy +'\')"><i class="fa fa-circle"></i></button>');
    toolBarDiv.append('<button class="toolBarButtons" title="Add Rectangle" onclick="ImageEditor_AddRectangle(\''+ buddy +'\')"><i class="fa fa-stop"></i></button>');
    toolBarDiv.append('<button class="toolBarButtons" title="Add Triangle" onclick="ImageEditor_AddTriangle(\''+ buddy +'\')"><i class="fa fa-play"></i></button>');
    toolBarDiv.append('<button class="toolBarButtons" title="Add Emoji" onclick="ImageEditor_SetectEmoji(\''+ buddy +'\')"><i class="fa fa-smile-o"></i></button>');
    toolBarDiv.append('<button class="toolBarButtons" title="Add Text" onclick="ImageEditor_AddText(\''+ buddy +'\')"><i class="fa fa-font"></i></button>');
    toolBarDiv.append('<button class="toolBarButtons" title="Delete Selected Items" onclick="ImageEditor_Clear(\''+ buddy +'\')"><i class="fa fa-times"></i></button>');
    toolBarDiv.append('<button class="toolBarButtons" title="Clear All" onclick="ImageEditor_ClearAll(\''+ buddy +'\')"><i class="fa fa-trash"></i></button>');
    toolBarDiv.append('&nbsp;|&nbsp;');
    toolBarDiv.append('<button class="toolBarButtons" title="Pan" onclick="ImageEditor_Pan(\''+ buddy +'\')"><i class="fa fa-hand-paper-o"></i></button>');
    toolBarDiv.append('<button class="toolBarButtons" title="Zoom In" onclick="ImageEditor_ZoomIn(\''+ buddy +'\')"><i class="fa fa-search-plus"></i></button>');
    toolBarDiv.append('<button class="toolBarButtons" title="Zoom Out" onclick="ImageEditor_ZoomOut(\''+ buddy +'\')"><i class="fa fa-search-minus"></i></button>');
    toolBarDiv.append('<button class="toolBarButtons" title="Reset Pan & Zoom" onclick="ImageEditor_ResetZoom(\''+ buddy +'\')"><i class="fa fa-search" aria-hidden="true"></i></button>');
    toolBarDiv.append('&nbsp;|&nbsp;');
    toolBarDiv.append('<button class="toolBarButtons" title="Cancel" onclick="ImageEditor_Cancel(\''+ buddy +'\')"><i class="fa fa-times-circle"></i></button>');
    toolBarDiv.append('<button class="toolBarButtons" title="Send" onclick="ImageEditor_Send(\''+ buddy +'\')"><i class="fa fa-paper-plane"></i></button>');
    $("#contact-" + buddy + "-imagePastePreview").append(toolBarDiv);

    // Create the canvas
    // =================
    var newCanvas = $('<canvas/>');
    newCanvas.prop("id", "contact-" + buddy + "-imageCanvas");
    newCanvas.css("border", "1px solid #CCCCCC");
    $("#contact-" + buddy + "-imagePastePreview").append(newCanvas);
    console.log("Canvas for ImageEditor created...");

    var imgWidth = placeholderImage.width;
    var imgHeight = placeholderImage.height;
    var maxWidth = $("#contact-" + buddy + "-imagePastePreview").width()-2; // for the border
    var maxHeight = 480;
    $("#contact-" + buddy + "-imageCanvas").prop("width", maxWidth);
    $("#contact-" + buddy + "-imageCanvas").prop("height", maxHeight);

    // Handle Initial Zoom
    var zoomToFitImage = 1;
    var zoomWidth = 1;
    var zoomHeight = 1;
    if(imgWidth > maxWidth || imgHeight > maxHeight)
    {
        if(imgWidth > maxWidth)
        {
            zoomWidth = (maxWidth / imgWidth);
        }
        if(imgHeight > maxHeight)
        {
            zoomHeight = (maxHeight / imgHeight);
            console.log("Scale to fit height: "+ zoomHeight);
        }
        zoomToFitImage = Math.min(zoomWidth, zoomHeight) // need the smallest because less is more zoom.
        console.log("Scale down to fit: "+ zoomToFitImage);

        // Shape the canvas to fit the image and the new zoom
        imgWidth = imgWidth * zoomToFitImage;
        imgHeight = imgHeight * zoomToFitImage;
        console.log("resizing canvas to fit new image size...");
        $("#contact-" + buddy + "-imageCanvas").prop("width", imgWidth);
        $("#contact-" + buddy + "-imageCanvas").prop("height", imgHeight);
    }
    else {
        console.log("Image is able to fit, resizing canvas...");
        $("#contact-" + buddy + "-imageCanvas").prop("width", imgWidth);
        $("#contact-" + buddy + "-imageCanvas").prop("height", imgHeight);
    }

    // Fabric Canvas API
    // =================
    console.log("Creating fabric API...");
    var canvas = new fabric.Canvas("contact-" + buddy + "-imageCanvas");
    canvas.id = "contact-" + buddy + "-imageCanvas";
    canvas.ToolSelected = "None";
    canvas.PenColour = "rgb(255, 0, 0)";
    canvas.PenWidth = 2;
    canvas.PaintColour = "rgba(227, 230, 3, 0.6)";
    canvas.PaintWidth = 10;
    canvas.FillColour = "rgb(255, 0, 0)";
    canvas.isDrawingMode = false;

    canvas.selectionColor = 'rgba(112,179,233,0.25)';
    canvas.selectionBorderColor = 'rgba(112,179,233, 0.8)';
    canvas.selectionLineWidth = 1;

    // Zoom to fit Width or Height
    // ===========================
    canvas.setZoom(zoomToFitImage);

    // Canvas Events
    // =============
    canvas.on('mouse:down', function(opt) {
        var evt = opt.e;

        if (this.ToolSelected == "Pan") {
            this.isDragging = true;
            this.selection = false;
            this.lastPosX = evt.clientX;
            this.lastPosY = evt.clientY;
        }
        // Make nicer grab handles
        if(opt.target != null){
            if(evt.altKey === true)
            {
                opt.target.lockMovementX = true;
            }
            if(evt.shiftKey === true)
            {
                opt.target.lockMovementY = true;
            }
            opt.target.set({
                transparentCorners: false,
                borderColor: 'rgba(112,179,233, 0.4)',
                cornerColor: 'rgba(112,179,233, 0.8)',
                cornerSize: 6
            });
        }
    });
    canvas.on('mouse:move', function(opt) {
        if (this.isDragging) {
            var e = opt.e;
            this.viewportTransform[4] += e.clientX - this.lastPosX;
            this.viewportTransform[5] += e.clientY - this.lastPosY;
            this.requestRenderAll();
            this.lastPosX = e.clientX;
            this.lastPosY = e.clientY;
        }
    });
    canvas.on('mouse:up', function(opt) {
        this.isDragging = false;
        this.selection = true;
        if(opt.target != null){
            opt.target.lockMovementX = false;
            opt.target.lockMovementY = false;
        }
    });
    canvas.on('mouse:wheel', function(opt) {
        var delta = opt.e.deltaY;
        var pointer = canvas.getPointer(opt.e);
        var zoom = canvas.getZoom();
        zoom = zoom + delta/200;
        if (zoom > 10) zoom = 10;
        if (zoom < 0.1) zoom = 0.1;
        canvas.zoomToPoint({ x: opt.e.offsetX, y: opt.e.offsetY }, zoom);
        opt.e.preventDefault();
        opt.e.stopPropagation();
    });

    // Add Image
    // ==========
    canvas.backgroundImage = new fabric.Image(placeholderImage);

    CanvasCollection.push(canvas);

    // Add Key Press Events
    // ====================
    $("#contact-" + buddy + "-imagePastePreview").keydown(function(evt) {
        evt = evt || window.event;
        var key = evt.keyCode;
        console.log("Key press on Image Editor ("+ buddy +"): "+ key);

        // Delete Key
        if (key == 46) ImageEditor_Clear(buddy);
    });

    console.log("ImageEditor: "+ canvas.id +" created");

    ImageEditor_FreedrawPen(buddy);
}
function GetCanvas(canvasId){
    for(var c = 0; c < CanvasCollection.length; c++){
        try {
            if(CanvasCollection[c].id == canvasId) return CanvasCollection[c];
        } catch(e) {
            console.warn("CanvasCollection.id not available");
        }
    }
    return null;
}
function RemoveCanvas(canvasId){
    for(var c = 0; c < CanvasCollection.length; c++){
        try{
            if(CanvasCollection[c].id == canvasId) {
                console.log("Found Old Canvas, Disposing...");

                CanvasCollection[c].clear()
                CanvasCollection[c].dispose();

                CanvasCollection[c].id = "--deleted--";

                console.log("CanvasCollection.splice("+ c +", 1)");
                CanvasCollection.splice(c, 1);
                break;
            }
        }
        catch(e){ }
    }
    console.log("There are "+ CanvasCollection.length +" canvas now.");
}
var ImageEditor_Select = function (buddy){
    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
    if(canvas != null) {
        canvas.ToolSelected = "none";
        canvas.isDrawingMode = false;
        return true;
    }
    return false;
}
var ImageEditor_FreedrawPen = function (buddy){
    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
    if(canvas != null) {
        canvas.freeDrawingBrush.color = canvas.PenColour;
        canvas.freeDrawingBrush.width = canvas.PenWidth;
        canvas.ToolSelected = "Draw";
        canvas.isDrawingMode = true;
        console.log(canvas)
        return true;
    }
    return false;
}
var ImageEditor_FreedrawPaint = function (buddy){
    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
    if(canvas != null) {
        canvas.freeDrawingBrush.color = canvas.PaintColour;
        canvas.freeDrawingBrush.width = canvas.PaintWidth;
        canvas.ToolSelected = "Paint";
        canvas.isDrawingMode = true;
        return true;
    }
    return false;
}
var ImageEditor_Pan = function (buddy){
    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
    if(canvas != null) {
        canvas.ToolSelected = "Pan";
        canvas.isDrawingMode = false;
        return true;
    }
    return false;
}
var ImageEditor_ResetZoom = function (buddy){
    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
    if(canvas != null) {
        canvas.setZoom(1);
        canvas.setViewportTransform([1,0,0,1,0,0]);
        return true;
    } 
    return false;
}
var ImageEditor_ZoomIn = function (buddy){
    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
    if(canvas != null) {
        var zoom = canvas.getZoom();
        zoom = zoom + 0.5;
        if (zoom > 10) zoom = 10;
        if (zoom < 0.1) zoom = 0.1;

        var point = new fabric.Point(canvas.getWidth() / 2, canvas.getHeight() / 2);
        var center = fabric.util.transformPoint(point, canvas.viewportTransform);

        canvas.zoomToPoint(point, zoom);

        return true;
    }
    return false;
}
var ImageEditor_ZoomOut = function (buddy){
    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
    if(canvas != null) {
        var zoom = canvas.getZoom();
        zoom = zoom - 0.5;
        if (zoom > 10) zoom = 10;
        if (zoom < 0.1) zoom = 0.1;

        var point = new fabric.Point(canvas.getWidth() / 2, canvas.getHeight() / 2);
        var center = fabric.util.transformPoint(point, canvas.viewportTransform);

        canvas.zoomToPoint(point, zoom);

        return true;
    }
    return false;
}
var ImageEditor_AddCircle = function (buddy){
    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
    if(canvas != null) {
        canvas.ToolSelected = "none";
        canvas.isDrawingMode = false;
        var circle = new fabric.Circle({
            radius: 20, fill: canvas.FillColour
        })
        canvas.add(circle);
        canvas.centerObject(circle);
        canvas.setActiveObject(circle);
        return true;
    }
    return false;
}
var ImageEditor_AddRectangle = function (buddy){
    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
    if(canvas != null) {
        canvas.ToolSelected = "none";
        canvas.isDrawingMode = false;
        var rectangle = new fabric.Rect({ 
            width: 40, height: 40, fill: canvas.FillColour
        })
        canvas.add(rectangle);
        canvas.centerObject(rectangle);
        canvas.setActiveObject(rectangle);
        return true;
    }
    return false;
}
var ImageEditor_AddTriangle = function (buddy){
    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
    if(canvas != null) {
        canvas.ToolSelected = "none";
        canvas.isDrawingMode = false;
        var triangle = new fabric.Triangle({
            width: 40, height: 40, fill: canvas.FillColour
        })
        canvas.add(triangle);
        canvas.centerObject(triangle);
        canvas.setActiveObject(triangle);
        return true;
    }
    return false;
}
var ImageEditor_AddEmoji = function (buddy){
    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
    if(canvas != null) {
        canvas.ToolSelected = "none";
        canvas.isDrawingMode = false;
        var text = new fabric.Text(String.fromCodePoint(0x1F642), { fontSize : 24 });
        canvas.add(text);
        canvas.centerObject(text);
        canvas.setActiveObject(text);
        return true;
    }
    return false;
}
var ImageEditor_AddText = function (buddy, textString){
    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
    if(canvas != null) {
        canvas.ToolSelected = "none";
        canvas.isDrawingMode = false;
        var text = new fabric.IText(textString, { fill: canvas.FillColour, fontFamily: 'arial', fontSize : 18 });
        canvas.add(text);
        canvas.centerObject(text);
        canvas.setActiveObject(text);
        return true;
    }
    return false;
}
var ImageEditor_Clear = function (buddy){
    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
    if(canvas != null) {
        canvas.ToolSelected = "none";
        canvas.isDrawingMode = false;

        var activeObjects = canvas.getActiveObjects();
        for (var i=0; i<activeObjects.length; i++){
            canvas.remove(activeObjects[i]);
        }
        canvas.discardActiveObject();

        return true;
    }
    return false;
}
var ImageEditor_ClearAll = function (buddy){
    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
    if(canvas != null) {
        var savedBgImage = canvas.backgroundImage;

        canvas.ToolSelected = "none";
        canvas.isDrawingMode = false;
        canvas.clear();

        canvas.backgroundImage = savedBgImage;
        return true;
    }
    return false;
}
var ImageEditor_Cancel = function (buddy){
    console.log("Removing ImageEditor...");

    $("#contact-" + buddy + "-imagePastePreview").empty();
    RemoveCanvas("contact-" + buddy + "-imageCanvas");
    $("#contact-" + buddy + "-imagePastePreview").hide();
}
var ImageEditor_Send = function (buddy){
    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
    if(canvas != null) {
        var imgData = canvas.toDataURL({ format: 'png' });
        SendImageDataMessage(buddy, imgData);
        return true;
    }
    return false;
}

// Find something in the message stream
// ====================================
function FindSomething(buddy) {
    $("#contact-" + buddy + "-search").toggle();
    if($("#contact-" + buddy + "-search").is(":visible") == false){
        RefreshStream(FindBuddyByIdentity(buddy));
    }
    updateScroll(buddy);
}

// FileShare an Upload
// ===================
var allowDradAndDrop = function() {
    var div = document.createElement('div');
    return (('draggable' in div) || ('ondragstart' in div && 'ondrop' in div)) && 'FormData' in window && 'FileReader' in window;
}
function onFileDragDrop(e, buddy){

    var filesArray = e.dataTransfer.files;
    console.log("You are about to upload " + filesArray.length + " file.");

    // Clear style
    $("#contact-"+ buddy +"-ChatHistory").css("outline", "none");

    for (var f = 0; f < filesArray.length; f++){
        var fileObj = filesArray[f];
        var reader = new FileReader();
        reader.onload = function (event) {
            
            // Check if the file is under 50MB
            if(fileObj.size <= 52428800){
                // Add to Stream
                // =============
                SendFileDataMessage(buddy, event.target.result, fileObj.name, fileObj.size);
            }
            else{
                alert("The file '"+ fileObj.name +"' is bigger than 50MB, you cannot upload this file")
            }
        }
        console.log("Adding: "+ fileObj.name + " of size: "+ fileObj.size +"bytes");
        reader.readAsDataURL(fileObj);
    }

    // Prevent Default
    preventDefault(e);
}
function cancelDragDrop(e, buddy){
    // dragleave dragend
    $("#contact-"+ buddy +"-ChatHistory").css("outline", "none");
    preventDefault(e);
}
function setupDragDrop(e, buddy){
    // dragover dragenter
    $("#contact-"+ buddy +"-ChatHistory").css("outline", "2px dashed #184369");
    preventDefault(e);
}
function preventDefault(e){
    e.preventDefault();
    e.stopPropagation();
}

// UI Elements
// ===========
function Alert(messageStr, TitleStr, onOk) {

    $("#jg_popup_l").empty();
    $("#jg_popup_b").empty();
    $("#windowCtrls").empty();
    $.jeegoopopup.close();

    var html = "<div class=NoSelect>";
    html += '<div id="windowCtrls"><img id="closeImg" src="images/3_close.svg" title="Close" /></div>';
    html += "<div class=UiText style=\"padding: 0px 10px 8px 10px;\" id=AllertMessageText>" + messageStr + "</div>";
    html += "</div>"

    $.jeegoopopup.open({
                title: TitleStr,
                html: html,
                width: '260',
                height: 'auto',
                center: true,
                scrolling: 'no',
                skinClass: 'jg_popup_basic',
                contentClass: 'confirmDelContact',
                overlay: true,
                opacity: 50,
                draggable: true,
                resizable: false,
                fadeIn: 0
    });

    $("#jg_popup_b").append("<div id=bottomButtons><button id=AlertOkButton style=\"width:80px\">"+ lang.ok +"</button></div>");

    $("#AlertOkButton").click(function () {
        console.log("Alert OK clicked");
        if (onOk) onOk();
    });

    $(window).resize(function() {
       $.jeegoopopup.center();
    });

    $("#closeImg").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
    $("#AlertOkButton").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); $("#jg_popup_b").empty(); } });

}
function AlertConfigExtWindow(messageStr, TitleStr) {

    $("#jg_popup_l").empty();
    $("#jg_popup_b").empty();
    $("#windowCtrls").empty();
    $.jeegoopopup.close();

    videoAudioCheck = 1;

    var html = "<div class=NoSelect>";
    html += '<div id="windowCtrls"><img id="closeImg" src="images/3_close.svg" title="Close" /></div>';
    html += "<div class=UiText style=\"padding: 10px\" id=AllertMessageText>" + messageStr + "</div>";
    html += "</div>"

    $.jeegoopopup.open({
                title: TitleStr,
                html: html,
                width: '260',
                height: 'auto',
                center: true,
                scrolling: 'no',
                skinClass: 'jg_popup_basic',
                contentClass: 'confirmDelContact',
                overlay: true,
                opacity: 50,
                draggable: true,
                resizable: false,
                fadeIn: 0
    });

    $("#jg_popup_b").append("<div id=bottomButtons><button id=AlertOkButton style=\"width:80px\">"+ lang.ok +"</button></div>");

    $(window).resize(function() {
       $.jeegoopopup.center();
    });

    $("#closeImg").click(function() { $("#windowCtrls").empty(); $("#jg_popup_b").empty(); $.jeegoopopup.close(); ConfigureExtensionWindow(); });
    $("#AlertOkButton").click(function() { console.log("Alert OK clicked"); $("#windowCtrls").empty(); $("#jg_popup_b").empty(); $.jeegoopopup.close(); ConfigureExtensionWindow(); });
    $("#jg_popup_overlay").click(function() { $("#windowCtrls").empty(); $("#jg_popup_b").empty(); $.jeegoopopup.close(); ConfigureExtensionWindow(); });
    $(window).on('keydown', function(event) { if (event.key == "Escape") { $("#windowCtrls").empty(); $("#jg_popup_b").empty(); $.jeegoopopup.close(); ConfigureExtensionWindow(); } });

}
function Confirm(messageStr, TitleStr, onOk, onCancel) {

    $("#jg_popup_l").empty();
    $("#jg_popup_b").empty();
    $("#windowCtrls").empty();
    $.jeegoopopup.close();

    var html = "<div class=NoSelect>";
    html += '<div id="windowCtrls"><img id="closeImg" src="images/3_close.svg" title="Close" /></div>';
    html += "<div class=UiText style=\"padding: 10px\" id=ConfirmMessageText>" + messageStr + "</div>";
    html += "</div>";

    $.jeegoopopup.open({
                html: html,
                width: '260',
                height: 'auto',
                center: true,
                scrolling: 'no',
                skinClass: 'jg_popup_basic',
                contentClass: 'confirmDelContact',
                overlay: true,
                opacity: 50,
                draggable: true,
                resizable: false,
                fadeIn: 0
    });

    $("#jg_popup_b").append("<div id=ConfDelContact><button id=ConfirmOkButton>"+ lang.ok +"</button><button id=ConfirmCancelButton>"+ lang.cancel +"</button></div>");

    $("#ConfirmOkButton").click(function () {
        console.log("Confirm OK clicked");
        if (onOk) onOk();
    });
    $("#ConfirmCancelButton").click(function () {
        console.log("Confirm Cancel clicked");
        if (onCancel) onCancel();
    });

    $(window).resize(function() {
       $.jeegoopopup.center();
    });

    $("#closeImg").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
    $("#ConfirmOkButton").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
    $("#ConfirmCancelButton").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); $("#jg_popup_b").empty(); } });
}
function ConfirmConfigExtWindow(messageStr, TitleStr, onOk, onCancel) {

    $("#jg_popup_l").empty();
    $("#jg_popup_b").empty();
    $("#windowCtrls").empty();
    $.jeegoopopup.close();

    var html = "<div class=NoSelect>";
    html += "<div id=windowCtrls><img id=closeImg src=images/3_close.svg title=Close /></div>";
    html += "<div class=UiText style=\"padding: 10px\" id=ConfirmMessageText>" + messageStr + "</div>";
    html += "</div>";

    $.jeegoopopup.open({
                html: html,
                width: '260',
                height: 'auto',
                center: true,
                scrolling: 'no',
                skinClass: 'jg_popup_basic',
                contentClass: 'ConfCloseAccount',
                overlay: true,
                opacity: 50,
                draggable: true,
                resizable: false,
                fadeIn: 0
    });

    $("#jg_popup_b").append("<div id=ConfCloseAccount><button id=ConfirmOkButton>"+ lang.close_user_account +"</button><button id=ConfirmCancelButton>"+ lang.cancel +"</button></div>");

    $("#ConfirmOkButton").click(function () {
        console.log("Confirm OK clicked");
        if (onOk) onOk();
    });
    $("#ConfirmCancelButton").click(function () {
        console.log("Confirm Cancel clicked");
        if (onCancel) onCancel();

        $("#windowCtrls").empty();
        $("#jg_popup_b").empty();
        $.jeegoopopup.close();
        ConfigureExtensionWindow();
    });

    $(window).resize(function() {
       $.jeegoopopup.center();
    });

    $("#closeImg").click(function() { $("#jg_popup_b").empty(); $("#windowCtrls").empty(); $.jeegoopopup.close(); ConfigureExtensionWindow(); });
}
function Prompt(messageStr, TitleStr, FieldText, defaultValue, dataType, placeholderText, onOk, onCancel) {

    $("#jg_popup_l").empty();
    $("#jg_popup_b").empty();
    $("#windowCtrls").empty();
    $.jeegoopopup.close();

    var html = "<div class=NoSelect>";
    html += '<div id="windowCtrls"><img id="closeImg" src="images/3_close.svg" title="Close" /></div>';
    html += "<div class=UiText style=\"padding: 10px\" id=PromptMessageText>";
    html += messageStr;
    html += "<div style=\"margin-top:10px\">" + FieldText + " : </div>";
    html += "<div style=\"margin-top:5px\"><INPUT id=PromptValueField type=" + dataType + " value=\"" + defaultValue + "\" placeholder=\"" + placeholderText + "\" style=\"width:98%\"></div>"
    html += "</div>";
    html += "</div>";

    $.jeegoopopup.open({
                html: html,
                width: '260',
                height: 'auto',
                center: true,
                scrolling: 'no',
                skinClass: 'jg_popup_basic',
                contentClass: 'confirmDelContact',
                overlay: true,
                opacity: 50,
                draggable: true,
                resizable: false,
                fadeIn: 0
    });

    $("#jg_popup_b").append("<div id=bottomButtons><button id=PromptOkButton style=\"width:80px\">"+ lang.ok +"</button>&nbsp;<button id=PromptCancelButton class=UiButton style=\"width:80px\">"+ lang.cancel +"</button></div>");

    $("#PromptOkButton").click(function () {
        console.log("Prompt OK clicked, with value: " + $("#PromptValueField").val());
        if (onOk) onOk($("#PromptValueField").val());
    });

    $("#PromptCancelButton").click(function () {
        console.log("Prompt Cancel clicked");
        if (onCancel) onCancel();
    });

    $(window).resize(function() {
       $.jeegoopopup.center();
    });

    $("#closeImg").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
    $("#PromptOkButton").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
    $("#PromptCancelButton").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); $("#jg_popup_b").empty(); } });
}

// Device Detection
// ================
function DetectDevices(){
    navigator.mediaDevices.enumerateDevices().then(function(deviceInfos){
        // deviceInfos will not have a populated lable unless to accept the permission
        // during getUserMedia. This normally happens at startup/setup
        // so from then on these devices will be with lables.
        HasVideoDevice = false;
        HasAudioDevice = false;
        HasSpeakerDevice = false; // Safari and Firefox don't have these
        AudioinputDevices = [];
        VideoinputDevices = [];
        SpeakerDevices = [];
        for (var i = 0; i < deviceInfos.length; ++i) {
            if (deviceInfos[i].kind === "audioinput") {
                HasAudioDevice = true;
                AudioinputDevices.push(deviceInfos[i]);
            } 
            else if (deviceInfos[i].kind === "audiooutput") {
                HasSpeakerDevice = true;
                SpeakerDevices.push(deviceInfos[i]);
            }
            else if (deviceInfos[i].kind === "videoinput") {
                HasVideoDevice = true;
                VideoinputDevices.push(deviceInfos[i]);
            }
        }

    }).catch(function(e){
        console.error("Error enumerating devices", e);
    });
}
DetectDevices();
window.setInterval(function(){
    DetectDevices();
}, 10000);

// STATUS_NULL: 0
// STATUS_INVITE_SENT: 1
// STATUS_1XX_RECEIVED: 2
// STATUS_INVITE_RECEIVED: 3
// STATUS_WAITING_FOR_ANSWER: 4
// STATUS_ANSWERED: 5
// STATUS_WAITING_FOR_PRACK: 6
// STATUS_WAITING_FOR_ACK: 7
// STATUS_CANCELED: 8
// STATUS_TERMINATED: 9
// STATUS_ANSWERED_WAITING_FOR_PRACK: 10
// STATUS_EARLY_MEDIA: 11
// STATUS_CONFIRMED: 12

// =======================================
// End Of File
