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