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