Browse code

added 4 modified files

DoubleBastionAdmin authored on 25/03/2022 13:16:26
Showing 4 changed files
1 1
new file mode 100644
... ...
@@ -0,0 +1,10 @@
1
+
2
+======= CHANGELOG =======
3
+
4
+Versions:
5
+
6
+== 1.0.0 - 2022-1-27 ==
7
+* Initial Release.
8
+
9
+== 1.0.1 - 2022-1-26 ==
10
+* Fixed error message on logout.
0 11
new file mode 100644
... ...
@@ -0,0 +1,12549 @@
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
+-------------------------------------------------------------
17
+ Copyright (c) 2020  - Conrad de Wet - All Rights Reserved.
18
+=============================================================
19
+File: phone.js
20
+License: GNU Affero General Public License v3.0
21
+Version: 0.1.0
22
+Owner: Conrad de Wet
23
+Date: April 2020
24
+Git: https://github.com/InnovateAsterisk/Browser-Phone
25
+*/
26
+
27
+// Global Settings
28
+// ===============
29
+var enabledExtendedServices = false;
30
+var enabledGroupServices = false;
31
+
32
+// Lanaguage Packs (lang/xx.json)
33
+// ===============
34
+// Note: The following should correspond to files on your server.
35
+// eg: If you list "fr" then you need to add the file "fr.json".
36
+// Use the "en.json" as a template.
37
+// More specific lanagauge must be first. ie: "zh-hans" should be before "zh".
38
+// "en.json" is always loaded by default
39
+const availableLang = ["ja", "zh-hans", "zh", "ru", "tr", "nl"];
40
+
41
+// User Settings & Defaults
42
+// ========================
43
+var wssServer = getDbItem("wssServer", null);
44
+var profileUserID = getDbItem("profileUserID", null);
45
+var profileUser = getDbItem("profileUser", null);
46
+var profileName = getDbItem("profileName", null);
47
+var WebSocketPort = getDbItem("WebSocketPort", null);
48
+var ServerPath = getDbItem("ServerPath", null);
49
+var SipUsername = getDbItem("SipUsername", null);
50
+var SipPassword = getDbItem("SipPassword", null);
51
+var StunServer = getDbItem("StunServer", "");
52
+
53
+var TransportConnectionTimeout = parseInt(getDbItem("TransportConnectionTimeout", 15));        // The timeout in seconds for the initial connection to make on the web socket port
54
+var TransportReconnectionAttempts = parseInt(getDbItem("TransportReconnectionAttempts", 99));  // The number of times to attempt to reconnect to a WebSocket when the connection drops.
55
+var TransportReconnectionTimeout = parseInt(getDbItem("TransportReconnectionTimeout", 15));    // The time in seconds to wait between WebSocket reconnection attempts.
56
+
57
+var userAgentStr = getDbItem("UserAgentStr", "Roundpin (SipJS - 0.11.6)");          // Set this to whatever you want.
58
+var hostingPrefex = getDbItem("HostingPrefex", "");                                 // Use if hosting off root directiory. eg: "/phone/" or "/static/"
59
+var RegisterExpires = parseInt(getDbItem("RegisterExpires", 300));                  // Registration expiry time (in seconds)
60
+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)
61
+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)
62
+var IceStunCheckTimeout = parseInt(getDbItem("IceStunCheckTimeout", 500));  // Set amount of time in milliseconds to wait for the ICE/STUN server
63
+var AutoAnswerEnabled = (getDbItem("AutoAnswerEnabled", "0") == "1");       // Automatically answers the phone when the call comes in, if you are not on a call already
64
+var DoNotDisturbEnabled = (getDbItem("DoNotDisturbEnabled", "0") == "1");   // Rejects any inbound call, while allowing outbound calls
65
+var CallWaitingEnabled = (getDbItem("CallWaitingEnabled", "1") == "1");     // Rejects any inbound call if you are on a call already.
66
+var RecordAllCalls = (getDbItem("RecordAllCalls", "0") == "1");             // Starts Call Recording when a call is established.
67
+var StartVideoFullScreen = (getDbItem("StartVideoFullScreen", "1") == "0"); // Starts a vdeo call in the full screen (browser screen, not dektop)
68
+var AutoGainControl = (getDbItem("AutoGainControl", "1") == "1");           // Attempts to adjust the microphone volume to a good audio level. (OS may be better at this)
69
+var EchoCancellation = (getDbItem("EchoCancellation", "1") == "1");         // Attemots to remove echo over the line.
70
+var NoiseSuppression = (getDbItem("NoiseSuppression", "1") == "1");         // Attempts to clear the call qulity of noise.
71
+var MirrorVideo = getDbItem("VideoOrientation", "rotateY(180deg)");         // Displays the self-preview in normal or mirror view, to better present the preview. 
72
+var maxFrameRate = getDbItem("FrameRate", "");                              // Suggests a frame rate to your webcam if possible.
73
+var videoHeight = getDbItem("VideoHeight", "");                             // Suggests a video height (and therefore picture quality) to your webcam.
74
+var videoAspectRatio = getDbItem("AspectRatio", "");                        // Suggests an aspect ratio (1:1 | 4:3 | 16:9) to your webcam.
75
+var NotificationsActive = (getDbItem("Notifications", "0") == "1");
76
+var StreamBuffer = parseInt(getDbItem("StreamBuffer", 50));                 // The amount of rows to buffer in the Buddy Stream
77
+var PosterJpegQuality = parseFloat(getDbItem("PosterJpegQuality", 0.6));    // The image quality of the Video Poster images
78
+var VideoResampleSize = getDbItem("VideoResampleSize", "HD");               // The resample size (height) to re-render video that gets presented (sent). (SD = ???x360 | HD = ???x720 | FHD = ???x1080)
79
+var RecordingVideoSize = getDbItem("RecordingVideoSize", "HD");             // The size/quality of the video track in the recodings (SD = 640x360 | HD = 1280x720 | FHD = 1920x1080)
80
+var RecordingVideoFps = parseInt(getDbItem("RecordingVideoFps", 12));       // The Frame Per Second of the Video Track recording
81
+var RecordingLayout = getDbItem("RecordingLayout", "them-pnp");             // The Layout of the Recording Video Track (side-by-side | us-pnp | them-pnp | us-only | them-only)
82
+var DidLength = parseInt(getDbItem("DidLength", 6));                        // DID length from which to decide if an incoming caller is a "contact" or an "extension".
83
+var MaxDidLength = parseInt(getDbItem("maximumNumberLength", 16));          // Maximum langth of any DID number including international dialled numbers.
84
+var DisplayDateFormat = getDbItem("DateFormat", "YYYY-MM-DD");              // The display format for all dates. https://momentjs.com/docs/#/displaying/
85
+var DisplayTimeFormat = getDbItem("TimeFormat", "h:mm:ss A");               // The display format for all times. https://momentjs.com/docs/#/displaying/
86
+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
87
+
88
+// Permission Settings
89
+var EnableTextMessaging = (getDbItem("EnableTextMessaging", "1") == "1");               // Enables the Text Messaging
90
+var DisableFreeDial = (getDbItem("DisableFreeDial", "0") == "1");                       // Removes the Dial icon in the profile area, users will need to add buddies in order to dial.
91
+var DisableBuddies = (getDbItem("DisableBuddies", "0") == "1");                         // Removes the Add Someone menu item and icon from the profile area. Buddies will still be created automatically. 
92
+var EnableTransfer = (getDbItem("EnableTransfer", "1") == "1");                         // Controls Transfering during a call
93
+var EnableConference = (getDbItem("EnableConference", "1") == "1");                     // Controls Conference during a call
94
+var AutoAnswerPolicy = getDbItem("AutoAnswerPolicy", "allow");                          // allow = user can choose | disabled = feature is disabled | enabled = feature is always on
95
+var DoNotDisturbPolicy = getDbItem("DoNotDisturbPolicy", "allow");                      // allow = user can choose | disabled = feature is disabled | enabled = feature is always on
96
+var CallWaitingPolicy = getDbItem("CallWaitingPolicy", "allow");                        // allow = user can choose | disabled = feature is disabled | enabled = feature is always on
97
+var CallRecordingPolicy = getDbItem("CallRecordingPolicy", "allow");                    // allow = user can choose | disabled = feature is disabled | enabled = feature is always on
98
+var EnableAccountSettings = (getDbItem("EnableAccountSettings", "1") == "1");           // Controls the Account tab in Settings
99
+var EnableAudioVideoSettings = (getDbItem("EnableAudioVideoSettings", "1") == "1");     // Controls the Audio & Video tab in Settings
100
+var EnableAppearanceSettings = (getDbItem("EnableAppearanceSettings", "1") == "1");     // Controls the Appearance tab in Settings
101
+var EnableChangeUserPasswordSettings = (getDbItem("EnableChangeUserPasswordSettings", "1") == "1"); // Controls the 'Change Password' tab in Settings
102
+var EnableChangeUserEmailSettings = (getDbItem("EnableChangeUserEmailSettings", "1") == "1");       // Controls the 'Change Email' tab in Settings
103
+var EnableCloseUserAccount = (getDbItem("EnableCloseUserAccount", "1") == "1");                     // Controls the 'Close Account' tab in Settings
104
+var EnableAlphanumericDial = (getDbItem("EnableAlphanumericDial", "1") == "1");                     // Allows calling /[^\da-zA-Z\*\#\+]/g default is /[^\d\*\#\+]/g
105
+var EnableVideoCalling = (getDbItem("EnableVideoCalling", "1") == "1");                             // Enables Video during a call
106
+var winVideoConf = null;
107
+var winVideoConfCheck = 0;
108
+
109
+// System variables
110
+// ================
111
+var localDB = window.localStorage;
112
+var userAgent = null;
113
+var voicemailSubs = null;
114
+var BlfSubs = [];
115
+var CanvasCollection = [];
116
+var Buddies = [];
117
+var isReRegister = false;
118
+var dhtmlxPopup = null;
119
+var selectedBuddy = null;
120
+var selectedLine = null;
121
+var alertObj = null;
122
+var confirmObj = null;
123
+var promptObj = null;
124
+var windowsCollection = null;
125
+var messagingCollection = null;
126
+var HasVideoDevice = false;
127
+var HasAudioDevice = false;
128
+var HasSpeakerDevice = false;
129
+var AudioinputDevices = [];
130
+var VideoinputDevices = [];
131
+var SpeakerDevices = [];
132
+var Lines = [];
133
+var lang = {};
134
+var audioBlobs = {};
135
+var newLineNumber = 0;
136
+var videoAudioCheck = 0;
137
+var RCLoginCheck = 0;
138
+var decSipPass = '';
139
+var currentChatPrivKey = '';
140
+var sendFileCheck = 0;
141
+var upFileName = '';
142
+var sendFileChatErr = '';
143
+var pubKeyCheck = 0;
144
+var splitMessage = {};
145
+
146
+// Utilities
147
+// =========
148
+function uID(){
149
+    return Date.now()+Math.floor(Math.random()*10000).toString(16).toUpperCase();
150
+}
151
+function utcDateNow(){
152
+    return moment().utc().format("YYYY-MM-DD HH:mm:ss UTC");
153
+}
154
+function getDbItem(itemIndex, defaultValue){
155
+    var localDB = window.localStorage;
156
+    if(localDB.getItem(itemIndex) != null) return localDB.getItem(itemIndex);
157
+    return defaultValue;
158
+}
159
+function getAudioSrcID(){
160
+    var id = localDB.getItem("AudioSrcId");
161
+    return (id != null)? id : "default";
162
+}
163
+function getAudioOutputID(){
164
+    var id = localDB.getItem("AudioOutputId");
165
+    return (id != null)? id : "default";
166
+}
167
+function getVideoSrcID(){
168
+    var id = localDB.getItem("VideoSrcId");
169
+    return (id != null)? id : "default";
170
+}
171
+function getRingerOutputID(){
172
+    var id = localDB.getItem("RingOutputId");
173
+    return (id != null)? id : "default";
174
+}
175
+function formatDuration(seconds){
176
+    var sec = Math.floor(parseFloat(seconds));
177
+    if(sec < 0){
178
+        return sec;
179
+    }
180
+    else if(sec >= 0 && sec < 60){
181
+         return sec + " " + ((sec != 1) ? lang.seconds_plural : lang.second_single);
182
+    } 
183
+    else if(sec >= 60 && sec < 60 * 60){ // greater then a minute and less then an hour
184
+        var duration = moment.duration(sec, 'seconds');
185
+        return duration.minutes() + " "+ ((duration.minutes() != 1) ? lang.minutes_plural: lang.minute_single) +" " + duration.seconds() +" "+ ((duration.seconds() != 1) ? lang.seconds_plural : lang.second_single);
186
+    } 
187
+    else if(sec >= 60 * 60 && sec < 24 * 60 * 60){ // greater than an hour and less then a day
188
+        var duration = moment.duration(sec, 'seconds');
189
+        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);
190
+    } 
191
+    //  Otherwise.. this is just too long
192
+}
193
+function formatShortDuration(seconds) {
194
+    var sec = Math.floor(parseFloat(seconds));
195
+    if(sec < 0){
196
+        return sec;
197
+    } 
198
+    else if(sec >= 0 && sec < 60){
199
+        return "00:"+ ((sec > 9)? sec : "0"+sec );
200
+    } 
201
+    else if(sec >= 60 && sec < 60 * 60){ // greater then a minute and less then an hour
202
+        var duration = moment.duration(sec, 'seconds');
203
+        return ((duration.minutes() > 9)? duration.minutes() : "0"+duration.minutes()) + ":" + ((duration.seconds() > 9)? duration.seconds() : "0"+duration.seconds());
204
+    } 
205
+    else if(sec >= 60 * 60 && sec < 24 * 60 * 60){ // greater than an hour and less then a day
206
+        var duration = moment.duration(sec, 'seconds');
207
+        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());
208
+    } 
209
+    //  Otherwise.. this is just too long
210
+}
211
+function formatBytes(bytes, decimals) {
212
+    if (bytes === 0) return "0 "+ lang.bytes;
213
+    var k = 1024;
214
+    var dm = (decimals && decimals >= 0)? decimals : 2;
215
+    var sizes = [lang.bytes, lang.kb, lang.mb, lang.gb, lang.tb, lang.pb, lang.eb, lang.zb, lang.yb];
216
+    var i = Math.floor(Math.log(bytes) / Math.log(k));
217
+    return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + " " + sizes[i];
218
+}
219
+function UserLocale(){
220
+    var language = window.navigator.userLanguage || window.navigator.language; // "en", "en-US", "fr", "fr-FR", "es-ES", etc.
221
+
222
+    langtag = language.split('-');
223
+    if(langtag.length == 1){
224
+        return ""; 
225
+    } 
226
+    else if(langtag.length == 2) {
227
+        return langtag[1].toLowerCase();  // en-US => us
228
+    }
229
+    else if(langtag.length >= 3) {
230
+        return langtag[1].toLowerCase();  // en-US => us
231
+    }
232
+}
233
+function GetAlternateLanguage() {
234
+    var userLanguage = window.navigator.userLanguage || window.navigator.language; // "en", "en-US", "fr", "fr-FR", "es-ES", etc.
235
+
236
+    if(Language != "auto") userLanguage = Language;
237
+    userLanguage = userLanguage.toLowerCase();
238
+    if(userLanguage == "en" || userLanguage.indexOf("en-") == 0) return "";  // English is already loaded
239
+
240
+    for(l = 0; l < availableLang.length; l++) {
241
+        if(userLanguage.indexOf(availableLang[l].toLowerCase()) == 0) {
242
+            console.log("Alternate Language detected: ", userLanguage);
243
+            // Set up Moment with the same langugae settings
244
+            moment.locale(userLanguage);
245
+            return availableLang[l].toLowerCase();
246
+        }
247
+    }
248
+    return "";
249
+}
250
+function getFilter(filter, keyword) {
251
+    if(filter.indexOf(",", filter.indexOf(keyword +": ") + keyword.length + 2) != -1) {
252
+        return filter.substring(filter.indexOf(keyword +": ") + keyword.length + 2, filter.indexOf(",", filter.indexOf(keyword +": ") + keyword.length + 2));
253
+    }
254
+    else {
255
+        return filter.substring(filter.indexOf(keyword +": ") + keyword.length + 2);
256
+    }
257
+}
258
+function base64toBlob(base64Data, contentType) {
259
+    if(base64Data.indexOf("," != -1)) base64Data = base64Data.split(",")[1]; // [data:image/png;base64] , [xxx...]
260
+    var byteCharacters = atob(base64Data);
261
+    var slicesCount = Math.ceil(byteCharacters.length / 1024);
262
+    var byteArrays = new Array(slicesCount);
263
+    for (var s = 0; s < slicesCount; ++s) {
264
+        var begin = s * 1024;
265
+        var end = Math.min(begin + 1024, byteCharacters.length);
266
+        var bytes = new Array(end - begin);
267
+        for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
268
+            bytes[i] = byteCharacters[offset].charCodeAt(0);
269
+        }
270
+        byteArrays[s] = new Uint8Array(bytes);
271
+    }
272
+    return new Blob(byteArrays, { type: contentType });
273
+}
274
+function MakeDataArray(defaultValue, count) {
275
+    var rtnArray = new Array(count);
276
+    for(var i=0; i< rtnArray.length; i++) {
277
+        rtnArray[i] = defaultValue;
278
+    }
279
+    return rtnArray;
280
+}
281
+// Save account configuration data to SQL database
282
+function saveConfToSqldb() {
283
+
284
+    wssServer = $("#Configure_Account_wssServer").val();
285
+    WebSocketPort = parseInt($("#Configure_Account_WebSocketPort").val());
286
+    ServerPath = $("#Configure_Account_ServerPath").val();
287
+    profileName = $("#Configure_Account_profileName").val();
288
+    SipUsername = $("#Configure_Account_SipUsername").val();
289
+    SipPassword = $("#Configure_Account_SipPassword").val();
290
+
291
+    var STUNServer = $("#Configure_Account_StunServer").val();
292
+    var AUDIOOutputId = $("#playbackSrc").val();
293
+    var VIDEOSrcId = $("#previewVideoSrc").val();
294
+    var VIDEOHeight = $("input[name=Settings_Quality]:checked").val(); 
295
+    var FRAMERate = parseInt($("input[name=Settings_FrameRate]:checked").val());
296
+    var ASPECTRatio = $("input[name=Settings_AspectRatio]:checked").val();
297
+    var VIDEOOrientation = $("input[name=Settings_Oriteation]:checked").val();
298
+    var AUDIOSrcId = $("#microphoneSrc").val();
299
+    var AUTOGainControl = ($("#Settings_AutoGainControl").is(':checked'))? "1" : "0";
300
+    var ECHOCancellation = ($("#Settings_EchoCancellation").is(':checked'))? "1" : "0";
301
+    var NOISESuppression = ($("#Settings_NoiseSuppression").is(':checked'))? "1" : "0";
302
+    var RINGOutputId = $("#ringDevice").val();
303
+    var VideoConfExtension = $("#Video_Conf_Extension").val();
304
+    var VideoConfWindowWidth = $("#Video_Conf_Window_Width").val();
305
+    var PROFILEpicture = (typeof getDbItem("profilePicture", "") === 'undefined') ? "" : getDbItem("profilePicture", "");
306
+    var NOTIFYCheck = ($("#Settings_Notifications").is(":checked"))? 1 : 0;
307
+    var EMAILIntegration = ($("#emailIntegration").is(":checked"))? 1 : 0;
308
+    var RCDomain = $("#RoundcubeDomain").val();
309
+    var RCbasicauthuser = $("#rcBasicAuthUser").val();
310
+    var RCbasicauthpass = $("#rcBasicAuthPass").val();
311
+    var RCuser = $("#RoundcubeUser").val();
312
+    var RCpassword = $("#RoundcubePass").val();
313
+
314
+    if (userName != '') {
315
+
316
+       if (wssServer != '' && WebSocketPort != '' && ServerPath != '' && SipUsername != '' && SipPassword != '') {
317
+
318
+          $.ajax({
319
+             type: "POST",
320
+             url: "save-update-settings.php",
321
+             dataType: "JSON",
322
+             data: {
323
+                     username: userName,
324
+                     wss_server: wssServer,
325
+                     web_socket_port: WebSocketPort,
326
+                     server_path: ServerPath,
327
+                     profile_name: profileName,
328
+                     sip_username: SipUsername,
329
+                     sip_password: SipPassword,
330
+                     stun_server: STUNServer,
331
+                     audio_output_id: AUDIOOutputId,
332
+                     video_src_id: VIDEOSrcId,
333
+                     video_height: VIDEOHeight,
334
+                     frame_rate: FRAMERate,
335
+                     aspect_ratio: ASPECTRatio,
336
+                     video_orientation: VIDEOOrientation,
337
+                     audio_src_id: AUDIOSrcId,
338
+                     auto_gain_control: AUTOGainControl,
339
+                     echo_cancellation: ECHOCancellation,
340
+                     noise_suppression: NOISESuppression,
341
+                     ring_output_id: RINGOutputId,
342
+                     video_conf_extension: VideoConfExtension,
343
+                     video_conf_window_width: VideoConfWindowWidth,
344
+                     profile_picture: PROFILEpicture,
345
+                     notifications: NOTIFYCheck,
346
+                     use_roundcube: EMAILIntegration,
347
+                     rcdomain: RCDomain,
348
+                     rcbasicauthuser: RCbasicauthuser,
349
+                     rcbasicauthpass: RCbasicauthpass,
350
+                     rcuser: RCuser,
351
+                     rcpassword: RCpassword,
352
+                     s_ajax_call: validateSToken
353
+             },
354
+             success: function(response) {
355
+                             window.location.reload();
356
+                      },
357
+             error: function(response) {
358
+                             alert("An error occurred while attempting to save the account configuration data!");
359
+             }
360
+          });
361
+
362
+       } else { alert("Fields: 'WebSocket Domain', 'WebSocket Port', 'WebSocket Path', 'SIP Username' and 'SIP Password' are required ! Please fill in all these fields !"); }
363
+
364
+    } else { alert("An error occurred while attempting to save the data!"); }
365
+}
366
+// Get account configuration data from SQL database
367
+function getConfFromSqldb() {
368
+
369
+          $.ajax({
370
+             type: "POST",
371
+             url: "get-settings.php",
372
+             dataType: "JSON",
373
+             data: {
374
+                     username: userName,
375
+                     s_ajax_call: validateSToken
376
+             },
377
+             success: function(datafromdb) {
378
+
379
+                        // Get configuration data from SQL database
380
+                        if (datafromdb.wss_server == null || datafromdb.web_socket_port == null || datafromdb.server_path == null ||
381
+                            datafromdb.sip_username == null || datafromdb.sip_password == null) {
382
+
383
+                            ConfigureExtensionWindow();
384
+
385
+                        } else {
386
+
387
+				if (!localStorage.getItem('firstReLoad')) {
388
+				     localStorage['firstReLoad'] = true;
389
+				     window.setTimeout(function() { window.location.reload(); }, 200);
390
+				}
391
+
392
+                                if (datafromdb.stun_server == null || typeof datafromdb.stun_server == 'undefined') {
393
+                                    var stunData = '';
394
+                                } else { var stunData = datafromdb.stun_server; }
395
+
396
+		                localDB.setItem("profileUserID", uID());
397
+				localDB.setItem("userrole", datafromdb.userrole);
398
+				localDB.setItem("wssServer", datafromdb.wss_server);
399
+				localDB.setItem("WebSocketPort", datafromdb.web_socket_port);
400
+				localDB.setItem("ServerPath", datafromdb.server_path);
401
+				localDB.setItem("profileUser", datafromdb.sip_username);
402
+				localDB.setItem("profileName", datafromdb.profile_name);
403
+				localDB.setItem("SipUsername", datafromdb.sip_username);
404
+				localDB.setItem("SipPassword", datafromdb.sip_password);
405
+				localDB.setItem("StunServer", stunData);
406
+				localDB.setItem("AudioOutputId", datafromdb.audio_output_id);
407
+				localDB.setItem("VideoSrcId", datafromdb.video_src_id);
408
+				localDB.setItem("VideoHeight", datafromdb.video_height);
409
+				localDB.setItem("FrameRate", datafromdb.frame_rate);
410
+				localDB.setItem("AspectRatio", datafromdb.aspect_ratio);
411
+				localDB.setItem("VideoOrientation", datafromdb.video_orientation);
412
+				localDB.setItem("AudioSrcId", datafromdb.audio_src_id);
413
+				localDB.setItem("AutoGainControl", datafromdb.auto_gain_control);
414
+				localDB.setItem("EchoCancellation", datafromdb.echo_cancellation);
415
+				localDB.setItem("NoiseSuppression", datafromdb.noise_suppression);
416
+				localDB.setItem("RingOutputId", datafromdb.ring_output_id);
417
+                                localDB.setItem("VidConfExtension", datafromdb.video_conf_extension);
418
+                                localDB.setItem("VidConfWindowWidth", datafromdb.video_conf_window_width);
419
+				localDB.setItem("profilePicture", datafromdb.profile_picture);
420
+				localDB.setItem("Notifications", datafromdb.notifications);
421
+                                localDB.setItem("useRoundcube", datafromdb.use_roundcube);
422
+                                localDB.setItem("rcDomain", (datafromdb.rcdomain != '' && datafromdb.rcdomain != null && typeof datafromdb.rcdomain != 'undefined')? datafromdb.rcdomain : "");
423
+                                localDB.setItem("rcBasicAuthUser", datafromdb.rcbasicauthuser);
424
+                                localDB.setItem("rcBasicAuthPass", datafromdb.rcbasicauthpass);
425
+                                localDB.setItem("RoundcubeUser", datafromdb.rcuser);
426
+                                localDB.setItem("RoundcubePass", datafromdb.rcpassword);
427
+
428
+		                Register();
429
+                        }
430
+                      },
431
+             error: function(datafromdb) {
432
+                           alert("An error occurred while attempting to retrieve account configuration data from the database!");
433
+             }
434
+          });
435
+}
436
+
437
+// Save contact data to SQL database
438
+function saveContactToSQLDB(newPerson) {
439
+
440
+    if (newPerson.length != 0) {
441
+             $.ajax({
442
+                type: "POST",
443
+                url: "save-contact.php",
444
+                dataType: "JSON",
445
+                data: {
446
+                     username: userName,
447
+                     contact_name: newPerson[0],
448
+                     contact_desc: newPerson[1],
449
+                     extension_number: newPerson[2],
450
+                     contact_mobile: newPerson[3],
451
+                     contact_num1: newPerson[4],
452
+                     contact_num2: newPerson[5],
453
+                     contact_email: newPerson[6],
454
+                     s_ajax_call: validateSToken
455
+                },
456
+                success: function(response) {
457
+                         if (response.result != 'success') { alert(response.result); }
458
+                },
459
+                error: function(response) {
460
+                         alert("An error occurred while attempting to save the contact to the database!");
461
+                }
462
+          });
463
+    } else { alert("An error occurred while attempting to save the data!"); }
464
+}
465
+
466
+// Update contact data in SQL database
467
+function updateContactToSQLDB(newPerson) {
468
+
469
+    if (newPerson.length != 0) {
470
+        if (newPerson[7] != '' && newPerson[7] != null && typeof newPerson[7] != 'undefined') {
471
+            $.ajax({
472
+                type: "POST",
473
+                url: "update-contact.php",
474
+                dataType: "JSON",
475
+                data: {
476
+                     contact_name: newPerson[0],
477
+                     contact_desc: newPerson[1],
478
+                     extension_number: newPerson[2],
479
+                     contact_mobile: newPerson[3],
480
+                     contact_num1: newPerson[4],
481
+                     contact_num2: newPerson[5],
482
+                     contact_email: newPerson[6],
483
+                     contactDBID: newPerson[7],
484
+                     s_ajax_call: validateSToken
485
+                },
486
+                success: function(response) {
487
+                         if (response.result != 'success') { alert(response.result); }
488
+                },
489
+                error: function(response) {
490
+                         alert("An error occurred while attempting to save the data!");
491
+                }
492
+            });
493
+        } else { alert("Error while attempting to retrieve contact data from the database!"); }
494
+    } else { alert("An error occurred while attempting to save the data!"); }
495
+}
496
+// Save contact picture data to SQL database
497
+function saveContactPicToSQLDB(newPic) {
498
+
499
+    if (newPic.length != 0) {
500
+        $.ajax({
501
+             type: "POST",
502
+             url: "save-update-contact-picture.php",
503
+             dataType: "JSON",
504
+             data: {
505
+                     username: userName,
506
+                     contact_name: newPic[0],
507
+                     profile_picture_c: newPic[1],
508
+                     s_ajax_call: validateSToken
509
+             },
510
+             success: function(response) {
511
+                      },
512
+             error: function(response) {
513
+                          alert("An error occurred while attempting to save contact picture!");
514
+             }
515
+        });
516
+    } else { alert("An error occurred while attempting to save contact picture!"); }
517
+}
518
+// Get contact data from SQL database
519
+function getContactsFromSQLDB() {
520
+
521
+          $.ajax({
522
+             type: "POST",
523
+             url: "get-contacts.php",
524
+             dataType: "JSON",
525
+             data: {
526
+                     username: userName,
527
+                     s_ajax_call: validateSToken
528
+             },
529
+             success: function(contactsfromdb) {
530
+
531
+                        // Get contacts from SQL database and save them to localDB
532
+                        var jsonCon = InitUserBuddies();
533
+
534
+                        $.each(contactsfromdb.contactsinfo, function(ind, contactrow) {
535
+			       var id = uID();
536
+			       var dateNow = utcDateNow();
537
+
538
+                               if (contactsfromdb.contactsinfo[ind].extension_number == '' || contactsfromdb.contactsinfo[ind].extension_number == null) {
539
+ 
540
+				    jsonCon.DataCollection.push(
541
+					{
542
+					    Type: "contact",
543
+					    LastActivity: dateNow,
544
+					    ExtensionNumber: "",
545
+					    MobileNumber: contactsfromdb.contactsinfo[ind].contact_mobile,
546
+					    ContactNumber1: contactsfromdb.contactsinfo[ind].contact_num1,
547
+					    ContactNumber2: contactsfromdb.contactsinfo[ind].contact_num2,
548
+					    uID: null,
549
+					    cID: id,
550
+					    gID: null,
551
+					    DisplayName: contactsfromdb.contactsinfo[ind].contact_name,
552
+					    Position: "",
553
+					    Description: contactsfromdb.contactsinfo[ind].contact_desc, 
554
+					    Email: contactsfromdb.contactsinfo[ind].contact_email,
555
+					    MemberCount: 0
556
+					}
557
+				    );
558
+
559
+                                    if (contactsfromdb.contactsinfo[ind].profile_picture_c != '' && contactsfromdb.contactsinfo[ind].profile_picture_c != null) {
560
+                                        localDB.setItem("img-"+id+"-contact", contactsfromdb.contactsinfo[ind].profile_picture_c);
561
+                                    }
562
+
563
+			            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);
564
+			            AddBuddy(buddyObj, true, false, false);
565
+
566
+                               } else {
567
+
568
+				    jsonCon.DataCollection.push(
569
+					{
570
+					    Type: "extension",
571
+					    LastActivity: dateNow,
572
+					    ExtensionNumber: contactsfromdb.contactsinfo[ind].extension_number,
573
+					    MobileNumber: contactsfromdb.contactsinfo[ind].contact_mobile,
574
+					    ContactNumber1: contactsfromdb.contactsinfo[ind].contact_num1,
575
+					    ContactNumber2: contactsfromdb.contactsinfo[ind].contact_num2,
576
+					    uID: id,
577
+					    cID: null,
578
+					    gID: null,
579
+					    DisplayName: contactsfromdb.contactsinfo[ind].contact_name,
580
+					    Position: contactsfromdb.contactsinfo[ind].contact_desc,
581
+					    Description: "", 
582
+					    Email: contactsfromdb.contactsinfo[ind].contact_email,
583
+					    MemberCount: 0
584
+					}
585
+				    );
586
+
587
+                                    if (contactsfromdb.contactsinfo[ind].profile_picture_c != '' && contactsfromdb.contactsinfo[ind].profile_picture_c != null) {
588
+                                        localDB.setItem("img-"+id+"-extension", contactsfromdb.contactsinfo[ind].profile_picture_c);
589
+                                    }
590
+
591
+			            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);
592
+			            AddBuddy(buddyObj, true, false, true);
593
+                               } 
594
+                        });
595
+
596
+		        jsonCon.TotalRows = jsonCon.DataCollection.length;
597
+		        localDB.setItem(profileUserID + "-Buddies", JSON.stringify(jsonCon));
598
+
599
+                        UpdateUI();
600
+                        PopulateBuddyList();
601
+
602
+                      },
603
+             error: function(contactsfromdb) {
604
+                           alert("An error occurred while attempting to retrieve contacts data from the database!");
605
+             }
606
+          });
607
+}
608
+
609
+// Get external users data from SQL database
610
+function getExternalUserConfFromSqldb() {
611
+
612
+         $.ajax({
613
+             type: "POST",
614
+             url: "get-external-users-conf.php",
615
+             dataType: "JSON",
616
+             data: {
617
+                     username: userName, 
618
+                     s_ajax_call: validateSToken
619
+             },
620
+             success: function(extdatafromdb) {
621
+
622
+                        var extdatafromdbstr = JSON.stringify(extdatafromdb);
623
+
624
+                        if (extdatafromdbstr.length > 0) {
625
+
626
+                            localDB.setItem("externalUserConfElem", extdatafromdb.length);
627
+
628
+                            for (var t = 0; t < extdatafromdb.length; t++) {
629
+				 localDB.setItem("extUserExtension-"+t, extdatafromdb[t]['exten_for_external']);
630
+                                 localDB.setItem("extUserExtensionPass-"+t, extdatafromdb[t]['exten_for_ext_pass']);
631
+                                 localDB.setItem("confAccessLink-"+t, extdatafromdb[t]['conf_access_link']);
632
+                            }
633
+                        }
634
+                      },
635
+             error: function(extdatafromdb) {
636
+                           alert("An error occurred while attempting to retrieve external users configuration data from the database!");
637
+             }
638
+         });
639
+}
640
+
641
+// Check if there are any links for external access associated with the current username
642
+function checkExternalLinks() {
643
+
644
+        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.")) {
645
+
646
+             $.ajax({
647
+                 type: "POST",
648
+                 url: "remove-links-for-external-access.php",
649
+                 dataType: "JSON",
650
+                 data: {
651
+                        username: userName,
652
+                        s_ajax_call: validateSToken
653
+                       },
654
+                 success: function(response) {
655
+                            alert("All the links for external access to conferences associated with your username have been successfully removed from the database!");
656
+
657
+		            Unregister();
658
+			    console.log("Signing Out ...");
659
+			    localStorage.clear();
660
+			    if (winVideoConf != null) {
661
+			        winVideoConf.close();
662
+			    }
663
+			    window.open('https://' + window.location.host + '/logout.php', '_self');
664
+                 },
665
+                 error: function(response) {
666
+                            alert("An error occurred while trying to remove the data from the database!");
667
+
668
+		            Unregister();
669
+			    console.log("Signing Out ...");
670
+			    localStorage.clear();
671
+			    if (winVideoConf != null) {
672
+			        winVideoConf.close();
673
+			    }
674
+			    window.open('https://' + window.location.host + '/logout.php', '_self');
675
+                 }
676
+             });
677
+
678
+        } else {
679
+                 Unregister();
680
+		 console.log("Signing Out ...");
681
+		 localStorage.clear();
682
+		 if (winVideoConf != null) {
683
+		     winVideoConf.close();
684
+		 }
685
+		 window.open('https://' + window.location.host + '/logout.php', '_self');
686
+        }
687
+}
688
+
689
+// Remove contact from SQL database
690
+function deleteBuddyFromSqldb(buddyDisplayName) {
691
+
692
+          $.ajax({
693
+             type: "POST",
694
+             url: "remove-contact.php",
695
+             dataType: "JSON",
696
+             data: {
697
+                     username: userName,
698
+                     contact_name: buddyDisplayName,
699
+                     s_ajax_call: validateSToken
700
+             },
701
+             success: function(delresult) {
702
+             },
703
+             error: function(delresult) {
704
+                        alert("An error occurred while attempting to remove the contact from the database!");
705
+             }
706
+          });
707
+}
708
+
709
+// Save new Roundpin user password
710
+function saveNewUserPassword() {
711
+
712
+      var currentPassword = $("#Current_User_Password").val();
713
+      var newPassword = $("#New_User_Password").val();
714
+      var repeatPassword = $("#Repeat_New_User_Password").val();
715
+
716
+      if (currentPassword == '' || newPassword == '' || repeatPassword == '') { alert("Please fill in all the fields!"); return; }
717
+
718
+      // Verify if the new password meets constraints
719
+      if (/^((?=.*\d)(?=.*[a-z])(?=.*\W).{10,})$/.test(newPassword)) {
720
+
721
+          if (repeatPassword == newPassword) {
722
+		  $.ajax({
723
+		     type: "POST",
724
+		     url: "save-new-user-password.php",
725
+		     dataType: "JSON",
726
+		     data: {
727
+		             username: userName,
728
+		             current_password: currentPassword,
729
+                             new_password: newPassword,
730
+		             s_ajax_call: validateSToken
731
+		     },
732
+		     success: function(passchangemessage) {
733
+                                       alert(passchangemessage);
734
+		     },
735
+		     error: function(passchangemessage) {
736
+		                alert("An error occurred while attempting to change the user password!");
737
+		     }
738
+		  });
739
+          } else { alert("The passwords entered in the new password fields don't match!"); }
740
+
741
+      } else {
742
+          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 ! ");
743
+        }
744
+}
745
+
746
+// Save new Roundpin user email
747
+function saveNewUserEmail() {
748
+
749
+      var currentEmail = $("#Current_User_Email").val();
750
+      var newEmail = $("#New_User_Email").val();
751
+      var repeatEmail = $("#Repeat_New_User_Email").val();
752
+
753
+      if (currentEmail == '' || newEmail == '' || repeatEmail == '') { alert("Please fill in all the fields!"); return; }
754
+
755
+      // Verify if the new email is a valid email address
756
+      if (/^[A-Za-z0-9\_\.\-\~\%\+\!\?\&\*\^\=\#\$\{\}\|\/]+@[A-Za-z0-9\.\-]+\.[A-Za-z0-9\-]{2,63}$/.test(newEmail)) {
757
+
758
+          if (repeatEmail == newEmail) {
759
+		  $.ajax({
760
+		     type: "POST",
761
+		     url: "save-new-user-email.php",
762
+		     dataType: "JSON",
763
+		     data: {
764
+		             username: userName,
765
+		             current_email: currentEmail,
766
+                             new_email: newEmail,
767
+		             s_ajax_call: validateSToken
768
+		     },
769
+		     success: function(emailchangemessage) {
770
+                                       alert(emailchangemessage);
771
+		     },
772
+		     error: function(emailchangemessage) {
773
+		                alert("An error occurred while attempting to change the user email address!");
774
+		     }
775
+		  });
776
+          } else { alert("The email addresses entered in the new email fields don't match!"); }
777
+
778
+      } else {
779
+            alert("The new email address is not a valid email address. Please enter a valid email address!");
780
+        }
781
+}
782
+
783
+// Close Roundpin user account
784
+function closeUserAccount() {
785
+
786
+      closeVideoAudio();
787
+
788
+      ConfirmConfigExtWindow(lang.confirm_close_account, lang.close_roundpin_user_account, function() {
789
+
790
+		  $.ajax({
791
+		     type: "POST",
792
+		     url: "close-user-account.php",
793
+		     dataType: "JSON",
794
+		     data: {
795
+		             username: userName,
796
+		             s_ajax_call: validateSToken
797
+		     },
798
+		     success: function(closeaccountmessage) {
799
+                                       alert(closeaccountmessage);
800
+                                       SignOut();
801
+		     },
802
+		     error: function(closeaccountmessage) {
803
+		                alert("An error occurred while attempting to close your user account!");
804
+		     }
805
+		  });
806
+      });
807
+}
808
+
809
+// Launch video conference
810
+function LaunchVideoConference() {
811
+     if (winVideoConfCheck == 0) {
812
+	    winVideoConf = window.open('https://' + window.location.host + '/videoconference/index.php');
813
+	    winVideoConfCheck = 1;
814
+     } else { alert("The video conference has been launched. If you want to launch it again refresh the page, then click \"Launch Video Conference\"."); }
815
+}
816
+// Generate a new text chat key
817
+function generateChatRSAKeys(currentSIPusername) {
818
+
819
+          var crypto = new JSEncrypt({default_key_size: 1024});
820
+          crypto.getKey();
821
+          var currentChatPubKey = crypto.getPublicKey();
822
+          currentChatPrivKey = crypto.getPrivateKey();
823
+
824
+	  $.ajax({
825
+	     type: "POST",
826
+	     url: "save-text-chat-pub-key.php",
827
+	     dataType: "JSON",
828
+	     data: {
829
+	             currentextension: currentSIPusername,
830
+                     currentchatpubkey: currentChatPubKey,
831
+	             s_ajax_call: validateSToken
832
+	     },
833
+	     success: function() {
834
+	     },
835
+	     error: function() {
836
+	                alert("An error occurred while trying to save the new text chat public key!");
837
+	     }
838
+	  });
839
+}
840
+
841
+// Remove the 'uploads' directory used to temporarily store files received during text chat
842
+function removeTextChatUploads(currentSIPUser) {
843
+	$.ajax({
844
+             'async': false,
845
+             'global': false,
846
+	     type: "POST",
847
+	     url: "text-chat-remove-uploaded-files.php",
848
+	     dataType: "JSON",
849
+	     data: {
850
+		     sipusername: currentSIPUser,
851
+		     s_ajax_call: validateSToken
852
+	     },
853
+	     success: function(resresult) {
854
+                          if (resresult.note != 'success') {
855
+                              alert("An error occurred while trying to remove the text chat 'uploads' directory!");
856
+                          }
857
+             },
858
+             error: function(resresult) {
859
+                              alert("An error occurred while attempting to remove the text chat 'uploads' directory!");
860
+             }
861
+        });
862
+}
863
+// On page reload, close the video conference tab if it is opened
864
+function closeVideoConfTab() {
865
+         if (winVideoConf) { winVideoConf.close(); }
866
+}
867
+
868
+// Show Email window
869
+function ShowEmailWindow() {
870
+
871
+   if (getDbItem("useRoundcube", "") == 1) {
872
+
873
+      $("#roundcubeFrame").remove();
874
+      $("#rightContent").show();
875
+      $(".streamSelected").each(function() { $(this).css("display", "none"); });
876
+      $("#rightContent").append('<iframe id="roundcubeFrame" name="displayFrame"></iframe>');
877
+
878
+      var rcDomain = '';
879
+      var rcBasicAuthUser = '';
880
+      var rcBasicAuthPass = '';
881
+      var rcUsername = '';
882
+      var rcPasswd = '';
883
+
884
+      $.ajax({
885
+             'async': false,
886
+             'global': false,
887
+             type: "POST",
888
+             url: "get-email-info.php",
889
+             dataType: "JSON",
890
+             data: {
891
+                     username: userName,
892
+                     s_ajax_call: validateSToken
893
+             },
894
+             success: function(datafromdb) {
895
+                               rcDomain = datafromdb.rcdomain;
896
+                               rcBasicAuthUser = encodeURIComponent(datafromdb.rcbasicauthuser);
897
+                               rcBasicAuthPass = encodeURIComponent(datafromdb.rcbasicauthpass);
898
+                               rcUsername = datafromdb.rcuser;
899
+                               rcPasswd = datafromdb.rcpassword;
900
+             },
901
+             error: function(datafromdb) {
902
+                             alert("An error occurred while trying to retrieve data from the database!");
903
+             }
904
+      });
905
+
906
+      if (rcBasicAuthUser != '' && rcBasicAuthPass != '') { 
907
+          var actionURL = "https://"+ rcBasicAuthUser +":"+ rcBasicAuthPass +"@"+ rcDomain +"/"; 
908
+      } else { var actionURL = "https://"+ rcDomain +"/"; }
909
+
910
+      var form = '<form id="rcForm" method="POST" action="'+ actionURL +'" target="displayFrame">'; 
911
+      form += '<input type="hidden" name="_action" value="login" />';
912
+      form += '<input type="hidden" name="_task" value="login" />';
913
+      form += '<input type="hidden" name="_autologin" value="1" />';
914
+      form += '<input name="_user" value="'+ rcUsername +'" type="text" />';
915
+      form += '<input name="_pass" value="'+ rcPasswd +'" type="password" />';
916
+      form += '<input id="submitButton" type="submit" value="Login" />';
917
+      form += '</form>';
918
+
919
+      $("#roundcubeFrame").append(form);
920
+
921
+      if (RCLoginCheck == 0) {
922
+          $("#submitButton").click();
923
+          RCLoginCheck = 1;
924
+      } else { $("#roundcubeFrame").attr("src", actionURL); }
925
+
926
+   } 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'"); }
927
+}
928
+// Shrink the left panel
929
+function CollapseLeftPanel() {
930
+    if ($(window).width() >= 920) {
931
+        if ($("#leftContent").hasClass("shrinkLeftContent")) {
932
+            $("#leftContent").removeClass("shrinkLeftContent");
933
+            $("#rightContent").removeClass("widenRightContent");
934
+            $('#aboutImg').css("margin-right", "-3px");
935
+        } else {
936
+            $("#leftContent").addClass("shrinkLeftContent");
937
+            $("#rightContent").addClass("widenRightContent");
938
+            $('#aboutImg').css("margin-right", "3px");
939
+        }
940
+    }
941
+}
942
+// Show the 'About' window
943
+function ShowAboutWindow() {
944
+
945
+   $.jeegoopopup.close();
946
+   var aboutHtml = '<div>';
947
+   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>';
948
+   aboutHtml += '<div class="UiWindowField scroller">';
949
+   aboutHtml += '<div><img id="AboutLogoImg" src="images/login-logo.svg"/></div>';
950
+   aboutHtml += '<div id="aboutPopup">'+lang.about_text+'</div>';
951
+   aboutHtml += '</div></div>';
952
+
953
+   $.jeegoopopup.open({
954
+                title: 'About Roundpin',
955
+                html: aboutHtml,
956
+                width: '640',
957
+                height: '500',
958
+                center: true,
959
+                scrolling: 'no',
960
+                skinClass: 'jg_popup_basic',
961
+                overlay: true,
962
+                opacity: 50,
963
+                draggable: true,
964
+                resizable: false,
965
+                fadeIn: 0
966
+   });
967
+
968
+   $("#jg_popup_b").append('<button id="ok_button">'+ lang.ok +'</button>');
969
+
970
+   var maxWidth = $(window).width() - 12;
971
+   var maxHeight = $(window).height() - 88;
972
+
973
+   if (maxWidth < 656 || maxHeight < 500) { 
974
+       $.jeegoopopup.width(maxWidth).height(maxHeight);
975
+       $.jeegoopopup.center();
976
+       $("#maximizeImg").hide();
977
+       $("#minimizeImg").hide();
978
+   } else { 
979
+       $.jeegoopopup.width(640).height(500);
980
+       $.jeegoopopup.center();
981
+       $("#minimizeImg").hide();
982
+       $("#maximizeImg").show();
983
+   }
984
+
985
+   $(window).resize(function() {
986
+       maxWidth = $(window).width() - 12;
987
+       maxHeight = $(window).height() - 88;
988
+
989
+       $.jeegoopopup.center();
990
+       if (maxWidth < 656 || maxHeight < 500) { 
991
+           $.jeegoopopup.width(maxWidth).height(maxHeight);
992
+           $.jeegoopopup.center();
993
+           $("#maximizeImg").hide();
994
+           $("#minimizeImg").hide();
995
+       } else { 
996
+           $.jeegoopopup.width(640).height(500);
997
+           $.jeegoopopup.center();
998
+           $("#minimizeImg").hide();
999
+           $("#maximizeImg").show();
1000
+       }
1001
+   });
1002
+
1003
+   
1004
+   $("#minimizeImg").click(function() { $.jeegoopopup.width(640).height(500); $.jeegoopopup.center(); $("#maximizeImg").show(); $("#minimizeImg").hide(); });
1005
+   $("#maximizeImg").click(function() { $.jeegoopopup.width(maxWidth).height(maxHeight); $.jeegoopopup.center(); $("#minimizeImg").show(); $("#maximizeImg").hide(); });
1006
+
1007
+   $("#closeImg").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
1008
+   $("#ok_button").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
1009
+   $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
1010
+   $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); $("#jg_popup_b").empty(); } });
1011
+}
1012
+
1013
+// Show system notifications on incoming calls
1014
+function incomingCallNote() {
1015
+   var incomingCallNotify = new Notification(lang.incomming_call, { icon: "../images/notification-logo.svg", body: "New incoming call !!!" });
1016
+   incomingCallNotify.onclick = function (event) {
1017
+       return;
1018
+   };
1019
+
1020
+   if (document.hasFocus()) {
1021
+       return;
1022
+   } else { setTimeout(incomingCallNote, 8000); }
1023
+}
1024
+
1025
+// Change page title on incoming calls
1026
+function changePageTitle() {
1027
+    if ($(document).attr("title") == "Roundpin") { $(document).prop("title", "New call !!!"); } else { $(document).prop("title", "Roundpin"); }
1028
+    if (document.hasFocus()) {
1029
+        $(document).prop("title", "Roundpin");
1030
+        return;
1031
+    } else { setTimeout(changePageTitle, 460); }
1032
+}
1033
+
1034
+// Window and Document Events
1035
+// ==========================
1036
+$(window).on("beforeunload", function() {
1037
+    Unregister();
1038
+});
1039
+$(window).on("resize", function() {
1040
+    UpdateUI();
1041
+});
1042
+
1043
+// User Interface
1044
+// ==============
1045
+function UpdateUI(){
1046
+    if($(window).outerWidth() < 920){
1047
+        // Narrow Layout
1048
+        if(selectedBuddy == null & selectedLine == null) {
1049
+            // Nobody Selected
1050
+            $("#rightContent").hide();
1051
+
1052
+            $("#leftContent").css("width", "100%");
1053
+            $("#leftContent").show();
1054
+        }
1055
+        else {
1056
+            $("#rightContent").css("margin-left", "0px");
1057
+            $("#rightContent").show();
1058
+
1059
+            $("#leftContent").hide();
1060
+
1061
+            if(selectedBuddy != null) updateScroll(selectedBuddy.identity);
1062
+        }
1063
+    }
1064
+    else {
1065
+        // Wide Screen Layout
1066
+        if(selectedBuddy == null & selectedLine == null) {
1067
+            $("#leftContent").css("width", "320px");
1068
+            $("#rightContent").css("margin-left", "0px");
1069
+            $("#leftContent").show();
1070
+            $("#rightContent").hide();
1071
+        }
1072
+        else{
1073
+            $("#leftContent").css("width", "320px");
1074
+            $("#rightContent").css("margin-left", "320px");
1075
+            $("#leftContent").show();
1076
+            $("#rightContent").show();
1077
+
1078
+            if(selectedBuddy != null) updateScroll(selectedBuddy.identity);
1079
+        }
1080
+    }
1081
+    for(var l=0; l<Lines.length; l++){
1082
+        updateLineScroll(Lines[l].LineNumber);
1083
+    }
1084
+}
1085
+
1086
+// UI Windows
1087
+// ==========
1088
+function AddSomeoneWindow(numberStr){
1089
+
1090
+    $("#userMenu").hide();
1091
+    $.jeegoopopup.close();
1092
+
1093
+    var html = "<div id='AddNewContact'>";
1094
+
1095
+    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>";
1096
+
1097
+    html += "<div class='UiWindowField scroller'>";
1098
+
1099
+    html += "<div class=UiText>"+ lang.display_name +":</div>";
1100
+    html += "<div><input id=AddSomeone_Name class=UiInputText type=text placeholder='"+ lang.eg_display_name +"'></div>";
1101
+
1102
+    html += "<div class=UiText>"+ lang.title_description +":</div>";
1103
+    html += "<div><input id=AddSomeone_Desc class=UiInputText type=text placeholder='"+ lang.eg_general_manager +"'></div>";
1104
+
1105
+    html += "<div class=UiText>"+ lang.internal_subscribe_extension +":</div>";
1106
+    if(numberStr && numberStr.length > 1 && numberStr.length < DidLength && numberStr.substring(0,1) != "*"){
1107
+        html += "<div><input id=AddSomeone_Exten class=UiInputText type=text value="+ numberStr +" placeholder='"+ lang.eg_internal_subscribe_extension +"'></div>";
1108
+    }
1109
+    else{
1110
+        html += "<div><input id=AddSomeone_Exten class=UiInputText type=text placeholder='"+ lang.eg_internal_subscribe_extension +"'></div>";
1111
+    }
1112
+
1113
+    html += "<div class=UiText>"+ lang.mobile_number +":</div>";
1114
+    html += "<div><input id=AddSomeone_Mobile class=UiInputText type=text placeholder='"+ lang.eg_mobile_number +"'></div>";
1115
+
1116
+    html += "<div class=UiText>"+ lang.contact_number_1 +":</div>";
1117
+    if(numberStr && numberStr.length > 1){
1118
+        html += "<div><input id=AddSomeone_Num1 class=UiInputText type=text value="+ numberStr +" placeholder='"+ lang.eg_contact_number_1 +"'></div>";
1119
+    }
1120
+    else {
1121
+        html += "<div><input id=AddSomeone_Num1 class=UiInputText type=text placeholder='"+ lang.eg_contact_number_1 +"'></div>";
1122
+    }
1123
+
1124
+    html += "<div class=UiText>"+ lang.contact_number_2 +":</div>";
1125
+    html += "<div><input id=AddSomeone_Num2 class=UiInputText type=text placeholder='"+ lang.eg_contact_number_2 +"'></div>";
1126
+
1127
+    html += "<div class=UiText>"+ lang.email +":</div>";
1128
+    html += "<div><input id=AddSomeone_Email class=UiInputText type=text placeholder='"+ lang.eg_email +"'></div>";
1129
+
1130
+    html += "</div></div>"
1131
+
1132
+    $.jeegoopopup.open({
1133
+                title: 'Add Contact',
1134
+                html: html,
1135
+                width: '640',
1136
+                height: '500',
1137
+                center: true,
1138
+                scrolling: 'no',
1139
+                skinClass: 'jg_popup_basic',
1140
+                contentClass: 'addContactPopup',
1141
+                overlay: true,
1142
+                opacity: 50,
1143
+                draggable: true,
1144
+                resizable: false,
1145
+                fadeIn: 0
1146
+    });
1147
+
1148
+    $("#jg_popup_b").append("<div id=bottomButtons><button id=save_button>Save</button><button id=cancel_button>Cancel</button></div>");
1149
+
1150
+    $("#save_button").click(function() {
1151
+
1152
+      var currentASName = $("#AddSomeone_Name").val();
1153
+
1154
+      if (currentASName != null && currentASName.trim() !== '') {
1155
+
1156
+        if (/^[A-Za-z0-9\s\-\'\[\]\(\)]+$/.test(currentASName)) {
1157
+
1158
+	   var currentDesc = $("#AddSomeone_Desc").val();
1159
+	   if (currentDesc != null && currentDesc.trim() !== '') {
1160
+	       if (/^[A-Za-z0-9\s\-\.\'\"\[\]\(\)\{\}\_\!\?\~\@\%\^\&\*\+\>\<\;\:\=]+$/.test(currentDesc)) { var finCurrentDesc = currentDesc; } else { 
1161
+		   var finCurrentDesc = ''; alert('The title/description that you entered is not valid!'); }
1162
+	   } else { var finCurrentDesc = ''; }
1163
+
1164
+	   var currentExtension = $("#AddSomeone_Exten").val();
1165
+	   if (currentExtension != null && currentExtension.trim() !== '') {
1166
+	       if (/^[a-zA-Z0-9\*\#]+$/.test(currentExtension)) { var finCurrentExtension = currentExtension; } else { 
1167
+		   var finCurrentExtension = ''; alert("The extension that you entered in the 'Extension (Internal)' field is not a valid extension!"); }
1168
+	   } else { var finCurrentExtension = ''; }
1169
+
1170
+	   var currentMobile = $("#AddSomeone_Mobile").val();
1171
+	   if (currentMobile != null && currentMobile.trim() !== '') {
1172
+	       if (/^[0-9\s\+\#]+$/.test(currentMobile)) { var finCurrentMobile = currentMobile; } else {
1173
+		   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."); }
1174
+	   } else { var finCurrentMobile = ''; }
1175
+
1176
+	   var currentNum1 = $("#AddSomeone_Num1").val();
1177
+	   if (currentNum1 != null && currentNum1.trim() !== '') {
1178
+	       if (/^[0-9\s\+\#]+$/.test(currentNum1)) { var finCurrentNum1 = currentNum1; } else {
1179
+		   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."); }
1180
+	   } else { var finCurrentNum1 = ''; }
1181
+
1182
+	   var currentNum2 = $("#AddSomeone_Num2").val();
1183
+	   if (currentNum2 != null && currentNum2.trim() !== '') {
1184
+	       if (/^[0-9\s\+\#]+$/.test(currentNum2)) { var finCurrentNum2 = currentNum2; } else {
1185
+		   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."); }
1186
+           } else { var finCurrentNum2 = ''; }
1187
+
1188
+	   var currentEmail = $("#AddSomeone_Email").val();
1189
+	   if (currentEmail != null && currentEmail.trim() !== '') {
1190
+	       if (/^[A-Za-z0-9\_\.\-\~\%\+\!\?\&\*\^\=\#\$\{\}\|\/]+@[A-Za-z0-9\.\-]+\.[A-Za-z0-9\-]{2,63}$/.test(currentEmail)) { var finCurrentEmail = currentEmail; } else {
1191
+		   var finCurrentEmail = ''; alert("The email that you entered is not a valid email address!"); }
1192
+	   } else { var finCurrentEmail = ''; }
1193
+
1194
+
1195
+           // Add Contact / Extension
1196
+           var json = JSON.parse(localDB.getItem(profileUserID + "-Buddies"));
1197
+           if(json == null) json = InitUserBuddies();
1198
+
1199
+           if(finCurrentExtension == ''){
1200
+               // Add Regular Contact
1201
+               var id = uID();
1202
+               var dateNow = utcDateNow();
1203
+               json.DataCollection.push(
1204
+                   {
1205
+                    Type: "contact",
1206
+                    LastActivity: dateNow,
1207
+                    ExtensionNumber: "",
1208
+                    MobileNumber: finCurrentMobile,
1209
+                    ContactNumber1: finCurrentNum1,
1210
+                    ContactNumber2: finCurrentNum2,
1211
+                    uID: null,
1212
+                    cID: id,
1213
+                    gID: null,
1214
+                    DisplayName: currentASName,
1215
+                    Position: "",
1216
+                    Description: finCurrentDesc,
1217
+                    Email: finCurrentEmail,
1218
+                    MemberCount: 0
1219
+                   }
1220
+               );
1221
+               var newPerson = [];
1222
+               newPerson = [currentASName, finCurrentDesc, "", finCurrentMobile, finCurrentNum1, finCurrentNum2, finCurrentEmail];
1223
+               saveContactToSQLDB(newPerson);
1224
+
1225
+               var buddyObj = new Buddy("contact", id, currentASName, "", finCurrentMobile, finCurrentNum1, finCurrentNum2, dateNow, finCurrentDesc, finCurrentEmail);
1226
+               AddBuddy(buddyObj, false, false, false);
1227
+
1228
+           } else {
1229
+               // Add Extension
1230
+               var id = uID();
1231
+               var dateNow = utcDateNow();
1232
+               json.DataCollection.push(
1233
+                   {
1234
+                    Type: "extension",
1235
+                    LastActivity: dateNow,
1236
+                    ExtensionNumber: finCurrentExtension,
1237
+                    MobileNumber: finCurrentMobile,
1238
+                    ContactNumber1: finCurrentNum1,
1239
+                    ContactNumber2: finCurrentNum2,
1240
+                    uID: id,
1241
+                    cID: null,
1242
+                    gID: null,
1243
+                    DisplayName: currentASName,
1244
+                    Position: finCurrentDesc,
1245
+                    Description: "",
1246
+                    Email: finCurrentEmail,
1247
+                    MemberCount: 0
1248
+                   }
1249
+               );
1250
+
1251
+               var newPerson = [];
1252
+
1253
+               newPerson = [currentASName, finCurrentDesc, finCurrentExtension, finCurrentMobile, finCurrentNum1, finCurrentNum2, finCurrentEmail];
1254
+               saveContactToSQLDB(newPerson);
1255
+
1256
+               var buddyObj = new Buddy("extension", id, currentASName, finCurrentExtension, finCurrentMobile, finCurrentNum1, finCurrentNum2, dateNow, finCurrentDesc, finCurrentEmail);
1257
+               AddBuddy(buddyObj, false, false, true);
1258
+
1259
+           }
1260
+           // Update Size:
1261
+           json.TotalRows = json.DataCollection.length;
1262
+
1263
+           // Save To Local DB
1264
+           localDB.setItem(profileUserID + "-Buddies", JSON.stringify(json));
1265
+           UpdateBuddyList();
1266
+
1267
+           $.jeegoopopup.close();
1268
+           $("#jg_popup_b").empty();
1269
+
1270
+        } else { alert('The display name that you entered is not a valid display name!'); }
1271
+
1272
+      } else { alert("'Display Name' cannot be empty!"); }
1273
+       
1274
+   });
1275
+
1276
+   var maxWidth = $(window).width() - 12;
1277
+   var maxHeight = $(window).height() - 110;
1278
+
1279
+   if (maxWidth < 656 || maxHeight < 500) { 
1280
+       $.jeegoopopup.width(maxWidth).height(maxHeight);
1281
+       $.jeegoopopup.center();
1282
+       $("#maximizeImg").hide();
1283
+       $("#minimizeImg").hide();
1284
+   } else { 
1285
+       $.jeegoopopup.width(640).height(500);
1286
+       $.jeegoopopup.center();
1287
+       $("#minimizeImg").hide();
1288
+       $("#maximizeImg").show();
1289
+   }
1290
+
1291
+   $(window).resize(function() {
1292
+       maxWidth = $(window).width() - 16;
1293
+       maxHeight = $(window).height() - 110;
1294
+       $.jeegoopopup.center();
1295
+       if (maxWidth < 656 || maxHeight < 500) { 
1296
+           $.jeegoopopup.width(maxWidth).height(maxHeight);
1297
+           $.jeegoopopup.center();
1298
+           $("#maximizeImg").hide();
1299
+           $("#minimizeImg").hide();
1300
+       } else { 
1301
+           $.jeegoopopup.width(640).height(500);
1302
+           $.jeegoopopup.center();
1303
+           $("#minimizeImg").hide();
1304
+           $("#maximizeImg").show();
1305
+       }
1306
+   });
1307
+
1308
+   $("#minimizeImg").click(function() { $.jeegoopopup.width(640).height(500); $.jeegoopopup.center(); $("#maximizeImg").show(); $("#minimizeImg").hide(); });
1309
+   $("#maximizeImg").click(function() { $.jeegoopopup.width(maxWidth).height(maxHeight); $.jeegoopopup.center(); $("#minimizeImg").show(); $("#maximizeImg").hide(); });
1310
+
1311
+   $("#closeImg").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
1312
+   $("#cancel_button").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
1313
+   $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
1314
+   $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); $("#jg_popup_b").empty(); } });
1315
+}
1316
+
1317
+function CreateGroupWindow(){
1318
+}
1319
+
1320
+function closeVideoAudio() {
1321
+
1322
+        var localVideo = $("#local-video-preview").get(0);
1323
+        try{
1324
+            var tracks = localVideo.srcObject.getTracks();
1325
+            tracks.forEach(function(track) {
1326
+                track.stop();
1327
+            });
1328
+            localVideo.srcObject = null;
1329
+        }
1330
+        catch(e){}
1331
+
1332
+        try{
1333
+            var tracks = window.SettingsMicrophoneStream.getTracks();
1334
+            tracks.forEach(function(track) {
1335
+                track.stop();
1336
+            });
1337
+        }
1338
+        catch(e){}
1339
+        window.SettingsMicrophoneStream = null;
1340
+
1341
+        try{
1342
+            var soundMeter = window.SettingsMicrophoneSoundMeter;
1343
+            soundMeter.stop();
1344
+        }
1345
+        catch(e){}
1346
+        window.SettingsMicrophoneSoundMeter = null;
1347
+
1348
+        try{
1349
+            window.SettingsOutputAudio.pause();
1350
+        }
1351
+        catch(e){}
1352
+        window.SettingsOutputAudio = null;
1353
+
1354
+        try{
1355
+            var tracks = window.SettingsOutputStream.getTracks();
1356
+            tracks.forEach(function(track) {
1357
+                track.stop();
1358
+            });
1359
+        }
1360
+        catch(e){}
1361
+        window.SettingsOutputStream = null;
1362
+
1363
+        try{
1364
+            var soundMeter = window.SettingsOutputStreamMeter;
1365
+            soundMeter.stop();
1366
+        }
1367
+        catch(e){}
1368
+        window.SettingsOutputStreamMeter = null;
1369
+
1370
+        return true;
1371
+}
1372
+function ConfigureExtensionWindow() {
1373
+
1374
+    $("#settingsCMenu").hide();
1375
+    $.jeegoopopup.close();
1376
+
1377
+    var configWindow = "<div id=\"mainConfWindow\">";
1378
+    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>"; 
1379
+    configWindow += "<div id=\"mainRightConf\">";
1380
+    configWindow += "<div id=\"rightMainConfWindow\">";
1381
+
1382
+    configWindow +=  "<div id=\"AccountHtml\" class=\"settingsSubSection\" style=\"display:block;\">";
1383
+    configWindow += "<div class=UiText>"+ lang.asterisk_server_address +": *</div>";
1384
+    configWindow += "<div><input id=Configure_Account_wssServer class=UiInputText type=text placeholder='"+ lang.eg_asterisk_server_address +"' value='"+ getDbItem("wssServer", "") +"'></div>";
1385
+    configWindow += "<div class=UiText>"+ lang.websocket_port +": *</div>";
1386
+    configWindow += "<div><input id=Configure_Account_WebSocketPort class=UiInputText type=text placeholder='"+ lang.eg_websocket_port +"' value='"+ getDbItem("WebSocketPort", "") +"'></div>";
1387
+    configWindow += "<div class=UiText>"+ lang.websocket_path +": *</div>";
1388
+    configWindow += "<div><input id=Configure_Account_ServerPath class=UiInputText type=text placeholder='"+ lang.eg_websocket_path +"' value='"+ getDbItem("ServerPath", "") +"'></div>";
1389
+    configWindow += "<div class=UiText>"+ lang.display_name +": *</div>";
1390
+
1391
+    var escapedDisplayName = 'value="' + getDbItem("profileName", "").replace("'","\'") + '"';
1392
+    configWindow += "<div><input id=Configure_Account_profileName class=UiInputText type=text placeholder='"+ lang.eg_display_name +"' "+ escapedDisplayName +"></div>";
1393
+    configWindow += "<div class=UiText>"+ lang.sip_username +": *</div>";
1394
+    configWindow += "<div><input id=Configure_Account_SipUsername class=UiInputText type=text placeholder='"+ lang.eg_sip_username +"' value='"+ getDbItem("SipUsername", "") +"'></div>";
1395
+    configWindow += "<div class=UiText>"+ lang.sip_password +": *</div>";
1396
+    configWindow += "<div><input id=Configure_Account_SipPassword class=UiInputText type=password placeholder='"+ lang.eg_sip_password +"' value='"+ getDbItem("SipPassword", "") +"'></div>";
1397
+    configWindow += "<div class=UiText>"+ lang.stun_server +":</div>";
1398
+    configWindow += "<div><input id=Configure_Account_StunServer class=UiInputText type=text placeholder='Eg: 123.123.123.123:8443' value='"+ getDbItem("StunServer", "") +"'></div>";
1399
+    configWindow += "<p style=\"color:#363636;\">* Required field.</p><br><br></div>";
1400
+
1401
+    configWindow += "<div id=\"AudioVideoHtml\" class=\"settingsSubSection\" style=\"display:none;\">";
1402
+    configWindow += "<div class=UiText>"+ lang.speaker +":</div>";
1403
+    configWindow += "<div style=\"text-align:center\"><select id=playbackSrc style=\"width:100%\"></select></div>";
1404
+    configWindow += "<div class=Settings_VolumeOutput_Container><div id=Settings_SpeakerOutput class=Settings_VolumeOutput></div></div>";
1405
+    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>";
1406
+
1407
+    configWindow += "<br><div class=UiText>"+ lang.ring_device +":</div>";
1408
+    configWindow += "<div style=\"text-align:center\"><select id=ringDevice style=\"width:100%\"></select></div>";
1409
+    configWindow += "<div class=Settings_VolumeOutput_Container><div id=Settings_RingerOutput class=Settings_VolumeOutput></div></div>";
1410
+    configWindow += "<div><button class=on_white id=preview_ringer_play><i class=\"fa fa-play\"></i></button></div>";
1411
+
1412
+    configWindow += "<br><div class=UiText>"+ lang.microphone +":</div>";
1413
+    configWindow += "<div style=\"text-align:center\"><select id=microphoneSrc style=\"width:100%\"></select></div>";
1414
+    configWindow += "<div class=Settings_VolumeOutput_Container><div id=Settings_MicrophoneOutput class=Settings_VolumeOutput></div></div>";
1415
+    configWindow += "<br><br><div><input type=checkbox id=Settings_AutoGainControl><label for=Settings_AutoGainControl> "+ lang.auto_gain_control +"<label></div>";
1416
+    configWindow += "<div><input type=checkbox id=Settings_EchoCancellation><label for=Settings_EchoCancellation> "+ lang.echo_cancellation +"<label></div>";
1417
+    configWindow += "<div><input type=checkbox id=Settings_NoiseSuppression><label for=Settings_NoiseSuppression> "+ lang.noise_suppression +"<label></div>";
1418
+    configWindow += "<br><div class=UiText>"+ lang.camera +":</div>";
1419
+    configWindow += "<div style=\"text-align:center\"><select id=previewVideoSrc style=\"width:100%\"></select></div>";
1420
+    configWindow += "<br><div class=UiText>"+ lang.frame_rate +":</div>"
1421
+    configWindow += "<div class=pill-nav>";
1422
+    configWindow += "<input name=Settings_FrameRate id=r40 type=radio value=\"2\"><label class=radio_pill for=r40>2</label>";
1423
+    configWindow += "<input name=Settings_FrameRate id=r41 type=radio value=\"5\"><label class=radio_pill for=r41>5</label>";
1424
+    configWindow += "<input name=Settings_FrameRate id=r42 type=radio value=\"10\"><label class=radio_pill for=r42>10</label>";
1425
+    configWindow += "<input name=Settings_FrameRate id=r43 type=radio value=\"15\"><label class=radio_pill for=r43>15</label>";
1426
+    configWindow += "<input name=Settings_FrameRate id=r44 type=radio value=\"20\"><label class=radio_pill for=r44>20</label>";
1427
+    configWindow += "<input name=Settings_FrameRate id=r45 type=radio value=\"25\"><label class=radio_pill for=r45>25</label>";
1428
+    configWindow += "<input name=Settings_FrameRate id=r46 type=radio value=\"30\"><label class=radio_pill for=r46>30</label>";
1429
+    configWindow += "<input name=Settings_FrameRate id=r47 type=radio value=\"\"><label class=radio_pill for=r47><i class=\"fa fa-trash\"></i></label>";
1430
+    configWindow += "</div>";
1431
+    configWindow += "<br><br><div class=UiText>"+ lang.quality +":</div>";
1432
+    configWindow += "<div class=pill-nav>";
1433
+    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>";
1434
+    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>";
1435
+    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>";
1436
+    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>";
1437
+    configWindow += "<input name=Settings_Quality id=r34 type=radio value=\"\"><label class=radio_pill for=r34><i class=\"fa fa-trash\"></i></label>";
1438
+    configWindow += "</div>";
1439
+    configWindow += "<br><br><div class=UiText>"+ lang.image_orientation +":</div>";
1440
+    configWindow += "<div class=pill-nav>";
1441
+    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>";
1442
+    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>";
1443
+    configWindow += "</div>";
1444
+    configWindow += "<br><br><div class=UiText>"+ lang.aspect_ratio +":</div>";
1445
+    configWindow += "<div class=pill-nav>";
1446
+    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>";
1447
+    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>";
1448
+    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>";
1449
+    configWindow += "<input name=Settings_AspectRatio id=r13 type=radio value=\"\"><label class=radio_pill for=r13><i class=\"fa fa-trash\"></i></label>";
1450
+    configWindow += "</div>";
1451
+    configWindow += "<br><br><div class=UiText>"+ lang.preview +":</div>";
1452
+    configWindow += "<div style=\"text-align:center; margin-top:10px\"><video id=\"local-video-preview\" class=\"previewVideo\"></video></div>";
1453
+    configWindow += "<br><div class=UiText>"+ lang.video_conference_extension +":</div>";
1454
+    configWindow += "<div><input id=Video_Conf_Extension class=UiInputText type=text placeholder='"+ lang.video_conference_extension_example +"' value='"+ getDbItem("VidConfExtension", "") +"'></div>";
1455
+    configWindow += "<br><div class=UiText>"+ lang.video_conference_window_width +":</div>";
1456
+    configWindow += "<div><input id=Video_Conf_Window_Width class=UiInputText type=text placeholder='"+ lang.video_conf_window_width_explanation +"' value='"+ getDbItem("VidConfWindowWidth", "") +"'></div>";
1457
+    if (getDbItem("userrole", "") == "superadmin") {
1458
+
1459
+	configWindow += "<div id=confTableSection>"+ lang.external_conf_users +"</div>";
1460
+        configWindow += "<div class=confTable><table id=vidConfExternalTable>";
1461
+        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>";
1462
+
1463
+        for (var cqt = 0; cqt < getDbItem("externalUserConfElem", ""); cqt++) {
1464
+	     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>";
1465
+        }
1466
+
1467
+	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>";
1468
+        configWindow += "</table></div>";
1469
+	configWindow += "<button id=add_New_External_User>Add External User</button>";
1470
+    }
1471
+    configWindow += "<br><br></div>";
1472
+
1473
+    configWindow += "<div id=\"AppearanceHtml\" class=\"settingsSubSection\" style=\"display:none;\">";
1474
+    configWindow += "<div id=ImageCanvas style=\"width:150px; height:150px;\"></div>";
1475
+    configWindow += "<label for=fileUploader class=customBrowseButton style=\"margin-left: 200px; margin-top: -2px;\">Select File</label>";
1476
+    configWindow += "<div><input id=fileUploader type=file></div>";
1477
+    configWindow += "<div style=\"margin-top: 50px\"></div>";
1478
+    configWindow += "</div>";
1479
+
1480
+    configWindow += "<div id=\"NotificationsHtml\" class=\"settingsSubSection\" style=\"display:none;\">";
1481
+    configWindow += "<div class=UiText>"+ lang.notifications +":</div>";
1482
+    configWindow += "<div id=\"notificationsCheck\"><input type=checkbox id=Settings_Notifications><label for=Settings_Notifications> "+ lang.enable_onscreen_notifications +"<label></div>";
1483
+    configWindow += "</div>";
1484
+
1485
+    configWindow += "<div id=\"RoundcubeEmailHtml\" class=\"settingsSubSection\" style=\"display:none;\">";
1486
+    configWindow += "<div class=UiText>"+ lang.email_integration +":</div>";
1487
+    configWindow += "<div id=\"enableRCcheck\"><input id=emailIntegration type=checkbox ><label for=emailIntegration> "+ lang.enable_roundcube_integration +"<label></div>";
1488
+    configWindow += "<div class=UiText>"+ lang.roundcube_domain +":</div>";
1489
+    configWindow += "<div><input id=RoundcubeDomain class=UiInputText type=text placeholder='Roundcube domain (Eg: mail.example.com).' value='"+ getDbItem("rcDomain", "") +"'></div>";
1490
+    configWindow += "<div class=UiText>"+ lang.roundcube_user +":</div>";
1491
+    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>";
1492
+    configWindow += "<div class=UiText>"+ lang.roundcube_password +":</div>";
1493
+    configWindow += "<div><input id=RoundcubePass class=UiInputText type=password placeholder='Roundcube login password.' value='"+ getDbItem("RoundcubePass", "") +"'></div>";
1494
+    configWindow += "<div class=UiText>"+ lang.rc_basic_auth_user +":</div>";
1495
+    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>";
1496
+    configWindow += "<div class=UiText>"+ lang.rc_basic_auth_password +":</div>";
1497
+    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>";
1498
+
1499
+    configWindow += "<br><br></div>";
1500
+
1501
+    configWindow += "<div id=\"ChangePasswordHtml\" class=\"settingsSubSection\" style=\"display:none;\">";
1502
+    configWindow += "<div class=UiText>"+ lang.current_user_password +":</div>";
1503
+    configWindow += "<div><input id=Current_User_Password class=UiInputText type=password placeholder='Enter your current Roundpin user password.' value=''></div>";
1504
+    configWindow += "<div class=UiText>"+ lang.new_user_password +":</div>";
1505
+    configWindow += "<div><input id=New_User_Password class=UiInputText type=password placeholder='Enter your new Roundpin user password.' value=''></div>";
1506
+    configWindow += "<div class=UiText>"+ lang.repeat_new_user_password +":</div>";
1507
+    configWindow += "<div><input id=Repeat_New_User_Password class=UiInputText type=password placeholder='Enter your new Roundpin user password again.' value=''></div><br>";
1508
+    configWindow += "<div><input id=Save_New_User_Password type=button value='Save New Password' onclick='saveNewUserPassword()' ></div>";
1509
+    configWindow += "<br><br></div>";
1510
+
1511
+    configWindow += "<div id=\"ChangeEmailHtml\" class=\"settingsSubSection\" style=\"display:none;\">";
1512
+    configWindow += "<div class=UiText>"+ lang.current_user_email +":</div>";
1513
+    configWindow += "<div><input id=Current_User_Email class=UiInputText type=text placeholder='Enter your current Roundpin email address.' value=''></div>";
1514
+    configWindow += "<div class=UiText>"+ lang.new_user_email +":</div>";
1515
+    configWindow += "<div><input id=New_User_Email class=UiInputText type=text placeholder='Enter your new email address.' value=''></div>";
1516
+    configWindow += "<div class=UiText>"+ lang.repeat_new_user_email +":</div>";
1517
+    configWindow += "<div><input id=Repeat_New_User_Email class=UiInputText type=text placeholder='Enter your new email address again.' value=''></div><br>";
1518
+    configWindow += "<div><input id=Save_New_User_Email type=button value='Save New Email' onclick='saveNewUserEmail()' ></div>";
1519
+    configWindow += "<br><br></div>";
1520
+
1521
+    configWindow += "<div id=\"CloseAccountHtml\" class=\"settingsSubSection\" style=\"display:none;\">";
1522
+    configWindow += "<div class=UiText>"+ lang.if_you_want_to_close_account +":</div><br><br>";
1523
+    configWindow += "<div><input id=Close_User_Account type=button value='Close User Account' onclick='closeUserAccount()' ></div>";
1524
+    configWindow += "<br><br></div>";
1525
+
1526
+    configWindow += "</div></div></div>";
1527
+
1528
+    var settingsSections = "<table id=leftPanelSettings cellspacing=14 cellpadding=0 style=\"width:184px;margin-left:8px;margin-top:14px;font-size:15px;\">";
1529
+    settingsSections += "<tr id=ConnectionSettingsRow><td class=SettingsSection>Connection Settings</td></tr>";
1530
+    settingsSections += "<tr id=AudioAndVideoRow><td class=SettingsSection>Audio & Video</td></tr>";
1531
+    settingsSections += "<tr id=ProfilePictureRow><td class=SettingsSection>Profile Picture</td></tr>";
1532
+    settingsSections += "<tr id=NotificationsRow><td class=SettingsSection>Notifications</td></tr>";
1533
+    settingsSections += "<tr id=RoundcubeEmailRow><td class=SettingsSection>Email Integration</td></tr>";
1534
+    settingsSections += "<tr id=ChangePasswordRow><td class=SettingsSection>Change Password</td></tr>";
1535
+    settingsSections += "<tr id=ChangeEmailRow><td class=SettingsSection>Change Email</td></tr>";
1536
+    settingsSections += "<tr id=CloseAccountRow><td class=SettingsSection>Close Account</td></tr></table>";
1537
+
1538
+    $.jeegoopopup.open({
1539
+                title: '<span id=settingsTitle>Settings</span>',
1540
+                html: configWindow,
1541
+                width: '520',
1542
+                height: '500',
1543
+                center: true,
1544
+                scrolling: 'no',
1545
+                skinClass: 'jg_popup_basic',
1546
+                contentClass: 'configPopup',
1547
+                overlay: true,
1548
+                opacity: 50,
1549
+                draggable: true,
1550
+                resizable: false,
1551
+                fadeIn: 0
1552
+    });
1553
+
1554
+    $("#jg_popup_b").append('<div id="bottomButtonsConf"><button id="save_button_conf">Save</button><button id="cancel_button_conf">Cancel</button></div>');
1555
+    $("#jg_popup_l").append(settingsSections);
1556
+
1557
+    if (getDbItem("useRoundcube", "") == 1) { $("#emailIntegration").prop("checked", true); } else { $("#emailIntegration").prop("checked", false); }
1558
+
1559
+    $("#ConnectionSettingsRow td").addClass("selectedSettingsSection");
1560
+
1561
+    $("#ConnectionSettingsRow").click(function() {
1562
+        $(".settingsSubSection").each(function() { $(this).css("display", "none"); });
1563
+        $("#AccountHtml").css("display", "block");
1564
+        $(".SettingsSection").each(function() { $(this).removeClass("selectedSettingsSection"); });
1565
+        $("#ConnectionSettingsRow td").addClass("selectedSettingsSection");
1566
+    });
1567
+
1568
+    $("#ProfilePictureRow").click(function() {
1569
+        $(".settingsSubSection").each(function() { $(this).css("display", "none"); });
1570
+        $("#AppearanceHtml").css("display", "block");
1571
+        $(".SettingsSection").each(function() { $(this).removeClass("selectedSettingsSection"); });
1572
+        $("#ProfilePictureRow td").addClass("selectedSettingsSection");
1573
+    });
1574
+
1575
+    $("#NotificationsRow").click(function() {
1576
+        $(".settingsSubSection").each(function() { $(this).css("display", "none"); });
1577
+        $("#NotificationsHtml").css("display", "block");
1578
+        $(".SettingsSection").each(function() { $(this).removeClass("selectedSettingsSection"); });
1579
+        $("#NotificationsRow td").addClass("selectedSettingsSection");
1580
+    });
1581
+
1582
+    $("#RoundcubeEmailRow").click(function() {
1583
+        $(".settingsSubSection").each(function() { $(this).css("display", "none"); });
1584
+        $("#RoundcubeEmailHtml").css("display", "block");
1585
+        $(".SettingsSection").each(function() { $(this).removeClass("selectedSettingsSection"); });
1586
+        $("#RoundcubeEmailRow td").addClass("selectedSettingsSection");
1587
+    });
1588
+
1589
+    $("#ChangePasswordRow").click(function() {
1590
+        $(".settingsSubSection").each(function() { $(this).css("display", "none"); });
1591
+        $("#ChangePasswordHtml").css("display", "block");
1592
+        $(".SettingsSection").each(function() { $(this).removeClass("selectedSettingsSection"); });
1593
+        $("#ChangePasswordRow td").addClass("selectedSettingsSection");
1594
+    });
1595
+
1596
+    $("#ChangeEmailRow").click(function() {
1597
+        $(".settingsSubSection").each(function() { $(this).css("display", "none"); });
1598
+        $("#ChangeEmailHtml").css("display", "block");
1599
+        $(".SettingsSection").each(function() { $(this).removeClass("selectedSettingsSection"); });
1600
+        $("#ChangeEmailRow td").addClass("selectedSettingsSection");
1601
+    });
1602
+
1603
+    $("#CloseAccountRow").click(function() {
1604
+        $(".settingsSubSection").each(function() { $(this).css("display", "none"); });
1605
+        $("#CloseAccountHtml").css("display", "block");
1606
+        $(".SettingsSection").each(function() { $(this).removeClass("selectedSettingsSection"); });
1607
+        $("#CloseAccountRow td").addClass("selectedSettingsSection");
1608
+    });
1609
+
1610
+    var maxWidth = $(window).width() - 192;
1611
+    var maxHeight = $(window).height() - 98;
1612
+
1613
+    if (maxWidth < 520 || maxHeight < 500) { 
1614
+       $.jeegoopopup.width(maxWidth).height(maxHeight);
1615
+       $.jeegoopopup.center();
1616
+       $("#maximizeImg").hide();
1617
+       $("#minimizeImg").hide();
1618
+    } else { 
1619
+       $.jeegoopopup.width(520).height(500);
1620
+       $.jeegoopopup.center();
1621
+       $("#minimizeImg").hide();
1622
+       $("#maximizeImg").show();
1623
+    }
1624
+
1625
+    $(window).resize(function() {
1626
+       maxWidth = $(window).width() - 192;
1627
+       maxHeight = $(window).height() - 98;
1628
+       $.jeegoopopup.center();
1629
+       if (maxWidth < 520 || maxHeight < 500) { 
1630
+           $.jeegoopopup.width(maxWidth).height(maxHeight);
1631
+           $.jeegoopopup.center();
1632
+           $("#maximizeImg").hide();
1633
+           $("#minimizeImg").hide();
1634
+       } else { 
1635
+           $.jeegoopopup.width(520).height(500);
1636
+           $.jeegoopopup.center();
1637
+           $("#minimizeImg").hide();
1638
+           $("#maximizeImg").show();
1639
+       }
1640
+    });
1641
+
1642
+    $("#minimizeImg").click(function() { $.jeegoopopup.width(520).height(500); $.jeegoopopup.center(); $("#maximizeImg").show(); $("#minimizeImg").hide(); });
1643
+    $("#maximizeImg").click(function() { $.jeegoopopup.width(maxWidth).height(maxHeight); $.jeegoopopup.center(); $("#minimizeImg").show(); $("#maximizeImg").hide(); });
1644
+
1645
+
1646
+    // Output
1647
+    var selectAudioScr = $("#playbackSrc");
1648
+
1649
+    var playButton = $("#preview_output_play");
1650
+
1651
+    var playRingButton = $("#preview_ringer_play");
1652
+
1653
+    var pauseButton = $("#preview_output_pause");
1654
+
1655
+    // Microphone
1656
+    var selectMicScr = $("#microphoneSrc");
1657
+    $("#Settings_AutoGainControl").prop("checked", AutoGainControl);
1658
+    $("#Settings_EchoCancellation").prop("checked", EchoCancellation);
1659
+    $("#Settings_NoiseSuppression").prop("checked", NoiseSuppression);
1660
+
1661
+    // Webcam
1662
+    var selectVideoScr = $("#previewVideoSrc");
1663
+
1664
+    // Orientation
1665
+    var OrientationSel = $("input[name=Settings_Oriteation]");
1666
+    OrientationSel.each(function(){
1667
+        if(this.value == MirrorVideo) $(this).prop("checked", true);
1668
+    });
1669
+    $("#local-video-preview").css("transform", MirrorVideo);
1670
+
1671
+    // Frame Rate
1672
+    var frameRateSel = $("input[name=Settings_FrameRate]");
1673
+    frameRateSel.each(function(){
1674
+        if(this.value == maxFrameRate) $(this).prop("checked", true);
1675
+    });
1676
+
1677
+    // Quality
1678
+    var QualitySel = $("input[name=Settings_Quality]");
1679
+    QualitySel.each(function(){
1680
+        if(this.value == videoHeight) $(this).prop("checked", true);
1681
+    });
1682
+
1683
+    // Aspect Ratio
1684
+    var AspectRatioSel = $("input[name=Settings_AspectRatio]");
1685
+    AspectRatioSel.each(function(){
1686
+        if(this.value == videoAspectRatio) $(this).prop("checked", true);
1687
+    });
1688
+
1689
+    // Ring Tone
1690
+    var selectRingTone = $("#ringTone");
1691
+
1692
+    // Ring Device
1693
+    var selectRingDevice = $("#ringDevice");
1694
+
1695
+    // Handle Aspect Ratio Change
1696
+    AspectRatioSel.change(function(){
1697
+        console.log("Call to change Aspect Ratio ("+ this.value +")");
1698
+
1699
+        var localVideo = $("#local-video-preview").get(0);
1700
+        localVideo.muted = true;
1701
+        localVideo.playsinline = true;
1702
+        localVideo.autoplay = true;
1703
+
1704
+        var tracks = localVideo.srcObject.getTracks();
1705
+        tracks.forEach(function(track) {
1706
+            track.stop();
1707
+        });
1708
+
1709
+        var constraints = {
1710
+            audio: false,
1711
+            video: {
1712
+                deviceId: (selectVideoScr.val() != "default")? { exact: selectVideoScr.val() } : "default"
1713
+            }
1714
+        }
1715
+        if($("input[name=Settings_FrameRate]:checked").val() != ""){
1716
+            constraints.video.frameRate = $("input[name=Settings_FrameRate]:checked").val();
1717
+        }
1718
+        if($("input[name=Settings_Quality]:checked").val() != ""){
1719
+            constraints.video.height = $("input[name=Settings_Quality]:checked").val();
1720
+        }
1721
+        if(this.value != ""){
1722
+            constraints.video.aspectRatio = this.value;
1723
+        }        
1724
+        console.log("Constraints:", constraints);
1725
+        var localStream = new MediaStream();
1726
+        if(navigator.mediaDevices){
1727
+            navigator.mediaDevices.getUserMedia(constraints).then(function(newStream){
1728
+                var videoTrack = newStream.getVideoTracks()[0];
1729
+                localStream.addTrack(videoTrack);
1730
+                localVideo.srcObject = localStream;
1731
+                localVideo.onloadedmetadata = function(e) {
1732
+                    localVideo.play();
1733
+                }
1734
+            }).catch(function(e){
1735
+                console.error(e);
1736
+                AlertConfigExtWindow(lang.alert_error_user_media, lang.error);
1737
+            });
1738
+        }
1739
+    });
1740
+
1741
+    // Handle Video Height Change
1742
+    QualitySel.change(function(){    
1743
+        console.log("Call to change Video Height ("+ this.value +")");
1744
+
1745
+        var localVideo = $("#local-video-preview").get(0);
1746
+        localVideo.muted = true;
1747
+        localVideo.playsinline = true;
1748
+        localVideo.autoplay = true;
1749
+
1750
+        var tracks = localVideo.srcObject.getTracks();
1751
+        tracks.forEach(function(track) {
1752
+            track.stop();
1753
+        });
1754
+
1755
+        var constraints = {
1756
+            audio: false,
1757
+            video: {
1758
+                deviceId: (selectVideoScr.val() != "default")? { exact: selectVideoScr.val() } : "default" ,
1759
+            }
1760
+        }
1761
+        if($("input[name=Settings_FrameRate]:checked").val() != ""){
1762
+            constraints.video.frameRate = $("input[name=Settings_FrameRate]:checked").val();
1763
+        }
1764
+        if(this.value){
1765
+            constraints.video.height = this.value;
1766
+        }
1767
+        if($("input[name=Settings_AspectRatio]:checked").val() != ""){
1768
+            constraints.video.aspectRatio = $("input[name=Settings_AspectRatio]:checked").val();
1769
+        } 
1770
+        console.log("Constraints:", constraints);
1771
+        var localStream = new MediaStream();
1772
+        if(navigator.mediaDevices){
1773
+            navigator.mediaDevices.getUserMedia(constraints).then(function(newStream){
1774
+                var videoTrack = newStream.getVideoTracks()[0];
1775
+                localStream.addTrack(videoTrack);
1776
+                localVideo.srcObject = localStream;
1777
+                localVideo.onloadedmetadata = function(e) {
1778
+                    localVideo.play();
1779
+                }
1780
+            }).catch(function(e){
1781
+                console.error(e);
1782
+                AlertConfigExtWindow(lang.alert_error_user_media, lang.error);
1783
+            });
1784
+        }
1785
+    });    
1786
+
1787
+    // Handle Frame Rate Change 
1788
+    frameRateSel.change(function(){
1789
+        console.log("Call to change Frame Rate ("+ this.value +")");
1790
+
1791
+        var localVideo = $("#local-video-preview").get(0);
1792
+        localVideo.muted = true;
1793
+        localVideo.playsinline = true;
1794
+        localVideo.autoplay = true;
1795
+
1796
+        var tracks = localVideo.srcObject.getTracks();
1797
+        tracks.forEach(function(track) {
1798
+            track.stop();
1799
+        });
1800
+
1801
+        var constraints = {
1802
+            audio: false,
1803
+            video: {
1804
+                deviceId: (selectVideoScr.val() != "default")? { exact: selectVideoScr.val() } : "default" ,
1805
+            }
1806
+        }
1807
+        if(this.value != ""){
1808
+            constraints.video.frameRate = this.value;
1809
+        }
1810
+        if($("input[name=Settings_Quality]:checked").val() != ""){
1811
+            constraints.video.height = $("input[name=Settings_Quality]:checked").val();
1812
+        }
1813
+        if($("input[name=Settings_AspectRatio]:checked").val() != ""){
1814
+            constraints.video.aspectRatio = $("input[name=Settings_AspectRatio]:checked").val();
1815
+        } 
1816
+        console.log("Constraints:", constraints);
1817
+        var localStream = new MediaStream();
1818
+        if(navigator.mediaDevices){
1819
+            navigator.mediaDevices.getUserMedia(constraints).then(function(newStream){
1820
+                var videoTrack = newStream.getVideoTracks()[0];
1821
+                localStream.addTrack(videoTrack);
1822
+                localVideo.srcObject = localStream;
1823
+                localVideo.onloadedmetadata = function(e) {
1824
+                    localVideo.play();
1825
+                }
1826
+            }).catch(function(e){
1827
+                console.error(e);
1828
+                AlertConfigExtWindow(lang.alert_error_user_media, lang.error);
1829
+            });
1830
+        }
1831
+    });
1832
+
1833
+    // Handle Audio Source changes (Microphone)
1834
+    selectMicScr.change(function(){
1835
+        console.log("Call to change Microphone ("+ this.value +")");
1836
+
1837
+        // Change and update visual preview
1838
+        try{
1839
+            var tracks = window.SettingsMicrophoneStream.getTracks();
1840
+            tracks.forEach(function(track) {
1841
+                track.stop();
1842
+            });
1843
+            window.SettingsMicrophoneStream = null;
1844
+        }
1845
+        catch(e){}
1846
+
1847
+        try{
1848
+            soundMeter = window.SettingsMicrophoneSoundMeter;
1849
+            soundMeter.stop();
1850
+            window.SettingsMicrophoneSoundMeter = null;
1851
+        }
1852
+        catch(e){}
1853
+
1854
+        // Get Microphone
1855
+        var constraints = { 
1856
+            audio: {
1857
+                deviceId: { exact: this.value }
1858
+            }, 
1859
+            video: false 
1860
+        }
1861
+        var localMicrophoneStream = new MediaStream();
1862
+        navigator.mediaDevices.getUserMedia(constraints).then(function(mediaStream){
1863
+            var audioTrack = mediaStream.getAudioTracks()[0];
1864
+            if(audioTrack != null){
1865
+                // Display Microphone Levels
1866
+                localMicrophoneStream.addTrack(audioTrack);
1867
+                window.SettingsMicrophoneStream = localMicrophoneStream;
1868
+                window.SettingsMicrophoneSoundMeter = MeterSettingsOutput(localMicrophoneStream, "Settings_MicrophoneOutput", "width", 50);
1869
+            }
1870
+        }).catch(function(e){
1871
+            console.log("Failed to getUserMedia", e);
1872
+        });
1873
+    });
1874
+
1875
+    // Handle output change (speaker)
1876
+    selectAudioScr.change(function(){
1877
+        console.log("Call to change Speaker ("+ this.value +")");
1878
+
1879
+        var audioObj = window.SettingsOutputAudio;
1880
+        if(audioObj != null) {
1881
+            if (typeof audioObj.sinkId !== 'undefined') {
1882
+                audioObj.setSinkId(this.value).then(function() {
1883
+                    console.log("sinkId applied to audioObj:", this.value);
1884
+                }).catch(function(e){
1885
+                    console.warn("Failed not apply setSinkId.", e);
1886
+                });
1887
+            }
1888
+        }
1889
+    });
1890
+
1891
+    // Play button press
1892
+    playButton.click(function(){
1893
+
1894
+        try{
1895
+            window.SettingsOutputAudio.pause();
1896
+        } 
1897
+        catch(e){}
1898
+        window.SettingsOutputAudio = null;
1899
+
1900
+        try{
1901
+            var tracks = window.SettingsOutputStream.getTracks();
1902
+            tracks.forEach(function(track) {
1903
+                track.stop();
1904
+            });
1905
+        }
1906
+        catch(e){}
1907
+        window.SettingsOutputStream = null;
1908
+
1909
+        try{
1910
+            var soundMeter = window.SettingsOutputStreamMeter;
1911
+            soundMeter.stop();
1912
+        }
1913
+        catch(e){}
1914
+        window.SettingsOutputStreamMeter = null;
1915
+
1916
+        // Load Sample
1917
+        console.log("Audio:", audioBlobs.speaker_test.url);
1918
+        var audioObj = new Audio(audioBlobs.speaker_test.blob);
1919
+        audioObj.preload = "auto";
1920
+        audioObj.onplay = function(){
1921
+            var outputStream = new MediaStream();
1922
+            if (typeof audioObj.captureStream !== 'undefined') {
1923
+                outputStream = audioObj.captureStream();
1924
+            } 
1925
+            else if (typeof audioObj.mozCaptureStream !== 'undefined') {
1926
+                return;
1927
+            }
1928
+            else if (typeof audioObj.webkitCaptureStream !== 'undefined') {
1929
+                outputStream = audioObj.webkitCaptureStream();
1930
+            }
1931
+            else {
1932
+                console.warn("Cannot display Audio Levels")
1933
+                return;
1934
+            }
1935
+
1936
+            // Display Speaker Levels
1937
+            window.SettingsOutputStream = outputStream;
1938
+            window.SettingsOutputStreamMeter = MeterSettingsOutput(outputStream, "Settings_SpeakerOutput", "width", 50);
1939
+        }
1940
+        audioObj.oncanplaythrough = function(e) {
1941
+            if (typeof audioObj.sinkId !== 'undefined') {
1942
+                audioObj.setSinkId(selectAudioScr.val()).then(function() {
1943
+                    console.log("Set sinkId to:", selectAudioScr.val());
1944
+                }).catch(function(e){
1945
+                    console.warn("Failed not apply setSinkId.", e);
1946
+                });
1947
+            }
1948
+            // Play
1949
+            audioObj.play().then(function(){
1950
+                // Audio Is Playing
1951
+            }).catch(function(e){
1952
+                console.warn("Unable to play audio file", e);
1953
+            });
1954
+            console.log("Playing sample audio file... ");
1955
+        }
1956
+
1957
+        window.SettingsOutputAudio = audioObj;
1958
+    });
1959
+
1960
+    // Pause button press
1961
+    pauseButton.click(function() {
1962
+       if (window.SettingsOutputAudio.paused) {
1963
+           window.SettingsOutputAudio.play();
1964
+       } else { 
1965
+           window.SettingsOutputAudio.pause();
1966
+         }
1967
+    });
1968
+
1969
+
1970
+    playRingButton.click(function(){
1971
+
1972
+        try{
1973
+            window.SettingsRingerAudio.pause();
1974
+        } 
1975
+        catch(e){}
1976
+        window.SettingsRingerAudio = null;
1977
+
1978
+        try{
1979
+            var tracks = window.SettingsRingerStream.getTracks();
1980
+            tracks.forEach(function(track) {
1981
+                track.stop();
1982
+            });
1983
+        }
1984
+        catch(e){}
1985
+        window.SettingsRingerStream = null;
1986
+
1987
+        try{
1988
+            var soundMeter = window.SettingsRingerStreamMeter;
1989
+            soundMeter.stop();
1990
+        }
1991
+        catch(e){}
1992
+        window.SettingsRingerStreamMeter = null;
1993
+
1994
+        // Load Sample
1995
+        console.log("Audio:", audioBlobs.Ringtone.url);
1996
+        var audioObj = new Audio(audioBlobs.Ringtone.blob);
1997
+        audioObj.preload = "auto";
1998
+        audioObj.onplay = function(){
1999
+            var outputStream = new MediaStream();
2000
+            if (typeof audioObj.captureStream !== 'undefined') {
2001
+                outputStream = audioObj.captureStream();
2002
+            } 
2003
+            else if (typeof audioObj.mozCaptureStream !== 'undefined') {
2004
+                return;
2005
+                // BUG: mozCaptureStream() in Firefox does not work the same way as captureStream()
2006
+                // the actual sound does not play out to the speakers... its as if the mozCaptureStream
2007
+                // removes the stream from the <audio> object.
2008
+                outputStream = audioObj.mozCaptureStream();
2009
+            }
2010
+            else if (typeof audioObj.webkitCaptureStream !== 'undefined') {
2011
+                outputStream = audioObj.webkitCaptureStream();
2012
+            }
2013
+            else {
2014
+                console.warn("Cannot display Audio Levels")
2015
+                return;
2016
+            }
2017
+            // Monitor Output
2018
+            window.SettingsRingerStream = outputStream;
2019
+            window.SettingsRingerStreamMeter = MeterSettingsOutput(outputStream, "Settings_RingerOutput", "width", 50);
2020
+        }
2021
+        audioObj.oncanplaythrough = function(e) {
2022
+            if (typeof audioObj.sinkId !== 'undefined') {
2023
+                audioObj.setSinkId(selectRingDevice.val()).then(function() {
2024
+                    console.log("Set sinkId to:", selectRingDevice.val());
2025
+                }).catch(function(e){
2026
+                    console.warn("Failed not apply setSinkId.", e);
2027
+                });
2028
+            }
2029
+            // Play
2030
+            audioObj.play().then(function(){
2031
+                // Audio Is Playing
2032
+            }).catch(function(e){
2033
+                console.warn("Unable to play audio file", e);
2034
+            });
2035
+            console.log("Playing sample audio file... ");
2036
+        }
2037
+
2038
+        window.SettingsRingerAudio = audioObj;
2039
+    });
2040
+
2041
+    // Change Video Image
2042
+    OrientationSel.change(function(){
2043
+        console.log("Call to change Orientation ("+ this.value +")");
2044
+        $("#local-video-preview").css("transform", this.value);
2045
+    });
2046
+
2047
+    // Handle video input change (WebCam)
2048
+    selectVideoScr.change(function(){
2049
+        console.log("Call to change WebCam ("+ this.value +")");
2050
+
2051
+        var localVideo = $("#local-video-preview").get(0);
2052
+        localVideo.muted = true;
2053
+        localVideo.playsinline = true;
2054
+        localVideo.autoplay = true;
2055
+
2056
+        var tracks = localVideo.srcObject.getTracks();
2057
+        tracks.forEach(function(track) {
2058
+            track.stop();
2059
+        });
2060
+
2061
+        var constraints = {
2062
+            audio: false,
2063
+            video: {
2064
+                deviceId: (this.value != "default")? { exact: this.value } : "default"
2065
+            }
2066
+        }
2067
+        if($("input[name=Settings_FrameRate]:checked").val() != ""){
2068
+            constraints.video.frameRate = $("input[name=Settings_FrameRate]:checked").val();
2069
+        }
2070
+        if($("input[name=Settings_Quality]:checked").val() != ""){
2071
+            constraints.video.height = $("input[name=Settings_Quality]:checked").val();
2072
+        }
2073
+        if($("input[name=Settings_AspectRatio]:checked").val() != ""){
2074
+            constraints.video.aspectRatio = $("input[name=Settings_AspectRatio]:checked").val();
2075
+        } 
2076
+        console.log("Constraints:", constraints);
2077
+        var localStream = new MediaStream();
2078
+        if(navigator.mediaDevices){
2079
+            navigator.mediaDevices.getUserMedia(constraints).then(function(newStream){
2080
+                var videoTrack = newStream.getVideoTracks()[0];
2081
+                localStream.addTrack(videoTrack);
2082
+                localVideo.srcObject = localStream;
2083
+                localVideo.onloadedmetadata = function(e) {
2084
+                    localVideo.play();
2085
+                }
2086
+            }).catch(function(e){
2087
+                console.error(e);
2088
+                AlertConfigExtWindow(lang.alert_error_user_media, lang.error);
2089
+            });
2090
+        }
2091
+    });
2092
+
2093
+    $("#AudioAndVideoRow").click(function() {
2094
+
2095
+       $(".settingsSubSection").each(function() { $(this).css("display", "none"); });
2096
+       $("#AudioVideoHtml").css("display", "block");
2097
+       $(".SettingsSection").each(function() { $(this).removeClass("selectedSettingsSection"); });
2098
+       $("#AudioAndVideoRow td").addClass("selectedSettingsSection");
2099
+
2100
+       if (videoAudioCheck == 0) {
2101
+
2102
+            videoAudioCheck = 1;
2103
+
2104
+	    // Note: Only works over HTTPS or via localhost!!
2105
+	    var localVideo = $("#local-video-preview").get(0);
2106
+	    localVideo.muted = true;
2107
+	    localVideo.playsinline = true;
2108
+	    localVideo.autoplay = true;
2109
+
2110
+	    var localVideoStream = new MediaStream();
2111
+	    var localMicrophoneStream = new MediaStream();
2112
+	    
2113
+	    if(navigator.mediaDevices){
2114
+		navigator.mediaDevices.enumerateDevices().then(function(deviceInfos){
2115
+		    var savedVideoDevice = getVideoSrcID();
2116
+		    var videoDeviceFound = false;
2117
+
2118
+		    var savedAudioDevice = getAudioSrcID();
2119
+		    var audioDeviceFound = false;
2120
+
2121
+		    var MicrophoneFound = false;
2122
+		    var SpeakerFound = false;
2123
+		    var VideoFound = false;
2124
+
2125
+		    for (var i = 0; i < deviceInfos.length; ++i) {
2126
+		        console.log("Found Device ("+ deviceInfos[i].kind +"): ", deviceInfos[i].label);
2127
+
2128
+		        // Check Devices
2129
+		        if (deviceInfos[i].kind === "audioinput") {
2130
+		            MicrophoneFound = true;
2131
+		            if(savedAudioDevice != "default" && deviceInfos[i].deviceId == savedAudioDevice) {
2132
+		                audioDeviceFound = true;
2133
+		            }                   
2134
+		        }
2135
+		        else if (deviceInfos[i].kind === "audiooutput") {
2136
+		            SpeakerFound = true;
2137
+		        }
2138
+		        else if (deviceInfos[i].kind === "videoinput") {
2139
+		            VideoFound = true;
2140
+		            if(savedVideoDevice != "default" && deviceInfos[i].deviceId == savedVideoDevice) {
2141
+		                videoDeviceFound = true;
2142
+		            }
2143
+		        }
2144
+		    }
2145
+
2146
+		    var contraints = {
2147
+		        audio: MicrophoneFound,
2148
+		        video: VideoFound
2149
+		    }
2150
+
2151
+		    if(MicrophoneFound){
2152
+		        contraints.audio = { deviceId: "default" }
2153
+		        if(audioDeviceFound) contraints.audio.deviceId = { exact: savedAudioDevice }
2154
+		    }
2155
+		    if(VideoFound){
2156
+		        contraints.video = { deviceId: "default" }
2157
+		        if(videoDeviceFound) contraints.video.deviceId = { exact: savedVideoDevice }
2158
+		    }
2159
+		    // Additional
2160
+		    if($("input[name=Settings_FrameRate]:checked").val() != ""){
2161
+		        contraints.video.frameRate = $("input[name=Settings_FrameRate]:checked").val();
2162
+		    }
2163
+		    if($("input[name=Settings_Quality]:checked").val() != ""){
2164
+		        contraints.video.height = $("input[name=Settings_Quality]:checked").val();
2165
+		    }
2166
+		    if($("input[name=Settings_AspectRatio]:checked").val() != ""){
2167
+		        contraints.video.aspectRatio = $("input[name=Settings_AspectRatio]:checked").val();
2168
+		    } 
2169
+		    console.log("Get User Media", contraints);
2170
+		    // Get User Media
2171
+		    navigator.mediaDevices.getUserMedia(contraints).then(function(mediaStream){
2172
+		        // Handle Video
2173
+		        var videoTrack = (mediaStream.getVideoTracks().length >= 1)? mediaStream.getVideoTracks()[0] : null;
2174
+		        if(VideoFound && videoTrack != null){
2175
+		            localVideoStream.addTrack(videoTrack);
2176
+		            // Display Preview Video
2177
+		            localVideo.srcObject = localVideoStream;
2178
+		            localVideo.onloadedmetadata = function(e) {
2179
+		                localVideo.play();
2180
+		            }
2181
+		        }
2182
+		        else {
2183
+		            console.warn("No video / webcam devices found. Video Calling will not be possible.")
2184
+		        }
2185
+
2186
+		        // Handle Audio
2187
+		        var audioTrack = (mediaStream.getAudioTracks().length >= 1)? mediaStream.getAudioTracks()[0] : null ;
2188
+		        if(MicrophoneFound && audioTrack != null){
2189
+		            localMicrophoneStream.addTrack(audioTrack);
2190
+		            // Display Micrphone Levels
2191
+		            window.SettingsMicrophoneStream = localMicrophoneStream;
2192
+		            window.SettingsMicrophoneSoundMeter = MeterSettingsOutput(localMicrophoneStream, "Settings_MicrophoneOutput", "width", 50);
2193
+		        }
2194
+		        else {
2195
+		            console.warn("No microphone devices found. Calling will not be possible.")
2196
+		        }
2197
+
2198
+		        // Display Output Levels
2199
+		        $("#Settings_SpeakerOutput").css("width", "0%");
2200
+		        if(!SpeakerFound){
2201
+		            console.log("No speaker devices found, make sure one is plugged in.")
2202
+		            $("#playbackSrc").hide();
2203
+		            $("#RingDeviceSection").hide();
2204
+		        }
2205
+
2206
+		       // Return .then()
2207
+		       return navigator.mediaDevices.enumerateDevices();
2208
+		    }).then(function(deviceInfos){
2209
+		        for (var i = 0; i < deviceInfos.length; ++i) {
2210
+		            console.log("Found Device ("+ deviceInfos[i].kind +") Again: ", deviceInfos[i].label, deviceInfos[i].deviceId);
2211
+
2212
+		            var deviceInfo = deviceInfos[i];
2213
+		            var devideId = deviceInfo.deviceId;
2214
+		            var DisplayName = deviceInfo.label;
2215
+		            if(DisplayName.indexOf("(") > 0) DisplayName = DisplayName.substring(0,DisplayName.indexOf("("));
2216
+
2217
+		            var option = $('<option/>');
2218
+		            option.prop("value", devideId);
2219
+
2220
+		            if (deviceInfo.kind === "audioinput") {
2221
+		                option.text((DisplayName != "")? DisplayName : "Microphone");
2222
+		                if(getAudioSrcID() == devideId) option.prop("selected", true);
2223
+		                selectMicScr.append(option);
2224
+		            }
2225
+		            else if (deviceInfo.kind === "audiooutput") {
2226
+		                option.text((DisplayName != "")? DisplayName : "Speaker");
2227
+		                if(getAudioOutputID() == devideId) option.prop("selected", true);
2228
+		                selectAudioScr.append(option);
2229
+		                selectRingDevice.append(option.clone());
2230
+		            }
2231
+		            else if (deviceInfo.kind === "videoinput") {
2232
+		                if(getVideoSrcID() == devideId) option.prop("selected", true);
2233
+		                option.text((DisplayName != "")? DisplayName : "Webcam");
2234
+		                selectVideoScr.append(option);
2235
+		            }
2236
+		        }
2237
+		        // Add "Default" option
2238
+		        if(selectVideoScr.children('option').length > 0){
2239
+		            var option = $('<option/>');
2240
+		            option.prop("value", "default");
2241
+		            if(getVideoSrcID() == "default" || getVideoSrcID() == "" || getVideoSrcID() == "null") option.prop("selected", true);
2242
+		            option.text("(Default)");
2243
+		            selectVideoScr.append(option);
2244
+		        }
2245
+		    }).catch(function(e){
2246
+		        console.error(e);
2247
+		        AlertConfigExtWindow(lang.alert_error_user_media, lang.error);
2248
+		    });
2249
+		}).catch(function(e){
2250
+		    console.error("Error getting Media Devices", e);
2251
+		});
2252
+
2253
+	    } else {
2254
+		AlertConfigExtWindow(lang.alert_error_user_media, lang.error);
2255
+	    }
2256
+        }
2257
+    });
2258
+
2259
+    var NotificationsCheck = $("#Settings_Notifications");
2260
+    NotificationsCheck.prop("checked", NotificationsActive);
2261
+    NotificationsCheck.change(function(){
2262
+        if(this.checked){
2263
+            if(Notification.permission != "granted"){
2264
+                if(checkNotificationPromise()){
2265
+                    Notification.requestPermission().then(function(p){
2266
+                        console.log(p);
2267
+                        HandleNotifyPermission(p);
2268
+                    });
2269
+                }
2270
+                else {
2271
+                    Notification.requestPermission(function(p){
2272
+                        console.log(p);
2273
+                        HandleNotifyPermission(p)
2274
+                    });
2275
+                }
2276
+            }
2277
+        }
2278
+    });
2279
+
2280
+
2281
+    // Save configration data for external video conference users
2282
+    $("#vidConfExternalTable").on("click", ".saveExtConfExtension", function() {
2283
+
2284
+      if ($(this).val() == "Save") {
2285
+
2286
+        var extUserExtension = $(this).closest('tr').find('input.extConfExtension').val();
2287
+        var extUserExtensionPass = $(this).closest('tr').find('input.extConfExtensionPass').val();
2288
+
2289
+        var WSSServer = localDB.getItem("wssServer");
2290
+
2291
+        if (extUserExtension != '' && extUserExtensionPass != '') {
2292
+          if (extUserExtension.length < 200 && extUserExtensionPass.length < 400) {
2293
+            // Check if the extension that has been entered is valid
2294
+            if (/^[a-zA-Z0-9]+$/.test(extUserExtension)) {
2295
+
2296
+              $.ajax({
2297
+                 type: "POST",
2298
+                 url: "save-update-external-user-conf.php",
2299
+                 dataType: "JSON",
2300
+                 data: {
2301
+                        username: userName,
2302
+                        exten_for_external: extUserExtension,
2303
+                        exten_for_ext_pass: extUserExtensionPass,
2304
+                        wss_server: WSSServer,
2305
+                        s_ajax_call: validateSToken
2306
+                     },
2307
+                 success: function(response) {
2308
+
2309
+                                 if (response.result == 'The data has been successfully saved to the database !') {
2310
+
2311
+                                     getExternalUserConfFromSqldb();
2312
+                                     alert("The data has been successfully saved to the database ! To see the result, please reopen this window !");
2313
+
2314
+                                     $("#jg_popup_b").empty(); $("#jg_popup_l").empty(); $("#windowCtrls").empty(); closeVideoAudio(); $.jeegoopopup.close();
2315
+
2316
+                                 } else { alert(response.result); }
2317
+
2318
+                 },
2319
+                 error: function(response) {
2320
+                                 alert("An error occurred while trying to save the data to the database !");
2321
+                 }
2322
+              });
2323
+
2324
+              $(this).closest('[class="btnTableRow"]').find('[class="extConfExtension"]').attr("disabled", true);
2325
+              $(this).closest('[class="btnTableRow"]').find('[class="extConfExtensionPass"]').attr("disabled", true);
2326
+              $(this).attr("value", "Edit");
2327
+              $(this).prop("title", "Edit this row.");
2328
+
2329
+            } else { alert("The extension should contain only numbers and letters."); }
2330
+          } else { alert("The extension and/or the SIP password don't have a reasonable length."); }
2331
+        } else { alert("Please fill in both the \"Extension\" and the \"SIP Password\" fields !"); }
2332
+      } else {
2333
+          $(this).closest('[class="btnTableRow"]').find('[class="extConfExtension"]').attr("disabled", false);
2334
+          $(this).closest('[class="btnTableRow"]').find('[class="extConfExtensionPass"]').attr("disabled", false);
2335
+          $(this).attr("value", "Save");
2336
+          $(this).prop("title", "Save this row.");
2337
+      }
2338
+    });
2339
+
2340
+    // Delete extension data from the database
2341
+    $("#vidConfExternalTable").on("click", ".deleteExtRow", function() {
2342
+
2343
+      var targetExtension = $(this).closest('[class="btnTableRow"]').find('[class="extConfExtension"]').val();
2344
+
2345
+      if (targetExtension != '') {
2346
+
2347
+         if (confirm("Do you really want to delete this row from this window and from the database ?")) {
2348
+
2349
+             $.ajax({
2350
+                 type: "POST",
2351
+                 url: "remove-external-user-ext-data.php",
2352
+                 dataType: "JSON",
2353
+                 data: {
2354
+                        username: userName,
2355
+                        exten_for_external: targetExtension,
2356
+                        s_ajax_call: validateSToken
2357
+                       },
2358
+                 success: function(response) {
2359
+                                   $(this).closest('tr').find('input.extConfExtension').empty();
2360
+                                   $(this).closest('tr').find('input.extConfExtensionPass').empty();
2361
+                                   $(this).closest('tr').find('input.extConfExtensionLink').empty();
2362
+                                   getExternalUserConfFromSqldb();
2363
+                                   alert("The data has been permanently removed !");
2364
+                 },
2365
+                 error: function(response) {
2366
+                             alert("An error occurred while trying to remove the data !");
2367
+                 }
2368
+             });
2369
+
2370
+             $(this).closest('[class="btnTableRow"]').hide();
2371
+         }
2372
+      }
2373
+    });
2374
+
2375
+    $(".copyToClipboard").mouseenter(function() {
2376
+        if ($(this).closest('[class="btnTableRow"]').find('[class="extConfExtensionLink"]').val() != '') {
2377
+            $(this).css("color", "#424242");
2378
+            $(this).css("cursor", "pointer");
2379
+        }
2380
+    });
2381
+
2382
+    $(".copyToClipboard").mouseleave(function() {
2383
+        $(this).css("color", "#cccccc");
2384
+    });
2385
+
2386
+    $(".copyToClipboard").click(function() {
2387
+        if ($(this).closest('[class="btnTableRow"]').find('[class="extConfExtensionLink"]').val() != '') {
2388
+	      var $tempEl = $("<input>");
2389
+	      $("body").append($tempEl);
2390
+	      $tempEl.val($(this).closest('[class="btnTableRow"]').find('[class="extConfExtensionLink"]').val()).select();
2391
+	      document.execCommand("Copy");
2392
+	      $tempEl.remove();
2393
+	      alert("The link has been copied to your clipboard!");
2394
+        }
2395
+    });
2396
+
2397
+    var externUserData = getDbItem("externalUserConfElem", "");
2398
+    if (externUserData !== 'undefined' && externUserData != 'null' && externUserData != 0) {
2399
+        $("#emptyExtRow").hide();
2400
+    }
2401
+
2402
+    $("#add_New_External_User").click(function() {
2403
+       $("#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>");
2404
+    });
2405
+
2406
+
2407
+    // Profile Picture
2408
+    cropper = $("#ImageCanvas").croppie({
2409
+        viewport: { width: 150, height: 150, type: 'circle' }
2410
+    });
2411
+
2412
+    // Preview Existing Image
2413
+    $("#ImageCanvas").croppie('bind', { url: getPicture("profilePicture") }).then(function() {
2414
+       $('.cr-slider').attr({ min: 0.5, max: 3 });
2415
+    });
2416
+
2417
+    // Wireup File Change
2418
+    $("#fileUploader").change(function () {
2419
+        var filesArray = $(this).prop('files');
2420
+    
2421
+        if (filesArray.length == 1) {
2422
+            var uploadId = Math.floor(Math.random() * 1000000000);
2423
+            var fileObj = filesArray[0];
2424
+            var fileName = fileObj.name;
2425
+            var fileSize = fileObj.size;
2426
+    
2427
+            if (fileSize <= 52428800) {
2428
+                console.log("Adding (" + uploadId + "): " + fileName + " of size: " + fileSize + "bytes");
2429
+    
2430
+                var reader = new FileReader();
2431
+                reader.Name = fileName;
2432
+                reader.UploadId = uploadId;
2433
+                reader.Size = fileSize;
2434
+                reader.onload = function (event) {
2435
+                    $("#ImageCanvas").croppie('bind', {
2436
+                        url: event.target.result
2437
+                    });
2438
+                }
2439
+
2440
+                // Use onload for this
2441
+                reader.readAsDataURL(fileObj);
2442
+            }
2443
+            else {
2444
+                Alert(lang.alert_file_size, lang.error);
2445
+            }
2446
+        }
2447
+        else {
2448
+            Alert(lang.alert_single_file, lang.error);
2449
+        }
2450
+    });
2451
+
2452
+
2453
+    $("#save_button_conf").click(function() {
2454
+
2455
+        if(localDB.getItem("profileUserID") == null) localDB.setItem("profileUserID", uID()); // For first time only
2456
+
2457
+        var confAccWssServer = $("#Configure_Account_wssServer").val();
2458
+        if (/^[A-Za-z0-9\.\-]+\.[A-Za-z0-9\-]{2,63}$/.test(confAccWssServer)) { var finconfAccWssServer = confAccWssServer; } else { 
2459
+            var finconfAccWssServer = ''; alert('The WebSocket domain that you entered is not a valid domain name!'); }
2460
+
2461
+        var confAccWSPort = $("#Configure_Account_WebSocketPort").val();
2462
+        if (/^[0-9]+$/.test(confAccWSPort)) { var finConfAccWSPort = confAccWSPort; } else { 
2463
+            var finConfAccWSPort = ''; alert('The web socket port that you entered is not a valid port!'); }
2464
+
2465
+        var confAccServerPath = $("#Configure_Account_ServerPath").val();
2466
+        if (/^[A-Za-z0-9\/]+$/.test(confAccServerPath)) { var finConfAccServerPath = confAccServerPath; } else { 
2467
+            var finConfAccServerPath = ''; alert('The server path that you entered is not a valid server path!');}
2468
+
2469
+        var confAccProfileName = $("#Configure_Account_profileName").val();
2470
+        if (/^[A-Za-z0-9\s\-\'\[\]\(\)]+$/.test(confAccProfileName)) { var finConfAccProfileName = confAccProfileName; } else { 
2471
+            var finConfAccProfileName = ''; alert('The profile name that you entered is not a valid profile name!'); }
2472
+
2473
+        var confAccSipUsername = $("#Configure_Account_SipUsername").val();
2474
+        if (/^[A-Za-z0-9\-\.\_\@\*\!\?\&\~\(\)\[\]]+$/.test(confAccSipUsername)) { var finConfAccSipUsername = confAccSipUsername; } else { 
2475
+            var finConfAccSipUsername = ''; alert('The SIP username that you entered is not a valid SIP username!'); }
2476
+
2477
+        var confAccSipPassword = $("#Configure_Account_SipPassword").val();
2478
+        if (confAccSipPassword.length < 400) { var finConfAccSipPassword = confAccSipPassword; } else { 
2479
+            var finConfAccSipPassword = ''; alert('The SIP password that you entered is too long!'); }
2480
+
2481
+        var confAccStun = $("#Configure_Account_StunServer").val();
2482
+        if (confAccStun != null && confAccStun.trim() !== '') {
2483
+            if (/^(\d+\.\d+\.\d+\.\d+:\d+)$|^([A-Za-z0-9\.\-]+\.[A-Za-z0-9\-]{2,63}:\d+)/.test(confAccStun)) { var finConfAccStun = confAccStun; } else { 
2484
+                var finConfAccStun = ''; alert('The domain or IP or port number of the STUN server is not valid!'); }
2485
+        } else { var finConfAccStun = ''; }
2486
+
2487
+        if (finconfAccWssServer != null && finconfAccWssServer.trim() !== '' &&
2488
+            finConfAccWSPort != null && finConfAccWSPort.trim() !== '' &&
2489
+            finConfAccServerPath != null && finConfAccServerPath.trim() !== '' &&
2490
+            finConfAccProfileName != null && finConfAccProfileName.trim() !== '' &&
2491
+            finConfAccSipUsername != null && finConfAccSipUsername.trim() !== '' &&
2492
+            finConfAccSipPassword != null && finConfAccSipPassword.trim() !== '') {
2493
+
2494
+            // OK
2495
+
2496
+        } else { alert('All fields marked with an asterisk are required!'); return; }
2497
+
2498
+
2499
+        // Audio & Video
2500
+        localDB.setItem("AudioOutputId", $("#playbackSrc").val());
2501
+        localDB.setItem("VideoSrcId", $("#previewVideoSrc").val());
2502
+        localDB.setItem("VideoHeight", $("input[name=Settings_Quality]:checked").val());
2503
+        localDB.setItem("FrameRate", $("input[name=Settings_FrameRate]:checked").val());
2504
+        localDB.setItem("AspectRatio", $("input[name=Settings_AspectRatio]:checked").val());
2505
+        localDB.setItem("VideoOrientation", $("input[name=Settings_Oriteation]:checked").val());
2506
+        localDB.setItem("AudioSrcId", $("#microphoneSrc").val());
2507
+        localDB.setItem("AutoGainControl", ($("#Settings_AutoGainControl").is(':checked'))? "1" : "0");
2508
+        localDB.setItem("EchoCancellation", ($("#Settings_EchoCancellation").is(':checked'))? "1" : "0");
2509
+        localDB.setItem("NoiseSuppression", ($("#Settings_NoiseSuppression").is(':checked'))? "1" : "0");
2510
+        localDB.setItem("RingOutputId", $("#ringDevice").val());
2511
+
2512
+        // Check if the extension that has been entered is valid
2513
+        var videoConfExten = $("#Video_Conf_Extension").val();
2514
+        if (/^[a-zA-Z0-9\*\#]+$/.test(videoConfExten)) { var finVideoConfExten = videoConfExten; } else { 
2515
+            var finVideoConfExten = ''; alert("The extension that you entered in the 'Video Conference Extension' field is not a valid extension!");}
2516
+
2517
+        localDB.setItem("VidConfExtension", finVideoConfExten);
2518
+
2519
+        var videoConfWinWidth = $("#Video_Conf_Window_Width").val();
2520
+        if ((/^[0-9]+$/.test(videoConfWinWidth)) && Math.abs(videoConfWinWidth) <= 100) { var finVideoConfWinWidth = Math.abs(videoConfWinWidth); } else { 
2521
+             var finVideoConfWinWidth = ''; alert("The percent value that you entered in the 'Percent of screen width ...' field is not valid!"); }
2522
+
2523
+        localDB.setItem("VidConfWindowWidth", finVideoConfWinWidth);
2524
+
2525
+        localDB.setItem("Notifications", ($("#Settings_Notifications").is(":checked"))? "1" : "0");
2526
+
2527
+        if ($("#emailIntegration").is(":checked")) {
2528
+
2529
+            if (/^[A-Za-z0-9\.\-]+\.[A-Za-z0-9\-]{2,63}$/.test($("#RoundcubeDomain").val())) {} else {
2530
+                $("#emailIntegration").prop("checked", false);
2531
+                $("#RoundcubeDomain").val("");
2532
+                alert("The Roundcube domain is not valid. After entering a valid Roundcube domain, please remember to check the checkbox 'Enable Roundcube email integration' again !");
2533
+                return;
2534
+            }
2535
+
2536
+            if (/^[A-Za-z0-9\_\.\-\@\~\%\+\!\?\&\*\^\=\#\$\{\}\|\/]{1,300}$/.test($("#RoundcubeUser").val())) {} else {
2537
+                $("#emailIntegration").prop("checked", false);
2538
+                $("#RoundcubeUser").val("");
2539
+                alert("The Roundcube user is not valid. After entering a valid Roundcube user, please remember to check the checkbox 'Enable Roundcube email integration' again !");
2540
+                return;
2541
+            }
2542
+
2543
+            if ($("#RoundcubePass").val() == '' || $("#RoundcubePass").val().length > 300) { 
2544
+                $("#emailIntegration").prop("checked", false); 
2545
+                $("#RoundcubePass").val("");
2546
+                alert("The Roundcube password is not valid. After entering a valid Roundcube password, please remember to check the checkbox 'Enable Roundcube email integration' again !");
2547
+                return;
2548
+            }
2549
+
2550
+            if ($("#rcBasicAuthUser").val().length > 300) { $("#rcBasicAuthUser").val(""); alert("The Roundcube basic authentication user is not valid."); return; }
2551
+
2552
+            if ($("#rcBasicAuthPass").val().length > 300) { $("#rcBasicAuthPass").val(""); alert("The Roundcube basic authentication password is not valid."); return; }
2553
+        }
2554
+
2555
+        // The profile picture can't be saved if the style of its section is 'display: none;'
2556
+        $("#AppearanceHtml").css({ 'display' : 'block', 'visibility' : 'hidden', 'margin-top' : '-228px' });
2557
+
2558
+
2559
+        // Convert the profile picture to base64
2560
+        $("#ImageCanvas").croppie('result', {
2561
+            type: 'base64',
2562
+            size: 'viewport',
2563
+            format: 'png',
2564
+            quality: 1,
2565
+            circle: false
2566
+        }).then(function(base64) {
2567
+            localDB.setItem("profilePicture", base64);
2568
+        });
2569
+
2570
+        setTimeout(function() {
2571
+            saveConfToSqldb();
2572
+        }, 600);
2573
+
2574
+    });
2575
+
2576
+    $("#closeImg").click(function() { $("#jg_popup_b").empty(); $("#jg_popup_l").empty(); $("#windowCtrls").empty(); closeVideoAudio(); $.jeegoopopup.close(); });
2577
+    $("#cancel_button_conf").click(function() { $("#jg_popup_b").empty(); $("#jg_popup_l").empty(); $("#windowCtrls").empty(); closeVideoAudio(); $.jeegoopopup.close(); });
2578
+    $("#jg_popup_overlay").click(function() { $("#jg_popup_b").empty(); $("#jg_popup_l").empty(); $("#windowCtrls").empty(); closeVideoAudio(); $.jeegoopopup.close(); });
2579
+    $(window).on('keydown', function(event) { if (event.key == "Escape") { $("#jg_popup_b").empty(); $("#jg_popup_l").empty(); $("#windowCtrls").empty(); closeVideoAudio(); $.jeegoopopup.close(); } });
2580
+
2581
+}
2582
+
2583
+function checkNotificationPromise() {
2584
+    try {
2585
+        Notification.requestPermission().then();
2586
+    }
2587
+    catch(e) {
2588
+        return false;
2589
+    }
2590
+    return true;
2591
+}
2592
+function HandleNotifyPermission(p){
2593
+
2594
+    if(p == "granted") {
2595
+       // Good
2596
+    } else {
2597
+        Alert(lang.alert_notification_permission, lang.permission, function(){
2598
+            console.log("Attempting to uncheck the checkbox...");
2599
+            $("#Settings_Notifications").prop("checked", false);
2600
+        });
2601
+    }
2602
+}
2603
+function EditBuddyWindow(buddy){
2604
+
2605
+    $.jeegoopopup.close();
2606
+
2607
+    var buddyObj = null;
2608
+    var itemId = -1;
2609
+    var json = JSON.parse(localDB.getItem(profileUserID + "-Buddies"));
2610
+    $.each(json.DataCollection, function (i, item) {
2611
+        if(item.uID == buddy || item.cID == buddy || item.gID == buddy){
2612
+            buddyObj = item;
2613
+            itemId = i;
2614
+            return false;
2615
+        }
2616
+    });
2617
+
2618
+    if(buddyObj == null){
2619
+        Alert(lang.alert_not_found, lang.error);
2620
+        return;
2621
+    }
2622
+
2623
+    var html = "<div id='EditContact'>";
2624
+
2625
+    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>";
2626
+
2627
+    html += "<div class='UiWindowField scroller'>";
2628
+
2629
+    html += "<div id=ImageCanvas style=\"width:150px; height:150px\"></div>";
2630
+    html += "<label for=ebFileUploader class=customBrowseButton style=\"margin-left: 200px; margin-top: -9px;\">Select File</label>";
2631
+    html += "<div><input type=file id=ebFileUploader /></div>";
2632
+    html += "<div style=\"margin-top: 50px\"></div>";
2633
+
2634
+    html += "<div class=UiText>"+ lang.display_name +":</div>";
2635
+
2636
+    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>";
2637
+
2638
+    html += "<div class=UiText>"+ lang.title_description +":</div>";
2639
+
2640
+    if(buddyObj.Type == "extension"){
2641
+        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>";
2642
+    }
2643
+    else {
2644
+        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>";
2645
+    }
2646
+
2647
+    html += "<div class=UiText>"+ lang.internal_subscribe_extension +":</div>";
2648
+    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>";
2649
+
2650
+    html += "<div class=UiText>"+ lang.mobile_number +":</div>";
2651
+    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>";
2652
+
2653
+    html += "<div class=UiText>"+ lang.contact_number_1 +":</div>";
2654
+    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>";
2655
+
2656
+    html += "<div class=UiText>"+ lang.contact_number_2 +":</div>";
2657
+    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>";
2658
+
2659
+    html += "<div class=UiText>"+ lang.email +":</div>";
2660
+    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>";
2661
+
2662
+    html += "</div></div>"
2663
+
2664
+    $.jeegoopopup.open({
2665
+                title: 'Edit Contact',
2666
+                html: html,
2667
+                width: '640',
2668
+                height: '500',
2669
+                center: true,
2670
+                scrolling: 'no',
2671
+                skinClass: 'jg_popup_basic',
2672
+                contentClass: 'editContactPopup',
2673
+                overlay: true,
2674
+                opacity: 50,
2675
+                draggable: true,
2676
+                resizable: false,
2677
+                fadeIn: 0
2678
+    });
2679
+
2680
+    $("#jg_popup_b").append("<div id=bottomButtons><button id=save_button>Save</button><button id=cancel_button>Cancel</button></div>");
2681
+
2682
+
2683
+    var contactDatabaseId = '';
2684
+
2685
+    $.ajax({
2686
+        type: "POST",
2687
+        url: "get-contact-dbid.php",
2688
+        dataType: "JSON",
2689
+        data: {
2690
+            username: userName,
2691
+            contact_name: buddyObj.DisplayName,
2692
+            s_ajax_call: validateSToken
2693
+        },
2694
+        success: function(response) {
2695
+                 if (response.successorfailure == 'success') {
2696
+                     contactDatabaseId = response.cntctDatabaseID;
2697
+                 } else { alert("Error while attempting to retrieve contact data from the database!"); }
2698
+        },
2699
+        error: function(response) {
2700
+                 alert("Error while attempting to retrieve contact data from the database!");
2701
+        }
2702
+    });
2703
+
2704
+    // DoOnLoad
2705
+    var cropper = $("#ImageCanvas").croppie({
2706
+              viewport: { width: 150, height: 150, type: 'circle' }
2707
+    });
2708
+
2709
+    // Preview Existing Image
2710
+    if(buddyObj.Type == "extension"){
2711
+       $("#ImageCanvas").croppie('bind', { url: getPicture(buddyObj.uID, "extension") }).then(function() {
2712
+          $('.cr-slider').attr({ min: 0.5, max: 3 });
2713
+       });
2714
+    } else if(buddyObj.Type == "contact") {
2715
+            $("#ImageCanvas").croppie('bind', { url: getPicture(buddyObj.cID, "contact") }).then(function() {
2716
+               $('.cr-slider').attr({ min: 0.5, max: 3 });
2717
+            });
2718
+    } else if(buddyObj.Type == "group") {
2719
+            $("#ImageCanvas").croppie('bind', { url: getPicture(buddyObj.gID, "group") }).then(function() {
2720
+               $('.cr-slider').attr({ min: 0.5, max: 3 });
2721
+            });
2722
+    }
2723
+
2724
+    // Wireup File Change
2725
+    $("#ebFileUploader").change(function () {
2726
+
2727
+        var filesArray = $(this).prop('files');
2728
+        
2729
+        if (filesArray.length == 1) {
2730
+            var uploadId = Math.floor(Math.random() * 1000000000);
2731
+            var fileObj = filesArray[0];
2732
+            var fileName = fileObj.name;
2733
+            var fileSize = fileObj.size;
2734
+        
2735
+            if (fileSize <= 52428800) {
2736
+                console.log("Adding (" + uploadId + "): " + fileName + " of size: " + fileSize + "bytes");
2737
+      
2738
+                var reader = new FileReader();
2739
+                reader.Name = fileName;
2740
+                reader.UploadId = uploadId;
2741
+                reader.Size = fileSize;
2742
+                reader.onload = function (event) {
2743
+                    $("#ImageCanvas").croppie('bind', {
2744
+                       url: event.target.result
2745
+                    });
2746
+                }
2747
+                reader.readAsDataURL(fileObj);
2748
+            } else {
2749
+                Alert(lang.alert_file_size, lang.error);
2750
+            }
2751
+        } else {
2752
+                Alert(lang.alert_single_file, lang.error);
2753
+        }
2754
+    });
2755
+
2756
+    $("#save_button").click(function() {
2757
+
2758
+      var currentCtctName = $("#AddSomeone_Name").val();
2759
+
2760
+      if (currentCtctName != null && currentCtctName.trim() !== '') {
2761
+
2762
+        if (/^[A-Za-z0-9\s\-\'\[\]\(\)]+$/.test(currentCtctName)) {
2763
+
2764
+            buddyObj.LastActivity = utcDateNow();
2765
+            buddyObj.DisplayName = currentCtctName;
2766
+
2767
+	    var currentDesc = $("#AddSomeone_Desc").val();
2768
+	    if (currentDesc != null && currentDesc.trim() !== '') {
2769
+	        if (/^[A-Za-z0-9\s\-\.\'\"\[\]\(\)\{\}\_\!\?\~\@\%\^\&\*\+\>\<\;\:\=]+$/.test(currentDesc)) { var finCurrentDesc = currentDesc; } else { 
2770
+		    var finCurrentDesc = ''; alert('The title/description that you entered is not valid!'); }
2771
+	    } else { var finCurrentDesc = ''; }
2772
+
2773
+            if(buddyObj.Type == "extension") {
2774
+                buddyObj.Position = finCurrentDesc;
2775
+
2776
+            } else {
2777
+                buddyObj.Description = finCurrentDesc;
2778
+            }
2779
+
2780
+	    var currentExtension = $("#AddSomeone_Exten").val();
2781
+	    if (currentExtension != null && currentExtension.trim() !== '') {
2782
+	        if (/^[a-zA-Z0-9\*\#]+$/.test(currentExtension)) { var finCurrentExtension = currentExtension; } else { 
2783
+		    var finCurrentExtension = ''; alert("The extension that you entered in the 'Extension (Internal)' field is not a valid extension!"); }
2784
+	    } else { var finCurrentExtension = ''; }
2785
+
2786
+            buddyObj.ExtensionNumber = finCurrentExtension;
2787
+
2788
+	    var currentMobile = $("#AddSomeone_Mobile").val();
2789
+	    if (currentMobile != null && currentMobile.trim() !== '') {
2790
+	        if (/^[0-9\s\+\#]+$/.test(currentMobile)) { var finCurrentMobile = currentMobile; } else {
2791
+		    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."); }
2792
+	    } else { var finCurrentMobile = ''; }
2793
+
2794
+            buddyObj.MobileNumber = finCurrentMobile;
2795
+
2796
+	    var currentNum1 = $("#AddSomeone_Num1").val();
2797
+	    if (currentNum1 != null && currentNum1.trim() !== '') {
2798
+	        if (/^[0-9\s\+\#]+$/.test(currentNum1)) { var finCurrentNum1 = currentNum1; } else {
2799
+		    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."); }
2800
+	    } else { var finCurrentNum1 = ''; }
2801
+
2802
+            buddyObj.ContactNumber1 = finCurrentNum1;
2803
+
2804
+	    var currentNum2 = $("#AddSomeone_Num2").val();
2805
+	    if (currentNum2 != null && currentNum2.trim() !== '') {
2806
+	        if (/^[0-9\s\+\#]+$/.test(currentNum2)) { var finCurrentNum2 = currentNum2; } else {
2807
+		    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."); }
2808
+            } else { var finCurrentNum2 = ''; }
2809
+
2810
+            buddyObj.ContactNumber2 = finCurrentNum2;
2811
+
2812
+	    var currentEmail = $("#AddSomeone_Email").val();
2813
+	    if (currentEmail != null && currentEmail.trim() !== '') {
2814
+	        if (/^[A-Za-z0-9\_\.\-\~\%\+\!\?\&\*\^\=\#\$\{\}\|\/]+@[A-Za-z0-9\.\-]+\.[A-Za-z0-9\-]{2,63}$/.test(currentEmail)) { var finCurrentEmail = currentEmail; } else {
2815
+		    var finCurrentEmail = ''; alert("The email that you entered is not a valid email address!"); }
2816
+	    } else { var finCurrentEmail = ''; }
2817
+
2818
+            buddyObj.Email = finCurrentEmail;
2819
+
2820
+
2821
+            // Update Image
2822
+            var constraints = { 
2823
+                type: 'base64', 
2824
+                size: 'viewport', 
2825
+                format: 'png', 
2826
+                quality: 1, 
2827
+                circle: false 
2828
+            }
2829
+
2830
+            $("#ImageCanvas").croppie('result', constraints).then(function(base64) {
2831
+                if(buddyObj.Type == "extension"){
2832
+                    localDB.setItem("img-"+ buddyObj.uID +"-extension", base64);
2833
+                    $("#contact-"+ buddyObj.uID +"-picture-main").css("background-image", 'url('+ getPicture(buddyObj.uID, 'extension') +')');
2834
+                    $("#contact-"+ buddyObj.uID +"-presence-main").html(buddyObj.Position);
2835
+
2836
+                    // Save contact picture to SQL database
2837
+		    var newPic = [];
2838
+                    newPic = [buddyObj.DisplayName, localDB.getItem("img-"+ buddyObj.uID +"-extension", base64)];
2839
+		    saveContactPicToSQLDB(newPic);
2840
+                }
2841
+                else if(buddyObj.Type == "contact") {
2842
+                    localDB.setItem("img-"+ buddyObj.cID +"-contact", base64);
2843
+                    $("#contact-"+ buddyObj.cID +"-picture-main").css("background-image", 'url('+ getPicture(buddyObj.cID, 'contact') +')');
2844
+                    $("#contact-"+ buddyObj.cID +"-presence-main").html(buddyObj.Description);
2845
+
2846
+                    // Save contact picture to SQL database
2847
+		    var newPic = [];
2848
+		    newPic = [buddyObj.DisplayName, localDB.getItem("img-"+ buddyObj.cID +"-contact", base64)];
2849
+		    saveContactPicToSQLDB(newPic);
2850
+                }
2851
+                else if(buddyObj.Type == "group") {
2852
+                    localDB.setItem("img-"+ buddyObj.gID +"-group", base64);
2853
+                    $("#contact-"+ buddyObj.gID +"-picture-main").css("background-image", 'url('+ getPicture(buddyObj.gID, 'group') +')');
2854
+                    $("#contact-"+ buddyObj.gID +"-presence-main").html(buddyObj.Description);
2855
+
2856
+                    // Save contact picture to SQL database
2857
+		    var newPic = [];
2858
+		    newPic = [buddyObj.DisplayName, localDB.getItem("img-"+ buddyObj.gID +"-group", base64)];
2859
+		    saveContactPicToSQLDB(newPic);
2860
+                }
2861
+
2862
+                // Update
2863
+                UpdateBuddyList();
2864
+            });
2865
+
2866
+            // Update: 
2867
+            json.DataCollection[itemId] = buddyObj;
2868
+
2869
+            // Save To DB
2870
+            localDB.setItem(profileUserID + "-Buddies", JSON.stringify(json));
2871
+
2872
+            var newPerson = [];
2873
+
2874
+            newPerson = [currentCtctName, finCurrentDesc, finCurrentExtension, finCurrentMobile, finCurrentNum1, finCurrentNum2, finCurrentEmail, contactDatabaseId];
2875
+
2876
+            updateContactToSQLDB(newPerson);
2877
+
2878
+            // Update the Memory Array, so that the UpdateBuddyList can make the changes
2879
+            for(var b = 0; b < Buddies.length; b++) {
2880
+                if(buddyObj.Type == "extension"){
2881
+                    if(buddyObj.uID == Buddies[b].identity){
2882
+                        Buddies[b].lastActivity = buddyObj.LastActivity;
2883
+                        Buddies[b].CallerIDName = buddyObj.DisplayName;
2884
+                        Buddies[b].Desc = buddyObj.Position;
2885
+                    }                
2886
+                }
2887
+                else if(buddyObj.Type == "contact") {
2888
+                    if(buddyObj.cID == Buddies[b].identity){
2889
+                        Buddies[b].lastActivity = buddyObj.LastActivity;
2890
+                        Buddies[b].CallerIDName = buddyObj.DisplayName;
2891
+                        Buddies[b].Desc = buddyObj.Description;
2892
+                    }                
2893
+                }
2894
+                else if(buddyObj.Type == "group") {
2895
+                
2896
+                }
2897
+            }
2898
+
2899
+            UpdateBuddyList();
2900
+
2901
+            $.jeegoopopup.close();
2902
+            $("#jg_popup_b").empty();
2903
+
2904
+        } else { alert('The display name that you entered is not a valid display name!'); }
2905
+
2906
+      } else { alert("'Display Name' cannot be empty!"); }
2907
+
2908
+    });
2909
+
2910
+    var maxWidth = $(window).width() - 16;
2911
+    var maxHeight = $(window).height() - 110;
2912
+
2913
+    if (maxWidth < 656 || maxHeight < 500) { 
2914
+        $.jeegoopopup.width(maxWidth).height(maxHeight);
2915
+        $.jeegoopopup.center();
2916
+        $("#maximizeImg").hide();
2917
+        $("#minimizeImg").hide();
2918
+    } else { 
2919
+        $.jeegoopopup.width(640).height(500);
2920
+        $.jeegoopopup.center();
2921
+        $("#minimizeImg").hide();
2922
+        $("#maximizeImg").show();
2923
+    }
2924
+
2925
+    $(window).resize(function() {
2926
+        maxWidth = $(window).width() - 16;
2927
+        maxHeight = $(window).height() - 110;
2928
+        $.jeegoopopup.center();
2929
+        if (maxWidth < 656 || maxHeight < 500) { 
2930
+            $.jeegoopopup.width(maxWidth).height(maxHeight);
2931
+            $.jeegoopopup.center();
2932
+            $("#maximizeImg").hide();
2933
+            $("#minimizeImg").hide();
2934
+        } else { 
2935
+            $.jeegoopopup.width(640).height(500);
2936
+            $.jeegoopopup.center();
2937
+            $("#minimizeImg").hide();
2938
+            $("#maximizeImg").show();
2939
+        }
2940
+    });
2941
+
2942
+    $("#minimizeImg").click(function() { $.jeegoopopup.width(640).height(500); $.jeegoopopup.center(); $("#maximizeImg").show(); $("#minimizeImg").hide(); });
2943
+    $("#maximizeImg").click(function() { $.jeegoopopup.width(maxWidth).height(maxHeight); $.jeegoopopup.center(); $("#minimizeImg").show(); $("#maximizeImg").hide(); });
2944
+
2945
+    $("#closeImg").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
2946
+    $("#cancel_button").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
2947
+    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
2948
+    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); $("#jg_popup_b").empty(); } });
2949
+}
2950
+
2951
+// Document Ready
2952
+// ==============
2953
+$(document).ready(function () {
2954
+    
2955
+    // Load Langauge File
2956
+    // ==================
2957
+    $.getJSON(hostingPrefex + "lang/en.json", function (data){
2958
+        lang = data;
2959
+        var userLang = GetAlternateLanguage();
2960
+        if(userLang != ""){
2961
+            $.getJSON(hostingPrefex +"lang/"+ userLang +".json", function (altdata){
2962
+                lang = altdata;
2963
+            }).always(function() {
2964
+                console.log("Alternate Lanaguage Pack loaded: ", lang);
2965
+                InitUi();
2966
+            });
2967
+        }
2968
+        else {
2969
+            console.log("Lanaguage Pack already loaded: ", lang);
2970
+            InitUi();
2971
+        }
2972
+    });
2973
+
2974
+    // Get configuration data from SQL database
2975
+    getConfFromSqldb();
2976
+    getExternalUserConfFromSqldb();
2977
+});
2978
+
2979
+// Init UI
2980
+// =======
2981
+function InitUi(){
2982
+
2983
+    var phone = $("#Phone");
2984
+    phone.empty();
2985
+    phone.attr("class", "pageContainer");
2986
+
2987
+    // Left Section
2988
+    var leftSection = $("<div>");
2989
+    leftSection.attr("id", "leftContent");
2990
+    leftSection.attr("style", "float:left; height: 100%; width:320px");
2991
+
2992
+    var leftHTML = "<table style=\"height:100%; width:100%\" cellspacing=5 cellpadding=0>";
2993
+    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>";
2994
+    leftHTML += "<tr><td class=streamSection style=\"height: 82px\">";
2995
+
2996
+    // Profile User
2997
+    leftHTML += "<div class=profileContainer>";
2998
+    leftHTML += "<div class=contact id=UserProfile style=\"margin-bottom:12px;\">";
2999
+    leftHTML += "<div id=UserProfilePic class=buddyIcon title=\"Status\"></div>";
3000
+    leftHTML += "<span id=reglink class=dotOffline></span>";
3001
+    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>";
3002
+    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>";
3003
+    leftHTML += "<div class=contactNameText style=\"margin-right: 0px;\"><i class=\"fa fa-phone-square\"></i> <span id=UserDID></span> - <span id=UserCallID></span></div>";
3004
+    leftHTML += "<div id=regStatus class=presenceText>&nbsp;</div>";
3005
+    leftHTML += "</div>";
3006
+    // Search / Add Buddies
3007
+    leftHTML += "<div id=searchBoxAndIcons>";
3008
+    leftHTML += "<span class=searchClean><INPUT id=txtFindBuddy type=text autocomplete=none style=\"width:142px;\" title=\"Find Contact\"></span>";
3009
+    leftHTML += "<div id=ButtonsOnSearchLine>";
3010
+    leftHTML += "<button id=BtnFreeDial title='"+ lang.dial_number +"'></button>";
3011
+    leftHTML += "<button id=LaunchVideoConf title='"+ lang.launch_video_conference +"'><i class=\"fa fa-users\"></i></button>";
3012
+    leftHTML += "<button id=BtnSettings title='"+ lang.account_settings +"'><i class=\"fa fa-cog\"></i></button>";
3013
+    leftHTML += "</div>";
3014
+    leftHTML += "</div>";
3015
+    leftHTML += "</div>";
3016
+    leftHTML += "</td></tr>";
3017
+    // Lines & Buddies
3018
+    leftHTML += "<tr><td class=streamSection><div id=myContacts class=\"contactArea cleanScroller\"></div></td></tr>";
3019
+    leftHTML += "</table>";
3020
+
3021
+    leftSection.html(leftHTML);
3022
+    
3023
+    // Right Section
3024
+    var rightSection = $("<div>");
3025
+    rightSection.attr("id", "rightContent");
3026
+    rightSection.attr("style", "margin-left: 320px; height: 100%; overflow: auto;");
3027
+
3028
+    phone.append(leftSection);
3029
+    phone.append(rightSection);
3030
+
3031
+    // Setup Windows
3032
+    windowsCollection = '';
3033
+    messagingCollection = '';
3034
+
3035
+    if(DisableFreeDial == true) $("#BtnFreeDial").hide();
3036
+    if(DisableBuddies == true) $("#BtnAddSomeone").hide();
3037
+    if(enabledGroupServices == false) $("#BtnCreateGroup").hide();
3038
+
3039
+    $("#UserDID").html(profileUser);
3040
+    $("#UserCallID").html(profileName);
3041
+    $("#UserProfilePic").css("background-image", "url('"+ getPicture("profilePicture") +"')");
3042
+    
3043
+    $("#txtFindBuddy").attr("placeholder", lang.find_someone);
3044
+    $("#txtFindBuddy").on('keyup', function(event){
3045
+        UpdateBuddyList();
3046
+    });
3047
+
3048
+    $("#BtnFreeDial").on('click', function(event){
3049
+        ShowDial(this);
3050
+    });
3051
+
3052
+    $("#BtnAddSomeone").attr("title", lang.add_contact);
3053
+    $("#BtnAddSomeone").on('click', function(event){
3054
+        AddSomeoneWindow();
3055
+    });
3056
+
3057
+    $("#BtnCreateGroup").attr("title", lang.create_group);
3058
+    $("#BtnCreateGroup").on('click', function(event){
3059
+        CreateGroupWindow();
3060
+    });
3061
+
3062
+    $("#LaunchVideoConf").on('click', function(event){
3063
+       ShowLaunchVidConfMenu(this);
3064
+    });
3065
+
3066
+    $("#BtnSettings").on('click', function(event){
3067
+       ShowAccountSettingsMenu(this);
3068
+    });
3069
+
3070
+    $("#UserProfile").on('click', function(event){
3071
+        ShowMyProfileMenu(this);
3072
+    });
3073
+
3074
+    UpdateUI();
3075
+    
3076
+    PopulateBuddyList();
3077
+
3078
+    // Select Last user
3079
+    if(localDB.getItem("SelectedBuddy") != null){
3080
+        console.log("Selecting previously selected buddy...", localDB.getItem("SelectedBuddy"));
3081
+        SelectBuddy(localDB.getItem("SelectedBuddy"));
3082
+        UpdateUI();
3083
+    }
3084
+
3085
+    PreloadAudioFiles();
3086
+
3087
+    CreateUserAgent();
3088
+
3089
+    getContactsFromSQLDB();
3090
+
3091
+    generateChatRSAKeys(getDbItem("SipUsername", ""));
3092
+
3093
+    removeTextChatUploads(getDbItem("SipUsername", ""));
3094
+}
3095
+
3096
+function PreloadAudioFiles(){
3097
+    audioBlobs.Alert = { file : "Alert.mp3", url : hostingPrefex +"sounds/Alert.mp3" }
3098
+    audioBlobs.Ringtone = { file : "Ringtone_1.mp3", url : hostingPrefex +"sounds/Ringtone_1.mp3" }
3099
+    audioBlobs.speaker_test = { file : "Speaker_test.mp3", url : hostingPrefex +"sounds/Speaker_test.mp3" }
3100
+    audioBlobs.Busy_UK = { file : "Tone_Busy-UK.mp3", url : hostingPrefex +"sounds/Tone_Busy-UK.mp3" }
3101
+    audioBlobs.Busy_US = { file : "Tone_Busy-US.mp3", url : hostingPrefex +"sounds/Tone_Busy-US.mp3" }
3102
+    audioBlobs.CallWaiting = { file : "Tone_CallWaiting.mp3", url : hostingPrefex +"sounds/Tone_CallWaiting.mp3" }
3103
+    audioBlobs.Congestion_UK = { file : "Tone_Congestion-UK.mp3", url : hostingPrefex +"sounds/Tone_Congestion-UK.mp3" }
3104
+    audioBlobs.Congestion_US = { file : "Tone_Congestion-US.mp3", url : hostingPrefex +"sounds/Tone_Congestion-US.mp3" }
3105
+    audioBlobs.EarlyMedia_Australia = { file : "Tone_EarlyMedia-Australia.mp3", url : hostingPrefex +"sounds/Tone_EarlyMedia-Australia.mp3" }
3106
+    audioBlobs.EarlyMedia_European = { file : "Tone_EarlyMedia-European.mp3", url : hostingPrefex +"sounds/Tone_EarlyMedia-European.mp3" }
3107
+    audioBlobs.EarlyMedia_Japan = { file : "Tone_EarlyMedia-Japan.mp3", url : hostingPrefex +"sounds/Tone_EarlyMedia-Japan.mp3" }
3108
+    audioBlobs.EarlyMedia_UK = { file : "Tone_EarlyMedia-UK.mp3", url : hostingPrefex +"sounds/Tone_EarlyMedia-UK.mp3" }
3109
+    audioBlobs.EarlyMedia_US = { file : "Tone_EarlyMedia-US.mp3", url : hostingPrefex +"sounds/Tone_EarlyMedia-US.mp3" }
3110
+    
3111
+    $.each(audioBlobs, function (i, item) {
3112
+        var oReq = new XMLHttpRequest();
3113
+        oReq.open("GET", item.url, true);
3114
+        oReq.responseType = "blob";
3115
+        oReq.onload = function(oEvent) {
3116
+            var reader = new FileReader();
3117
+            reader.readAsDataURL(oReq.response);
3118
+            reader.onload = function() {
3119
+                item.blob = reader.result;
3120
+            }
3121
+        }
3122
+        oReq.send();
3123
+    });
3124
+}
3125
+// Create User Agent
3126
+// =================
3127
+function CreateUserAgent() {
3128
+
3129
+    $.ajax({
3130
+        'async': false,
3131
+        'global': false,
3132
+        type: "POST",
3133
+        url: "get-sippass.php",
3134
+        dataType: "JSON",
3135
+        data: {
3136
+                username: userName,
3137
+                s_ajax_call: validateSToken
3138
+        },
3139
+        success: function (sipdatafromdb) {
3140
+                       decSipPass = sipdatafromdb;
3141
+        },
3142
+        error: function(sipdatafromdb) {
3143
+                 alert("An error occurred while attempting to retrieve data from the database!");
3144
+        }
3145
+    });
3146
+
3147
+    try {
3148
+        console.log("Creating User Agent...");
3149
+        var options = {
3150
+            displayName: profileName,
3151
+            uri: SipUsername + "@" + wssServer,
3152
+            transportOptions: {
3153
+                wsServers: "wss://" + wssServer + ":"+ WebSocketPort +""+ ServerPath,
3154
+                traceSip: false,
3155
+                connectionTimeout: TransportConnectionTimeout,
3156
+                maxReconnectionAttempts: TransportReconnectionAttempts,
3157
+                reconnectionTimeout: TransportReconnectionTimeout,
3158
+            },
3159
+            sessionDescriptionHandlerFactoryOptions:{
3160
+                peerConnectionOptions :{
3161
+                    alwaysAcquireMediaFirst: true, // Better for firefox, but seems to have no effect on others
3162
+                    iceCheckingTimeout: IceStunCheckTimeout,
3163
+                    rtcConfiguration: {}
3164
+                }
3165
+            },
3166
+            authorizationUser: SipUsername,
3167
+//            password: SipPassword,
3168
+            password: decSipPass,
3169
+            registerExpires: RegisterExpires,
3170
+            hackWssInTransport: WssInTransport,
3171
+            hackIpInContact: IpInContact,
3172
+            userAgentString: userAgentStr,
3173
+            autostart: false,
3174
+            register: false,
3175
+        }
3176
+
3177
+        decSipPass = '';
3178
+
3179
+        var currentStunServer = getDbItem("StunServer", "");
3180
+
3181
+        if (currentStunServer == '' || currentStunServer == null || typeof currentStunServer == 'undefined') { 
3182
+            var IceStunServersList = '';
3183
+        } else { var IceStunServersList = '[{"urls":"stun:'+currentStunServer+'"}]'; }
3184
+
3185
+        if (IceStunServersList != "") {
3186
+            options.sessionDescriptionHandlerFactoryOptions.peerConnectionOptions.rtcConfiguration.iceServers = JSON.parse(IceStunServersList);
3187
+        }
3188
+
3189
+        userAgent = new SIP.UA(options);
3190
+        console.log("Creating User Agent... Done");
3191
+    }
3192
+    catch (e) {
3193
+        console.error("Error creating User Agent: "+ e);
3194
+        $("#regStatus").html(lang.error_user_agant);
3195
+        alert(e.message);
3196
+        return;
3197
+    }
3198
+
3199
+    // UA Register events
3200
+    userAgent.on('registered', function () {
3201
+        // This code fires on re-regiter after session timeout
3202
+        // to ensure that events are not fired multiple times
3203
+        // an isReRegister state is kept.
3204
+        if(!isReRegister) {
3205
+            console.log("Registered!");
3206
+
3207
+            $("#reglink").hide();
3208
+            $("#dereglink").show();
3209
+            if(DoNotDisturbEnabled || DoNotDisturbPolicy == "enabled") {
3210
+                $("#dereglink").attr("class", "dotDoNotDisturb");
3211
+            }
3212
+
3213
+            // Start Subscribe Loop
3214
+            SubscribeAll();
3215
+
3216
+            // Output to status
3217
+            $("#regStatus").html(lang.registered);
3218
+
3219
+            // Custom Web hook
3220
+            if(typeof web_hook_on_register !== 'undefined') web_hook_on_register(userAgent);
3221
+        }
3222
+        isReRegister = true;
3223
+    });
3224
+
3225
+    userAgent.on('registrationFailed', function (response, cause) {
3226
+        console.log("Registration Failed: " + cause);
3227
+        $("#regStatus").html(lang.registration_failed);
3228
+
3229
+        $("#reglink").show();
3230
+        $("#dereglink").hide();
3231
+
3232
+        // We set this flag here so that the re-register attepts are fully completed.
3233
+        isReRegister = false;
3234
+
3235
+        // Custom Web hook
3236
+        if(typeof web_hook_on_registrationFailed !== 'undefined') web_hook_on_registrationFailed(cause);
3237
+    });
3238
+    userAgent.on('unregistered', function () {
3239
+        console.log("Unregistered, bye!");
3240
+        $("#regStatus").html(lang.unregistered);
3241
+
3242
+        $("#reglink").show();
3243
+        $("#dereglink").hide();
3244
+
3245
+        // Custom Web hook
3246
+        if(typeof web_hook_on_unregistered !== 'undefined') web_hook_on_unregistered();
3247
+    });
3248
+
3249
+    // UA transport
3250
+    userAgent.on('transportCreated', function (transport) {
3251
+        console.log("Transport Object Created");
3252
+        
3253
+        // Transport Events
3254
+        transport.on('connected', function () {
3255
+            console.log("Connected to Web Socket!");
3256
+            $("#regStatus").html(lang.connected_to_web_socket);
3257
+
3258
+            $("#WebRtcFailed").hide();
3259
+
3260
+            window.setTimeout(function (){
3261
+                Register();
3262
+            }, 500);
3263
+
3264
+        });
3265
+        transport.on('disconnected', function () {
3266
+            console.log("Disconnected from Web Socket!");
3267
+            $("#regStatus").html(lang.disconnected_from_web_socket);
3268
+
3269
+            // We set this flag here so that the re-register attepts are fully completed.
3270
+            isReRegister = false;
3271
+        });
3272
+        transport.on('transportError', function () {
3273
+            console.log("Web Socket error!");
3274
+            $("#regStatus").html(lang.web_socket_error);
3275
+
3276
+            $("#WebRtcFailed").show();
3277
+
3278
+            // Custom Web hook
3279
+            if(typeof web_hook_on_transportError !== 'undefined') web_hook_on_transportError(transport, userAgent);
3280
+        });
3281
+    });
3282
+
3283
+    // Inbound Calls
3284
+    userAgent.on("invite", function (session) {
3285
+
3286
+        ReceiveCall(session);
3287
+
3288
+        // Show a system notification when the phone rings
3289
+        if (getDbItem("Notifications", "") == 1) {
3290
+            incomingCallNote();
3291
+        }
3292
+
3293
+        changePageTitle();
3294
+
3295
+        // Custom Web hook
3296
+        if(typeof web_hook_on_invite !== 'undefined') web_hook_on_invite(session);
3297
+    });
3298
+
3299
+    // Inbound Text Message
3300
+    userAgent.on('message', function (message) {
3301
+        ReceiveMessage(message);
3302
+
3303
+        // Custom Web hook
3304
+        if(typeof web_hook_on_message !== 'undefined') web_hook_on_message(message);
3305
+    });
3306
+
3307
+    // Start the WebService Connection loop
3308
+    console.log("Connecting to Web Socket...");
3309
+    $("#regStatus").html(lang.connecting_to_web_socket);
3310
+    userAgent.start();
3311
+    
3312
+    // Register Buttons
3313
+    $("#reglink").on('click', Register);
3314
+
3315
+    // WebRTC Error Page
3316
+    $("#WebRtcFailed").on('click', function(){
3317
+        Confirm(lang.error_connecting_web_socket, lang.web_socket_error, function(){
3318
+            window.open("https://"+ wssServer +":"+ WebSocketPort +"/httpstatus");
3319
+        }, null);
3320
+    });
3321
+}
3322
+
3323
+
3324
+// Registration
3325
+// ============
3326
+function Register() {
3327
+
3328
+    if (userAgent == null || userAgent.isRegistered()) return;
3329
+
3330
+    console.log("Sending Registration...");
3331
+    $("#regStatus").html(lang.sending_registration);
3332
+    userAgent.register();
3333
+
3334
+    if (getDbItem("Notifications", "") == 1) {
3335
+          if (Notification.permission != "granted") {
3336
+              Notification.requestPermission();
3337
+          }
3338
+    }
3339
+}
3340
+function Unregister() {
3341
+    if (userAgent == null || !userAgent.isRegistered()) return;
3342
+
3343
+    console.log("Unsubscribing...");
3344
+    $("#regStatus").html(lang.unsubscribing);
3345
+    try {
3346
+        UnsubscribeAll();
3347
+    } catch (e) { }
3348
+
3349
+    console.log("Disconnecting...");
3350
+    $("#regStatus").html(lang.disconnecting);
3351
+    userAgent.unregister();
3352
+
3353
+    isReRegister = false;
3354
+}
3355
+
3356
+// Inbound Calls
3357
+// =============
3358
+function ReceiveCall(session) {
3359
+    var callerID = session.remoteIdentity.displayName;
3360
+    var did = session.remoteIdentity.uri.user;
3361
+
3362
+    if ( typeof callerID == 'undefined') { callerID = ""; }
3363
+
3364
+    console.log("New Incoming Call!", callerID +" <"+ did +">");
3365
+
3366
+    var CurrentCalls = countSessions(session.id);
3367
+    console.log("Current Call Count:", CurrentCalls);
3368
+
3369
+    var buddyObj = FindBuddyByDid(did);
3370
+    // Make new contact if it's not there
3371
+    if(buddyObj == null) {
3372
+        var buddyType = (did.length > DidLength)? "contact" : "extension";
3373
+        var focusOnBuddy = (CurrentCalls==0);
3374
+        buddyObj = MakeBuddy(buddyType, true, focusOnBuddy, true, callerID, did);
3375
+    } else {
3376
+        // Double check that the buddy has the same caller ID as the incoming call
3377
+        // With Buddies that are contacts, eg +441234567890 <+441234567890> leave as is
3378
+        if(buddyObj.type == "extension" && buddyObj.CallerIDName != callerID){
3379
+            UpdateBuddyCalerID(buddyObj, callerID);
3380
+        }
3381
+        else if(buddyObj.type == "contact" && callerID != did && buddyObj.CallerIDName != callerID){
3382
+            UpdateBuddyCalerID(buddyObj, callerID);
3383
+        }
3384
+    }
3385
+    var buddy = buddyObj.identity;
3386
+
3387
+    // Time Stamp
3388
+    window.clearInterval(session.data.callTimer);
3389
+    var startTime = moment.utc();
3390
+    session.data.callstart = startTime.format("YYYY-MM-DD HH:mm:ss UTC");
3391
+    $("#contact-" + buddy + "-timer").show();
3392
+    session.data.callTimer = window.setInterval(function(){
3393
+        var now = moment.utc();
3394
+        var duration = moment.duration(now.diff(startTime)); 
3395
+        $("#contact-" + buddy + "-timer").html(formatShortDuration(duration.asSeconds()));
3396
+    }, 1000);
3397
+    session.data.buddyId = buddy;
3398
+    session.data.calldirection = "inbound";
3399
+    session.data.terminateby = "them";
3400
+    session.data.withvideo = false;
3401
+    var videoInvite = false;
3402
+    if (session.request.body) {
3403
+        // Asterisk 13 PJ_SIP always sends m=video if endpoint has video codec,
3404
+        // even if origional invite does not specify video.
3405
+        if (session.request.body.indexOf("m=video") > -1) {
3406
+           videoInvite = true;
3407
+           if (buddyObj.type == "contact"){
3408
+                videoInvite = false;
3409
+           }
3410
+        }
3411
+    }
3412
+
3413
+    // Inbound You or They Rejected
3414
+    session.on('rejected', function (response, cause) {
3415
+        console.log("Call rejected: " + cause);
3416
+
3417
+        session.data.reasonCode = response.status_code
3418
+        session.data.reasonText = cause
3419
+    
3420
+        AddCallMessage(buddy, session, response.status_code, cause);
3421
+
3422
+        // Custom Web hook
3423
+        if(typeof web_hook_on_terminate !== 'undefined') web_hook_on_terminate(session);
3424
+    });
3425
+    // They cancelled (Gets called regardless)
3426
+    session.on('terminated', function(response, cause) {
3427
+
3428
+        // Stop the ringtone
3429
+        if(session.data.rinngerObj){
3430
+            session.data.rinngerObj.pause();
3431
+            session.data.rinngerObj.removeAttribute('src');
3432
+            session.data.rinngerObj.load();
3433
+            session.data.rinngerObj = null;
3434
+        }
3435
+
3436
+        $.jeegoopopup.close();
3437
+        console.log("Call terminated");
3438
+
3439
+        window.clearInterval(session.data.callTimer);
3440
+
3441
+        $("#contact-" + buddy + "-timer").html("");
3442
+        $("#contact-" + buddy + "-timer").hide();
3443
+        $("#contact-" + buddy + "-msg").html("");
3444
+        $("#contact-" + buddy + "-msg").hide();
3445
+        $("#contact-" + buddy + "-AnswerCall").hide();
3446
+
3447
+        RefreshStream(buddyObj);
3448
+        updateScroll(buddyObj.identity);
3449
+        UpdateBuddyList();
3450
+    });
3451
+
3452
+    // Start Handle Call
3453
+    if(DoNotDisturbEnabled || DoNotDisturbPolicy == "enabled") {
3454
+        console.log("Do Not Disturb Enabled, rejecting call.");
3455
+        RejectCall(buddyObj.identity);
3456
+        return;
3457
+    }
3458
+    if(CurrentCalls >= 1){
3459
+        if(CallWaitingEnabled == false || CallWaitingEnabled == "disabled"){
3460
+            console.log("Call Waiting Disabled, rejecting call.");
3461
+            RejectCall(buddyObj.identity);
3462
+            return;
3463
+        }
3464
+    }
3465
+    if(AutoAnswerEnabled || AutoAnswerPolicy == "enabled"){
3466
+        if(CurrentCalls == 0){ // There are no other calls, so you can answer
3467
+            console.log("Auto Answer Call...");
3468
+            var buddyId = buddyObj.identity;
3469
+            window.setTimeout(function(){
3470
+                // If the call is with video, assume the auto answer is also
3471
+                // In order for this to work nicely, the recipient must be "ready" to accept video calls
3472
+                // In order to ensure video call compatibility (i.e. the recipient must have their web cam in, and working)
3473
+                // The NULL video should be configured
3474
+                // https://github.com/InnovateAsterisk/Browser-Phone/issues/26
3475
+                if(videoInvite) {
3476
+                    AnswerVideoCall(buddyId)
3477
+                }
3478
+                else {
3479
+                    AnswerAudioCall(buddyId);
3480
+                }
3481
+            }, 1000);
3482
+
3483
+            // Select Buddy
3484
+            SelectBuddy(buddyObj.identity);
3485
+            return;
3486
+        }
3487
+        else {
3488
+            console.warn("Could not auto answer call, already on a call.");
3489
+        }
3490
+    }
3491
+    
3492
+    // Show the Answer Thingy
3493
+    $("#contact-" + buddyObj.identity + "-msg").html(lang.incomming_call_from +" " + callerID +" &lt;"+ did +"&gt;");
3494
+    $("#contact-" + buddyObj.identity + "-msg").show();
3495
+    if(videoInvite){
3496
+        $("#contact-"+ buddyObj.identity +"-answer-video").show();
3497
+    }
3498
+    else {
3499
+        $("#contact-"+ buddyObj.identity +"-answer-video").hide();
3500
+    }
3501
+    $("#contact-" + buddyObj.identity + "-AnswerCall").show();
3502
+    updateScroll(buddyObj.identity);
3503
+
3504
+    // Play Ring Tone if not on the phone
3505
+    if(CurrentCalls >= 1){
3506
+
3507
+        // Play Alert
3508
+        console.log("Audio:", audioBlobs.CallWaiting.url);
3509
+        var rinnger = new Audio(audioBlobs.CallWaiting.blob);
3510
+        rinnger.preload = "auto";
3511
+        rinnger.loop = false;
3512
+        rinnger.oncanplaythrough = function(e) {
3513
+            if (typeof rinnger.sinkId !== 'undefined' && getRingerOutputID() != "default") {
3514
+                rinnger.setSinkId(getRingerOutputID()).then(function() {
3515
+                    console.log("Set sinkId to:", getRingerOutputID());
3516
+                }).catch(function(e){
3517
+                    console.warn("Failed not apply setSinkId.", e);
3518
+                });
3519
+            }
3520
+            // If there has been no interaction with the page at all... this page will not work
3521
+            rinnger.play().then(function(){
3522
+               // Audio Is Playing
3523
+            }).catch(function(e){
3524
+                console.warn("Unable to play audio file.", e);
3525
+            }); 
3526
+        }
3527
+        session.data.rinngerObj = rinnger;
3528
+    } else {
3529
+        // Play Ring Tone
3530
+        console.log("Audio:", audioBlobs.Ringtone.url);
3531
+        var rinnger = new Audio(audioBlobs.Ringtone.blob);
3532
+        rinnger.preload = "auto";
3533
+        rinnger.loop = true;
3534
+        rinnger.oncanplaythrough = function(e) {
3535
+            if (typeof rinnger.sinkId !== 'undefined' && getRingerOutputID() != "default") {
3536
+                rinnger.setSinkId(getRingerOutputID()).then(function() {
3537
+                    console.log("Set sinkId to:", getRingerOutputID());
3538
+                }).catch(function(e){
3539
+                    console.warn("Failed not apply setSinkId.", e);
3540
+                });
3541
+            }
3542
+            // If there has been no interaction with the page at all... this page will not work
3543
+            rinnger.play().then(function(){
3544
+               // Audio Is Playing
3545
+            }).catch(function(e){
3546
+                console.warn("Unable to play audio file.", e);
3547
+            }); 
3548
+        }
3549
+        session.data.rinngerObj = rinnger;
3550
+    }
3551
+
3552
+    $.jeegoopopup.close();
3553
+
3554
+    // Show Call Answer Window
3555
+    var callAnswerHtml = '<div id="windowCtrls"><img id="closeImg" src="images/3_close.svg" title="Close" /></div>';
3556
+    callAnswerHtml += "<div class=\"UiWindowField scroller\" style=\"text-align:center\">";
3557
+    callAnswerHtml += "<div style=\"font-size: 18px; margin-top:1px\">"+ callerID + "<div>";
3558
+    if(callerID != did) {
3559
+            callAnswerHtml += "<div style=\"font-size: 18px; margin-top:1px\">&lt;"+ did + "&gt;<div>";
3560
+    }
3561
+    callAnswerHtml += "<div class=callAnswerBuddyIcon style=\"background-image: url("+ getPicture(buddyObj.identity) +"); margin-top:6px\"></div>";
3562
+    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>";
3563
+    if(videoInvite) {
3564
+            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>";
3565
+    }
3566
+    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>";
3567
+    callAnswerHtml += "</div>";
3568
+
3569
+    $.jeegoopopup.open({
3570
+                title: 'Incoming Call',
3571
+                html: callAnswerHtml,
3572
+                width: '290',
3573
+                height: '300',
3574
+                center: true,
3575
+                scrolling: 'no',
3576
+                skinClass: 'jg_popup_basic',
3577
+                overlay: true,
3578
+                opacity: 50,
3579
+                draggable: true,
3580
+                resizable: false,
3581
+                fadeIn: 0
3582
+    });
3583
+
3584
+    $("#closeImg").click(function() { $.jeegoopopup.close(); });
3585
+    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); });
3586
+    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); } });
3587
+
3588
+    // Add a notification badge
3589
+    IncreaseMissedBadge(buddyObj.identity);
3590
+
3591
+    // Show notification
3592
+    // =================
3593
+    if ("Notification" in window) {
3594
+        if (getDbItem("Notifications", "") == 1) {
3595
+            var noticeOptions = { body: lang.incomming_call_from +" " + callerID +" \""+ did +"\"", icon: getPicture(buddyObj.identity) }
3596
+            var inComingCallNotification = new Notification(lang.incomming_call, noticeOptions);
3597
+            inComingCallNotification.onclick = function (event) {
3598
+
3599
+                var buddyId = buddyObj.identity;
3600
+                window.setTimeout(function() {
3601
+                    // https://github.com/InnovateAsterisk/Browser-Phone/issues/26
3602
+                    if(videoInvite) {
3603
+                            AnswerVideoCall(buddyId)
3604
+                    } else {
3605
+                            AnswerAudioCall(buddyId);
3606
+                    }
3607
+                }, 4000);
3608
+
3609
+                // Select Buddy
3610
+                SelectBuddy(buddyObj.identity);
3611
+
3612
+                return;
3613
+            }
3614
+        }
3615
+    }
3616
+
3617
+}
3618
+
3619
+function AnswerAudioCall(buddy) {
3620
+
3621
+    $.jeegoopopup.close();
3622
+
3623
+    var buddyObj = FindBuddyByIdentity(buddy);
3624
+    if(buddyObj == null) {
3625
+        console.warn("Audio Answer failed, null buddy");
3626
+        $("#contact-" + buddy + "-msg").html(lang.call_failed);
3627
+        $("#contact-" + buddy + "-AnswerCall").hide();
3628
+        return;
3629
+    }
3630
+
3631
+    var session = getSession(buddy);
3632
+    if (session == null) {
3633
+        console.warn("Audio Answer failed, null session");
3634
+        $("#contact-" + buddy + "-msg").html(lang.call_failed);
3635
+        $("#contact-" + buddy + "-AnswerCall").hide();
3636
+        return;
3637
+    }
3638
+    
3639
+    // Stop the ringtone
3640
+    if(session.data.rinngerObj){
3641
+        session.data.rinngerObj.pause();
3642
+        session.data.rinngerObj.removeAttribute('src');
3643
+        session.data.rinngerObj.load();
3644
+        session.data.rinngerObj = null;
3645
+    }
3646
+
3647
+    // Check vitals
3648
+    if(HasAudioDevice == false){
3649
+        Alert(lang.alert_no_microphone);
3650
+        $("#contact-" + buddy + "-msg").html(lang.call_failed);
3651
+        $("#contact-" + buddy + "-AnswerCall").hide();
3652
+        return;
3653
+    }
3654
+    $("#contact-" + buddy + "-timer").html("");
3655
+    $("#contact-" + buddy + "-timer").hide();
3656
+    $("#contact-" + buddy + "-msg").html("");
3657
+    $("#contact-" + buddy + "-msg").hide();
3658
+    $("#contact-" + buddy + "-AnswerCall").hide();
3659
+
3660
+    // Create a new Line and move the session over to the line
3661
+    var callerID = session.remoteIdentity.displayName;
3662
+    var did = session.remoteIdentity.uri.user;
3663
+    newLineNumber = newLineNumber + 1;
3664
+    lineObj = new Line(newLineNumber, callerID, did, buddyObj);
3665
+    lineObj.SipSession = session;
3666
+    lineObj.SipSession.data.line = lineObj.LineNumber;
3667
+    lineObj.SipSession.data.buddyId = lineObj.BuddyObj.identity;
3668
+    Lines.push(lineObj);
3669
+    AddLineHtml(lineObj);
3670
+    SelectLine(newLineNumber);
3671
+    UpdateBuddyList();
3672
+
3673
+    var supportedConstraints = navigator.mediaDevices.getSupportedConstraints();
3674
+    var spdOptions = {
3675
+        sessionDescriptionHandlerOptions: {
3676
+            constraints: {
3677
+                audio: { deviceId : "default" },
3678
+                video: false
3679
+            }
3680
+        }
3681
+    }
3682
+
3683
+    // Configure Audio
3684
+    var currentAudioDevice = getAudioSrcID();
3685
+    if(currentAudioDevice != "default"){
3686
+        var confirmedAudioDevice = false;
3687
+        for (var i = 0; i < AudioinputDevices.length; ++i) {
3688
+            if(currentAudioDevice == AudioinputDevices[i].deviceId) {
3689
+                confirmedAudioDevice = true;
3690
+                break;
3691
+            }
3692
+        }
3693
+        if(confirmedAudioDevice) {
3694
+            spdOptions.sessionDescriptionHandlerOptions.constraints.audio.deviceId = { exact: currentAudioDevice }
3695
+        }
3696
+        else {
3697
+            console.warn("The audio device you used before is no longer available, default settings applied.");
3698
+            localDB.setItem("AudioSrcId", "default");
3699
+        }
3700
+    }
3701
+    // Add additional Constraints
3702
+    if(supportedConstraints.autoGainControl) {
3703
+        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.autoGainControl = AutoGainControl;
3704
+    }
3705
+    if(supportedConstraints.echoCancellation) {
3706
+        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.echoCancellation = EchoCancellation;
3707
+    }
3708
+    if(supportedConstraints.noiseSuppression) {
3709
+        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.noiseSuppression = NoiseSuppression;
3710
+    }
3711
+
3712
+    // Send Answer
3713
+    lineObj.SipSession.accept(spdOptions);
3714
+    lineObj.SipSession.data.withvideo = false;
3715
+    lineObj.SipSession.data.VideoSourceDevice = null;
3716
+    lineObj.SipSession.data.AudioSourceDevice = getAudioSrcID();
3717
+    lineObj.SipSession.data.AudioOutputDevice = getAudioOutputID();
3718
+
3719
+    // Wire up UI
3720
+    wireupAudioSession(lineObj);
3721
+    $("#contact-" + buddy + "-msg").html(lang.call_in_progress);
3722
+
3723
+    // Clear Answer Buttons
3724
+    $("#contact-" + buddy + "-AnswerCall").hide();
3725
+}
3726
+
3727
+function AnswerVideoCall(buddy) {
3728
+
3729
+    $.jeegoopopup.close();
3730
+
3731
+    var buddyObj = FindBuddyByIdentity(buddy);
3732
+    if(buddyObj == null) {
3733
+        console.warn("Audio Answer failed, null buddy");
3734
+        $("#contact-" + buddy + "-msg").html(lang.call_failed);
3735
+        $("#contact-" + buddy + "-AnswerCall").hide();
3736
+        return;
3737
+    }
3738
+
3739
+    var session = getSession(buddy);
3740
+    if (session == null) {
3741
+        console.warn("Video Answer failed, null session");
3742
+        $("#contact-" + buddy + "-msg").html(lang.call_failed);
3743
+        $("#contact-" + buddy + "-AnswerCall").hide();
3744
+        return;
3745
+    }
3746
+
3747
+    // Stop the ringtone
3748
+    if(session.data.rinngerObj){
3749
+        session.data.rinngerObj.pause();
3750
+        session.data.rinngerObj.removeAttribute('src');
3751
+        session.data.rinngerObj.load();
3752
+        session.data.rinngerObj = null;
3753
+    }
3754
+
3755
+    // Check vitals
3756
+    if(HasAudioDevice == false){
3757
+        Alert(lang.alert_no_microphone);
3758
+        $("#contact-" + buddy + "-msg").html(lang.call_failed);
3759
+        $("#contact-" + buddy + "-AnswerCall").hide();
3760
+        return;
3761
+    }
3762
+    if(HasVideoDevice == false){
3763
+        console.warn("No video devices (webcam) found, switching to audio call.");
3764
+        AnswerAudioCall(buddy);
3765
+        return;
3766
+    }
3767
+    $("#contact-" + buddy + "-timer").html("");
3768
+    $("#contact-" + buddy + "-timer").hide();
3769
+    $("#contact-" + buddy + "-msg").html("");
3770
+    $("#contact-" + buddy + "-msg").hide();
3771
+    $("#contact-" + buddy + "-AnswerCall").hide();
3772
+
3773
+    // Create a new Line and move the session over to the line
3774
+    var callerID = session.remoteIdentity.displayName;
3775
+    var did = session.remoteIdentity.uri.user;
3776
+    newLineNumber = newLineNumber + 1;
3777
+    lineObj = new Line(newLineNumber, callerID, did, buddyObj);
3778
+    lineObj.SipSession = session;
3779
+    lineObj.SipSession.data.line = lineObj.LineNumber;
3780
+    lineObj.SipSession.data.buddyId = lineObj.BuddyObj.identity;
3781
+    Lines.push(lineObj);
3782
+    AddLineHtml(lineObj);
3783
+    SelectLine(newLineNumber);
3784
+    UpdateBuddyList();
3785
+
3786
+    var supportedConstraints = navigator.mediaDevices.getSupportedConstraints();
3787
+    var spdOptions = {
3788
+        sessionDescriptionHandlerOptions: {
3789
+            constraints: {
3790
+                audio: { deviceId : "default" },
3791
+                video: { deviceId : "default" }
3792
+            }
3793
+        }
3794
+    }
3795
+
3796
+    // Configure Audio
3797
+    var currentAudioDevice = getAudioSrcID();
3798
+    if(currentAudioDevice != "default"){
3799
+        var confirmedAudioDevice = false;
3800
+        for (var i = 0; i < AudioinputDevices.length; ++i) {
3801
+            if(currentAudioDevice == AudioinputDevices[i].deviceId) {
3802
+                confirmedAudioDevice = true;
3803
+                break;
3804
+            }
3805
+        }
3806
+        if(confirmedAudioDevice) {
3807
+            spdOptions.sessionDescriptionHandlerOptions.constraints.audio.deviceId = { exact: currentAudioDevice }
3808
+        }
3809
+        else {
3810
+            console.warn("The audio device you used before is no longer available, default settings applied.");
3811
+            localDB.setItem("AudioSrcId", "default");
3812
+        }
3813
+    }
3814
+    // Add additional Constraints
3815
+    if(supportedConstraints.autoGainControl) {
3816
+        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.autoGainControl = AutoGainControl;
3817
+    }
3818
+    if(supportedConstraints.echoCancellation) {
3819
+        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.echoCancellation = EchoCancellation;
3820
+    }
3821
+    if(supportedConstraints.noiseSuppression) {
3822
+        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.noiseSuppression = NoiseSuppression;
3823
+    }
3824
+
3825
+    // Configure Video
3826
+    var currentVideoDevice = getVideoSrcID();
3827
+    if(currentVideoDevice != "default"){
3828
+        var confirmedVideoDevice = false;
3829
+        for (var i = 0; i < VideoinputDevices.length; ++i) {
3830
+            if(currentVideoDevice == VideoinputDevices[i].deviceId) {
3831
+                confirmedVideoDevice = true;
3832
+                break;
3833
+            }
3834
+        }
3835
+        if(confirmedVideoDevice){
3836
+            spdOptions.sessionDescriptionHandlerOptions.constraints.video.deviceId = { exact: currentVideoDevice }
3837
+        }
3838
+        else {
3839
+            console.warn("The video device you used before is no longer available, default settings applied.");
3840
+            localDB.setItem("VideoSrcId", "default"); // resets for later and subsequent calls
3841
+        }
3842
+    }
3843
+    // Add additional Constraints
3844
+    if(supportedConstraints.frameRate && maxFrameRate != "") {
3845
+        spdOptions.sessionDescriptionHandlerOptions.constraints.video.frameRate = maxFrameRate;
3846
+    }
3847
+    if(supportedConstraints.height && videoHeight != "") {
3848
+        spdOptions.sessionDescriptionHandlerOptions.constraints.video.height = videoHeight;
3849
+    }
3850
+    if(supportedConstraints.aspectRatio && videoAspectRatio != "") {
3851
+        spdOptions.sessionDescriptionHandlerOptions.constraints.video.aspectRatio = videoAspectRatio;
3852
+    }
3853
+
3854
+    // Send Answer
3855
+    lineObj.SipSession.data.withvideo = true;
3856
+    lineObj.SipSession.data.VideoSourceDevice = getVideoSrcID();
3857
+    lineObj.SipSession.data.AudioSourceDevice = getAudioSrcID();
3858
+    lineObj.SipSession.data.AudioOutputDevice = getAudioOutputID();
3859
+
3860
+    // Send Answer
3861
+    // If this fails, it must still wireup the call so we can manually close it
3862
+    $("#contact-" + buddy + "-msg").html(lang.call_in_progress);
3863
+    // Wire up UI
3864
+    wireupVideoSession(lineObj);
3865
+
3866
+    try{
3867
+        lineObj.SipSession.accept(spdOptions);
3868
+        if(StartVideoFullScreen) ExpandVideoArea(lineObj.LineNumber);
3869
+        $("#contact-" + buddy + "-AnswerCall").hide();
3870
+    }
3871
+    catch(e){
3872
+        console.warn("Failed to answer call", e, lineObj.SipSession);
3873
+        teardownSession(lineObj, 500, "Client Error");
3874
+    }
3875
+
3876
+}
3877
+
3878
+function RejectCall(buddy) {
3879
+    var session = getSession(buddy);
3880
+    if (session == null) {
3881
+        console.warn("Reject failed, null session");
3882
+        $("#contact-" + buddy + "-msg").html(lang.call_failed);
3883
+        $("#contact-" + buddy + "-AnswerCall").hide();
3884
+    }
3885
+    session.data.terminateby = "us";
3886
+    session.reject({ 
3887
+        statusCode: 486, 
3888
+        reasonPhrase: "Rejected by us"
3889
+    });
3890
+    $("#contact-" + buddy + "-msg").html(lang.call_rejected);
3891
+}
3892
+
3893
+// Session Wireup
3894
+// ==============
3895
+function wireupAudioSession(lineObj) {
3896
+    if (lineObj == null) return;
3897
+
3898
+    var MessageObjId = "#line-" + lineObj.LineNumber + "-msg";
3899
+    var session = lineObj.SipSession;
3900
+
3901
+    session.on('progress', function (response) {
3902
+        // Provisional 1xx
3903
+        if(response.status_code == 100){
3904
+            $(MessageObjId).html(lang.trying);
3905
+        } else if(response.status_code == 180){
3906
+            $(MessageObjId).html(lang.ringing);
3907
+            
3908
+            var soundFile = audioBlobs.EarlyMedia_European;
3909
+            if(UserLocale().indexOf("us") > -1) soundFile = audioBlobs.EarlyMedia_US;
3910
+            if(UserLocale().indexOf("gb") > -1) soundFile = audioBlobs.EarlyMedia_UK;
3911
+            if(UserLocale().indexOf("au") > -1) soundFile = audioBlobs.EarlyMedia_Australia;
3912
+            if(UserLocale().indexOf("jp") > -1) soundFile = audioBlobs.EarlyMedia_Japan;
3913
+
3914
+            // Play Early Media
3915
+            console.log("Audio:", soundFile.url);
3916
+            var earlyMedia = new Audio(soundFile.blob);
3917
+            earlyMedia.preload = "auto";
3918
+            earlyMedia.loop = true;
3919
+            earlyMedia.oncanplaythrough = function(e) {
3920
+                if (typeof earlyMedia.sinkId !== 'undefined' && getAudioOutputID() != "default") {
3921
+                    earlyMedia.setSinkId(getAudioOutputID()).then(function() {
3922
+                        console.log("Set sinkId to:", getAudioOutputID());
3923
+                    }).catch(function(e){
3924
+                        console.warn("Failed not apply setSinkId.", e);
3925
+                    });
3926
+                }
3927
+                earlyMedia.play().then(function(){
3928
+                   // Audio Is Playing
3929
+                }).catch(function(e){
3930
+                    console.warn("Unable to play audio file.", e);
3931
+                }); 
3932
+            }
3933
+            session.data.earlyMedia = earlyMedia;
3934
+        } else {
3935
+            $(MessageObjId).html(response.reason_phrase + "...");
3936
+        }
3937
+
3938
+        // Custom Web hook
3939
+        if(typeof web_hook_on_modify !== 'undefined') web_hook_on_modify("progress", session);
3940
+    });
3941
+    session.on('trackAdded', function () {
3942
+        var pc = session.sessionDescriptionHandler.peerConnection;
3943
+
3944
+        // Gets Remote Audio Track (Local audio is setup via initial GUM)
3945
+        var remoteStream = new MediaStream();
3946
+        pc.getReceivers().forEach(function (receiver) {
3947
+            if(receiver.track && receiver.track.kind == "audio"){
3948
+               remoteStream.addTrack(receiver.track);
3949
+            } 
3950
+        });
3951
+        var remoteAudio = $("#line-" + lineObj.LineNumber + "-remoteAudio").get(0);
3952
+        remoteAudio.srcObject = remoteStream;
3953
+        remoteAudio.onloadedmetadata = function(e) {
3954
+            if (typeof remoteAudio.sinkId !== 'undefined') {
3955
+                remoteAudio.setSinkId(getAudioOutputID()).then(function(){
3956
+                    console.log("sinkId applied: "+ getAudioOutputID());
3957
+                }).catch(function(e){
3958
+                    console.warn("Error using setSinkId: ", e);
3959
+                });
3960
+            }
3961
+            remoteAudio.play();
3962
+        }
3963
+
3964
+        // Custom Web hook
3965
+        if(typeof web_hook_on_modify !== 'undefined') web_hook_on_modify("trackAdded", session);
3966
+    });
3967
+    session.on('accepted', function (data) {
3968
+
3969
+        if(session.data.earlyMedia){
3970
+            session.data.earlyMedia.pause();
3971
+            session.data.earlyMedia.removeAttribute('src');
3972
+            session.data.earlyMedia.load();
3973
+            session.data.earlyMedia = null;
3974
+        }
3975
+
3976
+        window.clearInterval(session.data.callTimer);
3977
+        var startTime = moment.utc();
3978
+        session.data.callTimer = window.setInterval(function(){
3979
+            var now = moment.utc();
3980
+            var duration = moment.duration(now.diff(startTime)); 
3981
+            $("#line-" + lineObj.LineNumber + "-timer").html(formatShortDuration(duration.asSeconds()));
3982
+        }, 1000);
3983
+
3984
+        if(RecordAllCalls || CallRecordingPolicy == "enabled") {
3985
+            StartRecording(lineObj.LineNumber);
3986
+        }
3987
+
3988
+        $("#line-" + lineObj.LineNumber + "-progress").hide();
3989
+        $("#line-" + lineObj.LineNumber + "-VideoCall").hide();
3990
+        $("#line-" + lineObj.LineNumber + "-ActiveCall").show();
3991
+
3992
+        // Audo Monitoring
3993
+        lineObj.LocalSoundMeter = StartLocalAudioMediaMonitoring(lineObj.LineNumber, session);
3994
+        lineObj.RemoteSoundMeter = StartRemoteAudioMediaMonitoring(lineObj.LineNumber, session);
3995
+        
3996
+        $(MessageObjId).html(lang.call_in_progress);
3997
+
3998
+        updateLineScroll(lineObj.LineNumber);
3999
+
4000
+        UpdateBuddyList();
4001
+
4002
+        // Custom Web hook
4003
+        if(typeof web_hook_on_modify !== 'undefined') web_hook_on_modify("accepted", session);
4004
+    });
4005
+    session.on('rejected', function (response, cause) {
4006
+        // Should only apply befor answer
4007
+        $(MessageObjId).html(lang.call_rejected +": " + cause);
4008
+        console.log("Call rejected: " + cause);
4009
+        teardownSession(lineObj, response.status_code, response.reason_phrase);
4010
+    });
4011
+    session.on('failed', function (response, cause) {
4012
+        $(MessageObjId).html(lang.call_failed + ": " + cause);
4013
+        console.log("Call failed: " + cause);
4014
+        teardownSession(lineObj, 0, "Call failed");
4015
+    });
4016
+    session.on('cancel', function () {
4017
+        $(MessageObjId).html(lang.call_cancelled);
4018
+        console.log("Call Cancelled");
4019
+        teardownSession(lineObj, 0, "Cancelled by caller");
4020
+    });
4021
+    // referRequested
4022
+    // replaced
4023
+    session.on('bye', function () {
4024
+        $(MessageObjId).html(lang.call_ended);
4025
+        console.log("Call ended, bye!");
4026
+        teardownSession(lineObj, 16, "Normal Call clearing");
4027
+    });
4028
+    session.on('terminated', function (message, cause) {
4029
+        $(MessageObjId).html(lang.call_ended);
4030
+        console.log("Session terminated");
4031
+        teardownSession(lineObj, 16, "Normal Call clearing");
4032
+    });
4033
+    session.on('reinvite', function (session) {
4034
+        console.log("Session reinvited!");
4035
+    });
4036
+    //dtmf
4037
+    session.on('directionChanged', function() {
4038
+        var direction = session.sessionDescriptionHandler.getDirection();
4039
+        console.log("Direction Change: ", direction);
4040
+
4041
+        // Custom Web hook
4042
+        if(typeof web_hook_on_modify !== 'undefined') web_hook_on_modify("directionChanged", session);
4043
+    });
4044
+
4045
+    $("#line-" + lineObj.LineNumber + "-btn-settings").removeAttr('disabled');
4046
+    $("#line-" + lineObj.LineNumber + "-btn-audioCall").prop('disabled','disabled');
4047
+    $("#line-" + lineObj.LineNumber + "-btn-videoCall").prop('disabled','disabled');
4048
+    $("#line-" + lineObj.LineNumber + "-btn-search").removeAttr('disabled');
4049
+    $("#line-" + lineObj.LineNumber + "-btn-remove").prop('disabled','disabled');
4050
+
4051
+    $("#line-" + lineObj.LineNumber + "-progress").show();
4052
+    $("#line-" + lineObj.LineNumber + "-msg").show();
4053
+
4054
+    if(lineObj.BuddyObj.type == "group") {
4055
+        $("#line-" + lineObj.LineNumber + "-conference").show();
4056
+    } 
4057
+    else {
4058
+        $("#line-" + lineObj.LineNumber + "-conference").hide();
4059
+    }
4060
+
4061
+    updateLineScroll(lineObj.LineNumber);
4062
+
4063
+    UpdateUI();
4064
+}
4065
+
4066
+function wireupVideoSession(lineObj) {
4067
+    if (lineObj == null) return;
4068
+
4069
+    var MessageObjId = "#line-" + lineObj.LineNumber + "-msg";
4070
+    var session = lineObj.SipSession;
4071
+
4072
+    session.on('trackAdded', function () {
4073
+        // Gets remote tracks
4074
+        var pc = session.sessionDescriptionHandler.peerConnection;
4075
+        var remoteAudioStream = new MediaStream();
4076
+        var remoteVideoStream = new MediaStream();
4077
+        pc.getReceivers().forEach(function (receiver) {
4078
+            if(receiver.track){
4079
+                if(receiver.track.kind == "audio"){
4080
+                    remoteAudioStream.addTrack(receiver.track);
4081
+                }
4082
+                if(receiver.track.kind == "video"){
4083
+                    remoteVideoStream.addTrack(receiver.track);
4084
+                }
4085
+            }
4086
+        });
4087
+
4088
+        if (remoteAudioStream.getAudioTracks().length >= 1) {
4089
+            var remoteAudio = $("#line-" + lineObj.LineNumber + "-remoteAudio").get(0);
4090
+            remoteAudio.srcObject = remoteAudioStream;
4091
+            remoteAudio.onloadedmetadata = function(e) {
4092
+               if (typeof remoteAudio.sinkId !== 'undefined') {
4093
+                   remoteAudio.setSinkId(getAudioOutputID()).then(function(){
4094
+                       console.log("sinkId applied: "+ getAudioOutputID());
4095
+                   }).catch(function(e){
4096
+                       console.warn("Error using setSinkId: ", e);
4097
+                   });
4098
+               }
4099
+               remoteAudio.play();
4100
+            }
4101
+        }
4102
+
4103
+        if (remoteVideoStream.getVideoTracks().length >= 1) {
4104
+            var remoteVideo = $("#line-" + lineObj.LineNumber + "-remoteVideo").get(0);
4105
+            remoteVideo.srcObject = remoteVideoStream;
4106
+            remoteVideo.onloadedmetadata = function(e) {
4107
+                remoteVideo.play();
4108
+            }
4109
+        }
4110
+
4111
+        // Note: There appears to be a bug in the peerConnection.getSenders()
4112
+        // The array returns but may or may not be fully populated by the RTCRtpSender
4113
+        // The track property appears to be null initially and then moments later populated.
4114
+        // This does not appear to be the case when originating a call, mostly when receiving a call.
4115
+        window.setTimeout(function(){
4116
+            var localVideoStream = new MediaStream();
4117
+            var pc = session.sessionDescriptionHandler.peerConnection;
4118
+            pc.getSenders().forEach(function (sender) {
4119
+                if(sender.track && sender.track.kind == "video"){
4120
+                    localVideoStream.addTrack(sender.track);
4121
+                }
4122
+            });
4123
+            var localVideo = $("#line-" + lineObj.LineNumber + "-localVideo").get(0);
4124
+            localVideo.srcObject = localVideoStream;
4125
+            localVideo.onloadedmetadata = function(e) {
4126
+                localVideo.play();
4127
+            }
4128
+        }, 1000);
4129
+
4130
+        // Custom Web hook
4131
+        if(typeof web_hook_on_modify !== 'undefined') web_hook_on_modify("trackAdded", session);
4132
+    });
4133
+    session.on('progress', function (response) {
4134
+        // Provisional 1xx
4135
+        if(response.status_code == 100){
4136
+            $(MessageObjId).html(lang.trying);
4137
+        } else if(response.status_code == 180){
4138
+            $(MessageObjId).html(lang.ringing);
4139
+
4140
+            var soundFile = audioBlobs.EarlyMedia_European;
4141
+            if(UserLocale().indexOf("us") > -1) soundFile = audioBlobs.EarlyMedia_US;
4142
+            if(UserLocale().indexOf("gb") > -1) soundFile = audioBlobs.EarlyMedia_UK;
4143
+            if(UserLocale().indexOf("au") > -1) soundFile = audioBlobs.EarlyMedia_Australia;
4144
+            if(UserLocale().indexOf("jp") > -1) soundFile = audioBlobs.EarlyMedia_Japan;
4145
+
4146
+            // Play Early Media
4147
+            console.log("Audio:", soundFile.url);
4148
+            var earlyMedia = new Audio(soundFile.blob);
4149
+            earlyMedia.preload = "auto";
4150
+            earlyMedia.loop = true;
4151
+            earlyMedia.oncanplaythrough = function(e) {
4152
+                if (typeof earlyMedia.sinkId !== 'undefined' && getAudioOutputID() != "default") {
4153
+                    earlyMedia.setSinkId(getAudioOutputID()).then(function() {
4154
+                        console.log("Set sinkId to:", getAudioOutputID());
4155
+                    }).catch(function(e){
4156
+                        console.warn("Failed not apply setSinkId.", e);
4157
+                    });
4158
+                }
4159
+                earlyMedia.play().then(function(){
4160
+                   // Audio Is Playing
4161
+                }).catch(function(e){
4162
+                    console.warn("Unable to play audio file.", e);
4163
+                }); 
4164
+            }
4165
+            session.data.earlyMedia = earlyMedia;
4166
+        } else {
4167
+            $(MessageObjId).html(response.reason_phrase + "...");
4168
+        }
4169
+
4170
+        // Custom Web hook
4171
+        if(typeof web_hook_on_modify !== 'undefined') web_hook_on_modify("progress", session);
4172
+    });
4173
+    session.on('accepted', function (data) {
4174
+        
4175
+        if(session.data.earlyMedia){
4176
+            session.data.earlyMedia.pause();
4177
+            session.data.earlyMedia.removeAttribute('src');
4178
+            session.data.earlyMedia.load();
4179
+            session.data.earlyMedia = null;
4180
+        }
4181
+
4182
+        window.clearInterval(session.data.callTimer);
4183
+        $("#line-" + lineObj.LineNumber + "-timer").show();
4184
+        var startTime = moment.utc();
4185
+        session.data.callTimer = window.setInterval(function(){
4186
+            var now = moment.utc();
4187
+            var duration = moment.duration(now.diff(startTime)); 
4188
+            $("#line-" + lineObj.LineNumber + "-timer").html(formatShortDuration(duration.asSeconds()));
4189
+        }, 1000);
4190
+
4191
+        if(RecordAllCalls || CallRecordingPolicy == "enabled") {
4192
+            StartRecording(lineObj.LineNumber);
4193
+        }
4194
+
4195
+        $("#line-"+ lineObj.LineNumber +"-progress").hide();
4196
+        $("#line-"+ lineObj.LineNumber +"-VideoCall").show();
4197
+        $("#line-"+ lineObj.LineNumber +"-ActiveCall").show();
4198
+
4199
+        $("#line-"+ lineObj.LineNumber +"-btn-Conference").hide(); // Cannot conference a Video Call (Yet...)
4200
+        $("#line-"+ lineObj.LineNumber +"-btn-CancelConference").hide();
4201
+        $("#line-"+ lineObj.LineNumber +"-Conference").hide();
4202
+
4203
+        $("#line-"+ lineObj.LineNumber +"-btn-Transfer").hide(); // Cannot transfer a Video Call (Yet...)
4204
+        $("#line-"+ lineObj.LineNumber +"-btn-CancelTransfer").hide();
4205
+        $("#line-"+ lineObj.LineNumber +"-Transfer").hide();
4206
+
4207
+        // Default to use Camera
4208
+        $("#line-"+ lineObj.LineNumber +"-src-camera").prop("disabled", true);
4209
+        $("#line-"+ lineObj.LineNumber +"-src-canvas").prop("disabled", false);
4210
+        $("#line-"+ lineObj.LineNumber +"-src-desktop").prop("disabled", false);
4211
+        $("#line-"+ lineObj.LineNumber +"-src-video").prop("disabled", false);
4212
+
4213
+        updateLineScroll(lineObj.LineNumber);
4214
+
4215
+        // Start Audio Monitoring
4216
+        lineObj.LocalSoundMeter = StartLocalAudioMediaMonitoring(lineObj.LineNumber, session);
4217
+        lineObj.RemoteSoundMeter = StartRemoteAudioMediaMonitoring(lineObj.LineNumber, session);
4218
+
4219
+        $(MessageObjId).html(lang.call_in_progress);
4220
+
4221
+        if(StartVideoFullScreen) ExpandVideoArea(lineObj.LineNumber);
4222
+
4223
+        // Custom Web hook
4224
+        if(typeof web_hook_on_modify !== 'undefined') web_hook_on_modify("accepted", session);
4225
+    });
4226
+    session.on('rejected', function (response, cause) {
4227
+        // Should only apply before answer
4228
+        $(MessageObjId).html(lang.call_rejected +": "+ cause);
4229
+        console.log("Call rejected: "+ cause);
4230
+        teardownSession(lineObj, response.status_code, response.reason_phrase);
4231
+    });
4232
+    session.on('failed', function (response, cause) {
4233
+        $(MessageObjId).html(lang.call_failed +": "+ cause);
4234
+        console.log("Call failed: "+ cause);
4235
+        teardownSession(lineObj, 0, "call failed");
4236
+    });
4237
+    session.on('cancel', function () {
4238
+        $(MessageObjId).html(lang.call_cancelled);
4239
+        console.log("Call Cancelled");
4240
+        teardownSession(lineObj, 0, "Cancelled by caller");
4241
+    });
4242
+    // referRequested
4243
+    // replaced
4244
+    session.on('bye', function () {
4245
+        $(MessageObjId).html(lang.call_ended);
4246
+        console.log("Call ended, bye!");
4247
+        teardownSession(lineObj, 16, "Normal Call clearing");
4248
+    });
4249
+    session.on('terminated', function (message, cause) {
4250
+        $(MessageObjId).html(lang.call_ended);
4251
+        console.log("Session terminated");
4252
+        teardownSession(lineObj, 16, "Normal Call clearing");
4253
+    });
4254
+    session.on('reinvite', function (session) {
4255
+        console.log("Session reinvited!");
4256
+    });
4257
+    // dtmf
4258
+    session.on('directionChanged', function() {
4259
+        var direction = session.sessionDescriptionHandler.getDirection();
4260
+        console.log("Direction Change: ", direction);
4261
+
4262
+        // Custom Web hook
4263
+        if(typeof web_hook_on_modify !== 'undefined') web_hook_on_modify("directionChanged", session);
4264
+    });
4265
+
4266
+    $("#line-" + lineObj.LineNumber + "-btn-settings").removeAttr('disabled');
4267
+    $("#line-" + lineObj.LineNumber + "-btn-audioCall").prop('disabled','disabled');
4268
+    $("#line-" + lineObj.LineNumber + "-btn-videoCall").prop('disabled','disabled');
4269
+    $("#line-" + lineObj.LineNumber + "-btn-search").removeAttr('disabled');
4270
+    $("#line-" + lineObj.LineNumber + "-btn-remove").prop('disabled','disabled');
4271
+
4272
+    $("#line-" + lineObj.LineNumber + "-progress").show();
4273
+    $("#line-" + lineObj.LineNumber + "-msg").show();
4274
+    
4275
+    updateLineScroll(lineObj.LineNumber);
4276
+
4277
+    UpdateUI();
4278
+}
4279
+function teardownSession(lineObj, reasonCode, reasonText) {
4280
+    if(lineObj == null || lineObj.SipSession == null) return;
4281
+
4282
+    var session = lineObj.SipSession;
4283
+    if(session.data.teardownComplete == true) return;
4284
+    session.data.teardownComplete = true; // Run this code only once
4285
+
4286
+    session.data.reasonCode = reasonCode
4287
+    session.data.reasonText = reasonText
4288
+
4289
+    // Call UI
4290
+    $.jeegoopopup.close();
4291
+
4292
+    // End any child calls
4293
+    if(session.data.childsession){
4294
+        try{
4295
+            if(session.data.childsession.status == SIP.Session.C.STATUS_CONFIRMED){
4296
+                session.data.childsession.bye();
4297
+            } 
4298
+            else{
4299
+                session.data.childsession.cancel();
4300
+            }
4301
+        } catch(e){}
4302
+    }
4303
+    session.data.childsession = null;
4304
+
4305
+    // Mixed Tracks
4306
+    if(session.data.AudioSourceTrack && session.data.AudioSourceTrack.kind == "audio"){
4307
+        session.data.AudioSourceTrack.stop();
4308
+        session.data.AudioSourceTrack = null;
4309
+    }
4310
+    // Stop any Early Media
4311
+    if(session.data.earlyMedia){
4312
+        session.data.earlyMedia.pause();
4313
+        session.data.earlyMedia.removeAttribute('src');
4314
+        session.data.earlyMedia.load();
4315
+        session.data.earlyMedia = null;
4316
+    }
4317
+
4318
+    // Stop Recording if we are
4319
+    StopRecording(lineObj.LineNumber,true);
4320
+
4321
+    // Audio Meters
4322
+    if(lineObj.LocalSoundMeter != null){
4323
+        lineObj.LocalSoundMeter.stop();
4324
+        lineObj.LocalSoundMeter = null;
4325
+    }
4326
+    if(lineObj.RemoteSoundMeter != null){
4327
+        lineObj.RemoteSoundMeter.stop();
4328
+        lineObj.RemoteSoundMeter = null;
4329
+    }
4330
+
4331
+    // End timers
4332
+    window.clearInterval(session.data.videoResampleInterval);
4333
+    window.clearInterval(session.data.callTimer);
4334
+
4335
+    // Add to stream
4336
+    AddCallMessage(lineObj.BuddyObj.identity, session, reasonCode, reasonText);
4337
+
4338
+    // Close up the UI
4339
+    window.setTimeout(function () {
4340
+        RemoveLine(lineObj);
4341
+    }, 1000);
4342
+
4343
+    UpdateBuddyList();
4344
+    UpdateUI();
4345
+
4346
+    // Custom Web hook
4347
+    if(typeof web_hook_on_terminate !== 'undefined') web_hook_on_terminate(session);
4348
+}
4349
+
4350
+// Mic and Speaker Levels
4351
+// ======================
4352
+function StartRemoteAudioMediaMonitoring(lineNum, session) {
4353
+    console.log("Creating RemoteAudio AudioContext on Line:" + lineNum);
4354
+
4355
+    // Create local SoundMeter
4356
+    var soundMeter = new SoundMeter(session.id, lineNum);
4357
+    if(soundMeter == null){
4358
+        console.warn("AudioContext() RemoteAudio not available... it fine.");
4359
+        return null;
4360
+    }
4361
+
4362
+    // Ready the getStats request
4363
+    var remoteAudioStream = new MediaStream();
4364
+    var audioReceiver = null;
4365
+    var pc = session.sessionDescriptionHandler.peerConnection;
4366
+    pc.getReceivers().forEach(function (RTCRtpReceiver) {
4367
+        if(RTCRtpReceiver.track && RTCRtpReceiver.track.kind == "audio"){
4368
+            if(audioReceiver == null) {
4369
+                remoteAudioStream.addTrack(RTCRtpReceiver.track);
4370
+                audioReceiver = RTCRtpReceiver;
4371
+            }
4372
+            else {
4373
+                console.log("Found another Track, but audioReceiver not null");
4374
+                console.log(RTCRtpReceiver);
4375
+                console.log(RTCRtpReceiver.track);
4376
+            }
4377
+        }
4378
+    });
4379
+
4380
+    // Setup Charts
4381
+    var maxDataLength = 100;
4382
+    soundMeter.startTime = Date.now();
4383
+    Chart.defaults.global.defaultFontSize = 12;
4384
+
4385
+    var ChatHistoryOptions = { 
4386
+        responsive: false,
4387
+        maintainAspectRatio: false,
4388
+        devicePixelRatio: 1,
4389
+        animation: false,
4390
+        scales: {
4391
+            yAxes: [{
4392
+                ticks: { beginAtZero: true } //, min: 0, max: 100
4393
+            }]
4394
+        }, 
4395
+    }
4396
+
4397
+    // Receive Kilobits per second
4398
+    soundMeter.ReceiveBitRateChart = new Chart($("#line-"+ lineNum +"-AudioReceiveBitRate"), {
4399
+        type: 'line',
4400
+        data: {
4401
+            labels: MakeDataArray("", maxDataLength),
4402
+            datasets: [{
4403
+                label: lang.receive_kilobits_per_second,
4404
+                data: MakeDataArray(0, maxDataLength),
4405
+                backgroundColor: 'rgba(168, 0, 0, 0.5)',
4406
+                borderColor: 'rgba(168, 0, 0, 1)',
4407
+                borderWidth: 1,
4408
+                pointRadius: 1
4409
+            }]
4410
+        },
4411
+        options: ChatHistoryOptions
4412
+    });
4413
+    soundMeter.ReceiveBitRateChart.lastValueBytesReceived = 0;
4414
+    soundMeter.ReceiveBitRateChart.lastValueTimestamp = 0;
4415
+
4416
+    // Receive Packets per second
4417
+    soundMeter.ReceivePacketRateChart = new Chart($("#line-"+ lineNum +"-AudioReceivePacketRate"), {
4418
+        type: 'line',
4419
+        data: {
4420
+            labels: MakeDataArray("", maxDataLength),
4421
+            datasets: [{
4422
+                label: lang.receive_packets_per_second,
4423
+                data: MakeDataArray(0, maxDataLength),
4424
+                backgroundColor: 'rgba(168, 0, 0, 0.5)',
4425
+                borderColor: 'rgba(168, 0, 0, 1)',
4426
+                borderWidth: 1,
4427
+                pointRadius: 1
4428
+            }]
4429
+        },
4430
+        options: ChatHistoryOptions
4431
+    });
4432
+    soundMeter.ReceivePacketRateChart.lastValuePacketReceived = 0;
4433
+    soundMeter.ReceivePacketRateChart.lastValueTimestamp = 0;
4434
+
4435
+    // Receive Packet Loss
4436
+    soundMeter.ReceivePacketLossChart = new Chart($("#line-"+ lineNum +"-AudioReceivePacketLoss"), {
4437
+        type: 'line',
4438
+        data: {
4439
+            labels: MakeDataArray("", maxDataLength),
4440
+            datasets: [{
4441
+                label: lang.receive_packet_loss,
4442
+                data: MakeDataArray(0, maxDataLength),
4443
+                backgroundColor: 'rgba(168, 99, 0, 0.5)',
4444
+                borderColor: 'rgba(168, 99, 0, 1)',
4445
+                borderWidth: 1,
4446
+                pointRadius: 1
4447
+            }]
4448
+        },
4449
+        options: ChatHistoryOptions
4450
+    });
4451
+    soundMeter.ReceivePacketLossChart.lastValuePacketLoss = 0;
4452
+    soundMeter.ReceivePacketLossChart.lastValueTimestamp = 0;
4453
+
4454
+    // Receive Jitter
4455
+    soundMeter.ReceiveJitterChart = new Chart($("#line-"+ lineNum +"-AudioReceiveJitter"), {
4456
+        type: 'line',
4457
+        data: {
4458
+            labels: MakeDataArray("", maxDataLength),
4459
+            datasets: [{
4460
+                label: lang.receive_jitter,
4461
+                data: MakeDataArray(0, maxDataLength),
4462
+                backgroundColor: 'rgba(0, 38, 168, 0.5)',
4463
+                borderColor: 'rgba(0, 38, 168, 1)',
4464
+                borderWidth: 1,
4465
+                pointRadius: 1
4466
+            }]
4467
+        },
4468
+        options: ChatHistoryOptions
4469
+    });
4470
+
4471
+    // Receive Audio Levels
4472
+    soundMeter.ReceiveLevelsChart = new Chart($("#line-"+ lineNum +"-AudioReceiveLevels"), {
4473
+        type: 'line',
4474
+        data: {
4475
+            labels: MakeDataArray("", maxDataLength),
4476
+            datasets: [{
4477
+                label: lang.receive_audio_levels,
4478
+                data: MakeDataArray(0, maxDataLength),
4479
+                backgroundColor: 'rgba(140, 0, 168, 0.5)',
4480
+                borderColor: 'rgba(140, 0, 168, 1)',
4481
+                borderWidth: 1,
4482
+                pointRadius: 1
4483
+            }]
4484
+        },
4485
+        options: ChatHistoryOptions
4486
+    });
4487
+
4488
+    // Connect to Source
4489
+    soundMeter.connectToSource(remoteAudioStream, function (e) {
4490
+        if (e != null) return;
4491
+
4492
+        // Create remote SoundMeter
4493
+        console.log("SoundMeter for RemoteAudio Connected, displaying levels for Line: " + lineNum);
4494
+        soundMeter.levelsInterval = window.setInterval(function () {
4495
+            // Calculate Levels
4496
+            //value="0" max="1" high="0.25" (this seems low... )
4497
+            var level = soundMeter.instant * 4.0;
4498
+            if (level > 1) level = 1;
4499
+            var instPercent = level * 100;
4500
+
4501
+            $("#line-" + lineNum + "-Speaker").css("height", instPercent.toFixed(2) +"%");
4502
+        }, 50);
4503
+        soundMeter.networkInterval = window.setInterval(function (){
4504
+            // Calculate Network Conditions
4505
+            if(audioReceiver != null) {
4506
+                audioReceiver.getStats().then(function(stats) {
4507
+                    stats.forEach(function(report){
4508
+
4509
+                        var theMoment = utcDateNow();
4510
+                        var ReceiveBitRateChart = soundMeter.ReceiveBitRateChart;
4511
+                        var ReceivePacketRateChart = soundMeter.ReceivePacketRateChart;
4512
+                        var ReceivePacketLossChart = soundMeter.ReceivePacketLossChart;
4513
+                        var ReceiveJitterChart = soundMeter.ReceiveJitterChart;
4514
+                        var ReceiveLevelsChart = soundMeter.ReceiveLevelsChart;
4515
+                        var elapsedSec = Math.floor((Date.now() - soundMeter.startTime)/1000);
4516
+
4517
+                        if(report.type == "inbound-rtp"){
4518
+
4519
+                            if(ReceiveBitRateChart.lastValueTimestamp == 0) {
4520
+                                ReceiveBitRateChart.lastValueTimestamp = report.timestamp;
4521
+                                ReceiveBitRateChart.lastValueBytesReceived = report.bytesReceived;
4522
+
4523
+                                ReceivePacketRateChart.lastValueTimestamp = report.timestamp;
4524
+                                ReceivePacketRateChart.lastValuePacketReceived = report.packetsReceived;
4525
+
4526
+                                ReceivePacketLossChart.lastValueTimestamp = report.timestamp;
4527
+                                ReceivePacketLossChart.lastValuePacketLoss = report.packetsLost;
4528
+
4529
+                                return;
4530
+                            }
4531
+                            // Receive Kilobits Per second
4532
+                            var kbitsPerSec = (8 * (report.bytesReceived - ReceiveBitRateChart.lastValueBytesReceived))/1000;
4533
+
4534
+                            ReceiveBitRateChart.lastValueTimestamp = report.timestamp;
4535
+                            ReceiveBitRateChart.lastValueBytesReceived = report.bytesReceived;
4536
+
4537
+                            soundMeter.ReceiveBitRate.push({ value: kbitsPerSec, timestamp : theMoment});
4538
+                            ReceiveBitRateChart.data.datasets[0].data.push(kbitsPerSec);
4539
+                            ReceiveBitRateChart.data.labels.push("");
4540
+                            if(ReceiveBitRateChart.data.datasets[0].data.length > maxDataLength) {
4541
+                                ReceiveBitRateChart.data.datasets[0].data.splice(0,1);
4542
+                                ReceiveBitRateChart.data.labels.splice(0,1);
4543
+                            }
4544
+                            ReceiveBitRateChart.update();
4545
+
4546
+                            // Receive Packets Per Second
4547
+                            var PacketsPerSec = (report.packetsReceived - ReceivePacketRateChart.lastValuePacketReceived);
4548
+
4549
+                            ReceivePacketRateChart.lastValueTimestamp = report.timestamp;
4550
+                            ReceivePacketRateChart.lastValuePacketReceived = report.packetsReceived;
4551
+
4552
+                            soundMeter.ReceivePacketRate.push({ value: PacketsPerSec, timestamp : theMoment});
4553
+                            ReceivePacketRateChart.data.datasets[0].data.push(PacketsPerSec);
4554
+                            ReceivePacketRateChart.data.labels.push("");
4555
+                            if(ReceivePacketRateChart.data.datasets[0].data.length > maxDataLength) {
4556
+                                ReceivePacketRateChart.data.datasets[0].data.splice(0,1);
4557
+                                ReceivePacketRateChart.data.labels.splice(0,1);
4558
+                            }
4559
+                            ReceivePacketRateChart.update();
4560
+
4561
+                            // Receive Packet Loss
4562
+                            var PacketsLost = (report.packetsLost - ReceivePacketLossChart.lastValuePacketLoss);
4563
+
4564
+                            ReceivePacketLossChart.lastValueTimestamp = report.timestamp;
4565
+                            ReceivePacketLossChart.lastValuePacketLoss = report.packetsLost;
4566
+
4567
+                            soundMeter.ReceivePacketLoss.push({ value: PacketsLost, timestamp : theMoment});
4568
+                            ReceivePacketLossChart.data.datasets[0].data.push(PacketsLost);
4569
+                            ReceivePacketLossChart.data.labels.push("");
4570
+                            if(ReceivePacketLossChart.data.datasets[0].data.length > maxDataLength) {
4571
+                                ReceivePacketLossChart.data.datasets[0].data.splice(0,1);
4572
+                                ReceivePacketLossChart.data.labels.splice(0,1);
4573
+                            }
4574
+                            ReceivePacketLossChart.update();
4575
+
4576
+                            // Receive Jitter
4577
+                            soundMeter.ReceiveJitter.push({ value: report.jitter, timestamp : theMoment});
4578
+                            ReceiveJitterChart.data.datasets[0].data.push(report.jitter);
4579
+                            ReceiveJitterChart.data.labels.push("");
4580
+                            if(ReceiveJitterChart.data.datasets[0].data.length > maxDataLength) {
4581
+                                ReceiveJitterChart.data.datasets[0].data.splice(0,1);
4582
+                                ReceiveJitterChart.data.labels.splice(0,1);
4583
+                            }
4584
+                            ReceiveJitterChart.update();
4585
+                        }
4586
+                        if(report.type == "track") {
4587
+
4588
+                            // Receive Audio Levels
4589
+                            var levelPercent = (report.audioLevel * 100);
4590
+                            soundMeter.ReceiveLevels.push({ value: levelPercent, timestamp : theMoment});
4591
+                            ReceiveLevelsChart.data.datasets[0].data.push(levelPercent);
4592
+                            ReceiveLevelsChart.data.labels.push("");
4593
+                            if(ReceiveLevelsChart.data.datasets[0].data.length > maxDataLength)
4594
+                            {
4595
+                                ReceiveLevelsChart.data.datasets[0].data.splice(0,1);
4596
+                                ReceiveLevelsChart.data.labels.splice(0,1);
4597
+                            }
4598
+                            ReceiveLevelsChart.update();
4599
+                        }
4600
+                    });
4601
+                });
4602
+            }
4603
+        } ,1000);
4604
+    });
4605
+
4606
+    return soundMeter;
4607
+}
4608
+function StartLocalAudioMediaMonitoring(lineNum, session) {
4609
+    console.log("Creating LocalAudio AudioContext on line " + lineNum);
4610
+
4611
+    // Create local SoundMeter
4612
+    var soundMeter = new SoundMeter(session.id, lineNum);
4613
+    if(soundMeter == null){
4614
+        console.warn("AudioContext() LocalAudio not available... its fine.")
4615
+        return null;
4616
+    }
4617
+
4618
+    // Ready the getStats request
4619
+    var localAudioStream = new MediaStream();
4620
+    var audioSender = null;
4621
+    var pc = session.sessionDescriptionHandler.peerConnection;
4622
+    pc.getSenders().forEach(function (RTCRtpSender) {
4623
+        if(RTCRtpSender.track && RTCRtpSender.track.kind == "audio"){
4624
+            if(audioSender == null){
4625
+                console.log("Adding Track to Monitor: ", RTCRtpSender.track.label);
4626
+                localAudioStream.addTrack(RTCRtpSender.track);
4627
+                audioSender = RTCRtpSender;
4628
+            }
4629
+            else {
4630
+                console.log("Found another Track, but audioSender not null");
4631
+                console.log(RTCRtpSender);
4632
+                console.log(RTCRtpSender.track);
4633
+            }
4634
+        }
4635
+    });
4636
+
4637
+    // Setup Charts
4638
+    var maxDataLength = 100;
4639
+    soundMeter.startTime = Date.now();
4640
+    Chart.defaults.global.defaultFontSize = 12;
4641
+    var ChatHistoryOptions = { 
4642
+        responsive: false,    
4643
+        maintainAspectRatio: false,
4644
+        devicePixelRatio: 1,
4645
+        animation: false,
4646
+        scales: {
4647
+            yAxes: [{
4648
+                ticks: { beginAtZero: true }
4649
+            }]
4650
+        }, 
4651
+    }
4652
+
4653
+    // Send Kilobits Per Second
4654
+    soundMeter.SendBitRateChart = new Chart($("#line-"+ lineNum +"-AudioSendBitRate"), {
4655
+        type: 'line',
4656
+        data: {
4657
+            labels: MakeDataArray("", maxDataLength),
4658
+            datasets: [{
4659
+                label: lang.send_kilobits_per_second,
4660
+                data: MakeDataArray(0, maxDataLength),
4661
+                backgroundColor: 'rgba(0, 121, 19, 0.5)',
4662
+                borderColor: 'rgba(0, 121, 19, 1)',
4663
+                borderWidth: 1,
4664
+                pointRadius: 1
4665
+            }]
4666
+        },
4667
+        options: ChatHistoryOptions
4668
+    });
4669
+    soundMeter.SendBitRateChart.lastValueBytesSent = 0;
4670
+    soundMeter.SendBitRateChart.lastValueTimestamp = 0;
4671
+
4672
+    // Send Packets Per Second
4673
+    soundMeter.SendPacketRateChart = new Chart($("#line-"+ lineNum +"-AudioSendPacketRate"), {
4674
+        type: 'line',
4675
+        data: {
4676
+            labels: MakeDataArray("", maxDataLength),
4677
+            datasets: [{
4678
+                label: lang.send_packets_per_second,
4679
+                data: MakeDataArray(0, maxDataLength),
4680
+                backgroundColor: 'rgba(0, 121, 19, 0.5)',
4681
+                borderColor: 'rgba(0, 121, 19, 1)',
4682
+                borderWidth: 1,
4683
+                pointRadius: 1
4684
+            }]
4685
+        },
4686
+        options: ChatHistoryOptions
4687
+    });
4688
+    soundMeter.SendPacketRateChart.lastValuePacketSent = 0;
4689
+    soundMeter.SendPacketRateChart.lastValueTimestamp = 0;    
4690
+
4691
+    // Connect to Source
4692
+    soundMeter.connectToSource(localAudioStream, function (e) {
4693
+        if (e != null) return;
4694
+
4695
+        console.log("SoundMeter for LocalAudio Connected, displaying levels for Line: " + lineNum);
4696
+        soundMeter.levelsInterval = window.setInterval(function () {
4697
+            // Calculate Levels
4698
+            //value="0" max="1" high="0.25" (this seems low... )
4699
+            var level = soundMeter.instant * 4.0;
4700
+            if (level > 1) level = 1;
4701
+            var instPercent = level * 100;
4702
+            $("#line-" + lineNum + "-Mic").css("height", instPercent.toFixed(2) +"%");
4703
+        }, 50);
4704
+        soundMeter.networkInterval = window.setInterval(function (){
4705
+            // Calculate Network Conditions
4706
+            // Sending Audio Track
4707
+            if(audioSender != null) {
4708
+                audioSender.getStats().then(function(stats) {
4709
+                    stats.forEach(function(report){
4710
+
4711
+                        var theMoment = utcDateNow();
4712
+                        var SendBitRateChart = soundMeter.SendBitRateChart;
4713
+                        var SendPacketRateChart = soundMeter.SendPacketRateChart;
4714
+                        var elapsedSec = Math.floor((Date.now() - soundMeter.startTime)/1000);
4715
+
4716
+                        if(report.type == "outbound-rtp"){
4717
+                            if(SendBitRateChart.lastValueTimestamp == 0) {
4718
+                                SendBitRateChart.lastValueTimestamp = report.timestamp;
4719
+                                SendBitRateChart.lastValueBytesSent = report.bytesSent;
4720
+
4721
+                                SendPacketRateChart.lastValueTimestamp = report.timestamp;
4722
+                                SendPacketRateChart.lastValuePacketSent = report.packetsSent;
4723
+                                return;
4724
+                            }
4725
+
4726
+                            // Send Kilobits Per second
4727
+                            var kbitsPerSec = (8 * (report.bytesSent - SendBitRateChart.lastValueBytesSent))/1000;
4728
+
4729
+                            SendBitRateChart.lastValueTimestamp = report.timestamp;
4730
+                            SendBitRateChart.lastValueBytesSent = report.bytesSent;
4731
+
4732
+                            soundMeter.SendBitRate.push({ value: kbitsPerSec, timestamp : theMoment});
4733
+                            SendBitRateChart.data.datasets[0].data.push(kbitsPerSec);
4734
+                            SendBitRateChart.data.labels.push("");
4735
+                            if(SendBitRateChart.data.datasets[0].data.length > maxDataLength) {
4736
+                                SendBitRateChart.data.datasets[0].data.splice(0,1);
4737
+                                SendBitRateChart.data.labels.splice(0,1);
4738
+                            }
4739
+                            SendBitRateChart.update();
4740
+
4741
+                            // Send Packets Per Second
4742
+                            var PacketsPerSec = report.packetsSent - SendPacketRateChart.lastValuePacketSent;
4743
+
4744
+                            SendPacketRateChart.lastValueTimestamp = report.timestamp;
4745
+                            SendPacketRateChart.lastValuePacketSent = report.packetsSent;
4746
+
4747
+                            soundMeter.SendPacketRate.push({ value: PacketsPerSec, timestamp : theMoment});
4748
+                            SendPacketRateChart.data.datasets[0].data.push(PacketsPerSec);
4749
+                            SendPacketRateChart.data.labels.push("");
4750
+                            if(SendPacketRateChart.data.datasets[0].data.length > maxDataLength) {
4751
+                                SendPacketRateChart.data.datasets[0].data.splice(0,1);
4752
+                                SendPacketRateChart.data.labels.splice(0,1);
4753
+                            }
4754
+                            SendPacketRateChart.update();
4755
+                        }
4756
+                        if(report.type == "track") {
4757
+                            // Bug/security consern... this seems always to report "0"
4758
+                            // 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).
4759
+                            // console.log("Audio Sender: " + report.audioLevel);
4760
+                        }
4761
+                    });
4762
+                });
4763
+            }
4764
+        } ,1000);
4765
+    });
4766
+
4767
+    return soundMeter;
4768
+}
4769
+
4770
+// Sounds Meter Class
4771
+// ==================
4772
+class SoundMeter {
4773
+    constructor(sessionId, lineNum) {
4774
+        var audioContext = null;
4775
+        try {
4776
+            window.AudioContext = window.AudioContext || window.webkitAudioContext;
4777
+            audioContext = new AudioContext();
4778
+        }
4779
+        catch(e) {
4780
+            console.warn("AudioContext() LocalAudio not available... its fine.");
4781
+        }
4782
+        if (audioContext == null) return null;
4783
+
4784
+        this.lineNum = lineNum;
4785
+        this.sessionId = sessionId;
4786
+        this.levelsInterval = null;
4787
+        this.networkInterval = null;
4788
+        this.startTime = 0;
4789
+        this.ReceiveBitRateChart = null;
4790
+        this.ReceiveBitRate = [];
4791
+        this.ReceivePacketRateChart = null;
4792
+        this.ReceivePacketRate = [];
4793
+        this.ReceivePacketLossChart = null;
4794
+        this.ReceivePacketLoss = [];
4795
+        this.ReceiveJitterChart = null;
4796
+        this.ReceiveJitter = [];
4797
+        this.ReceiveLevelsChart = null;
4798
+        this.ReceiveLevels = [];
4799
+        this.SendBitRateChart = null;
4800
+        this.SendBitRate = [];
4801
+        this.SendPacketRateChart = null;
4802
+        this.SendPacketRate = [];
4803
+        this.context = audioContext;
4804
+        this.instant = 0.0;
4805
+        this.script = audioContext.createScriptProcessor(2048, 1, 1);
4806
+        const that = this;
4807
+        this.script.onaudioprocess = function (event) {
4808
+            const input = event.inputBuffer.getChannelData(0);
4809
+            let i;
4810
+            let sum = 0.0;
4811
+            for (i = 0; i < input.length; ++i) {
4812
+                sum += input[i] * input[i];
4813
+            }
4814
+            that.instant = Math.sqrt(sum / input.length);
4815
+        }
4816
+    }
4817
+    connectToSource(stream, callback) {
4818
+        console.log("SoundMeter connecting...");
4819
+        try {
4820
+            this.mic = this.context.createMediaStreamSource(stream);
4821
+            this.mic.connect(this.script);
4822
+            // necessary to make sample run, but should not be.
4823
+            this.script.connect(this.context.destination);
4824
+            callback(null);
4825
+        }
4826
+        catch(e) {
4827
+            console.error(e); // Probably not audio track
4828
+            callback(e);
4829
+        }
4830
+    }
4831
+    stop() {
4832
+        console.log("Disconnecting SoundMeter...");
4833
+        try {
4834
+            window.clearInterval(this.levelsInterval);
4835
+            this.levelsInterval = null;
4836
+        }
4837
+        catch(e) { }
4838
+        try {
4839
+            window.clearInterval(this.networkInterval);
4840
+            this.networkInterval = null;
4841
+        }
4842
+        catch(e) { }
4843
+        this.mic.disconnect();
4844
+        this.script.disconnect();
4845
+        this.mic = null;
4846
+        this.script = null;
4847
+        try {
4848
+            this.context.close();
4849
+        }
4850
+        catch(e) { }
4851
+        this.context = null;
4852
+
4853
+        // Save to IndexDb
4854
+        var lineObj = FindLineByNumber(this.lineNum);
4855
+        var QosData = {
4856
+            ReceiveBitRate: this.ReceiveBitRate,
4857
+            ReceivePacketRate: this.ReceivePacketRate,
4858
+            ReceivePacketLoss: this.ReceivePacketLoss,
4859
+            ReceiveJitter: this.ReceiveJitter,
4860
+            ReceiveLevels: this.ReceiveLevels,
4861
+            SendBitRate: this.SendBitRate,
4862
+            SendPacketRate: this.SendPacketRate,
4863
+        }
4864
+        SaveQosData(QosData, this.sessionId, lineObj.BuddyObj.identity);
4865
+    }
4866
+}
4867
+function MeterSettingsOutput(audioStream, objectId, direction, interval){
4868
+    var soundMeter = new SoundMeter(null, null);
4869
+    soundMeter.startTime = Date.now();
4870
+    soundMeter.connectToSource(audioStream, function (e) {
4871
+        if (e != null) return;
4872
+
4873
+        console.log("SoundMeter Connected, displaying levels to:"+ objectId);
4874
+        soundMeter.levelsInterval = window.setInterval(function () {
4875
+            // Calculate Levels
4876
+            //value="0" max="1" high="0.25" (this seems low... )
4877
+            var level = soundMeter.instant * 4.0;
4878
+            if (level > 1) level = 1;
4879
+            var instPercent = level * 100;
4880
+
4881
+            $("#"+objectId).css(direction, instPercent.toFixed(2) +"%"); // Settings_MicrophoneOutput "width" 50
4882
+        }, interval);
4883
+    });
4884
+
4885
+    return soundMeter;
4886
+}
4887
+
4888
+// QOS
4889
+// ===
4890
+function SaveQosData(QosData, sessionId, buddy){
4891
+    var indexedDB = window.indexedDB;
4892
+    var request = indexedDB.open("CallQosData");
4893
+    request.onerror = function(event) {
4894
+        console.error("IndexDB Request Error:", event);
4895
+    }
4896
+    request.onupgradeneeded = function(event) {
4897
+        console.warn("Upgrade Required for IndexDB... probably because of first time use.");
4898
+        var IDB = event.target.result;
4899
+
4900
+        // Create Object Store
4901
+        if(IDB.objectStoreNames.contains("CallQos") == false){
4902
+            var objectStore = IDB.createObjectStore("CallQos", { keyPath: "uID" });
4903
+            objectStore.createIndex("sessionid", "sessionid", { unique: false });
4904
+            objectStore.createIndex("buddy", "buddy", { unique: false });
4905
+            objectStore.createIndex("QosData", "QosData", { unique: false });
4906
+        }
4907
+        else {
4908
+            console.warn("IndexDB requested upgrade, but object store was in place");
4909
+        }
4910
+    }
4911
+    request.onsuccess = function(event) {
4912
+        console.log("IndexDB connected to CallQosData");
4913
+
4914
+        var IDB = event.target.result;
4915
+        if(IDB.objectStoreNames.contains("CallQos") == false){
4916
+            console.warn("IndexDB CallQosData.CallQos does not exists");
4917
+            return;
4918
+        }
4919
+        IDB.onerror = function(event) {
4920
+            console.error("IndexDB Error:", event);
4921
+        }
4922
+
4923
+        // Prepare data to write
4924
+        var data = {
4925
+            uID: uID(),
4926
+            sessionid: sessionId,
4927
+            buddy: buddy,
4928
+            QosData: QosData
4929
+        }
4930
+        // Commit Transaction
4931
+        var transaction = IDB.transaction(["CallQos"], "readwrite");
4932
+        var objectStoreAdd = transaction.objectStore("CallQos").add(data);
4933
+        objectStoreAdd.onsuccess = function(event) {
4934
+            console.log("Call CallQos Sucess: ", sessionId);
4935
+        }
4936
+    }
4937
+}
4938
+function DisplayQosData(sessionId){
4939
+    var indexedDB = window.indexedDB;
4940
+    var request = indexedDB.open("CallQosData");
4941
+    request.onerror = function(event) {
4942
+        console.error("IndexDB Request Error:", event);
4943
+    }
4944
+    request.onupgradeneeded = function(event) {
4945
+        console.warn("Upgrade Required for IndexDB... probably because of first time use.");
4946
+    }
4947
+    request.onsuccess = function(event) {
4948
+        console.log("IndexDB connected to CallQosData");
4949
+
4950
+        var IDB = event.target.result;
4951
+        if(IDB.objectStoreNames.contains("CallQos") == false){
4952
+            console.warn("IndexDB CallQosData.CallQos does not exists");
4953
+            return;
4954
+        } 
4955
+
4956
+        var transaction = IDB.transaction(["CallQos"]);
4957
+        var objectStoreGet = transaction.objectStore("CallQos").index('sessionid').getAll(sessionId);
4958
+        objectStoreGet.onerror = function(event) {
4959
+            console.error("IndexDB Get Error:", event);
4960
+        }
4961
+        objectStoreGet.onsuccess = function(event) {
4962
+            if(event.target.result && event.target.result.length == 2){
4963
+                // This is the correct data
4964
+
4965
+                var QosData0 = event.target.result[0].QosData;
4966
+                // ReceiveBitRate: (8) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
4967
+                // ReceiveJitter: (8) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
4968
+                // ReceiveLevels: (9) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
4969
+                // ReceivePacketLoss: (8) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
4970
+                // ReceivePacketRate: (8) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
4971
+                // SendBitRate: []
4972
+                // SendPacketRate: []
4973
+                var QosData1 = event.target.result[1].QosData;
4974
+                // ReceiveBitRate: []
4975
+                // ReceiveJitter: []
4976
+                // ReceiveLevels: []
4977
+                // ReceivePacketLoss: []
4978
+                // ReceivePacketRate: []
4979
+                // SendBitRate: (9) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
4980
+                // SendPacketRate: (9) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
4981
+
4982
+                Chart.defaults.global.defaultFontSize = 12;
4983
+
4984
+                var ChatHistoryOptions = { 
4985
+                    responsive: true,
4986
+                    maintainAspectRatio: false,
4987
+                    animation: false,
4988
+                    scales: {
4989
+                        yAxes: [{
4990
+                            ticks: { beginAtZero: true } //, min: 0, max: 100
4991
+                        }],
4992
+                        xAxes: [{
4993
+                            display: false
4994
+                        }]
4995
+                    }, 
4996
+                }
4997
+
4998
+                // ReceiveBitRateChart
4999
+                var labelset = [];
5000
+                var dataset = [];
5001
+                var data = (QosData0.ReceiveBitRate.length > 0)? QosData0.ReceiveBitRate : QosData1.ReceiveBitRate;
5002
+                $.each(data, function(i,item){
5003
+                    labelset.push(moment.utc(item.timestamp.replace(" UTC", "")).local().format(DisplayDateFormat +" "+ DisplayTimeFormat));
5004
+                    dataset.push(item.value);
5005
+                });
5006
+                var ReceiveBitRateChart = new Chart($("#cdr-AudioReceiveBitRate"), {
5007
+                    type: 'line',
5008
+                    data: {
5009
+                        labels: labelset,
5010
+                        datasets: [{
5011
+                            label: lang.receive_kilobits_per_second,
5012
+                            data: dataset,
5013
+                            backgroundColor: 'rgba(168, 0, 0, 0.5)',
5014
+                            borderColor: 'rgba(168, 0, 0, 1)',
5015
+                            borderWidth: 1,
5016
+                            pointRadius: 1
5017
+                        }]
5018
+                    },
5019
+                    options: ChatHistoryOptions
5020
+                });
5021
+
5022
+                // ReceivePacketRateChart
5023
+                var labelset = [];
5024
+                var dataset = [];
5025
+                var data = (QosData0.ReceivePacketRate.length > 0)? QosData0.ReceivePacketRate : QosData1.ReceivePacketRate;
5026
+                $.each(data, function(i,item){
5027
+                    labelset.push(moment.utc(item.timestamp.replace(" UTC", "")).local().format(DisplayDateFormat +" "+ DisplayTimeFormat));
5028
+                    dataset.push(item.value);
5029
+                });
5030
+                var ReceivePacketRateChart = new Chart($("#cdr-AudioReceivePacketRate"), {
5031
+                    type: 'line',
5032
+                    data: {
5033
+                        labels: labelset,
5034
+                        datasets: [{
5035
+                            label: lang.receive_packets_per_second,
5036
+                            data: dataset,
5037
+                            backgroundColor: 'rgba(168, 0, 0, 0.5)',
5038
+                            borderColor: 'rgba(168, 0, 0, 1)',
5039
+                            borderWidth: 1,
5040
+                            pointRadius: 1
5041
+                        }]
5042
+                    },
5043
+                    options: ChatHistoryOptions
5044
+                });
5045
+
5046
+                // AudioReceivePacketLossChart
5047
+                var labelset = [];
5048
+                var dataset = [];
5049
+                var data = (QosData0.ReceivePacketLoss.length > 0)? QosData0.ReceivePacketLoss : QosData1.ReceivePacketLoss;
5050
+                $.each(data, function(i,item){
5051
+                    labelset.push(moment.utc(item.timestamp.replace(" UTC", "")).local().format(DisplayDateFormat +" "+ DisplayTimeFormat));
5052
+                    dataset.push(item.value);
5053
+                });
5054
+                var AudioReceivePacketLossChart = new Chart($("#cdr-AudioReceivePacketLoss"), {
5055
+                    type: 'line',
5056
+                    data: {
5057
+                        labels: labelset,
5058
+                        datasets: [{
5059
+                            label: lang.receive_packet_loss,
5060
+                            data: dataset,
5061
+                            backgroundColor: 'rgba(168, 99, 0, 0.5)',
5062
+                            borderColor: 'rgba(168, 99, 0, 1)',
5063
+                            borderWidth: 1,
5064
+                            pointRadius: 1
5065
+                        }]
5066
+                    },
5067
+                    options: ChatHistoryOptions
5068
+                });
5069
+
5070
+                // AudioReceiveJitterChart
5071
+                var labelset = [];
5072
+                var dataset = [];
5073
+                var data = (QosData0.ReceiveJitter.length > 0)? QosData0.ReceiveJitter : QosData1.ReceiveJitter;
5074
+                $.each(data, function(i,item){
5075
+                    labelset.push(moment.utc(item.timestamp.replace(" UTC", "")).local().format(DisplayDateFormat +" "+ DisplayTimeFormat));
5076
+                    dataset.push(item.value);
5077
+                });
5078
+                var AudioReceiveJitterChart = new Chart($("#cdr-AudioReceiveJitter"), {
5079
+                    type: 'line',
5080
+                    data: {
5081
+                        labels: labelset,
5082
+                        datasets: [{
5083
+                            label: lang.receive_jitter,
5084
+                            data: dataset,
5085
+                            backgroundColor: 'rgba(0, 38, 168, 0.5)',
5086
+                            borderColor: 'rgba(0, 38, 168, 1)',
5087
+                            borderWidth: 1,
5088
+                            pointRadius: 1
5089
+                        }]
5090
+                    },
5091
+                    options: ChatHistoryOptions
5092
+                });
5093
+              
5094
+                // AudioReceiveLevelsChart
5095
+                var labelset = [];
5096
+                var dataset = [];
5097
+                var data = (QosData0.ReceiveLevels.length > 0)? QosData0.ReceiveLevels : QosData1.ReceiveLevels;
5098
+                $.each(data, function(i,item){
5099
+                    labelset.push(moment.utc(item.timestamp.replace(" UTC", "")).local().format(DisplayDateFormat +" "+ DisplayTimeFormat));
5100
+                    dataset.push(item.value);
5101
+                });
5102
+                var AudioReceiveLevelsChart = new Chart($("#cdr-AudioReceiveLevels"), {
5103
+                    type: 'line',
5104
+                    data: {
5105
+                        labels: labelset,
5106
+                        datasets: [{
5107
+                            label: lang.receive_audio_levels,
5108
+                            data: dataset,
5109
+                            backgroundColor: 'rgba(140, 0, 168, 0.5)',
5110
+                            borderColor: 'rgba(140, 0, 168, 1)',
5111
+                            borderWidth: 1,
5112
+                            pointRadius: 1
5113
+                        }]
5114
+                    },
5115
+                    options: ChatHistoryOptions
5116
+                });
5117
+                 
5118
+                // SendPacketRateChart
5119
+                var labelset = [];
5120
+                var dataset = [];
5121
+                var data = (QosData0.SendPacketRate.length > 0)? QosData0.SendPacketRate : QosData1.SendPacketRate;
5122
+                $.each(data, function(i,item){
5123
+                    labelset.push(moment.utc(item.timestamp.replace(" UTC", "")).local().format(DisplayDateFormat +" "+ DisplayTimeFormat));
5124
+                    dataset.push(item.value);
5125
+                });
5126
+                var SendPacketRateChart = new Chart($("#cdr-AudioSendPacketRate"), {
5127
+                    type: 'line',
5128
+                    data: {
5129
+                        labels: labelset,
5130
+                        datasets: [{
5131
+                            label: lang.send_packets_per_second,
5132
+                            data: dataset,
5133
+                            backgroundColor: 'rgba(0, 121, 19, 0.5)',
5134
+                            borderColor: 'rgba(0, 121, 19, 1)',
5135
+                            borderWidth: 1,
5136
+                            pointRadius: 1
5137
+                        }]
5138
+                    },
5139
+                    options: ChatHistoryOptions
5140
+                });
5141
+
5142
+                // AudioSendBitRateChart
5143
+                var labelset = [];
5144
+                var dataset = [];
5145
+                var data = (QosData0.SendBitRate.length > 0)? QosData0.SendBitRate : QosData1.SendBitRate;
5146
+                $.each(data, function(i,item){
5147
+                    labelset.push(moment.utc(item.timestamp.replace(" UTC", "")).local().format(DisplayDateFormat +" "+ DisplayTimeFormat));
5148
+                    dataset.push(item.value);
5149
+                });
5150
+                var AudioSendBitRateChart = new Chart($("#cdr-AudioSendBitRate"), {
5151
+                    type: 'line',
5152
+                    data: {
5153
+                        labels: labelset,
5154
+                        datasets: [{
5155
+                            label: lang.send_kilobits_per_second,
5156
+                            data: dataset,
5157
+                            backgroundColor: 'rgba(0, 121, 19, 0.5)',
5158
+                            borderColor: 'rgba(0, 121, 19, 1)',
5159
+                            borderWidth: 1,
5160
+                            pointRadius: 1
5161
+                        }]
5162
+                    },
5163
+                    options: ChatHistoryOptions
5164
+                });
5165
+            } else {
5166
+                console.warn("Result not expected", event.target.result);
5167
+            }
5168
+        }
5169
+    }
5170
+}
5171
+function DeleteQosData(buddy){
5172
+    var indexedDB = window.indexedDB;
5173
+    var request = indexedDB.open("CallQosData");
5174
+    request.onerror = function(event) {
5175
+        console.error("IndexDB Request Error:", event);
5176
+    }
5177
+    request.onupgradeneeded = function(event) {
5178
+        console.warn("Upgrade Required for IndexDB... probably because of first time use.");
5179
+        // If this is the case, there will be no call recordings
5180
+    }
5181
+    request.onsuccess = function(event) {
5182
+        console.log("IndexDB connected to CallQosData");
5183
+
5184
+        var IDB = event.target.result;
5185
+        if(IDB.objectStoreNames.contains("CallQos") == false){
5186
+            console.warn("IndexDB CallQosData.CallQos does not exists");
5187
+            return;
5188
+        }
5189
+        IDB.onerror = function(event) {
5190
+            console.error("IndexDB Error:", event);
5191
+        }
5192
+
5193
+        // Loop and Delete
5194
+        console.log("Deleting CallQosData: ", buddy);
5195
+        var transaction = IDB.transaction(["CallQos"], "readwrite");
5196
+        var objectStore = transaction.objectStore("CallQos");
5197
+        var objectStoreGet = objectStore.index('buddy').getAll(buddy);
5198
+
5199
+        objectStoreGet.onerror = function(event) {
5200
+            console.error("IndexDB Get Error:", event);
5201
+        }
5202
+        objectStoreGet.onsuccess = function(event) {
5203
+            if(event.target.result && event.target.result.length > 0){
5204
+                // There sre some rows to delete
5205
+                $.each(event.target.result, function(i, item){
5206
+                    // console.log("Delete: ", item.uID);
5207
+                    try{
5208
+                        objectStore.delete(item.uID);
5209
+                    } catch(e){
5210
+                        console.log("Call CallQosData Delete failed: ", e);
5211
+                    }
5212
+                });
5213
+            }
5214
+        }
5215
+
5216
+    }
5217
+}
5218
+
5219
+// Presence / Subscribe
5220
+// ====================
5221
+function SubscribeAll() {
5222
+    console.log("Subscribe to voicemail Messages...");
5223
+
5224
+    // conference, message-summary, dialog, presence, presence.winfo, xcap-diff, dialog.winfo, refer
5225
+
5226
+    // Voicemail notice
5227
+    var vmOptions = { expires: 300 }
5228
+    voicemailSubs = userAgent.subscribe(SipUsername + "@" + wssServer, 'message-summary', vmOptions); // message-summary = voicemail messages
5229
+    voicemailSubs.on('notify', function (notification) {
5230
+
5231
+        // You have voicemail: 
5232
+        // Message-Account: sip:alice@example.com
5233
+        // Messages-Waiting: no
5234
+        // Fax-Message: 2/4
5235
+        // Voice-Message: 0/0 (0/0)   <-- new/old (new & urgent/ old & urgent)
5236
+
5237
+        var messagesWaitng = false;
5238
+        $.each(notification.request.body.split("\n"), function (i, line) {
5239
+            if(line.indexOf("Messages-Waiting:") != -1){
5240
+                messagesWaitng = ($.trim(line.replace("Messages-Waiting:", "")) == "yes");
5241
+            }
5242
+        });
5243
+
5244
+        if(messagesWaitng){
5245
+            // Notify user of voicemail
5246
+            console.log("You have voicemail!");
5247
+        }
5248
+    });
5249
+
5250
+    // Dialog Subscription (This version isnt as nice as PIDF)
5251
+    // var dialogOptions = { expires: 300, extraHeaders: ['Accept: application/dialog-info+xml'] }
5252
+
5253
+    // PIDF Subscription
5254
+    var dialogOptions = { expires: 300, extraHeaders: ['Accept: application/pidf+xml'] }
5255
+    // var dialogOptions = { expires: 300, extraHeaders: ['Accept: application/pidf+xml', 'application/xpidf+xml', 'application/simple-message-summary', 'application/im-iscomposing+xml'] }
5256
+
5257
+    // Start subscribe all
5258
+    console.log("Starting Subscribe of all ("+ Buddies.length +") Extension Buddies...");
5259
+    for(var b=0; b<Buddies.length; b++) {
5260
+        var buddyObj = Buddies[b];
5261
+        if(buddyObj.type == "extension") {
5262
+            console.log("SUBSCRIBE: "+ buddyObj.ExtNo +"@" + wssServer);
5263
+            var blfObj = userAgent.subscribe(buddyObj.ExtNo +"@" + wssServer, 'presence', dialogOptions); 
5264
+            blfObj.data.buddyId = buddyObj.identity;
5265
+            blfObj.on('notify', function (notification) {
5266
+                RecieveBlf(notification);
5267
+            });
5268
+            BlfSubs.push(blfObj);
5269
+        }
5270
+    }
5271
+}
5272
+function SubscribeBuddy(buddyObj) {
5273
+    var dialogOptions = { expires: 300, extraHeaders: ['Accept: application/pidf+xml'] }
5274
+
5275
+    if(buddyObj.type == "extension") {
5276
+        console.log("SUBSCRIBE: "+ buddyObj.ExtNo +"@" + wssServer);
5277
+        var blfObj = userAgent.subscribe(buddyObj.ExtNo +"@" + wssServer, 'presence', dialogOptions);
5278
+        blfObj.data.buddyId = buddyObj.identity;
5279
+        blfObj.on('notify', function (notification) {
5280
+            RecieveBlf(notification);
5281
+        });
5282
+        BlfSubs.push(blfObj);
5283
+    }
5284
+}
5285
+function RecieveBlf(notification) {
5286
+    if (userAgent == null || !userAgent.isRegistered()) return;
5287
+
5288
+    var ContentType = notification.request.headers["Content-Type"][0].parsed;
5289
+    if (ContentType == "application/pidf+xml") {
5290
+
5291
+        var xml = $($.parseXML(notification.request.body));
5292
+
5293
+        var Entity = xml.find("presence").attr("entity");
5294
+        var Contact = xml.find("presence").find("tuple").find("contact").text();
5295
+        if (SipUsername == Entity.split("@")[0].split(":")[1] || SipUsername == Contact.split("@")[0].split(":")[1]){
5296
+            // Message is for you.
5297
+        } 
5298
+        else {
5299
+            console.warn("presence message not for you.", xml);
5300
+            return;
5301
+        }
5302
+
5303
+        var buddy = xml.find("presence").find("tuple").attr("id");
5304
+
5305
+        var statusObj = xml.find("presence").find("tuple").find("status");
5306
+        var availability = xml.find("presence").find("tuple").find("status").find("basic").text();
5307
+        var friendlyState = xml.find("presence").find("note").text();
5308
+        var dotClass = "dotOffline";
5309
+
5310
+        if (friendlyState == "Not online") dotClass = "dotOffline";
5311
+        if (friendlyState == "Ready") dotClass = "dotOnline";
5312
+        if (friendlyState == "On the phone") dotClass = "dotInUse";
5313
+        if (friendlyState == "Ringing") dotClass = "dotRinging";
5314
+        if (friendlyState == "On hold") dotClass = "dotOnHold";
5315
+        if (friendlyState == "Unavailable") dotClass = "dotOffline";
5316
+
5317
+        // dotOnline | dotOffline | dotRinging | dotInUse | dotReady | dotOnHold
5318
+        var buddyObj = FindBuddyByExtNo(buddy);
5319
+        if(buddyObj != null)
5320
+        {
5321
+            console.log("Setting Presence for "+ buddyObj.identity +" to "+ friendlyState);
5322
+            $("#contact-" + buddyObj.identity + "-devstate").prop("class", dotClass);
5323
+            $("#contact-" + buddyObj.identity + "-devstate-main").prop("class", dotClass);
5324
+            buddyObj.devState = dotClass;
5325
+            buddyObj.presence = friendlyState;
5326
+
5327
+            if (friendlyState == "Not online") friendlyState = lang.state_not_online;
5328
+            if (friendlyState == "Ready") friendlyState = lang.state_ready;
5329
+            if (friendlyState == "On the phone") friendlyState = lang.state_on_the_phone;
5330
+            if (friendlyState == "Ringing") friendlyState = lang.state_ringing;
5331
+            if (friendlyState == "On hold") friendlyState = lang.state_on_hold;
5332
+            if (friendlyState == "Unavailable") friendlyState = lang.state_unavailable;
5333
+            $("#contact-" + buddyObj.identity + "-presence").html(friendlyState);
5334
+            $("#contact-" + buddyObj.identity + "-presence-main").html(friendlyState);
5335
+        }
5336
+    }
5337
+    else if (ContentType == "application/dialog-info+xml")
5338
+    {
5339
+        // Handle "Dialog" State
5340
+
5341
+        var xml = $($.parseXML(notification.request.body));
5342
+
5343
+        var ObservedUser = xml.find("dialog-info").attr("entity");
5344
+        var buddy = ObservedUser.split("@")[0].split(":")[1];
5345
+
5346
+        var version = xml.find("dialog-info").attr("version");
5347
+
5348
+        var DialogState = xml.find("dialog-info").attr("state");
5349
+        if (DialogState != "full") return;
5350
+
5351
+        var extId = xml.find("dialog-info").find("dialog").attr("id");
5352
+        if (extId != buddy) return;
5353
+
5354
+        var state = xml.find("dialog-info").find("dialog").find("state").text();
5355
+        var friendlyState = "Unknown";
5356
+        if (state == "terminated") friendlyState = "Ready";
5357
+        if (state == "trying") friendlyState = "On the phone";
5358
+        if (state == "proceeding") friendlyState = "On the phone";
5359
+        if (state == "early") friendlyState = "Ringing";
5360
+        if (state == "confirmed") friendlyState = "On the phone";
5361
+
5362
+        var dotClass = "dotOffline";
5363
+        if (friendlyState == "Not online") dotClass = "dotOffline";
5364
+        if (friendlyState == "Ready") dotClass = "dotOnline";
5365
+        if (friendlyState == "On the phone") dotClass = "dotInUse";
5366
+        if (friendlyState == "Ringing") dotClass = "dotRinging";
5367
+        if (friendlyState == "On hold") dotClass = "dotOnHold";
5368
+        if (friendlyState == "Unavailable") dotClass = "dotOffline";
5369
+
5370
+        // The dialog states only report devices states, and cant say online or offline.
5371
+        // dotOnline | dotOffline | dotRinging | dotInUse | dotReady | dotOnHold
5372
+        var buddyObj = FindBuddyByExtNo(buddy);
5373
+        if(buddyObj != null)
5374
+        {
5375
+            console.log("Setting Presence for "+ buddyObj.identity +" to "+ friendlyState);
5376
+            $("#contact-" + buddyObj.identity + "-devstate").prop("class", dotClass);
5377
+            $("#contact-" + buddyObj.identity + "-devstate-main").prop("class", dotClass);
5378
+            buddyObj.devState = dotClass;
5379
+            buddyObj.presence = friendlyState;
5380
+
5381
+            if (friendlyState == "Unknown") friendlyState = lang.state_unknown;
5382
+            if (friendlyState == "Not online") friendlyState = lang.state_not_online;
5383
+            if (friendlyState == "Ready") friendlyState = lang.state_ready;
5384
+            if (friendlyState == "On the phone") friendlyState = lang.state_on_the_phone;
5385
+            if (friendlyState == "Ringing") friendlyState = lang.state_ringing;
5386
+            if (friendlyState == "On hold") friendlyState = lang.state_on_hold;
5387
+            if (friendlyState == "Unavailable") friendlyState = lang.state_unavailable;
5388
+            $("#contact-" + buddyObj.identity + "-presence").html(friendlyState);
5389
+            $("#contact-" + buddyObj.identity + "-presence-main").html(friendlyState);
5390
+        }
5391
+    }
5392
+}
5393
+function UnsubscribeAll() {
5394
+    console.log("Unsubscribing "+ BlfSubs.length + " subscriptions...");
5395
+    for (var blf = 0; blf < BlfSubs.length; blf++) {
5396
+        BlfSubs[blf].unsubscribe();
5397
+        BlfSubs[blf].close();
5398
+    }
5399
+    BlfSubs = new Array();
5400
+
5401
+    for(var b=0; b<Buddies.length; b++) {
5402
+        var buddyObj = Buddies[b];
5403
+        if(buddyObj.type == "extension") {
5404
+            $("#contact-" + buddyObj.identity + "-devstate").prop("class", "dotOffline");
5405
+            $("#contact-" + buddyObj.identity + "-devstate-main").prop("class", "dotOffline");
5406
+            $("#contact-" + buddyObj.identity + "-presence").html(lang.state_unknown);
5407
+            $("#contact-" + buddyObj.identity + "-presence-main").html(lang.state_unknown);
5408
+        }
5409
+    }
5410
+}
5411
+function UnsubscribeBuddy(buddyObj) {
5412
+    if(buddyObj.type != "extension") return;
5413
+
5414
+    for (var blf = 0; blf < BlfSubs.length; blf++) {
5415
+        var blfObj = BlfSubs[blf];
5416
+        if(blfObj.data.buddyId == buddyObj.identity){
5417
+        console.log("Unsubscribing:", buddyObj.identity);
5418
+            if(blfObj.dialog != null){
5419
+                blfObj.unsubscribe();
5420
+                blfObj.close();
5421
+            }
5422
+            BlfSubs.splice(blf, 1);
5423
+            break;
5424
+        }
5425
+    }
5426
+}
5427
+
5428
+// Buddy: Chat / Instant Message / XMPP
5429
+// ====================================
5430
+function InitinaliseStream(buddy){
5431
+    var template = { TotalRows:0, DataCollection:[] }
5432
+    localDB.setItem(buddy + "-stream", JSON.stringify(template));
5433
+    return JSON.parse(localDB.getItem(buddy + "-stream"));
5434
+}
5435
+function splitString(str, size) {
5436
+    const mPieces = Math.ceil(str.length / size);
5437
+    const piecesArr = [];
5438
+
5439
+    for (let i = 0, s = 0; i < mPieces; ++i, s += size) {
5440
+      piecesArr[i] = str.substr(s, size);
5441
+    }
5442
+    return piecesArr;
5443
+}
5444
+function generateAESKey(passphrase) {
5445
+    const salt = CryptoJS.lib.WordArray.random(128 / 8);
5446
+    const key256Bits = CryptoJS.PBKDF2(passphrase, salt, {
5447
+      keySize: 256 / 32,
5448
+      iterations: 100,
5449
+    });
5450
+    return key256Bits;
5451
+}
5452
+function encryptAES(message, key) {
5453
+    var message = CryptoJS.AES.encrypt(message, key);
5454
+    return message.toString();
5455
+}
5456
+function decryptAES(message, key) {
5457
+    var code = CryptoJS.AES.decrypt(message, key);
5458
+    var decryptedMessage = code.toString(CryptoJS.enc.Utf8);
5459
+    return decryptedMessage;
5460
+}
5461
+function getChatRSAPubKey(recsendSIPuser) {
5462
+    var chatPubKey = '';
5463
+    $.ajax({
5464
+	     'async': false,
5465
+	     'global': false,
5466
+	     type: "POST",
5467
+	     url: "get-text-chat-pub-key.php",
5468
+	     dataType: "JSON",
5469
+	     data: { 
5470
+		     recsendsipuser: recsendSIPuser,
5471
+                     s_ajax_call: validateSToken
5472
+             },
5473
+	     success: function(result) {
5474
+                            if (result.resmessage == 'success') {
5475
+                                chatPubKey = "`" + result.chatkey.join("") + "`";
5476
+                            } else {
5477
+                                pubKeyCheck = 1;
5478
+                                alert('An error occurred while retrieving the public key for text chat!');
5479
+                            }
5480
+             },
5481
+             error: function(result) {
5482
+                    alert('An error occurred while attempting to retrieve the public key for text chat!');
5483
+             }
5484
+    });
5485
+    return chatPubKey;
5486
+}
5487
+
5488
+function SendChatMessage(buddy) {
5489
+
5490
+    if (userAgent == null) return;
5491
+    if (!userAgent.isRegistered()) return;
5492
+
5493
+    var messageraw = $("#contact-" + buddy + "-ChatMessage").val();
5494
+    messagetrim = $.trim(messageraw);
5495
+
5496
+    if (messagetrim == "" && (sendFileCheck == 0 || (sendFileCheck == 1 && $("#selectedFile").val() == ""))) { 
5497
+        Alert(lang.alert_empty_text_message, lang.no_message);
5498
+        return;
5499
+    }
5500
+
5501
+    var buddyObj = FindBuddyByIdentity(buddy);
5502
+
5503
+    if ($.inArray(buddyObj.presence, ["Ready", "On the phone", "Ringing", "On hold"]) == -1) {
5504
+        alert("You cannot send a message or a file to a contact who is not online!");
5505
+        $("#sendFileLoader").remove();
5506
+        $("#selectedFile").val("");
5507
+        $("#sendFileFormChat").remove();
5508
+        sendFileCheck = 0;
5509
+        return; 
5510
+    }
5511
+
5512
+    var genPassphr = Date.now() + Math.floor(Math.random()*10000).toString(6).toUpperCase();
5513
+    var aesKey = String(generateAESKey(genPassphr));
5514
+    var encryptedMes = encryptAES(messagetrim, aesKey);
5515
+
5516
+    // Split the encrypted message into smaller pieces to fit the 1024 byte limit for SIP messages, which is hard-coded in Asterisk
5517
+    var messageprearr = [];
5518
+    var messageprearr = splitString(encryptedMes, 900);
5519
+
5520
+    var genMessageId =  Date.now() + Math.floor(Math.random()*10000).toString(16).toUpperCase();
5521
+    var messageIdent = genMessageId + profileUser;
5522
+    var firstPieceCheck = [];
5523
+    firstPieceCheck = [messageIdent, 1];
5524
+    var lastPieceCheck = [];
5525
+    lastPieceCheck = [messageIdent, 0];
5526
+
5527
+    // Get the public key of the extension to which we send the message
5528
+    var destExtChatRSAPubKey = getChatRSAPubKey(buddyObj.ExtNo);
5529
+
5530
+    // Encrypt the AES key with RSA
5531
+    var newencrypt = new JSEncrypt();
5532
+    newencrypt.setPublicKey(destExtChatRSAPubKey);
5533
+    var encmIdAesKey = newencrypt.encrypt(aesKey);
5534
+
5535
+    // Add the encrypted AES key as the first element of the array of message pieces
5536
+    messageprearr.unshift(encmIdAesKey);
5537
+
5538
+    $("#contact-"+ buddy +"-ChatHistory").after("<span id='sendFileLoader'></span>");
5539
+
5540
+    for (var k = 0; k < messageprearr.length; k++) {
5541
+
5542
+         if (k == 0) {
5543
+             // Send the RSA-encrypted AES key as first piece of the message
5544
+             var messagePiece = messageIdent + "|" + messageprearr.length + "|" + parseInt(k) + "||" + messageprearr[k];
5545
+	 } else if (sendFileCheck == 0 && messageprearr[k] != '') {
5546
+	     var messagePiece = messageIdent + "|" + messageprearr.length + "|" + parseInt(k) + "||" + messageprearr[k];
5547
+	 } else if (sendFileCheck == 1 && sendFileChatErr == '') {
5548
+	     var messagePiece = messageIdent + "|" + messageprearr.length + "|" + parseInt(k) + "|" + upFileName + "|" + messageprearr[k];
5549
+	 } else if (sendFileCheck == 1 && sendFileChatErr != '') {
5550
+	     $("#sendFileFormChat").remove();
5551
+             sendFileChatErr = '';
5552
+	     sendFileCheck = 0;
5553
+	     return;
5554
+	 }
5555
+
5556
+         if (k == 1) { firstPieceCheck = [messageIdent, 0]; }
5557
+
5558
+         if (k == (messageprearr.length - 1)) { lastPieceCheck = [messageIdent, 1]; }
5559
+
5560
+         SendChatMessageProc(buddy, buddyObj, messageIdent, messagePiece, messagetrim, firstPieceCheck, lastPieceCheck);
5561
+    }
5562
+}
5563
+
5564
+function SendChatMessageProc(buddy, buddyObj, messageIdent, messagePiece, messagetrim, firstPieceCheck, lastPieceCheck) {
5565
+
5566
+    var messageId = uID();
5567
+
5568
+    if (pubKeyCheck == 1) { pubKeyCheck = 0; $("#selectedFile").val(""); $("#sendFileLoader").remove(); return; }
5569
+
5570
+    sendFileChatErr = '';
5571
+
5572
+    $("#sendFileFormChat").on('submit', function(ev) {
5573
+             ev.preventDefault();
5574
+
5575
+             $.ajax({
5576
+                'async': false,
5577
+                'global': false,
5578
+                type: 'POST',
5579
+                url: 'text-chat-upload-file.php',
5580
+                data: new FormData(this),
5581
+                dataType: "JSON",
5582
+                contentType: false,
5583
+                cache: false,
5584
+                processData:false,
5585
+                success: function(respdata) {
5586
+                            if (respdata.error != '') { 
5587
+                                sendFileChatErr = respdata.error;
5588
+                                $("#sendFileFormChat").remove();
5589
+                                $("#sendFileLoader").remove();
5590
+                                alert("Error: " + respdata.error);
5591
+                            }
5592
+                },
5593
+                error: function(respdata) {
5594
+                            alert("An error occurred while sending the file!");
5595
+                }          
5596
+             });
5597
+    });
5598
+
5599
+    if (sendFileCheck == 1 && (firstPieceCheck[0] == messageIdent && firstPieceCheck[1] == 1)) {
5600
+        $("#submitFileChat").click();
5601
+    }
5602
+
5603
+    if (lastPieceCheck[0] == messageIdent && lastPieceCheck[1] == 1 && sendFileCheck == 1 && sendFileChatErr != '') {
5604
+        $("#sendFileFormChat").remove();
5605
+        $("#sendFileLoader").remove();
5606
+        sendFileChatErr = '';
5607
+        sendFileCheck = 0;
5608
+        return;
5609
+    }
5610
+
5611
+    if (buddyObj.type == "extension" || buddyObj.type == "group") {
5612
+
5613
+          var chatBuddy = buddyObj.ExtNo + "@" + wssServer;
5614
+          console.log("MESSAGE: "+ chatBuddy + " (extension)");
5615
+
5616
+          var messageObj = userAgent.message(chatBuddy, messagePiece);
5617
+
5618
+            messageObj.data.direction = "outbound";
5619
+            messageObj.data.messageId = messageId;
5620
+
5621
+            messageObj.on("accepted", function (response, cause){
5622
+
5623
+                if(response.status_code == 202) {
5624
+                    console.log("Message Accepted:", messageId);
5625
+
5626
+                    // Update DB
5627
+                    var currentStream = JSON.parse(localDB.getItem(buddy + "-stream"));
5628
+                    if(currentStream != null || currentStream.DataCollection != null){
5629
+                        $.each(currentStream.DataCollection, function (i, item) {
5630
+                            if (item.ItemType == "MSG" && item.ItemId == messageId) {
5631
+                                // Found
5632
+                                item.Sent = true;
5633
+                                return false;
5634
+                            }
5635
+                        });
5636
+                        localDB.setItem(buddy + "-stream", JSON.stringify(currentStream));
5637
+
5638
+                        RefreshStream(buddyObj);
5639
+                    }
5640
+                } else {
5641
+                    console.warn("Message Error", response.status_code, cause);
5642
+
5643
+                    // Update DB
5644
+                    var currentStream = JSON.parse(localDB.getItem(buddy + "-stream"));
5645
+                    if(currentStream != null || currentStream.DataCollection != null){
5646
+                        $.each(currentStream.DataCollection, function (i, item) {
5647
+                            if (item.ItemType == "MSG" && item.ItemId == messageId) {
5648
+                                // Found
5649
+                                item.Sent = false;
5650
+                                return false;
5651
+                            }
5652
+                        });
5653
+                        localDB.setItem(buddy + "-stream", JSON.stringify(currentStream));
5654
+
5655
+                        RefreshStream(buddyObj);
5656
+                    }                
5657
+                }
5658
+            });
5659
+
5660
+          // Custom Web hook
5661
+          if (typeof web_hook_on_message !== 'undefined') web_hook_on_message(messageObj); 
5662
+    }
5663
+
5664
+    if (lastPieceCheck[0] == messageIdent && lastPieceCheck[1] == 1) {
5665
+
5666
+       // Update Stream
5667
+       var DateTime = moment.utc().format("YYYY-MM-DD HH:mm:ss UTC");
5668
+       var currentStream = JSON.parse(localDB.getItem(buddy + "-stream"));
5669
+       if(currentStream == null) currentStream = InitinaliseStream(buddy);
5670
+
5671
+       // Add New Message
5672
+       var newMessageJson = {
5673
+           ItemId: messageId,
5674
+           ItemType: "MSG",
5675
+           ItemDate: DateTime,
5676
+           SrcUserId: profileUserID,
5677
+           Src: "\""+ profileName +"\" <"+ profileUser +">",
5678
+           DstUserId: buddy,
5679
+           Dst: "",
5680
+           MessageData: messagetrim
5681
+       }
5682
+
5683
+       // If a file is sent, add the sent file section
5684
+       if (sendFileCheck == 1) {
5685
+
5686
+           $("#sendFileFormChat").remove();
5687
+           sendFileCheck = 0;
5688
+
5689
+           var newMessageId = uID();
5690
+           var newDateTime = moment.utc().format("YYYY-MM-DD HH:mm:ss UTC");
5691
+
5692
+	   var newFileMessageJson = {
5693
+	        ItemId: newMessageId,
5694
+	        ItemType: "FILE",
5695
+	        ItemDate: newDateTime,
5696
+	        SrcUserId: profileUserID,
5697
+	        Src: "\""+ profileName +"\" <"+ profileUser +">",
5698
+	        DstUserId: buddy,
5699
+	        Dst: buddyObj.ExtNo,
5700
+                SentFileName: upFileName,
5701
+	        MessageData: "Download file"
5702
+	   }
5703
+
5704
+           if (sendFileChatErr == '') {
5705
+               currentStream.DataCollection.push(newFileMessageJson);
5706
+           }
5707
+
5708
+       } else { $("#sendFileFormChat").remove(); }
5709
+
5710
+       currentStream.DataCollection.push(newMessageJson);
5711
+
5712
+       currentStream.TotalRows = currentStream.DataCollection.length;
5713
+       localDB.setItem(buddy + "-stream", JSON.stringify(currentStream));
5714
+
5715
+    }
5716
+
5717
+    // Post Add Activity
5718
+    if (lastPieceCheck[0] == messageIdent && lastPieceCheck[1] == 1) {
5719
+        $("#sendFileLoader").remove();
5720
+        $("#contact-" + buddy + "-ChatMessage").val("");
5721
+    }
5722
+    $("#contact-" + buddy + "-emoji-menu").hide();
5723
+
5724
+    if(buddyObj.recognition != null){
5725
+       buddyObj.recognition.abort();
5726
+       buddyObj.recognition = null;
5727
+    }
5728
+
5729
+    RefreshStream(buddyObj);
5730
+}
5731
+
5732
+function ReceiveMessage(message) {
5733
+
5734
+    var callerID = message.remoteIdentity.displayName;
5735
+    var did = message.remoteIdentity.uri.user;
5736
+
5737
+    console.log("New Incoming Message!", "\""+ callerID +"\" <"+ did +">");
5738
+
5739
+    message.data.direction = "inbound";
5740
+
5741
+    if(did.length > DidLength) {
5742
+        // Contacts cannot receive Text Messages, because they cannot reply
5743
+        // This may change with FAX, Email, WhatsApp etc
5744
+        console.warn("DID length greater then extensions length")
5745
+        return;
5746
+    }
5747
+
5748
+    var CurrentCalls = countSessions("0");
5749
+
5750
+    var buddyObj = FindBuddyByDid(did);
5751
+    // Make new contact if it's not there
5752
+    if(buddyObj == null) {
5753
+        var json = JSON.parse(localDB.getItem(profileUserID + "-Buddies"));
5754
+        if(json == null) json = InitUserBuddies();
5755
+
5756
+        // Add Extension
5757
+        var id = uID();
5758
+        var dateNow = utcDateNow();
5759
+        json.DataCollection.push({
5760
+            Type: "extension",
5761
+            LastActivity: dateNow,
5762
+            ExtensionNumber: did,
5763
+            MobileNumber: "",
5764
+            ContactNumber1: "",
5765
+            ContactNumber2: "",
5766
+            uID: id,
5767
+            cID: null,
5768
+            gID: null,
5769
+            DisplayName: callerID,
5770
+            Position: "",
5771
+            Description: "",
5772
+            Email: "",
5773
+            MemberCount: 0
5774
+        });
5775
+        buddyObj = new Buddy("extension", id, callerID, did, "", "", "", dateNow, "", "");
5776
+        AddBuddy(buddyObj, true, (CurrentCalls==0), true);
5777
+
5778
+        // Update Size
5779
+        json.TotalRows = json.DataCollection.length;
5780
+
5781
+        // Save To DB
5782
+        localDB.setItem(profileUserID + "-Buddies", JSON.stringify(json));
5783
+    }
5784
+
5785
+    var encryptedtext = message.body;
5786
+    var originalMessageArr = encryptedtext.split("|");
5787
+
5788
+    if (originalMessageArr[3] != '' && typeof originalMessageArr[3] != 'undefined' && originalMessageArr[3] != null) {
5789
+        var fileSentDuringChat = 1;
5790
+	var recFileName = originalMessageArr[3];
5791
+    } else {
5792
+	var fileSentDuringChat = 0;
5793
+        var recFileName = '';
5794
+    }
5795
+
5796
+    var currentMId = originalMessageArr[0];
5797
+    var totalPieceNo = parseInt(originalMessageArr[1]);
5798
+    var currentPieceNo = parseInt(originalMessageArr[2]);
5799
+
5800
+    // Reassemble the original message and decrypt it
5801
+    if (currentPieceNo == 0) {
5802
+
5803
+       if (splitMessage.hasOwnProperty(currentMId)) {
5804
+
5805
+          if (currentPieceNo == 0) {
5806
+              var aesPayload = originalMessageArr[4];
5807
+              var newdecrypt = new JSEncrypt();
5808
+              newdecrypt.setPrivateKey(currentChatPrivKey);
5809
+              var decAESKeyCon = newdecrypt.decrypt(aesPayload);
5810
+              splitMessage[currentMId].aeskeyandiv = decAESKeyCon;
5811
+
5812
+          } else {
5813
+             splitMessage[currentMId][currentPieceNo] = originalMessageArr[4];
5814
+          }
5815
+
5816
+       } else {
5817
+
5818
+          if (currentPieceNo == 0) {
5819
+              var aesPayload = originalMessageArr[4];
5820
+              var newdecrypt = new JSEncrypt();
5821
+              newdecrypt.setPrivateKey(currentChatPrivKey);
5822
+              var decAESKeyCon = newdecrypt.decrypt(aesPayload);
5823
+              splitMessage[currentMId] = { "aeskeyandiv": decAESKeyCon };
5824
+
5825
+          } else {
5826
+             splitMessage[currentMId] = { [currentPieceNo]: originalMessageArr[4] };
5827
+          }
5828
+
5829
+       }
5830
+
5831
+       return;
5832
+
5833
+    } else if (currentPieceNo < (totalPieceNo - 1)) {
5834
+
5835
+        if (splitMessage.hasOwnProperty(currentMId)) {
5836
+            splitMessage[currentMId][currentPieceNo] = originalMessageArr[4];
5837
+        } else {
5838
+	    splitMessage[currentMId] = { [currentPieceNo]: originalMessageArr[4] };
5839
+        }
5840
+
5841
+        return;
5842
+
5843
+    } else if (currentPieceNo == (totalPieceNo - 1)) {
5844
+
5845
+        if (splitMessage.hasOwnProperty(currentMId)) {
5846
+            splitMessage[currentMId][currentPieceNo] = originalMessageArr[4];
5847
+        } else {
5848
+	    splitMessage[currentMId] = { [currentPieceNo]: originalMessageArr[4] };
5849
+        }
5850
+
5851
+        if (Object.keys(splitMessage[currentMId]).length == totalPieceNo) {
5852
+
5853
+            var decryptAesKey = splitMessage[currentMId]["aeskeyandiv"];
5854
+
5855
+            delete splitMessage[currentMId]["aeskeyandiv"];
5856
+            var origMessageEnc = '';
5857
+            var orderedMPieces = Object.keys(splitMessage[currentMId]).sort().reduce(function(obj, key) { 
5858
+                obj[key] = splitMessage[currentMId][key]; 
5859
+                return obj;
5860
+            },{});
5861
+
5862
+            Object.keys(orderedMPieces).forEach(function(key, index) {
5863
+                origMessageEnc += splitMessage[currentMId][key];
5864
+            });
5865
+
5866
+            var originalMessage = decryptAES(origMessageEnc, decryptAesKey);
5867
+
5868
+	    delete splitMessage[currentMId];
5869
+
5870
+        } else { return; }
5871
+    }
5872
+
5873
+    var messageId = uID();
5874
+    var DateTime = utcDateNow();
5875
+
5876
+    // Get the actual person sending (since all group messages come from the group)
5877
+    var ActualSender = "";
5878
+    if(buddyObj.type == "group") {
5879
+        var assertedIdentity = message.request.headers["P-Asserted-Identity"][0].raw; // Name Surname <ExtNo> 
5880
+        var bits = assertedIdentity.split(" <");
5881
+        var CallerID = bits[0];
5882
+        var CallerIDNum = bits[1].replace(">", "");
5883
+
5884
+        ActualSender = CallerID; // P-Asserted-Identity;
5885
+    }
5886
+
5887
+    // Current stream
5888
+    var currentStream = JSON.parse(localDB.getItem(buddyObj.identity + "-stream"));
5889
+    if(currentStream == null) currentStream = InitinaliseStream(buddyObj.identity);
5890
+
5891
+    // Add new message
5892
+    var newMessageJson = {
5893
+        ItemId: messageId,
5894
+        ItemType: "MSG",
5895
+        ItemDate: DateTime,
5896
+        SrcUserId: buddyObj.identity,
5897
+        Src: "\""+ buddyObj.CallerIDName +"\" <"+ buddyObj.ExtNo +">",
5898
+        DstUserId: profileUserID,
5899
+        Dst: "",
5900
+        MessageData: originalMessage
5901
+    }
5902
+
5903
+    // If a file is received, add the received file section
5904
+    if (fileSentDuringChat == 1 && recFileName != '') {
5905
+
5906
+        fileSentDuringChat = 0;
5907
+
5908
+        var newMessageId = uID();
5909
+        var newDateTime = moment.utc().format("YYYY-MM-DD HH:mm:ss UTC");
5910
+
5911
+	var newFileMessageJson = {
5912
+	        ItemId: newMessageId,
5913
+	        ItemType: "FILE",
5914
+	        ItemDate: newDateTime,
5915
+	        SrcUserId: buddyObj.identity,
5916
+                Src: "\""+ buddyObj.CallerIDName +"\" <"+ buddyObj.ExtNo +">",
5917
+	        DstUserId: profileUserID,
5918
+	        Dst: profileUser,
5919
+                ReceivedFileName: recFileName,
5920
+	        MessageData: "Download file"
5921
+	}
5922
+
5923
+        currentStream.DataCollection.push(newFileMessageJson);
5924
+    }
5925
+
5926
+    currentStream.DataCollection.push(newMessageJson);
5927
+
5928
+    currentStream.TotalRows = currentStream.DataCollection.length;
5929
+    localDB.setItem(buddyObj.identity + "-stream", JSON.stringify(currentStream));
5930
+
5931
+    // Update Last Activity
5932
+    // ====================
5933
+    UpdateBuddyActivity(buddyObj.identity);
5934
+    RefreshStream(buddyObj);
5935
+
5936
+    // Handle Stream Not visible
5937
+    // =========================
5938
+    var streamVisible = $("#stream-"+ buddyObj.identity).is(":visible");
5939
+    if (!streamVisible) {
5940
+        // Add or Increase the Badge
5941
+        IncreaseMissedBadge(buddyObj.identity);
5942
+        if ("Notification" in window) {
5943
+            if (Notification.permission === "granted") {
5944
+                var imageUrl = getPicture(buddyObj.identity);
5945
+                var noticeOptions = { body: originalMessage.substring(0, 250), icon: imageUrl }
5946
+                var inComingChatNotification = new Notification(lang.message_from + " : " + buddyObj.CallerIDName, noticeOptions);
5947
+                inComingChatNotification.onclick = function (event) {
5948
+                    // Show Message
5949
+                    SelectBuddy(buddyObj.identity);
5950
+                }
5951
+            }
5952
+        }
5953
+        // Play Alert
5954
+        console.log("Audio:", audioBlobs.Alert.url);
5955
+        var rinnger = new Audio(audioBlobs.Alert.blob);
5956
+        rinnger.preload = "auto";
5957
+        rinnger.loop = false;
5958
+        rinnger.oncanplaythrough = function(e) {
5959
+            if (typeof rinnger.sinkId !== 'undefined' && getRingerOutputID() != "default") {
5960
+                rinnger.setSinkId(getRingerOutputID()).then(function() {
5961
+                    console.log("Set sinkId to:", getRingerOutputID());
5962
+                }).catch(function(e){
5963
+                    console.warn("Failed not apply setSinkId.", e);
5964
+                });
5965
+            }
5966
+            // If there has been no interaction with the page at all... this page will not work
5967
+            rinnger.play().then(function(){
5968
+               // Audio Is Playing
5969
+            }).catch(function(e){
5970
+                console.warn("Unable to play audio file.", e);
5971
+            });
5972
+        }
5973
+        message.data.rinngerObj = rinnger; // Will be attached to this object until its disposed.
5974
+    } else {
5975
+        // Message window is active.
5976
+    }
5977
+}
5978
+function AddCallMessage(buddy, session, reasonCode, reasonText) {
5979
+
5980
+    var currentStream = JSON.parse(localDB.getItem(buddy + "-stream"));
5981
+    if(currentStream == null) currentStream = InitinaliseStream(buddy);
5982
+
5983
+    var CallEnd = moment.utc(); // Take Now as the Hangup Time
5984
+    var callDuration = 0;
5985
+    var totalDuration = 0;
5986
+    var ringTime = 0;
5987
+
5988
+    var CallStart = moment.utc(session.data.callstart.replace(" UTC", "")); // Actual start (both inbound and outbound)
5989
+    var CallAnswer = null; // On Accept when inbound, Remote Side when Outbound
5990
+    if(session.startTime){
5991
+        // The time when WE answered the call (May be null - no answer)
5992
+        // or
5993
+        // The time when THEY answered the call (May be null - no answer)
5994
+        CallAnswer = moment.utc(session.startTime);  // Local Time gets converted to UTC 
5995
+
5996
+        callDuration = moment.duration(CallEnd.diff(CallAnswer));
5997
+        ringTime = moment.duration(CallAnswer.diff(CallStart));
5998
+    }
5999
+    totalDuration = moment.duration(CallEnd.diff(CallStart));
6000
+
6001
+    console.log(session.data.reasonCode + "("+ session.data.reasonText +")")
6002
+
6003
+    var srcId = "";
6004
+    var srcCallerID = "";
6005
+    var dstId = ""
6006
+    var dstCallerID = "";
6007
+    if(session.data.calldirection == "inbound") {
6008
+        srcId = buddy;
6009
+        dstId = profileUserID;
6010
+        srcCallerID = "<"+ session.remoteIdentity.uri.user +"> "+ session.remoteIdentity.displayName;
6011
+        dstCallerID = "<"+ profileUser+"> "+ profileName;
6012
+    } else if(session.data.calldirection == "outbound") {
6013
+        srcId = profileUserID;
6014
+        dstId = buddy;
6015
+        srcCallerID = "<"+ profileUser+"> "+ profileName;
6016
+        dstCallerID = session.remoteIdentity.uri.user;
6017
+    }
6018
+
6019
+    var callDirection = session.data.calldirection;
6020
+    var withVideo = session.data.withvideo;
6021
+    var sessionId = session.id;
6022
+    var hanupBy = session.data.terminateby;
6023
+
6024
+    var newMessageJson = {
6025
+        CdrId: uID(),
6026
+        ItemType: "CDR",
6027
+        ItemDate: CallStart.format("YYYY-MM-DD HH:mm:ss UTC"),
6028
+        CallAnswer: (CallAnswer)? CallAnswer.format("YYYY-MM-DD HH:mm:ss UTC") : null,
6029
+        CallEnd: CallEnd.format("YYYY-MM-DD HH:mm:ss UTC"),
6030
+        SrcUserId: srcId,
6031
+        Src: srcCallerID,
6032
+        DstUserId: dstId,
6033
+        Dst: dstCallerID,
6034
+        RingTime: (ringTime != 0)? ringTime.asSeconds() : 0,
6035
+        Billsec: (callDuration != 0)? callDuration.asSeconds() : 0,
6036
+        TotalDuration: (totalDuration != 0)? totalDuration.asSeconds() : 0,
6037
+        ReasonCode: reasonCode,
6038
+        ReasonText: reasonText,
6039
+        WithVideo: withVideo,
6040
+        SessionId: sessionId,
6041
+        CallDirection: callDirection,
6042
+        Terminate: hanupBy,
6043
+        // CRM
6044
+        MessageData: null,
6045
+        Tags: [],
6046
+        //Reporting
6047
+        Transfers: (session.data.transfer)? session.data.transfer : [],
6048
+        Mutes: (session.data.mute)? session.data.mute : [],
6049
+        Holds: (session.data.hold)? session.data.hold : [],
6050
+        Recordings: (session.data.recordings)? session.data.recordings : [],
6051
+        ConfCalls: (session.data.confcalls)? session.data.confcalls : [],
6052
+        QOS: []
6053
+    }
6054
+
6055
+    console.log("New CDR", newMessageJson);
6056
+
6057
+    currentStream.DataCollection.push(newMessageJson);
6058
+    currentStream.TotalRows = currentStream.DataCollection.length;
6059
+    localDB.setItem(buddy + "-stream", JSON.stringify(currentStream));
6060
+
6061
+    UpdateBuddyActivity(buddy);
6062
+}
6063
+
6064
+function SendImageDataMessage(buddy, ImgDataUrl) {
6065
+    if (userAgent == null) return;
6066
+    if (!userAgent.isRegistered()) return;
6067
+
6068
+    // Ajax Upload
6069
+    // ===========
6070
+
6071
+    var DateTime = moment.utc().format("YYYY-MM-DD HH:mm:ss UTC");
6072
+    var formattedMessage = '<IMG class=previewImage onClick="PreviewImage(this)" src="'+ ImgDataUrl +'">';
6073
+    var messageString = "<table class=\"ourChatMessage chatMessageTable\" cellspacing=0 cellpadding=0><tr><td style=\"width: 80px\">"
6074
+        + "<div class=messageDate>" + DateTime + "</div>"
6075
+        + "</td><td>"
6076
+        + "<div class=ourChatMessageText>" + formattedMessage + "</div>"
6077
+        + "</td></tr></table>";
6078
+    $("#contact-" + buddy + "-ChatHistory").append(messageString);
6079
+    updateScroll(buddy);
6080
+
6081
+    ImageEditor_Cancel(buddy);
6082
+
6083
+    UpdateBuddyActivity(buddy);
6084
+}
6085
+
6086
+function SendFileDataMessage(buddy, FileDataUrl, fileName, fileSize) {
6087
+    if (userAgent == null) return;
6088
+    if (!userAgent.isRegistered()) return;
6089
+
6090
+    var fileID = uID();
6091
+
6092
+    // Ajax Upload
6093
+    // ===========
6094
+    $.ajax({
6095
+        type:'POST',
6096
+        url: '/api/',
6097
+        data: "<XML>"+ FileDataUrl +"</XML>",
6098
+        xhr: function(e) {
6099
+            var myXhr = $.ajaxSettings.xhr();
6100
+            if(myXhr.upload){
6101
+                myXhr.upload.addEventListener('progress',function(event){
6102
+                    var percent = (event.loaded / event.total) * 100;
6103
+                    console.log("Progress for upload to "+ buddy +" ("+ fileID +"):"+ percent);
6104
+                    $("#FileProgress-Bar-"+ fileID).css("width", percent +"%");
6105
+                }, false);
6106
+            }
6107
+            return myXhr;
6108
+        },
6109
+        success:function(data, status, jqXHR){
6110
+            // console.log(data);
6111
+            $("#FileUpload-"+ fileID).html("Sent");
6112
+            $("#FileProgress-"+ fileID).hide();
6113
+            $("#FileProgress-Bar-"+ fileID).css("width", "0%");
6114
+        },
6115
+        error: function(data, status, error){
6116
+            // console.log(data);
6117
+            $("#FileUpload-"+ fileID).html("Failed ("+ data.status +")");
6118
+            $("#FileProgress-"+ fileID).hide();
6119
+            $("#FileProgress-Bar-"+ fileID).css("width", "100%");
6120
+        }
6121
+    });
6122
+
6123
+    // Add To Message Stream
6124
+    // =====================
6125
+    var DateTime = utcDateNow();
6126
+
6127
+    var showReview = false;
6128
+    var fileIcon = '<i class="fa fa-file"></i>';
6129
+    // Image Icons
6130
+    if(fileName.toLowerCase().endsWith(".png")) {
6131
+        fileIcon =  '<i class="fa fa-file-image-o"></i>';
6132
+        showReview = true;
6133
+    }
6134
+    if(fileName.toLowerCase().endsWith(".jpg")) {
6135
+        fileIcon =  '<i class="fa fa-file-image-o"></i>';
6136
+        showReview = true;
6137
+    }
6138
+    if(fileName.toLowerCase().endsWith(".jpeg")) {
6139
+        fileIcon =  '<i class="fa fa-file-image-o"></i>';
6140
+        showReview = true;
6141
+    }
6142
+    if(fileName.toLowerCase().endsWith(".bmp")) {
6143
+        fileIcon =  '<i class="fa fa-file-image-o"></i>';
6144
+        showReview = true;
6145
+    }
6146
+    if(fileName.toLowerCase().endsWith(".gif")) {
6147
+        fileIcon =  '<i class="fa fa-file-image-o"></i>';
6148
+        showReview = true;
6149
+    }
6150
+    // video Icons
6151
+    if(fileName.toLowerCase().endsWith(".mov")) fileIcon =  '<i class="fa fa-file-video-o"></i>';
6152
+    if(fileName.toLowerCase().endsWith(".avi")) fileIcon =  '<i class="fa fa-file-video-o"></i>';
6153
+    if(fileName.toLowerCase().endsWith(".mpeg")) fileIcon =  '<i class="fa fa-file-video-o"></i>';
6154
+    if(fileName.toLowerCase().endsWith(".mp4")) fileIcon =  '<i class="fa fa-file-video-o"></i>';
6155
+    if(fileName.toLowerCase().endsWith(".mvk")) fileIcon =  '<i class="fa fa-file-video-o"></i>';
6156
+    if(fileName.toLowerCase().endsWith(".webm")) fileIcon =  '<i class="fa fa-file-video-o"></i>';
6157
+    // Audio Icons
6158
+    if(fileName.toLowerCase().endsWith(".wav")) fileIcon =  '<i class="fa fa-file-audio-o"></i>';
6159
+    if(fileName.toLowerCase().endsWith(".mp3")) fileIcon =  '<i class="fa fa-file-audio-o"></i>';
6160
+    if(fileName.toLowerCase().endsWith(".ogg")) fileIcon =  '<i class="fa fa-file-audio-o"></i>';
6161
+    // Compressed Icons
6162
+    if(fileName.toLowerCase().endsWith(".zip")) fileIcon =  '<i class="fa fa-file-archive-o"></i>';
6163
+    if(fileName.toLowerCase().endsWith(".rar")) fileIcon =  '<i class="fa fa-file-archive-o"></i>';
6164
+    if(fileName.toLowerCase().endsWith(".tar.gz")) fileIcon =  '<i class="fa fa-file-archive-o"></i>';
6165
+    // Pdf Icons
6166
+    if(fileName.toLowerCase().endsWith(".pdf")) fileIcon =  '<i class="fa fa-file-pdf-o"></i>';
6167
+
6168
+    var formattedMessage = "<DIV><SPAN id=\"FileUpload-"+ fileID +"\">Sending</SPAN>: "+ fileIcon +" "+ fileName +"</DIV>"
6169
+    formattedMessage += "<DIV id=\"FileProgress-"+ fileID +"\" class=\"progressBarContainer\"><DIV id=\"FileProgress-Bar-"+ fileID +"\" class=\"progressBarTrack\"></DIV></DIV>"
6170
+    if(showReview){
6171
+        formattedMessage += "<DIV><IMG class=previewImage onClick=\"PreviewImage(this)\" src=\""+ FileDataUrl +"\"></DIV>";
6172
+    }
6173
+
6174
+    var messageString = "<table class=\"ourChatMessage chatMessageTable\" cellspacing=0 cellpadding=0><tr><td style=\"width: 80px\">"
6175
+        + "<div class=messageDate>" + DateTime + "</div>"
6176
+        + "</td><td>"
6177
+        + "<div class=ourChatMessageText>" + formattedMessage + "</div>"
6178
+        + "</td></tr></table>";
6179
+    $("#contact-" + buddy + "-ChatHistory").append(messageString);
6180
+    updateScroll(buddy);
6181
+
6182
+    ImageEditor_Cancel(buddy);
6183
+
6184
+    // Update Last Activity
6185
+    // ====================
6186
+    UpdateBuddyActivity(buddy);
6187
+}
6188
+function updateLineScroll(lineNum) {
6189
+    RefreshLineActivity(lineNum);
6190
+
6191
+    var element = $("#line-"+ lineNum +"-CallDetails").get(0);
6192
+    element.scrollTop = element.scrollHeight;
6193
+}
6194
+function updateScroll(buddy) {
6195
+    var history = $("#contact-"+ buddy +"-ChatHistory");
6196
+    if(history.children().length > 0) history.children().last().get(0).scrollIntoView(false);
6197
+    history.get(0).scrollTop = history.get(0).scrollHeight;
6198
+}
6199
+function PreviewImage(obj){
6200
+
6201
+    $.jeegoopopup.close();
6202
+    var previewimgHtml = '<div>';
6203
+    previewimgHtml += '<div class="UiWindowField scroller">';
6204
+    previewimgHtml += '<div><img src="'+ obj.src +'"/></div>';
6205
+    previewimgHtml += '</div></div>';
6206
+
6207
+    $.jeegoopopup.open({
6208
+                title: 'Preview Image',
6209
+                html: previewimgHtml,
6210
+                width: '800',
6211
+                height: '600',
6212
+                center: true,
6213
+                scrolling: 'no',
6214
+                skinClass: 'jg_popup_basic',
6215
+                overlay: true,
6216
+                opacity: 50,
6217
+                draggable: true,
6218
+                resizable: false,
6219
+                fadeIn: 0
6220
+    });
6221
+    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); });
6222
+    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); } });
6223
+}
6224
+
6225
+// Missed Item Notification
6226
+// ========================
6227
+function IncreaseMissedBadge(buddy) {
6228
+    var buddyObj = FindBuddyByIdentity(buddy);
6229
+    if(buddyObj == null) return;
6230
+
6231
+    // Up the Missed Count
6232
+    // ===================
6233
+    buddyObj.missed += 1;
6234
+
6235
+    // Take Out
6236
+    var json = JSON.parse(localDB.getItem(profileUserID + "-Buddies"));
6237
+    if(json != null) {
6238
+        $.each(json.DataCollection, function (i, item) {
6239
+            if(item.uID == buddy || item.cID == buddy || item.gID == buddy){
6240
+                item.missed = item.missed +1;
6241
+                return false;
6242
+            }
6243
+        });
6244
+        // Put Back
6245
+        localDB.setItem(profileUserID + "-Buddies", JSON.stringify(json));
6246
+    }
6247
+
6248
+    // Update Badge
6249
+    // ============
6250
+    $("#contact-" + buddy + "-missed").text(buddyObj.missed);
6251
+    $("#contact-" + buddy + "-missed").show();
6252
+    console.log("Set Missed badge for "+ buddy +" to: "+ buddyObj.missed);
6253
+}
6254
+function UpdateBuddyActivity(buddy){
6255
+    var buddyObj = FindBuddyByIdentity(buddy);
6256
+    if(buddyObj == null) return;
6257
+
6258
+    // Update Last Activity Time
6259
+    // =========================
6260
+    var timeStamp = utcDateNow();
6261
+    buddyObj.lastActivity = timeStamp;
6262
+    console.log("Last Activity is now: "+ timeStamp);
6263
+
6264
+    // Take Out
6265
+    var json = JSON.parse(localDB.getItem(profileUserID + "-Buddies"));
6266
+    if(json != null) {
6267
+        $.each(json.DataCollection, function (i, item) {
6268
+            if(item.uID == buddy || item.cID == buddy || item.gID == buddy){
6269
+                item.LastActivity = timeStamp;
6270
+                return false;
6271
+            }
6272
+        });
6273
+        // Put Back
6274
+        localDB.setItem(profileUserID + "-Buddies", JSON.stringify(json));
6275
+    }
6276
+
6277
+    // List Update
6278
+    // ===========
6279
+    UpdateBuddyList();
6280
+}
6281
+function ClearMissedBadge(buddy) {
6282
+    var buddyObj = FindBuddyByIdentity(buddy);
6283
+    if(buddyObj == null) return;
6284
+
6285
+    buddyObj.missed = 0;
6286
+
6287
+    // Take Out
6288
+    var json = JSON.parse(localDB.getItem(profileUserID + "-Buddies"));
6289
+    if(json != null) {
6290
+        $.each(json.DataCollection, function (i, item) {
6291
+            if(item.uID == buddy || item.cID == buddy || item.gID == buddy){
6292
+                item.missed = 0;
6293
+                return false;
6294
+            }
6295
+        });
6296
+        // Put Back
6297
+        localDB.setItem(profileUserID + "-Buddies", JSON.stringify(json));
6298
+    }
6299
+
6300
+    $("#contact-" + buddy + "-missed").text(buddyObj.missed);
6301
+    $("#contact-" + buddy + "-missed").hide(400);
6302
+}
6303
+
6304
+// Outbound Calling
6305
+// ================
6306
+function VideoCall(lineObj, dialledNumber) {
6307
+    if (userAgent == null) return;
6308
+    if (!userAgent.isRegistered()) return;
6309
+    if(lineObj == null) return;
6310
+
6311
+    if(HasAudioDevice == false){
6312
+        Alert(lang.alert_no_microphone);
6313
+        return;
6314
+    }
6315
+
6316
+    if(HasVideoDevice == false){
6317
+        console.warn("No video devices (webcam) found, switching to audio call.");
6318
+        AudioCall(lineObj, dialledNumber);
6319
+        return;
6320
+    }
6321
+
6322
+    var supportedConstraints = navigator.mediaDevices.getSupportedConstraints();
6323
+    var spdOptions = {
6324
+        sessionDescriptionHandlerOptions: {
6325
+            constraints: {
6326
+                audio: { deviceId : "default" },
6327
+                video: { deviceId : "default" }
6328
+            }
6329
+        }
6330
+    }
6331
+
6332
+    // Configure Audio
6333
+    var currentAudioDevice = getAudioSrcID();
6334
+    if(currentAudioDevice != "default"){
6335
+        var confirmedAudioDevice = false;
6336
+        for (var i = 0; i < AudioinputDevices.length; ++i) {
6337
+            if(currentAudioDevice == AudioinputDevices[i].deviceId) {
6338
+                confirmedAudioDevice = true;
6339
+                break;
6340
+            }
6341
+        }
6342
+        if(confirmedAudioDevice) {
6343
+            spdOptions.sessionDescriptionHandlerOptions.constraints.audio.deviceId = { exact: currentAudioDevice }
6344
+        }
6345
+        else {
6346
+            console.warn("The audio device you used before is no longer available, default settings applied.");
6347
+            localDB.setItem("AudioSrcId", "default");
6348
+        }
6349
+    }
6350
+    // Add additional Constraints
6351
+    if(supportedConstraints.autoGainControl) {
6352
+        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.autoGainControl = AutoGainControl;
6353
+    }
6354
+    if(supportedConstraints.echoCancellation) {
6355
+        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.echoCancellation = EchoCancellation;
6356
+    }
6357
+    if(supportedConstraints.noiseSuppression) {
6358
+        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.noiseSuppression = NoiseSuppression;
6359
+    }
6360
+
6361
+    // Configure Video
6362
+    var currentVideoDevice = getVideoSrcID();
6363
+    if(currentVideoDevice != "default"){
6364
+        var confirmedVideoDevice = false;
6365
+        for (var i = 0; i < VideoinputDevices.length; ++i) {
6366
+            if(currentVideoDevice == VideoinputDevices[i].deviceId) {
6367
+                confirmedVideoDevice = true;
6368
+                break;
6369
+            }
6370
+        }
6371
+        if(confirmedVideoDevice){
6372
+            spdOptions.sessionDescriptionHandlerOptions.constraints.video.deviceId = { exact: currentVideoDevice }
6373
+        }
6374
+        else {
6375
+            console.warn("The video device you used before is no longer available, default settings applied.");
6376
+            localDB.setItem("VideoSrcId", "default"); // resets for later and subsequent calls
6377
+        }
6378
+    }
6379
+    // Add additional Constraints
6380
+    if(supportedConstraints.frameRate && maxFrameRate != "") {
6381
+        spdOptions.sessionDescriptionHandlerOptions.constraints.video.frameRate = maxFrameRate;
6382
+    }
6383
+    if(supportedConstraints.height && videoHeight != "") {
6384
+        spdOptions.sessionDescriptionHandlerOptions.constraints.video.height = videoHeight;
6385
+    }
6386
+    console.log(supportedConstraints)
6387
+    console.log(supportedConstraints.aspectRatio)
6388
+    console.log(videoAspectRatio)
6389
+    if(supportedConstraints.aspectRatio && videoAspectRatio != "") {
6390
+        spdOptions.sessionDescriptionHandlerOptions.constraints.video.aspectRatio = videoAspectRatio;
6391
+    }
6392
+
6393
+    $("#line-" + lineObj.LineNumber + "-msg").html(lang.starting_video_call);
6394
+    $("#line-" + lineObj.LineNumber + "-timer").show();
6395
+
6396
+    // Invite
6397
+    console.log("INVITE (video): " + dialledNumber + "@" + wssServer, spdOptions);
6398
+    lineObj.SipSession = userAgent.invite("sip:" + dialledNumber + "@" + wssServer, spdOptions);
6399
+
6400
+    var startTime = moment.utc();
6401
+    lineObj.SipSession.data.line = lineObj.LineNumber;
6402
+    lineObj.SipSession.data.buddyId = lineObj.BuddyObj.identity;
6403
+    lineObj.SipSession.data.calldirection = "outbound";
6404
+    lineObj.SipSession.data.dst = dialledNumber;
6405
+    lineObj.SipSession.data.callstart = startTime.format("YYYY-MM-DD HH:mm:ss UTC");
6406
+    lineObj.SipSession.data.callTimer = window.setInterval(function(){
6407
+        var now = moment.utc();
6408
+        var duration = moment.duration(now.diff(startTime)); 
6409
+        $("#line-" + lineObj.LineNumber + "-timer").html(formatShortDuration(duration.asSeconds()));
6410
+    }, 1000);
6411
+    lineObj.SipSession.data.VideoSourceDevice = getVideoSrcID();
6412
+    lineObj.SipSession.data.AudioSourceDevice = getAudioSrcID();
6413
+    lineObj.SipSession.data.AudioOutputDevice = getAudioOutputID();
6414
+    lineObj.SipSession.data.terminateby = "them";
6415
+    lineObj.SipSession.data.withvideo = true;
6416
+
6417
+    updateLineScroll(lineObj.LineNumber);
6418
+
6419
+    // Do Necessary UI Wireup
6420
+    wireupVideoSession(lineObj);
6421
+
6422
+    // Custom Web hook
6423
+    if(typeof web_hook_on_invite !== 'undefined') web_hook_on_invite(lineObj.SipSession);
6424
+}
6425
+
6426
+function ComposeEmail(buddy, obj, event) {
6427
+
6428
+        event.stopPropagation();
6429
+        SelectBuddy(buddy);
6430
+
6431
+        var buddyObj = FindBuddyByIdentity(buddy);
6432
+
6433
+	$("#roundcubeFrame").remove();
6434
+	$("#rightContent").show();
6435
+	$(".streamSelected").each(function() { $(this).css("display", "none"); });
6436
+	$("#rightContent").append('<iframe id="roundcubeFrame" name="displayFrame"></iframe>');
6437
+
6438
+	var rcDomain = '';
6439
+	var rcBasicAuthUser = '';
6440
+	var rcBasicAuthPass = '';
6441
+	var rcUsername = '';
6442
+	var rcPasswd = '';
6443
+
6444
+	$.ajax({
6445
+	     'async': false,
6446
+	     'global': false,
6447
+	     type: "POST",
6448
+	     url: "get-email-info.php",
6449
+	     dataType: "JSON",
6450
+	     data: {
6451
+		     username: userName,
6452
+		     s_ajax_call: validateSToken
6453
+	     },
6454
+	     success: function(datafromdb) {
6455
+		               rcDomain = datafromdb.rcdomain;
6456
+		               rcBasicAuthUser = encodeURIComponent(datafromdb.rcbasicauthuser);                              
6457
+		               rcBasicAuthPass = encodeURIComponent(datafromdb.rcbasicauthpass);
6458
+		               rcUsername = datafromdb.rcuser;
6459
+		               rcPasswd = datafromdb.rcpassword;
6460
+	     },
6461
+	     error: function(datafromdb) {
6462
+		             alert("An error occurred while trying to retrieve data from the database!");
6463
+	     }
6464
+	});
6465
+
6466
+	if (rcBasicAuthUser != '' && rcBasicAuthPass != '') { 
6467
+	    var loginURL = "https://"+ rcBasicAuthUser +":"+ rcBasicAuthPass +"@"+ rcDomain +"/";
6468
+            var composeURL = "https://"+ rcBasicAuthUser +":"+ rcBasicAuthPass +"@"+ rcDomain +"/?_task=mail&_action=compose&_to="+ encodeURIComponent(buddyObj.Email) +"";
6469
+	} else { 
6470
+            var loginURL = "https://"+ rcDomain +"/";
6471
+            var composeURL = "https://"+ rcDomain +"/?_task=mail&_action=compose&_to="+ encodeURIComponent(buddyObj.Email) +"";
6472
+        }
6473
+
6474
+	var form = '<form id="rcForm" method="POST" action="'+ loginURL +'" target="displayFrame">'; 
6475
+	form += '<input type="hidden" name="_action" value="login" />';
6476
+	form += '<input type="hidden" name="_task" value="login" />';
6477
+	form += '<input type="hidden" name="_autologin" value="1" />';
6478
+	form += '<input name="_user" value="'+ rcUsername +'" type="text" />';
6479
+	form += '<input name="_pass" value="'+ rcPasswd +'" type="password" />';
6480
+	form += '<input id="submitButton" type="submit" value="Login" />';
6481
+	form += '</form>';
6482
+
6483
+	$("#roundcubeFrame").append(form);
6484
+
6485
+        if (RCLoginCheck == 0) {
6486
+            $("#submitButton").click();
6487
+            RCLoginCheck = 1;
6488
+
6489
+            if (rcBasicAuthUser != '' && rcBasicAuthPass != '') {
6490
+                if (confirm('You are about to log in to the site "'+ rcDomain +'" with the username "'+ rcBasicAuthUser +'".')) {
6491
+                    $("#roundcubeFrame").attr("src", composeURL);
6492
+                }
6493
+            } else { setTimeout(function() { $("#roundcubeFrame").attr("src", composeURL); }, 1000); }
6494
+
6495
+//            setTimeout(function() { $("#roundcubeFrame").attr("src", composeURL); }, 1000);
6496
+
6497
+        } else { $("#roundcubeFrame").attr("src", composeURL); }
6498
+}
6499
+function AudioCallMenu(buddy, obj){
6500
+
6501
+    if (($(window).width() - event.pageX) > 54) { var leftPos = event.pageX - 222; } else { var leftPos = event.pageX - 276; }
6502
+    if (($(window).height() - event.pageY) > 140) { var topPos = event.pageY + 27; } else { var topPos = event.pageY - 80; }
6503
+
6504
+    var buddyObj = FindBuddyByIdentity(buddy);
6505
+
6506
+    if(buddyObj.type == "extension") {
6507
+
6508
+        // Extension
6509
+        var menu = "<div id=quickCallMenu>";
6510
+        menu += "<table id=quickCallTable cellspacing=10 cellpadding=0 style=\"margin-left:auto; margin-right: auto\">";
6511
+
6512
+        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>";
6513
+
6514
+        if (buddyObj.MobileNumber != null && buddyObj.MobileNumber != "") {
6515
+            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>";
6516
+        }
6517
+
6518
+        if (buddyObj.ContactNumber1 != null && buddyObj.ContactNumber1 != "") {
6519
+            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>";
6520
+        }
6521
+
6522
+        if (buddyObj.ContactNumber2 != null && buddyObj.ContactNumber2 != "") {
6523
+            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>";
6524
+        }
6525
+
6526
+        menu += "</table>";
6527
+        menu += "</div>";
6528
+
6529
+        var consoleLogContent = "Menu click AudioCall("+ buddy +", ";
6530
+
6531
+    } else if (buddyObj.type == "contact") {
6532
+
6533
+        // Contact
6534
+        var menu = "<div id=quickCallMenu>";
6535
+        menu += "<table id=quickCallTable cellspacing=10 cellpadding=0 style=\"margin-left:auto; margin-right: auto\">";
6536
+
6537
+        if (buddyObj.MobileNumber != null && buddyObj.MobileNumber != "") {
6538
+            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>";
6539
+        }
6540
+
6541
+        if (buddyObj.ContactNumber1 != null && buddyObj.ContactNumber1 != "") {
6542
+            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>";
6543
+        }
6544
+
6545
+        if (buddyObj.ContactNumber2 != null && buddyObj.ContactNumber2 != "") {
6546
+            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>";
6547
+        }
6548
+
6549
+        menu += "</table>";
6550
+        menu += "</div>";
6551
+
6552
+        var consoleLogContent = "Menu click AudioCall("+ buddy +", ";
6553
+
6554
+    } else if(buddyObj.type == "group") {
6555
+
6556
+        var menu = "<div id=quickCallMenu>";
6557
+        menu += "<table id=quickCallTable cellspacing=10 cellpadding=0 style=\"margin-left:auto; margin-right: auto\">";
6558
+        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>";
6559
+        menu += "</table>";
6560
+        menu += "</div>";
6561
+
6562
+        var consoleLogContent = "Menu click AudioCallGroup("+ buddy +", ";
6563
+
6564
+    }
6565
+
6566
+    $.jeegoopopup.open({
6567
+                html: menu,
6568
+                width: 'auto',
6569
+                height: 'auto',
6570
+                left: leftPos,
6571
+                top: topPos,
6572
+                scrolling: 'no',
6573
+                skinClass: 'jg_popup_basic',
6574
+                overlay: true,
6575
+                opacity: 0,
6576
+                draggable: false,
6577
+                resizable: false,
6578
+                fadeIn: 0
6579
+    });
6580
+
6581
+    $("#quickCallTable").on("click", ".quickNumDialRow", function() {
6582
+       var NumberToDial = $(this).closest("tr").find("span.quickNumToDial").html();
6583
+       console.log(consoleLogContent + NumberToDial +")");
6584
+       DialByLine("audio", buddy, NumberToDial);
6585
+    });
6586
+
6587
+    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); });
6588
+    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); } });
6589
+}
6590
+function AudioCall(lineObj, dialledNumber) {
6591
+    if(userAgent == null) return;
6592
+    if(userAgent.isRegistered() == false) return;
6593
+    if(lineObj == null) return;
6594
+
6595
+    if(HasAudioDevice == false){
6596
+        Alert(lang.alert_no_microphone);
6597
+        return;
6598
+    }
6599
+
6600
+    var supportedConstraints = navigator.mediaDevices.getSupportedConstraints();
6601
+
6602
+    var spdOptions = {
6603
+        sessionDescriptionHandlerOptions: {
6604
+            constraints: {
6605
+                audio: { deviceId : "default" },
6606
+                video: false
6607
+            }
6608
+        }
6609
+    }
6610
+    // Configure Audio
6611
+    var currentAudioDevice = getAudioSrcID();
6612
+    if(currentAudioDevice != "default"){
6613
+        var confirmedAudioDevice = false;
6614
+        for (var i = 0; i < AudioinputDevices.length; ++i) {
6615
+            if(currentAudioDevice == AudioinputDevices[i].deviceId) {
6616
+                confirmedAudioDevice = true;
6617
+                break;
6618
+            }
6619
+        }
6620
+        if(confirmedAudioDevice) {
6621
+            spdOptions.sessionDescriptionHandlerOptions.constraints.audio.deviceId = { exact: currentAudioDevice }
6622
+        }
6623
+        else {
6624
+            console.warn("The audio device you used before is no longer available, default settings applied.");
6625
+            localDB.setItem("AudioSrcId", "default");
6626
+        }
6627
+    }
6628
+    // Add additional Constraints
6629
+    if(supportedConstraints.autoGainControl) {
6630
+        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.autoGainControl = AutoGainControl;
6631
+    }
6632
+    if(supportedConstraints.echoCancellation) {
6633
+        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.echoCancellation = EchoCancellation;
6634
+    }
6635
+    if(supportedConstraints.noiseSuppression) {
6636
+        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.noiseSuppression = NoiseSuppression;
6637
+    }
6638
+
6639
+    $("#line-" + lineObj.LineNumber + "-msg").html(lang.starting_audio_call);
6640
+    $("#line-" + lineObj.LineNumber + "-timer").show();
6641
+
6642
+    // Invite
6643
+    console.log("INVITE (audio): " + dialledNumber + "@" + wssServer);
6644
+    lineObj.SipSession = userAgent.invite("sip:" + dialledNumber + "@" + wssServer, spdOptions);
6645
+
6646
+    var startTime = moment.utc();
6647
+    lineObj.SipSession.data.line = lineObj.LineNumber;
6648
+    lineObj.SipSession.data.buddyId = lineObj.BuddyObj.identity;
6649
+    lineObj.SipSession.data.calldirection = "outbound";
6650
+    lineObj.SipSession.data.dst = dialledNumber;
6651
+    lineObj.SipSession.data.callstart = startTime.format("YYYY-MM-DD HH:mm:ss UTC");
6652
+    lineObj.SipSession.data.callTimer = window.setInterval(function(){
6653
+        var now = moment.utc();
6654
+        var duration = moment.duration(now.diff(startTime)); 
6655
+        $("#line-" + lineObj.LineNumber + "-timer").html(formatShortDuration(duration.asSeconds()));
6656
+    }, 1000);
6657
+    lineObj.SipSession.data.VideoSourceDevice = null;
6658
+    lineObj.SipSession.data.AudioSourceDevice = getAudioSrcID();
6659
+    lineObj.SipSession.data.AudioOutputDevice = getAudioOutputID();
6660
+    lineObj.SipSession.data.terminateby = "them";
6661
+    lineObj.SipSession.data.withvideo = false;
6662
+
6663
+    updateLineScroll(lineObj.LineNumber);
6664
+
6665
+    // Do Necessary UI Wireup
6666
+    wireupAudioSession(lineObj);
6667
+
6668
+    // Custom Web hook
6669
+    if(typeof web_hook_on_invite !== 'undefined') web_hook_on_invite(lineObj.SipSession);
6670
+}
6671
+
6672
+// Sessions & During Call Activity
6673
+// ===============================
6674
+function getSession(buddy) {
6675
+    if(userAgent == null) {
6676
+        console.warn("userAgent is null");
6677
+        return;
6678
+    }
6679
+    if(userAgent.isRegistered() == false) {
6680
+        console.warn("userAgent is not registered");
6681
+        return;
6682
+    }
6683
+
6684
+    var rtnSession = null;
6685
+    $.each(userAgent.sessions, function (i, session) {
6686
+        if(session.data.buddyId == buddy) {
6687
+           rtnSession = session;
6688
+           return false;
6689
+        }
6690
+    });
6691
+    return rtnSession;
6692
+}
6693
+function countSessions(id){
6694
+    var rtn = 0;
6695
+    if(userAgent == null) {
6696
+       console.warn("userAgent is null");
6697
+       return 0;
6698
+    }
6699
+    $.each(userAgent.sessions, function (i, session) {
6700
+        if(id != session.id) rtn ++;
6701
+    });
6702
+    return rtn;
6703
+}
6704
+function StartRecording(lineNum){
6705
+    if(CallRecordingPolicy == "disabled") {
6706
+        console.warn("Policy Disabled: Call Recording");
6707
+        return;
6708
+    }
6709
+    var lineObj = FindLineByNumber(lineNum);
6710
+    if(lineObj == null) return;
6711
+
6712
+    $("#line-"+ lineObj.LineNumber +"-btn-start-recording").hide();
6713
+    $("#line-"+ lineObj.LineNumber +"-btn-stop-recording").show();
6714
+
6715
+    var session = lineObj.SipSession;
6716
+    if(session == null){
6717
+        console.warn("Could not find session");
6718
+        return;
6719
+    }
6720
+
6721
+    var id = uID();
6722
+
6723
+    if(!session.data.recordings) session.data.recordings = [];
6724
+    session.data.recordings.push({
6725
+        uID: id,
6726
+        startTime: utcDateNow(),
6727
+        stopTime: utcDateNow(),
6728
+    });
6729
+
6730
+    if(!session.data.mediaRecorder){
6731
+        console.log("Creating call recorder...");
6732
+        var recordStream = new MediaStream();
6733
+        var pc = session.sessionDescriptionHandler.peerConnection;
6734
+        pc.getSenders().forEach(function (RTCRtpSender) {
6735
+            if(RTCRtpSender.track && RTCRtpSender.track.kind == "audio") {
6736
+                console.log("Adding sender audio track to record:", RTCRtpSender.track.label);
6737
+                recordStream.addTrack(RTCRtpSender.track);
6738
+            }
6739
+        });
6740
+        pc.getReceivers().forEach(function (RTCRtpReceiver) {
6741
+            if(RTCRtpReceiver.track && RTCRtpReceiver.track.kind == "audio") {
6742
+                console.log("Adding receiver audio track to record:", RTCRtpReceiver.track.label);
6743
+                recordStream.addTrack(RTCRtpReceiver.track);
6744
+            }
6745
+            if(session.data.withvideo){
6746
+                if(RTCRtpReceiver.track && RTCRtpReceiver.track.kind == "video") {
6747
+                    console.log("Adding receiver video track to record:", RTCRtpReceiver.track.label);
6748
+                    recordStream.addTrack(RTCRtpReceiver.track);
6749
+                }
6750
+            }
6751
+        });
6752
+
6753
+        // Resample the Video Recording
6754
+        if(session.data.withvideo){
6755
+            var recordingWidth = 640;
6756
+            var recordingHeight = 360;
6757
+            var pnpVideSize = 100;
6758
+            if(RecordingVideoSize == "HD"){
6759
+                recordingWidth = 1280;
6760
+                recordingHeight = 720;
6761
+                pnpVideSize = 144;
6762
+            }
6763
+            if(RecordingVideoSize == "FHD"){
6764
+                recordingWidth = 1920;
6765
+                recordingHeight = 1080;
6766
+                pnpVideSize = 240;
6767
+            }
6768
+
6769
+            // them-pnp
6770
+            var pnpVideo = $("#line-" + lineObj.LineNumber + "-localVideo").get(0);
6771
+            var mainVideo = $("#line-" + lineObj.LineNumber + "-remoteVideo").get(0);
6772
+            if(RecordingLayout == "us-pnp"){
6773
+                pnpVideo = $("#line-" + lineObj.LineNumber + "-remoteVideo").get(0);
6774
+                mainVideo = $("#line-" + lineObj.LineNumber + "-localVideo").get(0);
6775
+            }
6776
+            var recordingCanvas = $('<canvas/>').get(0);
6777
+            recordingCanvas.width = (RecordingLayout == "side-by-side")? (recordingWidth * 2) + 5: recordingWidth;
6778
+            recordingCanvas.height = recordingHeight;
6779
+            var recordingContext = recordingCanvas.getContext("2d");
6780
+
6781
+            window.clearInterval(session.data.recordingRedrawInterval);
6782
+            session.data.recordingRedrawInterval = window.setInterval(function(){
6783
+
6784
+                // Main Video
6785
+                var videoWidth = (mainVideo.videoWidth > 0)? mainVideo.videoWidth : recordingWidth ;
6786
+                var videoHeight = (mainVideo.videoHeight > 0)? mainVideo.videoHeight : recordingHeight ;
6787
+
6788
+                if(videoWidth >= videoHeight){
6789
+                    // Landscape / Square
6790
+                    var scale = recordingWidth / videoWidth;
6791
+                    videoWidth = recordingWidth;
6792
+                    videoHeight = videoHeight * scale;
6793
+                    if(videoHeight > recordingHeight){
6794
+                        var scale = recordingHeight / videoHeight;
6795
+                        videoHeight = recordingHeight;
6796
+                        videoWidth = videoWidth * scale;
6797
+                    }
6798
+                } 
6799
+                else {
6800
+                    // Portrait
6801
+                    var scale = recordingHeight / videoHeight;
6802
+                    videoHeight = recordingHeight;
6803
+                    videoWidth = videoWidth * scale;
6804
+                }
6805
+                var offsetX = (videoWidth < recordingWidth)? (recordingWidth - videoWidth) / 2 : 0;
6806
+                var offsetY = (videoHeight < recordingHeight)? (recordingHeight - videoHeight) / 2 : 0;
6807
+                if(RecordingLayout == "side-by-side") offsetX = recordingWidth + 5 + offsetX;
6808
+
6809
+                // Picture-in-Picture Video
6810
+                var pnpVideoHeight = pnpVideo.videoHeight;
6811
+                var pnpVideoWidth = pnpVideo.videoWidth;
6812
+                if(pnpVideoHeight > 0){
6813
+                    if(pnpVideoWidth >= pnpVideoHeight){
6814
+                        var scale = pnpVideSize / pnpVideoHeight;
6815
+                        pnpVideoHeight = pnpVideSize;
6816
+                        pnpVideoWidth = pnpVideoWidth * scale;
6817
+                    } 
6818
+                    else{
6819
+                        var scale = pnpVideSize / pnpVideoWidth;
6820
+                        pnpVideoWidth = pnpVideSize;
6821
+                        pnpVideoHeight = pnpVideoHeight * scale;
6822
+                    }
6823
+                }
6824
+                var pnpOffsetX = 10;
6825
+                var pnpOffsetY = 10;
6826
+                if(RecordingLayout == "side-by-side"){
6827
+                    pnpVideoWidth = pnpVideo.videoWidth;
6828
+                    pnpVideoHeight = pnpVideo.videoHeight;
6829
+                    if(pnpVideoWidth >= pnpVideoHeight){
6830
+                        // Landscape / Square
6831
+                        var scale = recordingWidth / pnpVideoWidth;
6832
+                        pnpVideoWidth = recordingWidth;
6833
+                        pnpVideoHeight = pnpVideoHeight * scale;
6834
+                        if(pnpVideoHeight > recordingHeight){
6835
+                            var scale = recordingHeight / pnpVideoHeight;
6836
+                            pnpVideoHeight = recordingHeight;
6837
+                            pnpVideoWidth = pnpVideoWidth * scale;
6838
+                        }
6839
+                    } 
6840
+                    else {
6841
+                        // Portrait
6842
+                        var scale = recordingHeight / pnpVideoHeight;
6843
+                        pnpVideoHeight = recordingHeight;
6844
+                        pnpVideoWidth = pnpVideoWidth * scale;
6845
+                    }
6846
+                    pnpOffsetX = (pnpVideoWidth < recordingWidth)? (recordingWidth - pnpVideoWidth) / 2 : 0;
6847
+                    pnpOffsetY = (pnpVideoHeight < recordingHeight)? (recordingHeight - pnpVideoHeight) / 2 : 0;
6848
+                }
6849
+
6850
+                // Draw Elements
6851
+                recordingContext.fillRect(0, 0, recordingCanvas.width, recordingCanvas.height);
6852
+                if(mainVideo.videoHeight > 0){
6853
+                    recordingContext.drawImage(mainVideo, offsetX, offsetY, videoWidth, videoHeight);
6854
+                }
6855
+                if(pnpVideo.videoHeight > 0 && (RecordingLayout == "side-by-side" || RecordingLayout == "us-pnp" || RecordingLayout == "them-pnp")){
6856
+                    // Only Draw the Pnp Video when needed
6857
+                    recordingContext.drawImage(pnpVideo, pnpOffsetX, pnpOffsetY, pnpVideoWidth, pnpVideoHeight);
6858
+                }
6859
+            }, Math.floor(1000/RecordingVideoFps));
6860
+            var recordingVideoMediaStream = recordingCanvas.captureStream(RecordingVideoFps);
6861
+        }
6862
+
6863
+        var mixedAudioVideoRecordStream = new MediaStream();
6864
+        mixedAudioVideoRecordStream.addTrack(MixAudioStreams(recordStream).getAudioTracks()[0]);
6865
+        if(session.data.withvideo){
6866
+           mixedAudioVideoRecordStream.addTrack(recordingVideoMediaStream.getVideoTracks()[0]);
6867
+        }
6868
+
6869
+        var mediaType = "audio/webm";
6870
+        if(session.data.withvideo) mediaType = "video/webm";
6871
+        var options = {
6872
+            mimeType : mediaType
6873
+        }
6874
+        var mediaRecorder = new MediaRecorder(mixedAudioVideoRecordStream, options);
6875
+        mediaRecorder.data = {}
6876
+        mediaRecorder.data.id = ""+ id;
6877
+        mediaRecorder.data.sessionId = ""+ session.id;
6878
+        mediaRecorder.data.buddyId = ""+ lineObj.BuddyObj.identity;
6879
+        mediaRecorder.ondataavailable = function(event) {
6880
+            console.log("Got Call Recording Data: ", event.data.size +"Bytes", this.data.id, this.data.buddyId, this.data.sessionId);
6881
+            // Save the Audio/Video file
6882
+            SaveCallRecording(event.data, this.data.id, this.data.buddyId, this.data.sessionId);
6883
+        }
6884
+
6885
+        console.log("Starting Call Recording", id);
6886
+        session.data.mediaRecorder = mediaRecorder;
6887
+        session.data.mediaRecorder.start(); // Safari does not support timeslice
6888
+        session.data.recordings[session.data.recordings.length-1].startTime = utcDateNow();
6889
+
6890
+        $("#line-" + lineObj.LineNumber + "-msg").html(lang.call_recording_started);
6891
+
6892
+        updateLineScroll(lineNum);
6893
+    }
6894
+    else if(session.data.mediaRecorder.state == "inactive") {
6895
+        session.data.mediaRecorder.data = {}
6896
+        session.data.mediaRecorder.data.id = ""+ id;
6897
+        session.data.mediaRecorder.data.sessionId = ""+ session.id;
6898
+        session.data.mediaRecorder.data.buddyId = ""+ lineObj.BuddyObj.identity;
6899
+
6900
+        console.log("Starting Call Recording", id);
6901
+        session.data.mediaRecorder.start();
6902
+        session.data.recordings[session.data.recordings.length-1].startTime = utcDateNow();
6903
+
6904
+        $("#line-" + lineObj.LineNumber + "-msg").html(lang.call_recording_started);
6905
+
6906
+        updateLineScroll(lineNum);
6907
+    } 
6908
+    else {
6909
+        console.warn("Recorder is in an unknown state");
6910
+    }
6911
+}
6912
+function SaveCallRecording(blob, id, buddy, sessionid){
6913
+    var indexedDB = window.indexedDB;
6914
+    var request = indexedDB.open("CallRecordings");
6915
+    request.onerror = function(event) {
6916
+        console.error("IndexDB Request Error:", event);
6917
+    }
6918
+    request.onupgradeneeded = function(event) {
6919
+        console.warn("Upgrade Required for IndexDB... probably because of first time use.");
6920
+        var IDB = event.target.result;
6921
+
6922
+        // Create Object Store
6923
+        if(IDB.objectStoreNames.contains("Recordings") == false){
6924
+            var objectStore = IDB.createObjectStore("Recordings", { keyPath: "uID" });
6925
+            objectStore.createIndex("sessionid", "sessionid", { unique: false });
6926
+            objectStore.createIndex("bytes", "bytes", { unique: false });
6927
+            objectStore.createIndex("type", "type", { unique: false });
6928
+            objectStore.createIndex("mediaBlob", "mediaBlob", { unique: false });
6929
+        }
6930
+        else {
6931
+            console.warn("IndexDB requested upgrade, but object store was in place");
6932
+        }
6933
+    }
6934
+    request.onsuccess = function(event) {
6935
+        console.log("IndexDB connected to CallRecordings");
6936
+
6937
+        var IDB = event.target.result;
6938
+        if(IDB.objectStoreNames.contains("Recordings") == false){
6939
+            console.warn("IndexDB CallRecordings.Recordings does not exists");
6940
+            return;
6941
+        }
6942
+        IDB.onerror = function(event) {
6943
+            console.error("IndexDB Error:", event);
6944
+        }
6945
+    
6946
+        // Prepare data to write
6947
+        var data = {
6948
+            uID: id,
6949
+            sessionid: sessionid,
6950
+            bytes: blob.size,
6951
+            type: blob.type,
6952
+            mediaBlob: blob
6953
+        }
6954
+        // Commit Transaction
6955
+        var transaction = IDB.transaction(["Recordings"], "readwrite");
6956
+        var objectStoreAdd = transaction.objectStore("Recordings").add(data);
6957
+        objectStoreAdd.onsuccess = function(event) {
6958
+            console.log("Call Recording Sucess: ", id, blob.size, blob.type, buddy, sessionid);
6959
+        }
6960
+    }
6961
+}
6962
+function StopRecording(lineNum, noConfirm){
6963
+    var lineObj = FindLineByNumber(lineNum);
6964
+    if(lineObj == null || lineObj.SipSession == null) return;
6965
+
6966
+    var session = lineObj.SipSession;
6967
+    if(noConfirm == true){
6968
+        // Called at the end of a call
6969
+        $("#line-"+ lineObj.LineNumber +"-btn-start-recording").show();
6970
+        $("#line-"+ lineObj.LineNumber +"-btn-stop-recording").hide();
6971
+
6972
+        if(session.data.mediaRecorder){
6973
+            if(session.data.mediaRecorder.state == "recording"){
6974
+                console.log("Stopping Call Recording");
6975
+                session.data.mediaRecorder.stop();
6976
+                session.data.recordings[session.data.recordings.length-1].stopTime = utcDateNow();
6977
+                window.clearInterval(session.data.recordingRedrawInterval);
6978
+
6979
+                $("#line-" + lineObj.LineNumber + "-msg").html(lang.call_recording_stopped);
6980
+
6981
+                updateLineScroll(lineNum);
6982
+            } 
6983
+            else{
6984
+                console.warn("Recorder is in an unknow state");
6985
+            }
6986
+        }
6987
+        return;
6988
+    } 
6989
+    else {
6990
+        // User attempts to end call recording
6991
+        if(CallRecordingPolicy == "enabled"){
6992
+            console.log("Policy Enabled: Call Recording");
6993
+        }
6994
+
6995
+        Confirm(lang.confirm_stop_recording, lang.stop_recording, function(){
6996
+            $("#line-"+ lineObj.LineNumber +"-btn-start-recording").show();
6997
+            $("#line-"+ lineObj.LineNumber +"-btn-stop-recording").hide();
6998
+    
6999
+            if(session.data.mediaRecorder){
7000
+                if(session.data.mediaRecorder.state == "recording"){
7001
+                    console.log("Stopping Call Recording");
7002
+                    session.data.mediaRecorder.stop();
7003
+                    session.data.recordings[session.data.recordings.length-1].stopTime = utcDateNow();
7004
+                    window.clearInterval(session.data.recordingRedrawInterval);
7005
+
7006
+                    $("#line-" + lineObj.LineNumber + "-msg").html(lang.call_recording_stopped);
7007
+
7008
+                    updateLineScroll(lineNum);
7009
+                }
7010
+                else{
7011
+                    console.warn("Recorder is in an unknow state");
7012
+                }
7013
+            }
7014
+        });
7015
+    }
7016
+}
7017
+function PlayAudioCallRecording(obj, cdrId, uID){
7018
+    var container = $(obj).parent();
7019
+    container.empty();
7020
+
7021
+    var audioObj = new Audio();
7022
+    audioObj.autoplay = false;
7023
+    audioObj.controls = true;
7024
+
7025
+    // Make sure you are playing out via the correct device
7026
+    var sinkId = getAudioOutputID();
7027
+    if (typeof audioObj.sinkId !== 'undefined') {
7028
+        audioObj.setSinkId(sinkId).then(function(){
7029
+            console.log("sinkId applied: "+ sinkId);
7030
+        }).catch(function(e){
7031
+            console.warn("Error using setSinkId: ", e);
7032
+        });
7033
+    } else {
7034
+        console.warn("setSinkId() is not possible using this browser.")
7035
+    }
7036
+
7037
+    container.append(audioObj);
7038
+
7039
+    // Get Call Recording
7040
+    var indexedDB = window.indexedDB;
7041
+    var request = indexedDB.open("CallRecordings");
7042
+    request.onerror = function(event) {
7043
+        console.error("IndexDB Request Error:", event);
7044
+    }
7045
+    request.onupgradeneeded = function(event) {
7046
+        console.warn("Upgrade Required for IndexDB... probably because of first time use.");
7047
+    }
7048
+    request.onsuccess = function(event) {
7049
+        console.log("IndexDB connected to CallRecordings");
7050
+
7051
+        var IDB = event.target.result;
7052
+        if(IDB.objectStoreNames.contains("Recordings") == false){
7053
+            console.warn("IndexDB CallRecordings.Recordings does not exists");
7054
+            return;
7055
+        } 
7056
+
7057
+        var transaction = IDB.transaction(["Recordings"]);
7058
+        var objectStoreGet = transaction.objectStore("Recordings").get(uID);
7059
+        objectStoreGet.onerror = function(event) {
7060
+            console.error("IndexDB Get Error:", event);
7061
+        }
7062
+        objectStoreGet.onsuccess = function(event) {
7063
+            $("#cdr-media-meta-size-"+ cdrId +"-"+ uID).html(" Size: "+ formatBytes(event.target.result.bytes));
7064
+            $("#cdr-media-meta-codec-"+ cdrId +"-"+ uID).html(" Codec: "+ event.target.result.type);
7065
+
7066
+            // Play
7067
+            audioObj.src = window.URL.createObjectURL(event.target.result.mediaBlob);
7068
+            audioObj.oncanplaythrough = function(){
7069
+                audioObj.play().then(function(){
7070
+                    console.log("Playback started");
7071
+                }).catch(function(e){
7072
+                    console.error("Error playing back file: ", e);
7073
+                });
7074
+            }
7075
+        }
7076
+    }
7077
+}
7078
+function PlayVideoCallRecording(obj, cdrId, uID, buddy){
7079
+    var container = $(obj).parent();
7080
+    container.empty();
7081
+
7082
+    var videoObj = $("<video>").get(0);
7083
+    videoObj.id = "callrecording-video-"+ cdrId;
7084
+    videoObj.autoplay = false;
7085
+    videoObj.controls = true;
7086
+    videoObj.ontimeupdate = function(event){
7087
+        $("#cdr-video-meta-width-"+ cdrId +"-"+ uID).html(lang.width + " : "+ event.target.videoWidth +"px");
7088
+        $("#cdr-video-meta-height-"+ cdrId +"-"+ uID).html(lang.height +" : "+ event.target.videoHeight +"px");
7089
+    }
7090
+
7091
+    var sinkId = getAudioOutputID();
7092
+    if (typeof videoObj.sinkId !== 'undefined') {
7093
+        videoObj.setSinkId(sinkId).then(function(){
7094
+            console.log("sinkId applied: "+ sinkId);
7095
+        }).catch(function(e){
7096
+            console.warn("Error using setSinkId: ", e);
7097
+        });
7098
+    } else {
7099
+        console.warn("setSinkId() is not possible using this browser.")
7100
+    }
7101
+
7102
+    container.append(videoObj);
7103
+
7104
+    // Get Call Recording
7105
+    var indexedDB = window.indexedDB;
7106
+    var request = indexedDB.open("CallRecordings");
7107
+    request.onerror = function(event) {
7108
+        console.error("IndexDB Request Error:", event);
7109
+    }
7110
+    request.onupgradeneeded = function(event) {
7111
+        console.warn("Upgrade Required for IndexDB... probably because of first time use.");
7112
+    }
7113
+    request.onsuccess = function(event) {
7114
+        console.log("IndexDB connected to CallRecordings");
7115
+
7116
+        var IDB = event.target.result;
7117
+        if(IDB.objectStoreNames.contains("Recordings") == false){
7118
+            console.warn("IndexDB CallRecordings.Recordings does not exists");
7119
+            return;
7120
+        } 
7121
+
7122
+        var transaction = IDB.transaction(["Recordings"]);
7123
+        var objectStoreGet = transaction.objectStore("Recordings").get(uID);
7124
+        objectStoreGet.onerror = function(event) {
7125
+            console.error("IndexDB Get Error:", event);
7126
+        }
7127
+        objectStoreGet.onsuccess = function(event) {
7128
+            $("#cdr-media-meta-size-"+ cdrId +"-"+ uID).html(" Size: "+ formatBytes(event.target.result.bytes));
7129
+            $("#cdr-media-meta-codec-"+ cdrId +"-"+ uID).html(" Codec: "+ event.target.result.type);
7130
+
7131
+            // Play
7132
+            videoObj.src = window.URL.createObjectURL(event.target.result.mediaBlob);
7133
+            videoObj.oncanplaythrough = function(){
7134
+                try{
7135
+                    videoObj.scrollIntoViewIfNeeded(false);
7136
+                } catch(e){}
7137
+                videoObj.play().then(function(){
7138
+                    console.log("Playback started");
7139
+                }).catch(function(e){
7140
+                    console.error("Error playing back file: ", e);
7141
+                });
7142
+
7143
+                // Create a Post Image after a second
7144
+                if(buddy){
7145
+                    window.setTimeout(function(){
7146
+                        var canvas = $("<canvas>").get(0);
7147
+                        var videoWidth = videoObj.videoWidth;
7148
+                        var videoHeight = videoObj.videoHeight;
7149
+                        if(videoWidth > videoHeight){
7150
+                            // Landscape
7151
+                            if(videoHeight > 225){
7152
+                                var p = 225 / videoHeight;
7153
+                                videoHeight = 225;
7154
+                                videoWidth = videoWidth * p;
7155
+                            }
7156
+                        }
7157
+                        else {
7158
+                            // Portrait
7159
+                            if(videoHeight > 225){
7160
+                                var p = 225 / videoWidth;
7161
+                                videoWidth = 225;
7162
+                                videoHeight = videoHeight * p;
7163
+                            }
7164
+                        }
7165
+                        canvas.width = videoWidth;
7166
+                        canvas.height = videoHeight;
7167
+                        canvas.getContext('2d').drawImage(videoObj, 0, 0, videoWidth, videoHeight);  
7168
+                        canvas.toBlob(function(blob) {
7169
+                            var reader = new FileReader();
7170
+                            reader.readAsDataURL(blob);
7171
+                            reader.onloadend = function() {
7172
+                                var Poster = { width: videoWidth, height: videoHeight, posterBase64: reader.result }
7173
+                                console.log("Capturing Video Poster...");
7174
+    
7175
+                                // Update DB
7176
+                                var currentStream = JSON.parse(localDB.getItem(buddy + "-stream"));
7177
+                                if(currentStream != null || currentStream.DataCollection != null){
7178
+                                    $.each(currentStream.DataCollection, function(i, item) {
7179
+                                        if (item.ItemType == "CDR" && item.CdrId == cdrId) {
7180
+                                            // Found
7181
+                                            if(item.Recordings && item.Recordings.length >= 1){
7182
+                                                $.each(item.Recordings, function(r, recording) {
7183
+                                                    if(recording.uID == uID) recording.Poster = Poster;
7184
+                                                });
7185
+                                            }
7186
+                                            return false;
7187
+                                        }
7188
+                                    });
7189
+                                    localDB.setItem(buddy + "-stream", JSON.stringify(currentStream));
7190
+                                    console.log("Capturing Video Poster, Done");
7191
+                                }
7192
+                            }
7193
+                        }, 'image/jpeg', PosterJpegQuality);
7194
+                    }, 1000);
7195
+                }
7196
+            }
7197
+        }
7198
+    }
7199
+}
7200
+
7201
+// Stream Manipulations
7202
+// ====================
7203
+function MixAudioStreams(MultiAudioTackStream){
7204
+    // Takes in a MediaStream with any number of audio tracks and mixes them together
7205
+
7206
+    var audioContext = null;
7207
+    try {
7208
+        window.AudioContext = window.AudioContext || window.webkitAudioContext;
7209
+        audioContext = new AudioContext();
7210
+    }
7211
+    catch(e){
7212
+        console.warn("AudioContext() not available, cannot record");
7213
+        return MultiAudioTackStream;
7214
+    }
7215
+    var mixedAudioStream = audioContext.createMediaStreamDestination();
7216
+    MultiAudioTackStream.getAudioTracks().forEach(function(audioTrack){
7217
+        var srcStream = new MediaStream();
7218
+        srcStream.addTrack(audioTrack);
7219
+        var streamSourceNode = audioContext.createMediaStreamSource(srcStream);
7220
+        streamSourceNode.connect(mixedAudioStream);
7221
+    });
7222
+
7223
+    return mixedAudioStream.stream;
7224
+}
7225
+
7226
+// Call Transfer & Conference
7227
+// ============================
7228
+function QuickFindBuddy(obj){
7229
+
7230
+    $.jeegoopopup.close();
7231
+
7232
+    var leftPos = obj.offsetWidth + 178;
7233
+    var topPos = obj.offsetHeight + 68;
7234
+
7235
+    if($(window).width() < 1467) {
7236
+        topPos = obj.offsetHeight + 164;
7237
+        if ($(window).width() < 918) {
7238
+            leftPos = obj.offsetWidth - 140;
7239
+            if($(window).width() < 690) {
7240
+               leftPos = obj.offsetWidth - 70;
7241
+               topPos = obj.offsetHeight + 164;
7242
+            }
7243
+        }
7244
+    }
7245
+
7246
+    var filter = obj.value;
7247
+    if(filter == "") return;
7248
+
7249
+    console.log("Find Buddy: ", filter);
7250
+
7251
+    Buddies.sort(function(a, b){
7252
+        if(a.CallerIDName < b.CallerIDName) return -1;
7253
+        if(a.CallerIDName > b.CallerIDName) return 1;
7254
+        return 0;
7255
+    });
7256
+
7257
+    var visibleItems = 0;
7258
+
7259
+    var menu = "<div id=\"quickSearchBuddy\">";
7260
+    menu += "<table id=\"quickSearchBdTable\" cellspacing=10 cellpadding=0 style=\"margin-left:auto; margin-right: auto\">";
7261
+
7262
+    for(var b = 0; b < Buddies.length; b++){
7263
+        var buddyObj = Buddies[b];
7264
+
7265
+        // Perform Filter Display
7266
+        var display = false;
7267
+        if(buddyObj.CallerIDName.toLowerCase().indexOf(filter.toLowerCase()) > -1) display = true;
7268
+        if(buddyObj.ExtNo.toLowerCase().indexOf(filter.toLowerCase()) > -1) display = true;
7269
+        if(buddyObj.Desc.toLowerCase().indexOf(filter.toLowerCase()) > -1) display = true;
7270
+        if(buddyObj.MobileNumber.toLowerCase().indexOf(filter.toLowerCase()) > -1) display = true;
7271
+        if(buddyObj.ContactNumber1.toLowerCase().indexOf(filter.toLowerCase()) > -1) display = true;
7272
+        if(buddyObj.ContactNumber2.toLowerCase().indexOf(filter.toLowerCase()) > -1) display = true;
7273
+        if(display) {
7274
+            // Filtered Results
7275
+            var iconColor = "#404040";
7276
+            if(buddyObj.presence == "Unknown" || buddyObj.presence == "Not online" || buddyObj.presence == "Unavailable") iconColor = "#666666";
7277
+            if(buddyObj.presence == "Ready") iconColor = "#3fbd3f";
7278
+            if(buddyObj.presence == "On the phone" || buddyObj.presence == "Ringing" || buddyObj.presence == "On hold") iconColor = "#c99606";
7279
+
7280
+            menu += "<tr class=\"quickFindBdTagRow\"><td></td><td><b>"+ buddyObj.CallerIDName +"</b></td><td></td></tr>";
7281
+
7282
+            if (buddyObj.ExtNo != "") {
7283
+                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>";
7284
+            }
7285
+            if (buddyObj.MobileNumber != "") {
7286
+                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>";
7287
+            }
7288
+
7289
+            if (buddyObj.ContactNumber1 != "") {
7290
+                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>";
7291
+            }
7292
+            if (buddyObj.ContactNumber2 != "") {
7293
+                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>";
7294
+            }
7295
+
7296
+            visibleItems++;
7297
+        }
7298
+        if(visibleItems >= 5) break;
7299
+    }
7300
+
7301
+    menu += "</table></div>";
7302
+
7303
+    if(menu.length > 1) {
7304
+       $.jeegoopopup.open({
7305
+                html: menu,
7306
+                width: 'auto',
7307
+                height: 'auto',
7308
+                left: leftPos,
7309
+                top: topPos,
7310
+                scrolling: 'no',
7311
+                skinClass: 'jg_popup_basic',
7312
+                overlay: true,
7313
+                opacity: 0,
7314
+                draggable: false,
7315
+                resizable: false,
7316
+                fadeIn: 0
7317
+       });
7318
+
7319
+       $("#jg_popup_inner").focus();
7320
+       $("#jg_popup_inner #jg_popup_content #quickSearchBuddy #quickSearchBdTable").on("click", ".quickFindBdRow", function() {
7321
+
7322
+          var quickFoundNum = $(this).closest("tr").find("span.quickNumFound").html();
7323
+
7324
+          $.jeegoopopup.close();
7325
+          $(document).find("input[id*='-txt-FindTransferBuddy']").focus();
7326
+          $(document).find("input[id*='-txt-FindTransferBuddy']").val(quickFoundNum);
7327
+       });
7328
+
7329
+       $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); });
7330
+       $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); } });
7331
+    }
7332
+}
7333
+
7334
+// Call Transfer
7335
+// =============
7336
+function StartTransferSession(lineNum){
7337
+    $("#line-"+ lineNum +"-btn-Transfer").hide();
7338
+    $("#line-"+ lineNum +"-btn-CancelTransfer").show();
7339
+
7340
+    holdSession(lineNum);
7341
+    $("#line-"+ lineNum +"-txt-FindTransferBuddy").val("");
7342
+    $("#line-"+ lineNum +"-txt-FindTransferBuddy").parent().show();
7343
+
7344
+    $("#line-"+ lineNum +"-btn-blind-transfer").show();
7345
+    $("#line-"+ lineNum +"-btn-attended-transfer").show();
7346
+    $("#line-"+ lineNum +"-btn-complete-transfer").hide();
7347
+    $("#line-"+ lineNum +"-btn-cancel-transfer").hide();
7348
+
7349
+    $("#line-"+ lineNum +"-transfer-status").hide();
7350
+
7351
+    $("#line-"+ lineNum +"-Transfer").show();
7352
+
7353
+    updateLineScroll(lineNum);
7354
+}
7355
+function CancelTransferSession(lineNum){
7356
+    var lineObj = FindLineByNumber(lineNum);
7357
+    if(lineObj == null || lineObj.SipSession == null){
7358
+        console.warn("Null line or session");
7359
+        return;
7360
+    }
7361
+    var session = lineObj.SipSession;
7362
+    if(session.data.childsession){
7363
+        console.log("Child Transfer call detected:", session.data.childsession.status)
7364
+        try{
7365
+            if(session.data.childsession.status == SIP.Session.C.STATUS_CONFIRMED){
7366
+                session.data.childsession.bye();
7367
+            } 
7368
+            else{
7369
+                session.data.childsession.cancel();
7370
+            }
7371
+        } catch(e){}
7372
+    }
7373
+
7374
+    $("#line-"+ lineNum +"-btn-Transfer").show();
7375
+    $("#line-"+ lineNum +"-btn-CancelTransfer").hide();
7376
+
7377
+    unholdSession(lineNum);
7378
+    $("#line-"+ lineNum +"-Transfer").hide();
7379
+
7380
+    updateLineScroll(lineNum);
7381
+}
7382
+function BlindTransfer(lineNum) {
7383
+    var dstNo = $("#line-"+ lineNum +"-txt-FindTransferBuddy").val().replace(/[^0-9\*\#\+]/g,'');
7384
+    if(dstNo == ""){
7385
+        console.warn("Cannot transfer, must be [0-9*+#]");
7386
+        return;
7387
+    }
7388
+
7389
+    var lineObj = FindLineByNumber(lineNum);
7390
+    if(lineObj == null || lineObj.SipSession == null){
7391
+        console.warn("Null line or session");
7392
+        return;
7393
+    }
7394
+    var session = lineObj.SipSession;
7395
+
7396
+    if(!session.data.transfer) session.data.transfer = [];
7397
+    session.data.transfer.push({ 
7398
+        type: "Blind", 
7399
+        to: dstNo, 
7400
+        transferTime: utcDateNow(), 
7401
+        disposition: "refer",
7402
+        dispositionTime: utcDateNow(), 
7403
+        accept : {
7404
+            complete: null,
7405
+            eventTime: null,
7406
+            disposition: ""
7407
+        }
7408
+    });
7409
+    var transferid = session.data.transfer.length-1;
7410
+
7411
+    var transferOptions  = { 
7412
+        receiveResponse: function doReceiveResponse(response){
7413
+            console.log("Blind transfer response: ", response.reason_phrase);
7414
+
7415
+            session.data.terminateby = "refer";
7416
+            session.data.transfer[transferid].accept.disposition = response.reason_phrase;
7417
+            session.data.transfer[transferid].accept.eventTime = utcDateNow();
7418
+
7419
+            $("#line-" + lineNum + "-msg").html("Call Blind Transfered (Accepted)");
7420
+
7421
+            updateLineScroll(lineNum);
7422
+        }
7423
+    }
7424
+    console.log("REFER: ", dstNo + "@" + wssServer);
7425
+    session.refer("sip:" + dstNo + "@" + wssServer, transferOptions);
7426
+    $("#line-" + lineNum + "-msg").html(lang.call_blind_transfered);
7427
+
7428
+    updateLineScroll(lineNum);
7429
+}
7430
+function AttendedTransfer(lineNum){
7431
+    var dstNo = $("#line-"+ lineNum +"-txt-FindTransferBuddy").val().replace(/[^0-9\*\#\+]/g,'');
7432
+    if(dstNo == ""){
7433
+        console.warn("Cannot transfer, must be [0-9*+#]");
7434
+        return;
7435
+    }
7436
+    
7437
+    var lineObj = FindLineByNumber(lineNum);
7438
+    if(lineObj == null || lineObj.SipSession == null){
7439
+        console.warn("Null line or session");
7440
+        return;
7441
+    }
7442
+    var session = lineObj.SipSession;
7443
+
7444
+    $.jeegoopopup.close();
7445
+
7446
+    $("#line-"+ lineNum +"-txt-FindTransferBuddy").parent().hide();
7447
+    $("#line-"+ lineNum +"-btn-blind-transfer").hide();
7448
+    $("#line-"+ lineNum +"-btn-attended-transfer").hide();
7449
+
7450
+    $("#line-"+ lineNum +"-btn-complete-attended-transfer").hide();
7451
+    $("#line-"+ lineNum +"-btn-cancel-attended-transfer").hide();
7452
+    $("#line-"+ lineNum +"-btn-terminate-attended-transfer").hide();
7453
+
7454
+    var newCallStatus = $("#line-"+ lineNum +"-transfer-status");
7455
+    newCallStatus.html(lang.connecting);
7456
+    newCallStatus.show();
7457
+
7458
+    if(!session.data.transfer) session.data.transfer = [];
7459
+    session.data.transfer.push({ 
7460
+        type: "Attended", 
7461
+        to: dstNo, 
7462
+        transferTime: utcDateNow(), 
7463
+        disposition: "invite",
7464
+        dispositionTime: utcDateNow(), 
7465
+        accept : {
7466
+            complete: null,
7467
+            eventTime: null,
7468
+            disposition: ""
7469
+        }
7470
+    });
7471
+    var transferid = session.data.transfer.length-1;
7472
+
7473
+    updateLineScroll(lineNum);
7474
+
7475
+    // SDP options
7476
+    var supportedConstraints = navigator.mediaDevices.getSupportedConstraints();
7477
+    var spdOptions = {
7478
+        sessionDescriptionHandlerOptions: {
7479
+            constraints: {
7480
+                audio: { deviceId : "default" },
7481
+                video: false
7482
+            }
7483
+        }
7484
+    }
7485
+    if(session.data.AudioSourceDevice != "default"){
7486
+        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.deviceId = { exact: session.data.AudioSourceDevice }
7487
+    }
7488
+    // Add additional Constraints
7489
+    if(supportedConstraints.autoGainControl) {
7490
+        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.autoGainControl = AutoGainControl;
7491
+    }
7492
+    if(supportedConstraints.echoCancellation) {
7493
+        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.echoCancellation = EchoCancellation;
7494
+    }
7495
+    if(supportedConstraints.noiseSuppression) {
7496
+        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.noiseSuppression = NoiseSuppression;
7497
+    }
7498
+
7499
+    if(session.data.withvideo){
7500
+        spdOptions.sessionDescriptionHandlerOptions.constraints.video = true;
7501
+        if(session.data.VideoSourceDevice != "default"){
7502
+            spdOptions.sessionDescriptionHandlerOptions.constraints.video.deviceId = { exact: session.data.VideoSourceDevice }
7503
+        }
7504
+        // Add additional Constraints
7505
+        if(supportedConstraints.frameRate && maxFrameRate != "") {
7506
+            spdOptions.sessionDescriptionHandlerOptions.constraints.video.frameRate = maxFrameRate;
7507
+        }
7508
+        if(supportedConstraints.height && videoHeight != "") {
7509
+            spdOptions.sessionDescriptionHandlerOptions.constraints.video.height = videoHeight;
7510
+        }
7511
+        if(supportedConstraints.aspectRatio && videoAspectRatio != "") {
7512
+            spdOptions.sessionDescriptionHandlerOptions.constraints.video.aspectRatio = videoAspectRatio;
7513
+        }
7514
+    }
7515
+
7516
+    // Create new call session
7517
+    console.log("INVITE: ", "sip:" + dstNo + "@" + wssServer);
7518
+    var newSession = userAgent.invite("sip:" + dstNo + "@" + wssServer, spdOptions);
7519
+    session.data.childsession = newSession;
7520
+    newSession.on('progress', function (response) {
7521
+        newCallStatus.html(lang.ringing);
7522
+        session.data.transfer[transferid].disposition = "progress";
7523
+        session.data.transfer[transferid].dispositionTime = utcDateNow();
7524
+
7525
+        $("#line-" + lineNum + "-msg").html(lang.attended_transfer_call_started);
7526
+        
7527
+        var CancelAttendedTransferBtn = $("#line-"+ lineNum +"-btn-cancel-attended-transfer");
7528
+        CancelAttendedTransferBtn.off('click');
7529
+        CancelAttendedTransferBtn.on('click', function(){
7530
+            newSession.cancel();
7531
+            newCallStatus.html(lang.call_cancelled);
7532
+            console.log("New call session canceled");
7533
+
7534
+            session.data.transfer[transferid].accept.complete = false;
7535
+            session.data.transfer[transferid].accept.disposition = "cancel";
7536
+            session.data.transfer[transferid].accept.eventTime = utcDateNow();
7537
+
7538
+            $("#line-" + lineNum + "-msg").html(lang.attended_transfer_call_cancelled);
7539
+
7540
+            updateLineScroll(lineNum);
7541
+        });
7542
+        CancelAttendedTransferBtn.show();
7543
+
7544
+        updateLineScroll(lineNum);
7545
+    });
7546
+    newSession.on('accepted', function (response) {
7547
+        newCallStatus.html(lang.call_in_progress);
7548
+        $("#line-"+ lineNum +"-btn-cancel-attended-transfer").hide();
7549
+        session.data.transfer[transferid].disposition = "accepted";
7550
+        session.data.transfer[transferid].dispositionTime = utcDateNow();
7551
+
7552
+        var CompleteTransferBtn = $("#line-"+ lineNum +"-btn-complete-attended-transfer");
7553
+        CompleteTransferBtn.off('click');
7554
+        CompleteTransferBtn.on('click', function(){
7555
+            var transferOptions  = { 
7556
+                receiveResponse: function doReceiveResponse(response){
7557
+                    console.log("Attended transfer response: ", response.reason_phrase);
7558
+
7559
+                    session.data.terminateby = "refer";
7560
+                    session.data.transfer[transferid].accept.disposition = response.reason_phrase;
7561
+                    session.data.transfer[transferid].accept.eventTime = utcDateNow();
7562
+
7563
+                    $("#line-" + lineNum + "-msg").html(lang.attended_transfer_complete_accepted);
7564
+
7565
+                    updateLineScroll(lineNum);
7566
+                }
7567
+            }
7568
+
7569
+            // Send REFER
7570
+            session.refer(newSession, transferOptions);
7571
+
7572
+            newCallStatus.html(lang.attended_transfer_complete);
7573
+            console.log("Attended transfer complete");
7574
+            // Call will now teardown...
7575
+
7576
+            session.data.transfer[transferid].accept.complete = true;
7577
+            session.data.transfer[transferid].accept.disposition = "refer";
7578
+            session.data.transfer[transferid].accept.eventTime = utcDateNow();
7579
+
7580
+            $("#line-" + lineNum + "-msg").html(lang.attended_transfer_complete);
7581
+
7582
+            updateLineScroll(lineNum);
7583
+        });
7584
+        CompleteTransferBtn.show();
7585
+
7586
+        updateLineScroll(lineNum);
7587
+
7588
+        var TerminateAttendedTransferBtn = $("#line-"+ lineNum +"-btn-terminate-attended-transfer");
7589
+        TerminateAttendedTransferBtn.off('click');
7590
+        TerminateAttendedTransferBtn.on('click', function(){
7591
+            newSession.bye();
7592
+            newCallStatus.html(lang.call_ended);
7593
+            console.log("New call session end");
7594
+
7595
+            session.data.transfer[transferid].accept.complete = false;
7596
+            session.data.transfer[transferid].accept.disposition = "bye";
7597
+            session.data.transfer[transferid].accept.eventTime = utcDateNow();
7598
+
7599
+            $("#line-" + lineNum + "-msg").html(lang.attended_transfer_call_ended);
7600
+
7601
+            updateLineScroll(lineNum);
7602
+        });
7603
+        TerminateAttendedTransferBtn.show();
7604
+
7605
+        updateLineScroll(lineNum);
7606
+    });
7607
+    newSession.on('trackAdded', function () {
7608
+        var pc = newSession.sessionDescriptionHandler.peerConnection;
7609
+
7610
+        // Gets Remote Audio Track (Local audio is setup via initial GUM)
7611
+        var remoteStream = new MediaStream();
7612
+        pc.getReceivers().forEach(function (receiver) {
7613
+            if(receiver.track && receiver.track.kind == "audio"){
7614
+                remoteStream.addTrack(receiver.track);
7615
+            }
7616
+        });
7617
+        var remoteAudio = $("#line-" + lineNum + "-transfer-remoteAudio").get(0);
7618
+        remoteAudio.srcObject = remoteStream;
7619
+        remoteAudio.onloadedmetadata = function(e) {
7620
+            if (typeof remoteAudio.sinkId !== 'undefined') {
7621
+                remoteAudio.setSinkId(session.data.AudioOutputDevice).then(function(){
7622
+                    console.log("sinkId applied: "+ session.data.AudioOutputDevice);
7623
+                }).catch(function(e){
7624
+                    console.warn("Error using setSinkId: ", e);
7625
+                });            
7626
+            }
7627
+            remoteAudio.play();
7628
+        }
7629
+    });
7630
+    newSession.on('rejected', function (response, cause) {
7631
+        console.log("New call session rejected: ", cause);
7632
+        newCallStatus.html(lang.call_rejected);
7633
+        session.data.transfer[transferid].disposition = "rejected";
7634
+        session.data.transfer[transferid].dispositionTime = utcDateNow();
7635
+
7636
+        $("#line-"+ lineNum +"-txt-FindTransferBuddy").parent().show();
7637
+        $("#line-"+ lineNum +"-btn-blind-transfer").show();
7638
+        $("#line-"+ lineNum +"-btn-attended-transfer").show();
7639
+
7640
+        $("#line-"+ lineNum +"-btn-complete-attended-transfer").hide();
7641
+        $("#line-"+ lineNum +"-btn-cancel-attended-transfer").hide();
7642
+        $("#line-"+ lineNum +"-btn-terminate-attended-transfer").hide();
7643
+
7644
+        $("#line-"+ lineNum +"-msg").html(lang.attended_transfer_call_rejected);
7645
+
7646
+        updateLineScroll(lineNum);
7647
+
7648
+        window.setTimeout(function(){
7649
+            newCallStatus.hide();
7650
+            updateLineScroll(lineNum);
7651
+        }, 1000);
7652
+    });
7653
+    newSession.on('terminated', function (response, cause) {
7654
+        console.log("New call session terminated: ", cause);
7655
+        newCallStatus.html(lang.call_ended);
7656
+        session.data.transfer[transferid].disposition = "terminated";
7657
+        session.data.transfer[transferid].dispositionTime = utcDateNow();
7658
+
7659
+        $("#line-"+ lineNum +"-txt-FindTransferBuddy").parent().show();
7660
+        $("#line-"+ lineNum +"-btn-blind-transfer").show();
7661
+        $("#line-"+ lineNum +"-btn-attended-transfer").show();
7662
+
7663
+        $("#line-"+ lineNum +"-btn-complete-attended-transfer").hide();
7664
+        $("#line-"+ lineNum +"-btn-cancel-attended-transfer").hide();
7665
+        $("#line-"+ lineNum +"-btn-terminate-attended-transfer").hide();
7666
+
7667
+        $("#line-"+ lineNum +"-msg").html(lang.attended_transfer_call_terminated);
7668
+
7669
+        updateLineScroll(lineNum);
7670
+
7671
+        window.setTimeout(function(){
7672
+            newCallStatus.hide();
7673
+            updateLineScroll(lineNum);
7674
+        }, 1000);
7675
+    });
7676
+}
7677
+
7678
+// Conference Calls
7679
+// ================
7680
+function StartConferenceCall(lineNum){
7681
+    $("#line-"+ lineNum +"-btn-Conference").hide();
7682
+    $("#line-"+ lineNum +"-btn-CancelConference").show();
7683
+
7684
+    holdSession(lineNum);
7685
+    $("#line-"+ lineNum +"-txt-FindConferenceBuddy").val("");
7686
+    $("#line-"+ lineNum +"-txt-FindConferenceBuddy").parent().show();
7687
+
7688
+    $("#line-"+ lineNum +"-btn-conference-dial").show();
7689
+    $("#line-"+ lineNum +"-btn-cancel-conference-dial").hide();
7690
+    $("#line-"+ lineNum +"-btn-join-conference-call").hide();
7691
+    $("#line-"+ lineNum +"-btn-terminate-conference-call").hide();
7692
+
7693
+    $("#line-"+ lineNum +"-conference-status").hide();
7694
+
7695
+    $("#line-"+ lineNum +"-Conference").show();
7696
+
7697
+    updateLineScroll(lineNum);
7698
+}
7699
+function CancelConference(lineNum){
7700
+    var lineObj = FindLineByNumber(lineNum);
7701
+    if(lineObj == null || lineObj.SipSession == null){
7702
+        console.warn("Null line or session");
7703
+        return;
7704
+    }
7705
+    var session = lineObj.SipSession;
7706
+    if(session.data.childsession){
7707
+        try{
7708
+            if(session.data.childsession.status == SIP.Session.C.STATUS_CONFIRMED){
7709
+                session.data.childsession.bye();
7710
+            } 
7711
+            else{
7712
+                session.data.childsession.cancel();
7713
+            }
7714
+        } catch(e){}
7715
+    }
7716
+
7717
+    $("#line-"+ lineNum +"-btn-Conference").show();
7718
+    $("#line-"+ lineNum +"-btn-CancelConference").hide();
7719
+
7720
+    unholdSession(lineNum);
7721
+    $("#line-"+ lineNum +"-Conference").hide();
7722
+
7723
+    updateLineScroll(lineNum);
7724
+}
7725
+function ConferenceDial(lineNum){
7726
+    var dstNo = $("#line-"+ lineNum +"-txt-FindConferenceBuddy").val().replace(/[^0-9\*\#\+]/g,'');
7727
+    if(dstNo == ""){
7728
+        console.warn("Cannot transfer, must be [0-9*+#]");
7729
+        return;
7730
+    }
7731
+    
7732
+    var lineObj = FindLineByNumber(lineNum);
7733
+    if(lineObj == null || lineObj.SipSession == null){
7734
+        console.warn("Null line or session");
7735
+        return;
7736
+    }
7737
+    var session = lineObj.SipSession;
7738
+
7739
+    $.jeegoopopup.close();
7740
+
7741
+    $("#line-"+ lineNum +"-txt-FindConferenceBuddy").parent().hide();
7742
+
7743
+    $("#line-"+ lineNum +"-btn-conference-dial").hide();
7744
+    $("#line-"+ lineNum +"-btn-cancel-conference-dial")
7745
+    $("#line-"+ lineNum +"-btn-join-conference-call").hide();
7746
+    $("#line-"+ lineNum +"-btn-terminate-conference-call").hide();
7747
+
7748
+    var newCallStatus = $("#line-"+ lineNum +"-conference-status");
7749
+    newCallStatus.html(lang.connecting);
7750
+    newCallStatus.show();
7751
+
7752
+    if(!session.data.confcalls) session.data.confcalls = [];
7753
+    session.data.confcalls.push({ 
7754
+        to: dstNo, 
7755
+        startTime: utcDateNow(), 
7756
+        disposition: "invite",
7757
+        dispositionTime: utcDateNow(), 
7758
+        accept : {
7759
+            complete: null,
7760
+            eventTime: null,
7761
+            disposition: ""
7762
+        }
7763
+    });
7764
+    var confcallid = session.data.confcalls.length-1;
7765
+
7766
+    updateLineScroll(lineNum);
7767
+
7768
+    // SDP options
7769
+    var supportedConstraints = navigator.mediaDevices.getSupportedConstraints();
7770
+    var spdOptions = {
7771
+        sessionDescriptionHandlerOptions: {
7772
+            constraints: {
7773
+                audio: { deviceId : "default" },
7774
+                video: false
7775
+            }
7776
+        }
7777
+    }
7778
+    if(session.data.AudioSourceDevice != "default"){
7779
+        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.deviceId = { exact: session.data.AudioSourceDevice }
7780
+    }
7781
+    // Add additional Constraints
7782
+    if(supportedConstraints.autoGainControl) {
7783
+        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.autoGainControl = AutoGainControl;
7784
+    }
7785
+    if(supportedConstraints.echoCancellation) {
7786
+        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.echoCancellation = EchoCancellation;
7787
+    }
7788
+    if(supportedConstraints.noiseSuppression) {
7789
+        spdOptions.sessionDescriptionHandlerOptions.constraints.audio.noiseSuppression = NoiseSuppression;
7790
+    }
7791
+
7792
+    // Unlikely this will work
7793
+    if(session.data.withvideo){
7794
+        spdOptions.sessionDescriptionHandlerOptions.constraints.video = true;
7795
+        if(session.data.VideoSourceDevice != "default"){
7796
+            spdOptions.sessionDescriptionHandlerOptions.constraints.video.deviceId = { exact: session.data.VideoSourceDevice }
7797
+        }
7798
+        // Add additional Constraints
7799
+        if(supportedConstraints.frameRate && maxFrameRate != "") {
7800
+            spdOptions.sessionDescriptionHandlerOptions.constraints.video.frameRate = maxFrameRate;
7801
+        }
7802
+        if(supportedConstraints.height && videoHeight != "") {
7803
+            spdOptions.sessionDescriptionHandlerOptions.constraints.video.height = videoHeight;
7804
+        }
7805
+        if(supportedConstraints.aspectRatio && videoAspectRatio != "") {
7806
+            spdOptions.sessionDescriptionHandlerOptions.constraints.video.aspectRatio = videoAspectRatio;
7807
+        }
7808
+    }
7809
+
7810
+    // Create new call session
7811
+    console.log("INVITE: ", "sip:" + dstNo + "@" + wssServer);
7812
+    var newSession = userAgent.invite("sip:" + dstNo + "@" + wssServer, spdOptions);
7813
+    session.data.childsession = newSession;
7814
+    newSession.on('progress', function (response) {
7815
+        newCallStatus.html(lang.ringing);
7816
+        session.data.confcalls[confcallid].disposition = "progress";
7817
+        session.data.confcalls[confcallid].dispositionTime = utcDateNow();
7818
+
7819
+        $("#line-" + lineNum + "-msg").html(lang.conference_call_started);
7820
+
7821
+        var CancelConferenceDialBtn = $("#line-"+ lineNum +"-btn-cancel-conference-dial");
7822
+        CancelConferenceDialBtn.off('click');
7823
+        CancelConferenceDialBtn.on('click', function(){
7824
+            newSession.cancel();
7825
+            newCallStatus.html(lang.call_cancelled);
7826
+            console.log("New call session canceled");
7827
+
7828
+            session.data.confcalls[confcallid].accept.complete = false;
7829
+            session.data.confcalls[confcallid].accept.disposition = "cancel";
7830
+            session.data.confcalls[confcallid].accept.eventTime = utcDateNow();
7831
+
7832
+            $("#line-" + lineNum + "-msg").html(lang.canference_call_cancelled);
7833
+
7834
+            updateLineScroll(lineNum);
7835
+        });
7836
+        CancelConferenceDialBtn.show();
7837
+
7838
+        updateLineScroll(lineNum);
7839
+    });
7840
+    newSession.on('accepted', function (response) {
7841
+        newCallStatus.html(lang.call_in_progress);
7842
+        $("#line-"+ lineNum +"-btn-cancel-conference-dial").hide();
7843
+        session.data.confcalls[confcallid].complete = true;
7844
+        session.data.confcalls[confcallid].disposition = "accepted";
7845
+        session.data.confcalls[confcallid].dispositionTime = utcDateNow();
7846
+
7847
+        // Join Call
7848
+        var JoinCallBtn = $("#line-"+ lineNum +"-btn-join-conference-call");
7849
+        JoinCallBtn.off('click');
7850
+        JoinCallBtn.on('click', function(){
7851
+            // Merge Call Audio
7852
+            if(!session.data.childsession){
7853
+                console.warn("Conference session lost");
7854
+                return;
7855
+            }
7856
+
7857
+            var outputStreamForSession = new MediaStream();
7858
+            var outputStreamForConfSession = new MediaStream();
7859
+
7860
+            var pc = session.sessionDescriptionHandler.peerConnection;
7861
+            var confPc = session.data.childsession.sessionDescriptionHandler.peerConnection;
7862
+
7863
+            // Get conf call input channel
7864
+            confPc.getReceivers().forEach(function (RTCRtpReceiver) {
7865
+                if(RTCRtpReceiver.track && RTCRtpReceiver.track.kind == "audio") {
7866
+                    console.log("Adding conference session:", RTCRtpReceiver.track.label);
7867
+                    outputStreamForSession.addTrack(RTCRtpReceiver.track);
7868
+                }
7869
+            });
7870
+
7871
+            // Get session input channel
7872
+            pc.getReceivers().forEach(function (RTCRtpReceiver) {
7873
+                if(RTCRtpReceiver.track && RTCRtpReceiver.track.kind == "audio") {
7874
+                    console.log("Adding conference session:", RTCRtpReceiver.track.label);
7875
+                    outputStreamForConfSession.addTrack(RTCRtpReceiver.track);
7876
+                }
7877
+            });
7878
+
7879
+            // Replace tracks of Parent Call
7880
+            pc.getSenders().forEach(function (RTCRtpSender) {
7881
+                if(RTCRtpSender.track && RTCRtpSender.track.kind == "audio") {
7882
+                    console.log("Switching to mixed Audio track on session");
7883
+
7884
+                    session.data.AudioSourceTrack = RTCRtpSender.track;
7885
+                    outputStreamForSession.addTrack(RTCRtpSender.track);
7886
+                    var mixedAudioTrack = MixAudioStreams(outputStreamForSession).getAudioTracks()[0];
7887
+                    mixedAudioTrack.IsMixedTrack = true;
7888
+
7889
+                    RTCRtpSender.replaceTrack(mixedAudioTrack);
7890
+                }
7891
+            });
7892
+            // Replace tracks of Child Call
7893
+            confPc.getSenders().forEach(function (RTCRtpSender) {
7894
+                if(RTCRtpSender.track && RTCRtpSender.track.kind == "audio") {
7895
+                    console.log("Switching to mixed Audio track on conf call");
7896
+
7897
+                    session.data.childsession.data.AudioSourceTrack = RTCRtpSender.track;
7898
+                    outputStreamForConfSession.addTrack(RTCRtpSender.track);
7899
+                    var mixedAudioTrackForConf = MixAudioStreams(outputStreamForConfSession).getAudioTracks()[0];
7900
+                    mixedAudioTrackForConf.IsMixedTrack = true;
7901
+
7902
+                    RTCRtpSender.replaceTrack(mixedAudioTrackForConf);
7903
+                }
7904
+            });
7905
+
7906
+            newCallStatus.html(lang.call_in_progress);
7907
+            console.log("Conference Call In Progress");
7908
+
7909
+            session.data.confcalls[confcallid].accept.complete = true;
7910
+            session.data.confcalls[confcallid].accept.disposition = "join";
7911
+            session.data.confcalls[confcallid].accept.eventTime = utcDateNow();
7912
+
7913
+            $("#line-"+ lineNum +"-btn-terminate-conference-call").show();
7914
+
7915
+            $("#line-" + lineNum + "-msg").html(lang.conference_call_in_progress);
7916
+
7917
+            // Take the parent call off hold
7918
+            unholdSession(lineNum);
7919
+
7920
+            JoinCallBtn.hide();
7921
+
7922
+            updateLineScroll(lineNum);
7923
+        });
7924
+        JoinCallBtn.show();
7925
+
7926
+        updateLineScroll(lineNum);
7927
+
7928
+        // End Call
7929
+        var TerminateAttendedTransferBtn = $("#line-"+ lineNum +"-btn-terminate-conference-call");
7930
+        TerminateAttendedTransferBtn.off('click');
7931
+        TerminateAttendedTransferBtn.on('click', function(){
7932
+            newSession.bye();
7933
+            newCallStatus.html(lang.call_ended);
7934
+            console.log("New call session end");
7935
+
7936
+            session.data.confcalls[confcallid].accept.disposition = "bye";
7937
+            session.data.confcalls[confcallid].accept.eventTime = utcDateNow();
7938
+
7939
+            $("#line-" + lineNum + "-msg").html(lang.conference_call_ended);
7940
+
7941
+            updateLineScroll(lineNum);
7942
+        });
7943
+        TerminateAttendedTransferBtn.show();
7944
+
7945
+        updateLineScroll(lineNum);
7946
+    });
7947
+    newSession.on('trackAdded', function () {
7948
+
7949
+        var pc = newSession.sessionDescriptionHandler.peerConnection;
7950
+
7951
+        // Gets Remote Audio Track (Local audio is setup via initial GUM)
7952
+        var remoteStream = new MediaStream();
7953
+        pc.getReceivers().forEach(function (receiver) {
7954
+            if(receiver.track && receiver.track.kind == "audio"){
7955
+                remoteStream.addTrack(receiver.track);
7956
+            }
7957
+        });
7958
+        var remoteAudio = $("#line-" + lineNum + "-conference-remoteAudio").get(0);
7959
+        remoteAudio.srcObject = remoteStream;
7960
+        remoteAudio.onloadedmetadata = function(e) {
7961
+            if (typeof remoteAudio.sinkId !== 'undefined') {
7962
+                remoteAudio.setSinkId(session.data.AudioOutputDevice).then(function(){
7963
+                    console.log("sinkId applied: "+ session.data.AudioOutputDevice);
7964
+                }).catch(function(e){
7965
+                    console.warn("Error using setSinkId: ", e);
7966
+                });
7967
+            }
7968
+            remoteAudio.play();
7969
+        }
7970
+    });
7971
+    newSession.on('rejected', function (response, cause) {
7972
+        console.log("New call session rejected: ", cause);
7973
+        newCallStatus.html(lang.call_rejected);
7974
+        session.data.confcalls[confcallid].disposition = "rejected";
7975
+        session.data.confcalls[confcallid].dispositionTime = utcDateNow();
7976
+
7977
+        $("#line-"+ lineNum +"-txt-FindConferenceBuddy").parent().show();
7978
+        $("#line-"+ lineNum +"-btn-conference-dial").show();
7979
+
7980
+        $("#line-"+ lineNum +"-btn-cancel-conference-dial").hide();
7981
+        $("#line-"+ lineNum +"-btn-join-conference-call").hide();
7982
+        $("#line-"+ lineNum +"-btn-terminate-conference-call").hide();
7983
+
7984
+        $("#line-"+ lineNum +"-msg").html(lang.conference_call_rejected);
7985
+
7986
+        updateLineScroll(lineNum);
7987
+
7988
+        window.setTimeout(function(){
7989
+            newCallStatus.hide();
7990
+            updateLineScroll(lineNum);
7991
+        }, 1000);
7992
+    });
7993
+    newSession.on('terminated', function (response, cause) {
7994
+        console.log("New call session terminated: ", cause);
7995
+        newCallStatus.html(lang.call_ended);
7996
+        session.data.confcalls[confcallid].disposition = "terminated";
7997
+        session.data.confcalls[confcallid].dispositionTime = utcDateNow();
7998
+
7999
+        // Ends the mixed audio, and releases the mic
8000
+        if(session.data.childsession.data.AudioSourceTrack && session.data.childsession.data.AudioSourceTrack.kind == "audio"){
8001
+            session.data.childsession.data.AudioSourceTrack.stop();
8002
+        }
8003
+        // Restore Audio Stream if it was changed
8004
+        if(session.data.AudioSourceTrack && session.data.AudioSourceTrack.kind == "audio"){
8005
+            var pc = session.sessionDescriptionHandler.peerConnection;
8006
+            pc.getSenders().forEach(function (RTCRtpSender) {
8007
+                if(RTCRtpSender.track && RTCRtpSender.track.kind == "audio") {
8008
+                    RTCRtpSender.replaceTrack(session.data.AudioSourceTrack).then(function(){
8009
+                        if(session.data.ismute){
8010
+                            RTCRtpSender.track.enabled = false;
8011
+                        }
8012
+                    }).catch(function(){
8013
+                        console.error(e);
8014
+                    });
8015
+                    session.data.AudioSourceTrack = null;
8016
+                }
8017
+            });
8018
+        }
8019
+        $("#line-"+ lineNum +"-txt-FindConferenceBuddy").parent().show();
8020
+        $("#line-"+ lineNum +"-btn-conference-dial").show();
8021
+
8022
+        $("#line-"+ lineNum +"-btn-cancel-conference-dial").hide();
8023
+        $("#line-"+ lineNum +"-btn-join-conference-call").hide();
8024
+        $("#line-"+ lineNum +"-btn-terminate-conference-call").hide();
8025
+
8026
+        $("#line-"+ lineNum +"-msg").html(lang.conference_call_terminated);
8027
+
8028
+        updateLineScroll(lineNum);
8029
+
8030
+        window.setTimeout(function(){
8031
+            newCallStatus.hide();
8032
+            updateLineScroll(lineNum);
8033
+        }, 1000);
8034
+    });
8035
+}
8036
+
8037
+
8038
+function cancelSession(lineNum) {
8039
+    var lineObj = FindLineByNumber(lineNum);
8040
+    if(lineObj == null || lineObj.SipSession == null) return;
8041
+
8042
+    lineObj.SipSession.data.terminateby = "us";
8043
+
8044
+    console.log("Cancelling session : "+ lineNum);
8045
+    lineObj.SipSession.cancel();
8046
+
8047
+    $("#line-" + lineNum + "-msg").html(lang.call_cancelled);
8048
+}
8049
+function holdSession(lineNum) {
8050
+    var lineObj = FindLineByNumber(lineNum);
8051
+    if(lineObj == null || lineObj.SipSession == null) return;
8052
+
8053
+    console.log("Putting Call on hold: "+ lineNum);
8054
+    if(lineObj.SipSession.local_hold == false){
8055
+        lineObj.SipSession.hold();
8056
+    }
8057
+    // Log Hold
8058
+    if(!lineObj.SipSession.data.hold) lineObj.SipSession.data.hold = [];
8059
+    lineObj.SipSession.data.hold.push({ event: "hold", eventTime: utcDateNow() });
8060
+
8061
+    $("#line-" + lineNum + "-btn-Hold").hide();
8062
+    $("#line-" + lineNum + "-btn-Unhold").show();
8063
+    $("#line-" + lineNum + "-msg").html(lang.call_on_hold);
8064
+
8065
+    updateLineScroll(lineNum);
8066
+}
8067
+function unholdSession(lineNum) {
8068
+    var lineObj = FindLineByNumber(lineNum);
8069
+    if(lineObj == null || lineObj.SipSession == null) return;
8070
+
8071
+    console.log("Taking call off hold: "+ lineNum);
8072
+    if(lineObj.SipSession.local_hold == true){
8073
+        lineObj.SipSession.unhold();
8074
+    }
8075
+    // Log Hold
8076
+    if(!lineObj.SipSession.data.hold) lineObj.SipSession.data.hold = [];
8077
+    lineObj.SipSession.data.hold.push({ event: "unhold", eventTime: utcDateNow() });
8078
+
8079
+    $("#line-" + lineNum + "-msg").html(lang.call_in_progress);
8080
+    $("#line-" + lineNum + "-btn-Hold").show();
8081
+    $("#line-" + lineNum + "-btn-Unhold").hide();
8082
+
8083
+    updateLineScroll(lineNum);
8084
+}
8085
+function endSession(lineNum) {
8086
+    var lineObj = FindLineByNumber(lineNum);
8087
+    if(lineObj == null || lineObj.SipSession == null) return;
8088
+
8089
+    console.log("Ending call with: "+ lineNum);
8090
+    lineObj.SipSession.data.terminateby = "us";
8091
+    lineObj.SipSession.bye();
8092
+
8093
+    $("#line-" + lineNum + "-msg").html(lang.call_ended);
8094
+    $("#line-" + lineNum + "-ActiveCall").hide();
8095
+
8096
+    updateLineScroll(lineNum);
8097
+}
8098
+function sendDTMF(lineNum, itemStr) {
8099
+    var lineObj = FindLineByNumber(lineNum);
8100
+    if(lineObj == null || lineObj.SipSession == null) return;
8101
+
8102
+    console.log("Sending DTMF ("+ itemStr +"): "+ lineNum);
8103
+    lineObj.SipSession.dtmf(itemStr);
8104
+
8105
+    $("#line-" + lineNum + "-msg").html(lang.send_dtmf + ": "+ itemStr);
8106
+
8107
+    updateLineScroll(lineNum);
8108
+
8109
+    // Custom Web hook
8110
+    if(typeof web_hook_on_dtmf !== 'undefined') web_hook_on_dtmf(itemStr, lineObj.SipSession);
8111
+}
8112
+function switchVideoSource(lineNum, srcId){
8113
+    var lineObj = FindLineByNumber(lineNum);
8114
+    if(lineObj == null || lineObj.SipSession == null){
8115
+        console.warn("Line or Session is Null");
8116
+        return;
8117
+    }
8118
+    var session = lineObj.SipSession;
8119
+
8120
+    $("#line-" + lineNum + "-msg").html(lang.switching_video_source);
8121
+
8122
+    var supportedConstraints = navigator.mediaDevices.getSupportedConstraints();
8123
+    var constraints = { 
8124
+        audio: false, 
8125
+        video: { deviceId: "default" }
8126
+    }
8127
+    if(srcId != "default"){
8128
+        constraints.video.deviceId = { exact: srcId }
8129
+    }
8130
+
8131
+    // Add additional Constraints
8132
+    if(supportedConstraints.frameRate && maxFrameRate != "") {
8133
+        constraints.video.frameRate = maxFrameRate;
8134
+    }
8135
+    if(supportedConstraints.height && videoHeight != "") {
8136
+        constraints.video.height = videoHeight;
8137
+    }
8138
+    if(supportedConstraints.aspectRatio && videoAspectRatio != "") {
8139
+        constraints.video.aspectRatio = videoAspectRatio;
8140
+    }
8141
+
8142
+    session.data.VideoSourceDevice = srcId;
8143
+
8144
+    var pc = session.sessionDescriptionHandler.peerConnection;
8145
+
8146
+    var localStream = new MediaStream();
8147
+    navigator.mediaDevices.getUserMedia(constraints).then(function(newStream){
8148
+        var newMediaTrack = newStream.getVideoTracks()[0];
8149
+        pc.getSenders().forEach(function (RTCRtpSender) {
8150
+            if(RTCRtpSender.track && RTCRtpSender.track.kind == "video") {
8151
+                console.log("Switching Video Track : "+ RTCRtpSender.track.label + " to "+ newMediaTrack.label);
8152
+                RTCRtpSender.track.stop();
8153
+                RTCRtpSender.replaceTrack(newMediaTrack);
8154
+                localStream.addTrack(newMediaTrack);
8155
+            }
8156
+        });
8157
+    }).catch(function(e){
8158
+        console.error("Error on getUserMedia", e, constraints);
8159
+    });
8160
+
8161
+    // Restore Audio Stream is it was changed
8162
+    if(session.data.AudioSourceTrack && session.data.AudioSourceTrack.kind == "audio"){
8163
+        pc.getSenders().forEach(function (RTCRtpSender) {
8164
+            if(RTCRtpSender.track && RTCRtpSender.track.kind == "audio") {
8165
+                RTCRtpSender.replaceTrack(session.data.AudioSourceTrack).then(function(){
8166
+                    if(session.data.ismute){
8167
+                        RTCRtpSender.track.enabled = false;
8168
+                    }
8169
+                }).catch(function(){
8170
+                    console.error(e);
8171
+                });
8172
+                session.data.AudioSourceTrack = null;
8173
+            }
8174
+        });
8175
+    }
8176
+
8177
+    // Set Preview
8178
+    console.log("Showing as preview...");
8179
+    var localVideo = $("#line-" + lineNum + "-localVideo").get(0);
8180
+    localVideo.srcObject = localStream;
8181
+    localVideo.onloadedmetadata = function(e) {
8182
+        localVideo.play();
8183
+    }
8184
+}
8185
+function SendCanvas(lineNum){
8186
+    var lineObj = FindLineByNumber(lineNum);
8187
+    if(lineObj == null || lineObj.SipSession == null){
8188
+        console.warn("Line or Session is Null");
8189
+        return;
8190
+    }
8191
+    var session = lineObj.SipSession;
8192
+
8193
+    $("#line-" + lineNum + "-msg").html(lang.switching_to_canvas);
8194
+
8195
+    // Create scratch Pad
8196
+    RemoveScratchpad(lineNum);
8197
+
8198
+    var newCanvas = $('<canvas/>');
8199
+    newCanvas.prop("id", "line-" + lineNum + "-scratchpad");
8200
+    $("#line-" + lineNum + "-scratchpad-container").append(newCanvas);
8201
+    $("#line-" + lineNum + "-scratchpad").css("display", "inline-block");
8202
+    $("#line-" + lineNum + "-scratchpad").css("width", "640px"); // SD
8203
+    $("#line-" + lineNum + "-scratchpad").css("height", "360px"); // SD
8204
+    $("#line-" + lineNum + "-scratchpad").prop("width", 640); // SD
8205
+    $("#line-" + lineNum + "-scratchpad").prop("height", 360); // SD
8206
+    $("#line-" + lineNum + "-scratchpad-container").show();
8207
+
8208
+    console.log("Canvas for Scratchpad created...");
8209
+
8210
+    scratchpad = new fabric.Canvas("line-" + lineNum + "-scratchpad");
8211
+    scratchpad.id = "line-" + lineNum + "-scratchpad";
8212
+    scratchpad.backgroundColor = "#FFFFFF";
8213
+    scratchpad.isDrawingMode = true;
8214
+    scratchpad.renderAll();
8215
+    scratchpad.redrawIntrtval = window.setInterval(function(){
8216
+        scratchpad.renderAll();
8217
+    }, 1000);
8218
+
8219
+    CanvasCollection.push(scratchpad);
8220
+
8221
+    // Get The Canvas Stream
8222
+    var canvasMediaStream = $("#line-"+ lineNum +"-scratchpad").get(0).captureStream(25);
8223
+    var canvasMediaTrack = canvasMediaStream.getVideoTracks()[0];
8224
+
8225
+    // Switch Tracks
8226
+    var pc = session.sessionDescriptionHandler.peerConnection;
8227
+    pc.getSenders().forEach(function (RTCRtpSender) {
8228
+        if(RTCRtpSender.track && RTCRtpSender.track.kind == "video") {
8229
+            console.log("Switching Track : "+ RTCRtpSender.track.label + " to Scratchpad Canvas");
8230
+            RTCRtpSender.track.stop();
8231
+            RTCRtpSender.replaceTrack(canvasMediaTrack);
8232
+        }
8233
+    });
8234
+
8235
+    // Restore Audio Stream if it was changed
8236
+    if(session.data.AudioSourceTrack && session.data.AudioSourceTrack.kind == "audio"){
8237
+        pc.getSenders().forEach(function (RTCRtpSender) {
8238
+            if(RTCRtpSender.track && RTCRtpSender.track.kind == "audio") {
8239
+                RTCRtpSender.replaceTrack(session.data.AudioSourceTrack).then(function(){
8240
+                    if(session.data.ismute){
8241
+                        RTCRtpSender.track.enabled = false;
8242
+                    }
8243
+                }).catch(function(){
8244
+                    console.error(e);
8245
+                });
8246
+                session.data.AudioSourceTrack = null;
8247
+            }
8248
+        });
8249
+    }
8250
+
8251
+    // Set Preview
8252
+    // ===========
8253
+    console.log("Showing as preview...");
8254
+    var localVideo = $("#line-" + lineNum + "-localVideo").get(0);
8255
+    localVideo.srcObject = canvasMediaStream;
8256
+    localVideo.onloadedmetadata = function(e) {
8257
+        localVideo.play();
8258
+    }
8259
+}
8260
+function SendVideo(lineNum, src){
8261
+    var lineObj = FindLineByNumber(lineNum);
8262
+    if(lineObj == null || lineObj.SipSession == null){
8263
+        console.warn("Line or Session is Null");
8264
+        return;
8265
+    }
8266
+    var session = lineObj.SipSession;
8267
+
8268
+    $("#line-"+ lineNum +"-src-camera").prop("disabled", false);
8269
+    $("#line-"+ lineNum +"-src-canvas").prop("disabled", false);
8270
+    $("#line-"+ lineNum +"-src-desktop").prop("disabled", false);
8271
+    $("#line-"+ lineNum +"-src-video").prop("disabled", true);
8272
+    $("#line-"+ lineNum +"-src-blank").prop("disabled", false);
8273
+
8274
+    $("#line-" + lineNum + "-msg").html(lang.switching_to_shared_video);
8275
+
8276
+    $("#line-" + lineNum + "-scratchpad-container").hide();
8277
+    RemoveScratchpad(lineNum);
8278
+    $("#line-"+ lineNum +"-sharevideo").hide();
8279
+    $("#line-"+ lineNum +"-sharevideo").get(0).pause();
8280
+    $("#line-"+ lineNum +"-sharevideo").get(0).removeAttribute('src');
8281
+    $("#line-"+ lineNum +"-sharevideo").get(0).load();
8282
+
8283
+    $("#line-"+ lineNum +"-localVideo").hide();
8284
+    $("#line-"+ lineNum +"-remoteVideo").appendTo("#line-" + lineNum + "-preview-container");
8285
+
8286
+    // Create Video Object
8287
+    var newVideo = $("#line-" + lineNum + "-sharevideo");
8288
+    newVideo.prop("src", src);
8289
+    newVideo.off("loadedmetadata");
8290
+    newVideo.on("loadedmetadata", function () {
8291
+        console.log("Video can play now... ");
8292
+
8293
+        // Resample Video
8294
+        var ResampleSize = 360;
8295
+        if(VideoResampleSize == "HD") ResampleSize = 720;
8296
+        if(VideoResampleSize == "FHD") ResampleSize = 1080;
8297
+
8298
+        var videoObj = newVideo.get(0);
8299
+        var resampleCanvas = $('<canvas/>').get(0);
8300
+
8301
+        var videoWidth = videoObj.videoWidth;
8302
+        var videoHeight = videoObj.videoHeight;
8303
+        if(videoWidth >= videoHeight){
8304
+            // Landscape / Square
8305
+            if(videoHeight > ResampleSize){
8306
+                var p = ResampleSize / videoHeight;
8307
+                videoHeight = ResampleSize;
8308
+                videoWidth = videoWidth * p;
8309
+            }
8310
+        }
8311
+        else {
8312
+            // Portrate... (phone turned on its side)
8313
+            if(videoWidth > ResampleSize){
8314
+                var p = ResampleSize / videoWidth;
8315
+                videoWidth = ResampleSize;
8316
+                videoHeight = videoHeight * p;
8317
+            }
8318
+        }
8319
+
8320
+        resampleCanvas.width = videoWidth;
8321
+        resampleCanvas.height = videoHeight;
8322
+        var resampleContext = resampleCanvas.getContext("2d");
8323
+
8324
+        window.clearInterval(session.data.videoResampleInterval);
8325
+        session.data.videoResampleInterval = window.setInterval(function(){
8326
+            resampleContext.drawImage(videoObj, 0, 0, videoWidth, videoHeight);
8327
+        }, 40); // 25frames per second
8328
+
8329
+        // Capture the streams
8330
+        var videoMediaStream = null;
8331
+        if('captureStream' in videoObj) {
8332
+            videoMediaStream = videoObj.captureStream();
8333
+        }
8334
+        else if('mozCaptureStream' in videoObj) {
8335
+            // This doesn't really work
8336
+            // see: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/captureStream
8337
+            videoMediaStream = videoObj.mozCaptureStream();
8338
+        }
8339
+        else {
8340
+            // This is not supported.
8341
+            // videoMediaStream = videoObj.webkitCaptureStream();
8342
+            console.warn("Cannot capture stream from video, this will result in no audio being transmitted.")
8343
+        }
8344
+        var resampleVideoMediaStream = resampleCanvas.captureStream(25);
8345
+
8346
+        // Get the Tracks
8347
+        var videoMediaTrack = resampleVideoMediaStream.getVideoTracks()[0];
8348
+
8349
+        var audioTrackFromVideo = (videoMediaStream != null )? videoMediaStream.getAudioTracks()[0] : null;
8350
+
8351
+        // Switch & Merge Tracks
8352
+        var pc = session.sessionDescriptionHandler.peerConnection;
8353
+        pc.getSenders().forEach(function (RTCRtpSender) {
8354
+            if(RTCRtpSender.track && RTCRtpSender.track.kind == "video") {
8355
+                console.log("Switching Track : "+ RTCRtpSender.track.label);
8356
+                RTCRtpSender.track.stop();
8357
+                RTCRtpSender.replaceTrack(videoMediaTrack);
8358
+            }
8359
+            if(RTCRtpSender.track && RTCRtpSender.track.kind == "audio") {
8360
+                console.log("Switching to mixed Audio track on session");
8361
+
8362
+                session.data.AudioSourceTrack = RTCRtpSender.track;
8363
+
8364
+                var mixedAudioStream = new MediaStream();
8365
+                if(audioTrackFromVideo) mixedAudioStream.addTrack(audioTrackFromVideo);
8366
+                mixedAudioStream.addTrack(RTCRtpSender.track);
8367
+                var mixedAudioTrack = MixAudioStreams(mixedAudioStream).getAudioTracks()[0];
8368
+                mixedAudioTrack.IsMixedTrack = true;
8369
+
8370
+                RTCRtpSender.replaceTrack(mixedAudioTrack);
8371
+            }
8372
+        });
8373
+
8374
+        // Set Preview
8375
+        console.log("Showing as preview...");
8376
+        var localVideo = $("#line-" + lineNum + "-localVideo").get(0);
8377
+        localVideo.srcObject = videoMediaStream;
8378
+        localVideo.onloadedmetadata = function(e) {
8379
+            localVideo.play().then(function(){
8380
+                console.log("Playing Preview Video File");
8381
+            }).catch(function(e){
8382
+                console.error("Cannot play back video", e);
8383
+            });
8384
+        }
8385
+        // Play the video
8386
+        console.log("Starting Video...");
8387
+        $("#line-"+ lineNum +"-sharevideo").get(0).play();
8388
+    });
8389
+
8390
+    $("#line-"+ lineNum +"-sharevideo").show();
8391
+    console.log("Video for Sharing created...");
8392
+}
8393
+function ShareScreen(lineNum){
8394
+    var lineObj = FindLineByNumber(lineNum);
8395
+    if(lineObj == null || lineObj.SipSession == null){
8396
+        console.warn("Line or Session is Null");
8397
+        return;
8398
+    }
8399
+    var session = lineObj.SipSession;
8400
+
8401
+    $("#line-" + lineNum + "-msg").html(lang.switching_to_shared_screeen);
8402
+
8403
+    var localStream = new MediaStream();
8404
+    var pc = session.sessionDescriptionHandler.peerConnection;
8405
+
8406
+    if (navigator.getDisplayMedia) {
8407
+        // EDGE, legacy support
8408
+        var screenShareConstraints = { video: true, audio: false }
8409
+        navigator.getDisplayMedia(screenShareConstraints).then(function(newStream) {
8410
+            console.log("navigator.getDisplayMedia")
8411
+            var newMediaTrack = newStream.getVideoTracks()[0];
8412
+            pc.getSenders().forEach(function (RTCRtpSender) {
8413
+                if(RTCRtpSender.track && RTCRtpSender.track.kind == "video") {
8414
+                    console.log("Switching Video Track : "+ RTCRtpSender.track.label + " to Screen");
8415
+                    RTCRtpSender.track.stop();
8416
+                    RTCRtpSender.replaceTrack(newMediaTrack);
8417
+                    localStream.addTrack(newMediaTrack);
8418
+                }
8419
+            });
8420
+
8421
+            // Set Preview
8422
+            // ===========
8423
+            console.log("Showing as preview...");
8424
+            var localVideo = $("#line-" + lineNum + "-localVideo").get(0);
8425
+            localVideo.srcObject = localStream;
8426
+            localVideo.onloadedmetadata = function(e) {
8427
+                localVideo.play();
8428
+            }
8429
+        }).catch(function (err) {
8430
+            console.error("Error on getUserMedia");
8431
+        });
8432
+    }
8433
+    else if (navigator.mediaDevices.getDisplayMedia) {
8434
+        // New standard
8435
+        var screenShareConstraints = { video: true, audio: false }
8436
+        navigator.mediaDevices.getDisplayMedia(screenShareConstraints).then(function(newStream) {
8437
+            console.log("navigator.mediaDevices.getDisplayMedia")
8438
+            var newMediaTrack = newStream.getVideoTracks()[0];
8439
+            pc.getSenders().forEach(function (RTCRtpSender) {
8440
+                if(RTCRtpSender.track && RTCRtpSender.track.kind == "video") {
8441
+                    console.log("Switching Video Track : "+ RTCRtpSender.track.label + " to Screen");
8442
+                    RTCRtpSender.track.stop();
8443
+                    RTCRtpSender.replaceTrack(newMediaTrack);
8444
+                    localStream.addTrack(newMediaTrack);
8445
+                }
8446
+            });
8447
+
8448
+            // Set Preview
8449
+            // ===========
8450
+            console.log("Showing as preview...");
8451
+            var localVideo = $("#line-" + lineNum + "-localVideo").get(0);
8452
+            localVideo.srcObject = localStream;
8453
+            localVideo.onloadedmetadata = function(e) {
8454
+                localVideo.play();
8455
+            }
8456
+        }).catch(function (err) {
8457
+            console.error("Error on getUserMedia");
8458
+        });
8459
+    } 
8460
+    else {
8461
+        // Firefox, apparently
8462
+        var screenShareConstraints = { video: { mediaSource: 'screen' }, audio: false }
8463
+        navigator.mediaDevices.getUserMedia(screenShareConstraints).then(function(newStream) {
8464
+            console.log("navigator.mediaDevices.getUserMedia")
8465
+            var newMediaTrack = newStream.getVideoTracks()[0];
8466
+            pc.getSenders().forEach(function (RTCRtpSender) {
8467
+                if(RTCRtpSender.track && RTCRtpSender.track.kind == "video") {
8468
+                    console.log("Switching Video Track : "+ RTCRtpSender.track.label + " to Screen");
8469
+                    RTCRtpSender.track.stop();
8470
+                    RTCRtpSender.replaceTrack(newMediaTrack);
8471
+                    localStream.addTrack(newMediaTrack);
8472
+                }
8473
+            });
8474
+
8475
+            // Set Preview
8476
+            console.log("Showing as preview...");
8477
+            var localVideo = $("#line-" + lineNum + "-localVideo").get(0);
8478
+            localVideo.srcObject = localStream;
8479
+            localVideo.onloadedmetadata = function(e) {
8480
+                localVideo.play();
8481
+            }
8482
+        }).catch(function (err) {
8483
+            console.error("Error on getUserMedia");
8484
+        });
8485
+    }
8486
+
8487
+    // Restore Audio Stream if it was changed
8488
+    if(session.data.AudioSourceTrack && session.data.AudioSourceTrack.kind == "audio"){
8489
+        pc.getSenders().forEach(function (RTCRtpSender) {
8490
+            if(RTCRtpSender.track && RTCRtpSender.track.kind == "audio") {
8491
+                RTCRtpSender.replaceTrack(session.data.AudioSourceTrack).then(function(){
8492
+                    if(session.data.ismute){
8493
+                        RTCRtpSender.track.enabled = false;
8494
+                    }
8495
+                }).catch(function(){
8496
+                    console.error(e);
8497
+                });
8498
+                session.data.AudioSourceTrack = null;
8499
+            }
8500
+        });
8501
+    }
8502
+
8503
+}
8504
+function DisableVideoStream(lineNum){
8505
+    var lineObj = FindLineByNumber(lineNum);
8506
+    if(lineObj == null || lineObj.SipSession == null){
8507
+        console.warn("Line or Session is Null");
8508
+        return;
8509
+    }
8510
+    var session = lineObj.SipSession;
8511
+
8512
+    var pc = session.sessionDescriptionHandler.peerConnection;
8513
+    pc.getSenders().forEach(function (RTCRtpSender) {
8514
+        if(RTCRtpSender.track && RTCRtpSender.track.kind == "video") {
8515
+            console.log("Disable Video Track : "+ RTCRtpSender.track.label + "");
8516
+            RTCRtpSender.track.enabled = false; //stop();
8517
+        }
8518
+        if(RTCRtpSender.track && RTCRtpSender.track.kind == "audio") {
8519
+            if(session.data.AudioSourceTrack && session.data.AudioSourceTrack.kind == "audio"){
8520
+                RTCRtpSender.replaceTrack(session.data.AudioSourceTrack).then(function(){
8521
+                    if(session.data.ismute){
8522
+                        RTCRtpSender.track.enabled = false;
8523
+                    }
8524
+                }).catch(function(){
8525
+                    console.error(e);
8526
+                });
8527
+                session.data.AudioSourceTrack = null;
8528
+            }
8529
+        }
8530
+    });
8531
+
8532
+    // Set Preview
8533
+    console.log("Showing as preview...");
8534
+    var localVideo = $("#line-" + lineNum + "-localVideo").get(0);
8535
+    localVideo.pause();
8536
+    localVideo.removeAttribute('src');
8537
+    localVideo.load();
8538
+
8539
+    $("#line-" + lineNum + "-msg").html(lang.video_disabled);
8540
+}
8541
+
8542
+// Phone Lines
8543
+// ===========
8544
+var Line = function(lineNumber, displayName, displayNumber, buddyObj){
8545
+    this.LineNumber = lineNumber;
8546
+    this.DisplayName = displayName;
8547
+    this.DisplayNumber = displayNumber;
8548
+    this.IsSelected = false;
8549
+    this.BuddyObj = buddyObj;
8550
+    this.SipSession = null;
8551
+    this.LocalSoundMeter = null;
8552
+    this.RemoteSoundMeter = null;
8553
+}
8554
+function ShowDial(obj){
8555
+
8556
+    var leftPos = obj.offsetWidth + 104;
8557
+    var rightPos = 0;
8558
+    var topPos = obj.offsetHeight + 117;
8559
+
8560
+    if ($(window).width() <= 915) {
8561
+        leftPos = event.pageX + obj.offsetWidth - 120;
8562
+        rightPos = 0;
8563
+        topPos = event.pageY + obj.offsetHeight - 11;
8564
+    }
8565
+
8566
+    var html = "<div id=mainDialPad><div><input id=dialText class=dialTextInput oninput=\"handleDialInput(this, event)\" onkeydown=\"dialOnkeydown(event, this)\"></div>";
8567
+    html += "<table cellspacing=10 cellpadding=0 style=\"margin-left:auto; margin-right: auto\">";
8568
+    html += "<tr><td><button class=dtmfButtons onclick=\"KeyPress('1');new Audio('sounds/dtmf.mp3').play();\"><div>1</div><span>&nbsp;</span></button></td>"
8569
+    html += "<td><button class=dtmfButtons onclick=\"KeyPress('2');new Audio('sounds/dtmf.mp3').play();\"><div>2</div><span>ABC</span></button></td>"
8570
+    html += "<td><button class=dtmfButtons onclick=\"KeyPress('3');new Audio('sounds/dtmf.mp3').play();\"><div>3</div><span>DEF</span></button></td></tr>";
8571
+    html += "<tr><td><button class=dtmfButtons onclick=\"KeyPress('4');new Audio('sounds/dtmf.mp3').play();\"><div>4</div><span>GHI</span></button></td>"
8572
+    html += "<td><button class=dtmfButtons onclick=\"KeyPress('5');new Audio('sounds/dtmf.mp3').play();\"><div>5</div><span>JKL</span></button></td>"
8573
+    html += "<td><button class=dtmfButtons onclick=\"KeyPress('6');new Audio('sounds/dtmf.mp3').play();\"><div>6</div><span>MNO</span></button></td></tr>";
8574
+    html += "<tr><td><button class=dtmfButtons onclick=\"KeyPress('7');new Audio('sounds/dtmf.mp3').play();\"><div>7</div><span>PQRS</span></button></td>"
8575
+    html += "<td><button class=dtmfButtons onclick=\"KeyPress('8');new Audio('sounds/dtmf.mp3').play();\"><div>8</div><span>TUV</span></button></td>"
8576
+    html += "<td><button class=dtmfButtons onclick=\"KeyPress('9');new Audio('sounds/dtmf.mp3').play();\"><div>9</div><span>WXYZ</span></button></td></tr>";
8577
+    html += "<tr><td><button class=dtmfButtons onclick=\"KeyPress('*');new Audio('sounds/dtmf.mp3').play();\">*</button></td>"
8578
+    html += "<td><button class=dtmfButtons onclick=\"KeyPress('0');new Audio('sounds/dtmf.mp3').play();\">0</button></td>"
8579
+    html += "<td><button class=dtmfButtons onclick=\"KeyPress('#');new Audio('sounds/dtmf.mp3').play();\">#</button></td></tr>";
8580
+    html += "</table>";
8581
+    html += "<div style=\"text-align: center;\">";
8582
+    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>";
8583
+    if(EnableVideoCalling){
8584
+        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>";
8585
+    }
8586
+    html += "</div></div>";
8587
+
8588
+    $.jeegoopopup.open({
8589
+                html: html,
8590
+                width: "auto",
8591
+                height: "auto",
8592
+                left: leftPos,
8593
+                right: rightPos,
8594
+                top: topPos,
8595
+                scrolling: 'no',
8596
+                skinClass: 'jg_popup_basic',
8597
+//                innerClass: 'showDialInner',
8598
+                overlay: true,
8599
+                opacity: 0,
8600
+                draggable: true,
8601
+                resizable: false,
8602
+                fadeIn: 0
8603
+    });
8604
+
8605
+    $("#dialText").focus();
8606
+
8607
+    if ($(window).width() <= 915) { $.jeegoopopup.right(6); } else { $.jeegoopopup.width('auto').height('auto').left(leftPos).top(topPos); }
8608
+
8609
+    $("#jg_popup_overlay").click(function() { $("#jg_popup_b").empty(); $("#jg_popup_l").empty(); $("#windowCtrls").empty(); $.jeegoopopup.close(); });
8610
+    $(window).on('keydown', function(event) { if (event.key == "Escape") { $("#jg_popup_b").empty(); $("#jg_popup_l").empty(); $("#windowCtrls").empty(); $.jeegoopopup.close(); } });
8611
+}
8612
+
8613
+function handleDialInput(obj, event){
8614
+    if(EnableAlphanumericDial){
8615
+        $("#dialText").val($("#dialText").val().replace(/[^\da-zA-Z\*\#\+]/g, "").substring(0,MaxDidLength));
8616
+    }
8617
+    else {
8618
+        $("#dialText").val($("#dialText").val().replace(/[^\d\*\#\+]/g, "").substring(0,MaxDidLength));
8619
+    }
8620
+    $("#dialVideo").prop('disabled', ($("#dialText").val().length >= DidLength));
8621
+}
8622
+function dialOnkeydown(event, obj, buddy) {
8623
+    var keycode = (event.keyCode ? event.keyCode : event.which);
8624
+    if (keycode == '13'){
8625
+
8626
+        event.preventDefault();
8627
+
8628
+        // Defaults to audio dial
8629
+        DialByLine('audio');
8630
+
8631
+        $("#jg_popup_b").empty(); $("#jg_popup_l").empty(); $("#windowCtrls").empty(); $.jeegoopopup.close();
8632
+
8633
+        return false;
8634
+    }
8635
+}
8636
+function KeyPress(num){
8637
+    $("#dialText").val(($("#dialText").val()+num).substring(0,MaxDidLength));
8638
+    $("#dialVideo").prop('disabled', ($("#dialText").val().length >= DidLength));
8639
+}
8640
+function DialByLine(type, buddy, numToDial, CallerID){
8641
+    $.jeegoopopup.close();
8642
+    if(userAgent == null || userAgent.isRegistered()==false){
8643
+        ConfigureExtensionWindow();
8644
+        return;
8645
+    }
8646
+
8647
+    var numDial = (numToDial)? numToDial : $("#dialText").val();
8648
+    if(EnableAlphanumericDial){
8649
+        numDial = numDial.replace(/[^\da-zA-Z\*\#\+]/g, "").substring(0,MaxDidLength);
8650
+    }
8651
+    else {
8652
+        numDial = numDial.replace(/[^\d\*\#\+]/g, "").substring(0,MaxDidLength);
8653
+    }
8654
+    if(numDial.length == 0) {
8655
+        console.warn("Enter number to dial");
8656
+        return;
8657
+    }
8658
+
8659
+    // Create a Buddy if one is not already existing
8660
+    var buddyObj = (buddy)? FindBuddyByIdentity(buddy) : FindBuddyByDid(numDial);
8661
+    if(buddyObj == null) {
8662
+        var buddyType = (numDial.length > DidLength)? "contact" : "extension";
8663
+        // Assumption but anyway: If the number starts with a * or # then its probably not a subscribable DID,
8664
+        // and is probably a feature code.
8665
+        if(buddyType.substring(0,1) == "*" || buddyType.substring(0,1) == "#") buddyType = "contact";
8666
+        buddyObj = MakeBuddy(buddyType, true, false, true, (CallerID)? CallerID : numDial, numDial);
8667
+    }
8668
+
8669
+    // Create a Line
8670
+    newLineNumber = newLineNumber + 1;
8671
+    lineObj = new Line(newLineNumber, buddyObj.CallerIDName, numDial, buddyObj);
8672
+    Lines.push(lineObj);
8673
+    AddLineHtml(lineObj);
8674
+    SelectLine(newLineNumber);
8675
+    UpdateBuddyList();
8676
+
8677
+    // Start Call Invite
8678
+    if(type == "audio"){
8679
+        AudioCall(lineObj, numDial);
8680
+    }
8681
+    else {
8682
+        VideoCall(lineObj, numDial);
8683
+    }
8684
+
8685
+    try{
8686
+        $("#line-" + newLineNumber).get(0).scrollIntoViewIfNeeded();
8687
+    } catch(e){}
8688
+}
8689
+function SelectLine(lineNum){
8690
+
8691
+    $("#roundcubeFrame").remove();
8692
+
8693
+    var lineObj = FindLineByNumber(lineNum);
8694
+    if(lineObj == null) return;
8695
+
8696
+    var displayLineNumber = 0;
8697
+    for(var l = 0; l < Lines.length; l++) {
8698
+        if(Lines[l].LineNumber == lineObj.LineNumber) displayLineNumber = l+1;
8699
+        if(Lines[l].IsSelected == true && Lines[l].LineNumber == lineObj.LineNumber){
8700
+            // Nothing to do, you re-selected the same buddy;
8701
+            return;
8702
+        }
8703
+    }
8704
+
8705
+    console.log("Selecting Line : "+ lineObj.LineNumber);
8706
+
8707
+    // Can only display one thing on the right
8708
+    $(".streamSelected").each(function () {
8709
+        $(this).prop('class', 'stream');
8710
+    });
8711
+    $("#line-ui-" + lineObj.LineNumber).prop('class', 'streamSelected');
8712
+
8713
+    $("#line-ui-" + lineObj.LineNumber + "-DisplayLineNo").html("<i class=\"fa fa-phone\"></i> "+ lang.line +" "+ displayLineNumber);
8714
+    $("#line-ui-" + lineObj.LineNumber + "-LineIcon").html(displayLineNumber);
8715
+
8716
+    // Switch the SIP Sessions
8717
+    SwitchLines(lineObj.LineNumber);
8718
+
8719
+    // Update Lines List
8720
+    for(var l = 0; l < Lines.length; l++) {
8721
+        var classStr = (Lines[l].LineNumber == lineObj.LineNumber)? "buddySelected" : "buddy";
8722
+        if(Lines[l].SipSession != null) classStr = (Lines[l].SipSession.local_hold)? "buddyActiveCallHollding" : "buddyActiveCall";
8723
+
8724
+        $("#line-" + Lines[l].LineNumber).prop('class', classStr);
8725
+        Lines[l].IsSelected = (Lines[l].LineNumber == lineObj.LineNumber);
8726
+    }
8727
+    // Update Buddy List
8728
+    for(var b = 0; b < Buddies.length; b++) {
8729
+        $("#contact-" + Buddies[b].identity).prop("class", "buddy");
8730
+        Buddies[b].IsSelected = false;
8731
+    }
8732
+
8733
+    // Change to Stream if in Narrow view
8734
+    UpdateUI();
8735
+}
8736
+function FindLineByNumber(lineNum) {
8737
+    for(var l = 0; l < Lines.length; l++) {
8738
+        if(Lines[l].LineNumber == lineNum) return Lines[l];
8739
+    }
8740
+    return null;
8741
+}
8742
+function AddLineHtml(lineObj) {
8743
+
8744
+    var html = "<table id=\"line-ui-"+ lineObj.LineNumber +"\" class=\"stream\" cellspacing=\"5\" cellpadding=\"0\">";
8745
+    html += "<tr><td class=streamSection>";
8746
+
8747
+    // Close|Return|Back Button
8748
+    html += "<div style=\"float:left; margin:0px; padding:5px; height:38px; line-height:38px\">"
8749
+    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> ";
8750
+    html += "</div>"
8751
+
8752
+    // Profile UI
8753
+    html += "<div class=contact style=\"float: left;\">";
8754
+    html += "<div id=\"line-ui-"+ lineObj.LineNumber +"-LineIcon\" class=lineIcon>"+ lineObj.LineNumber +"</div>";
8755
+    html += "<div id=\"line-ui-"+ lineObj.LineNumber +"-DisplayLineNo\" class=contactNameText><i class=\"fa fa-phone\"></i> "+ lang.line +" "+ lineObj.LineNumber +"</div>";
8756
+
8757
+    html += "<div class=presenceText>"+ lineObj.DisplayName +" <"+ lineObj.DisplayNumber +"></div>";
8758
+    html += "</div>";
8759
+
8760
+    // Action Buttons
8761
+    html += "<div style=\"float:right; line-height: 46px;\">";
8762
+    html += "</div>";
8763
+
8764
+    // Separator --------------------------------------------------------------------------
8765
+    html += "<div style=\"clear:both; height:0px\"></div>"
8766
+
8767
+    // Calling UI --------------------------------------------------------------------------
8768
+    html += "<div id=\"line-"+ lineObj.LineNumber +"-calling\">";
8769
+
8770
+    // Gneral Messages
8771
+    html += "<div id=\"line-"+ lineObj.LineNumber +"-timer\" style=\"float: right; margin-top: 4px; margin-right: 10px; color: #575757; display:none;\"></div>";
8772
+    html += "<div id=\"line-"+ lineObj.LineNumber +"-msg\" class=callStatus style=\"display:none\">...</div>";
8773
+
8774
+    // Dialing Out Progress
8775
+    html += "<div id=\"line-"+ lineObj.LineNumber +"-progress\" style=\"display:none; margin-top: 10px\">";
8776
+    html += "<div class=progressCall>";
8777
+    html += "<button onclick=\"cancelSession('"+ lineObj.LineNumber +"')\" class=hangupButton><i class=\"fa fa-phone\"></i>&nbsp;&nbsp;"+ lang.cancel +"</button>";
8778
+    html += "</div>";
8779
+    html += "</div>";
8780
+
8781
+    // Active Call UI
8782
+    html += "<div id=\"line-"+ lineObj.LineNumber +"-ActiveCall\" style=\"display:none; margin-top: 10px;\">";
8783
+
8784
+    // Group Call
8785
+    html += "<div id=\"line-"+ lineObj.LineNumber +"-conference\" style=\"display:none;\"></div>";
8786
+
8787
+    // Video UI
8788
+    if(lineObj.BuddyObj.type == "extension") {
8789
+        html += "<div id=\"line-"+ lineObj.LineNumber +"-VideoCall\" class=videoCall style=\"display:none;\">";
8790
+
8791
+        // Presentation
8792
+        html += "<div style=\"height:35px; line-height:35px; text-align: right\">"+ lang.present +": ";
8793
+        html += "<div class=pill-nav style=\"border-color:#333333\">";
8794
+        html += "<button id=\"line-"+ lineObj.LineNumber +"-src-camera\" onclick=\"PresentCamera('"+ lineObj.LineNumber +"')\" title=\""+ lang.camera +"\" disabled><i class=\"fa fa-video-camera\"></i></button>";
8795
+        html += "<button id=\"line-"+ lineObj.LineNumber +"-src-canvas\" onclick=\"PresentScratchpad('"+ lineObj.LineNumber +"')\" title=\""+ lang.scratchpad +"\"><i class=\"fa fa-pencil-square\"></i></button>";
8796
+        html += "<button id=\"line-"+ lineObj.LineNumber +"-src-desktop\" onclick=\"PresentScreen('"+ lineObj.LineNumber +"')\" title=\""+ lang.screen +"\"><i class=\"fa fa-desktop\"></i></button>";
8797
+        html += "<button id=\"line-"+ lineObj.LineNumber +"-src-video\" onclick=\"PresentVideo('"+ lineObj.LineNumber +"')\" title=\""+ lang.video +"\"><i class=\"fa fa-file-video-o\"></i></button>";
8798
+        html += "<button id=\"line-"+ lineObj.LineNumber +"-src-blank\" onclick=\"PresentBlank('"+ lineObj.LineNumber +"')\" title=\""+ lang.blank +"\"><i class=\"fa fa-ban\"></i></button>";
8799
+        html += "</div>";
8800
+        html += "&nbsp;<button id=\"line-"+ lineObj.LineNumber +"-expand\" onclick=\"ExpandVideoArea('"+ lineObj.LineNumber +"')\"><i class=\"fa fa-expand\"></i></button>";
8801
+        html += "<button id=\"line-"+ lineObj.LineNumber +"-restore\" onclick=\"RestoreVideoArea('"+ lineObj.LineNumber +"')\" style=\"display:none\"><i class=\"fa fa-compress\"></i></button>";
8802
+        html += "</div>";
8803
+
8804
+        // Preview
8805
+        html += "<div id=\"line-"+ lineObj.LineNumber +"-preview-container\" class=PreviewContainer>";
8806
+        html += "<video id=\"line-"+ lineObj.LineNumber +"-localVideo\" muted></video>"; // Default Display
8807
+        html += "</div>";
8808
+
8809
+        // Stage
8810
+        html += "<div id=\"line-"+ lineObj.LineNumber +"-stage-container\" class=StageContainer>";
8811
+        html += "<video id=\"line-"+ lineObj.LineNumber +"-remoteVideo\" muted></video>"; // Default Display
8812
+        html += "<div id=\"line-"+ lineObj.LineNumber +"-scratchpad-container\" style=\"display:none\"></div>";
8813
+        html += "<video id=\"line-"+ lineObj.LineNumber +"-sharevideo\" controls muted style=\"display:none; object-fit: contain;\"></video>";
8814
+        html += "</div>";
8815
+
8816
+        html += "</div>";
8817
+    }
8818
+
8819
+    // Audio Call
8820
+    html += "<div id=\"line-"+ lineObj.LineNumber +"-AudioCall\" style=\"display:none;\">";
8821
+    html += "<audio id=\"line-"+ lineObj.LineNumber+"-remoteAudio\"></audio>";
8822
+    html += "</div>";
8823
+
8824
+    // In Call Buttons
8825
+    html += "<div style=\"text-align:center\">";
8826
+    html += "<div style=\"margin-top:10px\">";
8827
+    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>";
8828
+    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>";
8829
+    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>";
8830
+    if(typeof MediaRecorder != "undefined" && (CallRecordingPolicy == "allow" || CallRecordingPolicy == "enabled")){
8831
+        // Safari: must enable in Develop > Experimental Features > MediaRecorder
8832
+        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>";
8833
+        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>";
8834
+    }
8835
+    if(EnableTransfer){
8836
+        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>";
8837
+        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>";
8838
+    }
8839
+
8840
+    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>";
8841
+    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>";
8842
+    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>";
8843
+    html += "</div>";
8844
+    // Call Transfer
8845
+    html += "<div id=\"line-"+ lineObj.LineNumber +"-Transfer\" style=\"display:none\">";
8846
+    html += "<div style=\"margin-top:10px\">";
8847
+    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>";
8848
+    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>"
8849
+    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>";
8850
+    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>";
8851
+    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>";
8852
+    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>";
8853
+    html += "</div>";
8854
+    html += "<div id=\"line-"+ lineObj.LineNumber +"-transfer-status\" class=callStatus style=\"margin-top:10px; display:none\">...</div>";
8855
+    html += "<audio id=\"line-"+ lineObj.LineNumber +"-transfer-remoteAudio\" style=\"display:none\"></audio>";
8856
+    html += "</div>";
8857
+    // Call Conference
8858
+    html += "<div id=\"line-"+ lineObj.LineNumber +"-Conference\" style=\"display:none\">";
8859
+    html += "<div style=\"margin-top:10px\">";
8860
+    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>";
8861
+    html += " <button id=\"line-"+ lineObj.LineNumber +"-btn-conference-dial\" onclick=\"ConferenceDial('"+ lineObj.LineNumber +"')\"><i class=\"fa fa-phone\"></i> "+ lang.call +"</button>";
8862
+    html += " <button id=\"line-"+ lineObj.LineNumber +"-btn-cancel-conference-dial\" style=\"display:none\"><i class=\"fa fa-phone\"></i> "+ lang.cancel_call +"</buuton>";
8863
+    html += " <button id=\"line-"+ lineObj.LineNumber +"-btn-join-conference-call\" style=\"display:none\"><i class=\"fa fa-users\"></i> "+ lang.join_conference_call +"</buuton>";
8864
+    html += " <button id=\"line-"+ lineObj.LineNumber +"-btn-terminate-conference-call\" style=\"display:none\"><i class=\"fa fa-phone\"></i> "+ lang.end_conference_call +"</buuton>";
8865
+    html += "</div>";
8866
+    html += "<div id=\"line-"+ lineObj.LineNumber +"-conference-status\" class=callStatus style=\"margin-top:10px; display:none\">...</div>";
8867
+    html += "<audio id=\"line-"+ lineObj.LineNumber +"-conference-remoteAudio\" style=\"display:none\"></audio>";
8868
+    html += "</div>";
8869
+    
8870
+    // Monitoring
8871
+    html += "<div  id=\"line-"+ lineObj.LineNumber +"-monitoring\" style=\"margin-top:10px;margin-bottom:10px;\">";
8872
+    html += "<span style=\"vertical-align: middle\"><i class=\"fa fa-microphone\"></i></span> ";
8873
+    html += "<span class=meterContainer title=\""+ lang.microphone_levels +"\">";
8874
+    html += "<span id=\"line-"+ lineObj.LineNumber +"-Mic\" class=meterLevel style=\"height:0%\"></span>";
8875
+    html += "</span> ";
8876
+    html += "<span style=\"vertical-align: middle\"><i class=\"fa fa-volume-up\"></i></span> ";
8877
+    html += "<span class=meterContainer title=\""+ lang.speaker_levels +"\">";
8878
+    html += "<span id=\"line-"+ lineObj.LineNumber +"-Speaker\" class=meterLevel style=\"height:0%\"></span>";
8879
+    html += "</span> ";
8880
+    html += "<button id=\"line-"+ lineObj.LineNumber +"-btn-settings\" onclick=\"ChangeSettings('"+ lineObj.LineNumber +"', this)\"><i class=\"fa fa-cogs\"></i> "+ lang.device_settings +"</button>";
8881
+    html += "<button id=\"line-"+ lineObj.LineNumber +"-call-stats\" onclick=\"ShowCallStats('"+ lineObj.LineNumber +"', this)\"><i class=\"fa fa-area-chart\"></i> "+ lang.call_stats +"</button>";
8882
+    html += "</div>";
8883
+
8884
+    html += "<div id=\"line-"+ lineObj.LineNumber +"-AudioStats\" class=\"audioStats cleanScroller\" style=\"display:none\">";
8885
+    html += "<div style=\"text-align:right\"><button onclick=\"HideCallStats('"+ lineObj.LineNumber +"', this)\"><i class=\"fa fa-times\" style=\"font-size:20px;\"></i></button></div>";
8886
+    html += "<fieldset class=audioStatsSet onclick=\"HideCallStats('"+ lineObj.LineNumber +"', this)\">";
8887
+    html += "<legend>"+ lang.send_statistics +"</legend>";
8888
+    html += "<canvas id=\"line-"+ lineObj.LineNumber +"-AudioSendBitRate\" class=audioGraph width=600 height=160 style=\"width:600px; height:160px\"></canvas>";
8889
+    html += "<canvas id=\"line-"+ lineObj.LineNumber +"-AudioSendPacketRate\" class=audioGraph width=600 height=160 style=\"width:600px; height:160px\"></canvas>";
8890
+    html += "</fieldset>";
8891
+    html += "<fieldset class=audioStatsSet onclick=\"HideCallStats('"+ lineObj.LineNumber +"', this)\">";
8892
+    html += "<legend>"+ lang.receive_statistics +"</legend>";
8893
+    html += "<canvas id=\"line-"+ lineObj.LineNumber +"-AudioReceiveBitRate\" class=audioGraph width=600 height=160 style=\"width:600px; height:160px\"></canvas>";
8894
+    html += "<canvas id=\"line-"+ lineObj.LineNumber +"-AudioReceivePacketRate\" class=audioGraph width=600 height=160 style=\"width:600px; height:160px\"></canvas>";
8895
+    html += "<canvas id=\"line-"+ lineObj.LineNumber +"-AudioReceivePacketLoss\" class=audioGraph width=600 height=160 style=\"width:600px; height:160px\"></canvas>";
8896
+    html += "<canvas id=\"line-"+ lineObj.LineNumber +"-AudioReceiveJitter\" class=audioGraph width=600 height=160 style=\"width:600px; height:160px\"></canvas>";
8897
+    html += "<canvas id=\"line-"+ lineObj.LineNumber +"-AudioReceiveLevels\" class=audioGraph width=600 height=160 style=\"width:600px; height:160px\"></canvas>";
8898
+    html += "</fieldset>";
8899
+    html += "</div>";
8900
+
8901
+    html += "</div>";
8902
+    html += "</div>";
8903
+    html += "</div>";
8904
+    html += "</td></tr>";
8905
+    html += "<tr><td class=\"streamSection streamSectionBackground\">";
8906
+    
8907
+    html += "<div id=\"line-"+ lineObj.LineNumber +"-CallDetails\" class=\"chatHistory cleanScroller\">";
8908
+    // In Call Activity
8909
+    html += "</div>";
8910
+
8911
+    html += "</td></tr>";
8912
+    html += "</table>";
8913
+
8914
+    $("#rightContent").append(html);
8915
+}
8916
+function RemoveLine(lineObj){
8917
+    if(lineObj == null) return;
8918
+
8919
+    for(var l = 0; l < Lines.length; l++) {
8920
+        if(Lines[l].LineNumber == lineObj.LineNumber) {
8921
+            Lines.splice(l,1);
8922
+            break;
8923
+        }
8924
+    }
8925
+
8926
+    CloseLine(lineObj.LineNumber);
8927
+    $("#line-ui-"+ lineObj.LineNumber).remove();
8928
+
8929
+    UpdateBuddyList();
8930
+
8931
+    // Rather than showing nothing, go to the last buddy selected
8932
+    // Select last user
8933
+    if(localDB.getItem("SelectedBuddy") != null){
8934
+        console.log("Selecting previously selected buddy...", localDB.getItem("SelectedBuddy"));
8935
+        SelectBuddy(localDB.getItem("SelectedBuddy"));
8936
+        UpdateUI();
8937
+    }
8938
+}
8939
+function CloseLine(lineNum){
8940
+    // Lines and Buddies (Left)
8941
+    $(".buddySelected").each(function () {
8942
+        $(this).prop('class', 'buddy');
8943
+    });
8944
+    // Streams (Right)
8945
+    $(".streamSelected").each(function () {
8946
+        $(this).prop('class', 'stream');
8947
+    });
8948
+
8949
+    SwitchLines(0);
8950
+
8951
+    console.log("Closing Line: "+ lineNum);
8952
+    for(var l = 0; l < Lines.length; l++){
8953
+        Lines[l].IsSelected = false;
8954
+    }
8955
+    selectedLine = null;
8956
+    for(var b = 0; b < Buddies.length; b++){
8957
+        Buddies[b].IsSelected = false;
8958
+    }
8959
+    selectedBuddy = null;
8960
+
8961
+    $.jeegoopopup.close();
8962
+
8963
+    // Change to Stream if in Narrow view
8964
+    UpdateUI();
8965
+}
8966
+function SwitchLines(lineNum){
8967
+    $.each(userAgent.sessions, function (i, session) {
8968
+        // All the other calls, not on hold
8969
+        if(session.local_hold == false && session.data.line != lineNum) {
8970
+            console.log("Putting an active call on hold: Line: "+ session.data.line +" buddy: "+ session.data.buddyId);
8971
+            session.hold(); // Check state
8972
+
8973
+            // Log Hold
8974
+            if(!session.data.hold) session.data.hold = [];
8975
+            session.data.hold.push({ event: "hold", eventTime: utcDateNow() });
8976
+        }
8977
+        $("#line-" + session.data.line + "-btn-Hold").hide();
8978
+        $("#line-" + session.data.line + "-btn-Unhold").show();
8979
+        session.data.IsCurrentCall = false;
8980
+    });
8981
+
8982
+    var lineObj = FindLineByNumber(lineNum);
8983
+    if(lineObj != null && lineObj.SipSession != null) {
8984
+        var session = lineObj.SipSession;
8985
+        if(session.local_hold == true) {
8986
+            console.log("Taking call off hold:  Line: "+ lineNum +" buddy: "+ session.data.buddyId);
8987
+            session.unhold();
8988
+
8989
+            // Log Hold
8990
+            if(!session.data.hold) session.data.hold = [];
8991
+            session.data.hold.push({ event: "unhold", eventTime: utcDateNow() });
8992
+        }
8993
+        $("#line-" + lineNum + "-btn-Hold").show();
8994
+        $("#line-" + lineNum + "-btn-Unhold").hide();
8995
+        session.data.IsCurrentCall = true;
8996
+    }
8997
+    selectedLine = lineNum;
8998
+
8999
+    RefreshLineActivity(lineNum);
9000
+}
9001
+function RefreshLineActivity(lineNum){
9002
+    var lineObj = FindLineByNumber(lineNum);
9003
+    if(lineObj == null || lineObj.SipSession == null) {
9004
+        return;
9005
+    }
9006
+    var session = lineObj.SipSession;
9007
+
9008
+    $("#line-"+ lineNum +"-CallDetails").empty();
9009
+
9010
+    var callDetails = [];
9011
+
9012
+    var ringTime = 0;
9013
+    var CallStart = moment.utc(session.data.callstart.replace(" UTC", ""));
9014
+    var CallAnswer = null;
9015
+    if(session.startTime){
9016
+        CallAnswer = moment.utc(session.startTime);
9017
+        ringTime = moment.duration(CallAnswer.diff(CallStart));
9018
+    }
9019
+    CallStart = CallStart.format("YYYY-MM-DD HH:mm:ss UTC")
9020
+    CallAnswer = (CallAnswer)? CallAnswer.format("YYYY-MM-DD HH:mm:ss UTC") : null,
9021
+    ringTime = (ringTime != 0)? ringTime.asSeconds() : 0
9022
+
9023
+    var srcCallerID = "";
9024
+    var dstCallerID = "";
9025
+    if(session.data.calldirection == "inbound") {
9026
+        srcCallerID = "<"+ session.remoteIdentity.uri.user +"> "+ session.remoteIdentity.displayName;
9027
+    } 
9028
+    else if(session.data.calldirection == "outbound") {
9029
+        dstCallerID = session.remoteIdentity.uri.user;
9030
+    }
9031
+
9032
+    var withVideo = (session.data.withvideo)? "("+ lang.with_video +")" : "";
9033
+    var startCallMessage = (session.data.calldirection == "inbound")? lang.you_received_a_call_from + " " + srcCallerID  +" "+ withVideo : lang.you_made_a_call_to + " " + dstCallerID +" "+ withVideo;
9034
+    callDetails.push({ 
9035
+        Message: startCallMessage,
9036
+        TimeStr : CallStart
9037
+    });
9038
+    if(CallAnswer){
9039
+        var answerCallMessage = (session.data.calldirection == "inbound")? lang.you_answered_after + " " + ringTime + " " + lang.seconds_plural : lang.they_answered_after + " " + ringTime + " " + lang.seconds_plural;
9040
+        callDetails.push({ 
9041
+            Message: answerCallMessage,
9042
+            TimeStr : CallAnswer
9043
+        });
9044
+    }
9045
+
9046
+    var Transfers = (session.data.transfer)? session.data.transfer : [];
9047
+    $.each(Transfers, function(item, transfer){
9048
+        var msg = (transfer.type == "Blind")? lang.you_started_a_blind_transfer_to +" "+ transfer.to +". " : lang.you_started_an_attended_transfer_to + " "+ transfer.to +". ";
9049
+        if(transfer.accept && transfer.accept.complete == true){
9050
+            msg += lang.the_call_was_completed
9051
+        }
9052
+        else if(transfer.accept.disposition != "") {
9053
+            msg += lang.the_call_was_not_completed +" ("+ transfer.accept.disposition +")"
9054
+        }
9055
+        callDetails.push({
9056
+            Message : msg,
9057
+            TimeStr : transfer.transferTime
9058
+        });
9059
+    });
9060
+    var Mutes = (session.data.mute)? session.data.mute : []
9061
+    $.each(Mutes, function(item, mute){
9062
+        callDetails.push({
9063
+            Message : (mute.event == "mute")? lang.you_put_the_call_on_mute : lang.you_took_the_call_off_mute,
9064
+            TimeStr : mute.eventTime
9065
+        });
9066
+    });
9067
+    var Holds = (session.data.hold)? session.data.hold : []
9068
+    $.each(Holds, function(item, hold){
9069
+        callDetails.push({
9070
+            Message : (hold.event == "hold")? lang.you_put_the_call_on_hold : lang.you_took_the_call_off_hold,
9071
+            TimeStr : hold.eventTime
9072
+        });
9073
+    });
9074
+    var Recordings = (session.data.recordings)? session.data.recordings : []
9075
+    $.each(Recordings, function(item, recording){
9076
+        var msg = lang.call_is_being_recorded;
9077
+        if(recording.startTime != recording.stopTime){
9078
+            msg += "("+ lang.now_stopped +")"
9079
+        }
9080
+        callDetails.push({
9081
+            Message : msg,
9082
+            TimeStr : recording.startTime
9083
+        });
9084
+    });
9085
+    var ConfCalls = (session.data.confcalls)? session.data.confcalls : []
9086
+    $.each(ConfCalls, function(item, confCall){
9087
+        var msg = lang.you_started_a_conference_call_to +" "+ confCall.to +". ";
9088
+        if(confCall.accept && confCall.accept.complete == true){
9089
+            msg += lang.the_call_was_completed
9090
+        }
9091
+        else if(confCall.accept.disposition != "") {
9092
+            msg += lang.the_call_was_not_completed +" ("+ confCall.accept.disposition +")"
9093
+        }
9094
+        callDetails.push({
9095
+            Message : msg,
9096
+            TimeStr : confCall.startTime
9097
+        });
9098
+    });
9099
+
9100
+    callDetails.sort(function(a, b){
9101
+        var aMo = moment.utc(a.TimeStr.replace(" UTC", ""));
9102
+        var bMo = moment.utc(b.TimeStr.replace(" UTC", ""));
9103
+        if (aMo.isSameOrAfter(bMo, "second")) {
9104
+            return -1;
9105
+        } else return 1;
9106
+        return 0;
9107
+    });
9108
+
9109
+    $.each(callDetails, function(item, detail){
9110
+        var Time = moment.utc(detail.TimeStr.replace(" UTC", "")).local().format(DisplayTimeFormat);
9111
+        var messageString = "<table class=timelineMessage cellspacing=0 cellpadding=0><tr>"
9112
+        messageString += "<td class=timelineMessageArea>"
9113
+        messageString += "<div class=timelineMessageDate><i class=\"fa fa-circle timelineMessageDot\"></i>"+ Time +"</div>"
9114
+        messageString += "<div class=timelineMessageText>"+ detail.Message +"</div>"
9115
+        messageString += "</td>"
9116
+        messageString += "</tr></table>";
9117
+        $("#line-"+ lineNum +"-CallDetails").prepend(messageString);
9118
+    });
9119
+}
9120
+
9121
+// Buddy & Contacts
9122
+// ================
9123
+var Buddy = function(type, identity, CallerIDName, ExtNo, MobileNumber, ContactNumber1, ContactNumber2, lastActivity, desc, Email){
9124
+    this.type = type; // extension | contact | group
9125
+    this.identity = identity;
9126
+    this.CallerIDName = CallerIDName;
9127
+    this.Email = Email;
9128
+    this.Desc = desc;
9129
+    this.ExtNo = ExtNo;
9130
+    this.MobileNumber = MobileNumber;
9131
+    this.ContactNumber1 = ContactNumber1;
9132
+    this.ContactNumber2 = ContactNumber2;
9133
+    this.lastActivity = lastActivity; // Full Date as string eg "1208-03-21 15:34:23 UTC"
9134
+    this.devState = "dotOffline";
9135
+    this.presence = "Unknown";
9136
+    this.missed = 0;
9137
+    this.IsSelected = false;
9138
+    this.imageObjectURL = "";
9139
+}
9140
+function InitUserBuddies(){
9141
+    var template = { TotalRows:0, DataCollection:[] }
9142
+    localDB.setItem(profileUserID + "-Buddies", JSON.stringify(template));
9143
+    return JSON.parse(localDB.getItem(profileUserID + "-Buddies"));
9144
+}
9145
+function MakeBuddy(type, update, focus, subscribe, callerID, did){
9146
+    var json = JSON.parse(localDB.getItem(profileUserID + "-Buddies"));
9147
+    if(json == null) json = InitUserBuddies();
9148
+
9149
+    var buddyObj = null;
9150
+    if(type == "contact"){
9151
+        var id = uID();
9152
+        var dateNow = utcDateNow();
9153
+        json.DataCollection.push({
9154
+            Type: "contact", 
9155
+            LastActivity: dateNow,
9156
+            ExtensionNumber: "", 
9157
+            MobileNumber: "",
9158
+            ContactNumber1: did,
9159
+            ContactNumber2: "",
9160
+            uID: null,
9161
+            cID: id,
9162
+            gID: null,
9163
+            DisplayName: callerID,
9164
+            Position: "",
9165
+            Description: "",
9166
+            Email: "",
9167
+            MemberCount: 0
9168
+        });
9169
+        buddyObj = new Buddy("contact", id, callerID, "", "", did, "", dateNow, "", "");
9170
+        AddBuddy(buddyObj, update, focus);
9171
+    }
9172
+    else {
9173
+        var id = uID();
9174
+        var dateNow = utcDateNow();
9175
+        json.DataCollection.push({
9176
+            Type: "extension",
9177
+            LastActivity: dateNow,
9178
+            ExtensionNumber: did,
9179
+            MobileNumber: "",
9180
+            ContactNumber1: "",
9181
+            ContactNumber2: "",
9182
+            uID: id,
9183
+            cID: null,
9184
+            gID: null,
9185
+            DisplayName: callerID,
9186
+            Position: "",
9187
+            Description: "", 
9188
+            Email: "",
9189
+            MemberCount: 0
9190
+        });
9191
+        buddyObj = new Buddy("extension", id, callerID, did, "", "", "", dateNow, "", "");
9192
+        AddBuddy(buddyObj, update, focus, subscribe);
9193
+    }
9194
+    // Update Size: 
9195
+    json.TotalRows = json.DataCollection.length;
9196
+
9197
+    // Save To DB
9198
+    localDB.setItem(profileUserID + "-Buddies", JSON.stringify(json));
9199
+
9200
+    // Return new buddy
9201
+    return buddyObj;
9202
+}
9203
+function UpdateBuddyCalerID(buddyObj, callerID){
9204
+    buddyObj.CallerIDName = callerID;
9205
+
9206
+    var buddy = buddyObj.identity;
9207
+    // Update DB
9208
+    var json = JSON.parse(localDB.getItem(profileUserID + "-Buddies"));
9209
+    if(json != null){
9210
+        $.each(json.DataCollection, function (i, item) {
9211
+            if(item.uID == buddy || item.cID == buddy || item.gID == buddy){
9212
+                item.DisplayName = callerID;
9213
+                return false;
9214
+            }
9215
+        });
9216
+        // Save To DB
9217
+        localDB.setItem(profileUserID + "-Buddies", JSON.stringify(json));
9218
+    }
9219
+
9220
+    UpdateBuddyList();
9221
+}
9222
+function AddBuddy(buddyObj, update, focus, subscribe){
9223
+    Buddies.push(buddyObj);
9224
+    if(update == true) UpdateBuddyList();
9225
+    AddBuddyMessageStream(buddyObj);
9226
+    if(subscribe == true) SubscribeBuddy(buddyObj);
9227
+    if(focus == true) SelectBuddy(buddyObj.identity);
9228
+}
9229
+function PopulateBuddyList() {
9230
+    console.log("Clearing Buddies...");
9231
+    Buddies = new Array();
9232
+    console.log("Adding Buddies...");
9233
+    var json = JSON.parse(localDB.getItem(profileUserID + "-Buddies"));
9234
+    if(json == null) return;
9235
+
9236
+    console.log("Total Buddies: " + json.TotalRows);
9237
+    $.each(json.DataCollection, function (i, item) {
9238
+        if(item.Type == "extension"){
9239
+            // extension
9240
+            var buddy = new Buddy("extension", item.uID, item.DisplayName, item.ExtensionNumber, item.MobileNumber, item.ContactNumber1, item.ContactNumber2, item.LastActivity, item.Position, item.Email);
9241
+            AddBuddy(buddy, false, false);
9242
+        }
9243
+        else if(item.Type == "contact"){
9244
+            // contact
9245
+            var buddy = new Buddy("contact", item.cID, item.DisplayName, "", item.MobileNumber, item.ContactNumber1, item.ContactNumber2, item.LastActivity, item.Description, item.Email);
9246
+            AddBuddy(buddy, false, false);
9247
+        }
9248
+        else if(item.Type == "group"){
9249
+            // group
9250
+            var buddy = new Buddy("group", item.gID, item.DisplayName, item.ExtensionNumber, "", "", "", item.LastActivity, item.MemberCount + " member(s)", item.Email);
9251
+            AddBuddy(buddy, false, false);
9252
+        }
9253
+    });
9254
+
9255
+    // Update List (after add)
9256
+    console.log("Updating Buddy List...");
9257
+    UpdateBuddyList();
9258
+}
9259
+function UpdateBuddyList(){
9260
+    var filter = $("#txtFindBuddy").val();
9261
+
9262
+    $("#myContacts").empty();
9263
+
9264
+    var callCount = 0
9265
+    for(var l = 0; l < Lines.length; l++) {
9266
+
9267
+        var classStr = (Lines[l].IsSelected)? "buddySelected" : "buddy";
9268
+        if(Lines[l].SipSession != null) classStr = (Lines[l].SipSession.local_hold)? "buddyActiveCallHollding" : "buddyActiveCall";
9269
+
9270
+        var html = "<div id=\"line-"+ Lines[l].LineNumber +"\" class="+ classStr +" onclick=\"SelectLine('"+ Lines[l].LineNumber +"')\">";
9271
+        html += "<div class=lineIcon>"+ (l + 1) +"</div>";
9272
+        html += "<div class=contactNameText><i class=\"fa fa-phone\"></i> "+ lang.line +" "+ (l + 1) +"</div>";
9273
+        html += "<div id=\"Line-"+ Lines[l].ExtNo +"-datetime\" class=contactDate>&nbsp;</div>";
9274
+        html += "<div class=presenceText>"+ Lines[l].DisplayName +" <"+ Lines[l].DisplayNumber +">" +"</div>";
9275
+        html += "</div>";
9276
+        // SIP.Session.C.STATUS_TERMINATED
9277
+        if(Lines[l].SipSession && Lines[l].SipSession.data.earlyReject != true){
9278
+            $("#myContacts").append(html);
9279
+            callCount ++;
9280
+        }
9281
+    }
9282
+
9283
+    // Sort and shuffle Buddy List
9284
+    // ===========================
9285
+    Buddies.sort(function(a, b){
9286
+        var aMo = moment.utc(a.lastActivity.replace(" UTC", ""));
9287
+        var bMo = moment.utc(b.lastActivity.replace(" UTC", ""));
9288
+        if (aMo.isSameOrAfter(bMo, "second")) {
9289
+            return -1;
9290
+        } else return 1;
9291
+        return 0;
9292
+    });
9293
+
9294
+
9295
+    for(var b = 0; b < Buddies.length; b++) {
9296
+        var buddyObj = Buddies[b];
9297
+
9298
+        if(filter && filter.length >= 1){
9299
+            // Perform Filter Display
9300
+            var display = false;
9301
+            if(buddyObj.CallerIDName.toLowerCase().indexOf(filter.toLowerCase()) > -1 ) display = true;
9302
+            if(buddyObj.ExtNo.toLowerCase().indexOf(filter.toLowerCase()) > -1 ) display = true;
9303
+            if(buddyObj.Desc.toLowerCase().indexOf(filter.toLowerCase()) > -1 ) display = true;
9304
+            if(!display) continue;
9305
+        }
9306
+
9307
+        var today = moment.utc();
9308
+        var lastActivity = moment.utc(buddyObj.lastActivity.replace(" UTC", ""));
9309
+        var displayDateTime = "";
9310
+        if(lastActivity.isSame(today, 'day'))
9311
+        {
9312
+            displayDateTime = lastActivity.local().format(DisplayTimeFormat);
9313
+        } 
9314
+        else {
9315
+            displayDateTime = lastActivity.local().format(DisplayDateFormat);
9316
+        }
9317
+
9318
+        var classStr = (buddyObj.IsSelected)? "buddySelected" : "buddy";
9319
+        if(buddyObj.type == "extension") {
9320
+            var friendlyState = buddyObj.presence;
9321
+            if (friendlyState == "Unknown") friendlyState = lang.state_unknown;
9322
+            if (friendlyState == "Not online") friendlyState = lang.state_not_online;
9323
+            if (friendlyState == "Ready") friendlyState = lang.state_ready;
9324
+            if (friendlyState == "On the phone") friendlyState = lang.state_on_the_phone;
9325
+            if (friendlyState == "Ringing") friendlyState = lang.state_ringing;
9326
+            if (friendlyState == "On hold") friendlyState = lang.state_on_hold;
9327
+            if (friendlyState == "Unavailable") friendlyState = lang.state_unavailable;
9328
+
9329
+            // An extension on the same system
9330
+            var html = "<div id=\"contact-"+ buddyObj.identity +"\" class="+ classStr +" onmouseenter=\"ShowBuddyDial(this, '"+ buddyObj.identity +"')\" onmouseleave=\"HideBuddyDial(this, '"+ buddyObj.identity +"')\" onclick=\"SelectBuddy('"+ buddyObj.identity +"', 'extension')\">";
9331
+            html += "<span id=\"contact-"+ buddyObj.identity +"-devstate\" class=\""+ buddyObj.devState +"\"></span>";
9332
+            if (getDbItem("useRoundcube", "") == 1 && buddyObj.Email != '' && buddyObj.Email != null && typeof buddyObj.Email != 'undefined') {
9333
+                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>";
9334
+            }
9335
+            if (EnableVideoCalling) {
9336
+                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>";
9337
+                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>";
9338
+            } else {
9339
+                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>";
9340
+            }
9341
+            if(buddyObj.missed && buddyObj.missed > 0){
9342
+                html += "<span id=\"contact-"+ buddyObj.identity +"-missed\" class=missedNotifyer>"+ buddyObj.missed +"</span>";
9343
+            }
9344
+            else{
9345
+                html += "<span id=\"contact-"+ buddyObj.identity +"-missed\" class=missedNotifyer style=\"display:none\">"+ buddyObj.missed +"</span>";
9346
+            }
9347
+            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>";
9348
+            html += "<div class=contactNameText><i class=\"fa fa-phone-square\"></i> "+ buddyObj.ExtNo +" - "+ buddyObj.CallerIDName +"</div>";
9349
+            html += "<div id=\"contact-"+ buddyObj.identity +"-datetime\" class=contactDate>"+ displayDateTime +"</div>";
9350
+            html += "<div id=\"contact-"+ buddyObj.identity +"-presence\" class=presenceText>"+ friendlyState +"</div>";
9351
+            html += "</div>";
9352
+            $("#myContacts").append(html);
9353
+        } else if(buddyObj.type == "contact") { 
9354
+            // An Addressbook Contact
9355
+            var html = "<div id=\"contact-"+ buddyObj.identity +"\" class="+ classStr +" onmouseenter=\"ShowBuddyDial(this, '"+ buddyObj.identity +"')\" onmouseleave=\"HideBuddyDial(this, '"+ buddyObj.identity +"')\" onclick=\"SelectBuddy('"+ buddyObj.identity +"', 'contact')\">";
9356
+            if (getDbItem("useRoundcube", "") == 1 && buddyObj.Email != '' && buddyObj.Email != null && typeof buddyObj.Email != 'undefined') {
9357
+                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>";
9358
+            }
9359
+            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>";
9360
+            if(buddyObj.missed && buddyObj.missed > 0){
9361
+                html += "<span id=\"contact-"+ buddyObj.identity +"-missed\" class=missedNotifyer>"+ buddyObj.missed +"</span>";
9362
+            }
9363
+            else{
9364
+                html += "<span id=\"contact-"+ buddyObj.identity +"-missed\" class=missedNotifyer style=\"display:none\">"+ buddyObj.missed +"</span>";
9365
+            }
9366
+            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>";
9367
+            html += "<div class=contactNameText><i class=\"fa fa-address-card\"></i> "+ buddyObj.CallerIDName +"</div>";
9368
+            html += "<div id=\"contact-"+ buddyObj.identity +"-datetime\" class=contactDate>"+ displayDateTime +"</div>";
9369
+            html += "<div class=presenceText>"+ buddyObj.Desc +"</div>";
9370
+            html += "</div>";
9371
+            $("#myContacts").append(html);
9372
+        } else if(buddyObj.type == "group"){ 
9373
+            // A collection of extensions and contacts
9374
+            var html = "<div id=\"contact-"+ buddyObj.identity +"\" class="+ classStr +" onmouseenter=\"ShowBuddyDial(this, '"+ buddyObj.identity +"')\" onmouseleave=\"HideBuddyDial(this, '"+ buddyObj.identity +"')\" onclick=\"SelectBuddy('"+ buddyObj.identity +"', 'group')\">";
9375
+            if (getDbItem("useRoundcube", "") == 1 && buddyObj.Email != '' && buddyObj.Email != null && typeof buddyObj.Email != 'undefined') {
9376
+                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>";
9377
+            }
9378
+            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>";
9379
+            if(buddyObj.missed && buddyObj.missed > 0){
9380
+                html += "<span id=\"contact-"+ buddyObj.identity +"-missed\" class=missedNotifyer>"+ buddyObj.missed +"</span>";
9381
+            }
9382
+            else{
9383
+                html += "<span id=\"contact-"+ buddyObj.identity +"-missed\" class=missedNotifyer style=\"display:none\">"+ buddyObj.missed +"</span>";
9384
+            }
9385
+            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>";
9386
+            html += "<div class=contactNameText><i class=\"fa fa-users\"></i> "+ buddyObj.CallerIDName +"</div>";
9387
+            html += "<div id=\"contact-"+ buddyObj.identity +"-datetime\" class=contactDate>"+ displayDateTime +"</div>";
9388
+            html += "<div class=presenceText>"+ buddyObj.Desc +"</div>";
9389
+            html += "</div>";
9390
+            $("#myContacts").append(html);
9391
+        }
9392
+    }
9393
+}
9394
+function AddBuddyMessageStream(buddyObj) {
9395
+    var html = "<table id=\"stream-"+ buddyObj.identity +"\" class=stream cellspacing=5 cellpadding=0>";
9396
+    html += "<tr><td class=streamSection style=\"height: 48px;\">";
9397
+
9398
+    // Close|Return|Back Button
9399
+    html += "<div style=\"float:left; margin:8.7px 0px 0px 8.7px; width: 38px; height:38px; line-height:38px;\">"
9400
+
9401
+    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> ";
9402
+    html += "</div>"
9403
+    
9404
+    // Profile UI
9405
+    html += "<div class=contact style=\"float: left; position: absolute; left: 47px; right: 190px;\" onclick=\"ShowBuddyProfileMenu('"+ buddyObj.identity +"', this, '"+ buddyObj.type +"')\">";
9406
+    if(buddyObj.type == "extension") {
9407
+        html += "<span id=\"contact-"+ buddyObj.identity +"-devstate-main\" class=\""+ buddyObj.devState +"\"></span>";
9408
+    }
9409
+    if(buddyObj.type == "extension") {
9410
+        html += "<div id=\"contact-"+ buddyObj.identity +"-picture-main\" class=buddyIcon style=\"background-image: url('"+ getPicture(buddyObj.identity) +"')\"></div>";
9411
+    }
9412
+    else if(buddyObj.type == "contact") {
9413
+        html += "<div class=buddyIcon style=\"background-image: url('"+ getPicture(buddyObj.identity,"contact") +"')\"></div>";
9414
+    }
9415
+    else if(buddyObj.type == "group") {
9416
+        html += "<div class=buddyIcon style=\"background-image: url('"+ getPicture(buddyObj.identity,"group") +"')\"></div>";
9417
+    }
9418
+    if(buddyObj.type == "extension") {
9419
+        html += "<div class=contactNameText style=\"margin-right: 0px;\"><i class=\"fa fa-phone-square\"></i> "+ buddyObj.ExtNo +" - "+ buddyObj.CallerIDName +"</div>";
9420
+    }
9421
+    else if(buddyObj.type == "contact") {
9422
+        html += "<div class=contactNameText style=\"margin-right: 0px;\"><i class=\"fa fa-address-card\"></i> "+ buddyObj.CallerIDName +"</div>";
9423
+    } 
9424
+    else if(buddyObj.type == "group") {
9425
+        html += "<div class=contactNameText style=\"margin-right: 0px;\"><i class=\"fa fa-users\"></i> "+ buddyObj.CallerIDName +"</div>";
9426
+    }
9427
+    if(buddyObj.type == "extension") {
9428
+        var friendlyState = buddyObj.presence;
9429
+        if (friendlyState == "Unknown") friendlyState = lang.state_unknown;
9430
+        if (friendlyState == "Not online") friendlyState = lang.state_not_online;
9431
+        if (friendlyState == "Ready") friendlyState = lang.state_ready;
9432
+        if (friendlyState == "On the phone") friendlyState = lang.state_on_the_phone;
9433
+        if (friendlyState == "Ringing") friendlyState = lang.state_ringing;
9434
+        if (friendlyState == "On hold") friendlyState = lang.state_on_hold;
9435
+        if (friendlyState == "Unavailable") friendlyState = lang.state_unavailable;
9436
+
9437
+        html += "<div id=\"contact-"+ buddyObj.identity +"-presence-main\" class=presenceText>"+ friendlyState +"</div>";
9438
+    } else{
9439
+        html += "<div id=\"contact-"+ buddyObj.identity +"-presence-main\" class=presenceText>"+ buddyObj.Desc +"</div>";
9440
+    }
9441
+    html += "</div>";
9442
+
9443
+    // Action Buttons
9444
+    html += "<div style=\"float:right; line-height:46px; margin:3.2px 5px 0px 0px;\">";
9445
+    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> ";
9446
+    if(buddyObj.type == "extension" && EnableVideoCalling) {
9447
+        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> ";
9448
+    }
9449
+    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> ";
9450
+    if(buddyObj.type == "extension") {
9451
+        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> ";
9452
+    }
9453
+    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> ";
9454
+    html += "</div>";
9455
+
9456
+    // Separator --------------------------------------------------------------------------
9457
+    html += "<div style=\"clear:both; height:0px\"></div>"
9458
+
9459
+    // Calling UI --------------------------------------------------------------------------
9460
+    html += "<div id=\"contact-"+ buddyObj.identity +"-calling\">";
9461
+
9462
+    // Gneral Messages
9463
+    html += "<div id=\"contact-"+ buddyObj.identity +"-timer\" style=\"float: right; margin-top: 4px; margin-right: 10px; color: #575757; display:none;\"></div>";
9464
+    html += "<div id=\"contact-"+ buddyObj.identity +"-msg\" class=callStatus style=\"display:none\">...</div>";
9465
+
9466
+    // Call Answer UI
9467
+    html += "<div id=\"contact-"+ buddyObj.identity +"-AnswerCall\" class=answerCall style=\"display:none\">";
9468
+    html += "<div>";
9469
+    html += "<button onclick=\"AnswerAudioCall('"+ buddyObj.identity +"')\" class=answerButton><i class=\"fa fa-phone\"></i>&nbsp;&nbsp;"+ lang.answer_call +"</button> ";
9470
+    if(buddyObj.type == "extension" && EnableVideoCalling) {
9471
+        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> ";
9472
+    }
9473
+    html += "<button onclick=\"RejectCall('"+ buddyObj.identity +"')\" class=hangupButton><i class=\"fa fa-phone\"></i>&nbsp;&nbsp;"+ lang.reject_call +"</button> ";
9474
+    html += "</div>";
9475
+    html += "</div>";
9476
+
9477
+    html += "</div>";
9478
+
9479
+    // Search & Related Elements
9480
+    html += "<div id=\"contact-"+ buddyObj.identity +"-search\" style=\"margin-top:6px; display:none\">";
9481
+    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>";
9482
+
9483
+    html += "</div>";
9484
+
9485
+    html += "</td></tr>";
9486
+    html += "<tr><td class=\"streamSection streamSectionBackground\">";
9487
+
9488
+    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 +"')\">";
9489
+    // Previous Chat messages
9490
+    html += "</div>";
9491
+
9492
+    html += "</td></tr>";
9493
+
9494
+    if ((buddyObj.type == "extension" || buddyObj.type == "group") && EnableTextMessaging) {
9495
+
9496
+        html += "<tr><td  id=sendChatMessageSection class=streamSection style=\"height:110px\">";
9497
+
9498
+        // Send Paste Image
9499
+        html += "<div id=\"contact-"+ buddyObj.identity +"-imagePastePreview\" class=sendImagePreview style=\"display:none\" tabindex=0></div>";
9500
+
9501
+        // Send File
9502
+        html += "<div id=\"contact-"+ buddyObj.identity +"-fileShare\" style=\"display:none\">";
9503
+        html += "<input type=file multiple onchange=\"console.log(this)\" />";
9504
+        html += "</div>";
9505
+
9506
+        // Send Audio Recording
9507
+        html += "<div id=\"contact-"+ buddyObj.identity +"-audio-recording\" style=\"display:none\"></div>";
9508
+
9509
+        // Send Video Recording
9510
+        html += "<div id=\"contact-"+ buddyObj.identity +"-video-recording\" style=\"display:none\"></div>";
9511
+
9512
+        // Dictate Message
9513
+        // html += "<div id=\"contact-"+ buddyObj.identity +"-dictate-message\" style=\"display:none\"></div>";
9514
+
9515
+        // Emoji Menu Bar
9516
+        html += "<div id=\"contact-"+ buddyObj.identity +"-emoji-menu\" style=\"display:none\" class=\"EmojiMenu\"></div>";
9517
+
9518
+        // =====================================
9519
+        // Type Area
9520
+        html += "<table class=sendMessageContainer cellpadding=0 cellspacing=0><tr>";
9521
+        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>";
9522
+        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>";
9523
+        html += "<button onclick=\"ShowEmojiBar('"+ buddyObj.identity +"')\" class=roundButtonsSpec title=\""+ lang.select_expression + "\"><i class=\"fa fa-smile-o\"></i></button>";
9524
+        html += "<button onclick=\"SendFile('"+ buddyObj.identity +"')\" class=roundButtonsSpec title=\""+ lang.send_file + "\"><i class=\"fa fa-file-text-o\"></i></button></td>";
9525
+        html += "</tr></table>";
9526
+        html += "</td></tr>";
9527
+    }
9528
+
9529
+    html += "</table>";
9530
+
9531
+    $("#rightContent").append(html);
9532
+}
9533
+function RemoveBuddyMessageStream(buddyObj){
9534
+    CloseBuddy(buddyObj.identity);
9535
+
9536
+    UpdateBuddyList();
9537
+
9538
+    // Remove Stream
9539
+    $("#stream-"+ buddyObj.identity).remove();
9540
+    var stream = JSON.parse(localDB.getItem(buddyObj.identity + "-stream"));
9541
+    localDB.removeItem(buddyObj.identity + "-stream");
9542
+
9543
+    // Remove Buddy
9544
+    var json = JSON.parse(localDB.getItem(profileUserID + "-Buddies"));
9545
+    var x = 0;
9546
+    $.each(json.DataCollection, function (i, item) {
9547
+        if(item.uID == buddyObj.identity || item.cID == buddyObj.identity || item.gID == buddyObj.identity){
9548
+            x = i;
9549
+            return false;
9550
+        }
9551
+    });
9552
+    json.DataCollection.splice(x,1);
9553
+    json.TotalRows = json.DataCollection.length;
9554
+    localDB.setItem(profileUserID + "-Buddies", JSON.stringify(json));
9555
+
9556
+    // Remove Images
9557
+    localDB.removeItem("img-"+ buddyObj.identity +"-extension");
9558
+    localDB.removeItem("img-"+ buddyObj.identity +"-contact");
9559
+    localDB.removeItem("img-"+ buddyObj.identity +"-group");
9560
+
9561
+    // Remove Call Recordings
9562
+    if(stream && stream.DataCollection && stream.DataCollection.length >= 1){
9563
+        DeleteCallRecordings(buddyObj.identity, stream);
9564
+    }
9565
+    
9566
+    // Remove QOS Data
9567
+    DeleteQosData(buddyObj.identity);
9568
+}
9569
+function DeleteCallRecordings(buddy, stream){
9570
+    var indexedDB = window.indexedDB;
9571
+    var request = indexedDB.open("CallRecordings");
9572
+    request.onerror = function(event) {
9573
+        console.error("IndexDB Request Error:", event);
9574
+    }
9575
+    request.onupgradeneeded = function(event) {
9576
+        console.warn("Upgrade Required for IndexDB... probably because of first time use.");
9577
+        // If this is the case, there will be no call recordings
9578
+    }
9579
+    request.onsuccess = function(event) {
9580
+        console.log("IndexDB connected to CallRecordings");
9581
+
9582
+        var IDB = event.target.result;
9583
+        if(IDB.objectStoreNames.contains("Recordings") == false){
9584
+            console.warn("IndexDB CallRecordings.Recordings does not exists");
9585
+            return;
9586
+        }
9587
+        IDB.onerror = function(event) {
9588
+            console.error("IndexDB Error:", event);
9589
+        }
9590
+
9591
+        // Loop and Delete
9592
+        $.each(stream.DataCollection, function (i, item) {
9593
+            if (item.Recordings && item.Recordings.length) {
9594
+                $.each(item.Recordings, function (i, recording) {
9595
+                    console.log("Deleting Call Recording: ", recording.uID);
9596
+                    var objectStore = IDB.transaction(["Recordings"], "readwrite").objectStore("Recordings");
9597
+                    try{
9598
+                        var deleteRequest = objectStore.delete(recording.uID);
9599
+                        deleteRequest.onsuccess = function(event) {
9600
+                            console.log("Call Recording Deleted: ", recording.uID);
9601
+                        }
9602
+                    } catch(e){
9603
+                        console.log("Call Recording Delete failed: ", e);
9604
+                    }
9605
+                });
9606
+            }
9607
+        });
9608
+    }
9609
+}
9610
+
9611
+function MakeUpName(){
9612
+    var shortname = 4;
9613
+    var longName = 12;
9614
+    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"];
9615
+    var rtn = "";
9616
+    rtn += letters[Math.floor(Math.random() * letters.length)];
9617
+    for(var n=0; n<Math.floor(Math.random() * longName) + shortname; n++){
9618
+        rtn += letters[Math.floor(Math.random() * letters.length)].toLowerCase();
9619
+    }
9620
+    rtn += " ";
9621
+    rtn += letters[Math.floor(Math.random() * letters.length)];
9622
+    for(var n=0; n<Math.floor(Math.random() * longName) + shortname; n++){
9623
+        rtn += letters[Math.floor(Math.random() * letters.length)].toLowerCase();
9624
+    }
9625
+    return rtn;
9626
+}
9627
+function MakeUpNumber(){
9628
+    var numbers = ["0","1","2","3","4","5","6","7","8","9","0"];
9629
+    var rtn = "0";
9630
+    for(var n=0; n<9; n++){
9631
+        rtn += numbers[Math.floor(Math.random() * numbers.length)];
9632
+    }
9633
+    return rtn;
9634
+}
9635
+function MakeUpBuddies(int){
9636
+    for(var i=0; i<int; i++){
9637
+        var buddyObj = new Buddy("contact", uID(), MakeUpName(), "", "", MakeUpNumber(), "", utcDateNow(), "Testing", "");
9638
+        AddBuddy(buddyObj, false, false);
9639
+    }
9640
+    UpdateBuddyList();
9641
+}
9642
+
9643
+function SelectBuddy(buddy) {
9644
+
9645
+    $("#roundcubeFrame").remove();
9646
+    $(".streamSelected").each(function() { $(this).show(); });
9647
+
9648
+    var buddyObj = FindBuddyByIdentity(buddy);
9649
+    if(buddyObj == null) return;
9650
+
9651
+    for(var b = 0; b < Buddies.length; b++) {
9652
+        if(Buddies[b].IsSelected == true && Buddies[b].identity == buddy){
9653
+            // Nothing to do, you re-selected the same buddy;
9654
+            return;
9655
+        }
9656
+    }
9657
+
9658
+    console.log("Selecting Buddy: "+ buddy);
9659
+
9660
+    selectedBuddy = buddyObj;
9661
+
9662
+    // Can only display one thing on the right
9663
+    $(".streamSelected").each(function () {
9664
+        $(this).prop('class', 'stream');
9665
+    });
9666
+    $("#stream-" + buddy).prop('class', 'streamSelected');
9667
+
9668
+    // Update Lines List
9669
+    for(var l = 0; l < Lines.length; l++) {
9670
+        var classStr = "buddy";
9671
+        if(Lines[l].SipSession != null) classStr = (Lines[l].SipSession.local_hold)? "buddyActiveCallHollding" : "buddyActiveCall";
9672
+        $("#line-" + Lines[l].LineNumber).prop('class', classStr);
9673
+        Lines[l].IsSelected = false;
9674
+    }
9675
+
9676
+    ClearMissedBadge(buddy);
9677
+    // Update Buddy List
9678
+    for(var b = 0; b < Buddies.length; b++) {
9679
+        var classStr = (Buddies[b].identity == buddy)? "buddySelected" : "buddy";
9680
+        $("#contact-" + Buddies[b].identity).prop('class', classStr);
9681
+
9682
+        $("#contact-"+ Buddies[b].identity +"-ChatHistory").empty();
9683
+
9684
+        Buddies[b].IsSelected = (Buddies[b].identity == buddy);
9685
+    }
9686
+
9687
+    // Change to Stream if in Narrow view
9688
+    UpdateUI();
9689
+    
9690
+    // Refresh Stream
9691
+    RefreshStream(buddyObj);
9692
+
9693
+    try{
9694
+        $("#contact-" + buddy).get(0).scrollIntoViewIfNeeded();
9695
+    } catch(e){}
9696
+
9697
+    // Save Selected
9698
+    localDB.setItem("SelectedBuddy", buddy);
9699
+}
9700
+function CloseBuddy(buddy){
9701
+    // Lines and Buddies (Left)
9702
+    $(".buddySelected").each(function () {
9703
+        $(this).prop('class', 'buddy');
9704
+    });
9705
+    // Streams (Right)
9706
+    $(".streamSelected").each(function () {
9707
+        $(this).prop('class', 'stream');
9708
+    });
9709
+
9710
+    console.log("Closing Buddy: "+ buddy);
9711
+    for(var b = 0; b < Buddies.length; b++){
9712
+        Buddies[b].IsSelected = false;
9713
+    }
9714
+    selectedBuddy = null;
9715
+    for(var l = 0; l < Lines.length; l++){
9716
+        Lines[l].IsSelected = false;
9717
+    }
9718
+    selectedLine = null;
9719
+
9720
+    // Save Selected
9721
+    localDB.setItem("SelectedBuddy", null);
9722
+
9723
+    // Change to Stream if in Narrow view
9724
+    UpdateUI();
9725
+}
9726
+function DownloadChatText(buddy) {
9727
+
9728
+    var buddyInfo = FindBuddyByIdentity(buddy);
9729
+    var DispNamePre = buddyInfo.CallerIDName;
9730
+    var DispName = DispNamePre.replace(" ", "_");
9731
+    var buddyExt = buddyInfo.ExtNo;
9732
+    var presDate = moment().format("YYYY-MM-DD_HH-mm-ss");
9733
+
9734
+    var wholeChatTextTitle = "\n" + "Roundpin Chat With " + DispNamePre + " (extension " + buddyExt + "), saved on " + moment().format("YYYY-MM-DD HH:mm:ss") + "\n\n\n\n";
9735
+    var wholeChatText = "";
9736
+
9737
+    $("#contact-"+buddy+"-ChatHistory .chatMessageTable").each(function() {
9738
+       if ($(this).hasClass("theirChatMessage")) {
9739
+           wholeChatText += "\n" + DispNamePre + "\n" + $(this).text() + "\n\n";
9740
+       } else {
9741
+           wholeChatText += "\n" + "Me" + "\n" + $(this).text() + "\n\n";
9742
+       }
9743
+    });
9744
+
9745
+    if (wholeChatText == "") { alert("There is no chat text to save ! "); return; }
9746
+    var wholeChatTextConc = wholeChatTextTitle + wholeChatText;
9747
+    var downFilename = 'Roundpin_Chat-' + DispName + "_" + presDate;
9748
+    var downlink = document.createElement('a');
9749
+    var mimeType = 'text/plain';
9750
+
9751
+    downlink.setAttribute('download', downFilename);
9752
+    downlink.setAttribute('href', 'data:' + mimeType + ';charset=utf-8,' + encodeURIComponent(wholeChatTextConc));
9753
+    downlink.click(); 
9754
+}
9755
+function RemoveBuddy(buddy){
9756
+
9757
+    var buddyData = FindBuddyByIdentity(buddy);
9758
+    var buddyDisplayName = buddyData.CallerIDName;
9759
+
9760
+    // Check if you are on the phone, etc.
9761
+    Confirm(lang.confirm_remove_buddy, lang.remove_buddy, function(){
9762
+        for(var b = 0; b < Buddies.length; b++) {
9763
+            if(Buddies[b].identity == buddy) {
9764
+                RemoveBuddyMessageStream(Buddies[b]);
9765
+                UnsubscribeBuddy(Buddies[b])
9766
+                Buddies.splice(b, 1);
9767
+                break;
9768
+            }
9769
+        }
9770
+        // Remove contact from SQL database
9771
+        deleteBuddyFromSqldb(buddyDisplayName);
9772
+
9773
+        UpdateBuddyList();
9774
+    });
9775
+}
9776
+function FindBuddyByDid(did){
9777
+    // Used only in Inboud
9778
+    for(var b = 0; b < Buddies.length; b++){
9779
+        if(Buddies[b].ExtNo == did || Buddies[b].MobileNumber == did || Buddies[b].ContactNumber1 == did || Buddies[b].ContactNumber2 == did) {
9780
+            return Buddies[b];
9781
+        }
9782
+    }
9783
+    return null;
9784
+}
9785
+function FindBuddyByExtNo(ExtNo){
9786
+    for(var b = 0; b < Buddies.length; b++){
9787
+        if(Buddies[b].type == "extension" && Buddies[b].ExtNo == ExtNo) return Buddies[b];
9788
+    }
9789
+    return null;
9790
+}
9791
+function FindBuddyByNumber(number){
9792
+    // Number could be: +XXXXXXXXXX
9793
+    // Any special characters must be removed prior to adding
9794
+    for(var b = 0; b < Buddies.length; b++){
9795
+        if(Buddies[b].MobileNumber == number || Buddies[b].ContactNumber1 == number || Buddies[b].ContactNumber2 == number) {
9796
+            return Buddies[b];
9797
+        }
9798
+    }
9799
+    return null;
9800
+}
9801
+function FindBuddyByIdentity(identity){
9802
+    for(var b = 0; b < Buddies.length; b++){
9803
+        if(Buddies[b].identity == identity) return Buddies[b];
9804
+    }
9805
+    return null;
9806
+}
9807
+function SearchStream(obj, buddy){
9808
+    var q = obj.value;
9809
+
9810
+    var buddyObj = FindBuddyByIdentity(buddy);
9811
+    if(q == ""){
9812
+        console.log("Restore Stream");
9813
+        RefreshStream(buddyObj);
9814
+    }
9815
+    else{
9816
+        RefreshStream(buddyObj, q);
9817
+    }
9818
+}
9819
+function RefreshStream(buddyObj, filter) {
9820
+    $("#contact-" + buddyObj.identity + "-ChatHistory").empty();
9821
+
9822
+    var json = JSON.parse(localDB.getItem(buddyObj.identity +"-stream"));
9823
+    if(json == null || json.DataCollection == null) return;
9824
+
9825
+    // Sort DataCollection (Newest items first)
9826
+    json.DataCollection.sort(function(a, b){
9827
+        var aMo = moment.utc(a.ItemDate.replace(" UTC", ""));
9828
+        var bMo = moment.utc(b.ItemDate.replace(" UTC", ""));
9829
+        if (aMo.isSameOrAfter(bMo, "second")) {
9830
+            return -1;
9831
+        } else return 1;
9832
+        return 0;
9833
+    });
9834
+
9835
+    // Filter
9836
+    if(filter && filter != ""){
9837
+
9838
+        console.log("Rows without filter ("+ filter +"): ", json.DataCollection.length);
9839
+        json.DataCollection = json.DataCollection.filter(function(item){
9840
+            if(filter.indexOf("date: ") != -1){
9841
+                // Apply Date Filter
9842
+                var dateFilter = getFilter(filter, "date");
9843
+                if(dateFilter != "" && item.ItemDate.indexOf(dateFilter) != -1) return true;
9844
+            }
9845
+            if(item.MessageData && item.MessageData.length > 1){
9846
+                if(item.MessageData.toLowerCase().indexOf(filter.toLowerCase()) != -1) return true;
9847
+                if(filter.toLowerCase().indexOf(item.MessageData.toLowerCase()) != -1) return true;
9848
+            }
9849
+            if (item.ItemType == "MSG") {
9850
+                // Special search
9851
+            } 
9852
+            else if (item.ItemType == "CDR") {
9853
+                // Tag search
9854
+                if(item.Tags && item.Tags.length > 1){
9855
+                    var tagFilter = getFilter(filter, "tag");
9856
+                    if(tagFilter != "") {
9857
+                        if(item.Tags.some(function(i){
9858
+                            if(tagFilter.toLowerCase().indexOf(i.value.toLowerCase()) != -1) return true;
9859
+                            if(i.value.toLowerCase().indexOf(tagFilter.toLowerCase()) != -1) return true;
9860
+                            return false;
9861
+                        }) == true) return true;
9862
+                    }
9863
+                }
9864
+            }
9865
+            else if(item.ItemType == "FILE"){
9866
+
9867
+            } 
9868
+            else if(item.ItemType == "SMS"){
9869
+                 // Not yet implemented
9870
+            }
9871
+            // return true to keep;
9872
+            return false;
9873
+        });
9874
+        console.log("Rows After Filter: ", json.DataCollection.length);
9875
+    }
9876
+
9877
+    // Create Buffer
9878
+    if(json.DataCollection.length > StreamBuffer){
9879
+        console.log("Rows:", json.DataCollection.length, " (will be trimed to "+ StreamBuffer +")");
9880
+        // Always limit the Stream to {StreamBuffer}, users must search for messages further back
9881
+        json.DataCollection.splice(StreamBuffer);
9882
+    }
9883
+
9884
+    $.each(json.DataCollection, function (i, item) {
9885
+
9886
+        var IsToday = moment.utc(item.ItemDate.replace(" UTC", "")).isSame(moment.utc(), "day");
9887
+        var DateTime = "  " + moment.utc(item.ItemDate.replace(" UTC", "")).local().calendar(null, { sameElse: DisplayDateFormat });
9888
+        if(IsToday) DateTime = "  " + moment.utc(item.ItemDate.replace(" UTC", "")).local().format(DisplayTimeFormat);
9889
+
9890
+        if (item.ItemType == "MSG") {
9891
+            // Add Chat Message
9892
+            // ===================
9893
+            var deliveryStatus = "<i class=\"fa fa-question-circle-o SendingMessage\"></i>";
9894
+            if(item.Sent == true) deliveryStatus = "<i class=\"fa fa-check SentMessage\"></i>";
9895
+            if(item.Sent == false) deliveryStatus = "<i class=\"fa fa-exclamation-circle FailedMessage\"></i>";
9896
+            if(item.Delivered) deliveryStatus += "<i class=\"fa fa-check DeliveredMessage\"></i>";
9897
+
9898
+            var formattedMessage = ReformatMessage(item.MessageData);
9899
+            var longMessage = (formattedMessage.length > 1000);
9900
+
9901
+            if (item.SrcUserId == profileUserID) {
9902
+                // You are the source (sending)
9903
+                if (formattedMessage.length != 0) {
9904
+                    var messageString = "<table class=\"ourChatMessage chatMessageTable\" cellspacing=0 cellpadding=0><tr>";
9905
+                    messageString += "<td class=ourChatMessageText onmouseenter=\"ShowChatMenu(this)\" onmouseleave=\"HideChatMenu(this)\">";
9906
+                    messageString += "<span onclick=\"ShowMessgeMenu(this,'MSG','"+  item.ItemId +"', '"+ buddyObj.identity +"')\" class=chatMessageDropdown style=\"display:none\"><i class=\"fa fa-chevron-down\"></i></span>";
9907
+                    messageString += "<div id=msg-text-"+ item.ItemId +" class=messageText style=\""+ ((longMessage)? "max-height:190px; overflow:hidden" : "") +"\">" + formattedMessage + "</div>";
9908
+                    if(longMessage){
9909
+                       messageString += "<div id=msg-readmore-"+  item.ItemId +" class=messageReadMore><span onclick=\"ExpandMessage(this,'"+ item.ItemId +"', '"+ buddyObj.identity +"')\">"+ lang.read_more +"</span></div>";
9910
+                    }
9911
+
9912
+                    messageString += "<div class=messageDate>" + DateTime + " " + deliveryStatus +"</div>";
9913
+                    messageString += "</td>";
9914
+                    messageString += "</tr></table>";
9915
+                }
9916
+            } 
9917
+            else {
9918
+                // You are the destination (receiving)
9919
+                var ActualSender = "";
9920
+                if (formattedMessage.length != 0) {
9921
+                    var messageString = "<table class=\"theirChatMessage chatMessageTable\" cellspacing=0 cellpadding=0><tr>";
9922
+                    messageString += "<td class=theirChatMessageText onmouseenter=\"ShowChatMenu(this)\" onmouseleave=\"HideChatMenu(this)\">";
9923
+                    messageString += "<span onclick=\"ShowMessgeMenu(this,'MSG','"+  item.ItemId +"', '"+ buddyObj.identity +"')\" class=chatMessageDropdown style=\"display:none\"><i class=\"fa fa-chevron-down\"></i></span>";
9924
+
9925
+                    if(buddyObj.type == "group"){
9926
+                       messageString += "<div class=messageDate>" + ActualSender + "</div>";
9927
+                    }
9928
+                    messageString += "<div id=msg-text-"+ item.ItemId +" class=messageText style=\""+ ((longMessage)? "max-height:190px; overflow:hidden" : "") +"\">" + formattedMessage + "</div>";
9929
+                    if(longMessage){
9930
+                       messageString += "<div id=msg-readmore-"+  item.ItemId +" class=messageReadMore><span onclick=\"ExpandMessage(this,'"+ item.ItemId +"', '"+ buddyObj.identity +"')\">"+ lang.read_more +"</span></div>";
9931
+                    }
9932
+                    messageString += "<div class=messageDate>"+ DateTime + "</div>";
9933
+                    messageString += "</td>";
9934
+                    messageString += "</tr></table>";
9935
+                }
9936
+            }
9937
+            if (formattedMessage.length != 0) {
9938
+                $("#contact-" + buddyObj.identity + "-ChatHistory").prepend(messageString);
9939
+            }
9940
+        } 
9941
+        else if (item.ItemType == "CDR") {
9942
+            // Add CDR 
9943
+            // =======
9944
+            var iconColor = (item.Billsec > 0)? "green" : "red";
9945
+            var formattedMessage = "";
9946
+
9947
+            // Flagged
9948
+            var flag = "<span id=cdr-flagged-"+  item.CdrId +" style=\""+ ((item.Flagged)? "" : "display:none") +"\">";
9949
+            flag += "<i class=\"fa fa-flag FlagCall\"></i> ";
9950
+            flag += "</span>";
9951
+
9952
+            // Comment
9953
+            var callComment = "";
9954
+            if(item.MessageData) callComment = item.MessageData;
9955
+
9956
+            // Tags
9957
+            if(!item.Tags) item.Tags = [];
9958
+            var CallTags = "<ul id=cdr-tags-"+  item.CdrId +" class=tags style=\""+ ((item.Tags && item.Tags.length > 0)? "" : "display:none" ) +"\">"
9959
+            $.each(item.Tags, function (i, tag) {
9960
+                CallTags += "<li onclick=\"TagClick(this, '"+ item.CdrId +"', '"+ buddyObj.identity +"')\">"+ tag.value +"</li>";
9961
+            });
9962
+            CallTags += "<li class=tagText><input maxlength=24 type=text onkeypress=\"TagKeyPress(event, this, '"+ item.CdrId +"', '"+ buddyObj.identity +"')\" onfocus=\"TagFocus(this)\"></li>";
9963
+            CallTags += "</ul>";
9964
+
9965
+            // Call Type
9966
+            var callIcon = (item.WithVideo)? "fa-video-camera" :  "fa-phone";
9967
+            formattedMessage += "<i class=\"fa "+ callIcon +"\" style=\"color:"+ iconColor +"\"></i>";
9968
+            var audioVideo = (item.WithVideo)? lang.a_video_call :  lang.an_audio_call;
9969
+
9970
+            // Recordings
9971
+            var recordingsHtml = "";
9972
+            if(item.Recordings && item.Recordings.length >= 1){
9973
+                $.each(item.Recordings, function (i, recording) {
9974
+                    if(recording.uID){
9975
+                        var StartTime = moment.utc(recording.startTime.replace(" UTC", "")).local();
9976
+                        var StopTime = moment.utc(recording.stopTime.replace(" UTC", "")).local();
9977
+                        var recordingDuration = moment.duration(StopTime.diff(StartTime));
9978
+                        recordingsHtml += "<div class=callRecording>";
9979
+                        if(item.WithVideo){
9980
+                            if(recording.Poster){
9981
+                                var posterWidth = recording.Poster.width;
9982
+                                var posterHeight = recording.Poster.height;
9983
+                                var posterImage = recording.Poster.posterBase64;
9984
+                                recordingsHtml += "<div><IMG src=\""+ posterImage +"\"><button onclick=\"PlayVideoCallRecording(this, '"+ item.CdrId +"', '"+ recording.uID +"')\" class=videoPoster><i class=\"fa fa-play\"></i></button></div>";
9985
+                            }
9986
+                            else {
9987
+                                recordingsHtml += "<div><button onclick=\"PlayVideoCallRecording(this, '"+ item.CdrId +"', '"+ recording.uID +"', '"+ buddyObj.identity +"')\"><i class=\"fa fa-video-camera\"></i></button></div>";
9988
+                            }
9989
+                        } 
9990
+                        else {
9991
+                            recordingsHtml += "<div><button onclick=\"PlayAudioCallRecording(this, '"+ item.CdrId +"', '"+ recording.uID +"', '"+ buddyObj.identity +"')\"><i class=\"fa fa-play\"></i></button></div>";
9992
+                        } 
9993
+                        recordingsHtml += "<div>"+ lang.started +": "+ StartTime.format(DisplayTimeFormat) +" <i class=\"fa fa-long-arrow-right\"></i> "+ lang.stopped +": "+ StopTime.format(DisplayTimeFormat) +"</div>";
9994
+                        recordingsHtml += "<div>"+ lang.recording_duration +": "+ formatShortDuration(recordingDuration.asSeconds()) +"</div>";
9995
+                        recordingsHtml += "<div>";
9996
+                        recordingsHtml += "<span id=\"cdr-video-meta-width-"+ item.CdrId +"-"+ recording.uID +"\"></span>";
9997
+                        recordingsHtml += "<span id=\"cdr-video-meta-height-"+ item.CdrId +"-"+ recording.uID +"\"></span>";
9998
+                        recordingsHtml += "<span id=\"cdr-media-meta-size-"+ item.CdrId +"-"+ recording.uID +"\"></span>";
9999
+                        recordingsHtml += "<span id=\"cdr-media-meta-codec-"+ item.CdrId +"-"+ recording.uID +"\"></span>";
10000
+                        recordingsHtml += "</div>";
10001
+                        recordingsHtml += "</div>";
10002
+                    }
10003
+                });
10004
+            }
10005
+
10006
+            if (item.SrcUserId == profileUserID) {
10007
+                // (Outbound) You(profileUserID) initiated a call
10008
+                if(item.Billsec == "0") {
10009
+                    formattedMessage += " "+ lang.you_tried_to_make +" "+ audioVideo +" ("+ item.ReasonText +").";
10010
+                } 
10011
+                else {
10012
+                    formattedMessage += " "+ lang.you_made + " "+ audioVideo +", "+ lang.and_spoke_for +" " + formatDuration(item.Billsec) + ".";
10013
+                }
10014
+                var messageString = "<table class=\"ourChatMessage chatMessageTable\" cellspacing=0 cellpadding=0><tr>"
10015
+                messageString += "<td style=\"padding-right:4px;\">" + flag + "</td>"
10016
+                messageString += "<td class=ourChatMessageText onmouseenter=\"ShowChatMenu(this)\" onmouseleave=\"HideChatMenu(this)\">";
10017
+                messageString += "<span onClick=\"ShowMessgeMenu(this,'CDR','"+  item.CdrId +"', '"+ buddyObj.identity +"')\" class=chatMessageDropdown style=\"display:none\"><i class=\"fa fa-chevron-down\"></i></span>";
10018
+                messageString += "<div>" + formattedMessage + "</div>";
10019
+                messageString += "<div>" + CallTags + "</div>";
10020
+                messageString += "<div id=cdr-comment-"+  item.CdrId +" class=cdrComment>" + callComment + "</div>";
10021
+                messageString += "<div class=callRecordings>" + recordingsHtml + "</div>";
10022
+                messageString += "<div class=messageDate>" + DateTime  + "</div>";
10023
+                messageString += "</td>"
10024
+                messageString += "</tr></table>";
10025
+            } 
10026
+            else {
10027
+                // (Inbound) you(profileUserID) received a call
10028
+                if(item.Billsec == "0"){
10029
+                    formattedMessage += " "+ lang.you_missed_a_call + " ("+ item.ReasonText +").";
10030
+                } 
10031
+                else {
10032
+                    formattedMessage += " "+ lang.you_recieved + " "+ audioVideo +", "+ lang.and_spoke_for +" " + formatDuration(item.Billsec) + ".";
10033
+                }
10034
+
10035
+                var messageString = "<table class=\"theirChatMessage chatMessageTable\" cellspacing=0 cellpadding=0><tr>";
10036
+                messageString += "<td class=theirChatMessageText onmouseenter=\"ShowChatMenu(this)\" onmouseleave=\"HideChatMenu(this)\">";
10037
+                messageString += "<span onClick=\"ShowMessgeMenu(this,'CDR','"+  item.CdrId +"', '"+ buddyObj.identity +"')\" class=chatMessageDropdown style=\"display:none\"><i class=\"fa fa-chevron-down\"></i></span>";
10038
+                messageString += "<div style=\"text-align:left\">" + formattedMessage + "</div>";
10039
+                messageString += "<div>" + CallTags + "</div>";
10040
+                messageString += "<div id=cdr-comment-"+  item.CdrId +" class=cdrComment>" + callComment + "</div>";
10041
+                messageString += "<div class=callRecordings>" + recordingsHtml + "</div>";
10042
+                messageString += "<div class=messageDate> " + DateTime + "</div>";
10043
+                messageString += "</td>";
10044
+                messageString += "<td style=\"padding-left:4px\">" + flag + "</td>";
10045
+                messageString += "</tr></table>";
10046
+            }
10047
+            // Messges are reappended here, and appended when logging
10048
+            $("#contact-" + buddyObj.identity + "-ChatHistory").prepend(messageString);
10049
+        } 
10050
+        else if (item.ItemType == "FILE") {
10051
+
10052
+            if (item.SrcUserId == profileUserID) {
10053
+                // File is sent
10054
+                var sentFileSection = "<table class=\"ourChatMessage chatMessageTable\" cellspacing=0 cellpadding=0><tr>"
10055
+                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>";
10056
+                sentFileSection += "<span style=\"display:block;width:100%;height:10px;\"></span><div class=\"messageDate\">"+ DateTime + "</div></div>";
10057
+                sentFileSection += "</td>";
10058
+                sentFileSection += "</tr></table>";
10059
+
10060
+                $("#contact-" + buddyObj.identity + "-ChatHistory").prepend(sentFileSection);
10061
+                $("#sendFileLoader").remove();
10062
+
10063
+            } else {
10064
+                // File is received
10065
+                var recFileSection = "<table class=\"theirChatMessage chatMessageTable\" cellspacing=0 cellpadding=0><tr>"
10066
+                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>";
10067
+
10068
+                recFileSection += "<span style=\"display:block;width:100%;height:10px;\"></span><div class=\"messageDate\">"+ DateTime + "</div></div>";
10069
+                recFileSection += "</td>";
10070
+                recFileSection += "</tr></table>";
10071
+
10072
+                $("#contact-" + buddyObj.identity + "-ChatHistory").prepend(recFileSection);
10073
+            }
10074
+        } 
10075
+        else if(item.ItemType == "SMS"){
10076
+
10077
+        }
10078
+    });
10079
+
10080
+    // For some reason, the first time this fires, it doesn't always work
10081
+    updateScroll(buddyObj.identity);
10082
+    window.setTimeout(function(){
10083
+        updateScroll(buddyObj.identity);
10084
+    }, 300);
10085
+}
10086
+function ShowChatMenu(obj){
10087
+    $(obj).children("span").show();
10088
+}
10089
+function HideChatMenu(obj){
10090
+    $(obj).children("span").hide();
10091
+}
10092
+function ExpandMessage(obj, ItemId, buddy){
10093
+    $("#msg-text-" + ItemId).css("max-height", "");
10094
+    $("#msg-text-" + ItemId).css("overflow", "");
10095
+    $("#msg-readmore-" + ItemId).remove();
10096
+
10097
+    $.jeegoopopup.close();
10098
+}
10099
+function ShowBuddyDial(obj, buddy){
10100
+    $("#contact-"+ buddy +"-email").show();
10101
+    $("#contact-"+ buddy +"-audio-dial").show();
10102
+    $("#contact-"+ buddy +"-video-dial").show();
10103
+}
10104
+function HideBuddyDial(obj, buddy){
10105
+    $("#contact-"+ buddy +"-email").hide();
10106
+    $("#contact-"+ buddy +"-audio-dial").hide();
10107
+    $("#contact-"+ buddy +"-video-dial").hide();
10108
+}
10109
+function QuickDialAudio(buddy, obj, event){
10110
+    AudioCallMenu(buddy, obj);
10111
+    event.stopPropagation();
10112
+}
10113
+function QuickDialVideo(buddy, ExtNo, event){
10114
+    event.stopPropagation();
10115
+    window.setTimeout(function(){
10116
+        DialByLine('video', buddy, ExtNo);
10117
+    }, 300);
10118
+}
10119
+
10120
+// Sessions
10121
+// ========
10122
+function ExpandVideoArea(lineNum){
10123
+    $("#line-" + lineNum + "-ActiveCall").prop("class","FullScreenVideo");
10124
+    $("#line-" + lineNum + "-VideoCall").css("height", "calc(100% - 100px)");
10125
+    $("#line-" + lineNum + "-VideoCall").css("margin-top", "0px");
10126
+
10127
+    $("#line-" + lineNum + "-preview-container").prop("class","PreviewContainer PreviewContainer_FS");
10128
+    $("#line-" + lineNum + "-stage-container").prop("class","StageContainer StageContainer_FS");
10129
+
10130
+    $("#line-" + lineNum + "-restore").show();
10131
+    $("#line-" + lineNum + "-expand").hide();
10132
+
10133
+    $("#line-" + lineNum + "-monitoring").hide();    
10134
+}
10135
+function RestoreVideoArea(lineNum){
10136
+
10137
+    $("#line-" + lineNum + "-ActiveCall").prop("class","");
10138
+    $("#line-" + lineNum + "-VideoCall").css("height", "");
10139
+    $("#line-" + lineNum + "-VideoCall").css("margin-top", "10px");
10140
+
10141
+    $("#line-" + lineNum + "-preview-container").prop("class","PreviewContainer");
10142
+    $("#line-" + lineNum + "-stage-container").prop("class","StageContainer");
10143
+
10144
+    $("#line-" + lineNum + "-restore").hide();
10145
+    $("#line-" + lineNum + "-expand").show();
10146
+
10147
+    $("#line-" + lineNum + "-monitoring").show();
10148
+}
10149
+function MuteSession(lineNum){
10150
+    $("#line-"+ lineNum +"-btn-Unmute").show();
10151
+    $("#line-"+ lineNum +"-btn-Mute").hide();
10152
+
10153
+    var lineObj = FindLineByNumber(lineNum);
10154
+    if(lineObj == null || lineObj.SipSession == null) return;
10155
+
10156
+    var session = lineObj.SipSession;
10157
+    var pc = session.sessionDescriptionHandler.peerConnection;
10158
+    pc.getSenders().forEach(function (RTCRtpSender) {
10159
+        if(RTCRtpSender.track.kind == "audio") {
10160
+            if(RTCRtpSender.track.IsMixedTrack == true){
10161
+                if(session.data.AudioSourceTrack && session.data.AudioSourceTrack.kind == "audio"){
10162
+                    console.log("Muting Audio Track : "+ session.data.AudioSourceTrack.label);
10163
+                    session.data.AudioSourceTrack.enabled = false;
10164
+                }
10165
+            }
10166
+            else {
10167
+                console.log("Muting Audio Track : "+ RTCRtpSender.track.label);
10168
+                RTCRtpSender.track.enabled = false;
10169
+            }
10170
+        }
10171
+    });
10172
+
10173
+    if(!session.data.mute) session.data.mute = [];
10174
+    session.data.mute.push({ event: "mute", eventTime: utcDateNow() });
10175
+    session.data.ismute = true;
10176
+
10177
+    $("#line-" + lineNum + "-msg").html(lang.call_on_mute);
10178
+
10179
+    updateLineScroll(lineNum);
10180
+
10181
+    // Custom Web hook
10182
+    if(typeof web_hook_on_modify !== 'undefined') web_hook_on_modify("mute", session);
10183
+}
10184
+function UnmuteSession(lineNum){
10185
+    $("#line-"+ lineNum +"-btn-Unmute").hide();
10186
+    $("#line-"+ lineNum +"-btn-Mute").show();
10187
+
10188
+    var lineObj = FindLineByNumber(lineNum);
10189
+    if(lineObj == null || lineObj.SipSession == null) return;
10190
+
10191
+    var session = lineObj.SipSession;
10192
+    var pc = session.sessionDescriptionHandler.peerConnection;
10193
+    pc.getSenders().forEach(function (RTCRtpSender) {
10194
+        if(RTCRtpSender.track.kind == "audio") {
10195
+            if(RTCRtpSender.track.IsMixedTrack == true){
10196
+                if(session.data.AudioSourceTrack && session.data.AudioSourceTrack.kind == "audio"){
10197
+                    console.log("Unmuting Audio Track : "+ session.data.AudioSourceTrack.label);
10198
+                    session.data.AudioSourceTrack.enabled = true;
10199
+                }
10200
+            }
10201
+            else {
10202
+                console.log("Unmuting Audio Track : "+ RTCRtpSender.track.label);
10203
+                RTCRtpSender.track.enabled = true;
10204
+            }
10205
+        }
10206
+    });
10207
+
10208
+    if(!session.data.mute) session.data.mute = [];
10209
+    session.data.mute.push({ event: "unmute", eventTime: utcDateNow() });
10210
+    session.data.ismute = false;
10211
+
10212
+    $("#line-" + lineNum + "-msg").html(lang.call_off_mute);
10213
+
10214
+    updateLineScroll(lineNum);
10215
+
10216
+    // Custom Web hook
10217
+    if(typeof web_hook_on_modify !== 'undefined') web_hook_on_modify("unmute", session);
10218
+}
10219
+function ShowDtmfMenu(obj, lineNum){
10220
+
10221
+    var leftPos = event.pageX - 90;
10222
+    var topPos = event.pageY + 30;
10223
+
10224
+    var html = "<div id=mainDtmfDialPad>";
10225
+    html += "<table cellspacing=10 cellpadding=0 style=\"margin-left:auto; margin-right: auto\">";
10226
+    html += "<tr><td><button class=dtmfButtons onclick=\"sendDTMF('"+ lineNum +"', '1');new Audio('sounds/dtmf.mp3').play();\"><div>1</div><span>&nbsp;</span></button></td>"
10227
+    html += "<td><button class=dtmfButtons onclick=\"sendDTMF('"+ lineNum +"', '2');new Audio('sounds/dtmf.mp3').play();\"><div>2</div><span>ABC</span></button></td>"
10228
+    html += "<td><button class=dtmfButtons onclick=\"sendDTMF('"+ lineNum +"', '3');new Audio('sounds/dtmf.mp3').play();\"><div>3</div><span>DEF</span></button></td></tr>";
10229
+    html += "<tr><td><button class=dtmfButtons onclick=\"sendDTMF('"+ lineNum +"', '4');new Audio('sounds/dtmf.mp3').play();\"><div>4</div><span>GHI</span></button></td>"
10230
+    html += "<td><button class=dtmfButtons onclick=\"sendDTMF('"+ lineNum +"', '5');new Audio('sounds/dtmf.mp3').play();\"><div>5</div><span>JKL</span></button></td>"
10231
+    html += "<td><button class=dtmfButtons onclick=\"sendDTMF('"+ lineNum +"', '6');new Audio('sounds/dtmf.mp3').play();\"><div>6</div><span>MNO</span></button></td></tr>";
10232
+    html += "<tr><td><button class=dtmfButtons onclick=\"sendDTMF('"+ lineNum +"', '7');new Audio('sounds/dtmf.mp3').play();\"><div>7</div><span>PQRS</span></button></td>"
10233
+    html += "<td><button class=dtmfButtons onclick=\"sendDTMF('"+ lineNum +"', '8');new Audio('sounds/dtmf.mp3').play();\"><div>8</div><span>TUV</span></button></td>"
10234
+    html += "<td><button class=dtmfButtons onclick=\"sendDTMF('"+ lineNum +"', '9');new Audio('sounds/dtmf.mp3').play();\"><div>9</div><span>WXYZ</span></button></td></tr>";
10235
+    html += "<tr><td><button class=dtmfButtons onclick=\"sendDTMF('"+ lineNum +"', '*');new Audio('sounds/dtmf.mp3').play();\">*</button></td>"
10236
+    html += "<td><button class=dtmfButtons onclick=\"sendDTMF('"+ lineNum +"', '0');new Audio('sounds/dtmf.mp3').play();\">0</button></td>"
10237
+    html += "<td><button class=dtmfButtons onclick=\"sendDTMF('"+ lineNum +"', '#');new Audio('sounds/dtmf.mp3').play();\">#</button></td></tr>";
10238
+    html += "</table>";
10239
+    html += "</div>";
10240
+
10241
+    $.jeegoopopup.open({
10242
+                html: html,
10243
+                width: "auto",
10244
+                height: "auto",
10245
+                left: leftPos,
10246
+                top: topPos,
10247
+                scrolling: 'no',
10248
+                skinClass: 'jg_popup_basic',
10249
+                overlay: true,
10250
+                opacity: 0,
10251
+                draggable: true,
10252
+                resizable: false,
10253
+                fadeIn: 0
10254
+    });
10255
+
10256
+    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); });
10257
+    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); } });
10258
+}
10259
+
10260
+// Stream Functionality
10261
+// =====================
10262
+function ShowMessgeMenu(obj, typeStr, cdrId, buddy) {
10263
+
10264
+    $.jeegoopopup.close();
10265
+
10266
+    var leftPos = event.pageX;
10267
+    var topPos = event.pageY;
10268
+
10269
+    if (($(window).width() - event.pageX) < (obj.offsetWidth + 50)) { leftPos = event.pageX - 200; }
10270
+
10271
+    var menu = "<div id=\"messageMenu\">";
10272
+    menu += "<table id=\"messageMenuTable\" cellspacing=10 cellpadding=0 style=\"margin-left:auto; margin-right: auto\">";
10273
+
10274
+    // CDR's Menu
10275
+    if (typeStr == "CDR") {
10276
+        var TagState = $("#cdr-flagged-"+ cdrId).is(":visible");
10277
+        var TagText = (TagState)? lang.clear_flag : lang.flag_call;
10278
+        menu += "<tr id=\"CMDetails_1\"><td><i class=\"fa fa-external-link\"></i></td><td class=\"callDetails\">"+ lang.show_call_detail_record +"</td></tr>";
10279
+        menu += "<tr id=\"CMDetails_2\"><td><i class=\"fa fa-tags\"></i></td><td class=\"callDetails\">"+ lang.tag_call +"</td></tr>";
10280
+        menu += "<tr id=\"CMDetails_3\"><td><i class=\"fa fa-flag\"></i></td><td class=\"callDetails\">"+ TagText +"</td></tr>";
10281
+        menu += "<tr id=\"CMDetails_4\"><td><i class=\"fa fa-quote-left\"></i></td><td class=\"callDetails\">"+ lang.edit_comment +"</td></tr>";
10282
+    }
10283
+    if (typeStr == "MSG") {
10284
+        menu += "<tr id=\"CMDetails_5\"><td><i class=\"fa fa-clipboard\"></i></td><td class=\"callDetails\">"+ lang.copy_message +"</td></tr>";
10285
+        menu += "<tr id=\"CMDetails_6\"><td><i class=\"fa fa-quote-left\"></i></td><td class=\"callDetails\">"+ lang.quote_message +"</td></tr>";
10286
+    }
10287
+
10288
+    menu += "</table></div>";
10289
+
10290
+    $.jeegoopopup.open({
10291
+                html: menu,
10292
+                width: 'auto',
10293
+                height: 'auto',
10294
+                left: leftPos,
10295
+                top: topPos,
10296
+                scrolling: 'no',
10297
+                skinClass: 'jg_popup_basic',
10298
+                overlay: true,
10299
+                opacity: 0,
10300
+                draggable: false,
10301
+                resizable: false,
10302
+                fadeIn: 0
10303
+    });
10304
+
10305
+    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); });
10306
+    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); } });
10307
+
10308
+    // CDR messages
10309
+    $("#CMDetails_1").click(function(event) {
10310
+
10311
+            var cdr = null;
10312
+            var currentStream = JSON.parse(localDB.getItem(buddy + "-stream"));
10313
+            if(currentStream != null || currentStream.DataCollection != null){
10314
+                $.each(currentStream.DataCollection, function (i, item) {
10315
+                    if (item.ItemType == "CDR" && item.CdrId == cdrId) {
10316
+                        // Found
10317
+                        cdr = item;
10318
+                        return false;
10319
+                    }
10320
+                });
10321
+            }
10322
+            if(cdr == null) return;
10323
+
10324
+            var callDetails = [];
10325
+
10326
+            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>';
10327
+            html += "<div class=\"UiWindowField scroller\">";
10328
+
10329
+            var CallDate = moment.utc(cdr.ItemDate.replace(" UTC", "")).local().format(DisplayDateFormat +" "+ DisplayTimeFormat);
10330
+            var CallAnswer = (cdr.CallAnswer)? moment.utc(cdr.CallAnswer.replace(" UTC", "")).local().format(DisplayDateFormat +" "+ DisplayTimeFormat) : null ;
10331
+            var ringTime = (cdr.RingTime)? cdr.RingTime : 0 ;
10332
+            var CallEnd = moment.utc(cdr.CallEnd.replace(" UTC", "")).local().format(DisplayDateFormat +" "+ DisplayTimeFormat);
10333
+
10334
+            var srcCallerID = "";
10335
+            var dstCallerID = "";
10336
+            if(cdr.CallDirection == "inbound") {
10337
+                srcCallerID = cdr.Src;
10338
+            } 
10339
+            else if(cdr.CallDirection == "outbound") {
10340
+                dstCallerID = cdr.Dst;
10341
+            }
10342
+            html += "<div class=UiText><b>SIP CallID</b> : "+ cdr.SessionId +"</div>";
10343
+            html += "<div class=UiText><b>"+ lang.call_direction +"</b> : "+ cdr.CallDirection +"</div>";
10344
+            html += "<div class=UiText><b>"+ lang.call_date_and_time +"</b> : "+ CallDate +"</div>";
10345
+            html += "<div class=UiText><b>"+ lang.ring_time +"</b> : "+ formatDuration(ringTime) +" ("+ ringTime +")</div>";
10346
+            html += "<div class=UiText><b>"+ lang.talk_time +"</b> : " + formatDuration(cdr.Billsec) +" ("+ cdr.Billsec +")</div>";
10347
+            html += "<div class=UiText><b>"+ lang.call_duration +"</b> : "+ formatDuration(cdr.TotalDuration) +" ("+ cdr.TotalDuration +")</div>";
10348
+            html += "<div class=UiText><b>"+ lang.video_call +"</b> : "+ ((cdr.WithVideo)? lang.yes : lang.no) +"</div>";
10349
+            html += "<div class=UiText><b>"+ lang.flagged +"</b> : "+ ((cdr.Flagged)? "<i class=\"fa fa-flag FlagCall\"></i> " + lang.yes : lang.no)  +"</div>";
10350
+            html += "<hr>";
10351
+            html += "<h2 style=\"font-size: 16px\">"+ lang.call_tags +"</h2>";
10352
+            html += "<hr>";
10353
+            $.each(cdr.Tags, function(item, tag){
10354
+                html += "<span class=cdrTag>"+ tag.value +"</span>"
10355
+            });
10356
+
10357
+            html += "<h2 style=\"font-size: 16px\">"+ lang.call_notes +"</h2>";
10358
+            html += "<hr>";
10359
+            if(cdr.MessageData){
10360
+                html += "\"" + cdr.MessageData + "\"";
10361
+            }
10362
+
10363
+            html += "<h2 style=\"font-size: 16px\">"+ lang.activity_timeline +"</h2>";
10364
+            html += "<hr>";
10365
+
10366
+            var withVideo = (cdr.WithVideo)? "("+ lang.with_video +")" : "";
10367
+            var startCallMessage = (cdr.CallDirection == "inbound")? lang.you_received_a_call_from + " " + srcCallerID  +" "+ withVideo : lang.you_made_a_call_to + " " + dstCallerID +" "+ withVideo;
10368
+            callDetails.push({ 
10369
+                Message: startCallMessage,
10370
+                TimeStr: cdr.ItemDate
10371
+            });
10372
+            if(CallAnswer){
10373
+                var answerCallMessage = (cdr.CallDirection == "inbound")? lang.you_answered_after + " " + ringTime + " " + lang.seconds_plural : lang.they_answered_after + " " + ringTime + " " + lang.seconds_plural;
10374
+                callDetails.push({ 
10375
+                    Message: answerCallMessage,
10376
+                    TimeStr: cdr.CallAnswer
10377
+                });
10378
+            }
10379
+            $.each(cdr.Transfers, function(item, transfer){
10380
+                var msg = (transfer.type == "Blind")? lang.you_started_a_blind_transfer_to +" "+ transfer.to +". " : lang.you_started_an_attended_transfer_to + " "+ transfer.to +". ";
10381
+                if(transfer.accept && transfer.accept.complete == true){
10382
+                    msg += lang.the_call_was_completed
10383
+                }
10384
+                else if(transfer.accept.disposition != "") {
10385
+                    msg += lang.the_call_was_not_completed +" ("+ transfer.accept.disposition +")"
10386
+                }
10387
+                callDetails.push({
10388
+                    Message : msg,
10389
+                    TimeStr : transfer.transferTime
10390
+                });
10391
+            });
10392
+            $.each(cdr.Mutes, function(item, mute){
10393
+                callDetails.push({
10394
+                    Message : (mute.event == "mute")? lang.you_put_the_call_on_mute : lang.you_took_the_call_off_mute,
10395
+                    TimeStr : mute.eventTime
10396
+                });
10397
+            });
10398
+            $.each(cdr.Holds, function(item, hold){
10399
+                callDetails.push({
10400
+                    Message : (hold.event == "hold")? lang.you_put_the_call_on_hold : lang.you_took_the_call_off_hold,
10401
+                    TimeStr : hold.eventTime
10402
+                });
10403
+            });
10404
+            $.each(cdr.ConfCalls, function(item, confCall){
10405
+                var msg = lang.you_started_a_conference_call_to +" "+ confCall.to +". ";
10406
+                if(confCall.accept && confCall.accept.complete == true){
10407
+                    msg += lang.the_call_was_completed
10408
+                }
10409
+                else if(confCall.accept.disposition != "") {
10410
+                    msg += lang.the_call_was_not_completed +" ("+ confCall.accept.disposition +")"
10411
+                }
10412
+                callDetails.push({
10413
+                    Message : msg,
10414
+                    TimeStr : confCall.startTime
10415
+                });
10416
+            });
10417
+            $.each(cdr.Recordings, function(item, recording){
10418
+                var StartTime = moment.utc(recording.startTime.replace(" UTC", "")).local();
10419
+                var StopTime = moment.utc(recording.stopTime.replace(" UTC", "")).local();
10420
+                var recordingDuration = moment.duration(StopTime.diff(StartTime));
10421
+
10422
+                var msg = lang.call_is_being_recorded;
10423
+                if(recording.startTime != recording.stopTime){
10424
+                    msg += "("+ formatShortDuration(recordingDuration.asSeconds()) +")"
10425
+                }
10426
+                callDetails.push({
10427
+                    Message : msg,
10428
+                    TimeStr : recording.startTime
10429
+                });
10430
+            });
10431
+            callDetails.push({
10432
+                Message: (cdr.Terminate == "us")? "You ended the call." : "They ended the call",
10433
+                TimeStr : cdr.CallEnd
10434
+            });
10435
+
10436
+            callDetails.sort(function(a, b){
10437
+                var aMo = moment.utc(a.TimeStr.replace(" UTC", ""));
10438
+                var bMo = moment.utc(b.TimeStr.replace(" UTC", ""));
10439
+                if (aMo.isSameOrAfter(bMo, "second")) {
10440
+                    return 1;
10441
+                } else return -1;
10442
+                return 0;
10443
+            });
10444
+            $.each(callDetails, function(item, detail){
10445
+                var Time = moment.utc(detail.TimeStr.replace(" UTC", "")).local().format(DisplayTimeFormat);
10446
+                var messageString = "<table class=timelineMessage cellspacing=0 cellpadding=0><tr>"
10447
+                messageString += "<td class=timelineMessageArea>"
10448
+                messageString += "<div class=timelineMessageDate style=\"color: #333333\"><i class=\"fa fa-circle timelineMessageDot\"></i>"+ Time +"</div>"
10449
+                messageString += "<div class=timelineMessageText style=\"color: #000000\">"+ detail.Message +"</div>"
10450
+                messageString += "</td>"
10451
+                messageString += "</tr></table>";
10452
+                html += messageString;
10453
+            });
10454
+
10455
+            html += "<h2 style=\"font-size: 16px\">"+ lang.call_recordings +"</h2>";
10456
+            html += "<hr>";
10457
+            var recordingsHtml = "";
10458
+            $.each(cdr.Recordings, function(r, recording){
10459
+                if(recording.uID){
10460
+                    var StartTime = moment.utc(recording.startTime.replace(" UTC", "")).local();
10461
+                    var StopTime = moment.utc(recording.stopTime.replace(" UTC", "")).local();
10462
+                    var recordingDuration = moment.duration(StopTime.diff(StartTime));
10463
+                    recordingsHtml += "<div>";
10464
+                    if(cdr.WithVideo){
10465
+                        recordingsHtml += "<div><video id=\"callrecording-video-"+ recording.uID +"\" controls style=\"width: 100%\"></div>";
10466
+                    } 
10467
+                    else {
10468
+                        recordingsHtml += "<div><audio id=\"callrecording-audio-"+ recording.uID +"\" controls style=\"width: 100%\"></div>";
10469
+                    } 
10470
+                    recordingsHtml += "<div>"+ lang.started +": "+ StartTime.format(DisplayTimeFormat) +" <i class=\"fa fa-long-arrow-right\"></i> "+ lang.stopped +": "+ StopTime.format(DisplayTimeFormat) +"</div>";
10471
+                    recordingsHtml += "<div>"+ lang.recording_duration +": "+ formatShortDuration(recordingDuration.asSeconds()) +"</div>";
10472
+                    recordingsHtml += "<div><a id=\"download-"+ recording.uID +"\">"+ lang.save_as +"</a> ("+ lang.right_click_and_select_save_link_as +")</div>";
10473
+                    recordingsHtml += "</div>";
10474
+                }
10475
+            });
10476
+            html += recordingsHtml;
10477
+
10478
+            html += "<h2 style=\"font-size: 16px\">"+ lang.send_statistics +"</h2>";
10479
+            html += "<hr>";
10480
+
10481
+            html += "<div style=\"position: relative; margin: auto; height: 160px; width: 100%;\"><canvas id=\"cdr-AudioSendBitRate\"></canvas></div>";
10482
+            html += "<div style=\"position: relative; margin: auto; height: 160px; width: 100%;\"><canvas id=\"cdr-AudioSendPacketRate\"></canvas></div>";
10483
+
10484
+            html += "<h2 style=\"font-size: 16px\">"+ lang.receive_statistics +"</h2>";
10485
+            html += "<hr>";
10486
+
10487
+            html += "<div style=\"position: relative; margin: auto; height: 160px; width: 100%;\"><canvas id=\"cdr-AudioReceiveBitRate\"></canvas></div>";
10488
+            html += "<div style=\"position: relative; margin: auto; height: 160px; width: 100%;\"><canvas id=\"cdr-AudioReceivePacketRate\"></canvas></div>";
10489
+            html += "<div style=\"position: relative; margin: auto; height: 160px; width: 100%;\"><canvas id=\"cdr-AudioReceivePacketLoss\"></canvas></div>";
10490
+            html += "<div style=\"position: relative; margin: auto; height: 160px; width: 100%;\"><canvas id=\"cdr-AudioReceiveJitter\"></canvas></div>";
10491
+            html += "<div style=\"position: relative; margin: auto; height: 160px; width: 100%;\"><canvas id=\"cdr-AudioReceiveLevels\"></canvas></div>";
10492
+
10493
+            html += "<br><br></div>";
10494
+
10495
+            $.jeegoopopup.close();
10496
+
10497
+            $.jeegoopopup.open({
10498
+                title: 'Call Statistics',
10499
+                html: html,
10500
+                width: '640',
10501
+                height: '500',
10502
+                center: true,
10503
+                scrolling: 'no',
10504
+                skinClass: 'jg_popup_basic',
10505
+                overlay: true,
10506
+                opacity: 50,
10507
+                draggable: true,
10508
+                resizable: false,
10509
+                fadeIn: 0
10510
+            });
10511
+
10512
+            $("#jg_popup_b").append('<button id="ok_button">'+ lang.ok +'</button>');
10513
+
10514
+            // Display QOS data
10515
+            DisplayQosData(cdr.SessionId);
10516
+
10517
+
10518
+	    var maxWidth = $(window).width() - 12;
10519
+	    var maxHeight = $(window).height() - 88;
10520
+
10521
+	    if (maxWidth < 656 || maxHeight < 500) { 
10522
+	       $.jeegoopopup.width(maxWidth).height(maxHeight);
10523
+	       $.jeegoopopup.center();
10524
+	       $("#maximizeImg").hide();
10525
+	       $("#minimizeImg").hide();
10526
+	    } else { 
10527
+	       $.jeegoopopup.width(640).height(500);
10528
+	       $.jeegoopopup.center();
10529
+	       $("#minimizeImg").hide();
10530
+	       $("#maximizeImg").show();
10531
+	    }
10532
+
10533
+	    $(window).resize(function() {
10534
+	       maxWidth = $(window).width() - 12;
10535
+	       maxHeight = $(window).height() - 88;
10536
+	       $.jeegoopopup.center();
10537
+	       if (maxWidth < 656 || maxHeight < 500) { 
10538
+		   $.jeegoopopup.width(maxWidth).height(maxHeight);
10539
+		   $.jeegoopopup.center();
10540
+		   $("#maximizeImg").hide();
10541
+		   $("#minimizeImg").hide();
10542
+	       } else { 
10543
+		   $.jeegoopopup.width(640).height(500);
10544
+		   $.jeegoopopup.center();
10545
+		   $("#minimizeImg").hide();
10546
+		   $("#maximizeImg").show();
10547
+	       }
10548
+	    });
10549
+
10550
+	   
10551
+	    $("#minimizeImg").click(function() { $.jeegoopopup.width(640).height(500); $.jeegoopopup.center(); $("#maximizeImg").show(); $("#minimizeImg").hide(); });
10552
+	    $("#maximizeImg").click(function() { $.jeegoopopup.width(maxWidth).height(maxHeight); $.jeegoopopup.center(); $("#minimizeImg").show(); $("#maximizeImg").hide(); });
10553
+
10554
+	    $("#closeImg").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
10555
+	    $("#ok_button").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
10556
+	    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
10557
+	    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); $("#jg_popup_b").empty(); } });
10558
+
10559
+
10560
+            // Queue video and audio
10561
+            $.each(cdr.Recordings, function(r, recording){
10562
+                    var mediaObj = null;
10563
+                    if(cdr.WithVideo){
10564
+                        mediaObj = $("#callrecording-video-"+ recording.uID).get(0);
10565
+                    }
10566
+                    else {
10567
+                        mediaObj = $("#callrecording-audio-"+ recording.uID).get(0);
10568
+                    }
10569
+                    var downloadURL = $("#download-"+ recording.uID);
10570
+
10571
+                    // Playback device
10572
+                    var sinkId = getAudioOutputID();
10573
+                    if (typeof mediaObj.sinkId !== 'undefined') {
10574
+                        mediaObj.setSinkId(sinkId).then(function(){
10575
+                            console.log("sinkId applied: "+ sinkId);
10576
+                        }).catch(function(e){
10577
+                            console.warn("Error using setSinkId: ", e);
10578
+                        });
10579
+                    } else {
10580
+                        console.warn("setSinkId() is not possible using this browser.")
10581
+                    }
10582
+
10583
+                    // Get Call Recording
10584
+                    var indexedDB = window.indexedDB;
10585
+                    var request = indexedDB.open("CallRecordings");
10586
+                    request.onerror = function(event) {
10587
+                        console.error("IndexDB Request Error:", event);
10588
+                    }
10589
+                    request.onupgradeneeded = function(event) {
10590
+                        console.warn("Upgrade Required for IndexDB... probably because of first time use.");
10591
+                    }
10592
+                    request.onsuccess = function(event) {
10593
+                        console.log("IndexDB connected to CallRecordings");
10594
+
10595
+                        var IDB = event.target.result;
10596
+                        if(IDB.objectStoreNames.contains("Recordings") == false){
10597
+                            console.warn("IndexDB CallRecordings.Recordings does not exists");
10598
+                            return;
10599
+                        } 
10600
+
10601
+                        var transaction = IDB.transaction(["Recordings"]);
10602
+                        var objectStoreGet = transaction.objectStore("Recordings").get(recording.uID);
10603
+                        objectStoreGet.onerror = function(event) {
10604
+                            console.error("IndexDB Get Error:", event);
10605
+                        }
10606
+                        objectStoreGet.onsuccess = function(event) {
10607
+                            var mediaBlobUrl = window.URL.createObjectURL(event.target.result.mediaBlob);
10608
+                            mediaObj.src = mediaBlobUrl;
10609
+
10610
+                            // Download Link
10611
+                            if(cdr.WithVideo){
10612
+                                downloadURL.prop("download",  "Video-Call-Recording-"+ recording.uID +".webm");
10613
+                            }
10614
+                            else {
10615
+                                downloadURL.prop("download",  "Audio-Call-Recording-"+ recording.uID +".webm");
10616
+                            }
10617
+                            downloadURL.prop("href", mediaBlobUrl);
10618
+                        }
10619
+                    }
10620
+
10621
+            });
10622
+
10623
+    });
10624
+
10625
+    $("#CMDetails_2").click(function(event) {
10626
+            $("#cdr-tags-"+ cdrId).show();
10627
+
10628
+            $.jeegoopopup.close();
10629
+    });
10630
+
10631
+    $("#CMDetails_3").click(function(event) {
10632
+            // Tag / Untag Call
10633
+            var TagState = $("#cdr-flagged-"+ cdrId).is(":visible");
10634
+            if(TagState){
10635
+                console.log("Clearing Flag from: ", cdrId);
10636
+                $("#cdr-flagged-"+ cdrId).hide();
10637
+
10638
+                // Update DB
10639
+                var currentStream = JSON.parse(localDB.getItem(buddy + "-stream"));
10640
+                if(currentStream != null || currentStream.DataCollection != null){
10641
+                    $.each(currentStream.DataCollection, function (i, item) {
10642
+                        if (item.ItemType == "CDR" && item.CdrId == cdrId) {
10643
+                            // Found
10644
+                            item.Flagged = false;
10645
+                            return false;
10646
+                        }
10647
+                    });
10648
+                    localDB.setItem(buddy + "-stream", JSON.stringify(currentStream));
10649
+                }
10650
+            }
10651
+            else {
10652
+                console.log("Flag Call: ", cdrId);
10653
+                $("#cdr-flagged-"+ cdrId).show();
10654
+
10655
+                // Update DB
10656
+                var currentStream = JSON.parse(localDB.getItem(buddy + "-stream"));
10657
+                if(currentStream != null || currentStream.DataCollection != null){
10658
+                    $.each(currentStream.DataCollection, function (i, item) {
10659
+                        if (item.ItemType == "CDR" && item.CdrId == cdrId) {
10660
+                            // Found
10661
+                            item.Flagged = true;
10662
+                            return false;
10663
+                        }
10664
+                    });
10665
+                    localDB.setItem(buddy + "-stream", JSON.stringify(currentStream));
10666
+                }
10667
+            }
10668
+
10669
+            $.jeegoopopup.close();
10670
+    });
10671
+
10672
+    $("#CMDetails_4").click(function(event) {
10673
+
10674
+            var currentText = $("#cdr-comment-"+ cdrId).text();
10675
+            $("#cdr-comment-"+ cdrId).empty();
10676
+
10677
+            var textboxObj = $("<input maxlength=500 type=text>").appendTo("#cdr-comment-"+ cdrId);
10678
+            textboxObj.on("focus", function(){
10679
+                $.jeegoopopup.close();
10680
+            });
10681
+            textboxObj.on("blur", function(){
10682
+                var newText = $(this).val();
10683
+                SaveComment(cdrId, buddy, newText);
10684
+            });
10685
+            textboxObj.keypress(function(event){
10686
+                window.setTimeout(function(){
10687
+
10688
+                      $.jeegoopopup.close();
10689
+
10690
+                }, 500);
10691
+
10692
+                var keycode = (event.keyCode ? event.keyCode : event.which);
10693
+                if (keycode == '13') {
10694
+                    event.preventDefault();
10695
+
10696
+                    var newText = $(this).val();
10697
+                    SaveComment(cdrId, buddy, newText);
10698
+                }
10699
+            });
10700
+            textboxObj.val(currentText);
10701
+            textboxObj.focus();
10702
+
10703
+            $.jeegoopopup.close();
10704
+    });
10705
+
10706
+    $("#CMDetails_5").click(function(event) {
10707
+        // Text Messages
10708
+            var msgtext = $("#msg-text-"+ cdrId).text();
10709
+            navigator.clipboard.writeText(msgtext).then(function(){
10710
+                console.log("Text coppied to the clipboard:", msgtext);
10711
+            }).catch(function(){
10712
+                console.error("Error writing to the clipboard:", e);
10713
+            });
10714
+
10715
+            $.jeegoopopup.close();
10716
+    });
10717
+
10718
+    $("#CMDetails_6").click(function(event) {
10719
+
10720
+            var msgtext = $("#msg-text-"+ cdrId).text();
10721
+            msgtext = "\""+ msgtext + "\"";
10722
+            var textarea = $("#contact-"+ buddy +"-ChatMessage");
10723
+            console.log("Quote Message:", msgtext);
10724
+            textarea.val(msgtext +"\n" + textarea.val());
10725
+
10726
+            $.jeegoopopup.close();
10727
+    });
10728
+
10729
+}
10730
+function SaveComment(cdrId, buddy, newText){
10731
+    console.log("Setting Comment:", newText);
10732
+
10733
+    $("#cdr-comment-"+ cdrId).empty();
10734
+    $("#cdr-comment-"+ cdrId).append(newText);
10735
+
10736
+    // Update DB
10737
+    var currentStream = JSON.parse(localDB.getItem(buddy + "-stream"));
10738
+    if(currentStream != null || currentStream.DataCollection != null){
10739
+        $.each(currentStream.DataCollection, function (i, item) {
10740
+            if (item.ItemType == "CDR" && item.CdrId == cdrId) {
10741
+                // Found
10742
+                item.MessageData = newText;
10743
+                return false;
10744
+            }
10745
+        });
10746
+        localDB.setItem(buddy + "-stream", JSON.stringify(currentStream));
10747
+    }
10748
+}
10749
+function TagKeyPress(event, obj, cdrId, buddy){
10750
+
10751
+    $.jeegoopopup.close();
10752
+
10753
+    var keycode = (event.keyCode ? event.keyCode : event.which);
10754
+    if (keycode == '13' || keycode == '44') {
10755
+        event.preventDefault();
10756
+
10757
+        if ($(obj).val() == "") return;
10758
+
10759
+        console.log("Adding Tag:", $(obj).val());
10760
+
10761
+        $("#cdr-tags-"+ cdrId+" li:last").before("<li onclick=\"TagClick(this, '"+ cdrId +"', '"+ buddy +"')\">"+ $(obj).val() +"</li>");
10762
+        $(obj).val("");
10763
+
10764
+        // Update DB
10765
+        UpdateTags(cdrId, buddy);
10766
+    }
10767
+}
10768
+function TagClick(obj, cdrId, buddy){
10769
+    window.setTimeout(function(){
10770
+       $.jeegoopopup.close();
10771
+    }, 500);
10772
+
10773
+    console.log("Removing Tag:", $(obj).text());
10774
+    $(obj).remove();
10775
+
10776
+    // Dpdate DB
10777
+    UpdateTags(cdrId, buddy);
10778
+}
10779
+function UpdateTags(cdrId, buddy){
10780
+    var currentStream = JSON.parse(localDB.getItem(buddy + "-stream"));
10781
+    if(currentStream != null || currentStream.DataCollection != null){
10782
+        $.each(currentStream.DataCollection, function (i, item) {
10783
+            if (item.ItemType == "CDR" && item.CdrId == cdrId) {
10784
+                // Found
10785
+                item.Tags = [];
10786
+                $("#cdr-tags-"+ cdrId).children('li').each(function () {
10787
+                    if($(this).prop("class") != "tagText") item.Tags.push({ value: $(this).text() });
10788
+                });
10789
+                return false;
10790
+            }
10791
+        });
10792
+        localDB.setItem(buddy + "-stream", JSON.stringify(currentStream));
10793
+    }
10794
+}
10795
+
10796
+function TagFocus(obj){
10797
+      $.jeegoopopup.close();
10798
+}
10799
+function SendFile(buddy) {
10800
+
10801
+      $('#selectedFile').val('');
10802
+      $("#upFile").empty();
10803
+
10804
+      var buddyObj = FindBuddyByIdentity(buddy);
10805
+      var uploadfile = '<form id="sendFileFormChat" enctype="multipart/form-data">';
10806
+      uploadfile += '<input type="hidden" name="MAX_FILE_SIZE" value="786432000" />';
10807
+      uploadfile += '<input type="hidden" name="sipUser" value="'+ buddyObj.ExtNo +'" />';
10808
+      uploadfile += '<input type="hidden" name="s_ajax_call" value="'+ validateSToken +'" />';
10809
+      uploadfile += '<label for="selectedFile" class="customBrowseButton">Select File</label>';
10810
+      uploadfile += '<span id="upFile"></span>';
10811
+      uploadfile += '<input type="file" id="selectedFile" name="uploadedFile" />';
10812
+      uploadfile += '<input type="submit" id="submitFileChat" value="Send File" style="visibility:hidden;"/>';
10813
+      uploadfile += '</form>';
10814
+
10815
+      if ($("#sendFileFormChat").is(":visible")) {
10816
+          $("#sendFileFormChat").remove();
10817
+          sendFileCheck = 0;
10818
+      } else {
10819
+          sendFileCheck = 1;
10820
+          $("#contact-"+ buddy +"-ChatMessage").before(uploadfile);
10821
+          $("#sendFileFormChat").css("display", "block");
10822
+
10823
+          $("#selectedFile").bind("change", function() {
10824
+             upFileName = $(this).val().split('\\').pop();
10825
+             if (/^[a-zA-Z0-9\-\_\.]+$/.test(upFileName)) {
10826
+                 $("#upFile").html(upFileName);
10827
+             } else { 
10828
+                   $("#sendFileFormChat").remove();
10829
+                   sendFileCheck = 0;
10830
+                   alert("The name of the uploaded file is not valid!");
10831
+             }
10832
+          });
10833
+      }
10834
+}
10835
+
10836
+function ShowEmojiBar(buddy) {
10837
+
10838
+    var messageContainer = $("#contact-"+ buddy +"-emoji-menu");
10839
+    var textarea = $("#contact-"+ buddy +"-ChatMessage");
10840
+
10841
+    if (messageContainer.is(":visible")) { messageContainer.hide(); } else { messageContainer.show(); }
10842
+
10843
+    var menuBar = $("<div>");
10844
+    menuBar.prop("class", "emojiButton")
10845
+    var emojis = ["😀","😁","😂","😃","😄","😅","😆","😊","😦","😉","😊","😋","😌","😍","😎","😏","😐","😑","😒","😓","😔","😕","😖","😗","😘","😙","😚","😛","😜","😝","😞","😟","😠","😡","😢","😣","😤","😥","😦","😧","😨","😩","😪","😫","😬","😭","😮","😯","😰","😱","😲","😳","😴","😵","😶","😷","🙁","🙂","🙃","🙄","🤐","🤑","🤒","🤓","🤔","🤕","🤠","🤡","🤢","🤣","🤤","🤥","🤧","🤨","🤩","🤪","🤫","🤬","🥺","🤭","🤯","🧐"];
10846
+    $.each(emojis, function(i,e){
10847
+        var emoji = $("<button>");
10848
+        emoji.html(e);
10849
+        emoji.on('click', function() {
10850
+            var i = textarea.prop('selectionStart');
10851
+            var v = textarea.val();
10852
+            textarea.val(v.substring(0, i) + " " + $(this).html() + v.substring(i, v.length) + " ");
10853
+
10854
+            messageContainer.hide();
10855
+            textarea.focus();
10856
+            updateScroll(buddy);
10857
+        });
10858
+        menuBar.append(emoji);
10859
+    });
10860
+
10861
+    $(".chatMessage,.chatHistory").on('click', function(){
10862
+        messageContainer.hide();
10863
+    });
10864
+
10865
+    messageContainer.empty();
10866
+    messageContainer.append(menuBar);
10867
+
10868
+    updateScroll(buddy);
10869
+}
10870
+
10871
+// My Profile
10872
+// ==========
10873
+function ShowMyProfileMenu(obj){
10874
+
10875
+    var leftPos = obj.offsetWidth - 254;
10876
+    var topPos = obj.offsetHeight + 56 ;
10877
+
10878
+    var usrRoleFromDB = getDbItem("userrole", "");
10879
+    if (usrRoleFromDB == "superadmin") { var usrRole = "(superadmin)"; } else { var usrRole = ""; }
10880
+    var currentUser = '<font style=\'color:#000000;cursor:auto;\'>' + userName + ' ' + usrRole + '</font>';
10881
+
10882
+    var autoAnswerCheck = AutoAnswerEnabled ? "<i class='fa fa-check' style='float:right;'></i>" : "";
10883
+    var doNotDisturbCheck = DoNotDisturbEnabled ? "<i class='fa fa-check' style='float:right;'></i>" : "";
10884
+    var callWaitingCheck = CallWaitingEnabled ? "<i class='fa fa-check' style='float:right;'></i>" : "";
10885
+
10886
+    var menu = "<div id=userMenu>";
10887
+    menu += "<table id=userMenuTable cellspacing=10 cellpadding=0 style=\"margin-left:auto; margin-right: auto\">";
10888
+    menu += "<tr id=userMenu_1><td><i class=\"fa fa-phone\"></i>&nbsp; "+ lang.auto_answer + "<span id=\"autoAnswerTick\">" + autoAnswerCheck + "</span></td></tr>";
10889
+    menu += "<tr id=userMenu_2><td><i class=\"fa fa-ban\"></i>&nbsp; "+ lang.do_not_disturb + "<span id=\"doNotDisturbTick\">" + doNotDisturbCheck + "</span></td></tr>";
10890
+    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>";
10891
+    menu += "<tr id=userMenu_4><td><i class=\"fa fa-refresh\"></i>&nbsp; "+ lang.refresh_registration + "</td></tr>";
10892
+    menu += "<tr id=userMenu_5><td><i class=\"fa fa-user-plus\"></i>&nbsp; "+ lang.add_contact + "</td></tr>";
10893
+    menu += "<tr id=userMenu_6><td><font style=\'color:#000000;cursor:auto;\'>"+ lang.logged_in_as + "</font></td></tr>";
10894
+    menu += "<tr id=userMenu_7><td><span style='width:20px;'></span>" + currentUser + "</td></tr>";
10895
+    menu += "<tr id=userMenu_8><td><i class=\"fa fa-power-off\"></i>&nbsp; "+ lang.log_out + "</td></tr>";
10896
+    menu += "</table>";
10897
+    menu += "</div>";  
10898
+
10899
+    $.jeegoopopup.open({
10900
+                html: menu,
10901
+                width: 'auto',
10902
+                height: 'auto',
10903
+                left: '56',
10904
+                top: topPos,
10905
+                scrolling: 'no',
10906
+                skinClass: 'jg_popup_basic',
10907
+                innerClass: 'userMenuInner',
10908
+                contentClass: 'userMenuContent',
10909
+                overlay: true,
10910
+                opacity: 0,
10911
+                draggable: false,
10912
+                resizable: false,
10913
+                fadeIn: 0
10914
+    });
10915
+
10916
+    $(window).resize(function() {
10917
+      $.jeegoopopup.width('auto').height('auto').left('56').top(topPos);   
10918
+    });
10919
+
10920
+    $("#userMenu_1").click(function() {
10921
+      ToggleAutoAnswer();
10922
+      if (AutoAnswerEnabled) {
10923
+          $("#autoAnswerTick").append("<i class='fa fa-check' style='float:right;'></i>");
10924
+      } else {
10925
+          $("#autoAnswerTick").empty();
10926
+      } 
10927
+    });
10928
+    $("#userMenu_2").click(function() {
10929
+      ToggleDoNoDisturb();
10930
+      if (DoNotDisturbEnabled) {
10931
+          $("#doNotDisturbTick").append("<i class='fa fa-check' style='float:right;'></i>");
10932
+      } else {
10933
+          $("#doNotDisturbTick").empty();
10934
+      } 
10935
+    });
10936
+    $("#userMenu_3").click(function() {
10937
+      ToggleCallWaiting();
10938
+      if (CallWaitingEnabled) {
10939
+          $("#callWaitingTick").append("<i class='fa fa-check' style='float:right;'></i>");
10940
+      } else {
10941
+          $("#callWaitingTick").empty();
10942
+      }
10943
+    });
10944
+    $("#userMenu_4").click(function() { RefreshRegistration(); });
10945
+    $("#userMenu_5").click(function() { AddSomeoneWindow(); });
10946
+    $("#userMenu_8").click(function() { SignOut(); });
10947
+
10948
+    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); });
10949
+    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); } });
10950
+}
10951
+
10952
+function ShowLaunchVidConfMenu(obj){
10953
+
10954
+    var leftPos = obj.offsetWidth + 121;
10955
+    var rightPos = 0;
10956
+    var topPos = obj.offsetHeight + 117;
10957
+
10958
+    if ($(window).width() <= 915) {
10959
+        leftPos = event.pageX + obj.offsetWidth - 113;
10960
+        rightPos = 0;
10961
+        topPos = event.pageY + obj.offsetHeight - 11;
10962
+    }
10963
+
10964
+    var vcmenu = "<div id=videoConfMenu>";
10965
+    vcmenu += "<table id=lauchVConfTable cellspacing=0 cellpadding=0 style=\"margin: 0px\">";
10966
+    vcmenu += "<tr id=launchVConfMenu_1><td><i class=\"fa fa-users\"></i>&nbsp; "+ lang.launch_video_conference + "</td></tr>";
10967
+    vcmenu += "</table>";
10968
+    vcmenu += "</div>";
10969
+
10970
+    $.jeegoopopup.open({
10971
+                html: vcmenu,
10972
+                width: '228',
10973
+                height: '22',
10974
+                left: leftPos,
10975
+                right: rightPos,
10976
+                top: topPos,
10977
+                scrolling: 'no',
10978
+                skinClass: 'jg_popup_basic',
10979
+                overlay: true,
10980
+                opacity: 0,
10981
+                draggable: false,
10982
+                resizable: false,
10983
+                fadeIn: 0
10984
+    });
10985
+
10986
+    $(window).resize(function() {
10987
+      $.jeegoopopup.width('228').height('22').left(leftPos).top(topPos);   
10988
+    });
10989
+
10990
+    if ($(window).width() <= 915) { $.jeegoopopup.right(6); } else { $.jeegoopopup.width('228').height('22').left(leftPos).top(topPos); }
10991
+
10992
+    $("#launchVConfMenu_1").click(function() { LaunchVideoConference(); $.jeegoopopup.close(); });
10993
+    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); });
10994
+    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); } });
10995
+}
10996
+
10997
+function ShowAccountSettingsMenu(obj) {
10998
+
10999
+    $.jeegoopopup.close();
11000
+
11001
+    var leftPos = obj.offsetWidth + 212;
11002
+    var rightPos = 0;
11003
+    var topPos = obj.offsetHeight + 117;
11004
+
11005
+    if ($(window).width() <= 915) {
11006
+
11007
+        leftPos = event.pageX - 32;
11008
+        rightPos = 0;
11009
+        topPos = event.pageY + 11;
11010
+    }
11011
+
11012
+    var setconfmenu = "<div id=settingsCMenu>";
11013
+    setconfmenu += "<table id=lauchSetConfTable cellspacing=0 cellpadding=0 style=\"margin: 0px\">";
11014
+    setconfmenu += "<tr id=settingsCMenu_1><td><i class=\"fa fa-wrench\"></i>&nbsp; "+ lang.account_settings + "</td></tr>";
11015
+    setconfmenu += "</table>";
11016
+    setconfmenu += "</div>";
11017
+
11018
+    $.jeegoopopup.open({
11019
+                html: setconfmenu,
11020
+                width: '94',
11021
+                height: '22',
11022
+                left: leftPos,
11023
+                right: rightPos,
11024
+                top: topPos,
11025
+                scrolling: 'no',
11026
+                skinClass: 'jg_popup_basic',
11027
+                overlay: true,
11028
+                opacity: 0,
11029
+                draggable: false,
11030
+                resizable: false,
11031
+                fadeIn: 0
11032
+    });
11033
+
11034
+    $(window).resize(function() {
11035
+      $.jeegoopopup.width('94').height('22').left(leftPos).top(topPos);   
11036
+    });
11037
+
11038
+    if ($(window).width() <= 915) { $.jeegoopopup.right(6); } else { $.jeegoopopup.width('94').height('22').left(leftPos).top(topPos); }
11039
+
11040
+    $("#settingsCMenu_1").click(function() { ConfigureExtensionWindow(); });
11041
+    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); });
11042
+    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); } });
11043
+}
11044
+
11045
+function RefreshRegistration(){
11046
+    Unregister();
11047
+    console.log("Unregister complete...");
11048
+    window.setTimeout(function(){
11049
+        console.log("Starting registration...");
11050
+        Register();
11051
+    }, 1000);
11052
+}
11053
+
11054
+function SignOut() {
11055
+
11056
+    if (getDbItem("useRoundcube", "") == 1) {
11057
+
11058
+        // Log out from Roundcube
11059
+        $("#roundcubeFrame").remove();
11060
+        $("#rightContent").show();
11061
+        $(".streamSelected").each(function() { $(this).css("display", "none"); });
11062
+        $("#rightContent").append('<iframe id="rcLogoutFrame" name="logoutFrame"></iframe>');
11063
+
11064
+
11065
+        var logoutURL = "https://"+ getDbItem("rcDomain", "") +"/";
11066
+
11067
+        var logoutform = '<form id="rcloForm" method="POST" action="'+ logoutURL +'" target="logoutFrame">'; 
11068
+        logoutform += '<input type="hidden" name="_action" value="logout" />';
11069
+        logoutform += '<input type="hidden" name="_task" value="logout" />';
11070
+        logoutform += '<input type="hidden" name="_autologout" value="1" />';
11071
+        logoutform += '<input id="submitloButton" type="submit" value="Logout" />';
11072
+        logoutform += '</form>';
11073
+
11074
+        $("#rcLogoutFrame").append(logoutform);
11075
+        $("#submitloButton").click();
11076
+
11077
+    }
11078
+
11079
+    // Remove the 'uploads' directory used to temporarily store files received during text chat
11080
+    removeTextChatUploads(getDbItem("SipUsername", ""));
11081
+
11082
+    setTimeout(function() {
11083
+
11084
+       // Check if there are any configured external video conference users
11085
+       var externalLinks = getDbItem("externalUserConfElem", "");
11086
+
11087
+       if (typeof externalLinks !== 'undefined' && externalLinks != null && externalLinks != 0) {
11088
+
11089
+           checkExternalLinks();
11090
+
11091
+       } else {
11092
+           Unregister();
11093
+           console.log("Signing Out ...");
11094
+           localStorage.clear();
11095
+           if (winVideoConf != null) {
11096
+               winVideoConf.close();
11097
+           }
11098
+           window.open('https://' + window.location.host + '/logout.php', '_self');
11099
+       }
11100
+    }, 100);
11101
+}
11102
+
11103
+function ToggleAutoAnswer(){
11104
+    if(AutoAnswerPolicy == "disabled"){
11105
+        AutoAnswerEnabled = false;
11106
+        console.warn("Policy AutoAnswer: Disabled");
11107
+        return;
11108
+    }
11109
+    AutoAnswerEnabled = (AutoAnswerEnabled == true)? false : true;
11110
+    if(AutoAnswerPolicy == "enabled") AutoAnswerEnabled = true;
11111
+    localDB.setItem("AutoAnswerEnabled", (AutoAnswerEnabled == true)? "1" : "0");
11112
+    console.log("AutoAnswer:", AutoAnswerEnabled);
11113
+}
11114
+function ToggleDoNoDisturb(){
11115
+    if(DoNotDisturbPolicy == "disabled"){
11116
+        DoNotDisturbEnabled = false;
11117
+        console.warn("Policy DoNotDisturb: Disabled");
11118
+        return;
11119
+    }
11120
+    DoNotDisturbEnabled = (DoNotDisturbEnabled == true)? false : true;
11121
+    if(DoNotDisturbPolicy == "enabled") DoNotDisturbEnabled = true;
11122
+    localDB.setItem("DoNotDisturbEnabled", (DoNotDisturbEnabled == true)? "1" : "0");
11123
+    $("#dereglink").attr("class", (DoNotDisturbEnabled == true)? "dotDoNotDisturb" : "dotOnline" );
11124
+    console.log("DoNotDisturb", DoNotDisturbEnabled);
11125
+}
11126
+function ToggleCallWaiting(){
11127
+    if(CallWaitingPolicy == "disabled"){
11128
+        CallWaitingEnabled = false;
11129
+        console.warn("Policy CallWaiting: Disabled");
11130
+        return;
11131
+    }
11132
+    CallWaitingEnabled = (CallWaitingEnabled == true)? false : true;
11133
+    if(CallWaitingPolicy == "enabled") CallWaitingPolicy = true;
11134
+    localDB.setItem("CallWaitingEnabled", (CallWaitingEnabled == true)? "1" : "0");
11135
+    console.log("CallWaiting", CallWaitingEnabled);
11136
+}
11137
+function ToggleRecordAllCalls(){
11138
+    if(CallRecordingPolicy == "disabled"){
11139
+        RecordAllCalls = false;
11140
+        console.warn("Policy CallRecording: Disabled");
11141
+        return;
11142
+    }
11143
+    RecordAllCalls = (RecordAllCalls == true)? false : true;
11144
+    if(CallRecordingPolicy == "enabled") RecordAllCalls = true;
11145
+    localDB.setItem("RecordAllCalls", (RecordAllCalls == true)? "1" : "0");
11146
+    console.log("RecordAllCalls", RecordAllCalls);
11147
+}
11148
+
11149
+function ShowBuddyProfileMenu(buddy, obj, typeStr){
11150
+
11151
+    $.jeegoopopup.close();
11152
+
11153
+    leftPos = event.pageX - 60;
11154
+    topPos = event.pageY + 45;
11155
+
11156
+    var buddyObj = FindBuddyByIdentity(buddy);
11157
+
11158
+    if (typeStr == "extension") {
11159
+
11160
+        var html = "<div style=\"width:200px; cursor:pointer\" onclick=\"EditBuddyWindow('"+ buddy +"')\">";
11161
+        html += "<div class=\"buddyProfilePic\" style=\"background-image:url('"+ getPicture(buddy, "extension") +"')\"></div>";
11162
+        html += "<div id=ProfileInfo style=\"text-align:center\"><i class=\"fa fa-spinner fa-spin\"></i></div>"
11163
+        html += "</div>";
11164
+
11165
+        $.jeegoopopup.open({
11166
+                html: html,
11167
+                width: '200',
11168
+                height: 'auto',
11169
+                left: leftPos,
11170
+                top: topPos,
11171
+                scrolling: 'no',
11172
+                skinClass: 'jg_popup_basic',
11173
+                contentClass: 'showContactDetails',
11174
+                overlay: true,
11175
+                opacity: 0,
11176
+                draggable: true,
11177
+                resizable: false,
11178
+                fadeIn: 0
11179
+        });
11180
+      
11181
+        // Done
11182
+        $("#ProfileInfo").html("");
11183
+
11184
+        $("#ProfileInfo").append("<div class=ProfileTextLarge style=\"margin-top:15px\">"+ buddyObj.CallerIDName +"</div>");
11185
+        $("#ProfileInfo").append("<div class=ProfileTextMedium>"+ buddyObj.Desc +"</div>");
11186
+
11187
+        $("#ProfileInfo").append("<div class=ProfileTextSmall style=\"margin-top:15px\">"+ lang.extension_number +":</div>");
11188
+        $("#ProfileInfo").append("<div class=ProfileTextMedium>"+ buddyObj.ExtNo +" </div>");
11189
+
11190
+        if(buddyObj.Email && buddyObj.Email != "null" && buddyObj.Email != "undefined"){
11191
+            $("#ProfileInfo").append("<div class=ProfileTextSmall style=\"margin-top:15px\">"+ lang.email +":</div>");
11192
+            $("#ProfileInfo").append("<div class=ProfileTextMedium>"+ buddyObj.Email +" </div>");
11193
+        }
11194
+        if(buddyObj.MobileNumber && buddyObj.MobileNumber != "null" && buddyObj.MobileNumber != "undefined"){
11195
+            $("#ProfileInfo").append("<div class=ProfileTextSmall style=\"margin-top:15px\">"+ lang.mobile +":</div>");
11196
+            $("#ProfileInfo").append("<div class=ProfileTextMedium>"+ buddyObj.MobileNumber +" </div>");
11197
+        }
11198
+        if(buddyObj.ContactNumber1 && buddyObj.ContactNumber1 != "null" && buddyObj.ContactNumber1 != "undefined"){
11199
+            $("#ProfileInfo").append("<div class=ProfileTextSmall style=\"margin-top:15px\">"+ lang.alternative_contact +":</div>");
11200
+            $("#ProfileInfo").append("<div class=ProfileTextMedium>"+ buddyObj.ContactNumber1 +" </div>");
11201
+        }
11202
+        if(buddyObj.ContactNumber2 && buddyObj.ContactNumber2 != "null" && buddyObj.ContactNumber2 != "undefined"){
11203
+            $("#ProfileInfo").append("<div class=ProfileTextSmall style=\"margin-top:15px\">"+ lang.alternative_contact +":</div>");
11204
+            $("#ProfileInfo").append("<div class=ProfileTextMedium>"+ buddyObj.ContactNumber2 +" </div>");
11205
+        }
11206
+
11207
+    } else if (typeStr == "contact") {
11208
+
11209
+        var html = "<div style=\"width:200px; cursor:pointer\" onclick=\"EditBuddyWindow('"+ buddy +"')\">";
11210
+        html += "<div class=\"buddyProfilePic\" style=\"background-image:url('"+ getPicture(buddy, "contact") +"')\"></div>";
11211
+        html += "<div id=ProfileInfo style=\"text-align:center\"><i class=\"fa fa-spinner fa-spin\"></i></div>"
11212
+        html += "</div>";
11213
+
11214
+        $.jeegoopopup.open({
11215
+                html: html,
11216
+                width: '200',
11217
+                height: 'auto',
11218
+                left: leftPos,
11219
+                top: topPos,
11220
+                scrolling: 'no',
11221
+                skinClass: 'jg_popup_basic',
11222
+                contentClass: 'showContactDetails',
11223
+                overlay: true,
11224
+                opacity: 0,
11225
+                draggable: true,
11226
+                resizable: false,
11227
+                fadeIn: 0
11228
+        });
11229
+
11230
+        $("#ProfileInfo").html("");
11231
+        $("#ProfileInfo").append("<div class=ProfileTextLarge style=\"margin-top:15px\">"+ buddyObj.CallerIDName +"</div>");
11232
+        $("#ProfileInfo").append("<div class=ProfileTextMedium>"+ buddyObj.Desc +"</div>");
11233
+
11234
+        if(buddyObj.Email && buddyObj.Email != "null" && buddyObj.Email != "undefined"){
11235
+            $("#ProfileInfo").append("<div class=ProfileTextSmall style=\"margin-top:15px\">"+ lang.email +":</div>");
11236
+            $("#ProfileInfo").append("<div class=ProfileTextMedium>"+ buddyObj.Email +" </div>");
11237
+        }
11238
+        if(buddyObj.MobileNumber && buddyObj.MobileNumber != "null" && buddyObj.MobileNumber != "undefined"){
11239
+            $("#ProfileInfo").append("<div class=ProfileTextSmall style=\"margin-top:15px\">"+ lang.mobile +":</div>");
11240
+            $("#ProfileInfo").append("<div class=ProfileTextMedium>"+ buddyObj.MobileNumber +" </div>");
11241
+        }
11242
+        if(buddyObj.ContactNumber1 && buddyObj.ContactNumber1 != "null" && buddyObj.ContactNumber1 != "undefined"){
11243
+            $("#ProfileInfo").append("<div class=ProfileTextSmall style=\"margin-top:15px\">"+ lang.alternative_contact +":</div>");
11244
+            $("#ProfileInfo").append("<div class=ProfileTextMedium>"+ buddyObj.ContactNumber1 +" </div>");
11245
+        }
11246
+        if(buddyObj.ContactNumber2 && buddyObj.ContactNumber2 != "null" && buddyObj.ContactNumber2 != "undefined"){
11247
+            $("#ProfileInfo").append("<div class=ProfileTextSmall style=\"margin-top:15px\">"+ lang.alternative_contact +":</div>");
11248
+            $("#ProfileInfo").append("<div class=ProfileTextMedium>"+ buddyObj.ContactNumber2 +" </div>");
11249
+        }
11250
+
11251
+    } else if (typeStr == "group") {
11252
+
11253
+        var html = "<div style=\"width:200px; cursor:pointer\" onclick=\"EditBuddyWindow('"+ buddy +"')\">";
11254
+        html += "<div class=\"buddyProfilePic\" style=\"background-image:url('"+ getPicture(buddy, "group") +"')\"></div>";
11255
+        html += "<div id=ProfileInfo style=\"text-align:center\"><i class=\"fa fa-spinner fa-spin\"></i></div>"
11256
+        html += "</div>";
11257
+
11258
+        $.jeegoopopup.open({
11259
+                html: html,
11260
+                width: '200',
11261
+                height: 'auto',
11262
+                left: leftPos,
11263
+                top: topPos,
11264
+                scrolling: 'no',
11265
+                skinClass: 'jg_popup_basic',
11266
+                contentClass: 'showContactDetails',
11267
+                overlay: true,
11268
+                opacity: 0,
11269
+                draggable: true,
11270
+                resizable: false,
11271
+                fadeIn: 0
11272
+        });
11273
+
11274
+        $("#ProfileInfo").html("");
11275
+
11276
+        $("#ProfileInfo").append("<div class=ProfileTextLarge style=\"margin-top:15px\">"+ buddyObj.CallerIDName +"</div>");
11277
+        $("#ProfileInfo").append("<div class=ProfileTextMedium>"+ buddyObj.Desc +"</div>");
11278
+    }
11279
+
11280
+    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); });
11281
+    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); } });
11282
+}
11283
+
11284
+// Device and Settings
11285
+// ===================
11286
+function ChangeSettings(lineNum, obj){
11287
+
11288
+    var leftPos = event.pageX - 138;
11289
+    var topPos = event.pageY + 28;
11290
+
11291
+    if (($(window).height() - event.pageY) < 300) { topPos = event.pageY - 170; }
11292
+
11293
+    // Check if you are in a call
11294
+    var lineObj = FindLineByNumber(lineNum);
11295
+    if(lineObj == null || lineObj.SipSession == null) return;
11296
+    var session = lineObj.SipSession;
11297
+
11298
+    var html = "<div id=DeviceSelector style=\"width:250px\"></div>";
11299
+
11300
+    $.jeegoopopup.open({
11301
+                html: html,
11302
+                width: "auto",
11303
+                height: "auto",
11304
+                left: leftPos,
11305
+                top: topPos,
11306
+                scrolling: 'no',
11307
+                skinClass: 'jg_popup_basic',
11308
+                contentClass: 'callSettingsContent',
11309
+                overlay: true,
11310
+                opacity: 0,
11311
+                draggable: true,
11312
+                resizable: false,
11313
+                fadeIn: 0
11314
+    });
11315
+
11316
+    var audioSelect = $('<select/>');
11317
+    audioSelect.prop("id", "audioSrcSelect");
11318
+    audioSelect.css("width", "100%");
11319
+
11320
+    var videoSelect = $('<select/>');
11321
+    videoSelect.prop("id", "videoSrcSelect");
11322
+    videoSelect.css("width", "100%");
11323
+
11324
+    var speakerSelect = $('<select/>');
11325
+    speakerSelect.prop("id", "audioOutputSelect");
11326
+    speakerSelect.css("width", "100%");
11327
+
11328
+    var ringerSelect = $('<select/>');
11329
+    ringerSelect.prop("id", "ringerSelect");
11330
+    ringerSelect.css("width", "100%");
11331
+
11332
+    // Handle Audio Source changes (Microphone)
11333
+    audioSelect.change(function() {
11334
+
11335
+        console.log("Call to change Microphone: ", this.value);
11336
+
11337
+        // First Stop Recording the call
11338
+        var mustRestartRecording = false;
11339
+        if(session.data.mediaRecorder && session.data.mediaRecorder.state == "recording"){
11340
+            StopRecording(lineNum, true);
11341
+            mustRestartRecording = true;
11342
+        }
11343
+
11344
+        // Stop Monitoring
11345
+        if(lineObj.LocalSoundMeter) lineObj.LocalSoundMeter.stop();
11346
+
11347
+        // Save Setting
11348
+        session.data.AudioSourceDevice = this.value;
11349
+
11350
+        var constraints = {
11351
+            audio: {
11352
+                deviceId: (this.value != "default")? { exact: this.value } : "default"
11353
+            },
11354
+            video: false
11355
+        }
11356
+        navigator.mediaDevices.getUserMedia(constraints).then(function(newStream){
11357
+            // Assume that since we are selecting from a dropdown, this is possible
11358
+            var newMediaTrack = newStream.getAudioTracks()[0];
11359
+            var pc = session.sessionDescriptionHandler.peerConnection;
11360
+            pc.getSenders().forEach(function (RTCRtpSender) {
11361
+                if(RTCRtpSender.track && RTCRtpSender.track.kind == "audio") {
11362
+                    console.log("Switching Audio Track : "+ RTCRtpSender.track.label + " to "+ newMediaTrack.label);
11363
+                    RTCRtpSender.track.stop(); // Must stop, or this mic will stay in use
11364
+                    RTCRtpSender.replaceTrack(newMediaTrack).then(function(){
11365
+                        // Start recording again
11366
+                        if(mustRestartRecording) StartRecording(lineNum);
11367
+                        // Monitor audio stream
11368
+                        lineObj.LocalSoundMeter = StartLocalAudioMediaMonitoring(lineNum, session);
11369
+                    }).catch(function(e){
11370
+                        console.error("Error replacing track: ", e);
11371
+                    });
11372
+                }
11373
+            });
11374
+        }).catch(function(e){
11375
+            console.error("Error on getUserMedia");
11376
+        });
11377
+    });
11378
+
11379
+    // Handle output change (speaker)
11380
+    speakerSelect.change(function() {
11381
+        console.log("Call to change Speaker: ", this.value);
11382
+
11383
+        // Save Setting
11384
+        session.data.AudioOutputDevice = this.value;
11385
+
11386
+        // Also change the sinkId
11387
+        // ======================
11388
+        var sinkId = this.value;
11389
+        console.log("Attempting to set Audio Output SinkID for line "+ lineNum +" [" + sinkId + "]");
11390
+
11391
+        // Remote audio
11392
+        var element = $("#line-"+ lineNum +"-remoteAudio").get(0);
11393
+        if (element) {
11394
+            if (typeof element.sinkId !== 'undefined') {
11395
+                element.setSinkId(sinkId).then(function(){
11396
+                    console.log("sinkId applied: "+ sinkId);
11397
+                }).catch(function(e){
11398
+                    console.warn("Error using setSinkId: ", e);
11399
+                });
11400
+            } else {
11401
+                console.warn("setSinkId() is not possible using this browser.")
11402
+            }
11403
+        }
11404
+    });
11405
+
11406
+    // Handle video input change (WebCam)
11407
+    videoSelect.change(function(){
11408
+        console.log("Call to change WebCam");
11409
+
11410
+        switchVideoSource(lineNum, this.value);
11411
+    });
11412
+
11413
+    // Load Devices
11414
+    if(!navigator.mediaDevices) {
11415
+        console.warn("navigator.mediaDevices not possible.");
11416
+        return;
11417
+    }
11418
+
11419
+    for (var i = 0; i < AudioinputDevices.length; ++i) {
11420
+        var deviceInfo = AudioinputDevices[i];
11421
+        var devideId = deviceInfo.deviceId;
11422
+        var DisplayName = (deviceInfo.label)? deviceInfo.label : "";
11423
+        if(DisplayName.indexOf("(") > 0) DisplayName = DisplayName.substring(0,DisplayName.indexOf("("));
11424
+
11425
+        // Create Option
11426
+        var option = $('<option/>');
11427
+        option.prop("value", devideId);
11428
+        option.text((DisplayName != "")? DisplayName : "Microphone");
11429
+        if(session.data.AudioSourceDevice == devideId) option.prop("selected", true);
11430
+        audioSelect.append(option);
11431
+    }
11432
+    for (var i = 0; i < VideoinputDevices.length; ++i) {
11433
+        var deviceInfo = VideoinputDevices[i];
11434
+        var devideId = deviceInfo.deviceId;
11435
+        var DisplayName = (deviceInfo.label)? deviceInfo.label : "";
11436
+        if(DisplayName.indexOf("(") > 0) DisplayName = DisplayName.substring(0,DisplayName.indexOf("("));
11437
+
11438
+        // Create Option
11439
+        var option = $('<option/>');
11440
+        option.prop("value", devideId);
11441
+        option.text((DisplayName != "")? DisplayName : "Webcam");
11442
+        if(session.data.VideoSourceDevice == devideId) option.prop("selected", true);
11443
+        videoSelect.append(option);
11444
+    }
11445
+    if(HasSpeakerDevice){
11446
+        for (var i = 0; i < SpeakerDevices.length; ++i) {
11447
+            var deviceInfo = SpeakerDevices[i];
11448
+            var devideId = deviceInfo.deviceId;
11449
+            var DisplayName = (deviceInfo.label)? deviceInfo.label : "";
11450
+            if(DisplayName.indexOf("(") > 0) DisplayName = DisplayName.substring(0,DisplayName.indexOf("("));
11451
+
11452
+            // Create Option
11453
+            var option = $('<option/>');
11454
+            option.prop("value", devideId);
11455
+            option.text((DisplayName != "")? DisplayName : "Speaker"); 
11456
+            if(session.data.AudioOutputDevice == devideId) option.prop("selected", true);
11457
+            speakerSelect.append(option);
11458
+        }
11459
+    }
11460
+
11461
+    // Mic Serttings
11462
+    $("#DeviceSelector").append("<div class=callSettingsDvs>"+ lang.microphone +": </div>");
11463
+    $("#DeviceSelector").append(audioSelect);
11464
+    
11465
+    // Speaker
11466
+    if(HasSpeakerDevice){
11467
+        $("#DeviceSelector").append("<div class=callSettingsDvs>"+ lang.speaker +": </div>");
11468
+        $("#DeviceSelector").append(speakerSelect);
11469
+    }
11470
+    // Camera
11471
+    if(session.data.withvideo == true){
11472
+        $("#DeviceSelector").append("<div class=callSettingsDvs>"+ lang.camera +": </div>");
11473
+        $("#DeviceSelector").append(videoSelect);
11474
+    }
11475
+
11476
+    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); });
11477
+    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); } });
11478
+}
11479
+
11480
+// Media Presentation
11481
+// ==================
11482
+function PresentCamera(lineNum){
11483
+    var lineObj = FindLineByNumber(lineNum);
11484
+    if(lineObj == null || lineObj.SipSession == null){
11485
+        console.warn("Line or Session is Null.");
11486
+        return;
11487
+    }
11488
+    var session = lineObj.SipSession;
11489
+
11490
+    $("#line-"+ lineNum +"-src-camera").prop("disabled", true);
11491
+    $("#line-"+ lineNum +"-src-canvas").prop("disabled", false);
11492
+    $("#line-"+ lineNum +"-src-desktop").prop("disabled", false);
11493
+    $("#line-"+ lineNum +"-src-video").prop("disabled", false);
11494
+    $("#line-"+ lineNum +"-src-blank").prop("disabled", false);
11495
+
11496
+    $("#line-"+ lineNum + "-scratchpad-container").hide();
11497
+    RemoveScratchpad(lineNum);
11498
+    $("#line-"+ lineNum +"-sharevideo").hide();
11499
+    $("#line-"+ lineNum +"-sharevideo").get(0).pause();
11500
+    $("#line-"+ lineNum +"-sharevideo").get(0).removeAttribute('src');
11501
+    $("#line-"+ lineNum +"-sharevideo").get(0).load();
11502
+    window.clearInterval(session.data.videoResampleInterval);
11503
+
11504
+    $("#line-"+ lineNum + "-localVideo").show();
11505
+    $("#line-"+ lineNum + "-remoteVideo").appendTo("#line-"+ lineNum + "-stage-container");
11506
+
11507
+    switchVideoSource(lineNum, session.data.VideoSourceDevice);
11508
+}
11509
+function PresentScreen(lineNum){
11510
+    var lineObj = FindLineByNumber(lineNum);
11511
+    if(lineObj == null || lineObj.SipSession == null){
11512
+        console.warn("Line or Session is Null.");
11513
+        return;
11514
+    }
11515
+    var session = lineObj.SipSession;
11516
+
11517
+    $("#line-"+ lineNum +"-src-camera").prop("disabled", false);
11518
+    $("#line-"+ lineNum +"-src-canvas").prop("disabled", false);
11519
+    $("#line-"+ lineNum +"-src-desktop").prop("disabled", true);
11520
+    $("#line-"+ lineNum +"-src-video").prop("disabled", false);
11521
+    $("#line-"+ lineNum +"-src-blank").prop("disabled", false);
11522
+
11523
+    $("#line-"+ lineNum + "-scratchpad-container").hide();
11524
+    RemoveScratchpad(lineNum);
11525
+    $("#line-"+ lineNum +"-sharevideo").hide();
11526
+    $("#line-"+ lineNum +"-sharevideo").get(0).pause();
11527
+    $("#line-"+ lineNum +"-sharevideo").get(0).removeAttribute('src');
11528
+    $("#line-"+ lineNum +"-sharevideo").get(0).load();
11529
+    window.clearInterval(session.data.videoResampleInterval);
11530
+
11531
+    $("#line-"+ lineNum + "-localVideo").hide();
11532
+    $("#line-"+ lineNum + "-remoteVideo").appendTo("#line-"+ lineNum + "-stage-container");
11533
+
11534
+    ShareScreen(lineNum);
11535
+}
11536
+function PresentScratchpad(lineNum){
11537
+    var lineObj = FindLineByNumber(lineNum);
11538
+    if(lineObj == null || lineObj.SipSession == null){
11539
+        console.warn("Line or Session is Null.");
11540
+        return;
11541
+    }
11542
+    var session = lineObj.SipSession;
11543
+
11544
+    $("#line-"+ lineNum +"-src-camera").prop("disabled", false);
11545
+    $("#line-"+ lineNum +"-src-canvas").prop("disabled", true);
11546
+    $("#line-"+ lineNum +"-src-desktop").prop("disabled", false);
11547
+    $("#line-"+ lineNum +"-src-video").prop("disabled", false);
11548
+    $("#line-"+ lineNum +"-src-blank").prop("disabled", false);
11549
+
11550
+    $("#line-"+ lineNum + "-scratchpad-container").hide();
11551
+    RemoveScratchpad(lineNum);
11552
+    $("#line-"+ lineNum +"-sharevideo").hide();
11553
+    $("#line-"+ lineNum +"-sharevideo").get(0).pause();
11554
+    $("#line-"+ lineNum +"-sharevideo").get(0).removeAttribute('src');
11555
+    $("#line-"+ lineNum +"-sharevideo").get(0).load();
11556
+    window.clearInterval(session.data.videoResampleInterval);
11557
+
11558
+    $("#line-"+ lineNum + "-localVideo").hide();
11559
+    $("#line-"+ lineNum + "-remoteVideo").appendTo("#line-"+ lineNum + "-preview-container");
11560
+
11561
+    SendCanvas(lineNum);
11562
+}
11563
+function PresentVideo(lineNum){
11564
+
11565
+    var lineObj = FindLineByNumber(lineNum);
11566
+    if(lineObj == null || lineObj.SipSession == null){
11567
+        console.warn("Line or Session is Null.");
11568
+        return;
11569
+    }
11570
+    var session = lineObj.SipSession;
11571
+
11572
+    $.jeegoopopup.close();
11573
+
11574
+    var presentVideoHtml = "<div>";
11575
+    presentVideoHtml += '<div id="windowCtrls"><img id="closeImg" src="images/3_close.svg" title="Close" /></div>';
11576
+    presentVideoHtml += "<label for=SelectVideoToSend class=customBrowseButton style=\"display: block; margin: 26px auto;\">Select File</label>";
11577
+    presentVideoHtml += "<div class=\"UiWindowField\"><input type=file  accept=\"video/*\" id=SelectVideoToSend></div>";
11578
+    presentVideoHtml += "</div>";
11579
+
11580
+    $.jeegoopopup.open({
11581
+                html: presentVideoHtml,
11582
+                width: '180',
11583
+                height: '80',
11584
+                center: true,
11585
+                scrolling: 'no',
11586
+                skinClass: 'jg_popup_basic',
11587
+                overlay: true,
11588
+                opacity: 0,
11589
+                draggable: true,
11590
+                resizable: false,
11591
+                fadeIn: 0
11592
+    });
11593
+
11594
+    $("#SelectVideoToSend").on('change', function(event){
11595
+            var input = event.target;
11596
+            if(input.files.length >= 1){
11597
+
11598
+                $.jeegoopopup.close();
11599
+
11600
+                // Send Video (Can only send one file)
11601
+                SendVideo(lineNum, URL.createObjectURL(input.files[0]));
11602
+            }
11603
+            else {
11604
+                console.warn("Please Select a file to present.");
11605
+            }
11606
+    });
11607
+
11608
+    $("#closeImg").click(function() { $.jeegoopopup.close(); });
11609
+    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); });
11610
+    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); } });
11611
+}
11612
+function PresentBlank(lineNum){
11613
+    var lineObj = FindLineByNumber(lineNum);
11614
+    if(lineObj == null || lineObj.SipSession == null){
11615
+        console.warn("Line or Session is Null.");
11616
+        return;
11617
+    }
11618
+    var session = lineObj.SipSession;
11619
+
11620
+    $("#line-"+ lineNum +"-src-camera").prop("disabled", false);
11621
+    $("#line-"+ lineNum +"-src-canvas").prop("disabled", false);
11622
+    $("#line-"+ lineNum +"-src-desktop").prop("disabled", false);
11623
+    $("#line-"+ lineNum +"-src-video").prop("disabled", false);
11624
+    $("#line-"+ lineNum +"-src-blank").prop("disabled", true);
11625
+    
11626
+    $("#line-"+ lineNum + "-scratchpad-container").hide();
11627
+    RemoveScratchpad(lineNum);
11628
+    $("#line-"+ lineNum +"-sharevideo").hide();
11629
+    $("#line-"+ lineNum +"-sharevideo").get(0).pause();
11630
+    $("#line-"+ lineNum +"-sharevideo").get(0).removeAttribute('src');
11631
+    $("#line-"+ lineNum +"-sharevideo").get(0).load();
11632
+    window.clearInterval(session.data.videoResampleInterval);
11633
+
11634
+    $("#line-"+ lineNum + "-localVideo").hide();
11635
+    $("#line-"+ lineNum + "-remoteVideo").appendTo("#line-"+ lineNum + "-stage-container");
11636
+
11637
+    DisableVideoStream(lineNum);
11638
+}
11639
+function RemoveScratchpad(lineNum){
11640
+    var scratchpad = GetCanvas("line-" + lineNum + "-scratchpad");
11641
+    if(scratchpad != null){
11642
+        window.clearInterval(scratchpad.redrawIntrtval);
11643
+
11644
+        RemoveCanvas("line-" + lineNum + "-scratchpad");
11645
+        $("#line-"+ lineNum + "-scratchpad-container").empty();
11646
+
11647
+        scratchpad = null;
11648
+    }
11649
+}
11650
+
11651
+// Call Statistics
11652
+// ===============
11653
+function ShowCallStats(lineNum, obj){
11654
+    console.log("Show Call Stats");
11655
+    $("#line-"+ lineNum +"-AudioStats").show(300);
11656
+}
11657
+function HideCallStats(lineNum, obj){
11658
+    console.log("Hide Call Stats");
11659
+    $("#line-"+ lineNum +"-AudioStats").hide(300);
11660
+}
11661
+
11662
+// Chatting
11663
+// ========
11664
+function chatOnbeforepaste(event, obj, buddy){
11665
+    console.log("Handle paste, checking for Images...");
11666
+    var items = (event.clipboardData || event.originalEvent.clipboardData).items;
11667
+
11668
+    // Find pasted image among pasted items
11669
+    var preventDefault = false;
11670
+    for (var i = 0; i < items.length; i++) {
11671
+        if (items[i].type.indexOf("image") === 0) {
11672
+            console.log("Image found! Opening image editor...");
11673
+
11674
+            var blob = items[i].getAsFile();
11675
+
11676
+            // Read the image in
11677
+            var reader = new FileReader();
11678
+            reader.onload = function (event) {
11679
+
11680
+                // Image has loaded, open Image Preview Editor
11681
+                // ===========================================
11682
+                console.log("Image loaded... setting placeholder...");
11683
+                var placeholderImage = new Image();
11684
+                placeholderImage.onload = function () {
11685
+
11686
+                    console.log("Placeholder loaded... CreateImageEditor...");
11687
+
11688
+                    CreateImageEditor(buddy, placeholderImage);
11689
+                }
11690
+                placeholderImage.src = event.target.result;
11691
+            }
11692
+            reader.readAsDataURL(blob);
11693
+
11694
+            preventDefault = true;
11695
+            continue;
11696
+        }
11697
+    }
11698
+
11699
+    // Pevent default if you found an image
11700
+    if (preventDefault) event.preventDefault();
11701
+}
11702
+function chatOnkeydown(event, obj, buddy) {
11703
+
11704
+    var keycode = (event.keyCode ? event.keyCode : event.which);
11705
+    if (keycode == '13'){
11706
+        if(event.ctrlKey) {
11707
+            SendChatMessage(buddy);
11708
+            return false;
11709
+        }
11710
+    }
11711
+}
11712
+
11713
+function ReformatMessage(str) {
11714
+    var msg = str;
11715
+    // Simple tex=>HTML 
11716
+    msg = msg.replace(/</gi, "&lt;");
11717
+    msg = msg.replace(/>/gi, "&gt;");
11718
+    msg = msg.replace(/\n/gi, "<br>");
11719
+    // Emojy
11720
+    // Skype: :) :( :D :O ;) ;( (:| :| :P :$ :^) |-) |-( :x ]:)
11721
+    // (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)
11722
+    msg = msg.replace(/(:\)|:\-\)|:o\))/g, String.fromCodePoint(0x1F642));     // :) :-) :o)
11723
+    msg = msg.replace(/(:\(|:\-\(|:o\()/g, String.fromCodePoint(0x1F641));     // :( :-( :o(
11724
+    msg = msg.replace(/(;\)|;\-\)|;o\))/g, String.fromCodePoint(0x1F609));     // ;) ;-) ;o)
11725
+    msg = msg.replace(/(:'\(|:'\-\()/g, String.fromCodePoint(0x1F62A));        // :'( :'‑(
11726
+    msg = msg.replace(/(:'\(|:'\-\()/g, String.fromCodePoint(0x1F602));        // :') :'‑)
11727
+    msg = msg.replace(/(:\$)/g, String.fromCodePoint(0x1F633));                // :$
11728
+    msg = msg.replace(/(>:\()/g, String.fromCodePoint(0x1F623));               // >:(
11729
+    msg = msg.replace(/(:\×)/g, String.fromCodePoint(0x1F618));                // :×
11730
+    msg = msg.replace(/(:\O|:\‑O)/g, String.fromCodePoint(0x1F632));             // :O :‑O
11731
+    msg = msg.replace(/(:P|:\-P|:p|:\-p)/g, String.fromCodePoint(0x1F61B));      // :P :-P :p :-p
11732
+    msg = msg.replace(/(;P|;\-P|;p|;\-p)/g, String.fromCodePoint(0x1F61C));      // ;P ;-P ;p ;-p
11733
+    msg = msg.replace(/(:D|:\-D)/g, String.fromCodePoint(0x1F60D));             // :D :-D
11734
+
11735
+    msg = msg.replace(/(\(like\))/g, String.fromCodePoint(0x1F44D));           // (like)
11736
+
11737
+    // Make clickable Hyperlinks
11738
+    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) {
11739
+          var niceLink = (x.length > 50) ? x.substring(0, 47) + "..." : x;
11740
+          var rtn = "<A target=_blank class=previewHyperlink href=\"" + x + "\">" + niceLink + "</A>";
11741
+          return rtn;
11742
+    });
11743
+    return msg;
11744
+}
11745
+function getPicture(buddy, typestr){
11746
+    if(buddy == "profilePicture"){
11747
+        // Special handling for profile image
11748
+        var dbImg = localDB.getItem("profilePicture");
11749
+        if(dbImg == null){
11750
+            return hostingPrefex + "images/default.png";
11751
+        }
11752
+        else {
11753
+            return dbImg; 
11754
+        }
11755
+    }
11756
+
11757
+    typestr = (typestr)? typestr : "extension";
11758
+
11759
+    var buddyObj = FindBuddyByIdentity(buddy);
11760
+    if(buddyObj.imageObjectURL != ""){
11761
+        // Use Cache
11762
+        return buddyObj.imageObjectURL;
11763
+    }
11764
+
11765
+    var dbImg = localDB.getItem("img-"+ buddy +"-"+ typestr);
11766
+
11767
+    if(dbImg == null){
11768
+        return hostingPrefex + "images/default.png";
11769
+    } else {
11770
+        buddyObj.imageObjectURL = URL.createObjectURL(base64toBlob(dbImg, 'image/png'));
11771
+        return buddyObj.imageObjectURL;
11772
+    }
11773
+}
11774
+
11775
+// Image Editor
11776
+// ============
11777
+function CreateImageEditor(buddy, placeholderImage){
11778
+    // Show Interface
11779
+    // ==============
11780
+    console.log("Setting Up ImageEditor...");
11781
+    if($("#contact-" + buddy + "-imagePastePreview").is(":visible")) {
11782
+        console.log("Resetting ImageEditor...");
11783
+        $("#contact-" + buddy + "-imagePastePreview").empty();
11784
+        RemoveCanvas("contact-" + buddy + "-imageCanvas")
11785
+    } else {
11786
+        $("#contact-" + buddy + "-imagePastePreview").show();
11787
+    }
11788
+    // Create UI
11789
+    // =========
11790
+    var toolBarDiv = $('<div/>');
11791
+    toolBarDiv.css("margin-bottom", "5px")
11792
+    toolBarDiv.append('<button class="toolBarButtons" title="Select" onclick="ImageEditor_Select(\''+ buddy +'\')"><i class="fa fa-mouse-pointer"></i></button>');
11793
+    toolBarDiv.append('&nbsp;|&nbsp;');
11794
+    toolBarDiv.append('<button class="toolBarButtons" title="Draw" onclick="ImageEditor_FreedrawPen(\''+ buddy +'\')"><i class="fa fa-pencil"></i></button>');
11795
+    toolBarDiv.append('<button class="toolBarButtons" title="Paint" onclick="ImageEditor_FreedrawPaint(\''+ buddy +'\')"><i class="fa fa-paint-brush"></i></button>');
11796
+    toolBarDiv.append('&nbsp;|&nbsp;');
11797
+    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>');
11798
+    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>');
11799
+    toolBarDiv.append('&nbsp;|&nbsp;');
11800
+    toolBarDiv.append('<button class="toolBarButtons" title="Add Circle" onclick="ImageEditor_AddCircle(\''+ buddy +'\')"><i class="fa fa-circle"></i></button>');
11801
+    toolBarDiv.append('<button class="toolBarButtons" title="Add Rectangle" onclick="ImageEditor_AddRectangle(\''+ buddy +'\')"><i class="fa fa-stop"></i></button>');
11802
+    toolBarDiv.append('<button class="toolBarButtons" title="Add Triangle" onclick="ImageEditor_AddTriangle(\''+ buddy +'\')"><i class="fa fa-play"></i></button>');
11803
+    toolBarDiv.append('<button class="toolBarButtons" title="Add Emoji" onclick="ImageEditor_SetectEmoji(\''+ buddy +'\')"><i class="fa fa-smile-o"></i></button>');
11804
+    toolBarDiv.append('<button class="toolBarButtons" title="Add Text" onclick="ImageEditor_AddText(\''+ buddy +'\')"><i class="fa fa-font"></i></button>');
11805
+    toolBarDiv.append('<button class="toolBarButtons" title="Delete Selected Items" onclick="ImageEditor_Clear(\''+ buddy +'\')"><i class="fa fa-times"></i></button>');
11806
+    toolBarDiv.append('<button class="toolBarButtons" title="Clear All" onclick="ImageEditor_ClearAll(\''+ buddy +'\')"><i class="fa fa-trash"></i></button>');
11807
+    toolBarDiv.append('&nbsp;|&nbsp;');
11808
+    toolBarDiv.append('<button class="toolBarButtons" title="Pan" onclick="ImageEditor_Pan(\''+ buddy +'\')"><i class="fa fa-hand-paper-o"></i></button>');
11809
+    toolBarDiv.append('<button class="toolBarButtons" title="Zoom In" onclick="ImageEditor_ZoomIn(\''+ buddy +'\')"><i class="fa fa-search-plus"></i></button>');
11810
+    toolBarDiv.append('<button class="toolBarButtons" title="Zoom Out" onclick="ImageEditor_ZoomOut(\''+ buddy +'\')"><i class="fa fa-search-minus"></i></button>');
11811
+    toolBarDiv.append('<button class="toolBarButtons" title="Reset Pan & Zoom" onclick="ImageEditor_ResetZoom(\''+ buddy +'\')"><i class="fa fa-search" aria-hidden="true"></i></button>');
11812
+    toolBarDiv.append('&nbsp;|&nbsp;');
11813
+    toolBarDiv.append('<button class="toolBarButtons" title="Cancel" onclick="ImageEditor_Cancel(\''+ buddy +'\')"><i class="fa fa-times-circle"></i></button>');
11814
+    toolBarDiv.append('<button class="toolBarButtons" title="Send" onclick="ImageEditor_Send(\''+ buddy +'\')"><i class="fa fa-paper-plane"></i></button>');
11815
+    $("#contact-" + buddy + "-imagePastePreview").append(toolBarDiv);
11816
+
11817
+    // Create the canvas
11818
+    // =================
11819
+    var newCanvas = $('<canvas/>');
11820
+    newCanvas.prop("id", "contact-" + buddy + "-imageCanvas");
11821
+    newCanvas.css("border", "1px solid #CCCCCC");
11822
+    $("#contact-" + buddy + "-imagePastePreview").append(newCanvas);
11823
+    console.log("Canvas for ImageEditor created...");
11824
+
11825
+    var imgWidth = placeholderImage.width;
11826
+    var imgHeight = placeholderImage.height;
11827
+    var maxWidth = $("#contact-" + buddy + "-imagePastePreview").width()-2; // for the border
11828
+    var maxHeight = 480;
11829
+    $("#contact-" + buddy + "-imageCanvas").prop("width", maxWidth);
11830
+    $("#contact-" + buddy + "-imageCanvas").prop("height", maxHeight);
11831
+
11832
+    // Handle Initial Zoom
11833
+    var zoomToFitImage = 1;
11834
+    var zoomWidth = 1;
11835
+    var zoomHeight = 1;
11836
+    if(imgWidth > maxWidth || imgHeight > maxHeight)
11837
+    {
11838
+        if(imgWidth > maxWidth)
11839
+        {
11840
+            zoomWidth = (maxWidth / imgWidth);
11841
+        }
11842
+        if(imgHeight > maxHeight)
11843
+        {
11844
+            zoomHeight = (maxHeight / imgHeight);
11845
+            console.log("Scale to fit height: "+ zoomHeight);
11846
+        }
11847
+        zoomToFitImage = Math.min(zoomWidth, zoomHeight) // need the smallest because less is more zoom.
11848
+        console.log("Scale down to fit: "+ zoomToFitImage);
11849
+
11850
+        // Shape the canvas to fit the image and the new zoom
11851
+        imgWidth = imgWidth * zoomToFitImage;
11852
+        imgHeight = imgHeight * zoomToFitImage;
11853
+        console.log("resizing canvas to fit new image size...");
11854
+        $("#contact-" + buddy + "-imageCanvas").prop("width", imgWidth);
11855
+        $("#contact-" + buddy + "-imageCanvas").prop("height", imgHeight);
11856
+    }
11857
+    else {
11858
+        console.log("Image is able to fit, resizing canvas...");
11859
+        $("#contact-" + buddy + "-imageCanvas").prop("width", imgWidth);
11860
+        $("#contact-" + buddy + "-imageCanvas").prop("height", imgHeight);
11861
+    }
11862
+
11863
+    // Fabric Canvas API
11864
+    // =================
11865
+    console.log("Creating fabric API...");
11866
+    var canvas = new fabric.Canvas("contact-" + buddy + "-imageCanvas");
11867
+    canvas.id = "contact-" + buddy + "-imageCanvas";
11868
+    canvas.ToolSelected = "None";
11869
+    canvas.PenColour = "rgb(255, 0, 0)";
11870
+    canvas.PenWidth = 2;
11871
+    canvas.PaintColour = "rgba(227, 230, 3, 0.6)";
11872
+    canvas.PaintWidth = 10;
11873
+    canvas.FillColour = "rgb(255, 0, 0)";
11874
+    canvas.isDrawingMode = false;
11875
+
11876
+    canvas.selectionColor = 'rgba(112,179,233,0.25)';
11877
+    canvas.selectionBorderColor = 'rgba(112,179,233, 0.8)';
11878
+    canvas.selectionLineWidth = 1;
11879
+
11880
+    // Zoom to fit Width or Height
11881
+    // ===========================
11882
+    canvas.setZoom(zoomToFitImage);
11883
+
11884
+    // Canvas Events
11885
+    // =============
11886
+    canvas.on('mouse:down', function(opt) {
11887
+        var evt = opt.e;
11888
+
11889
+        if (this.ToolSelected == "Pan") {
11890
+            this.isDragging = true;
11891
+            this.selection = false;
11892
+            this.lastPosX = evt.clientX;
11893
+            this.lastPosY = evt.clientY;
11894
+        }
11895
+        // Make nicer grab handles
11896
+        if(opt.target != null){
11897
+            if(evt.altKey === true)
11898
+            {
11899
+                opt.target.lockMovementX = true;
11900
+            }
11901
+            if(evt.shiftKey === true)
11902
+            {
11903
+                opt.target.lockMovementY = true;
11904
+            }
11905
+            opt.target.set({
11906
+                transparentCorners: false,
11907
+                borderColor: 'rgba(112,179,233, 0.4)',
11908
+                cornerColor: 'rgba(112,179,233, 0.8)',
11909
+                cornerSize: 6
11910
+            });
11911
+        }
11912
+    });
11913
+    canvas.on('mouse:move', function(opt) {
11914
+        if (this.isDragging) {
11915
+            var e = opt.e;
11916
+            this.viewportTransform[4] += e.clientX - this.lastPosX;
11917
+            this.viewportTransform[5] += e.clientY - this.lastPosY;
11918
+            this.requestRenderAll();
11919
+            this.lastPosX = e.clientX;
11920
+            this.lastPosY = e.clientY;
11921
+        }
11922
+    });
11923
+    canvas.on('mouse:up', function(opt) {
11924
+        this.isDragging = false;
11925
+        this.selection = true;
11926
+        if(opt.target != null){
11927
+            opt.target.lockMovementX = false;
11928
+            opt.target.lockMovementY = false;
11929
+        }
11930
+    });
11931
+    canvas.on('mouse:wheel', function(opt) {
11932
+        var delta = opt.e.deltaY;
11933
+        var pointer = canvas.getPointer(opt.e);
11934
+        var zoom = canvas.getZoom();
11935
+        zoom = zoom + delta/200;
11936
+        if (zoom > 10) zoom = 10;
11937
+        if (zoom < 0.1) zoom = 0.1;
11938
+        canvas.zoomToPoint({ x: opt.e.offsetX, y: opt.e.offsetY }, zoom);
11939
+        opt.e.preventDefault();
11940
+        opt.e.stopPropagation();
11941
+    });
11942
+
11943
+    // Add Image
11944
+    // ==========
11945
+    canvas.backgroundImage = new fabric.Image(placeholderImage);
11946
+
11947
+    CanvasCollection.push(canvas);
11948
+
11949
+    // Add Key Press Events
11950
+    // ====================
11951
+    $("#contact-" + buddy + "-imagePastePreview").keydown(function(evt) {
11952
+        evt = evt || window.event;
11953
+        var key = evt.keyCode;
11954
+        console.log("Key press on Image Editor ("+ buddy +"): "+ key);
11955
+
11956
+        // Delete Key
11957
+        if (key == 46) ImageEditor_Clear(buddy);
11958
+    });
11959
+
11960
+    console.log("ImageEditor: "+ canvas.id +" created");
11961
+
11962
+    ImageEditor_FreedrawPen(buddy);
11963
+}
11964
+function GetCanvas(canvasId){
11965
+    for(var c = 0; c < CanvasCollection.length; c++){
11966
+        try {
11967
+            if(CanvasCollection[c].id == canvasId) return CanvasCollection[c];
11968
+        } catch(e) {
11969
+            console.warn("CanvasCollection.id not available");
11970
+        }
11971
+    }
11972
+    return null;
11973
+}
11974
+function RemoveCanvas(canvasId){
11975
+    for(var c = 0; c < CanvasCollection.length; c++){
11976
+        try{
11977
+            if(CanvasCollection[c].id == canvasId) {
11978
+                console.log("Found Old Canvas, Disposing...");
11979
+
11980
+                CanvasCollection[c].clear()
11981
+                CanvasCollection[c].dispose();
11982
+
11983
+                CanvasCollection[c].id = "--deleted--";
11984
+
11985
+                console.log("CanvasCollection.splice("+ c +", 1)");
11986
+                CanvasCollection.splice(c, 1);
11987
+                break;
11988
+            }
11989
+        }
11990
+        catch(e){ }
11991
+    }
11992
+    console.log("There are "+ CanvasCollection.length +" canvas now.");
11993
+}
11994
+var ImageEditor_Select = function (buddy){
11995
+    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
11996
+    if(canvas != null) {
11997
+        canvas.ToolSelected = "none";
11998
+        canvas.isDrawingMode = false;
11999
+        return true;
12000
+    }
12001
+    return false;
12002
+}
12003
+var ImageEditor_FreedrawPen = function (buddy){
12004
+    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
12005
+    if(canvas != null) {
12006
+        canvas.freeDrawingBrush.color = canvas.PenColour;
12007
+        canvas.freeDrawingBrush.width = canvas.PenWidth;
12008
+        canvas.ToolSelected = "Draw";
12009
+        canvas.isDrawingMode = true;
12010
+        console.log(canvas)
12011
+        return true;
12012
+    }
12013
+    return false;
12014
+}
12015
+var ImageEditor_FreedrawPaint = function (buddy){
12016
+    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
12017
+    if(canvas != null) {
12018
+        canvas.freeDrawingBrush.color = canvas.PaintColour;
12019
+        canvas.freeDrawingBrush.width = canvas.PaintWidth;
12020
+        canvas.ToolSelected = "Paint";
12021
+        canvas.isDrawingMode = true;
12022
+        return true;
12023
+    }
12024
+    return false;
12025
+}
12026
+var ImageEditor_Pan = function (buddy){
12027
+    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
12028
+    if(canvas != null) {
12029
+        canvas.ToolSelected = "Pan";
12030
+        canvas.isDrawingMode = false;
12031
+        return true;
12032
+    }
12033
+    return false;
12034
+}
12035
+var ImageEditor_ResetZoom = function (buddy){
12036
+    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
12037
+    if(canvas != null) {
12038
+        canvas.setZoom(1);
12039
+        canvas.setViewportTransform([1,0,0,1,0,0]);
12040
+        return true;
12041
+    } 
12042
+    return false;
12043
+}
12044
+var ImageEditor_ZoomIn = function (buddy){
12045
+    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
12046
+    if(canvas != null) {
12047
+        var zoom = canvas.getZoom();
12048
+        zoom = zoom + 0.5;
12049
+        if (zoom > 10) zoom = 10;
12050
+        if (zoom < 0.1) zoom = 0.1;
12051
+
12052
+        var point = new fabric.Point(canvas.getWidth() / 2, canvas.getHeight() / 2);
12053
+        var center = fabric.util.transformPoint(point, canvas.viewportTransform);
12054
+
12055
+        canvas.zoomToPoint(point, zoom);
12056
+
12057
+        return true;
12058
+    }
12059
+    return false;
12060
+}
12061
+var ImageEditor_ZoomOut = function (buddy){
12062
+    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
12063
+    if(canvas != null) {
12064
+        var zoom = canvas.getZoom();
12065
+        zoom = zoom - 0.5;
12066
+        if (zoom > 10) zoom = 10;
12067
+        if (zoom < 0.1) zoom = 0.1;
12068
+
12069
+        var point = new fabric.Point(canvas.getWidth() / 2, canvas.getHeight() / 2);
12070
+        var center = fabric.util.transformPoint(point, canvas.viewportTransform);
12071
+
12072
+        canvas.zoomToPoint(point, zoom);
12073
+
12074
+        return true;
12075
+    }
12076
+    return false;
12077
+}
12078
+var ImageEditor_AddCircle = function (buddy){
12079
+    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
12080
+    if(canvas != null) {
12081
+        canvas.ToolSelected = "none";
12082
+        canvas.isDrawingMode = false;
12083
+        var circle = new fabric.Circle({
12084
+            radius: 20, fill: canvas.FillColour
12085
+        })
12086
+        canvas.add(circle);
12087
+        canvas.centerObject(circle);
12088
+        canvas.setActiveObject(circle);
12089
+        return true;
12090
+    }
12091
+    return false;
12092
+}
12093
+var ImageEditor_AddRectangle = function (buddy){
12094
+    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
12095
+    if(canvas != null) {
12096
+        canvas.ToolSelected = "none";
12097
+        canvas.isDrawingMode = false;
12098
+        var rectangle = new fabric.Rect({ 
12099
+            width: 40, height: 40, fill: canvas.FillColour
12100
+        })
12101
+        canvas.add(rectangle);
12102
+        canvas.centerObject(rectangle);
12103
+        canvas.setActiveObject(rectangle);
12104
+        return true;
12105
+    }
12106
+    return false;
12107
+}
12108
+var ImageEditor_AddTriangle = function (buddy){
12109
+    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
12110
+    if(canvas != null) {
12111
+        canvas.ToolSelected = "none";
12112
+        canvas.isDrawingMode = false;
12113
+        var triangle = new fabric.Triangle({
12114
+            width: 40, height: 40, fill: canvas.FillColour
12115
+        })
12116
+        canvas.add(triangle);
12117
+        canvas.centerObject(triangle);
12118
+        canvas.setActiveObject(triangle);
12119
+        return true;
12120
+    }
12121
+    return false;
12122
+}
12123
+var ImageEditor_AddEmoji = function (buddy){
12124
+    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
12125
+    if(canvas != null) {
12126
+        canvas.ToolSelected = "none";
12127
+        canvas.isDrawingMode = false;
12128
+        var text = new fabric.Text(String.fromCodePoint(0x1F642), { fontSize : 24 });
12129
+        canvas.add(text);
12130
+        canvas.centerObject(text);
12131
+        canvas.setActiveObject(text);
12132
+        return true;
12133
+    }
12134
+    return false;
12135
+}
12136
+var ImageEditor_AddText = function (buddy, textString){
12137
+    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
12138
+    if(canvas != null) {
12139
+        canvas.ToolSelected = "none";
12140
+        canvas.isDrawingMode = false;
12141
+        var text = new fabric.IText(textString, { fill: canvas.FillColour, fontFamily: 'arial', fontSize : 18 });
12142
+        canvas.add(text);
12143
+        canvas.centerObject(text);
12144
+        canvas.setActiveObject(text);
12145
+        return true;
12146
+    }
12147
+    return false;
12148
+}
12149
+var ImageEditor_Clear = function (buddy){
12150
+    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
12151
+    if(canvas != null) {
12152
+        canvas.ToolSelected = "none";
12153
+        canvas.isDrawingMode = false;
12154
+
12155
+        var activeObjects = canvas.getActiveObjects();
12156
+        for (var i=0; i<activeObjects.length; i++){
12157
+            canvas.remove(activeObjects[i]);
12158
+        }
12159
+        canvas.discardActiveObject();
12160
+
12161
+        return true;
12162
+    }
12163
+    return false;
12164
+}
12165
+var ImageEditor_ClearAll = function (buddy){
12166
+    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
12167
+    if(canvas != null) {
12168
+        var savedBgImage = canvas.backgroundImage;
12169
+
12170
+        canvas.ToolSelected = "none";
12171
+        canvas.isDrawingMode = false;
12172
+        canvas.clear();
12173
+
12174
+        canvas.backgroundImage = savedBgImage;
12175
+        return true;
12176
+    }
12177
+    return false;
12178
+}
12179
+var ImageEditor_Cancel = function (buddy){
12180
+    console.log("Removing ImageEditor...");
12181
+
12182
+    $("#contact-" + buddy + "-imagePastePreview").empty();
12183
+    RemoveCanvas("contact-" + buddy + "-imageCanvas");
12184
+    $("#contact-" + buddy + "-imagePastePreview").hide();
12185
+}
12186
+var ImageEditor_Send = function (buddy){
12187
+    var canvas = GetCanvas("contact-" + buddy + "-imageCanvas");
12188
+    if(canvas != null) {
12189
+        var imgData = canvas.toDataURL({ format: 'png' });
12190
+        SendImageDataMessage(buddy, imgData);
12191
+        return true;
12192
+    }
12193
+    return false;
12194
+}
12195
+
12196
+// Find something in the message stream
12197
+// ====================================
12198
+function FindSomething(buddy) {
12199
+    $("#contact-" + buddy + "-search").toggle();
12200
+    if($("#contact-" + buddy + "-search").is(":visible") == false){
12201
+        RefreshStream(FindBuddyByIdentity(buddy));
12202
+    }
12203
+    updateScroll(buddy);
12204
+}
12205
+
12206
+// FileShare an Upload
12207
+// ===================
12208
+var allowDradAndDrop = function() {
12209
+    var div = document.createElement('div');
12210
+    return (('draggable' in div) || ('ondragstart' in div && 'ondrop' in div)) && 'FormData' in window && 'FileReader' in window;
12211
+}
12212
+function onFileDragDrop(e, buddy){
12213
+
12214
+    var filesArray = e.dataTransfer.files;
12215
+    console.log("You are about to upload " + filesArray.length + " file.");
12216
+
12217
+    // Clear style
12218
+    $("#contact-"+ buddy +"-ChatHistory").css("outline", "none");
12219
+
12220
+    for (var f = 0; f < filesArray.length; f++){
12221
+        var fileObj = filesArray[f];
12222
+        var reader = new FileReader();
12223
+        reader.onload = function (event) {
12224
+            
12225
+            // Check if the file is under 50MB
12226
+            if(fileObj.size <= 52428800){
12227
+                // Add to Stream
12228
+                // =============
12229
+                SendFileDataMessage(buddy, event.target.result, fileObj.name, fileObj.size);
12230
+            }
12231
+            else{
12232
+                alert("The file '"+ fileObj.name +"' is bigger than 50MB, you cannot upload this file")
12233
+            }
12234
+        }
12235
+        console.log("Adding: "+ fileObj.name + " of size: "+ fileObj.size +"bytes");
12236
+        reader.readAsDataURL(fileObj);
12237
+    }
12238
+
12239
+    // Prevent Default
12240
+    preventDefault(e);
12241
+}
12242
+function cancelDragDrop(e, buddy){
12243
+    // dragleave dragend
12244
+    $("#contact-"+ buddy +"-ChatHistory").css("outline", "none");
12245
+    preventDefault(e);
12246
+}
12247
+function setupDragDrop(e, buddy){
12248
+    // dragover dragenter
12249
+    $("#contact-"+ buddy +"-ChatHistory").css("outline", "2px dashed #184369");
12250
+    preventDefault(e);
12251
+}
12252
+function preventDefault(e){
12253
+    e.preventDefault();
12254
+    e.stopPropagation();
12255
+}
12256
+
12257
+// UI Elements
12258
+// ===========
12259
+function Alert(messageStr, TitleStr, onOk) {
12260
+
12261
+    $("#jg_popup_l").empty();
12262
+    $("#jg_popup_b").empty();
12263
+    $("#windowCtrls").empty();
12264
+    $.jeegoopopup.close();
12265
+
12266
+    var html = "<div class=NoSelect>";
12267
+    html += '<div id="windowCtrls"><img id="closeImg" src="images/3_close.svg" title="Close" /></div>';
12268
+    html += "<div class=UiText style=\"padding: 0px 10px 8px 10px;\" id=AllertMessageText>" + messageStr + "</div>";
12269
+    html += "</div>"
12270
+
12271
+    $.jeegoopopup.open({
12272
+                title: TitleStr,
12273
+                html: html,
12274
+                width: '260',
12275
+                height: 'auto',
12276
+                center: true,
12277
+                scrolling: 'no',
12278
+                skinClass: 'jg_popup_basic',
12279
+                contentClass: 'confirmDelContact',
12280
+                overlay: true,
12281
+                opacity: 50,
12282
+                draggable: true,
12283
+                resizable: false,
12284
+                fadeIn: 0
12285
+    });
12286
+
12287
+    $("#jg_popup_b").append("<div id=bottomButtons><button id=AlertOkButton style=\"width:80px\">"+ lang.ok +"</button></div>");
12288
+
12289
+    $("#AlertOkButton").click(function () {
12290
+        console.log("Alert OK clicked");
12291
+        if (onOk) onOk();
12292
+    });
12293
+
12294
+    $(window).resize(function() {
12295
+       $.jeegoopopup.center();
12296
+    });
12297
+
12298
+    $("#closeImg").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
12299
+    $("#AlertOkButton").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
12300
+    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
12301
+    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); $("#jg_popup_b").empty(); } });
12302
+
12303
+}
12304
+function AlertConfigExtWindow(messageStr, TitleStr) {
12305
+
12306
+    $("#jg_popup_l").empty();
12307
+    $("#jg_popup_b").empty();
12308
+    $("#windowCtrls").empty();
12309
+    $.jeegoopopup.close();
12310
+
12311
+    videoAudioCheck = 1;
12312
+
12313
+    var html = "<div class=NoSelect>";
12314
+    html += '<div id="windowCtrls"><img id="closeImg" src="images/3_close.svg" title="Close" /></div>';
12315
+    html += "<div class=UiText style=\"padding: 10px\" id=AllertMessageText>" + messageStr + "</div>";
12316
+    html += "</div>"
12317
+
12318
+    $.jeegoopopup.open({
12319
+                title: TitleStr,
12320
+                html: html,
12321
+                width: '260',
12322
+                height: 'auto',
12323
+                center: true,
12324
+                scrolling: 'no',
12325
+                skinClass: 'jg_popup_basic',
12326
+                contentClass: 'confirmDelContact',
12327
+                overlay: true,
12328
+                opacity: 50,
12329
+                draggable: true,
12330
+                resizable: false,
12331
+                fadeIn: 0
12332
+    });
12333
+
12334
+    $("#jg_popup_b").append("<div id=bottomButtons><button id=AlertOkButton style=\"width:80px\">"+ lang.ok +"</button></div>");
12335
+
12336
+    $(window).resize(function() {
12337
+       $.jeegoopopup.center();
12338
+    });
12339
+
12340
+    $("#closeImg").click(function() { $("#windowCtrls").empty(); $("#jg_popup_b").empty(); $.jeegoopopup.close(); ConfigureExtensionWindow(); });
12341
+    $("#AlertOkButton").click(function() { console.log("Alert OK clicked"); $("#windowCtrls").empty(); $("#jg_popup_b").empty(); $.jeegoopopup.close(); ConfigureExtensionWindow(); });
12342
+    $("#jg_popup_overlay").click(function() { $("#windowCtrls").empty(); $("#jg_popup_b").empty(); $.jeegoopopup.close(); ConfigureExtensionWindow(); });
12343
+    $(window).on('keydown', function(event) { if (event.key == "Escape") { $("#windowCtrls").empty(); $("#jg_popup_b").empty(); $.jeegoopopup.close(); ConfigureExtensionWindow(); } });
12344
+
12345
+}
12346
+function Confirm(messageStr, TitleStr, onOk, onCancel) {
12347
+
12348
+    $("#jg_popup_l").empty();
12349
+    $("#jg_popup_b").empty();
12350
+    $("#windowCtrls").empty();
12351
+    $.jeegoopopup.close();
12352
+
12353
+    var html = "<div class=NoSelect>";
12354
+    html += '<div id="windowCtrls"><img id="closeImg" src="images/3_close.svg" title="Close" /></div>';
12355
+    html += "<div class=UiText style=\"padding: 10px\" id=ConfirmMessageText>" + messageStr + "</div>";
12356
+    html += "</div>";
12357
+
12358
+    $.jeegoopopup.open({
12359
+                html: html,
12360
+                width: '260',
12361
+                height: 'auto',
12362
+                center: true,
12363
+                scrolling: 'no',
12364
+                skinClass: 'jg_popup_basic',
12365
+                contentClass: 'confirmDelContact',
12366
+                overlay: true,
12367
+                opacity: 50,
12368
+                draggable: true,
12369
+                resizable: false,
12370
+                fadeIn: 0
12371
+    });
12372
+
12373
+    $("#jg_popup_b").append("<div id=ConfDelContact><button id=ConfirmOkButton>"+ lang.ok +"</button><button id=ConfirmCancelButton>"+ lang.cancel +"</button></div>");
12374
+
12375
+    $("#ConfirmOkButton").click(function () {
12376
+        console.log("Confirm OK clicked");
12377
+        if (onOk) onOk();
12378
+    });
12379
+    $("#ConfirmCancelButton").click(function () {
12380
+        console.log("Confirm Cancel clicked");
12381
+        if (onCancel) onCancel();
12382
+    });
12383
+
12384
+    $(window).resize(function() {
12385
+       $.jeegoopopup.center();
12386
+    });
12387
+
12388
+    $("#closeImg").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
12389
+    $("#ConfirmOkButton").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
12390
+    $("#ConfirmCancelButton").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
12391
+    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
12392
+    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); $("#jg_popup_b").empty(); } });
12393
+}
12394
+function ConfirmConfigExtWindow(messageStr, TitleStr, onOk, onCancel) {
12395
+
12396
+    $("#jg_popup_l").empty();
12397
+    $("#jg_popup_b").empty();
12398
+    $("#windowCtrls").empty();
12399
+    $.jeegoopopup.close();
12400
+
12401
+    var html = "<div class=NoSelect>";
12402
+    html += "<div id=windowCtrls><img id=closeImg src=images/3_close.svg title=Close /></div>";
12403
+    html += "<div class=UiText style=\"padding: 10px\" id=ConfirmMessageText>" + messageStr + "</div>";
12404
+    html += "</div>";
12405
+
12406
+    $.jeegoopopup.open({
12407
+                html: html,
12408
+                width: '260',
12409
+                height: 'auto',
12410
+                center: true,
12411
+                scrolling: 'no',
12412
+                skinClass: 'jg_popup_basic',
12413
+                contentClass: 'ConfCloseAccount',
12414
+                overlay: true,
12415
+                opacity: 50,
12416
+                draggable: true,
12417
+                resizable: false,
12418
+                fadeIn: 0
12419
+    });
12420
+
12421
+    $("#jg_popup_b").append("<div id=ConfCloseAccount><button id=ConfirmOkButton>"+ lang.close_user_account +"</button><button id=ConfirmCancelButton>"+ lang.cancel +"</button></div>");
12422
+
12423
+    $("#ConfirmOkButton").click(function () {
12424
+        console.log("Confirm OK clicked");
12425
+        if (onOk) onOk();
12426
+    });
12427
+    $("#ConfirmCancelButton").click(function () {
12428
+        console.log("Confirm Cancel clicked");
12429
+        if (onCancel) onCancel();
12430
+
12431
+        $("#windowCtrls").empty();
12432
+        $("#jg_popup_b").empty();
12433
+        $.jeegoopopup.close();
12434
+        ConfigureExtensionWindow();
12435
+    });
12436
+
12437
+    $(window).resize(function() {
12438
+       $.jeegoopopup.center();
12439
+    });
12440
+
12441
+    $("#closeImg").click(function() { $("#jg_popup_b").empty(); $("#windowCtrls").empty(); $.jeegoopopup.close(); ConfigureExtensionWindow(); });
12442
+}
12443
+function Prompt(messageStr, TitleStr, FieldText, defaultValue, dataType, placeholderText, onOk, onCancel) {
12444
+
12445
+    $("#jg_popup_l").empty();
12446
+    $("#jg_popup_b").empty();
12447
+    $("#windowCtrls").empty();
12448
+    $.jeegoopopup.close();
12449
+
12450
+    var html = "<div class=NoSelect>";
12451
+    html += '<div id="windowCtrls"><img id="closeImg" src="images/3_close.svg" title="Close" /></div>';
12452
+    html += "<div class=UiText style=\"padding: 10px\" id=PromptMessageText>";
12453
+    html += messageStr;
12454
+    html += "<div style=\"margin-top:10px\">" + FieldText + " : </div>";
12455
+    html += "<div style=\"margin-top:5px\"><INPUT id=PromptValueField type=" + dataType + " value=\"" + defaultValue + "\" placeholder=\"" + placeholderText + "\" style=\"width:98%\"></div>"
12456
+    html += "</div>";
12457
+    html += "</div>";
12458
+
12459
+    $.jeegoopopup.open({
12460
+                html: html,
12461
+                width: '260',
12462
+                height: 'auto',
12463
+                center: true,
12464
+                scrolling: 'no',
12465
+                skinClass: 'jg_popup_basic',
12466
+                contentClass: 'confirmDelContact',
12467
+                overlay: true,
12468
+                opacity: 50,
12469
+                draggable: true,
12470
+                resizable: false,
12471
+                fadeIn: 0
12472
+    });
12473
+
12474
+    $("#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>");
12475
+
12476
+    $("#PromptOkButton").click(function () {
12477
+        console.log("Prompt OK clicked, with value: " + $("#PromptValueField").val());
12478
+        if (onOk) onOk($("#PromptValueField").val());
12479
+    });
12480
+
12481
+    $("#PromptCancelButton").click(function () {
12482
+        console.log("Prompt Cancel clicked");
12483
+        if (onCancel) onCancel();
12484
+    });
12485
+
12486
+    $(window).resize(function() {
12487
+       $.jeegoopopup.center();
12488
+    });
12489
+
12490
+    $("#closeImg").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
12491
+    $("#PromptOkButton").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
12492
+    $("#PromptCancelButton").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
12493
+    $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); $("#jg_popup_b").empty(); });
12494
+    $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); $("#jg_popup_b").empty(); } });
12495
+}
12496
+
12497
+// Device Detection
12498
+// ================
12499
+function DetectDevices(){
12500
+    navigator.mediaDevices.enumerateDevices().then(function(deviceInfos){
12501
+        // deviceInfos will not have a populated lable unless to accept the permission
12502
+        // during getUserMedia. This normally happens at startup/setup
12503
+        // so from then on these devices will be with lables.
12504
+        HasVideoDevice = false;
12505
+        HasAudioDevice = false;
12506
+        HasSpeakerDevice = false; // Safari and Firefox don't have these
12507
+        AudioinputDevices = [];
12508
+        VideoinputDevices = [];
12509
+        SpeakerDevices = [];
12510
+        for (var i = 0; i < deviceInfos.length; ++i) {
12511
+            if (deviceInfos[i].kind === "audioinput") {
12512
+                HasAudioDevice = true;
12513
+                AudioinputDevices.push(deviceInfos[i]);
12514
+            } 
12515
+            else if (deviceInfos[i].kind === "audiooutput") {
12516
+                HasSpeakerDevice = true;
12517
+                SpeakerDevices.push(deviceInfos[i]);
12518
+            }
12519
+            else if (deviceInfos[i].kind === "videoinput") {
12520
+                HasVideoDevice = true;
12521
+                VideoinputDevices.push(deviceInfos[i]);
12522
+            }
12523
+        }
12524
+
12525
+    }).catch(function(e){
12526
+        console.error("Error enumerating devices", e);
12527
+    });
12528
+}
12529
+DetectDevices();
12530
+window.setInterval(function(){
12531
+    DetectDevices();
12532
+}, 10000);
12533
+
12534
+// STATUS_NULL: 0
12535
+// STATUS_INVITE_SENT: 1
12536
+// STATUS_1XX_RECEIVED: 2
12537
+// STATUS_INVITE_RECEIVED: 3
12538
+// STATUS_WAITING_FOR_ANSWER: 4
12539
+// STATUS_ANSWERED: 5
12540
+// STATUS_WAITING_FOR_PRACK: 6
12541
+// STATUS_WAITING_FOR_ACK: 7
12542
+// STATUS_CANCELED: 8
12543
+// STATUS_TERMINATED: 9
12544
+// STATUS_ANSWERED_WAITING_FOR_PRACK: 10
12545
+// STATUS_EARLY_MEDIA: 11
12546
+// STATUS_CONFIRMED: 12
12547
+
12548
+// =======================================
12549
+// End Of File
0 12550
new file mode 100644
... ...
@@ -0,0 +1 @@
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({async:!1,global:!1,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);
0 2
\ No newline at end of file
1 3
new file mode 100644
... ...
@@ -0,0 +1,314 @@
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.1<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
+}