]> git.donarmstrong.com Git - roundcube.git/blob - program/js/app.js
Imported Upstream version 0.1~rc2
[roundcube.git] / program / js / app.js
1 /*
2  +-----------------------------------------------------------------------+
3  | RoundCube Webmail Client Script                                       |
4  |                                                                       |
5  | This file is part of the RoundCube Webmail client                     |
6  | Copyright (C) 2005-2007, RoundCube Dev, - Switzerland                 |
7  | Licensed under the GNU GPL                                            |
8  |                                                                       |
9  +-----------------------------------------------------------------------+
10  | Authors: Thomas Bruederli <roundcube@gmail.com>                       |
11  |          Charles McNulty <charles@charlesmcnulty.com>                 |
12  +-----------------------------------------------------------------------+
13  | Requires: common.js, list.js                                          |
14  +-----------------------------------------------------------------------+
15
16   $Id: app.js 888 2007-10-19 14:04:43Z robin $
17 */
18
19
20 var rcube_webmail_client;
21
22 function rcube_webmail()
23   {
24   this.env = new Object();
25   this.labels = new Object();
26   this.buttons = new Object();
27   this.gui_objects = new Object();
28   this.commands = new Object();
29   this.onloads = new Array();
30
31   // create protected reference to myself
32   rcube_webmail_client = this;
33   this.ref = 'rcube_webmail_client';
34   var ref = this;
35  
36   // webmail client settings
37   this.dblclick_time = 500;
38   this.message_time = 3000;
39   
40   this.identifier_expr = new RegExp('[^0-9a-z\-_]', 'gi');
41   
42   // mimetypes supported by the browser (default settings)
43   this.mimetypes = new Array('text/plain', 'text/html', 'text/xml',
44                              'image/jpeg', 'image/gif', 'image/png',
45                              'application/x-javascript', 'application/pdf',
46                              'application/x-shockwave-flash');
47
48   // default environment vars
49   this.env.keep_alive = 60;        // seconds
50   this.env.request_timeout = 180;  // seconds
51   this.env.draft_autosave = 0;     // seconds
52   this.env.comm_path = './';
53   this.env.bin_path = './bin/';
54   this.env.blankpage = 'program/blank.gif';
55
56
57   // set environment variable(s)
58   this.set_env = function(p, value)
59     {
60     if (p != null && typeof(p) == 'object' && !value)
61       for (var n in p)
62         this.env[n] = p[n];
63     else
64       this.env[p] = value;
65     };
66
67
68   // add a localized label to the client environment
69   this.add_label = function(key, value)
70     {
71     this.labels[key] = value;
72     };
73
74
75   // add a button to the button list
76   this.register_button = function(command, id, type, act, sel, over)
77     {
78     if (!this.buttons[command])
79       this.buttons[command] = new Array();
80       
81     var button_prop = {id:id, type:type};
82     if (act) button_prop.act = act;
83     if (sel) button_prop.sel = sel;
84     if (over) button_prop.over = over;
85
86     this.buttons[command][this.buttons[command].length] = button_prop;    
87     };
88
89   // register a specific gui object
90   this.gui_object = function(name, id)
91     {
92     this.gui_objects[name] = id;
93     };
94   
95   // execute the given script on load
96   this.add_onload = function(f)
97     {
98       this.onloads[this.onloads.length] = f;
99     };
100
101   // initialize webmail client
102   this.init = function()
103     {
104     var p = this;
105     this.task = this.env.task;
106     
107     // check browser
108     if (!bw.dom || !bw.xmlhttp_test())
109       {
110       this.goto_url('error', '_code=0x199');
111       return;
112       }
113     
114     // find all registered gui objects
115     for (var n in this.gui_objects)
116       this.gui_objects[n] = rcube_find_object(this.gui_objects[n]);
117
118     // tell parent window that this frame is loaded
119     if (this.env.framed && parent.rcmail && parent.rcmail.set_busy)
120       parent.rcmail.set_busy(false);
121
122     // enable general commands
123     this.enable_command('logout', 'mail', 'addressbook', 'settings', true);
124     
125     switch (this.task)
126       {
127       case 'mail':
128         if (this.gui_objects.messagelist)
129           {
130           this.message_list = new rcube_list_widget(this.gui_objects.messagelist, {multiselect:true, draggable:true, keyboard:true, dblclick_time:this.dblclick_time});
131           this.message_list.row_init = function(o){ p.init_message_row(o); };
132           this.message_list.addEventListener('dblclick', function(o){ p.msglist_dbl_click(o); });
133           this.message_list.addEventListener('keypress', function(o){ p.msglist_keypress(o); });
134           this.message_list.addEventListener('select', function(o){ p.msglist_select(o); });
135           this.message_list.addEventListener('dragstart', function(o){ p.drag_active = true; });
136           this.message_list.addEventListener('dragend', function(o){ p.drag_active = false; });
137
138           this.message_list.init();
139           this.enable_command('toggle_status', true);
140           
141           if (this.gui_objects.mailcontframe)
142             {
143             this.gui_objects.mailcontframe.onmousedown = function(e){ return p.click_on_list(e); };
144             document.onmouseup = function(e){ return p.doc_mouse_up(e); };
145             }
146           else
147             this.message_list.focus();
148           }
149
150         // enable mail commands
151         this.enable_command('list', 'checkmail', 'compose', 'add-contact', 'search', 'reset-search', true);
152         
153         if (this.env.action=='show' || this.env.action=='preview')
154           {
155           this.enable_command('show', 'reply', 'reply-all', 'forward', 'moveto', 'delete', 'viewsource', 'print', 'load-attachment', true);
156           if (this.env.next_uid)
157             {
158             this.enable_command('nextmessage', true);
159             this.enable_command('lastmessage', true);
160             }
161           if (this.env.prev_uid)
162             {
163             this.enable_command('previousmessage', true);
164             this.enable_command('firstmessage', true);
165             }
166           }
167
168         if (this.env.trash_mailbox && this.env.mailbox != this.env.trash_mailbox)
169           this.set_alttext('delete', 'movemessagetotrash');
170         
171         // make preview/message frame visible
172         if (this.env.action == 'preview' && this.env.framed && parent.rcmail)
173           {
174           this.enable_command('compose', 'add-contact', false);
175           parent.rcmail.show_contentframe(true);
176           parent.rcmail.mark_message('read', this.env.uid);
177           }
178
179         if ((this.env.action=='show' || this.env.action=='preview') && this.env.blockedobjects)
180           {
181           if (this.gui_objects.remoteobjectsmsg)
182             this.gui_objects.remoteobjectsmsg.style.display = 'block';
183           this.enable_command('load-images', true);
184           }
185
186         if (this.env.action=='compose')
187           {
188           this.enable_command('add-attachment', 'send-attachment', 'remove-attachment', 'send', true);
189           if (this.env.spellcheck)
190             {
191             this.env.spellcheck.spelling_state_observer = function(s){ ref.set_spellcheck_state(s); };
192             this.set_spellcheck_state('ready');
193             }
194           if (this.env.drafts_mailbox)
195             this.enable_command('savedraft', true);
196           }
197
198         if (this.env.messagecount)
199           this.enable_command('select-all', 'select-none', 'sort', 'expunge', true);
200
201         if (this.env.messagecount && (this.env.mailbox==this.env.trash_mailbox || this.env.mailbox==this.env.junk_mailbox))
202           this.enable_command('purge', true);
203
204         this.set_page_buttons();
205
206         // focus main window
207         if (this.env.framed && window.parent)
208           window.parent.focus();
209         else
210           window.focus();
211
212         // init message compose form
213         if (this.env.action=='compose')
214           this.init_messageform();
215
216         // show printing dialog
217         if (this.env.action=='print')
218           window.print();
219
220         // get unread count for each mailbox
221         if (this.gui_objects.mailboxlist)
222         {
223           this.gui_objects.folderlist = this.gui_objects.mailboxlist;
224           this.http_request('getunread', '');
225         }
226
227         break;
228
229
230       case 'addressbook':
231         if (this.gui_objects.contactslist)
232           {
233           this.contact_list = new rcube_list_widget(this.gui_objects.contactslist, {multiselect:true, draggable:true, keyboard:true});
234           this.contact_list.addEventListener('keypress', function(o){ p.contactlist_keypress(o); });
235           this.contact_list.addEventListener('select', function(o){ p.contactlist_select(o); });
236           this.contact_list.addEventListener('dragstart', function(o){ p.drag_active = true; });
237           this.contact_list.addEventListener('dragend', function(o){ p.drag_active = false; });
238           this.contact_list.init();
239
240           if (this.env.cid)
241             this.contact_list.highlight_row(this.env.cid);
242
243           if (this.gui_objects.contactslist.parentNode)
244             {
245             this.gui_objects.contactslist.parentNode.onmousedown = function(e){ return p.click_on_list(e); };
246             document.onmouseup = function(e){ return p.doc_mouse_up(e); };
247             }
248           else
249             this.contact_list.focus();
250           }
251
252         this.set_page_buttons();
253         
254         if (this.env.address_sources && !this.env.address_sources[this.env.source].readonly)
255           this.enable_command('add', true);
256         
257         if (this.env.cid)
258           this.enable_command('show', 'edit', true);
259
260         if ((this.env.action=='add' || this.env.action=='edit') && this.gui_objects.editform)
261           this.enable_command('save', true);
262         else
263           this.enable_command('search', 'reset-search', 'moveto', true);
264
265         this.enable_command('list', true);
266         break;
267
268
269       case 'settings':
270         this.enable_command('preferences', 'identities', 'save', 'folders', true);
271         
272         if (this.env.action=='identities' || this.env.action=='edit-identity' || this.env.action=='add-identity')
273           this.enable_command('edit', 'add', 'delete', true);
274
275         if (this.env.action=='edit-identity' || this.env.action=='add-identity')
276           this.enable_command('save', true);
277           
278         if (this.env.action=='folders')
279           this.enable_command('subscribe', 'unsubscribe', 'create-folder', 'rename-folder', 'delete-folder', true);
280
281         if (this.gui_objects.identitieslist)
282           {
283           this.identity_list = new rcube_list_widget(this.gui_objects.identitieslist, {multiselect:false, draggable:false, keyboard:false});
284           this.identity_list.addEventListener('select', function(o){ p.identity_select(o); });
285           this.identity_list.init();
286           this.identity_list.focus();
287
288           if (this.env.iid)
289             this.identity_list.highlight_row(this.env.iid);
290           }
291
292         if (this.gui_objects.subscriptionlist)
293           this.init_subscription_list();
294
295         break;
296
297       case 'login':
298         var input_user = rcube_find_object('_user');
299         var input_pass = rcube_find_object('_pass');
300         if (input_user)
301           input_user.onkeypress = function(e){ return rcmail.login_user_keypress(e); };
302         if (input_user && input_user.value=='')
303           input_user.focus();
304         else if (input_pass)
305           input_pass.focus();
306           
307         this.enable_command('login', true);
308         break;
309       
310       default:
311         break;
312       }
313
314
315     // enable basic commands
316     this.enable_command('logout', true);
317
318     // flag object as complete
319     this.loaded = true;
320
321     // show message
322     if (this.pending_message)
323       this.display_message(this.pending_message[0], this.pending_message[1]);
324
325     // start keep-alive interval
326     this.start_keepalive();
327     
328     
329     // execute all foreign onload scripts
330     for (var i=0; i<this.onloads.length; i++)
331       {
332       if (typeof(this.onloads[i]) == 'string')
333         eval(this.onloads[i]);
334       else if (typeof(this.onloads[i]) == 'function')
335         this.onloads[i]();
336       }
337     };
338
339
340   // start interval for keep-alive/recent_check signal
341   this.start_keepalive = function()
342     {
343     if (this.env.keep_alive && !this.env.framed && this.task=='mail' && this.gui_objects.messagelist)
344       this._int = setInterval(function(){ ref.check_for_recent(); }, this.env.keep_alive * 1000);
345     else if (this.env.keep_alive && !this.env.framed && this.task!='login')
346       this._int = setInterval(function(){ ref.send_keep_alive(); }, this.env.keep_alive * 1000);    
347     }
348
349
350   this.init_message_row = function(row)
351   {
352     var uid = row.uid;
353     if (uid && this.env.messages[uid])
354       {
355       row.deleted = this.env.messages[uid].deleted ? true : false;
356       row.unread = this.env.messages[uid].unread ? true : false;
357       row.replied = this.env.messages[uid].replied ? true : false;
358       }
359
360     // set eventhandler to message icon
361     if ((row.icon = row.obj.cells[0].childNodes[0]) && row.icon.nodeName=='IMG')
362       {
363       var p = this;
364       row.icon.id = 'msgicn_'+row.uid;
365       row.icon._row = row.obj;
366       row.icon.onmousedown = function(e) { p.command('toggle_status', this); };
367       }
368   };
369
370
371   // init message compose form: set focus and eventhandlers
372   this.init_messageform = function()
373     {
374     if (!this.gui_objects.messageform)
375       return false;
376     
377     //this.messageform = this.gui_objects.messageform;
378     var input_from = rcube_find_object('_from');
379     var input_to = rcube_find_object('_to');
380     var input_cc = rcube_find_object('_cc');
381     var input_bcc = rcube_find_object('_bcc');
382     var input_replyto = rcube_find_object('_replyto');
383     var input_subject = rcube_find_object('_subject');
384     var input_message = rcube_find_object('_message');
385
386     // init live search events
387     if (input_to)
388       this.init_address_input_events(input_to);
389     if (input_cc)
390       this.init_address_input_events(input_cc);
391     if (input_bcc)
392       this.init_address_input_events(input_bcc);
393       
394     // add signature according to selected identity
395     if (input_from && input_from.type=='select-one')
396       this.change_identity(input_from);
397
398     if (input_to && input_to.value=='')
399       input_to.focus();
400     else if (input_subject && input_subject.value=='')
401       input_subject.focus();
402     else if (input_message)
403       this.set_caret2start(input_message);
404
405     // get summary of all field values
406     this.compose_field_hash(true);
407  
408     // start the auto-save timer
409     this.auto_save_start();
410     };
411
412   this.init_address_input_events = function(obj)
413     {
414     var handler = function(e){ return ref.ksearch_keypress(e,this); };
415     var handler2 = function(e){ return ref.ksearch_blur(e,this); };
416     
417     if (obj.addEventListener)
418     {
419       obj.addEventListener(bw.safari ? 'keydown' : 'keypress', handler, false);
420       obj.addEventListener('blur', handler2, false);
421     }
422     else
423     {
424       obj.onkeydown = handler;
425       obj.onblur = handler2;
426     }
427
428     obj.setAttribute('autocomplete', 'off');       
429     };
430
431
432
433   /*********************************************************/
434   /*********       client command interface        *********/
435   /*********************************************************/
436
437
438   // execute a specific command on the web client
439   this.command = function(command, props, obj)
440     {
441     if (obj && obj.blur)
442       obj.blur();
443
444     if (this.busy)
445       return false;
446
447     // command not supported or allowed
448     if (!this.commands[command])
449       {
450       // pass command to parent window
451       if (this.env.framed && parent.rcmail && parent.rcmail.command)
452         parent.rcmail.command(command, props);
453
454       return false;
455       }
456       
457       
458    // check input before leaving compose step
459    if (this.task=='mail' && this.env.action=='compose' && (command=='list' || command=='mail' || command=='addressbook' || command=='settings'))
460      {
461      if (this.cmp_hash != this.compose_field_hash() && !confirm(this.get_label('notsentwarning')))
462         return false;
463      }
464
465
466     // process command
467     switch (command)
468       {
469       case 'login':
470         if (this.gui_objects.loginform)
471           this.gui_objects.loginform.submit();
472         break;
473
474       case 'logout':
475         this.goto_url('logout', true);
476         break;      
477
478       // commands to switch task
479       case 'mail':
480       case 'addressbook':
481       case 'settings':
482         this.switch_task(command);
483         break;
484
485
486       // misc list commands
487       case 'list':
488         if (this.task=='mail')
489           {
490           if (this.env.search_request<0 || (this.env.search_request && props != this.env.mailbox))
491             this.reset_qsearch();
492
493           this.list_mailbox(props);
494
495           if (this.env.trash_mailbox)
496             this.set_alttext('delete', this.env.mailbox != this.env.trash_mailbox ? 'movemessagetotrash' : 'deletemessage');
497           }
498         else if (this.task=='addressbook')
499           {
500           if (this.env.search_request<0 || (this.env.search_request && props != this.env.source))
501             this.reset_qsearch();
502
503           this.list_contacts(props);
504           this.enable_command('add', (this.env.address_sources && !this.env.address_sources[props].readonly));
505           }
506         break;
507
508
509       case 'sort':
510         // get the type of sorting
511         var a_sort = props.split('_');
512         var sort_col = a_sort[0];
513         var sort_order = a_sort[1] ? a_sort[1].toUpperCase() : null;
514         var header;
515         
516         // no sort order specified: toggle
517         if (sort_order==null)
518           {
519           if (this.env.sort_col==sort_col)
520             sort_order = this.env.sort_order=='ASC' ? 'DESC' : 'ASC';
521           else
522             sort_order = this.env.sort_order;
523           }
524
525         if (this.env.sort_col==sort_col && this.env.sort_order==sort_order)
526           break;
527
528         // set table header class
529         if (header = document.getElementById('rcmHead'+this.env.sort_col))
530           this.set_classname(header, 'sorted'+(this.env.sort_order.toUpperCase()), false);
531         if (header = document.getElementById('rcmHead'+sort_col))
532           this.set_classname(header, 'sorted'+sort_order, true);
533
534         // save new sort properties
535         this.env.sort_col = sort_col;
536         this.env.sort_order = sort_order;
537
538         // reload message list
539         this.list_mailbox('', '', sort_col+'_'+sort_order);
540         break;
541
542       case 'nextpage':
543         this.list_page('next');
544         break;
545
546       case 'lastpage':
547         this.list_page('last');
548         break;
549
550       case 'previouspage':
551         this.list_page('prev');
552         break;
553
554       case 'firstpage':
555         this.list_page('first');
556         break;
557
558       case 'expunge':
559         if (this.env.messagecount)
560           this.expunge_mailbox(this.env.mailbox);
561         break;
562
563       case 'purge':
564       case 'empty-mailbox':
565         if (this.env.messagecount)
566           this.purge_mailbox(this.env.mailbox);
567         break;
568
569
570       // common commands used in multiple tasks
571       case 'show':
572         if (this.task=='mail')
573           {
574           var uid = this.get_single_uid();
575           if (uid && (!this.env.uid || uid != this.env.uid))
576             {
577             if (this.env.mailbox == this.env.drafts_mailbox)
578               this.goto_url('compose', '_draft_uid='+uid+'&_mbox='+urlencode(this.env.mailbox), true);
579             else
580               this.show_message(uid);
581             }
582           }
583         else if (this.task=='addressbook')
584           {
585           var cid = props ? props : this.get_single_cid();
586           if (cid && !(this.env.action=='show' && cid==this.env.cid))
587             this.load_contact(cid, 'show');
588           }
589         break;
590
591       case 'add':
592         if (this.task=='addressbook')
593           this.load_contact(0, 'add');
594         else if (this.task=='settings')
595           {
596           this.identity_list.clear_selection();
597           this.load_identity(0, 'add-identity');
598           }
599         break;
600
601       case 'edit':
602         var cid;
603         if (this.task=='addressbook' && (cid = this.get_single_cid()))
604           this.load_contact(cid, 'edit');
605         else if (this.task=='settings' && props)
606           this.load_identity(props, 'edit-identity');
607         break;
608
609       case 'save-identity':
610       case 'save':
611         if (this.gui_objects.editform)
612           {
613           var input_pagesize = rcube_find_object('_pagesize');
614           var input_name  = rcube_find_object('_name');
615           var input_email = rcube_find_object('_email');
616
617           // user prefs
618           if (input_pagesize && isNaN(input_pagesize.value))
619             {
620             alert(this.get_label('nopagesizewarning'));
621             input_pagesize.focus();
622             break;
623             }
624           // contacts/identities
625           else
626             {
627             if (input_name && input_name.value == '')
628               {
629               alert(this.get_label('nonamewarning'));
630               input_name.focus();
631               break;
632               }
633             else if (input_email && !rcube_check_email(input_email.value))
634               {
635               alert(this.get_label('noemailwarning'));
636               input_email.focus();
637               break;
638               }
639             }
640
641           this.gui_objects.editform.submit();
642           }
643         break;
644
645       case 'delete':
646         // mail task
647         if (this.task=='mail')
648           this.delete_messages();
649         // addressbook task
650         else if (this.task=='addressbook')
651           this.delete_contacts();
652         // user settings task
653         else if (this.task=='settings')
654           this.delete_identity();
655         break;
656
657
658       // mail task commands
659       case 'move':
660       case 'moveto':
661         if (this.task == 'mail')
662           this.move_messages(props);
663         else if (this.task == 'addressbook' && this.drag_active)
664           this.copy_contact(null, props);
665         break;
666         
667       case 'toggle_status':
668         if (props && !props._row)
669           break;
670         
671         var uid;
672         var flag = 'read';
673         
674         if (props._row.uid)
675           {
676           uid = props._row.uid;
677           this.message_list.dont_select = true;
678           // toggle read/unread
679           if (this.message_list.rows[uid].deleted) {
680             flag = 'undelete';
681           } else if (!this.message_list.rows[uid].unread)
682             flag = 'unread';
683           }
684           
685         this.mark_message(flag, uid);
686         break;
687         
688       case 'load-images':
689         if (this.env.uid)
690           this.show_message(this.env.uid, true, this.env.action=='preview');
691         break;
692
693       case 'load-attachment':
694         var qstring = '_mbox='+this.env.mailbox+'&_uid='+this.env.uid+'&_part='+props.part;
695         
696         // open attachment in frame if it's of a supported mimetype
697         if (this.env.uid && props.mimetype && find_in_array(props.mimetype, this.mimetypes)>=0)
698           {
699           if (props.mimetype == 'text/html')
700             qstring += '&_safe=1';
701           this.attachment_win = window.open(this.env.comm_path+'&_action=get&'+qstring+'&_frame=1', 'rcubemailattachment');
702           if (this.attachment_win)
703             {
704             setTimeout(function(){ ref.attachment_win.focus(); }, 10);
705             break;
706             }
707           }
708
709         this.goto_url('get', qstring+'&_download=1', false);
710         break;
711         
712       case 'select-all':
713         this.message_list.select_all(props);
714         break;
715
716       case 'select-none':
717         this.message_list.clear_selection();
718         break;
719
720       case 'nextmessage':
721         if (this.env.next_uid)
722           this.show_message(this.env.next_uid, false, this.env.action=='preview');
723         break;
724
725       case 'lastmessage':
726         if (this.env.last_uid)
727           this.show_message(this.env.last_uid);
728         break;
729
730       case 'previousmessage':
731         if (this.env.prev_uid)
732           this.show_message(this.env.prev_uid, false, this.env.action=='preview');
733         break;
734
735       case 'firstmessage':
736         if (this.env.first_uid)
737           this.show_message(this.env.first_uid);
738         break;
739       
740       case 'checkmail':
741         this.check_for_recent();
742         break;
743       
744       case 'compose':
745         var url = this.env.comm_path+'&_action=compose';
746        
747         if (this.task=='mail' && this.env.mailbox==this.env.drafts_mailbox)
748           {
749           var uid;
750           if (uid = this.get_single_uid())
751             url += '&_draft_uid='+uid+'&_mbox='+urlencode(this.env.mailbox);
752           }
753         // modify url if we're in addressbook
754         else if (this.task=='addressbook')
755           {
756           // switch to mail compose step directly
757           if (props && props.indexOf('@') > 0)
758           {
759             url = this.get_task_url('mail', url);
760             this.redirect(url + '&_to='+urlencode(props));
761             break;
762           }
763           
764           // use contact_id passed as command parameter
765           var a_cids = new Array();
766           if (props)
767             a_cids[a_cids.length] = props;
768           // get selected contacts
769           else if (this.contact_list)
770             {
771             var selection = this.contact_list.get_selection();
772             for (var n=0; n<selection.length; n++)
773               a_cids[a_cids.length] = selection[n];
774             }
775             
776           if (a_cids.length)
777             this.http_request('mailto', '_cid='+urlencode(a_cids.join(','))+'&_source='+urlencode(this.env.source), true);
778
779           break;
780           }
781         else if (props)
782            url += '&_to='+urlencode(props);
783
784         // don't know if this is necessary...
785         url = url.replace(/&_framed=1/, "");
786
787         this.redirect(url);
788         break;
789         
790       case 'spellcheck':
791         if (this.env.spellcheck && this.env.spellcheck.spellCheck && this.spellcheck_ready)
792           {
793           this.env.spellcheck.spellCheck(this.env.spellcheck.check_link);
794           this.set_spellcheck_state('checking');
795           }
796         break;
797
798       case 'savedraft':
799         // Reset the auto-save timer
800         self.clearTimeout(this.save_timer);
801
802         if (!this.gui_objects.messageform)
803           break;
804
805         // if saving Drafts is disabled in main.inc.php
806         // or if compose form did not change
807         if (!this.env.drafts_mailbox || this.cmp_hash == this.compose_field_hash())
808           break;
809
810         this.set_busy(true, 'savingmessage');
811         var form = this.gui_objects.messageform;
812         form.target = "savetarget";
813         form._draft.value = '1';
814         form.submit();
815         break;
816
817       case 'send':
818         if (!this.gui_objects.messageform)
819           break;
820
821         if (!this.check_compose_input())
822           break;
823           
824         // Reset the auto-save timer
825         self.clearTimeout(this.save_timer);
826
827         // all checks passed, send message
828         this.set_busy(true, 'sendingmessage');
829         var form = this.gui_objects.messageform;
830         form.target = "savetarget";     
831         form._draft.value = '';
832         form.submit();
833         
834         // clear timeout (sending could take longer)
835         clearTimeout(this.request_timer);
836         break;
837
838       case 'add-attachment':
839         this.show_attachment_form(true);
840         
841       case 'send-attachment':
842         // Reset the auto-save timer
843         self.clearTimeout(this.save_timer);
844
845         this.upload_file(props)      
846         break;
847       
848       case 'remove-attachment':
849         this.remove_attachment(props);
850         break;
851
852       case 'reply-all':
853       case 'reply':
854         var uid;
855         if (uid = this.get_single_uid())
856           this.goto_url('compose', '_reply_uid='+uid+'&_mbox='+urlencode(this.env.mailbox)+(command=='reply-all' ? '&_all=1' : ''), true);
857         break;      
858
859       case 'forward':
860         var uid;
861         if (uid = this.get_single_uid())
862           this.goto_url('compose', '_forward_uid='+uid+'&_mbox='+urlencode(this.env.mailbox), true);
863         break;
864         
865       case 'print':
866         var uid;
867         if (uid = this.get_single_uid())
868           {
869           ref.printwin = window.open(this.env.comm_path+'&_action=print&_uid='+uid+'&_mbox='+urlencode(this.env.mailbox)+(this.env.safemode ? '&_safe=1' : ''));
870           if (this.printwin)
871             setTimeout(function(){ ref.printwin.focus(); }, 20);
872           }
873         break;
874
875       case 'viewsource':
876         var uid;
877         if (uid = this.get_single_uid())
878           {
879           ref.sourcewin = window.open(this.env.comm_path+'&_action=viewsource&_uid='+this.env.uid+'&_mbox='+urlencode(this.env.mailbox));
880           if (this.sourcewin)
881             setTimeout(function(){ ref.sourcewin.focus(); }, 20);
882           }
883         break;
884
885       case 'add-contact':
886         this.add_contact(props);
887         break;
888       
889       // quicksearch
890       case 'search':
891         if (!props && this.gui_objects.qsearchbox)
892           props = this.gui_objects.qsearchbox.value;
893         if (props)
894         {
895           this.qsearch(props);
896           break;
897         }
898
899       // reset quicksearch        
900       case 'reset-search':
901         var s = this.env.search_request;
902         this.reset_qsearch();
903         
904         if (s && this.env.mailbox)
905           this.list_mailbox(this.env.mailbox);
906         else if (s && this.task == 'addressbook')
907           this.list_contacts(this.env.source);
908         break;
909
910
911       // user settings commands
912       case 'preferences':
913         this.goto_url('');
914         break;
915
916       case 'identities':
917         this.goto_url('identities');
918         break;
919           
920       case 'delete-identity':
921         this.delete_identity();
922         
923       case 'folders':
924         this.goto_url('folders');
925         break;
926
927       case 'subscribe':
928         this.subscribe_folder(props);
929         break;
930
931       case 'unsubscribe':
932         this.unsubscribe_folder(props);
933         break;
934         
935       case 'create-folder':
936         this.create_folder(props);
937         break;
938
939       case 'rename-folder':
940         this.rename_folder(props);
941         break;
942
943       case 'delete-folder':
944         this.delete_folder(props);
945         break;
946
947       }
948
949     return obj ? false : true;
950     };
951
952
953   // set command enabled or disabled
954   this.enable_command = function()
955     {
956     var args = arguments;
957     if(!args.length) return -1;
958
959     var command;
960     var enable = args[args.length-1];
961     
962     for(var n=0; n<args.length-1; n++)
963       {
964       command = args[n];
965       this.commands[command] = enable;
966       this.set_button(command, (enable ? 'act' : 'pas'));
967       }
968       return true;
969     };
970
971
972   // lock/unlock interface
973   this.set_busy = function(a, message)
974     {
975     if (a && message)
976       {
977       var msg = this.get_label(message);
978       if (msg==message)        
979         msg = 'Loading...';
980
981       this.display_message(msg, 'loading', true);
982       }
983     else if (!a)
984       this.hide_message();
985
986     this.busy = a;
987     //document.body.style.cursor = a ? 'wait' : 'default';
988     
989     if (this.gui_objects.editform)
990       this.lock_form(this.gui_objects.editform, a);
991       
992     // clear pending timer
993     if (this.request_timer)
994       clearTimeout(this.request_timer);
995
996     // set timer for requests
997     if (a && this.env.request_timeout)
998       this.request_timer = setTimeout(function(){ ref.request_timed_out(); }, this.env.request_timeout * 1000);
999     };
1000
1001
1002   // return a localized string
1003   this.get_label = function(name)
1004     {
1005     if (this.labels[name])
1006       return this.labels[name];
1007     else
1008       return name;
1009     };
1010
1011
1012   // switch to another application task
1013   this.switch_task = function(task)
1014     {
1015     if (this.task===task && task!='mail')
1016       return;
1017
1018     var url = this.get_task_url(task);
1019     if (task=='mail')
1020       url += '&_mbox=INBOX';
1021
1022     this.redirect(url);
1023     };
1024
1025
1026   this.get_task_url = function(task, url)
1027     {
1028     if (!url)
1029       url = this.env.comm_path;
1030
1031     return url.replace(/_task=[a-z]+/, '_task='+task);
1032     };
1033     
1034   
1035   // called when a request timed out
1036   this.request_timed_out = function()
1037     {
1038     this.set_busy(false);
1039     this.display_message('Request timed out!', 'error');
1040     };
1041
1042
1043   /*********************************************************/
1044   /*********        event handling methods         *********/
1045   /*********************************************************/
1046
1047
1048   this.doc_mouse_up = function(e)
1049     {
1050     if (this.message_list)
1051       this.message_list.blur();
1052     else if (this.contact_list)
1053       this.contact_list.blur();
1054     };
1055
1056   this.focus_folder = function(id)
1057     {
1058     var li;
1059     if (this.drag_active && this.check_droptarget(id) && (li = this.get_folder_li(id)))
1060       this.set_classname(li, 'droptarget', true);
1061     }
1062
1063   this.unfocus_folder = function(id)
1064     {
1065     var li;
1066     if (this.drag_active && (li = this.get_folder_li(id)))
1067       this.set_classname(li, 'droptarget', false);
1068     }
1069
1070   // onmouseup handler for folder list item
1071   this.folder_mouse_up = function(id)
1072     {
1073     if (this.drag_active)
1074       {
1075       this.unfocus_folder(id);
1076       this.command('moveto', id);
1077       }
1078
1079     // Hide message command buttons until a message is selected 
1080     this.enable_command('reply', 'reply-all', 'forward', 'delete', 'print', false); 
1081     return false;
1082     };
1083
1084   this.click_on_list = function(e)
1085     {
1086     if (this.message_list)
1087       this.message_list.focus();
1088     else if (this.contact_list)
1089         this.contact_list.focus();
1090
1091     var mbox_li;
1092     if (mbox_li = this.get_folder_li())
1093       this.set_classname(mbox_li, 'unfocused', true);
1094
1095     rcube_event.cancel(e);
1096     };
1097
1098
1099   this.msglist_select = function(list)
1100     {
1101     if (this.preview_timer)
1102       clearTimeout(this.preview_timer);
1103
1104     var selected = list.selection.length==1;
1105
1106     // Hide certain command buttons when Drafts folder is selected
1107     if (this.env.mailbox == this.env.drafts_mailbox)
1108       {
1109       this.enable_command('reply', 'reply-all', 'forward', false);
1110       this.enable_command('show', selected);
1111       this.enable_command('delete', 'moveto', (list.selection.length > 0 ? true : false));
1112       }
1113     else
1114       {
1115       this.enable_command('show', 'reply', 'reply-all', 'forward', 'print', selected);
1116       this.enable_command('delete', 'moveto', (list.selection.length > 0 ? true : false));
1117       }
1118
1119     // start timer for message preview (wait for double click)
1120     if (selected && this.env.contentframe)
1121       this.preview_timer = setTimeout(function(){ ref.msglist_get_preview(); }, this.dblclick_time + 10);
1122     else if (this.env.contentframe)
1123       this.show_contentframe(false);
1124     };
1125
1126
1127   this.msglist_dbl_click = function(list)
1128     {
1129       if (this.preview_timer)
1130         clearTimeout(this.preview_timer);
1131
1132     var uid = list.get_single_selection();
1133     if (uid && this.env.mailbox == this.env.drafts_mailbox)
1134       this.goto_url('compose', '_draft_uid='+uid+'&_mbox='+urlencode(this.env.mailbox), true);
1135     else if (uid)
1136       this.show_message(uid, false, false);
1137     };
1138
1139
1140   this.msglist_keypress = function(list)
1141     {
1142     if (list.key_pressed == list.ENTER_KEY)
1143       this.command('show');
1144     else if (list.key_pressed == list.DELETE_KEY)
1145       this.command('delete');
1146     };
1147
1148
1149   this.msglist_get_preview = function()
1150   {
1151     var uid = this.get_single_uid();
1152     if (uid && this.env.contentframe && !this.drag_active)
1153       this.show_message(uid, false, true);
1154     else if (this.env.contentframe)
1155       this.show_contentframe(false);
1156   };
1157   
1158   
1159   this.check_droptarget = function(id)
1160   {
1161     if (this.task == 'mail')
1162       return (id != this.env.mailbox);
1163     else if (this.task == 'addressbook')
1164       return (id != this.env.source && this.env.address_sources[id] && !this.env.address_sources[id].readonly);
1165     else if (this.task == 'settings')
1166       return (id != this.env.folder);
1167   };
1168
1169
1170   /*********************************************************/
1171   /*********     (message) list functionality      *********/
1172   /*********************************************************/
1173
1174
1175   // when user doble-clicks on a row
1176   this.show_message = function(id, safe, preview)
1177     {
1178     var add_url = '';
1179     var action = preview ? 'preview': 'show';
1180     var target = window;
1181     if (preview && this.env.contentframe && window.frames && window.frames[this.env.contentframe])
1182       {
1183       target = window.frames[this.env.contentframe];
1184       add_url = '&_framed=1';
1185       }
1186
1187     if (safe)
1188       add_url = '&_safe=1';
1189
1190     if (id)
1191       {
1192       var url = '&_action='+action+'&_uid='+id+'&_mbox='+urlencode(this.env.mailbox)+add_url;
1193       if (action == 'preview' && String(target.location.href).indexOf(url) >= 0)
1194         this.show_contentframe(true);
1195       else
1196         {
1197         this.set_busy(true, 'loading');
1198         target.location.href = this.env.comm_path+url;
1199         }
1200       }
1201     };
1202
1203
1204   this.show_contentframe = function(show)
1205     {
1206     var frm;
1207     if (this.env.contentframe && (frm = rcube_find_object(this.env.contentframe)))
1208       {
1209       if (!show && window.frames[this.env.contentframe] && frames[this.env.contentframe].location.href.indexOf(this.env.blankpage)<0)
1210         frames[this.env.contentframe].location.href = this.env.blankpage;
1211       if (!bw.safari)
1212         frm.style.display = show ? 'block' : 'none';
1213       }
1214       
1215     if (!show && this.busy)
1216       this.set_busy(false);
1217     };
1218
1219
1220   // list a specific page
1221   this.list_page = function(page)
1222     {
1223     if (page=='next')
1224       page = this.env.current_page+1;
1225     if (page=='last')
1226       page = this.env.pagecount;
1227     if (page=='prev' && this.env.current_page>1)
1228       page = this.env.current_page-1;
1229     if (page=='first' && this.env.current_page>1)
1230       page = 1;
1231       
1232     if (page > 0 && page <= this.env.pagecount)
1233       {
1234       this.env.current_page = page;
1235       
1236       if (this.task=='mail')
1237         this.list_mailbox(this.env.mailbox, page);
1238       else if (this.task=='addressbook')
1239         this.list_contacts(this.env.source, page);
1240       }
1241     };
1242
1243
1244   // list messages of a specific mailbox
1245   this.list_mailbox = function(mbox, page, sort)
1246     {
1247     this.last_selected = 0;
1248     var add_url = '';
1249     var target = window;
1250
1251     if (!mbox)
1252       mbox = this.env.mailbox;
1253
1254     // add sort to url if set
1255     if (sort)
1256       add_url += '&_sort=' + sort;
1257
1258     // also send search request to get the right messages
1259     if (this.env.search_request)
1260       add_url += '&_search='+this.env.search_request;
1261       
1262     // set page=1 if changeing to another mailbox
1263     if (!page && mbox != this.env.mailbox)
1264       {
1265       page = 1;
1266       this.env.current_page = page;
1267       if (this.message_list)
1268         this.message_list.clear_selection();
1269       this.show_contentframe(false);
1270       }
1271     
1272     if (mbox != this.env.mailbox || (mbox == this.env.mailbox && !page && !sort))
1273       add_url += '&_refresh=1';
1274     
1275     this.select_folder(mbox, this.env.mailbox);
1276     this.env.mailbox = mbox;
1277
1278     // load message list remotely
1279     if (this.gui_objects.messagelist)
1280       {
1281       this.list_mailbox_remote(mbox, page, add_url);
1282       return;
1283       }
1284     
1285     if (this.env.contentframe && window.frames && window.frames[this.env.contentframe])
1286       {
1287       target = window.frames[this.env.contentframe];
1288       add_url += '&_framed=1';
1289       }
1290
1291     // load message list to target frame/window
1292     if (mbox)
1293       {
1294       this.set_busy(true, 'loading');
1295       target.location.href = this.env.comm_path+'&_mbox='+urlencode(mbox)+(page ? '&_page='+page : '')+add_url;
1296       }
1297     };
1298
1299
1300   // send remote request to load message list
1301   this.list_mailbox_remote = function(mbox, page, add_url)
1302     {
1303     // clear message list first
1304     this.message_list.clear();
1305
1306     // send request to server
1307     var url = '_mbox='+urlencode(mbox)+(page ? '&_page='+page : '');
1308     this.set_busy(true, 'loading');
1309     this.http_request('list', url+add_url, true);
1310     };
1311
1312
1313   this.expunge_mailbox = function(mbox)
1314     {
1315     var lock = false;
1316     var add_url = '';
1317     
1318     // lock interface if it's the active mailbox
1319     if (mbox == this.env.mailbox)
1320        {
1321        lock = true;
1322        this.set_busy(true, 'loading');
1323        add_url = '&_reload=1';
1324        }
1325
1326     // send request to server
1327     var url = '_mbox='+urlencode(mbox);
1328     this.http_post('expunge', url+add_url, lock);
1329     };
1330
1331
1332   this.purge_mailbox = function(mbox)
1333     {
1334     var lock = false;
1335     var add_url = '';
1336     
1337     if (!confirm(this.get_label('purgefolderconfirm')))
1338       return false;
1339     
1340     // lock interface if it's the active mailbox
1341     if (mbox == this.env.mailbox)
1342        {
1343        lock = true;
1344        this.set_busy(true, 'loading');
1345        add_url = '&_reload=1';
1346        }
1347
1348     // send request to server
1349     var url = '_mbox='+urlencode(mbox);
1350     this.http_post('purge', url+add_url, lock);
1351     return true;
1352     };
1353
1354   
1355   // move selected messages to the specified mailbox
1356   this.move_messages = function(mbox)
1357     {
1358     // exit if current or no mailbox specified or if selection is empty
1359     if (!mbox || !this.env.uid || mbox==this.env.mailbox)
1360       {
1361       if (!this.message_list || !this.message_list.get_selection().length)
1362         return;
1363       }
1364
1365     var lock = false;
1366     var add_url = '&_target_mbox='+urlencode(mbox)+'&_from='+(this.env.action ? this.env.action : '');
1367
1368     // show wait message
1369     if (this.env.action=='show')
1370       {
1371       lock = true;
1372       this.set_busy(true, 'movingmessage');
1373       }
1374     else
1375       this.show_contentframe(false);
1376
1377     this._with_selected_messages('moveto', lock, add_url);
1378     };
1379
1380   // delete selected messages from the current mailbox
1381   this.delete_messages = function()
1382     {
1383     var selection = this.message_list ? this.message_list.get_selection() : new Array();
1384     
1385     // exit if no mailbox specified or if selection is empty
1386     if (!this.env.uid && !selection.length)
1387         return;
1388
1389     // if there is a trash mailbox defined and we're not currently in it:
1390     if (this.env.trash_mailbox && String(this.env.mailbox).toLowerCase() != String(this.env.trash_mailbox).toLowerCase())
1391       {
1392       // if shift was pressed delete it immediately
1393       if (this.message_list && this.message_list.shiftkey)
1394         {
1395         if (confirm(this.get_label('deletemessagesconfirm')))
1396           this.permanently_remove_messages();
1397         }
1398       else
1399         this.move_messages(this.env.trash_mailbox);
1400       }
1401     // if there is a trash mailbox defined but we *are* in it:
1402     else if (this.env.trash_mailbox && String(this.env.mailbox).toLowerCase() == String(this.env.trash_mailbox).toLowerCase())
1403       this.permanently_remove_messages();
1404     // if there isn't a defined trash mailbox and the config is set to flag for deletion
1405     else if (!this.env.trash_mailbox && this.env.flag_for_deletion)
1406       {
1407       this.mark_message('delete');
1408       if(this.env.action=="show")
1409         this.command('nextmessage','',this);
1410       else if (selection.length == 1)
1411         this.message_list.select_next();
1412       }
1413     // if there isn't a defined trash mailbox and the config is set NOT to flag for deletion
1414     else if (!this.env.trash_mailbox) 
1415       this.permanently_remove_messages();
1416   };
1417
1418
1419   // delete the selected messages permanently
1420   this.permanently_remove_messages = function()
1421     {
1422     // exit if no mailbox specified or if selection is empty
1423     if (!this.env.uid && (!this.message_list || !this.message_list.get_selection().length))
1424       return;
1425       
1426     this.show_contentframe(false);
1427     this._with_selected_messages('delete', false, '&_from='+(this.env.action ? this.env.action : ''));
1428     };
1429
1430   // Send a specifc request with UIDs of all selected messages
1431   // @private
1432   this._with_selected_messages = function(action, lock, add_url)
1433     {
1434     var a_uids = new Array();
1435     if (this.env.uid)
1436       a_uids[a_uids.length] = this.env.uid;
1437     else
1438       {
1439       var selection = this.message_list.get_selection();
1440       var id;
1441       for (var n=0; n<selection.length; n++)
1442         {
1443         id = selection[n];
1444         a_uids[a_uids.length] = id;
1445         this.message_list.remove_row(id, (n == selection.length-1));
1446         }
1447       }
1448       
1449     // also send search request to get the right messages 
1450     if (this.env.search_request) 
1451       add_url += '&_search='+this.env.search_request;
1452
1453     // send request to server
1454     this.http_post(action, '_uid='+a_uids.join(',')+'&_mbox='+urlencode(this.env.mailbox)+add_url, lock);
1455     };
1456
1457
1458   // set a specific flag to one or more messages
1459   this.mark_message = function(flag, uid)
1460     {
1461     var a_uids = new Array();
1462     var selection = this.message_list ? this.message_list.get_selection() : new Array();
1463     
1464     if (uid)
1465       a_uids[0] = uid;
1466     else if (this.env.uid)
1467       a_uids[0] = this.env.uid;
1468     else if (this.message_list)
1469       {
1470       for (var id, n=0; n<selection.length; n++)
1471         {
1472         id = selection[n];
1473         if ((flag=='read' && this.message_list.rows[id].unread) || (flag=='unread' && !this.message_list.rows[id].unread)
1474             || (flag=='delete' && !this.message_list.rows[id].deleted) || (flag=='undelete' && this.message_list.rows[id].deleted))
1475           a_uids[a_uids.length] = id;
1476         }
1477       }
1478     
1479     // nothing to do
1480     if (!a_uids.length)
1481       return;
1482       
1483     switch (flag)
1484       {
1485         case 'read':
1486         case 'unread':
1487           this.toggle_read_status(flag, a_uids);
1488           break;
1489         case 'delete':
1490         case 'undelete':
1491           this.toggle_delete_status(a_uids);
1492           break;
1493       }
1494     };
1495
1496   // set class to read/unread
1497   this.toggle_read_status = function(flag, a_uids)
1498   {
1499     // mark all message rows as read/unread
1500     var icn_src;
1501     var rows = this.message_list.rows;
1502     for (var i=0; i<a_uids.length; i++)
1503       {
1504       uid = a_uids[i];
1505       if (rows[uid])
1506         {
1507         rows[uid].unread = (flag=='unread' ? true : false);
1508         
1509         if (rows[uid].classname.indexOf('unread')<0 && rows[uid].unread)
1510           {
1511           rows[uid].classname += ' unread';
1512           this.set_classname(rows[uid].obj, 'unread', true);
1513
1514           if (this.env.unreadicon)
1515             icn_src = this.env.unreadicon;
1516           }
1517         else if (!rows[uid].unread)
1518           {
1519           rows[uid].classname = rows[uid].classname.replace(/\s*unread/, '');
1520           this.set_classname(rows[uid].obj, 'unread', false);
1521
1522           if (rows[uid].replied && this.env.repliedicon)
1523             icn_src = this.env.repliedicon;
1524           else if (this.env.messageicon)
1525             icn_src = this.env.messageicon;
1526           }
1527
1528         if (rows[uid].icon && icn_src)
1529           rows[uid].icon.src = icn_src;
1530         }
1531       }
1532       
1533     this.http_post('mark', '_uid='+a_uids.join(',')+'&_flag='+flag);
1534   };
1535   
1536   // mark all message rows as deleted/undeleted
1537   this.toggle_delete_status = function(a_uids)
1538   {
1539     if (this.env.read_when_deleted)
1540       this.toggle_read_status('read',a_uids);
1541
1542     // if deleting message from "view message" don't bother with delete icon
1543     if (this.env.action == "show")
1544       return false;
1545
1546     var rows = this.message_list.rows;
1547     if (a_uids.length==1)
1548     {
1549       if (rows[a_uids[0]] && rows[a_uids[0]].classname.indexOf('deleted') < 0)
1550         this.flag_as_deleted(a_uids);
1551       else
1552         this.flag_as_undeleted(a_uids);
1553
1554       return true;
1555     }
1556     
1557     var all_deleted = true;
1558     for (var i=0; i<a_uids.length; i++)
1559     {
1560       uid = a_uids[i];
1561       if (rows[uid]) {
1562         if (rows[uid].classname.indexOf('deleted')<0)
1563         {
1564           all_deleted = false;
1565           break;
1566         }
1567       }
1568     }
1569     
1570     if (all_deleted)
1571       this.flag_as_undeleted(a_uids);
1572     else
1573       this.flag_as_deleted(a_uids);
1574     
1575     return true;
1576   };
1577
1578
1579   this.flag_as_undeleted = function(a_uids)
1580   {
1581     // if deleting message from "view message" don't bother with delete icon
1582     if (this.env.action == "show")
1583       return false;
1584
1585     var icn_src;
1586     var rows = this.message_list.rows;
1587       
1588     for (var i=0; i<a_uids.length; i++)
1589     {
1590       uid = a_uids[i];
1591       if (rows[uid]) {
1592         rows[uid].deleted = false;
1593         
1594         if (rows[uid].classname.indexOf('deleted') > 0)
1595         {
1596           rows[uid].classname = rows[uid].classname.replace(/\s*deleted/, '');
1597           this.set_classname(rows[uid].obj, 'deleted', false);
1598         }
1599         if (rows[uid].unread && this.env.unreadicon)
1600           icn_src = this.env.unreadicon;
1601         else if (rows[uid].replied && this.env.repliedicon)
1602           icn_src = this.env.repliedicon;
1603         else if (this.env.messageicon)
1604           icn_src = this.env.messageicon;
1605         if (rows[uid].icon && icn_src)
1606           rows[uid].icon.src = icn_src;
1607       }
1608     }
1609
1610     this.http_post('mark', '_uid='+a_uids.join(',')+'&_flag=undelete');
1611     return true;
1612   };
1613
1614   
1615   this.flag_as_deleted = function(a_uids)
1616   {
1617     // if deleting message from "view message" don't bother with delete icon
1618     if (this.env.action == "show")
1619       return false;
1620
1621     var rows = this.message_list.rows;
1622     for (var i=0; i<a_uids.length; i++)
1623     {
1624       uid = a_uids[i];
1625       if (rows[uid]) {
1626         rows[uid].deleted = true;
1627         
1628         if (rows[uid].classname.indexOf('deleted')<0) {
1629           rows[uid].classname += ' deleted';
1630           this.set_classname(rows[uid].obj, 'deleted', true);
1631         }
1632         if (rows[uid].icon && this.env.deletedicon)
1633           rows[uid].icon.src = this.env.deletedicon;
1634       }
1635     }
1636
1637     this.http_post('mark', '_uid='+a_uids.join(',')+'&_flag=delete');
1638     return true;  
1639   };
1640
1641
1642   /*********************************************************/
1643   /*********           login form methods          *********/
1644   /*********************************************************/
1645
1646   // handler for keyboard events on the _user field
1647   this.login_user_keypress = function(e)
1648   {
1649     var key = rcube_event.get_keycode(e);
1650     var elm;
1651
1652     // enter
1653     if ((key==13) && (elm = rcube_find_object('_pass')))
1654     {
1655       elm.focus();
1656       return false;
1657     }
1658   };
1659
1660
1661   /*********************************************************/
1662   /*********        message compose methods        *********/
1663   /*********************************************************/
1664   
1665   
1666   // checks the input fields before sending a message
1667   this.check_compose_input = function()
1668     {
1669     // check input fields
1670     var input_to = rcube_find_object('_to');
1671     var input_subject = rcube_find_object('_subject');
1672     var input_message = rcube_find_object('_message');
1673
1674     // check for empty recipient
1675     if (input_to && !rcube_check_email(input_to.value, true))
1676       {
1677       alert(this.get_label('norecipientwarning'));
1678       input_to.focus();
1679       return false;
1680       }
1681
1682     // display localized warning for missing subject
1683     if (input_subject && input_subject.value == '')
1684       {
1685       var subject = prompt(this.get_label('nosubjectwarning'), this.get_label('nosubject'));
1686
1687       // user hit cancel, so don't send
1688       if (!subject && subject !== '')
1689         {
1690         input_subject.focus();
1691         return false;
1692         }
1693       else
1694         {
1695         input_subject.value = subject ? subject : this.get_label('nosubject');            
1696         }
1697       }
1698
1699     // check for empty body
1700     if ((input_message.value == '' && (!window.tinyMCE || tinyMCE.getContent() == '')) && !confirm(this.get_label('nobodywarning')))
1701       {
1702       input_message.focus();
1703       return false;
1704       }
1705
1706     return true;
1707     };
1708
1709
1710   this.set_spellcheck_state = function(s)
1711     {
1712     this.spellcheck_ready = (s=='check_spelling' || s=='ready');
1713     this.enable_command('spellcheck', this.spellcheck_ready);
1714     };
1715
1716
1717   this.set_draft_id = function(id)
1718     {
1719     var f;
1720     if (f = rcube_find_object('_draft_saveid'))
1721       f.value = id;
1722     };
1723
1724   this.auto_save_start = function()
1725     {
1726     if (this.env.draft_autosave)
1727       this.save_timer = self.setTimeout(function(){ ref.command("savedraft"); }, this.env.draft_autosave * 1000);
1728
1729     // Unlock interface now that saving is complete
1730     this.busy = false;
1731     };
1732
1733
1734   this.compose_field_hash = function(save)
1735     {
1736     // check input fields
1737     var input_to = rcube_find_object('_to');
1738     var input_cc = rcube_find_object('_to');
1739     var input_bcc = rcube_find_object('_to');
1740     var input_subject = rcube_find_object('_subject');
1741     var input_message = rcube_find_object('_message');
1742     
1743     var str = '';
1744     if (input_to && input_to.value)
1745       str += input_to.value+':';
1746     if (input_cc && input_cc.value)
1747       str += input_cc.value+':';
1748     if (input_bcc && input_bcc.value)
1749       str += input_bcc.value+':';
1750     if (input_subject && input_subject.value)
1751       str += input_subject.value+':';
1752     if (input_message && input_message.value)
1753       str += input_message.value;
1754     
1755     if (save)
1756       this.cmp_hash = str;
1757     
1758     return str;
1759     };
1760     
1761   
1762   this.change_identity = function(obj)
1763     {
1764     if (!obj || !obj.options)
1765       return false;
1766
1767     var id = obj.options[obj.selectedIndex].value;
1768     var input_message = rcube_find_object('_message');
1769     var message = input_message ? input_message.value : '';
1770     var is_html = (rcube_find_object('_is_html').value == '1');
1771     var sig, p;
1772
1773     if (!this.env.identity)
1774       this.env.identity = id
1775   
1776     if (!is_html)
1777       {
1778       // remove the 'old' signature
1779       if (this.env.identity && this.env.signatures && this.env.signatures[this.env.identity])
1780         {
1781         sig = this.env.signatures[this.env.identity]['text'];
1782         if (sig.indexOf('-- ')!=0)
1783           sig = '-- \n'+sig;
1784
1785         p = message.lastIndexOf(sig);
1786         if (p>=0)
1787           message = message.substring(0, p-1) + message.substring(p+sig.length, message.length);
1788         }
1789
1790       // add the new signature string
1791       if (this.env.signatures && this.env.signatures[id])
1792         {
1793         sig = this.env.signatures[id]['text'];
1794         if (this.env.signatures[id]['is_html'])
1795           {
1796           sig = this.env.signatures[id]['plain_text'];
1797           }
1798         if (sig.indexOf('-- ')!=0)
1799           sig = '-- \n'+sig;
1800         message += '\n'+sig;
1801         }
1802       }
1803     else
1804       {
1805       var eid = tinyMCE.getEditorId('_message');
1806       // editor is a TinyMCE_Control object
1807       var editor = tinyMCE.getInstanceById(eid);
1808       var msgDoc = editor.getDoc();
1809       var msgBody = msgDoc.body;
1810
1811       if (this.env.signatures && this.env.signatures[id])
1812         {
1813         // Append the signature as a span within the body
1814         var sigElem = msgDoc.getElementById("_rc_sig");
1815         if (!sigElem)
1816           {
1817           sigElem = msgDoc.createElement("span");
1818           sigElem.setAttribute("id", "_rc_sig");
1819           msgBody.appendChild(sigElem);
1820           }
1821         if (this.env.signatures[id]['is_html'])
1822           {
1823           sigElem.innerHTML = this.env.signatures[id]['text'];
1824           }
1825         else
1826           {
1827           sigElem.innerHTML = '<pre>' + this.env.signatures[id]['text'] + '</pre>';
1828           }
1829         }
1830       }
1831
1832     if (input_message)
1833       input_message.value = message;
1834
1835     this.env.identity = id;
1836     return true;
1837     };
1838
1839
1840   this.show_attachment_form = function(a)
1841     {
1842     if (!this.gui_objects.uploadbox)
1843       return false;
1844       
1845     var elm, list;
1846     if (elm = this.gui_objects.uploadbox)
1847       {
1848       if (a &&  (list = this.gui_objects.attachmentlist))
1849         {
1850         var pos = rcube_get_object_pos(list);
1851         var left = pos.x;
1852         var top = pos.y + list.offsetHeight + 10;
1853       
1854         elm.style.top = top+'px';
1855         elm.style.left = left+'px';
1856         }
1857       
1858       elm.style.visibility = a ? 'visible' : 'hidden';
1859       }
1860       
1861     // clear upload form
1862         try {
1863       if (!a && this.gui_objects.attachmentform != this.gui_objects.messageform)
1864         this.gui_objects.attachmentform.reset();
1865         }
1866         catch(e){}  // ignore errors
1867     
1868     return true;  
1869     };
1870
1871
1872   // upload attachment file
1873   this.upload_file = function(form)
1874     {
1875     
1876     if (!form)
1877       return false;
1878       
1879     // get file input fields
1880     var send = false;
1881     for (var n=0; n<form.elements.length; n++)
1882       if (form.elements[n].type=='file' && form.elements[n].value)
1883         {
1884         send = true;
1885         break;
1886         }
1887     
1888     // create hidden iframe and post upload form
1889     if (send)
1890       {
1891       var ts = new Date().getTime();
1892       var frame_name = 'rcmupload'+ts;
1893
1894       // have to do it this way for IE
1895       // otherwise the form will be posted to a new window
1896       if(document.all && !window.opera)
1897         {
1898         var html = '<iframe name="'+frame_name+'" src="program/blank.gif" style="width:0;height:0;visibility:hidden;"></iframe>';
1899         document.body.insertAdjacentHTML('BeforeEnd',html);
1900         }
1901       else  // for standards-compilant browsers
1902         {
1903         var frame = document.createElement('IFRAME');
1904         frame.name = frame_name;
1905         frame.width = 10;
1906         frame.height = 10;
1907         frame.style.visibility = 'hidden';
1908         document.body.appendChild(frame);
1909         }
1910
1911       form.target = frame_name;
1912       form.action = this.env.comm_path+'&_action=upload';
1913       form.setAttribute('enctype', 'multipart/form-data');
1914       form.submit();
1915       }
1916     
1917     // set reference to the form object
1918     this.gui_objects.attachmentform = form;
1919     return true;
1920     };
1921
1922
1923   // add file name to attachment list
1924   // called from upload page
1925   this.add2attachment_list = function(name, content)
1926     {
1927     if (!this.gui_objects.attachmentlist)
1928       return false;
1929       
1930     var li = document.createElement('LI');
1931     li.id = name;
1932     li.innerHTML = content;
1933     this.gui_objects.attachmentlist.appendChild(li);
1934     return true;
1935     };
1936
1937   this.remove_from_attachment_list = function(name)
1938     {
1939     if (!this.gui_objects.attachmentlist)
1940       return false;
1941
1942     var list = this.gui_objects.attachmentlist.getElementsByTagName("li");
1943     for (i=0;i<list.length;i++)
1944       if (list[i].id == name)
1945         this.gui_objects.attachmentlist.removeChild(list[i]);
1946     };
1947
1948   this.remove_attachment = function(name)
1949     {
1950     if (name)
1951       this.http_post('remove-attachment', '_file='+urlencode(name));
1952
1953     return true;
1954     };
1955
1956   // send remote request to add a new contact
1957   this.add_contact = function(value)
1958     {
1959     if (value)
1960       this.http_post('addcontact', '_address='+value);
1961     
1962     return true;
1963     };
1964
1965   // send remote request to search mail or contacts
1966   this.qsearch = function(value)
1967     {
1968     if (value != '')
1969       {
1970       if (this.message_list)
1971         this.message_list.clear();
1972       else if (this.contact_list) {
1973         this.contact_list.clear(true);
1974         this.show_contentframe(false);
1975       }
1976
1977       // reset vars
1978       this.env.current_page = 1;
1979       this.set_busy(true, 'searching');
1980       this.http_request('search', '_q='+urlencode(value)+(this.env.mailbox ? '&_mbox='+this.env.mailbox : '')+(this.env.source ? '&_source='+urlencode(this.env.source) : ''), true);
1981       }
1982     return true;
1983     };
1984
1985   // reset quick-search form
1986   this.reset_qsearch = function()
1987     {
1988     if (this.gui_objects.qsearchbox)
1989       this.gui_objects.qsearchbox.value = '';
1990       
1991     this.env.search_request = null;
1992     return true;
1993     };
1994
1995
1996   this.sent_successfully = function(msg)
1997     {
1998     this.list_mailbox();
1999     this.display_message(msg, 'confirmation', true);
2000     }
2001
2002
2003   /*********************************************************/
2004   /*********     keyboard live-search methods      *********/
2005   /*********************************************************/
2006
2007
2008   // handler for keyboard events on address-fields
2009   this.ksearch_keypress = function(e, obj)
2010     {
2011     if (typeof(this.env.contacts)!='object' || !this.env.contacts.length)
2012       return true;
2013
2014     if (this.ksearch_timer)
2015       clearTimeout(this.ksearch_timer);
2016
2017     var highlight;
2018     var key = rcube_event.get_keycode(e);
2019     var mod = rcube_event.get_modifier(e);
2020
2021     switch (key)
2022       {
2023       case 38:  // key up
2024       case 40:  // key down
2025         if (!this.ksearch_pane)
2026           break;
2027           
2028         var dir = key==38 ? 1 : 0;
2029         var next;
2030         
2031         highlight = document.getElementById('rcmksearchSelected');
2032         if (!highlight)
2033           highlight = this.ksearch_pane.ul.firstChild;
2034         
2035         if (highlight && (next = dir ? highlight.previousSibling : highlight.nextSibling))
2036           {
2037           highlight.removeAttribute('id');
2038           this.set_classname(highlight, 'selected', false);
2039           }
2040
2041         if (next)
2042           {
2043           next.setAttribute('id', 'rcmksearchSelected');
2044           this.set_classname(next, 'selected', true);
2045           this.ksearch_selected = next._rcm_id;
2046           }
2047
2048         return rcube_event.cancel(e);
2049
2050       case 9:  // tab
2051         if(mod == SHIFT_KEY)
2052           break;
2053
2054       case 13:  // enter     
2055         if (this.ksearch_selected===null || !this.ksearch_input || !this.ksearch_value)
2056           break;
2057
2058         // insert selected address and hide ksearch pane
2059         this.insert_recipient(this.ksearch_selected);
2060         this.ksearch_hide();
2061
2062         return rcube_event.cancel(e);
2063
2064       case 27:  // escape
2065         this.ksearch_hide();
2066         break;
2067
2068       }
2069
2070     // start timer
2071     this.ksearch_timer = setTimeout(function(){ ref.ksearch_get_results(); }, 200);
2072     this.ksearch_input = obj;
2073     
2074     return true;
2075     };
2076
2077
2078   this.insert_recipient = function(id)
2079   {
2080     if (!this.env.contacts[id] || !this.ksearch_input)
2081       return;
2082     
2083     // get cursor pos
2084     var inp_value = this.ksearch_input.value.toLowerCase();
2085     var cpos = this.get_caret_pos(this.ksearch_input);
2086     var p = inp_value.lastIndexOf(this.ksearch_value, cpos);
2087     
2088     // replace search string with full address
2089     var pre = this.ksearch_input.value.substring(0, p);
2090     var end = this.ksearch_input.value.substring(p+this.ksearch_value.length, this.ksearch_input.value.length);
2091     var insert  = this.env.contacts[id]+', ';
2092     this.ksearch_input.value = pre + insert + end;
2093     
2094     // set caret to insert pos
2095     cpos = p+insert.length;
2096     if (this.ksearch_input.setSelectionRange)
2097       this.ksearch_input.setSelectionRange(cpos, cpos);
2098     
2099   };
2100
2101
2102   // address search processor
2103   this.ksearch_get_results = function()
2104     {
2105     var inp_value = this.ksearch_input ? this.ksearch_input.value : null;
2106     if (inp_value===null)
2107       return;
2108
2109     // get string from current cursor pos to last comma
2110     var cpos = this.get_caret_pos(this.ksearch_input);
2111     var p = inp_value.lastIndexOf(',', cpos-1);
2112     var q = inp_value.substring(p+1, cpos);
2113
2114     // trim query string
2115     q = q.replace(/(^\s+|\s+$)/g, '').toLowerCase();
2116
2117     if (!q.length || q==this.ksearch_value)
2118       {
2119       if (!q.length && this.ksearch_pane && this.ksearch_pane.visible)
2120         this.ksearch_pane.show(0);
2121
2122       return;
2123       }
2124
2125     this.ksearch_value = q;
2126     
2127     // start searching the contact list
2128     var a_results = new Array();
2129     var a_result_ids = new Array();
2130     var c=0;
2131     for (var i=0; i<this.env.contacts.length; i++)
2132       {
2133       if (this.env.contacts[i].toLowerCase().indexOf(q)>=0)
2134         {
2135         a_results[c] = this.env.contacts[i];
2136         a_result_ids[c++] = i;
2137         
2138         if (c==15)  // limit search results
2139           break;
2140         }
2141       }
2142
2143     // display search results
2144     if (c && a_results.length)
2145       {
2146       var p, ul, li;
2147       
2148       // create results pane if not present
2149       if (!this.ksearch_pane)
2150         {
2151         ul = document.createElement('UL');
2152         this.ksearch_pane = new rcube_layer('rcmKSearchpane', {vis:0, zindex:30000});
2153         this.ksearch_pane.elm.appendChild(ul);
2154         this.ksearch_pane.ul = ul;
2155         }
2156       else
2157         ul = this.ksearch_pane.ul;
2158
2159       // remove all search results
2160       ul.innerHTML = '';
2161             
2162       // add each result line to list
2163       for (i=0; i<a_results.length; i++)
2164         {
2165         li = document.createElement('LI');
2166         li.innerHTML = a_results[i].replace(/</, '&lt;').replace(/>/, '&gt;');
2167         li.onmousedown = function(e){ ref.insert_recipient(this._rcm_id); ref.ksearch_pane.show(0); return rcube_event.cancel(e); };
2168         li.style.cursor = 'pointer';
2169         li._rcm_id = a_result_ids[i];
2170         ul.appendChild(li);
2171         }
2172
2173       // check if last selected item is still in result list
2174       if (this.ksearch_selected!==null)
2175         {
2176         p = find_in_array(this.ksearch_selected, a_result_ids);
2177         if (p>=0 && ul.childNodes)
2178           {
2179           ul.childNodes[p].setAttribute('id', 'rcmksearchSelected');
2180           this.set_classname(ul.childNodes[p], 'selected', true);
2181           }
2182         else
2183           this.ksearch_selected = null;
2184         }
2185       
2186       // if no item selected, select the first one
2187       if (this.ksearch_selected===null)
2188         {
2189         ul.firstChild.setAttribute('id', 'rcmksearchSelected');
2190         this.set_classname(ul.firstChild, 'selected', true);
2191         this.ksearch_selected = a_result_ids[0];
2192         }
2193
2194       // move the results pane right under the input box and make it visible
2195       var pos = rcube_get_object_pos(this.ksearch_input);
2196       this.ksearch_pane.move(pos.x, pos.y+this.ksearch_input.offsetHeight);
2197       this.ksearch_pane.show(1); 
2198       }
2199     // hide results pane
2200     else
2201       this.ksearch_hide();
2202     };
2203
2204
2205   this.ksearch_blur = function(e, obj)
2206     {
2207     if (this.ksearch_timer)
2208       clearTimeout(this.ksearch_timer);
2209
2210     this.ksearch_value = '';      
2211     this.ksearch_input = null;
2212     
2213     this.ksearch_hide();
2214     };
2215
2216
2217   this.ksearch_hide = function()
2218     {
2219     this.ksearch_selected = null;
2220     
2221     if (this.ksearch_pane)
2222       this.ksearch_pane.show(0);    
2223     };
2224
2225
2226
2227   /*********************************************************/
2228   /*********         address book methods          *********/
2229   /*********************************************************/
2230
2231
2232   this.contactlist_keypress = function(list)
2233     {
2234       if (list.key_pressed == list.DELETE_KEY)
2235         this.command('delete');
2236     };
2237
2238
2239   this.contactlist_select = function(list)
2240     {
2241       if (this.preview_timer)
2242         clearTimeout(this.preview_timer);
2243
2244       var id, frame, ref = this;
2245       if (id = list.get_single_selection())
2246         this.preview_timer = setTimeout(function(){ ref.load_contact(id, 'show'); }, this.dblclick_time + 10);
2247       else if (this.env.contentframe)
2248         this.show_contentframe(false);
2249
2250       this.enable_command('edit', id?true:false);
2251       this.enable_command('compose', list.selection.length > 0);
2252       this.enable_command('delete', list.selection.length && this.env.address_sources && !this.env.address_sources[this.env.source].readonly);
2253
2254       return false;
2255     };
2256
2257
2258   this.list_contacts = function(src, page)
2259     {
2260     var add_url = '';
2261     var target = window;
2262     
2263     if (!src)
2264       src = this.env.source;
2265     
2266     if (page && this.current_page==page && src == this.env.source)
2267       return false;
2268       
2269     if (src != this.env.source)
2270       {
2271       page = 1;
2272       this.env.current_page = page;
2273       this.reset_qsearch();
2274       }
2275
2276     this.select_folder(src, this.env.source);
2277     this.env.source = src;
2278
2279     // load contacts remotely
2280     if (this.gui_objects.contactslist)
2281       {
2282       this.list_contacts_remote(src, page);
2283       return;
2284       }
2285
2286     if (this.env.contentframe && window.frames && window.frames[this.env.contentframe])
2287       {
2288       target = window.frames[this.env.contentframe];
2289       add_url = '&_framed=1';
2290       }
2291
2292     // also send search request to get the correct listing
2293     if (this.env.search_request)
2294       add_url += '&_search='+this.env.search_request;
2295
2296     this.set_busy(true, 'loading');
2297     target.location.href = this.env.comm_path+(src ? '&_source='+urlencode(src) : '')+(page ? '&_page='+page : '')+add_url;
2298     };
2299
2300
2301   // send remote request to load contacts list
2302   this.list_contacts_remote = function(src, page)
2303     {
2304     // clear message list first
2305     this.contact_list.clear(true);
2306     this.show_contentframe(false);
2307     this.enable_command('delete', 'compose', false);
2308
2309     // send request to server
2310     var url = (src ? '_source='+urlencode(src) : '') + (page ? (src?'&':'') + '_page='+page : '');
2311     this.env.source = src;
2312     
2313     // also send search request to get the right messages 
2314     if (this.env.search_request) 
2315       url += '&_search='+this.env.search_request;
2316
2317     this.set_busy(true, 'loading');
2318     this.http_request('list', url, true);
2319     };
2320
2321
2322   // load contact record
2323   this.load_contact = function(cid, action, framed)
2324     {
2325     var add_url = '';
2326     var target = window;
2327     if (this.env.contentframe && window.frames && window.frames[this.env.contentframe])
2328       {
2329       add_url = '&_framed=1';
2330       target = window.frames[this.env.contentframe];
2331       this.show_contentframe(true);
2332       }
2333     else if (framed)
2334       return false;
2335       
2336     if (action && (cid || action=='add') && !this.drag_active)
2337       {
2338       this.set_busy(true);
2339       target.location.href = this.env.comm_path+'&_action='+action+'&_source='+urlencode(this.env.source)+'&_cid='+urlencode(cid) + add_url;
2340       }
2341     return true;
2342     };
2343
2344   // copy a contact to the specified target (group or directory)
2345   this.copy_contact = function(cid, to)
2346   {
2347     if (!cid)
2348       cid = this.contact_list.get_selection().join(',');
2349
2350     if (to != this.env.source && cid && this.env.address_sources[to] && !this.env.address_sources[to].readonly)
2351       this.http_post('copy', '_cid='+urlencode(cid)+'&_source='+urlencode(this.env.source)+'&_to='+urlencode(to));
2352   };
2353
2354
2355   this.delete_contacts = function()
2356     {
2357     // exit if no mailbox specified or if selection is empty
2358     var selection = this.contact_list.get_selection();
2359     if (!(selection.length || this.env.cid) || !confirm(this.get_label('deletecontactconfirm')))
2360       return;
2361       
2362     var a_cids = new Array();
2363
2364     if (this.env.cid)
2365       a_cids[a_cids.length] = this.env.cid;
2366     else
2367       {
2368       var id;
2369       for (var n=0; n<selection.length; n++)
2370         {
2371         id = selection[n];
2372         a_cids[a_cids.length] = id;
2373         this.contact_list.remove_row(id, (n == selection.length-1));
2374         }
2375
2376       // hide content frame if we delete the currently displayed contact
2377       if (selection.length == 1)
2378         this.show_contentframe(false);
2379       }
2380
2381     // send request to server
2382     this.http_post('delete', '_cid='+urlencode(a_cids.join(','))+'&_from='+(this.env.action ? this.env.action : ''));
2383     return true;
2384     };
2385
2386
2387   // update a contact record in the list
2388   this.update_contact_row = function(cid, cols_arr)
2389     {
2390     var row;
2391     if (this.contact_list.rows[cid] && (row = this.contact_list.rows[cid].obj))
2392       {
2393       for (var c=0; c<cols_arr.length; c++)
2394         if (row.cells[c])
2395           row.cells[c].innerHTML = cols_arr[c];
2396
2397       return true;
2398       }
2399
2400     return false;
2401     };
2402
2403
2404   /*********************************************************/
2405   /*********        user settings methods          *********/
2406   /*********************************************************/
2407
2408   this.init_subscription_list = function()
2409     {
2410     var p = this;
2411     this.subscription_list = new rcube_list_widget(this.gui_objects.subscriptionlist, {multiselect:false, draggable:true, keyboard:false, toggleselect:true});
2412     this.subscription_list.addEventListener('select', function(o){ p.subscription_select(o); });
2413     this.subscription_list.addEventListener('dragstart', function(o){ p.drag_active = true; });
2414     this.subscription_list.addEventListener('dragend', function(o){ p.subscription_move_folder(o); });
2415     this.subscription_list.row_init = function (row)
2416       {
2417       var anchors = row.obj.getElementsByTagName('A');
2418       if (anchors[0])
2419         anchors[0].onclick = function() { p.rename_folder(row.id); };
2420       if (anchors[1])
2421         anchors[1].onclick = function() { p.delete_folder(row.id); };
2422       row.obj.onmouseover = function() { p.focus_subscription(row.id); };
2423       row.obj.onmouseout = function() { p.unfocus_subscription(row.id); };
2424       }
2425     this.subscription_list.init();
2426     }
2427
2428   this.identity_select = function(list)
2429     {
2430     var id;
2431     if (id = list.get_single_selection())
2432       this.load_identity(id, 'edit-identity');
2433     };
2434
2435   // load contact record
2436   this.load_identity = function(id, action)
2437     {
2438     if (action=='edit-identity' && (!id || id==this.env.iid))
2439       return false;
2440
2441     var add_url = '';
2442     var target = window;
2443     if (this.env.contentframe && window.frames && window.frames[this.env.contentframe])
2444       {
2445       add_url = '&_framed=1';
2446       target = window.frames[this.env.contentframe];
2447       document.getElementById(this.env.contentframe).style.visibility = 'inherit';
2448       }
2449
2450     if (action && (id || action=='add-identity'))
2451       {
2452       this.set_busy(true);
2453       target.location.href = this.env.comm_path+'&_action='+action+'&_iid='+id+add_url;
2454       }
2455     return true;
2456     };
2457
2458
2459   this.delete_identity = function(id)
2460     {
2461     // exit if no mailbox specified or if selection is empty
2462     var selection = this.identity_list.get_selection();
2463     if (!(selection.length || this.env.iid))
2464       return;
2465     
2466     if (!id)
2467       id = this.env.iid ? this.env.iid : selection[0];
2468
2469     // if (this.env.framed && id)
2470     this.goto_url('delete-identity', '_iid='+id, true);
2471     return true;
2472     };
2473
2474
2475   this.focus_subscription = function(id)
2476     {
2477     var row, folder;
2478     var reg = RegExp('['+RegExp.escape(this.env.delimiter)+']?[^'+RegExp.escape(this.env.delimiter)+']+$');
2479
2480     if (this.drag_active && (row = document.getElementById(id)))
2481       if (this.env.subscriptionrows[id] &&
2482           (folder = this.env.subscriptionrows[id][0]))
2483         {
2484         if (this.check_droptarget(folder) &&
2485             (folder != this.env.folder.replace(reg, '')) &&
2486             (!folder.match(new RegExp('^'+RegExp.escape(this.env.folder+this.env.delimiter)))))
2487           {
2488           this.set_env('dstfolder', folder);
2489           this.set_classname(row, 'droptarget', true);
2490           }
2491         }
2492       else if (this.env.folder.match(new RegExp(RegExp.escape(this.env.delimiter))))
2493         {
2494         this.set_env('dstfolder', this.env.delimiter);
2495         this.set_classname(this.subscription_list.frame, 'droptarget', true);
2496         }
2497     }
2498
2499
2500   this.unfocus_subscription = function(id)
2501     {
2502       var row;
2503       this.set_env('dstfolder', null);
2504       if (this.env.subscriptionrows[id] &&
2505           (row = document.getElementById(id)))
2506         this.set_classname(row, 'droptarget', false);
2507       else
2508         this.set_classname(this.subscription_list.frame, 'droptarget', false);
2509     }
2510
2511
2512   this.subscription_select = function(list)
2513     {
2514     var id, folder;
2515     if ((id = list.get_single_selection()) &&
2516         this.env.subscriptionrows['rcmrow'+id] &&
2517         (folder = this.env.subscriptionrows['rcmrow'+id][0]) &&
2518         (find_in_array(this.env.defaultfolders, folder)!=0))
2519       this.set_env('folder', folder);
2520     else
2521       this.set_env('folder', null);
2522     };
2523
2524
2525   this.subscription_move_folder = function(list)
2526     {
2527     var reg = RegExp('['+RegExp.escape(this.env.delimiter)+']?[^'+RegExp.escape(this.env.delimiter)+']+$');
2528     if (this.env.folder && this.env.dstfolder && (this.env.dstfolder != this.env.folder) &&
2529         (this.env.dstfolder != this.env.folder.replace(reg, '')))
2530       {
2531       var reg = new RegExp('[^'+RegExp.escape(this.env.delimiter)+']*['+RegExp.escape(this.env.delimiter)+']', 'g');
2532       var basename = this.env.folder.replace(reg, '');
2533       var newname = this.env.dstfolder==this.env.delimiter ? basename : this.env.dstfolder+this.env.delimiter+basename;
2534       this.http_post('rename-folder', '_folder_oldname='+urlencode(this.env.folder)+'&_folder_newname='+urlencode(newname));
2535       }
2536     this.drag_active = false;
2537     this.unfocus_subscription(this.get_folder_row_id(this.env.dstfolder));
2538     };
2539
2540
2541   // tell server to create and subscribe a new mailbox
2542   this.create_folder = function(name)
2543     {
2544   if (this.edit_folder)
2545     this.reset_folder_rename();
2546
2547     var form;
2548     if ((form = this.gui_objects.editform) && form.elements['_folder_name'])
2549       name = form.elements['_folder_name'].value;
2550     if (this.env.folder)
2551       name = this.env.folder+this.env.delimiter+name;
2552
2553     if (name)
2554       this.http_post('create-folder', '_name='+urlencode(name), true);
2555     else if (form.elements['_folder_name'])
2556       form.elements['_folder_name'].focus();
2557     };
2558
2559
2560   // start renaming the mailbox name.
2561   // this will replace the name string with an input field
2562   this.rename_folder = function(id)
2563     {
2564     var temp, row, form;
2565     var folder = this.env.subscriptionrows[id][0];
2566
2567     // reset current renaming
2568   if (temp = this.edit_folder)
2569     {
2570     this.reset_folder_rename();
2571     if (temp == id)
2572       return;
2573     }
2574
2575     if (id && (row = document.getElementById(id)))
2576       {
2577       var reg = new RegExp('.*['+RegExp.escape(this.env.delimiter)+']');
2578       this.name_input = document.createElement('INPUT');
2579       this.name_input.value = folder.replace(reg, '');
2580       this.name_input.style.width = '100%';
2581       reg = new RegExp('['+RegExp.escape(this.env.delimiter)+']?[^'+RegExp.escape(this.env.delimiter)+']+$');
2582       this.name_input.setAttribute('parent', folder.replace(reg, ''));
2583       this.name_input.onkeypress = function(e){ rcmail.name_input_keypress(e); };
2584       
2585       row.cells[0].replaceChild(this.name_input, row.cells[0].firstChild);
2586       this.edit_folder = id;
2587       this.name_input.select();
2588       
2589       if (form = this.gui_objects.editform)
2590         form.onsubmit = function(){ return false; };
2591       }
2592     };
2593
2594
2595   // remove the input field and write the current mailbox name to the table cell
2596   this.reset_folder_rename = function()
2597     {
2598     var cell = this.name_input ? this.name_input.parentNode : null;
2599     if (cell && this.edit_folder && this.env.subscriptionrows[this.edit_folder])
2600       {
2601       var reg = new RegExp('[^'+RegExp.escape(this.env.delimiter)+']*['+RegExp.escape(this.env.delimiter)+']', 'g');
2602       cell.innerHTML = this.env.subscriptionrows[this.edit_folder][1].replace(reg, '&nbsp;&nbsp;&nbsp;&nbsp;');
2603       }
2604       
2605     this.edit_folder = null;
2606     };
2607
2608
2609   // handler for keyboard events on the input field
2610   this.name_input_keypress = function(e)
2611     {
2612     var key = rcube_event.get_keycode(e);
2613
2614     // enter
2615     if (key==13)
2616       {
2617       var newname = this.name_input ? this.name_input.value : null;
2618       if (this.edit_folder && newname)
2619         {
2620         if (this.name_input.getAttribute('parent') && this.name_input.getAttribute('parent')!='')
2621           newname = this.name_input.getAttribute('parent')+this.env.delimiter+newname;
2622           this.http_post('rename-folder', '_folder_oldname='+urlencode(this.env.subscriptionrows[this.edit_folder][0])+'&_folder_newname='+urlencode(newname));
2623         }
2624       }
2625     // escape
2626     else if (key==27)
2627       this.reset_folder_rename();
2628     };
2629
2630
2631   // delete a specific mailbox with all its messages
2632   this.delete_folder = function(id)
2633     {
2634     var folder = this.env.subscriptionrows[id][0];
2635
2636     if (this.edit_folder)
2637       this.reset_folder_rename();
2638
2639     if (folder && confirm(this.get_label('deletefolderconfirm')))
2640       {
2641       this.http_post('delete-folder', '_mboxes='+urlencode(folder));
2642       this.set_env('folder', null);
2643       }
2644     };
2645
2646
2647   // add a new folder to the subscription list by cloning a folder row
2648   this.add_folder_row = function(name, display_name, replace)
2649     {
2650     name = name.replace('\\',"");
2651     if (!this.gui_objects.subscriptionlist)
2652       return false;
2653
2654     for (var refid in this.env.subscriptionrows)
2655       if (this.env.subscriptionrows[refid]!=null)
2656         break;
2657
2658     var refrow, form;
2659     var tbody = this.gui_objects.subscriptionlist.tBodies[0];
2660     var id = replace && replace.id ? replace.id : 'rcmrow'+(tbody.childNodes.length+1);
2661     var selection = this.subscription_list.get_single_selection();
2662
2663     if (!id || !(refrow = document.getElementById(refid)))
2664       {
2665       // Refresh page if we don't have a table row to clone
2666       this.goto_url('folders');
2667       }
2668     else
2669       {
2670       // clone a table row if there are existing rows
2671       var row = this.clone_table_row(refrow);
2672       row.id = id;
2673       if (replace)
2674         tbody.replaceChild(row, replace);
2675       else
2676         tbody.appendChild(row);
2677       }
2678
2679     // add to folder/row-ID map
2680     this.env.subscriptionrows[row.id] = [name, display_name];
2681
2682     // set folder name
2683     row.cells[0].innerHTML = display_name;
2684     if (row.cells[1] && row.cells[1].firstChild.tagName=='INPUT')
2685       {
2686       row.cells[1].firstChild.value = name;
2687       row.cells[1].firstChild.checked = true;
2688       }
2689        
2690     // add new folder to rename-folder list and clear input field
2691     if (!replace && (form = this.gui_objects.editform))
2692       {
2693       if (form.elements['_folder_oldname'])
2694         form.elements['_folder_oldname'].options[form.elements['_folder_oldname'].options.length] = new Option(name,name);
2695       if (form.elements['_folder_name'])
2696         form.elements['_folder_name'].value = ''; 
2697       }
2698
2699     this.sort_subscription_list();
2700     this.init_subscription_list();
2701     if (selection && document.getElementById('rcmrow'+selection))
2702       this.subscription_list.select_row(selection);
2703
2704     if (document.getElementById(id).scrollIntoView)
2705       document.getElementById(id).scrollIntoView();
2706     };
2707
2708
2709   // replace an existing table row with a new folder line
2710   this.replace_folder_row = function(oldfolder, newfolder, display_name)
2711     {
2712     var id = this.get_folder_row_id(oldfolder);
2713     var row = document.getElementById(id);
2714     
2715     // replace an existing table row (if found)
2716     this.add_folder_row(newfolder, display_name, row);
2717     
2718     // rename folder in rename-folder dropdown
2719     var form, elm;
2720     if ((form = this.gui_objects.editform) && (elm = form.elements['_folder_oldname']))
2721       {
2722       for (var i=0;i<elm.options.length;i++)
2723         {
2724         if (elm.options[i].value == oldfolder)
2725           {
2726           elm.options[i].text = display_name;
2727           elm.options[i].value = newfolder;
2728           break;
2729           }
2730         }
2731
2732       form.elements['_folder_newname'].value = '';
2733       }
2734     };
2735     
2736
2737   // remove the table row of a specific mailbox from the table
2738   // (the row will not be removed, just hidden)
2739   this.remove_folder_row = function(folder)
2740     {
2741     var row;
2742     var id = this.get_folder_row_id(folder);
2743     if (id && (row = document.getElementById(id)))
2744       row.style.display = 'none';    
2745
2746     // remove folder from rename-folder list
2747     var form;
2748     if ((form = this.gui_objects.editform) && form.elements['_folder_oldname'])
2749       {
2750       for (var i=0;i<form.elements['_folder_oldname'].options.length;i++)
2751         {
2752         if (form.elements['_folder_oldname'].options[i].value == folder) 
2753           {
2754           form.elements['_folder_oldname'].options[i] = null;
2755           break;
2756           }
2757         }
2758       }
2759     
2760     if (form && form.elements['_folder_newname'])
2761       form.elements['_folder_newname'].value = '';
2762     };
2763
2764
2765   this.subscribe_folder = function(folder)
2766     {
2767     var form;
2768     if ((form = this.gui_objects.editform) && form.elements['_unsubscribed'])
2769       this.change_subscription('_unsubscribed', '_subscribed', 'subscribe');
2770     else if (folder)
2771       this.http_post('subscribe', '_mboxes='+urlencode(folder));
2772     };
2773
2774
2775   this.unsubscribe_folder = function(folder)
2776     {
2777     var form;
2778     if ((form = this.gui_objects.editform) && form.elements['_subscribed'])
2779       this.change_subscription('_subscribed', '_unsubscribed', 'unsubscribe');
2780     else if (folder)
2781       this.http_post('unsubscribe', '_mboxes='+urlencode(folder));
2782     };
2783     
2784
2785   this.change_subscription = function(from, to, action)
2786     {
2787     var form;
2788     if (form = this.gui_objects.editform)
2789       {
2790       var a_folders = new Array();
2791       var list_from = form.elements[from];
2792
2793       for (var i=0; list_from && i<list_from.options.length; i++)
2794         {
2795         if (list_from.options[i] && list_from.options[i].selected)
2796           {
2797           a_folders[a_folders.length] = list_from.options[i].value;
2798           list_from[i] = null;
2799           i--;
2800           }
2801         }
2802
2803       // yes, we have some folders selected
2804       if (a_folders.length)
2805         {
2806         var list_to = form.elements[to];
2807         var index;
2808         
2809         for (var n=0; n<a_folders.length; n++)
2810           {
2811           index = list_to.options.length;
2812           list_to[index] = new Option(a_folders[n]);
2813           }
2814           
2815         this.http_post(action, '_mboxes='+urlencode(a_folders.join(',')));
2816         }
2817       }
2818       
2819     };
2820
2821   // helper method to find a specific mailbox row ID
2822   this.get_folder_row_id = function(folder)
2823     {
2824     for (var id in this.env.subscriptionrows)
2825       if (this.env.subscriptionrows[id] && this.env.subscriptionrows[id][0] == folder)
2826         break;
2827         
2828     return id;
2829     };
2830
2831   // duplicate a specific table row
2832   this.clone_table_row = function(row)
2833     {
2834     var cell, td;
2835     var new_row = document.createElement('TR');
2836     for(var n=0; n<row.childNodes.length; n++)
2837       {
2838       cell = row.childNodes[n];
2839       td = document.createElement('TD');
2840
2841       if (cell.className)
2842         td.className = cell.className;
2843       if (cell.align)
2844         td.setAttribute('align', cell.align);
2845         
2846       td.innerHTML = cell.innerHTML;
2847       new_row.appendChild(td);
2848       }
2849     
2850     return new_row;
2851     };
2852
2853   // sort subscription folder list
2854   this.sort_subscription_list = function()
2855     {
2856     var index = new Array();
2857     var tbody = this.gui_objects.subscriptionlist.tBodies[0];
2858     var swapped = false;
2859     for (var i = 0; i<tbody.childNodes.length; i++)
2860       if (this.env.subscriptionrows[tbody.childNodes[i].id]!=null)
2861         index.push(i);
2862     for (i = 0; i<(index.length-1); i++)
2863       {
2864       var one = tbody.childNodes[index[i]];
2865       var two = tbody.childNodes[index[i+1]];
2866       if (this.env.subscriptionrows[one.id][0].toLowerCase()>
2867           this.env.subscriptionrows[two.id][0].toLowerCase())
2868         {
2869         var swap = one.cloneNode(true);
2870         tbody.replaceChild(swap, two);
2871         tbody.replaceChild(two, one);
2872         swapped = true;
2873         }
2874       }
2875     if (swapped)
2876       this.sort_subscription_list();
2877     };
2878
2879
2880   /*********************************************************/
2881   /*********           GUI functionality           *********/
2882   /*********************************************************/
2883
2884
2885   // eable/disable buttons for page shifting
2886   this.set_page_buttons = function()
2887     {
2888     this.enable_command('nextpage', (this.env.pagecount > this.env.current_page));
2889     this.enable_command('lastpage', (this.env.pagecount > this.env.current_page));
2890     this.enable_command('previouspage', (this.env.current_page > 1));
2891     this.enable_command('firstpage', (this.env.current_page > 1));
2892     }
2893
2894
2895   // set button to a specific state
2896   this.set_button = function(command, state)
2897     {
2898     var a_buttons = this.buttons[command];
2899     var button, obj;
2900
2901     if(!a_buttons || !a_buttons.length)
2902       return;
2903
2904     for(var n=0; n<a_buttons.length; n++)
2905       {
2906       button = a_buttons[n];
2907       obj = document.getElementById(button.id);
2908
2909       // get default/passive setting of the button
2910       if (obj && button.type=='image' && !button.status) {
2911         button.pas = obj._original_src ? obj._original_src : obj.src;
2912         // respect PNG fix on IE browsers
2913         if (obj.runtimeStyle && obj.runtimeStyle.filter && obj.runtimeStyle.filter.match(/src=['"]([^'"]+)['"]/))
2914           button.pas = RegExp.$1;
2915       }
2916       else if (obj && !button.status)
2917         button.pas = String(obj.className);
2918
2919       // set image according to button state
2920       if (obj && button.type=='image' && button[state])
2921         {
2922         button.status = state;        
2923         obj.src = button[state];
2924         }
2925       // set class name according to button state
2926       else if (obj && typeof(button[state])!='undefined')
2927         {
2928         button.status = state;        
2929         obj.className = button[state];        
2930         }
2931       // disable/enable input buttons
2932       if (obj && button.type=='input')
2933         {
2934         button.status = state;
2935         obj.disabled = !state;
2936         }
2937       }
2938     };
2939
2940   // display a specific alttext
2941   this.set_alttext = function(command, label)
2942     {
2943       if (!this.buttons[command] || !this.buttons[command].length)
2944         return;
2945       
2946       var button, obj, link;
2947       for (var n=0; n<this.buttons[command].length; n++)
2948       {
2949         button = this.buttons[command][n];
2950         obj = document.getElementById(button.id);
2951         
2952         if (button.type=='image' && obj)
2953         {
2954           obj.setAttribute('alt', this.get_label(label));
2955           if ((link = obj.parentNode) && link.tagName == 'A')
2956             link.setAttribute('title', this.get_label(label));
2957         }
2958         else if (obj)
2959           obj.setAttribute('title', this.get_label(label));
2960       }
2961     };
2962
2963   // mouse over button
2964   this.button_over = function(command, id)
2965     {
2966     var a_buttons = this.buttons[command];
2967     var button, img;
2968
2969     if(!a_buttons || !a_buttons.length)
2970       return;
2971
2972     for(var n=0; n<a_buttons.length; n++)
2973       {
2974       button = a_buttons[n];
2975       if(button.id==id && button.status=='act')
2976         {
2977         img = document.getElementById(button.id);
2978         if (img && button.over)
2979           img.src = button.over;
2980         }
2981       }
2982     };
2983
2984   // mouse down on button
2985   this.button_sel = function(command, id)
2986     {
2987     var a_buttons = this.buttons[command];
2988     var button, img;
2989
2990     if(!a_buttons || !a_buttons.length)
2991       return;
2992
2993     for(var n=0; n<a_buttons.length; n++)
2994       {
2995       button = a_buttons[n];
2996       if(button.id==id && button.status=='act')
2997         {
2998         img = document.getElementById(button.id);
2999         if (img && button.sel)
3000           img.src = button.sel;
3001         }
3002       }
3003     };
3004
3005   // mouse out of button
3006   this.button_out = function(command, id)
3007     {
3008     var a_buttons = this.buttons[command];
3009     var button, img;
3010
3011     if(!a_buttons || !a_buttons.length)
3012       return;
3013
3014     for(var n=0; n<a_buttons.length; n++)
3015       {
3016       button = a_buttons[n];
3017       if(button.id==id && button.status=='act')
3018         {
3019         img = document.getElementById(button.id);
3020         if (img && button.act)
3021           img.src = button.act;
3022         }
3023       }
3024     };
3025
3026
3027   // set/unset a specific class name
3028   this.set_classname = function(obj, classname, set)
3029     {
3030     var reg = new RegExp('\s*'+classname, 'i');
3031     if (!set && obj.className.match(reg))
3032       obj.className = obj.className.replace(reg, '');
3033     else if (set && !obj.className.match(reg))
3034       obj.className += ' '+classname;
3035     };
3036
3037
3038   // write to the document/window title
3039   this.set_pagetitle = function(title)
3040   {
3041     if (title && document.title)
3042       document.title = title;
3043   }
3044
3045
3046   // display a system message
3047   this.display_message = function(msg, type, hold)
3048     {
3049     if (!this.loaded)  // save message in order to display after page loaded
3050       {
3051       this.pending_message = new Array(msg, type);
3052       return true;
3053       }
3054
3055     // pass command to parent window
3056     if (this.env.framed && parent.rcmail)
3057       return parent.rcmail.display_message(msg, type, hold);
3058
3059     if (!this.gui_objects.message)
3060       return false;
3061
3062     if (this.message_timer)
3063       clearTimeout(this.message_timer);
3064     
3065     var cont = msg;
3066     if (type)
3067       cont = '<div class="'+type+'">'+cont+'</div>';
3068
3069     var _rcube = this;
3070     this.gui_objects.message.innerHTML = cont;
3071     this.gui_objects.message.style.display = 'block';
3072     
3073     if (type!='loading')
3074       this.gui_objects.message.onmousedown = function(){ _rcube.hide_message(); return true; };
3075     
3076     if (!hold)
3077       this.message_timer = setTimeout(function(){ ref.hide_message(); }, this.message_time);
3078     };
3079
3080
3081   // make a message row disapear
3082   this.hide_message = function()
3083     {
3084     if (this.gui_objects.message)
3085       {
3086       this.gui_objects.message.style.display = 'none';
3087       this.gui_objects.message.onmousedown = null;
3088       }
3089     };
3090
3091
3092   // mark a mailbox as selected and set environment variable
3093   this.select_folder = function(name, old)
3094   {
3095     if (this.gui_objects.folderlist)
3096     {
3097       var current_li, target_li;
3098       
3099       if ((current_li = this.get_folder_li(old)))
3100       {
3101         this.set_classname(current_li, 'selected', false);
3102         this.set_classname(current_li, 'unfocused', false);
3103       }
3104
3105       if ((target_li = this.get_folder_li(name)))
3106       {
3107         this.set_classname(target_li, 'unfocused', false);
3108         this.set_classname(target_li, 'selected', true);
3109       }
3110     }
3111   };
3112
3113   // helper method to find a folder list item
3114   this.get_folder_li = function(name)
3115   {
3116     if (this.gui_objects.folderlist)
3117     {
3118       name = String(name).replace(this.identifier_expr, '');
3119       return document.getElementById('rcmli'+name);
3120     }
3121
3122     return null;
3123   };
3124
3125
3126   // for reordering column array, Konqueror workaround
3127   this.set_message_coltypes = function(coltypes) 
3128   { 
3129     this.coltypes = coltypes;
3130     
3131     // set correct list titles
3132     var cell, col;
3133     var thead = this.gui_objects.messagelist ? this.gui_objects.messagelist.tHead : null;
3134     for (var n=0; thead && n<this.coltypes.length; n++) 
3135       {
3136       col = this.coltypes[n];
3137       if ((cell = thead.rows[0].cells[n+1]) && (col=='from' || col=='to'))
3138         {
3139         // if we have links for sorting, it's a bit more complicated...
3140         if (cell.firstChild && cell.firstChild.tagName=='A')
3141           {
3142           cell.firstChild.innerHTML = this.get_label(this.coltypes[n]);
3143           cell.firstChild.onclick = function(){ return rcmail.command('sort', this.__col, this); };
3144           cell.firstChild.__col = col;
3145           }
3146         else
3147           cell.innerHTML = this.get_label(this.coltypes[n]);
3148
3149         cell.id = 'rcmHead'+col;
3150         }
3151       }
3152
3153   };
3154
3155   // create a table row in the message list
3156   this.add_message_row = function(uid, cols, flags, attachment, attop)
3157     {
3158     if (!this.gui_objects.messagelist || !this.message_list)
3159       return false;
3160
3161     var tbody = this.gui_objects.messagelist.tBodies[0];
3162     var rowcount = tbody.rows.length;
3163     var even = rowcount%2;
3164     
3165     this.env.messages[uid] = {deleted:flags.deleted?1:0,
3166                               replied:flags.replied?1:0,
3167                               unread:flags.unread?1:0};
3168     
3169     var row = document.createElement('TR');
3170     row.id = 'rcmrow'+uid;
3171     row.className = 'message '+(even ? 'even' : 'odd')+(flags.unread ? ' unread' : '')+(flags.deleted ? ' deleted' : '');
3172
3173     if (this.message_list.in_selection(uid))
3174       row.className += ' selected';
3175
3176     var icon = flags.deleted && this.env.deletedicon ? this.env.deletedicon:
3177                (flags.unread && this.env.unreadicon ? this.env.unreadicon :
3178                (flags.replied && this.env.repliedicon ? this.env.repliedicon : this.env.messageicon));
3179
3180     var col = document.createElement('TD');
3181     col.className = 'icon';
3182     col.innerHTML = icon ? '<img src="'+icon+'" alt="" border="0" />' : '';
3183     row.appendChild(col);
3184
3185     // add each submitted col
3186     for (var n = 0; n < this.coltypes.length; n++) 
3187       { 
3188       var c = this.coltypes[n];
3189       col = document.createElement('TD');
3190       col.className = String(c).toLowerCase();
3191       col.innerHTML = cols[c];
3192       row.appendChild(col);
3193       }
3194
3195     col = document.createElement('TD');
3196     col.className = 'icon';
3197     col.innerHTML = attachment && this.env.attachmenticon ? '<img src="'+this.env.attachmenticon+'" alt="" border="0" />' : '';
3198     row.appendChild(col);
3199
3200     this.message_list.insert_row(row, attop);
3201     };
3202
3203
3204   // replace content of row count display
3205   this.set_rowcount = function(text)
3206     {
3207     if (this.gui_objects.countdisplay)
3208       this.gui_objects.countdisplay.innerHTML = text;
3209
3210     // update page navigation buttons
3211     this.set_page_buttons();
3212     };
3213
3214   // replace content of quota display
3215   this.set_quota = function()
3216     {
3217     if (this.gui_objects.quotadisplay &&
3218         this.gui_objects.quotadisplay.attributes.getNamedItem('display') &&
3219         this.gui_objects.quotadisplay.attributes.getNamedItem('id'))
3220       this.http_request('quotadisplay', '_display='+
3221       this.gui_objects.quotadisplay.attributes.getNamedItem('display').nodeValue+
3222       '&_id='+this.gui_objects.quotadisplay.attributes.getNamedItem('id').nodeValue, false);
3223      };
3224
3225
3226   // update the mailboxlist
3227   this.set_unread_count = function(mbox, count, set_title)
3228     {
3229     if (!this.gui_objects.mailboxlist)
3230       return false;
3231
3232     var reg, text_obj;
3233     var item = this.get_folder_li(mbox);
3234     mbox = String(mbox).toLowerCase().replace(this.identifier_expr, '');
3235
3236     if (item && item.className && item.className.indexOf('mailbox '+mbox)>=0)
3237       {
3238       // set new text
3239       text_obj = item.firstChild;
3240       reg = /\s+\([0-9]+\)$/i;
3241
3242       if (count && text_obj.innerHTML.match(reg))
3243         text_obj.innerHTML = text_obj.innerHTML.replace(reg, ' ('+count+')');
3244       else if (count)
3245         text_obj.innerHTML += ' ('+count+')';
3246       else
3247         text_obj.innerHTML = text_obj.innerHTML.replace(reg, '');
3248
3249       // set the right classes
3250       this.set_classname(item, 'unread', count>0 ? true : false);
3251       }
3252
3253     // set unread count to window title
3254     reg = /^\([0-9]+\)\s+/i;
3255     if (set_title && document.title)
3256       {
3257       var doc_title = String(document.title);
3258       var new_title = "";
3259
3260       if (count && doc_title.match(reg))
3261         new_title = doc_title.replace(reg, '('+count+') ');
3262       else if (count)
3263         new_title = '('+count+') '+doc_title;
3264       else
3265         new_title = doc_title.replace(reg, '');
3266         
3267       this.set_pagetitle(new_title);
3268       }
3269     };
3270
3271
3272   // add row to contacts list
3273   this.add_contact_row = function(cid, cols, select)
3274     {
3275     if (!this.gui_objects.contactslist || !this.gui_objects.contactslist.tBodies[0])
3276       return false;
3277     
3278     var tbody = this.gui_objects.contactslist.tBodies[0];
3279     var rowcount = tbody.rows.length;
3280     var even = rowcount%2;
3281     
3282     var row = document.createElement('TR');
3283     row.id = 'rcmrow'+cid;
3284     row.className = 'contact '+(even ? 'even' : 'odd');
3285     
3286     if (this.contact_list.in_selection(cid))
3287       row.className += ' selected';
3288
3289     // add each submitted col
3290     for (var c in cols)
3291       {
3292       col = document.createElement('TD');
3293       col.className = String(c).toLowerCase();
3294       col.innerHTML = cols[c];
3295       row.appendChild(col);
3296       }
3297     
3298     this.contact_list.insert_row(row);
3299     };
3300
3301
3302   this.toggle_editor = function(checkbox, textElementName)
3303     {
3304     var ischecked = checkbox.checked;
3305     if (ischecked)
3306       {
3307         tinyMCE.execCommand('mceAddControl', true, textElementName);
3308       }
3309     else
3310       {
3311         tinyMCE.execCommand('mceRemoveControl', true, textElementName);
3312       }
3313     };
3314
3315
3316
3317   /********************************************************/
3318   /*********        remote request methods        *********/
3319   /********************************************************/
3320
3321   this.redirect = function(url, lock)
3322     {
3323     if (lock || lock === null)
3324       this.set_busy(true);
3325
3326     if (this.env.framed && window.parent)
3327       parent.location.href = url;
3328     else  
3329       location.href = url;
3330     };
3331
3332   this.goto_url = function(action, query, lock)
3333     {
3334     var querystring = query ? '&'+query : '';
3335     this.redirect(this.env.comm_path+'&_action='+action+querystring, lock);
3336     };
3337
3338
3339   this.http_sockets = new Array();
3340   
3341   // find a non-busy socket or create a new one
3342   this.get_request_obj = function()
3343     {
3344     for (var n=0; n<this.http_sockets.length; n++)
3345       {
3346       if (!this.http_sockets[n].busy)
3347         return this.http_sockets[n];
3348       }
3349     
3350     // create a new XMLHTTP object
3351     var i = this.http_sockets.length;
3352     this.http_sockets[i] = new rcube_http_request();
3353
3354     return this.http_sockets[i];
3355     };
3356   
3357
3358   // send a http request to the server
3359   this.http_request = function(action, querystring, lock)
3360     {
3361     var request_obj = this.get_request_obj();
3362     querystring += (querystring ? '&' : '') + '_remote=1';
3363     
3364     // add timestamp to request url to avoid cacheing problems in Safari
3365     if (bw.safari)
3366       querystring += '&_ts='+(new Date().getTime());
3367
3368     // send request
3369     if (request_obj)
3370       {
3371       console.log('HTTP request: '+this.env.comm_path+'&_action='+action+'&'+querystring);
3372
3373       if (lock)
3374         this.set_busy(true);
3375
3376       var rcm = this;
3377       request_obj.__lock = lock ? true : false;
3378       request_obj.__action = action;
3379       request_obj.onerror = function(o){ ref.http_error(o); };
3380       request_obj.oncomplete = function(o){ ref.http_response(o); };
3381       request_obj.GET(this.env.comm_path+'&_action='+action+'&'+querystring);
3382       }
3383     };
3384
3385     // send a http POST request to the server
3386     this.http_post = function(action, postdata, lock)
3387       {
3388       var request_obj;
3389       if (postdata && typeof(postdata) == 'object')
3390         postdata._remote = 1;
3391       else
3392         postdata += (postdata ? '&' : '') + '_remote=1';
3393
3394       // send request
3395       if (request_obj = this.get_request_obj())
3396         {
3397         console.log('HTTP POST: '+this.env.comm_path+'&_action='+action);
3398
3399         if (lock)
3400           this.set_busy(true);
3401
3402         var rcm = this;
3403         request_obj.__lock = lock ? true : false;
3404         request_obj.__action = action;
3405         request_obj.onerror = function(o){ rcm.http_error(o); };
3406         request_obj.oncomplete = function(o){ rcm.http_response(o); };
3407         request_obj.POST(this.env.comm_path+'&_action='+action, postdata);
3408         }
3409       };
3410
3411   // handle HTTP response
3412   this.http_response = function(request_obj)
3413     {
3414     var ctype = request_obj.get_header('Content-Type');
3415     if (ctype){
3416       ctype = String(ctype).toLowerCase();
3417       var ctype_array=ctype.split(";");
3418       ctype = ctype_array[0];
3419     }
3420
3421     if (request_obj.__lock)
3422         this.set_busy(false);
3423
3424     console.log(request_obj.get_text());
3425
3426     // if we get javascript code from server -> execute it
3427     if (request_obj.get_text() && (ctype=='text/javascript' || ctype=='application/x-javascript'))
3428       eval(request_obj.get_text());
3429
3430     // process the response data according to the sent action
3431     switch (request_obj.__action)
3432       {
3433       case 'delete':
3434       case 'moveto':
3435         if (this.env.action=='show')
3436           this.command('list');
3437         else if (this.message_list)
3438           this.message_list.init();
3439         break;
3440
3441       case 'list':
3442         if (this.env.messagecount)
3443           this.enable_command('purge', (this.env.mailbox==this.env.trash_mailbox || this.env.mailbox==this.env.junk_mailbox));
3444         this.msglist_select(this.message_list);
3445
3446       case 'expunge':
3447         this.enable_command('select-all', 'select-none', 'expunge', this.env.messagecount ? true : false);
3448         break;
3449       }
3450
3451     request_obj.reset();
3452     };
3453
3454
3455   // handle HTTP request errors
3456   this.http_error = function(request_obj)
3457     {
3458     //alert('Error sending request: '+request_obj.url);
3459
3460     if (request_obj.__lock)
3461       this.set_busy(false);
3462
3463     request_obj.reset();
3464     request_obj.__lock = false;
3465     };
3466
3467
3468   // use an image to send a keep-alive siganl to the server
3469   this.send_keep_alive = function()
3470     {
3471     var d = new Date();
3472     this.http_request('keep-alive', '_t='+d.getTime());
3473     };
3474
3475     
3476   // send periodic request to check for recent messages
3477   this.check_for_recent = function()
3478     {
3479     if (this.busy)
3480       {
3481       this.send_keep_alive();
3482       return;
3483       }
3484
3485     this.set_busy(true, 'checkingmail');
3486     this.http_request('check-recent', '_t='+(new Date().getTime()), true);
3487     };
3488
3489
3490   /********************************************************/
3491   /*********            helper methods            *********/
3492   /********************************************************/
3493   
3494   // check if we're in show mode or if we have a unique selection
3495   // and return the message uid
3496   this.get_single_uid = function()
3497     {
3498     return this.env.uid ? this.env.uid : (this.message_list ? this.message_list.get_single_selection() : null);
3499     };
3500
3501   // same as above but for contacts
3502   this.get_single_cid = function()
3503     {
3504     return this.env.cid ? this.env.cid : (this.contact_list ? this.contact_list.get_single_selection() : null);
3505     };
3506
3507
3508   this.get_caret_pos = function(obj)
3509     {
3510     if (typeof(obj.selectionEnd)!='undefined')
3511       return obj.selectionEnd;
3512
3513     else if (document.selection && document.selection.createRange)
3514       {
3515       var range = document.selection.createRange();
3516       if (range.parentElement()!=obj)
3517         return 0;
3518
3519       var gm = range.duplicate();
3520       if (obj.tagName=='TEXTAREA')
3521         gm.moveToElementText(obj);
3522       else
3523         gm.expand('textedit');
3524       
3525       gm.setEndPoint('EndToStart', range);
3526       var p = gm.text.length;
3527
3528       return p<=obj.value.length ? p : -1;
3529       }
3530
3531     else
3532       return obj.value.length;
3533     };
3534
3535
3536   this.set_caret2start = function(obj)
3537     {
3538     if (obj.createTextRange)
3539       {
3540       var range = obj.createTextRange();
3541       range.collapse(true);
3542       range.select();
3543       }
3544     else if (obj.setSelectionRange)
3545       obj.setSelectionRange(0,0);
3546
3547     obj.focus();
3548     };
3549
3550
3551   // set all fields of a form disabled
3552   this.lock_form = function(form, lock)
3553     {
3554     if (!form || !form.elements)
3555       return;
3556     
3557     var type;
3558     for (var n=0; n<form.elements.length; n++)
3559       {
3560       type = form.elements[n];
3561       if (type=='hidden')
3562         continue;
3563         
3564       form.elements[n].disabled = lock;
3565       }
3566     };
3567     
3568   }  // end object rcube_webmail
3569
3570
3571
3572 /**
3573  * Class for sending HTTP requests
3574  * @constructor
3575  */
3576 function rcube_http_request()
3577   {
3578   this.url = '';
3579   this.busy = false;
3580   this.xmlhttp = null;
3581
3582
3583   // reset object properties
3584   this.reset = function()
3585     {
3586     // set unassigned event handlers
3587     this.onloading = function(){ };
3588     this.onloaded = function(){ };
3589     this.oninteractive = function(){ };
3590     this.oncomplete = function(){ };
3591     this.onabort = function(){ };
3592     this.onerror = function(){ };
3593     
3594     this.url = '';
3595     this.busy = false;
3596     this.xmlhttp = null;
3597     }
3598
3599
3600   // create HTMLHTTP object
3601   this.build = function()
3602     {
3603     if (window.XMLHttpRequest)
3604       this.xmlhttp = new XMLHttpRequest();
3605     else if (window.ActiveXObject)
3606       {
3607       try { this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
3608       catch(e) { this.xmlhttp = null; }
3609       }
3610     else
3611       {
3612       
3613       }
3614     }
3615
3616   // send GET request
3617   this.GET = function(url)
3618     {
3619     this.build();
3620
3621     if (!this.xmlhttp)
3622       {
3623       this.onerror(this);
3624       return false;
3625       }
3626
3627     var _ref = this;
3628     this.url = url;
3629     this.busy = true;
3630
3631     this.xmlhttp.onreadystatechange = function(){ _ref.xmlhttp_onreadystatechange(); };
3632     this.xmlhttp.open('GET', url);
3633     this.xmlhttp.setRequestHeader('X-RoundCube-Referer', bw.get_cookie('roundcube_sessid'));
3634     this.xmlhttp.send(null);
3635     };
3636
3637
3638   this.POST = function(url, body, contentType)
3639     {
3640     // default value for contentType if not provided
3641     if (typeof(contentType) == 'undefined')
3642       contentType = 'application/x-www-form-urlencoded';
3643
3644     this.build();
3645     
3646     if (!this.xmlhttp)
3647     {
3648        this.onerror(this);
3649        return false;
3650     }
3651     
3652     var req_body = body;
3653     if (typeof(body) == 'object')
3654     {
3655       req_body = '';
3656       for (var p in body)
3657         req_body += (req_body ? '&' : '') + p+'='+urlencode(body[p]);
3658     }
3659
3660     var ref = this;
3661     this.url = url;
3662     this.busy = true;
3663     
3664     this.xmlhttp.onreadystatechange = function() { ref.xmlhttp_onreadystatechange(); };
3665     this.xmlhttp.open('POST', url, true);
3666     this.xmlhttp.setRequestHeader('Content-Type', contentType);
3667     this.xmlhttp.setRequestHeader('X-RoundCube-Referer', bw.get_cookie('roundcube_sessid'));
3668     this.xmlhttp.send(req_body);
3669     };
3670
3671
3672   // handle onreadystatechange event
3673   this.xmlhttp_onreadystatechange = function()
3674     {
3675     if(this.xmlhttp.readyState == 1)
3676       this.onloading(this);
3677
3678     else if(this.xmlhttp.readyState == 2)
3679       this.onloaded(this);
3680
3681     else if(this.xmlhttp.readyState == 3)
3682       this.oninteractive(this);
3683
3684     else if(this.xmlhttp.readyState == 4)
3685       {
3686       try {
3687         if (this.xmlhttp.status == 0)
3688           this.onabort(this);
3689         else if(this.xmlhttp.status == 200)
3690           this.oncomplete(this);
3691         else
3692           this.onerror(this);
3693
3694         this.busy = false;
3695         }
3696       catch(err)
3697         {
3698         this.onerror(this);
3699         this.busy = false;
3700         }
3701       }
3702     }
3703
3704   // getter method for HTTP headers
3705   this.get_header = function(name)
3706     {
3707     return this.xmlhttp.getResponseHeader(name);
3708     };
3709
3710   this.get_text = function()
3711     {
3712     return this.xmlhttp.responseText;
3713     };
3714
3715   this.get_xml = function()
3716     {
3717     return this.xmlhttp.responseXML;
3718     };
3719
3720   this.reset();
3721   
3722   }  // end class rcube_http_request
3723
3724
3725 // helper function to call the init method with a delay
3726 function call_init(o)
3727   {
3728   if (window[o] && window[o].init)
3729     setTimeout(o+'.init()', 200);
3730   }
3731