Browse code

removed 4 files

DoubleBastionAdmin authored on 25/03/2022 13:14:12
Showing 4 changed files
1 1
deleted file mode 100644
... ...
@@ -1,7 +0,0 @@
1
-
2
-======= CHANGELOG =======
3
-
4
-Versions:
5
-
6
-== 1.0.0 - 2022-1-27 ==
7
-* Initial Release.
8 0
deleted file mode 100644
... ...
@@ -1,12547 +0,0 @@
1
-/**
2
- *  Copyright (C) 2021  Double Bastion LLC
3
- *
4
- *  This file is part of Roundpin, which is licensed under the
5
- *  GNU Affero General Public License Version 3.0. The license terms
6
- *  are detailed in the "LICENSE.txt" file located in the root directory.
7
- *
8
- *  This is a modified version of the original file
9
- *  "phone.js", first modified in 2020.
10
- *
11
- *  The original "phone.js" file was written by Conrad de Wet.
12
- *  We thank Conrad de Wet for his work and we list below
13
- *  the copyright notice of the original "phone.js" file:
14
-
15
-/*
16
- Copyright (c) 2020  - Conrad de Wet - All Rights Reserved.
17
-=============================================================
18
-File: phone.js
19
-License: GNU Affero General Public License v3.0
20
-Version: 0.1.0
21
-Owner: Conrad de Wet
22
-Date: April 2020
23
-Git: https://github.com/InnovateAsterisk/Browser-Phone
24
-*/
25
-
26
-// Global Settings
27
-// ===============
28
-var enabledExtendedServices = false;
29
-var enabledGroupServices = false;
30
-
31
-// Lanaguage Packs (lang/xx.json)
32
-// ===============
33
-// Note: The following should correspond to files on your server.
34
-// eg: If you list "fr" then you need to add the file "fr.json".
35
-// Use the "en.json" as a template.
36
-// More specific lanagauge must be first. ie: "zh-hans" should be before "zh".
37
-// "en.json" is always loaded by default
38
-const availableLang = ["ja", "zh-hans", "zh", "ru", "tr", "nl"];
39
-
40
-// User Settings & Defaults
41
-// ========================
42
-var wssServer = getDbItem("wssServer", null);
43
-var profileUserID = getDbItem("profileUserID", null);
44
-var profileUser = getDbItem("profileUser", null);
45
-var profileName = getDbItem("profileName", null);
46
-var WebSocketPort = getDbItem("WebSocketPort", null);
47
-var ServerPath = getDbItem("ServerPath", null);
48
-var SipUsername = getDbItem("SipUsername", null);
49
-var SipPassword = getDbItem("SipPassword", null);
50
-var StunServer = getDbItem("StunServer", "");
51
-
52
-var TransportConnectionTimeout = parseInt(getDbItem("TransportConnectionTimeout", 15));        // The timeout in seconds for the initial connection to make on the web socket port
53
-var TransportReconnectionAttempts = parseInt(getDbItem("TransportReconnectionAttempts", 99));  // The number of times to attempt to reconnect to a WebSocket when the connection drops.
54
-var TransportReconnectionTimeout = parseInt(getDbItem("TransportReconnectionTimeout", 15));    // The time in seconds to wait between WebSocket reconnection attempts.
55
-
56
-var userAgentStr = getDbItem("UserAgentStr", "Roundpin (SipJS - 0.11.6)");          // Set this to whatever you want.
57
-var hostingPrefex = getDbItem("HostingPrefex", "");                                 // Use if hosting off root directiory. eg: "/phone/" or "/static/"
58
-var RegisterExpires = parseInt(getDbItem("RegisterExpires", 300));                  // Registration expiry time (in seconds)
59
-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)
60
-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)
61
-var IceStunCheckTimeout = parseInt(getDbItem("IceStunCheckTimeout", 500));  // Set amount of time in milliseconds to wait for the ICE/STUN server
62
-var AutoAnswerEnabled = (getDbItem("AutoAnswerEnabled", "0") == "1");       // Automatically answers the phone when the call comes in, if you are not on a call already
63
-var DoNotDisturbEnabled = (getDbItem("DoNotDisturbEnabled", "0") == "1");   // Rejects any inbound call, while allowing outbound calls
64
-var CallWaitingEnabled = (getDbItem("CallWaitingEnabled", "1") == "1");     // Rejects any inbound call if you are on a call already.
65
-var RecordAllCalls = (getDbItem("RecordAllCalls", "0") == "1");             // Starts Call Recording when a call is established.
66
-var StartVideoFullScreen = (getDbItem("StartVideoFullScreen", "1") == "0"); // Starts a vdeo call in the full screen (browser screen, not dektop)
67
-var AutoGainControl = (getDbItem("AutoGainControl", "1") == "1");           // Attempts to adjust the microphone volume to a good audio level. (OS may be better at this)
68
-var EchoCancellation = (getDbItem("EchoCancellation", "1") == "1");         // Attemots to remove echo over the line.
69
-var NoiseSuppression = (getDbItem("NoiseSuppression", "1") == "1");         // Attempts to clear the call qulity of noise.
70
-var MirrorVideo = getDbItem("VideoOrientation", "rotateY(180deg)");         // Displays the self-preview in normal or mirror view, to better present the preview. 
71
-var maxFrameRate = getDbItem("FrameRate", "");                              // Suggests a frame rate to your webcam if possible.
72
-var videoHeight = getDbItem("VideoHeight", "");                             // Suggests a video height (and therefore picture quality) to your webcam.
73
-var videoAspectRatio = getDbItem("AspectRatio", "");                        // Suggests an aspect ratio (1:1 | 4:3 | 16:9) to your webcam.
74
-var NotificationsActive = (getDbItem("Notifications", "0") == "1");
75
-var StreamBuffer = parseInt(getDbItem("StreamBuffer", 50));                 // The amount of rows to buffer in the Buddy Stream
76
-var PosterJpegQuality = parseFloat(getDbItem("PosterJpegQuality", 0.6));    // The image quality of the Video Poster images
77
-var VideoResampleSize = getDbItem("VideoResampleSize", "HD");               // The resample size (height) to re-render video that gets presented (sent). (SD = ???x360 | HD = ???x720 | FHD = ???x1080)
78
-var RecordingVideoSize = getDbItem("RecordingVideoSize", "HD");             // The size/quality of the video track in the recodings (SD = 640x360 | HD = 1280x720 | FHD = 1920x1080)
79
-var RecordingVideoFps = parseInt(getDbItem("RecordingVideoFps", 12));       // The Frame Per Second of the Video Track recording
80
-var RecordingLayout = getDbItem("RecordingLayout", "them-pnp");             // The Layout of the Recording Video Track (side-by-side | us-pnp | them-pnp | us-only | them-only)
81
-var DidLength = parseInt(getDbItem("DidLength", 6));                        // DID length from which to decide if an incoming caller is a "contact" or an "extension".
82
-var MaxDidLength = parseInt(getDbItem("maximumNumberLength", 16));          // Maximum langth of any DID number including international dialled numbers.
83
-var DisplayDateFormat = getDbItem("DateFormat", "YYYY-MM-DD");              // The display format for all dates. https://momentjs.com/docs/#/displaying/
84
-var DisplayTimeFormat = getDbItem("TimeFormat", "h:mm:ss A");               // The display format for all times. https://momentjs.com/docs/#/displaying/
85
-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
86
-
87
-// Permission Settings
88
-var EnableTextMessaging = (getDbItem("EnableTextMessaging", "1") == "1");               // Enables the Text Messaging
89
-var DisableFreeDial = (getDbItem("DisableFreeDial", "0") == "1");                       // Removes the Dial icon in the profile area, users will need to add buddies in order to dial.
90
-var DisableBuddies = (getDbItem("DisableBuddies", "0") == "1");                         // Removes the Add Someone menu item and icon from the profile area. Buddies will still be created automatically. 
91
-var EnableTransfer = (getDbItem("EnableTransfer", "1") == "1");                         // Controls Transfering during a call
92
-var EnableConference = (getDbItem("EnableConference", "1") == "1");                     // Controls Conference during a call
93
-var AutoAnswerPolicy = getDbItem("AutoAnswerPolicy", "allow");                          // allow = user can choose | disabled = feature is disabled | enabled = feature is always on
94
-var DoNotDisturbPolicy = getDbItem("DoNotDisturbPolicy", "allow");                      // allow = user can choose | disabled = feature is disabled | enabled = feature is always on
95
-var CallWaitingPolicy = getDbItem("CallWaitingPolicy", "allow");                        // allow = user can choose | disabled = feature is disabled | enabled = feature is always on
96
-var CallRecordingPolicy = getDbItem("CallRecordingPolicy", "allow");                    // allow = user can choose | disabled = feature is disabled | enabled = feature is always on
97
-var EnableAccountSettings = (getDbItem("EnableAccountSettings", "1") == "1");           // Controls the Account tab in Settings
98
-var EnableAudioVideoSettings = (getDbItem("EnableAudioVideoSettings", "1") == "1");     // Controls the Audio & Video tab in Settings
99
-var EnableAppearanceSettings = (getDbItem("EnableAppearanceSettings", "1") == "1");     // Controls the Appearance tab in Settings
100
-var EnableChangeUserPasswordSettings = (getDbItem("EnableChangeUserPasswordSettings", "1") == "1"); // Controls the 'Change Password' tab in Settings
101
-var EnableChangeUserEmailSettings = (getDbItem("EnableChangeUserEmailSettings", "1") == "1");       // Controls the 'Change Email' tab in Settings
102
-var EnableCloseUserAccount = (getDbItem("EnableCloseUserAccount", "1") == "1");                     // Controls the 'Close Account' tab in Settings
103
-var EnableAlphanumericDial = (getDbItem("EnableAlphanumericDial", "1") == "1");                     // Allows calling /[^\da-zA-Z\*\#\+]/g default is /[^\d\*\#\+]/g
104
-var EnableVideoCalling = (getDbItem("EnableVideoCalling", "1") == "1");                             // Enables Video during a call
105
-var winVideoConf = null;
106
-var winVideoConfCheck = 0;
107
-
108
-// System variables
109
-// ================
110
-var localDB = window.localStorage;
111
-var userAgent = null;
112
-var voicemailSubs = null;
113
-var BlfSubs = [];
114
-var CanvasCollection = [];
115
-var Buddies = [];
116
-var isReRegister = false;
117
-var dhtmlxPopup = null;
118
-var selectedBuddy = null;
119
-var selectedLine = null;
120
-var alertObj = null;
121
-var confirmObj = null;
122
-var promptObj = null;
123
-var windowsCollection = null;
124
-var messagingCollection = null;
125
-var HasVideoDevice = false;
126
-var HasAudioDevice = false;
127
-var HasSpeakerDevice = false;
128
-var AudioinputDevices = [];
129
-var VideoinputDevices = [];
130
-var SpeakerDevices = [];
131
-var Lines = [];
132
-var lang = {};
133
-var audioBlobs = {};
134
-var newLineNumber = 0;
135
-var videoAudioCheck = 0;
136
-var RCLoginCheck = 0;
137
-var decSipPass = '';
138
-var currentChatPrivKey = '';
139
-var sendFileCheck = 0;
140
-var upFileName = '';
141
-var sendFileChatErr = '';
142
-var pubKeyCheck = 0;
143
-var splitMessage = {};
144
-
145
-// Utilities
146
-// =========
147
-function uID(){
148
-    return Date.now()+Math.floor(Math.random()*10000).toString(16).toUpperCase();
149
-}
150
-function utcDateNow(){
151
-    return moment().utc().format("YYYY-MM-DD HH:mm:ss UTC");
152
-}
153
-function getDbItem(itemIndex, defaultValue){
154
-    var localDB = window.localStorage;
155
-    if(localDB.getItem(itemIndex) != null) return localDB.getItem(itemIndex);
156
-    return defaultValue;
157
-}
158
-function getAudioSrcID(){
159
-    var id = localDB.getItem("AudioSrcId");
160
-    return (id != null)? id : "default";
161
-}
162
-function getAudioOutputID(){
163
-    var id = localDB.getItem("AudioOutputId");
164
-    return (id != null)? id : "default";
165
-}
166
-function getVideoSrcID(){
167
-    var id = localDB.getItem("VideoSrcId");
168
-    return (id != null)? id : "default";
169
-}
170
-function getRingerOutputID(){
171
-    var id = localDB.getItem("RingOutputId");
172
-    return (id != null)? id : "default";
173
-}
174
-function formatDuration(seconds){
175
-    var sec = Math.floor(parseFloat(seconds));
176
-    if(sec < 0){
177
-        return sec;
178
-    }
179
-    else if(sec >= 0 && sec < 60){
180
-         return sec + " " + ((sec != 1) ? lang.seconds_plural : lang.second_single);
181
-    } 
182
-    else if(sec >= 60 && sec < 60 * 60){ // greater then a minute and less then an hour
183
-        var duration = moment.duration(sec, 'seconds');
184
-        return duration.minutes() + " "+ ((duration.minutes() != 1) ? lang.minutes_plural: lang.minute_single) +" " + duration.seconds() +" "+ ((duration.seconds() != 1) ? lang.seconds_plural : lang.second_single);
185
-    } 
186
-    else if(sec >= 60 * 60 && sec < 24 * 60 * 60){ // greater than an hour and less then a day
187
-        var duration = moment.duration(sec, 'seconds');
188
-        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);
189
-    } 
190
-    //  Otherwise.. this is just too long
191
-}
192
-function formatShortDuration(seconds) {
193
-    var sec = Math.floor(parseFloat(seconds));
194
-    if(sec < 0){
195
-        return sec;
196
-    } 
197
-    else if(sec >= 0 && sec < 60){
198
-        return "00:"+ ((sec > 9)? sec : "0"+sec );
199
-    } 
200
-    else if(sec >= 60 && sec < 60 * 60){ // greater then a minute and less then an hour
201
-        var duration = moment.duration(sec, 'seconds');
202
-        return ((duration.minutes() > 9)? duration.minutes() : "0"+duration.minutes()) + ":" + ((duration.seconds() > 9)? duration.seconds() : "0"+duration.seconds());
203
-    } 
204
-    else if(sec >= 60 * 60 && sec < 24 * 60 * 60){ // greater than an hour and less then a day
205
-        var duration = moment.duration(sec, 'seconds');
206
-        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());
207
-    } 
208
-    //  Otherwise.. this is just too long
209
-}
210
-function formatBytes(bytes, decimals) {
211
-    if (bytes === 0) return "0 "+ lang.bytes;
212
-    var k = 1024;
213
-    var dm = (decimals && decimals >= 0)? decimals : 2;
214
-    var sizes = [lang.bytes, lang.kb, lang.mb, lang.gb, lang.tb, lang.pb, lang.eb, lang.zb, lang.yb];
215
-    var i = Math.floor(Math.log(bytes) / Math.log(k));
216
-    return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + " " + sizes[i];
217
-}
218
-function UserLocale(){
219
-    var language = window.navigator.userLanguage || window.navigator.language; // "en", "en-US", "fr", "fr-FR", "es-ES", etc.
220
-
221
-    langtag = language.split('-');
222
-    if(langtag.length == 1){
223
-        return ""; 
224
-    } 
225
-    else if(langtag.length == 2) {
226
-        return langtag[1].toLowerCase();  // en-US => us
227
-    }
228
-    else if(langtag.length >= 3) {
229
-        return langtag[1].toLowerCase();  // en-US => us
230
-    }
231
-}
232
-function GetAlternateLanguage() {
233
-    var userLanguage = window.navigator.userLanguage || window.navigator.language; // "en", "en-US", "fr", "fr-FR", "es-ES", etc.
234
-
235
-    if(Language != "auto") userLanguage = Language;
236
-    userLanguage = userLanguage.toLowerCase();
237
-    if(userLanguage == "en" || userLanguage.indexOf("en-") == 0) return "";  // English is already loaded
238
-
239
-    for(l = 0; l < availableLang.length; l++) {
240
-        if(userLanguage.indexOf(availableLang[l].toLowerCase()) == 0) {
241
-            console.log("Alternate Language detected: ", userLanguage);
242
-            // Set up Moment with the same langugae settings
243
-            moment.locale(userLanguage);
244
-            return availableLang[l].toLowerCase();
245
-        }
246
-    }
247
-    return "";
248
-}
249
-function getFilter(filter, keyword) {
250
-    if(filter.indexOf(",", filter.indexOf(keyword +": ") + keyword.length + 2) != -1) {
251
-        return filter.substring(filter.indexOf(keyword +": ") + keyword.length + 2, filter.indexOf(",", filter.indexOf(keyword +": ") + keyword.length + 2));
252
-    }
253
-    else {
254
-        return filter.substring(filter.indexOf(keyword +": ") + keyword.length + 2);
255
-    }
256
-}
257
-function base64toBlob(base64Data, contentType) {
258
-    if(base64Data.indexOf("," != -1)) base64Data = base64Data.split(",")[1]; // [data:image/png;base64] , [xxx...]
259
-    var byteCharacters = atob(base64Data);
260
-    var slicesCount = Math.ceil(byteCharacters.length / 1024);
261
-    var byteArrays = new Array(slicesCount);
262
-    for (var s = 0; s < slicesCount; ++s) {
263
-        var begin = s * 1024;
264
-        var end = Math.min(begin + 1024, byteCharacters.length);
265
-        var bytes = new Array(end - begin);
266
-        for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
267
-            bytes[i] = byteCharacters[offset].charCodeAt(0);
268
-        }
269
-        byteArrays[s] = new Uint8Array(bytes);
270
-    }
271
-    return new Blob(byteArrays, { type: contentType });
272
-}
273
-function MakeDataArray(defaultValue, count) {
274
-    var rtnArray = new Array(count);
275
-    for(var i=0; i< rtnArray.length; i++) {
276
-        rtnArray[i] = defaultValue;
277
-    }
278
-    return rtnArray;
279
-}
280
-// Save account configuration data to SQL database
281
-function saveConfToSqldb() {
282
-
283
-    wssServer = $("#Configure_Account_wssServer").val();
284
-    WebSocketPort = parseInt($("#Configure_Account_WebSocketPort").val());
285
-    ServerPath = $("#Configure_Account_ServerPath").val();
286
-    profileName = $("#Configure_Account_profileName").val();
287
-    SipUsername = $("#Configure_Account_SipUsername").val();
288
-    SipPassword = $("#Configure_Account_SipPassword").val();
289
-
290
-    var STUNServer = $("#Configure_Account_StunServer").val();
291
-    var AUDIOOutputId = $("#playbackSrc").val();
292
-    var VIDEOSrcId = $("#previewVideoSrc").val();
293
-    var VIDEOHeight = $("input[name=Settings_Quality]:checked").val(); 
294
-    var FRAMERate = parseInt($("input[name=Settings_FrameRate]:checked").val());
295
-    var ASPECTRatio = $("input[name=Settings_AspectRatio]:checked").val();
296
-    var VIDEOOrientation = $("input[name=Settings_Oriteation]:checked").val();
297
-    var AUDIOSrcId = $("#microphoneSrc").val();
298
-    var AUTOGainControl = ($("#Settings_AutoGainControl").is(':checked'))? "1" : "0";
299
-    var ECHOCancellation = ($("#Settings_EchoCancellation").is(':checked'))? "1" : "0";
300
-    var NOISESuppression = ($("#Settings_NoiseSuppression").is(':checked'))? "1" : "0";
301
-    var RINGOutputId = $("#ringDevice").val();
302
-    var VideoConfExtension = $("#Video_Conf_Extension").val();
303
-    var VideoConfWindowWidth = $("#Video_Conf_Window_Width").val();
304
-    var PROFILEpicture = (typeof getDbItem("profilePicture", "") === 'undefined') ? "" : getDbItem("profilePicture", "");
305
-    var NOTIFYCheck = ($("#Settings_Notifications").is(":checked"))? 1 : 0;
306
-    var EMAILIntegration = ($("#emailIntegration").is(":checked"))? 1 : 0;
307
-    var RCDomain = $("#RoundcubeDomain").val();
308
-    var RCbasicauthuser = $("#rcBasicAuthUser").val();
309
-    var RCbasicauthpass = $("#rcBasicAuthPass").val();
310
-    var RCuser = $("#RoundcubeUser").val();
311
-    var RCpassword = $("#RoundcubePass").val();
312
-
313
-    if (userName != '') {
314
-
315
-       if (wssServer != '' && WebSocketPort != '' && ServerPath != '' && SipUsername != '' && SipPassword != '') {
316
-
317
-          $.ajax({
318
-             type: "POST",
319
-             url: "save-update-settings.php",
320
-             dataType: "JSON",
321
-             data: {
322
-                     username: userName,
323
-                     wss_server: wssServer,
324
-                     web_socket_port: WebSocketPort,
325
-                     server_path: ServerPath,
326
-                     profile_name: profileName,
327
-                     sip_username: SipUsername,
328
-                     sip_password: SipPassword,
329
-                     stun_server: STUNServer,
330
-                     audio_output_id: AUDIOOutputId,
331
-                     video_src_id: VIDEOSrcId,
332
-                     video_height: VIDEOHeight,
333
-                     frame_rate: FRAMERate,
334
-                     aspect_ratio: ASPECTRatio,
335
-                     video_orientation: VIDEOOrientation,
336
-                     audio_src_id: AUDIOSrcId,
337
-                     auto_gain_control: AUTOGainControl,
338
-                     echo_cancellation: ECHOCancellation,
339
-                     noise_suppression: NOISESuppression,
340
-                     ring_output_id: RINGOutputId,
341
-                     video_conf_extension: VideoConfExtension,
342
-                     video_conf_window_width: VideoConfWindowWidth,
343
-                     profile_picture: PROFILEpicture,
344
-                     notifications: NOTIFYCheck,
345
-                     use_roundcube: EMAILIntegration,
346
-                     rcdomain: RCDomain,
347
-                     rcbasicauthuser: RCbasicauthuser,
348
-                     rcbasicauthpass: RCbasicauthpass,
349
-                     rcuser: RCuser,
350
-                     rcpassword: RCpassword,
351
-                     s_ajax_call: validateSToken
352
-             },
353
-             success: function(response) {
354
-                             window.location.reload();
355
-                      },
356
-             error: function(response) {
357
-                             alert("An error occurred while attempting to save the account configuration data!");
358
-             }
359
-          });
360
-
361
-       } else { alert("Fields: 'WebSocket Domain', 'WebSocket Port', 'WebSocket Path', 'SIP Username' and 'SIP Password' are required ! Please fill in all these fields !"); }
362
-
363
-    } else { alert("An error occurred while attempting to save the data!"); }
364
-}
365
-// Get account configuration data from SQL database
366
-function getConfFromSqldb() {
367
-
368
-          $.ajax({
369
-             type: "POST",
370
-             url: "get-settings.php",
371
-             dataType: "JSON",
372
-             data: {
373
-                     username: userName,
374
-                     s_ajax_call: validateSToken
375
-             },
376
-             success: function(datafromdb) {
377
-
378
-                        // Get configuration data from SQL database
379
-                        if (datafromdb.wss_server == null || datafromdb.web_socket_port == null || datafromdb.server_path == null ||
380
-                            datafromdb.sip_username == null || datafromdb.sip_password == null) {
381
-
382
-                            ConfigureExtensionWindow();
383
-
384
-                        } else {
385
-
386
-				if (!localStorage.getItem('firstReLoad')) {
387
-				     localStorage['firstReLoad'] = true;
388
-				     window.setTimeout(function() { window.location.reload(); }, 200);
389
-				}
390
-
391
-                                if (datafromdb.stun_server == null || typeof datafromdb.stun_server == 'undefined') {
392
-                                    var stunData = '';
393
-                                } else { var stunData = datafromdb.stun_server; }
394
-
395
-		                localDB.setItem("profileUserID", uID());
396
-				localDB.setItem("userrole", datafromdb.userrole);
397
-				localDB.setItem("wssServer", datafromdb.wss_server);
398
-				localDB.setItem("WebSocketPort", datafromdb.web_socket_port);
399
-				localDB.setItem("ServerPath", datafromdb.server_path);
400
-				localDB.setItem("profileUser", datafromdb.sip_username);
401
-				localDB.setItem("profileName", datafromdb.profile_name);
402
-				localDB.setItem("SipUsername", datafromdb.sip_username);
403
-				localDB.setItem("SipPassword", datafromdb.sip_password);
404
-				localDB.setItem("StunServer", stunData);
405
-				localDB.setItem("AudioOutputId", datafromdb.audio_output_id);
406
-				localDB.setItem("VideoSrcId", datafromdb.video_src_id);
407
-				localDB.setItem("VideoHeight", datafromdb.video_height);
408
-				localDB.setItem("FrameRate", datafromdb.frame_rate);
409
-				localDB.setItem("AspectRatio", datafromdb.aspect_ratio);
410
-				localDB.setItem("VideoOrientation", datafromdb.video_orientation);
411
-				localDB.setItem("AudioSrcId", datafromdb.audio_src_id);
412
-				localDB.setItem("AutoGainControl", datafromdb.auto_gain_control);
413
-				localDB.setItem("EchoCancellation", datafromdb.echo_cancellation);
414
-				localDB.setItem("NoiseSuppression", datafromdb.noise_suppression);
415
-				localDB.setItem("RingOutputId", datafromdb.ring_output_id);
416
-                                localDB.setItem("VidConfExtension", datafromdb.video_conf_extension);
417
-                                localDB.setItem("VidConfWindowWidth", datafromdb.video_conf_window_width);
418
-				localDB.setItem("profilePicture", datafromdb.profile_picture);
419
-				localDB.setItem("Notifications", datafromdb.notifications);
420
-                                localDB.setItem("useRoundcube", datafromdb.use_roundcube);
421
-                                localDB.setItem("rcDomain", (datafromdb.rcdomain != '' && datafromdb.rcdomain != null && typeof datafromdb.rcdomain != 'undefined')? datafromdb.rcdomain : "");
422
-                                localDB.setItem("rcBasicAuthUser", datafromdb.rcbasicauthuser);
423
-                                localDB.setItem("rcBasicAuthPass", datafromdb.rcbasicauthpass);
424
-                                localDB.setItem("RoundcubeUser", datafromdb.rcuser);
425
-                                localDB.setItem("RoundcubePass", datafromdb.rcpassword);
426
-
427
-		                Register();
428
-                        }
429
-                      },
430
-             error: function(datafromdb) {
431
-                           alert("An error occurred while attempting to retrieve account configuration data from the database!");
432
-             }
433
-          });
434
-}
435
-
436
-// Save contact data to SQL database
437
-function saveContactToSQLDB(newPerson) {
438
-
439
-    if (newPerson.length != 0) {
440
-             $.ajax({
441
-                type: "POST",
442
-                url: "save-contact.php",
443
-                dataType: "JSON",
444
-                data: {
445
-                     username: userName,
446
-                     contact_name: newPerson[0],
447
-                     contact_desc: newPerson[1],
448
-                     extension_number: newPerson[2],
449
-                     contact_mobile: newPerson[3],
450
-                     contact_num1: newPerson[4],
451
-                     contact_num2: newPerson[5],
452
-                     contact_email: newPerson[6],
453
-                     s_ajax_call: validateSToken
454
-                },
455
-                success: function(response) {
456
-                         if (response.result != 'success') { alert(response.result); }
457
-                },
458
-                error: function(response) {
459
-                         alert("An error occurred while attempting to save the contact to the database!");
460
-                }
461
-          });
462
-    } else { alert("An error occurred while attempting to save the data!"); }
463
-}
464
-
465
-// Update contact data in SQL database
466
-function updateContactToSQLDB(newPerson) {
467
-
468
-    if (newPerson.length != 0) {
469
-        if (newPerson[7] != '' && newPerson[7] != null && typeof newPerson[7] != 'undefined') {
470
-            $.ajax({
471
-                type: "POST",
472
-                url: "update-contact.php",
473
-                dataType: "JSON",
474
-                data: {
475
-                     contact_name: newPerson[0],
476
-                     contact_desc: newPerson[1],
477
-                     extension_number: newPerson[2],
478
-                     contact_mobile: newPerson[3],
479
-                     contact_num1: newPerson[4],
480
-                     contact_num2: newPerson[5],
481
-                     contact_email: newPerson[6],
482
-                     contactDBID: newPerson[7],
483
-                     s_ajax_call: validateSToken
484
-                },
485
-                success: function(response) {
486
-                         if (response.result != 'success') { alert(response.result); }
487
-                },
488
-                error: function(response) {
489
-                         alert("An error occurred while attempting to save the data!");
490
-                }
491
-            });
492
-        } else { alert("Error while attempting to retrieve contact data from the database!"); }
493
-    } else { alert("An error occurred while attempting to save the data!"); }
494
-}
495
-// Save contact picture data to SQL database
496
-function saveContactPicToSQLDB(newPic) {
497
-
498
-    if (newPic.length != 0) {
499
-        $.ajax({
500
-             type: "POST",
501
-             url: "save-update-contact-picture.php",
502
-             dataType: "JSON",
503
-             data: {
504
-                     username: userName,
505
-                     contact_name: newPic[0],
506
-                     profile_picture_c: newPic[1],
507
-                     s_ajax_call: validateSToken
508
-             },
509
-             success: function(response) {
510
-                      },
511
-             error: function(response) {
512
-                          alert("An error occurred while attempting to save contact picture!");
513
-             }
514
-        });
515
-    } else { alert("An error occurred while attempting to save contact picture!"); }
516
-}
517
-// Get contact data from SQL database
518
-function getContactsFromSQLDB() {
519
-
520
-          $.ajax({
521
-             type: "POST",
522
-             url: "get-contacts.php",
523
-             dataType: "JSON",
524
-             data: {
525
-                     username: userName,
526
-                     s_ajax_call: validateSToken
527
-             },
528
-             success: function(contactsfromdb) {
529
-
530
-                        // Get contacts from SQL database and save them to localDB
531
-                        var jsonCon = InitUserBuddies();
532
-
533
-                        $.each(contactsfromdb.contactsinfo, function(ind, contactrow) {
534
-			       var id = uID();
535
-			       var dateNow = utcDateNow();
536
-
537
-                               if (contactsfromdb.contactsinfo[ind].extension_number == '' || contactsfromdb.contactsinfo[ind].extension_number == null) {
538
- 
539
-				    jsonCon.DataCollection.push(
540
-					{
541
-					    Type: "contact",
542
-					    LastActivity: dateNow,
543
-					    ExtensionNumber: "",
544
-					    MobileNumber: contactsfromdb.contactsinfo[ind].contact_mobile,
545
-					    ContactNumber1: contactsfromdb.contactsinfo[ind].contact_num1,
546
-					    ContactNumber2: contactsfromdb.contactsinfo[ind].contact_num2,
547
-					    uID: null,
548
-					    cID: id,
549
-					    gID: null,
550
-					    DisplayName: contactsfromdb.contactsinfo[ind].contact_name,
551
-					    Position: "",
552
-					    Description: contactsfromdb.contactsinfo[ind].contact_desc, 
553
-					    Email: contactsfromdb.contactsinfo[ind].contact_email,
554
-					    MemberCount: 0
555
-					}
556
-				    );
557
-
558
-                                    if (contactsfromdb.contactsinfo[ind].profile_picture_c != '' && contactsfromdb.contactsinfo[ind].profile_picture_c != null) {
559
-                                        localDB.setItem("img-"+id+"-contact", contactsfromdb.contactsinfo[ind].profile_picture_c);
560
-                                    }
561
-
562
-			            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);
563
-			            AddBuddy(buddyObj, true, false, false);
564
-
565
-                               } else {
566
-
567
-				    jsonCon.DataCollection.push(
568
-					{
569
-					    Type: "extension",
570
-					    LastActivity: dateNow,
571
-					    ExtensionNumber: contactsfromdb.contactsinfo[ind].extension_number,
572
-					    MobileNumber: contactsfromdb.contactsinfo[ind].contact_mobile,
573
-					    ContactNumber1: contactsfromdb.contactsinfo[ind].contact_num1,
574
-					    ContactNumber2: contactsfromdb.contactsinfo[ind].contact_num2,
575
-					    uID: id,
576
-					    cID: null,
577
-					    gID: null,
578
-					    DisplayName: contactsfromdb.contactsinfo[ind].contact_name,
579
-					    Position: contactsfromdb.contactsinfo[ind].contact_desc,
580
-					    Description: "", 
581
-					    Email: contactsfromdb.contactsinfo[ind].contact_email,
582
-					    MemberCount: 0
583
-					}
584
-				    );
585
-
586
-                                    if (contactsfromdb.contactsinfo[ind].profile_picture_c != '' && contactsfromdb.contactsinfo[ind].profile_picture_c != null) {
587
-                                        localDB.setItem("img-"+id+"-extension", contactsfromdb.contactsinfo[ind].profile_picture_c);
588
-                                    }
589
-
590
-			            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);
591
-			            AddBuddy(buddyObj, true, false, true);
592
-                               } 
593
-                        });
594
-
595
-		        jsonCon.TotalRows = jsonCon.DataCollection.length;
596
-		        localDB.setItem(profileUserID + "-Buddies", JSON.stringify(jsonCon));
597
-
598
-                        UpdateUI();
599
-                        PopulateBuddyList();
600
-
601
-                      },
602
-             error: function(contactsfromdb) {
603
-                           alert("An error occurred while attempting to retrieve contacts data from the database!");
604
-             }
605
-          });
606
-}
607
-
608
-// Get external users data from SQL database
609
-function getExternalUserConfFromSqldb() {
610
-
611
-         $.ajax({
612
-             type: "POST",
613
-             url: "get-external-users-conf.php",
614
-             dataType: "JSON",
615
-             data: {
616
-                     username: userName, 
617
-                     s_ajax_call: validateSToken
618
-             },
619
-             success: function(extdatafromdb) {
620
-
621
-                        var extdatafromdbstr = JSON.stringify(extdatafromdb);
622
-
623
-                        if (extdatafromdbstr.length > 0) {
624
-
625
-                            localDB.setItem("externalUserConfElem", extdatafromdb.length);
626
-
627
-                            for (var t = 0; t < extdatafromdb.length; t++) {
628
-				 localDB.setItem("extUserExtension-"+t, extdatafromdb[t]['exten_for_external']);
629
-                                 localDB.setItem("extUserExtensionPass-"+t, extdatafromdb[t]['exten_for_ext_pass']);
630
-                                 localDB.setItem("confAccessLink-"+t, extdatafromdb[t]['conf_access_link']);
631
-                            }
632
-                        }
633
-                      },
634
-             error: function(extdatafromdb) {
635
-                           alert("An error occurred while attempting to retrieve external users configuration data from the database!");
636
-             }
637
-         });
638
-}
639
-
640
-// Check if there are any links for external access associated with the current username
641
-function checkExternalLinks() {
642
-
643
-        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.")) {
644
-
645
-             $.ajax({
646
-                 type: "POST",
647
-                 url: "remove-links-for-external-access.php",
648
-                 dataType: "JSON",
649
-                 data: {
650
-                        username: userName,
651
-                        s_ajax_call: validateSToken
652
-                       },
653
-                 success: function(response) {
654
-                            alert("All the links for external access to conferences associated with your username have been successfully removed from the database!");
655
-
656
-		            Unregister();
657
-			    console.log("Signing Out ...");
658
-			    localStorage.clear();
659
-			    if (winVideoConf != null) {
660
-			        winVideoConf.close();
661
-			    }
662
-			    window.open('https://' + window.location.host + '/logout.php', '_self');
663
-                 },
664
-                 error: function(response) {
665
-                            alert("An error occurred while trying to remove the data from the database!");
666
-
667
-		            Unregister();
668
-			    console.log("Signing Out ...");
669
-			    localStorage.clear();
670
-			    if (winVideoConf != null) {
671
-			        winVideoConf.close();
672
-			    }
673
-			    window.open('https://' + window.location.host + '/logout.php', '_self');
674
-                 }
675
-             });
676
-
677
-        } else {
678
-                 Unregister();
679
-		 console.log("Signing Out ...");
680
-		 localStorage.clear();
681
-		 if (winVideoConf != null) {
682
-		     winVideoConf.close();
683
-		 }
684
-		 window.open('https://' + window.location.host + '/logout.php', '_self');
685
-        }
686
-}
687
-
688
-// Remove contact from SQL database
689
-function deleteBuddyFromSqldb(buddyDisplayName) {
690
-
691
-          $.ajax({
692
-             type: "POST",
693
-             url: "remove-contact.php",
694
-             dataType: "JSON",
695
-             data: {
696
-                     username: userName,
697
-                     contact_name: buddyDisplayName,
698
-                     s_ajax_call: validateSToken
699
-             },
700
-             success: function(delresult) {
701
-             },
702
-             error: function(delresult) {
703
-                        alert("An error occurred while attempting to remove the contact from the database!");
704
-             }
705
-          });
706
-}
707
-
708
-// Save new Roundpin user password
709
-function saveNewUserPassword() {
710
-
711
-      var currentPassword = $("#Current_User_Password").val();
712
-      var newPassword = $("#New_User_Password").val();
713
-      var repeatPassword = $("#Repeat_New_User_Password").val();
714
-
715
-      if (currentPassword == '' || newPassword == '' || repeatPassword == '') { alert("Please fill in all the fields!"); return; }
716
-
717
-      // Verify if the new password meets constraints
718
-      if (/^((?=.*\d)(?=.*[a-z])(?=.*\W).{10,})$/.test(newPassword)) {
719
-
720
-          if (repeatPassword == newPassword) {
721
-		  $.ajax({
722
-		     type: "POST",
723
-		     url: "save-new-user-password.php",
724
-		     dataType: "JSON",
725
-		     data: {
726
-		             username: userName,
727
-		             current_password: currentPassword,
728
-                             new_password: newPassword,
729
-		             s_ajax_call: validateSToken
730
-		     },
731
-		     success: function(passchangemessage) {
732
-                                       alert(passchangemessage);
733
-		     },
734
-		     error: function(passchangemessage) {
735
-		                alert("An error occurred while attempting to change the user password!");
736
-		     }
737
-		  });
738
-          } else { alert("The passwords entered in the new password fields don't match!"); }
739
-
740
-      } else {
741
-          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 ! ");
742
-        }
743
-}
744
-
745
-// Save new Roundpin user email
746
-function saveNewUserEmail() {
747
-
748
-      var currentEmail = $("#Current_User_Email").val();
749
-      var newEmail = $("#New_User_Email").val();
750
-      var repeatEmail = $("#Repeat_New_User_Email").val();
751
-
752
-      if (currentEmail == '' || newEmail == '' || repeatEmail == '') { alert("Please fill in all the fields!"); return; }
753
-
754
-      // Verify if the new email is a valid email address
755
-      if (/^[A-Za-z0-9\_\.\-\~\%\+\!\?\&\*\^\=\#\$\{\}\|\/]+@[A-Za-z0-9\.\-]+\.[A-Za-z0-9\-]{2,63}$/.test(newEmail)) {
756
-
757
-          if (repeatEmail == newEmail) {
758
-		  $.ajax({
759
-		     type: "POST",
760
-		     url: "save-new-user-email.php",
761
-		     dataType: "JSON",
762
-		     data: {
763
-		             username: userName,
764
-		             current_email: currentEmail,
765
-                             new_email: newEmail,
766
-		             s_ajax_call: validateSToken
767
-		     },
768
-		     success: function(emailchangemessage) {
769
-                                       alert(emailchangemessage);
770
-		     },
771
-		     error: function(emailchangemessage) {
772
-		                alert("An error occurred while attempting to change the user email address!");
773
-		     }
774
-		  });
775
-          } else { alert("The email addresses entered in the new email fields don't match!"); }
776
-
777
-      } else {
778
-            alert("The new email address is not a valid email address. Please enter a valid email address!");
779
-        }
780
-}
781
-
782
-// Close Roundpin user account
783
-function closeUserAccount() {
784
-
785
-      closeVideoAudio();
786
-
787
-      ConfirmConfigExtWindow(lang.confirm_close_account, lang.close_roundpin_user_account, function() {
788
-
789
-		  $.ajax({
790
-		     type: "POST",
791
-		     url: "close-user-account.php",
792
-		     dataType: "JSON",
793
-		     data: {
794
-		             username: userName,
795
-		             s_ajax_call: validateSToken
796
-		     },
797
-		     success: function(closeaccountmessage) {
798
-                                       alert(closeaccountmessage);
799
-                                       SignOut();
800
-		     },
801
-		     error: function(closeaccountmessage) {
802
-		                alert("An error occurred while attempting to close your user account!");
803
-		     }
804
-		  });
805
-      });
806
-}
807
-
808
-// Launch video conference
809
-function LaunchVideoConference() {
810
-     if (winVideoConfCheck == 0) {
811
-	    winVideoConf = window.open('https://' + window.location.host + '/videoconference/index.php');
812
-	    winVideoConfCheck = 1;
813
-     } else { alert("The video conference has been launched. If you want to launch it again refresh the page, then click \"Launch Video Conference\"."); }
814
-}
815
-// Generate a new text chat key
816
-function generateChatRSAKeys(currentSIPusername) {
817
-
818
-          var crypto = new JSEncrypt({default_key_size: 1024});
819
-          crypto.getKey();
820
-          var currentChatPubKey = crypto.getPublicKey();
821
-          currentChatPrivKey = crypto.getPrivateKey();
822
-
823
-	  $.ajax({
824
-	     type: "POST",
825
-	     url: "save-text-chat-pub-key.php",
826
-	     dataType: "JSON",
827
-	     data: {
828
-	             currentextension: currentSIPusername,
829
-                     currentchatpubkey: currentChatPubKey,
830
-	             s_ajax_call: validateSToken
831
-	     },
832
-	     success: function() {
833
-	     },
834
-	     error: function() {
835
-	                alert("An error occurred while trying to save the new text chat public key!");
836
-	     }
837
-	  });
838
-}
839
-
840
-// Remove the 'uploads' directory used to temporarily store files received during text chat
841
-function removeTextChatUploads(currentSIPUser) {
842
-	$.ajax({
843
-	     type: "POST",
844
-	     url: "text-chat-remove-uploaded-files.php",
845
-	     dataType: "JSON",
846
-	     data: {
847
-		     sipusername: currentSIPUser,
848
-		     s_ajax_call: validateSToken
849
-	     },
850
-	     success: function(resresult) {
851
-                          if (resresult.note != 'success') {
852
-                              alert("An error occurred while trying to remove the text chat 'uploads' directory!");
853
-                          }
854
-             },
855
-             error: function(resresult) {
856
-                              alert("An error occurred while attempting to remove the text chat 'uploads' directory!");
857
-             }
858
-        });
859
-}
860
-// On page reload, close the video conference tab if it is opened
861
-function closeVideoConfTab() {
862
-         if (winVideoConf) { winVideoConf.close(); }
863
-}
864
-
865
-// Show Email window
866
-function ShowEmailWindow() {
867
-
868
-   if (getDbItem("useRoundcube", "") == 1) {
869
-
870
-      $("#roundcubeFrame").remove();
871
-      $("#rightContent").show();
872
-      $(".streamSelected").each(function() { $(this).css("display", "none"); });
873
-      $("#rightContent").append('<iframe id="roundcubeFrame" name="displayFrame"></iframe>');
874
-
875
-      var rcDomain = '';
876
-      var rcBasicAuthUser = '';
877
-      var rcBasicAuthPass = '';
878
-      var rcUsername = '';
879
-      var rcPasswd = '';
880
-
881
-      $.ajax({
882
-             'async': false,
883
-             'global': false,
884
-             type: "POST",
885
-             url: "get-email-info.php",
886
-             dataType: "JSON",
887
-             data: {
888
-                     username: userName,
889
-                     s_ajax_call: validateSToken
890
-             },
891
-             success: function(datafromdb) {
892
-                               rcDomain = datafromdb.rcdomain;
893
-                               rcBasicAuthUser = encodeURIComponent(datafromdb.rcbasicauthuser);
894
-                               rcBasicAuthPass = encodeURIComponent(datafromdb.rcbasicauthpass);
895
-                               rcUsername = datafromdb.rcuser;
896
-                               rcPasswd = datafromdb.rcpassword;
897
-             },
898
-             error: function(datafromdb) {
899
-                             alert("An error occurred while trying to retrieve data from the database!");
900
-             }
901
-      });
902
-
903
-      if (rcBasicAuthUser != '' && rcBasicAuthPass != '') { 
904
-          var actionURL = "https://"+ rcBasicAuthUser +":"+ rcBasicAuthPass +"@"+ rcDomain +"/"; 
905
-      } else { var actionURL = "https://"+ rcDomain +"/"; }
906
-
907
-      var form = '<form id="rcForm" method="POST" action="'+ actionURL +'" target="displayFrame">'; 
908
-      form += '<input type="hidden" name="_action" value="login" />';
909
-      form += '<input type="hidden" name="_task" value="login" />';
910
-      form += '<input type="hidden" name="_autologin" value="1" />';
911
-      form += '<input name="_user" value="'+ rcUsername +'" type="text" />';
912
-      form += '<input name="_pass" value="'+ rcPasswd +'" type="password" />';
913
-      form += '<input id="submitButton" type="submit" value="Login" />';
914
-      form += '</form>';
915
-
916
-      $("#roundcubeFrame").append(form);
917
-
918
-      if (RCLoginCheck == 0) {
919
-          $("#submitButton").click();
920
-          RCLoginCheck = 1;
921
-      } else { $("#roundcubeFrame").attr("src", actionURL); }
922
-
923
-   } 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'"); }
924
-}
925
-// Shrink the left panel
926
-function CollapseLeftPanel() {
927
-    if ($(window).width() >= 920) {
928
-        if ($("#leftContent").hasClass("shrinkLeftContent")) {
929
-            $("#leftContent").removeClass("shrinkLeftContent");
930
-            $("#rightContent").removeClass("widenRightContent");
931
-            $('#aboutImg').css("margin-right", "-3px");
932
-        } else {
933
-            $("#leftContent").addClass("shrinkLeftContent");
934
-            $("#rightContent").addClass("widenRightContent");
935
-            $('#aboutImg').css("margin-right", "3px");
936
-        }
937
-    }
938
-}
939
-// Show the 'About' window
940
-function ShowAboutWindow() {
941
-
942
-   $.jeegoopopup.close();
943
-   var aboutHtml = '<div>';
944
-   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>';
945
-   aboutHtml += '<div class="UiWindowField scroller">';
946
-   aboutHtml += '<div><img id="AboutLogoImg" src="images/login-logo.svg"/></div>';
947
-   aboutHtml += '<div id="aboutPopup">'+lang.about_text+'</div>';
948
-   aboutHtml += '</div></div>';
949
-
950
-   $.jeegoopopup.open({
951
-                title: 'About Roundpin',
952
-                html: aboutHtml,
953
-                width: '640',
954
-                height: '500',
955
-                center: true,
956
-                scrolling: 'no',
957
-                skinClass: 'jg_popup_basic',
958
-                overlay: true,
959
-                opacity: 50,
960
-                draggable: true,
961
-                resizable: false,
962
-                fadeIn: 0
963
-   });
964
-
965
-   $("#jg_popup_b").append('<button id="ok_button">'+ lang.ok +'</button>');
966
-
967
-   var maxWidth = $(window).width() - 12;
968
-   var maxHeight = $(window).height() - 88;
969
-
970
-   if (maxWidth < 656 || maxHeight < 500) { 
971
-       $.jeegoopopup.width(maxWidth).height(maxHeight);
972
-       $.jeegoopopup.center();
973
-       $("#maximizeImg").hide();
974
-       $("#minimizeImg").hide();
975
-   } else { 
976
-       $.jeegoopopup.width(640).height(500);
977
-       $.jeegoopopup.center();
978
-       $("#minimizeImg").hide();
979
-       $("#maximizeImg").show();
980
-   }
981
-
982
-   $(window).resize(function() {
983
-       maxWidth = $(window).width() - 12;
984
-       maxHeight = $(window).height() - 88;
985
-
986
-       $.jeegoopopup.center();
987
-       if (maxWidth < 656 || maxHeight < 500) { 
988
-           $.jeegoopopup.width(maxWidth).height(maxHeight);
989
-           $.jeegoopopup.center();
990
-           $("#maximizeImg").hide();
991
-           $("#minimizeImg").hide();
992
-       } else { 
993
-           $.jeegoopopup.width(640).height(500);
994
-           $.jeegoopopup.center();
995
-           $("#minimizeImg").hide();
996
-           $("#maximizeImg").show();
997
-       }
998
-   });
999
-
1000
-   
1001
-   $("#minimizeImg").click(function() { $.jeegoopopup.width(640).height(500); $.jeegoopopup.center(); $("#maximizeImg").show(); $("#minimizeImg").hide(); });
1002
-   $("#maximizeImg").click(function() { $.jeegoopopup.width(maxWidth).height(maxHeight); $.jeegoopopup.center(); $("#minimizeImg").show(); $("#maximizeImg").hide(); });
1003
-
1004
-   $("#closeImg").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
1005
-   $("#ok_button").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
1006
-   $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
1007
-   $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); $("#jg_popup_b").empty(); } });
1008
-}
1009
-
1010
-// Show system notifications on incoming calls
1011
-function incomingCallNote() {
1012
-   var incomingCallNotify = new Notification(lang.incomming_call, { icon: "../images/notification-logo.svg", body: "New incoming call !!!" });
1013
-   incomingCallNotify.onclick = function (event) {
1014
-       return;
1015
-   };
1016
-
1017
-   if (document.hasFocus()) {
1018
-       return;
1019
-   } else { setTimeout(incomingCallNote, 8000); }
1020
-}
1021
-
1022
-// Change page title on incoming calls
1023
-function changePageTitle() {
1024
-    if ($(document).attr("title") == "Roundpin") { $(document).prop("title", "New call !!!"); } else { $(document).prop("title", "Roundpin"); }
1025
-    if (document.hasFocus()) {
1026
-        $(document).prop("title", "Roundpin");
1027
-        return;
1028
-    } else { setTimeout(changePageTitle, 460); }
1029
-}
1030
-
1031
-// Window and Document Events
1032
-// ==========================
1033
-$(window).on("beforeunload", function() {
1034
-    Unregister();
1035
-});
1036
-$(window).on("resize", function() {
1037
-    UpdateUI();
1038
-});
1039
-
1040
-// User Interface
1041
-// ==============
1042
-function UpdateUI(){
1043
-    if($(window).outerWidth() < 920){
1044
-        // Narrow Layout
1045
-        if(selectedBuddy == null & selectedLine == null) {
1046
-            // Nobody Selected
1047
-            $("#rightContent").hide();
1048
-
1049
-            $("#leftContent").css("width", "100%");
1050
-            $("#leftContent").show();
1051
-        }
1052
-        else {
1053
-            $("#rightContent").css("margin-left", "0px");
1054
-            $("#rightContent").show();
1055
-
1056
-            $("#leftContent").hide();
1057
-
1058
-            if(selectedBuddy != null) updateScroll(selectedBuddy.identity);
1059
-        }
1060
-    }
1061
-    else {
1062
-        // Wide Screen Layout
1063
-        if(selectedBuddy == null & selectedLine == null) {
1064
-            $("#leftContent").css("width", "320px");
1065
-            $("#rightContent").css("margin-left", "0px");
1066
-            $("#leftContent").show();
1067
-            $("#rightContent").hide();
1068
-        }
1069
-        else{
1070
-            $("#leftContent").css("width", "320px");
1071
-            $("#rightContent").css("margin-left", "320px");
1072
-            $("#leftContent").show();
1073
-            $("#rightContent").show();
1074
-
1075
-            if(selectedBuddy != null) updateScroll(selectedBuddy.identity);
1076
-        }
1077
-    }
1078
-    for(var l=0; l<Lines.length; l++){
1079
-        updateLineScroll(Lines[l].LineNumber);
1080
-    }
1081
-}
1082
-
1083
-// UI Windows
1084
-// ==========
1085
-function AddSomeoneWindow(numberStr){
1086
-
1087
-    $("#userMenu").hide();
1088
-    $.jeegoopopup.close();
1089
-
1090
-    var html = "<div id='AddNewContact'>";
1091
-
1092
-    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>";
1093
-
1094
-    html += "<div class='UiWindowField scroller'>";
1095
-
1096
-    html += "<div class=UiText>"+ lang.display_name +":</div>";
1097
-    html += "<div><input id=AddSomeone_Name class=UiInputText type=text placeholder='"+ lang.eg_display_name +"'></div>";
1098
-
1099
-    html += "<div class=UiText>"+ lang.title_description +":</div>";
1100
-    html += "<div><input id=AddSomeone_Desc class=UiInputText type=text placeholder='"+ lang.eg_general_manager +"'></div>";
1101
-
1102
-    html += "<div class=UiText>"+ lang.internal_subscribe_extension +":</div>";
1103
-    if(numberStr && numberStr.length > 1 && numberStr.length < DidLength && numberStr.substring(0,1) != "*"){
1104
-        html += "<div><input id=AddSomeone_Exten class=UiInputText type=text value="+ numberStr +" placeholder='"+ lang.eg_internal_subscribe_extension +"'></div>";
1105
-    }
1106
-    else{
1107
-        html += "<div><input id=AddSomeone_Exten class=UiInputText type=text placeholder='"+ lang.eg_internal_subscribe_extension +"'></div>";
1108
-    }
1109
-
1110
-    html += "<div class=UiText>"+ lang.mobile_number +":</div>";
1111
-    html += "<div><input id=AddSomeone_Mobile class=UiInputText type=text placeholder='"+ lang.eg_mobile_number +"'></div>";
1112
-
1113
-    html += "<div class=UiText>"+ lang.contact_number_1 +":</div>";
1114
-    if(numberStr && numberStr.length > 1){
1115
-        html += "<div><input id=AddSomeone_Num1 class=UiInputText type=text value="+ numberStr +" placeholder='"+ lang.eg_contact_number_1 +"'></div>";
1116
-    }
1117
-    else {
1118
-        html += "<div><input id=AddSomeone_Num1 class=UiInputText type=text placeholder='"+ lang.eg_contact_number_1 +"'></div>";
1119
-    }
1120
-
1121
-    html += "<div class=UiText>"+ lang.contact_number_2 +":</div>";
1122
-    html += "<div><input id=AddSomeone_Num2 class=UiInputText type=text placeholder='"+ lang.eg_contact_number_2 +"'></div>";
1123
-
1124
-    html += "<div class=UiText>"+ lang.email +":</div>";
1125
-    html += "<div><input id=AddSomeone_Email class=UiInputText type=text placeholder='"+ lang.eg_email +"'></div>";
1126
-
1127
-    html += "</div></div>"
1128
-
1129
-    $.jeegoopopup.open({
1130
-                title: 'Add Contact',
1131
-                html: html,
1132
-                width: '640',
1133
-                height: '500',
1134
-                center: true,
1135
-                scrolling: 'no',
1136
-                skinClass: 'jg_popup_basic',
1137
-                contentClass: 'addContactPopup',
1138
-                overlay: true,
1139
-                opacity: 50,
1140
-                draggable: true,
1141
-                resizable: false,
1142
-                fadeIn: 0
1143
-    });
1144
-
1145
-    $("#jg_popup_b").append("<div id=bottomButtons><button id=save_button>Save</button><button id=cancel_button>Cancel</button></div>");
1146
-
1147
-    $("#save_button").click(function() {
1148
-
1149
-      var currentASName = $("#AddSomeone_Name").val();
1150
-
1151
-      if (currentASName != null && currentASName.trim() !== '') {
1152
-
1153
-        if (/^[A-Za-z0-9\s\-\'\[\]\(\)]+$/.test(currentASName)) {
1154
-
1155
-	   var currentDesc = $("#AddSomeone_Desc").val();
1156
-	   if (currentDesc != null && currentDesc.trim() !== '') {
1157
-	       if (/^[A-Za-z0-9\s\-\.\'\"\[\]\(\)\{\}\_\!\?\~\@\%\^\&\*\+\>\<\;\:\=]+$/.test(currentDesc)) { var finCurrentDesc = currentDesc; } else { 
1158
-		   var finCurrentDesc = ''; alert('The title/description that you entered is not valid!'); }
1159
-	   } else { var finCurrentDesc = ''; }
1160
-
1161
-	   var currentExtension = $("#AddSomeone_Exten").val();
1162
-	   if (currentExtension != null && currentExtension.trim() !== '') {
1163
-	       if (/^[a-zA-Z0-9\*\#]+$/.test(currentExtension)) { var finCurrentExtension = currentExtension; } else { 
1164
-		   var finCurrentExtension = ''; alert("The extension that you entered in the 'Extension (Internal)' field is not a valid extension!"); }
1165
-	   } else { var finCurrentExtension = ''; }
1166
-
1167
-	   var currentMobile = $("#AddSomeone_Mobile").val();
1168
-	   if (currentMobile != null && currentMobile.trim() !== '') {
1169
-	       if (/^[0-9\s\+\#]+$/.test(currentMobile)) { var finCurrentMobile = currentMobile; } else {
1170
-		   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."); }
1171
-	   } else { var finCurrentMobile = ''; }
1172
-
1173
-	   var currentNum1 = $("#AddSomeone_Num1").val();
1174
-	   if (currentNum1 != null && currentNum1.trim() !== '') {
1175
-	       if (/^[0-9\s\+\#]+$/.test(currentNum1)) { var finCurrentNum1 = currentNum1; } else {
1176
-		   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."); }
1177
-	   } else { var finCurrentNum1 = ''; }
1178
-
1179
-	   var currentNum2 = $("#AddSomeone_Num2").val();
1180
-	   if (currentNum2 != null && currentNum2.trim() !== '') {
1181
-	       if (/^[0-9\s\+\#]+$/.test(currentNum2)) { var finCurrentNum2 = currentNum2; } else {
1182
-		   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."); }
1183
-           } else { var finCurrentNum2 = ''; }
1184
-
1185
-	   var currentEmail = $("#AddSomeone_Email").val();
1186
-	   if (currentEmail != null && currentEmail.trim() !== '') {
1187
-	       if (/^[A-Za-z0-9\_\.\-\~\%\+\!\?\&\*\^\=\#\$\{\}\|\/]+@[A-Za-z0-9\.\-]+\.[A-Za-z0-9\-]{2,63}$/.test(currentEmail)) { var finCurrentEmail = currentEmail; } else {
1188
-		   var finCurrentEmail = ''; alert("The email that you entered is not a valid email address!"); }
1189
-	   } else { var finCurrentEmail = ''; }
1190
-
1191
-
1192
-           // Add Contact / Extension
1193
-           var json = JSON.parse(localDB.getItem(profileUserID + "-Buddies"));
1194
-           if(json == null) json = InitUserBuddies();
1195
-
1196
-           if(finCurrentExtension == ''){
1197
-               // Add Regular Contact
1198
-               var id = uID();
1199
-               var dateNow = utcDateNow();
1200
-               json.DataCollection.push(
1201
-                   {
1202
-                    Type: "contact",
1203
-                    LastActivity: dateNow,
1204
-                    ExtensionNumber: "",
1205
-                    MobileNumber: finCurrentMobile,
1206
-                    ContactNumber1: finCurrentNum1,
1207
-                    ContactNumber2: finCurrentNum2,
1208
-                    uID: null,
1209
-                    cID: id,
1210
-                    gID: null,
1211
-                    DisplayName: currentASName,
1212
-                    Position: "",
1213
-                    Description: finCurrentDesc,
1214
-                    Email: finCurrentEmail,
1215
-                    MemberCount: 0
1216
-                   }
1217
-               );
1218
-               var newPerson = [];
1219
-               newPerson = [currentASName, finCurrentDesc, "", finCurrentMobile, finCurrentNum1, finCurrentNum2, finCurrentEmail];
1220
-               saveContactToSQLDB(newPerson);
1221
-
1222
-               var buddyObj = new Buddy("contact", id, currentASName, "", finCurrentMobile, finCurrentNum1, finCurrentNum2, dateNow, finCurrentDesc, finCurrentEmail);
1223
-               AddBuddy(buddyObj, false, false, false);
1224
-
1225
-           } else {
1226
-               // Add Extension
1227
-               var id = uID();
1228
-               var dateNow = utcDateNow();
1229
-               json.DataCollection.push(
1230
-                   {
1231
-                    Type: "extension",
1232
-                    LastActivity: dateNow,
1233
-                    ExtensionNumber: finCurrentExtension,
1234
-                    MobileNumber: finCurrentMobile,
1235
-                    ContactNumber1: finCurrentNum1,
1236
-                    ContactNumber2: finCurrentNum2,
1237
-                    uID: id,
1238
-                    cID: null,
1239
-                    gID: null,
1240
-                    DisplayName: currentASName,
1241
-                    Position: finCurrentDesc,
1242
-                    Description: "",
1243
-                    Email: finCurrentEmail,
1244
-                    MemberCount: 0
1245
-                   }
1246
-               );
1247
-
1248
-               var newPerson = [];
1249
-
1250
-               newPerson = [currentASName, finCurrentDesc, finCurrentExtension, finCurrentMobile, finCurrentNum1, finCurrentNum2, finCurrentEmail];
1251
-               saveContactToSQLDB(newPerson);
1252
-
1253
-               var buddyObj = new Buddy("extension", id, currentASName, finCurrentExtension, finCurrentMobile, finCurrentNum1, finCurrentNum2, dateNow, finCurrentDesc, finCurrentEmail);
1254
-               AddBuddy(buddyObj, false, false, true);
1255
-
1256
-           }
1257
-           // Update Size:
1258
-           json.TotalRows = json.DataCollection.length;
1259
-
1260
-           // Save To Local DB
1261
-           localDB.setItem(profileUserID + "-Buddies", JSON.stringify(json));
1262
-           UpdateBuddyList();
1263
-
1264
-           $.jeegoopopup.close();
1265
-           $("#jg_popup_b").empty();
1266
-
1267
-        } else { alert('The display name that you entered is not a valid display name!'); }
1268
-
1269
-      } else { alert("'Display Name' cannot be empty!"); }
1270
-       
1271
-   });
1272
-
1273
-   var maxWidth = $(window).width() - 12;
1274
-   var maxHeight = $(window).height() - 110;
1275
-
1276
-   if (maxWidth < 656 || maxHeight < 500) { 
1277
-       $.jeegoopopup.width(maxWidth).height(maxHeight);
1278
-       $.jeegoopopup.center();
1279
-       $("#maximizeImg").hide();
1280
-       $("#minimizeImg").hide();
1281
-   } else { 
1282
-       $.jeegoopopup.width(640).height(500);
1283
-       $.jeegoopopup.center();
1284
-       $("#minimizeImg").hide();
1285
-       $("#maximizeImg").show();
1286
-   }
1287
-
1288
-   $(window).resize(function() {
1289
-       maxWidth = $(window).width() - 16;
1290
-       maxHeight = $(window).height() - 110;
1291
-       $.jeegoopopup.center();
1292
-       if (maxWidth < 656 || maxHeight < 500) { 
1293
-           $.jeegoopopup.width(maxWidth).height(maxHeight);
1294
-           $.jeegoopopup.center();
1295
-           $("#maximizeImg").hide();
1296
-           $("#minimizeImg").hide();
1297
-       } else { 
1298
-           $.jeegoopopup.width(640).height(500);
1299
-           $.jeegoopopup.center();
1300
-           $("#minimizeImg").hide();
1301
-           $("#maximizeImg").show();
1302
-       }
1303
-   });
1304
-
1305
-   $("#minimizeImg").click(function() { $.jeegoopopup.width(640).height(500); $.jeegoopopup.center(); $("#maximizeImg").show(); $("#minimizeImg").hide(); });
1306
-   $("#maximizeImg").click(function() { $.jeegoopopup.width(maxWidth).height(maxHeight); $.jeegoopopup.center(); $("#minimizeImg").show(); $("#maximizeImg").hide(); });
1307
-
1308
-   $("#closeImg").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
1309
-   $("#cancel_button").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
1310
-   $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
1311
-   $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); $("#jg_popup_b").empty(); } });
1312
-}
1313
-
1314
-function CreateGroupWindow(){
1315
-}
1316
-
1317
-function closeVideoAudio() {
1318
-
1319
-        var localVideo = $("#local-video-preview").get(0);
1320
-        try{
1321
-            var tracks = localVideo.srcObject.getTracks();
1322
-            tracks.forEach(function(track) {
1323
-                track.stop();
1324
-            });
1325
-            localVideo.srcObject = null;
1326
-        }
1327
-        catch(e){}
1328
-
1329
-        try{
1330
-            var tracks = window.SettingsMicrophoneStream.getTracks();
1331
-            tracks.forEach(function(track) {
1332
-                track.stop();
1333
-            });
1334
-        }
1335
-        catch(e){}
1336
-        window.SettingsMicrophoneStream = null;
1337
-
1338
-        try{
1339
-            var soundMeter = window.SettingsMicrophoneSoundMeter;
1340
-            soundMeter.stop();
1341
-        }
1342
-        catch(e){}
1343
-        window.SettingsMicrophoneSoundMeter = null;
1344
-
1345
-        try{
1346
-            window.SettingsOutputAudio.pause();
1347
-        }
1348
-        catch(e){}
1349
-        window.SettingsOutputAudio = null;
1350
-
1351
-        try{
1352
-            var tracks = window.SettingsOutputStream.getTracks();
1353
-            tracks.forEach(function(track) {
1354
-                track.stop();
1355
-            });
1356
-        }
1357
-        catch(e){}
1358
-        window.SettingsOutputStream = null;
1359
-
1360
-        try{
1361
-            var soundMeter = window.SettingsOutputStreamMeter;
1362
-            soundMeter.stop();
1363
-        }
1364
-        catch(e){}
1365
-        window.SettingsOutputStreamMeter = null;
1366
-
1367
-        return true;
1368
-}
1369
-function ConfigureExtensionWindow() {
1370
-
1371
-    $("#settingsCMenu").hide();
1372
-    $.jeegoopopup.close();
1373
-
1374
-    var configWindow = "<div id=\"mainConfWindow\">";
1375
-    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>"; 
1376
-    configWindow += "<div id=\"mainRightConf\">";
1377
-    configWindow += "<div id=\"rightMainConfWindow\">";
1378
-
1379
-    configWindow +=  "<div id=\"AccountHtml\" class=\"settingsSubSection\" style=\"display:block;\">";
1380
-    configWindow += "<div class=UiText>"+ lang.asterisk_server_address +": *</div>";
1381
-    configWindow += "<div><input id=Configure_Account_wssServer class=UiInputText type=text placeholder='"+ lang.eg_asterisk_server_address +"' value='"+ getDbItem("wssServer", "") +"'></div>";
1382
-    configWindow += "<div class=UiText>"+ lang.websocket_port +": *</div>";
1383
-    configWindow += "<div><input id=Configure_Account_WebSocketPort class=UiInputText type=text placeholder='"+ lang.eg_websocket_port +"' value='"+ getDbItem("WebSocketPort", "") +"'></div>";
1384
-    configWindow += "<div class=UiText>"+ lang.websocket_path +": *</div>";
1385
-    configWindow += "<div><input id=Configure_Account_ServerPath class=UiInputText type=text placeholder='"+ lang.eg_websocket_path +"' value='"+ getDbItem("ServerPath", "") +"'></div>";
1386
-    configWindow += "<div class=UiText>"+ lang.display_name +": *</div>";
1387
-
1388
-    var escapedDisplayName = 'value="' + getDbItem("profileName", "").replace("'","\'") + '"';
1389
-    configWindow += "<div><input id=Configure_Account_profileName class=UiInputText type=text placeholder='"+ lang.eg_display_name +"' "+ escapedDisplayName +"></div>";
1390
-    configWindow += "<div class=UiText>"+ lang.sip_username +": *</div>";
1391
-    configWindow += "<div><input id=Configure_Account_SipUsername class=UiInputText type=text placeholder='"+ lang.eg_sip_username +"' value='"+ getDbItem("SipUsername", "") +"'></div>";
1392
-    configWindow += "<div class=UiText>"+ lang.sip_password +": *</div>";
1393
-    configWindow += "<div><input id=Configure_Account_SipPassword class=UiInputText type=password placeholder='"+ lang.eg_sip_password +"' value='"+ getDbItem("SipPassword", "") +"'></div>";
1394
-    configWindow += "<div class=UiText>"+ lang.stun_server +":</div>";
1395
-    configWindow += "<div><input id=Configure_Account_StunServer class=UiInputText type=text placeholder='Eg: 123.123.123.123:8443' value='"+ getDbItem("StunServer", "") +"'></div>";
1396
-    configWindow += "<p style=\"color:#363636;\">* Required field.</p><br><br></div>";
1397
-
1398
-    configWindow += "<div id=\"AudioVideoHtml\" class=\"settingsSubSection\" style=\"display:none;\">";
1399
-    configWindow += "<div class=UiText>"+ lang.speaker +":</div>";
1400
-    configWindow += "<div style=\"text-align:center\"><select id=playbackSrc style=\"width:100%\"></select></div>";
1401
-    configWindow += "<div class=Settings_VolumeOutput_Container><div id=Settings_SpeakerOutput class=Settings_VolumeOutput></div></div>";
1402
-    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>";
1403
-
1404
-    configWindow += "<br><div class=UiText>"+ lang.ring_device +":</div>";
1405
-    configWindow += "<div style=\"text-align:center\"><select id=ringDevice style=\"width:100%\"></select></div>";
1406
-    configWindow += "<div class=Settings_VolumeOutput_Container><div id=Settings_RingerOutput class=Settings_VolumeOutput></div></div>";
1407
-    configWindow += "<div><button class=on_white id=preview_ringer_play><i class=\"fa fa-play\"></i></button></div>";
1408
-
1409
-    configWindow += "<br><div class=UiText>"+ lang.microphone +":</div>";
1410
-    configWindow += "<div style=\"text-align:center\"><select id=microphoneSrc style=\"width:100%\"></select></div>";
1411
-    configWindow += "<div class=Settings_VolumeOutput_Container><div id=Settings_MicrophoneOutput class=Settings_VolumeOutput></div></div>";
1412
-    configWindow += "<br><br><div><input type=checkbox id=Settings_AutoGainControl><label for=Settings_AutoGainControl> "+ lang.auto_gain_control +"<label></div>";
1413
-    configWindow += "<div><input type=checkbox id=Settings_EchoCancellation><label for=Settings_EchoCancellation> "+ lang.echo_cancellation +"<label></div>";
1414
-    configWindow += "<div><input type=checkbox id=Settings_NoiseSuppression><label for=Settings_NoiseSuppression> "+ lang.noise_suppression +"<label></div>";
1415
-    configWindow += "<br><div class=UiText>"+ lang.camera +":</div>";
1416
-    configWindow += "<div style=\"text-align:center\"><select id=previewVideoSrc style=\"width:100%\"></select></div>";
1417
-    configWindow += "<br><div class=UiText>"+ lang.frame_rate +":</div>"
1418
-    configWindow += "<div class=pill-nav>";
1419
-    configWindow += "<input name=Settings_FrameRate id=r40 type=radio value=\"2\"><label class=radio_pill for=r40>2</label>";
1420
-    configWindow += "<input name=Settings_FrameRate id=r41 type=radio value=\"5\"><label class=radio_pill for=r41>5</label>";
1421
-    configWindow += "<input name=Settings_FrameRate id=r42 type=radio value=\"10\"><label class=radio_pill for=r42>10</label>";
1422
-    configWindow += "<input name=Settings_FrameRate id=r43 type=radio value=\"15\"><label class=radio_pill for=r43>15</label>";
1423
-    configWindow += "<input name=Settings_FrameRate id=r44 type=radio value=\"20\"><label class=radio_pill for=r44>20</label>";
1424
-    configWindow += "<input name=Settings_FrameRate id=r45 type=radio value=\"25\"><label class=radio_pill for=r45>25</label>";
1425
-    configWindow += "<input name=Settings_FrameRate id=r46 type=radio value=\"30\"><label class=radio_pill for=r46>30</label>";
1426
-    configWindow += "<input name=Settings_FrameRate id=r47 type=radio value=\"\"><label class=radio_pill for=r47><i class=\"fa fa-trash\"></i></label>";
1427
-    configWindow += "</div>";
1428
-    configWindow += "<br><br><div class=UiText>"+ lang.quality +":</div>";
1429
-    configWindow += "<div class=pill-nav>";
1430
-    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>";
1431
-    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>";
1432
-    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>";
1433
-    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>";
1434
-    configWindow += "<input name=Settings_Quality id=r34 type=radio value=\"\"><label class=radio_pill for=r34><i class=\"fa fa-trash\"></i></label>";
1435
-    configWindow += "</div>";
1436
-    configWindow += "<br><br><div class=UiText>"+ lang.image_orientation +":</div>";
1437
-    configWindow += "<div class=pill-nav>";
1438
-    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>";
1439
-    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>";
1440
-    configWindow += "</div>";
1441
-    configWindow += "<br><br><div class=UiText>"+ lang.aspect_ratio +":</div>";
1442
-    configWindow += "<div class=pill-nav>";
1443
-    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>";
1444
-    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>";
1445
-    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>";
1446
-    configWindow += "<input name=Settings_AspectRatio id=r13 type=radio value=\"\"><label class=radio_pill for=r13><i class=\"fa fa-trash\"></i></label>";
1447
-    configWindow += "</div>";
1448
-    configWindow += "<br><br><div class=UiText>"+ lang.preview +":</div>";
1449
-    configWindow += "<div style=\"text-align:center; margin-top:10px\"><video id=\"local-video-preview\" class=\"previewVideo\"></video></div>";
1450
-    configWindow += "<br><div class=UiText>"+ lang.video_conference_extension +":</div>";
1451
-    configWindow += "<div><input id=Video_Conf_Extension class=UiInputText type=text placeholder='"+ lang.video_conference_extension_example +"' value='"+ getDbItem("VidConfExtension", "") +"'></div>";
1452
-    configWindow += "<br><div class=UiText>"+ lang.video_conference_window_width +":</div>";
1453
-    configWindow += "<div><input id=Video_Conf_Window_Width class=UiInputText type=text placeholder='"+ lang.video_conf_window_width_explanation +"' value='"+ getDbItem("VidConfWindowWidth", "") +"'></div>";
1454
-    if (getDbItem("userrole", "") == "superadmin") {
1455
-
1456
-	configWindow += "<div id=confTableSection>"+ lang.external_conf_users +"</div>";
1457
-        configWindow += "<div class=confTable><table id=vidConfExternalTable>";
1458
-        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>";
1459
-
1460
-        for (var cqt = 0; cqt < getDbItem("externalUserConfElem", ""); cqt++) {
1461
-	     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>";
1462
-        }
1463
-
1464
-	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>";
1465
-        configWindow += "</table></div>";
1466
-	configWindow += "<button id=add_New_External_User>Add External User</button>";
1467
-    }
1468
-    configWindow += "<br><br></div>";
1469
-
1470
-    configWindow += "<div id=\"AppearanceHtml\" class=\"settingsSubSection\" style=\"display:none;\">";
1471
-    configWindow += "<div id=ImageCanvas style=\"width:150px; height:150px;\"></div>";
1472
-    configWindow += "<label for=fileUploader class=customBrowseButton style=\"margin-left: 200px; margin-top: -2px;\">Select File</label>";
1473
-    configWindow += "<div><input id=fileUploader type=file></div>";
1474
-    configWindow += "<div style=\"margin-top: 50px\"></div>";
1475
-    configWindow += "</div>";
1476
-
1477
-    configWindow += "<div id=\"NotificationsHtml\" class=\"settingsSubSection\" style=\"display:none;\">";
1478
-    configWindow += "<div class=UiText>"+ lang.notifications +":</div>";
1479
-    configWindow += "<div id=\"notificationsCheck\"><input type=checkbox id=Settings_Notifications><label for=Settings_Notifications> "+ lang.enable_onscreen_notifications +"<label></div>";
1480
-    configWindow += "</div>";
1481
-
1482
-    configWindow += "<div id=\"RoundcubeEmailHtml\" class=\"settingsSubSection\" style=\"display:none;\">";
1483
-    configWindow += "<div class=UiText>"+ lang.email_integration +":</div>";
1484
-    configWindow += "<div id=\"enableRCcheck\"><input id=emailIntegration type=checkbox ><label for=emailIntegration> "+ lang.enable_roundcube_integration +"<label></div>";
1485
-    configWindow += "<div class=UiText>"+ lang.roundcube_domain +":</div>";
1486
-    configWindow += "<div><input id=RoundcubeDomain class=UiInputText type=text placeholder='Roundcube domain (Eg: mail.example.com).' value='"+ getDbItem("rcDomain", "") +"'></div>";
1487
-    configWindow += "<div class=UiText>"+ lang.roundcube_user +":</div>";
1488
-    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>";
1489
-    configWindow += "<div class=UiText>"+ lang.roundcube_password +":</div>";
1490
-    configWindow += "<div><input id=RoundcubePass class=UiInputText type=password placeholder='Roundcube login password.' value='"+ getDbItem("RoundcubePass", "") +"'></div>";
1491
-    configWindow += "<div class=UiText>"+ lang.rc_basic_auth_user +":</div>";
1492
-    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>";
1493
-    configWindow += "<div class=UiText>"+ lang.rc_basic_auth_password +":</div>";
1494
-    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>";
1495
-
1496
-    configWindow += "<br><br></div>";
1497
-
1498
-    configWindow += "<div id=\"ChangePasswordHtml\" class=\"settingsSubSection\" style=\"display:none;\">";
1499
-    configWindow += "<div class=UiText>"+ lang.current_user_password +":</div>";
1500
-    configWindow += "<div><input id=Current_User_Password class=UiInputText type=password placeholder='Enter your current Roundpin user password.' value=''></div>";
1501
-    configWindow += "<div class=UiText>"+ lang.new_user_password +":</div>";
1502
-    configWindow += "<div><input id=New_User_Password class=UiInputText type=password placeholder='Enter your new Roundpin user password.' value=''></div>";
1503
-    configWindow += "<div class=UiText>"+ lang.repeat_new_user_password +":</div>";
1504
-    configWindow += "<div><input id=Repeat_New_User_Password class=UiInputText type=password placeholder='Enter your new Roundpin user password again.' value=''></div><br>";
1505
-    configWindow += "<div><input id=Save_New_User_Password type=button value='Save New Password' onclick='saveNewUserPassword()' ></div>";
1506
-    configWindow += "<br><br></div>";
1507
-
1508
-    configWindow += "<div id=\"ChangeEmailHtml\" class=\"settingsSubSection\" style=\"display:none;\">";
1509
-    configWindow += "<div class=UiText>"+ lang.current_user_email +":</div>";
1510
-    configWindow += "<div><input id=Current_User_Email class=UiInputText type=text placeholder='Enter your current Roundpin email address.' value=''></div>";
1511
-    configWindow += "<div class=UiText>"+ lang.new_user_email +":</div>";
1512
-    configWindow += "<div><input id=New_User_Email class=UiInputText type=text placeholder='Enter your new email address.' value=''></div>";
1513
-    configWindow += "<div class=UiText>"+ lang.repeat_new_user_email +":</div>";
1514
-    configWindow += "<div><input id=Repeat_New_User_Email class=UiInputText type=text placeholder='Enter your new email address again.' value=''></div><br>";
1515
-    configWindow += "<div><input id=Save_New_User_Email type=button value='Save New Email' onclick='saveNewUserEmail()' ></div>";
1516
-    configWindow += "<br><br></div>";
1517
-
1518
-    configWindow += "<div id=\"CloseAccountHtml\" class=\"settingsSubSection\" style=\"display:none;\">";
1519
-    configWindow += "<div class=UiText>"+ lang.if_you_want_to_close_account +":</div><br><br>";
1520
-    configWindow += "<div><input id=Close_User_Account type=button value='Close User Account' onclick='closeUserAccount()' ></div>";
1521
-    configWindow += "<br><br></div>";
1522
-
1523
-    configWindow += "</div></div></div>";
1524
-
1525
-    var settingsSections = "<table id=leftPanelSettings cellspacing=14 cellpadding=0 style=\"width:184px;margin-left:8px;margin-top:14px;font-size:15px;\">";
1526
-    settingsSections += "<tr id=ConnectionSettingsRow><td class=SettingsSection>Connection Settings</td></tr>";
1527
-    settingsSections += "<tr id=AudioAndVideoRow><td class=SettingsSection>Audio & Video</td></tr>";
1528
-    settingsSections += "<tr id=ProfilePictureRow><td class=SettingsSection>Profile Picture</td></tr>";
1529
-    settingsSections += "<tr id=NotificationsRow><td class=SettingsSection>Notifications</td></tr>";
1530
-    settingsSections += "<tr id=RoundcubeEmailRow><td class=SettingsSection>Email Integration</td></tr>";
1531
-    settingsSections += "<tr id=ChangePasswordRow><td class=SettingsSection>Change Password</td></tr>";
1532
-    settingsSections += "<tr id=ChangeEmailRow><td class=SettingsSection>Change Email</td></tr>";
1533
-    settingsSections += "<tr id=CloseAccountRow><td class=SettingsSection>Close Account</td></tr></table>";
1534
-
1535
-    $.jeegoopopup.open({
1536
-                title: '<span id=settingsTitle>Settings</span>',
1537
-                html: configWindow,
1538
-                width: '520',
1539
-                height: '500',
1540
-                center: true,
1541
-                scrolling: 'no',
1542
-                skinClass: 'jg_popup_basic',
1543
-                contentClass: 'configPopup',
1544
-                overlay: true,
1545
-                opacity: 50,
1546
-                draggable: true,
1547
-                resizable: false,
1548
-                fadeIn: 0
1549
-    });
1550
-
1551
-    $("#jg_popup_b").append('<div id="bottomButtonsConf"><button id="save_button_conf">Save</button><button id="cancel_button_conf">Cancel</button></div>');
1552
-    $("#jg_popup_l").append(settingsSections);
1553
-
1554
-    if (getDbItem("useRoundcube", "") == 1) { $("#emailIntegration").prop("checked", true); } else { $("#emailIntegration").prop("checked", false); }
1555
-
1556
-    $("#ConnectionSettingsRow td").addClass("selectedSettingsSection");
1557
-
1558
-    $("#ConnectionSettingsRow").click(function() {
1559
-        $(".settingsSubSection").each(function() { $(this).css("display", "none"); });
1560
-        $("#AccountHtml").css("display", "block");
1561
-        $(".SettingsSection").each(function() { $(this).removeClass("selectedSettingsSection"); });
1562
-        $("#ConnectionSettingsRow td").addClass("selectedSettingsSection");
1563
-    });
1564
-
1565
-    $("#ProfilePictureRow").click(function() {
1566
-        $(".settingsSubSection").each(function() { $(this).css("display", "none"); });
1567
-        $("#AppearanceHtml").css("display", "block");
1568
-        $(".SettingsSection").each(function() { $(this).removeClass("selectedSettingsSection"); });
1569
-        $("#ProfilePictureRow td").addClass("selectedSettingsSection");
1570
-    });
1571
-
1572
-    $("#NotificationsRow").click(function() {
1573
-        $(".settingsSubSection").each(function() { $(this).css("display", "none"); });
1574
-        $("#NotificationsHtml").css("display", "block");
1575
-        $(".SettingsSection").each(function() { $(this).removeClass("selectedSettingsSection"); });
1576
-        $("#NotificationsRow td").addClass("selectedSettingsSection");
1577
-    });
1578
-
1579
-    $("#RoundcubeEmailRow").click(function() {
1580
-        $(".settingsSubSection").each(function() { $(this).css("display", "none"); });
1581
-        $("#RoundcubeEmailHtml").css("display", "block");
1582
-        $(".SettingsSection").each(function() { $(this).removeClass("selectedSettingsSection"); });
1583
-        $("#RoundcubeEmailRow td").addClass("selectedSettingsSection");
1584
-    });
1585
-
1586
-    $("#ChangePasswordRow").click(function() {
1587
-        $(".settingsSubSection").each(function() { $(this).css("display", "none"); });
1588
-        $("#ChangePasswordHtml").css("display", "block");
1589
-        $(".SettingsSection").each(function() { $(this).removeClass("selectedSettingsSection"); });
1590
-        $("#ChangePasswordRow td").addClass("selectedSettingsSection");
1591
-    });
1592
-
1593
-    $("#ChangeEmailRow").click(function() {
1594
-        $(".settingsSubSection").each(function() { $(this).css("display", "none"); });
1595
-        $("#ChangeEmailHtml").css("display", "block");
1596
-        $(".SettingsSection").each(function() { $(this).removeClass("selectedSettingsSection"); });
1597
-        $("#ChangeEmailRow td").addClass("selectedSettingsSection");
1598
-    });
1599
-
1600
-    $("#CloseAccountRow").click(function() {
1601
-        $(".settingsSubSection").each(function() { $(this).css("display", "none"); });
1602
-        $("#CloseAccountHtml").css("display", "block");
1603
-        $(".SettingsSection").each(function() { $(this).removeClass("selectedSettingsSection"); });
1604
-        $("#CloseAccountRow td").addClass("selectedSettingsSection");
1605
-    });
1606
-
1607
-    var maxWidth = $(window).width() - 192;
1608
-    var maxHeight = $(window).height() - 98;
1609
-
1610
-    if (maxWidth < 520 || maxHeight < 500) { 
1611
-       $.jeegoopopup.width(maxWidth).height(maxHeight);
1612
-       $.jeegoopopup.center();
1613
-       $("#maximizeImg").hide();
1614
-       $("#minimizeImg").hide();
1615
-    } else { 
1616
-       $.jeegoopopup.width(520).height(500);
1617
-       $.jeegoopopup.center();
1618
-       $("#minimizeImg").hide();
1619
-       $("#maximizeImg").show();
1620
-    }
1621
-
1622
-    $(window).resize(function() {
1623
-       maxWidth = $(window).width() - 192;
1624
-       maxHeight = $(window).height() - 98;
1625
-       $.jeegoopopup.center();
1626
-       if (maxWidth < 520 || maxHeight < 500) { 
1627
-           $.jeegoopopup.width(maxWidth).height(maxHeight);
1628
-           $.jeegoopopup.center();
1629
-           $("#maximizeImg").hide();
1630
-           $("#minimizeImg").hide();
1631
-       } else { 
1632
-           $.jeegoopopup.width(520).height(500);
1633
-           $.jeegoopopup.center();
1634
-           $("#minimizeImg").hide();
1635
-           $("#maximizeImg").show();
1636
-       }
1637
-    });
1638
-
1639
-    $("#minimizeImg").click(function() { $.jeegoopopup.width(520).height(500); $.jeegoopopup.center(); $("#maximizeImg").show(); $("#minimizeImg").hide(); });
1640
-    $("#maximizeImg").click(function() { $.jeegoopopup.width(maxWidth).height(maxHeight); $.jeegoopopup.center(); $("#minimizeImg").show(); $("#maximizeImg").hide(); });
1641
-
1642
-
1643
-    // Output
1644
-    var selectAudioScr = $("#playbackSrc");
1645
-
1646
-    var playButton = $("#preview_output_play");
1647
-
1648
-    var playRingButton = $("#preview_ringer_play");
1649
-
1650
-    var pauseButton = $("#preview_output_pause");
1651
-
1652
-    // Microphone
1653
-    var selectMicScr = $("#microphoneSrc");
1654
-    $("#Settings_AutoGainControl").prop("checked", AutoGainControl);
1655
-    $("#Settings_EchoCancellation").prop("checked", EchoCancellation);
1656
-    $("#Settings_NoiseSuppression").prop("checked", NoiseSuppression);
1657
-
1658
-    // Webcam
1659
-    var selectVideoScr = $("#previewVideoSrc");
1660
-
1661
-    // Orientation
1662
-    var OrientationSel = $("input[name=Settings_Oriteation]");
1663
-    OrientationSel.each(function(){
1664
-        if(this.value == MirrorVideo) $(this).prop("checked", true);
1665
-    });
1666
-    $("#local-video-preview").css("transform", MirrorVideo);
1667
-
1668
-    // Frame Rate
1669
-    var frameRateSel = $("input[name=Settings_FrameRate]");
1670
-    frameRateSel.each(function(){
1671
-        if(this.value == maxFrameRate) $(this).prop("checked", true);
1672
-    });
1673
-
1674
-    // Quality
1675
-    var QualitySel = $("input[name=Settings_Quality]");
1676
-    QualitySel.each(function(){
1677
-        if(this.value == videoHeight) $(this).prop("checked", true);
1678
-    });
1679
-
1680
-    // Aspect Ratio
1681
-    var AspectRatioSel = $("input[name=Settings_AspectRatio]");
1682
-    AspectRatioSel.each(function(){
1683
-        if(this.value == videoAspectRatio) $(this).prop("checked", true);
1684
-    });
1685
-
1686
-    // Ring Tone
1687
-    var selectRingTone = $("#ringTone");
1688
-
1689
-    // Ring Device
1690
-    var selectRingDevice = $("#ringDevice");
1691
-
1692
-    // Handle Aspect Ratio Change
1693
-    AspectRatioSel.change(function(){
1694
-        console.log("Call to change Aspect Ratio ("+ this.value +")");
1695
-
1696
-        var localVideo = $("#local-video-preview").get(0);
1697
-        localVideo.muted = true;
1698
-        localVideo.playsinline = true;
1699
-        localVideo.autoplay = true;
1700
-
1701
-        var tracks = localVideo.srcObject.getTracks();
1702
-        tracks.forEach(function(track) {
1703
-            track.stop();
1704
-        });
1705
-
1706
-        var constraints = {
1707
-            audio: false,
1708
-            video: {
1709
-                deviceId: (selectVideoScr.val() != "default")? { exact: selectVideoScr.val() } : "default"
1710
-            }
1711
-        }
1712
-        if($("input[name=Settings_FrameRate]:checked").val() != ""){
1713
-            constraints.video.frameRate = $("input[name=Settings_FrameRate]:checked").val();
1714
-        }
1715
-        if($("input[name=Settings_Quality]:checked").val() != ""){
1716
-            constraints.video.height = $("input[name=Settings_Quality]:checked").val();
1717
-        }
1718
-        if(this.value != ""){
1719
-            constraints.video.aspectRatio = this.value;
1720
-        }        
1721
-        console.log("Constraints:", constraints);
1722
-        var localStream = new MediaStream();
1723
-        if(navigator.mediaDevices){
1724
-            navigator.mediaDevices.getUserMedia(constraints).then(function(newStream){
1725
-                var videoTrack = newStream.getVideoTracks()[0];
1726
-                localStream.addTrack(videoTrack);
1727
-                localVideo.srcObject = localStream;
1728
-                localVideo.onloadedmetadata = function(e) {
1729
-                    localVideo.play();
1730
-                }
1731
-            }).catch(function(e){
1732
-                console.error(e);
1733
-                AlertConfigExtWindow(lang.alert_error_user_media, lang.error);
1734
-            });
1735
-        }
1736
-    });
1737
-
1738
-    // Handle Video Height Change
1739
-    QualitySel.change(function(){    
1740
-        console.log("Call to change Video Height ("+ this.value +")");
1741
-
1742
-        var localVideo = $("#local-video-preview").get(0);
1743
-        localVideo.muted = true;
1744
-        localVideo.playsinline = true;
1745
-        localVideo.autoplay = true;
1746
-
1747
-        var tracks = localVideo.srcObject.getTracks();
1748
-        tracks.forEach(function(track) {
1749
-            track.stop();
1750
-        });
1751
-
1752
-        var constraints = {
1753
-            audio: false,
1754
-            video: {
1755
-                deviceId: (selectVideoScr.val() != "default")? { exact: selectVideoScr.val() } : "default" ,
1756
-            }
1757
-        }
1758
-        if($("input[name=Settings_FrameRate]:checked").val() != ""){
1759
-            constraints.video.frameRate = $("input[name=Settings_FrameRate]:checked").val();
1760
-        }
1761
-        if(this.value){
1762
-            constraints.video.height = this.value;
1763
-        }
1764
-        if($("input[name=Settings_AspectRatio]:checked").val() != ""){
1765
-            constraints.video.aspectRatio = $("input[name=Settings_AspectRatio]:checked").val();
1766
-        } 
1767
-        console.log("Constraints:", constraints);
1768
-        var localStream = new MediaStream();
1769
-        if(navigator.mediaDevices){
1770
-            navigator.mediaDevices.getUserMedia(constraints).then(function(newStream){
1771
-                var videoTrack = newStream.getVideoTracks()[0];
1772
-                localStream.addTrack(videoTrack);
1773
-                localVideo.srcObject = localStream;
1774
-                localVideo.onloadedmetadata = function(e) {
1775
-                    localVideo.play();
1776
-                }
1777
-            }).catch(function(e){
1778
-                console.error(e);
1779
-                AlertConfigExtWindow(lang.alert_error_user_media, lang.error);
1780
-            });
1781
-        }
1782
-    });    
1783
-
1784
-    // Handle Frame Rate Change 
1785
-    frameRateSel.change(function(){
1786
-        console.log("Call to change Frame Rate ("+ this.value +")");
1787
-
1788
-        var localVideo = $("#local-video-preview").get(0);
1789
-        localVideo.muted = true;
1790
-        localVideo.playsinline = true;
1791
-        localVideo.autoplay = true;
1792
-
1793
-        var tracks = localVideo.srcObject.getTracks();
1794
-        tracks.forEach(function(track) {
1795
-            track.stop();
1796
-        });
1797
-
1798
-        var constraints = {
1799
-            audio: false,
1800
-            video: {
1801
-                deviceId: (selectVideoScr.val() != "default")? { exact: selectVideoScr.val() } : "default" ,
1802
-            }
1803
-        }
1804
-        if(this.value != ""){
1805
-            constraints.video.frameRate = this.value;
1806
-        }
1807
-        if($("input[name=Settings_Quality]:checked").val() != ""){
1808
-            constraints.video.height = $("input[name=Settings_Quality]:checked").val();
1809
-        }
1810
-        if($("input[name=Settings_AspectRatio]:checked").val() != ""){
1811
-            constraints.video.aspectRatio = $("input[name=Settings_AspectRatio]:checked").val();
1812
-        } 
1813
-        console.log("Constraints:", constraints);
1814
-        var localStream = new MediaStream();
1815
-        if(navigator.mediaDevices){
1816
-            navigator.mediaDevices.getUserMedia(constraints).then(function(newStream){
1817
-                var videoTrack = newStream.getVideoTracks()[0];
1818
-                localStream.addTrack(videoTrack);
1819
-                localVideo.srcObject = localStream;
1820
-                localVideo.onloadedmetadata = function(e) {
1821
-                    localVideo.play();
1822
-                }
1823
-            }).catch(function(e){
1824
-                console.error(e);
1825
-                AlertConfigExtWindow(lang.alert_error_user_media, lang.error);
1826
-            });
1827
-        }
1828
-    });
1829
-
1830
-    // Handle Audio Source changes (Microphone)
1831
-    selectMicScr.change(function(){
1832
-        console.log("Call to change Microphone ("+ this.value +")");
1833
-
1834
-        // Change and update visual preview
1835
-        try{
1836
-            var tracks = window.SettingsMicrophoneStream.getTracks();
1837
-            tracks.forEach(function(track) {
1838
-                track.stop();
1839
-            });
1840
-            window.SettingsMicrophoneStream = null;
1841
-        }
1842
-        catch(e){}
1843
-
1844
-        try{
1845
-            soundMeter = window.SettingsMicrophoneSoundMeter;
1846
-            soundMeter.stop();
1847
-            window.SettingsMicrophoneSoundMeter = null;
1848
-        }
1849
-        catch(e){}
1850
-
1851
-        // Get Microphone
1852
-        var constraints = { 
1853
-            audio: {
1854
-                deviceId: { exact: this.value }
1855
-            }, 
1856
-            video: false 
1857
-        }
1858
-        var localMicrophoneStream = new MediaStream();
1859
-        navigator.mediaDevices.getUserMedia(constraints).then(function(mediaStream){
1860
-            var audioTrack = mediaStream.getAudioTracks()[0];
1861
-            if(audioTrack != null){
1862
-                // Display Microphone Levels
1863
-                localMicrophoneStream.addTrack(audioTrack);
1864
-                window.SettingsMicrophoneStream = localMicrophoneStream;
1865
-                window.SettingsMicrophoneSoundMeter = MeterSettingsOutput(localMicrophoneStream, "Settings_MicrophoneOutput", "width", 50);
1866
-            }
1867
-        }).catch(function(e){
1868
-            console.log("Failed to getUserMedia", e);
1869
-        });
1870
-    });
1871
-
1872
-    // Handle output change (speaker)
1873
-    selectAudioScr.change(function(){
1874
-        console.log("Call to change Speaker ("+ this.value +")");
1875
-
1876
-        var audioObj = window.SettingsOutputAudio;
1877
-        if(audioObj != null) {
1878
-            if (typeof audioObj.sinkId !== 'undefined') {
1879
-                audioObj.setSinkId(this.value).then(function() {
1880
-                    console.log("sinkId applied to audioObj:", this.value);
1881
-                }).catch(function(e){
1882
-                    console.warn("Failed not apply setSinkId.", e);
1883
-                });
1884
-            }
1885
-        }
1886
-    });
1887
-
1888
-    // Play button press
1889
-    playButton.click(function(){
1890
-
1891
-        try{
1892
-            window.SettingsOutputAudio.pause();
1893
-        } 
1894
-        catch(e){}
1895
-        window.SettingsOutputAudio = null;
1896
-
1897
-        try{
1898
-            var tracks = window.SettingsOutputStream.getTracks();
1899
-            tracks.forEach(function(track) {
1900
-                track.stop();
1901
-            });
1902
-        }
1903
-        catch(e){}
1904
-        window.SettingsOutputStream = null;
1905
-
1906
-        try{
1907
-            var soundMeter = window.SettingsOutputStreamMeter;
1908
-            soundMeter.stop();
1909
-        }
1910
-        catch(e){}
1911
-        window.SettingsOutputStreamMeter = null;
1912
-
1913
-        // Load Sample
1914
-        console.log("Audio:", audioBlobs.speaker_test.url);
1915
-        var audioObj = new Audio(audioBlobs.speaker_test.blob);
1916
-        audioObj.preload = "auto";
1917
-        audioObj.onplay = function(){
1918
-            var outputStream = new MediaStream();
1919
-            if (typeof audioObj.captureStream !== 'undefined') {
1920
-                outputStream = audioObj.captureStream();
1921
-            } 
1922
-            else if (typeof audioObj.mozCaptureStream !== 'undefined') {
1923
-                return;
1924
-            }
1925
-            else if (typeof audioObj.webkitCaptureStream !== 'undefined') {
1926
-                outputStream = audioObj.webkitCaptureStream();
1927
-            }
1928
-            else {
1929
-                console.warn("Cannot display Audio Levels")
1930
-                return;
1931
-            }
1932
-
1933
-            // Display Speaker Levels
1934
-            window.SettingsOutputStream = outputStream;
1935
-            window.SettingsOutputStreamMeter = MeterSettingsOutput(outputStream, "Settings_SpeakerOutput", "width", 50);
1936
-        }
1937
-        audioObj.oncanplaythrough = function(e) {
1938
-            if (typeof audioObj.sinkId !== 'undefined') {
1939
-                audioObj.setSinkId(selectAudioScr.val()).then(function() {
1940
-                    console.log("Set sinkId to:", selectAudioScr.val());
1941
-                }).catch(function(e){
1942
-                    console.warn("Failed not apply setSinkId.", e);
1943
-                });
1944
-            }
1945
-            // Play
1946
-            audioObj.play().then(function(){
1947
-                // Audio Is Playing
1948
-            }).catch(function(e){
1949
-                console.warn("Unable to play audio file", e);
1950
-            });
1951
-            console.log("Playing sample audio file... ");
1952
-        }
1953
-
1954
-        window.SettingsOutputAudio = audioObj;
1955
-    });
1956
-
1957
-    // Pause button press
1958
-    pauseButton.click(function() {
1959
-       if (window.SettingsOutputAudio.paused) {
1960
-           window.SettingsOutputAudio.play();
1961
-       } else { 
1962
-           window.SettingsOutputAudio.pause();
1963
-         }
1964
-    });
1965
-
1966
-
1967
-    playRingButton.click(function(){
1968
-
1969
-        try{
1970
-            window.SettingsRingerAudio.pause();
1971
-        } 
1972
-        catch(e){}
1973
-        window.SettingsRingerAudio = null;
1974
-
1975
-        try{
1976
-            var tracks = window.SettingsRingerStream.getTracks();
1977
-            tracks.forEach(function(track) {
1978
-                track.stop();
1979
-            });
1980
-        }
1981
-        catch(e){}
1982
-        window.SettingsRingerStream = null;
1983
-
1984
-        try{
1985
-            var soundMeter = window.SettingsRingerStreamMeter;
1986
-            soundMeter.stop();
1987
-        }
1988
-        catch(e){}
1989
-        window.SettingsRingerStreamMeter = null;
1990
-
1991
-        // Load Sample
1992
-        console.log("Audio:", audioBlobs.Ringtone.url);
1993
-        var audioObj = new Audio(audioBlobs.Ringtone.blob);
1994
-        audioObj.preload = "auto";
1995
-        audioObj.onplay = function(){
1996
-            var outputStream = new MediaStream();
1997
-            if (typeof audioObj.captureStream !== 'undefined') {
1998
-                outputStream = audioObj.captureStream();
1999
-            } 
2000
-            else if (typeof audioObj.mozCaptureStream !== 'undefined') {
2001
-                return;
2002
-                // BUG: mozCaptureStream() in Firefox does not work the same way as captureStream()
2003
-                // the actual sound does not play out to the speakers... its as if the mozCaptureStream
2004
-                // removes the stream from the <audio> object.
2005
-                outputStream = audioObj.mozCaptureStream();
2006
-            }
2007
-            else if (typeof audioObj.webkitCaptureStream !== 'undefined') {
2008
-                outputStream = audioObj.webkitCaptureStream();
2009
-            }
2010
-            else {
2011
-                console.warn("Cannot display Audio Levels")
2012
-                return;
2013
-            }
2014
-            // Monitor Output
2015
-            window.SettingsRingerStream = outputStream;
2016
-            window.SettingsRingerStreamMeter = MeterSettingsOutput(outputStream, "Settings_RingerOutput", "width", 50);
2017
-        }
2018
-        audioObj.oncanplaythrough = function(e) {
2019
-            if (typeof audioObj.sinkId !== 'undefined') {
2020
-                audioObj.setSinkId(selectRingDevice.val()).then(function() {
2021
-                    console.log("Set sinkId to:", selectRingDevice.val());
2022
-                }).catch(function(e){
2023
-                    console.warn("Failed not apply setSinkId.", e);
2024
-                });
2025
-            }
2026
-            // Play
2027
-            audioObj.play().then(function(){
2028
-                // Audio Is Playing
2029
-            }).catch(function(e){
2030
-                console.warn("Unable to play audio file", e);
2031
-            });
2032
-            console.log("Playing sample audio file... ");
2033
-        }
2034
-
2035
-        window.SettingsRingerAudio = audioObj;
2036
-    });
2037
-
2038
-    // Change Video Image
2039
-    OrientationSel.change(function(){
2040
-        console.log("Call to change Orientation ("+ this.value +")");
2041
-        $("#local-video-preview").css("transform", this.value);
2042
-    });
2043
-
2044
-    // Handle video input change (WebCam)
2045
-    selectVideoScr.change(function(){
2046
-        console.log("Call to change WebCam ("+ this.value +")");
2047
-
2048
-        var localVideo = $("#local-video-preview").get(0);
2049
-        localVideo.muted = true;
2050
-        localVideo.playsinline = true;
2051
-        localVideo.autoplay = true;
2052
-
2053
-        var tracks = localVideo.srcObject.getTracks();
2054
-        tracks.forEach(function(track) {
2055
-            track.stop();
2056
-        });
2057
-
2058
-        var constraints = {
2059
-            audio: false,
2060
-            video: {
2061
-                deviceId: (this.value != "default")? { exact: this.value } : "default"
2062
-            }
2063
-        }
2064
-        if($("input[name=Settings_FrameRate]:checked").val() != ""){
2065
-            constraints.video.frameRate = $("input[name=Settings_FrameRate]:checked").val();
2066
-        }
2067
-        if($("input[name=Settings_Quality]:checked").val() != ""){
2068
-            constraints.video.height = $("input[name=Settings_Quality]:checked").val();
2069
-        }
2070
-        if($("input[name=Settings_AspectRatio]:checked").val() != ""){
2071
-            constraints.video.aspectRatio = $("input[name=Settings_AspectRatio]:checked").val();
2072
-        } 
2073
-        console.log("Constraints:", constraints);
2074
-        var localStream = new MediaStream();
2075
-        if(navigator.mediaDevices){
2076
-            navigator.mediaDevices.getUserMedia(constraints).then(function(newStream){
2077
-                var videoTrack = newStream.getVideoTracks()[0];
2078
-                localStream.addTrack(videoTrack);
2079
-                localVideo.srcObject = localStream;
2080
-                localVideo.onloadedmetadata = function(e) {
2081
-                    localVideo.play();
2082
-                }
2083
-            }).catch(function(e){
2084
-                console.error(e);
2085
-                AlertConfigExtWindow(lang.alert_error_user_media, lang.error);
2086
-            });
2087
-        }
2088
-    });
2089
-
2090
-    $("#AudioAndVideoRow").click(function() {
2091
-
2092
-       $(".settingsSubSection").each(function() { $(this).css("display", "none"); });
2093
-       $("#AudioVideoHtml").css("display", "block");
2094
-       $(".SettingsSection").each(function() { $(this).removeClass("selectedSettingsSection"); });
2095
-       $("#AudioAndVideoRow td").addClass("selectedSettingsSection");
2096
-
2097
-       if (videoAudioCheck == 0) {
2098
-
2099
-            videoAudioCheck = 1;
2100
-
2101
-	    // Note: Only works over HTTPS or via localhost!!
2102
-	    var localVideo = $("#local-video-preview").get(0);
2103
-	    localVideo.muted = true;
2104
-	    localVideo.playsinline = true;
2105
-	    localVideo.autoplay = true;
2106
-
2107
-	    var localVideoStream = new MediaStream();
2108
-	    var localMicrophoneStream = new MediaStream();
2109
-	    
2110
-	    if(navigator.mediaDevices){
2111
-		navigator.mediaDevices.enumerateDevices().then(function(deviceInfos){
2112
-		    var savedVideoDevice = getVideoSrcID();
2113
-		    var videoDeviceFound = false;
2114
-
2115
-		    var savedAudioDevice = getAudioSrcID();
2116
-		    var audioDeviceFound = false;
2117
-
2118
-		    var MicrophoneFound = false;
2119
-		    var SpeakerFound = false;
2120
-		    var VideoFound = false;
2121
-
2122
-		    for (var i = 0; i < deviceInfos.length; ++i) {
2123
-		        console.log("Found Device ("+ deviceInfos[i].kind +"): ", deviceInfos[i].label);
2124
-
2125
-		        // Check Devices
2126
-		        if (deviceInfos[i].kind === "audioinput") {
2127
-		            MicrophoneFound = true;
2128
-		            if(savedAudioDevice != "default" && deviceInfos[i].deviceId == savedAudioDevice) {
2129
-		                audioDeviceFound = true;
2130
-		            }                   
2131
-		        }
2132
-		        else if (deviceInfos[i].kind === "audiooutput") {
2133
-		            SpeakerFound = true;
2134
-		        }
2135
-		        else if (deviceInfos[i].kind === "videoinput") {
2136
-		            VideoFound = true;
2137
-		            if(savedVideoDevice != "default" && deviceInfos[i].deviceId == savedVideoDevice) {
2138
-		                videoDeviceFound = true;
2139
-		            }
2140
-		        }
2141
-		    }
2142
-
2143
-		    var contraints = {
2144
-		        audio: MicrophoneFound,
2145
-		        video: VideoFound
2146
-		    }
2147
-
2148
-		    if(MicrophoneFound){
2149
-		        contraints.audio = { deviceId: "default" }
2150
-		        if(audioDeviceFound) contraints.audio.deviceId = { exact: savedAudioDevice }
2151
-		    }
2152
-		    if(VideoFound){
2153
-		        contraints.video = { deviceId: "default" }
2154
-		        if(videoDeviceFound) contraints.video.deviceId = { exact: savedVideoDevice }
2155
-		    }
2156
-		    // Additional
2157
-		    if($("input[name=Settings_FrameRate]:checked").val() != ""){
2158
-		        contraints.video.frameRate = $("input[name=Settings_FrameRate]:checked").val();
2159
-		    }
2160
-		    if($("input[name=Settings_Quality]:checked").val() != ""){
2161
-		        contraints.video.height = $("input[name=Settings_Quality]:checked").val();
2162
-		    }
2163
-		    if($("input[name=Settings_AspectRatio]:checked").val() != ""){
2164
-		        contraints.video.aspectRatio = $("input[name=Settings_AspectRatio]:checked").val();
2165
-		    } 
2166
-		    console.log("Get User Media", contraints);
2167
-		    // Get User Media
2168
-		    navigator.mediaDevices.getUserMedia(contraints).then(function(mediaStream){
2169
-		        // Handle Video
2170
-		        var videoTrack = (mediaStream.getVideoTracks().length >= 1)? mediaStream.getVideoTracks()[0] : null;
2171
-		        if(VideoFound && videoTrack != null){
2172
-		            localVideoStream.addTrack(videoTrack);
2173
-		            // Display Preview Video
2174
-		            localVideo.srcObject = localVideoStream;
2175
-		            localVideo.onloadedmetadata = function(e) {
2176
-		                localVideo.play();
2177
-		            }
2178
-		        }
2179
-		        else {
2180
-		            console.warn("No video / webcam devices found. Video Calling will not be possible.")
2181
-		        }
2182
-
2183
-		        // Handle Audio
2184
-		        var audioTrack = (mediaStream.getAudioTracks().length >= 1)? mediaStream.getAudioTracks()[0] : null ;
2185
-		        if(MicrophoneFound && audioTrack != null){
2186
-		            localMicrophoneStream.addTrack(audioTrack);
2187
-		            // Display Micrphone Levels
2188
-		            window.SettingsMicrophoneStream = localMicrophoneStream;
2189
-		            window.SettingsMicrophoneSoundMeter = MeterSettingsOutput(localMicrophoneStream, "Settings_MicrophoneOutput", "width", 50);
2190
-		        }
2191
-		        else {
2192
-		            console.warn("No microphone devices found. Calling will not be possible.")
2193
-		        }
2194
-
2195
-		        // Display Output Levels
2196
-		        $("#Settings_SpeakerOutput").css("width", "0%");
2197
-		        if(!SpeakerFound){
2198
-		            console.log("No speaker devices found, make sure one is plugged in.")
2199
-		            $("#playbackSrc").hide();
2200
-		            $("#RingDeviceSection").hide();
2201
-		        }
2202
-
2203
-		       // Return .then()
2204
-		       return navigator.mediaDevices.enumerateDevices();
2205
-		    }).then(function(deviceInfos){
2206
-		        for (var i = 0; i < deviceInfos.length; ++i) {
2207
-		            console.log("Found Device ("+ deviceInfos[i].kind +") Again: ", deviceInfos[i].label, deviceInfos[i].deviceId);
2208
-
2209
-		            var deviceInfo = deviceInfos[i];
2210
-		            var devideId = deviceInfo.deviceId;
2211
-		            var DisplayName = deviceInfo.label;
2212
-		            if(DisplayName.indexOf("(") > 0) DisplayName = DisplayName.substring(0,DisplayName.indexOf("("));
2213
-
2214
-		            var option = $('<option/>');
2215
-		            option.prop("value", devideId);
2216
-
2217
-		            if (deviceInfo.kind === "audioinput") {
2218
-		                option.text((DisplayName != "")? DisplayName : "Microphone");
2219
-		                if(getAudioSrcID() == devideId) option.prop("selected", true);
2220
-		                selectMicScr.append(option);
2221
-		            }
2222
-		            else if (deviceInfo.kind === "audiooutput") {
2223
-		                option.text((DisplayName != "")? DisplayName : "Speaker");
2224
-		                if(getAudioOutputID() == devideId) option.prop("selected", true);
2225
-		                selectAudioScr.append(option);
2226
-		                selectRingDevice.append(option.clone());
2227
-		            }
2228
-		            else if (deviceInfo.kind === "videoinput") {
2229
-		                if(getVideoSrcID() == devideId) option.prop("selected", true);
2230
-		                option.text((DisplayName != "")? DisplayName : "Webcam");
2231
-		                selectVideoScr.append(option);
2232
-		            }
2233
-		        }
2234
-		        // Add "Default" option
2235
-		        if(selectVideoScr.children('option').length > 0){
2236
-		            var option = $('<option/>');
2237
-		            option.prop("value", "default");
2238
-		            if(getVideoSrcID() == "default" || getVideoSrcID() == "" || getVideoSrcID() == "null") option.prop("selected", true);
2239
-		            option.text("(Default)");
2240
-		            selectVideoScr.append(option);
2241
-		        }
2242
-		    }).catch(function(e){
2243
-		        console.error(e);
2244
-		        AlertConfigExtWindow(lang.alert_error_user_media, lang.error);
2245
-		    });
2246
-		}).catch(function(e){
2247
-		    console.error("Error getting Media Devices", e);
2248
-		});
2249
-
2250
-	    } else {
2251
-		AlertConfigExtWindow(lang.alert_error_user_media, lang.error);
2252
-	    }
2253
-        }
2254
-    });
2255
-
2256
-    var NotificationsCheck = $("#Settings_Notifications");
2257
-    NotificationsCheck.prop("checked", NotificationsActive);
2258
-    NotificationsCheck.change(function(){
2259
-        if(this.checked){
2260
-            if(Notification.permission != "granted"){
2261
-                if(checkNotificationPromise()){
2262
-                    Notification.requestPermission().then(function(p){
2263
-                        console.log(p);
2264
-                        HandleNotifyPermission(p);
2265
-                    });
2266
-                }
2267
-                else {
2268
-                    Notification.requestPermission(function(p){
2269
-                        console.log(p);
2270
-                        HandleNotifyPermission(p)
2271
-                    });
2272
-                }
2273
-            }
2274
-        }
2275
-    });
2276
-
2277
-
2278
-    // Save configration data for external video conference users
2279
-    $("#vidConfExternalTable").on("click", ".saveExtConfExtension", function() {
2280
-
2281
-      if ($(this).val() == "Save") {
2282
-
2283
-        var extUserExtension = $(this).closest('tr').find('input.extConfExtension').val();
2284
-        var extUserExtensionPass = $(this).closest('tr').find('input.extConfExtensionPass').val();
2285
-
2286
-        var WSSServer = localDB.getItem("wssServer");
2287
-
2288
-        if (extUserExtension != '' && extUserExtensionPass != '') {
2289
-          if (extUserExtension.length < 200 && extUserExtensionPass.length < 400) {
2290
-            // Check if the extension that has been entered is valid
2291
-            if (/^[a-zA-Z0-9]+$/.test(extUserExtension)) {
2292
-
2293
-              $.ajax({
2294
-                 type: "POST",
2295
-                 url: "save-update-external-user-conf.php",
2296
-                 dataType: "JSON",
2297
-                 data: {
2298
-                        username: userName,
2299
-                        exten_for_external: extUserExtension,
2300
-                        exten_for_ext_pass: extUserExtensionPass,
2301
-                        wss_server: WSSServer,
2302
-                        s_ajax_call: validateSToken
2303
-                     },
2304
-                 success: function(response) {
2305
-
2306
-                                 if (response.result == 'The data has been successfully saved to the database !') {
2307
-
2308
-                                     getExternalUserConfFromSqldb();
2309
-                                     alert("The data has been successfully saved to the database ! To see the result, please reopen this window !");
2310
-
2311
-                                     $("#jg_popup_b").empty(); $("#jg_popup_l").empty(); $("#windowCtrls").empty(); closeVideoAudio(); $.jeegoopopup.close();
2312
-
2313
-                                 } else { alert(response.result); }
2314
-
2315
-                 },
2316
-                 error: function(response) {
2317
-                                 alert("An error occurred while trying to save the data to the database !");
2318
-                 }
2319
-              });
2320
-
2321
-              $(this).closest('[class="btnTableRow"]').find('[class="extConfExtension"]').attr("disabled", true);
2322
-              $(this).closest('[class="btnTableRow"]').find('[class="extConfExtensionPass"]').attr("disabled", true);
2323
-              $(this).attr("value", "Edit");
2324
-              $(this).prop("title", "Edit this row.");
2325
-
2326
-            } else { alert("The extension should contain only numbers and letters."); }
2327
-          } else { alert("The extension and/or the SIP password don't have a reasonable length."); }
2328
-        } else { alert("Please fill in both the \"Extension\" and the \"SIP Password\" fields !"); }
2329
-      } else {
2330
-          $(this).closest('[class="btnTableRow"]').find('[class="extConfExtension"]').attr("disabled", false);
2331
-          $(this).closest('[class="btnTableRow"]').find('[class="extConfExtensionPass"]').attr("disabled", false);
2332
-          $(this).attr("value", "Save");
2333
-          $(this).prop("title", "Save this row.");
2334
-      }
2335
-    });
2336
-
2337
-    // Delete extension data from the database
2338
-    $("#vidConfExternalTable").on("click", ".deleteExtRow", function() {
2339
-
2340
-      var targetExtension = $(this).closest('[class="btnTableRow"]').find('[class="extConfExtension"]').val();
2341
-
2342
-      if (targetExtension != '') {
2343
-
2344
-         if (confirm("Do you really want to delete this row from this window and from the database ?")) {
2345
-
2346
-             $.ajax({
2347
-                 type: "POST",
2348
-                 url: "remove-external-user-ext-data.php",
2349
-                 dataType: "JSON",
2350
-                 data: {
2351
-                        username: userName,
2352
-                        exten_for_external: targetExtension,
2353
-                        s_ajax_call: validateSToken
2354
-                       },
2355
-                 success: function(response) {
2356
-                                   $(this).closest('tr').find('input.extConfExtension').empty();
2357
-                                   $(this).closest('tr').find('input.extConfExtensionPass').empty();
2358
-                                   $(this).closest('tr').find('input.extConfExtensionLink').empty();
2359
-                                   getExternalUserConfFromSqldb();
2360
-                                   alert("The data has been permanently removed !");
2361
-                 },
2362
-                 error: function(response) {
2363
-                             alert("An error occurred while trying to remove the data !");
2364
-                 }
2365
-             });
2366
-
2367
-             $(this).closest('[class="btnTableRow"]').hide();
2368
-         }
2369
-      }
2370
-    });
2371
-
2372
-    $(".copyToClipboard").mouseenter(function() {
2373
-        if ($(this).closest('[class="btnTableRow"]').find('[class="extConfExtensionLink"]').val() != '') {
2374
-            $(this).css("color", "#424242");
2375
-            $(this).css("cursor", "pointer");
2376
-        }
2377
-    });
2378
-
2379
-    $(".copyToClipboard").mouseleave(function() {
2380
-        $(this).css("color", "#cccccc");
2381
-    });
2382
-
2383
-    $(".copyToClipboard").click(function() {
2384
-        if ($(this).closest('[class="btnTableRow"]').find('[class="extConfExtensionLink"]').val() != '') {
2385
-	      var $tempEl = $("<input>");
2386
-	      $("body").append($tempEl);
2387
-	      $tempEl.val($(this).closest('[class="btnTableRow"]').find('[class="extConfExtensionLink"]').val()).select();
2388
-	      document.execCommand("Copy");
2389
-	      $tempEl.remove();
2390
-	      alert("The link has been copied to your clipboard!");
2391
-        }
2392
-    });
2393
-
2394
-    var externUserData = getDbItem("externalUserConfElem", "");
2395
-    if (externUserData !== 'undefined' && externUserData != 'null' && externUserData != 0) {
2396
-        $("#emptyExtRow").hide();
2397
-    }
2398
-
2399
-    $("#add_New_External_User").click(function() {
2400
-       $("#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>");
2401
-    });
2402
-
2403
-
2404
-    // Profile Picture
2405
-    cropper = $("#ImageCanvas").croppie({
2406
-        viewport: { width: 150, height: 150, type: 'circle' }
2407
-    });
2408
-
2409
-    // Preview Existing Image
2410
-    $("#ImageCanvas").croppie('bind', { url: getPicture("profilePicture") }).then(function() {
2411
-       $('.cr-slider').attr({ min: 0.5, max: 3 });
2412
-    });
2413
-
2414
-    // Wireup File Change
2415
-    $("#fileUploader").change(function () {
2416
-        var filesArray = $(this).prop('files');
2417
-    
2418
-        if (filesArray.length == 1) {
2419
-            var uploadId = Math.floor(Math.random() * 1000000000);
2420
-            var fileObj = filesArray[0];
2421
-            var fileName = fileObj.name;
2422
-            var fileSize = fileObj.size;
2423
-    
2424
-            if (fileSize <= 52428800) {
2425
-                console.log("Adding (" + uploadId + "): " + fileName + " of size: " + fileSize + "bytes");
2426
-    
2427
-                var reader = new FileReader();
2428
-                reader.Name = fileName;
2429
-                reader.UploadId = uploadId;
2430
-                reader.Size = fileSize;
2431
-                reader.onload = function (event) {
2432
-                    $("#ImageCanvas").croppie('bind', {
2433
-                        url: event.target.result
2434
-                    });
2435
-                }
2436
-
2437
-                // Use onload for this
2438
-                reader.readAsDataURL(fileObj);
2439
-            }
2440
-            else {
2441
-                Alert(lang.alert_file_size, lang.error);
2442
-            }
2443
-        }
2444
-        else {
2445
-            Alert(lang.alert_single_file, lang.error);
2446
-        }
2447
-    });
2448
-
2449
-
2450
-    $("#save_button_conf").click(function() {
2451
-
2452
-        if(localDB.getItem("profileUserID") == null) localDB.setItem("profileUserID", uID()); // For first time only
2453
-
2454
-        var confAccWssServer = $("#Configure_Account_wssServer").val();
2455
-        if (/^[A-Za-z0-9\.\-]+\.[A-Za-z0-9\-]{2,63}$/.test(confAccWssServer)) { var finconfAccWssServer = confAccWssServer; } else { 
2456
-            var finconfAccWssServer = ''; alert('The WebSocket domain that you entered is not a valid domain name!'); }
2457
-
2458
-        var confAccWSPort = $("#Configure_Account_WebSocketPort").val();
2459
-        if (/^[0-9]+$/.test(confAccWSPort)) { var finConfAccWSPort = confAccWSPort; } else { 
2460
-            var finConfAccWSPort = ''; alert('The web socket port that you entered is not a valid port!'); }
2461
-
2462
-        var confAccServerPath = $("#Configure_Account_ServerPath").val();
2463
-        if (/^[A-Za-z0-9\/]+$/.test(confAccServerPath)) { var finConfAccServerPath = confAccServerPath; } else { 
2464
-            var finConfAccServerPath = ''; alert('The server path that you entered is not a valid server path!');}
2465
-
2466
-        var confAccProfileName = $("#Configure_Account_profileName").val();
2467
-        if (/^[A-Za-z0-9\s\-\'\[\]\(\)]+$/.test(confAccProfileName)) { var finConfAccProfileName = confAccProfileName; } else { 
2468
-            var finConfAccProfileName = ''; alert('The profile name that you entered is not a valid profile name!'); }
2469
-
2470
-        var confAccSipUsername = $("#Configure_Account_SipUsername").val();
2471
-        if (/^[A-Za-z0-9\-\.\_\@\*\!\?\&\~\(\)\[\]]+$/.test(confAccSipUsername)) { var finConfAccSipUsername = confAccSipUsername; } else { 
2472
-            var finConfAccSipUsername = ''; alert('The SIP username that you entered is not a valid SIP username!'); }
2473
-
2474
-        var confAccSipPassword = $("#Configure_Account_SipPassword").val();
2475
-        if (confAccSipPassword.length < 400) { var finConfAccSipPassword = confAccSipPassword; } else { 
2476
-            var finConfAccSipPassword = ''; alert('The SIP password that you entered is too long!'); }
2477
-
2478
-        var confAccStun = $("#Configure_Account_StunServer").val();
2479
-        if (confAccStun != null && confAccStun.trim() !== '') {
2480
-            if (/^(\d+\.\d+\.\d+\.\d+:\d+)$|^([A-Za-z0-9\.\-]+\.[A-Za-z0-9\-]{2,63}:\d+)/.test(confAccStun)) { var finConfAccStun = confAccStun; } else { 
2481
-                var finConfAccStun = ''; alert('The domain or IP or port number of the STUN server is not valid!'); }
2482
-        } else { var finConfAccStun = ''; }
2483
-
2484
-        if (finconfAccWssServer != null && finconfAccWssServer.trim() !== '' &&
2485
-            finConfAccWSPort != null && finConfAccWSPort.trim() !== '' &&
2486
-            finConfAccServerPath != null && finConfAccServerPath.trim() !== '' &&
2487
-            finConfAccProfileName != null && finConfAccProfileName.trim() !== '' &&
2488
-            finConfAccSipUsername != null && finConfAccSipUsername.trim() !== '' &&
2489
-            finConfAccSipPassword != null && finConfAccSipPassword.trim() !== '') {
2490
-
2491
-            // OK
2492
-
2493
-        } else { alert('All fields marked with an asterisk are required!'); return; }
2494
-
2495
-
2496
-        // Audio & Video
2497
-        localDB.setItem("AudioOutputId", $("#playbackSrc").val());
2498
-        localDB.setItem("VideoSrcId", $("#previewVideoSrc").val());
2499
-        localDB.setItem("VideoHeight", $("input[name=Settings_Quality]:checked").val());
2500
-        localDB.setItem("FrameRate", $("input[name=Settings_FrameRate]:checked").val());
2501
-        localDB.setItem("AspectRatio", $("input[name=Settings_AspectRatio]:checked").val());
2502
-        localDB.setItem("VideoOrientation", $("input[name=Settings_Oriteation]:checked").val());
2503
-        localDB.setItem("AudioSrcId", $("#microphoneSrc").val());
2504
-        localDB.setItem("AutoGainControl", ($("#Settings_AutoGainControl").is(':checked'))? "1" : "0");
2505
-        localDB.setItem("EchoCancellation", ($("#Settings_EchoCancellation").is(':checked'))? "1" : "0");
2506
-        localDB.setItem("NoiseSuppression", ($("#Settings_NoiseSuppression").is(':checked'))? "1" : "0");
2507
-        localDB.setItem("RingOutputId", $("#ringDevice").val());
2508
-
2509
-        // Check if the extension that has been entered is valid
2510
-        var videoConfExten = $("#Video_Conf_Extension").val();
2511
-        if (/^[a-zA-Z0-9\*\#]+$/.test(videoConfExten)) { var finVideoConfExten = videoConfExten; } else { 
2512
-            var finVideoConfExten = ''; alert("The extension that you entered in the 'Video Conference Extension' field is not a valid extension!");}
2513
-
2514
-        localDB.setItem("VidConfExtension", finVideoConfExten);
2515
-
2516
-        var videoConfWinWidth = $("#Video_Conf_Window_Width").val();
2517
-        if ((/^[0-9]+$/.test(videoConfWinWidth)) && Math.abs(videoConfWinWidth) <= 100) { var finVideoConfWinWidth = Math.abs(videoConfWinWidth); } else { 
2518
-             var finVideoConfWinWidth = ''; alert("The percent value that you entered in the 'Percent of screen width ...' field is not valid!"); }
2519
-
2520
-        localDB.setItem("VidConfWindowWidth", finVideoConfWinWidth);
2521
-
2522
-        localDB.setItem("Notifications", ($("#Settings_Notifications").is(":checked"))? "1" : "0");
2523
-
2524
-        if ($("#emailIntegration").is(":checked")) {
2525
-
2526
-            if (/^[A-Za-z0-9\.\-]+\.[A-Za-z0-9\-]{2,63}$/.test($("#RoundcubeDomain").val())) {} else {
2527
-                $("#emailIntegration").prop("checked", false);
2528
-                $("#RoundcubeDomain").val("");
2529
-                alert("The Roundcube domain is not valid. After entering a valid Roundcube domain, please remember to check the checkbox 'Enable Roundcube email integration' again !");
2530
-                return;
2531
-            }
2532
-
2533
-            if (/^[A-Za-z0-9\_\.\-\@\~\%\+\!\?\&\*\^\=\#\$\{\}\|\/]{1,300}$/.test($("#RoundcubeUser").val())) {} else {
2534
-                $("#emailIntegration").prop("checked", false);
2535
-                $("#RoundcubeUser").val("");
2536
-                alert("The Roundcube user is not valid. After entering a valid Roundcube user, please remember to check the checkbox 'Enable Roundcube email integration' again !");
2537
-                return;
2538
-            }
2539
-
2540
-            if ($("#RoundcubePass").val() == '' || $("#RoundcubePass").val().length > 300) { 
2541
-                $("#emailIntegration").prop("checked", false); 
2542
-                $("#RoundcubePass").val("");
2543
-                alert("The Roundcube password is not valid. After entering a valid Roundcube password, please remember to check the checkbox 'Enable Roundcube email integration' again !");
2544
-                return;
2545
-            }
2546
-
2547
-            if ($("#rcBasicAuthUser").val().length > 300) { $("#rcBasicAuthUser").val(""); alert("The Roundcube basic authentication user is not valid."); return; }
2548
-
2549
-            if ($("#rcBasicAuthPass").val().length > 300) { $("#rcBasicAuthPass").val(""); alert("The Roundcube basic authentication password is not valid."); return; }
2550
-        }
2551
-
2552
-        // The profile picture can't be saved if the style of its section is 'display: none;'
2553
-        $("#AppearanceHtml").css({ 'display' : 'block', 'visibility' : 'hidden', 'margin-top' : '-228px' });
2554
-
2555
-
2556
-        // Convert the profile picture to base64
2557
-        $("#ImageCanvas").croppie('result', {
2558
-            type: 'base64',
2559
-            size: 'viewport',
2560
-            format: 'png',
2561
-            quality: 1,
2562
-            circle: false
2563
-        }).then(function(base64) {
2564
-            localDB.setItem("profilePicture", base64);
2565
-        });
2566
-
2567
-        setTimeout(function() {
2568
-            saveConfToSqldb();
2569
-        }, 600);
2570
-
2571
-    });
2572
-
2573
-    $("#closeImg").click(function() { $("#jg_popup_b").empty(); $("#jg_popup_l").empty(); $("#windowCtrls").empty(); closeVideoAudio(); $.jeegoopopup.close(); });
2574
-    $("#cancel_button_conf").click(function() { $("#jg_popup_b").empty(); $("#jg_popup_l").empty(); $("#windowCtrls").empty(); closeVideoAudio(); $.jeegoopopup.close(); });
2575
-    $("#jg_popup_overlay").click(function() { $("#jg_popup_b").empty(); $("#jg_popup_l").empty(); $("#windowCtrls").empty(); closeVideoAudio(); $.jeegoopopup.close(); });
2576
-    $(window).on('keydown', function(event) { if (event.key == "Escape") { $("#jg_popup_b").empty(); $("#jg_popup_l").empty(); $("#windowCtrls").empty(); closeVideoAudio(); $.jeegoopopup.close(); } });
2577
-
2578
-}
2579
-
2580
-function checkNotificationPromise() {
2581
-    try {
2582
-        Notification.requestPermission().then();
2583
-    }
2584
-    catch(e) {
2585
-        return false;
2586
-    }
2587
-    return true;
2588
-}
2589
-function HandleNotifyPermission(p){
2590
-
2591
-    if(p == "granted") {
2592
-       // Good
2593
-    } else {
2594
-        Alert(lang.alert_notification_permission, lang.permission, function(){
2595
-            console.log("Attempting to uncheck the checkbox...");
2596
-            $("#Settings_Notifications").prop("checked", false);
2597
-        });
2598
-    }
2599
-}
2600
-function EditBuddyWindow(buddy){
2601
-
2602
-    $.jeegoopopup.close();
2603
-
2604
-    var buddyObj = null;
2605
-    var itemId = -1;
2606
-    var json = JSON.parse(localDB.getItem(profileUserID + "-Buddies"));
2607
-    $.each(json.DataCollection, function (i, item) {
2608
-        if(item.uID == buddy || item.cID == buddy || item.gID == buddy){
2609
-            buddyObj = item;
2610
-            itemId = i;
2611
-            return false;
2612
-        }
2613
-    });
2614
-
2615
-    if(buddyObj == null){
2616
-        Alert(lang.alert_not_found, lang.error);
2617
-        return;
2618
-    }
2619
-
2620
-    var html = "<div id='EditContact'>";
2621
-
2622
-    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>";
2623
-
2624
-    html += "<div class='UiWindowField scroller'>";
2625
-
2626
-    html += "<div id=ImageCanvas style=\"width:150px; height:150px\"></div>";
2627
-    html += "<label for=ebFileUploader class=customBrowseButton style=\"margin-left: 200px; margin-top: -9px;\">Select File</label>";
2628
-    html += "<div><input type=file id=ebFileUploader /></div>";
2629
-    html += "<div style=\"margin-top: 50px\"></div>";
2630
-
2631
-    html += "<div class=UiText>"+ lang.display_name +":</div>";
2632
-
2633
-    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>";
2634
-
2635
-    html += "<div class=UiText>"+ lang.title_description +":</div>";
2636
-
2637
-    if(buddyObj.Type == "extension"){
2638
-        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>";
2639
-    }
2640
-    else {
2641
-        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>";
2642
-    }
2643
-
2644
-    html += "<div class=UiText>"+ lang.internal_subscribe_extension +":</div>";
2645
-    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>";
2646
-
2647
-    html += "<div class=UiText>"+ lang.mobile_number +":</div>";
2648
-    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>";
2649
-
2650
-    html += "<div class=UiText>"+ lang.contact_number_1 +":</div>";
2651
-    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>";
2652
-
2653
-    html += "<div class=UiText>"+ lang.contact_number_2 +":</div>";
2654
-    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>";
2655
-
2656
-    html += "<div class=UiText>"+ lang.email +":</div>";
2657
-    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>";
2658
-
2659
-    html += "</div></div>"
2660
-
2661
-    $.jeegoopopup.open({
2662
-                title: 'Edit Contact',
2663
-                html: html,
2664
-                width: '640',
2665
-                height: '500',
2666
-                center: true,
2667
-                scrolling: 'no',
2668
-                skinClass: 'jg_popup_basic',
2669
-                contentClass: 'editContactPopup',
2670
-                overlay: true,
2671
-                opacity: 50,
2672
-                draggable: true,
2673
-                resizable: false,
2674
-                fadeIn: 0
2675
-    });
2676
-
2677
-    $("#jg_popup_b").append("<div id=bottomButtons><button id=save_button>Save</button><button id=cancel_button>Cancel</button></div>");
2678
-
2679
-
2680
-    var contactDatabaseId = '';
2681
-
2682
-    $.ajax({
2683
-        type: "POST",
2684
-        url: "get-contact-dbid.php",
2685
-        dataType: "JSON",
2686
-        data: {
2687
-            username: userName,
2688
-            contact_name: buddyObj.DisplayName,
2689
-            s_ajax_call: validateSToken
2690
-        },
2691
-        success: function(response) {
2692
-                 if (response.successorfailure == 'success') {
2693
-                     contactDatabaseId = response.cntctDatabaseID;
2694
-                 } else { alert("Error while attempting to retrieve contact data from the database!"); }
2695
-        },
2696
-        error: function(response) {
2697
-                 alert("Error while attempting to retrieve contact data from the database!");
2698
-        }
2699
-    });
2700
-
2701
-    // DoOnLoad
2702
-    var cropper = $("#ImageCanvas").croppie({
2703
-              viewport: { width: 150, height: 150, type: 'circle' }
2704
-    });
2705
-
2706
-    // Preview Existing Image
2707
-    if(buddyObj.Type == "extension"){
2708
-       $("#ImageCanvas").croppie('bind', { url: getPicture(buddyObj.uID, "extension") }).then(function() {
2709
-          $('.cr-slider').attr({ min: 0.5, max: 3 });
2710
-       });
2711
-    } else if(buddyObj.Type == "contact") {
2712
-            $("#ImageCanvas").croppie('bind', { url: getPicture(buddyObj.cID, "contact") }).then(function() {
2713
-               $('.cr-slider').attr({ min: 0.5, max: 3 });
2714
-            });
2715
-    } else if(buddyObj.Type == "group") {
2716
-            $("#ImageCanvas").croppie('bind', { url: getPicture(buddyObj.gID, "group") }).then(function() {
2717
-               $('.cr-slider').attr({ min: 0.5, max: 3 });
2718
-            });
2719
-    }
2720
-
2721
-    // Wireup File Change
2722
-    $("#ebFileUploader").change(function () {
2723
-
2724
-        var filesArray = $(this).prop('files');
2725
-        
2726
-        if (filesArray.length == 1) {
2727
-            var uploadId = Math.floor(Math.random() * 1000000000);
2728
-            var fileObj = filesArray[0];
2729
-            var fileName = fileObj.name;
2730
-            var fileSize = fileObj.size;
2731
-        
2732
-            if (fileSize <= 52428800) {
2733
-                console.log("Adding (" + uploadId + "): " + fileName + " of size: " + fileSize + "bytes");
2734
-      
2735
-                var reader = new FileReader();
2736
-                reader.Name = fileName;
2737
-                reader.UploadId = uploadId;
2738
-                reader.Size = fileSize;
2739
-                reader.onload = function (event) {
2740
-                    $("#ImageCanvas").croppie('bind', {
2741
-                       url: event.target.result
2742
-                    });
2743
-                }
2744
-                reader.readAsDataURL(fileObj);
2745
-            } else {
2746
-                Alert(lang.alert_file_size, lang.error);
2747
-            }
2748
-        } else {
2749
-                Alert(lang.alert_single_file, lang.error);
2750
-        }
2751
-    });
2752
-
2753
-    $("#save_button").click(function() {
2754
-
2755
-      var currentCtctName = $("#AddSomeone_Name").val();
2756
-
2757
-      if (currentCtctName != null && currentCtctName.trim() !== '') {
2758
-
2759
-        if (/^[A-Za-z0-9\s\-\'\[\]\(\)]+$/.test(currentCtctName)) {
2760
-
2761
-            buddyObj.LastActivity = utcDateNow();
2762
-            buddyObj.DisplayName = currentCtctName;
2763
-
2764
-	    var currentDesc = $("#AddSomeone_Desc").val();
2765
-	    if (currentDesc != null && currentDesc.trim() !== '') {
2766
-	        if (/^[A-Za-z0-9\s\-\.\'\"\[\]\(\)\{\}\_\!\?\~\@\%\^\&\*\+\>\<\;\:\=]+$/.test(currentDesc)) { var finCurrentDesc = currentDesc; } else { 
2767
-		    var finCurrentDesc = ''; alert('The title/description that you entered is not valid!'); }
2768
-	    } else { var finCurrentDesc = ''; }
2769
-
2770
-            if(buddyObj.Type == "extension") {
2771
-                buddyObj.Position = finCurrentDesc;
2772
-
2773
-            } else {
2774
-                buddyObj.Description = finCurrentDesc;
2775
-            }
2776
-
2777
-	    var currentExtension = $("#AddSomeone_Exten").val();
2778
-	    if (currentExtension != null && currentExtension.trim() !== '') {
2779
-	        if (/^[a-zA-Z0-9\*\#]+$/.test(currentExtension)) { var finCurrentExtension = currentExtension; } else { 
2780
-		    var finCurrentExtension = ''; alert("The extension that you entered in the 'Extension (Internal)' field is not a valid extension!"); }
2781
-	    } else { var finCurrentExtension = ''; }
2782
-
2783
-            buddyObj.ExtensionNumber = finCurrentExtension;
2784
-
2785
-	    var currentMobile = $("#AddSomeone_Mobile").val();
2786
-	    if (currentMobile != null && currentMobile.trim() !== '') {
2787
-	        if (/^[0-9\s\+\#]+$/.test(currentMobile)) { var finCurrentMobile = currentMobile; } else {
2788
-		    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."); }
2789
-	    } else { var finCurrentMobile = ''; }
2790
-
2791
-            buddyObj.MobileNumber = finCurrentMobile;
2792
-
2793
-	    var currentNum1 = $("#AddSomeone_Num1").val();
2794
-	    if (currentNum1 != null && currentNum1.trim() !== '') {
2795
-	        if (/^[0-9\s\+\#]+$/.test(currentNum1)) { var finCurrentNum1 = currentNum1; } else {
2796
-		    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."); }
2797
-	    } else { var finCurrentNum1 = ''; }
2798
-
2799
-            buddyObj.ContactNumber1 = finCurrentNum1;
2800
-
2801
-	    var currentNum2 = $("#AddSomeone_Num2").val();
2802
-	    if (currentNum2 != null && currentNum2.trim() !== '') {
2803
-	        if (/^[0-9\s\+\#]+$/.test(currentNum2)) { var finCurrentNum2 = currentNum2; } else {
2804
-		    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."); }
2805
-            } else { var finCurrentNum2 = ''; }
2806
-
2807
-            buddyObj.ContactNumber2 = finCurrentNum2;
2808
-
2809
-	    var currentEmail = $("#AddSomeone_Email").val();
2810
-	    if (currentEmail != null && currentEmail.trim() !== '') {
2811
-	        if (/^[A-Za-z0-9\_\.\-\~\%\+\!\?\&\*\^\=\#\$\{\}\|\/]+@[A-Za-z0-9\.\-]+\.[A-Za-z0-9\-]{2,63}$/.test(currentEmail)) { var finCurrentEmail = currentEmail; } else {
2812
-		    var finCurrentEmail = ''; alert("The email that you entered is not a valid email address!"); }
2813
-	    } else { var finCurrentEmail = ''; }
2814
-
2815
-            buddyObj.Email = finCurrentEmail;
2816
-
2817
-
2818
-            // Update Image
2819
-            var constraints = { 
2820
-                type: 'base64', 
2821
-                size: 'viewport', 
2822
-                format: 'png', 
2823
-                quality: 1, 
2824
-                circle: false 
2825
-            }
2826
-
2827
-            $("#ImageCanvas").croppie('result', constraints).then(function(base64) {
2828
-                if(buddyObj.Type == "extension"){
2829
-                    localDB.setItem("img-"+ buddyObj.uID +"-extension", base64);
2830
-                    $("#contact-"+ buddyObj.uID +"-picture-main").css("background-image", 'url('+ getPicture(buddyObj.uID, 'extension') +')');
2831
-                    $("#contact-"+ buddyObj.uID +"-presence-main").html(buddyObj.Position);
2832
-
2833
-                    // Save contact picture to SQL database
2834
-		    var newPic = [];
2835
-                    newPic = [buddyObj.DisplayName, localDB.getItem("img-"+ buddyObj.uID +"-extension", base64)];
2836
-		    saveContactPicToSQLDB(newPic);
2837
-                }
2838
-                else if(buddyObj.Type == "contact") {
2839
-                    localDB.setItem("img-"+ buddyObj.cID +"-contact", base64);
2840
-                    $("#contact-"+ buddyObj.cID +"-picture-main").css("background-image", 'url('+ getPicture(buddyObj.cID, 'contact') +')');
2841
-                    $("#contact-"+ buddyObj.cID +"-presence-main").html(buddyObj.Description);
2842
-
2843
-                    // Save contact picture to SQL database
2844
-		    var newPic = [];
2845
-		    newPic = [buddyObj.DisplayName, localDB.getItem("img-"+ buddyObj.cID +"-contact", base64)];
2846
-		    saveContactPicToSQLDB(newPic);
2847
-                }
2848
-                else if(buddyObj.Type == "group") {
2849
-                    localDB.setItem("img-"+ buddyObj.gID +"-group", base64);
2850
-                    $("#contact-"+ buddyObj.gID +"-picture-main").css("background-image", 'url('+ getPicture(buddyObj.gID, 'group') +')');
2851
-                    $("#contact-"+ buddyObj.gID +"-presence-main").html(buddyObj.Description);
2852
-
2853
-                    // Save contact picture to SQL database
2854
-		    var newPic = [];
2855
-		    newPic = [buddyObj.DisplayName, localDB.getItem("img-"+ buddyObj.gID +"-group", base64)];
2856
-		    saveContactPicToSQLDB(newPic);
2857
-                }
2858
-
2859
-                // Update
2860
-                UpdateBuddyList();
2861
-            });
2862
-
2863
-            // Update: 
2864
-            json.DataCollection[itemId] = buddyObj;
2865
-
2866
-            // Save To DB
2867
-            localDB.setItem(profileUserID + "-Buddies", JSON.stringify(json));
2868
-
2869
-            var newPerson = [];
2870
-
2871
-            newPerson = [currentCtctName, finCurrentDesc, finCurrentExtension, finCurrentMobile, finCurrentNum1, finCurrentNum2, finCurrentEmail, contactDatabaseId];
2872
-
2873
-            updateContactToSQLDB(newPerson);
2874
-
2875
-            // Update the Memory Array, so that the UpdateBuddyList can make the changes
2876
-            for(var b = 0; b < Buddies.length; b++) {
2877
-                if(buddyObj.Type == "extension"){
2878
-                    if(buddyObj.uID == Buddies[b].identity){
2879
-                        Buddies[b].lastActivity = buddyObj.LastActivity;
2880
-                        Buddies[b].CallerIDName = buddyObj.DisplayName;
2881
-                        Buddies[b].Desc = buddyObj.Position;
2882
-                    }                
2883
-                }
2884
-                else if(buddyObj.Type == "contact") {
2885
-                    if(buddyObj.cID == Buddies[b].identity){
2886
-                        Buddies[b].lastActivity = buddyObj.LastActivity;
2887
-                        Buddies[b].CallerIDName = buddyObj.DisplayName;
2888
-                        Buddies[b].Desc = buddyObj.Description;
2889
-                    }                
2890
-                }
2891
-                else if(buddyObj.Type == "group") {
2892
-                
2893
-                }
2894
-            }
2895
-
2896
-            UpdateBuddyList();
2897
-
2898
-            $.jeegoopopup.close();
2899
-            $("#jg_popup_b").empty();
2900
-
2901
-        } else { alert('The display name that you entered is not a valid display name!'); }
2902
-
2903
-      } else { alert("'Display Name' cannot be empty!"); }
2904
-
2905
-    });
2906
-
2907
-    var maxWidth = $(window).width() - 16;
2908
-    var maxHeight = $(window).height() - 110;
2909
-
2910
-    if (maxWidth < 656 || maxHeight < 500) { 
2911
-        $.jeegoopopup.width(maxWidth).height(maxHeight);
2912
-        $.jeegoopopup.center();
2913
-        $("#maximizeImg").hide();
2914
-        $("#minimizeImg").hide();
2915
-    } else { 
2916
-        $.jeegoopopup.width(640).height(500);
2917
-        $.jeegoopopup.center();
2918
-        $("#minimizeImg").hide();
2919
-        $("#maximizeImg").show();
2920
-    }
2921
-
2922
-    $(window).resize(function() {
2923
-        maxWidth = $(window).width() - 16;
2924
-        maxHeight = $(window).height() - 110;
2925
-        $.jeegoopopup.center();
2926
-        if (maxWidth < 656 || maxHeight < 500) { 
2927
-            $.jeegoopopup.width(maxWidth).height(maxHeight);
2928
-            $.jeegoopopup.center();
2929
-            $("#maximizeImg").hide();
2930
-            $("#minimizeImg").hide();
2931
-        } else { 
2932
-            $.jeegoopopup.width(640).height(500);
2933
-            $.jeegoopopup.center();
2934
-            $("#minimizeImg").hide();
2935
-            $("#maximizeImg").show();
2936
-        }
2937
-    });
2938
-
2939
-    $("#minimizeImg").click(function() { $.jeegoopopup.width(640).height(500); $.jeegoopopup.center(); $("#maximizeImg").show(); $("#minimizeImg").hide(); });
2940
-    $("#maximizeImg").click(function() { $.jeegoopopup.width(maxWidth).height(maxHeight); $.jeegoopopup.center(); $("#minimizeImg").show(); $("#maximizeImg").hide(); });
2941
-
2942
-    $("#closeImg").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
2943
-    $("#cancel_button").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
2944
-    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
2945
-    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); $("#jg_popup_b").empty(); } });
2946
-}
2947
-
2948
-// Document Ready
2949
-// ==============
2950
-$(document).ready(function () {
2951
-    
2952
-    // Load Langauge File
2953
-    // ==================
2954
-    $.getJSON(hostingPrefex + "lang/en.json", function (data){
2955
-        lang = data;
2956
-        var userLang = GetAlternateLanguage();
2957
-        if(userLang != ""){
2958
-            $.getJSON(hostingPrefex +"lang/"+ userLang +".json", function (altdata){
2959
-                lang = altdata;
2960
-            }).always(function() {
2961
-                console.log("Alternate Lanaguage Pack loaded: ", lang);
2962
-                InitUi();
2963
-            });
2964
-        }
2965
-        else {
2966
-            console.log("Lanaguage Pack already loaded: ", lang);
2967
-            InitUi();
2968
-        }
2969
-    });
2970
-
2971
-    // Get configuration data from SQL database
2972
-    getConfFromSqldb();
2973
-    getExternalUserConfFromSqldb();
2974
-});
2975
-
2976
-// Init UI
2977
-// =======
2978
-function InitUi(){
2979
-
2980
-    var phone = $("#Phone");
2981
-    phone.empty();
2982
-    phone.attr("class", "pageContainer");
2983
-
2984
-    // Left Section
2985
-    var leftSection = $("<div>");
2986
-    leftSection.attr("id", "leftContent");
2987
-    leftSection.attr("style", "float:left; height: 100%; width:320px");
2988
-
2989
-    var leftHTML = "<table style=\"height:100%; width:100%\" cellspacing=5 cellpadding=0>";
2990
-    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>";
2991
-    leftHTML += "<tr><td class=streamSection style=\"height: 82px\">";
2992
-
2993
-    // Profile User
2994
-    leftHTML += "<div class=profileContainer>";
2995
-    leftHTML += "<div class=contact id=UserProfile style=\"margin-bottom:12px;\">";
2996
-    leftHTML += "<div id=UserProfilePic class=buddyIcon title=\"Status\"></div>";
2997
-    leftHTML += "<span id=reglink class=dotOffline></span>";
2998
-    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>";
2999
-    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>";
3000
-    leftHTML += "<div class=contactNameText style=\"margin-right: 0px;\"><i class=\"fa fa-phone-square\"></i> <span id=UserDID></span> - <span id=UserCallID></span></div>";
3001
-    leftHTML += "<div id=regStatus class=presenceText>&nbsp;</div>";
3002
-    leftHTML += "</div>";
3003
-    // Search / Add Buddies
3004
-    leftHTML += "<div id=searchBoxAndIcons>";
3005
-    leftHTML += "<span class=searchClean><INPUT id=txtFindBuddy type=text autocomplete=none style=\"width:142px;\" title=\"Find Contact\"></span>";
3006
-    leftHTML += "<div id=ButtonsOnSearchLine>";
3007
-    leftHTML += "<button id=BtnFreeDial title='"+ lang.dial_number +"'></button>";
3008
-    leftHTML += "<button id=LaunchVideoConf title='"+ lang.launch_video_conference +"'><i class=\"fa fa-users\"></i></button>";
3009
-    leftHTML += "<button id=BtnSettings title='"+ lang.account_settings +"'><i class=\"fa fa-cog\"></i></button>";
3010
-    leftHTML += "</div>";
3011
-    leftHTML += "</div>";
3012
-    leftHTML += "</div>";
3013
-    leftHTML += "</td></tr>";
3014
-    // Lines & Buddies
3015
-    leftHTML += "<tr><td class=streamSection><div id=myContacts class=\"contactArea cleanScroller\"></div></td></tr>";
3016
-    leftHTML += "</table>";
3017
-
3018
-    leftSection.html(leftHTML);
3019
-    
3020
-    // Right Section
3021
-    var rightSection = $("<div>");
3022
-    rightSection.attr("id", "rightContent");
3023
-    rightSection.attr("style", "margin-left: 320px; height: 100%; overflow: auto;");
3024
-
3025
-    phone.append(leftSection);
3026
-    phone.append(rightSection);
3027
-
3028
-    // Setup Windows
3029
-    windowsCollection = '';
3030
-    messagingCollection = '';
3031
-
3032
-    if(DisableFreeDial == true) $("#BtnFreeDial").hide();
3033
-    if(DisableBuddies == true) $("#BtnAddSomeone").hide();
3034
-    if(enabledGroupServices == false) $("#BtnCreateGroup").hide();
3035
-
3036
-    $("#UserDID").html(profileUser);
3037
-    $("#UserCallID").html(profileName);
3038
-    $("#UserProfilePic").css("background-image", "url('"+ getPicture("profilePicture") +"')");
3039
-    
3040
-    $("#txtFindBuddy").attr("placeholder", lang.find_someone);
3041
-    $("#txtFindBuddy").on('keyup', function(event){
3042
-        UpdateBuddyList();
3043
-    });
3044
-
3045
-    $("#BtnFreeDial").on('click', function(event){
3046
-        ShowDial(this);
3047
-    });
3048
-
3049
-    $("#BtnAddSomeone").attr("title", lang.add_contact);
3050
-    $("#BtnAddSomeone").on('click', function(event){
3051
-        AddSomeoneWindow();
3052
-    });
3053
-
3054
-    $("#BtnCreateGroup").attr("title", lang.create_group);
3055
-    $("#BtnCreateGroup").on('click', function(event){
3056
-        CreateGroupWindow();
3057
-    });
3058
-
3059
-    $("#LaunchVideoConf").on('click', function(event){
3060
-       ShowLaunchVidConfMenu(this);
3061
-    });
3062
-
3063
-    $("#BtnSettings").on('click', function(event){
3064
-       ShowAccountSettingsMenu(this);
3065
-    });
3066
-
3067
-    $("#UserProfile").on('click', function(event){
3068
-        ShowMyProfileMenu(this);
3069
-    });
3070
-
3071
-    UpdateUI();
3072
-    
3073
-    PopulateBuddyList();
3074
-
3075
-    // Select Last user
3076
-    if(localDB.getItem("SelectedBuddy") != null){
3077
-        console.log("Selecting previously selected buddy...", localDB.getItem("SelectedBuddy"));
3078
-        SelectBuddy(localDB.getItem("SelectedBuddy"));
3079
-        UpdateUI();
3080
-    }
3081
-
3082
-    PreloadAudioFiles();
3083
-
3084
-    CreateUserAgent();
3085
-
3086
-    getContactsFromSQLDB();
3087
-
3088
-    generateChatRSAKeys(getDbItem("SipUsername", ""));
3089
-
3090
-    removeTextChatUploads(getDbItem("SipUsername", ""));
3091
-}
3092
-
3093
-function PreloadAudioFiles(){
3094
-    audioBlobs.Alert = { file : "Alert.mp3", url : hostingPrefex +"sounds/Alert.mp3" }
3095
-    audioBlobs.Ringtone = { file : "Ringtone_1.mp3", url : hostingPrefex +"sounds/Ringtone_1.mp3" }
3096
-    audioBlobs.speaker_test = { file : "Speaker_test.mp3", url : hostingPrefex +"sounds/Speaker_test.mp3" }
3097
-    audioBlobs.Busy_UK = { file : "Tone_Busy-UK.mp3", url : hostingPrefex +"sounds/Tone_Busy-UK.mp3" }
3098
-    audioBlobs.Busy_US = { file : "Tone_Busy-US.mp3", url : hostingPrefex +"sounds/Tone_Busy-US.mp3" }
3099
-    audioBlobs.CallWaiting = { file : "Tone_CallWaiting.mp3", url : hostingPrefex +"sounds/Tone_CallWaiting.mp3" }
3100
-    audioBlobs.Congestion_UK = { file : "Tone_Congestion-UK.mp3", url : hostingPrefex +"sounds/Tone_Congestion-UK.mp3" }
3101
-    audioBlobs.Congestion_US = { file : "Tone_Congestion-US.mp3", url : hostingPrefex +"sounds/Tone_Congestion-US.mp3" }
3102
-    audioBlobs.EarlyMedia_Australia = { file : "Tone_EarlyMedia-Australia.mp3", url : hostingPrefex +"sounds/Tone_EarlyMedia-Australia.mp3" }
3103
-    audioBlobs.EarlyMedia_European = { file : "Tone_EarlyMedia-European.mp3", url : hostingPrefex +"sounds/Tone_EarlyMedia-European.mp3" }
3104
-    audioBlobs.EarlyMedia_Japan = { file : "Tone_EarlyMedia-Japan.mp3", url : hostingPrefex +"sounds/Tone_EarlyMedia-Japan.mp3" }
3105
-    audioBlobs.EarlyMedia_UK = { file : "Tone_EarlyMedia-UK.mp3", url : hostingPrefex +"sounds/Tone_EarlyMedia-UK.mp3" }
3106
-    audioBlobs.EarlyMedia_US = { file : "Tone_EarlyMedia-US.mp3", url : hostingPrefex +"sounds/Tone_EarlyMedia-US.mp3" }
3107
-    
3108
-    $.each(audioBlobs, function (i, item) {
3109
-        var oReq = new XMLHttpRequest();
3110
-        oReq.open("GET", item.url, true);
3111
-        oReq.responseType = "blob";
3112
-        oReq.onload = function(oEvent) {
3113
-            var reader = new FileReader();
3114
-            reader.readAsDataURL(oReq.response);
3115
-            reader.onload = function() {
3116
-                item.blob = reader.result;
3117
-            }
3118
-        }
3119
-        oReq.send();
3120
-    });
3121
-}
3122
-// Create User Agent
3123
-// =================
3124
-function CreateUserAgent() {
3125
-
3126
-    $.ajax({
3127
-        'async': false,
3128
-        'global': false,
3129
-        type: "POST",
3130
-        url: "get-sippass.php",
3131
-        dataType: "JSON",
3132
-        data: {
3133
-                username: userName,
3134
-                s_ajax_call: validateSToken
3135
-        },
3136
-        success: function (sipdatafromdb) {
3137
-                       decSipPass = sipdatafromdb;
3138
-        },
3139
-        error: function(sipdatafromdb) {
3140
-                 alert("An error occurred while attempting to retrieve data from the database!");
3141
-        }
3142
-    });
3143
-
3144
-    try {
3145
-        console.log("Creating User Agent...");
3146
-        var options = {
3147
-            displayName: profileName,
3148
-            uri: SipUsername + "@" + wssServer,
3149
-            transportOptions: {
3150
-                wsServers: "wss://" + wssServer + ":"+ WebSocketPort +""+ ServerPath,
3151
-                traceSip: false,
3152
-                connectionTimeout: TransportConnectionTimeout,
3153
-                maxReconnectionAttempts: TransportReconnectionAttempts,
3154
-                reconnectionTimeout: TransportReconnectionTimeout,
3155
-            },
3156
-            sessionDescriptionHandlerFactoryOptions:{
3157
-                peerConnectionOptions :{
3158
-                    alwaysAcquireMediaFirst: true, // Better for firefox, but seems to have no effect on others
3159
-                    iceCheckingTimeout: IceStunCheckTimeout,
3160
-                    rtcConfiguration: {}
3161
-                }
3162
-            },
3163
-            authorizationUser: SipUsername,
3164
-//            password: SipPassword,
3165
-            password: decSipPass,
3166
-            registerExpires: RegisterExpires,
3167
-            hackWssInTransport: WssInTransport,
3168
-            hackIpInContact: IpInContact,
3169
-            userAgentString: userAgentStr,
3170
-            autostart: false,
3171
-            register: false,
3172
-        }
3173
-
3174
-        decSipPass = '';
3175
-
3176
-        var currentStunServer = getDbItem("StunServer", "");
3177
-
3178
-        if (currentStunServer == '' || currentStunServer == null || typeof currentStunServer == 'undefined') { 
3179
-            var IceStunServersList = '';
3180
-        } else { var IceStunServersList = '[{"urls":"stun:'+currentStunServer+'"}]'; }
3181
-
3182
-        if (IceStunServersList != "") {
3183
-            options.sessionDescriptionHandlerFactoryOptions.peerConnectionOptions.rtcConfiguration.iceServers = JSON.parse(IceStunServersList);
3184
-        }
3185
-
3186
-        userAgent = new SIP.UA(options);
3187
-        console.log("Creating User Agent... Done");
3188
-    }
3189
-    catch (e) {
3190
-        console.error("Error creating User Agent: "+ e);
3191
-        $("#regStatus").html(lang.error_user_agant);
3192
-        alert(e.message);
3193
-        return;
3194
-    }
3195
-
3196
-    // UA Register events
3197
-    userAgent.on('registered', function () {
3198
-        // This code fires on re-regiter after session timeout
3199
-        // to ensure that events are not fired multiple times
3200
-        // an isReRegister state is kept.
3201
-        if(!isReRegister) {
3202
-            console.log("Registered!");
3203
-
3204
-            $("#reglink").hide();
3205
-            $("#dereglink").show();
3206
-            if(DoNotDisturbEnabled || DoNotDisturbPolicy == "enabled") {
3207
-                $("#dereglink").attr("class", "dotDoNotDisturb");
3208
-            }
3209
-
3210
-            // Start Subscribe Loop
3211
-            SubscribeAll();
3212
-
3213
-            // Output to status
3214
-            $("#regStatus").html(lang.registered);
3215
-
3216
-            // Custom Web hook
3217
-            if(typeof web_hook_on_register !== 'undefined') web_hook_on_register(userAgent);
3218
-        }
3219
-        isReRegister = true;
3220
-    });
3221
-
3222
-    userAgent.on('registrationFailed', function (response, cause) {
3223
-        console.log("Registration Failed: " + cause);
3224
-        $("#regStatus").html(lang.registration_failed);
3225
-
3226
-        $("#reglink").show();
3227
-        $("#dereglink").hide();
3228
-
3229
-        // We set this flag here so that the re-register attepts are fully completed.
3230
-        isReRegister = false;
3231
-
3232
-        // Custom Web hook
3233
-        if(typeof web_hook_on_registrationFailed !== 'undefined') web_hook_on_registrationFailed(cause);
3234
-    });
3235
-    userAgent.on('unregistered', function () {
3236
-        console.log("Unregistered, bye!");
3237
-        $("#regStatus").html(lang.unregistered);
3238
-
3239
-        $("#reglink").show();
3240
-        $("#dereglink").hide();
3241
-
3242
-        // Custom Web hook
3243
-        if(typeof web_hook_on_unregistered !== 'undefined') web_hook_on_unregistered();
3244
-    });
3245
-
3246
-    // UA transport
3247
-    userAgent.on('transportCreated', function (transport) {
3248
-        console.log("Transport Object Created");
3249
-        
3250
-        // Transport Events
3251
-        transport.on('connected', function () {
3252
-            console.log("Connected to Web Socket!");
3253
-            $("#regStatus").html(lang.connected_to_web_socket);
3254
-
3255
-            $("#WebRtcFailed").hide();
3256
-
3257
-            window.setTimeout(function (){
3258
-                Register();
3259
-            }, 500);
3260
-
3261
-        });
3262
-        transport.on('disconnected', function () {
3263
-            console.log("Disconnected from Web Socket!");
3264
-            $("#regStatus").html(lang.disconnected_from_web_socket);
3265
-
3266
-            // We set this flag here so that the re-register attepts are fully completed.
3267
-            isReRegister = false;
3268
-        });
3269
-        transport.on('transportError', function () {
3270
-            console.log("Web Socket error!");
3271
-            $("#regStatus").html(lang.web_socket_error);
3272
-
3273
-            $("#WebRtcFailed").show();
3274
-
3275
-            // Custom Web hook
3276
-            if(typeof web_hook_on_transportError !== 'undefined') web_hook_on_transportError(transport, userAgent);
3277
-        });
3278
-    });
3279
-
3280
-    // Inbound Calls
3281
-    userAgent.on("invite", function (session) {
3282
-
3283
-        ReceiveCall(session);
3284
-
3285
-        // Show a system notification when the phone rings
3286
-        if (getDbItem("Notifications", "") == 1) {
3287
-            incomingCallNote();
3288
-        }
3289
-
3290
-        changePageTitle();
3291
-
3292
-        // Custom Web hook
3293
-        if(typeof web_hook_on_invite !== 'undefined') web_hook_on_invite(session);
3294
-    });
3295
-
3296
-    // Inbound Text Message
3297
-    userAgent.on('message', function (message) {
3298
-        ReceiveMessage(message);
3299
-
3300
-        // Custom Web hook
3301
-        if(typeof web_hook_on_message !== 'undefined') web_hook_on_message(message);
3302
-    });
3303
-
3304
-    // Start the WebService Connection loop
3305
-    console.log("Connecting to Web Socket...");
3306
-    $("#regStatus").html(lang.connecting_to_web_socket);
3307
-    userAgent.start();
3308
-    
3309
-    // Register Buttons
3310
-    $("#reglink").on('click', Register);
3311
-
3312
-    // WebRTC Error Page
3313
-    $("#WebRtcFailed").on('click', function(){
3314
-        Confirm(lang.error_connecting_web_socket, lang.web_socket_error, function(){
3315
-            window.open("https://"+ wssServer +":"+ WebSocketPort +"/httpstatus");
3316
-        }, null);
3317
-    });
3318
-}
3319
-
3320
-
3321
-// Registration
3322
-// ============
3323
-function Register() {
3324
-
3325
-    if (userAgent == null || userAgent.isRegistered()) return;
3326
-
3327
-    console.log("Sending Registration...");
3328
-    $("#regStatus").html(lang.sending_registration);
3329
-    userAgent.register();
3330
-
3331
-    if (getDbItem("Notifications", "") == 1) {
3332
-          if (Notification.permission != "granted") {
3333
-              Notification.requestPermission();
3334
-          }
3335
-    }
3336
-}
3337
-function Unregister() {
3338
-    if (userAgent == null || !userAgent.isRegistered()) return;
3339
-
3340
-    console.log("Unsubscribing...");
3341
-    $("#regStatus").html(lang.unsubscribing);
3342
-    try {
3343
-        UnsubscribeAll();
3344
-    } catch (e) { }
3345
-
3346
-    console.log("Disconnecting...");
3347
-    $("#regStatus").html(lang.disconnecting);
3348
-    userAgent.unregister();
3349
-
3350
-    isReRegister = false;
3351
-}
3352
-
3353
-// Inbound Calls
3354
-// =============
3355
-function ReceiveCall(session) {
3356
-    var callerID = session.remoteIdentity.displayName;
3357
-    var did = session.remoteIdentity.uri.user;
3358
-
3359
-    if ( typeof callerID == 'undefined') { callerID = ""; }
3360
-
3361
-    console.log("New Incoming Call!", callerID +" <"+ did +">");
3362
-
3363
-    var CurrentCalls = countSessions(session.id);
3364
-    console.log("Current Call Count:", CurrentCalls);
3365
-
3366
-    var buddyObj = FindBuddyByDid(did);
3367
-    // Make new contact if it's not there
3368
-    if(buddyObj == null) {
3369
-        var buddyType = (did.length > DidLength)? "contact" : "extension";
3370
-        var focusOnBuddy = (CurrentCalls==0);
3371
-        buddyObj = MakeBuddy(buddyType, true, focusOnBuddy, true, callerID, did);
3372
-    } else {
3373
-        // Double check that the buddy has the same caller ID as the incoming call
3374
-        // With Buddies that are contacts, eg +441234567890 <+441234567890> leave as is
3375
-        if(buddyObj.type == "extension" && buddyObj.CallerIDName != callerID){
3376
-            UpdateBuddyCalerID(buddyObj, callerID);
3377
-        }
3378
-        else if(buddyObj.type == "contact" && callerID != did && buddyObj.CallerIDName != callerID){
3379
-            UpdateBuddyCalerID(buddyObj, callerID);
3380
-        }
3381
-    }
3382
-    var buddy = buddyObj.identity;
3383
-
3384
-    // Time Stamp
3385
-    window.clearInterval(session.data.callTimer);
3386
-    var startTime = moment.utc();
3387
-    session.data.callstart = startTime.format("YYYY-MM-DD HH:mm:ss UTC");
3388
-    $("#contact-" + buddy + "-timer").show();
3389
-    session.data.callTimer = window.setInterval(function(){
3390
-        var now = moment.utc();
3391
-        var duration = moment.duration(now.diff(startTime)); 
3392
-        $("#contact-" + buddy + "-timer").html(formatShortDuration(duration.asSeconds()));
3393
-    }, 1000);
3394
-    session.data.buddyId = buddy;
3395
-    session.data.calldirection = "inbound";
3396
-    session.data.terminateby = "them";
3397
-    session.data.withvideo = false;
3398
-    var videoInvite = false;
3399
-    if (session.request.body) {
3400
-        // Asterisk 13 PJ_SIP always sends m=video if endpoint has video codec,
3401
-        // even if origional invite does not specify video.
3402
-        if (session.request.body.indexOf("m=video") > -1) {
3403
-           videoInvite = true;
3404
-           if (buddyObj.type == "contact"){
3405
-                videoInvite = false;
3406
-           }
3407
-        }
3408
-    }
3409
-
3410
-    // Inbound You or They Rejected
3411
-    session.on('rejected', function (response, cause) {
3412
-        console.log("Call rejected: " + cause);
3413
-
3414
-        session.data.reasonCode = response.status_code
3415
-        session.data.reasonText = cause
3416
-    
3417
-        AddCallMessage(buddy, session, response.status_code, cause);
3418
-
3419
-        // Custom Web hook
3420
-        if(typeof web_hook_on_terminate !== 'undefined') web_hook_on_terminate(session);
3421
-    });
3422
-    // They cancelled (Gets called regardless)
3423
-    session.on('terminated', function(response, cause) {
3424
-
3425
-        // Stop the ringtone
3426
-        if(session.data.rinngerObj){
3427
-            session.data.rinngerObj.pause();
3428
-            session.data.rinngerObj.removeAttribute('src');
3429
-            session.data.rinngerObj.load();
3430
-            session.data.rinngerObj = null;
3431
-        }
3432
-
3433
-        $.jeegoopopup.close();
3434
-        console.log("Call terminated");
3435
-
3436
-        window.clearInterval(session.data.callTimer);
3437
-
3438
-        $("#contact-" + buddy + "-timer").html("");
3439
-        $("#contact-" + buddy + "-timer").hide();
3440
-        $("#contact-" + buddy + "-msg").html("");
3441
-        $("#contact-" + buddy + "-msg").hide();
3442
-        $("#contact-" + buddy + "-AnswerCall").hide();
3443
-
3444
-        RefreshStream(buddyObj);
3445
-        updateScroll(buddyObj.identity);
3446
-        UpdateBuddyList();
3447
-    });
3448
-
3449
-    // Start Handle Call
3450
-    if(DoNotDisturbEnabled || DoNotDisturbPolicy == "enabled") {
3451
-        console.log("Do Not Disturb Enabled, rejecting call.");
3452
-        RejectCall(buddyObj.identity);
3453
-        return;
3454
-    }
3455
-    if(CurrentCalls >= 1){
3456
-        if(CallWaitingEnabled == false || CallWaitingEnabled == "disabled"){
3457
-            console.log("Call Waiting Disabled, rejecting call.");
3458
-            RejectCall(buddyObj.identity);
3459
-            return;
3460
-        }
3461
-    }
3462
-    if(AutoAnswerEnabled || AutoAnswerPolicy == "enabled"){
3463
-        if(CurrentCalls == 0){ // There are no other calls, so you can answer
3464
-            console.log("Auto Answer Call...");
3465
-            var buddyId = buddyObj.identity;
3466
-            window.setTimeout(function(){
3467
-                // If the call is with video, assume the auto answer is also
3468
-                // In order for this to work nicely, the recipient must be "ready" to accept video calls
3469
-                // In order to ensure video call compatibility (i.e. the recipient must have their web cam in, and working)
3470
-                // The NULL video should be configured
3471
-                // https://github.com/InnovateAsterisk/Browser-Phone/issues/26
3472
-                if(videoInvite) {
3473
-                    AnswerVideoCall(buddyId)
3474
-                }
3475
-                else {
3476
-                    AnswerAudioCall(buddyId);
3477
-                }
3478
-            }, 1000);
3479
-
3480
-            // Select Buddy
3481
-            SelectBuddy(buddyObj.identity);
3482
-            return;
3483
-        }
3484
-        else {
3485
-            console.warn("Could not auto answer call, already on a call.");
3486
-        }
3487
-    }
3488
-    
3489
-    // Show the Answer Thingy
3490
-    $("#contact-" + buddyObj.identity + "-msg").html(lang.incomming_call_from +" " + callerID +" &lt;"+ did +"&gt;");
3491
-    $("#contact-" + buddyObj.identity + "-msg").show();
3492
-    if(videoInvite){
3493
-        $("#contact-"+ buddyObj.identity +"-answer-video").show();
3494
-    }
3495
-    else {
3496
-        $("#contact-"+ buddyObj.identity +"-answer-video").hide();
3497
-    }
3498
-    $("#contact-" + buddyObj.identity + "-AnswerCall").show();
3499
-    updateScroll(buddyObj.identity);
3500
-
3501
-    // Play Ring Tone if not on the phone
3502
-    if(CurrentCalls >= 1){
3503
-
3504
-        // Play Alert
3505
-        console.log("Audio:", audioBlobs.CallWaiting.url);
3506
-        var rinnger = new Audio(audioBlobs.CallWaiting.blob);
3507
-        rinnger.preload = "auto";
3508
-        rinnger.loop = false;
3509
-        rinnger.oncanplaythrough = function(e) {
3510
-            if (typeof rinnger.sinkId !== 'undefined' && getRingerOutputID() != "default") {
3511
-                rinnger.setSinkId(getRingerOutputID()).then(function() {
3512
-                    console.log("Set sinkId to:", getRingerOutputID());
3513
-                }).catch(function(e){
3514
-                    console.warn("Failed not apply setSinkId.", e);
3515
-                });
3516
-            }
3517
-            // If there has been no interaction with the page at all... this page will not work
3518
-            rinnger.play().then(function(){
3519
-               // Audio Is Playing
3520
-            }).catch(function(e){
3521
-                console.warn("Unable to play audio file.", e);
3522
-            }); 
3523
-        }
3524
-        session.data.rinngerObj = rinnger;
3525
-    } else {
3526
-        // Play Ring Tone
3527
-        console.log("Audio:", audioBlobs.Ringtone.url);
3528
-        var rinnger = new Audio(audioBlobs.Ringtone.blob);
3529
-        rinnger.preload = "auto";
3530
-        rinnger.loop = true;
3531
-        rinnger.oncanplaythrough = function(e) {
3532
-            if (typeof rinnger.sinkId !== 'undefined' && getRingerOutputID() != "default") {
3533
-                rinnger.setSinkId(getRingerOutputID()).then(function() {
3534
-                    console.log("Set sinkId to:", getRingerOutputID());
3535
-                }).catch(function(e){
3536
-                    console.warn("Failed not apply setSinkId.", e);
3537
-                });
3538
-            }
3539
-            // If there has been no interaction with the page at all... this page will not work
3540
-            rinnger.play().then(function(){
3541
-               // Audio Is Playing
3542
-            }).catch(function(e){
3543
-                console.warn("Unable to play audio file.", e);
3544
-            }); 
3545
-        }
3546
-        session.data.rinngerObj = rinnger;
3547
-    }
3548
-
3549
-    $.jeegoopopup.close();
3550
-
3551
-    // Show Call Answer Window
3552
-    var callAnswerHtml = '<div id="windowCtrls"><img id="closeImg" src="images/3_close.svg" title="Close" /></div>';
3553
-    callAnswerHtml += "<div class=\"UiWindowField scroller\" style=\"text-align:center\">";
3554
-    callAnswerHtml += "<div style=\"font-size: 18px; margin-top:1px\">"+ callerID + "<div>";
3555
-    if(callerID != did) {
3556
-            callAnswerHtml += "<div style=\"font-size: 18px; margin-top:1px\">&lt;"+ did + "&gt;<div>";
3557
-    }
3558
-    callAnswerHtml += "<div class=callAnswerBuddyIcon style=\"background-image: url("+ getPicture(buddyObj.identity) +"); margin-top:6px\"></div>";
3559
-    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>";
3560
-    if(videoInvite) {
3561
-            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>";
3562
-    }
3563
-    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>";
3564
-    callAnswerHtml += "</div>";
3565
-
3566
-    $.jeegoopopup.open({
3567
-                title: 'Incoming Call',
3568
-                html: callAnswerHtml,
3569
-                width: '290',
3570
-                height: '300',
3571
-                center: true,
3572
-                scrolling: 'no',
3573
-                skinClass: 'jg_popup_basic',
3574
-                overlay: true,
3575
-                opacity: 50,
3576
-                draggable: true,
3577
-                resizable: false,
3578
-                fadeIn: 0
3579
-    });
3580
-
3581
-    $("#closeImg").click(function() { $.jeegoopopup.close(); });
3582
-    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); });
3583
-    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); } });
3584
-
3585
-    // Add a notification badge
3586
-    IncreaseMissedBadge(buddyObj.identity);
3587
-
3588
-    // Show notification
3589
-    // =================
3590
-    if ("Notification" in window) {
3591
-        if (getDbItem("Notifications", "") == 1) {
3592
-            var noticeOptions = { body: lang.incomming_call_from +" " + callerID +" \""+ did +"\"", icon: getPicture(buddyObj.identity) }
3593
-            var inComingCallNotification = new Notification(lang.incomming_call, noticeOptions);
3594
-            inComingCallNotification.onclick = function (event) {
3595
-
3596
-                var buddyId = buddyObj.identity;
3597
-                window.setTimeout(function() {
3598
-                    // https://github.com/InnovateAsterisk/Browser-Phone/issues/26
3599
-                    if(videoInvite) {
3600
-                            AnswerVideoCall(buddyId)
3601
-                    } else {
3602
-                            AnswerAudioCall(buddyId);
3603
-                    }
3604
-                }, 4000);
3605
-
3606
-                // Select Buddy
3607
-                SelectBuddy(buddyObj.identity);
3608
-
3609
-                return;
3610
-            }
3611
-        }
3612
-    }
3613
-
3614
-}
3615
-
3616
-function AnswerAudioCall(buddy) {
3617
-
3618
-    $.jeegoopopup.close();
3619
-
3620
-    var buddyObj = FindBuddyByIdentity(buddy);
3621
-    if(buddyObj == null) {
3622
-        console.warn("Audio Answer failed, null buddy");
3623
-        $("#contact-" + buddy + "-msg").html(lang.call_failed);
3624
-        $("#contact-" + buddy + "-AnswerCall").hide();
3625
-        return;
3626
-    }
3627
-
3628
-    var session = getSession(buddy);
3629
-    if (session == null) {
3630
-        console.warn("Audio Answer failed, null session");
3631
-        $("#contact-" + buddy + "-msg").html(lang.call_failed);
3632
-        $("#contact-" + buddy + "-AnswerCall").hide();
3633
-        return;
3634
-    }
3635
-    
3636
-    // Stop the ringtone
3637
-    if(session.data.rinngerObj){
3638
-        session.data.rinngerObj.pause();
3639
-        session.data.rinngerObj.removeAttribute('src');
3640
-        session.data.rinngerObj.load();
3641
-        session.data.rinngerObj = null;
3642
-    }
3643
-
3644
-    // Check vitals
3645
-    if(HasAudioDevice == false){
3646
-        Alert(lang.alert_no_microphone);
3647
-        $("#contact-" + buddy + "-msg").html(lang.call_failed);
3648
-        $("#contact-" + buddy + "-AnswerCall").hide();
3649
-        return;
3650
-    }
3651
-    $("#contact-" + buddy + "-timer").html("");
3652
-    $("#contact-" + buddy + "-timer").hide();
3653
-    $("#contact-" + buddy + "-msg").html("");
3654
-    $("#contact-" + buddy + "-msg").hide();
3655
-    $("#contact-" + buddy + "-AnswerCall").hide();
3656
-
3657
-    // Create a new Line and move the session over to the line
3658
-    var callerID = session.remoteIdentity.displayName;
3659
-    var did = session.remoteIdentity.uri.user;
3660
-    newLineNumber = newLineNumber + 1;
3661
-    lineObj = new Line(newLineNumber, callerID, did, buddyObj);
3662
-    lineObj.SipSession = session;
3663
-    lineObj.SipSession.data.line = lineObj.LineNumber;
3664
-    lineObj.SipSession.data.buddyId = lineObj.BuddyObj.identity;
3665
-    Lines.push(lineObj);
3666
-    AddLineHtml(lineObj);
3667
-    SelectLine(newLineNumber);
3668
-    UpdateBuddyList();
3669
-
3670
-    var supportedConstraints = navigator.mediaDevices.getSupportedConstraints();
3671
-    var spdOptions = {
3672
-        sessionDescriptionHandlerOptions: {
3673
-            constraints: {
3674
-                audio: { deviceId : "default" },
3675
-                video: false
3676
-            }
3677
-        }
3678
-    }
3679
-
3680
-    // Configure Audio
3681
-    var currentAudioDevice = getAudioSrcID();
3682
-    if(currentAudioDevice != "default"){
3683
-        var confirmedAudioDevice = false;
3684
-        for (var i = 0; i < AudioinputDevices.length; ++i) {
3685
-            if(currentAudioDevice == AudioinputDevices[i].deviceId) {
3686
-                confirmedAudioDevice = true;
3687
-                break;
3688
-            }
3689
-        }
3690
-        if(confirmedAudioDevice) {
3691
-            spdOptions.sessionDescriptionHandlerOptions.constraints.audio.deviceId = { exact: currentAudioDevice }
3692
-        }
3693
-        else {
3694
-            console.warn("The audio device you used before is no longer available, default settings applied.");
3695
-            localDB.setItem("AudioSrcId", "default");
3696
-        }
3697
-    }
3698
-    // Add additional Constraints
3699
-    if(supportedConstraints.autoGainControl) {
3700
-        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.autoGainControl = AutoGainControl;
3701
-    }
3702
-    if(supportedConstraints.echoCancellation) {
3703
-        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.echoCancellation = EchoCancellation;
3704
-    }
3705
-    if(supportedConstraints.noiseSuppression) {
3706
-        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.noiseSuppression = NoiseSuppression;
3707
-    }
3708
-
3709
-    // Send Answer
3710
-    lineObj.SipSession.accept(spdOptions);
3711
-    lineObj.SipSession.data.withvideo = false;
3712
-    lineObj.SipSession.data.VideoSourceDevice = null;
3713
-    lineObj.SipSession.data.AudioSourceDevice = getAudioSrcID();
3714
-    lineObj.SipSession.data.AudioOutputDevice = getAudioOutputID();
3715
-
3716
-    // Wire up UI
3717
-    wireupAudioSession(lineObj);
3718
-    $("#contact-" + buddy + "-msg").html(lang.call_in_progress);
3719
-
3720
-    // Clear Answer Buttons
3721
-    $("#contact-" + buddy + "-AnswerCall").hide();
3722
-}
3723
-
3724
-function AnswerVideoCall(buddy) {
3725
-
3726
-    $.jeegoopopup.close();
3727
-
3728
-    var buddyObj = FindBuddyByIdentity(buddy);
3729
-    if(buddyObj == null) {
3730
-        console.warn("Audio Answer failed, null buddy");
3731
-        $("#contact-" + buddy + "-msg").html(lang.call_failed);
3732
-        $("#contact-" + buddy + "-AnswerCall").hide();
3733
-        return;
3734
-    }
3735
-
3736
-    var session = getSession(buddy);
3737
-    if (session == null) {
3738
-        console.warn("Video Answer failed, null session");
3739
-        $("#contact-" + buddy + "-msg").html(lang.call_failed);
3740
-        $("#contact-" + buddy + "-AnswerCall").hide();
3741
-        return;
3742
-    }
3743
-
3744
-    // Stop the ringtone
3745
-    if(session.data.rinngerObj){
3746
-        session.data.rinngerObj.pause();
3747
-        session.data.rinngerObj.removeAttribute('src');
3748
-        session.data.rinngerObj.load();
3749
-        session.data.rinngerObj = null;
3750
-    }
3751
-
3752
-    // Check vitals
3753
-    if(HasAudioDevice == false){
3754
-        Alert(lang.alert_no_microphone);
3755
-        $("#contact-" + buddy + "-msg").html(lang.call_failed);
3756
-        $("#contact-" + buddy + "-AnswerCall").hide();
3757
-        return;
3758
-    }
3759
-    if(HasVideoDevice == false){
3760
-        console.warn("No video devices (webcam) found, switching to audio call.");
3761
-        AnswerAudioCall(buddy);
3762
-        return;
3763
-    }
3764
-    $("#contact-" + buddy + "-timer").html("");
3765
-    $("#contact-" + buddy + "-timer").hide();
3766
-    $("#contact-" + buddy + "-msg").html("");
3767
-    $("#contact-" + buddy + "-msg").hide();
3768
-    $("#contact-" + buddy + "-AnswerCall").hide();
3769
-
3770
-    // Create a new Line and move the session over to the line
3771
-    var callerID = session.remoteIdentity.displayName;
3772
-    var did = session.remoteIdentity.uri.user;
3773
-    newLineNumber = newLineNumber + 1;
3774
-    lineObj = new Line(newLineNumber, callerID, did, buddyObj);
3775
-    lineObj.SipSession = session;
3776
-    lineObj.SipSession.data.line = lineObj.LineNumber;
3777
-    lineObj.SipSession.data.buddyId = lineObj.BuddyObj.identity;
3778
-    Lines.push(lineObj);
3779
-    AddLineHtml(lineObj);
3780
-    SelectLine(newLineNumber);
3781
-    UpdateBuddyList();
3782
-
3783
-    var supportedConstraints = navigator.mediaDevices.getSupportedConstraints();
3784
-    var spdOptions = {
3785
-        sessionDescriptionHandlerOptions: {
3786
-            constraints: {
3787
-                audio: { deviceId : "default" },
3788
-                video: { deviceId : "default" }
3789
-            }
3790
-        }
3791
-    }
3792
-
3793
-    // Configure Audio
3794
-    var currentAudioDevice = getAudioSrcID();
3795
-    if(currentAudioDevice != "default"){
3796
-        var confirmedAudioDevice = false;
3797
-        for (var i = 0; i < AudioinputDevices.length; ++i) {
3798
-            if(currentAudioDevice == AudioinputDevices[i].deviceId) {
3799
-                confirmedAudioDevice = true;
3800
-                break;
3801
-            }
3802
-        }
3803
-        if(confirmedAudioDevice) {
3804
-            spdOptions.sessionDescriptionHandlerOptions.constraints.audio.deviceId = { exact: currentAudioDevice }
3805
-        }
3806
-        else {
3807
-            console.warn("The audio device you used before is no longer available, default settings applied.");
3808
-            localDB.setItem("AudioSrcId", "default");
3809
-        }
3810
-    }
3811
-    // Add additional Constraints
3812
-    if(supportedConstraints.autoGainControl) {
3813
-        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.autoGainControl = AutoGainControl;
3814
-    }
3815
-    if(supportedConstraints.echoCancellation) {
3816
-        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.echoCancellation = EchoCancellation;
3817
-    }
3818
-    if(supportedConstraints.noiseSuppression) {
3819
-        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.noiseSuppression = NoiseSuppression;
3820
-    }
3821
-
3822
-    // Configure Video
3823
-    var currentVideoDevice = getVideoSrcID();
3824
-    if(currentVideoDevice != "default"){
3825
-        var confirmedVideoDevice = false;
3826
-        for (var i = 0; i < VideoinputDevices.length; ++i) {
3827
-            if(currentVideoDevice == VideoinputDevices[i].deviceId) {
3828
-                confirmedVideoDevice = true;
3829
-                break;
3830
-            }
3831
-        }
3832
-        if(confirmedVideoDevice){
3833
-            spdOptions.sessionDescriptionHandlerOptions.constraints.video.deviceId = { exact: currentVideoDevice }
3834
-        }
3835
-        else {
3836
-            console.warn("The video device you used before is no longer available, default settings applied.");
3837
-            localDB.setItem("VideoSrcId", "default"); // resets for later and subsequent calls
3838
-        }
3839
-    }
3840
-    // Add additional Constraints
3841
-    if(supportedConstraints.frameRate && maxFrameRate != "") {
3842
-        spdOptions.sessionDescriptionHandlerOptions.constraints.video.frameRate = maxFrameRate;
3843
-    }
3844
-    if(supportedConstraints.height && videoHeight != "") {
3845
-        spdOptions.sessionDescriptionHandlerOptions.constraints.video.height = videoHeight;
3846
-    }
3847
-    if(supportedConstraints.aspectRatio && videoAspectRatio != "") {
3848
-        spdOptions.sessionDescriptionHandlerOptions.constraints.video.aspectRatio = videoAspectRatio;
3849
-    }
3850
-
3851
-    // Send Answer
3852
-    lineObj.SipSession.data.withvideo = true;
3853
-    lineObj.SipSession.data.VideoSourceDevice = getVideoSrcID();
3854
-    lineObj.SipSession.data.AudioSourceDevice = getAudioSrcID();
3855
-    lineObj.SipSession.data.AudioOutputDevice = getAudioOutputID();
3856
-
3857
-    // Send Answer
3858
-    // If this fails, it must still wireup the call so we can manually close it
3859
-    $("#contact-" + buddy + "-msg").html(lang.call_in_progress);
3860
-    // Wire up UI
3861
-    wireupVideoSession(lineObj);
3862
-
3863
-    try{
3864
-        lineObj.SipSession.accept(spdOptions);
3865
-        if(StartVideoFullScreen) ExpandVideoArea(lineObj.LineNumber);
3866
-        $("#contact-" + buddy + "-AnswerCall").hide();
3867
-    }
3868
-    catch(e){
3869
-        console.warn("Failed to answer call", e, lineObj.SipSession);
3870
-        teardownSession(lineObj, 500, "Client Error");
3871
-    }
3872
-
3873
-}
3874
-
3875
-function RejectCall(buddy) {
3876
-    var session = getSession(buddy);
3877
-    if (session == null) {
3878
-        console.warn("Reject failed, null session");
3879
-        $("#contact-" + buddy + "-msg").html(lang.call_failed);
3880
-        $("#contact-" + buddy + "-AnswerCall").hide();
3881
-    }
3882
-    session.data.terminateby = "us";
3883
-    session.reject({ 
3884
-        statusCode: 486, 
3885
-        reasonPhrase: "Rejected by us"
3886
-    });
3887
-    $("#contact-" + buddy + "-msg").html(lang.call_rejected);
3888
-}
3889
-
3890
-// Session Wireup
3891
-// ==============
3892
-function wireupAudioSession(lineObj) {
3893
-    if (lineObj == null) return;
3894
-
3895
-    var MessageObjId = "#line-" + lineObj.LineNumber + "-msg";
3896
-    var session = lineObj.SipSession;
3897
-
3898
-    session.on('progress', function (response) {
3899
-        // Provisional 1xx
3900
-        if(response.status_code == 100){
3901
-            $(MessageObjId).html(lang.trying);
3902
-        } else if(response.status_code == 180){
3903
-            $(MessageObjId).html(lang.ringing);
3904
-            
3905
-            var soundFile = audioBlobs.EarlyMedia_European;
3906
-            if(UserLocale().indexOf("us") > -1) soundFile = audioBlobs.EarlyMedia_US;
3907
-            if(UserLocale().indexOf("gb") > -1) soundFile = audioBlobs.EarlyMedia_UK;
3908
-            if(UserLocale().indexOf("au") > -1) soundFile = audioBlobs.EarlyMedia_Australia;
3909
-            if(UserLocale().indexOf("jp") > -1) soundFile = audioBlobs.EarlyMedia_Japan;
3910
-
3911
-            // Play Early Media
3912
-            console.log("Audio:", soundFile.url);
3913
-            var earlyMedia = new Audio(soundFile.blob);
3914
-            earlyMedia.preload = "auto";
3915
-            earlyMedia.loop = true;
3916
-            earlyMedia.oncanplaythrough = function(e) {
3917
-                if (typeof earlyMedia.sinkId !== 'undefined' && getAudioOutputID() != "default") {
3918
-                    earlyMedia.setSinkId(getAudioOutputID()).then(function() {
3919
-                        console.log("Set sinkId to:", getAudioOutputID());
3920
-                    }).catch(function(e){
3921
-                        console.warn("Failed not apply setSinkId.", e);
3922
-                    });
3923
-                }
3924
-                earlyMedia.play().then(function(){
3925
-                   // Audio Is Playing
3926
-                }).catch(function(e){
3927
-                    console.warn("Unable to play audio file.", e);
3928
-                }); 
3929
-            }
3930
-            session.data.earlyMedia = earlyMedia;
3931
-        } else {
3932
-            $(MessageObjId).html(response.reason_phrase + "...");
3933
-        }
3934
-
3935
-        // Custom Web hook
3936
-        if(typeof web_hook_on_modify !== 'undefined') web_hook_on_modify("progress", session);
3937
-    });
3938
-    session.on('trackAdded', function () {
3939
-        var pc = session.sessionDescriptionHandler.peerConnection;
3940
-
3941
-        // Gets Remote Audio Track (Local audio is setup via initial GUM)
3942
-        var remoteStream = new MediaStream();
3943
-        pc.getReceivers().forEach(function (receiver) {
3944
-            if(receiver.track && receiver.track.kind == "audio"){
3945
-               remoteStream.addTrack(receiver.track);
3946
-            } 
3947
-        });
3948
-        var remoteAudio = $("#line-" + lineObj.LineNumber + "-remoteAudio").get(0);
3949
-        remoteAudio.srcObject = remoteStream;
3950
-        remoteAudio.onloadedmetadata = function(e) {
3951
-            if (typeof remoteAudio.sinkId !== 'undefined') {
3952
-                remoteAudio.setSinkId(getAudioOutputID()).then(function(){
3953
-                    console.log("sinkId applied: "+ getAudioOutputID());
3954
-                }).catch(function(e){
3955
-                    console.warn("Error using setSinkId: ", e);
3956
-                });
3957
-            }
3958
-            remoteAudio.play();
3959
-        }
3960
-
3961
-        // Custom Web hook
3962
-        if(typeof web_hook_on_modify !== 'undefined') web_hook_on_modify("trackAdded", session);
3963
-    });
3964
-    session.on('accepted', function (data) {
3965
-
3966
-        if(session.data.earlyMedia){
3967
-            session.data.earlyMedia.pause();
3968
-            session.data.earlyMedia.removeAttribute('src');
3969
-            session.data.earlyMedia.load();
3970
-            session.data.earlyMedia = null;
3971
-        }
3972
-
3973
-        window.clearInterval(session.data.callTimer);
3974
-        var startTime = moment.utc();
3975
-        session.data.callTimer = window.setInterval(function(){
3976
-            var now = moment.utc();
3977
-            var duration = moment.duration(now.diff(startTime)); 
3978
-            $("#line-" + lineObj.LineNumber + "-timer").html(formatShortDuration(duration.asSeconds()));
3979
-        }, 1000);
3980
-
3981
-        if(RecordAllCalls || CallRecordingPolicy == "enabled") {
3982
-            StartRecording(lineObj.LineNumber);
3983
-        }
3984
-
3985
-        $("#line-" + lineObj.LineNumber + "-progress").hide();
3986
-        $("#line-" + lineObj.LineNumber + "-VideoCall").hide();
3987
-        $("#line-" + lineObj.LineNumber + "-ActiveCall").show();
3988
-
3989
-        // Audo Monitoring
3990
-        lineObj.LocalSoundMeter = StartLocalAudioMediaMonitoring(lineObj.LineNumber, session);
3991
-        lineObj.RemoteSoundMeter = StartRemoteAudioMediaMonitoring(lineObj.LineNumber, session);
3992
-        
3993
-        $(MessageObjId).html(lang.call_in_progress);
3994
-
3995
-        updateLineScroll(lineObj.LineNumber);
3996
-
3997
-        UpdateBuddyList();
3998
-
3999
-        // Custom Web hook
4000
-        if(typeof web_hook_on_modify !== 'undefined') web_hook_on_modify("accepted", session);
4001
-    });
4002
-    session.on('rejected', function (response, cause) {
4003
-        // Should only apply befor answer
4004
-        $(MessageObjId).html(lang.call_rejected +": " + cause);
4005
-        console.log("Call rejected: " + cause);
4006
-        teardownSession(lineObj, response.status_code, response.reason_phrase);
4007
-    });
4008
-    session.on('failed', function (response, cause) {
4009
-        $(MessageObjId).html(lang.call_failed + ": " + cause);
4010
-        console.log("Call failed: " + cause);
4011
-        teardownSession(lineObj, 0, "Call failed");
4012
-    });
4013
-    session.on('cancel', function () {
4014
-        $(MessageObjId).html(lang.call_cancelled);
4015
-        console.log("Call Cancelled");
4016
-        teardownSession(lineObj, 0, "Cancelled by caller");
4017
-    });
4018
-    // referRequested
4019
-    // replaced
4020
-    session.on('bye', function () {
4021
-        $(MessageObjId).html(lang.call_ended);
4022
-        console.log("Call ended, bye!");
4023
-        teardownSession(lineObj, 16, "Normal Call clearing");
4024
-    });
4025
-    session.on('terminated', function (message, cause) {
4026
-        $(MessageObjId).html(lang.call_ended);
4027
-        console.log("Session terminated");
4028
-        teardownSession(lineObj, 16, "Normal Call clearing");
4029
-    });
4030
-    session.on('reinvite', function (session) {
4031
-        console.log("Session reinvited!");
4032
-    });
4033
-    //dtmf
4034
-    session.on('directionChanged', function() {
4035
-        var direction = session.sessionDescriptionHandler.getDirection();
4036
-        console.log("Direction Change: ", direction);
4037
-
4038
-        // Custom Web hook
4039
-        if(typeof web_hook_on_modify !== 'undefined') web_hook_on_modify("directionChanged", session);
4040
-    });
4041
-
4042
-    $("#line-" + lineObj.LineNumber + "-btn-settings").removeAttr('disabled');
4043
-    $("#line-" + lineObj.LineNumber + "-btn-audioCall").prop('disabled','disabled');
4044
-    $("#line-" + lineObj.LineNumber + "-btn-videoCall").prop('disabled','disabled');
4045
-    $("#line-" + lineObj.LineNumber + "-btn-search").removeAttr('disabled');
4046
-    $("#line-" + lineObj.LineNumber + "-btn-remove").prop('disabled','disabled');
4047
-
4048
-    $("#line-" + lineObj.LineNumber + "-progress").show();
4049
-    $("#line-" + lineObj.LineNumber + "-msg").show();
4050
-
4051
-    if(lineObj.BuddyObj.type == "group") {
4052
-        $("#line-" + lineObj.LineNumber + "-conference").show();
4053
-    } 
4054
-    else {
4055
-        $("#line-" + lineObj.LineNumber + "-conference").hide();
4056
-    }
4057
-
4058
-    updateLineScroll(lineObj.LineNumber);
4059
-
4060
-    UpdateUI();
4061
-}
4062
-
4063
-function wireupVideoSession(lineObj) {
4064
-    if (lineObj == null) return;
4065
-
4066
-    var MessageObjId = "#line-" + lineObj.LineNumber + "-msg";
4067
-    var session = lineObj.SipSession;
4068
-
4069
-    session.on('trackAdded', function () {
4070
-        // Gets remote tracks
4071
-        var pc = session.sessionDescriptionHandler.peerConnection;
4072
-        var remoteAudioStream = new MediaStream();
4073
-        var remoteVideoStream = new MediaStream();
4074
-        pc.getReceivers().forEach(function (receiver) {
4075
-            if(receiver.track){
4076
-                if(receiver.track.kind == "audio"){
4077
-                    remoteAudioStream.addTrack(receiver.track);
4078
-                }
4079
-                if(receiver.track.kind == "video"){
4080
-                    remoteVideoStream.addTrack(receiver.track);
4081
-                }
4082
-            }
4083
-        });
4084
-
4085
-        if (remoteAudioStream.getAudioTracks().length >= 1) {
4086
-            var remoteAudio = $("#line-" + lineObj.LineNumber + "-remoteAudio").get(0);
4087
-            remoteAudio.srcObject = remoteAudioStream;
4088
-            remoteAudio.onloadedmetadata = function(e) {
4089
-               if (typeof remoteAudio.sinkId !== 'undefined') {
4090
-                   remoteAudio.setSinkId(getAudioOutputID()).then(function(){
4091
-                       console.log("sinkId applied: "+ getAudioOutputID());
4092
-                   }).catch(function(e){
4093
-                       console.warn("Error using setSinkId: ", e);
4094
-                   });
4095
-               }
4096
-               remoteAudio.play();
4097
-            }
4098
-        }
4099
-
4100
-        if (remoteVideoStream.getVideoTracks().length >= 1) {
4101
-            var remoteVideo = $("#line-" + lineObj.LineNumber + "-remoteVideo").get(0);
4102
-            remoteVideo.srcObject = remoteVideoStream;
4103
-            remoteVideo.onloadedmetadata = function(e) {
4104
-                remoteVideo.play();
4105
-            }
4106
-        }
4107
-
4108
-        // Note: There appears to be a bug in the peerConnection.getSenders()
4109
-        // The array returns but may or may not be fully populated by the RTCRtpSender
4110
-        // The track property appears to be null initially and then moments later populated.
4111
-        // This does not appear to be the case when originating a call, mostly when receiving a call.
4112
-        window.setTimeout(function(){
4113
-            var localVideoStream = new MediaStream();
4114
-            var pc = session.sessionDescriptionHandler.peerConnection;
4115
-            pc.getSenders().forEach(function (sender) {
4116
-                if(sender.track && sender.track.kind == "video"){
4117
-                    localVideoStream.addTrack(sender.track);
4118
-                }
4119
-            });
4120
-            var localVideo = $("#line-" + lineObj.LineNumber + "-localVideo").get(0);
4121
-            localVideo.srcObject = localVideoStream;
4122
-            localVideo.onloadedmetadata = function(e) {
4123
-                localVideo.play();
4124
-            }
4125
-        }, 1000);
4126
-
4127
-        // Custom Web hook
4128
-        if(typeof web_hook_on_modify !== 'undefined') web_hook_on_modify("trackAdded", session);
4129
-    });
4130
-    session.on('progress', function (response) {
4131
-        // Provisional 1xx
4132
-        if(response.status_code == 100){
4133
-            $(MessageObjId).html(lang.trying);
4134
-        } else if(response.status_code == 180){
4135
-            $(MessageObjId).html(lang.ringing);
4136
-
4137
-            var soundFile = audioBlobs.EarlyMedia_European;
4138
-            if(UserLocale().indexOf("us") > -1) soundFile = audioBlobs.EarlyMedia_US;
4139
-            if(UserLocale().indexOf("gb") > -1) soundFile = audioBlobs.EarlyMedia_UK;
4140
-            if(UserLocale().indexOf("au") > -1) soundFile = audioBlobs.EarlyMedia_Australia;
4141
-            if(UserLocale().indexOf("jp") > -1) soundFile = audioBlobs.EarlyMedia_Japan;
4142
-
4143
-            // Play Early Media
4144
-            console.log("Audio:", soundFile.url);
4145
-            var earlyMedia = new Audio(soundFile.blob);
4146
-            earlyMedia.preload = "auto";
4147
-            earlyMedia.loop = true;
4148
-            earlyMedia.oncanplaythrough = function(e) {
4149
-                if (typeof earlyMedia.sinkId !== 'undefined' && getAudioOutputID() != "default") {
4150
-                    earlyMedia.setSinkId(getAudioOutputID()).then(function() {
4151
-                        console.log("Set sinkId to:", getAudioOutputID());
4152
-                    }).catch(function(e){
4153
-                        console.warn("Failed not apply setSinkId.", e);
4154
-                    });
4155
-                }
4156
-                earlyMedia.play().then(function(){
4157
-                   // Audio Is Playing
4158
-                }).catch(function(e){
4159
-                    console.warn("Unable to play audio file.", e);
4160
-                }); 
4161
-            }
4162
-            session.data.earlyMedia = earlyMedia;
4163
-        } else {
4164
-            $(MessageObjId).html(response.reason_phrase + "...");
4165
-        }
4166
-
4167
-        // Custom Web hook
4168
-        if(typeof web_hook_on_modify !== 'undefined') web_hook_on_modify("progress", session);
4169
-    });
4170
-    session.on('accepted', function (data) {
4171
-        
4172
-        if(session.data.earlyMedia){
4173
-            session.data.earlyMedia.pause();
4174
-            session.data.earlyMedia.removeAttribute('src');
4175
-            session.data.earlyMedia.load();
4176
-            session.data.earlyMedia = null;
4177
-        }
4178
-
4179
-        window.clearInterval(session.data.callTimer);
4180
-        $("#line-" + lineObj.LineNumber + "-timer").show();
4181
-        var startTime = moment.utc();
4182
-        session.data.callTimer = window.setInterval(function(){
4183
-            var now = moment.utc();
4184
-            var duration = moment.duration(now.diff(startTime)); 
4185
-            $("#line-" + lineObj.LineNumber + "-timer").html(formatShortDuration(duration.asSeconds()));
4186
-        }, 1000);
4187
-
4188
-        if(RecordAllCalls || CallRecordingPolicy == "enabled") {
4189
-            StartRecording(lineObj.LineNumber);
4190
-        }
4191
-
4192
-        $("#line-"+ lineObj.LineNumber +"-progress").hide();
4193
-        $("#line-"+ lineObj.LineNumber +"-VideoCall").show();
4194
-        $("#line-"+ lineObj.LineNumber +"-ActiveCall").show();
4195
-
4196
-        $("#line-"+ lineObj.LineNumber +"-btn-Conference").hide(); // Cannot conference a Video Call (Yet...)
4197
-        $("#line-"+ lineObj.LineNumber +"-btn-CancelConference").hide();
4198
-        $("#line-"+ lineObj.LineNumber +"-Conference").hide();
4199
-
4200
-        $("#line-"+ lineObj.LineNumber +"-btn-Transfer").hide(); // Cannot transfer a Video Call (Yet...)
4201
-        $("#line-"+ lineObj.LineNumber +"-btn-CancelTransfer").hide();
4202
-        $("#line-"+ lineObj.LineNumber +"-Transfer").hide();
4203
-
4204
-        // Default to use Camera
4205
-        $("#line-"+ lineObj.LineNumber +"-src-camera").prop("disabled", true);
4206
-        $("#line-"+ lineObj.LineNumber +"-src-canvas").prop("disabled", false);
4207
-        $("#line-"+ lineObj.LineNumber +"-src-desktop").prop("disabled", false);
4208
-        $("#line-"+ lineObj.LineNumber +"-src-video").prop("disabled", false);
4209
-
4210
-        updateLineScroll(lineObj.LineNumber);
4211
-
4212
-        // Start Audio Monitoring
4213
-        lineObj.LocalSoundMeter = StartLocalAudioMediaMonitoring(lineObj.LineNumber, session);
4214
-        lineObj.RemoteSoundMeter = StartRemoteAudioMediaMonitoring(lineObj.LineNumber, session);
4215
-
4216
-        $(MessageObjId).html(lang.call_in_progress);
4217
-
4218
-        if(StartVideoFullScreen) ExpandVideoArea(lineObj.LineNumber);
4219
-
4220
-        // Custom Web hook
4221
-        if(typeof web_hook_on_modify !== 'undefined') web_hook_on_modify("accepted", session);
4222
-    });
4223
-    session.on('rejected', function (response, cause) {
4224
-        // Should only apply before answer
4225
-        $(MessageObjId).html(lang.call_rejected +": "+ cause);
4226
-        console.log("Call rejected: "+ cause);
4227
-        teardownSession(lineObj, response.status_code, response.reason_phrase);
4228
-    });
4229
-    session.on('failed', function (response, cause) {
4230
-        $(MessageObjId).html(lang.call_failed +": "+ cause);
4231
-        console.log("Call failed: "+ cause);
4232
-        teardownSession(lineObj, 0, "call failed");
4233
-    });
4234
-    session.on('cancel', function () {
4235
-        $(MessageObjId).html(lang.call_cancelled);
4236
-        console.log("Call Cancelled");
4237
-        teardownSession(lineObj, 0, "Cancelled by caller");
4238
-    });
4239
-    // referRequested
4240
-    // replaced
4241
-    session.on('bye', function () {
4242
-        $(MessageObjId).html(lang.call_ended);
4243
-        console.log("Call ended, bye!");
4244
-        teardownSession(lineObj, 16, "Normal Call clearing");
4245
-    });
4246
-    session.on('terminated', function (message, cause) {
4247
-        $(MessageObjId).html(lang.call_ended);
4248
-        console.log("Session terminated");
4249
-        teardownSession(lineObj, 16, "Normal Call clearing");
4250
-    });
4251
-    session.on('reinvite', function (session) {
4252
-        console.log("Session reinvited!");
4253
-    });
4254
-    // dtmf
4255
-    session.on('directionChanged', function() {
4256
-        var direction = session.sessionDescriptionHandler.getDirection();
4257
-        console.log("Direction Change: ", direction);
4258
-
4259
-        // Custom Web hook
4260
-        if(typeof web_hook_on_modify !== 'undefined') web_hook_on_modify("directionChanged", session);
4261
-    });
4262
-
4263
-    $("#line-" + lineObj.LineNumber + "-btn-settings").removeAttr('disabled');
4264
-    $("#line-" + lineObj.LineNumber + "-btn-audioCall").prop('disabled','disabled');
4265
-    $("#line-" + lineObj.LineNumber + "-btn-videoCall").prop('disabled','disabled');
4266
-    $("#line-" + lineObj.LineNumber + "-btn-search").removeAttr('disabled');
4267
-    $("#line-" + lineObj.LineNumber + "-btn-remove").prop('disabled','disabled');
4268
-
4269
-    $("#line-" + lineObj.LineNumber + "-progress").show();
4270
-    $("#line-" + lineObj.LineNumber + "-msg").show();
4271
-    
4272
-    updateLineScroll(lineObj.LineNumber);
4273
-
4274
-    UpdateUI();
4275
-}
4276
-function teardownSession(lineObj, reasonCode, reasonText) {
4277
-    if(lineObj == null || lineObj.SipSession == null) return;
4278
-
4279
-    var session = lineObj.SipSession;
4280
-    if(session.data.teardownComplete == true) return;
4281
-    session.data.teardownComplete = true; // Run this code only once
4282
-
4283
-    session.data.reasonCode = reasonCode
4284
-    session.data.reasonText = reasonText
4285
-
4286
-    // Call UI
4287
-    $.jeegoopopup.close();
4288
-
4289
-    // End any child calls
4290
-    if(session.data.childsession){
4291
-        try{
4292
-            if(session.data.childsession.status == SIP.Session.C.STATUS_CONFIRMED){
4293
-                session.data.childsession.bye();
4294
-            } 
4295
-            else{
4296
-                session.data.childsession.cancel();
4297
-            }
4298
-        } catch(e){}
4299
-    }
4300
-    session.data.childsession = null;
4301
-
4302
-    // Mixed Tracks
4303
-    if(session.data.AudioSourceTrack && session.data.AudioSourceTrack.kind == "audio"){
4304
-        session.data.AudioSourceTrack.stop();
4305
-        session.data.AudioSourceTrack = null;
4306
-    }
4307
-    // Stop any Early Media
4308
-    if(session.data.earlyMedia){
4309
-        session.data.earlyMedia.pause();
4310
-        session.data.earlyMedia.removeAttribute('src');
4311
-        session.data.earlyMedia.load();
4312
-        session.data.earlyMedia = null;
4313
-    }
4314
-
4315
-    // Stop Recording if we are
4316
-    StopRecording(lineObj.LineNumber,true);
4317
-
4318
-    // Audio Meters
4319
-    if(lineObj.LocalSoundMeter != null){
4320
-        lineObj.LocalSoundMeter.stop();
4321
-        lineObj.LocalSoundMeter = null;
4322
-    }
4323
-    if(lineObj.RemoteSoundMeter != null){
4324
-        lineObj.RemoteSoundMeter.stop();
4325
-        lineObj.RemoteSoundMeter = null;
4326
-    }
4327
-
4328
-    // End timers
4329
-    window.clearInterval(session.data.videoResampleInterval);
4330
-    window.clearInterval(session.data.callTimer);
4331
-
4332
-    // Add to stream
4333
-    AddCallMessage(lineObj.BuddyObj.identity, session, reasonCode, reasonText);
4334
-
4335
-    // Close up the UI
4336
-    window.setTimeout(function () {
4337
-        RemoveLine(lineObj);
4338
-    }, 1000);
4339
-
4340
-    UpdateBuddyList();
4341
-    UpdateUI();
4342
-
4343
-    // Custom Web hook
4344
-    if(typeof web_hook_on_terminate !== 'undefined') web_hook_on_terminate(session);
4345
-}
4346
-
4347
-// Mic and Speaker Levels
4348
-// ======================
4349
-function StartRemoteAudioMediaMonitoring(lineNum, session) {
4350
-    console.log("Creating RemoteAudio AudioContext on Line:" + lineNum);
4351
-
4352
-    // Create local SoundMeter
4353
-    var soundMeter = new SoundMeter(session.id, lineNum);
4354
-    if(soundMeter == null){
4355
-        console.warn("AudioContext() RemoteAudio not available... it fine.");
4356
-        return null;
4357
-    }
4358
-
4359
-    // Ready the getStats request
4360
-    var remoteAudioStream = new MediaStream();
4361
-    var audioReceiver = null;
4362
-    var pc = session.sessionDescriptionHandler.peerConnection;
4363
-    pc.getReceivers().forEach(function (RTCRtpReceiver) {
4364
-        if(RTCRtpReceiver.track && RTCRtpReceiver.track.kind == "audio"){
4365
-            if(audioReceiver == null) {
4366
-                remoteAudioStream.addTrack(RTCRtpReceiver.track);
4367
-                audioReceiver = RTCRtpReceiver;
4368
-            }
4369
-            else {
4370
-                console.log("Found another Track, but audioReceiver not null");
4371
-                console.log(RTCRtpReceiver);
4372
-                console.log(RTCRtpReceiver.track);
4373
-            }
4374
-        }
4375
-    });
4376
-
4377
-    // Setup Charts
4378
-    var maxDataLength = 100;
4379
-    soundMeter.startTime = Date.now();
4380
-    Chart.defaults.global.defaultFontSize = 12;
4381
-
4382
-    var ChatHistoryOptions = { 
4383
-        responsive: false,
4384
-        maintainAspectRatio: false,
4385
-        devicePixelRatio: 1,
4386
-        animation: false,
4387
-        scales: {
4388
-            yAxes: [{
4389
-                ticks: { beginAtZero: true } //, min: 0, max: 100
4390
-            }]
4391
-        }, 
4392
-    }
4393
-
4394
-    // Receive Kilobits per second
4395
-    soundMeter.ReceiveBitRateChart = new Chart($("#line-"+ lineNum +"-AudioReceiveBitRate"), {
4396
-        type: 'line',
4397
-        data: {
4398
-            labels: MakeDataArray("", maxDataLength),
4399
-            datasets: [{
4400
-                label: lang.receive_kilobits_per_second,
4401
-                data: MakeDataArray(0, maxDataLength),
4402
-                backgroundColor: 'rgba(168, 0, 0, 0.5)',
4403
-                borderColor: 'rgba(168, 0, 0, 1)',
4404
-                borderWidth: 1,
4405
-                pointRadius: 1
4406
-            }]
4407
-        },
4408
-        options: ChatHistoryOptions
4409
-    });
4410
-    soundMeter.ReceiveBitRateChart.lastValueBytesReceived = 0;
4411
-    soundMeter.ReceiveBitRateChart.lastValueTimestamp = 0;
4412
-
4413
-    // Receive Packets per second
4414
-    soundMeter.ReceivePacketRateChart = new Chart($("#line-"+ lineNum +"-AudioReceivePacketRate"), {
4415
-        type: 'line',
4416
-        data: {
4417
-            labels: MakeDataArray("", maxDataLength),
4418
-            datasets: [{
4419
-                label: lang.receive_packets_per_second,
4420
-                data: MakeDataArray(0, maxDataLength),
4421
-                backgroundColor: 'rgba(168, 0, 0, 0.5)',
4422
-                borderColor: 'rgba(168, 0, 0, 1)',
4423
-                borderWidth: 1,
4424
-                pointRadius: 1
4425
-            }]
4426
-        },
4427
-        options: ChatHistoryOptions
4428
-    });
4429
-    soundMeter.ReceivePacketRateChart.lastValuePacketReceived = 0;
4430
-    soundMeter.ReceivePacketRateChart.lastValueTimestamp = 0;
4431
-
4432
-    // Receive Packet Loss
4433
-    soundMeter.ReceivePacketLossChart = new Chart($("#line-"+ lineNum +"-AudioReceivePacketLoss"), {
4434
-        type: 'line',
4435
-        data: {
4436
-            labels: MakeDataArray("", maxDataLength),
4437
-            datasets: [{
4438
-                label: lang.receive_packet_loss,
4439
-                data: MakeDataArray(0, maxDataLength),
4440
-                backgroundColor: 'rgba(168, 99, 0, 0.5)',
4441
-                borderColor: 'rgba(168, 99, 0, 1)',
4442
-                borderWidth: 1,
4443
-                pointRadius: 1
4444
-            }]
4445
-        },
4446
-        options: ChatHistoryOptions
4447
-    });
4448
-    soundMeter.ReceivePacketLossChart.lastValuePacketLoss = 0;
4449
-    soundMeter.ReceivePacketLossChart.lastValueTimestamp = 0;
4450
-
4451
-    // Receive Jitter
4452
-    soundMeter.ReceiveJitterChart = new Chart($("#line-"+ lineNum +"-AudioReceiveJitter"), {
4453
-        type: 'line',
4454
-        data: {
4455
-            labels: MakeDataArray("", maxDataLength),
4456
-            datasets: [{
4457
-                label: lang.receive_jitter,
4458
-                data: MakeDataArray(0, maxDataLength),
4459
-                backgroundColor: 'rgba(0, 38, 168, 0.5)',
4460
-                borderColor: 'rgba(0, 38, 168, 1)',
4461
-                borderWidth: 1,
4462
-                pointRadius: 1
4463
-            }]
4464
-        },
4465
-        options: ChatHistoryOptions
4466
-    });
4467
-
4468
-    // Receive Audio Levels
4469
-    soundMeter.ReceiveLevelsChart = new Chart($("#line-"+ lineNum +"-AudioReceiveLevels"), {
4470
-        type: 'line',
4471
-        data: {
4472
-            labels: MakeDataArray("", maxDataLength),
4473
-            datasets: [{
4474
-                label: lang.receive_audio_levels,
4475
-                data: MakeDataArray(0, maxDataLength),
4476
-                backgroundColor: 'rgba(140, 0, 168, 0.5)',
4477
-                borderColor: 'rgba(140, 0, 168, 1)',
4478
-                borderWidth: 1,
4479
-                pointRadius: 1
4480
-            }]
4481
-        },
4482
-        options: ChatHistoryOptions
4483
-    });
4484
-
4485
-    // Connect to Source
4486
-    soundMeter.connectToSource(remoteAudioStream, function (e) {
4487
-        if (e != null) return;
4488
-
4489
-        // Create remote SoundMeter
4490
-        console.log("SoundMeter for RemoteAudio Connected, displaying levels for Line: " + lineNum);
4491
-        soundMeter.levelsInterval = window.setInterval(function () {
4492
-            // Calculate Levels
4493
-            //value="0" max="1" high="0.25" (this seems low... )
4494
-            var level = soundMeter.instant * 4.0;
4495
-            if (level > 1) level = 1;
4496
-            var instPercent = level * 100;
4497
-
4498
-            $("#line-" + lineNum + "-Speaker").css("height", instPercent.toFixed(2) +"%");
4499
-        }, 50);
4500
-        soundMeter.networkInterval = window.setInterval(function (){
4501
-            // Calculate Network Conditions
4502
-            if(audioReceiver != null) {
4503
-                audioReceiver.getStats().then(function(stats) {
4504
-                    stats.forEach(function(report){
4505
-
4506
-                        var theMoment = utcDateNow();
4507
-                        var ReceiveBitRateChart = soundMeter.ReceiveBitRateChart;
4508
-                        var ReceivePacketRateChart = soundMeter.ReceivePacketRateChart;
4509
-                        var ReceivePacketLossChart = soundMeter.ReceivePacketLossChart;
4510
-                        var ReceiveJitterChart = soundMeter.ReceiveJitterChart;
4511
-                        var ReceiveLevelsChart = soundMeter.ReceiveLevelsChart;
4512
-                        var elapsedSec = Math.floor((Date.now() - soundMeter.startTime)/1000);
4513
-
4514
-                        if(report.type == "inbound-rtp"){
4515
-
4516
-                            if(ReceiveBitRateChart.lastValueTimestamp == 0) {
4517
-                                ReceiveBitRateChart.lastValueTimestamp = report.timestamp;
4518
-                                ReceiveBitRateChart.lastValueBytesReceived = report.bytesReceived;
4519
-
4520
-                                ReceivePacketRateChart.lastValueTimestamp = report.timestamp;
4521
-                                ReceivePacketRateChart.lastValuePacketReceived = report.packetsReceived;
4522
-
4523
-                                ReceivePacketLossChart.lastValueTimestamp = report.timestamp;
4524
-                                ReceivePacketLossChart.lastValuePacketLoss = report.packetsLost;
4525
-
4526
-                                return;
4527
-                            }
4528
-                            // Receive Kilobits Per second
4529
-                            var kbitsPerSec = (8 * (report.bytesReceived - ReceiveBitRateChart.lastValueBytesReceived))/1000;
4530
-
4531
-                            ReceiveBitRateChart.lastValueTimestamp = report.timestamp;
4532
-                            ReceiveBitRateChart.lastValueBytesReceived = report.bytesReceived;
4533
-
4534
-                            soundMeter.ReceiveBitRate.push({ value: kbitsPerSec, timestamp : theMoment});
4535
-                            ReceiveBitRateChart.data.datasets[0].data.push(kbitsPerSec);
4536
-                            ReceiveBitRateChart.data.labels.push("");
4537
-                            if(ReceiveBitRateChart.data.datasets[0].data.length > maxDataLength) {
4538
-                                ReceiveBitRateChart.data.datasets[0].data.splice(0,1);
4539
-                                ReceiveBitRateChart.data.labels.splice(0,1);
4540
-                            }
4541
-                            ReceiveBitRateChart.update();
4542
-
4543
-                            // Receive Packets Per Second
4544
-                            var PacketsPerSec = (report.packetsReceived - ReceivePacketRateChart.lastValuePacketReceived);
4545
-
4546
-                            ReceivePacketRateChart.lastValueTimestamp = report.timestamp;
4547
-                            ReceivePacketRateChart.lastValuePacketReceived = report.packetsReceived;
4548
-
4549
-                            soundMeter.ReceivePacketRate.push({ value: PacketsPerSec, timestamp : theMoment});
4550
-                            ReceivePacketRateChart.data.datasets[0].data.push(PacketsPerSec);
4551
-                            ReceivePacketRateChart.data.labels.push("");
4552
-                            if(ReceivePacketRateChart.data.datasets[0].data.length > maxDataLength) {
4553
-                                ReceivePacketRateChart.data.datasets[0].data.splice(0,1);
4554
-                                ReceivePacketRateChart.data.labels.splice(0,1);
4555
-                            }
4556
-                            ReceivePacketRateChart.update();
4557
-
4558
-                            // Receive Packet Loss
4559
-                            var PacketsLost = (report.packetsLost - ReceivePacketLossChart.lastValuePacketLoss);
4560
-
4561
-                            ReceivePacketLossChart.lastValueTimestamp = report.timestamp;
4562
-                            ReceivePacketLossChart.lastValuePacketLoss = report.packetsLost;
4563
-
4564
-                            soundMeter.ReceivePacketLoss.push({ value: PacketsLost, timestamp : theMoment});
4565
-                            ReceivePacketLossChart.data.datasets[0].data.push(PacketsLost);
4566
-                            ReceivePacketLossChart.data.labels.push("");
4567
-                            if(ReceivePacketLossChart.data.datasets[0].data.length > maxDataLength) {
4568
-                                ReceivePacketLossChart.data.datasets[0].data.splice(0,1);
4569
-                                ReceivePacketLossChart.data.labels.splice(0,1);
4570
-                            }
4571
-                            ReceivePacketLossChart.update();
4572
-
4573
-                            // Receive Jitter
4574
-                            soundMeter.ReceiveJitter.push({ value: report.jitter, timestamp : theMoment});
4575
-                            ReceiveJitterChart.data.datasets[0].data.push(report.jitter);
4576
-                            ReceiveJitterChart.data.labels.push("");
4577
-                            if(ReceiveJitterChart.data.datasets[0].data.length > maxDataLength) {
4578
-                                ReceiveJitterChart.data.datasets[0].data.splice(0,1);
4579
-                                ReceiveJitterChart.data.labels.splice(0,1);
4580
-                            }
4581
-                            ReceiveJitterChart.update();
4582
-                        }
4583
-                        if(report.type == "track") {
4584
-
4585
-                            // Receive Audio Levels
4586
-                            var levelPercent = (report.audioLevel * 100);
4587
-                            soundMeter.ReceiveLevels.push({ value: levelPercent, timestamp : theMoment});
4588
-                            ReceiveLevelsChart.data.datasets[0].data.push(levelPercent);
4589
-                            ReceiveLevelsChart.data.labels.push("");
4590
-                            if(ReceiveLevelsChart.data.datasets[0].data.length > maxDataLength)
4591
-                            {
4592
-                                ReceiveLevelsChart.data.datasets[0].data.splice(0,1);
4593
-                                ReceiveLevelsChart.data.labels.splice(0,1);
4594
-                            }
4595
-                            ReceiveLevelsChart.update();
4596
-                        }
4597
-                    });
4598
-                });
4599
-            }
4600
-        } ,1000);
4601
-    });
4602
-
4603
-    return soundMeter;
4604
-}
4605
-function StartLocalAudioMediaMonitoring(lineNum, session) {
4606
-    console.log("Creating LocalAudio AudioContext on line " + lineNum);
4607
-
4608
-    // Create local SoundMeter
4609
-    var soundMeter = new SoundMeter(session.id, lineNum);
4610
-    if(soundMeter == null){
4611
-        console.warn("AudioContext() LocalAudio not available... its fine.")
4612
-        return null;
4613
-    }
4614
-
4615
-    // Ready the getStats request
4616
-    var localAudioStream = new MediaStream();
4617
-    var audioSender = null;
4618
-    var pc = session.sessionDescriptionHandler.peerConnection;
4619
-    pc.getSenders().forEach(function (RTCRtpSender) {
4620
-        if(RTCRtpSender.track && RTCRtpSender.track.kind == "audio"){
4621
-            if(audioSender == null){
4622
-                console.log("Adding Track to Monitor: ", RTCRtpSender.track.label);
4623
-                localAudioStream.addTrack(RTCRtpSender.track);
4624
-                audioSender = RTCRtpSender;
4625
-            }
4626
-            else {
4627
-                console.log("Found another Track, but audioSender not null");
4628
-                console.log(RTCRtpSender);
4629
-                console.log(RTCRtpSender.track);
4630
-            }
4631
-        }
4632
-    });
4633
-
4634
-    // Setup Charts
4635
-    var maxDataLength = 100;
4636
-    soundMeter.startTime = Date.now();
4637
-    Chart.defaults.global.defaultFontSize = 12;
4638
-    var ChatHistoryOptions = { 
4639
-        responsive: false,    
4640
-        maintainAspectRatio: false,
4641
-        devicePixelRatio: 1,
4642
-        animation: false,
4643
-        scales: {
4644
-            yAxes: [{
4645
-                ticks: { beginAtZero: true }
4646
-            }]
4647
-        }, 
4648
-    }
4649
-
4650
-    // Send Kilobits Per Second
4651
-    soundMeter.SendBitRateChart = new Chart($("#line-"+ lineNum +"-AudioSendBitRate"), {
4652
-        type: 'line',
4653
-        data: {
4654
-            labels: MakeDataArray("", maxDataLength),
4655
-            datasets: [{
4656
-                label: lang.send_kilobits_per_second,
4657
-                data: MakeDataArray(0, maxDataLength),
4658
-                backgroundColor: 'rgba(0, 121, 19, 0.5)',
4659
-                borderColor: 'rgba(0, 121, 19, 1)',
4660
-                borderWidth: 1,
4661
-                pointRadius: 1
4662
-            }]
4663
-        },
4664
-        options: ChatHistoryOptions
4665
-    });
4666
-    soundMeter.SendBitRateChart.lastValueBytesSent = 0;
4667
-    soundMeter.SendBitRateChart.lastValueTimestamp = 0;
4668
-
4669
-    // Send Packets Per Second
4670
-    soundMeter.SendPacketRateChart = new Chart($("#line-"+ lineNum +"-AudioSendPacketRate"), {
4671
-        type: 'line',
4672
-        data: {
4673
-            labels: MakeDataArray("", maxDataLength),
4674
-            datasets: [{
4675
-                label: lang.send_packets_per_second,
4676
-                data: MakeDataArray(0, maxDataLength),
4677
-                backgroundColor: 'rgba(0, 121, 19, 0.5)',
4678
-                borderColor: 'rgba(0, 121, 19, 1)',
4679
-                borderWidth: 1,
4680
-                pointRadius: 1
4681
-            }]
4682
-        },
4683
-        options: ChatHistoryOptions
4684
-    });
4685
-    soundMeter.SendPacketRateChart.lastValuePacketSent = 0;
4686
-    soundMeter.SendPacketRateChart.lastValueTimestamp = 0;    
4687
-
4688
-    // Connect to Source
4689
-    soundMeter.connectToSource(localAudioStream, function (e) {
4690
-        if (e != null) return;
4691
-
4692
-        console.log("SoundMeter for LocalAudio Connected, displaying levels for Line: " + lineNum);
4693
-        soundMeter.levelsInterval = window.setInterval(function () {
4694
-            // Calculate Levels
4695
-            //value="0" max="1" high="0.25" (this seems low... )
4696
-            var level = soundMeter.instant * 4.0;
4697
-            if (level > 1) level = 1;
4698
-            var instPercent = level * 100;
4699
-            $("#line-" + lineNum + "-Mic").css("height", instPercent.toFixed(2) +"%");
4700
-        }, 50);
4701
-        soundMeter.networkInterval = window.setInterval(function (){
4702
-            // Calculate Network Conditions
4703
-            // Sending Audio Track
4704
-            if(audioSender != null) {
4705
-                audioSender.getStats().then(function(stats) {
4706
-                    stats.forEach(function(report){
4707
-
4708
-                        var theMoment = utcDateNow();
4709
-                        var SendBitRateChart = soundMeter.SendBitRateChart;
4710
-                        var SendPacketRateChart = soundMeter.SendPacketRateChart;
4711
-                        var elapsedSec = Math.floor((Date.now() - soundMeter.startTime)/1000);
4712
-
4713
-                        if(report.type == "outbound-rtp"){
4714
-                            if(SendBitRateChart.lastValueTimestamp == 0) {
4715
-                                SendBitRateChart.lastValueTimestamp = report.timestamp;
4716
-                                SendBitRateChart.lastValueBytesSent = report.bytesSent;
4717
-
4718
-                                SendPacketRateChart.lastValueTimestamp = report.timestamp;
4719
-                                SendPacketRateChart.lastValuePacketSent = report.packetsSent;
4720
-                                return;
4721
-                            }
4722
-
4723
-                            // Send Kilobits Per second
4724
-                            var kbitsPerSec = (8 * (report.bytesSent - SendBitRateChart.lastValueBytesSent))/1000;
4725
-
4726
-                            SendBitRateChart.lastValueTimestamp = report.timestamp;
4727
-                            SendBitRateChart.lastValueBytesSent = report.bytesSent;
4728
-
4729
-                            soundMeter.SendBitRate.push({ value: kbitsPerSec, timestamp : theMoment});
4730
-                            SendBitRateChart.data.datasets[0].data.push(kbitsPerSec);
4731
-                            SendBitRateChart.data.labels.push("");
4732
-                            if(SendBitRateChart.data.datasets[0].data.length > maxDataLength) {
4733
-                                SendBitRateChart.data.datasets[0].data.splice(0,1);
4734
-                                SendBitRateChart.data.labels.splice(0,1);
4735
-                            }
4736
-                            SendBitRateChart.update();
4737
-
4738
-                            // Send Packets Per Second
4739
-                            var PacketsPerSec = report.packetsSent - SendPacketRateChart.lastValuePacketSent;
4740
-
4741
-                            SendPacketRateChart.lastValueTimestamp = report.timestamp;
4742
-                            SendPacketRateChart.lastValuePacketSent = report.packetsSent;
4743
-
4744
-                            soundMeter.SendPacketRate.push({ value: PacketsPerSec, timestamp : theMoment});
4745
-                            SendPacketRateChart.data.datasets[0].data.push(PacketsPerSec);
4746
-                            SendPacketRateChart.data.labels.push("");
4747
-                            if(SendPacketRateChart.data.datasets[0].data.length > maxDataLength) {
4748
-                                SendPacketRateChart.data.datasets[0].data.splice(0,1);
4749
-                                SendPacketRateChart.data.labels.splice(0,1);
4750
-                            }
4751
-                            SendPacketRateChart.update();
4752
-                        }
4753
-                        if(report.type == "track") {
4754
-                            // Bug/security consern... this seems always to report "0"
4755
-                            // 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).
4756
-                            // console.log("Audio Sender: " + report.audioLevel);
4757
-                        }
4758
-                    });
4759
-                });
4760
-            }
4761
-        } ,1000);
4762
-    });
4763
-
4764
-    return soundMeter;
4765
-}
4766
-
4767
-// Sounds Meter Class
4768
-// ==================
4769
-class SoundMeter {
4770
-    constructor(sessionId, lineNum) {
4771
-        var audioContext = null;
4772
-        try {
4773
-            window.AudioContext = window.AudioContext || window.webkitAudioContext;
4774
-            audioContext = new AudioContext();
4775
-        }
4776
-        catch(e) {
4777
-            console.warn("AudioContext() LocalAudio not available... its fine.");
4778
-        }
4779
-        if (audioContext == null) return null;
4780
-
4781
-        this.lineNum = lineNum;
4782
-        this.sessionId = sessionId;
4783
-        this.levelsInterval = null;
4784
-        this.networkInterval = null;
4785
-        this.startTime = 0;
4786
-        this.ReceiveBitRateChart = null;
4787
-        this.ReceiveBitRate = [];
4788
-        this.ReceivePacketRateChart = null;
4789
-        this.ReceivePacketRate = [];
4790
-        this.ReceivePacketLossChart = null;
4791
-        this.ReceivePacketLoss = [];
4792
-        this.ReceiveJitterChart = null;
4793
-        this.ReceiveJitter = [];
4794
-        this.ReceiveLevelsChart = null;
4795
-        this.ReceiveLevels = [];
4796
-        this.SendBitRateChart = null;
4797
-        this.SendBitRate = [];
4798
-        this.SendPacketRateChart = null;
4799
-        this.SendPacketRate = [];
4800
-        this.context = audioContext;
4801
-        this.instant = 0.0;
4802
-        this.script = audioContext.createScriptProcessor(2048, 1, 1);
4803
-        const that = this;
4804
-        this.script.onaudioprocess = function (event) {
4805
-            const input = event.inputBuffer.getChannelData(0);
4806
-            let i;
4807
-            let sum = 0.0;
4808
-            for (i = 0; i < input.length; ++i) {
4809
-                sum += input[i] * input[i];
4810
-            }
4811
-            that.instant = Math.sqrt(sum / input.length);
4812
-        }
4813
-    }
4814
-    connectToSource(stream, callback) {
4815
-        console.log("SoundMeter connecting...");
4816
-        try {
4817
-            this.mic = this.context.createMediaStreamSource(stream);
4818
-            this.mic.connect(this.script);
4819
-            // necessary to make sample run, but should not be.
4820
-            this.script.connect(this.context.destination);
4821
-            callback(null);
4822
-        }
4823
-        catch(e) {
4824
-            console.error(e); // Probably not audio track
4825
-            callback(e);
4826
-        }
4827
-    }
4828
-    stop() {
4829
-        console.log("Disconnecting SoundMeter...");
4830
-        try {
4831
-            window.clearInterval(this.levelsInterval);
4832
-            this.levelsInterval = null;
4833
-        }
4834
-        catch(e) { }
4835
-        try {
4836
-            window.clearInterval(this.networkInterval);
4837
-            this.networkInterval = null;
4838
-        }
4839
-        catch(e) { }
4840
-        this.mic.disconnect();
4841
-        this.script.disconnect();
4842
-        this.mic = null;
4843
-        this.script = null;
4844
-        try {
4845
-            this.context.close();
4846
-        }
4847
-        catch(e) { }
4848
-        this.context = null;
4849
-
4850
-        // Save to IndexDb
4851
-        var lineObj = FindLineByNumber(this.lineNum);
4852
-        var QosData = {
4853
-            ReceiveBitRate: this.ReceiveBitRate,
4854
-            ReceivePacketRate: this.ReceivePacketRate,
4855
-            ReceivePacketLoss: this.ReceivePacketLoss,
4856
-            ReceiveJitter: this.ReceiveJitter,
4857
-            ReceiveLevels: this.ReceiveLevels,
4858
-            SendBitRate: this.SendBitRate,
4859
-            SendPacketRate: this.SendPacketRate,
4860
-        }
4861
-        SaveQosData(QosData, this.sessionId, lineObj.BuddyObj.identity);
4862
-    }
4863
-}
4864
-function MeterSettingsOutput(audioStream, objectId, direction, interval){
4865
-    var soundMeter = new SoundMeter(null, null);
4866
-    soundMeter.startTime = Date.now();
4867
-    soundMeter.connectToSource(audioStream, function (e) {
4868
-        if (e != null) return;
4869
-
4870
-        console.log("SoundMeter Connected, displaying levels to:"+ objectId);
4871
-        soundMeter.levelsInterval = window.setInterval(function () {
4872
-            // Calculate Levels
4873
-            //value="0" max="1" high="0.25" (this seems low... )
4874
-            var level = soundMeter.instant * 4.0;
4875
-            if (level > 1) level = 1;
4876
-            var instPercent = level * 100;
4877
-
4878
-            $("#"+objectId).css(direction, instPercent.toFixed(2) +"%"); // Settings_MicrophoneOutput "width" 50
4879
-        }, interval);
4880
-    });
4881
-
4882
-    return soundMeter;
4883
-}
4884
-
4885
-// QOS
4886
-// ===
4887
-function SaveQosData(QosData, sessionId, buddy){
4888
-    var indexedDB = window.indexedDB;
4889
-    var request = indexedDB.open("CallQosData");
4890
-    request.onerror = function(event) {
4891
-        console.error("IndexDB Request Error:", event);
4892
-    }
4893
-    request.onupgradeneeded = function(event) {
4894
-        console.warn("Upgrade Required for IndexDB... probably because of first time use.");
4895
-        var IDB = event.target.result;
4896
-
4897
-        // Create Object Store
4898
-        if(IDB.objectStoreNames.contains("CallQos") == false){
4899
-            var objectStore = IDB.createObjectStore("CallQos", { keyPath: "uID" });
4900
-            objectStore.createIndex("sessionid", "sessionid", { unique: false });
4901
-            objectStore.createIndex("buddy", "buddy", { unique: false });
4902
-            objectStore.createIndex("QosData", "QosData", { unique: false });
4903
-        }
4904
-        else {
4905
-            console.warn("IndexDB requested upgrade, but object store was in place");
4906
-        }
4907
-    }
4908
-    request.onsuccess = function(event) {
4909
-        console.log("IndexDB connected to CallQosData");
4910
-
4911
-        var IDB = event.target.result;
4912
-        if(IDB.objectStoreNames.contains("CallQos") == false){
4913
-            console.warn("IndexDB CallQosData.CallQos does not exists");
4914
-            return;
4915
-        }
4916
-        IDB.onerror = function(event) {
4917
-            console.error("IndexDB Error:", event);
4918
-        }
4919
-
4920
-        // Prepare data to write
4921
-        var data = {
4922
-            uID: uID(),
4923
-            sessionid: sessionId,
4924
-            buddy: buddy,
4925
-            QosData: QosData
4926
-        }
4927
-        // Commit Transaction
4928
-        var transaction = IDB.transaction(["CallQos"], "readwrite");
4929
-        var objectStoreAdd = transaction.objectStore("CallQos").add(data);
4930
-        objectStoreAdd.onsuccess = function(event) {
4931
-            console.log("Call CallQos Sucess: ", sessionId);
4932
-        }
4933
-    }
4934
-}
4935
-function DisplayQosData(sessionId){
4936
-    var indexedDB = window.indexedDB;
4937
-    var request = indexedDB.open("CallQosData");
4938
-    request.onerror = function(event) {
4939
-        console.error("IndexDB Request Error:", event);
4940
-    }
4941
-    request.onupgradeneeded = function(event) {
4942
-        console.warn("Upgrade Required for IndexDB... probably because of first time use.");
4943
-    }
4944
-    request.onsuccess = function(event) {
4945
-        console.log("IndexDB connected to CallQosData");
4946
-
4947
-        var IDB = event.target.result;
4948
-        if(IDB.objectStoreNames.contains("CallQos") == false){
4949
-            console.warn("IndexDB CallQosData.CallQos does not exists");
4950
-            return;
4951
-        } 
4952
-
4953
-        var transaction = IDB.transaction(["CallQos"]);
4954
-        var objectStoreGet = transaction.objectStore("CallQos").index('sessionid').getAll(sessionId);
4955
-        objectStoreGet.onerror = function(event) {
4956
-            console.error("IndexDB Get Error:", event);
4957
-        }
4958
-        objectStoreGet.onsuccess = function(event) {
4959
-            if(event.target.result && event.target.result.length == 2){
4960
-                // This is the correct data
4961
-
4962
-                var QosData0 = event.target.result[0].QosData;
4963
-                // ReceiveBitRate: (8) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
4964
-                // ReceiveJitter: (8) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
4965
-                // ReceiveLevels: (9) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
4966
-                // ReceivePacketLoss: (8) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
4967
-                // ReceivePacketRate: (8) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
4968
-                // SendBitRate: []
4969
-                // SendPacketRate: []
4970
-                var QosData1 = event.target.result[1].QosData;
4971
-                // ReceiveBitRate: []
4972
-                // ReceiveJitter: []
4973
-                // ReceiveLevels: []
4974
-                // ReceivePacketLoss: []
4975
-                // ReceivePacketRate: []
4976
-                // SendBitRate: (9) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
4977
-                // SendPacketRate: (9) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
4978
-
4979
-                Chart.defaults.global.defaultFontSize = 12;
4980
-
4981
-                var ChatHistoryOptions = { 
4982
-                    responsive: true,
4983
-                    maintainAspectRatio: false,
4984
-                    animation: false,
4985
-                    scales: {
4986
-                        yAxes: [{
4987
-                            ticks: { beginAtZero: true } //, min: 0, max: 100
4988
-                        }],
4989
-                        xAxes: [{
4990
-                            display: false
4991
-                        }]
4992
-                    }, 
4993
-                }
4994
-
4995
-                // ReceiveBitRateChart
4996
-                var labelset = [];
4997
-                var dataset = [];
4998
-                var data = (QosData0.ReceiveBitRate.length > 0)? QosData0.ReceiveBitRate : QosData1.ReceiveBitRate;
4999
-                $.each(data, function(i,item){
5000
-                    labelset.push(moment.utc(item.timestamp.replace(" UTC", "")).local().format(DisplayDateFormat +" "+ DisplayTimeFormat));
5001
-                    dataset.push(item.value);
5002
-                });
5003
-                var ReceiveBitRateChart = new Chart($("#cdr-AudioReceiveBitRate"), {
5004
-                    type: 'line',
5005
-                    data: {
5006
-                        labels: labelset,
5007
-                        datasets: [{
5008
-                            label: lang.receive_kilobits_per_second,
5009
-                            data: dataset,
5010
-                            backgroundColor: 'rgba(168, 0, 0, 0.5)',
5011
-                            borderColor: 'rgba(168, 0, 0, 1)',
5012
-                            borderWidth: 1,
5013
-                            pointRadius: 1
5014
-                        }]
5015
-                    },
5016
-                    options: ChatHistoryOptions
5017
-                });
5018
-
5019
-                // ReceivePacketRateChart
5020
-                var labelset = [];
5021
-                var dataset = [];
5022
-                var data = (QosData0.ReceivePacketRate.length > 0)? QosData0.ReceivePacketRate : QosData1.ReceivePacketRate;
5023
-                $.each(data, function(i,item){
5024
-                    labelset.push(moment.utc(item.timestamp.replace(" UTC", "")).local().format(DisplayDateFormat +" "+ DisplayTimeFormat));
5025
-                    dataset.push(item.value);
5026
-                });
5027
-                var ReceivePacketRateChart = new Chart($("#cdr-AudioReceivePacketRate"), {
5028
-                    type: 'line',
5029
-                    data: {
5030
-                        labels: labelset,
5031
-                        datasets: [{
5032
-                            label: lang.receive_packets_per_second,
5033
-                            data: dataset,
5034
-                            backgroundColor: 'rgba(168, 0, 0, 0.5)',
5035
-                            borderColor: 'rgba(168, 0, 0, 1)',
5036
-                            borderWidth: 1,
5037
-                            pointRadius: 1
5038
-                        }]
5039
-                    },
5040
-                    options: ChatHistoryOptions
5041
-                });
5042
-
5043
-                // AudioReceivePacketLossChart
5044
-                var labelset = [];
5045
-                var dataset = [];
5046
-                var data = (QosData0.ReceivePacketLoss.length > 0)? QosData0.ReceivePacketLoss : QosData1.ReceivePacketLoss;
5047
-                $.each(data, function(i,item){
5048
-                    labelset.push(moment.utc(item.timestamp.replace(" UTC", "")).local().format(DisplayDateFormat +" "+ DisplayTimeFormat));
5049
-                    dataset.push(item.value);
5050
-                });
5051
-                var AudioReceivePacketLossChart = new Chart($("#cdr-AudioReceivePacketLoss"), {
5052
-                    type: 'line',
5053
-                    data: {
5054
-                        labels: labelset,
5055
-                        datasets: [{
5056
-                            label: lang.receive_packet_loss,
5057
-                            data: dataset,
5058
-                            backgroundColor: 'rgba(168, 99, 0, 0.5)',
5059
-                            borderColor: 'rgba(168, 99, 0, 1)',
5060
-                            borderWidth: 1,
5061
-                            pointRadius: 1
5062
-                        }]
5063
-                    },
5064
-                    options: ChatHistoryOptions
5065
-                });
5066
-
5067
-                // AudioReceiveJitterChart
5068
-                var labelset = [];
5069
-                var dataset = [];
5070
-                var data = (QosData0.ReceiveJitter.length > 0)? QosData0.ReceiveJitter : QosData1.ReceiveJitter;
5071
-                $.each(data, function(i,item){
5072
-                    labelset.push(moment.utc(item.timestamp.replace(" UTC", "")).local().format(DisplayDateFormat +" "+ DisplayTimeFormat));
5073
-                    dataset.push(item.value);
5074
-                });
5075
-                var AudioReceiveJitterChart = new Chart($("#cdr-AudioReceiveJitter"), {
5076
-                    type: 'line',
5077
-                    data: {
5078
-                        labels: labelset,
5079
-                        datasets: [{
5080
-                            label: lang.receive_jitter,
5081
-                            data: dataset,
5082
-                            backgroundColor: 'rgba(0, 38, 168, 0.5)',
5083
-                            borderColor: 'rgba(0, 38, 168, 1)',
5084
-                            borderWidth: 1,
5085
-                            pointRadius: 1
5086
-                        }]
5087
-                    },
5088
-                    options: ChatHistoryOptions
5089
-                });
5090
-              
5091
-                // AudioReceiveLevelsChart
5092
-                var labelset = [];
5093
-                var dataset = [];
5094
-                var data = (QosData0.ReceiveLevels.length > 0)? QosData0.ReceiveLevels : QosData1.ReceiveLevels;
5095
-                $.each(data, function(i,item){
5096
-                    labelset.push(moment.utc(item.timestamp.replace(" UTC", "")).local().format(DisplayDateFormat +" "+ DisplayTimeFormat));
5097
-                    dataset.push(item.value);
5098
-                });
5099
-                var AudioReceiveLevelsChart = new Chart($("#cdr-AudioReceiveLevels"), {
5100
-                    type: 'line',
5101
-                    data: {
5102
-                        labels: labelset,
5103
-                        datasets: [{
5104
-                            label: lang.receive_audio_levels,
5105
-                            data: dataset,
5106
-                            backgroundColor: 'rgba(140, 0, 168, 0.5)',
5107
-                            borderColor: 'rgba(140, 0, 168, 1)',
5108
-                            borderWidth: 1,
5109
-                            pointRadius: 1
5110
-                        }]
5111
-                    },
5112
-                    options: ChatHistoryOptions
5113
-                });
5114
-                 
5115
-                // SendPacketRateChart
5116
-                var labelset = [];
5117
-                var dataset = [];
5118
-                var data = (QosData0.SendPacketRate.length > 0)? QosData0.SendPacketRate : QosData1.SendPacketRate;
5119
-                $.each(data, function(i,item){
5120
-                    labelset.push(moment.utc(item.timestamp.replace(" UTC", "")).local().format(DisplayDateFormat +" "+ DisplayTimeFormat));
5121
-                    dataset.push(item.value);
5122
-                });
5123
-                var SendPacketRateChart = new Chart($("#cdr-AudioSendPacketRate"), {
5124
-                    type: 'line',
5125
-                    data: {
5126
-                        labels: labelset,
5127
-                        datasets: [{
5128
-                            label: lang.send_packets_per_second,
5129
-                            data: dataset,
5130
-                            backgroundColor: 'rgba(0, 121, 19, 0.5)',
5131
-                            borderColor: 'rgba(0, 121, 19, 1)',
5132
-                            borderWidth: 1,
5133
-                            pointRadius: 1
5134
-                        }]
5135
-                    },
5136
-                    options: ChatHistoryOptions
5137
-                });
5138
-
5139
-                // AudioSendBitRateChart
5140
-                var labelset = [];
5141
-                var dataset = [];
5142
-                var data = (QosData0.SendBitRate.length > 0)? QosData0.SendBitRate : QosData1.SendBitRate;
5143
-                $.each(data, function(i,item){
5144
-                    labelset.push(moment.utc(item.timestamp.replace(" UTC", "")).local().format(DisplayDateFormat +" "+ DisplayTimeFormat));
5145
-                    dataset.push(item.value);
5146
-                });
5147
-                var AudioSendBitRateChart = new Chart($("#cdr-AudioSendBitRate"), {
5148
-                    type: 'line',
5149
-                    data: {
5150
-                        labels: labelset,
5151
-                        datasets: [{
5152
-                            label: lang.send_kilobits_per_second,
5153
-                            data: dataset,
5154
-                            backgroundColor: 'rgba(0, 121, 19, 0.5)',
5155
-                            borderColor: 'rgba(0, 121, 19, 1)',
5156
-                            borderWidth: 1,
5157
-                            pointRadius: 1
5158
-                        }]
5159
-                    },
5160
-                    options: ChatHistoryOptions
5161
-                });
5162
-            } else {
5163
-                console.warn("Result not expected", event.target.result);
5164
-            }
5165
-        }
5166
-    }
5167
-}
5168
-function DeleteQosData(buddy){
5169
-    var indexedDB = window.indexedDB;
5170
-    var request = indexedDB.open("CallQosData");
5171
-    request.onerror = function(event) {
5172
-        console.error("IndexDB Request Error:", event);
5173
-    }
5174
-    request.onupgradeneeded = function(event) {
5175
-        console.warn("Upgrade Required for IndexDB... probably because of first time use.");
5176
-        // If this is the case, there will be no call recordings
5177
-    }
5178
-    request.onsuccess = function(event) {
5179
-        console.log("IndexDB connected to CallQosData");
5180
-
5181
-        var IDB = event.target.result;
5182
-        if(IDB.objectStoreNames.contains("CallQos") == false){
5183
-            console.warn("IndexDB CallQosData.CallQos does not exists");
5184
-            return;
5185
-        }
5186
-        IDB.onerror = function(event) {
5187
-            console.error("IndexDB Error:", event);
5188
-        }
5189
-
5190
-        // Loop and Delete
5191
-        console.log("Deleting CallQosData: ", buddy);
5192
-        var transaction = IDB.transaction(["CallQos"], "readwrite");
5193
-        var objectStore = transaction.objectStore("CallQos");
5194
-        var objectStoreGet = objectStore.index('buddy').getAll(buddy);
5195
-
5196
-        objectStoreGet.onerror = function(event) {
5197
-            console.error("IndexDB Get Error:", event);
5198
-        }
5199
-        objectStoreGet.onsuccess = function(event) {
5200
-            if(event.target.result && event.target.result.length > 0){
5201
-                // There sre some rows to delete
5202
-                $.each(event.target.result, function(i, item){
5203
-                    // console.log("Delete: ", item.uID);
5204
-                    try{
5205
-                        objectStore.delete(item.uID);
5206
-                    } catch(e){
5207
-                        console.log("Call CallQosData Delete failed: ", e);
5208
-                    }
5209
-                });
5210
-            }
5211
-        }
5212
-
5213
-    }
5214
-}
5215
-
5216
-// Presence / Subscribe
5217
-// ====================
5218
-function SubscribeAll() {
5219
-    console.log("Subscribe to voicemail Messages...");
5220
-
5221
-    // conference, message-summary, dialog, presence, presence.winfo, xcap-diff, dialog.winfo, refer
5222
-
5223
-    // Voicemail notice
5224
-    var vmOptions = { expires: 300 }
5225
-    voicemailSubs = userAgent.subscribe(SipUsername + "@" + wssServer, 'message-summary', vmOptions); // message-summary = voicemail messages
5226
-    voicemailSubs.on('notify', function (notification) {
5227
-
5228
-        // You have voicemail: 
5229
-        // Message-Account: sip:alice@example.com
5230
-        // Messages-Waiting: no
5231
-        // Fax-Message: 2/4
5232
-        // Voice-Message: 0/0 (0/0)   <-- new/old (new & urgent/ old & urgent)
5233
-
5234
-        var messagesWaitng = false;
5235
-        $.each(notification.request.body.split("\n"), function (i, line) {
5236
-            if(line.indexOf("Messages-Waiting:") != -1){
5237
-                messagesWaitng = ($.trim(line.replace("Messages-Waiting:", "")) == "yes");
5238
-            }
5239
-        });
5240
-
5241
-        if(messagesWaitng){
5242
-            // Notify user of voicemail
5243
-            console.log("You have voicemail!");
5244
-        }
5245
-    });
5246
-
5247
-    // Dialog Subscription (This version isnt as nice as PIDF)
5248
-    // var dialogOptions = { expires: 300, extraHeaders: ['Accept: application/dialog-info+xml'] }
5249
-
5250
-    // PIDF Subscription
5251
-    var dialogOptions = { expires: 300, extraHeaders: ['Accept: application/pidf+xml'] }
5252
-    // var dialogOptions = { expires: 300, extraHeaders: ['Accept: application/pidf+xml', 'application/xpidf+xml', 'application/simple-message-summary', 'application/im-iscomposing+xml'] }
5253
-
5254
-    // Start subscribe all
5255
-    console.log("Starting Subscribe of all ("+ Buddies.length +") Extension Buddies...");
5256
-    for(var b=0; b<Buddies.length; b++) {
5257
-        var buddyObj = Buddies[b];
5258
-        if(buddyObj.type == "extension") {
5259
-            console.log("SUBSCRIBE: "+ buddyObj.ExtNo +"@" + wssServer);
5260
-            var blfObj = userAgent.subscribe(buddyObj.ExtNo +"@" + wssServer, 'presence', dialogOptions); 
5261
-            blfObj.data.buddyId = buddyObj.identity;
5262
-            blfObj.on('notify', function (notification) {
5263
-                RecieveBlf(notification);
5264
-            });
5265
-            BlfSubs.push(blfObj);
5266
-        }
5267
-    }
5268
-}
5269
-function SubscribeBuddy(buddyObj) {
5270
-    var dialogOptions = { expires: 300, extraHeaders: ['Accept: application/pidf+xml'] }
5271
-
5272
-    if(buddyObj.type == "extension") {
5273
-        console.log("SUBSCRIBE: "+ buddyObj.ExtNo +"@" + wssServer);
5274
-        var blfObj = userAgent.subscribe(buddyObj.ExtNo +"@" + wssServer, 'presence', dialogOptions);
5275
-        blfObj.data.buddyId = buddyObj.identity;
5276
-        blfObj.on('notify', function (notification) {
5277
-            RecieveBlf(notification);
5278
-        });
5279
-        BlfSubs.push(blfObj);
5280
-    }
5281
-}
5282
-function RecieveBlf(notification) {
5283
-    if (userAgent == null || !userAgent.isRegistered()) return;
5284
-
5285
-    var ContentType = notification.request.headers["Content-Type"][0].parsed;
5286
-    if (ContentType == "application/pidf+xml") {
5287
-
5288
-        var xml = $($.parseXML(notification.request.body));
5289
-
5290
-        var Entity = xml.find("presence").attr("entity");
5291
-        var Contact = xml.find("presence").find("tuple").find("contact").text();
5292
-        if (SipUsername == Entity.split("@")[0].split(":")[1] || SipUsername == Contact.split("@")[0].split(":")[1]){
5293
-            // Message is for you.
5294
-        } 
5295
-        else {
5296
-            console.warn("presence message not for you.", xml);
5297
-            return;
5298
-        }
5299
-
5300
-        var buddy = xml.find("presence").find("tuple").attr("id");
5301
-
5302
-        var statusObj = xml.find("presence").find("tuple").find("status");
5303
-        var availability = xml.find("presence").find("tuple").find("status").find("basic").text();
5304
-        var friendlyState = xml.find("presence").find("note").text();
5305
-        var dotClass = "dotOffline";
5306
-
5307
-        if (friendlyState == "Not online") dotClass = "dotOffline";
5308
-        if (friendlyState == "Ready") dotClass = "dotOnline";
5309
-        if (friendlyState == "On the phone") dotClass = "dotInUse";
5310
-        if (friendlyState == "Ringing") dotClass = "dotRinging";
5311
-        if (friendlyState == "On hold") dotClass = "dotOnHold";
5312
-        if (friendlyState == "Unavailable") dotClass = "dotOffline";
5313
-
5314
-        // dotOnline | dotOffline | dotRinging | dotInUse | dotReady | dotOnHold
5315
-        var buddyObj = FindBuddyByExtNo(buddy);
5316
-        if(buddyObj != null)
5317
-        {
5318
-            console.log("Setting Presence for "+ buddyObj.identity +" to "+ friendlyState);
5319
-            $("#contact-" + buddyObj.identity + "-devstate").prop("class", dotClass);
5320
-            $("#contact-" + buddyObj.identity + "-devstate-main").prop("class", dotClass);
5321
-            buddyObj.devState = dotClass;
5322
-            buddyObj.presence = friendlyState;
5323
-
5324
-            if (friendlyState == "Not online") friendlyState = lang.state_not_online;
5325
-            if (friendlyState == "Ready") friendlyState = lang.state_ready;
5326
-            if (friendlyState == "On the phone") friendlyState = lang.state_on_the_phone;
5327
-            if (friendlyState == "Ringing") friendlyState = lang.state_ringing;
5328
-            if (friendlyState == "On hold") friendlyState = lang.state_on_hold;
5329
-            if (friendlyState == "Unavailable") friendlyState = lang.state_unavailable;
5330
-            $("#contact-" + buddyObj.identity + "-presence").html(friendlyState);
5331
-            $("#contact-" + buddyObj.identity + "-presence-main").html(friendlyState);
5332
-        }
5333
-    }
5334
-    else if (ContentType == "application/dialog-info+xml")
5335
-    {
5336
-        // Handle "Dialog" State
5337
-
5338
-        var xml = $($.parseXML(notification.request.body));
5339
-
5340
-        var ObservedUser = xml.find("dialog-info").attr("entity");
5341
-        var buddy = ObservedUser.split("@")[0].split(":")[1];
5342
-
5343
-        var version = xml.find("dialog-info").attr("version");
5344
-
5345
-        var DialogState = xml.find("dialog-info").attr("state");
5346
-        if (DialogState != "full") return;
5347
-
5348
-        var extId = xml.find("dialog-info").find("dialog").attr("id");
5349
-        if (extId != buddy) return;
5350
-
5351
-        var state = xml.find("dialog-info").find("dialog").find("state").text();
5352
-        var friendlyState = "Unknown";
5353
-        if (state == "terminated") friendlyState = "Ready";
5354
-        if (state == "trying") friendlyState = "On the phone";
5355
-        if (state == "proceeding") friendlyState = "On the phone";
5356
-        if (state == "early") friendlyState = "Ringing";
5357
-        if (state == "confirmed") friendlyState = "On the phone";
5358
-
5359
-        var dotClass = "dotOffline";
5360
-        if (friendlyState == "Not online") dotClass = "dotOffline";
5361
-        if (friendlyState == "Ready") dotClass = "dotOnline";
5362
-        if (friendlyState == "On the phone") dotClass = "dotInUse";
5363
-        if (friendlyState == "Ringing") dotClass = "dotRinging";
5364
-        if (friendlyState == "On hold") dotClass = "dotOnHold";
5365
-        if (friendlyState == "Unavailable") dotClass = "dotOffline";
5366
-
5367
-        // The dialog states only report devices states, and cant say online or offline.
5368
-        // dotOnline | dotOffline | dotRinging | dotInUse | dotReady | dotOnHold
5369
-        var buddyObj = FindBuddyByExtNo(buddy);
5370
-        if(buddyObj != null)
5371
-        {
5372
-            console.log("Setting Presence for "+ buddyObj.identity +" to "+ friendlyState);
5373
-            $("#contact-" + buddyObj.identity + "-devstate").prop("class", dotClass);
5374
-            $("#contact-" + buddyObj.identity + "-devstate-main").prop("class", dotClass);
5375
-            buddyObj.devState = dotClass;
5376
-            buddyObj.presence = friendlyState;
5377
-
5378
-            if (friendlyState == "Unknown") friendlyState = lang.state_unknown;
5379
-            if (friendlyState == "Not online") friendlyState = lang.state_not_online;
5380
-            if (friendlyState == "Ready") friendlyState = lang.state_ready;
5381
-            if (friendlyState == "On the phone") friendlyState = lang.state_on_the_phone;
5382
-            if (friendlyState == "Ringing") friendlyState = lang.state_ringing;
5383
-            if (friendlyState == "On hold") friendlyState = lang.state_on_hold;
5384
-            if (friendlyState == "Unavailable") friendlyState = lang.state_unavailable;
5385
-            $("#contact-" + buddyObj.identity + "-presence").html(friendlyState);
5386
-            $("#contact-" + buddyObj.identity + "-presence-main").html(friendlyState);
5387
-        }
5388
-    }
5389
-}
5390
-function UnsubscribeAll() {
5391
-    console.log("Unsubscribing "+ BlfSubs.length + " subscriptions...");
5392
-    for (var blf = 0; blf < BlfSubs.length; blf++) {
5393
-        BlfSubs[blf].unsubscribe();
5394
-        BlfSubs[blf].close();
5395
-    }
5396
-    BlfSubs = new Array();
5397
-
5398
-    for(var b=0; b<Buddies.length; b++) {
5399
-        var buddyObj = Buddies[b];
5400
-        if(buddyObj.type == "extension") {
5401
-            $("#contact-" + buddyObj.identity + "-devstate").prop("class", "dotOffline");
5402
-            $("#contact-" + buddyObj.identity + "-devstate-main").prop("class", "dotOffline");
5403
-            $("#contact-" + buddyObj.identity + "-presence").html(lang.state_unknown);
5404
-            $("#contact-" + buddyObj.identity + "-presence-main").html(lang.state_unknown);
5405
-        }
5406
-    }
5407
-}
5408
-function UnsubscribeBuddy(buddyObj) {
5409
-    if(buddyObj.type != "extension") return;
5410
-
5411
-    for (var blf = 0; blf < BlfSubs.length; blf++) {
5412
-        var blfObj = BlfSubs[blf];
5413
-        if(blfObj.data.buddyId == buddyObj.identity){
5414
-        console.log("Unsubscribing:", buddyObj.identity);
5415
-            if(blfObj.dialog != null){
5416
-                blfObj.unsubscribe();
5417
-                blfObj.close();
5418
-            }
5419
-            BlfSubs.splice(blf, 1);
5420
-            break;
5421
-        }
5422
-    }
5423
-}
5424
-
5425
-// Buddy: Chat / Instant Message / XMPP
5426
-// ====================================
5427
-function InitinaliseStream(buddy){
5428
-    var template = { TotalRows:0, DataCollection:[] }
5429
-    localDB.setItem(buddy + "-stream", JSON.stringify(template));
5430
-    return JSON.parse(localDB.getItem(buddy + "-stream"));
5431
-}
5432
-function splitString(str, size) {
5433
-    const mPieces = Math.ceil(str.length / size);
5434
-    const piecesArr = [];
5435
-
5436
-    for (let i = 0, s = 0; i < mPieces; ++i, s += size) {
5437
-      piecesArr[i] = str.substr(s, size);
5438
-    }
5439
-    return piecesArr;
5440
-}
5441
-function generateAESKey(passphrase) {
5442
-    const salt = CryptoJS.lib.WordArray.random(128 / 8);
5443
-    const key256Bits = CryptoJS.PBKDF2(passphrase, salt, {
5444
-      keySize: 256 / 32,
5445
-      iterations: 100,
5446
-    });
5447
-    return key256Bits;
5448
-}
5449
-function encryptAES(message, key) {
5450
-    var message = CryptoJS.AES.encrypt(message, key);
5451
-    return message.toString();
5452
-}
5453
-function decryptAES(message, key) {
5454
-    var code = CryptoJS.AES.decrypt(message, key);
5455
-    var decryptedMessage = code.toString(CryptoJS.enc.Utf8);
5456
-    return decryptedMessage;
5457
-}
5458
-function getChatRSAPubKey(recsendSIPuser) {
5459
-    var chatPubKey = '';
5460
-    $.ajax({
5461
-	     'async': false,
5462
-	     'global': false,
5463
-	     type: "POST",
5464
-	     url: "get-text-chat-pub-key.php",
5465
-	     dataType: "JSON",
5466
-	     data: { 
5467
-		     recsendsipuser: recsendSIPuser,
5468
-                     s_ajax_call: validateSToken
5469
-             },
5470
-	     success: function(result) {
5471
-                            if (result.resmessage == 'success') {
5472
-                                chatPubKey = "`" + result.chatkey.join("") + "`";
5473
-                            } else {
5474
-                                pubKeyCheck = 1;
5475
-                                alert('An error occurred while retrieving the public key for text chat!');
5476
-                            }
5477
-             },
5478
-             error: function(result) {
5479
-                    alert('An error occurred while attempting to retrieve the public key for text chat!');
5480
-             }
5481
-    });
5482
-    return chatPubKey;
5483
-}
5484
-
5485
-function SendChatMessage(buddy) {
5486
-
5487
-    if (userAgent == null) return;
5488
-    if (!userAgent.isRegistered()) return;
5489
-
5490
-    var messageraw = $("#contact-" + buddy + "-ChatMessage").val();
5491
-    messagetrim = $.trim(messageraw);
5492
-
5493
-    if (messagetrim == "" && (sendFileCheck == 0 || (sendFileCheck == 1 && $("#selectedFile").val() == ""))) { 
5494
-        Alert(lang.alert_empty_text_message, lang.no_message);
5495
-        return;
5496
-    }
5497
-
5498
-    var buddyObj = FindBuddyByIdentity(buddy);
5499
-
5500
-    if ($.inArray(buddyObj.presence, ["Ready", "On the phone", "Ringing", "On hold"]) == -1) {
5501
-        alert("You cannot send a message or a file to a contact who is not online!");
5502
-        $("#sendFileLoader").remove();
5503
-        $("#selectedFile").val("");
5504
-        $("#sendFileFormChat").remove();
5505
-        sendFileCheck = 0;
5506
-        return; 
5507
-    }
5508
-
5509
-    var genPassphr = Date.now() + Math.floor(Math.random()*10000).toString(6).toUpperCase();
5510
-    var aesKey = String(generateAESKey(genPassphr));
5511
-    var encryptedMes = encryptAES(messagetrim, aesKey);
5512
-
5513
-    // Split the encrypted message into smaller pieces to fit the 1024 byte limit for SIP messages, which is hard-coded in Asterisk
5514
-    var messageprearr = [];
5515
-    var messageprearr = splitString(encryptedMes, 900);
5516
-
5517
-    var genMessageId =  Date.now() + Math.floor(Math.random()*10000).toString(16).toUpperCase();
5518
-    var messageIdent = genMessageId + profileUser;
5519
-    var firstPieceCheck = [];
5520
-    firstPieceCheck = [messageIdent, 1];
5521
-    var lastPieceCheck = [];
5522
-    lastPieceCheck = [messageIdent, 0];
5523
-
5524
-    // Get the public key of the extension to which we send the message
5525
-    var destExtChatRSAPubKey = getChatRSAPubKey(buddyObj.ExtNo);
5526
-
5527
-    // Encrypt the AES key with RSA
5528
-    var newencrypt = new JSEncrypt();
5529
-    newencrypt.setPublicKey(destExtChatRSAPubKey);
5530
-    var encmIdAesKey = newencrypt.encrypt(aesKey);
5531
-
5532
-    // Add the encrypted AES key as the first element of the array of message pieces
5533
-    messageprearr.unshift(encmIdAesKey);
5534
-
5535
-    $("#contact-"+ buddy +"-ChatHistory").after("<span id='sendFileLoader'></span>");
5536
-
5537
-    for (var k = 0; k < messageprearr.length; k++) {
5538
-
5539
-         if (k == 0) {
5540
-             // Send the RSA-encrypted AES key as first piece of the message
5541
-             var messagePiece = messageIdent + "|" + messageprearr.length + "|" + parseInt(k) + "||" + messageprearr[k];
5542
-	 } else if (sendFileCheck == 0 && messageprearr[k] != '') {
5543
-	     var messagePiece = messageIdent + "|" + messageprearr.length + "|" + parseInt(k) + "||" + messageprearr[k];
5544
-	 } else if (sendFileCheck == 1 && sendFileChatErr == '') {
5545
-	     var messagePiece = messageIdent + "|" + messageprearr.length + "|" + parseInt(k) + "|" + upFileName + "|" + messageprearr[k];
5546
-	 } else if (sendFileCheck == 1 && sendFileChatErr != '') {
5547
-	     $("#sendFileFormChat").remove();
5548
-             sendFileChatErr = '';
5549
-	     sendFileCheck = 0;
5550
-	     return;
5551
-	 }
5552
-
5553
-         if (k == 1) { firstPieceCheck = [messageIdent, 0]; }
5554
-
5555
-         if (k == (messageprearr.length - 1)) { lastPieceCheck = [messageIdent, 1]; }
5556
-
5557
-         SendChatMessageProc(buddy, buddyObj, messageIdent, messagePiece, messagetrim, firstPieceCheck, lastPieceCheck);
5558
-    }
5559
-}
5560
-
5561
-function SendChatMessageProc(buddy, buddyObj, messageIdent, messagePiece, messagetrim, firstPieceCheck, lastPieceCheck) {
5562
-
5563
-    var messageId = uID();
5564
-
5565
-    if (pubKeyCheck == 1) { pubKeyCheck = 0; $("#selectedFile").val(""); $("#sendFileLoader").remove(); return; }
5566
-
5567
-    sendFileChatErr = '';
5568
-
5569
-    $("#sendFileFormChat").on('submit', function(ev) {
5570
-             ev.preventDefault();
5571
-
5572
-             $.ajax({
5573
-                'async': false,
5574
-                'global': false,
5575
-                type: 'POST',
5576
-                url: 'text-chat-upload-file.php',
5577
-                data: new FormData(this),
5578
-                dataType: "JSON",
5579
-                contentType: false,
5580
-                cache: false,
5581
-                processData:false,
5582
-                success: function(respdata) {
5583
-                            if (respdata.error != '') { 
5584
-                                sendFileChatErr = respdata.error;
5585
-                                $("#sendFileFormChat").remove();
5586
-                                $("#sendFileLoader").remove();
5587
-                                alert("Error: " + respdata.error);
5588
-                            }
5589
-                },
5590
-                error: function(respdata) {
5591
-                            alert("An error occurred while sending the file!");
5592
-                }          
5593
-             });
5594
-    });
5595
-
5596
-    if (sendFileCheck == 1 && (firstPieceCheck[0] == messageIdent && firstPieceCheck[1] == 1)) {
5597
-        $("#submitFileChat").click();
5598
-    }
5599
-
5600
-    if (lastPieceCheck[0] == messageIdent && lastPieceCheck[1] == 1 && sendFileCheck == 1 && sendFileChatErr != '') {
5601
-        $("#sendFileFormChat").remove();
5602
-        $("#sendFileLoader").remove();
5603
-        sendFileChatErr = '';
5604
-        sendFileCheck = 0;
5605
-        return;
5606
-    }
5607
-
5608
-    if (buddyObj.type == "extension" || buddyObj.type == "group") {
5609
-
5610
-          var chatBuddy = buddyObj.ExtNo + "@" + wssServer;
5611
-          console.log("MESSAGE: "+ chatBuddy + " (extension)");
5612
-
5613
-          var messageObj = userAgent.message(chatBuddy, messagePiece);
5614
-
5615
-            messageObj.data.direction = "outbound";
5616
-            messageObj.data.messageId = messageId;
5617
-
5618
-            messageObj.on("accepted", function (response, cause){
5619
-
5620
-                if(response.status_code == 202) {
5621
-                    console.log("Message Accepted:", messageId);
5622
-
5623
-                    // Update DB
5624
-                    var currentStream = JSON.parse(localDB.getItem(buddy + "-stream"));
5625
-                    if(currentStream != null || currentStream.DataCollection != null){
5626
-                        $.each(currentStream.DataCollection, function (i, item) {
5627
-                            if (item.ItemType == "MSG" && item.ItemId == messageId) {
5628
-                                // Found
5629
-                                item.Sent = true;
5630
-                                return false;
5631
-                            }
5632
-                        });
5633
-                        localDB.setItem(buddy + "-stream", JSON.stringify(currentStream));
5634
-
5635
-                        RefreshStream(buddyObj);
5636
-                    }
5637
-                } else {
5638
-                    console.warn("Message Error", response.status_code, cause);
5639
-
5640
-                    // Update DB
5641
-                    var currentStream = JSON.parse(localDB.getItem(buddy + "-stream"));
5642
-                    if(currentStream != null || currentStream.DataCollection != null){
5643
-                        $.each(currentStream.DataCollection, function (i, item) {
5644
-                            if (item.ItemType == "MSG" && item.ItemId == messageId) {
5645
-                                // Found
5646
-                                item.Sent = false;
5647
-                                return false;
5648
-                            }
5649
-                        });
5650
-                        localDB.setItem(buddy + "-stream", JSON.stringify(currentStream));
5651
-
5652
-                        RefreshStream(buddyObj);
5653
-                    }                
5654
-                }
5655
-            });
5656
-
5657
-          // Custom Web hook
5658
-          if (typeof web_hook_on_message !== 'undefined') web_hook_on_message(messageObj); 
5659
-    }
5660
-
5661
-    if (lastPieceCheck[0] == messageIdent && lastPieceCheck[1] == 1) {
5662
-
5663
-       // Update Stream
5664
-       var DateTime = moment.utc().format("YYYY-MM-DD HH:mm:ss UTC");
5665
-       var currentStream = JSON.parse(localDB.getItem(buddy + "-stream"));
5666
-       if(currentStream == null) currentStream = InitinaliseStream(buddy);
5667
-
5668
-       // Add New Message
5669
-       var newMessageJson = {
5670
-           ItemId: messageId,
5671
-           ItemType: "MSG",
5672
-           ItemDate: DateTime,
5673
-           SrcUserId: profileUserID,
5674
-           Src: "\""+ profileName +"\" <"+ profileUser +">",
5675
-           DstUserId: buddy,
5676
-           Dst: "",
5677
-           MessageData: messagetrim
5678
-       }
5679
-
5680
-       // If a file is sent, add the sent file section
5681
-       if (sendFileCheck == 1) {
5682
-
5683
-           $("#sendFileFormChat").remove();
5684
-           sendFileCheck = 0;
5685
-
5686
-           var newMessageId = uID();
5687
-           var newDateTime = moment.utc().format("YYYY-MM-DD HH:mm:ss UTC");
5688
-
5689
-	   var newFileMessageJson = {
5690
-	        ItemId: newMessageId,
5691
-	        ItemType: "FILE",
5692
-	        ItemDate: newDateTime,
5693
-	        SrcUserId: profileUserID,
5694
-	        Src: "\""+ profileName +"\" <"+ profileUser +">",
5695
-	        DstUserId: buddy,
5696
-	        Dst: buddyObj.ExtNo,
5697
-                SentFileName: upFileName,
5698
-	        MessageData: "Download file"
5699
-	   }
5700
-
5701
-           if (sendFileChatErr == '') {
5702
-               currentStream.DataCollection.push(newFileMessageJson);
5703
-           }
5704
-
5705
-       } else { $("#sendFileFormChat").remove(); }
5706
-
5707
-       currentStream.DataCollection.push(newMessageJson);
5708
-
5709
-       currentStream.TotalRows = currentStream.DataCollection.length;
5710
-       localDB.setItem(buddy + "-stream", JSON.stringify(currentStream));
5711
-
5712
-    }
5713
-
5714
-    // Post Add Activity
5715
-    if (lastPieceCheck[0] == messageIdent && lastPieceCheck[1] == 1) {
5716
-        $("#sendFileLoader").remove();
5717
-        $("#contact-" + buddy + "-ChatMessage").val("");
5718
-    }
5719
-    $("#contact-" + buddy + "-emoji-menu").hide();
5720
-
5721
-    if(buddyObj.recognition != null){
5722
-       buddyObj.recognition.abort();
5723
-       buddyObj.recognition = null;
5724
-    }
5725
-
5726
-    RefreshStream(buddyObj);
5727
-}
5728
-
5729
-function ReceiveMessage(message) {
5730
-
5731
-    var callerID = message.remoteIdentity.displayName;
5732
-    var did = message.remoteIdentity.uri.user;
5733
-
5734
-    console.log("New Incoming Message!", "\""+ callerID +"\" <"+ did +">");
5735
-
5736
-    message.data.direction = "inbound";
5737
-
5738
-    if(did.length > DidLength) {
5739
-        // Contacts cannot receive Text Messages, because they cannot reply
5740
-        // This may change with FAX, Email, WhatsApp etc
5741
-        console.warn("DID length greater then extensions length")
5742
-        return;
5743
-    }
5744
-
5745
-    var CurrentCalls = countSessions("0");
5746
-
5747
-    var buddyObj = FindBuddyByDid(did);
5748
-    // Make new contact if it's not there
5749
-    if(buddyObj == null) {
5750
-        var json = JSON.parse(localDB.getItem(profileUserID + "-Buddies"));
5751
-        if(json == null) json = InitUserBuddies();
5752
-
5753
-        // Add Extension
5754
-        var id = uID();
5755
-        var dateNow = utcDateNow();
5756
-        json.DataCollection.push({
5757
-            Type: "extension",
5758
-            LastActivity: dateNow,
5759
-            ExtensionNumber: did,
5760
-            MobileNumber: "",
5761
-            ContactNumber1: "",
5762
-            ContactNumber2: "",
5763
-            uID: id,
5764
-            cID: null,
5765
-            gID: null,
5766
-            DisplayName: callerID,
5767
-            Position: "",
5768
-            Description: "",
5769
-            Email: "",
5770
-            MemberCount: 0
5771
-        });
5772
-        buddyObj = new Buddy("extension", id, callerID, did, "", "", "", dateNow, "", "");
5773
-        AddBuddy(buddyObj, true, (CurrentCalls==0), true);
5774
-
5775
-        // Update Size
5776
-        json.TotalRows = json.DataCollection.length;
5777
-
5778
-        // Save To DB
5779
-        localDB.setItem(profileUserID + "-Buddies", JSON.stringify(json));
5780
-    }
5781
-
5782
-    var encryptedtext = message.body;
5783
-    var originalMessageArr = encryptedtext.split("|");
5784
-
5785
-    if (originalMessageArr[3] != '' && typeof originalMessageArr[3] != 'undefined' && originalMessageArr[3] != null) {
5786
-        var fileSentDuringChat = 1;
5787
-	var recFileName = originalMessageArr[3];
5788
-    } else {
5789
-	var fileSentDuringChat = 0;
5790
-        var recFileName = '';
5791
-    }
5792
-
5793
-    var currentMId = originalMessageArr[0];
5794
-    var totalPieceNo = parseInt(originalMessageArr[1]);
5795
-    var currentPieceNo = parseInt(originalMessageArr[2]);
5796
-
5797
-    // Reassemble the original message and decrypt it
5798
-    if (currentPieceNo == 0) {
5799
-
5800
-       if (splitMessage.hasOwnProperty(currentMId)) {
5801
-
5802
-          if (currentPieceNo == 0) {
5803
-              var aesPayload = originalMessageArr[4];
5804
-              var newdecrypt = new JSEncrypt();
5805
-              newdecrypt.setPrivateKey(currentChatPrivKey);
5806
-              var decAESKeyCon = newdecrypt.decrypt(aesPayload);
5807
-              splitMessage[currentMId].aeskeyandiv = decAESKeyCon;
5808
-
5809
-          } else {
5810
-             splitMessage[currentMId][currentPieceNo] = originalMessageArr[4];
5811
-          }
5812
-
5813
-       } else {
5814
-
5815
-          if (currentPieceNo == 0) {
5816
-              var aesPayload = originalMessageArr[4];
5817
-              var newdecrypt = new JSEncrypt();
5818
-              newdecrypt.setPrivateKey(currentChatPrivKey);
5819
-              var decAESKeyCon = newdecrypt.decrypt(aesPayload);
5820
-              splitMessage[currentMId] = { "aeskeyandiv": decAESKeyCon };
5821
-
5822
-          } else {
5823
-             splitMessage[currentMId] = { [currentPieceNo]: originalMessageArr[4] };
5824
-          }
5825
-
5826
-       }
5827
-
5828
-       return;
5829
-
5830
-    } else if (currentPieceNo < (totalPieceNo - 1)) {
5831
-
5832
-        if (splitMessage.hasOwnProperty(currentMId)) {
5833
-            splitMessage[currentMId][currentPieceNo] = originalMessageArr[4];
5834
-        } else {
5835
-	    splitMessage[currentMId] = { [currentPieceNo]: originalMessageArr[4] };
5836
-        }
5837
-
5838
-        return;
5839
-
5840
-    } else if (currentPieceNo == (totalPieceNo - 1)) {
5841
-
5842
-        if (splitMessage.hasOwnProperty(currentMId)) {
5843
-            splitMessage[currentMId][currentPieceNo] = originalMessageArr[4];
5844
-        } else {
5845
-	    splitMessage[currentMId] = { [currentPieceNo]: originalMessageArr[4] };
5846
-        }
5847
-
5848
-        if (Object.keys(splitMessage[currentMId]).length == totalPieceNo) {
5849
-
5850
-            var decryptAesKey = splitMessage[currentMId]["aeskeyandiv"];
5851
-
5852
-            delete splitMessage[currentMId]["aeskeyandiv"];
5853
-            var origMessageEnc = '';
5854
-            var orderedMPieces = Object.keys(splitMessage[currentMId]).sort().reduce(function(obj, key) { 
5855
-                obj[key] = splitMessage[currentMId][key]; 
5856
-                return obj;
5857
-            },{});
5858
-
5859
-            Object.keys(orderedMPieces).forEach(function(key, index) {
5860
-                origMessageEnc += splitMessage[currentMId][key];
5861
-            });
5862
-
5863
-            var originalMessage = decryptAES(origMessageEnc, decryptAesKey);
5864
-
5865
-	    delete splitMessage[currentMId];
5866
-
5867
-        } else { return; }
5868
-    }
5869
-
5870
-    var messageId = uID();
5871
-    var DateTime = utcDateNow();
5872
-
5873
-    // Get the actual person sending (since all group messages come from the group)
5874
-    var ActualSender = "";
5875
-    if(buddyObj.type == "group") {
5876
-        var assertedIdentity = message.request.headers["P-Asserted-Identity"][0].raw; // Name Surname <ExtNo> 
5877
-        var bits = assertedIdentity.split(" <");
5878
-        var CallerID = bits[0];
5879
-        var CallerIDNum = bits[1].replace(">", "");
5880
-
5881
-        ActualSender = CallerID; // P-Asserted-Identity;
5882
-    }
5883
-
5884
-    // Current stream
5885
-    var currentStream = JSON.parse(localDB.getItem(buddyObj.identity + "-stream"));
5886
-    if(currentStream == null) currentStream = InitinaliseStream(buddyObj.identity);
5887
-
5888
-    // Add new message
5889
-    var newMessageJson = {
5890
-        ItemId: messageId,
5891
-        ItemType: "MSG",
5892
-        ItemDate: DateTime,
5893
-        SrcUserId: buddyObj.identity,
5894
-        Src: "\""+ buddyObj.CallerIDName +"\" <"+ buddyObj.ExtNo +">",
5895
-        DstUserId: profileUserID,
5896
-        Dst: "",
5897
-        MessageData: originalMessage
5898
-    }
5899
-
5900
-    // If a file is received, add the received file section
5901
-    if (fileSentDuringChat == 1 && recFileName != '') {
5902
-
5903
-        fileSentDuringChat = 0;
5904
-
5905
-        var newMessageId = uID();
5906
-        var newDateTime = moment.utc().format("YYYY-MM-DD HH:mm:ss UTC");
5907
-
5908
-	var newFileMessageJson = {
5909
-	        ItemId: newMessageId,
5910
-	        ItemType: "FILE",
5911
-	        ItemDate: newDateTime,
5912
-	        SrcUserId: buddyObj.identity,
5913
-                Src: "\""+ buddyObj.CallerIDName +"\" <"+ buddyObj.ExtNo +">",
5914
-	        DstUserId: profileUserID,
5915
-	        Dst: profileUser,
5916
-                ReceivedFileName: recFileName,
5917
-	        MessageData: "Download file"
5918
-	}
5919
-
5920
-        currentStream.DataCollection.push(newFileMessageJson);
5921
-    }
5922
-
5923
-    currentStream.DataCollection.push(newMessageJson);
5924
-
5925
-    currentStream.TotalRows = currentStream.DataCollection.length;
5926
-    localDB.setItem(buddyObj.identity + "-stream", JSON.stringify(currentStream));
5927
-
5928
-    // Update Last Activity
5929
-    // ====================
5930
-    UpdateBuddyActivity(buddyObj.identity);
5931
-    RefreshStream(buddyObj);
5932
-
5933
-    // Handle Stream Not visible
5934
-    // =========================
5935
-    var streamVisible = $("#stream-"+ buddyObj.identity).is(":visible");
5936
-    if (!streamVisible) {
5937
-        // Add or Increase the Badge
5938
-        IncreaseMissedBadge(buddyObj.identity);
5939
-        if ("Notification" in window) {
5940
-            if (Notification.permission === "granted") {
5941
-                var imageUrl = getPicture(buddyObj.identity);
5942
-                var noticeOptions = { body: originalMessage.substring(0, 250), icon: imageUrl }
5943
-                var inComingChatNotification = new Notification(lang.message_from + " : " + buddyObj.CallerIDName, noticeOptions);
5944
-                inComingChatNotification.onclick = function (event) {
5945
-                    // Show Message
5946
-                    SelectBuddy(buddyObj.identity);
5947
-                }
5948
-            }
5949
-        }
5950
-        // Play Alert
5951
-        console.log("Audio:", audioBlobs.Alert.url);
5952
-        var rinnger = new Audio(audioBlobs.Alert.blob);
5953
-        rinnger.preload = "auto";
5954
-        rinnger.loop = false;
5955
-        rinnger.oncanplaythrough = function(e) {
5956
-            if (typeof rinnger.sinkId !== 'undefined' && getRingerOutputID() != "default") {
5957
-                rinnger.setSinkId(getRingerOutputID()).then(function() {
5958
-                    console.log("Set sinkId to:", getRingerOutputID());
5959
-                }).catch(function(e){
5960
-                    console.warn("Failed not apply setSinkId.", e);
5961
-                });
5962
-            }
5963
-            // If there has been no interaction with the page at all... this page will not work
5964
-            rinnger.play().then(function(){
5965
-               // Audio Is Playing
5966
-            }).catch(function(e){
5967
-                console.warn("Unable to play audio file.", e);
5968
-            });
5969
-        }
5970
-        message.data.rinngerObj = rinnger; // Will be attached to this object until its disposed.
5971
-    } else {
5972
-        // Message window is active.
5973
-    }
5974
-}
5975
-function AddCallMessage(buddy, session, reasonCode, reasonText) {
5976
-
5977
-    var currentStream = JSON.parse(localDB.getItem(buddy + "-stream"));
5978
-    if(currentStream == null) currentStream = InitinaliseStream(buddy);
5979
-
5980
-    var CallEnd = moment.utc(); // Take Now as the Hangup Time
5981
-    var callDuration = 0;
5982
-    var totalDuration = 0;
5983
-    var ringTime = 0;
5984
-
5985
-    var CallStart = moment.utc(session.data.callstart.replace(" UTC", "")); // Actual start (both inbound and outbound)
5986
-    var CallAnswer = null; // On Accept when inbound, Remote Side when Outbound
5987
-    if(session.startTime){
5988
-        // The time when WE answered the call (May be null - no answer)
5989
-        // or
5990
-        // The time when THEY answered the call (May be null - no answer)
5991
-        CallAnswer = moment.utc(session.startTime);  // Local Time gets converted to UTC 
5992
-
5993
-        callDuration = moment.duration(CallEnd.diff(CallAnswer));
5994
-        ringTime = moment.duration(CallAnswer.diff(CallStart));
5995
-    }
5996
-    totalDuration = moment.duration(CallEnd.diff(CallStart));
5997
-
5998
-    console.log(session.data.reasonCode + "("+ session.data.reasonText +")")
5999
-
6000
-    var srcId = "";
6001
-    var srcCallerID = "";
6002
-    var dstId = ""
6003
-    var dstCallerID = "";
6004
-    if(session.data.calldirection == "inbound") {
6005
-        srcId = buddy;
6006
-        dstId = profileUserID;
6007
-        srcCallerID = "<"+ session.remoteIdentity.uri.user +"> "+ session.remoteIdentity.displayName;
6008
-        dstCallerID = "<"+ profileUser+"> "+ profileName;
6009
-    } else if(session.data.calldirection == "outbound") {
6010
-        srcId = profileUserID;
6011
-        dstId = buddy;
6012
-        srcCallerID = "<"+ profileUser+"> "+ profileName;
6013
-        dstCallerID = session.remoteIdentity.uri.user;
6014
-    }
6015
-
6016
-    var callDirection = session.data.calldirection;
6017
-    var withVideo = session.data.withvideo;
6018
-    var sessionId = session.id;
6019
-    var hanupBy = session.data.terminateby;
6020
-
6021
-    var newMessageJson = {
6022
-        CdrId: uID(),
6023
-        ItemType: "CDR",
6024
-        ItemDate: CallStart.format("YYYY-MM-DD HH:mm:ss UTC"),
6025
-        CallAnswer: (CallAnswer)? CallAnswer.format("YYYY-MM-DD HH:mm:ss UTC") : null,
6026
-        CallEnd: CallEnd.format("YYYY-MM-DD HH:mm:ss UTC"),
6027
-        SrcUserId: srcId,
6028
-        Src: srcCallerID,
6029
-        DstUserId: dstId,
6030
-        Dst: dstCallerID,
6031
-        RingTime: (ringTime != 0)? ringTime.asSeconds() : 0,
6032
-        Billsec: (callDuration != 0)? callDuration.asSeconds() : 0,
6033
-        TotalDuration: (totalDuration != 0)? totalDuration.asSeconds() : 0,
6034
-        ReasonCode: reasonCode,
6035
-        ReasonText: reasonText,
6036
-        WithVideo: withVideo,
6037
-        SessionId: sessionId,
6038
-        CallDirection: callDirection,
6039
-        Terminate: hanupBy,
6040
-        // CRM
6041
-        MessageData: null,
6042
-        Tags: [],
6043
-        //Reporting
6044
-        Transfers: (session.data.transfer)? session.data.transfer : [],
6045
-        Mutes: (session.data.mute)? session.data.mute : [],
6046
-        Holds: (session.data.hold)? session.data.hold : [],
6047
-        Recordings: (session.data.recordings)? session.data.recordings : [],
6048
-        ConfCalls: (session.data.confcalls)? session.data.confcalls : [],
6049
-        QOS: []
6050
-    }
6051
-
6052
-    console.log("New CDR", newMessageJson);
6053
-
6054
-    currentStream.DataCollection.push(newMessageJson);
6055
-    currentStream.TotalRows = currentStream.DataCollection.length;
6056
-    localDB.setItem(buddy + "-stream", JSON.stringify(currentStream));
6057
-
6058
-    UpdateBuddyActivity(buddy);
6059
-}
6060
-
6061
-function SendImageDataMessage(buddy, ImgDataUrl) {
6062
-    if (userAgent == null) return;
6063
-    if (!userAgent.isRegistered()) return;
6064
-
6065
-    // Ajax Upload
6066
-    // ===========
6067
-
6068
-    var DateTime = moment.utc().format("YYYY-MM-DD HH:mm:ss UTC");
6069
-    var formattedMessage = '<IMG class=previewImage onClick="PreviewImage(this)" src="'+ ImgDataUrl +'">';
6070
-    var messageString = "<table class=\"ourChatMessage chatMessageTable\" cellspacing=0 cellpadding=0><tr><td style=\"width: 80px\">"
6071
-        + "<div class=messageDate>" + DateTime + "</div>"
6072
-        + "</td><td>"
6073
-        + "<div class=ourChatMessageText>" + formattedMessage + "</div>"
6074
-        + "</td></tr></table>";
6075
-    $("#contact-" + buddy + "-ChatHistory").append(messageString);
6076
-    updateScroll(buddy);
6077
-
6078
-    ImageEditor_Cancel(buddy);
6079
-
6080
-    UpdateBuddyActivity(buddy);
6081
-}
6082
-
6083
-function SendFileDataMessage(buddy, FileDataUrl, fileName, fileSize) {
6084
-    if (userAgent == null) return;
6085
-    if (!userAgent.isRegistered()) return;
6086
-
6087
-    var fileID = uID();
6088
-
6089
-    // Ajax Upload
6090
-    // ===========
6091
-    $.ajax({
6092
-        type:'POST',
6093
-        url: '/api/',
6094
-        data: "<XML>"+ FileDataUrl +"</XML>",
6095
-        xhr: function(e) {
6096
-            var myXhr = $.ajaxSettings.xhr();
6097
-            if(myXhr.upload){
6098
-                myXhr.upload.addEventListener('progress',function(event){
6099
-                    var percent = (event.loaded / event.total) * 100;
6100
-                    console.log("Progress for upload to "+ buddy +" ("+ fileID +"):"+ percent);
6101
-                    $("#FileProgress-Bar-"+ fileID).css("width", percent +"%");
6102
-                }, false);
6103
-            }
6104
-            return myXhr;
6105
-        },
6106
-        success:function(data, status, jqXHR){
6107
-            // console.log(data);
6108
-            $("#FileUpload-"+ fileID).html("Sent");
6109
-            $("#FileProgress-"+ fileID).hide();
6110
-            $("#FileProgress-Bar-"+ fileID).css("width", "0%");
6111
-        },
6112
-        error: function(data, status, error){
6113
-            // console.log(data);
6114
-            $("#FileUpload-"+ fileID).html("Failed ("+ data.status +")");
6115
-            $("#FileProgress-"+ fileID).hide();
6116
-            $("#FileProgress-Bar-"+ fileID).css("width", "100%");
6117
-        }
6118
-    });
6119
-
6120
-    // Add To Message Stream
6121
-    // =====================
6122
-    var DateTime = utcDateNow();
6123
-
6124
-    var showReview = false;
6125
-    var fileIcon = '<i class="fa fa-file"></i>';
6126
-    // Image Icons
6127
-    if(fileName.toLowerCase().endsWith(".png")) {
6128
-        fileIcon =  '<i class="fa fa-file-image-o"></i>';
6129
-        showReview = true;
6130
-    }
6131
-    if(fileName.toLowerCase().endsWith(".jpg")) {
6132
-        fileIcon =  '<i class="fa fa-file-image-o"></i>';
6133
-        showReview = true;
6134
-    }
6135
-    if(fileName.toLowerCase().endsWith(".jpeg")) {
6136
-        fileIcon =  '<i class="fa fa-file-image-o"></i>';
6137
-        showReview = true;
6138
-    }
6139
-    if(fileName.toLowerCase().endsWith(".bmp")) {
6140
-        fileIcon =  '<i class="fa fa-file-image-o"></i>';
6141
-        showReview = true;
6142
-    }
6143
-    if(fileName.toLowerCase().endsWith(".gif")) {
6144
-        fileIcon =  '<i class="fa fa-file-image-o"></i>';
6145
-        showReview = true;
6146
-    }
6147
-    // video Icons
6148
-    if(fileName.toLowerCase().endsWith(".mov")) fileIcon =  '<i class="fa fa-file-video-o"></i>';
6149
-    if(fileName.toLowerCase().endsWith(".avi")) fileIcon =  '<i class="fa fa-file-video-o"></i>';
6150
-    if(fileName.toLowerCase().endsWith(".mpeg")) fileIcon =  '<i class="fa fa-file-video-o"></i>';
6151
-    if(fileName.toLowerCase().endsWith(".mp4")) fileIcon =  '<i class="fa fa-file-video-o"></i>';
6152
-    if(fileName.toLowerCase().endsWith(".mvk")) fileIcon =  '<i class="fa fa-file-video-o"></i>';
6153
-    if(fileName.toLowerCase().endsWith(".webm")) fileIcon =  '<i class="fa fa-file-video-o"></i>';
6154
-    // Audio Icons
6155
-    if(fileName.toLowerCase().endsWith(".wav")) fileIcon =  '<i class="fa fa-file-audio-o"></i>';
6156
-    if(fileName.toLowerCase().endsWith(".mp3")) fileIcon =  '<i class="fa fa-file-audio-o"></i>';
6157
-    if(fileName.toLowerCase().endsWith(".ogg")) fileIcon =  '<i class="fa fa-file-audio-o"></i>';
6158
-    // Compressed Icons
6159
-    if(fileName.toLowerCase().endsWith(".zip")) fileIcon =  '<i class="fa fa-file-archive-o"></i>';
6160
-    if(fileName.toLowerCase().endsWith(".rar")) fileIcon =  '<i class="fa fa-file-archive-o"></i>';
6161
-    if(fileName.toLowerCase().endsWith(".tar.gz")) fileIcon =  '<i class="fa fa-file-archive-o"></i>';
6162
-    // Pdf Icons
6163
-    if(fileName.toLowerCase().endsWith(".pdf")) fileIcon =  '<i class="fa fa-file-pdf-o"></i>';
6164
-
6165
-    var formattedMessage = "<DIV><SPAN id=\"FileUpload-"+ fileID +"\">Sending</SPAN>: "+ fileIcon +" "+ fileName +"</DIV>"
6166
-    formattedMessage += "<DIV id=\"FileProgress-"+ fileID +"\" class=\"progressBarContainer\"><DIV id=\"FileProgress-Bar-"+ fileID +"\" class=\"progressBarTrack\"></DIV></DIV>"
6167
-    if(showReview){
6168
-        formattedMessage += "<DIV><IMG class=previewImage onClick=\"PreviewImage(this)\" src=\""+ FileDataUrl +"\"></DIV>";
6169
-    }
6170
-
6171
-    var messageString = "<table class=\"ourChatMessage chatMessageTable\" cellspacing=0 cellpadding=0><tr><td style=\"width: 80px\">"
6172
-        + "<div class=messageDate>" + DateTime + "</div>"
6173
-        + "</td><td>"
6174
-        + "<div class=ourChatMessageText>" + formattedMessage + "</div>"
6175
-        + "</td></tr></table>";
6176
-    $("#contact-" + buddy + "-ChatHistory").append(messageString);
6177
-    updateScroll(buddy);
6178
-
6179
-    ImageEditor_Cancel(buddy);
6180
-
6181
-    // Update Last Activity
6182
-    // ====================
6183
-    UpdateBuddyActivity(buddy);
6184
-}
6185
-function updateLineScroll(lineNum) {
6186
-    RefreshLineActivity(lineNum);
6187
-
6188
-    var element = $("#line-"+ lineNum +"-CallDetails").get(0);
6189
-    element.scrollTop = element.scrollHeight;
6190
-}
6191
-function updateScroll(buddy) {
6192
-    var history = $("#contact-"+ buddy +"-ChatHistory");
6193
-    if(history.children().length > 0) history.children().last().get(0).scrollIntoView(false);
6194
-    history.get(0).scrollTop = history.get(0).scrollHeight;
6195
-}
6196
-function PreviewImage(obj){
6197
-
6198
-    $.jeegoopopup.close();
6199
-    var previewimgHtml = '<div>';
6200
-    previewimgHtml += '<div class="UiWindowField scroller">';
6201
-    previewimgHtml += '<div><img src="'+ obj.src +'"/></div>';
6202
-    previewimgHtml += '</div></div>';
6203
-
6204
-    $.jeegoopopup.open({
6205
-                title: 'Preview Image',
6206
-                html: previewimgHtml,
6207
-                width: '800',
6208
-                height: '600',
6209
-                center: true,
6210
-                scrolling: 'no',
6211
-                skinClass: 'jg_popup_basic',
6212
-                overlay: true,
6213
-                opacity: 50,
6214
-                draggable: true,
6215
-                resizable: false,
6216
-                fadeIn: 0
6217
-    });
6218
-    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); });
6219
-    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); } });
6220
-}
6221
-
6222
-// Missed Item Notification
6223
-// ========================
6224
-function IncreaseMissedBadge(buddy) {
6225
-    var buddyObj = FindBuddyByIdentity(buddy);
6226
-    if(buddyObj == null) return;
6227
-
6228
-    // Up the Missed Count
6229
-    // ===================
6230
-    buddyObj.missed += 1;
6231
-
6232
-    // Take Out
6233
-    var json = JSON.parse(localDB.getItem(profileUserID + "-Buddies"));
6234
-    if(json != null) {
6235
-        $.each(json.DataCollection, function (i, item) {
6236
-            if(item.uID == buddy || item.cID == buddy || item.gID == buddy){
6237
-                item.missed = item.missed +1;
6238
-                return false;
6239
-            }
6240
-        });
6241
-        // Put Back
6242
-        localDB.setItem(profileUserID + "-Buddies", JSON.stringify(json));
6243
-    }
6244
-
6245
-    // Update Badge
6246
-    // ============
6247
-    $("#contact-" + buddy + "-missed").text(buddyObj.missed);
6248
-    $("#contact-" + buddy + "-missed").show();
6249
-    console.log("Set Missed badge for "+ buddy +" to: "+ buddyObj.missed);
6250
-}
6251
-function UpdateBuddyActivity(buddy){
6252
-    var buddyObj = FindBuddyByIdentity(buddy);
6253
-    if(buddyObj == null) return;
6254
-
6255
-    // Update Last Activity Time
6256
-    // =========================
6257
-    var timeStamp = utcDateNow();
6258
-    buddyObj.lastActivity = timeStamp;
6259
-    console.log("Last Activity is now: "+ timeStamp);
6260
-
6261
-    // Take Out
6262
-    var json = JSON.parse(localDB.getItem(profileUserID + "-Buddies"));
6263
-    if(json != null) {
6264
-        $.each(json.DataCollection, function (i, item) {
6265
-            if(item.uID == buddy || item.cID == buddy || item.gID == buddy){
6266
-                item.LastActivity = timeStamp;
6267
-                return false;
6268
-            }
6269
-        });
6270
-        // Put Back
6271
-        localDB.setItem(profileUserID + "-Buddies", JSON.stringify(json));
6272
-    }
6273
-
6274
-    // List Update
6275
-    // ===========
6276
-    UpdateBuddyList();
6277
-}
6278
-function ClearMissedBadge(buddy) {
6279
-    var buddyObj = FindBuddyByIdentity(buddy);
6280
-    if(buddyObj == null) return;
6281
-
6282
-    buddyObj.missed = 0;
6283
-
6284
-    // Take Out
6285
-    var json = JSON.parse(localDB.getItem(profileUserID + "-Buddies"));
6286
-    if(json != null) {
6287
-        $.each(json.DataCollection, function (i, item) {
6288
-            if(item.uID == buddy || item.cID == buddy || item.gID == buddy){
6289
-                item.missed = 0;
6290
-                return false;
6291
-            }
6292
-        });
6293
-        // Put Back
6294
-        localDB.setItem(profileUserID + "-Buddies", JSON.stringify(json));
6295
-    }
6296
-
6297
-    $("#contact-" + buddy + "-missed").text(buddyObj.missed);
6298
-    $("#contact-" + buddy + "-missed").hide(400);
6299
-}
6300
-
6301
-// Outbound Calling
6302
-// ================
6303
-function VideoCall(lineObj, dialledNumber) {
6304
-    if (userAgent == null) return;
6305
-    if (!userAgent.isRegistered()) return;
6306
-    if(lineObj == null) return;
6307
-
6308
-    if(HasAudioDevice == false){
6309
-        Alert(lang.alert_no_microphone);
6310
-        return;
6311
-    }
6312
-
6313
-    if(HasVideoDevice == false){
6314
-        console.warn("No video devices (webcam) found, switching to audio call.");
6315
-        AudioCall(lineObj, dialledNumber);
6316
-        return;
6317
-    }
6318
-
6319
-    var supportedConstraints = navigator.mediaDevices.getSupportedConstraints();
6320
-    var spdOptions = {
6321
-        sessionDescriptionHandlerOptions: {
6322
-            constraints: {
6323
-                audio: { deviceId : "default" },
6324
-                video: { deviceId : "default" }
6325
-            }
6326
-        }
6327
-    }
6328
-
6329
-    // Configure Audio
6330
-    var currentAudioDevice = getAudioSrcID();
6331
-    if(currentAudioDevice != "default"){
6332
-        var confirmedAudioDevice = false;
6333
-        for (var i = 0; i < AudioinputDevices.length; ++i) {
6334
-            if(currentAudioDevice == AudioinputDevices[i].deviceId) {
6335
-                confirmedAudioDevice = true;
6336
-                break;
6337
-            }
6338
-        }
6339
-        if(confirmedAudioDevice) {
6340
-            spdOptions.sessionDescriptionHandlerOptions.constraints.audio.deviceId = { exact: currentAudioDevice }
6341
-        }
6342
-        else {
6343
-            console.warn("The audio device you used before is no longer available, default settings applied.");
6344
-            localDB.setItem("AudioSrcId", "default");
6345
-        }
6346
-    }
6347
-    // Add additional Constraints
6348
-    if(supportedConstraints.autoGainControl) {
6349
-        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.autoGainControl = AutoGainControl;
6350
-    }
6351
-    if(supportedConstraints.echoCancellation) {
6352
-        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.echoCancellation = EchoCancellation;
6353
-    }
6354
-    if(supportedConstraints.noiseSuppression) {
6355
-        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.noiseSuppression = NoiseSuppression;
6356
-    }
6357
-
6358
-    // Configure Video
6359
-    var currentVideoDevice = getVideoSrcID();
6360
-    if(currentVideoDevice != "default"){
6361
-        var confirmedVideoDevice = false;
6362
-        for (var i = 0; i < VideoinputDevices.length; ++i) {
6363
-            if(currentVideoDevice == VideoinputDevices[i].deviceId) {
6364
-                confirmedVideoDevice = true;
6365
-                break;
6366
-            }
6367
-        }
6368
-        if(confirmedVideoDevice){
6369
-            spdOptions.sessionDescriptionHandlerOptions.constraints.video.deviceId = { exact: currentVideoDevice }
6370
-        }
6371
-        else {
6372
-            console.warn("The video device you used before is no longer available, default settings applied.");
6373
-            localDB.setItem("VideoSrcId", "default"); // resets for later and subsequent calls
6374
-        }
6375
-    }
6376
-    // Add additional Constraints
6377
-    if(supportedConstraints.frameRate && maxFrameRate != "") {
6378
-        spdOptions.sessionDescriptionHandlerOptions.constraints.video.frameRate = maxFrameRate;
6379
-    }
6380
-    if(supportedConstraints.height && videoHeight != "") {
6381
-        spdOptions.sessionDescriptionHandlerOptions.constraints.video.height = videoHeight;
6382
-    }
6383
-    console.log(supportedConstraints)
6384
-    console.log(supportedConstraints.aspectRatio)
6385
-    console.log(videoAspectRatio)
6386
-    if(supportedConstraints.aspectRatio && videoAspectRatio != "") {
6387
-        spdOptions.sessionDescriptionHandlerOptions.constraints.video.aspectRatio = videoAspectRatio;
6388
-    }
6389
-
6390
-    $("#line-" + lineObj.LineNumber + "-msg").html(lang.starting_video_call);
6391
-    $("#line-" + lineObj.LineNumber + "-timer").show();
6392
-
6393
-    // Invite
6394
-    console.log("INVITE (video): " + dialledNumber + "@" + wssServer, spdOptions);
6395
-    lineObj.SipSession = userAgent.invite("sip:" + dialledNumber + "@" + wssServer, spdOptions);
6396
-
6397
-    var startTime = moment.utc();
6398
-    lineObj.SipSession.data.line = lineObj.LineNumber;
6399
-    lineObj.SipSession.data.buddyId = lineObj.BuddyObj.identity;
6400
-    lineObj.SipSession.data.calldirection = "outbound";
6401
-    lineObj.SipSession.data.dst = dialledNumber;
6402
-    lineObj.SipSession.data.callstart = startTime.format("YYYY-MM-DD HH:mm:ss UTC");
6403
-    lineObj.SipSession.data.callTimer = window.setInterval(function(){
6404
-        var now = moment.utc();
6405
-        var duration = moment.duration(now.diff(startTime)); 
6406
-        $("#line-" + lineObj.LineNumber + "-timer").html(formatShortDuration(duration.asSeconds()));
6407
-    }, 1000);
6408
-    lineObj.SipSession.data.VideoSourceDevice = getVideoSrcID();
6409
-    lineObj.SipSession.data.AudioSourceDevice = getAudioSrcID();
6410
-    lineObj.SipSession.data.AudioOutputDevice = getAudioOutputID();
6411
-    lineObj.SipSession.data.terminateby = "them";
6412
-    lineObj.SipSession.data.withvideo = true;
6413
-
6414
-    updateLineScroll(lineObj.LineNumber);
6415
-
6416
-    // Do Necessary UI Wireup
6417
-    wireupVideoSession(lineObj);
6418
-
6419
-    // Custom Web hook
6420
-    if(typeof web_hook_on_invite !== 'undefined') web_hook_on_invite(lineObj.SipSession);
6421
-}
6422
-
6423
-function ComposeEmail(buddy, obj, event) {
6424
-
6425
-        event.stopPropagation();
6426
-        SelectBuddy(buddy);
6427
-
6428
-        var buddyObj = FindBuddyByIdentity(buddy);
6429
-
6430
-	$("#roundcubeFrame").remove();
6431
-	$("#rightContent").show();
6432
-	$(".streamSelected").each(function() { $(this).css("display", "none"); });
6433
-	$("#rightContent").append('<iframe id="roundcubeFrame" name="displayFrame"></iframe>');
6434
-
6435
-	var rcDomain = '';
6436
-	var rcBasicAuthUser = '';
6437
-	var rcBasicAuthPass = '';
6438
-	var rcUsername = '';
6439
-	var rcPasswd = '';
6440
-
6441
-	$.ajax({
6442
-	     'async': false,
6443
-	     'global': false,
6444
-	     type: "POST",
6445
-	     url: "get-email-info.php",
6446
-	     dataType: "JSON",
6447
-	     data: {
6448
-		     username: userName,
6449
-		     s_ajax_call: validateSToken
6450
-	     },
6451
-	     success: function(datafromdb) {
6452
-		               rcDomain = datafromdb.rcdomain;
6453
-		               rcBasicAuthUser = encodeURIComponent(datafromdb.rcbasicauthuser);                              
6454
-		               rcBasicAuthPass = encodeURIComponent(datafromdb.rcbasicauthpass);
6455
-		               rcUsername = datafromdb.rcuser;
6456
-		               rcPasswd = datafromdb.rcpassword;
6457
-	     },
6458
-	     error: function(datafromdb) {
6459
-		             alert("An error occurred while trying to retrieve data from the database!");
6460
-	     }
6461
-	});
6462
-
6463
-	if (rcBasicAuthUser != '' && rcBasicAuthPass != '') { 
6464
-	    var loginURL = "https://"+ rcBasicAuthUser +":"+ rcBasicAuthPass +"@"+ rcDomain +"/";
6465
-            var composeURL = "https://"+ rcBasicAuthUser +":"+ rcBasicAuthPass +"@"+ rcDomain +"/?_task=mail&_action=compose&_to="+ encodeURIComponent(buddyObj.Email) +"";
6466
-	} else { 
6467
-            var loginURL = "https://"+ rcDomain +"/";
6468
-            var composeURL = "https://"+ rcDomain +"/?_task=mail&_action=compose&_to="+ encodeURIComponent(buddyObj.Email) +"";
6469
-        }
6470
-
6471
-	var form = '<form id="rcForm" method="POST" action="'+ loginURL +'" target="displayFrame">'; 
6472
-	form += '<input type="hidden" name="_action" value="login" />';
6473
-	form += '<input type="hidden" name="_task" value="login" />';
6474
-	form += '<input type="hidden" name="_autologin" value="1" />';
6475
-	form += '<input name="_user" value="'+ rcUsername +'" type="text" />';
6476
-	form += '<input name="_pass" value="'+ rcPasswd +'" type="password" />';
6477
-	form += '<input id="submitButton" type="submit" value="Login" />';
6478
-	form += '</form>';
6479
-
6480
-	$("#roundcubeFrame").append(form);
6481
-
6482
-        if (RCLoginCheck == 0) {
6483
-            $("#submitButton").click();
6484
-            RCLoginCheck = 1;
6485
-
6486
-            if (rcBasicAuthUser != '' && rcBasicAuthPass != '') {
6487
-                if (confirm('You are about to log in to the site "'+ rcDomain +'" with the username "'+ rcBasicAuthUser +'".')) {
6488
-                    $("#roundcubeFrame").attr("src", composeURL);
6489
-                }
6490
-            } else { setTimeout(function() { $("#roundcubeFrame").attr("src", composeURL); }, 1000); }
6491
-
6492
-//            setTimeout(function() { $("#roundcubeFrame").attr("src", composeURL); }, 1000);
6493
-
6494
-        } else { $("#roundcubeFrame").attr("src", composeURL); }
6495
-}
6496
-function AudioCallMenu(buddy, obj){
6497
-
6498
-    if (($(window).width() - event.pageX) > 54) { var leftPos = event.pageX - 222; } else { var leftPos = event.pageX - 276; }
6499
-    if (($(window).height() - event.pageY) > 140) { var topPos = event.pageY + 27; } else { var topPos = event.pageY - 80; }
6500
-
6501
-    var buddyObj = FindBuddyByIdentity(buddy);
6502
-
6503
-    if(buddyObj.type == "extension") {
6504
-
6505
-        // Extension
6506
-        var menu = "<div id=quickCallMenu>";
6507
-        menu += "<table id=quickCallTable cellspacing=10 cellpadding=0 style=\"margin-left:auto; margin-right: auto\">";
6508
-
6509
-        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>";
6510
-
6511
-        if (buddyObj.MobileNumber != null && buddyObj.MobileNumber != "") {
6512
-            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>";
6513
-        }
6514
-
6515
-        if (buddyObj.ContactNumber1 != null && buddyObj.ContactNumber1 != "") {
6516
-            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>";
6517
-        }
6518
-
6519
-        if (buddyObj.ContactNumber2 != null && buddyObj.ContactNumber2 != "") {
6520
-            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>";
6521
-        }
6522
-
6523
-        menu += "</table>";
6524
-        menu += "</div>";
6525
-
6526
-        var consoleLogContent = "Menu click AudioCall("+ buddy +", ";
6527
-
6528
-    } else if (buddyObj.type == "contact") {
6529
-
6530
-        // Contact
6531
-        var menu = "<div id=quickCallMenu>";
6532
-        menu += "<table id=quickCallTable cellspacing=10 cellpadding=0 style=\"margin-left:auto; margin-right: auto\">";
6533
-
6534
-        if (buddyObj.MobileNumber != null && buddyObj.MobileNumber != "") {
6535
-            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>";
6536
-        }
6537
-
6538
-        if (buddyObj.ContactNumber1 != null && buddyObj.ContactNumber1 != "") {
6539
-            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>";
6540
-        }
6541
-
6542
-        if (buddyObj.ContactNumber2 != null && buddyObj.ContactNumber2 != "") {
6543
-            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>";
6544
-        }
6545
-
6546
-        menu += "</table>";
6547
-        menu += "</div>";
6548
-
6549
-        var consoleLogContent = "Menu click AudioCall("+ buddy +", ";
6550
-
6551
-    } else if(buddyObj.type == "group") {
6552
-
6553
-        var menu = "<div id=quickCallMenu>";
6554
-        menu += "<table id=quickCallTable cellspacing=10 cellpadding=0 style=\"margin-left:auto; margin-right: auto\">";
6555
-        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>";
6556
-        menu += "</table>";
6557
-        menu += "</div>";
6558
-
6559
-        var consoleLogContent = "Menu click AudioCallGroup("+ buddy +", ";
6560
-
6561
-    }
6562
-
6563
-    $.jeegoopopup.open({
6564
-                html: menu,
6565
-                width: 'auto',
6566
-                height: 'auto',
6567
-                left: leftPos,
6568
-                top: topPos,
6569
-                scrolling: 'no',
6570
-                skinClass: 'jg_popup_basic',
6571
-                overlay: true,
6572
-                opacity: 0,
6573
-                draggable: false,
6574
-                resizable: false,
6575
-                fadeIn: 0
6576
-    });
6577
-
6578
-    $("#quickCallTable").on("click", ".quickNumDialRow", function() {
6579
-       var NumberToDial = $(this).closest("tr").find("span.quickNumToDial").html();
6580
-       console.log(consoleLogContent + NumberToDial +")");
6581
-       DialByLine("audio", buddy, NumberToDial);
6582
-    });
6583
-
6584
-    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); });
6585
-    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); } });
6586
-}
6587
-function AudioCall(lineObj, dialledNumber) {
6588
-    if(userAgent == null) return;
6589
-    if(userAgent.isRegistered() == false) return;
6590
-    if(lineObj == null) return;
6591
-
6592
-    if(HasAudioDevice == false){
6593
-        Alert(lang.alert_no_microphone);
6594
-        return;
6595
-    }
6596
-
6597
-    var supportedConstraints = navigator.mediaDevices.getSupportedConstraints();
6598
-
6599
-    var spdOptions = {
6600
-        sessionDescriptionHandlerOptions: {
6601
-            constraints: {
6602
-                audio: { deviceId : "default" },
6603
-                video: false
6604
-            }
6605
-        }
6606
-    }
6607
-    // Configure Audio
6608
-    var currentAudioDevice = getAudioSrcID();
6609
-    if(currentAudioDevice != "default"){
6610
-        var confirmedAudioDevice = false;
6611
-        for (var i = 0; i < AudioinputDevices.length; ++i) {
6612
-            if(currentAudioDevice == AudioinputDevices[i].deviceId) {
6613
-                confirmedAudioDevice = true;
6614
-                break;
6615
-            }
6616
-        }
6617
-        if(confirmedAudioDevice) {
6618
-            spdOptions.sessionDescriptionHandlerOptions.constraints.audio.deviceId = { exact: currentAudioDevice }
6619
-        }
6620
-        else {
6621
-            console.warn("The audio device you used before is no longer available, default settings applied.");
6622
-            localDB.setItem("AudioSrcId", "default");
6623
-        }
6624
-    }
6625
-    // Add additional Constraints
6626
-    if(supportedConstraints.autoGainControl) {
6627
-        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.autoGainControl = AutoGainControl;
6628
-    }
6629
-    if(supportedConstraints.echoCancellation) {
6630
-        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.echoCancellation = EchoCancellation;
6631
-    }
6632
-    if(supportedConstraints.noiseSuppression) {
6633
-        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.noiseSuppression = NoiseSuppression;
6634
-    }
6635
-
6636
-    $("#line-" + lineObj.LineNumber + "-msg").html(lang.starting_audio_call);
6637
-    $("#line-" + lineObj.LineNumber + "-timer").show();
6638
-
6639
-    // Invite
6640
-    console.log("INVITE (audio): " + dialledNumber + "@" + wssServer);
6641
-    lineObj.SipSession = userAgent.invite("sip:" + dialledNumber + "@" + wssServer, spdOptions);
6642
-
6643
-    var startTime = moment.utc();
6644
-    lineObj.SipSession.data.line = lineObj.LineNumber;
6645
-    lineObj.SipSession.data.buddyId = lineObj.BuddyObj.identity;
6646
-    lineObj.SipSession.data.calldirection = "outbound";
6647
-    lineObj.SipSession.data.dst = dialledNumber;
6648
-    lineObj.SipSession.data.callstart = startTime.format("YYYY-MM-DD HH:mm:ss UTC");
6649
-    lineObj.SipSession.data.callTimer = window.setInterval(function(){
6650
-        var now = moment.utc();
6651
-        var duration = moment.duration(now.diff(startTime)); 
6652
-        $("#line-" + lineObj.LineNumber + "-timer").html(formatShortDuration(duration.asSeconds()));
6653
-    }, 1000);
6654
-    lineObj.SipSession.data.VideoSourceDevice = null;
6655
-    lineObj.SipSession.data.AudioSourceDevice = getAudioSrcID();
6656
-    lineObj.SipSession.data.AudioOutputDevice = getAudioOutputID();
6657
-    lineObj.SipSession.data.terminateby = "them";
6658
-    lineObj.SipSession.data.withvideo = false;
6659
-
6660
-    updateLineScroll(lineObj.LineNumber);
6661
-
6662
-    // Do Necessary UI Wireup
6663
-    wireupAudioSession(lineObj);
6664
-
6665
-    // Custom Web hook
6666
-    if(typeof web_hook_on_invite !== 'undefined') web_hook_on_invite(lineObj.SipSession);
6667
-}
6668
-
6669
-// Sessions & During Call Activity
6670
-// ===============================
6671
-function getSession(buddy) {
6672
-    if(userAgent == null) {
6673
-        console.warn("userAgent is null");
6674
-        return;
6675
-    }
6676
-    if(userAgent.isRegistered() == false) {
6677
-        console.warn("userAgent is not registered");
6678
-        return;
6679
-    }
6680
-
6681
-    var rtnSession = null;
6682
-    $.each(userAgent.sessions, function (i, session) {
6683
-        if(session.data.buddyId == buddy) {
6684
-           rtnSession = session;
6685
-           return false;
6686
-        }
6687
-    });
6688
-    return rtnSession;
6689
-}
6690
-function countSessions(id){
6691
-    var rtn = 0;
6692
-    if(userAgent == null) {
6693
-       console.warn("userAgent is null");
6694
-       return 0;
6695
-    }
6696
-    $.each(userAgent.sessions, function (i, session) {
6697
-        if(id != session.id) rtn ++;
6698
-    });
6699
-    return rtn;
6700
-}
6701
-function StartRecording(lineNum){
6702
-    if(CallRecordingPolicy == "disabled") {
6703
-        console.warn("Policy Disabled: Call Recording");
6704
-        return;
6705
-    }
6706
-    var lineObj = FindLineByNumber(lineNum);
6707
-    if(lineObj == null) return;
6708
-
6709
-    $("#line-"+ lineObj.LineNumber +"-btn-start-recording").hide();
6710
-    $("#line-"+ lineObj.LineNumber +"-btn-stop-recording").show();
6711
-
6712
-    var session = lineObj.SipSession;
6713
-    if(session == null){
6714
-        console.warn("Could not find session");
6715
-        return;
6716
-    }
6717
-
6718
-    var id = uID();
6719
-
6720
-    if(!session.data.recordings) session.data.recordings = [];
6721
-    session.data.recordings.push({
6722
-        uID: id,
6723
-        startTime: utcDateNow(),
6724
-        stopTime: utcDateNow(),
6725
-    });
6726
-
6727
-    if(!session.data.mediaRecorder){
6728
-        console.log("Creating call recorder...");
6729
-        var recordStream = new MediaStream();
6730
-        var pc = session.sessionDescriptionHandler.peerConnection;
6731
-        pc.getSenders().forEach(function (RTCRtpSender) {
6732
-            if(RTCRtpSender.track && RTCRtpSender.track.kind == "audio") {
6733
-                console.log("Adding sender audio track to record:", RTCRtpSender.track.label);
6734
-                recordStream.addTrack(RTCRtpSender.track);
6735
-            }
6736
-        });
6737
-        pc.getReceivers().forEach(function (RTCRtpReceiver) {
6738
-            if(RTCRtpReceiver.track && RTCRtpReceiver.track.kind == "audio") {
6739
-                console.log("Adding receiver audio track to record:", RTCRtpReceiver.track.label);
6740
-                recordStream.addTrack(RTCRtpReceiver.track);
6741
-            }
6742
-            if(session.data.withvideo){
6743
-                if(RTCRtpReceiver.track && RTCRtpReceiver.track.kind == "video") {
6744
-                    console.log("Adding receiver video track to record:", RTCRtpReceiver.track.label);
6745
-                    recordStream.addTrack(RTCRtpReceiver.track);
6746
-                }
6747
-            }
6748
-        });
6749
-
6750
-        // Resample the Video Recording
6751
-        if(session.data.withvideo){
6752
-            var recordingWidth = 640;
6753
-            var recordingHeight = 360;
6754
-            var pnpVideSize = 100;
6755
-            if(RecordingVideoSize == "HD"){
6756
-                recordingWidth = 1280;
6757
-                recordingHeight = 720;
6758
-                pnpVideSize = 144;
6759
-            }
6760
-            if(RecordingVideoSize == "FHD"){
6761
-                recordingWidth = 1920;
6762
-                recordingHeight = 1080;
6763
-                pnpVideSize = 240;
6764
-            }
6765
-
6766
-            // them-pnp
6767
-            var pnpVideo = $("#line-" + lineObj.LineNumber + "-localVideo").get(0);
6768
-            var mainVideo = $("#line-" + lineObj.LineNumber + "-remoteVideo").get(0);
6769
-            if(RecordingLayout == "us-pnp"){
6770
-                pnpVideo = $("#line-" + lineObj.LineNumber + "-remoteVideo").get(0);
6771
-                mainVideo = $("#line-" + lineObj.LineNumber + "-localVideo").get(0);
6772
-            }
6773
-            var recordingCanvas = $('<canvas/>').get(0);
6774
-            recordingCanvas.width = (RecordingLayout == "side-by-side")? (recordingWidth * 2) + 5: recordingWidth;
6775
-            recordingCanvas.height = recordingHeight;
6776
-            var recordingContext = recordingCanvas.getContext("2d");
6777
-
6778
-            window.clearInterval(session.data.recordingRedrawInterval);
6779
-            session.data.recordingRedrawInterval = window.setInterval(function(){
6780
-
6781
-                // Main Video
6782
-                var videoWidth = (mainVideo.videoWidth > 0)? mainVideo.videoWidth : recordingWidth ;
6783
-                var videoHeight = (mainVideo.videoHeight > 0)? mainVideo.videoHeight : recordingHeight ;
6784
-
6785
-                if(videoWidth >= videoHeight){
6786
-                    // Landscape / Square
6787
-                    var scale = recordingWidth / videoWidth;
6788
-                    videoWidth = recordingWidth;
6789
-                    videoHeight = videoHeight * scale;
6790
-                    if(videoHeight > recordingHeight){
6791
-                        var scale = recordingHeight / videoHeight;
6792
-                        videoHeight = recordingHeight;
6793
-                        videoWidth = videoWidth * scale;
6794
-                    }
6795
-                } 
6796
-                else {
6797
-                    // Portrait
6798
-                    var scale = recordingHeight / videoHeight;
6799
-                    videoHeight = recordingHeight;
6800
-                    videoWidth = videoWidth * scale;
6801
-                }
6802
-                var offsetX = (videoWidth < recordingWidth)? (recordingWidth - videoWidth) / 2 : 0;
6803
-                var offsetY = (videoHeight < recordingHeight)? (recordingHeight - videoHeight) / 2 : 0;
6804
-                if(RecordingLayout == "side-by-side") offsetX = recordingWidth + 5 + offsetX;
6805
-
6806
-                // Picture-in-Picture Video
6807
-                var pnpVideoHeight = pnpVideo.videoHeight;
6808
-                var pnpVideoWidth = pnpVideo.videoWidth;
6809
-                if(pnpVideoHeight > 0){
6810
-                    if(pnpVideoWidth >= pnpVideoHeight){
6811
-                        var scale = pnpVideSize / pnpVideoHeight;
6812
-                        pnpVideoHeight = pnpVideSize;
6813
-                        pnpVideoWidth = pnpVideoWidth * scale;
6814
-                    } 
6815
-                    else{
6816
-                        var scale = pnpVideSize / pnpVideoWidth;
6817
-                        pnpVideoWidth = pnpVideSize;
6818
-                        pnpVideoHeight = pnpVideoHeight * scale;
6819
-                    }
6820
-                }
6821
-                var pnpOffsetX = 10;
6822
-                var pnpOffsetY = 10;
6823
-                if(RecordingLayout == "side-by-side"){
6824
-                    pnpVideoWidth = pnpVideo.videoWidth;
6825
-                    pnpVideoHeight = pnpVideo.videoHeight;
6826
-                    if(pnpVideoWidth >= pnpVideoHeight){
6827
-                        // Landscape / Square
6828
-                        var scale = recordingWidth / pnpVideoWidth;
6829
-                        pnpVideoWidth = recordingWidth;
6830
-                        pnpVideoHeight = pnpVideoHeight * scale;
6831
-                        if(pnpVideoHeight > recordingHeight){
6832
-                            var scale = recordingHeight / pnpVideoHeight;
6833
-                            pnpVideoHeight = recordingHeight;
6834
-                            pnpVideoWidth = pnpVideoWidth * scale;
6835
-                        }
6836
-                    } 
6837
-                    else {
6838
-                        // Portrait
6839
-                        var scale = recordingHeight / pnpVideoHeight;
6840
-                        pnpVideoHeight = recordingHeight;
6841
-                        pnpVideoWidth = pnpVideoWidth * scale;
6842
-                    }
6843
-                    pnpOffsetX = (pnpVideoWidth < recordingWidth)? (recordingWidth - pnpVideoWidth) / 2 : 0;
6844
-                    pnpOffsetY = (pnpVideoHeight < recordingHeight)? (recordingHeight - pnpVideoHeight) / 2 : 0;
6845
-                }
6846
-
6847
-                // Draw Elements
6848
-                recordingContext.fillRect(0, 0, recordingCanvas.width, recordingCanvas.height);
6849
-                if(mainVideo.videoHeight > 0){
6850
-                    recordingContext.drawImage(mainVideo, offsetX, offsetY, videoWidth, videoHeight);
6851
-                }
6852
-                if(pnpVideo.videoHeight > 0 && (RecordingLayout == "side-by-side" || RecordingLayout == "us-pnp" || RecordingLayout == "them-pnp")){
6853
-                    // Only Draw the Pnp Video when needed
6854
-                    recordingContext.drawImage(pnpVideo, pnpOffsetX, pnpOffsetY, pnpVideoWidth, pnpVideoHeight);
6855
-                }
6856
-            }, Math.floor(1000/RecordingVideoFps));
6857
-            var recordingVideoMediaStream = recordingCanvas.captureStream(RecordingVideoFps);
6858
-        }
6859
-
6860
-        var mixedAudioVideoRecordStream = new MediaStream();
6861
-        mixedAudioVideoRecordStream.addTrack(MixAudioStreams(recordStream).getAudioTracks()[0]);
6862
-        if(session.data.withvideo){
6863
-           mixedAudioVideoRecordStream.addTrack(recordingVideoMediaStream.getVideoTracks()[0]);
6864
-        }
6865
-
6866
-        var mediaType = "audio/webm";
6867
-        if(session.data.withvideo) mediaType = "video/webm";
6868
-        var options = {
6869
-            mimeType : mediaType
6870
-        }
6871
-        var mediaRecorder = new MediaRecorder(mixedAudioVideoRecordStream, options);
6872
-        mediaRecorder.data = {}
6873
-        mediaRecorder.data.id = ""+ id;
6874
-        mediaRecorder.data.sessionId = ""+ session.id;
6875
-        mediaRecorder.data.buddyId = ""+ lineObj.BuddyObj.identity;
6876
-        mediaRecorder.ondataavailable = function(event) {
6877
-            console.log("Got Call Recording Data: ", event.data.size +"Bytes", this.data.id, this.data.buddyId, this.data.sessionId);
6878
-            // Save the Audio/Video file
6879
-            SaveCallRecording(event.data, this.data.id, this.data.buddyId, this.data.sessionId);
6880
-        }
6881
-
6882
-        console.log("Starting Call Recording", id);
6883
-        session.data.mediaRecorder = mediaRecorder;
6884
-        session.data.mediaRecorder.start(); // Safari does not support timeslice
6885
-        session.data.recordings[session.data.recordings.length-1].startTime = utcDateNow();
6886
-
6887
-        $("#line-" + lineObj.LineNumber + "-msg").html(lang.call_recording_started);
6888
-
6889
-        updateLineScroll(lineNum);
6890
-    }
6891
-    else if(session.data.mediaRecorder.state == "inactive") {
6892
-        session.data.mediaRecorder.data = {}
6893
-        session.data.mediaRecorder.data.id = ""+ id;
6894
-        session.data.mediaRecorder.data.sessionId = ""+ session.id;
6895
-        session.data.mediaRecorder.data.buddyId = ""+ lineObj.BuddyObj.identity;
6896
-
6897
-        console.log("Starting Call Recording", id);
6898
-        session.data.mediaRecorder.start();
6899
-        session.data.recordings[session.data.recordings.length-1].startTime = utcDateNow();
6900
-
6901
-        $("#line-" + lineObj.LineNumber + "-msg").html(lang.call_recording_started);
6902
-
6903
-        updateLineScroll(lineNum);
6904
-    } 
6905
-    else {
6906
-        console.warn("Recorder is in an unknown state");
6907
-    }
6908
-}
6909
-function SaveCallRecording(blob, id, buddy, sessionid){
6910
-    var indexedDB = window.indexedDB;
6911
-    var request = indexedDB.open("CallRecordings");
6912
-    request.onerror = function(event) {
6913
-        console.error("IndexDB Request Error:", event);
6914
-    }
6915
-    request.onupgradeneeded = function(event) {
6916
-        console.warn("Upgrade Required for IndexDB... probably because of first time use.");
6917
-        var IDB = event.target.result;
6918
-
6919
-        // Create Object Store
6920
-        if(IDB.objectStoreNames.contains("Recordings") == false){
6921
-            var objectStore = IDB.createObjectStore("Recordings", { keyPath: "uID" });
6922
-            objectStore.createIndex("sessionid", "sessionid", { unique: false });
6923
-            objectStore.createIndex("bytes", "bytes", { unique: false });
6924
-            objectStore.createIndex("type", "type", { unique: false });
6925
-            objectStore.createIndex("mediaBlob", "mediaBlob", { unique: false });
6926
-        }
6927
-        else {
6928
-            console.warn("IndexDB requested upgrade, but object store was in place");
6929
-        }
6930
-    }
6931
-    request.onsuccess = function(event) {
6932
-        console.log("IndexDB connected to CallRecordings");
6933
-
6934
-        var IDB = event.target.result;
6935
-        if(IDB.objectStoreNames.contains("Recordings") == false){
6936
-            console.warn("IndexDB CallRecordings.Recordings does not exists");
6937
-            return;
6938
-        }
6939
-        IDB.onerror = function(event) {
6940
-            console.error("IndexDB Error:", event);
6941
-        }
6942
-    
6943
-        // Prepare data to write
6944
-        var data = {
6945
-            uID: id,
6946
-            sessionid: sessionid,
6947
-            bytes: blob.size,
6948
-            type: blob.type,
6949
-            mediaBlob: blob
6950
-        }
6951
-        // Commit Transaction
6952
-        var transaction = IDB.transaction(["Recordings"], "readwrite");
6953
-        var objectStoreAdd = transaction.objectStore("Recordings").add(data);
6954
-        objectStoreAdd.onsuccess = function(event) {
6955
-            console.log("Call Recording Sucess: ", id, blob.size, blob.type, buddy, sessionid);
6956
-        }
6957
-    }
6958
-}
6959
-function StopRecording(lineNum, noConfirm){
6960
-    var lineObj = FindLineByNumber(lineNum);
6961
-    if(lineObj == null || lineObj.SipSession == null) return;
6962
-
6963
-    var session = lineObj.SipSession;
6964
-    if(noConfirm == true){
6965
-        // Called at the end of a call
6966
-        $("#line-"+ lineObj.LineNumber +"-btn-start-recording").show();
6967
-        $("#line-"+ lineObj.LineNumber +"-btn-stop-recording").hide();
6968
-
6969
-        if(session.data.mediaRecorder){
6970
-            if(session.data.mediaRecorder.state == "recording"){
6971
-                console.log("Stopping Call Recording");
6972
-                session.data.mediaRecorder.stop();
6973
-                session.data.recordings[session.data.recordings.length-1].stopTime = utcDateNow();
6974
-                window.clearInterval(session.data.recordingRedrawInterval);
6975
-
6976
-                $("#line-" + lineObj.LineNumber + "-msg").html(lang.call_recording_stopped);
6977
-
6978
-                updateLineScroll(lineNum);
6979
-            } 
6980
-            else{
6981
-                console.warn("Recorder is in an unknow state");
6982
-            }
6983
-        }
6984
-        return;
6985
-    } 
6986
-    else {
6987
-        // User attempts to end call recording
6988
-        if(CallRecordingPolicy == "enabled"){
6989
-            console.log("Policy Enabled: Call Recording");
6990
-        }
6991
-
6992
-        Confirm(lang.confirm_stop_recording, lang.stop_recording, function(){
6993
-            $("#line-"+ lineObj.LineNumber +"-btn-start-recording").show();
6994
-            $("#line-"+ lineObj.LineNumber +"-btn-stop-recording").hide();
6995
-    
6996
-            if(session.data.mediaRecorder){
6997
-                if(session.data.mediaRecorder.state == "recording"){
6998
-                    console.log("Stopping Call Recording");
6999
-                    session.data.mediaRecorder.stop();
7000
-                    session.data.recordings[session.data.recordings.length-1].stopTime = utcDateNow();
7001
-                    window.clearInterval(session.data.recordingRedrawInterval);
7002
-
7003
-                    $("#line-" + lineObj.LineNumber + "-msg").html(lang.call_recording_stopped);
7004
-
7005
-                    updateLineScroll(lineNum);
7006
-                }
7007
-                else{
7008
-                    console.warn("Recorder is in an unknow state");
7009
-                }
7010
-            }
7011
-        });
7012
-    }
7013
-}
7014
-function PlayAudioCallRecording(obj, cdrId, uID){
7015
-    var container = $(obj).parent();
7016
-    container.empty();
7017
-
7018
-    var audioObj = new Audio();
7019
-    audioObj.autoplay = false;
7020
-    audioObj.controls = true;
7021
-
7022
-    // Make sure you are playing out via the correct device
7023
-    var sinkId = getAudioOutputID();
7024
-    if (typeof audioObj.sinkId !== 'undefined') {
7025
-        audioObj.setSinkId(sinkId).then(function(){
7026
-            console.log("sinkId applied: "+ sinkId);
7027
-        }).catch(function(e){
7028
-            console.warn("Error using setSinkId: ", e);
7029
-        });
7030
-    } else {
7031
-        console.warn("setSinkId() is not possible using this browser.")
7032
-    }
7033
-
7034
-    container.append(audioObj);
7035
-
7036
-    // Get Call Recording
7037
-    var indexedDB = window.indexedDB;
7038
-    var request = indexedDB.open("CallRecordings");
7039
-    request.onerror = function(event) {
7040
-        console.error("IndexDB Request Error:", event);
7041
-    }
7042
-    request.onupgradeneeded = function(event) {
7043
-        console.warn("Upgrade Required for IndexDB... probably because of first time use.");
7044
-    }
7045
-    request.onsuccess = function(event) {
7046
-        console.log("IndexDB connected to CallRecordings");
7047
-
7048
-        var IDB = event.target.result;
7049
-        if(IDB.objectStoreNames.contains("Recordings") == false){
7050
-            console.warn("IndexDB CallRecordings.Recordings does not exists");
7051
-            return;
7052
-        } 
7053
-
7054
-        var transaction = IDB.transaction(["Recordings"]);
7055
-        var objectStoreGet = transaction.objectStore("Recordings").get(uID);
7056
-        objectStoreGet.onerror = function(event) {
7057
-            console.error("IndexDB Get Error:", event);
7058
-        }
7059
-        objectStoreGet.onsuccess = function(event) {
7060
-            $("#cdr-media-meta-size-"+ cdrId +"-"+ uID).html(" Size: "+ formatBytes(event.target.result.bytes));
7061
-            $("#cdr-media-meta-codec-"+ cdrId +"-"+ uID).html(" Codec: "+ event.target.result.type);
7062
-
7063
-            // Play
7064
-            audioObj.src = window.URL.createObjectURL(event.target.result.mediaBlob);
7065
-            audioObj.oncanplaythrough = function(){
7066
-                audioObj.play().then(function(){
7067
-                    console.log("Playback started");
7068
-                }).catch(function(e){
7069
-                    console.error("Error playing back file: ", e);
7070
-                });
7071
-            }
7072
-        }
7073
-    }
7074
-}
7075
-function PlayVideoCallRecording(obj, cdrId, uID, buddy){
7076
-    var container = $(obj).parent();
7077
-    container.empty();
7078
-
7079
-    var videoObj = $("<video>").get(0);
7080
-    videoObj.id = "callrecording-video-"+ cdrId;
7081
-    videoObj.autoplay = false;
7082
-    videoObj.controls = true;
7083
-    videoObj.ontimeupdate = function(event){
7084
-        $("#cdr-video-meta-width-"+ cdrId +"-"+ uID).html(lang.width + " : "+ event.target.videoWidth +"px");
7085
-        $("#cdr-video-meta-height-"+ cdrId +"-"+ uID).html(lang.height +" : "+ event.target.videoHeight +"px");
7086
-    }
7087
-
7088
-    var sinkId = getAudioOutputID();
7089
-    if (typeof videoObj.sinkId !== 'undefined') {
7090
-        videoObj.setSinkId(sinkId).then(function(){
7091
-            console.log("sinkId applied: "+ sinkId);
7092
-        }).catch(function(e){
7093
-            console.warn("Error using setSinkId: ", e);
7094
-        });
7095
-    } else {
7096
-        console.warn("setSinkId() is not possible using this browser.")
7097
-    }
7098
-
7099
-    container.append(videoObj);
7100
-
7101
-    // Get Call Recording
7102
-    var indexedDB = window.indexedDB;
7103
-    var request = indexedDB.open("CallRecordings");
7104
-    request.onerror = function(event) {
7105
-        console.error("IndexDB Request Error:", event);
7106
-    }
7107
-    request.onupgradeneeded = function(event) {
7108
-        console.warn("Upgrade Required for IndexDB... probably because of first time use.");
7109
-    }
7110
-    request.onsuccess = function(event) {
7111
-        console.log("IndexDB connected to CallRecordings");
7112
-
7113
-        var IDB = event.target.result;
7114
-        if(IDB.objectStoreNames.contains("Recordings") == false){
7115
-            console.warn("IndexDB CallRecordings.Recordings does not exists");
7116
-            return;
7117
-        } 
7118
-
7119
-        var transaction = IDB.transaction(["Recordings"]);
7120
-        var objectStoreGet = transaction.objectStore("Recordings").get(uID);
7121
-        objectStoreGet.onerror = function(event) {
7122
-            console.error("IndexDB Get Error:", event);
7123
-        }
7124
-        objectStoreGet.onsuccess = function(event) {
7125
-            $("#cdr-media-meta-size-"+ cdrId +"-"+ uID).html(" Size: "+ formatBytes(event.target.result.bytes));
7126
-            $("#cdr-media-meta-codec-"+ cdrId +"-"+ uID).html(" Codec: "+ event.target.result.type);
7127
-
7128
-            // Play
7129
-            videoObj.src = window.URL.createObjectURL(event.target.result.mediaBlob);
7130
-            videoObj.oncanplaythrough = function(){
7131
-                try{
7132
-                    videoObj.scrollIntoViewIfNeeded(false);
7133
-                } catch(e){}
7134
-                videoObj.play().then(function(){
7135
-                    console.log("Playback started");
7136
-                }).catch(function(e){
7137
-                    console.error("Error playing back file: ", e);
7138
-                });
7139
-
7140
-                // Create a Post Image after a second
7141
-                if(buddy){
7142
-                    window.setTimeout(function(){
7143
-                        var canvas = $("<canvas>").get(0);
7144
-                        var videoWidth = videoObj.videoWidth;
7145
-                        var videoHeight = videoObj.videoHeight;
7146
-                        if(videoWidth > videoHeight){
7147
-                            // Landscape
7148
-                            if(videoHeight > 225){
7149
-                                var p = 225 / videoHeight;
7150
-                                videoHeight = 225;
7151
-                                videoWidth = videoWidth * p;
7152
-                            }
7153
-                        }
7154
-                        else {
7155
-                            // Portrait
7156
-                            if(videoHeight > 225){
7157
-                                var p = 225 / videoWidth;
7158
-                                videoWidth = 225;
7159
-                                videoHeight = videoHeight * p;
7160
-                            }
7161
-                        }
7162
-                        canvas.width = videoWidth;
7163
-                        canvas.height = videoHeight;
7164
-                        canvas.getContext('2d').drawImage(videoObj, 0, 0, videoWidth, videoHeight);  
7165
-                        canvas.toBlob(function(blob) {
7166
-                            var reader = new FileReader();
7167
-                            reader.readAsDataURL(blob);
7168
-                            reader.onloadend = function() {
7169
-                                var Poster = { width: videoWidth, height: videoHeight, posterBase64: reader.result }
7170
-                                console.log("Capturing Video Poster...");
7171
-    
7172
-                                // Update DB
7173
-                                var currentStream = JSON.parse(localDB.getItem(buddy + "-stream"));
7174
-                                if(currentStream != null || currentStream.DataCollection != null){
7175
-                                    $.each(currentStream.DataCollection, function(i, item) {
7176
-                                        if (item.ItemType == "CDR" && item.CdrId == cdrId) {
7177
-                                            // Found
7178
-                                            if(item.Recordings && item.Recordings.length >= 1){
7179
-                                                $.each(item.Recordings, function(r, recording) {
7180
-                                                    if(recording.uID == uID) recording.Poster = Poster;
7181
-                                                });
7182
-                                            }
7183
-                                            return false;
7184
-                                        }
7185
-                                    });
7186
-                                    localDB.setItem(buddy + "-stream", JSON.stringify(currentStream));
7187
-                                    console.log("Capturing Video Poster, Done");
7188
-                                }
7189
-                            }
7190
-                        }, 'image/jpeg', PosterJpegQuality);
7191
-                    }, 1000);
7192
-                }
7193
-            }
7194
-        }
7195
-    }
7196
-}
7197
-
7198
-// Stream Manipulations
7199
-// ====================
7200
-function MixAudioStreams(MultiAudioTackStream){
7201
-    // Takes in a MediaStream with any number of audio tracks and mixes them together
7202
-
7203
-    var audioContext = null;
7204
-    try {
7205
-        window.AudioContext = window.AudioContext || window.webkitAudioContext;
7206
-        audioContext = new AudioContext();
7207
-    }
7208
-    catch(e){
7209
-        console.warn("AudioContext() not available, cannot record");
7210
-        return MultiAudioTackStream;
7211
-    }
7212
-    var mixedAudioStream = audioContext.createMediaStreamDestination();
7213
-    MultiAudioTackStream.getAudioTracks().forEach(function(audioTrack){
7214
-        var srcStream = new MediaStream();
7215
-        srcStream.addTrack(audioTrack);
7216
-        var streamSourceNode = audioContext.createMediaStreamSource(srcStream);
7217
-        streamSourceNode.connect(mixedAudioStream);
7218
-    });
7219
-
7220
-    return mixedAudioStream.stream;
7221
-}
7222
-
7223
-// Call Transfer & Conference
7224
-// ============================
7225
-function QuickFindBuddy(obj){
7226
-
7227
-    $.jeegoopopup.close();
7228
-
7229
-    var leftPos = obj.offsetWidth + 178;
7230
-    var topPos = obj.offsetHeight + 68;
7231
-
7232
-    if($(window).width() < 1467) {
7233
-        topPos = obj.offsetHeight + 164;
7234
-        if ($(window).width() < 918) {
7235
-            leftPos = obj.offsetWidth - 140;
7236
-            if($(window).width() < 690) {
7237
-               leftPos = obj.offsetWidth - 70;
7238
-               topPos = obj.offsetHeight + 164;
7239
-            }
7240
-        }
7241
-    }
7242
-
7243
-    var filter = obj.value;
7244
-    if(filter == "") return;
7245
-
7246
-    console.log("Find Buddy: ", filter);
7247
-
7248
-    Buddies.sort(function(a, b){
7249
-        if(a.CallerIDName < b.CallerIDName) return -1;
7250
-        if(a.CallerIDName > b.CallerIDName) return 1;
7251
-        return 0;
7252
-    });
7253
-
7254
-    var visibleItems = 0;
7255
-
7256
-    var menu = "<div id=\"quickSearchBuddy\">";
7257
-    menu += "<table id=\"quickSearchBdTable\" cellspacing=10 cellpadding=0 style=\"margin-left:auto; margin-right: auto\">";
7258
-
7259
-    for(var b = 0; b < Buddies.length; b++){
7260
-        var buddyObj = Buddies[b];
7261
-
7262
-        // Perform Filter Display
7263
-        var display = false;
7264
-        if(buddyObj.CallerIDName.toLowerCase().indexOf(filter.toLowerCase()) > -1) display = true;
7265
-        if(buddyObj.ExtNo.toLowerCase().indexOf(filter.toLowerCase()) > -1) display = true;
7266
-        if(buddyObj.Desc.toLowerCase().indexOf(filter.toLowerCase()) > -1) display = true;
7267
-        if(buddyObj.MobileNumber.toLowerCase().indexOf(filter.toLowerCase()) > -1) display = true;
7268
-        if(buddyObj.ContactNumber1.toLowerCase().indexOf(filter.toLowerCase()) > -1) display = true;
7269
-        if(buddyObj.ContactNumber2.toLowerCase().indexOf(filter.toLowerCase()) > -1) display = true;
7270
-        if(display) {
7271
-            // Filtered Results
7272
-            var iconColor = "#404040";
7273
-            if(buddyObj.presence == "Unknown" || buddyObj.presence == "Not online" || buddyObj.presence == "Unavailable") iconColor = "#666666";
7274
-            if(buddyObj.presence == "Ready") iconColor = "#3fbd3f";
7275
-            if(buddyObj.presence == "On the phone" || buddyObj.presence == "Ringing" || buddyObj.presence == "On hold") iconColor = "#c99606";
7276
-
7277
-            menu += "<tr class=\"quickFindBdTagRow\"><td></td><td><b>"+ buddyObj.CallerIDName +"</b></td><td></td></tr>";
7278
-
7279
-            if (buddyObj.ExtNo != "") {
7280
-                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>";
7281
-            }
7282
-            if (buddyObj.MobileNumber != "") {
7283
-                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>";
7284
-            }
7285
-
7286
-            if (buddyObj.ContactNumber1 != "") {
7287
-                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>";
7288
-            }
7289
-            if (buddyObj.ContactNumber2 != "") {
7290
-                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>";
7291
-            }
7292
-
7293
-            visibleItems++;
7294
-        }
7295
-        if(visibleItems >= 5) break;
7296
-    }
7297
-
7298
-    menu += "</table></div>";
7299
-
7300
-    if(menu.length > 1) {
7301
-       $.jeegoopopup.open({
7302
-                html: menu,
7303
-                width: 'auto',
7304
-                height: 'auto',
7305
-                left: leftPos,
7306
-                top: topPos,
7307
-                scrolling: 'no',
7308
-                skinClass: 'jg_popup_basic',
7309
-                overlay: true,
7310
-                opacity: 0,
7311
-                draggable: false,
7312
-                resizable: false,
7313
-                fadeIn: 0
7314
-       });
7315
-
7316
-       $("#jg_popup_inner").focus();
7317
-       $("#jg_popup_inner #jg_popup_content #quickSearchBuddy #quickSearchBdTable").on("click", ".quickFindBdRow", function() {
7318
-
7319
-          var quickFoundNum = $(this).closest("tr").find("span.quickNumFound").html();
7320
-
7321
-          $.jeegoopopup.close();
7322
-          $(document).find("input[id*='-txt-FindTransferBuddy']").focus();
7323
-          $(document).find("input[id*='-txt-FindTransferBuddy']").val(quickFoundNum);
7324
-       });
7325
-
7326
-       $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); });
7327
-       $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); } });
7328
-    }
7329
-}
7330
-
7331
-// Call Transfer
7332
-// =============
7333
-function StartTransferSession(lineNum){
7334
-    $("#line-"+ lineNum +"-btn-Transfer").hide();
7335
-    $("#line-"+ lineNum +"-btn-CancelTransfer").show();
7336
-
7337
-    holdSession(lineNum);
7338
-    $("#line-"+ lineNum +"-txt-FindTransferBuddy").val("");
7339
-    $("#line-"+ lineNum +"-txt-FindTransferBuddy").parent().show();
7340
-
7341
-    $("#line-"+ lineNum +"-btn-blind-transfer").show();
7342
-    $("#line-"+ lineNum +"-btn-attended-transfer").show();
7343
-    $("#line-"+ lineNum +"-btn-complete-transfer").hide();
7344
-    $("#line-"+ lineNum +"-btn-cancel-transfer").hide();
7345
-
7346
-    $("#line-"+ lineNum +"-transfer-status").hide();
7347
-
7348
-    $("#line-"+ lineNum +"-Transfer").show();
7349
-
7350
-    updateLineScroll(lineNum);
7351
-}
7352
-function CancelTransferSession(lineNum){
7353
-    var lineObj = FindLineByNumber(lineNum);
7354
-    if(lineObj == null || lineObj.SipSession == null){
7355
-        console.warn("Null line or session");
7356
-        return;
7357
-    }
7358
-    var session = lineObj.SipSession;
7359
-    if(session.data.childsession){
7360
-        console.log("Child Transfer call detected:", session.data.childsession.status)
7361
-        try{
7362
-            if(session.data.childsession.status == SIP.Session.C.STATUS_CONFIRMED){
7363
-                session.data.childsession.bye();
7364
-            } 
7365
-            else{
7366
-                session.data.childsession.cancel();
7367
-            }
7368
-        } catch(e){}
7369
-    }
7370
-
7371
-    $("#line-"+ lineNum +"-btn-Transfer").show();
7372
-    $("#line-"+ lineNum +"-btn-CancelTransfer").hide();
7373
-
7374
-    unholdSession(lineNum);
7375
-    $("#line-"+ lineNum +"-Transfer").hide();
7376
-
7377
-    updateLineScroll(lineNum);
7378
-}
7379
-function BlindTransfer(lineNum) {
7380
-    var dstNo = $("#line-"+ lineNum +"-txt-FindTransferBuddy").val().replace(/[^0-9\*\#\+]/g,'');
7381
-    if(dstNo == ""){
7382
-        console.warn("Cannot transfer, must be [0-9*+#]");
7383
-        return;
7384
-    }
7385
-
7386
-    var lineObj = FindLineByNumber(lineNum);
7387
-    if(lineObj == null || lineObj.SipSession == null){
7388
-        console.warn("Null line or session");
7389
-        return;
7390
-    }
7391
-    var session = lineObj.SipSession;
7392
-
7393
-    if(!session.data.transfer) session.data.transfer = [];
7394
-    session.data.transfer.push({ 
7395
-        type: "Blind", 
7396
-        to: dstNo, 
7397
-        transferTime: utcDateNow(), 
7398
-        disposition: "refer",
7399
-        dispositionTime: utcDateNow(), 
7400
-        accept : {
7401
-            complete: null,
7402
-            eventTime: null,
7403
-            disposition: ""
7404
-        }
7405
-    });
7406
-    var transferid = session.data.transfer.length-1;
7407
-
7408
-    var transferOptions  = { 
7409
-        receiveResponse: function doReceiveResponse(response){
7410
-            console.log("Blind transfer response: ", response.reason_phrase);
7411
-
7412
-            session.data.terminateby = "refer";
7413
-            session.data.transfer[transferid].accept.disposition = response.reason_phrase;
7414
-            session.data.transfer[transferid].accept.eventTime = utcDateNow();
7415
-
7416
-            $("#line-" + lineNum + "-msg").html("Call Blind Transfered (Accepted)");
7417
-
7418
-            updateLineScroll(lineNum);
7419
-        }
7420
-    }
7421
-    console.log("REFER: ", dstNo + "@" + wssServer);
7422
-    session.refer("sip:" + dstNo + "@" + wssServer, transferOptions);
7423
-    $("#line-" + lineNum + "-msg").html(lang.call_blind_transfered);
7424
-
7425
-    updateLineScroll(lineNum);
7426
-}
7427
-function AttendedTransfer(lineNum){
7428
-    var dstNo = $("#line-"+ lineNum +"-txt-FindTransferBuddy").val().replace(/[^0-9\*\#\+]/g,'');
7429
-    if(dstNo == ""){
7430
-        console.warn("Cannot transfer, must be [0-9*+#]");
7431
-        return;
7432
-    }
7433
-    
7434
-    var lineObj = FindLineByNumber(lineNum);
7435
-    if(lineObj == null || lineObj.SipSession == null){
7436
-        console.warn("Null line or session");
7437
-        return;
7438
-    }
7439
-    var session = lineObj.SipSession;
7440
-
7441
-    $.jeegoopopup.close();
7442
-
7443
-    $("#line-"+ lineNum +"-txt-FindTransferBuddy").parent().hide();
7444
-    $("#line-"+ lineNum +"-btn-blind-transfer").hide();
7445
-    $("#line-"+ lineNum +"-btn-attended-transfer").hide();
7446
-
7447
-    $("#line-"+ lineNum +"-btn-complete-attended-transfer").hide();
7448
-    $("#line-"+ lineNum +"-btn-cancel-attended-transfer").hide();
7449
-    $("#line-"+ lineNum +"-btn-terminate-attended-transfer").hide();
7450
-
7451
-    var newCallStatus = $("#line-"+ lineNum +"-transfer-status");
7452
-    newCallStatus.html(lang.connecting);
7453
-    newCallStatus.show();
7454
-
7455
-    if(!session.data.transfer) session.data.transfer = [];
7456
-    session.data.transfer.push({ 
7457
-        type: "Attended", 
7458
-        to: dstNo, 
7459
-        transferTime: utcDateNow(), 
7460
-        disposition: "invite",
7461
-        dispositionTime: utcDateNow(), 
7462
-        accept : {
7463
-            complete: null,
7464
-            eventTime: null,
7465
-            disposition: ""
7466
-        }
7467
-    });
7468
-    var transferid = session.data.transfer.length-1;
7469
-
7470
-    updateLineScroll(lineNum);
7471
-
7472
-    // SDP options
7473
-    var supportedConstraints = navigator.mediaDevices.getSupportedConstraints();
7474
-    var spdOptions = {
7475
-        sessionDescriptionHandlerOptions: {
7476
-            constraints: {
7477
-                audio: { deviceId : "default" },
7478
-                video: false
7479
-            }
7480
-        }
7481
-    }
7482
-    if(session.data.AudioSourceDevice != "default"){
7483
-        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.deviceId = { exact: session.data.AudioSourceDevice }
7484
-    }
7485
-    // Add additional Constraints
7486
-    if(supportedConstraints.autoGainControl) {
7487
-        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.autoGainControl = AutoGainControl;
7488
-    }
7489
-    if(supportedConstraints.echoCancellation) {
7490
-        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.echoCancellation = EchoCancellation;
7491
-    }
7492
-    if(supportedConstraints.noiseSuppression) {
7493
-        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.noiseSuppression = NoiseSuppression;
7494
-    }
7495
-
7496
-    if(session.data.withvideo){
7497
-        spdOptions.sessionDescriptionHandlerOptions.constraints.video = true;
7498
-        if(session.data.VideoSourceDevice != "default"){
7499
-            spdOptions.sessionDescriptionHandlerOptions.constraints.video.deviceId = { exact: session.data.VideoSourceDevice }
7500
-        }
7501
-        // Add additional Constraints
7502
-        if(supportedConstraints.frameRate && maxFrameRate != "") {
7503
-            spdOptions.sessionDescriptionHandlerOptions.constraints.video.frameRate = maxFrameRate;
7504
-        }
7505
-        if(supportedConstraints.height && videoHeight != "") {
7506
-            spdOptions.sessionDescriptionHandlerOptions.constraints.video.height = videoHeight;
7507
-        }
7508
-        if(supportedConstraints.aspectRatio && videoAspectRatio != "") {
7509
-            spdOptions.sessionDescriptionHandlerOptions.constraints.video.aspectRatio = videoAspectRatio;
7510
-        }
7511
-    }
7512
-
7513
-    // Create new call session
7514
-    console.log("INVITE: ", "sip:" + dstNo + "@" + wssServer);
7515
-    var newSession = userAgent.invite("sip:" + dstNo + "@" + wssServer, spdOptions);
7516
-    session.data.childsession = newSession;
7517
-    newSession.on('progress', function (response) {
7518
-        newCallStatus.html(lang.ringing);
7519
-        session.data.transfer[transferid].disposition = "progress";
7520
-        session.data.transfer[transferid].dispositionTime = utcDateNow();
7521
-
7522
-        $("#line-" + lineNum + "-msg").html(lang.attended_transfer_call_started);
7523
-        
7524
-        var CancelAttendedTransferBtn = $("#line-"+ lineNum +"-btn-cancel-attended-transfer");
7525
-        CancelAttendedTransferBtn.off('click');
7526
-        CancelAttendedTransferBtn.on('click', function(){
7527
-            newSession.cancel();
7528
-            newCallStatus.html(lang.call_cancelled);
7529
-            console.log("New call session canceled");
7530
-
7531
-            session.data.transfer[transferid].accept.complete = false;
7532
-            session.data.transfer[transferid].accept.disposition = "cancel";
7533
-            session.data.transfer[transferid].accept.eventTime = utcDateNow();
7534
-
7535
-            $("#line-" + lineNum + "-msg").html(lang.attended_transfer_call_cancelled);
7536
-
7537
-            updateLineScroll(lineNum);
7538
-        });
7539
-        CancelAttendedTransferBtn.show();
7540
-
7541
-        updateLineScroll(lineNum);
7542
-    });
7543
-    newSession.on('accepted', function (response) {
7544
-        newCallStatus.html(lang.call_in_progress);
7545
-        $("#line-"+ lineNum +"-btn-cancel-attended-transfer").hide();
7546
-        session.data.transfer[transferid].disposition = "accepted";
7547
-        session.data.transfer[transferid].dispositionTime = utcDateNow();
7548
-
7549
-        var CompleteTransferBtn = $("#line-"+ lineNum +"-btn-complete-attended-transfer");
7550
-        CompleteTransferBtn.off('click');
7551
-        CompleteTransferBtn.on('click', function(){
7552
-            var transferOptions  = { 
7553
-                receiveResponse: function doReceiveResponse(response){
7554
-                    console.log("Attended transfer response: ", response.reason_phrase);
7555
-
7556
-                    session.data.terminateby = "refer";
7557
-                    session.data.transfer[transferid].accept.disposition = response.reason_phrase;
7558
-                    session.data.transfer[transferid].accept.eventTime = utcDateNow();
7559
-
7560
-                    $("#line-" + lineNum + "-msg").html(lang.attended_transfer_complete_accepted);
7561
-
7562
-                    updateLineScroll(lineNum);
7563
-                }
7564
-            }
7565
-
7566
-            // Send REFER
7567
-            session.refer(newSession, transferOptions);
7568
-
7569
-            newCallStatus.html(lang.attended_transfer_complete);
7570
-            console.log("Attended transfer complete");
7571
-            // Call will now teardown...
7572
-
7573
-            session.data.transfer[transferid].accept.complete = true;
7574
-            session.data.transfer[transferid].accept.disposition = "refer";
7575
-            session.data.transfer[transferid].accept.eventTime = utcDateNow();
7576
-
7577
-            $("#line-" + lineNum + "-msg").html(lang.attended_transfer_complete);
7578
-
7579
-            updateLineScroll(lineNum);
7580
-        });
7581
-        CompleteTransferBtn.show();
7582
-
7583
-        updateLineScroll(lineNum);
7584
-
7585
-        var TerminateAttendedTransferBtn = $("#line-"+ lineNum +"-btn-terminate-attended-transfer");
7586
-        TerminateAttendedTransferBtn.off('click');
7587
-        TerminateAttendedTransferBtn.on('click', function(){
7588
-            newSession.bye();
7589
-            newCallStatus.html(lang.call_ended);
7590
-            console.log("New call session end");
7591
-
7592
-            session.data.transfer[transferid].accept.complete = false;
7593
-            session.data.transfer[transferid].accept.disposition = "bye";
7594
-            session.data.transfer[transferid].accept.eventTime = utcDateNow();
7595
-
7596
-            $("#line-" + lineNum + "-msg").html(lang.attended_transfer_call_ended);
7597
-
7598
-            updateLineScroll(lineNum);
7599
-        });
7600
-        TerminateAttendedTransferBtn.show();
7601
-
7602
-        updateLineScroll(lineNum);
7603
-    });
7604
-    newSession.on('trackAdded', function () {
7605
-        var pc = newSession.sessionDescriptionHandler.peerConnection;
7606
-
7607
-        // Gets Remote Audio Track (Local audio is setup via initial GUM)
7608
-        var remoteStream = new MediaStream();
7609
-        pc.getReceivers().forEach(function (receiver) {
7610
-            if(receiver.track && receiver.track.kind == "audio"){
7611
-                remoteStream.addTrack(receiver.track);
7612
-            }
7613
-        });
7614
-        var remoteAudio = $("#line-" + lineNum + "-transfer-remoteAudio").get(0);
7615
-        remoteAudio.srcObject = remoteStream;
7616
-        remoteAudio.onloadedmetadata = function(e) {
7617
-            if (typeof remoteAudio.sinkId !== 'undefined') {
7618
-                remoteAudio.setSinkId(session.data.AudioOutputDevice).then(function(){
7619
-                    console.log("sinkId applied: "+ session.data.AudioOutputDevice);
7620
-                }).catch(function(e){
7621
-                    console.warn("Error using setSinkId: ", e);
7622
-                });            
7623
-            }
7624
-            remoteAudio.play();
7625
-        }
7626
-    });
7627
-    newSession.on('rejected', function (response, cause) {
7628
-        console.log("New call session rejected: ", cause);
7629
-        newCallStatus.html(lang.call_rejected);
7630
-        session.data.transfer[transferid].disposition = "rejected";
7631
-        session.data.transfer[transferid].dispositionTime = utcDateNow();
7632
-
7633
-        $("#line-"+ lineNum +"-txt-FindTransferBuddy").parent().show();
7634
-        $("#line-"+ lineNum +"-btn-blind-transfer").show();
7635
-        $("#line-"+ lineNum +"-btn-attended-transfer").show();
7636
-
7637
-        $("#line-"+ lineNum +"-btn-complete-attended-transfer").hide();
7638
-        $("#line-"+ lineNum +"-btn-cancel-attended-transfer").hide();
7639
-        $("#line-"+ lineNum +"-btn-terminate-attended-transfer").hide();
7640
-
7641
-        $("#line-"+ lineNum +"-msg").html(lang.attended_transfer_call_rejected);
7642
-
7643
-        updateLineScroll(lineNum);
7644
-
7645
-        window.setTimeout(function(){
7646
-            newCallStatus.hide();
7647
-            updateLineScroll(lineNum);
7648
-        }, 1000);
7649
-    });
7650
-    newSession.on('terminated', function (response, cause) {
7651
-        console.log("New call session terminated: ", cause);
7652
-        newCallStatus.html(lang.call_ended);
7653
-        session.data.transfer[transferid].disposition = "terminated";
7654
-        session.data.transfer[transferid].dispositionTime = utcDateNow();
7655
-
7656
-        $("#line-"+ lineNum +"-txt-FindTransferBuddy").parent().show();
7657
-        $("#line-"+ lineNum +"-btn-blind-transfer").show();
7658
-        $("#line-"+ lineNum +"-btn-attended-transfer").show();
7659
-
7660
-        $("#line-"+ lineNum +"-btn-complete-attended-transfer").hide();
7661
-        $("#line-"+ lineNum +"-btn-cancel-attended-transfer").hide();
7662
-        $("#line-"+ lineNum +"-btn-terminate-attended-transfer").hide();
7663
-
7664
-        $("#line-"+ lineNum +"-msg").html(lang.attended_transfer_call_terminated);
7665
-
7666
-        updateLineScroll(lineNum);
7667
-
7668
-        window.setTimeout(function(){
7669
-            newCallStatus.hide();
7670
-            updateLineScroll(lineNum);
7671
-        }, 1000);
7672
-    });
7673
-}
7674
-
7675
-// Conference Calls
7676
-// ================
7677
-function StartConferenceCall(lineNum){
7678
-    $("#line-"+ lineNum +"-btn-Conference").hide();
7679
-    $("#line-"+ lineNum +"-btn-CancelConference").show();
7680
-
7681
-    holdSession(lineNum);
7682
-    $("#line-"+ lineNum +"-txt-FindConferenceBuddy").val("");
7683
-    $("#line-"+ lineNum +"-txt-FindConferenceBuddy").parent().show();
7684
-
7685
-    $("#line-"+ lineNum +"-btn-conference-dial").show();
7686
-    $("#line-"+ lineNum +"-btn-cancel-conference-dial").hide();
7687
-    $("#line-"+ lineNum +"-btn-join-conference-call").hide();
7688
-    $("#line-"+ lineNum +"-btn-terminate-conference-call").hide();
7689
-
7690
-    $("#line-"+ lineNum +"-conference-status").hide();
7691
-
7692
-    $("#line-"+ lineNum +"-Conference").show();
7693
-
7694
-    updateLineScroll(lineNum);
7695
-}
7696
-function CancelConference(lineNum){
7697
-    var lineObj = FindLineByNumber(lineNum);
7698
-    if(lineObj == null || lineObj.SipSession == null){
7699
-        console.warn("Null line or session");
7700
-        return;
7701
-    }
7702
-    var session = lineObj.SipSession;
7703
-    if(session.data.childsession){
7704
-        try{
7705
-            if(session.data.childsession.status == SIP.Session.C.STATUS_CONFIRMED){
7706
-                session.data.childsession.bye();
7707
-            } 
7708
-            else{
7709
-                session.data.childsession.cancel();
7710
-            }
7711
-        } catch(e){}
7712
-    }
7713
-
7714
-    $("#line-"+ lineNum +"-btn-Conference").show();
7715
-    $("#line-"+ lineNum +"-btn-CancelConference").hide();
7716
-
7717
-    unholdSession(lineNum);
7718
-    $("#line-"+ lineNum +"-Conference").hide();
7719
-
7720
-    updateLineScroll(lineNum);
7721
-}
7722
-function ConferenceDial(lineNum){
7723
-    var dstNo = $("#line-"+ lineNum +"-txt-FindConferenceBuddy").val().replace(/[^0-9\*\#\+]/g,'');
7724
-    if(dstNo == ""){
7725
-        console.warn("Cannot transfer, must be [0-9*+#]");
7726
-        return;
7727
-    }
7728
-    
7729
-    var lineObj = FindLineByNumber(lineNum);
7730
-    if(lineObj == null || lineObj.SipSession == null){
7731
-        console.warn("Null line or session");
7732
-        return;
7733
-    }
7734
-    var session = lineObj.SipSession;
7735
-
7736
-    $.jeegoopopup.close();
7737
-
7738
-    $("#line-"+ lineNum +"-txt-FindConferenceBuddy").parent().hide();
7739
-
7740
-    $("#line-"+ lineNum +"-btn-conference-dial").hide();
7741
-    $("#line-"+ lineNum +"-btn-cancel-conference-dial")
7742
-    $("#line-"+ lineNum +"-btn-join-conference-call").hide();
7743
-    $("#line-"+ lineNum +"-btn-terminate-conference-call").hide();
7744
-
7745
-    var newCallStatus = $("#line-"+ lineNum +"-conference-status");
7746
-    newCallStatus.html(lang.connecting);
7747
-    newCallStatus.show();
7748
-
7749
-    if(!session.data.confcalls) session.data.confcalls = [];
7750
-    session.data.confcalls.push({ 
7751
-        to: dstNo, 
7752
-        startTime: utcDateNow(), 
7753
-        disposition: "invite",
7754
-        dispositionTime: utcDateNow(), 
7755
-        accept : {
7756
-            complete: null,
7757
-            eventTime: null,
7758
-            disposition: ""
7759
-        }
7760
-    });
7761
-    var confcallid = session.data.confcalls.length-1;
7762
-
7763
-    updateLineScroll(lineNum);
7764
-
7765
-    // SDP options
7766
-    var supportedConstraints = navigator.mediaDevices.getSupportedConstraints();
7767
-    var spdOptions = {
7768
-        sessionDescriptionHandlerOptions: {
7769
-            constraints: {
7770
-                audio: { deviceId : "default" },
7771
-                video: false
7772
-            }
7773
-        }
7774
-    }
7775
-    if(session.data.AudioSourceDevice != "default"){
7776
-        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.deviceId = { exact: session.data.AudioSourceDevice }
7777
-    }
7778
-    // Add additional Constraints
7779
-    if(supportedConstraints.autoGainControl) {
7780
-        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.autoGainControl = AutoGainControl;
7781
-    }
7782
-    if(supportedConstraints.echoCancellation) {
7783
-        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.echoCancellation = EchoCancellation;
7784
-    }
7785
-    if(supportedConstraints.noiseSuppression) {
7786
-        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.noiseSuppression = NoiseSuppression;
7787
-    }
7788
-
7789
-    // Unlikely this will work
7790
-    if(session.data.withvideo){
7791
-        spdOptions.sessionDescriptionHandlerOptions.constraints.video = true;
7792
-        if(session.data.VideoSourceDevice != "default"){
7793
-            spdOptions.sessionDescriptionHandlerOptions.constraints.video.deviceId = { exact: session.data.VideoSourceDevice }
7794
-        }
7795
-        // Add additional Constraints
7796
-        if(supportedConstraints.frameRate && maxFrameRate != "") {
7797
-            spdOptions.sessionDescriptionHandlerOptions.constraints.video.frameRate = maxFrameRate;
7798
-        }
7799
-        if(supportedConstraints.height && videoHeight != "") {
7800
-            spdOptions.sessionDescriptionHandlerOptions.constraints.video.height = videoHeight;
7801
-        }
7802
-        if(supportedConstraints.aspectRatio && videoAspectRatio != "") {
7803
-            spdOptions.sessionDescriptionHandlerOptions.constraints.video.aspectRatio = videoAspectRatio;
7804
-        }
7805
-    }
7806
-
7807
-    // Create new call session
7808
-    console.log("INVITE: ", "sip:" + dstNo + "@" + wssServer);
7809
-    var newSession = userAgent.invite("sip:" + dstNo + "@" + wssServer, spdOptions);
7810
-    session.data.childsession = newSession;
7811
-    newSession.on('progress', function (response) {
7812
-        newCallStatus.html(lang.ringing);
7813
-        session.data.confcalls[confcallid].disposition = "progress";
7814
-        session.data.confcalls[confcallid].dispositionTime = utcDateNow();
7815
-
7816
-        $("#line-" + lineNum + "-msg").html(lang.conference_call_started);
7817
-
7818
-        var CancelConferenceDialBtn = $("#line-"+ lineNum +"-btn-cancel-conference-dial");
7819
-        CancelConferenceDialBtn.off('click');
7820
-        CancelConferenceDialBtn.on('click', function(){
7821
-            newSession.cancel();
7822
-            newCallStatus.html(lang.call_cancelled);
7823
-            console.log("New call session canceled");
7824
-
7825
-            session.data.confcalls[confcallid].accept.complete = false;
7826
-            session.data.confcalls[confcallid].accept.disposition = "cancel";
7827
-            session.data.confcalls[confcallid].accept.eventTime = utcDateNow();
7828
-
7829
-            $("#line-" + lineNum + "-msg").html(lang.canference_call_cancelled);
7830
-
7831
-            updateLineScroll(lineNum);
7832
-        });
7833
-        CancelConferenceDialBtn.show();
7834
-
7835
-        updateLineScroll(lineNum);
7836
-    });
7837
-    newSession.on('accepted', function (response) {
7838
-        newCallStatus.html(lang.call_in_progress);
7839
-        $("#line-"+ lineNum +"-btn-cancel-conference-dial").hide();
7840
-        session.data.confcalls[confcallid].complete = true;
7841
-        session.data.confcalls[confcallid].disposition = "accepted";
7842
-        session.data.confcalls[confcallid].dispositionTime = utcDateNow();
7843
-
7844
-        // Join Call
7845
-        var JoinCallBtn = $("#line-"+ lineNum +"-btn-join-conference-call");
7846
-        JoinCallBtn.off('click');
7847
-        JoinCallBtn.on('click', function(){
7848
-            // Merge Call Audio
7849
-            if(!session.data.childsession){
7850
-                console.warn("Conference session lost");
7851
-                return;
7852
-            }
7853
-
7854
-            var outputStreamForSession = new MediaStream();
7855
-            var outputStreamForConfSession = new MediaStream();
7856
-
7857
-            var pc = session.sessionDescriptionHandler.peerConnection;
7858
-            var confPc = session.data.childsession.sessionDescriptionHandler.peerConnection;
7859
-
7860
-            // Get conf call input channel
7861
-            confPc.getReceivers().forEach(function (RTCRtpReceiver) {
7862
-                if(RTCRtpReceiver.track && RTCRtpReceiver.track.kind == "audio") {
7863
-                    console.log("Adding conference session:", RTCRtpReceiver.track.label);
7864
-                    outputStreamForSession.addTrack(RTCRtpReceiver.track);
7865
-                }
7866
-            });
7867
-
7868
-            // Get session input channel
7869
-            pc.getReceivers().forEach(function (RTCRtpReceiver) {
7870
-                if(RTCRtpReceiver.track && RTCRtpReceiver.track.kind == "audio") {
7871
-                    console.log("Adding conference session:", RTCRtpReceiver.track.label);
7872
-                    outputStreamForConfSession.addTrack(RTCRtpReceiver.track);
7873
-                }
7874
-            });
7875
-
7876
-            // Replace tracks of Parent Call
7877
-            pc.getSenders().forEach(function (RTCRtpSender) {
7878
-                if(RTCRtpSender.track && RTCRtpSender.track.kind == "audio") {
7879
-                    console.log("Switching to mixed Audio track on session");
7880
-
7881
-                    session.data.AudioSourceTrack = RTCRtpSender.track;
7882
-                    outputStreamForSession.addTrack(RTCRtpSender.track);
7883
-                    var mixedAudioTrack = MixAudioStreams(outputStreamForSession).getAudioTracks()[0];
7884
-                    mixedAudioTrack.IsMixedTrack = true;
7885
-
7886
-                    RTCRtpSender.replaceTrack(mixedAudioTrack);
7887
-                }
7888
-            });
7889
-            // Replace tracks of Child Call
7890
-            confPc.getSenders().forEach(function (RTCRtpSender) {
7891
-                if(RTCRtpSender.track && RTCRtpSender.track.kind == "audio") {
7892
-                    console.log("Switching to mixed Audio track on conf call");
7893
-
7894
-                    session.data.childsession.data.AudioSourceTrack = RTCRtpSender.track;
7895
-                    outputStreamForConfSession.addTrack(RTCRtpSender.track);
7896
-                    var mixedAudioTrackForConf = MixAudioStreams(outputStreamForConfSession).getAudioTracks()[0];
7897
-                    mixedAudioTrackForConf.IsMixedTrack = true;
7898
-
7899
-                    RTCRtpSender.replaceTrack(mixedAudioTrackForConf);
7900
-                }
7901
-            });
7902
-
7903
-            newCallStatus.html(lang.call_in_progress);
7904
-            console.log("Conference Call In Progress");
7905
-
7906
-            session.data.confcalls[confcallid].accept.complete = true;
7907
-            session.data.confcalls[confcallid].accept.disposition = "join";
7908
-            session.data.confcalls[confcallid].accept.eventTime = utcDateNow();
7909
-
7910
-            $("#line-"+ lineNum +"-btn-terminate-conference-call").show();
7911
-
7912
-            $("#line-" + lineNum + "-msg").html(lang.conference_call_in_progress);
7913
-
7914
-            // Take the parent call off hold
7915
-            unholdSession(lineNum);
7916
-
7917
-            JoinCallBtn.hide();
7918
-
7919
-            updateLineScroll(lineNum);
7920
-        });
7921
-        JoinCallBtn.show();
7922
-
7923
-        updateLineScroll(lineNum);
7924
-
7925
-        // End Call
7926
-        var TerminateAttendedTransferBtn = $("#line-"+ lineNum +"-btn-terminate-conference-call");
7927
-        TerminateAttendedTransferBtn.off('click');
7928
-        TerminateAttendedTransferBtn.on('click', function(){
7929
-            newSession.bye();
7930
-            newCallStatus.html(lang.call_ended);
7931
-            console.log("New call session end");
7932
-
7933
-            session.data.confcalls[confcallid].accept.disposition = "bye";
7934
-            session.data.confcalls[confcallid].accept.eventTime = utcDateNow();
7935
-
7936
-            $("#line-" + lineNum + "-msg").html(lang.conference_call_ended);
7937
-
7938
-            updateLineScroll(lineNum);
7939
-        });
7940
-        TerminateAttendedTransferBtn.show();
7941
-
7942
-        updateLineScroll(lineNum);
7943
-    });
7944
-    newSession.on('trackAdded', function () {
7945
-
7946
-        var pc = newSession.sessionDescriptionHandler.peerConnection;
7947
-
7948
-        // Gets Remote Audio Track (Local audio is setup via initial GUM)
7949
-        var remoteStream = new MediaStream();
7950
-        pc.getReceivers().forEach(function (receiver) {
7951
-            if(receiver.track && receiver.track.kind == "audio"){
7952
-                remoteStream.addTrack(receiver.track);
7953
-            }
7954
-        });
7955
-        var remoteAudio = $("#line-" + lineNum + "-conference-remoteAudio").get(0);
7956
-        remoteAudio.srcObject = remoteStream;
7957
-        remoteAudio.onloadedmetadata = function(e) {
7958
-            if (typeof remoteAudio.sinkId !== 'undefined') {
7959
-                remoteAudio.setSinkId(session.data.AudioOutputDevice).then(function(){
7960
-                    console.log("sinkId applied: "+ session.data.AudioOutputDevice);
7961
-                }).catch(function(e){
7962
-                    console.warn("Error using setSinkId: ", e);
7963
-                });
7964
-            }
7965
-            remoteAudio.play();
7966
-        }
7967
-    });
7968
-    newSession.on('rejected', function (response, cause) {
7969
-        console.log("New call session rejected: ", cause);
7970
-        newCallStatus.html(lang.call_rejected);
7971
-        session.data.confcalls[confcallid].disposition = "rejected";
7972
-        session.data.confcalls[confcallid].dispositionTime = utcDateNow();
7973
-
7974
-        $("#line-"+ lineNum +"-txt-FindConferenceBuddy").parent().show();
7975
-        $("#line-"+ lineNum +"-btn-conference-dial").show();
7976
-
7977
-        $("#line-"+ lineNum +"-btn-cancel-conference-dial").hide();
7978
-        $("#line-"+ lineNum +"-btn-join-conference-call").hide();
7979
-        $("#line-"+ lineNum +"-btn-terminate-conference-call").hide();
7980
-
7981
-        $("#line-"+ lineNum +"-msg").html(lang.conference_call_rejected);
7982
-
7983
-        updateLineScroll(lineNum);
7984
-
7985
-        window.setTimeout(function(){
7986
-            newCallStatus.hide();
7987
-            updateLineScroll(lineNum);
7988
-        }, 1000);
7989
-    });
7990
-    newSession.on('terminated', function (response, cause) {
7991
-        console.log("New call session terminated: ", cause);
7992
-        newCallStatus.html(lang.call_ended);
7993
-        session.data.confcalls[confcallid].disposition = "terminated";
7994
-        session.data.confcalls[confcallid].dispositionTime = utcDateNow();
7995
-
7996
-        // Ends the mixed audio, and releases the mic
7997
-        if(session.data.childsession.data.AudioSourceTrack && session.data.childsession.data.AudioSourceTrack.kind == "audio"){
7998
-            session.data.childsession.data.AudioSourceTrack.stop();
7999
-        }
8000
-        // Restore Audio Stream if it was changed
8001
-        if(session.data.AudioSourceTrack && session.data.AudioSourceTrack.kind == "audio"){
8002
-            var pc = session.sessionDescriptionHandler.peerConnection;
8003
-            pc.getSenders().forEach(function (RTCRtpSender) {
8004
-                if(RTCRtpSender.track && RTCRtpSender.track.kind == "audio") {
8005
-                    RTCRtpSender.replaceTrack(session.data.AudioSourceTrack).then(function(){
8006
-                        if(session.data.ismute){
8007
-                            RTCRtpSender.track.enabled = false;
8008
-                        }
8009
-                    }).catch(function(){
8010
-                        console.error(e);
8011
-                    });
8012
-                    session.data.AudioSourceTrack = null;
8013
-                }
8014
-            });
8015
-        }
8016
-        $("#line-"+ lineNum +"-txt-FindConferenceBuddy").parent().show();
8017
-        $("#line-"+ lineNum +"-btn-conference-dial").show();
8018
-
8019
-        $("#line-"+ lineNum +"-btn-cancel-conference-dial").hide();
8020
-        $("#line-"+ lineNum +"-btn-join-conference-call").hide();
8021
-        $("#line-"+ lineNum +"-btn-terminate-conference-call").hide();
8022
-
8023
-        $("#line-"+ lineNum +"-msg").html(lang.conference_call_terminated);
8024
-
8025
-        updateLineScroll(lineNum);
8026
-
8027
-        window.setTimeout(function(){
8028
-            newCallStatus.hide();
8029
-            updateLineScroll(lineNum);
8030
-        }, 1000);
8031
-    });
8032
-}
8033
-
8034
-
8035
-function cancelSession(lineNum) {
8036
-    var lineObj = FindLineByNumber(lineNum);
8037
-    if(lineObj == null || lineObj.SipSession == null) return;
8038
-
8039
-    lineObj.SipSession.data.terminateby = "us";
8040
-
8041
-    console.log("Cancelling session : "+ lineNum);
8042
-    lineObj.SipSession.cancel();
8043
-
8044
-    $("#line-" + lineNum + "-msg").html(lang.call_cancelled);
8045
-}
8046
-function holdSession(lineNum) {
8047
-    var lineObj = FindLineByNumber(lineNum);
8048
-    if(lineObj == null || lineObj.SipSession == null) return;
8049
-
8050
-    console.log("Putting Call on hold: "+ lineNum);
8051
-    if(lineObj.SipSession.local_hold == false){
8052
-        lineObj.SipSession.hold();
8053
-    }
8054
-    // Log Hold
8055
-    if(!lineObj.SipSession.data.hold) lineObj.SipSession.data.hold = [];
8056
-    lineObj.SipSession.data.hold.push({ event: "hold", eventTime: utcDateNow() });
8057
-
8058
-    $("#line-" + lineNum + "-btn-Hold").hide();
8059
-    $("#line-" + lineNum + "-btn-Unhold").show();
8060
-    $("#line-" + lineNum + "-msg").html(lang.call_on_hold);
8061
-
8062
-    updateLineScroll(lineNum);
8063
-}
8064
-function unholdSession(lineNum) {
8065
-    var lineObj = FindLineByNumber(lineNum);
8066
-    if(lineObj == null || lineObj.SipSession == null) return;
8067
-
8068
-    console.log("Taking call off hold: "+ lineNum);
8069
-    if(lineObj.SipSession.local_hold == true){
8070
-        lineObj.SipSession.unhold();
8071
-    }
8072
-    // Log Hold
8073
-    if(!lineObj.SipSession.data.hold) lineObj.SipSession.data.hold = [];
8074
-    lineObj.SipSession.data.hold.push({ event: "unhold", eventTime: utcDateNow() });
8075
-
8076
-    $("#line-" + lineNum + "-msg").html(lang.call_in_progress);
8077
-    $("#line-" + lineNum + "-btn-Hold").show();
8078
-    $("#line-" + lineNum + "-btn-Unhold").hide();
8079
-
8080
-    updateLineScroll(lineNum);
8081
-}
8082
-function endSession(lineNum) {
8083
-    var lineObj = FindLineByNumber(lineNum);
8084
-    if(lineObj == null || lineObj.SipSession == null) return;
8085
-
8086
-    console.log("Ending call with: "+ lineNum);
8087
-    lineObj.SipSession.data.terminateby = "us";
8088
-    lineObj.SipSession.bye();
8089
-
8090
-    $("#line-" + lineNum + "-msg").html(lang.call_ended);
8091
-    $("#line-" + lineNum + "-ActiveCall").hide();
8092
-
8093
-    updateLineScroll(lineNum);
8094
-}
8095
-function sendDTMF(lineNum, itemStr) {
8096
-    var lineObj = FindLineByNumber(lineNum);
8097
-    if(lineObj == null || lineObj.SipSession == null) return;
8098
-
8099
-    console.log("Sending DTMF ("+ itemStr +"): "+ lineNum);
8100
-    lineObj.SipSession.dtmf(itemStr);
8101
-
8102
-    $("#line-" + lineNum + "-msg").html(lang.send_dtmf + ": "+ itemStr);
8103
-
8104
-    updateLineScroll(lineNum);
8105
-
8106
-    // Custom Web hook
8107
-    if(typeof web_hook_on_dtmf !== 'undefined') web_hook_on_dtmf(itemStr, lineObj.SipSession);
8108
-}
8109
-function switchVideoSource(lineNum, srcId){
8110
-    var lineObj = FindLineByNumber(lineNum);
8111
-    if(lineObj == null || lineObj.SipSession == null){
8112
-        console.warn("Line or Session is Null");
8113
-        return;
8114
-    }
8115
-    var session = lineObj.SipSession;
8116
-
8117
-    $("#line-" + lineNum + "-msg").html(lang.switching_video_source);
8118
-
8119
-    var supportedConstraints = navigator.mediaDevices.getSupportedConstraints();
8120
-    var constraints = { 
8121
-        audio: false, 
8122
-        video: { deviceId: "default" }
8123
-    }
8124
-    if(srcId != "default"){
8125
-        constraints.video.deviceId = { exact: srcId }
8126
-    }
8127
-
8128
-    // Add additional Constraints
8129
-    if(supportedConstraints.frameRate && maxFrameRate != "") {
8130
-        constraints.video.frameRate = maxFrameRate;
8131
-    }
8132
-    if(supportedConstraints.height && videoHeight != "") {
8133
-        constraints.video.height = videoHeight;
8134
-    }
8135
-    if(supportedConstraints.aspectRatio && videoAspectRatio != "") {
8136
-        constraints.video.aspectRatio = videoAspectRatio;
8137
-    }
8138
-
8139
-    session.data.VideoSourceDevice = srcId;
8140
-
8141
-    var pc = session.sessionDescriptionHandler.peerConnection;
8142
-
8143
-    var localStream = new MediaStream();
8144
-    navigator.mediaDevices.getUserMedia(constraints).then(function(newStream){
8145
-        var newMediaTrack = newStream.getVideoTracks()[0];
8146
-        pc.getSenders().forEach(function (RTCRtpSender) {
8147
-            if(RTCRtpSender.track && RTCRtpSender.track.kind == "video") {
8148
-                console.log("Switching Video Track : "+ RTCRtpSender.track.label + " to "+ newMediaTrack.label);
8149
-                RTCRtpSender.track.stop();
8150
-                RTCRtpSender.replaceTrack(newMediaTrack);
8151
-                localStream.addTrack(newMediaTrack);
8152
-            }
8153
-        });
8154
-    }).catch(function(e){
8155
-        console.error("Error on getUserMedia", e, constraints);
8156
-    });
8157
-
8158
-    // Restore Audio Stream is it was changed
8159
-    if(session.data.AudioSourceTrack && session.data.AudioSourceTrack.kind == "audio"){
8160
-        pc.getSenders().forEach(function (RTCRtpSender) {
8161
-            if(RTCRtpSender.track && RTCRtpSender.track.kind == "audio") {
8162
-                RTCRtpSender.replaceTrack(session.data.AudioSourceTrack).then(function(){
8163
-                    if(session.data.ismute){
8164
-                        RTCRtpSender.track.enabled = false;
8165
-                    }
8166
-                }).catch(function(){
8167
-                    console.error(e);
8168
-                });
8169
-                session.data.AudioSourceTrack = null;
8170
-            }
8171
-        });
8172
-    }
8173
-
8174
-    // Set Preview
8175
-    console.log("Showing as preview...");
8176
-    var localVideo = $("#line-" + lineNum + "-localVideo").get(0);
8177
-    localVideo.srcObject = localStream;
8178
-    localVideo.onloadedmetadata = function(e) {
8179
-        localVideo.play();
8180
-    }
8181
-}
8182
-function SendCanvas(lineNum){
8183
-    var lineObj = FindLineByNumber(lineNum);
8184
-    if(lineObj == null || lineObj.SipSession == null){
8185
-        console.warn("Line or Session is Null");
8186
-        return;
8187
-    }
8188
-    var session = lineObj.SipSession;
8189
-
8190
-    $("#line-" + lineNum + "-msg").html(lang.switching_to_canvas);
8191
-
8192
-    // Create scratch Pad
8193
-    RemoveScratchpad(lineNum);
8194
-
8195
-    var newCanvas = $('<canvas/>');
8196
-    newCanvas.prop("id", "line-" + lineNum + "-scratchpad");
8197
-    $("#line-" + lineNum + "-scratchpad-container").append(newCanvas);
8198
-    $("#line-" + lineNum + "-scratchpad").css("display", "inline-block");
8199
-    $("#line-" + lineNum + "-scratchpad").css("width", "640px"); // SD
8200
-    $("#line-" + lineNum + "-scratchpad").css("height", "360px"); // SD
8201
-    $("#line-" + lineNum + "-scratchpad").prop("width", 640); // SD
8202
-    $("#line-" + lineNum + "-scratchpad").prop("height", 360); // SD
8203
-    $("#line-" + lineNum + "-scratchpad-container").show();
8204
-
8205
-    console.log("Canvas for Scratchpad created...");
8206
-
8207
-    scratchpad = new fabric.Canvas("line-" + lineNum + "-scratchpad");
8208
-    scratchpad.id = "line-" + lineNum + "-scratchpad";
8209
-    scratchpad.backgroundColor = "#FFFFFF";
8210
-    scratchpad.isDrawingMode = true;
8211
-    scratchpad.renderAll();
8212
-    scratchpad.redrawIntrtval = window.setInterval(function(){
8213
-        scratchpad.renderAll();
8214
-    }, 1000);
8215
-
8216
-    CanvasCollection.push(scratchpad);
8217
-
8218
-    // Get The Canvas Stream
8219
-    var canvasMediaStream = $("#line-"+ lineNum +"-scratchpad").get(0).captureStream(25);
8220
-    var canvasMediaTrack = canvasMediaStream.getVideoTracks()[0];
8221
-
8222
-    // Switch Tracks
8223
-    var pc = session.sessionDescriptionHandler.peerConnection;
8224
-    pc.getSenders().forEach(function (RTCRtpSender) {
8225
-        if(RTCRtpSender.track && RTCRtpSender.track.kind == "video") {
8226
-            console.log("Switching Track : "+ RTCRtpSender.track.label + " to Scratchpad Canvas");
8227
-            RTCRtpSender.track.stop();
8228
-            RTCRtpSender.replaceTrack(canvasMediaTrack);
8229
-        }
8230
-    });
8231
-
8232
-    // Restore Audio Stream if it was changed
8233
-    if(session.data.AudioSourceTrack && session.data.AudioSourceTrack.kind == "audio"){
8234
-        pc.getSenders().forEach(function (RTCRtpSender) {
8235
-            if(RTCRtpSender.track && RTCRtpSender.track.kind == "audio") {
8236
-                RTCRtpSender.replaceTrack(session.data.AudioSourceTrack).then(function(){
8237
-                    if(session.data.ismute){
8238
-                        RTCRtpSender.track.enabled = false;
8239
-                    }
8240
-                }).catch(function(){
8241
-                    console.error(e);
8242
-                });
8243
-                session.data.AudioSourceTrack = null;
8244
-            }
8245
-        });
8246
-    }
8247
-
8248
-    // Set Preview
8249
-    // ===========
8250
-    console.log("Showing as preview...");
8251
-    var localVideo = $("#line-" + lineNum + "-localVideo").get(0);
8252
-    localVideo.srcObject = canvasMediaStream;
8253
-    localVideo.onloadedmetadata = function(e) {
8254
-        localVideo.play();
8255
-    }
8256
-}
8257
-function SendVideo(lineNum, src){
8258
-    var lineObj = FindLineByNumber(lineNum);
8259
-    if(lineObj == null || lineObj.SipSession == null){
8260
-        console.warn("Line or Session is Null");
8261
-        return;
8262
-    }
8263
-    var session = lineObj.SipSession;
8264
-
8265
-    $("#line-"+ lineNum +"-src-camera").prop("disabled", false);
8266
-    $("#line-"+ lineNum +"-src-canvas").prop("disabled", false);
8267
-    $("#line-"+ lineNum +"-src-desktop").prop("disabled", false);
8268
-    $("#line-"+ lineNum +"-src-video").prop("disabled", true);
8269
-    $("#line-"+ lineNum +"-src-blank").prop("disabled", false);
8270
-
8271
-    $("#line-" + lineNum + "-msg").html(lang.switching_to_shared_video);
8272
-
8273
-    $("#line-" + lineNum + "-scratchpad-container").hide();
8274
-    RemoveScratchpad(lineNum);
8275
-    $("#line-"+ lineNum +"-sharevideo").hide();
8276
-    $("#line-"+ lineNum +"-sharevideo").get(0).pause();
8277
-    $("#line-"+ lineNum +"-sharevideo").get(0).removeAttribute('src');
8278
-    $("#line-"+ lineNum +"-sharevideo").get(0).load();
8279
-
8280
-    $("#line-"+ lineNum +"-localVideo").hide();
8281
-    $("#line-"+ lineNum +"-remoteVideo").appendTo("#line-" + lineNum + "-preview-container");
8282
-
8283
-    // Create Video Object
8284
-    var newVideo = $("#line-" + lineNum + "-sharevideo");
8285
-    newVideo.prop("src", src);
8286
-    newVideo.off("loadedmetadata");
8287
-    newVideo.on("loadedmetadata", function () {
8288
-        console.log("Video can play now... ");
8289
-
8290
-        // Resample Video
8291
-        var ResampleSize = 360;
8292
-        if(VideoResampleSize == "HD") ResampleSize = 720;
8293
-        if(VideoResampleSize == "FHD") ResampleSize = 1080;
8294
-
8295
-        var videoObj = newVideo.get(0);
8296
-        var resampleCanvas = $('<canvas/>').get(0);
8297
-
8298
-        var videoWidth = videoObj.videoWidth;
8299
-        var videoHeight = videoObj.videoHeight;
8300
-        if(videoWidth >= videoHeight){
8301
-            // Landscape / Square
8302
-            if(videoHeight > ResampleSize){
8303
-                var p = ResampleSize / videoHeight;
8304
-                videoHeight = ResampleSize;
8305
-                videoWidth = videoWidth * p;
8306
-            }
8307
-        }
8308
-        else {
8309
-            // Portrate... (phone turned on its side)
8310
-            if(videoWidth > ResampleSize){
8311
-                var p = ResampleSize / videoWidth;
8312
-                videoWidth = ResampleSize;
8313
-                videoHeight = videoHeight * p;
8314
-            }
8315
-        }
8316
-
8317
-        resampleCanvas.width = videoWidth;
8318
-        resampleCanvas.height = videoHeight;
8319
-        var resampleContext = resampleCanvas.getContext("2d");
8320
-
8321
-        window.clearInterval(session.data.videoResampleInterval);
8322
-        session.data.videoResampleInterval = window.setInterval(function(){
8323
-            resampleContext.drawImage(videoObj, 0, 0, videoWidth, videoHeight);
8324
-        }, 40); // 25frames per second
8325
-
8326
-        // Capture the streams
8327
-        var videoMediaStream = null;
8328
-        if('captureStream' in videoObj) {
8329
-            videoMediaStream = videoObj.captureStream();
8330
-        }
8331
-        else if('mozCaptureStream' in videoObj) {
8332
-            // This doesn't really work
8333
-            // see: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/captureStream
8334
-            videoMediaStream = videoObj.mozCaptureStream();
8335
-        }
8336
-        else {
8337
-            // This is not supported.
8338
-            // videoMediaStream = videoObj.webkitCaptureStream();
8339
-            console.warn("Cannot capture stream from video, this will result in no audio being transmitted.")
8340
-        }
8341
-        var resampleVideoMediaStream = resampleCanvas.captureStream(25);
8342
-
8343
-        // Get the Tracks
8344
-        var videoMediaTrack = resampleVideoMediaStream.getVideoTracks()[0];
8345
-
8346
-        var audioTrackFromVideo = (videoMediaStream != null )? videoMediaStream.getAudioTracks()[0] : null;
8347
-
8348
-        // Switch & Merge Tracks
8349
-        var pc = session.sessionDescriptionHandler.peerConnection;
8350
-        pc.getSenders().forEach(function (RTCRtpSender) {
8351
-            if(RTCRtpSender.track && RTCRtpSender.track.kind == "video") {
8352
-                console.log("Switching Track : "+ RTCRtpSender.track.label);
8353
-                RTCRtpSender.track.stop();
8354
-                RTCRtpSender.replaceTrack(videoMediaTrack);
8355
-            }
8356
-            if(RTCRtpSender.track && RTCRtpSender.track.kind == "audio") {
8357
-                console.log("Switching to mixed Audio track on session");
8358
-
8359
-                session.data.AudioSourceTrack = RTCRtpSender.track;
8360
-
8361
-                var mixedAudioStream = new MediaStream();
8362
-                if(audioTrackFromVideo) mixedAudioStream.addTrack(audioTrackFromVideo);
8363
-                mixedAudioStream.addTrack(RTCRtpSender.track);
8364
-                var mixedAudioTrack = MixAudioStreams(mixedAudioStream).getAudioTracks()[0];
8365
-                mixedAudioTrack.IsMixedTrack = true;
8366
-
8367
-                RTCRtpSender.replaceTrack(mixedAudioTrack);
8368
-            }
8369
-        });
8370
-
8371
-        // Set Preview
8372
-        console.log("Showing as preview...");
8373
-        var localVideo = $("#line-" + lineNum + "-localVideo").get(0);
8374
-        localVideo.srcObject = videoMediaStream;
8375
-        localVideo.onloadedmetadata = function(e) {
8376
-            localVideo.play().then(function(){
8377
-                console.log("Playing Preview Video File");
8378
-            }).catch(function(e){
8379
-                console.error("Cannot play back video", e);
8380
-            });
8381
-        }
8382
-        // Play the video
8383
-        console.log("Starting Video...");
8384
-        $("#line-"+ lineNum +"-sharevideo").get(0).play();
8385
-    });
8386
-
8387
-    $("#line-"+ lineNum +"-sharevideo").show();
8388
-    console.log("Video for Sharing created...");
8389
-}
8390
-function ShareScreen(lineNum){
8391
-    var lineObj = FindLineByNumber(lineNum);
8392
-    if(lineObj == null || lineObj.SipSession == null){
8393
-        console.warn("Line or Session is Null");
8394
-        return;
8395
-    }
8396
-    var session = lineObj.SipSession;
8397
-
8398
-    $("#line-" + lineNum + "-msg").html(lang.switching_to_shared_screeen);
8399
-
8400
-    var localStream = new MediaStream();
8401
-    var pc = session.sessionDescriptionHandler.peerConnection;
8402
-
8403
-    if (navigator.getDisplayMedia) {
8404
-        // EDGE, legacy support
8405
-        var screenShareConstraints = { video: true, audio: false }
8406
-        navigator.getDisplayMedia(screenShareConstraints).then(function(newStream) {
8407
-            console.log("navigator.getDisplayMedia")
8408
-            var newMediaTrack = newStream.getVideoTracks()[0];
8409
-            pc.getSenders().forEach(function (RTCRtpSender) {
8410
-                if(RTCRtpSender.track && RTCRtpSender.track.kind == "video") {
8411
-                    console.log("Switching Video Track : "+ RTCRtpSender.track.label + " to Screen");
8412
-                    RTCRtpSender.track.stop();
8413
-                    RTCRtpSender.replaceTrack(newMediaTrack);
8414
-                    localStream.addTrack(newMediaTrack);
8415
-                }
8416
-            });
8417
-
8418
-            // Set Preview
8419
-            // ===========
8420
-            console.log("Showing as preview...");
8421
-            var localVideo = $("#line-" + lineNum + "-localVideo").get(0);
8422
-            localVideo.srcObject = localStream;
8423
-            localVideo.onloadedmetadata = function(e) {
8424
-                localVideo.play();
8425
-            }
8426
-        }).catch(function (err) {
8427
-            console.error("Error on getUserMedia");
8428
-        });
8429
-    }
8430
-    else if (navigator.mediaDevices.getDisplayMedia) {
8431
-        // New standard
8432
-        var screenShareConstraints = { video: true, audio: false }
8433
-        navigator.mediaDevices.getDisplayMedia(screenShareConstraints).then(function(newStream) {
8434
-            console.log("navigator.mediaDevices.getDisplayMedia")
8435
-            var newMediaTrack = newStream.getVideoTracks()[0];
8436
-            pc.getSenders().forEach(function (RTCRtpSender) {
8437
-                if(RTCRtpSender.track && RTCRtpSender.track.kind == "video") {
8438
-                    console.log("Switching Video Track : "+ RTCRtpSender.track.label + " to Screen");
8439
-                    RTCRtpSender.track.stop();
8440
-                    RTCRtpSender.replaceTrack(newMediaTrack);
8441
-                    localStream.addTrack(newMediaTrack);
8442
-                }
8443
-            });
8444
-
8445
-            // Set Preview
8446
-            // ===========
8447
-            console.log("Showing as preview...");
8448
-            var localVideo = $("#line-" + lineNum + "-localVideo").get(0);
8449
-            localVideo.srcObject = localStream;
8450
-            localVideo.onloadedmetadata = function(e) {
8451
-                localVideo.play();
8452
-            }
8453
-        }).catch(function (err) {
8454
-            console.error("Error on getUserMedia");
8455
-        });
8456
-    } 
8457
-    else {
8458
-        // Firefox, apparently
8459
-        var screenShareConstraints = { video: { mediaSource: 'screen' }, audio: false }
8460
-        navigator.mediaDevices.getUserMedia(screenShareConstraints).then(function(newStream) {
8461
-            console.log("navigator.mediaDevices.getUserMedia")
8462
-            var newMediaTrack = newStream.getVideoTracks()[0];
8463
-            pc.getSenders().forEach(function (RTCRtpSender) {
8464
-                if(RTCRtpSender.track && RTCRtpSender.track.kind == "video") {
8465
-                    console.log("Switching Video Track : "+ RTCRtpSender.track.label + " to Screen");
8466
-                    RTCRtpSender.track.stop();
8467
-                    RTCRtpSender.replaceTrack(newMediaTrack);
8468
-                    localStream.addTrack(newMediaTrack);
8469
-                }
8470
-            });
8471
-
8472
-            // Set Preview
8473
-            console.log("Showing as preview...");
8474
-            var localVideo = $("#line-" + lineNum + "-localVideo").get(0);
8475
-            localVideo.srcObject = localStream;
8476
-            localVideo.onloadedmetadata = function(e) {
8477
-                localVideo.play();
8478
-            }
8479
-        }).catch(function (err) {
8480
-            console.error("Error on getUserMedia");
8481
-        });
8482
-    }
8483
-
8484
-    // Restore Audio Stream if it was changed
8485
-    if(session.data.AudioSourceTrack && session.data.AudioSourceTrack.kind == "audio"){
8486
-        pc.getSenders().forEach(function (RTCRtpSender) {
8487
-            if(RTCRtpSender.track && RTCRtpSender.track.kind == "audio") {
8488
-                RTCRtpSender.replaceTrack(session.data.AudioSourceTrack).then(function(){
8489
-                    if(session.data.ismute){
8490
-                        RTCRtpSender.track.enabled = false;
8491
-                    }
8492
-                }).catch(function(){
8493
-                    console.error(e);
8494
-                });
8495
-                session.data.AudioSourceTrack = null;
8496
-            }
8497
-        });
8498
-    }
8499
-
8500
-}
8501
-function DisableVideoStream(lineNum){
8502
-    var lineObj = FindLineByNumber(lineNum);
8503
-    if(lineObj == null || lineObj.SipSession == null){
8504
-        console.warn("Line or Session is Null");
8505
-        return;
8506
-    }
8507
-    var session = lineObj.SipSession;
8508
-
8509
-    var pc = session.sessionDescriptionHandler.peerConnection;
8510
-    pc.getSenders().forEach(function (RTCRtpSender) {
8511
-        if(RTCRtpSender.track && RTCRtpSender.track.kind == "video") {
8512
-            console.log("Disable Video Track : "+ RTCRtpSender.track.label + "");
8513
-            RTCRtpSender.track.enabled = false; //stop();
8514
-        }
8515
-        if(RTCRtpSender.track && RTCRtpSender.track.kind == "audio") {
8516
-            if(session.data.AudioSourceTrack && session.data.AudioSourceTrack.kind == "audio"){
8517
-                RTCRtpSender.replaceTrack(session.data.AudioSourceTrack).then(function(){
8518
-                    if(session.data.ismute){
8519
-                        RTCRtpSender.track.enabled = false;
8520
-                    }
8521
-                }).catch(function(){
8522
-                    console.error(e);
8523
-                });
8524
-                session.data.AudioSourceTrack = null;
8525
-            }
8526
-        }
8527
-    });
8528
-
8529
-    // Set Preview
8530
-    console.log("Showing as preview...");
8531
-    var localVideo = $("#line-" + lineNum + "-localVideo").get(0);
8532
-    localVideo.pause();
8533
-    localVideo.removeAttribute('src');
8534
-    localVideo.load();
8535
-
8536
-    $("#line-" + lineNum + "-msg").html(lang.video_disabled);
8537
-}
8538
-
8539
-// Phone Lines
8540
-// ===========
8541
-var Line = function(lineNumber, displayName, displayNumber, buddyObj){
8542
-    this.LineNumber = lineNumber;
8543
-    this.DisplayName = displayName;
8544
-    this.DisplayNumber = displayNumber;
8545
-    this.IsSelected = false;
8546
-    this.BuddyObj = buddyObj;
8547
-    this.SipSession = null;
8548
-    this.LocalSoundMeter = null;
8549
-    this.RemoteSoundMeter = null;
8550
-}
8551
-function ShowDial(obj){
8552
-
8553
-    var leftPos = obj.offsetWidth + 104;
8554
-    var rightPos = 0;
8555
-    var topPos = obj.offsetHeight + 117;
8556
-
8557
-    if ($(window).width() <= 915) {
8558
-        leftPos = event.pageX + obj.offsetWidth - 120;
8559
-        rightPos = 0;
8560
-        topPos = event.pageY + obj.offsetHeight - 11;
8561
-    }
8562
-
8563
-    var html = "<div id=mainDialPad><div><input id=dialText class=dialTextInput oninput=\"handleDialInput(this, event)\" onkeydown=\"dialOnkeydown(event, this)\"></div>";
8564
-    html += "<table cellspacing=10 cellpadding=0 style=\"margin-left:auto; margin-right: auto\">";
8565
-    html += "<tr><td><button class=dtmfButtons onclick=\"KeyPress('1');new Audio('sounds/dtmf.mp3').play();\"><div>1</div><span>&nbsp;</span></button></td>"
8566
-    html += "<td><button class=dtmfButtons onclick=\"KeyPress('2');new Audio('sounds/dtmf.mp3').play();\"><div>2</div><span>ABC</span></button></td>"
8567
-    html += "<td><button class=dtmfButtons onclick=\"KeyPress('3');new Audio('sounds/dtmf.mp3').play();\"><div>3</div><span>DEF</span></button></td></tr>";
8568
-    html += "<tr><td><button class=dtmfButtons onclick=\"KeyPress('4');new Audio('sounds/dtmf.mp3').play();\"><div>4</div><span>GHI</span></button></td>"
8569
-    html += "<td><button class=dtmfButtons onclick=\"KeyPress('5');new Audio('sounds/dtmf.mp3').play();\"><div>5</div><span>JKL</span></button></td>"
8570
-    html += "<td><button class=dtmfButtons onclick=\"KeyPress('6');new Audio('sounds/dtmf.mp3').play();\"><div>6</div><span>MNO</span></button></td></tr>";
8571
-    html += "<tr><td><button class=dtmfButtons onclick=\"KeyPress('7');new Audio('sounds/dtmf.mp3').play();\"><div>7</div><span>PQRS</span></button></td>"
8572
-    html += "<td><button class=dtmfButtons onclick=\"KeyPress('8');new Audio('sounds/dtmf.mp3').play();\"><div>8</div><span>TUV</span></button></td>"
8573
-    html += "<td><button class=dtmfButtons onclick=\"KeyPress('9');new Audio('sounds/dtmf.mp3').play();\"><div>9</div><span>WXYZ</span></button></td></tr>";
8574
-    html += "<tr><td><button class=dtmfButtons onclick=\"KeyPress('*');new Audio('sounds/dtmf.mp3').play();\">*</button></td>"
8575
-    html += "<td><button class=dtmfButtons onclick=\"KeyPress('0');new Audio('sounds/dtmf.mp3').play();\">0</button></td>"
8576
-    html += "<td><button class=dtmfButtons onclick=\"KeyPress('#');new Audio('sounds/dtmf.mp3').play();\">#</button></td></tr>";
8577
-    html += "</table>";
8578
-    html += "<div style=\"text-align: center;\">";
8579
-    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>";
8580
-    if(EnableVideoCalling){
8581
-        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>";
8582
-    }
8583
-    html += "</div></div>";
8584
-
8585
-    $.jeegoopopup.open({
8586
-                html: html,
8587
-                width: "auto",
8588
-                height: "auto",
8589
-                left: leftPos,
8590
-                right: rightPos,
8591
-                top: topPos,
8592
-                scrolling: 'no',
8593
-                skinClass: 'jg_popup_basic',
8594
-//                innerClass: 'showDialInner',
8595
-                overlay: true,
8596
-                opacity: 0,
8597
-                draggable: true,
8598
-                resizable: false,
8599
-                fadeIn: 0
8600
-    });
8601
-
8602
-    $("#dialText").focus();
8603
-
8604
-    if ($(window).width() <= 915) { $.jeegoopopup.right(6); } else { $.jeegoopopup.width('auto').height('auto').left(leftPos).top(topPos); }
8605
-
8606
-    $("#jg_popup_overlay").click(function() { $("#jg_popup_b").empty(); $("#jg_popup_l").empty(); $("#windowCtrls").empty(); $.jeegoopopup.close(); });
8607
-    $(window).on('keydown', function(event) { if (event.key == "Escape") { $("#jg_popup_b").empty(); $("#jg_popup_l").empty(); $("#windowCtrls").empty(); $.jeegoopopup.close(); } });
8608
-}
8609
-
8610
-function handleDialInput(obj, event){
8611
-    if(EnableAlphanumericDial){
8612
-        $("#dialText").val($("#dialText").val().replace(/[^\da-zA-Z\*\#\+]/g, "").substring(0,MaxDidLength));
8613
-    }
8614
-    else {
8615
-        $("#dialText").val($("#dialText").val().replace(/[^\d\*\#\+]/g, "").substring(0,MaxDidLength));
8616
-    }
8617
-    $("#dialVideo").prop('disabled', ($("#dialText").val().length >= DidLength));
8618
-}
8619
-function dialOnkeydown(event, obj, buddy) {
8620
-    var keycode = (event.keyCode ? event.keyCode : event.which);
8621
-    if (keycode == '13'){
8622
-
8623
-        event.preventDefault();
8624
-
8625
-        // Defaults to audio dial
8626
-        DialByLine('audio');
8627
-
8628
-        $("#jg_popup_b").empty(); $("#jg_popup_l").empty(); $("#windowCtrls").empty(); $.jeegoopopup.close();
8629
-
8630
-        return false;
8631
-    }
8632
-}
8633
-function KeyPress(num){
8634
-    $("#dialText").val(($("#dialText").val()+num).substring(0,MaxDidLength));
8635
-    $("#dialVideo").prop('disabled', ($("#dialText").val().length >= DidLength));
8636
-}
8637
-function DialByLine(type, buddy, numToDial, CallerID){
8638
-    $.jeegoopopup.close();
8639
-    if(userAgent == null || userAgent.isRegistered()==false){
8640
-        ConfigureExtensionWindow();
8641
-        return;
8642
-    }
8643
-
8644
-    var numDial = (numToDial)? numToDial : $("#dialText").val();
8645
-    if(EnableAlphanumericDial){
8646
-        numDial = numDial.replace(/[^\da-zA-Z\*\#\+]/g, "").substring(0,MaxDidLength);
8647
-    }
8648
-    else {
8649
-        numDial = numDial.replace(/[^\d\*\#\+]/g, "").substring(0,MaxDidLength);
8650
-    }
8651
-    if(numDial.length == 0) {
8652
-        console.warn("Enter number to dial");
8653
-        return;
8654
-    }
8655
-
8656
-    // Create a Buddy if one is not already existing
8657
-    var buddyObj = (buddy)? FindBuddyByIdentity(buddy) : FindBuddyByDid(numDial);
8658
-    if(buddyObj == null) {
8659
-        var buddyType = (numDial.length > DidLength)? "contact" : "extension";
8660
-        // Assumption but anyway: If the number starts with a * or # then its probably not a subscribable DID,
8661
-        // and is probably a feature code.
8662
-        if(buddyType.substring(0,1) == "*" || buddyType.substring(0,1) == "#") buddyType = "contact";
8663
-        buddyObj = MakeBuddy(buddyType, true, false, true, (CallerID)? CallerID : numDial, numDial);
8664
-    }
8665
-
8666
-    // Create a Line
8667
-    newLineNumber = newLineNumber + 1;
8668
-    lineObj = new Line(newLineNumber, buddyObj.CallerIDName, numDial, buddyObj);
8669
-    Lines.push(lineObj);
8670
-    AddLineHtml(lineObj);
8671
-    SelectLine(newLineNumber);
8672
-    UpdateBuddyList();
8673
-
8674
-    // Start Call Invite
8675
-    if(type == "audio"){
8676
-        AudioCall(lineObj, numDial);
8677
-    }
8678
-    else {
8679
-        VideoCall(lineObj, numDial);
8680
-    }
8681
-
8682
-    try{
8683
-        $("#line-" + newLineNumber).get(0).scrollIntoViewIfNeeded();
8684
-    } catch(e){}
8685
-}
8686
-function SelectLine(lineNum){
8687
-
8688
-    $("#roundcubeFrame").remove();
8689
-
8690
-    var lineObj = FindLineByNumber(lineNum);
8691
-    if(lineObj == null) return;
8692
-
8693
-    var displayLineNumber = 0;
8694
-    for(var l = 0; l < Lines.length; l++) {
8695
-        if(Lines[l].LineNumber == lineObj.LineNumber) displayLineNumber = l+1;
8696
-        if(Lines[l].IsSelected == true && Lines[l].LineNumber == lineObj.LineNumber){
8697
-            // Nothing to do, you re-selected the same buddy;
8698
-            return;
8699
-        }
8700
-    }
8701
-
8702
-    console.log("Selecting Line : "+ lineObj.LineNumber);
8703
-
8704
-    // Can only display one thing on the right
8705
-    $(".streamSelected").each(function () {
8706
-        $(this).prop('class', 'stream');
8707
-    });
8708
-    $("#line-ui-" + lineObj.LineNumber).prop('class', 'streamSelected');
8709
-
8710
-    $("#line-ui-" + lineObj.LineNumber + "-DisplayLineNo").html("<i class=\"fa fa-phone\"></i> "+ lang.line +" "+ displayLineNumber);
8711
-    $("#line-ui-" + lineObj.LineNumber + "-LineIcon").html(displayLineNumber);
8712
-
8713
-    // Switch the SIP Sessions
8714
-    SwitchLines(lineObj.LineNumber);
8715
-
8716
-    // Update Lines List
8717
-    for(var l = 0; l < Lines.length; l++) {
8718
-        var classStr = (Lines[l].LineNumber == lineObj.LineNumber)? "buddySelected" : "buddy";
8719
-        if(Lines[l].SipSession != null) classStr = (Lines[l].SipSession.local_hold)? "buddyActiveCallHollding" : "buddyActiveCall";
8720
-
8721
-        $("#line-" + Lines[l].LineNumber).prop('class', classStr);
8722
-        Lines[l].IsSelected = (Lines[l].LineNumber == lineObj.LineNumber);
8723
-    }
8724
-    // Update Buddy List
8725
-    for(var b = 0; b < Buddies.length; b++) {
8726
-        $("#contact-" + Buddies[b].identity).prop("class", "buddy");
8727
-        Buddies[b].IsSelected = false;
8728
-    }
8729
-
8730
-    // Change to Stream if in Narrow view
8731
-    UpdateUI();
8732
-}
8733
-function FindLineByNumber(lineNum) {
8734
-    for(var l = 0; l < Lines.length; l++) {
8735
-        if(Lines[l].LineNumber == lineNum) return Lines[l];
8736
-    }
8737
-    return null;
8738
-}
8739
-function AddLineHtml(lineObj) {
8740
-
8741
-    var html = "<table id=\"line-ui-"+ lineObj.LineNumber +"\" class=\"stream\" cellspacing=\"5\" cellpadding=\"0\">";
8742
-    html += "<tr><td class=streamSection>";
8743
-
8744
-    // Close|Return|Back Button
8745
-    html += "<div style=\"float:left; margin:0px; padding:5px; height:38px; line-height:38px\">"
8746
-    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> ";
8747
-    html += "</div>"
8748
-
8749
-    // Profile UI
8750
-    html += "<div class=contact style=\"float: left;\">";
8751
-    html += "<div id=\"line-ui-"+ lineObj.LineNumber +"-LineIcon\" class=lineIcon>"+ lineObj.LineNumber +"</div>";
8752
-    html += "<div id=\"line-ui-"+ lineObj.LineNumber +"-DisplayLineNo\" class=contactNameText><i class=\"fa fa-phone\"></i> "+ lang.line +" "+ lineObj.LineNumber +"</div>";
8753
-
8754
-    html += "<div class=presenceText>"+ lineObj.DisplayName +" <"+ lineObj.DisplayNumber +"></div>";
8755
-    html += "</div>";
8756
-
8757
-    // Action Buttons
8758
-    html += "<div style=\"float:right; line-height: 46px;\">";
8759
-    html += "</div>";
8760
-
8761
-    // Separator --------------------------------------------------------------------------
8762
-    html += "<div style=\"clear:both; height:0px\"></div>"
8763
-
8764
-    // Calling UI --------------------------------------------------------------------------
8765
-    html += "<div id=\"line-"+ lineObj.LineNumber +"-calling\">";
8766
-
8767
-    // Gneral Messages
8768
-    html += "<div id=\"line-"+ lineObj.LineNumber +"-timer\" style=\"float: right; margin-top: 4px; margin-right: 10px; color: #575757; display:none;\"></div>";
8769
-    html += "<div id=\"line-"+ lineObj.LineNumber +"-msg\" class=callStatus style=\"display:none\">...</div>";
8770
-
8771
-    // Dialing Out Progress
8772
-    html += "<div id=\"line-"+ lineObj.LineNumber +"-progress\" style=\"display:none; margin-top: 10px\">";
8773
-    html += "<div class=progressCall>";
8774
-    html += "<button onclick=\"cancelSession('"+ lineObj.LineNumber +"')\" class=hangupButton><i class=\"fa fa-phone\"></i>&nbsp;&nbsp;"+ lang.cancel +"</button>";
8775
-    html += "</div>";
8776
-    html += "</div>";
8777
-
8778
-    // Active Call UI
8779
-    html += "<div id=\"line-"+ lineObj.LineNumber +"-ActiveCall\" style=\"display:none; margin-top: 10px;\">";
8780
-
8781
-    // Group Call
8782
-    html += "<div id=\"line-"+ lineObj.LineNumber +"-conference\" style=\"display:none;\"></div>";
8783
-
8784
-    // Video UI
8785
-    if(lineObj.BuddyObj.type == "extension") {
8786
-        html += "<div id=\"line-"+ lineObj.LineNumber +"-VideoCall\" class=videoCall style=\"display:none;\">";
8787
-
8788
-        // Presentation
8789
-        html += "<div style=\"height:35px; line-height:35px; text-align: right\">"+ lang.present +": ";
8790
-        html += "<div class=pill-nav style=\"border-color:#333333\">";
8791
-        html += "<button id=\"line-"+ lineObj.LineNumber +"-src-camera\" onclick=\"PresentCamera('"+ lineObj.LineNumber +"')\" title=\""+ lang.camera +"\" disabled><i class=\"fa fa-video-camera\"></i></button>";
8792
-        html += "<button id=\"line-"+ lineObj.LineNumber +"-src-canvas\" onclick=\"PresentScratchpad('"+ lineObj.LineNumber +"')\" title=\""+ lang.scratchpad +"\"><i class=\"fa fa-pencil-square\"></i></button>";
8793
-        html += "<button id=\"line-"+ lineObj.LineNumber +"-src-desktop\" onclick=\"PresentScreen('"+ lineObj.LineNumber +"')\" title=\""+ lang.screen +"\"><i class=\"fa fa-desktop\"></i></button>";
8794
-        html += "<button id=\"line-"+ lineObj.LineNumber +"-src-video\" onclick=\"PresentVideo('"+ lineObj.LineNumber +"')\" title=\""+ lang.video +"\"><i class=\"fa fa-file-video-o\"></i></button>";
8795
-        html += "<button id=\"line-"+ lineObj.LineNumber +"-src-blank\" onclick=\"PresentBlank('"+ lineObj.LineNumber +"')\" title=\""+ lang.blank +"\"><i class=\"fa fa-ban\"></i></button>";
8796
-        html += "</div>";
8797
-        html += "&nbsp;<button id=\"line-"+ lineObj.LineNumber +"-expand\" onclick=\"ExpandVideoArea('"+ lineObj.LineNumber +"')\"><i class=\"fa fa-expand\"></i></button>";
8798
-        html += "<button id=\"line-"+ lineObj.LineNumber +"-restore\" onclick=\"RestoreVideoArea('"+ lineObj.LineNumber +"')\" style=\"display:none\"><i class=\"fa fa-compress\"></i></button>";
8799
-        html += "</div>";
8800
-
8801
-        // Preview
8802
-        html += "<div id=\"line-"+ lineObj.LineNumber +"-preview-container\" class=PreviewContainer>";
8803
-        html += "<video id=\"line-"+ lineObj.LineNumber +"-localVideo\" muted></video>"; // Default Display
8804
-        html += "</div>";
8805
-
8806
-        // Stage
8807
-        html += "<div id=\"line-"+ lineObj.LineNumber +"-stage-container\" class=StageContainer>";
8808
-        html += "<video id=\"line-"+ lineObj.LineNumber +"-remoteVideo\" muted></video>"; // Default Display
8809
-        html += "<div id=\"line-"+ lineObj.LineNumber +"-scratchpad-container\" style=\"display:none\"></div>";
8810
-        html += "<video id=\"line-"+ lineObj.LineNumber +"-sharevideo\" controls muted style=\"display:none; object-fit: contain;\"></video>";
8811
-        html += "</div>";
8812
-
8813
-        html += "</div>";
8814
-    }
8815
-
8816
-    // Audio Call
8817
-    html += "<div id=\"line-"+ lineObj.LineNumber +"-AudioCall\" style=\"display:none;\">";
8818
-    html += "<audio id=\"line-"+ lineObj.LineNumber+"-remoteAudio\"></audio>";
8819
-    html += "</div>";
8820
-
8821
-    // In Call Buttons
8822
-    html += "<div style=\"text-align:center\">";
8823
-    html += "<div style=\"margin-top:10px\">";
8824
-    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>";
8825
-    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>";
8826
-    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>";
8827
-    if(typeof MediaRecorder != "undefined" && (CallRecordingPolicy == "allow" || CallRecordingPolicy == "enabled")){
8828
-        // Safari: must enable in Develop > Experimental Features > MediaRecorder
8829
-        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>";
8830
-        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>";
8831
-    }
8832
-    if(EnableTransfer){
8833
-        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>";
8834
-        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>";
8835
-    }
8836
-
8837
-    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>";
8838
-    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>";
8839
-    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>";
8840
-    html += "</div>";
8841
-    // Call Transfer
8842
-    html += "<div id=\"line-"+ lineObj.LineNumber +"-Transfer\" style=\"display:none\">";
8843
-    html += "<div style=\"margin-top:10px\">";
8844
-    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>";
8845
-    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>"
8846
-    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>";
8847
-    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>";
8848
-    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>";
8849
-    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>";
8850
-    html += "</div>";
8851
-    html += "<div id=\"line-"+ lineObj.LineNumber +"-transfer-status\" class=callStatus style=\"margin-top:10px; display:none\">...</div>";
8852
-    html += "<audio id=\"line-"+ lineObj.LineNumber +"-transfer-remoteAudio\" style=\"display:none\"></audio>";
8853
-    html += "</div>";
8854
-    // Call Conference
8855
-    html += "<div id=\"line-"+ lineObj.LineNumber +"-Conference\" style=\"display:none\">";
8856
-    html += "<div style=\"margin-top:10px\">";
8857
-    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>";
8858
-    html += " <button id=\"line-"+ lineObj.LineNumber +"-btn-conference-dial\" onclick=\"ConferenceDial('"+ lineObj.LineNumber +"')\"><i class=\"fa fa-phone\"></i> "+ lang.call +"</button>";
8859
-    html += " <button id=\"line-"+ lineObj.LineNumber +"-btn-cancel-conference-dial\" style=\"display:none\"><i class=\"fa fa-phone\"></i> "+ lang.cancel_call +"</buuton>";
8860
-    html += " <button id=\"line-"+ lineObj.LineNumber +"-btn-join-conference-call\" style=\"display:none\"><i class=\"fa fa-users\"></i> "+ lang.join_conference_call +"</buuton>";
8861
-    html += " <button id=\"line-"+ lineObj.LineNumber +"-btn-terminate-conference-call\" style=\"display:none\"><i class=\"fa fa-phone\"></i> "+ lang.end_conference_call +"</buuton>";
8862
-    html += "</div>";
8863
-    html += "<div id=\"line-"+ lineObj.LineNumber +"-conference-status\" class=callStatus style=\"margin-top:10px; display:none\">...</div>";
8864
-    html += "<audio id=\"line-"+ lineObj.LineNumber +"-conference-remoteAudio\" style=\"display:none\"></audio>";
8865
-    html += "</div>";
8866
-    
8867
-    // Monitoring
8868
-    html += "<div  id=\"line-"+ lineObj.LineNumber +"-monitoring\" style=\"margin-top:10px;margin-bottom:10px;\">";
8869
-    html += "<span style=\"vertical-align: middle\"><i class=\"fa fa-microphone\"></i></span> ";
8870
-    html += "<span class=meterContainer title=\""+ lang.microphone_levels +"\">";
8871
-    html += "<span id=\"line-"+ lineObj.LineNumber +"-Mic\" class=meterLevel style=\"height:0%\"></span>";
8872
-    html += "</span> ";
8873
-    html += "<span style=\"vertical-align: middle\"><i class=\"fa fa-volume-up\"></i></span> ";
8874
-    html += "<span class=meterContainer title=\""+ lang.speaker_levels +"\">";
8875
-    html += "<span id=\"line-"+ lineObj.LineNumber +"-Speaker\" class=meterLevel style=\"height:0%\"></span>";
8876
-    html += "</span> ";
8877
-    html += "<button id=\"line-"+ lineObj.LineNumber +"-btn-settings\" onclick=\"ChangeSettings('"+ lineObj.LineNumber +"', this)\"><i class=\"fa fa-cogs\"></i> "+ lang.device_settings +"</button>";
8878
-    html += "<button id=\"line-"+ lineObj.LineNumber +"-call-stats\" onclick=\"ShowCallStats('"+ lineObj.LineNumber +"', this)\"><i class=\"fa fa-area-chart\"></i> "+ lang.call_stats +"</button>";
8879
-    html += "</div>";
8880
-
8881
-    html += "<div id=\"line-"+ lineObj.LineNumber +"-AudioStats\" class=\"audioStats cleanScroller\" style=\"display:none\">";
8882
-    html += "<div style=\"text-align:right\"><button onclick=\"HideCallStats('"+ lineObj.LineNumber +"', this)\"><i class=\"fa fa-times\" style=\"font-size:20px;\"></i></button></div>";
8883
-    html += "<fieldset class=audioStatsSet onclick=\"HideCallStats('"+ lineObj.LineNumber +"', this)\">";
8884
-    html += "<legend>"+ lang.send_statistics +"</legend>";
8885
-    html += "<canvas id=\"line-"+ lineObj.LineNumber +"-AudioSendBitRate\" class=audioGraph width=600 height=160 style=\"width:600px; height:160px\"></canvas>";
8886
-    html += "<canvas id=\"line-"+ lineObj.LineNumber +"-AudioSendPacketRate\" class=audioGraph width=600 height=160 style=\"width:600px; height:160px\"></canvas>";
8887
-    html += "</fieldset>";
8888
-    html += "<fieldset class=audioStatsSet onclick=\"HideCallStats('"+ lineObj.LineNumber +"', this)\">";
8889
-    html += "<legend>"+ lang.receive_statistics +"</legend>";
8890
-    html += "<canvas id=\"line-"+ lineObj.LineNumber +"-AudioReceiveBitRate\" class=audioGraph width=600 height=160 style=\"width:600px; height:160px\"></canvas>";
8891
-    html += "<canvas id=\"line-"+ lineObj.LineNumber +"-AudioReceivePacketRate\" class=audioGraph width=600 height=160 style=\"width:600px; height:160px\"></canvas>";
8892
-    html += "<canvas id=\"line-"+ lineObj.LineNumber +"-AudioReceivePacketLoss\" class=audioGraph width=600 height=160 style=\"width:600px; height:160px\"></canvas>";
8893
-    html += "<canvas id=\"line-"+ lineObj.LineNumber +"-AudioReceiveJitter\" class=audioGraph width=600 height=160 style=\"width:600px; height:160px\"></canvas>";
8894
-    html += "<canvas id=\"line-"+ lineObj.LineNumber +"-AudioReceiveLevels\" class=audioGraph width=600 height=160 style=\"width:600px; height:160px\"></canvas>";
8895
-    html += "</fieldset>";
8896
-    html += "</div>";
8897
-
8898
-    html += "</div>";
8899
-    html += "</div>";
8900
-    html += "</div>";
8901
-    html += "</td></tr>";
8902
-    html += "<tr><td class=\"streamSection streamSectionBackground\">";
8903
-    
8904
-    html += "<div id=\"line-"+ lineObj.LineNumber +"-CallDetails\" class=\"chatHistory cleanScroller\">";
8905
-    // In Call Activity
8906
-    html += "</div>";
8907
-
8908
-    html += "</td></tr>";
8909
-    html += "</table>";
8910
-
8911
-    $("#rightContent").append(html);
8912
-}
8913
-function RemoveLine(lineObj){
8914
-    if(lineObj == null) return;
8915
-
8916
-    for(var l = 0; l < Lines.length; l++) {
8917
-        if(Lines[l].LineNumber == lineObj.LineNumber) {
8918
-            Lines.splice(l,1);
8919
-            break;
8920
-        }
8921
-    }
8922
-
8923
-    CloseLine(lineObj.LineNumber);
8924
-    $("#line-ui-"+ lineObj.LineNumber).remove();
8925
-
8926
-    UpdateBuddyList();
8927
-
8928
-    // Rather than showing nothing, go to the last buddy selected
8929
-    // Select last user
8930
-    if(localDB.getItem("SelectedBuddy") != null){
8931
-        console.log("Selecting previously selected buddy...", localDB.getItem("SelectedBuddy"));
8932
-        SelectBuddy(localDB.getItem("SelectedBuddy"));
8933
-        UpdateUI();
8934
-    }
8935
-}
8936
-function CloseLine(lineNum){
8937
-    // Lines and Buddies (Left)
8938
-    $(".buddySelected").each(function () {
8939
-        $(this).prop('class', 'buddy');
8940
-    });
8941
-    // Streams (Right)
8942
-    $(".streamSelected").each(function () {
8943
-        $(this).prop('class', 'stream');
8944
-    });
8945
-
8946
-    SwitchLines(0);
8947
-
8948
-    console.log("Closing Line: "+ lineNum);
8949
-    for(var l = 0; l < Lines.length; l++){
8950
-        Lines[l].IsSelected = false;
8951
-    }
8952
-    selectedLine = null;
8953
-    for(var b = 0; b < Buddies.length; b++){
8954
-        Buddies[b].IsSelected = false;
8955
-    }
8956
-    selectedBuddy = null;
8957
-
8958
-    $.jeegoopopup.close();
8959
-
8960
-    // Change to Stream if in Narrow view
8961
-    UpdateUI();
8962
-}
8963
-function SwitchLines(lineNum){
8964
-    $.each(userAgent.sessions, function (i, session) {
8965
-        // All the other calls, not on hold
8966
-        if(session.local_hold == false && session.data.line != lineNum) {
8967
-            console.log("Putting an active call on hold: Line: "+ session.data.line +" buddy: "+ session.data.buddyId);
8968
-            session.hold(); // Check state
8969
-
8970
-            // Log Hold
8971
-            if(!session.data.hold) session.data.hold = [];
8972
-            session.data.hold.push({ event: "hold", eventTime: utcDateNow() });
8973
-        }
8974
-        $("#line-" + session.data.line + "-btn-Hold").hide();
8975
-        $("#line-" + session.data.line + "-btn-Unhold").show();
8976
-        session.data.IsCurrentCall = false;
8977
-    });
8978
-
8979
-    var lineObj = FindLineByNumber(lineNum);
8980
-    if(lineObj != null && lineObj.SipSession != null) {
8981
-        var session = lineObj.SipSession;
8982
-        if(session.local_hold == true) {
8983
-            console.log("Taking call off hold:  Line: "+ lineNum +" buddy: "+ session.data.buddyId);
8984
-            session.unhold();
8985
-
8986
-            // Log Hold
8987
-            if(!session.data.hold) session.data.hold = [];
8988
-            session.data.hold.push({ event: "unhold", eventTime: utcDateNow() });
8989
-        }
8990
-        $("#line-" + lineNum + "-btn-Hold").show();
8991
-        $("#line-" + lineNum + "-btn-Unhold").hide();
8992
-        session.data.IsCurrentCall = true;
8993
-    }
8994
-    selectedLine = lineNum;
8995
-
8996
-    RefreshLineActivity(lineNum);
8997
-}
8998
-function RefreshLineActivity(lineNum){
8999
-    var lineObj = FindLineByNumber(lineNum);
9000
-    if(lineObj == null || lineObj.SipSession == null) {
9001
-        return;
9002
-    }
9003
-    var session = lineObj.SipSession;
9004
-
9005
-    $("#line-"+ lineNum +"-CallDetails").empty();
9006
-
9007
-    var callDetails = [];
9008
-
9009
-    var ringTime = 0;
9010
-    var CallStart = moment.utc(session.data.callstart.replace(" UTC", ""));
9011
-    var CallAnswer = null;
9012
-    if(session.startTime){
9013
-        CallAnswer = moment.utc(session.startTime);
9014
-        ringTime = moment.duration(CallAnswer.diff(CallStart));
9015
-    }
9016
-    CallStart = CallStart.format("YYYY-MM-DD HH:mm:ss UTC")
9017
-    CallAnswer = (CallAnswer)? CallAnswer.format("YYYY-MM-DD HH:mm:ss UTC") : null,
9018
-    ringTime = (ringTime != 0)? ringTime.asSeconds() : 0
9019
-
9020
-    var srcCallerID = "";
9021
-    var dstCallerID = "";
9022
-    if(session.data.calldirection == "inbound") {
9023
-        srcCallerID = "<"+ session.remoteIdentity.uri.user +"> "+ session.remoteIdentity.displayName;
9024
-    } 
9025
-    else if(session.data.calldirection == "outbound") {
9026
-        dstCallerID = session.remoteIdentity.uri.user;
9027
-    }
9028
-
9029
-    var withVideo = (session.data.withvideo)? "("+ lang.with_video +")" : "";
9030
-    var startCallMessage = (session.data.calldirection == "inbound")? lang.you_received_a_call_from + " " + srcCallerID  +" "+ withVideo : lang.you_made_a_call_to + " " + dstCallerID +" "+ withVideo;
9031
-    callDetails.push({ 
9032
-        Message: startCallMessage,
9033
-        TimeStr : CallStart
9034
-    });
9035
-    if(CallAnswer){
9036
-        var answerCallMessage = (session.data.calldirection == "inbound")? lang.you_answered_after + " " + ringTime + " " + lang.seconds_plural : lang.they_answered_after + " " + ringTime + " " + lang.seconds_plural;
9037
-        callDetails.push({ 
9038
-            Message: answerCallMessage,
9039
-            TimeStr : CallAnswer
9040
-        });
9041
-    }
9042
-
9043
-    var Transfers = (session.data.transfer)? session.data.transfer : [];
9044
-    $.each(Transfers, function(item, transfer){
9045
-        var msg = (transfer.type == "Blind")? lang.you_started_a_blind_transfer_to +" "+ transfer.to +". " : lang.you_started_an_attended_transfer_to + " "+ transfer.to +". ";
9046
-        if(transfer.accept && transfer.accept.complete == true){
9047
-            msg += lang.the_call_was_completed
9048
-        }
9049
-        else if(transfer.accept.disposition != "") {
9050
-            msg += lang.the_call_was_not_completed +" ("+ transfer.accept.disposition +")"
9051
-        }
9052
-        callDetails.push({
9053
-            Message : msg,
9054
-            TimeStr : transfer.transferTime
9055
-        });
9056
-    });
9057
-    var Mutes = (session.data.mute)? session.data.mute : []
9058
-    $.each(Mutes, function(item, mute){
9059
-        callDetails.push({
9060
-            Message : (mute.event == "mute")? lang.you_put_the_call_on_mute : lang.you_took_the_call_off_mute,
9061
-            TimeStr : mute.eventTime
9062
-        });
9063
-    });
9064
-    var Holds = (session.data.hold)? session.data.hold : []
9065
-    $.each(Holds, function(item, hold){
9066
-        callDetails.push({
9067
-            Message : (hold.event == "hold")? lang.you_put_the_call_on_hold : lang.you_took_the_call_off_hold,
9068
-            TimeStr : hold.eventTime
9069
-        });
9070
-    });
9071
-    var Recordings = (session.data.recordings)? session.data.recordings : []
9072
-    $.each(Recordings, function(item, recording){
9073
-        var msg = lang.call_is_being_recorded;
9074
-        if(recording.startTime != recording.stopTime){
9075
-            msg += "("+ lang.now_stopped +")"
9076
-        }
9077
-        callDetails.push({
9078
-            Message : msg,
9079
-            TimeStr : recording.startTime
9080
-        });
9081
-    });
9082
-    var ConfCalls = (session.data.confcalls)? session.data.confcalls : []
9083
-    $.each(ConfCalls, function(item, confCall){
9084
-        var msg = lang.you_started_a_conference_call_to +" "+ confCall.to +". ";
9085
-        if(confCall.accept && confCall.accept.complete == true){
9086
-            msg += lang.the_call_was_completed
9087
-        }
9088
-        else if(confCall.accept.disposition != "") {
9089
-            msg += lang.the_call_was_not_completed +" ("+ confCall.accept.disposition +")"
9090
-        }
9091
-        callDetails.push({
9092
-            Message : msg,
9093
-            TimeStr : confCall.startTime
9094
-        });
9095
-    });
9096
-
9097
-    callDetails.sort(function(a, b){
9098
-        var aMo = moment.utc(a.TimeStr.replace(" UTC", ""));
9099
-        var bMo = moment.utc(b.TimeStr.replace(" UTC", ""));
9100
-        if (aMo.isSameOrAfter(bMo, "second")) {
9101
-            return -1;
9102
-        } else return 1;
9103
-        return 0;
9104
-    });
9105
-
9106
-    $.each(callDetails, function(item, detail){
9107
-        var Time = moment.utc(detail.TimeStr.replace(" UTC", "")).local().format(DisplayTimeFormat);
9108
-        var messageString = "<table class=timelineMessage cellspacing=0 cellpadding=0><tr>"
9109
-        messageString += "<td class=timelineMessageArea>"
9110
-        messageString += "<div class=timelineMessageDate><i class=\"fa fa-circle timelineMessageDot\"></i>"+ Time +"</div>"
9111
-        messageString += "<div class=timelineMessageText>"+ detail.Message +"</div>"
9112
-        messageString += "</td>"
9113
-        messageString += "</tr></table>";
9114
-        $("#line-"+ lineNum +"-CallDetails").prepend(messageString);
9115
-    });
9116
-}
9117
-
9118
-// Buddy & Contacts
9119
-// ================
9120
-var Buddy = function(type, identity, CallerIDName, ExtNo, MobileNumber, ContactNumber1, ContactNumber2, lastActivity, desc, Email){
9121
-    this.type = type; // extension | contact | group
9122
-    this.identity = identity;
9123
-    this.CallerIDName = CallerIDName;
9124
-    this.Email = Email;
9125
-    this.Desc = desc;
9126
-    this.ExtNo = ExtNo;
9127
-    this.MobileNumber = MobileNumber;
9128
-    this.ContactNumber1 = ContactNumber1;
9129
-    this.ContactNumber2 = ContactNumber2;
9130
-    this.lastActivity = lastActivity; // Full Date as string eg "1208-03-21 15:34:23 UTC"
9131
-    this.devState = "dotOffline";
9132
-    this.presence = "Unknown";
9133
-    this.missed = 0;
9134
-    this.IsSelected = false;
9135
-    this.imageObjectURL = "";
9136
-}
9137
-function InitUserBuddies(){
9138
-    var template = { TotalRows:0, DataCollection:[] }
9139
-    localDB.setItem(profileUserID + "-Buddies", JSON.stringify(template));
9140
-    return JSON.parse(localDB.getItem(profileUserID + "-Buddies"));
9141
-}
9142
-function MakeBuddy(type, update, focus, subscribe, callerID, did){
9143
-    var json = JSON.parse(localDB.getItem(profileUserID + "-Buddies"));
9144
-    if(json == null) json = InitUserBuddies();
9145
-
9146
-    var buddyObj = null;
9147
-    if(type == "contact"){
9148
-        var id = uID();
9149
-        var dateNow = utcDateNow();
9150
-        json.DataCollection.push({
9151
-            Type: "contact", 
9152
-            LastActivity: dateNow,
9153
-            ExtensionNumber: "", 
9154
-            MobileNumber: "",
9155
-            ContactNumber1: did,
9156
-            ContactNumber2: "",
9157
-            uID: null,
9158
-            cID: id,
9159
-            gID: null,
9160
-            DisplayName: callerID,
9161
-            Position: "",
9162
-            Description: "",
9163
-            Email: "",
9164
-            MemberCount: 0
9165
-        });
9166
-        buddyObj = new Buddy("contact", id, callerID, "", "", did, "", dateNow, "", "");
9167
-        AddBuddy(buddyObj, update, focus);
9168
-    }
9169
-    else {
9170
-        var id = uID();
9171
-        var dateNow = utcDateNow();
9172
-        json.DataCollection.push({
9173
-            Type: "extension",
9174
-            LastActivity: dateNow,
9175
-            ExtensionNumber: did,
9176
-            MobileNumber: "",
9177
-            ContactNumber1: "",
9178
-            ContactNumber2: "",
9179
-            uID: id,
9180
-            cID: null,
9181
-            gID: null,
9182
-            DisplayName: callerID,
9183
-            Position: "",
9184
-            Description: "", 
9185
-            Email: "",
9186
-            MemberCount: 0
9187
-        });
9188
-        buddyObj = new Buddy("extension", id, callerID, did, "", "", "", dateNow, "", "");
9189
-        AddBuddy(buddyObj, update, focus, subscribe);
9190
-    }
9191
-    // Update Size: 
9192
-    json.TotalRows = json.DataCollection.length;
9193
-
9194
-    // Save To DB
9195
-    localDB.setItem(profileUserID + "-Buddies", JSON.stringify(json));
9196
-
9197
-    // Return new buddy
9198
-    return buddyObj;
9199
-}
9200
-function UpdateBuddyCalerID(buddyObj, callerID){
9201
-    buddyObj.CallerIDName = callerID;
9202
-
9203
-    var buddy = buddyObj.identity;
9204
-    // Update DB
9205
-    var json = JSON.parse(localDB.getItem(profileUserID + "-Buddies"));
9206
-    if(json != null){
9207
-        $.each(json.DataCollection, function (i, item) {
9208
-            if(item.uID == buddy || item.cID == buddy || item.gID == buddy){
9209
-                item.DisplayName = callerID;
9210
-                return false;
9211
-            }
9212
-        });
9213
-        // Save To DB
9214
-        localDB.setItem(profileUserID + "-Buddies", JSON.stringify(json));
9215
-    }
9216
-
9217
-    UpdateBuddyList();
9218
-}
9219
-function AddBuddy(buddyObj, update, focus, subscribe){
9220
-    Buddies.push(buddyObj);
9221
-    if(update == true) UpdateBuddyList();
9222
-    AddBuddyMessageStream(buddyObj);
9223
-    if(subscribe == true) SubscribeBuddy(buddyObj);
9224
-    if(focus == true) SelectBuddy(buddyObj.identity);
9225
-}
9226
-function PopulateBuddyList() {
9227
-    console.log("Clearing Buddies...");
9228
-    Buddies = new Array();
9229
-    console.log("Adding Buddies...");
9230
-    var json = JSON.parse(localDB.getItem(profileUserID + "-Buddies"));
9231
-    if(json == null) return;
9232
-
9233
-    console.log("Total Buddies: " + json.TotalRows);
9234
-    $.each(json.DataCollection, function (i, item) {
9235
-        if(item.Type == "extension"){
9236
-            // extension
9237
-            var buddy = new Buddy("extension", item.uID, item.DisplayName, item.ExtensionNumber, item.MobileNumber, item.ContactNumber1, item.ContactNumber2, item.LastActivity, item.Position, item.Email);
9238
-            AddBuddy(buddy, false, false);
9239
-        }
9240
-        else if(item.Type == "contact"){
9241
-            // contact
9242
-            var buddy = new Buddy("contact", item.cID, item.DisplayName, "", item.MobileNumber, item.ContactNumber1, item.ContactNumber2, item.LastActivity, item.Description, item.Email);
9243
-            AddBuddy(buddy, false, false);
9244
-        }
9245
-        else if(item.Type == "group"){
9246
-            // group
9247
-            var buddy = new Buddy("group", item.gID, item.DisplayName, item.ExtensionNumber, "", "", "", item.LastActivity, item.MemberCount + " member(s)", item.Email);
9248
-            AddBuddy(buddy, false, false);
9249
-        }
9250
-    });
9251
-
9252
-    // Update List (after add)
9253
-    console.log("Updating Buddy List...");
9254
-    UpdateBuddyList();
9255
-}
9256
-function UpdateBuddyList(){
9257
-    var filter = $("#txtFindBuddy").val();
9258
-
9259
-    $("#myContacts").empty();
9260
-
9261
-    var callCount = 0
9262
-    for(var l = 0; l < Lines.length; l++) {
9263
-
9264
-        var classStr = (Lines[l].IsSelected)? "buddySelected" : "buddy";
9265
-        if(Lines[l].SipSession != null) classStr = (Lines[l].SipSession.local_hold)? "buddyActiveCallHollding" : "buddyActiveCall";
9266
-
9267
-        var html = "<div id=\"line-"+ Lines[l].LineNumber +"\" class="+ classStr +" onclick=\"SelectLine('"+ Lines[l].LineNumber +"')\">";
9268
-        html += "<div class=lineIcon>"+ (l + 1) +"</div>";
9269
-        html += "<div class=contactNameText><i class=\"fa fa-phone\"></i> "+ lang.line +" "+ (l + 1) +"</div>";
9270
-        html += "<div id=\"Line-"+ Lines[l].ExtNo +"-datetime\" class=contactDate>&nbsp;</div>";
9271
-        html += "<div class=presenceText>"+ Lines[l].DisplayName +" <"+ Lines[l].DisplayNumber +">" +"</div>";
9272
-        html += "</div>";
9273
-        // SIP.Session.C.STATUS_TERMINATED
9274
-        if(Lines[l].SipSession && Lines[l].SipSession.data.earlyReject != true){
9275
-            $("#myContacts").append(html);
9276
-            callCount ++;
9277
-        }
9278
-    }
9279
-
9280
-    // Sort and shuffle Buddy List
9281
-    // ===========================
9282
-    Buddies.sort(function(a, b){
9283
-        var aMo = moment.utc(a.lastActivity.replace(" UTC", ""));
9284
-        var bMo = moment.utc(b.lastActivity.replace(" UTC", ""));
9285
-        if (aMo.isSameOrAfter(bMo, "second")) {
9286
-            return -1;
9287
-        } else return 1;
9288
-        return 0;
9289
-    });
9290
-
9291
-
9292
-    for(var b = 0; b < Buddies.length; b++) {
9293
-        var buddyObj = Buddies[b];
9294
-
9295
-        if(filter && filter.length >= 1){
9296
-            // Perform Filter Display
9297
-            var display = false;
9298
-            if(buddyObj.CallerIDName.toLowerCase().indexOf(filter.toLowerCase()) > -1 ) display = true;
9299
-            if(buddyObj.ExtNo.toLowerCase().indexOf(filter.toLowerCase()) > -1 ) display = true;
9300
-            if(buddyObj.Desc.toLowerCase().indexOf(filter.toLowerCase()) > -1 ) display = true;
9301
-            if(!display) continue;
9302
-        }
9303
-
9304
-        var today = moment.utc();
9305
-        var lastActivity = moment.utc(buddyObj.lastActivity.replace(" UTC", ""));
9306
-        var displayDateTime = "";
9307
-        if(lastActivity.isSame(today, 'day'))
9308
-        {
9309
-            displayDateTime = lastActivity.local().format(DisplayTimeFormat);
9310
-        } 
9311
-        else {
9312
-            displayDateTime = lastActivity.local().format(DisplayDateFormat);
9313
-        }
9314
-
9315
-        var classStr = (buddyObj.IsSelected)? "buddySelected" : "buddy";
9316
-        if(buddyObj.type == "extension") {
9317
-            var friendlyState = buddyObj.presence;
9318
-            if (friendlyState == "Unknown") friendlyState = lang.state_unknown;
9319
-            if (friendlyState == "Not online") friendlyState = lang.state_not_online;
9320
-            if (friendlyState == "Ready") friendlyState = lang.state_ready;
9321
-            if (friendlyState == "On the phone") friendlyState = lang.state_on_the_phone;
9322
-            if (friendlyState == "Ringing") friendlyState = lang.state_ringing;
9323
-            if (friendlyState == "On hold") friendlyState = lang.state_on_hold;
9324
-            if (friendlyState == "Unavailable") friendlyState = lang.state_unavailable;
9325
-
9326
-            // An extension on the same system
9327
-            var html = "<div id=\"contact-"+ buddyObj.identity +"\" class="+ classStr +" onmouseenter=\"ShowBuddyDial(this, '"+ buddyObj.identity +"')\" onmouseleave=\"HideBuddyDial(this, '"+ buddyObj.identity +"')\" onclick=\"SelectBuddy('"+ buddyObj.identity +"', 'extension')\">";
9328
-            html += "<span id=\"contact-"+ buddyObj.identity +"-devstate\" class=\""+ buddyObj.devState +"\"></span>";
9329
-            if (getDbItem("useRoundcube", "") == 1 && buddyObj.Email != '' && buddyObj.Email != null && typeof buddyObj.Email != 'undefined') {
9330
-                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>";
9331
-            }
9332
-            if (EnableVideoCalling) {
9333
-                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>";
9334
-                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>";
9335
-            } else {
9336
-                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>";
9337
-            }
9338
-            if(buddyObj.missed && buddyObj.missed > 0){
9339
-                html += "<span id=\"contact-"+ buddyObj.identity +"-missed\" class=missedNotifyer>"+ buddyObj.missed +"</span>";
9340
-            }
9341
-            else{
9342
-                html += "<span id=\"contact-"+ buddyObj.identity +"-missed\" class=missedNotifyer style=\"display:none\">"+ buddyObj.missed +"</span>";
9343
-            }
9344
-            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>";
9345
-            html += "<div class=contactNameText><i class=\"fa fa-phone-square\"></i> "+ buddyObj.ExtNo +" - "+ buddyObj.CallerIDName +"</div>";
9346
-            html += "<div id=\"contact-"+ buddyObj.identity +"-datetime\" class=contactDate>"+ displayDateTime +"</div>";
9347
-            html += "<div id=\"contact-"+ buddyObj.identity +"-presence\" class=presenceText>"+ friendlyState +"</div>";
9348
-            html += "</div>";
9349
-            $("#myContacts").append(html);
9350
-        } else if(buddyObj.type == "contact") { 
9351
-            // An Addressbook Contact
9352
-            var html = "<div id=\"contact-"+ buddyObj.identity +"\" class="+ classStr +" onmouseenter=\"ShowBuddyDial(this, '"+ buddyObj.identity +"')\" onmouseleave=\"HideBuddyDial(this, '"+ buddyObj.identity +"')\" onclick=\"SelectBuddy('"+ buddyObj.identity +"', 'contact')\">";
9353
-            if (getDbItem("useRoundcube", "") == 1 && buddyObj.Email != '' && buddyObj.Email != null && typeof buddyObj.Email != 'undefined') {
9354
-                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>";
9355
-            }
9356
-            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>";
9357
-            if(buddyObj.missed && buddyObj.missed > 0){
9358
-                html += "<span id=\"contact-"+ buddyObj.identity +"-missed\" class=missedNotifyer>"+ buddyObj.missed +"</span>";
9359
-            }
9360
-            else{
9361
-                html += "<span id=\"contact-"+ buddyObj.identity +"-missed\" class=missedNotifyer style=\"display:none\">"+ buddyObj.missed +"</span>";
9362
-            }
9363
-            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>";
9364
-            html += "<div class=contactNameText><i class=\"fa fa-address-card\"></i> "+ buddyObj.CallerIDName +"</div>";
9365
-            html += "<div id=\"contact-"+ buddyObj.identity +"-datetime\" class=contactDate>"+ displayDateTime +"</div>";
9366
-            html += "<div class=presenceText>"+ buddyObj.Desc +"</div>";
9367
-            html += "</div>";
9368
-            $("#myContacts").append(html);
9369
-        } else if(buddyObj.type == "group"){ 
9370
-            // A collection of extensions and contacts
9371
-            var html = "<div id=\"contact-"+ buddyObj.identity +"\" class="+ classStr +" onmouseenter=\"ShowBuddyDial(this, '"+ buddyObj.identity +"')\" onmouseleave=\"HideBuddyDial(this, '"+ buddyObj.identity +"')\" onclick=\"SelectBuddy('"+ buddyObj.identity +"', 'group')\">";
9372
-            if (getDbItem("useRoundcube", "") == 1 && buddyObj.Email != '' && buddyObj.Email != null && typeof buddyObj.Email != 'undefined') {
9373
-                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>";
9374
-            }
9375
-            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>";
9376
-            if(buddyObj.missed && buddyObj.missed > 0){
9377
-                html += "<span id=\"contact-"+ buddyObj.identity +"-missed\" class=missedNotifyer>"+ buddyObj.missed +"</span>";
9378
-            }
9379
-            else{
9380
-                html += "<span id=\"contact-"+ buddyObj.identity +"-missed\" class=missedNotifyer style=\"display:none\">"+ buddyObj.missed +"</span>";
9381
-            }
9382
-            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>";
9383
-            html += "<div class=contactNameText><i class=\"fa fa-users\"></i> "+ buddyObj.CallerIDName +"</div>";
9384
-            html += "<div id=\"contact-"+ buddyObj.identity +"-datetime\" class=contactDate>"+ displayDateTime +"</div>";
9385
-            html += "<div class=presenceText>"+ buddyObj.Desc +"</div>";
9386
-            html += "</div>";
9387
-            $("#myContacts").append(html);
9388
-        }
9389
-    }
9390
-}
9391
-function AddBuddyMessageStream(buddyObj) {
9392
-    var html = "<table id=\"stream-"+ buddyObj.identity +"\" class=stream cellspacing=5 cellpadding=0>";
9393
-    html += "<tr><td class=streamSection style=\"height: 48px;\">";
9394
-
9395
-    // Close|Return|Back Button
9396
-    html += "<div style=\"float:left; margin:8.7px 0px 0px 8.7px; width: 38px; height:38px; line-height:38px;\">"
9397
-
9398
-    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> ";
9399
-    html += "</div>"
9400
-    
9401
-    // Profile UI
9402
-    html += "<div class=contact style=\"float: left; position: absolute; left: 47px; right: 190px;\" onclick=\"ShowBuddyProfileMenu('"+ buddyObj.identity +"', this, '"+ buddyObj.type +"')\">";
9403
-    if(buddyObj.type == "extension") {
9404
-        html += "<span id=\"contact-"+ buddyObj.identity +"-devstate-main\" class=\""+ buddyObj.devState +"\"></span>";
9405
-    }
9406
-    if(buddyObj.type == "extension") {
9407
-        html += "<div id=\"contact-"+ buddyObj.identity +"-picture-main\" class=buddyIcon style=\"background-image: url('"+ getPicture(buddyObj.identity) +"')\"></div>";
9408
-    }
9409
-    else if(buddyObj.type == "contact") {
9410
-        html += "<div class=buddyIcon style=\"background-image: url('"+ getPicture(buddyObj.identity,"contact") +"')\"></div>";
9411
-    }
9412
-    else if(buddyObj.type == "group") {
9413
-        html += "<div class=buddyIcon style=\"background-image: url('"+ getPicture(buddyObj.identity,"group") +"')\"></div>";
9414
-    }
9415
-    if(buddyObj.type == "extension") {
9416
-        html += "<div class=contactNameText style=\"margin-right: 0px;\"><i class=\"fa fa-phone-square\"></i> "+ buddyObj.ExtNo +" - "+ buddyObj.CallerIDName +"</div>";
9417
-    }
9418
-    else if(buddyObj.type == "contact") {
9419
-        html += "<div class=contactNameText style=\"margin-right: 0px;\"><i class=\"fa fa-address-card\"></i> "+ buddyObj.CallerIDName +"</div>";
9420
-    } 
9421
-    else if(buddyObj.type == "group") {
9422
-        html += "<div class=contactNameText style=\"margin-right: 0px;\"><i class=\"fa fa-users\"></i> "+ buddyObj.CallerIDName +"</div>";
9423
-    }
9424
-    if(buddyObj.type == "extension") {
9425
-        var friendlyState = buddyObj.presence;
9426
-        if (friendlyState == "Unknown") friendlyState = lang.state_unknown;
9427
-        if (friendlyState == "Not online") friendlyState = lang.state_not_online;
9428
-        if (friendlyState == "Ready") friendlyState = lang.state_ready;
9429
-        if (friendlyState == "On the phone") friendlyState = lang.state_on_the_phone;
9430
-        if (friendlyState == "Ringing") friendlyState = lang.state_ringing;
9431
-        if (friendlyState == "On hold") friendlyState = lang.state_on_hold;
9432
-        if (friendlyState == "Unavailable") friendlyState = lang.state_unavailable;
9433
-
9434
-        html += "<div id=\"contact-"+ buddyObj.identity +"-presence-main\" class=presenceText>"+ friendlyState +"</div>";
9435
-    } else{
9436
-        html += "<div id=\"contact-"+ buddyObj.identity +"-presence-main\" class=presenceText>"+ buddyObj.Desc +"</div>";
9437
-    }
9438
-    html += "</div>";
9439
-
9440
-    // Action Buttons
9441
-    html += "<div style=\"float:right; line-height:46px; margin:3.2px 5px 0px 0px;\">";
9442
-    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> ";
9443
-    if(buddyObj.type == "extension" && EnableVideoCalling) {
9444
-        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> ";
9445
-    }
9446
-    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> ";
9447
-    if(buddyObj.type == "extension") {
9448
-        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> ";
9449
-    }
9450
-    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> ";
9451
-    html += "</div>";
9452
-
9453
-    // Separator --------------------------------------------------------------------------
9454
-    html += "<div style=\"clear:both; height:0px\"></div>"
9455
-
9456
-    // Calling UI --------------------------------------------------------------------------
9457
-    html += "<div id=\"contact-"+ buddyObj.identity +"-calling\">";
9458
-
9459
-    // Gneral Messages
9460
-    html += "<div id=\"contact-"+ buddyObj.identity +"-timer\" style=\"float: right; margin-top: 4px; margin-right: 10px; color: #575757; display:none;\"></div>";
9461
-    html += "<div id=\"contact-"+ buddyObj.identity +"-msg\" class=callStatus style=\"display:none\">...</div>";
9462
-
9463
-    // Call Answer UI
9464
-    html += "<div id=\"contact-"+ buddyObj.identity +"-AnswerCall\" class=answerCall style=\"display:none\">";
9465
-    html += "<div>";
9466
-    html += "<button onclick=\"AnswerAudioCall('"+ buddyObj.identity +"')\" class=answerButton><i class=\"fa fa-phone\"></i>&nbsp;&nbsp;"+ lang.answer_call +"</button> ";
9467
-    if(buddyObj.type == "extension" && EnableVideoCalling) {
9468
-        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> ";
9469
-    }
9470
-    html += "<button onclick=\"RejectCall('"+ buddyObj.identity +"')\" class=hangupButton><i class=\"fa fa-phone\"></i>&nbsp;&nbsp;"+ lang.reject_call +"</button> ";
9471
-    html += "</div>";
9472
-    html += "</div>";
9473
-
9474
-    html += "</div>";
9475
-
9476
-    // Search & Related Elements
9477
-    html += "<div id=\"contact-"+ buddyObj.identity +"-search\" style=\"margin-top:6px; display:none\">";
9478
-    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>";
9479
-
9480
-    html += "</div>";
9481
-
9482
-    html += "</td></tr>";
9483
-    html += "<tr><td class=\"streamSection streamSectionBackground\">";
9484
-
9485
-    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 +"')\">";
9486
-    // Previous Chat messages
9487
-    html += "</div>";
9488
-
9489
-    html += "</td></tr>";
9490
-
9491
-    if ((buddyObj.type == "extension" || buddyObj.type == "group") && EnableTextMessaging) {
9492
-
9493
-        html += "<tr><td  id=sendChatMessageSection class=streamSection style=\"height:110px\">";
9494
-
9495
-        // Send Paste Image
9496
-        html += "<div id=\"contact-"+ buddyObj.identity +"-imagePastePreview\" class=sendImagePreview style=\"display:none\" tabindex=0></div>";
9497
-
9498
-        // Send File
9499
-        html += "<div id=\"contact-"+ buddyObj.identity +"-fileShare\" style=\"display:none\">";
9500
-        html += "<input type=file multiple onchange=\"console.log(this)\" />";
9501
-        html += "</div>";
9502
-
9503
-        // Send Audio Recording
9504
-        html += "<div id=\"contact-"+ buddyObj.identity +"-audio-recording\" style=\"display:none\"></div>";
9505
-
9506
-        // Send Video Recording
9507
-        html += "<div id=\"contact-"+ buddyObj.identity +"-video-recording\" style=\"display:none\"></div>";
9508
-
9509
-        // Dictate Message
9510
-        // html += "<div id=\"contact-"+ buddyObj.identity +"-dictate-message\" style=\"display:none\"></div>";
9511
-
9512
-        // Emoji Menu Bar
9513
-        html += "<div id=\"contact-"+ buddyObj.identity +"-emoji-menu\" style=\"display:none\" class=\"EmojiMenu\"></div>";
9514
-
9515
-        // =====================================
9516
-        // Type Area
9517
-        html += "<table class=sendMessageContainer cellpadding=0 cellspacing=0><tr>";
9518
-        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>";
9519
-        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>";
9520
-        html += "<button onclick=\"ShowEmojiBar('"+ buddyObj.identity +"')\" class=roundButtonsSpec title=\""+ lang.select_expression + "\"><i class=\"fa fa-smile-o\"></i></button>";
9521
-        html += "<button onclick=\"SendFile('"+ buddyObj.identity +"')\" class=roundButtonsSpec title=\""+ lang.send_file + "\"><i class=\"fa fa-file-text-o\"></i></button></td>";
9522
-        html += "</tr></table>";
9523
-        html += "</td></tr>";
9524
-    }
9525
-
9526
-    html += "</table>";
9527
-
9528
-    $("#rightContent").append(html);
9529
-}
9530
-function RemoveBuddyMessageStream(buddyObj){
9531
-    CloseBuddy(buddyObj.identity);
9532
-
9533
-    UpdateBuddyList();
9534
-
9535
-    // Remove Stream
9536
-    $("#stream-"+ buddyObj.identity).remove();
9537
-    var stream = JSON.parse(localDB.getItem(buddyObj.identity + "-stream"));
9538
-    localDB.removeItem(buddyObj.identity + "-stream");
9539
-
9540
-    // Remove Buddy
9541
-    var json = JSON.parse(localDB.getItem(profileUserID + "-Buddies"));
9542
-    var x = 0;
9543
-    $.each(json.DataCollection, function (i, item) {
9544
-        if(item.uID == buddyObj.identity || item.cID == buddyObj.identity || item.gID == buddyObj.identity){
9545
-            x = i;
9546
-            return false;
9547
-        }
9548
-    });
9549
-    json.DataCollection.splice(x,1);
9550
-    json.TotalRows = json.DataCollection.length;
9551
-    localDB.setItem(profileUserID + "-Buddies", JSON.stringify(json));
9552
-
9553
-    // Remove Images
9554
-    localDB.removeItem("img-"+ buddyObj.identity +"-extension");
9555
-    localDB.removeItem("img-"+ buddyObj.identity +"-contact");
9556
-    localDB.removeItem("img-"+ buddyObj.identity +"-group");
9557
-
9558
-    // Remove Call Recordings
9559
-    if(stream && stream.DataCollection && stream.DataCollection.length >= 1){
9560
-        DeleteCallRecordings(buddyObj.identity, stream);
9561
-    }
9562
-    
9563
-    // Remove QOS Data
9564
-    DeleteQosData(buddyObj.identity);
9565
-}
9566
-function DeleteCallRecordings(buddy, stream){
9567
-    var indexedDB = window.indexedDB;
9568
-    var request = indexedDB.open("CallRecordings");
9569
-    request.onerror = function(event) {
9570
-        console.error("IndexDB Request Error:", event);
9571
-    }
9572
-    request.onupgradeneeded = function(event) {
9573
-        console.warn("Upgrade Required for IndexDB... probably because of first time use.");
9574
-        // If this is the case, there will be no call recordings
9575
-    }
9576
-    request.onsuccess = function(event) {
9577
-        console.log("IndexDB connected to CallRecordings");
9578
-
9579
-        var IDB = event.target.result;
9580
-        if(IDB.objectStoreNames.contains("Recordings") == false){
9581
-            console.warn("IndexDB CallRecordings.Recordings does not exists");
9582
-            return;
9583
-        }
9584
-        IDB.onerror = function(event) {
9585
-            console.error("IndexDB Error:", event);
9586
-        }
9587
-
9588
-        // Loop and Delete
9589
-        $.each(stream.DataCollection, function (i, item) {
9590
-            if (item.Recordings && item.Recordings.length) {
9591
-                $.each(item.Recordings, function (i, recording) {
9592
-                    console.log("Deleting Call Recording: ", recording.uID);
9593
-                    var objectStore = IDB.transaction(["Recordings"], "readwrite").objectStore("Recordings");
9594
-                    try{
9595
-                        var deleteRequest = objectStore.delete(recording.uID);
9596
-                        deleteRequest.onsuccess = function(event) {
9597
-                            console.log("Call Recording Deleted: ", recording.uID);
9598
-                        }
9599
-                    } catch(e){
9600
-                        console.log("Call Recording Delete failed: ", e);
9601
-                    }
9602
-                });
9603
-            }
9604
-        });
9605
-    }
9606
-}
9607
-
9608
-function MakeUpName(){
9609
-    var shortname = 4;
9610
-    var longName = 12;
9611
-    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"];
9612
-    var rtn = "";
9613
-    rtn += letters[Math.floor(Math.random() * letters.length)];
9614
-    for(var n=0; n<Math.floor(Math.random() * longName) + shortname; n++){
9615
-        rtn += letters[Math.floor(Math.random() * letters.length)].toLowerCase();
9616
-    }
9617
-    rtn += " ";
9618
-    rtn += letters[Math.floor(Math.random() * letters.length)];
9619
-    for(var n=0; n<Math.floor(Math.random() * longName) + shortname; n++){
9620
-        rtn += letters[Math.floor(Math.random() * letters.length)].toLowerCase();
9621
-    }
9622
-    return rtn;
9623
-}
9624
-function MakeUpNumber(){
9625
-    var numbers = ["0","1","2","3","4","5","6","7","8","9","0"];
9626
-    var rtn = "0";
9627
-    for(var n=0; n<9; n++){
9628
-        rtn += numbers[Math.floor(Math.random() * numbers.length)];
9629
-    }
9630
-    return rtn;
9631
-}
9632
-function MakeUpBuddies(int){
9633
-    for(var i=0; i<int; i++){
9634
-        var buddyObj = new Buddy("contact", uID(), MakeUpName(), "", "", MakeUpNumber(), "", utcDateNow(), "Testing", "");
9635
-        AddBuddy(buddyObj, false, false);
9636
-    }
9637
-    UpdateBuddyList();
9638
-}
9639
-
9640
-function SelectBuddy(buddy) {
9641
-
9642
-    $("#roundcubeFrame").remove();
9643
-    $(".streamSelected").each(function() { $(this).show(); });
9644
-
9645
-    var buddyObj = FindBuddyByIdentity(buddy);
9646
-    if(buddyObj == null) return;
9647
-
9648
-    for(var b = 0; b < Buddies.length; b++) {
9649
-        if(Buddies[b].IsSelected == true && Buddies[b].identity == buddy){
9650
-            // Nothing to do, you re-selected the same buddy;
9651
-            return;
9652
-        }
9653
-    }
9654
-
9655
-    console.log("Selecting Buddy: "+ buddy);
9656
-
9657
-    selectedBuddy = buddyObj;
9658
-
9659
-    // Can only display one thing on the right
9660
-    $(".streamSelected").each(function () {
9661
-        $(this).prop('class', 'stream');
9662
-    });
9663
-    $("#stream-" + buddy).prop('class', 'streamSelected');
9664
-
9665
-    // Update Lines List
9666
-    for(var l = 0; l < Lines.length; l++) {
9667
-        var classStr = "buddy";
9668
-        if(Lines[l].SipSession != null) classStr = (Lines[l].SipSession.local_hold)? "buddyActiveCallHollding" : "buddyActiveCall";
9669
-        $("#line-" + Lines[l].LineNumber).prop('class', classStr);
9670
-        Lines[l].IsSelected = false;
9671
-    }
9672
-
9673
-    ClearMissedBadge(buddy);
9674
-    // Update Buddy List
9675
-    for(var b = 0; b < Buddies.length; b++) {
9676
-        var classStr = (Buddies[b].identity == buddy)? "buddySelected" : "buddy";
9677
-        $("#contact-" + Buddies[b].identity).prop('class', classStr);
9678
-
9679
-        $("#contact-"+ Buddies[b].identity +"-ChatHistory").empty();
9680
-
9681
-        Buddies[b].IsSelected = (Buddies[b].identity == buddy);
9682
-    }
9683
-
9684
-    // Change to Stream if in Narrow view
9685
-    UpdateUI();
9686
-    
9687
-    // Refresh Stream
9688
-    RefreshStream(buddyObj);
9689
-
9690
-    try{
9691
-        $("#contact-" + buddy).get(0).scrollIntoViewIfNeeded();
9692
-    } catch(e){}
9693
-
9694
-    // Save Selected
9695
-    localDB.setItem("SelectedBuddy", buddy);
9696
-}
9697
-function CloseBuddy(buddy){
9698
-    // Lines and Buddies (Left)
9699
-    $(".buddySelected").each(function () {
9700
-        $(this).prop('class', 'buddy');
9701
-    });
9702
-    // Streams (Right)
9703
-    $(".streamSelected").each(function () {
9704
-        $(this).prop('class', 'stream');
9705
-    });
9706
-
9707
-    console.log("Closing Buddy: "+ buddy);
9708
-    for(var b = 0; b < Buddies.length; b++){
9709
-        Buddies[b].IsSelected = false;
9710
-    }
9711
-    selectedBuddy = null;
9712
-    for(var l = 0; l < Lines.length; l++){
9713
-        Lines[l].IsSelected = false;
9714
-    }
9715
-    selectedLine = null;
9716
-
9717
-    // Save Selected
9718
-    localDB.setItem("SelectedBuddy", null);
9719
-
9720
-    // Change to Stream if in Narrow view
9721
-    UpdateUI();
9722
-}
9723
-function DownloadChatText(buddy) {
9724
-
9725
-    var buddyInfo = FindBuddyByIdentity(buddy);
9726
-    var DispNamePre = buddyInfo.CallerIDName;
9727
-    var DispName = DispNamePre.replace(" ", "_");
9728
-    var buddyExt = buddyInfo.ExtNo;
9729
-    var presDate = moment().format("YYYY-MM-DD_HH-mm-ss");
9730
-
9731
-    var wholeChatTextTitle = "\n" + "Roundpin Chat With " + DispNamePre + " (extension " + buddyExt + "), saved on " + moment().format("YYYY-MM-DD HH:mm:ss") + "\n\n\n\n";
9732
-    var wholeChatText = "";
9733
-
9734
-    $("#contact-"+buddy+"-ChatHistory .chatMessageTable").each(function() {
9735
-       if ($(this).hasClass("theirChatMessage")) {
9736
-           wholeChatText += "\n" + DispNamePre + "\n" + $(this).text() + "\n\n";
9737
-       } else {
9738
-           wholeChatText += "\n" + "Me" + "\n" + $(this).text() + "\n\n";
9739
-       }
9740
-    });
9741
-
9742
-    if (wholeChatText == "") { alert("There is no chat text to save ! "); return; }
9743
-    var wholeChatTextConc = wholeChatTextTitle + wholeChatText;
9744
-    var downFilename = 'Roundpin_Chat-' + DispName + "_" + presDate;
9745
-    var downlink = document.createElement('a');
9746
-    var mimeType = 'text/plain';
9747
-
9748
-    downlink.setAttribute('download', downFilename);
9749
-    downlink.setAttribute('href', 'data:' + mimeType + ';charset=utf-8,' + encodeURIComponent(wholeChatTextConc));
9750
-    downlink.click(); 
9751
-}
9752
-function RemoveBuddy(buddy){
9753
-
9754
-    var buddyData = FindBuddyByIdentity(buddy);
9755
-    var buddyDisplayName = buddyData.CallerIDName;
9756
-
9757
-    // Check if you are on the phone, etc.
9758
-    Confirm(lang.confirm_remove_buddy, lang.remove_buddy, function(){
9759
-        for(var b = 0; b < Buddies.length; b++) {
9760
-            if(Buddies[b].identity == buddy) {
9761
-                RemoveBuddyMessageStream(Buddies[b]);
9762
-                UnsubscribeBuddy(Buddies[b])
9763
-                Buddies.splice(b, 1);
9764
-                break;
9765
-            }
9766
-        }
9767
-        // Remove contact from SQL database
9768
-        deleteBuddyFromSqldb(buddyDisplayName);
9769
-
9770
-        UpdateBuddyList();
9771
-    });
9772
-}
9773
-function FindBuddyByDid(did){
9774
-    // Used only in Inboud
9775
-    for(var b = 0; b < Buddies.length; b++){
9776
-        if(Buddies[b].ExtNo == did || Buddies[b].MobileNumber == did || Buddies[b].ContactNumber1 == did || Buddies[b].ContactNumber2 == did) {
9777
-            return Buddies[b];
9778
-        }
9779
-    }
9780
-    return null;
9781
-}
9782
-function FindBuddyByExtNo(ExtNo){
9783
-    for(var b = 0; b < Buddies.length; b++){
9784
-        if(Buddies[b].type == "extension" && Buddies[b].ExtNo == ExtNo) return Buddies[b];
9785
-    }
9786
-    return null;
9787
-}
9788
-function FindBuddyByNumber(number){
9789
-    // Number could be: +XXXXXXXXXX
9790
-    // Any special characters must be removed prior to adding
9791
-    for(var b = 0; b < Buddies.length; b++){
9792
-        if(Buddies[b].MobileNumber == number || Buddies[b].ContactNumber1 == number || Buddies[b].ContactNumber2 == number) {
9793
-            return Buddies[b];
9794
-        }
9795
-    }
9796
-    return null;
9797
-}
9798
-function FindBuddyByIdentity(identity){
9799
-    for(var b = 0; b < Buddies.length; b++){
9800
-        if(Buddies[b].identity == identity) return Buddies[b];
9801
-    }
9802
-    return null;
9803
-}
9804
-function SearchStream(obj, buddy){
9805
-    var q = obj.value;
9806
-
9807
-    var buddyObj = FindBuddyByIdentity(buddy);
9808
-    if(q == ""){
9809
-        console.log("Restore Stream");
9810
-        RefreshStream(buddyObj);
9811
-    }
9812
-    else{
9813
-        RefreshStream(buddyObj, q);
9814
-    }
9815
-}
9816
-function RefreshStream(buddyObj, filter) {
9817
-    $("#contact-" + buddyObj.identity + "-ChatHistory").empty();
9818
-
9819
-    var json = JSON.parse(localDB.getItem(buddyObj.identity +"-stream"));
9820
-    if(json == null || json.DataCollection == null) return;
9821
-
9822
-    // Sort DataCollection (Newest items first)
9823
-    json.DataCollection.sort(function(a, b){
9824
-        var aMo = moment.utc(a.ItemDate.replace(" UTC", ""));
9825
-        var bMo = moment.utc(b.ItemDate.replace(" UTC", ""));
9826
-        if (aMo.isSameOrAfter(bMo, "second")) {
9827
-            return -1;
9828
-        } else return 1;
9829
-        return 0;
9830
-    });
9831
-
9832
-    // Filter
9833
-    if(filter && filter != ""){
9834
-
9835
-        console.log("Rows without filter ("+ filter +"): ", json.DataCollection.length);
9836
-        json.DataCollection = json.DataCollection.filter(function(item){
9837
-            if(filter.indexOf("date: ") != -1){
9838
-                // Apply Date Filter
9839
-                var dateFilter = getFilter(filter, "date");
9840
-                if(dateFilter != "" && item.ItemDate.indexOf(dateFilter) != -1) return true;
9841
-            }
9842
-            if(item.MessageData && item.MessageData.length > 1){
9843
-                if(item.MessageData.toLowerCase().indexOf(filter.toLowerCase()) != -1) return true;
9844
-                if(filter.toLowerCase().indexOf(item.MessageData.toLowerCase()) != -1) return true;
9845
-            }
9846
-            if (item.ItemType == "MSG") {
9847
-                // Special search
9848
-            } 
9849
-            else if (item.ItemType == "CDR") {
9850
-                // Tag search
9851
-                if(item.Tags && item.Tags.length > 1){
9852
-                    var tagFilter = getFilter(filter, "tag");
9853
-                    if(tagFilter != "") {
9854
-                        if(item.Tags.some(function(i){
9855
-                            if(tagFilter.toLowerCase().indexOf(i.value.toLowerCase()) != -1) return true;
9856
-                            if(i.value.toLowerCase().indexOf(tagFilter.toLowerCase()) != -1) return true;
9857
-                            return false;
9858
-                        }) == true) return true;
9859
-                    }
9860
-                }
9861
-            }
9862
-            else if(item.ItemType == "FILE"){
9863
-
9864
-            } 
9865
-            else if(item.ItemType == "SMS"){
9866
-                 // Not yet implemented
9867
-            }
9868
-            // return true to keep;
9869
-            return false;
9870
-        });
9871
-        console.log("Rows After Filter: ", json.DataCollection.length);
9872
-    }
9873
-
9874
-    // Create Buffer
9875
-    if(json.DataCollection.length > StreamBuffer){
9876
-        console.log("Rows:", json.DataCollection.length, " (will be trimed to "+ StreamBuffer +")");
9877
-        // Always limit the Stream to {StreamBuffer}, users must search for messages further back
9878
-        json.DataCollection.splice(StreamBuffer);
9879
-    }
9880
-
9881
-    $.each(json.DataCollection, function (i, item) {
9882
-
9883
-        var IsToday = moment.utc(item.ItemDate.replace(" UTC", "")).isSame(moment.utc(), "day");
9884
-        var DateTime = "  " + moment.utc(item.ItemDate.replace(" UTC", "")).local().calendar(null, { sameElse: DisplayDateFormat });
9885
-        if(IsToday) DateTime = "  " + moment.utc(item.ItemDate.replace(" UTC", "")).local().format(DisplayTimeFormat);
9886
-
9887
-        if (item.ItemType == "MSG") {
9888
-            // Add Chat Message
9889
-            // ===================
9890
-            var deliveryStatus = "<i class=\"fa fa-question-circle-o SendingMessage\"></i>";
9891
-            if(item.Sent == true) deliveryStatus = "<i class=\"fa fa-check SentMessage\"></i>";
9892
-            if(item.Sent == false) deliveryStatus = "<i class=\"fa fa-exclamation-circle FailedMessage\"></i>";
9893
-            if(item.Delivered) deliveryStatus += "<i class=\"fa fa-check DeliveredMessage\"></i>";
9894
-
9895
-            var formattedMessage = ReformatMessage(item.MessageData);
9896
-            var longMessage = (formattedMessage.length > 1000);
9897
-
9898
-            if (item.SrcUserId == profileUserID) {
9899
-                // You are the source (sending)
9900
-                if (formattedMessage.length != 0) {
9901
-                    var messageString = "<table class=\"ourChatMessage chatMessageTable\" cellspacing=0 cellpadding=0><tr>";
9902
-                    messageString += "<td class=ourChatMessageText onmouseenter=\"ShowChatMenu(this)\" onmouseleave=\"HideChatMenu(this)\">";
9903
-                    messageString += "<span onclick=\"ShowMessgeMenu(this,'MSG','"+  item.ItemId +"', '"+ buddyObj.identity +"')\" class=chatMessageDropdown style=\"display:none\"><i class=\"fa fa-chevron-down\"></i></span>";
9904
-                    messageString += "<div id=msg-text-"+ item.ItemId +" class=messageText style=\""+ ((longMessage)? "max-height:190px; overflow:hidden" : "") +"\">" + formattedMessage + "</div>";
9905
-                    if(longMessage){
9906
-                       messageString += "<div id=msg-readmore-"+  item.ItemId +" class=messageReadMore><span onclick=\"ExpandMessage(this,'"+ item.ItemId +"', '"+ buddyObj.identity +"')\">"+ lang.read_more +"</span></div>";
9907
-                    }
9908
-
9909
-                    messageString += "<div class=messageDate>" + DateTime + " " + deliveryStatus +"</div>";
9910
-                    messageString += "</td>";
9911
-                    messageString += "</tr></table>";
9912
-                }
9913
-            } 
9914
-            else {
9915
-                // You are the destination (receiving)
9916
-                var ActualSender = "";
9917
-                if (formattedMessage.length != 0) {
9918
-                    var messageString = "<table class=\"theirChatMessage chatMessageTable\" cellspacing=0 cellpadding=0><tr>";
9919
-                    messageString += "<td class=theirChatMessageText onmouseenter=\"ShowChatMenu(this)\" onmouseleave=\"HideChatMenu(this)\">";
9920
-                    messageString += "<span onclick=\"ShowMessgeMenu(this,'MSG','"+  item.ItemId +"', '"+ buddyObj.identity +"')\" class=chatMessageDropdown style=\"display:none\"><i class=\"fa fa-chevron-down\"></i></span>";
9921
-
9922
-                    if(buddyObj.type == "group"){
9923
-                       messageString += "<div class=messageDate>" + ActualSender + "</div>";
9924
-                    }
9925
-                    messageString += "<div id=msg-text-"+ item.ItemId +" class=messageText style=\""+ ((longMessage)? "max-height:190px; overflow:hidden" : "") +"\">" + formattedMessage + "</div>";
9926
-                    if(longMessage){
9927
-                       messageString += "<div id=msg-readmore-"+  item.ItemId +" class=messageReadMore><span onclick=\"ExpandMessage(this,'"+ item.ItemId +"', '"+ buddyObj.identity +"')\">"+ lang.read_more +"</span></div>";
9928
-                    }
9929
-                    messageString += "<div class=messageDate>"+ DateTime + "</div>";
9930
-                    messageString += "</td>";
9931
-                    messageString += "</tr></table>";
9932
-                }
9933
-            }
9934
-            if (formattedMessage.length != 0) {
9935
-                $("#contact-" + buddyObj.identity + "-ChatHistory").prepend(messageString);
9936
-            }
9937
-        } 
9938
-        else if (item.ItemType == "CDR") {
9939
-            // Add CDR 
9940
-            // =======
9941
-            var iconColor = (item.Billsec > 0)? "green" : "red";
9942
-            var formattedMessage = "";
9943
-
9944
-            // Flagged
9945
-            var flag = "<span id=cdr-flagged-"+  item.CdrId +" style=\""+ ((item.Flagged)? "" : "display:none") +"\">";
9946
-            flag += "<i class=\"fa fa-flag FlagCall\"></i> ";
9947
-            flag += "</span>";
9948
-
9949
-            // Comment
9950
-            var callComment = "";
9951
-            if(item.MessageData) callComment = item.MessageData;
9952
-
9953
-            // Tags
9954
-            if(!item.Tags) item.Tags = [];
9955
-            var CallTags = "<ul id=cdr-tags-"+  item.CdrId +" class=tags style=\""+ ((item.Tags && item.Tags.length > 0)? "" : "display:none" ) +"\">"
9956
-            $.each(item.Tags, function (i, tag) {
9957
-                CallTags += "<li onclick=\"TagClick(this, '"+ item.CdrId +"', '"+ buddyObj.identity +"')\">"+ tag.value +"</li>";
9958
-            });
9959
-            CallTags += "<li class=tagText><input maxlength=24 type=text onkeypress=\"TagKeyPress(event, this, '"+ item.CdrId +"', '"+ buddyObj.identity +"')\" onfocus=\"TagFocus(this)\"></li>";
9960
-            CallTags += "</ul>";
9961
-
9962
-            // Call Type
9963
-            var callIcon = (item.WithVideo)? "fa-video-camera" :  "fa-phone";
9964
-            formattedMessage += "<i class=\"fa "+ callIcon +"\" style=\"color:"+ iconColor +"\"></i>";
9965
-            var audioVideo = (item.WithVideo)? lang.a_video_call :  lang.an_audio_call;
9966
-
9967
-            // Recordings
9968
-            var recordingsHtml = "";
9969
-            if(item.Recordings && item.Recordings.length >= 1){
9970
-                $.each(item.Recordings, function (i, recording) {
9971
-                    if(recording.uID){
9972
-                        var StartTime = moment.utc(recording.startTime.replace(" UTC", "")).local();
9973
-                        var StopTime = moment.utc(recording.stopTime.replace(" UTC", "")).local();
9974
-                        var recordingDuration = moment.duration(StopTime.diff(StartTime));
9975
-                        recordingsHtml += "<div class=callRecording>";
9976
-                        if(item.WithVideo){
9977
-                            if(recording.Poster){
9978
-                                var posterWidth = recording.Poster.width;
9979
-                                var posterHeight = recording.Poster.height;
9980
-                                var posterImage = recording.Poster.posterBase64;
9981
-                                recordingsHtml += "<div><IMG src=\""+ posterImage +"\"><button onclick=\"PlayVideoCallRecording(this, '"+ item.CdrId +"', '"+ recording.uID +"')\" class=videoPoster><i class=\"fa fa-play\"></i></button></div>";
9982
-                            }
9983
-                            else {
9984
-                                recordingsHtml += "<div><button onclick=\"PlayVideoCallRecording(this, '"+ item.CdrId +"', '"+ recording.uID +"', '"+ buddyObj.identity +"')\"><i class=\"fa fa-video-camera\"></i></button></div>";
9985
-                            }
9986
-                        } 
9987
-                        else {
9988
-                            recordingsHtml += "<div><button onclick=\"PlayAudioCallRecording(this, '"+ item.CdrId +"', '"+ recording.uID +"', '"+ buddyObj.identity +"')\"><i class=\"fa fa-play\"></i></button></div>";
9989
-                        } 
9990
-                        recordingsHtml += "<div>"+ lang.started +": "+ StartTime.format(DisplayTimeFormat) +" <i class=\"fa fa-long-arrow-right\"></i> "+ lang.stopped +": "+ StopTime.format(DisplayTimeFormat) +"</div>";
9991
-                        recordingsHtml += "<div>"+ lang.recording_duration +": "+ formatShortDuration(recordingDuration.asSeconds()) +"</div>";
9992
-                        recordingsHtml += "<div>";
9993
-                        recordingsHtml += "<span id=\"cdr-video-meta-width-"+ item.CdrId +"-"+ recording.uID +"\"></span>";
9994
-                        recordingsHtml += "<span id=\"cdr-video-meta-height-"+ item.CdrId +"-"+ recording.uID +"\"></span>";
9995
-                        recordingsHtml += "<span id=\"cdr-media-meta-size-"+ item.CdrId +"-"+ recording.uID +"\"></span>";
9996
-                        recordingsHtml += "<span id=\"cdr-media-meta-codec-"+ item.CdrId +"-"+ recording.uID +"\"></span>";
9997
-                        recordingsHtml += "</div>";
9998
-                        recordingsHtml += "</div>";
9999
-                    }
10000
-                });
10001
-            }
10002
-
10003
-            if (item.SrcUserId == profileUserID) {
10004
-                // (Outbound) You(profileUserID) initiated a call
10005
-                if(item.Billsec == "0") {
10006
-                    formattedMessage += " "+ lang.you_tried_to_make +" "+ audioVideo +" ("+ item.ReasonText +").";
10007
-                } 
10008
-                else {
10009
-                    formattedMessage += " "+ lang.you_made + " "+ audioVideo +", "+ lang.and_spoke_for +" " + formatDuration(item.Billsec) + ".";
10010
-                }
10011
-                var messageString = "<table class=\"ourChatMessage chatMessageTable\" cellspacing=0 cellpadding=0><tr>"
10012
-                messageString += "<td style=\"padding-right:4px;\">" + flag + "</td>"
10013
-                messageString += "<td class=ourChatMessageText onmouseenter=\"ShowChatMenu(this)\" onmouseleave=\"HideChatMenu(this)\">";
10014
-                messageString += "<span onClick=\"ShowMessgeMenu(this,'CDR','"+  item.CdrId +"', '"+ buddyObj.identity +"')\" class=chatMessageDropdown style=\"display:none\"><i class=\"fa fa-chevron-down\"></i></span>";
10015
-                messageString += "<div>" + formattedMessage + "</div>";
10016
-                messageString += "<div>" + CallTags + "</div>";
10017
-                messageString += "<div id=cdr-comment-"+  item.CdrId +" class=cdrComment>" + callComment + "</div>";
10018
-                messageString += "<div class=callRecordings>" + recordingsHtml + "</div>";
10019
-                messageString += "<div class=messageDate>" + DateTime  + "</div>";
10020
-                messageString += "</td>"
10021
-                messageString += "</tr></table>";
10022
-            } 
10023
-            else {
10024
-                // (Inbound) you(profileUserID) received a call
10025
-                if(item.Billsec == "0"){
10026
-                    formattedMessage += " "+ lang.you_missed_a_call + " ("+ item.ReasonText +").";
10027
-                } 
10028
-                else {
10029
-                    formattedMessage += " "+ lang.you_recieved + " "+ audioVideo +", "+ lang.and_spoke_for +" " + formatDuration(item.Billsec) + ".";
10030
-                }
10031
-
10032
-                var messageString = "<table class=\"theirChatMessage chatMessageTable\" cellspacing=0 cellpadding=0><tr>";
10033
-                messageString += "<td class=theirChatMessageText onmouseenter=\"ShowChatMenu(this)\" onmouseleave=\"HideChatMenu(this)\">";
10034
-                messageString += "<span onClick=\"ShowMessgeMenu(this,'CDR','"+  item.CdrId +"', '"+ buddyObj.identity +"')\" class=chatMessageDropdown style=\"display:none\"><i class=\"fa fa-chevron-down\"></i></span>";
10035
-                messageString += "<div style=\"text-align:left\">" + formattedMessage + "</div>";
10036
-                messageString += "<div>" + CallTags + "</div>";
10037
-                messageString += "<div id=cdr-comment-"+  item.CdrId +" class=cdrComment>" + callComment + "</div>";
10038
-                messageString += "<div class=callRecordings>" + recordingsHtml + "</div>";
10039
-                messageString += "<div class=messageDate> " + DateTime + "</div>";
10040
-                messageString += "</td>";
10041
-                messageString += "<td style=\"padding-left:4px\">" + flag + "</td>";
10042
-                messageString += "</tr></table>";
10043
-            }
10044
-            // Messges are reappended here, and appended when logging
10045
-            $("#contact-" + buddyObj.identity + "-ChatHistory").prepend(messageString);
10046
-        } 
10047
-        else if (item.ItemType == "FILE") {
10048
-
10049
-            if (item.SrcUserId == profileUserID) {
10050
-                // File is sent
10051
-                var sentFileSection = "<table class=\"ourChatMessage chatMessageTable\" cellspacing=0 cellpadding=0><tr>"
10052
-                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>";
10053
-                sentFileSection += "<span style=\"display:block;width:100%;height:10px;\"></span><div class=\"messageDate\">"+ DateTime + "</div></div>";
10054
-                sentFileSection += "</td>";
10055
-                sentFileSection += "</tr></table>";
10056
-
10057
-                $("#contact-" + buddyObj.identity + "-ChatHistory").prepend(sentFileSection);
10058
-                $("#sendFileLoader").remove();
10059
-
10060
-            } else {
10061
-                // File is received
10062
-                var recFileSection = "<table class=\"theirChatMessage chatMessageTable\" cellspacing=0 cellpadding=0><tr>"
10063
-                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>";
10064
-
10065
-                recFileSection += "<span style=\"display:block;width:100%;height:10px;\"></span><div class=\"messageDate\">"+ DateTime + "</div></div>";
10066
-                recFileSection += "</td>";
10067
-                recFileSection += "</tr></table>";
10068
-
10069
-                $("#contact-" + buddyObj.identity + "-ChatHistory").prepend(recFileSection);
10070
-            }
10071
-        } 
10072
-        else if(item.ItemType == "SMS"){
10073
-
10074
-        }
10075
-    });
10076
-
10077
-    // For some reason, the first time this fires, it doesn't always work
10078
-    updateScroll(buddyObj.identity);
10079
-    window.setTimeout(function(){
10080
-        updateScroll(buddyObj.identity);
10081
-    }, 300);
10082
-}
10083
-function ShowChatMenu(obj){
10084
-    $(obj).children("span").show();
10085
-}
10086
-function HideChatMenu(obj){
10087
-    $(obj).children("span").hide();
10088
-}
10089
-function ExpandMessage(obj, ItemId, buddy){
10090
-    $("#msg-text-" + ItemId).css("max-height", "");
10091
-    $("#msg-text-" + ItemId).css("overflow", "");
10092
-    $("#msg-readmore-" + ItemId).remove();
10093
-
10094
-    $.jeegoopopup.close();
10095
-}
10096
-function ShowBuddyDial(obj, buddy){
10097
-    $("#contact-"+ buddy +"-email").show();
10098
-    $("#contact-"+ buddy +"-audio-dial").show();
10099
-    $("#contact-"+ buddy +"-video-dial").show();
10100
-}
10101
-function HideBuddyDial(obj, buddy){
10102
-    $("#contact-"+ buddy +"-email").hide();
10103
-    $("#contact-"+ buddy +"-audio-dial").hide();
10104
-    $("#contact-"+ buddy +"-video-dial").hide();
10105
-}
10106
-function QuickDialAudio(buddy, obj, event){
10107
-    AudioCallMenu(buddy, obj);
10108
-    event.stopPropagation();
10109
-}
10110
-function QuickDialVideo(buddy, ExtNo, event){
10111
-    event.stopPropagation();
10112
-    window.setTimeout(function(){
10113
-        DialByLine('video', buddy, ExtNo);
10114
-    }, 300);
10115
-}
10116
-
10117
-// Sessions
10118
-// ========
10119
-function ExpandVideoArea(lineNum){
10120
-    $("#line-" + lineNum + "-ActiveCall").prop("class","FullScreenVideo");
10121
-    $("#line-" + lineNum + "-VideoCall").css("height", "calc(100% - 100px)");
10122
-    $("#line-" + lineNum + "-VideoCall").css("margin-top", "0px");
10123
-
10124
-    $("#line-" + lineNum + "-preview-container").prop("class","PreviewContainer PreviewContainer_FS");
10125
-    $("#line-" + lineNum + "-stage-container").prop("class","StageContainer StageContainer_FS");
10126
-
10127
-    $("#line-" + lineNum + "-restore").show();
10128
-    $("#line-" + lineNum + "-expand").hide();
10129
-
10130
-    $("#line-" + lineNum + "-monitoring").hide();    
10131
-}
10132
-function RestoreVideoArea(lineNum){
10133
-
10134
-    $("#line-" + lineNum + "-ActiveCall").prop("class","");
10135
-    $("#line-" + lineNum + "-VideoCall").css("height", "");
10136
-    $("#line-" + lineNum + "-VideoCall").css("margin-top", "10px");
10137
-
10138
-    $("#line-" + lineNum + "-preview-container").prop("class","PreviewContainer");
10139
-    $("#line-" + lineNum + "-stage-container").prop("class","StageContainer");
10140
-
10141
-    $("#line-" + lineNum + "-restore").hide();
10142
-    $("#line-" + lineNum + "-expand").show();
10143
-
10144
-    $("#line-" + lineNum + "-monitoring").show();
10145
-}
10146
-function MuteSession(lineNum){
10147
-    $("#line-"+ lineNum +"-btn-Unmute").show();
10148
-    $("#line-"+ lineNum +"-btn-Mute").hide();
10149
-
10150
-    var lineObj = FindLineByNumber(lineNum);
10151
-    if(lineObj == null || lineObj.SipSession == null) return;
10152
-
10153
-    var session = lineObj.SipSession;
10154
-    var pc = session.sessionDescriptionHandler.peerConnection;
10155
-    pc.getSenders().forEach(function (RTCRtpSender) {
10156
-        if(RTCRtpSender.track.kind == "audio") {
10157
-            if(RTCRtpSender.track.IsMixedTrack == true){
10158
-                if(session.data.AudioSourceTrack && session.data.AudioSourceTrack.kind == "audio"){
10159
-                    console.log("Muting Audio Track : "+ session.data.AudioSourceTrack.label);
10160
-                    session.data.AudioSourceTrack.enabled = false;
10161
-                }
10162
-            }
10163
-            else {
10164
-                console.log("Muting Audio Track : "+ RTCRtpSender.track.label);
10165
-                RTCRtpSender.track.enabled = false;
10166
-            }
10167
-        }
10168
-    });
10169
-
10170
-    if(!session.data.mute) session.data.mute = [];
10171
-    session.data.mute.push({ event: "mute", eventTime: utcDateNow() });
10172
-    session.data.ismute = true;
10173
-
10174
-    $("#line-" + lineNum + "-msg").html(lang.call_on_mute);
10175
-
10176
-    updateLineScroll(lineNum);
10177
-
10178
-    // Custom Web hook
10179
-    if(typeof web_hook_on_modify !== 'undefined') web_hook_on_modify("mute", session);
10180
-}
10181
-function UnmuteSession(lineNum){
10182
-    $("#line-"+ lineNum +"-btn-Unmute").hide();
10183
-    $("#line-"+ lineNum +"-btn-Mute").show();
10184
-
10185
-    var lineObj = FindLineByNumber(lineNum);
10186
-    if(lineObj == null || lineObj.SipSession == null) return;
10187
-
10188
-    var session = lineObj.SipSession;
10189
-    var pc = session.sessionDescriptionHandler.peerConnection;
10190
-    pc.getSenders().forEach(function (RTCRtpSender) {
10191
-        if(RTCRtpSender.track.kind == "audio") {
10192
-            if(RTCRtpSender.track.IsMixedTrack == true){
10193
-                if(session.data.AudioSourceTrack && session.data.AudioSourceTrack.kind == "audio"){
10194
-                    console.log("Unmuting Audio Track : "+ session.data.AudioSourceTrack.label);
10195
-                    session.data.AudioSourceTrack.enabled = true;
10196
-                }
10197
-            }
10198
-            else {
10199
-                console.log("Unmuting Audio Track : "+ RTCRtpSender.track.label);
10200
-                RTCRtpSender.track.enabled = true;
10201
-            }
10202
-        }
10203
-    });
10204
-
10205
-    if(!session.data.mute) session.data.mute = [];
10206
-    session.data.mute.push({ event: "unmute", eventTime: utcDateNow() });
10207
-    session.data.ismute = false;
10208
-
10209
-    $("#line-" + lineNum + "-msg").html(lang.call_off_mute);
10210
-
10211
-    updateLineScroll(lineNum);
10212
-
10213
-    // Custom Web hook
10214
-    if(typeof web_hook_on_modify !== 'undefined') web_hook_on_modify("unmute", session);
10215
-}
10216
-function ShowDtmfMenu(obj, lineNum){
10217
-
10218
-    var leftPos = event.pageX - 90;
10219
-    var topPos = event.pageY + 30;
10220
-
10221
-    var html = "<div id=mainDtmfDialPad>";
10222
-    html += "<table cellspacing=10 cellpadding=0 style=\"margin-left:auto; margin-right: auto\">";
10223
-    html += "<tr><td><button class=dtmfButtons onclick=\"sendDTMF('"+ lineNum +"', '1');new Audio('sounds/dtmf.mp3').play();\"><div>1</div><span>&nbsp;</span></button></td>"
10224
-    html += "<td><button class=dtmfButtons onclick=\"sendDTMF('"+ lineNum +"', '2');new Audio('sounds/dtmf.mp3').play();\"><div>2</div><span>ABC</span></button></td>"
10225
-    html += "<td><button class=dtmfButtons onclick=\"sendDTMF('"+ lineNum +"', '3');new Audio('sounds/dtmf.mp3').play();\"><div>3</div><span>DEF</span></button></td></tr>";
10226
-    html += "<tr><td><button class=dtmfButtons onclick=\"sendDTMF('"+ lineNum +"', '4');new Audio('sounds/dtmf.mp3').play();\"><div>4</div><span>GHI</span></button></td>"
10227
-    html += "<td><button class=dtmfButtons onclick=\"sendDTMF('"+ lineNum +"', '5');new Audio('sounds/dtmf.mp3').play();\"><div>5</div><span>JKL</span></button></td>"
10228
-    html += "<td><button class=dtmfButtons onclick=\"sendDTMF('"+ lineNum +"', '6');new Audio('sounds/dtmf.mp3').play();\"><div>6</div><span>MNO</span></button></td></tr>";
10229
-    html += "<tr><td><button class=dtmfButtons onclick=\"sendDTMF('"+ lineNum +"', '7');new Audio('sounds/dtmf.mp3').play();\"><div>7</div><span>PQRS</span></button></td>"
10230
-    html += "<td><button class=dtmfButtons onclick=\"sendDTMF('"+ lineNum +"', '8');new Audio('sounds/dtmf.mp3').play();\"><div>8</div><span>TUV</span></button></td>"
10231
-    html += "<td><button class=dtmfButtons onclick=\"sendDTMF('"+ lineNum +"', '9');new Audio('sounds/dtmf.mp3').play();\"><div>9</div><span>WXYZ</span></button></td></tr>";
10232
-    html += "<tr><td><button class=dtmfButtons onclick=\"sendDTMF('"+ lineNum +"', '*');new Audio('sounds/dtmf.mp3').play();\">*</button></td>"
10233
-    html += "<td><button class=dtmfButtons onclick=\"sendDTMF('"+ lineNum +"', '0');new Audio('sounds/dtmf.mp3').play();\">0</button></td>"
10234
-    html += "<td><button class=dtmfButtons onclick=\"sendDTMF('"+ lineNum +"', '#');new Audio('sounds/dtmf.mp3').play();\">#</button></td></tr>";
10235
-    html += "</table>";
10236
-    html += "</div>";
10237
-
10238
-    $.jeegoopopup.open({
10239
-                html: html,
10240
-                width: "auto",
10241
-                height: "auto",
10242
-                left: leftPos,
10243
-                top: topPos,
10244
-                scrolling: 'no',
10245
-                skinClass: 'jg_popup_basic',
10246
-                overlay: true,
10247
-                opacity: 0,
10248
-                draggable: true,
10249
-                resizable: false,
10250
-                fadeIn: 0
10251
-    });
10252
-
10253
-    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); });
10254
-    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); } });
10255
-}
10256
-
10257
-// Stream Functionality
10258
-// =====================
10259
-function ShowMessgeMenu(obj, typeStr, cdrId, buddy) {
10260
-
10261
-    $.jeegoopopup.close();
10262
-
10263
-    var leftPos = event.pageX;
10264
-    var topPos = event.pageY;
10265
-
10266
-    if (($(window).width() - event.pageX) < (obj.offsetWidth + 50)) { leftPos = event.pageX - 200; }
10267
-
10268
-    var menu = "<div id=\"messageMenu\">";
10269
-    menu += "<table id=\"messageMenuTable\" cellspacing=10 cellpadding=0 style=\"margin-left:auto; margin-right: auto\">";
10270
-
10271
-    // CDR's Menu
10272
-    if (typeStr == "CDR") {
10273
-        var TagState = $("#cdr-flagged-"+ cdrId).is(":visible");
10274
-        var TagText = (TagState)? lang.clear_flag : lang.flag_call;
10275
-        menu += "<tr id=\"CMDetails_1\"><td><i class=\"fa fa-external-link\"></i></td><td class=\"callDetails\">"+ lang.show_call_detail_record +"</td></tr>";
10276
-        menu += "<tr id=\"CMDetails_2\"><td><i class=\"fa fa-tags\"></i></td><td class=\"callDetails\">"+ lang.tag_call +"</td></tr>";
10277
-        menu += "<tr id=\"CMDetails_3\"><td><i class=\"fa fa-flag\"></i></td><td class=\"callDetails\">"+ TagText +"</td></tr>";
10278
-        menu += "<tr id=\"CMDetails_4\"><td><i class=\"fa fa-quote-left\"></i></td><td class=\"callDetails\">"+ lang.edit_comment +"</td></tr>";
10279
-    }
10280
-    if (typeStr == "MSG") {
10281
-        menu += "<tr id=\"CMDetails_5\"><td><i class=\"fa fa-clipboard\"></i></td><td class=\"callDetails\">"+ lang.copy_message +"</td></tr>";
10282
-        menu += "<tr id=\"CMDetails_6\"><td><i class=\"fa fa-quote-left\"></i></td><td class=\"callDetails\">"+ lang.quote_message +"</td></tr>";
10283
-    }
10284
-
10285
-    menu += "</table></div>";
10286
-
10287
-    $.jeegoopopup.open({
10288
-                html: menu,
10289
-                width: 'auto',
10290
-                height: 'auto',
10291
-                left: leftPos,
10292
-                top: topPos,
10293
-                scrolling: 'no',
10294
-                skinClass: 'jg_popup_basic',
10295
-                overlay: true,
10296
-                opacity: 0,
10297
-                draggable: false,
10298
-                resizable: false,
10299
-                fadeIn: 0
10300
-    });
10301
-
10302
-    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); });
10303
-    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); } });
10304
-
10305
-    // CDR messages
10306
-    $("#CMDetails_1").click(function(event) {
10307
-
10308
-            var cdr = null;
10309
-            var currentStream = JSON.parse(localDB.getItem(buddy + "-stream"));
10310
-            if(currentStream != null || currentStream.DataCollection != null){
10311
-                $.each(currentStream.DataCollection, function (i, item) {
10312
-                    if (item.ItemType == "CDR" && item.CdrId == cdrId) {
10313
-                        // Found
10314
-                        cdr = item;
10315
-                        return false;
10316
-                    }
10317
-                });
10318
-            }
10319
-            if(cdr == null) return;
10320
-
10321
-            var callDetails = [];
10322
-
10323
-            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>';
10324
-            html += "<div class=\"UiWindowField scroller\">";
10325
-
10326
-            var CallDate = moment.utc(cdr.ItemDate.replace(" UTC", "")).local().format(DisplayDateFormat +" "+ DisplayTimeFormat);
10327
-            var CallAnswer = (cdr.CallAnswer)? moment.utc(cdr.CallAnswer.replace(" UTC", "")).local().format(DisplayDateFormat +" "+ DisplayTimeFormat) : null ;
10328
-            var ringTime = (cdr.RingTime)? cdr.RingTime : 0 ;
10329
-            var CallEnd = moment.utc(cdr.CallEnd.replace(" UTC", "")).local().format(DisplayDateFormat +" "+ DisplayTimeFormat);
10330
-
10331
-            var srcCallerID = "";
10332
-            var dstCallerID = "";
10333
-            if(cdr.CallDirection == "inbound") {
10334
-                srcCallerID = cdr.Src;
10335
-            } 
10336
-            else if(cdr.CallDirection == "outbound") {
10337
-                dstCallerID = cdr.Dst;
10338
-            }
10339
-            html += "<div class=UiText><b>SIP CallID</b> : "+ cdr.SessionId +"</div>";
10340
-            html += "<div class=UiText><b>"+ lang.call_direction +"</b> : "+ cdr.CallDirection +"</div>";
10341
-            html += "<div class=UiText><b>"+ lang.call_date_and_time +"</b> : "+ CallDate +"</div>";
10342
-            html += "<div class=UiText><b>"+ lang.ring_time +"</b> : "+ formatDuration(ringTime) +" ("+ ringTime +")</div>";
10343
-            html += "<div class=UiText><b>"+ lang.talk_time +"</b> : " + formatDuration(cdr.Billsec) +" ("+ cdr.Billsec +")</div>";
10344
-            html += "<div class=UiText><b>"+ lang.call_duration +"</b> : "+ formatDuration(cdr.TotalDuration) +" ("+ cdr.TotalDuration +")</div>";
10345
-            html += "<div class=UiText><b>"+ lang.video_call +"</b> : "+ ((cdr.WithVideo)? lang.yes : lang.no) +"</div>";
10346
-            html += "<div class=UiText><b>"+ lang.flagged +"</b> : "+ ((cdr.Flagged)? "<i class=\"fa fa-flag FlagCall\"></i> " + lang.yes : lang.no)  +"</div>";
10347
-            html += "<hr>";
10348
-            html += "<h2 style=\"font-size: 16px\">"+ lang.call_tags +"</h2>";
10349
-            html += "<hr>";
10350
-            $.each(cdr.Tags, function(item, tag){
10351
-                html += "<span class=cdrTag>"+ tag.value +"</span>"
10352
-            });
10353
-
10354
-            html += "<h2 style=\"font-size: 16px\">"+ lang.call_notes +"</h2>";
10355
-            html += "<hr>";
10356
-            if(cdr.MessageData){
10357
-                html += "\"" + cdr.MessageData + "\"";
10358
-            }
10359
-
10360
-            html += "<h2 style=\"font-size: 16px\">"+ lang.activity_timeline +"</h2>";
10361
-            html += "<hr>";
10362
-
10363
-            var withVideo = (cdr.WithVideo)? "("+ lang.with_video +")" : "";
10364
-            var startCallMessage = (cdr.CallDirection == "inbound")? lang.you_received_a_call_from + " " + srcCallerID  +" "+ withVideo : lang.you_made_a_call_to + " " + dstCallerID +" "+ withVideo;
10365
-            callDetails.push({ 
10366
-                Message: startCallMessage,
10367
-                TimeStr: cdr.ItemDate
10368
-            });
10369
-            if(CallAnswer){
10370
-                var answerCallMessage = (cdr.CallDirection == "inbound")? lang.you_answered_after + " " + ringTime + " " + lang.seconds_plural : lang.they_answered_after + " " + ringTime + " " + lang.seconds_plural;
10371
-                callDetails.push({ 
10372
-                    Message: answerCallMessage,
10373
-                    TimeStr: cdr.CallAnswer
10374
-                });
10375
-            }
10376
-            $.each(cdr.Transfers, function(item, transfer){
10377
-                var msg = (transfer.type == "Blind")? lang.you_started_a_blind_transfer_to +" "+ transfer.to +". " : lang.you_started_an_attended_transfer_to + " "+ transfer.to +". ";
10378
-                if(transfer.accept && transfer.accept.complete == true){
10379
-                    msg += lang.the_call_was_completed
10380
-                }
10381
-                else if(transfer.accept.disposition != "") {
10382
-                    msg += lang.the_call_was_not_completed +" ("+ transfer.accept.disposition +")"
10383
-                }
10384
-                callDetails.push({
10385
-                    Message : msg,
10386
-                    TimeStr : transfer.transferTime
10387
-                });
10388
-            });
10389
-            $.each(cdr.Mutes, function(item, mute){
10390
-                callDetails.push({
10391
-                    Message : (mute.event == "mute")? lang.you_put_the_call_on_mute : lang.you_took_the_call_off_mute,
10392
-                    TimeStr : mute.eventTime
10393
-                });
10394
-            });
10395
-            $.each(cdr.Holds, function(item, hold){
10396
-                callDetails.push({
10397
-                    Message : (hold.event == "hold")? lang.you_put_the_call_on_hold : lang.you_took_the_call_off_hold,
10398
-                    TimeStr : hold.eventTime
10399
-                });
10400
-            });
10401
-            $.each(cdr.ConfCalls, function(item, confCall){
10402
-                var msg = lang.you_started_a_conference_call_to +" "+ confCall.to +". ";
10403
-                if(confCall.accept && confCall.accept.complete == true){
10404
-                    msg += lang.the_call_was_completed
10405
-                }
10406
-                else if(confCall.accept.disposition != "") {
10407
-                    msg += lang.the_call_was_not_completed +" ("+ confCall.accept.disposition +")"
10408
-                }
10409
-                callDetails.push({
10410
-                    Message : msg,
10411
-                    TimeStr : confCall.startTime
10412
-                });
10413
-            });
10414
-            $.each(cdr.Recordings, function(item, recording){
10415
-                var StartTime = moment.utc(recording.startTime.replace(" UTC", "")).local();
10416
-                var StopTime = moment.utc(recording.stopTime.replace(" UTC", "")).local();
10417
-                var recordingDuration = moment.duration(StopTime.diff(StartTime));
10418
-
10419
-                var msg = lang.call_is_being_recorded;
10420
-                if(recording.startTime != recording.stopTime){
10421
-                    msg += "("+ formatShortDuration(recordingDuration.asSeconds()) +")"
10422
-                }
10423
-                callDetails.push({
10424
-                    Message : msg,
10425
-                    TimeStr : recording.startTime
10426
-                });
10427
-            });
10428
-            callDetails.push({
10429
-                Message: (cdr.Terminate == "us")? "You ended the call." : "They ended the call",
10430
-                TimeStr : cdr.CallEnd
10431
-            });
10432
-
10433
-            callDetails.sort(function(a, b){
10434
-                var aMo = moment.utc(a.TimeStr.replace(" UTC", ""));
10435
-                var bMo = moment.utc(b.TimeStr.replace(" UTC", ""));
10436
-                if (aMo.isSameOrAfter(bMo, "second")) {
10437
-                    return 1;
10438
-                } else return -1;
10439
-                return 0;
10440
-            });
10441
-            $.each(callDetails, function(item, detail){
10442
-                var Time = moment.utc(detail.TimeStr.replace(" UTC", "")).local().format(DisplayTimeFormat);
10443
-                var messageString = "<table class=timelineMessage cellspacing=0 cellpadding=0><tr>"
10444
-                messageString += "<td class=timelineMessageArea>"
10445
-                messageString += "<div class=timelineMessageDate style=\"color: #333333\"><i class=\"fa fa-circle timelineMessageDot\"></i>"+ Time +"</div>"
10446
-                messageString += "<div class=timelineMessageText style=\"color: #000000\">"+ detail.Message +"</div>"
10447
-                messageString += "</td>"
10448
-                messageString += "</tr></table>";
10449
-                html += messageString;
10450
-            });
10451
-
10452
-            html += "<h2 style=\"font-size: 16px\">"+ lang.call_recordings +"</h2>";
10453
-            html += "<hr>";
10454
-            var recordingsHtml = "";
10455
-            $.each(cdr.Recordings, function(r, recording){
10456
-                if(recording.uID){
10457
-                    var StartTime = moment.utc(recording.startTime.replace(" UTC", "")).local();
10458
-                    var StopTime = moment.utc(recording.stopTime.replace(" UTC", "")).local();
10459
-                    var recordingDuration = moment.duration(StopTime.diff(StartTime));
10460
-                    recordingsHtml += "<div>";
10461
-                    if(cdr.WithVideo){
10462
-                        recordingsHtml += "<div><video id=\"callrecording-video-"+ recording.uID +"\" controls style=\"width: 100%\"></div>";
10463
-                    } 
10464
-                    else {
10465
-                        recordingsHtml += "<div><audio id=\"callrecording-audio-"+ recording.uID +"\" controls style=\"width: 100%\"></div>";
10466
-                    } 
10467
-                    recordingsHtml += "<div>"+ lang.started +": "+ StartTime.format(DisplayTimeFormat) +" <i class=\"fa fa-long-arrow-right\"></i> "+ lang.stopped +": "+ StopTime.format(DisplayTimeFormat) +"</div>";
10468
-                    recordingsHtml += "<div>"+ lang.recording_duration +": "+ formatShortDuration(recordingDuration.asSeconds()) +"</div>";
10469
-                    recordingsHtml += "<div><a id=\"download-"+ recording.uID +"\">"+ lang.save_as +"</a> ("+ lang.right_click_and_select_save_link_as +")</div>";
10470
-                    recordingsHtml += "</div>";
10471
-                }
10472
-            });
10473
-            html += recordingsHtml;
10474
-
10475
-            html += "<h2 style=\"font-size: 16px\">"+ lang.send_statistics +"</h2>";
10476
-            html += "<hr>";
10477
-
10478
-            html += "<div style=\"position: relative; margin: auto; height: 160px; width: 100%;\"><canvas id=\"cdr-AudioSendBitRate\"></canvas></div>";
10479
-            html += "<div style=\"position: relative; margin: auto; height: 160px; width: 100%;\"><canvas id=\"cdr-AudioSendPacketRate\"></canvas></div>";
10480
-
10481
-            html += "<h2 style=\"font-size: 16px\">"+ lang.receive_statistics +"</h2>";
10482
-            html += "<hr>";
10483
-
10484
-            html += "<div style=\"position: relative; margin: auto; height: 160px; width: 100%;\"><canvas id=\"cdr-AudioReceiveBitRate\"></canvas></div>";
10485
-            html += "<div style=\"position: relative; margin: auto; height: 160px; width: 100%;\"><canvas id=\"cdr-AudioReceivePacketRate\"></canvas></div>";
10486
-            html += "<div style=\"position: relative; margin: auto; height: 160px; width: 100%;\"><canvas id=\"cdr-AudioReceivePacketLoss\"></canvas></div>";
10487
-            html += "<div style=\"position: relative; margin: auto; height: 160px; width: 100%;\"><canvas id=\"cdr-AudioReceiveJitter\"></canvas></div>";
10488
-            html += "<div style=\"position: relative; margin: auto; height: 160px; width: 100%;\"><canvas id=\"cdr-AudioReceiveLevels\"></canvas></div>";
10489
-
10490
-            html += "<br><br></div>";
10491
-
10492
-            $.jeegoopopup.close();
10493
-
10494
-            $.jeegoopopup.open({
10495
-                title: 'Call Statistics',
10496
-                html: html,
10497
-                width: '640',
10498
-                height: '500',
10499
-                center: true,
10500
-                scrolling: 'no',
10501
-                skinClass: 'jg_popup_basic',
10502
-                overlay: true,
10503
-                opacity: 50,
10504
-                draggable: true,
10505
-                resizable: false,
10506
-                fadeIn: 0
10507
-            });
10508
-
10509
-            $("#jg_popup_b").append('<button id="ok_button">'+ lang.ok +'</button>');
10510
-
10511
-            // Display QOS data
10512
-            DisplayQosData(cdr.SessionId);
10513
-
10514
-
10515
-	    var maxWidth = $(window).width() - 12;
10516
-	    var maxHeight = $(window).height() - 88;
10517
-
10518
-	    if (maxWidth < 656 || maxHeight < 500) { 
10519
-	       $.jeegoopopup.width(maxWidth).height(maxHeight);
10520
-	       $.jeegoopopup.center();
10521
-	       $("#maximizeImg").hide();
10522
-	       $("#minimizeImg").hide();
10523
-	    } else { 
10524
-	       $.jeegoopopup.width(640).height(500);
10525
-	       $.jeegoopopup.center();
10526
-	       $("#minimizeImg").hide();
10527
-	       $("#maximizeImg").show();
10528
-	    }
10529
-
10530
-	    $(window).resize(function() {
10531
-	       maxWidth = $(window).width() - 12;
10532
-	       maxHeight = $(window).height() - 88;
10533
-	       $.jeegoopopup.center();
10534
-	       if (maxWidth < 656 || maxHeight < 500) { 
10535
-		   $.jeegoopopup.width(maxWidth).height(maxHeight);
10536
-		   $.jeegoopopup.center();
10537
-		   $("#maximizeImg").hide();
10538
-		   $("#minimizeImg").hide();
10539
-	       } else { 
10540
-		   $.jeegoopopup.width(640).height(500);
10541
-		   $.jeegoopopup.center();
10542
-		   $("#minimizeImg").hide();
10543
-		   $("#maximizeImg").show();
10544
-	       }
10545
-	    });
10546
-
10547
-	   
10548
-	    $("#minimizeImg").click(function() { $.jeegoopopup.width(640).height(500); $.jeegoopopup.center(); $("#maximizeImg").show(); $("#minimizeImg").hide(); });
10549
-	    $("#maximizeImg").click(function() { $.jeegoopopup.width(maxWidth).height(maxHeight); $.jeegoopopup.center(); $("#minimizeImg").show(); $("#maximizeImg").hide(); });
10550
-
10551
-	    $("#closeImg").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
10552
-	    $("#ok_button").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
10553
-	    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
10554
-	    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); $("#jg_popup_b").empty(); } });
10555
-
10556
-
10557
-            // Queue video and audio
10558
-            $.each(cdr.Recordings, function(r, recording){
10559
-                    var mediaObj = null;
10560
-                    if(cdr.WithVideo){
10561
-                        mediaObj = $("#callrecording-video-"+ recording.uID).get(0);
10562
-                    }
10563
-                    else {
10564
-                        mediaObj = $("#callrecording-audio-"+ recording.uID).get(0);
10565
-                    }
10566
-                    var downloadURL = $("#download-"+ recording.uID);
10567
-
10568
-                    // Playback device
10569
-                    var sinkId = getAudioOutputID();
10570
-                    if (typeof mediaObj.sinkId !== 'undefined') {
10571
-                        mediaObj.setSinkId(sinkId).then(function(){
10572
-                            console.log("sinkId applied: "+ sinkId);
10573
-                        }).catch(function(e){
10574
-                            console.warn("Error using setSinkId: ", e);
10575
-                        });
10576
-                    } else {
10577
-                        console.warn("setSinkId() is not possible using this browser.")
10578
-                    }
10579
-
10580
-                    // Get Call Recording
10581
-                    var indexedDB = window.indexedDB;
10582
-                    var request = indexedDB.open("CallRecordings");
10583
-                    request.onerror = function(event) {
10584
-                        console.error("IndexDB Request Error:", event);
10585
-                    }
10586
-                    request.onupgradeneeded = function(event) {
10587
-                        console.warn("Upgrade Required for IndexDB... probably because of first time use.");
10588
-                    }
10589
-                    request.onsuccess = function(event) {
10590
-                        console.log("IndexDB connected to CallRecordings");
10591
-
10592
-                        var IDB = event.target.result;
10593
-                        if(IDB.objectStoreNames.contains("Recordings") == false){
10594
-                            console.warn("IndexDB CallRecordings.Recordings does not exists");
10595
-                            return;
10596
-                        } 
10597
-
10598
-                        var transaction = IDB.transaction(["Recordings"]);
10599
-                        var objectStoreGet = transaction.objectStore("Recordings").get(recording.uID);
10600
-                        objectStoreGet.onerror = function(event) {
10601
-                            console.error("IndexDB Get Error:", event);
10602
-                        }
10603
-                        objectStoreGet.onsuccess = function(event) {
10604
-                            var mediaBlobUrl = window.URL.createObjectURL(event.target.result.mediaBlob);
10605
-                            mediaObj.src = mediaBlobUrl;
10606
-
10607
-                            // Download Link
10608
-                            if(cdr.WithVideo){
10609
-                                downloadURL.prop("download",  "Video-Call-Recording-"+ recording.uID +".webm");
10610
-                            }
10611
-                            else {
10612
-                                downloadURL.prop("download",  "Audio-Call-Recording-"+ recording.uID +".webm");
10613
-                            }
10614
-                            downloadURL.prop("href", mediaBlobUrl);
10615
-                        }
10616
-                    }
10617
-
10618
-            });
10619
-
10620
-    });
10621
-
10622
-    $("#CMDetails_2").click(function(event) {
10623
-            $("#cdr-tags-"+ cdrId).show();
10624
-
10625
-            $.jeegoopopup.close();
10626
-    });
10627
-
10628
-    $("#CMDetails_3").click(function(event) {
10629
-            // Tag / Untag Call
10630
-            var TagState = $("#cdr-flagged-"+ cdrId).is(":visible");
10631
-            if(TagState){
10632
-                console.log("Clearing Flag from: ", cdrId);
10633
-                $("#cdr-flagged-"+ cdrId).hide();
10634
-
10635
-                // Update DB
10636
-                var currentStream = JSON.parse(localDB.getItem(buddy + "-stream"));
10637
-                if(currentStream != null || currentStream.DataCollection != null){
10638
-                    $.each(currentStream.DataCollection, function (i, item) {
10639
-                        if (item.ItemType == "CDR" && item.CdrId == cdrId) {
10640
-                            // Found
10641
-                            item.Flagged = false;
10642
-                            return false;
10643
-                        }
10644
-                    });
10645
-                    localDB.setItem(buddy + "-stream", JSON.stringify(currentStream));
10646
-                }
10647
-            }
10648
-            else {
10649
-                console.log("Flag Call: ", cdrId);
10650
-                $("#cdr-flagged-"+ cdrId).show();
10651
-
10652
-                // Update DB
10653
-                var currentStream = JSON.parse(localDB.getItem(buddy + "-stream"));
10654
-                if(currentStream != null || currentStream.DataCollection != null){
10655
-                    $.each(currentStream.DataCollection, function (i, item) {
10656
-                        if (item.ItemType == "CDR" && item.CdrId == cdrId) {
10657
-                            // Found
10658
-                            item.Flagged = true;
10659
-                            return false;
10660
-                        }
10661
-                    });
10662
-                    localDB.setItem(buddy + "-stream", JSON.stringify(currentStream));
10663
-                }
10664
-            }
10665
-
10666
-            $.jeegoopopup.close();
10667
-    });
10668
-
10669
-    $("#CMDetails_4").click(function(event) {
10670
-
10671
-            var currentText = $("#cdr-comment-"+ cdrId).text();
10672
-            $("#cdr-comment-"+ cdrId).empty();
10673
-
10674
-            var textboxObj = $("<input maxlength=500 type=text>").appendTo("#cdr-comment-"+ cdrId);
10675
-            textboxObj.on("focus", function(){
10676
-                $.jeegoopopup.close();
10677
-            });
10678
-            textboxObj.on("blur", function(){
10679
-                var newText = $(this).val();
10680
-                SaveComment(cdrId, buddy, newText);
10681
-            });
10682
-            textboxObj.keypress(function(event){
10683
-                window.setTimeout(function(){
10684
-
10685
-                      $.jeegoopopup.close();
10686
-
10687
-                }, 500);
10688
-
10689
-                var keycode = (event.keyCode ? event.keyCode : event.which);
10690
-                if (keycode == '13') {
10691
-                    event.preventDefault();
10692
-
10693
-                    var newText = $(this).val();
10694
-                    SaveComment(cdrId, buddy, newText);
10695
-                }
10696
-            });
10697
-            textboxObj.val(currentText);
10698
-            textboxObj.focus();
10699
-
10700
-            $.jeegoopopup.close();
10701
-    });
10702
-
10703
-    $("#CMDetails_5").click(function(event) {
10704
-        // Text Messages
10705
-            var msgtext = $("#msg-text-"+ cdrId).text();
10706
-            navigator.clipboard.writeText(msgtext).then(function(){
10707
-                console.log("Text coppied to the clipboard:", msgtext);
10708
-            }).catch(function(){
10709
-                console.error("Error writing to the clipboard:", e);
10710
-            });
10711
-
10712
-            $.jeegoopopup.close();
10713
-    });
10714
-
10715
-    $("#CMDetails_6").click(function(event) {
10716
-
10717
-            var msgtext = $("#msg-text-"+ cdrId).text();
10718
-            msgtext = "\""+ msgtext + "\"";
10719
-            var textarea = $("#contact-"+ buddy +"-ChatMessage");
10720
-            console.log("Quote Message:", msgtext);
10721
-            textarea.val(msgtext +"\n" + textarea.val());
10722
-
10723
-            $.jeegoopopup.close();
10724
-    });
10725
-
10726
-}
10727
-function SaveComment(cdrId, buddy, newText){
10728
-    console.log("Setting Comment:", newText);
10729
-
10730
-    $("#cdr-comment-"+ cdrId).empty();
10731
-    $("#cdr-comment-"+ cdrId).append(newText);
10732
-
10733
-    // Update DB
10734
-    var currentStream = JSON.parse(localDB.getItem(buddy + "-stream"));
10735
-    if(currentStream != null || currentStream.DataCollection != null){
10736
-        $.each(currentStream.DataCollection, function (i, item) {
10737
-            if (item.ItemType == "CDR" && item.CdrId == cdrId) {
10738
-                // Found
10739
-                item.MessageData = newText;
10740
-                return false;
10741
-            }
10742
-        });
10743
-        localDB.setItem(buddy + "-stream", JSON.stringify(currentStream));
10744
-    }
10745
-}
10746
-function TagKeyPress(event, obj, cdrId, buddy){
10747
-
10748
-    $.jeegoopopup.close();
10749
-
10750
-    var keycode = (event.keyCode ? event.keyCode : event.which);
10751
-    if (keycode == '13' || keycode == '44') {
10752
-        event.preventDefault();
10753
-
10754
-        if ($(obj).val() == "") return;
10755
-
10756
-        console.log("Adding Tag:", $(obj).val());
10757
-
10758
-        $("#cdr-tags-"+ cdrId+" li:last").before("<li onclick=\"TagClick(this, '"+ cdrId +"', '"+ buddy +"')\">"+ $(obj).val() +"</li>");
10759
-        $(obj).val("");
10760
-
10761
-        // Update DB
10762
-        UpdateTags(cdrId, buddy);
10763
-    }
10764
-}
10765
-function TagClick(obj, cdrId, buddy){
10766
-    window.setTimeout(function(){
10767
-       $.jeegoopopup.close();
10768
-    }, 500);
10769
-
10770
-    console.log("Removing Tag:", $(obj).text());
10771
-    $(obj).remove();
10772
-
10773
-    // Dpdate DB
10774
-    UpdateTags(cdrId, buddy);
10775
-}
10776
-function UpdateTags(cdrId, buddy){
10777
-    var currentStream = JSON.parse(localDB.getItem(buddy + "-stream"));
10778
-    if(currentStream != null || currentStream.DataCollection != null){
10779
-        $.each(currentStream.DataCollection, function (i, item) {
10780
-            if (item.ItemType == "CDR" && item.CdrId == cdrId) {
10781
-                // Found
10782
-                item.Tags = [];
10783
-                $("#cdr-tags-"+ cdrId).children('li').each(function () {
10784
-                    if($(this).prop("class") != "tagText") item.Tags.push({ value: $(this).text() });
10785
-                });
10786
-                return false;
10787
-            }
10788
-        });
10789
-        localDB.setItem(buddy + "-stream", JSON.stringify(currentStream));
10790
-    }
10791
-}
10792
-
10793
-function TagFocus(obj){
10794
-      $.jeegoopopup.close();
10795
-}
10796
-function SendFile(buddy) {
10797
-
10798
-      $('#selectedFile').val('');
10799
-      $("#upFile").empty();
10800
-
10801
-      var buddyObj = FindBuddyByIdentity(buddy);
10802
-      var uploadfile = '<form id="sendFileFormChat" enctype="multipart/form-data">';
10803
-      uploadfile += '<input type="hidden" name="MAX_FILE_SIZE" value="786432000" />';
10804
-      uploadfile += '<input type="hidden" name="sipUser" value="'+ buddyObj.ExtNo +'" />';
10805
-      uploadfile += '<input type="hidden" name="s_ajax_call" value="'+ validateSToken +'" />';
10806
-      uploadfile += '<label for="selectedFile" class="customBrowseButton">Select File</label>';
10807
-      uploadfile += '<span id="upFile"></span>';
10808
-      uploadfile += '<input type="file" id="selectedFile" name="uploadedFile" />';
10809
-      uploadfile += '<input type="submit" id="submitFileChat" value="Send File" style="visibility:hidden;"/>';
10810
-      uploadfile += '</form>';
10811
-
10812
-      if ($("#sendFileFormChat").is(":visible")) {
10813
-          $("#sendFileFormChat").remove();
10814
-          sendFileCheck = 0;
10815
-      } else {
10816
-          sendFileCheck = 1;
10817
-          $("#contact-"+ buddy +"-ChatMessage").before(uploadfile);
10818
-          $("#sendFileFormChat").css("display", "block");
10819
-
10820
-          $("#selectedFile").bind("change", function() {
10821
-             upFileName = $(this).val().split('\\').pop();
10822
-             if (/^[a-zA-Z0-9\-\_\.]+$/.test(upFileName)) {
10823
-                 $("#upFile").html(upFileName);
10824
-             } else { 
10825
-                   $("#sendFileFormChat").remove();
10826
-                   sendFileCheck = 0;
10827
-                   alert("The name of the uploaded file is not valid!");
10828
-             }
10829
-          });
10830
-      }
10831
-}
10832
-
10833
-function ShowEmojiBar(buddy) {
10834
-
10835
-    var messageContainer = $("#contact-"+ buddy +"-emoji-menu");
10836
-    var textarea = $("#contact-"+ buddy +"-ChatMessage");
10837
-
10838
-    if (messageContainer.is(":visible")) { messageContainer.hide(); } else { messageContainer.show(); }
10839
-
10840
-    var menuBar = $("<div>");
10841
-    menuBar.prop("class", "emojiButton")
10842
-    var emojis = ["😀","😁","😂","😃","😄","😅","😆","😊","😦","😉","😊","😋","😌","😍","😎","😏","😐","😑","😒","😓","😔","😕","😖","😗","😘","😙","😚","😛","😜","😝","😞","😟","😠","😡","😢","😣","😤","😥","😦","😧","😨","😩","😪","😫","😬","😭","😮","😯","😰","😱","😲","😳","😴","😵","😶","😷","🙁","🙂","🙃","🙄","🤐","🤑","🤒","🤓","🤔","🤕","🤠","🤡","🤢","🤣","🤤","🤥","🤧","🤨","🤩","🤪","🤫","🤬","🥺","🤭","🤯","🧐"];
10843
-    $.each(emojis, function(i,e){
10844
-        var emoji = $("<button>");
10845
-        emoji.html(e);
10846
-        emoji.on('click', function() {
10847
-            var i = textarea.prop('selectionStart');
10848
-            var v = textarea.val();
10849
-            textarea.val(v.substring(0, i) + " " + $(this).html() + v.substring(i, v.length) + " ");
10850
-
10851
-            messageContainer.hide();
10852
-            textarea.focus();
10853
-            updateScroll(buddy);
10854
-        });
10855
-        menuBar.append(emoji);
10856
-    });
10857
-
10858
-    $(".chatMessage,.chatHistory").on('click', function(){
10859
-        messageContainer.hide();
10860
-    });
10861
-
10862
-    messageContainer.empty();
10863
-    messageContainer.append(menuBar);
10864
-
10865
-    updateScroll(buddy);
10866
-}
10867
-
10868
-// My Profile
10869
-// ==========
10870
-function ShowMyProfileMenu(obj){
10871
-
10872
-    var leftPos = obj.offsetWidth - 254;
10873
-    var topPos = obj.offsetHeight + 56 ;
10874
-
10875
-    var usrRoleFromDB = getDbItem("userrole", "");
10876
-    if (usrRoleFromDB == "superadmin") { var usrRole = "(superadmin)"; } else { var usrRole = ""; }
10877
-    var currentUser = '<font style=\'color:#000000;cursor:auto;\'>' + userName + ' ' + usrRole + '</font>';
10878
-
10879
-    var autoAnswerCheck = AutoAnswerEnabled ? "<i class='fa fa-check' style='float:right;'></i>" : "";
10880
-    var doNotDisturbCheck = DoNotDisturbEnabled ? "<i class='fa fa-check' style='float:right;'></i>" : "";
10881
-    var callWaitingCheck = CallWaitingEnabled ? "<i class='fa fa-check' style='float:right;'></i>" : "";
10882
-
10883
-    var menu = "<div id=userMenu>";
10884
-    menu += "<table id=userMenuTable cellspacing=10 cellpadding=0 style=\"margin-left:auto; margin-right: auto\">";
10885
-    menu += "<tr id=userMenu_1><td><i class=\"fa fa-phone\"></i>&nbsp; "+ lang.auto_answer + "<span id=\"autoAnswerTick\">" + autoAnswerCheck + "</span></td></tr>";
10886
-    menu += "<tr id=userMenu_2><td><i class=\"fa fa-ban\"></i>&nbsp; "+ lang.do_not_disturb + "<span id=\"doNotDisturbTick\">" + doNotDisturbCheck + "</span></td></tr>";
10887
-    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>";
10888
-    menu += "<tr id=userMenu_4><td><i class=\"fa fa-refresh\"></i>&nbsp; "+ lang.refresh_registration + "</td></tr>";
10889
-    menu += "<tr id=userMenu_5><td><i class=\"fa fa-user-plus\"></i>&nbsp; "+ lang.add_contact + "</td></tr>";
10890
-    menu += "<tr id=userMenu_6><td><font style=\'color:#000000;cursor:auto;\'>"+ lang.logged_in_as + "</font></td></tr>";
10891
-    menu += "<tr id=userMenu_7><td><span style='width:20px;'></span>" + currentUser + "</td></tr>";
10892
-    menu += "<tr id=userMenu_8><td><i class=\"fa fa-power-off\"></i>&nbsp; "+ lang.log_out + "</td></tr>";
10893
-    menu += "</table>";
10894
-    menu += "</div>";  
10895
-
10896
-    $.jeegoopopup.open({
10897
-                html: menu,
10898
-                width: 'auto',
10899
-                height: 'auto',
10900
-                left: '56',
10901
-                top: topPos,
10902
-                scrolling: 'no',
10903
-                skinClass: 'jg_popup_basic',
10904
-                innerClass: 'userMenuInner',
10905
-                contentClass: 'userMenuContent',
10906
-                overlay: true,
10907
-                opacity: 0,
10908
-                draggable: false,
10909
-                resizable: false,
10910
-                fadeIn: 0
10911
-    });
10912
-
10913
-    $(window).resize(function() {
10914
-      $.jeegoopopup.width('auto').height('auto').left('56').top(topPos);   
10915
-    });
10916
-
10917
-    $("#userMenu_1").click(function() {
10918
-      ToggleAutoAnswer();
10919
-      if (AutoAnswerEnabled) {
10920
-          $("#autoAnswerTick").append("<i class='fa fa-check' style='float:right;'></i>");
10921
-      } else {
10922
-          $("#autoAnswerTick").empty();
10923
-      } 
10924
-    });
10925
-    $("#userMenu_2").click(function() {
10926
-      ToggleDoNoDisturb();
10927
-      if (DoNotDisturbEnabled) {
10928
-          $("#doNotDisturbTick").append("<i class='fa fa-check' style='float:right;'></i>");
10929
-      } else {
10930
-          $("#doNotDisturbTick").empty();
10931
-      } 
10932
-    });
10933
-    $("#userMenu_3").click(function() {
10934
-      ToggleCallWaiting();
10935
-      if (CallWaitingEnabled) {
10936
-          $("#callWaitingTick").append("<i class='fa fa-check' style='float:right;'></i>");
10937
-      } else {
10938
-          $("#callWaitingTick").empty();
10939
-      }
10940
-    });
10941
-    $("#userMenu_4").click(function() { RefreshRegistration(); });
10942
-    $("#userMenu_5").click(function() { AddSomeoneWindow(); });
10943
-    $("#userMenu_8").click(function() { SignOut(); });
10944
-
10945
-    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); });
10946
-    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); } });
10947
-}
10948
-
10949
-function ShowLaunchVidConfMenu(obj){
10950
-
10951
-    var leftPos = obj.offsetWidth + 121;
10952
-    var rightPos = 0;
10953
-    var topPos = obj.offsetHeight + 117;
10954
-
10955
-    if ($(window).width() <= 915) {
10956
-        leftPos = event.pageX + obj.offsetWidth - 113;
10957
-        rightPos = 0;
10958
-        topPos = event.pageY + obj.offsetHeight - 11;
10959
-    }
10960
-
10961
-    var vcmenu = "<div id=videoConfMenu>";
10962
-    vcmenu += "<table id=lauchVConfTable cellspacing=0 cellpadding=0 style=\"margin: 0px\">";
10963
-    vcmenu += "<tr id=launchVConfMenu_1><td><i class=\"fa fa-users\"></i>&nbsp; "+ lang.launch_video_conference + "</td></tr>";
10964
-    vcmenu += "</table>";
10965
-    vcmenu += "</div>";
10966
-
10967
-    $.jeegoopopup.open({
10968
-                html: vcmenu,
10969
-                width: '228',
10970
-                height: '22',
10971
-                left: leftPos,
10972
-                right: rightPos,
10973
-                top: topPos,
10974
-                scrolling: 'no',
10975
-                skinClass: 'jg_popup_basic',
10976
-                overlay: true,
10977
-                opacity: 0,
10978
-                draggable: false,
10979
-                resizable: false,
10980
-                fadeIn: 0
10981
-    });
10982
-
10983
-    $(window).resize(function() {
10984
-      $.jeegoopopup.width('228').height('22').left(leftPos).top(topPos);   
10985
-    });
10986
-
10987
-    if ($(window).width() <= 915) { $.jeegoopopup.right(6); } else { $.jeegoopopup.width('228').height('22').left(leftPos).top(topPos); }
10988
-
10989
-    $("#launchVConfMenu_1").click(function() { LaunchVideoConference(); $.jeegoopopup.close(); });
10990
-    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); });
10991
-    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); } });
10992
-}
10993
-
10994
-function ShowAccountSettingsMenu(obj) {
10995
-
10996
-    $.jeegoopopup.close();
10997
-
10998
-    var leftPos = obj.offsetWidth + 212;
10999
-    var rightPos = 0;
11000
-    var topPos = obj.offsetHeight + 117;
11001
-
11002
-    if ($(window).width() <= 915) {
11003
-
11004
-        leftPos = event.pageX - 32;
11005
-        rightPos = 0;
11006
-        topPos = event.pageY + 11;
11007
-    }
11008
-
11009
-    var setconfmenu = "<div id=settingsCMenu>";
11010
-    setconfmenu += "<table id=lauchSetConfTable cellspacing=0 cellpadding=0 style=\"margin: 0px\">";
11011
-    setconfmenu += "<tr id=settingsCMenu_1><td><i class=\"fa fa-wrench\"></i>&nbsp; "+ lang.account_settings + "</td></tr>";
11012
-    setconfmenu += "</table>";
11013
-    setconfmenu += "</div>";
11014
-
11015
-    $.jeegoopopup.open({
11016
-                html: setconfmenu,
11017
-                width: '94',
11018
-                height: '22',
11019
-                left: leftPos,
11020
-                right: rightPos,
11021
-                top: topPos,
11022
-                scrolling: 'no',
11023
-                skinClass: 'jg_popup_basic',
11024
-                overlay: true,
11025
-                opacity: 0,
11026
-                draggable: false,
11027
-                resizable: false,
11028
-                fadeIn: 0
11029
-    });
11030
-
11031
-    $(window).resize(function() {
11032
-      $.jeegoopopup.width('94').height('22').left(leftPos).top(topPos);   
11033
-    });
11034
-
11035
-    if ($(window).width() <= 915) { $.jeegoopopup.right(6); } else { $.jeegoopopup.width('94').height('22').left(leftPos).top(topPos); }
11036
-
11037
-    $("#settingsCMenu_1").click(function() { ConfigureExtensionWindow(); });
11038
-    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); });
11039
-    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); } });
11040
-}
11041
-
11042
-function RefreshRegistration(){
11043
-    Unregister();
11044
-    console.log("Unregister complete...");
11045
-    window.setTimeout(function(){
11046
-        console.log("Starting registration...");
11047
-        Register();
11048
-    }, 1000);
11049
-}
11050
-
11051
-function SignOut() {
11052
-
11053
-    if (getDbItem("useRoundcube", "") == 1) {
11054
-
11055
-        // Log out from Roundcube
11056
-        $("#roundcubeFrame").remove();
11057
-        $("#rightContent").show();
11058
-        $(".streamSelected").each(function() { $(this).css("display", "none"); });
11059
-        $("#rightContent").append('<iframe id="rcLogoutFrame" name="logoutFrame"></iframe>');
11060
-
11061
-
11062
-        var logoutURL = "https://"+ getDbItem("rcDomain", "") +"/";
11063
-
11064
-        var logoutform = '<form id="rcloForm" method="POST" action="'+ logoutURL +'" target="logoutFrame">'; 
11065
-        logoutform += '<input type="hidden" name="_action" value="logout" />';
11066
-        logoutform += '<input type="hidden" name="_task" value="logout" />';
11067
-        logoutform += '<input type="hidden" name="_autologout" value="1" />';
11068
-        logoutform += '<input id="submitloButton" type="submit" value="Logout" />';
11069
-        logoutform += '</form>';
11070
-
11071
-        $("#rcLogoutFrame").append(logoutform);
11072
-        $("#submitloButton").click();
11073
-
11074
-    }
11075
-
11076
-    // Remove the 'uploads' directory used to temporarily store files received during text chat
11077
-    removeTextChatUploads(getDbItem("SipUsername", ""));
11078
-
11079
-    setTimeout(function() {
11080
-
11081
-       // Check if there are any configured external video conference users
11082
-       var externalLinks = getDbItem("externalUserConfElem", "");
11083
-
11084
-       if (typeof externalLinks !== 'undefined' && externalLinks != null && externalLinks != 0) {
11085
-
11086
-           checkExternalLinks();
11087
-
11088
-       } else {
11089
-           Unregister();
11090
-           console.log("Signing Out ...");
11091
-           localStorage.clear();
11092
-           if (winVideoConf != null) {
11093
-               winVideoConf.close();
11094
-           }
11095
-           window.open('https://' + window.location.host + '/logout.php', '_self');
11096
-       }
11097
-    }, 100);
11098
-}
11099
-
11100
-function ToggleAutoAnswer(){
11101
-    if(AutoAnswerPolicy == "disabled"){
11102
-        AutoAnswerEnabled = false;
11103
-        console.warn("Policy AutoAnswer: Disabled");
11104
-        return;
11105
-    }
11106
-    AutoAnswerEnabled = (AutoAnswerEnabled == true)? false : true;
11107
-    if(AutoAnswerPolicy == "enabled") AutoAnswerEnabled = true;
11108
-    localDB.setItem("AutoAnswerEnabled", (AutoAnswerEnabled == true)? "1" : "0");
11109
-    console.log("AutoAnswer:", AutoAnswerEnabled);
11110
-}
11111
-function ToggleDoNoDisturb(){
11112
-    if(DoNotDisturbPolicy == "disabled"){
11113
-        DoNotDisturbEnabled = false;
11114
-        console.warn("Policy DoNotDisturb: Disabled");
11115
-        return;
11116
-    }
11117
-    DoNotDisturbEnabled = (DoNotDisturbEnabled == true)? false : true;
11118
-    if(DoNotDisturbPolicy == "enabled") DoNotDisturbEnabled = true;
11119
-    localDB.setItem("DoNotDisturbEnabled", (DoNotDisturbEnabled == true)? "1" : "0");
11120
-    $("#dereglink").attr("class", (DoNotDisturbEnabled == true)? "dotDoNotDisturb" : "dotOnline" );
11121
-    console.log("DoNotDisturb", DoNotDisturbEnabled);
11122
-}
11123
-function ToggleCallWaiting(){
11124
-    if(CallWaitingPolicy == "disabled"){
11125
-        CallWaitingEnabled = false;
11126
-        console.warn("Policy CallWaiting: Disabled");
11127
-        return;
11128
-    }
11129
-    CallWaitingEnabled = (CallWaitingEnabled == true)? false : true;
11130
-    if(CallWaitingPolicy == "enabled") CallWaitingPolicy = true;
11131
-    localDB.setItem("CallWaitingEnabled", (CallWaitingEnabled == true)? "1" : "0");
11132
-    console.log("CallWaiting", CallWaitingEnabled);
11133
-}
11134
-function ToggleRecordAllCalls(){
11135
-    if(CallRecordingPolicy == "disabled"){
11136
-        RecordAllCalls = false;
11137
-        console.warn("Policy CallRecording: Disabled");
11138
-        return;
11139
-    }
11140
-    RecordAllCalls = (RecordAllCalls == true)? false : true;
11141
-    if(CallRecordingPolicy == "enabled") RecordAllCalls = true;
11142
-    localDB.setItem("RecordAllCalls", (RecordAllCalls == true)? "1" : "0");
11143
-    console.log("RecordAllCalls", RecordAllCalls);
11144
-}
11145
-
11146
-function ShowBuddyProfileMenu(buddy, obj, typeStr){
11147
-
11148
-    $.jeegoopopup.close();
11149
-
11150
-    leftPos = event.pageX - 60;
11151
-    topPos = event.pageY + 45;
11152
-
11153
-    var buddyObj = FindBuddyByIdentity(buddy);
11154
-
11155
-    if (typeStr == "extension") {
11156
-
11157
-        var html = "<div style=\"width:200px; cursor:pointer\" onclick=\"EditBuddyWindow('"+ buddy +"')\">";
11158
-        html += "<div class=\"buddyProfilePic\" style=\"background-image:url('"+ getPicture(buddy, "extension") +"')\"></div>";
11159
-        html += "<div id=ProfileInfo style=\"text-align:center\"><i class=\"fa fa-spinner fa-spin\"></i></div>"
11160
-        html += "</div>";
11161
-
11162
-        $.jeegoopopup.open({
11163
-                html: html,
11164
-                width: '200',
11165
-                height: 'auto',
11166
-                left: leftPos,
11167
-                top: topPos,
11168
-                scrolling: 'no',
11169
-                skinClass: 'jg_popup_basic',
11170
-                contentClass: 'showContactDetails',
11171
-                overlay: true,
11172
-                opacity: 0,
11173
-                draggable: true,
11174
-                resizable: false,
11175
-                fadeIn: 0
11176
-        });
11177
-      
11178
-        // Done
11179
-        $("#ProfileInfo").html("");
11180
-
11181
-        $("#ProfileInfo").append("<div class=ProfileTextLarge style=\"margin-top:15px\">"+ buddyObj.CallerIDName +"</div>");
11182
-        $("#ProfileInfo").append("<div class=ProfileTextMedium>"+ buddyObj.Desc +"</div>");
11183
-
11184
-        $("#ProfileInfo").append("<div class=ProfileTextSmall style=\"margin-top:15px\">"+ lang.extension_number +":</div>");
11185
-        $("#ProfileInfo").append("<div class=ProfileTextMedium>"+ buddyObj.ExtNo +" </div>");
11186
-
11187
-        if(buddyObj.Email && buddyObj.Email != "null" && buddyObj.Email != "undefined"){
11188
-            $("#ProfileInfo").append("<div class=ProfileTextSmall style=\"margin-top:15px\">"+ lang.email +":</div>");
11189
-            $("#ProfileInfo").append("<div class=ProfileTextMedium>"+ buddyObj.Email +" </div>");
11190
-        }
11191
-        if(buddyObj.MobileNumber && buddyObj.MobileNumber != "null" && buddyObj.MobileNumber != "undefined"){
11192
-            $("#ProfileInfo").append("<div class=ProfileTextSmall style=\"margin-top:15px\">"+ lang.mobile +":</div>");
11193
-            $("#ProfileInfo").append("<div class=ProfileTextMedium>"+ buddyObj.MobileNumber +" </div>");
11194
-        }
11195
-        if(buddyObj.ContactNumber1 && buddyObj.ContactNumber1 != "null" && buddyObj.ContactNumber1 != "undefined"){
11196
-            $("#ProfileInfo").append("<div class=ProfileTextSmall style=\"margin-top:15px\">"+ lang.alternative_contact +":</div>");
11197
-            $("#ProfileInfo").append("<div class=ProfileTextMedium>"+ buddyObj.ContactNumber1 +" </div>");
11198
-        }
11199
-        if(buddyObj.ContactNumber2 && buddyObj.ContactNumber2 != "null" && buddyObj.ContactNumber2 != "undefined"){
11200
-            $("#ProfileInfo").append("<div class=ProfileTextSmall style=\"margin-top:15px\">"+ lang.alternative_contact +":</div>");
11201
-            $("#ProfileInfo").append("<div class=ProfileTextMedium>"+ buddyObj.ContactNumber2 +" </div>");
11202
-        }
11203
-
11204
-    } else if (typeStr == "contact") {
11205
-
11206
-        var html = "<div style=\"width:200px; cursor:pointer\" onclick=\"EditBuddyWindow('"+ buddy +"')\">";
11207
-        html += "<div class=\"buddyProfilePic\" style=\"background-image:url('"+ getPicture(buddy, "contact") +"')\"></div>";
11208
-        html += "<div id=ProfileInfo style=\"text-align:center\"><i class=\"fa fa-spinner fa-spin\"></i></div>"
11209
-        html += "</div>";
11210
-
11211
-        $.jeegoopopup.open({
11212
-                html: html,
11213
-                width: '200',
11214
-                height: 'auto',
11215
-                left: leftPos,
11216
-                top: topPos,
11217
-                scrolling: 'no',
11218
-                skinClass: 'jg_popup_basic',
11219
-                contentClass: 'showContactDetails',
11220
-                overlay: true,
11221
-                opacity: 0,
11222
-                draggable: true,
11223
-                resizable: false,
11224
-                fadeIn: 0
11225
-        });
11226
-
11227
-        $("#ProfileInfo").html("");
11228
-        $("#ProfileInfo").append("<div class=ProfileTextLarge style=\"margin-top:15px\">"+ buddyObj.CallerIDName +"</div>");
11229
-        $("#ProfileInfo").append("<div class=ProfileTextMedium>"+ buddyObj.Desc +"</div>");
11230
-
11231
-        if(buddyObj.Email && buddyObj.Email != "null" && buddyObj.Email != "undefined"){
11232
-            $("#ProfileInfo").append("<div class=ProfileTextSmall style=\"margin-top:15px\">"+ lang.email +":</div>");
11233
-            $("#ProfileInfo").append("<div class=ProfileTextMedium>"+ buddyObj.Email +" </div>");
11234
-        }
11235
-        if(buddyObj.MobileNumber && buddyObj.MobileNumber != "null" && buddyObj.MobileNumber != "undefined"){
11236
-            $("#ProfileInfo").append("<div class=ProfileTextSmall style=\"margin-top:15px\">"+ lang.mobile +":</div>");
11237
-            $("#ProfileInfo").append("<div class=ProfileTextMedium>"+ buddyObj.MobileNumber +" </div>");
11238
-        }
11239
-        if(buddyObj.ContactNumber1 && buddyObj.ContactNumber1 != "null" && buddyObj.ContactNumber1 != "undefined"){
11240
-            $("#ProfileInfo").append("<div class=ProfileTextSmall style=\"margin-top:15px\">"+ lang.alternative_contact +":</div>");
11241
-            $("#ProfileInfo").append("<div class=ProfileTextMedium>"+ buddyObj.ContactNumber1 +" </div>");
11242
-        }
11243
-        if(buddyObj.ContactNumber2 && buddyObj.ContactNumber2 != "null" && buddyObj.ContactNumber2 != "undefined"){
11244
-            $("#ProfileInfo").append("<div class=ProfileTextSmall style=\"margin-top:15px\">"+ lang.alternative_contact +":</div>");
11245
-            $("#ProfileInfo").append("<div class=ProfileTextMedium>"+ buddyObj.ContactNumber2 +" </div>");
11246
-        }
11247
-
11248
-    } else if (typeStr == "group") {
11249
-
11250
-        var html = "<div style=\"width:200px; cursor:pointer\" onclick=\"EditBuddyWindow('"+ buddy +"')\">";
11251
-        html += "<div class=\"buddyProfilePic\" style=\"background-image:url('"+ getPicture(buddy, "group") +"')\"></div>";
11252
-        html += "<div id=ProfileInfo style=\"text-align:center\"><i class=\"fa fa-spinner fa-spin\"></i></div>"
11253
-        html += "</div>";
11254
-
11255
-        $.jeegoopopup.open({
11256
-                html: html,
11257
-                width: '200',
11258
-                height: 'auto',
11259
-                left: leftPos,
11260
-                top: topPos,
11261
-                scrolling: 'no',
11262
-                skinClass: 'jg_popup_basic',
11263
-                contentClass: 'showContactDetails',
11264
-                overlay: true,
11265
-                opacity: 0,
11266
-                draggable: true,
11267
-                resizable: false,
11268
-                fadeIn: 0
11269
-        });
11270
-
11271
-        $("#ProfileInfo").html("");
11272
-
11273
-        $("#ProfileInfo").append("<div class=ProfileTextLarge style=\"margin-top:15px\">"+ buddyObj.CallerIDName +"</div>");
11274
-        $("#ProfileInfo").append("<div class=ProfileTextMedium>"+ buddyObj.Desc +"</div>");
11275
-    }
11276
-
11277
-    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); });
11278
-    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); } });
11279
-}
11280
-
11281
-// Device and Settings
11282
-// ===================
11283
-function ChangeSettings(lineNum, obj){
11284
-
11285
-    var leftPos = event.pageX - 138;
11286
-    var topPos = event.pageY + 28;
11287
-
11288
-    if (($(window).height() - event.pageY) < 300) { topPos = event.pageY - 170; }
11289
-
11290
-    // Check if you are in a call
11291
-    var lineObj = FindLineByNumber(lineNum);
11292
-    if(lineObj == null || lineObj.SipSession == null) return;
11293
-    var session = lineObj.SipSession;
11294
-
11295
-    var html = "<div id=DeviceSelector style=\"width:250px\"></div>";
11296
-
11297
-    $.jeegoopopup.open({
11298
-                html: html,
11299
-                width: "auto",
11300
-                height: "auto",
11301
-                left: leftPos,
11302
-                top: topPos,
11303
-                scrolling: 'no',
11304
-                skinClass: 'jg_popup_basic',
11305
-                contentClass: 'callSettingsContent',
11306
-                overlay: true,
11307
-                opacity: 0,
11308
-                draggable: true,
11309
-                resizable: false,
11310
-                fadeIn: 0
11311
-    });
11312
-
11313
-    var audioSelect = $('<select/>');
11314
-    audioSelect.prop("id", "audioSrcSelect");
11315
-    audioSelect.css("width", "100%");
11316
-
11317
-    var videoSelect = $('<select/>');
11318
-    videoSelect.prop("id", "videoSrcSelect");
11319
-    videoSelect.css("width", "100%");
11320
-
11321
-    var speakerSelect = $('<select/>');
11322
-    speakerSelect.prop("id", "audioOutputSelect");
11323
-    speakerSelect.css("width", "100%");
11324
-
11325
-    var ringerSelect = $('<select/>');
11326
-    ringerSelect.prop("id", "ringerSelect");
11327
-    ringerSelect.css("width", "100%");
11328
-
11329
-    // Handle Audio Source changes (Microphone)
11330
-    audioSelect.change(function() {
11331
-
11332
-        console.log("Call to change Microphone: ", this.value);
11333
-
11334
-        // First Stop Recording the call
11335
-        var mustRestartRecording = false;
11336
-        if(session.data.mediaRecorder && session.data.mediaRecorder.state == "recording"){
11337
-            StopRecording(lineNum, true);
11338
-            mustRestartRecording = true;
11339
-        }
11340
-
11341
-        // Stop Monitoring
11342
-        if(lineObj.LocalSoundMeter) lineObj.LocalSoundMeter.stop();
11343
-
11344
-        // Save Setting
11345
-        session.data.AudioSourceDevice = this.value;
11346
-
11347
-        var constraints = {
11348
-            audio: {
11349
-                deviceId: (this.value != "default")? { exact: this.value } : "default"
11350
-            },
11351
-            video: false
11352
-        }
11353
-        navigator.mediaDevices.getUserMedia(constraints).then(function(newStream){
11354
-            // Assume that since we are selecting from a dropdown, this is possible
11355
-            var newMediaTrack = newStream.getAudioTracks()[0];
11356
-            var pc = session.sessionDescriptionHandler.peerConnection;
11357
-            pc.getSenders().forEach(function (RTCRtpSender) {
11358
-                if(RTCRtpSender.track && RTCRtpSender.track.kind == "audio") {
11359
-                    console.log("Switching Audio Track : "+ RTCRtpSender.track.label + " to "+ newMediaTrack.label);
11360
-                    RTCRtpSender.track.stop(); // Must stop, or this mic will stay in use
11361
-                    RTCRtpSender.replaceTrack(newMediaTrack).then(function(){
11362
-                        // Start recording again
11363
-                        if(mustRestartRecording) StartRecording(lineNum);
11364
-                        // Monitor audio stream
11365
-                        lineObj.LocalSoundMeter = StartLocalAudioMediaMonitoring(lineNum, session);
11366
-                    }).catch(function(e){
11367
-                        console.error("Error replacing track: ", e);
11368
-                    });
11369
-                }
11370
-            });
11371
-        }).catch(function(e){
11372
-            console.error("Error on getUserMedia");
11373
-        });
11374
-    });
11375
-
11376
-    // Handle output change (speaker)
11377
-    speakerSelect.change(function() {
11378
-        console.log("Call to change Speaker: ", this.value);
11379
-
11380
-        // Save Setting
11381
-        session.data.AudioOutputDevice = this.value;
11382
-
11383
-        // Also change the sinkId
11384
-        // ======================
11385
-        var sinkId = this.value;
11386
-        console.log("Attempting to set Audio Output SinkID for line "+ lineNum +" [" + sinkId + "]");
11387
-
11388
-        // Remote audio
11389
-        var element = $("#line-"+ lineNum +"-remoteAudio").get(0);
11390
-        if (element) {
11391
-            if (typeof element.sinkId !== 'undefined') {
11392
-                element.setSinkId(sinkId).then(function(){
11393
-                    console.log("sinkId applied: "+ sinkId);
11394
-                }).catch(function(e){
11395
-                    console.warn("Error using setSinkId: ", e);
11396
-                });
11397
-            } else {
11398
-                console.warn("setSinkId() is not possible using this browser.")
11399
-            }
11400
-        }
11401
-    });
11402
-
11403
-    // Handle video input change (WebCam)
11404
-    videoSelect.change(function(){
11405
-        console.log("Call to change WebCam");
11406
-
11407
-        switchVideoSource(lineNum, this.value);
11408
-    });
11409
-
11410
-    // Load Devices
11411
-    if(!navigator.mediaDevices) {
11412
-        console.warn("navigator.mediaDevices not possible.");
11413
-        return;
11414
-    }
11415
-
11416
-    for (var i = 0; i < AudioinputDevices.length; ++i) {
11417
-        var deviceInfo = AudioinputDevices[i];
11418
-        var devideId = deviceInfo.deviceId;
11419
-        var DisplayName = (deviceInfo.label)? deviceInfo.label : "";
11420
-        if(DisplayName.indexOf("(") > 0) DisplayName = DisplayName.substring(0,DisplayName.indexOf("("));
11421
-
11422
-        // Create Option
11423
-        var option = $('<option/>');
11424
-        option.prop("value", devideId);
11425
-        option.text((DisplayName != "")? DisplayName : "Microphone");
11426
-        if(session.data.AudioSourceDevice == devideId) option.prop("selected", true);
11427
-        audioSelect.append(option);
11428
-    }
11429
-    for (var i = 0; i < VideoinputDevices.length; ++i) {
11430
-        var deviceInfo = VideoinputDevices[i];
11431
-        var devideId = deviceInfo.deviceId;
11432
-        var DisplayName = (deviceInfo.label)? deviceInfo.label : "";
11433
-        if(DisplayName.indexOf("(") > 0) DisplayName = DisplayName.substring(0,DisplayName.indexOf("("));
11434
-
11435
-        // Create Option
11436
-        var option = $('<option/>');
11437
-        option.prop("value", devideId);
11438
-        option.text((DisplayName != "")? DisplayName : "Webcam");
11439
-        if(session.data.VideoSourceDevice == devideId) option.prop("selected", true);
11440
-        videoSelect.append(option);
11441
-    }
11442
-    if(HasSpeakerDevice){
11443
-        for (var i = 0; i < SpeakerDevices.length; ++i) {
11444
-            var deviceInfo = SpeakerDevices[i];
11445
-            var devideId = deviceInfo.deviceId;
11446
-            var DisplayName = (deviceInfo.label)? deviceInfo.label : "";
11447
-            if(DisplayName.indexOf("(") > 0) DisplayName = DisplayName.substring(0,DisplayName.indexOf("("));
11448
-
11449
-            // Create Option
11450
-            var option = $('<option/>');
11451
-            option.prop("value", devideId);
11452
-            option.text((DisplayName != "")? DisplayName : "Speaker"); 
11453
-            if(session.data.AudioOutputDevice == devideId) option.prop("selected", true);
11454
-            speakerSelect.append(option);
11455
-        }
11456
-    }
11457
-
11458
-    // Mic Serttings
11459
-    $("#DeviceSelector").append("<div class=callSettingsDvs>"+ lang.microphone +": </div>");
11460
-    $("#DeviceSelector").append(audioSelect);
11461
-    
11462
-    // Speaker
11463
-    if(HasSpeakerDevice){
11464
-        $("#DeviceSelector").append("<div class=callSettingsDvs>"+ lang.speaker +": </div>");
11465
-        $("#DeviceSelector").append(speakerSelect);
11466
-    }
11467
-    // Camera
11468
-    if(session.data.withvideo == true){
11469
-        $("#DeviceSelector").append("<div class=callSettingsDvs>"+ lang.camera +": </div>");
11470
-        $("#DeviceSelector").append(videoSelect);
11471
-    }
11472
-
11473
-    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); });
11474
-    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); } });
11475
-}
11476
-
11477
-// Media Presentation
11478
-// ==================
11479
-function PresentCamera(lineNum){
11480
-    var lineObj = FindLineByNumber(lineNum);
11481
-    if(lineObj == null || lineObj.SipSession == null){
11482
-        console.warn("Line or Session is Null.");
11483
-        return;
11484
-    }
11485
-    var session = lineObj.SipSession;
11486
-
11487
-    $("#line-"+ lineNum +"-src-camera").prop("disabled", true);
11488
-    $("#line-"+ lineNum +"-src-canvas").prop("disabled", false);
11489
-    $("#line-"+ lineNum +"-src-desktop").prop("disabled", false);
11490
-    $("#line-"+ lineNum +"-src-video").prop("disabled", false);
11491
-    $("#line-"+ lineNum +"-src-blank").prop("disabled", false);
11492
-
11493
-    $("#line-"+ lineNum + "-scratchpad-container").hide();
11494
-    RemoveScratchpad(lineNum);
11495
-    $("#line-"+ lineNum +"-sharevideo").hide();
11496
-    $("#line-"+ lineNum +"-sharevideo").get(0).pause();
11497
-    $("#line-"+ lineNum +"-sharevideo").get(0).removeAttribute('src');
11498
-    $("#line-"+ lineNum +"-sharevideo").get(0).load();
11499
-    window.clearInterval(session.data.videoResampleInterval);
11500
-
11501
-    $("#line-"+ lineNum + "-localVideo").show();
11502
-    $("#line-"+ lineNum + "-remoteVideo").appendTo("#line-"+ lineNum + "-stage-container");
11503
-
11504
-    switchVideoSource(lineNum, session.data.VideoSourceDevice);
11505
-}
11506
-function PresentScreen(lineNum){
11507
-    var lineObj = FindLineByNumber(lineNum);
11508
-    if(lineObj == null || lineObj.SipSession == null){
11509
-        console.warn("Line or Session is Null.");
11510
-        return;
11511
-    }
11512
-    var session = lineObj.SipSession;
11513
-
11514
-    $("#line-"+ lineNum +"-src-camera").prop("disabled", false);
11515
-    $("#line-"+ lineNum +"-src-canvas").prop("disabled", false);
11516
-    $("#line-"+ lineNum +"-src-desktop").prop("disabled", true);
11517
-    $("#line-"+ lineNum +"-src-video").prop("disabled", false);
11518
-    $("#line-"+ lineNum +"-src-blank").prop("disabled", false);
11519
-
11520
-    $("#line-"+ lineNum + "-scratchpad-container").hide();
11521
-    RemoveScratchpad(lineNum);
11522
-    $("#line-"+ lineNum +"-sharevideo").hide();
11523
-    $("#line-"+ lineNum +"-sharevideo").get(0).pause();
11524
-    $("#line-"+ lineNum +"-sharevideo").get(0).removeAttribute('src');
11525
-    $("#line-"+ lineNum +"-sharevideo").get(0).load();
11526
-    window.clearInterval(session.data.videoResampleInterval);
11527
-
11528
-    $("#line-"+ lineNum + "-localVideo").hide();
11529
-    $("#line-"+ lineNum + "-remoteVideo").appendTo("#line-"+ lineNum + "-stage-container");
11530
-
11531
-    ShareScreen(lineNum);
11532
-}
11533
-function PresentScratchpad(lineNum){
11534
-    var lineObj = FindLineByNumber(lineNum);
11535
-    if(lineObj == null || lineObj.SipSession == null){
11536
-        console.warn("Line or Session is Null.");
11537
-        return;
11538
-    }
11539
-    var session = lineObj.SipSession;
11540
-
11541
-    $("#line-"+ lineNum +"-src-camera").prop("disabled", false);
11542
-    $("#line-"+ lineNum +"-src-canvas").prop("disabled", true);
11543
-    $("#line-"+ lineNum +"-src-desktop").prop("disabled", false);
11544
-    $("#line-"+ lineNum +"-src-video").prop("disabled", false);
11545
-    $("#line-"+ lineNum +"-src-blank").prop("disabled", false);
11546
-
11547
-    $("#line-"+ lineNum + "-scratchpad-container").hide();
11548
-    RemoveScratchpad(lineNum);
11549
-    $("#line-"+ lineNum +"-sharevideo").hide();
11550
-    $("#line-"+ lineNum +"-sharevideo").get(0).pause();
11551
-    $("#line-"+ lineNum +"-sharevideo").get(0).removeAttribute('src');
11552
-    $("#line-"+ lineNum +"-sharevideo").get(0).load();
11553
-    window.clearInterval(session.data.videoResampleInterval);
11554
-
11555
-    $("#line-"+ lineNum + "-localVideo").hide();
11556
-    $("#line-"+ lineNum + "-remoteVideo").appendTo("#line-"+ lineNum + "-preview-container");
11557
-
11558
-    SendCanvas(lineNum);
11559
-}
11560
-function PresentVideo(lineNum){
11561
-
11562
-    var lineObj = FindLineByNumber(lineNum);
11563
-    if(lineObj == null || lineObj.SipSession == null){
11564
-        console.warn("Line or Session is Null.");
11565
-        return;
11566
-    }
11567
-    var session = lineObj.SipSession;
11568
-
11569
-    $.jeegoopopup.close();
11570
-
11571
-    var presentVideoHtml = "<div>";
11572
-    presentVideoHtml += '<div id="windowCtrls"><img id="closeImg" src="images/3_close.svg" title="Close" /></div>';
11573
-    presentVideoHtml += "<label for=SelectVideoToSend class=customBrowseButton style=\"display: block; margin: 26px auto;\">Select File</label>";
11574
-    presentVideoHtml += "<div class=\"UiWindowField\"><input type=file  accept=\"video/*\" id=SelectVideoToSend></div>";
11575
-    presentVideoHtml += "</div>";
11576
-
11577
-    $.jeegoopopup.open({
11578
-                html: presentVideoHtml,
11579
-                width: '180',
11580
-                height: '80',
11581
-                center: true,
11582
-                scrolling: 'no',
11583
-                skinClass: 'jg_popup_basic',
11584
-                overlay: true,
11585
-                opacity: 0,
11586
-                draggable: true,
11587
-                resizable: false,
11588
-                fadeIn: 0
11589
-    });
11590
-
11591
-    $("#SelectVideoToSend").on('change', function(event){
11592
-            var input = event.target;
11593
-            if(input.files.length >= 1){
11594
-
11595
-                $.jeegoopopup.close();
11596
-
11597
-                // Send Video (Can only send one file)
11598
-                SendVideo(lineNum, URL.createObjectURL(input.files[0]));
11599
-            }
11600
-            else {
11601
-                console.warn("Please Select a file to present.");
11602
-            }
11603
-    });
11604
-
11605
-    $("#closeImg").click(function() { $.jeegoopopup.close(); });
11606
-    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); });
11607
-    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); } });
11608
-}
11609
-function PresentBlank(lineNum){
11610
-    var lineObj = FindLineByNumber(lineNum);
11611
-    if(lineObj == null || lineObj.SipSession == null){
11612
-        console.warn("Line or Session is Null.");
11613
-        return;
11614
-    }
11615
-    var session = lineObj.SipSession;
11616
-
11617
-    $("#line-"+ lineNum +"-src-camera").prop("disabled", false);
11618
-    $("#line-"+ lineNum +"-src-canvas").prop("disabled", false);
11619
-    $("#line-"+ lineNum +"-src-desktop").prop("disabled", false);
11620
-    $("#line-"+ lineNum +"-src-video").prop("disabled", false);
11621
-    $("#line-"+ lineNum +"-src-blank").prop("disabled", true);
11622
-    
11623
-    $("#line-"+ lineNum + "-scratchpad-container").hide();
11624
-    RemoveScratchpad(lineNum);
11625
-    $("#line-"+ lineNum +"-sharevideo").hide();
11626
-    $("#line-"+ lineNum +"-sharevideo").get(0).pause();
11627
-    $("#line-"+ lineNum +"-sharevideo").get(0).removeAttribute('src');
11628
-    $("#line-"+ lineNum +"-sharevideo").get(0).load();
11629
-    window.clearInterval(session.data.videoResampleInterval);
11630
-
11631
-    $("#line-"+ lineNum + "-localVideo").hide();
11632
-    $("#line-"+ lineNum + "-remoteVideo").appendTo("#line-"+ lineNum + "-stage-container");
11633
-
11634
-    DisableVideoStream(lineNum);
11635
-}
11636
-function RemoveScratchpad(lineNum){
11637
-    var scratchpad = GetCanvas("line-" + lineNum + "-scratchpad");
11638
-    if(scratchpad != null){
11639
-        window.clearInterval(scratchpad.redrawIntrtval);
11640
-
11641
-        RemoveCanvas("line-" + lineNum + "-scratchpad");
11642
-        $("#line-"+ lineNum + "-scratchpad-container").empty();
11643
-
11644
-        scratchpad = null;
11645
-    }
11646
-}
11647
-
11648
-// Call Statistics
11649
-// ===============
11650
-function ShowCallStats(lineNum, obj){
11651
-    console.log("Show Call Stats");
11652
-    $("#line-"+ lineNum +"-AudioStats").show(300);
11653
-}
11654
-function HideCallStats(lineNum, obj){
11655
-    console.log("Hide Call Stats");
11656
-    $("#line-"+ lineNum +"-AudioStats").hide(300);
11657
-}
11658
-
11659
-// Chatting
11660
-// ========
11661
-function chatOnbeforepaste(event, obj, buddy){
11662
-    console.log("Handle paste, checking for Images...");
11663
-    var items = (event.clipboardData || event.originalEvent.clipboardData).items;
11664
-
11665
-    // Find pasted image among pasted items
11666
-    var preventDefault = false;
11667
-    for (var i = 0; i < items.length; i++) {
11668
-        if (items[i].type.indexOf("image") === 0) {
11669
-            console.log("Image found! Opening image editor...");
11670
-
11671
-            var blob = items[i].getAsFile();
11672
-
11673
-            // Read the image in
11674
-            var reader = new FileReader();
11675
-            reader.onload = function (event) {
11676
-
11677
-                // Image has loaded, open Image Preview Editor
11678
-                // ===========================================
11679
-                console.log("Image loaded... setting placeholder...");
11680
-                var placeholderImage = new Image();
11681
-                placeholderImage.onload = function () {
11682
-
11683
-                    console.log("Placeholder loaded... CreateImageEditor...");
11684
-
11685
-                    CreateImageEditor(buddy, placeholderImage);
11686
-                }
11687
-                placeholderImage.src = event.target.result;
11688
-            }
11689
-            reader.readAsDataURL(blob);
11690
-
11691
-            preventDefault = true;
11692
-            continue;
11693
-        }
11694
-    }
11695
-
11696
-    // Pevent default if you found an image
11697
-    if (preventDefault) event.preventDefault();
11698
-}
11699
-function chatOnkeydown(event, obj, buddy) {
11700
-
11701
-    var keycode = (event.keyCode ? event.keyCode : event.which);
11702
-    if (keycode == '13'){
11703
-        if(event.ctrlKey) {
11704
-            SendChatMessage(buddy);
11705
-            return false;
11706
-        }
11707
-    }
11708
-}
11709
-
11710
-function ReformatMessage(str) {
11711
-    var msg = str;
11712
-    // Simple tex=>HTML 
11713
-    msg = msg.replace(/</gi, "&lt;");
11714
-    msg = msg.replace(/>/gi, "&gt;");
11715
-    msg = msg.replace(/\n/gi, "<br>");
11716
-    // Emojy
11717
-    // Skype: :) :( :D :O ;) ;( (:| :| :P :$ :^) |-) |-( :x ]:)
11718
-    // (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)
11719
-    msg = msg.replace(/(:\)|:\-\)|:o\))/g, String.fromCodePoint(0x1F642));     // :) :-) :o)
11720
-    msg = msg.replace(/(:\(|:\-\(|:o\()/g, String.fromCodePoint(0x1F641));     // :( :-( :o(
11721
-    msg = msg.replace(/(;\)|;\-\)|;o\))/g, String.fromCodePoint(0x1F609));     // ;) ;-) ;o)
11722
-    msg = msg.replace(/(:'\(|:'\-\()/g, String.fromCodePoint(0x1F62A));        // :'( :'‑(
11723
-    msg = msg.replace(/(:'\(|:'\-\()/g, String.fromCodePoint(0x1F602));        // :') :'‑)
11724
-    msg = msg.replace(/(:\$)/g, String.fromCodePoint(0x1F633));                // :$
11725
-    msg = msg.replace(/(>:\()/g, String.fromCodePoint(0x1F623));               // >:(
11726
-    msg = msg.replace(/(:\×)/g, String.fromCodePoint(0x1F618));                // :×
11727
-    msg = msg.replace(/(:\O|:\‑O)/g, String.fromCodePoint(0x1F632));             // :O :‑O
11728
-    msg = msg.replace(/(:P|:\-P|:p|:\-p)/g, String.fromCodePoint(0x1F61B));      // :P :-P :p :-p
11729
-    msg = msg.replace(/(;P|;\-P|;p|;\-p)/g, String.fromCodePoint(0x1F61C));      // ;P ;-P ;p ;-p
11730
-    msg = msg.replace(/(:D|:\-D)/g, String.fromCodePoint(0x1F60D));             // :D :-D
11731
-
11732
-    msg = msg.replace(/(\(like\))/g, String.fromCodePoint(0x1F44D));           // (like)
11733
-
11734
-    // Make clickable Hyperlinks
11735
-    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) {
11736
-          var niceLink = (x.length > 50) ? x.substring(0, 47) + "..." : x;
11737
-          var rtn = "<A target=_blank class=previewHyperlink href=\"" + x + "\">" + niceLink + "</A>";
11738
-          return rtn;
11739
-    });
11740
-    return msg;
11741
-}
11742
-function getPicture(buddy, typestr){
11743
-    if(buddy == "profilePicture"){
11744
-        // Special handling for profile image
11745
-        var dbImg = localDB.getItem("profilePicture");
11746
-        if(dbImg == null){
11747
-            return hostingPrefex + "images/default.png";
11748
-        }
11749
-        else {
11750
-            return dbImg; 
11751
-        }
11752
-    }
11753
-
11754
-    typestr = (typestr)? typestr : "extension";
11755
-
11756
-    var buddyObj = FindBuddyByIdentity(buddy);
11757
-    if(buddyObj.imageObjectURL != ""){
11758
-        // Use Cache
11759
-        return buddyObj.imageObjectURL;
11760
-    }
11761
-
11762
-    var dbImg = localDB.getItem("img-"+ buddy +"-"+ typestr);
11763
-
11764
-    if(dbImg == null){
11765
-        return hostingPrefex + "images/default.png";
11766
-    } else {
11767
-        buddyObj.imageObjectURL = URL.createObjectURL(base64toBlob(dbImg, 'image/png'));
11768
-        return buddyObj.imageObjectURL;
11769
-    }
11770
-}
11771
-
11772
-// Image Editor
11773
-// ============
11774
-function CreateImageEditor(buddy, placeholderImage){
11775
-    // Show Interface
11776
-    // ==============
11777
-    console.log("Setting Up ImageEditor...");
11778
-    if($("#contact-" + buddy + "-imagePastePreview").is(":visible")) {
11779
-        console.log("Resetting ImageEditor...");
11780
-        $("#contact-" + buddy + "-imagePastePreview").empty();
11781
-        RemoveCanvas("contact-" + buddy + "-imageCanvas")
11782
-    } else {
11783
-        $("#contact-" + buddy + "-imagePastePreview").show();
11784
-    }
11785
-    // Create UI
11786
-    // =========
11787
-    var toolBarDiv = $('<div/>');
11788
-    toolBarDiv.css("margin-bottom", "5px")
11789
-    toolBarDiv.append('<button class="toolBarButtons" title="Select" onclick="ImageEditor_Select(\''+ buddy +'\')"><i class="fa fa-mouse-pointer"></i></button>');
11790
-    toolBarDiv.append('&nbsp;|&nbsp;');
11791
-    toolBarDiv.append('<button class="toolBarButtons" title="Draw" onclick="ImageEditor_FreedrawPen(\''+ buddy +'\')"><i class="fa fa-pencil"></i></button>');
11792
-    toolBarDiv.append('<button class="toolBarButtons" title="Paint" onclick="ImageEditor_FreedrawPaint(\''+ buddy +'\')"><i class="fa fa-paint-brush"></i></button>');
11793
-    toolBarDiv.append('&nbsp;|&nbsp;');
11794
-    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>');
11795
-    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>');
11796
-    toolBarDiv.append('&nbsp;|&nbsp;');
11797
-    toolBarDiv.append('<button class="toolBarButtons" title="Add Circle" onclick="ImageEditor_AddCircle(\''+ buddy +'\')"><i class="fa fa-circle"></i></button>');
11798
-    toolBarDiv.append('<button class="toolBarButtons" title="Add Rectangle" onclick="ImageEditor_AddRectangle(\''+ buddy +'\')"><i class="fa fa-stop"></i></button>');
11799
-    toolBarDiv.append('<button class="toolBarButtons" title="Add Triangle" onclick="ImageEditor_AddTriangle(\''+ buddy +'\')"><i class="fa fa-play"></i></button>');
11800
-    toolBarDiv.append('<button class="toolBarButtons" title="Add Emoji" onclick="ImageEditor_SetectEmoji(\''+ buddy +'\')"><i class="fa fa-smile-o"></i></button>');
11801
-    toolBarDiv.append('<button class="toolBarButtons" title="Add Text" onclick="ImageEditor_AddText(\''+ buddy +'\')"><i class="fa fa-font"></i></button>');
11802
-    toolBarDiv.append('<button class="toolBarButtons" title="Delete Selected Items" onclick="ImageEditor_Clear(\''+ buddy +'\')"><i class="fa fa-times"></i></button>');
11803
-    toolBarDiv.append('<button class="toolBarButtons" title="Clear All" onclick="ImageEditor_ClearAll(\''+ buddy +'\')"><i class="fa fa-trash"></i></button>');
11804
-    toolBarDiv.append('&nbsp;|&nbsp;');
11805
-    toolBarDiv.append('<button class="toolBarButtons" title="Pan" onclick="ImageEditor_Pan(\''+ buddy +'\')"><i class="fa fa-hand-paper-o"></i></button>');
11806
-    toolBarDiv.append('<button class="toolBarButtons" title="Zoom In" onclick="ImageEditor_ZoomIn(\''+ buddy +'\')"><i class="fa fa-search-plus"></i></button>');
11807
-    toolBarDiv.append('<button class="toolBarButtons" title="Zoom Out" onclick="ImageEditor_ZoomOut(\''+ buddy +'\')"><i class="fa fa-search-minus"></i></button>');
11808
-    toolBarDiv.append('<button class="toolBarButtons" title="Reset Pan & Zoom" onclick="ImageEditor_ResetZoom(\''+ buddy +'\')"><i class="fa fa-search" aria-hidden="true"></i></button>');
11809
-    toolBarDiv.append('&nbsp;|&nbsp;');
11810
-    toolBarDiv.append('<button class="toolBarButtons" title="Cancel" onclick="ImageEditor_Cancel(\''+ buddy +'\')"><i class="fa fa-times-circle"></i></button>');
11811
-    toolBarDiv.append('<button class="toolBarButtons" title="Send" onclick="ImageEditor_Send(\''+ buddy +'\')"><i class="fa fa-paper-plane"></i></button>');
11812
-    $("#contact-" + buddy + "-imagePastePreview").append(toolBarDiv);
11813
-
11814
-    // Create the canvas
11815
-    // =================
11816
-    var newCanvas = $('<canvas/>');
11817
-    newCanvas.prop("id", "contact-" + buddy + "-imageCanvas");
11818
-    newCanvas.css("border", "1px solid #CCCCCC");
11819
-    $("#contact-" + buddy + "-imagePastePreview").append(newCanvas);
11820
-    console.log("Canvas for ImageEditor created...");
11821
-
11822
-    var imgWidth = placeholderImage.width;
11823
-    var imgHeight = placeholderImage.height;
11824
-    var maxWidth = $("#contact-" + buddy + "-imagePastePreview").width()-2; // for the border
11825
-    var maxHeight = 480;
11826
-    $("#contact-" + buddy + "-imageCanvas").prop("width", maxWidth);
11827
-    $("#contact-" + buddy + "-imageCanvas").prop("height", maxHeight);
11828
-
11829
-    // Handle Initial Zoom
11830
-    var zoomToFitImage = 1;
11831
-    var zoomWidth = 1;
11832
-    var zoomHeight = 1;
11833
-    if(imgWidth > maxWidth || imgHeight > maxHeight)
11834
-    {
11835
-        if(imgWidth > maxWidth)
11836
-        {
11837
-            zoomWidth = (maxWidth / imgWidth);
11838
-        }
11839
-        if(imgHeight > maxHeight)
11840
-        {
11841
-            zoomHeight = (maxHeight / imgHeight);
11842
-            console.log("Scale to fit height: "+ zoomHeight);
11843
-        }
11844
-        zoomToFitImage = Math.min(zoomWidth, zoomHeight) // need the smallest because less is more zoom.
11845
-        console.log("Scale down to fit: "+ zoomToFitImage);
11846
-
11847
-        // Shape the canvas to fit the image and the new zoom
11848
-        imgWidth = imgWidth * zoomToFitImage;
11849
-        imgHeight = imgHeight * zoomToFitImage;
11850
-        console.log("resizing canvas to fit new image size...");
11851
-        $("#contact-" + buddy + "-imageCanvas").prop("width", imgWidth);
11852
-        $("#contact-" + buddy + "-imageCanvas").prop("height", imgHeight);
11853
-    }
11854
-    else {
11855
-        console.log("Image is able to fit, resizing canvas...");
11856
-        $("#contact-" + buddy + "-imageCanvas").prop("width", imgWidth);
11857
-        $("#contact-" + buddy + "-imageCanvas").prop("height", imgHeight);
11858
-    }
11859
-
11860
-    // Fabric Canvas API
11861
-    // =================
11862
-    console.log("Creating fabric API...");
11863
-    var canvas = new fabric.Canvas("contact-" + buddy + "-imageCanvas");
11864
-    canvas.id = "contact-" + buddy + "-imageCanvas";
11865
-    canvas.ToolSelected = "None";
11866
-    canvas.PenColour = "rgb(255, 0, 0)";
11867
-    canvas.PenWidth = 2;
11868
-    canvas.PaintColour = "rgba(227, 230, 3, 0.6)";
11869
-    canvas.PaintWidth = 10;
11870
-    canvas.FillColour = "rgb(255, 0, 0)";
11871
-    canvas.isDrawingMode = false;
11872
-
11873
-    canvas.selectionColor = 'rgba(112,179,233,0.25)';
11874
-    canvas.selectionBorderColor = 'rgba(112,179,233, 0.8)';
11875
-    canvas.selectionLineWidth = 1;
11876
-
11877
-    // Zoom to fit Width or Height
11878
-    // ===========================
11879
-    canvas.setZoom(zoomToFitImage);
11880
-
11881
-    // Canvas Events
11882
-    // =============
11883
-    canvas.on('mouse:down', function(opt) {
11884
-        var evt = opt.e;
11885
-
11886
-        if (this.ToolSelected == "Pan") {
11887
-            this.isDragging = true;
11888
-            this.selection = false;
11889
-            this.lastPosX = evt.clientX;
11890
-            this.lastPosY = evt.clientY;
11891
-        }
11892
-        // Make nicer grab handles
11893
-        if(opt.target != null){
11894
-            if(evt.altKey === true)
11895
-            {
11896
-                opt.target.lockMovementX = true;
11897
-            }
11898
-            if(evt.shiftKey === true)
11899
-            {
11900
-                opt.target.lockMovementY = true;
11901
-            }
11902
-            opt.target.set({
11903
-                transparentCorners: false,
11904
-                borderColor: 'rgba(112,179,233, 0.4)',
11905
-                cornerColor: 'rgba(112,179,233, 0.8)',
11906
-                cornerSize: 6
11907
-            });
11908
-        }
11909
-    });
11910
-    canvas.on('mouse:move', function(opt) {
11911
-        if (this.isDragging) {
11912
-            var e = opt.e;
11913
-            this.viewportTransform[4] += e.clientX - this.lastPosX;
11914
-            this.viewportTransform[5] += e.clientY - this.lastPosY;
11915
-            this.requestRenderAll();
11916
-            this.lastPosX = e.clientX;
11917
-            this.lastPosY = e.clientY;
11918
-        }
11919
-    });
11920
-    canvas.on('mouse:up', function(opt) {
11921
-        this.isDragging = false;
11922
-        this.selection = true;
11923
-        if(opt.target != null){
11924
-            opt.target.lockMovementX = false;
11925
-            opt.target.lockMovementY = false;
11926
-        }
11927
-    });
11928
-    canvas.on('mouse:wheel', function(opt) {
11929
-        var delta = opt.e.deltaY;
11930
-        var pointer = canvas.getPointer(opt.e);
11931
-        var zoom = canvas.getZoom();
11932
-        zoom = zoom + delta/200;
11933
-        if (zoom > 10) zoom = 10;
11934
-        if (zoom < 0.1) zoom = 0.1;
11935
-        canvas.zoomToPoint({ x: opt.e.offsetX, y: opt.e.offsetY }, zoom);
11936
-        opt.e.preventDefault();
11937
-        opt.e.stopPropagation();
11938
-    });
11939
-
11940
-    // Add Image
11941
-    // ==========
11942
-    canvas.backgroundImage = new fabric.Image(placeholderImage);
11943
-
11944
-    CanvasCollection.push(canvas);
11945
-
11946
-    // Add Key Press Events
11947
-    // ====================
11948
-    $("#contact-" + buddy + "-imagePastePreview").keydown(function(evt) {
11949
-        evt = evt || window.event;
11950
-        var key = evt.keyCode;
11951
-        console.log("Key press on Image Editor ("+ buddy +"): "+ key);
11952
-
11953
-        // Delete Key
11954
-        if (key == 46) ImageEditor_Clear(buddy);
11955
-    });
11956
-
11957
-    console.log("ImageEditor: "+ canvas.id +" created");
11958
-
11959
-    ImageEditor_FreedrawPen(buddy);
11960
-}
11961
-function GetCanvas(canvasId){
11962
-    for(var c = 0; c < CanvasCollection.length; c++){
11963
-        try {
11964
-            if(CanvasCollection[c].id == canvasId) return CanvasCollection[c];
11965
-        } catch(e) {
11966
-            console.warn("CanvasCollection.id not available");
11967
-        }
11968
-    }
11969
-    return null;
11970
-}
11971
-function RemoveCanvas(canvasId){
11972
-    for(var c = 0; c < CanvasCollection.length; c++){
11973
-        try{
11974
-            if(CanvasCollection[c].id == canvasId) {
11975
-                console.log("Found Old Canvas, Disposing...");
11976
-
11977
-                CanvasCollection[c].clear()
11978
-                CanvasCollection[c].dispose();
11979
-
11980
-                CanvasCollection[c].id = "--deleted--";
11981
-
11982
-                console.log("CanvasCollection.splice("+ c +", 1)");
11983
-                CanvasCollection.splice(c, 1);
11984
-                break;
11985
-            }
11986
-        }
11987
-        catch(e){ }
11988
-    }
11989
-    console.log("There are "+ CanvasCollection.length +" canvas now.");
11990
-}
11991
-var ImageEditor_Select = function (buddy){
11992
-    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
11993
-    if(canvas != null) {
11994
-        canvas.ToolSelected = "none";
11995
-        canvas.isDrawingMode = false;
11996
-        return true;
11997
-    }
11998
-    return false;
11999
-}
12000
-var ImageEditor_FreedrawPen = function (buddy){
12001
-    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
12002
-    if(canvas != null) {
12003
-        canvas.freeDrawingBrush.color = canvas.PenColour;
12004
-        canvas.freeDrawingBrush.width = canvas.PenWidth;
12005
-        canvas.ToolSelected = "Draw";
12006
-        canvas.isDrawingMode = true;
12007
-        console.log(canvas)
12008
-        return true;
12009
-    }
12010
-    return false;
12011
-}
12012
-var ImageEditor_FreedrawPaint = function (buddy){
12013
-    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
12014
-    if(canvas != null) {
12015
-        canvas.freeDrawingBrush.color = canvas.PaintColour;
12016
-        canvas.freeDrawingBrush.width = canvas.PaintWidth;
12017
-        canvas.ToolSelected = "Paint";
12018
-        canvas.isDrawingMode = true;
12019
-        return true;
12020
-    }
12021
-    return false;
12022
-}
12023
-var ImageEditor_Pan = function (buddy){
12024
-    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
12025
-    if(canvas != null) {
12026
-        canvas.ToolSelected = "Pan";
12027
-        canvas.isDrawingMode = false;
12028
-        return true;
12029
-    }
12030
-    return false;
12031
-}
12032
-var ImageEditor_ResetZoom = function (buddy){
12033
-    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
12034
-    if(canvas != null) {
12035
-        canvas.setZoom(1);
12036
-        canvas.setViewportTransform([1,0,0,1,0,0]);
12037
-        return true;
12038
-    } 
12039
-    return false;
12040
-}
12041
-var ImageEditor_ZoomIn = function (buddy){
12042
-    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
12043
-    if(canvas != null) {
12044
-        var zoom = canvas.getZoom();
12045
-        zoom = zoom + 0.5;
12046
-        if (zoom > 10) zoom = 10;
12047
-        if (zoom < 0.1) zoom = 0.1;
12048
-
12049
-        var point = new fabric.Point(canvas.getWidth() / 2, canvas.getHeight() / 2);
12050
-        var center = fabric.util.transformPoint(point, canvas.viewportTransform);
12051
-
12052
-        canvas.zoomToPoint(point, zoom);
12053
-
12054
-        return true;
12055
-    }
12056
-    return false;
12057
-}
12058
-var ImageEditor_ZoomOut = function (buddy){
12059
-    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
12060
-    if(canvas != null) {
12061
-        var zoom = canvas.getZoom();
12062
-        zoom = zoom - 0.5;
12063
-        if (zoom > 10) zoom = 10;
12064
-        if (zoom < 0.1) zoom = 0.1;
12065
-
12066
-        var point = new fabric.Point(canvas.getWidth() / 2, canvas.getHeight() / 2);
12067
-        var center = fabric.util.transformPoint(point, canvas.viewportTransform);
12068
-
12069
-        canvas.zoomToPoint(point, zoom);
12070
-
12071
-        return true;
12072
-    }
12073
-    return false;
12074
-}
12075
-var ImageEditor_AddCircle = function (buddy){
12076
-    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
12077
-    if(canvas != null) {
12078
-        canvas.ToolSelected = "none";
12079
-        canvas.isDrawingMode = false;
12080
-        var circle = new fabric.Circle({
12081
-            radius: 20, fill: canvas.FillColour
12082
-        })
12083
-        canvas.add(circle);
12084
-        canvas.centerObject(circle);
12085
-        canvas.setActiveObject(circle);
12086
-        return true;
12087
-    }
12088
-    return false;
12089
-}
12090
-var ImageEditor_AddRectangle = function (buddy){
12091
-    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
12092
-    if(canvas != null) {
12093
-        canvas.ToolSelected = "none";
12094
-        canvas.isDrawingMode = false;
12095
-        var rectangle = new fabric.Rect({ 
12096
-            width: 40, height: 40, fill: canvas.FillColour
12097
-        })
12098
-        canvas.add(rectangle);
12099
-        canvas.centerObject(rectangle);
12100
-        canvas.setActiveObject(rectangle);
12101
-        return true;
12102
-    }
12103
-    return false;
12104
-}
12105
-var ImageEditor_AddTriangle = function (buddy){
12106
-    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
12107
-    if(canvas != null) {
12108
-        canvas.ToolSelected = "none";
12109
-        canvas.isDrawingMode = false;
12110
-        var triangle = new fabric.Triangle({
12111
-            width: 40, height: 40, fill: canvas.FillColour
12112
-        })
12113
-        canvas.add(triangle);
12114
-        canvas.centerObject(triangle);
12115
-        canvas.setActiveObject(triangle);
12116
-        return true;
12117
-    }
12118
-    return false;
12119
-}
12120
-var ImageEditor_AddEmoji = function (buddy){
12121
-    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
12122
-    if(canvas != null) {
12123
-        canvas.ToolSelected = "none";
12124
-        canvas.isDrawingMode = false;
12125
-        var text = new fabric.Text(String.fromCodePoint(0x1F642), { fontSize : 24 });
12126
-        canvas.add(text);
12127
-        canvas.centerObject(text);
12128
-        canvas.setActiveObject(text);
12129
-        return true;
12130
-    }
12131
-    return false;
12132
-}
12133
-var ImageEditor_AddText = function (buddy, textString){
12134
-    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
12135
-    if(canvas != null) {
12136
-        canvas.ToolSelected = "none";
12137
-        canvas.isDrawingMode = false;
12138
-        var text = new fabric.IText(textString, { fill: canvas.FillColour, fontFamily: 'arial', fontSize : 18 });
12139
-        canvas.add(text);
12140
-        canvas.centerObject(text);
12141
-        canvas.setActiveObject(text);
12142
-        return true;
12143
-    }
12144
-    return false;
12145
-}
12146
-var ImageEditor_Clear = function (buddy){
12147
-    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
12148
-    if(canvas != null) {
12149
-        canvas.ToolSelected = "none";
12150
-        canvas.isDrawingMode = false;
12151
-
12152
-        var activeObjects = canvas.getActiveObjects();
12153
-        for (var i=0; i<activeObjects.length; i++){
12154
-            canvas.remove(activeObjects[i]);
12155
-        }
12156
-        canvas.discardActiveObject();
12157
-
12158
-        return true;
12159
-    }
12160
-    return false;
12161
-}
12162
-var ImageEditor_ClearAll = function (buddy){
12163
-    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
12164
-    if(canvas != null) {
12165
-        var savedBgImage = canvas.backgroundImage;
12166
-
12167
-        canvas.ToolSelected = "none";
12168
-        canvas.isDrawingMode = false;
12169
-        canvas.clear();
12170
-
12171
-        canvas.backgroundImage = savedBgImage;
12172
-        return true;
12173
-    }
12174
-    return false;
12175
-}
12176
-var ImageEditor_Cancel = function (buddy){
12177
-    console.log("Removing ImageEditor...");
12178
-
12179
-    $("#contact-" + buddy + "-imagePastePreview").empty();
12180
-    RemoveCanvas("contact-" + buddy + "-imageCanvas");
12181
-    $("#contact-" + buddy + "-imagePastePreview").hide();
12182
-}
12183
-var ImageEditor_Send = function (buddy){
12184
-    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
12185
-    if(canvas != null) {
12186
-        var imgData = canvas.toDataURL({ format: 'png' });
12187
-        SendImageDataMessage(buddy, imgData);
12188
-        return true;
12189
-    }
12190
-    return false;
12191
-}
12192
-
12193
-// Find something in the message stream
12194
-// ====================================
12195
-function FindSomething(buddy) {
12196
-    $("#contact-" + buddy + "-search").toggle();
12197
-    if($("#contact-" + buddy + "-search").is(":visible") == false){
12198
-        RefreshStream(FindBuddyByIdentity(buddy));
12199
-    }
12200
-    updateScroll(buddy);
12201
-}
12202
-
12203
-// FileShare an Upload
12204
-// ===================
12205
-var allowDradAndDrop = function() {
12206
-    var div = document.createElement('div');
12207
-    return (('draggable' in div) || ('ondragstart' in div && 'ondrop' in div)) && 'FormData' in window && 'FileReader' in window;
12208
-}
12209
-function onFileDragDrop(e, buddy){
12210
-
12211
-    var filesArray = e.dataTransfer.files;
12212
-    console.log("You are about to upload " + filesArray.length + " file.");
12213
-
12214
-    // Clear style
12215
-    $("#contact-"+ buddy +"-ChatHistory").css("outline", "none");
12216
-
12217
-    for (var f = 0; f < filesArray.length; f++){
12218
-        var fileObj = filesArray[f];
12219
-        var reader = new FileReader();
12220
-        reader.onload = function (event) {
12221
-            
12222
-            // Check if the file is under 50MB
12223
-            if(fileObj.size <= 52428800){
12224
-                // Add to Stream
12225
-                // =============
12226
-                SendFileDataMessage(buddy, event.target.result, fileObj.name, fileObj.size);
12227
-            }
12228
-            else{
12229
-                alert("The file '"+ fileObj.name +"' is bigger than 50MB, you cannot upload this file")
12230
-            }
12231
-        }
12232
-        console.log("Adding: "+ fileObj.name + " of size: "+ fileObj.size +"bytes");
12233
-        reader.readAsDataURL(fileObj);
12234
-    }
12235
-
12236
-    // Prevent Default
12237
-    preventDefault(e);
12238
-}
12239
-function cancelDragDrop(e, buddy){
12240
-    // dragleave dragend
12241
-    $("#contact-"+ buddy +"-ChatHistory").css("outline", "none");
12242
-    preventDefault(e);
12243
-}
12244
-function setupDragDrop(e, buddy){
12245
-    // dragover dragenter
12246
-    $("#contact-"+ buddy +"-ChatHistory").css("outline", "2px dashed #184369");
12247
-    preventDefault(e);
12248
-}
12249
-function preventDefault(e){
12250
-    e.preventDefault();
12251
-    e.stopPropagation();
12252
-}
12253
-
12254
-// UI Elements
12255
-// ===========
12256
-function Alert(messageStr, TitleStr, onOk) {
12257
-
12258
-    $("#jg_popup_l").empty();
12259
-    $("#jg_popup_b").empty();
12260
-    $("#windowCtrls").empty();
12261
-    $.jeegoopopup.close();
12262
-
12263
-    var html = "<div class=NoSelect>";
12264
-    html += '<div id="windowCtrls"><img id="closeImg" src="images/3_close.svg" title="Close" /></div>';
12265
-    html += "<div class=UiText style=\"padding: 0px 10px 8px 10px;\" id=AllertMessageText>" + messageStr + "</div>";
12266
-    html += "</div>"
12267
-
12268
-    $.jeegoopopup.open({
12269
-                title: TitleStr,
12270
-                html: html,
12271
-                width: '260',
12272
-                height: 'auto',
12273
-                center: true,
12274
-                scrolling: 'no',
12275
-                skinClass: 'jg_popup_basic',
12276
-                contentClass: 'confirmDelContact',
12277
-                overlay: true,
12278
-                opacity: 50,
12279
-                draggable: true,
12280
-                resizable: false,
12281
-                fadeIn: 0
12282
-    });
12283
-
12284
-    $("#jg_popup_b").append("<div id=bottomButtons><button id=AlertOkButton style=\"width:80px\">"+ lang.ok +"</button></div>");
12285
-
12286
-    $("#AlertOkButton").click(function () {
12287
-        console.log("Alert OK clicked");
12288
-        if (onOk) onOk();
12289
-    });
12290
-
12291
-    $(window).resize(function() {
12292
-       $.jeegoopopup.center();
12293
-    });
12294
-
12295
-    $("#closeImg").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
12296
-    $("#AlertOkButton").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
12297
-    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
12298
-    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); $("#jg_popup_b").empty(); } });
12299
-
12300
-}
12301
-function AlertConfigExtWindow(messageStr, TitleStr) {
12302
-
12303
-    $("#jg_popup_l").empty();
12304
-    $("#jg_popup_b").empty();
12305
-    $("#windowCtrls").empty();
12306
-    $.jeegoopopup.close();
12307
-
12308
-    videoAudioCheck = 1;
12309
-
12310
-    var html = "<div class=NoSelect>";
12311
-    html += '<div id="windowCtrls"><img id="closeImg" src="images/3_close.svg" title="Close" /></div>';
12312
-    html += "<div class=UiText style=\"padding: 10px\" id=AllertMessageText>" + messageStr + "</div>";
12313
-    html += "</div>"
12314
-
12315
-    $.jeegoopopup.open({
12316
-                title: TitleStr,
12317
-                html: html,
12318
-                width: '260',
12319
-                height: 'auto',
12320
-                center: true,
12321
-                scrolling: 'no',
12322
-                skinClass: 'jg_popup_basic',
12323
-                contentClass: 'confirmDelContact',
12324
-                overlay: true,
12325
-                opacity: 50,
12326
-                draggable: true,
12327
-                resizable: false,
12328
-                fadeIn: 0
12329
-    });
12330
-
12331
-    $("#jg_popup_b").append("<div id=bottomButtons><button id=AlertOkButton style=\"width:80px\">"+ lang.ok +"</button></div>");
12332
-
12333
-    $(window).resize(function() {
12334
-       $.jeegoopopup.center();
12335
-    });
12336
-
12337
-    $("#closeImg").click(function() { $("#windowCtrls").empty(); $("#jg_popup_b").empty(); $.jeegoopopup.close(); ConfigureExtensionWindow(); });
12338
-    $("#AlertOkButton").click(function() { console.log("Alert OK clicked"); $("#windowCtrls").empty(); $("#jg_popup_b").empty(); $.jeegoopopup.close(); ConfigureExtensionWindow(); });
12339
-    $("#jg_popup_overlay").click(function() { $("#windowCtrls").empty(); $("#jg_popup_b").empty(); $.jeegoopopup.close(); ConfigureExtensionWindow(); });
12340
-    $(window).on('keydown', function(event) { if (event.key == "Escape") { $("#windowCtrls").empty(); $("#jg_popup_b").empty(); $.jeegoopopup.close(); ConfigureExtensionWindow(); } });
12341
-
12342
-}
12343
-function Confirm(messageStr, TitleStr, onOk, onCancel) {
12344
-
12345
-    $("#jg_popup_l").empty();
12346
-    $("#jg_popup_b").empty();
12347
-    $("#windowCtrls").empty();
12348
-    $.jeegoopopup.close();
12349
-
12350
-    var html = "<div class=NoSelect>";
12351
-    html += '<div id="windowCtrls"><img id="closeImg" src="images/3_close.svg" title="Close" /></div>';
12352
-    html += "<div class=UiText style=\"padding: 10px\" id=ConfirmMessageText>" + messageStr + "</div>";
12353
-    html += "</div>";
12354
-
12355
-    $.jeegoopopup.open({
12356
-                html: html,
12357
-                width: '260',
12358
-                height: 'auto',
12359
-                center: true,
12360
-                scrolling: 'no',
12361
-                skinClass: 'jg_popup_basic',
12362
-                contentClass: 'confirmDelContact',
12363
-                overlay: true,
12364
-                opacity: 50,
12365
-                draggable: true,
12366
-                resizable: false,
12367
-                fadeIn: 0
12368
-    });
12369
-
12370
-    $("#jg_popup_b").append("<div id=ConfDelContact><button id=ConfirmOkButton>"+ lang.ok +"</button><button id=ConfirmCancelButton>"+ lang.cancel +"</button></div>");
12371
-
12372
-    $("#ConfirmOkButton").click(function () {
12373
-        console.log("Confirm OK clicked");
12374
-        if (onOk) onOk();
12375
-    });
12376
-    $("#ConfirmCancelButton").click(function () {
12377
-        console.log("Confirm Cancel clicked");
12378
-        if (onCancel) onCancel();
12379
-    });
12380
-
12381
-    $(window).resize(function() {
12382
-       $.jeegoopopup.center();
12383
-    });
12384
-
12385
-    $("#closeImg").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
12386
-    $("#ConfirmOkButton").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
12387
-    $("#ConfirmCancelButton").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
12388
-    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
12389
-    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); $("#jg_popup_b").empty(); } });
12390
-}
12391
-function ConfirmConfigExtWindow(messageStr, TitleStr, onOk, onCancel) {
12392
-
12393
-    $("#jg_popup_l").empty();
12394
-    $("#jg_popup_b").empty();
12395
-    $("#windowCtrls").empty();
12396
-    $.jeegoopopup.close();
12397
-
12398
-    var html = "<div class=NoSelect>";
12399
-    html += "<div id=windowCtrls><img id=closeImg src=images/3_close.svg title=Close /></div>";
12400
-    html += "<div class=UiText style=\"padding: 10px\" id=ConfirmMessageText>" + messageStr + "</div>";
12401
-    html += "</div>";
12402
-
12403
-    $.jeegoopopup.open({
12404
-                html: html,
12405
-                width: '260',
12406
-                height: 'auto',
12407
-                center: true,
12408
-                scrolling: 'no',
12409
-                skinClass: 'jg_popup_basic',
12410
-                contentClass: 'ConfCloseAccount',
12411
-                overlay: true,
12412
-                opacity: 50,
12413
-                draggable: true,
12414
-                resizable: false,
12415
-                fadeIn: 0
12416
-    });
12417
-
12418
-    $("#jg_popup_b").append("<div id=ConfCloseAccount><button id=ConfirmOkButton>"+ lang.close_user_account +"</button><button id=ConfirmCancelButton>"+ lang.cancel +"</button></div>");
12419
-
12420
-    $("#ConfirmOkButton").click(function () {
12421
-        console.log("Confirm OK clicked");
12422
-        if (onOk) onOk();
12423
-    });
12424
-    $("#ConfirmCancelButton").click(function () {
12425
-        console.log("Confirm Cancel clicked");
12426
-        if (onCancel) onCancel();
12427
-
12428
-        $("#windowCtrls").empty();
12429
-        $("#jg_popup_b").empty();
12430
-        $.jeegoopopup.close();
12431
-        ConfigureExtensionWindow();
12432
-    });
12433
-
12434
-    $(window).resize(function() {
12435
-       $.jeegoopopup.center();
12436
-    });
12437
-
12438
-    $("#closeImg").click(function() { $("#jg_popup_b").empty(); $("#windowCtrls").empty(); $.jeegoopopup.close(); ConfigureExtensionWindow(); });
12439
-}
12440
-function Prompt(messageStr, TitleStr, FieldText, defaultValue, dataType, placeholderText, onOk, onCancel) {
12441
-
12442
-    $("#jg_popup_l").empty();
12443
-    $("#jg_popup_b").empty();
12444
-    $("#windowCtrls").empty();
12445
-    $.jeegoopopup.close();
12446
-
12447
-    var html = "<div class=NoSelect>";
12448
-    html += '<div id="windowCtrls"><img id="closeImg" src="images/3_close.svg" title="Close" /></div>';
12449
-    html += "<div class=UiText style=\"padding: 10px\" id=PromptMessageText>";
12450
-    html += messageStr;
12451
-    html += "<div style=\"margin-top:10px\">" + FieldText + " : </div>";
12452
-    html += "<div style=\"margin-top:5px\"><INPUT id=PromptValueField type=" + dataType + " value=\"" + defaultValue + "\" placeholder=\"" + placeholderText + "\" style=\"width:98%\"></div>"
12453
-    html += "</div>";
12454
-    html += "</div>";
12455
-
12456
-    $.jeegoopopup.open({
12457
-                html: html,
12458
-                width: '260',
12459
-                height: 'auto',
12460
-                center: true,
12461
-                scrolling: 'no',
12462
-                skinClass: 'jg_popup_basic',
12463
-                contentClass: 'confirmDelContact',
12464
-                overlay: true,
12465
-                opacity: 50,
12466
-                draggable: true,
12467
-                resizable: false,
12468
-                fadeIn: 0
12469
-    });
12470
-
12471
-    $("#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>");
12472
-
12473
-    $("#PromptOkButton").click(function () {
12474
-        console.log("Prompt OK clicked, with value: " + $("#PromptValueField").val());
12475
-        if (onOk) onOk($("#PromptValueField").val());
12476
-    });
12477
-
12478
-    $("#PromptCancelButton").click(function () {
12479
-        console.log("Prompt Cancel clicked");
12480
-        if (onCancel) onCancel();
12481
-    });
12482
-
12483
-    $(window).resize(function() {
12484
-       $.jeegoopopup.center();
12485
-    });
12486
-
12487
-    $("#closeImg").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
12488
-    $("#PromptOkButton").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
12489
-    $("#PromptCancelButton").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
12490
-    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
12491
-    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); $("#jg_popup_b").empty(); } });
12492
-}
12493
-
12494
-// Device Detection
12495
-// ================
12496
-function DetectDevices(){
12497
-    navigator.mediaDevices.enumerateDevices().then(function(deviceInfos){
12498
-        // deviceInfos will not have a populated lable unless to accept the permission
12499
-        // during getUserMedia. This normally happens at startup/setup
12500
-        // so from then on these devices will be with lables.
12501
-        HasVideoDevice = false;
12502
-        HasAudioDevice = false;
12503
-        HasSpeakerDevice = false; // Safari and Firefox don't have these
12504
-        AudioinputDevices = [];
12505
-        VideoinputDevices = [];
12506
-        SpeakerDevices = [];
12507
-        for (var i = 0; i < deviceInfos.length; ++i) {
12508
-            if (deviceInfos[i].kind === "audioinput") {
12509
-                HasAudioDevice = true;
12510
-                AudioinputDevices.push(deviceInfos[i]);
12511
-            } 
12512
-            else if (deviceInfos[i].kind === "audiooutput") {
12513
-                HasSpeakerDevice = true;
12514
-                SpeakerDevices.push(deviceInfos[i]);
12515
-            }
12516
-            else if (deviceInfos[i].kind === "videoinput") {
12517
-                HasVideoDevice = true;
12518
-                VideoinputDevices.push(deviceInfos[i]);
12519
-            }
12520
-        }
12521
-
12522
-    }).catch(function(e){
12523
-        console.error("Error enumerating devices", e);
12524
-    });
12525
-}
12526
-DetectDevices();
12527
-window.setInterval(function(){
12528
-    DetectDevices();
12529
-}, 10000);
12530
-
12531
-// STATUS_NULL: 0
12532
-// STATUS_INVITE_SENT: 1
12533
-// STATUS_1XX_RECEIVED: 2
12534
-// STATUS_INVITE_RECEIVED: 3
12535
-// STATUS_WAITING_FOR_ANSWER: 4
12536
-// STATUS_ANSWERED: 5
12537
-// STATUS_WAITING_FOR_PRACK: 6
12538
-// STATUS_WAITING_FOR_ACK: 7
12539
-// STATUS_CANCELED: 8
12540
-// STATUS_TERMINATED: 9
12541
-// STATUS_ANSWERED_WAITING_FOR_PRACK: 10
12542
-// STATUS_EARLY_MEDIA: 11
12543
-// STATUS_CONFIRMED: 12
12544
-
12545
-// =======================================
12546
-// End Of File
12547 0
deleted file mode 100644
... ...
@@ -1 +0,0 @@
1
-var enabledExtendedServices=!1,enabledGroupServices=!1;const availableLang=["ja","zh-hans","zh","ru","tr","nl"];var wssServer=getDbItem("wssServer",null),profileUserID=getDbItem("profileUserID",null),profileUser=getDbItem("profileUser",null),profileName=getDbItem("profileName",null),WebSocketPort=getDbItem("WebSocketPort",null),ServerPath=getDbItem("ServerPath",null),SipUsername=getDbItem("SipUsername",null),SipPassword=getDbItem("SipPassword",null),StunServer=getDbItem("StunServer",""),TransportConnectionTimeout=parseInt(getDbItem("TransportConnectionTimeout",15)),TransportReconnectionAttempts=parseInt(getDbItem("TransportReconnectionAttempts",99)),TransportReconnectionTimeout=parseInt(getDbItem("TransportReconnectionTimeout",15)),userAgentStr=getDbItem("UserAgentStr","Roundpin (SipJS - 0.11.6)"),hostingPrefex=getDbItem("HostingPrefex",""),RegisterExpires=parseInt(getDbItem("RegisterExpires",300)),WssInTransport="1"==getDbItem("WssInTransport","1"),IpInContact="1"==getDbItem("IpInContact","1"),IceStunCheckTimeout=parseInt(getDbItem("IceStunCheckTimeout",500)),AutoAnswerEnabled="1"==getDbItem("AutoAnswerEnabled","0"),DoNotDisturbEnabled="1"==getDbItem("DoNotDisturbEnabled","0"),CallWaitingEnabled="1"==getDbItem("CallWaitingEnabled","1"),RecordAllCalls="1"==getDbItem("RecordAllCalls","0"),StartVideoFullScreen="0"==getDbItem("StartVideoFullScreen","1"),AutoGainControl="1"==getDbItem("AutoGainControl","1"),EchoCancellation="1"==getDbItem("EchoCancellation","1"),NoiseSuppression="1"==getDbItem("NoiseSuppression","1"),MirrorVideo=getDbItem("VideoOrientation","rotateY(180deg)"),maxFrameRate=getDbItem("FrameRate",""),videoHeight=getDbItem("VideoHeight",""),videoAspectRatio=getDbItem("AspectRatio",""),NotificationsActive="1"==getDbItem("Notifications","0"),StreamBuffer=parseInt(getDbItem("StreamBuffer",50)),PosterJpegQuality=parseFloat(getDbItem("PosterJpegQuality",.6)),VideoResampleSize=getDbItem("VideoResampleSize","HD"),RecordingVideoSize=getDbItem("RecordingVideoSize","HD"),RecordingVideoFps=parseInt(getDbItem("RecordingVideoFps",12)),RecordingLayout=getDbItem("RecordingLayout","them-pnp"),DidLength=parseInt(getDbItem("DidLength",6)),MaxDidLength=parseInt(getDbItem("maximumNumberLength",16)),DisplayDateFormat=getDbItem("DateFormat","YYYY-MM-DD"),DisplayTimeFormat=getDbItem("TimeFormat","h:mm:ss A"),Language=getDbItem("Language","auto"),EnableTextMessaging="1"==getDbItem("EnableTextMessaging","1"),DisableFreeDial="1"==getDbItem("DisableFreeDial","0"),DisableBuddies="1"==getDbItem("DisableBuddies","0"),EnableTransfer="1"==getDbItem("EnableTransfer","1"),EnableConference="1"==getDbItem("EnableConference","1"),AutoAnswerPolicy=getDbItem("AutoAnswerPolicy","allow"),DoNotDisturbPolicy=getDbItem("DoNotDisturbPolicy","allow"),CallWaitingPolicy=getDbItem("CallWaitingPolicy","allow"),CallRecordingPolicy=getDbItem("CallRecordingPolicy","allow"),EnableAccountSettings="1"==getDbItem("EnableAccountSettings","1"),EnableAudioVideoSettings="1"==getDbItem("EnableAudioVideoSettings","1"),EnableAppearanceSettings="1"==getDbItem("EnableAppearanceSettings","1"),EnableChangeUserPasswordSettings="1"==getDbItem("EnableChangeUserPasswordSettings","1"),EnableChangeUserEmailSettings="1"==getDbItem("EnableChangeUserEmailSettings","1"),EnableCloseUserAccount="1"==getDbItem("EnableCloseUserAccount","1"),EnableAlphanumericDial="1"==getDbItem("EnableAlphanumericDial","1"),EnableVideoCalling="1"==getDbItem("EnableVideoCalling","1"),winVideoConf=null,winVideoConfCheck=0,localDB=window.localStorage,userAgent=null,voicemailSubs=null,BlfSubs=[],CanvasCollection=[],Buddies=[],isReRegister=!1,dhtmlxPopup=null,selectedBuddy=null,selectedLine=null,alertObj=null,confirmObj=null,promptObj=null,windowsCollection=null,messagingCollection=null,HasVideoDevice=!1,HasAudioDevice=!1,HasSpeakerDevice=!1,AudioinputDevices=[],VideoinputDevices=[],SpeakerDevices=[],Lines=[],lang={},audioBlobs={},newLineNumber=0,videoAudioCheck=0,RCLoginCheck=0,decSipPass="",currentChatPrivKey="",sendFileCheck=0,upFileName="",sendFileChatErr="",pubKeyCheck=0,splitMessage={};function uID(){return Date.now()+Math.floor(1e4*Math.random()).toString(16).toUpperCase()}function utcDateNow(){return moment().utc().format("YYYY-MM-DD HH:mm:ss UTC")}function getDbItem(e,t){var i=window.localStorage;return null!=i.getItem(e)?i.getItem(e):t}function getAudioSrcID(){var e=localDB.getItem("AudioSrcId");return null!=e?e:"default"}function getAudioOutputID(){var e=localDB.getItem("AudioOutputId");return null!=e?e:"default"}function getVideoSrcID(){var e=localDB.getItem("VideoSrcId");return null!=e?e:"default"}function getRingerOutputID(){var e=localDB.getItem("RingOutputId");return null!=e?e:"default"}function formatDuration(e){var t,i=Math.floor(parseFloat(e));return i<0?i:i>=0&&i<60?i+" "+(1!=i?lang.seconds_plural:lang.second_single):i>=60&&i<3600?(t=moment.duration(i,"seconds")).minutes()+" "+(1!=t.minutes()?lang.minutes_plural:lang.minute_single)+" "+t.seconds()+" "+(1!=t.seconds()?lang.seconds_plural:lang.second_single):i>=3600&&i<86400?(t=moment.duration(i,"seconds")).hours()+" "+(1!=t.hours()?lang.hours_plural:lang.hour_single)+" "+t.minutes()+" "+(1!=t.minutes()?lang.minutes_plural:lang.minute_single)+" "+t.seconds()+" "+(1!=t.seconds()?lang.seconds_plural:lang.second_single):void 0}function formatShortDuration(e){var t,i=Math.floor(parseFloat(e));return i<0?i:i>=0&&i<60?"00:"+(i>9?i:"0"+i):i>=60&&i<3600?((t=moment.duration(i,"seconds")).minutes()>9?t.minutes():"0"+t.minutes())+":"+(t.seconds()>9?t.seconds():"0"+t.seconds()):i>=3600&&i<86400?((t=moment.duration(i,"seconds")).hours()>9?t.hours():"0"+t.hours())+":"+(t.minutes()>9?t.minutes():"0"+t.minutes())+":"+(t.seconds()>9?t.seconds():"0"+t.seconds()):void 0}function formatBytes(e,t){if(0===e)return"0 "+lang.bytes;var i=t&&t>=0?t:2,n=[lang.bytes,lang.kb,lang.mb,lang.gb,lang.tb,lang.pb,lang.eb,lang.zb,lang.yb],a=Math.floor(Math.log(e)/Math.log(1024));return parseFloat((e/Math.pow(1024,a)).toFixed(i))+" "+n[a]}function UserLocale(){var e=window.navigator.userLanguage||window.navigator.language;return langtag=e.split("-"),1==langtag.length?"":2==langtag.length||langtag.length>=3?langtag[1].toLowerCase():void 0}function GetAlternateLanguage(){var e=window.navigator.userLanguage||window.navigator.language;if("auto"!=Language&&(e=Language),"en"==(e=e.toLowerCase())||0==e.indexOf("en-"))return"";for(l=0;l<availableLang.length;l++)if(0==e.indexOf(availableLang[l].toLowerCase()))return console.log("Alternate Language detected: ",e),moment.locale(e),availableLang[l].toLowerCase();return""}function getFilter(e,t){return-1!=e.indexOf(",",e.indexOf(t+": ")+t.length+2)?e.substring(e.indexOf(t+": ")+t.length+2,e.indexOf(",",e.indexOf(t+": ")+t.length+2)):e.substring(e.indexOf(t+": ")+t.length+2)}function base64toBlob(e,t){e.indexOf(!0)&&(e=e.split(",")[1]);for(var i=atob(e),n=Math.ceil(i.length/1024),a=new Array(n),o=0;o<n;++o){for(var l=1024*o,s=Math.min(l+1024,i.length),r=new Array(s-l),d=l,c=0;d<s;++c,++d)r[c]=i[d].charCodeAt(0);a[o]=new Uint8Array(r)}return new Blob(a,{type:t})}function MakeDataArray(e,t){for(var i=new Array(t),n=0;n<i.length;n++)i[n]=e;return i}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 e=$("#Configure_Account_StunServer").val(),t=$("#playbackSrc").val(),i=$("#previewVideoSrc").val(),n=$("input[name=Settings_Quality]:checked").val(),a=parseInt($("input[name=Settings_FrameRate]:checked").val()),o=$("input[name=Settings_AspectRatio]:checked").val(),l=$("input[name=Settings_Oriteation]:checked").val(),s=$("#microphoneSrc").val(),r=$("#Settings_AutoGainControl").is(":checked")?"1":"0",d=$("#Settings_EchoCancellation").is(":checked")?"1":"0",c=$("#Settings_NoiseSuppression").is(":checked")?"1":"0",u=$("#ringDevice").val(),p=$("#Video_Conf_Extension").val(),g=$("#Video_Conf_Window_Width").val(),m=void 0===getDbItem("profilePicture","")?"":getDbItem("profilePicture",""),f=$("#Settings_Notifications").is(":checked")?1:0,v=$("#emailIntegration").is(":checked")?1:0,h=$("#RoundcubeDomain").val(),b=$("#rcBasicAuthUser").val(),y=$("#rcBasicAuthPass").val(),w=$("#RoundcubeUser").val(),S=$("#RoundcubePass").val();""!=userName?""!=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:e,audio_output_id:t,video_src_id:i,video_height:n,frame_rate:a,aspect_ratio:o,video_orientation:l,audio_src_id:s,auto_gain_control:r,echo_cancellation:d,noise_suppression:c,ring_output_id:u,video_conf_extension:p,video_conf_window_width:g,profile_picture:m,notifications:f,use_roundcube:v,rcdomain:h,rcbasicauthuser:b,rcbasicauthpass:y,rcuser:w,rcpassword:S,s_ajax_call:validateSToken},success:function(e){window.location.reload()},error:function(e){alert("An error occurred while attempting to save the account configuration data!")}}):alert("Fields: 'WebSocket Domain', 'WebSocket Port', 'WebSocket Path', 'SIP Username' and 'SIP Password' are required ! Please fill in all these fields !"):alert("An error occurred while attempting to save the data!")}function getConfFromSqldb(){$.ajax({type:"POST",url:"get-settings.php",dataType:"JSON",data:{username:userName,s_ajax_call:validateSToken},success:function(e){if(null==e.wss_server||null==e.web_socket_port||null==e.server_path||null==e.sip_username||null==e.sip_password)ConfigureExtensionWindow();else{if(localStorage.getItem("firstReLoad")||(localStorage.firstReLoad=!0,window.setTimeout((function(){window.location.reload()}),200)),null==e.stun_server||void 0===e.stun_server)var t="";else t=e.stun_server;localDB.setItem("profileUserID",uID()),localDB.setItem("userrole",e.userrole),localDB.setItem("wssServer",e.wss_server),localDB.setItem("WebSocketPort",e.web_socket_port),localDB.setItem("ServerPath",e.server_path),localDB.setItem("profileUser",e.sip_username),localDB.setItem("profileName",e.profile_name),localDB.setItem("SipUsername",e.sip_username),localDB.setItem("SipPassword",e.sip_password),localDB.setItem("StunServer",t),localDB.setItem("AudioOutputId",e.audio_output_id),localDB.setItem("VideoSrcId",e.video_src_id),localDB.setItem("VideoHeight",e.video_height),localDB.setItem("FrameRate",e.frame_rate),localDB.setItem("AspectRatio",e.aspect_ratio),localDB.setItem("VideoOrientation",e.video_orientation),localDB.setItem("AudioSrcId",e.audio_src_id),localDB.setItem("AutoGainControl",e.auto_gain_control),localDB.setItem("EchoCancellation",e.echo_cancellation),localDB.setItem("NoiseSuppression",e.noise_suppression),localDB.setItem("RingOutputId",e.ring_output_id),localDB.setItem("VidConfExtension",e.video_conf_extension),localDB.setItem("VidConfWindowWidth",e.video_conf_window_width),localDB.setItem("profilePicture",e.profile_picture),localDB.setItem("Notifications",e.notifications),localDB.setItem("useRoundcube",e.use_roundcube),localDB.setItem("rcDomain",""!=e.rcdomain&&null!=e.rcdomain&&void 0!==e.rcdomain?e.rcdomain:""),localDB.setItem("rcBasicAuthUser",e.rcbasicauthuser),localDB.setItem("rcBasicAuthPass",e.rcbasicauthpass),localDB.setItem("RoundcubeUser",e.rcuser),localDB.setItem("RoundcubePass",e.rcpassword),Register()}},error:function(e){alert("An error occurred while attempting to retrieve account configuration data from the database!")}})}function saveContactToSQLDB(e){0!=e.length?$.ajax({type:"POST",url:"save-contact.php",dataType:"JSON",data:{username:userName,contact_name:e[0],contact_desc:e[1],extension_number:e[2],contact_mobile:e[3],contact_num1:e[4],contact_num2:e[5],contact_email:e[6],s_ajax_call:validateSToken},success:function(e){"success"!=e.result&&alert(e.result)},error:function(e){alert("An error occurred while attempting to save the contact to the database!")}}):alert("An error occurred while attempting to save the data!")}function updateContactToSQLDB(e){0!=e.length?""!=e[7]&&null!=e[7]&&void 0!==e[7]?$.ajax({type:"POST",url:"update-contact.php",dataType:"JSON",data:{contact_name:e[0],contact_desc:e[1],extension_number:e[2],contact_mobile:e[3],contact_num1:e[4],contact_num2:e[5],contact_email:e[6],contactDBID:e[7],s_ajax_call:validateSToken},success:function(e){"success"!=e.result&&alert(e.result)},error:function(e){alert("An error occurred while attempting to save the data!")}}):alert("Error while attempting to retrieve contact data from the database!"):alert("An error occurred while attempting to save the data!")}function saveContactPicToSQLDB(e){0!=e.length?$.ajax({type:"POST",url:"save-update-contact-picture.php",dataType:"JSON",data:{username:userName,contact_name:e[0],profile_picture_c:e[1],s_ajax_call:validateSToken},success:function(e){},error:function(e){alert("An error occurred while attempting to save contact picture!")}}):alert("An error occurred while attempting to save contact picture!")}function getContactsFromSQLDB(){$.ajax({type:"POST",url:"get-contacts.php",dataType:"JSON",data:{username:userName,s_ajax_call:validateSToken},success:function(e){var t=InitUserBuddies();$.each(e.contactsinfo,(function(i,n){var a=uID(),o=utcDateNow();""==e.contactsinfo[i].extension_number||null==e.contactsinfo[i].extension_number?(t.DataCollection.push({Type:"contact",LastActivity:o,ExtensionNumber:"",MobileNumber:e.contactsinfo[i].contact_mobile,ContactNumber1:e.contactsinfo[i].contact_num1,ContactNumber2:e.contactsinfo[i].contact_num2,uID:null,cID:a,gID:null,DisplayName:e.contactsinfo[i].contact_name,Position:"",Description:e.contactsinfo[i].contact_desc,Email:e.contactsinfo[i].contact_email,MemberCount:0}),""!=e.contactsinfo[i].profile_picture_c&&null!=e.contactsinfo[i].profile_picture_c&&localDB.setItem("img-"+a+"-contact",e.contactsinfo[i].profile_picture_c),AddBuddy(new Buddy("contact",a,e.contactsinfo[i].contact_name,"",e.contactsinfo[i].contact_mobile,e.contactsinfo[i].contact_num1,e.contactsinfo[i].contact_num2,o,e.contactsinfo[i].contact_desc,e.contactsinfo[i].contact_email),!0,!1,!1)):(t.DataCollection.push({Type:"extension",LastActivity:o,ExtensionNumber:e.contactsinfo[i].extension_number,MobileNumber:e.contactsinfo[i].contact_mobile,ContactNumber1:e.contactsinfo[i].contact_num1,ContactNumber2:e.contactsinfo[i].contact_num2,uID:a,cID:null,gID:null,DisplayName:e.contactsinfo[i].contact_name,Position:e.contactsinfo[i].contact_desc,Description:"",Email:e.contactsinfo[i].contact_email,MemberCount:0}),""!=e.contactsinfo[i].profile_picture_c&&null!=e.contactsinfo[i].profile_picture_c&&localDB.setItem("img-"+a+"-extension",e.contactsinfo[i].profile_picture_c),AddBuddy(new Buddy("extension",a,e.contactsinfo[i].contact_name,e.contactsinfo[i].extension_number,e.contactsinfo[i].contact_mobile,e.contactsinfo[i].contact_num1,e.contactsinfo[i].contact_num2,o,e.contactsinfo[i].contact_desc,e.contactsinfo[i].contact_email),!0,!1,!0))})),t.TotalRows=t.DataCollection.length,localDB.setItem(profileUserID+"-Buddies",JSON.stringify(t)),UpdateUI(),PopulateBuddyList()},error:function(e){alert("An error occurred while attempting to retrieve contacts data from the database!")}})}function getExternalUserConfFromSqldb(){$.ajax({type:"POST",url:"get-external-users-conf.php",dataType:"JSON",data:{username:userName,s_ajax_call:validateSToken},success:function(e){if(JSON.stringify(e).length>0){localDB.setItem("externalUserConfElem",e.length);for(var t=0;t<e.length;t++)localDB.setItem("extUserExtension-"+t,e[t].exten_for_external),localDB.setItem("extUserExtensionPass-"+t,e[t].exten_for_ext_pass),localDB.setItem("confAccessLink-"+t,e[t].conf_access_link)}},error:function(e){alert("An error occurred while attempting to retrieve external users configuration data from the database!")}})}function checkExternalLinks(){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(e){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(),null!=winVideoConf&&winVideoConf.close(),window.open("https://"+window.location.host+"/logout.php","_self")},error:function(e){alert("An error occurred while trying to remove the data from the database!"),Unregister(),console.log("Signing Out ..."),localStorage.clear(),null!=winVideoConf&&winVideoConf.close(),window.open("https://"+window.location.host+"/logout.php","_self")}}):(Unregister(),console.log("Signing Out ..."),localStorage.clear(),null!=winVideoConf&&winVideoConf.close(),window.open("https://"+window.location.host+"/logout.php","_self"))}function deleteBuddyFromSqldb(e){$.ajax({type:"POST",url:"remove-contact.php",dataType:"JSON",data:{username:userName,contact_name:e,s_ajax_call:validateSToken},success:function(e){},error:function(e){alert("An error occurred while attempting to remove the contact from the database!")}})}function saveNewUserPassword(){var e=$("#Current_User_Password").val(),t=$("#New_User_Password").val(),i=$("#Repeat_New_User_Password").val();""!=e&&""!=t&&""!=i?/^((?=.*\d)(?=.*[a-z])(?=.*\W).{10,})$/.test(t)?i==t?$.ajax({type:"POST",url:"save-new-user-password.php",dataType:"JSON",data:{username:userName,current_password:e,new_password:t,s_ajax_call:validateSToken},success:function(e){alert(e)},error:function(e){alert("An error occurred while attempting to change the user password!")}}):alert("The passwords entered in the new password fields don't match!"):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 ! "):alert("Please fill in all the fields!")}function saveNewUserEmail(){var e=$("#Current_User_Email").val(),t=$("#New_User_Email").val(),i=$("#Repeat_New_User_Email").val();""!=e&&""!=t&&""!=i?/^[A-Za-z0-9\_\.\-\~\%\+\!\?\&\*\^\=\#\$\{\}\|\/]+@[A-Za-z0-9\.\-]+\.[A-Za-z0-9\-]{2,63}$/.test(t)?i==t?$.ajax({type:"POST",url:"save-new-user-email.php",dataType:"JSON",data:{username:userName,current_email:e,new_email:t,s_ajax_call:validateSToken},success:function(e){alert(e)},error:function(e){alert("An error occurred while attempting to change the user email address!")}}):alert("The email addresses entered in the new email fields don't match!"):alert("The new email address is not a valid email address. Please enter a valid email address!"):alert("Please fill in all the fields!")}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(e){alert(e),SignOut()},error:function(e){alert("An error occurred while attempting to close your user account!")}})}))}function LaunchVideoConference(){0==winVideoConfCheck?(winVideoConf=window.open("https://"+window.location.host+"/videoconference/index.php"),winVideoConfCheck=1):alert('The video conference has been launched. If you want to launch it again refresh the page, then click "Launch Video Conference".')}function generateChatRSAKeys(e){var t=new JSEncrypt({default_key_size:1024});t.getKey();var i=t.getPublicKey();currentChatPrivKey=t.getPrivateKey(),$.ajax({type:"POST",url:"save-text-chat-pub-key.php",dataType:"JSON",data:{currentextension:e,currentchatpubkey:i,s_ajax_call:validateSToken},success:function(){},error:function(){alert("An error occurred while trying to save the new text chat public key!")}})}function removeTextChatUploads(e){$.ajax({type:"POST",url:"text-chat-remove-uploaded-files.php",dataType:"JSON",data:{sipusername:e,s_ajax_call:validateSToken},success:function(e){"success"!=e.note&&alert("An error occurred while trying to remove the text chat 'uploads' directory!")},error:function(e){alert("An error occurred while attempting to remove the text chat 'uploads' directory!")}})}function closeVideoConfTab(){winVideoConf&&winVideoConf.close()}function ShowEmailWindow(){if(1==getDbItem("useRoundcube","")){$("#roundcubeFrame").remove(),$("#rightContent").show(),$(".streamSelected").each((function(){$(this).css("display","none")})),$("#rightContent").append('<iframe id="roundcubeFrame" name="displayFrame"></iframe>');var e="",t="",i="",n="",a="";if($.ajax({async:!1,global:!1,type:"POST",url:"get-email-info.php",dataType:"JSON",data:{username:userName,s_ajax_call:validateSToken},success:function(o){e=o.rcdomain,t=encodeURIComponent(o.rcbasicauthuser),i=encodeURIComponent(o.rcbasicauthpass),n=o.rcuser,a=o.rcpassword},error:function(e){alert("An error occurred while trying to retrieve data from the database!")}}),""!=t&&""!=i)var o="https://"+t+":"+i+"@"+e+"/";else o="https://"+e+"/";var l='<form id="rcForm" method="POST" action="'+o+'" target="displayFrame">';l+='<input type="hidden" name="_action" value="login" />',l+='<input type="hidden" name="_task" value="login" />',l+='<input type="hidden" name="_autologin" value="1" />',l+='<input name="_user" value="'+n+'" type="text" />',l+='<input name="_pass" value="'+a+'" type="password" />',l+='<input id="submitButton" type="submit" value="Login" />',l+="</form>",$("#roundcubeFrame").append(l),0==RCLoginCheck?($("#submitButton").click(),RCLoginCheck=1):$("#roundcubeFrame").attr("src",o)}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'")}function CollapseLeftPanel(){$(window).width()>=920&&($("#leftContent").hasClass("shrinkLeftContent")?($("#leftContent").removeClass("shrinkLeftContent"),$("#rightContent").removeClass("widenRightContent"),$("#aboutImg").css("margin-right","-3px")):($("#leftContent").addClass("shrinkLeftContent"),$("#rightContent").addClass("widenRightContent"),$("#aboutImg").css("margin-right","3px")))}function ShowAboutWindow(){$.jeegoopopup.close();var e="<div>";e+='<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>',e+='<div class="UiWindowField scroller">',e+='<div><img id="AboutLogoImg" src="images/login-logo.svg"/></div>',e+='<div id="aboutPopup">'+lang.about_text+"</div>",e+="</div></div>",$.jeegoopopup.open({title:"About Roundpin",html:e,width:"640",height:"500",center:!0,scrolling:"no",skinClass:"jg_popup_basic",overlay:!0,opacity:50,draggable:!0,resizable:!1,fadeIn:0}),$("#jg_popup_b").append('<button id="ok_button">'+lang.ok+"</button>");var t=$(window).width()-12,i=$(window).height()-88;t<656||i<500?($.jeegoopopup.width(t).height(i),$.jeegoopopup.center(),$("#maximizeImg").hide(),$("#minimizeImg").hide()):($.jeegoopopup.width(640).height(500),$.jeegoopopup.center(),$("#minimizeImg").hide(),$("#maximizeImg").show()),$(window).resize((function(){t=$(window).width()-12,i=$(window).height()-88,$.jeegoopopup.center(),t<656||i<500?($.jeegoopopup.width(t).height(i),$.jeegoopopup.center(),$("#maximizeImg").hide(),$("#minimizeImg").hide()):($.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(t).height(i),$.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(e){"Escape"==e.key&&($.jeegoopopup.close(),$("#jg_popup_b").empty())}))}function incomingCallNote(){new Notification(lang.incomming_call,{icon:"../images/notification-logo.svg",body:"New incoming call !!!"}).onclick=function(e){},document.hasFocus()||setTimeout(incomingCallNote,8e3)}function changePageTitle(){"Roundpin"==$(document).attr("title")?$(document).prop("title","New call !!!"):$(document).prop("title","Roundpin"),document.hasFocus()?$(document).prop("title","Roundpin"):setTimeout(changePageTitle,460)}function UpdateUI(){$(window).outerWidth()<920?null==selectedBuddy&null==selectedLine?($("#rightContent").hide(),$("#leftContent").css("width","100%"),$("#leftContent").show()):($("#rightContent").css("margin-left","0px"),$("#rightContent").show(),$("#leftContent").hide(),null!=selectedBuddy&&updateScroll(selectedBuddy.identity)):null==selectedBuddy&null==selectedLine?($("#leftContent").css("width","320px"),$("#rightContent").css("margin-left","0px"),$("#leftContent").show(),$("#rightContent").hide()):($("#leftContent").css("width","320px"),$("#rightContent").css("margin-left","320px"),$("#leftContent").show(),$("#rightContent").show(),null!=selectedBuddy&&updateScroll(selectedBuddy.identity));for(var e=0;e<Lines.length;e++)updateLineScroll(Lines[e].LineNumber)}function AddSomeoneWindow(e){$("#userMenu").hide(),$.jeegoopopup.close();var t="<div id='AddNewContact'>";t+="<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>",t+="<div class='UiWindowField scroller'>",t+="<div class=UiText>"+lang.display_name+":</div>",t+="<div><input id=AddSomeone_Name class=UiInputText type=text placeholder='"+lang.eg_display_name+"'></div>",t+="<div class=UiText>"+lang.title_description+":</div>",t+="<div><input id=AddSomeone_Desc class=UiInputText type=text placeholder='"+lang.eg_general_manager+"'></div>",t+="<div class=UiText>"+lang.internal_subscribe_extension+":</div>",e&&e.length>1&&e.length<DidLength&&"*"!=e.substring(0,1)?t+="<div><input id=AddSomeone_Exten class=UiInputText type=text value="+e+" placeholder='"+lang.eg_internal_subscribe_extension+"'></div>":t+="<div><input id=AddSomeone_Exten class=UiInputText type=text placeholder='"+lang.eg_internal_subscribe_extension+"'></div>",t+="<div class=UiText>"+lang.mobile_number+":</div>",t+="<div><input id=AddSomeone_Mobile class=UiInputText type=text placeholder='"+lang.eg_mobile_number+"'></div>",t+="<div class=UiText>"+lang.contact_number_1+":</div>",e&&e.length>1?t+="<div><input id=AddSomeone_Num1 class=UiInputText type=text value="+e+" placeholder='"+lang.eg_contact_number_1+"'></div>":t+="<div><input id=AddSomeone_Num1 class=UiInputText type=text placeholder='"+lang.eg_contact_number_1+"'></div>",t+="<div class=UiText>"+lang.contact_number_2+":</div>",t+="<div><input id=AddSomeone_Num2 class=UiInputText type=text placeholder='"+lang.eg_contact_number_2+"'></div>",t+="<div class=UiText>"+lang.email+":</div>",t+="<div><input id=AddSomeone_Email class=UiInputText type=text placeholder='"+lang.eg_email+"'></div>",t+="</div></div>",$.jeegoopopup.open({title:"Add Contact",html:t,width:"640",height:"500",center:!0,scrolling:"no",skinClass:"jg_popup_basic",contentClass:"addContactPopup",overlay:!0,opacity:50,draggable:!0,resizable:!1,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 e=$("#AddSomeone_Name").val();if(null!=e&&""!==e.trim())if(/^[A-Za-z0-9\s\-\'\[\]\(\)]+$/.test(e)){var t=$("#AddSomeone_Desc").val();if(null!=t&&""!==t.trim())if(/^[A-Za-z0-9\s\-\.\'\"\[\]\(\)\{\}\_\!\?\~\@\%\^\&\*\+\>\<\;\:\=]+$/.test(t))var i=t;else{i="";alert("The title/description that you entered is not valid!")}else i="";var n=$("#AddSomeone_Exten").val();if(null!=n&&""!==n.trim())if(/^[a-zA-Z0-9\*\#]+$/.test(n))var a=n;else{a="";alert("The extension that you entered in the 'Extension (Internal)' field is not a valid extension!")}else a="";var o=$("#AddSomeone_Mobile").val();if(null!=o&&""!==o.trim())if(/^[0-9\s\+\#]+$/.test(o))var l=o;else{l="";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 l="";var s=$("#AddSomeone_Num1").val();if(null!=s&&""!==s.trim())if(/^[0-9\s\+\#]+$/.test(s))var r=s;else{r="";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 r="";var d=$("#AddSomeone_Num2").val();if(null!=d&&""!==d.trim())if(/^[0-9\s\+\#]+$/.test(d))var c=d;else{c="";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 c="";var u=$("#AddSomeone_Email").val();if(null!=u&&""!==u.trim())if(/^[A-Za-z0-9\_\.\-\~\%\+\!\?\&\*\^\=\#\$\{\}\|\/]+@[A-Za-z0-9\.\-]+\.[A-Za-z0-9\-]{2,63}$/.test(u))var p=u;else{p="";alert("The email that you entered is not a valid email address!")}else p="";var g=JSON.parse(localDB.getItem(profileUserID+"-Buddies"));if(null==g&&(g=InitUserBuddies()),""==a){var m=uID(),f=utcDateNow();g.DataCollection.push({Type:"contact",LastActivity:f,ExtensionNumber:"",MobileNumber:l,ContactNumber1:r,ContactNumber2:c,uID:null,cID:m,gID:null,DisplayName:e,Position:"",Description:i,Email:p,MemberCount:0});saveContactToSQLDB([e,i,"",l,r,c,p]),AddBuddy(new Buddy("contact",m,e,"",l,r,c,f,i,p),!1,!1,!1)}else{m=uID(),f=utcDateNow();g.DataCollection.push({Type:"extension",LastActivity:f,ExtensionNumber:a,MobileNumber:l,ContactNumber1:r,ContactNumber2:c,uID:m,cID:null,gID:null,DisplayName:e,Position:i,Description:"",Email:p,MemberCount:0});saveContactToSQLDB([e,i,a,l,r,c,p]),AddBuddy(new Buddy("extension",m,e,a,l,r,c,f,i,p),!1,!1,!0)}g.TotalRows=g.DataCollection.length,localDB.setItem(profileUserID+"-Buddies",JSON.stringify(g)),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 i=$(window).width()-12,n=$(window).height()-110;i<656||n<500?($.jeegoopopup.width(i).height(n),$.jeegoopopup.center(),$("#maximizeImg").hide(),$("#minimizeImg").hide()):($.jeegoopopup.width(640).height(500),$.jeegoopopup.center(),$("#minimizeImg").hide(),$("#maximizeImg").show()),$(window).resize((function(){i=$(window).width()-16,n=$(window).height()-110,$.jeegoopopup.center(),i<656||n<500?($.jeegoopopup.width(i).height(n),$.jeegoopopup.center(),$("#maximizeImg").hide(),$("#minimizeImg").hide()):($.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(i).height(n),$.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(e){"Escape"==e.key&&($.jeegoopopup.close(),$("#jg_popup_b").empty())}))}function CreateGroupWindow(){}function closeVideoAudio(){var e=$("#local-video-preview").get(0);try{e.srcObject.getTracks().forEach((function(e){e.stop()})),e.srcObject=null}catch(e){}try{window.SettingsMicrophoneStream.getTracks().forEach((function(e){e.stop()}))}catch(e){}window.SettingsMicrophoneStream=null;try{window.SettingsMicrophoneSoundMeter.stop()}catch(e){}window.SettingsMicrophoneSoundMeter=null;try{window.SettingsOutputAudio.pause()}catch(e){}window.SettingsOutputAudio=null;try{window.SettingsOutputStream.getTracks().forEach((function(e){e.stop()}))}catch(e){}window.SettingsOutputStream=null;try{window.SettingsOutputStreamMeter.stop()}catch(e){}return window.SettingsOutputStreamMeter=null,!0}function ConfigureExtensionWindow(){$("#settingsCMenu").hide(),$.jeegoopopup.close();var e='<div id="mainConfWindow">';e+="<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>",e+='<div id="mainRightConf">',e+='<div id="rightMainConfWindow">',e+='<div id="AccountHtml" class="settingsSubSection" style="display:block;">',e+="<div class=UiText>"+lang.asterisk_server_address+": *</div>",e+="<div><input id=Configure_Account_wssServer class=UiInputText type=text placeholder='"+lang.eg_asterisk_server_address+"' value='"+getDbItem("wssServer","")+"'></div>",e+="<div class=UiText>"+lang.websocket_port+": *</div>",e+="<div><input id=Configure_Account_WebSocketPort class=UiInputText type=text placeholder='"+lang.eg_websocket_port+"' value='"+getDbItem("WebSocketPort","")+"'></div>",e+="<div class=UiText>"+lang.websocket_path+": *</div>",e+="<div><input id=Configure_Account_ServerPath class=UiInputText type=text placeholder='"+lang.eg_websocket_path+"' value='"+getDbItem("ServerPath","")+"'></div>",e+="<div class=UiText>"+lang.display_name+": *</div>";var t='value="'+getDbItem("profileName","").replace("'","'")+'"';if(e+="<div><input id=Configure_Account_profileName class=UiInputText type=text placeholder='"+lang.eg_display_name+"' "+t+"></div>",e+="<div class=UiText>"+lang.sip_username+": *</div>",e+="<div><input id=Configure_Account_SipUsername class=UiInputText type=text placeholder='"+lang.eg_sip_username+"' value='"+getDbItem("SipUsername","")+"'></div>",e+="<div class=UiText>"+lang.sip_password+": *</div>",e+="<div><input id=Configure_Account_SipPassword class=UiInputText type=password placeholder='"+lang.eg_sip_password+"' value='"+getDbItem("SipPassword","")+"'></div>",e+="<div class=UiText>"+lang.stun_server+":</div>",e+="<div><input id=Configure_Account_StunServer class=UiInputText type=text placeholder='Eg: 123.123.123.123:8443' value='"+getDbItem("StunServer","")+"'></div>",e+='<p style="color:#363636;">* Required field.</p><br><br></div>',e+='<div id="AudioVideoHtml" class="settingsSubSection" style="display:none;">',e+="<div class=UiText>"+lang.speaker+":</div>",e+='<div style="text-align:center"><select id=playbackSrc style="width:100%"></select></div>',e+="<div class=Settings_VolumeOutput_Container><div id=Settings_SpeakerOutput class=Settings_VolumeOutput></div></div>",e+='<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>',e+="<br><div class=UiText>"+lang.ring_device+":</div>",e+='<div style="text-align:center"><select id=ringDevice style="width:100%"></select></div>',e+="<div class=Settings_VolumeOutput_Container><div id=Settings_RingerOutput class=Settings_VolumeOutput></div></div>",e+='<div><button class=on_white id=preview_ringer_play><i class="fa fa-play"></i></button></div>',e+="<br><div class=UiText>"+lang.microphone+":</div>",e+='<div style="text-align:center"><select id=microphoneSrc style="width:100%"></select></div>',e+="<div class=Settings_VolumeOutput_Container><div id=Settings_MicrophoneOutput class=Settings_VolumeOutput></div></div>",e+="<br><br><div><input type=checkbox id=Settings_AutoGainControl><label for=Settings_AutoGainControl> "+lang.auto_gain_control+"<label></div>",e+="<div><input type=checkbox id=Settings_EchoCancellation><label for=Settings_EchoCancellation> "+lang.echo_cancellation+"<label></div>",e+="<div><input type=checkbox id=Settings_NoiseSuppression><label for=Settings_NoiseSuppression> "+lang.noise_suppression+"<label></div>",e+="<br><div class=UiText>"+lang.camera+":</div>",e+='<div style="text-align:center"><select id=previewVideoSrc style="width:100%"></select></div>',e+="<br><div class=UiText>"+lang.frame_rate+":</div>",e+="<div class=pill-nav>",e+='<input name=Settings_FrameRate id=r40 type=radio value="2"><label class=radio_pill for=r40>2</label>',e+='<input name=Settings_FrameRate id=r41 type=radio value="5"><label class=radio_pill for=r41>5</label>',e+='<input name=Settings_FrameRate id=r42 type=radio value="10"><label class=radio_pill for=r42>10</label>',e+='<input name=Settings_FrameRate id=r43 type=radio value="15"><label class=radio_pill for=r43>15</label>',e+='<input name=Settings_FrameRate id=r44 type=radio value="20"><label class=radio_pill for=r44>20</label>',e+='<input name=Settings_FrameRate id=r45 type=radio value="25"><label class=radio_pill for=r45>25</label>',e+='<input name=Settings_FrameRate id=r46 type=radio value="30"><label class=radio_pill for=r46>30</label>',e+='<input name=Settings_FrameRate id=r47 type=radio value=""><label class=radio_pill for=r47><i class="fa fa-trash"></i></label>',e+="</div>",e+="<br><br><div class=UiText>"+lang.quality+":</div>",e+="<div class=pill-nav>",e+='<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>',e+='<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>',e+='<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>',e+='<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>',e+='<input name=Settings_Quality id=r34 type=radio value=""><label class=radio_pill for=r34><i class="fa fa-trash"></i></label>',e+="</div>",e+="<br><br><div class=UiText>"+lang.image_orientation+":</div>",e+="<div class=pill-nav>",e+='<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>',e+='<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>',e+="</div>",e+="<br><br><div class=UiText>"+lang.aspect_ratio+":</div>",e+="<div class=pill-nav>",e+='<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>',e+='<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>',e+='<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>',e+='<input name=Settings_AspectRatio id=r13 type=radio value=""><label class=radio_pill for=r13><i class="fa fa-trash"></i></label>',e+="</div>",e+="<br><br><div class=UiText>"+lang.preview+":</div>",e+='<div style="text-align:center; margin-top:10px"><video id="local-video-preview" class="previewVideo"></video></div>',e+="<br><div class=UiText>"+lang.video_conference_extension+":</div>",e+="<div><input id=Video_Conf_Extension class=UiInputText type=text placeholder='"+lang.video_conference_extension_example+"' value='"+getDbItem("VidConfExtension","")+"'></div>",e+="<br><div class=UiText>"+lang.video_conference_window_width+":</div>",e+="<div><input id=Video_Conf_Window_Width class=UiInputText type=text placeholder='"+lang.video_conf_window_width_explanation+"' value='"+getDbItem("VidConfWindowWidth","")+"'></div>","superadmin"==getDbItem("userrole","")){e+="<div id=confTableSection>"+lang.external_conf_users+"</div>",e+="<div class=confTable><table id=vidConfExternalTable>",e+="<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 i=0;i<getDbItem("externalUserConfElem","");i++)e+="<tr class=btnTableRow><td><input type=text class=extConfExtension name=extConfExtension value='"+getDbItem("extUserExtension-"+i,"")+"' disabled=\"disabled\" /></td><td><input type=password class=extConfExtensionPass name=extConfExtensionPass value='"+getDbItem("extUserExtensionPass-"+i,"")+"' disabled=\"disabled\"/></td><td><input type=text class=extConfExtensionLink name=extConfExtensionLink value='"+getDbItem("confAccessLink-"+i,"")+'\' /></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>';e+='<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>',e+="</table></div>",e+="<button id=add_New_External_User>Add External User</button>"}e+="<br><br></div>",e+='<div id="AppearanceHtml" class="settingsSubSection" style="display:none;">',e+='<div id=ImageCanvas style="width:150px; height:150px;"></div>',e+='<label for=fileUploader class=customBrowseButton style="margin-left: 200px; margin-top: -2px;">Select File</label>',e+="<div><input id=fileUploader type=file></div>",e+='<div style="margin-top: 50px"></div>',e+="</div>",e+='<div id="NotificationsHtml" class="settingsSubSection" style="display:none;">',e+="<div class=UiText>"+lang.notifications+":</div>",e+='<div id="notificationsCheck"><input type=checkbox id=Settings_Notifications><label for=Settings_Notifications> '+lang.enable_onscreen_notifications+"<label></div>",e+="</div>",e+='<div id="RoundcubeEmailHtml" class="settingsSubSection" style="display:none;">',e+="<div class=UiText>"+lang.email_integration+":</div>",e+='<div id="enableRCcheck"><input id=emailIntegration type=checkbox ><label for=emailIntegration> '+lang.enable_roundcube_integration+"<label></div>",e+="<div class=UiText>"+lang.roundcube_domain+":</div>",e+="<div><input id=RoundcubeDomain class=UiInputText type=text placeholder='Roundcube domain (Eg: mail.example.com).' value='"+getDbItem("rcDomain","")+"'></div>",e+="<div class=UiText>"+lang.roundcube_user+":</div>",e+="<div><input id=RoundcubeUser class=UiInputText type=text placeholder='Roundcube login user (Eg: john.doe@example.com or john_doe).' value='"+getDbItem("RoundcubeUser","")+"'></div>",e+="<div class=UiText>"+lang.roundcube_password+":</div>",e+="<div><input id=RoundcubePass class=UiInputText type=password placeholder='Roundcube login password.' value='"+getDbItem("RoundcubePass","")+"'></div>",e+="<div class=UiText>"+lang.rc_basic_auth_user+":</div>",e+="<div><input id=rcBasicAuthUser class=UiInputText type=text placeholder='If you have a Roundcube basic auth user, enter it here.' value='"+getDbItem("rcBasicAuthUser","")+"'></div>",e+="<div class=UiText>"+lang.rc_basic_auth_password+":</div>",e+="<div><input id=rcBasicAuthPass class=UiInputText type=password placeholder='If you have a Roundcube basic auth password, enter it here.' value='"+getDbItem("rcBasicAuthPass","")+"'></div>",e+="<br><br></div>",e+='<div id="ChangePasswordHtml" class="settingsSubSection" style="display:none;">',e+="<div class=UiText>"+lang.current_user_password+":</div>",e+="<div><input id=Current_User_Password class=UiInputText type=password placeholder='Enter your current Roundpin user password.' value=''></div>",e+="<div class=UiText>"+lang.new_user_password+":</div>",e+="<div><input id=New_User_Password class=UiInputText type=password placeholder='Enter your new Roundpin user password.' value=''></div>",e+="<div class=UiText>"+lang.repeat_new_user_password+":</div>",e+="<div><input id=Repeat_New_User_Password class=UiInputText type=password placeholder='Enter your new Roundpin user password again.' value=''></div><br>",e+="<div><input id=Save_New_User_Password type=button value='Save New Password' onclick='saveNewUserPassword()' ></div>",e+="<br><br></div>",e+='<div id="ChangeEmailHtml" class="settingsSubSection" style="display:none;">',e+="<div class=UiText>"+lang.current_user_email+":</div>",e+="<div><input id=Current_User_Email class=UiInputText type=text placeholder='Enter your current Roundpin email address.' value=''></div>",e+="<div class=UiText>"+lang.new_user_email+":</div>",e+="<div><input id=New_User_Email class=UiInputText type=text placeholder='Enter your new email address.' value=''></div>",e+="<div class=UiText>"+lang.repeat_new_user_email+":</div>",e+="<div><input id=Repeat_New_User_Email class=UiInputText type=text placeholder='Enter your new email address again.' value=''></div><br>",e+="<div><input id=Save_New_User_Email type=button value='Save New Email' onclick='saveNewUserEmail()' ></div>",e+="<br><br></div>",e+='<div id="CloseAccountHtml" class="settingsSubSection" style="display:none;">',e+="<div class=UiText>"+lang.if_you_want_to_close_account+":</div><br><br>",e+="<div><input id=Close_User_Account type=button value='Close User Account' onclick='closeUserAccount()' ></div>",e+="<br><br></div>",e+="</div></div></div>";$.jeegoopopup.open({title:"<span id=settingsTitle>Settings</span>",html:e,width:"520",height:"500",center:!0,scrolling:"no",skinClass:"jg_popup_basic",contentClass:"configPopup",overlay:!0,opacity:50,draggable:!0,resizable:!1,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('<table id=leftPanelSettings cellspacing=14 cellpadding=0 style="width:184px;margin-left:8px;margin-top:14px;font-size:15px;"><tr id=ConnectionSettingsRow><td class=SettingsSection>Connection Settings</td></tr><tr id=AudioAndVideoRow><td class=SettingsSection>Audio & Video</td></tr><tr id=ProfilePictureRow><td class=SettingsSection>Profile Picture</td></tr><tr id=NotificationsRow><td class=SettingsSection>Notifications</td></tr><tr id=RoundcubeEmailRow><td class=SettingsSection>Email Integration</td></tr><tr id=ChangePasswordRow><td class=SettingsSection>Change Password</td></tr><tr id=ChangeEmailRow><td class=SettingsSection>Change Email</td></tr><tr id=CloseAccountRow><td class=SettingsSection>Close Account</td></tr></table>'),1==getDbItem("useRoundcube","")?$("#emailIntegration").prop("checked",!0):$("#emailIntegration").prop("checked",!1),$("#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 n=$(window).width()-192,a=$(window).height()-98;n<520||a<500?($.jeegoopopup.width(n).height(a),$.jeegoopopup.center(),$("#maximizeImg").hide(),$("#minimizeImg").hide()):($.jeegoopopup.width(520).height(500),$.jeegoopopup.center(),$("#minimizeImg").hide(),$("#maximizeImg").show()),$(window).resize((function(){n=$(window).width()-192,a=$(window).height()-98,$.jeegoopopup.center(),n<520||a<500?($.jeegoopopup.width(n).height(a),$.jeegoopopup.center(),$("#maximizeImg").hide(),$("#minimizeImg").hide()):($.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(n).height(a),$.jeegoopopup.center(),$("#minimizeImg").show(),$("#maximizeImg").hide()}));var o=$("#playbackSrc"),l=$("#preview_output_play"),s=$("#preview_ringer_play"),r=$("#preview_output_pause"),d=$("#microphoneSrc");$("#Settings_AutoGainControl").prop("checked",AutoGainControl),$("#Settings_EchoCancellation").prop("checked",EchoCancellation),$("#Settings_NoiseSuppression").prop("checked",NoiseSuppression);var c=$("#previewVideoSrc"),u=$("input[name=Settings_Oriteation]");u.each((function(){this.value==MirrorVideo&&$(this).prop("checked",!0)})),$("#local-video-preview").css("transform",MirrorVideo);var p=$("input[name=Settings_FrameRate]");p.each((function(){this.value==maxFrameRate&&$(this).prop("checked",!0)}));var g=$("input[name=Settings_Quality]");g.each((function(){this.value==videoHeight&&$(this).prop("checked",!0)}));var m=$("input[name=Settings_AspectRatio]");m.each((function(){this.value==videoAspectRatio&&$(this).prop("checked",!0)}));$("#ringTone");var f=$("#ringDevice");m.change((function(){console.log("Call to change Aspect Ratio ("+this.value+")");var e=$("#local-video-preview").get(0);e.muted=!0,e.playsinline=!0,e.autoplay=!0,e.srcObject.getTracks().forEach((function(e){e.stop()}));var t={audio:!1,video:{deviceId:"default"!=c.val()?{exact:c.val()}:"default"}};""!=$("input[name=Settings_FrameRate]:checked").val()&&(t.video.frameRate=$("input[name=Settings_FrameRate]:checked").val()),""!=$("input[name=Settings_Quality]:checked").val()&&(t.video.height=$("input[name=Settings_Quality]:checked").val()),""!=this.value&&(t.video.aspectRatio=this.value),console.log("Constraints:",t);var i=new MediaStream;navigator.mediaDevices&&navigator.mediaDevices.getUserMedia(t).then((function(t){var n=t.getVideoTracks()[0];i.addTrack(n),e.srcObject=i,e.onloadedmetadata=function(t){e.play()}})).catch((function(e){console.error(e),AlertConfigExtWindow(lang.alert_error_user_media,lang.error)}))})),g.change((function(){console.log("Call to change Video Height ("+this.value+")");var e=$("#local-video-preview").get(0);e.muted=!0,e.playsinline=!0,e.autoplay=!0,e.srcObject.getTracks().forEach((function(e){e.stop()}));var t={audio:!1,video:{deviceId:"default"!=c.val()?{exact:c.val()}:"default"}};""!=$("input[name=Settings_FrameRate]:checked").val()&&(t.video.frameRate=$("input[name=Settings_FrameRate]:checked").val()),this.value&&(t.video.height=this.value),""!=$("input[name=Settings_AspectRatio]:checked").val()&&(t.video.aspectRatio=$("input[name=Settings_AspectRatio]:checked").val()),console.log("Constraints:",t);var i=new MediaStream;navigator.mediaDevices&&navigator.mediaDevices.getUserMedia(t).then((function(t){var n=t.getVideoTracks()[0];i.addTrack(n),e.srcObject=i,e.onloadedmetadata=function(t){e.play()}})).catch((function(e){console.error(e),AlertConfigExtWindow(lang.alert_error_user_media,lang.error)}))})),p.change((function(){console.log("Call to change Frame Rate ("+this.value+")");var e=$("#local-video-preview").get(0);e.muted=!0,e.playsinline=!0,e.autoplay=!0,e.srcObject.getTracks().forEach((function(e){e.stop()}));var t={audio:!1,video:{deviceId:"default"!=c.val()?{exact:c.val()}:"default"}};""!=this.value&&(t.video.frameRate=this.value),""!=$("input[name=Settings_Quality]:checked").val()&&(t.video.height=$("input[name=Settings_Quality]:checked").val()),""!=$("input[name=Settings_AspectRatio]:checked").val()&&(t.video.aspectRatio=$("input[name=Settings_AspectRatio]:checked").val()),console.log("Constraints:",t);var i=new MediaStream;navigator.mediaDevices&&navigator.mediaDevices.getUserMedia(t).then((function(t){var n=t.getVideoTracks()[0];i.addTrack(n),e.srcObject=i,e.onloadedmetadata=function(t){e.play()}})).catch((function(e){console.error(e),AlertConfigExtWindow(lang.alert_error_user_media,lang.error)}))})),d.change((function(){console.log("Call to change Microphone ("+this.value+")");try{window.SettingsMicrophoneStream.getTracks().forEach((function(e){e.stop()})),window.SettingsMicrophoneStream=null}catch(e){}try{soundMeter=window.SettingsMicrophoneSoundMeter,soundMeter.stop(),window.SettingsMicrophoneSoundMeter=null}catch(e){}var e={audio:{deviceId:{exact:this.value}},video:!1},t=new MediaStream;navigator.mediaDevices.getUserMedia(e).then((function(e){var i=e.getAudioTracks()[0];null!=i&&(t.addTrack(i),window.SettingsMicrophoneStream=t,window.SettingsMicrophoneSoundMeter=MeterSettingsOutput(t,"Settings_MicrophoneOutput","width",50))})).catch((function(e){console.log("Failed to getUserMedia",e)}))})),o.change((function(){console.log("Call to change Speaker ("+this.value+")");var e=window.SettingsOutputAudio;null!=e&&void 0!==e.sinkId&&e.setSinkId(this.value).then((function(){console.log("sinkId applied to audioObj:",this.value)})).catch((function(e){console.warn("Failed not apply setSinkId.",e)}))})),l.click((function(){try{window.SettingsOutputAudio.pause()}catch(e){}window.SettingsOutputAudio=null;try{window.SettingsOutputStream.getTracks().forEach((function(e){e.stop()}))}catch(e){}window.SettingsOutputStream=null;try{window.SettingsOutputStreamMeter.stop()}catch(e){}window.SettingsOutputStreamMeter=null,console.log("Audio:",audioBlobs.speaker_test.url);var e=new Audio(audioBlobs.speaker_test.blob);e.preload="auto",e.onplay=function(){var t=new MediaStream;if(void 0!==e.captureStream)t=e.captureStream();else{if(void 0!==e.mozCaptureStream)return;if(void 0===e.webkitCaptureStream)return void console.warn("Cannot display Audio Levels");t=e.webkitCaptureStream()}window.SettingsOutputStream=t,window.SettingsOutputStreamMeter=MeterSettingsOutput(t,"Settings_SpeakerOutput","width",50)},e.oncanplaythrough=function(t){void 0!==e.sinkId&&e.setSinkId(o.val()).then((function(){console.log("Set sinkId to:",o.val())})).catch((function(e){console.warn("Failed not apply setSinkId.",e)})),e.play().then((function(){})).catch((function(e){console.warn("Unable to play audio file",e)})),console.log("Playing sample audio file... ")},window.SettingsOutputAudio=e})),r.click((function(){window.SettingsOutputAudio.paused?window.SettingsOutputAudio.play():window.SettingsOutputAudio.pause()})),s.click((function(){try{window.SettingsRingerAudio.pause()}catch(e){}window.SettingsRingerAudio=null;try{window.SettingsRingerStream.getTracks().forEach((function(e){e.stop()}))}catch(e){}window.SettingsRingerStream=null;try{window.SettingsRingerStreamMeter.stop()}catch(e){}window.SettingsRingerStreamMeter=null,console.log("Audio:",audioBlobs.Ringtone.url);var e=new Audio(audioBlobs.Ringtone.blob);e.preload="auto",e.onplay=function(){var t=new MediaStream;if(void 0!==e.captureStream)t=e.captureStream();else{if(void 0!==e.mozCaptureStream)return;if(void 0===e.webkitCaptureStream)return void console.warn("Cannot display Audio Levels");t=e.webkitCaptureStream()}window.SettingsRingerStream=t,window.SettingsRingerStreamMeter=MeterSettingsOutput(t,"Settings_RingerOutput","width",50)},e.oncanplaythrough=function(t){void 0!==e.sinkId&&e.setSinkId(f.val()).then((function(){console.log("Set sinkId to:",f.val())})).catch((function(e){console.warn("Failed not apply setSinkId.",e)})),e.play().then((function(){})).catch((function(e){console.warn("Unable to play audio file",e)})),console.log("Playing sample audio file... ")},window.SettingsRingerAudio=e})),u.change((function(){console.log("Call to change Orientation ("+this.value+")"),$("#local-video-preview").css("transform",this.value)})),c.change((function(){console.log("Call to change WebCam ("+this.value+")");var e=$("#local-video-preview").get(0);e.muted=!0,e.playsinline=!0,e.autoplay=!0,e.srcObject.getTracks().forEach((function(e){e.stop()}));var t={audio:!1,video:{deviceId:"default"!=this.value?{exact:this.value}:"default"}};""!=$("input[name=Settings_FrameRate]:checked").val()&&(t.video.frameRate=$("input[name=Settings_FrameRate]:checked").val()),""!=$("input[name=Settings_Quality]:checked").val()&&(t.video.height=$("input[name=Settings_Quality]:checked").val()),""!=$("input[name=Settings_AspectRatio]:checked").val()&&(t.video.aspectRatio=$("input[name=Settings_AspectRatio]:checked").val()),console.log("Constraints:",t);var i=new MediaStream;navigator.mediaDevices&&navigator.mediaDevices.getUserMedia(t).then((function(t){var n=t.getVideoTracks()[0];i.addTrack(n),e.srcObject=i,e.onloadedmetadata=function(t){e.play()}})).catch((function(e){console.error(e),AlertConfigExtWindow(lang.alert_error_user_media,lang.error)}))})),$("#AudioAndVideoRow").click((function(){if($(".settingsSubSection").each((function(){$(this).css("display","none")})),$("#AudioVideoHtml").css("display","block"),$(".SettingsSection").each((function(){$(this).removeClass("selectedSettingsSection")})),$("#AudioAndVideoRow td").addClass("selectedSettingsSection"),0==videoAudioCheck){videoAudioCheck=1;var e=$("#local-video-preview").get(0);e.muted=!0,e.playsinline=!0,e.autoplay=!0;var t=new MediaStream,i=new MediaStream;navigator.mediaDevices?navigator.mediaDevices.enumerateDevices().then((function(n){for(var a=getVideoSrcID(),l=!1,s=getAudioSrcID(),r=!1,u=!1,p=!1,g=!1,m=0;m<n.length;++m)console.log("Found Device ("+n[m].kind+"): ",n[m].label),"audioinput"===n[m].kind?(u=!0,"default"!=s&&n[m].deviceId==s&&(r=!0)):"audiooutput"===n[m].kind?p=!0:"videoinput"===n[m].kind&&(g=!0,"default"!=a&&n[m].deviceId==a&&(l=!0));var v={audio:u,video:g};u&&(v.audio={deviceId:"default"},r&&(v.audio.deviceId={exact:s})),g&&(v.video={deviceId:"default"},l&&(v.video.deviceId={exact:a})),""!=$("input[name=Settings_FrameRate]:checked").val()&&(v.video.frameRate=$("input[name=Settings_FrameRate]:checked").val()),""!=$("input[name=Settings_Quality]:checked").val()&&(v.video.height=$("input[name=Settings_Quality]:checked").val()),""!=$("input[name=Settings_AspectRatio]:checked").val()&&(v.video.aspectRatio=$("input[name=Settings_AspectRatio]:checked").val()),console.log("Get User Media",v),navigator.mediaDevices.getUserMedia(v).then((function(n){var a=n.getVideoTracks().length>=1?n.getVideoTracks()[0]:null;g&&null!=a?(t.addTrack(a),e.srcObject=t,e.onloadedmetadata=function(t){e.play()}):console.warn("No video / webcam devices found. Video Calling will not be possible.");var o=n.getAudioTracks().length>=1?n.getAudioTracks()[0]:null;return u&&null!=o?(i.addTrack(o),window.SettingsMicrophoneStream=i,window.SettingsMicrophoneSoundMeter=MeterSettingsOutput(i,"Settings_MicrophoneOutput","width",50)):console.warn("No microphone devices found. Calling will not be possible."),$("#Settings_SpeakerOutput").css("width","0%"),p||(console.log("No speaker devices found, make sure one is plugged in."),$("#playbackSrc").hide(),$("#RingDeviceSection").hide()),navigator.mediaDevices.enumerateDevices()})).then((function(e){for(var t=0;t<e.length;++t){console.log("Found Device ("+e[t].kind+") Again: ",e[t].label,e[t].deviceId);var i=e[t],n=i.deviceId,a=i.label;a.indexOf("(")>0&&(a=a.substring(0,a.indexOf("("))),(l=$("<option/>")).prop("value",n),"audioinput"===i.kind?(l.text(""!=a?a:"Microphone"),getAudioSrcID()==n&&l.prop("selected",!0),d.append(l)):"audiooutput"===i.kind?(l.text(""!=a?a:"Speaker"),getAudioOutputID()==n&&l.prop("selected",!0),o.append(l),f.append(l.clone())):"videoinput"===i.kind&&(getVideoSrcID()==n&&l.prop("selected",!0),l.text(""!=a?a:"Webcam"),c.append(l))}var l;c.children("option").length>0&&((l=$("<option/>")).prop("value","default"),"default"!=getVideoSrcID()&&""!=getVideoSrcID()&&"null"!=getVideoSrcID()||l.prop("selected",!0),l.text("(Default)"),c.append(l))})).catch((function(e){console.error(e),AlertConfigExtWindow(lang.alert_error_user_media,lang.error)}))})).catch((function(e){console.error("Error getting Media Devices",e)})):AlertConfigExtWindow(lang.alert_error_user_media,lang.error)}}));var v=$("#Settings_Notifications");v.prop("checked",NotificationsActive),v.change((function(){this.checked&&"granted"!=Notification.permission&&(checkNotificationPromise()?Notification.requestPermission().then((function(e){console.log(e),HandleNotifyPermission(e)})):Notification.requestPermission((function(e){console.log(e),HandleNotifyPermission(e)})))})),$("#vidConfExternalTable").on("click",".saveExtConfExtension",(function(){if("Save"==$(this).val()){var e=$(this).closest("tr").find("input.extConfExtension").val(),t=$(this).closest("tr").find("input.extConfExtensionPass").val(),i=localDB.getItem("wssServer");""!=e&&""!=t?e.length<200&&t.length<400?/^[a-zA-Z0-9]+$/.test(e)?($.ajax({type:"POST",url:"save-update-external-user-conf.php",dataType:"JSON",data:{username:userName,exten_for_external:e,exten_for_ext_pass:t,wss_server:i,s_ajax_call:validateSToken},success:function(e){"The data has been successfully saved to the database !"==e.result?(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()):alert(e.result)},error:function(e){alert("An error occurred while trying to save the data to the database !")}}),$(this).closest('[class="btnTableRow"]').find('[class="extConfExtension"]').attr("disabled",!0),$(this).closest('[class="btnTableRow"]').find('[class="extConfExtensionPass"]').attr("disabled",!0),$(this).attr("value","Edit"),$(this).prop("title","Edit this row.")):alert("The extension should contain only numbers and letters."):alert("The extension and/or the SIP password don't have a reasonable length."):alert('Please fill in both the "Extension" and the "SIP Password" fields !')}else $(this).closest('[class="btnTableRow"]').find('[class="extConfExtension"]').attr("disabled",!1),$(this).closest('[class="btnTableRow"]').find('[class="extConfExtensionPass"]').attr("disabled",!1),$(this).attr("value","Save"),$(this).prop("title","Save this row.")})),$("#vidConfExternalTable").on("click",".deleteExtRow",(function(){var e=$(this).closest('[class="btnTableRow"]').find('[class="extConfExtension"]').val();""!=e&&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:e,s_ajax_call:validateSToken},success:function(e){$(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(e){alert("An error occurred while trying to remove the data !")}}),$(this).closest('[class="btnTableRow"]').hide())})),$(".copyToClipboard").mouseenter((function(){""!=$(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 e=$("<input>");$("body").append(e),e.val($(this).closest('[class="btnTableRow"]').find('[class="extConfExtensionLink"]').val()).select(),document.execCommand("Copy"),e.remove(),alert("The link has been copied to your clipboard!")}}));var h=getDbItem("externalUserConfElem","");"undefined"!==h&&"null"!=h&&0!=h&&$("#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>')})),cropper=$("#ImageCanvas").croppie({viewport:{width:150,height:150,type:"circle"}}),$("#ImageCanvas").croppie("bind",{url:getPicture("profilePicture")}).then((function(){$(".cr-slider").attr({min:.5,max:3})})),$("#fileUploader").change((function(){var e=$(this).prop("files");if(1==e.length){var t=Math.floor(1e9*Math.random()),i=e[0],n=i.name,a=i.size;if(a<=52428800){console.log("Adding ("+t+"): "+n+" of size: "+a+"bytes");var o=new FileReader;o.Name=n,o.UploadId=t,o.Size=a,o.onload=function(e){$("#ImageCanvas").croppie("bind",{url:e.target.result})},o.readAsDataURL(i)}else Alert(lang.alert_file_size,lang.error)}else Alert(lang.alert_single_file,lang.error)})),$("#save_button_conf").click((function(){null==localDB.getItem("profileUserID")&&localDB.setItem("profileUserID",uID());var e=$("#Configure_Account_wssServer").val();if(/^[A-Za-z0-9\.\-]+\.[A-Za-z0-9\-]{2,63}$/.test(e))var t=e;else{t="";alert("The WebSocket domain that you entered is not a valid domain name!")}var i=$("#Configure_Account_WebSocketPort").val();if(/^[0-9]+$/.test(i))var n=i;else{n="";alert("The web socket port that you entered is not a valid port!")}var a=$("#Configure_Account_ServerPath").val();if(/^[A-Za-z0-9\/]+$/.test(a))var o=a;else{o="";alert("The server path that you entered is not a valid server path!")}var l=$("#Configure_Account_profileName").val();if(/^[A-Za-z0-9\s\-\'\[\]\(\)]+$/.test(l))var s=l;else{s="";alert("The profile name that you entered is not a valid profile name!")}var r=$("#Configure_Account_SipUsername").val();if(/^[A-Za-z0-9\-\.\_\@\*\!\?\&\~\(\)\[\]]+$/.test(r))var d=r;else{d="";alert("The SIP username that you entered is not a valid SIP username!")}var c=$("#Configure_Account_SipPassword").val();if(c.length<400)var u=c;else{u="";alert("The SIP password that you entered is too long!")}var p=$("#Configure_Account_StunServer").val();if(null!=p&&""!==p.trim())if(/^(\d+\.\d+\.\d+\.\d+:\d+)$|^([A-Za-z0-9\.\-]+\.[A-Za-z0-9\-]{2,63}:\d+)/.test(p));else{alert("The domain or IP or port number of the STUN server is not valid!")}else;if(null!=t&&""!==t.trim()&&null!=n&&""!==n.trim()&&null!=o&&""!==o.trim()&&null!=s&&""!==s.trim()&&null!=d&&""!==d.trim()&&null!=u&&""!==u.trim()){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());var g=$("#Video_Conf_Extension").val();if(/^[a-zA-Z0-9\*\#]+$/.test(g))var m=g;else{m="";alert("The extension that you entered in the 'Video Conference Extension' field is not a valid extension!")}localDB.setItem("VidConfExtension",m);var f=$("#Video_Conf_Window_Width").val();if(/^[0-9]+$/.test(f)&&Math.abs(f)<=100)var v=Math.abs(f);else{v="";alert("The percent value that you entered in the 'Percent of screen width ...' field is not valid!")}if(localDB.setItem("VidConfWindowWidth",v),localDB.setItem("Notifications",$("#Settings_Notifications").is(":checked")?"1":"0"),$("#emailIntegration").is(":checked")){if(!/^[A-Za-z0-9\.\-]+\.[A-Za-z0-9\-]{2,63}$/.test($("#RoundcubeDomain").val()))return $("#emailIntegration").prop("checked",!1),$("#RoundcubeDomain").val(""),void alert("The Roundcube domain is not valid. After entering a valid Roundcube domain, please remember to check the checkbox 'Enable Roundcube email integration' again !");if(!/^[A-Za-z0-9\_\.\-\@\~\%\+\!\?\&\*\^\=\#\$\{\}\|\/]{1,300}$/.test($("#RoundcubeUser").val()))return $("#emailIntegration").prop("checked",!1),$("#RoundcubeUser").val(""),void alert("The Roundcube user is not valid. After entering a valid Roundcube user, please remember to check the checkbox 'Enable Roundcube email integration' again !");if(""==$("#RoundcubePass").val()||$("#RoundcubePass").val().length>300)return $("#emailIntegration").prop("checked",!1),$("#RoundcubePass").val(""),void alert("The Roundcube password is not valid. After entering a valid Roundcube password, please remember to check the checkbox 'Enable Roundcube email integration' again !");if($("#rcBasicAuthUser").val().length>300)return $("#rcBasicAuthUser").val(""),void alert("The Roundcube basic authentication user is not valid.");if($("#rcBasicAuthPass").val().length>300)return $("#rcBasicAuthPass").val(""),void alert("The Roundcube basic authentication password is not valid.")}$("#AppearanceHtml").css({display:"block",visibility:"hidden","margin-top":"-228px"}),$("#ImageCanvas").croppie("result",{type:"base64",size:"viewport",format:"png",quality:1,circle:!1}).then((function(e){localDB.setItem("profilePicture",e)})),setTimeout((function(){saveConfToSqldb()}),600)}else alert("All fields marked with an asterisk are required!")})),$("#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(e){"Escape"==e.key&&($("#jg_popup_b").empty(),$("#jg_popup_l").empty(),$("#windowCtrls").empty(),closeVideoAudio(),$.jeegoopopup.close())}))}function checkNotificationPromise(){try{Notification.requestPermission().then()}catch(e){return!1}return!0}function HandleNotifyPermission(e){"granted"==e||Alert(lang.alert_notification_permission,lang.permission,(function(){console.log("Attempting to uncheck the checkbox..."),$("#Settings_Notifications").prop("checked",!1)}))}function EditBuddyWindow(e){$.jeegoopopup.close();var t=null,i=-1,n=JSON.parse(localDB.getItem(profileUserID+"-Buddies"));if($.each(n.DataCollection,(function(n,a){if(a.uID==e||a.cID==e||a.gID==e)return t=a,i=n,!1})),null!=t){var a="<div id='EditContact'>";a+="<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>",a+="<div class='UiWindowField scroller'>",a+='<div id=ImageCanvas style="width:150px; height:150px"></div>',a+='<label for=ebFileUploader class=customBrowseButton style="margin-left: 200px; margin-top: -9px;">Select File</label>',a+="<div><input type=file id=ebFileUploader /></div>",a+='<div style="margin-top: 50px"></div>',a+="<div class=UiText>"+lang.display_name+":</div>",a+="<div><input id=AddSomeone_Name class=UiInputText type=text placeholder='"+lang.eg_display_name+"' value='"+(t.DisplayName&&"null"!=t.DisplayName&&"undefined"!=t.DisplayName?t.DisplayName:"")+"'></div>",a+="<div class=UiText>"+lang.title_description+":</div>","extension"==t.Type?a+="<div><input id=AddSomeone_Desc class=UiInputText type=text placeholder='"+lang.eg_general_manager+"' value='"+(t.Position&&"null"!=t.Position&&"undefined"!=t.Position?t.Position:"")+"'></div>":a+="<div><input id=AddSomeone_Desc class=UiInputText type=text placeholder='"+lang.eg_general_manager+"' value='"+(t.Description&&"null"!=t.Description&&"undefined"!=t.Description?t.Description:"")+"'></div>",a+="<div class=UiText>"+lang.internal_subscribe_extension+":</div>",a+="<div><input id=AddSomeone_Exten class=UiInputText type=text placeholder='"+lang.eg_internal_subscribe_extension+"' value='"+(t.ExtensionNumber&&"null"!=t.ExtensionNumber&&"undefined"!=t.ExtensionNumber?t.ExtensionNumber:"")+"'></div>",a+="<div class=UiText>"+lang.mobile_number+":</div>",a+="<div><input id=AddSomeone_Mobile class=UiInputText type=text placeholder='"+lang.eg_mobile_number+"' value='"+(t.MobileNumber&&"null"!=t.MobileNumber&&"undefined"!=t.MobileNumber?t.MobileNumber:"")+"'></div>",a+="<div class=UiText>"+lang.contact_number_1+":</div>",a+="<div><input id=AddSomeone_Num1 class=UiInputText type=text placeholder='"+lang.eg_contact_number_1+"' value='"+(t.ContactNumber1&&"null"!=t.ContactNumber1&&"undefined"!=t.ContactNumber1?t.ContactNumber1:"")+"'></div>",a+="<div class=UiText>"+lang.contact_number_2+":</div>",a+="<div><input id=AddSomeone_Num2 class=UiInputText type=text placeholder='"+lang.eg_contact_number_2+"' value='"+(t.ContactNumber2&&"null"!=t.ContactNumber2&&"undefined"!=t.ContactNumber2?t.ContactNumber2:"")+"'></div>",a+="<div class=UiText>"+lang.email+":</div>",a+="<div><input id=AddSomeone_Email class=UiInputText type=text placeholder='"+lang.email+"' value='"+(t.Email&&"null"!=t.Email&&"undefined"!=t.Email?t.Email:"")+"'></div>",a+="</div></div>",$.jeegoopopup.open({title:"Edit Contact",html:a,width:"640",height:"500",center:!0,scrolling:"no",skinClass:"jg_popup_basic",contentClass:"editContactPopup",overlay:!0,opacity:50,draggable:!0,resizable:!1,fadeIn:0}),$("#jg_popup_b").append("<div id=bottomButtons><button id=save_button>Save</button><button id=cancel_button>Cancel</button></div>");var o="";$.ajax({type:"POST",url:"get-contact-dbid.php",dataType:"JSON",data:{username:userName,contact_name:t.DisplayName,s_ajax_call:validateSToken},success:function(e){"success"==e.successorfailure?o=e.cntctDatabaseID:alert("Error while attempting to retrieve contact data from the database!")},error:function(e){alert("Error while attempting to retrieve contact data from the database!")}});$("#ImageCanvas").croppie({viewport:{width:150,height:150,type:"circle"}});"extension"==t.Type?$("#ImageCanvas").croppie("bind",{url:getPicture(t.uID,"extension")}).then((function(){$(".cr-slider").attr({min:.5,max:3})})):"contact"==t.Type?$("#ImageCanvas").croppie("bind",{url:getPicture(t.cID,"contact")}).then((function(){$(".cr-slider").attr({min:.5,max:3})})):"group"==t.Type&&$("#ImageCanvas").croppie("bind",{url:getPicture(t.gID,"group")}).then((function(){$(".cr-slider").attr({min:.5,max:3})})),$("#ebFileUploader").change((function(){var e=$(this).prop("files");if(1==e.length){var t=Math.floor(1e9*Math.random()),i=e[0],n=i.name,a=i.size;if(a<=52428800){console.log("Adding ("+t+"): "+n+" of size: "+a+"bytes");var o=new FileReader;o.Name=n,o.UploadId=t,o.Size=a,o.onload=function(e){$("#ImageCanvas").croppie("bind",{url:e.target.result})},o.readAsDataURL(i)}else Alert(lang.alert_file_size,lang.error)}else Alert(lang.alert_single_file,lang.error)})),$("#save_button").click((function(){var e=$("#AddSomeone_Name").val();if(null!=e&&""!==e.trim())if(/^[A-Za-z0-9\s\-\'\[\]\(\)]+$/.test(e)){t.LastActivity=utcDateNow(),t.DisplayName=e;var a=$("#AddSomeone_Desc").val();if(null!=a&&""!==a.trim())if(/^[A-Za-z0-9\s\-\.\'\"\[\]\(\)\{\}\_\!\?\~\@\%\^\&\*\+\>\<\;\:\=]+$/.test(a))var l=a;else{l="";alert("The title/description that you entered is not valid!")}else l="";"extension"==t.Type?t.Position=l:t.Description=l;var s=$("#AddSomeone_Exten").val();if(null!=s&&""!==s.trim())if(/^[a-zA-Z0-9\*\#]+$/.test(s))var r=s;else{r="";alert("The extension that you entered in the 'Extension (Internal)' field is not a valid extension!")}else r="";t.ExtensionNumber=r;var d=$("#AddSomeone_Mobile").val();if(null!=d&&""!==d.trim())if(/^[0-9\s\+\#]+$/.test(d))var c=d;else{c="";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 c="";t.MobileNumber=c;var u=$("#AddSomeone_Num1").val();if(null!=u&&""!==u.trim())if(/^[0-9\s\+\#]+$/.test(u))var p=u;else{p="";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 p="";t.ContactNumber1=p;var g=$("#AddSomeone_Num2").val();if(null!=g&&""!==g.trim())if(/^[0-9\s\+\#]+$/.test(g))var m=g;else{m="";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 m="";t.ContactNumber2=m;var f=$("#AddSomeone_Email").val();if(null!=f&&""!==f.trim())if(/^[A-Za-z0-9\_\.\-\~\%\+\!\?\&\*\^\=\#\$\{\}\|\/]+@[A-Za-z0-9\.\-]+\.[A-Za-z0-9\-]{2,63}$/.test(f))var v=f;else{v="";alert("The email that you entered is not a valid email address!")}else v="";t.Email=v;$("#ImageCanvas").croppie("result",{type:"base64",size:"viewport",format:"png",quality:1,circle:!1}).then((function(e){if("extension"==t.Type){localDB.setItem("img-"+t.uID+"-extension",e),$("#contact-"+t.uID+"-picture-main").css("background-image","url("+getPicture(t.uID,"extension")+")"),$("#contact-"+t.uID+"-presence-main").html(t.Position);saveContactPicToSQLDB([t.DisplayName,localDB.getItem("img-"+t.uID+"-extension",e)])}else if("contact"==t.Type){localDB.setItem("img-"+t.cID+"-contact",e),$("#contact-"+t.cID+"-picture-main").css("background-image","url("+getPicture(t.cID,"contact")+")"),$("#contact-"+t.cID+"-presence-main").html(t.Description);saveContactPicToSQLDB([t.DisplayName,localDB.getItem("img-"+t.cID+"-contact",e)])}else if("group"==t.Type){localDB.setItem("img-"+t.gID+"-group",e),$("#contact-"+t.gID+"-picture-main").css("background-image","url("+getPicture(t.gID,"group")+")"),$("#contact-"+t.gID+"-presence-main").html(t.Description);saveContactPicToSQLDB([t.DisplayName,localDB.getItem("img-"+t.gID+"-group",e)])}UpdateBuddyList()})),n.DataCollection[i]=t,localDB.setItem(profileUserID+"-Buddies",JSON.stringify(n));updateContactToSQLDB([e,l,r,c,p,m,v,o]);for(var h=0;h<Buddies.length;h++)"extension"==t.Type?t.uID==Buddies[h].identity&&(Buddies[h].lastActivity=t.LastActivity,Buddies[h].CallerIDName=t.DisplayName,Buddies[h].Desc=t.Position):"contact"==t.Type?t.cID==Buddies[h].identity&&(Buddies[h].lastActivity=t.LastActivity,Buddies[h].CallerIDName=t.DisplayName,Buddies[h].Desc=t.Description):t.Type;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 l=$(window).width()-16,s=$(window).height()-110;l<656||s<500?($.jeegoopopup.width(l).height(s),$.jeegoopopup.center(),$("#maximizeImg").hide(),$("#minimizeImg").hide()):($.jeegoopopup.width(640).height(500),$.jeegoopopup.center(),$("#minimizeImg").hide(),$("#maximizeImg").show()),$(window).resize((function(){l=$(window).width()-16,s=$(window).height()-110,$.jeegoopopup.center(),l<656||s<500?($.jeegoopopup.width(l).height(s),$.jeegoopopup.center(),$("#maximizeImg").hide(),$("#minimizeImg").hide()):($.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(l).height(s),$.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(e){"Escape"==e.key&&($.jeegoopopup.close(),$("#jg_popup_b").empty())}))}else Alert(lang.alert_not_found,lang.error)}function InitUi(){var e=$("#Phone");e.empty(),e.attr("class","pageContainer");var t=$("<div>");t.attr("id","leftContent"),t.attr("style","float:left; height: 100%; width:320px");var i='<table style="height:100%; width:100%" cellspacing=5 cellpadding=0>';i+='<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>',i+='<tr><td class=streamSection style="height: 82px">',i+="<div class=profileContainer>",i+='<div class=contact id=UserProfile style="margin-bottom:12px;">',i+='<div id=UserProfilePic class=buddyIcon title="Status"></div>',i+="<span id=reglink class=dotOffline></span>",i+='<span id=dereglink class=dotOnline style="display:none"><i class="fa fa-wifi" style="line-height: 14px; text-align: center; display: block;"></i></span>',i+='<span id=WebRtcFailed class=dotFailed style="display:none"><i class="fa fa-cross" style="line-height: 14px; text-align: center; display: block;"></i></span>',i+='<div class=contactNameText style="margin-right: 0px;"><i class="fa fa-phone-square"></i> <span id=UserDID></span> - <span id=UserCallID></span></div>',i+="<div id=regStatus class=presenceText>&nbsp;</div>",i+="</div>",i+="<div id=searchBoxAndIcons>",i+='<span class=searchClean><INPUT id=txtFindBuddy type=text autocomplete=none style="width:142px;" title="Find Contact"></span>',i+="<div id=ButtonsOnSearchLine>",i+="<button id=BtnFreeDial title='"+lang.dial_number+"'></button>",i+="<button id=LaunchVideoConf title='"+lang.launch_video_conference+'\'><i class="fa fa-users"></i></button>',i+="<button id=BtnSettings title='"+lang.account_settings+'\'><i class="fa fa-cog"></i></button>',i+="</div>",i+="</div>",i+="</div>",i+="</td></tr>",i+='<tr><td class=streamSection><div id=myContacts class="contactArea cleanScroller"></div></td></tr>',i+="</table>",t.html(i);var n=$("<div>");n.attr("id","rightContent"),n.attr("style","margin-left: 320px; height: 100%; overflow: auto;"),e.append(t),e.append(n),windowsCollection="",messagingCollection="",1==DisableFreeDial&&$("#BtnFreeDial").hide(),1==DisableBuddies&&$("#BtnAddSomeone").hide(),0==enabledGroupServices&&$("#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(e){UpdateBuddyList()})),$("#BtnFreeDial").on("click",(function(e){ShowDial(this)})),$("#BtnAddSomeone").attr("title",lang.add_contact),$("#BtnAddSomeone").on("click",(function(e){AddSomeoneWindow()})),$("#BtnCreateGroup").attr("title",lang.create_group),$("#BtnCreateGroup").on("click",(function(e){CreateGroupWindow()})),$("#LaunchVideoConf").on("click",(function(e){ShowLaunchVidConfMenu(this)})),$("#BtnSettings").on("click",(function(e){ShowAccountSettingsMenu(this)})),$("#UserProfile").on("click",(function(e){ShowMyProfileMenu(this)})),UpdateUI(),PopulateBuddyList(),null!=localDB.getItem("SelectedBuddy")&&(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(e,t){var i=new XMLHttpRequest;i.open("GET",t.url,!0),i.responseType="blob",i.onload=function(e){var n=new FileReader;n.readAsDataURL(i.response),n.onload=function(){t.blob=n.result}},i.send()}))}function CreateUserAgent(){$.ajax({async:!1,global:!1,type:"POST",url:"get-sippass.php",dataType:"JSON",data:{username:userName,s_ajax_call:validateSToken},success:function(e){decSipPass=e},error:function(e){alert("An error occurred while attempting to retrieve data from the database!")}});try{console.log("Creating User Agent...");var e={displayName:profileName,uri:SipUsername+"@"+wssServer,transportOptions:{wsServers:"wss://"+wssServer+":"+WebSocketPort+ServerPath,traceSip:!1,connectionTimeout:TransportConnectionTimeout,maxReconnectionAttempts:TransportReconnectionAttempts,reconnectionTimeout:TransportReconnectionTimeout},sessionDescriptionHandlerFactoryOptions:{peerConnectionOptions:{alwaysAcquireMediaFirst:!0,iceCheckingTimeout:IceStunCheckTimeout,rtcConfiguration:{}}},authorizationUser:SipUsername,password:decSipPass,registerExpires:RegisterExpires,hackWssInTransport:WssInTransport,hackIpInContact:IpInContact,userAgentString:userAgentStr,autostart:!1,register:!1};decSipPass="";var t=getDbItem("StunServer","");if(""==t||null==t||void 0===t)var i="";else i='[{"urls":"stun:'+t+'"}]';""!=i&&(e.sessionDescriptionHandlerFactoryOptions.peerConnectionOptions.rtcConfiguration.iceServers=JSON.parse(i)),userAgent=new SIP.UA(e),console.log("Creating User Agent... Done")}catch(e){return console.error("Error creating User Agent: "+e),$("#regStatus").html(lang.error_user_agant),void alert(e.message)}userAgent.on("registered",(function(){isReRegister||(console.log("Registered!"),$("#reglink").hide(),$("#dereglink").show(),(DoNotDisturbEnabled||"enabled"==DoNotDisturbPolicy)&&$("#dereglink").attr("class","dotDoNotDisturb"),SubscribeAll(),$("#regStatus").html(lang.registered),"undefined"!=typeof web_hook_on_register&&web_hook_on_register(userAgent)),isReRegister=!0})),userAgent.on("registrationFailed",(function(e,t){console.log("Registration Failed: "+t),$("#regStatus").html(lang.registration_failed),$("#reglink").show(),$("#dereglink").hide(),isReRegister=!1,"undefined"!=typeof web_hook_on_registrationFailed&&web_hook_on_registrationFailed(t)})),userAgent.on("unregistered",(function(){console.log("Unregistered, bye!"),$("#regStatus").html(lang.unregistered),$("#reglink").show(),$("#dereglink").hide(),"undefined"!=typeof web_hook_on_unregistered&&web_hook_on_unregistered()})),userAgent.on("transportCreated",(function(e){console.log("Transport Object Created"),e.on("connected",(function(){console.log("Connected to Web Socket!"),$("#regStatus").html(lang.connected_to_web_socket),$("#WebRtcFailed").hide(),window.setTimeout((function(){Register()}),500)})),e.on("disconnected",(function(){console.log("Disconnected from Web Socket!"),$("#regStatus").html(lang.disconnected_from_web_socket),isReRegister=!1})),e.on("transportError",(function(){console.log("Web Socket error!"),$("#regStatus").html(lang.web_socket_error),$("#WebRtcFailed").show(),"undefined"!=typeof web_hook_on_transportError&&web_hook_on_transportError(e,userAgent)}))})),userAgent.on("invite",(function(e){ReceiveCall(e),1==getDbItem("Notifications","")&&incomingCallNote(),changePageTitle(),"undefined"!=typeof web_hook_on_invite&&web_hook_on_invite(e)})),userAgent.on("message",(function(e){ReceiveMessage(e),"undefined"!=typeof web_hook_on_message&&web_hook_on_message(e)})),console.log("Connecting to Web Socket..."),$("#regStatus").html(lang.connecting_to_web_socket),userAgent.start(),$("#reglink").on("click",Register),$("#WebRtcFailed").on("click",(function(){Confirm(lang.error_connecting_web_socket,lang.web_socket_error,(function(){window.open("https://"+wssServer+":"+WebSocketPort+"/httpstatus")}),null)}))}function Register(){null==userAgent||userAgent.isRegistered()||(console.log("Sending Registration..."),$("#regStatus").html(lang.sending_registration),userAgent.register(),1==getDbItem("Notifications","")&&"granted"!=Notification.permission&&Notification.requestPermission())}function Unregister(){if(null!=userAgent&&userAgent.isRegistered()){console.log("Unsubscribing..."),$("#regStatus").html(lang.unsubscribing);try{UnsubscribeAll()}catch(e){}console.log("Disconnecting..."),$("#regStatus").html(lang.disconnecting),userAgent.unregister(),isReRegister=!1}}function ReceiveCall(e){var t=e.remoteIdentity.displayName,i=e.remoteIdentity.uri.user;void 0===t&&(t=""),console.log("New Incoming Call!",t+" <"+i+">");var n=countSessions(e.id);console.log("Current Call Count:",n);var a=FindBuddyByDid(i);if(null==a){var o=i.length>DidLength?"contact":"extension";a=MakeBuddy(o,!0,0==n,!0,t,i)}else("extension"==a.type&&a.CallerIDName!=t||"contact"==a.type&&t!=i&&a.CallerIDName!=t)&&UpdateBuddyCalerID(a,t);var l=a.identity;window.clearInterval(e.data.callTimer);var s=moment.utc();e.data.callstart=s.format("YYYY-MM-DD HH:mm:ss UTC"),$("#contact-"+l+"-timer").show(),e.data.callTimer=window.setInterval((function(){var e=moment.utc(),t=moment.duration(e.diff(s));$("#contact-"+l+"-timer").html(formatShortDuration(t.asSeconds()))}),1e3),e.data.buddyId=l,e.data.calldirection="inbound",e.data.terminateby="them",e.data.withvideo=!1;var r,d=!1;if(e.request.body&&e.request.body.indexOf("m=video")>-1&&(d=!0,"contact"==a.type&&(d=!1)),e.on("rejected",(function(t,i){console.log("Call rejected: "+i),e.data.reasonCode=t.status_code,e.data.reasonText=i,AddCallMessage(l,e,t.status_code,i),"undefined"!=typeof web_hook_on_terminate&&web_hook_on_terminate(e)})),e.on("terminated",(function(t,i){e.data.rinngerObj&&(e.data.rinngerObj.pause(),e.data.rinngerObj.removeAttribute("src"),e.data.rinngerObj.load(),e.data.rinngerObj=null),$.jeegoopopup.close(),console.log("Call terminated"),window.clearInterval(e.data.callTimer),$("#contact-"+l+"-timer").html(""),$("#contact-"+l+"-timer").hide(),$("#contact-"+l+"-msg").html(""),$("#contact-"+l+"-msg").hide(),$("#contact-"+l+"-AnswerCall").hide(),RefreshStream(a),updateScroll(a.identity),UpdateBuddyList()})),DoNotDisturbEnabled||"enabled"==DoNotDisturbPolicy)return console.log("Do Not Disturb Enabled, rejecting call."),void RejectCall(a.identity);if(n>=1&&(0==CallWaitingEnabled||"disabled"==CallWaitingEnabled))return console.log("Call Waiting Disabled, rejecting call."),void RejectCall(a.identity);if(AutoAnswerEnabled||"enabled"==AutoAnswerPolicy){if(0==n){console.log("Auto Answer Call...");var c=a.identity;return window.setTimeout((function(){d?AnswerVideoCall(c):AnswerAudioCall(c)}),1e3),void SelectBuddy(a.identity)}console.warn("Could not auto answer call, already on a call.")}($("#contact-"+a.identity+"-msg").html(lang.incomming_call_from+" "+t+" &lt;"+i+"&gt;"),$("#contact-"+a.identity+"-msg").show(),d?$("#contact-"+a.identity+"-answer-video").show():$("#contact-"+a.identity+"-answer-video").hide(),$("#contact-"+a.identity+"-AnswerCall").show(),updateScroll(a.identity),n>=1)?(console.log("Audio:",audioBlobs.CallWaiting.url),(r=new Audio(audioBlobs.CallWaiting.blob)).preload="auto",r.loop=!1,r.oncanplaythrough=function(e){void 0!==r.sinkId&&"default"!=getRingerOutputID()&&r.setSinkId(getRingerOutputID()).then((function(){console.log("Set sinkId to:",getRingerOutputID())})).catch((function(e){console.warn("Failed not apply setSinkId.",e)})),r.play().then((function(){})).catch((function(e){console.warn("Unable to play audio file.",e)}))},e.data.rinngerObj=r):(console.log("Audio:",audioBlobs.Ringtone.url),(r=new Audio(audioBlobs.Ringtone.blob)).preload="auto",r.loop=!0,r.oncanplaythrough=function(e){void 0!==r.sinkId&&"default"!=getRingerOutputID()&&r.setSinkId(getRingerOutputID()).then((function(){console.log("Set sinkId to:",getRingerOutputID())})).catch((function(e){console.warn("Failed not apply setSinkId.",e)})),r.play().then((function(){})).catch((function(e){console.warn("Unable to play audio file.",e)}))},e.data.rinngerObj=r);$.jeegoopopup.close();var u='<div id="windowCtrls"><img id="closeImg" src="images/3_close.svg" title="Close" /></div>';if(u+='<div class="UiWindowField scroller" style="text-align:center">',u+='<div style="font-size: 18px; margin-top:1px">'+t+"<div>",t!=i&&(u+='<div style="font-size: 18px; margin-top:1px">&lt;'+i+"&gt;<div>"),u+='<div class=callAnswerBuddyIcon style="background-image: url('+getPicture(a.identity)+'); margin-top:6px"></div>',u+='<div style="margin-top:14px"><button onclick="AnswerAudioCall(\''+a.identity+'\')" class=answerButton><i class="fa fa-phone"></i>&nbsp;&nbsp;'+lang.answer_call+"</button></div>",d&&(u+='<div style="margin-top:11px"><button onclick="AnswerVideoCall(\''+a.identity+'\')" class=answerButton><i class="fa fa-video-camera"></i>&nbsp;&nbsp;'+lang.answer_call_with_video+"</button></div>"),u+='<div style="margin-top:11px"><button onclick="RejectCall(\''+a.identity+'\')" class=hangupButton><i class="fa fa-phone"></i>&nbsp;&nbsp;'+lang.reject_call+"</button></div>",u+="</div>",$.jeegoopopup.open({title:"Incoming Call",html:u,width:"290",height:"300",center:!0,scrolling:"no",skinClass:"jg_popup_basic",overlay:!0,opacity:50,draggable:!0,resizable:!1,fadeIn:0}),$("#closeImg").click((function(){$.jeegoopopup.close()})),$("#jg_popup_overlay").click((function(){$.jeegoopopup.close()})),$(window).on("keydown",(function(e){"Escape"==e.key&&$.jeegoopopup.close()})),IncreaseMissedBadge(a.identity),"Notification"in window&&1==getDbItem("Notifications","")){var p={body:lang.incomming_call_from+" "+t+' "'+i+'"',icon:getPicture(a.identity)};new Notification(lang.incomming_call,p).onclick=function(e){var t=a.identity;window.setTimeout((function(){d?AnswerVideoCall(t):AnswerAudioCall(t)}),4e3),SelectBuddy(a.identity)}}}function AnswerAudioCall(e){$.jeegoopopup.close();var t=FindBuddyByIdentity(e);if(null==t)return console.warn("Audio Answer failed, null buddy"),$("#contact-"+e+"-msg").html(lang.call_failed),void $("#contact-"+e+"-AnswerCall").hide();var i=getSession(e);if(null==i)return console.warn("Audio Answer failed, null session"),$("#contact-"+e+"-msg").html(lang.call_failed),void $("#contact-"+e+"-AnswerCall").hide();if(i.data.rinngerObj&&(i.data.rinngerObj.pause(),i.data.rinngerObj.removeAttribute("src"),i.data.rinngerObj.load(),i.data.rinngerObj=null),0==HasAudioDevice)return Alert(lang.alert_no_microphone),$("#contact-"+e+"-msg").html(lang.call_failed),void $("#contact-"+e+"-AnswerCall").hide();$("#contact-"+e+"-timer").html(""),$("#contact-"+e+"-timer").hide(),$("#contact-"+e+"-msg").html(""),$("#contact-"+e+"-msg").hide(),$("#contact-"+e+"-AnswerCall").hide();var n=i.remoteIdentity.displayName,a=i.remoteIdentity.uri.user;newLineNumber+=1,lineObj=new Line(newLineNumber,n,a,t),lineObj.SipSession=i,lineObj.SipSession.data.line=lineObj.LineNumber,lineObj.SipSession.data.buddyId=lineObj.BuddyObj.identity,Lines.push(lineObj),AddLineHtml(lineObj),SelectLine(newLineNumber),UpdateBuddyList();var o=navigator.mediaDevices.getSupportedConstraints(),l={sessionDescriptionHandlerOptions:{constraints:{audio:{deviceId:"default"},video:!1}}},s=getAudioSrcID();if("default"!=s){for(var r=!1,d=0;d<AudioinputDevices.length;++d)if(s==AudioinputDevices[d].deviceId){r=!0;break}r?l.sessionDescriptionHandlerOptions.constraints.audio.deviceId={exact:s}:(console.warn("The audio device you used before is no longer available, default settings applied."),localDB.setItem("AudioSrcId","default"))}o.autoGainControl&&(l.sessionDescriptionHandlerOptions.constraints.audio.autoGainControl=AutoGainControl),o.echoCancellation&&(l.sessionDescriptionHandlerOptions.constraints.audio.echoCancellation=EchoCancellation),o.noiseSuppression&&(l.sessionDescriptionHandlerOptions.constraints.audio.noiseSuppression=NoiseSuppression),lineObj.SipSession.accept(l),lineObj.SipSession.data.withvideo=!1,lineObj.SipSession.data.VideoSourceDevice=null,lineObj.SipSession.data.AudioSourceDevice=getAudioSrcID(),lineObj.SipSession.data.AudioOutputDevice=getAudioOutputID(),wireupAudioSession(lineObj),$("#contact-"+e+"-msg").html(lang.call_in_progress),$("#contact-"+e+"-AnswerCall").hide()}function AnswerVideoCall(e){$.jeegoopopup.close();var t=FindBuddyByIdentity(e);if(null==t)return console.warn("Audio Answer failed, null buddy"),$("#contact-"+e+"-msg").html(lang.call_failed),void $("#contact-"+e+"-AnswerCall").hide();var i=getSession(e);if(null==i)return console.warn("Video Answer failed, null session"),$("#contact-"+e+"-msg").html(lang.call_failed),void $("#contact-"+e+"-AnswerCall").hide();if(i.data.rinngerObj&&(i.data.rinngerObj.pause(),i.data.rinngerObj.removeAttribute("src"),i.data.rinngerObj.load(),i.data.rinngerObj=null),0==HasAudioDevice)return Alert(lang.alert_no_microphone),$("#contact-"+e+"-msg").html(lang.call_failed),void $("#contact-"+e+"-AnswerCall").hide();if(0==HasVideoDevice)return console.warn("No video devices (webcam) found, switching to audio call."),void AnswerAudioCall(e);$("#contact-"+e+"-timer").html(""),$("#contact-"+e+"-timer").hide(),$("#contact-"+e+"-msg").html(""),$("#contact-"+e+"-msg").hide(),$("#contact-"+e+"-AnswerCall").hide();var n=i.remoteIdentity.displayName,a=i.remoteIdentity.uri.user;newLineNumber+=1,lineObj=new Line(newLineNumber,n,a,t),lineObj.SipSession=i,lineObj.SipSession.data.line=lineObj.LineNumber,lineObj.SipSession.data.buddyId=lineObj.BuddyObj.identity,Lines.push(lineObj),AddLineHtml(lineObj),SelectLine(newLineNumber),UpdateBuddyList();var o=navigator.mediaDevices.getSupportedConstraints(),l={sessionDescriptionHandlerOptions:{constraints:{audio:{deviceId:"default"},video:{deviceId:"default"}}}},s=getAudioSrcID();if("default"!=s){for(var r=!1,d=0;d<AudioinputDevices.length;++d)if(s==AudioinputDevices[d].deviceId){r=!0;break}r?l.sessionDescriptionHandlerOptions.constraints.audio.deviceId={exact:s}:(console.warn("The audio device you used before is no longer available, default settings applied."),localDB.setItem("AudioSrcId","default"))}o.autoGainControl&&(l.sessionDescriptionHandlerOptions.constraints.audio.autoGainControl=AutoGainControl),o.echoCancellation&&(l.sessionDescriptionHandlerOptions.constraints.audio.echoCancellation=EchoCancellation),o.noiseSuppression&&(l.sessionDescriptionHandlerOptions.constraints.audio.noiseSuppression=NoiseSuppression);var c=getVideoSrcID();if("default"!=c){var u=!1;for(d=0;d<VideoinputDevices.length;++d)if(c==VideoinputDevices[d].deviceId){u=!0;break}u?l.sessionDescriptionHandlerOptions.constraints.video.deviceId={exact:c}:(console.warn("The video device you used before is no longer available, default settings applied."),localDB.setItem("VideoSrcId","default"))}o.frameRate&&""!=maxFrameRate&&(l.sessionDescriptionHandlerOptions.constraints.video.frameRate=maxFrameRate),o.height&&""!=videoHeight&&(l.sessionDescriptionHandlerOptions.constraints.video.height=videoHeight),o.aspectRatio&&""!=videoAspectRatio&&(l.sessionDescriptionHandlerOptions.constraints.video.aspectRatio=videoAspectRatio),lineObj.SipSession.data.withvideo=!0,lineObj.SipSession.data.VideoSourceDevice=getVideoSrcID(),lineObj.SipSession.data.AudioSourceDevice=getAudioSrcID(),lineObj.SipSession.data.AudioOutputDevice=getAudioOutputID(),$("#contact-"+e+"-msg").html(lang.call_in_progress),wireupVideoSession(lineObj);try{lineObj.SipSession.accept(l),StartVideoFullScreen&&ExpandVideoArea(lineObj.LineNumber),$("#contact-"+e+"-AnswerCall").hide()}catch(e){console.warn("Failed to answer call",e,lineObj.SipSession),teardownSession(lineObj,500,"Client Error")}}function RejectCall(e){var t=getSession(e);null==t&&(console.warn("Reject failed, null session"),$("#contact-"+e+"-msg").html(lang.call_failed),$("#contact-"+e+"-AnswerCall").hide()),t.data.terminateby="us",t.reject({statusCode:486,reasonPhrase:"Rejected by us"}),$("#contact-"+e+"-msg").html(lang.call_rejected)}function wireupAudioSession(e){if(null!=e){var t="#line-"+e.LineNumber+"-msg",i=e.SipSession;i.on("progress",(function(e){if(100==e.status_code)$(t).html(lang.trying);else if(180==e.status_code){$(t).html(lang.ringing);var n=audioBlobs.EarlyMedia_European;UserLocale().indexOf("us")>-1&&(n=audioBlobs.EarlyMedia_US),UserLocale().indexOf("gb")>-1&&(n=audioBlobs.EarlyMedia_UK),UserLocale().indexOf("au")>-1&&(n=audioBlobs.EarlyMedia_Australia),UserLocale().indexOf("jp")>-1&&(n=audioBlobs.EarlyMedia_Japan),console.log("Audio:",n.url);var a=new Audio(n.blob);a.preload="auto",a.loop=!0,a.oncanplaythrough=function(e){void 0!==a.sinkId&&"default"!=getAudioOutputID()&&a.setSinkId(getAudioOutputID()).then((function(){console.log("Set sinkId to:",getAudioOutputID())})).catch((function(e){console.warn("Failed not apply setSinkId.",e)})),a.play().then((function(){})).catch((function(e){console.warn("Unable to play audio file.",e)}))},i.data.earlyMedia=a}else $(t).html(e.reason_phrase+"...");"undefined"!=typeof web_hook_on_modify&&web_hook_on_modify("progress",i)})),i.on("trackAdded",(function(){var t=i.sessionDescriptionHandler.peerConnection,n=new MediaStream;t.getReceivers().forEach((function(e){e.track&&"audio"==e.track.kind&&n.addTrack(e.track)}));var a=$("#line-"+e.LineNumber+"-remoteAudio").get(0);a.srcObject=n,a.onloadedmetadata=function(e){void 0!==a.sinkId&&a.setSinkId(getAudioOutputID()).then((function(){console.log("sinkId applied: "+getAudioOutputID())})).catch((function(e){console.warn("Error using setSinkId: ",e)})),a.play()},"undefined"!=typeof web_hook_on_modify&&web_hook_on_modify("trackAdded",i)})),i.on("accepted",(function(n){i.data.earlyMedia&&(i.data.earlyMedia.pause(),i.data.earlyMedia.removeAttribute("src"),i.data.earlyMedia.load(),i.data.earlyMedia=null),window.clearInterval(i.data.callTimer);var a=moment.utc();i.data.callTimer=window.setInterval((function(){var t=moment.utc(),i=moment.duration(t.diff(a));$("#line-"+e.LineNumber+"-timer").html(formatShortDuration(i.asSeconds()))}),1e3),(RecordAllCalls||"enabled"==CallRecordingPolicy)&&StartRecording(e.LineNumber),$("#line-"+e.LineNumber+"-progress").hide(),$("#line-"+e.LineNumber+"-VideoCall").hide(),$("#line-"+e.LineNumber+"-ActiveCall").show(),e.LocalSoundMeter=StartLocalAudioMediaMonitoring(e.LineNumber,i),e.RemoteSoundMeter=StartRemoteAudioMediaMonitoring(e.LineNumber,i),$(t).html(lang.call_in_progress),updateLineScroll(e.LineNumber),UpdateBuddyList(),"undefined"!=typeof web_hook_on_modify&&web_hook_on_modify("accepted",i)})),i.on("rejected",(function(i,n){$(t).html(lang.call_rejected+": "+n),console.log("Call rejected: "+n),teardownSession(e,i.status_code,i.reason_phrase)})),i.on("failed",(function(i,n){$(t).html(lang.call_failed+": "+n),console.log("Call failed: "+n),teardownSession(e,0,"Call failed")})),i.on("cancel",(function(){$(t).html(lang.call_cancelled),console.log("Call Cancelled"),teardownSession(e,0,"Cancelled by caller")})),i.on("bye",(function(){$(t).html(lang.call_ended),console.log("Call ended, bye!"),teardownSession(e,16,"Normal Call clearing")})),i.on("terminated",(function(i,n){$(t).html(lang.call_ended),console.log("Session terminated"),teardownSession(e,16,"Normal Call clearing")})),i.on("reinvite",(function(e){console.log("Session reinvited!")})),i.on("directionChanged",(function(){var e=i.sessionDescriptionHandler.getDirection();console.log("Direction Change: ",e),"undefined"!=typeof web_hook_on_modify&&web_hook_on_modify("directionChanged",i)})),$("#line-"+e.LineNumber+"-btn-settings").removeAttr("disabled"),$("#line-"+e.LineNumber+"-btn-audioCall").prop("disabled","disabled"),$("#line-"+e.LineNumber+"-btn-videoCall").prop("disabled","disabled"),$("#line-"+e.LineNumber+"-btn-search").removeAttr("disabled"),$("#line-"+e.LineNumber+"-btn-remove").prop("disabled","disabled"),$("#line-"+e.LineNumber+"-progress").show(),$("#line-"+e.LineNumber+"-msg").show(),"group"==e.BuddyObj.type?$("#line-"+e.LineNumber+"-conference").show():$("#line-"+e.LineNumber+"-conference").hide(),updateLineScroll(e.LineNumber),UpdateUI()}}function wireupVideoSession(e){if(null!=e){var t="#line-"+e.LineNumber+"-msg",i=e.SipSession;i.on("trackAdded",(function(){var t=i.sessionDescriptionHandler.peerConnection,n=new MediaStream,a=new MediaStream;if(t.getReceivers().forEach((function(e){e.track&&("audio"==e.track.kind&&n.addTrack(e.track),"video"==e.track.kind&&a.addTrack(e.track))})),n.getAudioTracks().length>=1){var o=$("#line-"+e.LineNumber+"-remoteAudio").get(0);o.srcObject=n,o.onloadedmetadata=function(e){void 0!==o.sinkId&&o.setSinkId(getAudioOutputID()).then((function(){console.log("sinkId applied: "+getAudioOutputID())})).catch((function(e){console.warn("Error using setSinkId: ",e)})),o.play()}}if(a.getVideoTracks().length>=1){var l=$("#line-"+e.LineNumber+"-remoteVideo").get(0);l.srcObject=a,l.onloadedmetadata=function(e){l.play()}}window.setTimeout((function(){var t=new MediaStream;i.sessionDescriptionHandler.peerConnection.getSenders().forEach((function(e){e.track&&"video"==e.track.kind&&t.addTrack(e.track)}));var n=$("#line-"+e.LineNumber+"-localVideo").get(0);n.srcObject=t,n.onloadedmetadata=function(e){n.play()}}),1e3),"undefined"!=typeof web_hook_on_modify&&web_hook_on_modify("trackAdded",i)})),i.on("progress",(function(e){if(100==e.status_code)$(t).html(lang.trying);else if(180==e.status_code){$(t).html(lang.ringing);var n=audioBlobs.EarlyMedia_European;UserLocale().indexOf("us")>-1&&(n=audioBlobs.EarlyMedia_US),UserLocale().indexOf("gb")>-1&&(n=audioBlobs.EarlyMedia_UK),UserLocale().indexOf("au")>-1&&(n=audioBlobs.EarlyMedia_Australia),UserLocale().indexOf("jp")>-1&&(n=audioBlobs.EarlyMedia_Japan),console.log("Audio:",n.url);var a=new Audio(n.blob);a.preload="auto",a.loop=!0,a.oncanplaythrough=function(e){void 0!==a.sinkId&&"default"!=getAudioOutputID()&&a.setSinkId(getAudioOutputID()).then((function(){console.log("Set sinkId to:",getAudioOutputID())})).catch((function(e){console.warn("Failed not apply setSinkId.",e)})),a.play().then((function(){})).catch((function(e){console.warn("Unable to play audio file.",e)}))},i.data.earlyMedia=a}else $(t).html(e.reason_phrase+"...");"undefined"!=typeof web_hook_on_modify&&web_hook_on_modify("progress",i)})),i.on("accepted",(function(n){i.data.earlyMedia&&(i.data.earlyMedia.pause(),i.data.earlyMedia.removeAttribute("src"),i.data.earlyMedia.load(),i.data.earlyMedia=null),window.clearInterval(i.data.callTimer),$("#line-"+e.LineNumber+"-timer").show();var a=moment.utc();i.data.callTimer=window.setInterval((function(){var t=moment.utc(),i=moment.duration(t.diff(a));$("#line-"+e.LineNumber+"-timer").html(formatShortDuration(i.asSeconds()))}),1e3),(RecordAllCalls||"enabled"==CallRecordingPolicy)&&StartRecording(e.LineNumber),$("#line-"+e.LineNumber+"-progress").hide(),$("#line-"+e.LineNumber+"-VideoCall").show(),$("#line-"+e.LineNumber+"-ActiveCall").show(),$("#line-"+e.LineNumber+"-btn-Conference").hide(),$("#line-"+e.LineNumber+"-btn-CancelConference").hide(),$("#line-"+e.LineNumber+"-Conference").hide(),$("#line-"+e.LineNumber+"-btn-Transfer").hide(),$("#line-"+e.LineNumber+"-btn-CancelTransfer").hide(),$("#line-"+e.LineNumber+"-Transfer").hide(),$("#line-"+e.LineNumber+"-src-camera").prop("disabled",!0),$("#line-"+e.LineNumber+"-src-canvas").prop("disabled",!1),$("#line-"+e.LineNumber+"-src-desktop").prop("disabled",!1),$("#line-"+e.LineNumber+"-src-video").prop("disabled",!1),updateLineScroll(e.LineNumber),e.LocalSoundMeter=StartLocalAudioMediaMonitoring(e.LineNumber,i),e.RemoteSoundMeter=StartRemoteAudioMediaMonitoring(e.LineNumber,i),$(t).html(lang.call_in_progress),StartVideoFullScreen&&ExpandVideoArea(e.LineNumber),"undefined"!=typeof web_hook_on_modify&&web_hook_on_modify("accepted",i)})),i.on("rejected",(function(i,n){$(t).html(lang.call_rejected+": "+n),console.log("Call rejected: "+n),teardownSession(e,i.status_code,i.reason_phrase)})),i.on("failed",(function(i,n){$(t).html(lang.call_failed+": "+n),console.log("Call failed: "+n),teardownSession(e,0,"call failed")})),i.on("cancel",(function(){$(t).html(lang.call_cancelled),console.log("Call Cancelled"),teardownSession(e,0,"Cancelled by caller")})),i.on("bye",(function(){$(t).html(lang.call_ended),console.log("Call ended, bye!"),teardownSession(e,16,"Normal Call clearing")})),i.on("terminated",(function(i,n){$(t).html(lang.call_ended),console.log("Session terminated"),teardownSession(e,16,"Normal Call clearing")})),i.on("reinvite",(function(e){console.log("Session reinvited!")})),i.on("directionChanged",(function(){var e=i.sessionDescriptionHandler.getDirection();console.log("Direction Change: ",e),"undefined"!=typeof web_hook_on_modify&&web_hook_on_modify("directionChanged",i)})),$("#line-"+e.LineNumber+"-btn-settings").removeAttr("disabled"),$("#line-"+e.LineNumber+"-btn-audioCall").prop("disabled","disabled"),$("#line-"+e.LineNumber+"-btn-videoCall").prop("disabled","disabled"),$("#line-"+e.LineNumber+"-btn-search").removeAttr("disabled"),$("#line-"+e.LineNumber+"-btn-remove").prop("disabled","disabled"),$("#line-"+e.LineNumber+"-progress").show(),$("#line-"+e.LineNumber+"-msg").show(),updateLineScroll(e.LineNumber),UpdateUI()}}function teardownSession(e,t,i){if(null!=e&&null!=e.SipSession){var n=e.SipSession;if(1!=n.data.teardownComplete){if(n.data.teardownComplete=!0,n.data.reasonCode=t,n.data.reasonText=i,$.jeegoopopup.close(),n.data.childsession)try{n.data.childsession.status==SIP.Session.C.STATUS_CONFIRMED?n.data.childsession.bye():n.data.childsession.cancel()}catch(e){}n.data.childsession=null,n.data.AudioSourceTrack&&"audio"==n.data.AudioSourceTrack.kind&&(n.data.AudioSourceTrack.stop(),n.data.AudioSourceTrack=null),n.data.earlyMedia&&(n.data.earlyMedia.pause(),n.data.earlyMedia.removeAttribute("src"),n.data.earlyMedia.load(),n.data.earlyMedia=null),StopRecording(e.LineNumber,!0),null!=e.LocalSoundMeter&&(e.LocalSoundMeter.stop(),e.LocalSoundMeter=null),null!=e.RemoteSoundMeter&&(e.RemoteSoundMeter.stop(),e.RemoteSoundMeter=null),window.clearInterval(n.data.videoResampleInterval),window.clearInterval(n.data.callTimer),AddCallMessage(e.BuddyObj.identity,n,t,i),window.setTimeout((function(){RemoveLine(e)}),1e3),UpdateBuddyList(),UpdateUI(),"undefined"!=typeof web_hook_on_terminate&&web_hook_on_terminate(n)}}}function StartRemoteAudioMediaMonitoring(e,t){console.log("Creating RemoteAudio AudioContext on Line:"+e);var i=new SoundMeter(t.id,e);if(null==i)return console.warn("AudioContext() RemoteAudio not available... it fine."),null;var n=new MediaStream,a=null;t.sessionDescriptionHandler.peerConnection.getReceivers().forEach((function(e){e.track&&"audio"==e.track.kind&&(null==a?(n.addTrack(e.track),a=e):(console.log("Found another Track, but audioReceiver not null"),console.log(e),console.log(e.track)))}));i.startTime=Date.now(),Chart.defaults.global.defaultFontSize=12;var o={responsive:!1,maintainAspectRatio:!1,devicePixelRatio:1,animation:!1,scales:{yAxes:[{ticks:{beginAtZero:!0}}]}};return i.ReceiveBitRateChart=new Chart($("#line-"+e+"-AudioReceiveBitRate"),{type:"line",data:{labels:MakeDataArray("",100),datasets:[{label:lang.receive_kilobits_per_second,data:MakeDataArray(0,100),backgroundColor:"rgba(168, 0, 0, 0.5)",borderColor:"rgba(168, 0, 0, 1)",borderWidth:1,pointRadius:1}]},options:o}),i.ReceiveBitRateChart.lastValueBytesReceived=0,i.ReceiveBitRateChart.lastValueTimestamp=0,i.ReceivePacketRateChart=new Chart($("#line-"+e+"-AudioReceivePacketRate"),{type:"line",data:{labels:MakeDataArray("",100),datasets:[{label:lang.receive_packets_per_second,data:MakeDataArray(0,100),backgroundColor:"rgba(168, 0, 0, 0.5)",borderColor:"rgba(168, 0, 0, 1)",borderWidth:1,pointRadius:1}]},options:o}),i.ReceivePacketRateChart.lastValuePacketReceived=0,i.ReceivePacketRateChart.lastValueTimestamp=0,i.ReceivePacketLossChart=new Chart($("#line-"+e+"-AudioReceivePacketLoss"),{type:"line",data:{labels:MakeDataArray("",100),datasets:[{label:lang.receive_packet_loss,data:MakeDataArray(0,100),backgroundColor:"rgba(168, 99, 0, 0.5)",borderColor:"rgba(168, 99, 0, 1)",borderWidth:1,pointRadius:1}]},options:o}),i.ReceivePacketLossChart.lastValuePacketLoss=0,i.ReceivePacketLossChart.lastValueTimestamp=0,i.ReceiveJitterChart=new Chart($("#line-"+e+"-AudioReceiveJitter"),{type:"line",data:{labels:MakeDataArray("",100),datasets:[{label:lang.receive_jitter,data:MakeDataArray(0,100),backgroundColor:"rgba(0, 38, 168, 0.5)",borderColor:"rgba(0, 38, 168, 1)",borderWidth:1,pointRadius:1}]},options:o}),i.ReceiveLevelsChart=new Chart($("#line-"+e+"-AudioReceiveLevels"),{type:"line",data:{labels:MakeDataArray("",100),datasets:[{label:lang.receive_audio_levels,data:MakeDataArray(0,100),backgroundColor:"rgba(140, 0, 168, 0.5)",borderColor:"rgba(140, 0, 168, 1)",borderWidth:1,pointRadius:1}]},options:o}),i.connectToSource(n,(function(t){null==t&&(console.log("SoundMeter for RemoteAudio Connected, displaying levels for Line: "+e),i.levelsInterval=window.setInterval((function(){var t=4*i.instant;t>1&&(t=1);var n=100*t;$("#line-"+e+"-Speaker").css("height",n.toFixed(2)+"%")}),50),i.networkInterval=window.setInterval((function(){null!=a&&a.getStats().then((function(e){e.forEach((function(e){var t=utcDateNow(),n=i.ReceiveBitRateChart,a=i.ReceivePacketRateChart,o=i.ReceivePacketLossChart,l=i.ReceiveJitterChart,s=i.ReceiveLevelsChart;Math.floor((Date.now()-i.startTime)/1e3);if("inbound-rtp"==e.type){if(0==n.lastValueTimestamp)return n.lastValueTimestamp=e.timestamp,n.lastValueBytesReceived=e.bytesReceived,a.lastValueTimestamp=e.timestamp,a.lastValuePacketReceived=e.packetsReceived,o.lastValueTimestamp=e.timestamp,void(o.lastValuePacketLoss=e.packetsLost);var r=8*(e.bytesReceived-n.lastValueBytesReceived)/1e3;n.lastValueTimestamp=e.timestamp,n.lastValueBytesReceived=e.bytesReceived,i.ReceiveBitRate.push({value:r,timestamp:t}),n.data.datasets[0].data.push(r),n.data.labels.push(""),n.data.datasets[0].data.length>100&&(n.data.datasets[0].data.splice(0,1),n.data.labels.splice(0,1)),n.update();var d=e.packetsReceived-a.lastValuePacketReceived;a.lastValueTimestamp=e.timestamp,a.lastValuePacketReceived=e.packetsReceived,i.ReceivePacketRate.push({value:d,timestamp:t}),a.data.datasets[0].data.push(d),a.data.labels.push(""),a.data.datasets[0].data.length>100&&(a.data.datasets[0].data.splice(0,1),a.data.labels.splice(0,1)),a.update();var c=e.packetsLost-o.lastValuePacketLoss;o.lastValueTimestamp=e.timestamp,o.lastValuePacketLoss=e.packetsLost,i.ReceivePacketLoss.push({value:c,timestamp:t}),o.data.datasets[0].data.push(c),o.data.labels.push(""),o.data.datasets[0].data.length>100&&(o.data.datasets[0].data.splice(0,1),o.data.labels.splice(0,1)),o.update(),i.ReceiveJitter.push({value:e.jitter,timestamp:t}),l.data.datasets[0].data.push(e.jitter),l.data.labels.push(""),l.data.datasets[0].data.length>100&&(l.data.datasets[0].data.splice(0,1),l.data.labels.splice(0,1)),l.update()}if("track"==e.type){var u=100*e.audioLevel;i.ReceiveLevels.push({value:u,timestamp:t}),s.data.datasets[0].data.push(u),s.data.labels.push(""),s.data.datasets[0].data.length>100&&(s.data.datasets[0].data.splice(0,1),s.data.labels.splice(0,1)),s.update()}}))}))}),1e3))})),i}function StartLocalAudioMediaMonitoring(e,t){console.log("Creating LocalAudio AudioContext on line "+e);var i=new SoundMeter(t.id,e);if(null==i)return console.warn("AudioContext() LocalAudio not available... its fine."),null;var n=new MediaStream,a=null;t.sessionDescriptionHandler.peerConnection.getSenders().forEach((function(e){e.track&&"audio"==e.track.kind&&(null==a?(console.log("Adding Track to Monitor: ",e.track.label),n.addTrack(e.track),a=e):(console.log("Found another Track, but audioSender not null"),console.log(e),console.log(e.track)))}));i.startTime=Date.now(),Chart.defaults.global.defaultFontSize=12;var o={responsive:!1,maintainAspectRatio:!1,devicePixelRatio:1,animation:!1,scales:{yAxes:[{ticks:{beginAtZero:!0}}]}};return i.SendBitRateChart=new Chart($("#line-"+e+"-AudioSendBitRate"),{type:"line",data:{labels:MakeDataArray("",100),datasets:[{label:lang.send_kilobits_per_second,data:MakeDataArray(0,100),backgroundColor:"rgba(0, 121, 19, 0.5)",borderColor:"rgba(0, 121, 19, 1)",borderWidth:1,pointRadius:1}]},options:o}),i.SendBitRateChart.lastValueBytesSent=0,i.SendBitRateChart.lastValueTimestamp=0,i.SendPacketRateChart=new Chart($("#line-"+e+"-AudioSendPacketRate"),{type:"line",data:{labels:MakeDataArray("",100),datasets:[{label:lang.send_packets_per_second,data:MakeDataArray(0,100),backgroundColor:"rgba(0, 121, 19, 0.5)",borderColor:"rgba(0, 121, 19, 1)",borderWidth:1,pointRadius:1}]},options:o}),i.SendPacketRateChart.lastValuePacketSent=0,i.SendPacketRateChart.lastValueTimestamp=0,i.connectToSource(n,(function(t){null==t&&(console.log("SoundMeter for LocalAudio Connected, displaying levels for Line: "+e),i.levelsInterval=window.setInterval((function(){var t=4*i.instant;t>1&&(t=1);var n=100*t;$("#line-"+e+"-Mic").css("height",n.toFixed(2)+"%")}),50),i.networkInterval=window.setInterval((function(){null!=a&&a.getStats().then((function(e){e.forEach((function(e){var t=utcDateNow(),n=i.SendBitRateChart,a=i.SendPacketRateChart;Math.floor((Date.now()-i.startTime)/1e3);if("outbound-rtp"==e.type){if(0==n.lastValueTimestamp)return n.lastValueTimestamp=e.timestamp,n.lastValueBytesSent=e.bytesSent,a.lastValueTimestamp=e.timestamp,void(a.lastValuePacketSent=e.packetsSent);var o=8*(e.bytesSent-n.lastValueBytesSent)/1e3;n.lastValueTimestamp=e.timestamp,n.lastValueBytesSent=e.bytesSent,i.SendBitRate.push({value:o,timestamp:t}),n.data.datasets[0].data.push(o),n.data.labels.push(""),n.data.datasets[0].data.length>100&&(n.data.datasets[0].data.splice(0,1),n.data.labels.splice(0,1)),n.update();var l=e.packetsSent-a.lastValuePacketSent;a.lastValueTimestamp=e.timestamp,a.lastValuePacketSent=e.packetsSent,i.SendPacketRate.push({value:l,timestamp:t}),a.data.datasets[0].data.push(l),a.data.labels.push(""),a.data.datasets[0].data.length>100&&(a.data.datasets[0].data.splice(0,1),a.data.labels.splice(0,1)),a.update()}e.type}))}))}),1e3))})),i}$(window).on("beforeunload",(function(){Unregister()})),$(window).on("resize",(function(){UpdateUI()})),$(document).ready((function(){$.getJSON(hostingPrefex+"lang/en.json",(function(e){lang=e;var t=GetAlternateLanguage();""!=t?$.getJSON(hostingPrefex+"lang/"+t+".json",(function(e){lang=e})).always((function(){console.log("Alternate Lanaguage Pack loaded: ",lang),InitUi()})):(console.log("Lanaguage Pack already loaded: ",lang),InitUi())})),getConfFromSqldb(),getExternalUserConfFromSqldb()}));class SoundMeter{constructor(e,t){var i=null;try{window.AudioContext=window.AudioContext||window.webkitAudioContext,i=new AudioContext}catch(e){console.warn("AudioContext() LocalAudio not available... its fine.")}if(null==i)return null;this.lineNum=t,this.sessionId=e,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=i,this.instant=0,this.script=i.createScriptProcessor(2048,1,1);const n=this;this.script.onaudioprocess=function(e){const t=e.inputBuffer.getChannelData(0);let i,a=0;for(i=0;i<t.length;++i)a+=t[i]*t[i];n.instant=Math.sqrt(a/t.length)}}connectToSource(e,t){console.log("SoundMeter connecting...");try{this.mic=this.context.createMediaStreamSource(e),this.mic.connect(this.script),this.script.connect(this.context.destination),t(null)}catch(e){console.error(e),t(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;var e=FindLineByNumber(this.lineNum);SaveQosData({ReceiveBitRate:this.ReceiveBitRate,ReceivePacketRate:this.ReceivePacketRate,ReceivePacketLoss:this.ReceivePacketLoss,ReceiveJitter:this.ReceiveJitter,ReceiveLevels:this.ReceiveLevels,SendBitRate:this.SendBitRate,SendPacketRate:this.SendPacketRate},this.sessionId,e.BuddyObj.identity)}}function MeterSettingsOutput(e,t,i,n){var a=new SoundMeter(null,null);return a.startTime=Date.now(),a.connectToSource(e,(function(e){null==e&&(console.log("SoundMeter Connected, displaying levels to:"+t),a.levelsInterval=window.setInterval((function(){var e=4*a.instant;e>1&&(e=1);var n=100*e;$("#"+t).css(i,n.toFixed(2)+"%")}),n))})),a}function SaveQosData(e,t,i){var n=window.indexedDB.open("CallQosData");n.onerror=function(e){console.error("IndexDB Request Error:",e)},n.onupgradeneeded=function(e){console.warn("Upgrade Required for IndexDB... probably because of first time use.");var t=e.target.result;if(0==t.objectStoreNames.contains("CallQos")){var i=t.createObjectStore("CallQos",{keyPath:"uID"});i.createIndex("sessionid","sessionid",{unique:!1}),i.createIndex("buddy","buddy",{unique:!1}),i.createIndex("QosData","QosData",{unique:!1})}else console.warn("IndexDB requested upgrade, but object store was in place")},n.onsuccess=function(n){console.log("IndexDB connected to CallQosData");var a=n.target.result;if(0!=a.objectStoreNames.contains("CallQos")){a.onerror=function(e){console.error("IndexDB Error:",e)};var o={uID:uID(),sessionid:t,buddy:i,QosData:e};a.transaction(["CallQos"],"readwrite").objectStore("CallQos").add(o).onsuccess=function(e){console.log("Call CallQos Sucess: ",t)}}else console.warn("IndexDB CallQosData.CallQos does not exists")}}function DisplayQosData(e){var t=window.indexedDB.open("CallQosData");t.onerror=function(e){console.error("IndexDB Request Error:",e)},t.onupgradeneeded=function(e){console.warn("Upgrade Required for IndexDB... probably because of first time use.")},t.onsuccess=function(t){console.log("IndexDB connected to CallQosData");var i=t.target.result;if(0!=i.objectStoreNames.contains("CallQos")){var n=i.transaction(["CallQos"]).objectStore("CallQos").index("sessionid").getAll(e);n.onerror=function(e){console.error("IndexDB Get Error:",e)},n.onsuccess=function(e){if(e.target.result&&2==e.target.result.length){var t=e.target.result[0].QosData,i=e.target.result[1].QosData;Chart.defaults.global.defaultFontSize=12;var n={responsive:!0,maintainAspectRatio:!1,animation:!1,scales:{yAxes:[{ticks:{beginAtZero:!0}}],xAxes:[{display:!1}]}},a=[],o=[],l=t.ReceiveBitRate.length>0?t.ReceiveBitRate:i.ReceiveBitRate;$.each(l,(function(e,t){a.push(moment.utc(t.timestamp.replace(" UTC","")).local().format(DisplayDateFormat+" "+DisplayTimeFormat)),o.push(t.value)}));new Chart($("#cdr-AudioReceiveBitRate"),{type:"line",data:{labels:a,datasets:[{label:lang.receive_kilobits_per_second,data:o,backgroundColor:"rgba(168, 0, 0, 0.5)",borderColor:"rgba(168, 0, 0, 1)",borderWidth:1,pointRadius:1}]},options:n}),a=[],o=[],l=t.ReceivePacketRate.length>0?t.ReceivePacketRate:i.ReceivePacketRate;$.each(l,(function(e,t){a.push(moment.utc(t.timestamp.replace(" UTC","")).local().format(DisplayDateFormat+" "+DisplayTimeFormat)),o.push(t.value)}));new Chart($("#cdr-AudioReceivePacketRate"),{type:"line",data:{labels:a,datasets:[{label:lang.receive_packets_per_second,data:o,backgroundColor:"rgba(168, 0, 0, 0.5)",borderColor:"rgba(168, 0, 0, 1)",borderWidth:1,pointRadius:1}]},options:n}),a=[],o=[],l=t.ReceivePacketLoss.length>0?t.ReceivePacketLoss:i.ReceivePacketLoss;$.each(l,(function(e,t){a.push(moment.utc(t.timestamp.replace(" UTC","")).local().format(DisplayDateFormat+" "+DisplayTimeFormat)),o.push(t.value)}));new Chart($("#cdr-AudioReceivePacketLoss"),{type:"line",data:{labels:a,datasets:[{label:lang.receive_packet_loss,data:o,backgroundColor:"rgba(168, 99, 0, 0.5)",borderColor:"rgba(168, 99, 0, 1)",borderWidth:1,pointRadius:1}]},options:n}),a=[],o=[],l=t.ReceiveJitter.length>0?t.ReceiveJitter:i.ReceiveJitter;$.each(l,(function(e,t){a.push(moment.utc(t.timestamp.replace(" UTC","")).local().format(DisplayDateFormat+" "+DisplayTimeFormat)),o.push(t.value)}));new Chart($("#cdr-AudioReceiveJitter"),{type:"line",data:{labels:a,datasets:[{label:lang.receive_jitter,data:o,backgroundColor:"rgba(0, 38, 168, 0.5)",borderColor:"rgba(0, 38, 168, 1)",borderWidth:1,pointRadius:1}]},options:n}),a=[],o=[],l=t.ReceiveLevels.length>0?t.ReceiveLevels:i.ReceiveLevels;$.each(l,(function(e,t){a.push(moment.utc(t.timestamp.replace(" UTC","")).local().format(DisplayDateFormat+" "+DisplayTimeFormat)),o.push(t.value)}));new Chart($("#cdr-AudioReceiveLevels"),{type:"line",data:{labels:a,datasets:[{label:lang.receive_audio_levels,data:o,backgroundColor:"rgba(140, 0, 168, 0.5)",borderColor:"rgba(140, 0, 168, 1)",borderWidth:1,pointRadius:1}]},options:n}),a=[],o=[],l=t.SendPacketRate.length>0?t.SendPacketRate:i.SendPacketRate;$.each(l,(function(e,t){a.push(moment.utc(t.timestamp.replace(" UTC","")).local().format(DisplayDateFormat+" "+DisplayTimeFormat)),o.push(t.value)}));new Chart($("#cdr-AudioSendPacketRate"),{type:"line",data:{labels:a,datasets:[{label:lang.send_packets_per_second,data:o,backgroundColor:"rgba(0, 121, 19, 0.5)",borderColor:"rgba(0, 121, 19, 1)",borderWidth:1,pointRadius:1}]},options:n}),a=[],o=[],l=t.SendBitRate.length>0?t.SendBitRate:i.SendBitRate;$.each(l,(function(e,t){a.push(moment.utc(t.timestamp.replace(" UTC","")).local().format(DisplayDateFormat+" "+DisplayTimeFormat)),o.push(t.value)}));new Chart($("#cdr-AudioSendBitRate"),{type:"line",data:{labels:a,datasets:[{label:lang.send_kilobits_per_second,data:o,backgroundColor:"rgba(0, 121, 19, 0.5)",borderColor:"rgba(0, 121, 19, 1)",borderWidth:1,pointRadius:1}]},options:n})}else console.warn("Result not expected",e.target.result)}}else console.warn("IndexDB CallQosData.CallQos does not exists")}}function DeleteQosData(e){var t=window.indexedDB.open("CallQosData");t.onerror=function(e){console.error("IndexDB Request Error:",e)},t.onupgradeneeded=function(e){console.warn("Upgrade Required for IndexDB... probably because of first time use.")},t.onsuccess=function(t){console.log("IndexDB connected to CallQosData");var i=t.target.result;if(0!=i.objectStoreNames.contains("CallQos")){i.onerror=function(e){console.error("IndexDB Error:",e)},console.log("Deleting CallQosData: ",e);var n=i.transaction(["CallQos"],"readwrite").objectStore("CallQos"),a=n.index("buddy").getAll(e);a.onerror=function(e){console.error("IndexDB Get Error:",e)},a.onsuccess=function(e){e.target.result&&e.target.result.length>0&&$.each(e.target.result,(function(e,t){try{n.delete(t.uID)}catch(e){console.log("Call CallQosData Delete failed: ",e)}}))}}else console.warn("IndexDB CallQosData.CallQos does not exists")}}function SubscribeAll(){console.log("Subscribe to voicemail Messages...");(voicemailSubs=userAgent.subscribe(SipUsername+"@"+wssServer,"message-summary",{expires:300})).on("notify",(function(e){var t=!1;$.each(e.request.body.split("\n"),(function(e,i){-1!=i.indexOf("Messages-Waiting:")&&(t="yes"==$.trim(i.replace("Messages-Waiting:","")))})),t&&console.log("You have voicemail!")}));var e={expires:300,extraHeaders:["Accept: application/pidf+xml"]};console.log("Starting Subscribe of all ("+Buddies.length+") Extension Buddies...");for(var t=0;t<Buddies.length;t++){var i=Buddies[t];if("extension"==i.type){console.log("SUBSCRIBE: "+i.ExtNo+"@"+wssServer);var n=userAgent.subscribe(i.ExtNo+"@"+wssServer,"presence",e);n.data.buddyId=i.identity,n.on("notify",(function(e){RecieveBlf(e)})),BlfSubs.push(n)}}}function SubscribeBuddy(e){if("extension"==e.type){console.log("SUBSCRIBE: "+e.ExtNo+"@"+wssServer);var t=userAgent.subscribe(e.ExtNo+"@"+wssServer,"presence",{expires:300,extraHeaders:["Accept: application/pidf+xml"]});t.data.buddyId=e.identity,t.on("notify",(function(e){RecieveBlf(e)})),BlfSubs.push(t)}}function RecieveBlf(e){if(null!=userAgent&&userAgent.isRegistered()){var t=e.request.headers["Content-Type"][0].parsed;if("application/pidf+xml"==t){var i=(l=$($.parseXML(e.request.body))).find("presence").attr("entity"),n=l.find("presence").find("tuple").find("contact").text();if(SipUsername!=i.split("@")[0].split(":")[1]&&SipUsername!=n.split("@")[0].split(":")[1])return void console.warn("presence message not for you.",l);var a=l.find("presence").find("tuple").attr("id"),o=(l.find("presence").find("tuple").find("status"),l.find("presence").find("tuple").find("status").find("basic").text(),"dotOffline");"Not online"==(r=l.find("presence").find("note").text())&&(o="dotOffline"),"Ready"==r&&(o="dotOnline"),"On the phone"==r&&(o="dotInUse"),"Ringing"==r&&(o="dotRinging"),"On hold"==r&&(o="dotOnHold"),"Unavailable"==r&&(o="dotOffline"),null!=(d=FindBuddyByExtNo(a))&&(console.log("Setting Presence for "+d.identity+" to "+r),$("#contact-"+d.identity+"-devstate").prop("class",o),$("#contact-"+d.identity+"-devstate-main").prop("class",o),d.devState=o,d.presence=r,"Not online"==r&&(r=lang.state_not_online),"Ready"==r&&(r=lang.state_ready),"On the phone"==r&&(r=lang.state_on_the_phone),"Ringing"==r&&(r=lang.state_ringing),"On hold"==r&&(r=lang.state_on_hold),"Unavailable"==r&&(r=lang.state_unavailable),$("#contact-"+d.identity+"-presence").html(r),$("#contact-"+d.identity+"-presence-main").html(r))}else if("application/dialog-info+xml"==t){var l;a=(l=$($.parseXML(e.request.body))).find("dialog-info").attr("entity").split("@")[0].split(":")[1],l.find("dialog-info").attr("version");if("full"!=l.find("dialog-info").attr("state"))return;if(l.find("dialog-info").find("dialog").attr("id")!=a)return;var s=l.find("dialog-info").find("dialog").find("state").text(),r="Unknown";"terminated"==s&&(r="Ready"),"trying"==s&&(r="On the phone"),"proceeding"==s&&(r="On the phone"),"early"==s&&(r="Ringing"),"confirmed"==s&&(r="On the phone");var d;o="dotOffline";"Not online"==r&&(o="dotOffline"),"Ready"==r&&(o="dotOnline"),"On the phone"==r&&(o="dotInUse"),"Ringing"==r&&(o="dotRinging"),"On hold"==r&&(o="dotOnHold"),"Unavailable"==r&&(o="dotOffline"),null!=(d=FindBuddyByExtNo(a))&&(console.log("Setting Presence for "+d.identity+" to "+r),$("#contact-"+d.identity+"-devstate").prop("class",o),$("#contact-"+d.identity+"-devstate-main").prop("class",o),d.devState=o,d.presence=r,"Unknown"==r&&(r=lang.state_unknown),"Not online"==r&&(r=lang.state_not_online),"Ready"==r&&(r=lang.state_ready),"On the phone"==r&&(r=lang.state_on_the_phone),"Ringing"==r&&(r=lang.state_ringing),"On hold"==r&&(r=lang.state_on_hold),"Unavailable"==r&&(r=lang.state_unavailable),$("#contact-"+d.identity+"-presence").html(r),$("#contact-"+d.identity+"-presence-main").html(r))}}}function UnsubscribeAll(){console.log("Unsubscribing "+BlfSubs.length+" subscriptions...");for(var e=0;e<BlfSubs.length;e++)BlfSubs[e].unsubscribe(),BlfSubs[e].close();BlfSubs=new Array;for(var t=0;t<Buddies.length;t++){var i=Buddies[t];"extension"==i.type&&($("#contact-"+i.identity+"-devstate").prop("class","dotOffline"),$("#contact-"+i.identity+"-devstate-main").prop("class","dotOffline"),$("#contact-"+i.identity+"-presence").html(lang.state_unknown),$("#contact-"+i.identity+"-presence-main").html(lang.state_unknown))}}function UnsubscribeBuddy(e){if("extension"==e.type)for(var t=0;t<BlfSubs.length;t++){var i=BlfSubs[t];if(i.data.buddyId==e.identity){console.log("Unsubscribing:",e.identity),null!=i.dialog&&(i.unsubscribe(),i.close()),BlfSubs.splice(t,1);break}}}function InitinaliseStream(e){return localDB.setItem(e+"-stream",JSON.stringify({TotalRows:0,DataCollection:[]})),JSON.parse(localDB.getItem(e+"-stream"))}function splitString(e,t){const i=Math.ceil(e.length/t),n=[];for(let a=0,o=0;a<i;++a,o+=t)n[a]=e.substr(o,t);return n}function generateAESKey(e){const t=CryptoJS.lib.WordArray.random(16);return CryptoJS.PBKDF2(e,t,{keySize:8,iterations:100})}function encryptAES(e,t){return(e=CryptoJS.AES.encrypt(e,t)).toString()}function decryptAES(e,t){return CryptoJS.AES.decrypt(e,t).toString(CryptoJS.enc.Utf8)}function getChatRSAPubKey(e){var t="";return $.ajax({async:!1,global:!1,type:"POST",url:"get-text-chat-pub-key.php",dataType:"JSON",data:{recsendsipuser:e,s_ajax_call:validateSToken},success:function(e){"success"==e.resmessage?t="`"+e.chatkey.join("")+"`":(pubKeyCheck=1,alert("An error occurred while retrieving the public key for text chat!"))},error:function(e){alert("An error occurred while attempting to retrieve the public key for text chat!")}}),t}function SendChatMessage(e){if(null!=userAgent&&userAgent.isRegistered()){var t=$("#contact-"+e+"-ChatMessage").val();if(messagetrim=$.trim(t),""!=messagetrim||0!=sendFileCheck&&(1!=sendFileCheck||""!=$("#selectedFile").val())){var i=FindBuddyByIdentity(e);if(-1==$.inArray(i.presence,["Ready","On the phone","Ringing","On hold"]))return alert("You cannot send a message or a file to a contact who is not online!"),$("#sendFileLoader").remove(),$("#selectedFile").val(""),$("#sendFileFormChat").remove(),void(sendFileCheck=0);var n=Date.now()+Math.floor(1e4*Math.random()).toString(6).toUpperCase(),a=String(generateAESKey(n)),o=[],l=(o=splitString(encryptAES(messagetrim,a),900),Date.now()+Math.floor(1e4*Math.random()).toString(16).toUpperCase()+profileUser),s=[];s=[l,1];var r=[];r=[l,0];var d=getChatRSAPubKey(i.ExtNo),c=new JSEncrypt;c.setPublicKey(d);var u=c.encrypt(a);o.unshift(u),$("#contact-"+e+"-ChatHistory").after("<span id='sendFileLoader'></span>");for(var p=0;p<o.length;p++){if(0==p)var g=l+"|"+o.length+"|"+parseInt(p)+"||"+o[p];else if(0==sendFileCheck&&""!=o[p])g=l+"|"+o.length+"|"+parseInt(p)+"||"+o[p];else if(1==sendFileCheck&&""==sendFileChatErr)g=l+"|"+o.length+"|"+parseInt(p)+"|"+upFileName+"|"+o[p];else if(1==sendFileCheck&&""!=sendFileChatErr)return $("#sendFileFormChat").remove(),sendFileChatErr="",void(sendFileCheck=0);1==p&&(s=[l,0]),p==o.length-1&&(r=[l,1]),SendChatMessageProc(e,i,l,g,messagetrim,s,r)}}else Alert(lang.alert_empty_text_message,lang.no_message)}}function SendChatMessageProc(e,t,i,n,a,o,l){var s=uID();if(1==pubKeyCheck)return pubKeyCheck=0,$("#selectedFile").val(""),void $("#sendFileLoader").remove();if(sendFileChatErr="",$("#sendFileFormChat").on("submit",(function(e){e.preventDefault(),$.ajax({async:!1,global:!1,type:"POST",url:"text-chat-upload-file.php",data:new FormData(this),dataType:"JSON",contentType:!1,cache:!1,processData:!1,success:function(e){""!=e.error&&(sendFileChatErr=e.error,$("#sendFileFormChat").remove(),$("#sendFileLoader").remove(),alert("Error: "+e.error))},error:function(e){alert("An error occurred while sending the file!")}})})),1==sendFileCheck&&o[0]==i&&1==o[1]&&$("#submitFileChat").click(),l[0]==i&&1==l[1]&&1==sendFileCheck&&""!=sendFileChatErr)return $("#sendFileFormChat").remove(),$("#sendFileLoader").remove(),sendFileChatErr="",void(sendFileCheck=0);if("extension"==t.type||"group"==t.type){var r=t.ExtNo+"@"+wssServer;console.log("MESSAGE: "+r+" (extension)");var d=userAgent.message(r,n);d.data.direction="outbound",d.data.messageId=s,d.on("accepted",(function(i,n){var a;202==i.status_code?(console.log("Message Accepted:",s),null==(a=JSON.parse(localDB.getItem(e+"-stream")))&&null==a.DataCollection||($.each(a.DataCollection,(function(e,t){if("MSG"==t.ItemType&&t.ItemId==s)return t.Sent=!0,!1})),localDB.setItem(e+"-stream",JSON.stringify(a)),RefreshStream(t))):(console.warn("Message Error",i.status_code,n),null==(a=JSON.parse(localDB.getItem(e+"-stream")))&&null==a.DataCollection||($.each(a.DataCollection,(function(e,t){if("MSG"==t.ItemType&&t.ItemId==s)return t.Sent=!1,!1})),localDB.setItem(e+"-stream",JSON.stringify(a)),RefreshStream(t)))})),"undefined"!=typeof web_hook_on_message&&web_hook_on_message(d)}if(l[0]==i&&1==l[1]){var c=moment.utc().format("YYYY-MM-DD HH:mm:ss UTC"),u=JSON.parse(localDB.getItem(e+"-stream"));null==u&&(u=InitinaliseStream(e));var p={ItemId:s,ItemType:"MSG",ItemDate:c,SrcUserId:profileUserID,Src:'"'+profileName+'" <'+profileUser+">",DstUserId:e,Dst:"",MessageData:a};if(1==sendFileCheck){$("#sendFileFormChat").remove(),sendFileCheck=0;var g={ItemId:uID(),ItemType:"FILE",ItemDate:moment.utc().format("YYYY-MM-DD HH:mm:ss UTC"),SrcUserId:profileUserID,Src:'"'+profileName+'" <'+profileUser+">",DstUserId:e,Dst:t.ExtNo,SentFileName:upFileName,MessageData:"Download file"};""==sendFileChatErr&&u.DataCollection.push(g)}else $("#sendFileFormChat").remove();u.DataCollection.push(p),u.TotalRows=u.DataCollection.length,localDB.setItem(e+"-stream",JSON.stringify(u))}l[0]==i&&1==l[1]&&($("#sendFileLoader").remove(),$("#contact-"+e+"-ChatMessage").val("")),$("#contact-"+e+"-emoji-menu").hide(),null!=t.recognition&&(t.recognition.abort(),t.recognition=null),RefreshStream(t)}function ReceiveMessage(e){var t=e.remoteIdentity.displayName,i=e.remoteIdentity.uri.user;if(console.log("New Incoming Message!",'"'+t+'" <'+i+">"),e.data.direction="inbound",i.length>DidLength)console.warn("DID length greater then extensions length");else{var n=countSessions("0"),a=FindBuddyByDid(i);if(null==a){var o=JSON.parse(localDB.getItem(profileUserID+"-Buddies"));null==o&&(o=InitUserBuddies());var l=uID(),s=utcDateNow();o.DataCollection.push({Type:"extension",LastActivity:s,ExtensionNumber:i,MobileNumber:"",ContactNumber1:"",ContactNumber2:"",uID:l,cID:null,gID:null,DisplayName:t,Position:"",Description:"",Email:"",MemberCount:0}),AddBuddy(a=new Buddy("extension",l,t,i,"","","",s,"",""),!0,0==n,!0),o.TotalRows=o.DataCollection.length,localDB.setItem(profileUserID+"-Buddies",JSON.stringify(o))}var r=e.body.split("|");if(""!=r[3]&&void 0!==r[3]&&null!=r[3])var d=1,c=r[3];else d=0,c="";var u=r[0],p=parseInt(r[1]),g=parseInt(r[2]);if(0!=g)if(g<p-1)splitMessage.hasOwnProperty(u)?splitMessage[u][g]=r[4]:splitMessage[u]={[g]:r[4]};else{if(g==p-1){if(splitMessage.hasOwnProperty(u)?splitMessage[u][g]=r[4]:splitMessage[u]={[g]:r[4]},Object.keys(splitMessage[u]).length!=p)return;var m=splitMessage[u].aeskeyandiv;delete splitMessage[u].aeskeyandiv;var f="",v=Object.keys(splitMessage[u]).sort().reduce((function(e,t){return e[t]=splitMessage[u][t],e}),{});Object.keys(v).forEach((function(e,t){f+=splitMessage[u][e]}));var h=decryptAES(f,m);delete splitMessage[u]}var b=uID(),y=utcDateNow();if("group"==a.type){var w=e.request.headers["P-Asserted-Identity"][0].raw.split(" <"),S=w[0];w[1].replace(">","");S}var _=JSON.parse(localDB.getItem(a.identity+"-stream"));null==_&&(_=InitinaliseStream(a.identity));var C={ItemId:b,ItemType:"MSG",ItemDate:y,SrcUserId:a.identity,Src:'"'+a.CallerIDName+'" <'+a.ExtNo+">",DstUserId:profileUserID,Dst:"",MessageData:h};if(1==d&&""!=c){d=0;var D={ItemId:uID(),ItemType:"FILE",ItemDate:moment.utc().format("YYYY-MM-DD HH:mm:ss UTC"),SrcUserId:a.identity,Src:'"'+a.CallerIDName+'" <'+a.ExtNo+">",DstUserId:profileUserID,Dst:profileUser,ReceivedFileName:c,MessageData:"Download file"};_.DataCollection.push(D)}if(_.DataCollection.push(C),_.TotalRows=_.DataCollection.length,localDB.setItem(a.identity+"-stream",JSON.stringify(_)),UpdateBuddyActivity(a.identity),RefreshStream(a),!$("#stream-"+a.identity).is(":visible")){if(IncreaseMissedBadge(a.identity),"Notification"in window&&"granted"===Notification.permission){var k=getPicture(a.identity),I={body:h.substring(0,250),icon:k};new Notification(lang.message_from+" : "+a.CallerIDName,I).onclick=function(e){SelectBuddy(a.identity)}}console.log("Audio:",audioBlobs.Alert.url);var x=new Audio(audioBlobs.Alert.blob);x.preload="auto",x.loop=!1,x.oncanplaythrough=function(e){void 0!==x.sinkId&&"default"!=getRingerOutputID()&&x.setSinkId(getRingerOutputID()).then((function(){console.log("Set sinkId to:",getRingerOutputID())})).catch((function(e){console.warn("Failed not apply setSinkId.",e)})),x.play().then((function(){})).catch((function(e){console.warn("Unable to play audio file.",e)}))},e.data.rinngerObj=x}}else if(splitMessage.hasOwnProperty(u))if(0==g){var T=r[4];(B=new JSEncrypt).setPrivateKey(currentChatPrivKey);var A=B.decrypt(T);splitMessage[u].aeskeyandiv=A}else splitMessage[u][g]=r[4];else if(0==g){var B;T=r[4];(B=new JSEncrypt).setPrivateKey(currentChatPrivKey);A=B.decrypt(T);splitMessage[u]={aeskeyandiv:A}}else splitMessage[u]={[g]:r[4]}}}function AddCallMessage(e,t,i,n){var a=JSON.parse(localDB.getItem(e+"-stream"));null==a&&(a=InitinaliseStream(e));var o=moment.utc(),l=0,s=0,r=0,d=moment.utc(t.data.callstart.replace(" UTC","")),c=null;t.startTime&&(c=moment.utc(t.startTime),l=moment.duration(o.diff(c)),r=moment.duration(c.diff(d))),s=moment.duration(o.diff(d)),console.log(t.data.reasonCode+"("+t.data.reasonText+")");var u="",p="",g="",m="";"inbound"==t.data.calldirection?(u=e,g=profileUserID,p="<"+t.remoteIdentity.uri.user+"> "+t.remoteIdentity.displayName,m="<"+profileUser+"> "+profileName):"outbound"==t.data.calldirection&&(u=profileUserID,g=e,p="<"+profileUser+"> "+profileName,m=t.remoteIdentity.uri.user);var f=t.data.calldirection,v=t.data.withvideo,h=t.id,b=t.data.terminateby,y={CdrId:uID(),ItemType:"CDR",ItemDate:d.format("YYYY-MM-DD HH:mm:ss UTC"),CallAnswer:c?c.format("YYYY-MM-DD HH:mm:ss UTC"):null,CallEnd:o.format("YYYY-MM-DD HH:mm:ss UTC"),SrcUserId:u,Src:p,DstUserId:g,Dst:m,RingTime:0!=r?r.asSeconds():0,Billsec:0!=l?l.asSeconds():0,TotalDuration:0!=s?s.asSeconds():0,ReasonCode:i,ReasonText:n,WithVideo:v,SessionId:h,CallDirection:f,Terminate:b,MessageData:null,Tags:[],Transfers:t.data.transfer?t.data.transfer:[],Mutes:t.data.mute?t.data.mute:[],Holds:t.data.hold?t.data.hold:[],Recordings:t.data.recordings?t.data.recordings:[],ConfCalls:t.data.confcalls?t.data.confcalls:[],QOS:[]};console.log("New CDR",y),a.DataCollection.push(y),a.TotalRows=a.DataCollection.length,localDB.setItem(e+"-stream",JSON.stringify(a)),UpdateBuddyActivity(e)}function SendImageDataMessage(e,t){if(null!=userAgent&&userAgent.isRegistered()){var i='<table class="ourChatMessage chatMessageTable" cellspacing=0 cellpadding=0><tr><td style="width: 80px"><div class=messageDate>'+moment.utc().format("YYYY-MM-DD HH:mm:ss UTC")+"</div></td><td><div class=ourChatMessageText>"+('<IMG class=previewImage onClick="PreviewImage(this)" src="'+t+'">')+"</div></td></tr></table>";$("#contact-"+e+"-ChatHistory").append(i),updateScroll(e),ImageEditor_Cancel(e),UpdateBuddyActivity(e)}}function SendFileDataMessage(e,t,i,n){if(null!=userAgent&&userAgent.isRegistered()){var a=uID();$.ajax({type:"POST",url:"/api/",data:"<XML>"+t+"</XML>",xhr:function(t){var i=$.ajaxSettings.xhr();return i.upload&&i.upload.addEventListener("progress",(function(t){var i=t.loaded/t.total*100;console.log("Progress for upload to "+e+" ("+a+"):"+i),$("#FileProgress-Bar-"+a).css("width",i+"%")}),!1),i},success:function(e,t,i){$("#FileUpload-"+a).html("Sent"),$("#FileProgress-"+a).hide(),$("#FileProgress-Bar-"+a).css("width","0%")},error:function(e,t,i){$("#FileUpload-"+a).html("Failed ("+e.status+")"),$("#FileProgress-"+a).hide(),$("#FileProgress-Bar-"+a).css("width","100%")}});var o=utcDateNow(),l=!1,s='<i class="fa fa-file"></i>';i.toLowerCase().endsWith(".png")&&(s='<i class="fa fa-file-image-o"></i>',l=!0),i.toLowerCase().endsWith(".jpg")&&(s='<i class="fa fa-file-image-o"></i>',l=!0),i.toLowerCase().endsWith(".jpeg")&&(s='<i class="fa fa-file-image-o"></i>',l=!0),i.toLowerCase().endsWith(".bmp")&&(s='<i class="fa fa-file-image-o"></i>',l=!0),i.toLowerCase().endsWith(".gif")&&(s='<i class="fa fa-file-image-o"></i>',l=!0),i.toLowerCase().endsWith(".mov")&&(s='<i class="fa fa-file-video-o"></i>'),i.toLowerCase().endsWith(".avi")&&(s='<i class="fa fa-file-video-o"></i>'),i.toLowerCase().endsWith(".mpeg")&&(s='<i class="fa fa-file-video-o"></i>'),i.toLowerCase().endsWith(".mp4")&&(s='<i class="fa fa-file-video-o"></i>'),i.toLowerCase().endsWith(".mvk")&&(s='<i class="fa fa-file-video-o"></i>'),i.toLowerCase().endsWith(".webm")&&(s='<i class="fa fa-file-video-o"></i>'),i.toLowerCase().endsWith(".wav")&&(s='<i class="fa fa-file-audio-o"></i>'),i.toLowerCase().endsWith(".mp3")&&(s='<i class="fa fa-file-audio-o"></i>'),i.toLowerCase().endsWith(".ogg")&&(s='<i class="fa fa-file-audio-o"></i>'),i.toLowerCase().endsWith(".zip")&&(s='<i class="fa fa-file-archive-o"></i>'),i.toLowerCase().endsWith(".rar")&&(s='<i class="fa fa-file-archive-o"></i>'),i.toLowerCase().endsWith(".tar.gz")&&(s='<i class="fa fa-file-archive-o"></i>'),i.toLowerCase().endsWith(".pdf")&&(s='<i class="fa fa-file-pdf-o"></i>');var r='<DIV><SPAN id="FileUpload-'+a+'">Sending</SPAN>: '+s+" "+i+"</DIV>";r+='<DIV id="FileProgress-'+a+'" class="progressBarContainer"><DIV id="FileProgress-Bar-'+a+'" class="progressBarTrack"></DIV></DIV>',l&&(r+='<DIV><IMG class=previewImage onClick="PreviewImage(this)" src="'+t+'"></DIV>');var d='<table class="ourChatMessage chatMessageTable" cellspacing=0 cellpadding=0><tr><td style="width: 80px"><div class=messageDate>'+o+"</div></td><td><div class=ourChatMessageText>"+r+"</div></td></tr></table>";$("#contact-"+e+"-ChatHistory").append(d),updateScroll(e),ImageEditor_Cancel(e),UpdateBuddyActivity(e)}}function updateLineScroll(e){RefreshLineActivity(e);var t=$("#line-"+e+"-CallDetails").get(0);t.scrollTop=t.scrollHeight}function updateScroll(e){var t=$("#contact-"+e+"-ChatHistory");t.children().length>0&&t.children().last().get(0).scrollIntoView(!1),t.get(0).scrollTop=t.get(0).scrollHeight}function PreviewImage(e){$.jeegoopopup.close();var t="<div>";t+='<div class="UiWindowField scroller">',t+='<div><img src="'+e.src+'"/></div>',t+="</div></div>",$.jeegoopopup.open({title:"Preview Image",html:t,width:"800",height:"600",center:!0,scrolling:"no",skinClass:"jg_popup_basic",overlay:!0,opacity:50,draggable:!0,resizable:!1,fadeIn:0}),$("#jg_popup_overlay").click((function(){$.jeegoopopup.close()})),$(window).on("keydown",(function(e){"Escape"==e.key&&$.jeegoopopup.close()}))}function IncreaseMissedBadge(e){var t=FindBuddyByIdentity(e);if(null!=t){t.missed+=1;var i=JSON.parse(localDB.getItem(profileUserID+"-Buddies"));null!=i&&($.each(i.DataCollection,(function(t,i){if(i.uID==e||i.cID==e||i.gID==e)return i.missed=i.missed+1,!1})),localDB.setItem(profileUserID+"-Buddies",JSON.stringify(i))),$("#contact-"+e+"-missed").text(t.missed),$("#contact-"+e+"-missed").show(),console.log("Set Missed badge for "+e+" to: "+t.missed)}}function UpdateBuddyActivity(e){var t=FindBuddyByIdentity(e);if(null!=t){var i=utcDateNow();t.lastActivity=i,console.log("Last Activity is now: "+i);var n=JSON.parse(localDB.getItem(profileUserID+"-Buddies"));null!=n&&($.each(n.DataCollection,(function(t,n){if(n.uID==e||n.cID==e||n.gID==e)return n.LastActivity=i,!1})),localDB.setItem(profileUserID+"-Buddies",JSON.stringify(n))),UpdateBuddyList()}}function ClearMissedBadge(e){var t=FindBuddyByIdentity(e);if(null!=t){t.missed=0;var i=JSON.parse(localDB.getItem(profileUserID+"-Buddies"));null!=i&&($.each(i.DataCollection,(function(t,i){if(i.uID==e||i.cID==e||i.gID==e)return i.missed=0,!1})),localDB.setItem(profileUserID+"-Buddies",JSON.stringify(i))),$("#contact-"+e+"-missed").text(t.missed),$("#contact-"+e+"-missed").hide(400)}}function VideoCall(e,t){if(null!=userAgent&&userAgent.isRegistered()&&null!=e)if(0!=HasAudioDevice){if(0==HasVideoDevice)return console.warn("No video devices (webcam) found, switching to audio call."),void AudioCall(e,t);var i=navigator.mediaDevices.getSupportedConstraints(),n={sessionDescriptionHandlerOptions:{constraints:{audio:{deviceId:"default"},video:{deviceId:"default"}}}},a=getAudioSrcID();if("default"!=a){for(var o=!1,l=0;l<AudioinputDevices.length;++l)if(a==AudioinputDevices[l].deviceId){o=!0;break}o?n.sessionDescriptionHandlerOptions.constraints.audio.deviceId={exact:a}:(console.warn("The audio device you used before is no longer available, default settings applied."),localDB.setItem("AudioSrcId","default"))}i.autoGainControl&&(n.sessionDescriptionHandlerOptions.constraints.audio.autoGainControl=AutoGainControl),i.echoCancellation&&(n.sessionDescriptionHandlerOptions.constraints.audio.echoCancellation=EchoCancellation),i.noiseSuppression&&(n.sessionDescriptionHandlerOptions.constraints.audio.noiseSuppression=NoiseSuppression);var s=getVideoSrcID();if("default"!=s){var r=!1;for(l=0;l<VideoinputDevices.length;++l)if(s==VideoinputDevices[l].deviceId){r=!0;break}r?n.sessionDescriptionHandlerOptions.constraints.video.deviceId={exact:s}:(console.warn("The video device you used before is no longer available, default settings applied."),localDB.setItem("VideoSrcId","default"))}i.frameRate&&""!=maxFrameRate&&(n.sessionDescriptionHandlerOptions.constraints.video.frameRate=maxFrameRate),i.height&&""!=videoHeight&&(n.sessionDescriptionHandlerOptions.constraints.video.height=videoHeight),console.log(i),console.log(i.aspectRatio),console.log(videoAspectRatio),i.aspectRatio&&""!=videoAspectRatio&&(n.sessionDescriptionHandlerOptions.constraints.video.aspectRatio=videoAspectRatio),$("#line-"+e.LineNumber+"-msg").html(lang.starting_video_call),$("#line-"+e.LineNumber+"-timer").show(),console.log("INVITE (video): "+t+"@"+wssServer,n),e.SipSession=userAgent.invite("sip:"+t+"@"+wssServer,n);var d=moment.utc();e.SipSession.data.line=e.LineNumber,e.SipSession.data.buddyId=e.BuddyObj.identity,e.SipSession.data.calldirection="outbound",e.SipSession.data.dst=t,e.SipSession.data.callstart=d.format("YYYY-MM-DD HH:mm:ss UTC"),e.SipSession.data.callTimer=window.setInterval((function(){var t=moment.utc(),i=moment.duration(t.diff(d));$("#line-"+e.LineNumber+"-timer").html(formatShortDuration(i.asSeconds()))}),1e3),e.SipSession.data.VideoSourceDevice=getVideoSrcID(),e.SipSession.data.AudioSourceDevice=getAudioSrcID(),e.SipSession.data.AudioOutputDevice=getAudioOutputID(),e.SipSession.data.terminateby="them",e.SipSession.data.withvideo=!0,updateLineScroll(e.LineNumber),wireupVideoSession(e),"undefined"!=typeof web_hook_on_invite&&web_hook_on_invite(e.SipSession)}else Alert(lang.alert_no_microphone)}function ComposeEmail(e,t,i){i.stopPropagation(),SelectBuddy(e);var n=FindBuddyByIdentity(e);$("#roundcubeFrame").remove(),$("#rightContent").show(),$(".streamSelected").each((function(){$(this).css("display","none")})),$("#rightContent").append('<iframe id="roundcubeFrame" name="displayFrame"></iframe>');var a="",o="",l="",s="",r="";if($.ajax({async:!1,global:!1,type:"POST",url:"get-email-info.php",dataType:"JSON",data:{username:userName,s_ajax_call:validateSToken},success:function(e){a=e.rcdomain,o=encodeURIComponent(e.rcbasicauthuser),l=encodeURIComponent(e.rcbasicauthpass),s=e.rcuser,r=e.rcpassword},error:function(e){alert("An error occurred while trying to retrieve data from the database!")}}),""!=o&&""!=l)var d="https://"+o+":"+l+"@"+a+"/",c="https://"+o+":"+l+"@"+a+"/?_task=mail&_action=compose&_to="+encodeURIComponent(n.Email);else d="https://"+a+"/",c="https://"+a+"/?_task=mail&_action=compose&_to="+encodeURIComponent(n.Email);var u='<form id="rcForm" method="POST" action="'+d+'" target="displayFrame">';u+='<input type="hidden" name="_action" value="login" />',u+='<input type="hidden" name="_task" value="login" />',u+='<input type="hidden" name="_autologin" value="1" />',u+='<input name="_user" value="'+s+'" type="text" />',u+='<input name="_pass" value="'+r+'" type="password" />',u+='<input id="submitButton" type="submit" value="Login" />',u+="</form>",$("#roundcubeFrame").append(u),0==RCLoginCheck?($("#submitButton").click(),RCLoginCheck=1,""!=o&&""!=l?confirm('You are about to log in to the site "'+a+'" with the username "'+o+'".')&&$("#roundcubeFrame").attr("src",c):setTimeout((function(){$("#roundcubeFrame").attr("src",c)}),1e3)):$("#roundcubeFrame").attr("src",c)}function AudioCallMenu(e,t){if($(window).width()-event.pageX>54)var i=event.pageX-222;else i=event.pageX-276;if($(window).height()-event.pageY>140)var n=event.pageY+27;else n=event.pageY-80;var a=FindBuddyByIdentity(e);if("extension"==a.type){var o="<div id=quickCallMenu>";o+='<table id=quickCallTable cellspacing=10 cellpadding=0 style="margin-left:auto; margin-right: auto">',o+='<tr class=quickNumDialRow><td><i class="fa fa-phone-square"></i></td><td>'+lang.call_extension+"</td><td><span class=quickNumToDial>"+a.ExtNo+"</span></td></tr>",null!=a.MobileNumber&&""!=a.MobileNumber&&(o+='<tr class=quickNumDialRow><td><i class="fa fa-mobile"></i></td><td>'+lang.call_mobile+"</td><td><span class=quickNumToDial>"+a.MobileNumber+"</span></td></tr>"),null!=a.ContactNumber1&&""!=a.ContactNumber1&&(o+='<tr class=quickNumDialRow><td><i class="fa fa-phone"></i></td><td>'+lang.call_number+"</td><td><span class=quickNumToDial>"+a.ContactNumber1+"</span></td></tr>"),null!=a.ContactNumber2&&""!=a.ContactNumber2&&(o+='<tr class=quickNumDialRow><td><i class="fa fa-phone"></i></td><td>'+lang.call_number+"</td><td><span class=quickNumToDial>"+a.ContactNumber2+"</span></td></tr>"),o+="</table>",o+="</div>";var l="Menu click AudioCall("+e+", "}else if("contact"==a.type){o="<div id=quickCallMenu>";o+='<table id=quickCallTable cellspacing=10 cellpadding=0 style="margin-left:auto; margin-right: auto">',null!=a.MobileNumber&&""!=a.MobileNumber&&(o+='<tr class=quickNumDialRow><td><i class="fa fa-mobile"></i></td><td>'+lang.call_mobile+"</td><td><span class=quickNumToDial>"+a.MobileNumber+"</span></td></tr>"),null!=a.ContactNumber1&&""!=a.ContactNumber1&&(o+='<tr class=quickNumDialRow><td><i class="fa fa-phone"></i></td><td>'+lang.call_number+"</td><td><span class=quickNumToDial>"+a.ContactNumber1+"</span></td></tr>"),null!=a.ContactNumber2&&""!=a.ContactNumber2&&(o+='<tr class=quickNumDialRow><td><i class="fa fa-phone"></i></td><td>'+lang.call_number+"</td><td><span class=quickNumToDial>"+a.ContactNumber2+"</span></td></tr>"),o+="</table>",o+="</div>";l="Menu click AudioCall("+e+", "}else if("group"==a.type){o="<div id=quickCallMenu>";o+='<table id=quickCallTable cellspacing=10 cellpadding=0 style="margin-left:auto; margin-right: auto">',o+='<tr class=quickNumDialRow><td><i class="fa fa-users"></i></td><td>'+lang.call_group+"</td><td><span class=quickNumToDial>"+a.ExtNo+"</span></td></tr>",o+="</table>",o+="</div>";l="Menu click AudioCallGroup("+e+", "}$.jeegoopopup.open({html:o,width:"auto",height:"auto",left:i,top:n,scrolling:"no",skinClass:"jg_popup_basic",overlay:!0,opacity:0,draggable:!1,resizable:!1,fadeIn:0}),$("#quickCallTable").on("click",".quickNumDialRow",(function(){var t=$(this).closest("tr").find("span.quickNumToDial").html();console.log(l+t+")"),DialByLine("audio",e,t)})),$("#jg_popup_overlay").click((function(){$.jeegoopopup.close()})),$(window).on("keydown",(function(e){"Escape"==e.key&&$.jeegoopopup.close()}))}function AudioCall(e,t){if(null!=userAgent&&0!=userAgent.isRegistered()&&null!=e)if(0!=HasAudioDevice){var i=navigator.mediaDevices.getSupportedConstraints(),n={sessionDescriptionHandlerOptions:{constraints:{audio:{deviceId:"default"},video:!1}}},a=getAudioSrcID();if("default"!=a){for(var o=!1,l=0;l<AudioinputDevices.length;++l)if(a==AudioinputDevices[l].deviceId){o=!0;break}o?n.sessionDescriptionHandlerOptions.constraints.audio.deviceId={exact:a}:(console.warn("The audio device you used before is no longer available, default settings applied."),localDB.setItem("AudioSrcId","default"))}i.autoGainControl&&(n.sessionDescriptionHandlerOptions.constraints.audio.autoGainControl=AutoGainControl),i.echoCancellation&&(n.sessionDescriptionHandlerOptions.constraints.audio.echoCancellation=EchoCancellation),i.noiseSuppression&&(n.sessionDescriptionHandlerOptions.constraints.audio.noiseSuppression=NoiseSuppression),$("#line-"+e.LineNumber+"-msg").html(lang.starting_audio_call),$("#line-"+e.LineNumber+"-timer").show(),console.log("INVITE (audio): "+t+"@"+wssServer),e.SipSession=userAgent.invite("sip:"+t+"@"+wssServer,n);var s=moment.utc();e.SipSession.data.line=e.LineNumber,e.SipSession.data.buddyId=e.BuddyObj.identity,e.SipSession.data.calldirection="outbound",e.SipSession.data.dst=t,e.SipSession.data.callstart=s.format("YYYY-MM-DD HH:mm:ss UTC"),e.SipSession.data.callTimer=window.setInterval((function(){var t=moment.utc(),i=moment.duration(t.diff(s));$("#line-"+e.LineNumber+"-timer").html(formatShortDuration(i.asSeconds()))}),1e3),e.SipSession.data.VideoSourceDevice=null,e.SipSession.data.AudioSourceDevice=getAudioSrcID(),e.SipSession.data.AudioOutputDevice=getAudioOutputID(),e.SipSession.data.terminateby="them",e.SipSession.data.withvideo=!1,updateLineScroll(e.LineNumber),wireupAudioSession(e),"undefined"!=typeof web_hook_on_invite&&web_hook_on_invite(e.SipSession)}else Alert(lang.alert_no_microphone)}function getSession(e){if(null!=userAgent){if(0!=userAgent.isRegistered()){var t=null;return $.each(userAgent.sessions,(function(i,n){if(n.data.buddyId==e)return t=n,!1})),t}console.warn("userAgent is not registered")}else console.warn("userAgent is null")}function countSessions(e){var t=0;return null==userAgent?(console.warn("userAgent is null"),0):($.each(userAgent.sessions,(function(i,n){e!=n.id&&t++})),t)}function StartRecording(e){if("disabled"!=CallRecordingPolicy){var t=FindLineByNumber(e);if(null!=t){$("#line-"+t.LineNumber+"-btn-start-recording").hide(),$("#line-"+t.LineNumber+"-btn-stop-recording").show();var i=t.SipSession;if(null!=i){var n=uID();if(i.data.recordings||(i.data.recordings=[]),i.data.recordings.push({uID:n,startTime:utcDateNow(),stopTime:utcDateNow()}),i.data.mediaRecorder)"inactive"==i.data.mediaRecorder.state?(i.data.mediaRecorder.data={},i.data.mediaRecorder.data.id=""+n,i.data.mediaRecorder.data.sessionId=""+i.id,i.data.mediaRecorder.data.buddyId=""+t.BuddyObj.identity,console.log("Starting Call Recording",n),i.data.mediaRecorder.start(),i.data.recordings[i.data.recordings.length-1].startTime=utcDateNow(),$("#line-"+t.LineNumber+"-msg").html(lang.call_recording_started),updateLineScroll(e)):console.warn("Recorder is in an unknown state");else{console.log("Creating call recorder...");var a=new MediaStream,o=i.sessionDescriptionHandler.peerConnection;if(o.getSenders().forEach((function(e){e.track&&"audio"==e.track.kind&&(console.log("Adding sender audio track to record:",e.track.label),a.addTrack(e.track))})),o.getReceivers().forEach((function(e){e.track&&"audio"==e.track.kind&&(console.log("Adding receiver audio track to record:",e.track.label),a.addTrack(e.track)),i.data.withvideo&&e.track&&"video"==e.track.kind&&(console.log("Adding receiver video track to record:",e.track.label),a.addTrack(e.track))})),i.data.withvideo){var l=640,s=360,r=100;"HD"==RecordingVideoSize&&(l=1280,s=720,r=144),"FHD"==RecordingVideoSize&&(l=1920,s=1080,r=240);var d=$("#line-"+t.LineNumber+"-localVideo").get(0),c=$("#line-"+t.LineNumber+"-remoteVideo").get(0);"us-pnp"==RecordingLayout&&(d=$("#line-"+t.LineNumber+"-remoteVideo").get(0),c=$("#line-"+t.LineNumber+"-localVideo").get(0));var u=$("<canvas/>").get(0);u.width="side-by-side"==RecordingLayout?2*l+5:l,u.height=s;var p=u.getContext("2d");window.clearInterval(i.data.recordingRedrawInterval),i.data.recordingRedrawInterval=window.setInterval((function(){var e=c.videoWidth>0?c.videoWidth:l,t=c.videoHeight>0?c.videoHeight:s;if(e>=t){var i=l/e;if(e=l,(t*=i)>s){i=s/t;t=s,e*=i}}else{i=s/t;t=s,e*=i}var n=e<l?(l-e)/2:0,a=t<s?(s-t)/2:0;"side-by-side"==RecordingLayout&&(n=l+5+n);var o=d.videoHeight,g=d.videoWidth;if(o>0)if(g>=o){i=r/o;o=r,g*=i}else{i=r/g;g=r,o*=i}var m=10,f=10;if("side-by-side"==RecordingLayout){if((g=d.videoWidth)>=(o=d.videoHeight)){i=l/g;if(g=l,(o*=i)>s){i=s/o;o=s,g*=i}}else{i=s/o;o=s,g*=i}m=g<l?(l-g)/2:0,f=o<s?(s-o)/2:0}p.fillRect(0,0,u.width,u.height),c.videoHeight>0&&p.drawImage(c,n,a,e,t),d.videoHeight>0&&("side-by-side"==RecordingLayout||"us-pnp"==RecordingLayout||"them-pnp"==RecordingLayout)&&p.drawImage(d,m,f,g,o)}),Math.floor(1e3/RecordingVideoFps));var g=u.captureStream(RecordingVideoFps)}var m=new MediaStream;m.addTrack(MixAudioStreams(a).getAudioTracks()[0]),i.data.withvideo&&m.addTrack(g.getVideoTracks()[0]);var f="audio/webm";i.data.withvideo&&(f="video/webm");var v=new MediaRecorder(m,{mimeType:f});v.data={},v.data.id=""+n,v.data.sessionId=""+i.id,v.data.buddyId=""+t.BuddyObj.identity,v.ondataavailable=function(e){console.log("Got Call Recording Data: ",e.data.size+"Bytes",this.data.id,this.data.buddyId,this.data.sessionId),SaveCallRecording(e.data,this.data.id,this.data.buddyId,this.data.sessionId)},console.log("Starting Call Recording",n),i.data.mediaRecorder=v,i.data.mediaRecorder.start(),i.data.recordings[i.data.recordings.length-1].startTime=utcDateNow(),$("#line-"+t.LineNumber+"-msg").html(lang.call_recording_started),updateLineScroll(e)}}else console.warn("Could not find session")}}else console.warn("Policy Disabled: Call Recording")}function SaveCallRecording(e,t,i,n){var a=window.indexedDB.open("CallRecordings");a.onerror=function(e){console.error("IndexDB Request Error:",e)},a.onupgradeneeded=function(e){console.warn("Upgrade Required for IndexDB... probably because of first time use.");var t=e.target.result;if(0==t.objectStoreNames.contains("Recordings")){var i=t.createObjectStore("Recordings",{keyPath:"uID"});i.createIndex("sessionid","sessionid",{unique:!1}),i.createIndex("bytes","bytes",{unique:!1}),i.createIndex("type","type",{unique:!1}),i.createIndex("mediaBlob","mediaBlob",{unique:!1})}else console.warn("IndexDB requested upgrade, but object store was in place")},a.onsuccess=function(a){console.log("IndexDB connected to CallRecordings");var o=a.target.result;if(0!=o.objectStoreNames.contains("Recordings")){o.onerror=function(e){console.error("IndexDB Error:",e)};var l={uID:t,sessionid:n,bytes:e.size,type:e.type,mediaBlob:e};o.transaction(["Recordings"],"readwrite").objectStore("Recordings").add(l).onsuccess=function(a){console.log("Call Recording Sucess: ",t,e.size,e.type,i,n)}}else console.warn("IndexDB CallRecordings.Recordings does not exists")}}function StopRecording(e,t){var i=FindLineByNumber(e);if(null!=i&&null!=i.SipSession){var n=i.SipSession;if(1==t)return $("#line-"+i.LineNumber+"-btn-start-recording").show(),$("#line-"+i.LineNumber+"-btn-stop-recording").hide(),void(n.data.mediaRecorder&&("recording"==n.data.mediaRecorder.state?(console.log("Stopping Call Recording"),n.data.mediaRecorder.stop(),n.data.recordings[n.data.recordings.length-1].stopTime=utcDateNow(),window.clearInterval(n.data.recordingRedrawInterval),$("#line-"+i.LineNumber+"-msg").html(lang.call_recording_stopped),updateLineScroll(e)):console.warn("Recorder is in an unknow state")));"enabled"==CallRecordingPolicy&&console.log("Policy Enabled: Call Recording"),Confirm(lang.confirm_stop_recording,lang.stop_recording,(function(){$("#line-"+i.LineNumber+"-btn-start-recording").show(),$("#line-"+i.LineNumber+"-btn-stop-recording").hide(),n.data.mediaRecorder&&("recording"==n.data.mediaRecorder.state?(console.log("Stopping Call Recording"),n.data.mediaRecorder.stop(),n.data.recordings[n.data.recordings.length-1].stopTime=utcDateNow(),window.clearInterval(n.data.recordingRedrawInterval),$("#line-"+i.LineNumber+"-msg").html(lang.call_recording_stopped),updateLineScroll(e)):console.warn("Recorder is in an unknow state"))}))}}function PlayAudioCallRecording(e,t,i){var n=$(e).parent();n.empty();var a=new Audio;a.autoplay=!1,a.controls=!0;var o=getAudioOutputID();void 0!==a.sinkId?a.setSinkId(o).then((function(){console.log("sinkId applied: "+o)})).catch((function(e){console.warn("Error using setSinkId: ",e)})):console.warn("setSinkId() is not possible using this browser."),n.append(a);var l=window.indexedDB.open("CallRecordings");l.onerror=function(e){console.error("IndexDB Request Error:",e)},l.onupgradeneeded=function(e){console.warn("Upgrade Required for IndexDB... probably because of first time use.")},l.onsuccess=function(e){console.log("IndexDB connected to CallRecordings");var n=e.target.result;if(0!=n.objectStoreNames.contains("Recordings")){var o=n.transaction(["Recordings"]).objectStore("Recordings").get(i);o.onerror=function(e){console.error("IndexDB Get Error:",e)},o.onsuccess=function(e){$("#cdr-media-meta-size-"+t+"-"+i).html(" Size: "+formatBytes(e.target.result.bytes)),$("#cdr-media-meta-codec-"+t+"-"+i).html(" Codec: "+e.target.result.type),a.src=window.URL.createObjectURL(e.target.result.mediaBlob),a.oncanplaythrough=function(){a.play().then((function(){console.log("Playback started")})).catch((function(e){console.error("Error playing back file: ",e)}))}}}else console.warn("IndexDB CallRecordings.Recordings does not exists")}}function PlayVideoCallRecording(e,t,i,n){var a=$(e).parent();a.empty();var o=$("<video>").get(0);o.id="callrecording-video-"+t,o.autoplay=!1,o.controls=!0,o.ontimeupdate=function(e){$("#cdr-video-meta-width-"+t+"-"+i).html(lang.width+" : "+e.target.videoWidth+"px"),$("#cdr-video-meta-height-"+t+"-"+i).html(lang.height+" : "+e.target.videoHeight+"px")};var l=getAudioOutputID();void 0!==o.sinkId?o.setSinkId(l).then((function(){console.log("sinkId applied: "+l)})).catch((function(e){console.warn("Error using setSinkId: ",e)})):console.warn("setSinkId() is not possible using this browser."),a.append(o);var s=window.indexedDB.open("CallRecordings");s.onerror=function(e){console.error("IndexDB Request Error:",e)},s.onupgradeneeded=function(e){console.warn("Upgrade Required for IndexDB... probably because of first time use.")},s.onsuccess=function(e){console.log("IndexDB connected to CallRecordings");var a=e.target.result;if(0!=a.objectStoreNames.contains("Recordings")){var l=a.transaction(["Recordings"]).objectStore("Recordings").get(i);l.onerror=function(e){console.error("IndexDB Get Error:",e)},l.onsuccess=function(e){$("#cdr-media-meta-size-"+t+"-"+i).html(" Size: "+formatBytes(e.target.result.bytes)),$("#cdr-media-meta-codec-"+t+"-"+i).html(" Codec: "+e.target.result.type),o.src=window.URL.createObjectURL(e.target.result.mediaBlob),o.oncanplaythrough=function(){try{o.scrollIntoViewIfNeeded(!1)}catch(e){}o.play().then((function(){console.log("Playback started")})).catch((function(e){console.error("Error playing back file: ",e)})),n&&window.setTimeout((function(){var e=$("<canvas>").get(0),a=o.videoWidth,l=o.videoHeight;if(a>l){if(l>225){var s=225/l;l=225,a*=s}}else if(l>225){s=225/a;a=225,l*=s}e.width=a,e.height=l,e.getContext("2d").drawImage(o,0,0,a,l),e.toBlob((function(e){var o=new FileReader;o.readAsDataURL(e),o.onloadend=function(){var e={width:a,height:l,posterBase64:o.result};console.log("Capturing Video Poster...");var s=JSON.parse(localDB.getItem(n+"-stream"));null==s&&null==s.DataCollection||($.each(s.DataCollection,(function(n,a){if("CDR"==a.ItemType&&a.CdrId==t)return a.Recordings&&a.Recordings.length>=1&&$.each(a.Recordings,(function(t,n){n.uID==i&&(n.Poster=e)})),!1})),localDB.setItem(n+"-stream",JSON.stringify(s)),console.log("Capturing Video Poster, Done"))}}),"image/jpeg",PosterJpegQuality)}),1e3)}}}else console.warn("IndexDB CallRecordings.Recordings does not exists")}}function MixAudioStreams(e){var t=null;try{window.AudioContext=window.AudioContext||window.webkitAudioContext,t=new AudioContext}catch(t){return console.warn("AudioContext() not available, cannot record"),e}var i=t.createMediaStreamDestination();return e.getAudioTracks().forEach((function(e){var n=new MediaStream;n.addTrack(e),t.createMediaStreamSource(n).connect(i)})),i.stream}function QuickFindBuddy(e){$.jeegoopopup.close();var t=e.offsetWidth+178,i=e.offsetHeight+68;$(window).width()<1467&&(i=e.offsetHeight+164,$(window).width()<918&&(t=e.offsetWidth-140,$(window).width()<690&&(t=e.offsetWidth-70,i=e.offsetHeight+164)));var n=e.value;if(""!=n){console.log("Find Buddy: ",n),Buddies.sort((function(e,t){return e.CallerIDName<t.CallerIDName?-1:e.CallerIDName>t.CallerIDName?1:0}));var a=0,o='<div id="quickSearchBuddy">';o+='<table id="quickSearchBdTable" cellspacing=10 cellpadding=0 style="margin-left:auto; margin-right: auto">';for(var l=0;l<Buddies.length;l++){var s=Buddies[l],r=!1;if(s.CallerIDName.toLowerCase().indexOf(n.toLowerCase())>-1&&(r=!0),s.ExtNo.toLowerCase().indexOf(n.toLowerCase())>-1&&(r=!0),s.Desc.toLowerCase().indexOf(n.toLowerCase())>-1&&(r=!0),s.MobileNumber.toLowerCase().indexOf(n.toLowerCase())>-1&&(r=!0),s.ContactNumber1.toLowerCase().indexOf(n.toLowerCase())>-1&&(r=!0),s.ContactNumber2.toLowerCase().indexOf(n.toLowerCase())>-1&&(r=!0),r){var d="#404040";"Unknown"!=s.presence&&"Not online"!=s.presence&&"Unavailable"!=s.presence||(d="#666666"),"Ready"==s.presence&&(d="#3fbd3f"),"On the phone"!=s.presence&&"Ringing"!=s.presence&&"On hold"!=s.presence||(d="#c99606"),o+='<tr class="quickFindBdTagRow"><td></td><td><b>'+s.CallerIDName+"</b></td><td></td></tr>",""!=s.ExtNo&&(o+='<tr class="quickFindBdRow"><td><i class="fa fa-phone-square" style="color:'+d+'"></i></td><td>'+lang.extension+" ("+s.presence+')</td><td><span class="quickNumFound">'+s.ExtNo+"</span></td></tr>"),""!=s.MobileNumber&&(o+='<tr class="quickFindBdRow"><td><i class="fa fa-mobile"></i></td><td>'+lang.mobile+'</td><td><span class="quickNumFound">'+s.MobileNumber+"</span></td></tr>"),""!=s.ContactNumber1&&(o+='<tr class="quickFindBdRow"><td><i class="fa fa-phone"></i></td><td>'+lang.contact_number_1+'</td><td><span class="quickNumFound">'+s.ContactNumber1+"</span></td></tr>"),""!=s.ContactNumber2&&(o+='<tr class="quickFindBdRow"><td><i class="fa fa-phone"></i></td><td>'+lang.contact_number_2+'</td><td><span class="quickNumFound">'+s.ContactNumber2+"</span></td></tr>"),a++}if(a>=5)break}(o+="</table></div>").length>1&&($.jeegoopopup.open({html:o,width:"auto",height:"auto",left:t,top:i,scrolling:"no",skinClass:"jg_popup_basic",overlay:!0,opacity:0,draggable:!1,resizable:!1,fadeIn:0}),$("#jg_popup_inner").focus(),$("#jg_popup_inner #jg_popup_content #quickSearchBuddy #quickSearchBdTable").on("click",".quickFindBdRow",(function(){var e=$(this).closest("tr").find("span.quickNumFound").html();$.jeegoopopup.close(),$(document).find("input[id*='-txt-FindTransferBuddy']").focus(),$(document).find("input[id*='-txt-FindTransferBuddy']").val(e)})),$("#jg_popup_overlay").click((function(){$.jeegoopopup.close()})),$(window).on("keydown",(function(e){"Escape"==e.key&&$.jeegoopopup.close()})))}}function StartTransferSession(e){$("#line-"+e+"-btn-Transfer").hide(),$("#line-"+e+"-btn-CancelTransfer").show(),holdSession(e),$("#line-"+e+"-txt-FindTransferBuddy").val(""),$("#line-"+e+"-txt-FindTransferBuddy").parent().show(),$("#line-"+e+"-btn-blind-transfer").show(),$("#line-"+e+"-btn-attended-transfer").show(),$("#line-"+e+"-btn-complete-transfer").hide(),$("#line-"+e+"-btn-cancel-transfer").hide(),$("#line-"+e+"-transfer-status").hide(),$("#line-"+e+"-Transfer").show(),updateLineScroll(e)}function CancelTransferSession(e){var t=FindLineByNumber(e);if(null!=t&&null!=t.SipSession){var i=t.SipSession;if(i.data.childsession){console.log("Child Transfer call detected:",i.data.childsession.status);try{i.data.childsession.status==SIP.Session.C.STATUS_CONFIRMED?i.data.childsession.bye():i.data.childsession.cancel()}catch(e){}}$("#line-"+e+"-btn-Transfer").show(),$("#line-"+e+"-btn-CancelTransfer").hide(),unholdSession(e),$("#line-"+e+"-Transfer").hide(),updateLineScroll(e)}else console.warn("Null line or session")}function BlindTransfer(e){var t=$("#line-"+e+"-txt-FindTransferBuddy").val().replace(/[^0-9\*\#\+]/g,"");if(""!=t){var i=FindLineByNumber(e);if(null!=i&&null!=i.SipSession){var n=i.SipSession;n.data.transfer||(n.data.transfer=[]),n.data.transfer.push({type:"Blind",to:t,transferTime:utcDateNow(),disposition:"refer",dispositionTime:utcDateNow(),accept:{complete:null,eventTime:null,disposition:""}});var a=n.data.transfer.length-1,o={receiveResponse:function(t){console.log("Blind transfer response: ",t.reason_phrase),n.data.terminateby="refer",n.data.transfer[a].accept.disposition=t.reason_phrase,n.data.transfer[a].accept.eventTime=utcDateNow(),$("#line-"+e+"-msg").html("Call Blind Transfered (Accepted)"),updateLineScroll(e)}};console.log("REFER: ",t+"@"+wssServer),n.refer("sip:"+t+"@"+wssServer,o),$("#line-"+e+"-msg").html(lang.call_blind_transfered),updateLineScroll(e)}else console.warn("Null line or session")}else console.warn("Cannot transfer, must be [0-9*+#]")}function AttendedTransfer(e){var t=$("#line-"+e+"-txt-FindTransferBuddy").val().replace(/[^0-9\*\#\+]/g,"");if(""!=t){var i=FindLineByNumber(e);if(null!=i&&null!=i.SipSession){var n=i.SipSession;$.jeegoopopup.close(),$("#line-"+e+"-txt-FindTransferBuddy").parent().hide(),$("#line-"+e+"-btn-blind-transfer").hide(),$("#line-"+e+"-btn-attended-transfer").hide(),$("#line-"+e+"-btn-complete-attended-transfer").hide(),$("#line-"+e+"-btn-cancel-attended-transfer").hide(),$("#line-"+e+"-btn-terminate-attended-transfer").hide();var a=$("#line-"+e+"-transfer-status");a.html(lang.connecting),a.show(),n.data.transfer||(n.data.transfer=[]),n.data.transfer.push({type:"Attended",to:t,transferTime:utcDateNow(),disposition:"invite",dispositionTime:utcDateNow(),accept:{complete:null,eventTime:null,disposition:""}});var o=n.data.transfer.length-1;updateLineScroll(e);var l=navigator.mediaDevices.getSupportedConstraints(),s={sessionDescriptionHandlerOptions:{constraints:{audio:{deviceId:"default"},video:!1}}};"default"!=n.data.AudioSourceDevice&&(s.sessionDescriptionHandlerOptions.constraints.audio.deviceId={exact:n.data.AudioSourceDevice}),l.autoGainControl&&(s.sessionDescriptionHandlerOptions.constraints.audio.autoGainControl=AutoGainControl),l.echoCancellation&&(s.sessionDescriptionHandlerOptions.constraints.audio.echoCancellation=EchoCancellation),l.noiseSuppression&&(s.sessionDescriptionHandlerOptions.constraints.audio.noiseSuppression=NoiseSuppression),n.data.withvideo&&(s.sessionDescriptionHandlerOptions.constraints.video=!0,"default"!=n.data.VideoSourceDevice&&(s.sessionDescriptionHandlerOptions.constraints.video.deviceId={exact:n.data.VideoSourceDevice}),l.frameRate&&""!=maxFrameRate&&(s.sessionDescriptionHandlerOptions.constraints.video.frameRate=maxFrameRate),l.height&&""!=videoHeight&&(s.sessionDescriptionHandlerOptions.constraints.video.height=videoHeight),l.aspectRatio&&""!=videoAspectRatio&&(s.sessionDescriptionHandlerOptions.constraints.video.aspectRatio=videoAspectRatio)),console.log("INVITE: ","sip:"+t+"@"+wssServer);var r=userAgent.invite("sip:"+t+"@"+wssServer,s);n.data.childsession=r,r.on("progress",(function(t){a.html(lang.ringing),n.data.transfer[o].disposition="progress",n.data.transfer[o].dispositionTime=utcDateNow(),$("#line-"+e+"-msg").html(lang.attended_transfer_call_started);var i=$("#line-"+e+"-btn-cancel-attended-transfer");i.off("click"),i.on("click",(function(){r.cancel(),a.html(lang.call_cancelled),console.log("New call session canceled"),n.data.transfer[o].accept.complete=!1,n.data.transfer[o].accept.disposition="cancel",n.data.transfer[o].accept.eventTime=utcDateNow(),$("#line-"+e+"-msg").html(lang.attended_transfer_call_cancelled),updateLineScroll(e)})),i.show(),updateLineScroll(e)})),r.on("accepted",(function(t){a.html(lang.call_in_progress),$("#line-"+e+"-btn-cancel-attended-transfer").hide(),n.data.transfer[o].disposition="accepted",n.data.transfer[o].dispositionTime=utcDateNow();var i=$("#line-"+e+"-btn-complete-attended-transfer");i.off("click"),i.on("click",(function(){var t={receiveResponse:function(t){console.log("Attended transfer response: ",t.reason_phrase),n.data.terminateby="refer",n.data.transfer[o].accept.disposition=t.reason_phrase,n.data.transfer[o].accept.eventTime=utcDateNow(),$("#line-"+e+"-msg").html(lang.attended_transfer_complete_accepted),updateLineScroll(e)}};n.refer(r,t),a.html(lang.attended_transfer_complete),console.log("Attended transfer complete"),n.data.transfer[o].accept.complete=!0,n.data.transfer[o].accept.disposition="refer",n.data.transfer[o].accept.eventTime=utcDateNow(),$("#line-"+e+"-msg").html(lang.attended_transfer_complete),updateLineScroll(e)})),i.show(),updateLineScroll(e);var l=$("#line-"+e+"-btn-terminate-attended-transfer");l.off("click"),l.on("click",(function(){r.bye(),a.html(lang.call_ended),console.log("New call session end"),n.data.transfer[o].accept.complete=!1,n.data.transfer[o].accept.disposition="bye",n.data.transfer[o].accept.eventTime=utcDateNow(),$("#line-"+e+"-msg").html(lang.attended_transfer_call_ended),updateLineScroll(e)})),l.show(),updateLineScroll(e)})),r.on("trackAdded",(function(){var t=r.sessionDescriptionHandler.peerConnection,i=new MediaStream;t.getReceivers().forEach((function(e){e.track&&"audio"==e.track.kind&&i.addTrack(e.track)}));var a=$("#line-"+e+"-transfer-remoteAudio").get(0);a.srcObject=i,a.onloadedmetadata=function(e){void 0!==a.sinkId&&a.setSinkId(n.data.AudioOutputDevice).then((function(){console.log("sinkId applied: "+n.data.AudioOutputDevice)})).catch((function(e){console.warn("Error using setSinkId: ",e)})),a.play()}})),r.on("rejected",(function(t,i){console.log("New call session rejected: ",i),a.html(lang.call_rejected),n.data.transfer[o].disposition="rejected",n.data.transfer[o].dispositionTime=utcDateNow(),$("#line-"+e+"-txt-FindTransferBuddy").parent().show(),$("#line-"+e+"-btn-blind-transfer").show(),$("#line-"+e+"-btn-attended-transfer").show(),$("#line-"+e+"-btn-complete-attended-transfer").hide(),$("#line-"+e+"-btn-cancel-attended-transfer").hide(),$("#line-"+e+"-btn-terminate-attended-transfer").hide(),$("#line-"+e+"-msg").html(lang.attended_transfer_call_rejected),updateLineScroll(e),window.setTimeout((function(){a.hide(),updateLineScroll(e)}),1e3)})),r.on("terminated",(function(t,i){console.log("New call session terminated: ",i),a.html(lang.call_ended),n.data.transfer[o].disposition="terminated",n.data.transfer[o].dispositionTime=utcDateNow(),$("#line-"+e+"-txt-FindTransferBuddy").parent().show(),$("#line-"+e+"-btn-blind-transfer").show(),$("#line-"+e+"-btn-attended-transfer").show(),$("#line-"+e+"-btn-complete-attended-transfer").hide(),$("#line-"+e+"-btn-cancel-attended-transfer").hide(),$("#line-"+e+"-btn-terminate-attended-transfer").hide(),$("#line-"+e+"-msg").html(lang.attended_transfer_call_terminated),updateLineScroll(e),window.setTimeout((function(){a.hide(),updateLineScroll(e)}),1e3)}))}else console.warn("Null line or session")}else console.warn("Cannot transfer, must be [0-9*+#]")}function StartConferenceCall(e){$("#line-"+e+"-btn-Conference").hide(),$("#line-"+e+"-btn-CancelConference").show(),holdSession(e),$("#line-"+e+"-txt-FindConferenceBuddy").val(""),$("#line-"+e+"-txt-FindConferenceBuddy").parent().show(),$("#line-"+e+"-btn-conference-dial").show(),$("#line-"+e+"-btn-cancel-conference-dial").hide(),$("#line-"+e+"-btn-join-conference-call").hide(),$("#line-"+e+"-btn-terminate-conference-call").hide(),$("#line-"+e+"-conference-status").hide(),$("#line-"+e+"-Conference").show(),updateLineScroll(e)}function CancelConference(e){var t=FindLineByNumber(e);if(null!=t&&null!=t.SipSession){var i=t.SipSession;if(i.data.childsession)try{i.data.childsession.status==SIP.Session.C.STATUS_CONFIRMED?i.data.childsession.bye():i.data.childsession.cancel()}catch(e){}$("#line-"+e+"-btn-Conference").show(),$("#line-"+e+"-btn-CancelConference").hide(),unholdSession(e),$("#line-"+e+"-Conference").hide(),updateLineScroll(e)}else console.warn("Null line or session")}function ConferenceDial(t){var i=$("#line-"+t+"-txt-FindConferenceBuddy").val().replace(/[^0-9\*\#\+]/g,"");if(""!=i){var n=FindLineByNumber(t);if(null!=n&&null!=n.SipSession){var a=n.SipSession;$.jeegoopopup.close(),$("#line-"+t+"-txt-FindConferenceBuddy").parent().hide(),$("#line-"+t+"-btn-conference-dial").hide(),$("#line-"+t+"-btn-cancel-conference-dial"),$("#line-"+t+"-btn-join-conference-call").hide(),$("#line-"+t+"-btn-terminate-conference-call").hide();var o=$("#line-"+t+"-conference-status");o.html(lang.connecting),o.show(),a.data.confcalls||(a.data.confcalls=[]),a.data.confcalls.push({to:i,startTime:utcDateNow(),disposition:"invite",dispositionTime:utcDateNow(),accept:{complete:null,eventTime:null,disposition:""}});var l=a.data.confcalls.length-1;updateLineScroll(t);var s=navigator.mediaDevices.getSupportedConstraints(),r={sessionDescriptionHandlerOptions:{constraints:{audio:{deviceId:"default"},video:!1}}};"default"!=a.data.AudioSourceDevice&&(r.sessionDescriptionHandlerOptions.constraints.audio.deviceId={exact:a.data.AudioSourceDevice}),s.autoGainControl&&(r.sessionDescriptionHandlerOptions.constraints.audio.autoGainControl=AutoGainControl),s.echoCancellation&&(r.sessionDescriptionHandlerOptions.constraints.audio.echoCancellation=EchoCancellation),s.noiseSuppression&&(r.sessionDescriptionHandlerOptions.constraints.audio.noiseSuppression=NoiseSuppression),a.data.withvideo&&(r.sessionDescriptionHandlerOptions.constraints.video=!0,"default"!=a.data.VideoSourceDevice&&(r.sessionDescriptionHandlerOptions.constraints.video.deviceId={exact:a.data.VideoSourceDevice}),s.frameRate&&""!=maxFrameRate&&(r.sessionDescriptionHandlerOptions.constraints.video.frameRate=maxFrameRate),s.height&&""!=videoHeight&&(r.sessionDescriptionHandlerOptions.constraints.video.height=videoHeight),s.aspectRatio&&""!=videoAspectRatio&&(r.sessionDescriptionHandlerOptions.constraints.video.aspectRatio=videoAspectRatio)),console.log("INVITE: ","sip:"+i+"@"+wssServer);var d=userAgent.invite("sip:"+i+"@"+wssServer,r);a.data.childsession=d,d.on("progress",(function(e){o.html(lang.ringing),a.data.confcalls[l].disposition="progress",a.data.confcalls[l].dispositionTime=utcDateNow(),$("#line-"+t+"-msg").html(lang.conference_call_started);var i=$("#line-"+t+"-btn-cancel-conference-dial");i.off("click"),i.on("click",(function(){d.cancel(),o.html(lang.call_cancelled),console.log("New call session canceled"),a.data.confcalls[l].accept.complete=!1,a.data.confcalls[l].accept.disposition="cancel",a.data.confcalls[l].accept.eventTime=utcDateNow(),$("#line-"+t+"-msg").html(lang.canference_call_cancelled),updateLineScroll(t)})),i.show(),updateLineScroll(t)})),d.on("accepted",(function(e){o.html(lang.call_in_progress),$("#line-"+t+"-btn-cancel-conference-dial").hide(),a.data.confcalls[l].complete=!0,a.data.confcalls[l].disposition="accepted",a.data.confcalls[l].dispositionTime=utcDateNow();var i=$("#line-"+t+"-btn-join-conference-call");i.off("click"),i.on("click",(function(){if(a.data.childsession){var e=new MediaStream,n=new MediaStream,s=a.sessionDescriptionHandler.peerConnection,r=a.data.childsession.sessionDescriptionHandler.peerConnection;r.getReceivers().forEach((function(t){t.track&&"audio"==t.track.kind&&(console.log("Adding conference session:",t.track.label),e.addTrack(t.track))})),s.getReceivers().forEach((function(e){e.track&&"audio"==e.track.kind&&(console.log("Adding conference session:",e.track.label),n.addTrack(e.track))})),s.getSenders().forEach((function(t){if(t.track&&"audio"==t.track.kind){console.log("Switching to mixed Audio track on session"),a.data.AudioSourceTrack=t.track,e.addTrack(t.track);var i=MixAudioStreams(e).getAudioTracks()[0];i.IsMixedTrack=!0,t.replaceTrack(i)}})),r.getSenders().forEach((function(e){if(e.track&&"audio"==e.track.kind){console.log("Switching to mixed Audio track on conf call"),a.data.childsession.data.AudioSourceTrack=e.track,n.addTrack(e.track);var t=MixAudioStreams(n).getAudioTracks()[0];t.IsMixedTrack=!0,e.replaceTrack(t)}})),o.html(lang.call_in_progress),console.log("Conference Call In Progress"),a.data.confcalls[l].accept.complete=!0,a.data.confcalls[l].accept.disposition="join",a.data.confcalls[l].accept.eventTime=utcDateNow(),$("#line-"+t+"-btn-terminate-conference-call").show(),$("#line-"+t+"-msg").html(lang.conference_call_in_progress),unholdSession(t),i.hide(),updateLineScroll(t)}else console.warn("Conference session lost")})),i.show(),updateLineScroll(t);var n=$("#line-"+t+"-btn-terminate-conference-call");n.off("click"),n.on("click",(function(){d.bye(),o.html(lang.call_ended),console.log("New call session end"),a.data.confcalls[l].accept.disposition="bye",a.data.confcalls[l].accept.eventTime=utcDateNow(),$("#line-"+t+"-msg").html(lang.conference_call_ended),updateLineScroll(t)})),n.show(),updateLineScroll(t)})),d.on("trackAdded",(function(){var e=d.sessionDescriptionHandler.peerConnection,i=new MediaStream;e.getReceivers().forEach((function(e){e.track&&"audio"==e.track.kind&&i.addTrack(e.track)}));var n=$("#line-"+t+"-conference-remoteAudio").get(0);n.srcObject=i,n.onloadedmetadata=function(e){void 0!==n.sinkId&&n.setSinkId(a.data.AudioOutputDevice).then((function(){console.log("sinkId applied: "+a.data.AudioOutputDevice)})).catch((function(e){console.warn("Error using setSinkId: ",e)})),n.play()}})),d.on("rejected",(function(e,i){console.log("New call session rejected: ",i),o.html(lang.call_rejected),a.data.confcalls[l].disposition="rejected",a.data.confcalls[l].dispositionTime=utcDateNow(),$("#line-"+t+"-txt-FindConferenceBuddy").parent().show(),$("#line-"+t+"-btn-conference-dial").show(),$("#line-"+t+"-btn-cancel-conference-dial").hide(),$("#line-"+t+"-btn-join-conference-call").hide(),$("#line-"+t+"-btn-terminate-conference-call").hide(),$("#line-"+t+"-msg").html(lang.conference_call_rejected),updateLineScroll(t),window.setTimeout((function(){o.hide(),updateLineScroll(t)}),1e3)})),d.on("terminated",(function(i,n){(console.log("New call session terminated: ",n),o.html(lang.call_ended),a.data.confcalls[l].disposition="terminated",a.data.confcalls[l].dispositionTime=utcDateNow(),a.data.childsession.data.AudioSourceTrack&&"audio"==a.data.childsession.data.AudioSourceTrack.kind&&a.data.childsession.data.AudioSourceTrack.stop(),a.data.AudioSourceTrack&&"audio"==a.data.AudioSourceTrack.kind)&&a.sessionDescriptionHandler.peerConnection.getSenders().forEach((function(t){t.track&&"audio"==t.track.kind&&(t.replaceTrack(a.data.AudioSourceTrack).then((function(){a.data.ismute&&(t.track.enabled=!1)})).catch((function(){console.error(e)})),a.data.AudioSourceTrack=null)}));$("#line-"+t+"-txt-FindConferenceBuddy").parent().show(),$("#line-"+t+"-btn-conference-dial").show(),$("#line-"+t+"-btn-cancel-conference-dial").hide(),$("#line-"+t+"-btn-join-conference-call").hide(),$("#line-"+t+"-btn-terminate-conference-call").hide(),$("#line-"+t+"-msg").html(lang.conference_call_terminated),updateLineScroll(t),window.setTimeout((function(){o.hide(),updateLineScroll(t)}),1e3)}))}else console.warn("Null line or session")}else console.warn("Cannot transfer, must be [0-9*+#]")}function cancelSession(e){var t=FindLineByNumber(e);null!=t&&null!=t.SipSession&&(t.SipSession.data.terminateby="us",console.log("Cancelling session : "+e),t.SipSession.cancel(),$("#line-"+e+"-msg").html(lang.call_cancelled))}function holdSession(e){var t=FindLineByNumber(e);null!=t&&null!=t.SipSession&&(console.log("Putting Call on hold: "+e),0==t.SipSession.local_hold&&t.SipSession.hold(),t.SipSession.data.hold||(t.SipSession.data.hold=[]),t.SipSession.data.hold.push({event:"hold",eventTime:utcDateNow()}),$("#line-"+e+"-btn-Hold").hide(),$("#line-"+e+"-btn-Unhold").show(),$("#line-"+e+"-msg").html(lang.call_on_hold),updateLineScroll(e))}function unholdSession(e){var t=FindLineByNumber(e);null!=t&&null!=t.SipSession&&(console.log("Taking call off hold: "+e),1==t.SipSession.local_hold&&t.SipSession.unhold(),t.SipSession.data.hold||(t.SipSession.data.hold=[]),t.SipSession.data.hold.push({event:"unhold",eventTime:utcDateNow()}),$("#line-"+e+"-msg").html(lang.call_in_progress),$("#line-"+e+"-btn-Hold").show(),$("#line-"+e+"-btn-Unhold").hide(),updateLineScroll(e))}function endSession(e){var t=FindLineByNumber(e);null!=t&&null!=t.SipSession&&(console.log("Ending call with: "+e),t.SipSession.data.terminateby="us",t.SipSession.bye(),$("#line-"+e+"-msg").html(lang.call_ended),$("#line-"+e+"-ActiveCall").hide(),updateLineScroll(e))}function sendDTMF(e,t){var i=FindLineByNumber(e);null!=i&&null!=i.SipSession&&(console.log("Sending DTMF ("+t+"): "+e),i.SipSession.dtmf(t),$("#line-"+e+"-msg").html(lang.send_dtmf+": "+t),updateLineScroll(e),"undefined"!=typeof web_hook_on_dtmf&&web_hook_on_dtmf(t,i.SipSession))}function switchVideoSource(t,i){var n=FindLineByNumber(t);if(null!=n&&null!=n.SipSession){var a=n.SipSession;$("#line-"+t+"-msg").html(lang.switching_video_source);var o=navigator.mediaDevices.getSupportedConstraints(),l={audio:!1,video:{deviceId:"default"}};"default"!=i&&(l.video.deviceId={exact:i}),o.frameRate&&""!=maxFrameRate&&(l.video.frameRate=maxFrameRate),o.height&&""!=videoHeight&&(l.video.height=videoHeight),o.aspectRatio&&""!=videoAspectRatio&&(l.video.aspectRatio=videoAspectRatio),a.data.VideoSourceDevice=i;var s=a.sessionDescriptionHandler.peerConnection,r=new MediaStream;navigator.mediaDevices.getUserMedia(l).then((function(e){var t=e.getVideoTracks()[0];s.getSenders().forEach((function(e){e.track&&"video"==e.track.kind&&(console.log("Switching Video Track : "+e.track.label+" to "+t.label),e.track.stop(),e.replaceTrack(t),r.addTrack(t))}))})).catch((function(e){console.error("Error on getUserMedia",e,l)})),a.data.AudioSourceTrack&&"audio"==a.data.AudioSourceTrack.kind&&s.getSenders().forEach((function(t){t.track&&"audio"==t.track.kind&&(t.replaceTrack(a.data.AudioSourceTrack).then((function(){a.data.ismute&&(t.track.enabled=!1)})).catch((function(){console.error(e)})),a.data.AudioSourceTrack=null)})),console.log("Showing as preview...");var d=$("#line-"+t+"-localVideo").get(0);d.srcObject=r,d.onloadedmetadata=function(e){d.play()}}else console.warn("Line or Session is Null")}function SendCanvas(t){var i=FindLineByNumber(t);if(null!=i&&null!=i.SipSession){var n=i.SipSession;$("#line-"+t+"-msg").html(lang.switching_to_canvas),RemoveScratchpad(t);var a=$("<canvas/>");a.prop("id","line-"+t+"-scratchpad"),$("#line-"+t+"-scratchpad-container").append(a),$("#line-"+t+"-scratchpad").css("display","inline-block"),$("#line-"+t+"-scratchpad").css("width","640px"),$("#line-"+t+"-scratchpad").css("height","360px"),$("#line-"+t+"-scratchpad").prop("width",640),$("#line-"+t+"-scratchpad").prop("height",360),$("#line-"+t+"-scratchpad-container").show(),console.log("Canvas for Scratchpad created..."),scratchpad=new fabric.Canvas("line-"+t+"-scratchpad"),scratchpad.id="line-"+t+"-scratchpad",scratchpad.backgroundColor="#FFFFFF",scratchpad.isDrawingMode=!0,scratchpad.renderAll(),scratchpad.redrawIntrtval=window.setInterval((function(){scratchpad.renderAll()}),1e3),CanvasCollection.push(scratchpad);var o=$("#line-"+t+"-scratchpad").get(0).captureStream(25),l=o.getVideoTracks()[0],s=n.sessionDescriptionHandler.peerConnection;s.getSenders().forEach((function(e){e.track&&"video"==e.track.kind&&(console.log("Switching Track : "+e.track.label+" to Scratchpad Canvas"),e.track.stop(),e.replaceTrack(l))})),n.data.AudioSourceTrack&&"audio"==n.data.AudioSourceTrack.kind&&s.getSenders().forEach((function(t){t.track&&"audio"==t.track.kind&&(t.replaceTrack(n.data.AudioSourceTrack).then((function(){n.data.ismute&&(t.track.enabled=!1)})).catch((function(){console.error(e)})),n.data.AudioSourceTrack=null)})),console.log("Showing as preview...");var r=$("#line-"+t+"-localVideo").get(0);r.srcObject=o,r.onloadedmetadata=function(e){r.play()}}else console.warn("Line or Session is Null")}function SendVideo(e,t){var i=FindLineByNumber(e);if(null!=i&&null!=i.SipSession){var n=i.SipSession;$("#line-"+e+"-src-camera").prop("disabled",!1),$("#line-"+e+"-src-canvas").prop("disabled",!1),$("#line-"+e+"-src-desktop").prop("disabled",!1),$("#line-"+e+"-src-video").prop("disabled",!0),$("#line-"+e+"-src-blank").prop("disabled",!1),$("#line-"+e+"-msg").html(lang.switching_to_shared_video),$("#line-"+e+"-scratchpad-container").hide(),RemoveScratchpad(e),$("#line-"+e+"-sharevideo").hide(),$("#line-"+e+"-sharevideo").get(0).pause(),$("#line-"+e+"-sharevideo").get(0).removeAttribute("src"),$("#line-"+e+"-sharevideo").get(0).load(),$("#line-"+e+"-localVideo").hide(),$("#line-"+e+"-remoteVideo").appendTo("#line-"+e+"-preview-container");var a=$("#line-"+e+"-sharevideo");a.prop("src",t),a.off("loadedmetadata"),a.on("loadedmetadata",(function(){console.log("Video can play now... ");var t=360;"HD"==VideoResampleSize&&(t=720),"FHD"==VideoResampleSize&&(t=1080);var i=a.get(0),o=$("<canvas/>").get(0),l=i.videoWidth,s=i.videoHeight;if(l>=s){if(s>t){var r=t/s;s=t,l*=r}}else if(l>t){r=t/l;l=t,s*=r}o.width=l,o.height=s;var d=o.getContext("2d");window.clearInterval(n.data.videoResampleInterval),n.data.videoResampleInterval=window.setInterval((function(){d.drawImage(i,0,0,l,s)}),40);var c=null;"captureStream"in i?c=i.captureStream():"mozCaptureStream"in i?c=i.mozCaptureStream():console.warn("Cannot capture stream from video, this will result in no audio being transmitted.");var u=o.captureStream(25).getVideoTracks()[0],p=null!=c?c.getAudioTracks()[0]:null;n.sessionDescriptionHandler.peerConnection.getSenders().forEach((function(e){if(e.track&&"video"==e.track.kind&&(console.log("Switching Track : "+e.track.label),e.track.stop(),e.replaceTrack(u)),e.track&&"audio"==e.track.kind){console.log("Switching to mixed Audio track on session"),n.data.AudioSourceTrack=e.track;var t=new MediaStream;p&&t.addTrack(p),t.addTrack(e.track);var i=MixAudioStreams(t).getAudioTracks()[0];i.IsMixedTrack=!0,e.replaceTrack(i)}})),console.log("Showing as preview...");var g=$("#line-"+e+"-localVideo").get(0);g.srcObject=c,g.onloadedmetadata=function(e){g.play().then((function(){console.log("Playing Preview Video File")})).catch((function(e){console.error("Cannot play back video",e)}))},console.log("Starting Video..."),$("#line-"+e+"-sharevideo").get(0).play()})),$("#line-"+e+"-sharevideo").show(),console.log("Video for Sharing created...")}else console.warn("Line or Session is Null")}function ShareScreen(t){var i=FindLineByNumber(t);if(null!=i&&null!=i.SipSession){var n=i.SipSession;$("#line-"+t+"-msg").html(lang.switching_to_shared_screeen);var a=new MediaStream,o=n.sessionDescriptionHandler.peerConnection;if(navigator.getDisplayMedia){var l={video:!0,audio:!1};navigator.getDisplayMedia(l).then((function(e){console.log("navigator.getDisplayMedia");var i=e.getVideoTracks()[0];o.getSenders().forEach((function(e){e.track&&"video"==e.track.kind&&(console.log("Switching Video Track : "+e.track.label+" to Screen"),e.track.stop(),e.replaceTrack(i),a.addTrack(i))})),console.log("Showing as preview...");var n=$("#line-"+t+"-localVideo").get(0);n.srcObject=a,n.onloadedmetadata=function(e){n.play()}})).catch((function(e){console.error("Error on getUserMedia")}))}else if(navigator.mediaDevices.getDisplayMedia){l={video:!0,audio:!1};navigator.mediaDevices.getDisplayMedia(l).then((function(e){console.log("navigator.mediaDevices.getDisplayMedia");var i=e.getVideoTracks()[0];o.getSenders().forEach((function(e){e.track&&"video"==e.track.kind&&(console.log("Switching Video Track : "+e.track.label+" to Screen"),e.track.stop(),e.replaceTrack(i),a.addTrack(i))})),console.log("Showing as preview...");var n=$("#line-"+t+"-localVideo").get(0);n.srcObject=a,n.onloadedmetadata=function(e){n.play()}})).catch((function(e){console.error("Error on getUserMedia")}))}else{l={video:{mediaSource:"screen"},audio:!1};navigator.mediaDevices.getUserMedia(l).then((function(e){console.log("navigator.mediaDevices.getUserMedia");var i=e.getVideoTracks()[0];o.getSenders().forEach((function(e){e.track&&"video"==e.track.kind&&(console.log("Switching Video Track : "+e.track.label+" to Screen"),e.track.stop(),e.replaceTrack(i),a.addTrack(i))})),console.log("Showing as preview...");var n=$("#line-"+t+"-localVideo").get(0);n.srcObject=a,n.onloadedmetadata=function(e){n.play()}})).catch((function(e){console.error("Error on getUserMedia")}))}n.data.AudioSourceTrack&&"audio"==n.data.AudioSourceTrack.kind&&o.getSenders().forEach((function(t){t.track&&"audio"==t.track.kind&&(t.replaceTrack(n.data.AudioSourceTrack).then((function(){n.data.ismute&&(t.track.enabled=!1)})).catch((function(){console.error(e)})),n.data.AudioSourceTrack=null)}))}else console.warn("Line or Session is Null")}function DisableVideoStream(t){var i=FindLineByNumber(t);if(null!=i&&null!=i.SipSession){var n=i.SipSession;n.sessionDescriptionHandler.peerConnection.getSenders().forEach((function(t){t.track&&"video"==t.track.kind&&(console.log("Disable Video Track : "+t.track.label),t.track.enabled=!1),t.track&&"audio"==t.track.kind&&n.data.AudioSourceTrack&&"audio"==n.data.AudioSourceTrack.kind&&(t.replaceTrack(n.data.AudioSourceTrack).then((function(){n.data.ismute&&(t.track.enabled=!1)})).catch((function(){console.error(e)})),n.data.AudioSourceTrack=null)})),console.log("Showing as preview...");var a=$("#line-"+t+"-localVideo").get(0);a.pause(),a.removeAttribute("src"),a.load(),$("#line-"+t+"-msg").html(lang.video_disabled)}else console.warn("Line or Session is Null")}var Line=function(e,t,i,n){this.LineNumber=e,this.DisplayName=t,this.DisplayNumber=i,this.IsSelected=!1,this.BuddyObj=n,this.SipSession=null,this.LocalSoundMeter=null,this.RemoteSoundMeter=null};function ShowDial(e){var t=e.offsetWidth+104,i=0,n=e.offsetHeight+117;$(window).width()<=915&&(t=event.pageX+e.offsetWidth-120,i=0,n=event.pageY+e.offsetHeight-11);var a='<div id=mainDialPad><div><input id=dialText class=dialTextInput oninput="handleDialInput(this, event)" onkeydown="dialOnkeydown(event, this)"></div>';a+='<table cellspacing=10 cellpadding=0 style="margin-left:auto; margin-right: auto">',a+="<tr><td><button class=dtmfButtons onclick=\"KeyPress('1');new Audio('sounds/dtmf.mp3').play();\"><div>1</div><span>&nbsp;</span></button></td>",a+="<td><button class=dtmfButtons onclick=\"KeyPress('2');new Audio('sounds/dtmf.mp3').play();\"><div>2</div><span>ABC</span></button></td>",a+="<td><button class=dtmfButtons onclick=\"KeyPress('3');new Audio('sounds/dtmf.mp3').play();\"><div>3</div><span>DEF</span></button></td></tr>",a+="<tr><td><button class=dtmfButtons onclick=\"KeyPress('4');new Audio('sounds/dtmf.mp3').play();\"><div>4</div><span>GHI</span></button></td>",a+="<td><button class=dtmfButtons onclick=\"KeyPress('5');new Audio('sounds/dtmf.mp3').play();\"><div>5</div><span>JKL</span></button></td>",a+="<td><button class=dtmfButtons onclick=\"KeyPress('6');new Audio('sounds/dtmf.mp3').play();\"><div>6</div><span>MNO</span></button></td></tr>",a+="<tr><td><button class=dtmfButtons onclick=\"KeyPress('7');new Audio('sounds/dtmf.mp3').play();\"><div>7</div><span>PQRS</span></button></td>",a+="<td><button class=dtmfButtons onclick=\"KeyPress('8');new Audio('sounds/dtmf.mp3').play();\"><div>8</div><span>TUV</span></button></td>",a+="<td><button class=dtmfButtons onclick=\"KeyPress('9');new Audio('sounds/dtmf.mp3').play();\"><div>9</div><span>WXYZ</span></button></td></tr>",a+="<tr><td><button class=dtmfButtons onclick=\"KeyPress('*');new Audio('sounds/dtmf.mp3').play();\">*</button></td>",a+="<td><button class=dtmfButtons onclick=\"KeyPress('0');new Audio('sounds/dtmf.mp3').play();\">0</button></td>",a+="<td><button class=dtmfButtons onclick=\"KeyPress('#');new Audio('sounds/dtmf.mp3').play();\">#</button></td></tr>",a+="</table>",a+='<div style="text-align: center;">',a+='<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>',EnableVideoCalling&&(a+='<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>'),a+="</div></div>",$.jeegoopopup.open({html:a,width:"auto",height:"auto",left:t,right:i,top:n,scrolling:"no",skinClass:"jg_popup_basic",overlay:!0,opacity:0,draggable:!0,resizable:!1,fadeIn:0}),$("#dialText").focus(),$(window).width()<=915?$.jeegoopopup.right(6):$.jeegoopopup.width("auto").height("auto").left(t).top(n),$("#jg_popup_overlay").click((function(){$("#jg_popup_b").empty(),$("#jg_popup_l").empty(),$("#windowCtrls").empty(),$.jeegoopopup.close()})),$(window).on("keydown",(function(e){"Escape"==e.key&&($("#jg_popup_b").empty(),$("#jg_popup_l").empty(),$("#windowCtrls").empty(),$.jeegoopopup.close())}))}function handleDialInput(e,t){EnableAlphanumericDial?$("#dialText").val($("#dialText").val().replace(/[^\da-zA-Z\*\#\+]/g,"").substring(0,MaxDidLength)):$("#dialText").val($("#dialText").val().replace(/[^\d\*\#\+]/g,"").substring(0,MaxDidLength)),$("#dialVideo").prop("disabled",$("#dialText").val().length>=DidLength)}function dialOnkeydown(e,t,i){if("13"==(e.keyCode?e.keyCode:e.which))return e.preventDefault(),DialByLine("audio"),$("#jg_popup_b").empty(),$("#jg_popup_l").empty(),$("#windowCtrls").empty(),$.jeegoopopup.close(),!1}function KeyPress(e){$("#dialText").val(($("#dialText").val()+e).substring(0,MaxDidLength)),$("#dialVideo").prop("disabled",$("#dialText").val().length>=DidLength)}function DialByLine(e,t,i,n){if($.jeegoopopup.close(),null!=userAgent&&0!=userAgent.isRegistered()){var a=i||$("#dialText").val();if(0!=(a=EnableAlphanumericDial?a.replace(/[^\da-zA-Z\*\#\+]/g,"").substring(0,MaxDidLength):a.replace(/[^\d\*\#\+]/g,"").substring(0,MaxDidLength)).length){var o=t?FindBuddyByIdentity(t):FindBuddyByDid(a);if(null==o){var l=a.length>DidLength?"contact":"extension";"*"!=l.substring(0,1)&&"#"!=l.substring(0,1)||(l="contact"),o=MakeBuddy(l,!0,!1,!0,n||a,a)}newLineNumber+=1,lineObj=new Line(newLineNumber,o.CallerIDName,a,o),Lines.push(lineObj),AddLineHtml(lineObj),SelectLine(newLineNumber),UpdateBuddyList(),"audio"==e?AudioCall(lineObj,a):VideoCall(lineObj,a);try{$("#line-"+newLineNumber).get(0).scrollIntoViewIfNeeded()}catch(e){}}else console.warn("Enter number to dial")}else ConfigureExtensionWindow()}function SelectLine(e){$("#roundcubeFrame").remove();var t=FindLineByNumber(e);if(null!=t){for(var i=0,n=0;n<Lines.length;n++)if(Lines[n].LineNumber==t.LineNumber&&(i=n+1),1==Lines[n].IsSelected&&Lines[n].LineNumber==t.LineNumber)return;console.log("Selecting Line : "+t.LineNumber),$(".streamSelected").each((function(){$(this).prop("class","stream")})),$("#line-ui-"+t.LineNumber).prop("class","streamSelected"),$("#line-ui-"+t.LineNumber+"-DisplayLineNo").html('<i class="fa fa-phone"></i> '+lang.line+" "+i),$("#line-ui-"+t.LineNumber+"-LineIcon").html(i),SwitchLines(t.LineNumber);for(n=0;n<Lines.length;n++){var a=Lines[n].LineNumber==t.LineNumber?"buddySelected":"buddy";null!=Lines[n].SipSession&&(a=Lines[n].SipSession.local_hold?"buddyActiveCallHollding":"buddyActiveCall"),$("#line-"+Lines[n].LineNumber).prop("class",a),Lines[n].IsSelected=Lines[n].LineNumber==t.LineNumber}for(var o=0;o<Buddies.length;o++)$("#contact-"+Buddies[o].identity).prop("class","buddy"),Buddies[o].IsSelected=!1;UpdateUI()}}function FindLineByNumber(e){for(var t=0;t<Lines.length;t++)if(Lines[t].LineNumber==e)return Lines[t];return null}function AddLineHtml(e){var t='<table id="line-ui-'+e.LineNumber+'" class="stream" cellspacing="5" cellpadding="0">';t+="<tr><td class=streamSection>",t+='<div style="float:left; margin:0px; padding:5px; height:38px; line-height:38px">',t+='<button id="line-'+e.LineNumber+'-btn-back" onclick="CloseLine(\''+e.LineNumber+'\')" class=roundButtons title="'+lang.back+'"><i class="fa fa-chevron-left"></i></button> ',t+="</div>",t+='<div class=contact style="float: left;">',t+='<div id="line-ui-'+e.LineNumber+'-LineIcon" class=lineIcon>'+e.LineNumber+"</div>",t+='<div id="line-ui-'+e.LineNumber+'-DisplayLineNo" class=contactNameText><i class="fa fa-phone"></i> '+lang.line+" "+e.LineNumber+"</div>",t+="<div class=presenceText>"+e.DisplayName+" <"+e.DisplayNumber+"></div>",t+="</div>",t+='<div style="float:right; line-height: 46px;">',t+="</div>",t+='<div style="clear:both; height:0px"></div>',t+='<div id="line-'+e.LineNumber+'-calling">',t+='<div id="line-'+e.LineNumber+'-timer" style="float: right; margin-top: 4px; margin-right: 10px; color: #575757; display:none;"></div>',t+='<div id="line-'+e.LineNumber+'-msg" class=callStatus style="display:none">...</div>',t+='<div id="line-'+e.LineNumber+'-progress" style="display:none; margin-top: 10px">',t+="<div class=progressCall>",t+="<button onclick=\"cancelSession('"+e.LineNumber+'\')" class=hangupButton><i class="fa fa-phone"></i>&nbsp;&nbsp;'+lang.cancel+"</button>",t+="</div>",t+="</div>",t+='<div id="line-'+e.LineNumber+'-ActiveCall" style="display:none; margin-top: 10px;">',t+='<div id="line-'+e.LineNumber+'-conference" style="display:none;"></div>',"extension"==e.BuddyObj.type&&(t+='<div id="line-'+e.LineNumber+'-VideoCall" class=videoCall style="display:none;">',t+='<div style="height:35px; line-height:35px; text-align: right">'+lang.present+": ",t+='<div class=pill-nav style="border-color:#333333">',t+='<button id="line-'+e.LineNumber+'-src-camera" onclick="PresentCamera(\''+e.LineNumber+'\')" title="'+lang.camera+'" disabled><i class="fa fa-video-camera"></i></button>',t+='<button id="line-'+e.LineNumber+'-src-canvas" onclick="PresentScratchpad(\''+e.LineNumber+'\')" title="'+lang.scratchpad+'"><i class="fa fa-pencil-square"></i></button>',t+='<button id="line-'+e.LineNumber+'-src-desktop" onclick="PresentScreen(\''+e.LineNumber+'\')" title="'+lang.screen+'"><i class="fa fa-desktop"></i></button>',t+='<button id="line-'+e.LineNumber+'-src-video" onclick="PresentVideo(\''+e.LineNumber+'\')" title="'+lang.video+'"><i class="fa fa-file-video-o"></i></button>',t+='<button id="line-'+e.LineNumber+'-src-blank" onclick="PresentBlank(\''+e.LineNumber+'\')" title="'+lang.blank+'"><i class="fa fa-ban"></i></button>',t+="</div>",t+='&nbsp;<button id="line-'+e.LineNumber+'-expand" onclick="ExpandVideoArea(\''+e.LineNumber+'\')"><i class="fa fa-expand"></i></button>',t+='<button id="line-'+e.LineNumber+'-restore" onclick="RestoreVideoArea(\''+e.LineNumber+'\')" style="display:none"><i class="fa fa-compress"></i></button>',t+="</div>",t+='<div id="line-'+e.LineNumber+'-preview-container" class=PreviewContainer>',t+='<video id="line-'+e.LineNumber+'-localVideo" muted></video>',t+="</div>",t+='<div id="line-'+e.LineNumber+'-stage-container" class=StageContainer>',t+='<video id="line-'+e.LineNumber+'-remoteVideo" muted></video>',t+='<div id="line-'+e.LineNumber+'-scratchpad-container" style="display:none"></div>',t+='<video id="line-'+e.LineNumber+'-sharevideo" controls muted style="display:none; object-fit: contain;"></video>',t+="</div>",t+="</div>"),t+='<div id="line-'+e.LineNumber+'-AudioCall" style="display:none;">',t+='<audio id="line-'+e.LineNumber+'-remoteAudio"></audio>',t+="</div>",t+='<div style="text-align:center">',t+='<div style="margin-top:10px">',t+='<button id="line-'+e.LineNumber+'-btn-ShowDtmf" onclick="ShowDtmfMenu(this, \''+e.LineNumber+'\')" class="roundButtons inCallButtons" title="'+lang.show_key_pad+'"><i class="fa fa-keyboard-o"></i></button>',t+='<button id="line-'+e.LineNumber+'-btn-Mute" onclick="MuteSession(\''+e.LineNumber+'\')" class="roundButtons inCallButtons" title="'+lang.mute+'"><i class="fa fa-microphone-slash"></i></button>',t+='<button id="line-'+e.LineNumber+'-btn-Unmute" onclick="UnmuteSession(\''+e.LineNumber+'\')" class="roundButtons inCallButtons" title="'+lang.unmute+'" style="color: red; display:none"><i class="fa fa-microphone"></i></button>',"undefined"==typeof MediaRecorder||"allow"!=CallRecordingPolicy&&"enabled"!=CallRecordingPolicy||(t+='<button id="line-'+e.LineNumber+'-btn-start-recording" onclick="StartRecording(\''+e.LineNumber+'\')" class="roundButtons inCallButtons" title="'+lang.start_call_recording+'"><i class="fa fa-dot-circle-o"></i></button>',t+='<button id="line-'+e.LineNumber+'-btn-stop-recording" onclick="StopRecording(\''+e.LineNumber+'\')" class="roundButtons inCallButtons" title="'+lang.stop_call_recording+'" style="color: red; display:none"><i class="fa fa-circle"></i></button>'),EnableTransfer&&(t+='<button id="line-'+e.LineNumber+'-btn-Transfer" onclick="StartTransferSession(\''+e.LineNumber+'\')" class="roundButtons inCallButtons" title="'+lang.transfer_call+'"><i class="fa fa-reply" style="transform: rotateY(180deg)"></i></button>',t+='<button id="line-'+e.LineNumber+'-btn-CancelTransfer" onclick="CancelTransferSession(\''+e.LineNumber+'\')" class="roundButtons inCallButtons" title="'+lang.cancel_transfer+'" style="color: red; display:none"><i class="fa fa-reply" style="transform: rotateY(180deg)"></i></button>'),t+='<button id="line-'+e.LineNumber+'-btn-Hold" onclick="holdSession(\''+e.LineNumber+'\')" class="roundButtons inCallButtons"  title="'+lang.hold_call+'"><i class="fa fa-pause-circle"></i></button>',t+='<button id="line-'+e.LineNumber+'-btn-Unhold" onclick="unholdSession(\''+e.LineNumber+'\')" class="roundButtons inCallButtons" title="'+lang.resume_call+'" style="color: red; display:none"><i class="fa fa-play-circle"></i></button>',t+='<button id="line-'+e.LineNumber+'-btn-End" onclick="endSession(\''+e.LineNumber+'\')" class="roundButtons inCallButtons hangupButton" title="'+lang.end_call+'"><i class="fa fa-phone"></i></button>',t+="</div>",t+='<div id="line-'+e.LineNumber+'-Transfer" style="display:none">',t+='<div style="margin-top:10px">',t+='<span class=searchClean><input id="line-'+e.LineNumber+'-txt-FindTransferBuddy" oninput="QuickFindBuddy(this,\''+e.LineNumber+'\')" type=text autocomplete=none style="width:150px;" autocomplete=none placeholder="'+lang.search_or_enter_number+'"></span>',t+=' <button id="line-'+e.LineNumber+'-btn-blind-transfer" onclick="BlindTransfer(\''+e.LineNumber+'\')"><i class="fa fa-reply" style="transform: rotateY(180deg)"></i> '+lang.blind_transfer+"</button>",t+=' <button id="line-'+e.LineNumber+'-btn-attended-transfer" onclick="AttendedTransfer(\''+e.LineNumber+'\')"><i class="fa fa-reply-all" style="transform: rotateY(180deg)"></i> '+lang.attended_transfer+"</button>",t+=' <button id="line-'+e.LineNumber+'-btn-complete-attended-transfer" style="display:none"><i class="fa fa-reply-all" style="transform: rotateY(180deg)"></i> '+lang.complete_transfer+"</buuton>",t+=' <button id="line-'+e.LineNumber+'-btn-cancel-attended-transfer" style="display:none"><i class="fa fa-phone" style="transform: rotate(135deg);"></i> '+lang.cancel_transfer+"</buuton>",t+=' <button id="line-'+e.LineNumber+'-btn-terminate-attended-transfer" style="display:none"><i class="fa fa-phone" style="transform: rotate(135deg);"></i> '+lang.end_transfer_call+"</buuton>",t+="</div>",t+='<div id="line-'+e.LineNumber+'-transfer-status" class=callStatus style="margin-top:10px; display:none">...</div>',t+='<audio id="line-'+e.LineNumber+'-transfer-remoteAudio" style="display:none"></audio>',t+="</div>",t+='<div id="line-'+e.LineNumber+'-Conference" style="display:none">',t+='<div style="margin-top:10px">',t+='<span class=searchClean><input id="line-'+e.LineNumber+'-txt-FindConferenceBuddy" oninput="QuickFindBuddy(this,\''+e.LineNumber+'\')" type=text autocomplete=none style="width:150px;" autocomplete=none placeholder="'+lang.search_or_enter_number+'"></span>',t+=' <button id="line-'+e.LineNumber+'-btn-conference-dial" onclick="ConferenceDial(\''+e.LineNumber+'\')"><i class="fa fa-phone"></i> '+lang.call+"</button>",t+=' <button id="line-'+e.LineNumber+'-btn-cancel-conference-dial" style="display:none"><i class="fa fa-phone"></i> '+lang.cancel_call+"</buuton>",t+=' <button id="line-'+e.LineNumber+'-btn-join-conference-call" style="display:none"><i class="fa fa-users"></i> '+lang.join_conference_call+"</buuton>",t+=' <button id="line-'+e.LineNumber+'-btn-terminate-conference-call" style="display:none"><i class="fa fa-phone"></i> '+lang.end_conference_call+"</buuton>",t+="</div>",t+='<div id="line-'+e.LineNumber+'-conference-status" class=callStatus style="margin-top:10px; display:none">...</div>',t+='<audio id="line-'+e.LineNumber+'-conference-remoteAudio" style="display:none"></audio>',t+="</div>",t+='<div  id="line-'+e.LineNumber+'-monitoring" style="margin-top:10px;margin-bottom:10px;">',t+='<span style="vertical-align: middle"><i class="fa fa-microphone"></i></span> ',t+='<span class=meterContainer title="'+lang.microphone_levels+'">',t+='<span id="line-'+e.LineNumber+'-Mic" class=meterLevel style="height:0%"></span>',t+="</span> ",t+='<span style="vertical-align: middle"><i class="fa fa-volume-up"></i></span> ',t+='<span class=meterContainer title="'+lang.speaker_levels+'">',t+='<span id="line-'+e.LineNumber+'-Speaker" class=meterLevel style="height:0%"></span>',t+="</span> ",t+='<button id="line-'+e.LineNumber+'-btn-settings" onclick="ChangeSettings(\''+e.LineNumber+'\', this)"><i class="fa fa-cogs"></i> '+lang.device_settings+"</button>",t+='<button id="line-'+e.LineNumber+'-call-stats" onclick="ShowCallStats(\''+e.LineNumber+'\', this)"><i class="fa fa-area-chart"></i> '+lang.call_stats+"</button>",t+="</div>",t+='<div id="line-'+e.LineNumber+'-AudioStats" class="audioStats cleanScroller" style="display:none">',t+='<div style="text-align:right"><button onclick="HideCallStats(\''+e.LineNumber+'\', this)"><i class="fa fa-times" style="font-size:20px;"></i></button></div>',t+="<fieldset class=audioStatsSet onclick=\"HideCallStats('"+e.LineNumber+"', this)\">",t+="<legend>"+lang.send_statistics+"</legend>",t+='<canvas id="line-'+e.LineNumber+'-AudioSendBitRate" class=audioGraph width=600 height=160 style="width:600px; height:160px"></canvas>',t+='<canvas id="line-'+e.LineNumber+'-AudioSendPacketRate" class=audioGraph width=600 height=160 style="width:600px; height:160px"></canvas>',t+="</fieldset>",t+="<fieldset class=audioStatsSet onclick=\"HideCallStats('"+e.LineNumber+"', this)\">",t+="<legend>"+lang.receive_statistics+"</legend>",t+='<canvas id="line-'+e.LineNumber+'-AudioReceiveBitRate" class=audioGraph width=600 height=160 style="width:600px; height:160px"></canvas>',t+='<canvas id="line-'+e.LineNumber+'-AudioReceivePacketRate" class=audioGraph width=600 height=160 style="width:600px; height:160px"></canvas>',t+='<canvas id="line-'+e.LineNumber+'-AudioReceivePacketLoss" class=audioGraph width=600 height=160 style="width:600px; height:160px"></canvas>',t+='<canvas id="line-'+e.LineNumber+'-AudioReceiveJitter" class=audioGraph width=600 height=160 style="width:600px; height:160px"></canvas>',t+='<canvas id="line-'+e.LineNumber+'-AudioReceiveLevels" class=audioGraph width=600 height=160 style="width:600px; height:160px"></canvas>',t+="</fieldset>",t+="</div>",t+="</div>",t+="</div>",t+="</div>",t+="</td></tr>",t+='<tr><td class="streamSection streamSectionBackground">',t+='<div id="line-'+e.LineNumber+'-CallDetails" class="chatHistory cleanScroller">',t+="</div>",t+="</td></tr>",t+="</table>",$("#rightContent").append(t)}function RemoveLine(e){if(null!=e){for(var t=0;t<Lines.length;t++)if(Lines[t].LineNumber==e.LineNumber){Lines.splice(t,1);break}CloseLine(e.LineNumber),$("#line-ui-"+e.LineNumber).remove(),UpdateBuddyList(),null!=localDB.getItem("SelectedBuddy")&&(console.log("Selecting previously selected buddy...",localDB.getItem("SelectedBuddy")),SelectBuddy(localDB.getItem("SelectedBuddy")),UpdateUI())}}function CloseLine(e){$(".buddySelected").each((function(){$(this).prop("class","buddy")})),$(".streamSelected").each((function(){$(this).prop("class","stream")})),SwitchLines(0),console.log("Closing Line: "+e);for(var t=0;t<Lines.length;t++)Lines[t].IsSelected=!1;selectedLine=null;for(var i=0;i<Buddies.length;i++)Buddies[i].IsSelected=!1;selectedBuddy=null,$.jeegoopopup.close(),UpdateUI()}function SwitchLines(e){$.each(userAgent.sessions,(function(t,i){0==i.local_hold&&i.data.line!=e&&(console.log("Putting an active call on hold: Line: "+i.data.line+" buddy: "+i.data.buddyId),i.hold(),i.data.hold||(i.data.hold=[]),i.data.hold.push({event:"hold",eventTime:utcDateNow()})),$("#line-"+i.data.line+"-btn-Hold").hide(),$("#line-"+i.data.line+"-btn-Unhold").show(),i.data.IsCurrentCall=!1}));var t=FindLineByNumber(e);if(null!=t&&null!=t.SipSession){var i=t.SipSession;1==i.local_hold&&(console.log("Taking call off hold:  Line: "+e+" buddy: "+i.data.buddyId),i.unhold(),i.data.hold||(i.data.hold=[]),i.data.hold.push({event:"unhold",eventTime:utcDateNow()})),$("#line-"+e+"-btn-Hold").show(),$("#line-"+e+"-btn-Unhold").hide(),i.data.IsCurrentCall=!0}selectedLine=e,RefreshLineActivity(e)}function RefreshLineActivity(e){var t=FindLineByNumber(e);if(null!=t&&null!=t.SipSession){var i=t.SipSession;$("#line-"+e+"-CallDetails").empty();var n=[],a=0,o=moment.utc(i.data.callstart.replace(" UTC","")),l=null;i.startTime&&(l=moment.utc(i.startTime),a=moment.duration(l.diff(o))),o=o.format("YYYY-MM-DD HH:mm:ss UTC"),l=l?l.format("YYYY-MM-DD HH:mm:ss UTC"):null,a=0!=a?a.asSeconds():0;var s="",r="";"inbound"==i.data.calldirection?s="<"+i.remoteIdentity.uri.user+"> "+i.remoteIdentity.displayName:"outbound"==i.data.calldirection&&(r=i.remoteIdentity.uri.user);var d=i.data.withvideo?"("+lang.with_video+")":"",c="inbound"==i.data.calldirection?lang.you_received_a_call_from+" "+s+" "+d:lang.you_made_a_call_to+" "+r+" "+d;if(n.push({Message:c,TimeStr:o}),l){var u="inbound"==i.data.calldirection?lang.you_answered_after+" "+a+" "+lang.seconds_plural:lang.they_answered_after+" "+a+" "+lang.seconds_plural;n.push({Message:u,TimeStr:l})}var p=i.data.transfer?i.data.transfer:[];$.each(p,(function(e,t){var i="Blind"==t.type?lang.you_started_a_blind_transfer_to+" "+t.to+". ":lang.you_started_an_attended_transfer_to+" "+t.to+". ";t.accept&&1==t.accept.complete?i+=lang.the_call_was_completed:""!=t.accept.disposition&&(i+=lang.the_call_was_not_completed+" ("+t.accept.disposition+")"),n.push({Message:i,TimeStr:t.transferTime})}));var g=i.data.mute?i.data.mute:[];$.each(g,(function(e,t){n.push({Message:"mute"==t.event?lang.you_put_the_call_on_mute:lang.you_took_the_call_off_mute,TimeStr:t.eventTime})}));var m=i.data.hold?i.data.hold:[];$.each(m,(function(e,t){n.push({Message:"hold"==t.event?lang.you_put_the_call_on_hold:lang.you_took_the_call_off_hold,TimeStr:t.eventTime})}));var f=i.data.recordings?i.data.recordings:[];$.each(f,(function(e,t){var i=lang.call_is_being_recorded;t.startTime!=t.stopTime&&(i+="("+lang.now_stopped+")"),n.push({Message:i,TimeStr:t.startTime})}));var v=i.data.confcalls?i.data.confcalls:[];$.each(v,(function(e,t){var i=lang.you_started_a_conference_call_to+" "+t.to+". ";t.accept&&1==t.accept.complete?i+=lang.the_call_was_completed:""!=t.accept.disposition&&(i+=lang.the_call_was_not_completed+" ("+t.accept.disposition+")"),n.push({Message:i,TimeStr:t.startTime})})),n.sort((function(e,t){var i=moment.utc(e.TimeStr.replace(" UTC","")),n=moment.utc(t.TimeStr.replace(" UTC",""));return i.isSameOrAfter(n,"second")?-1:1})),$.each(n,(function(t,i){var n="<table class=timelineMessage cellspacing=0 cellpadding=0><tr>";n+="<td class=timelineMessageArea>",n+='<div class=timelineMessageDate><i class="fa fa-circle timelineMessageDot"></i>'+moment.utc(i.TimeStr.replace(" UTC","")).local().format(DisplayTimeFormat)+"</div>",n+="<div class=timelineMessageText>"+i.Message+"</div>",n+="</td>",n+="</tr></table>",$("#line-"+e+"-CallDetails").prepend(n)}))}}var Buddy=function(e,t,i,n,a,o,l,s,r,d){this.type=e,this.identity=t,this.CallerIDName=i,this.Email=d,this.Desc=r,this.ExtNo=n,this.MobileNumber=a,this.ContactNumber1=o,this.ContactNumber2=l,this.lastActivity=s,this.devState="dotOffline",this.presence="Unknown",this.missed=0,this.IsSelected=!1,this.imageObjectURL=""};function InitUserBuddies(){return localDB.setItem(profileUserID+"-Buddies",JSON.stringify({TotalRows:0,DataCollection:[]})),JSON.parse(localDB.getItem(profileUserID+"-Buddies"))}function MakeBuddy(e,t,i,n,a,o){var l=JSON.parse(localDB.getItem(profileUserID+"-Buddies"));null==l&&(l=InitUserBuddies());var s=null;if("contact"==e){var r=uID(),d=utcDateNow();l.DataCollection.push({Type:"contact",LastActivity:d,ExtensionNumber:"",MobileNumber:"",ContactNumber1:o,ContactNumber2:"",uID:null,cID:r,gID:null,DisplayName:a,Position:"",Description:"",Email:"",MemberCount:0}),AddBuddy(s=new Buddy("contact",r,a,"","",o,"",d,"",""),t,i)}else{r=uID(),d=utcDateNow();l.DataCollection.push({Type:"extension",LastActivity:d,ExtensionNumber:o,MobileNumber:"",ContactNumber1:"",ContactNumber2:"",uID:r,cID:null,gID:null,DisplayName:a,Position:"",Description:"",Email:"",MemberCount:0}),AddBuddy(s=new Buddy("extension",r,a,o,"","","",d,"",""),t,i,n)}return l.TotalRows=l.DataCollection.length,localDB.setItem(profileUserID+"-Buddies",JSON.stringify(l)),s}function UpdateBuddyCalerID(e,t){e.CallerIDName=t;var i=e.identity,n=JSON.parse(localDB.getItem(profileUserID+"-Buddies"));null!=n&&($.each(n.DataCollection,(function(e,n){if(n.uID==i||n.cID==i||n.gID==i)return n.DisplayName=t,!1})),localDB.setItem(profileUserID+"-Buddies",JSON.stringify(n))),UpdateBuddyList()}function AddBuddy(e,t,i,n){Buddies.push(e),1==t&&UpdateBuddyList(),AddBuddyMessageStream(e),1==n&&SubscribeBuddy(e),1==i&&SelectBuddy(e.identity)}function PopulateBuddyList(){console.log("Clearing Buddies..."),Buddies=new Array,console.log("Adding Buddies...");var e=JSON.parse(localDB.getItem(profileUserID+"-Buddies"));null!=e&&(console.log("Total Buddies: "+e.TotalRows),$.each(e.DataCollection,(function(e,t){if("extension"==t.Type)AddBuddy(new Buddy("extension",t.uID,t.DisplayName,t.ExtensionNumber,t.MobileNumber,t.ContactNumber1,t.ContactNumber2,t.LastActivity,t.Position,t.Email),!1,!1);else if("contact"==t.Type){AddBuddy(new Buddy("contact",t.cID,t.DisplayName,"",t.MobileNumber,t.ContactNumber1,t.ContactNumber2,t.LastActivity,t.Description,t.Email),!1,!1)}else if("group"==t.Type){AddBuddy(new Buddy("group",t.gID,t.DisplayName,t.ExtensionNumber,"","","",t.LastActivity,t.MemberCount+" member(s)",t.Email),!1,!1)}})),console.log("Updating Buddy List..."),UpdateBuddyList())}function UpdateBuddyList(){var e=$("#txtFindBuddy").val();$("#myContacts").empty();for(var t=0;t<Lines.length;t++){var i=Lines[t].IsSelected?"buddySelected":"buddy";null!=Lines[t].SipSession&&(i=Lines[t].SipSession.local_hold?"buddyActiveCallHollding":"buddyActiveCall");var n='<div id="line-'+Lines[t].LineNumber+'" class='+i+" onclick=\"SelectLine('"+Lines[t].LineNumber+"')\">";n+="<div class=lineIcon>"+(t+1)+"</div>",n+='<div class=contactNameText><i class="fa fa-phone"></i> '+lang.line+" "+(t+1)+"</div>",n+='<div id="Line-'+Lines[t].ExtNo+'-datetime" class=contactDate>&nbsp;</div>',n+="<div class=presenceText>"+Lines[t].DisplayName+" <"+Lines[t].DisplayNumber+"></div>",n+="</div>",Lines[t].SipSession&&1!=Lines[t].SipSession.data.earlyReject&&($("#myContacts").append(n))}Buddies.sort((function(e,t){var i=moment.utc(e.lastActivity.replace(" UTC","")),n=moment.utc(t.lastActivity.replace(" UTC",""));return i.isSameOrAfter(n,"second")?-1:1}));for(var a=0;a<Buddies.length;a++){var o=Buddies[a];if(e&&e.length>=1){var l=!1;if(o.CallerIDName.toLowerCase().indexOf(e.toLowerCase())>-1&&(l=!0),o.ExtNo.toLowerCase().indexOf(e.toLowerCase())>-1&&(l=!0),o.Desc.toLowerCase().indexOf(e.toLowerCase())>-1&&(l=!0),!l)continue}var s=moment.utc(),r=moment.utc(o.lastActivity.replace(" UTC","")),d="";d=r.isSame(s,"day")?r.local().format(DisplayTimeFormat):r.local().format(DisplayDateFormat);i=o.IsSelected?"buddySelected":"buddy";if("extension"==o.type){var c=o.presence;"Unknown"==c&&(c=lang.state_unknown),"Not online"==c&&(c=lang.state_not_online),"Ready"==c&&(c=lang.state_ready),"On the phone"==c&&(c=lang.state_on_the_phone),"Ringing"==c&&(c=lang.state_ringing),"On hold"==c&&(c=lang.state_on_hold),"Unavailable"==c&&(c=lang.state_unavailable);n='<div id="contact-'+o.identity+'" class='+i+" onmouseenter=\"ShowBuddyDial(this, '"+o.identity+"')\" onmouseleave=\"HideBuddyDial(this, '"+o.identity+"')\" onclick=\"SelectBuddy('"+o.identity+"', 'extension')\">";n+='<span id="contact-'+o.identity+'-devstate" class="'+o.devState+'"></span>',1==getDbItem("useRoundcube","")&&""!=o.Email&&null!=o.Email&&void 0!==o.Email&&(n+='<span id="contact-'+o.identity+'-email" class=quickDial style="right: 66px; display:none" title=\''+lang.send_email+"' onclick=\"ComposeEmail('"+o.identity+'\', this, event)"><i class="fa fa-envelope-o" aria-hidden="true"></i></span>'),EnableVideoCalling?(n+='<span id="contact-'+o.identity+'-audio-dial" class=quickDial style="right: 44px; display:none" title=\''+lang.audio_call+"' onclick=\"QuickDialAudio('"+o.identity+'\', this, event)"><i class="fa fa-phone"></i></span>',n+='<span id="contact-'+o.identity+'-video-dial" class=quickDial style="right: 23px; display:none" title=\''+lang.video_call+"' onclick=\"QuickDialVideo('"+o.identity+"', '"+o.ExtNo+'\', event)"><i class="fa fa-video-camera"></i></span>'):n+='<span id="contact-'+o.identity+'-audio-dial" class=quickDial style="right: 23px; display:none" title=\''+lang.audio_call+"' onclick=\"QuickDialAudio('"+o.identity+'\', this, event)"><i class="fa fa-phone"></i></span>',o.missed&&o.missed>0?n+='<span id="contact-'+o.identity+'-missed" class=missedNotifyer>'+o.missed+"</span>":n+='<span id="contact-'+o.identity+'-missed" class=missedNotifyer style="display:none">'+o.missed+"</span>",n+="<div class=buddyIcon onclick=\"EditBuddyWindow('"+o.identity+"')\" style=\"background-image: url('"+getPicture(o.identity)+'\')" title="Edit Contact"><i class="fa fa-pencil-square-o" aria-hidden="true"></i></div>',n+='<div class=contactNameText><i class="fa fa-phone-square"></i> '+o.ExtNo+" - "+o.CallerIDName+"</div>",n+='<div id="contact-'+o.identity+'-datetime" class=contactDate>'+d+"</div>",n+='<div id="contact-'+o.identity+'-presence" class=presenceText>'+c+"</div>",n+="</div>",$("#myContacts").append(n)}else if("contact"==o.type){n='<div id="contact-'+o.identity+'" class='+i+" onmouseenter=\"ShowBuddyDial(this, '"+o.identity+"')\" onmouseleave=\"HideBuddyDial(this, '"+o.identity+"')\" onclick=\"SelectBuddy('"+o.identity+"', 'contact')\">";1==getDbItem("useRoundcube","")&&""!=o.Email&&null!=o.Email&&void 0!==o.Email&&(n+='<span id="contact-'+o.identity+'-email" class=quickDial style="right: 44px; display:none" title=\''+lang.send_email+"' onclick=\"ComposeEmail('"+o.identity+'\', this, event)"><i class="fa fa-envelope-o" aria-hidden="true"></i></span>'),n+='<span id="contact-'+o.identity+'-audio-dial" class=quickDial style="right: 23px; display:none" title=\''+lang.audio_call+"' onclick=\"QuickDialAudio('"+o.identity+'\', this, event)"><i class="fa fa-phone"></i></span>',o.missed&&o.missed>0?n+='<span id="contact-'+o.identity+'-missed" class=missedNotifyer>'+o.missed+"</span>":n+='<span id="contact-'+o.identity+'-missed" class=missedNotifyer style="display:none">'+o.missed+"</span>",n+="<div class=buddyIcon onclick=\"EditBuddyWindow('"+o.identity+"')\" style=\"background-image: url('"+getPicture(o.identity,"contact")+'\')" title="Edit Contact"><i class="fa fa-pencil-square-o" aria-hidden="true"></i></div>',n+='<div class=contactNameText><i class="fa fa-address-card"></i> '+o.CallerIDName+"</div>",n+='<div id="contact-'+o.identity+'-datetime" class=contactDate>'+d+"</div>",n+="<div class=presenceText>"+o.Desc+"</div>",n+="</div>",$("#myContacts").append(n)}else if("group"==o.type){n='<div id="contact-'+o.identity+'" class='+i+" onmouseenter=\"ShowBuddyDial(this, '"+o.identity+"')\" onmouseleave=\"HideBuddyDial(this, '"+o.identity+"')\" onclick=\"SelectBuddy('"+o.identity+"', 'group')\">";1==getDbItem("useRoundcube","")&&""!=o.Email&&null!=o.Email&&void 0!==o.Email&&(n+='<span id="contact-'+o.identity+'-email" class=quickDial style="right: 44px; display:none" title=\''+lang.send_email+"' onclick=\"ComposeEmail('"+o.identity+'\', this, event)"><i class="fa fa-envelope-o" aria-hidden="true"></i></span>'),n+='<span id="contact-'+o.identity+'-audio-dial" class=quickDial style="right: 23px; display:none" title=\''+lang.audio_call+"' onclick=\"QuickDialAudio('"+o.identity+'\', this, event)"><i class="fa fa-phone"></i></span>',o.missed&&o.missed>0?n+='<span id="contact-'+o.identity+'-missed" class=missedNotifyer>'+o.missed+"</span>":n+='<span id="contact-'+o.identity+'-missed" class=missedNotifyer style="display:none">'+o.missed+"</span>",n+="<div class=buddyIcon onclick=\"EditBuddyWindow('"+o.identity+"')\" style=\"background-image: url('"+getPicture(o.identity,"group")+'\')" title="Edit Contact"><i class="fa fa-pencil-square-o" aria-hidden="true"></i></div>',n+='<div class=contactNameText><i class="fa fa-users"></i> '+o.CallerIDName+"</div>",n+='<div id="contact-'+o.identity+'-datetime" class=contactDate>'+d+"</div>",n+="<div class=presenceText>"+o.Desc+"</div>",n+="</div>",$("#myContacts").append(n)}}}function AddBuddyMessageStream(e){var t='<table id="stream-'+e.identity+'" class=stream cellspacing=5 cellpadding=0>';if(t+='<tr><td class=streamSection style="height: 48px;">',t+='<div style="float:left; margin:8.7px 0px 0px 8.7px; width: 38px; height:38px; line-height:38px;">',t+='<button id="contact-'+e.identity+'-btn-back" onclick="CloseBuddy(\''+e.identity+'\')" class=roundButtons title="'+lang.back+'"><i class="fa fa-chevron-left"></i></button> ',t+="</div>",t+='<div class=contact style="float: left; position: absolute; left: 47px; right: 190px;" onclick="ShowBuddyProfileMenu(\''+e.identity+"', this, '"+e.type+"')\">","extension"==e.type&&(t+='<span id="contact-'+e.identity+'-devstate-main" class="'+e.devState+'"></span>'),"extension"==e.type?t+='<div id="contact-'+e.identity+'-picture-main" class=buddyIcon style="background-image: url(\''+getPicture(e.identity)+"')\"></div>":"contact"==e.type?t+="<div class=buddyIcon style=\"background-image: url('"+getPicture(e.identity,"contact")+"')\"></div>":"group"==e.type&&(t+="<div class=buddyIcon style=\"background-image: url('"+getPicture(e.identity,"group")+"')\"></div>"),"extension"==e.type?t+='<div class=contactNameText style="margin-right: 0px;"><i class="fa fa-phone-square"></i> '+e.ExtNo+" - "+e.CallerIDName+"</div>":"contact"==e.type?t+='<div class=contactNameText style="margin-right: 0px;"><i class="fa fa-address-card"></i> '+e.CallerIDName+"</div>":"group"==e.type&&(t+='<div class=contactNameText style="margin-right: 0px;"><i class="fa fa-users"></i> '+e.CallerIDName+"</div>"),"extension"==e.type){var i=e.presence;"Unknown"==i&&(i=lang.state_unknown),"Not online"==i&&(i=lang.state_not_online),"Ready"==i&&(i=lang.state_ready),"On the phone"==i&&(i=lang.state_on_the_phone),"Ringing"==i&&(i=lang.state_ringing),"On hold"==i&&(i=lang.state_on_hold),"Unavailable"==i&&(i=lang.state_unavailable),t+='<div id="contact-'+e.identity+'-presence-main" class=presenceText>'+i+"</div>"}else t+='<div id="contact-'+e.identity+'-presence-main" class=presenceText>'+e.Desc+"</div>";t+="</div>",t+='<div style="float:right; line-height:46px; margin:3.2px 5px 0px 0px;">',t+='<button id="contact-'+e.identity+'-btn-audioCall" onclick="AudioCallMenu(\''+e.identity+'\', this)" class=roundButtons title="'+lang.audio_call+'"><i class="fa fa-phone"></i></button> ',"extension"==e.type&&EnableVideoCalling&&(t+='<button id="contact-'+e.identity+"-btn-videoCall\" onclick=\"DialByLine('video', '"+e.identity+"', '"+e.ExtNo+'\');" class=roundButtons title="'+lang.video_call+'"><i class="fa fa-video-camera"></i></button> '),t+='<button id="contact-'+e.identity+'-btn-search" onclick="FindSomething(\''+e.identity+'\')" class=roundButtons title="'+lang.find_something+'"><i class="fa fa-search"></i></button> ',"extension"==e.type&&(t+='<button id="contact-'+e.identity+'-btn-download-chat" onclick="DownloadChatText(\''+e.identity+'\')" class=roundButtons title="'+lang.save_chat_text+'"><i class="fa fa-download" aria-hidden="true"></i></button> '),t+='<button id="contact-'+e.identity+'-btn-remove" onclick="RemoveBuddy(\''+e.identity+'\')" class=roundButtons title="'+lang.remove_contact+'"><i class="fa fa-trash"></i></button> ',t+="</div>",t+='<div style="clear:both; height:0px"></div>',t+='<div id="contact-'+e.identity+'-calling">',t+='<div id="contact-'+e.identity+'-timer" style="float: right; margin-top: 4px; margin-right: 10px; color: #575757; display:none;"></div>',t+='<div id="contact-'+e.identity+'-msg" class=callStatus style="display:none">...</div>',t+='<div id="contact-'+e.identity+'-AnswerCall" class=answerCall style="display:none">',t+="<div>",t+="<button onclick=\"AnswerAudioCall('"+e.identity+'\')" class=answerButton><i class="fa fa-phone"></i>&nbsp;&nbsp;'+lang.answer_call+"</button> ","extension"==e.type&&EnableVideoCalling&&(t+='<button id="contact-'+e.identity+'-answer-video" onclick="AnswerVideoCall(\''+e.identity+'\')" class=answerButton><i class="fa fa-video-camera"></i>&nbsp;&nbsp;'+lang.answer_call_with_video+"</button> "),t+="<button onclick=\"RejectCall('"+e.identity+'\')" class=hangupButton><i class="fa fa-phone"></i>&nbsp;&nbsp;'+lang.reject_call+"</button> ",t+="</div>",t+="</div>",t+="</div>",t+='<div id="contact-'+e.identity+'-search" style="margin-top:6px; display:none">',t+='<span class=searchClean style="width:100%; margin-left:9px;"><input type=text style="width:40%;margin-bottom:5px;" autocomplete=none oninput=SearchStream(this,\''+e.identity+"') placeholder=\""+lang.find_something_in_the_message_stream+'"></span>',t+="</div>",t+="</td></tr>",t+='<tr><td class="streamSection streamSectionBackground">',t+='<div id="contact-'+e.identity+'-ChatHistory" class="chatHistory cleanScroller" ondragenter="setupDragDrop(event, \''+e.identity+"')\" ondragover=\"setupDragDrop(event, '"+e.identity+"')\" ondragleave=\"cancelDragDrop(event, '"+e.identity+"')\" ondrop=\"onFileDragDrop(event, '"+e.identity+"')\">",t+="</div>",t+="</td></tr>","extension"!=e.type&&"group"!=e.type||!EnableTextMessaging||(t+='<tr><td  id=sendChatMessageSection class=streamSection style="height:110px">',t+='<div id="contact-'+e.identity+'-imagePastePreview" class=sendImagePreview style="display:none" tabindex=0></div>',t+='<div id="contact-'+e.identity+'-fileShare" style="display:none">',t+='<input type=file multiple onchange="console.log(this)" />',t+="</div>",t+='<div id="contact-'+e.identity+'-audio-recording" style="display:none"></div>',t+='<div id="contact-'+e.identity+'-video-recording" style="display:none"></div>',t+='<div id="contact-'+e.identity+'-emoji-menu" style="display:none" class="EmojiMenu"></div>',t+="<table class=sendMessageContainer cellpadding=0 cellspacing=0><tr>",t+='<td><textarea id="contact-'+e.identity+'-ChatMessage" class="chatMessage" placeholder="'+lang.type_your_message_here+'" onkeydown="chatOnkeydown(event, this,\''+e.identity+"')\" onpaste=\"chatOnbeforepaste(event, this,'"+e.identity+"')\"></textarea></td>",t+='<td style="width:40px;padding-top:4px;"><button onclick="SendChatMessage(\''+e.identity+'\')" class=roundButtonsSpec title="'+lang.send_chat_message+'"><i class="fa fa-paper-plane-o" aria-hidden="true"></i></button>',t+="<button onclick=\"ShowEmojiBar('"+e.identity+'\')" class=roundButtonsSpec title="'+lang.select_expression+'"><i class="fa fa-smile-o"></i></button>',t+="<button onclick=\"SendFile('"+e.identity+'\')" class=roundButtonsSpec title="'+lang.send_file+'"><i class="fa fa-file-text-o"></i></button></td>',t+="</tr></table>",t+="</td></tr>"),t+="</table>",$("#rightContent").append(t)}function RemoveBuddyMessageStream(e){CloseBuddy(e.identity),UpdateBuddyList(),$("#stream-"+e.identity).remove();var t=JSON.parse(localDB.getItem(e.identity+"-stream"));localDB.removeItem(e.identity+"-stream");var i=JSON.parse(localDB.getItem(profileUserID+"-Buddies")),n=0;$.each(i.DataCollection,(function(t,i){if(i.uID==e.identity||i.cID==e.identity||i.gID==e.identity)return n=t,!1})),i.DataCollection.splice(n,1),i.TotalRows=i.DataCollection.length,localDB.setItem(profileUserID+"-Buddies",JSON.stringify(i)),localDB.removeItem("img-"+e.identity+"-extension"),localDB.removeItem("img-"+e.identity+"-contact"),localDB.removeItem("img-"+e.identity+"-group"),t&&t.DataCollection&&t.DataCollection.length>=1&&DeleteCallRecordings(e.identity,t),DeleteQosData(e.identity)}function DeleteCallRecordings(e,t){var i=window.indexedDB.open("CallRecordings");i.onerror=function(e){console.error("IndexDB Request Error:",e)},i.onupgradeneeded=function(e){console.warn("Upgrade Required for IndexDB... probably because of first time use.")},i.onsuccess=function(e){console.log("IndexDB connected to CallRecordings");var i=e.target.result;0!=i.objectStoreNames.contains("Recordings")?(i.onerror=function(e){console.error("IndexDB Error:",e)},$.each(t.DataCollection,(function(e,t){t.Recordings&&t.Recordings.length&&$.each(t.Recordings,(function(e,t){console.log("Deleting Call Recording: ",t.uID);var n=i.transaction(["Recordings"],"readwrite").objectStore("Recordings");try{n.delete(t.uID).onsuccess=function(e){console.log("Call Recording Deleted: ",t.uID)}}catch(e){console.log("Call Recording Delete failed: ",e)}}))}))):console.warn("IndexDB CallRecordings.Recordings does not exists")}}function MakeUpName(){var e=["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"],t="";t+=e[Math.floor(Math.random()*e.length)];for(var i=0;i<Math.floor(12*Math.random())+4;i++)t+=e[Math.floor(Math.random()*e.length)].toLowerCase();t+=" ",t+=e[Math.floor(Math.random()*e.length)];for(i=0;i<Math.floor(12*Math.random())+4;i++)t+=e[Math.floor(Math.random()*e.length)].toLowerCase();return t}function MakeUpNumber(){for(var e=["0","1","2","3","4","5","6","7","8","9","0"],t="0",i=0;i<9;i++)t+=e[Math.floor(Math.random()*e.length)];return t}function MakeUpBuddies(e){for(var t=0;t<e;t++){AddBuddy(new Buddy("contact",uID(),MakeUpName(),"","",MakeUpNumber(),"",utcDateNow(),"Testing",""),!1,!1)}UpdateBuddyList()}function SelectBuddy(e){$("#roundcubeFrame").remove(),$(".streamSelected").each((function(){$(this).show()}));var t=FindBuddyByIdentity(e);if(null!=t){for(var i=0;i<Buddies.length;i++)if(1==Buddies[i].IsSelected&&Buddies[i].identity==e)return;console.log("Selecting Buddy: "+e),selectedBuddy=t,$(".streamSelected").each((function(){$(this).prop("class","stream")})),$("#stream-"+e).prop("class","streamSelected");for(var n=0;n<Lines.length;n++){var a="buddy";null!=Lines[n].SipSession&&(a=Lines[n].SipSession.local_hold?"buddyActiveCallHollding":"buddyActiveCall"),$("#line-"+Lines[n].LineNumber).prop("class",a),Lines[n].IsSelected=!1}ClearMissedBadge(e);for(i=0;i<Buddies.length;i++){a=Buddies[i].identity==e?"buddySelected":"buddy";$("#contact-"+Buddies[i].identity).prop("class",a),$("#contact-"+Buddies[i].identity+"-ChatHistory").empty(),Buddies[i].IsSelected=Buddies[i].identity==e}UpdateUI(),RefreshStream(t);try{$("#contact-"+e).get(0).scrollIntoViewIfNeeded()}catch(e){}localDB.setItem("SelectedBuddy",e)}}function CloseBuddy(e){$(".buddySelected").each((function(){$(this).prop("class","buddy")})),$(".streamSelected").each((function(){$(this).prop("class","stream")})),console.log("Closing Buddy: "+e);for(var t=0;t<Buddies.length;t++)Buddies[t].IsSelected=!1;selectedBuddy=null;for(var i=0;i<Lines.length;i++)Lines[i].IsSelected=!1;selectedLine=null,localDB.setItem("SelectedBuddy",null),UpdateUI()}function DownloadChatText(e){var t=FindBuddyByIdentity(e),i=t.CallerIDName,n=i.replace(" ","_"),a=t.ExtNo,o=moment().format("YYYY-MM-DD_HH-mm-ss"),l="\nRoundpin Chat With "+i+" (extension "+a+"), saved on "+moment().format("YYYY-MM-DD HH:mm:ss")+"\n\n\n\n",s="";if($("#contact-"+e+"-ChatHistory .chatMessageTable").each((function(){$(this).hasClass("theirChatMessage")?s+="\n"+i+"\n"+$(this).text()+"\n\n":s+="\nMe\n"+$(this).text()+"\n\n"})),""!=s){var r=l+s,d="Roundpin_Chat-"+n+"_"+o,c=document.createElement("a");c.setAttribute("download",d),c.setAttribute("href","data:text/plain;charset=utf-8,"+encodeURIComponent(r)),c.click()}else alert("There is no chat text to save ! ")}function RemoveBuddy(e){var t=FindBuddyByIdentity(e).CallerIDName;Confirm(lang.confirm_remove_buddy,lang.remove_buddy,(function(){for(var i=0;i<Buddies.length;i++)if(Buddies[i].identity==e){RemoveBuddyMessageStream(Buddies[i]),UnsubscribeBuddy(Buddies[i]),Buddies.splice(i,1);break}deleteBuddyFromSqldb(t),UpdateBuddyList()}))}function FindBuddyByDid(e){for(var t=0;t<Buddies.length;t++)if(Buddies[t].ExtNo==e||Buddies[t].MobileNumber==e||Buddies[t].ContactNumber1==e||Buddies[t].ContactNumber2==e)return Buddies[t];return null}function FindBuddyByExtNo(e){for(var t=0;t<Buddies.length;t++)if("extension"==Buddies[t].type&&Buddies[t].ExtNo==e)return Buddies[t];return null}function FindBuddyByNumber(e){for(var t=0;t<Buddies.length;t++)if(Buddies[t].MobileNumber==e||Buddies[t].ContactNumber1==e||Buddies[t].ContactNumber2==e)return Buddies[t];return null}function FindBuddyByIdentity(e){for(var t=0;t<Buddies.length;t++)if(Buddies[t].identity==e)return Buddies[t];return null}function SearchStream(e,t){var i=e.value,n=FindBuddyByIdentity(t);""==i?(console.log("Restore Stream"),RefreshStream(n)):RefreshStream(n,i)}function RefreshStream(e,t){$("#contact-"+e.identity+"-ChatHistory").empty();var i=JSON.parse(localDB.getItem(e.identity+"-stream"));null!=i&&null!=i.DataCollection&&(i.DataCollection.sort((function(e,t){var i=moment.utc(e.ItemDate.replace(" UTC","")),n=moment.utc(t.ItemDate.replace(" UTC",""));return i.isSameOrAfter(n,"second")?-1:1})),t&&""!=t&&(console.log("Rows without filter ("+t+"): ",i.DataCollection.length),i.DataCollection=i.DataCollection.filter((function(e){if(-1!=t.indexOf("date: ")){var i=getFilter(t,"date");if(""!=i&&-1!=e.ItemDate.indexOf(i))return!0}if(e.MessageData&&e.MessageData.length>1){if(-1!=e.MessageData.toLowerCase().indexOf(t.toLowerCase()))return!0;if(-1!=t.toLowerCase().indexOf(e.MessageData.toLowerCase()))return!0}if("MSG"==e.ItemType);else if("CDR"==e.ItemType){if(e.Tags&&e.Tags.length>1){var n=getFilter(t,"tag");if(""!=n&&1==e.Tags.some((function(e){return-1!=n.toLowerCase().indexOf(e.value.toLowerCase())||-1!=e.value.toLowerCase().indexOf(n.toLowerCase())})))return!0}}else"FILE"==e.ItemType||e.ItemType;return!1})),console.log("Rows After Filter: ",i.DataCollection.length)),i.DataCollection.length>StreamBuffer&&(console.log("Rows:",i.DataCollection.length," (will be trimed to "+StreamBuffer+")"),i.DataCollection.splice(StreamBuffer)),$.each(i.DataCollection,(function(t,i){var n=moment.utc(i.ItemDate.replace(" UTC","")).isSame(moment.utc(),"day"),a="  "+moment.utc(i.ItemDate.replace(" UTC","")).local().calendar(null,{sameElse:DisplayDateFormat});if(n&&(a="  "+moment.utc(i.ItemDate.replace(" UTC","")).local().format(DisplayTimeFormat)),"MSG"==i.ItemType){var o='<i class="fa fa-question-circle-o SendingMessage"></i>';1==i.Sent&&(o='<i class="fa fa-check SentMessage"></i>'),0==i.Sent&&(o='<i class="fa fa-exclamation-circle FailedMessage"></i>'),i.Delivered&&(o+='<i class="fa fa-check DeliveredMessage"></i>');var l=(d=ReformatMessage(i.MessageData)).length>1e3;if(i.SrcUserId==profileUserID){if(0!=d.length){var s='<table class="ourChatMessage chatMessageTable" cellspacing=0 cellpadding=0><tr>';s+='<td class=ourChatMessageText onmouseenter="ShowChatMenu(this)" onmouseleave="HideChatMenu(this)">',s+="<span onclick=\"ShowMessgeMenu(this,'MSG','"+i.ItemId+"', '"+e.identity+'\')" class=chatMessageDropdown style="display:none"><i class="fa fa-chevron-down"></i></span>',s+="<div id=msg-text-"+i.ItemId+' class=messageText style="'+(l?"max-height:190px; overflow:hidden":"")+'">'+d+"</div>",l&&(s+="<div id=msg-readmore-"+i.ItemId+" class=messageReadMore><span onclick=\"ExpandMessage(this,'"+i.ItemId+"', '"+e.identity+"')\">"+lang.read_more+"</span></div>"),s+="<div class=messageDate>"+a+" "+o+"</div>",s+="</td>",s+="</tr></table>"}}else{if(0!=d.length){s='<table class="theirChatMessage chatMessageTable" cellspacing=0 cellpadding=0><tr>';s+='<td class=theirChatMessageText onmouseenter="ShowChatMenu(this)" onmouseleave="HideChatMenu(this)">',s+="<span onclick=\"ShowMessgeMenu(this,'MSG','"+i.ItemId+"', '"+e.identity+'\')" class=chatMessageDropdown style="display:none"><i class="fa fa-chevron-down"></i></span>',"group"==e.type&&(s+="<div class=messageDate></div>"),s+="<div id=msg-text-"+i.ItemId+' class=messageText style="'+(l?"max-height:190px; overflow:hidden":"")+'">'+d+"</div>",l&&(s+="<div id=msg-readmore-"+i.ItemId+" class=messageReadMore><span onclick=\"ExpandMessage(this,'"+i.ItemId+"', '"+e.identity+"')\">"+lang.read_more+"</span></div>"),s+="<div class=messageDate>"+a+"</div>",s+="</td>",s+="</tr></table>"}}0!=d.length&&$("#contact-"+e.identity+"-ChatHistory").prepend(s)}else if("CDR"==i.ItemType){var r=i.Billsec>0?"green":"red",d="",c="<span id=cdr-flagged-"+i.CdrId+' style="'+(i.Flagged?"":"display:none")+'">';c+='<i class="fa fa-flag FlagCall"></i> ',c+="</span>";var u="";i.MessageData&&(u=i.MessageData),i.Tags||(i.Tags=[]);var p="<ul id=cdr-tags-"+i.CdrId+' class=tags style="'+(i.Tags&&i.Tags.length>0?"":"display:none")+'">';$.each(i.Tags,(function(t,n){p+="<li onclick=\"TagClick(this, '"+i.CdrId+"', '"+e.identity+"')\">"+n.value+"</li>"})),p+="<li class=tagText><input maxlength=24 type=text onkeypress=\"TagKeyPress(event, this, '"+i.CdrId+"', '"+e.identity+'\')" onfocus="TagFocus(this)"></li>',p+="</ul>",d+='<i class="fa '+(i.WithVideo?"fa-video-camera":"fa-phone")+'" style="color:'+r+'"></i>';var g=i.WithVideo?lang.a_video_call:lang.an_audio_call,m="";if(i.Recordings&&i.Recordings.length>=1&&$.each(i.Recordings,(function(t,n){if(n.uID){var a=moment.utc(n.startTime.replace(" UTC","")).local(),o=moment.utc(n.stopTime.replace(" UTC","")).local(),l=moment.duration(o.diff(a));if(m+="<div class=callRecording>",i.WithVideo)if(n.Poster){n.Poster.width,n.Poster.height;var s=n.Poster.posterBase64;m+='<div><IMG src="'+s+'"><button onclick="PlayVideoCallRecording(this, \''+i.CdrId+"', '"+n.uID+'\')" class=videoPoster><i class="fa fa-play"></i></button></div>'}else m+="<div><button onclick=\"PlayVideoCallRecording(this, '"+i.CdrId+"', '"+n.uID+"', '"+e.identity+'\')"><i class="fa fa-video-camera"></i></button></div>';else m+="<div><button onclick=\"PlayAudioCallRecording(this, '"+i.CdrId+"', '"+n.uID+"', '"+e.identity+'\')"><i class="fa fa-play"></i></button></div>';m+="<div>"+lang.started+": "+a.format(DisplayTimeFormat)+' <i class="fa fa-long-arrow-right"></i> '+lang.stopped+": "+o.format(DisplayTimeFormat)+"</div>",m+="<div>"+lang.recording_duration+": "+formatShortDuration(l.asSeconds())+"</div>",m+="<div>",m+='<span id="cdr-video-meta-width-'+i.CdrId+"-"+n.uID+'"></span>',m+='<span id="cdr-video-meta-height-'+i.CdrId+"-"+n.uID+'"></span>',m+='<span id="cdr-media-meta-size-'+i.CdrId+"-"+n.uID+'"></span>',m+='<span id="cdr-media-meta-codec-'+i.CdrId+"-"+n.uID+'"></span>',m+="</div>",m+="</div>"}})),i.SrcUserId==profileUserID){"0"==i.Billsec?d+=" "+lang.you_tried_to_make+" "+g+" ("+i.ReasonText+").":d+=" "+lang.you_made+" "+g+", "+lang.and_spoke_for+" "+formatDuration(i.Billsec)+".";s='<table class="ourChatMessage chatMessageTable" cellspacing=0 cellpadding=0><tr>';s+='<td style="padding-right:4px;">'+c+"</td>",s+='<td class=ourChatMessageText onmouseenter="ShowChatMenu(this)" onmouseleave="HideChatMenu(this)">',s+="<span onClick=\"ShowMessgeMenu(this,'CDR','"+i.CdrId+"', '"+e.identity+'\')" class=chatMessageDropdown style="display:none"><i class="fa fa-chevron-down"></i></span>',s+="<div>"+d+"</div>",s+="<div>"+p+"</div>",s+="<div id=cdr-comment-"+i.CdrId+" class=cdrComment>"+u+"</div>",s+="<div class=callRecordings>"+m+"</div>",s+="<div class=messageDate>"+a+"</div>",s+="</td>",s+="</tr></table>"}else{"0"==i.Billsec?d+=" "+lang.you_missed_a_call+" ("+i.ReasonText+").":d+=" "+lang.you_recieved+" "+g+", "+lang.and_spoke_for+" "+formatDuration(i.Billsec)+".";s='<table class="theirChatMessage chatMessageTable" cellspacing=0 cellpadding=0><tr>';s+='<td class=theirChatMessageText onmouseenter="ShowChatMenu(this)" onmouseleave="HideChatMenu(this)">',s+="<span onClick=\"ShowMessgeMenu(this,'CDR','"+i.CdrId+"', '"+e.identity+'\')" class=chatMessageDropdown style="display:none"><i class="fa fa-chevron-down"></i></span>',s+='<div style="text-align:left">'+d+"</div>",s+="<div>"+p+"</div>",s+="<div id=cdr-comment-"+i.CdrId+" class=cdrComment>"+u+"</div>",s+="<div class=callRecordings>"+m+"</div>",s+="<div class=messageDate> "+a+"</div>",s+="</td>",s+='<td style="padding-left:4px">'+c+"</td>",s+="</tr></table>"}$("#contact-"+e.identity+"-ChatHistory").prepend(s)}else if("FILE"==i.ItemType)if(i.SrcUserId==profileUserID){var f='<table class="ourChatMessage chatMessageTable" cellspacing=0 cellpadding=0><tr>';f+="<td><div class='sentFileChatRect'>Download file<br><a href='download-sent-chat-file.php?s_ajax_call="+validateSToken+"&destSipUser="+i.Dst+"&sentFlNm="+i.SentFileName+"' target='_blank'>"+i.SentFileName+"</a>",f+='<span style="display:block;width:100%;height:10px;"></span><div class="messageDate">'+a+"</div></div>",f+="</td>",f+="</tr></table>",$("#contact-"+e.identity+"-ChatHistory").prepend(f),$("#sendFileLoader").remove()}else{var v='<table class="theirChatMessage chatMessageTable" cellspacing=0 cellpadding=0><tr>';v+="<td><div class='recFileChatRect'>Download file<br><a href='download-rec-chat-file.php?s_ajax_call="+validateSToken+"&recSipUser="+i.Dst+"&recFlNm="+i.ReceivedFileName+"' target='_blank'>"+i.ReceivedFileName+"</a>",v+='<span style="display:block;width:100%;height:10px;"></span><div class="messageDate">'+a+"</div></div>",v+="</td>",v+="</tr></table>",$("#contact-"+e.identity+"-ChatHistory").prepend(v)}else i.ItemType})),updateScroll(e.identity),window.setTimeout((function(){updateScroll(e.identity)}),300))}function ShowChatMenu(e){$(e).children("span").show()}function HideChatMenu(e){$(e).children("span").hide()}function ExpandMessage(e,t,i){$("#msg-text-"+t).css("max-height",""),$("#msg-text-"+t).css("overflow",""),$("#msg-readmore-"+t).remove(),$.jeegoopopup.close()}function ShowBuddyDial(e,t){$("#contact-"+t+"-email").show(),$("#contact-"+t+"-audio-dial").show(),$("#contact-"+t+"-video-dial").show()}function HideBuddyDial(e,t){$("#contact-"+t+"-email").hide(),$("#contact-"+t+"-audio-dial").hide(),$("#contact-"+t+"-video-dial").hide()}function QuickDialAudio(e,t,i){AudioCallMenu(e,t),i.stopPropagation()}function QuickDialVideo(e,t,i){i.stopPropagation(),window.setTimeout((function(){DialByLine("video",e,t)}),300)}function ExpandVideoArea(e){$("#line-"+e+"-ActiveCall").prop("class","FullScreenVideo"),$("#line-"+e+"-VideoCall").css("height","calc(100% - 100px)"),$("#line-"+e+"-VideoCall").css("margin-top","0px"),$("#line-"+e+"-preview-container").prop("class","PreviewContainer PreviewContainer_FS"),$("#line-"+e+"-stage-container").prop("class","StageContainer StageContainer_FS"),$("#line-"+e+"-restore").show(),$("#line-"+e+"-expand").hide(),$("#line-"+e+"-monitoring").hide()}function RestoreVideoArea(e){$("#line-"+e+"-ActiveCall").prop("class",""),$("#line-"+e+"-VideoCall").css("height",""),$("#line-"+e+"-VideoCall").css("margin-top","10px"),$("#line-"+e+"-preview-container").prop("class","PreviewContainer"),$("#line-"+e+"-stage-container").prop("class","StageContainer"),$("#line-"+e+"-restore").hide(),$("#line-"+e+"-expand").show(),$("#line-"+e+"-monitoring").show()}function MuteSession(e){$("#line-"+e+"-btn-Unmute").show(),$("#line-"+e+"-btn-Mute").hide();var t=FindLineByNumber(e);if(null!=t&&null!=t.SipSession){var i=t.SipSession;i.sessionDescriptionHandler.peerConnection.getSenders().forEach((function(e){"audio"==e.track.kind&&(1==e.track.IsMixedTrack?i.data.AudioSourceTrack&&"audio"==i.data.AudioSourceTrack.kind&&(console.log("Muting Audio Track : "+i.data.AudioSourceTrack.label),i.data.AudioSourceTrack.enabled=!1):(console.log("Muting Audio Track : "+e.track.label),e.track.enabled=!1))})),i.data.mute||(i.data.mute=[]),i.data.mute.push({event:"mute",eventTime:utcDateNow()}),i.data.ismute=!0,$("#line-"+e+"-msg").html(lang.call_on_mute),updateLineScroll(e),"undefined"!=typeof web_hook_on_modify&&web_hook_on_modify("mute",i)}}function UnmuteSession(e){$("#line-"+e+"-btn-Unmute").hide(),$("#line-"+e+"-btn-Mute").show();var t=FindLineByNumber(e);if(null!=t&&null!=t.SipSession){var i=t.SipSession;i.sessionDescriptionHandler.peerConnection.getSenders().forEach((function(e){"audio"==e.track.kind&&(1==e.track.IsMixedTrack?i.data.AudioSourceTrack&&"audio"==i.data.AudioSourceTrack.kind&&(console.log("Unmuting Audio Track : "+i.data.AudioSourceTrack.label),i.data.AudioSourceTrack.enabled=!0):(console.log("Unmuting Audio Track : "+e.track.label),e.track.enabled=!0))})),i.data.mute||(i.data.mute=[]),i.data.mute.push({event:"unmute",eventTime:utcDateNow()}),i.data.ismute=!1,$("#line-"+e+"-msg").html(lang.call_off_mute),updateLineScroll(e),"undefined"!=typeof web_hook_on_modify&&web_hook_on_modify("unmute",i)}}function ShowDtmfMenu(e,t){var i=event.pageX-90,n=event.pageY+30,a="<div id=mainDtmfDialPad>";a+='<table cellspacing=10 cellpadding=0 style="margin-left:auto; margin-right: auto">',a+="<tr><td><button class=dtmfButtons onclick=\"sendDTMF('"+t+"', '1');new Audio('sounds/dtmf.mp3').play();\"><div>1</div><span>&nbsp;</span></button></td>",a+="<td><button class=dtmfButtons onclick=\"sendDTMF('"+t+"', '2');new Audio('sounds/dtmf.mp3').play();\"><div>2</div><span>ABC</span></button></td>",a+="<td><button class=dtmfButtons onclick=\"sendDTMF('"+t+"', '3');new Audio('sounds/dtmf.mp3').play();\"><div>3</div><span>DEF</span></button></td></tr>",a+="<tr><td><button class=dtmfButtons onclick=\"sendDTMF('"+t+"', '4');new Audio('sounds/dtmf.mp3').play();\"><div>4</div><span>GHI</span></button></td>",a+="<td><button class=dtmfButtons onclick=\"sendDTMF('"+t+"', '5');new Audio('sounds/dtmf.mp3').play();\"><div>5</div><span>JKL</span></button></td>",a+="<td><button class=dtmfButtons onclick=\"sendDTMF('"+t+"', '6');new Audio('sounds/dtmf.mp3').play();\"><div>6</div><span>MNO</span></button></td></tr>",a+="<tr><td><button class=dtmfButtons onclick=\"sendDTMF('"+t+"', '7');new Audio('sounds/dtmf.mp3').play();\"><div>7</div><span>PQRS</span></button></td>",a+="<td><button class=dtmfButtons onclick=\"sendDTMF('"+t+"', '8');new Audio('sounds/dtmf.mp3').play();\"><div>8</div><span>TUV</span></button></td>",a+="<td><button class=dtmfButtons onclick=\"sendDTMF('"+t+"', '9');new Audio('sounds/dtmf.mp3').play();\"><div>9</div><span>WXYZ</span></button></td></tr>",a+="<tr><td><button class=dtmfButtons onclick=\"sendDTMF('"+t+"', '*');new Audio('sounds/dtmf.mp3').play();\">*</button></td>",a+="<td><button class=dtmfButtons onclick=\"sendDTMF('"+t+"', '0');new Audio('sounds/dtmf.mp3').play();\">0</button></td>",a+="<td><button class=dtmfButtons onclick=\"sendDTMF('"+t+"', '#');new Audio('sounds/dtmf.mp3').play();\">#</button></td></tr>",a+="</table>",a+="</div>",$.jeegoopopup.open({html:a,width:"auto",height:"auto",left:i,top:n,scrolling:"no",skinClass:"jg_popup_basic",overlay:!0,opacity:0,draggable:!0,resizable:!1,fadeIn:0}),$("#jg_popup_overlay").click((function(){$.jeegoopopup.close()})),$(window).on("keydown",(function(e){"Escape"==e.key&&$.jeegoopopup.close()}))}function ShowMessgeMenu(t,i,n,a){$.jeegoopopup.close();var o=event.pageX,l=event.pageY;$(window).width()-event.pageX<t.offsetWidth+50&&(o=event.pageX-200);var s='<div id="messageMenu">';if(s+='<table id="messageMenuTable" cellspacing=10 cellpadding=0 style="margin-left:auto; margin-right: auto">',"CDR"==i){var r=$("#cdr-flagged-"+n).is(":visible")?lang.clear_flag:lang.flag_call;s+='<tr id="CMDetails_1"><td><i class="fa fa-external-link"></i></td><td class="callDetails">'+lang.show_call_detail_record+"</td></tr>",s+='<tr id="CMDetails_2"><td><i class="fa fa-tags"></i></td><td class="callDetails">'+lang.tag_call+"</td></tr>",s+='<tr id="CMDetails_3"><td><i class="fa fa-flag"></i></td><td class="callDetails">'+r+"</td></tr>",s+='<tr id="CMDetails_4"><td><i class="fa fa-quote-left"></i></td><td class="callDetails">'+lang.edit_comment+"</td></tr>"}"MSG"==i&&(s+='<tr id="CMDetails_5"><td><i class="fa fa-clipboard"></i></td><td class="callDetails">'+lang.copy_message+"</td></tr>",s+='<tr id="CMDetails_6"><td><i class="fa fa-quote-left"></i></td><td class="callDetails">'+lang.quote_message+"</td></tr>"),s+="</table></div>",$.jeegoopopup.open({html:s,width:"auto",height:"auto",left:o,top:l,scrolling:"no",skinClass:"jg_popup_basic",overlay:!0,opacity:0,draggable:!1,resizable:!1,fadeIn:0}),$("#jg_popup_overlay").click((function(){$.jeegoopopup.close()})),$(window).on("keydown",(function(e){"Escape"==e.key&&$.jeegoopopup.close()})),$("#CMDetails_1").click((function(e){var t=null,i=JSON.parse(localDB.getItem(a+"-stream"));if(null==i&&null==i.DataCollection||$.each(i.DataCollection,(function(e,i){if("CDR"==i.ItemType&&i.CdrId==n)return t=i,!1})),null!=t){var o=[],l='<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>';l+='<div class="UiWindowField scroller">';var s=moment.utc(t.ItemDate.replace(" UTC","")).local().format(DisplayDateFormat+" "+DisplayTimeFormat),r=t.CallAnswer?moment.utc(t.CallAnswer.replace(" UTC","")).local().format(DisplayDateFormat+" "+DisplayTimeFormat):null,d=t.RingTime?t.RingTime:0,c=(moment.utc(t.CallEnd.replace(" UTC","")).local().format(DisplayDateFormat+" "+DisplayTimeFormat),""),u="";"inbound"==t.CallDirection?c=t.Src:"outbound"==t.CallDirection&&(u=t.Dst),l+="<div class=UiText><b>SIP CallID</b> : "+t.SessionId+"</div>",l+="<div class=UiText><b>"+lang.call_direction+"</b> : "+t.CallDirection+"</div>",l+="<div class=UiText><b>"+lang.call_date_and_time+"</b> : "+s+"</div>",l+="<div class=UiText><b>"+lang.ring_time+"</b> : "+formatDuration(d)+" ("+d+")</div>",l+="<div class=UiText><b>"+lang.talk_time+"</b> : "+formatDuration(t.Billsec)+" ("+t.Billsec+")</div>",l+="<div class=UiText><b>"+lang.call_duration+"</b> : "+formatDuration(t.TotalDuration)+" ("+t.TotalDuration+")</div>",l+="<div class=UiText><b>"+lang.video_call+"</b> : "+(t.WithVideo?lang.yes:lang.no)+"</div>",l+="<div class=UiText><b>"+lang.flagged+"</b> : "+(t.Flagged?'<i class="fa fa-flag FlagCall"></i> '+lang.yes:lang.no)+"</div>",l+="<hr>",l+='<h2 style="font-size: 16px">'+lang.call_tags+"</h2>",l+="<hr>",$.each(t.Tags,(function(e,t){l+="<span class=cdrTag>"+t.value+"</span>"})),l+='<h2 style="font-size: 16px">'+lang.call_notes+"</h2>",l+="<hr>",t.MessageData&&(l+='"'+t.MessageData+'"'),l+='<h2 style="font-size: 16px">'+lang.activity_timeline+"</h2>",l+="<hr>";var p=t.WithVideo?"("+lang.with_video+")":"",g="inbound"==t.CallDirection?lang.you_received_a_call_from+" "+c+" "+p:lang.you_made_a_call_to+" "+u+" "+p;if(o.push({Message:g,TimeStr:t.ItemDate}),r){var m="inbound"==t.CallDirection?lang.you_answered_after+" "+d+" "+lang.seconds_plural:lang.they_answered_after+" "+d+" "+lang.seconds_plural;o.push({Message:m,TimeStr:t.CallAnswer})}$.each(t.Transfers,(function(e,t){var i="Blind"==t.type?lang.you_started_a_blind_transfer_to+" "+t.to+". ":lang.you_started_an_attended_transfer_to+" "+t.to+". ";t.accept&&1==t.accept.complete?i+=lang.the_call_was_completed:""!=t.accept.disposition&&(i+=lang.the_call_was_not_completed+" ("+t.accept.disposition+")"),o.push({Message:i,TimeStr:t.transferTime})})),$.each(t.Mutes,(function(e,t){o.push({Message:"mute"==t.event?lang.you_put_the_call_on_mute:lang.you_took_the_call_off_mute,TimeStr:t.eventTime})})),$.each(t.Holds,(function(e,t){o.push({Message:"hold"==t.event?lang.you_put_the_call_on_hold:lang.you_took_the_call_off_hold,TimeStr:t.eventTime})})),$.each(t.ConfCalls,(function(e,t){var i=lang.you_started_a_conference_call_to+" "+t.to+". ";t.accept&&1==t.accept.complete?i+=lang.the_call_was_completed:""!=t.accept.disposition&&(i+=lang.the_call_was_not_completed+" ("+t.accept.disposition+")"),o.push({Message:i,TimeStr:t.startTime})})),$.each(t.Recordings,(function(e,t){var i=moment.utc(t.startTime.replace(" UTC","")).local(),n=moment.utc(t.stopTime.replace(" UTC","")).local(),a=moment.duration(n.diff(i)),l=lang.call_is_being_recorded;t.startTime!=t.stopTime&&(l+="("+formatShortDuration(a.asSeconds())+")"),o.push({Message:l,TimeStr:t.startTime})})),o.push({Message:"us"==t.Terminate?"You ended the call.":"They ended the call",TimeStr:t.CallEnd}),o.sort((function(e,t){var i=moment.utc(e.TimeStr.replace(" UTC","")),n=moment.utc(t.TimeStr.replace(" UTC",""));return i.isSameOrAfter(n,"second")?1:-1})),$.each(o,(function(e,t){var i="<table class=timelineMessage cellspacing=0 cellpadding=0><tr>";i+="<td class=timelineMessageArea>",i+='<div class=timelineMessageDate style="color: #333333"><i class="fa fa-circle timelineMessageDot"></i>'+moment.utc(t.TimeStr.replace(" UTC","")).local().format(DisplayTimeFormat)+"</div>",i+='<div class=timelineMessageText style="color: #000000">'+t.Message+"</div>",i+="</td>",l+=i+="</tr></table>"})),l+='<h2 style="font-size: 16px">'+lang.call_recordings+"</h2>",l+="<hr>";var f="";$.each(t.Recordings,(function(e,i){if(i.uID){var n=moment.utc(i.startTime.replace(" UTC","")).local(),a=moment.utc(i.stopTime.replace(" UTC","")).local(),o=moment.duration(a.diff(n));f+="<div>",t.WithVideo?f+='<div><video id="callrecording-video-'+i.uID+'" controls style="width: 100%"></div>':f+='<div><audio id="callrecording-audio-'+i.uID+'" controls style="width: 100%"></div>',f+="<div>"+lang.started+": "+n.format(DisplayTimeFormat)+' <i class="fa fa-long-arrow-right"></i> '+lang.stopped+": "+a.format(DisplayTimeFormat)+"</div>",f+="<div>"+lang.recording_duration+": "+formatShortDuration(o.asSeconds())+"</div>",f+='<div><a id="download-'+i.uID+'">'+lang.save_as+"</a> ("+lang.right_click_and_select_save_link_as+")</div>",f+="</div>"}})),l+=f,l+='<h2 style="font-size: 16px">'+lang.send_statistics+"</h2>",l+="<hr>",l+='<div style="position: relative; margin: auto; height: 160px; width: 100%;"><canvas id="cdr-AudioSendBitRate"></canvas></div>',l+='<div style="position: relative; margin: auto; height: 160px; width: 100%;"><canvas id="cdr-AudioSendPacketRate"></canvas></div>',l+='<h2 style="font-size: 16px">'+lang.receive_statistics+"</h2>",l+="<hr>",l+='<div style="position: relative; margin: auto; height: 160px; width: 100%;"><canvas id="cdr-AudioReceiveBitRate"></canvas></div>',l+='<div style="position: relative; margin: auto; height: 160px; width: 100%;"><canvas id="cdr-AudioReceivePacketRate"></canvas></div>',l+='<div style="position: relative; margin: auto; height: 160px; width: 100%;"><canvas id="cdr-AudioReceivePacketLoss"></canvas></div>',l+='<div style="position: relative; margin: auto; height: 160px; width: 100%;"><canvas id="cdr-AudioReceiveJitter"></canvas></div>',l+='<div style="position: relative; margin: auto; height: 160px; width: 100%;"><canvas id="cdr-AudioReceiveLevels"></canvas></div>',l+="<br><br></div>",$.jeegoopopup.close(),$.jeegoopopup.open({title:"Call Statistics",html:l,width:"640",height:"500",center:!0,scrolling:"no",skinClass:"jg_popup_basic",overlay:!0,opacity:50,draggable:!0,resizable:!1,fadeIn:0}),$("#jg_popup_b").append('<button id="ok_button">'+lang.ok+"</button>"),DisplayQosData(t.SessionId);var v=$(window).width()-12,h=$(window).height()-88;v<656||h<500?($.jeegoopopup.width(v).height(h),$.jeegoopopup.center(),$("#maximizeImg").hide(),$("#minimizeImg").hide()):($.jeegoopopup.width(640).height(500),$.jeegoopopup.center(),$("#minimizeImg").hide(),$("#maximizeImg").show()),$(window).resize((function(){v=$(window).width()-12,h=$(window).height()-88,$.jeegoopopup.center(),v<656||h<500?($.jeegoopopup.width(v).height(h),$.jeegoopopup.center(),$("#maximizeImg").hide(),$("#minimizeImg").hide()):($.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(v).height(h),$.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(e){"Escape"==e.key&&($.jeegoopopup.close(),$("#jg_popup_b").empty())})),$.each(t.Recordings,(function(e,i){var n=null;n=t.WithVideo?$("#callrecording-video-"+i.uID).get(0):$("#callrecording-audio-"+i.uID).get(0);var a=$("#download-"+i.uID),o=getAudioOutputID();void 0!==n.sinkId?n.setSinkId(o).then((function(){console.log("sinkId applied: "+o)})).catch((function(e){console.warn("Error using setSinkId: ",e)})):console.warn("setSinkId() is not possible using this browser.");var l=window.indexedDB.open("CallRecordings");l.onerror=function(e){console.error("IndexDB Request Error:",e)},l.onupgradeneeded=function(e){console.warn("Upgrade Required for IndexDB... probably because of first time use.")},l.onsuccess=function(e){console.log("IndexDB connected to CallRecordings");var o=e.target.result;if(0!=o.objectStoreNames.contains("Recordings")){var l=o.transaction(["Recordings"]).objectStore("Recordings").get(i.uID);l.onerror=function(e){console.error("IndexDB Get Error:",e)},l.onsuccess=function(e){var o=window.URL.createObjectURL(e.target.result.mediaBlob);n.src=o,t.WithVideo?a.prop("download","Video-Call-Recording-"+i.uID+".webm"):a.prop("download","Audio-Call-Recording-"+i.uID+".webm"),a.prop("href",o)}}else console.warn("IndexDB CallRecordings.Recordings does not exists")}}))}})),$("#CMDetails_2").click((function(e){$("#cdr-tags-"+n).show(),$.jeegoopopup.close()})),$("#CMDetails_3").click((function(e){var t;$("#cdr-flagged-"+n).is(":visible")?(console.log("Clearing Flag from: ",n),$("#cdr-flagged-"+n).hide(),null==(t=JSON.parse(localDB.getItem(a+"-stream")))&&null==t.DataCollection||($.each(t.DataCollection,(function(e,t){if("CDR"==t.ItemType&&t.CdrId==n)return t.Flagged=!1,!1})),localDB.setItem(a+"-stream",JSON.stringify(t)))):(console.log("Flag Call: ",n),$("#cdr-flagged-"+n).show(),null==(t=JSON.parse(localDB.getItem(a+"-stream")))&&null==t.DataCollection||($.each(t.DataCollection,(function(e,t){if("CDR"==t.ItemType&&t.CdrId==n)return t.Flagged=!0,!1})),localDB.setItem(a+"-stream",JSON.stringify(t))));$.jeegoopopup.close()})),$("#CMDetails_4").click((function(e){var t=$("#cdr-comment-"+n).text();$("#cdr-comment-"+n).empty();var i=$("<input maxlength=500 type=text>").appendTo("#cdr-comment-"+n);i.on("focus",(function(){$.jeegoopopup.close()})),i.on("blur",(function(){var e=$(this).val();SaveComment(n,a,e)})),i.keypress((function(e){if(window.setTimeout((function(){$.jeegoopopup.close()}),500),"13"==(e.keyCode?e.keyCode:e.which)){e.preventDefault();var t=$(this).val();SaveComment(n,a,t)}})),i.val(t),i.focus(),$.jeegoopopup.close()})),$("#CMDetails_5").click((function(t){var i=$("#msg-text-"+n).text();navigator.clipboard.writeText(i).then((function(){console.log("Text coppied to the clipboard:",i)})).catch((function(){console.error("Error writing to the clipboard:",e)})),$.jeegoopopup.close()})),$("#CMDetails_6").click((function(e){var t=$("#msg-text-"+n).text();t='"'+t+'"';var i=$("#contact-"+a+"-ChatMessage");console.log("Quote Message:",t),i.val(t+"\n"+i.val()),$.jeegoopopup.close()}))}function SaveComment(e,t,i){console.log("Setting Comment:",i),$("#cdr-comment-"+e).empty(),$("#cdr-comment-"+e).append(i);var n=JSON.parse(localDB.getItem(t+"-stream"));null==n&&null==n.DataCollection||($.each(n.DataCollection,(function(t,n){if("CDR"==n.ItemType&&n.CdrId==e)return n.MessageData=i,!1})),localDB.setItem(t+"-stream",JSON.stringify(n)))}function TagKeyPress(e,t,i,n){$.jeegoopopup.close();var a=e.keyCode?e.keyCode:e.which;if("13"==a||"44"==a){if(e.preventDefault(),""==$(t).val())return;console.log("Adding Tag:",$(t).val()),$("#cdr-tags-"+i+" li:last").before("<li onclick=\"TagClick(this, '"+i+"', '"+n+"')\">"+$(t).val()+"</li>"),$(t).val(""),UpdateTags(i,n)}}function TagClick(e,t,i){window.setTimeout((function(){$.jeegoopopup.close()}),500),console.log("Removing Tag:",$(e).text()),$(e).remove(),UpdateTags(t,i)}function UpdateTags(e,t){var i=JSON.parse(localDB.getItem(t+"-stream"));null==i&&null==i.DataCollection||($.each(i.DataCollection,(function(t,i){if("CDR"==i.ItemType&&i.CdrId==e)return i.Tags=[],$("#cdr-tags-"+e).children("li").each((function(){"tagText"!=$(this).prop("class")&&i.Tags.push({value:$(this).text()})})),!1})),localDB.setItem(t+"-stream",JSON.stringify(i)))}function TagFocus(e){$.jeegoopopup.close()}function SendFile(e){$("#selectedFile").val(""),$("#upFile").empty();var t='<form id="sendFileFormChat" enctype="multipart/form-data">';t+='<input type="hidden" name="MAX_FILE_SIZE" value="786432000" />',t+='<input type="hidden" name="sipUser" value="'+FindBuddyByIdentity(e).ExtNo+'" />',t+='<input type="hidden" name="s_ajax_call" value="'+validateSToken+'" />',t+='<label for="selectedFile" class="customBrowseButton">Select File</label>',t+='<span id="upFile"></span>',t+='<input type="file" id="selectedFile" name="uploadedFile" />',t+='<input type="submit" id="submitFileChat" value="Send File" style="visibility:hidden;"/>',t+="</form>",$("#sendFileFormChat").is(":visible")?($("#sendFileFormChat").remove(),sendFileCheck=0):(sendFileCheck=1,$("#contact-"+e+"-ChatMessage").before(t),$("#sendFileFormChat").css("display","block"),$("#selectedFile").bind("change",(function(){upFileName=$(this).val().split("\\").pop(),/^[a-zA-Z0-9\-\_\.]+$/.test(upFileName)?$("#upFile").html(upFileName):($("#sendFileFormChat").remove(),sendFileCheck=0,alert("The name of the uploaded file is not valid!"))})))}function ShowEmojiBar(e){var t=$("#contact-"+e+"-emoji-menu"),i=$("#contact-"+e+"-ChatMessage");t.is(":visible")?t.hide():t.show();var n=$("<div>");n.prop("class","emojiButton");$.each(["😀","😁","😂","😃","😄","😅","😆","😊","😦","😉","😊","😋","😌","😍","😎","😏","😐","😑","😒","😓","😔","😕","😖","😗","😘","😙","😚","😛","😜","😝","😞","😟","😠","😡","😢","😣","😤","😥","😦","😧","😨","😩","😪","😫","😬","😭","😮","😯","😰","😱","😲","😳","😴","😵","😶","😷","🙁","🙂","🙃","🙄","🤐","🤑","🤒","🤓","🤔","🤕","🤠","🤡","🤢","🤣","🤤","🤥","🤧","🤨","🤩","🤪","🤫","🤬","🥺","🤭","🤯","🧐"],(function(a,o){var l=$("<button>");l.html(o),l.on("click",(function(){var n=i.prop("selectionStart"),a=i.val();i.val(a.substring(0,n)+" "+$(this).html()+a.substring(n,a.length)+" "),t.hide(),i.focus(),updateScroll(e)})),n.append(l)})),$(".chatMessage,.chatHistory").on("click",(function(){t.hide()})),t.empty(),t.append(n),updateScroll(e)}function ShowMyProfileMenu(e){e.offsetWidth;var t=e.offsetHeight+56;if("superadmin"==getDbItem("userrole",""))var i="(superadmin)";else i="";var n="<font style='color:#000000;cursor:auto;'>"+userName+" "+i+"</font>",a=AutoAnswerEnabled?"<i class='fa fa-check' style='float:right;'></i>":"",o=DoNotDisturbEnabled?"<i class='fa fa-check' style='float:right;'></i>":"",l=CallWaitingEnabled?"<i class='fa fa-check' style='float:right;'></i>":"",s="<div id=userMenu>";s+='<table id=userMenuTable cellspacing=10 cellpadding=0 style="margin-left:auto; margin-right: auto">',s+='<tr id=userMenu_1><td><i class="fa fa-phone"></i>&nbsp; '+lang.auto_answer+'<span id="autoAnswerTick">'+a+"</span></td></tr>",s+='<tr id=userMenu_2><td><i class="fa fa-ban"></i>&nbsp; '+lang.do_not_disturb+'<span id="doNotDisturbTick">'+o+"</span></td></tr>",s+='<tr id=userMenu_3><td><i class="fa fa-volume-control-phone"></i>&nbsp; '+lang.call_waiting+'<span id="callWaitingTick">'+l+"</span></td></tr>",s+='<tr id=userMenu_4><td><i class="fa fa-refresh"></i>&nbsp; '+lang.refresh_registration+"</td></tr>",s+='<tr id=userMenu_5><td><i class="fa fa-user-plus"></i>&nbsp; '+lang.add_contact+"</td></tr>",s+="<tr id=userMenu_6><td><font style='color:#000000;cursor:auto;'>"+lang.logged_in_as+"</font></td></tr>",s+="<tr id=userMenu_7><td><span style='width:20px;'></span>"+n+"</td></tr>",s+='<tr id=userMenu_8><td><i class="fa fa-power-off"></i>&nbsp; '+lang.log_out+"</td></tr>",s+="</table>",s+="</div>",$.jeegoopopup.open({html:s,width:"auto",height:"auto",left:"56",top:t,scrolling:"no",skinClass:"jg_popup_basic",innerClass:"userMenuInner",contentClass:"userMenuContent",overlay:!0,opacity:0,draggable:!1,resizable:!1,fadeIn:0}),$(window).resize((function(){$.jeegoopopup.width("auto").height("auto").left("56").top(t)})),$("#userMenu_1").click((function(){ToggleAutoAnswer(),AutoAnswerEnabled?$("#autoAnswerTick").append("<i class='fa fa-check' style='float:right;'></i>"):$("#autoAnswerTick").empty()})),$("#userMenu_2").click((function(){ToggleDoNoDisturb(),DoNotDisturbEnabled?$("#doNotDisturbTick").append("<i class='fa fa-check' style='float:right;'></i>"):$("#doNotDisturbTick").empty()})),$("#userMenu_3").click((function(){ToggleCallWaiting(),CallWaitingEnabled?$("#callWaitingTick").append("<i class='fa fa-check' style='float:right;'></i>"):$("#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(e){"Escape"==e.key&&$.jeegoopopup.close()}))}function ShowLaunchVidConfMenu(e){var t=e.offsetWidth+121,i=0,n=e.offsetHeight+117;$(window).width()<=915&&(t=event.pageX+e.offsetWidth-113,i=0,n=event.pageY+e.offsetHeight-11);var a="<div id=videoConfMenu>";a+='<table id=lauchVConfTable cellspacing=0 cellpadding=0 style="margin: 0px">',a+='<tr id=launchVConfMenu_1><td><i class="fa fa-users"></i>&nbsp; '+lang.launch_video_conference+"</td></tr>",a+="</table>",a+="</div>",$.jeegoopopup.open({html:a,width:"228",height:"22",left:t,right:i,top:n,scrolling:"no",skinClass:"jg_popup_basic",overlay:!0,opacity:0,draggable:!1,resizable:!1,fadeIn:0}),$(window).resize((function(){$.jeegoopopup.width("228").height("22").left(t).top(n)})),$(window).width()<=915?$.jeegoopopup.right(6):$.jeegoopopup.width("228").height("22").left(t).top(n),$("#launchVConfMenu_1").click((function(){LaunchVideoConference(),$.jeegoopopup.close()})),$("#jg_popup_overlay").click((function(){$.jeegoopopup.close()})),$(window).on("keydown",(function(e){"Escape"==e.key&&$.jeegoopopup.close()}))}function ShowAccountSettingsMenu(e){$.jeegoopopup.close();var t=e.offsetWidth+212,i=0,n=e.offsetHeight+117;$(window).width()<=915&&(t=event.pageX-32,i=0,n=event.pageY+11);var a="<div id=settingsCMenu>";a+='<table id=lauchSetConfTable cellspacing=0 cellpadding=0 style="margin: 0px">',a+='<tr id=settingsCMenu_1><td><i class="fa fa-wrench"></i>&nbsp; '+lang.account_settings+"</td></tr>",a+="</table>",a+="</div>",$.jeegoopopup.open({html:a,width:"94",height:"22",left:t,right:i,top:n,scrolling:"no",skinClass:"jg_popup_basic",overlay:!0,opacity:0,draggable:!1,resizable:!1,fadeIn:0}),$(window).resize((function(){$.jeegoopopup.width("94").height("22").left(t).top(n)})),$(window).width()<=915?$.jeegoopopup.right(6):$.jeegoopopup.width("94").height("22").left(t).top(n),$("#settingsCMenu_1").click((function(){ConfigureExtensionWindow()})),$("#jg_popup_overlay").click((function(){$.jeegoopopup.close()})),$(window).on("keydown",(function(e){"Escape"==e.key&&$.jeegoopopup.close()}))}function RefreshRegistration(){Unregister(),console.log("Unregister complete..."),window.setTimeout((function(){console.log("Starting registration..."),Register()}),1e3)}function SignOut(){if(1==getDbItem("useRoundcube","")){$("#roundcubeFrame").remove(),$("#rightContent").show(),$(".streamSelected").each((function(){$(this).css("display","none")})),$("#rightContent").append('<iframe id="rcLogoutFrame" name="logoutFrame"></iframe>');var e='<form id="rcloForm" method="POST" action="'+("https://"+getDbItem("rcDomain","")+"/")+'" target="logoutFrame">';e+='<input type="hidden" name="_action" value="logout" />',e+='<input type="hidden" name="_task" value="logout" />',e+='<input type="hidden" name="_autologout" value="1" />',e+='<input id="submitloButton" type="submit" value="Logout" />',e+="</form>",$("#rcLogoutFrame").append(e),$("#submitloButton").click()}removeTextChatUploads(getDbItem("SipUsername","")),setTimeout((function(){var e=getDbItem("externalUserConfElem","");void 0!==e&&null!=e&&0!=e?checkExternalLinks():(Unregister(),console.log("Signing Out ..."),localStorage.clear(),null!=winVideoConf&&winVideoConf.close(),window.open("https://"+window.location.host+"/logout.php","_self"))}),100)}function ToggleAutoAnswer(){if("disabled"==AutoAnswerPolicy)return AutoAnswerEnabled=!1,void console.warn("Policy AutoAnswer: Disabled");AutoAnswerEnabled=1!=AutoAnswerEnabled,"enabled"==AutoAnswerPolicy&&(AutoAnswerEnabled=!0),localDB.setItem("AutoAnswerEnabled",1==AutoAnswerEnabled?"1":"0"),console.log("AutoAnswer:",AutoAnswerEnabled)}function ToggleDoNoDisturb(){if("disabled"==DoNotDisturbPolicy)return DoNotDisturbEnabled=!1,void console.warn("Policy DoNotDisturb: Disabled");DoNotDisturbEnabled=1!=DoNotDisturbEnabled,"enabled"==DoNotDisturbPolicy&&(DoNotDisturbEnabled=!0),localDB.setItem("DoNotDisturbEnabled",1==DoNotDisturbEnabled?"1":"0"),$("#dereglink").attr("class",1==DoNotDisturbEnabled?"dotDoNotDisturb":"dotOnline"),console.log("DoNotDisturb",DoNotDisturbEnabled)}function ToggleCallWaiting(){if("disabled"==CallWaitingPolicy)return CallWaitingEnabled=!1,void console.warn("Policy CallWaiting: Disabled");CallWaitingEnabled=1!=CallWaitingEnabled,"enabled"==CallWaitingPolicy&&(CallWaitingPolicy=!0),localDB.setItem("CallWaitingEnabled",1==CallWaitingEnabled?"1":"0"),console.log("CallWaiting",CallWaitingEnabled)}function ToggleRecordAllCalls(){if("disabled"==CallRecordingPolicy)return RecordAllCalls=!1,void console.warn("Policy CallRecording: Disabled");RecordAllCalls=1!=RecordAllCalls,"enabled"==CallRecordingPolicy&&(RecordAllCalls=!0),localDB.setItem("RecordAllCalls",1==RecordAllCalls?"1":"0"),console.log("RecordAllCalls",RecordAllCalls)}function ShowBuddyProfileMenu(e,t,i){$.jeegoopopup.close(),leftPos=event.pageX-60,topPos=event.pageY+45;var n=FindBuddyByIdentity(e);if("extension"==i){var a='<div style="width:200px; cursor:pointer" onclick="EditBuddyWindow(\''+e+"')\">";a+='<div class="buddyProfilePic" style="background-image:url(\''+getPicture(e,"extension")+"')\"></div>",a+='<div id=ProfileInfo style="text-align:center"><i class="fa fa-spinner fa-spin"></i></div>',a+="</div>",$.jeegoopopup.open({html:a,width:"200",height:"auto",left:leftPos,top:topPos,scrolling:"no",skinClass:"jg_popup_basic",contentClass:"showContactDetails",overlay:!0,opacity:0,draggable:!0,resizable:!1,fadeIn:0}),$("#ProfileInfo").html(""),$("#ProfileInfo").append('<div class=ProfileTextLarge style="margin-top:15px">'+n.CallerIDName+"</div>"),$("#ProfileInfo").append("<div class=ProfileTextMedium>"+n.Desc+"</div>"),$("#ProfileInfo").append('<div class=ProfileTextSmall style="margin-top:15px">'+lang.extension_number+":</div>"),$("#ProfileInfo").append("<div class=ProfileTextMedium>"+n.ExtNo+" </div>"),n.Email&&"null"!=n.Email&&"undefined"!=n.Email&&($("#ProfileInfo").append('<div class=ProfileTextSmall style="margin-top:15px">'+lang.email+":</div>"),$("#ProfileInfo").append("<div class=ProfileTextMedium>"+n.Email+" </div>")),n.MobileNumber&&"null"!=n.MobileNumber&&"undefined"!=n.MobileNumber&&($("#ProfileInfo").append('<div class=ProfileTextSmall style="margin-top:15px">'+lang.mobile+":</div>"),$("#ProfileInfo").append("<div class=ProfileTextMedium>"+n.MobileNumber+" </div>")),n.ContactNumber1&&"null"!=n.ContactNumber1&&"undefined"!=n.ContactNumber1&&($("#ProfileInfo").append('<div class=ProfileTextSmall style="margin-top:15px">'+lang.alternative_contact+":</div>"),$("#ProfileInfo").append("<div class=ProfileTextMedium>"+n.ContactNumber1+" </div>")),n.ContactNumber2&&"null"!=n.ContactNumber2&&"undefined"!=n.ContactNumber2&&($("#ProfileInfo").append('<div class=ProfileTextSmall style="margin-top:15px">'+lang.alternative_contact+":</div>"),$("#ProfileInfo").append("<div class=ProfileTextMedium>"+n.ContactNumber2+" </div>"))}else if("contact"==i){a='<div style="width:200px; cursor:pointer" onclick="EditBuddyWindow(\''+e+"')\">";a+='<div class="buddyProfilePic" style="background-image:url(\''+getPicture(e,"contact")+"')\"></div>",a+='<div id=ProfileInfo style="text-align:center"><i class="fa fa-spinner fa-spin"></i></div>',a+="</div>",$.jeegoopopup.open({html:a,width:"200",height:"auto",left:leftPos,top:topPos,scrolling:"no",skinClass:"jg_popup_basic",contentClass:"showContactDetails",overlay:!0,opacity:0,draggable:!0,resizable:!1,fadeIn:0}),$("#ProfileInfo").html(""),$("#ProfileInfo").append('<div class=ProfileTextLarge style="margin-top:15px">'+n.CallerIDName+"</div>"),$("#ProfileInfo").append("<div class=ProfileTextMedium>"+n.Desc+"</div>"),n.Email&&"null"!=n.Email&&"undefined"!=n.Email&&($("#ProfileInfo").append('<div class=ProfileTextSmall style="margin-top:15px">'+lang.email+":</div>"),$("#ProfileInfo").append("<div class=ProfileTextMedium>"+n.Email+" </div>")),n.MobileNumber&&"null"!=n.MobileNumber&&"undefined"!=n.MobileNumber&&($("#ProfileInfo").append('<div class=ProfileTextSmall style="margin-top:15px">'+lang.mobile+":</div>"),$("#ProfileInfo").append("<div class=ProfileTextMedium>"+n.MobileNumber+" </div>")),n.ContactNumber1&&"null"!=n.ContactNumber1&&"undefined"!=n.ContactNumber1&&($("#ProfileInfo").append('<div class=ProfileTextSmall style="margin-top:15px">'+lang.alternative_contact+":</div>"),$("#ProfileInfo").append("<div class=ProfileTextMedium>"+n.ContactNumber1+" </div>")),n.ContactNumber2&&"null"!=n.ContactNumber2&&"undefined"!=n.ContactNumber2&&($("#ProfileInfo").append('<div class=ProfileTextSmall style="margin-top:15px">'+lang.alternative_contact+":</div>"),$("#ProfileInfo").append("<div class=ProfileTextMedium>"+n.ContactNumber2+" </div>"))}else if("group"==i){a='<div style="width:200px; cursor:pointer" onclick="EditBuddyWindow(\''+e+"')\">";a+='<div class="buddyProfilePic" style="background-image:url(\''+getPicture(e,"group")+"')\"></div>",a+='<div id=ProfileInfo style="text-align:center"><i class="fa fa-spinner fa-spin"></i></div>',a+="</div>",$.jeegoopopup.open({html:a,width:"200",height:"auto",left:leftPos,top:topPos,scrolling:"no",skinClass:"jg_popup_basic",contentClass:"showContactDetails",overlay:!0,opacity:0,draggable:!0,resizable:!1,fadeIn:0}),$("#ProfileInfo").html(""),$("#ProfileInfo").append('<div class=ProfileTextLarge style="margin-top:15px">'+n.CallerIDName+"</div>"),$("#ProfileInfo").append("<div class=ProfileTextMedium>"+n.Desc+"</div>")}$("#jg_popup_overlay").click((function(){$.jeegoopopup.close()})),$(window).on("keydown",(function(e){"Escape"==e.key&&$.jeegoopopup.close()}))}function ChangeSettings(e,t){var i=event.pageX-138,n=event.pageY+28;$(window).height()-event.pageY<300&&(n=event.pageY-170);var a=FindLineByNumber(e);if(null!=a&&null!=a.SipSession){var o=a.SipSession;$.jeegoopopup.open({html:'<div id=DeviceSelector style="width:250px"></div>',width:"auto",height:"auto",left:i,top:n,scrolling:"no",skinClass:"jg_popup_basic",contentClass:"callSettingsContent",overlay:!0,opacity:0,draggable:!0,resizable:!1,fadeIn:0});var l=$("<select/>");l.prop("id","audioSrcSelect"),l.css("width","100%");var s=$("<select/>");s.prop("id","videoSrcSelect"),s.css("width","100%");var r=$("<select/>");r.prop("id","audioOutputSelect"),r.css("width","100%");var d=$("<select/>");if(d.prop("id","ringerSelect"),d.css("width","100%"),l.change((function(){console.log("Call to change Microphone: ",this.value);var t=!1;o.data.mediaRecorder&&"recording"==o.data.mediaRecorder.state&&(StopRecording(e,!0),t=!0),a.LocalSoundMeter&&a.LocalSoundMeter.stop(),o.data.AudioSourceDevice=this.value;var i={audio:{deviceId:"default"!=this.value?{exact:this.value}:"default"},video:!1};navigator.mediaDevices.getUserMedia(i).then((function(i){var n=i.getAudioTracks()[0];o.sessionDescriptionHandler.peerConnection.getSenders().forEach((function(i){i.track&&"audio"==i.track.kind&&(console.log("Switching Audio Track : "+i.track.label+" to "+n.label),i.track.stop(),i.replaceTrack(n).then((function(){t&&StartRecording(e),a.LocalSoundMeter=StartLocalAudioMediaMonitoring(e,o)})).catch((function(e){console.error("Error replacing track: ",e)})))}))})).catch((function(e){console.error("Error on getUserMedia")}))})),r.change((function(){console.log("Call to change Speaker: ",this.value),o.data.AudioOutputDevice=this.value;var t=this.value;console.log("Attempting to set Audio Output SinkID for line "+e+" ["+t+"]");var i=$("#line-"+e+"-remoteAudio").get(0);i&&(void 0!==i.sinkId?i.setSinkId(t).then((function(){console.log("sinkId applied: "+t)})).catch((function(e){console.warn("Error using setSinkId: ",e)})):console.warn("setSinkId() is not possible using this browser."))})),s.change((function(){console.log("Call to change WebCam"),switchVideoSource(e,this.value)})),navigator.mediaDevices){for(var c=0;c<AudioinputDevices.length;++c){var u=(p=AudioinputDevices[c]).deviceId;(g=p.label?p.label:"").indexOf("(")>0&&(g=g.substring(0,g.indexOf("("))),(m=$("<option/>")).prop("value",u),m.text(""!=g?g:"Microphone"),o.data.AudioSourceDevice==u&&m.prop("selected",!0),l.append(m)}for(c=0;c<VideoinputDevices.length;++c){u=(p=VideoinputDevices[c]).deviceId;(g=p.label?p.label:"").indexOf("(")>0&&(g=g.substring(0,g.indexOf("("))),(m=$("<option/>")).prop("value",u),m.text(""!=g?g:"Webcam"),o.data.VideoSourceDevice==u&&m.prop("selected",!0),s.append(m)}if(HasSpeakerDevice)for(c=0;c<SpeakerDevices.length;++c){var p,g,m;u=(p=SpeakerDevices[c]).deviceId;(g=p.label?p.label:"").indexOf("(")>0&&(g=g.substring(0,g.indexOf("("))),(m=$("<option/>")).prop("value",u),m.text(""!=g?g:"Speaker"),o.data.AudioOutputDevice==u&&m.prop("selected",!0),r.append(m)}$("#DeviceSelector").append("<div class=callSettingsDvs>"+lang.microphone+": </div>"),$("#DeviceSelector").append(l),HasSpeakerDevice&&($("#DeviceSelector").append("<div class=callSettingsDvs>"+lang.speaker+": </div>"),$("#DeviceSelector").append(r)),1==o.data.withvideo&&($("#DeviceSelector").append("<div class=callSettingsDvs>"+lang.camera+": </div>"),$("#DeviceSelector").append(s)),$("#jg_popup_overlay").click((function(){$.jeegoopopup.close()})),$(window).on("keydown",(function(e){"Escape"==e.key&&$.jeegoopopup.close()}))}else console.warn("navigator.mediaDevices not possible.")}}function PresentCamera(e){var t=FindLineByNumber(e);if(null!=t&&null!=t.SipSession){var i=t.SipSession;$("#line-"+e+"-src-camera").prop("disabled",!0),$("#line-"+e+"-src-canvas").prop("disabled",!1),$("#line-"+e+"-src-desktop").prop("disabled",!1),$("#line-"+e+"-src-video").prop("disabled",!1),$("#line-"+e+"-src-blank").prop("disabled",!1),$("#line-"+e+"-scratchpad-container").hide(),RemoveScratchpad(e),$("#line-"+e+"-sharevideo").hide(),$("#line-"+e+"-sharevideo").get(0).pause(),$("#line-"+e+"-sharevideo").get(0).removeAttribute("src"),$("#line-"+e+"-sharevideo").get(0).load(),window.clearInterval(i.data.videoResampleInterval),$("#line-"+e+"-localVideo").show(),$("#line-"+e+"-remoteVideo").appendTo("#line-"+e+"-stage-container"),switchVideoSource(e,i.data.VideoSourceDevice)}else console.warn("Line or Session is Null.")}function PresentScreen(e){var t=FindLineByNumber(e);if(null!=t&&null!=t.SipSession){var i=t.SipSession;$("#line-"+e+"-src-camera").prop("disabled",!1),$("#line-"+e+"-src-canvas").prop("disabled",!1),$("#line-"+e+"-src-desktop").prop("disabled",!0),$("#line-"+e+"-src-video").prop("disabled",!1),$("#line-"+e+"-src-blank").prop("disabled",!1),$("#line-"+e+"-scratchpad-container").hide(),RemoveScratchpad(e),$("#line-"+e+"-sharevideo").hide(),$("#line-"+e+"-sharevideo").get(0).pause(),$("#line-"+e+"-sharevideo").get(0).removeAttribute("src"),$("#line-"+e+"-sharevideo").get(0).load(),window.clearInterval(i.data.videoResampleInterval),$("#line-"+e+"-localVideo").hide(),$("#line-"+e+"-remoteVideo").appendTo("#line-"+e+"-stage-container"),ShareScreen(e)}else console.warn("Line or Session is Null.")}function PresentScratchpad(e){var t=FindLineByNumber(e);if(null!=t&&null!=t.SipSession){var i=t.SipSession;$("#line-"+e+"-src-camera").prop("disabled",!1),$("#line-"+e+"-src-canvas").prop("disabled",!0),$("#line-"+e+"-src-desktop").prop("disabled",!1),$("#line-"+e+"-src-video").prop("disabled",!1),$("#line-"+e+"-src-blank").prop("disabled",!1),$("#line-"+e+"-scratchpad-container").hide(),RemoveScratchpad(e),$("#line-"+e+"-sharevideo").hide(),$("#line-"+e+"-sharevideo").get(0).pause(),$("#line-"+e+"-sharevideo").get(0).removeAttribute("src"),$("#line-"+e+"-sharevideo").get(0).load(),window.clearInterval(i.data.videoResampleInterval),$("#line-"+e+"-localVideo").hide(),$("#line-"+e+"-remoteVideo").appendTo("#line-"+e+"-preview-container"),SendCanvas(e)}else console.warn("Line or Session is Null.")}function PresentVideo(e){var t=FindLineByNumber(e);if(null!=t&&null!=t.SipSession){t.SipSession;$.jeegoopopup.close();'<div id="windowCtrls"><img id="closeImg" src="images/3_close.svg" title="Close" /></div>','<label for=SelectVideoToSend class=customBrowseButton style="display: block; margin: 26px auto;">Select File</label>','<div class="UiWindowField"><input type=file  accept="video/*" id=SelectVideoToSend></div>',"</div>",$.jeegoopopup.open({html:'<div><div id="windowCtrls"><img id="closeImg" src="images/3_close.svg" title="Close" /></div><label for=SelectVideoToSend class=customBrowseButton style="display: block; margin: 26px auto;">Select File</label><div class="UiWindowField"><input type=file  accept="video/*" id=SelectVideoToSend></div></div>',width:"180",height:"80",center:!0,scrolling:"no",skinClass:"jg_popup_basic",overlay:!0,opacity:0,draggable:!0,resizable:!1,fadeIn:0}),$("#SelectVideoToSend").on("change",(function(t){var i=t.target;i.files.length>=1?($.jeegoopopup.close(),SendVideo(e,URL.createObjectURL(i.files[0]))):console.warn("Please Select a file to present.")})),$("#closeImg").click((function(){$.jeegoopopup.close()})),$("#jg_popup_overlay").click((function(){$.jeegoopopup.close()})),$(window).on("keydown",(function(e){"Escape"==e.key&&$.jeegoopopup.close()}))}else console.warn("Line or Session is Null.")}function PresentBlank(e){var t=FindLineByNumber(e);if(null!=t&&null!=t.SipSession){var i=t.SipSession;$("#line-"+e+"-src-camera").prop("disabled",!1),$("#line-"+e+"-src-canvas").prop("disabled",!1),$("#line-"+e+"-src-desktop").prop("disabled",!1),$("#line-"+e+"-src-video").prop("disabled",!1),$("#line-"+e+"-src-blank").prop("disabled",!0),$("#line-"+e+"-scratchpad-container").hide(),RemoveScratchpad(e),$("#line-"+e+"-sharevideo").hide(),$("#line-"+e+"-sharevideo").get(0).pause(),$("#line-"+e+"-sharevideo").get(0).removeAttribute("src"),$("#line-"+e+"-sharevideo").get(0).load(),window.clearInterval(i.data.videoResampleInterval),$("#line-"+e+"-localVideo").hide(),$("#line-"+e+"-remoteVideo").appendTo("#line-"+e+"-stage-container"),DisableVideoStream(e)}else console.warn("Line or Session is Null.")}function RemoveScratchpad(e){var t=GetCanvas("line-"+e+"-scratchpad");null!=t&&(window.clearInterval(t.redrawIntrtval),RemoveCanvas("line-"+e+"-scratchpad"),$("#line-"+e+"-scratchpad-container").empty(),t=null)}function ShowCallStats(e,t){console.log("Show Call Stats"),$("#line-"+e+"-AudioStats").show(300)}function HideCallStats(e,t){console.log("Hide Call Stats"),$("#line-"+e+"-AudioStats").hide(300)}function chatOnbeforepaste(e,t,i){console.log("Handle paste, checking for Images...");for(var n=(e.clipboardData||e.originalEvent.clipboardData).items,a=!1,o=0;o<n.length;o++)if(0!==n[o].type.indexOf("image"));else{console.log("Image found! Opening image editor...");var l=n[o].getAsFile(),s=new FileReader;s.onload=function(e){console.log("Image loaded... setting placeholder...");var t=new Image;t.onload=function(){console.log("Placeholder loaded... CreateImageEditor..."),CreateImageEditor(i,t)},t.src=e.target.result},s.readAsDataURL(l),a=!0}a&&e.preventDefault()}function chatOnkeydown(e,t,i){if("13"==(e.keyCode?e.keyCode:e.which)&&e.ctrlKey)return SendChatMessage(i),!1}function ReformatMessage(e){var t=e;return t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=t.replace(/</gi,"&lt;")).replace(/>/gi,"&gt;")).replace(/\n/gi,"<br>")).replace(/(:\)|:\-\)|:o\))/g,String.fromCodePoint(128578))).replace(/(:\(|:\-\(|:o\()/g,String.fromCodePoint(128577))).replace(/(;\)|;\-\)|;o\))/g,String.fromCodePoint(128521))).replace(/(:'\(|:'\-\()/g,String.fromCodePoint(128554))).replace(/(:'\(|:'\-\()/g,String.fromCodePoint(128514))).replace(/(:\$)/g,String.fromCodePoint(128563))).replace(/(>:\()/g,String.fromCodePoint(128547))).replace(/(:\×)/g,String.fromCodePoint(128536))).replace(/(:\O|:\‑O)/g,String.fromCodePoint(128562))).replace(/(:P|:\-P|:p|:\-p)/g,String.fromCodePoint(128539))).replace(/(;P|;\-P|;p|;\-p)/g,String.fromCodePoint(128540))).replace(/(:D|:\-D)/g,String.fromCodePoint(128525))).replace(/(\(like\))/g,String.fromCodePoint(128077))).replace(/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/gi,(function(e){var t=e.length>50?e.substring(0,47)+"...":e;return'<A target=_blank class=previewHyperlink href="'+e+'">'+t+"</A>"}))}function getPicture(e,t){if("profilePicture"==e)return null==(i=localDB.getItem("profilePicture"))?hostingPrefex+"images/default.png":i;t=t||"extension";var i,n=FindBuddyByIdentity(e);return""!=n.imageObjectURL?n.imageObjectURL:null==(i=localDB.getItem("img-"+e+"-"+t))?hostingPrefex+"images/default.png":(n.imageObjectURL=URL.createObjectURL(base64toBlob(i,"image/png")),n.imageObjectURL)}function CreateImageEditor(e,t){console.log("Setting Up ImageEditor..."),$("#contact-"+e+"-imagePastePreview").is(":visible")?(console.log("Resetting ImageEditor..."),$("#contact-"+e+"-imagePastePreview").empty(),RemoveCanvas("contact-"+e+"-imageCanvas")):$("#contact-"+e+"-imagePastePreview").show();var i=$("<div/>");i.css("margin-bottom","5px"),i.append('<button class="toolBarButtons" title="Select" onclick="ImageEditor_Select(\''+e+'\')"><i class="fa fa-mouse-pointer"></i></button>'),i.append("&nbsp;|&nbsp;"),i.append('<button class="toolBarButtons" title="Draw" onclick="ImageEditor_FreedrawPen(\''+e+'\')"><i class="fa fa-pencil"></i></button>'),i.append('<button class="toolBarButtons" title="Paint" onclick="ImageEditor_FreedrawPaint(\''+e+'\')"><i class="fa fa-paint-brush"></i></button>'),i.append("&nbsp;|&nbsp;"),i.append('<button class="toolBarButtons" title="Select Line Color" onclick="ImageEditor_SetectLineColor(\''+e+'\')"><i class="fa fa-pencil-square-o" style="color:rgb(255, 0, 0)"></i></button>'),i.append('<button class="toolBarButtons" title="Select Fill Color" onclick="ImageEditor_SetectFillColor(\''+e+'\')"><i class="fa fa-pencil-square" style="color:rgb(255, 0, 0)"></i></button>'),i.append("&nbsp;|&nbsp;"),i.append('<button class="toolBarButtons" title="Add Circle" onclick="ImageEditor_AddCircle(\''+e+'\')"><i class="fa fa-circle"></i></button>'),i.append('<button class="toolBarButtons" title="Add Rectangle" onclick="ImageEditor_AddRectangle(\''+e+'\')"><i class="fa fa-stop"></i></button>'),i.append('<button class="toolBarButtons" title="Add Triangle" onclick="ImageEditor_AddTriangle(\''+e+'\')"><i class="fa fa-play"></i></button>'),i.append('<button class="toolBarButtons" title="Add Emoji" onclick="ImageEditor_SetectEmoji(\''+e+'\')"><i class="fa fa-smile-o"></i></button>'),i.append('<button class="toolBarButtons" title="Add Text" onclick="ImageEditor_AddText(\''+e+'\')"><i class="fa fa-font"></i></button>'),i.append('<button class="toolBarButtons" title="Delete Selected Items" onclick="ImageEditor_Clear(\''+e+'\')"><i class="fa fa-times"></i></button>'),i.append('<button class="toolBarButtons" title="Clear All" onclick="ImageEditor_ClearAll(\''+e+'\')"><i class="fa fa-trash"></i></button>'),i.append("&nbsp;|&nbsp;"),i.append('<button class="toolBarButtons" title="Pan" onclick="ImageEditor_Pan(\''+e+'\')"><i class="fa fa-hand-paper-o"></i></button>'),i.append('<button class="toolBarButtons" title="Zoom In" onclick="ImageEditor_ZoomIn(\''+e+'\')"><i class="fa fa-search-plus"></i></button>'),i.append('<button class="toolBarButtons" title="Zoom Out" onclick="ImageEditor_ZoomOut(\''+e+'\')"><i class="fa fa-search-minus"></i></button>'),i.append('<button class="toolBarButtons" title="Reset Pan & Zoom" onclick="ImageEditor_ResetZoom(\''+e+'\')"><i class="fa fa-search" aria-hidden="true"></i></button>'),i.append("&nbsp;|&nbsp;"),i.append('<button class="toolBarButtons" title="Cancel" onclick="ImageEditor_Cancel(\''+e+'\')"><i class="fa fa-times-circle"></i></button>'),i.append('<button class="toolBarButtons" title="Send" onclick="ImageEditor_Send(\''+e+'\')"><i class="fa fa-paper-plane"></i></button>'),$("#contact-"+e+"-imagePastePreview").append(i);var n=$("<canvas/>");n.prop("id","contact-"+e+"-imageCanvas"),n.css("border","1px solid #CCCCCC"),$("#contact-"+e+"-imagePastePreview").append(n),console.log("Canvas for ImageEditor created...");var a=t.width,o=t.height,l=$("#contact-"+e+"-imagePastePreview").width()-2;$("#contact-"+e+"-imageCanvas").prop("width",l),$("#contact-"+e+"-imageCanvas").prop("height",480);var s=1,r=1,d=1;a>l||o>480?(a>l&&(r=l/a),o>480&&(d=480/o,console.log("Scale to fit height: "+d)),s=Math.min(r,d),console.log("Scale down to fit: "+s),a*=s,o*=s,console.log("resizing canvas to fit new image size..."),$("#contact-"+e+"-imageCanvas").prop("width",a),$("#contact-"+e+"-imageCanvas").prop("height",o)):(console.log("Image is able to fit, resizing canvas..."),$("#contact-"+e+"-imageCanvas").prop("width",a),$("#contact-"+e+"-imageCanvas").prop("height",o)),console.log("Creating fabric API...");var c=new fabric.Canvas("contact-"+e+"-imageCanvas");c.id="contact-"+e+"-imageCanvas",c.ToolSelected="None",c.PenColour="rgb(255, 0, 0)",c.PenWidth=2,c.PaintColour="rgba(227, 230, 3, 0.6)",c.PaintWidth=10,c.FillColour="rgb(255, 0, 0)",c.isDrawingMode=!1,c.selectionColor="rgba(112,179,233,0.25)",c.selectionBorderColor="rgba(112,179,233, 0.8)",c.selectionLineWidth=1,c.setZoom(s),c.on("mouse:down",(function(e){var t=e.e;"Pan"==this.ToolSelected&&(this.isDragging=!0,this.selection=!1,this.lastPosX=t.clientX,this.lastPosY=t.clientY),null!=e.target&&(!0===t.altKey&&(e.target.lockMovementX=!0),!0===t.shiftKey&&(e.target.lockMovementY=!0),e.target.set({transparentCorners:!1,borderColor:"rgba(112,179,233, 0.4)",cornerColor:"rgba(112,179,233, 0.8)",cornerSize:6}))})),c.on("mouse:move",(function(e){if(this.isDragging){var t=e.e;this.viewportTransform[4]+=t.clientX-this.lastPosX,this.viewportTransform[5]+=t.clientY-this.lastPosY,this.requestRenderAll(),this.lastPosX=t.clientX,this.lastPosY=t.clientY}})),c.on("mouse:up",(function(e){this.isDragging=!1,this.selection=!0,null!=e.target&&(e.target.lockMovementX=!1,e.target.lockMovementY=!1)})),c.on("mouse:wheel",(function(e){var t=e.e.deltaY,i=(c.getPointer(e.e),c.getZoom());(i+=t/200)>10&&(i=10),i<.1&&(i=.1),c.zoomToPoint({x:e.e.offsetX,y:e.e.offsetY},i),e.e.preventDefault(),e.e.stopPropagation()})),c.backgroundImage=new fabric.Image(t),CanvasCollection.push(c),$("#contact-"+e+"-imagePastePreview").keydown((function(t){var i=(t=t||window.event).keyCode;console.log("Key press on Image Editor ("+e+"): "+i),46==i&&ImageEditor_Clear(e)})),console.log("ImageEditor: "+c.id+" created"),ImageEditor_FreedrawPen(e)}function GetCanvas(e){for(var t=0;t<CanvasCollection.length;t++)try{if(CanvasCollection[t].id==e)return CanvasCollection[t]}catch(e){console.warn("CanvasCollection.id not available")}return null}function RemoveCanvas(e){for(var t=0;t<CanvasCollection.length;t++)try{if(CanvasCollection[t].id==e){console.log("Found Old Canvas, Disposing..."),CanvasCollection[t].clear(),CanvasCollection[t].dispose(),CanvasCollection[t].id="--deleted--",console.log("CanvasCollection.splice("+t+", 1)"),CanvasCollection.splice(t,1);break}}catch(e){}console.log("There are "+CanvasCollection.length+" canvas now.")}var ImageEditor_Select=function(e){var t=GetCanvas("contact-"+e+"-imageCanvas");return null!=t&&(t.ToolSelected="none",t.isDrawingMode=!1,!0)},ImageEditor_FreedrawPen=function(e){var t=GetCanvas("contact-"+e+"-imageCanvas");return null!=t&&(t.freeDrawingBrush.color=t.PenColour,t.freeDrawingBrush.width=t.PenWidth,t.ToolSelected="Draw",t.isDrawingMode=!0,console.log(t),!0)},ImageEditor_FreedrawPaint=function(e){var t=GetCanvas("contact-"+e+"-imageCanvas");return null!=t&&(t.freeDrawingBrush.color=t.PaintColour,t.freeDrawingBrush.width=t.PaintWidth,t.ToolSelected="Paint",t.isDrawingMode=!0,!0)},ImageEditor_Pan=function(e){var t=GetCanvas("contact-"+e+"-imageCanvas");return null!=t&&(t.ToolSelected="Pan",t.isDrawingMode=!1,!0)},ImageEditor_ResetZoom=function(e){var t=GetCanvas("contact-"+e+"-imageCanvas");return null!=t&&(t.setZoom(1),t.setViewportTransform([1,0,0,1,0,0]),!0)},ImageEditor_ZoomIn=function(e){var t=GetCanvas("contact-"+e+"-imageCanvas");if(null!=t){var i=t.getZoom();(i+=.5)>10&&(i=10),i<.1&&(i=.1);var n=new fabric.Point(t.getWidth()/2,t.getHeight()/2);fabric.util.transformPoint(n,t.viewportTransform);return t.zoomToPoint(n,i),!0}return!1},ImageEditor_ZoomOut=function(e){var t=GetCanvas("contact-"+e+"-imageCanvas");if(null!=t){var i=t.getZoom();(i-=.5)>10&&(i=10),i<.1&&(i=.1);var n=new fabric.Point(t.getWidth()/2,t.getHeight()/2);fabric.util.transformPoint(n,t.viewportTransform);return t.zoomToPoint(n,i),!0}return!1},ImageEditor_AddCircle=function(e){var t=GetCanvas("contact-"+e+"-imageCanvas");if(null!=t){t.ToolSelected="none",t.isDrawingMode=!1;var i=new fabric.Circle({radius:20,fill:t.FillColour});return t.add(i),t.centerObject(i),t.setActiveObject(i),!0}return!1},ImageEditor_AddRectangle=function(e){var t=GetCanvas("contact-"+e+"-imageCanvas");if(null!=t){t.ToolSelected="none",t.isDrawingMode=!1;var i=new fabric.Rect({width:40,height:40,fill:t.FillColour});return t.add(i),t.centerObject(i),t.setActiveObject(i),!0}return!1},ImageEditor_AddTriangle=function(e){var t=GetCanvas("contact-"+e+"-imageCanvas");if(null!=t){t.ToolSelected="none",t.isDrawingMode=!1;var i=new fabric.Triangle({width:40,height:40,fill:t.FillColour});return t.add(i),t.centerObject(i),t.setActiveObject(i),!0}return!1},ImageEditor_AddEmoji=function(e){var t=GetCanvas("contact-"+e+"-imageCanvas");if(null!=t){t.ToolSelected="none",t.isDrawingMode=!1;var i=new fabric.Text(String.fromCodePoint(128578),{fontSize:24});return t.add(i),t.centerObject(i),t.setActiveObject(i),!0}return!1},ImageEditor_AddText=function(e,t){var i=GetCanvas("contact-"+e+"-imageCanvas");if(null!=i){i.ToolSelected="none",i.isDrawingMode=!1;var n=new fabric.IText(t,{fill:i.FillColour,fontFamily:"arial",fontSize:18});return i.add(n),i.centerObject(n),i.setActiveObject(n),!0}return!1},ImageEditor_Clear=function(e){var t=GetCanvas("contact-"+e+"-imageCanvas");if(null!=t){t.ToolSelected="none",t.isDrawingMode=!1;for(var i=t.getActiveObjects(),n=0;n<i.length;n++)t.remove(i[n]);return t.discardActiveObject(),!0}return!1},ImageEditor_ClearAll=function(e){var t=GetCanvas("contact-"+e+"-imageCanvas");if(null!=t){var i=t.backgroundImage;return t.ToolSelected="none",t.isDrawingMode=!1,t.clear(),t.backgroundImage=i,!0}return!1},ImageEditor_Cancel=function(e){console.log("Removing ImageEditor..."),$("#contact-"+e+"-imagePastePreview").empty(),RemoveCanvas("contact-"+e+"-imageCanvas"),$("#contact-"+e+"-imagePastePreview").hide()},ImageEditor_Send=function(e){var t=GetCanvas("contact-"+e+"-imageCanvas");return null!=t&&(SendImageDataMessage(e,t.toDataURL({format:"png"})),!0)};function FindSomething(e){$("#contact-"+e+"-search").toggle(),0==$("#contact-"+e+"-search").is(":visible")&&RefreshStream(FindBuddyByIdentity(e)),updateScroll(e)}var allowDradAndDrop=function(){var e=document.createElement("div");return("draggable"in e||"ondragstart"in e&&"ondrop"in e)&&"FormData"in window&&"FileReader"in window};function onFileDragDrop(e,t){var i=e.dataTransfer.files;console.log("You are about to upload "+i.length+" file."),$("#contact-"+t+"-ChatHistory").css("outline","none");for(var n=0;n<i.length;n++){var a=i[n],o=new FileReader;o.onload=function(e){a.size<=52428800?SendFileDataMessage(t,e.target.result,a.name,a.size):alert("The file '"+a.name+"' is bigger than 50MB, you cannot upload this file")},console.log("Adding: "+a.name+" of size: "+a.size+"bytes"),o.readAsDataURL(a)}preventDefault(e)}function cancelDragDrop(e,t){$("#contact-"+t+"-ChatHistory").css("outline","none"),preventDefault(e)}function setupDragDrop(e,t){$("#contact-"+t+"-ChatHistory").css("outline","2px dashed #184369"),preventDefault(e)}function preventDefault(e){e.preventDefault(),e.stopPropagation()}function Alert(e,t,i){$("#jg_popup_l").empty(),$("#jg_popup_b").empty(),$("#windowCtrls").empty(),$.jeegoopopup.close();var n="<div class=NoSelect>";n+='<div id="windowCtrls"><img id="closeImg" src="images/3_close.svg" title="Close" /></div>',n+='<div class=UiText style="padding: 0px 10px 8px 10px;" id=AllertMessageText>'+e+"</div>",n+="</div>",$.jeegoopopup.open({title:t,html:n,width:"260",height:"auto",center:!0,scrolling:"no",skinClass:"jg_popup_basic",contentClass:"confirmDelContact",overlay:!0,opacity:50,draggable:!0,resizable:!1,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"),i&&i()})),$(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(e){"Escape"==e.key&&($.jeegoopopup.close(),$("#jg_popup_b").empty())}))}function AlertConfigExtWindow(e,t){$("#jg_popup_l").empty(),$("#jg_popup_b").empty(),$("#windowCtrls").empty(),$.jeegoopopup.close(),videoAudioCheck=1;var i="<div class=NoSelect>";i+='<div id="windowCtrls"><img id="closeImg" src="images/3_close.svg" title="Close" /></div>',i+='<div class=UiText style="padding: 10px" id=AllertMessageText>'+e+"</div>",i+="</div>",$.jeegoopopup.open({title:t,html:i,width:"260",height:"auto",center:!0,scrolling:"no",skinClass:"jg_popup_basic",contentClass:"confirmDelContact",overlay:!0,opacity:50,draggable:!0,resizable:!1,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(e){"Escape"==e.key&&($("#windowCtrls").empty(),$("#jg_popup_b").empty(),$.jeegoopopup.close(),ConfigureExtensionWindow())}))}function Confirm(e,t,i,n){$("#jg_popup_l").empty(),$("#jg_popup_b").empty(),$("#windowCtrls").empty(),$.jeegoopopup.close();var a="<div class=NoSelect>";a+='<div id="windowCtrls"><img id="closeImg" src="images/3_close.svg" title="Close" /></div>',a+='<div class=UiText style="padding: 10px" id=ConfirmMessageText>'+e+"</div>",a+="</div>",$.jeegoopopup.open({html:a,width:"260",height:"auto",center:!0,scrolling:"no",skinClass:"jg_popup_basic",contentClass:"confirmDelContact",overlay:!0,opacity:50,draggable:!0,resizable:!1,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"),i&&i()})),$("#ConfirmCancelButton").click((function(){console.log("Confirm Cancel clicked"),n&&n()})),$(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(e){"Escape"==e.key&&($.jeegoopopup.close(),$("#jg_popup_b").empty())}))}function ConfirmConfigExtWindow(e,t,i,n){$("#jg_popup_l").empty(),$("#jg_popup_b").empty(),$("#windowCtrls").empty(),$.jeegoopopup.close();var a="<div class=NoSelect>";a+="<div id=windowCtrls><img id=closeImg src=images/3_close.svg title=Close /></div>",a+='<div class=UiText style="padding: 10px" id=ConfirmMessageText>'+e+"</div>",a+="</div>",$.jeegoopopup.open({html:a,width:"260",height:"auto",center:!0,scrolling:"no",skinClass:"jg_popup_basic",contentClass:"ConfCloseAccount",overlay:!0,opacity:50,draggable:!0,resizable:!1,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"),i&&i()})),$("#ConfirmCancelButton").click((function(){console.log("Confirm Cancel clicked"),n&&n(),$("#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(e,t,i,n,a,o,l,s){$("#jg_popup_l").empty(),$("#jg_popup_b").empty(),$("#windowCtrls").empty(),$.jeegoopopup.close();var r="<div class=NoSelect>";r+='<div id="windowCtrls"><img id="closeImg" src="images/3_close.svg" title="Close" /></div>',r+='<div class=UiText style="padding: 10px" id=PromptMessageText>',r+=e,r+='<div style="margin-top:10px">'+i+" : </div>",r+='<div style="margin-top:5px"><INPUT id=PromptValueField type='+a+' value="'+n+'" placeholder="'+o+'" style="width:98%"></div>',r+="</div>",r+="</div>",$.jeegoopopup.open({html:r,width:"260",height:"auto",center:!0,scrolling:"no",skinClass:"jg_popup_basic",contentClass:"confirmDelContact",overlay:!0,opacity:50,draggable:!0,resizable:!1,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()),l&&l($("#PromptValueField").val())})),$("#PromptCancelButton").click((function(){console.log("Prompt Cancel clicked"),s&&s()})),$(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(e){"Escape"==e.key&&($.jeegoopopup.close(),$("#jg_popup_b").empty())}))}function DetectDevices(){navigator.mediaDevices.enumerateDevices().then((function(e){HasVideoDevice=!1,HasAudioDevice=!1,HasSpeakerDevice=!1,AudioinputDevices=[],VideoinputDevices=[],SpeakerDevices=[];for(var t=0;t<e.length;++t)"audioinput"===e[t].kind?(HasAudioDevice=!0,AudioinputDevices.push(e[t])):"audiooutput"===e[t].kind?(HasSpeakerDevice=!0,SpeakerDevices.push(e[t])):"videoinput"===e[t].kind&&(HasVideoDevice=!0,VideoinputDevices.push(e[t]))})).catch((function(e){console.error("Error enumerating devices",e)}))}DetectDevices(),window.setInterval((function(){DetectDevices()}),1e4);
2 0
\ No newline at end of file
3 1
deleted file mode 100644
... ...
@@ -1,314 +0,0 @@
1
-{
2
-    "account_settings" : "Settings",
3
-    "create_group" : "Create Group",
4
-    "add_someone" : "Add Someone",
5
-    "add_contact" : "Add Contact",
6
-    "find_someone" : "Find contact ...",
7
-    "refresh_registration" : "Refresh Registration",
8
-    "configure_extension" : "Configure Extension",
9
-    "configure_account" : "Configure Account",
10
-    "auto_answer" : "Auto Answer",
11
-    "do_not_disturb" : "Do Not Disturb",
12
-    "call_waiting" : "Call Waiting",
13
-    "record_all_calls" : "Record All Calls",
14
-    "log_out" : "Log Out",
15
-    "logged_in_as" : "You are logged in as",
16
-    "extension_number" : "Extension Number",
17
-    "email" : "Email",
18
-    "mobile" : "Mobile",
19
-    "alternative_contact" : "Alternate Contact",
20
-    "full_name" : "Full Name",
21
-    "display_name": "Display Name",
22
-    "eg_full_name" : "Eg: John Doe",
23
-    "eg_display_name" : "Eg: John Doe",
24
-    "title_description" : "Title / Description",
25
-    "eg_general_manager" : "Eg: General Manager",
26
-    "internal_subscribe_extension" : "Extension (Internal)",
27
-    "eg_internal_subscribe_extension" : "eg: 100 or john",
28
-    "mobile_number" : "Mobile Number",
29
-    "eg_mobile_number" : "Eg: +497201234567",
30
-    "eg_email" : "Eg: john.doe@domain.com",
31
-    "contact_number_1" : "Contact Number 1",
32
-    "eg_contact_number_1" : "Eg: +499876543210",
33
-    "contact_number_2" : "Contact Number 2",
34
-    "eg_contact_number_2" : "Eg: +491234567890",
35
-    "add" : "Add",
36
-    "cancel" : "Cancel",
37
-    "save" : "Save",
38
-    "remove": "Remove",
39
-    "reload_required" : "Reload Required",
40
-    "alert_settings" : "In order to apply these settings, the page must reload, OK?",
41
-    "account" : "Account",
42
-    "audio_video" : "Audio & Video",
43
-    "appearance" : "Appearance",
44
-    "notifications" : "Notifications",
45
-    "email_integration": "Email integration",
46
-    "enable_roundcube_integration": "Enable Roundcube email integration (To enable this you need to also enable the plugins 'autologon' and 'autologout' in Roundcube).",
47
-    "roundcube_domain": "Roundcube domain",
48
-    "rc_basic_auth_user": "Roundcube basic authentication username (if basic auth is configured)(basic auth will work in Firefox but not in Chrome)",
49
-    "rc_basic_auth_password": "Roundcube basic authentication password (if basic auth is configured)(basic auth will work in Firefox but not in Chrome)",
50
-    "roundcube_user": "Roundcube user",
51
-    "roundcube_password": "Roundcube password",
52
-    "change_user_password" : "Change Password",
53
-    "current_user_password" : "Current Password",
54
-    "new_user_password" : "New Password",
55
-    "repeat_new_user_password": "Repeat New Password",
56
-    "change_user_email" : "Change Email",
57
-    "current_user_email" : "Current Email",
58
-    "new_user_email" : "New Email",
59
-    "repeat_new_user_email" : "Repeat New Email",
60
-    "close_user_account" : "Close Account",
61
-    "if_you_want_to_close_account" : "If you want to close your Roundpin user account click on the button from below",
62
-    "asterisk_server_address" : "WebSocket Domain",
63
-    "eg_asterisk_server_address" : "Eg: roundpin.example.com",
64
-    "websocket_port" : "WebSocket Port",
65
-    "eg_websocket_port" : "Eg: 8089",
66
-    "websocket_path" : "WebSocket Path",
67
-    "eg_websocket_path" : "Eg: /ws", 
68
-    "sip_username" : "SIP Username",
69
-    "eg_sip_username" : "Eg: 601",
70
-    "sip_password" : "SIP Password",
71
-    "eg_sip_password" : "Eg: y2G5vEz6Q8l9U2RsC",
72
-    "stun_server" : "STUN server domain or IPv4 address, and port number",
73
-    "speaker" : "Speaker",
74
-    "microphone" : "Microphone",
75
-    "camera" : "Camera",
76
-    "frame_rate" : "Frame Rate (per second)",
77
-    "quality" : "Quality",
78
-    "image_orientation" : "Image Orientation",
79
-    "aspect_ratio" : "Aspect Ratio",
80
-    "preview" : "Preview",
81
-    "ringtone" : "Ringtone",
82
-    "ring_device" : "Ring Device",
83
-    "video_conference_extension" : "Video Conference Extension",
84
-    "video_conference_extension_example" : "Eg: 789",
85
-    "video_conference_window_width" : "Percent of screen width that the video conference windows will have",
86
-    "video_conf_window_width_explanation" : "Eg: enter 32 to make windows 32% of screen width",
87
-    "auto_gain_control" : "Auto Gain Control",
88
-    "echo_cancellation" : "Echo Cancellation",
89
-    "noise_suppression" : "Noise Suppression",
90
-    "enable_onscreen_notifications" : "Enabled Onscreen Notifications",
91
-    "alert_notification_permission" : "You need to accept the permission request to allow Notifications",
92
-    "permission" : "Permission",
93
-    "error" : "Error",
94
-    "alert_media_devices" : "MediaDevices was null -  Check if your connection is secure (HTTPS)",
95
-    "alert_error_user_media" : "Error getting User Media.",
96
-    "alert_file_size" : "The file is bigger than 50MB, you cannot upload this file",
97
-    "alert_single_file" : "Select a single file",
98
-    "alert_not_found" : "This item was not found",
99
-    "edit" : "Edit",
100
-    "edit_contact" : "Edit Contact",
101
-    "welcome" : "Welcome",
102
-    "accept" : "Accept",
103
-    "error_user_agant" : "Error creating User Agent",
104
-    "registered" : "Registered",
105
-    "registration_failed" : "Registration Failed",
106
-    "unregistered" : "Unregistered, bye!",
107
-    "connected_to_web_socket" : "Connected to Web Socket!",
108
-    "disconnected_from_web_socket" : "Disconnected from Web Socket!",
109
-    "web_socket_error" : "Web Socket Error",
110
-    "connecting_to_web_socket" : "Connecting to Web Socket...",
111
-    "error_connecting_web_socket" : "Error connecting to the server on the WebSocket port",
112
-    "sending_registration" : "Sending Registration...",
113
-    "unsubscribing" : "Unsubscribing...",
114
-    "disconnecting" : "Disconnecting...",
115
-    "incomming_call" : "Roundpin Incoming Call",
116
-    "incomming_call_from" : "Incoming call from:",
117
-    "answer_call" : "Answer Call",
118
-    "answer_call_with_video" : "Answer Call with Video",
119
-    "reject_call" : "Reject Call",
120
-    "call_failed" : "Call Failed",
121
-    "alert_no_microphone" : "Sorry, you don't have any Microphone connected to this computer. You cannot receive calls.",
122
-    "call_in_progress" : "Call in Progress!",
123
-    "call_rejected" : "Call Rejected",
124
-    "trying" : "Trying...",
125
-    "ringing" : "Ringing...",
126
-    "call_cancelled" : "Call Cancelled",
127
-    "call_ended" : "Call ended, bye!",
128
-    "yes" : "Yes",
129
-    "no" : "No",
130
-    "receive_kilobits_per_second" : "Receive Kilobits per second",
131
-    "receive_packets_per_second" : "Receive Packets per second",
132
-    "receive_packet_loss" : "Receive Packet Loss",
133
-    "receive_jitter" : "Receive Jitter",
134
-    "receive_audio_levels" : "Receive Audio Levels",
135
-    "send_kilobits_per_second" : "Send Kilobits Per Second",
136
-    "send_packets_per_second" : "Send Packets Per Second",
137
-    "state_not_online" : "Not online",
138
-    "state_ready" : "Ready",
139
-    "state_on_the_phone" : "On the phone",
140
-    "state_ringing" : "Ringing",
141
-    "state_on_hold" : "On hold",
142
-    "state_unavailable" : "Unavailable",
143
-    "state_unknown" : "Unknown",
144
-    "alert_empty_text_message" : "Please enter a message in the provided text box or select a file to send, then click the paper plane button on the right, or press Ctrl + Enter, to send the message and/or the file.",
145
-    "no_message" : "No Message",
146
-    "message_from" : "Message from",
147
-    "starting_video_call" : "Starting Video Call...",
148
-    "call_extension" : "Call Extension",
149
-    "call_mobile" : "Call Mobile",
150
-    "call_number" : "Call Number",
151
-    "call_group" : "Call Group",
152
-    "starting_audio_call" : "Starting Audio Call...",
153
-    "call_recording_started" : "Call Recording Started",
154
-    "call_recording_stopped" : "Call Recording Stopped",
155
-    "confirm_stop_recording" : "Are you sure you want to stop recording this call?",
156
-    "dial_number" : "Dial Number",
157
-    "stop_recording" : "Stop Recording?",
158
-    "width" : "Width",
159
-    "height" : "Height",
160
-    "extension" : "Extension",
161
-    "call_blind_transfered" : "Call Blind Transfered",
162
-    "connecting" : "Connecting...",
163
-    "attended_transfer_call_started" : "Attended Transfer Call Started...",
164
-    "attended_transfer_call_cancelled" : "Attended Transfer Call Cancelled",
165
-    "attended_transfer_complete_accepted" : "Attended Transfer Complete (Accepted)",
166
-    "attended_transfer_complete" : "Attended Transfer complete",
167
-    "attended_transfer_call_ended" : "Attended Transfer Call Ended",
168
-    "attended_transfer_call_rejected" : "Attended Transfer Call Rejected",
169
-    "attended_transfer_call_terminated" : "Attended Transfer Call Terminated",
170
-    "launch_video_conference" : "Launch Video Conference",
171
-    "conference_call_started" : "Conference Call Started...",
172
-    "canference_call_cancelled" : "Conference Call Cancelled",
173
-    "conference_call_in_progress" : "Conference Call In Progress",
174
-    "conference_call_ended" : "Conference Call Ended",
175
-    "conference_call_rejected" : "Conference Call Rejected",
176
-    "conference_call_terminated" : "Conference Call Terminated",
177
-    "null_session" : "Session Error, Null",
178
-    "call_on_hold" : "Call on Hold",
179
-    "send_dtmf" : "Sent DTMF",
180
-    "switching_video_source" : "Switching video source",
181
-    "switching_to_canvas" : "Switching to canvas",
182
-    "switching_to_shared_video" : "Switching to Shared Video",
183
-    "switching_to_shared_screeen" : "Switching to Shared Screen",
184
-    "video_disabled" : "Video Disabled",
185
-    "line" : "Line",
186
-    "back" : "Back",
187
-    "send_email" : "Send Email",
188
-    "audio_call" : "Audio Call",
189
-    "video_call" : "Video Call",
190
-    "find_something" : "Find in Message Stream",
191
-    "send_chat_message": "Send Message",
192
-    "save_chat_text": "Save Chat Text",
193
-    "remove" : "Remove",
194
-    "remove_contact" : "Remove Contact",
195
-    "present" : "Present",
196
-    "scratchpad" : "Scratchpad",
197
-    "screen" : "Screen",
198
-    "video" : "Video",
199
-    "blank" : "Blank",
200
-    "show_key_pad" : "Show Key Pad",
201
-    "mute" : "Mute",
202
-    "unmute" : "Unmute",
203
-    "start_call_recording" : "Start Call Recording",
204
-    "stop_call_recording" : "Stop Call Recording",
205
-    "transfer_call" : "Transfer Call",
206
-    "cancel_transfer" : "Cancel Transfer",
207
-    "conference_call" : "Conference Call",
208
-    "cancel_conference" : "Cancel Conference",
209
-    "hold_call" : "Hold Call",
210
-    "resume_call" : "Resume Call",
211
-    "end_call" : "End Call",
212
-    "search_or_enter_number" : "Search or enter number",
213
-    "blind_transfer" : "Blind Transfer",
214
-    "attended_transfer" : "Attended Transfer",
215
-    "complete_transfer" : "Complete Transfer",
216
-    "end_transfer_call" : "End Transfer Call",
217
-    "call" : "Call",
218
-    "cancel_call" : "Cancel Call",
219
-    "join_conference_call" : "Join Conference Call",
220
-    "end_conference_call" : "End Conference Call",
221
-    "microphone_levels" : "Microphone Levels",
222
-    "speaker_levels" : "Speaker Levels",
223
-    "send_statistics" : "Send Statistics",
224
-    "receive_statistics" : "Receive Statistics",
225
-    "find_something_in_the_message_stream" : "Find in message stream ...",
226
-    "type_your_message_here" : "Type the message here, then click the paper plane button on the right or press Ctrl + Enter to send it.",
227
-    "menu" : "Menu",
228
-    "confirm_remove_buddy" : "Are you sure you want to remove this contact from your contacts list and from the database ? This action cannot be undone. Click 'OK' to remove the contact or 'Cancel' to cancel.",
229
-    "remove_buddy" : "Remove Contact",
230
-    "confirm_close_account" : "Are you sure you want to close your Roundpin user account ? Click 'OK' to close your Roundpin user account, or 'Cancel' to cancel.",
231
-    "close_user_account" : "Close Account",
232
-    "close_roundpin_user_account" : "Close Roundpin User Account",
233
-    "read_more" : "Read More",
234
-    "started" : "Started",
235
-    "stopped" : "Stopped",
236
-    "recording_duration" : "Recording Duration",
237
-    "a_video_call" : "a video call",
238
-    "an_audio_call" : "an audio call",
239
-    "you_tried_to_make" : "You tried to make",
240
-    "you_made" : "You made",
241
-    "and_spoke_for" : "and spoke for",
242
-    "you_missed_a_call" : "Missed call",
243
-    "you_recieved" : "You received",
244
-    "second_single" : "second",
245
-    "seconds_plural" : "seconds",
246
-    "minute_single" : "minute",
247
-    "minutes_plural" : "minutes",
248
-    "hour_single" : "hour",
249
-    "hours_plural" : "hours",
250
-    "bytes" : "Bytes",
251
-    "kb" : "KB",
252
-    "mb" : "MB",
253
-    "gb" : "GB",
254
-    "tb" : "TB",
255
-    "pb" : "PB",
256
-    "eb" : "EB",
257
-    "zb" : "ZB",
258
-    "yb" : "YB",
259
-    "call_on_mute" : "Call on Mute",
260
-    "call_off_mute" : "Call off Mute",
261
-    "tag_call" : "Tag Call",
262
-    "clear_flag" : "Clear Flag",
263
-    "flag_call" : "Flag Call",
264
-    "edit_comment" : "Edit Comment",
265
-    "copy_message" : "Copy Message",
266
-    "quote_message" : "Quote Message",
267
-    "select_expression" : "Select Emoticon",
268
-    "send_file": "Send File",
269
-    "dictate_message" : "Dictate Message",
270
-    "alert_speech_recognition" : "Your browser does not support this function, sorry",
271
-    "speech_recognition" : "Speech Recognition",
272
-    "im_listening" : "I'm listening...",
273
-    "msg_silence_detection": "You were quiet for a while so voice recognition turned itself off.",
274
-    "msg_no_speech": "No speech was detected. Try again.",
275
-    "loading": "Loading...",
276
-    "select_video": "Select Video",
277
-    "ok": "OK",
278
-    "device_settings" : "Device Settings",
279
-    "call_stats" : "Call Stats",
280
-    "you_received_a_call_from" : "You received a call from",
281
-    "you_made_a_call_to" : "You made a call to",
282
-    "you_answered_after" : "You answered after",
283
-    "they_answered_after" : "They answered after",
284
-    "with_video" : "with video",
285
-    "you_started_a_blind_transfer_to" : "You started a blind transfer to",
286
-    "you_started_an_attended_transfer_to" : "You started an attended transfer to",
287
-    "the_call_was_completed" : "The call was completed.",
288
-    "the_call_was_not_completed" : "The call was not completed.",
289
-    "you_put_the_call_on_mute" : "You put the call on mute.",
290
-    "you_took_the_call_off_mute" : "You took the call off mute.",
291
-    "you_put_the_call_on_hold" : "You put the call on hold.",
292
-    "you_took_the_call_off_hold" : "You took the call off hold.",
293
-    "call_is_being_recorded" : "Call is being recorded.",
294
-    "now_stopped" : "Now Stopped",
295
-    "you_started_a_conference_call_to" : "You started a conference call to",
296
-    "show_call_detail_record" : "Show Call Detail Record",
297
-    "call_detail_record" : "Call Detail Record",
298
-    "call_direction" : "Call Direction",
299
-    "call_date_and_time" : "Call Date & Time",
300
-    "ring_time" : "Ring Time",
301
-    "talk_time" : "Talk Time",
302
-    "call_duration" : "Call Duration",
303
-    "flagged" : "Flagged",
304
-    "call_tags" : "Call Tags",
305
-    "call_notes" : "Call Notes",
306
-    "activity_timeline" : "Activity Timeline",
307
-    "call_recordings" : "Call Recordings",
308
-    "save_as" : "Save As",
309
-    "right_click_and_select_save_link_as" : "Right click and select Save Link As",
310
-    "send" : "Send",
311
-    "external_conf_users" : "External Video Conference Users",
312
-    "about" : "About",
313
-    "about_text" : "Roundpin is a fully featured browser phone that connects to an Asterisk server and implements audio/video calls, text messaging and video conferencing by using SIP over WebSocket and WebRTC. <br><br>Version 1.0.8<br><br>You can support the continuous maintenance of Roundpin by <a href='https://www.doublebastion.com/donations' target='_blank'>donating</a>.<br>Roundpin is a component of <a href='https://www.doublebastion.com/' target='_blank'>RED SCARF Suite</a>.<br><br> Copyright © 2021 <a href='https://www.doublebastion.com/contact/' target='_blank'>Double Bastion LLC</a> <br> License: <a href='https://www.gnu.org/licenses/agpl-3.0.html' target='_blank'>GNU Affero General Public License v3.0</a><br><br><a href='https://www.doublebastion.com/roundpin/' target='_blank'>Web page<a><br><a href='https://git.doublebastion.com/roundpin/' target='_blank'>Repository</a>"
314
-}