Welcome to mirror list, hosted at ThFree Co, Russian Federation.

chat.js « pane « view « src - github.com/candy-chat/candy.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 44293b2f3a78d6585dc4364057300ec5079693ff (plain)
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
/** File: chat.js
 * Candy - Chats are not dead yet.
 *
 * Authors:
 *   - Patrick Stadler <patrick.stadler@gmail.com>
 *   - Michael Weibel <michael.weibel@gmail.com>
 *
 * Copyright:
 *   (c) 2011 Amiado Group AG. All rights reserved.
 *   (c) 2012-2014 Patrick Stadler & Michael Weibel. All rights reserved.
 *   (c) 2015 Adhearsion Foundation Inc <info@adhearsion.com>. All rights reserved.
 */
'use strict';

/* global Candy, document, Mustache, Strophe, Audio, jQuery */

/** Class: Candy.View.Pane
 * Candy view pane handles everything regarding DOM updates etc.
 *
 * Parameters:
 *   (Candy.View.Pane) self - itself
 *   (jQuery) $ - jQuery
 */
Candy.View.Pane = (function(self, $) {

  /** Class: Candy.View.Pane.Chat
   * Chat-View related view updates
   */
  self.Chat = {
    /** Variable: rooms
     * Contains opened room elements
     */
    rooms: [],

    /** Function: addTab
     * Add a tab to the chat pane.
     *
     * Parameters:
     *   (String) roomJid - JID of room
     *   (String) roomName - Tab label
     *   (String) roomType - Type of room: `groupchat` or `chat`
     */
    addTab: function(roomJid, roomName, roomType) {
      var roomId = Candy.Util.jidToId(roomJid);

      var evtData = {
        roomJid: roomJid,
        roomName: roomName,
        roomType: roomType,
        roomId: roomId
      };

      /** Event: candy:view.pane.before-tab
       * Before sending a message
       *
       * Parameters:
       *   (String) roomJid - JID of the room the tab is for.
       *   (String) roomName - Name of the room.
       *   (String) roomType - What type of room: `groupchat` or `chat`
       *
       * Returns:
       *   Boolean|undefined - If you want to handle displaying the tab on your own, return false.
       */
      if ($(Candy).triggerHandler('candy:view.pane.before-tab', evtData) === false) {
        event.preventDefault();
        return;
      }

      var html = Mustache.to_html(Candy.View.Template.Chat.tab, {
          roomJid: roomJid,
          roomId: roomId,
          name: roomName || Strophe.getNodeFromJid(roomJid),
          privateUserChat: function() {return roomType === 'chat';},
          roomType: roomType
        }),
        tab = $(html).appendTo('#chat-tabs');

      tab.click(self.Chat.tabClick);
      // TODO: maybe we find a better way to get the close element.
      $('a.close', tab).click(self.Chat.tabClose);

      self.Chat.fitTabs();
    },

    /** Function: getTab
     * Get tab by JID.
     *
     * Parameters:
     *   (String) roomJid - JID of room
     *
     * Returns:
     *   (jQuery object) - Tab element
     */
    getTab: function(roomJid) {
      return $('#chat-tabs').children('li[data-roomjid="' + roomJid + '"]');
    },

    /** Function: removeTab
     * Remove tab element.
     *
     * Parameters:
     *   (String) roomJid - JID of room
     */
    removeTab: function(roomJid) {
      self.Chat.getTab(roomJid).remove();
      self.Chat.fitTabs();
    },

    /** Function: setActiveTab
     * Set the active tab.
     *
     * Add CSS classname `active` to the choosen tab and remove `active` from all other.
     *
     * Parameters:
     *   (String) roomJid - JID of room
     */
    setActiveTab: function(roomJid) {
      $('#chat-tabs').children().each(function() {
        var tab = $(this);
        if(tab.attr('data-roomjid') === roomJid) {
          tab.addClass('active');
        } else {
          tab.removeClass('active');
        }
      });
    },

    /** Function: increaseUnreadMessages
     * Increase unread message count in a tab by one.
     *
     * Parameters:
     *   (String) roomJid - JID of room
     *
     * Uses:
     *   - <Window.increaseUnreadMessages>
     */
    increaseUnreadMessages: function(roomJid) {
      var unreadElem = this.getTab(roomJid).find('.unread');
      unreadElem.show().text(unreadElem.text() !== '' ? parseInt(unreadElem.text(), 10) + 1 : 1);
      // only increase window unread messages in private chats
      if (self.Chat.rooms[roomJid].type === 'chat' || Candy.View.getOptions().updateWindowOnAllMessages === true) {
        self.Window.increaseUnreadMessages();
      }
    },

    /** Function: clearUnreadMessages
     * Clear unread message count in a tab.
     *
     * Parameters:
     *   (String) roomJid - JID of room
     *
     * Uses:
     *   - <Window.reduceUnreadMessages>
     */
    clearUnreadMessages: function(roomJid) {
      var unreadElem = self.Chat.getTab(roomJid).find('.unread');
      self.Window.reduceUnreadMessages(unreadElem.text());
      unreadElem.hide().text('');
    },

    /** Function: tabClick
     * Tab click event: show the room associated with the tab and stops the event from doing the default.
     */
    tabClick: function(e) {
      // remember scroll position of current room
      var currentRoomJid = Candy.View.getCurrent().roomJid;
      var roomPane = self.Room.getPane(currentRoomJid, '.message-pane');
      if (roomPane) {
        self.Chat.rooms[currentRoomJid].scrollPosition = roomPane.scrollTop();
      }

      self.Room.show($(this).attr('data-roomjid'));
      e.preventDefault();
    },

    /** Function: tabClose
     * Tab close (click) event: Leave the room (groupchat) or simply close the tab (chat).
     *
     * Parameters:
     *   (DOMEvent) e - Event triggered
     *
     * Returns:
     *   (Boolean) - false, this will stop the event from bubbling
     */
    tabClose: function() {
      var roomJid = $(this).parent().attr('data-roomjid');
      // close private user tab
      if(self.Chat.rooms[roomJid].type === 'chat') {
        self.Room.close(roomJid);
      // close multi-user room tab
      } else {
        Candy.Core.Action.Jabber.Room.Leave(roomJid);
      }
      return false;
    },

    /** Function: allTabsClosed
     * All tabs closed event: Disconnect from service. Hide sound control.
     *
     * TODO: Handle window close
     *
     * Returns:
     *   (Boolean) - false, this will stop the event from bubbling
     */
    allTabsClosed: function() {
      if (Candy.Core.getOptions().disconnectWithoutTabs) {
        Candy.Core.disconnect();
        self.Chat.Toolbar.hide();
        return;
      }
    },

    /** Function: fitTabs
     * Fit tab size according to window size
     */
    fitTabs: function() {
      var availableWidth = $('#chat-tabs').innerWidth(),
        tabsWidth = 0,
        tabs = $('#chat-tabs').children();
      tabs.each(function() {
        tabsWidth += $(this).css({width: 'auto', overflow: 'visible'}).outerWidth(true);
      });
      if(tabsWidth > availableWidth) {
        // tabs.[outer]Width() measures the first element in `tabs`. It's no very readable but nearly two times faster than using :first
        var tabDiffToRealWidth = tabs.outerWidth(true) - tabs.width(),
          tabWidth = Math.floor((availableWidth) / tabs.length) - tabDiffToRealWidth;
        tabs.css({width: tabWidth, overflow: 'hidden'});
      }
    },

    /** Function: adminMessage
     * Display admin message
     *
     * Parameters:
     *   (String) subject - Admin message subject
     *   (String) message - Message to be displayed
     *
     * Triggers:
     *   candy:view.chat.admin-message using {subject, message}
     */
    adminMessage: function(subject, message) {
      if(Candy.View.getCurrent().roomJid) { // Simply dismiss admin message if no room joined so far. TODO: maybe we should show those messages on a dedicated pane?
        message = Candy.Util.Parser.all(message.substring(0, Candy.View.getOptions().crop.message.body));
        if(Candy.View.getOptions().enableXHTML === true) {
          message = Candy.Util.parseAndCropXhtml(message, Candy.View.getOptions().crop.message.body);
        }
        var timestamp = new Date();
        var html = Mustache.to_html(Candy.View.Template.Chat.adminMessage, {
          subject: subject,
          message: message,
          sender: $.i18n._('administratorMessageSubject'),
          time: Candy.Util.localizedTime(timestamp),
          timestamp: timestamp.toISOString()
        });
        $('#chat-rooms').children().each(function() {
          self.Room.appendToMessagePane($(this).attr('data-roomjid'), html);
        });
        self.Room.scrollToBottom(Candy.View.getCurrent().roomJid);

        /** Event: candy:view.chat.admin-message
         * After admin message display
         *
         * Parameters:
         *   (String) presetJid - Preset user JID
         */
        $(Candy).triggerHandler('candy:view.chat.admin-message', {
          'subject' : subject,
          'message' : message
        });
      }
    },

    /** Function: infoMessage
     * Display info message. This is a wrapper for <onInfoMessage> to be able to disable certain info messages.
     *
     * Parameters:
     *   (String) roomJid - Room JID
     *   (String) subject - Subject
     *   (String) message - Message
     */
    infoMessage: function(roomJid, subject, message) {
      self.Chat.onInfoMessage(roomJid, subject, message);
    },

    /** Function: onInfoMessage
     * Display info message. Used by <infoMessage> and several other functions which do not wish that their info message
     * can be disabled (such as kick/ban message or leave/join message in private chats).
     *
     * Parameters:
     *   (String) roomJid - Room JID
     *   (String) subject - Subject
     *   (String) message - Message
     */
    onInfoMessage: function(roomJid, subject, message) {
      message = message || '';
      if(Candy.View.getCurrent().roomJid && self.Chat.rooms[roomJid]) { // Simply dismiss info message if no room joined so far. TODO: maybe we should show those messages on a dedicated pane?
        message = Candy.Util.Parser.all(message.substring(0, Candy.View.getOptions().crop.message.body));
        if(Candy.View.getOptions().enableXHTML === true) {
          message = Candy.Util.parseAndCropXhtml(message, Candy.View.getOptions().crop.message.body);
        }
        var timestamp = new Date();
        var html = Mustache.to_html(Candy.View.Template.Chat.infoMessage, {
          subject: subject,
          message: $.i18n._(message),
          time: Candy.Util.localizedTime(timestamp),
          timestamp: timestamp.toISOString()
        });
        self.Room.appendToMessagePane(roomJid, html);
        if (Candy.View.getCurrent().roomJid === roomJid) {
          self.Room.scrollToBottom(Candy.View.getCurrent().roomJid);
        }
      }
    },

    /** Class: Candy.View.Pane.Toolbar
     * Chat toolbar for things like emoticons toolbar, room management etc.
     */
    Toolbar: {
      _supportsNativeAudio: null,

      /** Function: init
       * Register handler and enable or disable sound and status messages.
       */
      init: function() {
        $('#emoticons-icon').click(function(e) {
        self.Chat.Context.showEmoticonsMenu(e.currentTarget);
          e.stopPropagation();
        });
        $('#chat-autoscroll-control').click(self.Chat.Toolbar.onAutoscrollControlClick);
        try {
          if( !!document.createElement('audio').canPlayType ) {
            var a = document.createElement('audio');
            if( !!(a.canPlayType('audio/mpeg;').replace(/no/, '')) ) {
              self.Chat.Toolbar._supportsNativeAudio = "mp3";
            }
            else if( !!(a.canPlayType('audio/ogg; codecs="vorbis"').replace(/no/, '')) ) {
              self.Chat.Toolbar._supportsNativeAudio = "ogg";
            }
            else if ( !!(a.canPlayType('audio/mp4; codecs="mp4a.40.2"').replace(/no/, '')) ) {
              self.Chat.Toolbar._supportsNativeAudio = "m4a";
            }
          }
        } catch(e){ }
        $('#chat-sound-control').click(self.Chat.Toolbar.onSoundControlClick);
        if(Candy.Util.cookieExists('candy-nosound')) {
          $('#chat-sound-control').click();
        }
        $('#chat-statusmessage-control').click(self.Chat.Toolbar.onStatusMessageControlClick);
        if(Candy.Util.cookieExists('candy-nostatusmessages')) {
          $('#chat-statusmessage-control').click();
        }
      },

      /** Function: show
       * Show toolbar.
       */
      show: function() {
        $('#chat-toolbar').show();
      },

      /** Function: hide
       * Hide toolbar.
       */
      hide: function() {
        $('#chat-toolbar').hide();
      },

      /* Function: update
       * Update toolbar for specific room
       */
      update: function(roomJid) {
        var context = $('#chat-toolbar').find('.context'),
          me = self.Room.getUser(roomJid);
        if(!me || !me.isModerator()) {
          context.hide();
        } else {
          context.show().click(function(e) {
            self.Chat.Context.show(e.currentTarget, roomJid);
            e.stopPropagation();
          });
        }
        self.Chat.Toolbar.updateUsercount(self.Chat.rooms[roomJid].usercount);
      },

      /** Function: playSound
       * Play sound (default method).
       */
      playSound: function() {
        self.Chat.Toolbar.onPlaySound();
      },

      /** Function: onPlaySound
       * Sound play event handler. Uses native (HTML5) audio if supported,
       * otherwise it will attempt to use bgsound with autostart.
       *
       * Don't call this method directly. Call `playSound()` instead.
       * `playSound()` will only call this method if sound is enabled.
       */
      onPlaySound: function() {
        try {
          if(self.Chat.Toolbar._supportsNativeAudio !== null) {
            new Audio(Candy.View.getOptions().assets + 'notify.' + self.Chat.Toolbar._supportsNativeAudio).play();
          } else {
            $('#chat-sound-control bgsound').remove();
            $('<bgsound/>').attr({ src: Candy.View.getOptions().assets + 'notify.mp3', loop: 1, autostart: true }).appendTo("#chat-sound-control");
          }
        } catch (e) {}
      },

      /** Function: onSoundControlClick
       * Sound control click event handler.
       *
       * Toggle sound (overwrite `playSound()`) and handle cookies.
       */
      onSoundControlClick: function() {
        var control = $('#chat-sound-control');
        if(control.hasClass('checked')) {
          self.Chat.Toolbar.playSound = function() {};
          Candy.Util.setCookie('candy-nosound', '1', 365);
        } else {
          self.Chat.Toolbar.playSound = function() {
            self.Chat.Toolbar.onPlaySound();
          };
          Candy.Util.deleteCookie('candy-nosound');
        }
        control.toggleClass('checked');
      },

      /** Function: onAutoscrollControlClick
       * Autoscroll control event handler.
       *
       * Toggle autoscroll
       */
      onAutoscrollControlClick: function() {
        var control = $('#chat-autoscroll-control');
        if(control.hasClass('checked')) {
          self.Room.scrollToBottom = function(roomJid) {
            self.Room.onScrollToStoredPosition(roomJid);
          };
          self.Window.autoscroll = false;
        } else {
          self.Room.scrollToBottom = function(roomJid) {
            self.Room.onScrollToBottom(roomJid);
          };
          self.Room.scrollToBottom(Candy.View.getCurrent().roomJid);
          self.Window.autoscroll = true;
        }
        control.toggleClass('checked');
      },

      /** Function: onStatusMessageControlClick
       * Status message control event handler.
       *
       * Toggle status message
       */
      onStatusMessageControlClick: function() {
        var control = $('#chat-statusmessage-control');
        if(control.hasClass('checked')) {
          self.Chat.infoMessage = function() {};
          Candy.Util.setCookie('candy-nostatusmessages', '1', 365);
        } else {
          self.Chat.infoMessage = function(roomJid, subject, message) {
            self.Chat.onInfoMessage(roomJid, subject, message);
          };
          Candy.Util.deleteCookie('candy-nostatusmessages');
        }
        control.toggleClass('checked');
      },

      /** Function: updateUserCount
       * Update usercount element with count.
       *
       * Parameters:
       *   (Integer) count - Current usercount
       */
      updateUsercount: function(count) {
        $('#chat-usercount').text(count);
      }
    },

    /** Class: Candy.View.Pane.Modal
     * Modal window
     */
    Modal: {
      /** Function: show
       * Display modal window
       *
       * Parameters:
       *   (String) html - HTML code to put into the modal window
       *   (Boolean) showCloseControl - set to true if a close button should be displayed [default false]
       *   (Boolean) showSpinner - set to true if a loading spinner should be shown [default false]
       *   (String) modalClass - custom class (or space-separate classes) to attach to the modal
       */
      show: function(html, showCloseControl, showSpinner, modalClass) {
        if(showCloseControl) {
          self.Chat.Modal.showCloseControl();
        } else {
          self.Chat.Modal.hideCloseControl();
        }
        if(showSpinner) {
          self.Chat.Modal.showSpinner();
        } else {
          self.Chat.Modal.hideSpinner();
        }
        // Reset classes to 'modal-common' only in case .show() is called
        // with different arguments before .hide() can remove the last applied
        // custom class
        $('#chat-modal').removeClass().addClass('modal-common');
        if( modalClass ) {
          $('#chat-modal').addClass(modalClass);
        }
        $('#chat-modal').stop(false, true);
        $('#chat-modal-body').html(html);
        $('#chat-modal').fadeIn('fast');
        $('#chat-modal-overlay').show();
      },

      /** Function: hide
       * Hide modal window
       *
       * Parameters:
       *   (Function) callback - Calls the specified function after modal window has been hidden.
       */
      hide: function(callback) {
        // Reset classes to include only `modal-common`.
        $('#chat-modal').removeClass().addClass('modal-common');
        $('#chat-modal').fadeOut('fast', function() {
          $('#chat-modal-body').text('');
          $('#chat-modal-overlay').hide();
        });
        // restore initial esc handling
        $(document).keydown(function(e) {
          if(e.which === 27) {
            e.preventDefault();
          }
        });
        if (callback) {
          callback();
        }
      },

      /** Function: showSpinner
       * Show loading spinner
       */
      showSpinner: function() {
        $('#chat-modal-spinner').show();
      },

      /** Function: hideSpinner
       * Hide loading spinner
       */
      hideSpinner: function() {
        $('#chat-modal-spinner').hide();
      },

      /** Function: showCloseControl
       * Show a close button
       */
      showCloseControl: function() {
        $('#admin-message-cancel').show().click(function(e) {
          self.Chat.Modal.hide();
          // some strange behaviour on IE7 (and maybe other browsers) triggers onWindowUnload when clicking on the close button.
          // prevent this.
          e.preventDefault();
        });

        // enable esc to close modal
        $(document).keydown(function(e) {
          if(e.which === 27) {
            self.Chat.Modal.hide();
            e.preventDefault();
          }
        });
      },

      /** Function: hideCloseControl
       * Hide the close button
       */
      hideCloseControl: function() {
        $('#admin-message-cancel').hide().click(function() {});
      },

      /** Function: showLoginForm
       * Show the login form modal
       *
       * Parameters:
       *  (String) message - optional message to display above the form
       *  (String) presetJid - optional user jid. if set, the user will only be prompted for password.
       */
      showLoginForm: function(message, presetJid) {
        var domains = Candy.Core.getOptions().domains;
        var hideDomainList = Candy.Core.getOptions().hideDomainList;
        domains = domains ? domains.map( function(d) {return {'domain':d};} )
                           : null;
        var customClass = domains && !hideDomainList ? 'login-with-domains'
                                                     : null;
        self.Chat.Modal.show((message ? message : '') + Mustache.to_html(Candy.View.Template.Login.form, {
          _labelNickname: $.i18n._('labelNickname'),
          _labelUsername: $.i18n._('labelUsername'),
          domains: domains,
          _labelPassword: $.i18n._('labelPassword'),
          _loginSubmit: $.i18n._('loginSubmit'),
          displayPassword: !Candy.Core.isAnonymousConnection(),
          displayUsername: !presetJid,
          displayDomain: domains ? true : false,
          displayNickname: Candy.Core.isAnonymousConnection(),
          presetJid: presetJid ? presetJid : false
        }), null, null, customClass);
        if(hideDomainList) {
          $('#domain').hide();
          $('.at-symbol').hide();
        }
        $('#login-form').children(':input:first').focus();

        // register submit handler
        $('#login-form').submit(function() {
          var username = $('#username').val(),
            password = $('#password').val(),
            domain = $('#domain');
          domain = domain.length ? domain.val().split(' ')[0] : null;

          if (!Candy.Core.isAnonymousConnection()) {
            var jid;
            if(domain) { // domain is stipulated
              // Ensure there is no domain part in username
              username = username.split('@')[0];
              jid = username + '@' + domain;
            } else {  // domain not stipulated
              // guess the input and create a jid out of it
              jid = Candy.Core.getUser() && username.indexOf("@") < 0 ?
              username + '@' + Strophe.getDomainFromJid(Candy.Core.getUser().getJid()) : username;
            }

            if(jid.indexOf("@") < 0 && !Candy.Core.getUser()) {
              Candy.View.Pane.Chat.Modal.showLoginForm($.i18n._('loginInvalid'));
            } else {
              //Candy.View.Pane.Chat.Modal.hide();
              Candy.Core.connect(jid, password);
            }
          } else { // anonymous login
            Candy.Core.connect(presetJid, null, username);
          }
          return false;
        });
      },

      /** Function: showEnterPasswordForm
       * Shows a form for entering room password
       *
       * Parameters:
       *   (String) roomJid - Room jid to join
       *   (String) roomName - Room name
       *   (String) message - [optional] Message to show as the label
       */
      showEnterPasswordForm: function(roomJid, roomName, message) {
        self.Chat.Modal.show(Mustache.to_html(Candy.View.Template.PresenceError.enterPasswordForm, {
          roomName: roomName,
          _labelPassword: $.i18n._('labelPassword'),
          _label: (message ? message : $.i18n._('enterRoomPassword', [roomName])),
          _joinSubmit: $.i18n._('enterRoomPasswordSubmit')
        }), true);
        $('#password').focus();

        // register submit handler
        $('#enter-password-form').submit(function() {
          var password = $('#password').val();

          self.Chat.Modal.hide(function() {
            Candy.Core.Action.Jabber.Room.Join(roomJid, password);
          });
          return false;
        });
      },

      /** Function: showNicknameConflictForm
       * Shows a form indicating that the nickname is already taken and
       * for chosing a new nickname
       *
       * Parameters:
       *   (String) roomJid - Room jid to join
       */
      showNicknameConflictForm: function(roomJid) {
        self.Chat.Modal.show(Mustache.to_html(Candy.View.Template.PresenceError.nicknameConflictForm, {
          _labelNickname: $.i18n._('labelNickname'),
          _label: $.i18n._('nicknameConflict'),
          _loginSubmit: $.i18n._('loginSubmit')
        }));
        $('#nickname').focus();

        // register submit handler
        $('#nickname-conflict-form').submit(function() {
          var nickname = $('#nickname').val();

          self.Chat.Modal.hide(function() {
            Candy.Core.getUser().data.nick = nickname;
            Candy.Core.Action.Jabber.Room.Join(roomJid);
          });
          return false;
        });
      },

      /** Function: showError
       * Show modal containing error message
       *
       * Parameters:
       *   (String) message - key of translation to display
       *   (Array) replacements - array containing replacements for translation (%s)
       */
      showError: function(message, replacements) {
        self.Chat.Modal.show(Mustache.to_html(Candy.View.Template.PresenceError.displayError, {
          _error: $.i18n._(message, replacements)
        }), true);
      }
    },

    /** Class: Candy.View.Pane.Tooltip
     * Class to display tooltips over specific elements
     */
    Tooltip: {
      /** Function: show
       * Show a tooltip on event.currentTarget with content specified or content within the target's attribute data-tooltip.
       *
       * On mouseleave on the target, hide the tooltip.
       *
       * Parameters:
       *   (Event) event - Triggered event
       *   (String) content - Content to display [optional]
       */
      show: function(event, content) {
        var tooltip = $('#tooltip'),
          target = $(event.currentTarget);

        if(!content) {
          content = target.attr('data-tooltip');
        }

        if(tooltip.length === 0) {
          var html = Mustache.to_html(Candy.View.Template.Chat.tooltip);
          $('#chat-pane').append(html);
          tooltip = $('#tooltip');
        }

        $('#context-menu').hide();

        tooltip.stop(false, true);
        tooltip.children('div').html(content);

        var pos = target.offset(),
            posLeft = Candy.Util.getPosLeftAccordingToWindowBounds(tooltip, pos.left),
            posTop  = Candy.Util.getPosTopAccordingToWindowBounds(tooltip, pos.top);

        tooltip
          .css({'left': posLeft.px, 'top': posTop.px})
          .removeClass('left-top left-bottom right-top right-bottom')
          .addClass(posLeft.backgroundPositionAlignment + '-' + posTop.backgroundPositionAlignment)
          .fadeIn('fast');

        target.mouseleave(function(event) {
          event.stopPropagation();
          $('#tooltip').stop(false, true).fadeOut('fast', function() {$(this).css({'top': 0, 'left': 0});});
        });
      }
    },

    /** Class: Candy.View.Pane.Context
     * Context menu for actions and settings
     */
    Context: {
      /** Function: init
       * Initialize context menu and setup mouseleave handler.
       */
      init: function() {
        if ($('#context-menu').length === 0) {
          var html = Mustache.to_html(Candy.View.Template.Chat.Context.menu);
          $('#chat-pane').append(html);
          $('#context-menu').mouseleave(function() {
            $(this).fadeOut('fast');
          });
        }
      },

      /** Function: show
       * Show context menu (positions it according to the window height/width)
       *
       * Parameters:
       *   (Element) elem - On which element it should be shown
       *   (String) roomJid - Room Jid of the room it should be shown
       *   (Candy.Core.chatUser) user - User
       *
       * Uses:
       *   <getMenuLinks> for getting menulinks the user has access to
       *   <Candy.Util.getPosLeftAccordingToWindowBounds> for positioning
       *   <Candy.Util.getPosTopAccordingToWindowBounds> for positioning
       *
       * Triggers:
       *   candy:view.roster.after-context-menu using {roomJid, user, elements}
       */
      show: function(elem, roomJid, user) {
        elem = $(elem);
        var roomId = self.Chat.rooms[roomJid].id,
          menu = $('#context-menu'),
          links = $('ul li', menu);

        $('#tooltip').hide();

        // add specific context-user class if a user is available (when context menu should be opened next to a user)
        if(!user) {
          user = Candy.Core.getUser();
        }

        links.remove();

        var menulinks = this.getMenuLinks(roomJid, user, elem),
          id,
          clickHandler = function(roomJid, user) {
            return function(event) {
              event.data.callback(event, roomJid, user);
              $('#context-menu').hide();
            };
          };

        for(id in menulinks) {
          if(menulinks.hasOwnProperty(id)) {
            var link = menulinks[id],
              html = Mustache.to_html(Candy.View.Template.Chat.Context.menulinks, {
                'roomId'   : roomId,
                'class'    : link['class'],
                'id'       : id,
                'label'    : link.label
              });
            $('ul', menu).append(html);
            $('#context-menu-' + id).bind('click', link, clickHandler(roomJid, user));
          }
        }
        // if `id` is set the menu is not empty
        if(id) {
          var pos = elem.offset(),
            posLeft = Candy.Util.getPosLeftAccordingToWindowBounds(menu, pos.left),
            posTop  = Candy.Util.getPosTopAccordingToWindowBounds(menu, pos.top);

          menu
            .css({'left': posLeft.px, 'top': posTop.px})
            .removeClass('left-top left-bottom right-top right-bottom')
            .addClass(posLeft.backgroundPositionAlignment + '-' + posTop.backgroundPositionAlignment)
            .fadeIn('fast');

          /** Event: candy:view.roster.after-context-menu
           * After context menu display
           *
           * Parameters:
           *   (String) roomJid - room where the context menu has been triggered
           *   (Candy.Core.ChatUser) user - User
           *   (jQuery.Element) element - Menu element
           */
          $(Candy).triggerHandler('candy:view.roster.after-context-menu', {
            'roomJid' : roomJid,
            'user' : user,
            'element': menu
          });

          return true;
        }
      },

      /** Function: getMenuLinks
       * Extends <initialMenuLinks> with menu links gathered from candy:view.roster.contextmenu
       *
       * Parameters:
       *   (String) roomJid - Room in which the menu will be displayed
       *   (Candy.Core.ChatUser) user - User
       *   (jQuery.Element) elem - Parent element of the context menu
       *
       * Triggers:
       *   candy:view.roster.context-menu using {roomJid, user, elem}
       *
       * Returns:
       *   (Object) - object containing the extended menulinks.
       */
      getMenuLinks: function(roomJid, user, elem) {
        var menulinks, id;

        var evtData = {
          'roomJid' : roomJid,
          'user' : user,
          'elem': elem,
          'menulinks': this.initialMenuLinks(elem)
        };

        /** Event: candy:view.roster.context-menu
         * Modify existing menu links (add links)
         *
         * In order to modify the links you need to change the object passed with an additional
         * key "menulinks" containing the menulink object.
         *
         * Parameters:
         *   (String) roomJid - Room on which the menu should be displayed
         *   (Candy.Core.ChatUser) user - User
         *   (jQuery.Element) elem - Parent element of the context menu
         */
        $(Candy).triggerHandler('candy:view.roster.context-menu', evtData);

        menulinks = evtData.menulinks;

        for(id in menulinks) {
          if(menulinks.hasOwnProperty(id) && menulinks[id].requiredPermission !== undefined && !menulinks[id].requiredPermission(user, self.Room.getUser(roomJid), elem)) {
            delete menulinks[id];
          }
        }
        return menulinks;
      },

      /** Function: initialMenuLinks
       * Returns initial menulinks. The following are initial:
       *
       * - Private Chat
       * - Ignore
       * - Unignore
       * - Kick
       * - Ban
       * - Change Subject
       *
       * Returns:
       *   (Object) - object containing those menulinks
       */
      initialMenuLinks: function() {
        return {
          'private': {
            requiredPermission: function(user, me) {
              return me.getNick() !== user.getNick() && Candy.Core.getRoom(Candy.View.getCurrent().roomJid) && !Candy.Core.getUser().isInPrivacyList('ignore', user.getJid());
            },
            'class' : 'private',
            'label' : $.i18n._('privateActionLabel'),
            'callback' : function(e, roomJid, user) {
              $('#user-' + Candy.Util.jidToId(roomJid) + '-' + Candy.Util.jidToId(user.getJid())).click();
            }
          },
          'ignore': {
            requiredPermission: function(user, me) {
              return me.getNick() !== user.getNick() && !Candy.Core.getUser().isInPrivacyList('ignore', user.getJid());
            },
            'class' : 'ignore',
            'label' : $.i18n._('ignoreActionLabel'),
            'callback' : function(e, roomJid, user) {
              Candy.View.Pane.Room.ignoreUser(roomJid, user.getJid());
            }
          },
          'unignore': {
            requiredPermission: function(user, me) {
              return me.getNick() !== user.getNick() && Candy.Core.getUser().isInPrivacyList('ignore', user.getJid());
            },
            'class' : 'unignore',
            'label' : $.i18n._('unignoreActionLabel'),
            'callback' : function(e, roomJid, user) {
              Candy.View.Pane.Room.unignoreUser(roomJid, user.getJid());
            }
          },
          'kick': {
            requiredPermission: function(user, me) {
              return me.getNick() !== user.getNick() && me.isModerator() && !user.isModerator();
            },
            'class' : 'kick',
            'label' : $.i18n._('kickActionLabel'),
            'callback' : function(e, roomJid, user) {
              self.Chat.Modal.show(Mustache.to_html(Candy.View.Template.Chat.Context.contextModalForm, {
                _label: $.i18n._('reason'),
                _submit: $.i18n._('kickActionLabel')
              }), true);
              $('#context-modal-field').focus();
              $('#context-modal-form').submit(function() {
                Candy.Core.Action.Jabber.Room.Admin.UserAction(roomJid, user.getJid(), 'kick', $('#context-modal-field').val());
                self.Chat.Modal.hide();
                return false; // stop propagation & preventDefault, as otherwise you get disconnected (wtf?)
              });
            }
          },
          'ban': {
            requiredPermission: function(user, me) {
              return me.getNick() !== user.getNick() && me.isModerator() && !user.isModerator();
            },
            'class' : 'ban',
            'label' : $.i18n._('banActionLabel'),
            'callback' : function(e, roomJid, user) {
              self.Chat.Modal.show(Mustache.to_html(Candy.View.Template.Chat.Context.contextModalForm, {
                _label: $.i18n._('reason'),
                _submit: $.i18n._('banActionLabel')
              }), true);
              $('#context-modal-field').focus();
              $('#context-modal-form').submit(function() {
                Candy.Core.Action.Jabber.Room.Admin.UserAction(roomJid, user.getJid(), 'ban', $('#context-modal-field').val());
                self.Chat.Modal.hide();
                return false; // stop propagation & preventDefault, as otherwise you get disconnected (wtf?)
              });
            }
          },
          'subject': {
            requiredPermission: function(user, me) {
              return me.getNick() === user.getNick() && me.isModerator();
            },
            'class': 'subject',
            'label' : $.i18n._('setSubjectActionLabel'),
            'callback': function(e, roomJid) {
              self.Chat.Modal.show(Mustache.to_html(Candy.View.Template.Chat.Context.contextModalForm, {
                _label: $.i18n._('subject'),
                _submit: $.i18n._('setSubjectActionLabel')
              }), true);
              $('#context-modal-field').focus();
              $('#context-modal-form').submit(function(e) {
                Candy.Core.Action.Jabber.Room.Admin.SetSubject(roomJid, $('#context-modal-field').val());
                self.Chat.Modal.hide();
                e.preventDefault();
              });
            }
          }
        };
      },

      /** Function: showEmoticonsMenu
       * Shows the special emoticons menu
       *
       * Parameters:
       *   (Element) elem - Element on which it should be positioned to.
       *
       * Returns:
       *   (Boolean) - true
       */
      showEmoticonsMenu: function(elem) {
        elem = $(elem);
        var pos = elem.offset(),
          menu = $('#context-menu'),
          content = $('ul', menu),
          emoticons = '',
          i;

        $('#tooltip').hide();

        for(i = Candy.Util.Parser.emoticons.length-1; i >= 0; i--) {
          emoticons = '<img src="' + Candy.Util.Parser._emoticonPath + Candy.Util.Parser.emoticons[i].image + '" alt="' + Candy.Util.Parser.emoticons[i].plain + '" />' + emoticons;
        }
        content.html('<li class="emoticons">' + emoticons + '</li>');
        content.find('img').click(function() {
          var input = Candy.View.Pane.Room.getPane(Candy.View.getCurrent().roomJid, '.message-form').children('.field'),
            value = input.val(),
            emoticon = $(this).attr('alt') + ' ';
          input.val(value ? value + ' ' + emoticon : emoticon).focus();

          // Once you make a selction, hide the menu.
          menu.hide();
        });

        var posLeft = Candy.Util.getPosLeftAccordingToWindowBounds(menu, pos.left),
          posTop  = Candy.Util.getPosTopAccordingToWindowBounds(menu, pos.top);

        menu
          .css({'left': posLeft.px, 'top': posTop.px})
          .removeClass('left-top left-bottom right-top right-bottom')
          .addClass(posLeft.backgroundPositionAlignment + '-' + posTop.backgroundPositionAlignment)
          .fadeIn('fast');

        return true;
      }
    }
  };

  return self;
}(Candy.View.Pane || {}, jQuery));