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