Aleksander Machniak
2015-08-16 3fa3f156cae81ef6c453ee3969b95a0b77bb1824
commit | author | age
b34d67 1 /**
TB 2  * Roundcube Webmail Client Script
3  *
4  * This file is part of the Roundcube Webmail client
5  *
6  * @licstart  The following is the entire license notice for the
7  * JavaScript code in this file.
8  *
9  * Copyright (C) 2005-2014, The Roundcube Dev Team
10  * Copyright (C) 2011-2014, Kolab Systems AG
11  *
12  * The JavaScript code in this page is free software: you can
13  * redistribute it and/or modify it under the terms of the GNU
14  * General Public License (GNU GPL) as published by the Free Software
15  * Foundation, either version 3 of the License, or (at your option)
16  * any later version.  The code is distributed WITHOUT ANY WARRANTY;
17  * without even the implied warranty of MERCHANTABILITY or FITNESS
18  * FOR A PARTICULAR PURPOSE.  See the GNU GPL for more details.
19  *
20  * As additional permission under GNU GPL version 3 section 7, you
21  * may distribute non-source (e.g., minimized or compacted) forms of
22  * that code without the copy of the GNU GPL normally required by
23  * section 4, provided you include this license notice and a URL
24  * through which recipients can access the Corresponding Source.
25  *
26  * @licend  The above is the entire license notice
27  * for the JavaScript code in this file.
28  *
29  * @author Thomas Bruederli <roundcube@gmail.com>
30  * @author Aleksander 'A.L.E.C' Machniak <alec@alec.pl>
31  * @author Charles McNulty <charles@charlesmcnulty.com>
32  *
33  * @requires jquery.js, common.js, list.js
34  */
24053e 35
4e17e6 36 function rcube_webmail()
cc97ea 37 {
8fa922 38   this.labels = {};
A 39   this.buttons = {};
40   this.buttons_sel = {};
41   this.gui_objects = {};
42   this.gui_containers = {};
43   this.commands = {};
44   this.command_handlers = {};
45   this.onloads = [];
ad334a 46   this.messages = {};
eeb73c 47   this.group2expand = {};
017c4f 48   this.http_request_jobs = {};
a5fe9a 49   this.menu_stack = [];
4e17e6 50
T 51   // webmail client settings
b19097 52   this.dblclick_time = 500;
34003c 53   this.message_time = 5000;
a5fe9a 54   this.identifier_expr = /[^0-9a-z_-]/gi;
8fa922 55
3c047d 56   // environment defaults
AM 57   this.env = {
58     request_timeout: 180,  // seconds
59     draft_autosave: 0,     // seconds
60     comm_path: './',
61     recipients_separator: ',',
ece3a5 62     recipients_delimiter: ', ',
AM 63     popup_width: 1150,
64     popup_width_small: 900
3c047d 65   };
AM 66
67   // create protected reference to myself
68   this.ref = 'rcmail';
69   var ref = this;
cc97ea 70
T 71   // set jQuery ajax options
8fa922 72   $.ajaxSetup({
110360 73     cache: false,
T 74     timeout: this.env.request_timeout * 1000,
75     error: function(request, status, err){ ref.http_error(request, status, err); },
76     beforeSend: function(xmlhttp){ xmlhttp.setRequestHeader('X-Roundcube-Request', ref.env.request_token); }
cc97ea 77   });
9a5261 78
3c047d 79   // unload fix
f1aaca 80   $(window).bind('beforeunload', function() { ref.unload = true; });
7794ae 81
f11541 82   // set environment variable(s)
T 83   this.set_env = function(p, value)
8fa922 84   {
d8cf6d 85     if (p != null && typeof p === 'object' && !value)
f11541 86       for (var n in p)
T 87         this.env[n] = p[n];
88     else
89       this.env[p] = value;
8fa922 90   };
10a699 91
T 92   // add a localized label to the client environment
4dcd43 93   this.add_label = function(p, value)
8fa922 94   {
4dcd43 95     if (typeof p == 'string')
T 96       this.labels[p] = value;
97     else if (typeof p == 'object')
98       $.extend(this.labels, p);
8fa922 99   };
4e17e6 100
T 101   // add a button to the button list
102   this.register_button = function(command, id, type, act, sel, over)
8fa922 103   {
4e17e6 104     var button_prop = {id:id, type:type};
3c047d 105
4e17e6 106     if (act) button_prop.act = act;
T 107     if (sel) button_prop.sel = sel;
108     if (over) button_prop.over = over;
3c047d 109
AM 110     if (!this.buttons[command])
111       this.buttons[command] = [];
4e17e6 112
0e7b66 113     this.buttons[command].push(button_prop);
699a25 114
e639c5 115     if (this.loaded)
T 116       init_button(command, button_prop);
8fa922 117   };
4e17e6 118
T 119   // register a specific gui object
120   this.gui_object = function(name, id)
8fa922 121   {
e639c5 122     this.gui_objects[name] = this.loaded ? rcube_find_object(id) : id;
8fa922 123   };
A 124
cc97ea 125   // register a container object
T 126   this.gui_container = function(name, id)
127   {
128     this.gui_containers[name] = id;
129   };
8fa922 130
cc97ea 131   // add a GUI element (html node) to a specified container
T 132   this.add_element = function(elm, container)
133   {
134     if (this.gui_containers[container] && this.gui_containers[container].jquery)
135       this.gui_containers[container].append(elm);
136   };
137
138   // register an external handler for a certain command
139   this.register_command = function(command, callback, enable)
140   {
141     this.command_handlers[command] = callback;
8fa922 142
cc97ea 143     if (enable)
T 144       this.enable_command(command, true);
145   };
8fa922 146
a7d5c6 147   // execute the given script on load
T 148   this.add_onload = function(f)
cc97ea 149   {
0e7b66 150     this.onloads.push(f);
cc97ea 151   };
4e17e6 152
T 153   // initialize webmail client
154   this.init = function()
8fa922 155   {
2611ac 156     var n;
4e17e6 157     this.task = this.env.task;
8fa922 158
4e17e6 159     // check browser
a5f8c8 160     if (this.env.server_error != 409 && (!bw.dom || !bw.xmlhttp_test() || (bw.mz && bw.vendver < 1.9) || (bw.ie && bw.vendver < 7))) {
6b47de 161       this.goto_url('error', '_code=0x199');
4e17e6 162       return;
8fa922 163     }
681ba6 164
AM 165     if (!this.env.blankpage)
166       this.env.blankpage = this.assets_path('program/resources/blank.gif');
9e953b 167
cc97ea 168     // find all registered gui containers
249815 169     for (n in this.gui_containers)
cc97ea 170       this.gui_containers[n] = $('#'+this.gui_containers[n]);
T 171
4e17e6 172     // find all registered gui objects
249815 173     for (n in this.gui_objects)
4e17e6 174       this.gui_objects[n] = rcube_find_object(this.gui_objects[n]);
8fa922 175
10e2db 176     // clickjacking protection
T 177     if (this.env.x_frame_options) {
178       try {
179         // bust frame if not allowed
180         if (this.env.x_frame_options == 'deny' && top.location.href != self.location.href)
181           top.location.href = self.location.href;
182         else if (top.location.hostname != self.location.hostname)
183           throw 1;
184       } catch (e) {
185         // possible clickjacking attack: disable all form elements
186         $('form').each(function(){ ref.lock_form(this, true); });
187         this.display_message("Blocked: possible clickjacking attack!", 'error');
188         return;
189       }
190     }
191
29f977 192     // init registered buttons
T 193     this.init_buttons();
a7d5c6 194
4e17e6 195     // tell parent window that this frame is loaded
27acfd 196     if (this.is_framed()) {
ad334a 197       parent.rcmail.set_busy(false, null, parent.rcmail.env.frame_lock);
A 198       parent.rcmail.env.frame_lock = null;
199     }
4e17e6 200
T 201     // enable general commands
bc2c43 202     this.enable_command('close', 'logout', 'mail', 'addressbook', 'settings', 'save-pref',
b2992d 203       'compose', 'undo', 'about', 'switch-task', 'menu-open', 'menu-close', 'menu-save', true);
8fa922 204
e8bcf0 205     // set active task button
TB 206     this.set_button(this.task, 'sel');
4e17e6 207
a25d39 208     if (this.env.permaurl)
271efe 209       this.enable_command('permaurl', 'extwin', true);
9e953b 210
8fa922 211     switch (this.task) {
A 212
4e17e6 213       case 'mail':
f52c93 214         // enable mail commands
4f53ab 215         this.enable_command('list', 'checkmail', 'add-contact', 'search', 'reset-search', 'collapse-folder', 'import-messages', true);
8fa922 216
A 217         if (this.gui_objects.messagelist) {
9800a8 218           this.message_list = new rcube_list_widget(this.gui_objects.messagelist, {
A 219             multiselect:true, multiexpand:true, draggable:true, keyboard:true,
6c9d49 220             column_movable:this.env.col_movable, dblclick_time:this.dblclick_time
9800a8 221             });
772bec 222           this.message_list
2611ac 223             .addEventListener('initrow', function(o) { ref.init_message_row(o); })
AM 224             .addEventListener('dblclick', function(o) { ref.msglist_dbl_click(o); })
225             .addEventListener('click', function(o) { ref.msglist_click(o); })
226             .addEventListener('keypress', function(o) { ref.msglist_keypress(o); })
227             .addEventListener('select', function(o) { ref.msglist_select(o); })
228             .addEventListener('dragstart', function(o) { ref.drag_start(o); })
229             .addEventListener('dragmove', function(e) { ref.drag_move(e); })
230             .addEventListener('dragend', function(e) { ref.drag_end(e); })
231             .addEventListener('expandcollapse', function(o) { ref.msglist_expand(o); })
232             .addEventListener('column_replace', function(o) { ref.msglist_set_coltypes(o); })
233             .addEventListener('listupdate', function(o) { ref.triggerEvent('listupdate', o); })
772bec 234             .init();
da8f11 235
c83535 236           // TODO: this should go into the list-widget code
TB 237           $(this.message_list.thead).on('click', 'a.sortcol', function(e){
2611ac 238             return ref.command('sort', $(this).attr('rel'), this);
c83535 239           });
TB 240
bc2c43 241           this.enable_command('toggle_status', 'toggle_flag', 'sort', true);
f50a66 242           this.enable_command('set-listmode', this.env.threads && !this.is_multifolder_listing());
8fa922 243
f52c93 244           // load messages
9800a8 245           this.command('list');
1f020b 246
f1aaca 247           $(this.gui_objects.qsearchbox).val(this.env.search_text).focusin(function() { ref.message_list.blur(); });
8fa922 248         }
eb6842 249
1b30a7 250         this.set_button_titles();
4e17e6 251
d9f109 252         this.env.message_commands = ['show', 'reply', 'reply-all', 'reply-list',
a45f9b 253           'move', 'copy', 'delete', 'open', 'mark', 'edit', 'viewsource',
bc2c43 254           'print', 'load-attachment', 'download-attachment', 'show-headers', 'hide-headers', 'download',
a02c77 255           'forward', 'forward-inline', 'forward-attachment', 'change-format'];
14259c 256
46cdbf 257         if (this.env.action == 'show' || this.env.action == 'preview') {
64e3e8 258           this.enable_command(this.env.message_commands, this.env.uid);
e25a35 259           this.enable_command('reply-list', this.env.list_post);
da8f11 260
29b397 261           if (this.env.action == 'show') {
c31360 262             this.http_request('pagenav', {_uid: this.env.uid, _mbox: this.env.mailbox, _search: this.env.search_request},
29b397 263               this.display_message('', 'loading'));
8fa922 264           }
A 265
da8f11 266           if (this.env.blockedobjects) {
A 267             if (this.gui_objects.remoteobjectsmsg)
268               this.gui_objects.remoteobjectsmsg.style.display = 'block';
269             this.enable_command('load-images', 'always-load', true);
8fa922 270           }
da8f11 271
A 272           // make preview/message frame visible
27acfd 273           if (this.env.action == 'preview' && this.is_framed()) {
da8f11 274             this.enable_command('compose', 'add-contact', false);
A 275             parent.rcmail.show_contentframe(true);
276           }
8fa922 277         }
da8f11 278         else if (this.env.action == 'compose') {
de98a8 279           this.env.address_group_stack = [];
0b1de8 280           this.env.compose_commands = ['send-attachment', 'remove-attachment', 'send', 'cancel',
TB 281             'toggle-editor', 'list-adresses', 'pushgroup', 'search', 'reset-search', 'extwin',
6789bf 282             'insert-response', 'save-response', 'menu-open', 'menu-close'];
d7f9eb 283
A 284           if (this.env.drafts_mailbox)
285             this.env.compose_commands.push('savedraft')
286
0933d6 287           this.enable_command(this.env.compose_commands, 'identities', 'responses', true);
da8f11 288
8304e5 289           // add more commands (not enabled)
T 290           $.merge(this.env.compose_commands, ['add-recipient', 'firstpage', 'previouspage', 'nextpage', 'lastpage']);
291
646b64 292           if (window.googie) {
AM 293             this.env.editor_config.spellchecker = googie;
294             this.env.editor_config.spellcheck_observer = function(s) { ref.spellcheck_state(); };
295
d7f9eb 296             this.env.compose_commands.push('spellcheck')
4be86f 297             this.enable_command('spellcheck', true);
0b1de8 298           }
646b64 299
AM 300           // initialize HTML editor
301           this.editor_init(this.env.editor_config, this.env.composebody);
0b1de8 302
TB 303           // init canned response functions
304           if (this.gui_objects.responseslist) {
305             $('a.insertresponse', this.gui_objects.responseslist)
0933d6 306               .attr('unselectable', 'on')
0b1de8 307               .mousedown(function(e){ return rcube_event.cancel(e); })
ea0866 308               .bind('mouseup keypress', function(e){
TB 309                 if (e.type == 'mouseup' || rcube_event.get_keycode(e) == 13) {
310                   ref.command('insert-response', $(this).attr('rel'));
311                   $(document.body).trigger('mouseup');  // hides the menu
312                   return rcube_event.cancel(e);
313                 }
0b1de8 314               });
TB 315
04fbc5 316             // avoid textarea loosing focus when hitting the save-response button/link
a5fe9a 317             $.each(this.buttons['save-response'] || [], function (i, v) {
AM 318               $('#' + v.id).mousedown(function(e){ return rcube_event.cancel(e); })
319             });
8fa922 320           }
f05834 321
A 322           // init message compose form
323           this.init_messageform();
8fa922 324         }
049428 325         else if (this.env.action == 'get')
AM 326           this.enable_command('download', 'print', true);
da8f11 327         // show printing dialog
4f53ab 328         else if (this.env.action == 'print' && this.env.uid) {
f7af22 329           this.print_dialog();
4f53ab 330         }
4e17e6 331
15a9d1 332         // get unread count for each mailbox
da8f11 333         if (this.gui_objects.mailboxlist) {
85360d 334           this.env.unread_counts = {};
f11541 335           this.gui_objects.folderlist = this.gui_objects.mailboxlist;
c31360 336           this.http_request('getunread');
8fa922 337         }
A 338
18a28a 339         // init address book widget
T 340         if (this.gui_objects.contactslist) {
341           this.contact_list = new rcube_list_widget(this.gui_objects.contactslist,
ea0866 342             { multiselect:true, draggable:false, keyboard:true });
772bec 343           this.contact_list
2611ac 344             .addEventListener('initrow', function(o) { ref.triggerEvent('insertrow', { cid:o.uid, row:o }); })
772bec 345             .addEventListener('select', function(o) { ref.compose_recipient_select(o); })
b4cbed 346             .addEventListener('dblclick', function(o) { ref.compose_add_recipient(); })
d58c39 347             .addEventListener('keypress', function(o) {
TB 348               if (o.key_pressed == o.ENTER_KEY) {
b4cbed 349                 if (!ref.compose_add_recipient()) {
d58c39 350                   // execute link action on <enter> if not a recipient entry
TB 351                   if (o.last_selected && String(o.last_selected).charAt(0) == 'G') {
352                     $(o.rows[o.last_selected].obj).find('a').first().click();
353                   }
354                 }
355               }
356             })
772bec 357             .init();
b4cbed 358
AM 359           // remember last focused address field
360           $('#_to,#_cc,#_bcc').focus(function() { ref.env.focused_field = this; });
18a28a 361         }
T 362
363         if (this.gui_objects.addressbookslist) {
364           this.gui_objects.folderlist = this.gui_objects.addressbookslist;
365           this.enable_command('list-adresses', true);
366         }
367
fba1f5 368         // ask user to send MDN
da8f11 369         if (this.env.mdn_request && this.env.uid) {
c31360 370           var postact = 'sendmdn',
A 371             postdata = {_uid: this.env.uid, _mbox: this.env.mailbox};
372           if (!confirm(this.get_label('mdnrequest'))) {
373             postdata._flag = 'mdnsent';
374             postact = 'mark';
375           }
376           this.http_post(postact, postdata);
8fa922 377         }
4e17e6 378
e349a8 379         // detect browser capabilities
222c7d 380         if (!this.is_framed() && !this.env.extwin)
e349a8 381           this.browser_capabilities_check();
AM 382
4e17e6 383         break;
T 384
385       case 'addressbook':
de98a8 386         this.env.address_group_stack = [];
TB 387
a61bbb 388         if (this.gui_objects.folderlist)
T 389           this.env.contactfolders = $.extend($.extend({}, this.env.address_sources), this.env.contactgroups);
8fa922 390
487173 391         this.enable_command('add', 'import', this.env.writable_source);
04fbc5 392         this.enable_command('list', 'listgroup', 'pushgroup', 'popgroup', 'listsearch', 'search', 'reset-search', 'advanced-search', true);
487173 393
8fa922 394         if (this.gui_objects.contactslist) {
a61bbb 395           this.contact_list = new rcube_list_widget(this.gui_objects.contactslist,
T 396             {multiselect:true, draggable:this.gui_objects.folderlist?true:false, keyboard:true});
772bec 397           this.contact_list
2611ac 398             .addEventListener('initrow', function(o) { ref.triggerEvent('insertrow', { cid:o.uid, row:o }); })
AM 399             .addEventListener('keypress', function(o) { ref.contactlist_keypress(o); })
400             .addEventListener('select', function(o) { ref.contactlist_select(o); })
401             .addEventListener('dragstart', function(o) { ref.drag_start(o); })
402             .addEventListener('dragmove', function(e) { ref.drag_move(e); })
403             .addEventListener('dragend', function(e) { ref.drag_end(e); })
772bec 404             .init();
04fbc5 405
2611ac 406           $(this.gui_objects.qsearchbox).focusin(function() { ref.contact_list.blur(); });
9382b6 407
62811c 408           this.update_group_commands();
487173 409           this.command('list');
8fa922 410         }
d1d2c4 411
71a522 412         if (this.gui_objects.savedsearchlist) {
TB 413           this.savedsearchlist = new rcube_treelist_widget(this.gui_objects.savedsearchlist, {
414             id_prefix: 'rcmli',
415             id_encode: this.html_identifier_encode,
416             id_decode: this.html_identifier_decode
417           });
418
419           this.savedsearchlist.addEventListener('select', function(node) {
420             ref.triggerEvent('selectfolder', { folder:node.id, prefix:'rcmli' }); });
421         }
422
4e17e6 423         this.set_page_buttons();
8fa922 424
cb7d32 425         if (this.env.cid) {
4e17e6 426           this.enable_command('show', 'edit', true);
cb7d32 427           // register handlers for group assignment via checkboxes
T 428           if (this.gui_objects.editform) {
2c77f5 429             $('input.groupmember').change(function() {
A 430               ref.group_member_change(this.checked ? 'add' : 'del', ref.env.cid, ref.env.source, this.value);
cb7d32 431             });
T 432           }
433         }
4e17e6 434
e9a9f2 435         if (this.gui_objects.editform) {
4e17e6 436           this.enable_command('save', true);
83f707 437           if (this.env.action == 'add' || this.env.action == 'edit' || this.env.action == 'search')
e9a9f2 438               this.init_contact_form();
f7af22 439         }
AM 440         else if (this.env.action == 'print') {
441           this.print_dialog();
9d2a3a 442         }
487173 443
4e17e6 444         break;
T 445
446       case 'settings':
0ce212 447         this.enable_command('preferences', 'identities', 'responses', 'save', 'folders', true);
8fa922 448
e50551 449         if (this.env.action == 'identities') {
223ae9 450           this.enable_command('add', this.env.identities_level < 2);
875ac8 451         }
e50551 452         else if (this.env.action == 'edit-identity' || this.env.action == 'add-identity') {
7c2a93 453           this.enable_command('save', 'edit', 'toggle-editor', true);
223ae9 454           this.enable_command('delete', this.env.identities_level < 2);
646b64 455
AM 456           // initialize HTML editor
457           this.editor_init(this.env.editor_config, 'rcmfd_signature');
875ac8 458         }
e50551 459         else if (this.env.action == 'folders') {
af3c04 460           this.enable_command('subscribe', 'unsubscribe', 'create-folder', 'rename-folder', true);
A 461         }
462         else if (this.env.action == 'edit-folder' && this.gui_objects.editform) {
463           this.enable_command('save', 'folder-size', true);
f47727 464           parent.rcmail.env.exists = this.env.messagecount;
af3c04 465           parent.rcmail.enable_command('purge', this.env.messagecount);
A 466         }
0ce212 467         else if (this.env.action == 'responses') {
TB 468           this.enable_command('add', true);
469         }
6b47de 470
fb4663 471         if (this.gui_objects.identitieslist) {
772bec 472           this.identity_list = new rcube_list_widget(this.gui_objects.identitieslist,
f0928e 473             {multiselect:false, draggable:false, keyboard:true});
772bec 474           this.identity_list
2611ac 475             .addEventListener('select', function(o) { ref.identity_select(o); })
f0928e 476             .addEventListener('keypress', function(o) {
TB 477               if (o.key_pressed == o.ENTER_KEY) {
478                 ref.identity_select(o);
479               }
480             })
772bec 481             .init()
AM 482             .focus();
fb4663 483         }
A 484         else if (this.gui_objects.sectionslist) {
f0928e 485           this.sections_list = new rcube_list_widget(this.gui_objects.sectionslist, {multiselect:false, draggable:false, keyboard:true});
772bec 486           this.sections_list
2611ac 487             .addEventListener('select', function(o) { ref.section_select(o); })
f0928e 488             .addEventListener('keypress', function(o) { if (o.key_pressed == o.ENTER_KEY) ref.section_select(o); })
772bec 489             .init()
AM 490             .focus();
875ac8 491         }
0ce212 492         else if (this.gui_objects.subscriptionlist) {
b0dbf3 493           this.init_subscription_list();
0ce212 494         }
TB 495         else if (this.gui_objects.responseslist) {
f0928e 496           this.responses_list = new rcube_list_widget(this.gui_objects.responseslist, {multiselect:false, draggable:false, keyboard:true});
772bec 497           this.responses_list
AM 498             .addEventListener('select', function(list) {
499               var win, id = list.get_single_selection();
2611ac 500               ref.enable_command('delete', !!id && $.inArray(id, ref.env.readonly_responses) < 0);
AM 501               if (id && (win = ref.get_frame_window(ref.env.contentframe))) {
502                 ref.set_busy(true);
503                 ref.location_href({ _action:'edit-response', _key:id, _framed:1 }, win);
772bec 504               }
AM 505             })
506             .init()
507             .focus();
0ce212 508         }
b0dbf3 509
4e17e6 510         break;
T 511
512       case 'login':
cc97ea 513         var input_user = $('#rcmloginuser');
f1aaca 514         input_user.bind('keyup', function(e){ return ref.login_user_keyup(e); });
8fa922 515
cc97ea 516         if (input_user.val() == '')
4e17e6 517           input_user.focus();
cc97ea 518         else
T 519           $('#rcmloginpwd').focus();
c8ae24 520
T 521         // detect client timezone
361a91 522         if (window.jstz) {
086b15 523           var timezone = jstz.determine();
TB 524           if (timezone.name())
525             $('#rcmlogintz').val(timezone.name());
526         }
527         else {
528           $('#rcmlogintz').val(new Date().getStdTimezoneOffset() / -60);
529         }
c8ae24 530
effdb3 531         // display 'loading' message on form submit, lock submit button
e94706 532         $('form').submit(function () {
491133 533           $('input[type=submit]', this).prop('disabled', true);
f1aaca 534           ref.clear_messages();
AM 535           ref.display_message('', 'loading');
effdb3 536         });
cecf46 537
4e17e6 538         this.enable_command('login', true);
T 539         break;
8809a1 540     }
04fbc5 541
AM 542     // select first input field in an edit form
543     if (this.gui_objects.editform)
544       $("input,select,textarea", this.gui_objects.editform)
3cb61e 545         .not(':hidden').not(':disabled').first().select().focus();
8fa922 546
8809a1 547     // unset contentframe variable if preview_pane is enabled
AM 548     if (this.env.contentframe && !$('#' + this.env.contentframe).is(':visible'))
549       this.env.contentframe = null;
4e17e6 550
3ef524 551     // prevent from form submit with Enter key in file input fields
A 552     if (bw.ie)
553       $('input[type=file]').keydown(function(e) { if (e.keyCode == '13') e.preventDefault(); });
554
4e17e6 555     // flag object as complete
T 556     this.loaded = true;
b461a2 557     this.env.lastrefresh = new Date();
9a5261 558
4e17e6 559     // show message
T 560     if (this.pending_message)
0b36d1 561       this.display_message.apply(this, this.pending_message);
8fa922 562
3cf97b 563     // init treelist widget
AM 564     if (this.gui_objects.folderlist && window.rcube_treelist_widget) {
565       this.treelist = new rcube_treelist_widget(this.gui_objects.folderlist, {
71a522 566           selectable: true,
3c309a 567           id_prefix: 'rcmli',
3fb36a 568           parent_focus: true,
3c309a 569           id_encode: this.html_identifier_encode,
TB 570           id_decode: this.html_identifier_decode,
772bec 571           check_droptarget: function(node) { return !node.virtual && ref.check_droptarget(node.id) }
3cf97b 572       });
AM 573
574       this.treelist
575         .addEventListener('collapse', function(node) { ref.folder_collapsed(node) })
576         .addEventListener('expand', function(node) { ref.folder_collapsed(node) })
ceee7e 577         .addEventListener('beforeselect', function(node) { return !ref.busy; })
3cf97b 578         .addEventListener('select', function(node) { ref.triggerEvent('selectfolder', { folder:node.id, prefix:'rcmli' }) });
3c309a 579     }
9a5261 580
ae6d2d 581     // activate html5 file drop feature (if browser supports it and if configured)
9d7271 582     if (this.gui_objects.filedrop && this.env.filedrop && ((window.XMLHttpRequest && XMLHttpRequest.prototype && XMLHttpRequest.prototype.sendAsBinary) || window.FormData)) {
ae6d2d 583       $(document.body).bind('dragover dragleave drop', function(e){ return ref.document_drag_hover(e, e.type == 'dragover'); });
TB 584       $(this.gui_objects.filedrop).addClass('droptarget')
585         .bind('dragover dragleave', function(e){ return ref.file_drag_hover(e, e.type == 'dragover'); })
586         .get(0).addEventListener('drop', function(e){ return ref.file_dropped(e); }, false);
587     }
588
6789bf 589     // catch document (and iframe) mouse clicks
TB 590     var body_mouseup = function(e){ return ref.doc_mouse_up(e); };
591     $(document.body)
592       .bind('mouseup', body_mouseup)
593       .bind('keydown', function(e){ return ref.doc_keypress(e); });
594
718573 595     $('iframe').on('load', function(e) {
6789bf 596         try { $(this.contentDocument || this.contentWindow).on('mouseup', body_mouseup);  }
TB 597         catch (e) {/* catch possible "Permission denied" error in IE */ }
598       })
599       .contents().on('mouseup', body_mouseup);
600
cc97ea 601     // trigger init event hook
T 602     this.triggerEvent('init', { task:this.task, action:this.env.action });
8fa922 603
a7d5c6 604     // execute all foreign onload scripts
cc97ea 605     // @deprecated
b21f8b 606     for (n in this.onloads) {
AM 607       if (typeof this.onloads[n] === 'string')
608         eval(this.onloads[n]);
609       else if (typeof this.onloads[n] === 'function')
610         this.onloads[n]();
611     }
cc97ea 612
77de23 613     // start keep-alive and refresh intervals
AM 614     this.start_refresh();
cc97ea 615     this.start_keepalive();
T 616   };
4e17e6 617
b0eb95 618   this.log = function(msg)
A 619   {
620     if (window.console && console.log)
621       console.log(msg);
622   };
4e17e6 623
T 624   /*********************************************************/
625   /*********       client command interface        *********/
626   /*********************************************************/
627
628   // execute a specific command on the web client
c28161 629   this.command = function(command, props, obj, event)
8fa922 630   {
08da30 631     var ret, uid, cid, url, flag, aborted = false;
14d494 632
0b2586 633     if (obj && obj.blur && !(event && rcube_event.is_keyboard(event)))
4e17e6 634       obj.blur();
T 635
a3873b 636     // do nothing if interface is locked by another command
AM 637     // with exception for searching reset and menu
638     if (this.busy && !(command == 'reset-search' && this.last_command == 'search') && !command.match(/^menu-/))
4e17e6 639       return false;
T 640
e30500 641     // let the browser handle this click (shift/ctrl usually opens the link in a new window/tab)
38b71e 642     if ((obj && obj.href && String(obj.href).indexOf('#') < 0) && rcube_event.get_modifier(event)) {
e30500 643       return true;
TB 644     }
645
4e17e6 646     // command not supported or allowed
8fa922 647     if (!this.commands[command]) {
4e17e6 648       // pass command to parent window
27acfd 649       if (this.is_framed())
4e17e6 650         parent.rcmail.command(command, props);
T 651
652       return false;
8fa922 653     }
A 654
655     // check input before leaving compose step
3fa3f1 656     if (this.task == 'mail' && this.env.action == 'compose' && !this.env.server_error && command != 'save-pref'
AM 657       && $.inArray(command, this.env.compose_commands) < 0
658     ) {
c5c8e7 659       if (!this.env.is_sent && this.cmp_hash != this.compose_field_hash() && !confirm(this.get_label('notsentwarning')))
15a9d1 660         return false;
1f164e 661
AM 662       // remove copy from local storage if compose screen is left intentionally
663       this.remove_compose_data(this.env.compose_id);
7e7e45 664       this.compose_skip_unsavedcheck = true;
8fa922 665     }
15a9d1 666
d2e3a2 667     this.last_command = command;
AM 668
cc97ea 669     // process external commands
d8cf6d 670     if (typeof this.command_handlers[command] === 'function') {
aa13b4 671       ret = this.command_handlers[command](props, obj, event);
d8cf6d 672       return ret !== undefined ? ret : (obj ? false : true);
cc97ea 673     }
d8cf6d 674     else if (typeof this.command_handlers[command] === 'string') {
aa13b4 675       ret = window[this.command_handlers[command]](props, obj, event);
d8cf6d 676       return ret !== undefined ? ret : (obj ? false : true);
cc97ea 677     }
8fa922 678
2bb1f6 679     // trigger plugin hooks
6789bf 680     this.triggerEvent('actionbefore', {props:props, action:command, originalEvent:event});
TB 681     ret = this.triggerEvent('before'+command, props || event);
7fc056 682     if (ret !== undefined) {
14d494 683       // abort if one of the handlers returned false
7fc056 684       if (ret === false)
cc97ea 685         return false;
T 686       else
7fc056 687         props = ret;
cc97ea 688     }
14d494 689
A 690     ret = undefined;
cc97ea 691
T 692     // process internal command
8fa922 693     switch (command) {
A 694
4e17e6 695       case 'login':
T 696         if (this.gui_objects.loginform)
697           this.gui_objects.loginform.submit();
698         break;
699
700       // commands to switch task
85e60a 701       case 'logout':
4e17e6 702       case 'mail':
T 703       case 'addressbook':
704       case 'settings':
705         this.switch_task(command);
706         break;
707
45fa64 708       case 'about':
e30500 709         this.redirect('?_task=settings&_action=about', false);
45fa64 710         break;
A 711
a25d39 712       case 'permaurl':
T 713         if (obj && obj.href && obj.target)
714           return true;
715         else if (this.env.permaurl)
716           parent.location.href = this.env.permaurl;
717         break;
718
271efe 719       case 'extwin':
TB 720         if (this.env.action == 'compose') {
2f321c 721           var form = this.gui_objects.messageform,
AM 722             win = this.open_window('');
a5c9fd 723
d27a4f 724           if (win) {
TB 725             this.save_compose_form_local();
7e7e45 726             this.compose_skip_unsavedcheck = true;
d27a4f 727             $("input[name='_action']", form).val('compose');
TB 728             form.action = this.url('mail/compose', { _id: this.env.compose_id, _extwin: 1 });
729             form.target = win.name;
730             form.submit();
731           }
271efe 732         }
TB 733         else {
ece3a5 734           this.open_window(this.env.permaurl, true);
271efe 735         }
TB 736         break;
737
a02c77 738       case 'change-format':
AM 739         url = this.env.permaurl + '&_format=' + props;
740
741         if (this.env.action == 'preview')
742           url = url.replace(/_action=show/, '_action=preview') + '&_framed=1';
743         if (this.env.extwin)
744           url += '&_extwin=1';
745
746         location.href = url;
747         break;
748
f52c93 749       case 'menu-open':
bc2c43 750         if (props && props.menu == 'attachmentmenu') {
AM 751           var mimetype = this.env.attachments[props.id];
752           this.enable_command('open-attachment', mimetype && this.env.mimetypes && $.inArray(mimetype, this.env.mimetypes) >= 0);
753         }
6789bf 754         this.show_menu(props, props.show || undefined, event);
TB 755         break;
756
757       case 'menu-close':
758         this.hide_menu(props, event);
759         break;
bc2c43 760
f52c93 761       case 'menu-save':
b2992d 762         this.triggerEvent(command, {props:props, originalEvent:event});
a61bbb 763         return false;
f52c93 764
49dfb0 765       case 'open':
da8f11 766         if (uid = this.get_single_uid()) {
602d74 767           obj.href = this.url('show', this.params_from_uid(uid));
a25d39 768           return true;
T 769         }
770         break;
4e17e6 771
271efe 772       case 'close':
TB 773         if (this.env.extwin)
774           window.close();
775         break;
776
4e17e6 777       case 'list':
fd4436 778         if (props && props != '') {
da1816 779           this.reset_qsearch(true);
6884f3 780         }
fd4436 781         if (this.env.action == 'compose' && this.env.extwin) {
271efe 782           window.close();
fd4436 783         }
271efe 784         else if (this.task == 'mail') {
2483a8 785           this.list_mailbox(props);
1b30a7 786           this.set_button_titles();
da8f11 787         }
1b30a7 788         else if (this.task == 'addressbook')
f11541 789           this.list_contacts(props);
1bbf8c 790         break;
TB 791
792       case 'set-listmode':
793         this.set_list_options(null, undefined, undefined, props == 'threads' ? 1 : 0);
f3b659 794         break;
T 795
796       case 'sort':
f0affa 797         var sort_order = this.env.sort_order,
AM 798           sort_col = !this.env.disabled_sort_col ? props : this.env.sort_col;
d59aaa 799
f0affa 800         if (!this.env.disabled_sort_order)
AM 801           sort_order = this.env.sort_col == sort_col && sort_order == 'ASC' ? 'DESC' : 'ASC';
5e9a56 802
f52c93 803         // set table header and update env
T 804         this.set_list_sorting(sort_col, sort_order);
b076a4 805
T 806         // reload message list
1cded8 807         this.list_mailbox('', '', sort_col+'_'+sort_order);
4e17e6 808         break;
T 809
810       case 'nextpage':
811         this.list_page('next');
812         break;
813
d17008 814       case 'lastpage':
S 815         this.list_page('last');
816         break;
817
4e17e6 818       case 'previouspage':
T 819         this.list_page('prev');
d17008 820         break;
S 821
822       case 'firstpage':
823         this.list_page('first');
15a9d1 824         break;
T 825
826       case 'expunge':
04689f 827         if (this.env.exists)
15a9d1 828           this.expunge_mailbox(this.env.mailbox);
T 829         break;
830
5e3512 831       case 'purge':
T 832       case 'empty-mailbox':
04689f 833         if (this.env.exists)
5e3512 834           this.purge_mailbox(this.env.mailbox);
4e17e6 835         break;
T 836
837       // common commands used in multiple tasks
838       case 'show':
e9a9f2 839         if (this.task == 'mail') {
249815 840           uid = this.get_single_uid();
da8f11 841           if (uid && (!this.env.uid || uid != this.env.uid)) {
6b47de 842             if (this.env.mailbox == this.env.drafts_mailbox)
271efe 843               this.open_compose_step({ _draft_uid: uid, _mbox: this.env.mailbox });
1966c5 844             else
S 845               this.show_message(uid);
4e17e6 846           }
da8f11 847         }
e9a9f2 848         else if (this.task == 'addressbook') {
249815 849           cid = props ? props : this.get_single_cid();
e9a9f2 850           if (cid && !(this.env.action == 'show' && cid == this.env.cid))
4e17e6 851             this.load_contact(cid, 'show');
da8f11 852         }
4e17e6 853         break;
T 854
855       case 'add':
e9a9f2 856         if (this.task == 'addressbook')
6b47de 857           this.load_contact(0, 'add');
0ce212 858         else if (this.task == 'settings' && this.env.action == 'responses') {
TB 859           var frame;
860           if ((frame = this.get_frame_window(this.env.contentframe))) {
861             this.set_busy(true);
862             this.location_href({ _action:'add-response', _framed:1 }, frame);
863           }
864         }
e9a9f2 865         else if (this.task == 'settings') {
6b47de 866           this.identity_list.clear_selection();
4e17e6 867           this.load_identity(0, 'add-identity');
da8f11 868         }
4e17e6 869         break;
T 870
871       case 'edit':
528c78 872         if (this.task == 'addressbook' && (cid = this.get_single_cid()))
4e17e6 873           this.load_contact(cid, 'edit');
528c78 874         else if (this.task == 'settings' && props)
4e17e6 875           this.load_identity(props, 'edit-identity');
9684dc 876         else if (this.task == 'mail' && (uid = this.get_single_uid())) {
T 877           url = { _mbox: this.get_message_mailbox(uid) };
878           url[this.env.mailbox == this.env.drafts_mailbox && props != 'new' ? '_draft_uid' : '_uid'] = uid;
271efe 879           this.open_compose_step(url);
141c9e 880         }
4e17e6 881         break;
T 882
883       case 'save':
e9a9f2 884         var input, form = this.gui_objects.editform;
A 885         if (form) {
886           // adv. search
887           if (this.env.action == 'search') {
888           }
10a699 889           // user prefs
e9a9f2 890           else if ((input = $("input[name='_pagesize']", form)) && input.length && isNaN(parseInt(input.val()))) {
10a699 891             alert(this.get_label('nopagesizewarning'));
e9a9f2 892             input.focus();
10a699 893             break;
8fa922 894           }
10a699 895           // contacts/identities
8fa922 896           else {
1a3c91 897             // reload form
5b3ac3 898             if (props == 'reload') {
3c4d3d 899               form.action += '&_reload=1';
5b3ac3 900             }
e9a9f2 901             else if (this.task == 'settings' && (this.env.identities_level % 2) == 0  &&
1a3c91 902               (input = $("input[name='_email']", form)) && input.length && !rcube_check_email(input.val())
e9a9f2 903             ) {
9f3fad 904               alert(this.get_label('noemailwarning'));
e9a9f2 905               input.focus();
9f3fad 906               break;
10a699 907             }
4737e5 908
0501b6 909             // clear empty input fields
T 910             $('input.placeholder').each(function(){ if (this.value == this._placeholder) this.value = ''; });
8fa922 911           }
1a3c91 912
A 913           // add selected source (on the list)
914           if (parent.rcmail && parent.rcmail.env.source)
915             form.action = this.add_url(form.action, '_orig_source', parent.rcmail.env.source);
10a699 916
e9a9f2 917           form.submit();
8fa922 918         }
4e17e6 919         break;
T 920
921       case 'delete':
922         // mail task
476407 923         if (this.task == 'mail')
c28161 924           this.delete_messages(event);
4e17e6 925         // addressbook task
476407 926         else if (this.task == 'addressbook')
4e17e6 927           this.delete_contacts();
0ce212 928         // settings: canned response
TB 929         else if (this.task == 'settings' && this.env.action == 'responses')
930           this.delete_response();
931         // settings: user identities
476407 932         else if (this.task == 'settings')
4e17e6 933           this.delete_identity();
T 934         break;
935
936       // mail task commands
937       case 'move':
a45f9b 938       case 'moveto': // deprecated
f11541 939         if (this.task == 'mail')
6789bf 940           this.move_messages(props, event);
33dc82 941         else if (this.task == 'addressbook')
a45f9b 942           this.move_contacts(props);
9b3fdc 943         break;
A 944
945       case 'copy':
946         if (this.task == 'mail')
6789bf 947           this.copy_messages(props, event);
a45f9b 948         else if (this.task == 'addressbook')
AM 949           this.copy_contacts(props);
4e17e6 950         break;
b85bf8 951
T 952       case 'mark':
953         if (props)
954           this.mark_message(props);
955         break;
8fa922 956
857a38 957       case 'toggle_status':
89e507 958       case 'toggle_flag':
AM 959         flag = command == 'toggle_flag' ? 'flagged' : 'read';
8fa922 960
89e507 961         if (uid = props) {
AM 962           // toggle flagged/unflagged
963           if (flag == 'flagged') {
964             if (this.message_list.rows[uid].flagged)
965               flag = 'unflagged';
966           }
4e17e6 967           // toggle read/unread
89e507 968           else if (this.message_list.rows[uid].deleted)
6b47de 969             flag = 'undelete';
da8f11 970           else if (!this.message_list.rows[uid].unread)
A 971             flag = 'unread';
89e507 972
AM 973           this.mark_message(flag, uid);
da8f11 974         }
8fa922 975
e189a6 976         break;
A 977
62e43d 978       case 'always-load':
T 979         if (this.env.uid && this.env.sender) {
644f00 980           this.add_contact(this.env.sender);
da5cad 981           setTimeout(function(){ ref.command('load-images'); }, 300);
62e43d 982           break;
T 983         }
8fa922 984
4e17e6 985       case 'load-images':
T 986         if (this.env.uid)
b19097 987           this.show_message(this.env.uid, true, this.env.action=='preview');
4e17e6 988         break;
T 989
990       case 'load-attachment':
bc2c43 991       case 'open-attachment':
AM 992       case 'download-attachment':
993         var qstring = '_mbox='+urlencode(this.env.mailbox)+'&_uid='+this.env.uid+'&_part='+props,
994           mimetype = this.env.attachments[props];
8fa922 995
4e17e6 996         // open attachment in frame if it's of a supported mimetype
bc2c43 997         if (command != 'download-attachment' && mimetype && this.env.mimetypes && $.inArray(mimetype, this.env.mimetypes) >= 0) {
049428 998           if (this.open_window(this.env.comm_path+'&_action=get&'+qstring+'&_frame=1'))
4e17e6 999             break;
da8f11 1000         }
4e17e6 1001
4b9efb 1002         this.goto_url('get', qstring+'&_download=1', false);
4e17e6 1003         break;
8fa922 1004
4e17e6 1005       case 'select-all':
fb7ec5 1006         this.select_all_mode = props ? false : true;
196d04 1007         this.dummy_select = true; // prevent msg opening if there's only one msg on the list
528185 1008         if (props == 'invert')
A 1009           this.message_list.invert_selection();
141c9e 1010         else
fb7ec5 1011           this.message_list.select_all(props == 'page' ? '' : props);
196d04 1012         this.dummy_select = null;
4e17e6 1013         break;
T 1014
1015       case 'select-none':
349cbf 1016         this.select_all_mode = false;
6b47de 1017         this.message_list.clear_selection();
f52c93 1018         break;
T 1019
1020       case 'expand-all':
1021         this.env.autoexpand_threads = 1;
1022         this.message_list.expand_all();
1023         break;
1024
1025       case 'expand-unread':
1026         this.env.autoexpand_threads = 2;
1027         this.message_list.collapse_all();
1028         this.expand_unread();
1029         break;
1030
1031       case 'collapse-all':
1032         this.env.autoexpand_threads = 0;
1033         this.message_list.collapse_all();
4e17e6 1034         break;
T 1035
1036       case 'nextmessage':
1037         if (this.env.next_uid)
a5c9fd 1038           this.show_message(this.env.next_uid, false, this.env.action == 'preview');
4e17e6 1039         break;
T 1040
a7d5c6 1041       case 'lastmessage':
d17008 1042         if (this.env.last_uid)
S 1043           this.show_message(this.env.last_uid);
1044         break;
1045
4e17e6 1046       case 'previousmessage':
T 1047         if (this.env.prev_uid)
3c047d 1048           this.show_message(this.env.prev_uid, false, this.env.action == 'preview');
d17008 1049         break;
S 1050
1051       case 'firstmessage':
1052         if (this.env.first_uid)
1053           this.show_message(this.env.first_uid);
4e17e6 1054         break;
8fa922 1055
4e17e6 1056       case 'compose':
271efe 1057         url = {};
8fa922 1058
cf58ce 1059         if (this.task == 'mail') {
de0bc6 1060           url = {_mbox: this.env.mailbox, _search: this.env.search_request};
46cdbf 1061           if (props)
d47833 1062             url._to = props;
a9ab9f 1063         }
4e17e6 1064         // modify url if we're in addressbook
cf58ce 1065         else if (this.task == 'addressbook') {
f11541 1066           // switch to mail compose step directly
da8f11 1067           if (props && props.indexOf('@') > 0) {
271efe 1068             url._to = props;
TB 1069           }
1070           else {
0826b2 1071             var a_cids = [];
AM 1072             // use contact id passed as command parameter
271efe 1073             if (props)
TB 1074               a_cids.push(props);
1075             // get selected contacts
0826b2 1076             else if (this.contact_list)
AM 1077               a_cids = this.contact_list.get_selection();
271efe 1078
TB 1079             if (a_cids.length)
111acf 1080               this.http_post('mailto', { _cid: a_cids.join(','), _source: this.env.source }, true);
271efe 1081             else if (this.env.group)
TB 1082               this.http_post('mailto', { _gid: this.env.group, _source: this.env.source }, true);
1083
f11541 1084             break;
da8f11 1085           }
A 1086         }
d47833 1087         else if (props && typeof props == 'string') {
271efe 1088           url._to = props;
d47833 1089         }
TB 1090         else if (props && typeof props == 'object') {
1091           $.extend(url, props);
1092         }
d1d2c4 1093
271efe 1094         this.open_compose_step(url);
ed5d29 1095         break;
8fa922 1096
ed5d29 1097       case 'spellcheck':
4be86f 1098         if (this.spellcheck_state()) {
646b64 1099           this.editor.spellcheck_stop();
4ca10b 1100         }
4be86f 1101         else {
646b64 1102           this.editor.spellcheck_start();
4ca10b 1103         }
ed5d29 1104         break;
4e17e6 1105
1966c5 1106       case 'savedraft':
41fa0b 1107         // Reset the auto-save timer
da5cad 1108         clearTimeout(this.save_timer);
f0f98f 1109
1f82e4 1110         // compose form did not change (and draft wasn't saved already)
3ca58c 1111         if (this.env.draft_id && this.cmp_hash == this.compose_field_hash()) {
da5cad 1112           this.auto_save_start();
41fa0b 1113           break;
da5cad 1114         }
A 1115
b169de 1116         this.submit_messageform(true);
1966c5 1117         break;
S 1118
4e17e6 1119       case 'send':
c5c8e7 1120         if (!props.nocheck && !this.env.is_sent && !this.check_compose_input(command))
10a699 1121           break;
4315b0 1122
9a5261 1123         // Reset the auto-save timer
da5cad 1124         clearTimeout(this.save_timer);
10a699 1125
b169de 1126         this.submit_messageform();
50f56d 1127         break;
8fa922 1128
4e17e6 1129       case 'send-attachment':
f0f98f 1130         // Reset the auto-save timer
da5cad 1131         clearTimeout(this.save_timer);
85fd29 1132
fb162e 1133         if (!(flag = this.upload_file(props || this.gui_objects.uploadform, 'upload'))) {
AM 1134           if (flag !== false)
1135             alert(this.get_label('selectimportfile'));
08da30 1136           aborted = true;
TB 1137         }
4e17e6 1138         break;
8fa922 1139
0207c4 1140       case 'insert-sig':
T 1141         this.change_identity($("[name='_from']")[0], true);
eeb73c 1142         break;
T 1143
1144       case 'list-adresses':
1145         this.list_contacts(props);
1146         this.enable_command('add-recipient', false);
1147         break;
1148
1149       case 'add-recipient':
1150         this.compose_add_recipient(props);
a894ba 1151         break;
4e17e6 1152
583f1c 1153       case 'reply-all':
e25a35 1154       case 'reply-list':
4e17e6 1155       case 'reply':
e25a35 1156         if (uid = this.get_single_uid()) {
de0bc6 1157           url = {_reply_uid: uid, _mbox: this.get_message_mailbox(uid), _search: this.env.search_request};
e25a35 1158           if (command == 'reply-all')
0a9d41 1159             // do reply-list, when list is detected and popup menu wasn't used
b972b4 1160             url._all = (!props && this.env.reply_all_mode == 1 && this.commands['reply-list'] ? 'list' : 'all');
e25a35 1161           else if (command == 'reply-list')
4d1515 1162             url._all = 'list';
e25a35 1163
271efe 1164           this.open_compose_step(url);
e25a35 1165         }
2bb1f6 1166         break;
4e17e6 1167
a208a4 1168       case 'forward-attachment':
d9f109 1169       case 'forward-inline':
4e17e6 1170       case 'forward':
d9f109 1171         var uids = this.env.uid ? [this.env.uid] : (this.message_list ? this.message_list.get_selection() : []);
AM 1172         if (uids.length) {
aafbe8 1173           url = { _forward_uid: this.uids_to_list(uids), _mbox: this.env.mailbox, _search: this.env.search_request };
d9f109 1174           if (command == 'forward-attachment' || (!props && this.env.forward_attachment) || uids.length > 1)
528c78 1175             url._attachment = 1;
271efe 1176           this.open_compose_step(url);
a509bb 1177         }
4e17e6 1178         break;
8fa922 1179
4e17e6 1180       case 'print':
f7af22 1181         if (this.task == 'addressbook') {
AM 1182           if (uid = this.contact_list.get_single_selection()) {
1183             url = '&_action=print&_cid=' + uid;
1184             if (this.env.source)
1185               url += '&_source=' + urlencode(this.env.source);
1186             this.open_window(this.env.comm_path + url, true, true);
1187           }
1188         }
1189         else if (this.env.action == 'get') {
049428 1190           this.gui_objects.messagepartframe.contentWindow.print();
AM 1191         }
1192         else if (uid = this.get_single_uid()) {
602d74 1193           url = this.url('print', this.params_from_uid(uid, {_safe: this.env.safemode ? 1 : 0}));
AM 1194           if (this.open_window(url, true, true)) {
4d3f3b 1195             if (this.env.action != 'show')
5d97ac 1196               this.mark_message('read', uid);
4e17e6 1197           }
4d3f3b 1198         }
4e17e6 1199         break;
T 1200
1201       case 'viewsource':
2f321c 1202         if (uid = this.get_single_uid())
602d74 1203           this.open_window(this.url('viewsource', this.params_from_uid(uid)), true, true);
49dfb0 1204         break;
A 1205
1206       case 'download':
049428 1207         if (this.env.action == 'get') {
AM 1208           location.href = location.href.replace(/_frame=/, '_download=');
1209         }
9684dc 1210         else if (uid = this.get_single_uid()) {
602d74 1211           this.goto_url('viewsource', this.params_from_uid(uid, {_save: 1}));
9684dc 1212         }
4e17e6 1213         break;
T 1214
f11541 1215       // quicksearch
4647e1 1216       case 'search':
T 1217         if (!props && this.gui_objects.qsearchbox)
1218           props = this.gui_objects.qsearchbox.value;
8fa922 1219         if (props) {
f11541 1220           this.qsearch(props);
T 1221           break;
1222         }
4647e1 1223
ed132e 1224       // reset quicksearch
4647e1 1225       case 'reset-search':
d12b99 1226         var n, s = this.env.search_request || this.env.qsearch;
5271bf 1227
da1816 1228         this.reset_qsearch(true);
5271bf 1229         this.select_all_mode = false;
8fa922 1230
6c27c3 1231         if (s && this.env.action == 'compose') {
TB 1232           if (this.contact_list)
1233             this.list_contacts_clear();
1234         }
d12b99 1235         else if (s && this.env.mailbox) {
b7fd98 1236           this.list_mailbox(this.env.mailbox, 1);
6c27c3 1237         }
ecf295 1238         else if (s && this.task == 'addressbook') {
A 1239           if (this.env.source == '') {
db0408 1240             for (n in this.env.address_sources) break;
ecf295 1241             this.env.source = n;
A 1242             this.env.group = '';
1243           }
b7fd98 1244           this.list_contacts(this.env.source, this.env.group, 1);
ecf295 1245         }
a61bbb 1246         break;
T 1247
c5a5f9 1248       case 'pushgroup':
86552f 1249         // add group ID to stack
TB 1250         this.env.address_group_stack.push(props.id);
1251         if (obj && event)
1252           rcube_event.cancel(event);
1253
edfe91 1254       case 'listgroup':
f8e48d 1255         this.reset_qsearch();
edfe91 1256         this.list_contacts(props.source, props.id);
de98a8 1257         break;
TB 1258
1259       case 'popgroup':
1260         if (this.env.address_group_stack.length > 1) {
1261           this.env.address_group_stack.pop();
1262           this.reset_qsearch();
1263           this.list_contacts(props.source, this.env.address_group_stack[this.env.address_group_stack.length-1]);
1264         }
4f53ab 1265         break;
TB 1266
1267       case 'import-messages':
fb162e 1268         var form = props || this.gui_objects.importform,
AM 1269           importlock = this.set_busy(true, 'importwait');
1270
a36369 1271         $('input[name="_unlock"]', form).val(importlock);
fb162e 1272
42f8ab 1273         if (!(flag = this.upload_file(form, 'import', importlock))) {
a36369 1274           this.set_busy(false, null, importlock);
fb162e 1275           if (flag !== false)
AM 1276             alert(this.get_label('selectimportfile'));
08da30 1277           aborted = true;
a36369 1278         }
4647e1 1279         break;
4e17e6 1280
ed132e 1281       case 'import':
T 1282         if (this.env.action == 'import' && this.gui_objects.importform) {
1283           var file = document.getElementById('rcmimportfile');
1284           if (file && !file.value) {
1285             alert(this.get_label('selectimportfile'));
08da30 1286             aborted = true;
ed132e 1287             break;
T 1288           }
1289           this.gui_objects.importform.submit();
1290           this.set_busy(true, 'importwait');
1291           this.lock_form(this.gui_objects.importform, true);
1292         }
1293         else
d4a2c0 1294           this.goto_url('import', (this.env.source ? '_target='+urlencode(this.env.source)+'&' : ''));
0dbac3 1295         break;
8fa922 1296
0dbac3 1297       case 'export':
T 1298         if (this.contact_list.rowcount > 0) {
528c78 1299           this.goto_url('export', { _source: this.env.source, _gid: this.env.group, _search: this.env.search_request });
0dbac3 1300         }
0501b6 1301         break;
4737e5 1302
9a6c38 1303       case 'export-selected':
TB 1304         if (this.contact_list.rowcount > 0) {
1305           this.goto_url('export', { _source: this.env.source, _gid: this.env.group, _cid: this.contact_list.get_selection().join(',') });
1306         }
1307         break;
1308
0501b6 1309       case 'upload-photo':
a84bfa 1310         this.upload_contact_photo(props || this.gui_objects.uploadform);
0501b6 1311         break;
T 1312
1313       case 'delete-photo':
1314         this.replace_contact_photo('-del-');
0dbac3 1315         break;
ed132e 1316
4e17e6 1317       // user settings commands
T 1318       case 'preferences':
1319       case 'identities':
0ce212 1320       case 'responses':
4e17e6 1321       case 'folders':
4737e5 1322         this.goto_url('settings/' + command);
4e17e6 1323         break;
T 1324
7f5a84 1325       case 'undo':
A 1326         this.http_request('undo', '', this.display_message('', 'loading'));
1327         break;
1328
edfe91 1329       // unified command call (command name == function name)
A 1330       default:
2fc459 1331         var func = command.replace(/-/g, '_');
14d494 1332         if (this[func] && typeof this[func] === 'function') {
646b64 1333           ret = this[func](props, obj, event);
14d494 1334         }
4e17e6 1335         break;
8fa922 1336     }
A 1337
08da30 1338     if (!aborted && this.triggerEvent('after'+command, props) === false)
14d494 1339       ret = false;
08da30 1340     this.triggerEvent('actionafter', { props:props, action:command, aborted:aborted });
4e17e6 1341
14d494 1342     return ret === false ? false : obj ? false : true;
8fa922 1343   };
4e17e6 1344
14259c 1345   // set command(s) enabled or disabled
4e17e6 1346   this.enable_command = function()
8fa922 1347   {
249815 1348     var i, n, args = Array.prototype.slice.call(arguments),
d470f9 1349       enable = args.pop(), cmd;
8fa922 1350
249815 1351     for (n=0; n<args.length; n++) {
d470f9 1352       cmd = args[n];
A 1353       // argument of type array
1354       if (typeof cmd === 'string') {
1355         this.commands[cmd] = enable;
1356         this.set_button(cmd, (enable ? 'act' : 'pas'));
235504 1357         this.triggerEvent('enable-command', {command: cmd, status: enable});
14259c 1358       }
d470f9 1359       // push array elements into commands array
A 1360       else {
249815 1361         for (i in cmd)
d470f9 1362           args.push(cmd[i]);
A 1363       }
8fa922 1364     }
A 1365   };
4e17e6 1366
26b520 1367   this.command_enabled = function(cmd)
TB 1368   {
1369     return this.commands[cmd];
a5fe9a 1370   };
26b520 1371
a95e0e 1372   // lock/unlock interface
ad334a 1373   this.set_busy = function(a, message, id)
8fa922 1374   {
A 1375     if (a && message) {
10a699 1376       var msg = this.get_label(message);
fb4663 1377       if (msg == message)
10a699 1378         msg = 'Loading...';
T 1379
ad334a 1380       id = this.display_message(msg, 'loading');
8fa922 1381     }
ad334a 1382     else if (!a && id) {
A 1383       this.hide_message(id);
554d79 1384     }
4e17e6 1385
T 1386     this.busy = a;
1387     //document.body.style.cursor = a ? 'wait' : 'default';
8fa922 1388
4e17e6 1389     if (this.gui_objects.editform)
T 1390       this.lock_form(this.gui_objects.editform, a);
8fa922 1391
ad334a 1392     return id;
8fa922 1393   };
4e17e6 1394
10a699 1395   // return a localized string
cc97ea 1396   this.get_label = function(name, domain)
8fa922 1397   {
cc97ea 1398     if (domain && this.labels[domain+'.'+name])
T 1399       return this.labels[domain+'.'+name];
1400     else if (this.labels[name])
10a699 1401       return this.labels[name];
T 1402     else
1403       return name;
8fa922 1404   };
A 1405
cc97ea 1406   // alias for convenience reasons
T 1407   this.gettext = this.get_label;
10a699 1408
T 1409   // switch to another application task
4e17e6 1410   this.switch_task = function(task)
8fa922 1411   {
a5fe9a 1412     if (this.task === task && task != 'mail')
4e17e6 1413       return;
T 1414
01bb03 1415     var url = this.get_task_url(task);
a5fe9a 1416
85e60a 1417     if (task == 'mail')
01bb03 1418       url += '&_mbox=INBOX';
681ba6 1419     else if (task == 'logout' && !this.env.server_error) {
AM 1420       url += '&_token=' + this.env.request_token;
85e60a 1421       this.clear_compose_data();
681ba6 1422     }
01bb03 1423
f11541 1424     this.redirect(url);
8fa922 1425   };
4e17e6 1426
T 1427   this.get_task_url = function(task, url)
8fa922 1428   {
4e17e6 1429     if (!url)
T 1430       url = this.env.comm_path;
1431
681ba6 1432     if (url.match(/[?&]_task=[a-zA-Z0-9_-]+/))
AM 1433         return url.replace(/_task=[a-zA-Z0-9_-]+/, '_task=' + task);
1434     else
1435         return url.replace(/\?.*$/, '') + '?_task=' + task;
8fa922 1436   };
A 1437
141c9e 1438   this.reload = function(delay)
T 1439   {
27acfd 1440     if (this.is_framed())
141c9e 1441       parent.rcmail.reload(delay);
T 1442     else if (delay)
f1aaca 1443       setTimeout(function() { ref.reload(); }, delay);
141c9e 1444     else if (window.location)
e8e88d 1445       location.href = this.url('', {_extwin: this.env.extwin});
141c9e 1446   };
4e17e6 1447
ad334a 1448   // Add variable to GET string, replace old value if exists
A 1449   this.add_url = function(url, name, value)
1450   {
1451     value = urlencode(value);
1452
1453     if (/(\?.*)$/.test(url)) {
1454       var urldata = RegExp.$1,
1455         datax = RegExp('((\\?|&)'+RegExp.escape(name)+'=[^&]*)');
1456
1457       if (datax.test(urldata)) {
1458         urldata = urldata.replace(datax, RegExp.$2 + name + '=' + value);
1459       }
1460       else
1461         urldata += '&' + name + '=' + value
1462
1463       return url.replace(/(\?.*)$/, urldata);
1464     }
c31360 1465
A 1466     return url + '?' + name + '=' + value;
ad334a 1467   };
27acfd 1468
A 1469   this.is_framed = function()
1470   {
44cfef 1471     return this.env.framed && parent.rcmail && parent.rcmail != this && typeof parent.rcmail.command == 'function';
27acfd 1472   };
A 1473
9b6c82 1474   this.save_pref = function(prop)
A 1475   {
a5fe9a 1476     var request = {_name: prop.name, _value: prop.value};
9b6c82 1477
A 1478     if (prop.session)
a5fe9a 1479       request._session = prop.session;
9b6c82 1480     if (prop.env)
A 1481       this.env[prop.env] = prop.value;
1482
1483     this.http_post('save-pref', request);
1484   };
1485
fb6d86 1486   this.html_identifier = function(str, encode)
A 1487   {
3c309a 1488     return encode ? this.html_identifier_encode(str) : String(str).replace(this.identifier_expr, '_');
TB 1489   };
1490
1491   this.html_identifier_encode = function(str)
1492   {
1493     return Base64.encode(String(str)).replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
fb6d86 1494   };
A 1495
1496   this.html_identifier_decode = function(str)
1497   {
1498     str = String(str).replace(/-/g, '+').replace(/_/g, '/');
1499
1500     while (str.length % 4) str += '=';
1501
1502     return Base64.decode(str);
1503   };
1504
4e17e6 1505
T 1506   /*********************************************************/
1507   /*********        event handling methods         *********/
1508   /*********************************************************/
1509
a61bbb 1510   this.drag_menu = function(e, target)
9b3fdc 1511   {
8fa922 1512     var modkey = rcube_event.get_modifier(e),
a45f9b 1513       menu = this.gui_objects.dragmenu;
9b3fdc 1514
a61bbb 1515     if (menu && modkey == SHIFT_KEY && this.commands['copy']) {
9b3fdc 1516       var pos = rcube_event.get_mouse_pos(e);
a61bbb 1517       this.env.drag_target = target;
6789bf 1518       this.show_menu(this.gui_objects.dragmenu.id, true, e);
TB 1519       $(menu).css({top: (pos.y-10)+'px', left: (pos.x-10)+'px'});
9b3fdc 1520       return true;
A 1521     }
8fa922 1522
a61bbb 1523     return false;
9b3fdc 1524   };
A 1525
1526   this.drag_menu_action = function(action)
1527   {
a45f9b 1528     var menu = this.gui_objects.dragmenu;
9b3fdc 1529     if (menu) {
b6a069 1530       $(menu).hide();
9b3fdc 1531     }
a61bbb 1532     this.command(action, this.env.drag_target);
T 1533     this.env.drag_target = null;
f89f03 1534   };
f5aa16 1535
b75488 1536   this.drag_start = function(list)
f89f03 1537   {
b75488 1538     this.drag_active = true;
3a003c 1539
b75488 1540     if (this.preview_timer)
A 1541       clearTimeout(this.preview_timer);
bc4960 1542     if (this.preview_read_timer)
T 1543       clearTimeout(this.preview_read_timer);
1544
3c309a 1545     // prepare treelist widget for dragging interactions
TB 1546     if (this.treelist)
1547       this.treelist.drag_start();
f89f03 1548   };
b75488 1549
91d1a1 1550   this.drag_end = function(e)
A 1551   {
001e39 1552     var list, model;
8fa922 1553
3c309a 1554     if (this.treelist)
TB 1555       this.treelist.drag_end();
001e39 1556
TB 1557     // execute drag & drop action when mouse was released
1558     if (list = this.message_list)
1559       model = this.env.mailboxes;
1560     else if (list = this.contact_list)
1561       model = this.env.contactfolders;
1562
1563     if (this.drag_active && model && this.env.last_folder_target) {
1564       var target = model[this.env.last_folder_target];
1565       list.draglayer.hide();
1566
1567       if (this.contact_list) {
1568         if (!this.contacts_drag_menu(e, target))
1569           this.command('move', target);
1570       }
1571       else if (!this.drag_menu(e, target))
1572         this.command('move', target);
1573     }
1574
1575     this.drag_active = false;
1576     this.env.last_folder_target = null;
91d1a1 1577   };
8fa922 1578
b75488 1579   this.drag_move = function(e)
cc97ea 1580   {
3c309a 1581     if (this.gui_objects.folderlist) {
TB 1582       var drag_target, oldclass,
249815 1583         layerclass = 'draglayernormal',
3c309a 1584         mouse = rcube_event.get_mouse_pos(e);
7f5a84 1585
ca38db 1586       if (this.contact_list && this.contact_list.draglayer)
T 1587         oldclass = this.contact_list.draglayer.attr('class');
8fa922 1588
3c309a 1589       // mouse intersects a valid drop target on the treelist
TB 1590       if (this.treelist && (drag_target = this.treelist.intersects(mouse, true))) {
1591         this.env.last_folder_target = drag_target;
1592         layerclass = 'draglayer' + (this.check_droptarget(drag_target) > 1 ? 'copy' : 'normal');
cc97ea 1593       }
3c309a 1594       else {
TB 1595         // Clear target, otherwise drag end will trigger move into last valid droptarget
1596         this.env.last_folder_target = null;
b75488 1597       }
176c76 1598
ca38db 1599       if (layerclass != oldclass && this.contact_list && this.contact_list.draglayer)
T 1600         this.contact_list.draglayer.attr('class', layerclass);
cc97ea 1601     }
T 1602   };
0061e7 1603
fb6d86 1604   this.collapse_folder = function(name)
da8f11 1605   {
3c309a 1606     if (this.treelist)
TB 1607       this.treelist.toggle(name);
1608   };
8fa922 1609
3c309a 1610   this.folder_collapsed = function(node)
TB 1611   {
9ad0fc 1612     var prefname = this.env.task == 'addressbook' ? 'collapsed_abooks' : 'collapsed_folders',
AM 1613       old = this.env[prefname];
3c309a 1614
TB 1615     if (node.collapsed) {
1616       this.env[prefname] = this.env[prefname] + '&'+urlencode(node.id)+'&';
f1f17f 1617
1837c3 1618       // select the folder if one of its childs is currently selected
A 1619       // don't select if it's virtual (#1488346)
c4383b 1620       if (!node.virtual && this.env.mailbox && this.env.mailbox.startsWith(node.id + this.env.delimiter))
AM 1621         this.command('list', node.id);
da8f11 1622     }
3c309a 1623     else {
TB 1624       var reg = new RegExp('&'+urlencode(node.id)+'&');
1625       this.env[prefname] = this.env[prefname].replace(reg, '');
f11541 1626     }
da8f11 1627
3c309a 1628     if (!this.drag_active) {
9ad0fc 1629       if (old !== this.env[prefname])
AM 1630         this.command('save-pref', { name: prefname, value: this.env[prefname] });
3c309a 1631
TB 1632       if (this.env.unread_counts)
1633         this.set_unread_count_display(node.id, false);
1634     }
da8f11 1635   };
A 1636
6789bf 1637   // global mouse-click handler to cleanup some UI elements
da8f11 1638   this.doc_mouse_up = function(e)
A 1639   {
6789bf 1640     var list, id, target = rcube_event.get_target(e);
da8f11 1641
6c1eae 1642     // ignore event if jquery UI dialog is open
6789bf 1643     if ($(target).closest('.ui-dialog, .ui-widget-overlay').length)
6c1eae 1644       return;
T 1645
f0928e 1646     // remove focus from list widgets
TB 1647     if (window.rcube_list_widget && rcube_list_widget._instances.length) {
1648       $.each(rcube_list_widget._instances, function(i,list){
1649         if (list && !rcube_mouse_is_over(e, list.list.parentNode))
1650           list.blur();
1651       });
1652     }
da8f11 1653
A 1654     // reset 'pressed' buttons
1655     if (this.buttons_sel) {
476407 1656       for (id in this.buttons_sel)
d8cf6d 1657         if (typeof id !== 'function')
da8f11 1658           this.button_out(this.buttons_sel[id], id);
A 1659       this.buttons_sel = {};
1660     }
6789bf 1661
TB 1662     // reset popup menus; delayed to have updated menu_stack data
a5fe9a 1663     setTimeout(function(e){
f0928e 1664       var obj, skip, config, id, i, parents = $(target).parents();
6789bf 1665       for (i = ref.menu_stack.length - 1; i >= 0; i--) {
TB 1666         id = ref.menu_stack[i];
1667         obj = $('#' + id);
1668
1669         if (obj.is(':visible')
1670           && target != obj.data('opener')
1671           && target != obj.get(0)  // check if scroll bar was clicked (#1489832)
f0928e 1672           && !parents.is(obj.data('opener'))
6789bf 1673           && id != skip
TB 1674           && (obj.attr('data-editable') != 'true' || !$(target).parents('#' + id).length)
1675           && (obj.attr('data-sticky') != 'true' || !rcube_mouse_is_over(e, obj.get(0)))
1676         ) {
1677           ref.hide_menu(id, e);
1678         }
1679         skip = obj.data('parent');
1680       }
a35c9f 1681     }, 10, e);
da8f11 1682   };
6789bf 1683
TB 1684   // global keypress event handler
1685   this.doc_keypress = function(e)
1686   {
1687     // Helper method to move focus to the next/prev active menu item
1688     var focus_menu_item = function(dir) {
d58c39 1689       var obj, item, mod = dir < 0 ? 'prevAll' : 'nextAll', limit = dir < 0 ? 'last' : 'first';
6789bf 1690       if (ref.focused_menu && (obj = $('#'+ref.focused_menu))) {
d58c39 1691         item = obj.find(':focus').closest('li')[mod](':has(:not([aria-disabled=true]))').find('a,input')[limit]();
TB 1692         if (!item.length)
1693           item = obj.find(':focus').closest('ul')[mod](':has(:not([aria-disabled=true]))').find('a,input')[limit]();
1694         return item.focus().length;
6789bf 1695       }
TB 1696
1697       return 0;
1698     };
1699
1700     var target = e.target || {},
1701       keyCode = rcube_event.get_keycode(e);
1702
bf3379 1703     // save global reference for keyboard detection on click events in IE
TB 1704     rcube_event._last_keyboard_event = e;
1705
6789bf 1706     if (e.keyCode != 27 && (!this.menu_keyboard_active || target.nodeName == 'TEXTAREA' || target.nodeName == 'SELECT')) {
TB 1707       return true;
1708     }
1709
1710     switch (keyCode) {
1711       case 38:
1712       case 40:
1713       case 63232: // "up", in safari keypress
1714       case 63233: // "down", in safari keypress
a5fe9a 1715         focus_menu_item(keyCode == 38 || keyCode == 63232 ? -1 : 1);
9749ae 1716         return rcube_event.cancel(e);
6789bf 1717
TB 1718       case 9:   // tab
1719         if (this.focused_menu) {
1720           var mod = rcube_event.get_modifier(e);
1721           if (!focus_menu_item(mod == SHIFT_KEY ? -1 : 1)) {
1722             this.hide_menu(this.focused_menu, e);
1723           }
1724         }
1725         return rcube_event.cancel(e);
1726
1727       case 27:  // esc
1728         if (this.menu_stack.length)
1729           this.hide_menu(this.menu_stack[this.menu_stack.length-1], e);
1730         break;
1731     }
1732
1733     return true;
1734   }
4e17e6 1735
6b47de 1736   this.msglist_select = function(list)
186537 1737   {
b19097 1738     if (this.preview_timer)
T 1739       clearTimeout(this.preview_timer);
bc4960 1740     if (this.preview_read_timer)
T 1741       clearTimeout(this.preview_read_timer);
1742
4fe8f9 1743     var selected = list.get_single_selection();
4b9efb 1744
4fe8f9 1745     this.enable_command(this.env.message_commands, selected != null);
e25a35 1746     if (selected) {
A 1747       // Hide certain command buttons when Drafts folder is selected
1748       if (this.env.mailbox == this.env.drafts_mailbox)
d9f109 1749         this.enable_command('reply', 'reply-all', 'reply-list', 'forward', 'forward-attachment', 'forward-inline', false);
e25a35 1750       // Disable reply-list when List-Post header is not set
A 1751       else {
4fe8f9 1752         var msg = this.env.messages[selected];
e25a35 1753         if (!msg.ml)
A 1754           this.enable_command('reply-list', false);
1755       }
14259c 1756     }
A 1757     // Multi-message commands
a45f9b 1758     this.enable_command('delete', 'move', 'copy', 'mark', 'forward', 'forward-attachment', list.selection.length > 0);
a1f7e9 1759
A 1760     // reset all-pages-selection
488074 1761     if (selected || (list.selection.length && list.selection.length != list.rowcount))
c6a6d2 1762       this.select_all_mode = false;
068f6a 1763
S 1764     // start timer for message preview (wait for double click)
196d04 1765     if (selected && this.env.contentframe && !list.multi_selecting && !this.dummy_select)
ab845c 1766       this.preview_timer = setTimeout(function() { ref.msglist_get_preview(); }, this.dblclick_time);
068f6a 1767     else if (this.env.contentframe)
f11541 1768       this.show_contentframe(false);
186537 1769   };
A 1770
1771   // This allow as to re-select selected message and display it in preview frame
1772   this.msglist_click = function(list)
1773   {
1774     if (list.multi_selecting || !this.env.contentframe)
1775       return;
1776
24fa5d 1777     if (list.get_single_selection())
AM 1778       return;
1779
1780     var win = this.get_frame_window(this.env.contentframe);
1781
ab845c 1782     if (win && win.location.href.indexOf(this.env.blankpage) >= 0) {
24fa5d 1783       if (this.preview_timer)
AM 1784         clearTimeout(this.preview_timer);
1785       if (this.preview_read_timer)
1786         clearTimeout(this.preview_read_timer);
ab845c 1787
AM 1788       this.preview_timer = setTimeout(function() { ref.msglist_get_preview(); }, this.dblclick_time);
186537 1789     }
A 1790   };
d1d2c4 1791
6b47de 1792   this.msglist_dbl_click = function(list)
186537 1793   {
A 1794     if (this.preview_timer)
1795       clearTimeout(this.preview_timer);
1796     if (this.preview_read_timer)
1797       clearTimeout(this.preview_read_timer);
b19097 1798
6b47de 1799     var uid = list.get_single_selection();
ab845c 1800
2c33c7 1801     if (uid && (this.env.messages[uid].mbox || this.env.mailbox) == this.env.drafts_mailbox)
271efe 1802       this.open_compose_step({ _draft_uid: uid, _mbox: this.env.mailbox });
6b47de 1803     else if (uid)
b19097 1804       this.show_message(uid, false, false);
186537 1805   };
6b47de 1806
T 1807   this.msglist_keypress = function(list)
186537 1808   {
699a25 1809     if (list.modkey == CONTROL_KEY)
A 1810       return;
1811
6b47de 1812     if (list.key_pressed == list.ENTER_KEY)
T 1813       this.command('show');
699a25 1814     else if (list.key_pressed == list.DELETE_KEY || list.key_pressed == list.BACKSPACE_KEY)
6e6e89 1815       this.command('delete');
33e2e4 1816     else if (list.key_pressed == 33)
A 1817       this.command('previouspage');
1818     else if (list.key_pressed == 34)
1819       this.command('nextpage');
186537 1820   };
4e17e6 1821
b19097 1822   this.msglist_get_preview = function()
T 1823   {
1824     var uid = this.get_single_uid();
f11541 1825     if (uid && this.env.contentframe && !this.drag_active)
b19097 1826       this.show_message(uid, false, true);
T 1827     else if (this.env.contentframe)
f11541 1828       this.show_contentframe(false);
T 1829   };
8fa922 1830
f52c93 1831   this.msglist_expand = function(row)
T 1832   {
1833     if (this.env.messages[row.uid])
1834       this.env.messages[row.uid].expanded = row.expanded;
32afef 1835     $(row.obj)[row.expanded?'addClass':'removeClass']('expanded');
f52c93 1836   };
176c76 1837
b62c48 1838   this.msglist_set_coltypes = function(list)
A 1839   {
517dae 1840     var i, found, name, cols = list.thead.rows[0].cells;
176c76 1841
c83535 1842     this.env.listcols = [];
176c76 1843
b62c48 1844     for (i=0; i<cols.length; i++)
6a9144 1845       if (cols[i].id && cols[i].id.startsWith('rcm')) {
AM 1846         name = cols[i].id.slice(3);
c83535 1847         this.env.listcols.push(name);
b62c48 1848       }
A 1849
c83535 1850     if ((found = $.inArray('flag', this.env.listcols)) >= 0)
9f07d1 1851       this.env.flagged_col = found;
b62c48 1852
c83535 1853     if ((found = $.inArray('subject', this.env.listcols)) >= 0)
9f07d1 1854       this.env.subject_col = found;
8e32dc 1855
c83535 1856     this.command('save-pref', { name: 'list_cols', value: this.env.listcols, session: 'list_attrib/columns' });
b62c48 1857   };
8fa922 1858
f11541 1859   this.check_droptarget = function(id)
T 1860   {
a45f9b 1861     switch (this.task) {
AM 1862       case 'mail':
1e9a59 1863         return (this.env.mailboxes[id]
TB 1864             && !this.env.mailboxes[id].virtual
f50a66 1865             && (this.env.mailboxes[id].id != this.env.mailbox || this.is_multifolder_listing())) ? 1 : 0;
ff4a92 1866
a45f9b 1867       case 'addressbook':
AM 1868         var target;
1869         if (id != this.env.source && (target = this.env.contactfolders[id])) {
1870           // droptarget is a group
1871           if (target.type == 'group') {
1872             if (target.id != this.env.group && !this.env.contactfolders[target.source].readonly) {
1873               var is_other = this.env.selection_sources.length > 1 || $.inArray(target.source, this.env.selection_sources) == -1;
1874               return !is_other || this.commands.move ? 1 : 2;
1875             }
1876           }
1877           // droptarget is a (writable) addressbook and it's not the source
1878           else if (!target.readonly && (this.env.selection_sources.length > 1 || $.inArray(id, this.env.selection_sources) == -1)) {
1879             return this.commands.move ? 1 : 2;
ff4a92 1880           }
ca38db 1881         }
T 1882     }
56f41a 1883
ff4a92 1884     return 0;
271efe 1885   };
TB 1886
ece3a5 1887   // open popup window
2f321c 1888   this.open_window = function(url, small, toolbar)
271efe 1889   {
3863a9 1890     var wname = 'rcmextwin' + new Date().getTime();
AM 1891
1892     url += (url.match(/\?/) ? '&' : '?') + '_extwin=1';
1893
1894     if (this.env.standard_windows)
4c8491 1895       var extwin = window.open(url, wname);
3863a9 1896     else {
AM 1897       var win = this.is_framed() ? parent.window : window,
1898         page = $(win),
1899         page_width = page.width(),
1900         page_height = bw.mz ? $('body', win).height() : page.height(),
1901         w = Math.min(small ? this.env.popup_width_small : this.env.popup_width, page_width),
1902         h = page_height, // always use same height
1903         l = (win.screenLeft || win.screenX) + 20,
1904         t = (win.screenTop || win.screenY) + 20,
1905         extwin = window.open(url, wname,
1906           'width='+w+',height='+h+',top='+t+',left='+l+',resizable=yes,location=no,scrollbars=yes'
1907           +(toolbar ? ',toolbar=yes,menubar=yes,status=yes' : ',toolbar=no,menubar=no,status=no'));
1908     }
838e42 1909
b408e0 1910     // detect popup blocker (#1489618)
AM 1911     // don't care this might not work with all browsers
1912     if (!extwin || extwin.closed) {
1913       this.display_message(this.get_label('windowopenerror'), 'warning');
1914       return;
1915     }
1916
838e42 1917     // write loading... message to empty windows
TB 1918     if (!url && extwin.document) {
1919       extwin.document.write('<html><body>' + this.get_label('loading') + '</body></html>');
1920     }
1921
bf3018 1922     // allow plugins to grab the window reference (#1489413)
TB 1923     this.triggerEvent('openwindow', { url:url, handle:extwin });
1924
838e42 1925     // focus window, delayed to bring to front
10a397 1926     setTimeout(function() { extwin && extwin.focus(); }, 10);
271efe 1927
2f321c 1928     return extwin;
b19097 1929   };
T 1930
4e17e6 1931
T 1932   /*********************************************************/
1933   /*********     (message) list functionality      *********/
1934   /*********************************************************/
f52c93 1935
T 1936   this.init_message_row = function(row)
1937   {
2611ac 1938     var i, fn = {}, uid = row.uid,
1bbf8c 1939       status_icon = (this.env.status_col != null ? 'status' : 'msg') + 'icn' + row.id;
8fa922 1940
f52c93 1941     if (uid && this.env.messages[uid])
T 1942       $.extend(row, this.env.messages[uid]);
1943
98f2c9 1944     // set eventhandler to status icon
A 1945     if (row.icon = document.getElementById(status_icon)) {
2611ac 1946       fn.icon = function(e) { ref.command('toggle_status', uid); };
f52c93 1947     }
T 1948
98f2c9 1949     // save message icon position too
A 1950     if (this.env.status_col != null)
1bbf8c 1951       row.msgicon = document.getElementById('msgicn'+row.id);
98f2c9 1952     else
A 1953       row.msgicon = row.icon;
1954
89e507 1955     // set eventhandler to flag icon
1bbf8c 1956     if (this.env.flagged_col != null && (row.flagicon = document.getElementById('flagicn'+row.id))) {
2611ac 1957       fn.flagicon = function(e) { ref.command('toggle_flag', uid); };
f52c93 1958     }
T 1959
89e507 1960     // set event handler to thread expand/collapse icon
1bbf8c 1961     if (!row.depth && row.has_children && (row.expando = document.getElementById('rcmexpando'+row.id))) {
2611ac 1962       fn.expando = function(e) { ref.expand_message_row(e, uid); };
89e507 1963     }
AM 1964
1965     // attach events
1966     $.each(fn, function(i, f) {
1967       row[i].onclick = function(e) { f(e); return rcube_event.cancel(e); };
b7e3b1 1968       if (bw.touch && row[i].addEventListener) {
89e507 1969         row[i].addEventListener('touchend', function(e) {
5793e7 1970           if (e.changedTouches.length == 1) {
89e507 1971             f(e);
5793e7 1972             return rcube_event.cancel(e);
TB 1973           }
1974         }, false);
1975       }
89e507 1976     });
f52c93 1977
T 1978     this.triggerEvent('insertrow', { uid:uid, row:row });
1979   };
1980
1981   // create a table row in the message list
1982   this.add_message_row = function(uid, cols, flags, attop)
1983   {
1984     if (!this.gui_objects.messagelist || !this.message_list)
1985       return false;
519aed 1986
bba252 1987     // Prevent from adding messages from different folder (#1487752)
A 1988     if (flags.mbox != this.env.mailbox && !flags.skip_mbox_check)
1989       return false;
1990
f52c93 1991     if (!this.env.messages[uid])
T 1992       this.env.messages[uid] = {};
519aed 1993
f52c93 1994     // merge flags over local message object
T 1995     $.extend(this.env.messages[uid], {
1996       deleted: flags.deleted?1:0,
609d39 1997       replied: flags.answered?1:0,
A 1998       unread: !flags.seen?1:0,
f52c93 1999       forwarded: flags.forwarded?1:0,
T 2000       flagged: flags.flagged?1:0,
2001       has_children: flags.has_children?1:0,
2002       depth: flags.depth?flags.depth:0,
0e7b66 2003       unread_children: flags.unread_children?flags.unread_children:0,
A 2004       parent_uid: flags.parent_uid?flags.parent_uid:0,
56f41a 2005       selected: this.select_all_mode || this.message_list.in_selection(uid),
e25a35 2006       ml: flags.ml?1:0,
6b4929 2007       ctype: flags.ctype,
9684dc 2008       mbox: flags.mbox,
56f41a 2009       // flags from plugins
A 2010       flags: flags.extra_flags
f52c93 2011     });
T 2012
8fd955 2013     var c, n, col, html, css_class, label, status_class = '', status_label = '',
03fe1c 2014       tree = '', expando = '',
488074 2015       list = this.message_list,
A 2016       rows = list.rows,
8fa922 2017       message = this.env.messages[uid],
c3ce9c 2018       msg_id = this.html_identifier(uid,true),
03fe1c 2019       row_class = 'message'
609d39 2020         + (!flags.seen ? ' unread' : '')
f52c93 2021         + (flags.deleted ? ' deleted' : '')
T 2022         + (flags.flagged ? ' flagged' : '')
488074 2023         + (message.selected ? ' selected' : ''),
c3ce9c 2024       row = { cols:[], style:{}, id:'rcmrow'+msg_id, uid:uid };
519aed 2025
4438d6 2026     // message status icons
e94706 2027     css_class = 'msgicon';
98f2c9 2028     if (this.env.status_col === null) {
A 2029       css_class += ' status';
8fd955 2030       if (flags.deleted) {
TB 2031         status_class += ' deleted';
2032         status_label += this.get_label('deleted') + ' ';
2033       }
2034       else if (!flags.seen) {
2035         status_class += ' unread';
2036         status_label += this.get_label('unread') + ' ';
2037       }
2038       else if (flags.unread_children > 0) {
2039         status_class += ' unreadchildren';
2040       }
98f2c9 2041     }
8fd955 2042     if (flags.answered) {
TB 2043       status_class += ' replied';
2044       status_label += this.get_label('replied') + ' ';
2045     }
2046     if (flags.forwarded) {
2047       status_class += ' forwarded';
adc23f 2048       status_label += this.get_label('forwarded') + ' ';
8fd955 2049     }
519aed 2050
488074 2051     // update selection
A 2052     if (message.selected && !list.in_selection(uid))
2053       list.selection.push(uid);
2054
8fa922 2055     // threads
519aed 2056     if (this.env.threading) {
f52c93 2057       if (message.depth) {
c84d33 2058         // This assumes that div width is hardcoded to 15px,
c3ce9c 2059         tree += '<span id="rcmtab' + msg_id + '" class="branch" style="width:' + (message.depth * 15) + 'px;">&nbsp;&nbsp;</span>';
c84d33 2060
488074 2061         if ((rows[message.parent_uid] && rows[message.parent_uid].expanded === false)
A 2062           || ((this.env.autoexpand_threads == 0 || this.env.autoexpand_threads == 2) &&
2063             (!rows[message.parent_uid] || !rows[message.parent_uid].expanded))
2064         ) {
f52c93 2065           row.style.display = 'none';
T 2066           message.expanded = false;
2067         }
2068         else
2069           message.expanded = true;
03fe1c 2070
T 2071         row_class += ' thread expanded';
488074 2072       }
f52c93 2073       else if (message.has_children) {
d8cf6d 2074         if (message.expanded === undefined && (this.env.autoexpand_threads == 1 || (this.env.autoexpand_threads == 2 && message.unread_children))) {
f52c93 2075           message.expanded = true;
T 2076         }
2077
1bbf8c 2078         expando = '<div id="rcmexpando' + row.id + '" class="' + (message.expanded ? 'expanded' : 'collapsed') + '">&nbsp;&nbsp;</div>';
03fe1c 2079         row_class += ' thread' + (message.expanded? ' expanded' : '');
c84d33 2080       }
7c494b 2081
AM 2082       if (flags.unread_children && flags.seen && !message.expanded)
2083         row_class += ' unroot';
519aed 2084     }
f52c93 2085
8fd955 2086     tree += '<span id="msgicn'+row.id+'" class="'+css_class+status_class+'" title="'+status_label+'"></span>';
03fe1c 2087     row.className = row_class;
8fa922 2088
adaddf 2089     // build subject link
0ca978 2090     if (cols.subject) {
e8bcf0 2091       var action  = flags.mbox == this.env.drafts_mailbox ? 'compose' : 'show',
TB 2092         uid_param = flags.mbox == this.env.drafts_mailbox ? '_draft_uid' : '_uid',
2093         query = { _mbox: flags.mbox };
2094       query[uid_param] = uid;
2095       cols.subject = '<a href="' + this.url(action, query) + '" onclick="return rcube_event.keyboard_only(event)"' +
2096         ' onmouseover="rcube_webmail.long_subject_title(this,'+(message.depth+1)+')" tabindex="-1"><span>'+cols.subject+'</span></a>';
f52c93 2097     }
T 2098
2099     // add each submitted col
c83535 2100     for (n in this.env.listcols) {
TB 2101       c = this.env.listcols[n];
7a5c3a 2102       col = {className: String(c).toLowerCase(), events:{}};
c83535 2103
TB 2104       if (this.env.coltypes[c] && this.env.coltypes[c].hidden) {
2105         col.className += ' hidden';
2106       }
f52c93 2107
dbd069 2108       if (c == 'flag') {
e94706 2109         css_class = (flags.flagged ? 'flagged' : 'unflagged');
8fd955 2110         label = this.get_label(css_class);
TB 2111         html = '<span id="flagicn'+row.id+'" class="'+css_class+'" title="'+label+'"></span>';
e94706 2112       }
A 2113       else if (c == 'attachment') {
8fd955 2114         label = this.get_label('withattachment');
a20496 2115         if (flags.attachmentClass)
8fd955 2116           html = '<span class="'+flags.attachmentClass+'" title="'+label+'"></span>';
a20496 2117         else if (/application\/|multipart\/(m|signed)/.test(flags.ctype))
8fd955 2118           html = '<span class="attachment" title="'+label+'"></span>';
32c657 2119         else if (/multipart\/report/.test(flags.ctype))
8fd955 2120           html = '<span class="report"></span>';
TB 2121           else
6b4929 2122           html = '&nbsp;';
4438d6 2123       }
A 2124       else if (c == 'status') {
8fd955 2125         label = '';
TB 2126         if (flags.deleted) {
4438d6 2127           css_class = 'deleted';
8fd955 2128           label = this.get_label('deleted');
TB 2129         }
2130         else if (!flags.seen) {
4438d6 2131           css_class = 'unread';
8fd955 2132           label = this.get_label('unread');
TB 2133         }
2134         else if (flags.unread_children > 0) {
98f2c9 2135           css_class = 'unreadchildren';
8fd955 2136         }
4438d6 2137         else
A 2138           css_class = 'msgicon';
8fd955 2139         html = '<span id="statusicn'+row.id+'" class="'+css_class+status_class+'" title="'+label+'"></span>';
f52c93 2140       }
6c9d49 2141       else if (c == 'threads')
A 2142         html = expando;
065d70 2143       else if (c == 'subject') {
7a5c3a 2144         if (bw.ie)
AM 2145           col.events.mouseover = function() { rcube_webmail.long_subject_title_ex(this); };
f52c93 2146         html = tree + cols[c];
065d70 2147       }
7a2bad 2148       else if (c == 'priority') {
8fd955 2149         if (flags.prio > 0 && flags.prio < 6) {
TB 2150           label = this.get_label('priority') + ' ' + flags.prio;
2151           html = '<span class="prio'+flags.prio+'" title="'+label+'"></span>';
2152         }
7a2bad 2153         else
A 2154           html = '&nbsp;';
2155       }
31aa08 2156       else if (c == 'folder') {
TB 2157         html = '<span onmouseover="rcube_webmail.long_subject_title(this)">' + cols[c] + '<span>';
2158       }
f52c93 2159       else
T 2160         html = cols[c];
2161
2162       col.innerHTML = html;
517dae 2163       row.cols.push(col);
f52c93 2164     }
T 2165
488074 2166     list.insert_row(row, attop);
f52c93 2167
T 2168     // remove 'old' row
488074 2169     if (attop && this.env.pagesize && list.rowcount > this.env.pagesize) {
A 2170       var uid = list.get_last_row();
2171       list.remove_row(uid);
2172       list.clear_selection(uid);
f52c93 2173     }
T 2174   };
2175
2176   this.set_list_sorting = function(sort_col, sort_order)
186537 2177   {
f52c93 2178     // set table header class
T 2179     $('#rcm'+this.env.sort_col).removeClass('sorted'+(this.env.sort_order.toUpperCase()));
2180     if (sort_col)
2181       $('#rcm'+sort_col).addClass('sorted'+sort_order);
8fa922 2182
f52c93 2183     this.env.sort_col = sort_col;
T 2184     this.env.sort_order = sort_order;
186537 2185   };
f52c93 2186
T 2187   this.set_list_options = function(cols, sort_col, sort_order, threads)
186537 2188   {
c31360 2189     var update, post_data = {};
f52c93 2190
d8cf6d 2191     if (sort_col === undefined)
b5002a 2192       sort_col = this.env.sort_col;
A 2193     if (!sort_order)
2194       sort_order = this.env.sort_order;
b62c48 2195
f52c93 2196     if (this.env.sort_col != sort_col || this.env.sort_order != sort_order) {
T 2197       update = 1;
2198       this.set_list_sorting(sort_col, sort_order);
186537 2199     }
8fa922 2200
f52c93 2201     if (this.env.threading != threads) {
T 2202       update = 1;
c31360 2203       post_data._threads = threads;
186537 2204     }
f52c93 2205
b62c48 2206     if (cols && cols.length) {
A 2207       // make sure new columns are added at the end of the list
c83535 2208       var i, idx, name, newcols = [], oldcols = this.env.listcols;
b62c48 2209       for (i=0; i<oldcols.length; i++) {
e0efd8 2210         name = oldcols[i];
b62c48 2211         idx = $.inArray(name, cols);
A 2212         if (idx != -1) {
c3eab2 2213           newcols.push(name);
b62c48 2214           delete cols[idx];
6c9d49 2215         }
b62c48 2216       }
A 2217       for (i=0; i<cols.length; i++)
2218         if (cols[i])
c3eab2 2219           newcols.push(cols[i]);
b5002a 2220
6c9d49 2221       if (newcols.join() != oldcols.join()) {
b62c48 2222         update = 1;
c31360 2223         post_data._cols = newcols.join(',');
b62c48 2224       }
186537 2225     }
f52c93 2226
T 2227     if (update)
c31360 2228       this.list_mailbox('', '', sort_col+'_'+sort_order, post_data);
186537 2229   };
4e17e6 2230
271efe 2231   // when user double-clicks on a row
b19097 2232   this.show_message = function(id, safe, preview)
186537 2233   {
dbd069 2234     if (!id)
A 2235       return;
186537 2236
24fa5d 2237     var win, target = window,
602d74 2238       url = this.params_from_uid(id, {_caps: this.browser_capabilities()});
186537 2239
24fa5d 2240     if (preview && (win = this.get_frame_window(this.env.contentframe))) {
AM 2241       target = win;
04a688 2242       url._framed = 1;
186537 2243     }
6b47de 2244
4e17e6 2245     if (safe)
04a688 2246       url._safe = 1;
4e17e6 2247
1f020b 2248     // also send search request to get the right messages
S 2249     if (this.env.search_request)
04a688 2250       url._search = this.env.search_request;
e349a8 2251
271efe 2252     if (this.env.extwin)
04a688 2253       url._extwin = 1;
AM 2254
2255     url = this.url(preview ? 'preview': 'show', url);
271efe 2256
TB 2257     if (preview && String(target.location.href).indexOf(url) >= 0) {
bf2f39 2258       this.show_contentframe(true);
271efe 2259     }
bc4960 2260     else {
271efe 2261       if (!preview && this.env.message_extwin && !this.env.extwin)
04a688 2262         this.open_window(url, true);
271efe 2263       else
04a688 2264         this.location_href(url, target, true);
ca3c73 2265
bf2f39 2266       // mark as read and change mbox unread counter
d28dae 2267       if (preview && this.message_list && this.message_list.rows[id] && this.message_list.rows[id].unread && this.env.preview_pane_mark_read > 0) {
da5cad 2268         this.preview_read_timer = setTimeout(function() {
d28dae 2269           ref.set_unread_message(id, ref.env.mailbox);
6ca090 2270           ref.http_post('mark', {_uid: id, _flag: 'read', _mbox: ref.env.mailbox, _quiet: 1});
bc4960 2271         }, this.env.preview_pane_mark_read * 1000);
4e17e6 2272       }
bc4960 2273     }
T 2274   };
b19097 2275
d28dae 2276   // update message status and unread counter after marking a message as read
AM 2277   this.set_unread_message = function(id, folder)
2278   {
2279     var self = this;
2280
2281     // find window with messages list
2282     if (!self.message_list)
2283       self = self.opener();
2284
2285     if (!self && window.parent)
2286       self = parent.rcmail;
2287
2288     if (!self || !self.message_list)
2289       return;
2290
ae4873 2291     // this may fail in multifolder mode
AM 2292     if (self.set_message(id, 'unread', false) === false)
2293       self.set_message(id + '-' + folder, 'unread', false);
d28dae 2294
AM 2295     if (self.env.unread_counts[folder] > 0) {
2296       self.env.unread_counts[folder] -= 1;
ae4873 2297       self.set_unread_count(folder, self.env.unread_counts[folder], folder == 'INBOX' && !self.is_multifolder_listing());
d28dae 2298     }
AM 2299   };
2300
f11541 2301   this.show_contentframe = function(show)
186537 2302   {
24fa5d 2303     var frame, win, name = this.env.contentframe;
AM 2304
2305     if (name && (frame = this.get_frame_element(name))) {
2306       if (!show && (win = this.get_frame_window(name))) {
c511f5 2307         if (win.location.href.indexOf(this.env.blankpage) < 0) {
AM 2308           if (win.stop)
2309             win.stop();
2310           else // IE
2311             win.document.execCommand('Stop');
446dbe 2312
c511f5 2313           win.location.href = this.env.blankpage;
AM 2314         }
186537 2315       }
ca3c73 2316       else if (!bw.safari && !bw.konq)
24fa5d 2317         $(frame)[show ? 'show' : 'hide']();
AM 2318     }
ca3c73 2319
446dbe 2320     if (!show && this.env.frame_lock)
d808ba 2321       this.set_busy(false, null, this.env.frame_lock);
24fa5d 2322   };
AM 2323
2324   this.get_frame_element = function(id)
2325   {
2326     var frame;
2327
2328     if (id && (frame = document.getElementById(id)))
2329       return frame;
2330   };
2331
2332   this.get_frame_window = function(id)
2333   {
2334     var frame = this.get_frame_element(id);
2335
2336     if (frame && frame.name && window.frames)
2337       return window.frames[frame.name];
a16400 2338   };
A 2339
2340   this.lock_frame = function()
2341   {
2342     if (!this.env.frame_lock)
2343       (this.is_framed() ? parent.rcmail : this).env.frame_lock = this.set_busy(true, 'loading');
186537 2344   };
4e17e6 2345
T 2346   // list a specific page
2347   this.list_page = function(page)
186537 2348   {
dbd069 2349     if (page == 'next')
4e17e6 2350       page = this.env.current_page+1;
b0fd4c 2351     else if (page == 'last')
d17008 2352       page = this.env.pagecount;
b0fd4c 2353     else if (page == 'prev' && this.env.current_page > 1)
4e17e6 2354       page = this.env.current_page-1;
b0fd4c 2355     else if (page == 'first' && this.env.current_page > 1)
d17008 2356       page = 1;
186537 2357
A 2358     if (page > 0 && page <= this.env.pagecount) {
4e17e6 2359       this.env.current_page = page;
8fa922 2360
eeb73c 2361       if (this.task == 'addressbook' || this.contact_list)
053e5a 2362         this.list_contacts(this.env.source, this.env.group, page);
eeb73c 2363       else if (this.task == 'mail')
T 2364         this.list_mailbox(this.env.mailbox, page);
186537 2365     }
77de23 2366   };
AM 2367
2368   // sends request to check for recent messages
2369   this.checkmail = function()
2370   {
2371     var lock = this.set_busy(true, 'checkingmail'),
2372       params = this.check_recent_params();
2373
a59499 2374     this.http_post('check-recent', params, lock);
186537 2375   };
4e17e6 2376
e538b3 2377   // list messages of a specific mailbox using filter
A 2378   this.filter_mailbox = function(filter)
186537 2379   {
1ec105 2380     if (this.filter_disabled)
AM 2381       return;
2382
e9c47c 2383     var lock = this.set_busy(true, 'searching');
e538b3 2384
bb2699 2385     this.clear_message_list();
186537 2386
A 2387     // reset vars
2388     this.env.current_page = 1;
26b520 2389     this.env.search_filter = filter;
e9c47c 2390     this.http_request('search', this.search_params(false, filter), lock);
186537 2391   };
e538b3 2392
1e9a59 2393   // reload the current message listing
TB 2394   this.refresh_list = function()
2395   {
2396     this.list_mailbox(this.env.mailbox, this.env.current_page || 1, null, { _clear:1 }, true);
2397     if (this.message_list)
2398       this.message_list.clear_selection();
2399   };
2400
4e17e6 2401   // list messages of a specific mailbox
1e9a59 2402   this.list_mailbox = function(mbox, page, sort, url, update_only)
186537 2403   {
24fa5d 2404     var win, target = window;
c31360 2405
A 2406     if (typeof url != 'object')
2407       url = {};
4e17e6 2408
T 2409     if (!mbox)
4da0be 2410       mbox = this.env.mailbox ? this.env.mailbox : 'INBOX';
4e17e6 2411
f3b659 2412     // add sort to url if set
T 2413     if (sort)
c31360 2414       url._sort = sort;
f11541 2415
1ec105 2416     // folder change, reset page, search scope, etc.
488074 2417     if (this.env.mailbox != mbox) {
4e17e6 2418       page = 1;
T 2419       this.env.current_page = page;
1ec105 2420       this.env.search_scope = 'base';
488074 2421       this.select_all_mode = false;
da1816 2422       this.reset_search_filter();
186537 2423     }
1ec105 2424     // also send search request to get the right messages
AM 2425     else if (this.env.search_request)
2426       url._search = this.env.search_request;
be9d4d 2427
1e9a59 2428     if (!update_only) {
TB 2429       // unselect selected messages and clear the list and message data
2430       this.clear_message_list();
e737a5 2431
1e9a59 2432       if (mbox != this.env.mailbox || (mbox == this.env.mailbox && !page && !sort))
TB 2433         url._refresh = 1;
d9c83e 2434
1e9a59 2435       this.select_folder(mbox, '', true);
TB 2436       this.unmark_folder(mbox, 'recent', '', true);
2437       this.env.mailbox = mbox;
2438     }
4e17e6 2439
T 2440     // load message list remotely
186537 2441     if (this.gui_objects.messagelist) {
f52c93 2442       this.list_mailbox_remote(mbox, page, url);
4e17e6 2443       return;
186537 2444     }
8fa922 2445
24fa5d 2446     if (win = this.get_frame_window(this.env.contentframe)) {
AM 2447       target = win;
c31360 2448       url._framed = 1;
186537 2449     }
4e17e6 2450
64f7d6 2451     if (this.env.uid)
AM 2452       url._uid = this.env.uid;
2453
4e17e6 2454     // load message list to target frame/window
186537 2455     if (mbox) {
4e17e6 2456       this.set_busy(true, 'loading');
c31360 2457       url._mbox = mbox;
A 2458       if (page)
2459         url._page = page;
2460       this.location_href(url, target);
186537 2461     }
be9d4d 2462   };
A 2463
2464   this.clear_message_list = function()
2465   {
39a82a 2466     this.env.messages = {};
be9d4d 2467
39a82a 2468     this.show_contentframe(false);
AM 2469     if (this.message_list)
2470       this.message_list.clear(true);
186537 2471   };
4e17e6 2472
T 2473   // send remote request to load message list
1e9a59 2474   this.list_mailbox_remote = function(mbox, page, url)
186537 2475   {
c31360 2476     var lock = this.set_busy(true, 'loading');
A 2477
1e9a59 2478     if (typeof url != 'object')
TB 2479       url = {};
2480     url._mbox = mbox;
c31360 2481     if (page)
1e9a59 2482       url._page = page;
c31360 2483
1e9a59 2484     this.http_request('list', url, lock);
b2992d 2485     this.update_state({ _mbox: mbox, _page: (page && page > 1 ? page : null) });
186537 2486   };
488074 2487
A 2488   // removes messages that doesn't exists from list selection array
2489   this.update_selection = function()
2490   {
2491     var selected = this.message_list.selection,
2492       rows = this.message_list.rows,
2493       i, selection = [];
2494
2495     for (i in selected)
2496       if (rows[selected[i]])
2497         selection.push(selected[i]);
2498
2499     this.message_list.selection = selection;
5d42a9 2500
AM 2501     // reset preview frame, if currently previewed message is not selected (has been removed)
2502     try {
2503       var win = this.get_frame_window(this.env.contentframe),
2504         id = win.rcmail.env.uid;
2505
2506       if (id && $.inArray(id, selection) < 0)
2507         this.show_contentframe(false);
2508     }
2509     catch (e) {};
a5fe9a 2510   };
15a9d1 2511
f52c93 2512   // expand all threads with unread children
T 2513   this.expand_unread = function()
186537 2514   {
1cb23c 2515     var r, tbody = this.message_list.tbody,
dbd069 2516       new_row = tbody.firstChild;
8fa922 2517
f52c93 2518     while (new_row) {
609d39 2519       if (new_row.nodeType == 1 && (r = this.message_list.rows[new_row.uid]) && r.unread_children) {
a945da 2520         this.message_list.expand_all(r);
A 2521         this.set_unread_children(r.uid);
f52c93 2522       }
a5fe9a 2523
186537 2524       new_row = new_row.nextSibling;
A 2525     }
a5fe9a 2526
f52c93 2527     return false;
186537 2528   };
4e17e6 2529
b5002a 2530   // thread expanding/collapsing handler
f52c93 2531   this.expand_message_row = function(e, uid)
186537 2532   {
f52c93 2533     var row = this.message_list.rows[uid];
5e3512 2534
f52c93 2535     // handle unread_children mark
T 2536     row.expanded = !row.expanded;
2537     this.set_unread_children(uid);
2538     row.expanded = !row.expanded;
2539
2540     this.message_list.expand_row(e, uid);
186537 2541   };
f11541 2542
f52c93 2543   // message list expanding
T 2544   this.expand_threads = function()
b5002a 2545   {
f52c93 2546     if (!this.env.threading || !this.env.autoexpand_threads || !this.message_list)
T 2547       return;
186537 2548
f52c93 2549     switch (this.env.autoexpand_threads) {
T 2550       case 2: this.expand_unread(); break;
2551       case 1: this.message_list.expand_all(); break;
2552     }
8fa922 2553   };
f52c93 2554
0e7b66 2555   // Initializes threads indicators/expanders after list update
bba252 2556   this.init_threads = function(roots, mbox)
0e7b66 2557   {
bba252 2558     // #1487752
A 2559     if (mbox && mbox != this.env.mailbox)
2560       return false;
2561
0e7b66 2562     for (var n=0, len=roots.length; n<len; n++)
54531f 2563       this.add_tree_icons(roots[n]);
A 2564     this.expand_threads();
0e7b66 2565   };
A 2566
2567   // adds threads tree icons to the list (or specified thread)
2568   this.add_tree_icons = function(root)
2569   {
2570     var i, l, r, n, len, pos, tmp = [], uid = [],
2571       row, rows = this.message_list.rows;
2572
2573     if (root)
2574       row = rows[root] ? rows[root].obj : null;
2575     else
517dae 2576       row = this.message_list.tbody.firstChild;
0e7b66 2577
A 2578     while (row) {
2579       if (row.nodeType == 1 && (r = rows[row.uid])) {
2580         if (r.depth) {
2581           for (i=tmp.length-1; i>=0; i--) {
2582             len = tmp[i].length;
2583             if (len > r.depth) {
2584               pos = len - r.depth;
2585               if (!(tmp[i][pos] & 2))
2586                 tmp[i][pos] = tmp[i][pos] ? tmp[i][pos]+2 : 2;
2587             }
2588             else if (len == r.depth) {
2589               if (!(tmp[i][0] & 2))
2590                 tmp[i][0] += 2;
2591             }
2592             if (r.depth > len)
2593               break;
2594           }
2595
2596           tmp.push(new Array(r.depth));
2597           tmp[tmp.length-1][0] = 1;
2598           uid.push(r.uid);
2599         }
2600         else {
2601           if (tmp.length) {
2602             for (i in tmp) {
2603               this.set_tree_icons(uid[i], tmp[i]);
2604             }
2605             tmp = [];
2606             uid = [];
2607           }
2608           if (root && row != rows[root].obj)
2609             break;
2610         }
2611       }
2612       row = row.nextSibling;
2613     }
2614
2615     if (tmp.length) {
2616       for (i in tmp) {
2617         this.set_tree_icons(uid[i], tmp[i]);
2618       }
2619     }
fb4663 2620   };
0e7b66 2621
A 2622   // adds tree icons to specified message row
2623   this.set_tree_icons = function(uid, tree)
2624   {
2625     var i, divs = [], html = '', len = tree.length;
2626
2627     for (i=0; i<len; i++) {
2628       if (tree[i] > 2)
2629         divs.push({'class': 'l3', width: 15});
2630       else if (tree[i] > 1)
2631         divs.push({'class': 'l2', width: 15});
2632       else if (tree[i] > 0)
2633         divs.push({'class': 'l1', width: 15});
2634       // separator div
2635       else if (divs.length && !divs[divs.length-1]['class'])
2636         divs[divs.length-1].width += 15;
2637       else
2638         divs.push({'class': null, width: 15});
2639     }
fb4663 2640
0e7b66 2641     for (i=divs.length-1; i>=0; i--) {
A 2642       if (divs[i]['class'])
2643         html += '<div class="tree '+divs[i]['class']+'" />';
2644       else
2645         html += '<div style="width:'+divs[i].width+'px" />';
2646     }
fb4663 2647
0e7b66 2648     if (html)
1bbf8c 2649       $('#rcmtab'+this.html_identifier(uid, true)).html(html);
0e7b66 2650   };
A 2651
f52c93 2652   // update parent in a thread
T 2653   this.update_thread_root = function(uid, flag)
0dbac3 2654   {
f52c93 2655     if (!this.env.threading)
T 2656       return;
2657
bc2acc 2658     var root = this.message_list.find_root(uid);
8fa922 2659
f52c93 2660     if (uid == root)
T 2661       return;
2662
2663     var p = this.message_list.rows[root];
2664
2665     if (flag == 'read' && p.unread_children) {
2666       p.unread_children--;
dbd069 2667     }
A 2668     else if (flag == 'unread' && p.has_children) {
f52c93 2669       // unread_children may be undefined
T 2670       p.unread_children = p.unread_children ? p.unread_children + 1 : 1;
dbd069 2671     }
A 2672     else {
f52c93 2673       return;
T 2674     }
2675
2676     this.set_message_icon(root);
2677     this.set_unread_children(root);
0dbac3 2678   };
f52c93 2679
T 2680   // update thread indicators for all messages in a thread below the specified message
2681   // return number of removed/added root level messages
2682   this.update_thread = function (uid)
2683   {
2684     if (!this.env.threading)
2685       return 0;
2686
dbd069 2687     var r, parent, count = 0,
A 2688       rows = this.message_list.rows,
2689       row = rows[uid],
2690       depth = rows[uid].depth,
2691       roots = [];
f52c93 2692
T 2693     if (!row.depth) // root message: decrease roots count
2694       count--;
2695     else if (row.unread) {
2696       // update unread_children for thread root
dbd069 2697       parent = this.message_list.find_root(uid);
f52c93 2698       rows[parent].unread_children--;
T 2699       this.set_unread_children(parent);
186537 2700     }
f52c93 2701
T 2702     parent = row.parent_uid;
2703
2704     // childrens
2705     row = row.obj.nextSibling;
2706     while (row) {
2707       if (row.nodeType == 1 && (r = rows[row.uid])) {
a945da 2708         if (!r.depth || r.depth <= depth)
A 2709           break;
f52c93 2710
a945da 2711         r.depth--; // move left
0e7b66 2712         // reset width and clear the content of a tab, icons will be added later
1bbf8c 2713         $('#rcmtab'+r.id).width(r.depth * 15).html('');
f52c93 2714         if (!r.depth) { // a new root
a945da 2715           count++; // increase roots count
A 2716           r.parent_uid = 0;
2717           if (r.has_children) {
2718             // replace 'leaf' with 'collapsed'
1bbf8c 2719             $('#'+r.id+' .leaf:first')
TB 2720               .attr('id', 'rcmexpando' + r.id)
a945da 2721               .attr('class', (r.obj.style.display != 'none' ? 'expanded' : 'collapsed'))
f1aaca 2722               .bind('mousedown', {uid: r.uid},
AM 2723                 function(e) { return ref.expand_message_row(e, e.data.uid); });
f52c93 2724
a945da 2725             r.unread_children = 0;
A 2726             roots.push(r);
2727           }
2728           // show if it was hidden
2729           if (r.obj.style.display == 'none')
2730             $(r.obj).show();
2731         }
2732         else {
2733           if (r.depth == depth)
2734             r.parent_uid = parent;
2735           if (r.unread && roots.length)
2736             roots[roots.length-1].unread_children++;
2737         }
2738       }
2739       row = row.nextSibling;
186537 2740     }
8fa922 2741
f52c93 2742     // update unread_children for roots
a5fe9a 2743     for (r=0; r<roots.length; r++)
AM 2744       this.set_unread_children(roots[r].uid);
f52c93 2745
T 2746     return count;
2747   };
2748
2749   this.delete_excessive_thread_rows = function()
2750   {
dbd069 2751     var rows = this.message_list.rows,
517dae 2752       tbody = this.message_list.tbody,
dbd069 2753       row = tbody.firstChild,
A 2754       cnt = this.env.pagesize + 1;
8fa922 2755
f52c93 2756     while (row) {
T 2757       if (row.nodeType == 1 && (r = rows[row.uid])) {
a945da 2758         if (!r.depth && cnt)
A 2759           cnt--;
f52c93 2760
T 2761         if (!cnt)
a945da 2762           this.message_list.remove_row(row.uid);
A 2763       }
2764       row = row.nextSibling;
186537 2765     }
A 2766   };
0dbac3 2767
25c35c 2768   // set message icon
A 2769   this.set_message_icon = function(uid)
2770   {
8fd955 2771     var css_class, label = '',
98f2c9 2772       row = this.message_list.rows[uid];
25c35c 2773
98f2c9 2774     if (!row)
25c35c 2775       return false;
e94706 2776
98f2c9 2777     if (row.icon) {
A 2778       css_class = 'msgicon';
8fd955 2779       if (row.deleted) {
98f2c9 2780         css_class += ' deleted';
8fd955 2781         label += this.get_label('deleted') + ' ';
TB 2782       }
2783       else if (row.unread) {
98f2c9 2784         css_class += ' unread';
8fd955 2785         label += this.get_label('unread') + ' ';
TB 2786       }
98f2c9 2787       else if (row.unread_children)
A 2788         css_class += ' unreadchildren';
2789       if (row.msgicon == row.icon) {
8fd955 2790         if (row.replied) {
98f2c9 2791           css_class += ' replied';
8fd955 2792           label += this.get_label('replied') + ' ';
TB 2793         }
2794         if (row.forwarded) {
98f2c9 2795           css_class += ' forwarded';
8fd955 2796           label += this.get_label('forwarded') + ' ';
TB 2797         }
98f2c9 2798         css_class += ' status';
A 2799       }
4438d6 2800
8fd955 2801       $(row.icon).attr('class', css_class).attr('title', label);
4438d6 2802     }
A 2803
98f2c9 2804     if (row.msgicon && row.msgicon != row.icon) {
8fd955 2805       label = '';
e94706 2806       css_class = 'msgicon';
8fd955 2807       if (!row.unread && row.unread_children) {
e94706 2808         css_class += ' unreadchildren';
8fd955 2809       }
TB 2810       if (row.replied) {
4438d6 2811         css_class += ' replied';
8fd955 2812         label += this.get_label('replied') + ' ';
TB 2813       }
2814       if (row.forwarded) {
4438d6 2815         css_class += ' forwarded';
8fd955 2816         label += this.get_label('forwarded') + ' ';
TB 2817       }
e94706 2818
8fd955 2819       $(row.msgicon).attr('class', css_class).attr('title', label);
f52c93 2820     }
e94706 2821
98f2c9 2822     if (row.flagicon) {
A 2823       css_class = (row.flagged ? 'flagged' : 'unflagged');
8fd955 2824       label = this.get_label(css_class);
TB 2825       $(row.flagicon).attr('class', css_class)
2826         .attr('aria-label', label)
2827         .attr('title', label);
186537 2828     }
A 2829   };
25c35c 2830
A 2831   // set message status
2832   this.set_message_status = function(uid, flag, status)
186537 2833   {
98f2c9 2834     var row = this.message_list.rows[uid];
25c35c 2835
98f2c9 2836     if (!row)
A 2837       return false;
25c35c 2838
5f3c7e 2839     if (flag == 'unread') {
AM 2840       if (row.unread != status)
2841         this.update_thread_root(uid, status ? 'unread' : 'read');
2842     }
cf22ce 2843
AM 2844     if ($.inArray(flag, ['unread', 'deleted', 'replied', 'forwarded', 'flagged']) > -1)
2845       row[flag] = status;
186537 2846   };
25c35c 2847
A 2848   // set message row status, class and icon
2849   this.set_message = function(uid, flag, status)
186537 2850   {
0746d5 2851     var row = this.message_list && this.message_list.rows[uid];
25c35c 2852
98f2c9 2853     if (!row)
A 2854       return false;
8fa922 2855
25c35c 2856     if (flag)
A 2857       this.set_message_status(uid, flag, status);
f52c93 2858
cf22ce 2859     if ($.inArray(flag, ['unread', 'deleted', 'flagged']) > -1)
AM 2860       $(row.obj)[row[flag] ? 'addClass' : 'removeClass'](flag);
163a13 2861
f52c93 2862     this.set_unread_children(uid);
25c35c 2863     this.set_message_icon(uid);
186537 2864   };
f52c93 2865
T 2866   // sets unroot (unread_children) class of parent row
2867   this.set_unread_children = function(uid)
186537 2868   {
f52c93 2869     var row = this.message_list.rows[uid];
186537 2870
0e7b66 2871     if (row.parent_uid)
f52c93 2872       return;
T 2873
2874     if (!row.unread && row.unread_children && !row.expanded)
2875       $(row.obj).addClass('unroot');
2876     else
2877       $(row.obj).removeClass('unroot');
186537 2878   };
9b3fdc 2879
A 2880   // copy selected messages to the specified mailbox
6789bf 2881   this.copy_messages = function(mbox, event)
186537 2882   {
d8cf6d 2883     if (mbox && typeof mbox === 'object')
488074 2884       mbox = mbox.id;
9a0153 2885     else if (!mbox)
6789bf 2886       return this.folder_selector(event, function(folder) { ref.command('copy', folder); });
488074 2887
463ce6 2888     // exit if current or no mailbox specified
AM 2889     if (!mbox || mbox == this.env.mailbox)
9b3fdc 2890       return;
A 2891
463ce6 2892     var post_data = this.selection_post_data({_target_mbox: mbox});
9b3fdc 2893
463ce6 2894     // exit if selection is empty
AM 2895     if (!post_data._uid)
2896       return;
c0c0c0 2897
9b3fdc 2898     // send request to server
463ce6 2899     this.http_post('copy', post_data, this.display_message(this.get_label('copyingmessage'), 'loading'));
186537 2900   };
0dbac3 2901
4e17e6 2902   // move selected messages to the specified mailbox
6789bf 2903   this.move_messages = function(mbox, event)
186537 2904   {
d8cf6d 2905     if (mbox && typeof mbox === 'object')
a61bbb 2906       mbox = mbox.id;
9a0153 2907     else if (!mbox)
6789bf 2908       return this.folder_selector(event, function(folder) { ref.command('move', folder); });
8fa922 2909
463ce6 2910     // exit if current or no mailbox specified
f50a66 2911     if (!mbox || (mbox == this.env.mailbox && !this.is_multifolder_listing()))
aa9836 2912       return;
e4bbb2 2913
463ce6 2914     var lock = false, post_data = this.selection_post_data({_target_mbox: mbox});
AM 2915
2916     // exit if selection is empty
2917     if (!post_data._uid)
2918       return;
4e17e6 2919
T 2920     // show wait message
c31360 2921     if (this.env.action == 'show')
ad334a 2922       lock = this.set_busy(true, 'movingmessage');
0b2ce9 2923     else
f11541 2924       this.show_contentframe(false);
6b47de 2925
faebf4 2926     // Hide message command buttons until a message is selected
14259c 2927     this.enable_command(this.env.message_commands, false);
faebf4 2928
a45f9b 2929     this._with_selected_messages('move', post_data, lock);
186537 2930   };
4e17e6 2931
857a38 2932   // delete selected messages from the current mailbox
c28161 2933   this.delete_messages = function(event)
84a331 2934   {
7eecf8 2935     var list = this.message_list, trash = this.env.trash_mailbox;
8fa922 2936
0b2ce9 2937     // if config is set to flag for deletion
f52c93 2938     if (this.env.flag_for_deletion) {
0b2ce9 2939       this.mark_message('delete');
f52c93 2940       return false;
84a331 2941     }
0b2ce9 2942     // if there isn't a defined trash mailbox or we are in it
476407 2943     else if (!trash || this.env.mailbox == trash)
0b2ce9 2944       this.permanently_remove_messages();
1b30a7 2945     // we're in Junk folder and delete_junk is enabled
A 2946     else if (this.env.delete_junk && this.env.junk_mailbox && this.env.mailbox == this.env.junk_mailbox)
2947       this.permanently_remove_messages();
0b2ce9 2948     // if there is a trash mailbox defined and we're not currently in it
A 2949     else {
31c171 2950       // if shift was pressed delete it immediately
c28161 2951       if ((list && list.modkey == SHIFT_KEY) || (event && rcube_event.get_modifier(event) == SHIFT_KEY)) {
31c171 2952         if (confirm(this.get_label('deletemessagesconfirm')))
S 2953           this.permanently_remove_messages();
84a331 2954       }
31c171 2955       else
476407 2956         this.move_messages(trash);
84a331 2957     }
f52c93 2958
T 2959     return true;
857a38 2960   };
cfdf04 2961
T 2962   // delete the selected messages permanently
2963   this.permanently_remove_messages = function()
186537 2964   {
463ce6 2965     var post_data = this.selection_post_data();
AM 2966
2967     // exit if selection is empty
2968     if (!post_data._uid)
cfdf04 2969       return;
8fa922 2970
f11541 2971     this.show_contentframe(false);
463ce6 2972     this._with_selected_messages('delete', post_data);
186537 2973   };
cfdf04 2974
7eecf8 2975   // Send a specific move/delete request with UIDs of all selected messages
cfdf04 2976   // @private
463ce6 2977   this._with_selected_messages = function(action, post_data, lock)
d22455 2978   {
1e9a59 2979     var count = 0, msg,
f50a66 2980       remove = (action == 'delete' || !this.is_multifolder_listing());
c31360 2981
463ce6 2982     // update the list (remove rows, clear selection)
AM 2983     if (this.message_list) {
0e7b66 2984       var n, id, root, roots = [],
A 2985         selection = this.message_list.get_selection();
2986
2987       for (n=0, len=selection.length; n<len; n++) {
cfdf04 2988         id = selection[n];
0e7b66 2989
A 2990         if (this.env.threading) {
2991           count += this.update_thread(id);
2992           root = this.message_list.find_root(id);
2993           if (root != id && $.inArray(root, roots) < 0) {
2994             roots.push(root);
2995           }
2996         }
1e9a59 2997         if (remove)
TB 2998           this.message_list.remove_row(id, (this.env.display_next && n == selection.length-1));
cfdf04 2999       }
e54bb7 3000       // make sure there are no selected rows
1e9a59 3001       if (!this.env.display_next && remove)
e54bb7 3002         this.message_list.clear_selection();
0e7b66 3003       // update thread tree icons
A 3004       for (n=0, len=roots.length; n<len; n++) {
3005         this.add_tree_icons(roots[n]);
3006       }
d22455 3007     }
132aae 3008
f52c93 3009     if (count < 0)
c31360 3010       post_data._count = (count*-1);
A 3011     // remove threads from the end of the list
1e9a59 3012     else if (count > 0 && remove)
f52c93 3013       this.delete_excessive_thread_rows();
1e9a59 3014
TB 3015     if (!remove)
3016       post_data._refresh = 1;
c50d88 3017
A 3018     if (!lock) {
a45f9b 3019       msg = action == 'move' ? 'movingmessage' : 'deletingmessage';
c50d88 3020       lock = this.display_message(this.get_label(msg), 'loading');
A 3021     }
fb7ec5 3022
cfdf04 3023     // send request to server
c31360 3024     this.http_post(action, post_data, lock);
d22455 3025   };
4e17e6 3026
3a1a36 3027   // build post data for message delete/move/copy/flag requests
463ce6 3028   this.selection_post_data = function(data)
AM 3029   {
3030     if (typeof(data) != 'object')
3031       data = {};
3032
3033     data._mbox = this.env.mailbox;
3a1a36 3034
AM 3035     if (!data._uid) {
5c421d 3036       var uids = this.env.uid ? [this.env.uid] : this.message_list.get_selection();
3a1a36 3037       data._uid = this.uids_to_list(uids);
AM 3038     }
463ce6 3039
AM 3040     if (this.env.action)
3041       data._from = this.env.action;
3042
3043     // also send search request to get the right messages
3044     if (this.env.search_request)
3045       data._search = this.env.search_request;
3046
ccb132 3047     if (this.env.display_next && this.env.next_uid)
60e1b3 3048       data._next_uid = this.env.next_uid;
ccb132 3049
463ce6 3050     return data;
AM 3051   };
3052
4e17e6 3053   // set a specific flag to one or more messages
T 3054   this.mark_message = function(flag, uid)
186537 3055   {
463ce6 3056     var a_uids = [], r_uids = [], len, n, id,
4877db 3057       list = this.message_list;
3d3531 3058
4e17e6 3059     if (uid)
T 3060       a_uids[0] = uid;
3061     else if (this.env.uid)
3062       a_uids[0] = this.env.uid;
463ce6 3063     else if (list)
AM 3064       a_uids = list.get_selection();
5d97ac 3065
4877db 3066     if (!list)
3d3531 3067       r_uids = a_uids;
4877db 3068     else {
AM 3069       list.focus();
0e7b66 3070       for (n=0, len=a_uids.length; n<len; n++) {
5d97ac 3071         id = a_uids[n];
463ce6 3072         if ((flag == 'read' && list.rows[id].unread)
AM 3073             || (flag == 'unread' && !list.rows[id].unread)
3074             || (flag == 'delete' && !list.rows[id].deleted)
3075             || (flag == 'undelete' && list.rows[id].deleted)
3076             || (flag == 'flagged' && !list.rows[id].flagged)
3077             || (flag == 'unflagged' && list.rows[id].flagged))
d22455 3078         {
0e7b66 3079           r_uids.push(id);
d22455 3080         }
4e17e6 3081       }
4877db 3082     }
3d3531 3083
1a98a6 3084     // nothing to do
f3d37f 3085     if (!r_uids.length && !this.select_all_mode)
1a98a6 3086       return;
3d3531 3087
186537 3088     switch (flag) {
857a38 3089         case 'read':
S 3090         case 'unread':
5d97ac 3091           this.toggle_read_status(flag, r_uids);
857a38 3092           break;
S 3093         case 'delete':
3094         case 'undelete':
5d97ac 3095           this.toggle_delete_status(r_uids);
e189a6 3096           break;
A 3097         case 'flagged':
3098         case 'unflagged':
3099           this.toggle_flagged_status(flag, a_uids);
857a38 3100           break;
186537 3101     }
A 3102   };
4e17e6 3103
857a38 3104   // set class to read/unread
6b47de 3105   this.toggle_read_status = function(flag, a_uids)
T 3106   {
4fb6a2 3107     var i, len = a_uids.length,
3a1a36 3108       post_data = this.selection_post_data({_uid: this.uids_to_list(a_uids), _flag: flag}),
c50d88 3109       lock = this.display_message(this.get_label('markingmessage'), 'loading');
4fb6a2 3110
A 3111     // mark all message rows as read/unread
3112     for (i=0; i<len; i++)
3a1a36 3113       this.set_message(a_uids[i], 'unread', (flag == 'unread' ? true : false));
ab10d6 3114
c31360 3115     this.http_post('mark', post_data, lock);
6b47de 3116   };
6d2714 3117
e189a6 3118   // set image to flagged or unflagged
A 3119   this.toggle_flagged_status = function(flag, a_uids)
3120   {
4fb6a2 3121     var i, len = a_uids.length,
3a1a36 3122       post_data = this.selection_post_data({_uid: this.uids_to_list(a_uids), _flag: flag}),
c50d88 3123       lock = this.display_message(this.get_label('markingmessage'), 'loading');
4fb6a2 3124
A 3125     // mark all message rows as flagged/unflagged
3126     for (i=0; i<len; i++)
3a1a36 3127       this.set_message(a_uids[i], 'flagged', (flag == 'flagged' ? true : false));
ab10d6 3128
c31360 3129     this.http_post('mark', post_data, lock);
e189a6 3130   };
8fa922 3131
857a38 3132   // mark all message rows as deleted/undeleted
6b47de 3133   this.toggle_delete_status = function(a_uids)
T 3134   {
4fb6a2 3135     var len = a_uids.length,
A 3136       i, uid, all_deleted = true,
85fece 3137       rows = this.message_list ? this.message_list.rows : {};
8fa922 3138
4fb6a2 3139     if (len == 1) {
85fece 3140       if (!this.message_list || (rows[a_uids[0]] && !rows[a_uids[0]].deleted))
6b47de 3141         this.flag_as_deleted(a_uids);
T 3142       else
3143         this.flag_as_undeleted(a_uids);
3144
1c5853 3145       return true;
S 3146     }
8fa922 3147
4fb6a2 3148     for (i=0; i<len; i++) {
857a38 3149       uid = a_uids[i];
f3d37f 3150       if (rows[uid] && !rows[uid].deleted) {
A 3151         all_deleted = false;
3152         break;
857a38 3153       }
1c5853 3154     }
8fa922 3155
1c5853 3156     if (all_deleted)
S 3157       this.flag_as_undeleted(a_uids);
3158     else
3159       this.flag_as_deleted(a_uids);
8fa922 3160
1c5853 3161     return true;
6b47de 3162   };
4e17e6 3163
6b47de 3164   this.flag_as_undeleted = function(a_uids)
T 3165   {
3a1a36 3166     var i, len = a_uids.length,
AM 3167       post_data = this.selection_post_data({_uid: this.uids_to_list(a_uids), _flag: 'undelete'}),
c50d88 3168       lock = this.display_message(this.get_label('markingmessage'), 'loading');
4fb6a2 3169
A 3170     for (i=0; i<len; i++)
3171       this.set_message(a_uids[i], 'deleted', false);
ab10d6 3172
c31360 3173     this.http_post('mark', post_data, lock);
6b47de 3174   };
T 3175
3176   this.flag_as_deleted = function(a_uids)
3177   {
c31360 3178     var r_uids = [],
3a1a36 3179       post_data = this.selection_post_data({_uid: this.uids_to_list(a_uids), _flag: 'delete'}),
c31360 3180       lock = this.display_message(this.get_label('markingmessage'), 'loading'),
85fece 3181       rows = this.message_list ? this.message_list.rows : {},
fb7ec5 3182       count = 0;
f52c93 3183
0e7b66 3184     for (var i=0, len=a_uids.length; i<len; i++) {
1c5853 3185       uid = a_uids[i];
fb7ec5 3186       if (rows[uid]) {
d22455 3187         if (rows[uid].unread)
T 3188           r_uids[r_uids.length] = uid;
0b2ce9 3189
a945da 3190         if (this.env.skip_deleted) {
A 3191           count += this.update_thread(uid);
e54bb7 3192           this.message_list.remove_row(uid, (this.env.display_next && i == this.message_list.selection.length-1));
a945da 3193         }
A 3194         else
3195           this.set_message(uid, 'deleted', true);
3d3531 3196       }
fb7ec5 3197     }
e54bb7 3198
A 3199     // make sure there are no selected rows
f52c93 3200     if (this.env.skip_deleted && this.message_list) {
85fece 3201       if (!this.env.display_next)
fb7ec5 3202         this.message_list.clear_selection();
f52c93 3203       if (count < 0)
c31360 3204         post_data._count = (count*-1);
70da8c 3205       else if (count > 0)
f52c93 3206         // remove threads from the end of the list
T 3207         this.delete_excessive_thread_rows();
fb7ec5 3208     }
3d3531 3209
70da8c 3210     // set of messages to mark as seen
3d3531 3211     if (r_uids.length)
c31360 3212       post_data._ruid = this.uids_to_list(r_uids);
3d3531 3213
c31360 3214     if (this.env.skip_deleted && this.env.display_next && this.env.next_uid)
A 3215       post_data._next_uid = this.env.next_uid;
8fa922 3216
c31360 3217     this.http_post('mark', post_data, lock);
6b47de 3218   };
3d3531 3219
A 3220   // flag as read without mark request (called from backend)
3221   // argument should be a coma-separated list of uids
3222   this.flag_deleted_as_read = function(uids)
3223   {
70da8c 3224     var uid, i, len,
85fece 3225       rows = this.message_list ? this.message_list.rows : {};
3d3531 3226
188247 3227     if (typeof uids == 'string')
65070f 3228       uids = uids.split(',');
4fb6a2 3229
A 3230     for (i=0, len=uids.length; i<len; i++) {
3231       uid = uids[i];
3d3531 3232       if (rows[uid])
132aae 3233         this.set_message(uid, 'unread', false);
8fa922 3234     }
3d3531 3235   };
f52c93 3236
fb7ec5 3237   // Converts array of message UIDs to comma-separated list for use in URL
A 3238   // with select_all mode checking
3239   this.uids_to_list = function(uids)
3240   {
188247 3241     return this.select_all_mode ? '*' : (uids.length <= 1 ? uids.join(',') : uids);
fb7ec5 3242   };
8fa922 3243
1b30a7 3244   // Sets title of the delete button
A 3245   this.set_button_titles = function()
3246   {
3247     var label = 'deletemessage';
3248
3249     if (!this.env.flag_for_deletion
3250       && this.env.trash_mailbox && this.env.mailbox != this.env.trash_mailbox
3251       && (!this.env.delete_junk || !this.env.junk_mailbox || this.env.mailbox != this.env.junk_mailbox)
3252     )
3253       label = 'movemessagetotrash';
3254
3255     this.set_alttext('delete', label);
3256   };
f52c93 3257
9a5d9a 3258   // Initialize input element for list page jump
AM 3259   this.init_pagejumper = function(element)
3260   {
3261     $(element).addClass('rcpagejumper')
3262       .on('focus', function(e) {
3263         // create and display popup with page selection
3264         var i, html = '';
3265
3266         for (i = 1; i <= ref.env.pagecount; i++)
3267           html += '<li>' + i + '</li>';
3268
3269         html = '<ul class="toolbarmenu">' + html + '</ul>';
3270
3271         if (!ref.pagejump) {
3272           ref.pagejump = $('<div id="pagejump-selector" class="popupmenu"></div>')
3273             .appendTo(document.body)
3274             .on('click', 'li', function() {
3275               if (!ref.busy)
3276                 $(element).val($(this).text()).change();
3277             });
3278         }
3279
3280         if (ref.pagejump.data('count') != i)
3281           ref.pagejump.html(html);
3282
3283         ref.pagejump.attr('rel', '#' + this.id).data('count', i);
3284
3285         // display page selector
3286         ref.show_menu('pagejump-selector', true, e);
3287         $(this).keydown();
3288       })
3289       // keyboard navigation
9d49c8 3290       .on('keydown keyup click', function(e) {
9a5d9a 3291         var current, selector = $('#pagejump-selector'),
AM 3292           ul = $('ul', selector),
3293           list = $('li', ul),
3294           height = ul.height(),
3295           p = parseInt(this.value);
3296
9d49c8 3297         if (e.which != 27 && e.which != 9 && e.which != 13 && !selector.is(':visible'))
AM 3298           return ref.show_menu('pagejump-selector', true, e);
3299
9a5d9a 3300         if (e.type == 'keydown') {
AM 3301           // arrow-down
3302           if (e.which == 40) {
3303             if (list.length > p)
3304               this.value = (p += 1);
3305           }
3306           // arrow-up
3307           else if (e.which == 38) {
3308             if (p > 1 && list.length > p - 1)
3309               this.value = (p -= 1);
3310           }
3311           // enter
3312           else if (e.which == 13) {
3313             return $(this).change();
3314           }
820be4 3315           // esc, tab
AM 3316           else if (e.which == 27 || e.which == 9) {
3317             return $(element).val(ref.env.current_page);
3318           }
9a5d9a 3319         }
AM 3320
3321         $('li.selected', ul).removeClass('selected');
3322
3323         if ((current = $(list[p - 1])).length) {
3324           current.addClass('selected');
3325           $('#pagejump-selector').scrollTop(((ul.height() / list.length) * (p - 1)) - selector.height() / 2);
3326         }
3327       })
3328       .on('change', function(e) {
3329         // go to specified page
3330         var p = parseInt(this.value);
3331         if (p && p != ref.env.current_page && !ref.busy) {
3332           ref.hide_menu('pagejump-selector');
3333           ref.list_page(p);
3334         }
3335       });
3336   };
3337
3338   // Update page-jumper state on list updates
3339   this.update_pagejumper = function()
3340   {
3341     $('input.rcpagejumper').val(this.env.current_page).prop('disabled', this.env.pagecount < 2);
3342   };
3343
f52c93 3344   /*********************************************************/
T 3345   /*********       mailbox folders methods         *********/
3346   /*********************************************************/
3347
3348   this.expunge_mailbox = function(mbox)
8fa922 3349   {
c31360 3350     var lock, post_data = {_mbox: mbox};
8fa922 3351
f52c93 3352     // lock interface if it's the active mailbox
8fa922 3353     if (mbox == this.env.mailbox) {
b7fd98 3354       lock = this.set_busy(true, 'loading');
c31360 3355       post_data._reload = 1;
b7fd98 3356       if (this.env.search_request)
c31360 3357         post_data._search = this.env.search_request;
b7fd98 3358     }
f52c93 3359
T 3360     // send request to server
c31360 3361     this.http_post('expunge', post_data, lock);
8fa922 3362   };
f52c93 3363
T 3364   this.purge_mailbox = function(mbox)
8fa922 3365   {
c31360 3366     var lock, post_data = {_mbox: mbox};
8fa922 3367
f52c93 3368     if (!confirm(this.get_label('purgefolderconfirm')))
T 3369       return false;
8fa922 3370
f52c93 3371     // lock interface if it's the active mailbox
8fa922 3372     if (mbox == this.env.mailbox) {
ad334a 3373        lock = this.set_busy(true, 'loading');
c31360 3374        post_data._reload = 1;
8fa922 3375      }
f52c93 3376
T 3377     // send request to server
c31360 3378     this.http_post('purge', post_data, lock);
8fa922 3379   };
f52c93 3380
T 3381   // test if purge command is allowed
3382   this.purge_mailbox_test = function()
3383   {
8f8e26 3384     return (this.env.exists && (
AM 3385       this.env.mailbox == this.env.trash_mailbox
3386       || this.env.mailbox == this.env.junk_mailbox
6a9144 3387       || this.env.mailbox.startsWith(this.env.trash_mailbox + this.env.delimiter)
AM 3388       || this.env.mailbox.startsWith(this.env.junk_mailbox + this.env.delimiter)
8f8e26 3389     ));
f52c93 3390   };
T 3391
8fa922 3392
b566ff 3393   /*********************************************************/
S 3394   /*********           login form methods          *********/
3395   /*********************************************************/
3396
3397   // handler for keyboard events on the _user field
65444b 3398   this.login_user_keyup = function(e)
b566ff 3399   {
eb7e45 3400     var key = rcube_event.get_keycode(e),
AM 3401       passwd = $('#rcmloginpwd');
b566ff 3402
S 3403     // enter
cc97ea 3404     if (key == 13 && passwd.length && !passwd.val()) {
T 3405       passwd.focus();
3406       return rcube_event.cancel(e);
b566ff 3407     }
8fa922 3408
cc97ea 3409     return true;
b566ff 3410   };
f11541 3411
4e17e6 3412
T 3413   /*********************************************************/
3414   /*********        message compose methods        *********/
3415   /*********************************************************/
8fa922 3416
271efe 3417   this.open_compose_step = function(p)
TB 3418   {
3419     var url = this.url('mail/compose', p);
3420
3421     // open new compose window
7bf6d2 3422     if (this.env.compose_extwin && !this.env.extwin) {
ece3a5 3423       this.open_window(url);
7bf6d2 3424     }
TB 3425     else {
271efe 3426       this.redirect(url);
99e27c 3427       if (this.env.extwin)
AM 3428         window.resizeTo(Math.max(this.env.popup_width, $(window).width()), $(window).height() + 24);
7bf6d2 3429     }
271efe 3430   };
TB 3431
f52c93 3432   // init message compose form: set focus and eventhandlers
T 3433   this.init_messageform = function()
3434   {
3435     if (!this.gui_objects.messageform)
3436       return false;
8fa922 3437
65e735 3438     var i, elem, pos, input_from = $("[name='_from']"),
9be483 3439       input_to = $("[name='_to']"),
A 3440       input_subject = $("input[name='_subject']"),
3441       input_message = $("[name='_message']").get(0),
3442       html_mode = $("input[name='_is_html']").val() == '1',
0213f8 3443       ac_fields = ['cc', 'bcc', 'replyto', 'followupto'],
32da69 3444       ac_props, opener_rc = this.opener();
271efe 3445
715a39 3446     // close compose step in opener
32da69 3447     if (opener_rc && opener_rc.env.action == 'compose') {
d27a4f 3448       setTimeout(function(){
TB 3449         if (opener.history.length > 1)
3450           opener.history.back();
3451         else
3452           opener_rc.redirect(opener_rc.get_task_url('mail'));
3453       }, 100);
762565 3454       this.env.opened_extwin = true;
271efe 3455     }
0213f8 3456
A 3457     // configure parallel autocompletion
3458     if (this.env.autocomplete_threads > 0) {
3459       ac_props = {
3460         threads: this.env.autocomplete_threads,
e3acfa 3461         sources: this.env.autocomplete_sources
0213f8 3462       };
A 3463     }
f52c93 3464
T 3465     // init live search events
0213f8 3466     this.init_address_input_events(input_to, ac_props);
646b64 3467     for (i in ac_fields) {
0213f8 3468       this.init_address_input_events($("[name='_"+ac_fields[i]+"']"), ac_props);
9be483 3469     }
8fa922 3470
a4c163 3471     if (!html_mode) {
0b96b1 3472       pos = this.env.top_posting ? 0 : input_message.value.length;
AM 3473
a4c163 3474       // add signature according to selected identity
09225a 3475       // if we have HTML editor, signature is added in a callback
3b944e 3476       if (input_from.prop('type') == 'select-one') {
a4c163 3477         this.change_identity(input_from[0]);
A 3478       }
0b96b1 3479
09225a 3480       // set initial cursor position
AM 3481       this.set_caret_pos(input_message, pos);
3482
0b96b1 3483       // scroll to the bottom of the textarea (#1490114)
AM 3484       if (pos) {
3485         $(input_message).scrollTop(input_message.scrollHeight);
3486       }
f52c93 3487     }
T 3488
85e60a 3489     // check for locally stored compose data
44b47d 3490     if (this.env.save_localstorage)
TB 3491       this.compose_restore_dialog(0, html_mode)
85e60a 3492
f52c93 3493     if (input_to.val() == '')
65e735 3494       elem = input_to;
f52c93 3495     else if (input_subject.val() == '')
65e735 3496       elem = input_subject;
1f019c 3497     else if (input_message)
65e735 3498       elem = input_message;
AM 3499
3500     // focus first empty element (need to be visible on IE8)
3501     $(elem).filter(':visible').focus();
1f019c 3502
A 3503     this.env.compose_focus_elem = document.activeElement;
f52c93 3504
T 3505     // get summary of all field values
3506     this.compose_field_hash(true);
8fa922 3507
f52c93 3508     // start the auto-save timer
T 3509     this.auto_save_start();
3510   };
3511
b54731 3512   this.compose_restore_dialog = function(j, html_mode)
TB 3513   {
3514     var i, key, formdata, index = this.local_storage_get_item('compose.index', []);
3515
3516     var show_next = function(i) {
3517       if (++i < index.length)
3518         ref.compose_restore_dialog(i, html_mode)
3519     }
3520
3521     for (i = j || 0; i < index.length; i++) {
3522       key = index[i];
3523       formdata = this.local_storage_get_item('compose.' + key, null, true);
3524       if (!formdata) {
3525         continue;
3526       }
3527       // restore saved copy of current compose_id
3528       if (formdata.changed && key == this.env.compose_id) {
3529         this.restore_compose_form(key, html_mode);
3530         break;
3531       }
3532       // skip records from 'other' drafts
3533       if (this.env.draft_id && formdata.draft_id && formdata.draft_id != this.env.draft_id) {
3534         continue;
3535       }
3536       // skip records on reply
3537       if (this.env.reply_msgid && formdata.reply_msgid != this.env.reply_msgid) {
3538         continue;
3539       }
3540       // show dialog asking to restore the message
3541       if (formdata.changed && formdata.session != this.env.session_id) {
3542         this.show_popup_dialog(
3543           this.get_label('restoresavedcomposedata')
3544             .replace('$date', new Date(formdata.changed).toLocaleString())
3545             .replace('$subject', formdata._subject)
3546             .replace(/\n/g, '<br/>'),
3547           this.get_label('restoremessage'),
3548           [{
3549             text: this.get_label('restore'),
630d08 3550             'class': 'mainaction',
b54731 3551             click: function(){
TB 3552               ref.restore_compose_form(key, html_mode);
3553               ref.remove_compose_data(key);  // remove old copy
3554               ref.save_compose_form_local();  // save under current compose_id
3555               $(this).dialog('close');
3556             }
3557           },
3558           {
3559             text: this.get_label('delete'),
630d08 3560             'class': 'delete',
b54731 3561             click: function(){
TB 3562               ref.remove_compose_data(key);
3563               $(this).dialog('close');
3564               show_next(i);
3565             }
3566           },
3567           {
3568             text: this.get_label('ignore'),
3569             click: function(){
3570               $(this).dialog('close');
3571               show_next(i);
3572             }
3573           }]
3574         );
3575         break;
3576       }
3577     }
3578   }
3579
0213f8 3580   this.init_address_input_events = function(obj, props)
f52c93 3581   {
62c861 3582     this.env.recipients_delimiter = this.env.recipients_separator + ' ';
T 3583
184a11 3584     obj.keydown(function(e) { return ref.ksearch_keydown(e, this, props); })
6d3ab6 3585       .attr({ 'autocomplete': 'off', 'aria-autocomplete': 'list', 'aria-expanded': 'false', 'role': 'combobox' });
f52c93 3586   };
a945da 3587
c5c8e7 3588   this.submit_messageform = function(draft, saveonly)
b169de 3589   {
AM 3590     var form = this.gui_objects.messageform;
3591
3592     if (!form)
3593       return;
3594
c5c8e7 3595     // the message has been sent but not saved, ask the user what to do
AM 3596     if (!saveonly && this.env.is_sent) {
3597       return this.show_popup_dialog(this.get_label('messageissent'), '',
3598         [{
3599           text: this.get_label('save'),
3600           'class': 'mainaction',
3601           click: function() {
3602             ref.submit_messageform(false, true);
3603             $(this).dialog('close');
3604           }
3605         },
3606         {
3607           text: this.get_label('cancel'),
3608           click: function() {
3609             $(this).dialog('close');
3610           }
3611         }]
3612       );
3613     }
3614
b169de 3615     // all checks passed, send message
c5c8e7 3616     var msgid = this.set_busy(true, draft || saveonly ? 'savingmessage' : 'sendingmessage'),
b169de 3617       lang = this.spellcheck_lang(),
AM 3618       files = [];
3619
3620     // send files list
3621     $('li', this.gui_objects.attachmentlist).each(function() { files.push(this.id.replace(/^rcmfile/, '')); });
3622     $('input[name="_attachments"]', form).val(files.join());
3623
3624     form.target = 'savetarget';
3625     form._draft.value = draft ? '1' : '';
3626     form.action = this.add_url(form.action, '_unlock', msgid);
3627     form.action = this.add_url(form.action, '_lang', lang);
7e7e45 3628     form.action = this.add_url(form.action, '_framed', 1);
c5c8e7 3629
AM 3630     if (saveonly) {
3631       form.action = this.add_url(form.action, '_saveonly', 1);
3632     }
72e24b 3633
TB 3634     // register timer to notify about connection timeout
3635     this.submit_timer = setTimeout(function(){
3636       ref.set_busy(false, null, msgid);
3637       ref.display_message(ref.get_label('requesttimedout'), 'error');
3638     }, this.env.request_timeout * 1000);
3639
b169de 3640     form.submit();
AM 3641   };
3642
635722 3643   this.compose_recipient_select = function(list)
eeb73c 3644   {
86552f 3645     var id, n, recipients = 0;
TB 3646     for (n=0; n < list.selection.length; n++) {
3647       id = list.selection[n];
3648       if (this.env.contactdata[id])
3649         recipients++;
3650     }
3651     this.enable_command('add-recipient', recipients);
eeb73c 3652   };
T 3653
3654   this.compose_add_recipient = function(field)
3655   {
b4cbed 3656     // find last focused field name
AM 3657     if (!field) {
3658       field = $(this.env.focused_field).filter(':visible');
3659       field = field.length ? field.attr('id').replace('_', '') : 'to';
3660     }
3661
1dfa85 3662     var recipients = [], input = $('#_'+field), delim = this.env.recipients_delimiter;
a945da 3663
eeb73c 3664     if (this.contact_list && this.contact_list.selection.length) {
T 3665       for (var id, n=0; n < this.contact_list.selection.length; n++) {
3666         id = this.contact_list.selection[n];
3667         if (id && this.env.contactdata[id]) {
3668           recipients.push(this.env.contactdata[id]);
3669
3670           // group is added, expand it
3671           if (id.charAt(0) == 'E' && this.env.contactdata[id].indexOf('@') < 0 && input.length) {
3672             var gid = id.substr(1);
3673             this.group2expand[gid] = { name:this.env.contactdata[id], input:input.get(0) };
c31360 3674             this.http_request('group-expand', {_source: this.env.source, _gid: gid}, false);
eeb73c 3675           }
T 3676         }
3677       }
3678     }
3679
3680     if (recipients.length && input.length) {
1dfa85 3681       var oldval = input.val(), rx = new RegExp(RegExp.escape(delim) + '\\s*$');
AM 3682       if (oldval && !rx.test(oldval))
3683         oldval += delim + ' ';
3684       input.val(oldval + recipients.join(delim + ' ') + delim + ' ');
eeb73c 3685       this.triggerEvent('add-recipient', { field:field, recipients:recipients });
T 3686     }
d58c39 3687
TB 3688     return recipients.length;
eeb73c 3689   };
f52c93 3690
977a29 3691   // checks the input fields before sending a message
ac9ba4 3692   this.check_compose_input = function(cmd)
f52c93 3693   {
977a29 3694     // check input fields
646b64 3695     var input_to = $("[name='_to']"),
736790 3696       input_cc = $("[name='_cc']"),
A 3697       input_bcc = $("[name='_bcc']"),
3698       input_from = $("[name='_from']"),
646b64 3699       input_subject = $("[name='_subject']");
977a29 3700
fd51e0 3701     // check sender (if have no identities)
02e079 3702     if (input_from.prop('type') == 'text' && !rcube_check_email(input_from.val(), true)) {
fd51e0 3703       alert(this.get_label('nosenderwarning'));
A 3704       input_from.focus();
3705       return false;
a4c163 3706     }
fd51e0 3707
977a29 3708     // check for empty recipient
cc97ea 3709     var recipients = input_to.val() ? input_to.val() : (input_cc.val() ? input_cc.val() : input_bcc.val());
a4c163 3710     if (!rcube_check_email(recipients.replace(/^\s+/, '').replace(/[\s,;]+$/, ''), true)) {
977a29 3711       alert(this.get_label('norecipientwarning'));
T 3712       input_to.focus();
3713       return false;
a4c163 3714     }
977a29 3715
ebf872 3716     // check if all files has been uploaded
01ffe0 3717     for (var key in this.env.attachments) {
d8cf6d 3718       if (typeof this.env.attachments[key] === 'object' && !this.env.attachments[key].complete) {
01ffe0 3719         alert(this.get_label('notuploadedwarning'));
T 3720         return false;
3721       }
ebf872 3722     }
8fa922 3723
977a29 3724     // display localized warning for missing subject
f52c93 3725     if (input_subject.val() == '') {
646b64 3726       var buttons = {},
AM 3727         myprompt = $('<div class="prompt">').html('<div class="message">' + this.get_label('nosubjectwarning') + '</div>')
3728           .appendTo(document.body),
3729         prompt_value = $('<input>').attr({type: 'text', size: 30}).val(this.get_label('nosubject'))
db7dcf 3730           .appendTo(myprompt),
AM 3731         save_func = function() {
3732           input_subject.val(prompt_value.val());
3733           myprompt.dialog('close');
3734           ref.command(cmd, { nocheck:true });  // repeat command which triggered this
3735         };
977a29 3736
db7dcf 3737       buttons[this.get_label('sendmessage')] = function() {
AM 3738         save_func($(this));
3739       };
3740       buttons[this.get_label('cancel')] = function() {
977a29 3741         input_subject.focus();
ac9ba4 3742         $(this).dialog('close');
T 3743       };
3744
3745       myprompt.dialog({
3746         modal: true,
3747         resizable: false,
3748         buttons: buttons,
db7dcf 3749         close: function(event, ui) { $(this).remove(); }
ac9ba4 3750       });
646b64 3751
db7dcf 3752       prompt_value.select().keydown(function(e) {
AM 3753         if (e.which == 13) save_func();
3754       });
3755
ac9ba4 3756       return false;
f52c93 3757     }
977a29 3758
736790 3759     // check for empty body
646b64 3760     if (!this.editor.get_content() && !confirm(this.get_label('nobodywarning'))) {
AM 3761       this.editor.focus();
736790 3762       return false;
A 3763     }
646b64 3764
AM 3765     // move body from html editor to textarea (just to be sure, #1485860)
3766     this.editor.save();
3940ba 3767
A 3768     return true;
3769   };
3770
646b64 3771   this.toggle_editor = function(props, obj, e)
3940ba 3772   {
646b64 3773     // @todo: this should work also with many editors on page
7d3be1 3774     var result = this.editor.toggle(props.html, props.noconvert || false);
TB 3775
3776     // satisfy the expectations of aftertoggle-editor event subscribers
3777     props.mode = props.html ? 'html' : 'plain';
4be86f 3778
646b64 3779     if (!result && e) {
AM 3780       // fix selector value if operation failed
7d3be1 3781       props.mode = props.html ? 'plain' : 'html';
TB 3782       $(e.target).filter('select').val(props.mode);
59b765 3783     }
AM 3784
4f3f3b 3785     if (result) {
AM 3786       // update internal format flag
3787       $("input[name='_is_html']").val(props.html ? 1 : 0);
3788     }
3789
59b765 3790     return result;
f52c93 3791   };
41fa0b 3792
0b1de8 3793   this.insert_response = function(key)
TB 3794   {
3795     var insert = this.env.textresponses[key] ? this.env.textresponses[key].text : null;
646b64 3796
0b1de8 3797     if (!insert)
TB 3798       return false;
3799
646b64 3800     this.editor.replace(insert);
0b1de8 3801   };
TB 3802
3803   /**
3804    * Open the dialog to save a new canned response
3805    */
3806   this.save_response = function()
3807   {
3808     // show dialog to enter a name and to modify the text to be saved
45bfde 3809     var buttons = {}, text = this.editor.get_content({selection: true, format: 'text', nosig: true}),
0b1de8 3810       html = '<form class="propform">' +
TB 3811       '<div class="prop block"><label>' + this.get_label('responsename') + '</label>' +
3812       '<input type="text" name="name" id="ffresponsename" size="40" /></div>' +
3813       '<div class="prop block"><label>' + this.get_label('responsetext') + '</label>' +
3814       '<textarea name="text" id="ffresponsetext" cols="40" rows="8"></textarea></div>' +
3815       '</form>';
3816
3817     buttons[this.gettext('save')] = function(e) {
3818       var name = $('#ffresponsename').val(),
3819         text = $('#ffresponsetext').val();
3820
3821       if (!text) {
3822         $('#ffresponsetext').select();
3823         return false;
3824       }
3825       if (!name)
3826         name = text.substring(0,40);
3827
3828       var lock = ref.display_message(ref.get_label('savingresponse'), 'loading');
3829       ref.http_post('settings/responses', { _insert:1, _name:name, _text:text }, lock);
3830       $(this).dialog('close');
3831     };
3832
3833     buttons[this.gettext('cancel')] = function() {
3834       $(this).dialog('close');
3835     };
3836
630d08 3837     this.show_popup_dialog(html, this.gettext('newresponse'), buttons, {button_classes: ['mainaction']});
0b1de8 3838
TB 3839     $('#ffresponsetext').val(text);
3840     $('#ffresponsename').select();
3841   };
3842
3843   this.add_response_item = function(response)
3844   {
3845     var key = response.key;
3846     this.env.textresponses[key] = response;
3847
3848     // append to responses list
3849     if (this.gui_objects.responseslist) {
3850       var li = $('<li>').appendTo(this.gui_objects.responseslist);
3851       $('<a>').addClass('insertresponse active')
3852         .attr('href', '#')
3853         .attr('rel', key)
b2992d 3854         .attr('tabindex', '0')
2d6242 3855         .html(this.quote_html(response.name))
0b1de8 3856         .appendTo(li)
TB 3857         .mousedown(function(e){
3858           return rcube_event.cancel(e);
3859         })
ea0866 3860         .bind('mouseup keypress', function(e){
TB 3861           if (e.type == 'mouseup' || rcube_event.get_keycode(e) == 13) {
3862             ref.command('insert-response', $(this).attr('rel'));
3863             $(document.body).trigger('mouseup');  // hides the menu
3864             return rcube_event.cancel(e);
3865           }
0b1de8 3866         });
TB 3867     }
977a29 3868   };
41fa0b 3869
0ce212 3870   this.edit_responses = function()
TB 3871   {
0933d6 3872     // TODO: implement inline editing of responses
0ce212 3873   };
TB 3874
3875   this.delete_response = function(key)
3876   {
3877     if (!key && this.responses_list) {
3878       var selection = this.responses_list.get_selection();
3879       key = selection[0];
3880     }
3881
3882     // submit delete request
3883     if (key && confirm(this.get_label('deleteresponseconfirm'))) {
3884       this.http_post('settings/delete-response', { _key: key }, false);
3885     }
3886   };
3887
646b64 3888   // updates spellchecker buttons on state change
4be86f 3889   this.spellcheck_state = function()
f52c93 3890   {
646b64 3891     var active = this.editor.spellcheck_state();
41fa0b 3892
a5fe9a 3893     $.each(this.buttons.spellcheck || [], function(i, v) {
AM 3894       $('#' + v.id)[active ? 'addClass' : 'removeClass']('selected');
3895     });
4be86f 3896
A 3897     return active;
a4c163 3898   };
e170b4 3899
644e3a 3900   // get selected language
A 3901   this.spellcheck_lang = function()
3902   {
646b64 3903     return this.editor.get_language();
4be86f 3904   };
A 3905
3906   this.spellcheck_lang_set = function(lang)
3907   {
646b64 3908     this.editor.set_language(lang);
644e3a 3909   };
A 3910
340546 3911   // resume spellchecking, highlight provided mispellings without new ajax request
646b64 3912   this.spellcheck_resume = function(data)
340546 3913   {
646b64 3914     this.editor.spellcheck_resume(data);
AM 3915   };
340546 3916
f11541 3917   this.set_draft_id = function(id)
a4c163 3918   {
10936f 3919     if (id && id != this.env.draft_id) {
5a8473 3920       var filter = {task: 'mail', action: ''},
AM 3921         rc = this.opener(false, filter) || this.opener(true, filter);
3922
3923       // refresh the drafts folder in the opener window
3924       if (rc && rc.env.mailbox == this.env.drafts_mailbox)
3925         rc.command('checkmail');
10936f 3926
AM 3927       this.env.draft_id = id;
3928       $("input[name='_draft_saveid']").val(id);
3929
d27a4f 3930       // reset history of hidden iframe used for saving draft (#1489643)
467374 3931       // but don't do this on timer-triggered draft-autosaving (#1489789)
TB 3932       if (window.frames['savetarget'] && window.frames['savetarget'].history && !this.draft_autosave_submit) {
d27a4f 3933         window.frames['savetarget'].history.back();
TB 3934       }
467374 3935
TB 3936       this.draft_autosave_submit = false;
723f4e 3937     }
90dc9b 3938
TB 3939     // always remove local copy upon saving as draft
3940     this.remove_compose_data(this.env.compose_id);
7e7e45 3941     this.compose_skip_unsavedcheck = false;
a4c163 3942   };
f11541 3943
f0f98f 3944   this.auto_save_start = function()
a4c163 3945   {
7d3d62 3946     if (this.env.draft_autosave) {
467374 3947       this.draft_autosave_submit = false;
TB 3948       this.save_timer = setTimeout(function(){
3949           ref.draft_autosave_submit = true;  // set auto-saved flag (#1489789)
3950           ref.command("savedraft");
3951       }, this.env.draft_autosave * 1000);
7d3d62 3952     }
85e60a 3953
8c7492 3954     // save compose form content to local storage every 5 seconds
44b47d 3955     if (!this.local_save_timer && window.localStorage && this.env.save_localstorage) {
8c7492 3956       // track typing activity and only save on changes
TB 3957       this.compose_type_activity = this.compose_type_activity_last = 0;
3958       $(document).bind('keypress', function(e){ ref.compose_type_activity++; });
3959
3960       this.local_save_timer = setInterval(function(){
3961         if (ref.compose_type_activity > ref.compose_type_activity_last) {
3962           ref.save_compose_form_local();
3963           ref.compose_type_activity_last = ref.compose_type_activity;
3964         }
3965       }, 5000);
7e7e45 3966
718573 3967       $(window).on('unload', function() {
7e7e45 3968         // remove copy from local storage if compose screen is left after warning
TB 3969         if (!ref.env.server_error)
3970           ref.remove_compose_data(ref.env.compose_id);
3971       });
3972     }
3973
3974     // check for unsaved changes before leaving the compose page
3975     if (!window.onbeforeunload) {
3976       window.onbeforeunload = function() {
3977         if (!ref.compose_skip_unsavedcheck && ref.cmp_hash != ref.compose_field_hash()) {
3978           return ref.get_label('notsentwarning');
3979         }
3980       };
8c7492 3981     }
4b9efb 3982
S 3983     // Unlock interface now that saving is complete
3984     this.busy = false;
a4c163 3985   };
41fa0b 3986
f11541 3987   this.compose_field_hash = function(save)
a4c163 3988   {
977a29 3989     // check input fields
646b64 3990     var i, id, val, str = '', hash_fields = ['to', 'cc', 'bcc', 'subject'];
8fa922 3991
390959 3992     for (i=0; i<hash_fields.length; i++)
A 3993       if (val = $('[name="_' + hash_fields[i] + '"]').val())
3994         str += val + ':';
8fa922 3995
45bfde 3996     str += this.editor.get_content({refresh: false});
b4d940 3997
A 3998     if (this.env.attachments)
10a397 3999       for (id in this.env.attachments)
AM 4000         str += id;
b4d940 4001
f11541 4002     if (save)
T 4003       this.cmp_hash = str;
b4d940 4004
977a29 4005     return str;
a4c163 4006   };
85e60a 4007
TB 4008   // store the contents of the compose form to localstorage
4009   this.save_compose_form_local = function()
4010   {
44b47d 4011     // feature is disabled
TB 4012     if (!this.env.save_localstorage)
4013       return;
4014
85e60a 4015     var formdata = { session:this.env.session_id, changed:new Date().getTime() },
TB 4016       ed, empty = true;
4017
4018     // get fresh content from editor
646b64 4019     this.editor.save();
85e60a 4020
ceb2a3 4021     if (this.env.draft_id) {
TB 4022       formdata.draft_id = this.env.draft_id;
4023     }
90dc9b 4024     if (this.env.reply_msgid) {
TB 4025       formdata.reply_msgid = this.env.reply_msgid;
4026     }
ceb2a3 4027
303e21 4028     $('input, select, textarea', this.gui_objects.messageform).each(function(i, elem) {
85e60a 4029       switch (elem.tagName.toLowerCase()) {
TB 4030         case 'input':
4031           if (elem.type == 'button' || elem.type == 'submit' || (elem.type == 'hidden' && elem.name != '_is_html')) {
4032             break;
4033           }
b7fb20 4034           formdata[elem.name] = elem.type != 'checkbox' || elem.checked ? $(elem).val() : '';
85e60a 4035
TB 4036           if (formdata[elem.name] != '' && elem.type != 'hidden')
4037             empty = false;
4038           break;
4039
4040         case 'select':
4041           formdata[elem.name] = $('option:checked', elem).val();
4042           break;
4043
4044         default:
4045           formdata[elem.name] = $(elem).val();
8c7492 4046           if (formdata[elem.name] != '')
TB 4047             empty = false;
85e60a 4048       }
TB 4049     });
4050
b0b9cf 4051     if (!empty) {
85e60a 4052       var index = this.local_storage_get_item('compose.index', []),
TB 4053         key = this.env.compose_id;
4054
b0b9cf 4055       if ($.inArray(key, index) < 0) {
AM 4056         index.push(key);
4057       }
4058
4059       this.local_storage_set_item('compose.' + key, formdata, true);
4060       this.local_storage_set_item('compose.index', index);
85e60a 4061     }
TB 4062   };
4063
4064   // write stored compose data back to form
4065   this.restore_compose_form = function(key, html_mode)
4066   {
4067     var ed, formdata = this.local_storage_get_item('compose.' + key, true);
4068
4069     if (formdata && typeof formdata == 'object') {
303e21 4070       $.each(formdata, function(k, value) {
85e60a 4071         if (k[0] == '_') {
TB 4072           var elem = $("*[name='"+k+"']");
4073           if (elem[0] && elem[0].type == 'checkbox') {
4074             elem.prop('checked', value != '');
4075           }
4076           else {
4077             elem.val(value);
4078           }
4079         }
4080       });
4081
4082       // initialize HTML editor
646b64 4083       if ((formdata._is_html == '1' && !html_mode) || (formdata._is_html != '1' && html_mode)) {
7d3be1 4084         this.command('toggle-editor', {id: this.env.composebody, html: !html_mode, noconvert: true});
85e60a 4085       }
TB 4086     }
4087   };
4088
4089   // remove stored compose data from localStorage
4090   this.remove_compose_data = function(key)
4091   {
b0b9cf 4092     var index = this.local_storage_get_item('compose.index', []);
85e60a 4093
b0b9cf 4094     if ($.inArray(key, index) >= 0) {
AM 4095       this.local_storage_remove_item('compose.' + key);
4096       this.local_storage_set_item('compose.index', $.grep(index, function(val,i) { return val != key; }));
85e60a 4097     }
TB 4098   };
4099
4100   // clear all stored compose data of this user
4101   this.clear_compose_data = function()
4102   {
b0b9cf 4103     var i, index = this.local_storage_get_item('compose.index', []);
85e60a 4104
b0b9cf 4105     for (i=0; i < index.length; i++) {
AM 4106       this.local_storage_remove_item('compose.' + index[i]);
85e60a 4107     }
b0b9cf 4108
AM 4109     this.local_storage_remove_item('compose.index');
a5fe9a 4110   };
85e60a 4111
50f56d 4112   this.change_identity = function(obj, show_sig)
655bd9 4113   {
1cded8 4114     if (!obj || !obj.options)
T 4115       return false;
4116
50f56d 4117     if (!show_sig)
A 4118       show_sig = this.env.show_sig;
4119
e0496f 4120     var id = obj.options[obj.selectedIndex].value,
TB 4121       sig = this.env.identity,
4122       delim = this.env.recipients_separator,
4123       rx_delim = RegExp.escape(delim);
4124
4125     // enable manual signature insert
4126     if (this.env.signatures && this.env.signatures[id]) {
4127       this.enable_command('insert-sig', true);
4128       this.env.compose_commands.push('insert-sig');
4129     }
4130     else
4131       this.enable_command('insert-sig', false);
4132
3b944e 4133     // first function execution
AM 4134     if (!this.env.identities_initialized) {
4135       this.env.identities_initialized = true;
4136       if (this.env.show_sig_later)
4137         this.env.show_sig = true;
4138       if (this.env.opened_extwin)
4139         return;
4140     }
15482b 4141
AM 4142     // update reply-to/bcc fields with addresses defined in identities
be6a09 4143     $.each(['replyto', 'bcc'], function() {
AM 4144       var rx, key = this,
4145         old_val = sig && ref.env.identities[sig] ? ref.env.identities[sig][key] : '',
4146         new_val = id && ref.env.identities[id] ? ref.env.identities[id][key] : '',
15482b 4147         input = $('[name="_'+key+'"]'), input_val = input.val();
AM 4148
4149       // remove old address(es)
4150       if (old_val && input_val) {
4151         rx = new RegExp('\\s*' + RegExp.escape(old_val) + '\\s*');
4152         input_val = input_val.replace(rx, '');
4153       }
4154
4155       // cleanup
8deae9 4156       rx = new RegExp(rx_delim + '\\s*' + rx_delim, 'g');
6789bf 4157       input_val = String(input_val).replace(rx, delim);
8deae9 4158       rx = new RegExp('^[\\s' + rx_delim + ']+');
AM 4159       input_val = input_val.replace(rx, '');
15482b 4160
AM 4161       // add new address(es)
8deae9 4162       if (new_val && input_val.indexOf(new_val) == -1 && input_val.indexOf(new_val.replace(/"/g, '')) == -1) {
AM 4163         if (input_val) {
4164           rx = new RegExp('[' + rx_delim + '\\s]+$')
4165           input_val = input_val.replace(rx, '') + delim + ' ';
4166         }
4167
15482b 4168         input_val += new_val + delim + ' ';
AM 4169       }
4170
4171       if (old_val || new_val)
4172         input.val(input_val).change();
be6a09 4173     });
50f56d 4174
646b64 4175     this.editor.change_signature(id, show_sig);
1cded8 4176     this.env.identity = id;
af61b9 4177     this.triggerEvent('change_identity');
1c5853 4178     return true;
655bd9 4179   };
4e17e6 4180
4f53ab 4181   // upload (attachment) file
42f8ab 4182   this.upload_file = function(form, action, lock)
a4c163 4183   {
4e17e6 4184     if (!form)
fb162e 4185       return;
8fa922 4186
271c5c 4187     // count files and size on capable browser
TB 4188     var size = 0, numfiles = 0;
4189
4190     $('input[type=file]', form).each(function(i, field) {
4191       var files = field.files ? field.files.length : (field.value ? 1 : 0);
4192
4193       // check file size
4194       if (field.files) {
4195         for (var i=0; i < files; i++)
4196           size += field.files[i].size;
4197       }
4198
4199       numfiles += files;
4200     });
8fa922 4201
4e17e6 4202     // create hidden iframe and post upload form
271c5c 4203     if (numfiles) {
TB 4204       if (this.env.max_filesize && this.env.filesizeerror && size > this.env.max_filesize) {
4205         this.display_message(this.env.filesizeerror, 'error');
08da30 4206         return false;
fe0cb6 4207       }
A 4208
4f53ab 4209       var frame_name = this.async_upload_form(form, action || 'upload', function(e) {
87a868 4210         var d, content = '';
ebf872 4211         try {
A 4212           if (this.contentDocument) {
87a868 4213             d = this.contentDocument;
01ffe0 4214           } else if (this.contentWindow) {
87a868 4215             d = this.contentWindow.document;
01ffe0 4216           }
f1aaca 4217           content = d.childNodes[1].innerHTML;
b649c4 4218         } catch (err) {}
ebf872 4219
f1aaca 4220         if (!content.match(/add2attachment/) && (!bw.opera || (ref.env.uploadframe && ref.env.uploadframe == e.data.ts))) {
87a868 4221           if (!content.match(/display_message/))
f1aaca 4222             ref.display_message(ref.get_label('fileuploaderror'), 'error');
AM 4223           ref.remove_from_attachment_list(e.data.ts);
42f8ab 4224
AM 4225           if (lock)
4226             ref.set_busy(false, null, lock);
ebf872 4227         }
01ffe0 4228         // Opera hack: handle double onload
T 4229         if (bw.opera)
f1aaca 4230           ref.env.uploadframe = e.data.ts;
ebf872 4231       });
8fa922 4232
3f9712 4233       // display upload indicator and cancel button
271c5c 4234       var content = '<span>' + this.get_label('uploading' + (numfiles > 1 ? 'many' : '')) + '</span>',
b649c4 4235         ts = frame_name.replace(/^rcmupload/, '');
A 4236
ae6d2d 4237       this.add2attachment_list(ts, { name:'', html:content, classname:'uploading', frame:frame_name, complete:false });
4171c5 4238
A 4239       // upload progress support
4240       if (this.env.upload_progress_time) {
4241         this.upload_progress_start('upload', ts);
4242       }
a36369 4243
TB 4244       // set reference to the form object
4245       this.gui_objects.attachmentform = form;
4246       return true;
a4c163 4247     }
A 4248   };
4e17e6 4249
T 4250   // add file name to attachment list
4251   // called from upload page
01ffe0 4252   this.add2attachment_list = function(name, att, upload_id)
T 4253   {
b21f8b 4254     if (upload_id)
AM 4255       this.triggerEvent('fileuploaded', {name: name, attachment: att, id: upload_id});
4256
3cc1af 4257     if (!this.env.attachments)
AM 4258       this.env.attachments = {};
4259
4260     if (upload_id && this.env.attachments[upload_id])
4261       delete this.env.attachments[upload_id];
4262
4263     this.env.attachments[name] = att;
4264
4e17e6 4265     if (!this.gui_objects.attachmentlist)
T 4266       return false;
ae6d2d 4267
10a397 4268     if (!att.complete && this.env.loadingicon)
AM 4269       att.html = '<img src="'+this.env.loadingicon+'" alt="" class="uploading" />' + att.html;
ae6d2d 4270
TB 4271     if (!att.complete && att.frame)
4272       att.html = '<a title="'+this.get_label('cancel')+'" onclick="return rcmail.cancel_attachment_upload(\''+name+'\', \''+att.frame+'\');" href="#cancelupload" class="cancelupload">'
9240c9 4273         + (this.env.cancelicon ? '<img src="'+this.env.cancelicon+'" alt="'+this.get_label('cancel')+'" />' : this.get_label('cancel')) + '</a>' + att.html;
8fa922 4274
2efe33 4275     var indicator, li = $('<li>');
AM 4276
4277     li.attr('id', name)
4278       .addClass(att.classname)
4279       .html(att.html)
7a5c3a 4280       .on('mouseover', function() { rcube_webmail.long_subject_title_ex(this); });
8fa922 4281
ebf872 4282     // replace indicator's li
A 4283     if (upload_id && (indicator = document.getElementById(upload_id))) {
01ffe0 4284       li.replaceAll(indicator);
T 4285     }
4286     else { // add new li
4287       li.appendTo(this.gui_objects.attachmentlist);
4288     }
8fa922 4289
9240c9 4290     // set tabindex attribute
TB 4291     var tabindex = $(this.gui_objects.attachmentlist).attr('data-tabindex') || '0';
4292     li.find('a').attr('tabindex', tabindex);
8fa922 4293
1c5853 4294     return true;
01ffe0 4295   };
4e17e6 4296
a894ba 4297   this.remove_from_attachment_list = function(name)
01ffe0 4298   {
a36369 4299     if (this.env.attachments) {
TB 4300       delete this.env.attachments[name];
4301       $('#'+name).remove();
4302     }
01ffe0 4303   };
a894ba 4304
S 4305   this.remove_attachment = function(name)
a4c163 4306   {
01ffe0 4307     if (name && this.env.attachments[name])
4591de 4308       this.http_post('remove-attachment', { _id:this.env.compose_id, _file:name });
a894ba 4309
S 4310     return true;
a4c163 4311   };
4e17e6 4312
3f9712 4313   this.cancel_attachment_upload = function(name, frame_name)
a4c163 4314   {
3f9712 4315     if (!name || !frame_name)
V 4316       return false;
4317
4318     this.remove_from_attachment_list(name);
4319     $("iframe[name='"+frame_name+"']").remove();
4320     return false;
4171c5 4321   };
A 4322
4323   this.upload_progress_start = function(action, name)
4324   {
f1aaca 4325     setTimeout(function() { ref.http_request(action, {_progress: name}); },
4171c5 4326       this.env.upload_progress_time * 1000);
A 4327   };
4328
4329   this.upload_progress_update = function(param)
4330   {
a5fe9a 4331     var elem = $('#'+param.name + ' > span');
4171c5 4332
A 4333     if (!elem.length || !param.text)
4334       return;
4335
4336     elem.text(param.text);
4337
4338     if (!param.done)
4339       this.upload_progress_start(param.action, param.name);
a4c163 4340   };
3f9712 4341
4e17e6 4342   // send remote request to add a new contact
T 4343   this.add_contact = function(value)
a4c163 4344   {
4e17e6 4345     if (value)
c31360 4346       this.http_post('addcontact', {_address: value});
8fa922 4347
1c5853 4348     return true;
a4c163 4349   };
4e17e6 4350
f11541 4351   // send remote request to search mail or contacts
30b152 4352   this.qsearch = function(value)
a4c163 4353   {
A 4354     if (value != '') {
c31360 4355       var r, lock = this.set_busy(true, 'searching'),
10a397 4356         url = this.search_params(value),
AM 4357         action = this.env.action == 'compose' && this.contact_list ? 'search-contacts' : 'search';
3cacf9 4358
e9c47c 4359       if (this.message_list)
be9d4d 4360         this.clear_message_list();
e9c47c 4361       else if (this.contact_list)
e9a9f2 4362         this.list_contacts_clear();
e9c47c 4363
c31360 4364       if (this.env.source)
A 4365         url._source = this.env.source;
4366       if (this.env.group)
4367         url._gid = this.env.group;
4368
e9c47c 4369       // reset vars
A 4370       this.env.current_page = 1;
c31360 4371
6c27c3 4372       r = this.http_request(action, url, lock);
e9c47c 4373
A 4374       this.env.qsearch = {lock: lock, request: r};
1bbf8c 4375       this.enable_command('set-listmode', this.env.threads && (this.env.search_scope || 'base') == 'base');
26b520 4376
TB 4377       return true;
e9c47c 4378     }
26b520 4379
TB 4380     return false;
31aa08 4381   };
TB 4382
4383   this.continue_search = function(request_id)
4384   {
10a397 4385     var lock = this.set_busy(true, 'stillsearching');
31aa08 4386
10a397 4387     setTimeout(function() {
31aa08 4388       var url = ref.search_params();
TB 4389       url._continue = request_id;
4390       ref.env.qsearch = { lock: lock, request: ref.http_request('search', url, lock) };
4391     }, 100);
e9c47c 4392   };
A 4393
4394   // build URL params for search
47a783 4395   this.search_params = function(search, filter)
e9c47c 4396   {
c31360 4397     var n, url = {}, mods_arr = [],
e9c47c 4398       mods = this.env.search_mods,
4a7a86 4399       scope = this.env.search_scope || 'base',
TB 4400       mbox = scope == 'all' ? '*' : this.env.mailbox;
e9c47c 4401
A 4402     if (!filter && this.gui_objects.search_filter)
4403       filter = this.gui_objects.search_filter.value;
4404
4405     if (!search && this.gui_objects.qsearchbox)
4406       search = this.gui_objects.qsearchbox.value;
4407
4408     if (filter)
c31360 4409       url._filter = filter;
e9c47c 4410
A 4411     if (search) {
c31360 4412       url._q = search;
e9c47c 4413
47a783 4414       if (mods && this.message_list)
672621 4415         mods = mods[mbox] || mods['*'];
3cacf9 4416
672621 4417       if (mods) {
AM 4418         for (n in mods)
3cacf9 4419           mods_arr.push(n);
c31360 4420         url._headers = mods_arr.join(',');
a4c163 4421       }
A 4422     }
e9c47c 4423
1bbf8c 4424     if (scope)
TB 4425       url._scope = scope;
4426     if (mbox && scope != 'all')
c31360 4427       url._mbox = mbox;
e9c47c 4428
c31360 4429     return url;
a4c163 4430   };
4647e1 4431
da1816 4432   // reset search filter
AM 4433   this.reset_search_filter = function()
4434   {
4435     this.filter_disabled = true;
4436     if (this.gui_objects.search_filter)
4437       $(this.gui_objects.search_filter).val('ALL').change();
4438     this.filter_disabled = false;
4439   };
4440
4647e1 4441   // reset quick-search form
da1816 4442   this.reset_qsearch = function(all)
a4c163 4443   {
4647e1 4444     if (this.gui_objects.qsearchbox)
T 4445       this.gui_objects.qsearchbox.value = '';
8fa922 4446
d96151 4447     if (this.env.qsearch)
A 4448       this.abort_request(this.env.qsearch);
db0408 4449
da1816 4450     if (all) {
AM 4451       this.env.search_scope = 'base';
4452       this.reset_search_filter();
4453     }
4454
db0408 4455     this.env.qsearch = null;
4647e1 4456     this.env.search_request = null;
f8e48d 4457     this.env.search_id = null;
1bbf8c 4458
TB 4459     this.enable_command('set-listmode', this.env.threads);
a4c163 4460   };
41fa0b 4461
c83535 4462   this.set_searchscope = function(scope)
TB 4463   {
4464     var old = this.env.search_scope;
4465     this.env.search_scope = scope;
4466
4467     // re-send search query with new scope
4468     if (scope != old && this.env.search_request) {
26b520 4469       if (!this.qsearch(this.gui_objects.qsearchbox.value) && this.env.search_filter && this.env.search_filter != 'ALL')
TB 4470         this.filter_mailbox(this.env.search_filter);
4471       if (scope != 'all')
c83535 4472         this.select_folder(this.env.mailbox, '', true);
TB 4473     }
4474   };
4475
4476   this.set_searchmods = function(mods)
4477   {
f1aaca 4478     var mbox = this.env.mailbox,
c83535 4479       scope = this.env.search_scope || 'base';
TB 4480
4481     if (scope == 'all')
4482       mbox = '*';
4483
4484     if (!this.env.search_mods)
4485       this.env.search_mods = {};
4486
672621 4487     if (mbox)
AM 4488       this.env.search_mods[mbox] = mods;
c83535 4489   };
TB 4490
f50a66 4491   this.is_multifolder_listing = function()
1e9a59 4492   {
10a397 4493     return this.env.multifolder_listing !== undefined ? this.env.multifolder_listing :
f50a66 4494       (this.env.search_request && (this.env.search_scope || 'base') != 'base');
10a397 4495   };
1e9a59 4496
5d42a9 4497   // action executed after mail is sent
c5c8e7 4498   this.sent_successfully = function(type, msg, folders, save_error)
a4c163 4499   {
ad334a 4500     this.display_message(msg, type);
7e7e45 4501     this.compose_skip_unsavedcheck = true;
271efe 4502
64afb5 4503     if (this.env.extwin) {
c5c8e7 4504       if (!save_error)
AM 4505         this.lock_form(this.gui_objects.messageform);
a4b6f5 4506
5d42a9 4507       var filter = {task: 'mail', action: ''},
AM 4508         rc = this.opener(false, filter) || this.opener(true, filter);
4509
723f4e 4510       if (rc) {
AM 4511         rc.display_message(msg, type);
66a549 4512         // refresh the folder where sent message was saved or replied message comes from
5d42a9 4513         if (folders && $.inArray(rc.env.mailbox, folders) >= 0) {
a4b6f5 4514           rc.command('checkmail');
66a549 4515         }
723f4e 4516       }
a4b6f5 4517
c5c8e7 4518       if (!save_error)
AM 4519         setTimeout(function() { window.close(); }, 1000);
271efe 4520     }
c5c8e7 4521     else if (!save_error) {
271efe 4522       // before redirect we need to wait some time for Chrome (#1486177)
a4b6f5 4523       setTimeout(function() { ref.list_mailbox(); }, 500);
271efe 4524     }
c5c8e7 4525
AM 4526     if (save_error)
4527       this.env.is_sent = true;
a4c163 4528   };
41fa0b 4529
4e17e6 4530
T 4531   /*********************************************************/
4532   /*********     keyboard live-search methods      *********/
4533   /*********************************************************/
4534
4535   // handler for keyboard events on address-fields
0213f8 4536   this.ksearch_keydown = function(e, obj, props)
2c8e84 4537   {
4e17e6 4538     if (this.ksearch_timer)
T 4539       clearTimeout(this.ksearch_timer);
4540
70da8c 4541     var key = rcube_event.get_keycode(e),
74f0a6 4542       mod = rcube_event.get_modifier(e);
4e17e6 4543
8fa922 4544     switch (key) {
6699a6 4545       case 38:  // arrow up
A 4546       case 40:  // arrow down
4547         if (!this.ksearch_visible())
8d9177 4548           return;
8fa922 4549
70da8c 4550         var dir = key == 38 ? 1 : 0,
99cdca 4551           highlight = document.getElementById('rcmkSearchItem' + this.ksearch_selected);
8fa922 4552
4e17e6 4553         if (!highlight)
cc97ea 4554           highlight = this.ksearch_pane.__ul.firstChild;
8fa922 4555
2c8e84 4556         if (highlight)
T 4557           this.ksearch_select(dir ? highlight.previousSibling : highlight.nextSibling);
4e17e6 4558
86958f 4559         return rcube_event.cancel(e);
4e17e6 4560
7f0388 4561       case 9:   // tab
A 4562         if (mod == SHIFT_KEY || !this.ksearch_visible()) {
4563           this.ksearch_hide();
4564           return;
4565         }
4566
0213f8 4567       case 13:  // enter
7f0388 4568         if (!this.ksearch_visible())
A 4569           return false;
4e17e6 4570
86958f 4571         // insert selected address and hide ksearch pane
T 4572         this.insert_recipient(this.ksearch_selected);
4e17e6 4573         this.ksearch_hide();
86958f 4574
T 4575         return rcube_event.cancel(e);
4e17e6 4576
T 4577       case 27:  // escape
4578         this.ksearch_hide();
bd3891 4579         return;
8fa922 4580
ca3c73 4581       case 37:  // left
A 4582       case 39:  // right
8d9177 4583         return;
8fa922 4584     }
4e17e6 4585
T 4586     // start timer
da5cad 4587     this.ksearch_timer = setTimeout(function(){ ref.ksearch_get_results(props); }, 200);
4e17e6 4588     this.ksearch_input = obj;
8fa922 4589
4e17e6 4590     return true;
2c8e84 4591   };
8fa922 4592
7f0388 4593   this.ksearch_visible = function()
A 4594   {
10a397 4595     return this.ksearch_selected !== null && this.ksearch_selected !== undefined && this.ksearch_value;
7f0388 4596   };
A 4597
2c8e84 4598   this.ksearch_select = function(node)
T 4599   {
d4d62a 4600     if (this.ksearch_pane && node) {
d0d7f4 4601       this.ksearch_pane.find('li.selected').removeClass('selected').removeAttr('aria-selected');
2c8e84 4602     }
T 4603
4604     if (node) {
6d3ab6 4605       $(node).addClass('selected').attr('aria-selected', 'true');
2c8e84 4606       this.ksearch_selected = node._rcm_id;
6d3ab6 4607       $(this.ksearch_input).attr('aria-activedescendant', 'rcmkSearchItem' + this.ksearch_selected);
2c8e84 4608     }
T 4609   };
86958f 4610
T 4611   this.insert_recipient = function(id)
4612   {
609d39 4613     if (id === null || !this.env.contacts[id] || !this.ksearch_input)
86958f 4614       return;
8fa922 4615
86958f 4616     // get cursor pos
c296b8 4617     var inp_value = this.ksearch_input.value,
A 4618       cpos = this.get_caret_pos(this.ksearch_input),
4619       p = inp_value.lastIndexOf(this.ksearch_value, cpos),
ec65ad 4620       trigger = false,
c296b8 4621       insert = '',
A 4622       // replace search string with full address
4623       pre = inp_value.substring(0, p),
4624       end = inp_value.substring(p+this.ksearch_value.length, inp_value.length);
0213f8 4625
A 4626     this.ksearch_destroy();
8fa922 4627
a61bbb 4628     // insert all members of a group
96f084 4629     if (typeof this.env.contacts[id] === 'object' && this.env.contacts[id].type == 'group' && !this.env.contacts[id].email) {
62c861 4630       insert += this.env.contacts[id].name + this.env.recipients_delimiter;
eeb73c 4631       this.group2expand[this.env.contacts[id].id] = $.extend({ input: this.ksearch_input }, this.env.contacts[id]);
c31360 4632       this.http_request('mail/group-expand', {_source: this.env.contacts[id].source, _gid: this.env.contacts[id].id}, false);
532c10 4633     }
TB 4634     else if (typeof this.env.contacts[id] === 'object' && this.env.contacts[id].name) {
4635       insert = this.env.contacts[id].name + this.env.recipients_delimiter;
4636       trigger = true;
a61bbb 4637     }
ec65ad 4638     else if (typeof this.env.contacts[id] === 'string') {
62c861 4639       insert = this.env.contacts[id] + this.env.recipients_delimiter;
ec65ad 4640       trigger = true;
T 4641     }
a61bbb 4642
86958f 4643     this.ksearch_input.value = pre + insert + end;
7b0eac 4644
86958f 4645     // set caret to insert pos
3dfb94 4646     this.set_caret_pos(this.ksearch_input, p + insert.length);
ec65ad 4647
8c7492 4648     if (trigger) {
532c10 4649       this.triggerEvent('autocomplete_insert', { field:this.ksearch_input, insert:insert, data:this.env.contacts[id] });
8c7492 4650       this.compose_type_activity++;
TB 4651     }
53d626 4652   };
8fa922 4653
53d626 4654   this.replace_group_recipients = function(id, recipients)
T 4655   {
eeb73c 4656     if (this.group2expand[id]) {
T 4657       this.group2expand[id].input.value = this.group2expand[id].input.value.replace(this.group2expand[id].name, recipients);
4658       this.triggerEvent('autocomplete_insert', { field:this.group2expand[id].input, insert:recipients });
4659       this.group2expand[id] = null;
8c7492 4660       this.compose_type_activity++;
53d626 4661     }
c0297f 4662   };
4e17e6 4663
T 4664   // address search processor
0213f8 4665   this.ksearch_get_results = function(props)
2c8e84 4666   {
4e17e6 4667     var inp_value = this.ksearch_input ? this.ksearch_input.value : null;
c296b8 4668
2c8e84 4669     if (inp_value === null)
4e17e6 4670       return;
8fa922 4671
cc97ea 4672     if (this.ksearch_pane && this.ksearch_pane.is(":visible"))
T 4673       this.ksearch_pane.hide();
4e17e6 4674
T 4675     // get string from current cursor pos to last comma
c296b8 4676     var cpos = this.get_caret_pos(this.ksearch_input),
62c861 4677       p = inp_value.lastIndexOf(this.env.recipients_separator, cpos-1),
c296b8 4678       q = inp_value.substring(p+1, cpos),
f8ca74 4679       min = this.env.autocomplete_min_length,
017c4f 4680       data = this.ksearch_data;
4e17e6 4681
T 4682     // trim query string
ef17c5 4683     q = $.trim(q);
4e17e6 4684
297a43 4685     // Don't (re-)search if the last results are still active
cea956 4686     if (q == this.ksearch_value)
ca3c73 4687       return;
8fa922 4688
48a065 4689     this.ksearch_destroy();
A 4690
2b3a8e 4691     if (q.length && q.length < min) {
5f7129 4692       if (!this.ksearch_info) {
A 4693         this.ksearch_info = this.display_message(
2b3a8e 4694           this.get_label('autocompletechars').replace('$min', min));
c296b8 4695       }
A 4696       return;
4697     }
4698
297a43 4699     var old_value = this.ksearch_value;
4e17e6 4700     this.ksearch_value = q;
241450 4701
297a43 4702     // ...string is empty
cea956 4703     if (!q.length)
A 4704       return;
297a43 4705
f8ca74 4706     // ...new search value contains old one and previous search was not finished or its result was empty
017c4f 4707     if (old_value && old_value.length && q.startsWith(old_value) && (!data || data.num <= 0) && this.env.contacts && !this.env.contacts.length)
297a43 4708       return;
0213f8 4709
017c4f 4710     var sources = props && props.sources ? props.sources : [''];
T 4711     var reqid = this.multi_thread_http_request({
4712       items: sources,
4713       threads: props && props.threads ? props.threads : 1,
4714       action:  props && props.action ? props.action : 'mail/autocomplete',
4715       postdata: { _search:q, _source:'%s' },
4716       lock: this.display_message(this.get_label('searching'), 'loading')
4717     });
0213f8 4718
017c4f 4719     this.ksearch_data = { id:reqid, sources:sources.slice(), num:sources.length };
2c8e84 4720   };
4e17e6 4721
0213f8 4722   this.ksearch_query_results = function(results, search, reqid)
2c8e84 4723   {
017c4f 4724     // trigger multi-thread http response callback
T 4725     this.multi_thread_http_response(results, reqid);
4726
5f5cf8 4727     // search stopped in meantime?
A 4728     if (!this.ksearch_value)
4729       return;
4730
aaffbe 4731     // ignore this outdated search response
5f5cf8 4732     if (this.ksearch_input && search != this.ksearch_value)
aaffbe 4733       return;
8fa922 4734
4e17e6 4735     // display search results
d0d7f4 4736     var i, id, len, ul, text, type, init,
48a065 4737       value = this.ksearch_value,
0213f8 4738       maxlen = this.env.autocomplete_max ? this.env.autocomplete_max : 15;
8fa922 4739
0213f8 4740     // create results pane if not present
A 4741     if (!this.ksearch_pane) {
4742       ul = $('<ul>');
d4d62a 4743       this.ksearch_pane = $('<div>').attr('id', 'rcmKSearchpane').attr('role', 'listbox')
0213f8 4744         .css({ position:'absolute', 'z-index':30000 }).append(ul).appendTo(document.body);
A 4745       this.ksearch_pane.__ul = ul[0];
4746     }
4e17e6 4747
0213f8 4748     ul = this.ksearch_pane.__ul;
A 4749
4750     // remove all search results or add to existing list if parallel search
4751     if (reqid && this.ksearch_pane.data('reqid') == reqid) {
4752       maxlen -= ul.childNodes.length;
4753     }
4754     else {
4755       this.ksearch_pane.data('reqid', reqid);
4756       init = 1;
4757       // reset content
4e17e6 4758       ul.innerHTML = '';
0213f8 4759       this.env.contacts = [];
A 4760       // move the results pane right under the input box
4761       var pos = $(this.ksearch_input).offset();
4762       this.ksearch_pane.css({ left:pos.left+'px', top:(pos.top + this.ksearch_input.offsetHeight)+'px', display: 'none'});
4763     }
812abd 4764
0213f8 4765     // add each result line to list
249815 4766     if (results && (len = results.length)) {
A 4767       for (i=0; i < len && maxlen > 0; i++) {
36d004 4768         text = typeof results[i] === 'object' ? (results[i].display || results[i].name) : results[i];
532c10 4769         type = typeof results[i] === 'object' ? results[i].type : '';
d0d7f4 4770         id = i + this.env.contacts.length;
TB 4771         $('<li>').attr('id', 'rcmkSearchItem' + id)
4772           .attr('role', 'option')
e833e8 4773           .html('<i class="icon"></i>' + this.quote_html(text.replace(new RegExp('('+RegExp.escape(value)+')', 'ig'), '##$1%%')).replace(/##([^%]+)%%/g, '<b>$1</b>'))
d0d7f4 4774           .addClass(type || '')
TB 4775           .appendTo(ul)
5a897b 4776           .mouseover(function() { ref.ksearch_select(this); })
AM 4777           .mouseup(function() { ref.ksearch_click(this); })
d0d7f4 4778           .get(0)._rcm_id = id;
0213f8 4779         maxlen -= 1;
2c8e84 4780       }
T 4781     }
0213f8 4782
A 4783     if (ul.childNodes.length) {
d4d62a 4784       // set the right aria-* attributes to the input field
TB 4785       $(this.ksearch_input)
4786         .attr('aria-haspopup', 'true')
4787         .attr('aria-expanded', 'true')
6d3ab6 4788         .attr('aria-owns', 'rcmKSearchpane');
TB 4789
0213f8 4790       this.ksearch_pane.show();
6d3ab6 4791
0213f8 4792       // select the first
A 4793       if (!this.env.contacts.length) {
6d3ab6 4794         this.ksearch_select($('li:first', ul).get(0));
0213f8 4795       }
A 4796     }
4797
249815 4798     if (len)
0213f8 4799       this.env.contacts = this.env.contacts.concat(results);
A 4800
017c4f 4801     if (this.ksearch_data.id == reqid)
T 4802       this.ksearch_data.num--;
2c8e84 4803   };
8fa922 4804
2c8e84 4805   this.ksearch_click = function(node)
T 4806   {
7b0eac 4807     if (this.ksearch_input)
A 4808       this.ksearch_input.focus();
4809
2c8e84 4810     this.insert_recipient(node._rcm_id);
T 4811     this.ksearch_hide();
4812   };
4e17e6 4813
2c8e84 4814   this.ksearch_blur = function()
8fa922 4815   {
4e17e6 4816     if (this.ksearch_timer)
T 4817       clearTimeout(this.ksearch_timer);
4818
4819     this.ksearch_input = null;
4820     this.ksearch_hide();
8fa922 4821   };
4e17e6 4822
T 4823   this.ksearch_hide = function()
8fa922 4824   {
4e17e6 4825     this.ksearch_selected = null;
0213f8 4826     this.ksearch_value = '';
8fa922 4827
4e17e6 4828     if (this.ksearch_pane)
cc97ea 4829       this.ksearch_pane.hide();
31f05c 4830
d4d62a 4831     $(this.ksearch_input)
TB 4832       .attr('aria-haspopup', 'false')
4833       .attr('aria-expanded', 'false')
761ee4 4834       .removeAttr('aria-activedescendant')
d4d62a 4835       .removeAttr('aria-owns');
31f05c 4836
A 4837     this.ksearch_destroy();
4838   };
4e17e6 4839
48a065 4840   // Clears autocomplete data/requests
0213f8 4841   this.ksearch_destroy = function()
A 4842   {
017c4f 4843     if (this.ksearch_data)
T 4844       this.multi_thread_request_abort(this.ksearch_data.id);
0213f8 4845
5f7129 4846     if (this.ksearch_info)
A 4847       this.hide_message(this.ksearch_info);
4848
4849     if (this.ksearch_msg)
4850       this.hide_message(this.ksearch_msg);
4851
0213f8 4852     this.ksearch_data = null;
5f7129 4853     this.ksearch_info = null;
A 4854     this.ksearch_msg = null;
48a065 4855   };
A 4856
4857
4e17e6 4858   /*********************************************************/
T 4859   /*********         address book methods          *********/
4860   /*********************************************************/
4861
6b47de 4862   this.contactlist_keypress = function(list)
8fa922 4863   {
A 4864     if (list.key_pressed == list.DELETE_KEY)
4865       this.command('delete');
4866   };
6b47de 4867
T 4868   this.contactlist_select = function(list)
8fa922 4869   {
A 4870     if (this.preview_timer)
4871       clearTimeout(this.preview_timer);
f11541 4872
2611ac 4873     var n, id, sid, contact, writable = false,
f7af22 4874       selected = list.selection.length,
ecf295 4875       source = this.env.source ? this.env.address_sources[this.env.source] : null;
A 4876
ab845c 4877     // we don't have dblclick handler here, so use 200 instead of this.dblclick_time
0a909f 4878     if (this.env.contentframe && (id = list.get_single_selection()))
da5cad 4879       this.preview_timer = setTimeout(function(){ ref.load_contact(id, 'show'); }, 200);
8fa922 4880     else if (this.env.contentframe)
A 4881       this.show_contentframe(false);
6b47de 4882
f7af22 4883     if (selected) {
6ff6be 4884       list.draggable = false;
TB 4885
ff4a92 4886       // no source = search result, we'll need to detect if any of
AM 4887       // selected contacts are in writable addressbook to enable edit/delete
4888       // we'll also need to know sources used in selection for copy
4889       // and group-addmember operations (drag&drop)
4890       this.env.selection_sources = [];
86552f 4891
TB 4892       if (source) {
4893         this.env.selection_sources.push(this.env.source);
4894       }
4895
4896       for (n in list.selection) {
4897         contact = list.data[list.selection[n]];
4898         if (!source) {
ecf295 4899           sid = String(list.selection[n]).replace(/^[^-]+-/, '');
ff4a92 4900           if (sid && this.env.address_sources[sid]) {
86552f 4901             writable = writable || (!this.env.address_sources[sid].readonly && !contact.readonly);
ff4a92 4902             this.env.selection_sources.push(sid);
ecf295 4903           }
A 4904         }
86552f 4905         else {
TB 4906           writable = writable || (!source.readonly && !contact.readonly);
4907         }
6ff6be 4908
TB 4909         if (contact._type != 'group')
4910           list.draggable = true;
ecf295 4911       }
86552f 4912
TB 4913       this.env.selection_sources = $.unique(this.env.selection_sources);
ecf295 4914     }
A 4915
1ba07f 4916     // if a group is currently selected, and there is at least one contact selected
T 4917     // thend we can enable the group-remove-selected command
f7af22 4918     this.enable_command('group-remove-selected', this.env.group && selected && writable);
AM 4919     this.enable_command('compose', this.env.group || selected);
4920     this.enable_command('print', selected == 1);
4921     this.enable_command('export-selected', 'copy', selected > 0);
ecf295 4922     this.enable_command('edit', id && writable);
f7af22 4923     this.enable_command('delete', 'move', selected && writable);
6b47de 4924
8fa922 4925     return false;
A 4926   };
6b47de 4927
a61bbb 4928   this.list_contacts = function(src, group, page)
8fa922 4929   {
24fa5d 4930     var win, folder, url = {},
765a0b 4931       refresh = src === undefined && group === undefined && page === undefined,
053e5a 4932       target = window;
8fa922 4933
bb8012 4934     if (!src)
f11541 4935       src = this.env.source;
8fa922 4936
9e2603 4937     if (refresh)
AM 4938       group = this.env.group;
4939
a61bbb 4940     if (page && this.current_page == page && src == this.env.source && group == this.env.group)
4e17e6 4941       return false;
8fa922 4942
A 4943     if (src != this.env.source) {
053e5a 4944       page = this.env.current_page = 1;
6b603d 4945       this.reset_qsearch();
8fa922 4946     }
765a0b 4947     else if (!refresh && group != this.env.group)
a61bbb 4948       page = this.env.current_page = 1;
f11541 4949
f8e48d 4950     if (this.env.search_id)
A 4951       folder = 'S'+this.env.search_id;
6c27c3 4952     else if (!this.env.search_request)
f8e48d 4953       folder = group ? 'G'+src+group : src;
A 4954
f11541 4955     this.env.source = src;
a61bbb 4956     this.env.group = group;
86552f 4957
TB 4958     // truncate groups listing stack
4959     var index = $.inArray(this.env.group, this.env.address_group_stack);
4960     if (index < 0)
4961       this.env.address_group_stack = [];
4962     else
4963       this.env.address_group_stack = this.env.address_group_stack.slice(0,index);
4964
4965     // make sure the current group is on top of the stack
4966     if (this.env.group) {
4967       this.env.address_group_stack.push(this.env.group);
4968
4969       // mark the first group on the stack as selected in the directory list
4970       folder = 'G'+src+this.env.address_group_stack[0];
4971     }
4972     else if (this.gui_objects.addresslist_title) {
4973         $(this.gui_objects.addresslist_title).html(this.get_label('contacts'));
4974     }
4975
71a522 4976     if (!this.env.search_id)
TB 4977       this.select_folder(folder, '', true);
4e17e6 4978
T 4979     // load contacts remotely
8fa922 4980     if (this.gui_objects.contactslist) {
a61bbb 4981       this.list_contacts_remote(src, group, page);
4e17e6 4982       return;
8fa922 4983     }
4e17e6 4984
24fa5d 4985     if (win = this.get_frame_window(this.env.contentframe)) {
AM 4986       target = win;
c31360 4987       url._framed = 1;
8fa922 4988     }
A 4989
a61bbb 4990     if (group)
c31360 4991       url._gid = group;
a61bbb 4992     if (page)
c31360 4993       url._page = page;
A 4994     if (src)
4995       url._source = src;
4e17e6 4996
f11541 4997     // also send search request to get the correct listing
T 4998     if (this.env.search_request)
c31360 4999       url._search = this.env.search_request;
f11541 5000
4e17e6 5001     this.set_busy(true, 'loading');
c31360 5002     this.location_href(url, target);
8fa922 5003   };
4e17e6 5004
T 5005   // send remote request to load contacts list
a61bbb 5006   this.list_contacts_remote = function(src, group, page)
8fa922 5007   {
6b47de 5008     // clear message list first
e9a9f2 5009     this.list_contacts_clear();
4e17e6 5010
T 5011     // send request to server
c31360 5012     var url = {}, lock = this.set_busy(true, 'loading');
A 5013
5014     if (src)
5015       url._source = src;
5016     if (page)
5017       url._page = page;
5018     if (group)
5019       url._gid = group;
ad334a 5020
f11541 5021     this.env.source = src;
a61bbb 5022     this.env.group = group;
8fa922 5023
6c27c3 5024     // also send search request to get the right records
f8e48d 5025     if (this.env.search_request)
c31360 5026       url._search = this.env.search_request;
f11541 5027
eeb73c 5028     this.http_request(this.env.task == 'mail' ? 'list-contacts' : 'list', url, lock);
e9a9f2 5029   };
A 5030
5031   this.list_contacts_clear = function()
5032   {
c5a5f9 5033     this.contact_list.data = {};
e9a9f2 5034     this.contact_list.clear(true);
A 5035     this.show_contentframe(false);
f7af22 5036     this.enable_command('delete', 'move', 'copy', 'print', false);
AM 5037     this.enable_command('compose', this.env.group);
8fa922 5038   };
4e17e6 5039
86552f 5040   this.set_group_prop = function(prop)
TB 5041   {
de98a8 5042     if (this.gui_objects.addresslist_title) {
TB 5043       var boxtitle = $(this.gui_objects.addresslist_title).html('');  // clear contents
5044
5045       // add link to pop back to parent group
5046       if (this.env.address_group_stack.length > 1) {
5047         $('<a href="#list">...</a>')
458af8 5048           .attr('title', this.gettext('uponelevel'))
de98a8 5049           .addClass('poplink')
TB 5050           .appendTo(boxtitle)
5051           .click(function(e){ return ref.command('popgroup','',this); });
5052         boxtitle.append('&nbsp;&raquo;&nbsp;');
5053       }
5054
2e30b2 5055       boxtitle.append($('<span>').text(prop.name));
de98a8 5056     }
86552f 5057
TB 5058     this.triggerEvent('groupupdate', prop);
5059   };
5060
4e17e6 5061   // load contact record
T 5062   this.load_contact = function(cid, action, framed)
8fa922 5063   {
c5a5f9 5064     var win, url = {}, target = window,
a0e86d 5065       rec = this.contact_list ? this.contact_list.data[cid] : null;
356a79 5066
24fa5d 5067     if (win = this.get_frame_window(this.env.contentframe)) {
c31360 5068       url._framed = 1;
24fa5d 5069       target = win;
f11541 5070       this.show_contentframe(true);
1a3c91 5071
0b3b66 5072       // load dummy content, unselect selected row(s)
AM 5073       if (!cid)
1a3c91 5074         this.contact_list.clear_selection();
86552f 5075
a0e86d 5076       this.enable_command('compose', rec && rec.email);
f7af22 5077       this.enable_command('export-selected', 'print', rec && rec._type != 'group');
8fa922 5078     }
4e17e6 5079     else if (framed)
T 5080       return false;
8fa922 5081
70da8c 5082     if (action && (cid || action == 'add') && !this.drag_active) {
356a79 5083       if (this.env.group)
c31360 5084         url._gid = this.env.group;
356a79 5085
765a0b 5086       if (this.env.search_request)
AM 5087         url._search = this.env.search_request;
5088
c31360 5089       url._action = action;
A 5090       url._source = this.env.source;
5091       url._cid = cid;
5092
5093       this.location_href(url, target, true);
8fa922 5094     }
c31360 5095
1c5853 5096     return true;
8fa922 5097   };
f11541 5098
2c77f5 5099   // add/delete member to/from the group
A 5100   this.group_member_change = function(what, cid, source, gid)
5101   {
70da8c 5102     if (what != 'add')
AM 5103       what = 'del';
5104
c31360 5105     var label = this.get_label(what == 'add' ? 'addingmember' : 'removingmember'),
A 5106       lock = this.display_message(label, 'loading'),
5107       post_data = {_cid: cid, _source: source, _gid: gid};
2c77f5 5108
c31360 5109     this.http_post('group-'+what+'members', post_data, lock);
2c77f5 5110   };
A 5111
a45f9b 5112   this.contacts_drag_menu = function(e, to)
AM 5113   {
5114     var dest = to.type == 'group' ? to.source : to.id,
5115       source = this.env.source;
5116
5117     if (!this.env.address_sources[dest] || this.env.address_sources[dest].readonly)
5118       return true;
5119
5120     // search result may contain contacts from many sources, but if there is only one...
5121     if (source == '' && this.env.selection_sources.length == 1)
5122       source = this.env.selection_sources[0];
5123
5124     if (to.type == 'group' && dest == source) {
5125       var cid = this.contact_list.get_selection().join(',');
5126       this.group_member_change('add', cid, dest, to.id);
5127       return true;
5128     }
5129     // move action is not possible, "redirect" to copy if menu wasn't requested
5130     else if (!this.commands.move && rcube_event.get_modifier(e) != SHIFT_KEY) {
5131       this.copy_contacts(to);
5132       return true;
5133     }
5134
5135     return this.drag_menu(e, to);
5136   };
5137
5138   // copy contact(s) to the specified target (group or directory)
5139   this.copy_contacts = function(to)
8fa922 5140   {
70da8c 5141     var dest = to.type == 'group' ? to.source : to.id,
ff4a92 5142       source = this.env.source,
a45f9b 5143       group = this.env.group ? this.env.group : '',
f11541 5144       cid = this.contact_list.get_selection().join(',');
T 5145
ff4a92 5146     if (!cid || !this.env.address_sources[dest] || this.env.address_sources[dest].readonly)
AM 5147       return;
c31360 5148
ff4a92 5149     // search result may contain contacts from many sources, but if there is only one...
AM 5150     if (source == '' && this.env.selection_sources.length == 1)
5151       source = this.env.selection_sources[0];
5152
5153     // tagret is a group
5154     if (to.type == 'group') {
5155       if (dest == source)
a45f9b 5156         return;
ff4a92 5157
a45f9b 5158       var lock = this.display_message(this.get_label('copyingcontact'), 'loading'),
AM 5159         post_data = {_cid: cid, _source: this.env.source, _to: dest, _togid: to.id, _gid: group};
5160
5161       this.http_post('copy', post_data, lock);
ca38db 5162     }
ff4a92 5163     // target is an addressbook
AM 5164     else if (to.id != source) {
c31360 5165       var lock = this.display_message(this.get_label('copyingcontact'), 'loading'),
eafb68 5166         post_data = {_cid: cid, _source: this.env.source, _to: to.id, _gid: group};
c31360 5167
A 5168       this.http_post('copy', post_data, lock);
ca38db 5169     }
8fa922 5170   };
4e17e6 5171
a45f9b 5172   // move contact(s) to the specified target (group or directory)
AM 5173   this.move_contacts = function(to)
8fa922 5174   {
a45f9b 5175     var dest = to.type == 'group' ? to.source : to.id,
AM 5176       source = this.env.source,
5177       group = this.env.group ? this.env.group : '';
b17539 5178
a45f9b 5179     if (!this.env.address_sources[dest] || this.env.address_sources[dest].readonly)
4e17e6 5180       return;
8fa922 5181
a45f9b 5182     // search result may contain contacts from many sources, but if there is only one...
AM 5183     if (source == '' && this.env.selection_sources.length == 1)
5184       source = this.env.selection_sources[0];
4e17e6 5185
a45f9b 5186     if (to.type == 'group') {
AM 5187       if (dest == source)
5188         return;
5189
5190       this._with_selected_contacts('move', {_to: dest, _togid: to.id});
5191     }
5192     // target is an addressbook
5193     else if (to.id != source)
5194       this._with_selected_contacts('move', {_to: to.id});
5195   };
5196
5197   // delete contact(s)
5198   this.delete_contacts = function()
5199   {
5200     var undelete = this.env.source && this.env.address_sources[this.env.source].undelete;
5201
5202     if (!undelete && !confirm(this.get_label('deletecontactconfirm')))
5203       return;
5204
5205     return this._with_selected_contacts('delete');
5206   };
5207
5208   this._with_selected_contacts = function(action, post_data)
5209   {
5210     var selection = this.contact_list ? this.contact_list.get_selection() : [];
5211
a5fe9a 5212     // exit if no contact specified or if selection is empty
a45f9b 5213     if (!selection.length && !this.env.cid)
AM 5214       return;
5215
5216     var n, a_cids = [],
5217       label = action == 'delete' ? 'contactdeleting' : 'movingcontact',
5218       lock = this.display_message(this.get_label(label), 'loading');
70da8c 5219
4e17e6 5220     if (this.env.cid)
0e7b66 5221       a_cids.push(this.env.cid);
8fa922 5222     else {
ecf295 5223       for (n=0; n<selection.length; n++) {
6b47de 5224         id = selection[n];
0e7b66 5225         a_cids.push(id);
f4f8c6 5226         this.contact_list.remove_row(id, (n == selection.length-1));
8fa922 5227       }
4e17e6 5228
T 5229       // hide content frame if we delete the currently displayed contact
f11541 5230       if (selection.length == 1)
T 5231         this.show_contentframe(false);
8fa922 5232     }
4e17e6 5233
a45f9b 5234     if (!post_data)
AM 5235       post_data = {};
5236
5237     post_data._source = this.env.source;
5238     post_data._from = this.env.action;
c31360 5239     post_data._cid = a_cids.join(',');
A 5240
8458c7 5241     if (this.env.group)
c31360 5242       post_data._gid = this.env.group;
8458c7 5243
b15568 5244     // also send search request to get the right records from the next page
ecf295 5245     if (this.env.search_request)
c31360 5246       post_data._search = this.env.search_request;
b15568 5247
4e17e6 5248     // send request to server
a45f9b 5249     this.http_post(action, post_data, lock)
8fa922 5250
1c5853 5251     return true;
8fa922 5252   };
4e17e6 5253
T 5254   // update a contact record in the list
a0e86d 5255   this.update_contact_row = function(cid, cols_arr, newcid, source, data)
cc97ea 5256   {
70da8c 5257     var list = this.contact_list;
ce988a 5258
fb6d86 5259     cid = this.html_identifier(cid);
3a24a1 5260
5db6f9 5261     // when in searching mode, concat cid with the source name
A 5262     if (!list.rows[cid]) {
70da8c 5263       cid = cid + '-' + source;
5db6f9 5264       if (newcid)
70da8c 5265         newcid = newcid + '-' + source;
5db6f9 5266     }
A 5267
517dae 5268     list.update_row(cid, cols_arr, newcid, true);
dd5472 5269     list.data[cid] = data;
cc97ea 5270   };
e83f03 5271
A 5272   // add row to contacts list
c5a5f9 5273   this.add_contact_row = function(cid, cols, classes, data)
8fa922 5274   {
c84d33 5275     if (!this.gui_objects.contactslist)
e83f03 5276       return false;
8fa922 5277
56012e 5278     var c, col, list = this.contact_list,
517dae 5279       row = { cols:[] };
8fa922 5280
70da8c 5281     row.id = 'rcmrow' + this.html_identifier(cid);
4cf42f 5282     row.className = 'contact ' + (classes || '');
8fa922 5283
c84d33 5284     if (list.in_selection(cid))
e83f03 5285       row.className += ' selected';
A 5286
5287     // add each submitted col
57863c 5288     for (c in cols) {
517dae 5289       col = {};
e83f03 5290       col.className = String(c).toLowerCase();
A 5291       col.innerHTML = cols[c];
517dae 5292       row.cols.push(col);
e83f03 5293     }
8fa922 5294
c5a5f9 5295     // store data in list member
TB 5296     list.data[cid] = data;
c84d33 5297     list.insert_row(row);
8fa922 5298
c84d33 5299     this.enable_command('export', list.rowcount > 0);
e50551 5300   };
A 5301
5302   this.init_contact_form = function()
5303   {
2611ac 5304     var col;
e50551 5305
83f707 5306     if (this.env.coltypes) {
AM 5307       this.set_photo_actions($('#ff_photo').val());
5308       for (col in this.env.coltypes)
5309         this.init_edit_field(col, null);
5310     }
e50551 5311
A 5312     $('.contactfieldgroup .row a.deletebutton').click(function() {
5313       ref.delete_edit_field(this);
5314       return false;
5315     });
5316
70da8c 5317     $('select.addfieldmenu').change(function() {
e50551 5318       ref.insert_edit_field($(this).val(), $(this).attr('rel'), this);
A 5319       this.selectedIndex = 0;
5320     });
5321
537c39 5322     // enable date pickers on date fields
T 5323     if ($.datepicker && this.env.date_format) {
5324       $.datepicker.setDefaults({
5325         dateFormat: this.env.date_format,
5326         changeMonth: true,
5327         changeYear: true,
686ff4 5328         yearRange: '-120:+10',
537c39 5329         showOtherMonths: true,
b7c35d 5330         selectOtherMonths: true
686ff4 5331 //        onSelect: function(dateText) { $(this).focus().val(dateText); }
537c39 5332       });
T 5333       $('input.datepicker').datepicker();
5334     }
5335
55a2e5 5336     // Submit search form on Enter
AM 5337     if (this.env.action == 'search')
5338       $(this.gui_objects.editform).append($('<input type="submit">').hide())
5339         .submit(function() { $('input.mainaction').click(); return false; });
8fa922 5340   };
A 5341
6c5c22 5342   // group creation dialog
edfe91 5343   this.group_create = function()
a61bbb 5344   {
6c5c22 5345     var input = $('<input>').attr('type', 'text'),
AM 5346       content = $('<label>').text(this.get_label('namex')).append(input);
5347
5348     this.show_popup_dialog(content, this.get_label('newgroup'),
5349       [{
5350         text: this.get_label('save'),
630d08 5351         'class': 'mainaction',
6c5c22 5352         click: function() {
AM 5353           var name;
5354
5355           if (name = input.val()) {
5356             ref.http_post('group-create', {_source: ref.env.source, _name: name},
5357               ref.set_busy(true, 'loading'));
5358           }
5359
5360           $(this).dialog('close');
5361         }
5362       }]
5363     );
a61bbb 5364   };
8fa922 5365
6c5c22 5366   // group rename dialog
edfe91 5367   this.group_rename = function()
3baa72 5368   {
6c5c22 5369     if (!this.env.group)
3baa72 5370       return;
8fa922 5371
6c5c22 5372     var group_name = this.env.contactgroups['G' + this.env.source + this.env.group].name,
AM 5373       input = $('<input>').attr('type', 'text').val(group_name),
5374       content = $('<label>').text(this.get_label('namex')).append(input);
3baa72 5375
6c5c22 5376     this.show_popup_dialog(content, this.get_label('grouprename'),
AM 5377       [{
5378         text: this.get_label('save'),
630d08 5379         'class': 'mainaction',
6c5c22 5380         click: function() {
AM 5381           var name;
3baa72 5382
6c5c22 5383           if ((name = input.val()) && name != group_name) {
AM 5384             ref.http_post('group-rename', {_source: ref.env.source, _gid: ref.env.group, _name: name},
5385               ref.set_busy(true, 'loading'));
5386           }
5387
5388           $(this).dialog('close');
5389         }
5390       }],
5391       {open: function() { input.select(); }}
5392     );
3baa72 5393   };
8fa922 5394
edfe91 5395   this.group_delete = function()
3baa72 5396   {
5731d6 5397     if (this.env.group && confirm(this.get_label('deletegroupconfirm'))) {
A 5398       var lock = this.set_busy(true, 'groupdeleting');
c31360 5399       this.http_post('group-delete', {_source: this.env.source, _gid: this.env.group}, lock);
5731d6 5400     }
3baa72 5401   };
8fa922 5402
3baa72 5403   // callback from server upon group-delete command
bb8012 5404   this.remove_group_item = function(prop)
3baa72 5405   {
344943 5406     var key = 'G'+prop.source+prop.id;
70da8c 5407
344943 5408     if (this.treelist.remove(key)) {
1fdb55 5409       this.triggerEvent('group_delete', { source:prop.source, id:prop.id });
3baa72 5410       delete this.env.contactfolders[key];
T 5411       delete this.env.contactgroups[key];
5412     }
8fa922 5413
bb8012 5414     this.list_contacts(prop.source, 0);
3baa72 5415   };
8fa922 5416
1ba07f 5417   //remove selected contacts from current active group
T 5418   this.group_remove_selected = function()
5419   {
10a397 5420     this.http_post('group-delmembers', {_cid: this.contact_list.selection,
c31360 5421       _source: this.env.source, _gid: this.env.group});
1ba07f 5422   };
T 5423
5424   //callback after deleting contact(s) from current group
5425   this.remove_group_contacts = function(props)
5426   {
10a397 5427     if (this.env.group !== undefined && (this.env.group === props.gid)) {
c31360 5428       var n, selection = this.contact_list.get_selection();
A 5429       for (n=0; n<selection.length; n++) {
5430         id = selection[n];
5431         this.contact_list.remove_row(id, (n == selection.length-1));
1ba07f 5432       }
T 5433     }
10a397 5434   };
1ba07f 5435
a61bbb 5436   // callback for creating a new contact group
T 5437   this.insert_contact_group = function(prop)
5438   {
0dc5bc 5439     prop.type = 'group';
70da8c 5440
1564d4 5441     var key = 'G'+prop.source+prop.id,
A 5442       link = $('<a>').attr('href', '#')
5443         .attr('rel', prop.source+':'+prop.id)
f1aaca 5444         .click(function() { return ref.command('listgroup', prop, this); })
344943 5445         .html(prop.name);
0dc5bc 5446
1564d4 5447     this.env.contactfolders[key] = this.env.contactgroups[key] = prop;
71a522 5448     this.treelist.insert({ id:key, html:link, classes:['contactgroup'] }, prop.source, 'contactgroup');
8fa922 5449
344943 5450     this.triggerEvent('group_insert', { id:prop.id, source:prop.source, name:prop.name, li:this.treelist.get_item(key) });
3baa72 5451   };
8fa922 5452
3baa72 5453   // callback for renaming a contact group
bb8012 5454   this.update_contact_group = function(prop)
3baa72 5455   {
360bd3 5456     var key = 'G'+prop.source+prop.id,
344943 5457       newnode = {};
8fa922 5458
360bd3 5459     // group ID has changed, replace link node and identifiers
344943 5460     if (prop.newid) {
1564d4 5461       var newkey = 'G'+prop.source+prop.newid,
344943 5462         newprop = $.extend({}, prop);
1564d4 5463
360bd3 5464       this.env.contactfolders[newkey] = this.env.contactfolders[key];
ec6c39 5465       this.env.contactfolders[newkey].id = prop.newid;
360bd3 5466       this.env.group = prop.newid;
d1d9fd 5467
1564d4 5468       delete this.env.contactfolders[key];
A 5469       delete this.env.contactgroups[key];
5470
360bd3 5471       newprop.id = prop.newid;
T 5472       newprop.type = 'group';
d1d9fd 5473
344943 5474       newnode.id = newkey;
TB 5475       newnode.html = $('<a>').attr('href', '#')
360bd3 5476         .attr('rel', prop.source+':'+prop.newid)
f1aaca 5477         .click(function() { return ref.command('listgroup', newprop, this); })
360bd3 5478         .html(prop.name);
T 5479     }
5480     // update displayed group name
344943 5481     else {
TB 5482       $(this.treelist.get_item(key)).children().first().html(prop.name);
5483       this.env.contactfolders[key].name = this.env.contactgroups[key].name = prop.name;
1564d4 5484     }
A 5485
344943 5486     // update list node and re-sort it
TB 5487     this.treelist.update(key, newnode, true);
1564d4 5488
344943 5489     this.triggerEvent('group_update', { id:prop.id, source:prop.source, name:prop.name, li:this.treelist.get_item(key), newid:prop.newid });
1564d4 5490   };
A 5491
62811c 5492   this.update_group_commands = function()
A 5493   {
70da8c 5494     var source = this.env.source != '' ? this.env.address_sources[this.env.source] : null,
AM 5495       supported = source && source.groups && !source.readonly;
5496
5497     this.enable_command('group-create', supported);
5498     this.enable_command('group-rename', 'group-delete', supported && this.env.group);
3baa72 5499   };
4e17e6 5500
0501b6 5501   this.init_edit_field = function(col, elem)
T 5502   {
28391b 5503     var label = this.env.coltypes[col].label;
A 5504
0501b6 5505     if (!elem)
T 5506       elem = $('.ff_' + col);
d1d9fd 5507
28391b 5508     if (label)
A 5509       elem.placeholder(label);
0501b6 5510   };
T 5511
5512   this.insert_edit_field = function(col, section, menu)
5513   {
5514     // just make pre-defined input field visible
5515     var elem = $('#ff_'+col);
5516     if (elem.length) {
5517       elem.show().focus();
491133 5518       $(menu).children('option[value="'+col+'"]').prop('disabled', true);
0501b6 5519     }
T 5520     else {
5521       var lastelem = $('.ff_'+col),
5522         appendcontainer = $('#contactsection'+section+' .contactcontroller'+col);
e9a9f2 5523
c71e95 5524       if (!appendcontainer.length) {
A 5525         var sect = $('#contactsection'+section),
5526           lastgroup = $('.contactfieldgroup', sect).last();
5527         appendcontainer = $('<fieldset>').addClass('contactfieldgroup contactcontroller'+col);
5528         if (lastgroup.length)
5529           appendcontainer.insertAfter(lastgroup);
5530         else
5531           sect.prepend(appendcontainer);
5532       }
0501b6 5533
T 5534       if (appendcontainer.length && appendcontainer.get(0).nodeName == 'FIELDSET') {
5535         var input, colprop = this.env.coltypes[col],
24e89e 5536           input_id = 'ff_' + col + (colprop.count || 0),
0501b6 5537           row = $('<div>').addClass('row'),
T 5538           cell = $('<div>').addClass('contactfieldcontent data'),
5539           label = $('<div>').addClass('contactfieldlabel label');
e9a9f2 5540
0501b6 5541         if (colprop.subtypes_select)
T 5542           label.html(colprop.subtypes_select);
5543         else
24e89e 5544           label.html('<label for="' + input_id + '">' + colprop.label + '</label>');
0501b6 5545
T 5546         var name_suffix = colprop.limit != 1 ? '[]' : '';
70da8c 5547
0501b6 5548         if (colprop.type == 'text' || colprop.type == 'date') {
T 5549           input = $('<input>')
5550             .addClass('ff_'+col)
24e89e 5551             .attr({type: 'text', name: '_'+col+name_suffix, size: colprop.size, id: input_id})
0501b6 5552             .appendTo(cell);
T 5553
5554           this.init_edit_field(col, input);
249815 5555
537c39 5556           if (colprop.type == 'date' && $.datepicker)
T 5557             input.datepicker();
0501b6 5558         }
5a7941 5559         else if (colprop.type == 'textarea') {
T 5560           input = $('<textarea>')
5561             .addClass('ff_'+col)
24e89e 5562             .attr({ name: '_'+col+name_suffix, cols:colprop.size, rows:colprop.rows, id: input_id })
5a7941 5563             .appendTo(cell);
T 5564
5565           this.init_edit_field(col, input);
5566         }
0501b6 5567         else if (colprop.type == 'composite') {
70da8c 5568           var i, childcol, cp, first, templ, cols = [], suffices = [];
AM 5569
b0c70b 5570           // read template for composite field order
T 5571           if ((templ = this.env[col+'_template'])) {
70da8c 5572             for (i=0; i < templ.length; i++) {
AM 5573               cols.push(templ[i][1]);
5574               suffices.push(templ[i][2]);
b0c70b 5575             }
T 5576           }
5577           else {  // list fields according to appearance in colprop
5578             for (childcol in colprop.childs)
5579               cols.push(childcol);
5580           }
ecf295 5581
70da8c 5582           for (i=0; i < cols.length; i++) {
b0c70b 5583             childcol = cols[i];
0501b6 5584             cp = colprop.childs[childcol];
T 5585             input = $('<input>')
5586               .addClass('ff_'+childcol)
b0c70b 5587               .attr({ type: 'text', name: '_'+childcol+name_suffix, size: cp.size })
0501b6 5588               .appendTo(cell);
b0c70b 5589             cell.append(suffices[i] || " ");
0501b6 5590             this.init_edit_field(childcol, input);
T 5591             if (!first) first = input;
5592           }
5593           input = first;  // set focus to the first of this composite fields
5594         }
5595         else if (colprop.type == 'select') {
5596           input = $('<select>')
5597             .addClass('ff_'+col)
24e89e 5598             .attr({ 'name': '_'+col+name_suffix, id: input_id })
0501b6 5599             .appendTo(cell);
e9a9f2 5600
0501b6 5601           var options = input.attr('options');
T 5602           options[options.length] = new Option('---', '');
5603           if (colprop.options)
5604             $.each(colprop.options, function(i, val){ options[options.length] = new Option(val, i); });
5605         }
5606
5607         if (input) {
5608           var delbutton = $('<a href="#del"></a>')
5609             .addClass('contactfieldbutton deletebutton')
491133 5610             .attr({title: this.get_label('delete'), rel: col})
0501b6 5611             .html(this.env.delbutton)
T 5612             .click(function(){ ref.delete_edit_field(this); return false })
5613             .appendTo(cell);
e9a9f2 5614
0501b6 5615           row.append(label).append(cell).appendTo(appendcontainer.show());
T 5616           input.first().focus();
e9a9f2 5617
0501b6 5618           // disable option if limit reached
T 5619           if (!colprop.count) colprop.count = 0;
5620           if (++colprop.count == colprop.limit && colprop.limit)
491133 5621             $(menu).children('option[value="'+col+'"]').prop('disabled', true);
0501b6 5622         }
T 5623       }
5624     }
5625   };
5626
5627   this.delete_edit_field = function(elem)
5628   {
5629     var col = $(elem).attr('rel'),
5630       colprop = this.env.coltypes[col],
5631       fieldset = $(elem).parents('fieldset.contactfieldgroup'),
5632       addmenu = fieldset.parent().find('select.addfieldmenu');
e9a9f2 5633
0501b6 5634     // just clear input but don't hide the last field
T 5635     if (--colprop.count <= 0 && colprop.visible)
5636       $(elem).parent().children('input').val('').blur();
5637     else {
5638       $(elem).parents('div.row').remove();
5639       // hide entire fieldset if no more rows
5640       if (!fieldset.children('div.row').length)
5641         fieldset.hide();
5642     }
e9a9f2 5643
0501b6 5644     // enable option in add-field selector or insert it if necessary
T 5645     if (addmenu.length) {
5646       var option = addmenu.children('option[value="'+col+'"]');
5647       if (option.length)
491133 5648         option.prop('disabled', false);
0501b6 5649       else
T 5650         option = $('<option>').attr('value', col).html(colprop.label).appendTo(addmenu);
5651       addmenu.show();
5652     }
5653   };
5654
5655   this.upload_contact_photo = function(form)
5656   {
5657     if (form && form.elements._photo.value) {
5658       this.async_upload_form(form, 'upload-photo', function(e) {
f1aaca 5659         ref.set_busy(false, null, ref.file_upload_id);
0501b6 5660       });
T 5661
5662       // display upload indicator
0be8bd 5663       this.file_upload_id = this.set_busy(true, 'uploading');
0501b6 5664     }
T 5665   };
e50551 5666
0501b6 5667   this.replace_contact_photo = function(id)
T 5668   {
5669     var img_src = id == '-del-' ? this.env.photo_placeholder :
8799df 5670       this.env.comm_path + '&_action=photo&_source=' + this.env.source + '&_cid=' + (this.env.cid || 0) + '&_photo=' + id;
e50551 5671
A 5672     this.set_photo_actions(id);
0501b6 5673     $(this.gui_objects.contactphoto).children('img').attr('src', img_src);
T 5674   };
e50551 5675
0501b6 5676   this.photo_upload_end = function()
T 5677   {
0be8bd 5678     this.set_busy(false, null, this.file_upload_id);
TB 5679     delete this.file_upload_id;
0501b6 5680   };
T 5681
e50551 5682   this.set_photo_actions = function(id)
A 5683   {
5684     var n, buttons = this.buttons['upload-photo'];
27eb27 5685     for (n=0; buttons && n < buttons.length; n++)
589385 5686       $('a#'+buttons[n].id).html(this.get_label(id == '-del-' ? 'addphoto' : 'replacephoto'));
e50551 5687
A 5688     $('#ff_photo').val(id);
5689     this.enable_command('upload-photo', this.env.coltypes.photo ? true : false);
5690     this.enable_command('delete-photo', this.env.coltypes.photo && id != '-del-');
5691   };
5692
e9a9f2 5693   // load advanced search page
A 5694   this.advanced_search = function()
5695   {
24fa5d 5696     var win, url = {_form: 1, _action: 'search'}, target = window;
e9a9f2 5697
24fa5d 5698     if (win = this.get_frame_window(this.env.contentframe)) {
c31360 5699       url._framed = 1;
24fa5d 5700       target = win;
e9a9f2 5701       this.contact_list.clear_selection();
A 5702     }
5703
c31360 5704     this.location_href(url, target, true);
e9a9f2 5705
A 5706     return true;
ecf295 5707   };
A 5708
5709   // unselect directory/group
5710   this.unselect_directory = function()
5711   {
f8e48d 5712     this.select_folder('');
A 5713     this.enable_command('search-delete', false);
5714   };
5715
5716   // callback for creating a new saved search record
5717   this.insert_saved_search = function(name, id)
5718   {
5719     var key = 'S'+id,
5720       link = $('<a>').attr('href', '#')
5721         .attr('rel', id)
f1aaca 5722         .click(function() { return ref.command('listsearch', id, this); })
f8e48d 5723         .html(name),
344943 5724       prop = { name:name, id:id };
f8e48d 5725
71a522 5726     this.savedsearchlist.insert({ id:key, html:link, classes:['contactsearch'] }, null, 'contactsearch');
3c309a 5727     this.select_folder(key,'',true);
f8e48d 5728     this.enable_command('search-delete', true);
A 5729     this.env.search_id = id;
5730
5731     this.triggerEvent('abook_search_insert', prop);
5732   };
5733
6c5c22 5734   // creates a dialog for saved search
f8e48d 5735   this.search_create = function()
A 5736   {
6c5c22 5737     var input = $('<input>').attr('type', 'text'),
AM 5738       content = $('<label>').text(this.get_label('namex')).append(input);
5739
5740     this.show_popup_dialog(content, this.get_label('searchsave'),
5741       [{
5742         text: this.get_label('save'),
630d08 5743         'class': 'mainaction',
6c5c22 5744         click: function() {
AM 5745           var name;
5746
5747           if (name = input.val()) {
5748             ref.http_post('search-create', {_search: ref.env.search_request, _name: name},
5749               ref.set_busy(true, 'loading'));
5750           }
5751
5752           $(this).dialog('close');
5753         }
5754       }]
5755     );
f8e48d 5756   };
A 5757
5758   this.search_delete = function()
5759   {
5760     if (this.env.search_request) {
5761       var lock = this.set_busy(true, 'savedsearchdeleting');
c31360 5762       this.http_post('search-delete', {_sid: this.env.search_id}, lock);
f8e48d 5763     }
A 5764   };
5765
5766   // callback from server upon search-delete command
5767   this.remove_search_item = function(id)
5768   {
5769     var li, key = 'S'+id;
71a522 5770     if (this.savedsearchlist.remove(key)) {
f8e48d 5771       this.triggerEvent('search_delete', { id:id, li:li });
A 5772     }
5773
5774     this.env.search_id = null;
5775     this.env.search_request = null;
5776     this.list_contacts_clear();
5777     this.reset_qsearch();
5778     this.enable_command('search-delete', 'search-create', false);
5779   };
5780
5781   this.listsearch = function(id)
5782   {
70da8c 5783     var lock = this.set_busy(true, 'searching');
f8e48d 5784
A 5785     if (this.contact_list) {
5786       this.list_contacts_clear();
5787     }
5788
5789     this.reset_qsearch();
71a522 5790
TB 5791     if (this.savedsearchlist) {
5792       this.treelist.select('');
5793       this.savedsearchlist.select('S'+id);
5794     }
5795     else
5796       this.select_folder('S'+id, '', true);
f8e48d 5797
A 5798     // reset vars
5799     this.env.current_page = 1;
c31360 5800     this.http_request('search', {_sid: id}, lock);
e9a9f2 5801   };
A 5802
0501b6 5803
4e17e6 5804   /*********************************************************/
T 5805   /*********        user settings methods          *********/
5806   /*********************************************************/
5807
f05834 5808   // preferences section select and load options frame
A 5809   this.section_select = function(list)
8fa922 5810   {
24fa5d 5811     var win, id = list.get_single_selection(), target = window,
c31360 5812       url = {_action: 'edit-prefs', _section: id};
8fa922 5813
f05834 5814     if (id) {
24fa5d 5815       if (win = this.get_frame_window(this.env.contentframe)) {
c31360 5816         url._framed = 1;
24fa5d 5817         target = win;
f05834 5818       }
c31360 5819       this.location_href(url, target, true);
8fa922 5820     }
f05834 5821
A 5822     return true;
8fa922 5823   };
f05834 5824
6b47de 5825   this.identity_select = function(list)
8fa922 5826   {
6b47de 5827     var id;
223ae9 5828     if (id = list.get_single_selection()) {
A 5829       this.enable_command('delete', list.rowcount > 1 && this.env.identities_level < 2);
6b47de 5830       this.load_identity(id, 'edit-identity');
223ae9 5831     }
8fa922 5832   };
4e17e6 5833
e83f03 5834   // load identity record
4e17e6 5835   this.load_identity = function(id, action)
8fa922 5836   {
223ae9 5837     if (action == 'edit-identity' && (!id || id == this.env.iid))
1c5853 5838       return false;
4e17e6 5839
24fa5d 5840     var win, target = window,
c31360 5841       url = {_action: action, _iid: id};
8fa922 5842
24fa5d 5843     if (win = this.get_frame_window(this.env.contentframe)) {
c31360 5844       url._framed = 1;
24fa5d 5845       target = win;
8fa922 5846     }
4e17e6 5847
b82fcc 5848     if (id || action == 'add-identity') {
AM 5849       this.location_href(url, target, true);
8fa922 5850     }
A 5851
1c5853 5852     return true;
8fa922 5853   };
4e17e6 5854
T 5855   this.delete_identity = function(id)
8fa922 5856   {
223ae9 5857     // exit if no identity is specified or if selection is empty
6b47de 5858     var selection = this.identity_list.get_selection();
T 5859     if (!(selection.length || this.env.iid))
4e17e6 5860       return;
8fa922 5861
4e17e6 5862     if (!id)
6b47de 5863       id = this.env.iid ? this.env.iid : selection[0];
4e17e6 5864
7c2a93 5865     // submit request with appended token
ca01e2 5866     if (id && confirm(this.get_label('deleteidentityconfirm')))
AM 5867       this.http_post('settings/delete-identity', { _iid: id }, true);
254d5e 5868   };
06c990 5869
7c2a93 5870   this.update_identity_row = function(id, name, add)
T 5871   {
517dae 5872     var list = this.identity_list,
7c2a93 5873       rid = this.html_identifier(id);
T 5874
517dae 5875     if (add) {
TB 5876       list.insert_row({ id:'rcmrow'+rid, cols:[ { className:'mail', innerHTML:name } ] });
7c2a93 5877       list.select(rid);
517dae 5878     }
TB 5879     else {
5880       list.update_row(rid, [ name ]);
7c2a93 5881     }
T 5882   };
254d5e 5883
0ce212 5884   this.update_response_row = function(response, oldkey)
TB 5885   {
5886     var list = this.responses_list;
5887
5888     if (list && oldkey) {
5889       list.update_row(oldkey, [ response.name ], response.key, true);
5890     }
5891     else if (list) {
5892       list.insert_row({ id:'rcmrow'+response.key, cols:[ { className:'name', innerHTML:response.name } ] });
5893       list.select(response.key);
5894     }
5895   };
5896
5897   this.remove_response = function(key)
5898   {
5899     var frame;
5900
5901     if (this.env.textresponses) {
5902       delete this.env.textresponses[key];
5903     }
5904
5905     if (this.responses_list) {
5906       this.responses_list.remove_row(key);
5907       if (this.env.contentframe && (frame = this.get_frame_window(this.env.contentframe))) {
5908         frame.location.href = this.env.blankpage;
5909       }
5910     }
911d4e 5911
AM 5912     this.enable_command('delete', false);
0ce212 5913   };
TB 5914
ca01e2 5915   this.remove_identity = function(id)
AM 5916   {
5917     var frame, list = this.identity_list,
5918       rid = this.html_identifier(id);
5919
5920     if (list && id) {
5921       list.remove_row(rid);
5922       if (this.env.contentframe && (frame = this.get_frame_window(this.env.contentframe))) {
5923         frame.location.href = this.env.blankpage;
5924       }
5925     }
911d4e 5926
AM 5927     this.enable_command('delete', false);
ca01e2 5928   };
AM 5929
254d5e 5930
A 5931   /*********************************************************/
5932   /*********        folder manager methods         *********/
5933   /*********************************************************/
5934
5935   this.init_subscription_list = function()
5936   {
2611ac 5937     var delim = RegExp.escape(this.env.delimiter);
04fbc5 5938
AM 5939     this.last_sub_rx = RegExp('['+delim+']?[^'+delim+']+$');
5940
c6447e 5941     this.subscription_list = new rcube_treelist_widget(this.gui_objects.subscriptionlist, {
3cb61e 5942         selectable: true,
48e340 5943         tabexit: false,
3fb36a 5944         parent_focus: true,
3cb61e 5945         id_prefix: 'rcmli',
AM 5946         id_encode: this.html_identifier_encode,
66233b 5947         id_decode: this.html_identifier_decode,
AM 5948         searchbox: '#foldersearch'
c6447e 5949     });
AM 5950
772bec 5951     this.subscription_list
c6447e 5952       .addEventListener('select', function(node) { ref.subscription_select(node.id); })
3cb61e 5953       .addEventListener('collapse', function(node) { ref.folder_collapsed(node) })
AM 5954       .addEventListener('expand', function(node) { ref.folder_collapsed(node) })
66233b 5955       .addEventListener('search', function(p) { if (p.query) ref.subscription_select(); })
3cb61e 5956       .draggable({cancel: 'li.mailbox.root'})
c6447e 5957       .droppable({
AM 5958         // @todo: find better way, accept callback is executed for every folder
5959         // on the list when dragging starts (and stops), this is slow, but
5960         // I didn't find a method to check droptarget on over event
5961         accept: function(node) {
a109d1 5962           if (!$(node).is('.mailbox'))
AM 5963             return false;
5964
3cb61e 5965           var source_folder = ref.folder_id2name($(node).attr('id')),
AM 5966             dest_folder = ref.folder_id2name(this.id),
5967             source = ref.env.subscriptionrows[source_folder],
5968             dest = ref.env.subscriptionrows[dest_folder];
04fbc5 5969
3cb61e 5970           return source && !source[2]
AM 5971             && dest_folder != source_folder.replace(ref.last_sub_rx, '')
5972             && !dest_folder.startsWith(source_folder + ref.env.delimiter);
c6447e 5973         },
AM 5974         drop: function(e, ui) {
3cb61e 5975           var source = ref.folder_id2name(ui.draggable.attr('id')),
AM 5976             dest = ref.folder_id2name(this.id);
5977
5978           ref.subscription_move_folder(source, dest);
b0dbf3 5979         }
c6447e 5980       });
3cb61e 5981   };
AM 5982
5983   this.folder_id2name = function(id)
5984   {
a109d1 5985     return id ? ref.html_identifier_decode(id.replace(/^rcmli/, '')) : null;
8fa922 5986   };
b0dbf3 5987
c6447e 5988   this.subscription_select = function(id)
8fa922 5989   {
c6447e 5990     var folder;
8fa922 5991
3cb61e 5992     if (id && id != '*' && (folder = this.env.subscriptionrows[id])) {
AM 5993       this.env.mailbox = id;
5994       this.show_folder(id);
af3c04 5995       this.enable_command('delete-folder', !folder[2]);
A 5996     }
5997     else {
5998       this.env.mailbox = null;
5999       this.show_contentframe(false);
6000       this.enable_command('delete-folder', 'purge', false);
6001     }
8fa922 6002   };
b0dbf3 6003
c6447e 6004   this.subscription_move_folder = function(from, to)
8fa922 6005   {
3cb61e 6006     if (from && to !== null && from != to && to != from.replace(this.last_sub_rx, '')) {
AM 6007       var path = from.split(this.env.delimiter),
c6447e 6008         basename = path.pop(),
3cb61e 6009         newname = to === '' || to === '*' ? basename : to + this.env.delimiter + basename;
c6447e 6010
3cb61e 6011       if (newname != from) {
AM 6012         this.http_post('rename-folder', {_folder_oldname: from, _folder_newname: newname},
c6447e 6013           this.set_busy(true, 'foldermoving'));
71cc6b 6014       }
8fa922 6015     }
A 6016   };
4e17e6 6017
24053e 6018   // tell server to create and subscribe a new mailbox
af3c04 6019   this.create_folder = function()
8fa922 6020   {
af3c04 6021     this.show_folder('', this.env.mailbox);
8fa922 6022   };
24053e 6023
T 6024   // delete a specific mailbox with all its messages
af3c04 6025   this.delete_folder = function(name)
8fa922 6026   {
3cb61e 6027     if (!name)
AM 6028       name = this.env.mailbox;
fdbb19 6029
3cb61e 6030     if (name && confirm(this.get_label('deletefolderconfirm'))) {
AM 6031       this.http_post('delete-folder', {_mbox: name}, this.set_busy(true, 'folderdeleting'));
8fa922 6032     }
A 6033   };
24053e 6034
254d5e 6035   // Add folder row to the table and initialize it
3cb61e 6036   this.add_folder_row = function (id, name, display_name, is_protected, subscribed, class_name, refrow, subfolders)
8fa922 6037   {
24053e 6038     if (!this.gui_objects.subscriptionlist)
T 6039       return false;
6040
ef4c47 6041     // reset searching
AM 6042     if (this.subscription_list.is_search()) {
6043       this.subscription_select();
6044       this.subscription_list.reset_search();
6045     }
6046
2c0d3e 6047     // disable drag-n-drop temporarily
AM 6048     this.subscription_list.draggable('destroy').droppable('destroy');
6049
3cb61e 6050     var row, n, tmp, tmp_name, rowid, collator, pos, p, parent = '',
244126 6051       folders = [], list = [], slist = [],
3cb61e 6052       list_element = $(this.gui_objects.subscriptionlist);
AM 6053       row = refrow ? refrow : $($('li', list_element).get(1)).clone(true);
8fa922 6054
3cb61e 6055     if (!row.length) {
24053e 6056       // Refresh page if we don't have a table row to clone
6b47de 6057       this.goto_url('folders');
c5c3ae 6058       return false;
8fa922 6059     }
681a59 6060
1a0343 6061     // set ID, reset css class
3cb61e 6062     row.attr({id: 'rcmli' + this.html_identifier_encode(id), 'class': class_name});
AM 6063
6064     if (!refrow || !refrow.length) {
e9ecd4 6065       // remove old data, subfolders and toggle
3cb61e 6066       $('ul,div.treetoggle', row).remove();
e9ecd4 6067       row.removeData('filtered');
3cb61e 6068     }
24053e 6069
T 6070     // set folder name
3cb61e 6071     $('a:first', row).text(display_name);
8fa922 6072
254d5e 6073     // update subscription checkbox
3cb61e 6074     $('input[name="_subscribed[]"]:first', row).val(id)
8fc0f9 6075       .prop({checked: subscribed ? true : false, disabled: is_protected ? true : false});
c5c3ae 6076
254d5e 6077     // add to folder/row-ID map
302eb2 6078     this.env.subscriptionrows[id] = [name, display_name, false];
254d5e 6079
244126 6080     // copy folders data to an array for sorting
3cb61e 6081     $.each(this.env.subscriptionrows, function(k, v) { v[3] = k; folders.push(v); });
302eb2 6082
244126 6083     try {
AM 6084       // use collator if supported (FF29, IE11, Opera15, Chrome24)
6085       collator = new Intl.Collator(this.env.locale.replace('_', '-'));
6086     }
6087     catch (e) {};
302eb2 6088
244126 6089     // sort folders
5bd871 6090     folders.sort(function(a, b) {
244126 6091       var i, f1, f2,
AM 6092         path1 = a[0].split(ref.env.delimiter),
3cb61e 6093         path2 = b[0].split(ref.env.delimiter),
AM 6094         len = path1.length;
244126 6095
3cb61e 6096       for (i=0; i<len; i++) {
244126 6097         f1 = path1[i];
AM 6098         f2 = path2[i];
6099
6100         if (f1 !== f2) {
3cb61e 6101           if (f2 === undefined)
AM 6102             return 1;
244126 6103           if (collator)
AM 6104             return collator.compare(f1, f2);
6105           else
6106             return f1 < f2 ? -1 : 1;
6107         }
3cb61e 6108         else if (i == len-1) {
AM 6109           return -1
6110         }
244126 6111       }
5bd871 6112     });
71cc6b 6113
254d5e 6114     for (n in folders) {
3cb61e 6115       p = folders[n][3];
254d5e 6116       // protected folder
A 6117       if (folders[n][2]) {
3cb61e 6118         tmp_name = p + this.env.delimiter;
18a3dc 6119         // prefix namespace cannot have subfolders (#1488349)
A 6120         if (tmp_name == this.env.prefix_ns)
6121           continue;
3cb61e 6122         slist.push(p);
18a3dc 6123         tmp = tmp_name;
254d5e 6124       }
A 6125       // protected folder's child
3cb61e 6126       else if (tmp && p.startsWith(tmp))
AM 6127         slist.push(p);
254d5e 6128       // other
A 6129       else {
3cb61e 6130         list.push(p);
254d5e 6131         tmp = null;
A 6132       }
6133     }
71cc6b 6134
T 6135     // check if subfolder of a protected folder
6136     for (n=0; n<slist.length; n++) {
3cb61e 6137       if (id.startsWith(slist[n] + this.env.delimiter))
AM 6138         rowid = slist[n];
71cc6b 6139     }
254d5e 6140
A 6141     // find folder position after sorting
71cc6b 6142     for (n=0; !rowid && n<list.length; n++) {
3cb61e 6143       if (n && list[n] == id)
AM 6144         rowid = list[n-1];
8fa922 6145     }
24053e 6146
254d5e 6147     // add row to the table
3cb61e 6148     if (rowid && (n = this.subscription_list.get_item(rowid, true))) {
AM 6149       // find parent folder
6150       if (pos = id.lastIndexOf(this.env.delimiter)) {
6151         parent = id.substring(0, pos);
6152         parent = this.subscription_list.get_item(parent, true);
6153
6154         // add required tree elements to the parent if not already there
6155         if (!$('div.treetoggle', parent).length) {
6156           $('<div>&nbsp;</div>').addClass('treetoggle collapsed').appendTo(parent);
6157         }
6158         if (!$('ul', parent).length) {
6159           $('<ul>').css('display', 'none').appendTo(parent);
6160         }
6161       }
6162
6163       if (parent && n == parent) {
6164         $('ul:first', parent).append(row);
6165       }
6166       else {
6167         while (p = $(n).parent().parent().get(0)) {
6168           if (parent && p == parent)
6169             break;
6170           if (!$(p).is('li.mailbox'))
6171             break;
6172           n = p;
6173         }
6174
6175         $(n).after(row);
6176       }
6177     }
6178     else {
c6447e 6179       list_element.append(row);
3cb61e 6180     }
AM 6181
6182     // add subfolders
6183     $.extend(this.env.subscriptionrows, subfolders || {});
b0dbf3 6184
254d5e 6185     // update list widget
3cb61e 6186     this.subscription_list.reset(true);
AM 6187     this.subscription_select();
c6447e 6188
3cb61e 6189     // expand parent
AM 6190     if (parent) {
6191       this.subscription_list.expand(this.folder_id2name(parent.id));
6192     }
254d5e 6193
e9ecd4 6194     row = row.show().get(0);
254d5e 6195     if (row.scrollIntoView)
A 6196       row.scrollIntoView();
6197
6198     return row;
8fa922 6199   };
24053e 6200
254d5e 6201   // replace an existing table row with a new folder line (with subfolders)
3cb61e 6202   this.replace_folder_row = function(oldid, id, name, display_name, is_protected, class_name)
8fa922 6203   {
7c28d4 6204     if (!this.gui_objects.subscriptionlist) {
9e9dcc 6205       if (this.is_framed()) {
AM 6206         // @FIXME: for some reason this 'parent' variable need to be prefixed with 'window.'
6207         return window.parent.rcmail.replace_folder_row(oldid, id, name, display_name, is_protected, class_name);
6208       }
c6447e 6209
254d5e 6210       return false;
7c28d4 6211     }
8fa922 6212
ef4c47 6213     // reset searching
AM 6214     if (this.subscription_list.is_search()) {
6215       this.subscription_select();
6216       this.subscription_list.reset_search();
6217     }
6218
3cb61e 6219     var subfolders = {},
AM 6220       row = this.subscription_list.get_item(oldid, true),
6221       parent = $(row).parent(),
6222       old_folder = this.env.subscriptionrows[oldid],
6223       prefix_len_id = oldid.length,
6224       prefix_len_name = old_folder[0].length,
6225       subscribed = $('input[name="_subscribed[]"]:first', row).prop('checked');
254d5e 6226
7c28d4 6227     // no renaming, only update class_name
3cb61e 6228     if (oldid == id) {
AM 6229       $(row).attr('class', class_name || '');
7c28d4 6230       return;
TB 6231     }
6232
3cb61e 6233     // update subfolders
AM 6234     $('li', row).each(function() {
6235       var fname = ref.folder_id2name(this.id),
6236         folder = ref.env.subscriptionrows[fname],
6237         newid = id + fname.slice(prefix_len_id);
254d5e 6238
3cb61e 6239       this.id = 'rcmli' + ref.html_identifier_encode(newid);
AM 6240       $('input[name="_subscribed[]"]:first', this).val(newid);
6241       folder[0] = name + folder[0].slice(prefix_len_name);
6242
6243       subfolders[newid] = folder;
6244       delete ref.env.subscriptionrows[fname];
6245     });
6246
6247     // get row off the list
6248     row = $(row).detach();
6249
6250     delete this.env.subscriptionrows[oldid];
6251
6252     // remove parent list/toggle elements if not needed
6253     if (parent.get(0) != this.gui_objects.subscriptionlist && !$('li', parent).length) {
6254       $('ul,div.treetoggle', parent.parent()).remove();
254d5e 6255     }
A 6256
3cb61e 6257     // move the existing table row
AM 6258     this.add_folder_row(id, name, display_name, is_protected, subscribed, class_name, row, subfolders);
8fa922 6259   };
24053e 6260
T 6261   // remove the table row of a specific mailbox from the table
3cb61e 6262   this.remove_folder_row = function(folder)
8fa922 6263   {
ef4c47 6264     // reset searching
AM 6265     if (this.subscription_list.is_search()) {
6266       this.subscription_select();
6267       this.subscription_list.reset_search();
6268     }
6269
3cb61e 6270     var list = [], row = this.subscription_list.get_item(folder, true);
8fa922 6271
254d5e 6272     // get subfolders if any
3cb61e 6273     $('li', row).each(function() { list.push(ref.folder_id2name(this.id)); });
254d5e 6274
3cb61e 6275     // remove folder row (and subfolders)
AM 6276     this.subscription_list.remove(folder);
254d5e 6277
3cb61e 6278     // update local list variable
AM 6279     list.push(folder);
6280     $.each(list, function(i, v) { delete ref.env.subscriptionrows[v]; });
70da8c 6281   };
4e17e6 6282
edfe91 6283   this.subscribe = function(folder)
8fa922 6284   {
af3c04 6285     if (folder) {
5be0d0 6286       var lock = this.display_message(this.get_label('foldersubscribing'), 'loading');
c31360 6287       this.http_post('subscribe', {_mbox: folder}, lock);
af3c04 6288     }
8fa922 6289   };
4e17e6 6290
edfe91 6291   this.unsubscribe = function(folder)
8fa922 6292   {
af3c04 6293     if (folder) {
5be0d0 6294       var lock = this.display_message(this.get_label('folderunsubscribing'), 'loading');
c31360 6295       this.http_post('unsubscribe', {_mbox: folder}, lock);
af3c04 6296     }
8fa922 6297   };
9bebdf 6298
af3c04 6299   // when user select a folder in manager
A 6300   this.show_folder = function(folder, path, force)
6301   {
24fa5d 6302     var win, target = window,
af3c04 6303       url = '&_action=edit-folder&_mbox='+urlencode(folder);
A 6304
6305     if (path)
6306       url += '&_path='+urlencode(path);
6307
24fa5d 6308     if (win = this.get_frame_window(this.env.contentframe)) {
AM 6309       target = win;
af3c04 6310       url += '&_framed=1';
A 6311     }
6312
c31360 6313     if (String(target.location.href).indexOf(url) >= 0 && !force)
af3c04 6314       this.show_contentframe(true);
c31360 6315     else
dc0be3 6316       this.location_href(this.env.comm_path+url, target, true);
af3c04 6317   };
A 6318
e81a30 6319   // disables subscription checkbox (for protected folder)
A 6320   this.disable_subscription = function(folder)
6321   {
3cb61e 6322     var row = this.subscription_list.get_item(folder, true);
AM 6323     if (row)
6324       $('input[name="_subscribed[]"]:first', row).prop('disabled', true);
e81a30 6325   };
A 6326
af3c04 6327   this.folder_size = function(folder)
A 6328   {
6329     var lock = this.set_busy(true, 'loading');
c31360 6330     this.http_post('folder-size', {_mbox: folder}, lock);
af3c04 6331   };
A 6332
6333   this.folder_size_update = function(size)
6334   {
6335     $('#folder-size').replaceWith(size);
6336   };
6337
e9ecd4 6338   // filter folders by namespace
AM 6339   this.folder_filter = function(prefix)
6340   {
6341     this.subscription_list.reset_search();
6342
6343     this.subscription_list.container.children('li').each(function() {
6344       var i, folder = ref.folder_id2name(this.id);
6345       // show all folders
6346       if (prefix == '---') {
6347       }
6348       // got namespace prefix
6349       else if (prefix) {
6350         if (folder !== prefix) {
6351           $(this).data('filtered', true).hide();
6352           return
6353         }
6354       }
6355       // no namespace prefix, filter out all other namespaces
6356       else {
6357         // first get all namespace roots
6358         for (i in ref.env.ns_roots) {
6359           if (folder === ref.env.ns_roots[i]) {
6360             $(this).data('filtered', true).hide();
6361             return;
6362           }
6363         }
6364       }
6365
6366       $(this).removeData('filtered').show();
6367     });
6368   };
4e17e6 6369
T 6370   /*********************************************************/
6371   /*********           GUI functionality           *********/
6372   /*********************************************************/
6373
e639c5 6374   var init_button = function(cmd, prop)
T 6375   {
6376     var elm = document.getElementById(prop.id);
6377     if (!elm)
6378       return;
6379
6380     var preload = false;
6381     if (prop.type == 'image') {
6382       elm = elm.parentNode;
6383       preload = true;
6384     }
6385
6386     elm._command = cmd;
6387     elm._id = prop.id;
6388     if (prop.sel) {
f1aaca 6389       elm.onmousedown = function(e) { return ref.button_sel(this._command, this._id); };
AM 6390       elm.onmouseup = function(e) { return ref.button_out(this._command, this._id); };
e639c5 6391       if (preload)
T 6392         new Image().src = prop.sel;
6393     }
6394     if (prop.over) {
f1aaca 6395       elm.onmouseover = function(e) { return ref.button_over(this._command, this._id); };
AM 6396       elm.onmouseout = function(e) { return ref.button_out(this._command, this._id); };
e639c5 6397       if (preload)
T 6398         new Image().src = prop.over;
6399     }
6400   };
6401
29f977 6402   // set event handlers on registered buttons
T 6403   this.init_buttons = function()
6404   {
6405     for (var cmd in this.buttons) {
d8cf6d 6406       if (typeof cmd !== 'string')
29f977 6407         continue;
8fa922 6408
ab8fda 6409       for (var i=0; i<this.buttons[cmd].length; i++) {
e639c5 6410         init_button(cmd, this.buttons[cmd][i]);
29f977 6411       }
4e17e6 6412     }
29f977 6413   };
4e17e6 6414
T 6415   // set button to a specific state
6416   this.set_button = function(command, state)
8fa922 6417   {
ea0866 6418     var n, button, obj, $obj, a_buttons = this.buttons[command],
249815 6419       len = a_buttons ? a_buttons.length : 0;
4e17e6 6420
249815 6421     for (n=0; n<len; n++) {
4e17e6 6422       button = a_buttons[n];
T 6423       obj = document.getElementById(button.id);
6424
a7dad4 6425       if (!obj || button.status === state)
ab8fda 6426         continue;
AM 6427
4e17e6 6428       // get default/passive setting of the button
ab8fda 6429       if (button.type == 'image' && !button.status) {
4e17e6 6430         button.pas = obj._original_src ? obj._original_src : obj.src;
104ee3 6431         // respect PNG fix on IE browsers
T 6432         if (obj.runtimeStyle && obj.runtimeStyle.filter && obj.runtimeStyle.filter.match(/src=['"]([^'"]+)['"]/))
6433           button.pas = RegExp.$1;
6434       }
ab8fda 6435       else if (!button.status)
4e17e6 6436         button.pas = String(obj.className);
T 6437
a7dad4 6438       button.status = state;
AM 6439
4e17e6 6440       // set image according to button state
ab8fda 6441       if (button.type == 'image' && button[state]) {
4e17e6 6442         obj.src = button[state];
8fa922 6443       }
4e17e6 6444       // set class name according to button state
ab8fda 6445       else if (button[state] !== undefined) {
c833ed 6446         obj.className = button[state];
8fa922 6447       }
4e17e6 6448       // disable/enable input buttons
ab8fda 6449       if (button.type == 'input') {
34ddfc 6450         obj.disabled = state == 'pas';
TB 6451       }
6452       else if (button.type == 'uibutton') {
e8bcf0 6453         button.status = state;
34ddfc 6454         $(obj).button('option', 'disabled', state == 'pas');
e8bcf0 6455       }
TB 6456       else {
ea0866 6457         $obj = $(obj);
TB 6458         $obj
6459           .attr('tabindex', state == 'pas' || state == 'sel' ? '-1' : ($obj.attr('data-tabindex') || '0'))
e8bcf0 6460           .attr('aria-disabled', state == 'pas' || state == 'sel' ? 'true' : 'false');
4e17e6 6461       }
8fa922 6462     }
A 6463   };
4e17e6 6464
eb6842 6465   // display a specific alttext
T 6466   this.set_alttext = function(command, label)
8fa922 6467   {
249815 6468     var n, button, obj, link, a_buttons = this.buttons[command],
A 6469       len = a_buttons ? a_buttons.length : 0;
8fa922 6470
249815 6471     for (n=0; n<len; n++) {
A 6472       button = a_buttons[n];
8fa922 6473       obj = document.getElementById(button.id);
A 6474
249815 6475       if (button.type == 'image' && obj) {
8fa922 6476         obj.setAttribute('alt', this.get_label(label));
A 6477         if ((link = obj.parentNode) && link.tagName.toLowerCase() == 'a')
6478           link.setAttribute('title', this.get_label(label));
eb6842 6479       }
8fa922 6480       else if (obj)
A 6481         obj.setAttribute('title', this.get_label(label));
6482     }
6483   };
4e17e6 6484
T 6485   // mouse over button
6486   this.button_over = function(command, id)
356a67 6487   {
04fbc5 6488     this.button_event(command, id, 'over');
356a67 6489   };
4e17e6 6490
c8c1e0 6491   // mouse down on button
S 6492   this.button_sel = function(command, id)
356a67 6493   {
04fbc5 6494     this.button_event(command, id, 'sel');
356a67 6495   };
4e17e6 6496
T 6497   // mouse out of button
6498   this.button_out = function(command, id)
04fbc5 6499   {
AM 6500     this.button_event(command, id, 'act');
6501   };
6502
6503   // event of button
6504   this.button_event = function(command, id, event)
356a67 6505   {
249815 6506     var n, button, obj, a_buttons = this.buttons[command],
A 6507       len = a_buttons ? a_buttons.length : 0;
4e17e6 6508
249815 6509     for (n=0; n<len; n++) {
4e17e6 6510       button = a_buttons[n];
8fa922 6511       if (button.id == id && button.status == 'act') {
04fbc5 6512         if (button[event] && (obj = document.getElementById(button.id))) {
AM 6513           obj[button.type == 'image' ? 'src' : 'className'] = button[event];
6514         }
6515
6516         if (event == 'sel') {
6517           this.buttons_sel[id] = command;
4e17e6 6518         }
T 6519       }
356a67 6520     }
0501b6 6521   };
7f5a84 6522
5eee00 6523   // write to the document/window title
T 6524   this.set_pagetitle = function(title)
6525   {
6526     if (title && document.title)
6527       document.title = title;
8fa922 6528   };
5eee00 6529
ad334a 6530   // display a system message, list of types in common.css (below #message definition)
0b36d1 6531   this.display_message = function(msg, type, timeout, key)
8fa922 6532   {
b716bd 6533     // pass command to parent window
27acfd 6534     if (this.is_framed())
7f5a84 6535       return parent.rcmail.display_message(msg, type, timeout);
b716bd 6536
ad334a 6537     if (!this.gui_objects.message) {
A 6538       // save message in order to display after page loaded
6539       if (type != 'loading')
0b36d1 6540         this.pending_message = [msg, type, timeout, key];
a8f496 6541       return 1;
ad334a 6542     }
f9c107 6543
0b36d1 6544     if (!type)
AM 6545       type = 'notice';
8fa922 6546
0b36d1 6547     if (!key)
AM 6548       key = this.html_identifier(msg);
6549
6550     var date = new Date(),
7f5a84 6551       id = type + date.getTime();
A 6552
0b36d1 6553     if (!timeout) {
AM 6554       switch (type) {
6555         case 'error':
6556         case 'warning':
6557           timeout = this.message_time * 2;
6558           break;
6559
6560         case 'uploading':
6561           timeout = 0;
6562           break;
6563
6564         default:
6565           timeout = this.message_time;
6566       }
6567     }
7f5a84 6568
ef292e 6569     if (type == 'loading') {
T 6570       key = 'loading';
6571       timeout = this.env.request_timeout * 1000;
6572       if (!msg)
6573         msg = this.get_label('loading');
6574     }
29b397 6575
b37e69 6576     // The same message is already displayed
ef292e 6577     if (this.messages[key]) {
57e38f 6578       // replace label
ef292e 6579       if (this.messages[key].obj)
T 6580         this.messages[key].obj.html(msg);
57e38f 6581       // store label in stack
A 6582       if (type == 'loading') {
6583         this.messages[key].labels.push({'id': id, 'msg': msg});
6584       }
6585       // add element and set timeout
ef292e 6586       this.messages[key].elements.push(id);
da5cad 6587       setTimeout(function() { ref.hide_message(id, type == 'loading'); }, timeout);
b37e69 6588       return id;
ad334a 6589     }
8fa922 6590
57e38f 6591     // create DOM object and display it
A 6592     var obj = $('<div>').addClass(type).html(msg).data('key', key),
6593       cont = $(this.gui_objects.message).append(obj).show();
6594
6595     this.messages[key] = {'obj': obj, 'elements': [id]};
8fa922 6596
ad334a 6597     if (type == 'loading') {
57e38f 6598       this.messages[key].labels = [{'id': id, 'msg': msg}];
ad334a 6599     }
0b36d1 6600     else if (type != 'uploading') {
a539ce 6601       obj.click(function() { return ref.hide_message(obj); })
TB 6602         .attr('role', 'alert');
70cfb4 6603     }
57e38f 6604
0e530b 6605     this.triggerEvent('message', { message:msg, type:type, timeout:timeout, object:obj });
T 6606
fcc7f8 6607     if (timeout > 0)
34003c 6608       setTimeout(function() { ref.hide_message(id, type != 'loading'); }, timeout);
0b36d1 6609
57e38f 6610     return id;
8fa922 6611   };
4e17e6 6612
ad334a 6613   // make a message to disapear
A 6614   this.hide_message = function(obj, fade)
554d79 6615   {
ad334a 6616     // pass command to parent window
27acfd 6617     if (this.is_framed())
ad334a 6618       return parent.rcmail.hide_message(obj, fade);
A 6619
a8f496 6620     if (!this.gui_objects.message)
TB 6621       return;
6622
ffc2d0 6623     var k, n, i, o, m = this.messages;
57e38f 6624
A 6625     // Hide message by object, don't use for 'loading'!
d8cf6d 6626     if (typeof obj === 'object') {
ffc2d0 6627       o = $(obj);
AM 6628       k = o.data('key');
6629       this.hide_message_object(o, fade);
6630       if (m[k])
6631         delete m[k];
ad334a 6632     }
57e38f 6633     // Hide message by id
ad334a 6634     else {
ee72e4 6635       for (k in m) {
A 6636         for (n in m[k].elements) {
6637           if (m[k] && m[k].elements[n] == obj) {
6638             m[k].elements.splice(n, 1);
57e38f 6639             // hide DOM element if last instance is removed
ee72e4 6640             if (!m[k].elements.length) {
ffc2d0 6641               this.hide_message_object(m[k].obj, fade);
ee72e4 6642               delete m[k];
ad334a 6643             }
57e38f 6644             // set pending action label for 'loading' message
A 6645             else if (k == 'loading') {
6646               for (i in m[k].labels) {
6647                 if (m[k].labels[i].id == obj) {
6648                   delete m[k].labels[i];
6649                 }
6650                 else {
77f9a4 6651                   o = m[k].labels[i].msg;
AM 6652                   m[k].obj.html(o);
57e38f 6653                 }
A 6654               }
6655             }
ad334a 6656           }
A 6657         }
6658       }
6659     }
554d79 6660   };
A 6661
ffc2d0 6662   // hide message object and remove from the DOM
AM 6663   this.hide_message_object = function(o, fade)
6664   {
6665     if (fade)
6666       o.fadeOut(600, function() {$(this).remove(); });
6667     else
6668       o.hide().remove();
6669   };
6670
54dfd1 6671   // remove all messages immediately
A 6672   this.clear_messages = function()
6673   {
6674     // pass command to parent window
6675     if (this.is_framed())
6676       return parent.rcmail.clear_messages();
6677
6678     var k, n, m = this.messages;
6679
6680     for (k in m)
6681       for (n in m[k].elements)
6682         if (m[k].obj)
ffc2d0 6683           this.hide_message_object(m[k].obj);
54dfd1 6684
A 6685     this.messages = {};
6686   };
6687
0b36d1 6688   // display uploading message with progress indicator
AM 6689   // data should contain: name, total, current, percent, text
6690   this.display_progress = function(data)
6691   {
6692     if (!data || !data.name)
6693       return;
6694
6695     var msg = this.messages['progress' + data.name];
6696
6697     if (!data.label)
6698       data.label = this.get_label('uploadingmany');
6699
6700     if (!msg) {
6701       if (!data.percent || data.percent < 100)
6702         this.display_message(data.label, 'uploading', 0, 'progress' + data.name);
6703       return;
6704     }
6705
6706     if (!data.total || data.percent >= 100) {
6707       this.hide_message(msg.obj);
6708       return;
6709     }
6710
6711     if (data.text)
6712       data.label += ' ' + data.text;
6713
6714     msg.obj.text(data.label);
6715   };
6716
765ecb 6717   // open a jquery UI dialog with the given content
6c5c22 6718   this.show_popup_dialog = function(content, title, buttons, options)
765ecb 6719   {
TB 6720     // forward call to parent window
6721     if (this.is_framed()) {
6c5c22 6722       return parent.rcmail.show_popup_dialog(content, title, buttons, options);
765ecb 6723     }
TB 6724
6c5c22 6725     var popup = $('<div class="popup">');
AM 6726
6727     if (typeof content == 'object')
6728       popup.append(content);
6729     else
31b023 6730       popup.html(content);
6c5c22 6731
79e92d 6732     options = $.extend({
765ecb 6733         title: title,
c8bc8c 6734         buttons: buttons,
765ecb 6735         modal: true,
TB 6736         resizable: true,
c8bc8c 6737         width: 500,
6c5c22 6738         close: function(event, ui) { $(this).remove(); }
79e92d 6739       }, options || {});
AM 6740
6741     popup.dialog(options);
765ecb 6742
c8bc8c 6743     // resize and center popup
AM 6744     var win = $(window), w = win.width(), h = win.height(),
6745       width = popup.width(), height = popup.height();
6746
6747     popup.dialog('option', {
6748       height: Math.min(h - 40, height + 75 + (buttons ? 50 : 0)),
f14784 6749       width: Math.min(w - 20, width + 36)
c8bc8c 6750     });
6abdff 6751
630d08 6752     // assign special classes to dialog buttons
AM 6753     $.each(options.button_classes || [], function(i, v) {
6754       if (v) $($('.ui-dialog-buttonpane button.ui-button', popup.parent()).get(i)).addClass(v);
6755     });
6756
6abdff 6757     return popup;
765ecb 6758   };
TB 6759
ab8fda 6760   // enable/disable buttons for page shifting
AM 6761   this.set_page_buttons = function()
6762   {
04fbc5 6763     this.enable_command('nextpage', 'lastpage', this.env.pagecount > this.env.current_page);
AM 6764     this.enable_command('previouspage', 'firstpage', this.env.current_page > 1);
9a5d9a 6765
AM 6766     this.update_pagejumper();
ab8fda 6767   };
AM 6768
4e17e6 6769   // mark a mailbox as selected and set environment variable
fb6d86 6770   this.select_folder = function(name, prefix, encode)
f11541 6771   {
71a522 6772     if (this.savedsearchlist) {
TB 6773       this.savedsearchlist.select('');
6774     }
6775
344943 6776     if (this.treelist) {
TB 6777       this.treelist.select(name);
6778     }
6779     else if (this.gui_objects.folderlist) {
f5de03 6780       $('li.selected', this.gui_objects.folderlist).removeClass('selected');
TB 6781       $(this.get_folder_li(name, prefix, encode)).addClass('selected');
8fa922 6782
99d866 6783       // trigger event hook
f8e48d 6784       this.triggerEvent('selectfolder', { folder:name, prefix:prefix });
f11541 6785     }
T 6786   };
6787
636bd7 6788   // adds a class to selected folder
A 6789   this.mark_folder = function(name, class_name, prefix, encode)
6790   {
6791     $(this.get_folder_li(name, prefix, encode)).addClass(class_name);
a62c73 6792     this.triggerEvent('markfolder', {folder: name, mark: class_name, status: true});
636bd7 6793   };
A 6794
6795   // adds a class to selected folder
6796   this.unmark_folder = function(name, class_name, prefix, encode)
6797   {
6798     $(this.get_folder_li(name, prefix, encode)).removeClass(class_name);
a62c73 6799     this.triggerEvent('markfolder', {folder: name, mark: class_name, status: false});
636bd7 6800   };
A 6801
f11541 6802   // helper method to find a folder list item
fb6d86 6803   this.get_folder_li = function(name, prefix, encode)
f11541 6804   {
a61bbb 6805     if (!prefix)
T 6806       prefix = 'rcmli';
8fa922 6807
A 6808     if (this.gui_objects.folderlist) {
fb6d86 6809       name = this.html_identifier(name, encode);
a61bbb 6810       return document.getElementById(prefix+name);
f11541 6811     }
T 6812   };
24053e 6813
f52c93 6814   // for reordering column array (Konqueror workaround)
T 6815   // and for setting some message list global variables
c83535 6816   this.set_message_coltypes = function(listcols, repl, smart_col)
c3eab2 6817   {
5b67d3 6818     var list = this.message_list,
517dae 6819       thead = list ? list.thead : null,
c83535 6820       repl, cell, col, n, len, tr;
8fa922 6821
c83535 6822     this.env.listcols = listcols;
f52c93 6823
465ba8 6824     if (!this.env.coltypes)
TB 6825       this.env.coltypes = {};
6826
f52c93 6827     // replace old column headers
c3eab2 6828     if (thead) {
A 6829       if (repl) {
c83535 6830         thead.innerHTML = '';
5b67d3 6831         tr = document.createElement('tr');
A 6832
c3eab2 6833         for (c=0, len=repl.length; c < len; c++) {
72afe3 6834           cell = document.createElement('th');
9749da 6835           cell.innerHTML = repl[c].html || '';
c3eab2 6836           if (repl[c].id) cell.id = repl[c].id;
A 6837           if (repl[c].className) cell.className = repl[c].className;
6838           tr.appendChild(cell);
f52c93 6839         }
c83535 6840         thead.appendChild(tr);
c3eab2 6841       }
A 6842
c83535 6843       for (n=0, len=this.env.listcols.length; n<len; n++) {
TB 6844         col = this.env.listcols[n];
e0efd8 6845         if ((cell = thead.rows[0].cells[n]) && (col == 'from' || col == 'to' || col == 'fromto')) {
c83535 6846           $(cell).attr('rel', col).find('span,a').text(this.get_label(col == 'fromto' ? smart_col : col));
c3eab2 6847         }
f52c93 6848       }
T 6849     }
095d05 6850
f52c93 6851     this.env.subject_col = null;
T 6852     this.env.flagged_col = null;
98f2c9 6853     this.env.status_col = null;
c4b819 6854
c83535 6855     if (this.env.coltypes.folder)
TB 6856       this.env.coltypes.folder.hidden = !(this.env.search_request || this.env.search_id) || this.env.search_scope == 'base';
6857
6858     if ((n = $.inArray('subject', this.env.listcols)) >= 0) {
9f07d1 6859       this.env.subject_col = n;
5b67d3 6860       if (list)
A 6861         list.subject_col = n;
8fa922 6862     }
c83535 6863     if ((n = $.inArray('flag', this.env.listcols)) >= 0)
9f07d1 6864       this.env.flagged_col = n;
c83535 6865     if ((n = $.inArray('status', this.env.listcols)) >= 0)
9f07d1 6866       this.env.status_col = n;
b62c48 6867
628706 6868     if (list) {
f5799d 6869       list.hide_column('folder', (this.env.coltypes.folder && this.env.coltypes.folder.hidden) || $.inArray('folder', this.env.listcols) < 0);
5b67d3 6870       list.init_header();
628706 6871     }
f52c93 6872   };
4e17e6 6873
T 6874   // replace content of row count display
bba252 6875   this.set_rowcount = function(text, mbox)
8fa922 6876   {
bba252 6877     // #1487752
A 6878     if (mbox && mbox != this.env.mailbox)
6879       return false;
6880
cc97ea 6881     $(this.gui_objects.countdisplay).html(text);
4e17e6 6882
T 6883     // update page navigation buttons
6884     this.set_page_buttons();
8fa922 6885   };
6d2714 6886
ac5d15 6887   // replace content of mailboxname display
T 6888   this.set_mailboxname = function(content)
8fa922 6889   {
ac5d15 6890     if (this.gui_objects.mailboxname && content)
T 6891       this.gui_objects.mailboxname.innerHTML = content;
8fa922 6892   };
ac5d15 6893
58e360 6894   // replace content of quota display
6d2714 6895   this.set_quota = function(content)
8fa922 6896   {
2c1937 6897     if (this.gui_objects.quotadisplay && content && content.type == 'text')
1187f6 6898       $(this.gui_objects.quotadisplay).text((content.percent||0) + '%').attr('title', content.title);
2c1937 6899
fe1bd5 6900     this.triggerEvent('setquota', content);
2c1937 6901     this.env.quota_content = content;
8fa922 6902   };
6b47de 6903
da5fa2 6904   // update trash folder state
AM 6905   this.set_trash_count = function(count)
6906   {
6907     this[(count ? 'un' : '') + 'mark_folder'](this.env.trash_mailbox, 'empty', '', true);
6908   };
6909
4e17e6 6910   // update the mailboxlist
636bd7 6911   this.set_unread_count = function(mbox, count, set_title, mark)
8fa922 6912   {
4e17e6 6913     if (!this.gui_objects.mailboxlist)
T 6914       return false;
25d8ba 6915
85360d 6916     this.env.unread_counts[mbox] = count;
T 6917     this.set_unread_count_display(mbox, set_title);
636bd7 6918
A 6919     if (mark)
6920       this.mark_folder(mbox, mark, '', true);
d0924d 6921     else if (!count)
A 6922       this.unmark_folder(mbox, 'recent', '', true);
8fa922 6923   };
7f9d71 6924
S 6925   // update the mailbox count display
6926   this.set_unread_count_display = function(mbox, set_title)
8fa922 6927   {
de06fc 6928     var reg, link, text_obj, item, mycount, childcount, div;
dbd069 6929
fb6d86 6930     if (item = this.get_folder_li(mbox, '', true)) {
07d367 6931       mycount = this.env.unread_counts[mbox] ? this.env.unread_counts[mbox] : 0;
de06fc 6932       link = $(item).children('a').eq(0);
T 6933       text_obj = link.children('span.unreadcount');
6934       if (!text_obj.length && mycount)
6935         text_obj = $('<span>').addClass('unreadcount').appendTo(link);
15a9d1 6936       reg = /\s+\([0-9]+\)$/i;
7f9d71 6937
835a0c 6938       childcount = 0;
S 6939       if ((div = item.getElementsByTagName('div')[0]) &&
8fa922 6940           div.className.match(/collapsed/)) {
7f9d71 6941         // add children's counters
fb6d86 6942         for (var k in this.env.unread_counts)
6a9144 6943           if (k.startsWith(mbox + this.env.delimiter))
85360d 6944             childcount += this.env.unread_counts[k];
8fa922 6945       }
4e17e6 6946
de06fc 6947       if (mycount && text_obj.length)
ce86f0 6948         text_obj.html(this.env.unreadwrap.replace(/%[sd]/, mycount));
de06fc 6949       else if (text_obj.length)
T 6950         text_obj.remove();
25d8ba 6951
7f9d71 6952       // set parent's display
07d367 6953       reg = new RegExp(RegExp.escape(this.env.delimiter) + '[^' + RegExp.escape(this.env.delimiter) + ']+$');
7f9d71 6954       if (mbox.match(reg))
S 6955         this.set_unread_count_display(mbox.replace(reg, ''), false);
6956
15a9d1 6957       // set the right classes
cc97ea 6958       if ((mycount+childcount)>0)
T 6959         $(item).addClass('unread');
6960       else
6961         $(item).removeClass('unread');
8fa922 6962     }
15a9d1 6963
T 6964     // set unread count to window title
01c86f 6965     reg = /^\([0-9]+\)\s+/i;
8fa922 6966     if (set_title && document.title) {
dbd069 6967       var new_title = '',
A 6968         doc_title = String(document.title);
15a9d1 6969
85360d 6970       if (mycount && doc_title.match(reg))
T 6971         new_title = doc_title.replace(reg, '('+mycount+') ');
6972       else if (mycount)
6973         new_title = '('+mycount+') '+doc_title;
15a9d1 6974       else
5eee00 6975         new_title = doc_title.replace(reg, '');
8fa922 6976
5eee00 6977       this.set_pagetitle(new_title);
8fa922 6978     }
A 6979   };
4e17e6 6980
e5686f 6981   // display fetched raw headers
A 6982   this.set_headers = function(content)
cc97ea 6983   {
ad334a 6984     if (this.gui_objects.all_headers_row && this.gui_objects.all_headers_box && content)
cc97ea 6985       $(this.gui_objects.all_headers_box).html(content).show();
T 6986   };
a980cb 6987
e5686f 6988   // display all-headers row and fetch raw message headers
76248c 6989   this.show_headers = function(props, elem)
8fa922 6990   {
e5686f 6991     if (!this.gui_objects.all_headers_row || !this.gui_objects.all_headers_box || !this.env.uid)
A 6992       return;
8fa922 6993
cc97ea 6994     $(elem).removeClass('show-headers').addClass('hide-headers');
T 6995     $(this.gui_objects.all_headers_row).show();
f1aaca 6996     elem.onclick = function() { ref.command('hide-headers', '', elem); };
e5686f 6997
A 6998     // fetch headers only once
8fa922 6999     if (!this.gui_objects.all_headers_box.innerHTML) {
701905 7000       this.http_post('headers', {_uid: this.env.uid, _mbox: this.env.mailbox},
AM 7001         this.display_message(this.get_label('loading'), 'loading')
7002       );
e5686f 7003     }
8fa922 7004   };
e5686f 7005
A 7006   // hide all-headers row
76248c 7007   this.hide_headers = function(props, elem)
8fa922 7008   {
e5686f 7009     if (!this.gui_objects.all_headers_row || !this.gui_objects.all_headers_box)
A 7010       return;
7011
cc97ea 7012     $(elem).removeClass('hide-headers').addClass('show-headers');
T 7013     $(this.gui_objects.all_headers_row).hide();
f1aaca 7014     elem.onclick = function() { ref.command('show-headers', '', elem); };
8fa922 7015   };
e5686f 7016
9a0153 7017   // create folder selector popup, position and display it
6789bf 7018   this.folder_selector = function(event, callback)
9a0153 7019   {
AM 7020     var container = this.folder_selector_element;
7021
7022     if (!container) {
7023       var rows = [],
7024         delim = this.env.delimiter,
6789bf 7025         ul = $('<ul class="toolbarmenu">'),
TB 7026         link = document.createElement('a');
9a0153 7027
AM 7028       container = $('<div id="folder-selector" class="popupmenu"></div>');
7029       link.href = '#';
7030       link.className = 'icon';
7031
7032       // loop over sorted folders list
7033       $.each(this.env.mailboxes_list, function() {
6789bf 7034         var n = 0, s = 0,
9a0153 7035           folder = ref.env.mailboxes[this],
AM 7036           id = folder.id,
6789bf 7037           a = $(link.cloneNode(false)),
TB 7038           row = $('<li>');
9a0153 7039
AM 7040         if (folder.virtual)
6789bf 7041           a.addClass('virtual').attr('aria-disabled', 'true').attr('tabindex', '-1');
TB 7042         else
7043           a.addClass('active').data('id', folder.id);
9a0153 7044
AM 7045         if (folder['class'])
6789bf 7046           a.addClass(folder['class']);
9a0153 7047
AM 7048         // calculate/set indentation level
7049         while ((s = id.indexOf(delim, s)) >= 0) {
7050           n++; s++;
7051         }
6789bf 7052         a.css('padding-left', n ? (n * 16) + 'px' : 0);
9a0153 7053
AM 7054         // add folder name element
6789bf 7055         a.append($('<span>').text(folder.name));
9a0153 7056
6789bf 7057         row.append(a);
9a0153 7058         rows.push(row);
AM 7059       });
7060
7061       ul.append(rows).appendTo(container);
7062
7063       // temporarily show element to calculate its size
7064       container.css({left: '-1000px', top: '-1000px'})
7065         .appendTo($('body')).show();
7066
7067       // set max-height if the list is long
7068       if (rows.length > 10)
6789bf 7069         container.css('max-height', $('li', container)[0].offsetHeight * 10 + 9);
9a0153 7070
6789bf 7071       // register delegate event handler for folder item clicks
TB 7072       container.on('click', 'a.active', function(e){
7073         container.data('callback')($(this).data('id'));
7074         return false;
7075       });
9a0153 7076
AM 7077       this.folder_selector_element = container;
7078     }
7079
6789bf 7080     container.data('callback', callback);
9a0153 7081
6789bf 7082     // position menu on the screen
TB 7083     this.show_menu('folder-selector', true, event);
9a0153 7084   };
AM 7085
6789bf 7086
TB 7087   /***********************************************/
7088   /*********    popup menu functions     *********/
7089   /***********************************************/
7090
7091   // Show/hide a specific popup menu
7092   this.show_menu = function(prop, show, event)
7093   {
7094     var name = typeof prop == 'object' ? prop.menu : prop,
7095       obj = $('#'+name),
7096       ref = event && event.target ? $(event.target) : $(obj.attr('rel') || '#'+name+'link'),
7097       keyboard = rcube_event.is_keyboard(event),
7098       align = obj.attr('data-align') || '',
7099       stack = false;
7100
f0928e 7101     // find "real" button element
TB 7102     if (ref.get(0).tagName != 'A' && ref.closest('a').length)
7103       ref = ref.closest('a');
7104
6789bf 7105     if (typeof prop == 'string')
TB 7106       prop = { menu:name };
7107
7108     // let plugins or skins provide the menu element
7109     if (!obj.length) {
7110       obj = this.triggerEvent('menu-get', { name:name, props:prop, originalEvent:event });
7111     }
7112
7113     if (!obj || !obj.length) {
7114       // just delegate the action to subscribers
7115       return this.triggerEvent(show === false ? 'menu-close' : 'menu-open', { name:name, props:prop, originalEvent:event });
7116     }
7117
7118     // move element to top for proper absolute positioning
7119     obj.appendTo(document.body);
7120
7121     if (typeof show == 'undefined')
7122       show = obj.is(':visible') ? false : true;
7123
7124     if (show && ref.length) {
7125       var win = $(window),
7126         pos = ref.offset(),
7127         above = align.indexOf('bottom') >= 0;
7128
7129       stack = ref.attr('role') == 'menuitem' || ref.closest('[role=menuitem]').length > 0;
7130
7131       ref.offsetWidth = ref.outerWidth();
7132       ref.offsetHeight = ref.outerHeight();
7133       if (!above && pos.top + ref.offsetHeight + obj.height() > win.height()) {
7134         above = true;
7135       }
7136       if (align.indexOf('right') >= 0) {
7137         pos.left = pos.left + ref.outerWidth() - obj.width();
7138       }
7139       else if (stack) {
7140         pos.left = pos.left + ref.offsetWidth - 5;
7141         pos.top -= ref.offsetHeight;
7142       }
7143       if (pos.left + obj.width() > win.width()) {
7144         pos.left = win.width() - obj.width() - 12;
7145       }
7146       pos.top = Math.max(0, pos.top + (above ? -obj.height() : ref.offsetHeight));
7147       obj.css({ left:pos.left+'px', top:pos.top+'px' });
7148     }
7149
7150     // add menu to stack
7151     if (show) {
7152       // truncate stack down to the one containing the ref link
7153       for (var i = this.menu_stack.length - 1; stack && i >= 0; i--) {
7154         if (!$(ref).parents('#'+this.menu_stack[i]).length)
3ef97f 7155           this.hide_menu(this.menu_stack[i], event);
6789bf 7156       }
TB 7157       if (stack && this.menu_stack.length) {
f5de03 7158         obj.data('parent', $.last(this.menu_stack));
TB 7159         obj.css('z-index', ($('#'+$.last(this.menu_stack)).css('z-index') || 0) + 1);
6789bf 7160       }
TB 7161       else if (!stack && this.menu_stack.length) {
7162         this.hide_menu(this.menu_stack[0], event);
7163       }
7164
a2f8fa 7165       obj.show().attr('aria-hidden', 'false').data('opener', ref.attr('aria-expanded', 'true').get(0));
6789bf 7166       this.triggerEvent('menu-open', { name:name, obj:obj, props:prop, originalEvent:event });
TB 7167       this.menu_stack.push(name);
7168
7169       this.menu_keyboard_active = show && keyboard;
7170       if (this.menu_keyboard_active) {
7171         this.focused_menu = name;
7172         obj.find('a,input:not(:disabled)').not('[aria-disabled=true]').first().focus();
7173       }
7174     }
7175     else {  // close menu
7176       this.hide_menu(name, event);
7177     }
7178
7179     return show;
7180   };
7181
7182   // hide the given popup menu (and it's childs)
7183   this.hide_menu = function(name, event)
7184   {
7185     if (!this.menu_stack.length) {
7186       // delegate to subscribers
7187       this.triggerEvent('menu-close', { name:name, props:{ menu:name }, originalEvent:event });
7188       return;
7189     }
7190
7191     var obj, keyboard = rcube_event.is_keyboard(event);
7192     for (var j=this.menu_stack.length-1; j >= 0; j--) {
7193       obj = $('#' + this.menu_stack[j]).hide().attr('aria-hidden', 'true').data('parent', false);
7194       this.triggerEvent('menu-close', { name:this.menu_stack[j], obj:obj, props:{ menu:this.menu_stack[j] }, originalEvent:event });
7195       if (this.menu_stack[j] == name) {
7196         j = -1;  // stop loop
a2f8fa 7197         if (obj.data('opener')) {
TB 7198           $(obj.data('opener')).attr('aria-expanded', 'false');
7199           if (keyboard)
7200             obj.data('opener').focus();
6789bf 7201         }
TB 7202       }
7203       this.menu_stack.pop();
7204     }
7205
7206     // focus previous menu in stack
7207     if (this.menu_stack.length && keyboard) {
7208       this.menu_keyboard_active = true;
f5de03 7209       this.focused_menu = $.last(this.menu_stack);
6789bf 7210       if (!obj || !obj.data('opener'))
TB 7211         $('#'+this.focused_menu).find('a,input:not(:disabled)').not('[aria-disabled=true]').first().focus();
7212     }
7213     else {
7214       this.focused_menu = null;
7215       this.menu_keyboard_active = false;
7216     }
7217   }
7218
9a0153 7219
AM 7220   // position a menu element on the screen in relation to other object
7221   this.element_position = function(element, obj)
7222   {
7223     var obj = $(obj), win = $(window),
5e8da2 7224       width = obj.outerWidth(),
AM 7225       height = obj.outerHeight(),
7226       menu_pos = obj.data('menu-pos'),
9a0153 7227       win_height = win.height(),
AM 7228       elem_height = $(element).height(),
7229       elem_width = $(element).width(),
7230       pos = obj.offset(),
7231       top = pos.top,
7232       left = pos.left + width;
7233
5e8da2 7234     if (menu_pos == 'bottom') {
AM 7235       top += height;
7236       left -= width;
7237     }
7238     else
7239       left -= 5;
7240
9a0153 7241     if (top + elem_height > win_height) {
AM 7242       top -= elem_height - height;
7243       if (top < 0)
7244         top = Math.max(0, (win_height - elem_height) / 2);
7245     }
7246
7247     if (left + elem_width > win.width())
7248       left -= elem_width + width;
7249
7250     element.css({left: left + 'px', top: top + 'px'});
7251   };
7252
646b64 7253   // initialize HTML editor
AM 7254   this.editor_init = function(config, id)
7255   {
7256     this.editor = new rcube_text_editor(config, id);
7257   };
7258
4e17e6 7259
T 7260   /********************************************************/
3bd94b 7261   /*********  html to text conversion functions   *********/
A 7262   /********************************************************/
7263
eda92e 7264   this.html2plain = function(html, func)
AM 7265   {
7266     return this.format_converter(html, 'html', func);
7267   };
7268
7269   this.plain2html = function(plain, func)
7270   {
7271     return this.format_converter(plain, 'plain', func);
7272   };
7273
7274   this.format_converter = function(text, format, func)
8fa922 7275   {
fb1203 7276     // warn the user (if converted content is not empty)
eda92e 7277     if (!text
AM 7278       || (format == 'html' && !(text.replace(/<[^>]+>|&nbsp;|\xC2\xA0|\s/g, '')).length)
7279       || (format != 'html' && !(text.replace(/\xC2\xA0|\s/g, '')).length)
7280     ) {
fb1203 7281       // without setTimeout() here, textarea is filled with initial (onload) content
59b765 7282       if (func)
AM 7283         setTimeout(function() { func(''); }, 50);
fb1203 7284       return true;
AM 7285     }
7286
eda92e 7287     var confirmed = this.env.editor_warned || confirm(this.get_label('editorwarning'));
AM 7288
7289     this.env.editor_warned = true;
7290
7291     if (!confirmed)
fb1203 7292       return false;
AM 7293
eda92e 7294     var url = '?_task=utils&_action=' + (format == 'html' ? 'html2text' : 'text2html'),
ad334a 7295       lock = this.set_busy(true, 'converting');
3bd94b 7296
b0eb95 7297     this.log('HTTP POST: ' + url);
3bd94b 7298
eda92e 7299     $.ajax({ type: 'POST', url: url, data: text, contentType: 'application/octet-stream',
2611ac 7300       error: function(o, status, err) { ref.http_error(o, status, err, lock); },
eda92e 7301       success: function(data) {
AM 7302         ref.set_busy(false, null, lock);
7303         if (func) func(data);
7304       }
8fa922 7305     });
fb1203 7306
AM 7307     return true;
8fa922 7308   };
962085 7309
3bd94b 7310
A 7311   /********************************************************/
4e17e6 7312   /*********        remote request methods        *********/
T 7313   /********************************************************/
0213f8 7314
0501b6 7315   // compose a valid url with the given parameters
T 7316   this.url = function(action, query)
7317   {
e8e88d 7318     var querystring = typeof query === 'string' ? query : '';
d8cf6d 7319
A 7320     if (typeof action !== 'string')
0501b6 7321       query = action;
d8cf6d 7322     else if (!query || typeof query !== 'object')
0501b6 7323       query = {};
d8cf6d 7324
0501b6 7325     if (action)
T 7326       query._action = action;
14423c 7327     else if (this.env.action)
0501b6 7328       query._action = this.env.action;
d8cf6d 7329
e8e88d 7330     var url = this.env.comm_path, k, param = {};
0501b6 7331
T 7332     // overwrite task name
14423c 7333     if (action && action.match(/([a-z0-9_-]+)\/([a-z0-9-_.]+)/)) {
0501b6 7334       query._action = RegExp.$2;
e8e88d 7335       url = url.replace(/\_task=[a-z0-9_-]+/, '_task=' + RegExp.$1);
0501b6 7336     }
d8cf6d 7337
0501b6 7338     // remove undefined values
c31360 7339     for (k in query) {
d8cf6d 7340       if (query[k] !== undefined && query[k] !== null)
0501b6 7341         param[k] = query[k];
T 7342     }
d8cf6d 7343
e8e88d 7344     if (param = $.param(param))
AM 7345       url += (url.indexOf('?') > -1 ? '&' : '?') + param;
7346
7347     if (querystring)
7348       url += (url.indexOf('?') > -1 ? '&' : '?') + querystring;
7349
7350     return url;
0501b6 7351   };
6b47de 7352
4b9efb 7353   this.redirect = function(url, lock)
8fa922 7354   {
719a25 7355     if (lock || lock === null)
4b9efb 7356       this.set_busy(true);
S 7357
7bf6d2 7358     if (this.is_framed()) {
a41dcf 7359       parent.rcmail.redirect(url, lock);
7bf6d2 7360     }
TB 7361     else {
7362       if (this.env.extwin) {
7363         if (typeof url == 'string')
7364           url += (url.indexOf('?') < 0 ? '?' : '&') + '_extwin=1';
7365         else
7366           url._extwin = 1;
7367       }
d7167e 7368       this.location_href(url, window);
7bf6d2 7369     }
8fa922 7370   };
6b47de 7371
T 7372   this.goto_url = function(action, query, lock)
8fa922 7373   {
45924a 7374     this.redirect(this.url(action, query), lock);
8fa922 7375   };
4e17e6 7376
dc0be3 7377   this.location_href = function(url, target, frame)
d7167e 7378   {
dc0be3 7379     if (frame)
A 7380       this.lock_frame();
c31360 7381
A 7382     if (typeof url == 'object')
7383       url = this.env.comm_path + '&' + $.param(url);
dc0be3 7384
d7167e 7385     // simulate real link click to force IE to send referer header
T 7386     if (bw.ie && target == window)
7387       $('<a>').attr('href', url).appendTo(document.body).get(0).click();
7388     else
7389       target.location.href = url;
c442f8 7390
AM 7391     // reset keep-alive interval
7392     this.start_keepalive();
d7167e 7393   };
T 7394
b2992d 7395   // update browser location to remember current view
TB 7396   this.update_state = function(query)
7397   {
7398     if (window.history.replaceState)
7399       window.history.replaceState({}, document.title, rcmail.url('', query));
614c64 7400   };
d8cf6d 7401
7ceabc 7402   // send a http request to the server
c2df5d 7403   this.http_request = function(action, data, lock)
4e17e6 7404   {
c2df5d 7405     if (typeof data !== 'object')
AM 7406       data = rcube_parse_query(data);
7407
7408     data._remote = 1;
7409     data._unlock = lock ? lock : 0;
ecf759 7410
cc97ea 7411     // trigger plugin hook
c2df5d 7412     var result = this.triggerEvent('request' + action, data);
7ceabc 7413
c2df5d 7414     // abort if one of the handlers returned false
AM 7415     if (result === false) {
7416       if (data._unlock)
7417         this.set_busy(false, null, data._unlock);
7418       return false;
7419     }
7420     else if (result !== undefined) {
7421       data = result;
7422       if (data._action) {
7423         action = data._action;
7424         delete data._action;
7425       }
7ceabc 7426     }
8fa922 7427
c2df5d 7428     var url = this.url(action, data);
56f41a 7429
cc97ea 7430     // send request
b0eb95 7431     this.log('HTTP GET: ' + url);
0213f8 7432
a2b638 7433     // reset keep-alive interval
AM 7434     this.start_keepalive();
7435
0213f8 7436     return $.ajax({
c2df5d 7437       type: 'GET', url: url, dataType: 'json',
AM 7438       success: function(data) { ref.http_response(data); },
110360 7439       error: function(o, status, err) { ref.http_error(o, status, err, lock, action); }
ad334a 7440     });
cc97ea 7441   };
T 7442
7443   // send a http POST request to the server
c2df5d 7444   this.http_post = function(action, data, lock)
cc97ea 7445   {
c2df5d 7446     if (typeof data !== 'object')
AM 7447       data = rcube_parse_query(data);
8fa922 7448
c2df5d 7449     data._remote = 1;
AM 7450     data._unlock = lock ? lock : 0;
4e17e6 7451
7ceabc 7452     // trigger plugin hook
c2df5d 7453     var result = this.triggerEvent('request'+action, data);
AM 7454
7455     // abort if one of the handlers returned false
7456     if (result === false) {
7457       if (data._unlock)
7458         this.set_busy(false, null, data._unlock);
7459       return false;
7ceabc 7460     }
c2df5d 7461     else if (result !== undefined) {
AM 7462       data = result;
7463       if (data._action) {
7464         action = data._action;
7465         delete data._action;
7466       }
7467     }
7468
7469     var url = this.url(action);
7ceabc 7470
4e17e6 7471     // send request
b0eb95 7472     this.log('HTTP POST: ' + url);
0213f8 7473
a2b638 7474     // reset keep-alive interval
AM 7475     this.start_keepalive();
7476
0213f8 7477     return $.ajax({
c2df5d 7478       type: 'POST', url: url, data: data, dataType: 'json',
ad334a 7479       success: function(data){ ref.http_response(data); },
110360 7480       error: function(o, status, err) { ref.http_error(o, status, err, lock, action); }
ad334a 7481     });
cc97ea 7482   };
4e17e6 7483
d96151 7484   // aborts ajax request
A 7485   this.abort_request = function(r)
7486   {
7487     if (r.request)
7488       r.request.abort();
7489     if (r.lock)
241450 7490       this.set_busy(false, null, r.lock);
d96151 7491   };
A 7492
ecf759 7493   // handle HTTP response
cc97ea 7494   this.http_response = function(response)
T 7495   {
ad334a 7496     if (!response)
A 7497       return;
7498
cc97ea 7499     if (response.unlock)
e5686f 7500       this.set_busy(false);
4e17e6 7501
2bb1f6 7502     this.triggerEvent('responsebefore', {response: response});
A 7503     this.triggerEvent('responsebefore'+response.action, {response: response});
7504
cc97ea 7505     // set env vars
T 7506     if (response.env)
7507       this.set_env(response.env);
7508
7509     // we have labels to add
d8cf6d 7510     if (typeof response.texts === 'object') {
cc97ea 7511       for (var name in response.texts)
d8cf6d 7512         if (typeof response.texts[name] === 'string')
cc97ea 7513           this.add_label(name, response.texts[name]);
T 7514     }
4e17e6 7515
ecf759 7516     // if we get javascript code from server -> execute it
cc97ea 7517     if (response.exec) {
b0eb95 7518       this.log(response.exec);
cc97ea 7519       eval(response.exec);
0e99d3 7520     }
f52c93 7521
50067d 7522     // execute callback functions of plugins
A 7523     if (response.callbacks && response.callbacks.length) {
7524       for (var i=0; i < response.callbacks.length; i++)
7525         this.triggerEvent(response.callbacks[i][0], response.callbacks[i][1]);
14259c 7526     }
50067d 7527
ecf759 7528     // process the response data according to the sent action
cc97ea 7529     switch (response.action) {
ecf759 7530       case 'delete':
0dbac3 7531         if (this.task == 'addressbook') {
ecf295 7532           var sid, uid = this.contact_list.get_selection(), writable = false;
A 7533
7534           if (uid && this.contact_list.rows[uid]) {
7535             // search results, get source ID from record ID
7536             if (this.env.source == '') {
7537               sid = String(uid).replace(/^[^-]+-/, '');
7538               writable = sid && this.env.address_sources[sid] && !this.env.address_sources[sid].readonly;
7539             }
7540             else {
7541               writable = !this.env.address_sources[this.env.source].readonly;
7542             }
7543           }
0dbac3 7544           this.enable_command('compose', (uid && this.contact_list.rows[uid]));
ecf295 7545           this.enable_command('delete', 'edit', writable);
0dbac3 7546           this.enable_command('export', (this.contact_list && this.contact_list.rowcount > 0));
f7af22 7547           this.enable_command('export-selected', 'print', false);
0dbac3 7548         }
8fa922 7549
a45f9b 7550       case 'move':
dc2fc0 7551         if (this.env.action == 'show') {
5e9a56 7552           // re-enable commands on move/delete error
14259c 7553           this.enable_command(this.env.message_commands, true);
e25a35 7554           if (!this.env.list_post)
A 7555             this.enable_command('reply-list', false);
dbd069 7556         }
13e155 7557         else if (this.task == 'addressbook') {
A 7558           this.triggerEvent('listupdate', { folder:this.env.source, rowcount:this.contact_list.rowcount });
7559         }
8fa922 7560
2eb032 7561       case 'purge':
cc97ea 7562       case 'expunge':
13e155 7563         if (this.task == 'mail') {
04689f 7564           if (!this.env.exists) {
13e155 7565             // clear preview pane content
A 7566             if (this.env.contentframe)
7567               this.show_contentframe(false);
7568             // disable commands useless when mailbox is empty
7569             this.enable_command(this.env.message_commands, 'purge', 'expunge',
27032f 7570               'select-all', 'select-none', 'expand-all', 'expand-unread', 'collapse-all', false);
13e155 7571           }
172e33 7572           if (this.message_list)
A 7573             this.triggerEvent('listupdate', { folder:this.env.mailbox, rowcount:this.message_list.rowcount });
0dbac3 7574         }
T 7575         break;
fdccdb 7576
77de23 7577       case 'refresh':
d41d67 7578       case 'check-recent':
ac0fc3 7579         // update message flags
AM 7580         $.each(this.env.recent_flags || {}, function(uid, flags) {
7581           ref.set_message(uid, 'deleted', flags.deleted);
7582           ref.set_message(uid, 'replied', flags.answered);
7583           ref.set_message(uid, 'unread', !flags.seen);
7584           ref.set_message(uid, 'forwarded', flags.forwarded);
7585           ref.set_message(uid, 'flagged', flags.flagged);
7586         });
7587         delete this.env.recent_flags;
7588
fdccdb 7589       case 'getunread':
f52c93 7590       case 'search':
db0408 7591         this.env.qsearch = null;
0dbac3 7592       case 'list':
T 7593         if (this.task == 'mail') {
c095e6 7594           var is_multifolder = this.is_multifolder_listing(),
AM 7595             list = this.message_list,
7596             uid = this.env.list_uid;
7597
04689f 7598           this.enable_command('show', 'select-all', 'select-none', this.env.messagecount > 0);
26b520 7599           this.enable_command('expunge', this.env.exists && !is_multifolder);
TB 7600           this.enable_command('purge', this.purge_mailbox_test() && !is_multifolder);
7601           this.enable_command('import-messages', !is_multifolder);
7602           this.enable_command('expand-all', 'expand-unread', 'collapse-all', this.env.threading && this.env.messagecount && !is_multifolder);
f52c93 7603
c095e6 7604           if (list) {
28331d 7605             if (response.action == 'list' || response.action == 'search') {
c095e6 7606               // highlight message row when we're back from message page
AM 7607               if (uid) {
7608                 if (!list.rows[uid])
7609                   uid += '-' + this.env.mailbox;
7610                 if (list.rows[uid]) {
7611                   list.select(uid);
7612                 }
7613                 delete this.env.list_uid;
7614               }
7615
28331d 7616               this.enable_command('set-listmode', this.env.threads && !is_multifolder);
c360e1 7617               if (list.rowcount > 0 && !$(document.activeElement).is('input,textarea'))
28331d 7618                 list.focus();
AM 7619               this.msglist_select(list);
7620             }
64f7d6 7621
c095e6 7622             if (response.action != 'getunread')
AM 7623               this.triggerEvent('listupdate', { folder:this.env.mailbox, rowcount:list.rowcount });
c833ed 7624           }
0dbac3 7625         }
99d866 7626         else if (this.task == 'addressbook') {
0dbac3 7627           this.enable_command('export', (this.contact_list && this.contact_list.rowcount > 0));
8fa922 7628
c833ed 7629           if (response.action == 'list' || response.action == 'search') {
f8e48d 7630             this.enable_command('search-create', this.env.source == '');
A 7631             this.enable_command('search-delete', this.env.search_id);
62811c 7632             this.update_group_commands();
c360e1 7633             if (this.contact_list.rowcount > 0 && !$(document.activeElement).is('input,textarea'))
d58c39 7634               this.contact_list.focus();
99d866 7635             this.triggerEvent('listupdate', { folder:this.env.source, rowcount:this.contact_list.rowcount });
a61bbb 7636           }
99d866 7637         }
0dbac3 7638         break;
d58c39 7639
TB 7640       case 'list-contacts':
7641       case 'search-contacts':
7642         if (this.contact_list && this.contact_list.rowcount > 0)
7643           this.contact_list.focus();
7644         break;
cc97ea 7645     }
2bb1f6 7646
ad334a 7647     if (response.unlock)
A 7648       this.hide_message(response.unlock);
7649
2bb1f6 7650     this.triggerEvent('responseafter', {response: response});
A 7651     this.triggerEvent('responseafter'+response.action, {response: response});
c442f8 7652
AM 7653     // reset keep-alive interval
7654     this.start_keepalive();
cc97ea 7655   };
ecf759 7656
T 7657   // handle HTTP request errors
110360 7658   this.http_error = function(request, status, err, lock, action)
8fa922 7659   {
9ff9f5 7660     var errmsg = request.statusText;
ecf759 7661
ad334a 7662     this.set_busy(false, null, lock);
9ff9f5 7663     request.abort();
8fa922 7664
7794ae 7665     // don't display error message on page unload (#1488547)
TB 7666     if (this.unload)
7667       return;
7668
7fbd94 7669     if (request.status && errmsg)
74d421 7670       this.display_message(this.get_label('servererror') + ' (' + errmsg + ')', 'error');
110360 7671     else if (status == 'timeout')
T 7672       this.display_message(this.get_label('requesttimedout'), 'error');
7673     else if (request.status == 0 && status != 'abort')
adaddf 7674       this.display_message(this.get_label('connerror'), 'error');
110360 7675
7fac4d 7676     // redirect to url specified in location header if not empty
J 7677     var location_url = request.getResponseHeader("Location");
72e24b 7678     if (location_url && this.env.action != 'compose')  // don't redirect on compose screen, contents might get lost (#1488926)
7fac4d 7679       this.redirect(location_url);
J 7680
daddbf 7681     // 403 Forbidden response (CSRF prevention) - reload the page.
AM 7682     // In case there's a new valid session it will be used, otherwise
7683     // login form will be presented (#1488960).
7684     if (request.status == 403) {
7685       (this.is_framed() ? parent : window).location.reload();
7686       return;
7687     }
7688
110360 7689     // re-send keep-alive requests after 30 seconds
T 7690     if (action == 'keep-alive')
92cb7f 7691       setTimeout(function(){ ref.keep_alive(); ref.start_keepalive(); }, 30000);
8fa922 7692   };
ecf759 7693
85e60a 7694   // handler for session errors detected on the server
TB 7695   this.session_error = function(redirect_url)
7696   {
7697     this.env.server_error = 401;
7698
7699     // save message in local storage and do not redirect
7700     if (this.env.action == 'compose') {
7701       this.save_compose_form_local();
7e7e45 7702       this.compose_skip_unsavedcheck = true;
85e60a 7703     }
TB 7704     else if (redirect_url) {
10a397 7705       setTimeout(function(){ ref.redirect(redirect_url, true); }, 2000);
85e60a 7706     }
TB 7707   };
7708
72e24b 7709   // callback when an iframe finished loading
TB 7710   this.iframe_loaded = function(unlock)
7711   {
7712     this.set_busy(false, null, unlock);
7713
7714     if (this.submit_timer)
7715       clearTimeout(this.submit_timer);
7716   };
7717
017c4f 7718   /**
T 7719    Send multi-threaded parallel HTTP requests to the server for a list if items.
7720    The string '%' in either a GET query or POST parameters will be replaced with the respective item value.
7721    This is the argument object expected: {
7722        items: ['foo','bar','gna'],      // list of items to send requests for
7723        action: 'task/some-action',      // Roudncube action to call
7724        query: { q:'%s' },               // GET query parameters
7725        postdata: { source:'%s' },       // POST data (sends a POST request if present)
7726        threads: 3,                      // max. number of concurrent requests
7727        onresponse: function(data){ },   // Callback function called for every response received from server
7728        whendone: function(alldata){ }   // Callback function called when all requests have been sent
7729    }
7730   */
7731   this.multi_thread_http_request = function(prop)
7732   {
eb7e45 7733     var i, item, reqid = new Date().getTime(),
AM 7734       threads = prop.threads || 1;
017c4f 7735
T 7736     prop.reqid = reqid;
7737     prop.running = 0;
7738     prop.requests = [];
7739     prop.result = [];
7740     prop._items = $.extend([], prop.items);  // copy items
7741
7742     if (!prop.lock)
7743       prop.lock = this.display_message(this.get_label('loading'), 'loading');
7744
7745     // add the request arguments to the jobs pool
7746     this.http_request_jobs[reqid] = prop;
7747
7748     // start n threads
eb7e45 7749     for (i=0; i < threads; i++) {
017c4f 7750       item = prop._items.shift();
T 7751       if (item === undefined)
7752         break;
7753
7754       prop.running++;
7755       prop.requests.push(this.multi_thread_send_request(prop, item));
7756     }
7757
7758     return reqid;
7759   };
7760
7761   // helper method to send an HTTP request with the given iterator value
7762   this.multi_thread_send_request = function(prop, item)
7763   {
65070f 7764     var k, postdata, query;
017c4f 7765
T 7766     // replace %s in post data
7767     if (prop.postdata) {
7768       postdata = {};
65070f 7769       for (k in prop.postdata) {
017c4f 7770         postdata[k] = String(prop.postdata[k]).replace('%s', item);
T 7771       }
7772       postdata._reqid = prop.reqid;
7773     }
7774     // replace %s in query
7775     else if (typeof prop.query == 'string') {
7776       query = prop.query.replace('%s', item);
7777       query += '&_reqid=' + prop.reqid;
7778     }
7779     else if (typeof prop.query == 'object' && prop.query) {
7780       query = {};
65070f 7781       for (k in prop.query) {
017c4f 7782         query[k] = String(prop.query[k]).replace('%s', item);
T 7783       }
7784       query._reqid = prop.reqid;
7785     }
7786
7787     // send HTTP GET or POST request
7788     return postdata ? this.http_post(prop.action, postdata) : this.http_request(prop.action, query);
7789   };
7790
7791   // callback function for multi-threaded http responses
7792   this.multi_thread_http_response = function(data, reqid)
7793   {
7794     var prop = this.http_request_jobs[reqid];
7795     if (!prop || prop.running <= 0 || prop.cancelled)
7796       return;
7797
7798     prop.running--;
7799
7800     // trigger response callback
7801     if (prop.onresponse && typeof prop.onresponse == 'function') {
7802       prop.onresponse(data);
7803     }
7804
7805     prop.result = $.extend(prop.result, data);
7806
7807     // send next request if prop.items is not yet empty
7808     var item = prop._items.shift();
7809     if (item !== undefined) {
7810       prop.running++;
7811       prop.requests.push(this.multi_thread_send_request(prop, item));
7812     }
7813     // trigger whendone callback and mark this request as done
7814     else if (prop.running == 0) {
7815       if (prop.whendone && typeof prop.whendone == 'function') {
7816         prop.whendone(prop.result);
7817       }
7818
7819       this.set_busy(false, '', prop.lock);
7820
7821       // remove from this.http_request_jobs pool
7822       delete this.http_request_jobs[reqid];
7823     }
7824   };
7825
7826   // abort a running multi-thread request with the given identifier
7827   this.multi_thread_request_abort = function(reqid)
7828   {
7829     var prop = this.http_request_jobs[reqid];
7830     if (prop) {
7831       for (var i=0; prop.running > 0 && i < prop.requests.length; i++) {
7832         if (prop.requests[i].abort)
7833           prop.requests[i].abort();
7834       }
7835
7836       prop.running = 0;
7837       prop.cancelled = true;
7838       this.set_busy(false, '', prop.lock);
7839     }
7840   };
7841
0501b6 7842   // post the given form to a hidden iframe
T 7843   this.async_upload_form = function(form, action, onload)
7844   {
a41aaf 7845     // create hidden iframe
AM 7846     var ts = new Date().getTime(),
7847       frame_name = 'rcmupload' + ts,
7848       frame = this.async_upload_form_frame(frame_name);
0501b6 7849
4171c5 7850     // upload progress support
A 7851     if (this.env.upload_progress_name) {
7852       var fname = this.env.upload_progress_name,
7853         field = $('input[name='+fname+']', form);
7854
7855       if (!field.length) {
7856         field = $('<input>').attr({type: 'hidden', name: fname});
65b61c 7857         field.prependTo(form);
4171c5 7858       }
A 7859
7860       field.val(ts);
7861     }
7862
a41aaf 7863     // handle upload errors by parsing iframe content in onload
ff993e 7864     frame.bind('load', {ts:ts}, onload);
0501b6 7865
c269b4 7866     $(form).attr({
A 7867         target: frame_name,
3cc1af 7868         action: this.url(action, {_id: this.env.compose_id || '', _uploadid: ts, _from: this.env.action}),
c269b4 7869         method: 'POST'})
A 7870       .attr(form.encoding ? 'encoding' : 'enctype', 'multipart/form-data')
7871       .submit();
b649c4 7872
A 7873     return frame_name;
0501b6 7874   };
ecf295 7875
a41aaf 7876   // create iframe element for files upload
AM 7877   this.async_upload_form_frame = function(name)
7878   {
7879     return $('<iframe>').attr({name: name, style: 'border: none; width: 0; height: 0; visibility: hidden'})
7880       .appendTo(document.body);
7881   };
7882
ae6d2d 7883   // html5 file-drop API
TB 7884   this.document_drag_hover = function(e, over)
7885   {
7886     e.preventDefault();
10a397 7887     $(this.gui_objects.filedrop)[(over?'addClass':'removeClass')]('active');
ae6d2d 7888   };
TB 7889
7890   this.file_drag_hover = function(e, over)
7891   {
7892     e.preventDefault();
7893     e.stopPropagation();
10a397 7894     $(this.gui_objects.filedrop)[(over?'addClass':'removeClass')]('hover');
ae6d2d 7895   };
TB 7896
7897   // handler when files are dropped to a designated area.
7898   // compose a multipart form data and submit it to the server
7899   this.file_dropped = function(e)
7900   {
7901     // abort event and reset UI
7902     this.file_drag_hover(e, false);
7903
7904     // prepare multipart form data composition
7905     var files = e.target.files || e.dataTransfer.files,
7906       formdata = window.FormData ? new FormData() : null,
0be8bd 7907       fieldname = (this.env.filedrop.fieldname || '_file') + (this.env.filedrop.single ? '' : '[]'),
ae6d2d 7908       boundary = '------multipartformboundary' + (new Date).getTime(),
TB 7909       dashdash = '--', crlf = '\r\n',
7910       multipart = dashdash + boundary + crlf;
7911
d1d056 7912     if (!files || !files.length)
ae6d2d 7913       return;
TB 7914
7915     // inline function to submit the files to the server
7916     var submit_data = function() {
7917       var multiple = files.length > 1,
7918         ts = new Date().getTime(),
7919         content = '<span>' + (multiple ? ref.get_label('uploadingmany') : files[0].name) + '</span>';
7920
7921       // add to attachments list
0be8bd 7922       if (!ref.add2attachment_list(ts, { name:'', html:content, classname:'uploading', complete:false }))
TB 7923         ref.file_upload_id = ref.set_busy(true, 'uploading');
ae6d2d 7924
TB 7925       // complete multipart content and post request
7926       multipart += dashdash + boundary + dashdash + crlf;
7927
7928       $.ajax({
7929         type: 'POST',
7930         dataType: 'json',
9fa836 7931         url: ref.url(ref.env.filedrop.action || 'upload', {_id: ref.env.compose_id||ref.env.cid||'', _uploadid: ts, _remote: 1, _from: ref.env.action}),
ae6d2d 7932         contentType: formdata ? false : 'multipart/form-data; boundary=' + boundary,
TB 7933         processData: false,
99e17f 7934         timeout: 0, // disable default timeout set in ajaxSetup()
ae6d2d 7935         data: formdata || multipart,
962054 7936         headers: {'X-Roundcube-Request': ref.env.request_token},
988840 7937         xhr: function() { var xhr = jQuery.ajaxSettings.xhr(); if (!formdata && xhr.sendAsBinary) xhr.send = xhr.sendAsBinary; return xhr; },
ae6d2d 7938         success: function(data){ ref.http_response(data); },
TB 7939         error: function(o, status, err) { ref.http_error(o, status, err, null, 'attachment'); }
7940       });
7941     };
7942
7943     // get contents of all dropped files
7944     var last = this.env.filedrop.single ? 0 : files.length - 1;
0be8bd 7945     for (var j=0, i=0, f; j <= last && (f = files[i]); i++) {
ae6d2d 7946       if (!f.name) f.name = f.fileName;
TB 7947       if (!f.size) f.size = f.fileSize;
7948       if (!f.type) f.type = 'application/octet-stream';
7949
9df79d 7950       // file name contains non-ASCII characters, do UTF8-binary string conversion.
ae6d2d 7951       if (!formdata && /[^\x20-\x7E]/.test(f.name))
TB 7952         f.name_bin = unescape(encodeURIComponent(f.name));
7953
9df79d 7954       // filter by file type if requested
ae6d2d 7955       if (this.env.filedrop.filter && !f.type.match(new RegExp(this.env.filedrop.filter))) {
TB 7956         // TODO: show message to user
7957         continue;
7958       }
7959
9df79d 7960       // do it the easy way with FormData (FF 4+, Chrome 5+, Safari 5+)
ae6d2d 7961       if (formdata) {
0be8bd 7962         formdata.append(fieldname, f);
TB 7963         if (j == last)
ae6d2d 7964           return submit_data();
TB 7965       }
7966       // use FileReader supporetd by Firefox 3.6
7967       else if (window.FileReader) {
7968         var reader = new FileReader();
7969
7970         // closure to pass file properties to async callback function
0be8bd 7971         reader.onload = (function(file, j) {
ae6d2d 7972           return function(e) {
0be8bd 7973             multipart += 'Content-Disposition: form-data; name="' + fieldname + '"';
ae6d2d 7974             multipart += '; filename="' + (f.name_bin || file.name) + '"' + crlf;
TB 7975             multipart += 'Content-Length: ' + file.size + crlf;
7976             multipart += 'Content-Type: ' + file.type + crlf + crlf;
988840 7977             multipart += reader.result + crlf;
ae6d2d 7978             multipart += dashdash + boundary + crlf;
TB 7979
0be8bd 7980             if (j == last)  // we're done, submit the data
ae6d2d 7981               return submit_data();
TB 7982           }
0be8bd 7983         })(f,j);
ae6d2d 7984         reader.readAsBinaryString(f);
TB 7985       }
7986       // Firefox 3
7987       else if (f.getAsBinary) {
0be8bd 7988         multipart += 'Content-Disposition: form-data; name="' + fieldname + '"';
ae6d2d 7989         multipart += '; filename="' + (f.name_bin || f.name) + '"' + crlf;
TB 7990         multipart += 'Content-Length: ' + f.size + crlf;
7991         multipart += 'Content-Type: ' + f.type + crlf + crlf;
7992         multipart += f.getAsBinary() + crlf;
7993         multipart += dashdash + boundary +crlf;
7994
0be8bd 7995         if (j == last)
ae6d2d 7996           return submit_data();
TB 7997       }
0be8bd 7998
TB 7999       j++;
ae6d2d 8000     }
TB 8001   };
8002
c442f8 8003   // starts interval for keep-alive signal
f52c93 8004   this.start_keepalive = function()
8fa922 8005   {
77de23 8006     if (!this.env.session_lifetime || this.env.framed || this.env.extwin || this.task == 'login' || this.env.action == 'print')
390959 8007       return;
A 8008
77de23 8009     if (this._keepalive)
AM 8010       clearInterval(this._keepalive);
488074 8011
77de23 8012     this._keepalive = setInterval(function(){ ref.keep_alive(); }, this.env.session_lifetime * 0.5 * 1000);
AM 8013   };
8014
8015   // starts interval for refresh signal
8016   this.start_refresh = function()
8017   {
f22654 8018     if (!this.env.refresh_interval || this.env.framed || this.env.extwin || this.task == 'login' || this.env.action == 'print')
77de23 8019       return;
AM 8020
8021     if (this._refresh)
8022       clearInterval(this._refresh);
8023
f22654 8024     this._refresh = setInterval(function(){ ref.refresh(); }, this.env.refresh_interval * 1000);
93a35c 8025   };
A 8026
8027   // sends keep-alive signal
8028   this.keep_alive = function()
8029   {
8030     if (!this.busy)
8031       this.http_request('keep-alive');
488074 8032   };
A 8033
77de23 8034   // sends refresh signal
AM 8035   this.refresh = function()
8fa922 8036   {
77de23 8037     if (this.busy) {
AM 8038       // try again after 10 seconds
8039       setTimeout(function(){ ref.refresh(); ref.start_refresh(); }, 10000);
aade7b 8040       return;
5e9a56 8041     }
T 8042
77de23 8043     var params = {}, lock = this.set_busy(true, 'refreshing');
2e1809 8044
77de23 8045     if (this.task == 'mail' && this.gui_objects.mailboxlist)
AM 8046       params = this.check_recent_params();
8047
b461a2 8048     params._last = Math.floor(this.env.lastrefresh.getTime() / 1000);
TB 8049     this.env.lastrefresh = new Date();
8050
77de23 8051     // plugins should bind to 'requestrefresh' event to add own params
a59499 8052     this.http_post('refresh', params, lock);
77de23 8053   };
AM 8054
8055   // returns check-recent request parameters
8056   this.check_recent_params = function()
8057   {
8058     var params = {_mbox: this.env.mailbox};
8059
8060     if (this.gui_objects.mailboxlist)
8061       params._folderlist = 1;
8062     if (this.gui_objects.quotadisplay)
8063       params._quota = 1;
8064     if (this.env.search_request)
8065       params._search = this.env.search_request;
8066
ac0fc3 8067     if (this.gui_objects.messagelist) {
AM 8068       params._list = 1;
8069
8070       // message uids for flag updates check
8071       params._uids = $.map(this.message_list.rows, function(row, uid) { return uid; }).join(',');
8072     }
8073
77de23 8074     return params;
8fa922 8075   };
4e17e6 8076
T 8077
8078   /********************************************************/
8079   /*********            helper methods            *********/
8080   /********************************************************/
8fa922 8081
2d6242 8082   /**
TB 8083    * Quote html entities
8084    */
8085   this.quote_html = function(str)
8086   {
8087     return String(str).replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
8088   };
8089
32da69 8090   // get window.opener.rcmail if available
5a8473 8091   this.opener = function(deep, filter)
32da69 8092   {
5a8473 8093     var i, win = window.opener;
AM 8094
32da69 8095     // catch Error: Permission denied to access property rcmail
AM 8096     try {
5a8473 8097       if (win && !win.closed) {
AM 8098         // try parent of the opener window, e.g. preview frame
8099         if (deep && (!win.rcmail || win.rcmail.env.framed) && win.parent && win.parent.rcmail)
8100           win = win.parent;
8101
8102         if (win.rcmail && filter)
8103           for (i in filter)
8104             if (win.rcmail.env[i] != filter[i])
8105               return;
8106
8107         return win.rcmail;
8108       }
32da69 8109     }
AM 8110     catch (e) {}
8111   };
8112
4e17e6 8113   // check if we're in show mode or if we have a unique selection
T 8114   // and return the message uid
8115   this.get_single_uid = function()
8fa922 8116   {
9d693a 8117     var uid = this.env.uid || (this.message_list ? this.message_list.get_single_selection() : null);
J 8118     var result = ref.triggerEvent('get_single_uid', { uid: uid });
8119     return result || uid;
8fa922 8120   };
4e17e6 8121
T 8122   // same as above but for contacts
8123   this.get_single_cid = function()
8fa922 8124   {
9d693a 8125     var cid = this.env.cid || (this.contact_list ? this.contact_list.get_single_selection() : null);
J 8126     var result = ref.triggerEvent('get_single_cid', { cid: cid });
8127     return result || cid;
8fa922 8128   };
4e17e6 8129
9684dc 8130   // get the IMP mailbox of the message with the given UID
T 8131   this.get_message_mailbox = function(uid)
8132   {
3d0747 8133     var msg = (this.env.messages && uid ? this.env.messages[uid] : null) || {};
9684dc 8134     return msg.mbox || this.env.mailbox;
378efd 8135   };
9684dc 8136
602d74 8137   // build request parameters from single message id (maybe with mailbox name)
AM 8138   this.params_from_uid = function(uid, params)
8139   {
8140     if (!params)
8141       params = {};
8142
8143     params._uid = String(uid).split('-')[0];
8144     params._mbox = this.get_message_mailbox(uid);
8145
8146     return params;
8147   };
8148
8fa922 8149   // gets cursor position
4e17e6 8150   this.get_caret_pos = function(obj)
8fa922 8151   {
d8cf6d 8152     if (obj.selectionEnd !== undefined)
4e17e6 8153       return obj.selectionEnd;
3c047d 8154
AM 8155     return obj.value.length;
8fa922 8156   };
4e17e6 8157
8fa922 8158   // moves cursor to specified position
40418d 8159   this.set_caret_pos = function(obj, pos)
8fa922 8160   {
378efd 8161     try {
AM 8162       if (obj.setSelectionRange)
8163         obj.setSelectionRange(pos, pos);
40418d 8164     }
10a397 8165     catch(e) {} // catch Firefox exception if obj is hidden
8fa922 8166   };
4e17e6 8167
0b1de8 8168   // get selected text from an input field
TB 8169   this.get_input_selection = function(obj)
8170   {
378efd 8171     var start = 0, end = 0, normalizedValue = '';
0b1de8 8172
TB 8173     if (typeof obj.selectionStart == "number" && typeof obj.selectionEnd == "number") {
2d6242 8174       normalizedValue = obj.value;
TB 8175       start = obj.selectionStart;
8176       end = obj.selectionEnd;
8177     }
0b1de8 8178
378efd 8179     return {start: start, end: end, text: normalizedValue.substr(start, end-start)};
0b1de8 8180   };
TB 8181
b0d46b 8182   // disable/enable all fields of a form
4e17e6 8183   this.lock_form = function(form, lock)
8fa922 8184   {
4e17e6 8185     if (!form || !form.elements)
T 8186       return;
8fa922 8187
b0d46b 8188     var n, len, elm;
A 8189
8190     if (lock)
8191       this.disabled_form_elements = [];
8192
8193     for (n=0, len=form.elements.length; n<len; n++) {
8194       elm = form.elements[n];
8195
8196       if (elm.type == 'hidden')
4e17e6 8197         continue;
b0d46b 8198       // remember which elem was disabled before lock
A 8199       if (lock && elm.disabled)
8200         this.disabled_form_elements.push(elm);
378efd 8201       else if (lock || $.inArray(elm, this.disabled_form_elements) < 0)
b0d46b 8202         elm.disabled = lock;
8fa922 8203     }
A 8204   };
8205
06c990 8206   this.mailto_handler_uri = function()
A 8207   {
8208     return location.href.split('?')[0] + '?_task=mail&_action=compose&_to=%s';
8209   };
8210
8211   this.register_protocol_handler = function(name)
8212   {
8213     try {
8214       window.navigator.registerProtocolHandler('mailto', this.mailto_handler_uri(), name);
8215     }
d22157 8216     catch(e) {
TB 8217       this.display_message(String(e), 'error');
10a397 8218     }
06c990 8219   };
A 8220
8221   this.check_protocol_handler = function(name, elem)
8222   {
8223     var nav = window.navigator;
10a397 8224
d22157 8225     if (!nav || (typeof nav.registerProtocolHandler != 'function')) {
TB 8226       $(elem).addClass('disabled').click(function(){ return false; });
8227     }
10a397 8228     else if (typeof nav.isProtocolHandlerRegistered == 'function') {
AM 8229       var status = nav.isProtocolHandlerRegistered('mailto', this.mailto_handler_uri());
8230       if (status)
8231         $(elem).parent().find('.mailtoprotohandler-status').html(status);
8232     }
d22157 8233     else {
10a397 8234       $(elem).click(function() { ref.register_protocol_handler(name); return false; });
d22157 8235     }
06c990 8236   };
A 8237
e349a8 8238   // Checks browser capabilities eg. PDF support, TIF support
AM 8239   this.browser_capabilities_check = function()
8240   {
8241     if (!this.env.browser_capabilities)
8242       this.env.browser_capabilities = {};
8243
8244     if (this.env.browser_capabilities.pdf === undefined)
8245       this.env.browser_capabilities.pdf = this.pdf_support_check();
8246
b9854b 8247     if (this.env.browser_capabilities.flash === undefined)
AM 8248       this.env.browser_capabilities.flash = this.flash_support_check();
8249
e349a8 8250     if (this.env.browser_capabilities.tif === undefined)
AM 8251       this.tif_support_check();
8252   };
8253
8254   // Returns browser capabilities string
8255   this.browser_capabilities = function()
8256   {
8257     if (!this.env.browser_capabilities)
8258       return '';
8259
8260     var n, ret = [];
8261
8262     for (n in this.env.browser_capabilities)
8263       ret.push(n + '=' + this.env.browser_capabilities[n]);
8264
8265     return ret.join();
8266   };
8267
8268   this.tif_support_check = function()
8269   {
8270     var img = new Image();
8271
f1aaca 8272     img.onload = function() { ref.env.browser_capabilities.tif = 1; };
AM 8273     img.onerror = function() { ref.env.browser_capabilities.tif = 0; };
681ba6 8274     img.src = this.assets_path('program/resources/blank.tif');
e349a8 8275   };
AM 8276
8277   this.pdf_support_check = function()
8278   {
8279     var plugin = navigator.mimeTypes ? navigator.mimeTypes["application/pdf"] : {},
8280       plugins = navigator.plugins,
8281       len = plugins.length,
8282       regex = /Adobe Reader|PDF|Acrobat/i;
8283
8284     if (plugin && plugin.enabledPlugin)
8285         return 1;
8286
b6b285 8287     if ('ActiveXObject' in window) {
e349a8 8288       try {
10a397 8289         if (plugin = new ActiveXObject("AcroPDF.PDF"))
e349a8 8290           return 1;
AM 8291       }
8292       catch (e) {}
8293       try {
10a397 8294         if (plugin = new ActiveXObject("PDF.PdfCtrl"))
e349a8 8295           return 1;
AM 8296       }
8297       catch (e) {}
8298     }
8299
8300     for (i=0; i<len; i++) {
8301       plugin = plugins[i];
8302       if (typeof plugin === 'String') {
8303         if (regex.test(plugin))
8304           return 1;
8305       }
8306       else if (plugin.name && regex.test(plugin.name))
8307         return 1;
8308     }
8309
8310     return 0;
8311   };
8312
b9854b 8313   this.flash_support_check = function()
AM 8314   {
8315     var plugin = navigator.mimeTypes ? navigator.mimeTypes["application/x-shockwave-flash"] : {};
8316
8317     if (plugin && plugin.enabledPlugin)
8318         return 1;
8319
b6b285 8320     if ('ActiveXObject' in window) {
b9854b 8321       try {
10a397 8322         if (plugin = new ActiveXObject("ShockwaveFlash.ShockwaveFlash"))
b9854b 8323           return 1;
AM 8324       }
8325       catch (e) {}
8326     }
8327
8328     return 0;
8329   };
8330
681ba6 8331   this.assets_path = function(path)
AM 8332   {
8333     if (this.env.assets_path && !path.startsWith(this.env.assets_path)) {
8334       path = this.env.assets_path + path;
8335     }
8336
8337     return path;
8338   };
8339
ae7027 8340   // Cookie setter
AM 8341   this.set_cookie = function(name, value, expires)
8342   {
8343     setCookie(name, value, expires, this.env.cookie_path, this.env.cookie_domain, this.env.cookie_secure);
85e60a 8344   };
TB 8345
078679 8346   this.get_local_storage_prefix = function()
TB 8347   {
8348     if (!this.local_storage_prefix)
8349       this.local_storage_prefix = 'roundcube.' + (this.env.user_id || 'anonymous') + '.';
8350
8351     return this.local_storage_prefix;
8352   };
8353
85e60a 8354   // wrapper for localStorage.getItem(key)
TB 8355   this.local_storage_get_item = function(key, deflt, encrypted)
8356   {
56040b 8357     var item, result;
b0b9cf 8358
85e60a 8359     // TODO: add encryption
b0b9cf 8360     try {
AM 8361       item = localStorage.getItem(this.get_local_storage_prefix() + key);
56040b 8362       result = JSON.parse(item);
b0b9cf 8363     }
AM 8364     catch (e) { }
8365
56040b 8366     return result || deflt || null;
85e60a 8367   };
TB 8368
8369   // wrapper for localStorage.setItem(key, data)
8370   this.local_storage_set_item = function(key, data, encrypted)
8371   {
b0b9cf 8372     // try/catch to handle no localStorage support, but also error
AM 8373     // in Safari-in-private-browsing-mode where localStorage exists
8374     // but can't be used (#1489996)
8375     try {
8376       // TODO: add encryption
8377       localStorage.setItem(this.get_local_storage_prefix() + key, JSON.stringify(data));
8378       return true;
8379     }
8380     catch (e) {
8381       return false;
8382     }
85e60a 8383   };
TB 8384
8385   // wrapper for localStorage.removeItem(key)
8386   this.local_storage_remove_item = function(key)
8387   {
b0b9cf 8388     try {
AM 8389       localStorage.removeItem(this.get_local_storage_prefix() + key);
8390       return true;
8391     }
8392     catch (e) {
8393       return false;
8394     }
85e60a 8395   };
f7af22 8396
AM 8397   this.print_dialog = function()
8398   {
8399     if (bw.safari)
8400       setTimeout('window.print()', 10);
8401     else
8402       window.print();
8403   };
cc97ea 8404 }  // end object rcube_webmail
4e17e6 8405
bc3745 8406
T 8407 // some static methods
8408 rcube_webmail.long_subject_title = function(elem, indent)
8409 {
8410   if (!elem.title) {
8411     var $elem = $(elem);
31aa08 8412     if ($elem.width() + (indent || 0) * 15 > $elem.parent().width())
83b583 8413       elem.title = rcube_webmail.subject_text(elem);
bc3745 8414   }
T 8415 };
8416
7a5c3a 8417 rcube_webmail.long_subject_title_ex = function(elem)
065d70 8418 {
A 8419   if (!elem.title) {
8420     var $elem = $(elem),
eb616c 8421       txt = $.trim($elem.text()),
065d70 8422       tmp = $('<span>').text(txt)
A 8423         .css({'position': 'absolute', 'float': 'left', 'visibility': 'hidden',
8424           'font-size': $elem.css('font-size'), 'font-weight': $elem.css('font-weight')})
8425         .appendTo($('body')),
8426       w = tmp.width();
8427
8428     tmp.remove();
7a5c3a 8429     if (w + $('span.branch', $elem).width() * 15 > $elem.width())
83b583 8430       elem.title = rcube_webmail.subject_text(elem);
065d70 8431   }
A 8432 };
8433
83b583 8434 rcube_webmail.subject_text = function(elem)
AM 8435 {
8436   var t = $(elem).clone();
8437   t.find('.skip-on-drag').remove();
8438   return t.text();
8439 };
8440
ae7027 8441 rcube_webmail.prototype.get_cookie = getCookie;
AM 8442
cc97ea 8443 // copy event engine prototype
T 8444 rcube_webmail.prototype.addEventListener = rcube_event_engine.prototype.addEventListener;
8445 rcube_webmail.prototype.removeEventListener = rcube_event_engine.prototype.removeEventListener;
8446 rcube_webmail.prototype.triggerEvent = rcube_event_engine.prototype.triggerEvent;