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