]> git.donarmstrong.com Git - roundcube.git/blob - program/js/app.js.src
Imported Upstream version 0.7
[roundcube.git] / program / js / app.js.src
1 /*
2  +-----------------------------------------------------------------------+
3  | Roundcube Webmail Client Script                                       |
4  |                                                                       |
5  | This file is part of the Roundcube Webmail client                     |
6  | Copyright (C) 2005-2011, The Roundcube Dev Team                       |
7  | Copyright (C) 2011, Kolab Systems AG                                  |
8  | Licensed under the GNU GPL                                            |
9  |                                                                       |
10  +-----------------------------------------------------------------------+
11  | Authors: Thomas Bruederli <roundcube@gmail.com>                       |
12  |          Aleksander 'A.L.E.C' Machniak <alec@alec.pl>                 |
13  |          Charles McNulty <charles@charlesmcnulty.com>                 |
14  +-----------------------------------------------------------------------+
15  | Requires: jquery.js, common.js, list.js                               |
16  +-----------------------------------------------------------------------+
17
18   $Id: app.js 5554 2011-12-07 07:50:00Z alec $
19 */
20
21 function rcube_webmail()
22 {
23   this.env = { recipients_separator:',', recipients_delimiter:', ' };
24   this.labels = {};
25   this.buttons = {};
26   this.buttons_sel = {};
27   this.gui_objects = {};
28   this.gui_containers = {};
29   this.commands = {};
30   this.command_handlers = {};
31   this.onloads = [];
32   this.messages = {};
33
34   // create protected reference to myself
35   this.ref = 'rcmail';
36   var ref = this;
37
38   // webmail client settings
39   this.dblclick_time = 500;
40   this.message_time = 4000;
41
42   this.identifier_expr = new RegExp('[^0-9a-z\-_]', 'gi');
43
44   // default environment vars
45   this.env.keep_alive = 60;        // seconds
46   this.env.request_timeout = 180;  // seconds
47   this.env.draft_autosave = 0;     // seconds
48   this.env.comm_path = './';
49   this.env.blankpage = 'program/blank.gif';
50
51   // set jQuery ajax options
52   $.ajaxSetup({
53     cache:false,
54     error:function(request, status, err){ ref.http_error(request, status, err); },
55     beforeSend:function(xmlhttp){ xmlhttp.setRequestHeader('X-Roundcube-Request', ref.env.request_token); }
56   });
57
58   // set environment variable(s)
59   this.set_env = function(p, value)
60   {
61     if (p != null && typeof p === 'object' && !value)
62       for (var n in p)
63         this.env[n] = p[n];
64     else
65       this.env[p] = value;
66   };
67
68   // add a localized label to the client environment
69   this.add_label = function(p, value)
70   {
71     if (typeof p == 'string')
72       this.labels[p] = value;
73     else if (typeof p == 'object')
74       $.extend(this.labels, p);
75   };
76
77   // add a button to the button list
78   this.register_button = function(command, id, type, act, sel, over)
79   {
80     if (!this.buttons[command])
81       this.buttons[command] = [];
82
83     var button_prop = {id:id, type:type};
84     if (act) button_prop.act = act;
85     if (sel) button_prop.sel = sel;
86     if (over) button_prop.over = over;
87
88     this.buttons[command].push(button_prop);
89
90     if (this.loaded)
91       init_button(command, button_prop);
92   };
93
94   // register a specific gui object
95   this.gui_object = function(name, id)
96   {
97     this.gui_objects[name] = this.loaded ? rcube_find_object(id) : id;
98   };
99
100   // register a container object
101   this.gui_container = function(name, id)
102   {
103     this.gui_containers[name] = id;
104   };
105
106   // add a GUI element (html node) to a specified container
107   this.add_element = function(elm, container)
108   {
109     if (this.gui_containers[container] && this.gui_containers[container].jquery)
110       this.gui_containers[container].append(elm);
111   };
112
113   // register an external handler for a certain command
114   this.register_command = function(command, callback, enable)
115   {
116     this.command_handlers[command] = callback;
117
118     if (enable)
119       this.enable_command(command, true);
120   };
121
122   // execute the given script on load
123   this.add_onload = function(f)
124   {
125     this.onloads.push(f);
126   };
127
128   // initialize webmail client
129   this.init = function()
130   {
131     var n, p = this;
132     this.task = this.env.task;
133
134     // check browser
135     if (!bw.dom || !bw.xmlhttp_test()) {
136       this.goto_url('error', '_code=0x199');
137       return;
138     }
139
140     // find all registered gui containers
141     for (n in this.gui_containers)
142       this.gui_containers[n] = $('#'+this.gui_containers[n]);
143
144     // find all registered gui objects
145     for (n in this.gui_objects)
146       this.gui_objects[n] = rcube_find_object(this.gui_objects[n]);
147
148     // clickjacking protection
149     if (this.env.x_frame_options) {
150       try {
151         // bust frame if not allowed
152         if (this.env.x_frame_options == 'deny' && top.location.href != self.location.href)
153           top.location.href = self.location.href;
154         else if (top.location.hostname != self.location.hostname)
155           throw 1;
156       } catch (e) {
157         // possible clickjacking attack: disable all form elements
158         $('form').each(function(){ ref.lock_form(this, true); });
159         this.display_message("Blocked: possible clickjacking attack!", 'error');
160         return;
161       }
162     }
163
164     // init registered buttons
165     this.init_buttons();
166
167     // tell parent window that this frame is loaded
168     if (this.is_framed()) {
169       parent.rcmail.set_busy(false, null, parent.rcmail.env.frame_lock);
170       parent.rcmail.env.frame_lock = null;
171     }
172
173     // enable general commands
174     this.enable_command('logout', 'mail', 'addressbook', 'settings', 'save-pref', 'compose', 'undo', true);
175
176     if (this.env.permaurl)
177       this.enable_command('permaurl', true);
178
179     switch (this.task) {
180
181       case 'mail':
182         // enable mail commands
183         this.enable_command('list', 'checkmail', 'add-contact', 'search', 'reset-search', 'collapse-folder', true);
184
185         if (this.gui_objects.messagelist) {
186
187           this.message_list = new rcube_list_widget(this.gui_objects.messagelist, {
188             multiselect:true, multiexpand:true, draggable:true, keyboard:true,
189             column_movable:this.env.col_movable, dblclick_time:this.dblclick_time
190             });
191           this.message_list.row_init = function(o){ p.init_message_row(o); };
192           this.message_list.addEventListener('dblclick', function(o){ p.msglist_dbl_click(o); });
193           this.message_list.addEventListener('click', function(o){ p.msglist_click(o); });
194           this.message_list.addEventListener('keypress', function(o){ p.msglist_keypress(o); });
195           this.message_list.addEventListener('select', function(o){ p.msglist_select(o); });
196           this.message_list.addEventListener('dragstart', function(o){ p.drag_start(o); });
197           this.message_list.addEventListener('dragmove', function(e){ p.drag_move(e); });
198           this.message_list.addEventListener('dragend', function(e){ p.drag_end(e); });
199           this.message_list.addEventListener('expandcollapse', function(e){ p.msglist_expand(e); });
200           this.message_list.addEventListener('column_replace', function(e){ p.msglist_set_coltypes(e); });
201
202           document.onmouseup = function(e){ return p.doc_mouse_up(e); };
203           this.gui_objects.messagelist.parentNode.onmousedown = function(e){ return p.click_on_list(e); };
204
205           this.message_list.init();
206           this.enable_command('toggle_status', 'toggle_flag', 'menu-open', 'menu-save', true);
207
208           // load messages
209           this.command('list');
210         }
211
212         if (this.gui_objects.qsearchbox) {
213           if (this.env.search_text != null) {
214             this.gui_objects.qsearchbox.value = this.env.search_text;
215           }
216           $(this.gui_objects.qsearchbox).focusin(function() { rcmail.message_list.blur(); });
217         }
218
219         if (!this.env.flag_for_deletion && this.env.trash_mailbox && this.env.mailbox != this.env.trash_mailbox)
220           this.set_alttext('delete', 'movemessagetotrash');
221
222         this.env.message_commands = ['show', 'reply', 'reply-all', 'reply-list', 'forward',
223           'moveto', 'copy', 'delete', 'open', 'mark', 'edit', 'viewsource', 'download',
224           'print', 'load-attachment', 'load-headers', 'forward-attachment'];
225
226         if (this.env.action == 'show' || this.env.action == 'preview') {
227           this.enable_command(this.env.message_commands, this.env.uid);
228           this.enable_command('reply-list', this.env.list_post);
229
230           if (this.env.action == 'show') {
231             this.http_request('pagenav', '_uid='+this.env.uid+'&_mbox='+urlencode(this.env.mailbox)
232               + (this.env.search_request ? '&_search='+this.env.search_request : ''),
233               this.display_message('', 'loading'));
234           }
235
236           if (this.env.blockedobjects) {
237             if (this.gui_objects.remoteobjectsmsg)
238               this.gui_objects.remoteobjectsmsg.style.display = 'block';
239             this.enable_command('load-images', 'always-load', true);
240           }
241
242           // make preview/message frame visible
243           if (this.env.action == 'preview' && this.is_framed()) {
244             this.enable_command('compose', 'add-contact', false);
245             parent.rcmail.show_contentframe(true);
246           }
247         }
248         else if (this.env.action == 'compose') {
249           this.env.compose_commands = ['send-attachment', 'remove-attachment', 'send', 'cancel', 'toggle-editor'];
250
251           if (this.env.drafts_mailbox)
252             this.env.compose_commands.push('savedraft')
253
254           this.enable_command(this.env.compose_commands, 'identities', true);
255
256           if (this.env.spellcheck) {
257             this.env.spellcheck.spelling_state_observer = function(s){ ref.set_spellcheck_state(s); };
258             this.env.compose_commands.push('spellcheck')
259             this.set_spellcheck_state('ready');
260             if ($("input[name='_is_html']").val() == '1')
261               this.display_spellcheck_controls(false);
262           }
263
264           document.onmouseup = function(e){ return p.doc_mouse_up(e); };
265
266           // init message compose form
267           this.init_messageform();
268         }
269         // show printing dialog
270         else if (this.env.action == 'print' && this.env.uid)
271           if (bw.safari)
272             window.setTimeout('window.print()', 10);
273           else
274             window.print();
275
276         // get unread count for each mailbox
277         if (this.gui_objects.mailboxlist) {
278           this.env.unread_counts = {};
279           this.gui_objects.folderlist = this.gui_objects.mailboxlist;
280           this.http_request('getunread', '');
281         }
282
283         // ask user to send MDN
284         if (this.env.mdn_request && this.env.uid) {
285           var mdnurl = '_uid='+this.env.uid+'&_mbox='+urlencode(this.env.mailbox);
286           if (confirm(this.get_label('mdnrequest')))
287             this.http_post('sendmdn', mdnurl);
288           else
289             this.http_post('mark', mdnurl+'&_flag=mdnsent');
290         }
291
292         break;
293
294       case 'addressbook':
295         if (this.gui_objects.folderlist)
296           this.env.contactfolders = $.extend($.extend({}, this.env.address_sources), this.env.contactgroups);
297
298         this.enable_command('add', 'import', this.env.writable_source);
299         this.enable_command('list', 'listgroup', 'listsearch', 'advanced-search', true);
300
301         if (this.gui_objects.contactslist) {
302
303           this.contact_list = new rcube_list_widget(this.gui_objects.contactslist,
304             {multiselect:true, draggable:this.gui_objects.folderlist?true:false, keyboard:true});
305           this.contact_list.row_init = function(row){ p.triggerEvent('insertrow', { cid:row.uid, row:row }); };
306           this.contact_list.addEventListener('keypress', function(o){ p.contactlist_keypress(o); });
307           this.contact_list.addEventListener('select', function(o){ p.contactlist_select(o); });
308           this.contact_list.addEventListener('dragstart', function(o){ p.drag_start(o); });
309           this.contact_list.addEventListener('dragmove', function(e){ p.drag_move(e); });
310           this.contact_list.addEventListener('dragend', function(e){ p.drag_end(e); });
311           this.contact_list.init();
312
313           if (this.env.cid)
314             this.contact_list.highlight_row(this.env.cid);
315
316           this.gui_objects.contactslist.parentNode.onmousedown = function(e){ return p.click_on_list(e); };
317           document.onmouseup = function(e){ return p.doc_mouse_up(e); };
318           if (this.gui_objects.qsearchbox) {
319             $(this.gui_objects.qsearchbox).focusin(function() { rcmail.contact_list.blur(); });
320           }
321
322           this.update_group_commands();
323           this.command('list');
324         }
325
326         this.set_page_buttons();
327
328         if (this.env.cid) {
329           this.enable_command('show', 'edit', true);
330           // register handlers for group assignment via checkboxes
331           if (this.gui_objects.editform) {
332             $('input.groupmember').change(function() {
333               ref.group_member_change(this.checked ? 'add' : 'del', ref.env.cid, ref.env.source, this.value);
334             });
335           }
336         }
337
338         if (this.gui_objects.editform) {
339           this.enable_command('save', true);
340           if (this.env.action == 'add' || this.env.action == 'edit')
341               this.init_contact_form();
342         }
343
344         if (this.gui_objects.qsearchbox) {
345           this.enable_command('search', 'reset-search', 'moveto', true);
346         }
347
348         break;
349
350       case 'settings':
351         this.enable_command('preferences', 'identities', 'save', 'folders', true);
352
353         if (this.env.action == 'identities') {
354           this.enable_command('add', this.env.identities_level < 2);
355         }
356         else if (this.env.action == 'edit-identity' || this.env.action == 'add-identity') {
357           this.enable_command('add', this.env.identities_level < 2);
358           this.enable_command('save', 'delete', 'edit', 'toggle-editor', true);
359         }
360         else if (this.env.action == 'folders') {
361           this.enable_command('subscribe', 'unsubscribe', 'create-folder', 'rename-folder', true);
362         }
363         else if (this.env.action == 'edit-folder' && this.gui_objects.editform) {
364           this.enable_command('save', 'folder-size', true);
365           parent.rcmail.env.messagecount = this.env.messagecount;
366           parent.rcmail.enable_command('purge', this.env.messagecount);
367           $("input[type='text']").first().select();
368         }
369
370         if (this.gui_objects.identitieslist) {
371           this.identity_list = new rcube_list_widget(this.gui_objects.identitieslist, {multiselect:false, draggable:false, keyboard:false});
372           this.identity_list.addEventListener('select', function(o){ p.identity_select(o); });
373           this.identity_list.init();
374           this.identity_list.focus();
375
376           if (this.env.iid)
377             this.identity_list.highlight_row(this.env.iid);
378         }
379         else if (this.gui_objects.sectionslist) {
380           this.sections_list = new rcube_list_widget(this.gui_objects.sectionslist, {multiselect:false, draggable:false, keyboard:false});
381           this.sections_list.addEventListener('select', function(o){ p.section_select(o); });
382           this.sections_list.init();
383           this.sections_list.focus();
384         }
385         else if (this.gui_objects.subscriptionlist)
386           this.init_subscription_list();
387
388         break;
389
390       case 'login':
391         var input_user = $('#rcmloginuser');
392         input_user.bind('keyup', function(e){ return rcmail.login_user_keyup(e); });
393
394         if (input_user.val() == '')
395           input_user.focus();
396         else
397           $('#rcmloginpwd').focus();
398
399         // detect client timezone
400         var dt = new Date(),
401           tz = dt.getTimezoneOffset() / -60,
402           stdtz = dt.getStdTimezoneOffset() / -60;
403
404         $('#rcmlogintz').val(stdtz);
405         $('#rcmlogindst').val(tz > stdtz ? 1 : 0);
406
407         // display 'loading' message on form submit, lock submit button
408         $('form').submit(function () {
409           $('input[type=submit]', this).prop('disabled', true);
410           rcmail.display_message('', 'loading');
411         });
412
413         this.enable_command('login', true);
414         break;
415
416       default:
417         break;
418       }
419
420     // prevent from form submit with Enter key in file input fields
421     if (bw.ie)
422       $('input[type=file]').keydown(function(e) { if (e.keyCode == '13') e.preventDefault(); });
423
424     // flag object as complete
425     this.loaded = true;
426
427     // show message
428     if (this.pending_message)
429       this.display_message(this.pending_message[0], this.pending_message[1], this.pending_message[2]);
430
431     // map implicit containers
432     if (this.gui_objects.folderlist)
433       this.gui_containers.foldertray = $(this.gui_objects.folderlist);
434
435     // trigger init event hook
436     this.triggerEvent('init', { task:this.task, action:this.env.action });
437
438     // execute all foreign onload scripts
439     // @deprecated
440     for (var i in this.onloads) {
441       if (typeof this.onloads[i] === 'string')
442         eval(this.onloads[i]);
443       else if (typeof this.onloads[i] === 'function')
444         this.onloads[i]();
445       }
446
447     // start keep-alive interval
448     this.start_keepalive();
449   };
450
451   this.log = function(msg)
452   {
453     if (window.console && console.log)
454       console.log(msg);
455   };
456
457   /*********************************************************/
458   /*********       client command interface        *********/
459   /*********************************************************/
460
461   // execute a specific command on the web client
462   this.command = function(command, props, obj)
463   {
464     var ret, uid, cid, url, flag;
465
466     if (obj && obj.blur)
467       obj.blur();
468
469     if (this.busy)
470       return false;
471
472     // command not supported or allowed
473     if (!this.commands[command]) {
474       // pass command to parent window
475       if (this.is_framed())
476         parent.rcmail.command(command, props);
477
478       return false;
479     }
480
481     // check input before leaving compose step
482     if (this.task == 'mail' && this.env.action == 'compose' && $.inArray(command, this.env.compose_commands)<0) {
483       if (this.cmp_hash != this.compose_field_hash() && !confirm(this.get_label('notsentwarning')))
484         return false;
485     }
486
487     // process external commands
488     if (typeof this.command_handlers[command] === 'function') {
489       ret = this.command_handlers[command](props, obj);
490       return ret !== undefined ? ret : (obj ? false : true);
491     }
492     else if (typeof this.command_handlers[command] === 'string') {
493       ret = window[this.command_handlers[command]](props, obj);
494       return ret !== undefined ? ret : (obj ? false : true);
495     }
496
497     // trigger plugin hooks
498     this.triggerEvent('actionbefore', {props:props, action:command});
499     ret = this.triggerEvent('before'+command, props);
500     if (ret !== undefined) {
501       // abort if one of the handlers returned false
502       if (ret === false)
503         return false;
504       else
505         props = ret;
506     }
507
508     ret = undefined;
509
510     // process internal command
511     switch (command) {
512
513       case 'login':
514         if (this.gui_objects.loginform)
515           this.gui_objects.loginform.submit();
516         break;
517
518       // commands to switch task
519       case 'mail':
520       case 'addressbook':
521       case 'settings':
522       case 'logout':
523         this.switch_task(command);
524         break;
525
526       case 'permaurl':
527         if (obj && obj.href && obj.target)
528           return true;
529         else if (this.env.permaurl)
530           parent.location.href = this.env.permaurl;
531         break;
532
533       case 'menu-open':
534       case 'menu-save':
535         this.triggerEvent(command, {props:props});
536         return false;
537
538       case 'open':
539         if (uid = this.get_single_uid()) {
540           obj.href = '?_task='+this.env.task+'&_action=show&_mbox='+urlencode(this.env.mailbox)+'&_uid='+uid;
541           return true;
542         }
543         break;
544
545       case 'list':
546         this.reset_qsearch();
547         if (this.task == 'mail') {
548           this.list_mailbox(props);
549
550           if (this.env.trash_mailbox && !this.env.flag_for_deletion)
551             this.set_alttext('delete', this.env.mailbox != this.env.trash_mailbox ? 'movemessagetotrash' : 'deletemessage');
552         }
553         else if (this.task == 'addressbook') {
554           this.list_contacts(props);
555         }
556         break;
557
558       case 'load-headers':
559         this.load_headers(obj);
560         break;
561
562       case 'sort':
563         var sort_order, sort_col = props;
564
565         if (this.env.sort_col==sort_col)
566           sort_order = this.env.sort_order=='ASC' ? 'DESC' : 'ASC';
567         else
568           sort_order = 'ASC';
569
570         // set table header and update env
571         this.set_list_sorting(sort_col, sort_order);
572
573         // reload message list
574         this.list_mailbox('', '', sort_col+'_'+sort_order);
575         break;
576
577       case 'nextpage':
578         this.list_page('next');
579         break;
580
581       case 'lastpage':
582         this.list_page('last');
583         break;
584
585       case 'previouspage':
586         this.list_page('prev');
587         break;
588
589       case 'firstpage':
590         this.list_page('first');
591         break;
592
593       case 'expunge':
594         if (this.env.messagecount)
595           this.expunge_mailbox(this.env.mailbox);
596         break;
597
598       case 'purge':
599       case 'empty-mailbox':
600         if (this.env.messagecount)
601           this.purge_mailbox(this.env.mailbox);
602         break;
603
604       // common commands used in multiple tasks
605       case 'show':
606         if (this.task == 'mail') {
607           uid = this.get_single_uid();
608           if (uid && (!this.env.uid || uid != this.env.uid)) {
609             if (this.env.mailbox == this.env.drafts_mailbox)
610               this.goto_url('compose', '_draft_uid='+uid+'&_mbox='+urlencode(this.env.mailbox), true);
611             else
612               this.show_message(uid);
613           }
614         }
615         else if (this.task == 'addressbook') {
616           cid = props ? props : this.get_single_cid();
617           if (cid && !(this.env.action == 'show' && cid == this.env.cid))
618             this.load_contact(cid, 'show');
619         }
620         break;
621
622       case 'add':
623         if (this.task == 'addressbook')
624           this.load_contact(0, 'add');
625         else if (this.task == 'settings') {
626           this.identity_list.clear_selection();
627           this.load_identity(0, 'add-identity');
628         }
629         break;
630
631       case 'edit':
632         if (this.task=='addressbook' && (cid = this.get_single_cid()))
633           this.load_contact(cid, 'edit');
634         else if (this.task=='settings' && props)
635           this.load_identity(props, 'edit-identity');
636         else if (this.task=='mail' && (cid = this.get_single_uid())) {
637           url = (this.env.mailbox == this.env.drafts_mailbox) ? '_draft_uid=' : '_uid=';
638           this.goto_url('compose', url+cid+'&_mbox='+urlencode(this.env.mailbox), true);
639         }
640         break;
641
642       case 'save':
643         var input, form = this.gui_objects.editform;
644         if (form) {
645           // adv. search
646           if (this.env.action == 'search') {
647           }
648           // user prefs
649           else if ((input = $("input[name='_pagesize']", form)) && input.length && isNaN(parseInt(input.val()))) {
650             alert(this.get_label('nopagesizewarning'));
651             input.focus();
652             break;
653           }
654           // contacts/identities
655           else {
656             // reload form
657             if (props == 'reload') {
658               form.action += '?_reload=1';
659             }
660             else if (this.task == 'settings' && (this.env.identities_level % 2) == 0  &&
661               (input = $("input[name='_email']", form)) && input.length && !rcube_check_email(input.val())
662             ) {
663               alert(this.get_label('noemailwarning'));
664               input.focus();
665               break;
666             }
667
668             // clear empty input fields
669             $('input.placeholder').each(function(){ if (this.value == this._placeholder) this.value = ''; });
670           }
671
672           // add selected source (on the list)
673           if (parent.rcmail && parent.rcmail.env.source)
674             form.action = this.add_url(form.action, '_orig_source', parent.rcmail.env.source);
675
676           form.submit();
677         }
678         break;
679
680       case 'delete':
681         // mail task
682         if (this.task == 'mail')
683           this.delete_messages();
684         // addressbook task
685         else if (this.task == 'addressbook')
686           this.delete_contacts();
687         // user settings task
688         else if (this.task == 'settings')
689           this.delete_identity();
690         break;
691
692       // mail task commands
693       case 'move':
694       case 'moveto':
695         if (this.task == 'mail')
696           this.move_messages(props);
697         else if (this.task == 'addressbook' && this.drag_active)
698           this.copy_contact(null, props);
699         break;
700
701       case 'copy':
702         if (this.task == 'mail')
703           this.copy_messages(props);
704         break;
705
706       case 'mark':
707         if (props)
708           this.mark_message(props);
709         break;
710
711       case 'toggle_status':
712         if (props && !props._row)
713           break;
714
715         flag = 'read';
716
717         if (props._row.uid) {
718           uid = props._row.uid;
719
720           // toggle read/unread
721           if (this.message_list.rows[uid].deleted) {
722             flag = 'undelete';
723           }
724           else if (!this.message_list.rows[uid].unread)
725             flag = 'unread';
726         }
727
728         this.mark_message(flag, uid);
729         break;
730
731       case 'toggle_flag':
732         if (props && !props._row)
733           break;
734
735         flag = 'flagged';
736
737         if (props._row.uid) {
738           uid = props._row.uid;
739           // toggle flagged/unflagged
740           if (this.message_list.rows[uid].flagged)
741             flag = 'unflagged';
742           }
743         this.mark_message(flag, uid);
744         break;
745
746       case 'always-load':
747         if (this.env.uid && this.env.sender) {
748           this.add_contact(urlencode(this.env.sender));
749           window.setTimeout(function(){ ref.command('load-images'); }, 300);
750           break;
751         }
752
753       case 'load-images':
754         if (this.env.uid)
755           this.show_message(this.env.uid, true, this.env.action=='preview');
756         break;
757
758       case 'load-attachment':
759         var qstring = '_mbox='+urlencode(this.env.mailbox)+'&_uid='+this.env.uid+'&_part='+props.part;
760
761         // open attachment in frame if it's of a supported mimetype
762         if (this.env.uid && props.mimetype && this.env.mimetypes && $.inArray(props.mimetype, this.env.mimetypes)>=0) {
763           if (props.mimetype == 'text/html')
764             qstring += '&_safe=1';
765           this.attachment_win = window.open(this.env.comm_path+'&_action=get&'+qstring+'&_frame=1', 'rcubemailattachment');
766           if (this.attachment_win) {
767             window.setTimeout(function(){ ref.attachment_win.focus(); }, 10);
768             break;
769           }
770         }
771
772         this.goto_url('get', qstring+'&_download=1', false);
773         break;
774
775       case 'select-all':
776         this.select_all_mode = props ? false : true;
777         this.dummy_select = true; // prevent msg opening if there's only one msg on the list
778         if (props == 'invert')
779           this.message_list.invert_selection();
780         else
781           this.message_list.select_all(props == 'page' ? '' : props);
782         this.dummy_select = null;
783         break;
784
785       case 'select-none':
786         this.select_all_mode = false;
787         this.message_list.clear_selection();
788         break;
789
790       case 'expand-all':
791         this.env.autoexpand_threads = 1;
792         this.message_list.expand_all();
793         break;
794
795       case 'expand-unread':
796         this.env.autoexpand_threads = 2;
797         this.message_list.collapse_all();
798         this.expand_unread();
799         break;
800
801       case 'collapse-all':
802         this.env.autoexpand_threads = 0;
803         this.message_list.collapse_all();
804         break;
805
806       case 'nextmessage':
807         if (this.env.next_uid)
808           this.show_message(this.env.next_uid, false, this.env.action=='preview');
809         break;
810
811       case 'lastmessage':
812         if (this.env.last_uid)
813           this.show_message(this.env.last_uid);
814         break;
815
816       case 'previousmessage':
817         if (this.env.prev_uid)
818           this.show_message(this.env.prev_uid, false, this.env.action=='preview');
819         break;
820
821       case 'firstmessage':
822         if (this.env.first_uid)
823           this.show_message(this.env.first_uid);
824         break;
825
826       case 'checkmail':
827         this.check_for_recent(true);
828         break;
829
830       case 'compose':
831         url = this.url('mail/compose');
832
833         if (this.task == 'mail') {
834           url += '&_mbox='+urlencode(this.env.mailbox);
835           if (props)
836              url += '&_to='+urlencode(props);
837         }
838         // modify url if we're in addressbook
839         else if (this.task == 'addressbook') {
840           // switch to mail compose step directly
841           if (props && props.indexOf('@') > 0) {
842             url = this.get_task_url('mail', url);
843             this.redirect(url + '&_to='+urlencode(props));
844             break;
845           }
846
847           // use contact_id passed as command parameter
848           var n, len, a_cids = [];
849           if (props)
850             a_cids.push(props);
851           // get selected contacts
852           else if (this.contact_list) {
853             var selection = this.contact_list.get_selection();
854             for (n=0, len=selection.length; n<len; n++)
855               a_cids.push(selection[n]);
856           }
857
858           if (a_cids.length)
859             this.http_post('mailto', { _cid: a_cids.join(','), _source: this.env.source}, true);
860           else if (this.env.group)
861             this.http_post('mailto', { _gid: this.env.group, _source: this.env.source}, true);
862
863           break;
864         }
865         else if (props)
866           url += '&_to='+urlencode(props);
867
868         this.redirect(url);
869         break;
870
871       case 'spellcheck':
872         if (window.tinyMCE && tinyMCE.get(this.env.composebody)) {
873           tinyMCE.execCommand('mceSpellCheck', true);
874         }
875         else if (this.env.spellcheck && this.env.spellcheck.spellCheck && this.spellcheck_ready) {
876           this.env.spellcheck.spellCheck();
877           this.set_spellcheck_state('checking');
878         }
879         break;
880
881       case 'savedraft':
882         // Reset the auto-save timer
883         self.clearTimeout(this.save_timer);
884
885         if (!this.gui_objects.messageform)
886           break;
887
888         // if saving Drafts is disabled in main.inc.php
889         // or if compose form did not change
890         if (!this.env.drafts_mailbox || this.cmp_hash == this.compose_field_hash())
891           break;
892
893         var form = this.gui_objects.messageform,
894           msgid = this.set_busy(true, 'savingmessage');
895
896         form.target = "savetarget";
897         form._draft.value = '1';
898         form.action = this.add_url(form.action, '_unlock', msgid);
899         form.submit();
900         break;
901
902       case 'send':
903         if (!this.gui_objects.messageform)
904           break;
905
906         if (!props.nocheck && !this.check_compose_input(command))
907           break;
908
909         // Reset the auto-save timer
910         self.clearTimeout(this.save_timer);
911
912         // all checks passed, send message
913         var lang = this.spellcheck_lang(),
914           form = this.gui_objects.messageform,
915           msgid = this.set_busy(true, 'sendingmessage');
916
917         form.target = 'savetarget';
918         form._draft.value = '';
919         form.action = this.add_url(form.action, '_unlock', msgid);
920         form.action = this.add_url(form.action, '_lang', lang);
921         form.submit();
922
923         // clear timeout (sending could take longer)
924         clearTimeout(this.request_timer);
925         break;
926
927       case 'send-attachment':
928         // Reset the auto-save timer
929         self.clearTimeout(this.save_timer);
930
931         this.upload_file(props)
932         break;
933
934       case 'insert-sig':
935         this.change_identity($("[name='_from']")[0], true);
936         break;
937
938       case 'reply-all':
939       case 'reply-list':
940       case 'reply':
941         if (uid = this.get_single_uid()) {
942           url = '_reply_uid='+uid+'&_mbox='+urlencode(this.env.mailbox);
943           if (command == 'reply-all')
944             // do reply-list, when list is detected and popup menu wasn't used 
945             url += '&_all=' + (!props && this.commands['reply-list'] ? 'list' : 'all');
946           else if (command == 'reply-list')
947             url += '&_all=list';
948
949           this.goto_url('compose', url, true);
950         }
951         break;
952
953       case 'forward-attachment':
954       case 'forward':
955         if (uid = this.get_single_uid()) {
956           url = '_forward_uid='+uid+'&_mbox='+urlencode(this.env.mailbox);
957           if (command == 'forward-attachment' || (!props && this.env.forward_attachment))
958             url += '&_attachment=1';
959           this.goto_url('compose', url, true);
960         }
961         break;
962
963       case 'print':
964         if (uid = this.get_single_uid()) {
965           ref.printwin = window.open(this.env.comm_path+'&_action=print&_uid='+uid+'&_mbox='+urlencode(this.env.mailbox)+(this.env.safemode ? '&_safe=1' : ''));
966           if (this.printwin) {
967             window.setTimeout(function(){ ref.printwin.focus(); }, 20);
968             if (this.env.action != 'show')
969               this.mark_message('read', uid);
970           }
971         }
972         break;
973
974       case 'viewsource':
975         if (uid = this.get_single_uid()) {
976           ref.sourcewin = window.open(this.env.comm_path+'&_action=viewsource&_uid='+uid+'&_mbox='+urlencode(this.env.mailbox));
977           if (this.sourcewin)
978             window.setTimeout(function(){ ref.sourcewin.focus(); }, 20);
979           }
980         break;
981
982       case 'download':
983         if (uid = this.get_single_uid())
984           this.goto_url('viewsource', '&_uid='+uid+'&_mbox='+urlencode(this.env.mailbox)+'&_save=1');
985         break;
986
987       // quicksearch
988       case 'search':
989         if (!props && this.gui_objects.qsearchbox)
990           props = this.gui_objects.qsearchbox.value;
991         if (props) {
992           this.qsearch(props);
993           break;
994         }
995
996       // reset quicksearch
997       case 'reset-search':
998         var n, s = this.env.search_request || this.env.qsearch;
999
1000         this.reset_qsearch();
1001         this.select_all_mode = false;
1002
1003         if (s && this.env.mailbox)
1004           this.list_mailbox(this.env.mailbox, 1);
1005         else if (s && this.task == 'addressbook') {
1006           if (this.env.source == '') {
1007             for (n in this.env.address_sources) break;
1008             this.env.source = n;
1009             this.env.group = '';
1010           }
1011           this.list_contacts(this.env.source, this.env.group, 1);
1012         }
1013         break;
1014
1015       case 'listgroup':
1016         this.reset_qsearch();
1017         this.list_contacts(props.source, props.id);
1018         break;
1019
1020       case 'import':
1021         if (this.env.action == 'import' && this.gui_objects.importform) {
1022           var file = document.getElementById('rcmimportfile');
1023           if (file && !file.value) {
1024             alert(this.get_label('selectimportfile'));
1025             break;
1026           }
1027           this.gui_objects.importform.submit();
1028           this.set_busy(true, 'importwait');
1029           this.lock_form(this.gui_objects.importform, true);
1030         }
1031         else
1032           this.goto_url('import', (this.env.source ? '_target='+urlencode(this.env.source)+'&' : ''));
1033         break;
1034
1035       case 'export':
1036         if (this.contact_list.rowcount > 0) {
1037           this.goto_url('export', { _source:this.env.source, _gid:this.env.group, _search:this.env.search_request });
1038         }
1039         break;
1040
1041       case 'upload-photo':
1042         this.upload_contact_photo(props);
1043         break;
1044
1045       case 'delete-photo':
1046         this.replace_contact_photo('-del-');
1047         break;
1048
1049       // user settings commands
1050       case 'preferences':
1051       case 'identities':
1052       case 'folders':
1053         this.goto_url('settings/' + command);
1054         break;
1055
1056       case 'undo':
1057         this.http_request('undo', '', this.display_message('', 'loading'));
1058         break;
1059
1060       // unified command call (command name == function name)
1061       default:
1062         var func = command.replace(/-/g, '_');
1063         if (this[func] && typeof this[func] === 'function') {
1064           ret = this[func](props);
1065         }
1066         break;
1067     }
1068
1069     if (this.triggerEvent('after'+command, props) === false)
1070       ret = false;
1071     this.triggerEvent('actionafter', {props:props, action:command});
1072
1073     return ret === false ? false : obj ? false : true;
1074   };
1075
1076   // set command(s) enabled or disabled
1077   this.enable_command = function()
1078   {
1079     var i, n, args = Array.prototype.slice.call(arguments),
1080       enable = args.pop(), cmd;
1081
1082     for (n=0; n<args.length; n++) {
1083       cmd = args[n];
1084       // argument of type array
1085       if (typeof cmd === 'string') {
1086         this.commands[cmd] = enable;
1087         this.set_button(cmd, (enable ? 'act' : 'pas'));
1088       }
1089       // push array elements into commands array
1090       else {
1091         for (i in cmd)
1092           args.push(cmd[i]);
1093       }
1094     }
1095   };
1096
1097   // lock/unlock interface
1098   this.set_busy = function(a, message, id)
1099   {
1100     if (a && message) {
1101       var msg = this.get_label(message);
1102       if (msg == message)
1103         msg = 'Loading...';
1104
1105       id = this.display_message(msg, 'loading');
1106     }
1107     else if (!a && id) {
1108       this.hide_message(id);
1109     }
1110
1111     this.busy = a;
1112     //document.body.style.cursor = a ? 'wait' : 'default';
1113
1114     if (this.gui_objects.editform)
1115       this.lock_form(this.gui_objects.editform, a);
1116
1117     // clear pending timer
1118     if (this.request_timer)
1119       clearTimeout(this.request_timer);
1120
1121     // set timer for requests
1122     if (a && this.env.request_timeout)
1123       this.request_timer = window.setTimeout(function(){ ref.request_timed_out(); }, this.env.request_timeout * 1000);
1124
1125     return id;
1126   };
1127
1128   // return a localized string
1129   this.get_label = function(name, domain)
1130   {
1131     if (domain && this.labels[domain+'.'+name])
1132       return this.labels[domain+'.'+name];
1133     else if (this.labels[name])
1134       return this.labels[name];
1135     else
1136       return name;
1137   };
1138
1139   // alias for convenience reasons
1140   this.gettext = this.get_label;
1141
1142   // switch to another application task
1143   this.switch_task = function(task)
1144   {
1145     if (this.task===task && task!='mail')
1146       return;
1147
1148     var url = this.get_task_url(task);
1149     if (task=='mail')
1150       url += '&_mbox=INBOX';
1151
1152     this.redirect(url);
1153   };
1154
1155   this.get_task_url = function(task, url)
1156   {
1157     if (!url)
1158       url = this.env.comm_path;
1159
1160     return url.replace(/_task=[a-z]+/, '_task='+task);
1161   };
1162
1163   // called when a request timed out
1164   this.request_timed_out = function()
1165   {
1166     this.set_busy(false);
1167     this.display_message('Request timed out!', 'error');
1168   };
1169
1170   this.reload = function(delay)
1171   {
1172     if (this.is_framed())
1173       parent.rcmail.reload(delay);
1174     else if (delay)
1175       window.setTimeout(function(){ rcmail.reload(); }, delay);
1176     else if (window.location)
1177       location.href = this.env.comm_path + (this.env.action ? '&_action='+this.env.action : '');
1178   };
1179
1180   // Add variable to GET string, replace old value if exists
1181   this.add_url = function(url, name, value)
1182   {
1183     value = urlencode(value);
1184
1185     if (/(\?.*)$/.test(url)) {
1186       var urldata = RegExp.$1,
1187         datax = RegExp('((\\?|&)'+RegExp.escape(name)+'=[^&]*)');
1188
1189       if (datax.test(urldata)) {
1190         urldata = urldata.replace(datax, RegExp.$2 + name + '=' + value);
1191       }
1192       else
1193         urldata += '&' + name + '=' + value
1194
1195       return url.replace(/(\?.*)$/, urldata);
1196     }
1197     else
1198       return url + '?' + name + '=' + value;
1199   };
1200
1201   this.is_framed = function()
1202   {
1203     return (this.env.framed && parent.rcmail && parent.rcmail != this && parent.rcmail.command);
1204   };
1205
1206   this.save_pref = function(prop)
1207   {
1208     var request = {'_name': prop.name, '_value': prop.value};
1209
1210     if (prop.session)
1211       request['_session'] = prop.session;
1212     if (prop.env)
1213       this.env[prop.env] = prop.value;
1214
1215     this.http_post('save-pref', request);
1216   };
1217
1218   this.html_identifier = function(str, encode)
1219   {
1220     str = String(str);
1221     if (encode)
1222       return Base64.encode(str).replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
1223     else
1224       return str.replace(this.identifier_expr, '_');
1225   };
1226
1227   this.html_identifier_decode = function(str)
1228   {
1229     str = String(str).replace(/-/g, '+').replace(/_/g, '/');
1230
1231     while (str.length % 4) str += '=';
1232
1233     return Base64.decode(str);
1234   };
1235
1236
1237   /*********************************************************/
1238   /*********        event handling methods         *********/
1239   /*********************************************************/
1240
1241   this.drag_menu = function(e, target)
1242   {
1243     var modkey = rcube_event.get_modifier(e),
1244       menu = this.gui_objects.message_dragmenu;
1245
1246     if (menu && modkey == SHIFT_KEY && this.commands['copy']) {
1247       var pos = rcube_event.get_mouse_pos(e);
1248       this.env.drag_target = target;
1249       $(menu).css({top: (pos.y-10)+'px', left: (pos.x-10)+'px'}).show();
1250       return true;
1251     }
1252
1253     return false;
1254   };
1255
1256   this.drag_menu_action = function(action)
1257   {
1258     var menu = this.gui_objects.message_dragmenu;
1259     if (menu) {
1260       $(menu).hide();
1261     }
1262     this.command(action, this.env.drag_target);
1263     this.env.drag_target = null;
1264   };
1265
1266   this.drag_start = function(list)
1267   {
1268     var model = this.task == 'mail' ? this.env.mailboxes : this.env.contactfolders;
1269
1270     this.drag_active = true;
1271
1272     if (this.preview_timer)
1273       clearTimeout(this.preview_timer);
1274     if (this.preview_read_timer)
1275       clearTimeout(this.preview_read_timer);
1276
1277     // save folderlist and folders location/sizes for droptarget calculation in drag_move()
1278     if (this.gui_objects.folderlist && model) {
1279       this.initialBodyScrollTop = bw.ie ? 0 : window.pageYOffset;
1280       this.initialListScrollTop = this.gui_objects.folderlist.parentNode.scrollTop;
1281
1282       var k, li, height,
1283         list = $(this.gui_objects.folderlist);
1284         pos = list.offset();
1285
1286       this.env.folderlist_coords = { x1:pos.left, y1:pos.top, x2:pos.left + list.width(), y2:pos.top + list.height() };
1287
1288       this.env.folder_coords = [];
1289       for (k in model) {
1290         if (li = this.get_folder_li(k)) {
1291           // only visible folders
1292           if (height = li.firstChild.offsetHeight) {
1293             pos = $(li.firstChild).offset();
1294             this.env.folder_coords[k] = { x1:pos.left, y1:pos.top,
1295               x2:pos.left + li.firstChild.offsetWidth, y2:pos.top + height, on:0 };
1296           }
1297         }
1298       }
1299     }
1300   };
1301
1302   this.drag_end = function(e)
1303   {
1304     this.drag_active = false;
1305     this.env.last_folder_target = null;
1306
1307     if (this.folder_auto_timer) {
1308       window.clearTimeout(this.folder_auto_timer);
1309       this.folder_auto_timer = null;
1310       this.folder_auto_expand = null;
1311     }
1312
1313     // over the folders
1314     if (this.gui_objects.folderlist && this.env.folder_coords) {
1315       for (var k in this.env.folder_coords) {
1316         if (this.env.folder_coords[k].on)
1317           $(this.get_folder_li(k)).removeClass('droptarget');
1318       }
1319     }
1320   };
1321
1322   this.drag_move = function(e)
1323   {
1324     if (this.gui_objects.folderlist && this.env.folder_coords) {
1325       var k, li, div, check, oldclass,
1326         layerclass = 'draglayernormal',
1327         mouse = rcube_event.get_mouse_pos(e),
1328         pos = this.env.folderlist_coords,
1329         // offsets to compensate for scrolling while dragging a message
1330         boffset = bw.ie ? -document.documentElement.scrollTop : this.initialBodyScrollTop,
1331         moffset = this.initialListScrollTop-this.gui_objects.folderlist.parentNode.scrollTop;
1332
1333       if (this.contact_list && this.contact_list.draglayer)
1334         oldclass = this.contact_list.draglayer.attr('class');
1335
1336       mouse.y += -moffset-boffset;
1337
1338       // if mouse pointer is outside of folderlist
1339       if (mouse.x < pos.x1 || mouse.x >= pos.x2 || mouse.y < pos.y1 || mouse.y >= pos.y2) {
1340         if (this.env.last_folder_target) {
1341           $(this.get_folder_li(this.env.last_folder_target)).removeClass('droptarget');
1342           this.env.folder_coords[this.env.last_folder_target].on = 0;
1343           this.env.last_folder_target = null;
1344         }
1345         if (layerclass != oldclass && this.contact_list && this.contact_list.draglayer)
1346           this.contact_list.draglayer.attr('class', layerclass);
1347         return;
1348       }
1349
1350       // over the folders
1351       for (k in this.env.folder_coords) {
1352         pos = this.env.folder_coords[k];
1353         if (mouse.x >= pos.x1 && mouse.x < pos.x2 && mouse.y >= pos.y1 && mouse.y < pos.y2){
1354           if ((check = this.check_droptarget(k))) {
1355             li = this.get_folder_li(k);
1356             div = $(li.getElementsByTagName('div')[0]);
1357
1358             // if the folder is collapsed, expand it after 1sec and restart the drag & drop process.
1359             if (div.hasClass('collapsed')) {
1360               if (this.folder_auto_timer)
1361                 window.clearTimeout(this.folder_auto_timer);
1362
1363               this.folder_auto_expand = k;
1364               this.folder_auto_timer = window.setTimeout(function() {
1365                 rcmail.command('collapse-folder', rcmail.folder_auto_expand);
1366                 rcmail.drag_start(null);
1367               }, 1000);
1368             } else if (this.folder_auto_timer) {
1369               window.clearTimeout(this.folder_auto_timer);
1370               this.folder_auto_timer = null;
1371               this.folder_auto_expand = null;
1372             }
1373
1374             $(li).addClass('droptarget');
1375             this.env.folder_coords[k].on = 1;
1376             this.env.last_folder_target = k;
1377             layerclass = 'draglayer' + (check > 1 ? 'copy' : 'normal');
1378           } else { // Clear target, otherwise drag end will trigger move into last valid droptarget
1379             this.env.last_folder_target = null;
1380           }
1381         }
1382         else if (pos.on) {
1383           $(this.get_folder_li(k)).removeClass('droptarget');
1384           this.env.folder_coords[k].on = 0;
1385         }
1386       }
1387
1388       if (layerclass != oldclass && this.contact_list && this.contact_list.draglayer)
1389         this.contact_list.draglayer.attr('class', layerclass);
1390     }
1391   };
1392
1393   this.collapse_folder = function(name)
1394   {
1395     var li = this.get_folder_li(name, '', true),
1396       div = $('div:first', li),
1397       ul = $('ul:first', li);
1398
1399     if (div.hasClass('collapsed')) {
1400       ul.show();
1401       div.removeClass('collapsed').addClass('expanded');
1402       var reg = new RegExp('&'+urlencode(name)+'&');
1403       this.env.collapsed_folders = this.env.collapsed_folders.replace(reg, '');
1404     }
1405     else if (div.hasClass('expanded')) {
1406       ul.hide();
1407       div.removeClass('expanded').addClass('collapsed');
1408       this.env.collapsed_folders = this.env.collapsed_folders+'&'+urlencode(name)+'&';
1409
1410       // select parent folder if one of its childs is currently selected
1411       if (this.env.mailbox.indexOf(name + this.env.delimiter) == 0)
1412         this.command('list', name);
1413     }
1414     else
1415       return;
1416
1417     // Work around a bug in IE6 and IE7, see #1485309
1418     if (bw.ie6 || bw.ie7) {
1419       var siblings = li.nextSibling ? li.nextSibling.getElementsByTagName('ul') : null;
1420       if (siblings && siblings.length && (li = siblings[0]) && li.style && li.style.display != 'none') {
1421         li.style.display = 'none';
1422         li.style.display = '';
1423       }
1424     }
1425
1426     this.command('save-pref', { name: 'collapsed_folders', value: this.env.collapsed_folders });
1427     this.set_unread_count_display(name, false);
1428   };
1429
1430   this.doc_mouse_up = function(e)
1431   {
1432     var model, list, li, id;
1433
1434     // ignore event if jquery UI dialog is open
1435     if ($(rcube_event.get_target(e)).closest('.ui-dialog, .ui-widget-overlay').length)
1436       return;
1437
1438     if (list = this.message_list) {
1439       if (!rcube_mouse_is_over(e, list.list.parentNode))
1440         list.blur();
1441       else
1442         list.focus();
1443       model = this.env.mailboxes;
1444     }
1445     else if (list = this.contact_list) {
1446       if (!rcube_mouse_is_over(e, list.list.parentNode))
1447         list.blur();
1448       else
1449         list.focus();
1450       model = this.env.contactfolders;
1451     }
1452     else if (this.ksearch_value) {
1453       this.ksearch_blur();
1454     }
1455
1456     // handle mouse release when dragging
1457     if (this.drag_active && model && this.env.last_folder_target) {
1458       var target = model[this.env.last_folder_target];
1459
1460       $(this.get_folder_li(this.env.last_folder_target)).removeClass('droptarget');
1461       this.env.last_folder_target = null;
1462       list.draglayer.hide();
1463
1464       if (!this.drag_menu(e, target))
1465         this.command('moveto', target);
1466     }
1467
1468     // reset 'pressed' buttons
1469     if (this.buttons_sel) {
1470       for (id in this.buttons_sel)
1471         if (typeof id !== 'function')
1472           this.button_out(this.buttons_sel[id], id);
1473       this.buttons_sel = {};
1474     }
1475   };
1476
1477   this.click_on_list = function(e)
1478   {
1479     if (this.gui_objects.qsearchbox)
1480       this.gui_objects.qsearchbox.blur();
1481
1482     if (this.message_list)
1483       this.message_list.focus();
1484     else if (this.contact_list)
1485       this.contact_list.focus();
1486
1487     return true;
1488   };
1489
1490   this.msglist_select = function(list)
1491   {
1492     if (this.preview_timer)
1493       clearTimeout(this.preview_timer);
1494     if (this.preview_read_timer)
1495       clearTimeout(this.preview_read_timer);
1496
1497     var selected = list.get_single_selection() != null;
1498
1499     this.enable_command(this.env.message_commands, selected);
1500     if (selected) {
1501       // Hide certain command buttons when Drafts folder is selected
1502       if (this.env.mailbox == this.env.drafts_mailbox)
1503         this.enable_command('reply', 'reply-all', 'reply-list', 'forward', 'forward-attachment', false);
1504       // Disable reply-list when List-Post header is not set
1505       else {
1506         var msg = this.env.messages[list.get_single_selection()];
1507         if (!msg.ml)
1508           this.enable_command('reply-list', false);
1509       }
1510     }
1511     // Multi-message commands
1512     this.enable_command('delete', 'moveto', 'copy', 'mark', (list.selection.length > 0 ? true : false));
1513
1514     // reset all-pages-selection
1515     if (selected || (list.selection.length && list.selection.length != list.rowcount))
1516       this.select_all_mode = false;
1517
1518     // start timer for message preview (wait for double click)
1519     if (selected && this.env.contentframe && !list.multi_selecting && !this.dummy_select)
1520       this.preview_timer = window.setTimeout(function(){ ref.msglist_get_preview(); }, 200);
1521     else if (this.env.contentframe)
1522       this.show_contentframe(false);
1523   };
1524
1525   // This allow as to re-select selected message and display it in preview frame
1526   this.msglist_click = function(list)
1527   {
1528     if (list.multi_selecting || !this.env.contentframe)
1529       return;
1530
1531     if (list.get_single_selection() && window.frames && window.frames[this.env.contentframe]) {
1532       if (window.frames[this.env.contentframe].location.href.indexOf(this.env.blankpage)>=0) {
1533         if (this.preview_timer)
1534           clearTimeout(this.preview_timer);
1535         if (this.preview_read_timer)
1536           clearTimeout(this.preview_read_timer);
1537         this.preview_timer = window.setTimeout(function(){ ref.msglist_get_preview(); }, 200);
1538       }
1539     }
1540   };
1541
1542   this.msglist_dbl_click = function(list)
1543   {
1544     if (this.preview_timer)
1545       clearTimeout(this.preview_timer);
1546
1547     if (this.preview_read_timer)
1548       clearTimeout(this.preview_read_timer);
1549
1550     var uid = list.get_single_selection();
1551     if (uid && this.env.mailbox == this.env.drafts_mailbox)
1552       this.goto_url('compose', '_draft_uid='+uid+'&_mbox='+urlencode(this.env.mailbox), true);
1553     else if (uid)
1554       this.show_message(uid, false, false);
1555   };
1556
1557   this.msglist_keypress = function(list)
1558   {
1559     if (list.modkey == CONTROL_KEY)
1560       return;
1561
1562     if (list.key_pressed == list.ENTER_KEY)
1563       this.command('show');
1564     else if (list.key_pressed == list.DELETE_KEY || list.key_pressed == list.BACKSPACE_KEY)
1565       this.command('delete');
1566     else if (list.key_pressed == 33)
1567       this.command('previouspage');
1568     else if (list.key_pressed == 34)
1569       this.command('nextpage');
1570   };
1571
1572   this.msglist_get_preview = function()
1573   {
1574     var uid = this.get_single_uid();
1575     if (uid && this.env.contentframe && !this.drag_active)
1576       this.show_message(uid, false, true);
1577     else if (this.env.contentframe)
1578       this.show_contentframe(false);
1579   };
1580
1581   this.msglist_expand = function(row)
1582   {
1583     if (this.env.messages[row.uid])
1584       this.env.messages[row.uid].expanded = row.expanded;
1585   };
1586
1587   this.msglist_set_coltypes = function(list)
1588   {
1589     var i, found, name, cols = list.list.tHead.rows[0].cells;
1590
1591     this.env.coltypes = [];
1592
1593     for (i=0; i<cols.length; i++)
1594       if (cols[i].id && cols[i].id.match(/^rcm/)) {
1595         name = cols[i].id.replace(/^rcm/, '');
1596         this.env.coltypes.push(name == 'to' ? 'from' : name);
1597       }
1598
1599     if ((found = $.inArray('flag', this.env.coltypes)) >= 0)
1600       this.env.flagged_col = found;
1601
1602     if ((found = $.inArray('subject', this.env.coltypes)) >= 0)
1603       this.env.subject_col = found;
1604
1605     this.command('save-pref', { name: 'list_cols', value: this.env.coltypes, session: 'list_attrib/columns' });
1606   };
1607
1608   this.check_droptarget = function(id)
1609   {
1610     var allow = false, copy = false;
1611
1612     if (this.task == 'mail')
1613       allow = (this.env.mailboxes[id] && this.env.mailboxes[id].id != this.env.mailbox && !this.env.mailboxes[id].virtual);
1614     else if (this.task == 'settings')
1615       allow = (id != this.env.mailbox);
1616     else if (this.task == 'addressbook') {
1617       if (id != this.env.source && this.env.contactfolders[id]) {
1618         if (this.env.contactfolders[id].type == 'group') {
1619           var target_abook = this.env.contactfolders[id].source;
1620           allow = this.env.contactfolders[id].id != this.env.group && !this.env.contactfolders[target_abook].readonly;
1621           copy = target_abook != this.env.source;
1622         }
1623         else {
1624           allow = !this.env.contactfolders[id].readonly;
1625           copy = true;
1626         }
1627       }
1628     }
1629
1630     return allow ? (copy ? 2 : 1) : 0;
1631   };
1632
1633
1634   /*********************************************************/
1635   /*********     (message) list functionality      *********/
1636   /*********************************************************/
1637
1638   this.init_message_row = function(row)
1639   {
1640     var expando, self = this, uid = row.uid,
1641       status_icon = (this.env.status_col != null ? 'status' : 'msg') + 'icn' + row.uid;
1642
1643     if (uid && this.env.messages[uid])
1644       $.extend(row, this.env.messages[uid]);
1645
1646     // set eventhandler to status icon
1647     if (row.icon = document.getElementById(status_icon)) {
1648       row.icon._row = row.obj;
1649       row.icon.onmousedown = function(e) { self.command('toggle_status', this); rcube_event.cancel(e); };
1650     }
1651
1652     // save message icon position too
1653     if (this.env.status_col != null)
1654       row.msgicon = document.getElementById('msgicn'+row.uid);
1655     else
1656       row.msgicon = row.icon;
1657
1658     // set eventhandler to flag icon, if icon found
1659     if (this.env.flagged_col != null && (row.flagicon = document.getElementById('flagicn'+row.uid))) {
1660       row.flagicon._row = row.obj;
1661       row.flagicon.onmousedown = function(e) { self.command('toggle_flag', this); rcube_event.cancel(e); };
1662     }
1663
1664     if (!row.depth && row.has_children && (expando = document.getElementById('rcmexpando'+row.uid))) {
1665       row.expando = expando;
1666       expando.onmousedown = function(e) { return self.expand_message_row(e, uid); };
1667     }
1668
1669     this.triggerEvent('insertrow', { uid:uid, row:row });
1670   };
1671
1672   // create a table row in the message list
1673   this.add_message_row = function(uid, cols, flags, attop)
1674   {
1675     if (!this.gui_objects.messagelist || !this.message_list)
1676       return false;
1677
1678     // Prevent from adding messages from different folder (#1487752)
1679     if (flags.mbox != this.env.mailbox && !flags.skip_mbox_check)
1680       return false;
1681
1682     if (!this.env.messages[uid])
1683       this.env.messages[uid] = {};
1684
1685     // merge flags over local message object
1686     $.extend(this.env.messages[uid], {
1687       deleted: flags.deleted?1:0,
1688       replied: flags.answered?1:0,
1689       unread: !flags.seen?1:0,
1690       forwarded: flags.forwarded?1:0,
1691       flagged: flags.flagged?1:0,
1692       has_children: flags.has_children?1:0,
1693       depth: flags.depth?flags.depth:0,
1694       unread_children: flags.unread_children?flags.unread_children:0,
1695       parent_uid: flags.parent_uid?flags.parent_uid:0,
1696       selected: this.select_all_mode || this.message_list.in_selection(uid),
1697       ml: flags.ml?1:0,
1698       ctype: flags.ctype,
1699       // flags from plugins
1700       flags: flags.extra_flags
1701     });
1702
1703     var c, n, col, html, tree = '', expando = '',
1704       list = this.message_list,
1705       rows = list.rows,
1706       message = this.env.messages[uid],
1707       css_class = 'message'
1708         + (!flags.seen ? ' unread' : '')
1709         + (flags.deleted ? ' deleted' : '')
1710         + (flags.flagged ? ' flagged' : '')
1711         + (flags.unread_children && flags.seen && !this.env.autoexpand_threads ? ' unroot' : '')
1712         + (message.selected ? ' selected' : ''),
1713       // for performance use DOM instead of jQuery here
1714       row = document.createElement('tr');
1715
1716     row.id = 'rcmrow'+uid;
1717     row.className = css_class;
1718
1719     // message status icons
1720     css_class = 'msgicon';
1721     if (this.env.status_col === null) {
1722       css_class += ' status';
1723       if (flags.deleted)
1724         css_class += ' deleted';
1725       else if (!flags.seen)
1726         css_class += ' unread';
1727       else if (flags.unread_children > 0)
1728         css_class += ' unreadchildren';
1729     }
1730     if (flags.answered)
1731       css_class += ' replied';
1732     if (flags.forwarded)
1733       css_class += ' forwarded';
1734
1735     // update selection
1736     if (message.selected && !list.in_selection(uid))
1737       list.selection.push(uid);
1738
1739     // threads
1740     if (this.env.threading) {
1741       if (message.depth) {
1742         // This assumes that div width is hardcoded to 15px,
1743         tree += '<span id="rcmtab' + uid + '" class="branch" style="width:' + (message.depth * 15) + 'px;">&nbsp;&nbsp;</span>';
1744
1745         if ((rows[message.parent_uid] && rows[message.parent_uid].expanded === false)
1746           || ((this.env.autoexpand_threads == 0 || this.env.autoexpand_threads == 2) &&
1747             (!rows[message.parent_uid] || !rows[message.parent_uid].expanded))
1748         ) {
1749           row.style.display = 'none';
1750           message.expanded = false;
1751         }
1752         else
1753           message.expanded = true;
1754       }
1755       else if (message.has_children) {
1756         if (message.expanded === undefined && (this.env.autoexpand_threads == 1 || (this.env.autoexpand_threads == 2 && message.unread_children))) {
1757           message.expanded = true;
1758         }
1759
1760         expando = '<div id="rcmexpando' + uid + '" class="' + (message.expanded ? 'expanded' : 'collapsed') + '">&nbsp;&nbsp;</div>';
1761       }
1762     }
1763
1764     tree += '<span id="msgicn'+uid+'" class="'+css_class+'">&nbsp;</span>';
1765
1766     // build subject link 
1767     if (!bw.ie && cols.subject) {
1768       var action = flags.mbox == this.env.drafts_mailbox ? 'compose' : 'show';
1769       var uid_param = flags.mbox == this.env.drafts_mailbox ? '_draft_uid' : '_uid';
1770       cols.subject = '<a href="./?_task=mail&_action='+action+'&_mbox='+urlencode(flags.mbox)+'&'+uid_param+'='+uid+'"'+
1771         ' onclick="return rcube_event.cancel(event)" onmouseover="rcube_webmail.long_subject_title(this,'+(message.depth+1)+')">'+cols.subject+'</a>';
1772     }
1773
1774     // add each submitted col
1775     for (n in this.env.coltypes) {
1776       c = this.env.coltypes[n];
1777       col = document.createElement('td');
1778       col.className = String(c).toLowerCase();
1779
1780       if (c == 'flag') {
1781         css_class = (flags.flagged ? 'flagged' : 'unflagged');
1782         html = '<span id="flagicn'+uid+'" class="'+css_class+'">&nbsp;</span>';
1783       }
1784       else if (c == 'attachment') {
1785         if (/application\/|multipart\/m/.test(flags.ctype))
1786           html = '<span class="attachment">&nbsp;</span>';
1787         else if (/multipart\/report/.test(flags.ctype))
1788           html = '<span class="report">&nbsp;</span>';
1789         else
1790           html = '&nbsp;';
1791       }
1792       else if (c == 'status') {
1793         if (flags.deleted)
1794           css_class = 'deleted';
1795         else if (!flags.seen)
1796           css_class = 'unread';
1797         else if (flags.unread_children > 0)
1798           css_class = 'unreadchildren';
1799         else
1800           css_class = 'msgicon';
1801         html = '<span id="statusicn'+uid+'" class="'+css_class+'">&nbsp;</span>';
1802       }
1803       else if (c == 'threads')
1804         html = expando;
1805       else if (c == 'subject') {
1806         if (bw.ie)
1807           col.onmouseover = function() { rcube_webmail.long_subject_title_ie(this, message.depth+1); };
1808         html = tree + cols[c];
1809       }
1810       else if (c == 'priority') {
1811         if (flags.prio > 0 && flags.prio < 6)
1812           html = '<span class="prio'+flags.prio+'">&nbsp;</span>';
1813         else
1814           html = '&nbsp;';
1815       }
1816       else
1817         html = cols[c];
1818
1819       col.innerHTML = html;
1820
1821       row.appendChild(col);
1822     }
1823
1824     list.insert_row(row, attop);
1825
1826     // remove 'old' row
1827     if (attop && this.env.pagesize && list.rowcount > this.env.pagesize) {
1828       var uid = list.get_last_row();
1829       list.remove_row(uid);
1830       list.clear_selection(uid);
1831     }
1832   };
1833
1834   this.set_list_sorting = function(sort_col, sort_order)
1835   {
1836     // set table header class
1837     $('#rcm'+this.env.sort_col).removeClass('sorted'+(this.env.sort_order.toUpperCase()));
1838     if (sort_col)
1839       $('#rcm'+sort_col).addClass('sorted'+sort_order);
1840
1841     this.env.sort_col = sort_col;
1842     this.env.sort_order = sort_order;
1843   };
1844
1845   this.set_list_options = function(cols, sort_col, sort_order, threads)
1846   {
1847     var update, add_url = '';
1848
1849     if (sort_col === undefined)
1850       sort_col = this.env.sort_col;
1851     if (!sort_order)
1852       sort_order = this.env.sort_order;
1853
1854     if (this.env.sort_col != sort_col || this.env.sort_order != sort_order) {
1855       update = 1;
1856       this.set_list_sorting(sort_col, sort_order);
1857     }
1858
1859     if (this.env.threading != threads) {
1860       update = 1;
1861       add_url += '&_threads=' + threads;
1862     }
1863
1864     if (cols && cols.length) {
1865       // make sure new columns are added at the end of the list
1866       var i, idx, name, newcols = [], oldcols = this.env.coltypes;
1867       for (i=0; i<oldcols.length; i++) {
1868         name = oldcols[i] == 'to' ? 'from' : oldcols[i];
1869         idx = $.inArray(name, cols);
1870         if (idx != -1) {
1871           newcols.push(name);
1872           delete cols[idx];
1873         }
1874       }
1875       for (i=0; i<cols.length; i++)
1876         if (cols[i])
1877           newcols.push(cols[i]);
1878
1879       if (newcols.join() != oldcols.join()) {
1880         update = 1;
1881         add_url += '&_cols=' + newcols.join(',');
1882       }
1883     }
1884
1885     if (update)
1886       this.list_mailbox('', '', sort_col+'_'+sort_order, add_url);
1887   };
1888
1889   // when user doble-clicks on a row
1890   this.show_message = function(id, safe, preview)
1891   {
1892     if (!id)
1893       return;
1894
1895     var target = window,
1896       action = preview ? 'preview': 'show',
1897       url = '&_action='+action+'&_uid='+id+'&_mbox='+urlencode(this.env.mailbox);
1898
1899     if (preview && this.env.contentframe && window.frames && window.frames[this.env.contentframe]) {
1900       target = window.frames[this.env.contentframe];
1901       url += '&_framed=1';
1902     }
1903
1904     if (safe)
1905       url += '&_safe=1';
1906
1907     // also send search request to get the right messages
1908     if (this.env.search_request)
1909       url += '&_search='+this.env.search_request;
1910
1911     if (action == 'preview' && String(target.location.href).indexOf(url) >= 0)
1912       this.show_contentframe(true);
1913     else {
1914       this.location_href(this.env.comm_path+url, target, true);
1915
1916       // mark as read and change mbox unread counter
1917       if (action == 'preview' && this.message_list && this.message_list.rows[id] && this.message_list.rows[id].unread && this.env.preview_pane_mark_read >= 0) {
1918         this.preview_read_timer = window.setTimeout(function() {
1919           ref.set_message(id, 'unread', false);
1920           ref.update_thread_root(id, 'read');
1921           if (ref.env.unread_counts[ref.env.mailbox]) {
1922             ref.env.unread_counts[ref.env.mailbox] -= 1;
1923             ref.set_unread_count(ref.env.mailbox, ref.env.unread_counts[ref.env.mailbox], ref.env.mailbox == 'INBOX');
1924           }
1925           if (ref.env.preview_pane_mark_read > 0)
1926             ref.http_post('mark', '_uid='+id+'&_flag=read&_quiet=1');
1927         }, this.env.preview_pane_mark_read * 1000);
1928       }
1929     }
1930   };
1931
1932   this.show_contentframe = function(show)
1933   {
1934     var frm, win;
1935     if (this.env.contentframe && (frm = $('#'+this.env.contentframe)) && frm.length) {
1936       if (!show && (win = window.frames[this.env.contentframe])) {
1937         if (win.location && win.location.href.indexOf(this.env.blankpage)<0)
1938           win.location.href = this.env.blankpage;
1939       }
1940       else if (!bw.safari && !bw.konq)
1941         frm[show ? 'show' : 'hide']();
1942       }
1943
1944     if (!show && this.busy)
1945       this.set_busy(false, null, this.env.frame_lock);
1946   };
1947
1948   this.lock_frame = function()
1949   {
1950     if (!this.env.frame_lock)
1951       (this.is_framed() ? parent.rcmail : this).env.frame_lock = this.set_busy(true, 'loading');
1952   };
1953
1954   // list a specific page
1955   this.list_page = function(page)
1956   {
1957     if (page == 'next')
1958       page = this.env.current_page+1;
1959     else if (page == 'last')
1960       page = this.env.pagecount;
1961     else if (page == 'prev' && this.env.current_page > 1)
1962       page = this.env.current_page-1;
1963     else if (page == 'first' && this.env.current_page > 1)
1964       page = 1;
1965
1966     if (page > 0 && page <= this.env.pagecount) {
1967       this.env.current_page = page;
1968
1969       if (this.task == 'mail')
1970         this.list_mailbox(this.env.mailbox, page);
1971       else if (this.task == 'addressbook')
1972         this.list_contacts(this.env.source, this.env.group, page);
1973     }
1974   };
1975
1976   // list messages of a specific mailbox using filter
1977   this.filter_mailbox = function(filter)
1978   {
1979     var lock = this.set_busy(true, 'searching');
1980
1981     this.clear_message_list();
1982
1983     // reset vars
1984     this.env.current_page = 1;
1985     this.http_request('search', this.search_params(false, filter), lock);
1986   };
1987
1988   // list messages of a specific mailbox
1989   this.list_mailbox = function(mbox, page, sort, add_url)
1990   {
1991     var url = '', target = window;
1992
1993     if (!mbox)
1994       mbox = this.env.mailbox ? this.env.mailbox : 'INBOX';
1995
1996     if (add_url)
1997       url += add_url;
1998
1999     // add sort to url if set
2000     if (sort)
2001       url += '&_sort=' + sort;
2002
2003     // also send search request to get the right messages
2004     if (this.env.search_request)
2005       url += '&_search='+this.env.search_request;
2006
2007     // set page=1 if changeing to another mailbox
2008     if (this.env.mailbox != mbox) {
2009       page = 1;
2010       this.env.current_page = page;
2011       this.select_all_mode = false;
2012     }
2013
2014     // unselect selected messages and clear the list and message data
2015     this.clear_message_list();
2016
2017     if (mbox != this.env.mailbox || (mbox == this.env.mailbox && !page && !sort))
2018       url += '&_refresh=1';
2019
2020     this.select_folder(mbox, '', true);
2021     this.env.mailbox = mbox;
2022
2023     // load message list remotely
2024     if (this.gui_objects.messagelist) {
2025       this.list_mailbox_remote(mbox, page, url);
2026       return;
2027     }
2028
2029     if (this.env.contentframe && window.frames && window.frames[this.env.contentframe]) {
2030       target = window.frames[this.env.contentframe];
2031       url += '&_framed=1';
2032     }
2033
2034     // load message list to target frame/window
2035     if (mbox) {
2036       this.set_busy(true, 'loading');
2037       this.location_href(this.env.comm_path+'&_mbox='+urlencode(mbox)+(page ? '&_page='+page : '')+url, target);
2038     }
2039   };
2040
2041   this.clear_message_list = function()
2042   {
2043       this.env.messages = {};
2044       this.last_selected = 0;
2045
2046       this.show_contentframe(false);
2047       if (this.message_list)
2048         this.message_list.clear(true);
2049   };
2050
2051   // send remote request to load message list
2052   this.list_mailbox_remote = function(mbox, page, add_url)
2053   {
2054     // clear message list first
2055     this.message_list.clear();
2056
2057     // send request to server
2058     var url = '_mbox='+urlencode(mbox)+(page ? '&_page='+page : ''),
2059       lock = this.set_busy(true, 'loading');
2060     this.http_request('list', url+add_url, lock);
2061   };
2062
2063   // removes messages that doesn't exists from list selection array
2064   this.update_selection = function()
2065   {
2066     var selected = this.message_list.selection,
2067       rows = this.message_list.rows,
2068       i, selection = [];
2069
2070     for (i in selected)
2071       if (rows[selected[i]])
2072         selection.push(selected[i]);
2073
2074     this.message_list.selection = selection;
2075   }
2076
2077   // expand all threads with unread children
2078   this.expand_unread = function()
2079   {
2080     var r, tbody = this.gui_objects.messagelist.tBodies[0],
2081       new_row = tbody.firstChild;
2082
2083     while (new_row) {
2084       if (new_row.nodeType == 1 && (r = this.message_list.rows[new_row.uid]) && r.unread_children) {
2085             this.message_list.expand_all(r);
2086             this.set_unread_children(r.uid);
2087       }
2088       new_row = new_row.nextSibling;
2089     }
2090     return false;
2091   };
2092
2093   // thread expanding/collapsing handler
2094   this.expand_message_row = function(e, uid)
2095   {
2096     var row = this.message_list.rows[uid];
2097
2098     // handle unread_children mark
2099     row.expanded = !row.expanded;
2100     this.set_unread_children(uid);
2101     row.expanded = !row.expanded;
2102
2103     this.message_list.expand_row(e, uid);
2104   };
2105
2106   // message list expanding
2107   this.expand_threads = function()
2108   {
2109     if (!this.env.threading || !this.env.autoexpand_threads || !this.message_list)
2110       return;
2111
2112     switch (this.env.autoexpand_threads) {
2113       case 2: this.expand_unread(); break;
2114       case 1: this.message_list.expand_all(); break;
2115     }
2116   };
2117
2118   // Initializes threads indicators/expanders after list update
2119   this.init_threads = function(roots, mbox)
2120   {
2121     // #1487752
2122     if (mbox && mbox != this.env.mailbox)
2123       return false;
2124
2125     for (var n=0, len=roots.length; n<len; n++)
2126       this.add_tree_icons(roots[n]);
2127     this.expand_threads();
2128   };
2129
2130   // adds threads tree icons to the list (or specified thread)
2131   this.add_tree_icons = function(root)
2132   {
2133     var i, l, r, n, len, pos, tmp = [], uid = [],
2134       row, rows = this.message_list.rows;
2135
2136     if (root)
2137       row = rows[root] ? rows[root].obj : null;
2138     else
2139       row = this.message_list.list.tBodies[0].firstChild;
2140
2141     while (row) {
2142       if (row.nodeType == 1 && (r = rows[row.uid])) {
2143         if (r.depth) {
2144           for (i=tmp.length-1; i>=0; i--) {
2145             len = tmp[i].length;
2146             if (len > r.depth) {
2147               pos = len - r.depth;
2148               if (!(tmp[i][pos] & 2))
2149                 tmp[i][pos] = tmp[i][pos] ? tmp[i][pos]+2 : 2;
2150             }
2151             else if (len == r.depth) {
2152               if (!(tmp[i][0] & 2))
2153                 tmp[i][0] += 2;
2154             }
2155             if (r.depth > len)
2156               break;
2157           }
2158
2159           tmp.push(new Array(r.depth));
2160           tmp[tmp.length-1][0] = 1;
2161           uid.push(r.uid);
2162         }
2163         else {
2164           if (tmp.length) {
2165             for (i in tmp) {
2166               this.set_tree_icons(uid[i], tmp[i]);
2167             }
2168             tmp = [];
2169             uid = [];
2170           }
2171           if (root && row != rows[root].obj)
2172             break;
2173         }
2174       }
2175       row = row.nextSibling;
2176     }
2177
2178     if (tmp.length) {
2179       for (i in tmp) {
2180         this.set_tree_icons(uid[i], tmp[i]);
2181       }
2182     }
2183   };
2184
2185   // adds tree icons to specified message row
2186   this.set_tree_icons = function(uid, tree)
2187   {
2188     var i, divs = [], html = '', len = tree.length;
2189
2190     for (i=0; i<len; i++) {
2191       if (tree[i] > 2)
2192         divs.push({'class': 'l3', width: 15});
2193       else if (tree[i] > 1)
2194         divs.push({'class': 'l2', width: 15});
2195       else if (tree[i] > 0)
2196         divs.push({'class': 'l1', width: 15});
2197       // separator div
2198       else if (divs.length && !divs[divs.length-1]['class'])
2199         divs[divs.length-1].width += 15;
2200       else
2201         divs.push({'class': null, width: 15});
2202     }
2203
2204     for (i=divs.length-1; i>=0; i--) {
2205       if (divs[i]['class'])
2206         html += '<div class="tree '+divs[i]['class']+'" />';
2207       else
2208         html += '<div style="width:'+divs[i].width+'px" />';
2209     }
2210
2211     if (html)
2212       $('#rcmtab'+uid).html(html);
2213   };
2214
2215   // update parent in a thread
2216   this.update_thread_root = function(uid, flag)
2217   {
2218     if (!this.env.threading)
2219       return;
2220
2221     var root = this.message_list.find_root(uid);
2222
2223     if (uid == root)
2224       return;
2225
2226     var p = this.message_list.rows[root];
2227
2228     if (flag == 'read' && p.unread_children) {
2229       p.unread_children--;
2230     }
2231     else if (flag == 'unread' && p.has_children) {
2232       // unread_children may be undefined
2233       p.unread_children = p.unread_children ? p.unread_children + 1 : 1;
2234     }
2235     else {
2236       return;
2237     }
2238
2239     this.set_message_icon(root);
2240     this.set_unread_children(root);
2241   };
2242
2243   // update thread indicators for all messages in a thread below the specified message
2244   // return number of removed/added root level messages
2245   this.update_thread = function (uid)
2246   {
2247     if (!this.env.threading)
2248       return 0;
2249
2250     var r, parent, count = 0,
2251       rows = this.message_list.rows,
2252       row = rows[uid],
2253       depth = rows[uid].depth,
2254       roots = [];
2255
2256     if (!row.depth) // root message: decrease roots count
2257       count--;
2258     else if (row.unread) {
2259       // update unread_children for thread root
2260       parent = this.message_list.find_root(uid);
2261       rows[parent].unread_children--;
2262       this.set_unread_children(parent);
2263     }
2264
2265     parent = row.parent_uid;
2266
2267     // childrens
2268     row = row.obj.nextSibling;
2269     while (row) {
2270       if (row.nodeType == 1 && (r = rows[row.uid])) {
2271             if (!r.depth || r.depth <= depth)
2272               break;
2273
2274             r.depth--; // move left
2275         // reset width and clear the content of a tab, icons will be added later
2276             $('#rcmtab'+r.uid).width(r.depth * 15).html('');
2277         if (!r.depth) { // a new root
2278               count++; // increase roots count
2279               r.parent_uid = 0;
2280               if (r.has_children) {
2281                 // replace 'leaf' with 'collapsed'
2282                 $('#rcmrow'+r.uid+' '+'.leaf:first')
2283               .attr('id', 'rcmexpando' + r.uid)
2284                   .attr('class', (r.obj.style.display != 'none' ? 'expanded' : 'collapsed'))
2285               .bind('mousedown', {uid:r.uid, p:this},
2286                     function(e) { return e.data.p.expand_message_row(e, e.data.uid); });
2287
2288                 r.unread_children = 0;
2289                 roots.push(r);
2290               }
2291               // show if it was hidden
2292               if (r.obj.style.display == 'none')
2293                 $(r.obj).show();
2294             }
2295             else {
2296               if (r.depth == depth)
2297                 r.parent_uid = parent;
2298               if (r.unread && roots.length)
2299                 roots[roots.length-1].unread_children++;
2300             }
2301           }
2302           row = row.nextSibling;
2303     }
2304
2305     // update unread_children for roots
2306     for (var i=0; i<roots.length; i++)
2307       this.set_unread_children(roots[i].uid);
2308
2309     return count;
2310   };
2311
2312   this.delete_excessive_thread_rows = function()
2313   {
2314     var rows = this.message_list.rows,
2315       tbody = this.message_list.list.tBodies[0],
2316       row = tbody.firstChild,
2317       cnt = this.env.pagesize + 1;
2318
2319     while (row) {
2320       if (row.nodeType == 1 && (r = rows[row.uid])) {
2321             if (!r.depth && cnt)
2322               cnt--;
2323
2324         if (!cnt)
2325               this.message_list.remove_row(row.uid);
2326           }
2327           row = row.nextSibling;
2328     }
2329   };
2330
2331   // set message icon
2332   this.set_message_icon = function(uid)
2333   {
2334     var css_class,
2335       row = this.message_list.rows[uid];
2336
2337     if (!row)
2338       return false;
2339
2340     if (row.icon) {
2341       css_class = 'msgicon';
2342       if (row.deleted)
2343         css_class += ' deleted';
2344       else if (row.unread)
2345         css_class += ' unread';
2346       else if (row.unread_children)
2347         css_class += ' unreadchildren';
2348       if (row.msgicon == row.icon) {
2349         if (row.replied)
2350           css_class += ' replied';
2351         if (row.forwarded)
2352           css_class += ' forwarded';
2353         css_class += ' status';
2354       }
2355
2356       row.icon.className = css_class;
2357     }
2358
2359     if (row.msgicon && row.msgicon != row.icon) {
2360       css_class = 'msgicon';
2361       if (!row.unread && row.unread_children)
2362         css_class += ' unreadchildren';
2363       if (row.replied)
2364         css_class += ' replied';
2365       if (row.forwarded)
2366         css_class += ' forwarded';
2367
2368       row.msgicon.className = css_class;
2369     }
2370
2371     if (row.flagicon) {
2372       css_class = (row.flagged ? 'flagged' : 'unflagged');
2373       row.flagicon.className = css_class;
2374     }
2375   };
2376
2377   // set message status
2378   this.set_message_status = function(uid, flag, status)
2379   {
2380     var row = this.message_list.rows[uid];
2381
2382     if (!row)
2383       return false;
2384
2385     if (flag == 'unread')
2386       row.unread = status;
2387     else if(flag == 'deleted')
2388       row.deleted = status;
2389     else if (flag == 'replied')
2390       row.replied = status;
2391     else if (flag == 'forwarded')
2392       row.forwarded = status;
2393     else if (flag == 'flagged')
2394       row.flagged = status;
2395   };
2396
2397   // set message row status, class and icon
2398   this.set_message = function(uid, flag, status)
2399   {
2400     var row = this.message_list.rows[uid];
2401
2402     if (!row)
2403       return false;
2404
2405     if (flag)
2406       this.set_message_status(uid, flag, status);
2407
2408     var rowobj = $(row.obj);
2409
2410     if (row.unread && !rowobj.hasClass('unread'))
2411       rowobj.addClass('unread');
2412     else if (!row.unread && rowobj.hasClass('unread'))
2413       rowobj.removeClass('unread');
2414
2415     if (row.deleted && !rowobj.hasClass('deleted'))
2416       rowobj.addClass('deleted');
2417     else if (!row.deleted && rowobj.hasClass('deleted'))
2418       rowobj.removeClass('deleted');
2419
2420     if (row.flagged && !rowobj.hasClass('flagged'))
2421       rowobj.addClass('flagged');
2422     else if (!row.flagged && rowobj.hasClass('flagged'))
2423       rowobj.removeClass('flagged');
2424
2425     this.set_unread_children(uid);
2426     this.set_message_icon(uid);
2427   };
2428
2429   // sets unroot (unread_children) class of parent row
2430   this.set_unread_children = function(uid)
2431   {
2432     var row = this.message_list.rows[uid];
2433
2434     if (row.parent_uid)
2435       return;
2436
2437     if (!row.unread && row.unread_children && !row.expanded)
2438       $(row.obj).addClass('unroot');
2439     else
2440       $(row.obj).removeClass('unroot');
2441   };
2442
2443   // copy selected messages to the specified mailbox
2444   this.copy_messages = function(mbox)
2445   {
2446     if (mbox && typeof mbox === 'object')
2447       mbox = mbox.id;
2448
2449     // exit if current or no mailbox specified or if selection is empty
2450     if (!mbox || mbox == this.env.mailbox || (!this.env.uid && (!this.message_list || !this.message_list.get_selection().length)))
2451       return;
2452
2453     var a_uids = [],
2454       lock = this.display_message(this.get_label('copyingmessage'), 'loading'),
2455       add_url = '&_target_mbox='+urlencode(mbox)+'&_from='+(this.env.action ? this.env.action : '');
2456
2457     if (this.env.uid)
2458       a_uids[0] = this.env.uid;
2459     else {
2460       var selection = this.message_list.get_selection();
2461       for (var n in selection) {
2462         a_uids.push(selection[n]);
2463       }
2464     }
2465
2466     add_url += '&_uid='+this.uids_to_list(a_uids);
2467
2468     // send request to server
2469     this.http_post('copy', '_mbox='+urlencode(this.env.mailbox)+add_url, lock);
2470   };
2471
2472   // move selected messages to the specified mailbox
2473   this.move_messages = function(mbox)
2474   {
2475     if (mbox && typeof mbox === 'object')
2476       mbox = mbox.id;
2477
2478     // exit if current or no mailbox specified or if selection is empty
2479     if (!mbox || mbox == this.env.mailbox || (!this.env.uid && (!this.message_list || !this.message_list.get_selection().length)))
2480       return;
2481
2482     var lock = false,
2483       add_url = '&_target_mbox='+urlencode(mbox)+'&_from='+(this.env.action ? this.env.action : '');
2484
2485     // show wait message
2486     if (this.env.action == 'show') {
2487       lock = this.set_busy(true, 'movingmessage');
2488     }
2489     else
2490       this.show_contentframe(false);
2491
2492     // Hide message command buttons until a message is selected
2493     this.enable_command(this.env.message_commands, false);
2494
2495     this._with_selected_messages('moveto', lock, add_url);
2496   };
2497
2498   // delete selected messages from the current mailbox
2499   this.delete_messages = function()
2500   {
2501     var uid, i, len, trash = this.env.trash_mailbox,
2502       list = this.message_list,
2503       selection = list ? $.merge([], list.get_selection()) : [];
2504
2505     // exit if no mailbox specified or if selection is empty
2506     if (!this.env.uid && !selection.length)
2507       return;
2508
2509     // also select childs of collapsed rows
2510     for (i=0, len=selection.length; i<len; i++) {
2511       uid = selection[i];
2512       if (list.rows[uid].has_children && !list.rows[uid].expanded)
2513         list.select_childs(uid);
2514     }
2515
2516     // if config is set to flag for deletion
2517     if (this.env.flag_for_deletion) {
2518       this.mark_message('delete');
2519       return false;
2520     }
2521     // if there isn't a defined trash mailbox or we are in it
2522     // @TODO: we should check if defined trash mailbox exists
2523     else if (!trash || this.env.mailbox == trash)
2524       this.permanently_remove_messages();
2525     // if there is a trash mailbox defined and we're not currently in it
2526     else {
2527       // if shift was pressed delete it immediately
2528       if (list && list.modkey == SHIFT_KEY) {
2529         if (confirm(this.get_label('deletemessagesconfirm')))
2530           this.permanently_remove_messages();
2531       }
2532       else
2533         this.move_messages(trash);
2534     }
2535
2536     return true;
2537   };
2538
2539   // delete the selected messages permanently
2540   this.permanently_remove_messages = function()
2541   {
2542     // exit if no mailbox specified or if selection is empty
2543     if (!this.env.uid && (!this.message_list || !this.message_list.get_selection().length))
2544       return;
2545
2546     this.show_contentframe(false);
2547     this._with_selected_messages('delete', false, '&_from='+(this.env.action ? this.env.action : ''));
2548   };
2549
2550   // Send a specifc moveto/delete request with UIDs of all selected messages
2551   // @private
2552   this._with_selected_messages = function(action, lock, add_url)
2553   {
2554     var a_uids = [], count = 0, msg;
2555
2556     if (this.env.uid)
2557       a_uids[0] = this.env.uid;
2558     else {
2559       var n, id, root, roots = [],
2560         selection = this.message_list.get_selection();
2561
2562       for (n=0, len=selection.length; n<len; n++) {
2563         id = selection[n];
2564         a_uids.push(id);
2565
2566         if (this.env.threading) {
2567           count += this.update_thread(id);
2568           root = this.message_list.find_root(id);
2569           if (root != id && $.inArray(root, roots) < 0) {
2570             roots.push(root);
2571           }
2572         }
2573         this.message_list.remove_row(id, (this.env.display_next && n == selection.length-1));
2574       }
2575       // make sure there are no selected rows
2576       if (!this.env.display_next)
2577         this.message_list.clear_selection();
2578       // update thread tree icons
2579       for (n=0, len=roots.length; n<len; n++) {
2580         this.add_tree_icons(roots[n]);
2581       }
2582     }
2583
2584     // also send search request to get the right messages
2585     if (this.env.search_request)
2586       add_url += '&_search='+this.env.search_request;
2587
2588     if (this.env.display_next && this.env.next_uid)
2589       add_url += '&_next_uid='+this.env.next_uid;
2590
2591     if (count < 0)
2592       add_url += '&_count='+(count*-1);
2593     else if (count > 0) 
2594       // remove threads from the end of the list
2595       this.delete_excessive_thread_rows();
2596
2597     add_url += '&_uid='+this.uids_to_list(a_uids);
2598
2599     if (!lock) {
2600       msg = action == 'moveto' ? 'movingmessage' : 'deletingmessage';
2601       lock = this.display_message(this.get_label(msg), 'loading');
2602     }
2603
2604     // send request to server
2605     this.http_post(action, '_mbox='+urlencode(this.env.mailbox)+add_url, lock);
2606   };
2607
2608   // set a specific flag to one or more messages
2609   this.mark_message = function(flag, uid)
2610   {
2611     var a_uids = [], r_uids = [], len, n, id,
2612       selection = this.message_list ? this.message_list.get_selection() : [];
2613
2614     if (uid)
2615       a_uids[0] = uid;
2616     else if (this.env.uid)
2617       a_uids[0] = this.env.uid;
2618     else if (this.message_list) {
2619       for (n=0, len=selection.length; n<len; n++) {
2620           a_uids.push(selection[n]);
2621       }
2622     }
2623
2624     if (!this.message_list)
2625       r_uids = a_uids;
2626     else
2627       for (n=0, len=a_uids.length; n<len; n++) {
2628         id = a_uids[n];
2629         if ((flag=='read' && this.message_list.rows[id].unread) 
2630             || (flag=='unread' && !this.message_list.rows[id].unread)
2631             || (flag=='delete' && !this.message_list.rows[id].deleted)
2632             || (flag=='undelete' && this.message_list.rows[id].deleted)
2633             || (flag=='flagged' && !this.message_list.rows[id].flagged)
2634             || (flag=='unflagged' && this.message_list.rows[id].flagged))
2635         {
2636           r_uids.push(id);
2637         }
2638       }
2639
2640     // nothing to do
2641     if (!r_uids.length && !this.select_all_mode)
2642       return;
2643
2644     switch (flag) {
2645         case 'read':
2646         case 'unread':
2647           this.toggle_read_status(flag, r_uids);
2648           break;
2649         case 'delete':
2650         case 'undelete':
2651           this.toggle_delete_status(r_uids);
2652           break;
2653         case 'flagged':
2654         case 'unflagged':
2655           this.toggle_flagged_status(flag, a_uids);
2656           break;
2657     }
2658   };
2659
2660   // set class to read/unread
2661   this.toggle_read_status = function(flag, a_uids)
2662   {
2663     var i, len = a_uids.length,
2664       url = '_uid='+this.uids_to_list(a_uids)+'&_flag='+flag,
2665       lock = this.display_message(this.get_label('markingmessage'), 'loading');
2666
2667     // mark all message rows as read/unread
2668     for (i=0; i<len; i++)
2669       this.set_message(a_uids[i], 'unread', (flag=='unread' ? true : false));
2670
2671     // also send search request to get the right messages
2672     if (this.env.search_request)
2673       url += '&_search='+this.env.search_request;
2674
2675     this.http_post('mark', url, lock);
2676
2677     for (i=0; i<len; i++)
2678       this.update_thread_root(a_uids[i], flag);
2679   };
2680
2681   // set image to flagged or unflagged
2682   this.toggle_flagged_status = function(flag, a_uids)
2683   {
2684     var i, len = a_uids.length,
2685       url = '_uid='+this.uids_to_list(a_uids)+'&_flag='+flag,
2686       lock = this.display_message(this.get_label('markingmessage'), 'loading');
2687
2688     // mark all message rows as flagged/unflagged
2689     for (i=0; i<len; i++)
2690       this.set_message(a_uids[i], 'flagged', (flag=='flagged' ? true : false));
2691
2692     // also send search request to get the right messages
2693     if (this.env.search_request)
2694       url += '&_search='+this.env.search_request;
2695
2696     this.http_post('mark', url, lock);
2697   };
2698
2699   // mark all message rows as deleted/undeleted
2700   this.toggle_delete_status = function(a_uids)
2701   {
2702     var len = a_uids.length,
2703       i, uid, all_deleted = true,
2704       rows = this.message_list ? this.message_list.rows : [];
2705
2706     if (len == 1) {
2707       if (!rows.length || (rows[a_uids[0]] && !rows[a_uids[0]].deleted))
2708         this.flag_as_deleted(a_uids);
2709       else
2710         this.flag_as_undeleted(a_uids);
2711
2712       return true;
2713     }
2714
2715     for (i=0; i<len; i++) {
2716       uid = a_uids[i];
2717       if (rows[uid] && !rows[uid].deleted) {
2718         all_deleted = false;
2719         break;
2720       }
2721     }
2722
2723     if (all_deleted)
2724       this.flag_as_undeleted(a_uids);
2725     else
2726       this.flag_as_deleted(a_uids);
2727
2728     return true;
2729   };
2730
2731   this.flag_as_undeleted = function(a_uids)
2732   {
2733     var i, len=a_uids.length,
2734       url = '_uid='+this.uids_to_list(a_uids)+'&_flag=undelete',
2735       lock = this.display_message(this.get_label('markingmessage'), 'loading');
2736
2737     for (i=0; i<len; i++)
2738       this.set_message(a_uids[i], 'deleted', false);
2739
2740     // also send search request to get the right messages
2741     if (this.env.search_request)
2742       url += '&_search='+this.env.search_request;
2743
2744     this.http_post('mark', url, lock);
2745     return true;
2746   };
2747
2748   this.flag_as_deleted = function(a_uids)
2749   {
2750     var add_url = '',
2751       r_uids = [],
2752       rows = this.message_list ? this.message_list.rows : [],
2753       count = 0;
2754
2755     for (var i=0, len=a_uids.length; i<len; i++) {
2756       uid = a_uids[i];
2757       if (rows[uid]) {
2758         if (rows[uid].unread)
2759           r_uids[r_uids.length] = uid;
2760
2761             if (this.env.skip_deleted) {
2762               count += this.update_thread(uid);
2763           this.message_list.remove_row(uid, (this.env.display_next && i == this.message_list.selection.length-1));
2764             }
2765             else
2766               this.set_message(uid, 'deleted', true);
2767       }
2768     }
2769
2770     // make sure there are no selected rows
2771     if (this.env.skip_deleted && this.message_list) {
2772       if(!this.env.display_next)
2773         this.message_list.clear_selection();
2774       if (count < 0)
2775         add_url += '&_count='+(count*-1);
2776       else if (count > 0) 
2777         // remove threads from the end of the list
2778         this.delete_excessive_thread_rows();
2779     }
2780
2781     add_url = '&_from='+(this.env.action ? this.env.action : ''),
2782       lock = this.display_message(this.get_label('markingmessage'), 'loading');
2783
2784     // ??
2785     if (r_uids.length)
2786       add_url += '&_ruid='+this.uids_to_list(r_uids);
2787
2788     if (this.env.skip_deleted) {
2789       if (this.env.display_next && this.env.next_uid)
2790         add_url += '&_next_uid='+this.env.next_uid;
2791     }
2792
2793     // also send search request to get the right messages
2794     if (this.env.search_request)
2795       add_url += '&_search='+this.env.search_request;
2796
2797     this.http_post('mark', '_uid='+this.uids_to_list(a_uids)+'&_flag=delete'+add_url, lock);
2798     return true;
2799   };
2800
2801   // flag as read without mark request (called from backend)
2802   // argument should be a coma-separated list of uids
2803   this.flag_deleted_as_read = function(uids)
2804   {
2805     var icn_src, uid, i, len,
2806       rows = this.message_list ? this.message_list.rows : [];
2807
2808     uids = String(uids).split(',');
2809
2810     for (i=0, len=uids.length; i<len; i++) {
2811       uid = uids[i];
2812       if (rows[uid])
2813         this.set_message(uid, 'unread', false);
2814     }
2815   };
2816
2817   // Converts array of message UIDs to comma-separated list for use in URL
2818   // with select_all mode checking
2819   this.uids_to_list = function(uids)
2820   {
2821     return this.select_all_mode ? '*' : uids.join(',');
2822   };
2823
2824
2825   /*********************************************************/
2826   /*********       mailbox folders methods         *********/
2827   /*********************************************************/
2828
2829   this.expunge_mailbox = function(mbox)
2830   {
2831     var lock, url = '_mbox='+urlencode(mbox);
2832
2833     // lock interface if it's the active mailbox
2834     if (mbox == this.env.mailbox) {
2835       lock = this.set_busy(true, 'loading');
2836       url += '&_reload=1';
2837       if (this.env.search_request)
2838         url += '&_search='+this.env.search_request;
2839     }
2840
2841     // send request to server
2842     this.http_post('expunge', url, lock);
2843   };
2844
2845   this.purge_mailbox = function(mbox)
2846   {
2847     var lock = false,
2848       url = '_mbox='+urlencode(mbox);
2849
2850     if (!confirm(this.get_label('purgefolderconfirm')))
2851       return false;
2852
2853     // lock interface if it's the active mailbox
2854     if (mbox == this.env.mailbox) {
2855        lock = this.set_busy(true, 'loading');
2856        url += '&_reload=1';
2857      }
2858
2859     // send request to server
2860     this.http_post('purge', url, lock);
2861   };
2862
2863   // test if purge command is allowed
2864   this.purge_mailbox_test = function()
2865   {
2866     return (this.env.messagecount && (this.env.mailbox == this.env.trash_mailbox || this.env.mailbox == this.env.junk_mailbox
2867       || this.env.mailbox.match('^' + RegExp.escape(this.env.trash_mailbox) + RegExp.escape(this.env.delimiter))
2868       || this.env.mailbox.match('^' + RegExp.escape(this.env.junk_mailbox) + RegExp.escape(this.env.delimiter))));
2869   };
2870
2871
2872   /*********************************************************/
2873   /*********           login form methods          *********/
2874   /*********************************************************/
2875
2876   // handler for keyboard events on the _user field
2877   this.login_user_keyup = function(e)
2878   {
2879     var key = rcube_event.get_keycode(e);
2880     var passwd = $('#rcmloginpwd');
2881
2882     // enter
2883     if (key == 13 && passwd.length && !passwd.val()) {
2884       passwd.focus();
2885       return rcube_event.cancel(e);
2886     }
2887
2888     return true;
2889   };
2890
2891
2892   /*********************************************************/
2893   /*********        message compose methods        *********/
2894   /*********************************************************/
2895
2896   // init message compose form: set focus and eventhandlers
2897   this.init_messageform = function()
2898   {
2899     if (!this.gui_objects.messageform)
2900       return false;
2901
2902     var input_from = $("[name='_from']"),
2903       input_to = $("[name='_to']"),
2904       input_subject = $("input[name='_subject']"),
2905       input_message = $("[name='_message']").get(0),
2906       html_mode = $("input[name='_is_html']").val() == '1',
2907       ac_fields = ['cc', 'bcc', 'replyto', 'followupto'],
2908       ac_props;
2909
2910     // configure parallel autocompletion
2911     if (this.env.autocomplete_threads > 0) {
2912       ac_props = {
2913         threads: this.env.autocomplete_threads,
2914         sources: this.env.autocomplete_sources
2915       };
2916     }
2917
2918     // init live search events
2919     this.init_address_input_events(input_to, ac_props);
2920     for (var i in ac_fields) {
2921       this.init_address_input_events($("[name='_"+ac_fields[i]+"']"), ac_props);
2922     }
2923
2924     if (!html_mode) {
2925       this.set_caret_pos(input_message, this.env.top_posting ? 0 : $(input_message).val().length);
2926       // add signature according to selected identity
2927       // if we have HTML editor, signature is added in callback
2928       if (input_from.prop('type') == 'select-one' && $("input[name='_draft_saveid']").val() == '') {
2929         this.change_identity(input_from[0]);
2930       }
2931     }
2932
2933     if (input_to.val() == '')
2934       input_to.focus();
2935     else if (input_subject.val() == '')
2936       input_subject.focus();
2937     else if (input_message)
2938       input_message.focus();
2939
2940     this.env.compose_focus_elem = document.activeElement;
2941
2942     // get summary of all field values
2943     this.compose_field_hash(true);
2944
2945     // start the auto-save timer
2946     this.auto_save_start();
2947   };
2948
2949   this.init_address_input_events = function(obj, props)
2950   {
2951     this.env.recipients_delimiter = this.env.recipients_separator + ' ';
2952
2953     obj[bw.ie || bw.safari || bw.chrome ? 'keydown' : 'keypress'](function(e) { return ref.ksearch_keydown(e, this, props); })
2954       .attr('autocomplete', 'off');
2955   };
2956
2957   // checks the input fields before sending a message
2958   this.check_compose_input = function(cmd)
2959   {
2960     // check input fields
2961     var ed, input_to = $("[name='_to']"),
2962       input_cc = $("[name='_cc']"),
2963       input_bcc = $("[name='_bcc']"),
2964       input_from = $("[name='_from']"),
2965       input_subject = $("[name='_subject']"),
2966       input_message = $("[name='_message']");
2967
2968     // check sender (if have no identities)
2969     if (input_from.prop('type') == 'text' && !rcube_check_email(input_from.val(), true)) {
2970       alert(this.get_label('nosenderwarning'));
2971       input_from.focus();
2972       return false;
2973     }
2974
2975     // check for empty recipient
2976     var recipients = input_to.val() ? input_to.val() : (input_cc.val() ? input_cc.val() : input_bcc.val());
2977     if (!rcube_check_email(recipients.replace(/^\s+/, '').replace(/[\s,;]+$/, ''), true)) {
2978       alert(this.get_label('norecipientwarning'));
2979       input_to.focus();
2980       return false;
2981     }
2982
2983     // check if all files has been uploaded
2984     for (var key in this.env.attachments) {
2985       if (typeof this.env.attachments[key] === 'object' && !this.env.attachments[key].complete) {
2986         alert(this.get_label('notuploadedwarning'));
2987         return false;
2988       }
2989     }
2990
2991     // display localized warning for missing subject
2992     if (input_subject.val() == '') {
2993       var myprompt = $('<div class="prompt">').html('<div class="message">' + this.get_label('nosubjectwarning') + '</div>').appendTo(document.body);
2994       var prompt_value = $('<input>').attr('type', 'text').attr('size', 30).appendTo(myprompt).val(this.get_label('nosubject'));
2995
2996       var buttons = {};
2997       buttons[this.get_label('cancel')] = function(){
2998         input_subject.focus();
2999         $(this).dialog('close');
3000       };
3001       buttons[this.get_label('sendmessage')] = function(){
3002         input_subject.val(prompt_value.val());
3003         $(this).dialog('close');
3004         ref.command(cmd, { nocheck:true });  // repeat command which triggered this
3005       };
3006
3007       myprompt.dialog({
3008         modal: true,
3009         resizable: false,
3010         buttons: buttons,
3011         close: function(event, ui) { $(this).remove() }
3012       });
3013       prompt_value.select();
3014       return false;
3015     }
3016
3017     // Apply spellcheck changes if spell checker is active
3018     this.stop_spellchecking();
3019
3020     if (window.tinyMCE)
3021       ed = tinyMCE.get(this.env.composebody);
3022
3023     // check for empty body
3024     if (!ed && input_message.val() == '' && !confirm(this.get_label('nobodywarning'))) {
3025       input_message.focus();
3026       return false;
3027     }
3028     else if (ed) {
3029       if (!ed.getContent() && !confirm(this.get_label('nobodywarning'))) {
3030         ed.focus();
3031         return false;
3032       }
3033       // move body from html editor to textarea (just to be sure, #1485860)
3034       tinyMCE.triggerSave();
3035     }
3036
3037     return true;
3038   };
3039
3040   this.toggle_editor = function(props)
3041   {
3042     if (props.mode == 'html') {
3043       this.display_spellcheck_controls(false);
3044       this.plain2html($('#'+props.id).val(), props.id);
3045       tinyMCE.execCommand('mceAddControl', false, props.id);
3046     }
3047     else {
3048       var thisMCE = tinyMCE.get(props.id), existingHtml;
3049       if (thisMCE.plugins.spellchecker && thisMCE.plugins.spellchecker.active)
3050         thisMCE.execCommand('mceSpellCheck', false);
3051
3052       if (existingHtml = thisMCE.getContent()) {
3053         if (!confirm(this.get_label('editorwarning'))) {
3054           return false;
3055         }
3056         this.html2plain(existingHtml, props.id);
3057       }
3058       tinyMCE.execCommand('mceRemoveControl', false, props.id);
3059       this.display_spellcheck_controls(true);
3060     }
3061
3062     return true;
3063   };
3064
3065   this.stop_spellchecking = function()
3066   {
3067     var ed;
3068     if (window.tinyMCE && (ed = tinyMCE.get(this.env.composebody))) {
3069       if (ed.plugins.spellchecker && ed.plugins.spellchecker.active)
3070         ed.execCommand('mceSpellCheck');
3071     }
3072     else if ((ed = this.env.spellcheck) && !this.spellcheck_ready) {
3073       $(ed.spell_span).trigger('click');
3074       this.set_spellcheck_state('ready');
3075     }
3076   };
3077
3078   this.display_spellcheck_controls = function(vis)
3079   {
3080     if (this.env.spellcheck) {
3081       // stop spellchecking process
3082       if (!vis)
3083         this.stop_spellchecking();
3084
3085       $(this.env.spellcheck.spell_container).css('visibility', vis ? 'visible' : 'hidden');
3086     }
3087   };
3088
3089   this.set_spellcheck_state = function(s)
3090   {
3091     this.spellcheck_ready = (s == 'ready' || s == 'no_error_found');
3092     this.enable_command('spellcheck', this.spellcheck_ready);
3093   };
3094
3095   // get selected language
3096   this.spellcheck_lang = function()
3097   {
3098     var ed;
3099     if (window.tinyMCE && (ed = tinyMCE.get(this.env.composebody)) && ed.plugins.spellchecker) {
3100       return ed.plugins.spellchecker.selectedLang;
3101     }
3102     else if (this.env.spellcheck) {
3103       return GOOGIE_CUR_LANG;
3104     }
3105   };
3106
3107   // resume spellchecking, highlight provided mispellings without new ajax request
3108   this.spellcheck_resume = function(ishtml, data)
3109   {
3110     if (ishtml) {
3111       var ed = tinyMCE.get(this.env.composebody);
3112         sp = ed.plugins.spellchecker;
3113
3114       sp.active = 1;
3115       sp._markWords(data);
3116       ed.nodeChanged();
3117     }
3118     else {
3119       var sp = this.env.spellcheck;
3120       sp.prepare(false, true);
3121       sp.processData(data);
3122     }
3123   }
3124
3125   this.set_draft_id = function(id)
3126   {
3127     $("input[name='_draft_saveid']").val(id);
3128   };
3129
3130   this.auto_save_start = function()
3131   {
3132     if (this.env.draft_autosave)
3133       this.save_timer = self.setTimeout(function(){ ref.command("savedraft"); }, this.env.draft_autosave * 1000);
3134
3135     // Unlock interface now that saving is complete
3136     this.busy = false;
3137   };
3138
3139   this.compose_field_hash = function(save)
3140   {
3141     // check input fields
3142     var ed, str = '',
3143       value_to = $("[name='_to']").val(),
3144       value_cc = $("[name='_cc']").val(),
3145       value_bcc = $("[name='_bcc']").val(),
3146       value_subject = $("[name='_subject']").val();
3147
3148     if (value_to)
3149       str += value_to+':';
3150     if (value_cc)
3151       str += value_cc+':';
3152     if (value_bcc)
3153       str += value_bcc+':';
3154     if (value_subject)
3155       str += value_subject+':';
3156
3157     if (window.tinyMCE && (ed = tinyMCE.get(this.env.composebody)))
3158       str += ed.getContent();
3159     else
3160       str += $("[name='_message']").val();
3161
3162     if (this.env.attachments)
3163       for (var upload_id in this.env.attachments)
3164         str += upload_id;
3165
3166     if (save)
3167       this.cmp_hash = str;
3168
3169     return str;
3170   };
3171
3172   this.change_identity = function(obj, show_sig)
3173   {
3174     if (!obj || !obj.options)
3175       return false;
3176
3177     if (!show_sig)
3178       show_sig = this.env.show_sig;
3179
3180     var cursor_pos, p = -1,
3181       id = obj.options[obj.selectedIndex].value,
3182       input_message = $("[name='_message']"),
3183       message = input_message.val(),
3184       is_html = ($("input[name='_is_html']").val() == '1'),
3185       sig = this.env.identity,
3186       sig_separator = this.env.sig_above && (this.env.compose_mode == 'reply' || this.env.compose_mode == 'forward') ? '---' : '-- ';
3187
3188     // enable manual signature insert
3189     if (this.env.signatures && this.env.signatures[id]) {
3190       this.enable_command('insert-sig', true);
3191       this.env.compose_commands.push('insert-sig');
3192     }
3193     else
3194       this.enable_command('insert-sig', false);
3195
3196     if (!is_html) {
3197       // remove the 'old' signature
3198       if (show_sig && sig && this.env.signatures && this.env.signatures[sig]) {
3199
3200         sig = this.env.signatures[sig].is_html ? this.env.signatures[sig].plain_text : this.env.signatures[sig].text;
3201         sig = sig.replace(/\r\n/g, '\n');
3202
3203         if (!sig.match(/^--[ -]\n/m))
3204           sig = sig_separator + '\n' + sig;
3205
3206         p = this.env.sig_above ? message.indexOf(sig) : message.lastIndexOf(sig);
3207         if (p >= 0)
3208           message = message.substring(0, p) + message.substring(p+sig.length, message.length);
3209       }
3210       // add the new signature string
3211       if (show_sig && this.env.signatures && this.env.signatures[id]) {
3212         sig = this.env.signatures[id]['is_html'] ? this.env.signatures[id]['plain_text'] : this.env.signatures[id]['text'];
3213         sig = sig.replace(/\r\n/g, '\n');
3214
3215         if (!sig.match(/^--[ -]\n/m))
3216           sig = sig_separator + '\n' + sig;
3217
3218         if (this.env.sig_above) {
3219           if (p >= 0) { // in place of removed signature
3220             message = message.substring(0, p) + sig + message.substring(p, message.length);
3221             cursor_pos = p - 1;
3222           }
3223           else if (pos = this.get_caret_pos(input_message.get(0))) { // at cursor position
3224             message = message.substring(0, pos) + '\n' + sig + '\n\n' + message.substring(pos, message.length);
3225             cursor_pos = pos;
3226           }
3227           else { // on top
3228             cursor_pos = 0;
3229             message = '\n\n' + sig + '\n\n' + message.replace(/^[\r\n]+/, '');
3230           }
3231         }
3232         else {
3233           message = message.replace(/[\r\n]+$/, '');
3234           cursor_pos = !this.env.top_posting && message.length ? message.length+1 : 0;
3235           message += '\n\n' + sig;
3236         }
3237       }
3238       else
3239         cursor_pos = this.env.top_posting ? 0 : message.length;
3240
3241       input_message.val(message);
3242
3243       // move cursor before the signature
3244       this.set_caret_pos(input_message.get(0), cursor_pos);
3245     }
3246     else if (show_sig && this.env.signatures) {  // html
3247       var editor = tinyMCE.get(this.env.composebody),
3248         sigElem = editor.dom.get('_rc_sig');
3249
3250       // Append the signature as a div within the body
3251       if (!sigElem) {
3252         var body = editor.getBody(),
3253           doc = editor.getDoc();
3254
3255         sigElem = doc.createElement('div');
3256         sigElem.setAttribute('id', '_rc_sig');
3257
3258         if (this.env.sig_above) {
3259           // if no existing sig and top posting then insert at caret pos
3260           editor.getWin().focus(); // correct focus in IE & Chrome
3261
3262           var node = editor.selection.getNode();
3263           if (node.nodeName == 'BODY') {
3264             // no real focus, insert at start
3265             body.insertBefore(sigElem, body.firstChild);
3266             body.insertBefore(doc.createElement('br'), body.firstChild);
3267           }
3268           else {
3269             body.insertBefore(sigElem, node.nextSibling);
3270             body.insertBefore(doc.createElement('br'), node.nextSibling);
3271           }
3272         }
3273         else {
3274           if (bw.ie)  // add empty line before signature on IE
3275             body.appendChild(doc.createElement('br'));
3276
3277           body.appendChild(sigElem);
3278         }
3279       }
3280
3281       if (this.env.signatures[id]) {
3282         if (this.env.signatures[id].is_html) {
3283           sig = this.env.signatures[id].text;
3284           if (!this.env.signatures[id].plain_text.match(/^--[ -]\r?\n/m))
3285             sig = sig_separator + '<br />' + sig;
3286         }
3287         else {
3288           sig = this.env.signatures[id].text;
3289           if (!sig.match(/^--[ -]\r?\n/m))
3290             sig = sig_separator + '\n' + sig;
3291           sig = '<pre>' + sig + '</pre>';
3292         }
3293
3294         sigElem.innerHTML = sig;
3295       }
3296     }
3297
3298     this.env.identity = id;
3299     return true;
3300   };
3301
3302   // upload attachment file
3303   this.upload_file = function(form)
3304   {
3305     if (!form)
3306       return false;
3307
3308     // get file input field, count files on capable browser
3309     var i, size = 0, field = $('input[type=file]', form).get(0),
3310       files = field.files ? field.files.length : field.value ? 1 : 0;
3311
3312     // create hidden iframe and post upload form
3313     if (files) {
3314       // check file size
3315       if (field.files && this.env.max_filesize && this.env.filesizeerror) {
3316         for (i=0; i<files; i++)
3317           size += field.files[i].size;
3318         if (size && size > this.env.max_filesize) {
3319           this.display_message(this.env.filesizeerror, 'error');
3320           return;
3321         }
3322       }
3323
3324       var frame_name = this.async_upload_form(form, 'upload', function(e) {
3325         var d, content = '';
3326         try {
3327           if (this.contentDocument) {
3328             d = this.contentDocument;
3329           } else if (this.contentWindow) {
3330             d = this.contentWindow.document;
3331           }
3332           content = d.childNodes[0].innerHTML;
3333         } catch (err) {}
3334
3335         if (!content.match(/add2attachment/) && (!bw.opera || (rcmail.env.uploadframe && rcmail.env.uploadframe == e.data.ts))) {
3336           if (!content.match(/display_message/))
3337             rcmail.display_message(rcmail.get_label('fileuploaderror'), 'error');
3338           rcmail.remove_from_attachment_list(e.data.ts);
3339         }
3340         // Opera hack: handle double onload
3341         if (bw.opera)
3342           rcmail.env.uploadframe = e.data.ts;
3343       });
3344
3345       // display upload indicator and cancel button
3346       var content = '<span>' + this.get_label('uploading' + (files > 1 ? 'many' : '')) + '</span>',
3347         ts = frame_name.replace(/^rcmupload/, '');
3348
3349       if (this.env.loadingicon)
3350         content = '<img src="'+this.env.loadingicon+'" alt="" />'+content;
3351       if (this.env.cancelicon)
3352         content = '<a title="'+this.get_label('cancel')+'" onclick="return rcmail.cancel_attachment_upload(\''+ts+'\', \''+frame_name+'\');" href="#cancelupload"><img src="'+this.env.cancelicon+'" alt="" /></a>'+content;
3353       this.add2attachment_list(ts, { name:'', html:content, complete:false });
3354
3355       // upload progress support
3356       if (this.env.upload_progress_time) {
3357         this.upload_progress_start('upload', ts);
3358       }
3359     }
3360
3361     // set reference to the form object
3362     this.gui_objects.attachmentform = form;
3363     return true;
3364   };
3365
3366   // add file name to attachment list
3367   // called from upload page
3368   this.add2attachment_list = function(name, att, upload_id)
3369   {
3370     if (!this.gui_objects.attachmentlist)
3371       return false;
3372
3373     var indicator, li = $('<li>').attr('id', name).html(att.html);
3374
3375     // replace indicator's li
3376     if (upload_id && (indicator = document.getElementById(upload_id))) {
3377       li.replaceAll(indicator);
3378     }
3379     else { // add new li
3380       li.appendTo(this.gui_objects.attachmentlist);
3381     }
3382
3383     if (upload_id && this.env.attachments[upload_id])
3384       delete this.env.attachments[upload_id];
3385
3386     this.env.attachments[name] = att;
3387
3388     return true;
3389   };
3390
3391   this.remove_from_attachment_list = function(name)
3392   {
3393     delete this.env.attachments[name];
3394     $('#'+name).remove();
3395   };
3396
3397   this.remove_attachment = function(name)
3398   {
3399     if (name && this.env.attachments[name])
3400       this.http_post('remove-attachment', { _id:this.env.compose_id, _file:name });
3401
3402     return true;
3403   };
3404
3405   this.cancel_attachment_upload = function(name, frame_name)
3406   {
3407     if (!name || !frame_name)
3408       return false;
3409
3410     this.remove_from_attachment_list(name);
3411     $("iframe[name='"+frame_name+"']").remove();
3412     return false;
3413   };
3414
3415   this.upload_progress_start = function(action, name)
3416   {
3417     window.setTimeout(function() { rcmail.http_request(action, {_progress: name}); },
3418       this.env.upload_progress_time * 1000);
3419   };
3420
3421   this.upload_progress_update = function(param)
3422   {
3423     var elem = $('#'+param.name + '> span');
3424
3425     if (!elem.length || !param.text)
3426       return;
3427
3428     elem.text(param.text);
3429
3430     if (!param.done)
3431       this.upload_progress_start(param.action, param.name);
3432   };
3433
3434   // send remote request to add a new contact
3435   this.add_contact = function(value)
3436   {
3437     if (value)
3438       this.http_post('addcontact', '_address='+value);
3439
3440     return true;
3441   };
3442
3443   // send remote request to search mail or contacts
3444   this.qsearch = function(value)
3445   {
3446     if (value != '') {
3447       var n, lock = this.set_busy(true, 'searching');
3448
3449       if (this.message_list)
3450         this.clear_message_list();
3451       else if (this.contact_list)
3452         this.list_contacts_clear();
3453
3454       // reset vars
3455       this.env.current_page = 1;
3456       r = this.http_request('search', this.search_params(value)
3457         + (this.env.source ? '&_source='+urlencode(this.env.source) : '')
3458         + (this.env.group ? '&_gid='+urlencode(this.env.group) : ''), lock);
3459
3460       this.env.qsearch = {lock: lock, request: r};
3461     }
3462   };
3463
3464   // build URL params for search
3465   this.search_params = function(search, filter)
3466   {
3467     var n, url = [], mods_arr = [],
3468       mods = this.env.search_mods,
3469       mbox = this.env.mailbox;
3470
3471     if (!filter && this.gui_objects.search_filter)
3472       filter = this.gui_objects.search_filter.value;
3473
3474     if (!search && this.gui_objects.qsearchbox)
3475       search = this.gui_objects.qsearchbox.value;
3476
3477     if (filter)
3478       url.push('_filter=' + urlencode(filter));
3479
3480     if (search) {
3481       url.push('_q='+urlencode(search));
3482
3483       if (mods && this.message_list)
3484         mods = mods[mbox] ? mods[mbox] : mods['*'];
3485
3486       if (mods) {
3487         for (n in mods)
3488           mods_arr.push(n);
3489         url.push('_headers='+mods_arr.join(','));
3490       }
3491     }
3492
3493     if (mbox)
3494       url.push('_mbox='+urlencode(mbox));
3495
3496     return url.join('&');
3497   };
3498
3499   // reset quick-search form
3500   this.reset_qsearch = function()
3501   {
3502     if (this.gui_objects.qsearchbox)
3503       this.gui_objects.qsearchbox.value = '';
3504
3505     if (this.env.qsearch)
3506       this.abort_request(this.env.qsearch);
3507
3508     this.env.qsearch = null;
3509     this.env.search_request = null;
3510     this.env.search_id = null;
3511   };
3512
3513   this.sent_successfully = function(type, msg)
3514   {
3515     this.display_message(msg, type);
3516     // before redirect we need to wait some time for Chrome (#1486177)
3517     window.setTimeout(function(){ ref.list_mailbox(); }, 500);
3518   };
3519
3520
3521   /*********************************************************/
3522   /*********     keyboard live-search methods      *********/
3523   /*********************************************************/
3524
3525   // handler for keyboard events on address-fields
3526   this.ksearch_keydown = function(e, obj, props)
3527   {
3528     if (this.ksearch_timer)
3529       clearTimeout(this.ksearch_timer);
3530
3531     var highlight,
3532       key = rcube_event.get_keycode(e),
3533       mod = rcube_event.get_modifier(e);
3534
3535     switch (key) {
3536       case 38:  // key up
3537       case 40:  // key down
3538         if (!this.ksearch_pane)
3539           break;
3540
3541         var dir = key==38 ? 1 : 0;
3542
3543         highlight = document.getElementById('rcmksearchSelected');
3544         if (!highlight)
3545           highlight = this.ksearch_pane.__ul.firstChild;
3546
3547         if (highlight)
3548           this.ksearch_select(dir ? highlight.previousSibling : highlight.nextSibling);
3549
3550         return rcube_event.cancel(e);
3551
3552       case 9:   // tab
3553         if (mod == SHIFT_KEY || !this.ksearch_visible()) {
3554           this.ksearch_hide();
3555           return;
3556         }
3557
3558       case 13:  // enter
3559         if (!this.ksearch_visible())
3560           return false;
3561
3562         // insert selected address and hide ksearch pane
3563         this.insert_recipient(this.ksearch_selected);
3564         this.ksearch_hide();
3565
3566         return rcube_event.cancel(e);
3567
3568       case 27:  // escape
3569         this.ksearch_hide();
3570         return;
3571
3572       case 37:  // left
3573       case 39:  // right
3574         if (mod != SHIFT_KEY)
3575               return;
3576     }
3577
3578     // start timer
3579     this.ksearch_timer = window.setTimeout(function(){ ref.ksearch_get_results(props); }, 200);
3580     this.ksearch_input = obj;
3581
3582     return true;
3583   };
3584
3585   this.ksearch_visible = function()
3586   {
3587     return (this.ksearch_selected !== null && this.ksearch_selected !== undefined && this.ksearch_value);
3588   };
3589
3590   this.ksearch_select = function(node)
3591   {
3592     var current = $('#rcmksearchSelected');
3593     if (current[0] && node) {
3594       current.removeAttr('id').removeClass('selected');
3595     }
3596
3597     if (node) {
3598       $(node).attr('id', 'rcmksearchSelected').addClass('selected');
3599       this.ksearch_selected = node._rcm_id;
3600     }
3601   };
3602
3603   this.insert_recipient = function(id)
3604   {
3605     if (id === null || !this.env.contacts[id] || !this.ksearch_input)
3606       return;
3607
3608     // get cursor pos
3609     var inp_value = this.ksearch_input.value,
3610       cpos = this.get_caret_pos(this.ksearch_input),
3611       p = inp_value.lastIndexOf(this.ksearch_value, cpos),
3612       trigger = false,
3613       insert = '',
3614       // replace search string with full address
3615       pre = inp_value.substring(0, p),
3616       end = inp_value.substring(p+this.ksearch_value.length, inp_value.length);
3617
3618     this.ksearch_destroy();
3619
3620     // insert all members of a group
3621     if (typeof this.env.contacts[id] === 'object' && this.env.contacts[id].id) {
3622       insert += this.env.contacts[id].name + this.env.recipients_delimiter;
3623       this.group2expand = $.extend({}, this.env.contacts[id]);
3624       this.group2expand.input = this.ksearch_input;
3625       this.http_request('mail/group-expand', '_source='+urlencode(this.env.contacts[id].source)+'&_gid='+urlencode(this.env.contacts[id].id), false);
3626     }
3627     else if (typeof this.env.contacts[id] === 'string') {
3628       insert = this.env.contacts[id] + this.env.recipients_delimiter;
3629       trigger = true;
3630     }
3631
3632     this.ksearch_input.value = pre + insert + end;
3633
3634     // set caret to insert pos
3635     cpos = p+insert.length;
3636     if (this.ksearch_input.setSelectionRange)
3637       this.ksearch_input.setSelectionRange(cpos, cpos);
3638
3639     if (trigger)
3640       this.triggerEvent('autocomplete_insert', { field:this.ksearch_input, insert:insert });
3641   };
3642
3643   this.replace_group_recipients = function(id, recipients)
3644   {
3645     if (this.group2expand && this.group2expand.id == id) {
3646       this.group2expand.input.value = this.group2expand.input.value.replace(this.group2expand.name, recipients);
3647       this.triggerEvent('autocomplete_insert', { field:this.group2expand.input, insert:recipients });
3648       this.group2expand = null;
3649     }
3650   };
3651
3652   // address search processor
3653   this.ksearch_get_results = function(props)
3654   {
3655     var inp_value = this.ksearch_input ? this.ksearch_input.value : null;
3656
3657     if (inp_value === null)
3658       return;
3659
3660     if (this.ksearch_pane && this.ksearch_pane.is(":visible"))
3661       this.ksearch_pane.hide();
3662
3663     // get string from current cursor pos to last comma
3664     var cpos = this.get_caret_pos(this.ksearch_input),
3665       p = inp_value.lastIndexOf(this.env.recipients_separator, cpos-1),
3666       q = inp_value.substring(p+1, cpos),
3667       min = this.env.autocomplete_min_length,
3668       ac = this.ksearch_data;
3669
3670     // trim query string
3671     q = $.trim(q);
3672
3673     // Don't (re-)search if the last results are still active
3674     if (q == this.ksearch_value)
3675       return;
3676
3677     this.ksearch_destroy();
3678
3679     if (q.length && q.length < min) {
3680       if (!this.ksearch_info) {
3681         this.ksearch_info = this.display_message(
3682           this.get_label('autocompletechars').replace('$min', min));
3683       }
3684       return;
3685     }
3686
3687     var old_value = this.ksearch_value;
3688     this.ksearch_value = q;
3689
3690     // ...string is empty
3691     if (!q.length)
3692       return;
3693
3694     // ...new search value contains old one and previous search was not finished or its result was empty
3695     if (old_value && old_value.length && q.indexOf(old_value) == 0 && (!ac || !ac.num) && this.env.contacts && !this.env.contacts.length)
3696       return;
3697
3698     var i, lock, source, xhr, reqid = new Date().getTime(),
3699       threads = props && props.threads ? props.threads : 1,
3700       sources = props && props.sources ? props.sources : [],
3701       action = props && props.action ? props.action : 'mail/autocomplete';
3702
3703     this.ksearch_data = {id: reqid, sources: sources.slice(), action: action,
3704       locks: [], requests: [], num: sources.length};
3705
3706     for (i=0; i<threads; i++) {
3707       source = this.ksearch_data.sources.shift();
3708       if (threads > 1 && source === null)
3709         break;
3710
3711       lock = this.display_message(this.get_label('searching'), 'loading');
3712       xhr = this.http_post(action, '_search='+urlencode(q)+'&_id='+reqid
3713         + (source ? '&_source='+urlencode(source) : ''), lock);
3714
3715       this.ksearch_data.locks.push(lock);
3716       this.ksearch_data.requests.push(xhr);
3717     }
3718   };
3719
3720   this.ksearch_query_results = function(results, search, reqid)
3721   {
3722     // search stopped in meantime?
3723     if (!this.ksearch_value)
3724       return;
3725
3726     // ignore this outdated search response
3727     if (this.ksearch_input && search != this.ksearch_value)
3728       return;
3729
3730     // display search results
3731     var i, len, ul, li, text, init,
3732       value = this.ksearch_value,
3733       data = this.ksearch_data,
3734       maxlen = this.env.autocomplete_max ? this.env.autocomplete_max : 15;
3735
3736     // create results pane if not present
3737     if (!this.ksearch_pane) {
3738       ul = $('<ul>');
3739       this.ksearch_pane = $('<div>').attr('id', 'rcmKSearchpane')
3740         .css({ position:'absolute', 'z-index':30000 }).append(ul).appendTo(document.body);
3741       this.ksearch_pane.__ul = ul[0];
3742     }
3743
3744     ul = this.ksearch_pane.__ul;
3745
3746     // remove all search results or add to existing list if parallel search
3747     if (reqid && this.ksearch_pane.data('reqid') == reqid) {
3748       maxlen -= ul.childNodes.length;
3749     }
3750     else {
3751       this.ksearch_pane.data('reqid', reqid);
3752       init = 1;
3753       // reset content
3754       ul.innerHTML = '';
3755       this.env.contacts = [];
3756       // move the results pane right under the input box
3757       var pos = $(this.ksearch_input).offset();
3758       this.ksearch_pane.css({ left:pos.left+'px', top:(pos.top + this.ksearch_input.offsetHeight)+'px', display: 'none'});
3759     }
3760
3761     // add each result line to list
3762     if (results && (len = results.length)) {
3763       for (i=0; i < len && maxlen > 0; i++) {
3764         text = typeof results[i] === 'object' ? results[i].name : results[i];
3765         li = document.createElement('LI');
3766         li.innerHTML = text.replace(new RegExp('('+RegExp.escape(value)+')', 'ig'), '##$1%%').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/##([^%]+)%%/g, '<b>$1</b>');
3767         li.onmouseover = function(){ ref.ksearch_select(this); };
3768         li.onmouseup = function(){ ref.ksearch_click(this) };
3769         li._rcm_id = this.env.contacts.length + i;
3770         ul.appendChild(li);
3771         maxlen -= 1;
3772       }
3773     }
3774
3775     if (ul.childNodes.length) {
3776       this.ksearch_pane.show();
3777       // select the first
3778       if (!this.env.contacts.length) {
3779         $('li:first', ul).attr('id', 'rcmksearchSelected').addClass('selected');
3780         this.ksearch_selected = 0;
3781       }
3782     }
3783
3784     if (len)
3785       this.env.contacts = this.env.contacts.concat(results);
3786
3787     // run next parallel search
3788     if (data.id == reqid) {
3789       data.num--;
3790       if (maxlen > 0 && data.sources.length) {
3791         var lock, xhr, source = data.sources.shift();
3792         if (source) {
3793           lock = this.display_message(this.get_label('searching'), 'loading');
3794           xhr = this.http_post(data.action, '_search='+urlencode(value)+'&_id='+reqid
3795             +'&_source='+urlencode(source), lock);
3796
3797           this.ksearch_data.locks.push(lock);
3798           this.ksearch_data.requests.push(xhr);
3799         }
3800       }
3801       else if (!maxlen) {
3802         if (!this.ksearch_msg)
3803           this.ksearch_msg = this.display_message(this.get_label('autocompletemore'));
3804         // abort pending searches
3805         this.ksearch_abort();
3806       }
3807     }
3808   };
3809
3810   this.ksearch_click = function(node)
3811   {
3812     if (this.ksearch_input)
3813       this.ksearch_input.focus();
3814
3815     this.insert_recipient(node._rcm_id);
3816     this.ksearch_hide();
3817   };
3818
3819   this.ksearch_blur = function()
3820   {
3821     if (this.ksearch_timer)
3822       clearTimeout(this.ksearch_timer);
3823
3824     this.ksearch_input = null;
3825     this.ksearch_hide();
3826   };
3827
3828   this.ksearch_hide = function()
3829   {
3830     this.ksearch_selected = null;
3831     this.ksearch_value = '';
3832
3833     if (this.ksearch_pane)
3834       this.ksearch_pane.hide();
3835
3836     this.ksearch_destroy();
3837   };
3838
3839   // Clears autocomplete data/requests
3840   this.ksearch_destroy = function()
3841   {
3842     this.ksearch_abort();
3843
3844     if (this.ksearch_info)
3845       this.hide_message(this.ksearch_info);
3846
3847     if (this.ksearch_msg)
3848       this.hide_message(this.ksearch_msg);
3849
3850     this.ksearch_data = null;
3851     this.ksearch_info = null;
3852     this.ksearch_msg = null;
3853   }
3854
3855   // Aborts pending autocomplete requests
3856   this.ksearch_abort = function()
3857   {
3858     var i, len, ac = this.ksearch_data;
3859
3860     if (!ac)
3861       return;
3862
3863     for (i=0, len=ac.locks.length; i<len; i++)
3864       this.abort_request({request: ac.requests[i], lock: ac.locks[i]});
3865   };
3866
3867
3868   /*********************************************************/
3869   /*********         address book methods          *********/
3870   /*********************************************************/
3871
3872   this.contactlist_keypress = function(list)
3873   {
3874     if (list.key_pressed == list.DELETE_KEY)
3875       this.command('delete');
3876   };
3877
3878   this.contactlist_select = function(list)
3879   {
3880     if (this.preview_timer)
3881       clearTimeout(this.preview_timer);
3882
3883     var n, id, sid, ref = this, writable = false,
3884       source = this.env.source ? this.env.address_sources[this.env.source] : null;
3885
3886     if (id = list.get_single_selection())
3887       this.preview_timer = window.setTimeout(function(){ ref.load_contact(id, 'show'); }, 200);
3888     else if (this.env.contentframe)
3889       this.show_contentframe(false);
3890
3891     // no source = search result, we'll need to detect if any of
3892     // selected contacts are in writable addressbook to enable edit/delete
3893     if (list.selection.length) {
3894       if (!source) {
3895         for (n in list.selection) {
3896           sid = String(list.selection[n]).replace(/^[^-]+-/, '');
3897           if (sid && this.env.address_sources[sid] && !this.env.address_sources[sid].readonly) {
3898             writable = true;
3899             break;
3900           }
3901         }
3902       }
3903       else {
3904         writable = !source.readonly;
3905       }
3906     }
3907
3908     this.enable_command('compose', this.env.group || list.selection.length > 0);
3909     this.enable_command('edit', id && writable);
3910     this.enable_command('delete', list.selection.length && writable);
3911
3912     return false;
3913   };
3914
3915   this.list_contacts = function(src, group, page)
3916   {
3917     var folder, add_url = '',
3918       target = window;
3919
3920     if (!src)
3921       src = this.env.source;
3922
3923     if (page && this.current_page == page && src == this.env.source && group == this.env.group)
3924       return false;
3925
3926     if (src != this.env.source) {
3927       page = this.env.current_page = 1;
3928       this.reset_qsearch();
3929     }
3930     else if (group != this.env.group)
3931       page = this.env.current_page = 1;
3932
3933     if (this.env.search_id)
3934       folder = 'S'+this.env.search_id;
3935     else
3936       folder = group ? 'G'+src+group : src;
3937
3938     this.select_folder(folder);
3939
3940     this.env.source = src;
3941     this.env.group = group;
3942
3943     // load contacts remotely
3944     if (this.gui_objects.contactslist) {
3945       this.list_contacts_remote(src, group, page);
3946       return;
3947     }
3948
3949     if (this.env.contentframe && window.frames && window.frames[this.env.contentframe]) {
3950       target = window.frames[this.env.contentframe];
3951       add_url = '&_framed=1';
3952     }
3953
3954     if (group)
3955       add_url += '&_gid='+group;
3956     if (page)
3957       add_url += '&_page='+page;
3958
3959     // also send search request to get the correct listing
3960     if (this.env.search_request)
3961       add_url += '&_search='+this.env.search_request;
3962
3963     this.set_busy(true, 'loading');
3964     this.location_href(this.env.comm_path + (src ? '&_source='+urlencode(src) : '') + add_url, target);
3965   };
3966
3967   // send remote request to load contacts list
3968   this.list_contacts_remote = function(src, group, page)
3969   {
3970     // clear message list first
3971     this.list_contacts_clear();
3972
3973     // send request to server
3974     var url = (src ? '_source='+urlencode(src) : '') + (page ? (src?'&':'') + '_page='+page : ''),
3975       lock = this.set_busy(true, 'loading');
3976
3977     this.env.source = src;
3978     this.env.group = group;
3979
3980     if (group)
3981       url += '&_gid='+group;
3982
3983     // also send search request to get the right messages
3984     if (this.env.search_request)
3985       url += '&_search='+this.env.search_request;
3986
3987     this.http_request('list', url, lock);
3988   };
3989
3990   this.list_contacts_clear = function()
3991   {
3992     this.contact_list.clear(true);
3993     this.show_contentframe(false);
3994     this.enable_command('delete', false);
3995     this.enable_command('compose', this.env.group ? true : false);
3996   };
3997
3998   // load contact record
3999   this.load_contact = function(cid, action, framed)
4000   {
4001     var add_url = '', target = window;
4002
4003     if (this.env.contentframe && window.frames && window.frames[this.env.contentframe]) {
4004       add_url = '&_framed=1';
4005       target = window.frames[this.env.contentframe];
4006       this.show_contentframe(true);
4007
4008       // load dummy content
4009       if (!cid) {
4010         // unselect selected row(s)
4011         this.contact_list.clear_selection();
4012         this.enable_command('delete', 'compose', false);
4013       }
4014     }
4015     else if (framed)
4016       return false;
4017
4018     if (action && (cid || action=='add') && !this.drag_active) {
4019       if (this.env.group)
4020         add_url += '&_gid='+urlencode(this.env.group);
4021
4022       this.location_href(this.env.comm_path+'&_action='+action
4023         +'&_source='+urlencode(this.env.source)
4024         +'&_cid='+urlencode(cid) + add_url, target, true);
4025     }
4026     return true;
4027   };
4028
4029   // add/delete member to/from the group
4030   this.group_member_change = function(what, cid, source, gid)
4031   {
4032     what = what == 'add' ? 'add' : 'del';
4033     var lock = this.display_message(this.get_label(what == 'add' ? 'addingmember' : 'removingmember'), 'loading');
4034
4035     this.http_post('group-'+what+'members', '_cid='+urlencode(cid)
4036       + '&_source='+urlencode(source)
4037       + '&_gid='+urlencode(gid), lock);
4038   };
4039
4040   // copy a contact to the specified target (group or directory)
4041   this.copy_contact = function(cid, to)
4042   {
4043     if (!cid)
4044       cid = this.contact_list.get_selection().join(',');
4045
4046     if (to.type == 'group' && to.source == this.env.source)
4047       this.group_member_change('add', cid, to.source, to.id);
4048     else if (to.type == 'group' && !this.env.address_sources[to.source].readonly) {
4049       var lock = this.display_message(this.get_label('copyingcontact'), 'loading');
4050       this.http_post('copy', '_cid='+urlencode(cid)
4051         + '&_source='+urlencode(this.env.source)
4052         + '&_to='+urlencode(to.source)
4053         + '&_togid='+urlencode(to.id)
4054         + (this.env.group ? '&_gid='+urlencode(this.env.group) : ''), lock);
4055     }
4056     else if (to.id != this.env.source && cid && this.env.address_sources[to.id] && !this.env.address_sources[to.id].readonly) {
4057       var lock = this.display_message(this.get_label('copyingcontact'), 'loading');
4058       this.http_post('copy', '_cid='+urlencode(cid)
4059         + '&_source='+urlencode(this.env.source)
4060         + '&_to='+urlencode(to.id)
4061         + (this.env.group ? '&_gid='+urlencode(this.env.group) : ''), lock);
4062     }
4063   };
4064
4065   this.delete_contacts = function()
4066   {
4067     var selection = this.contact_list.get_selection(),
4068       undelete = this.env.source && this.env.address_sources[this.env.source].undelete;
4069
4070     // exit if no mailbox specified or if selection is empty
4071     if (!(selection.length || this.env.cid) || (!undelete && !confirm(this.get_label('deletecontactconfirm'))))
4072       return;
4073
4074     var id, n, a_cids = [], qs = '';
4075
4076     if (this.env.cid)
4077       a_cids.push(this.env.cid);
4078     else {
4079       for (n=0; n<selection.length; n++) {
4080         id = selection[n];
4081         a_cids.push(id);
4082         this.contact_list.remove_row(id, (n == selection.length-1));
4083       }
4084
4085       // hide content frame if we delete the currently displayed contact
4086       if (selection.length == 1)
4087         this.show_contentframe(false);
4088     }
4089
4090     if (this.env.group)
4091       qs += '&_gid='+urlencode(this.env.group);
4092
4093     // also send search request to get the right records from the next page
4094     if (this.env.search_request)
4095       qs += '&_search='+this.env.search_request;
4096
4097     // send request to server
4098     this.http_post('delete', '_cid='+urlencode(a_cids.join(','))
4099       +'&_source='+urlencode(this.env.source)
4100       +'&_from='+(this.env.action ? this.env.action : '')+qs,
4101       this.display_message(this.get_label('contactdeleting'), 'loading'));
4102
4103     return true;
4104   };
4105
4106   // update a contact record in the list
4107   this.update_contact_row = function(cid, cols_arr, newcid, source)
4108   {
4109     var c, row, list = this.contact_list;
4110
4111     cid = this.html_identifier(cid);
4112
4113     // when in searching mode, concat cid with the source name
4114     if (!list.rows[cid]) {
4115       cid = cid+'-'+source;
4116       if (newcid)
4117         newcid = newcid+'-'+source;
4118     }
4119
4120     if (list.rows[cid] && (row = list.rows[cid].obj)) {
4121       for (c=0; c<cols_arr.length; c++)
4122         if (row.cells[c])
4123           $(row.cells[c]).html(cols_arr[c]);
4124
4125       // cid change
4126       if (newcid) {
4127         newcid = this.html_identifier(newcid);
4128         row.id = 'rcmrow' + newcid;
4129         list.remove_row(cid);
4130         list.init_row(row);
4131         list.selection[0] = newcid;
4132         row.style.display = '';
4133       }
4134     }
4135   };
4136
4137   // add row to contacts list
4138   this.add_contact_row = function(cid, cols, select)
4139   {
4140     if (!this.gui_objects.contactslist)
4141       return false;
4142
4143     var c, list = this.contact_list,
4144       row = document.createElement('tr');
4145
4146     row.id = 'rcmrow'+this.html_identifier(cid);
4147     row.className = 'contact';
4148
4149     if (list.in_selection(cid))
4150       row.className += ' selected';
4151
4152     // add each submitted col
4153     for (c in cols) {
4154       col = document.createElement('td');
4155       col.className = String(c).toLowerCase();
4156       col.innerHTML = cols[c];
4157       row.appendChild(col);
4158     }
4159
4160     list.insert_row(row);
4161
4162     this.enable_command('export', list.rowcount > 0);
4163   };
4164
4165   this.init_contact_form = function()
4166   {
4167     var ref = this, col;
4168
4169     this.set_photo_actions($('#ff_photo').val());
4170
4171     for (col in this.env.coltypes)
4172       this.init_edit_field(col, null);
4173
4174     $('.contactfieldgroup .row a.deletebutton').click(function() {
4175       ref.delete_edit_field(this);
4176       return false;
4177     });
4178
4179     $('select.addfieldmenu').change(function(e) {
4180       ref.insert_edit_field($(this).val(), $(this).attr('rel'), this);
4181       this.selectedIndex = 0;
4182     });
4183
4184     // enable date pickers on date fields
4185     if ($.datepicker && this.env.date_format) {
4186       $.datepicker.setDefaults({
4187         dateFormat: this.env.date_format,
4188         changeMonth: true,
4189         changeYear: true,
4190         yearRange: '-100:+10',
4191         showOtherMonths: true,
4192         selectOtherMonths: true,
4193         monthNamesShort: this.env.month_names,
4194         onSelect: function(dateText) { $(this).focus().val(dateText) }
4195       });
4196       $('input.datepicker').datepicker();
4197     }
4198
4199     $("input[type='text']:visible").first().focus();
4200   };
4201
4202   this.group_create = function()
4203   {
4204     this.add_input_row('contactgroup');
4205   };
4206
4207   this.group_rename = function()
4208   {
4209     if (!this.env.group || !this.gui_objects.folderlist)
4210       return;
4211
4212     if (!this.name_input) {
4213       this.enable_command('list', 'listgroup', false);
4214       this.name_input = $('<input>').attr('type', 'text').val(this.env.contactgroups['G'+this.env.source+this.env.group].name);
4215       this.name_input.bind('keydown', function(e){ return rcmail.add_input_keydown(e); });
4216       this.env.group_renaming = true;
4217
4218       var link, li = this.get_folder_li(this.env.source+this.env.group, 'rcmliG');
4219       if (li && (link = li.firstChild)) {
4220         $(link).hide().before(this.name_input);
4221       }
4222     }
4223
4224     this.name_input.select().focus();
4225   };
4226
4227   this.group_delete = function()
4228   {
4229     if (this.env.group && confirm(this.get_label('deletegroupconfirm'))) {
4230       var lock = this.set_busy(true, 'groupdeleting');
4231       this.http_post('group-delete', '_source='+urlencode(this.env.source)+'&_gid='+urlencode(this.env.group), lock);
4232     }
4233   };
4234
4235   // callback from server upon group-delete command
4236   this.remove_group_item = function(prop)
4237   {
4238     var li, key = 'G'+prop.source+prop.id;
4239     if ((li = this.get_folder_li(key))) {
4240       this.triggerEvent('group_delete', { source:prop.source, id:prop.id, li:li });
4241
4242       li.parentNode.removeChild(li);
4243       delete this.env.contactfolders[key];
4244       delete this.env.contactgroups[key];
4245     }
4246
4247     this.list_contacts(prop.source, 0);
4248   };
4249
4250   // @TODO: maybe it would be better to use popup instead of inserting input to the list?
4251   this.add_input_row = function(type)
4252   {
4253     if (!this.gui_objects.folderlist)
4254       return;
4255
4256     if (!this.name_input) {
4257       this.name_input = $('<input>').attr('type', 'text').data('tt', type);
4258       this.name_input.bind('keydown', function(e){ return rcmail.add_input_keydown(e); });
4259       this.name_input_li = $('<li>').addClass(type).append(this.name_input);
4260
4261       var li = type == 'contactsearch' ? $('li:last', this.gui_objects.folderlist) : this.get_folder_li(this.env.source);
4262       this.name_input_li.insertAfter(li);
4263     }
4264
4265     this.name_input.select().focus();
4266   };
4267
4268   // handler for keyboard events on the input field
4269   this.add_input_keydown = function(e)
4270   {
4271     var key = rcube_event.get_keycode(e),
4272       input = $(e.target), itype = input.data('tt');
4273
4274     // enter
4275     if (key == 13) {
4276       var newname = input.val();
4277
4278       if (newname) {
4279         var lock = this.set_busy(true, 'loading');
4280
4281         if (itype == 'contactsearch')
4282           this.http_post('search-create', '_search='+urlencode(this.env.search_request)+'&_name='+urlencode(newname), lock);
4283         else if (this.env.group_renaming)
4284           this.http_post('group-rename', '_source='+urlencode(this.env.source)+'&_gid='+urlencode(this.env.group)+'&_name='+urlencode(newname), lock);
4285         else
4286           this.http_post('group-create', '_source='+urlencode(this.env.source)+'&_name='+urlencode(newname), lock);
4287       }
4288       return false;
4289     }
4290     // escape
4291     else if (key == 27)
4292       this.reset_add_input();
4293
4294     return true;
4295   };
4296
4297   this.reset_add_input = function()
4298   {
4299     if (this.name_input) {
4300       if (this.env.group_renaming) {
4301         var li = this.name_input.parent();
4302         li.children().last().show();
4303         this.env.group_renaming = false;
4304       }
4305
4306       this.name_input.remove();
4307
4308       if (this.name_input_li)
4309         this.name_input_li.remove();
4310
4311       this.name_input = this.name_input_li = null;
4312     }
4313
4314     this.enable_command('list', 'listgroup', true);
4315   };
4316
4317   // callback for creating a new contact group
4318   this.insert_contact_group = function(prop)
4319   {
4320     this.reset_add_input();
4321
4322     prop.type = 'group';
4323     var key = 'G'+prop.source+prop.id,
4324       link = $('<a>').attr('href', '#')
4325         .attr('rel', prop.source+':'+prop.id)
4326         .click(function() { return rcmail.command('listgroup', prop, this); })
4327         .html(prop.name),
4328       li = $('<li>').attr({id: 'rcmli'+this.html_identifier(key), 'class': 'contactgroup'})
4329         .append(link);
4330
4331     this.env.contactfolders[key] = this.env.contactgroups[key] = prop;
4332     this.add_contact_group_row(prop, li);
4333
4334     this.triggerEvent('group_insert', { id:prop.id, source:prop.source, name:prop.name, li:li[0] });
4335   };
4336
4337   // callback for renaming a contact group
4338   this.update_contact_group = function(prop)
4339   {
4340     this.reset_add_input();
4341
4342     var key = 'G'+prop.source+prop.id,
4343       li = this.get_folder_li(key),
4344       link;
4345
4346     // group ID has changed, replace link node and identifiers
4347     if (li && prop.newid) {
4348       var newkey = 'G'+prop.source+prop.newid,
4349         newprop = $.extend({}, prop);;
4350
4351       li.id = 'rcmli' + this.html_identifier(newkey);
4352       this.env.contactfolders[newkey] = this.env.contactfolders[key];
4353       this.env.contactfolders[newkey].id = prop.newid;
4354       this.env.group = prop.newid;
4355
4356       delete this.env.contactfolders[key];
4357       delete this.env.contactgroups[key];
4358
4359       newprop.id = prop.newid;
4360       newprop.type = 'group';
4361
4362       link = $('<a>').attr('href', '#')
4363         .attr('rel', prop.source+':'+prop.newid)
4364         .click(function() { return rcmail.command('listgroup', newprop, this); })
4365         .html(prop.name);
4366       $(li).children().replaceWith(link);
4367     }
4368     // update displayed group name
4369     else if (li && (link = li.firstChild) && link.tagName.toLowerCase() == 'a')
4370       link.innerHTML = prop.name;
4371
4372     this.env.contactfolders[key].name = this.env.contactgroups[key].name = prop.name;
4373     this.add_contact_group_row(prop, $(li), true);
4374
4375     this.triggerEvent('group_update', { id:prop.id, source:prop.source, name:prop.name, li:li[0], newid:prop.newid });
4376   };
4377
4378   // add contact group row to the list, with sorting
4379   this.add_contact_group_row = function(prop, li, reloc)
4380   {
4381     var row, name = prop.name.toUpperCase(),
4382       sibling = this.get_folder_li(prop.source),
4383       prefix = 'rcmliG' + this.html_identifier(prop.source);
4384
4385     // When renaming groups, we need to remove it from DOM and insert it in the proper place
4386     if (reloc) {
4387       row = li.clone(true);
4388       li.remove();
4389     }
4390     else
4391       row = li;
4392
4393     $('li[id^="'+prefix+'"]', this.gui_objects.folderlist).each(function(i, elem) {
4394       if (name >= $(this).text().toUpperCase())
4395         sibling = elem;
4396       else
4397         return false;
4398     });
4399
4400     row.insertAfter(sibling);
4401   };
4402
4403   this.update_group_commands = function()
4404   {
4405     var source = this.env.source != '' ? this.env.address_sources[this.env.source] : null;
4406     this.enable_command('group-create', (source && source.groups && !source.readonly));
4407     this.enable_command('group-rename', 'group-delete', (source && source.groups && this.env.group && !source.readonly));
4408   };
4409
4410   this.init_edit_field = function(col, elem)
4411   {
4412     if (!elem)
4413       elem = $('.ff_' + col);
4414
4415     elem.focus(function(){ ref.focus_textfield(this); })
4416       .blur(function(){ ref.blur_textfield(this); })
4417       .each(function(){ this._placeholder = this.title = ref.env.coltypes[col].label; ref.blur_textfield(this); });
4418   };
4419
4420   this.insert_edit_field = function(col, section, menu)
4421   {
4422     // just make pre-defined input field visible
4423     var elem = $('#ff_'+col);
4424     if (elem.length) {
4425       elem.show().focus();
4426       $(menu).children('option[value="'+col+'"]').prop('disabled', true);
4427     }
4428     else {
4429       var lastelem = $('.ff_'+col),
4430         appendcontainer = $('#contactsection'+section+' .contactcontroller'+col);
4431
4432       if (!appendcontainer.length)
4433         appendcontainer = $('<fieldset>').addClass('contactfieldgroup contactcontroller'+col).insertAfter($('#contactsection'+section+' .contactfieldgroup').last());
4434
4435       if (appendcontainer.length && appendcontainer.get(0).nodeName == 'FIELDSET') {
4436         var input, colprop = this.env.coltypes[col],
4437           row = $('<div>').addClass('row'),
4438           cell = $('<div>').addClass('contactfieldcontent data'),
4439           label = $('<div>').addClass('contactfieldlabel label');
4440
4441         if (colprop.subtypes_select)
4442           label.html(colprop.subtypes_select);
4443         else
4444           label.html(colprop.label);
4445
4446         var name_suffix = colprop.limit != 1 ? '[]' : '';
4447         if (colprop.type == 'text' || colprop.type == 'date') {
4448           input = $('<input>')
4449             .addClass('ff_'+col)
4450             .attr({type: 'text', name: '_'+col+name_suffix, size: colprop.size})
4451             .appendTo(cell);
4452
4453           this.init_edit_field(col, input);
4454
4455           if (colprop.type == 'date' && $.datepicker)
4456             input.datepicker();
4457         }
4458         else if (colprop.type == 'composite') {
4459           var childcol, cp, first, templ, cols = [], suffices = [];
4460           // read template for composite field order
4461           if ((templ = this.env[col+'_template'])) {
4462             for (var j=0; j < templ.length; j++) {
4463               cols.push(templ[j][1]);
4464               suffices.push(templ[j][2]);
4465             }
4466           }
4467           else {  // list fields according to appearance in colprop
4468             for (childcol in colprop.childs)
4469               cols.push(childcol);
4470           }
4471
4472           for (var i=0; i < cols.length; i++) {
4473             childcol = cols[i];
4474             cp = colprop.childs[childcol];
4475             input = $('<input>')
4476               .addClass('ff_'+childcol)
4477               .attr({ type: 'text', name: '_'+childcol+name_suffix, size: cp.size })
4478               .appendTo(cell);
4479             cell.append(suffices[i] || " ");
4480             this.init_edit_field(childcol, input);
4481             if (!first) first = input;
4482           }
4483           input = first;  // set focus to the first of this composite fields
4484         }
4485         else if (colprop.type == 'select') {
4486           input = $('<select>')
4487             .addClass('ff_'+col)
4488             .attr('name', '_'+col+name_suffix)
4489             .appendTo(cell);
4490
4491           var options = input.attr('options');
4492           options[options.length] = new Option('---', '');
4493           if (colprop.options)
4494             $.each(colprop.options, function(i, val){ options[options.length] = new Option(val, i); });
4495         }
4496
4497         if (input) {
4498           var delbutton = $('<a href="#del"></a>')
4499             .addClass('contactfieldbutton deletebutton')
4500             .attr({title: this.get_label('delete'), rel: col})
4501             .html(this.env.delbutton)
4502             .click(function(){ ref.delete_edit_field(this); return false })
4503             .appendTo(cell);
4504
4505           row.append(label).append(cell).appendTo(appendcontainer.show());
4506           input.first().focus();
4507
4508           // disable option if limit reached
4509           if (!colprop.count) colprop.count = 0;
4510           if (++colprop.count == colprop.limit && colprop.limit)
4511             $(menu).children('option[value="'+col+'"]').prop('disabled', true);
4512         }
4513       }
4514     }
4515   };
4516
4517   this.delete_edit_field = function(elem)
4518   {
4519     var col = $(elem).attr('rel'),
4520       colprop = this.env.coltypes[col],
4521       fieldset = $(elem).parents('fieldset.contactfieldgroup'),
4522       addmenu = fieldset.parent().find('select.addfieldmenu');
4523
4524     // just clear input but don't hide the last field
4525     if (--colprop.count <= 0 && colprop.visible)
4526       $(elem).parent().children('input').val('').blur();
4527     else {
4528       $(elem).parents('div.row').remove();
4529       // hide entire fieldset if no more rows
4530       if (!fieldset.children('div.row').length)
4531         fieldset.hide();
4532     }
4533
4534     // enable option in add-field selector or insert it if necessary
4535     if (addmenu.length) {
4536       var option = addmenu.children('option[value="'+col+'"]');
4537       if (option.length)
4538         option.prop('disabled', false);
4539       else
4540         option = $('<option>').attr('value', col).html(colprop.label).appendTo(addmenu);
4541       addmenu.show();
4542     }
4543   };
4544
4545   this.upload_contact_photo = function(form)
4546   {
4547     if (form && form.elements._photo.value) {
4548       this.async_upload_form(form, 'upload-photo', function(e) {
4549         rcmail.set_busy(false, null, rcmail.photo_upload_id);
4550       });
4551
4552       // display upload indicator
4553       this.photo_upload_id = this.set_busy(true, 'uploading');
4554     }
4555   };
4556
4557   this.replace_contact_photo = function(id)
4558   {
4559     var img_src = id == '-del-' ? this.env.photo_placeholder :
4560       this.env.comm_path + '&_action=photo&_source=' + this.env.source + '&_cid=' + this.env.cid + '&_photo=' + id;
4561
4562     this.set_photo_actions(id);
4563     $(this.gui_objects.contactphoto).children('img').attr('src', img_src);
4564   };
4565
4566   this.photo_upload_end = function()
4567   {
4568     this.set_busy(false, null, this.photo_upload_id);
4569     delete this.photo_upload_id;
4570   };
4571
4572   this.set_photo_actions = function(id)
4573   {
4574     var n, buttons = this.buttons['upload-photo'];
4575     for (n=0; buttons && n < buttons.length; n++)
4576       $('#'+buttons[n].id).html(this.get_label(id == '-del-' ? 'addphoto' : 'replacephoto'));
4577
4578     $('#ff_photo').val(id);
4579     this.enable_command('upload-photo', this.env.coltypes.photo ? true : false);
4580     this.enable_command('delete-photo', this.env.coltypes.photo && id != '-del-');
4581   };
4582
4583   // load advanced search page
4584   this.advanced_search = function()
4585   {
4586     var add_url = '&_form=1', target = window;
4587
4588     if (this.env.contentframe && window.frames && window.frames[this.env.contentframe]) {
4589       add_url += '&_framed=1';
4590       target = window.frames[this.env.contentframe];
4591       this.contact_list.clear_selection();
4592     }
4593
4594     this.location_href(this.env.comm_path+'&_action=search'+add_url, target, true);
4595
4596     return true;
4597   };
4598
4599   // unselect directory/group
4600   this.unselect_directory = function()
4601   {
4602     this.select_folder('');
4603     this.enable_command('search-delete', false);
4604   };
4605
4606   // callback for creating a new saved search record
4607   this.insert_saved_search = function(name, id)
4608   {
4609     this.reset_add_input();
4610
4611     var key = 'S'+id,
4612       link = $('<a>').attr('href', '#')
4613         .attr('rel', id)
4614         .click(function() { return rcmail.command('listsearch', id, this); })
4615         .html(name),
4616       li = $('<li>').attr({id: 'rcmli' + this.html_identifier(key), 'class': 'contactsearch'})
4617         .append(link),
4618       prop = {name:name, id:id, li:li[0]};
4619
4620     this.add_saved_search_row(prop, li);
4621     this.select_folder('S'+id);
4622     this.enable_command('search-delete', true);
4623     this.env.search_id = id;
4624
4625     this.triggerEvent('abook_search_insert', prop);
4626   };
4627
4628   // add saved search row to the list, with sorting
4629   this.add_saved_search_row = function(prop, li, reloc)
4630   {
4631     var row, sibling, name = prop.name.toUpperCase();
4632
4633     // When renaming groups, we need to remove it from DOM and insert it in the proper place
4634     if (reloc) {
4635       row = li.clone(true);
4636       li.remove();
4637     }
4638     else
4639       row = li;
4640
4641     $('li[class~="contactsearch"]', this.gui_objects.folderlist).each(function(i, elem) {
4642       if (!sibling)
4643         sibling = this.previousSibling;
4644
4645       if (name >= $(this).text().toUpperCase())
4646         sibling = elem;
4647       else
4648         return false;
4649     });
4650
4651     if (sibling)
4652       row.insertAfter(sibling);
4653     else
4654       row.appendTo(this.gui_objects.folderlist);
4655   };
4656
4657   // creates an input for saved search name
4658   this.search_create = function()
4659   {
4660     this.add_input_row('contactsearch');
4661   };
4662
4663   this.search_delete = function()
4664   {
4665     if (this.env.search_request) {
4666       var lock = this.set_busy(true, 'savedsearchdeleting');
4667       this.http_post('search-delete', '_sid='+urlencode(this.env.search_id), lock);
4668     }
4669   };
4670
4671   // callback from server upon search-delete command
4672   this.remove_search_item = function(id)
4673   {
4674     var li, key = 'S'+id;
4675     if ((li = this.get_folder_li(key))) {
4676       this.triggerEvent('search_delete', { id:id, li:li });
4677
4678       li.parentNode.removeChild(li);
4679     }
4680
4681     this.env.search_id = null;
4682     this.env.search_request = null;
4683     this.list_contacts_clear();
4684     this.reset_qsearch();
4685     this.enable_command('search-delete', 'search-create', false);
4686   };
4687
4688   this.listsearch = function(id)
4689   {
4690     var folder, lock = this.set_busy(true, 'searching');
4691
4692     if (this.contact_list) {
4693       this.list_contacts_clear();
4694     }
4695
4696     this.reset_qsearch();
4697     this.select_folder('S'+id);
4698
4699     // reset vars
4700     this.env.current_page = 1;
4701     this.http_request('search', '_sid='+urlencode(id), lock);
4702   };
4703
4704
4705   /*********************************************************/
4706   /*********        user settings methods          *********/
4707   /*********************************************************/
4708
4709   // preferences section select and load options frame
4710   this.section_select = function(list)
4711   {
4712     var id = list.get_single_selection(), add_url = '', target = window;
4713
4714     if (id) {
4715       if (this.env.contentframe && window.frames && window.frames[this.env.contentframe]) {
4716         add_url = '&_framed=1';
4717         target = window.frames[this.env.contentframe];
4718       }
4719       this.location_href(this.env.comm_path+'&_action=edit-prefs&_section='+id+add_url, target, true);
4720     }
4721
4722     return true;
4723   };
4724
4725   this.identity_select = function(list)
4726   {
4727     var id;
4728     if (id = list.get_single_selection())
4729       this.load_identity(id, 'edit-identity');
4730   };
4731
4732   // load identity record
4733   this.load_identity = function(id, action)
4734   {
4735     if (action=='edit-identity' && (!id || id==this.env.iid))
4736       return false;
4737
4738     var add_url = '', target = window;
4739
4740     if (this.env.contentframe && window.frames && window.frames[this.env.contentframe]) {
4741       add_url = '&_framed=1';
4742       target = window.frames[this.env.contentframe];
4743       document.getElementById(this.env.contentframe).style.visibility = 'inherit';
4744     }
4745
4746     if (action && (id || action=='add-identity')) {
4747       this.set_busy(true);
4748       this.location_href(this.env.comm_path+'&_action='+action+'&_iid='+id+add_url, target);
4749     }
4750
4751     return true;
4752   };
4753
4754   this.delete_identity = function(id)
4755   {
4756     // exit if no mailbox specified or if selection is empty
4757     var selection = this.identity_list.get_selection();
4758     if (!(selection.length || this.env.iid))
4759       return;
4760
4761     if (!id)
4762       id = this.env.iid ? this.env.iid : selection[0];
4763
4764     // append token to request
4765     this.goto_url('delete-identity', '_iid='+id+'&_token='+this.env.request_token, true);
4766
4767     return true;
4768   };
4769
4770
4771   /*********************************************************/
4772   /*********        folder manager methods         *********/
4773   /*********************************************************/
4774
4775   this.init_subscription_list = function()
4776   {
4777     var p = this;
4778     this.subscription_list = new rcube_list_widget(this.gui_objects.subscriptionlist,
4779       {multiselect:false, draggable:true, keyboard:false, toggleselect:true});
4780     this.subscription_list.addEventListener('select', function(o){ p.subscription_select(o); });
4781     this.subscription_list.addEventListener('dragstart', function(o){ p.drag_active = true; });
4782     this.subscription_list.addEventListener('dragend', function(o){ p.subscription_move_folder(o); });
4783     this.subscription_list.row_init = function (row) {
4784       row.obj.onmouseover = function() { p.focus_subscription(row.id); };
4785       row.obj.onmouseout = function() { p.unfocus_subscription(row.id); };
4786     };
4787     this.subscription_list.init();
4788     $('#mailboxroot')
4789       .mouseover(function(){ p.focus_subscription(this.id); })
4790       .mouseout(function(){ p.unfocus_subscription(this.id); })
4791   };
4792
4793   this.focus_subscription = function(id)
4794   {
4795     var row, folder,
4796       delim = RegExp.escape(this.env.delimiter),
4797       reg = RegExp('['+delim+']?[^'+delim+']+$');
4798
4799     if (this.drag_active && this.env.mailbox && (row = document.getElementById(id)))
4800       if (this.env.subscriptionrows[id] &&
4801           (folder = this.env.subscriptionrows[id][0]) !== null
4802       ) {
4803         if (this.check_droptarget(folder) &&
4804             !this.env.subscriptionrows[this.get_folder_row_id(this.env.mailbox)][2] &&
4805             (folder != this.env.mailbox.replace(reg, '')) &&
4806             (!folder.match(new RegExp('^'+RegExp.escape(this.env.mailbox+this.env.delimiter))))
4807         ) {
4808           this.env.dstfolder = folder;
4809           $(row).addClass('droptarget');
4810         }
4811       }
4812   };
4813
4814   this.unfocus_subscription = function(id)
4815   {
4816     var row = $('#'+id);
4817
4818     this.env.dstfolder = null;
4819     if (this.env.subscriptionrows[id] && row[0])
4820       row.removeClass('droptarget');
4821     else
4822       $(this.subscription_list.frame).removeClass('droptarget');
4823   };
4824
4825   this.subscription_select = function(list)
4826   {
4827     var id, folder;
4828
4829     if (list && (id = list.get_single_selection()) &&
4830         (folder = this.env.subscriptionrows['rcmrow'+id])
4831     ) {
4832       this.env.mailbox = folder[0];
4833       this.show_folder(folder[0]);
4834       this.enable_command('delete-folder', !folder[2]);
4835     }
4836     else {
4837       this.env.mailbox = null;
4838       this.show_contentframe(false);
4839       this.enable_command('delete-folder', 'purge', false);
4840     }
4841   };
4842
4843   this.subscription_move_folder = function(list)
4844   {
4845     var delim = RegExp.escape(this.env.delimiter),
4846       reg = RegExp('['+delim+']?[^'+delim+']+$');
4847
4848     if (this.env.mailbox && this.env.dstfolder !== null && (this.env.dstfolder != this.env.mailbox) &&
4849         (this.env.dstfolder != this.env.mailbox.replace(reg, ''))
4850     ) {
4851       reg = new RegExp('[^'+delim+']*['+delim+']', 'g');
4852       var basename = this.env.mailbox.replace(reg, ''),
4853         newname = this.env.dstfolder === '' ? basename : this.env.dstfolder+this.env.delimiter+basename;
4854
4855       if (newname != this.env.mailbox) {
4856         this.http_post('rename-folder', '_folder_oldname='+urlencode(this.env.mailbox)+'&_folder_newname='+urlencode(newname), this.set_busy(true, 'foldermoving'));
4857         this.subscription_list.draglayer.hide();
4858       }
4859     }
4860     this.drag_active = false;
4861     this.unfocus_subscription(this.get_folder_row_id(this.env.dstfolder));
4862   };
4863
4864   // tell server to create and subscribe a new mailbox
4865   this.create_folder = function()
4866   {
4867     this.show_folder('', this.env.mailbox);
4868   };
4869
4870   // delete a specific mailbox with all its messages
4871   this.delete_folder = function(name)
4872   {
4873     var id = this.get_folder_row_id(name ? name : this.env.mailbox),
4874       folder = this.env.subscriptionrows[id][0];
4875
4876     if (folder && confirm(this.get_label('deletefolderconfirm'))) {
4877       var lock = this.set_busy(true, 'folderdeleting');
4878       this.http_post('delete-folder', '_mbox='+urlencode(folder), lock);
4879     }
4880   };
4881
4882   // Add folder row to the table and initialize it
4883   this.add_folder_row = function (name, display_name, is_protected, subscribed, skip_init, class_name)
4884   {
4885     if (!this.gui_objects.subscriptionlist)
4886       return false;
4887
4888     var row, n, i, tmp, folders, rowid, list = [], slist = [],
4889       tbody = this.gui_objects.subscriptionlist.tBodies[0],
4890       refrow = $('tr', tbody).get(1),
4891       id = 'rcmrow'+((new Date).getTime());
4892
4893     if (!refrow) {
4894       // Refresh page if we don't have a table row to clone
4895       this.goto_url('folders');
4896       return false;
4897     }
4898
4899     // clone a table row if there are existing rows
4900     row = $(refrow).clone(true);
4901
4902     // set ID, reset css class
4903     row.attr('id', id);
4904     row.attr('class', class_name);
4905
4906     // set folder name
4907     row.find('td:first').html(display_name);
4908
4909     // update subscription checkbox
4910     $('input[name="_subscribed[]"]', row).val(name)
4911       .prop({checked: subscribed ? true : false, disabled: is_protected ? true : false});
4912
4913     // add to folder/row-ID map
4914     this.env.subscriptionrows[id] = [name, display_name, 0];
4915
4916     // sort folders, to find a place where to insert the row
4917     folders = [];
4918     $.each(this.env.subscriptionrows, function(k,v){ folders.push(v) });
4919     folders.sort(function(a,b){ return a[0] < b[0] ? -1 : (a[0] > b[0] ? 1 : 0) });
4920
4921     for (n in folders) {
4922       // protected folder
4923       if (folders[n][2]) {
4924         slist.push(folders[n][0]);
4925         tmp = folders[n][0]+this.env.delimiter;
4926       }
4927       // protected folder's child
4928       else if (tmp && folders[n][0].indexOf(tmp) == 0)
4929         slist.push(folders[n][0]);
4930       // other
4931       else {
4932         list.push(folders[n][0]);
4933         tmp = null;
4934       }
4935     }
4936
4937     // check if subfolder of a protected folder
4938     for (n=0; n<slist.length; n++) {
4939       if (name.indexOf(slist[n]+this.env.delimiter) == 0)
4940         rowid = this.get_folder_row_id(slist[n]);
4941     }
4942
4943     // find folder position after sorting
4944     for (n=0; !rowid && n<list.length; n++) {
4945       if (n && list[n] == name)
4946         rowid = this.get_folder_row_id(list[n-1]);
4947     }
4948
4949     // add row to the table
4950     if (rowid)
4951       $('#'+rowid).after(row);
4952     else
4953       row.appendTo(tbody);
4954
4955     // update list widget
4956     this.subscription_list.clear_selection();
4957     if (!skip_init)
4958       this.init_subscription_list();
4959
4960     row = row.get(0);
4961     if (row.scrollIntoView)
4962       row.scrollIntoView();
4963
4964     return row;
4965   };
4966
4967   // replace an existing table row with a new folder line (with subfolders)
4968   this.replace_folder_row = function(oldfolder, newfolder, display_name, is_protected, class_name)
4969   {
4970     if (!this.gui_objects.subscriptionlist)
4971       return false;
4972
4973     var i, n, len, name, dispname, oldrow, tmprow, row, level,
4974       tbody = this.gui_objects.subscriptionlist.tBodies[0],
4975       folders = this.env.subscriptionrows,
4976       id = this.get_folder_row_id(oldfolder),
4977       regex = new RegExp('^'+RegExp.escape(oldfolder)),
4978       subscribed = $('input[name="_subscribed[]"]', $('#'+id)).prop('checked'),
4979       // find subfolders of renamed folder
4980       list = this.get_subfolders(oldfolder);
4981
4982     // replace an existing table row
4983     this._remove_folder_row(id);
4984     row = $(this.add_folder_row(newfolder, display_name, is_protected, subscribed, true, class_name));
4985
4986     // detect tree depth change
4987     if (len = list.length) {
4988       level = (oldfolder.split(this.env.delimiter)).length - (newfolder.split(this.env.delimiter)).length;
4989     }
4990
4991     // move subfolders to the new branch
4992     for (n=0; n<len; n++) {
4993       id = list[n];
4994       name = this.env.subscriptionrows[id][0];
4995       dispname = this.env.subscriptionrows[id][1];
4996       oldrow = $('#'+id);
4997       tmprow = oldrow.clone(true);
4998       oldrow.remove();
4999       row.after(tmprow);
5000       row = tmprow;
5001       // update folder index
5002       name = name.replace(regex, newfolder);
5003       $('input[name="_subscribed[]"]', row).val(name);
5004       this.env.subscriptionrows[id][0] = name;
5005       // update the name if level is changed
5006       if (level != 0) {
5007         if (level > 0) {
5008           for (i=level; i>0; i--)
5009             dispname = dispname.replace(/^&nbsp;&nbsp;&nbsp;&nbsp;/, '');
5010         }
5011         else {
5012           for (i=level; i<0; i++)
5013             dispname = '&nbsp;&nbsp;&nbsp;&nbsp;' + dispname;
5014         }
5015         row.find('td:first').html(dispname);
5016         this.env.subscriptionrows[id][1] = dispname;
5017       }
5018     }
5019
5020     // update list widget
5021     this.init_subscription_list();
5022   };
5023
5024   // remove the table row of a specific mailbox from the table
5025   this.remove_folder_row = function(folder, subs)
5026   {
5027     var n, len, list = [], id = this.get_folder_row_id(folder);
5028
5029     // get subfolders if any
5030     if (subs)
5031       list = this.get_subfolders(folder);
5032
5033     // remove old row
5034     this._remove_folder_row(id);
5035
5036     // remove subfolders
5037     for (n=0, len=list.length; n<len; n++)
5038       this._remove_folder_row(list[n]);
5039   };
5040
5041   this._remove_folder_row = function(id)
5042   {
5043     this.subscription_list.remove_row(id.replace(/^rcmrow/, ''));
5044     $('#'+id).remove();
5045     delete this.env.subscriptionrows[id];
5046   }
5047
5048   this.get_subfolders = function(folder)
5049   {
5050     var name, list = [],
5051       regex = new RegExp('^'+RegExp.escape(folder)+RegExp.escape(this.env.delimiter)),
5052       row = $('#'+this.get_folder_row_id(folder)).get(0);
5053
5054     while (row = row.nextSibling) {
5055       if (row.id) {
5056         name = this.env.subscriptionrows[row.id][0];
5057         if (regex.test(name)) {
5058           list.push(row.id);
5059         }
5060         else
5061           break;
5062       }
5063     }
5064
5065     return list;
5066   }
5067
5068   this.subscribe = function(folder)
5069   {
5070     if (folder) {
5071       var lock = this.display_message(this.get_label('foldersubscribing'), 'loading');
5072       this.http_post('subscribe', '_mbox='+urlencode(folder), lock);
5073     }
5074   };
5075
5076   this.unsubscribe = function(folder)
5077   {
5078     if (folder) {
5079       var lock = this.display_message(this.get_label('folderunsubscribing'), 'loading');
5080       this.http_post('unsubscribe', '_mbox='+urlencode(folder), lock);
5081     }
5082   };
5083
5084   // helper method to find a specific mailbox row ID
5085   this.get_folder_row_id = function(folder)
5086   {
5087     var id, folders = this.env.subscriptionrows;
5088     for (id in folders)
5089       if (folders[id] && folders[id][0] == folder)
5090         break;
5091
5092     return id;
5093   };
5094
5095   // when user select a folder in manager
5096   this.show_folder = function(folder, path, force)
5097   {
5098     var target = window,
5099       url = '&_action=edit-folder&_mbox='+urlencode(folder);
5100
5101     if (path)
5102       url += '&_path='+urlencode(path);
5103
5104     if (this.env.contentframe && window.frames && window.frames[this.env.contentframe]) {
5105       target = window.frames[this.env.contentframe];
5106       url += '&_framed=1';
5107     }
5108
5109     if (String(target.location.href).indexOf(url) >= 0 && !force) {
5110       this.show_contentframe(true);
5111     }
5112     else {
5113       this.location_href(this.env.comm_path+url, target, true);
5114     }
5115   };
5116
5117   // disables subscription checkbox (for protected folder)
5118   this.disable_subscription = function(folder)
5119   {
5120     var id = this.get_folder_row_id(folder);
5121     if (id)
5122       $('input[name="_subscribed[]"]', $('#'+id)).prop('disabled', true);
5123   };
5124
5125   this.folder_size = function(folder)
5126   {
5127     var lock = this.set_busy(true, 'loading');
5128     this.http_post('folder-size', '_mbox='+urlencode(folder), lock);
5129   };
5130
5131   this.folder_size_update = function(size)
5132   {
5133     $('#folder-size').replaceWith(size);
5134   };
5135
5136
5137   /*********************************************************/
5138   /*********           GUI functionality           *********/
5139   /*********************************************************/
5140
5141   var init_button = function(cmd, prop)
5142   {
5143     var elm = document.getElementById(prop.id);
5144     if (!elm)
5145       return;
5146
5147     var preload = false;
5148     if (prop.type == 'image') {
5149       elm = elm.parentNode;
5150       preload = true;
5151     }
5152
5153     elm._command = cmd;
5154     elm._id = prop.id;
5155     if (prop.sel) {
5156       elm.onmousedown = function(e){ return rcmail.button_sel(this._command, this._id); };
5157       elm.onmouseup = function(e){ return rcmail.button_out(this._command, this._id); };
5158       if (preload)
5159         new Image().src = prop.sel;
5160     }
5161     if (prop.over) {
5162       elm.onmouseover = function(e){ return rcmail.button_over(this._command, this._id); };
5163       elm.onmouseout = function(e){ return rcmail.button_out(this._command, this._id); };
5164       if (preload)
5165         new Image().src = prop.over;
5166     }
5167   };
5168
5169   // enable/disable buttons for page shifting
5170   this.set_page_buttons = function()
5171   {
5172     this.enable_command('nextpage', 'lastpage', (this.env.pagecount > this.env.current_page));
5173     this.enable_command('previouspage', 'firstpage', (this.env.current_page > 1));
5174   };
5175
5176   // set event handlers on registered buttons
5177   this.init_buttons = function()
5178   {
5179     for (var cmd in this.buttons) {
5180       if (typeof cmd !== 'string')
5181         continue;
5182
5183       for (var i=0; i< this.buttons[cmd].length; i++) {
5184         init_button(cmd, this.buttons[cmd][i]);
5185       }
5186     }
5187
5188     // set active task button
5189     this.set_button(this.task, 'sel');
5190   };
5191
5192   // set button to a specific state
5193   this.set_button = function(command, state)
5194   {
5195     var n, button, obj, a_buttons = this.buttons[command],
5196       len = a_buttons ? a_buttons.length : 0;
5197
5198     for (n=0; n<len; n++) {
5199       button = a_buttons[n];
5200       obj = document.getElementById(button.id);
5201
5202       // get default/passive setting of the button
5203       if (obj && button.type=='image' && !button.status) {
5204         button.pas = obj._original_src ? obj._original_src : obj.src;
5205         // respect PNG fix on IE browsers
5206         if (obj.runtimeStyle && obj.runtimeStyle.filter && obj.runtimeStyle.filter.match(/src=['"]([^'"]+)['"]/))
5207           button.pas = RegExp.$1;
5208       }
5209       else if (obj && !button.status)
5210         button.pas = String(obj.className);
5211
5212       // set image according to button state
5213       if (obj && button.type=='image' && button[state]) {
5214         button.status = state;
5215         obj.src = button[state];
5216       }
5217       // set class name according to button state
5218       else if (obj && button[state] !== undefined) {
5219         button.status = state;
5220         obj.className = button[state];
5221       }
5222       // disable/enable input buttons
5223       if (obj && button.type=='input') {
5224         button.status = state;
5225         obj.disabled = !state;
5226       }
5227     }
5228   };
5229
5230   // display a specific alttext
5231   this.set_alttext = function(command, label)
5232   {
5233     var n, button, obj, link, a_buttons = this.buttons[command],
5234       len = a_buttons ? a_buttons.length : 0;
5235
5236     for (n=0; n<len; n++) {
5237       button = a_buttons[n];
5238       obj = document.getElementById(button.id);
5239
5240       if (button.type == 'image' && obj) {
5241         obj.setAttribute('alt', this.get_label(label));
5242         if ((link = obj.parentNode) && link.tagName.toLowerCase() == 'a')
5243           link.setAttribute('title', this.get_label(label));
5244       }
5245       else if (obj)
5246         obj.setAttribute('title', this.get_label(label));
5247     }
5248   };
5249
5250   // mouse over button
5251   this.button_over = function(command, id)
5252   {
5253     var n, button, obj, a_buttons = this.buttons[command],
5254       len = a_buttons ? a_buttons.length : 0;
5255
5256     for (n=0; n<len; n++) {
5257       button = a_buttons[n];
5258       if (button.id == id && button.status == 'act') {
5259         obj = document.getElementById(button.id);
5260         if (obj && button.over) {
5261           if (button.type == 'image')
5262             obj.src = button.over;
5263           else
5264             obj.className = button.over;
5265         }
5266       }
5267     }
5268   };
5269
5270   // mouse down on button
5271   this.button_sel = function(command, id)
5272   {
5273     var n, button, obj, a_buttons = this.buttons[command],
5274       len = a_buttons ? a_buttons.length : 0;
5275
5276     for (n=0; n<len; n++) {
5277       button = a_buttons[n];
5278       if (button.id == id && button.status == 'act') {
5279         obj = document.getElementById(button.id);
5280         if (obj && button.sel) {
5281           if (button.type == 'image')
5282             obj.src = button.sel;
5283           else
5284             obj.className = button.sel;
5285         }
5286         this.buttons_sel[id] = command;
5287       }
5288     }
5289   };
5290
5291   // mouse out of button
5292   this.button_out = function(command, id)
5293   {
5294     var n, button, obj, a_buttons = this.buttons[command],
5295       len = a_buttons ? a_buttons.length : 0;
5296
5297     for (n=0; n<len; n++) {
5298       button = a_buttons[n];
5299       if (button.id == id && button.status == 'act') {
5300         obj = document.getElementById(button.id);
5301         if (obj && button.act) {
5302           if (button.type == 'image')
5303             obj.src = button.act;
5304           else
5305             obj.className = button.act;
5306         }
5307       }
5308     }
5309   };
5310
5311   this.focus_textfield = function(elem)
5312   {
5313     elem._hasfocus = true;
5314     var $elem = $(elem);
5315     if ($elem.hasClass('placeholder') || $elem.val() == elem._placeholder)
5316       $elem.val('').removeClass('placeholder').attr('spellcheck', true);
5317   };
5318
5319   this.blur_textfield = function(elem)
5320   {
5321     elem._hasfocus = false;
5322     var $elem = $(elem);
5323     if (elem._placeholder && (!$elem.val() || $elem.val() == elem._placeholder))
5324       $elem.addClass('placeholder').attr('spellcheck', false).val(elem._placeholder);
5325   };
5326
5327   // write to the document/window title
5328   this.set_pagetitle = function(title)
5329   {
5330     if (title && document.title)
5331       document.title = title;
5332   };
5333
5334   // display a system message, list of types in common.css (below #message definition)
5335   this.display_message = function(msg, type, timeout)
5336   {
5337     // pass command to parent window
5338     if (this.is_framed())
5339       return parent.rcmail.display_message(msg, type, timeout);
5340
5341     if (!this.gui_objects.message) {
5342       // save message in order to display after page loaded
5343       if (type != 'loading')
5344         this.pending_message = [msg, type, timeout];
5345       return false;
5346     }
5347
5348     type = type ? type : 'notice';
5349
5350     var ref = this,
5351       key = this.html_identifier(msg),
5352       date = new Date(),
5353       id = type + date.getTime();
5354
5355     if (!timeout)
5356       timeout = this.message_time * (type == 'error' || type == 'warning' ? 2 : 1);
5357
5358     if (type == 'loading') {
5359       key = 'loading';
5360       timeout = this.env.request_timeout * 1000;
5361       if (!msg)
5362         msg = this.get_label('loading');
5363     }
5364
5365     // The same message is already displayed
5366     if (this.messages[key]) {
5367       // replace label
5368       if (this.messages[key].obj)
5369         this.messages[key].obj.html(msg);
5370       // store label in stack
5371       if (type == 'loading') {
5372         this.messages[key].labels.push({'id': id, 'msg': msg});
5373       }
5374       // add element and set timeout
5375       this.messages[key].elements.push(id);
5376       window.setTimeout(function() { ref.hide_message(id, type == 'loading'); }, timeout);
5377       return id;
5378     }
5379
5380     // create DOM object and display it
5381     var obj = $('<div>').addClass(type).html(msg).data('key', key),
5382       cont = $(this.gui_objects.message).append(obj).show();
5383
5384     this.messages[key] = {'obj': obj, 'elements': [id]};
5385
5386     if (type == 'loading') {
5387       this.messages[key].labels = [{'id': id, 'msg': msg}];
5388     }
5389     else {
5390       obj.click(function() { return ref.hide_message(obj); });
5391     }
5392
5393     if (timeout > 0)
5394       window.setTimeout(function() { ref.hide_message(id, type == 'loading'); }, timeout);
5395     return id;
5396   };
5397
5398   // make a message to disapear
5399   this.hide_message = function(obj, fade)
5400   {
5401     // pass command to parent window
5402     if (this.is_framed())
5403       return parent.rcmail.hide_message(obj, fade);
5404
5405     var k, n, i, msg, m = this.messages;
5406
5407     // Hide message by object, don't use for 'loading'!
5408     if (typeof obj === 'object') {
5409       $(obj)[fade?'fadeOut':'hide']();
5410       msg = $(obj).data('key');
5411       if (this.messages[msg])
5412         delete this.messages[msg];
5413     }
5414     // Hide message by id
5415     else {
5416       for (k in m) {
5417         for (n in m[k].elements) {
5418           if (m[k] && m[k].elements[n] == obj) {
5419             m[k].elements.splice(n, 1);
5420             // hide DOM element if last instance is removed
5421             if (!m[k].elements.length) {
5422               m[k].obj[fade?'fadeOut':'hide']();
5423               delete m[k];
5424             }
5425             // set pending action label for 'loading' message
5426             else if (k == 'loading') {
5427               for (i in m[k].labels) {
5428                 if (m[k].labels[i].id == obj) {
5429                   delete m[k].labels[i];
5430                 }
5431                 else {
5432                   msg = m[k].labels[i].msg;
5433                 }
5434                 m[k].obj.html(msg);
5435               }
5436             }
5437           }
5438         }
5439       }
5440     }
5441   };
5442
5443   // mark a mailbox as selected and set environment variable
5444   this.select_folder = function(name, prefix, encode)
5445   {
5446     if (this.gui_objects.folderlist) {
5447       var current_li, target_li;
5448
5449       if ((current_li = $('li.selected', this.gui_objects.folderlist))) {
5450         current_li.removeClass('selected').addClass('unfocused');
5451       }
5452       if ((target_li = this.get_folder_li(name, prefix, encode))) {
5453         $(target_li).removeClass('unfocused').addClass('selected');
5454       }
5455
5456       // trigger event hook
5457       this.triggerEvent('selectfolder', { folder:name, prefix:prefix });
5458     }
5459   };
5460
5461   // helper method to find a folder list item
5462   this.get_folder_li = function(name, prefix, encode)
5463   {
5464     if (!prefix)
5465       prefix = 'rcmli';
5466
5467     if (this.gui_objects.folderlist) {
5468       name = this.html_identifier(name, encode);
5469       return document.getElementById(prefix+name);
5470     }
5471
5472     return null;
5473   };
5474
5475   // for reordering column array (Konqueror workaround)
5476   // and for setting some message list global variables
5477   this.set_message_coltypes = function(coltypes, repl)
5478   {
5479     var list = this.message_list,
5480       thead = list ? list.list.tHead : null,
5481       cell, col, n, len, th, tr;
5482
5483     this.env.coltypes = coltypes;
5484
5485     // replace old column headers
5486     if (thead) {
5487       if (repl) {
5488         th = document.createElement('thead');
5489         tr = document.createElement('tr');
5490
5491         for (c=0, len=repl.length; c < len; c++) {
5492           cell = document.createElement('td');
5493           cell.innerHTML = repl[c].html;
5494           if (repl[c].id) cell.id = repl[c].id;
5495           if (repl[c].className) cell.className = repl[c].className;
5496           tr.appendChild(cell);
5497         }
5498         th.appendChild(tr);
5499         thead.parentNode.replaceChild(th, thead);
5500         thead = th;
5501       }
5502
5503       for (n=0, len=this.env.coltypes.length; n<len; n++) {
5504         col = this.env.coltypes[n];
5505         if ((cell = thead.rows[0].cells[n]) && (col=='from' || col=='to')) {
5506           cell.id = 'rcm'+col;
5507           // if we have links for sorting, it's a bit more complicated...
5508           if (cell.firstChild && cell.firstChild.tagName.toLowerCase()=='a') {
5509             cell = cell.firstChild;
5510             cell.onclick = function(){ return rcmail.command('sort', this.__col, this); };
5511             cell.__col = col;
5512           }
5513           cell.innerHTML = this.get_label(col);
5514         }
5515       }
5516     }
5517
5518     this.env.subject_col = null;
5519     this.env.flagged_col = null;
5520     this.env.status_col = null;
5521
5522     if ((n = $.inArray('subject', this.env.coltypes)) >= 0) {
5523       this.env.subject_col = n;
5524       if (list)
5525         list.subject_col = n;
5526     }
5527     if ((n = $.inArray('flag', this.env.coltypes)) >= 0)
5528       this.env.flagged_col = n;
5529     if ((n = $.inArray('status', this.env.coltypes)) >= 0)
5530       this.env.status_col = n;
5531
5532     if (list)
5533       list.init_header();
5534   };
5535
5536   // replace content of row count display
5537   this.set_rowcount = function(text, mbox)
5538   {
5539     // #1487752
5540     if (mbox && mbox != this.env.mailbox)
5541       return false;
5542
5543     $(this.gui_objects.countdisplay).html(text);
5544
5545     // update page navigation buttons
5546     this.set_page_buttons();
5547   };
5548
5549   // replace content of mailboxname display
5550   this.set_mailboxname = function(content)
5551   {
5552     if (this.gui_objects.mailboxname && content)
5553       this.gui_objects.mailboxname.innerHTML = content;
5554   };
5555
5556   // replace content of quota display
5557   this.set_quota = function(content)
5558   {
5559     if (content && this.gui_objects.quotadisplay) {
5560       if (typeof content === 'object' && content.type == 'image')
5561         this.percent_indicator(this.gui_objects.quotadisplay, content);
5562       else
5563         $(this.gui_objects.quotadisplay).html(content);
5564     }
5565   };
5566
5567   // update the mailboxlist
5568   this.set_unread_count = function(mbox, count, set_title)
5569   {
5570     if (!this.gui_objects.mailboxlist)
5571       return false;
5572
5573     this.env.unread_counts[mbox] = count;
5574     this.set_unread_count_display(mbox, set_title);
5575   };
5576
5577   // update the mailbox count display
5578   this.set_unread_count_display = function(mbox, set_title)
5579   {
5580     var reg, link, text_obj, item, mycount, childcount, div;
5581
5582     if (item = this.get_folder_li(mbox, '', true)) {
5583       mycount = this.env.unread_counts[mbox] ? this.env.unread_counts[mbox] : 0;
5584       link = $(item).children('a').eq(0);
5585       text_obj = link.children('span.unreadcount');
5586       if (!text_obj.length && mycount)
5587         text_obj = $('<span>').addClass('unreadcount').appendTo(link);
5588       reg = /\s+\([0-9]+\)$/i;
5589
5590       childcount = 0;
5591       if ((div = item.getElementsByTagName('div')[0]) &&
5592           div.className.match(/collapsed/)) {
5593         // add children's counters
5594         for (var k in this.env.unread_counts)
5595           if (k.indexOf(mbox + this.env.delimiter) == 0)
5596             childcount += this.env.unread_counts[k];
5597       }
5598
5599       if (mycount && text_obj.length)
5600         text_obj.html(' ('+mycount+')');
5601       else if (text_obj.length)
5602         text_obj.remove();
5603
5604       // set parent's display
5605       reg = new RegExp(RegExp.escape(this.env.delimiter) + '[^' + RegExp.escape(this.env.delimiter) + ']+$');
5606       if (mbox.match(reg))
5607         this.set_unread_count_display(mbox.replace(reg, ''), false);
5608
5609       // set the right classes
5610       if ((mycount+childcount)>0)
5611         $(item).addClass('unread');
5612       else
5613         $(item).removeClass('unread');
5614     }
5615
5616     // set unread count to window title
5617     reg = /^\([0-9]+\)\s+/i;
5618     if (set_title && document.title) {
5619       var new_title = '',
5620         doc_title = String(document.title);
5621
5622       if (mycount && doc_title.match(reg))
5623         new_title = doc_title.replace(reg, '('+mycount+') ');
5624       else if (mycount)
5625         new_title = '('+mycount+') '+doc_title;
5626       else
5627         new_title = doc_title.replace(reg, '');
5628
5629       this.set_pagetitle(new_title);
5630     }
5631   };
5632
5633   this.toggle_prefer_html = function(checkbox)
5634   {
5635     $('#rcmfd_show_images').prop('disabled', !checkbox.checked).val(0);
5636   };
5637
5638   this.toggle_preview_pane = function(checkbox)
5639   {
5640     $('#rcmfd_preview_pane_mark_read').prop('disabled', !checkbox.checked);
5641   };
5642
5643   // display fetched raw headers
5644   this.set_headers = function(content)
5645   {
5646     if (this.gui_objects.all_headers_row && this.gui_objects.all_headers_box && content)
5647       $(this.gui_objects.all_headers_box).html(content).show();
5648   };
5649
5650   // display all-headers row and fetch raw message headers
5651   this.load_headers = function(elem)
5652   {
5653     if (!this.gui_objects.all_headers_row || !this.gui_objects.all_headers_box || !this.env.uid)
5654       return;
5655
5656     $(elem).removeClass('show-headers').addClass('hide-headers');
5657     $(this.gui_objects.all_headers_row).show();
5658     elem.onclick = function() { rcmail.hide_headers(elem); };
5659
5660     // fetch headers only once
5661     if (!this.gui_objects.all_headers_box.innerHTML) {
5662       var lock = this.display_message(this.get_label('loading'), 'loading');
5663       this.http_post('headers', '_uid='+this.env.uid, lock);
5664     }
5665   };
5666
5667   // hide all-headers row
5668   this.hide_headers = function(elem)
5669   {
5670     if (!this.gui_objects.all_headers_row || !this.gui_objects.all_headers_box)
5671       return;
5672
5673     $(elem).removeClass('hide-headers').addClass('show-headers');
5674     $(this.gui_objects.all_headers_row).hide();
5675     elem.onclick = function() { rcmail.load_headers(elem); };
5676   };
5677
5678   // percent (quota) indicator
5679   this.percent_indicator = function(obj, data)
5680   {
5681     if (!data || !obj)
5682       return false;
5683
5684     var limit_high = 80,
5685       limit_mid  = 55,
5686       width = data.width ? data.width : this.env.indicator_width ? this.env.indicator_width : 100,
5687       height = data.height ? data.height : this.env.indicator_height ? this.env.indicator_height : 14,
5688       quota = data.percent ? Math.abs(parseInt(data.percent)) : 0,
5689       quota_width = parseInt(quota / 100 * width),
5690       pos = $(obj).position();
5691
5692     // workarounds for Opera and Webkit bugs
5693     pos.top = Math.max(0, pos.top);
5694     pos.left = Math.max(0, pos.left);
5695
5696     this.env.indicator_width = width;
5697     this.env.indicator_height = height;
5698
5699     // overlimit
5700     if (quota_width > width) {
5701       quota_width = width;
5702       quota = 100; 
5703     }
5704
5705     if (data.title)
5706       data.title = this.get_label('quota') + ': ' +  data.title;
5707
5708     // main div
5709     var main = $('<div>');
5710     main.css({position: 'absolute', top: pos.top, left: pos.left,
5711             width: width + 'px', height: height + 'px', zIndex: 100, lineHeight: height + 'px'})
5712           .attr('title', data.title).addClass('quota_text').html(quota + '%');
5713     // used bar
5714     var bar1 = $('<div>');
5715     bar1.css({position: 'absolute', top: pos.top + 1, left: pos.left + 1,
5716             width: quota_width + 'px', height: height + 'px', zIndex: 99});
5717     // background
5718     var bar2 = $('<div>');
5719     bar2.css({position: 'absolute', top: pos.top + 1, left: pos.left + 1,
5720             width: width + 'px', height: height + 'px', zIndex: 98})
5721           .addClass('quota_bg');
5722
5723     if (quota >= limit_high) {
5724       main.addClass(' quota_text_high');
5725       bar1.addClass('quota_high');
5726     }
5727     else if(quota >= limit_mid) {
5728       main.addClass(' quota_text_mid');
5729       bar1.addClass('quota_mid');
5730     }
5731     else {
5732       main.addClass(' quota_text_low');
5733       bar1.addClass('quota_low');
5734     }
5735
5736     // replace quota image
5737     $(obj).html('').append(bar1).append(bar2).append(main);
5738     // update #quotaimg title
5739     $('#quotaimg').attr('title', data.title);
5740   };
5741
5742   /********************************************************/
5743   /*********  html to text conversion functions   *********/
5744   /********************************************************/
5745
5746   this.html2plain = function(htmlText, id)
5747   {
5748     var rcmail = this,
5749       url = '?_task=utils&_action=html2text',
5750       lock = this.set_busy(true, 'converting');
5751
5752     this.log('HTTP POST: ' + url);
5753
5754     $.ajax({ type: 'POST', url: url, data: htmlText, contentType: 'application/octet-stream',
5755       error: function(o, status, err) { rcmail.http_error(o, status, err, lock); },
5756       success: function(data) { rcmail.set_busy(false, null, lock); $('#'+id).val(data); rcmail.log(data); }
5757     });
5758   };
5759
5760   this.plain2html = function(plain, id)
5761   {
5762     var lock = this.set_busy(true, 'converting');
5763
5764     plain = plain.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
5765     $('#'+id).val(plain ? '<pre>'+plain+'</pre>' : '');
5766
5767     this.set_busy(false, null, lock);
5768   };
5769
5770
5771   /********************************************************/
5772   /*********        remote request methods        *********/
5773   /********************************************************/
5774
5775   // compose a valid url with the given parameters
5776   this.url = function(action, query)
5777   {
5778     var querystring = typeof query === 'string' ? '&' + query : '';
5779
5780     if (typeof action !== 'string')
5781       query = action;
5782     else if (!query || typeof query !== 'object')
5783       query = {};
5784
5785     if (action)
5786       query._action = action;
5787     else
5788       query._action = this.env.action;
5789
5790     var base = this.env.comm_path;
5791
5792     // overwrite task name
5793     if (query._action.match(/([a-z]+)\/([a-z0-9-_.]+)/)) {
5794       query._action = RegExp.$2;
5795       base = base.replace(/\_task=[a-z]+/, '_task='+RegExp.$1);
5796     }
5797
5798     // remove undefined values
5799     var param = {};
5800     for (var k in query) {
5801       if (query[k] !== undefined && query[k] !== null)
5802         param[k] = query[k];
5803     }
5804
5805     return base + '&' + $.param(param) + querystring;
5806   };
5807
5808   this.redirect = function(url, lock)
5809   {
5810     if (lock || lock === null)
5811       this.set_busy(true);
5812
5813     if (this.is_framed())
5814       parent.rcmail.redirect(url, lock);
5815     else
5816       this.location_href(url, window);
5817   };
5818
5819   this.goto_url = function(action, query, lock)
5820   {
5821     this.redirect(this.url(action, query));
5822   };
5823
5824   this.location_href = function(url, target, frame)
5825   {
5826     if (frame)
5827       this.lock_frame();
5828
5829     // simulate real link click to force IE to send referer header
5830     if (bw.ie && target == window)
5831       $('<a>').attr('href', url).appendTo(document.body).get(0).click();
5832     else
5833       target.location.href = url;
5834   };
5835
5836   // send a http request to the server
5837   this.http_request = function(action, query, lock)
5838   {
5839     var url = this.url(action, query);
5840
5841     // trigger plugin hook
5842     var result = this.triggerEvent('request'+action, query);
5843
5844     if (result !== undefined) {
5845       // abort if one the handlers returned false
5846       if (result === false)
5847         return false;
5848       else
5849         query = result;
5850     }
5851
5852     url += '&_remote=1';
5853
5854     // send request
5855     this.log('HTTP GET: ' + url);
5856
5857     return $.ajax({
5858       type: 'GET', url: url, data: { _unlock:(lock?lock:0) }, dataType: 'json',
5859       success: function(data){ ref.http_response(data); },
5860       error: function(o, status, err) { rcmail.http_error(o, status, err, lock); }
5861     });
5862   };
5863
5864   // send a http POST request to the server
5865   this.http_post = function(action, postdata, lock)
5866   {
5867     var url = this.url(action);
5868
5869     if (postdata && typeof postdata === 'object') {
5870       postdata._remote = 1;
5871       postdata._unlock = (lock ? lock : 0);
5872     }
5873     else
5874       postdata += (postdata ? '&' : '') + '_remote=1' + (lock ? '&_unlock='+lock : '');
5875
5876     // trigger plugin hook
5877     var result = this.triggerEvent('request'+action, postdata);
5878     if (result !== undefined) {
5879       // abort if one the handlers returned false
5880       if (result === false)
5881         return false;
5882       else
5883         postdata = result;
5884     }
5885
5886     // send request
5887     this.log('HTTP POST: ' + url);
5888
5889     return $.ajax({
5890       type: 'POST', url: url, data: postdata, dataType: 'json',
5891       success: function(data){ ref.http_response(data); },
5892       error: function(o, status, err) { rcmail.http_error(o, status, err, lock); }
5893     });
5894   };
5895
5896   // aborts ajax request
5897   this.abort_request = function(r)
5898   {
5899     if (r.request)
5900       r.request.abort();
5901     if (r.lock)
5902       this.set_busy(false, null, r.lock);
5903   };
5904
5905   // handle HTTP response
5906   this.http_response = function(response)
5907   {
5908     if (!response)
5909       return;
5910
5911     if (response.unlock)
5912       this.set_busy(false);
5913
5914     this.triggerEvent('responsebefore', {response: response});
5915     this.triggerEvent('responsebefore'+response.action, {response: response});
5916
5917     // set env vars
5918     if (response.env)
5919       this.set_env(response.env);
5920
5921     // we have labels to add
5922     if (typeof response.texts === 'object') {
5923       for (var name in response.texts)
5924         if (typeof response.texts[name] === 'string')
5925           this.add_label(name, response.texts[name]);
5926     }
5927
5928     // if we get javascript code from server -> execute it
5929     if (response.exec) {
5930       this.log(response.exec);
5931       eval(response.exec);
5932     }
5933
5934     // execute callback functions of plugins
5935     if (response.callbacks && response.callbacks.length) {
5936       for (var i=0; i < response.callbacks.length; i++)
5937         this.triggerEvent(response.callbacks[i][0], response.callbacks[i][1]);
5938     }
5939
5940     // process the response data according to the sent action
5941     switch (response.action) {
5942       case 'delete':
5943         if (this.task == 'addressbook') {
5944           var sid, uid = this.contact_list.get_selection(), writable = false;
5945
5946           if (uid && this.contact_list.rows[uid]) {
5947             // search results, get source ID from record ID
5948             if (this.env.source == '') {
5949               sid = String(uid).replace(/^[^-]+-/, '');
5950               writable = sid && this.env.address_sources[sid] && !this.env.address_sources[sid].readonly;
5951             }
5952             else {
5953               writable = !this.env.address_sources[this.env.source].readonly;
5954             }
5955           }
5956           this.enable_command('compose', (uid && this.contact_list.rows[uid]));
5957           this.enable_command('delete', 'edit', writable);
5958           this.enable_command('export', (this.contact_list && this.contact_list.rowcount > 0));
5959         }
5960
5961       case 'moveto':
5962         if (this.env.action == 'show') {
5963           // re-enable commands on move/delete error
5964           this.enable_command(this.env.message_commands, true);
5965           if (!this.env.list_post)
5966             this.enable_command('reply-list', false);
5967         }
5968         else if (this.task == 'addressbook') {
5969           this.triggerEvent('listupdate', { folder:this.env.source, rowcount:this.contact_list.rowcount });
5970         }
5971
5972       case 'purge':
5973       case 'expunge':
5974         if (this.task == 'mail') {
5975           if (!this.env.messagecount) {
5976             // clear preview pane content
5977             if (this.env.contentframe)
5978               this.show_contentframe(false);
5979             // disable commands useless when mailbox is empty
5980             this.enable_command(this.env.message_commands, 'purge', 'expunge',
5981               'select-all', 'select-none', 'sort', 'expand-all', 'expand-unread', 'collapse-all', false);
5982           }
5983           if (this.message_list)
5984             this.triggerEvent('listupdate', { folder:this.env.mailbox, rowcount:this.message_list.rowcount });
5985         }
5986         break;
5987
5988       case 'check-recent':
5989       case 'getunread':
5990       case 'search':
5991         this.env.qsearch = null;
5992       case 'list':
5993         if (this.task == 'mail') {
5994           this.enable_command('show', 'expunge', 'select-all', 'select-none', 'sort', (this.env.messagecount > 0));
5995           this.enable_command('purge', this.purge_mailbox_test());
5996           this.enable_command('expand-all', 'expand-unread', 'collapse-all', this.env.threading && this.env.messagecount);
5997
5998           if (response.action == 'list' || response.action == 'search') {
5999             this.msglist_select(this.message_list);
6000             this.triggerEvent('listupdate', { folder:this.env.mailbox, rowcount:this.message_list.rowcount });
6001           }
6002         }
6003         else if (this.task == 'addressbook') {
6004           this.enable_command('export', (this.contact_list && this.contact_list.rowcount > 0));
6005
6006           if (response.action == 'list' || response.action == 'search') {
6007             this.enable_command('search-create', this.env.source == '');
6008             this.enable_command('search-delete', this.env.search_id);
6009             this.update_group_commands();
6010             this.triggerEvent('listupdate', { folder:this.env.source, rowcount:this.contact_list.rowcount });
6011           }
6012         }
6013         break;
6014     }
6015
6016     if (response.unlock)
6017       this.hide_message(response.unlock);
6018
6019     this.triggerEvent('responseafter', {response: response});
6020     this.triggerEvent('responseafter'+response.action, {response: response});
6021   };
6022
6023   // handle HTTP request errors
6024   this.http_error = function(request, status, err, lock)
6025   {
6026     var errmsg = request.statusText;
6027
6028     this.set_busy(false, null, lock);
6029     request.abort();
6030
6031     if (request.status && errmsg)
6032       this.display_message(this.get_label('servererror') + ' (' + errmsg + ')', 'error');
6033   };
6034
6035   // post the given form to a hidden iframe
6036   this.async_upload_form = function(form, action, onload)
6037   {
6038     var ts = new Date().getTime(),
6039       frame_name = 'rcmupload'+ts;
6040
6041     // upload progress support
6042     if (this.env.upload_progress_name) {
6043       var fname = this.env.upload_progress_name,
6044         field = $('input[name='+fname+']', form);
6045
6046       if (!field.length) {
6047         field = $('<input>').attr({type: 'hidden', name: fname});
6048         field.prependTo(form);
6049       }
6050
6051       field.val(ts);
6052     }
6053
6054     // have to do it this way for IE
6055     // otherwise the form will be posted to a new window
6056     if (document.all) {
6057       var html = '<iframe name="'+frame_name+'" src="program/blank.gif" style="width:0;height:0;visibility:hidden;"></iframe>';
6058       document.body.insertAdjacentHTML('BeforeEnd', html);
6059     }
6060     else { // for standards-compilant browsers
6061       var frame = document.createElement('iframe');
6062       frame.name = frame_name;
6063       frame.style.border = 'none';
6064       frame.style.width = 0;
6065       frame.style.height = 0;
6066       frame.style.visibility = 'hidden';
6067       document.body.appendChild(frame);
6068     }
6069
6070     // handle upload errors, parsing iframe content in onload
6071     $(frame_name).bind('load', {ts:ts}, onload);
6072
6073     $(form).attr({
6074         target: frame_name,
6075         action: this.url(action, { _id:this.env.compose_id||'', _uploadid:ts }),
6076         method: 'POST'})
6077       .attr(form.encoding ? 'encoding' : 'enctype', 'multipart/form-data')
6078       .submit();
6079
6080     return frame_name;
6081   };
6082
6083   // starts interval for keep-alive/check-recent signal
6084   this.start_keepalive = function()
6085   {
6086     if (this._int)
6087       clearInterval(this._int);
6088
6089     if (this.env.keep_alive && !this.env.framed && this.task == 'mail' && this.gui_objects.mailboxlist)
6090       this._int = setInterval(function(){ ref.check_for_recent(false); }, this.env.keep_alive * 1000);
6091     else if (this.env.keep_alive && !this.env.framed && this.task != 'login' && this.env.action != 'print')
6092       this._int = setInterval(function(){ ref.keep_alive(); }, this.env.keep_alive * 1000);
6093   };
6094
6095   // sends keep-alive signal
6096   this.keep_alive = function()
6097   {
6098     if (!this.busy)
6099       this.http_request('keep-alive');
6100   };
6101
6102   // sends request to check for recent messages
6103   this.check_for_recent = function(refresh)
6104   {
6105     if (this.busy)
6106       return;
6107
6108     var lock, addurl = '_mbox=' + urlencode(this.env.mailbox);
6109
6110     if (refresh) {
6111       lock = this.set_busy(true, 'checkingmail');
6112       addurl += '&_refresh=1';
6113       // reset check-recent interval
6114       this.start_keepalive();
6115     }
6116
6117     if (this.gui_objects.messagelist)
6118       addurl += '&_list=1';
6119     if (this.gui_objects.quotadisplay)
6120       addurl += '&_quota=1';
6121     if (this.env.search_request)
6122       addurl += '&_search=' + this.env.search_request;
6123
6124     this.http_request('check-recent', addurl, lock);
6125   };
6126
6127
6128   /********************************************************/
6129   /*********            helper methods            *********/
6130   /********************************************************/
6131
6132   // check if we're in show mode or if we have a unique selection
6133   // and return the message uid
6134   this.get_single_uid = function()
6135   {
6136     return this.env.uid ? this.env.uid : (this.message_list ? this.message_list.get_single_selection() : null);
6137   };
6138
6139   // same as above but for contacts
6140   this.get_single_cid = function()
6141   {
6142     return this.env.cid ? this.env.cid : (this.contact_list ? this.contact_list.get_single_selection() : null);
6143   };
6144
6145   // gets cursor position
6146   this.get_caret_pos = function(obj)
6147   {
6148     if (obj.selectionEnd !== undefined)
6149       return obj.selectionEnd;
6150     else if (document.selection && document.selection.createRange) {
6151       var range = document.selection.createRange();
6152       if (range.parentElement()!=obj)
6153         return 0;
6154
6155       var gm = range.duplicate();
6156       if (obj.tagName == 'TEXTAREA')
6157         gm.moveToElementText(obj);
6158       else
6159         gm.expand('textedit');
6160
6161       gm.setEndPoint('EndToStart', range);
6162       var p = gm.text.length;
6163
6164       return p<=obj.value.length ? p : -1;
6165     }
6166     else
6167       return obj.value.length;
6168   };
6169
6170   // moves cursor to specified position
6171   this.set_caret_pos = function(obj, pos)
6172   {
6173     if (obj.setSelectionRange)
6174       obj.setSelectionRange(pos, pos);
6175     else if (obj.createTextRange) {
6176       var range = obj.createTextRange();
6177       range.collapse(true);
6178       range.moveEnd('character', pos);
6179       range.moveStart('character', pos);
6180       range.select();
6181     }
6182   };
6183
6184   // disable/enable all fields of a form
6185   this.lock_form = function(form, lock)
6186   {
6187     if (!form || !form.elements)
6188       return;
6189
6190     var n, len, elm;
6191
6192     if (lock)
6193       this.disabled_form_elements = [];
6194
6195     for (n=0, len=form.elements.length; n<len; n++) {
6196       elm = form.elements[n];
6197
6198       if (elm.type == 'hidden')
6199         continue;
6200       // remember which elem was disabled before lock
6201       if (lock && elm.disabled)
6202         this.disabled_form_elements.push(elm);
6203       // check this.disabled_form_elements before inArray() as a workaround for FF5 bug
6204       // http://bugs.jquery.com/ticket/9873
6205       else if (lock || (this.disabled_form_elements && $.inArray(elm, this.disabled_form_elements)<0))
6206         elm.disabled = lock;
6207     }
6208   };
6209
6210 }  // end object rcube_webmail
6211
6212
6213 // some static methods
6214 rcube_webmail.long_subject_title = function(elem, indent)
6215 {
6216   if (!elem.title) {
6217     var $elem = $(elem);
6218     if ($elem.width() + indent * 15 > $elem.parent().width())
6219       elem.title = $elem.html();
6220   }
6221 };
6222
6223 rcube_webmail.long_subject_title_ie = function(elem, indent)
6224 {
6225   if (!elem.title) {
6226     var $elem = $(elem),
6227       txt = $.trim($elem.text()),
6228       tmp = $('<span>').text(txt)
6229         .css({'position': 'absolute', 'float': 'left', 'visibility': 'hidden',
6230           'font-size': $elem.css('font-size'), 'font-weight': $elem.css('font-weight')})
6231         .appendTo($('body')),
6232       w = tmp.width();
6233
6234     tmp.remove();
6235     if (w + indent * 15 > $elem.width())
6236       elem.title = txt;
6237   }
6238 };
6239
6240 // copy event engine prototype
6241 rcube_webmail.prototype.addEventListener = rcube_event_engine.prototype.addEventListener;
6242 rcube_webmail.prototype.removeEventListener = rcube_event_engine.prototype.removeEventListener;
6243 rcube_webmail.prototype.triggerEvent = rcube_event_engine.prototype.triggerEvent;
6244