From 2f2f15b7aabe19e45dad9bddb7eb7f4394aa1e21 Mon Sep 17 00:00:00 2001
From: thomascube <thomas@roundcube.net>
Date: Mon, 04 Sep 2006 08:26:30 -0400
Subject: [PATCH] Little improvements for message parsing and encoding

---
 program/js/app.js | 1266 ++++++++++++++++++++++++++++++++++++++++++++++++--------
 1 files changed, 1,076 insertions(+), 190 deletions(-)

diff --git a/program/js/app.js b/program/js/app.js
index ad91e1f..1b7312f 100644
--- a/program/js/app.js
+++ b/program/js/app.js
@@ -7,12 +7,17 @@
  | Licensed under the GNU GPL                                            |
  |                                                                       |
  +-----------------------------------------------------------------------+
- | Author: Thomas Bruederli <roundcube@gmail.com>                        |
+ | Authors: Thomas Bruederli <roundcube@gmail.com>                       |
+ |          Charles McNulty <charles@charlesmcnulty.com>                 |
  +-----------------------------------------------------------------------+
  
   $Id$
 */
 
+// Constants
+var CONTROL_KEY = 1;
+var SHIFT_KEY = 2;
+var CONTROL_SHIFT_KEY = 3;
 
 var rcube_webmail_client;
 
@@ -24,6 +29,8 @@
   this.gui_objects = new Object();
   this.commands = new Object();
   this.selection = new Array();
+  this.last_selected = 0;
+  this.in_message_list = false;
 
   // create public reference to myself
   rcube_webmail_client = this;
@@ -32,10 +39,8 @@
   // webmail client settings
   this.dblclick_time = 600;
   this.message_time = 5000;
-  this.request_timeout = 180000;
-  this.kepp_alive_interval = 60000;
+  
   this.mbox_expression = new RegExp('[^0-9a-z\-_]', 'gi');
-  this.env.blank_img = 'skins/default/images/blank.gif';
   
   // mimetypes supported by the browser (default settings)
   this.mimetypes = new Array('text/plain', 'text/html', 'text/xml',
@@ -43,12 +48,16 @@
                              'application/x-javascript', 'application/pdf',
                              'application/x-shockwave-flash');
 
+  // default environment vars
+  this.env.keep_alive = 60;        // seconds
+  this.env.request_timeout = 180;  // seconds
+  this.env.draft_autosave = 300;   // seconds
+
 
   // set environment variable
   this.set_env = function(name, value)
     {
-    //if (!this.busy)
-      this.env[name] = value;    
+    this.env[name] = value;
     };
 
 
@@ -107,15 +116,17 @@
     switch (this.task)
       {
       case 'mail':
+        var msg_list_frame = this.gui_objects.mailcontframe;
         var msg_list = this.gui_objects.messagelist;
         if (msg_list)
           {
+          msg_list_frame.onmousedown = function(e){return rcube_webmail_client.click_on_list(e);};
           this.init_messagelist(msg_list);
-          this.enable_command('markread', true);
+          this.enable_command('toggle_status', true);
           }
 
         // enable mail commands
-        this.enable_command('list', 'compose', 'add-contact', true);
+        this.enable_command('list', 'checkmail', 'compose', 'add-contact', 'search', 'reset-search', true);
         
         if (this.env.action=='show')
           {
@@ -134,10 +145,19 @@
           }  
 
         if (this.env.action=='compose')
-          this.enable_command('add-attachment', 'send-attachment', 'send', true);
+          {
+          this.enable_command('add-attachment', 'send-attachment', 'remove-attachment', 'send', true);
+          if (this.env.spellcheck)
+            this.enable_command('spellcheck', true);
+          if (this.env.drafts_mailbox)
+            this.enable_command('savedraft', true);
+          }
           
         if (this.env.messagecount)
           this.enable_command('select-all', 'select-none', 'sort', 'expunge', true);
+
+        if (this.env.messagecount && (this.env.mailbox==this.env.trash_mailbox || this.env.mailbox==this.env.junk_mailbox))
+          this.enable_command('purge', true);
 
         this.set_page_buttons();
 
@@ -194,7 +214,7 @@
           this.enable_command('save', true);
           
         if (this.env.action=='folders')
-          this.enable_command('subscribe', 'unsubscribe', 'create-folder', 'delete-folder', true);
+          this.enable_command('subscribe', 'unsubscribe', 'create-folder', 'rename-folder', 'delete-folder', true);
           
         var identities_list = this.gui_objects.identitieslist;
         if (identities_list)
@@ -224,34 +244,137 @@
     // disable browser's contextmenus
     // document.oncontextmenu = function(){ return false; }
 
+    // load body click event
+    document.onmousedown = function(){ return rcube_webmail_client.reset_click(); };
+    document.onkeydown   = function(e){ return rcube_webmail_client.key_pressed(e, msg_list_frame); };
+    
     // flag object as complete
     this.loaded = true;
-          
+
     // show message
     if (this.pending_message)
       this.display_message(this.pending_message[0], this.pending_message[1]);
-      
-    // start interval for keep-alive/recent_check signal
-    if (this.kepp_alive_interval && this.task=='mail' && this.gui_objects.messagelist)
-      this.kepp_alive_int = setInterval(this.ref+'.check_for_recent()', this.kepp_alive_interval);
-    else
-      this.kepp_alive_int = setInterval(this.ref+'.send_keep_alive()', this.kepp_alive_interval);
+
+    // start keep-alive interval
+    this.start_keepalive();
     };
 
+
+  // start interval for keep-alive/recent_check signal
+  this.start_keepalive = function()
+    {
+    if (this.env.keep_alive && this.task=='mail' && this.gui_objects.messagelist)
+      this._int = setInterval(this.ref+'.check_for_recent()', this.env.keep_alive * 1000);
+    else if (this.env.keep_alive && this.task!='login')
+      this._int = setInterval(this.ref+'.send_keep_alive()', this.env.keep_alive * 1000);    
+    }
+
+
+  // reset last clicked if user clicks on anything other than the message table
+  this.reset_click = function()
+    {
+    var id;
+    this.in_message_list = false;
+	for (var n=0; n<this.selection.length; n++)
+	  {
+      id = this.selection[n];
+      if (this.list_rows[id] && this.list_rows[id].obj)
+        {
+        this.set_classname(this.list_rows[id].obj, 'selected', false);
+		this.set_classname(this.list_rows[id].obj, 'unfocused', true);
+        }
+      }
+    };
+	
+  this.click_on_list = function(e)
+    {
+    if (!e)
+      e = window.event;
+
+    for (var n=0; n<this.selection.length; n++)
+      {
+      id = this.selection[n];
+      if (this.list_rows[id].obj)
+        {
+        this.set_classname(this.list_rows[id].obj, 'selected', true);
+		this.set_classname(this.list_rows[id].obj, 'unfocused', false);
+        }
+      }
+
+    var mbox_li;
+    if (mbox_li = this.get_mailbox_li()) 
+      this.set_classname(mbox_li, 'unfocused', true);
+    
+    this.in_message_list = true;
+    e.cancelBubble = true;
+    };
+
+  this.key_pressed = function(e, msg_list_frame) {
+    if (this.in_message_list != true) 
+      return true;
+    var keyCode = document.layers ? e.which : document.all ? event.keyCode : document.getElementById ? e.keyCode : 0;
+    var mod_key = this.get_modifier(e);
+    switch (keyCode) {
+      case 13:
+        this.command('show','',this);
+        break;
+      case 40:
+      case 38: 
+        return this.use_arrow_key(keyCode, mod_key, msg_list_frame);
+        break;
+      case 46:
+        return this.use_delete_key(keyCode, mod_key, msg_list_frame);
+        break;
+      default:
+        return true;
+    }
+    return true;
+  }
+
+  this.use_arrow_key = function(keyCode, mod_key, msg_list_frame) {
+    var scroll_to = 0;
+    if (keyCode == 40) { // down arrow key pressed
+      new_row = this.get_next_row();
+      if (!new_row) return false;
+      scroll_to = (Number(new_row.offsetTop) + Number(new_row.offsetHeight)) - Number(msg_list_frame.offsetHeight);
+    } else if (keyCode == 38) { // up arrow key pressed
+      new_row = this.get_prev_row();
+      if (!new_row) return false;
+      scroll_to = new_row.offsetTop;
+    } else {return true;}
+	
+    this.select_row(new_row.uid,mod_key,true);
+
+    if (((Number(new_row.offsetTop)) < (Number(msg_list_frame.scrollTop))) || 
+       ((Number(new_row.offsetTop) + Number(new_row.offsetHeight)) > (Number(msg_list_frame.scrollTop) + Number(msg_list_frame.offsetHeight)))) {
+      msg_list_frame.scrollTop = scroll_to;
+    }
+    return false;
+  };
+  
+  this.use_delete_key = function(keyCode, mod_key, msg_list_frame){
+    this.command('delete','',this);
+    return false;
+  }
 
   // get all message rows from HTML table and init each row
   this.init_messagelist = function(msg_list)
     {
     if (msg_list && msg_list.tBodies[0])
       {
+		  
       this.message_rows = new Array();
 
       var row;
       for(var r=0; r<msg_list.tBodies[0].childNodes.length; r++)
         {
         row = msg_list.tBodies[0].childNodes[r];
+        while (row && (row.nodeType != 1 || row.style.display == 'none')) {
+          row = row.nextSibling;
+          r++;
+        }
         //row = msg_list.tBodies[0].rows[r];
-        this.init_message_row(row);
+        if (row) this.init_message_row(row);
         }
       }
       
@@ -272,19 +395,23 @@
               
       this.message_rows[uid] = {id:row.id, obj:row,
                                 classname:row.className,
+                                deleted:this.env.messages[uid] ? this.env.messages[uid].deleted : null,
                                 unread:this.env.messages[uid] ? this.env.messages[uid].unread : null,
                                 replied:this.env.messages[uid] ? this.env.messages[uid].replied : null};
               
       // set eventhandlers to table row
       row.onmousedown = function(e){ return rcube_webmail_client.drag_row(e, this.uid); };
       row.onmouseup = function(e){ return rcube_webmail_client.click_row(e, this.uid); };
-              
+
+      if (document.all)
+        row.onselectstart = function() { return false; };
+
       // set eventhandler to message icon
       if ((msg_icon = row.cells[0].childNodes[0]) && row.cells[0].childNodes[0].nodeName=='IMG')
         {                
         msg_icon.id = 'msgicn_'+uid;
         msg_icon._row = row;
-        msg_icon.onmousedown = function(e) { rcube_webmail_client.command('markread', this); };
+        msg_icon.onmousedown = function(e) { rcube_webmail_client.command('toggle_status', this); };
                 
         // get message icon and save original icon src
         this.message_rows[uid].icon = msg_icon;
@@ -329,8 +456,10 @@
     
     // get summary of all field values
     this.cmp_hash = this.compose_field_hash();
+ 
+    // start the auto-save timer
+    this.auto_save_start();
     };
-
 
   this.init_address_input_events = function(obj)
     {
@@ -378,7 +507,7 @@
     this.list_rows = this.contact_rows;
     
     if (this.env.cid)
-      this.select(this.env.cid);
+      this.highlight_row(this.env.cid);
     };
 
 
@@ -442,7 +571,7 @@
     this.list_rows = this.identity_rows;
     
     if (this.env.iid)
-      this.select(this.env.iid);    
+      this.highlight_row(this.env.iid);    
     };
     
 
@@ -503,10 +632,21 @@
       // misc list commands
       case 'list':
         if (this.task=='mail')
+          {
+          if (this.env.search_request<0 || (this.env.search_request && props != this.env.mailbox))
+            this.reset_qsearch();
+
+          // Reset message list header, unless returning from compose/read/etc
+          // don't know what this is good for (thomasb, 2006/07/25)
+          //if (this.env.mailbox != props && this.message_rows)
+          //  this.clear_message_list_header();
+
           this.list_mailbox(props);
+          }
         else if (this.task=='addressbook')
           this.list_contacts();
         break;
+
 
       case 'sort':
         // get the type of sorting
@@ -523,7 +663,7 @@
           else
             sort_order = this.env.sort_order;
           }
-        
+
         if (this.env.sort_col==sort_col && this.env.sort_order==sort_order)
           break;
 
@@ -554,9 +694,10 @@
           this.expunge_mailbox(this.env.mailbox);
         break;
 
-      case 'clear-mailbox':
-        //if (this.env.messagecount)
-          //this.clear_mailbox(this.env.mailbox);
+      case 'purge':
+      case 'empty-mailbox':
+        if (this.env.messagecount)
+          this.purge_mailbox(this.env.mailbox);
         break;
 
 
@@ -566,7 +707,15 @@
           {
           var uid = this.get_single_uid();
           if (uid && (!this.env.uid || uid != this.env.uid))
-            this.show_message(uid);
+            {
+            if (this.env.mailbox==this.env.drafts_mailbox)
+              {
+              this.set_busy(true);
+              location.href = this.env.comm_path+'&_action=compose&_draft_uid='+uid+'&_mbox='+urlencode(this.env.mailbox);
+              }
+            else
+              this.show_message(uid);
+            }
           }
         else if (this.task=='addressbook')
           {
@@ -640,9 +789,7 @@
 
       case 'delete':
         // mail task
-        if (this.task=='mail' && this.env.trash_mailbox && String(this.env.mailbox).toLowerCase()!=String(this.env.trash_mailbox).toLowerCase())
-          this.move_messages(this.env.trash_mailbox);
-        else if (this.task=='mail')
+        if (this.task=='mail')
           this.delete_messages();
         // addressbook task
         else if (this.task=='addressbook')
@@ -659,7 +806,7 @@
         this.move_messages(props);
         break;
         
-      case 'markread':
+      case 'toggle_status':
         if (props && !props._row)
           break;
         
@@ -670,9 +817,10 @@
           {
           uid = props._row.uid;
           this.dont_select = true;
-          
           // toggle read/unread
-          if (!this.message_rows[uid].unread)
+          if (this.message_rows[uid].deleted) {
+          	flag = 'undelete';
+          } else if (!this.message_rows[uid].unread)
             flag = 'unread';
           }
           
@@ -721,12 +869,21 @@
           //location.href = this.env.comm_path+'&_action=show&_uid='+this.env.prev_uid+'&_mbox='+this.env.mailbox;
         break;
       
+      case 'checkmail':
+        this.check_for_recent();
+        break;
       
       case 'compose':
         var url = this.env.comm_path+'&_action=compose';
-        
+       
+        if (this.task=='mail' && this.env.mailbox==this.env.drafts_mailbox)
+          {
+          var uid;
+          if (uid = this.get_single_uid())
+            url += '&_draft_uid='+uid+'&_mbox='+urlencode(this.env.mailbox);
+          } 
         // modify url if we're in addressbook
-        if (this.task=='addressbook')
+        else if (this.task=='addressbook')
           {
           url = this.get_task_url('mail', url);            
           var a_cids = new Array();
@@ -758,35 +915,75 @@
             
           }
         else if (props)
-           url += '&_to='+props;
-        
+           url += '&_to='+encodeURIComponent(props);
+
         // don't know if this is necessary...
         url = url.replace(/&_framed=1/, "");
 
         this.set_busy(true);
 
         // need parent in case we are coming from the contact frame
-        parent.window.location.href = url;
-        break;    
+        if (this.env.framed)
+          parent.location.href = url;
+        else
+          location.href = url;
+        break;
+        
+      case 'spellcheck':
+        if (this.env.spellcheck && this.env.spellcheck.spellCheck)
+          this.env.spellcheck.spellCheck(this.env.spellcheck.check_link);
+        break;
+
+      case 'savedraft':
+        // Reset the auto-save timer
+        self.clearTimeout(this.save_timer);
+
+        if (!this.gui_objects.messageform)
+          break;
+
+        // if saving Drafts is disabled in main.inc.php
+        if (!this.env.drafts_mailbox)
+          break;
+
+        this.set_busy(true, 'savingmessage');
+        var form = this.gui_objects.messageform;
+        form.target = "savetarget";
+        form.submit();
+        break;
 
       case 'send':
         if (!this.gui_objects.messageform)
           break;
-          
+
         if (!this.check_compose_input())
           break;
+          
+        // Reset the auto-save timer
+        self.clearTimeout(this.save_timer);
 
         // all checks passed, send message
         this.set_busy(true, 'sendingmessage');
         var form = this.gui_objects.messageform;
+        form.target = "savetarget";     
+        form._draft.value = '';
         form.submit();
+        
+        // clear timeout (sending could take longer)
+        clearTimeout(this.request_timer);
         break;
 
       case 'add-attachment':
         this.show_attachment_form(true);
         
       case 'send-attachment':
+        // Reset the auto-save timer
+        self.clearTimeout(this.save_timer);
+
         this.upload_file(props)      
+        break;
+      
+      case 'remove-attachment':
+        this.remove_attachment(props);
         break;
 
       case 'reply-all':
@@ -795,7 +992,7 @@
         if (uid = this.get_single_uid())
           {
           this.set_busy(true);
-          location.href = this.env.comm_path+'&_action=compose&_reply_uid='+uid+'&_mbox='+escape(this.env.mailbox)+(command=='reply-all' ? '&_all=1' : '');
+          location.href = this.env.comm_path+'&_action=compose&_reply_uid='+uid+'&_mbox='+urlencode(this.env.mailbox)+(command=='reply-all' ? '&_all=1' : '');
           }
         break;      
 
@@ -804,7 +1001,7 @@
         if (uid = this.get_single_uid())
           {
           this.set_busy(true);
-          location.href = this.env.comm_path+'&_action=compose&_forward_uid='+uid+'&_mbox='+escape(this.env.mailbox);
+          location.href = this.env.comm_path+'&_action=compose&_forward_uid='+uid+'&_mbox='+urlencode(this.env.mailbox);
           }
         break;
         
@@ -812,7 +1009,7 @@
         var uid;
         if (uid = this.get_single_uid())
           {
-          this.printwin = window.open(this.env.comm_path+'&_action=print&_uid='+uid+'&_mbox='+escape(this.env.mailbox)+(this.env.safemode ? '&_safe=1' : ''));
+          this.printwin = window.open(this.env.comm_path+'&_action=print&_uid='+uid+'&_mbox='+urlencode(this.env.mailbox)+(this.env.safemode ? '&_safe=1' : ''));
           if (this.printwin)
             setTimeout(this.ref+'.printwin.focus()', 20);
           }
@@ -822,7 +1019,7 @@
         var uid;
         if (uid = this.get_single_uid())
           {          
-          this.sourcewin = window.open(this.env.comm_path+'&_action=viewsource&_uid='+this.env.uid+'&_mbox='+escape(this.env.mailbox));
+          this.sourcewin = window.open(this.env.comm_path+'&_action=viewsource&_uid='+this.env.uid+'&_mbox='+urlencode(this.env.mailbox));
           if (this.sourcewin)
             setTimeout(this.ref+'.sourcewin.focus()', 20);
           }
@@ -832,6 +1029,22 @@
         this.add_contact(props);
         break;
       
+      // mail quicksearch
+      case 'search':
+        if (!props && this.gui_objects.qsearchbox)
+          props = this.gui_objects.qsearchbox.value;
+        if (props)
+          this.qsearch(urlencode(props), this.env.mailbox);
+        break;
+
+      // reset quicksearch        
+      case 'reset-search':
+        var s = this.env.search_request;
+        this.reset_qsearch();
+        
+        if (s)
+          this.list_mailbox(this.env.mailbox);
+        break;
 
       // ldap search
       case 'ldappublicsearch':
@@ -870,6 +1083,10 @@
         this.create_folder(props);
         break;
 
+      case 'rename-folder':
+        this.rename_folder(props);
+        break;
+
       case 'delete-folder':
         if (confirm(this.get_label('deletefolderconfirm')))
           this.delete_folder(props);
@@ -884,7 +1101,7 @@
   // set command enabled or disabled
   this.enable_command = function()
     {
-    var args = this.enable_command.arguments;
+    var args = arguments;
     if(!args.length) return -1;
 
     var command;
@@ -896,6 +1113,7 @@
       this.commands[command] = enable;
       this.set_button(command, (enable ? 'act' : 'pas'));
       }
+      return true;
     };
 
 
@@ -924,8 +1142,8 @@
       clearTimeout(this.request_timer);
 
     // set timer for requests
-    if (a && this.request_timeout)
-      this.request_timer = setTimeout(this.ref+'.request_timed_out()', this.request_timeout);
+    if (a && this.env.request_timeout)
+      this.request_timer = setTimeout(this.ref+'.request_timed_out()', this.env.request_timeout * 1000);
     };
 
 
@@ -980,10 +1198,13 @@
   this.mbox_mouse_up = function(mbox)
     {
     if (this.drag_active)
+      {
+      this.unfocus_mailbox(mbox);
       this.command('moveto', mbox);
+      }
     else
       this.command('list', mbox);
-      
+  
     return false;
     };
 
@@ -997,11 +1218,12 @@
     if (this.dont_select)
       return false;
 
-    if (!this.in_selection_before)
-      {
-      var ctrl = this.check_ctrlkey(e);
-      this.select(id, ctrl);
-      }
+    // selects currently unselected row
+    if (!this.in_selection_before && !this.list_rows[id].clicked)
+    {
+	  var mod_key = this.get_modifier(e);
+	  this.select_row(id,mod_key,false);
+    }
     
     if (this.selection.length)
       {
@@ -1017,8 +1239,8 @@
   // onmouseup-handler of message list row
   this.click_row = function(e, id)
     {
-    var shift = this.check_shiftkey(e);
-    
+    var mod_key = this.get_modifier(e);
+
     // don't do anything (another action processed before)
     if (this.dont_select)
       {
@@ -1026,18 +1248,25 @@
       return false;
       }
     
-    if (!this.drag_active && this.in_selection_before==id)
-      {
-      this.select(id, (shift && this.task!='settings'));
-      }
-    
+    // unselects currently selected row    
+    if (!this.drag_active && this.in_selection_before==id && !this.list_rows[id].clicked)
+      this.select_row(id,mod_key,false);
+
     this.drag_start = false;
     this.in_selection_before = false;
         
     // row was double clicked
-    if (this.task=='mail' && this.list_rows && this.list_rows[id].clicked && !shift)
+    if (this.task=='mail' && this.list_rows && this.list_rows[id].clicked && this.in_selection(id))
       {
-      this.show_message(id);
+      if (this.env.mailbox==this.env.drafts_mailbox)
+        {
+        this.set_busy(true);
+        location.href = this.env.comm_path+'&_action=compose&_draft_uid='+id+'&_mbox='+urlencode(this.env.mailbox);
+        }
+      else
+        {
+        this.show_message(id);
+        }
       return false;
       }
     else if (this.task=='addressbook')
@@ -1103,9 +1332,29 @@
   /*********     (message) list functionality      *********/
   /*********************************************************/
 
-
-  // select/unselect a row
-  this.select = function(id, multiple)
+  // get next and previous rows that are not hidden
+  this.get_next_row = function(){
+  	if (!this.list_rows) return false;
+    var last_selected_row = this.list_rows[this.last_selected];
+    var new_row = last_selected_row.obj.nextSibling;
+    while (new_row && (new_row.nodeType != 1 || new_row.style.display == 'none')) {
+      new_row = new_row.nextSibling;
+    }
+    return new_row;
+  }
+  
+  this.get_prev_row = function(){
+    if (!this.list_rows) return false;
+    var last_selected_row = this.list_rows[this.last_selected];
+    var new_row = last_selected_row.obj.previousSibling;
+    while (new_row && (new_row.nodeType != 1 || new_row.style.display == 'none')) {
+      new_row = new_row.previousSibling;
+    }
+    return new_row;
+  }
+  
+  // highlight/unhighlight a row
+  this.highlight_row = function(id, multiple)
     {
     var selected = false
     
@@ -1122,7 +1371,7 @@
       if (!this.in_selection(id))  // select row
         {
         this.selection[this.selection.length] = id;
-        this.set_classname(this.list_rows[id].obj, 'selected', true);        
+        this.set_classname(this.list_rows[id].obj, 'selected', true);
         }
       else  // unselect row
         {
@@ -1131,16 +1380,24 @@
         var a_post = this.selection.slice(p+1, this.selection.length);
         this.selection = a_pre.concat(a_post);
         this.set_classname(this.list_rows[id].obj, 'selected', false);
+        this.set_classname(this.list_rows[id].obj, 'unfocused', false);
         }
-        
       selected = (this.selection.length==1);
       }
 
     // enable/disable commands for message
     if (this.task=='mail')
       {
-      this.enable_command('show', 'reply', 'reply-all', 'forward', 'print', selected);
-      this.enable_command('delete', 'moveto', this.selection.length>0 ? true : false);
+      if (this.env.mailbox==this.env.drafts_mailbox)
+	{
+	this.enable_command('show', selected);
+	this.enable_command('delete', 'moveto', this.selection.length>0 ? true : false);
+        }
+      else
+        {
+        this.enable_command('show', 'reply', 'reply-all', 'forward', 'print', selected);
+        this.enable_command('delete', 'moveto', this.selection.length>0 ? true : false);
+        }
       }
     else if (this.task=='addressbook')
       {
@@ -1150,12 +1407,66 @@
     };
 
 
+// selects or unselects the proper row depending on the modifier key pressed
+  this.select_row = function(id,mod_key,with_mouse)  { 
+  	if (!mod_key) {
+      this.shift_start = id;
+  	  this.highlight_row(id, false);
+    } else {
+      switch (mod_key) {
+        case SHIFT_KEY: { 
+          this.shift_select(id,false); 
+          break; }
+        case CONTROL_KEY: { 
+          this.shift_start = id;
+          if (!with_mouse)
+            this.highlight_row(id, true); 
+          break; 
+          }
+        case CONTROL_SHIFT_KEY: { 
+          this.shift_select(id,true);
+          break;
+          }
+        default: {
+          this.highlight_row(id, false); 
+          break;
+          }
+      }
+	}
+	if (this.last_selected != 0 && this.list_rows[this.last_selected])
+	  this.set_classname(this.list_rows[this.last_selected].obj, 'focused', false);
+
+    this.last_selected = id;
+    this.set_classname(this.list_rows[id].obj, 'focused', true);        
+  };
+
+  this.shift_select = function(id, control) {
+    var from_rowIndex = this.list_rows[this.shift_start].obj.rowIndex;
+    var to_rowIndex = this.list_rows[id].obj.rowIndex;
+        
+    var i = ((from_rowIndex < to_rowIndex)? from_rowIndex : to_rowIndex);
+    var j = ((from_rowIndex > to_rowIndex)? from_rowIndex : to_rowIndex);
+    
+	// iterate through the entire message list
+    for (var n in this.list_rows) {
+      if ((this.list_rows[n].obj.rowIndex >= i) && (this.list_rows[n].obj.rowIndex <= j)) {
+        if (!this.in_selection(n))
+          this.highlight_row(n, true);
+      } else {
+        if  (this.in_selection(n) && !control)
+          this.highlight_row(n, true);
+      }
+    }
+  };
+  
+
   this.clear_selection = function()
     {
     for(var n=0; n<this.selection.length; n++)
-      if (this.list_rows[this.selection[n]])
+      if (this.list_rows[this.selection[n]]) {
         this.set_classname(this.list_rows[this.selection[n]].obj, 'selected', false);
-
+        this.set_classname(this.list_rows[this.selection[n]].obj, 'unfocused', false);
+	  }
     this.selection = new Array();    
     };
 
@@ -1181,8 +1492,15 @@
     this.clear_selection();
     
     for (var n in this.list_rows)
+      {
       if (!filter || this.list_rows[n][filter]==true)
-      this.select(n, true);
+        {
+        this.last_selected = n;
+        this.highlight_row(n, true);
+        }
+      }
+
+    return true;  
     };
     
 
@@ -1203,7 +1521,7 @@
     if (id)
       {
       this.set_busy(true, 'loading');
-      target.location.href = this.env.comm_path+'&_action=show&_uid='+id+'&_mbox='+escape(this.env.mailbox)+add_url;
+      target.location.href = this.env.comm_path+'&_action=show&_uid='+id+'&_mbox='+urlencode(this.env.mailbox)+add_url;
       }
     };
 
@@ -1232,6 +1550,7 @@
   // list messages of a specific mailbox
   this.list_mailbox = function(mbox, page, sort)
     {
+    this.last_selected = 0;
     var add_url = '';
     var target = window;
 
@@ -1250,9 +1569,12 @@
       this.env.current_page = page;
       this.clear_selection();
       }
+    
+    // also send search request to get the right messages
+    if (this.env.search_request)
+      add_url += '&_search='+this.env.search_request;
       
-    if (this.env.mailbox!=mbox)
-      this.select_mailbox(mbox);
+    this.select_mailbox(mbox);
 
     // load message list remotely
     if (this.gui_objects.messagelist)
@@ -1271,7 +1593,7 @@
     if (mbox)
       {
       this.set_busy(true, 'loading');
-      target.location.href = this.env.comm_path+'&_mbox='+escape(mbox)+(page ? '&_page='+page : '')+add_url;
+      target.location.href = this.env.comm_path+'&_mbox='+urlencode(mbox)+(page ? '&_page='+page : '')+add_url;
       }
     };
 
@@ -1283,7 +1605,7 @@
     this.clear_message_list();
 
     // send request to server
-    var url = '_mbox='+escape(mbox)+(page ? '&_page='+page : '');
+    var url = '_mbox='+urlencode(mbox)+(page ? '&_page='+page : '');
     this.set_busy(true, 'loading');
     this.http_request('list', url+add_url, true);
     };
@@ -1292,6 +1614,7 @@
   this.clear_message_list = function()
     {
     var table = this.gui_objects.messagelist;
+   
     var tbody = document.createElement('TBODY');
     table.insertBefore(tbody, table.tBodies[0]);
     table.removeChild(table.tBodies[1]);
@@ -1299,6 +1622,24 @@
     this.message_rows = new Array();
     this.list_rows = this.message_rows;
     
+    };
+
+
+  this.clear_message_list_header = function()
+    {
+    var table;
+    if (table = this.gui_objects.messagelist)
+      {
+      if (table.colgroup)
+        table.removeChild(table.colgroup);
+      if (table.tHead)
+        table.removeChild(table.tHead);
+
+      var colgroup = document.createElement('COLGROUP');
+      var thead = document.createElement('THEAD');
+      table.insertBefore(colgroup, table.tBodies[0]);
+      table.insertBefore(thead, table.tBodies[0]);
+      }
     };
 
 
@@ -1316,11 +1657,47 @@
        }
 
     // send request to server
-    var url = '_mbox='+escape(mbox);
+    var url = '_mbox='+urlencode(mbox);
     this.http_request('expunge', url+add_url, lock);
     };
 
 
+  this.purge_mailbox = function(mbox)
+    {
+    var lock = false;
+    var add_url = '';
+    
+    if (!confirm(this.get_label('purgefolderconfirm')))
+      return false;
+    
+    // lock interface if it's the active mailbox
+    if (mbox == this.env.mailbox)
+       {
+       lock = true;
+       this.set_busy(true, 'loading');
+       add_url = '&_reload=1';
+       }
+
+    // send request to server
+    var url = '_mbox='+urlencode(mbox);
+    this.http_request('purge', url+add_url, lock);
+    return true;
+    };
+    
+  this.focus_mailbox = function(mbox)
+    {
+    var mbox_li;
+  	if (this.drag_active && mbox != this.env.mailbox && (mbox_li = this.get_mailbox_li(mbox)))
+      this.set_classname(mbox_li, 'droptarget', true);
+    }
+    
+  this.unfocus_mailbox = function(mbox)
+    {
+    var mbox_li;
+  	if (this.drag_active && (mbox_li = this.get_mailbox_li(mbox)))
+      this.set_classname(mbox_li, 'droptarget', false);
+    }
+  
   // move selected messages to the specified mailbox
   this.move_messages = function(mbox)
     {
@@ -1344,6 +1721,10 @@
         if (this.message_rows[id].obj)
           this.message_rows[id].obj.style.display = 'none';
         }
+      next_row = this.get_next_row();
+      prev_row = this.get_prev_row();
+      new_row = (next_row) ? next_row : prev_row;
+      if (new_row) this.select_row(new_row.uid,false,false);
       }
       
     var lock = false;
@@ -1354,15 +1735,11 @@
       lock = true;
       this.set_busy(true, 'movingmessage');
       }
-
     // send request to server
-    this.http_request('moveto', '_uid='+a_uids.join(',')+'&_mbox='+escape(this.env.mailbox)+'&_target_mbox='+escape(mbox)+'&_from='+(this.env.action ? this.env.action : ''), lock);
+    this.http_request('moveto', '_uid='+a_uids.join(',')+'&_mbox='+urlencode(this.env.mailbox)+'&_target_mbox='+urlencode(mbox)+'&_from='+(this.env.action ? this.env.action : ''), lock);
     };
 
-
-  // delete selected messages from the current mailbox
-  this.delete_messages = function()
-    {
+  this.permanently_remove_messages = function() {
     // exit if no mailbox specified or if selection is empty
     if (!(this.selection.length || this.env.uid))
       return;
@@ -1384,10 +1761,46 @@
           this.message_rows[id].obj.style.display = 'none';
         }
       }
+      next_row = this.get_next_row();
+      prev_row = this.get_prev_row();
+      new_row = (next_row) ? next_row : prev_row;
+      if (new_row) this.select_row(new_row.uid,false,false);
 
     // send request to server
-    this.http_request('delete', '_uid='+a_uids.join(',')+'&_mbox='+escape(this.env.mailbox)+'&_from='+(this.env.action ? this.env.action : ''));
-    };
+    this.http_request('delete', '_uid='+a_uids.join(',')+'&_mbox='+urlencode(this.env.mailbox)+'&_from='+(this.env.action ? this.env.action : ''));
+  }
+    
+    
+  // delete selected messages from the current mailbox
+  this.delete_messages = function()
+    {
+    // exit if no mailbox specified or if selection is empty
+    if (!(this.selection.length || this.env.uid))
+      return;
+    // if there is a trash mailbox defined and we're not currently in it:
+    if (this.env.trash_mailbox && String(this.env.mailbox).toLowerCase()!=String(this.env.trash_mailbox).toLowerCase())
+      this.move_messages(this.env.trash_mailbox);
+    // if there is a trash mailbox defined but we *are* in it:
+    else if (this.env.trash_mailbox && String(this.env.mailbox).toLowerCase() == String(this.env.trash_mailbox).toLowerCase())
+      this.permanently_remove_messages();
+    // if there isn't a defined trash mailbox and the config is set to flag for deletion
+    else if (!this.env.trash_mailbox && this.env.flag_for_deletion) {
+      flag = 'delete';
+      this.mark_message(flag);
+      if(this.env.action=="show"){
+        this.command('nextmessage','',this);
+      } else if (this.selection.length == 1) {
+        next_row = this.get_next_row();
+        prev_row = this.get_prev_row();
+        new_row = (next_row) ? next_row : prev_row;
+        if (new_row) this.select_row(new_row.uid,false,false);
+      }
+    // if there isn't a defined trash mailbox and the config is set NOT to flag for deletion
+    }else if (!this.env.trash_mailbox && !this.env.flag_for_deletion) {
+      this.permanently_remove_messages();
+    }
+    return;
+  };
 
 
   // set a specific flag to one or more messages
@@ -1406,13 +1819,22 @@
         {
         id = this.selection[n];
         a_uids[a_uids.length] = id;
-      
-        // 'remove' message row from list (just hide it)
-        if (this.message_rows[id].obj)
-          this.message_rows[id].obj.style.display = 'none';
         }
       }
+      switch (flag) {
+        case 'read':
+        case 'unread':
+          this.toggle_read_status(flag,a_uids);
+          break;
+        case 'delete':
+        case 'undelete':
+          this.toggle_delete_status(a_uids);
+          break;
+      }
+    };
 
+  // set class to read/unread
+  this.toggle_read_status = function(flag, a_uids) {
     // mark all message rows as read/unread
     var icn_src;
     for (var i=0; i<a_uids.length; i++)
@@ -1445,12 +1867,111 @@
           this.message_rows[uid].icon.src = icn_src;
         }
       }
+      this.http_request('mark', '_uid='+a_uids.join(',')+'&_flag='+flag);
+  }
+  
+  // mark all message rows as deleted/undeleted
+  this.toggle_delete_status = function(a_uids) {
+    if (this.env.read_when_deleted) {
+      this.toggle_read_status('read',a_uids);
+    }
+    // if deleting message from "view message" don't bother with delete icon
+    if (this.env.action == "show")
+      return false;
 
-    // send request to server
-    this.http_request('mark', '_uid='+a_uids.join(',')+'&_flag='+flag);
+    if (a_uids.length==1){
+      if(this.message_rows[a_uids[0]].classname.indexOf('deleted') < 0 ){
+      	this.flag_as_deleted(a_uids)
+      } else {
+      	this.flag_as_undeleted(a_uids)
+      }
+      return true;
+    }
+    
+    var all_deleted = true;
+    
+    for (var i=0; i<a_uids.length; i++) {
+      uid = a_uids[i];
+      if (this.message_rows[uid]) {
+        if (this.message_rows[uid].classname.indexOf('deleted')<0) {
+          all_deleted = false;
+          break;
+        }
+      }
+    }
+    
+    if (all_deleted)
+      this.flag_as_undeleted(a_uids);
+    else
+      this.flag_as_deleted(a_uids);
+    
+    return true;
+  }
+
+  this.flag_as_undeleted = function(a_uids){
+    // if deleting message from "view message" don't bother with delete icon
+    if (this.env.action == "show")
+      return false;
+
+    var icn_src;
+      
+    for (var i=0; i<a_uids.length; i++) {
+      uid = a_uids[i];
+      if (this.message_rows[uid]) {
+        this.message_rows[uid].deleted = false;
+        
+        if (this.message_rows[uid].classname.indexOf('deleted') > 0) {
+          this.message_rows[uid].classname = this.message_rows[uid].classname.replace(/\s*deleted/, '');
+          this.set_classname(this.message_rows[uid].obj, 'deleted', false);
+        }
+        if (this.message_rows[uid].unread && this.env.unreadicon)
+          icn_src = this.env.unreadicon;
+        else if (this.message_rows[uid].replied && this.env.repliedicon)
+          icn_src = this.env.repliedicon;
+        else if (this.env.messageicon)
+          icn_src = this.env.messageicon;
+        if (this.message_rows[uid].icon && icn_src)
+          this.message_rows[uid].icon.src = icn_src;
+      }
+    }
+    this.http_request('mark', '_uid='+a_uids.join(',')+'&_flag=undelete');
+    return true;
+  }
+  
+  this.flag_as_deleted = function(a_uids) {
+    // if deleting message from "view message" don't bother with delete icon
+    if (this.env.action == "show")
+      return false;
+
+    for (var i=0; i<a_uids.length; i++) {
+      uid = a_uids[i];
+      if (this.message_rows[uid]) {
+        this.message_rows[uid].deleted = true;
+        
+        if (this.message_rows[uid].classname.indexOf('deleted')<0) {
+          this.message_rows[uid].classname += ' deleted';
+          this.set_classname(this.message_rows[uid].obj, 'deleted', true);
+        }
+        if (this.message_rows[uid].icon && this.env.deletedicon)
+          this.message_rows[uid].icon.src = this.env.deletedicon;
+      }
+    }
+    this.http_request('mark', '_uid='+a_uids.join(',')+'&_flag=delete');
+    return true;  
+  }
+
+
+  this.get_mailbox_li = function(mbox)
+    {
+    if (this.gui_objects.mailboxlist)
+      {
+      mbox = String((mbox ? mbox : this.env.mailbox)).toLowerCase().replace(this.mbox_expression, '');
+      return document.getElementById('rcmbx'+mbox);
+      }
+    
+    return null;
     };
-
-
+    
 
   /*********************************************************/
   /*********        message compose methods        *********/
@@ -1502,8 +2023,15 @@
 
     return true;
     };
-    
-    
+
+
+  this.auto_save_start = function()
+    {
+    if (this.env.draft_autosave)
+      this.save_timer = self.setTimeout(this.ref+'.command("savedraft")', this.env.draft_autosave * 1000);
+    };
+
+
   this.compose_field_hash = function()
     {
     // check input fields
@@ -1539,12 +2067,15 @@
     var message = input_message ? input_message.value : '';
     var sig, p;
 
+    if (!this.env.identity)
+      this.env.identity = id
+
     // remove the 'old' signature
     if (this.env.identity && this.env.signatures && this.env.signatures[this.env.identity])
       {
       sig = this.env.signatures[this.env.identity];
-      if (sig.indexOf('-- ')!=0)
-        sig = '-- \n'+sig;
+      if (sig.indexOf('--')!=0)
+        sig = '--\n'+sig;
 
       p = message.lastIndexOf(sig);
       if (p>=0)
@@ -1555,8 +2086,8 @@
     if (this.env.signatures && this.env.signatures[id])
       {
       sig = this.env.signatures[id];
-      if (sig.indexOf('-- ')!=0)
-        sig = '-- \n'+sig;
+      if (sig.indexOf('--')!=0)
+        sig = '--\n'+sig;
       message += '\n'+sig;
       }
 
@@ -1564,6 +2095,7 @@
       input_message.value = message;
       
     this.env.identity = id;
+    return true;
     };
 
 
@@ -1591,12 +2123,15 @@
     // clear upload form
     if (!a && this.gui_objects.attachmentform && this.gui_objects.attachmentform!=this.gui_objects.messageform)
       this.gui_objects.attachmentform.reset();
+    
+    return true;  
     };
 
 
   // upload attachment file
   this.upload_file = function(form)
     {
+    
     if (!form)
       return false;
       
@@ -1640,28 +2175,80 @@
     
     // set reference to the form object
     this.gui_objects.attachmentform = form;
+    return true;
     };
 
 
   // add file name to attachment list
   // called from upload page
-  this.add2attachment_list = function(name)
+  this.add2attachment_list = function(name, content)
     {
     if (!this.gui_objects.attachmentlist)
       return false;
       
     var li = document.createElement('LI');
-    li.innerHTML = name;
+    li.id = name;
+    li.innerHTML = content;
     this.gui_objects.attachmentlist.appendChild(li);
+    return true;
     };
 
+  this.remove_from_attachment_list = function(name)
+    {
+    if (!this.gui_objects.attachmentlist)
+      return false;
+
+    var list = this.gui_objects.attachmentlist.getElementsByTagName("li");
+    for (i=0;i<list.length;i++)
+      if (list[i].id == name)
+        this.gui_objects.attachmentlist.removeChild(list[i]);
+    };
+
+  this.remove_attachment = function(name)
+    {
+    if (name)
+      this.http_request('remove-attachment', '_file='+urlencode(name));
+
+    return true;
+    };
 
   // send remote request to add a new contact
   this.add_contact = function(value)
     {
     if (value)
       this.http_request('addcontact', '_address='+value);
+    
+    return true;
     };
+
+  // send remote request to search mail
+  this.qsearch = function(value, mbox)
+    {
+    if (value && mbox)
+      {
+      this.clear_message_list();
+      this.set_busy(true, 'searching');
+      this.http_request('search', '_search='+value+'&_mbox='+mbox, true);
+      }
+    return true;
+    };
+
+  // reset quick-search form
+  this.reset_qsearch = function()
+    {
+    if (this.gui_objects.qsearchbox)
+      this.gui_objects.qsearchbox.value = '';
+      
+    this.env.search_request = null;
+    return true;
+    };
+
+
+  this.sent_successfully = function(msg)
+    {
+    this.list_mailbox();
+    this.display_message(msg, 'confirmation', true);
+    }
 
 
   /*********************************************************/
@@ -1954,6 +2541,7 @@
       return false;
       
     //if (this.env.framed && add_url=='')
+    
     //  add_url = '&_framed=1';
     
     if (action && (cid || action=='add'))
@@ -1961,15 +2549,16 @@
       this.set_busy(true);
       target.location.href = this.env.comm_path+'&_action='+action+'&_cid='+cid+add_url;
       }
+    return true;
     };
 
 
   this.delete_contacts = function()
     {
     // exit if no mailbox specified or if selection is empty
-    if (!(this.selection.length || this.env.cid))
+    if (!(this.selection.length || this.env.cid) || !confirm(this.get_label('deletecontactconfirm')))
       return;
-    
+      
     var a_cids = new Array();
 
     if (this.env.cid)
@@ -1997,6 +2586,7 @@
 
     // send request to server
     this.http_request('delete', '_cid='+a_cids.join(',')+'&_from='+(this.env.action ? this.env.action : ''));
+    return true;
     };
 
 
@@ -2007,10 +2597,11 @@
       return false;
       
     var row = this.contact_rows[cid].obj;
-    for (var c=0; c<cols_arr.length; c++)
+    for (var c=0; c<cols_arr.length; c++){
       if (row.cells[c])
         row.cells[c].innerHTML = cols_arr[c];
-
+    }
+    return true;
     };
   
   
@@ -2031,6 +2622,8 @@
 
     if (action == 'ldappublicsearch')
       target.location.href = this.env.comm_path+'&_action='+action+add_url;
+      
+    return true;
     };
  
   // add ldap contacts to address book
@@ -2068,7 +2661,7 @@
   this.load_identity = function(id, action)
     {
     if (action=='edit-identity' && (!id || id==this.env.iid))
-      return;
+      return false;
 
     var add_url = '';
     var target = window;
@@ -2084,6 +2677,7 @@
       this.set_busy(true);
       target.location.href = this.env.comm_path+'&_action='+action+'&_iid='+id+add_url;
       }
+    return true;
     };
 
 
@@ -2108,43 +2702,236 @@
 
     // if (this.env.framed && id)
       this.set_busy(true);
-      location.href = this.env.comm_path+'&_action=delete-identity&_iid='+id;
+      location.href = this.env.comm_path+'&_action=delete-identity&_iid='+id;     
     // else if (id)
     //  this.http_request('delete-identity', '_iid='+id);
+    return true;
     };
 
 
+  // tell server to create and subscribe a new mailbox
   this.create_folder = function(name)
     {
+	if (this.edit_folder)
+	  this.reset_folder_rename();
+
     var form;
     if ((form = this.gui_objects.editform) && form.elements['_folder_name'])
       name = form.elements['_folder_name'].value;
 
     if (name)
-      this.http_request('create-folder', '_name='+escape(name), true);
+      this.http_request('create-folder', '_name='+urlencode(name), true);
     else if (form.elements['_folder_name'])
       form.elements['_folder_name'].focus();
     };
 
 
-  this.delete_folder = function(folder)
+  // entry point for folder renaming
+  this.rename_folder = function(props)
     {
-    if (folder)
+    var form, oldname, newname;
+    
+    // rename a specific mailbox
+    if (props)
+      this.edit_foldername(props);
+
+    // use a dropdown and input field (old behavior)
+    else if ((form = this.gui_objects.editform) && form.elements['_folder_oldname'] && form.elements['_folder_newname'])
       {
-      this.http_request('delete-folder', '_mboxes='+escape(folder));
+      oldname = form.elements['_folder_oldname'].value;
+      newname = form.elements['_folder_newname'].value;
+      }
+
+    if (oldname && newname)
+      this.http_request('rename-folder', '_folder_oldname='+urlencode(oldname)+'&_folder_newname='+urlencode(newname));
+    };
+
+
+  // start editing the mailbox name.
+  // this will replace the name string with an input field
+  this.edit_foldername = function(folder)
+    {
+    var temp, row, form;
+    var id = this.get_folder_row_id(folder);
+
+    // reset current renaming
+	if (temp = this.edit_folder)
+	  {
+	  this.reset_folder_rename();
+	  if (temp == id)
+	    return;
+	  }
+
+    if (id && (row = document.getElementById(id)))
+      {
+      this.name_input = document.createElement('INPUT');
+      this.name_input.value = this.env.subscriptionrows[id][1];
+      this.name_input.style.width = '100%';
+      this.name_input.onkeypress = function(e){ rcmail.name_input_keypress(e); };
+      
+      row.cells[0].replaceChild(this.name_input, row.cells[0].firstChild);
+      this.edit_folder = id;
+      this.name_input.select();
+      
+      if (form = this.gui_objects.editform)
+        form.onsubmit = function(){ return false; };
       }
     };
 
 
-  this.remove_folder_row = function(folder)
+  // remove the input field and write the current mailbox name to the table cell
+  this.reset_folder_rename = function()
     {
-    for (var id in this.env.subscriptionrows)
-      if (this.env.subscriptionrows[id]==folder)
+    var cell = this.name_input ? this.name_input.parentNode : null;
+    if (cell && this.edit_folder)
+      cell.innerHTML = this.env.subscriptionrows[this.edit_folder][1];
+      
+    this.edit_folder = null;
+    };
+
+
+  // handler for keyboard events on the input field
+  this.name_input_keypress = function(e)
+    {
+    var key = document.all ? event.keyCode : document.getElementById ? e.keyCode : 0;
+
+    // enter
+    if (key==13)
+      {
+      var newname = this.name_input ? this.name_input.value : null;
+      if (this.edit_folder && newname)
+        this.http_request('rename-folder', '_folder_oldname='+urlencode(this.env.subscriptionrows[this.edit_folder][0])+'&_folder_newname='+urlencode(newname));        
+      }
+    // escape
+    else if (key==27)
+      this.reset_folder_rename();
+    };
+
+
+  // delete a specific mailbox with all its messages
+  this.delete_folder = function(folder)
+    {
+	if (this.edit_folder)
+	  this.reset_folder_rename();
+    
+    if (folder)
+      this.http_request('delete-folder', '_mboxes='+urlencode(folder));
+    };
+
+
+  // add a new folder to the subscription list by cloning a folder row
+  this.add_folder_row = function(name, display_name, replace)
+    {
+    name = name.replace('\\',"");
+    if (!this.gui_objects.subscriptionlist)
+      return false;
+
+    for (var refid in this.env.subscriptionrows)
+      if (this.env.subscriptionrows[refid]!=null)
         break;
 
+    var refrow, form;
+    var tbody = this.gui_objects.subscriptionlist.tBodies[0];
+    var id = replace && replace.id ? replace.id : tbody.childNodes.length+1;
+
+    if (!id || !(refrow = document.getElementById(refid)))
+      {
+      // Refresh page if we don't have a table row to clone
+      location.href = this.env.comm_path+'&_action=folders';
+      }
+    else
+      {
+      // clone a table row if there are existing rows
+      var row = this.clone_table_row(refrow);
+      row.id = 'rcmrow'+id;
+      if (replace)
+        tbody.replaceChild(row, replace);
+      else
+        tbody.appendChild(row);
+      }
+
+    // add to folder/row-ID map
+    this.env.subscriptionrows[row.id] = [name, display_name];
+
+    // set folder name
+    row.cells[0].innerHTML = display_name;
+    if (row.cells[1] && row.cells[1].firstChild.tagName=='INPUT')
+      {
+      row.cells[1].firstChild.value = name;
+      row.cells[1].firstChild.checked = true;
+      }
+       
+    if (row.cells[2] && row.cells[2].firstChild.tagName=='A')
+      row.cells[2].firstChild.onclick = new Function(this.ref+".command('rename-folder','"+name.replace('\'','\\\'')+"')");
+    if (row.cells[3] && row.cells[3].firstChild.tagName=='A')
+      row.cells[3].firstChild.onclick = new Function(this.ref+".command('delete-folder','"+name.replace('\'','\\\'')+"')");
+
+    // add new folder to rename-folder list and clear input field
+    if (!replace && (form = this.gui_objects.editform))
+      {
+      if (form.elements['_folder_oldname'])
+        form.elements['_folder_oldname'].options[form.elements['_folder_oldname'].options.length] = new Option(name,name);
+      if (form.elements['_folder_name'])
+        form.elements['_folder_name'].value = ''; 
+      }
+
+    };
+
+
+  // replace an existing table row with a new folder line
+  this.replace_folder_row = function(oldfolder, newfolder, display_name)
+    {
+    var id = this.get_folder_row_id(oldfolder);
+    var row = document.getElementById(id);
+    
+    // replace an existing table row (if found)
+    this.add_folder_row(newfolder, display_name, row);
+    this.env.subscriptionrows[id] = null;
+    
+    // rename folder in rename-folder dropdown
+    var form, elm;
+    if ((form = this.gui_objects.editform) && (elm = form.elements['_folder_oldname']))
+      {
+      for (var i=0;i<elm.options.length;i++)
+        {
+        if (elm.options[i].value == oldfolder)
+          {
+          elm.options[i].text = display_name;
+          elm.options[i].value = newfolder;
+          break;
+          }
+        }
+
+      form.elements['_folder_newname'].value = '';
+      }
+    };
+    
+
+  // remove the table row of a specific mailbox from the table
+  // (the row will not be removed, just hidden)
+  this.remove_folder_row = function(folder)
+    {
     var row;
+    var id = this.get_folder_row_id(folder);
     if (id && (row = document.getElementById(id)))
       row.style.display = 'none';    
+
+    // remove folder from rename-folder list
+    var form;
+    if ((form = this.gui_objects.editform) && form.elements['_folder_oldname'])
+      {
+      for (var i=0;i<form.elements['_folder_oldname'].options.length;i++)
+        {
+        if (form.elements['_folder_oldname'].options[i].value == folder) 
+          {
+          form.elements['_folder_oldname'].options[i] = null;
+          break;
+          }
+        }
+      }
+    
+    if (form && form.elements['_folder_newname'])
+      form.elements['_folder_newname'].value = '';
     };
 
 
@@ -2154,7 +2941,7 @@
     if ((form = this.gui_objects.editform) && form.elements['_unsubscribed'])
       this.change_subscription('_unsubscribed', '_subscribed', 'subscribe');
     else if (folder)
-      this.http_request('subscribe', '_mboxes='+escape(folder));
+      this.http_request('subscribe', '_mboxes='+urlencode(folder));
     };
 
 
@@ -2164,7 +2951,7 @@
     if ((form = this.gui_objects.editform) && form.elements['_subscribed'])
       this.change_subscription('_subscribed', '_unsubscribed', 'unsubscribe');
     else if (folder)
-      this.http_request('unsubscribe', '_mboxes='+escape(folder));
+      this.http_request('unsubscribe', '_mboxes='+urlencode(folder));
     };
     
 
@@ -2198,45 +2985,21 @@
           list_to[index] = new Option(a_folders[n]);
           }
           
-        this.http_request(action, '_mboxes='+escape(a_folders.join(',')));
+        this.http_request(action, '_mboxes='+urlencode(a_folders.join(',')));
         }
       }
       
     };
 
-
-   // add a new folder to the subscription list by cloning a folder row
-   this.add_folder_row = function(name)
-     {
-     if (!this.gui_objects.subscriptionlist)
-       return false;
-
-     var tbody = this.gui_objects.subscriptionlist.tBodies[0];
-     var id = tbody.childNodes.length+1;
-     
-     // clone a table row
-     var row = this.clone_table_row(tbody.rows[0]);
-     row.id = 'rcmrow'+id;
-     tbody.appendChild(row);
-
-     // add to folder/row-ID map
-     this.env.subscriptionrows[row.id] = name;
-
-     // set folder name
-     row.cells[0].innerHTML = name;
-     if (row.cells[1].firstChild.tagName=='INPUT')
-       {
-       row.cells[1].firstChild.value = name;
-       row.cells[1].firstChild.checked = true;
-       }
-     if (row.cells[2].firstChild.tagName=='A')
-       row.cells[2].firstChild.onclick = new Function(this.ref+".command('delete-folder','"+name+"')");
-
-    var form;
-    if ((form = this.gui_objects.editform) && form.elements['_folder_name'])
-      form.elements['_folder_name'].value = '';
-     };
-
+  // helper method to find a specific mailbox row ID
+  this.get_folder_row_id = function(folder)
+    {
+    for (var id in this.env.subscriptionrows)
+      if (this.env.subscriptionrows[id] && this.env.subscriptionrows[id][0] == folder)
+        break;
+        
+    return id;
+    };
 
   // duplicate a specific table row
   this.clone_table_row = function(row)
@@ -2337,6 +3100,26 @@
       }
     };
 
+  // mouse down on button
+  this.button_sel = function(command, id)
+    {
+    var a_buttons = this.buttons[command];
+    var button, img;
+
+    if(!a_buttons || !a_buttons.length)
+      return;
+
+    for(var n=0; n<a_buttons.length; n++)
+      {
+      button = a_buttons[n];
+      if(button.id==id && button.status=='act')
+        {
+        img = document.getElementById(button.id);
+        if (img && button.sel)
+          img.src = button.sel;
+        }
+      }
+    };
 
   // mouse out of button
   this.button_out = function(command, id)
@@ -2381,15 +3164,16 @@
   // display a system message
   this.display_message = function(msg, type, hold)
     {
+    this.set_busy(false);
     if (!this.loaded)  // save message in order to display after page loaded
       {
       this.pending_message = new Array(msg, type);
       return true;
       }
-    
+  
     if (!this.gui_objects.message)
       return false;
-      
+
     if (this.message_timer)
       clearTimeout(this.message_timer);
     
@@ -2400,7 +3184,7 @@
     this.gui_objects.message._rcube = this;
     this.gui_objects.message.innerHTML = cont;
     this.gui_objects.message.style.display = 'block';
-    
+ 
     if (type!='loading')
       this.gui_objects.message.onmousedown = function(){ this._rcube.hide_message(); return true; };
     
@@ -2423,25 +3207,66 @@
   // mark a mailbox as selected and set environment variable
   this.select_mailbox = function(mbox)
     {
-    if (this.gui_objects.mailboxlist)
+    if (this.gui_objects.mailboxlist )
       {
-      var item, reg, text_obj;
-      var s_current = this.env.mailbox.toLowerCase().replace(this.mbox_expression, '');
-      var s_mbox = String(mbox).toLowerCase().replace(this.mbox_expression, '');
-      var s_current = this.env.mailbox.toLowerCase().replace(this.mbox_expression, '');
-      
-      var current_li = document.getElementById('rcmbx'+s_current);
-      var mbox_li = document.getElementById('rcmbx'+s_mbox);
+      var item, reg, text_obj;      
+      var current_li = this.get_mailbox_li();
+      var mbox_li = this.get_mailbox_li(mbox);
       
       if (current_li)
+        {
         this.set_classname(current_li, 'selected', false);
-      if (mbox_li)
+        this.set_classname(current_li, 'unfocused', false);
+        }
+
+      if (mbox_li || this.env.mailbox == mbox)
+        {
+        this.set_classname(mbox_li, 'unfocused', false);
         this.set_classname(mbox_li, 'selected', true);
+        }
+      }
+      
+    // also update mailbox name in window title
+    if (document.title)
+      {
+      var doc_title = String(document.title);
+      var reg = new RegExp(this.env.mailbox.toLowerCase(), 'i');
+      if (this.env.mailbox && doc_title.match(reg))
+        document.title = doc_title.replace(reg, mbox).replace(/^\([0-9]+\)\s+/i, '');
       }
     
     this.env.mailbox = mbox;
     };
 
+
+  // for reordering column array, Konqueror workaround
+  this.set_message_coltypes = function(coltypes) 
+  { 
+    this.coltypes = coltypes;
+    
+    // set correct list titles
+    var cell, col;
+    var thead = this.gui_objects.messagelist ? this.gui_objects.messagelist.tHead : null;
+    for (var n=0; thead && n<this.coltypes.length; n++) 
+      {
+      col = this.coltypes[n];
+      if ((cell = thead.rows[0].cells[n+1]) && (col=='from' || col=='to'))
+        {
+        // if we have links for sorting, it's a bit more complicated...
+        if (cell.firstChild && cell.firstChild.tagName=='A')
+          {
+          cell.firstChild.innerHTML = this.get_label(this.coltypes[n]);
+          cell.firstChild.onclick = function(){ return rcmail.command('sort', this.__col, this); };
+          cell.firstChild.__col = col;
+          }
+        else
+          cell.innerHTML = this.get_label(this.coltypes[n]);
+
+        cell.id = 'rcmHead'+col;
+        }
+      }
+
+  };
 
   // create a table row in the message list
   this.add_message_row = function(uid, cols, flags, attachment, attop)
@@ -2453,7 +3278,8 @@
     var rowcount = tbody.rows.length;
     var even = rowcount%2;
     
-    this.env.messages[uid] = {replied:flags.replied?1:0,
+    this.env.messages[uid] = {deleted:flags.deleted?1:0,
+                              replied:flags.replied?1:0,
                               unread:flags.unread?1:0};
     
     var row = document.createElement('TR');
@@ -2463,8 +3289,9 @@
     if (this.in_selection(uid))
       row.className += ' selected';
 
-    var icon = flags.unread && this.env.unreadicon ? this.env.unreadicon :
-               (flags.replied && this.env.repliedicon ? this.env.repliedicon : this.env.messageicon);
+    var icon = flags.deleted && this.env.deletedicon ? this.env.deletedicon:
+               (flags.unread && this.env.unreadicon ? this.env.unreadicon :
+               (flags.replied && this.env.repliedicon ? this.env.repliedicon : this.env.messageicon));
 
     var col = document.createElement('TD');
     col.className = 'icon';
@@ -2472,8 +3299,9 @@
     row.appendChild(col);
 
     // add each submitted col
-    for (var c in cols)
-      {
+    for (var n = 0; n < this.coltypes.length; n++) 
+      { 
+      var c = this.coltypes[n];
       col = document.createElement('TD');
       col.className = String(c).toLowerCase();
       col.innerHTML = cols[c];
@@ -2504,16 +3332,26 @@
     this.set_page_buttons();
     };
 
+  // replace content of quota display
+   this.set_quota = function(text)
+     {
+     if (this.gui_objects.quotadisplay)
+       this.gui_objects.quotadisplay.innerHTML = text;
+     };
+			     
 
   // update the mailboxlist
   this.set_unread_count = function(mbox, count, set_title)
     {
     if (!this.gui_objects.mailboxlist)
       return false;
-      
-    var item, reg, text_obj;
+
+    if (mbox==this.env.mailbox)
+      set_title = true;
+
+    var reg, text_obj;
+    var item = this.get_mailbox_li(mbox);
     mbox = String(mbox).toLowerCase().replace(this.mbox_expression, '');
-    item = document.getElementById('rcmbx'+mbox);
 
     if (item && item.className && item.className.indexOf('mailbox '+mbox)>=0)
       {
@@ -2527,16 +3365,16 @@
         text_obj.innerHTML += ' ('+count+')';
       else
         text_obj.innerHTML = text_obj.innerHTML.replace(reg, '');
-          
+
       // set the right classes
       this.set_classname(item, 'unread', count>0 ? true : false);
       }
 
     // set unread count to window title
+    reg = /^\([0-9]+\)\s+/i;
     if (set_title && document.title)
       {
       var doc_title = String(document.title);
-      reg = /^\([0-9]+\)\s+/i;
 
       if (count && doc_title.match(reg))
         document.title = doc_title.replace(reg, '('+count+') ');
@@ -2682,8 +3520,8 @@
     // send request
     if (request_obj)
       {
-      // prompt('request', this.env.comm_path+'&_action='+escape(action)+'&'+querystring);
-      console('HTTP request: '+this.env.comm_path+'&_action='+escape(action)+'&'+querystring);
+      // prompt('request', this.env.comm_path+'&_action='+urlencode(action)+'&'+querystring);
+      console('HTTP request: '+this.env.comm_path+'&_action='+action+'&'+querystring);
 
       if (lock)
         this.set_busy(true);
@@ -2692,7 +3530,7 @@
       request_obj.__action = action;
       request_obj.onerror = function(o){ rcube_webmail_client.http_error(o); };
       request_obj.oncomplete = function(o){ rcube_webmail_client.http_response(o); };
-      request_obj.GET(this.env.comm_path+'&_action='+escape(action)+'&'+querystring);
+      request_obj.GET(this.env.comm_path+'&_action='+action+'&'+querystring);
       }
     };
 
@@ -2701,13 +3539,15 @@
   this.http_response = function(request_obj)
     {
     var ctype = request_obj.get_header('Content-Type');
-    if (ctype)
+    if (ctype){
       ctype = String(ctype).toLowerCase();
+      var ctype_array=ctype.split(";");
+      ctype = ctype_array[0];
+    }
 
-    if (request_obj.__lock)
-      this.set_busy(false);
+    this.set_busy(false);
 
-  console(request_obj.responseText);
+  console(request_obj.get_text());
 
     // if we get javascript code from server -> execute it
     if (request_obj.get_text() && (ctype=='text/javascript' || ctype=='application/x-javascript'))
@@ -2723,9 +3563,12 @@
         break;
 
       case 'list':
+        if (this.env.messagecount)
+          this.enable_command('purge', (this.env.mailbox==this.env.trash_mailbox));
+
       case 'expunge':
         this.enable_command('select-all', 'select-none', 'expunge', this.env.messagecount ? true : false);
-        break;
+        break;      
       }
 
     request_obj.reset();
@@ -2735,7 +3578,7 @@
   // handle HTTP request errors
   this.http_error = function(request_obj)
     {
-    alert('Error sending request: '+request_obj.url);
+    //alert('Error sending request: '+request_obj.url);
 
     if (request_obj.__lock)
       this.set_busy(false);
@@ -2756,6 +3599,13 @@
   // send periodic request to check for recent messages
   this.check_for_recent = function()
     {
+    if (this.busy)
+      {
+      this.send_keep_alive();
+      return;
+      }
+
+    this.set_busy(true, 'checkingmail');
     var d = new Date();
     this.http_request('check-recent', '_t='+d.getTime());
     };
@@ -2778,6 +3628,8 @@
     return this.env.cid ? this.env.cid : (this.selection.length==1 ? this.selection[0] : null);
     };
 
+
+/* deprecated methods
 
   // check if Shift-key is pressed on event
   this.check_shiftkey = function(e)
@@ -2808,6 +3660,33 @@
     else
       return false;
     }
+*/
+
+  // returns modifier key (constants defined at top of file)
+  this.get_modifier = function(e)
+    {
+    var opcode = 0;
+    e = e || window.event;
+
+    if (bw.mac && e)
+      {
+      opcode += (e.metaKey && CONTROL_KEY) + (e.shiftKey && SHIFT_KEY);
+      return opcode;    
+      }
+    if (e)
+      {
+      opcode += (e.ctrlKey && CONTROL_KEY) + (e.shiftKey && SHIFT_KEY);
+      return opcode;
+      }
+    if (e.cancelBubble)
+      {
+      e.cancelBubble = true;
+      e.returnValue = false;
+      }
+    else if (e.preventDefault)
+      e.preventDefault();
+  }
+
 
   this.get_mouse_pos = function(e)
     {
@@ -2968,14 +3847,21 @@
 
     else if(this.xmlhttp.readyState == 4)
       {
-      if(this.xmlhttp.status == 0)
-        this.onabort(this);
-      else if(this.xmlhttp.status == 200)
-        this.oncomplete(this);
-      else
+      try {
+        if (this.xmlhttp.status == 0)
+          this.onabort(this);
+        else if(this.xmlhttp.status == 200)
+          this.oncomplete(this);
+        else
+          this.onerror(this);
+
+        this.busy = false;
+        }
+      catch(err)
+        {
         this.onerror(this);
-        
-      this.busy = false;
+        this.busy = false;
+        }
       }
     }
 

--
Gitblit v1.9.1