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