Index: branches/2.5/expressoMail1_2/assetic.php
===================================================================
--- branches/2.5/expressoMail1_2/assetic.php	(revision 7919)
+++ branches/2.5/expressoMail1_2/assetic.php	(revision 8232)
@@ -47,5 +47,5 @@
         new FileAsset('../prototype/plugins/watermark/jquery.watermarkinput.js'),
         new FileAsset('../prototype/plugins/fileupload/jquery.iframe-transport.js'),
-        new FileAsset('../prototype/plugins/qtip/jquery.qtip-1.0.0-rc3.min.js'), 
+        new FileAsset('../prototype/plugins/qtip/jquery.qtip-1.0.0-rc3.min.js'),
         new FileAsset('../prototype/plugins/treeview/jquery.treeview.js'),
         new FileAsset('../prototype/plugins/treeview/lib/jquery.cookie.js'),    
Index: branches/2.5/expressoMail1_2/index.php
===================================================================
--- branches/2.5/expressoMail1_2/index.php	(revision 7919)
+++ branches/2.5/expressoMail1_2/index.php	(revision 8232)
@@ -16,5 +16,5 @@
 		'enable_nextmatchs_class' => True
 	);
-	
+
 	require_once('../header.inc.php');
 	include_once dirname(__FILE__) . '/../header.inc.php';
@@ -25,8 +25,13 @@
 	$AlternateEmailExpresso = $alternativeMailService->getMailAlternateByUidNumber($_SESSION['phpgw_info']['expressomail']['user']['account_id']);
 	$template->set_var("user_email_alternative", implode(",", $AlternateEmailExpresso));	
+  	
+  	if (execmethod('emailadmin.ui.countProfiles') == 0){
+        execmethod('emailadmin.ui.addDefaultProfile');
+    }
 
 	$update_version = $GLOBALS['phpgw_info']['apps']['expressoMail1_2']['version'];
 	$_SESSION['phpgw_info']['expressomail']['user'] = $GLOBALS['phpgw_info']['user'];
 	echo "<script type='text/javascript'>var template = '".$_SESSION['phpgw_info']['expressoMail1_2']['user']['preferences']['common']['template_set']."';</script>";
+
 
 	//jquery and Editor 
@@ -74,5 +79,21 @@
 		  <script type="text/javascript" src="js/DropDownContacts.js"></script>
 		  ';
-	
+
+//
+//    include_once(__DIR__.'/inc/class.imap_functions.inc.php');
+//
+//    $param = array();
+//    $param['folder'] = 'INBOX';
+//    $param['msg_range_begin'] = '1';
+//    $param['msg_range_end'] = '50';
+//    $param['sort_box_type'] = 'SORTARRIVAL';
+//    $param['search_box_type'] = 'ALL';
+//    $param['sort_box_reverse'] = '1';
+//
+//    $imapf = new imap_functions();
+//    $initialMessages = $imapf->get_range_msgs2($param);
+//
+//    echo '<script type="text/javascript"> var initialMessages  = '.json_encode($initialMessages).'</script>';
+
 	/*
 	 * TODO: implementar o controle como preferência do usuário 
@@ -251,6 +272,6 @@
     }
 
-    echo '<script type="text/javascript"> var preferences  = '.json_encode($_SESSION['phpgw_info']['user']['preferences']['expressoMail']).'</script>'; 
- 
+    echo '<script type="text/javascript"> var preferences  = '.json_encode($_SESSION['phpgw_info']['user']['preferences']['expressoMail']).'</script>';
+
     echo '
 	<script> var special_folders = new Array(4);
@@ -334,5 +355,5 @@
 	//echo $obj -> getFilesJs("js/common_functions.js",$update_version);
 	include("inc/load_lang.php");
-    
+
     // INCLUDE these JS Files:
 	if ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_local_messages']) 
@@ -349,6 +370,6 @@
 	echo "<script> use_local_messages = ".$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_local_messages']."</script>";		
 	if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_local_messages'])
-		$scripts .= "js/local_messages.js";	
-		
+		$scripts .= "js/local_messages.js";
+
 	echo '
 		<!--<script type="text/javascript" src="../prototype/modules/mail/js/followupflag.js"></script>-->
@@ -360,9 +381,26 @@
 	';
 
-	echo 
+//////////////////////////////////////////// Carregar Timezones para o javascript /////////////////////////////////////////
+
+    $zones = timezone_identifiers_list();
+    $Time = new DateTime('now', new DateTimeZone('UTC'));
+    $timezone = array();
+
+    foreach ($zones as $zone)
+    {
+        $timezone['timezones'][$zone] = $Time->setTimezone(new DateTimeZone($zone))->format('O');
+    }
+
+    $localtime = localtime(time(), true);
+    $timezone['isDaylightSaving'] =  !!$localtime['tm_isdst'] ? 1 : 0;
+
+    echo '<script type="text/javascript"> var Timezone  = '.json_encode($timezone).'</script>';
+
+////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+	echo
 	    '<script src="../prototype/plugins/datejs/date-pt-BR.js" language="javascript" ></script>
-		<script src="../prototype/modules/calendar/js/timezone.js" language="javascript" ></script>
-                <script src="../prototype/plugins/dateFormat/dateFormat.js" language="javascript" ></script> 
-                <script src="../prototype/modules/calendar/js/calendar.date.js" language="javascript" ></script> 
+		<script src="../prototype/plugins/dateFormat/dateFormat.js" language="javascript" ></script>
+		<script src="../prototype/modules/calendar/js/calendar.date.js" language="javascript" ></script>
 		<script src="../prototype/modules/calendar/js/calendar.codecs.js" language="javascript" ></script>
 		<script src="../prototype/modules/calendar/js/calendar.alarms.js" language="javascript" ></script>
@@ -371,7 +409,31 @@
 	echo $obj -> getFilesJs($scripts, $update_version);
 	echo '<script type="text/javascript">connector.updateVersion = "'.$update_version.'";</script>';
-		
 	echo '<script type="text/javascript" src="assetic.php"></script>';
-	
+
+/////////   Verifica se o usuario esta fora do escritorio imprime a variavel javascript "outOfficeFlag" /////////////////////////////
+
+    include_once(__DIR__ .'/../library/Net/Sieve.php');
+    $sieveConf  =  parse_ini_file( __DIR__."/../prototype/config/Sieve.srv", true );
+    $sieveConf = $sieveConf['config'];
+    $sieve = new Net_Sieve();
+    $inVacation = false;
+    @$sieve->connect( $sieveConf['host'] , $sieveConf['port'] , $sieveConf['options'] , $sieveConf['useTLS'] );
+    @$sieve->login( $_SESSION['wallet']['Sieve']['user'], $_SESSION['wallet']['Sieve']['password'] , $sieveConf['loginType']);
+    $script = $sieve->getScript($sieve->getActive());
+    $pos = strripos($script, "#PseudoScript#");
+    $pseudo_script = substr( $script, $pos+17 );
+    $sieveRules = json_decode( $pseudo_script, true );
+    foreach( $sieveRules as $i => $v)
+        if($v['id'] == 'vacation' && $v['enabled'] == 'true')
+            $inVacation = true;
+
+    if($inVacation)
+        echo '<script language="javascript"> write_msg(get_lang("Attention, you are in out of office mode."), true);   </script>';
+
+//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+
+
+
 
 	// Get Preferences or redirect to preferences page.
Index: branches/2.5/expressoMail1_2/templates/default/index.tpl
===================================================================
--- branches/2.5/expressoMail1_2/templates/default/index.tpl	(revision 8113)
+++ branches/2.5/expressoMail1_2/templates/default/index.tpl	(revision 8232)
@@ -209,5 +209,5 @@
 <div class="expressomail-module-container" style="display: none;"></div>
 <div id="importEmails" style="display:none;padding:5px;"></div>
-<div id="importEmailsLocal" style="display:none;padding:5px;"></div> 
+<div id="importEmailsLocal" style="display:none;padding:5px;"></div>
 <div id="sendFileMessages" style="display:none;"></div>
 <div id="quickAddContact" style="display:none;"></div>
Index: branches/2.5/expressoMail1_2/templates/default/main.css
===================================================================
--- branches/2.5/expressoMail1_2/templates/default/main.css	(revision 7762)
+++ branches/2.5/expressoMail1_2/templates/default/main.css	(revision 8232)
@@ -1245,5 +1245,6 @@
 	font-weight : bold;
 	padding-right : 5px;
-	padding-left : 25px;	
+	padding-left : 5px;	
+	padding-top : 2px;	
 	font-family : Lucida Grande, Lucida Sans, Arial, sans-serif;
 	font-size : 11px;
@@ -1255,9 +1256,10 @@
 	background-position: 0 -923px;
 	background-repeat:no-repeat;
-	padding-left : 20px;
+	padding-right : 5px;
+	padding-left : 5px;	
+	padding-top : 2px;	
 	color : red;
 	text-align: right;
 	font-weight : bold;
-	padding-right : 5px;
 }
 
@@ -1641,2 +1643,9 @@
 	top: 585px;
 }		
+
+@media screen and (max-width: 1100px){
+	#span_options, #span_D span
+	{
+		font-size: 0.8333em; /*10/12px*/
+	}
+}
Index: branches/2.5/expressoMail1_2/setup/phpgw_pt-br.lang
===================================================================
--- branches/2.5/expressoMail1_2/setup/phpgw_pt-br.lang	(revision 8117)
+++ branches/2.5/expressoMail1_2/setup/phpgw_pt-br.lang	(revision 8232)
@@ -972,4 +972,8 @@
 MailArchiver user logged out	expressoMail1_2	pt-br	Usuário desconectado do MailArchiver
 Error trying to send the message. Retry in a few seconds...	expressoMail1_2	pt-br	Erro ao tentar enviar a mensagem. Nova tentativa em alguns segundos...
+Create filter from message	expressoMail1_2	pt-br	Criar filtro a partir da mensagem
 Sending the message...	expressoMail1_2	pt-br	Enviando a mensagem...
-Local Archive	expressoMail1_2	pt-br	Arquivamento Local
+Please, Wait the messages from archieve be ready.	expressoMail1_2	pt-br	Por favor, Aguarde as mensagens arquivadas ficarem prontas.
+take on this option to regard the message body in the search.	expressoMail1_2	pt-br	Considerar o corpo da mensagem como filtro na busca
+take off this option to disregard the message body in the search.	expressoMail1_2	pt-br	Desconsiderar o corpo da mensagem como filtro na busca
+Local Archive	expressoMail1_2	pt-br	Arquivamento Local 
Index: branches/2.5/expressoMail1_2/setup/tables_update.inc.php
===================================================================
--- branches/2.5/expressoMail1_2/setup/tables_update.inc.php	(revision 7516)
+++ branches/2.5/expressoMail1_2/setup/tables_update.inc.php	(revision 8232)
@@ -330,8 +330,13 @@
 
 	$test[] = '2.4.8.2';
-    	function expressoMail1_2_upgrade2_4_8_2() {
-        	$GLOBALS['setup_info']['expressoMail1_2']['currentver'] = '2.5.0';
-        	return $GLOBALS['setup_info']['expressoMail1_2']['currentver'];
-    	}
-
+    function expressoMail1_2_upgrade2_4_8_2() {
+        $GLOBALS['setup_info']['expressoMail1_2']['currentver'] = '2.5.0';
+        return $GLOBALS['setup_info']['expressoMail1_2']['currentver'];
+    }
+
+    $test[] = '2.5.0';
+    function expressoMail1_2_upgrade2_5_0() {
+        $GLOBALS['setup_info']['expressoMail1_2']['currentver'] = '2.5.1';
+        return $GLOBALS['setup_info']['expressoMail1_2']['currentver'];
+    }
 ?>
Index: branches/2.5/expressoMail1_2/setup/setup.inc.php
===================================================================
--- branches/2.5/expressoMail1_2/setup/setup.inc.php	(revision 7516)
+++ branches/2.5/expressoMail1_2/setup/setup.inc.php	(revision 8232)
@@ -13,5 +13,5 @@
 $setup_info['expressoMail1_2']['name'] = 'expressoMail1_2';
 $setup_info['expressoMail1_2']['title'] = 'Expresso Mail';
-$setup_info['expressoMail1_2']['version'] = '2.5.0';
+$setup_info['expressoMail1_2']['version'] = '2.5.1';
 $setup_info['expressoMail1_2']['app_order'] = 2;
 $setup_info['expressoMail1_2']['tables'][] = 'phpgw_certificados';
@@ -46,5 +46,5 @@
 $setup_info['expressoMail1_2']['depends'][] = array(
     'appname' => 'phpgwapi',
-    'versions' => Array('2.5.0')
+    'versions' => Array('2.5.1.1')
 );
 
Index: branches/2.5/expressoMail1_2/inc/class.db_functions.inc.php
===================================================================
--- branches/2.5/expressoMail1_2/inc/class.db_functions.inc.php	(revision 7673)
+++ branches/2.5/expressoMail1_2/inc/class.db_functions.inc.php	(revision 8232)
@@ -147,14 +147,33 @@
 		return $stringDropDownContacts;
 	}
-	
-	function getContactsByGroupAlias($alias)
-	{
+function getContactsByGroupAlias($alias)
+	{
+		/*
 		list($alias,$uid) = explode("::",$alias);		
+		
 		$cc_related_ids = $_SESSION['phpgw_info']['expressomail']['user']['cc_related_ids'];		
 		// Explode personal group, If exists related ids (the user has permission to send email).
+		
 		if(is_array($cc_related_ids) && $uid){
-			$owner =  array_search($uid,$cc_related_ids);			
-		}
-		
+			$owner =  array_search($uid,$cc_related_ids);					
+		}*/
+		$groups = $this->get_cc_groups();
+		if ($groups){
+			$groups = explode(",", $groups);
+			for($ii=0; $ii < count($groups); ++$ii) {
+				$tmp = preg_split("/;|\::/",$groups[$ii]);
+				$relatedGroups[$ii] = array("name" => $tmp[0],"alias" => $tmp[1],"owner" => $tmp[2]);
+			}
+			foreach ($relatedGroups as $key => $value) {
+				if ($value["alias"] == $alias)
+				 	$owner = $value["owner"];
+			}
+			if ($owner){
+					include_once("class.ldap_functions.inc.php");
+					$ldap = new ldap_functions();			
+					$owner = $ldap->uid2uidnumber($owner);
+			}
+		}
+
 		$query = "select C.id_connection, A.names_ordered, C.connection_value from phpgw_cc_contact A, ".
 		"phpgw_cc_contact_conns B, phpgw_cc_connections C,phpgw_cc_contact_grps D,phpgw_cc_groups E where ".
Index: branches/2.5/expressoMail1_2/inc/class.imap_functions.inc.php
===================================================================
--- branches/2.5/expressoMail1_2/inc/class.imap_functions.inc.php	(revision 8114)
+++ branches/2.5/expressoMail1_2/inc/class.imap_functions.inc.php	(revision 8232)
@@ -42,5 +42,5 @@
 	var $useCache = false;
 	var $expirationCache = false;
-
+    var $msgIds = array();// Usado para guardar o messagesIds
         
 	function imap_functions (){
@@ -233,69 +233,74 @@
                                     ++$i;
                             }
-							
-							$filter = array('AND', array('=', 'folderName', $folder), array('IN','messageNumber', $sort_array_msg));
-							$followupflagged = Controller::find(
-								array('concept' => 'followupflagged'),
-								false, 
-								array('filter' => $filter, 'criteria' => array('deepness' => '2'))
-							);
-							$labeleds = Controller::find(
-								array('concept' => 'labeled'),
-								false, 
-								array('filter' => $filter, 'criteria' => array('deepness' => '2'))
-							);
-                            $sort_array_msg_count = count($sort_array_msg);
-							for($i=0; $i<$sort_array_msg_count; ++$i){
-								if(!isset($return[$i]['msg_number']))
-									continue;
-									
-								$numFlags = count($followupflagged);
-								for($ii=0; $ii<$numFlags; ++$ii){
-									if($return[$i]['msg_number'] == $followupflagged[$ii]['messageNumber']){
-										$followupflag = Controller::read( array( 'concept' => 'followupflag', 'id' => $followupflagged[$ii]['followupflagId'] ));
-										$return[$i]['followupflagged'] = $followupflagged[$ii];
-										$return[$i]['followupflagged']['followupflag'] = $followupflag;
-										break;
-									}
-								}
-								$numLabels = count($labeleds);
-								for($ii=0; $ii<$numLabels; ++$ii){
-									if($return[$i]['msg_number'] == $labeleds[$ii]['messageNumber']){
-										$labels = Controller::read( array( 'concept' => 'label', 'id' =>  $labeleds[$ii]['labelId'])); 
-										$return[$i]['labels'][$labeleds[$ii]['labelId']] = $labels;
-									}
-								}
-							}
+                            if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_followupflags_and_labels'] == "1")
+                            {
+                                $filter = array('AND', array('=', 'folderName', $folder), array('IN','messageNumber', $sort_array_msg));
+                                $followupflagged = Controller::find(
+                                    array('concept' => 'followupflagged'),
+                                    false,
+                                    array('filter' => $filter, 'criteria' => array('deepness' => '2'))
+                                );
+                                $labeleds = Controller::find(
+                                    array('concept' => 'labeled'),
+                                    false,
+                                    array('filter' => $filter, 'criteria' => array('deepness' => '2'))
+                                );
+                                $sort_array_msg_count = count($sort_array_msg);
+                                for($i=0; $i<$sort_array_msg_count; ++$i){
+                                    if(!isset($return[$i]['msg_number']))
+                                        continue;
+
+                                    $numFlags = count($followupflagged);
+                                    for($ii=0; $ii<$numFlags; ++$ii){
+                                        if($return[$i]['msg_number'] == $followupflagged[$ii]['messageNumber']){
+                                            $followupflag = Controller::read( array( 'concept' => 'followupflag', 'id' => $followupflagged[$ii]['followupflagId'] ));
+                                            $return[$i]['followupflagged'] = $followupflagged[$ii];
+                                            $return[$i]['followupflagged']['followupflag'] = $followupflag;
+                                            break;
+                                        }
+                                    }
+                                    $numLabels = count($labeleds);
+                                    for($ii=0; $ii<$numLabels; ++$ii){
+                                        if($return[$i]['msg_number'] == $labeleds[$ii]['messageNumber']){
+                                            $labels = Controller::read( array( 'concept' => 'label', 'id' =>  $labeleds[$ii]['labelId']));
+                                            $return[$i]['labels'][$labeleds[$ii]['labelId']] = $labels;
+                                        }
+                                    }
+                                }
+                            }
                     }
                     $return['num_msgs'] =  $num_msgs;   
-		} else {
+		}
+        else
+        {
 			$num_msgs = imap_num_msg($this->mbox);
 			$sort_array_msg = $this-> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse,$msg_range_begin,$num_msgs);
 
-
 			$return['tot_unseen'] = 0;
 			$i = 0;
 
-                        if(is_array($sort_array_msg)){
-
-                            foreach($sort_array_msg as $msg_number => $value)
-                            {
-                                $temp = $this->get_info_head_msg($msg_number);
-                                if(!$temp)
-                                    return false;
-
-                                if($temp['Unseen'] == 'U' || $temp['Recent'] == 'N'){
-						$return['tot_unseen']++;
-					}
-
-                                if($i <= ($msg_range_end-$msg_range_begin))
-                                    $return[$i] = $temp;
-                                ++$i;
-                            }
-                        }
-      			$return['num_msgs'] = count($sort_array_msg)+($msg_range_begin-1);
+            if(is_array($sort_array_msg))
+            {
+                foreach($sort_array_msg as $msg_number => $value)
+                {
+                    $temp = $this->get_info_head_msg($msg_number);
+                    if(!$temp)
+                        return false;
+
+                    if($temp['Unseen'] == 'U' || $temp['Recent'] == 'N')
+                        $return['tot_unseen']++;
+
+                    if($i <= ($msg_range_end-$msg_range_begin))
+                        $return[$i] = $temp;
+
+                    ++$i;
                 }
-				          	
-                return $return; 
+            }
+
+            $return['num_msgs'] = count($sort_array_msg)+($msg_range_begin-1);
+        }
+
+        $return['messagesIds'] = $this->msgIds;
+        return $return;
     }
 	
@@ -458,7 +463,13 @@
             $return['attachment'] = ( preg_match('/((Content-Disposition:(.)*([\r\n\s]*filename))|(Content-Type:(.)*([\r\n\s]*name)))/i', $mimeBody) ) ? '1' : '0'; //Verifica se a anexos na mensagem
             $return['reply_toaddress'] = isset($header->reply_toaddress) ? self::decodeMimeString($header->reply_toaddress) : '';
-            $return['flag'] = $header->Unseen.$header->Recent.$header->Flagged.$header->Draft.$header->Answered.$header->Deleted.( $return['attachment'] === '1' ? 'T': '' );
-			
-			if (!empty($header->to)){
+            $return['flag'] = $header->Unseen.
+                $header->Recent.
+                ($header->Flagged == 'F' || !( preg_match('/importance *: *(.*)\r/i', $mimeHeader , $importance) === 0 )? 'F' : '').
+                $header->Draft.
+                $header->Answered.
+                $header->Deleted.
+                ( $return['attachment'] === '1' ? 'T': '' );
+
+        if (!empty($header->to)){
 				foreach ($header->to as $i => $v){
 					$return['to'][$i] = self::formatMailObject( $v );
@@ -592,10 +603,10 @@
 					if (zip_entry_open($zip, $zip_entry, "r")) {
 						$email = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
- 
-                                                /*Caso mensagens vierem com quebras de linha diferentes do esperado, como por exemplo, 
-                                                mensagens exportadas pelo MailArchiver, é preciso corrigir.*/ 
-                                                $email = str_replace("\r\n", "\n", $email); 
-                                                $email = str_replace("\n", "\r\n", $email); 
- 
+
+						/*Caso mensagens vierem com quebras de linha diferentes do esperado, como por exemplo,
+						mensagens exportadas pelo MailArchiver, é preciso corrigir.*/
+						$email = str_replace("\r\n", "\n", $email);
+						$email = str_replace("\n", "\r\n", $email);
+
 						$status = @imap_append($this->mbox,
 								"{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$params["folder"],
@@ -620,10 +631,10 @@
 		}else if(substr($filename,strlen($filename)-4)==".eml") {
 			$email = implode("",file($params['FILES'][0]['tmp_name']));
- 
-                        /*Caso mensagens vierem com quebras de linha diferentes do esperado, como por exemplo, 
-                        mensagens exportadas pelo MailArchiver, é preciso corrigir.*/ 
-                        $email = str_replace("\r\n", "\n", $email); 
-                        $email = str_replace("\n", "\r\n", $email); 
- 
+
+			/*Caso mensagens vierem com quebras de linha diferentes do esperado, como por exemplo,
+			mensagens exportadas pelo MailArchiver, é preciso corrigir.*/
+			$email = str_replace("\r\n", "\n", $email);
+			$email = str_replace("\n", "\r\n", $email);
+
 			$status = imap_append($this->mbox,"{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$params["folder"],$email);
 				
@@ -954,4 +965,5 @@
 
                                    $content .= $this->decodeMailPart($part->body,$part->ctype_parameters['charset']);
+                                   $i = -1;
                                 }
 
@@ -962,26 +974,26 @@
 
                                    $content .= '<pre>'. htmlentities($this->decodeMailPart($part->body,$part->ctype_parameters['charset'],false)).'</pre>';
+                                   $i = -1;
                                 }
-                                if(strtolower($part->ctype_secondary) == 'calendar')
-                                    $content.= $this->builderMsgCalendar($this->decodeMailPart($part->body, $part->ctype_parameters['charset']));
-
+                               // Comentado para tratamento de e-mail multipart alternative com html e ical. Parseava o ical e ignorava o html.
+                               //if(strtolower($part->ctype_secondary) == 'calendar')
+                               //     $content.= $this->builderMsgCalendar($this->decodeMailPart($part->body, $part->ctype_parameters['charset']));
                            }
 
-                            $i = -1;
                             break;
 
                        case 'multipart':
 
- 	                    if(strtolower($part->ctype_secondary) == 'alternative' ) //Unico formato multipart suportado, escapa os outros 
- 	                    { 
- 	                        if($printHeader) 
- 	                            $content .= $this->builderMsgHeader($part); 
-
- 	                        $this->builderMsgBody($part,$content); 
-
- 	                        $i = -1; 
- 	                    } 
- 
- 	                    break;
+                           if(strtolower($part->ctype_secondary) == 'alternative' ) //Unico formato multipart suportado, escapa os outros
+                           {
+                               if($printHeader)
+                                   $content .= $this->builderMsgHeader($part);
+
+                               $this->builderMsgBody($part,$content);
+
+                               $i = -1;
+                           }
+
+                           break;
 
                        case 'message':
@@ -1211,6 +1223,6 @@
 
 		$return['msg_number'] = $msg_number.$plus_id;
-                $return['msg_folder'] = mb_convert_encoding( $msg_folder, "ISO-8859-1", "UTF-8" ); 
-                //isset($params['decoded']) ? mb_convert_encoding( $msg_folder, "ISO-8859-1", "UTF-8" ) : $msg_folder; 
+		$return['msg_folder'] = mb_convert_encoding( $msg_folder, "ISO-8859-1", "UTF-8" );
+		//isset($params['decoded']) ? mb_convert_encoding( $msg_folder, "ISO-8859-1", "UTF-8" ) : $msg_folder;
 
 		
@@ -1460,5 +1472,5 @@
 		}  
 		$return['alarm'] = $alarm;
-		
+
 		return $return;
 	}
@@ -2186,8 +2198,8 @@
 	function delete_msgs($params)
 	{
-
 		$folder = $params['folder'];
 		$folder =  mb_convert_encoding($folder, "UTF7-IMAP","ISO-8859-1");
 		$msgs_number = explode(",",$params['msgs_number']);
+
 		if(array_key_exists('border_ID' ,$params))
 		$border_ID = $params['border_ID'];
@@ -2205,5 +2217,5 @@
 	 	$mbox_stream = @imap_open("{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$folder, $this->username, $this->password) or die(serialize(array('imap_error' => $this->parse_error(imap_last_error()))));
 
-		foreach ($msgs_number as $msg_number)
+        foreach ($msgs_number as $msg_number)
 		{
 			if (imap_delete($mbox_stream, $msg_number, FT_UID));
@@ -2650,10 +2662,10 @@
 	function ren_mailbox($arr)
 	{
-                $namebox = $arr['current'];              
-                $path_delimiter = strrpos($namebox,$this->imap_delimiter)+1; 
-                $base_path = substr($namebox,0,$path_delimiter); 
-                $rename = preg_split("/\/|\./",substr($arr['rename'], $path_delimiter)); 
-                $new_box = array_shift($rename); 
-                $subfolders = $rename; 
+		$namebox = $arr['current'];		
+		$path_delimiter = strrpos($namebox,$this->imap_delimiter)+1;
+		$base_path = substr($namebox,0,$path_delimiter);
+		$rename = preg_split("/\/|\./",substr($arr['rename'], $path_delimiter));
+		$new_box = array_shift($rename);
+		$subfolders = $rename;
 		$imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
 		$mbox_stream = $this->open_mbox();
@@ -2666,20 +2678,20 @@
 			$result = imap_last_error();
 		}
-                /*Cria as subpastas*/ 
-                if (is_array($subfolders)){ 
-                        $child = $new_box.$this->imap_delimiter; 
-            $subfolders_count = count($subfolders); 
-                        for($i =0; $i < $subfolders_count; ++$i){ 
-                                $child .= ($subfolders[$i] ? $subfolders[$i] : $this->functions->getLang("New Folder")); 
-                                $namebox =  mb_convert_encoding($child, "UTF7-IMAP", "UTF-8"); 
-                                $result = "Ok"; 
-                                if(!imap_createmailbox($mbox_stream,"{".$imap_server."}$namebox")) 
-                                { 
-                                        $result = imap_last_error();                                             
-                                } 
-                                $child .=$this->imap_delimiter; 
-                        }                        
-                } 
- 
+		/*Cria as subpastas*/
+		if (is_array($subfolders)){
+			$child = $new_box.$this->imap_delimiter;
+            $subfolders_count = count($subfolders);
+			for($i =0; $i < $subfolders_count; ++$i){
+				$child .= ($subfolders[$i] ? $subfolders[$i] : $this->functions->getLang("New Folder"));
+				$namebox =  mb_convert_encoding($child, "UTF7-IMAP", "UTF-8");
+				$result = "Ok";
+				if(!imap_createmailbox($mbox_stream,"{".$imap_server."}$namebox"))
+				{
+					$result = imap_last_error();						
+				}
+				$child .=$this->imap_delimiter;
+			}			
+		}
+
 		if($mbox_stream)
 			imap_close($mbox_stream);
@@ -2711,5 +2723,23 @@
 		return $return;
 	}
-	
+
+	/*Método utilizado para retornar dados da mensagem local (desarquivada na pasta lixeira)
+	para poder ser anexada à mensagem.*/
+    function get_info_msg_archiver($params){
+        $folder = "INBOX".$this->imap_delimiter.$this->folders['trash'];
+        $mbox_stream = $this->open_mbox($folder);
+        $id = $params['idMsgs'];
+
+        $name = imap_headerinfo($mbox_stream, imap_msgno($mbox_stream, $id));
+        $return[] =  array(
+            'uid' => $id,
+            'folder' => "archiver",
+            'type' => "imapMSG",
+            'name' => base64_encode($name->subject.".eml")
+        );
+
+        return json_encode($return);
+    }
+
 	function send_mail($params) {
             require_once dirname(__FILE__) . '/../../services/class.servicelocator.php';
@@ -2934,5 +2964,5 @@
 					$arr_new_folder['base_path'] = $base_path;
 
-					$this->create_mailbox($arr_new_folder);					
+					$this->create_mailbox($arr_new_folder);	
 					$has_new_folder = true;
                     $folder = $newfolder;
@@ -2954,5 +2984,5 @@
 
 			$from = $fromaddress ?  ('"' . $fromaddress[0] . '" <' . $fromaddress[1] . '>') : ('"' . $_SESSION['phpgw_info']['expressomail']['user']['firstname'] . ' ' . $_SESSION['phpgw_info']['expressomail']['user']['lastname'] . '" <' . $_SESSION['phpgw_info']['expressomail']['user']['email'] . '>');
-			$mailService->setFrom($from);				
+			$mailService->setFrom( mb_convert_encoding($from, "ISO-8859-1","UTF-8, ISO-8859-1"));
         
 			$mailService->addHeaderField('Reply-To', !!$replytoaddress ? $replytoaddress : $from);
@@ -3004,6 +3034,5 @@
             $isHTML = ( isset($params['type']) && $params['type'] == 'html' )?  true : false;
 
-
-    //	TODO - tratar mensagem criptografada e remover o AND false abaixo
+    		//	TODO - tratar mensagem criptografada e remover o AND false abaixo
             if (($encrypt && $signed && $params['smime']) || ($encrypt && !$signed) AND false) { // a msg deve ser enviada cifrada...
                 $email = $this->add_recipients_cert($toaddress . ',' . $ccaddress . ',' . $ccoaddress);
@@ -3103,4 +3132,7 @@
                 {
                     $value = json_decode($value, true);
+                    if($value["folder"] == "archiver"){
+                        $value['folder'] = "INBOX/Trash";
+                    }
 
                     switch ($value['type']) {
@@ -3110,5 +3142,5 @@
                                 if(strstr($body,'src="./inc/get_archive.php?msgFolder='.$value['folder'].'&msgNumber='.$value['uid'].'&indexPart='.$value['part'].'"') !== false)//Embeded IMG
                                 {    
-                                    $body = str_ireplace('src="./inc/get_archive.php?msgFolder='.$value['folder'].'&msgNumber='.$value['uid'].'&indexPart='.$value['part'].'"' , 'src="'.$att['name'].'"', $body);
+                                    $body = str_ireplace('src="./inc/get_archive.php?msgFolder='.$value['folder'].  '&msgNumber='.$value['uid'].'&indexPart='.$value['part'].'"' , 'src="'.$att['name'].'"', $body);
                                     $mailService->addStringImage($att['source'], $att['type'],mb_convert_encoding($att['name'], 'ISO-8859-1' , 'UTF-8,ISO-8859-1') );
                                 }
@@ -3124,4 +3156,5 @@
                                 
                                 $mailService->addStringAttachment($rawmsg, mb_convert_encoding(base64_decode($value['name']), 'ISO-8859-1' , 'UTF-8,ISO-8859-1'), 'message/rfc822', '7bit', 'attachment' );
+                                /*envia o anexo para o email*/
                                 $message_size_total += mb_strlen($rawmsg); //Adiciona o tamanho do anexo a variavel que controlao tamanho da msg.
                                 unset($rawmsg);
@@ -3419,4 +3452,7 @@
 			$sort = array();
 		}
+
+        $this->msgIds = $sort;
+
 		if ($slice_array)
 			$sort = array_slice($sort,$offsetBegin-1,$offsetEnd-($offsetBegin-1),true);
@@ -3556,4 +3592,18 @@
 	}
 
+    function verifyShareFolder($params){
+        $folder = $params['folder'];
+
+         if (substr($folder,0,4) == 'user'){
+            $acl = $this->getacltouser($folder, isset($params['decoded']));
+
+            $acl_share_delete = (stripos($acl,'t') !== false && stripos($acl,'e') !== false);
+
+            if (!$acl_share_delete) {
+                $return['status'] = false;
+                return $return;
+            }
+        }
+    }
 	function move_messages($params)
 	{
@@ -3676,5 +3726,5 @@
 	}
 	
-	function set_messages_flag_from_search($params){		
+	function set_messages_flag_from_search($params){
 		$error = False;
 		$fileNames = "";
@@ -4404,29 +4454,31 @@
                                             $elem['uid'] = $new_search;
                                             /* compare dates in ordering */
-                                            $elem['udatecomp'] = substr ($elem['udate'], -4) ."-". substr ($elem['udate'], 3, 2) ."-". substr ($elem['udate'], 0, 2);  
-
-											$filter = array('AND', array('=', 'folderName', $name_box), array('=','messageNumber', $new_search));
-											$followupflagged = Controller::find(
-												array('concept' => 'followupflagged'),
-												false, 
-												array('filter' => $filter, 'criteria' => array('deepness' => '2'))
-											);
-
-											if(isset($followupflagged[0]['followupflagId']))
-											{
-												$followupflag = Controller::read( array( 'concept' => 'followupflag', 'id' => $followupflagged[0]['followupflagId'] ));     
-												$followupflagged[0]['followupflag'] = $followupflag;
-												$elem['followupflagged'] = $followupflagged[0];
-
-											}	
-											$labeleds = Controller::find(
-												array('concept' => 'labeled'),
-												false, 
-												array('filter' => $filter, 'criteria' => array('deepness' => '2'))
-											);
-											foreach ($labeleds as $e){
-												$labels = Controller::read( array( 'concept' => 'label', 'id' =>  $e['labelId']));     
-												$elem['labels'][$e['labelId']] = $labels;
-}											
+                                            $elem['udatecomp'] = substr ($elem['udate'], -4) ."-". substr ($elem['udate'], 3, 2) ."-". substr ($elem['udate'], 0, 2);
+                                            if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_followupflags_and_labels'] == "1")
+                                            {
+                                                $filter = array('AND', array('=', 'folderName', $name_box), array('=','messageNumber', $new_search));
+                                                $followupflagged = Controller::find(
+                                                    array('concept' => 'followupflagged'),
+                                                    false,
+                                                    array('filter' => $filter, 'criteria' => array('deepness' => '2'))
+                                                );
+
+                                                if(isset($followupflagged[0]['followupflagId']))
+                                                {
+                                                    $followupflag = Controller::read( array( 'concept' => 'followupflag', 'id' => $followupflagged[0]['followupflagId'] ));
+                                                    $followupflagged[0]['followupflag'] = $followupflag;
+                                                    $elem['followupflagged'] = $followupflagged[0];
+
+                                                }
+                                                $labeleds = Controller::find(
+                                                    array('concept' => 'labeled'),
+                                                    false,
+                                                    array('filter' => $filter, 'criteria' => array('deepness' => '2'))
+                                                );
+                                                foreach ($labeleds as $e){
+                                                    $labels = Controller::read( array( 'concept' => 'label', 'id' =>  $e['labelId']));
+                                                    $elem['labels'][$e['labelId']] = $labels;
+                                                }
+                                            }
                                             $retorno[] = $elem;
                                         }
@@ -4460,5 +4512,5 @@
 	    $arrayRetorno['data']		=  $pageret;
 	    $arrayRetorno['currentTab'] =  $params['current_tab'];
-            return ($pageret) ? $arrayRetorno : 'none';
+        return ($pageret) ? $arrayRetorno : 'none';
 	}
 
@@ -4546,9 +4598,9 @@
 	            {
 	                $folder = str_replace($serverString, "", imap_utf7_decode($val->name));
-                        //$folder = str_replace("&-", "&", $folder);                     
-                        $trashFolder = explode($this->imap_delimiter,$folder); 
-                        $acls = ($trashFolder[count($trashFolder) - 1] == "Trash") ? $value['acls']."i" : $value['acls']; 
-                        $folder = imap_utf7_encode($folder);                     
-                        imap_setacl ($mbox_stream, $folder, "$user", $acls); 
+	                //$folder = str_replace("&-", "&", $folder);			
+	                $trashFolder = explode($this->imap_delimiter,$folder);
+	                $acls = ($trashFolder[count($trashFolder) - 1] == "Trash") ? $value['acls']."i" : $value['acls'];
+	                $folder = imap_utf7_encode($folder);	                
+	                imap_setacl ($mbox_stream, $folder, "$user", $acls);
 	            }
 	        }
@@ -4909,4 +4961,5 @@
 				$insert = $this->insert_email($source,$dest_folder,$timestamps[$index],$flags[$index]);
 
+                $return['idsMsg'] = $insert['msg_no'];
                 if($insert['error'])
                 {
@@ -5070,33 +5123,39 @@
 				foreach ($subject as $tmp)
 					$return['msgs'][$i]['subject'] .= mb_convert_encoding($tmp->text, 'UTF-8', 'UTF-8 , ISO-8859-1');
-				
-				$filter = array('AND', array('=', 'folderName', $folder), array('=','messageNumber', $v));
-				$followupflagged = Controller::find(
-					array('concept' => 'followupflagged' , 'folder' => $folder ),
-					false, 
-					array('filter' => $filter, 'criteria' => array('deepness' => '2'))
-				);
-
-				if(isset($followupflagged[0]['followupflagId']))
-				{
-					$followupflag = Controller::read( array( 'concept' => 'followupflag', 'id' => $followupflagged[0]['followupflagId'] ));     
-					$followupflagged[0]['followupflag'] = $followupflag;
-					$return['msgs'][$i]['followupflagged'] = $followupflagged[0];
-
-				}	
-				$labeleds = Controller::find(
-					array('concept' => 'labeled'),
-					false, 
-					array('filter' => $filter, 'criteria' => array('deepness' => '2'))
-				);
-				if(is_array($labeleds))
-				foreach ($labeleds as $e){
-					$labels = Controller::read( array( 'concept' => 'label', 'id' =>  $e['labelId']));     
-					$return['msgs'][$i]['labels'][$e['labelId']] = $labels;
-				}	
+
+
+                if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_followupflags_and_labels'] == "1")
+                {
+
+                    $filter = array('AND', array('=', 'folderName', $folder), array('=','messageNumber', $v));
+                    $followupflagged = Controller::find(
+                        array('concept' => 'followupflagged' , 'folder' => $folder ),
+                        false,
+                        array('filter' => $filter, 'criteria' => array('deepness' => '2'))
+                    );
+
+                    if(isset($followupflagged[0]['followupflagId']))
+                    {
+                        $followupflag = Controller::read( array( 'concept' => 'followupflag', 'id' => $followupflagged[0]['followupflagId'] ));
+                        $followupflagged[0]['followupflag'] = $followupflag;
+                        $return['msgs'][$i]['followupflagged'] = $followupflagged[0];
+
+                    }
+                    $labeleds = Controller::find(
+                        array('concept' => 'labeled'),
+                        false,
+                        array('filter' => $filter, 'criteria' => array('deepness' => '2'))
+                    );
+                    if(is_array($labeleds))
+                    foreach ($labeleds as $e){
+                        $labels = Controller::read( array( 'concept' => 'label', 'id' =>  $e['labelId']));
+                        $return['msgs'][$i]['labels'][$e['labelId']] = $labels;
+                    }
+                }
+
 				$mimeBody = imap_body( $this->mbox, $v  , FT_UID|FT_PEEK  );
 				$return['msgs'][$i]['flag'] = ' ';
 				$return['msgs'][$i]['flag'] .= $msg->Unseen ? $msg->Unseen : '';
-				$return['msgs'][$i]['flag'] .= $msg->Recent ? $msg->Recent : '';	
+				$return['msgs'][$i]['flag'] .= $msg->Recent ? $msg->Recent : '';
 				$return['msgs'][$i]['flag'] .= $msg->Draft ? $msg->Draft : '';	
 				$return['msgs'][$i]['flag'] .= $msg->Answered ? $msg->Answered : '';	
@@ -5159,9 +5218,9 @@
 			$nMsgs[] = $v;
 		}
-		$return['msgs'] = $nMsgs;	
-		
-		$return = json_encode($return);		
+		$return['msgs'] = $nMsgs;
+
+		$return = json_encode($return);
 		$return = base64_encode($return);
-	
+        
 		return $return;
 	}
@@ -5227,16 +5286,17 @@
 	function searchSieveRule( $params )
 	{
- 
-		$imap = $this->open_mbox( 'INBOX' );
+		$imap = $this->open_mbox( $params['folder']['criteria'] ? $params['folder']['criteria'] : 'INBOX' );
 		$msgs = imap_sort( $imap , SORTDATE , 0 , SE_UID);
-		
+	
 		$rr = array();
- 
+
         if(isset($params['from']))  $rr['from'] = array();
         if(isset($params['to']))  $rr['to'] = array();
         if(isset($params['subject'])) $rr['subject'] = array();
-        if(isset($params['body'])) $rr['body'] = array(); 
-        if(isset($params['size'])) $rr['size'] = array(); 
- 
+        if(isset($params['body'])) $rr['body'] = array();
+        if(isset($params['size'])) $rr['size'] = array();
+
+        //$params['search'] = mb_convert_encoding($params['search'], 'UTF-8',mb_detect_encoding($params['search'].'x', 'UTF-8, ISO-8859-1'));
+
 		foreach ($msgs as $i => $v)
 		{
@@ -5264,5 +5324,5 @@
 			
 			if(isset($params['to']))
-			{ 
+			{
 				$tos = $msg->to;
 				$val = '';
@@ -5284,5 +5344,5 @@
 					
 				}
-				
+
 				if($this->filterCheck( $val , $params['to']['criteria'] , $params['to']['filter'] ))
 					$rr['to'][] = $v;
@@ -5294,5 +5354,5 @@
 				$subject = imap_mime_header_decode($msg->subject);
 				foreach ($subject as $tmp)
-					$ss .= $tmp->text;
+					$ss .= ($tmp->charset == "default") ? $tmp->text : utf8_encode($tmp->text);
 				
 				if($this->filterCheck($ss , $params['subject']['criteria'] , $params['subject']['filter'] ))
@@ -5302,10 +5362,10 @@
 			if(isset($params['body']))
 			{			
-				$this->mbox = $this->open_mbox( 'INBOX' );
-				$b = $this->get_body_msg( $v , 'INBOX' );
-				
-				if( $this->filterCheck( $b['body'] , $params['body']['criteria'] , $params['body']['filter'] ))
+				$this->mbox = $this->open_mbox( $params['folder']['criteria'] ? $params['folder']['criteria'] : 'INBOX' );
+				$b = $this->get_body_msg( $v , $params['folder']['criteria'] ? $params['folder']['criteria'] : 'INBOX' );
+
+				if( $this->filterCheck( mb_convert_encoding(html_entity_decode($b['body']), 'UTF-8',mb_detect_encoding(html_entity_decode($b['body']).'x', 'UTF-8, ISO-8859-1')) , $params['body']['criteria'] , $params['body']['filter'] ))
 					$rr['body'][] = $v;
-				
+
 				unset($b);
 			}
@@ -5320,17 +5380,13 @@
 		$rrr = array();
 		$init = true;
-		
-		
 		foreach ($rr as $i => $v)
-		{			
+		{
 			if(count($rrr) == 0 && $init === true)
 				$rrr = $v;
 			else if($params['isExact'] == 'yes')
-                		$rrr = array_intersect($rrr , $v);
+                $rrr = array_intersect($rrr , $v);
 			else
 				$rrr =  array_unique(array_merge($rrr , $v));
-			
-		}
-		
+		}
 
 //		if($params['page'] && $params['rows'])
@@ -5403,7 +5459,10 @@
 						$ret[$msg][] = imap_mail_copy($imap,$msg,$proc['value'], CP_UID);
 					else
+					{
 						/* Está sempre copiando a mensagem para a pasta destino */
 					    //$ret[$msg][] = imap_mail_move($imap,$msg,$proc['parameter'], CP_UID);
 						$ret[$msg][] = imap_mail_move($imap,$msg,$proc['parameter'], CP_UID);						
+						imap_expunge($imap);
+					}
 					break;
 				case 'redirect':											
Index: branches/2.5/expressoMail1_2/inc/class.exporteml.inc.php
===================================================================
--- branches/2.5/expressoMail1_2/inc/class.exporteml.inc.php	(revision 7673)
+++ branches/2.5/expressoMail1_2/inc/class.exporteml.inc.php	(revision 8232)
@@ -150,55 +150,4 @@
 	}
 
-function export_all_byLocalFolder($params){
-        $error = false;
-
-        if(empty($params['messages'])){
-            $file["empty_folder"] = true;
-        } else {
-            foreach($params['messages'] as $eachMsg){
-               $header = "";
-               $body = "";
-               $tempDir = $this->tempDir;
-
-               $this->get_header_byLocalFolder($eachMsg, $header);
-               $this->get_body_byLocalFolder($eachMsg, $body);
-               $sEMLData    = $this->parseEml($header, $body);
-               $fileName   = $this->createFileEml_by_localFolder($sEMLData, $tempDir,$eachMsg['msg_number']);
-
-               if(!$fileName){
-                   $error = true;
-                   break;
-               } else 
-                   $fileNames .= "\"".$fileName."\" ";
-            }
-
-            $nameFileZip = 'False';         
-            if($fileNames && !$error) {         
-                $nameFileZip = $this->createFileZip($fileNames, $tempDir);
-                ($nameFileZip) ? ($file = $tempDir.'/'.$nameFileZip) : ($file = false);
-            } else 
-                $file = false;
-        }
-       
-       return $file;
-
-}
-
-function get_header_byLocalFolder($eachMsg, &$header){
-    $header = <<<header
-        MIME-Version: 1.0
-        Content-Type: text/html; charset=ISO-8859-1
-        Content-Transfer-Encoding: quoted-printable
-        From: "{$eachMsg['from']['name']}" <{$eachMsg['from']['email']}>
-        To: {$eachMsg['to']['email']}
-        Subject: {$eachMsg['subject']}
-        Message-Id: {$eachMsg['msg_number']}
-        Date: {$eachMsg['date']}
-header;
-}
-
-function get_body_byLocalFolder($eachMsg, &$body){
-    $body = $eachMsg['msg_sample']['body'];
-}
 
 function export_all($params){
Index: branches/2.5/expressoMail1_2/inc/class.ldap_functions.inc.php
===================================================================
--- branches/2.5/expressoMail1_2/inc/class.ldap_functions.inc.php	(revision 8172)
+++ branches/2.5/expressoMail1_2/inc/class.ldap_functions.inc.php	(revision 8232)
@@ -499,6 +499,6 @@
 			
 			foreach($info_return as &$value){
-				$value['type_contact'] = "G";
-
+				if (is_array($value))
+					$value['type_contact'] = "G";
 				//Converte a descrição dos filtros para ISO8859 corrigindo inconsitências com caractéres especiais
 				if(isset($value['vacationinfo']) && isset($value['vacationinfo'][0]) && $value['vacationinfo'][0] != '')
Index: branches/2.5/expressoMail1_2/inc/hook_settings.inc.php
===================================================================
--- branches/2.5/expressoMail1_2/inc/hook_settings.inc.php	(revision 8166)
+++ branches/2.5/expressoMail1_2/inc/hook_settings.inc.php	(revision 8232)
@@ -150,6 +150,6 @@
 								    signatures[default_signature].replace( /\\n/g, "<br>" );
     }
-    if (document.getElementById( "signature" ).value != "") 
-        document.getElementById( "signature" ).value = encode64(document.getElementById( "signature" ).value); 
+    if (document.getElementById( "signature" ).value != "")
+    	document.getElementById( "signature" ).value = encode64(document.getElementById( "signature" ).value);
     document.getElementById( "signatures" ).value = toJSON( signatures );
     document.getElementById( "signature_types" ).value = toJSON( types );
@@ -270,51 +270,56 @@
 	return output.toString();
 }
-function normalizerSignature(values){ 
-	var value = {}; 
-	for( key in values ){ 
-		value[isEncoded64(key) ? decode64(key) : key] = values[key]; 
-	} 
-	return value; 
-} 
-/*Verifica se a string input esta em Base 64*/ 
-function isEncoded64(input){ 
-        var baseStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; 
-        var encoded = true; 
-        if ( (input.length % 4) != 0) 
-                return false; 
-        for(var i=0; i<input.length; i++){ 
-                if ( baseStr.indexOf(input[i]) < 0 ){ 
-                        encoded = false; 
-                        break; 
-                } 
-        } 
-        return encoded; 
+function normalizerSignature(values){
+
+    var value = {};
+
+    for( key in values ){
+
+        value[isEncoded64(key) ? decode64(key) : key] = values[key];
+
+    }
+
+    return value;
+}
+/*Verifica se a string input esta em Base 64*/
+function isEncoded64(input){
+	var baseStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
+	var encoded = true;
+	if ( (input.length % 4) != 0)
+		return false;
+	for(var i=0; i<input.length; i++){
+		if ( baseStr.indexOf(input[i]) < 0 ){
+			encoded = false;
+			break;
+		}
+	}
+	return encoded;
 }
 function loadSignature()
 {
     var types = fromJSON( document.getElementById( "signature_types" ).value );
-    var signatures; 
-    if (document.getElementById( "signatures" ).value) 
-    { 
-        signatures = fromJSON(document.getElementById("signatures").value); 
-    } else if (document.getElementById( "signature" ).value) // Caso a assinatura esteja no formato da versão 2.2.10: 
-    { 
-        // TODO: Internazionalizar a string 
-        signatures = {}; 
-        signatures["Assinatura padrão"] = document.getElementById( "signature" ).value; 
-        if (!document.getElementById("signature_default").value) 
-        { 
-            document.getElementById("signature_default").value = "Assinatura padrão"; 
-	} 
-}    
-    
-    var old_signature = document.getElementById( "signature" ).value; 
-    var def = document.getElementById( "signature_default" ).value; 
-        def = isEncoded64(def) ? decode64(def) : def; 
+    var signatures;
+    if (document.getElementById( "signatures" ).value)
+    {
+        signatures = fromJSON(document.getElementById("signatures").value);
+    } else if (document.getElementById( "signature" ).value) // Caso a assinatura esteja no formato da versão 2.2.10:
+    {
+        // TODO: Internazionalizar a string
+        signatures = {};
+        signatures["Assinatura padrão"] = document.getElementById( "signature" ).value;
+        if (!document.getElementById("signature_default").value)
+        {
+            document.getElementById("signature_default").value = "Assinatura padrão";
+        }
+    }
+
+    signatures = normalizerSignature(signatures);
+    types = normalizerSignature(types);
+
+    var old_signature = document.getElementById( "signature" ).value;
+    var def = document.getElementById( "signature_default" ).value;
+	def = isEncoded64(def) ? decode64(def) : def;
 
     var counter = 0, ids = [], def_signature = "", noSig = true;
-
-	signatures = normalizerSignature(signatures); 
- 	types = normalizerSignature(types);
 
     for( key in signatures )
@@ -336,14 +341,14 @@
 
     if( def_signature !== "" )
-		document.getElementById( "default_signature" + def_signature ).checked = true;
+    	document.getElementById( "default_signature" + def_signature ).checked = true;
     else if( noSig && old_signature )
     {
-	    var type_signature = document.getElementById("type_signature"); 
-        if (type_signature) 
-        { 
-            addSignature( type_signature.value !== "html" ); 
-            document.getElementById( "user_signature" + counter ).value = old_signature; 
-        }
-	}
+        var type_signature = document.getElementById("type_signature");
+        if (type_signature)
+        {
+            addSignature( type_signature.value !== "html" );
+            document.getElementById( "user_signature" + counter ).value = old_signature;
+        }
+    }
 }
 ');
@@ -364,4 +369,7 @@
 
 create_check_box('View the user name in the header of the messages printed?', 'show_name_print_messages', 'Displays the user name in the header print email');
+
+create_check_box('Habilitar funcionalidade de notificar ao receber mensagens filtradas por remetente ?', 'use_alert_filter_criteria', '');
+create_check_box('Habilitar sinalizadores e marcadores em mensagens', 'use_followupflags_and_labels', '');
 
 //$default = 0;
Index: branches/2.5/expressoMail1_2/js/mail_archiver.js
===================================================================
--- branches/2.5/expressoMail1_2/js/mail_archiver.js	(revision 8126)
+++ branches/2.5/expressoMail1_2/js/mail_archiver.js	(revision 8232)
@@ -427,14 +427,15 @@
            
                 var fcaption = "";
-                
-                if(destination_folder.substr(0,5) == 'local'){
-                    expresso_mail_archive.folder_destination = destination_folder.replace("local_messages_","");
-                }
-                else{
-                    expresso_mail_archive.folder_destination = destination_folder;
-                }
+
+                if(destination_folder.substr(0,5) == 'local'){ 
+                    expresso_mail_archive.folder_destination = destination_folder.replace("local_messages_",""); 
+                } 
+                else{ 
+                    expresso_mail_archive.folder_destination = destination_folder; 
+                } 
+
                 
                 if(!expresso_mail_archive.archivefolder){
-                    expresso_mail_archive.getFolderInfo(expresso_mail_archive.folder_destination);
+                    expresso_mail_archive.getFolderInfo(expresso_mail_archive.folder_destination); 
                     if(typeof(expresso_mail_archive.folder) != "undefined"){
                         //window.alert('folder.path -> ' + expresso_mail_archive.folder.path);
@@ -575,19 +576,13 @@
 }
 
-
-
-
-/**
- *Unarchieve Message
- *
- *@author Cassiano Dal Pizzol [cassiano.dalpizzol@serpro.gov.br]
- *
- *@param folder Original Folder of the message
- *@param new_folder The new folder of the message
- *@param msgs_number id of the messages
- */
-MailArchiver.prototype.unarchieve = function (folder, new_folder, msgs_number){
-    try{ 
-        write_msg(get_lang("Starting to unarchive messages"));
+MailArchiver.prototype.unarchieveToAttach = function (folder, new_folder, msgs_number, callback){
+    try{
+
+        if(typeof callback !== 'function') callback = function(){};
+
+        if(typeof(expresso_mail_archive.idMsgsToAttach) == "undefined"){
+            expresso_mail_archive.idMsgsToAttach = new Array();
+        }
+        //write_msg(get_lang("Starting to unarchive messages"));
         expresso_mail_archive.isArchiveOperation = true;
         if(currentTab.toString().indexOf("_r") != -1){
@@ -599,14 +594,15 @@
                 
         if (parseInt(msgs_number) > 0 || msgs_number.length > 0){       
-            expresso_mail_archive.message_list = new Array();
-            expresso_mail_archive.CreateMessageList(msgs_number);
-            if((expresso_mail_archive.message_list.length > 0) && (expresso_mail_archive.message_list[0] != '')) {
+           
+            expresso_mail_archive.messageToAttach = msgs_number;
+            if(expresso_mail_archive.messageToAttach) {
+                
                 expresso_mail_archive.unarchivecounter = 0;
                 expresso_mail_archive.unarchive_error_counter=0;
-                expresso_mail_archive.getFolderInfo(folder.replace("local_messages_",""));
+                expresso_mail_archive.getFolderInfo(folder.replace("local_messages_","")); 
                 expresso_mail_archive.unarchievefolder = expresso_mail_archive.folder.name;
                 (new_folder != null)?expresso_mail_archive.unarchievenewfolder = new_folder:expresso_mail_archive.unarchievenewfolder='INBOX';
                 
-                expresso_mail_archive.unarchieveHandler();
+                expresso_mail_archive.unarchieveToAttachHandler(callback);
                 
                 if(currentTab.toString().indexOf("_r") != -1){
@@ -628,14 +624,7 @@
 }
 
-/**
- *
- *Unarchieve Message Handler
- *
- *@author Cassiano Dal Pizzol [cassiano.dalpizzol@serpro.gov.br]
- *
- **/
-MailArchiver.prototype.unarchieveHandler = function(){
-    try{
-        var email = mail_archive_protocol+'://'+mail_archive_host+':'+mail_archive_port+'/mail/' + expresso_mail_archive.session.id +'/'+ expresso_mail_archive.folder.path + '/'+ expresso_mail_archive.message_list[expresso_mail_archive.unarchivecounter] + '.eml';    
+MailArchiver.prototype.unarchieveToAttachHandler = function(uCallback){
+    try{
+         var email = mail_archive_protocol+'://'+mail_archive_host+':'+mail_archive_port+'/mail/' + expresso_mail_archive.session.id +'/'+ expresso_mail_archive.folder.path + '/'+ expresso_mail_archive.messageToAttach + '.eml';    
     
         //Creates a new object to unarchive messages. It's a CXF Add-on CORS component
@@ -647,5 +636,5 @@
             for (var w=0; w < expresso_mail_archive.allcompletemessagesbyfolder.length; w++){
                                 
-                if(expresso_mail_archive.allcompletemessagesbyfolder[w]["msg_number"] == expresso_mail_archive.message_list[expresso_mail_archive.unarchivecounter]){
+                if(expresso_mail_archive.allcompletemessagesbyfolder[w]["msg_number"] == expresso_mail_archive.messageToAttach){
                     var timestamp = expresso_mail_archive.allcompletemessagesbyfolder[w]["timestamp"];
                     
@@ -702,4 +691,204 @@
                 }
             }
+            var id = expresso_mail_archive.messageToAttach;
+            var source =  encodeURIComponent(UnarchiveReqHandler.handler.responseText) + "#@#@#@";
+            var params = 
+            "&folder="      + escape(expresso_mail_archive.unarchievenewfolder) +
+            "&source="      + source + 
+            "&timestamp="   + timestamp + 
+            "&madata=true"  + 
+            "&flags="       + flags +
+            "&id="          + id;
+
+
+            var handler_unarchive = function(data){
+                expresso_mail_archive.unarchieveToAttachController(data);
+            }
+            write_msg(get_lang("Please, Wait the messages from archieve be ready."));
+            
+             $.ajax({
+                url: "controller.php?action=$this.imap_functions.unarchive_mail",
+                success: function(data){
+                    data = connector.unserialize(data);
+                    expresso_mail_archive.idMsgsToAttach.push(data.idsMsg);
+                    handler_unarchive(data);
+                    uCallback(data);
+                },
+                async: false,
+                data:  params,
+                type: 'POST',
+                
+            });
+
+        }
+
+        
+        UnarchiveReqHandler.handler.open("GET", email, true);
+        if(UnarchiveReqHandler.handler.overrideMimeType){
+            UnarchiveReqHandler.handler.overrideMimeType("message/rfc822; charset=windows-1252"); 
+        }
+        UnarchiveReqHandler.handler.send();
+    }
+    catch(e){
+        write_msg(get_lang('Unarchive error: ' + e));
+    }
+}
+
+MailArchiver.prototype.unarchieveToAttachController = function(data){
+    
+    if (data){
+        if (data.error != "") {
+            expresso_mail_archive.unarchive_error_counter++;
+        }
+        
+    }
+}
+
+
+/**
+ *Unarchieve Message
+ *
+ *@author Cassiano Dal Pizzol [cassiano.dalpizzol@serpro.gov.br]
+ *
+ *@param folder Original Folder of the message
+ *@param new_folder The new folder of the message
+ *@param msgs_number id of the messages
+ */
+MailArchiver.prototype.unarchieve = function (folder, new_folder, msgs_number){
+    try{ 
+
+        var aclShare = false;
+        $.ajax({
+              url: 'controller.php?' + $.param( { action: '$this.imap_functions.verifyShareFolder', folder: new_folder } ),
+              success: function( data ){
+                 data = connector.unserialize( data );
+                 if(data != null){
+                     if(!data.status){
+                        aclShare = true;
+                     }
+                 }
+
+              },
+              async: false
+        });
+
+        if(aclShare){
+            write_msg(get_lang("You don't have permission for this operation in this shared folder!"));
+            return false;
+        } 
+
+        write_msg(get_lang("Starting to unarchive messages"));
+        expresso_mail_archive.isArchiveOperation = true;
+        if(currentTab.toString().indexOf("_r") != -1){
+            msgs_number = currentTab.toString().substr(0,currentTab.toString().indexOf("_r"));
+        }
+
+        if(!msgs_number)
+            msgs_number = get_selected_messages();        
+                
+        if (parseInt(msgs_number) > 0 || msgs_number.length > 0){       
+            expresso_mail_archive.message_list = new Array();
+            expresso_mail_archive.CreateMessageList(msgs_number);
+            if((expresso_mail_archive.message_list.length > 0) && (expresso_mail_archive.message_list[0] != '')) {
+                expresso_mail_archive.unarchivecounter = 0;
+                expresso_mail_archive.unarchive_error_counter=0;
+                expresso_mail_archive.getFolderInfo(folder.replace("local_messages_","")); 
+                expresso_mail_archive.unarchievefolder = expresso_mail_archive.folder.name;
+                (new_folder != null)?expresso_mail_archive.unarchievenewfolder = new_folder:expresso_mail_archive.unarchievenewfolder='INBOX';
+                
+                expresso_mail_archive.unarchieveHandler();
+                
+                if(currentTab.toString().indexOf("_r") != -1){
+                    delete_border(currentTab,'false');  
+                }
+            }
+            else{
+                write_msg(get_lang('No selected message.'));
+            }
+        }                               
+        else
+            write_msg(get_lang('No selected message.'));
+        
+        clear_selected_messages();
+    }
+    catch (e){
+        write_msg(get_lang('Unarchive error: ' + e));
+    }
+}
+
+/**
+ *
+ *Unarchieve Message Handler
+ *
+ *@author Cassiano Dal Pizzol [cassiano.dalpizzol@serpro.gov.br]
+ *
+ **/
+MailArchiver.prototype.unarchieveHandler = function(){
+    try{
+        var email = mail_archive_protocol+'://'+mail_archive_host+':'+mail_archive_port+'/mail/' + expresso_mail_archive.session.id +'/'+ expresso_mail_archive.folder.path + '/'+ expresso_mail_archive.message_list[expresso_mail_archive.unarchivecounter] + '.eml';    
+    
+        //Creates a new object to unarchive messages. It's a CXF Add-on CORS component
+        var UnarchiveReqHandler = new cxf_cors_request_object();
+        UnarchiveReqHandler.init();
+
+        //Both XDomainRequest and XMLHttpRequest L2 supports onload event
+        UnarchiveReqHandler.handler.onload = function(){            
+            for (var w=0; w < expresso_mail_archive.allcompletemessagesbyfolder.length; w++){
+                                
+                if(expresso_mail_archive.allcompletemessagesbyfolder[w]["msg_number"] == expresso_mail_archive.message_list[expresso_mail_archive.unarchivecounter]){
+                    var timestamp = expresso_mail_archive.allcompletemessagesbyfolder[w]["timestamp"];
+                    
+                    //Get local tagged message data
+                    var flags = new String("");
+                    
+                    //Forwarded is special one: marks as "answered" and "draft"
+                    if(expresso_mail_archive.allcompletemessagesbyfolder[w]["Forwarded"]){
+                        if(expresso_mail_archive.allcompletemessagesbyfolder[w]["Forwarded"] == 'F')
+                            flags += 'A:X'+':';                                  
+                    }
+                    else{
+                        //Answered tag
+                        if(expresso_mail_archive.allcompletemessagesbyfolder[w]["Answered"])
+                            if(expresso_mail_archive.allcompletemessagesbyfolder[w]["Answered"] == 'A')
+                                flags += 'A'+':';
+                            else
+                                flags += ':';
+                        else
+                            flags += ':';                    
+
+                        //Draft tag
+                        if(expresso_mail_archive.allcompletemessagesbyfolder[w]["Draft"])
+                            if(expresso_mail_archive.allcompletemessagesbyfolder[w]["Draft"] == 'X')
+                                flags += 'D'+':';                    
+                            else
+                                flags += ':';
+                        else
+                            flags += ':';
+                    }
+                    
+                    //Flagged tag
+                    if(expresso_mail_archive.allcompletemessagesbyfolder[w]["Flagged"])
+                        if(expresso_mail_archive.allcompletemessagesbyfolder[w]["Flagged"] == 'F')
+                            flags += 'F'+':';                                        
+                        else
+                            flags += ':';
+                    else
+                        flags += ':';
+                    
+                    //Unseen tag
+                    if(expresso_mail_archive.allcompletemessagesbyfolder[w]["Unseen"])
+                        if(expresso_mail_archive.allcompletemessagesbyfolder[w]["Unseen"] == 'U')
+                            flags += 'U';     
+                        else
+                            flags += '';
+                    else
+                        flags += '';
+                    
+                    //Imap tag hash id
+                    flags += "#@#@#@";                    
+                    
+                    break;
+                }
+            }
             var id = expresso_mail_archive.message_list[expresso_mail_archive.unarchivecounter];
             var source =  encodeURIComponent(UnarchiveReqHandler.handler.responseText) + "#@#@#@";
@@ -717,5 +906,18 @@
             write_msg(get_lang('Unarchiving message %1 of %2', (expresso_mail_archive.unarchivecounter + 1), expresso_mail_archive.message_list.length));
             
-            cExecute ("$this.imap_functions.unarchive_mail&", handler_unarchive, params);
+            //cExecute ("$this.imap_functions.unarchive_mail&", handler_unarchive, params);
+
+            $.ajax({
+                url: "controller.php?action=$this.imap_functions.unarchive_mail",
+                data:  params,
+                type: 'POST',
+                async: false,
+                success: function(data){
+                    handler_unarchive(connector.unserialize(data));
+                },
+            });
+
+
+
         }
         
@@ -846,7 +1048,7 @@
     expresso_mail_archive.message_list = new Array();
 
-    expresso_mail_archive.currentfolder = folder.replace("local_messages_","");
-
-    expresso_mail_archive.listMessages(expresso_mail_archive.currentfolder);
+    expresso_mail_archive.currentfolder = folder.replace("local_messages_",""); 
+
+    expresso_mail_archive.listMessages(expresso_mail_archive.currentfolder); 
 
     // This is necessary 'couse we can get a delete operation while an unarchive operation
@@ -956,7 +1158,7 @@
         expresso_mail_archive.message_list = new Array();  
 
-        expresso_mail_archive.getFolderInfo(expresso_mail_archive.currentfolder);
-        expresso_mail_archive.getFolderInfo(expresso_mail_archive.folder_destination);
-        expresso_mail_archive.listMessages(expresso_mail_archive.currentfolder); 
+        expresso_mail_archive.getFolderInfo(expresso_mail_archive.currentfolder); 
+        expresso_mail_archive.getFolderInfo(expresso_mail_archive.folder_destination); 
+        expresso_mail_archive.listMessages(expresso_mail_archive.currentfolder);  
               
         expresso_mail_archive.resetObject();
@@ -1258,7 +1460,7 @@
         if(folderId == 'local_root')
             folderId = "";
-        var exp_verifyId = RegExp("^messages\_[0-9|a-z]+\-[0-9|a-z|\-]+$"); 
-        if(exp_verifyId.test(folderId)) 
-            folderId = folderId.replace("messages_", ""); 
+        var exp_verifyId = RegExp("^messages\_[0-9|a-z]+\-[0-9|a-z|\-]+$");
+        if(exp_verifyId.test(folderId))
+            folderId = folderId.replace("messages_", "");
         ArchiveServices.getFolderInfo(expresso_mail_archive.getFolderInfoOperationOK, expresso_mail_archive.getFolderInfoOperationFailure, expresso_mail_archive.session.id, folderId);
     }
@@ -1296,7 +1498,7 @@
 
 MailArchiver.prototype.deleteAllMessages = function(folderId){
-    try{
+    try{    
         var objfolder = new Object();
-        objfolder.folder = folderId;
+        objfolder.folder = folderId; 
 
         var query_data = expresso_mail_archive.queryconfig.query(objfolder);
@@ -1337,12 +1539,13 @@
         }
         var objfolder = new Object();
-        var exp_verifyId = RegExp("^messages\_[0-9|a-z]+\-[0-9|a-z|\-]+$"); 
-        if(exp_verifyId.test(folderid)) 
-            folderid = folderid.replace("messages_", ""); 
-        objfolder.folder = folderid; 
+        var exp_verifyId = RegExp("^messages\_[0-9|a-z]+\-[0-9|a-z|\-]+$");
+        if(exp_verifyId.test(folderid))
+            folderid = folderid.replace("messages_", "");
+        objfolder.folder = folderid;
         //var testing_data_xml = '<?xml version="1.0" encoding="UTF-8"?><query lowerIndex="0" upperIndex="50"><folder id="'+folderid+'"/><order asc="date"/><order desc="subject"/></query>';
         //var testing_data_json_mapped = '{"query":{"@lowerIndex":"0", "@upperIndex":"50", "folder":[{"@id":"'+folderid+'"}], "order":[{"@asc":"date", "@desc":"subject"}]}}';
         var query_data = expresso_mail_archive.queryconfig.query(objfolder);
-        expresso_mail_archive.getFolderInfo(folderid);
+
+        expresso_mail_archive.getFolderInfo(folderid); 
         expresso_mail_archive.currentfolder = folderid;
         
@@ -1404,4 +1607,47 @@
 }
 
+
+MailArchiver.prototype.getMessagesByFolder = function(folderid, searchType){
+    try{
+        if(searchType == "ALL")
+            var query_messages = '{"query":{"folder":[{"@id":"'+folderid+'"}], "order":[{"@asc":"date"}]}}';
+        else
+            var query_messages = '{"query":{"folder":[{"@id":"'+folderid+'"}], "tags":[{"@contains":"'+searchType+'"}], "order":[{"@asc":"date"}]}}';
+        ArchiveServices.listMessages(expresso_mail_archive.getMessagesByFolderOperationOK, expresso_mail_archive.getMessagesByFolderOperationFailure, expresso_mail_archive.session.id, query_messages);
+    }
+    catch (e){
+        expresso_mail_archive.getFaultInfo();
+    }
+}
+
+MailArchiver.prototype.getMessagesByFolderOperationOK = function(returnService){
+    var msglist = new Array();
+    var msglistcomplete = new Array();
+    var msgAll = new Array();
+    for(var i=0; i< returnService.getReturn().length; i++){
+        //Array montado apenas com ids para tratamento de seleÃ§Ã£o de mensagens independente de paginaÃ§Ã£o
+        msglist.push(returnService.getReturn()[i]._id);
+
+        msgAll.push(returnService.getReturn()[i]);
+
+        //Incremento de contadores para atualizaÃ§Ã£o da aba de listagem
+        if(returnService.getReturn()[i]._tags.indexOf("unseen") != -1){
+            expresso_mail_archive.tot_unseen_msgs_tab++;
+        }
+        expresso_mail_archive.tot_msgs_tab++;
+        //Array montado para operaÃ§Ã£o de desarquivamento
+        var ExpSerialized = expresso_mail_archive.pattern.toExpressoHeader(returnService.getReturn()[i]);
+        msglistcomplete.push(connector.unserialize(ExpSerialized));
+    }
+    expresso_mail_archive.allmessagesbyfolder = msglist;
+    expresso_mail_archive.allcompletemessagesbyfolder = msglistcomplete;
+    expresso_mail_archive.msgAll = msgAll;
+}
+
+MailArchiver.prototype.getMessagesByFolderOperationFailure = function(ServiceFault){
+    window.alert('listAllmessagesByFolder FALHOU!\n' + ServiceFault.getReturn());
+}
+
+
 //List all messages by folder given and set a array with all messages ids
 MailArchiver.prototype.listAllMessagesByFolder = function(folderid, searchType){
@@ -1521,4 +1767,5 @@
     if(msgfound){
         expresso_mail_archive.currentheaders = headerMsg;
+        expresso_mail_archive.subjectPreview = headerMsg.subject;
         return(headerMsg);
     }
@@ -1543,4 +1790,5 @@
             bodies.push(temp);
         }
+        expresso_mail_archive.bodyPreview = temp.getReturn();
         return bodies;
     }
@@ -1548,4 +1796,10 @@
         expresso_mail_archive.getFaultInfo();
     }
+}
+
+
+MailArchiver.prototype.getPreviewToAttach = function(id){
+    expresso_mail_archive.getMessageInfo(id);
+    expresso_mail_archive.getMessageBodies([id]);
 }
 
@@ -1624,4 +1878,5 @@
         return;
     }    
+    expresso_mail_archive.te = returnService.getReturn();
     var msgBody = returnService.getReturn();
     //var msgHeaders = expresso_mail_archive.getMessageHeaders(expresso_mail_archive.currentmessage);
@@ -1918,4 +2173,6 @@
             var filters = eval('(' + expresso_mail_archive.queryconfig.pharseSearchFields(fields) + ')');
 
+
+
             if(folderlist.indexOf("#") != -1)
                 filters.folder = folderlist.substr(0, folderlist.indexOf("#"));
@@ -1928,5 +2185,7 @@
 
             expresso_mail_archive.querydata = expresso_mail_archive.search_queryconfig.query(filters);
-            
+
+
+
             //var query_data = '<?xml version="1.0" encoding="UTF-8"?><query subject="teste"><folder id="inbox"/><order asc="date"/></query>';
             ArchiveServices.listMessages(expresso_mail_archive.searchOperationOK, expresso_mail_archive.searchOperationFailure, expresso_mail_archive.session.id, expresso_mail_archive.querydata);        
@@ -1962,5 +2221,5 @@
             
         //expresso_mail_archive.queryresult = msglist;        
-        expresso_mail_archive.search_queryresult = msglist;    
+        expresso_mail_archive.search_queryresult = msglist; 
         //expresso_mail_archive.messageslisted = msglist2;
         expresso_mail_archive.search_message_list = msglist2;
@@ -2096,6 +2355,10 @@
         var ExpSerialized2 = expresso_mail_archive.pattern.toExpressoHeader(serviceReturn.getReturn());
         var msgitem2 = connector.unserialize(ExpSerialized2);
+        if(!expresso_mail_archive.messageslisted){
+            expresso_mail_archive.messageslisted = [];
+        }
         expresso_mail_archive.messageslisted.push(msgitem2);    
         expresso_mail_archive.getMessageHeaders(serviceReturn.getReturn().getId());
+
     }
     else{
Index: branches/2.5/expressoMail1_2/js/abas.js
===================================================================
--- branches/2.5/expressoMail1_2/js/abas.js	(revision 8125)
+++ branches/2.5/expressoMail1_2/js/abas.js	(revision 8232)
@@ -10,6 +10,6 @@
 function setBorderAttributes(ID)
 {
-	this.border_id = "border_id_"+ID;
-	this.sequence = ID; 
+    this.border_id = "border_id_"+ID;
+    this.sequence = ID; 
 }
 
@@ -17,26 +17,28 @@
 function alternate_border(ID)
 {
-	msg_selected = false;//Controle da seleÃ§Ã£o de mensagens
-	if(isNaN(ID))
-		if(preferences.use_shortcuts == "1")
-			select_msg((ID.split("_"))[0]);
-	if( document.getElementById("div_menu_c3") != null )
-	{
-		//div que contém divs de paginação de todas abas de listagem possíveis (listagem de pasta e listagem de pesquisa)
-		var node = document.getElementById("div_menu_c3").firstChild;
-		//Se for diferente da aba de listagem, remove a paginação
-		if(currentTab != 0){
-			//Enquanto node for true (retorna false se não houver mais elementos)
-			while ( node ) {
-				node.style.display = "none";
-				node = node.nextSibling;
-			}
-		}
-		
-		if( document.getElementById("span_paging"+ID) != null )
-			document.getElementById("span_paging"+ID).style.display = "block";
-	}
-	
-	if ( typeof win == 'object' && win.close && win.close.constructor == Function ){
+   
+
+    msg_selected = false;//Controle da seleÃ§Ã£o de mensagens
+    if(isNaN(ID))
+        if(preferences.use_shortcuts == "1")
+            select_msg((ID.split("_"))[0]);
+    if( document.getElementById("div_menu_c3") != null )
+    {
+        //div que contém divs de paginação de todas abas de listagem possíveis (listagem de pasta e listagem de pesquisa)
+        var node = document.getElementById("div_menu_c3").firstChild;
+        //Se for diferente da aba de listagem, remove a paginação
+        if(currentTab != 0){
+            //Enquanto node for true (retorna false se não houver mais elementos)
+            while ( node ) {
+                node.style.display = "none";
+                node = node.nextSibling;
+            }
+        }
+        
+        if( document.getElementById("span_paging"+ID) != null )
+            document.getElementById("span_paging"+ID).style.display = "block";
+    }
+    
+    if ( typeof win == 'object' && win.close && win.close.constructor == Function ){
             var search_win = document.getElementById( 'window_QuickCatalogSearch' );
             if(search_win){
@@ -45,88 +47,88 @@
             win.close( );
         }
-		
-	if (! Element('border_id_'+ID))
-		return false; // Not possible to alternate
-	show_hide_span_paging(ID);
-	spanD = Element("span_D");
-	if (spanD)
-		spanD.style.display = (openTab.type[ID] == 0 ? '' : 'none');
-
-	var footer_menu = Element("footer_menu");	
-	var aba = Element('border_id_'+ID);
-	if (footer_menu != null) {
-		footer_menu.style.display = (openTab.type[ID] != 4 ? '' : 'none');
-		var alternate_menu = document.getElementById('localOption');
-		
-		if(alternate_menu != null && alternate_menu != 'undefined'){ //Quando Carregado o expresso mail
-			if(openTab.imapBox[ID]!= null && openTab.imapBox[ID]!= 'undefined' ){ //Quando abrir uma Nova Mensagem
-				if((openTab.imapBox[ID].indexOf("local_") >= 0)){						
-						alternate_menu.title = get_lang("Unarchive");
-						alternate_menu.removeAttribute("onclick");
-						if(!is_ie)
-							alternate_menu.setAttribute("onclick",  'expresso_local_messages.unarchive_msgs(\''+openTab.imapBox[ID]+'\', null)');
-						else{
-							alternate_menu.onclick = function(){
-								expresso_local_messages.unarchive_msgs(openTab.imapBox[ID], null);
-							}
-						}
-						alternate_menu.innerHTML = get_lang("Unarchive");
-						
-					}else{
-						alternate_menu.title = get_lang("Archive");
-						alternate_menu.removeAttribute("onclick");
-						if(!is_ie)
-							alternate_menu.setAttribute("onclick", 'archive_msgs(\''+openTab.imapBox[ID]+'\', null)');		
-						else{
-							alternate_menu.onclick = function(){
-								archive_msgs(openTab.imapBox[ID], null);
-							}	
-						}
-						alternate_menu.innerHTML = get_lang("Archive");
-					}
-					
-			}
-		}
-		
-		if((aba.id.indexOf("_r") < 0) && (aba.id.indexOf("_0") < 0) && (aba.id.indexOf("id_search_") < 0) && (aba.id.indexOf("_s") < 0)){
-			spanD.style.display = 'none';
-			footer_menu.style.display = 'none';			
-		}
-	}
-
-
-	var len = BordersArray.length;
-	for (var i=0; i < len; i++)
-	{
-		m = document.getElementById(BordersArray[i].border_id);
-		if ((m)&&(m.className == 'menu-sel'))
-		{
-			m.className = 'menu';
-			c = document.getElementById("content_id_"+BordersArray[i].sequence);
-			c.style.display = 'none';
-			if(Element("font_border_id_"+BordersArray[i].sequence))
-				Element("font_border_id_"+BordersArray[i].sequence).className = 'font-menu';	
-
-		}
-	}
-
-	m = Element("border_id_"+ID);
-	if (m)
-		m.className = 'menu-sel';
-	if(Element("font_border_id_" + ID))
-		Element("font_border_id_" + ID).className = 'font-menu-sel';
-	var c = Element("content_id_"+ID)
-	if (c)
-		c.style.display = '';
-
-
-	// hide the DropDrowContact, if necessary
-	window_DropDownContacts = Element('tipDiv');
-	if ((window_DropDownContacts)&&(window_DropDownContacts.style.visibility != 'hidden')){
-		window_DropDownContacts.style.visibility = 'hidden';
-	}
-
-	numBox = getNumBoxFromTabId(ID);
-	if (typeof(ID)=='number') {
+        
+    if (! Element('border_id_'+ID))
+        return false; // Not possible to alternate
+    show_hide_span_paging(ID);
+    spanD = Element("span_D");
+    if (spanD)
+        spanD.style.display = (openTab.type[ID] == 0 ? '' : 'none');
+
+    var footer_menu = Element("footer_menu");   
+    var aba = Element('border_id_'+ID);
+    if (footer_menu != null) {
+        footer_menu.style.display = (openTab.type[ID] != 4 ? '' : 'none');
+        var alternate_menu = document.getElementById('localOption');
+        
+        if(alternate_menu != null && alternate_menu != 'undefined'){ //Quando Carregado o expresso mail
+            if(openTab.imapBox[ID]!= null && openTab.imapBox[ID]!= 'undefined' ){ //Quando abrir uma Nova Mensagem
+                if((openTab.imapBox[ID].indexOf("local_") >= 0)){                       
+                        alternate_menu.title = get_lang("Unarchive");
+                        alternate_menu.removeAttribute("onclick");
+                        if(!is_ie)
+                            alternate_menu.setAttribute("onclick",  'expresso_local_messages.unarchive_msgs(\''+openTab.imapBox[ID]+'\', null)');
+                        else{
+                            alternate_menu.onclick = function(){
+                                expresso_local_messages.unarchive_msgs(openTab.imapBox[ID], null);
+                            }
+                        }
+                        alternate_menu.innerHTML = get_lang("Unarchive");
+                        
+                    }else{
+                        alternate_menu.title = get_lang("Archive");
+                        alternate_menu.removeAttribute("onclick");
+                        if(!is_ie)
+                            alternate_menu.setAttribute("onclick", 'archive_msgs(\''+openTab.imapBox[ID]+'\', null)');      
+                        else{
+                            alternate_menu.onclick = function(){
+                                archive_msgs(openTab.imapBox[ID], null);
+                            }   
+                        }
+                        alternate_menu.innerHTML = get_lang("Archive");
+                    }
+                    
+            }
+        }
+        
+        if((aba.id.indexOf("_r") < 0) && (aba.id.indexOf("_0") < 0) && (aba.id.indexOf("id_search_") < 0) && (aba.id.indexOf("_s") < 0)){
+            spanD.style.display = 'none';
+            footer_menu.style.display = 'none';         
+        }
+    }
+
+
+    var len = BordersArray.length;
+    for (var i=0; i < len; i++)
+    {
+        m = document.getElementById(BordersArray[i].border_id);
+        if ((m)&&(m.className == 'menu-sel'))
+        {
+            m.className = 'menu';
+            c = document.getElementById("content_id_"+BordersArray[i].sequence);
+            c.style.display = 'none';
+            if(Element("font_border_id_"+BordersArray[i].sequence))
+                Element("font_border_id_"+BordersArray[i].sequence).className = 'font-menu';    
+
+        }
+    }
+
+    m = Element("border_id_"+ID);
+    if (m)
+        m.className = 'menu-sel';
+    if(Element("font_border_id_" + ID))
+        Element("font_border_id_" + ID).className = 'font-menu-sel';
+    var c = Element("content_id_"+ID)
+    if (c)
+        c.style.display = '';
+
+
+    // hide the DropDrowContact, if necessary
+    window_DropDownContacts = Element('tipDiv');
+    if ((window_DropDownContacts)&&(window_DropDownContacts.style.visibility != 'hidden')){
+        window_DropDownContacts.style.visibility = 'hidden';
+    }
+
+    numBox = getNumBoxFromTabId(ID);
+    if (typeof(ID)=='number') {
                  numBox = ID;
          }
@@ -145,26 +147,27 @@
              }
          }
-	currentTab=ID;
-	if( document.getElementById('to_'+ID) && document.getElementById('to_'+ID).type == "textarea"){ 
- 	    document.getElementById('to_'+ID).focus(); 
-	}
-	if (ID == 0){ 
-		updateSelectedMsgs();
-	}
-	RichTextEditor.setEditable(ID);
-	resizeWindow();
-	return ID;
+    currentTab=ID;
+    if( document.getElementById('to_'+ID) && document.getElementById('to_'+ID).type == "textarea"){ 
+        document.getElementById('to_'+ID).focus(); 
+    }
+    if (ID == 0){ 
+        updateSelectedMsgs();
+    }
+    RichTextEditor.setEditable(ID);
+    resizeWindow();
+
+    return ID;
 }
 
 function create_border(borderTitle, id_value, search)
 {
-	borderTitle = ( ( borderTitle && borderTitle.constructor == String && borderTitle.length > 0 ) ? borderTitle : ' ' );
+    borderTitle = ( ( borderTitle && borderTitle.constructor == String && borderTitle.length > 0 ) ? borderTitle : ' ' );
     borderTitle = html_entities(borderTitle);    
-	var resize = false;
+    var resize = false;
         resize = resize_borders();
         if (!resize){
             var str_continue = '';
             var bolContinue = true;
-			str_continue = '\n' + get_lang('You must manually close one of your tabs before opening a new one');
+            str_continue = '\n' + get_lang('You must manually close one of your tabs before opening a new one');
             if (preferences.auto_close_first_tab == 1){
                 var children = Element('border_tr').childNodes;
@@ -180,92 +183,92 @@
                         }
                         if (bolDelete || bolContinue){
-							str_fechar = '\n' + get_lang('Reached maximum tab limit. Want to close this tab');
-							var confirmacao = confirm(str_fechar);
+                            str_fechar = '\n' + get_lang('Reached maximum tab limit. Want to close this tab');
+                            var confirmacao = confirm(str_fechar);
                             if(confirmacao){
                             bolContinue = false;
                             delete_border(num_child, 'false');
                             break;
-							}else{
-								return 'maximo';
+                            }else{
+                                return 'maximo';
                         }
                     }
                 }
             }
-            }else{			
+            }else{          
                 alert(get_lang('Reached maximum tab limit') + str_continue );
                 return 'maximo';
             }
         }
-	
-	if (! id_value){ // Is new message?
-		var ID = parseInt(BordersArray[(BordersArray.length-1)].sequence) + 1;
-			if(isNaN(ID)){
-				var aux = BordersArray[(BordersArray.length-1)].sequence.split("_");
-				ID = parseInt(aux[1]) + 1;
-			}
+    
+    if (! id_value){ // Is new message?
+        var ID = parseInt(BordersArray[(BordersArray.length-1)].sequence) + 1;
+            if(isNaN(ID)){
+                var aux = BordersArray[(BordersArray.length-1)].sequence.split("_");
+                ID = parseInt(aux[1]) + 1;
+            }
         }else
-	{
-		if (Element("border_id_"+id_value)) // It's opened already!
-			return alternate_border(id_value);
-		
-		var ID = id_value;
-		if(isNaN(ID) && ID.indexOf("search_local") >= 0){
-			if(current_folder.indexOf("local") >= 0)
-				openTab.imapBox[ID] = current_folder;
-			else
-				openTab.imapBox[ID] = 'local_search';
-		}else if(isNaN(ID) && ID.indexOf("search_") >= 0){
-			if(current_folder.indexOf("local") < 0)
-				openTab.imapBox[ID] = current_folder;
-			else
-				openTab.imapBox[ID] = 'search';
-		}else if( (currentTab != 0) && isNaN(currentTab) && (currentTab.indexOf("search") >= 0) && (ID.indexOf("msg") < 0) ) {
-			var id_border = currentTab.replace(/[a-zA-Z_]+/, "");
-			ID_TR = ID.toString().substr(0,ID.toString().indexOf("_r"));
-			var tr = Element(ID_TR) ? Element(ID_TR) : Element(ID_TR+"_s"+id_border);
-			openTab.imapBox[ID] = (tr.getAttribute('name') == null?get_current_folder():tr.getAttribute('name'));
-		}else
-			openTab.imapBox[ID] = current_folder;
-	}
-	td = document.createElement("TD");
-	td.id="border_id_" + ID;
-	if(resize) 
-	{
-		td.setAttribute("width", parseInt(resize)+"px");
-		td.style.width = parseInt(resize)+"px";
-	}
-	else
-		td.setAttribute("width", "200px");
-
-	td.setAttribute("align", "right");
-	td.onclick = function(){alternate_border(ID);resizeWindow()};
-	td.setAttribute("noWrap","true");
-    	td.setAttribute("role",get_current_folder());
-    	td.title = borderTitle;
-	borderTitle = borderTitle ?  borderTitle : id_value ? get_lang("No Subject") : " "	;
-	td.value = borderTitle;
-	if (borderTitle.length > 21)
-		borderTitle = borderTitle.substring(0,21) + "...";
-
-	if ( resize )
-		borderTitle = borderTitle.substring(0, resize*0.08);
-	
-	var cc = search;
-	if(!cc){
-		if(isNaN(ID)){
-			var is_local = ID.match('.*_local_.*');
-			if(!is_local)
-				cc = document.getElementById("em_message_search").value;
-			else{
-				if (currentTab == 0)
-					cc = "";
-				else
-					cc = document.getElementsByName(currentTab)[0].value;
-			}
-		}else{
-			cc ="";
-		}
-	}
-	td.innerHTML = "<div><div id='font_border_id_" + ID+"' class='font-menu'>" +
+    {
+        if (Element("border_id_"+id_value)) // It's opened already!
+            return alternate_border(id_value);
+        
+        var ID = id_value;
+        if(isNaN(ID) && ID.indexOf("search_local") >= 0){
+            if(current_folder.indexOf("local") >= 0)
+                openTab.imapBox[ID] = current_folder;
+            else
+                openTab.imapBox[ID] = 'local_search';
+        }else if(isNaN(ID) && ID.indexOf("search_") >= 0){
+            if(current_folder.indexOf("local") < 0)
+                openTab.imapBox[ID] = current_folder;
+            else
+                openTab.imapBox[ID] = 'search';
+        }else if( (currentTab != 0) && isNaN(currentTab) && (currentTab.indexOf("search") >= 0) && (ID.indexOf("msg") < 0) ) {
+            var id_border = currentTab.replace(/[a-zA-Z_]+/, "");
+            ID_TR = ID.toString().substr(0,ID.toString().indexOf("_r"));
+            var tr = Element(ID_TR) ? Element(ID_TR) : Element(ID_TR+"_s"+id_border);
+            openTab.imapBox[ID] = (tr.getAttribute('name') == null?get_current_folder():tr.getAttribute('name'));
+        }else
+            openTab.imapBox[ID] = current_folder;
+    }
+    td = document.createElement("TD");
+    td.id="border_id_" + ID;
+    if(resize) 
+    {
+        td.setAttribute("width", parseInt(resize)+"px");
+        td.style.width = parseInt(resize)+"px";
+    }
+    else
+        td.setAttribute("width", "200px");
+
+    td.setAttribute("align", "right");
+    td.onclick = function(){alternate_border(ID);resizeWindow()};
+    td.setAttribute("noWrap","true");
+    td.setAttribute("role",get_current_folder());
+    td.title = borderTitle;
+    borderTitle = borderTitle ?  borderTitle : id_value ? get_lang("No Subject") : " "  ;
+    td.value = borderTitle;
+    if (borderTitle.length > 21)
+        borderTitle = borderTitle.substring(0,21) + "...";
+
+    if ( resize )
+        borderTitle = borderTitle.substring(0, resize*0.08);
+    
+    var cc = search;
+    if(!cc){
+        if(isNaN(ID)){
+            var is_local = ID.match('.*_local_.*');
+            if(!is_local)
+                cc = document.getElementById("em_message_search").value;
+            else{
+                if (currentTab == 0)
+                    cc = "";
+                else
+                    cc = document.getElementsByName(currentTab)[0].value;
+            }
+        }else{
+            cc ="";
+        }
+    }
+    td.innerHTML = "<div><div id='font_border_id_" + ID+"' class='font-menu'>" +
                                 borderTitle +
                             "</div>\n\
@@ -273,130 +276,165 @@
                                 <img onmousedown='javascript:return false' style='cursor:pointer' onclick=delete_border('" + ID + "','false') src='templates/"+template+"/images/close_button.gif'/>\n\ " +
                             "</div>\n\ " + 
-							"<input type=\"hidden\" name=\""+ ID+"\" value=\""+cc+"\"></div>";		
-	bb = document.getElementById("border_blank");
-	parent_bb = bb.parentNode; //Pego o tbody
-	parent_bb.insertBefore(td, bb);
-
-	if((typeof(id_value) == 'string') && id_value.match(/_r/)){
-		$(td).draggable({
-			start : function(){
-				$('.upper, .lower').show();
-        		$(".lower").css("top", ($("#content_folders").height()-18) + $("#content_folders").offset().top);
-				if($(".shared-folders").length){
-					$(".shared-folders").parent().find('.folder:not(".shared-folders")').droppable({
-						over : function(a, b){						
-							//SETA BORDA EM VOLTA DA PASTA
-							over = $(this);
-							$(this).addClass("folder-over");
-							if(($(this)[0] != $(this).parent().find(".head_folder")[0]))
-								if($(this).prev()[0])
-									if($(this).parent().find(".expandable-hitarea")[0] == $(this).prev()[0]){
-										setTimeout(function(){
-											if(over.hasClass("folder-over"))
-												over.prev().trigger("click");
-										}, 500);
-										
-									}
-							//$("#content_folders").stop().scrollTo($(this), {axis:'y', margin:true, offset:-50, duration:400});
-						},
-						out : function(){
-							//RETIRA BORDA EM VOLTA DA PASTA
-							$(this).removeClass("folder-over");
-						},
-						//accept: ".draggin_mail",
-						drop : function(event, ui){
-							$(this).css("border", "0");
-							if($(this).parent().attr('id') == undefined){
-								var folder_to = 'INBOX';
-								var to_folder_title = get_lang("Inbox");
-							}else{
-								var folder_to = $(this).parent().attr('id');
-								var to_folder_title = $(this).attr('title');
-							}		
-							var folder_to_move = ui.draggable.parent().attr('id');
-							var border_id = ui.draggable.find("input[type=hidden]").attr("name");
-							if(folder_to_move == "border_tr"){
-								var id_msg = border_id.split("_")[0];
-								folder = $("#input_folder_"+border_id+"_r")[0] ? $("#input_folder_"+border_id+"_r").val() : (openTab.imapBox[border_id] ? openTab.imapBox[border_id]:get_current_folder());
-								move_msgs2(folder, id_msg, border_id, folder_to, to_folder_title,true);
-								return refresh();
-							}
-						}
-					});
-				}
-			},
-			stop :function(){
-				$('.upper, .lower').hide();
-				$(".shared-folders").parent().find(".folder").droppable("destroy");
-			},
-			helper: function(event){
-				if(	borderTitle.length > 18 )
-					return $("<td>"+DataLayer.render('../prototype/modules/mail/templates/draggin_box.ejs', {texto : borderTitle.substring(0,18) + "...", type: "messages"})+"</td>");
-				else
-					return $("<td>"+DataLayer.render('../prototype/modules/mail/templates/draggin_box.ejs', {texto : borderTitle, type: "messages"})+"</td>");
-			},
-			delay: 150,
-			cursorAt: {top: 5, left: 56},
-			refreshPositions: true ,
-			containment: "#divAppbox"
-		});
-	}
-		//_dragArea.makeDragged(td, id_value,td.value);
-
-	BordersArray[BordersArray.length] = new setBorderAttributes(ID);
-
-	var div = document.createElement("DIV");
-	div.id = "content_id_" + ID;
-	div.className = "conteudo";
-	div.style.display='';
-
-	div.style.overflow = "hidden";
-
-	Element("exmail_main_body").insertBefore(div,Element("footer_menu"));       
-	if (!is_ie)
-		resizeWindow();
-	alternate_border(ID);
+                            "<input type=\"hidden\" name=\""+ ID+"\" value=\""+cc+"\"></div>";      
+    bb = document.getElementById("border_blank");
+    parent_bb = bb.parentNode; //Pego o tbody
+    parent_bb.insertBefore(td, bb);
+
+    if((typeof(id_value) == 'string') && id_value.match(/_r/)){
+        $(td).draggable({
+            start : function(){
+                $('.upper, .lower').show();
+                $(".lower").css("top", ($("#content_folders").height()-18) + $("#content_folders").offset().top);
+                /* Habilitar anexar mensagem por drag-and-drop, se a aba atual for editável,  
+                ou seja, nem de leitura (2), nem de lista de mensagens (0):*/ 
+                var current_tab_type = openTab.type[currentTab]; 
+                if (current_tab_type != 0 && current_tab_type != 2){ 
+                    var dropzone = $("#fileupload_msg" + currentTab + "_droopzone"); 
+                    dropzone.show(); 
+                    dropzone.prev().hide(); 
+                    dropzone.droppable({ 
+                        over: function (event, ui){ 
+                            dropzone.addClass('hover in'); 
+                            $(ui.helper).find(".draggin-folder,.draggin-mail").css("color", "green"); 
+                        }, 
+                        out: function (event, ui) { 
+                            dropzone.removeClass('hover in'); 
+                            $(ui.helper).find(".draggin-folder,.draggin-mail").css("color", ""); 
+                        }, 
+                        drop: function (event, ui) { 
+                            var border_id = ui.draggable.find("input[type=hidden]").attr("name"); 
+                            var id_msg = border_id.split("_")[0]; 
+                            var folder = $("#input_folder_"+border_id+"_r")[0] ? $("#input_folder_"+border_id+"_r").val() : (openTab.imapBox[border_id] ? openTab.imapBox[border_id]:get_current_folder()); 
+                            attach_message(folder, id_msg); /* Anexa a mensagem especificada (por folder e id_msg) 
+                                                               na mensagem sendo criada.*/ 
+                        } 
+                    }); 
+                } 
+                if($(".shared-folders").length){
+                    $(".shared-folders").parent().find('.folder:not(".shared-folders")').droppable({
+                        over : function(a, b){                      
+                            //SETA BORDA EM VOLTA DA PASTA
+                            $(b.helper).find(".draggin-folder,.draggin-mail").css("color", "green");
+                            over = $(this);
+                            $(this).addClass("folder-over");
+                            if(($(this)[0] != $(this).parent().find(".head_folder")[0]))
+                                if($(this).prev()[0])
+                                    if($(this).parent().find(".expandable-hitarea")[0] == $(this).prev()[0]){
+                                        setTimeout(function(){
+                                            if(over.hasClass("folder-over"))
+                                                over.prev().trigger("click");
+                                        }, 500);
+                                        
+                                    }
+                            //$("#content_folders").stop().scrollTo($(this), {axis:'y', margin:true, offset:-50, duration:400});
+                        },
+                        out : function(a,b){
+                            //RETIRA BORDA EM VOLTA DA PASTA
+                            $(b.helper).find(".draggin-folder,.draggin-mail").css("color", "");
+                            $(this).removeClass("folder-over");
+                        },
+                        //accept: ".draggin_mail",
+                        drop : function(event, ui){
+                            $(this).css("border", "0");
+                            if($(this).parent().attr('id') == undefined){
+                                var folder_to = 'INBOX';
+                                var to_folder_title = get_lang("Inbox");
+                            }else{
+                                var folder_to = $(this).parent().attr('id');
+                                var to_folder_title = $(this).attr('title');
+                            }       
+                            var folder_to_move = ui.draggable.parent().attr('id');
+                            var border_id = ui.draggable.find("input[type=hidden]").attr("name");
+                            if(folder_to_move == "border_tr"){
+                                var id_msg = border_id.split("_")[0];
+                                folder = $("#input_folder_"+border_id+"_r")[0] ? $("#input_folder_"+border_id+"_r").val() : (openTab.imapBox[border_id] ? openTab.imapBox[border_id]:get_current_folder());
+                                move_msgs2(folder, id_msg, border_id, folder_to, to_folder_title,true);
+                                return refresh();
+                            }
+                        }
+                    });
+                }
+            },
+            stop :function(){
+                $('.upper, .lower').hide();
+                $(".shared-folders").parent().find(".folder").droppable("destroy");
+                /* Habilitar anexar mensagem por drag-and-drop, se a aba atual for editável,  
+                ou seja, nem de leitura (2), nem de lista de mensagens (0):*/ 
+                var current_tab_type = openTab.type[currentTab]; 
+                if (current_tab_type != 0 && current_tab_type != 2){ 
+                    var dropzone = $("#fileupload_msg" + currentTab + "_droopzone"); 
+                    dropzone.hide(); 
+                    dropzone.prev().show(); 
+                } 
+            },
+            helper: function(event){
+                if( borderTitle.length > 18 )
+                    return $("<td>"+DataLayer.render('../prototype/modules/mail/templates/draggin_box.ejs', {texto : borderTitle.substring(0,18) + "...", type: "messages"})+"</td>");
+                else
+                    return $("<td>"+DataLayer.render('../prototype/modules/mail/templates/draggin_box.ejs', {texto : borderTitle, type: "messages"})+"</td>");
+            },
+            delay: 150,
+            cursorAt: {top: 5, left: 56},
+            refreshPositions: true ,
+            containment: "#divAppbox"
+        });
+    }
+        //_dragArea.makeDragged(td, id_value,td.value);
+
+    BordersArray[BordersArray.length] = new setBorderAttributes(ID);
+
+    var div = document.createElement("DIV");
+    div.id = "content_id_" + ID;
+    div.className = "conteudo";
+    div.style.display='';
+
+    div.style.overflow = "hidden";
+
+    Element("exmail_main_body").insertBefore(div,Element("footer_menu"));       
+    if (!is_ie)
+        resizeWindow();
+    alternate_border(ID);
     uidsSave[ID] = [];
     saveBorderError[ID] = false;
-	return ID;
+    return ID;
 }
 
 function resize_borders()
 {
-	var numBorders = count_borders();
-
-	if (numBorders > 8)
-		return false;
-
-	return redim_borders(numBorders+1);
+    var numBorders = count_borders();
+
+    if (numBorders > 8)
+        return false;
+
+    return redim_borders(numBorders+1);
 }
 
 function count_borders()
 {
-	var numBorders = 0;
-	var children = Element('border_tr').childNodes;
-	for (var i=0; i<children.length; i++) {
-	    if ((children[i].nodeName === 'TD') && (children[i].id!=='border_id_0') && (children[i].id!=='border_blank'))
-		numBorders++;
-	}
-
-	return numBorders;
+    var numBorders = 0;
+    var children = Element('border_tr').childNodes;
+    for (var i=0; i<children.length; i++) {
+        if ((children[i].nodeName === 'TD') && (children[i].id!=='border_id_0') && (children[i].id!=='border_blank'))
+        numBorders++;
+    }
+
+    return numBorders;
 }
 
 function redim_borders(numBorders)
 {
-	var children = Element('border_tr').childNodes;
-	var clientWidth = (window.document.body.clientWidth - findPosX(Element("exmail_main_body"))) - Element("border_id_0").clientWidth - 30;
-	var newWidthTD = (clientWidth/numBorders)-6;
-	newWidthTD = newWidthTD > 200 ? 200 : (newWidthTD < 50 ? 50 : newWidthTD);
-	children = Element('border_tr').childNodes;
-	for (var i=0; i<children.length; i++) {
-		if ((children[i].nodeName === 'TD') && (children[i].id!=='border_id_0') && (children[i].id!=='border_blank')){
-			$(children[i]).css("width", newWidthTD);
-			$(children[i]).find('div:first').css("width", newWidthTD);
-			set_border_caption(children[i].id, children[i].title, newWidthTD);
-		}
-	}
-	return newWidthTD;
+    var children = Element('border_tr').childNodes;
+    var clientWidth = (window.document.body.clientWidth - findPosX(Element("exmail_main_body"))) - Element("border_id_0").clientWidth - 30;
+    var newWidthTD = (clientWidth/numBorders)-6;
+    newWidthTD = newWidthTD > 200 ? 200 : (newWidthTD < 50 ? 50 : newWidthTD);
+    children = Element('border_tr').childNodes;
+    for (var i=0; i<children.length; i++) {
+        if ((children[i].nodeName === 'TD') && (children[i].id!=='border_id_0') && (children[i].id!=='border_blank')){
+            $(children[i]).css("width", newWidthTD);
+            $(children[i]).find('div:first').css("width", newWidthTD);
+            set_border_caption(children[i].id, children[i].title, newWidthTD);
+        }
+    }
+    return newWidthTD;
 }
 
@@ -411,10 +449,10 @@
             border_width = border.clientWidth;
         }
-	var caption = "";
+    var caption = "";
     if (border != null){
-		Element("font_"+border.id).style.width = (border_width - 35)+'px';
-		Element("font_"+border.id).innerHTML = title;
-	}
-	return(title);
+        Element("font_"+border.id).style.width = (border_width - 35)+'px';
+        Element("font_"+border.id).innerHTML = title;
+    }
+    return(title);
 }
 
@@ -442,14 +480,14 @@
                             'type':     'question',
                             'overlay_opacity': '0.5',
-							'custom_class': 'custom-zebra-filter',
+                            'custom_class': 'custom-zebra-filter',
                             'buttons':  buttons,
                             'width' : width,
                             'onClose':  function(clicked) {
-									if(clicked == 'Cancelar'){
-										if (RichTextEditor.plain[id] != true) 
-											setTimeout("RichTextEditor.focus("+ID+")",100);                  
-										else  
-											$('#body_'+ID).focus(); 
-									}
+                                    if(clicked == 'Cancelar'){
+                                        if (RichTextEditor.plain[id] != true) 
+                                            setTimeout("RichTextEditor.focus("+ID+")",100);                  
+                                        else  
+                                            $('#body_'+ID).focus(); 
+                                    }
                                     if(clicked == 'Descartar alterações' || clicked == 'Descartar alterações e anexos' ) {
                                         if (openTab.imapBox[ID] && !openTab.toPreserve[ID])
@@ -477,5 +515,5 @@
                                                                 $("#cc_"+ID).focus();
                                                         else if ($("#tr_cco_"+ID).css('display') != 'none' && $.trim($("#cco_"+ID).val()) == "")
-                                                                $("#cco_"+ID).focus();		
+                                                                $("#cco_"+ID).focus();      
                                                         else if ($.trim($("#subject_"+ID).val()) == "")
                                                                 $("#subject_"+ID).focus();
@@ -494,10 +532,10 @@
                             }})}, 300);    
         }
-	
+    
 }
 
 function editTest(ID){
     var body = document.getElementById('body_'+ ID);
-	var content = $('#content_id_'+ ID);
+    var content = $('#content_id_'+ ID);
     if (body)
     {
@@ -522,8 +560,8 @@
     }
 
-    if($("#content_id_"+currentTab+" textarea[name=input_to]").length ){
-        if($("#content_id_"+currentTab+" .save").is(':disabled') ) {
+    if($("#content_id_"+ID+" textarea[name=input_to]").length ){
+        if($("#content_id_"+ID+" .save").is(':disabled') ) {
              close_delete(ID, msg_sent);
-        } else if( $("#content_id_"+currentTab+" .save").is(':enabled') ) {
+        } else if( $("#content_id_"+ID+" .save").is(':enabled') ) {
              return(draftTests(ID, msg_sent));
         }
@@ -537,12 +575,12 @@
      
     /*var bolExecuteClose = true;
-	var borderElem = Element("border_id_" + ID);
-	if (borderElem){
+    var borderElem = Element("border_id_" + ID);
+    if (borderElem){
             borderElem.onclick = null; // It's avoid a FF3 bug
         }else{
             return false;
         }
-	if (msg_sent == 'false')
-	{
+    if (msg_sent == 'false')
+    {
             if (editTest(ID)){
                 bolExecuteClose = false;
@@ -550,5 +588,5 @@
                     return(draftTests(ID, msg_sent));
             }
-	}
+    }
     
         
@@ -556,6 +594,6 @@
         {
             close_delete(ID, msg_sent);
-		}
-		delete(openTab.type[ID]);
+        }
+        delete(openTab.type[ID]);
         return true;*/
          
@@ -564,5 +602,5 @@
 function close_delete(ID, msg_sent)
 {
-	openTab.toPreserve[ID] = false;
+    openTab.toPreserve[ID] = false;
         // Limpa o autosave
             if (preferences.auto_save_draft == 1 && autoSaveControl.timer[ID] !== null )
@@ -573,38 +611,38 @@
         ////////////////////////////////
         
-	hold_session = false;
-	if (exist_className(Element('border_id_'+ID),'menu-sel'))
-	{
-		if (BordersArray[BordersArray.length-2].sequence == ID)
-			this.alternate_border(0);
-		else
-			this.alternate_border(BordersArray[BordersArray.length-2].sequence);
-	}
-
-	// Remove TD, title
-	border = Element('border_id_' + ID);
-	border.parentNode.removeChild(border);
-	var j=0;
-	var new_BordersArray = new Array();
-	for (i=0;i<BordersArray.length;i++)
-		if (document.getElementById(BordersArray[i].border_id) != null){
-			new_BordersArray[j] = BordersArray[i];
-			j++;
-		}
-	if(j == 1)
-		Element("footer_menu").style.display = '';
-	BordersArray = new_BordersArray;
-
-	// Remove Div Content
-	content = Element('content_id_' + ID);
-	content.parentNode.removeChild(content);
-	if(is_webkit)
-		resizeWindow();
-	RichTextEditor.destroy( 'body_'+ID );
+    hold_session = false;
+    if (exist_className(Element('border_id_'+ID),'menu-sel'))
+    {
+        if (BordersArray[BordersArray.length-2].sequence == ID)
+            this.alternate_border(0);
+        else
+            this.alternate_border(BordersArray[BordersArray.length-2].sequence);
+    }
+
+    // Remove TD, title
+    border = Element('border_id_' + ID);
+    border.parentNode.removeChild(border);
+    var j=0;
+    var new_BordersArray = new Array();
+    for (i=0;i<BordersArray.length;i++)
+        if (document.getElementById(BordersArray[i].border_id) != null){
+            new_BordersArray[j] = BordersArray[i];
+            j++;
+        }
+    if(j == 1)
+        Element("footer_menu").style.display = '';
+    BordersArray = new_BordersArray;
+
+    // Remove Div Content
+    content = Element('content_id_' + ID);
+    content.parentNode.removeChild(content);
+    if(is_webkit)
+        resizeWindow();
+    RichTextEditor.destroy( 'body_'+ID );
         delete msgAttachments[ID];
         //Caso for uma mensagem anexada tem que deletar ela da lixeira apos fechar a aba
             var isPartMsg = false;
-			if(!parseInt(id2))
-				return;
+            if(!parseInt(id2))
+                return;
             var id2 = ID.replace('_r','');
             for(var ii = 0; ii < partMsgs.length; ii++)
@@ -620,30 +658,30 @@
         ///////////////////////////////////////////////////////////////////////////////////
         
-	return true;
+    return true;
 }
 
 function getTabPrefix() { // define o prefixo para os checkboxes das mensagens
-	if (typeof(currentTab)!='number')
-		return currentTab+"_";
-	else
-		return "";
+    if (typeof(currentTab)!='number')
+        return currentTab+"_";
+    else
+        return "";
 }
 
 function getMessageIdFromRowId(row_id) { // extrai o id da mensagem do id da linha
-	var p = row_id.search("_s");
-	if (p>0)
-		return row_id.substr(0,p);
-	else
-		return row_id;
+    var p = row_id.search("_s");
+    if (p>0)
+        return row_id.substr(0,p);
+    else
+        return row_id;
 }
 
 function getNumBoxFromTabId(tab_id) { // extrai o numBox do id da tab
-	if (typeof(tab_id)=='number') {
-		return tab_id;
-	}
-	else {
-		var p = tab_id.search(/[0-9]/);
-		return tab_id.substr(p);
-	}
+    if (typeof(tab_id)=='number') {
+        return tab_id;
+    }
+    else {
+        var p = tab_id.search(/[0-9]/);
+        return tab_id.substr(p);
+    }
 }
 
@@ -673,5 +711,4 @@
 function listAttachment(ID)
 {
-   return (typeof(msgAttachments[ID]) == 'undefined') ? '' : JSON.stringify(msgAttachments[ID]); 
-}
-
+    return (typeof(msgAttachments[ID]) == 'undefined') ? '' : JSON.stringify(msgAttachments[ID]);
+}
Index: branches/2.5/expressoMail1_2/js/InfoContact.js
===================================================================
--- branches/2.5/expressoMail1_2/js/InfoContact.js	(revision 8147)
+++ branches/2.5/expressoMail1_2/js/InfoContact.js	(revision 8232)
@@ -7,4 +7,5 @@
 	this.td;
 	this.createCard();
+	this.folder = get_current_folder();
 }
 
@@ -69,9 +70,13 @@
 
 emInfoContact.prototype.show = function (data){
+	if (this.folder != get_current_folder()){
+		this.folder = get_current_folder();
+		return false;
+	}	
 	var _this = this;
 	var card = Element("card_cc");
 	card.style.left = (findPosX(this.td) + 20)+"px";
-        var divScroll = Element("divScrollMain_"+numBox); 
-        var y = findPosY(this.td) + 20 - (divScroll ? divScroll.scrollTop : 0); 
+	var divScroll = Element("divScrollMain_"+numBox);
+	var y = findPosY(this.td) + 20 - (divScroll ? divScroll.scrollTop : 0);
 	var w_height = is_ie ? document.body.clientHeight + document.body.scrollTop : window.innerHeight + window.pageYOffset;
 	if(y + 160 > w_height)
Index: branches/2.5/expressoMail1_2/js/common_functions.js
===================================================================
--- branches/2.5/expressoMail1_2/js/common_functions.js	(revision 8080)
+++ branches/2.5/expressoMail1_2/js/common_functions.js	(revision 8232)
@@ -694,4 +694,15 @@
 }
 
+/* 
+	Abre o diálogo de edição de filtro na tela de criação de filtro,  
+	com os dados da mensagem (remetente e assunto) pré-carregados. 
+*/ 
+ function filter_from_msg (msg) { 
+	var html = DataLayer.render( BASE_PATH + 'modules/filters/init.ejs', {}); 
+	initialize_container(html); 
+	list_container = create_filter_dialog(); 
+	render_new_rule(msg.from.email, html_entities(msg.subject)); 
+	$('.expresso-window-container').dialog('open'); 
+} 
 
 function sharebox(){
@@ -771,5 +782,5 @@
 			var number = id.replace(/_[a-zA-Z0-9]+/,"");
 		}
-		messages.push(onceOpenedHeadersMessages[folder_name][number]);
+		messages.push(onceOpenedHeadersMessages[folder_name][number] || number);
 	}
 
@@ -997,12 +1008,12 @@
     abas_unseen = abas_unseen.match(/(<font.*?>){0,1} *([0-9]+) *(<\/font>){0,1}/)[2];
 
-        if (folder_unseen){ 
-                //folder_unseen.innerHTML = (parseInt(folder_unseen.innerHTML) + 1); 
-                /*Incrementa recursivamente o contador de mensagens*/
-                $('.selected').parents().find('> span.folder').not('.inbox').each(function(index,ui){
-                   var unseen = $(ui).find('.folder_unseen:last');
-                   unseen.html(parseInt(unseen.html(),10) + 1);
-                }); 
-        } 
+	if (folder_unseen){
+		//folder_unseen.innerHTML = (parseInt(folder_unseen.innerHTML) + 1);
+		/*Incrementa recursivamente o contador de mensagens*/
+		$('.selected').parents().find('> span.folder').not('.inbox').each(function(index,ui){
+		   var unseen = $(ui).find('.folder_unseen:last');
+		   unseen.html(parseInt(unseen.html(),10) + 1);
+		});
+	}
 	else
 	{
@@ -1046,10 +1057,10 @@
 	if ((folder_unseen) && (parseInt(folder_unseen.innerHTML) > 1))
 	{
-                //folder_unseen.innerHTML = (parseInt(folder_unseen.innerHTML) - 1); 
-                /*Decrementa recursivamente o contador de mensagens*/ 
-                $('.selected').parents().find('> span.folder').not('.inbox').each(function(index,ui){ 
-                   var unseen = $(ui).find('.folder_unseen:last'); 
-                   unseen.html(parseInt(unseen.html(),10) - 1); 
-                });      
+		//folder_unseen.innerHTML = (parseInt(folder_unseen.innerHTML) - 1);
+		/*Decrementa recursivamente o contador de mensagens*/
+		$('.selected').parents().find('> span.folder').not('.inbox').each(function(index,ui){
+		   var unseen = $(ui).find('.folder_unseen:last');
+		   unseen.html(parseInt(unseen.html(),10) - 1);
+		});	
 	}
 	else if (parseInt(folder_unseen.innerHTML) <= 1)
Index: branches/2.5/expressoMail1_2/js/main.js
===================================================================
--- branches/2.5/expressoMail1_2/js/main.js	(revision 8188)
+++ branches/2.5/expressoMail1_2/js/main.js	(revision 8232)
@@ -1,3 +1,2 @@
-// Tempo do auto refresh (em milisegundos)
 var time_refresh = 150000;
 
@@ -152,137 +151,110 @@
 
 		
-    if(preferences.show_name_print_messages == "1") { 
-        var getUserName = document.getElementById("user_info"); 
-        var userName = getUserName.innerHTML; 
-        var position = userName.indexOf("-"); 
-        var userName = userName.substring(3, position); 
-        cabecalho = '<h4>' + userName; 
-    } 
- 
-        current_folder="INBOX"; 
- 
-    //MAILARCHIVER-02 
-    //Try to get ArchiveServices object directly 
-    if(ArchiveServices) 
-        expresso_mail_archive.Startup(); 
-    //ArchiveServices not runnnig: catch the user preferences to set up message at header 
-    else{ 
-        if(preferences.use_local_messages=="1") 
-            write_msg(get_lang('Sorry, but Mail Archiver does not seems to be running or installed at this workstation. By now, we are turning off local messages!')); 
-    } 
- 
-    //cExecute ("$this.db_functions.get_dropdown_contacts", save_contacts); //Save contacts needs preferences. 
-    $.ajax({ 
-        async: false, 
-        url: "controller.php?" + $.param( {action: "$this.imap_functions.getMessagesIds", 
-            folder: get_current_folder(), 
-             msg_range_begin: "0", 
-             msg_range_end: "0", 
-            sort_box_type: "SORTARRIVAL", 
-            search_box_type: search_box_type, 
-            sort_box_reverse: "1" 
-            }), 
-        success: function(data){ 
-            data = connector.unserialize(data); 
-            if(data){ 
-                var _data = {}; 
-                $.each(data,function(index,value){ 
-                    if (data[index]){ 
-                        _data[data[index]] = data[index]; 
-                    } 
-                }); 
-                populateSelectedMsgs(_data); 
-            } 
-        }, 
-        beforeSend: function( jqXHR, settings ){ 
-            connector.showProgressBar(); 
-        }, 
-        complete: function( jqXHR, settings ){ 
-            connector.hideProgressBar(); 
+    if(preferences.show_name_print_messages == "1") {
+        var getUserName = document.getElementById("user_info");
+        var userName = getUserName.innerHTML;
+        var position = userName.indexOf("-");
+        var userName = userName.substring(3, position);
+        cabecalho = '<h4>' + userName;
+    }
+
+	current_folder="INBOX";
+
+    //MAILARCHIVER-02
+    //Try to get ArchiveServices object directly
+    if(ArchiveServices)
+        expresso_mail_archive.Startup();
+    //ArchiveServices not runnnig: catch the user preferences to set up message at header
+    else{
+        if(preferences.use_local_messages=="1")
+            write_msg(get_lang('Sorry, but Mail Archiver does not seems to be running or installed at this workstation. By now, we are turning off local messages!'));
+    }
+
+//  cExecute ("$this.db_functions.get_dropdown_contacts", save_contacts); //Save contacts needs preferences.
+
+    cExecute ("$this.imap_functions.get_range_msgs2&folder=INBOX&msg_range_begin=1&msg_range_end="+preferences.max_email_per_page+"&sort_box_type=SORTARRIVAL&search_box_type=ALL&sort_box_reverse=1", handler_draw_box);
+
+    if(preferences.hide_folders == "1")
+        Element('divAppboxHeader').innerHTML =  title_app_menu;
+
+    //Desbilitado limpeza de lixeira por request. Ticket #3253
+    //if (preferences.delete_trash_messages_after_n_days != 0)
+    ///	cExecute ("$this.imap_functions.automatic_trash_cleanness&before_date="+preferences.delete_trash_messages_after_n_days+"&cyrus_delimiter="+cyrus_delimiter, handler_automatic_trash_cleanness);
+
+    //if(preferences.outoffice == "1")
+    //
+
+    //Troca da forma de construção de menu para o plugin jquery.contextMenu
+    //ConstructMenuTools();
+    //MAILARCHIVER-00
+    //if ( (preferences.use_local_messages==1) && (expresso_local_messages.is_offline_installed()) )  //Precisa ser feito após a renderização da caixa de emails
+        //check_mail_in_queue();
+
+    // Insere a applet de criptografia
+    if (preferences.use_signature_digital_cripto == '1'){
+        loadApplet();
+    }
+    // Fim da inserção da applet
+    cExecute("$this.imap_functions.get_folders_list&onload=true", update_menu);
+    //update_menu(Folder.getList(false));
+
+    if($.cookie('collapse_folders') == "true"){
+        if(!is_ie)
+            $("#folderscol").addClass( "hidden");
+        else
+            $("#folderscol").hide();
+        $(".collapse_folders").addClass("ui-icon ui-icon-triangle-1-e").children().attr('title', "Expandir");
+        refresh();
+        resizeWindow();
+    }
+    else{
+        $(".collapse_folders").addClass("ui-icon ui-icon-triangle-1-w").children().attr('title', "Ocultar");
+        refresh();
+        resizeWindow();
+    }
+
+    $(".collapse_folders_td").attr('title', "Ocultar/Expandir").click(function(){
+        if($("#folderscol").css("display") != "none"){
+            if(!is_ie)
+                $("#folderscol").addClass( "hidden");
+            else
+                $("#folderscol").hide();
+
+            $(".collapse_folders").removeClass("ui-icon-triangle-1-w");
+            $(".collapse_folders").addClass("ui-icon-triangle-1-e");
+            $(".collapse_folders").parent().attr('title', "Expandir");
+            $.cookie('collapse_folders', "true");
+            refresh();
+            resizeWindow();
+        }else{
+            if(!is_ie)
+                $("#folderscol").removeClass( "hidden");
+            else
+                $("#folderscol").show();
+            $(".collapse_folders").removeClass("ui-icon-triangle-1-e");
+            $(".collapse_folders").addClass("ui-icon-triangle-1-w");
+            $(".collapse_folders").parent().attr('title', "Ocultar");
+            $.cookie('collapse_folders', "false");
+            refresh();
+            resizeWindow();
         }
-    }); 
-     cExecute ("$this.imap_functions.get_range_msgs2&folder=INBOX&msg_range_begin=1&msg_range_end="+preferences.max_email_per_page+"&sort_box_type=SORTARRIVAL&search_box_type=ALL&sort_box_reverse=1", handler_draw_box); 
- 
-    if(preferences.hide_folders == "1") 
-        Element('divAppboxHeader').innerHTML =  title_app_menu; 
- 
-    //Desbilitado limpeza de lixeira por request. Ticket #3253 
-    //if (preferences.delete_trash_messages_after_n_days != 0) 
-    /// cExecute ("$this.imap_functions.automatic_trash_cleanness&before_date="+preferences.delete_trash_messages_after_n_days+"&cyrus_delimiter="+cyrus_delimiter, handler_automatic_trash_cleanness); 
- 
-    //if(preferences.outoffice == "1") 
-    // 
- 
-    //Troca da forma de construção de menu para o plugin jquery.contextMenu 
-    //ConstructMenuTools(); 
-    //MAILARCHIVER-00 
-    //if ( (preferences.use_local_messages==1) && (expresso_local_messages.is_offline_installed()) )  //Precisa ser feito após a renderização da caixa de emails 
-        //check_mail_in_queue(); 
- 
-    // Insere a applet de criptografia 
-    if (preferences.use_signature_digital_cripto == '1'){ 
-        loadApplet(); 
-    } 
-    // Fim da inserção da applet 
-    cExecute("$this.imap_functions.get_folders_list&onload=true", update_menu); 
- 
-    if($.cookie('collapse_folders') == "true"){ 
-        if(!is_ie) 
-            $("#folderscol").addClass( "hidden"); 
-        else 
-            $("#folderscol").hide(); 
-        $(".collapse_folders").addClass("ui-icon ui-icon-triangle-1-e").children().attr('title', "Expandir"); 
-        refresh(); 
-        resizeWindow(); 
-    } 
-    else{ 
-        $(".collapse_folders").addClass("ui-icon ui-icon-triangle-1-w").children().attr('title', "Ocultar"); 
-        refresh(); 
-        resizeWindow(); 
-    } 
- 
-    $(".collapse_folders_td").attr('title', "Ocultar/Expandir").click(function(){ 
-        if($("#folderscol").css("display") != "none"){ 
-            if(!is_ie) 
-                $("#folderscol").addClass( "hidden"); 
-            else 
-                $("#folderscol").hide(); 
- 
-            $(".collapse_folders").removeClass("ui-icon-triangle-1-w"); 
-            $(".collapse_folders").addClass("ui-icon-triangle-1-e"); 
-            $(".collapse_folders").parent().attr('title', "Expandir"); 
-            $.cookie('collapse_folders', "true"); 
-            refresh(); 
-            resizeWindow(); 
-        }else{ 
-            if(!is_ie) 
-                $("#folderscol").removeClass( "hidden"); 
-            else 
-                $("#folderscol").show(); 
-            $(".collapse_folders").removeClass("ui-icon-triangle-1-e"); 
-            $(".collapse_folders").addClass("ui-icon-triangle-1-w"); 
-            $(".collapse_folders").parent().attr('title', "Ocultar"); 
-            $.cookie('collapse_folders', "false"); 
-            refresh(); 
-            resizeWindow(); 
-        } 
-        resizeWindow(); 
- 
-    }).hover( 
-        function(){ 
-            $(this).addClass("collapse_folders_td_over"); 
-        }, 
-        function(){ 
-            $(this).removeClass("collapse_folders_td_over"); 
-        } 
-    ); 
- 
-    if(parseInt(preferences.use_dynamic_contacts)){ 
-        updateDynamicContact(); 
-    } 
- 
- 
-    var handler_automatic_trash_cleanness = function(data) 
-    { 
+        resizeWindow();
+
+    }).hover(
+        function(){
+            $(this).addClass("collapse_folders_td_over");
+        },
+        function(){
+            $(this).removeClass("collapse_folders_td_over");
+        }
+    );
+
+    if(parseInt(preferences.use_dynamic_contacts)){
+        updateDynamicContact();
+    }
+
+
+    var handler_automatic_trash_cleanness = function(data)
+    {
 		if (data != false){
 			write_msg(data.length +' '+ Element('txt_clear_trash').value);
@@ -295,8 +267,4 @@
 	// Get cyrus delimiter
 	cyrus_delimiter = Element('cyrus_delimiter').value;
-
-    cExecute ("phpgwapi.browser.isMobile", function( data ){
-		mobile_device = ( ( data.constructor == Boolean ) ? data : ( data === 'true' ) );
-	});
 
 	cExecute("$this.imap_functions.get_folders_list&onload=true", update_menu);	
@@ -595,9 +563,9 @@
 		if(Element("border_id_" + id_msg_read)) {
 			alternate_border(id_msg_read);
-			resizeWindow(); 
+			resizeWindow();
 		}
 		else {
 			var border_id = create_border(msg_info.subject, id_msg_read);
-			if(border_id)
+			if(border_id && border_id != "maximo")
 			{
 				openTab.type[border_id] = 2;
@@ -661,9 +629,9 @@
 				
 		}
-                if (msg_info.showImg) 
-                { 
-                        $("#body_"+id_msg_read).html(msg_info.body); 
-                        $('#show_img_link_'+id_msg_read).remove(); 
-                } 
+		if (msg_info.showImg)
+		{
+			$("#body_"+id_msg_read).html(msg_info.body);
+			$('#show_img_link_'+id_msg_read).remove();
+		}
 		//Change msg class to read.
 		if (!msg_is_read(ID))
@@ -705,10 +673,10 @@
 		if(differenceOfNewCriteria > 0){
 			for(var i=data.length - differenceOfNewCriteria; i < data.length; i++){
-                var msg_folder = data[i].msg_folder; 
-                var msg_number = data[i].msg_number; 
+                var msg_folder = data[i].msg_folder;
+                var msg_number = data[i].msg_number;
 				desktopNotification.sentNotification("",get_lang("Filter criteria"),  truncate(new Date(data[i].udate).toString('dd/MM HH:mm') + ' - ' + data[i].from+' - '+data[i].subject, 75));
-                                desktopNotification.showNotification(function(){ 
-                    cExecute ("$this.imap_functions.removeFlagMessagesFilter&folder="+msg_folder+"&msg_number="+msg_number, function(){}); 
-                }, function(){ 
+				desktopNotification.showNotification(function(){
+                    cExecute ("$this.imap_functions.removeFlagMessagesFilter&folder="+msg_folder+"&msg_number="+msg_number, function(){});
+                }, function(){
 					window.focus();
 					this.cancel();
@@ -721,13 +689,22 @@
 function refresh(alert_new_msg, notifyPermission){
 
+    //Não deixa atualizar caso o usuario esteja em uma aba de nova mesnagem , reponder ou encaminhar;
+    //Evita o travamento da escrita no CKEDITOR.
+    if(typeof(currentTab) !== 'undefined' && currentTab.toString().indexOf("_r_") === -1 && currentTab !== 0 )
+        return;
+
 	getFromAlertRules();
 	var handler_refresh = function(data){
-		handlerMessageFilter = function (data) {			
-			notificationFilter(data, notifyPermission);
-			alarmFollowupflagged('filtersAlarms', data);
-			
-		}
-		/* Busca  nas pastas indexadas para ver se há novas mensagens com a flag $FilteredMessage */
-		cExecute ("$this.imap_functions.getFlaggedAlertMessages&folders="+fromRules, handlerMessageFilter);
+
+        if(preferences['use_alert_filter_criteria'] == "1")
+        {
+            var handlerMessageFilter = function (data) {
+                notificationFilter(data, notifyPermission);
+                alarmFollowupflagged('filtersAlarms', data);
+
+            }
+            /* Busca  nas pastas indexadas para ver se há novas mensagens com a flag $FilteredMessage */
+            cExecute ("$this.imap_functions.getFlaggedAlertMessages&folders="+fromRules, handlerMessageFilter);
+        }
 
 		if(data['msg_range_end'])
@@ -801,4 +778,5 @@
 									over : function(a, b){						
 										//SETA BORDA EM VOLTA DA PASTA
+										$(b.helper).find(".draggin-folder,.draggin-mail").css("color", "green");
 										over = $(this);
 										$(this).addClass("folder-over");
@@ -813,6 +791,8 @@
 												}
 									},
-									out : function(){
+									out : function(a,b){
+
 										//RETIRA BORDA EM VOLTA DA PASTA
+										$(b.helper).find(".draggin-folder,.draggin-mail").css("color", "");
 										$(this).removeClass("folder-over");
 									},
@@ -1005,6 +985,6 @@
 				
  		        var userTrashFolder = ''; 
- 		       
- 		        if (arguments.length <= 6) show_success_msg = true; 
+
+ 		        if (arguments.length <= 6 && typeof(show_success_msg) == "undefined") show_success_msg = true; 
  		        if (folder == 'null') folder = current_folder; 
  		 
@@ -1013,11 +993,11 @@
 					var arrayFolder = folder.split(cyrus_delimiter); 
 					userTrashFolder = 'user'+cyrus_delimiter+arrayFolder[1]+cyrus_delimiter+special_folders['Trash'];
-                                        var has_folder = false;//Folder.get( userTrashFolder, false ); 
-                                        var folders = DataLayer.get("folder"); 
-                                        $.each(folders,function(index,value){ 
-                                                if(value && value.id == userTrashFolder)  
-                                                        has_folder = true; 
-                                        }); 
- 
+					var has_folder = false;//Folder.get( userTrashFolder, false );
+					var folders = DataLayer.get("folder");
+					$.each(folders,function(index,value){
+						if(value && value.id == userTrashFolder) 
+							has_folder = true;
+					});
+
 					if(!has_folder){
 						create_new_folder(special_folders['Trash'], 'user'+cyrus_delimiter+arrayFolder[1]);
@@ -1097,6 +1077,8 @@
 								  data = connector.unserialize( data );
 								  
-								  if( data )
-								  show_msg( data );
+								  if( data ){
+								  	data.openSameBorder = true;
+								  	show_msg( data );
+								  }
 							  },
 							  beforeSend: function( jqXHR, settings ){
@@ -1147,4 +1129,5 @@
 		params_to_delete += "&search_box_type="+search_box_type;
 		params_to_delete += "&sort_box_reverse="+sort_box_reverse;
+
 		cExecute ("$this.imap_functions.delete_msgs", handler_delete_msgs, params_to_delete);
 	}
@@ -1359,5 +1342,24 @@
 			return false;
 		}
+
 		mail_msg = ( Element("divScrollMain_"+numBox) ) ? Element("divScrollMain_"+numBox).firstChild.firstChild : Element("divScrollMain_0").firstChild.firstChild;
+
+        var showMsg = function(){
+
+            //Se pref. usar mensagens locais ativada e não for operação de arquivamento exibe mensagem de remoção.
+            if(preferences.use_local_messages == 1){
+                if(!expresso_mail_archive.isArchiveOperation){
+                    if (data.msgs_number.length == 1 || typeof(data.msgs_number) == 'string' )
+                        write_msg(get_lang("The message was moved to folder ") + lang_folder(data.new_folder_name));
+                    else
+                        write_msg(get_lang("The messages were moved to folder ") + lang_folder(data.new_folder_name));
+                }
+            } else {
+                if (data.msgs_number.length == 1 || typeof(data.msgs_number) == 'string' )
+                    write_msg(get_lang("The message was moved to folder ") + lang_folder(data.new_folder_name));
+                else
+                    write_msg(get_lang("The messages were moved to folder ") + lang_folder(data.new_folder_name));
+            }
+        }
 
 		if (openTab.type[currentTab] > 1)
@@ -1394,5 +1396,5 @@
 							proxy_mensagens.get_msg(previous_msg,folder,null,show_msg);
 						}
-					}	
+					}
 				}
 				//se houver pagina anterior a paginação deve ser refeita
@@ -1453,5 +1455,9 @@
 				mail_msg.removeChild(msg_to_delete);
 			}
-
+			if (preferences.use_shortcuts == '1' && msg_to_delete && !msg_to_delete.previousSibling){
+				if( $("#tbody_box .current_selected_shortcut_msg").length == 0 ){
+					select_msg('null','reload_msg','null');
+				}
+			}
 			// Update Box BgColor
 			var box = Element("tbody_box");
@@ -1464,4 +1470,6 @@
 				Element('tot_m').innerHTML = parseInt(Element('tot_m').innerHTML) - 1;
 			}
+
+            showMsg();
 			return;
 		}
@@ -1508,18 +1516,5 @@
 		}
 
-		//Se pref. usar mensagens locais ativada e não for operação de arquivamento exibe mensagem de remoção.
-		if(preferences.use_local_messages == 1){
-			if(!expresso_mail_archive.isArchiveOperation){
-				if (data.msgs_number.length == 1)
-					write_msg(get_lang("The message was moved to folder ") + lang_folder(data.new_folder_name));
-				else
-					write_msg(get_lang("The messages were moved to folder ") + lang_folder(data.new_folder_name));
-			}
-		} else {
-			if (data.msgs_number.length == 1)
-				write_msg(get_lang("The message was moved to folder ") + lang_folder(data.new_folder_name));
-			else
-				write_msg(get_lang("The messages were moved to folder ") + lang_folder(data.new_folder_name));
-		}	
+        showMsg();
 
 		if (data.border_ID.indexOf('r') != -1){
@@ -1550,8 +1545,9 @@
 
 	try{
-		if (proxy_mensagens.is_local_folder(Element('input_folder_'+currentTab).getAttribute('value')) && !border_ID) {
-			alert(get_lang("You cant manipulate local messages on search"));
-			return;
-		}
+        if(Element('input_folder_'+currentTab))
+            if (proxy_mensagens.is_local_folder(Element('input_folder_'+currentTab).getAttribute('value')) && !border_ID) {
+                alert(get_lang("You cant manipulate local messages on search"));
+                return;
+            }
 	} catch (e) {} 
     //Validação para recuperar o id caso não seja aba de listagem
@@ -1599,6 +1595,6 @@
                 //expresso_mail_archive.moveMessages(new_folder.substr(6), msgs_number);
                 expresso_mail_archive.moveMessages(new_folder.replace('local_messages_', ''), msgs_number);
-                if(currentTab != 0) 
-                        delete_border(border_ID); 
+                if(currentTab != 0)
+                	delete_border(border_ID);
             }
             else{
@@ -1682,11 +1678,14 @@
 				}
 				var hasFolder = false;
-				$.each(fromRules, function(index, value) {
-					if(value == folder){
-						hasFolder = true;
-						cExecute ("$this.imap_functions.removeFlagMessagesFilter&folder="+folder+"&msg_number="+msgs_number, handler_removeFlag); 
-						return false;
-					}
-				});
+                if(preferences['use_alert_filter_criteria'] == "1")
+                {
+                    $.each(fromRules, function(index, value) {
+                        if(value == folder){
+                            hasFolder = true;
+                            cExecute ("$this.imap_functions.removeFlagMessagesFilter&folder="+folder+"&msg_number="+msgs_number, handler_removeFlag);
+                            return false;
+                        }
+                    });
+                }
 				if(!hasFolder){
 					handler_removeFlag();
@@ -2149,38 +2148,38 @@
 
 function new_message_to(email) {
-        var new_border_ID = new_message('new','null');           
-        if (!new_border_ID){ 
-                var msgId; 
-                setTimeout(function(){ 
-                        msgId = $('#border_tr td.menu-sel').attr('id').toString(); 
-                        content = $("#content_id_"+msgId.substr(msgId.lastIndexOf("_")+1,msgId.length)); 
-                        /*Envio de email para um grupo*/ 
-                        if (email.indexOf('@') == -1){ 
-                                var groups = REST.get('/groups'); 
-                                        $.each(normalizeContacts(groups.collection.itens),function(index,group){ 
-                                                if (group.name.toLocaleLowerCase() == email.toLocaleLowerCase()){ 
-                                                        email = group.id; 
-                                                } 
-                                        }); 
-                                draw_email_box(email, content.find('.to').filter('textarea:first'),"G");         
-                        } 
-                        else 
-                                draw_reply_boxes_by_field("to",email,content); 
-                },500); 
-        } 
-        else{ 
-                var content = $("#content_id_"+new_border_ID);  
-                if (email.indexOf('@') == -1){ 
-                        var groups = REST.get('/groups'); 
-                                $.each(normalizeContacts(groups.collection.itens),function(index,group){ 
-                                        if (group.name.toLocaleLowerCase() == email.toLocaleLowerCase()){ 
-                                                email = group.id; 
-                                        } 
-                                }); 
-                        draw_email_box(email, content.find('.to').filter('textarea:first'),"G");         
-                } 
-                else 
-                        draw_reply_boxes_by_field("to",email,content); 
-        }        
+	var new_border_ID = new_message('new','null');		
+	if (!new_border_ID){
+		var msgId;
+		setTimeout(function(){
+			msgId = $('#border_tr td.menu-sel').attr('id').toString();
+			content = $("#content_id_"+msgId.substr(msgId.lastIndexOf("_")+1,msgId.length));
+			/*Envio de email para um grupo*/
+			if (email.indexOf('@') == -1){
+				var groups = REST.get('/groups');
+					$.each(normalizeContacts(groups.collection.itens),function(index,group){
+						if (group.name.toLocaleLowerCase() == email.toLocaleLowerCase()){
+							email = group.id;
+						}
+					});
+				draw_email_box(email, content.find('.to').filter('textarea:first'),"G");	
+			}
+			else
+				draw_reply_boxes_by_field("to",email,content);
+		},500);
+	}
+	else{
+		var content = $("#content_id_"+new_border_ID); 
+		if (email.indexOf('@') == -1){
+			var groups = REST.get('/groups');
+				$.each(normalizeContacts(groups.collection.itens),function(index,group){
+					if (group.name.toLocaleLowerCase() == email.toLocaleLowerCase()){
+						email = group.id;
+					}
+				});
+			draw_email_box(email, content.find('.to').filter('textarea:first'),"G");	
+		}
+		else
+			draw_reply_boxes_by_field("to",email,content);
+	}	
 }
 
@@ -3397,9 +3396,9 @@
 	/* Lista de palavras que vão ser procuradas no corpo do email, referente às variantes da palavra anexo em português, inglês e espanhol. */
 	if(language == "pt-br") //Português brasileiro
-		var words = ['anexo', 'anexos', 'anexada', 'anexado', 'anexei', 'anexando', 'anexaste', 'anexastes', 'anexamos', 'anexaram'];
-	else if(language == "es-es") //Espanhol
+        var words = ['anexando', 'anexos', 'anexadas', 'anexados', 'anexei',  'anexaste', 'anexastes', 'anexamos', 'anexaram', 'anexas', 'anexado', 'anexada', 'anexo', 'anexa'];
+    else if(language == "es-es") //Espanhol
 		var words = ['anexo','adjunto', 'adjuntos', 'adjuntado','adjuntamos'];
 	else //Inglês ('en')
-		var words = ['attach', 'attachment', 'attached', 'annex', 'appending'];
+        var words = ['attach', 'attachment', 'attached', 'annex', 'appending', 'appendage', 'annexe', 'appendix'];
 
 	if($('#fileupload_msg'+ID).find('.att-box').length == 0 && preferences.alert_message_attachment == '1' ) {
@@ -3456,12 +3455,12 @@
 function send_valided_message(ID, folder, folder_name)
 { 
-	if (preferences.auto_save_draft == 1)
-	   autoSaveControl.status[ID] = true;
-
-	var content = $("#content_id_"+ID);
-	var save_link = $("#content_id_"+ID).find(".save");
-	var onClick = save_link.onclick;
-	save_link.onclick = '';
-	save_link.button({disabled: true});
+    if (preferences.auto_save_draft == 1)
+       autoSaveControl.status[ID] = true;
+
+    var content = $("#content_id_"+ID);
+    var save_link = $("#content_id_"+ID).find(".save");
+    var onClick = save_link.onclick;
+    save_link.onclick = '';
+    save_link.button({disabled: true});
 
     var _subject = trim(content.find(".subject").val());
@@ -3478,5 +3477,5 @@
     $.each(array, function(index, value){
         stringReply += $(value).find("input").val() + ",";
-    });	
+    }); 
     var stringToEmail = "";
     draw_email_box(content.find(".to-tr").find("textarea:first").val() || content.find(".to-tr").find("input:visible").val(), content.find(".to-tr").find("textarea:first"));
@@ -3513,5 +3512,5 @@
         });
     }
-    stringEmail += 	stringCCEmail;
+    stringEmail +=  stringCCEmail;
 
     var mailData = new Object();
@@ -3534,41 +3533,34 @@
     mailData.msg_forward_from = $(content).find('[name="msg_forward_from"]').val();
     mailData.msg_reply_from = $(content).find('[name="msg_reply_from"]').val();
-	
-	if ($(content).find('select[name="input_from"]').val())
-		mailData.input_from = $(content).find('select[name="input_from"]').val();
-
-
-	if(stringEmail != ""){
-		$.ajax({
-			url: "controller.php?action=$this.imap_functions.send_mail",
-            data:  mailData,
-            type: 'POST',
-
-            beforeSend: function(jqXHR, settings){
-
-                write_msg( get_lang( 'Sending the message...' ) );
-                $(content).find('button.send').button('option', 'disabled', true);
-
-
-            },
-            success: function(data){
-                send_message_return(connector.unserialize(data),ID);
-			},
-			error: function(){
-				write_msg(get_lang( 'Error trying to send the message. Retry in a few seconds...' ) );
-                $(content).find('button.send').button('option', 'disabled', false);
-                var interval = setInterval(function(){
-						send_valided_message(ID,folder,folder_name);
-						clearInterval(interval);
-				},15000);
-				return;
-			}
-		});
+    
+    if ($(content).find('select[name="input_from"]').val())
+        mailData.input_from = $(content).find('select[name="input_from"]').val();
+    
+    if(stringEmail != ""){
+    $.ajax({
+        url: "controller.php?action=$this.imap_functions.send_mail",
+        data:  mailData,
+        type: 'POST',
+        async: false,
+        beforeSend: function(jqXHR, settings){
+            write_msg( get_lang( 'Sending the message...' ) );
+            $(content).find('button.send').button('option', 'disabled', true);
+        },
+        success: function(data){
+            send_message_return(connector.unserialize(data),ID);
+        },
+        error: function(){
+            write_msg(get_lang( 'Error trying to send the message. Retry in a few seconds...' ) );
+            $(content).find('button.send').button('option', 'disabled', false);
+            var interval = setInterval(function(){
+                send_valided_message(ID,folder,folder_name);
+                clearInterval(interval);
+            },15000);
+            return;
+        }
+    });
 	}else{
-		write_msg(get_lang("message without receiver"));
-		return;
-	}
-
-
+		write_msg(get_lang("message without receiver")); 
+	}
 }
 
@@ -3765,8 +3757,10 @@
 						case "unseen":
 							set_msg_as_unread(msgs[j]+'_s'+id_border, true);
+							set_msg_as_unread(msgs[j], true); // Atualiza msg na aba principal.
 							Element("search_"+id_border+"_check_box_message_"+msgs[j]).checked = false;
 							break;
 						case "seen":
 							set_msg_as_read(msgs[j]+'_s'+id_border, true);
+							set_msg_as_read(msgs[j], true); //Atualiza msg na aba principal.
 							Element("search_"+id_border+"_check_box_message_"+msgs[j]).checked = false;
 							break;
@@ -3787,5 +3781,5 @@
 		}
 		
-		draw_tree_folders();
+		draw_tree_folders(folders);
 		Element('chk_box_select_all_messages_search').checked = false;
 		refresh();
@@ -3878,12 +3872,14 @@
 						Element("check_box_message_" + msgs_to_set[i]).checked = false;
 
-						// remove a flag $FilteredMessage da mensagem ao ser marcada como lida	
-						$.each(fromRules, function(index, value) {
-							if(value == folder){
-								cExecute ("$this.imap_functions.removeFlagMessagesFilter&folder="+folder+"&msg_number="+msgs_to_set, function(){}); 
-								return false;
-							}
-						});	
-						
+                        if(preferences['use_alert_filter_criteria'] == "1")
+                        {
+                            // remove a flag $FilteredMessage da mensagem ao ser marcada como lida
+                            $.each(fromRules, function(index, value) {
+                                if(value == folder){
+                                    cExecute ("$this.imap_functions.removeFlagMessagesFilter&folder="+folder+"&msg_number="+msgs_to_set, function(){});
+                                    return false;
+                                }
+                            });
+                        }
 						break;
 					case "flagged":
@@ -4455,5 +4451,6 @@
 		update_quota(get_current_folder());
 		draw_new_tree_folder();
-		draw_tree_labels();
+        if( preferences['use_followupflags_and_labels'] == "1" )
+		    draw_tree_labels();
 		if (data){
 			if(typeof(data) == "object"){
@@ -4514,5 +4511,6 @@
 		//tree_folders.getNodeById(mount_url_folder(["INBOX",special_folders["Spam"]]))._refresh();
 		draw_new_tree_folder();
-		draw_tree_labels();
+        if( preferences['use_followupflags_and_labels'] == "1" )
+		    draw_tree_labels();
 		update_quota(get_current_folder());
 		if (data){
@@ -4552,40 +4550,4 @@
 }
 
-function buildExportArchiver(msgsArchive, name_box){
-
-    var hand_export = function(data){
-        if(!data){
-            write_msg(get_lang('Error compressing messages (ZIP). Contact the administrator.'))
-        }else if(data["empty_folder"] || data == "empty_folder"){
-            write_msg(get_lang("The selected folder is empty."));
-        }else
-          download_attachments(null, null, data, null,null, get_current_folder().split("_")[2] +'.zip');
-    }
-
-    var array = new Array();
-
-    for(var i =0; i < msgsArchive.length; i++){
-        eachMsg = {
-                'ContentType' : msgsArchive[i].ContentType,
-                'from' : { 'email' : msgsArchive[i].from.email, 'full' : msgsArchive[i].from.full, 'name' : msgsArchive[i].from.name},
-                'msg_sample' : msgsArchive[i].msg_sample,
-                'subject' : msgsArchive[i].subject,
-                'to' : { 'email' : msgsArchive[i].to.email, 'full' : msgsArchive[i].to.full, 'name' : msgsArchive[i].to.name},
-                'toaddress2' : msgsArchive[i].toaddress2,
-                'msg_number' : msgsArchive[i].msg_number,
-                'date' : new Date(msgsArchive[i].timestamp).toString()  
-        };
-        array.push(eachMsg);
-    }
-
-    $.ajax({
-        type: "POST",
-        url: "controller.php?action=$this.exporteml.export_all_byLocalFolder",
-        data: { folder: name_box, type: "msg_local", messages : array}
-    }).done(function(msg) {
-        hand_export(msg.split('"')[1]);
-    });
-}
-
 function export_all_selected_msgs(){
 	if(get_current_folder().split("_")[0] == "local"){
@@ -4596,9 +4558,7 @@
             expresso_mail_archive.getSomeMsgs([get_selected_messages()]);
         }
+
+    } else {
         
-        buildExportArchiver(expresso_mail_archive.getSomeMsg, get_current_folder().split("_")[2]);
-
-    } else {
-
     if (openTab.type[currentTab] > 1){	    
 		source_msg(currentTab,openTab.imapBox[currentTab]);
@@ -4635,9 +4595,9 @@
                 filename = data[1]+'.eml'; 
 			} 
- 
-            if(typeof data == "object") 
-                             download_attachments(null, null, data[0], null,null,filename); 
-            else  
-                 download_attachments(null, null, data, null,null,filename); 
+
+            if(typeof data == "object")
+			     download_attachments(null, null, data[0], null,null,filename);
+            else 
+                 download_attachments(null, null, data, null,null,filename);
 		}
 	}
@@ -4879,56 +4839,55 @@
 								 			write_msg(get_lang('You must wait while the messages will be imported...'));
 											
-                                                                                        var local_folder = input_hidden.attr("value"); //recupera a pasta selecionada 
-                                                                                        if(local_folder.indexOf("local_") == 0){ //verifica se a pasta selecionada é uma pasta local 
- 
-                                                                                                var fdata = local_folder.substr(15, local_folder.length); //recupera somente a estrutura da pasta ou o id 
-                                                                                                expresso_mail_archive.getFolderInfo(fdata); //recuperar a estrutura da pasta,  
-                                                                                                                                                                                        //para realizar a importação de mensagens 
-                                                                                                fdata = expresso_mail_archive.folder.path; 
- 
-                                                                                                //o mailarchiver não provê um serviço para a importação de mensagens nas pastas locais, 
-                                                                                                //mas sim uma modal, da qual são extraídas as informações e as urls para submitar os dados 
-                                                                                                //para o arquivamento de mensagens em pastas locais. 
-                                                                                                var url_src = mail_archive_protocol + '://' + mail_archive_host + ':' + mail_archive_port + '/arcserv/import?prt=' + mail_archive_protocol + '&por=' + mail_archive_port+ '&fid='+ encodeURIComponent(fdata) + '&sid=' + expresso_mail_archive.session.id; 
-                                                                                                var _html = DataLayer.render(url_src); 
-                                                                                                var regex_url = RegExp('\<iframe(.)*src=\"([^\"]*)"(.)*\>'); 
-                                                                                                var obj_params = $.parseQuery( regex_url.exec(_html)[2].split('?')[1] || '' ); 
-                                                                                                $(formSend).append('<input id="ma_import_flat" type="checkbox" value="false" name="flat" style="display:none"> ' + 
-                                                                                                        '<input id="sessionId" type="hidden" value="'+obj_params['sessvalue']+'" name="sessionId">' + 
-                                                                                                        '<input id="base" type="hidden" value="'+obj_params['basevalue']+'" name="base">' + 
-                                                                                                        '<input id="lang" type="hidden" value="'+obj_params['langvalue']+'" name="lang">'); 
- 
-                                                                                                var importEmailsLocalDialog = $('#importEmailsLocal'); 
-                                                                                                importEmailsLocalDialog.css("overflow","hidden"); 
-                                                                                                importEmailsLocalDialog.dialog( 
-                                                                                                { 
-                                                                                                        autoOpen    : false, 
-                                                                                                        height          : 200, 
-                                                                                                        width           : 350, 
-                                                                                                        resizable       : false, 
-                                                                                                        title           : get_lang('Local Archive'), 
-                                                                                                        modal           : true, 
-                                                                                                        buttons         : [ 
-                                                                                                                                         { 
-                                                                                                                                                text    : get_lang("Close"),  
-                                                                                                                                                click   : function() 
-                                                                                                                                                { 
-                                                                                                                                                        importEmailsLocalDialog.dialog("close").dialog("destroy"); 
-                                                                                                                                                } 
-                                                                                                                                         } 
-                                                                                                                                ] 
-                                                                                                }); 
- 
-                                                                                                importEmailsLocalDialog.html('<iframe frameborder="0" scrolling="no" id="frameResult" name="frameResult" ></iframe>') 
-                                                                                                $(formSend).attr("action", mail_archive_protocol + '://' + mail_archive_host + ':' + mail_archive_port + '/arcserv/import'); 
-                                                                                                $(formSend).attr("target", "frameResult"); 
-                                                                                                $(formSend).submit(); 
-                                                                                                importEmailsLocalDialog.dialog( "open" );
- 												if(typeof(shortcut) != 'undefined')
+											var local_folder = input_hidden.attr("value"); //recupera a pasta selecionada
+											if(local_folder.indexOf("local_") == 0){ //verifica se a pasta selecionada é uma pasta local
+												var fdata = local_folder.substr(15, local_folder.length); //recupera somente a estrutura da pasta ou o id
+												expresso_mail_archive.getFolderInfo(fdata); //recuperar a estrutura da pasta, 
+																							//para realizar a importação de mensagens
+												fdata = expresso_mail_archive.folder.path;
+
+												//o mailarchiver não provê um serviço para a importação de mensagens nas pastas locais,
+												//mas sim uma modal, da qual são extraídas as informações e as urls para submitar os dados
+												//para o arquivamento de mensagens em pastas locais.
+												var url_src = mail_archive_protocol + '://' + mail_archive_host + ':' + mail_archive_port + '/arcserv/import?prt=' + mail_archive_protocol + '&por=' + mail_archive_port+ '&fid='+ encodeURIComponent(fdata) + '&sid=' + expresso_mail_archive.session.id;
+												var _html = DataLayer.render(url_src);
+												var regex_url = RegExp('\<iframe(.)*src=\"([^\"]*)"(.)*\>');
+												var obj_params = $.parseQuery( regex_url.exec(_html)[2].split('?')[1] || '' );
+												$(formSend).append('<input id="ma_import_flat" type="checkbox" value="false" name="flat" style="display:none"> ' +
+													'<input id="sessionId" type="hidden" value="'+obj_params['sessvalue']+'" name="sessionId">' +
+													'<input id="base" type="hidden" value="'+obj_params['basevalue']+'" name="base">' +
+													'<input id="lang" type="hidden" value="'+obj_params['langvalue']+'" name="lang">');
+
+												var importEmailsLocalDialog = $('#importEmailsLocal');
+												importEmailsLocalDialog.css("overflow","hidden");
+												importEmailsLocalDialog.dialog(
+												{
+													autoOpen    : false,
+													height		: 200,
+													width		: 350,
+													resizable	: false,
+													title		: get_lang('Local Archive'),
+													modal		: true,
+													buttons		: [
+																	 {
+																	 	text	: get_lang("Close"), 
+																	 	click	: function()
+																	 	{
+																	 		importEmailsLocalDialog.dialog("close").dialog("destroy");
+																	 	}
+																	 }
+																]
+												});
+
+												importEmailsLocalDialog.html('<iframe frameborder="0" scrolling="no" id="frameResult" name="frameResult" ></iframe>')
+												$(formSend).attr("action", mail_archive_protocol + '://' + mail_archive_host + ':' + mail_archive_port + '/arcserv/import');
+												$(formSend).attr("target", "frameResult");
+												$(formSend).submit();
+												importEmailsLocalDialog.dialog( "open" );
+												if(typeof(shortcut) != 'undefined') 
 													shortcut.disabled = false;
-                                                                                        } else { 
-                                                                                                cExecuteForm('$this.imap_functions.import_msgs', formSend , handler_return ); 
-                                                                                        } 
- 
+											} else {
+												cExecuteForm('$this.imap_functions.import_msgs', formSend , handler_return );
+											}
+
 								 		}
 							 		}
@@ -5439,5 +5398,12 @@
             if(data.append == 1)
             {
-                proxy_mensagens.get_msg(data.msg_number,data.msg_folder,false,show_msg,false);
+                proxy_mensagens.get_msg(data.msg_number,data.msg_folder,false,function (data) {
+                    if (onceOpenedHeadersMessages[data.msg_folder] == undefined) 
+                    {
+                        onceOpenedHeadersMessages[data.msg_folder] = [];
+                    };
+                    onceOpenedHeadersMessages[data.msg_folder][data.msg_number] = data;
+                    show_msg(data);
+                },false);
                 partMsgs.push(data.msg_number);
 	}
Index: branches/2.5/expressoMail1_2/js/connector.js
===================================================================
--- branches/2.5/expressoMail1_2/js/connector.js	(revision 8103)
+++ branches/2.5/expressoMail1_2/js/connector.js	(revision 8232)
@@ -171,108 +171,108 @@
 	}
 
-    cConnector.prototype.unserializeArchiver = function(str) 
-    {    
-        _thisObject = this; 
-        var matchB = function (str, iniPos) 
-        { 
-            var nOpen, nClose = iniPos; 
-            do 
-            { 
-                nOpen = str.substr(nClose+1).search(/[0-9]\:\{/ ); 
- 
-                if (nOpen > 0) 
-                    nOpen = nOpen + nClose+3; 
- 
-                nClose = str.indexOf('}', nClose+1); 
- 
-                if (nOpen < 0) 
-                { 
-                    return nClose; 
-                } 
-                if (nOpen < nClose ) 
-                { 
-                    nClose = matchB(str, nOpen); 
-                } 
-            } while (nOpen < nClose); 
- 
-            return nClose; 
-        } 
-         
-        var f = function (str) 
-        { 
-            switch (str.charAt(0)) 
-            { 
-                case 'a': 
-                     
-                    var data = new Array(); 
-                    var n = parseInt( str.substring( str.indexOf(':')+1, str.indexOf(':',2) ) ); 
-                    var arrayContent = str.substring(str.indexOf('{')+1, str.lastIndexOf('}')); 
-                 
-                    for (var i = 0; i < n; i++) 
-                    { 
-                        var pos = 0; 
-     
-                        /* Process Index */ 
-                        var indexStr = arrayContent.substr(pos, arrayContent.indexOf(';')+1); 
-                        var index = f(indexStr); 
-                        pos = arrayContent.indexOf(';', pos)+1; 
-                         
-                        /* Process Content */ 
-                        var part = null; 
-                        switch (arrayContent.charAt(pos)) 
-                        { 
-                            case 'a': 
-                                var pos_ = matchB(arrayContent, arrayContent.indexOf('{', pos))+1; 
-                                part = arrayContent.substring(pos, pos_); 
-                                pos = pos_; 
-                                data[index] = f(part); 
-                                break; 
-                         
-                            case 's': 
-                                var pval = arrayContent.indexOf(':', pos+2); 
-                                var val  = parseInt(arrayContent.substring(pos+2, pval)); 
-                                pos = pval + val + 4; 
-                                data[index] = arrayContent.substr(pval+2, val); 
-                                break; 
-     
-                            default: 
-                                part = arrayContent.substring(pos, arrayContent.indexOf(';', pos)+1); 
-                                pos = arrayContent.indexOf(';', pos)+1; 
-                                data[index] = f(part); 
-                                break; 
-                        } 
-                        arrayContent = arrayContent.substr(pos); 
-                    } 
-                    break; 
-                     
-                case 's': 
-                    var pos = str.indexOf(':', 2); 
-                    var val = parseInt(str.substring(2,pos)); 
-                    var data = str.substr(pos+2, val); 
-                    str = str.substr(pos + 4 + val); 
-                    break; 
-     
-                case 'i': 
-                case 'd': 
-                    var pos = str.indexOf(';'); 
-                    var data = parseInt(str.substring(2,pos)); 
-                    str = str.substr(pos + 1); 
-                    break; 
-                 
-                case 'N': 
-                    var data = null; 
-                    str = str.substr(str.indexOf(';') + 1); 
-                    break; 
-     
-                case 'b': 
-                    var data = str.charAt(2) == '1' ? true : false; 
-                    break; 
-            } 
-            return data; 
-        } 
-     
-        return f(str); 
-    } 
- 
+    cConnector.prototype.unserializeArchiver = function(str)
+    {   
+        _thisObject = this;
+        var matchB = function (str, iniPos)
+        {
+            var nOpen, nClose = iniPos;
+            do
+            {
+                nOpen = str.substr(nClose+1).search(/[0-9]\:\{/ );
+
+                if (nOpen > 0)
+                    nOpen = nOpen + nClose+3;
+
+                nClose = str.indexOf('}', nClose+1);
+
+                if (nOpen < 0)
+                {
+                    return nClose;
+                }
+                if (nOpen < nClose )
+                {
+                    nClose = matchB(str, nOpen);
+                }
+            } while (nOpen < nClose);
+
+            return nClose;
+        }
+        
+        var f = function (str)
+        {
+            switch (str.charAt(0))
+            {
+                case 'a':
+                    
+                    var data = new Array();
+                    var n = parseInt( str.substring( str.indexOf(':')+1, str.indexOf(':',2) ) );
+                    var arrayContent = str.substring(str.indexOf('{')+1, str.lastIndexOf('}'));
+                
+                    for (var i = 0; i < n; i++)
+                    {
+                        var pos = 0;
+    
+                        /* Process Index */
+                        var indexStr = arrayContent.substr(pos, arrayContent.indexOf(';')+1);
+                        var index = f(indexStr);
+                        pos = arrayContent.indexOf(';', pos)+1;
+                        
+                        /* Process Content */
+                        var part = null;
+                        switch (arrayContent.charAt(pos))
+                        {
+                            case 'a':
+                                var pos_ = matchB(arrayContent, arrayContent.indexOf('{', pos))+1;
+                                part = arrayContent.substring(pos, pos_);
+                                pos = pos_;
+                                data[index] = f(part);
+                                break;
+                        
+                            case 's':
+                                var pval = arrayContent.indexOf(':', pos+2);
+                                var val  = parseInt(arrayContent.substring(pos+2, pval));
+                                pos = pval + val + 4;
+                                data[index] = arrayContent.substr(pval+2, val);
+                                break;
+    
+                            default:
+                                part = arrayContent.substring(pos, arrayContent.indexOf(';', pos)+1);
+                                pos = arrayContent.indexOf(';', pos)+1;
+                                data[index] = f(part);
+                                break;
+                        }
+                        arrayContent = arrayContent.substr(pos);
+                    }
+                    break;
+                    
+                case 's':
+                    var pos = str.indexOf(':', 2);
+                    var val = parseInt(str.substring(2,pos));
+                    var data = str.substr(pos+2, val);
+                    str = str.substr(pos + 4 + val);
+                    break;
+    
+                case 'i':
+                case 'd':
+                    var pos = str.indexOf(';');
+                    var data = parseInt(str.substring(2,pos));
+                    str = str.substr(pos + 1);
+                    break;
+                
+                case 'N':
+                    var data = null;
+                    str = str.substr(str.indexOf(';') + 1);
+                    break;
+    
+                case 'b':
+                    var data = str.charAt(2) == '1' ? true : false;
+                    break;
+            }
+            return data;
+        }
+    
+        return f(str);
+    }
+
 	//Unserialize Data Method
 	cConnector.prototype.unserialize = function(str)
@@ -290,5 +290,5 @@
 
                 nClose = (str.substr(nClose+1) == '}' || str.substr(nClose+1,1) == '}') ? nClose +1 : str.substr(nClose+1).search(/[0-9\"]\;\}/ ) + nClose + 3;
-                 
+                
                 if (nOpen < 0)
                 {
@@ -554,20 +554,20 @@
 	{
 		var div = document.getElementById('divProgressBar');
- 
-        if(div) 
-        { 
-            div.style.visibility = 'hidden'; 
-            this.isVisibleBar = false; 
-        } 
+
+        if(div)
+        {
+            div.style.visibility = 'hidden';
+            this.isVisibleBar = false;
+        }
 	}
 	
 	cConnector.prototype.showProgressBar = function(){
- 
+
 		var div = document.getElementById('divProgressBar');
-                if(div) 
-        { 
-            div.style.visibility = 'visible'; 
-            this.isVisibleBar = true; 
-        } 
+		if(div)
+        {
+            div.style.visibility = 'visible';
+            this.isVisibleBar = true;
+        }
 	}
 
Index: branches/2.5/expressoMail1_2/js/search.js
===================================================================
--- branches/2.5/expressoMail1_2/js/search.js	(revision 7760)
+++ branches/2.5/expressoMail1_2/js/search.js	(revision 8232)
@@ -568,4 +568,16 @@
 					$(td).click(function(event, ui){	
 						var messageClickedId = $(this).attr('id').match(/td_message_followup_search_([\d]+)/)[1];
+
+						var loading = $('tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited")
+                    		.find('img[alt=Carregando]');
+
+                    	//Verificar se está carregando a bandeira.
+                    	//Caso esteja ele sai da função até que seja carregado. 
+            			if( loading.length ) {
+                			return false;
+            			}
+
+ 						var followupColor = $('tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited").css('backgroundColor');
+
 						
 						var followupColor = $('tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited").css('backgroundColor');
@@ -607,5 +619,6 @@
 								
 								$('tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited")
-								.css({"background-image":"url(../prototype/modules/mail/img/flagEditor.png)"});
+								.css({"background-image":"url(../prototype/modules/mail/img/flagEditor.png)"})
+								.find('img').remove();;
 								
 								if (fail) {
@@ -613,4 +626,8 @@
 								    var isCurrentFolder = current_folder == mailbox ? '#td_message_followup_' + messageClickedId + ', ' : ''; 	
 								    $(isCurrentFolder + 'tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited").css("background", "#CCCCCC");
+								    
+								    $('#td_message_followup_search_' + messageClickedId).find(".flag-edited")
+								    .append("<img src='../prototype/modules/mail/img/flagEditor.png'/>");
+
 								    MsgsCallbackFollowupflag[fail]();
 								    return false;
@@ -619,7 +636,11 @@
 								if(current_folder == mailbox){
 									$('#td_message_followup_' + messageClickedId + ', ' + 
-									'tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).attr('title', get_lang('Follow up')).find(".flag-edited").css("background", aux.followupflagged.backgroundColor);	
+									'tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).attr('title', get_lang('Follow up')).find(".flag-edited").css("background", aux.followupflagged.backgroundColor);
+
+									$('tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).attr('title', get_lang('Follow up')).find(".flag-edited").css("background", aux.followupflagged.backgroundColor)
+									.append("<img src='../prototype/modules/mail/img/flagEditor.png'/>");	
 								}else{								
-									$('tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).attr('title', get_lang('Follow up')).find(".flag-edited").css("background", aux.followupflagged.backgroundColor);		
+									$('tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).attr('title', get_lang('Follow up')).find(".flag-edited").css("background", aux.followupflagged.backgroundColor)
+									.append("<img src='../prototype/modules/mail/img/flagEditor.png'/>");			
 								}								
 								updateCacheFollowupflag(messageClickedId, mailbox, true);
@@ -634,6 +655,6 @@
 							DataLayer.remove('followupflagged', flagged[0].id );
 							DataLayer.commit(false, false, function(){
-								$('tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited")
-								.css({"background-image":"url(../prototype/modules/mail/img/flagEditor.png)"});
+								$('tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited").html('<img src="../prototype/modules/mail/img/flagEditor.png">')
+								.css({"width":"8px","height":"6px"/*,"background-image":"url(../prototype/modules/mail/img/flagEditor.png)"*/});
 								if(current_folder == mailbox){
 									updateCacheFollowupflag(messageClickedId, mailbox, false);
@@ -651,5 +672,6 @@
 									
 									$('tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited")
-										.css({"background-image":"url(../prototype/modules/mail/img/flagEditor.png)"});
+										.css({"background-image":"url(../prototype/modules/mail/img/flagEditor.png)"})
+										.append("<img src='../prototype/modules/mail/img/flagEditor.png'/>");
 								}
 							});
@@ -657,7 +679,17 @@
 						} else {
 							$('tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited")
-							.css({"background-image":"url(../prototype/modules/mail/img/flagEditor.png)"});
-							$('tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited").css("background", followupColor);
-							$(this).parents('[role="'+messageClickedId+'_'+mailbox+'"]').attr('class', 'selected_msg').find(':checkbox').trigger('click');
+							.css({"background-image":"url(../prototype/modules/mail/img/flagEditor.png)"}).find('img').remove();
+							
+							$('tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited").css("background", followupColor)
+							.append("<img src='../prototype/modules/mail/img/flagEditor.png'/>");
+
+							//Pega id do checkbox
+							var id = $(this).parents('[role="'+messageClickedId+'_'+mailbox+'"]').attr('class', 'selected_msg').find(':checkbox').attr('id');
+							
+							//verifica se o checkbox já está selecionada
+							if($('#' + id).attr('checked') != 'checked')
+								$(this).parents('[role="'+messageClickedId+'_'+mailbox+'"]').attr('class', 'selected_msg').find(':checkbox').trigger('click');
+							
+							updateSelectedMsgs(true,messageClickedId);
 							configureFollowupflag();
 						}
@@ -676,5 +708,5 @@
 					if (aux.labels) {
 						//td1 = '<img src="../prototype/modules/mail/img/tag.png">';
-						$(td1).css({'background-image':'url(../prototype/modules/mail/img/mail-sprites.png)','background-position': '0 -1711px',"margin-left":"0",'margin-top':'3px','background-repeat':'no-repeat'});
+						$(td).css({'background-image':'url(../prototype/modules/mail/img/mail-sprites.png)','margin-left': '0px', 'margin-top':'3px', 'background-position': '0px -1706px', 'background-repeat':'no-repeat no-repeat'});
 						updateLabelsColumn(aux)		
 					} else {
@@ -829,4 +861,5 @@
 						over : function(a, b){						
 							//SETA BORDA EM VOLTA DA PASTA
+							$(b.helper).find(".draggin-folder,.draggin-mail").css("color", "green");
 							over = $(this);
 							$(this).addClass("folder-over");
@@ -841,6 +874,7 @@
 									}
 						},
-						out : function(){
+						out : function(a,b){
 							//RETIRA BORDA EM VOLTA DA PASTA
+							$(b.helper).find(".draggin-folder,.draggin-mail").css("color", "");
 							$(this).removeClass("folder-over");
 						},
@@ -882,5 +916,5 @@
 					return $(DataLayer.render('../prototype/modules/mail/templates/draggin_box.ejs', {texto : $(this).find(".td_msg_search_subject").text(), type: "messages"}));
 			},
-			cursorAt: {cursor: "crosshair", top: -5, left: -5},
+			cursorAt: {top: 5, left: 56},
 			refreshPositions: true ,
 			scroll: true, 
Index: branches/2.5/expressoMail1_2/js/messages_controller.js
===================================================================
--- branches/2.5/expressoMail1_2/js/messages_controller.js	(revision 8128)
+++ branches/2.5/expressoMail1_2/js/messages_controller.js	(revision 8232)
@@ -12,5 +12,5 @@
         if(this.is_local_folder(folder)) {
             //MAILARCHIVER-01
-            var baseFolder = folder.replace('local_messages_', '');
+            var baseFolder = folder.replace('local_messages_', ''); 
             var tree_name;
             var drawinginfo = {};
Index: branches/2.5/expressoMail1_2/js/shortcut.js
===================================================================
--- branches/2.5/expressoMail1_2/js/shortcut.js	(revision 8087)
+++ branches/2.5/expressoMail1_2/js/shortcut.js	(revision 8232)
@@ -209,8 +209,12 @@
 				
 			}
-                        if (currentTab && currentTab == 0 && code == 13){ 
-                                e.stopPropagation(); 
-                                e.preventDefault(); 
-                        } 
+			if (currentTab && currentTab == 0 && code == 13){
+				e.stopPropagation();
+				e.preventDefault();
+			}
+			if ((openTab.type[currentTab] == 2) && code == 13){
+				e.preventDefault();
+				e.stopPropagation();
+			}		
 		}
 		this.all_shortcuts[shortcut_combination] = {
@@ -279,6 +283,6 @@
 		proxy_mensagens.delete_msgs(current_folder, get_selected_messages(), 'null');
 	}else{
-                if (e.target.className.indexOf("box") == -1) 
-                        proxy_mensagens.delete_msgs(openTab.imapBox[currentTab], currentTab.substring(0, selMessageShortcut.indexOf("_r")), 'null'); 
+		if (e.target.className.indexOf("box") == -1)
+			proxy_mensagens.delete_msgs(openTab.imapBox[currentTab], currentTab.substring(0, selMessageShortcut.indexOf("_r")), 'null');
 	}
 }
Index: branches/2.5/expressoMail1_2/js/folder.js
===================================================================
--- branches/2.5/expressoMail1_2/js/folder.js	(revision 8102)
+++ branches/2.5/expressoMail1_2/js/folder.js	(revision 8232)
Index: branches/2.5/expressoMail1_2/js/MAExpressoPattern.js
===================================================================
--- branches/2.5/expressoMail1_2/js/MAExpressoPattern.js	(revision 8103)
+++ branches/2.5/expressoMail1_2/js/MAExpressoPattern.js	(revision 8232)
Index: branches/2.5/expressoMail1_2/js/wfolders.js
===================================================================
--- branches/2.5/expressoMail1_2/js/wfolders.js	(revision 7426)
+++ branches/2.5/expressoMail1_2/js/wfolders.js	(revision 8232)
@@ -48,5 +48,6 @@
 										 	click	: function()
 										 	{
-												winSaveFile.dialog("close"),dialog("destroy");
+												winSaveFile.dialog("close");
+                                                winSaveFile.dialog("destroy");
 										 	}
 										 },
@@ -134,10 +135,29 @@
 	cWFolders.prototype.makeWindow = function(border_id, type)
 	{
-        if(typeof (currentTab) == "string" && currentTab.indexOf("local") != -1){  
-            alert("Impossível manipular mensagens locais a partir de uma busca. Isso é permitido apenas para mensagens não locais.");
-            return true;
+        if(type == "move_to"){
+            if( (currentTab == 0) || (currentTab.toString().indexOf("search") >= 0)){
+                
+            	//Verifica em qual aba o usuário está
+                var selected_msg = (currentTab == 0) ? get_selected_messages() : get_selected_messages_search();
+
+                if ((parseInt(selected_msg) > 0 || selected_msg.length > 0)||(type != "move_to")){
+                    this.load( border_id, type, false);
+                }else
+                    write_msg(get_lang('No selected message.'));
+            } else{
+                if(typeof (currentTab) == "string" && currentTab.indexOf("local") != -1){
+                    alert("Impossível manipular mensagens locais a partir de uma busca. Isso é permitido apenas para mensagens não locais.");
+                    return true;
+                }
+                this.load( border_id, type, false);
+            }
+        }else {
+            if(typeof (currentTab) == "string" && currentTab.indexOf("local") != -1){
+                alert("Impossível manipular mensagens locais a partir de uma busca. Isso é permitido apenas para mensagens não locais.");
+                return true;
+            }
+            this.load( border_id, type, false);
         }
-		this.load( border_id, type, false);
-	}
+    }
 	
 /* Build the Object */
Index: branches/2.5/expressoMail1_2/js/draw_api.js
===================================================================
--- branches/2.5/expressoMail1_2/js/draw_api.js	(revision 8188)
+++ branches/2.5/expressoMail1_2/js/draw_api.js	(revision 8232)
@@ -106,4 +106,5 @@
 			}
 			cExecute ("$this.imap_functions.get_folders_list&folder="+current_folder, update_tree_folders);
+            
 		}
 
@@ -239,6 +240,7 @@
 					var nn = new dNode({id:folders[i].folder_id, caption:lang_folder(folders[i].folder_name) + '<font style=color:red>&nbsp(</font><span id="dftree_'+folders[i].folder_id+'_unseen" style=color:red>'+folders[i].folder_unseen+'</span><font style=color:red>)</font>', onClick:"change_folder('"+folders[i].folder_id+"','"+folders[i].folder_name+"')", plusSign:folders[i].folder_hasChildren});
 
-					if( folders[i].folder_name.toLowerCase() == 'inbox' )
-						Element('new_m').innerHTML = '<font style="color:red">' + folders[i].folder_unseen + '</font>';
+
+					// if( folders[i].folder_name.toLowerCase() == 'inbox' )
+					// 	Element('new_m').innerHTML = '<font style="color:black">' + folders[i].folder_unseen + '</font>';
 				}
 				else
@@ -471,6 +473,4 @@
 		}
 	}
-	
-	outOfficeVerify();
 }
 
@@ -646,5 +646,8 @@
 		}
 		draw_new_tree_folder(false, forceLoadFolders);
-		draw_tree_labels();
+
+        if( preferences['use_followupflags_and_labels'] == "1" )
+            draw_tree_labels();
+
 		if(Element("table_quota"))
 			connector.loadScript("InfoQuota");
@@ -655,4 +658,5 @@
 
 var handler_draw_box = function(data){
+    populateSelectedMsgs(data.messagesIds);
 	draw_box(data, 'INBOX', true);
 	//alternate_border(0);
@@ -661,5 +665,8 @@
 // Action on change folders.
 function change_folder(folder, folder_name){
-	if (openTab.imapBox[0] != folder)
+	if (parseInt(preferences.use_dynamic_contacts) && $(".to").length && $(".to").data( "autocomplete" ).menu.active){
+        $(".to").data( "autocomplete" ).close();
+    }
+    if (openTab.imapBox[0] != folder)
 	{
 		selectAllFolderMsgs(false);
@@ -667,5 +674,5 @@
 		var handler_draw_box = function(data)
 		{
-
+            populateSelectedMsgs(data.messagesIds);
 			if(!verify_session(data))
 				return;
@@ -683,39 +690,9 @@
 			return true;
 		}
+
 		//MAILARCHIVE
         //se for pasta local
         if (/^local_messages/.test(current_folder)) {
             $(".folders-loading").removeClass("folders-loading"); //remove o icone de loading ao clicar nas pastas locais
-        }
-        else { //se não, processamento normal da pasta
-    		$.ajax({
-                async: false,
-    			url: "controller.php?" + $.param( {action: "$this.imap_functions.getMessagesIds", 
-    				folder: folder,
-    				 msg_range_begin: "0",
-    				 msg_range_end: "0", 					
-    				sort_box_type: "SORTARRIVAL", 
-    				search_box_type: search_box_type,
-    				sort_box_reverse: "1"
-    				}),
-    			success: function(data){
-    				data = connector.unserialize(data);
-    				if(data){
-    					var _data = {};
-    					$.each(data,function(index,value){
-    						if (data[index]){
-    							_data[data[index]] = data[index];
-    						}
-    					});
-    					populateSelectedMsgs(_data);
-    				}
-    			},
-    			beforeSend: function( jqXHR, settings ){
-    				connector.showProgressBar();
-    			},
-    			complete: function( jqXHR, settings ){
-    				connector.hideProgressBar();
-    			}
-    		});
         }
 		proxy_mensagens.messages_list(current_folder,1,preferences.max_email_per_page,sort_box_type,search_box_type,sort_box_reverse,preferences.preview_msg_subject,preferences.preview_msg_tip,handler_draw_box);
@@ -917,7 +894,7 @@
 	if (document.getElementById("table_message_header_box_"+numBox).emptyBody)
 		return;
-    objCell.style.cursor = "col-resize"; 
-    $(objCell).next().css('cursor','col-resize'); 
- 
+    objCell.style.cursor = "col-resize";
+    $(objCell).next().css('cursor','col-resize');
+
 	if (objCell.style.cursor == "col-resize" && detectLeftButton(ev)) {
 		var cellIndex = objCell.cellIndex;
@@ -942,5 +919,5 @@
 
 		document.getElementById("table_message_ruler").style.left = cellOffset+cellWidth;
-        syncColumns(); 
+        syncColumns();
 	}
 	ev.returnValue = false;
@@ -1649,7 +1626,8 @@
                     $(".lower").css("top", ($("#content_folders").height()-18) + $("#content_folders").offset().top);
 					if($(".shared-folders").length){
-						$(".shared-folders").parent().find('.folder:not(".shared-folders")').droppable({
+						$(".shared-folders,.head_folder").parent().find('.folder:not(".shared-folders")').droppable({
 							over : function(a, b){						
 								//SETA BORDA EM VOLTA DA PASTA
+                                $(b.helper).find(".draggin-folder,.draggin-mail").css("color", "green");
 								over = $(this);
 								$(this).addClass("folder-over");
@@ -1664,6 +1642,7 @@
 										}
 							},
-							out : function(){
+							out : function(a,b){
 								//RETIRA BORDA EM VOLTA DA PASTA
+                                $(b.helper).find(".draggin-folder,.draggin-mail").css("color", "");
 								$(this).removeClass("folder-over");
 							},
@@ -1723,7 +1702,16 @@
 			
                         $(this).addClass("selected_msg");
-					}
-					updateSelectedMsgs($(this).find("input:checkbox").is(':checked'),$(this).attr("id"));
-				}
+                }
+                updateSelectedMsgs($(this).find("input:checkbox").is(':checked'),$(this).attr("id"));
+                } else if ( typeof $(event.target).attr("style") == "undefined" || $(event.target).attr("style").match(/background/g) == null ) {
+                    if($(this).find("input:checkbox").attr("checked") != "checked"){
+
+                        $(this).find("input:checkbox").trigger('click');
+            
+                        $(this).addClass("selected_msg");
+                    }
+                    updateSelectedMsgs($(this).find("input:checkbox").is(':checked'),$(this).attr("id"));
+                }
+
 			});
 	}
@@ -1739,8 +1727,5 @@
 	draw_footer_box(headers_msgs.num_msgs);
 	Element('main_table').style.display = '';
-	if(is_ie6)	  // Stupid Fixing on IE6.
-		setTimeout("resizeWindow()",1);
-	else
-		resizeWindow();
+	resizeWindow();
 	if(debug) {
 		var _eTime = new Date();
@@ -1752,9 +1737,9 @@
 	var msg_number = Element('msg_number').value;
 	if(!msg_folder && msg_number) {
-        if ((msg_number.toString().indexOf('@') != -1) || !msg_number.toString().match(/[0-9]/)){ 
-            new_message_to(msg_number); 
-        }     
-        else 
-            new_message('new','null'); 
+        if ((msg_number.toString().indexOf('@') != -1) || !msg_number.toString().match(/[0-9]/)){
+            new_message_to(msg_number);
+        }    
+        else
+            new_message('new','null');
 	}
 	else if(msg_folder && msg_number){
@@ -1871,16 +1856,16 @@
                     //if (headers_msgs.msg_sample.body.length > 0)
 				    tr_element.msg_sample = Base64.decode(headers_msgs.msg_sample.body).substr(0,180) + "..."; //trecho do body que sera exibido com o assunto; //blabla
-			     } else {
+			        tr_element.msg_sample = html_entities(tr_element.msg_sample); 
+                 } else {
 				    //if (headers_msgs.msg_sample.body.length > 0)
 					tr_element.msg_sample = Base64.decode(headers_msgs.msg_sample.body).substr(0,120) + "..."; //trecho do body que sera exibido com o assunto;
-		          }
-
-                // preferencia dos tooltips
-                if(headers_msgs.msg_sample && preferences.preview_msg_tip == "1" && headers_msgs.msg_sample.body !== "") {
-                    tr_element.tip = Base64.decode(headers_msgs.msg_sample.body).substr(3,300) + "..."; //trecho do body que sera exibido no tool-tip;
-                }
+		            tr_element.msg_sample = html_entities(tr_element.msg_sample);  
+                  }
             }
         }
-
+        // preferencia dos tooltips
+        if(headers_msgs.msg_sample && preferences.preview_msg_tip == "1" && headers_msgs.msg_sample.body !== "") {
+            tr_element.tip = Base64.decode(headers_msgs.msg_sample.body).substr(3,300) + "..."; //trecho do body que sera exibido no tool-tip;
+        }
 		
 		if ((headers_msgs.Unseen == 'U') || (headers_msgs.Recent == 'N')){
@@ -1925,5 +1910,5 @@
 
 		if ((headers_msgs.Forwarded == 'F')  || (headers_msgs.Draft == 'X' && headers_msgs.Answered == 'A')){
-			td_element21.onclick=function(){search_emails(headers_msgs.subject.replace(/^(re: ?|fw: ?|enc: ?|res: ?|fwd: ?)*/gi,''),true);};
+			$(td_element21).on('click',function(){search_emails(headers_msgs.subject.replace(/^(re: ?|fw: ?|enc: ?|res: ?|fwd: ?)*/gi,''),true);});
                         td_element21.innerHTML = "<img src ='templates/"+template+"/images/forwarded.png' title='"+get_lang('Forwarded')+"'>";
 			headers_msgs.Draft = ''
@@ -1934,5 +1919,5 @@
 			td_element21.innerHTML = "<img src ='templates/"+template+"/images/draft.png' title='"+get_lang('Draft')+"'>";
 		else if (headers_msgs.Answered == 'A'){
-                        td_element21.onclick=function(){search_emails(headers_msgs.subject.replace(/^(re: ?|fw: ?|enc: ?|res: ?|fwd: ?)*/gi,''),true);};
+                        $(td_element21).on('click',function(){search_emails(headers_msgs.subject.replace(/^(re: ?|fw: ?|enc: ?|res: ?|fwd: ?)*/gi,''),true);});
 			td_element21.innerHTML = "<img src ='templates/"+template+"/images/answered.png' title='"+get_lang('Answered')+"'>";
                     }else
@@ -2048,10 +2033,12 @@
 						this.title = title_to; 
 					};
-					if (headers_msgs.to && headers_msgs.to[0]) {
+					if (headers_msgs.to && headers_msgs.to[0] != null) {
 						if (headers_msgs.to[0].name != null){
 							spanSender.innerHTML += headers_msgs.to[0].name;
 						}else if(headers_msgs.to[0].email != null) {
 							spanSender.innerHTML += headers_msgs.to[0].email;
-						}
+						}else {
+                            spanSender.innerHTML += get_lang("without destination");
+                        }
 					}
 				}else if(headers_msgs.from !== undefined){
@@ -2139,5 +2126,16 @@
 		$(td_element26).click(function() {	
 			var messageClickedId = $(this).attr('id').match(/td_message_followup_([\d]+)/)[1];
-			
+
+            var loading = $('#td_message_followup_' + messageClickedId + ', ' + 
+            'tr[role="'+messageClickedId+'_'+msg_folder+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited")
+            .find('img[alt=Carregando]');
+
+
+            //Verificar se está carregando a bandeira.
+            //Caso esteja ele sai da função até que seja carregado. 
+            if( loading.length ) {
+                return false;
+            }
+
 			var followupColor = $('#td_message_followup_' + messageClickedId).find(".flag-edited").css('backgroundColor');
 			
@@ -2192,12 +2190,17 @@
 					
 					if(fail != 'success'){
-					    $('#td_message_followup_' + messageClickedId + ', ' + 
-					    'tr[role="'+messageClickedId+'_'+msg_folder+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited").css("background", "#CCCCCC")
-						.find('img').remove();
-					    MsgsCallbackFollowupflag[fail]();
+					    var msgFlag =  $('#td_message_followup_' + messageClickedId + ', ' + 
+                        'tr[role="'+messageClickedId+'_'+msg_folder+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited").css("background", "#CCCCCC");
+
+                        msgFlag.find('img').remove();
+                        
+                        //Insere a imagem da flag quando ocorre erro ao marcar a msg
+                        msgFlag.append("<img src='../prototype/modules/mail/img/flagEditor.png'/>");
+
+                        MsgsCallbackFollowupflag[fail]();
 					}else{
 					    $('#td_message_followup_' + messageClickedId + ', ' + 
 					    'tr[role="'+messageClickedId+'_'+msg_folder+'"] #td_message_followup_search_' + messageClickedId).attr('title', get_lang('Follow up')).find(".flag-edited").css("background", headers_msgs.followupflagged.backgroundColor)
-						.find('img').remove();
+						.append("<img src='../prototype/modules/mail/img/flagEditor.png'/>");
 					    updateCacheFollowupflag(messageClickedId, msg_folder, true);
 					}				
@@ -2215,5 +2218,4 @@
 					$('#td_message_followup_' + messageClickedId + ', ' + 
 					'tr[role="'+messageClickedId+'_'+msg_folder+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited")
-					.css({"background-image":"url(../prototype/modules/mail/img/flagEditor.png)"})
 					.find('img').remove();
 					
@@ -2222,6 +2224,6 @@
 				
 					$('#td_message_followup_' + messageClickedId + ', ' + 
-						'tr[role="'+messageClickedId+'_'+msg_folder+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited")
-                        .css({"background-image":"url(../prototype/modules/mail/img/flagEditor.png)"});
+						'tr[role="'+messageClickedId+'_'+msg_folder+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited").html('<img src="../prototype/modules/mail/img/flagEditor.png">')
+                        .css({"width":"8px","height":"6px"/*"background-image":"url(../prototype/modules/mail/img/flagEditor.png)"*/});
 				});	
 
@@ -2229,7 +2231,16 @@
 				$('#td_message_followup_' + messageClickedId + ', ' + 
 				'tr[role="'+messageClickedId+'_'+msg_folder+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited")
-				.css({"background-image":"url(../prototype/modules/mail/img/flagEditor.png)"}).css("background", followupColor);
+				.css("backgroundColor", followupColor)
+                .find('img').remove(); //remove imagem carregando da bandeira
+
+                $('#td_message_followup_' + messageClickedId).find('.flag-edited').append("<img src='../prototype/modules/mail/img/flagEditor.png'/>");
+
 				
-				$(tr_element).addClass('selected_msg').find(':checkbox').trigger('click');
+			   //Pega id do checkbox
+               var id = $(tr_element).addClass('selected_msg').find(':checkbox').attr('id');
+                
+                //Verifica se o checkbox está selecionado
+                if($('#' + id).attr('checked') != 'checked')
+                    $(tr_element).addClass('selected_msg').find(':checkbox').trigger('click');
 				
 				/**
@@ -2320,5 +2331,9 @@
 	var message_header = Element("message_header_"+search);
 	var handler_draw_box = function(data){
-		draw_box(data, current_folder,true);
+
+        if (typeof(clean_selected) == "undefined")
+            populateSelectedMsgs(data.messagesIds);
+
+        draw_box(data, current_folder,true);
 		//Mostrar as msgs nao lidas de acordo com o filtro de relevancia
         var msgs_unseen = 0;
@@ -2341,27 +2356,4 @@
 	sort_box_type = sort;
 	search_box_type = search;
-
-	if (typeof(clean_selected) == "undefined"){	
-        $.ajax({			
-			url: "controller.php?" + $.param( {action: "$this.imap_functions.getMessagesIds", 
-				folder: get_current_folder(),					
-				sort_box_type: "SORTARRIVAL", 
-				search_box_type: search_box_type,
-				sort_box_reverse: "1"
-				}),
-			success: function(data){
-				data = connector.unserialize(data);
-				if(data){
-					var _data = {};
-					$.each(data,function(index,value){
-						if (value){
-							_data[index] = value;
-						}
-					});
-					populateSelectedMsgs(_data);				
-				}
-			}
-		});
-	}	
 
 	proxy_mensagens.messages_list(current_folder,1,preferences.max_email_per_page,sort,search,sort_box_reverse,preferences.preview_msg_subject,preferences.preview_msg_tip,handler_draw_box);
@@ -2432,5 +2424,5 @@
 function draw_message(info_msg, ID){
 	// remove a flag $FilteredMessage da mensagem ao ser lida
-	if(info_msg.Unseen == "U"){
+	if(info_msg.Unseen == "U" && preferences['use_alert_filter_criteria'] == "1"){
 		$.each(fromRules, function(index, value) {
 			if(value == info_msg.msg_folder){
@@ -2479,8 +2471,8 @@
 			{
                 if(info_msg.msg_number.match("s[0-9]+")){
-                    var new_info = info_msg.msg_number;
-                    new_info = new_info.split("_")[1];
-                    info_msg.next_message = info_msg.next_message+"_"+new_info;
-                    info_msg.nextMsgBox = info_msg.nextMsgBox+"_"+new_info;
+                    var msg_next = $('#'+info_msg.msg_number).next();
+                    info_msg.next_message = msg_next.attr("id");
+                    info_msg.nextMsgBox = msg_next.attr("name");
+                    nextMsgBox = msg_next.attr("name");
                 }
 				currentTab = ID;
@@ -2489,5 +2481,6 @@
 				//select_msg('null', 'down', true);
 				if (!msg_selected){
-					select_msg('null', 'down', true);
+					if(!!parseInt(preferences.use_shortcuts))
+                        select_msg('null', 'down', true);
 					msg_selected = true;
 				}
@@ -2495,5 +2488,5 @@
 		}
 		/*Ultima mensagem de cada página, exceto a ultima*/
-        else if( (current_page < total_pages) ){
+        else if( (current_page < total_pages) && !info_msg.msg_number.match("s[0-9]+") ){
 		   
 		   img_next_msg.onclick = function()
@@ -2559,8 +2552,8 @@
 			{
                 if(info_msg.msg_number.match("s[0-9]+")){
-                    var new_info = info_msg.msg_number;
-                    new_info = new_info.split("_")[1];
-                    info_msg.prev_message = info_msg.prev_message+"_"+new_info;
-                    info_msg.previousMsgBox = info_msg.previousMsgBox+"_"+new_info;
+                    var msg_prev = $('#'+info_msg.msg_number).prev();
+                    info_msg.prev_message = msg_prev.attr("id");
+                    info_msg.previousMsgBox = msg_prev.attr("name");
+                    previousMsgBox = msg_prev.attr("name");
                 }
 				currentTab = ID;
@@ -2569,5 +2562,6 @@
 				//select_msg('null', 'up', false);
 				if (!msg_selected){
-					select_msg('null', 'up', true);
+                    if(!!parseInt(preferences.use_shortcuts))
+					    select_msg('null', 'up', true);
 					msg_selected = true;
 				}
@@ -3010,5 +3004,7 @@
 		var option_export = '<span onclick="proxy_mensagens.export_all_messages()" onmouseover="this.className=\'reply_options_active\'" onmouseout="this.className=\'reply_options\'" class="reply_options">'+get_lang("Export")+'</span> | ';
 		var report_error = '<span onmouseover="this.className=\'reply_options_active\'" onmouseout="this.className=\'reply_options\'" class="reply_options" onclick=reports_window("'+currentTab+'");>'+get_lang("Report error")+'</span> | '; 
-		div_other_more_options.innerHTML += option_move + option_print + option_export + block_user +  report_error;
+		// Opção do menu 'Mais Ações' para criar filtro a partir da mensagem aberta:  
+		var option_create_filter = '<span onmouseover="this.className=\'reply_options_active\'" onmouseout="this.className=\'reply_options\'" class="reply_options" onclick=filter_from_msg(onceOpenedHeadersMessages[\'' + html_entities(info_msg.msg_folder) + '\'][' + info_msg.msg_number + ']);>' + get_lang("Create filter from message") + '</span> | '; 
+		div_other_more_options.innerHTML += option_create_filter + option_move + option_print + option_export + block_user +  report_error;
 		
 		
@@ -3509,5 +3505,5 @@
 	subject.innerHTML = html_entities(info_msg.subject); 
 	subject.className = "header_message_field";
-	if(defaultCalendar == "expressoCalendar" && $("#expressoCalendarid")[0]){
+	if($("#expressoCalendarid")[0]){
 		var new_task_logo = document.createElement("IMG");
 		new_task_logo.title = "Criar uma nova tarefa a partir deste email.";
@@ -4644,24 +4640,17 @@
             delay : 300,
             minLength: 0
-        }).bind('catcompleteopen', function(event, ui) {
+        }).bind('autocompleteopen', function(event, ui) {
 
             $(this).data('is_open',true);
 
-        }).bind('catcompleteclose', function(event, ui) {
+        }).bind('autocompleteclose', function(event, ui) {
 
             canMakeBox = true;
             $(this).data('is_open',false);
-
+            $(this).blur().focus();
         }).data( "autocomplete" )._renderItem = function( ul, item ) {
             var autocomplete = $(this)[0].element;
 
-            //cálculo dinâmico da largura da lista
-            var minwidth = 450;
-            var width = (item.label ? item.label.length : (item.value ? item.value.length : (item.mail ? item.mail.length : 30 )));
-            width = (is_ie ? width*2 : (is_webkit && !is_mozilla ? width*4 : width*5)) + 30;
-            if (width < minwidth)
-                width = minwidth;
-
-            ul.css({"min-width":width, "max-height" : "180px", "overflow-y" : "auto", "min-height": "30px"});
+            ul.css({"width":'50%',"min-width":'600px', "max-height" : "180px", "overflow-y" : "auto", "min-height": "30px"});
 
             item.raty = ((item.number_of_messages*10)/topContact) > 1 ? ((item.number_of_messages*10)/topContact) : 1;
@@ -4753,4 +4742,132 @@
 			emQuickSearch(($(this).parents("tr:first").find("textarea").val() ? $(this).parents("tr:first").find("textarea").val() : input_search), "."+$(this).parents("tr:first").attr('class').split("-")[0], ID, undefined, true);
 	});
+}
+
+/* 
+	Anexa uma mensagem a mensagem sendo enviada. 
+	Parâmetros: 
+		folder_name: nome da pasta na qual a mensagem sendo anexada se encontra. 
+		message_number: id da mensagem sendo anexada. 
+*/ 
+function attach_message (folder_name, message_number) { 
+    var ID = currentTab; 
+    var fileUploadMSG = $('#fileupload_msg'+ID); 
+    fileUploadMSG.find(' .attachments-list').show(); 
+    var att = new Object(); 
+
+   
+
+    var attach = {}; 
+    attach.fileName = onceOpenedHeadersMessages[folder_name][message_number].subject + '.eml'; 
+    attach.fullFileName = onceOpenedHeadersMessages[folder_name][message_number].subject + '.eml'; 
+    if(attach.fileName.length > 20){ 
+        attach.fileName = attach.fileName.substr(0, 17) + "... " + attach.fileName.substr(attach.fileName.length - 9, attach.fileName.length); 
+    } 
+    attach.error = false; 
+    attach.OK = true;
+    if (folder_name.indexOf('local_messages_') == 0){
+        attach.fileSize = formatBytes(onceOpenedHeadersMessages[folder_name][message_number].size);
+    } else {
+        attach.fileSize = formatBytes(onceOpenedHeadersMessages[folder_name][message_number].Size); 
+    }
+    var upload = $(DataLayer.render("../prototype/modules/mail/templates/attachment_add_itemlist.ejs", { 
+        file: attach 
+    })); 
+    $("#content_id_" + currentTab + " .save").button("enable"); 
+    upload.find('.att-box-loading').remove(); 
+    upload.append('<input type="hidden" name="fileId[]" value=\'' + idATT + '\'/>'); 
+ 
+    upload.find('.att-box-delete').click(function() 
+    { 
+        $("#content_id_" + currentTab + " .save").button("enable"); 
+        var idAttach = $(this).parent().find('input[name="fileId[]"]').val(); 
+        fileUploadMSG.find(' .attachments-list').find('input[value="' + idAttach + '"]').remove(); 
+        delAttachment(ID, idAttach); 
+        $(this).parent().qtip("destroy"); 
+        $(this).parent().remove(); 
+        if(!fileUploadMSG.find(' .attachments-list').find(".att-box").length) 
+        { 
+            fileUploadMSG.find(' .attachments-list').hide(); 
+        } 
+    }); 
+ 
+    var addtip = function(attach){
+        fileUploadMSG.find('.attachments-list .att-box:last').qtip( 
+        { 
+            content: DataLayer.render("../prototype/modules/mail/templates/attachment_add_itemlist_tooltip.ejs", { 
+                attach: attach 
+            }), 
+            position: { 
+                corner: { 
+                    tooltip: 'bottomMiddle', 
+                    target: 'topMiddle' 
+                }, 
+                adjust: { 
+                    resize: true, 
+                    scroll: true 
+                } 
+            }, 
+            show: { 
+                when: 'mouseover', 
+                // Don't specify a show event 
+                ready: false // Show the tooltip when ready 
+            }, 
+            hide: 'mouseout', 
+            // Don't specify a hide event 
+            style: { 
+                border: { 
+                    width: 1, 
+                    radius: 5 
+                }, 
+                width: { 
+                    min: 75, 
+                    max: 1000 
+                }, 
+                padding: 5, 
+                textAlign: 'center', 
+                tip: true, 
+                // Give it a speech bubble tip with automatic corner detection 
+                name: 'blue' // Style it according to the preset 'cream' style 
+            } 
+        }); 
+    } 
+
+    if(folder_name.indexOf("local_messages_") != 0)
+    {
+        att.folder = folder_name; 
+        att.uid = message_number; 
+        att.type = 'imapMSG'; 
+        att.name = Base64.encode(onceOpenedHeadersMessages[folder_name][message_number].subject + '.eml'); 
+        var idATT = JSON.stringify(att); 
+        addAttachment(ID, idATT); 
+
+        fileUploadMSG.find('.attachments-list').append(upload);
+        addtip(attach);
+    }
+    else
+    {
+        var folder_trash = "INBOX"+cyrus_delimiter+special_folders["Trash"];
+        expresso_mail_archive.unarchieveToAttach(folder_name, folder_trash, message_number, function(data){
+            $.ajax({
+                url: "controller.php?action=$this.imap_functions.get_info_msg_archiver",
+                data:  {"idMsgs":data.idsMsg},
+                type: 'POST',
+                async: false,
+                success: function(data){
+                    data = JSON.parse(connector.unserialize(data));
+                    data = data[0];
+                    att.folder = folder_trash;
+                    att.uid = data.uid; 
+                    att.type = 'imapMSG'; 
+                    att.name = Base64.encode(onceOpenedHeadersMessages[folder_name][message_number].subject + '.eml'); 
+                    var idATT = JSON.stringify(att); 
+                    addAttachment(ID, idATT);
+                    fileUploadMSG.find('.attachments-list').append(upload);
+                    addtip(attach);
+                },
+            });
+        }); 
+    }
+    upload.find('.att-box-loading').remove();     
 }
 		
@@ -4933,9 +5050,7 @@
     	$(this).prev().show();
 	});
-	fileUploadMSG.find(".fileUploadButton, .message-attach-link").button().filter(".fileUploadButton").click(function(){
-            fileUploadMSG.find("input:file").trigger("click");
-    });
-
-    fileUploadMSG.find("input:file").fileupload({
+
+
+    fileUploadMSG.find(".button").button().filter(".fileinput-button").find(".ui-button-text").css("margin-top","2px").find("input:file").fileupload({
 		//singleFileUploads : true,fileUploadMSG
 		sequentialUploads: true, 
@@ -5113,11 +5228,15 @@
             });
         }*/
-	});/*.css({
-		"height" : "20px", 
-		"width": (is_webkit ? "205px" : "100px"), 
-		"border-width": "0 0 0px 0px", 
-        "-moz-transform" : "rotate(-180deg) translate(5px, -0.5px) scale(1.1)",  
-        "-webkit-transform" : "rotate(-180deg) translate(0px, 0px)"
-	}).end().end().end().*/
+	}).css({
+        "height" : ($.browser.mozilla ? "15px" : "20px"), 
+        // "width": (is_webkit ? "205px" : "100px"),
+        "width" : "205px",
+        "margin-top" : ($.browser.mozilla ? "10px" : "0"),
+        "margin-right" : (is_mozilla ? "30px" : "0"),
+        "border-width": "0 0 0px 0px", 
+        "transform" : "rotate(-360deg) translate(5px, -0.5px) scale(1.1)",  
+        "-webkit-transform" : "rotate(-360deg) translate(0px, 0px)"
+	});/*.end().end().end().*/
+
     fileUploadMSG.find(".message-attach-link").click(function(){
 		jQuery('#message-attach-dialog').html(DataLayer.render("../prototype/modules/attach_message/attach_message.ejs", {}));
@@ -5149,74 +5268,7 @@
 				jQuery.each(selectedMessages[folder_name], function(message_number, message) { 
 					if (message) {
-						fileUploadMSG.find(' .attachments-list').show();	
-						var att = new Object();
-						att.folder = folder_name;
-						att.uid = message_number;
-						att.type = 'imapMSG';
-						att.name = Base64.encode(onceOpenedMessages[folder_name][message_number].subject + '.eml');
-						var idATT = JSON.stringify(att);
-						addAttachment( ID , idATT);                        
-						var attach = {};
-						attach.fileName = onceOpenedMessages[folder_name][message_number].subject + '.eml';
-						attach.fullFileName = onceOpenedMessages[folder_name][message_number].subject + '.eml';
-						if(attach.fileName.length > 20)
-							attach.fileName = attach.fileName.substr(0, 17) + "... " + attach.fileName.substr(attach.fileName.length-9, attach.fileName.length);
-
-						attach.error = false;
-                        attach.OK = true;
-						attach.fileSize = formatBytes(onceOpenedMessages[folder_name][message_number].size);
-						var upload = $(DataLayer.render("../prototype/modules/mail/templates/attachment_add_itemlist.ejs", {file : attach}));
-						$("#content_id_"+currentTab+" .save").button("enable");
-                        upload.find('.att-box-loading').remove();
-						upload.append('<input type="hidden" name="fileId[]" value=\''+idATT+'\'/>');
-						
-						upload.find('.att-box-delete').click(function(){
-                            $("#content_id_"+currentTab+" .save").button("enable");
-							var idAttach = $(this).parent().find('input[name="fileId[]"]').val();
-							fileUploadMSG.find(' .attachments-list').find('input[value="'+idAttach+'"]').remove();
-							delAttachment(ID,idAttach); 
-							$(this).parent().qtip("destroy");
-							$(this).parent().remove();
-							if(!fileUploadMSG.find(' .attachments-list').find(".att-box").length){
-								fileUploadMSG.find(' .attachments-list').hide();
-							}
-						});	
-							
-						fileUploadMSG.find('.attachments-list').append(upload);
-
-						upload.find('.att-box-loading').remove();
-
-						fileUploadMSG.find('.attachments-list .att-box:last').qtip({
-		                	content: DataLayer.render("../prototype/modules/mail/templates/attachment_add_itemlist_tooltip.ejs", {attach : attach}),
-							position: {
-								corner: {
-									tooltip: 'bottomMiddle',
-									target: 'topMiddle'
-								},
-								adjust: {
-					               resize: true,
-					               scroll: true
-					            }
-							},
-							show: {
-								when: 'mouseover', // Don't specify a show event
-								ready: false // Show the tooltip when ready
-							},
-							hide: 'mouseout', // Don't specify a hide event
-							style: {
-								border: {
-									width: 1,
-									radius: 5
-								},
-								width: {
-									 min: 75,
-									 max : 1000
-								},
-								padding: 5, 
-								textAlign: 'center',
-								tip: true, // Give it a speech bubble tip with automatic corner detection
-								name: 'blue' // Style it according to the preset 'cream' style
-							}
-		                });
+						/* Anexa a mensagem especificada (por folder e id_msg) 
+						   na mensagem sendo criada.*/
+						attach_message(folder_name, message_number);
 					}
 				});
@@ -5781,13 +5833,13 @@
 }
 
-function verifyContext(type) { 
-    var folderN = $(".menu-sel").attr("role") ? $(".menu-sel").attr("role") : get_current_folder(); 
-    if(type == "unarchive"){ 
-        expresso_mail_archive.unarchieve(folderN, null, null); 
-    } else { 
-        archive_msgs(folderN,null,null) 
-    } 
-} 
- 
+function verifyContext(type) {
+    var folderN = $(".menu-sel").attr("role") ? $(".menu-sel").attr("role") : get_current_folder();
+    if(type == "unarchive"){
+        expresso_mail_archive.unarchieve(folderN, null, null);
+    } else {
+        archive_msgs(folderN,null,null)
+    }
+}
+
 function draw_footer_box(num_msgs){
 	folder = get_current_folder();
@@ -5815,5 +5867,5 @@
 		((expresso_offline)?" ":'<span class="message_options_import"><span ' + change_font_color + ' title="'+get_lang("Import")+'" class="message_options" onclick="import_window()">'+get_lang("Import")+'</span></span>');
 
-     
+    
     //Link arquivar e desarquivar com ação
     //MAILARCHIVER
Index: branches/2.5/expressoMail1_2/js/doiMenuData.js
===================================================================
--- branches/2.5/expressoMail1_2/js/doiMenuData.js	(revision 8127)
+++ branches/2.5/expressoMail1_2/js/doiMenuData.js	(revision 8232)
@@ -142,10 +142,11 @@
     function loadMenu(){
         var archive = "";
-        if(use_local_messages != 0){
-            archive = {"name": get_lang("Archive"), "icon": "archive", callback: function(key, opt){ proxy_mensagens.archive_message('inbox', 'get_selected_messages'); }}
-        }else{
-            archive = "";
+
+        if( preferences['use_followupflags_and_labels'] == "1" )
+            var labelItems = getLabels();
+
+        var revertSortBox = function(){
+            if (search_box_type == "UNSEEN") sort_box_reverse = sort_box_reverse ? 0 : 1; 
         }
-    	var labelItems = getLabels();
 
     	$.contextMenu({
@@ -156,28 +157,51 @@
                     return true;
                 }
-                if( current.indexOf("local") == -1){ 
-                    archive = {"name": get_lang("Archive"), "icon": "archive", callback: function(key, opt){ proxy_mensagens.archive_message(get_current_folder(), 'get_selected_messages'); }} 
-                    
-                } else { 
-                    archive = {"name": get_lang("Unarchive"), "icon": "archive", callback: function(key, opt){ proxy_mensagens.unarchive_message(get_current_folder(), 'get_selected_messages'); }} 
-                }
-                var itensNotLocal = {
-                    "label": { "name": get_lang("Labels"), "items": labelItems},
-                    "follouwpflag":{"name": get_lang("Follow up"), callback: function(key, opt){ configureFollowupflag(); } },
-                    "sep2": "---------"
-                }
+                if(use_local_messages != 0){
+                    if( current.indexOf("local") != -1){
+                       archive = {"name": get_lang("Unarchive"), "icon": "archive", callback: function(key, opt){ proxy_mensagens.unarchive_message('inbox', 'get_selected_messages'); }}
+                    } else {
+                        archive = {"name": get_lang("Archive"), "icon": "archive", callback: function(key, opt){ proxy_mensagens.unarchive_message('inbox', 'get_selected_messages'); }}
+                    }
+                }
+
+                if( preferences['use_followupflags_and_labels'] == "1" )
+                    var itensNotLocal = {
+                        "label": { "name": get_lang("Labels"), "items": labelItems},
+                        "follouwpflag":{"name": get_lang("Follow up"), callback: function(key, opt){ configureFollowupflag(); } },
+                        "sep2": "---------"
+                    }
 
                 var items= {
-                    "flagSeen":      {"name": get_lang("Mark as") + " " + get_lang('seen'), "icon": "seen", callback: function(key, opt){ proxy_mensagens.proxy_set_messages_flag('seen','get_selected_messages'); }},
-                    "flagUnseen":    {"name": get_lang("Mark as") + " " + get_lang('unseen'), "icon": "unseen", callback: function(key, opt){ proxy_mensagens.proxy_set_messages_flag('unseen','get_selected_messages'); }},
-                    "flagFlagged":   {"name": get_lang("Mark as") + " " + get_lang('important'), "icon": "important", callback: function(key, opt){ proxy_mensagens.proxy_set_messages_flag('flagged','get_selected_messages'); }},
-                    "flagUnflagged": {"name": get_lang("Mark as") + " " + get_lang('normal'), callback: function(key, opt){ proxy_mensagens.proxy_set_messages_flag('unflagged','get_selected_messages'); }},
+                    "flagSeen":      {"name": get_lang("Mark as") + " " + get_lang('seen'), "icon": "seen", callback: function(key, opt){ revertSortBox(); proxy_mensagens.proxy_set_messages_flag('seen','get_selected_messages'); }},
+                    "flagUnseen":    {"name": get_lang("Mark as") + " " + get_lang('unseen'), "icon": "unseen", callback: function(key, opt){ revertSortBox(); proxy_mensagens.proxy_set_messages_flag('unseen','get_selected_messages'); }},
+                    "flagFlagged":   {"name": get_lang("Mark as") + " " + get_lang('important'), "icon": "important", callback: function(key, opt){ revertSortBox(); proxy_mensagens.proxy_set_messages_flag('flagged','get_selected_messages'); }},
+                    "flagUnflagged": {"name": get_lang("Mark as") + " " + get_lang('normal'), callback: function(key, opt){ revertSortBox(); proxy_mensagens.proxy_set_messages_flag('unflagged','get_selected_messages'); }},
                     "sep1": "---------"
                 }
-
+				
+				// Desabilita a opção de criar filtro a partir da mensagem, caso mais de uma mensagem esteja selecionada: 
+				var is_filterFromMsg_disabled = function () { 
+					var base_selector = ".table_box tbody tr.selected_msg"; 
+					return ($(base_selector).length > 1) || ($(base_selector + " td span").text().indexOf(get_lang("Draft")) > -1); 
+				} 
+				
                 var lastItens = {
                     "move": {"name": get_lang("Move to")+"...", "icon": "move", callback: function(key, opt){ wfolders.makeWindow('', 'move_to'); }},
                     "remove": {"name": get_lang("Delete"),      "icon": "delete", callback: function(key, opt){ proxy_mensagens.delete_msgs('null','selected','null'); }},
                     "export": {"name": get_lang("Export"),      "icon": "export", callback: function(key, opt){ proxy_mensagens.export_all_messages(); }},
+					/*Abre o diálogo de criação de filtro a partir da mensagem:*/ 
+					"filterFromMsg": { 
+						"name": get_lang("Create filter from message"),  
+						"icon": "filter",  
+						callback: function (key, opt) { 
+							var msg_number = get_selected_messages(); 
+							var msg = onceOpenedHeadersMessages[current_folder][msg_number]; 
+							if (msg !== undefined) 
+							{ 
+								filter_from_msg(msg); 
+							} 
+						}, 
+						disabled: is_filterFromMsg_disabled() 
+					}, 
                     "archive": archive
                 }
@@ -318,6 +342,6 @@
     	} else {
             var labeleds =  (messageInfo.forceIcon ? messageInfo.labels : DataLayer.get('labeled', {
-    			criteria: {deepness: '2'},
-    			filter: [
+    			criteria: {deepness: 2},
+                filter: [
     				'AND',
     				['=', 'folderName', msg_folder], 
@@ -337,5 +361,5 @@
 
                 for (var i=0; i < labeleds.length; i++){
-                    menuItems[ labeleds[i].id ? labeleds[i].id : labeleds[i].label.id] = labeleds[i].id ? labeleds[i] : labeleds[i].label;
+                    menuItems[ (labeleds[i].id ? labeleds[i].id : labeleds[i].label.id) ] = labeleds[i].label ? labeleds[i].label : labeleds[i];
                 }
     		} else {
@@ -351,4 +375,6 @@
     		menuItensLabel[index] = {type: "label", customName: menuItems[index].name, id: msg_folder+"/"+msg_number+"#"+index};		
     	}
+
+
     	$.contextMenu.types.label = function(item, opt, root) {
             $('<span>'+item.customName+'</span><span class="removeLabeled" title="'+get_lang("Remove Label")+'">x</span>')
Index: branches/2.5/expressoMail1_2/js/rich_text_editor.js
===================================================================
--- branches/2.5/expressoMail1_2/js/rich_text_editor.js	(revision 8166)
+++ branches/2.5/expressoMail1_2/js/rich_text_editor.js	(revision 8232)
@@ -130,6 +130,6 @@
 cRichTextEditor.prototype.getSignaturesOptions = function() {
 	
-        if(RichTextEditor.signatures !== false)
-            return RichTextEditor.signatures;
+    if(RichTextEditor.signatures !== false)
+        return RichTextEditor.signatures;
                 
    	var signatures = RichTextEditor.normalizerSignature(this.fromJSON( preferences.signatures ));
@@ -138,52 +138,55 @@
 	for( key in signatures )
 	    if( !signature_types[key] )
-		signatures[key] = signatures[key].replace( /\n/g, "<br>" );
-                 
-        RichTextEditor.signatures = signatures;
-        return signatures;
-
-}
-cRichTextEditor.prototype.normalizerSignature = function(values) { 
-	var value = {};  
-	for (key in values){ 
-		value[RichTextEditor.isEncoded64(key) ? RichTextEditor.decode64(key) : key] = values[key]; 
-  	} 
- 	return value;
-
-} 
- 
-/*Verifica se a string input esta em Base64*/ 
-cRichTextEditor.prototype.isEncoded64 = function(input){ 
-var baseStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; 
-var encoded = true; 
-        if ( (input.length % 4) != 0) 
-                return false; 
-        for(var i=0; i<input.length; i++){ 
-                if ( baseStr.indexOf(input[i]) < 0 ){ 
-                        encoded = false; 
-                        break; 
-                } 
-        } 
-        return encoded; 
+		    signatures[key] = signatures[key].replace( /\n/g, "<br>" );
+
+    RichTextEditor.signatures = signatures;
+    return signatures;
+
+}
+cRichTextEditor.prototype.normalizerSignature = function(values) {
+
+    var value = {};
+
+    for (key in values){
+
+        value[RichTextEditor.isEncoded64(key) ? RichTextEditor.decode64(key) : key] = values[key];
+    }
+
+    return value;
+
+}
+
+/*Verifica se a string input esta em Base64*/
+cRichTextEditor.prototype.isEncoded64 = function(input){
+var baseStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
+var encoded = true;
+	if ( (input.length % 4) != 0)
+		return false;
+	for(var i=0; i<input.length; i++){
+		if ( baseStr.indexOf(input[i]) < 0 ){
+			encoded = false;
+			break;
+		}
+	}
+	return encoded;
 }
 
 cRichTextEditor.prototype.getSignatureDefault = function() {
-	 
-        if(RichTextEditor.signatures === false){
-            RichTextEditor.signatures = RichTextEditor.getSignaturesOptions();
-            preferences.signature_default = preferences.signature;
-        }     
+
+    if(RichTextEditor.signatures === false){
+        RichTextEditor.signatures = RichTextEditor.getSignaturesOptions();
+        preferences.signature_default = preferences.signature;
+    }
          
-        if(!RichTextEditor.signatures || !preferences.signature_default) 
-	{
-          preferences.use_signature = "0"; //Desabilita o uso da assinatura
-          return '';
-        } 
-        if (RichTextEditor.isEncoded64(preferences.signature_default)) 
-                preferences.signature_default = RichTextEditor.decode64(preferences.signature_default); 
-        return unescape(preferences.signature_default);
-
-}
-
+    if(!RichTextEditor.signatures || !preferences.signature_default)
+    {
+      preferences.use_signature = "0"; //Desabilita o uso da assinatura
+      return '';
+    }
+	if (RichTextEditor.isEncoded64(preferences.signature_default))
+		preferences.signature_default = RichTextEditor.decode64(preferences.signature_default);
+    return unescape(preferences.signature_default);
+
+}
 
 
@@ -216,5 +219,5 @@
 	{
             autoSaveControl.status[id] = true;
-            autoSaveControl.timer[id] = window.setInterval( "autoSave("+id+")" ,autosave_time);  
+            autoSaveControl.timer[id] = window.setInterval( "autoSave(\""+id+"\")" ,autosave_time);  
 
             CKEDITOR.instances[inst].document.on('keydown', function(event){   
