File: jsxc.lib.js.html

package info (click to toggle)
libjs-jsxc 3.4.4%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 18,704 kB
  • sloc: javascript: 68,510; makefile: 13; sh: 1
file content (1202 lines) | stat: -rw-r--r-- 34,764 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>JSDoc: Source: jsxc.lib.js</title>

    <script src="scripts/prettify/prettify.js"> </script>
    <script src="scripts/prettify/lang-css.js"> </script>
    <!--[if lt IE 9]>
      <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
    <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
</head>

<body>

<div id="main">

    <h1 class="page-title">Source: jsxc.lib.js</h1>

    



    
    <section>
        <article>
            <pre class="prettyprint source linenums"><code>/**
 * JavaScript Xmpp Chat namespace
 *
 * @namespace jsxc
 */
jsxc = {
   /** Version of jsxc */
   version: '&lt; $ app.version $ >',

   /** True if i'm the master */
   master: false,

   /** True if the role allocation is finished */
   role_allocation: false,

   /** Timeout for keepalive */
   to: [],

   /** Timeout after normal keepalive starts */
   toBusy: null,

   /** Timeout for notification */
   toNotification: null,

   /** Timeout delay for notification */
   toNotificationDelay: 500,

   /** Interval for keep-alive */
   keepaliveInterval: null,

   /** True if restore is complete */
   restoreCompleted: false,

   /** True if login through box */
   triggeredFromBox: false,

   /** True if logout through element click */
   triggeredFromElement: false,

   /** True if logout through logout click */
   triggeredFromLogout: false,

   /** last values which we wrote into localstorage (IE workaround) */
   ls: [],

   /**
    * storage event is even fired if I write something into storage (IE
    * workaround) 0: conform, 1: not conform, 2: not shure
    */
   storageNotConform: null,

   /** Timeout for storageNotConform test */
   toSNC: null,

   /** My bar id */
   bid: null,

   /** Current state */
   currentState: null,

   /** Current UI state */
   currentUIState: null,

   /** Some constants */
   CONST: {
      NOTIFICATION_DEFAULT: 'default',
      NOTIFICATION_GRANTED: 'granted',
      NOTIFICATION_DENIED: 'denied',
      STATUS: ['offline', 'dnd', 'xa', 'away', 'chat', 'online'],
      SOUNDS: {
         MSG: 'incomingMessage.wav',
         CALL: 'Rotary-Phone6.mp3',
         NOTICE: 'Ping1.mp3'
      },
      REGEX: {
         JID: new RegExp('\\b[^"&amp;\'\\/:&lt;>@\\s]+@[\\w-_.]+\\b', 'ig'),
         URL: new RegExp(/(https?:\/\/|www\.)[^\s&lt;>'"]+/gi),
         GEOURI: new RegExp(/geo:(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?)(?:,-?\d+(?:\.\d+)?)?(?:;crs=[\w-]+)?(?:;u=(\d+(?:\.\d+)?))?(?:;[\w-]+=(?:[\w-_.!~*'()]|%[\da-f][\da-f])+)*/)
      },
      NS: {
         CARBONS: 'urn:xmpp:carbons:2',
         FORWARD: 'urn:xmpp:forward:0',
         HINTS: 'urn:xmpp:hints'
      },
      HIDDEN: 'hidden',
      SHOWN: 'shown',
      STATE: {
         INITIATING: 0,
         PREVCONFOUND: 1,
         SUSPEND: 2,
         TRYTOINTERCEPT: 3,
         INTERCEPTED: 4,
         ESTABLISHING: 5,
         READY: 6
      },
      UISTATE: {
         INITIATING: 0,
         READY: 1
      }
   },

   /**
    * Parse a unix timestamp and return a formatted time string
    *
    * @memberOf jsxc
    * @param {Object} unixtime
    * @returns time of day and/or date
    */
   getFormattedTime: function(unixtime) {
      var msgDate = new Date(parseInt(unixtime));
      var day = ('0' + msgDate.getDate()).slice(-2);
      var month = ('0' + (msgDate.getMonth() + 1)).slice(-2);
      var year = msgDate.getFullYear();
      var hours = ('0' + msgDate.getHours()).slice(-2);
      var minutes = ('0' + msgDate.getMinutes()).slice(-2);
      var dateNow = new Date();

      var date = (typeof msgDate.toLocaleDateString === 'function') ? msgDate.toLocaleDateString() : day + '.' + month + '.' + year;
      var time = (typeof msgDate.toLocaleTimeString === 'function') ? msgDate.toLocaleTimeString() : hours + ':' + minutes;

      // compare dates only
      dateNow.setHours(0, 0, 0, 0);
      msgDate.setHours(0, 0, 0, 0);

      if (dateNow.getTime() !== msgDate.getTime()) {
         return date + ' ' + time;
      }
      return time;
   },

   /**
    * Write debug message to console and to log.
    *
    * @memberOf jsxc
    * @param {String} msg Debug message
    * @param {Object} data
    * @param {String} Could be warn|error|null
    */
   debug: function(msg, data, level) {
      if (level) {
         msg = '[' + level + '] ' + msg;
      }

      if (data) {
         if (jsxc.storage.getItem('debug') === true) {
            console.log(msg, data);
         }

         // try to convert data to string
         var d;
         try {
            // clone html snippet
            d = $("&lt;span>").prepend($(data).clone()).html();
         } catch (err) {
            try {
               d = JSON.stringify(data);
            } catch (err2) {
               d = 'see js console';
            }
         }

         jsxc.log = jsxc.log + '$ ' + msg + ': ' + d + '\n';
      } else {
         console.log(msg);
         jsxc.log = jsxc.log + '$ ' + msg + '\n';
      }
   },

   /**
    * Write warn message.
    *
    * @memberOf jsxc
    * @param {String} msg Warn message
    * @param {Object} data
    */
   warn: function(msg, data) {
      jsxc.debug(msg, data, 'WARN');
   },

   /**
    * Write error message.
    *
    * @memberOf jsxc
    * @param {String} msg Error message
    * @param {Object} data
    */
   error: function(msg, data) {
      jsxc.debug(msg, data, 'ERROR');
   },

   /** debug log */
   log: '',

   /**
    * This function initializes important core functions and event handlers.
    * Afterwards it performs the following actions in the given order:
    *
    * &lt;ol>
    *  &lt;li>If (loginForm.ifFound = 'force' and form was found) or (jid or rid or
    * 	sid was not found) intercept form, and listen for credentials.&lt;/li>
    *  &lt;li>Attach with jid, rid and sid from storage, if no form was found or
    * 	loginForm.ifFound = 'attach'&lt;/li>
    *  &lt;li>Attach with jid, rid and sid from options.xmpp, if no form was found or
    * 	loginForm.ifFound = 'attach'&lt;/li>
    * &lt;/ol>
    *
    * @memberOf jsxc
    * @param {object} options See {@link jsxc.options}
    */
   init: function(options) {
      jsxc.runMigrations();

      jsxc.changeState(jsxc.CONST.STATE.INITIATING);

      if (options &amp;&amp; options.loginForm &amp;&amp; typeof options.loginForm.attachIfFound === 'boolean' &amp;&amp; !options.loginForm.ifFound) {
         // translate deprated option attachIfFound found to new ifFound
         options.loginForm.ifFound = (options.loginForm.attachIfFound) ? 'attach' : 'pause';
      }

      if (options) {
         // override default options
         $.extend(true, jsxc.options, options);
      }

      // Check localStorage
      if (!jsxc.storage.hasSupport()) {
         jsxc.error("Browser doesn't support localStorage. JSXC will be disabled.");
         return;
      }

      /**
       * Getter method for options. Saved options will override default one.
       *
       * @param {string} key option key
       * @returns default or saved option value
       */
      jsxc.options.get = function(key) {
         if (jsxc.bid) {
            var local = jsxc.storage.getUserItem('options') || {};

            return (typeof local[key] !== 'undefined') ? local[key] : jsxc.options[key];
         }

         return jsxc.options[key];
      };

      /**
       * Setter method for options. Will write into localstorage.
       *
       * @param {string} key option key
       * @param {object} value option value
       */
      jsxc.options.set = function(key, value) {
         jsxc.storage.updateItem('options', key, value, true);
      };

      jsxc.storageNotConform = jsxc.storage.getItem('storageNotConform');
      if (jsxc.storageNotConform === null) {
         jsxc.storageNotConform = 2;
      }

      // detect language
      var lang;
      if (jsxc.storage.getItem('lang') !== null) {
         lang = jsxc.storage.getItem('lang');
      } else if (jsxc.options.autoLang &amp;&amp; navigator.languages &amp;&amp; navigator.languages.length > 0) {
         lang = navigator.languages[0];
      } else if (jsxc.options.autoLang &amp;&amp; navigator.language) {
         lang = navigator.language;
      } else {
         lang = jsxc.options.defaultLang;
      }

      var availableLanguages = Object.keys(window.jsxcLanguageResources);

      if (availableLanguages.indexOf(lang) &lt; 0) {
         var languagePrefix = lang.slice(0, 2);

         if (availableLanguages.indexOf(languagePrefix) > -1) {
            lang = languagePrefix;
         } else {
            var prefixMatch = availableLanguages.filter(function(l) {
               return l.slice(0, 2) === languagePrefix;
            });

            if (prefixMatch.length > 0) {
               lang = prefixMatch[0];
            }
         }
      }

      // initialize i18next translator
      window.i18next.init({
         lng: lang,
         fallbackLng: 'en',
         resources: window.jsxcLanguageResources,
         returnNull: false,
         debug: jsxc.storage.getItem('debug') === true,
         interpolation: {
            prefix: '__',
            suffix: '__'
         }
      }, function() {
         window.jqueryI18next.init(window.i18next, $, {
            tName: 't',
            i18nName: 'i18next',
            handleName: 'localize',
         });
      });

      if (jsxc.storage.getItem('debug') === true) {
         jsxc.options.otr.debug = true;
      }

      // Register event listener for the storage event
      window.addEventListener('storage', jsxc.storage.onStorage, false);

      $(document).on('attached.jsxc', jsxc.registerLogout);
      $(document).on('disconnected.jsxc', jsxc.relogin);

      var isStorageAttachParameters = jsxc.storage.getItem('rid') &amp;&amp; jsxc.storage.getItem('sid') &amp;&amp; jsxc.storage.getItem('jid');
      var isOptionsAttachParameters = jsxc.options.xmpp.rid &amp;&amp; jsxc.options.xmpp.sid &amp;&amp; jsxc.options.xmpp.jid;
      var isForceLoginForm = jsxc.options.loginForm &amp;&amp; jsxc.options.loginForm.ifFound === 'force' &amp;&amp; jsxc.isLoginForm();

      // Check if we have to establish a new connection
      if ((!isStorageAttachParameters &amp;&amp; !isOptionsAttachParameters) || isForceLoginForm) {

         if (jsxc.relogin()) {
            return;
         }

         jsxc.prepareNewConnection();

      } else if (!jsxc.isLoginForm() || (jsxc.options.loginForm &amp;&amp; jsxc.options.loginForm.ifFound === 'attach')) {

         // Restore old connection
         jsxc.changeState(jsxc.CONST.STATE.PREVCONFOUND);

         if (typeof jsxc.storage.getItem('alive') === 'undefined') {
            jsxc.onMaster();
         } else {
            jsxc.checkMaster();
         }
      }
   },

   runMigrations: function() {
      var lastUsedVersion = jsxc.storage.getItem('version');

      if (!lastUsedVersion) {
         var keys = Object.keys(localStorage).filter(function(key) {
            var isKeepMatch = key.match(/^jsxc:[^:]+:(key|history|msg|priv_fingerprint):?/);

            return (key.match(/^jsxc:/) &amp;&amp; !isKeepMatch) || key.match(/^strophe\.caps\./)
         });

         keys.forEach(function(key) {
            localStorage.removeItem(key);
         });

         jsxc.debug('I turned out your storage and deleted ' + keys.length + ' entries.');
      }

      if (lastUsedVersion !== jsxc.version) {
         jsxc.storage.setItem('version', jsxc.version);
      }
   },

   prepareNewConnection: function() {
      // clean up rid and sid
      jsxc.storage.removeItem('rid');
      jsxc.storage.removeItem('sid');

      // Looking for a login form
      if (!jsxc.isLoginForm()) {
         jsxc.changeState(jsxc.CONST.STATE.SUSPEND);

         if (jsxc.options.displayRosterMinimized()) {
            // Show minimized roster
            jsxc.storage.setUserItem('roster', 'hidden');
            jsxc.gui.roster.init();
            jsxc.gui.roster.noConnection();
         }

         return;
      }

      jsxc.changeState(jsxc.CONST.STATE.TRYTOINTERCEPT);

      if (typeof jsxc.options.formFound === 'function') {
         jsxc.options.formFound.call();
      }

      // create jquery object
      var form = jsxc.options.loginForm.form = $(jsxc.options.loginForm.form);
      var events = form.data('events') || {
         submit: []
      };
      var submits = [];

      // save attached submit events and remove them. Will be reattached
      // in jsxc.submitLoginForm
      $.each(events.submit, function(index, val) {
         submits.push(val.handler);
      });

      form.data('submits', submits);
      form.off('submit');

      // Add jsxc login action to form
      form.submit(function(ev) {
         ev.preventDefault();

         jsxc.prepareLogin(function(settings) {
            if (settings !== false) {
               // settings.xmpp.onlogin is deprecated since v2.1.0
               var enabled = (settings.loginForm &amp;&amp; settings.loginForm.enable) || (settings.xmpp &amp;&amp; settings.xmpp.onlogin);
               enabled = enabled === "true" || enabled === true;

               if (enabled) {
                  jsxc.options.loginForm.triggered = true;

                  jsxc.xmpp.login(jsxc.options.xmpp.jid, jsxc.options.xmpp.password);

                  return;
               }
            }

            jsxc.submitLoginForm();
         });

         // Trigger submit in jsxc.xmpp.connected()
         return false;
      });

      jsxc.changeState(jsxc.CONST.STATE.INTERCEPTED);
   },

   /**
    * Attach to previous session if jid, sid and rid are available
    * in storage or options (default behaviour also for {@link jsxc.init}).
    *
    * @memberOf jsxc
    */
   /**
    * Start new chat session with given jid and password.
    *
    * @memberOf jsxc
    * @param {string} jid Jabber Id
    * @param {string} password Jabber password
    */
   /**
    * Attach to new chat session with jid, sid and rid.
    *
    * @memberOf jsxc
    * @param {string} jid Jabber Id
    * @param {string} sid Session Id
    * @param {string} rid Request Id
    */
   start: function() {
      var args = arguments;

      if (jsxc.role_allocation &amp;&amp; !jsxc.master) {
         jsxc.debug('There is an other master tab');

         return false;
      }

      if (jsxc.xmpp.conn &amp;&amp; jsxc.xmpp.conn.authenticated) {
         jsxc.debug('We are already connected and authenticated');

         return false;
      }

      if (jsxc.currentState !== jsxc.CONST.STATE.INTERCEPTED &amp;&amp; jsxc.currentState !== jsxc.CONST.STATE.SUSPEND) {
         if (!jsxc.busy) {
            jsxc.debug('I am currently busy and will try again later. Please be patient.');
         }

         jsxc.busy = true;

         setTimeout(function() {
            jsxc.start.apply(jsxc, args);
         }, 400);

         return;
      }

      jsxc.busy = false;

      if (args.length === 3) {
         $(document).one('attached.jsxc', function() {
            // save rid after first attachment
            jsxc.xmpp.onRidChange(jsxc.xmpp.conn._proto.rid);

            jsxc.onMaster();
         });
      }

      jsxc.checkMaster(function() {
         jsxc.xmpp.login.apply(this, args);
      });
   },

   relogin: function() {
      jsxc.debug('Try to relogin');

      var jid = jsxc.storage.getItem('jid');
      jsxc.bid = jsxc.bid || (jid ? jsxc.jidToBid(jid) : null);

      if (!jsxc.bid || jsxc.storage.getUserItem('forcedLogout')) {
         jsxc.debug('Logout was forced or I found no valid jid');

         return false;
      }

      var xmppOptions = jsxc.options.get('xmpp');

      if (xmppOptions.url &amp;&amp; (xmppOptions.jid || (xmppOptions.username &amp;&amp; xmppOptions.domain)) &amp;&amp; xmppOptions.password) {
         xmppOptions.jid = xmppOptions.jid || (xmppOptions.username + '@' + xmppOptions.domain);

         jsxc.start(xmppOptions.jid, xmppOptions.password);

         return true;
      }

      var loadSettingsAllKnowing = jsxc.storage.getUserItem('loadSettingsAllKnowing');

      if (xmppOptions.url &amp;&amp; loadSettingsAllKnowing) {
         jsxc.options.loadSettings(null, null, function(settings) {
            jsxc._prepareLogin(null, null, function(settings) {
               if (settings !== false &amp;&amp; jsxc.options.xmpp.jid &amp;&amp; jsxc.options.xmpp.password) {
                  $(document).on('connfail.jsxc', reloginFailed);
                  $(document).on('authfail.jsxc', reloginFailed);
                  $(document).on('connected.jsxc', removeReloginHandler);

                  jsxc.start(jsxc.options.xmpp.jid, jsxc.options.xmpp.password);

                  delete jsxc.options.xmpp.password;
               } else {
                  reloginFailed();
               }

               function reloginFailed() {
                  jsxc.debug('Could not relogin.');

                  removeReloginHandler();

                  jsxc.storage.removeUserItem('loadSettingsAllKnowing');

                  jsxc.prepareNewConnection();
               }

               function removeReloginHandler() {
                  $(document).off('connfail.jsxc', reloginFailed);
                  $(document).off('authfail.jsxc', reloginFailed);
                  $(document).off('connected.jsxc', removeReloginHandler);
               }
            }, settings);
         });

         return true;
      }

      jsxc.debug('I am not able to relogin');

      return false;
   },

   registerLogout: function() {
      // Looking for logout element
      if (jsxc.options.logoutElement !== null &amp;&amp; $(jsxc.options.logoutElement).length > 0) {
         var logout = function(ev) {
            ev.stopPropagation();
            ev.preventDefault();

            jsxc.options.logoutElement = $(this);
            jsxc.triggeredFromLogout = true;

            jsxc.xmpp.logout();
         };

         jsxc.options.logoutElement = $(jsxc.options.logoutElement);

         jsxc.options.logoutElement.off('click', null, logout).one('click', logout);
      }
   },

   /**
    * Returns true if login form is found.
    *
    * @memberOf jsxc
    * @returns {boolean} True if login form was found.
    */
   isLoginForm: function() {
      return jsxc.options.loginForm.form &amp;&amp; jsxc.el_exists(jsxc.options.loginForm.form) &amp;&amp; jsxc.el_exists(jsxc.options.loginForm.jid) &amp;&amp; jsxc.el_exists(jsxc.options.loginForm.pass);
   },

   /**
    * Load settings and prepare jid.
    *
    * @memberOf jsxc
    * @param {string} username
    * @param {string} password
    * @param {function} cb Called after login is prepared with result as param
    */
   prepareLogin: function(username, password, cb) {
      if (typeof username === 'function') {
         cb = username;
         username = null;
      }
      username = username || $(jsxc.options.loginForm.jid).val();
      password = password || $(jsxc.options.loginForm.pass).val();

      if (!jsxc.triggeredFromBox &amp;&amp; (jsxc.options.loginForm.onConnecting === 'dialog' || typeof jsxc.options.loginForm.onConnecting === 'undefined')) {
         jsxc.gui.showWaitAlert($.t('Logging_in'));
      }

      var settings;

      if (typeof jsxc.options.loadSettings === 'function') {
         settings = jsxc.options.loadSettings.call(this, username, password, function(s) {
            jsxc._prepareLogin(username, password, cb, s);
         });

         if (typeof settings !== 'undefined') {
            jsxc._prepareLogin(username, password, cb, settings);
         }
      } else {
         jsxc._prepareLogin(username, password, cb);
      }
   },

   /**
    * Process xmpp settings and save loaded settings.
    *
    * @private
    * @memberOf jsxc
    * @param {string} username
    * @param {string} password
    * @param {function} cb Called after login is prepared with result as param
    * @param {object} [loadedSettings] additonal options
    */
   _prepareLogin: function(username, password, cb, loadedSettings) {
      if (loadedSettings === false) {
         jsxc.warn('No settings provided');

         cb(false);
         return;
      }

      // prevent to modify the original object
      var settings = $.extend(true, {}, jsxc.options);

      if (loadedSettings) {
         // overwrite current options with loaded settings;
         settings = $.extend(true, settings, loadedSettings);
      } else {
         loadedSettings = {};
      }

      if (typeof settings.xmpp.username === 'string') {
         username = settings.xmpp.username;
      }

      if (typeof settings.xmpp.password === 'string') {
         password = settings.xmpp.password;

         delete settings.xmpp.password;
      }

      var resource = (settings.xmpp.resource) ? '/' + settings.xmpp.resource : '';
      var domain = settings.xmpp.domain;
      var jid;

      if (username.match(/@(.*)$/)) {
         jid = (username.match(/\/(.*)$/)) ? username : username + resource;
      } else {
         jid = username + '@' + domain + resource;
      }

      if (typeof jsxc.options.loginForm.preJid === 'function') {
         jid = jsxc.options.loginForm.preJid(jid);
      }

      jsxc.bid = jsxc.jidToBid(jid);

      settings.xmpp.username = jid.split('@')[0];
      settings.xmpp.domain = jid.split('@')[1].split('/')[0];
      settings.xmpp.resource = jid.split('@')[1].split('/')[1] || "";

      if (!loadedSettings.xmpp) {
         // force xmpp settings to be saved to storage
         loadedSettings.xmpp = {};
      }

      jsxc.storage.setUserItem('loadSettingsAllKnowing', (!!loadedSettings.xmpp.jid || (!!loadedSettings.xmpp.username &amp;&amp; !!loadedSettings.xmpp.domain)) &amp;&amp; !!loadedSettings.xmpp.password);

      // save loaded settings to storage
      $.each(loadedSettings, function(key) {
         var old = jsxc.options.get(key);
         var val = settings[key];
         val = $.extend(true, old, val);

         jsxc.options.set(key, val);
      });

      jsxc.options.xmpp.jid = jid;
      jsxc.options.xmpp.password = password;

      cb(settings);
   },

   /**
    * Called if the script is a slave
    */
   onSlave: function() {
      jsxc.debug('I am the slave.');

      jsxc.role_allocation = true;
      jsxc.bid = jsxc.jidToBid(jsxc.storage.getItem('jid'));

      jsxc.gui.init();
      $('#jsxc_roster').removeClass('jsxc_noConnection');

      jsxc.registerLogout();
      jsxc.gui.avatar.update($('#jsxc_roster > .jsxc_bottom'), jsxc.jidToBid(jsxc.storage.getItem('jid')), 'own');

      jsxc.gui.restore();
   },

   /**
    * Called if the script is the master
    */
   onMaster: function() {
      jsxc.debug('I am master.');

      jsxc.master = true;

      // Init local storage
      jsxc.storage.setItem('alive', 0);
      jsxc.storage.setItem('alive_busy', 0);

      // Sending keepalive signal
      jsxc.startKeepAlive();

      jsxc.role_allocation = true;

      jsxc.xmpp.login();
   },

   /**
    * Checks if there is a master
    *
    * @param {function} [cb] Called if no master was found.
    */
   checkMaster: function(cb) {
      jsxc.debug('check master');

      cb = (cb &amp;&amp; typeof cb === 'function') ? cb : jsxc.onMaster;

      if (typeof jsxc.storage.getItem('alive') === 'undefined') {
         cb.call();
      } else {
         jsxc.to.push(window.setTimeout(cb, 1000));
         jsxc.keepAlive('slave');
      }
   },

   masterActions: function() {

      if (!jsxc.xmpp.conn || !jsxc.xmpp.conn.authenticated) {
         return;
      }

      //prepare notifications
      var noti = jsxc.storage.getUserItem('notification');
      noti = (typeof noti === 'number') ? noti : 2;
      if (jsxc.options.notification &amp;&amp; noti > 0 &amp;&amp; jsxc.notification.hasSupport()) {
         if (jsxc.notification.hasPermission()) {
            jsxc.notification.init();
         } else {
            jsxc.notification.prepareRequest();
         }
      } else {
         // No support => disable
         jsxc.options.notification = false;
      }

      if (jsxc.options.get('otr').enable) {
         // create or load DSA key
         jsxc.otr.createDSA();
      }

      jsxc.gui.avatar.update($('#jsxc_roster > .jsxc_bottom'), jsxc.jidToBid(jsxc.storage.getItem('jid')), 'own');
   },

   /**
    * Start sending keep-alive signal
    */
   startKeepAlive: function() {
      jsxc.keepaliveInterval = window.setInterval(jsxc.keepAlive, jsxc.options.timeout - 1000);
   },

   /**
    * Sends the keep-alive signal to signal that the master is still there.
    */
   keepAlive: function(role) {
      var next = parseInt(jsxc.storage.getItem('alive')) + 1;
      role = role || 'master';

      jsxc.storage.setItem('alive', next + ':' + role);
   },

   /**
    * Send one keep-alive signal with higher timeout, and than resume with
    * normal signal
    */
   keepBusyAlive: function() {
      if (jsxc.toBusy) {
         window.clearTimeout(jsxc.toBusy);
      }

      if (jsxc.keepaliveInterval) {
         window.clearInterval(jsxc.keepaliveInterval);
      }

      jsxc.storage.ink('alive_busy');
      jsxc.toBusy = window.setTimeout(jsxc.startKeepAlive, jsxc.options.busyTimeout - 1000);
   },

   /**
    * Generates a random integer number between 0 and max
    *
    * @param {Integer} max
    * @return {Integer} random integer between 0 and max
    */
   random: function(max) {
      return Math.floor(Math.random() * max);
   },

   /**
    * Checks if there is a element with the given selector
    *
    * @param {String} selector jQuery selector
    * @return {Boolean}
    */
   el_exists: function(selector) {
      return $(selector).length > 0;
   },

   /**
    * Creates a CSS compatible string from a JID
    *
    * @param {type} jid Valid Jabber ID
    * @returns {String} css Compatible string
    */
   jidToCid: function(jid) {
      jsxc.warn('jsxc.jidToCid is deprecated!');

      var cid = Strophe.getBareJidFromJid(jid).replace('@', '-').replace(/\./g, '-').toLowerCase();

      return cid;
   },

   /**
    * Create comparable bar jid.
    *
    * @memberOf jsxc
    * @param jid
    * @returns comparable bar jid
    */
   jidToBid: function(jid) {
      return Strophe.unescapeNode(Strophe.getBareJidFromJid(jid).toLowerCase());
   },

   /**
    * Restore roster
    */
   restoreRoster: function() {
      var buddies = jsxc.storage.getUserItem('buddylist');

      if (!buddies || buddies.length === 0) {
         jsxc.debug('No saved buddylist.');

         jsxc.gui.roster.empty();

         return;
      }

      $.each(buddies, function(index, value) {
         jsxc.gui.roster.add(value);
      });

      jsxc.gui.roster.loaded = true;
      $(document).trigger('cloaded.roster.jsxc');
   },

   /**
    * Restore all windows
    */
   restoreWindows: function() {
      var windows = jsxc.storage.getUserItem('windowlist');

      if (windows === null) {
         return;
      }

      $.each(windows, function(index, bid) {
         var win = jsxc.storage.getUserItem('window', bid);

         if (!win) {
            jsxc.debug('Associated window-element is missing: ' + bid);
            return true;
         }

         jsxc.gui.window.init(bid);

         if (!win.minimize) {
            jsxc.gui.window.show(bid);
         } else {
            jsxc.gui.window.hide(bid);
         }

         jsxc.gui.window.setText(bid, win.text);
      });
   },

   /**
    * This method submits the specified login form.
    */
   submitLoginForm: function() {
      var form = $(jsxc.options.loginForm.form).off('submit');

      // Attach original events
      var submits = form.data('submits') || [];
      $.each(submits, function(index, val) {
         form.submit(val);
      });

      if (form.find('#submit').length > 0) {
         form.find('#submit').click();
      } else if (form.get(0) &amp;&amp; typeof form.get(0).submit === 'function') {
         form.submit();
      } else if (form.find('[type="submit"]').length > 0) {
         form.find('[type="submit"]').click();
      } else {
         jsxc.warn('Could not submit login form.');
      }
   },

   /**
    * Escapes some characters to HTML character
    */
   escapeHTML: function(text) {
      text = text.replace(/&amp;amp;/g, '&amp;').replace(/&amp;lt;/g, '&lt;').replace(/&amp;gt;/g, '>');
      return text.replace(/&amp;/g, '&amp;amp;').replace(/&lt;/g, '&amp;lt;').replace(/>/g, '&amp;gt;');
   },

   /**
    * Removes all html tags.
    *
    * @memberOf jsxc
    * @param text
    * @returns stripped text
    */
   removeHTML: function(text) {
      return $('&lt;span>').html(text).text();
   },

   /**
    * Executes only one of the given events
    *
    * @param {string} obj.key event name
    * @param {function} obj.value function to execute
    * @returns {string} namespace of all events
    */
   switchEvents: function(obj) {
      var ns = Math.random().toString(36).substr(2, 12);
      var self = this;

      $.each(obj, function(key, val) {
         $(document).one(key + '.' + ns, function() {
            $(document).off('.' + ns);

            val.apply(self, arguments);
         });
      });

      return ns;
   },

   /**
    * Checks if tab is hidden.
    *
    * @returns {boolean} True if tab is hidden
    */
   isHidden: function() {
      var hidden = false;

      if (typeof document.hidden !== 'undefined') {
         hidden = document.hidden;
      } else if (typeof document.webkitHidden !== 'undefined') {
         hidden = document.webkitHidden;
      } else if (typeof document.mozHidden !== 'undefined') {
         hidden = document.mozHidden;
      } else if (typeof document.msHidden !== 'undefined') {
         hidden = document.msHidden;
      }

      // handle multiple tabs
      if (hidden &amp;&amp; jsxc.master) {
         jsxc.storage.ink('hidden', 0);
      } else if (!hidden &amp;&amp; !jsxc.master) {
         jsxc.storage.ink('hidden');
      }

      return hidden;
   },

   /**
    * Checks if tab has focus.
    *
    * @returns {boolean} True if tabs has focus
    */
   hasFocus: function() {
      var focus = true;

      if (typeof document.hasFocus === 'function') {
         focus = document.hasFocus();
      }

      if (!focus &amp;&amp; jsxc.master) {
         jsxc.storage.ink('focus', 0);
      } else if (focus &amp;&amp; !jsxc.master) {
         jsxc.storage.ink('focus');
      }

      return focus;
   },

   /**
    * Executes the given function in jsxc namespace.
    *
    * @memberOf jsxc
    * @param {string} fnName Function name
    * @param {array} fnParams Function parameters
    * @returns Function return value
    */
   exec: function(fnName, fnParams) {
      var fnList = fnName.split('.');
      var fn = jsxc[fnList[0]];
      var i;
      for (i = 1; i &lt; fnList.length; i++) {
         fn = fn[fnList[i]];
      }

      if (typeof fn === 'function') {
         return fn.apply(null, fnParams);
      }
   },

   /**
    * Hash string into 32-bit signed integer.
    *
    * @memberOf jsxc
    * @param {string} str input string
    * @returns {integer} 32-bit signed integer
    */
   hashStr: function(str) {
      var hash = 0,
         i;

      if (str.length === 0) {
         return hash;
      }

      for (i = 0; i &lt; str.length; i++) {
         hash = ((hash &lt;&lt; 5) - hash) + str.charCodeAt(i);
         hash |= 0; // Convert to 32bit integer
      }

      return hash;
   },

   isExtraSmallDevice: function() {
      return $(window).width() &lt; 500;
   },

   changeState: function(state) {
      jsxc.currentState = state;

      jsxc.debug('State changed to ' + Object.keys(jsxc.CONST.STATE)[state]);

      $(document).trigger('stateChange.jsxc', state);
   },

   changeUIState: function(state) {
      jsxc.currentUIState = state;

      jsxc.debug('UI State changed to ' + Object.keys(jsxc.CONST.UISTATE)[state]);

      $(document).trigger('stateUIChange.jsxc', state);
   },

   getLastMsg: function(bid) {
      var history = jsxc.storage.getUserItem('history', bid) || [];
      var i = 0;

      while (history.length > i) {
         var message = new jsxc.Message(history[i]);
         if (message.direction !== jsxc.Message.SYS) {
            return {
               text: message.msg,
               date: message.stamp
            };
         }
         i++;
      }
   },

   enableDebugMode: function() {
      jsxc.storage.setItem('debug', true);
   },

   disableDebugMode: function() {
      jsxc.storage.setItem('debug', false);
   },

   deleteAllData: function() {
      if (!jsxc.storage.getItem('debug')) {
         jsxc.warn('This action is only available in debug mode.');

         return 0;
      }

      var prefix = jsxc.storage.PREFIX + jsxc.storage.SEP;
      var prefixRegex = new RegExp('^' + prefix);
      var keys = Object.keys(localStorage);
      var count = 0;

      $.each(keys, function(index, key) {
         if (prefixRegex.test(key) &amp;&amp; key !== prefix + 'debug') {
            localStorage.removeItem(key);
            count++;
         }
      });

      return count;
   }
};
</code></pre>
        </article>
    </section>




</div>

<nav>
    <h2><a href="index.html">Home</a></h2><h3>Classes</h3><ul><li><a href="jsxc.Message.html">Message</a></li></ul><h3>Namespaces</h3><ul><li><a href="jsxc.html">jsxc</a></li><li><a href="jsxc.fileTransfer.html">fileTransfer</a></li><li><a href="jsxc.gui.html">gui</a></li><li><a href="jsxc.gui.dialog.html">dialog</a></li><li><a href="jsxc.gui.queryActions.html">queryActions</a></li><li><a href="jsxc.gui.roster.html">roster</a></li><li><a href="jsxc.gui.window.html">window</a></li><li><a href="jsxc.muc.html">muc</a></li><li><a href="jsxc.notification.html">notification</a></li><li><a href="jsxc.options.html">options</a></li><li><a href="jsxc.otr.html">otr</a></li><li><a href="jsxc.storage.html">storage</a></li><li><a href="jsxc.tab.html">tab</a></li><li><a href="jsxc.webrtc.html">webrtc</a></li><li><a href="jsxc.xmpp.html">xmpp</a></li><li><a href="jsxc.xmpp.bookmarks.html">bookmarks</a></li><li><a href="jsxc.xmpp.carbons.html">carbons</a></li><li><a href="jsxc.xmpp.chatState.html">chatState</a></li><li><a href="jsxc.xmpp.httpUpload.html">httpUpload</a></li><li><a href="jsxc.xmpp.mam.html">mam</a></li></ul><h3><a href="global.html">Global</a></h3>
</nav>

<br class="clear">

<footer>
    Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.5.5</a> on Fri May 10 2019 12:36:11 GMT+0200 (Central European Summer Time)
</footer>

<script> prettyPrint(); </script>
<script src="scripts/linenumber.js"> </script>
</body>
</html>