]> git.donarmstrong.com Git - roundcube.git/blob - program/js/app.js.src
Fix symlink mess
[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 5952 2012-03-03 13:20:14Z 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 = this.env.mailboxes[k].id;
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 the folder if one of its childs is currently selected
1411       // don't select if it's virtual (#1488346)
1412       if (this.env.mailbox.indexOf(name + this.env.delimiter) == 0 && !$(li).hasClass('virtual'))
1413         this.command('list', name);
1414     }
1415     else
1416       return;
1417
1418     // Work around a bug in IE6 and IE7, see #1485309
1419     if (bw.ie6 || bw.ie7) {
1420       var siblings = li.nextSibling ? li.nextSibling.getElementsByTagName('ul') : null;
1421       if (siblings && siblings.length && (li = siblings[0]) && li.style && li.style.display != 'none') {
1422         li.style.display = 'none';
1423         li.style.display = '';
1424       }
1425     }
1426
1427     this.command('save-pref', { name: 'collapsed_folders', value: this.env.collapsed_folders });
1428     this.set_unread_count_display(name, false);
1429   };
1430
1431   this.doc_mouse_up = function(e)
1432   {
1433     var model, list, li, id;
1434
1435     // ignore event if jquery UI dialog is open
1436     if ($(rcube_event.get_target(e)).closest('.ui-dialog, .ui-widget-overlay').length)
1437       return;
1438
1439     if (list = this.message_list) {
1440       if (!rcube_mouse_is_over(e, list.list.parentNode))
1441         list.blur();
1442       else
1443         list.focus();
1444       model = this.env.mailboxes;
1445     }
1446     else if (list = this.contact_list) {
1447       if (!rcube_mouse_is_over(e, list.list.parentNode))
1448         list.blur();
1449       else
1450         list.focus();
1451       model = this.env.contactfolders;
1452     }
1453     else if (this.ksearch_value) {
1454       this.ksearch_blur();
1455     }
1456
1457     // handle mouse release when dragging
1458     if (this.drag_active && model && this.env.last_folder_target) {
1459       var target = model[this.env.last_folder_target];
1460
1461       $(this.get_folder_li(this.env.last_folder_target)).removeClass('droptarget');
1462       this.env.last_folder_target = null;
1463       list.draglayer.hide();
1464
1465       if (!this.drag_menu(e, target))
1466         this.command('moveto', target);
1467     }
1468
1469     // reset 'pressed' buttons
1470     if (this.buttons_sel) {
1471       for (id in this.buttons_sel)
1472         if (typeof id !== 'function')
1473           this.button_out(this.buttons_sel[id], id);
1474       this.buttons_sel = {};
1475     }
1476   };
1477
1478   this.click_on_list = function(e)
1479   {
1480     if (this.gui_objects.qsearchbox)
1481       this.gui_objects.qsearchbox.blur();
1482
1483     if (this.message_list)
1484       this.message_list.focus();
1485     else if (this.contact_list)
1486       this.contact_list.focus();
1487
1488     return true;
1489   };
1490
1491   this.msglist_select = function(list)
1492   {
1493     if (this.preview_timer)
1494       clearTimeout(this.preview_timer);
1495     if (this.preview_read_timer)
1496       clearTimeout(this.preview_read_timer);
1497
1498     var selected = list.get_single_selection() != null;
1499
1500     this.enable_command(this.env.message_commands, selected);
1501     if (selected) {
1502       // Hide certain command buttons when Drafts folder is selected
1503       if (this.env.mailbox == this.env.drafts_mailbox)
1504         this.enable_command('reply', 'reply-all', 'reply-list', 'forward', 'forward-attachment', false);
1505       // Disable reply-list when List-Post header is not set
1506       else {
1507         var msg = this.env.messages[list.get_single_selection()];
1508         if (!msg.ml)
1509           this.enable_command('reply-list', false);
1510       }
1511     }
1512     // Multi-message commands
1513     this.enable_command('delete', 'moveto', 'copy', 'mark', (list.selection.length > 0 ? true : false));
1514
1515     // reset all-pages-selection
1516     if (selected || (list.selection.length && list.selection.length != list.rowcount))
1517       this.select_all_mode = false;
1518
1519     // start timer for message preview (wait for double click)
1520     if (selected && this.env.contentframe && !list.multi_selecting && !this.dummy_select)
1521       this.preview_timer = window.setTimeout(function(){ ref.msglist_get_preview(); }, 200);
1522     else if (this.env.contentframe)
1523       this.show_contentframe(false);
1524   };
1525
1526   // This allow as to re-select selected message and display it in preview frame
1527   this.msglist_click = function(list)
1528   {
1529     if (list.multi_selecting || !this.env.contentframe)
1530       return;
1531
1532     if (list.get_single_selection() && window.frames && window.frames[this.env.contentframe]) {
1533       if (window.frames[this.env.contentframe].location.href.indexOf(this.env.blankpage)>=0) {
1534         if (this.preview_timer)
1535           clearTimeout(this.preview_timer);
1536         if (this.preview_read_timer)
1537           clearTimeout(this.preview_read_timer);
1538         this.preview_timer = window.setTimeout(function(){ ref.msglist_get_preview(); }, 200);
1539       }
1540     }
1541   };
1542
1543   this.msglist_dbl_click = function(list)
1544   {
1545     if (this.preview_timer)
1546       clearTimeout(this.preview_timer);
1547
1548     if (this.preview_read_timer)
1549       clearTimeout(this.preview_read_timer);
1550
1551     var uid = list.get_single_selection();
1552     if (uid && this.env.mailbox == this.env.drafts_mailbox)
1553       this.goto_url('compose', '_draft_uid='+uid+'&_mbox='+urlencode(this.env.mailbox), true);
1554     else if (uid)
1555       this.show_message(uid, false, false);
1556   };
1557
1558   this.msglist_keypress = function(list)
1559   {
1560     if (list.modkey == CONTROL_KEY)
1561       return;
1562
1563     if (list.key_pressed == list.ENTER_KEY)
1564       this.command('show');
1565     else if (list.key_pressed == list.DELETE_KEY || list.key_pressed == list.BACKSPACE_KEY)
1566       this.command('delete');
1567     else if (list.key_pressed == 33)
1568       this.command('previouspage');
1569     else if (list.key_pressed == 34)
1570       this.command('nextpage');
1571   };
1572
1573   this.msglist_get_preview = function()
1574   {
1575     var uid = this.get_single_uid();
1576     if (uid && this.env.contentframe && !this.drag_active)
1577       this.show_message(uid, false, true);
1578     else if (this.env.contentframe)
1579       this.show_contentframe(false);
1580   };
1581
1582   this.msglist_expand = function(row)
1583   {
1584     if (this.env.messages[row.uid])
1585       this.env.messages[row.uid].expanded = row.expanded;
1586   };
1587
1588   this.msglist_set_coltypes = function(list)
1589   {
1590     var i, found, name, cols = list.list.tHead.rows[0].cells;
1591
1592     this.env.coltypes = [];
1593
1594     for (i=0; i<cols.length; i++)
1595       if (cols[i].id && cols[i].id.match(/^rcm/)) {
1596         name = cols[i].id.replace(/^rcm/, '');
1597         this.env.coltypes.push(name == 'to' ? 'from' : name);
1598       }
1599
1600     if ((found = $.inArray('flag', this.env.coltypes)) >= 0)
1601       this.env.flagged_col = found;
1602
1603     if ((found = $.inArray('subject', this.env.coltypes)) >= 0)
1604       this.env.subject_col = found;
1605
1606     this.command('save-pref', { name: 'list_cols', value: this.env.coltypes, session: 'list_attrib/columns' });
1607   };
1608
1609   this.check_droptarget = function(id)
1610   {
1611     var allow = false, copy = false;
1612
1613     if (this.task == 'mail')
1614       allow = (this.env.mailboxes[id] && this.env.mailboxes[id].id != this.env.mailbox && !this.env.mailboxes[id].virtual);
1615     else if (this.task == 'settings')
1616       allow = (id != this.env.mailbox);
1617     else if (this.task == 'addressbook') {
1618       if (id != this.env.source && this.env.contactfolders[id]) {
1619         if (this.env.contactfolders[id].type == 'group') {
1620           var target_abook = this.env.contactfolders[id].source;
1621           allow = this.env.contactfolders[id].id != this.env.group && !this.env.contactfolders[target_abook].readonly;
1622           copy = target_abook != this.env.source;
1623         }
1624         else {
1625           allow = !this.env.contactfolders[id].readonly;
1626           copy = true;
1627         }
1628       }
1629     }
1630
1631     return allow ? (copy ? 2 : 1) : 0;
1632   };
1633
1634
1635   /*********************************************************/
1636   /*********     (message) list functionality      *********/
1637   /*********************************************************/
1638
1639   this.init_message_row = function(row)
1640   {
1641     var expando, self = this, uid = row.uid,
1642       status_icon = (this.env.status_col != null ? 'status' : 'msg') + 'icn' + row.uid;
1643
1644     if (uid && this.env.messages[uid])
1645       $.extend(row, this.env.messages[uid]);
1646
1647     // set eventhandler to status icon
1648     if (row.icon = document.getElementById(status_icon)) {
1649       row.icon._row = row.obj;
1650       row.icon.onmousedown = function(e) { self.command('toggle_status', this); rcube_event.cancel(e); };
1651     }
1652
1653     // save message icon position too
1654     if (this.env.status_col != null)
1655       row.msgicon = document.getElementById('msgicn'+row.uid);
1656     else
1657       row.msgicon = row.icon;
1658
1659     // set eventhandler to flag icon, if icon found
1660     if (this.env.flagged_col != null && (row.flagicon = document.getElementById('flagicn'+row.uid))) {
1661       row.flagicon._row = row.obj;
1662       row.flagicon.onmousedown = function(e) { self.command('toggle_flag', this); rcube_event.cancel(e); };
1663     }
1664
1665     if (!row.depth && row.has_children && (expando = document.getElementById('rcmexpando'+row.uid))) {
1666       row.expando = expando;
1667       expando.onmousedown = function(e) { return self.expand_message_row(e, uid); };
1668     }
1669
1670     this.triggerEvent('insertrow', { uid:uid, row:row });
1671   };
1672
1673   // create a table row in the message list
1674   this.add_message_row = function(uid, cols, flags, attop)
1675   {
1676     if (!this.gui_objects.messagelist || !this.message_list)
1677       return false;
1678
1679     // Prevent from adding messages from different folder (#1487752)
1680     if (flags.mbox != this.env.mailbox && !flags.skip_mbox_check)
1681       return false;
1682
1683     if (!this.env.messages[uid])
1684       this.env.messages[uid] = {};
1685
1686     // merge flags over local message object
1687     $.extend(this.env.messages[uid], {
1688       deleted: flags.deleted?1:0,
1689       replied: flags.answered?1:0,
1690       unread: !flags.seen?1:0,
1691       forwarded: flags.forwarded?1:0,
1692       flagged: flags.flagged?1:0,
1693       has_children: flags.has_children?1:0,
1694       depth: flags.depth?flags.depth:0,
1695       unread_children: flags.unread_children?flags.unread_children:0,
1696       parent_uid: flags.parent_uid?flags.parent_uid:0,
1697       selected: this.select_all_mode || this.message_list.in_selection(uid),
1698       ml: flags.ml?1:0,
1699       ctype: flags.ctype,
1700       // flags from plugins
1701       flags: flags.extra_flags
1702     });
1703
1704     var c, n, col, html, tree = '', expando = '',
1705       list = this.message_list,
1706       rows = list.rows,
1707       message = this.env.messages[uid],
1708       css_class = 'message'
1709         + (!flags.seen ? ' unread' : '')
1710         + (flags.deleted ? ' deleted' : '')
1711         + (flags.flagged ? ' flagged' : '')
1712         + (flags.unread_children && flags.seen && !this.env.autoexpand_threads ? ' unroot' : '')
1713         + (message.selected ? ' selected' : ''),
1714       // for performance use DOM instead of jQuery here
1715       row = document.createElement('tr');
1716
1717     row.id = 'rcmrow'+uid;
1718     row.className = css_class;
1719
1720     // message status icons
1721     css_class = 'msgicon';
1722     if (this.env.status_col === null) {
1723       css_class += ' status';
1724       if (flags.deleted)
1725         css_class += ' deleted';
1726       else if (!flags.seen)
1727         css_class += ' unread';
1728       else if (flags.unread_children > 0)
1729         css_class += ' unreadchildren';
1730     }
1731     if (flags.answered)
1732       css_class += ' replied';
1733     if (flags.forwarded)
1734       css_class += ' forwarded';
1735
1736     // update selection
1737     if (message.selected && !list.in_selection(uid))
1738       list.selection.push(uid);
1739
1740     // threads
1741     if (this.env.threading) {
1742       if (message.depth) {
1743         // This assumes that div width is hardcoded to 15px,
1744         tree += '<span id="rcmtab' + uid + '" class="branch" style="width:' + (message.depth * 15) + 'px;">&nbsp;&nbsp;</span>';
1745
1746         if ((rows[message.parent_uid] && rows[message.parent_uid].expanded === false)
1747           || ((this.env.autoexpand_threads == 0 || this.env.autoexpand_threads == 2) &&
1748             (!rows[message.parent_uid] || !rows[message.parent_uid].expanded))
1749         ) {
1750           row.style.display = 'none';
1751           message.expanded = false;
1752         }
1753         else
1754           message.expanded = true;
1755       }
1756       else if (message.has_children) {
1757         if (message.expanded === undefined && (this.env.autoexpand_threads == 1 || (this.env.autoexpand_threads == 2 && message.unread_children))) {
1758           message.expanded = true;
1759         }
1760
1761         expando = '<div id="rcmexpando' + uid + '" class="' + (message.expanded ? 'expanded' : 'collapsed') + '">&nbsp;&nbsp;</div>';
1762       }
1763     }
1764
1765     tree += '<span id="msgicn'+uid+'" class="'+css_class+'">&nbsp;</span>';
1766
1767     // build subject link 
1768     if (!bw.ie && cols.subject) {
1769       var action = flags.mbox == this.env.drafts_mailbox ? 'compose' : 'show';
1770       var uid_param = flags.mbox == this.env.drafts_mailbox ? '_draft_uid' : '_uid';
1771       cols.subject = '<a href="./?_task=mail&_action='+action+'&_mbox='+urlencode(flags.mbox)+'&'+uid_param+'='+uid+'"'+
1772         ' onclick="return rcube_event.cancel(event)" onmouseover="rcube_webmail.long_subject_title(this,'+(message.depth+1)+')">'+cols.subject+'</a>';
1773     }
1774
1775     // add each submitted col
1776     for (n in this.env.coltypes) {
1777       c = this.env.coltypes[n];
1778       col = document.createElement('td');
1779       col.className = String(c).toLowerCase();
1780
1781       if (c == 'flag') {
1782         css_class = (flags.flagged ? 'flagged' : 'unflagged');
1783         html = '<span id="flagicn'+uid+'" class="'+css_class+'">&nbsp;</span>';
1784       }
1785       else if (c == 'attachment') {
1786         if (/application\/|multipart\/m/.test(flags.ctype))
1787           html = '<span class="attachment">&nbsp;</span>';
1788         else if (/multipart\/report/.test(flags.ctype))
1789           html = '<span class="report">&nbsp;</span>';
1790         else
1791           html = '&nbsp;';
1792       }
1793       else if (c == 'status') {
1794         if (flags.deleted)
1795           css_class = 'deleted';
1796         else if (!flags.seen)
1797           css_class = 'unread';
1798         else if (flags.unread_children > 0)
1799           css_class = 'unreadchildren';
1800         else
1801           css_class = 'msgicon';
1802         html = '<span id="statusicn'+uid+'" class="'+css_class+'">&nbsp;</span>';
1803       }
1804       else if (c == 'threads')
1805         html = expando;
1806       else if (c == 'subject') {
1807         if (bw.ie)
1808           col.onmouseover = function() { rcube_webmail.long_subject_title_ie(this, message.depth+1); };
1809         html = tree + cols[c];
1810       }
1811       else if (c == 'priority') {
1812         if (flags.prio > 0 && flags.prio < 6)
1813           html = '<span class="prio'+flags.prio+'">&nbsp;</span>';
1814         else
1815           html = '&nbsp;';
1816       }
1817       else
1818         html = cols[c];
1819
1820       col.innerHTML = html;
1821
1822       row.appendChild(col);
1823     }
1824
1825     list.insert_row(row, attop);
1826
1827     // remove 'old' row
1828     if (attop && this.env.pagesize && list.rowcount > this.env.pagesize) {
1829       var uid = list.get_last_row();
1830       list.remove_row(uid);
1831       list.clear_selection(uid);
1832     }
1833   };
1834
1835   this.set_list_sorting = function(sort_col, sort_order)
1836   {
1837     // set table header class
1838     $('#rcm'+this.env.sort_col).removeClass('sorted'+(this.env.sort_order.toUpperCase()));
1839     if (sort_col)
1840       $('#rcm'+sort_col).addClass('sorted'+sort_order);
1841
1842     this.env.sort_col = sort_col;
1843     this.env.sort_order = sort_order;
1844   };
1845
1846   this.set_list_options = function(cols, sort_col, sort_order, threads)
1847   {
1848     var update, add_url = '';
1849
1850     if (sort_col === undefined)
1851       sort_col = this.env.sort_col;
1852     if (!sort_order)
1853       sort_order = this.env.sort_order;
1854
1855     if (this.env.sort_col != sort_col || this.env.sort_order != sort_order) {
1856       update = 1;
1857       this.set_list_sorting(sort_col, sort_order);
1858     }
1859
1860     if (this.env.threading != threads) {
1861       update = 1;
1862       add_url += '&_threads=' + threads;
1863     }
1864
1865     if (cols && cols.length) {
1866       // make sure new columns are added at the end of the list
1867       var i, idx, name, newcols = [], oldcols = this.env.coltypes;
1868       for (i=0; i<oldcols.length; i++) {
1869         name = oldcols[i] == 'to' ? 'from' : oldcols[i];
1870         idx = $.inArray(name, cols);
1871         if (idx != -1) {
1872           newcols.push(name);
1873           delete cols[idx];
1874         }
1875       }
1876       for (i=0; i<cols.length; i++)
1877         if (cols[i])
1878           newcols.push(cols[i]);
1879
1880       if (newcols.join() != oldcols.join()) {
1881         update = 1;
1882         add_url += '&_cols=' + newcols.join(',');
1883       }
1884     }
1885
1886     if (update)
1887       this.list_mailbox('', '', sort_col+'_'+sort_order, add_url);
1888   };
1889
1890   // when user doble-clicks on a row
1891   this.show_message = function(id, safe, preview)
1892   {
1893     if (!id)
1894       return;
1895
1896     var target = window,
1897       action = preview ? 'preview': 'show',
1898       url = '&_action='+action+'&_uid='+id+'&_mbox='+urlencode(this.env.mailbox);
1899
1900     if (preview && this.env.contentframe && window.frames && window.frames[this.env.contentframe]) {
1901       target = window.frames[this.env.contentframe];
1902       url += '&_framed=1';
1903     }
1904
1905     if (safe)
1906       url += '&_safe=1';
1907
1908     // also send search request to get the right messages
1909     if (this.env.search_request)
1910       url += '&_search='+this.env.search_request;
1911
1912     if (action == 'preview' && String(target.location.href).indexOf(url) >= 0)
1913       this.show_contentframe(true);
1914     else {
1915       this.location_href(this.env.comm_path+url, target, true);
1916
1917       // mark as read and change mbox unread counter
1918       if (action == 'preview' && this.message_list && this.message_list.rows[id] && this.message_list.rows[id].unread && this.env.preview_pane_mark_read >= 0) {
1919         this.preview_read_timer = window.setTimeout(function() {
1920           ref.set_message(id, 'unread', false);
1921           ref.update_thread_root(id, 'read');
1922           if (ref.env.unread_counts[ref.env.mailbox]) {
1923             ref.env.unread_counts[ref.env.mailbox] -= 1;
1924             ref.set_unread_count(ref.env.mailbox, ref.env.unread_counts[ref.env.mailbox], ref.env.mailbox == 'INBOX');
1925           }
1926           if (ref.env.preview_pane_mark_read > 0)
1927             ref.http_post('mark', '_uid='+id+'&_flag=read&_quiet=1');
1928         }, this.env.preview_pane_mark_read * 1000);
1929       }
1930     }
1931   };
1932
1933   this.show_contentframe = function(show)
1934   {
1935     var frm, win;
1936     if (this.env.contentframe && (frm = $('#'+this.env.contentframe)) && frm.length) {
1937       if (!show && (win = window.frames[this.env.contentframe])) {
1938         if (win.location && win.location.href.indexOf(this.env.blankpage)<0)
1939           win.location.href = this.env.blankpage;
1940       }
1941       else if (!bw.safari && !bw.konq)
1942         frm[show ? 'show' : 'hide']();
1943       }
1944
1945     if (!show && this.busy)
1946       this.set_busy(false, null, this.env.frame_lock);
1947   };
1948
1949   this.lock_frame = function()
1950   {
1951     if (!this.env.frame_lock)
1952       (this.is_framed() ? parent.rcmail : this).env.frame_lock = this.set_busy(true, 'loading');
1953   };
1954
1955   // list a specific page
1956   this.list_page = function(page)
1957   {
1958     if (page == 'next')
1959       page = this.env.current_page+1;
1960     else if (page == 'last')
1961       page = this.env.pagecount;
1962     else if (page == 'prev' && this.env.current_page > 1)
1963       page = this.env.current_page-1;
1964     else if (page == 'first' && this.env.current_page > 1)
1965       page = 1;
1966
1967     if (page > 0 && page <= this.env.pagecount) {
1968       this.env.current_page = page;
1969
1970       if (this.task == 'mail')
1971         this.list_mailbox(this.env.mailbox, page);
1972       else if (this.task == 'addressbook')
1973         this.list_contacts(this.env.source, this.env.group, page);
1974     }
1975   };
1976
1977   // list messages of a specific mailbox using filter
1978   this.filter_mailbox = function(filter)
1979   {
1980     var lock = this.set_busy(true, 'searching');
1981
1982     this.clear_message_list();
1983
1984     // reset vars
1985     this.env.current_page = 1;
1986     this.http_request('search', this.search_params(false, filter), lock);
1987   };
1988
1989   // list messages of a specific mailbox
1990   this.list_mailbox = function(mbox, page, sort, add_url)
1991   {
1992     var url = '', target = window;
1993
1994     if (!mbox)
1995       mbox = this.env.mailbox ? this.env.mailbox : 'INBOX';
1996
1997     if (add_url)
1998       url += add_url;
1999
2000     // add sort to url if set
2001     if (sort)
2002       url += '&_sort=' + sort;
2003
2004     // also send search request to get the right messages
2005     if (this.env.search_request)
2006       url += '&_search='+this.env.search_request;
2007
2008     // set page=1 if changeing to another mailbox
2009     if (this.env.mailbox != mbox) {
2010       page = 1;
2011       this.env.current_page = page;
2012       this.select_all_mode = false;
2013     }
2014
2015     // unselect selected messages and clear the list and message data
2016     this.clear_message_list();
2017
2018     if (mbox != this.env.mailbox || (mbox == this.env.mailbox && !page && !sort))
2019       url += '&_refresh=1';
2020
2021     this.select_folder(mbox, '', true);
2022     this.env.mailbox = mbox;
2023
2024     // load message list remotely
2025     if (this.gui_objects.messagelist) {
2026       this.list_mailbox_remote(mbox, page, url);
2027       return;
2028     }
2029
2030     if (this.env.contentframe && window.frames && window.frames[this.env.contentframe]) {
2031       target = window.frames[this.env.contentframe];
2032       url += '&_framed=1';
2033     }
2034
2035     // load message list to target frame/window
2036     if (mbox) {
2037       this.set_busy(true, 'loading');
2038       this.location_href(this.env.comm_path+'&_mbox='+urlencode(mbox)+(page ? '&_page='+page : '')+url, target);
2039     }
2040   };
2041
2042   this.clear_message_list = function()
2043   {
2044       this.env.messages = {};
2045       this.last_selected = 0;
2046
2047       this.show_contentframe(false);
2048       if (this.message_list)
2049         this.message_list.clear(true);
2050   };
2051
2052   // send remote request to load message list
2053   this.list_mailbox_remote = function(mbox, page, add_url)
2054   {
2055     // clear message list first
2056     this.message_list.clear();
2057
2058     // send request to server
2059     var url = '_mbox='+urlencode(mbox)+(page ? '&_page='+page : ''),
2060       lock = this.set_busy(true, 'loading');
2061     this.http_request('list', url+add_url, lock);
2062   };
2063
2064   // removes messages that doesn't exists from list selection array
2065   this.update_selection = function()
2066   {
2067     var selected = this.message_list.selection,
2068       rows = this.message_list.rows,
2069       i, selection = [];
2070
2071     for (i in selected)
2072       if (rows[selected[i]])
2073         selection.push(selected[i]);
2074
2075     this.message_list.selection = selection;
2076   }
2077
2078   // expand all threads with unread children
2079   this.expand_unread = function()
2080   {
2081     var r, tbody = this.gui_objects.messagelist.tBodies[0],
2082       new_row = tbody.firstChild;
2083
2084     while (new_row) {
2085       if (new_row.nodeType == 1 && (r = this.message_list.rows[new_row.uid]) && r.unread_children) {
2086             this.message_list.expand_all(r);
2087             this.set_unread_children(r.uid);
2088       }
2089       new_row = new_row.nextSibling;
2090     }
2091     return false;
2092   };
2093
2094   // thread expanding/collapsing handler
2095   this.expand_message_row = function(e, uid)
2096   {
2097     var row = this.message_list.rows[uid];
2098
2099     // handle unread_children mark
2100     row.expanded = !row.expanded;
2101     this.set_unread_children(uid);
2102     row.expanded = !row.expanded;
2103
2104     this.message_list.expand_row(e, uid);
2105   };
2106
2107   // message list expanding
2108   this.expand_threads = function()
2109   {
2110     if (!this.env.threading || !this.env.autoexpand_threads || !this.message_list)
2111       return;
2112
2113     switch (this.env.autoexpand_threads) {
2114       case 2: this.expand_unread(); break;
2115       case 1: this.message_list.expand_all(); break;
2116     }
2117   };
2118
2119   // Initializes threads indicators/expanders after list update
2120   this.init_threads = function(roots, mbox)
2121   {
2122     // #1487752
2123     if (mbox && mbox != this.env.mailbox)
2124       return false;
2125
2126     for (var n=0, len=roots.length; n<len; n++)
2127       this.add_tree_icons(roots[n]);
2128     this.expand_threads();
2129   };
2130
2131   // adds threads tree icons to the list (or specified thread)
2132   this.add_tree_icons = function(root)
2133   {
2134     var i, l, r, n, len, pos, tmp = [], uid = [],
2135       row, rows = this.message_list.rows;
2136
2137     if (root)
2138       row = rows[root] ? rows[root].obj : null;
2139     else
2140       row = this.message_list.list.tBodies[0].firstChild;
2141
2142     while (row) {
2143       if (row.nodeType == 1 && (r = rows[row.uid])) {
2144         if (r.depth) {
2145           for (i=tmp.length-1; i>=0; i--) {
2146             len = tmp[i].length;
2147             if (len > r.depth) {
2148               pos = len - r.depth;
2149               if (!(tmp[i][pos] & 2))
2150                 tmp[i][pos] = tmp[i][pos] ? tmp[i][pos]+2 : 2;
2151             }
2152             else if (len == r.depth) {
2153               if (!(tmp[i][0] & 2))
2154                 tmp[i][0] += 2;
2155             }
2156             if (r.depth > len)
2157               break;
2158           }
2159
2160           tmp.push(new Array(r.depth));
2161           tmp[tmp.length-1][0] = 1;
2162           uid.push(r.uid);
2163         }
2164         else {
2165           if (tmp.length) {
2166             for (i in tmp) {
2167               this.set_tree_icons(uid[i], tmp[i]);
2168             }
2169             tmp = [];
2170             uid = [];
2171           }
2172           if (root && row != rows[root].obj)
2173             break;
2174         }
2175       }
2176       row = row.nextSibling;
2177     }
2178
2179     if (tmp.length) {
2180       for (i in tmp) {
2181         this.set_tree_icons(uid[i], tmp[i]);
2182       }
2183     }
2184   };
2185
2186   // adds tree icons to specified message row
2187   this.set_tree_icons = function(uid, tree)
2188   {
2189     var i, divs = [], html = '', len = tree.length;
2190
2191     for (i=0; i<len; i++) {
2192       if (tree[i] > 2)
2193         divs.push({'class': 'l3', width: 15});
2194       else if (tree[i] > 1)
2195         divs.push({'class': 'l2', width: 15});
2196       else if (tree[i] > 0)
2197         divs.push({'class': 'l1', width: 15});
2198       // separator div
2199       else if (divs.length && !divs[divs.length-1]['class'])
2200         divs[divs.length-1].width += 15;
2201       else
2202         divs.push({'class': null, width: 15});
2203     }
2204
2205     for (i=divs.length-1; i>=0; i--) {
2206       if (divs[i]['class'])
2207         html += '<div class="tree '+divs[i]['class']+'" />';
2208       else
2209         html += '<div style="width:'+divs[i].width+'px" />';
2210     }
2211
2212     if (html)
2213       $('#rcmtab'+uid).html(html);
2214   };
2215
2216   // update parent in a thread
2217   this.update_thread_root = function(uid, flag)
2218   {
2219     if (!this.env.threading)
2220       return;
2221
2222     var root = this.message_list.find_root(uid);
2223
2224     if (uid == root)
2225       return;
2226
2227     var p = this.message_list.rows[root];
2228
2229     if (flag == 'read' && p.unread_children) {
2230       p.unread_children--;
2231     }
2232     else if (flag == 'unread' && p.has_children) {
2233       // unread_children may be undefined
2234       p.unread_children = p.unread_children ? p.unread_children + 1 : 1;
2235     }
2236     else {
2237       return;
2238     }
2239
2240     this.set_message_icon(root);
2241     this.set_unread_children(root);
2242   };
2243
2244   // update thread indicators for all messages in a thread below the specified message
2245   // return number of removed/added root level messages
2246   this.update_thread = function (uid)
2247   {
2248     if (!this.env.threading)
2249       return 0;
2250
2251     var r, parent, count = 0,
2252       rows = this.message_list.rows,
2253       row = rows[uid],
2254       depth = rows[uid].depth,
2255       roots = [];
2256
2257     if (!row.depth) // root message: decrease roots count
2258       count--;
2259     else if (row.unread) {
2260       // update unread_children for thread root
2261       parent = this.message_list.find_root(uid);
2262       rows[parent].unread_children--;
2263       this.set_unread_children(parent);
2264     }
2265
2266     parent = row.parent_uid;
2267
2268     // childrens
2269     row = row.obj.nextSibling;
2270     while (row) {
2271       if (row.nodeType == 1 && (r = rows[row.uid])) {
2272             if (!r.depth || r.depth <= depth)
2273               break;
2274
2275             r.depth--; // move left
2276         // reset width and clear the content of a tab, icons will be added later
2277             $('#rcmtab'+r.uid).width(r.depth * 15).html('');
2278         if (!r.depth) { // a new root
2279               count++; // increase roots count
2280               r.parent_uid = 0;
2281               if (r.has_children) {
2282                 // replace 'leaf' with 'collapsed'
2283                 $('#rcmrow'+r.uid+' '+'.leaf:first')
2284               .attr('id', 'rcmexpando' + r.uid)
2285                   .attr('class', (r.obj.style.display != 'none' ? 'expanded' : 'collapsed'))
2286               .bind('mousedown', {uid:r.uid, p:this},
2287                     function(e) { return e.data.p.expand_message_row(e, e.data.uid); });
2288
2289                 r.unread_children = 0;
2290                 roots.push(r);
2291               }
2292               // show if it was hidden
2293               if (r.obj.style.display == 'none')
2294                 $(r.obj).show();
2295             }
2296             else {
2297               if (r.depth == depth)
2298                 r.parent_uid = parent;
2299               if (r.unread && roots.length)
2300                 roots[roots.length-1].unread_children++;
2301             }
2302           }
2303           row = row.nextSibling;
2304     }
2305
2306     // update unread_children for roots
2307     for (var i=0; i<roots.length; i++)
2308       this.set_unread_children(roots[i].uid);
2309
2310     return count;
2311   };
2312
2313   this.delete_excessive_thread_rows = function()
2314   {
2315     var rows = this.message_list.rows,
2316       tbody = this.message_list.list.tBodies[0],
2317       row = tbody.firstChild,
2318       cnt = this.env.pagesize + 1;
2319
2320     while (row) {
2321       if (row.nodeType == 1 && (r = rows[row.uid])) {
2322             if (!r.depth && cnt)
2323               cnt--;
2324
2325         if (!cnt)
2326               this.message_list.remove_row(row.uid);
2327           }
2328           row = row.nextSibling;
2329     }
2330   };
2331
2332   // set message icon
2333   this.set_message_icon = function(uid)
2334   {
2335     var css_class,
2336       row = this.message_list.rows[uid];
2337
2338     if (!row)
2339       return false;
2340
2341     if (row.icon) {
2342       css_class = 'msgicon';
2343       if (row.deleted)
2344         css_class += ' deleted';
2345       else if (row.unread)
2346         css_class += ' unread';
2347       else if (row.unread_children)
2348         css_class += ' unreadchildren';
2349       if (row.msgicon == row.icon) {
2350         if (row.replied)
2351           css_class += ' replied';
2352         if (row.forwarded)
2353           css_class += ' forwarded';
2354         css_class += ' status';
2355       }
2356
2357       row.icon.className = css_class;
2358     }
2359
2360     if (row.msgicon && row.msgicon != row.icon) {
2361       css_class = 'msgicon';
2362       if (!row.unread && row.unread_children)
2363         css_class += ' unreadchildren';
2364       if (row.replied)
2365         css_class += ' replied';
2366       if (row.forwarded)
2367         css_class += ' forwarded';
2368
2369       row.msgicon.className = css_class;
2370     }
2371
2372     if (row.flagicon) {
2373       css_class = (row.flagged ? 'flagged' : 'unflagged');
2374       row.flagicon.className = css_class;
2375     }
2376   };
2377
2378   // set message status
2379   this.set_message_status = function(uid, flag, status)
2380   {
2381     var row = this.message_list.rows[uid];
2382
2383     if (!row)
2384       return false;
2385
2386     if (flag == 'unread')
2387       row.unread = status;
2388     else if(flag == 'deleted')
2389       row.deleted = status;
2390     else if (flag == 'replied')
2391       row.replied = status;
2392     else if (flag == 'forwarded')
2393       row.forwarded = status;
2394     else if (flag == 'flagged')
2395       row.flagged = status;
2396   };
2397
2398   // set message row status, class and icon
2399   this.set_message = function(uid, flag, status)
2400   {
2401     var row = this.message_list.rows[uid];
2402
2403     if (!row)
2404       return false;
2405
2406     if (flag)
2407       this.set_message_status(uid, flag, status);
2408
2409     var rowobj = $(row.obj);
2410
2411     if (row.unread && !rowobj.hasClass('unread'))
2412       rowobj.addClass('unread');
2413     else if (!row.unread && rowobj.hasClass('unread'))
2414       rowobj.removeClass('unread');
2415
2416     if (row.deleted && !rowobj.hasClass('deleted'))
2417       rowobj.addClass('deleted');
2418     else if (!row.deleted && rowobj.hasClass('deleted'))
2419       rowobj.removeClass('deleted');
2420
2421     if (row.flagged && !rowobj.hasClass('flagged'))
2422       rowobj.addClass('flagged');
2423     else if (!row.flagged && rowobj.hasClass('flagged'))
2424       rowobj.removeClass('flagged');
2425
2426     this.set_unread_children(uid);
2427     this.set_message_icon(uid);
2428   };
2429
2430   // sets unroot (unread_children) class of parent row
2431   this.set_unread_children = function(uid)
2432   {
2433     var row = this.message_list.rows[uid];
2434
2435     if (row.parent_uid)
2436       return;
2437
2438     if (!row.unread && row.unread_children && !row.expanded)
2439       $(row.obj).addClass('unroot');
2440     else
2441       $(row.obj).removeClass('unroot');
2442   };
2443
2444   // copy selected messages to the specified mailbox
2445   this.copy_messages = function(mbox)
2446   {
2447     if (mbox && typeof mbox === 'object')
2448       mbox = mbox.id;
2449
2450     // exit if current or no mailbox specified or if selection is empty
2451     if (!mbox || mbox == this.env.mailbox || (!this.env.uid && (!this.message_list || !this.message_list.get_selection().length)))
2452       return;
2453
2454     var a_uids = [],
2455       lock = this.display_message(this.get_label('copyingmessage'), 'loading'),
2456       add_url = '&_target_mbox='+urlencode(mbox)+'&_from='+(this.env.action ? this.env.action : '');
2457
2458     if (this.env.uid)
2459       a_uids[0] = this.env.uid;
2460     else {
2461       var selection = this.message_list.get_selection();
2462       for (var n in selection) {
2463         a_uids.push(selection[n]);
2464       }
2465     }
2466
2467     add_url += '&_uid='+this.uids_to_list(a_uids);
2468
2469     // send request to server
2470     this.http_post('copy', '_mbox='+urlencode(this.env.mailbox)+add_url, lock);
2471   };
2472
2473   // move selected messages to the specified mailbox
2474   this.move_messages = function(mbox)
2475   {
2476     if (mbox && typeof mbox === 'object')
2477       mbox = mbox.id;
2478
2479     // exit if current or no mailbox specified or if selection is empty
2480     if (!mbox || mbox == this.env.mailbox || (!this.env.uid && (!this.message_list || !this.message_list.get_selection().length)))
2481       return;
2482
2483     var lock = false,
2484       add_url = '&_target_mbox='+urlencode(mbox)+'&_from='+(this.env.action ? this.env.action : '');
2485
2486     // show wait message
2487     if (this.env.action == 'show') {
2488       lock = this.set_busy(true, 'movingmessage');
2489     }
2490     else
2491       this.show_contentframe(false);
2492
2493     // Hide message command buttons until a message is selected
2494     this.enable_command(this.env.message_commands, false);
2495
2496     this._with_selected_messages('moveto', lock, add_url);
2497   };
2498
2499   // delete selected messages from the current mailbox
2500   this.delete_messages = function()
2501   {
2502     var uid, i, len, trash = this.env.trash_mailbox,
2503       list = this.message_list,
2504       selection = list ? $.merge([], list.get_selection()) : [];
2505
2506     // exit if no mailbox specified or if selection is empty
2507     if (!this.env.uid && !selection.length)
2508       return;
2509
2510     // also select childs of collapsed rows
2511     for (i=0, len=selection.length; i<len; i++) {
2512       uid = selection[i];
2513       if (list.rows[uid].has_children && !list.rows[uid].expanded)
2514         list.select_childs(uid);
2515     }
2516
2517     // if config is set to flag for deletion
2518     if (this.env.flag_for_deletion) {
2519       this.mark_message('delete');
2520       return false;
2521     }
2522     // if there isn't a defined trash mailbox or we are in it
2523     // @TODO: we should check if defined trash mailbox exists
2524     else if (!trash || this.env.mailbox == trash)
2525       this.permanently_remove_messages();
2526     // if there is a trash mailbox defined and we're not currently in it
2527     else {
2528       // if shift was pressed delete it immediately
2529       if (list && list.modkey == SHIFT_KEY) {
2530         if (confirm(this.get_label('deletemessagesconfirm')))
2531           this.permanently_remove_messages();
2532       }
2533       else
2534         this.move_messages(trash);
2535     }
2536
2537     return true;
2538   };
2539
2540   // delete the selected messages permanently
2541   this.permanently_remove_messages = function()
2542   {
2543     // exit if no mailbox specified or if selection is empty
2544     if (!this.env.uid && (!this.message_list || !this.message_list.get_selection().length))
2545       return;
2546
2547     this.show_contentframe(false);
2548     this._with_selected_messages('delete', false, '&_from='+(this.env.action ? this.env.action : ''));
2549   };
2550
2551   // Send a specifc moveto/delete request with UIDs of all selected messages
2552   // @private
2553   this._with_selected_messages = function(action, lock, add_url)
2554   {
2555     var a_uids = [], count = 0, msg;
2556
2557     if (this.env.uid)
2558       a_uids[0] = this.env.uid;
2559     else {
2560       var n, id, root, roots = [],
2561         selection = this.message_list.get_selection();
2562
2563       for (n=0, len=selection.length; n<len; n++) {
2564         id = selection[n];
2565         a_uids.push(id);
2566
2567         if (this.env.threading) {
2568           count += this.update_thread(id);
2569           root = this.message_list.find_root(id);
2570           if (root != id && $.inArray(root, roots) < 0) {
2571             roots.push(root);
2572           }
2573         }
2574         this.message_list.remove_row(id, (this.env.display_next && n == selection.length-1));
2575       }
2576       // make sure there are no selected rows
2577       if (!this.env.display_next)
2578         this.message_list.clear_selection();
2579       // update thread tree icons
2580       for (n=0, len=roots.length; n<len; n++) {
2581         this.add_tree_icons(roots[n]);
2582       }
2583     }
2584
2585     // also send search request to get the right messages
2586     if (this.env.search_request)
2587       add_url += '&_search='+this.env.search_request;
2588
2589     if (this.env.display_next && this.env.next_uid)
2590       add_url += '&_next_uid='+this.env.next_uid;
2591
2592     if (count < 0)
2593       add_url += '&_count='+(count*-1);
2594     else if (count > 0) 
2595       // remove threads from the end of the list
2596       this.delete_excessive_thread_rows();
2597
2598     add_url += '&_uid='+this.uids_to_list(a_uids);
2599
2600     if (!lock) {
2601       msg = action == 'moveto' ? 'movingmessage' : 'deletingmessage';
2602       lock = this.display_message(this.get_label(msg), 'loading');
2603     }
2604
2605     // send request to server
2606     this.http_post(action, '_mbox='+urlencode(this.env.mailbox)+add_url, lock);
2607   };
2608
2609   // set a specific flag to one or more messages
2610   this.mark_message = function(flag, uid)
2611   {
2612     var a_uids = [], r_uids = [], len, n, id,
2613       selection = this.message_list ? this.message_list.get_selection() : [];
2614
2615     if (uid)
2616       a_uids[0] = uid;
2617     else if (this.env.uid)
2618       a_uids[0] = this.env.uid;
2619     else if (this.message_list) {
2620       for (n=0, len=selection.length; n<len; n++) {
2621           a_uids.push(selection[n]);
2622       }
2623     }
2624
2625     if (!this.message_list)
2626       r_uids = a_uids;
2627     else
2628       for (n=0, len=a_uids.length; n<len; n++) {
2629         id = a_uids[n];
2630         if ((flag=='read' && this.message_list.rows[id].unread) 
2631             || (flag=='unread' && !this.message_list.rows[id].unread)
2632             || (flag=='delete' && !this.message_list.rows[id].deleted)
2633             || (flag=='undelete' && this.message_list.rows[id].deleted)
2634             || (flag=='flagged' && !this.message_list.rows[id].flagged)
2635             || (flag=='unflagged' && this.message_list.rows[id].flagged))
2636         {
2637           r_uids.push(id);
2638         }
2639       }
2640
2641     // nothing to do
2642     if (!r_uids.length && !this.select_all_mode)
2643       return;
2644
2645     switch (flag) {
2646         case 'read':
2647         case 'unread':
2648           this.toggle_read_status(flag, r_uids);
2649           break;
2650         case 'delete':
2651         case 'undelete':
2652           this.toggle_delete_status(r_uids);
2653           break;
2654         case 'flagged':
2655         case 'unflagged':
2656           this.toggle_flagged_status(flag, a_uids);
2657           break;
2658     }
2659   };
2660
2661   // set class to read/unread
2662   this.toggle_read_status = function(flag, a_uids)
2663   {
2664     var i, len = a_uids.length,
2665       url = '_uid='+this.uids_to_list(a_uids)+'&_flag='+flag,
2666       lock = this.display_message(this.get_label('markingmessage'), 'loading');
2667
2668     // mark all message rows as read/unread
2669     for (i=0; i<len; i++)
2670       this.set_message(a_uids[i], 'unread', (flag=='unread' ? true : false));
2671
2672     // also send search request to get the right messages
2673     if (this.env.search_request)
2674       url += '&_search='+this.env.search_request;
2675
2676     this.http_post('mark', url, lock);
2677
2678     for (i=0; i<len; i++)
2679       this.update_thread_root(a_uids[i], flag);
2680   };
2681
2682   // set image to flagged or unflagged
2683   this.toggle_flagged_status = function(flag, a_uids)
2684   {
2685     var i, len = a_uids.length,
2686       url = '_uid='+this.uids_to_list(a_uids)+'&_flag='+flag,
2687       lock = this.display_message(this.get_label('markingmessage'), 'loading');
2688
2689     // mark all message rows as flagged/unflagged
2690     for (i=0; i<len; i++)
2691       this.set_message(a_uids[i], 'flagged', (flag=='flagged' ? true : false));
2692
2693     // also send search request to get the right messages
2694     if (this.env.search_request)
2695       url += '&_search='+this.env.search_request;
2696
2697     this.http_post('mark', url, lock);
2698   };
2699
2700   // mark all message rows as deleted/undeleted
2701   this.toggle_delete_status = function(a_uids)
2702   {
2703     var len = a_uids.length,
2704       i, uid, all_deleted = true,
2705       rows = this.message_list ? this.message_list.rows : [];
2706
2707     if (len == 1) {
2708       if (!rows.length || (rows[a_uids[0]] && !rows[a_uids[0]].deleted))
2709         this.flag_as_deleted(a_uids);
2710       else
2711         this.flag_as_undeleted(a_uids);
2712
2713       return true;
2714     }
2715
2716     for (i=0; i<len; i++) {
2717       uid = a_uids[i];
2718       if (rows[uid] && !rows[uid].deleted) {
2719         all_deleted = false;
2720         break;
2721       }
2722     }
2723
2724     if (all_deleted)
2725       this.flag_as_undeleted(a_uids);
2726     else
2727       this.flag_as_deleted(a_uids);
2728
2729     return true;
2730   };
2731
2732   this.flag_as_undeleted = function(a_uids)
2733   {
2734     var i, len=a_uids.length,
2735       url = '_uid='+this.uids_to_list(a_uids)+'&_flag=undelete',
2736       lock = this.display_message(this.get_label('markingmessage'), 'loading');
2737
2738     for (i=0; i<len; i++)
2739       this.set_message(a_uids[i], 'deleted', false);
2740
2741     // also send search request to get the right messages
2742     if (this.env.search_request)
2743       url += '&_search='+this.env.search_request;
2744
2745     this.http_post('mark', url, lock);
2746     return true;
2747   };
2748
2749   this.flag_as_deleted = function(a_uids)
2750   {
2751     var add_url = '',
2752       r_uids = [],
2753       rows = this.message_list ? this.message_list.rows : [],
2754       count = 0;
2755
2756     for (var i=0, len=a_uids.length; i<len; i++) {
2757       uid = a_uids[i];
2758       if (rows[uid]) {
2759         if (rows[uid].unread)
2760           r_uids[r_uids.length] = uid;
2761
2762             if (this.env.skip_deleted) {
2763               count += this.update_thread(uid);
2764           this.message_list.remove_row(uid, (this.env.display_next && i == this.message_list.selection.length-1));
2765             }
2766             else
2767               this.set_message(uid, 'deleted', true);
2768       }
2769     }
2770
2771     // make sure there are no selected rows
2772     if (this.env.skip_deleted && this.message_list) {
2773       if(!this.env.display_next)
2774         this.message_list.clear_selection();
2775       if (count < 0)
2776         add_url += '&_count='+(count*-1);
2777       else if (count > 0) 
2778         // remove threads from the end of the list
2779         this.delete_excessive_thread_rows();
2780     }
2781
2782     add_url = '&_from='+(this.env.action ? this.env.action : ''),
2783       lock = this.display_message(this.get_label('markingmessage'), 'loading');
2784
2785     // ??
2786     if (r_uids.length)
2787       add_url += '&_ruid='+this.uids_to_list(r_uids);
2788
2789     if (this.env.skip_deleted) {
2790       if (this.env.display_next && this.env.next_uid)
2791         add_url += '&_next_uid='+this.env.next_uid;
2792     }
2793
2794     // also send search request to get the right messages
2795     if (this.env.search_request)
2796       add_url += '&_search='+this.env.search_request;
2797
2798     this.http_post('mark', '_uid='+this.uids_to_list(a_uids)+'&_flag=delete'+add_url, lock);
2799     return true;
2800   };
2801
2802   // flag as read without mark request (called from backend)
2803   // argument should be a coma-separated list of uids
2804   this.flag_deleted_as_read = function(uids)
2805   {
2806     var icn_src, uid, i, len,
2807       rows = this.message_list ? this.message_list.rows : [];
2808
2809     uids = String(uids).split(',');
2810
2811     for (i=0, len=uids.length; i<len; i++) {
2812       uid = uids[i];
2813       if (rows[uid])
2814         this.set_message(uid, 'unread', false);
2815     }
2816   };
2817
2818   // Converts array of message UIDs to comma-separated list for use in URL
2819   // with select_all mode checking
2820   this.uids_to_list = function(uids)
2821   {
2822     return this.select_all_mode ? '*' : uids.join(',');
2823   };
2824
2825
2826   /*********************************************************/
2827   /*********       mailbox folders methods         *********/
2828   /*********************************************************/
2829
2830   this.expunge_mailbox = function(mbox)
2831   {
2832     var lock, url = '_mbox='+urlencode(mbox);
2833
2834     // lock interface if it's the active mailbox
2835     if (mbox == this.env.mailbox) {
2836       lock = this.set_busy(true, 'loading');
2837       url += '&_reload=1';
2838       if (this.env.search_request)
2839         url += '&_search='+this.env.search_request;
2840     }
2841
2842     // send request to server
2843     this.http_post('expunge', url, lock);
2844   };
2845
2846   this.purge_mailbox = function(mbox)
2847   {
2848     var lock = false,
2849       url = '_mbox='+urlencode(mbox);
2850
2851     if (!confirm(this.get_label('purgefolderconfirm')))
2852       return false;
2853
2854     // lock interface if it's the active mailbox
2855     if (mbox == this.env.mailbox) {
2856        lock = this.set_busy(true, 'loading');
2857        url += '&_reload=1';
2858      }
2859
2860     // send request to server
2861     this.http_post('purge', url, lock);
2862   };
2863
2864   // test if purge command is allowed
2865   this.purge_mailbox_test = function()
2866   {
2867     return (this.env.messagecount && (this.env.mailbox == this.env.trash_mailbox || this.env.mailbox == this.env.junk_mailbox
2868       || this.env.mailbox.match('^' + RegExp.escape(this.env.trash_mailbox) + RegExp.escape(this.env.delimiter))
2869       || this.env.mailbox.match('^' + RegExp.escape(this.env.junk_mailbox) + RegExp.escape(this.env.delimiter))));
2870   };
2871
2872
2873   /*********************************************************/
2874   /*********           login form methods          *********/
2875   /*********************************************************/
2876
2877   // handler for keyboard events on the _user field
2878   this.login_user_keyup = function(e)
2879   {
2880     var key = rcube_event.get_keycode(e);
2881     var passwd = $('#rcmloginpwd');
2882
2883     // enter
2884     if (key == 13 && passwd.length && !passwd.val()) {
2885       passwd.focus();
2886       return rcube_event.cancel(e);
2887     }
2888
2889     return true;
2890   };
2891
2892
2893   /*********************************************************/
2894   /*********        message compose methods        *********/
2895   /*********************************************************/
2896
2897   // init message compose form: set focus and eventhandlers
2898   this.init_messageform = function()
2899   {
2900     if (!this.gui_objects.messageform)
2901       return false;
2902
2903     var input_from = $("[name='_from']"),
2904       input_to = $("[name='_to']"),
2905       input_subject = $("input[name='_subject']"),
2906       input_message = $("[name='_message']").get(0),
2907       html_mode = $("input[name='_is_html']").val() == '1',
2908       ac_fields = ['cc', 'bcc', 'replyto', 'followupto'],
2909       ac_props;
2910
2911     // configure parallel autocompletion
2912     if (this.env.autocomplete_threads > 0) {
2913       ac_props = {
2914         threads: this.env.autocomplete_threads,
2915         sources: this.env.autocomplete_sources
2916       };
2917     }
2918
2919     // init live search events
2920     this.init_address_input_events(input_to, ac_props);
2921     for (var i in ac_fields) {
2922       this.init_address_input_events($("[name='_"+ac_fields[i]+"']"), ac_props);
2923     }
2924
2925     if (!html_mode) {
2926       this.set_caret_pos(input_message, this.env.top_posting ? 0 : $(input_message).val().length);
2927       // add signature according to selected identity
2928       // if we have HTML editor, signature is added in callback
2929       if (input_from.prop('type') == 'select-one' && $("input[name='_draft_saveid']").val() == '') {
2930         this.change_identity(input_from[0]);
2931       }
2932     }
2933
2934     if (input_to.val() == '')
2935       input_to.focus();
2936     else if (input_subject.val() == '')
2937       input_subject.focus();
2938     else if (input_message)
2939       input_message.focus();
2940
2941     this.env.compose_focus_elem = document.activeElement;
2942
2943     // get summary of all field values
2944     this.compose_field_hash(true);
2945
2946     // start the auto-save timer
2947     this.auto_save_start();
2948   };
2949
2950   this.init_address_input_events = function(obj, props)
2951   {
2952     this.env.recipients_delimiter = this.env.recipients_separator + ' ';
2953
2954     obj[bw.ie || bw.safari || bw.chrome ? 'keydown' : 'keypress'](function(e) { return ref.ksearch_keydown(e, this, props); })
2955       .attr('autocomplete', 'off');
2956   };
2957
2958   // checks the input fields before sending a message
2959   this.check_compose_input = function(cmd)
2960   {
2961     // check input fields
2962     var ed, input_to = $("[name='_to']"),
2963       input_cc = $("[name='_cc']"),
2964       input_bcc = $("[name='_bcc']"),
2965       input_from = $("[name='_from']"),
2966       input_subject = $("[name='_subject']"),
2967       input_message = $("[name='_message']");
2968
2969     // check sender (if have no identities)
2970     if (input_from.prop('type') == 'text' && !rcube_check_email(input_from.val(), true)) {
2971       alert(this.get_label('nosenderwarning'));
2972       input_from.focus();
2973       return false;
2974     }
2975
2976     // check for empty recipient
2977     var recipients = input_to.val() ? input_to.val() : (input_cc.val() ? input_cc.val() : input_bcc.val());
2978     if (!rcube_check_email(recipients.replace(/^\s+/, '').replace(/[\s,;]+$/, ''), true)) {
2979       alert(this.get_label('norecipientwarning'));
2980       input_to.focus();
2981       return false;
2982     }
2983
2984     // check if all files has been uploaded
2985     for (var key in this.env.attachments) {
2986       if (typeof this.env.attachments[key] === 'object' && !this.env.attachments[key].complete) {
2987         alert(this.get_label('notuploadedwarning'));
2988         return false;
2989       }
2990     }
2991
2992     // display localized warning for missing subject
2993     if (input_subject.val() == '') {
2994       var myprompt = $('<div class="prompt">').html('<div class="message">' + this.get_label('nosubjectwarning') + '</div>').appendTo(document.body);
2995       var prompt_value = $('<input>').attr('type', 'text').attr('size', 30).appendTo(myprompt).val(this.get_label('nosubject'));
2996
2997       var buttons = {};
2998       buttons[this.get_label('cancel')] = function(){
2999         input_subject.focus();
3000         $(this).dialog('close');
3001       };
3002       buttons[this.get_label('sendmessage')] = function(){
3003         input_subject.val(prompt_value.val());
3004         $(this).dialog('close');
3005         ref.command(cmd, { nocheck:true });  // repeat command which triggered this
3006       };
3007
3008       myprompt.dialog({
3009         modal: true,
3010         resizable: false,
3011         buttons: buttons,
3012         close: function(event, ui) { $(this).remove() }
3013       });
3014       prompt_value.select();
3015       return false;
3016     }
3017
3018     // Apply spellcheck changes if spell checker is active
3019     this.stop_spellchecking();
3020
3021     if (window.tinyMCE)
3022       ed = tinyMCE.get(this.env.composebody);
3023
3024     // check for empty body
3025     if (!ed && input_message.val() == '' && !confirm(this.get_label('nobodywarning'))) {
3026       input_message.focus();
3027       return false;
3028     }
3029     else if (ed) {
3030       if (!ed.getContent() && !confirm(this.get_label('nobodywarning'))) {
3031         ed.focus();
3032         return false;
3033       }
3034       // move body from html editor to textarea (just to be sure, #1485860)
3035       tinyMCE.triggerSave();
3036     }
3037
3038     return true;
3039   };
3040
3041   this.toggle_editor = function(props)
3042   {
3043     if (props.mode == 'html') {
3044       this.display_spellcheck_controls(false);
3045       this.plain2html($('#'+props.id).val(), props.id);
3046       tinyMCE.execCommand('mceAddControl', false, props.id);
3047     }
3048     else {
3049       var thisMCE = tinyMCE.get(props.id), existingHtml;
3050       if (thisMCE.plugins.spellchecker && thisMCE.plugins.spellchecker.active)
3051         thisMCE.execCommand('mceSpellCheck', false);
3052
3053       if (existingHtml = thisMCE.getContent()) {
3054         if (!confirm(this.get_label('editorwarning'))) {
3055           return false;
3056         }
3057         this.html2plain(existingHtml, props.id);
3058       }
3059       tinyMCE.execCommand('mceRemoveControl', false, props.id);
3060       this.display_spellcheck_controls(true);
3061     }
3062
3063     return true;
3064   };
3065
3066   this.stop_spellchecking = function()
3067   {
3068     var ed;
3069     if (window.tinyMCE && (ed = tinyMCE.get(this.env.composebody))) {
3070       if (ed.plugins.spellchecker && ed.plugins.spellchecker.active)
3071         ed.execCommand('mceSpellCheck');
3072     }
3073     else if ((ed = this.env.spellcheck) && !this.spellcheck_ready) {
3074       $(ed.spell_span).trigger('click');
3075       this.set_spellcheck_state('ready');
3076     }
3077   };
3078
3079   this.display_spellcheck_controls = function(vis)
3080   {
3081     if (this.env.spellcheck) {
3082       // stop spellchecking process
3083       if (!vis)
3084         this.stop_spellchecking();
3085
3086       $(this.env.spellcheck.spell_container)[vis ? 'show' : 'hide']();
3087     }
3088   };
3089
3090   this.set_spellcheck_state = function(s)
3091   {
3092     this.spellcheck_ready = (s == 'ready' || s == 'no_error_found');
3093     this.enable_command('spellcheck', this.spellcheck_ready);
3094   };
3095
3096   // get selected language
3097   this.spellcheck_lang = function()
3098   {
3099     var ed;
3100     if (window.tinyMCE && (ed = tinyMCE.get(this.env.composebody)) && ed.plugins.spellchecker) {
3101       return ed.plugins.spellchecker.selectedLang;
3102     }
3103     else if (this.env.spellcheck) {
3104       return GOOGIE_CUR_LANG;
3105     }
3106   };
3107
3108   // resume spellchecking, highlight provided mispellings without new ajax request
3109   this.spellcheck_resume = function(ishtml, data)
3110   {
3111     if (ishtml) {
3112       var ed = tinyMCE.get(this.env.composebody);
3113         sp = ed.plugins.spellchecker;
3114
3115       sp.active = 1;
3116       sp._markWords(data);
3117       ed.nodeChanged();
3118     }
3119     else {
3120       var sp = this.env.spellcheck;
3121       sp.prepare(false, true);
3122       sp.processData(data);
3123     }
3124   }
3125
3126   this.set_draft_id = function(id)
3127   {
3128     $("input[name='_draft_saveid']").val(id);
3129   };
3130
3131   this.auto_save_start = function()
3132   {
3133     if (this.env.draft_autosave)
3134       this.save_timer = self.setTimeout(function(){ ref.command("savedraft"); }, this.env.draft_autosave * 1000);
3135
3136     // Unlock interface now that saving is complete
3137     this.busy = false;
3138   };
3139
3140   this.compose_field_hash = function(save)
3141   {
3142     // check input fields
3143     var ed, str = '',
3144       value_to = $("[name='_to']").val(),
3145       value_cc = $("[name='_cc']").val(),
3146       value_bcc = $("[name='_bcc']").val(),
3147       value_subject = $("[name='_subject']").val();
3148
3149     if (value_to)
3150       str += value_to+':';
3151     if (value_cc)
3152       str += value_cc+':';
3153     if (value_bcc)
3154       str += value_bcc+':';
3155     if (value_subject)
3156       str += value_subject+':';
3157
3158     if (window.tinyMCE && (ed = tinyMCE.get(this.env.composebody)))
3159       str += ed.getContent();
3160     else
3161       str += $("[name='_message']").val();
3162
3163     if (this.env.attachments)
3164       for (var upload_id in this.env.attachments)
3165         str += upload_id;
3166
3167     if (save)
3168       this.cmp_hash = str;
3169
3170     return str;
3171   };
3172
3173   this.change_identity = function(obj, show_sig)
3174   {
3175     if (!obj || !obj.options)
3176       return false;
3177
3178     if (!show_sig)
3179       show_sig = this.env.show_sig;
3180
3181     var cursor_pos, p = -1,
3182       id = obj.options[obj.selectedIndex].value,
3183       input_message = $("[name='_message']"),
3184       message = input_message.val(),
3185       is_html = ($("input[name='_is_html']").val() == '1'),
3186       sig = this.env.identity,
3187       sig_separator = this.env.sig_above && (this.env.compose_mode == 'reply' || this.env.compose_mode == 'forward') ? '---' : '-- ';
3188
3189     // enable manual signature insert
3190     if (this.env.signatures && this.env.signatures[id]) {
3191       this.enable_command('insert-sig', true);
3192       this.env.compose_commands.push('insert-sig');
3193     }
3194     else
3195       this.enable_command('insert-sig', false);
3196
3197     if (!is_html) {
3198       // remove the 'old' signature
3199       if (show_sig && sig && this.env.signatures && this.env.signatures[sig]) {
3200
3201         sig = this.env.signatures[sig].is_html ? this.env.signatures[sig].plain_text : this.env.signatures[sig].text;
3202         sig = sig.replace(/\r\n/g, '\n');
3203
3204         if (!sig.match(/^--[ -]\n/m))
3205           sig = sig_separator + '\n' + sig;
3206
3207         p = this.env.sig_above ? message.indexOf(sig) : message.lastIndexOf(sig);
3208         if (p >= 0)
3209           message = message.substring(0, p) + message.substring(p+sig.length, message.length);
3210       }
3211       // add the new signature string
3212       if (show_sig && this.env.signatures && this.env.signatures[id]) {
3213         sig = this.env.signatures[id]['is_html'] ? this.env.signatures[id]['plain_text'] : this.env.signatures[id]['text'];
3214         sig = sig.replace(/\r\n/g, '\n');
3215
3216         if (!sig.match(/^--[ -]\n/m))
3217           sig = sig_separator + '\n' + sig;
3218
3219         if (this.env.sig_above) {
3220           if (p >= 0) { // in place of removed signature
3221             message = message.substring(0, p) + sig + message.substring(p, message.length);
3222             cursor_pos = p - 1;
3223           }
3224           else if (pos = this.get_caret_pos(input_message.get(0))) { // at cursor position
3225             message = message.substring(0, pos) + '\n' + sig + '\n\n' + message.substring(pos, message.length);
3226             cursor_pos = pos;
3227           }
3228           else { // on top
3229             cursor_pos = 0;
3230             message = '\n\n' + sig + '\n\n' + message.replace(/^[\r\n]+/, '');
3231           }
3232         }
3233         else {
3234           message = message.replace(/[\r\n]+$/, '');
3235           cursor_pos = !this.env.top_posting && message.length ? message.length+1 : 0;
3236           message += '\n\n' + sig;
3237         }
3238       }
3239       else
3240         cursor_pos = this.env.top_posting ? 0 : message.length;
3241
3242       input_message.val(message);
3243
3244       // move cursor before the signature
3245       this.set_caret_pos(input_message.get(0), cursor_pos);
3246     }
3247     else if (show_sig && this.env.signatures) {  // html
3248       var editor = tinyMCE.get(this.env.composebody),
3249         sigElem = editor.dom.get('_rc_sig');
3250
3251       // Append the signature as a div within the body
3252       if (!sigElem) {
3253         var body = editor.getBody(),
3254           doc = editor.getDoc();
3255
3256         sigElem = doc.createElement('div');
3257         sigElem.setAttribute('id', '_rc_sig');
3258
3259         if (this.env.sig_above) {
3260           // if no existing sig and top posting then insert at caret pos
3261           editor.getWin().focus(); // correct focus in IE & Chrome
3262
3263           var node = editor.selection.getNode();
3264           if (node.nodeName == 'BODY') {
3265             // no real focus, insert at start
3266             body.insertBefore(sigElem, body.firstChild);
3267             body.insertBefore(doc.createElement('br'), body.firstChild);
3268           }
3269           else {
3270             body.insertBefore(sigElem, node.nextSibling);
3271             body.insertBefore(doc.createElement('br'), node.nextSibling);
3272           }
3273         }
3274         else {
3275           if (bw.ie)  // add empty line before signature on IE
3276             body.appendChild(doc.createElement('br'));
3277
3278           body.appendChild(sigElem);
3279         }
3280       }
3281
3282       if (this.env.signatures[id]) {
3283         if (this.env.signatures[id].is_html) {
3284           sig = this.env.signatures[id].text;
3285           if (!this.env.signatures[id].plain_text.match(/^--[ -]\r?\n/m))
3286             sig = sig_separator + '<br />' + sig;
3287         }
3288         else {
3289           sig = this.env.signatures[id].text;
3290           if (!sig.match(/^--[ -]\r?\n/m))
3291             sig = sig_separator + '\n' + sig;
3292           sig = '<pre>' + sig + '</pre>';
3293         }
3294
3295         sigElem.innerHTML = sig;
3296       }
3297     }
3298
3299     this.env.identity = id;
3300     return true;
3301   };
3302
3303   // upload attachment file
3304   this.upload_file = function(form)
3305   {
3306     if (!form)
3307       return false;
3308
3309     // get file input field, count files on capable browser
3310     var i, size = 0, field = $('input[type=file]', form).get(0),
3311       files = field.files ? field.files.length : field.value ? 1 : 0;
3312
3313     // create hidden iframe and post upload form
3314     if (files) {
3315       // check file size
3316       if (field.files && this.env.max_filesize && this.env.filesizeerror) {
3317         for (i=0; i<files; i++)
3318           size += field.files[i].size;
3319         if (size && size > this.env.max_filesize) {
3320           this.display_message(this.env.filesizeerror, 'error');
3321           return;
3322         }
3323       }
3324
3325       var frame_name = this.async_upload_form(form, 'upload', function(e) {
3326         var d, content = '';
3327         try {
3328           if (this.contentDocument) {
3329             d = this.contentDocument;
3330           } else if (this.contentWindow) {
3331             d = this.contentWindow.document;
3332           }
3333           content = d.childNodes[0].innerHTML;
3334         } catch (err) {}
3335
3336         if (!content.match(/add2attachment/) && (!bw.opera || (rcmail.env.uploadframe && rcmail.env.uploadframe == e.data.ts))) {
3337           if (!content.match(/display_message/))
3338             rcmail.display_message(rcmail.get_label('fileuploaderror'), 'error');
3339           rcmail.remove_from_attachment_list(e.data.ts);
3340         }
3341         // Opera hack: handle double onload
3342         if (bw.opera)
3343           rcmail.env.uploadframe = e.data.ts;
3344       });
3345
3346       // display upload indicator and cancel button
3347       var content = '<span>' + this.get_label('uploading' + (files > 1 ? 'many' : '')) + '</span>',
3348         ts = frame_name.replace(/^rcmupload/, '');
3349
3350       if (this.env.loadingicon)
3351         content = '<img src="'+this.env.loadingicon+'" alt="" />'+content;
3352       if (this.env.cancelicon)
3353         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;
3354       this.add2attachment_list(ts, { name:'', html:content, complete:false });
3355
3356       // upload progress support
3357       if (this.env.upload_progress_time) {
3358         this.upload_progress_start('upload', ts);
3359       }
3360     }
3361
3362     // set reference to the form object
3363     this.gui_objects.attachmentform = form;
3364     return true;
3365   };
3366
3367   // add file name to attachment list
3368   // called from upload page
3369   this.add2attachment_list = function(name, att, upload_id)
3370   {
3371     if (!this.gui_objects.attachmentlist)
3372       return false;
3373
3374     var indicator, li = $('<li>').attr('id', name).html(att.html);
3375
3376     // replace indicator's li
3377     if (upload_id && (indicator = document.getElementById(upload_id))) {
3378       li.replaceAll(indicator);
3379     }
3380     else { // add new li
3381       li.appendTo(this.gui_objects.attachmentlist);
3382     }
3383
3384     if (upload_id && this.env.attachments[upload_id])
3385       delete this.env.attachments[upload_id];
3386
3387     this.env.attachments[name] = att;
3388
3389     return true;
3390   };
3391
3392   this.remove_from_attachment_list = function(name)
3393   {
3394     delete this.env.attachments[name];
3395     $('#'+name).remove();
3396   };
3397
3398   this.remove_attachment = function(name)
3399   {
3400     if (name && this.env.attachments[name])
3401       this.http_post('remove-attachment', { _id:this.env.compose_id, _file:name });
3402
3403     return true;
3404   };
3405
3406   this.cancel_attachment_upload = function(name, frame_name)
3407   {
3408     if (!name || !frame_name)
3409       return false;
3410
3411     this.remove_from_attachment_list(name);
3412     $("iframe[name='"+frame_name+"']").remove();
3413     return false;
3414   };
3415
3416   this.upload_progress_start = function(action, name)
3417   {
3418     window.setTimeout(function() { rcmail.http_request(action, {_progress: name}); },
3419       this.env.upload_progress_time * 1000);
3420   };
3421
3422   this.upload_progress_update = function(param)
3423   {
3424     var elem = $('#'+param.name + '> span');
3425
3426     if (!elem.length || !param.text)
3427       return;
3428
3429     elem.text(param.text);
3430
3431     if (!param.done)
3432       this.upload_progress_start(param.action, param.name);
3433   };
3434
3435   // send remote request to add a new contact
3436   this.add_contact = function(value)
3437   {
3438     if (value)
3439       this.http_post('addcontact', '_address='+value);
3440
3441     return true;
3442   };
3443
3444   // send remote request to search mail or contacts
3445   this.qsearch = function(value)
3446   {
3447     if (value != '') {
3448       var n, lock = this.set_busy(true, 'searching');
3449
3450       if (this.message_list)
3451         this.clear_message_list();
3452       else if (this.contact_list)
3453         this.list_contacts_clear();
3454
3455       // reset vars
3456       this.env.current_page = 1;
3457       r = this.http_request('search', this.search_params(value)
3458         + (this.env.source ? '&_source='+urlencode(this.env.source) : '')
3459         + (this.env.group ? '&_gid='+urlencode(this.env.group) : ''), lock);
3460
3461       this.env.qsearch = {lock: lock, request: r};
3462     }
3463   };
3464
3465   // build URL params for search
3466   this.search_params = function(search, filter)
3467   {
3468     var n, url = [], mods_arr = [],
3469       mods = this.env.search_mods,
3470       mbox = this.env.mailbox;
3471
3472     if (!filter && this.gui_objects.search_filter)
3473       filter = this.gui_objects.search_filter.value;
3474
3475     if (!search && this.gui_objects.qsearchbox)
3476       search = this.gui_objects.qsearchbox.value;
3477
3478     if (filter)
3479       url.push('_filter=' + urlencode(filter));
3480
3481     if (search) {
3482       url.push('_q='+urlencode(search));
3483
3484       if (mods && this.message_list)
3485         mods = mods[mbox] ? mods[mbox] : mods['*'];
3486
3487       if (mods) {
3488         for (n in mods)
3489           mods_arr.push(n);
3490         url.push('_headers='+mods_arr.join(','));
3491       }
3492     }
3493
3494     if (mbox)
3495       url.push('_mbox='+urlencode(mbox));
3496
3497     return url.join('&');
3498   };
3499
3500   // reset quick-search form
3501   this.reset_qsearch = function()
3502   {
3503     if (this.gui_objects.qsearchbox)
3504       this.gui_objects.qsearchbox.value = '';
3505
3506     if (this.env.qsearch)
3507       this.abort_request(this.env.qsearch);
3508
3509     this.env.qsearch = null;
3510     this.env.search_request = null;
3511     this.env.search_id = null;
3512   };
3513
3514   this.sent_successfully = function(type, msg)
3515   {
3516     this.display_message(msg, type);
3517     // before redirect we need to wait some time for Chrome (#1486177)
3518     window.setTimeout(function(){ ref.list_mailbox(); }, 500);
3519   };
3520
3521
3522   /*********************************************************/
3523   /*********     keyboard live-search methods      *********/
3524   /*********************************************************/
3525
3526   // handler for keyboard events on address-fields
3527   this.ksearch_keydown = function(e, obj, props)
3528   {
3529     if (this.ksearch_timer)
3530       clearTimeout(this.ksearch_timer);
3531
3532     var highlight,
3533       key = rcube_event.get_keycode(e),
3534       mod = rcube_event.get_modifier(e);
3535
3536     switch (key) {
3537       case 38:  // key up
3538       case 40:  // key down
3539         if (!this.ksearch_pane)
3540           break;
3541
3542         var dir = key==38 ? 1 : 0;
3543
3544         highlight = document.getElementById('rcmksearchSelected');
3545         if (!highlight)
3546           highlight = this.ksearch_pane.__ul.firstChild;
3547
3548         if (highlight)
3549           this.ksearch_select(dir ? highlight.previousSibling : highlight.nextSibling);
3550
3551         return rcube_event.cancel(e);
3552
3553       case 9:   // tab
3554         if (mod == SHIFT_KEY || !this.ksearch_visible()) {
3555           this.ksearch_hide();
3556           return;
3557         }
3558
3559       case 13:  // enter
3560         if (!this.ksearch_visible())
3561           return false;
3562
3563         // insert selected address and hide ksearch pane
3564         this.insert_recipient(this.ksearch_selected);
3565         this.ksearch_hide();
3566
3567         return rcube_event.cancel(e);
3568
3569       case 27:  // escape
3570         this.ksearch_hide();
3571         return;
3572
3573       case 37:  // left
3574       case 39:  // right
3575         if (mod != SHIFT_KEY)
3576               return;
3577     }
3578
3579     // start timer
3580     this.ksearch_timer = window.setTimeout(function(){ ref.ksearch_get_results(props); }, 200);
3581     this.ksearch_input = obj;
3582
3583     return true;
3584   };
3585
3586   this.ksearch_visible = function()
3587   {
3588     return (this.ksearch_selected !== null && this.ksearch_selected !== undefined && this.ksearch_value);
3589   };
3590
3591   this.ksearch_select = function(node)
3592   {
3593     var current = $('#rcmksearchSelected');
3594     if (current[0] && node) {
3595       current.removeAttr('id').removeClass('selected');
3596     }
3597
3598     if (node) {
3599       $(node).attr('id', 'rcmksearchSelected').addClass('selected');
3600       this.ksearch_selected = node._rcm_id;
3601     }
3602   };
3603
3604   this.insert_recipient = function(id)
3605   {
3606     if (id === null || !this.env.contacts[id] || !this.ksearch_input)
3607       return;
3608
3609     // get cursor pos
3610     var inp_value = this.ksearch_input.value,
3611       cpos = this.get_caret_pos(this.ksearch_input),
3612       p = inp_value.lastIndexOf(this.ksearch_value, cpos),
3613       trigger = false,
3614       insert = '',
3615       // replace search string with full address
3616       pre = inp_value.substring(0, p),
3617       end = inp_value.substring(p+this.ksearch_value.length, inp_value.length);
3618
3619     this.ksearch_destroy();
3620
3621     // insert all members of a group
3622     if (typeof this.env.contacts[id] === 'object' && this.env.contacts[id].id) {
3623       insert += this.env.contacts[id].name + this.env.recipients_delimiter;
3624       this.group2expand = $.extend({}, this.env.contacts[id]);
3625       this.group2expand.input = this.ksearch_input;
3626       this.http_request('mail/group-expand', '_source='+urlencode(this.env.contacts[id].source)+'&_gid='+urlencode(this.env.contacts[id].id), false);
3627     }
3628     else if (typeof this.env.contacts[id] === 'string') {
3629       insert = this.env.contacts[id] + this.env.recipients_delimiter;
3630       trigger = true;
3631     }
3632
3633     this.ksearch_input.value = pre + insert + end;
3634
3635     // set caret to insert pos
3636     cpos = p+insert.length;
3637     if (this.ksearch_input.setSelectionRange)
3638       this.ksearch_input.setSelectionRange(cpos, cpos);
3639
3640     if (trigger)
3641       this.triggerEvent('autocomplete_insert', { field:this.ksearch_input, insert:insert });
3642   };
3643
3644   this.replace_group_recipients = function(id, recipients)
3645   {
3646     if (this.group2expand && this.group2expand.id == id) {
3647       this.group2expand.input.value = this.group2expand.input.value.replace(this.group2expand.name, recipients);
3648       this.triggerEvent('autocomplete_insert', { field:this.group2expand.input, insert:recipients });
3649       this.group2expand = null;
3650     }
3651   };
3652
3653   // address search processor
3654   this.ksearch_get_results = function(props)
3655   {
3656     var inp_value = this.ksearch_input ? this.ksearch_input.value : null;
3657
3658     if (inp_value === null)
3659       return;
3660
3661     if (this.ksearch_pane && this.ksearch_pane.is(":visible"))
3662       this.ksearch_pane.hide();
3663
3664     // get string from current cursor pos to last comma
3665     var cpos = this.get_caret_pos(this.ksearch_input),
3666       p = inp_value.lastIndexOf(this.env.recipients_separator, cpos-1),
3667       q = inp_value.substring(p+1, cpos),
3668       min = this.env.autocomplete_min_length,
3669       ac = this.ksearch_data;
3670
3671     // trim query string
3672     q = $.trim(q);
3673
3674     // Don't (re-)search if the last results are still active
3675     if (q == this.ksearch_value)
3676       return;
3677
3678     this.ksearch_destroy();
3679
3680     if (q.length && q.length < min) {
3681       if (!this.ksearch_info) {
3682         this.ksearch_info = this.display_message(
3683           this.get_label('autocompletechars').replace('$min', min));
3684       }
3685       return;
3686     }
3687
3688     var old_value = this.ksearch_value;
3689     this.ksearch_value = q;
3690
3691     // ...string is empty
3692     if (!q.length)
3693       return;
3694
3695     // ...new search value contains old one and previous search was not finished or its result was empty
3696     if (old_value && old_value.length && q.indexOf(old_value) == 0 && (!ac || !ac.num) && this.env.contacts && !this.env.contacts.length)
3697       return;
3698
3699     var i, lock, source, xhr, reqid = new Date().getTime(),
3700       threads = props && props.threads ? props.threads : 1,
3701       sources = props && props.sources ? props.sources : [],
3702       action = props && props.action ? props.action : 'mail/autocomplete';
3703
3704     this.ksearch_data = {id: reqid, sources: sources.slice(), action: action,
3705       locks: [], requests: [], num: sources.length};
3706
3707     for (i=0; i<threads; i++) {
3708       source = this.ksearch_data.sources.shift();
3709       if (threads > 1 && source === null)
3710         break;
3711
3712       lock = this.display_message(this.get_label('searching'), 'loading');
3713       xhr = this.http_post(action, '_search='+urlencode(q)+'&_id='+reqid
3714         + (source ? '&_source='+urlencode(source) : ''), lock);
3715
3716       this.ksearch_data.locks.push(lock);
3717       this.ksearch_data.requests.push(xhr);
3718     }
3719   };
3720
3721   this.ksearch_query_results = function(results, search, reqid)
3722   {
3723     // search stopped in meantime?
3724     if (!this.ksearch_value)
3725       return;
3726
3727     // ignore this outdated search response
3728     if (this.ksearch_input && search != this.ksearch_value)
3729       return;
3730
3731     // display search results
3732     var i, len, ul, li, text, init,
3733       value = this.ksearch_value,
3734       data = this.ksearch_data,
3735       maxlen = this.env.autocomplete_max ? this.env.autocomplete_max : 15;
3736
3737     // create results pane if not present
3738     if (!this.ksearch_pane) {
3739       ul = $('<ul>');
3740       this.ksearch_pane = $('<div>').attr('id', 'rcmKSearchpane')
3741         .css({ position:'absolute', 'z-index':30000 }).append(ul).appendTo(document.body);
3742       this.ksearch_pane.__ul = ul[0];
3743     }
3744
3745     ul = this.ksearch_pane.__ul;
3746
3747     // remove all search results or add to existing list if parallel search
3748     if (reqid && this.ksearch_pane.data('reqid') == reqid) {
3749       maxlen -= ul.childNodes.length;
3750     }
3751     else {
3752       this.ksearch_pane.data('reqid', reqid);
3753       init = 1;
3754       // reset content
3755       ul.innerHTML = '';
3756       this.env.contacts = [];
3757       // move the results pane right under the input box
3758       var pos = $(this.ksearch_input).offset();
3759       this.ksearch_pane.css({ left:pos.left+'px', top:(pos.top + this.ksearch_input.offsetHeight)+'px', display: 'none'});
3760     }
3761
3762     // add each result line to list
3763     if (results && (len = results.length)) {
3764       for (i=0; i < len && maxlen > 0; i++) {
3765         text = typeof results[i] === 'object' ? results[i].name : results[i];
3766         li = document.createElement('LI');
3767         li.innerHTML = text.replace(new RegExp('('+RegExp.escape(value)+')', 'ig'), '##$1%%').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/##([^%]+)%%/g, '<b>$1</b>');
3768         li.onmouseover = function(){ ref.ksearch_select(this); };
3769         li.onmouseup = function(){ ref.ksearch_click(this) };
3770         li._rcm_id = this.env.contacts.length + i;
3771         ul.appendChild(li);
3772         maxlen -= 1;
3773       }
3774     }
3775
3776     if (ul.childNodes.length) {
3777       this.ksearch_pane.show();
3778       // select the first
3779       if (!this.env.contacts.length) {
3780         $('li:first', ul).attr('id', 'rcmksearchSelected').addClass('selected');
3781         this.ksearch_selected = 0;
3782       }
3783     }
3784
3785     if (len)
3786       this.env.contacts = this.env.contacts.concat(results);
3787
3788     // run next parallel search
3789     if (data.id == reqid) {
3790       data.num--;
3791       if (maxlen > 0 && data.sources.length) {
3792         var lock, xhr, source = data.sources.shift();
3793         if (source) {
3794           lock = this.display_message(this.get_label('searching'), 'loading');
3795           xhr = this.http_post(data.action, '_search='+urlencode(value)+'&_id='+reqid
3796             +'&_source='+urlencode(source), lock);
3797
3798           this.ksearch_data.locks.push(lock);
3799           this.ksearch_data.requests.push(xhr);
3800         }
3801       }
3802       else if (!maxlen) {
3803         if (!this.ksearch_msg)
3804           this.ksearch_msg = this.display_message(this.get_label('autocompletemore'));
3805         // abort pending searches
3806         this.ksearch_abort();
3807       }
3808     }
3809   };
3810
3811   this.ksearch_click = function(node)
3812   {
3813     if (this.ksearch_input)
3814       this.ksearch_input.focus();
3815
3816     this.insert_recipient(node._rcm_id);
3817     this.ksearch_hide();
3818   };
3819
3820   this.ksearch_blur = function()
3821   {
3822     if (this.ksearch_timer)
3823       clearTimeout(this.ksearch_timer);
3824
3825     this.ksearch_input = null;
3826     this.ksearch_hide();
3827   };
3828
3829   this.ksearch_hide = function()
3830   {
3831     this.ksearch_selected = null;
3832     this.ksearch_value = '';
3833
3834     if (this.ksearch_pane)
3835       this.ksearch_pane.hide();
3836
3837     this.ksearch_destroy();
3838   };
3839
3840   // Clears autocomplete data/requests
3841   this.ksearch_destroy = function()
3842   {
3843     this.ksearch_abort();
3844
3845     if (this.ksearch_info)
3846       this.hide_message(this.ksearch_info);
3847
3848     if (this.ksearch_msg)
3849       this.hide_message(this.ksearch_msg);
3850
3851     this.ksearch_data = null;
3852     this.ksearch_info = null;
3853     this.ksearch_msg = null;
3854   }
3855
3856   // Aborts pending autocomplete requests
3857   this.ksearch_abort = function()
3858   {
3859     var i, len, ac = this.ksearch_data;
3860
3861     if (!ac)
3862       return;
3863
3864     for (i=0, len=ac.locks.length; i<len; i++)
3865       this.abort_request({request: ac.requests[i], lock: ac.locks[i]});
3866   };
3867
3868
3869   /*********************************************************/
3870   /*********         address book methods          *********/
3871   /*********************************************************/
3872
3873   this.contactlist_keypress = function(list)
3874   {
3875     if (list.key_pressed == list.DELETE_KEY)
3876       this.command('delete');
3877   };
3878
3879   this.contactlist_select = function(list)
3880   {
3881     if (this.preview_timer)
3882       clearTimeout(this.preview_timer);
3883
3884     var n, id, sid, ref = this, writable = false,
3885       source = this.env.source ? this.env.address_sources[this.env.source] : null;
3886
3887     if (id = list.get_single_selection())
3888       this.preview_timer = window.setTimeout(function(){ ref.load_contact(id, 'show'); }, 200);
3889     else if (this.env.contentframe)
3890       this.show_contentframe(false);
3891
3892     // no source = search result, we'll need to detect if any of
3893     // selected contacts are in writable addressbook to enable edit/delete
3894     if (list.selection.length) {
3895       if (!source) {
3896         for (n in list.selection) {
3897           sid = String(list.selection[n]).replace(/^[^-]+-/, '');
3898           if (sid && this.env.address_sources[sid] && !this.env.address_sources[sid].readonly) {
3899             writable = true;
3900             break;
3901           }
3902         }
3903       }
3904       else {
3905         writable = !source.readonly;
3906       }
3907     }
3908
3909     this.enable_command('compose', this.env.group || list.selection.length > 0);
3910     this.enable_command('edit', id && writable);
3911     this.enable_command('delete', list.selection.length && writable);
3912
3913     return false;
3914   };
3915
3916   this.list_contacts = function(src, group, page)
3917   {
3918     var folder, add_url = '',
3919       target = window;
3920
3921     if (!src)
3922       src = this.env.source;
3923
3924     if (page && this.current_page == page && src == this.env.source && group == this.env.group)
3925       return false;
3926
3927     if (src != this.env.source) {
3928       page = this.env.current_page = 1;
3929       this.reset_qsearch();
3930     }
3931     else if (group != this.env.group)
3932       page = this.env.current_page = 1;
3933
3934     if (this.env.search_id)
3935       folder = 'S'+this.env.search_id;
3936     else
3937       folder = group ? 'G'+src+group : src;
3938
3939     this.select_folder(folder);
3940
3941     this.env.source = src;
3942     this.env.group = group;
3943
3944     // load contacts remotely
3945     if (this.gui_objects.contactslist) {
3946       this.list_contacts_remote(src, group, page);
3947       return;
3948     }
3949
3950     if (this.env.contentframe && window.frames && window.frames[this.env.contentframe]) {
3951       target = window.frames[this.env.contentframe];
3952       add_url = '&_framed=1';
3953     }
3954
3955     if (group)
3956       add_url += '&_gid='+group;
3957     if (page)
3958       add_url += '&_page='+page;
3959
3960     // also send search request to get the correct listing
3961     if (this.env.search_request)
3962       add_url += '&_search='+this.env.search_request;
3963
3964     this.set_busy(true, 'loading');
3965     this.location_href(this.env.comm_path + (src ? '&_source='+urlencode(src) : '') + add_url, target);
3966   };
3967
3968   // send remote request to load contacts list
3969   this.list_contacts_remote = function(src, group, page)
3970   {
3971     // clear message list first
3972     this.list_contacts_clear();
3973
3974     // send request to server
3975     var url = (src ? '_source='+urlencode(src) : '') + (page ? (src?'&':'') + '_page='+page : ''),
3976       lock = this.set_busy(true, 'loading');
3977
3978     this.env.source = src;
3979     this.env.group = group;
3980
3981     if (group)
3982       url += '&_gid='+group;
3983
3984     // also send search request to get the right messages
3985     if (this.env.search_request)
3986       url += '&_search='+this.env.search_request;
3987
3988     this.http_request('list', url, lock);
3989   };
3990
3991   this.list_contacts_clear = function()
3992   {
3993     this.contact_list.clear(true);
3994     this.show_contentframe(false);
3995     this.enable_command('delete', false);
3996     this.enable_command('compose', this.env.group ? true : false);
3997   };
3998
3999   // load contact record
4000   this.load_contact = function(cid, action, framed)
4001   {
4002     var add_url = '', target = window;
4003
4004     if (this.env.contentframe && window.frames && window.frames[this.env.contentframe]) {
4005       add_url = '&_framed=1';
4006       target = window.frames[this.env.contentframe];
4007       this.show_contentframe(true);
4008
4009       // load dummy content
4010       if (!cid) {
4011         // unselect selected row(s)
4012         this.contact_list.clear_selection();
4013         this.enable_command('delete', 'compose', false);
4014       }
4015     }
4016     else if (framed)
4017       return false;
4018
4019     if (action && (cid || action=='add') && !this.drag_active) {
4020       if (this.env.group)
4021         add_url += '&_gid='+urlencode(this.env.group);
4022
4023       this.location_href(this.env.comm_path+'&_action='+action
4024         +'&_source='+urlencode(this.env.source)
4025         +'&_cid='+urlencode(cid) + add_url, target, true);
4026     }
4027     return true;
4028   };
4029
4030   // add/delete member to/from the group
4031   this.group_member_change = function(what, cid, source, gid)
4032   {
4033     what = what == 'add' ? 'add' : 'del';
4034     var lock = this.display_message(this.get_label(what == 'add' ? 'addingmember' : 'removingmember'), 'loading');
4035
4036     this.http_post('group-'+what+'members', '_cid='+urlencode(cid)
4037       + '&_source='+urlencode(source)
4038       + '&_gid='+urlencode(gid), lock);
4039   };
4040
4041   // copy a contact to the specified target (group or directory)
4042   this.copy_contact = function(cid, to)
4043   {
4044     if (!cid)
4045       cid = this.contact_list.get_selection().join(',');
4046
4047     if (to.type == 'group' && to.source == this.env.source)
4048       this.group_member_change('add', cid, to.source, to.id);
4049     else if (to.type == 'group' && !this.env.address_sources[to.source].readonly) {
4050       var lock = this.display_message(this.get_label('copyingcontact'), 'loading');
4051       this.http_post('copy', '_cid='+urlencode(cid)
4052         + '&_source='+urlencode(this.env.source)
4053         + '&_to='+urlencode(to.source)
4054         + '&_togid='+urlencode(to.id)
4055         + (this.env.group ? '&_gid='+urlencode(this.env.group) : ''), lock);
4056     }
4057     else if (to.id != this.env.source && cid && this.env.address_sources[to.id] && !this.env.address_sources[to.id].readonly) {
4058       var lock = this.display_message(this.get_label('copyingcontact'), 'loading');
4059       this.http_post('copy', '_cid='+urlencode(cid)
4060         + '&_source='+urlencode(this.env.source)
4061         + '&_to='+urlencode(to.id)
4062         + (this.env.group ? '&_gid='+urlencode(this.env.group) : ''), lock);
4063     }
4064   };
4065
4066   this.delete_contacts = function()
4067   {
4068     var selection = this.contact_list.get_selection(),
4069       undelete = this.env.source && this.env.address_sources[this.env.source].undelete;
4070
4071     // exit if no mailbox specified or if selection is empty
4072     if (!(selection.length || this.env.cid) || (!undelete && !confirm(this.get_label('deletecontactconfirm'))))
4073       return;
4074
4075     var id, n, a_cids = [], qs = '';
4076
4077     if (this.env.cid)
4078       a_cids.push(this.env.cid);
4079     else {
4080       for (n=0; n<selection.length; n++) {
4081         id = selection[n];
4082         a_cids.push(id);
4083         this.contact_list.remove_row(id, (n == selection.length-1));
4084       }
4085
4086       // hide content frame if we delete the currently displayed contact
4087       if (selection.length == 1)
4088         this.show_contentframe(false);
4089     }
4090
4091     if (this.env.group)
4092       qs += '&_gid='+urlencode(this.env.group);
4093
4094     // also send search request to get the right records from the next page
4095     if (this.env.search_request)
4096       qs += '&_search='+this.env.search_request;
4097
4098     // send request to server
4099     this.http_post('delete', '_cid='+urlencode(a_cids.join(','))
4100       +'&_source='+urlencode(this.env.source)
4101       +'&_from='+(this.env.action ? this.env.action : '')+qs,
4102       this.display_message(this.get_label('contactdeleting'), 'loading'));
4103
4104     return true;
4105   };
4106
4107   // update a contact record in the list
4108   this.update_contact_row = function(cid, cols_arr, newcid, source)
4109   {
4110     var c, row, list = this.contact_list;
4111
4112     cid = this.html_identifier(cid);
4113
4114     // when in searching mode, concat cid with the source name
4115     if (!list.rows[cid]) {
4116       cid = cid+'-'+source;
4117       if (newcid)
4118         newcid = newcid+'-'+source;
4119     }
4120
4121     if (list.rows[cid] && (row = list.rows[cid].obj)) {
4122       for (c=0; c<cols_arr.length; c++)
4123         if (row.cells[c])
4124           $(row.cells[c]).html(cols_arr[c]);
4125
4126       // cid change
4127       if (newcid) {
4128         newcid = this.html_identifier(newcid);
4129         row.id = 'rcmrow' + newcid;
4130         list.remove_row(cid);
4131         list.init_row(row);
4132         list.selection[0] = newcid;
4133         row.style.display = '';
4134       }
4135     }
4136   };
4137
4138   // add row to contacts list
4139   this.add_contact_row = function(cid, cols, select)
4140   {
4141     if (!this.gui_objects.contactslist)
4142       return false;
4143
4144     var c, list = this.contact_list,
4145       row = document.createElement('tr');
4146
4147     row.id = 'rcmrow'+this.html_identifier(cid);
4148     row.className = 'contact';
4149
4150     if (list.in_selection(cid))
4151       row.className += ' selected';
4152
4153     // add each submitted col
4154     for (c in cols) {
4155       col = document.createElement('td');
4156       col.className = String(c).toLowerCase();
4157       col.innerHTML = cols[c];
4158       row.appendChild(col);
4159     }
4160
4161     list.insert_row(row);
4162
4163     this.enable_command('export', list.rowcount > 0);
4164   };
4165
4166   this.init_contact_form = function()
4167   {
4168     var ref = this, col;
4169
4170     this.set_photo_actions($('#ff_photo').val());
4171
4172     for (col in this.env.coltypes)
4173       this.init_edit_field(col, null);
4174
4175     $('.contactfieldgroup .row a.deletebutton').click(function() {
4176       ref.delete_edit_field(this);
4177       return false;
4178     });
4179
4180     $('select.addfieldmenu').change(function(e) {
4181       ref.insert_edit_field($(this).val(), $(this).attr('rel'), this);
4182       this.selectedIndex = 0;
4183     });
4184
4185     // enable date pickers on date fields
4186     if ($.datepicker && this.env.date_format) {
4187       $.datepicker.setDefaults({
4188         dateFormat: this.env.date_format,
4189         changeMonth: true,
4190         changeYear: true,
4191         yearRange: '-100:+10',
4192         showOtherMonths: true,
4193         selectOtherMonths: true,
4194         monthNamesShort: this.env.month_names,
4195         onSelect: function(dateText) { $(this).focus().val(dateText) }
4196       });
4197       $('input.datepicker').datepicker();
4198     }
4199
4200     $("input[type='text']:visible").first().focus();
4201   };
4202
4203   this.group_create = function()
4204   {
4205     this.add_input_row('contactgroup');
4206   };
4207
4208   this.group_rename = function()
4209   {
4210     if (!this.env.group || !this.gui_objects.folderlist)
4211       return;
4212
4213     if (!this.name_input) {
4214       this.enable_command('list', 'listgroup', false);
4215       this.name_input = $('<input>').attr('type', 'text').val(this.env.contactgroups['G'+this.env.source+this.env.group].name);
4216       this.name_input.bind('keydown', function(e){ return rcmail.add_input_keydown(e); });
4217       this.env.group_renaming = true;
4218
4219       var link, li = this.get_folder_li(this.env.source+this.env.group, 'rcmliG');
4220       if (li && (link = li.firstChild)) {
4221         $(link).hide().before(this.name_input);
4222       }
4223     }
4224
4225     this.name_input.select().focus();
4226   };
4227
4228   this.group_delete = function()
4229   {
4230     if (this.env.group && confirm(this.get_label('deletegroupconfirm'))) {
4231       var lock = this.set_busy(true, 'groupdeleting');
4232       this.http_post('group-delete', '_source='+urlencode(this.env.source)+'&_gid='+urlencode(this.env.group), lock);
4233     }
4234   };
4235
4236   // callback from server upon group-delete command
4237   this.remove_group_item = function(prop)
4238   {
4239     var li, key = 'G'+prop.source+prop.id;
4240     if ((li = this.get_folder_li(key))) {
4241       this.triggerEvent('group_delete', { source:prop.source, id:prop.id, li:li });
4242
4243       li.parentNode.removeChild(li);
4244       delete this.env.contactfolders[key];
4245       delete this.env.contactgroups[key];
4246     }
4247
4248     this.list_contacts(prop.source, 0);
4249   };
4250
4251   // @TODO: maybe it would be better to use popup instead of inserting input to the list?
4252   this.add_input_row = function(type)
4253   {
4254     if (!this.gui_objects.folderlist)
4255       return;
4256
4257     if (!this.name_input) {
4258       this.name_input = $('<input>').attr('type', 'text').data('tt', type);
4259       this.name_input.bind('keydown', function(e){ return rcmail.add_input_keydown(e); });
4260       this.name_input_li = $('<li>').addClass(type).append(this.name_input);
4261
4262       var li = type == 'contactsearch' ? $('li:last', this.gui_objects.folderlist) : this.get_folder_li(this.env.source);
4263       this.name_input_li.insertAfter(li);
4264     }
4265
4266     this.name_input.select().focus();
4267   };
4268
4269   // handler for keyboard events on the input field
4270   this.add_input_keydown = function(e)
4271   {
4272     var key = rcube_event.get_keycode(e),
4273       input = $(e.target), itype = input.data('tt');
4274
4275     // enter
4276     if (key == 13) {
4277       var newname = input.val();
4278
4279       if (newname) {
4280         var lock = this.set_busy(true, 'loading');
4281
4282         if (itype == 'contactsearch')
4283           this.http_post('search-create', '_search='+urlencode(this.env.search_request)+'&_name='+urlencode(newname), lock);
4284         else if (this.env.group_renaming)
4285           this.http_post('group-rename', '_source='+urlencode(this.env.source)+'&_gid='+urlencode(this.env.group)+'&_name='+urlencode(newname), lock);
4286         else
4287           this.http_post('group-create', '_source='+urlencode(this.env.source)+'&_name='+urlencode(newname), lock);
4288       }
4289       return false;
4290     }
4291     // escape
4292     else if (key == 27)
4293       this.reset_add_input();
4294
4295     return true;
4296   };
4297
4298   this.reset_add_input = function()
4299   {
4300     if (this.name_input) {
4301       if (this.env.group_renaming) {
4302         var li = this.name_input.parent();
4303         li.children().last().show();
4304         this.env.group_renaming = false;
4305       }
4306
4307       this.name_input.remove();
4308
4309       if (this.name_input_li)
4310         this.name_input_li.remove();
4311
4312       this.name_input = this.name_input_li = null;
4313     }
4314
4315     this.enable_command('list', 'listgroup', true);
4316   };
4317
4318   // callback for creating a new contact group
4319   this.insert_contact_group = function(prop)
4320   {
4321     this.reset_add_input();
4322
4323     prop.type = 'group';
4324     var key = 'G'+prop.source+prop.id,
4325       link = $('<a>').attr('href', '#')
4326         .attr('rel', prop.source+':'+prop.id)
4327         .click(function() { return rcmail.command('listgroup', prop, this); })
4328         .html(prop.name),
4329       li = $('<li>').attr({id: 'rcmli'+this.html_identifier(key), 'class': 'contactgroup'})
4330         .append(link);
4331
4332     this.env.contactfolders[key] = this.env.contactgroups[key] = prop;
4333     this.add_contact_group_row(prop, li);
4334
4335     this.triggerEvent('group_insert', { id:prop.id, source:prop.source, name:prop.name, li:li[0] });
4336   };
4337
4338   // callback for renaming a contact group
4339   this.update_contact_group = function(prop)
4340   {
4341     this.reset_add_input();
4342
4343     var key = 'G'+prop.source+prop.id,
4344       li = this.get_folder_li(key),
4345       link;
4346
4347     // group ID has changed, replace link node and identifiers
4348     if (li && prop.newid) {
4349       var newkey = 'G'+prop.source+prop.newid,
4350         newprop = $.extend({}, prop);;
4351
4352       li.id = 'rcmli' + this.html_identifier(newkey);
4353       this.env.contactfolders[newkey] = this.env.contactfolders[key];
4354       this.env.contactfolders[newkey].id = prop.newid;
4355       this.env.group = prop.newid;
4356
4357       delete this.env.contactfolders[key];
4358       delete this.env.contactgroups[key];
4359
4360       newprop.id = prop.newid;
4361       newprop.type = 'group';
4362
4363       link = $('<a>').attr('href', '#')
4364         .attr('rel', prop.source+':'+prop.newid)
4365         .click(function() { return rcmail.command('listgroup', newprop, this); })
4366         .html(prop.name);
4367       $(li).children().replaceWith(link);
4368     }
4369     // update displayed group name
4370     else if (li && (link = li.firstChild) && link.tagName.toLowerCase() == 'a')
4371       link.innerHTML = prop.name;
4372
4373     this.env.contactfolders[key].name = this.env.contactgroups[key].name = prop.name;
4374     this.add_contact_group_row(prop, $(li), true);
4375
4376     this.triggerEvent('group_update', { id:prop.id, source:prop.source, name:prop.name, li:li[0], newid:prop.newid });
4377   };
4378
4379   // add contact group row to the list, with sorting
4380   this.add_contact_group_row = function(prop, li, reloc)
4381   {
4382     var row, name = prop.name.toUpperCase(),
4383       sibling = this.get_folder_li(prop.source),
4384       prefix = 'rcmliG' + this.html_identifier(prop.source);
4385
4386     // When renaming groups, we need to remove it from DOM and insert it in the proper place
4387     if (reloc) {
4388       row = li.clone(true);
4389       li.remove();
4390     }
4391     else
4392       row = li;
4393
4394     $('li[id^="'+prefix+'"]', this.gui_objects.folderlist).each(function(i, elem) {
4395       if (name >= $(this).text().toUpperCase())
4396         sibling = elem;
4397       else
4398         return false;
4399     });
4400
4401     row.insertAfter(sibling);
4402   };
4403
4404   this.update_group_commands = function()
4405   {
4406     var source = this.env.source != '' ? this.env.address_sources[this.env.source] : null;
4407     this.enable_command('group-create', (source && source.groups && !source.readonly));
4408     this.enable_command('group-rename', 'group-delete', (source && source.groups && this.env.group && !source.readonly));
4409   };
4410
4411   this.init_edit_field = function(col, elem)
4412   {
4413     if (!elem)
4414       elem = $('.ff_' + col);
4415
4416     elem.focus(function(){ ref.focus_textfield(this); })
4417       .blur(function(){ ref.blur_textfield(this); })
4418       .each(function(){ this._placeholder = this.title = ref.env.coltypes[col].label; ref.blur_textfield(this); });
4419   };
4420
4421   this.insert_edit_field = function(col, section, menu)
4422   {
4423     // just make pre-defined input field visible
4424     var elem = $('#ff_'+col);
4425     if (elem.length) {
4426       elem.show().focus();
4427       $(menu).children('option[value="'+col+'"]').prop('disabled', true);
4428     }
4429     else {
4430       var lastelem = $('.ff_'+col),
4431         appendcontainer = $('#contactsection'+section+' .contactcontroller'+col);
4432
4433       if (!appendcontainer.length)
4434         appendcontainer = $('<fieldset>').addClass('contactfieldgroup contactcontroller'+col).insertAfter($('#contactsection'+section+' .contactfieldgroup').last());
4435
4436       if (appendcontainer.length && appendcontainer.get(0).nodeName == 'FIELDSET') {
4437         var input, colprop = this.env.coltypes[col],
4438           row = $('<div>').addClass('row'),
4439           cell = $('<div>').addClass('contactfieldcontent data'),
4440           label = $('<div>').addClass('contactfieldlabel label');
4441
4442         if (colprop.subtypes_select)
4443           label.html(colprop.subtypes_select);
4444         else
4445           label.html(colprop.label);
4446
4447         var name_suffix = colprop.limit != 1 ? '[]' : '';
4448         if (colprop.type == 'text' || colprop.type == 'date') {
4449           input = $('<input>')
4450             .addClass('ff_'+col)
4451             .attr({type: 'text', name: '_'+col+name_suffix, size: colprop.size})
4452             .appendTo(cell);
4453
4454           this.init_edit_field(col, input);
4455
4456           if (colprop.type == 'date' && $.datepicker)
4457             input.datepicker();
4458         }
4459         else if (colprop.type == 'composite') {
4460           var childcol, cp, first, templ, cols = [], suffices = [];
4461           // read template for composite field order
4462           if ((templ = this.env[col+'_template'])) {
4463             for (var j=0; j < templ.length; j++) {
4464               cols.push(templ[j][1]);
4465               suffices.push(templ[j][2]);
4466             }
4467           }
4468           else {  // list fields according to appearance in colprop
4469             for (childcol in colprop.childs)
4470               cols.push(childcol);
4471           }
4472
4473           for (var i=0; i < cols.length; i++) {
4474             childcol = cols[i];
4475             cp = colprop.childs[childcol];
4476             input = $('<input>')
4477               .addClass('ff_'+childcol)
4478               .attr({ type: 'text', name: '_'+childcol+name_suffix, size: cp.size })
4479               .appendTo(cell);
4480             cell.append(suffices[i] || " ");
4481             this.init_edit_field(childcol, input);
4482             if (!first) first = input;
4483           }
4484           input = first;  // set focus to the first of this composite fields
4485         }
4486         else if (colprop.type == 'select') {
4487           input = $('<select>')
4488             .addClass('ff_'+col)
4489             .attr('name', '_'+col+name_suffix)
4490             .appendTo(cell);
4491
4492           var options = input.attr('options');
4493           options[options.length] = new Option('---', '');
4494           if (colprop.options)
4495             $.each(colprop.options, function(i, val){ options[options.length] = new Option(val, i); });
4496         }
4497
4498         if (input) {
4499           var delbutton = $('<a href="#del"></a>')
4500             .addClass('contactfieldbutton deletebutton')
4501             .attr({title: this.get_label('delete'), rel: col})
4502             .html(this.env.delbutton)
4503             .click(function(){ ref.delete_edit_field(this); return false })
4504             .appendTo(cell);
4505
4506           row.append(label).append(cell).appendTo(appendcontainer.show());
4507           input.first().focus();
4508
4509           // disable option if limit reached
4510           if (!colprop.count) colprop.count = 0;
4511           if (++colprop.count == colprop.limit && colprop.limit)
4512             $(menu).children('option[value="'+col+'"]').prop('disabled', true);
4513         }
4514       }
4515     }
4516   };
4517
4518   this.delete_edit_field = function(elem)
4519   {
4520     var col = $(elem).attr('rel'),
4521       colprop = this.env.coltypes[col],
4522       fieldset = $(elem).parents('fieldset.contactfieldgroup'),
4523       addmenu = fieldset.parent().find('select.addfieldmenu');
4524
4525     // just clear input but don't hide the last field
4526     if (--colprop.count <= 0 && colprop.visible)
4527       $(elem).parent().children('input').val('').blur();
4528     else {
4529       $(elem).parents('div.row').remove();
4530       // hide entire fieldset if no more rows
4531       if (!fieldset.children('div.row').length)
4532         fieldset.hide();
4533     }
4534
4535     // enable option in add-field selector or insert it if necessary
4536     if (addmenu.length) {
4537       var option = addmenu.children('option[value="'+col+'"]');
4538       if (option.length)
4539         option.prop('disabled', false);
4540       else
4541         option = $('<option>').attr('value', col).html(colprop.label).appendTo(addmenu);
4542       addmenu.show();
4543     }
4544   };
4545
4546   this.upload_contact_photo = function(form)
4547   {
4548     if (form && form.elements._photo.value) {
4549       this.async_upload_form(form, 'upload-photo', function(e) {
4550         rcmail.set_busy(false, null, rcmail.photo_upload_id);
4551       });
4552
4553       // display upload indicator
4554       this.photo_upload_id = this.set_busy(true, 'uploading');
4555     }
4556   };
4557
4558   this.replace_contact_photo = function(id)
4559   {
4560     var img_src = id == '-del-' ? this.env.photo_placeholder :
4561       this.env.comm_path + '&_action=photo&_source=' + this.env.source + '&_cid=' + this.env.cid + '&_photo=' + id;
4562
4563     this.set_photo_actions(id);
4564     $(this.gui_objects.contactphoto).children('img').attr('src', img_src);
4565   };
4566
4567   this.photo_upload_end = function()
4568   {
4569     this.set_busy(false, null, this.photo_upload_id);
4570     delete this.photo_upload_id;
4571   };
4572
4573   this.set_photo_actions = function(id)
4574   {
4575     var n, buttons = this.buttons['upload-photo'];
4576     for (n=0; buttons && n < buttons.length; n++)
4577       $('#'+buttons[n].id).html(this.get_label(id == '-del-' ? 'addphoto' : 'replacephoto'));
4578
4579     $('#ff_photo').val(id);
4580     this.enable_command('upload-photo', this.env.coltypes.photo ? true : false);
4581     this.enable_command('delete-photo', this.env.coltypes.photo && id != '-del-');
4582   };
4583
4584   // load advanced search page
4585   this.advanced_search = function()
4586   {
4587     var add_url = '&_form=1', target = window;
4588
4589     if (this.env.contentframe && window.frames && window.frames[this.env.contentframe]) {
4590       add_url += '&_framed=1';
4591       target = window.frames[this.env.contentframe];
4592       this.contact_list.clear_selection();
4593     }
4594
4595     this.location_href(this.env.comm_path+'&_action=search'+add_url, target, true);
4596
4597     return true;
4598   };
4599
4600   // unselect directory/group
4601   this.unselect_directory = function()
4602   {
4603     this.select_folder('');
4604     this.enable_command('search-delete', false);
4605   };
4606
4607   // callback for creating a new saved search record
4608   this.insert_saved_search = function(name, id)
4609   {
4610     this.reset_add_input();
4611
4612     var key = 'S'+id,
4613       link = $('<a>').attr('href', '#')
4614         .attr('rel', id)
4615         .click(function() { return rcmail.command('listsearch', id, this); })
4616         .html(name),
4617       li = $('<li>').attr({id: 'rcmli' + this.html_identifier(key), 'class': 'contactsearch'})
4618         .append(link),
4619       prop = {name:name, id:id, li:li[0]};
4620
4621     this.add_saved_search_row(prop, li);
4622     this.select_folder('S'+id);
4623     this.enable_command('search-delete', true);
4624     this.env.search_id = id;
4625
4626     this.triggerEvent('abook_search_insert', prop);
4627   };
4628
4629   // add saved search row to the list, with sorting
4630   this.add_saved_search_row = function(prop, li, reloc)
4631   {
4632     var row, sibling, name = prop.name.toUpperCase();
4633
4634     // When renaming groups, we need to remove it from DOM and insert it in the proper place
4635     if (reloc) {
4636       row = li.clone(true);
4637       li.remove();
4638     }
4639     else
4640       row = li;
4641
4642     $('li[class~="contactsearch"]', this.gui_objects.folderlist).each(function(i, elem) {
4643       if (!sibling)
4644         sibling = this.previousSibling;
4645
4646       if (name >= $(this).text().toUpperCase())
4647         sibling = elem;
4648       else
4649         return false;
4650     });
4651
4652     if (sibling)
4653       row.insertAfter(sibling);
4654     else
4655       row.appendTo(this.gui_objects.folderlist);
4656   };
4657
4658   // creates an input for saved search name
4659   this.search_create = function()
4660   {
4661     this.add_input_row('contactsearch');
4662   };
4663
4664   this.search_delete = function()
4665   {
4666     if (this.env.search_request) {
4667       var lock = this.set_busy(true, 'savedsearchdeleting');
4668       this.http_post('search-delete', '_sid='+urlencode(this.env.search_id), lock);
4669     }
4670   };
4671
4672   // callback from server upon search-delete command
4673   this.remove_search_item = function(id)
4674   {
4675     var li, key = 'S'+id;
4676     if ((li = this.get_folder_li(key))) {
4677       this.triggerEvent('search_delete', { id:id, li:li });
4678
4679       li.parentNode.removeChild(li);
4680     }
4681
4682     this.env.search_id = null;
4683     this.env.search_request = null;
4684     this.list_contacts_clear();
4685     this.reset_qsearch();
4686     this.enable_command('search-delete', 'search-create', false);
4687   };
4688
4689   this.listsearch = function(id)
4690   {
4691     var folder, lock = this.set_busy(true, 'searching');
4692
4693     if (this.contact_list) {
4694       this.list_contacts_clear();
4695     }
4696
4697     this.reset_qsearch();
4698     this.select_folder('S'+id);
4699
4700     // reset vars
4701     this.env.current_page = 1;
4702     this.http_request('search', '_sid='+urlencode(id), lock);
4703   };
4704
4705
4706   /*********************************************************/
4707   /*********        user settings methods          *********/
4708   /*********************************************************/
4709
4710   // preferences section select and load options frame
4711   this.section_select = function(list)
4712   {
4713     var id = list.get_single_selection(), add_url = '', target = window;
4714
4715     if (id) {
4716       if (this.env.contentframe && window.frames && window.frames[this.env.contentframe]) {
4717         add_url = '&_framed=1';
4718         target = window.frames[this.env.contentframe];
4719       }
4720       this.location_href(this.env.comm_path+'&_action=edit-prefs&_section='+id+add_url, target, true);
4721     }
4722
4723     return true;
4724   };
4725
4726   this.identity_select = function(list)
4727   {
4728     var id;
4729     if (id = list.get_single_selection())
4730       this.load_identity(id, 'edit-identity');
4731   };
4732
4733   // load identity record
4734   this.load_identity = function(id, action)
4735   {
4736     if (action=='edit-identity' && (!id || id==this.env.iid))
4737       return false;
4738
4739     var add_url = '', target = window;
4740
4741     if (this.env.contentframe && window.frames && window.frames[this.env.contentframe]) {
4742       add_url = '&_framed=1';
4743       target = window.frames[this.env.contentframe];
4744       document.getElementById(this.env.contentframe).style.visibility = 'inherit';
4745     }
4746
4747     if (action && (id || action=='add-identity')) {
4748       this.set_busy(true);
4749       this.location_href(this.env.comm_path+'&_action='+action+'&_iid='+id+add_url, target);
4750     }
4751
4752     return true;
4753   };
4754
4755   this.delete_identity = function(id)
4756   {
4757     // exit if no mailbox specified or if selection is empty
4758     var selection = this.identity_list.get_selection();
4759     if (!(selection.length || this.env.iid))
4760       return;
4761
4762     if (!id)
4763       id = this.env.iid ? this.env.iid : selection[0];
4764
4765     // append token to request
4766     this.goto_url('delete-identity', '_iid='+id+'&_token='+this.env.request_token, true);
4767
4768     return true;
4769   };
4770
4771
4772   /*********************************************************/
4773   /*********        folder manager methods         *********/
4774   /*********************************************************/
4775
4776   this.init_subscription_list = function()
4777   {
4778     var p = this;
4779     this.subscription_list = new rcube_list_widget(this.gui_objects.subscriptionlist,
4780       {multiselect:false, draggable:true, keyboard:false, toggleselect:true});
4781     this.subscription_list.addEventListener('select', function(o){ p.subscription_select(o); });
4782     this.subscription_list.addEventListener('dragstart', function(o){ p.drag_active = true; });
4783     this.subscription_list.addEventListener('dragend', function(o){ p.subscription_move_folder(o); });
4784     this.subscription_list.row_init = function (row) {
4785       row.obj.onmouseover = function() { p.focus_subscription(row.id); };
4786       row.obj.onmouseout = function() { p.unfocus_subscription(row.id); };
4787     };
4788     this.subscription_list.init();
4789     $('#mailboxroot')
4790       .mouseover(function(){ p.focus_subscription(this.id); })
4791       .mouseout(function(){ p.unfocus_subscription(this.id); })
4792   };
4793
4794   this.focus_subscription = function(id)
4795   {
4796     var row, folder,
4797       delim = RegExp.escape(this.env.delimiter),
4798       reg = RegExp('['+delim+']?[^'+delim+']+$');
4799
4800     if (this.drag_active && this.env.mailbox && (row = document.getElementById(id)))
4801       if (this.env.subscriptionrows[id] &&
4802           (folder = this.env.subscriptionrows[id][0]) !== null
4803       ) {
4804         if (this.check_droptarget(folder) &&
4805             !this.env.subscriptionrows[this.get_folder_row_id(this.env.mailbox)][2] &&
4806             (folder != this.env.mailbox.replace(reg, '')) &&
4807             (!folder.match(new RegExp('^'+RegExp.escape(this.env.mailbox+this.env.delimiter))))
4808         ) {
4809           this.env.dstfolder = folder;
4810           $(row).addClass('droptarget');
4811         }
4812       }
4813   };
4814
4815   this.unfocus_subscription = function(id)
4816   {
4817     var row = $('#'+id);
4818
4819     this.env.dstfolder = null;
4820     if (this.env.subscriptionrows[id] && row[0])
4821       row.removeClass('droptarget');
4822     else
4823       $(this.subscription_list.frame).removeClass('droptarget');
4824   };
4825
4826   this.subscription_select = function(list)
4827   {
4828     var id, folder;
4829
4830     if (list && (id = list.get_single_selection()) &&
4831         (folder = this.env.subscriptionrows['rcmrow'+id])
4832     ) {
4833       this.env.mailbox = folder[0];
4834       this.show_folder(folder[0]);
4835       this.enable_command('delete-folder', !folder[2]);
4836     }
4837     else {
4838       this.env.mailbox = null;
4839       this.show_contentframe(false);
4840       this.enable_command('delete-folder', 'purge', false);
4841     }
4842   };
4843
4844   this.subscription_move_folder = function(list)
4845   {
4846     var delim = RegExp.escape(this.env.delimiter),
4847       reg = RegExp('['+delim+']?[^'+delim+']+$');
4848
4849     if (this.env.mailbox && this.env.dstfolder !== null && (this.env.dstfolder != this.env.mailbox) &&
4850         (this.env.dstfolder != this.env.mailbox.replace(reg, ''))
4851     ) {
4852       reg = new RegExp('[^'+delim+']*['+delim+']', 'g');
4853       var basename = this.env.mailbox.replace(reg, ''),
4854         newname = this.env.dstfolder === '' ? basename : this.env.dstfolder+this.env.delimiter+basename;
4855
4856       if (newname != this.env.mailbox) {
4857         this.http_post('rename-folder', '_folder_oldname='+urlencode(this.env.mailbox)+'&_folder_newname='+urlencode(newname), this.set_busy(true, 'foldermoving'));
4858         this.subscription_list.draglayer.hide();
4859       }
4860     }
4861     this.drag_active = false;
4862     this.unfocus_subscription(this.get_folder_row_id(this.env.dstfolder));
4863   };
4864
4865   // tell server to create and subscribe a new mailbox
4866   this.create_folder = function()
4867   {
4868     this.show_folder('', this.env.mailbox);
4869   };
4870
4871   // delete a specific mailbox with all its messages
4872   this.delete_folder = function(name)
4873   {
4874     var id = this.get_folder_row_id(name ? name : this.env.mailbox),
4875       folder = this.env.subscriptionrows[id][0];
4876
4877     if (folder && confirm(this.get_label('deletefolderconfirm'))) {
4878       var lock = this.set_busy(true, 'folderdeleting');
4879       this.http_post('delete-folder', '_mbox='+urlencode(folder), lock);
4880     }
4881   };
4882
4883   // Add folder row to the table and initialize it
4884   this.add_folder_row = function (name, display_name, is_protected, subscribed, skip_init, class_name)
4885   {
4886     if (!this.gui_objects.subscriptionlist)
4887       return false;
4888
4889     var row, n, i, tmp, folders, rowid, list = [], slist = [],
4890       tbody = this.gui_objects.subscriptionlist.tBodies[0],
4891       refrow = $('tr', tbody).get(1),
4892       id = 'rcmrow'+((new Date).getTime());
4893
4894     if (!refrow) {
4895       // Refresh page if we don't have a table row to clone
4896       this.goto_url('folders');
4897       return false;
4898     }
4899
4900     // clone a table row if there are existing rows
4901     row = $(refrow).clone(true);
4902
4903     // set ID, reset css class
4904     row.attr('id', id);
4905     row.attr('class', class_name);
4906
4907     // set folder name
4908     row.find('td:first').html(display_name);
4909
4910     // update subscription checkbox
4911     $('input[name="_subscribed[]"]', row).val(name)
4912       .prop({checked: subscribed ? true : false, disabled: is_protected ? true : false});
4913
4914     // add to folder/row-ID map
4915     this.env.subscriptionrows[id] = [name, display_name, 0];
4916
4917     // sort folders, to find a place where to insert the row
4918     folders = [];
4919     $.each(this.env.subscriptionrows, function(k,v){ folders.push(v) });
4920     folders.sort(function(a,b){ return a[0] < b[0] ? -1 : (a[0] > b[0] ? 1 : 0) });
4921
4922     for (n in folders) {
4923       // protected folder
4924       if (folders[n][2]) {
4925         slist.push(folders[n][0]);
4926         tmp = folders[n][0]+this.env.delimiter;
4927       }
4928       // protected folder's child
4929       else if (tmp && folders[n][0].indexOf(tmp) == 0)
4930         slist.push(folders[n][0]);
4931       // other
4932       else {
4933         list.push(folders[n][0]);
4934         tmp = null;
4935       }
4936     }
4937
4938     // check if subfolder of a protected folder
4939     for (n=0; n<slist.length; n++) {
4940       if (name.indexOf(slist[n]+this.env.delimiter) == 0)
4941         rowid = this.get_folder_row_id(slist[n]);
4942     }
4943
4944     // find folder position after sorting
4945     for (n=0; !rowid && n<list.length; n++) {
4946       if (n && list[n] == name)
4947         rowid = this.get_folder_row_id(list[n-1]);
4948     }
4949
4950     // add row to the table
4951     if (rowid)
4952       $('#'+rowid).after(row);
4953     else
4954       row.appendTo(tbody);
4955
4956     // update list widget
4957     this.subscription_list.clear_selection();
4958     if (!skip_init)
4959       this.init_subscription_list();
4960
4961     row = row.get(0);
4962     if (row.scrollIntoView)
4963       row.scrollIntoView();
4964
4965     return row;
4966   };
4967
4968   // replace an existing table row with a new folder line (with subfolders)
4969   this.replace_folder_row = function(oldfolder, newfolder, display_name, is_protected, class_name)
4970   {
4971     if (!this.gui_objects.subscriptionlist)
4972       return false;
4973
4974     var i, n, len, name, dispname, oldrow, tmprow, row, level,
4975       tbody = this.gui_objects.subscriptionlist.tBodies[0],
4976       folders = this.env.subscriptionrows,
4977       id = this.get_folder_row_id(oldfolder),
4978       regex = new RegExp('^'+RegExp.escape(oldfolder)),
4979       subscribed = $('input[name="_subscribed[]"]', $('#'+id)).prop('checked'),
4980       // find subfolders of renamed folder
4981       list = this.get_subfolders(oldfolder);
4982
4983     // replace an existing table row
4984     this._remove_folder_row(id);
4985     row = $(this.add_folder_row(newfolder, display_name, is_protected, subscribed, true, class_name));
4986
4987     // detect tree depth change
4988     if (len = list.length) {
4989       level = (oldfolder.split(this.env.delimiter)).length - (newfolder.split(this.env.delimiter)).length;
4990     }
4991
4992     // move subfolders to the new branch
4993     for (n=0; n<len; n++) {
4994       id = list[n];
4995       name = this.env.subscriptionrows[id][0];
4996       dispname = this.env.subscriptionrows[id][1];
4997       oldrow = $('#'+id);
4998       tmprow = oldrow.clone(true);
4999       oldrow.remove();
5000       row.after(tmprow);
5001       row = tmprow;
5002       // update folder index
5003       name = name.replace(regex, newfolder);
5004       $('input[name="_subscribed[]"]', row).val(name);
5005       this.env.subscriptionrows[id][0] = name;
5006       // update the name if level is changed
5007       if (level != 0) {
5008         if (level > 0) {
5009           for (i=level; i>0; i--)
5010             dispname = dispname.replace(/^&nbsp;&nbsp;&nbsp;&nbsp;/, '');
5011         }
5012         else {
5013           for (i=level; i<0; i++)
5014             dispname = '&nbsp;&nbsp;&nbsp;&nbsp;' + dispname;
5015         }
5016         row.find('td:first').html(dispname);
5017         this.env.subscriptionrows[id][1] = dispname;
5018       }
5019     }
5020
5021     // update list widget
5022     this.init_subscription_list();
5023   };
5024
5025   // remove the table row of a specific mailbox from the table
5026   this.remove_folder_row = function(folder, subs)
5027   {
5028     var n, len, list = [], id = this.get_folder_row_id(folder);
5029
5030     // get subfolders if any
5031     if (subs)
5032       list = this.get_subfolders(folder);
5033
5034     // remove old row
5035     this._remove_folder_row(id);
5036
5037     // remove subfolders
5038     for (n=0, len=list.length; n<len; n++)
5039       this._remove_folder_row(list[n]);
5040   };
5041
5042   this._remove_folder_row = function(id)
5043   {
5044     this.subscription_list.remove_row(id.replace(/^rcmrow/, ''));
5045     $('#'+id).remove();
5046     delete this.env.subscriptionrows[id];
5047   }
5048
5049   this.get_subfolders = function(folder)
5050   {
5051     var name, list = [],
5052       regex = new RegExp('^'+RegExp.escape(folder)+RegExp.escape(this.env.delimiter)),
5053       row = $('#'+this.get_folder_row_id(folder)).get(0);
5054
5055     while (row = row.nextSibling) {
5056       if (row.id) {
5057         name = this.env.subscriptionrows[row.id][0];
5058         if (regex.test(name)) {
5059           list.push(row.id);
5060         }
5061         else
5062           break;
5063       }
5064     }
5065
5066     return list;
5067   }
5068
5069   this.subscribe = function(folder)
5070   {
5071     if (folder) {
5072       var lock = this.display_message(this.get_label('foldersubscribing'), 'loading');
5073       this.http_post('subscribe', '_mbox='+urlencode(folder), lock);
5074     }
5075   };
5076
5077   this.unsubscribe = function(folder)
5078   {
5079     if (folder) {
5080       var lock = this.display_message(this.get_label('folderunsubscribing'), 'loading');
5081       this.http_post('unsubscribe', '_mbox='+urlencode(folder), lock);
5082     }
5083   };
5084
5085   // helper method to find a specific mailbox row ID
5086   this.get_folder_row_id = function(folder)
5087   {
5088     var id, folders = this.env.subscriptionrows;
5089     for (id in folders)
5090       if (folders[id] && folders[id][0] == folder)
5091         break;
5092
5093     return id;
5094   };
5095
5096   // when user select a folder in manager
5097   this.show_folder = function(folder, path, force)
5098   {
5099     var target = window,
5100       url = '&_action=edit-folder&_mbox='+urlencode(folder);
5101
5102     if (path)
5103       url += '&_path='+urlencode(path);
5104
5105     if (this.env.contentframe && window.frames && window.frames[this.env.contentframe]) {
5106       target = window.frames[this.env.contentframe];
5107       url += '&_framed=1';
5108     }
5109
5110     if (String(target.location.href).indexOf(url) >= 0 && !force) {
5111       this.show_contentframe(true);
5112     }
5113     else {
5114       this.location_href(this.env.comm_path+url, target, true);
5115     }
5116   };
5117
5118   // disables subscription checkbox (for protected folder)
5119   this.disable_subscription = function(folder)
5120   {
5121     var id = this.get_folder_row_id(folder);
5122     if (id)
5123       $('input[name="_subscribed[]"]', $('#'+id)).prop('disabled', true);
5124   };
5125
5126   this.folder_size = function(folder)
5127   {
5128     var lock = this.set_busy(true, 'loading');
5129     this.http_post('folder-size', '_mbox='+urlencode(folder), lock);
5130   };
5131
5132   this.folder_size_update = function(size)
5133   {
5134     $('#folder-size').replaceWith(size);
5135   };
5136
5137
5138   /*********************************************************/
5139   /*********           GUI functionality           *********/
5140   /*********************************************************/
5141
5142   var init_button = function(cmd, prop)
5143   {
5144     var elm = document.getElementById(prop.id);
5145     if (!elm)
5146       return;
5147
5148     var preload = false;
5149     if (prop.type == 'image') {
5150       elm = elm.parentNode;
5151       preload = true;
5152     }
5153
5154     elm._command = cmd;
5155     elm._id = prop.id;
5156     if (prop.sel) {
5157       elm.onmousedown = function(e){ return rcmail.button_sel(this._command, this._id); };
5158       elm.onmouseup = function(e){ return rcmail.button_out(this._command, this._id); };
5159       if (preload)
5160         new Image().src = prop.sel;
5161     }
5162     if (prop.over) {
5163       elm.onmouseover = function(e){ return rcmail.button_over(this._command, this._id); };
5164       elm.onmouseout = function(e){ return rcmail.button_out(this._command, this._id); };
5165       if (preload)
5166         new Image().src = prop.over;
5167     }
5168   };
5169
5170   // enable/disable buttons for page shifting
5171   this.set_page_buttons = function()
5172   {
5173     this.enable_command('nextpage', 'lastpage', (this.env.pagecount > this.env.current_page));
5174     this.enable_command('previouspage', 'firstpage', (this.env.current_page > 1));
5175   };
5176
5177   // set event handlers on registered buttons
5178   this.init_buttons = function()
5179   {
5180     for (var cmd in this.buttons) {
5181       if (typeof cmd !== 'string')
5182         continue;
5183
5184       for (var i=0; i< this.buttons[cmd].length; i++) {
5185         init_button(cmd, this.buttons[cmd][i]);
5186       }
5187     }
5188
5189     // set active task button
5190     this.set_button(this.task, 'sel');
5191   };
5192
5193   // set button to a specific state
5194   this.set_button = function(command, state)
5195   {
5196     var n, button, obj, a_buttons = this.buttons[command],
5197       len = a_buttons ? a_buttons.length : 0;
5198
5199     for (n=0; n<len; n++) {
5200       button = a_buttons[n];
5201       obj = document.getElementById(button.id);
5202
5203       // get default/passive setting of the button
5204       if (obj && button.type=='image' && !button.status) {
5205         button.pas = obj._original_src ? obj._original_src : obj.src;
5206         // respect PNG fix on IE browsers
5207         if (obj.runtimeStyle && obj.runtimeStyle.filter && obj.runtimeStyle.filter.match(/src=['"]([^'"]+)['"]/))
5208           button.pas = RegExp.$1;
5209       }
5210       else if (obj && !button.status)
5211         button.pas = String(obj.className);
5212
5213       // set image according to button state
5214       if (obj && button.type=='image' && button[state]) {
5215         button.status = state;
5216         obj.src = button[state];
5217       }
5218       // set class name according to button state
5219       else if (obj && button[state] !== undefined) {
5220         button.status = state;
5221         obj.className = button[state];
5222       }
5223       // disable/enable input buttons
5224       if (obj && button.type=='input') {
5225         button.status = state;
5226         obj.disabled = !state;
5227       }
5228     }
5229   };
5230
5231   // display a specific alttext
5232   this.set_alttext = function(command, label)
5233   {
5234     var n, button, obj, link, a_buttons = this.buttons[command],
5235       len = a_buttons ? a_buttons.length : 0;
5236
5237     for (n=0; n<len; n++) {
5238       button = a_buttons[n];
5239       obj = document.getElementById(button.id);
5240
5241       if (button.type == 'image' && obj) {
5242         obj.setAttribute('alt', this.get_label(label));
5243         if ((link = obj.parentNode) && link.tagName.toLowerCase() == 'a')
5244           link.setAttribute('title', this.get_label(label));
5245       }
5246       else if (obj)
5247         obj.setAttribute('title', this.get_label(label));
5248     }
5249   };
5250
5251   // mouse over button
5252   this.button_over = function(command, id)
5253   {
5254     var n, button, obj, a_buttons = this.buttons[command],
5255       len = a_buttons ? a_buttons.length : 0;
5256
5257     for (n=0; n<len; n++) {
5258       button = a_buttons[n];
5259       if (button.id == id && button.status == 'act') {
5260         obj = document.getElementById(button.id);
5261         if (obj && button.over) {
5262           if (button.type == 'image')
5263             obj.src = button.over;
5264           else
5265             obj.className = button.over;
5266         }
5267       }
5268     }
5269   };
5270
5271   // mouse down on button
5272   this.button_sel = function(command, id)
5273   {
5274     var n, button, obj, a_buttons = this.buttons[command],
5275       len = a_buttons ? a_buttons.length : 0;
5276
5277     for (n=0; n<len; n++) {
5278       button = a_buttons[n];
5279       if (button.id == id && button.status == 'act') {
5280         obj = document.getElementById(button.id);
5281         if (obj && button.sel) {
5282           if (button.type == 'image')
5283             obj.src = button.sel;
5284           else
5285             obj.className = button.sel;
5286         }
5287         this.buttons_sel[id] = command;
5288       }
5289     }
5290   };
5291
5292   // mouse out of button
5293   this.button_out = function(command, id)
5294   {
5295     var n, button, obj, a_buttons = this.buttons[command],
5296       len = a_buttons ? a_buttons.length : 0;
5297
5298     for (n=0; n<len; n++) {
5299       button = a_buttons[n];
5300       if (button.id == id && button.status == 'act') {
5301         obj = document.getElementById(button.id);
5302         if (obj && button.act) {
5303           if (button.type == 'image')
5304             obj.src = button.act;
5305           else
5306             obj.className = button.act;
5307         }
5308       }
5309     }
5310   };
5311
5312   this.focus_textfield = function(elem)
5313   {
5314     elem._hasfocus = true;
5315     var $elem = $(elem);
5316     if ($elem.hasClass('placeholder') || $elem.val() == elem._placeholder)
5317       $elem.val('').removeClass('placeholder').attr('spellcheck', true);
5318   };
5319
5320   this.blur_textfield = function(elem)
5321   {
5322     elem._hasfocus = false;
5323     var $elem = $(elem);
5324     if (elem._placeholder && (!$elem.val() || $elem.val() == elem._placeholder))
5325       $elem.addClass('placeholder').attr('spellcheck', false).val(elem._placeholder);
5326   };
5327
5328   // write to the document/window title
5329   this.set_pagetitle = function(title)
5330   {
5331     if (title && document.title)
5332       document.title = title;
5333   };
5334
5335   // display a system message, list of types in common.css (below #message definition)
5336   this.display_message = function(msg, type, timeout)
5337   {
5338     // pass command to parent window
5339     if (this.is_framed())
5340       return parent.rcmail.display_message(msg, type, timeout);
5341
5342     if (!this.gui_objects.message) {
5343       // save message in order to display after page loaded
5344       if (type != 'loading')
5345         this.pending_message = [msg, type, timeout];
5346       return false;
5347     }
5348
5349     type = type ? type : 'notice';
5350
5351     var ref = this,
5352       key = this.html_identifier(msg),
5353       date = new Date(),
5354       id = type + date.getTime();
5355
5356     if (!timeout)
5357       timeout = this.message_time * (type == 'error' || type == 'warning' ? 2 : 1);
5358
5359     if (type == 'loading') {
5360       key = 'loading';
5361       timeout = this.env.request_timeout * 1000;
5362       if (!msg)
5363         msg = this.get_label('loading');
5364     }
5365
5366     // The same message is already displayed
5367     if (this.messages[key]) {
5368       // replace label
5369       if (this.messages[key].obj)
5370         this.messages[key].obj.html(msg);
5371       // store label in stack
5372       if (type == 'loading') {
5373         this.messages[key].labels.push({'id': id, 'msg': msg});
5374       }
5375       // add element and set timeout
5376       this.messages[key].elements.push(id);
5377       window.setTimeout(function() { ref.hide_message(id, type == 'loading'); }, timeout);
5378       return id;
5379     }
5380
5381     // create DOM object and display it
5382     var obj = $('<div>').addClass(type).html(msg).data('key', key),
5383       cont = $(this.gui_objects.message).append(obj).show();
5384
5385     this.messages[key] = {'obj': obj, 'elements': [id]};
5386
5387     if (type == 'loading') {
5388       this.messages[key].labels = [{'id': id, 'msg': msg}];
5389     }
5390     else {
5391       obj.click(function() { return ref.hide_message(obj); });
5392     }
5393
5394     if (timeout > 0)
5395       window.setTimeout(function() { ref.hide_message(id, type == 'loading'); }, timeout);
5396     return id;
5397   };
5398
5399   // make a message to disapear
5400   this.hide_message = function(obj, fade)
5401   {
5402     // pass command to parent window
5403     if (this.is_framed())
5404       return parent.rcmail.hide_message(obj, fade);
5405
5406     var k, n, i, msg, m = this.messages;
5407
5408     // Hide message by object, don't use for 'loading'!
5409     if (typeof obj === 'object') {
5410       $(obj)[fade?'fadeOut':'hide']();
5411       msg = $(obj).data('key');
5412       if (this.messages[msg])
5413         delete this.messages[msg];
5414     }
5415     // Hide message by id
5416     else {
5417       for (k in m) {
5418         for (n in m[k].elements) {
5419           if (m[k] && m[k].elements[n] == obj) {
5420             m[k].elements.splice(n, 1);
5421             // hide DOM element if last instance is removed
5422             if (!m[k].elements.length) {
5423               m[k].obj[fade?'fadeOut':'hide']();
5424               delete m[k];
5425             }
5426             // set pending action label for 'loading' message
5427             else if (k == 'loading') {
5428               for (i in m[k].labels) {
5429                 if (m[k].labels[i].id == obj) {
5430                   delete m[k].labels[i];
5431                 }
5432                 else {
5433                   msg = m[k].labels[i].msg;
5434                 }
5435                 m[k].obj.html(msg);
5436               }
5437             }
5438           }
5439         }
5440       }
5441     }
5442   };
5443
5444   // mark a mailbox as selected and set environment variable
5445   this.select_folder = function(name, prefix, encode)
5446   {
5447     if (this.gui_objects.folderlist) {
5448       var current_li, target_li;
5449
5450       if ((current_li = $('li.selected', this.gui_objects.folderlist))) {
5451         current_li.removeClass('selected').addClass('unfocused');
5452       }
5453       if ((target_li = this.get_folder_li(name, prefix, encode))) {
5454         $(target_li).removeClass('unfocused').addClass('selected');
5455       }
5456
5457       // trigger event hook
5458       this.triggerEvent('selectfolder', { folder:name, prefix:prefix });
5459     }
5460   };
5461
5462   // helper method to find a folder list item
5463   this.get_folder_li = function(name, prefix, encode)
5464   {
5465     if (!prefix)
5466       prefix = 'rcmli';
5467
5468     if (this.gui_objects.folderlist) {
5469       name = this.html_identifier(name, encode);
5470       return document.getElementById(prefix+name);
5471     }
5472
5473     return null;
5474   };
5475
5476   // for reordering column array (Konqueror workaround)
5477   // and for setting some message list global variables
5478   this.set_message_coltypes = function(coltypes, repl)
5479   {
5480     var list = this.message_list,
5481       thead = list ? list.list.tHead : null,
5482       cell, col, n, len, th, tr;
5483
5484     this.env.coltypes = coltypes;
5485
5486     // replace old column headers
5487     if (thead) {
5488       if (repl) {
5489         th = document.createElement('thead');
5490         tr = document.createElement('tr');
5491
5492         for (c=0, len=repl.length; c < len; c++) {
5493           cell = document.createElement('td');
5494           cell.innerHTML = repl[c].html;
5495           if (repl[c].id) cell.id = repl[c].id;
5496           if (repl[c].className) cell.className = repl[c].className;
5497           tr.appendChild(cell);
5498         }
5499         th.appendChild(tr);
5500         thead.parentNode.replaceChild(th, thead);
5501         thead = th;
5502       }
5503
5504       for (n=0, len=this.env.coltypes.length; n<len; n++) {
5505         col = this.env.coltypes[n];
5506         if ((cell = thead.rows[0].cells[n]) && (col=='from' || col=='to')) {
5507           cell.id = 'rcm'+col;
5508           // if we have links for sorting, it's a bit more complicated...
5509           if (cell.firstChild && cell.firstChild.tagName.toLowerCase()=='a') {
5510             cell = cell.firstChild;
5511             cell.onclick = function(){ return rcmail.command('sort', this.__col, this); };
5512             cell.__col = col;
5513           }
5514           cell.innerHTML = this.get_label(col);
5515         }
5516       }
5517     }
5518
5519     this.env.subject_col = null;
5520     this.env.flagged_col = null;
5521     this.env.status_col = null;
5522
5523     if ((n = $.inArray('subject', this.env.coltypes)) >= 0) {
5524       this.env.subject_col = n;
5525       if (list)
5526         list.subject_col = n;
5527     }
5528     if ((n = $.inArray('flag', this.env.coltypes)) >= 0)
5529       this.env.flagged_col = n;
5530     if ((n = $.inArray('status', this.env.coltypes)) >= 0)
5531       this.env.status_col = n;
5532
5533     if (list)
5534       list.init_header();
5535   };
5536
5537   // replace content of row count display
5538   this.set_rowcount = function(text, mbox)
5539   {
5540     // #1487752
5541     if (mbox && mbox != this.env.mailbox)
5542       return false;
5543
5544     $(this.gui_objects.countdisplay).html(text);
5545
5546     // update page navigation buttons
5547     this.set_page_buttons();
5548   };
5549
5550   // replace content of mailboxname display
5551   this.set_mailboxname = function(content)
5552   {
5553     if (this.gui_objects.mailboxname && content)
5554       this.gui_objects.mailboxname.innerHTML = content;
5555   };
5556
5557   // replace content of quota display
5558   this.set_quota = function(content)
5559   {
5560     if (content && this.gui_objects.quotadisplay) {
5561       if (typeof content === 'object' && content.type == 'image')
5562         this.percent_indicator(this.gui_objects.quotadisplay, content);
5563       else
5564         $(this.gui_objects.quotadisplay).html(content);
5565     }
5566   };
5567
5568   // update the mailboxlist
5569   this.set_unread_count = function(mbox, count, set_title)
5570   {
5571     if (!this.gui_objects.mailboxlist)
5572       return false;
5573
5574     this.env.unread_counts[mbox] = count;
5575     this.set_unread_count_display(mbox, set_title);
5576   };
5577
5578   // update the mailbox count display
5579   this.set_unread_count_display = function(mbox, set_title)
5580   {
5581     var reg, link, text_obj, item, mycount, childcount, div;
5582
5583     if (item = this.get_folder_li(mbox, '', true)) {
5584       mycount = this.env.unread_counts[mbox] ? this.env.unread_counts[mbox] : 0;
5585       link = $(item).children('a').eq(0);
5586       text_obj = link.children('span.unreadcount');
5587       if (!text_obj.length && mycount)
5588         text_obj = $('<span>').addClass('unreadcount').appendTo(link);
5589       reg = /\s+\([0-9]+\)$/i;
5590
5591       childcount = 0;
5592       if ((div = item.getElementsByTagName('div')[0]) &&
5593           div.className.match(/collapsed/)) {
5594         // add children's counters
5595         for (var k in this.env.unread_counts)
5596           if (k.indexOf(mbox + this.env.delimiter) == 0)
5597             childcount += this.env.unread_counts[k];
5598       }
5599
5600       if (mycount && text_obj.length)
5601         text_obj.html(' ('+mycount+')');
5602       else if (text_obj.length)
5603         text_obj.remove();
5604
5605       // set parent's display
5606       reg = new RegExp(RegExp.escape(this.env.delimiter) + '[^' + RegExp.escape(this.env.delimiter) + ']+$');
5607       if (mbox.match(reg))
5608         this.set_unread_count_display(mbox.replace(reg, ''), false);
5609
5610       // set the right classes
5611       if ((mycount+childcount)>0)
5612         $(item).addClass('unread');
5613       else
5614         $(item).removeClass('unread');
5615     }
5616
5617     // set unread count to window title
5618     reg = /^\([0-9]+\)\s+/i;
5619     if (set_title && document.title) {
5620       var new_title = '',
5621         doc_title = String(document.title);
5622
5623       if (mycount && doc_title.match(reg))
5624         new_title = doc_title.replace(reg, '('+mycount+') ');
5625       else if (mycount)
5626         new_title = '('+mycount+') '+doc_title;
5627       else
5628         new_title = doc_title.replace(reg, '');
5629
5630       this.set_pagetitle(new_title);
5631     }
5632   };
5633
5634   this.toggle_prefer_html = function(checkbox)
5635   {
5636     $('#rcmfd_show_images').prop('disabled', !checkbox.checked).val(0);
5637   };
5638
5639   this.toggle_preview_pane = function(checkbox)
5640   {
5641     $('#rcmfd_preview_pane_mark_read').prop('disabled', !checkbox.checked);
5642   };
5643
5644   // display fetched raw headers
5645   this.set_headers = function(content)
5646   {
5647     if (this.gui_objects.all_headers_row && this.gui_objects.all_headers_box && content)
5648       $(this.gui_objects.all_headers_box).html(content).show();
5649   };
5650
5651   // display all-headers row and fetch raw message headers
5652   this.load_headers = function(elem)
5653   {
5654     if (!this.gui_objects.all_headers_row || !this.gui_objects.all_headers_box || !this.env.uid)
5655       return;
5656
5657     $(elem).removeClass('show-headers').addClass('hide-headers');
5658     $(this.gui_objects.all_headers_row).show();
5659     elem.onclick = function() { rcmail.hide_headers(elem); };
5660
5661     // fetch headers only once
5662     if (!this.gui_objects.all_headers_box.innerHTML) {
5663       var lock = this.display_message(this.get_label('loading'), 'loading');
5664       this.http_post('headers', '_uid='+this.env.uid, lock);
5665     }
5666   };
5667
5668   // hide all-headers row
5669   this.hide_headers = function(elem)
5670   {
5671     if (!this.gui_objects.all_headers_row || !this.gui_objects.all_headers_box)
5672       return;
5673
5674     $(elem).removeClass('hide-headers').addClass('show-headers');
5675     $(this.gui_objects.all_headers_row).hide();
5676     elem.onclick = function() { rcmail.load_headers(elem); };
5677   };
5678
5679   // percent (quota) indicator
5680   this.percent_indicator = function(obj, data)
5681   {
5682     if (!data || !obj)
5683       return false;
5684
5685     var limit_high = 80,
5686       limit_mid  = 55,
5687       width = data.width ? data.width : this.env.indicator_width ? this.env.indicator_width : 100,
5688       height = data.height ? data.height : this.env.indicator_height ? this.env.indicator_height : 14,
5689       quota = data.percent ? Math.abs(parseInt(data.percent)) : 0,
5690       quota_width = parseInt(quota / 100 * width),
5691       pos = $(obj).position();
5692
5693     // workarounds for Opera and Webkit bugs
5694     pos.top = Math.max(0, pos.top);
5695     pos.left = Math.max(0, pos.left);
5696
5697     this.env.indicator_width = width;
5698     this.env.indicator_height = height;
5699
5700     // overlimit
5701     if (quota_width > width) {
5702       quota_width = width;
5703       quota = 100; 
5704     }
5705
5706     if (data.title)
5707       data.title = this.get_label('quota') + ': ' +  data.title;
5708
5709     // main div
5710     var main = $('<div>');
5711     main.css({position: 'absolute', top: pos.top, left: pos.left,
5712             width: width + 'px', height: height + 'px', zIndex: 100, lineHeight: height + 'px'})
5713           .attr('title', data.title).addClass('quota_text').html(quota + '%');
5714     // used bar
5715     var bar1 = $('<div>');
5716     bar1.css({position: 'absolute', top: pos.top + 1, left: pos.left + 1,
5717             width: quota_width + 'px', height: height + 'px', zIndex: 99});
5718     // background
5719     var bar2 = $('<div>');
5720     bar2.css({position: 'absolute', top: pos.top + 1, left: pos.left + 1,
5721             width: width + 'px', height: height + 'px', zIndex: 98})
5722           .addClass('quota_bg');
5723
5724     if (quota >= limit_high) {
5725       main.addClass(' quota_text_high');
5726       bar1.addClass('quota_high');
5727     }
5728     else if(quota >= limit_mid) {
5729       main.addClass(' quota_text_mid');
5730       bar1.addClass('quota_mid');
5731     }
5732     else {
5733       main.addClass(' quota_text_low');
5734       bar1.addClass('quota_low');
5735     }
5736
5737     // replace quota image
5738     $(obj).html('').append(bar1).append(bar2).append(main);
5739     // update #quotaimg title
5740     $('#quotaimg').attr('title', data.title);
5741   };
5742
5743   /********************************************************/
5744   /*********  html to text conversion functions   *********/
5745   /********************************************************/
5746
5747   this.html2plain = function(htmlText, id)
5748   {
5749     var rcmail = this,
5750       url = '?_task=utils&_action=html2text',
5751       lock = this.set_busy(true, 'converting');
5752
5753     this.log('HTTP POST: ' + url);
5754
5755     $.ajax({ type: 'POST', url: url, data: htmlText, contentType: 'application/octet-stream',
5756       error: function(o, status, err) { rcmail.http_error(o, status, err, lock); },
5757       success: function(data) { rcmail.set_busy(false, null, lock); $('#'+id).val(data); rcmail.log(data); }
5758     });
5759   };
5760
5761   this.plain2html = function(plain, id)
5762   {
5763     var lock = this.set_busy(true, 'converting');
5764
5765     plain = plain.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
5766     $('#'+id).val(plain ? '<pre>'+plain+'</pre>' : '');
5767
5768     this.set_busy(false, null, lock);
5769   };
5770
5771
5772   /********************************************************/
5773   /*********        remote request methods        *********/
5774   /********************************************************/
5775
5776   // compose a valid url with the given parameters
5777   this.url = function(action, query)
5778   {
5779     var querystring = typeof query === 'string' ? '&' + query : '';
5780
5781     if (typeof action !== 'string')
5782       query = action;
5783     else if (!query || typeof query !== 'object')
5784       query = {};
5785
5786     if (action)
5787       query._action = action;
5788     else
5789       query._action = this.env.action;
5790
5791     var base = this.env.comm_path;
5792
5793     // overwrite task name
5794     if (query._action.match(/([a-z]+)\/([a-z0-9-_.]+)/)) {
5795       query._action = RegExp.$2;
5796       base = base.replace(/\_task=[a-z]+/, '_task='+RegExp.$1);
5797     }
5798
5799     // remove undefined values
5800     var param = {};
5801     for (var k in query) {
5802       if (query[k] !== undefined && query[k] !== null)
5803         param[k] = query[k];
5804     }
5805
5806     return base + '&' + $.param(param) + querystring;
5807   };
5808
5809   this.redirect = function(url, lock)
5810   {
5811     if (lock || lock === null)
5812       this.set_busy(true);
5813
5814     if (this.is_framed())
5815       parent.rcmail.redirect(url, lock);
5816     else
5817       this.location_href(url, window);
5818   };
5819
5820   this.goto_url = function(action, query, lock)
5821   {
5822     this.redirect(this.url(action, query));
5823   };
5824
5825   this.location_href = function(url, target, frame)
5826   {
5827     if (frame)
5828       this.lock_frame();
5829
5830     // simulate real link click to force IE to send referer header
5831     if (bw.ie && target == window)
5832       $('<a>').attr('href', url).appendTo(document.body).get(0).click();
5833     else
5834       target.location.href = url;
5835   };
5836
5837   // send a http request to the server
5838   this.http_request = function(action, query, lock)
5839   {
5840     var url = this.url(action, query);
5841
5842     // trigger plugin hook
5843     var result = this.triggerEvent('request'+action, query);
5844
5845     if (result !== undefined) {
5846       // abort if one the handlers returned false
5847       if (result === false)
5848         return false;
5849       else
5850         query = result;
5851     }
5852
5853     url += '&_remote=1';
5854
5855     // send request
5856     this.log('HTTP GET: ' + url);
5857
5858     return $.ajax({
5859       type: 'GET', url: url, data: { _unlock:(lock?lock:0) }, dataType: 'json',
5860       success: function(data){ ref.http_response(data); },
5861       error: function(o, status, err) { rcmail.http_error(o, status, err, lock); }
5862     });
5863   };
5864
5865   // send a http POST request to the server
5866   this.http_post = function(action, postdata, lock)
5867   {
5868     var url = this.url(action);
5869
5870     if (postdata && typeof postdata === 'object') {
5871       postdata._remote = 1;
5872       postdata._unlock = (lock ? lock : 0);
5873     }
5874     else
5875       postdata += (postdata ? '&' : '') + '_remote=1' + (lock ? '&_unlock='+lock : '');
5876
5877     // trigger plugin hook
5878     var result = this.triggerEvent('request'+action, postdata);
5879     if (result !== undefined) {
5880       // abort if one the handlers returned false
5881       if (result === false)
5882         return false;
5883       else
5884         postdata = result;
5885     }
5886
5887     // send request
5888     this.log('HTTP POST: ' + url);
5889
5890     return $.ajax({
5891       type: 'POST', url: url, data: postdata, dataType: 'json',
5892       success: function(data){ ref.http_response(data); },
5893       error: function(o, status, err) { rcmail.http_error(o, status, err, lock); }
5894     });
5895   };
5896
5897   // aborts ajax request
5898   this.abort_request = function(r)
5899   {
5900     if (r.request)
5901       r.request.abort();
5902     if (r.lock)
5903       this.set_busy(false, null, r.lock);
5904   };
5905
5906   // handle HTTP response
5907   this.http_response = function(response)
5908   {
5909     if (!response)
5910       return;
5911
5912     if (response.unlock)
5913       this.set_busy(false);
5914
5915     this.triggerEvent('responsebefore', {response: response});
5916     this.triggerEvent('responsebefore'+response.action, {response: response});
5917
5918     // set env vars
5919     if (response.env)
5920       this.set_env(response.env);
5921
5922     // we have labels to add
5923     if (typeof response.texts === 'object') {
5924       for (var name in response.texts)
5925         if (typeof response.texts[name] === 'string')
5926           this.add_label(name, response.texts[name]);
5927     }
5928
5929     // if we get javascript code from server -> execute it
5930     if (response.exec) {
5931       this.log(response.exec);
5932       eval(response.exec);
5933     }
5934
5935     // execute callback functions of plugins
5936     if (response.callbacks && response.callbacks.length) {
5937       for (var i=0; i < response.callbacks.length; i++)
5938         this.triggerEvent(response.callbacks[i][0], response.callbacks[i][1]);
5939     }
5940
5941     // process the response data according to the sent action
5942     switch (response.action) {
5943       case 'delete':
5944         if (this.task == 'addressbook') {
5945           var sid, uid = this.contact_list.get_selection(), writable = false;
5946
5947           if (uid && this.contact_list.rows[uid]) {
5948             // search results, get source ID from record ID
5949             if (this.env.source == '') {
5950               sid = String(uid).replace(/^[^-]+-/, '');
5951               writable = sid && this.env.address_sources[sid] && !this.env.address_sources[sid].readonly;
5952             }
5953             else {
5954               writable = !this.env.address_sources[this.env.source].readonly;
5955             }
5956           }
5957           this.enable_command('compose', (uid && this.contact_list.rows[uid]));
5958           this.enable_command('delete', 'edit', writable);
5959           this.enable_command('export', (this.contact_list && this.contact_list.rowcount > 0));
5960         }
5961
5962       case 'moveto':
5963         if (this.env.action == 'show') {
5964           // re-enable commands on move/delete error
5965           this.enable_command(this.env.message_commands, true);
5966           if (!this.env.list_post)
5967             this.enable_command('reply-list', false);
5968         }
5969         else if (this.task == 'addressbook') {
5970           this.triggerEvent('listupdate', { folder:this.env.source, rowcount:this.contact_list.rowcount });
5971         }
5972
5973       case 'purge':
5974       case 'expunge':
5975         if (this.task == 'mail') {
5976           if (!this.env.messagecount) {
5977             // clear preview pane content
5978             if (this.env.contentframe)
5979               this.show_contentframe(false);
5980             // disable commands useless when mailbox is empty
5981             this.enable_command(this.env.message_commands, 'purge', 'expunge',
5982               'select-all', 'select-none', 'sort', 'expand-all', 'expand-unread', 'collapse-all', false);
5983           }
5984           if (this.message_list)
5985             this.triggerEvent('listupdate', { folder:this.env.mailbox, rowcount:this.message_list.rowcount });
5986         }
5987         break;
5988
5989       case 'check-recent':
5990       case 'getunread':
5991       case 'search':
5992         this.env.qsearch = null;
5993       case 'list':
5994         if (this.task == 'mail') {
5995           this.enable_command('show', 'expunge', 'select-all', 'select-none', 'sort', (this.env.messagecount > 0));
5996           this.enable_command('purge', this.purge_mailbox_test());
5997           this.enable_command('expand-all', 'expand-unread', 'collapse-all', this.env.threading && this.env.messagecount);
5998
5999           if (response.action == 'list' || response.action == 'search') {
6000             this.msglist_select(this.message_list);
6001             this.triggerEvent('listupdate', { folder:this.env.mailbox, rowcount:this.message_list.rowcount });
6002           }
6003         }
6004         else if (this.task == 'addressbook') {
6005           this.enable_command('export', (this.contact_list && this.contact_list.rowcount > 0));
6006
6007           if (response.action == 'list' || response.action == 'search') {
6008             this.enable_command('search-create', this.env.source == '');
6009             this.enable_command('search-delete', this.env.search_id);
6010             this.update_group_commands();
6011             this.triggerEvent('listupdate', { folder:this.env.source, rowcount:this.contact_list.rowcount });
6012           }
6013         }
6014         break;
6015     }
6016
6017     if (response.unlock)
6018       this.hide_message(response.unlock);
6019
6020     this.triggerEvent('responseafter', {response: response});
6021     this.triggerEvent('responseafter'+response.action, {response: response});
6022   };
6023
6024   // handle HTTP request errors
6025   this.http_error = function(request, status, err, lock)
6026   {
6027     var errmsg = request.statusText;
6028
6029     this.set_busy(false, null, lock);
6030     request.abort();
6031
6032     if (request.status && errmsg)
6033       this.display_message(this.get_label('servererror') + ' (' + errmsg + ')', 'error');
6034   };
6035
6036   // post the given form to a hidden iframe
6037   this.async_upload_form = function(form, action, onload)
6038   {
6039     var ts = new Date().getTime(),
6040       frame_name = 'rcmupload'+ts;
6041
6042     // upload progress support
6043     if (this.env.upload_progress_name) {
6044       var fname = this.env.upload_progress_name,
6045         field = $('input[name='+fname+']', form);
6046
6047       if (!field.length) {
6048         field = $('<input>').attr({type: 'hidden', name: fname});
6049         field.prependTo(form);
6050       }
6051
6052       field.val(ts);
6053     }
6054
6055     // have to do it this way for IE
6056     // otherwise the form will be posted to a new window
6057     if (document.all) {
6058       var html = '<iframe name="'+frame_name+'" src="program/blank.gif" style="width:0;height:0;visibility:hidden;"></iframe>';
6059       document.body.insertAdjacentHTML('BeforeEnd', html);
6060     }
6061     else { // for standards-compilant browsers
6062       var frame = document.createElement('iframe');
6063       frame.name = frame_name;
6064       frame.style.border = 'none';
6065       frame.style.width = 0;
6066       frame.style.height = 0;
6067       frame.style.visibility = 'hidden';
6068       document.body.appendChild(frame);
6069     }
6070
6071     // handle upload errors, parsing iframe content in onload
6072     $(frame_name).bind('load', {ts:ts}, onload);
6073
6074     $(form).attr({
6075         target: frame_name,
6076         action: this.url(action, { _id:this.env.compose_id||'', _uploadid:ts }),
6077         method: 'POST'})
6078       .attr(form.encoding ? 'encoding' : 'enctype', 'multipart/form-data')
6079       .submit();
6080
6081     return frame_name;
6082   };
6083
6084   // starts interval for keep-alive/check-recent signal
6085   this.start_keepalive = function()
6086   {
6087     if (this._int)
6088       clearInterval(this._int);
6089
6090     if (this.env.keep_alive && !this.env.framed && this.task == 'mail' && this.gui_objects.mailboxlist)
6091       this._int = setInterval(function(){ ref.check_for_recent(false); }, this.env.keep_alive * 1000);
6092     else if (this.env.keep_alive && !this.env.framed && this.task != 'login' && this.env.action != 'print')
6093       this._int = setInterval(function(){ ref.keep_alive(); }, this.env.keep_alive * 1000);
6094   };
6095
6096   // sends keep-alive signal
6097   this.keep_alive = function()
6098   {
6099     if (!this.busy)
6100       this.http_request('keep-alive');
6101   };
6102
6103   // sends request to check for recent messages
6104   this.check_for_recent = function(refresh)
6105   {
6106     if (this.busy)
6107       return;
6108
6109     var lock, addurl = '_mbox=' + urlencode(this.env.mailbox);
6110
6111     if (refresh) {
6112       lock = this.set_busy(true, 'checkingmail');
6113       addurl += '&_refresh=1';
6114       // reset check-recent interval
6115       this.start_keepalive();
6116     }
6117
6118     if (this.gui_objects.messagelist)
6119       addurl += '&_list=1';
6120     if (this.gui_objects.quotadisplay)
6121       addurl += '&_quota=1';
6122     if (this.env.search_request)
6123       addurl += '&_search=' + this.env.search_request;
6124
6125     this.http_request('check-recent', addurl, lock);
6126   };
6127
6128
6129   /********************************************************/
6130   /*********            helper methods            *********/
6131   /********************************************************/
6132
6133   // check if we're in show mode or if we have a unique selection
6134   // and return the message uid
6135   this.get_single_uid = function()
6136   {
6137     return this.env.uid ? this.env.uid : (this.message_list ? this.message_list.get_single_selection() : null);
6138   };
6139
6140   // same as above but for contacts
6141   this.get_single_cid = function()
6142   {
6143     return this.env.cid ? this.env.cid : (this.contact_list ? this.contact_list.get_single_selection() : null);
6144   };
6145
6146   // gets cursor position
6147   this.get_caret_pos = function(obj)
6148   {
6149     if (obj.selectionEnd !== undefined)
6150       return obj.selectionEnd;
6151     else if (document.selection && document.selection.createRange) {
6152       var range = document.selection.createRange();
6153       if (range.parentElement()!=obj)
6154         return 0;
6155
6156       var gm = range.duplicate();
6157       if (obj.tagName == 'TEXTAREA')
6158         gm.moveToElementText(obj);
6159       else
6160         gm.expand('textedit');
6161
6162       gm.setEndPoint('EndToStart', range);
6163       var p = gm.text.length;
6164
6165       return p<=obj.value.length ? p : -1;
6166     }
6167     else
6168       return obj.value.length;
6169   };
6170
6171   // moves cursor to specified position
6172   this.set_caret_pos = function(obj, pos)
6173   {
6174     if (obj.setSelectionRange)
6175       obj.setSelectionRange(pos, pos);
6176     else if (obj.createTextRange) {
6177       var range = obj.createTextRange();
6178       range.collapse(true);
6179       range.moveEnd('character', pos);
6180       range.moveStart('character', pos);
6181       range.select();
6182     }
6183   };
6184
6185   // disable/enable all fields of a form
6186   this.lock_form = function(form, lock)
6187   {
6188     if (!form || !form.elements)
6189       return;
6190
6191     var n, len, elm;
6192
6193     if (lock)
6194       this.disabled_form_elements = [];
6195
6196     for (n=0, len=form.elements.length; n<len; n++) {
6197       elm = form.elements[n];
6198
6199       if (elm.type == 'hidden')
6200         continue;
6201       // remember which elem was disabled before lock
6202       if (lock && elm.disabled)
6203         this.disabled_form_elements.push(elm);
6204       // check this.disabled_form_elements before inArray() as a workaround for FF5 bug
6205       // http://bugs.jquery.com/ticket/9873
6206       else if (lock || (this.disabled_form_elements && $.inArray(elm, this.disabled_form_elements)<0))
6207         elm.disabled = lock;
6208     }
6209   };
6210
6211 }  // end object rcube_webmail
6212
6213
6214 // some static methods
6215 rcube_webmail.long_subject_title = function(elem, indent)
6216 {
6217   if (!elem.title) {
6218     var $elem = $(elem);
6219     if ($elem.width() + indent * 15 > $elem.parent().width())
6220       elem.title = $elem.html();
6221   }
6222 };
6223
6224 rcube_webmail.long_subject_title_ie = function(elem, indent)
6225 {
6226   if (!elem.title) {
6227     var $elem = $(elem),
6228       txt = $.trim($elem.text()),
6229       tmp = $('<span>').text(txt)
6230         .css({'position': 'absolute', 'float': 'left', 'visibility': 'hidden',
6231           'font-size': $elem.css('font-size'), 'font-weight': $elem.css('font-weight')})
6232         .appendTo($('body')),
6233       w = tmp.width();
6234
6235     tmp.remove();
6236     if (w + indent * 15 > $elem.width())
6237       elem.title = txt;
6238   }
6239 };
6240
6241 // copy event engine prototype
6242 rcube_webmail.prototype.addEventListener = rcube_event_engine.prototype.addEventListener;
6243 rcube_webmail.prototype.removeEventListener = rcube_event_engine.prototype.removeEventListener;
6244 rcube_webmail.prototype.triggerEvent = rcube_event_engine.prototype.triggerEvent;
6245