Index: trunk/expressoMail1_2/index.php
===================================================================
--- trunk/expressoMail1_2/index.php	(revision 7110)
+++ trunk/expressoMail1_2/index.php	(revision 7414)
@@ -348,5 +348,42 @@
     // End Set Imap Folder names options
 	//User info
-	echo "<script language='javascript'> var account_id = ".$GLOBALS['phpgw_info']['user']['account_id'].";var expresso_offline = false;</script>";
+    echo "<script language='javascript'> var account_id = ".$GLOBALS['phpgw_info']['user']['account_id'].";var expresso_offline = false; var mail_archive_host = '127.0.0.1';</script>\n";
+        
+    //MAILARCHIVER-02
+    //todo: remover a linha abaixo e implementar a configuração
+    //$GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['use_local_messages'] = true;
+        if ( $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['use_local_messages'] == true ) {
+        $mail_archiver_host = '127.0.0.1';
+        //Check protocol in use (https or http)
+        if($_SERVER['HTTPS'] != 'on'){
+            $mail_archiver_protocol = "http";
+            $mail_archiver_port = "4333";
+        }
+        else{
+            $mail_archiver_protocol = "https";
+            $mail_archiver_port = "4334";
+        }
+    
+        //JS Variables (to add on jscripts variables, needed by dependence scripts following)
+        echo '<script type="text/javascript">var mail_archive_protocol="'.$mail_archiver_protocol.'"; var mail_archive_port="'.$mail_archiver_port.'";</script>';
+    
+        //CXF custom js files, from MailArchiver ArcServUtil JS files repository, intended to be running already: CORS support and custom TRANSPORT object
+        echo '<script type="text/javascript" src="'.$mail_archiver_protocol.'://'.$mail_archiver_host.':'.$mail_archiver_port.'/arcservutil/cxf-addon-xdr-adapter.js"></script>';
+        echo '<script type="text/javascript" src="'.$mail_archiver_protocol.'://'.$mail_archiver_host.':'.$mail_archiver_port.'/arcservutil/cxf-addon-cors-request-object.js"></script>';
+        echo '<script type="text/javascript" src="'.$mail_archiver_protocol.'://'.$mail_archiver_host.':'.$mail_archiver_port.'/arcservutil/cxf-addon-cors-utils.js"></script>';
+
+        //CXF UTILS MAIN FILE
+        echo '<script type="text/javascript" src="'.$mail_archiver_protocol.'://'.$mail_archiver_host.':'.$mail_archiver_port.'/arcserv/ArchiveServices?js&nojsutils"></script>';
+    
+        //QueryConfig add on
+        echo '<script src="js/MAQueryConfig.js?'.$update_version.'"></script>';        
+        //Expresso serialized format add on
+        echo '<script src="js/MAExpressoPattern.js?'.$update_version.'"></script>';        
+    
+        //echo $obj -> getFilesJs("js/mail_archiver.js," . $GLOBALS['phpgw_info']['flags']['update_version']);
+        echo '<script src="js/mail_archiver.js?'.$update_version.'"></script>';
+    
+    }
+	//echo "<script language='javascript'> var account_id = ".$GLOBALS['phpgw_info']['user']['account_id'].";var expresso_offline = false;</script>";
 
 	$obj = createobject("expressoMail1_2.functions");
@@ -376,5 +413,5 @@
 		$scripts .= "js/shortcut.js,";
 	}
-				
+	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,";
Index: trunk/expressoMail1_2/templates/default/main.css
===================================================================
--- trunk/expressoMail1_2/templates/default/main.css	(revision 7398)
+++ trunk/expressoMail1_2/templates/default/main.css	(revision 7414)
@@ -130,4 +130,6 @@
 .context-menu-item.icon-delete-box{ background-image: url(images/user_delete.png); }
 .context-menu-item.icon-quick-search-contact{ background-image: url(images/zoom.png); }
+/* Airton. Adicionando o ícone da opção de arquivar do menu de contexto do expressoMail */
+.context-menu-item.icon-archive{ background-image: url(images/archive.png); }
 
 
@@ -1586,2 +1588,23 @@
 	cursor: text;
 }
+
+/* Mail Archive */
+.local-folder {
+
+}
+
+.local-connect {
+ 	width: 16px;
+	height: 16px;
+	background: url("images/connect_delete.gif") no-repeat;
+	display: inline-block;
+	cursor: pointer;
+}
+
+.local-admin {
+	width: 16px;
+	height: 16px;
+	background: url("images/config.png") no-repeat;
+	display: inline-block;
+	cursor: pointer;
+}
Index: trunk/expressoMail1_2/setup/phpgw_pt-br.lang
===================================================================
--- trunk/expressoMail1_2/setup/phpgw_pt-br.lang	(revision 7354)
+++ trunk/expressoMail1_2/setup/phpgw_pt-br.lang	(revision 7414)
@@ -937,3 +937,19 @@
 One of his messages can not be marked as read, because it contains a read confirmation.	expressoMail1_2	pt-br	Uma de suas mensagens não pode ser marcada como lida, pois contém uma confirmação de leitura.
  of its messages could not be marked as read, because it contains a read confirmation.	expressoMail1_2	pt-br	 de suas mensagens não puderam ser marcadas como lida, pois contém uma confirmação de leitura.
-Cant share with yourself.	expressoMail1_2	pt-br	Não é possível compartilhar com você mesmo. 
+Cant share with yourself.	expressoMail1_2	pt-br	Não é possível compartilhar com você mesmo.
+You can not remove the message with the preference 'Send to Trash' enabled. There is no permission to move messages to the trash folder.	expressoMail1_2	pt-br	Não é possível remover a mensagem com a preferencia 'Enviar para lixeira' ativada. Não existe permissão para mover mensagens para a pasta lixeira.
+Moving message %1 of %2	expressoMail1_2	pt-br	Movendo mensagem %1 de %2
+All done. Message(s) moved successfully	expressoMail1_2	pt-br	Concluído. Mensagem(ns) movida(s) com sucesso.
+Starting to move messages	expressoMail1_2	pt-br	Iniciando a movimentação de mensagens
+MailArchiver does not seems to be running or installed at this workstation, local messages are disabled. Check it out!	expressoMail1_2	pt-br	O MailArchiver não parece estar rodando ou instalado nesta estação de trabalho, as mensagens locais estão desativadas. Verifique!
+Starting to unarchive messages	expressoMail1_2	pt-br	Iniciando o desarquivamento de mensagens
+Messages successfully unarchived	expressoMail1_2	pt-br	Mensagens desarquivadas com sucesso
+All done. End of archive messages operation	expressoMail1_2	pt-br	Concluído. Operação de arquivamento encerrada
+No messages were unarchived	expressoMail1_2	pt-br	Nenhuma mensagem foi desarquivada
+Some messages weren't successfully unarchived	expressoMail1_2	pt-br	Algumas mensagens não puderam ser desarquivadas
+Coudn't unarchive message	expressoMail1_2	pt-br	Não foi possível desarquivar mensagem
+Message successfully unarchived	expressoMail1_2	pt-br	Mensagem desarquivada com sucesso
+Unarchiving message %1 of %2	expressoMail1_2	pt-br	Desarquivando mensagem %1 de %2
+Message %1 of %2 successfully archived	expressoMail1_2	pt-br	Mensagem %1 de %2 arquivada com sucesso
+Sorry, but Mail Archiver does not seems to be running or installed at this workstation. By now, we are turning off local messages!	expressoMail1_2	pt-br	Desculpe, mas o Mail Archiver não parece estar rodando ou instalado nesta estação de trabalho. De momento, estamos desativando as mensagens locais!
+Sorry, but Mail Archiver still seems to be sleeping. Check out your system services!	expressoMail1_2	pt-br	Desculpe, mas o Mail Archiver parece continuar offline. Verifique os serviços do seu sistema!
Index: trunk/expressoMail1_2/inc/class.imap_functions.inc.php
===================================================================
--- trunk/expressoMail1_2/inc/class.imap_functions.inc.php	(revision 7413)
+++ trunk/expressoMail1_2/inc/class.imap_functions.inc.php	(revision 7414)
@@ -3163,4 +3163,5 @@
                 $mailService->addHeaderField('Disposition-Notification-To', $_SESSION['phpgw_info']['expressomail']['user']['email']);
 
+            $mailService->addHeaderField('Date', date("r"));
 
             if ($folder != 'null') {
@@ -4660,5 +4661,5 @@
 
     function insert_email($source,$folder,$timestamp,$flags){
-		
+
         $username = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
         $password = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
@@ -4667,46 +4668,63 @@
         $imap_options = '/notls/novalidate-cert';
 
-	
         $folder = mb_convert_encoding( $folder, "UTF7-IMAP","ISO-8859-1");
-
         $mbox_stream = imap_open("{".$imap_server.":".$imap_port.$imap_options."}".$folder, $username, $password);
         
         if(imap_last_error() === 'Mailbox already exists')
             imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}".$folder));
+
         if($timestamp){
-			$pdate = date_parse(date('r')); // pega a data atual do servidor (TODO: pegar a data da mensagem local) 
-			$timestamp += $pdate['zone']*(60); //converte a data da mensagem para o fuso horário GMT 0. Isto é feito devido ao Expresso Mail armazenar a data no fuso horário GMT 0 e para exibi-la converte ela para o fuso horário local. 
-			/* TODO: o diretorio /tmp deve ser substituido pelo diretorio temporario configurado no setup */ 
-			$file = "/tmp/sess_".$_SESSION[ 'phpgw_session' ][ 'session_id' ]; 
-		
-    		$f = fopen($file,"w");
-        	fputs($f,base64_encode($source));
-            fclose($f);
-            $command = "python ".dirname(__FILE__)."/../imap.py \"$imap_server\" \"$imap_port\" \"$username\" \"$password\" \"$timestamp\" \"$folder\" \"$file\"";
-            $return['command']= exec($command);
+            if(version_compare(PHP_VERSION, '5.3.2', '>=')){
+                $return['append'] = imap_append($mbox_stream, "{".$imap_server.":".$imap_port."}".mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1"), $source,'',date('d-M-Y H:i:s O',$timestamp));
+            }else{
+				$pdate = date_parse(date('r')); // pega a data atual do servidor (TODO: pegar a data da mensagem local) 
+				$timestamp += $pdate['zone']*(60); //converte a data da mensagem para o fuso horário GMT 0. Isto é feito devido ao Expresso Mail armazenar a data no fuso horário GMT 0 e para exibi-la converte ela para o fuso horário local. 
+				/* TODO: o diretorio /tmp deve ser substituido pelo diretorio temporario configurado no setup */ 
+				$file = "/tmp/sess_".$_SESSION[ 'phpgw_session' ][ 'session_id' ]; 
+			
+	    		$f = fopen($file,"w");
+	        	fputs($f,base64_encode($source));
+	            fclose($f);
+	            $command = "python ".dirname(__FILE__)."/../imap.py \"$imap_server\" \"$imap_port\" \"$username\" \"$password\" \"$timestamp\" \"$folder\" \"$file\"";
+	            $return['command']= exec($command);
+	        }
         }else{
             $return['append'] = imap_append($mbox_stream, "{".$imap_server.":".$imap_port."}".$folder, $source, "\\Seen");
         }
+
+        if (!empty($return['command']))
+        {
+            list ($result, $msg) = explode(':',$return['command']);
+            if (strtoupper($result) === 'NO')
+            {
+                $return['error'] = $msg;
+                return $return;
+            }
+        }
+
         $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
 			
         $return['msg_no'] = $status->uidnext - 1;
-	$return['error'] = imap_last_error();
-	if(!$return['error'] && $flags != '' ){
-
-                  $flags_array=explode(':',$flags);
-                  //"Answered","Draft","Flagged","Unseen"
-                  $flags_fixed = "";
-                  if($flags_array[0] == 'A')
-                        $flags_fixed.="\\Answered ";
-                  if($flags_array[1] == 'X')
-                        $flags_fixed.="\\Draft ";
-                  if($flags_array[2] == 'F')
-                        $flags_fixed.="\\Flagged ";
-                  if($flags_array[3] != 'U')
-                        $flags_fixed.="\\Seen ";
-                  if($flags_array[4] == 'F')
-                        $flags_fixed.="\\Answered \\Draft ";
-                  imap_setflag_full($mbox_stream, $return['msg_no'], $flags_fixed, ST_UID);
-                }
+		
+        $return['error'] = '';
+		if(imap_last_error() && imap_last_error() != "SECURITY PROBLEM: insecure server advertised AUTH=PLAIN")
+            $return['error'] = imap_last_error();
+
+		if(!$return['error'] && $flags != '' ){
+			$flags_array=explode(':',$flags);
+			//"Answered","Draft","Flagged","Unseen"
+			$flags_fixed = "";
+			if($flags_array[0] == 'A')
+			    $flags_fixed.="\\Answered ";
+			if($flags_array[1] == 'X')
+			    $flags_fixed.="\\Draft ";
+			if($flags_array[2] == 'F')
+			    $flags_fixed.="\\Flagged ";
+			if($flags_array[3] != 'U')
+			    $flags_fixed.="\\Seen ";
+			if($flags_array[4] == 'F')
+			    $flags_fixed.="\\Answered \\Draft ";
+			imap_setflag_full($mbox_stream, $return['msg_no'], $flags_fixed, ST_UID);
+		}
 	
         //Ignorando erro de AUTH=Plain
@@ -4773,47 +4791,80 @@
 
     function treat_base64_from_post($source){
-            $offset = 0;
-            do
+    	$source = preg_replace('/(?<!\r)\n/', "\r\n", $source);
+
+        $offset = 0;
+        do
+        {
+            if($inicio = strpos($source, 'Content-Transfer-Encoding: base64', $offset))
             {
-                    if($inicio = strpos($source, 'Content-Transfer-Encoding: base64', $offset))
-                    {
-                            $inicio = strpos($source, "\n\r", $inicio);
-                            $fim = strpos($source, '--', $inicio);
-                            if(!$fim)
-                                    $fim = strpos($source,"\n\r", $inicio);
-                            $length = $fim-$inicio;
-                            $parte = substr( $source,$inicio,$length-1);
-                            $parte = str_replace(" ", "+", $parte);
-                            $source = substr_replace($source, $parte, $inicio, $length-1);
-                    }
-                    if($offset > $inicio)
-                    $offset=FALSE;
-                    else
-                    $offset = $inicio;
+                    $inicio = strpos($source, "\n\r", $inicio);
+                    $fim = strpos($source, '--', $inicio);
+                    if(!$fim)
+                            $fim = strpos($source,"\n\r", $inicio);
+                    $length = $fim-$inicio;
+                    $parte = substr( $source,$inicio,$length-1);
+                    $parte = str_replace(" ", "+", $parte);
+                    $source = substr_replace($source, $parte, $inicio, $length-1);
             }
-            while($offset);
-            return $source;
+            if($offset > $inicio)
+            $offset=FALSE;
+            else
+            $offset = $inicio;
+        }
+        while($offset);
+        return $source;
     }
 
-//Por Bruno Costa(bruno.vieira-costa@serpro.gov.br - Recebe os fontes dos emails a serem desarquivados, separa e envia cada um para função insert_mail.
+	//Por Bruno Costa(bruno.vieira-costa@serpro.gov.br - Recebe os fontes dos emails a serem desarquivados, separa e envia cada um para função insert_mail.
 
     function unarchive_mail($params)
-    {		
-        $dest_folder = $params['folder'];
+    {	
+        $dest_folder = urldecode($params['folder']);
         $sources = explode("#@#@#@",$params['source']);
-        //Add user timeszone
         $timestamps = explode("#@#@#@",$params['timestamp']);
-
-
         $flags = explode("#@#@#@",$params['flags']);
-		
-		foreach($sources as $index=>$src) {
-			if($src!=""){
-		$source = $this->treat_base64_from_post($src);
-		$timestampsactual = $timestamps[$index] + $this->functions->CalculateDateOffset(); 
- 		        $insert = $this->insert_email($source, mb_convert_encoding( $dest_folder,"ISO-8859-1","UTF-8"), $timestampsactual,$flags[$index]); 
+        $ids = explode("#@#@#@",$params['id']);
+        $return = array();
+        $archived = array();
+        $error = array();
+
+        foreach($sources as $index=>$src)
+        {
+            if($src!="")
+            {
+                //If it is a MailArchiver incomming data
+                if($params['madata'])
+                    $sourcedec = utf8_decode($src);
+                //Default data
+                else
+                    $sourcedec = $src;
+
+		 		$source = $this->treat_base64_from_post($sourcedec);
+
+				$insert = $this->insert_email($source,$dest_folder,$timestamps[$index],$flags[$index]);
+
+                if($insert['error'])
+                {
+                    $error[] = $ids[$index];
+                }
+                else 
+                {
+                    $archived[] = $ids[$index];
+                }
+            }else{
+                $error[] = $ids[$index];
             }
-	}
-        return $insert;
+		}
+        
+        if (!empty($error))
+        {
+            $return['error'] = $error;
+        }
+        if (!empty($archived))
+        {
+            $return['archived'] = $archived;
+        }
+        
+        return $return;
     }
 
@@ -5484,4 +5535,45 @@
 	}
 
+	//MailArchiver -> get offsettogmt as a global javascript variable, invoked at "main.js", init()
+    function get_offset_gmt(){
+        return($this->functions->CalculateDateOffset());
+    }
+
+    //MailArchiver -> get message flags only, invoked at archive operation
+    function get_msg_flags($args){  
+        $msg_folder = $args['folder'];
+        $msg_n = $args['msg_number'];
+        $arr_msg = explode(",", $msg_n);
+       
+        for($i=0; $i<count($arr_msg); $i++){
+                        
+            if(!$this->mbox || !is_resource($this->mbox))
+                $this->mbox = $this->open_mbox($msg_folder);
+        
+            if(!is_resource($this->mbox))
+                return(false);
+                       
+            $msgno_imap = imap_msgno($this->mbox, $msg_n);          
+        	$header = @imap_headerinfo($this->mbox, $msgno_imap, 80, 255);
+                
+            if (!is_object($header))
+                return false;
+
+            $taglist[$i]["msgid"] = $msg_n;
+            $taglist[$i]["unseen"] = $header->Unseen;
+            $taglist[$i]["recent"] = $header->Recent;
+            $taglist[$i]["flagged"] = $header->Flagged;
+            $taglist[$i]["draft"] = $header->Draft;
+            $taglist[$i]["answered"] = $header->Answered;
+            $taglist[$i]["deleted"] = $header->Deleted;
+        
+            if($header->Answered =='A' && $header->Draft == 'X')
+                $taglist[$i]['forwarded'] = 'F';
+            else
+                $taglist[$i]['forwarded'] = ' ';
+        }
+
+		return $taglist;        
+    }    
 }
 ?>
Index: trunk/expressoMail1_2/inc/class.user.inc.php
===================================================================
--- trunk/expressoMail1_2/inc/class.user.inc.php	(revision 5509)
+++ trunk/expressoMail1_2/inc/class.user.inc.php	(revision 7414)
@@ -50,5 +50,28 @@
 			return $_SESSION['phpgw_info']['expressomail']['user']['email'];	
 		}
-		
+
+        //MailArchiver login validate operations
+        function get_mailarchiver_authid(){
+            if((isset($_COOKIE["BALANCEID"])) && ($_COOKIE["BALANCEID"] != null) && ($_COOKIE["BALANCEID"] != " "))
+                $cookie_balancer = $_COOKIE["BALANCEID"];
+            else
+                $cookie_balancer = "";
+            if((isset($_COOKIE["sessionid"])) && ($_COOKIE["sessionid"] != null) && ($_COOKIE["sessionid"] != " "))
+                $cookie_session = $_COOKIE["sessionid"];
+            else
+                $cookie_session = "";
+            if(isset($_SESSION['phpgw_info']['expressomail']['user']['userid']) && ($_SESSION['phpgw_info']['expressomail']['user']['userid'] != null) && ($_SESSION['phpgw_info']['expressomail']['user']['userid'] != " "))
+                $cookie_user = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
+            else
+                $cookie_user = "";
+            
+            if(isset($_SESSION['phpgw_info']['expressomail']['user']['passwd']) && ($_SESSION['phpgw_info']['expressomail']['user']['passwd'] != null) && ($_SESSION['phpgw_info']['expressomail']['user']['passwd'] != " "))
+                $cookie_pass = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
+            else
+                $cookie_pass = "";
+            
+            return(array($cookie_balancer, $cookie_session, $cookie_user, $cookie_pass));                    
+        }
+
 	}
 ?>
Index: trunk/expressoMail1_2/inc/class.exporteml.inc.php
===================================================================
--- trunk/expressoMail1_2/inc/class.exporteml.inc.php	(revision 7040)
+++ trunk/expressoMail1_2/inc/class.exporteml.inc.php	(revision 7414)
@@ -56,4 +56,19 @@
 	// Rommel Cysne (rommel.cysne@serpro.gov.br)
 	// em 17/12/2008.
+
+    function createFileEml_by_localFolder($sEMLData, $tempDir, $file){ 
+
+        $file = "{$file}.eml";
+
+        $f = fopen($tempDir.'/'.$file,"w");
+        if(!$f)
+            return False;
+
+        fputs($f,$sEMLData);
+        fclose($f);
+        
+        return $file;
+    }
+
 	function createFileEml($sEMLData, $tempDir, $id, $subject=false, $i=false)
     {
@@ -101,7 +116,7 @@
     } 
 
-	function createFileZip($files, $tempDir){		
+	function createFileZip($files, $tempDir){	
+
 		$tmp_zip_filename = "email_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].".zip";
-		
                 if (!empty($files))
                 {
@@ -119,6 +134,9 @@
                     }
                 }
-                
-		$command = "cd " . escapeshellarg($tempDir) . " && nice zip -m9 " . escapeshellarg($tmp_zip_filename) . " " .  $files;
+
+
+$command = "cd " . escapeshellarg($tempDir) . " && nice zip -m9 " . escapeshellarg($tmp_zip_filename) . " " .  $files;
+
+
 		if(!exec($command)) {
 			$command = "cd " .  escapeshellarg($tempDir) . " && rm ".$files." ". escapeshellarg($tmp_zip_filename);
@@ -126,11 +144,63 @@
 			return null;
 		}
-		
+
 		return $tmp_zip_filename;
 				
 	}
 
-	function export_all($params){
-		
+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){
+
 		$this->folder = $params['folder'];
 		$this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","UTF-8");
@@ -140,8 +210,11 @@
 		
 		$msgs = imap_search($this->mbox_stream,"ALL",SE_UID);
+
 		if($msgs){
 			foreach($msgs as $nMsgs){
-				$header	 	= $this-> getHeader($nMsgs);									
-				$body		= $this-> getBody($nMsgs);			
+
+				$header	 	= $this-> getHeader($nMsgs);								 
+				$body		= $this-> getBody($nMsgs);		
+
 				$sEMLData 	= $this -> parseEml($header, $body);
 				$fileName 	= $this -> CreateFileEml($sEMLData, $tempDir,$nMsgs);
@@ -478,4 +551,34 @@
 	}
 
+	//MAILARCHIVER 
+	function js_source_var($params) {
+		$this-> folder = $params['folder'];
+		if(!$this->folder){
+		   $aux = explode(';',$params['msgs_to_export']);
+		   $this->folder = $aux[0];
+		   $id_number = $aux[1];
+		}
+		else{
+			$id_number = $params['msgs_to_export'];
+		}
+		$this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","ISO_8859-1");
+		$tempDir = ini_get("session.save_path");
+
+		$this->connectImap();
+		$header	 	= $this-> getHeader($id_number);
+		$body		= $this-> getBody($id_number);
+		
+		if(!strpos($header,"Date: ")){
+			$header = "Date: " . $this->getHeaderInfo($id_number)->Date . "\r\n" .$header ;
+		}
+
+		imap_close($this->mbox_stream);
+
+		$input = $header . "\r\n\r\n" . $body;
+		$input = preg_replace('/\x1d/', '', $input); //remove special char control detected (hex 1D)
+		
+		return($input);
+	} 
+	
     function export_msg_data($id_msg,$folder) {
 		$this->folder = $folder;
@@ -752,4 +855,9 @@
 		return imap_fetchheader($this->mbox_stream, $msg_number, FT_UID);
 	}
+
+	function getHeaderInfo($msg_number){			
+		$header = imap_headerinfo($this->mbox_stream, imap_msgno($this->mbox_stream, $msg_number), 80, 255);
+		return $header;
+	}
 	
 	function getBody($msg_number){
Index: trunk/expressoMail1_2/js/mail_archiver.js
===================================================================
--- trunk/expressoMail1_2/js/mail_archiver.js	(revision 7414)
+++ trunk/expressoMail1_2/js/mail_archiver.js	(revision 7414)
@@ -0,0 +1,2050 @@
+<!--
+/* 
+ * Mail Archive JS API
+ * 
+ * This JavaScript file is the core to use MailArchiver embeded at Expresso suite.
+ * It contains all the resources used to handle local messages stored at the brand
+ * new solution Mail Archiver (a embeded application server running at client side).
+ *
+ * This feature is a replacement for Google Gears(obsolete by now), used by
+ * Expresso to store local messages at user workstation hard disk.
+ * 
+ * @author Fernando Wendt [fernando-alberto.wendt@serpro.gov.br]
+ *
+ * @status under development
+ */
+
+//var sessid = 'sessionId';
+
+function zeroFill(d){
+    if(parseInt(d) < 10)
+        return('0' + d);
+    else
+        return(d);
+}
+
+//+ Jonas Raoni Soares Silva
+//@ http://jsfromhell.com/geral/utf-8 [v1.0]
+
+UTF8 = {
+	encode: function(s){
+		for(var c, i = -1, l = (s = s.split("")).length, o = String.fromCharCode; ++i < l;
+			s[i] = (c = s[i].charCodeAt(0)) >= 127 ? o(0xc0 | (c >>> 6)) + o(0x80 | (c & 0x3f)) : s[i]
+		);
+		return s.join("");
+	},
+	decode: function(s){
+		for(var a, b, i = -1, l = (s = s.split("")).length, o = String.fromCharCode, c = "charCodeAt"; ++i < l;
+			((a = s[i][c](0)) & 0x80) &&
+			(s[i] = (a & 0xfc) == 0xc0 && ((b = s[i + 1][c](0)) & 0xc0) == 0x80 ?
+			o(((a & 0x03) << 6) + (b & 0x3f)) : o(128), s[++i] = "")
+		);
+		return s.join("");
+	}
+};
+
+
+/**
+ * Concatenates the values of a variable into an easily readable string
+ * by Matt Hackett [scriptnode.com]
+ * @param {Object} x The variable to debug
+ * @param {Number} max The maximum number of recursions allowed (keep low, around 5 for HTML elements to prevent errors) [default: 10]
+ * @param {String} sep The separator to use between [default: a single space ' ']
+ * @param {Number} l The current level deep (amount of recursion). Do not use this parameter: it's for the function's own use
+ */
+function print_r(x, max, sep, l) {
+
+	l = l || 0;
+	max = max || 100;
+	sep = sep || ' ';
+
+	if (l > max) {
+		return "[WARNING: Too much recursion]\n";
+	}
+
+	var
+		i,
+		r = '',
+		t = typeof x,
+		tab = '';
+
+	if (x === null) {
+		r += "(null)\n";
+	} else if (t == 'object') {
+
+		l++;
+
+		for (i = 0; i < l; i++) {
+			tab += sep;
+		}
+
+		if (x && x.length) {
+			t = 'array';
+		}
+
+		r += '(' + t + ") :\n";
+
+		for (i in x) {
+			try {
+				r += tab + '[' + i + '] : ' + print_r(x[i], max, sep, (l + 1));
+			} catch(e) {
+				return "[ERROR: " + e + "]\n";
+			}
+		}
+
+	} else {
+
+		if (t == 'string') {
+			if (x == '') {
+				x = '(empty)';
+			}
+		}
+
+		r += '(' + t + ') ' + x + "\n";
+
+	}
+
+	return r;
+
+};
+var_dump = print_r;
+
+
+
+//Main object structure: object property data definition
+function MailArchiver() { 
+    this.enabled = null;
+    this.interval = 500;
+    this.timer = null;
+    this.counter = 0;
+    this.service_count = 0;
+    this.service_count_tryouts = 0;
+    this.message_list = new Array();
+    this.search_message_list = new Array();
+    this.messageslisted = new Array();
+    this.total_messages = 0;
+    this.messages_processed = 0;
+    this.messages_fail = 0;
+    this.folder_origin = null;
+    this.folder_destination = null;
+    this.folders = null;
+    this.currentfolder = 'local_root';
+    this.currentmessage = null;
+    this.currentheaders = null;
+    this.drawdata = null;
+    this.onprocess = false;
+    this.folder_data = false;
+    this.queryconfig = new MAQueryConfig();
+    this.search_queryconfig = new MAQueryConfig();
+    this.pattern = new MAPattern();
+    this.messagesourcehandler = null;
+    this.ServiceReturnObjectList = null;
+    this.ServiceReturnObjectSearch = null;
+    
+    this.specialfolders = {
+                            "inbox":"local_inbox", 
+                            "sent":"local_sent", 
+                            "drafts":"local_drafts", 
+                            "outbox":"local_outbox", 
+                            "trash":"local_trash"
+                          };                          
+    this.unarchivecounter = 0;
+    this.archivefolder = null;
+    this.unarchievefolder = null;
+    this.unarchievenewfolder = null;
+    this.taglist = "";   
+    this.currenttag = "";   
+    this.tagmsg = false;
+    this.progressbar = null;
+    this.tmp_att_datasource = null;
+    this.tmp_att_data = null;
+    this.isbusy = false;
+    this.update_counters = false;
+    this.exportformat = 'zip';
+    this.querydata = null;
+    this.queryresult = null;
+    this.search_queryresult = null;
+    this.balancerid = null;
+    this.sessionid = null;
+    this.logonid = null;
+    this.session = null;
+    this.selectedfolder = null;
+    this.allmessagesbyfolder = new Array();
+}
+
+//Invoked at some possible MA crash issue
+MailArchiver.prototype.resetObject = function(){
+    expresso_mail_archive.message_list = new Array();
+    expresso_mail_archive.messagelisted = new Array();
+    expresso_mail_archive.total_messages = 0;
+    expresso_mail_archive.messages_processed = 0;
+    expresso_mail_archive.messages_fail = 0;
+    //expresso_mail_archive.folder_origin = null;
+    //expresso_mail_archive.folder_destination = null;
+    //expresso_mail_archive.folder = null;
+    expresso_mail_archive.isbusy = false;
+    //window.alert('ResetedObject, deixando current folder como "' + expresso_mail_archive.currentfolder + '"\nfolder destination "' + expresso_mail_archive.folder_destination+ '"');
+}
+
+/*SystemCheck method: test if MailArchive is installed and/or running at user workstation
+*Try to get a instance of ArchiveServices object - the handler of services provided by
+*the MailArchive services provider interface, from user workstation.
+*/
+MailArchiver.prototype.SystemCheck = function(){
+    expresso_mail_archive.enabled = ((ArchiveServices) ? true : false);    
+    if(expresso_mail_archive.enabled){
+        expresso_mail_archive.getAuthId();
+    }
+    else{
+        
+    }
+}
+
+//Check if preference is setted to use default local folders, try to create them
+MailArchiver.prototype.CreateDefaultStructrure = function(){
+    if(expresso_mail_archive.enabled){
+       //Base request object is a CXF Add-on CORS compatible component
+       var reqHandler = new cxf_cors_request_object();
+       reqHandler.init();
+       this.messagesourcehandler = reqHandler.handler;  
+       if(preferences.auto_create_local == 1){
+           expresso_mail_archive.createFolder("","Trash");
+           expresso_mail_archive.createFolder("","Drafts");
+           expresso_mail_archive.createFolder("","Sent");
+           expresso_mail_archive.createFolder("","Outbox");
+           expresso_mail_archive.createFolder("","Spam");
+       }
+       this.ActivateStatusListener(this);
+    }    
+}
+
+
+//Turns on the listener timer to check services availability
+MailArchiver.prototype.ActivateStatusListener = function(obj){
+    if (document.getElementById('mail_archiver_retry'))
+        tem_tag = true;
+    else
+        tem_tag = false;
+    try{
+        if (obj.enabled){
+            obj.interval = 500; //set default timer to 1ms (imediate lauching)
+            //draw_footer_box(get_current_folder());
+            obj.getServicesStatus(obj);
+        }
+        else{
+            throw "this is not enabled: " + obj;
+            window.alert('Nope: obj.enabled is not true...');
+        }
+    }
+    catch (e){
+        window.alert('ActivateStatusListener error: ' + e);
+    }
+}
+
+//Turns off the service status listener, at a crash issue
+MailArchiver.prototype.DeactivateStatusListener = function(obj){
+    window.clearInterval(obj.timer);
+    obj.enabled = null;
+    obj.timer=null;
+    obj.interval = 500;
+    ArchiveServices = null;
+    connector.purgeCache();
+    draw_footer_box(get_current_folder());
+    //auto_refresh();
+    if(document.getElementById('mail_archiver_retry')){
+        document.getElementById('mail_archiver_retry').parentNode.removeChild(document.getElementById('mail_archiver_retry'));
+    }
+    else{
+        //Redraw "Offline" linkage, intended to recoonect MailArchiver link    
+        connector.purgeCache();
+        draw_new_tree_folder();
+        change_folder('INBOX', 'INBOX'); 
+    }
+}
+
+//ServiceStatus callback OK
+MailArchiver.prototype.getServicesStatusOK = function(serviceData){
+    //window.alert('getServicesStatusOK com servicedata = ' + serviceData.getReturn());
+    expresso_mail_archive.service_count = expresso_mail_archive.counter;
+    if ((serviceData.getReturn().toUpperCase() == "STARTED") || (serviceData.getReturn().toUpperCase() == "RUNNING")){
+        //If there is no timer activated to services check interval, set it up.
+        if(expresso_mail_archive.enabled){
+           if(expresso_mail_archive.timer == null){
+                expresso_mail_archive.interval = 15000;
+                expresso_mail_archive.timer = window.setInterval(expresso_mail_archive.getServicesStatus, expresso_mail_archive.interval);
+                var drawinginfo = {treeObject: tree_folders, treeName: 'tree_folders', folderName: 'local_root'};
+                expresso_mail_archive.currentfolder = 'local_root';
+                expresso_mail_archive.drawdata = drawinginfo;
+                expresso_mail_archive.getFoldersList();
+           }
+        }
+        else{
+            window.clearInterval(expresso_mail_archive.timer);
+            write_msg(get_lang('MailArchiver does not seems to be running or installed at this workstation, local messages are disabled. Check it out!'),false);
+            expresso_mail_archive.enabled = false;
+            expresso_mail_archive.turnOffLocalTreeStructure();
+        }
+    }
+    else{
+        window.clearInterval(expresso_mail_archive.timer);
+        write_msg(get_lang('MailArchiver does not seems to be running or installed at this workstation, local messages are disabled. Check it out!'),false);
+        expresso_mail_archive.enabled = false;
+        expresso_mail_archive.turnOffLocalTreeStructure(); 
+    }
+    //window.alert('fooArc set to null');
+    fooArc = null;
+}
+
+//Dettach resources handler
+MailArchiver.prototype.DeactivateResources = function(obj){   
+    if(obj.timer)
+        window.clearInterval(obj.timer);
+    write_msg(get_lang('Mail Archiver is not responding. There is some communicating issue hang it up. Some services may not work properly. Check it out!'));
+    obj.DeactivateStatusListener(obj);
+    //draw_new_tree_folder();
+    return;
+}
+
+//Services Status Fail callback
+MailArchiver.prototype.getServicesStatusFailure = function(serviceData){
+    window.alert('getServicesStatusFailure incomming');
+    window.alert('getServicesStatusFailure feature: ' + serviceData);
+}
+
+//Service Status handler
+MailArchiver.prototype.getServicesStatus = function(obj){
+    //window.alert('em getServicesStatus obj.enabled = ' + obj.enabled + '\nArchiveServices.enabled = ' + ArchiveServices.enabled + '\nArchiveServices = ' + ArchiveServices);
+    try{
+        //window.alert('on try 01');
+        expresso_mail_archive.service_count_tryouts++;
+        //window.alert('service_count_tryouts = ' + expresso_mail_archive.service_count_tryouts + '\nservice_count = ' + expresso_mail_archive.service_count);
+        
+        if((expresso_mail_archive.service_count_tryouts - expresso_mail_archive.service_count) > 1){
+            //window.alert('problema -> deve desligar');
+            expresso_mail_archive.DeactivateResources(expresso_mail_archive);            
+        }
+        //else
+            //window.alert('ok');
+        
+        var fooArc = new web_service_mailarchiver_serpro__ArchiveServices();
+        fooArc.url = mail_archive_protocol + "://" + mail_archive_host + ":" + mail_archive_port + "/arcserv/ArchiveServices";
+        //window.alert('typeof(fooArc) = ' + typeof(fooArc) + '\nfooArc = ' + fooArc);
+        if(fooArc){
+            try{
+                //window.alert('on try 02');
+                fooArc.getState(expresso_mail_archive.getServicesStatusOK, expresso_mail_archive.getServicesStatusFailure, "true");
+                fooArc = null;
+            }catch (e){
+                throw "Service failure status: getState";
+            }
+        }
+        else {
+            throw "No ArchiveServices object present. Sorry, but leaving now...";
+        }
+    }catch (e){
+        //window.alert('getServiceStatus exception:' + e);
+    }
+    expresso_mail_archive.counter = expresso_mail_archive.counter +1;
+}
+
+/*Restart method: re-initializes all the Mail Archive structure
+ **/
+MailArchiver.prototype.Restart = function(obj){
+    obj.SystemCheck();
+    obj.ActivateStatusListener(obj);
+    //connector.resetProgressBarText();
+    auto_refresh();
+}
+
+/*Startup method: initializes all the Mail Archive structure to work so far as possible
+ *Looks like the old 'gears_init', from Gears
+ **/
+MailArchiver.prototype.Startup = function(){
+    this.SystemCheck();  
+}
+
+MailArchiver.prototype.serializeToExpresso = function(data){
+    return(connector.serialize(data));
+}
+
+MailArchiver.prototype.unserializeFromExpresso = function(data){
+    return(connector.unserialize(data));
+}
+
+
+MailArchiver.prototype.CreateMessageList = function(msg_list){
+    //window.alert('criando messagelist de arquivamento.');
+    
+//    for(var j=0; j<expresso_mail_archive.messageslisted.length; j++){
+//        window.alert('\nAnswered = ' + expresso_mail_archive.messageslisted[j]["Answered"] + '\nFlagged = ' + expresso_mail_archive.messageslisted[j]["Flagged"] + '\nUnseen = ' + expresso_mail_archive.messageslisted[j]["Unseen"] + '\nDraft = ' + expresso_mail_archive.messageslisted[j]["Draft"]);
+//    }
+    
+    if((msg_list != null) && (msg_list != "") && (msg_list != " ")){
+        if (expresso_mail_archive.message_list.length == 0){
+            //Get all the messages ids by pass at msgs_id to "message_list" object array propertie - if more than one exists
+            if(msg_list.indexOf(',') != -1){
+                var tmp_list = msg_list.split(',');
+                for(var i=0; i < tmp_list.length; i++){
+                    expresso_mail_archive.message_list.push(tmp_list[i]);
+                }
+            }
+            
+            //Push message list to process the only one
+            else {
+                //window.alert('testando marcadores default...\n->Answered = ' +expresso_mail_archive.messageslisted[i]["Answered"] + '\n->Unseen = '+expresso_mail_archive.messageslisted[i]["Unseen"]);
+                expresso_mail_archive.message_list.push(msg_list);
+            }
+        }
+    }
+    //msg_list is corrupted. aborting population
+    else expresso_mail_archive.message_list = new Array();
+}
+
+
+//Archive Operation
+MailArchiver.prototype.Archive = function(source_folder,destination_folder,msgs_id){
+    //window.alert('tentando arquivar a mensagem [' + msgs_id + '], do folder ['+source_folder+'] para a pasta destino ['+destination_folder+']');
+    //modal('archive_queue');
+    
+    try{
+        //Sets the folders properties: destination and origin
+        expresso_mail_archive.folder_origin = source_folder;
+        expresso_mail_archive.CreateMessageList(msgs_id);
+        var tagsHandler = function(data){
+            if(data){
+                var datah = eval(data);
+                //window.alert('unseen = ' +datah["unseen"] + '\nrecent = ' + datah["recent"] + '\nflagged = ' + datah["flagged"] + '\ndraft = ' + datah["draft"] + '\nanswered = ' + datah["answered"] + '\ndeleted = ' + datah["deleted"] + '\nforwarded = ' + datah["forwarded"]);
+                expresso_mail_archive.taglist = datah;
+                //Sets the message counter and busy state
+                if(expresso_mail_archive.isbusy == false){
+                    expresso_mail_archive.total_messages = expresso_mail_archive.message_list.length;
+                    expresso_mail_archive.isbusy =  true;
+                }
+           
+                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(!expresso_mail_archive.archivefolder){
+                    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);
+                        expresso_mail_archive.archivefolder = expresso_mail_archive.folder.path;
+                        //window.alert('folder.path2 -> ' + expresso_mail_archive.folder.path);
+                    }
+                    else{
+                     //window.alert('ainda, sem folder.path');   
+                     //window.alert('testando folder.path agora ' + expresso_mail_archive.folder.path);
+                    }
+                }   
+
+                fcaption = expresso_mail_archive.archivefolder;
+                            
+                //Special folders translation
+                if (fcaption && ((fcaption.toLowerCase() == 'inbox') || (fcaption.toLowerCase() == 'outbox') || (fcaption.toLowerCase() == 'sent') || (fcaption.toLowerCase() == 'drafts') || (fcaption.toLowerCase() == 'trash')))
+                    fcaption = get_lang(fcaption);
+            
+            
+                var arch_handler = function(data){
+                    //Store the message source from Ajax request by now (string data)
+                    var js_var = new String(data);
+                    try{
+                        //Archive services needs session id, message source and destination folder
+						ArchiveServices.archive(expresso_mail_archive.getArchiveOperationOK, expresso_mail_archive.getArchiveOperationFailure, expresso_mail_archive.session.id, expresso_mail_archive.folder_destination, data);
+                    }
+                    catch(e){
+                        expresso_mail_archive.getFaultInfo();
+                    }
+                }
+                
+                //document.getElementById('main_title').innerHTML = get_lang('Archiving message %1 of %2 on folder %3', expresso_mail_archive.messages_processed, expresso_mail_archive.total_messages, fcaption);
+                //document.getElementById('text_archive_queue').innerHTML = get_lang('Archiving message %1 of %2 on folder %3', expresso_mail_archive.messages_processed+1, expresso_mail_archive.total_messages, fcaption);
+                cExecute("$this.exporteml.js_source_var",arch_handler,"folder="+url_decode(source_folder)+"&msgs_to_export="+expresso_mail_archive.message_list[0]);                
+            }
+            else{
+                //close_lightbox();
+                write_msg(get_lang('Archive operation error: getting online message flags fails. Achievement will not be done'),true);
+                expresso_mail_archive.archivefolder = null;
+            }
+        }
+
+       if((expresso_mail_archive.message_list.length > 0) && (expresso_mail_archive.message_list[0] != '')){
+
+            //Get all tags from current archiving message
+           if(!expresso_mail_archive.folder_origin){
+                var aux1_folder = expresso_mail_archive.message_list[0].split(';')[0];
+                var aux1_msg_number = expresso_mail_archive.message_list[0].split(';')[1];
+            }
+            else{
+                var aux1_folder = expresso_mail_archive.folder_origin;
+                var aux1_msg_number = expresso_mail_archive.message_list[0];
+            }
+            //var pardata = "&folder=" + url_encode(expresso_mail_archive.folder_origin)+ "&msg_number="+ expresso_mail_archive.message_list[0]; 
+            var pardata = "&folder=" + url_encode(aux1_folder)+ "&msg_number="+ aux1_msg_number;
+            cExecute("$this.imap_functions.get_msg_flags", tagsHandler, pardata);
+        }
+        else throw('Archive operation error: message list stack is empty');
+    }
+    catch(e){
+        //window.alert(get_lang("Archive error: %1", (e.description)?e.description:e));
+		expresso_mail_archive.getFaultInfo();
+    }
+}
+
+//Archive callback OK
+MailArchiver.prototype.getArchiveOperationOK = function(status_message){
+    //message must be tagged
+    var arcid = status_message.getReturn().getId();
+    var tlist = expresso_mail_archive.pattern.tagConfig(expresso_mail_archive.taglist, arcid, 0);
+    if(tlist != null){
+        try{
+            expresso_mail_archive.drawdata = null //removes any draw parameter to archive msgs
+            ArchiveServices.tagMessages(expresso_mail_archive.tagMessagesOperationOK, expresso_mail_archive.tagMessagesOperationFailure, expresso_mail_archive.session.id, tlist);
+        }catch (e){
+            expresso_mail_archive.getFaultInfo();
+        }
+    }
+
+    //if user preference is setted to move messages, here, whe will call a delete message at mailserver
+    if(preferences.keep_archived_messages == 0){
+        proxy_mensagens.delete_msgs(expresso_mail_archive.folder_origin,expresso_mail_archive.message_list[0],null,false,true);
+    }else{
+        if (Element("check_box_message_" + expresso_mail_archive.message_list[0])) {
+            Element("check_box_message_" + expresso_mail_archive.message_list[0]).checked = false;
+            remove_className(Element(expresso_mail_archive.message_list[0]), 'selected_msg');
+        }
+    }
+
+    //archivement allready done, update controll data and interface
+    expresso_mail_archive.messages_processed++;
+    if(expresso_mail_archive.message_list.length > 1){
+       write_msg(get_lang("Message %1 of %2 successfully archived", expresso_mail_archive.messages_processed, expresso_mail_archive.total_messages));
+       expresso_mail_archive.message_list.shift();
+       expresso_mail_archive.Archive(expresso_mail_archive.folder_origin, expresso_mail_archive.folder_destination, expresso_mail_archive.message_list);
+    }
+    else{
+        write_msg(get_lang("All done. End of archive messages operation"));
+        expresso_mail_archive.resetObject();
+        expresso_mail_archive.archivefolder = null;
+        window.setTimeout("eval('document.getElementById(\"main_title\").innerHTML =\"Expresso Mail\"')",3000);        
+        connector.purgeCache();
+        //ttreeBox.name_folder = "local_" + expresso_mail_archive.currentfolder;
+        //ttreeBox.name_folder = "local_inbox";
+        draw_tree_local_folders();
+        //ttreeBox.update_folder(true);    
+    }
+    //close_lightbox();
+}
+//Archive callback Fail
+MailArchiver.prototype.getArchiveOperationFailure = function(error_message){
+    window.alert('Hi! getArchiveOperationFailure comes with ' + error_message.getReturn());
+    window.setTimeout("eval('document.getElementById(\"main_title\").innerHTML =\"Expresso Mail\"')",3000);
+}
+
+/**
+ *move Folder
+ *
+ *@author Thiago Rossetto Afonso [thiago@prognus.com.br]
+ *
+ *@param folder_to_move Current folder that will be moved to another folder
+ *@param folder_to Folter that will receive the new folder
+ */
+MailArchiver.prototype.moveFolder = function(folder_to_move, folder_to){
+    try{
+        connector.showProgressBar();
+        ArchiveServices.moveFolder(expresso_mail_archive.moveFolderOK, expresso_mail_archive.moveFolderFailure, expresso_mail_archive.session.id, folder_to_move, folder_to);
+    }catch(e){
+        expresso_mail_archive.getFaultInfo();
+    }
+}
+MailArchiver.prototype.moveFolderOK = function(message){
+    write_msg(get_lang("Your folder was moved!"));
+}
+MailArchiver.prototype.moveFolderFailure = function(error_message){
+    alert("Error: " + error_message.getReturn());
+}
+
+
+
+
+/**
+ *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"));
+        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.'));
+    }
+    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.messageslisted.length; w++){
+                                
+                if(expresso_mail_archive.messageslisted[w]["msg_number"] == expresso_mail_archive.message_list[expresso_mail_archive.unarchivecounter]){
+                    var timestamp = expresso_mail_archive.messageslisted[w]["timestamp"];
+                    
+                    //Get local tagged message data
+                    var flags = new String("");
+                    
+                    //Forwarded is special one: marks as "answered" and "draft"
+                    if(expresso_mail_archive.messageslisted[w]["Forwarded"]){
+                        if(expresso_mail_archive.messageslisted[w]["Forwarded"] == 'F')
+                            flags += 'A:X';                                  
+                    }
+                    else{
+                        //Answered tag
+                        if(expresso_mail_archive.messageslisted[w]["Answered"])
+                            if(expresso_mail_archive.messageslisted[w]["Answered"] == 'A')
+                                flags += 'A';
+                            else
+                                flags += ':';
+                        else
+                            flags += ':';                    
+
+                        //Draft tag
+                        if(expresso_mail_archive.messageslisted[w]["Draft"])
+                            if(expresso_mail_archive.messageslisted[w]["Draft"] == 'X')
+                                flags += 'D'+':';                    
+                            else
+                                flags += ':';
+                        else
+                            flags += ':';
+                    }
+                    
+                    //Flagged tag
+                    if(expresso_mail_archive.messageslisted[w]["Flagged"])
+                        if(expresso_mail_archive.messageslisted[w]["Flagged"] == 'F')
+                            flags += 'F'+':';                                        
+                        else
+                            flags += ':';
+                    else
+                        flags += ':';
+                    
+                    //Unseen tag
+                    if(expresso_mail_archive.messageslisted[w]["Unseen"])
+                        if(expresso_mail_archive.messageslisted[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) + "#@#@#@";
+            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.unarchieveController(data);
+            }
+            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);
+
+        }
+        
+        write_msg(get_lang('Opening message %1 to unarchive', (expresso_mail_archive.unarchivecounter + 1)));
+    
+        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));
+    }
+}
+
+/**
+ *
+ *Unarchieve Message Controller
+ *
+ *@author Cassiano Dal Pizzol [cassiano.dalpizzol@serpro.gov.br]
+ *
+ **/
+MailArchiver.prototype.unarchieveController = function(data){
+    expresso_mail_archive.unarchivecounter++;
+    
+    if (data)
+    {
+        if (data.error != "")
+        {
+            expresso_mail_archive.unarchive_error_counter++;
+        }
+        
+        if (data.archived && preferences.keep_archived_messages == "0")
+        {
+            // apaga
+            expresso_mail_archive.deleteMessages(data.archived[0]);
+        }
+        
+    }
+
+    if (expresso_mail_archive.unarchivecounter < expresso_mail_archive.message_list.length){
+        expresso_mail_archive.unarchieveHandler();
+    }
+    else
+    {
+        if (expresso_mail_archive.unarchive_error_counter == 0)
+        {    
+            if (expresso_mail_archive.message_list.length==1){
+                write_msg(get_lang('Message successfully unarchived'));
+            }
+            else{
+                write_msg(get_lang('Messages successfully unarchived'));
+            }
+        }
+        else
+        {
+            if (expresso_mail_archive.message_list.length==1){
+                write_msg(get_lang("Coudn't unarchive message"));
+            }
+            else if (expresso_mail_archive.unarchive_error_counter == expresso_mail_archive.message_list.length)
+            {
+                write_msg(get_lang('No messages were unarchived'));
+            }
+            else{
+                write_msg(get_lang("Some messages weren't successfully unarchived"));
+            }
+                
+        }
+        //clear message list
+        expresso_mail_archive.message_list = new Array();
+    }
+}
+
+/**
+ *Archieve Delete Message
+ *
+ *@author Cassiano Dal Pizzol [cassiano.dalpizzol@serpro.gov.br]
+ *
+ *@param msgs_number Unique identification of the message
+ */
+MailArchiver.prototype.deleteMessages = function(msgs_number){
+    try{
+        // This is necessary 'couse we can get a delete operation while an unarchive operation
+        // is still executing
+        expresso_mail_archive._temp_list = expresso_mail_archive.message_list;
+        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] != '')) {
+            ArchiveServices.deleteMessages(expresso_mail_archive.deleteMessagesOperationOK, 
+                                           expresso_mail_archive.deleteMessagesOperationFailure, 
+                                           expresso_mail_archive.session.id, 
+                                           expresso_mail_archive.message_list);
+        }
+        else{
+            write_msg(get_lang('No selected message.'));
+        }
+    }
+    catch (e){
+        window.alert('Delete error: ' + e);
+    }
+}
+
+/**
+ *Archieve Delete Message Ok
+ *
+ *@author Cassiano Dal Pizzol [cassiano.dalpizzol@serpro.gov.br]
+ *
+ */
+MailArchiver.prototype.deleteMessagesOperationOK = function(){
+/*    var drawinginfo = {treeObject: tree_folders, treeName: 'tree_folders'};
+    expresso_mail_archive.drawdata = drawinginfo;
+    expresso_mail_archive.drawFolderTree();
+    expresso_mail_archive.listMessages();
+    */
+    connector.purgeCache();
+    //ttreeBox.update_folder(true);
+    if(expresso_mail_archive.message_list.length > 1){
+        write_msg(get_lang("The messages were deleted."));
+    }else{
+        write_msg(get_lang("The message was deleted."));
+    } 
+    expresso_mail_archive.update_counters = true;
+    expresso_mail_archive.messageslisted = new Array();
+    expresso_mail_archive.message_list = new Array();
+
+    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
+    // is still executing
+    expresso_mail_archive.message_list = expresso_mail_archive._temp_list;
+    expresso_mail_archive._temp_list = null;
+}
+
+/**
+ *Archieve Delete Message Operation Failure
+ *
+ *@author Cassiano Dal Pizzol [cassiano.dalpizzol@serpro.gov.br]
+ *
+ */
+MailArchiver.prototype.deleteMessagesOperationFailure = function(error_message){
+    if(expresso_mail_archive.message_list.length > 1){
+        write_msg(get_lang("Error deleting messages.") + ' ' + error_message.getReturn());
+    }else{
+        write_msg(get_lang("Error deleting message.") + ' ' + error_message.getReturn());
+    }
+    
+    // This is necessary 'couse we can get a delete operation while an unarchive operation
+    // is still executing
+    expresso_mail_archive.message_list = expresso_mail_archive._temp_list;
+    expresso_mail_archive._temp_list = null;
+}
+
+/**
+ *Move message
+ *
+ *@param folder Folder where the message will be moved
+ *@param msgs_number Unique Id of the message
+ *
+ *@author Cassiano Dal Pizzol [cassiano.dalpizzol@serpro.gov.br]
+ *
+ */
+MailArchiver.prototype.moveMessages = function(folder, msgs_number){    
+    try{
+        write_msg(get_lang("Starting to move messages"));
+
+        expresso_mail_archive.CreateMessageList(msgs_number);
+        expresso_mail_archive.folder_destination = folder;
+        //window.alert('invocando o moveMessages com lista = ' + expresso_mail_archive.message_list.length + ' e folder destino =' + folder + '.\nFolder corrente ï¿œ ' + expresso_mail_archive.currentfolder);
+        
+        if((expresso_mail_archive.message_list.length > 0) && (expresso_mail_archive.message_list[0] != '')) {
+            expresso_mail_archive.total_messages = expresso_mail_archive.message_list.length;
+            expresso_mail_archive.moveMessagesHandler();           
+        }
+        else{
+            write_msg(get_lang('No selected message.'));
+        }
+    }
+    catch (e){
+        expresso_mail_archive.getFaultInfo();
+    }
+}
+
+MailArchiver.prototype.moveMessagesHandler = function(){
+    expresso_mail_archive.currentfolder = folder.substr(6, folder.length);
+
+    if((expresso_mail_archive.message_list.length > 0) && (expresso_mail_archive.message_list[0] != '')) {
+        write_msg(get_lang('Moving message %1 of %2', expresso_mail_archive.messages_processed, expresso_mail_archive.total_messages));
+        ArchiveServices.moveMessages(expresso_mail_archive.moveMessagesOperationOK, 
+                                     expresso_mail_archive.moveMessagesOperationFailure,
+                                     expresso_mail_archive.session.id, 
+                                     expresso_mail_archive.folder_destination,
+                                     new Array(expresso_mail_archive.message_list[parseInt(expresso_mail_archive.messages_processed)])
+                                     );
+    }
+    else{
+        window.alert('Moving handler messagelist caught:\n ' + expresso_mail_archive.message_list.length);        
+    }    
+}
+
+/**
+ *Move Message Ok
+ *
+ *@author Cassiano Dal Pizzol [cassiano.dalpizzol@serpro.gov.br]
+ *
+ */
+MailArchiver.prototype.moveMessagesOperationOK = function(){ 
+    //archivement allready done, update controll data and interface
+    expresso_mail_archive.messages_processed++;
+    
+    if(parseInt(expresso_mail_archive.messages_processed) < parseInt(expresso_mail_archive.total_messages)){
+       window.setTimeout(expresso_mail_archive.moveMessagesHandler,1);       
+    }
+    else{
+        write_msg(get_lang("All done. Message(s) moved successfully"));
+        
+        //Tag messages moved
+        for(var i=0; i<expresso_mail_archive.message_list.length; i++){
+            var tlist = expresso_mail_archive.pattern.tagConfig(expresso_mail_archive.taglist, expresso_mail_archive.message_list[i], 0);
+            if(tlist != null){
+                try{
+                    expresso_mail_archive.drawdata = null;
+                    ArchiveServices.tagMessages(expresso_mail_archive.tagMessagesOperationOK, expresso_mail_archive.tagMessagesOperationFailure, expresso_mail_archive.session.id, tlist);
+                }
+                catch(e){
+                    expresso_mail_archive.getFaultInfo();
+                }
+            }            
+        }          
+        
+        expresso_mail_archive.update_counters = true;
+        expresso_mail_archive.messageslisted = new Array();
+        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.resetObject();
+    }
+}
+
+/**
+ *Move Message Failure
+ *
+ *@author Cassiano Dal Pizzol [cassiano.dalpizzol@serpro.gov.br]
+ *
+ */
+MailArchiver.prototype.moveMessagesOperationFailure = function(error_message){
+    if(expresso_mail_archive.message_list.length > 1){
+        write_msg(get_lang("Error moving messages.") + ' ' + error_message.getReturn());
+    }else{
+        write_msg(get_lang("Error moving message.") + ' ' + error_message.getReturn());
+    } 
+}
+
+
+//getFolderList Operation
+MailArchiver.prototype.getFoldersList = function(basefolder){   
+    try{
+        connector.showProgressBar();
+        //window.alert('no expresso_mail_archive.getFoldersList com basefolder = ' + basefolder);
+        if(basefolder == 'local_root')
+            basefolder = "";
+        //window.alert('folderlist com basefolder = ' + basefolder);
+        //ArchiveServices.listFolders(expresso_mail_archive.getFoldersListOperationOK, expresso_mail_archive.getFoldersListOperationFailure, sessid, basefolder);
+        ArchiveServices.listFolders(expresso_mail_archive.getFoldersListOperationOK, expresso_mail_archive.getFoldersListOperationFailure, expresso_mail_archive.session.id, basefolder);
+        
+    }
+    catch (e){
+        expresso_mail_archive.getFaultInfo();
+    } 
+}
+
+//getFolderList callback OK
+MailArchiver.prototype.getFoldersListOperationOK = function(folderlist){
+    //Internal variable used to map all XML data return from WS invokated
+    var lfolders = new Array();
+
+    
+    //Mapping XML data to a handler data structure
+    if(folderlist.getReturn().length > 0){
+        var lfolders = new Array();
+        for(i=0; i<folderlist.getReturn().length; i++){
+            (folderlist.getReturn()[i].getFolderCount() > 0 ) ? folderChild = 1 : folderChild = 0;
+
+            //Store folder data at this format: {folder name, number of messages contained, folder has child nodes, folder id, folder parent id, folder full path}
+            //var folderData = new Array(folderlist.getReturn()[i].getName(), folderlist.getReturn()[i].getMessageCount(), folderChild, folderlist.getReturn()[i].getId(), folderlist.getReturn()[i].getParentId(), folderlist.getReturn()[i].getPath());
+            var folderData = {name: folderlist.getReturn()[i].getName(), messages: folderlist.getReturn()[i].getMessageCount(), haschild: folderChild, id: folderlist.getReturn()[i].getId(), parentid: folderlist.getReturn()[i].getParentId(), path: folderlist.getReturn()[i].getPath(), unseen: folderlist.getReturn()[i].getUnseenCount()};
+            //window.alert('folder ' + folderData.name + ' tem ' + folderData.messages + ' mensagens, sendo ' + folderData.unseen + ' nï¿œo lidas');
+            lfolders.push(folderData);
+        }
+
+        //Sets folders property at main object
+        expresso_mail_archive.folders = lfolders;
+        
+        //Sets current folder, only if no one is setted
+        //if(expresso_mail_archive.currentfolder == null){
+            if(expresso_mail_archive.folders[0]["parentid"] == "home"){ // change from "" to "home"(12/12/2011)
+                expresso_mail_archive.currentfolder = 'local_root';
+            }
+            else
+                expresso_mail_archive.currentfolder = expresso_mail_archive.folders[0]["parentid"];
+        //}
+        
+        
+        //Folders dumping :)
+        /*var strFolders = '---';
+        for (var w=0; w < expresso_mail_archive.folders.length; w++){
+            strFolders += '\nFolder ' + w + ' -->';
+            for (x in expresso_mail_archive.folders[w]){
+                strFolders += '\n----------' + x + ':= ' + expresso_mail_archive.folders[w][x];
+            }
+            strFolders += '\n<---';
+        }
+        strFolders += '\n---';
+        alert(lfolders.length + ' folders mapeados, com default = ' + expresso_mail_archive.currentfolder + '\nfolders list:\n\n' + strFolders);
+        */
+        //window.alert('foldersListOperationOK com drawdata:\n' + expresso_mail_archive.drawdata);
+        //If something UI related have been flagged, handle it
+        if (expresso_mail_archive.drawdata){
+            //window.alert('com drawdata e treeName = ' + expresso_mail_archive.drawdata.treeName);
+            expresso_mail_archive.drawFolderTree();
+        }
+    } else {
+        expresso_mail_archive.folders = 0;
+    }
+    connector.hideProgressBar();
+}
+
+//getFolderList callback Fail
+MailArchiver.prototype.getFoldersListOperationFailure = function(error, http_msg){
+    window.alert('List folders mistake:' + error + '\nhttp_error = ' + http_msg);
+    connector.hideProgressBar();
+}
+
+//drawFolderTree operation, if requested to
+MailArchiver.prototype.drawFolderTree = function(){  
+    var localBaseName  = 'local_';
+    var objectTree = expresso_mail_archive.drawdata.treeObject;
+    var evalobjectTree = (typeof(expresso_mail_archive.drawdata.treeObject) == 'object') ? expresso_mail_archive.drawdata.treeObject: eval( '(' + expresso_mail_archive.drawdata.treeName + ')');
+        
+    if((expresso_mail_archive.drawdata.treeName == 'search_folders') && (Element('dftree_search_folders')))
+        evalobjectTree = folders_tree;
+    else{
+        if((expresso_mail_archive.drawdata.treeName == 'folders_tree') && (Element('dftree_folders_tree')))
+            evalobjectTree = folders_tree;
+    }
+        
+    //Add nodes to tree    
+    if(typeof(evalobjectTree) == 'object'){
+        //window.alert('caiu pra dentro, com ' + expresso_mail_archive.folders.length + ' folders.');
+        evalobjectTree._drawn = true;
+        if(expresso_mail_archive.folders.length > 0){
+            for(i=0; i<expresso_mail_archive.folders.length; i++){
+                var folder_caption;
+                //window.alert('iterando nodo ' + expresso_mail_archive.folders[i]["name"]);
+            
+                //Special folders treatment: Inbox, Outbox, Drafts, Sent and Trash folders               
+                if((expresso_mail_archive.folders[i]["name"] == 'Inbox') || (expresso_mail_archive.folders[i]["name"] == 'Outbox') || (expresso_mail_archive.folders[i]["name"] == 'Drafts') || (expresso_mail_archive.folders[i]["name"] == 'Sent') || (expresso_mail_archive.folders[i]["name"] == 'Trash')){
+                    folder_caption = get_lang(expresso_mail_archive.folders[i]["name"]);
+                }
+                else{
+                    folder_caption = expresso_mail_archive.folders[i]["name"];
+                }
+                
+                var onClickVar = '';                               
+                if((evalobjectTree.name != "folders_tree") && (evalobjectTree.name != "search_folders")){
+                    onClickVar =  "change_folder('"+ localBaseName + expresso_mail_archive.folders[i]["id"] +"','"+ localBaseName + expresso_mail_archive.folders[i]["id"]+"', '" + expresso_mail_archive.drawdata.treeName + "')";
+                    if(expresso_mail_archive.folders[i]["unseen"] != "0")
+                        folder_caption = folder_caption + '<font style=color:red>&nbsp(</font><span id="dftree_local_'+expresso_mail_archive.folders[i]["id"]+'_unseen" style=color:red>'+expresso_mail_archive.folders[i]["unseen"]+'</span><font style=color:red>)</font>'
+                }
+     
+                var n_demo = new dNode({id: localBaseName + expresso_mail_archive.folders[i]["id"], caption: folder_caption, onClick: onClickVar, plusSign:expresso_mail_archive.folders[i]["haschild"]});
+                //var n_demo = new dNode({id: localBaseName + expresso_mail_archive.folders[i]["name"], caption: folder_caption, onClick: "change_folder('"+ localBaseName + expresso_mail_archive.folders[i]["name"] +"','"+ localBaseName + expresso_mail_archive.folders[i]["name"]+"', '" + expresso_mail_archive.drawdata.treeName + "')", plusSign:expresso_mail_archive.folders[i]["haschild"]});
+            
+                //Adjust the id node names
+                if(expresso_mail_archive.currentfolder){
+                    if(expresso_mail_archive.currentfolder.substr(0,5) != 'local'){
+                        evalobjectTree.add(n_demo, localBaseName + expresso_mail_archive.currentfolder);
+                    }
+                    else{
+                        evalobjectTree.add(n_demo,expresso_mail_archive.currentfolder);
+                    }
+                }
+                else {
+                    expresso_mail_archive.currentfolder = 'local_root';
+                    evalobjectTree.add(n_demo,expresso_mail_archive.currentfolder);
+                }            
+            }
+        }
+        //Set special folders icons   
+        if (document.getElementById('llocal_senttree_folders')){
+            document.getElementById('llocal_senttree_folders').style.backgroundImage="url(../phpgwapi/templates/"+template+"/images/foldertree_sent.png)";
+        }
+        if (document.getElementById('llocal_trashtree_folders')){
+            document.getElementById('llocal_trashtree_folders').style.backgroundImage="url(../phpgwapi/templates/"+template+"/images/foldertree_trash.png)";
+        }
+        if (document.getElementById('llocal_draftstree_folders')){
+            document.getElementById('llocal_draftstree_folders').style.backgroundImage="url(../phpgwapi/templates/"+template+"/images/foldertree_draft.png)";
+        }
+        if (document.getElementById('llocal_outboxtree_folders')){
+            document.getElementById('llocal_outboxtree_folders').style.backgroundImage="url(../phpgwapi/templates/"+template+"/images/foldertree_sent.png)";
+        }         
+    }
+    else {
+        //does nothing
+    }
+}
+
+//getFaultInfo operation
+MailArchiver.prototype.getFaultInfo = function(){
+    try{
+        //ArchiveServices.getFaultInfo(expresso_mail_archive.getFaultInfoOperationOK, expresso_mail_archive.getFaultInfoOperationFailure, sessid);
+         ArchiveServices.getFaultInfo(expresso_mail_archive.getFaultInfoOperationOK, expresso_mail_archive.getFaultInfoOperationFailure, expresso_mail_archive.session.id);
+         connector.hideProgressBar();
+    }    
+    catch(e){
+        if (!expresso_mail_archive.enabled)
+            write_msg(get_lang('MailArchiver does not seems to be running or installed at this workstation, local messages are disabled. Check it out!'),false);
+        else{
+            window.clearInterval(expresso_mail_archive.timer);
+            write_msg(get_lang('There is something wrong with MailArchiver environment. Contact you support'), false);
+            expresso_mail_archive.enabled = false;
+            expresso_mail_archive.turnOffLocalTreeStructure();
+        }
+        connector.hideProgressBar();
+    }
+}
+
+//getFaultInfo callback OK
+MailArchiver.prototype.getFaultInfoOperationOK = function(faultinfo){
+    try{
+        write_msg(get_lang('MailArchiver remote service reports the following error:', false) + faultinfo.getReturn().getSoapFaultString());
+    } catch(e){
+        write_msg(get_lang('The archive service reports a unknown error. Try to refresh your browser screen', false));
+    }
+    expresso_mail_archive.resetObject();
+    expresso_mail_archive.archivefolder = null;
+    window.setTimeout("eval('document.getElementById(\"main_title\").innerHTML =\"Expresso Mail\"')",3000);        
+    connector.purgeCache();
+    expresso_mail_archive.turnOffLocalTreeStructure();
+}
+
+//getFaultInfo callback Fail
+MailArchiver.prototype.getFaultInfoOperationFailure = function(errorCode, errorDesc){
+    try{
+        write_msg(get_lang('SoapFault capture fails at:' + errorCode + ' | ' + errorDesc, false));
+    } catch(e){
+        write_msg(get_lang('Service error mapping', false));
+    }    
+}
+
+//createFolder operation
+MailArchiver.prototype.createFolder = function(parentFolder, folderName){
+    
+    try{
+        //ArchiveServices.createFolder(expresso_mail_archive.createFolderOperationOK, expresso_mail_archive.createFolderOperationFailure, sessid, parentFolder, folderName);
+        ArchiveServices.createFolder(expresso_mail_archive.createFolderOperationOK, expresso_mail_archive.createFolderOperationFailure, expresso_mail_archive.session.id, parentFolder, folderName);
+    }
+    catch (e){
+        expresso_mail_archive.getFaultInfo();
+    } 
+    
+}
+
+//createFolder callback OK
+MailArchiver.prototype.createFolderOperationOK = function (folderObject){
+    //window.alert('callback de createfolderoperationok');
+    draw_tree_local_folders();
+    //expresso_mail_archive.drawdata.treeObject._drawn = true;
+    //ttreeBox.update_folder();    
+}
+
+//createFolder callback Fail
+MailArchiver.prototype.createFolderOperationFailure = function (message){
+    window.alert('Folder creation fails...\n->' + message.getReturn()); 
+}
+
+//deleteFolder operation
+MailArchiver.prototype.deleteFolder = function(folderName){
+    try{
+        ArchiveServices.deleteFolder(expresso_mail_archive.deleteFolderOperationOK, expresso_mail_archive.deleteFolderOperationFailure, expresso_mail_archive.session.id, folderName, true);
+    }
+    catch (e){
+        expresso_mail_archive.getFaultInfo();
+    } 
+    
+}
+
+//deleteFolder callback OK
+MailArchiver.prototype.deleteFolderOperationOK = function (folderObject){
+    write_msg(get_lang("The local folder \"%1\" was successfully removed", expresso_mail_archive.drawdata.folderName));
+    connector.purgeCache();
+    ttreeBox.name_folder = "root";
+    ttreeBox.update_folder();
+    draw_tree_local_folders();
+    ttreeBox.update_folder();	
+}
+
+//deleteFolder callback Fail
+MailArchiver.prototype.deleteFolderOperationFailure = function (message){
+    expresso_mail_archive.getFaultInfo();
+}
+
+//renameFolder operation
+MailArchiver.prototype.renameFolder = function(folderId, newFolderName){
+    try{
+        //ArchiveServices.renameFolder(expresso_mail_archive.renameFolderOperationOK, expresso_mail_archive.renameFolderOperationFailure, sessid, folderId, newFolderName);
+        ArchiveServices.renameFolder(expresso_mail_archive.renameFolderOperationOK, expresso_mail_archive.renameFolderOperationFailure, expresso_mail_archive.session.id, folderId, newFolderName);
+    }
+    catch (e){
+        expresso_mail_archive.getFaultInfo();
+    } 
+    
+}
+
+//renameFolder callback OK
+MailArchiver.prototype.renameFolderOperationOK = function (returnService){
+    var evalobjectTree = eval(expresso_mail_archive.drawdata.treeName);
+    evalobjectTree.update_folder();
+}
+
+//renameFolder callback Fail
+MailArchiver.prototype.renameFolderOperationFailure = function (ServiceFault){
+    expresso_mail_archive.getFaultInfo();
+}
+
+//getFolderInfo operation
+MailArchiver.prototype.getFolderInfo = function (folderId){
+    try{
+        if(folderId == 'local_root')
+            folderId = "";
+        ArchiveServices.getFolderInfo(expresso_mail_archive.getFolderInfoOperationOK, expresso_mail_archive.getFolderInfoOperationFailure, expresso_mail_archive.session.id, folderId);
+    }
+    catch (e){
+        expresso_mail_archive.getFaultInfo();
+    }     
+}
+
+//getFolderInfo callback OK
+MailArchiver.prototype.getFolderInfoOperationOK = function(returnService){
+   var folder_info = {id : returnService.getReturn().getId(), name : returnService.getReturn().getName(), parent : returnService.getReturn().getParentId(), numfolders: returnService.getReturn().getFolderCount(), nummessages: returnService.getReturn().getMessageCount(), unseen: returnService.getReturn().getUnseenCount(), path: returnService.getReturn().getPath()};
+   expresso_mail_archive.folder = folder_info;
+   expresso_mail_archive.updateCounter();
+}
+
+//getFolderInfo callback Fail
+MailArchiver.prototype.getFolderInfoOperationFailure = function (ServiceFault){
+    window.alert('getFolderInfo service fails...\n->' + ServiceFault.getReturn()); 
+    expresso_mail_archive.folder_data = true;
+}
+
+function foo(){
+    var a = 0;
+    a++;
+}
+
+
+/**
+ *delete All Messages
+ *
+ *@author Thiago Rossetto Afonso [thiago@prognus.com.br]
+ *
+ *@param folderId - folder id to get all messages that it has
+ */
+
+MailArchiver.prototype.deleteAllMessages = function(folderId){
+    try{
+        var objfolder = new Object();
+        objfolder.folder = folderId;
+
+        var query_data = expresso_mail_archive.queryconfig.query(objfolder);
+
+        ArchiveServices.listMessages(expresso_mail_archive.deleteMsgsOperationOK, expresso_mail_archive.deleteMsgsOperationFailure, expresso_mail_archive.session.id, query_data);
+    }catch(e){
+        expresso_mail_archive.getFaultInfo();
+    }
+}
+MailArchiver.prototype.deleteMsgsOperationOK = function(returnService){
+    var msgsArray = new Array();
+    var msgs = "";
+    for(var i=0; i< returnService.getReturn().length; i++){
+        msgsArray.push(returnService.getReturn()[i]._id);    
+    }  
+    msgs = msgsArray.join(",");
+
+    MailArchiver.prototype.deleteMessages(msgs);
+}
+MailArchiver.prototype.deleteMsgsOperationFailure = function(){
+    alert("Your Messages weren't deleted.");
+}
+
+//listMessages operation
+//OLD local_messages.prototype.get_local_range_msgs = function(folder,msg_range_begin,emails_per_page,sort,sort_reverse,search,preview_msg_subject,preview_msg_tip) {
+//ONLINE messages_proxy.prototype.messages_list = function(folder,msg_range_begin,emails_per_page,sort_box_type,search_box_type,sort_box_reverse,preview_msg_subject,preview_msg_tip,call_back,tree_name) {
+//sys call = 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);
+MailArchiver.prototype.listMessages = function(folderId){
+    try{
+        connector.showProgressBar();
+        var getcurrent = get_current_folder();       
+        //tree_folders.getNodeById(get_current_folder())._select();
+        var folderid;
+        if(typeof(folderId) != "undefined"){
+            folderid = folderId;
+        } else {
+            folderid = this.currentfolder;    
+        }
+        var objfolder = new Object();
+        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.currentfolder = folderid;
+        
+
+        //ArchiveServices.listMessages(expresso_mail_archive.listMessagesOperationOK, expresso_mail_archive.listMessagesOperationFailure, sessid, query_data);
+        ArchiveServices.listMessages(expresso_mail_archive.listMessagesOperationOK, expresso_mail_archive.listMessagesOperationFailure, expresso_mail_archive.session.id, query_data);
+    }
+    catch (e){
+        expresso_mail_archive.getFaultInfo();
+    }
+}
+
+//listMessages callback OK
+MailArchiver.prototype.listMessagesOperationOK = function(returnService){
+    var msglist = new Array();
+    expresso_mail_archive.ServiceReturnObjectList = new Array();
+    //window.alert('messages data\n\n' + print_r(returnService.getReturn().length));
+    /*window.alert('Dados da mensagem:\n->From ' + returnService.getReturn()[0].getFrom()
+                                      +'\n->To ' + returnService.getReturn()[0].getTo()
+                                      +'\n->Subject ' + returnService.getReturn()[0].getSubject()
+                                      +'\n->Date ' + returnService.getReturn()[0].getDate()
+                                      +'\n->Date ' + returnService.getReturn()[0].getSize()
+                                      +'\n->ID ' + returnService.getReturn()[0].getId());
+    */
+    var msg_unseen_count = 0;
+    for(var i=0; i< returnService.getReturn().length; i++){
+        var ExpSerialized = expresso_mail_archive.pattern.toExpressoHeader(returnService.getReturn()[i]);
+        var msgitem = connector.unserialize(ExpSerialized);
+        //counts unseen messages
+        if(msgitem.Unseen == 'U')
+            msg_unseen_count++;
+      
+        // correÃ§Ã£o para por no padrao certo, se nao fizer isso buga a listagem
+        msgitem_temp = msgitem.msg_sample;
+        msgitem.msg_sample = { "body": msgitem_temp };
+        msglist.push(msgitem);//usando connector.unserialize sobre o header mapeado no layout abaixo
+        expresso_mail_archive.ServiceReturnObjectList.push(returnService.getReturn()[i]); //add each one service return data into this embeded object array
+    }
+    var tab_counters = expresso_mail_archive.getFolderCounters();
+    
+    //msglist["num_msgs"] = returnService.getReturn().length;
+    //window.alert('service return length = ' + returnService.getReturn().length + '\nfolder.nummessages = ' + expresso_mail_archive.folder.nummessages);
+    
+    //window.alert('folder counters:\n' + print_r(tab_counters));
+
+    //msglist["num_msgs"] = expresso_mail_archive.folder.nummessages;
+    msglist["num_msgs"] = tab_counters[0];
+    //window.alert('num msgs');
+    //(expresso_mail_archive.folder.unseen) ? msglist["tot_unseen"] = expresso_mail_archive.folder.unseen : msglist["tot_unseen"] = 0;
+    (tab_counters[1] != 0) ? msglist["tot_unseen"] = tab_counters[1] : msglist["tot_unseen"] = 0;
+//    window.alert('num unseen');
+    //window.alert('print_r\n\n' + print_r(msglist));
+   
+    //expresso_mail_archive.updateCounter(returnService.getReturn().length, msg_unseen_count);    
+    expresso_mail_archive.messageslisted = msglist;
+    expresso_mail_archive.drawdata = {messagesList:msglist};
+    //expresso_mail_archive.drawMessagesList();
+    //expresso_mail_archive.drawMessagesList(returnService.getReturn().length, msg_unseen_count);
+    //expresso_mail_archive.drawMessagesList(msglist["num_msgs"], msg_unseen_count);
+    expresso_mail_archive.drawMessagesList(msglist["num_msgs"], msglist['tot_unseen']);
+    connector.hideProgressBar();
+}
+
+//listMessages callback Fail
+MailArchiver.prototype.listMessagesOperationFailure = function(ServiceFault){
+    window.alert('listmessages FALHOU!\n' + ServiceFault.getReturn());
+}
+
+//List all messages by folder given and set a array with all messages ids
+MailArchiver.prototype.listAllMessagesByFolder = function(folderid){
+    try{
+        var query_messages = '{"query":{"folder":[{"@id":"'+folderid+'"}], "order":[{"@asc":"date"}]}}';
+        ArchiveServices.listMessages(expresso_mail_archive.listAllMessagesByFolderOperationOK, expresso_mail_archive.listAllMessagesByFolderOperationFailure, expresso_mail_archive.session.id, query_messages);
+    }
+    catch (e){
+        expresso_mail_archive.getFaultInfo();
+    }
+}
+
+//listAllMessagesByFolder callback OK
+MailArchiver.prototype.listAllMessagesByFolderOperationOK = function(returnService){
+    var msglist = new Array();
+    for(var i=0; i< returnService.getReturn().length; i++){
+        msglist.push(returnService.getReturn()[i]._id);
+    }
+    expresso_mail_archive.allmessagesbyfolder = msglist;
+}
+
+//listAllMessagesByFolder callback Fail
+MailArchiver.prototype.listAllMessagesByFolderOperationFailure = function(ServiceFault){
+    window.alert('listAllmessagesByFolder FALHOU!\n' + ServiceFault.getReturn());
+}
+
+MailArchiver.prototype.getFolderMessagesNumber = function(){
+    var n = 0;
+    for(var i=0; i < expresso_mail_archive.folders.length; i++){
+        if(expresso_mail_archive.folders[i]["id"] == expresso_mail_archive.currentfolder){
+            n = expresso_mail_archive.folders[i]["messages"];
+        }
+    }
+    return(n);
+}
+
+MailArchiver.prototype.drawMessagesList = function(msgtot, msgunseen){
+    //window.alert('no drawMessagesList com folder = ' + expresso_mail_archive.currentfolder  + '\nudatecounters = ' + expresso_mail_archive.udatecounters);
+    var data_to_draw = expresso_mail_archive.drawdata.messagesList;  
+    //window.alert('data to draw =  ' + data_to_draw.length + '\ndata_to_draw[0].from.full = ' + print_r(data_to_draw));
+    //window.alert('Current folder = ' + expresso_mail_archive.currentfolder + ' com ' + expresso_mail_archive.folders.length + ' folders.');
+    var fcaption = expresso_mail_archive.currentfolder;
+    
+    /*for (var w=0; w < expresso_mail_archive.folders.length; w++){
+        //window.alert('comparando folder "' + expresso_mail_archive.folders[w]["id"] + '" com o corrente "' + expresso_mail_archive.currentfolder + '"\nEnquanto que o folder.name obtido do getfolderinfo Ã© "' + expresso_mail_archive.folder.name + '"');
+        if(expresso_mail_archive.folders[w]["id"] == expresso_mail_archive.currentfolder){
+            fcaption = expresso_mail_archive.folders[w]["name"];
+            window.alert('folder found!\n -> ' + fcaption);
+            break;
+        }
+    }*/
+    
+    var fcaption = expresso_mail_archive.folder.name;
+    
+    /*window.alert('fcaption = ' + fcaption);
+    var udate_tree_folder = expresso_mail_archive.drawdata.treefolder;
+    window.alert('atualizar contador da ï¿œrvore : ' + udate_tree_folder);
+    var udate_tab_folder = expresso_mail_archive.drawdata.tabfolder;
+    window.alert('atualizar contador da tab : ' + udate_tab_folder);*/
+    //var folder_num_msgs = expresso_mail_archive.getFolderMessagesNumber();
+    var folder_num_msgs = expresso_mail_archive.folder.nummessages;
+    //window.alert('num = ' + folder_num_msgs);
+
+    Element("border_id_0").innerHTML = "&nbsp;" + lang_folder(fcaption) + '&nbsp;<font face="Verdana" size="1" color="#505050">[<span id="new_m">&nbsp;</span> / <span id="tot_m"></span>]</font>';
+    draw_box(data_to_draw, 'local_' + expresso_mail_archive.currentfolder, true);
+    //draw_paging(expresso_mail_archive.drawdata.messagesList.length);
+    //draw_paging(preferences.max_email_per_page);
+    draw_paging(folder_num_msgs);    
+    if(((msgtot) && (msgunseen)) || ((parseInt(msgtot)==0)&&(parseInt(msgunseen)==0))){
+        Element('new_m').innerHTML = '<font color="RED">'+$(".tr_msg_unread").length+'</font>';
+    }
+    else{
+        Element("tot_m").innerHTML = folder_num_msgs;
+        Element('new_m').innerHTML = data_to_draw['tot_unseen'] ? '<font color="RED">'+data_to_draw['tot_unseen']+'</font>' : 0;
+    }
+}
+
+MailArchiver.prototype.getMessageHeaders = function(msgId){
+    var msgfound = false;
+    var headerMsg;
+        
+    //Get message header info, from message list operation previously invoked
+    for (var w=0; w < expresso_mail_archive.messageslisted.length; w++){
+        if(expresso_mail_archive.messageslisted[w]["msg_number"] == msgId){
+            headerMsg = expresso_mail_archive.messageslisted[w];
+            msgfound = true;
+            break;
+        }
+    }
+    
+    //Message does not exists at default message list previouslly invoked. Then, will be tryed to get it at possible search criteria existing tab.
+    if(!msgfound){
+        //Try to discover if desired message is at a search local data tab
+        if(currentTab.toString().indexOf("search_local") != -1){
+	    var msgId2 = msgId.substr(0,msgId.indexOf("_s"));            
+            for (var w=0; w < expresso_mail_archive.search_message_list.length; w++){
+                if(expresso_mail_archive.search_message_list[w]["msg_number"] == msgId2){
+                    headerMsg = expresso_mail_archive.search_message_list[w];
+                    msgfound = true;
+                    break;
+                }
+            }
+       
+        }
+    }
+    
+    //The message was found, as well the her headers
+    if(msgfound){
+        expresso_mail_archive.currentheaders = headerMsg;
+        return(headerMsg);
+    }
+    //The message was not found   
+    else{
+        headerMsg = null;
+        expresso_mail_archive.currentheaders = headerMsg;        
+        return;
+    }
+}
+
+
+
+MailArchiver.prototype.getSomeMsgs = function(msgIds){
+    try{
+       expresso_mail_archive.getSomeMsg = new Array();
+       for(var i=0; i < msgIds.length; i++){
+           expresso_mail_archive.getSomeMsg.push(expresso_mail_archive.getMessageHeaders(msgIds[i]));
+       }
+       
+   }catch(e){
+
+   }
+} 
+
+MailArchiver.prototype.getMessage = function(msgdata){
+    try{
+        if((msgdata.length <= 0) || (msgdata == null)){
+            return;
+        }
+        expresso_mail_archive.currentmessage = expresso_mail_archive.getMessageHeaders(msgdata)["msg_number"];
+        ArchiveServices.getMessageBody(expresso_mail_archive.getMessageOperationOK, expresso_mail_archive.getMessageOperationFailure, expresso_mail_archive.session.id, expresso_mail_archive.currentmessage);
+    }
+    catch(e){
+        expresso_mail_archive.getFaultInfo();
+    }
+}
+
+MailArchiver.prototype.getMessageOperationOK = function(returnService){    
+    if(returnService.getReturn().length <= 0){
+        window.alert('Oh no: service return data is zero length...');
+        return;
+    }    
+    var msgBody = returnService.getReturn();
+    //var msgHeaders = expresso_mail_archive.getMessageHeaders(expresso_mail_archive.currentmessage);
+    var msgHeaders = expresso_mail_archive.currentheaders;
+    var expSerializedMessage = expresso_mail_archive.pattern.toExpressoMail(msgHeaders, msgBody);
+    
+    // Unset \\Unseen flag
+    for (i=0; i < expresso_mail_archive.messageslisted.length; i++)
+    {
+        if (expresso_mail_archive.messageslisted[i].msg_number == expresso_mail_archive.currentmessage)
+        {
+            expresso_mail_archive.messageslisted[i]['Unseen'] = '';
+        }
+    }
+    
+    //window.alert('Serialized data\n\n' + print_r(expSerializedMessage));
+    //expresso_mail_archive.showEmbededImage(msgBody);
+    show_msg(expSerializedMessage);    
+    window.setTimeout("expresso_mail_archive.setEmbeddedLink()", 1);
+}
+MailArchiver.prototype.getMessageOperationFailure = function(ServiceFault){
+    window.alert('Message fails do be loaded.');
+}
+
+/*
+ *getMessageServiceObjet: search for a remote webservice object in memory to use
+ *draw interface. Look at messages list first, then, search list. Returns desired
+ *object, or null (if not found)
+ **/
+MailArchiver.prototype.getMessageServiceObject = function(msgid){
+    var flag_found = false;
+    var rtn_obj = null;
+    
+    //Message list
+    if(expresso_mail_archive.ServiceReturnObjectList != null){
+        for(var i=0; i < expresso_mail_archive.ServiceReturnObjectList.length; i++){
+            if (expresso_mail_archive.ServiceReturnObjectList[i].getId() == msgid){
+                flag_found = true;
+                rtn_obj = expresso_mail_archive.ServiceReturnObjectList[i];
+            }
+        }
+    }
+       
+    //Search list
+    if(!flag_found){
+        if(expresso_mail_archive.ServiceReturnObjectSearch != null){
+            for(var i=0; i < expresso_mail_archive.ServiceReturnObjectSearch.length; i++){
+                if (expresso_mail_archive.ServiceReturnObjectSearch[i].getId() == msgid){
+                    flag_found = true;
+                    rtn_obj = expresso_mail_archive.ServiceReturnObjectSearch[i];
+                }
+            }
+        }        
+    }
+    return(rtn_obj);
+}
+
+
+MailArchiver.prototype.tagMessage = function(taglist){
+    try{
+        if(!taglist)
+            taglist = expresso_mail_archive.taglist;
+        //ArchiveServices.tagMessages(expresso_mail_archive.tagMessagesOperationOK, expresso_mail_archive.tagMessagesOperationFailure, sessid, taglist);
+        ArchiveServices.tagMessages(expresso_mail_archive.tagMessagesOperationOK, expresso_mail_archive.tagMessagesOperationFailure, expresso_mail_archive.session.id, taglist);
+    } catch (e){
+        //window.alert('TagMessage fails at: ' + (e.description)?e.description:e);
+        expresso_mail_archive.getFaultInfo();
+    }     
+}
+
+MailArchiver.prototype.tagMessagesOperationOK = function(serviceData){
+    //ajustar os contadores de lida/nao lida etc...
+    if((expresso_mail_archive.currenttag != '') && (expresso_mail_archive.tagmsg == true)){
+        write_msg(get_lang('Messages marked as "%1"', get_lang(expresso_mail_archive.currenttag)));
+        expresso_mail_archive.tagmsg = false;
+    }
+    
+    expresso_mail_archive.currenttag = "";
+    expresso_mail_archive.taglist = "";
+
+    //window.alert('expresso_mail_archive.folder_origin = ' + expresso_mail_archive.folder_origin  + '\nexpresso_mail_archive.current_folder = ' + get_current_folder());
+
+    if((expresso_mail_archive.drawdata) && (get_current_folder() == expresso_mail_archive.folder_origin)){
+        expresso_mail_archive.drawFolderTree();
+        expresso_mail_archive.listMessages();
+        //expresso_mail_archive.drawdata = null;
+        window.clearTimeout(expresso_mail_archive.progressbar);
+    }
+    else{
+        /*
+        connector.purgeCache();
+        ttreeBox.name_folder = "local_" + expresso_mail_archive.currentfolder;
+        draw_tree_local_folders();
+        ttreeBox.update_folder(true);*/
+    }
+}
+
+MailArchiver.prototype.tagMessagesOperationFailure = function(serviceData){
+    var str_tag_fail = serviceData.getReturn();
+    expresso_mail_archive.getFaultInfo();
+}
+
+MailArchiver.prototype.download_all_msg_attachments = function(msgid){
+    var default_format = 'zip'; //tar, jar, gzip, bz2 supports too
+    var url = expresso_mail_archive.pattern.download_compressed_attachments(msgid, default_format);
+    //window.open(url,"mywindow","width=1,height=1,scrollbars=no");
+    location.href = url;
+}
+
+MailArchiver.prototype.download_msg_source = function (format){
+    //Default export format is zip
+    if(!format)
+        format = 'zip';
+    
+    expresso_mail_archive.exportformat = format;
+    
+    if (openTab.type[currentTab] > 1){
+	var msgs_id = currentTab.substring(0,currentTab.length-2,currentTab);
+    }else{
+	var msgs_id = get_selected_messages();
+    }    
+    
+    var vetmsg = msgs_id.split(",");
+    if(vetmsg.length > 0){
+        var arr_msg = new Array();
+        for(var k=0; k<vetmsg.length; k++){
+            arr_msg.push(vetmsg[k]);
+        }            
+    }
+    else var arr_msg = new Array(msgs_id);
+   
+    var messages_array = {"format": format, "type": 'messages', "messages": arr_msg};
+    var texp = expresso_mail_archive.pattern.zipConfig(messages_array);
+    
+    if(texp != null){
+        try{
+            //ArchiveServices.zipMessages(expresso_mail_archive.download_mgs_sourceOperationOK, expresso_mail_archive.download_msg_sourceOperationFailure, sessid, texp);
+            ArchiveServices.zipMessages(expresso_mail_archive.download_mgs_sourceOperationOK, expresso_mail_archive.download_msg_sourceOperationFailure, expresso_mail_archive.session.id, texp);
+        }
+        catch(e){
+            //window.alert('Export local messages fails: ' + (e.description)?e.description:e);
+            expresso_mail_archive.getFaultInfo();
+        }
+    }
+}
+
+MailArchiver.prototype.download_mgs_sourceOperationOK = function(serviceData){
+  if(serviceData.getReturn().length > 0){
+      window.location.href = mail_archive_protocol + "://" + mail_archive_host + ":" + mail_archive_port + "/temp/mails_" + serviceData.getReturn() + '.' + expresso_mail_archive.exportformat;
+  }
+  else{
+      
+  }
+}
+
+MailArchiver.prototype.download_mgs_sourceOperationFailure = function(serviceFail){
+  window.alert('ZipMessages FAIL:' + serviceFail.getReturn());  
+}
+
+MailArchiver.prototype.export_local_messages = function(folderid, recursive, format){
+    //Default export format is zip
+    if(!format)
+        format = 'zip';
+    
+    expresso_mail_archive.exportformat = format;    
+    if(folderid == 'root')//export root local folder
+        var messages_array = {"format": format, "type": 'folder', "recursive" : true, "messages": ""};
+    else//export local folder entry
+        var messages_array = {"format": format, "type": 'folder', "recursive" : recursive, "messages": folderid};
+    var texp = expresso_mail_archive.pattern.zipConfig(messages_array);
+    
+    if(texp != null){
+        try{
+            ArchiveServices.zipMessages(expresso_mail_archive.download_mgs_sourceOperationOK, expresso_mail_archive.download_msg_sourceOperationFailure, expresso_mail_archive.session.id, texp);
+        }
+        catch(e){
+            //window.alert('Export local messages fails: ' + (e.description)?e.description:e);
+            expresso_mail_archive.getFaultInfo();
+        }
+    }    
+}
+
+MailArchiver.prototype.updateCounter = function(a,b){
+    //window.alert('updateCounter reached');
+
+    if(((a) && (b)) || ((parseInt(a)==0)&&(parseInt(b)==0))){
+        //Element("tot_m").innerHTML = a;
+        Element('new_m').innerHTML = (b >= 0) ? '<font color="RED">'+b+'</font>' : 0; 
+        return;
+    }
+    
+    if(expresso_mail_archive.update_counters == true){
+        connector.purgeCache();
+        var elm_tree = Element('llocal_'+expresso_mail_archive.folder.id+'tree_folders');
+        
+        if(elm_tree){
+        
+        //search appropriate "unseen" span to handle with
+        for(var j=0; j<elm_tree.childNodes.length; j++){
+            if (elm_tree.childNodes[j].nodeName.toLowerCase() == 'span'){
+                var elm = elm_tree.childNodes[j];
+                break;
+            }        
+        }
+    
+        if(expresso_mail_archive.folder.unseen > 0){
+            if (elm){
+                elm.innerHTML = expresso_mail_archive.folder.unseen;
+            }                
+            else{
+                var htm_el = document.createElement('font');
+                htm_el.style.color = 'red';
+                document.getElementById('llocal_'+expresso_mail_archive.folder.id+'tree_folders').appendChild(htm_el);    
+                htm_el.innerHTML = '&nbsp(';
+                
+                var spn_el = document.createElement('span');
+                spn_el.id = 'dftree_'+expresso_mail_archive.folder.id+'_unseen';
+                spn_el.style.color = 'red';
+                document.getElementById('llocal_'+expresso_mail_archive.folder.id+'tree_folders').appendChild(spn_el);
+                spn_el.innerHTML = expresso_mail_archive.folder.unseen;
+                
+                var htm2_el = document.createElement('font');
+                htm2_el.style.color = 'red';
+                document.getElementById('llocal_'+expresso_mail_archive.folder.id+'tree_folders').appendChild(htm2_el);    
+                htm2_el.innerHTML = ')';
+            }
+        }
+        else{
+            if(elm){
+                var spn = elm.parentNode.parentNode;
+                elm.parentNode.removeChild(elm.previousSibling);
+                elm.parentNode.removeChild(elm.nextSibling);
+                elm.parentNode.removeChild(elm);
+            }
+        }
+
+        //reset pointer to re-do working to move messages (2 folders envolved)
+        if (expresso_mail_archive.folder_destination != null){
+            if(expresso_mail_archive.currentfolder == expresso_mail_archive.folder_destination){
+                expresso_mail_archive.update_counters = false;
+            }
+            else{
+                //window.alert('aqui, queima o folder_destination');
+                //expresso_mail_archive.folder_destination = null;
+            }            
+        }
+        else{
+            expresso_mail_archive.update_counters = false;
+        }
+    }
+    }
+    //no counter needs 
+    else return;
+}
+
+MailArchiver.prototype.getBase64PartData = function(partid, field){
+    var spid = new String(partid);
+    if(parseInt(spid.length) > 0){
+        expresso_mail_archive.tmp_att_datasource = field;
+        try{
+            //ArchiveServices.getRawBinaryBody(expresso_mail_archive.getBase64PartDataOK, expresso_mail_archive.getBase64PartDataFailure, sessid, partid);
+            ArchiveServices.getRawBinaryBody(expresso_mail_archive.getBase64PartDataOK, expresso_mail_archive.getBase64PartDataFailure, expresso_mail_archive.session.id, partid);
+        }
+        catch(e){
+            //window.alert('Fail to getRawBinaryBody data from part id ' + partid + ':\n' + (e.description)?e.description:e);
+            expresso_mail_archive.getFaultInfo();
+        }
+    }
+    else {
+        return(null);
+    }
+}
+
+MailArchiver.prototype.getBase64PartDataOK = function(serviceData){
+    var encdata = serviceData.getReturn();
+    if(encdata.length <= 0){
+        window.alert('Oh no: service return data is zero length...');
+        this.tmp_att_data = null;
+    }    
+    else{
+        expresso_mail_archive.tmp_att_datasource.value = encdata;
+    }
+}
+
+MailArchiver.prototype.getBase64PartDataFailure = function(serviceReturn){
+    window.alert('There are erros on getting binary data part:' + serviceReturn.getReturn());
+}
+
+MailArchiver.prototype.search = function(folders,fields){
+    try{
+        connector.showProgressBar();
+        if((folders) && (fields)){
+            expresso_mail_archive.search_queryconfig.reset();
+            var folderlist = expresso_mail_archive.search_queryconfig.pharseFolders(folders);
+            var filters = eval('(' + expresso_mail_archive.queryconfig.pharseSearchFields(fields) + ')');
+
+            if(folderlist.indexOf("#") != -1)
+                filters.folder = folderlist.substr(0, folderlist.indexOf("#"));
+            else
+                filters.folder = folderlist;
+            if(folderlist.toLowerCase().indexOf("#recursive") != -1)
+                expresso_mail_archive.search_queryconfig.folder_recursive = true;
+            else
+                expresso_mail_archive.search_queryconfig.folder_recursive = false;
+
+            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);        
+        }
+        //changing order view criteria (sorting result)
+        else{    
+            ArchiveServices.listMessages(expresso_mail_archive.searchOperationOK, expresso_mail_archive.searchOperationFailure, expresso_mail_archive.session.id, expresso_mail_archive.querydata);        
+        }
+    }catch (e){
+        expresso_mail_archive.getFaultInfo();
+    }
+}
+
+MailArchiver.prototype.searchOperationOK = function(returnService){
+    if(returnService.getReturn().length > 0){
+        var msglist = new Array();
+        var msglist2 = new Array();
+        expresso_mail_archive.ServiceReturnObjectSearch = new Array();
+
+        for(var i=0; i< returnService.getReturn().length; i++){
+            var ExpSerialized = expresso_mail_archive.pattern.toExpressoSearchHeader(returnService.getReturn()[i]);
+            var ExpSerialized2 = expresso_mail_archive.pattern.toExpressoHeader(returnService.getReturn()[i]);
+            var msgitem = connector.unserialize(ExpSerialized);
+            var msgitem2 = connector.unserialize(ExpSerialized2);
+      
+            msglist.push(msgitem);//usando connector.unserialize sobre o header mapeado no layout abaixo
+            msglist2.push(msgitem2);
+            expresso_mail_archive.ServiceReturnObjectSearch.push(returnService.getReturn()[i]); //add each one service return data into this embeded object array
+            
+        }
+        msglist["num_msgs"] = returnService.getReturn().length;
+        msglist2["num_msgs"] = returnService.getReturn().length;
+            
+        //expresso_mail_archive.queryresult = msglist;        
+        expresso_mail_archive.search_queryresult = msglist;    
+        //expresso_mail_archive.messageslisted = msglist2;
+        expresso_mail_archive.search_message_list = msglist2;
+        //window.alert('temos ' + expresso_mail_archive.search_message_list.length + ' mensagens de resultado da pesquisa mapeadas em memï¿œria');
+    }
+    else{
+        expresso_mail_archive.ServiceReturnObjectSearch = null;
+        expresso_mail_archive.search_queryresult        = null;
+        expresso_mail_archive.search_message_list       = null;
+        expresso_mail_archive.messageslisted            = null;
+        expresso_mail_archive.queryresult               = null;
+    } 
+    connector.hideProgressBar();
+}
+
+MailArchiver.prototype.searchOperationFailure = function(){
+    write_msg(get_lang('MailArchiver search operation fails', true));
+    expresso_mail_archive.ServiceReturnObjectSearch = null;
+    expresso_mail_archive.search_queryresult        = null;
+    expresso_mail_archive.search_message_list       = null;
+    expresso_mail_archive.messageslisted            = null;
+    expresso_mail_archive.queryresult               = null;
+    connector.hideProgressBar();
+}
+
+MailArchiver.prototype.getAuthId = function(){
+    var handler_get_logon = function(data){
+        if(data){
+            expresso_mail_archive.balancerid = data[0];
+            expresso_mail_archive.sessionid = data[1];
+            expresso_mail_archive.logonid = new Array(data[2],data[3]);
+            expresso_mail_archive.login();
+        }
+        else{
+            window.alert('Login credentials call failure');
+            expresso_mail_archive.session = null;
+        }
+    }
+    cExecute("$this.user.get_mailarchiver_authid",handler_get_logon);     
+}
+
+MailArchiver.prototype.login = function(){
+    try{
+        ArchiveServices.login(expresso_mail_archive.loginOperationOK, expresso_mail_archive.loginOperationFailure, expresso_mail_archive.logonid[0], expresso_mail_archive.logonid[1], expresso_mail_archive.sessionid, expresso_mail_archive.balancerid);
+    }
+    catch(e){
+        expresso_mail_archive.getFaultInfo();
+    }
+}
+
+MailArchiver.prototype.loginOperationOK = function(returnService){
+    if((typeof(returnService.getReturn()) == 'object') && (returnService.getReturn() != null)){
+        expresso_mail_archive.session = new Object();
+        expresso_mail_archive.session.expiration = returnService.getReturn().getExpiration();
+        expresso_mail_archive.session.id = returnService.getReturn().getId();
+        expresso_mail_archive.session.permissions = returnService.getReturn().getPermissions();
+        expresso_mail_archive.CreateDefaultStructrure();
+    }
+    else{
+        //not logged in MailArchiver
+        expresso_mail_archive.session = null;
+        write_msg(get_lang('MailArchiver user login fail', true));
+        expresso_mail_archive.enabled = false;
+        expresso_mail_archive.timer=null;
+        expresso_mail_archive.interval = 500;
+        ArchiveServices = null;
+        connector.purgeCache();        
+        draw_tree_folders();
+        //expresso_mail_archive.DeactivateStatusListener(expresso_mail_archive);
+    }
+}
+
+MailArchiver.prototype.getFolderCounters = function(){
+    var vetreturn = new Array();
+    /*for(var k=0; k<expresso_mail_archive.folders.length; k++){
+        if(expresso_mail_archive.folders[k]["id"] == expresso_mail_archive.currentfolder){
+            vetreturn.push(expresso_mail_archive.folders[k]["messages"], expresso_mail_archive.folders[k]["unseen"]);
+            break;
+        }
+    }*/
+    vetreturn.push(expresso_mail_archive.folder.nummessages, expresso_mail_archive.folder.unseen);
+    return(vetreturn);
+}
+
+MailArchiver.prototype.setEmbeddedLink = function(){
+    var img_objects = document.getElementsByTagName('img');
+    for(var k = 0; k < img_objects.length; k++){
+        if(img_objects[k].name.indexOf('embedded_img_') != -1) {
+            var obj_link = img_objects[k].name.split('embedded_img_');
+            var txt_link = obj_link[1];
+            var img_base_link = mail_archive_protocol + "://" + mail_archive_host + ":" + mail_archive_port + "/temp/" + txt_link;
+            img_objects[k].src = img_base_link;
+        }
+    }
+}
+/*
+MailArchiver.prototype.getFolderPath = function(folder){
+    try{
+        ArchiveServices.getFolderInfo(expresso_mail_archive.getFolderPathOperationOK, expresso_mail_archive.getFolderPathOperationFailure, expresso_mail_archive.session.id, folder);
+    }
+    catch(e){
+        window.alert('getFolderPath fails');
+    }
+}
+
+MailArchiver.prototype.getFolderPathOperationOK = function(serviceReturn){
+    window.alert('service return from getFolderPathOperationOK = ' + serviceReturn().getFolderPath());
+    if(serviceReturn().length>0){
+        window.alert('ok');
+    }
+    else{
+        window.alert('nope');
+    }
+}
+
+MailArchiver.prototype.getFolderPathOperationFailure = function(serviceFault){
+    window.alert('fails at gettting folder path');
+}
+*/
+
+MailArchiver.prototype.getMessageInfo = function(msgId){
+    try{
+        ArchiveServices.getMessageInfo(expresso_mail_archive.getMessageInfoOperationOK, expresso_mail_archive.getMessageInfoOperationFailure, expresso_mail_archive.session.id, msgId);
+    }
+    catch(e){
+        window.alert('getMessageInfo fails');
+    }    
+}
+
+MailArchiver.prototype.getMessageInfoOperationOK = function(serviceReturn){
+    //window.alert('service return from getMessageInfoOperationOK = ' + serviceReturn.getReturn() + '\n' + typeof(serviceReturn.getReturn()) + '\n' + print_r(serviceReturn.getReturn()));
+    if(typeof(serviceReturn.getReturn() == 'object')){
+        var ExpSerialized2 = expresso_mail_archive.pattern.toExpressoHeader(serviceReturn.getReturn());
+        var msgitem2 = connector.unserialize(ExpSerialized2);
+        expresso_mail_archive.messageslisted.push(msgitem2);    
+        window.alert('vai chamar de volta o getMessageHeaders com: \nid => ' + serviceReturn.getReturn().getId());
+        expresso_mail_archive.getMessageHeaders(serviceReturn.getReturn().getId());
+    }
+    else{
+        window.alert('getMessageInfoOperationOK nope');
+    }
+}
+
+MailArchiver.prototype.turnOffLocalTreeStructure = function (){
+     draw_new_tree_folder();  
+}
+
+MailArchiver.prototype.getMessageInfoOperationFailure = function(serviceFault){
+    window.alert('fails at gettting message info');
+}
+
+MailArchiver.prototype.loginOperationFailure = function(ServiceFaillure){
+    write_msg(get_lang('MailArchiver login operation fail', true));
+}
+
+MailArchiver.prototype.logout = function(){
+    write_msg(get_lang('MailArchiver user logged out', true));
+}
+/*
+ *The all pourpose JavaScript variable, used by all related functionalityes at
+ *Expresso Mail to handle this object at user gui.
+ */
+
+var expresso_mail_archive;
+expresso_mail_archive = new MailArchiver();
+-->
Index: trunk/expressoMail1_2/js/abas.js
===================================================================
--- trunk/expressoMail1_2/js/abas.js	(revision 6960)
+++ trunk/expressoMail1_2/js/abas.js	(revision 7414)
@@ -220,5 +220,5 @@
 			var id_border = currentTab.replace(/[a-zA-Z_]+/, "");
 			ID_TR = ID.toString().substr(0,ID.toString().indexOf("_r"));
-			var tr = Element(ID_TR);
+			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
@@ -255,5 +255,8 @@
 				cc = document.getElementById("em_message_search").value;
 			else{
-				cc = document.getElementsByName(currentTab)[0].value;
+				if (currentTab == 0)
+					cc = "";
+				else
+					cc = document.getElementsByName(currentTab)[0].value;
 			}
 		}else{
Index: trunk/expressoMail1_2/js/MAQueryConfig.js
===================================================================
--- trunk/expressoMail1_2/js/MAQueryConfig.js	(revision 7414)
+++ trunk/expressoMail1_2/js/MAQueryConfig.js	(revision 7414)
@@ -0,0 +1,657 @@
+<!--
+/**
+ *MailArchiver Query Config API
+ *
+ *This api is intended to be used with MailArquiver JavaScript API.
+ *Basicly, it is responsable to provide a standard data format conversion
+ *to handle queryes under MailArquiver web services pooling. *
+ *
+ */
+
+
+//MailArchiver Query Config data structure
+var MAQueryConfig = function(){
+  this.lowerIndex = null;
+  this.upperIndex = null;
+  this.from = null;
+  this.to = null;
+  this.cc = null;
+  this.subject = null;
+  this.body = null;
+  this.date = null;
+  this.dateLower = null;
+  this.dateUpper = null;  
+  this.tag = null;
+  this.folder = null;
+  this.folder_recursive = null;
+  this.order = null;
+  this.preview_message = null;
+  this.preview_tooltip = null;
+  this.defaults = null;
+}
+
+//Set up all criteria list received
+MAQueryConfig.prototype.setCriteriaList = function(cl){
+  //window.alert('dumpando setCriteriaList:\n' + print_r(cl));
+  for(var p in cl){
+    //window.alert('p = ' + p + '\ncl = ' + cl + '\ncl[p] = ' + cl[p] + '\np[cl] = ' + p[cl]);
+    //Decode the criteria for search.
+    cl[p] = url_decode_s(cl[p]);
+    if(p.toLowerCase() == 'all')
+      this.setSubject(cl[p]);
+    if(p.toLowerCase() == 'lowerindex')
+      this.setLowerIndex(cl[p]);    
+    if(p.toLowerCase() == 'upperindex')
+      this.setUpperIndex(cl[p]);      
+    if(p.toLowerCase() == 'from')
+      this.setFrom(cl[p]);
+    if(p.toLowerCase() == 'to')
+      this.setTo(cl[p]);
+    if(p.toLowerCase() == 'cc')
+      this.setCc(cl[p]);
+    if(p.toLowerCase() == 'subject')
+      this.setSubject(cl[p]);
+    if(p.toLowerCase() == 'body')
+      this.setBody(cl[p]);
+    if(p.toLowerCase() == 'on')
+      this.setDate('on',cl[p]);
+    if(p.toLowerCase() == 'since')
+      this.setDate('lower',cl[p]);  
+    if(p.toLowerCase() == 'before')
+      this.setDate('upper',cl[p]);  
+    if(p.toLowerCase() == 'flags')
+      this.setTag(cl[p]);
+    if(p.toLowerCase() == 'folder')
+      this.setFolder(cl[p]);
+    if(p.toLowerCase() == 'order')
+      this.setOrder(cl[p]);
+
+    //search tags window criteria mapping
+    if(p.toLowerCase() == 'flagged'){
+        var oexptag = eval('({"contains":"flagged"})'); 
+        this.setTags(oexptag);        
+    }
+    if(p.toLowerCase() == 'unflagged'){
+        var oexptag = eval('({"contains":"unflagged"})'); 
+        this.setTags(oexptag);        
+    }    
+    if(p.toLowerCase() == 'seen'){        
+        var oexptag = eval('({"contains":"seen"})'); 
+        this.setTags(oexptag);                
+    }    
+    if(p.toLowerCase() == 'unseen'){
+        var oexptag = eval('({"contains":"unseen"})'); 
+        this.setTags(oexptag);                
+    }
+    if(p.toLowerCase() == 'answered'){
+        var oexptag = eval('({"contains":"answered"})'); 
+        this.setTags(oexptag);                
+    }        
+    if(p.toLowerCase() == 'unanswered'){
+        var oexptag = eval('({"contains":"unanswered"})'); 
+        this.setTags(oexptag);                
+    }            
+  }
+}
+
+MAQueryConfig.prototype.setDefaults = function(defaults){
+    this.defaults = defaults;
+}
+
+MAQueryConfig.prototype.setExpressoDefaults = function(data_default){
+    //Expresso defaults came from "messages_controller.js": here, we maps
+    //each array entry from messages_list intended to run by our own behavior
+    if(data_default.length != 8)
+        return;
+   //expresso default argument list => new Array(baseFolder,msg_range_begin,emails_per_page,sort_box_type,search_box_type, sort_box_reverse,preview_msg_subject,preview_msg_tip);
+   this.setFolder(data_default[0]);
+   this.setLowerIndex(data_default[1]);
+   this.setUpperIndex(data_default[2]);
+   
+   if (parseInt(data_default[5]) == 0)
+       var oexpor = 'asc';
+   else
+       var oexpor = 'desc';
+   
+   //window.alert('NO MAQueryconfig setExpressoDefaults\n\nbase_folder = ' + data_default[0] + '\nmsg_range_begin = ' + data_default[1] + '\nemails_per_page = ' + data_default[2] + '\nsort_box_type =' + data_default[3].toLowerCase() + '\nsearch_box_type= ' + data_default[4] + '\nsort_box_reverse = ' + data_default[5] + '\npreview_msg_subject = ' + data_default[6] + '\npreview_msg_tip = ' + data_default[7]);
+   
+   //sets tag data filter
+   switch(data_default[4].toLowerCase()){
+    case 'all':
+        var tagtolist_criteria = 'contains';
+        var tagtolist_value = 'all';
+        break;
+    case 'unseen':
+        var tagtolist_criteria = 'contains';
+        var tagtolist_value = 'unseen';
+        break;
+    case 'seen':
+        var tagtolist_criteria = 'contains';
+        var tagtolist_value = 'seen';        
+        break;
+    case 'answered':
+        var tagtolist_criteria = 'contains';
+        var tagtolist_value = 'answered';        
+        break;
+    case 'unanswered':
+        var tagtolist_criteria = 'contains';
+        var tagtolist_value = 'unanswered';        
+        break;        
+    case 'flagged':
+        var tagtolist_criteria = 'contains';
+        var tagtolist_value = 'flagged';        
+        break;  
+    case 'unflagged':
+        var tagtolist_criteria = 'contains';
+        var tagtolist_value = 'unflagged';        
+        break;        
+    default:
+        var tagtolist_criteria = null;
+        var tagtolist_value = null;        
+   }
+
+   //sets TagConfig
+   var oexptag = eval('({"' + tagtolist_criteria + '":"' + tagtolist_value + '"})'); 
+   this.setTags(oexptag);
+
+
+   //sets order criteria
+   switch(data_default[3].toLowerCase()){
+       case 'sortfrom':
+           var oexpcrt = 'from';
+           break;
+       case 'sortsubject':
+           var oexpcrt = 'subject';
+           break;
+       case 'sortsize':
+           var oexpcrt = 'size';
+           break;
+       default:
+           var oexpcrt = 'date';
+           break;
+   }   
+
+   var oexporder = eval('({"' + oexpcrt + '":"' + oexpor + '"})');
+   this.setOrder(oexporder);
+}
+
+//PharseCriteria receives data to pharse structure format fields from, to, cc and subject
+MAQueryConfig.prototype.pharseCriteria = function(field, data, criteria){
+  //window.alert('pharseCriteria input data:\n\n-> field = ' + field + '\ndata = ' + data + '\ncriteria = ' + criteria);
+  if(!criteria)
+      criteria = 'none';
+  
+  var stdout = '"'+field+'":[';
+  switch (criteria.toLowerCase()){
+      case "equals":
+          stdout += '{"@equals":"'+data+'"},';
+          break;
+      case "equalsic":
+          stdout += '{"@equalsIgnoreCase":"'+data+'"},';
+          break;
+      case "like":
+          stdout += '{"@like":"'+data.like+'"},';
+          break;
+      default:
+          stdout+= '{"@likeIgnoreCase":"'+data+'"},';
+  }
+  stdout = stdout.substr(0,stdout.length-1) + '],';
+  return(stdout);
+}
+
+//setbounds up and down
+MAQueryConfig.prototype.setLowerIndex = function(low){
+  //window.alert('setbounds low = ' + low + ' high = ' + high);
+  this.lowerIndex = '"@lowerIndex":"'+(parseInt(low)-1)+'", ';
+}
+
+MAQueryConfig.prototype.setUpperIndex = function(high){
+  //window.alert('setbounds low = ' + low + ' high = ' + high);
+  this.upperIndex = '"@upperIndex":"'+(parseInt(high))+'", ';
+}
+ 
+//From receives a array of structutred data, by the model
+MAQueryConfig.prototype.setFrom = function(data){
+  if(data.length <= 0){
+    this.from = null;
+    return;
+  }
+  
+  //subdata = this.pharseCriteria('from', data);
+  this.from = '"@from":"' + data + '",';
+}
+
+//To receives a array of structutred data, by the model
+MAQueryConfig.prototype.setTo = function(data){
+  if(data.length <= 0){
+    this.to = null;
+    return;
+  }
+
+  //subdata = this.pharseCriteria('to', data);
+  this.to = '"@to":"' + data + '",';
+}
+
+//Cc data
+MAQueryConfig.prototype.setCc = function(data){
+  if(data.length <= 0){
+    this.cc = null;
+    return;
+  }
+
+  //subdata = this.pharseCriteria('cc', data);
+  this.cc = '"@cc":"' + data + '",';
+}
+
+//Subject data
+MAQueryConfig.prototype.setSubject = function(sub){
+  if(sub.length <= 0){
+    this.subject = null;
+    return;
+  }
+
+  //subdata = this.pharseCriteria('subject', sub);
+  this.subject = '"@subject":"' + sub + '",';
+}
+
+//PREGMatch date format
+MAQueryConfig.prototype.validateDate = function (dat){
+ var dateregex = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/;
+ if (dateregex.test(dat))
+   return true;
+ else
+   return false;
+}
+
+//PREGMatch time format
+MAQueryConfig.prototype.validateTime = function (tim){
+  //var timeregex = /^([1-9]|1[0-2]):[0-5]\d(:[0-5]\d(\.\d{1,3})?)?$/;
+  //var timeregex = /^[0-2][0-9]:[0-5][0-9]:[0-5][0-9]$/;
+  var timeregex = /^\d{1,2}[:]\d{2}([:]\d{2})?$/;
+  if (timeregex.test(tim))
+    return true;
+  else
+    return false;
+}
+
+//toStdDate returns date time as long. Format input:'DD/MM/YYYY HH:MM:SS'
+MAQueryConfig.prototype.toStdDate = function(dt){ 
+  if (dt.length <= 0)
+    return;
+
+  var date_time_picker = dt.split(" ");
+  var date_part = date_time_picker[0];
+  var time_part = date_time_picker[1];
+
+  //window.alert('date_part = ' + date_time_picker[0] + '\ntime_part = ' + date_time_picker[1]);
+
+  if ((this.validateDate(date_part)) /*&& (this.validateTime(time_part))*/){
+    var date_split = date_part.split("/");
+    var ddd = date_split[1]+'/'+date_split[0]+'/'+date_split[2] + ' ' + (time_part ? time_part : '00:00');
+    var ndate = new Date(ddd);   
+    
+    //window.alert('Date.parse (' + ddd + ') = ' + Date.parse(ndate));
+    return Math.round(ndate.getTime());//(Date.parse());
+  }
+  else
+    return("");
+}
+
+//Date data
+MAQueryConfig.prototype.setDate = function(date_field, date_data){
+  if((!date_field) || (!date_data)){
+    this.date = null;
+    this.dateLower = null;
+    this.dateUppder = null;
+    return;
+  }
+    
+  if(date_field == 'lower'){
+    if(date_data.indexOf('%') != -1)
+        var dt1b = this.pharseStdDate(date_data);
+    else
+        var dt1b = this.toStdDate(date_data);
+    this.dateLower = '"@lowerDate":"'+dt1b+'",';
+  }
+  if(date_field == 'upper'){
+    if(date_data.indexOf('%') != -1)
+        var dt2b = this.pharseStdDate(date_data);
+    else
+        var dt2b = this.toStdDate(date_data);
+    this.dateUpper = '"@upperDate":"'+dt2b+'",';
+  }
+  if(date_field == 'on'){
+    if(date_data.indexOf('%') != -1)
+        var dt3b = this.pharseStdDate(date_data);
+    else
+        var dt3b = this.toStdDate(date_data);
+    this.date = '"@date":"'+dt3b+'",';
+  }
+}
+
+//flags data
+MAQueryConfig.prototype.setTag = function(flaglist){
+  if(flaglist.flags.length <= 0){
+    this.tag = null;
+    return;
+  }
+
+  this.tag = '"flag":[';
+  var flag_data = flaglist.flags.split(',');
+  if(flag_data.length > 0){
+    for(var k=0; k<flag_data.length; k++){
+      this.tag += '{"@value":"'+flag_data[k]+'"},'
+    }
+    this.tag = this.tag.substr(0,this.tag.length-1);
+  }
+  else{
+    this.tag += '{"@value":"'+flaglist.flags+'"},';
+  }
+  this.tag += '],';
+
+}
+
+//Folder data
+MAQueryConfig.prototype.setFolder = function(folderslist){
+  if(folderslist.length <= 0){
+    this.folder = null;
+    return;
+  }
+  this.folder = '"folder":[';
+  if(this.folder_recursive){
+      var pfrec = ', "@recursive":"true"';
+  }
+  else
+      var pfrec = '';
+  
+  if (folderslist.indexOf(',') != -1){
+    var folder_data = folderslist.split(',');
+    if(folder_data.length > 0){
+        for(var k=0; k<folder_data.length; k++){
+            this.folder += '{"@id":"'+folder_data[k]+'"' + pfrec + '},'
+        }
+        this.folder = this.folder.substr(0,this.folder.length-1);
+    }
+    else{
+        this.folder += '{"@id":"'+folderslist+'"' + pfrec + '"}';
+    }
+  }
+  else{
+      this.folder += '{"@id":"' + folderslist +'"' + pfrec + '}';
+  }
+  this.folder += '],';
+}
+
+//Order criteria
+MAQueryConfig.prototype.setOrder = function(order){
+  if(typeof(order) != 'object'){
+    this.order = null;
+    return;
+  }
+
+  this.order = '"order":[';
+  for(var k in order){
+    if(k.toLowerCase().indexOf("date") != -1)
+      this.order += '{"@date":"'+order[k]+'"},';
+    if(k.toLowerCase().indexOf("from") != -1)
+      this.order += '{"@from":"'+order[k]+'"},';
+    if(k.toLowerCase().indexOf("subject") != -1)
+      this.order += '{"@subject":"'+order[k]+'"},';
+    if(k.toLowerCase().indexOf("size") != -1)
+      this.order += '{"@size":"'+order[k]+'"},';
+  }
+  this.order = this.order.substr(0,this.order.length-1) + ']';
+}
+
+//Tags criteria
+MAQueryConfig.prototype.setTags = function(taglist){
+  if(typeof(taglist) != 'object'){
+    this.tag = null;
+    return;
+  }
+  //Adding tag criteria
+  if(taglist.contains == "all"){
+    this.tag = null;
+  } else {
+      this.tag = '"tags":[';
+      if(get_current_folder().indexOf("local") != "-1"){
+          for(var k in taglist){
+            if(k != null){
+                    this.tag += '{"@contains":"'+taglist[k]+'"}],';
+            }
+          }
+      } 
+  }
+/*
+  if(this.tag != null)
+    this.tag = this.tag.substr(0, this.tag.length-2) + ', ';
+  //Creating tag criteria
+  else
+    this.tag = '"tags":[';
+  
+  for(var k in taglist){
+    if(k != null){
+        if(k.toLowerCase() == "contains"){
+            this.tag += '{"@contains":"'+taglist[k]+'"},';
+        }
+    }
+  }
+  //if no tag data was parametrizided, no one tag data will be returned
+  if(this.tag.length > 8)
+    this.tag = this.tag.substr(0,this.tag.length-1) + '],';
+  else
+    this.tag = null;
+  //if no tag data was parametrizided, no one tag data will be returned
+  */
+}
+
+//Body structrure
+MAQueryConfig.prototype.setBody = function(data){
+/*  if(body_data.length <= 0){
+    this.body = null;
+    return;
+  }
+  this.body = '"body":[';
+  for(var k in body_data){
+    if(k.toLowerCase() == "like")
+      this.body += '{"@like":"'+body_data[k]+'"},';
+    if(k.toLowerCase() == "likeic")
+      this.body += '{"@likeIgnoreCase":"'+body_data[k]+'"},';
+  }
+  this.body = this.body.substr(0,this.body.length-1) + '],';
+  */
+  if(data.length <= 0){
+    this.body = null;
+    return;
+  }
+  
+  //subdata = this.pharseCriteria('from', data);
+  this.body = '"@body":"' + data + '",';  
+}
+
+MAQueryConfig.prototype.pharseSearchFields = function(fields){
+   if(fields.length <= 0) 
+       return;
+   
+   var filters = fields.replace(/^##|##$/g,"").split('##');
+   if(filters.length > 0){
+     var filter_object = '{' ;
+     for(var k=0; k<filters.length; k++){
+       var filter_entry = filters[k].split('<=>');
+       filter_object += filter_entry[0].toLowerCase() + ':"' + filter_entry[1] + '", ';
+     }
+     filter_object = filter_object.substr(0, filter_object.length-2);
+     filter_object += '}';
+     return(filter_object);
+   }
+   else
+       return;
+}
+
+MAQueryConfig.prototype.pharseFolders = function(folderslist){
+    var folder_string_list = "";
+    if (folderslist.length > 1){
+        for(var k=0; k<folderslist.length; k++){
+            var f_criteria = folderslist[k].split("#");
+            var f_name = f_criteria[0];
+            var f_recursive = f_criteria[1];
+            folder_string_list += f_name + ',';
+        }
+        folder_string_list = folder_string_list.substr(0, folder_string_list.length-1) + '#' + f_recursive + ',';
+        folder_string_list = folder_string_list.substr(0, folder_string_list.length-1);
+    }
+    else{
+        folder_string_list = folderslist[0];
+    }
+    //window.alert('pharsefolders return = ' + folder_string_list);
+    return(folder_string_list);
+}
+
+MAQueryConfig.prototype.getLowerIndex = function(){
+  //  (this.lowerIndex != null) ? retdata = this.lowerIndex : retdata = '"@lowerIndex":"0", ';
+    (this.lowerIndex != null) ? retdata = this.lowerIndex : retdata = '';
+    return(retdata);
+}
+
+MAQueryConfig.prototype.getUpperIndex = function(){
+//    (this.upperIndex != null) ? retdata = this.upperIndex : retdata = '"@upperIndex":"' + preferences.max_email_per_page+ '", ';
+    (this.upperIndex != null) ? retdata = this.upperIndex : retdata = '';
+    return(retdata);
+}
+
+MAQueryConfig.prototype.getFrom = function(){
+    (this.from != null) ? retdata = this.from : retdata = "";
+    return(retdata);
+}
+
+MAQueryConfig.prototype.getTo = function(){
+    (this.to != null) ? retdata = this.to : retdata = "";
+    return(retdata);    
+}
+
+MAQueryConfig.prototype.getCc = function(){
+    (this.cc != null) ? retdata = this.cc : retdata = "";
+    return(retdata);    
+}
+
+MAQueryConfig.prototype.getSubject = function(){
+    (this.subject != null) ? retdata = this.subject : retdata = "";
+    return(retdata);    
+}
+
+MAQueryConfig.prototype.getBody = function(){
+    (this.body != null) ? retdata = this.body : retdata = "";
+    return(retdata);    
+}
+
+MAQueryConfig.prototype.getDate = function(){
+    (this.date != null) ? retdata = this.date : retdata = "";
+    return(retdata);    
+}
+
+MAQueryConfig.prototype.getDateLower = function(){
+    (this.dateLower != null) ? retdata = this.dateLower : retdata = "";
+    return(retdata);    
+}
+
+MAQueryConfig.prototype.getDateUpper = function(){
+    (this.dateUpper != null) ? retdata = this.dateUpper : retdata = "";
+    return(retdata);    
+}
+
+MAQueryConfig.prototype.getTag = function(){
+    (this.tag != null) ? retdata = this.tag : retdata = "";
+    return(retdata);    
+}
+
+MAQueryConfig.prototype.getFolder = function(){
+    if (this.folder != null){
+        if (this.folder_recursive){
+            var tmp_root_id = this.folder.substr(this.folder.indexOf("@id")+6, 4);
+            if(tmp_root_id == 'root')
+                retdata = "";
+            else
+                retdata = this.folder;
+        }
+        else
+            retdata = this.folder;
+    }
+    else retdata = "";
+    return(retdata);    
+}
+
+MAQueryConfig.prototype.getOrder = function(){
+    //defaults order criteria is date asc
+    (this.order != null) ? retdata = this.order : retdata = '"order":[{"@date":"desc"}]';
+    return(retdata);    
+}
+
+//Query criteria (core api)
+MAQueryConfig.prototype.query = function(criterialist){
+  //window.alert('MAQueryConfig.query\n\n - > CriteriaList:\n ' + criterialist + '[' + typeof(criterialist) + ']\ndump:\n' + print_r(criterialist));
+
+  if (criterialist){
+    this.setCriteriaList(criterialist);
+  }
+  
+  //window.alert('em qc.query com lower = ' + this.lowerIndex + ' e upper = ' + this.upperIndex);
+  var querystring = '{"query":{';
+  querystring += this.getLowerIndex();
+  querystring += this.getUpperIndex();
+  querystring += this.getDateLower();
+  querystring += this.getDateUpper();
+  querystring += this.getDate();  
+  querystring += this.getFrom();
+  querystring += this.getTo();
+  querystring += this.getCc();
+  querystring += this.getSubject();
+  querystring += this.getBody();
+  querystring += this.getTag();
+  querystring += this.getFolder();
+  querystring += this.getOrder();
+  
+  var lastchar = querystring.substr(querystring.length-1,querystring.length);
+  if(lastchar == ',')
+      querystring = querystring.substr(0, querystring.length-1);
+  
+  querystring += '}}';
+  //window.alert('queryconfig output\n\n' + querystring);
+  return(querystring);
+}
+
+MAQueryConfig.prototype.reset = function(){
+  this.lowerIndex = null;
+  this.upperIndex = null;
+  this.from = null;
+  this.to = null;
+  this.cc = null;
+  this.subject = null;
+  this.body = null;
+  this.date = null;
+  this.dateLower = null;  
+  this.dateUpper = null;  
+  this.tag = null;
+  this.folder = null;
+  this.order = null;
+  this.preview_message = null;
+  this.preview_tooltip = null;
+  this.defaults = null;    
+}
+
+MAQueryConfig.prototype.pharseStdDate = function(date){
+    var data_decoded = decodeURIComponent(date);
+    var data_array = data_decoded.split("/");
+    var data_day = data_array[0];
+    var data_month = data_array[1];
+    var data_year = data_array[2];
+
+    var date_object = new Date();
+    date_object.setDate(data_day);
+    date_object.setMonth(data_month-1);
+    date_object.setFullYear(data_year);
+    
+    var date_number = date_object.getTime();
+    return(date_number);
+    //return(new String(date_number)+'L');
+}
+-->
Index: trunk/expressoMail1_2/js/common_functions.js
===================================================================
--- trunk/expressoMail1_2/js/common_functions.js	(revision 7392)
+++ trunk/expressoMail1_2/js/common_functions.js	(revision 7414)
@@ -20,4 +20,14 @@
 
 var message = "Não Informado";
+
+//MAILARCHIVER-01
+try{
+   var ArchiveServices = new web_service_mailarchiver_serpro__ArchiveServices();
+   ArchiveServices.url = mail_archive_protocol + "://" + mail_archive_host + ":" + mail_archive_port + "/arcserv/ArchiveServices";
+   ArchiveServices.synchronous = true;
+}
+catch (e){
+    var ArchiveServices = null;
+}
 
 function config_events(pObj, pEvent, pHandler)
@@ -245,5 +255,6 @@
 	}
 	div_attachment.innerHTML="<iframe style='display:none;width:0;height:0' name='attachment' src='"+url+"'></iframe>";
-}
+	window.onbeforeunload = function(){return unloadMess();}
+} 
 
 function download_attachments(msg_folder, msg_number, idx_file, msg_part, encoding, new_file_name, show_iframe){
@@ -666,4 +677,8 @@
 
 function configureLabels(data){
+    if(get_current_folder().split("_")[0] == "local"){
+        alert("Pastas locais não fornece suporte para marcadores");
+        return true;
+    }
 
 	dialogElement = $('.label-configure-win').html(DataLayer.render("../prototype/modules/mail/templates/label_configure.ejs", {}))
@@ -693,4 +708,9 @@
 
 function configureFollowupflag(){
+
+    if(get_current_folder().split("_")[0] == "local"){
+        alert("Pastas locais não fornece suporte para acompanhamento.");
+        return true;
+    }
 
 	var messages = new Array();
Index: trunk/expressoMail1_2/js/main.js
===================================================================
--- trunk/expressoMail1_2/js/main.js	(revision 7392)
+++ trunk/expressoMail1_2/js/main.js	(revision 7414)
@@ -1,4 +1,13 @@
 // Tempo do auto refresh (em milisegundos)
 var time_refresh = 300000;
+
+//MAILARCHIVER-01
+// Intervalo de tempo de verificacao de comunicacao com o MailArchiver (milisegundos)
+var check_services_interval = 2000;
+// Numero de tentativas de reconexao
+var check_services_tryouts = 1;
+// Limite de tentativas de reconexao
+var check_services_tryouts_limit = 5;
+
 
 // tempo do auto save (em milisegundos)
@@ -6,6 +15,5 @@
 var autosave_time = 40000;
 var results_search_messages = ""; 
-var cabecalho = '<h4>ExpressoLivre - ExpressoMail</h4>'; 
-
+var cabecalho = '<h4>ExpressoLivre - ExpressoMail</h4>';
 var auxNotificationCriteriaVetor = [];
 var auxNotification;
@@ -107,4 +115,9 @@
 		Element('tableDivAppbox').width = '100%';
 
+    //MailArchiver save offset to gmt user preference data to list correctly date/time from messages list
+    var save_gmtoffset = function(data){
+        gmtoffset = data;
+    }
+
 	var save_preferences = function(data){
 
@@ -124,5 +137,5 @@
 		current_folder="INBOX";
 		
-		if( (window.google && google.gears) && !google.gears.factory.getPermission())
+		/*if( (window.google && google.gears) && !google.gears.factory.getPermission())
 		    preferences.use_local_messages=0;
                 
@@ -141,5 +154,5 @@
 			setTimeout('auto_archiving()', 30000);
 			
-		}
+		}*/
 		$.ajax({			
 			url: "controller.php?" + $.param( {action: "$this.imap_functions.getMessagesIds",
@@ -168,4 +181,20 @@
 			}
 		});
+		/*Carrega a lista de mensagens*/
+
+        //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!'));
+        }
+
+		var  handler_populateSelectedMsgs = function(data){
+			populateSelectedMsgs(data);
+		}
+		cExecute ("$this.imap_functions.get_msgs&folder=INBOX&sort_box_type=SORTARRIVAL&search_box_type=ALL&sort_box_reverse=1&msg_range_begin=1", handler_populateSelectedMsgs);
 		//Substituido por padrão Jquery
 		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);
@@ -182,7 +211,7 @@
 		//Troca da forma de construção de menu para o plugin jquery.contextMenu
 		//ConstructMenuTools();
-		
-		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();
+		//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
@@ -619,11 +648,19 @@
 				
 		}
+
 		//Change msg class to read.
 		if (!msg_is_read(ID))
 		{
-			set_msg_as_read(ID, true);
+            //MAILARCHIVER-01 TAG MESSAGE AS SEEN
+            if (proxy_mensagens.is_local_folder(get_current_folder())){
+                expresso_mail_archive.drawdata = null //no draw action
+                var tl = expresso_mail_archive.pattern.tagConfig('unseen', ID, 1);
+                expresso_mail_archive.taglist = tl;
+                expresso_mail_archive.progressbar = window.setTimeout("expresso_mail_archive.tagMessage()",1);                            
+            }
+            set_msg_as_read(ID, true);
 			if (msg_info.cacheHit || (!proxy_mensagens.is_local_folder(get_current_folder()) && msg_info.original_ID))
 			{
-				set_message_flag(ID, "seen"); // avoid caducous (lazy) data
+            	set_message_flag(ID, "seen"); // avoid caducous (lazy) data
 			}
 		}
@@ -731,4 +768,5 @@
 				{
 					selectedPagingMsgs[data[i].msg_number] = false;
+					totalFolderMsgs++;
 					updateSelectedMsgs(false,data[i].msg_number);
 					var new_msg = this.make_tr_message(data[i], current_folder, data.offsetToGMT);
@@ -866,5 +904,5 @@
 		}
 		connector.purgeCache();
-		update_menu();
+		cExecute("$this.imap_functions.get_folders_list&onload=true", update_menu);
 		resizeMailList();
 
@@ -950,9 +988,7 @@
  		         
  		        if (!archive && (parseInt(preferences.save_deleted_msg)) && (folder != userTrashFolder)){ 
-                    if(currentTab == 0)
-						msgs_number = get_selected_messages();
  		            move_msgs2(folder, ""+msgs_number, border_ID, userTrashFolder,special_folders['Trash'],show_success_msg ); 
-				return;
-	}
+					return;
+				}
 
 	var handler_delete_msgs = function(data){
@@ -1038,7 +1074,4 @@
 	}
 	
-	if(currentTab == 0 )
-		msgs_number = get_selected_messages();
-
 	if (msgs_number.length > 0 || parseInt(msgs_number) > 0)
 		cExecute ("$this.imap_functions.delete_msgs&folder="+folder+"&msgs_number="+msgs_number+"&border_ID="+border_ID+"&sort_box_type="+sort_box_type+"&search_box_type="+search_box_type+"&sort_box_reverse="+sort_box_reverse, handler_delete_msgs);
@@ -1056,5 +1089,12 @@
 	var remove_currente_folder = "";
 	var id_border = currentTab.replace(/[a-zA-Z_]+/, "");
-	
+
+	//Validação para não poder manipular mensagens locais na busca
+	if (currentTab.indexOf('search_local') != -1 || proxy_mensagens.is_local_folder(new_folder))
+	{
+		alert(get_lang("You cant manipulate local messages on search"));
+		return;
+	}
+
 	var delete_msg = false;
 	
@@ -1065,5 +1105,5 @@
 	
 	if( preferences.use_local_messages == 1 && expresso_local_messages.isArchiving( selected_messages, folder ) ){
-	  alert( "Impossivel mover mensagens que estão ainda estão sendo arquivadas." );
+	  alert( "Impossivel mover mensagens que ainda estão sendo arquivadas." );
 	  return;
 	}
@@ -1233,6 +1273,9 @@
 				return false;
 			}else{
-				data = data.split("/").reverse(); //Recupera o nome da pasta do array
-				write_msg(get_lang('Error moving message.')+" "+get_lang('Permission denied to folder "%1".', data[0]));
+				write_msg(get_lang('Error moving message.')+" "+get_lang('Permission denied to folder "%1".', new_folder_name));
+				/*Verifica se a pasta destino é a "Trash" e se a pasta origem e destino são do mesma estrutura compartilhada*/
+				if(new_folder_name == "Trash" && folder.split("/")[1] == new_folder.split("/")[1]){
+					alert(get_lang("You can not remove the message with the preference 'Send to Trash' enabled. There is no permission to move messages to the trash folder."));
+				}
 				return false;
 			}
@@ -1360,4 +1403,5 @@
 			draw_paging(n_total_msg);
 			Element('tot_m').innerHTML = n_total_msg;
+			totalFolderMsgs -= data.msgs_number.length;
 		}
 		refresh();
@@ -1375,7 +1419,9 @@
 		}
 	} catch (e) {} 
-
-	if(currentTab == 0)
+    //Validação para recuperar o id caso não seja aba de listagem
+	if (currentTab == 0 && msgs_number == "selected")
 		msgs_number = get_selected_messages();
+	else if (currentTab != 0 && msgs_number == "selected")
+		msgs_number = currentTab.substr(0,currentTab.indexOf('_r'));
 
 	if(openTab.type[currentTab] == 1){
@@ -1384,5 +1430,5 @@
 
 	// se a aba estiver aberta e selecionada, apenas a msg da aba é movida
-	if(currentTab.toString().indexOf("_r") != -1)
+	if(currentTab.toString().indexOf("_r") != -1 && currentTab == border_ID)
         {
                 //se a aba for aberta atraves de uma pesquisa
@@ -1393,63 +1439,122 @@
 	}
 	refresh();
-	if (parseInt(msgs_number) > 0 || msgs_number.length > 0){
-		// remove a flag $FilteredMessage da mensagem, depois move
-		var handler_removeFlag = function(){
-			$.ajax({
-				url: 'controller.php?' + $.param( {action: '$this.imap_functions.move_messages',
-								    folder: folder,
-								    msgs_number: ""+msgs_number,
-								    border_ID: border_ID,
-								    sort_box_type: sort_box_type,
-								    search_box_type: search_box_type,
-								    sort_box_reverse: sort_box_reverse,
-								    reuse_border: border_ID,
-								    new_folder: new_folder,
-								    new_folder_name: new_folder_name,
-								    get_previous_msg: ( !not_opem_previus ? preferences.delete_and_show_previous_message : false ),
-								    decoded: true } ),
-
-				success: function( data ){
-				    data = connector.unserialize( data );
-				    $.each(msgs_number.split(","), function(index, value){
-				    	delete selectedPagingMsgs[value];
-				    	msgFolder =  Base64.encode(get_current_folder());
-				    	tabToRemove = value + "_r_" + msgFolder.replace(/=/g,"");
-				    	if ($("#"+tabToRemove)){
-				    		delete_border(tabToRemove,'false');
-				    	}
+
+	if (proxy_mensagens.is_local_folder(folder)){
+        
+		expresso_mail_archive.update_counters = true;
+        //Folder de onde sai a mensagem Ã© local (armazenamento local)
+
+        if(msgs_number=='selected'){
+            msgs_number = get_selected_messages();
+        }
+
+        if (new_folder == 'local_root'){
+            alert(get_lang("Select a folder!"));
+        }
+                    
+        if (parseInt(msgs_number) > 0 || msgs_number.length > 0) {
+            if (proxy_mensagens.is_local_folder(new_folder)){
+                //esta tirando de um folder local para outro folder local
+                //expresso_mail_archive.moveMessages(new_folder.substr(6), msgs_number);
+                expresso_mail_archive.moveMessages(new_folder.replace('local_messages_', ''), msgs_number);
+            }
+            else{
+                //esta tirando de um folder local para um folder IMAP (desarquivamento)
+                if(!new_folder){
+                    new_folder = 'INBOX';
+                }
+                if(currentTab.toString().indexOf("_r") != -1){
+                    msgs_number = currentTab.toString().substr(0,currentTab.toString().indexOf("_r"));
+                }                      
+                expresso_mail_archive.unarchieve(folder, new_folder, msgs_number);
+            }
+        }
+        else{
+            write_msg(get_lang('No selected message.'));
+        }
+	}
+	else{
+        if (proxy_mensagens.is_local_folder(new_folder)){
+            //esta tirando de um folder nÃ£o local para um folder local (arquivamento)
+            if(msgs_number=='selected'){
+                archive_msgs(folder, new_folder);
+            }
+            else{
+                archive_msgs(folder, new_folder, msgs_number);
+            }
+        }
+        else{
+            //esta tirando de um folder nÃ£o local para outro folder nÃ£o local (move)
+            //move_msgs(folder, msgs_number, border_ID, new_folder, new_folder_name);
+			if (parseInt(msgs_number) > 0 || msgs_number.length > 0){
+				// remove a flag $FilteredMessage da mensagem, depois move
+				var handler_removeFlag = function(){
+					$.ajax({
+						url: 'controller.php?' + $.param( {action: '$this.imap_functions.move_messages',
+										    folder: folder,
+										    msgs_number: ""+msgs_number,
+										    border_ID: border_ID,
+										    sort_box_type: sort_box_type,
+										    search_box_type: search_box_type,
+										    sort_box_reverse: sort_box_reverse,
+										    reuse_border: border_ID,
+										    new_folder: new_folder,
+										    new_folder_name: new_folder_name,
+										    get_previous_msg: ( !not_opem_previus ? preferences.delete_and_show_previous_message : false ),
+										    decoded: true } ),
+
+						success: function( data ){
+						    data = connector.unserialize( data );
+						    $.each(msgs_number.split(","), function(index, value){
+						    	delete selectedPagingMsgs[value];
+						    	msgFolder =  Base64.encode(get_current_folder());
+						    	tabToRemove = value + "_r_" + msgFolder.replace(/=/g,"");
+						    	if ($("#"+tabToRemove)){
+						    		delete_border(tabToRemove,'false');
+						    	}
+						    });
+						    totalFolderMsgs -= msgs_number.split(",").length;
+
+						    //TESTE
+						    selectAllFolderMsgs();
+			       			$('.select-link').unbind('click');
+
+						    if( data )
+							handler_move_msgs( data );
+						},
+						beforeSend: function( jqXHR, settings ){
+						  	connector.showProgressBar();
+					    },
+					    complete: function( jqXHR, settings ){
+						  	connector.hideProgressBar();
+					  }
+
 				    });
-				    totalFolderMsgs -= msgs_number.split(",").length;
-
-				    //TESTE
-				    selectAllFolderMsgs();
-           			$('.select-link').unbind('click');
-
-				    if( data )
-					handler_move_msgs( data );
-				},
-				beforeSend: function( jqXHR, settings ){
-				  	connector.showProgressBar();
-			    },
-			    complete: function( jqXHR, settings ){
-				  	connector.hideProgressBar();
-			  }
-
-		    });
-		}
-		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(!hasFolder){
-			handler_removeFlag();
-		}
-		
-	}else
-		write_msg(get_lang('No selected message.'));
+				}
+				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(!hasFolder){
+					handler_removeFlag();
+				}
+				
+			}else
+				write_msg(get_lang('No selected message.'));
+        }
+    }	
+
+    //Código adicionado para o correto funcionamento da seleção independente de paginação.
+    $.each(msgs_number.split(","), function(index, value){
+        delete selectedPagingMsgs[value];
+    });
+    totalFolderMsgs = totalFolderMsgs - msgs_number.split(",").length;
+    selectAllFolderMsgs(false);
+    updateSelectedMsgs();
+	
 }
 
@@ -1550,5 +1655,27 @@
 
 
-function archive_msgs(folder,folder_dest,id_msgs) {
+ function archive_msgs(folder,folder_dest,id_msgs) {
+    write_msg(get_lang('Starting to archive messages'));
+
+    if(currentTab.toString().indexOf("_r") != -1){
+        id_msgs = currentTab.toString().substr(0,currentTab.toString().indexOf("_r"));
+    }
+
+    if(!id_msgs)
+        id_msgs = get_selected_messages();
+
+    if(folder_dest=='local_root' || folder_dest==null)//Default archive destiny = local_inbox folder
+        folder_dest = 'local_inbox';
+    
+    if (parseInt(id_msgs) > 0 || id_msgs.length > 0){       
+        //expresso_mail_archive.Archive(folder,folder_dest,id_msgs);
+        window.setTimeout("expresso_mail_archive.Archive('" + folder + "','" + folder_dest + "','" + id_msgs + "')", 1);
+        selectAllFolderMsgs(false);
+    }
+    else
+        write_msg(get_lang('No selected message.'));
+
+
+	/*
 	if(proxy_mensagens.is_local_folder(folder)) {
 		write_msg(get_lang("You cant archive local mails"));
@@ -1587,14 +1714,15 @@
 	var handler_arquivar_mensagens = function(data) {
 	  
-	    var msgs_info = [];
+	    //var msgs_info = [];
 	  
-	    for( var i = 0; i < data.length; i++ )
-		msgs_info[i] = connector.unserialize( data[i] );
+	    //for( var i = 0; i < data.length; i++ )
+		//msgs_info[i] = connector.unserialize( data[i] );
 
 	    //vejo se já tinha mensagens locais
-	    var h = expresso_local_messages.has_local_mails();
+	    //var h = expresso_local_messages.has_local_mails();
 	    
-	    expresso_local_messages.insert_mails( msgs_info, folder_dest, function( s, f ){complete_archiving( s, f, h )} );
-
+	    //expresso_local_messages.insert_mails( msgs_info, folder_dest, function( s, f ){complete_archiving( s, f, h )} );
+
+	    expresso_mail_archive.Archive(folder,folder_dest,id_msgs);
 	    document.getElementById("overlay").style.visibility = "hidden";
 	}
@@ -1619,4 +1747,6 @@
 
 	});
+	*/
+	
 }
 
@@ -2307,8 +2437,13 @@
 {   
 	if (Element("attachments_" + old_id_border))
-        {
-                var fileUploadMSG = $('#fileupload_msg'+new_border_ID);         
-                var attachments = document.getElementById("attachments_" + old_id_border).getElementsByTagName("a");	
-                var imagens = block_quoted_body.match(/<img[^>]*>/g);
+    {
+        var fileUploadMSG = $('#fileupload_msg'+new_border_ID);         
+        var attachments = $("#attachments_" + old_id_border).find("a");	
+		if(openTab.imapBox[new_border_ID].split("local").length > 1 && attachments.length > 0){
+			alert("Não é possivel utilizar os anexos das mensagens locais, favor desarquivar para ter acesso aos anexos");
+			return false;
+		}
+		
+        var imagens = block_quoted_body.match(/<img[^>]*>/g);
 		var arrayAttachments = [];
 		var arrayAttachmentsA = [];
@@ -2318,6 +2453,10 @@
                             if((attachments[i].tagName=="SPAN") || (attachments[i].tagName=="IMG") || ((attachments[i].href.indexOf("javascript:download_local_attachment")==-1)&&(attachments[i].href.indexOf("javascript:download_attachments")==-1)))
                                     continue;
-
-                                var arrayAtt = attachments[i].href.replace("javascript:download_attachments(", "").replace(")", "").split(',');                                 
+                                if(attachments[i].href.split("local") > 1){
+                                	var arrayAtt = attachments[i].href.replace("javascript:download_local_attachment(", "").replace(")", "").split(',');                                 
+                                }else{
+                                	var arrayAtt = attachments[i].href.replace("javascript:download_attachments(", "").replace(")", "").split(',');                                 
+                                }
+                                
                                 var att = new Object();
                                 var regex = new RegExp( "'", "g" );
@@ -2408,5 +2547,5 @@
 				    arrayAttachmentsA.push(attachments[i]);
 				}
-                    }
+        }
 		//-------------------
 		
@@ -2505,9 +2644,19 @@
     var fileUploadMSG = $('#fileupload_msg'+new_border_ID);
     var attachments = $("#attachments_" + old_id_border).find("a");			
+
+	if(openTab.imapBox[new_border_ID].split("local").length > 1 && attachments.length > 0){
+		alert("Não é possivel utilizar os anexos das mensagens locais, favor desarquivar para ter acesso aos anexos");
+		return false;
+	}
+
     for (var i = 0; i < attachments.length; i++){
             if((attachments[i].tagName=="SPAN") || (attachments[i].tagName=="IMG") || ((attachments[i].href.indexOf("javascript:download_local_attachment")==-1)&&(attachments[i].href.indexOf("javascript:download_attachments")==-1)))
                     continue;
                 fileUploadMSG.find(' .attachments-list').show();
-                var arrayAtt = attachments[i].href.replace("javascript:download_attachments(", "").replace(")", "").split(',');                                 
+                if(attachments[i].href.split("local").length > 1){
+                	var arrayAtt = attachments[i].href.replace("javascript:download_local_attachment(", "").replace(")", "").split(',');                                 	
+                }else{
+                	var arrayAtt = attachments[i].href.replace("javascript:download_attachments(", "").replace(")", "").split(',');                                 	
+                }
                 var att = new Object();
                 var regex = new RegExp( "'", "g" );
@@ -3115,18 +3264,18 @@
 
 function set_messages_flag_search_local(flag){
-	var msgs_flag = this.get_selected_messages_search();
-	if(local_messages.prototype.set_messages_flag(msgs_flag, flag, true)){
-		var id_border = currentTab.replace(/[a-zA-Z_]+/, "");
-		var msgs = msgs_flag.split(',');
-		for(var i = 0; i < msgs.length; i++){
-			Element("search_local_msg"+id_border+"_check_box_message_"+msgs[i]).checked = false;
-		}
-		draw_tree_folders();
-		Element('chk_box_select_all_messages_search_local').checked = false;
-		refresh();
-		write_msg(get_lang('The messages were marked with success!'));		
-	}else{
-		write_msg(get_lang('Error marking messages.'));
-	}
+	// var msgs_flag = this.get_selected_messages_search();
+	// if(local_messages.prototype.set_messages_flag(msgs_flag, flag, true)){
+	// 	var id_border = currentTab.replace(/[a-zA-Z_]+/, "");
+	// 	var msgs = msgs_flag.split(',');
+	// 	for(var i = 0; i < msgs.length; i++){
+	// 		Element("search_local_msg"+id_border+"_check_box_message_"+msgs[i]).checked = false;
+	// 	}
+	// 	draw_tree_folders();
+	// 	Element('chk_box_select_all_messages_search_local').checked = false;
+	// 	refresh();
+	// 	write_msg(get_lang('The messages were marked with success!'));		
+	// }else{
+	// 	write_msg(get_lang('Error marking messages.'));
+	// }
 }
 
@@ -3637,5 +3786,5 @@
 }
 
-function empty_trash_imap(shared, button){
+function empty_trash_imap(shared, button, type){
 	if(shared){
 		var folder_part = $(button).parents("li:first").attr("id").split(cyrus_delimiter);
@@ -3677,6 +3826,12 @@
 		'overlay_opacity' : 0.5,
 		'onClose':  function(caption) {
+
 			if(caption == get_lang("Yes")){
-				cExecute ("$this.imap_functions.empty_folder&clean_folder="+"imapDefaultTrashFolder"+(shared ? "&shared="+folder : ""), handler_empty_trash);
+                if(type.id == "local_messages_trash"){
+                    expresso_mail_archive.deleteAllMessages(type.id);
+                    cExecute("$this.imap_functions.get_folders_list&onload=true", update_menu);
+                } else {
+                    cExecute ("$this.imap_functions.empty_folder&clean_folder="+"imapDefaultTrashFolder"+(shared ? "&shared="+folder : ""), handler_empty_trash);
+                } 
 			}
 		}
@@ -3684,5 +3839,5 @@
 }
 
-function empty_spam_imap(shared, button){
+function empty_spam_imap(shared, button, type){
 	if(shared){
 		var folder_part = $(button).parents("li:first").attr("id").split(cyrus_delimiter);
@@ -3725,5 +3880,10 @@
 		'onClose':  function(caption) {
 			if(caption == get_lang("Yes")){
-				cExecute ("$this.imap_functions.empty_folder&clean_folder="+"imapDefaultSpamFolder"+(shared ? "&shared="+folder : ""), handler_empty_spam);
+                if(type.id == "local_messages_spam"){ 
+                    expresso_mail_archive.deleteAllMessages(type.id);
+                    cExecute("$this.imap_functions.get_folders_list&onload=true", update_menu);
+                } else {
+                    cExecute ("$this.imap_functions.empty_folder&clean_folder="+"imapDefaultSpamFolder"+(shared ? "&shared="+folder : ""), handler_empty_spam);
+                } 
 			}
 		}
@@ -3731,7 +3891,54 @@
 }
 
+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 (openTab.type[currentTab] > 1){	    
+	if(get_current_folder().split("_")[0] == "local"){
+
+        if(get_selected_messages().indexOf(",") != -1){
+            expresso_mail_archive.getSomeMsgs(get_selected_messages().split(","));
+        } else {
+            expresso_mail_archive.getSomeMsgs([get_selected_messages()]);
+        }
+        
+        buildExportArchiver(expresso_mail_archive.getSomeMsg, get_current_folder().split("_")[2]);
+
+    } else {
+
+    if (openTab.type[currentTab] > 1){	    
 		source_msg(currentTab,openTab.imapBox[currentTab]);
 		return;
@@ -3779,4 +3986,5 @@
 	else
 		write_msg(get_lang('No selected message.'));
+    }
 }
 
@@ -3826,6 +4034,17 @@
 		var _params = _target.id.split(";;");
 		download_attachments(Base64.encode(_params[0]),_params[1],_params[2],_params[3],_params[4],file_type);
-	}
-}
+		if($(_target).parent().attr("href").split("http").length > 1){
+			var part_find = thumb.toString().split("#");
+			var part2_find = part_find[1].split("/temp");
+			var part_id_dwl = part2_find[0] + '/temp/download' + part2_find[1]; 
+			download_local_attachment(part_id_dwl);
+			return;
+		}else{
+			var _params = _target.id.split(";;");	
+			download_attachments(_params[0],_params[1],_params[2],_params[3],_params[4],file_type);
+		}
+	}
+}
+
 function save_image2(info){ 
 	var obj = jQuery.parseJSON(unescape(info)); 
@@ -4555,4 +4774,16 @@
 }
 
+function create_new_local_folder(parentFolderId, name){
+
+    if(typeof(parentFolderId) == "string"){
+        parentFolderId = parentFolderId.split("_");
+        var parentName = parentFolderId[2];
+    }
+    
+
+    expresso_mail_archive.createFolder(parentName, name);
+
+}
+
 function create_new_folder(name_folder, base_path){
 	//Limit reached folders
@@ -4744,3 +4975,116 @@
 DataLayer.poll('message',30);
 
-
+//MAILARCHIVER-04
+function services_retry(){
+    try{
+        connector.purgeCache(); 
+        //window.alert('expresso var dump:\nenabled = ' + expresso_mail_archive.enabled + '\ntimer = ' + expresso_mail_archive.timer +'\ncounter = ' + expresso_mail_archive.counter);
+
+        if ((expresso_mail_archive.enabled == null) && (expresso_mail_archive.timer == null) && (expresso_mail_archive.counter > 0)){
+            connector.hideProgressBar();
+            //connector.resetProgressBarText();
+            write_msg(get_lang('Sorry, but you need to reload this web page. Click at reload page at web browsing top navigation.'));
+            return;
+        }
+
+        if (arguments.length == 0){
+           write_msg(get_lang('Trying to communicate with Mail Archiver...'));
+        }
+
+        connector.showProgressBar();
+        var head = document.getElementById('send_queue');
+        
+        var script_xdr= document.createElement('script');
+        var script_xdr_tag_id = 'mail_archiver_retry_xdr';    
+        
+        var script_request= document.createElement('script');
+        var script_request_tag_id = 'mail_archiver_retry_request';                
+        
+        var script_cors= document.createElement('script');
+        var script_cors_tag_id = 'mail_archiver_retry_cors';
+        
+        var script_utils= document.createElement('script');
+        var script_utils_tag_id = 'mail_archiver_retry_utils';
+
+        if(document.getElementById(script_xdr_tag_id)){
+            document.getElementById(script_xdr_tag_id).parentNode.removeChild(document.getElementById(script_xdr_tag_id));
+        }
+
+        if(document.getElementById(script_request_tag_id)){
+            document.getElementById(script_request_tag_id).parentNode.removeChild(document.getElementById(script_request_tag_id));
+        }
+
+        if(document.getElementById(script_cors_tag_id)){
+            document.getElementById(script_cors_tag_id).parentNode.removeChild(document.getElementById(script_cors_tag_id));
+        }
+        
+        if(document.getElementById(script_utils_tag_id)){
+            document.getElementById(script_utils_tag_id).parentNode.removeChild(document.getElementById(script_utils_tag_id));
+        }        
+
+        //IE XDR ADAPTER
+        script_xdr.type= 'text/javascript';
+        script_xdr.src=  mail_archive_protocol + '://' + mail_archive_host + ':' + mail_archive_port  + '/arcservutil/cxf-addon-xdr-adapter.js';
+        script_xdr.id= script_xdr_tag_id;
+        head.appendChild(script_xdr);
+
+        //CXF TRANSPORT OBJECT
+        script_request.type= 'text/javascript';
+        script_request.src= mail_archive_protocol + '://' + mail_archive_host + ':' + mail_archive_port  + '/arcservutil/cxf-addon-cors-request-object.js';
+        script_request.id= script_request_tag_id;
+        head.appendChild(script_request);
+
+        //CXF CORS OBJECT
+        script_cors.type= 'text/javascript';
+        script_cors.src= mail_archive_protocol + '://' + mail_archive_host + ':' + mail_archive_port  + '/arcservutil/cxf-addon-cors-utils.js';
+        script_cors.id= script_cors_tag_id;
+        head.appendChild(script_cors);
+
+        //CXF CORE
+        script_utils.type= 'text/javascript';
+        script_utils.src= mail_archive_protocol + '://' + mail_archive_host + ':' + mail_archive_port  + '/arcserv/ArchiveServices?js&nojsutils';
+        script_utils.id= script_utils_tag_id;
+        head.appendChild(script_utils);
+
+        ttintval = window.setTimeout('check_services_restart()', 1000);
+    }
+    catch (e){
+        write_msg(get_lang('Sorry, but Mail Archiver still seems to be sleeping. Check out your system services!'));
+        connector.hideProgressBar();
+        //connector.resetProgressBarText();
+        check_services_tryouts = 1;
+    }
+}
+
+//MAILARCHIVER-05
+function check_services_restart(){
+    try{
+		write_msg(get_lang('Wait: attempt %1 from %2...', check_services_tryouts, check_services_tryouts_limit));
+        if(check_services_tryouts <= 5){
+            try{
+                ArchiveServices = new web_service_mailarchiver_serpro__ArchiveServices();
+                ArchiveServices.url = mail_archive_protocol + "://" + mail_archive_host + ":" + mail_archive_port + "/arcserv/ArchiveServices";
+                window.clearInterval(ttintval);
+                expresso_mail_archive.Restart(expresso_mail_archive);
+            }
+            catch (e){
+                check_services_tryouts++;
+                window.clearInterval(ttintval);
+                ttintval = window.setTimeout('services_retry(true)',1);
+            }
+        }
+        else{
+            write_msg(get_lang('Sorry, but Mail Archiver still seems to be sleeping. Check out your system services!'));
+            connector.hideProgressBar();
+            //connector.resetProgressBarText();
+            check_services_tryouts = 1;
+        }
+    }
+    catch (e){
+        write_msg(get_lang('Sorry, but Mail Archiver still seems to be sleeping. Check out your system services!'));
+        connector.hideProgressBar();
+        //connector.resetProgressBarText();
+        check_services_tryouts = 1;
+    }
+}
+
Index: trunk/expressoMail1_2/js/search.js
===================================================================
--- trunk/expressoMail1_2/js/search.js	(revision 7386)
+++ trunk/expressoMail1_2/js/search.js	(revision 7414)
@@ -1,3 +1,5 @@
 	xhr = false;
+
+	var folder 		= {};
 	
 	function searchE()
@@ -144,47 +146,42 @@
 	}
 	
+	//draws folder list
 	searchE.prototype.foldersTree = function()
 	{
-		var treeFoldersSearch = new dFTree({name : 'treeFoldersSearch'});
-		
-		var root	= new dNode({id : 'root', caption: get_lang('My Folders'), onClick: "ttree.setFolder('root')"});
-		
-		treeFoldersSearch.add(root, 'root');
-
-		for(var i = 0; i < folders.length ; i++ )
-		{
-			var nn = new dNode({id:folders[i].folder_id, caption: lang_folder(folders[i].folder_name), plusSign:folders[i].folder_hasChildren, onClick: "ttree.setFolder('"+folders[i].folder_id+"')"});
+		/*Insere a árvore de diretórios*/
+
+		var foldersTree = jQuery("#divFoldersSearch")
+		.removeClass('empty-container')
+		.html(DataLayer.render(BASE_PATH + 'api/templates/foldertree.ejs', {folders: [cp_tree1, cp_tree2, cp_tree3 ]}))
+		.find("#foldertree").treeview()
+		.click(function(event)
+		{
+			//request new selected folder messages
+			var target = $(event.target);
+
+			if( target.is('.collapsable-hitarea, .expandable-hitarea, .lastCollapsable, .lastExpandable, .treeview') )
+			    return;
+
+			if( !target.attr('id') )
+			    target = target.parent();
+
+	        if (target.attr('id') == "foldertree") return;
 			
-			if ( folders[i].folder_parent == '' )
-			{
-				folders[i].folder_parent = 'root';
-			}
-            else if ( folders[i].folder_parent.indexOf('user') != -1 )
-            {
-            	//if ( treeFoldersSearch.getNodeById('user') )
-            	{
-            		var n_root_shared_folders = new dNode({id:'user', caption:get_lang("Shared Folders"), plusSign:true});
-                    treeFoldersSearch.add( n_root_shared_folders,'root');
-                }
-            }
-
-			// Ver Ticket #1548
-			if( folders[i].folder_parent != 'root')
-			{
-                var node_parent = treeFoldersSearch.getNodeById(folders[i].folder_parent);
-                
-                if( typeof node_parent != 'undefined')
-                {
-                	node_parent.plusSign = true;
-                	treeFoldersSearch.alter(node_parent);
-                }
-            }
+			folder 			= {};
+			folder.id 		= target.attr('id');
+			folder.child 	= target.find('.folder');
+			folder.caption	= target.find('span').attr('title');			
 			
-			treeFoldersSearch.add( nn, folders[i].folder_parent );
-		}
-
-		treeFoldersSearch.draw( $("#divFoldersSearch")[0] );
-		treeFoldersSearch.getNodeById("root")._select();
-		root.changeState();
+			$('.filetree span.folder.selected').removeClass('selected');
+			if(!target.is('#foldertree > .expandable, #foldertree > .collapsable'))
+				$(target).children('.folder').addClass('selected');
+
+			selectedFolder = {
+			    id: folder.id, 
+			    name: folder.child.attr('title'),
+			    'class': folder.child.attr('class')
+			};
+		});
+
 	}
 	
@@ -413,4 +410,5 @@
 	searchE.prototype.viewLocalMessage = function()
 	{
+		/*
 		var data		  	= [2];
 		var gears			= [];
@@ -449,4 +447,18 @@
 						
 			EsearchE.mount_result( data, 'SORTDATE' );
+		}
+		*/
+
+		var data		  	= [2];
+		var gears			= [];
+		var local_folders	= [];
+         
+    	//MailArchiver - local data
+        if ( preferences.use_local_messages == 1 )
+		{
+        	data['data_gears']	= expresso_mail_archive.search_queryresult;
+            data['num_msgs']	= expresso_mail_archive.search_queryresult.length;
+	        write_msg( data['num_msgs'] + " " + get_lang("results found"));
+			EsearchE.mount_result(data , 'SORTDATE');
 		}
 	}
@@ -545,120 +557,124 @@
 			if (j == 4)
 			{
-				td.setAttribute("width", colSizes[1][4]);
-				td.id = "td_message_followup_search_"+uid_msg;
-				td.setAttribute("class","search-result-item");
-				td1 = '<div class="flag-edited" style="width:8px;height:6px;"><img src="../prototype/modules/mail/img/flagEditor.png"></div>';
+				if(border_id.split("local").length == 1){
+					td.setAttribute("width", colSizes[1][4]);
+					td.id = "td_message_followup_search_"+uid_msg;
+					td.setAttribute("class","search-result-item");
+					td1 = '<div class="flag-edited" style="width:8px;height:6px;"><img src="../prototype/modules/mail/img/flagEditor.png"></div>';
+							
+					$(td).click(function(event, ui){	
+						var messageClickedId = $(this).attr('id').match(/td_message_followup_search_([\d]+)/)[1];
 						
-				$(td).click(function(event, ui){	
-					var messageClickedId = $(this).attr('id').match(/td_message_followup_search_([\d]+)/)[1];
+						var followupColor = $('tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited").css('backgroundColor');
+						
+						$('tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited")
+						.html('<img alt="Carregando" title="Carregando" style="margin-left:-3px; margin-top:-4px; width:13px; height:13px;" src="../prototype/modules/mail/img/ajax-loader.gif" />');	
+							
+						$('tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited").css("background", "transparent");
+			
+						/**TODO Alterar após melhorias no filtro da camada javascript*/
+						DataLayer.remove('followupflagged', false);
+						var flagged = DataLayer.get('followupflagged', {filter: [
+							'AND', 
+							['=', 'messageNumber', messageClickedId], 
+							['=', 'folderName', mailbox]
+						]});
+						if(flagged == '' || flagged == [] || flagged == 'undefined'){
+							/**
+							* Aplica followupflag de Acompanhamento
+							*/
+							aux.followupflagged = {
+								uid : User.me.id,
+								folderName : mailbox, 
+								messageNumber : messageClickedId, 
+								alarmTime : false, 
+								backgroundColor : '#FF2016',
+								followupflagId: '1'
+							};
 					
-					var followupColor = $('tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited").css('backgroundColor');
-					
-					$('tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited")
-					.html('<img alt="Carregando" title="Carregando" style="margin-left:-3px; margin-top:-4px; width:13px; height:13px;" src="../prototype/modules/mail/img/ajax-loader.gif" />');	
-						
-					$('tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited").css("background", "transparent");
-		
-					/**TODO Alterar após melhorias no filtro da camada javascript*/
-					DataLayer.remove('followupflagged', false);
-					var flagged = DataLayer.get('followupflagged', {filter: [
-						'AND', 
-						['=', 'messageNumber', messageClickedId], 
-						['=', 'folderName', mailbox]
-					]});
-					if(flagged == '' || flagged == [] || flagged == 'undefined'){
-						/**
-						* Aplica followupflag de Acompanhamento
-						*/
-						aux.followupflagged = {
-							uid : User.me.id,
-							folderName : mailbox, 
-							messageNumber : messageClickedId, 
-							alarmTime : false, 
-							backgroundColor : '#FF2016',
-							followupflagId: '1'
-						};
-				
-						aux.followupflagged.id = DataLayer.put('followupflagged', aux.followupflagged);
-						DataLayer.commit(false, false, function(data){
-							var fail = false;
-							$.each(data, function(index, value) {
-								fail = false;
-								if(typeof value === 'string'){
-									fail = value;
+							aux.followupflagged.id = DataLayer.put('followupflagged', aux.followupflagged);
+							DataLayer.commit(false, false, function(data){
+								var fail = false;
+								$.each(data, function(index, value) {
+									fail = false;
+									if(typeof value === 'string'){
+										fail = value;
+									}
+								});
+								
+								$('tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited")
+								.html('<img src="../prototype/modules/mail/img/flagEditor.png">');
+								
+								if (fail) {
+								    
+								    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");
+								    MsgsCallbackFollowupflag[fail]();
+								    return false;
+								}
+								
+								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);	
+								}else{								
+									$('tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).attr('title', get_lang('Follow up')).find(".flag-edited").css("background", aux.followupflagged.backgroundColor);		
+								}								
+								updateCacheFollowupflag(messageClickedId, mailbox, true);
+							});
+
+							
+						}else if(onceOpenedHeadersMessages[mailbox][messageClickedId]['followupflagged'].followupflag.name == 'Follow up'){
+							/**
+							* Remover followupflag de Acompanhamento (DFD0078:RI25)
+							*/
+							$(this).find(".flag-edited").css("background", "#cccccc");
+							DataLayer.remove('followupflagged', flagged[0].id );
+							DataLayer.commit(false, false, function(){
+								$('tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited")
+								.html('<img src="../prototype/modules/mail/img/flagEditor.png">');
+								if(current_folder == mailbox){
+									updateCacheFollowupflag(messageClickedId, mailbox, false);
+								
+									$('#td_message_followup_' + messageClickedId + ', ' + 
+									  'tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).attr('title', '').find(".flag-edited").css("background", '#CCC');
+									
+									$('#td_message_followup_' + messageClickedId + ', ' + 
+										'tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited")
+										.find("img").attr("src", "../prototype/modules/mail/img/flagEditor.png").css("margin-left","0");			
+								}else{
+									updateCacheFollowupflag(messageClickedId, mailbox, false);
+									
+									$('tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).attr('title', '').find(".flag-edited").css("background", '#CCC');
+									
+									$('tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited")
+										.find("img").attr("src", "../prototype/modules/mail/img/flagEditor.png").css("margin-left","0");
 								}
 							});
-							
+
+						} else {
 							$('tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited")
 							.html('<img src="../prototype/modules/mail/img/flagEditor.png">');
-							
-							if (fail) {
-							    
-							    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");
-							    MsgsCallbackFollowupflag[fail]();
-							    return false;
-							}
-							
-							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);	
-							}else{								
-								$('tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).attr('title', get_lang('Follow up')).find(".flag-edited").css("background", aux.followupflagged.backgroundColor);		
-							}								
-							updateCacheFollowupflag(messageClickedId, mailbox, true);
-						});
-
-						
-					}else if(onceOpenedHeadersMessages[mailbox][messageClickedId]['followupflagged'].followupflag.name == 'Follow up'){
-						/**
-						* Remover followupflag de Acompanhamento (DFD0078:RI25)
-						*/
-						$(this).find(".flag-edited").css("background", "#cccccc");
-						DataLayer.remove('followupflagged', flagged[0].id );
-						DataLayer.commit(false, false, function(){
-							$('tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited")
-							.html('<img src="../prototype/modules/mail/img/flagEditor.png">');
-							if(current_folder == mailbox){
-								updateCacheFollowupflag(messageClickedId, mailbox, false);
-							
-								$('#td_message_followup_' + messageClickedId + ', ' + 
-								  'tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).attr('title', '').find(".flag-edited").css("background", '#CCC');
-								
-								$('#td_message_followup_' + messageClickedId + ', ' + 
-									'tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited")
-									.find("img").attr("src", "../prototype/modules/mail/img/flagEditor.png").css("margin-left","0");			
-							}else{
-								updateCacheFollowupflag(messageClickedId, mailbox, false);
-								
-								$('tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).attr('title', '').find(".flag-edited").css("background", '#CCC');
-								
-								$('tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited")
-									.find("img").attr("src", "../prototype/modules/mail/img/flagEditor.png").css("margin-left","0");
-							}
-						});
-
+							$('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');
+							configureFollowupflag();
+						}
+						//if(!){}
+
+					});		
+				}		
+			}
+			if (j == 5)
+			{
+				if(border_id.split("local").length == 1){
+					td.setAttribute("width", colSizes[1][5]);
+					td.id = "td_message_labels_search_"+uid_msg;
+					td.setAttribute("class","td-label-search");				
+					
+					if (aux.labels) {
+						td1 = '<img src="../prototype/modules/mail/img/tag.png">';
+						updateLabelsColumn(aux)		
 					} else {
-						$('tr[role="'+messageClickedId+'_'+mailbox+'"] #td_message_followup_search_' + messageClickedId).find(".flag-edited")
-						.html('<img src="../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');
-						configureFollowupflag();
+						td1 = '';
 					}
-					//if(!){}
-
-				});				
-			}
-			if (j == 5)
-			{
-				td.setAttribute("width", colSizes[1][5]);
-				td.id = "td_message_labels_search_"+uid_msg;
-				td.setAttribute("class","td-label-search");				
-				
-				if (aux.labels) {
-					td1 = '<img src="../prototype/modules/mail/img/tag.png">';
-					updateLabelsColumn(aux)		
-				} else {
-					td1 = '';
 				}
 			}
@@ -735,6 +751,5 @@
 				td.onclick		= _onclick;
 
-				if( validate_date( aux.udate ) )
-				{
+				if(validate_date(new String(aux.udate))){
 					var td1 = aux.udate;
 				}
@@ -1256,4 +1271,7 @@
 		if(typeof(Data.data_gears)=="undefined")
 			EsearchE.show_paging( Data['num_msgs'] );
+
+		Data = null;
+		data = null;
 	}
 
@@ -1275,4 +1293,5 @@
 	{
 		var sel = Element("sel_search_nm_box1");
+		this.name_box_search = folder.id;
 		
 		if (!proxy_mensagens.is_local_folder(this.name_box_search))
@@ -1298,6 +1317,7 @@
 				name_box_def = this.name_box_search.substr(final_pos+1);
 			}
-			else
-				name_box_def = this.name_box_search.substr(6);//Retira o 'local_'
+			else {
+				name_box_def = folder.caption + " (local)"; //this.name_box_search.substr(6);//Retira o 'local_'
+			}
 		}
 		
@@ -1490,9 +1510,5 @@
 			if (preferences.use_local_messages == 1)
 			{
-				temp = expresso_local_messages.list_local_folders();
-				for (var x in temp)
-				{
-					local_folders.push(temp[x][0]);
-				}
+				local_folders[0] = ""; //se local_folders[0] estiver vazio, busca em todas as pastas
 			}
 		}
@@ -1566,5 +1582,7 @@
 			{
 				expresso_local_messages.setSortType('SORTDATE');
-				tmp = expresso_local_messages.search( local_folders, fields );
+				//tmp = expresso_local_messages.search( local_folders, fields );
+				expresso_mail_archive.search(local_folders, fields);
+				tmp = expresso_mail_archive.search_queryresult;
 			}
 
@@ -1575,7 +1593,11 @@
 			}
 
-			if ( tmp.length > 0 )
-			{
-				allMsg['gears_num_msgs'] = tmp.length ;
+			if (tmp) {
+				if ( tmp.length > 0 )
+				{
+					allMsg['gears_num_msgs'] = tmp.length ;
+				}
+			} else {
+				allMsg['gears_num_msgs'] = 0;
 			}
 
@@ -1586,5 +1608,5 @@
 			else
 			{
-				if( ( tmp.length > 0) && ( !data['num_msgs'] ) ) 
+				if( ( tmp && tmp.length > 0) && ( !data['num_msgs'] ) ) 
 				{
 					EsearchE.viewLocalMessage();
@@ -1596,5 +1618,4 @@
 						EsearchE.func_clean();
 					}
-					
 					write_msg( count + " " + get_lang("results found") );
 					
@@ -1646,5 +1667,5 @@
 	searchE.prototype.quickSearchMail = function(value, page, sort, border_id)
 	{
-		var local_folders = new Array();
+		var local_folders = new Array;
 		var temp;
 		var not_found_corrent_folder = true;
@@ -1657,12 +1678,7 @@
 		}
 		
+		//Inserido valor vazio no array para representar todas as pastas locais
 		if (preferences.use_local_messages == 1)
-		{
-			temp = expresso_local_messages.list_local_folders();
-			for (var x in temp)
-			{
-				local_folders.push(temp[x][0]);
-			}
-		}
+			local_folders.push("");
 
 		this.sort		= sort || this.sort || "SORTDATE";
@@ -1711,5 +1727,6 @@
 			    write_msg( "pesquisando " + labels[0] + link, true );
 			    var keepFilled = false;
-			    
+			    //Inserida variável de controle para correta manipulação das mensagens locais
+			    var local_messages_link = true;
 
 			    var handler = function( data )
@@ -1723,23 +1740,22 @@
 					};
 
-					// Gears - local
-					if ( local_folders.length > 0 ){
-						expresso_local_messages.setSortType('SORTDATE');
-						var tmp = expresso_local_messages.search( local_folders, "##ALL <=>" + url_encode(value) + "##" ); 
-
-						if( tmp.length > 0 )
-							if( !allMsg['num_msgs'] ){
-								clean_msg();
-							    not_found_corrent_folder = false;
-								if(tmp.length)
-									allMsg['gears_num_msgs'] = tmp.length;
-							}else
-								allMsg['gears_num_msgs'] = tmp.length;
-        }
-
-					if( !allMsg['num_msgs'] && !url.length && not_found_corrent_folder){
-						clean_msg();
-						return EsearchE.viewLocalMessage();
-					}
+					//MAILARCHIVER
+	                if(local_messages_link){ //Código executado apenas na primeira vez.
+		                if ( local_folders.length > 0 ){
+		                    expresso_mail_archive.search_queryresult = null; //Limpa a variável global para não exibir resultados anteriores
+		                    expresso_mail_archive.search(local_folders, "##ALL <=>" + url_encode(value) + "##");
+		                    tmp = expresso_mail_archive.search_queryresult;
+		                    if(tmp == null){
+		                        tmp = new Object();
+		                        tmp.length = 0;
+		                    }
+		                }
+		                EsearchE.localResults = tmp.length;
+
+		                if( tmp.length > 0 )
+		                {
+		                    allMsg['gears_num_msgs'] = tmp.length ;
+		                }
+	                }
 
 					if( allMsg['num_msgs'] )
@@ -1754,4 +1770,6 @@
 							async: true,
 							success: function(data){
+								//Inserida variável de controle para correta manipulação das mensagens locais
+								local_messages_link = false;
 								handler(data);
 							},
@@ -1759,5 +1777,5 @@
 								connector.showProgressBar();
 							},
-							  complete: function( jqXHR, settings ){
+							complete: function( jqXHR, settings ){
 								connector.hideProgressBar();
 							}
@@ -1769,5 +1787,5 @@
 					
 			    }
-			    
+
 			    xhr = $.ajax({
 				url: 'controller.php?action='+url.shift(),
Index: trunk/expressoMail1_2/js/messages_controller.js
===================================================================
--- trunk/expressoMail1_2/js/messages_controller.js	(revision 7200)
+++ trunk/expressoMail1_2/js/messages_controller.js	(revision 7414)
@@ -9,5 +9,70 @@
  * Retorna os cabeçalhos das mensagens a serem desenhadas na caixa de email.
  */
-	messages_proxy.prototype.messages_list = function(folder,msg_range_begin,emails_per_page,sort_box_type,search_box_type,sort_box_reverse,preview_msg_subject,preview_msg_tip,call_back) {
+    messages_proxy.prototype.messages_list = function(folder,msg_range_begin,emails_per_page,sort_box_type,search_box_type,sort_box_reverse,preview_msg_subject,preview_msg_tip,call_back) {
+        if(this.is_local_folder(folder)) {
+
+            //MAILARCHIVER-01
+            
+            //var baseFolder = folder.substr(6);
+            var baseFolder = folder.replace('local_messages_', '');
+            var tree_name;
+            //var drawinginfo = {treeObject: tree_name, treeName: tree_name, folderName: baseFolder};
+            var drawinginfo = {};
+            expresso_mail_archive.update_counters = false;
+            expresso_mail_archive.currentfolder = baseFolder;
+            expresso_mail_archive.getFolderInfo(expresso_mail_archive.currentfolder);
+            expresso_mail_archive.drawdata = drawinginfo;
+
+            if(tree_name == 'tree_folders'){ //only the 'tree_folders' must show messages. 'folders_tree' are just for managment operation
+                var exp_dfs = new Array(baseFolder,msg_range_begin,emails_per_page,sort_box_type,search_box_type, sort_box_reverse,preview_msg_subject,preview_msg_tip);
+                expresso_mail_archive.queryconfig.setExpressoDefaults(exp_dfs);
+                expresso_mail_archive.listMessages();
+            }
+            else{
+                if (!tree_name){
+                    //window.alert('sem arvore para atualizar, com sort_box_type =' + sort_box_type + ' e search_box_type= ' + search_box_type + ' reverse -- ' + sort_box_reverse);
+                    var exp_dfs = new Array(baseFolder,msg_range_begin,emails_per_page,sort_box_type,search_box_type,sort_box_reverse,preview_msg_subject,preview_msg_tip);
+                    expresso_mail_archive.queryconfig.setExpressoDefaults(exp_dfs);
+                    expresso_mail_archive.listMessages();
+                }
+                if(tree_name == 'folders_tree'){
+                    /*var div_export_local = document.createElement('div');
+                    div.style.width
+                    var lbl_check = document.createElement('label');
+                    var check_export_local_recursive = document.createElement('input');
+                    var lbl_combo = document.createElement('label');
+                    var combo_export_local_format = document.createElement('select');*/
+                    //window.alert('alert td content = ' + Element('div_buttons').getElementsByTagName('table')[0].tbody[0].tr[4].td[0].innerHTML);
+                    //Element('div_buttons').appendChild(div_export_local);
+                }
+            }
+
+        }else {
+            $.ajax({
+                url: "controller.php?" + $.param( {action: "$this.imap_functions.get_range_msgs3", 
+                                    folder: folder, 
+                                    msg_range_begin: msg_range_begin, 
+                                    msg_range_end: emails_per_page, 
+                                    sort_box_type: sort_box_type, 
+                                    search_box_type: search_box_type, 
+                                    sort_box_reverse: sort_box_reverse } ),
+
+                  success: function( data ){
+                    data = connector.unserialize(data);
+                    
+                    if( data )
+                        call_back( data );
+                  },
+                  beforeSend: function( jqXHR, settings ){
+                    connector.showProgressBar();
+                  },
+                  complete: function( jqXHR, settings ){
+                    connector.hideProgressBar();
+                  }
+              
+            });
+        }
+    }
+	messages_proxy.prototype.messages_list_old = function(folder,msg_range_begin,emails_per_page,sort_box_type,search_box_type,sort_box_reverse,preview_msg_subject,preview_msg_tip,call_back) {
 		if(this.is_local_folder(folder)) {
 			var real_folder = folder.substr(6);		
@@ -53,9 +118,13 @@
 	messages_proxy.prototype.get_msg = function(msg_number,msg_folder,set_flag,call_back) {
 		if(this.is_local_folder(msg_folder)) {
-			if(set_flag)
-				expresso_local_messages.set_messages_flag(msg_number,"seen");
-			var data = expresso_local_messages.get_local_mail(msg_number);	
-
-			eval("call_back(data)");
+			
+
+            //if(set_flag)
+			// 	expresso_local_messages.set_messages_flag(msg_number,"seen");
+			// var data = expresso_local_messages.get_local_mail(msg_number);	
+            //MAILARCHIVER-02
+            expresso_mail_archive.getMessage(msg_number);
+
+			//eval("call_back(data)");
 		}else{
 		    $.ajax({
@@ -86,7 +155,11 @@
 		if (folder == 'null')
 			folder = get_current_folder();
-		if (msgs_number == 'selected')
-			msgs_number = get_selected_messages();
-		
+
+        //Validação para recuperar o id caso não seja aba de listagem
+		if (msgs_number == 'selected' && currentTab != 0) //Recupera apenas o id da mensagem aberta
+			msgs_number = currentTab.substr(0,currentTab.indexOf('_r'));
+        else if (msgs_number == 'selected' && currentTab == 0)
+            msgs_number = get_selected_messages();
+
 		if(currentTab != 0 && currentTab.indexOf("search_")  >= 0){
 			var content_search = document.getElementById('content_id_'+currentTab);
@@ -100,18 +173,115 @@
 		if (!this.is_local_folder(folder)){
 			delete_msgs(folder, msgs_number, border_ID);
-		}else {
-			if((folder != 'local_Trash') && (expresso_local_messages.as_trash())){
-				expresso_local_messages.move_messages('Trash', msgs_number);
-				this.aux_interface_remove_mails(msgs_number, 'local_Trash', border_ID);
-				draw_tree_local_folders();
-				update_local_box(); 
-				refresh(); 
-			}else{
-			expresso_local_messages.delete_msgs(msgs_number, border_ID);
-			draw_tree_local_folders();
-				update_local_box(); 
-				refresh();
-			}
-		}
+		}else {    
+            //MAILARCHIVER-03
+            var msg_to_delete = Element(msgs_number);
+            //user has preference to show previous message on deleting one
+            if (isNaN(currentTab) && parseInt(preferences.delete_and_show_previous_message) && msg_to_delete) {
+                    if (msg_to_delete.previousSibling){ 
+                            var previous_msg = msg_to_delete.previousSibling.id;
+                            
+                            //user has preference to maintain default folder structure at local folders, so we have trash folder
+                            if(preferences.auto_create_local == 1){
+                                //user has preference to "save" delete messasge on trash folder, so move it to there
+                                if (((preferences.save_deleted_msg == true)) && (folder != expresso_mail_archive.specialfolders.trash)){
+                                    expresso_mail_archive.folder_destination = 'trash';
+                                    expresso_mail_archive.moveMessages(expresso_mail_archive.folder_destination, msgs_number);
+                                    delete_border(currentTab,'false'); 
+                                    expresso_mail_archive.getMessage(previous_msg);
+                                }
+                                //user does not want to save messages deleted on trash. purge them imediatly
+                                else{
+                                    expresso_mail_archive.deleteMessages(msgs_number);
+                                    delete_border(currentTab,'false'); 
+                                    expresso_mail_archive.getMessage(previous_msg)
+                                }                                                                                
+                            }
+                            //maybe, we do not have trash.
+                            else{
+                                //user has preference to "save" delete messasge on trash folder, so move it to there
+                                if (((preferences.save_deleted_msg == true)) && (folder != expresso_mail_archive.specialfolders.trash)){
+                                    expresso_mail_archive.createFolder("","Trash");
+                                    expresso_mail_archive.folder_destination = 'trash';
+                                    expresso_mail_archive.moveMessages(expresso_mail_archive.folder_destination, msgs_number);
+                                    delete_border(currentTab,'false');
+                                    expresso_mail_archive.getMessage(previous_msg);
+                                }
+                                //user does not want to save messages deleted on trash. purge them imediatly
+                                else{
+                                    expresso_mail_archive.deleteMessages(msgs_number);
+                                    delete_border(currentTab,'false'); 
+                                    expresso_mail_archive.getMessage(previous_msg)
+                                }                                          
+                            }
+                    } 
+                    //there is no previous message existing to show. Just delete de view context
+                    else{ 
+                           //user has preference to maintain default folder structure at local folders, so we have trash folder
+                           if(preferences.auto_create_local == 1){
+                                if (((preferences.save_deleted_msg == true)) && (folder != expresso_mail_archive.specialfolders.trash)){
+                                    expresso_mail_archive.folder_destination = 'trash';
+                                    expresso_mail_archive.moveMessages(expresso_mail_archive.folder_destination, msgs_number);
+                                    delete_border(currentTab,'false'); 
+                                }
+                                //user does not want to save messages deleted on trash. purge them imediatly
+                                else{
+                                    expresso_mail_archive.deleteMessages(msgs_number);
+                                    delete_border(currentTab,'false'); 
+                                }                                       
+                           }
+                            //maybe, we do not have trash. Purge message so.
+                            else{
+                                //user has preference to "save" delete messasge on trash folder, so move it to there
+                                if (((preferences.save_deleted_msg == true)) && (folder != expresso_mail_archive.specialfolders.trash)){
+                                    expresso_mail_archive.createFolder("","Trash");
+                                    expresso_mail_archive.folder_destination = 'trash';
+                                    expresso_mail_archive.moveMessages(expresso_mail_archive.folder_destination, msgs_number);
+                                    expresso_mail_archive.getMessage(previous_msg);
+                                }
+                                //user does not want to save messages deleted on trash. purge them imediatly
+                                else{
+                                    expresso_mail_archive.deleteMessages(msgs_number);
+                                }                                    
+                            }
+                    } 
+            } 
+            //user has no preferece to show previous message on deleting
+            else{ 
+                if(preferences.auto_create_local == 1){
+                    //user has preference to "save" delete messasge on trash folder, so move it to there
+                    if (((preferences.save_deleted_msg == true)) && (folder.replace('messages_','') != expresso_mail_archive.specialfolders.trash)){
+                        expresso_mail_archive.folder_destination = 'trash';
+                        expresso_mail_archive.moveMessages(expresso_mail_archive.folder_destination, msgs_number);
+                        delete_border(currentTab,'false');
+                    }
+                    //user does not want to save messages deleted on trash (or is cleaning it). purge them imediatly
+                    else{
+                        expresso_mail_archive.deleteMessages(msgs_number);
+                        delete_border(currentTab,'false');
+                    }                            
+                }
+                //maybe, we do not have trash. Purge message so.
+                else{
+                    //user has preference to "save" delete messasge on trash folder, so move it to there
+                    if (((preferences.save_deleted_msg == true)) && (folder.replace('messages_','') != expresso_mail_archive.specialfolders.trash)){
+                        expresso_mail_archive.createFolder("","Trash");
+                        expresso_mail_archive.folder_destination = 'trash';
+                        expresso_mail_archive.moveMessages(expresso_mail_archive.folder_destination, msgs_number);
+                    }
+                    //user does not want to save messages deleted on trash. purge them imediatly
+                    else{
+                        expresso_mail_archive.deleteMessages(msgs_number);
+                    }     
+                }
+            }
+		}
+
+        //Código adicionado para o correto funcionamento da seleção independente de paginação.
+        $.each(msgs_number.split(","), function(index, value){
+            delete selectedPagingMsgs[value];
+        });
+        totalFolderMsgs = totalFolderMsgs - msgs_number.split(",").length;
+        selectAllFolderMsgs(false);
+        updateSelectedMsgs();
 	}
 	
@@ -119,7 +289,10 @@
 
 		if(info_msg.local_message==true) {
-			return "javascript:download_local_attachment('"+
-					expresso_local_messages.get_url_anexo(info_msg.msg_number,info_msg.attachments[numero_ordem_anexo].pid)+
-					"')";
+            //ma serpro
+			// return "javascript:download_local_attachment('"+
+			// 		expresso_local_messages.get_url_anexo(info_msg.msg_number,info_msg.attachments[numero_ordem_anexo].pid)+
+			// 		"')";
+            //MAILARCHIVER-04
+            return "javascript:download_local_attachment('"+ mail_archive_protocol+'://'+mail_archive_host+':'+mail_archive_port+'/temp/download/' +info_msg.attachments[numero_ordem_anexo].pid + "')";
 		}
 		else {
@@ -139,27 +312,103 @@
 	
 	messages_proxy.prototype.proxy_set_messages_flag = function (flag,msg_number){
-		if(this.is_local_folder(get_current_folder())) {
-			expresso_local_messages.set_messages_flag(msg_number,flag);
-		}
-		else {
-			set_messages_flag(flag,msg_number);
-				// Verifica se a pasta que esta selecionada contem a opção "Não lidas" ativada
-				// caso exista, ele chama novamente a opção "Não lidas" para atualizar a pasta.
-				if('UNSEEN' == search_box_type)
-					return sort_box('UNSEEN','SORTARRIVAL');
-		}
-	}
-	
-	messages_proxy.prototype.proxy_set_message_flag = function (msg_number,flag,func_after_flag_change){
-		var msg_number_folder = Element("new_input_folder_"+msg_number+"_r"); //Mensagens respondidas/encaminhadas
+        //MAILARCHIVER
+        if(this.is_local_folder(get_current_folder())) {           
+            var msglist = get_selected_messages();    
+            var arrlist = msglist.split(",");
+            var operation;
+            var strtag;
+            
+            for(var i in arrlist){
+                switch(flag.toLowerCase()){
+                    case 'unseen':
+                        strtag = "unseen";
+                        operation = 0;
+                        set_msg_as_unread(arrlist[i]);
+                        break;
+                    case 'seen':
+                        strtag = "unseen";
+                        operation = 1;
+                        set_msg_as_read(arrlist[i]);
+                        break;
+                    case 'flagged':
+                        strtag = "flagged, importance_high";
+                        operation = 0;
+                        set_msg_as_flagged(arrlist[i]);
+                        break;
+                    case 'unflagged':
+                        strtag = "flagged, importance_high";
+                        operation = 1;
+                        set_msg_as_unflagged(arrlist[i]);
+                        break;
+                }
+                expresso_mail_archive.currenttag = flag;
+                var tl = expresso_mail_archive.pattern.tagConfig(strtag, arrlist[i], operation);
+                expresso_mail_archive.taglist = tl;                             
+                expresso_mail_archive.progressbar = window.setTimeout("expresso_mail_archive.tagMessage()",1);
+            }
+        }
+        else {
+            set_messages_flag(flag,msg_number);
+            // Verifica se a pasta que esta selecionada contem a opção "Não lidas" ativada
+            // caso exista, ele chama novamente a opção "Não lidas" para atualizar a pasta.
+            if('UNSEEN' == search_box_type)
+                return sort_box('UNSEEN','SORTARRIVAL');
+        }
+	}
+	
+	messages_proxy.prototype.proxy_set_message_flag = function (msg_number,flag,func_after_flag_change,msgid){
+        var msg_number_folder = Element("new_input_folder_"+msg_number+"_r"); //Mensagens respondidas/encaminhadas
 		if(!msg_number_folder)
 			var msg_number_folder = Element("input_folder_"+msg_number+"_r"); //Mensagens abertas
 		var folder = msg_number_folder ?  msg_number_folder.value : get_current_folder();
-		if(this.is_local_folder(folder)) {
-			expresso_local_messages.set_message_flag(msg_number,flag, func_after_flag_change);
-		}
-		else {
-			set_message_flag(msg_number,flag, func_after_flag_change);
-		}
+
+        //MAILARCHIVER
+        if(this.is_local_folder(folder)) {
+            if(!msgid)
+                msgid = msg_number;
+            var taglist = flag;
+            var operation;
+    
+            switch(flag.toLowerCase()){
+                case 'unseen':
+                    strtag = "unseen";
+                    operation = 0;
+                    set_msg_as_unread(msgid);
+                    break;
+                case 'seen':
+                    strtag = "unseen";
+                    operation = 1;
+                    set_msg_as_read(msgid);
+                    break;
+                case 'flagged':
+                    strtag = 'flagged, importance_high';
+                    operation = 0;
+                    set_msg_as_flagged(msgid);
+                    break;
+                case 'unflagged':
+                    strtag = "flagged, importance_high";
+                    operation = 1;
+                    set_msg_as_unflagged(msgid);
+                    break;
+                case 'forwarded':
+                    strtag = "forwarded";
+                    operation = 0;
+                    set_msg_as_flagged(msgid);
+                case 'answered':
+                    strtag = "answered";
+                    operation = 0;
+                    set_msg_as_flagged(msgid);                                  
+                    
+            }                
+            
+            expresso_mail_archive.drawdata = null;
+            var tl = expresso_mail_archive.pattern.tagConfig(strtag, msgid, operation);
+            expresso_mail_archive.currenttag = flag;
+            expresso_mail_archive.taglist = tl;
+            expresso_mail_archive.progressbar = window.setTimeout("expresso_mail_archive.tagMessage()",1);
+        }
+        else {
+            set_message_flag(msg_number,flag, func_after_flag_change);
+        }
 	}
 	
@@ -290,43 +539,68 @@
 		if (! folder || folder == 'null')
 			folder = Element("input_folder_"+msgs_number+"_r") ? Element("input_folder_"+msgs_number+"_r").value : (openTab.imapBox[currentTab] ? openTab.imapBox[currentTab]:get_current_folder());
-		if ((this.is_local_folder(folder)) && (this.is_local_folder(new_folder))) { //Move entre pastas não locais...
-			if (folder == new_folder){
-				write_msg(get_lang('The origin folder and the destination folder are the same.'));
+
+        //MAILARCHIVER-08
+        if (this.is_local_folder(folder)){
+            expresso_mail_archive.update_counters = true;
+            //Folder de onde sai a mensagem Ã© local (armazenamento local)
+            if (folder == new_folder){
+                write_msg(get_lang('The origin folder and the destination folder are the same.'));
 				return;
-			}
-			if(msgs_number=='selected')
-				msgs_number = get_selected_messages();
-			if (new_folder == 'local_root')
-				alert(get_lang("Select a folder!"));
-			if (parseInt(msgs_number) > 0 || msgs_number.length > 0) {
-				expresso_local_messages.move_messages(new_folder.substr(6), msgs_number);
-				this.aux_interface_remove_mails(msgs_number, new_folder_name, border_ID);
-				draw_tree_local_folders();
-                                update_local_box();
-			}
-			else 
-				write_msg(get_lang('No selected message.'));
-		}
-		else 
-			if ((!this.is_local_folder(folder)) && (!this.is_local_folder(new_folder))) { //Move entre pastas locais...
-				move_msgs(folder, msgs_number, border_ID, new_folder, new_folder_name);
-			}else if ((!this.is_local_folder(folder)) && (this.is_local_folder(new_folder))) {
-				if(msgs_number=='selected')
-					archive_msgs(folder,new_folder);
-				else
-					archive_msgs(folder,new_folder,msgs_number);
-
-				
-				draw_tree_local_folders();
-				refresh();
-			}
-			else {
-                //Por Bruno Costa (bruno.vieira-costa@serpro.gov.br) permite o desarquivamento de menssagens chamando a função unarchive_msgs quando uma msg é movida de uma pasta local para uma pasta remota.
-
-				expresso_local_messages.unarchive_msgs(folder,new_folder,msgs_number);
-                //write_msg(get_lang("you can't move mails from local to server folders"));
-			}
-		
-		
+            }                    
+
+            //Validação para recuperar o id caso não seja aba de listagem
+            if (msgs_number == 'selected' && currentTab != 0) //Recupera apenas o id da mensagem aberta
+                msgs_number = currentTab.substr(0,currentTab.indexOf('_r'));
+            else
+                msgs_number = get_selected_messages();
+
+            if (new_folder == 'local_root'){
+                alert(get_lang("Select a folder!"));
+            }
+                        
+            if (parseInt(msgs_number) > 0 || msgs_number.length > 0) {
+                if (this.is_local_folder(new_folder)){
+                    //esta tirando de um folder local para outro folder local
+                    expresso_mail_archive.moveMessages(new_folder.replace("local_messages_",""), msgs_number);
+                    if(currentTab != 0)
+                        delete_border(currentTab,'false'); 
+                }
+                else{
+                    //esta tirando de um folder local para um folder IMAP (desarquivamento)
+                    if(!new_folder){
+                        new_folder = 'INBOX';
+                    }
+                    if(currentTab.toString().indexOf("_r") != -1){
+                        msgs_number = currentTab.toString().substr(0,currentTab.toString().indexOf("_r"));
+                    }                      
+                    expresso_mail_archive.unarchieve(folder, new_folder, msgs_number);
+                }
+            }
+            else{
+                write_msg(get_lang('No selected message.'));
+            }
+        }else{
+            if (this.is_local_folder(new_folder)){
+                //esta tirando de um folder nÃ£o local para um folder local (arquivamento)
+                if(msgs_number=='selected'){
+                    archive_msgs(folder, new_folder);
+                }
+                else{
+                    archive_msgs(folder, new_folder, msgs_number);
+                }
+            }
+            else{
+                //esta tirando de um folder nÃ£o local para outro folder nÃ£o local (move)
+                move_msgs(folder, msgs_number, border_ID, new_folder, new_folder_name);
+            }
+        }	
+
+        //Adicionado código para o correto funcionamento da seleção independente de paginação.
+        $.each(msgs_number.split(","), function(index, value){
+            delete selectedPagingMsgs[value];
+        });
+        totalFolderMsgs = totalFolderMsgs - msgs_number.split(",").length;
+        selectAllFolderMsgs(false);
+        updateSelectedMsgs();
 	}
 	
@@ -462,15 +736,30 @@
 
     messages_proxy.prototype.export_all_messages = function(folder){
-
-		if (!folder){
-			folder = get_current_folder();
-		}
-
-		if(!this.is_local_folder(folder)){
-			export_all_selected_msgs();
-		}else{
-			local_messages.prototype.local_messages_to_export();
-		}
-	}
+        if (!folder) {
+            folder = get_current_folder();
+        }
+
+        if(!this.is_local_folder(folder) || folder.split("_")[0] == "local"){
+            export_all_selected_msgs();
+        }else{
+            local_messages.prototype.local_messages_to_export();
+        }
+	}
+	
+
+
+	/* Airton
+	* Método que vai chamar efetivamente o método Archive.
+	* TO-DO: Tirar desse arquivo o método e passar pra outro arquivo
+	*/
+	messages_proxy.prototype.archive_message = function(folder, msgs_number) {
+		if(msgs_number == 'get_selected_messages')
+			msgs_number = get_selected_messages();
+			
+		expresso_mail_archive.Archive("INBOX", "inbox", msgs_number);
+	}
+	
+	
+	
 	/*
     	messages_proxy.prototype.proxy_export_all_msg=function(){
Index: trunk/expressoMail1_2/js/local_messages.js
===================================================================
--- trunk/expressoMail1_2/js/local_messages.js	(revision 5264)
+++ trunk/expressoMail1_2/js/local_messages.js	(revision 7414)
@@ -157,5 +157,8 @@
 
 local_messages.prototype.init_local_messages = function(){ //starts only database operations
-		
+		return 'retorno local_messages.prototype.init_local_messages';
+}
+
+local_messages.prototype.init_local_messages_old = function(){
     if(this.dbGears==null || this.localServer==null || this.store == null)
 	this.create_objects();
@@ -835,5 +838,7 @@
 
 local_messages.prototype.get_local_range_msgs = function(folder,msg_range_begin,emails_per_page,sort,sort_reverse,search,preview_msg_subject,preview_msg_tip) {
-
+        this.init_local_messages();
+}
+local_messages.prototype.get_local_range_msgs_old = function(folder,msg_range_begin,emails_per_page,sort,sort_reverse,search,preview_msg_subject,preview_msg_tip) {
     this.init_local_messages();
     var retorno = new Array();
Index: trunk/expressoMail1_2/js/MAExpressoPattern.js
===================================================================
--- trunk/expressoMail1_2/js/MAExpressoPattern.js	(revision 7414)
+++ trunk/expressoMail1_2/js/MAExpressoPattern.js	(revision 7414)
@@ -0,0 +1,1663 @@
+<!--
+/* 
+ * MailArchiver Expresso Pattern serialized format
+ * ---
+ * This resources intended to be used on converting data formats, to make
+ * it work on ExpressoMail pattern.
+ * 
+ * Basicly, it gets all the service return data (almost enveloped at SOAP 
+ * webservices spec i.e XML data), and then transform it to the serialized
+ * pattern used by Expresso (somethink almost close or near JSON Javascript 
+ * objects).
+ * 
+ * @author Fernando Wendt [fernando-alberto.wendt@serpro.gov.br]
+ *
+ * @status under development
+ * 
+ */
+var MAPattern = function(){
+    
+}
+// -----------------------------------SERIALIZED DATA TEMPLATES ----------------
+MAPattern.prototype.toExpressoAddress = function(data){   
+    if((typeof(data) != 'undefined') && (data.length > 0)){
+
+        if((typeof(data) != 'string') || (data.indexOf("{") == -1)){
+            var objMsg = expresso_mail_archive.getMessageServiceObject(data);
+            var attData = objMsg.getTo();
+            var Fromdata = attData ? eval("(" + attData + ")") : null;
+            if (Fromdata == null)
+                return('N;');
+        }
+        else{
+            var Fromdata = data ?  eval("(" + data + ")") : null;
+            if (Fromdata == null){
+                return('N;');     
+            }
+            else{
+                if((!Fromdata.mailbox) && (!Fromdata.groupbox)){
+                    var nofrom = get_lang('Sender not identified');
+                    return('a:2{s:4:"name";s:' + nofrom.length + ':"' + nofrom + '";s:5:"email";s:'+nofrom.length +':"'+nofrom +'";}');
+                }
+            }
+        }       
+        
+        //var Fromdata = eval("(" + data + ")");
+        if(Fromdata.mailbox){
+            //just one address to pharse: length is undefined
+            if(typeof(Fromdata.mailbox.length) == 'undefined'){
+                var objfrom = Fromdata.mailbox;
+                flag1 = 1;
+            }
+            else{
+                var objfrom = Fromdata.mailbox[0];
+                flag1 = 2;
+            }
+            
+            if(objfrom["@name"] != 'null')
+                var dataName = (objfrom["@name"]);
+            else
+                var dataName = "";
+                
+            if(objfrom["@localPart"] != 'null')
+                var dataEmailPart = (objfrom["@localPart"]);
+            else 
+                var dataEmailpart = "";
+                
+            if(objfrom["@domain"] != 'null')
+                var dataEmailDomain = (objfrom["@domain"]);
+            else
+                var dataEmailDomain = "";
+                
+            if(dataEmailDomain != "")
+                var dataEmail =  dataEmailPart + '@' + dataEmailDomain;
+            else
+                var dataEmail =  dataEmailPart;
+                                
+            if(dataName == '')
+                dataName = dataEmail;
+                
+            var dataTmp = '\"'+dataName+'\"&lt;'+dataEmail+'&gt;'
+            var tplFrom = 'a:3:{'
++                         's:4:"name";'
++                         's:'+dataName.length+':"'+dataName+'";'
++                         's:5:"email";'
++                         's:'+dataEmail.length+':"'+dataEmail+'";'
++                         's:4:"full";'
++                         's:'+(dataTmp.length)+':"'+dataTmp+'";'
++                         '}';                
+        }
+        else{
+            if(Fromdata.group){
+                //just one address to pharse: length is undefined
+                if(typeof(Fromdata.group.length) == 'undefined'){
+                    if(Fromdata.group["@name"]){
+                        var dataName = Fromdata.group["@name"];
+                    }
+                    else
+                        var dataName = null;
+                    
+                    if(Fromdata.group["@localPart"]){
+                        var dataEmail = Fromdata.group["@localPart"] + '@' + Fromdata.group["@domain"];
+                    }
+                    else
+                        var dataEmail = null;
+                    
+                    if(dataName == 'null')
+                        dataName = dataEmail;
+                }
+                //address list to pharse, but to header(folder list messages action), only first metters
+                else{
+                    var dataName = Fromdata.group[0]["@name"];
+                    var dataEmail = Fromdata.group[0]["@localPart"] + '@' + Fromdata.group[0]["@domain"];
+                    if(dataName == 'null')
+                        dataName = dataEmail;
+                }
+            
+            if((dataName != null) && (dataEmail != null)){
+                var dataTmp = '\"'+dataName+'\"&lt;'+dataEmail+'&gt;'
+                var tplFrom = 'a:3:{'
++                         's:4:"name";'
++                         's:'+dataName.length+':"'+dataName+'";'
++                         's:5:"email";'
++                         's:'+dataEmail.length+':"'+dataEmail+'";'
++                         's:4:"full";'
++                         's:'+(dataTmp.length)+':"'+dataTmp+'";'
++                         '}';               
+            }
+            else{
+                if(dataName!= null){
+                var tplFrom = 'a:2:{'
++                         's:4:"name";'
++                         's:'+dataName.length+':"'+dataName+'";'
++                         's:4:"full";'
++                         's:'+(dataName.length)+':"'+dataName+'";'
++                         '}';                     
+                }
+                else{
+                    if(dataEmail != null){
+                    var tplFrom = 'a:2:{'
++                         's:4:"email";'
++                         's:'+dataEmail.length+':"'+dataEmail+'";'
++                         's:4:"full";'
++                         's:'+(dataEmail.length)+':"'+dataEmail+'";'
++                         '}';                         
+                    }
+                    else tplFrom = 'a:2{s:4:"name";s:14:"Unknow mailbox";s:5:"email";s:15:"Unknow_mailbox";}';
+                }
+            }
+           }   
+           //Data adrress from mailbox is empty, null, or canot be correctly returned by service invocation (will return 'unknow mailbox' string)
+           else {
+                tplFrom = 'N;';
+           }       
+        }
+    }
+    else{
+        tplFrom = 'N;';
+    }
+    return(tplFrom);
+}
+
+MAPattern.prototype.toExpressoCc = function(data){
+    if((typeof(data) != 'undefined') && (data.length > 0)){
+        var Fromdata = eval("(" + data + ")");
+        if(Fromdata.mailbox){
+        //just one address to pharse: length is undefined
+            if(typeof(Fromdata.mailbox.length) == 'undefined'){
+                var dataName = Fromdata.mailbox["@name"];
+                var dataEmail = Fromdata.mailbox["@localPart"] + '@' + Fromdata.mailbox["@domain"];
+                if (dataName == 'null')
+                    var dataFull = 's:'+(dataEmail.length)+':"'+dataEmail+'";';
+                else{
+                    var dataTmp = '\"'+dataName+'\"&lt;'+dataEmail+'&gt;'
+                    var dataFull = 's:'+(dataTmp.length)+':"'+dataTmp+'";'
+                }
+            }
+            //address list to pharse, but to header(folder list messages action), only first metters
+            else{
+                    var dataTmp = '';
+                    for( i in Fromdata.mailbox){
+                        var dataName = Fromdata.mailbox[i]["@name"];
+                        var dataEmail = Fromdata.mailbox[i]["@localPart"] + '@' + Fromdata.mailbox[i]["@domain"];
+                        if (dataName == 'null')
+                             dataTmp = dataTmp + dataEmail+',';
+                        else{
+                             dataTmp = dataTmp + '\"'+dataName+'\"&lt;'+dataEmail+'&gt;,';
+                            }
+                }
+                dataTmp = dataTmp.substring(0,(dataTmp.length - 1));
+                 var dataFull = 's:'+(dataTmp.length)+':"'+dataTmp+'";'
+
+            }
+
+            var tplCc = dataFull;
+
+        }
+        else {
+            tplCc = 'N;';
+        }
+    }
+    //Data adrress from mailbox is empty, null, or canot be correctly returned by service invocation (will return 'unknow mailbox' string)
+    else {
+        tplCc = 'N;';
+    }
+    
+    return(tplCc);
+    
+}
+
+MAPattern.prototype.toExpressoDispositionNotificationTo = function(data){
+    var objMsg = expresso_mail_archive.getMessageServiceObject(data);
+    var dntData = objMsg.getDispositionNotificationTo();
+
+    if((typeof(dntData) != 'undefined') && (dntData.length > 0)){
+        var notificationData = eval("(" + dntData + ")");
+        if(notificationData.mailbox){
+            //just one address to pharse: length is undefined
+            if(typeof(notificationData.mailbox.length) == 'undefined'){
+                var dataEmail = notificationData.mailbox["@localPart"] + '@' + notificationData.mailbox["@domain"];
+            }
+            //address list to parse, but to header(folder list messages action), only first matters
+            else{
+                var dataEmail = notificationData.mailbox[0]["@localPart"] + '@' + notificationData.mailbox[0]["@domain"];
+            }
+
+            var tplNotification = 's:25:"DispositionNotificationTo";s:' + dataEmail.length + ':"' + dataEmail + '";'
+        }
+        //Data adrress from mailbox is empty, null, or canot be correctly returned by service invocation (will return 'unknow mailbox' string)
+        else {
+            tplNotification = 's:25:"DispositionNotificationTo";N;';
+        }
+    }
+    else {
+        tplNotification = 's:25:"DispositionNotificationTo";N;';
+    }
+
+    return tplNotification;
+}
+
+MAPattern.prototype.toExpressoAddress2 = function(data){
+    if((typeof(data) != 'undefined') && (data.length > 0)){
+        if((typeof(data) != 'string') || (data.indexOf("{") == -1)){
+            var objMsg = expresso_mail_archive.getMessageServiceObject(data);
+            var attData = objMsg.getTo();
+            var Fromdata = attData ? eval("(" + attData + ")") : null;
+            if (Fromdata == null){                
+                var noto = get_lang("without destination");
+                return('s:10:"toaddress2";s:' + noto.length + ':"'+noto+'";');
+            }
+        }
+        else{
+            var Fromdata = data ?  eval("(" + data + ")") : null;
+            if (Fromdata == null)
+                return('s:10:"toaddress2";N;');                        
+        }       
+       
+        if(Fromdata && Fromdata.mailbox){
+            //just one address to pharse: length is undefined
+            if(typeof(Fromdata.mailbox.length) == 'undefined'){
+                var dataEmail = Fromdata.mailbox["@localPart"] + '@' + Fromdata.mailbox["@domain"];
+            }
+            //address list to pharse, but to header(folder list messages action), only first metters
+            else{
+                var datatmp = "";
+                for(var k=0; k<Fromdata.mailbox.length; k++){                    
+                    if(Fromdata.mailbox[k]["@name"] != 'null'){
+                        datatmp += '"' + Fromdata.mailbox[k]["@name"] + '" ';
+                        if(Fromdata.mailbox[k]["@localPart"] != 'null')
+                            datatmp += '&lt;' + Fromdata.mailbox[k]["@localPart"];
+                        if(Fromdata.mailbox[k]["@domain"] != 'null')
+                            datatmp += '@' + Fromdata.mailbox[k]["@domain"] + '&gt;';                    
+                        else
+                            datatmp += '&gt;';
+                    }
+                    else{
+                        if(Fromdata.mailbox[k]["@localPart"] != 'null')
+                            datatmp += Fromdata.mailbox[k]["@localPart"];
+                        if(Fromdata.mailbox[k]["@domain"] != 'null')
+                            datatmp += '@' + Fromdata.mailbox[k]["@domain"];
+                    }
+                    if(datatmp != '')
+                        datatmp += ', ';
+                }
+                datatmp = datatmp.substr(0, datatmp.length -2);
+                var dataEmail = datatmp;
+                
+                //var dataEmail = Fromdata.mailbox[0]["@localPart"] + '@' + Fromdata.mailbox[0]["@domain"];
+            }
+
+            //var tplAddr2 = 's:10:"toaddress2";s:' + dataEmail.length + ':"' + dataEmail + '";'
+            var tplAddr2 = 's:10:"toaddress2";s:' + dataEmail.length + ':"' + dataEmail + '";'
+        }
+        else{
+            if(Fromdata && Fromdata.group){
+                //just one address group to pharse
+                if(typeof(Fromdata.group.length) == 'undefined'){   
+                    //there is a group email identifier
+                    if(Fromdata.group['@localPart']){
+                        var dataEmail = Fromdata.group["@localPart"] + '@' + Fromdata.group["@domain"];
+                    }
+                    //there is no email identifier, will try by name
+                    else{
+                        if(Fromdata.group['@name']){
+                            var dataEmail = '"' + Fromdata.group['@name'] + '"';                        
+                        }
+                        else{
+                            dataEmail = 'N';
+                        }
+                    } 
+
+                }
+                //group address list to pharse, but to header(folder list messages action), only first metters
+                else{
+                    var dataEmail = Fromdata.group[0]["@localPart"] + '@' + Fromdata.group[0]["@domain"];
+                }
+
+                var tplAddr2 = 's:10:"toaddress2";s:' + dataEmail.length + ':"' + dataEmail + '";'                
+            }
+            //Data adrress from mailbox is empty, null, or canot be correctly returned by service invocation (will return 'unknow mailbox' string)
+            else {
+                tplAddr2 = 's:10:"toaddress2";s:1:"N";';
+            }
+        }
+
+    }
+    else{
+        //tplAddr2 = 's:10:"toaddress2";s:1:"";';
+        var noto = get_lang("without destination");
+        tplAddr2 = 's:10:"toaddress2";s:' + noto.length + ':"'+noto+'";';
+    }
+    return(tplAddr2);
+}
+
+
+MAPattern.prototype.toExpressoSender = function(data){
+    if((typeof(data) != 'undefined') && (data.length > 0)){
+        if((typeof(data) != 'string') || (data.indexOf("{") == -1)){
+            var objMsg = expresso_mail_archive.getMessageServiceObject(data);
+            var attData = objMsg.getSender();
+            var Fromdata = attData ? eval("(" + attData + ")") : null;
+            if (Fromdata == null)
+                return('s:6:"sender";N;');
+        }
+        else{
+            var Fromdata = data ?  eval("(" + data + ")") : null;
+            if (Fromdata == null)
+                return('s:6:"sender";N;');                        
+        }       
+        
+        //var Fromdata = eval("(" + data + ")");
+        if(Fromdata.mailbox){
+            //just one address to pharse: length is undefined
+            if(typeof(Fromdata.mailbox.length) == 'undefined'){
+                var objfrom = Fromdata.mailbox;
+                flag1 = 1;
+            }
+            else{
+                var objfrom = Fromdata.mailbox[0];
+                flag1 = 2;
+            }
+            
+            if(objfrom["@name"] != 'null')
+                var dataName = (objfrom["@name"]);
+            else
+                var dataName = "";
+                
+            if(objfrom["@localPart"] != 'null')
+                var dataEmailPart = (objfrom["@localPart"]);
+            else 
+                var dataEmailpart = "";
+                
+            if(objfrom["@domain"] != 'null')
+                var dataEmailDomain = (objfrom["@domain"]);
+            else
+                var dataEmailDomain = "";
+                
+            if(dataEmailDomain != "")
+                var dataEmail =  dataEmailPart + '@' + dataEmailDomain;
+            else
+                var dataEmail =  dataEmailPart;
+                
+            if(dataName == '')
+                dataName = dataEmail;
+                
+            var dataTmp = '\"'+dataName+'\"&lt;'+dataEmail+'&gt;'
+            
+            var tplFrom = 'a:3:{'
++                         's:4:"name";'
++                         's:'+dataName.length+':"'+dataName+'";'
++                         's:5:"email";'
++                         's:'+dataEmail.length+':"'+dataEmail+'";'
++                         's:4:"full";'
++                         's:'+(dataTmp.length)+':"'+dataTmp+'";'
++                         '}';                
+            }
+            else{
+                if(Fromdata.group){
+                    //just one address to pharse: length is undefined
+                    if(typeof(Fromdata.group.length) == 'undefined'){
+                        if(Fromdata.group["@name"]){
+                            var dataName = Fromdata.group["@name"];
+                        }
+                        else
+                            var dataName = null;
+                    
+                        if(Fromdata.group["@localPart"]){
+                            var dataEmail = Fromdata.group["@localPart"] + '@' + Fromdata.group["@domain"];
+                        }
+                        else
+                            var dataEmail = null;
+                    
+                        if(dataName == 'null')
+                            dataName = dataEmail;
+                    }
+                    //address list to pharse, but to header(folder list messages action), only first metters
+                    else{
+                        var dataName = Fromdata.group[0]["@name"];
+                        var dataEmail = Fromdata.group[0]["@localPart"] + '@' + Fromdata.group[0]["@domain"];
+                        if(dataName == 'null')
+                            dataName = dataEmail;
+                    }
+            
+                if((dataName != null) && (dataEmail != null)){
+                    var dataTmp = '\"'+dataName+'\"&lt;'+dataEmail+'&gt;'
+                    var tplFrom = 'a:3:{'
++                         's:4:"name";'
++                         's:'+dataName.length+':"'+dataName+'";'
++                         's:5:"email";'
++                         's:'+dataEmail.length+':"'+dataEmail+'";'
++                         's:4:"full";'
++                         's:'+(dataTmp.length)+':"'+dataTmp+'";'
++                         '}';               
+                }
+                else{
+                    if(dataName!= null){
+                    var tplFrom = 'a:2:{'
++                         's:4:"name";'
++                         's:'+dataName.length+':"'+dataName+'";'
++                         's:4:"full";'
++                         's:'+(dataName.length)+':"'+dataName+'";'
++                         '}';                     
+                    }
+                    else{
+                        if(dataEmail != null){
+                        var tplFrom = 'a:2:{'
++                         's:4:"email";'
++                         's:'+dataEmail.length+':"'+dataEmail+'";'
++                         's:4:"full";'
++                         's:'+(dataEmail.length)+':"'+dataEmail+'";'
++                         '}';                         
+                        }
+                        else tplFrom = 'a:2{s:4:"name";s:14:"Unknow mailbox";s:5:"email";s:15:"Unknow_mailbox";}';
+                    }
+                }
+            }   
+           else {
+                tplFrom = 'N;';
+           }       
+        }
+    }
+    else{
+        tplFrom = 'N;';
+    }
+    return('s:6:"sender";' + tplFrom);
+}
+
+MAPattern.prototype.toExpressoReplyTo = function(data){
+    if((typeof(data) != 'undefined') && (data.length > 0)){
+
+        if((typeof(data) != 'string') || (data.indexOf("{") == -1)){
+            var objMsg = expresso_mail_archive.getMessageServiceObject(data);
+            var attData = objMsg.getReplyTo();
+            var Fromdata = attData ? eval("(" + attData + ")") : null;
+            if (Fromdata == null)
+                return('s:8:"reply_to";N;');            
+        }
+        else{
+            var Fromdata = data ?  eval("(" + data + ")") : null;
+            if (Fromdata == null)
+                return('s:8:"reply_to";N;');                        
+        }       
+        
+        //var Fromdata = eval("(" + data + ")");        
+        if(Fromdata.mailbox){
+            //just one address to pharse: length is undefined
+            if(typeof(Fromdata.mailbox.length) == 'undefined'){
+                var objfrom = Fromdata.mailbox;
+                flag1 = 1;
+            }
+            else{
+                var objfrom = Fromdata.mailbox[0];
+                flag1 = 2;
+            }
+            
+            if(objfrom["@name"] != 'null')
+                var dataName = (objfrom["@name"]);
+            else
+                var dataName = "";
+                
+            if(objfrom["@localPart"] != 'null')
+                var dataEmailPart = (objfrom["@localPart"]);
+            else 
+                var dataEmailpart = "";
+                
+            if(objfrom["@domain"] != 'null')
+                var dataEmailDomain = (objfrom["@domain"]);
+            else
+                var dataEmailDomain = "";
+                
+            if(dataEmailDomain != "")
+                var dataEmail =  dataEmailPart + '@' + dataEmailDomain;
+            else
+                var dataEmail =  dataEmailPart;
+                
+            if(dataName == '')
+                tplFrom = dataEmail;
+            else
+                tplFrom = '\"'+dataName+'\" &lt;'+dataEmail+'&gt;'                
+            
+           
+            //tplFrom = dataEmail;
+            
+            }
+            else{
+                if(Fromdata.group){
+                    //just one address to pharse: length is undefined
+                    if(typeof(Fromdata.group.length) == 'undefined'){
+                        if(Fromdata.group["@name"]){
+                            var dataName = Fromdata.group["@name"];
+                        }
+                        else
+                            var dataName = null;
+                    
+                        if(Fromdata.group["@localPart"]){
+                            var dataEmail = Fromdata.group["@localPart"] + '@' + Fromdata.group["@domain"];
+                        }
+                        else
+                            var dataEmail = null;
+                    
+                        if(dataName == 'null')
+                            tplFrom = dataEmail;
+                        else
+                            tplFrom = '\"'+dataName+'\" &lt;'+dataEmail+'&gt;'    
+                        
+                    }
+                    //address list to pharse, but to header(folder list messages action), only first metters
+                    else{
+                        var dataName = Fromdata.group[0]["@name"];
+                        var dataEmail = Fromdata.group[0]["@localPart"] + '@' + Fromdata.group[0]["@domain"];
+                        
+                        if(dataName == 'null')
+                            tplFrom = dataEmail;
+                        else
+                            tplFrom = '\"'+dataName+'\" &lt;'+dataEmail+'&gt;'    
+                    }
+                }   
+                //Data adrress from mailbox is empty, null, or canot be correctly returned by service invocation (will return 'unknow mailbox' string)
+                else {
+                    tplFrom = 'N;';
+                    return('');
+                }       
+            }
+        }
+        else{
+            tplFrom = 'N;';
+            return('')
+        }
+        return('s:8:"reply_to";s:' + tplFrom.length + ':"' + tplFrom + '";');
+}
+
+MAPattern.prototype.toExpressoSearchFrom = function(data){
+    if((typeof(data) != 'undefined') && (data.length > 0)){
+
+        if((typeof(data) != 'string') || (data.indexOf("{") == -1)){
+            var objMsg = expresso_mail_archive.getMessageServiceObject(data);
+            var attData = objMsg.getFrom();
+            var Fromdata = attData ? eval("(" + attData + ")") : null;
+            if (Fromdata == null)
+                return('N;');
+        }
+        else{
+            var Fromdata = data ?  eval("(" + data + ")") : null;
+            if (Fromdata == null)
+                return('N;');            
+        }       
+        
+        //var Fromdata = eval("(" + data + ")");
+        if(Fromdata.mailbox){
+            //just one address to pharse: length is undefined
+            if(typeof(Fromdata.mailbox.length) == 'undefined'){
+                var objfrom = Fromdata.mailbox;
+            }
+            else{
+                var objfrom = Fromdata.mailbox[0];
+            }
+            
+            if(objfrom["@name"] != 'null')
+                var tplSearchFrom = (objfrom["@name"]);
+            else{                
+                if(objfrom["@localPart"] != 'null')
+                   var dataEmailPart = (objfrom["@localPart"]);
+                else 
+                   var dataEmailpart = "";
+                
+                if(objfrom["@domain"] != 'null')
+                    var dataEmailDomain = (objfrom["@domain"]);
+                else
+                    var dataEmailDomain = "";
+                
+                if(dataEmailDomain != "")
+                    var tplSearchFrom =  dataEmailPart + '@' + dataEmailDomain;
+                else
+                    var tplSearchFrom =  dataEmailPart;
+            }
+        }
+        else{
+            if(Fromdata.group){
+                //just one address to pharse: length is undefined
+                if(typeof(Fromdata.group.length) == 'undefined'){
+                    if(Fromdata.group["@name"]){
+                        var tplSearchFrom = Fromdata.group["@name"];
+                    }
+                    else{
+                    
+                        if(Fromdata.group["@localPart"]){
+                            var tplSearchFrom = Fromdata.group["@localPart"] + '@' + Fromdata.group["@domain"];
+                        }
+                        else
+                            var tplSearchFrom = null;
+                    }
+                    
+                }
+                //address list to pharse, but to header(folder list messages action), only first metters
+                else{
+                    var dataName = Fromdata.group[0]["@name"];
+                    var dataEmail = Fromdata.group[0]["@localPart"] + '@' + Fromdata.group[0]["@domain"];
+                    if(dataName == 'null')
+                        var tplSearchFrom = dataEmail;
+                    else
+                        var tplSearchFrom = dataName;
+                }
+            
+        }
+    }
+    }
+    else{
+        var tplSearchFrom = 'N;';
+    }
+    //window.alert('from search = ' + tplSearchFrom);
+    return(tplSearchFrom);
+}
+
+
+MAPattern.prototype.toExpressoSubject = function(data){
+    if((typeof(data) != 'undefined') && (data.length > 0)){
+        var tplSbj = 's:'+data.length+':"'+data+'";'
+    }
+    //Subject is empty, null, or canot be correctly returned by service invocation (will return 'Message without subject' string)
+    else {
+        tplSbj = 's:25:"[Message without subject]";';
+    }
+    return(tplSbj);
+}
+
+MAPattern.prototype.toExpressoPreview = function(data){
+    //var objMsg = expresso_mail_archive.getMessageServiceObject(data);
+    var prwData = data;
+    
+    
+    if(prwData){
+        if((typeof(prwData) != 'undefined') && (prwData.length > 0)){
+            var tplSbj = 's:'+prwData.length+':"'+prwData+'";'
+        }
+        else {
+            tplSbj = 's:1:" ";';
+        }
+    }
+    else
+        tplSbj = 's:1:" ";';
+    return(tplSbj);
+}
+
+MAPattern.prototype.toExpressoAttachmentsHeader = function(data){
+    if((typeof(data) != 'undefined') && (data.length > 2)){
+        var Attdata = eval("(" + data + ")");
+        if(typeof(Attdata.attachment) != 'undefined'){                    
+            var tplAttatch = 'a:2:{'
++               's:5:"names";';
+            //More than 1 attachment - because length will be 'undefined' if just one exists
+            if(Attdata.attachment.length > 0){
+                var strnamesatt = "";
+                for(var x=0; x<Attdata.attachment.length; x++){
+                  var attId = Attdata.attachment[x]["@id"];
+                  var attName = Attdata.attachment[x]["@name"];
+                  var attSize = Attdata.attachment[x]["@size"];
+                  var attMediaType = Attdata.attachment[x]["@mediaType"];
+                  var attSubType = Attdata.attachment[x]["@subType"];
+                  var attEncoding = Attdata.attachment[x]["@encoding"];
+                  
+                  strnamesatt += attName + ', ';
+                }
+                strnamesatt = strnamesatt.substr(0, strnamesatt.length-2);
+                var intnumberatt = Attdata.attachment.length;
+            }
+            //Just one attachment
+            else{
+                var attId = Attdata.attachment["@id"];
+                var attName = Attdata.attachment["@name"];
+                var attSize = Attdata.attachment["@size"];
+                var attMediaType = Attdata.attachment["@mediaType"];
+                var attSubType = Attdata.attachment["@subType"];
+                var attEncoding = Attdata.attachment["@encoding"];
+                strnamesatt = attName;
+                var intnumberatt = 1;
+            }
+            
+            tplAttatch += 's:'+strnamesatt.length+':"'+strnamesatt+'";'
++               's:18:"number_attachments";i:' +intnumberatt+';'
++           '}';
+        }
+        else {
+            tplAttatch = 'a:2:{s:5:"names";b:0;s:18:"number_attachments";i:0;}';    
+        }
+    }
+    //No attatch data
+    else {
+        tplAttatch = 'a:2:{s:5:"names";b:0;s:18:"number_attachments";i:0;}';
+    }
+    return(tplAttatch);
+}
+
+MAPattern.prototype.toExpressoDate = function(data){
+    var ndate = new Date(data);
+    var odate = zeroFill(ndate.getDate()) + '/' + zeroFill(ndate.getMonth()+1) + '/' + zeroFill(ndate.getFullYear() + ' ' + zeroFill(ndate.getHours()) + ':' + zeroFill(ndate.getMinutes()) + ':' + zeroFill(ndate.getSeconds()));
+    return(odate);
+}
+
+MAPattern.prototype.toExpressoFlags = function(data){
+    if((data.length > 0) && (typeof(data) != 'undefined')){
+        var Tagdata = eval("(" + data + ")");
+        if(typeof(Tagdata.tag) != 'undefined'){ 
+        //More than 1 attachment: length will be 'undefined' if just one exists
+        if(Tagdata.tag.length >= 0){
+            var strnamestag = "";
+            for(var x=0; x<Tagdata.tag.length; x++){
+                var tagvalue = Tagdata.tag[x]["@value"];
+                if(tagvalue.toLowerCase() == 'recent')
+                    strnamestag += 's:6:"Recent";s:1:"N";';
+                if(tagvalue.toLowerCase() == 'unseen')
+                    strnamestag += 's:6:"Unseen";s:1:"U";';
+                if(tagvalue.toLowerCase() == 'seen')
+                    strnamestag += 's:6:"Unseen";s:1:" ";';                
+                if(tagvalue.toLowerCase() == 'deleted')
+                    strnamestag += 's:7:"Deleted";s:1:"D";';
+                if(tagvalue.toLowerCase() == 'answered')
+                    strnamestag += 's:8:"Answered";s:1:"A";';
+                if(tagvalue.toLowerCase() == 'unanswered')
+                    strnamestag += 's:8:"Answered";s:1:" ";';                
+                if(tagvalue.toLowerCase() == 'forwarded')
+                    strnamestag += 's:9:"Forwarded";s:1:"F";';
+                if(tagvalue.toLowerCase() == 'draft')
+                    strnamestag += 's:5:"Draft";s:1:"X";';
+                if(tagvalue.toLowerCase() == 'importance_high')
+                    strnamestag += 's:10:"Importance";s:4:"High";';
+                if(tagvalue.toLowerCase() == 'flagged')
+                    strnamestag += 's:7:"Flagged";s:1:"F";';
+                if(tagvalue.toLowerCase() == 'unflagged')
+                    strnamestag += 's:7:"Flagged";b:0;';                
+            } 
+            var tplTags = strnamestag; 
+          }
+          
+          else{
+            var strnamestag = "";
+            var tagvalue = Tagdata.tag["@value"];
+                if(tagvalue.toLowerCase() == 'recent')
+                    strnamestag += 's:6:"Recent";s:1:"N";';
+                if(tagvalue.toLowerCase() == 'unseen')
+                    strnamestag += 's:6:"Unseen";s:1:"U";';
+                if(tagvalue.toLowerCase() == 'seen')
+                    strnamestag += 's:6:"Unseen";s:1:" ";';                
+                if(tagvalue.toLowerCase() == 'deleted')
+                    strnamestag += 's:7:"Deleted";s:1:"D";';
+                if(tagvalue.toLowerCase() == 'answered')
+                    strnamestag += 's:8:"Answered";s:1:"A";';
+                if(tagvalue.toLowerCase() == 'unanswered')
+                    strnamestag += 's:8:"Answered";s:1:" ";';                
+                if(tagvalue.toLowerCase() == 'forwarded')
+                    strnamestag += 's:9:"Forwarded";s:1:"F";';
+                if(tagvalue.toLowerCase() == 'draft')
+                    strnamestag += 's:5:"Draft";s:1:"X";';
+                if(tagvalue.toLowerCase() == 'importance_high')
+                    strnamestag += 's:10:"Importance";s:4:"High";';
+                if(tagvalue.toLowerCase() == 'flagged')
+                    strnamestag += 's:7:"Flagged";s:1:"F";';
+                if(tagvalue.toLowerCase() == 'unflagged')
+                    strnamestag += 's:7:"Flagged";b:0;';   
+            var tplTags = strnamestag;
+          }
+      }
+      //Something is wrong with tags: return defaults is no one tag
+      else{
+        tplTags = 's:6:"Recent";s:1:" ";s:6:"Unseen";s:1:" ";s:7:"Deleted";s:1:" ";s:8:"Answered";s:1:" ";s:9:"Forwarded";s:1:" ";s:5:"Draft";s:1:" ";s:10:"Importance";s:6:"Normal";s:7:"Flagged";b:0;';
+      }
+      return(tplTags);
+    }
+}
+
+MAPattern.prototype.toExpressoSearchFlags = function(data){
+    if((data.length > 0) && (typeof(data) != 'undefined')){
+        var Tagdata = eval("(" + data + ")");
+        if(typeof(Tagdata.tag) != 'undefined'){ 
+        //More than 1 attachment: length will be 'undefined' if just one exists
+        var tflagged = false;
+        if(Tagdata.tag.length >= 0){
+            var strnamestag = '';
+            for(var x=0; x<Tagdata.tag.length; x++){
+                var tagvalue = Tagdata.tag[x]["@value"];
+                if(tagvalue.toLowerCase() == 'recent')
+                    strnamestag += 'N';
+                if(tagvalue.toLowerCase() == 'unseen')
+                    strnamestag += 'U';
+                if(tagvalue.toLowerCase() == 'draft')
+                    strnamestag += 'X';
+                if(tagvalue.toLowerCase() == 'flagged')
+                    tflagged = true;
+                if((tagvalue.toLowerCase() == 'importance_high') && tflagged)
+                        strnamestag += 'F';
+            } 
+            var tplTags = strnamestag; 
+          }
+          
+          else{
+            var strnamestag = "";
+            var tflagged = false;
+            var tagvalue = Tagdata.tag["@value"];
+                if(tagvalue.toLowerCase() == 'recent')
+                    strnamestag += 'N';
+                if(tagvalue.toLowerCase() == 'unseen')
+                    strnamestag += 'U';
+                if(tagvalue.toLowerCase() == 'draft')
+                    strnamestag += 'X';
+                /*if(tagvalue.toLowerCase() == 'importance_high')
+                    strnamestag += 'F';
+                if(tagvalue.toLowerCase().indexOf('flagged')!= -1)
+                    strnamestag += 'F';*/
+                if(tagvalue.toLowerCase() == 'flagged')
+                    tflagged = true;
+                if((tagvalue.toLowerCase() == 'importance_high') && tflagged)
+                        strnamestag += 'F';
+            var tplTags = strnamestag;
+          }
+          var tplSearchTags = 's:4:"flag";s:' + tplTags.length + ':"' + tplTags + '";'
+      }
+      //Something is wrong with tags: return defaults is no one tag
+      else{
+        var tplSearchTags = 's:4:"flag";s:1:" ";';
+      }
+      //window.alert('tags to search data\n' + tplSearchTags);
+      return(tplSearchTags);
+    }
+}
+
+MAPattern.prototype.toExpressoHeader = function(data){   
+    var tplHeader = 'a:40:{'
++           's:11:"ContentType";'
++           's:' + data.getContentType().length + ':"' + data.getContentType() + '";'
++           expresso_mail_archive.pattern.toExpressoFlags(data.getTags())
++           's:10:"msg_number";'
++           's:'+data.getId().length+':"'+data.getId()+'";'
++           's:5:"udate";'
++           'i:' + parseInt(data.getDate()/1000) + ';'
++           's:9:"timestamp";'
++           'i:' + parseInt(data.getDate()/1000) + ';'
++           's:4:"from";'
++           expresso_mail_archive.pattern.toExpressoAddress(data.getFrom())
+//+           's:6:"sender":' xpresso_mail_archive.pattern.toExpressoSender(expresso_mail_archive.currentmessage)
++           's:2:"to";'
++           expresso_mail_archive.pattern.toExpressoAddress(data.getTo())
++           expresso_mail_archive.pattern.toExpressoAddress2(data.getTo())
++           's:2:"cc";'
++           expresso_mail_archive.pattern.toExpressoCc(data.getCc())
++           's:3:"bcc";'
++           expresso_mail_archive.pattern.toExpressoCc(data.getBcc())
++           's:7:"subject";'
++           expresso_mail_archive.pattern.toExpressoSubject(data.getSubject())
++           's:4:"Size";'
++           'i:'+data.getSize()+';'
++           's:10:"msg_sample";' + expresso_mail_archive.pattern.toExpressoPreview(data.getPreview())
++           's:10:"attachment";'
++           expresso_mail_archive.pattern.toExpressoAttachmentsHeader(data.getAttachments())
++           '}';
+    return(tplHeader);
+}
+
+MAPattern.prototype.toExpressoSearchHeader = function(data){   
+    //var accid = new String(account_id);
+    var accid = new String(data.getId());
+    //var fdata = data.getFolderId();
+    var fdata = data.getFolderPath();
+    var fname = fdata;
+       
+    var tplHeader = 'a:16:{'
++           's:11:"ContentType";'
++           's:' + data.getContentType().length + ':"' + data.getContentType() + '";'
++           expresso_mail_archive.pattern.toExpressoSearchFlags(data.getTags())
++           's:10:"msg_number";'
++           's:'+data.getId().length+':"'+data.getId()+'";'
++           's:5:"udate";'
++           'i:' + parseInt(data.getDate()/1000) + ';'
++           's:9:"timestamp";'
++           'i:' + parseInt(data.getDate()/1000) + ';'
++           's:4:"from";'
++           's:' + expresso_mail_archive.pattern.toExpressoSearchFrom(data.getFrom()).length + ':"' + expresso_mail_archive.pattern.toExpressoSearchFrom(data.getFrom()) + '";'
+//+           's:6:"sender":' expresso_mail_archive.pattern.toExpressoSender(expresso_mail_archive.currentmessage)
++           's:2:"to";'
++           expresso_mail_archive.pattern.toExpressoAddress(data.getTo())
++           expresso_mail_archive.pattern.toExpressoAddress2(data.getTo())
++           's:2:"cc";'
++           expresso_mail_archive.pattern.toExpressoCc(data.getCc())
++           's:3:"bcc";'
++           expresso_mail_archive.pattern.toExpressoCc(data.getBcc())
++           's:7:"subject";'
++           expresso_mail_archive.pattern.toExpressoSubject(data.getSubject())
++           's:4:"size";'
++           'i:'+data.getSize()+';'
++           's:3:"uid";'
++           's:'+ accid.length + ':"' + accid + '";'
++           's:7:"boxname";'
++           's:'+(fname.length + 6)+':"local_' + fname + '";'
++           's:10:"msg_sample";' + expresso_mail_archive.pattern.toExpressoPreview(data.getPreview())
++           's:10:"attachment";'
++           expresso_mail_archive.pattern.toExpressoAttachmentsHeader(data.getAttachments())
++           '}';
+
+    //window.alert('return from TplSearchHeader:\n' + tplHeader);
+    
+    return(tplHeader);
+}
+
+/*
+MAPattern.prototype.toExpressoBody = function(mheader){
+    var tplBody = 'a:33:{'
++                   's:4:"body";N;'
++                   's:11:"attachments";N;'
++                   's:6:"thumbs";N;'
++                   's:9:"signature";N;'
++                   's:10:"Importance";s:6:"Normal";'
++                   's:6:"Recent";s:1:" ";'
++                   's:6:"Unseen";s:1:"N";'
++                   's:7:"Deleted";s:1:" ";'
++                   's:7:"Flagged";b:0;'
++                   's:8:"Answered";s:1:" ";'
++                   's:5:"Draft";s:1:" ";'
++                   's:10:"msg_number";s:4:"2241";'
++                   's:10:"msg_folder";s:5:"INBOX";'
++                   's:5:"udate";s:5:"10:01";'
++                   's:7:"msg_day";s:10:"10/05/2011";'
++                   's:8:"msg_hour";s:5:"10:02";'
++                   's:8:"fulldate";s:36:"10/05/2011 10:01 (05:35 horas atras)";'
++                   's:9:"smalldate";s:5:"10:04";'
++                   's:4:"from";N;'
++                   's:6:"sender";a:3:{'
++                       's:4:"name";N;'
++                       's:5:"email";s:46:"listaregional-pae-bounces@grupos.serpro.gov.br";'
++                       's:4:"full";s:46:"listaregional-pae-bounces@grupos.serpro.gov.br";'
++                   '}'
++                   's:10:"toaddress2";s:32:"comunicacao.social@serpro.gov.br";'
++                   's:2:"cc";N;'
++                   's:3:"bcc";N;'
++                   's:8:"reply_to";N;'
++                   's:7:"subject";N;'
++                   's:4:"Size";s:4:"1234";'
++                   's:15:"reply_toaddress";s:45:"com.social <comunicacao.social@serpro.gov.br>";'
++                   's:9:"timestamp";i:1305032476;'
++                   's:5:"login";i:944889240;'
++                   's:6:"header";a:16:{'
++                      's:11:"ContentType";s:6:"normal";'
++                      's:10:"Importance";s:6:"Normal";'
++                      's:6:"Recent";s:1:" ";'
++                      's:6:"Unseen";s:1:"N";'
++                      's:8:"Answered";s:1:" ";'
++                      's:5:"Draft";s:1:" ";'
++                      's:7:"Deleted";s:1:" ";'
++                      's:7:"Flagged";b:0;'
++                      's:10:"msg_number";s:4:"2251";'
++                      's:5:"udate";s:10:"10/05/2011";'
++                      's:11:"offsetToGMT";i:-10800;'
++                      's:8:"aux_date";N;'
++                      's:4:"from";a:2:{'
++                         's:4:"name";s:10:"com.social";'
++                         's:5:"email";s:32:"comunicacao.social@serpro.gov.br";'
++                      '}'
++                      's:2:"to";a:2:{'
++                         's:4:"name";s:32:"comunicacao.social@serpro.gov.br";'
++                         's:5:"email";s:32:"comunicacao.social@serpro.gov.br";'
++                      '}'
++                      's:7:"subject";s:28:"Primeira leitura - 10/5/2011";'
++                      's:4:"Size";N;'
++                      's:10:"attachment";a:2:{'
++                         's:5:"names";b:0;'
++                         's:18:"number_attachments";i:0;'
++                      '}'
++                  '}'
++                  's:12:"array_attach";N;'
++                  's:15:"url_export_file";s:160:"inc/gotodownload.php?idx_file=/var/www/expressov2/expressoMail1_2/inc/../tmpLclAtt/source_38a3e960115351578aa182ae1d6c2b7b.txt&newfilename=fonte_da_mensagem.txt";'
++                  's:2:"to";N;'
++              '}';
+    return(tplBody);
+}
+*/
+
+MAPattern.prototype.toExpressoMailDataHeader = function(msgid){
+    var tplHMail = "";
+    var tmpHead = expresso_mail_archive.getMessageHeaders(msgid);
+    return tplHMail;    
+}
+
+MAPattern.prototype.toExpressoMailData = function(msg){
+    var tplBMail = "";
+    
+    return(tplBMail);
+}
+
+MAPattern.prototype.toExpressoMailAttachment = function(att){    
+    var objMsg = expresso_mail_archive.getMessageServiceObject(att);
+    var attData = objMsg.getAttachments();
+    var objAtt =  eval("(" + attData + ")");
+    var srlData = "";
+
+    //There are attachments
+    if(typeof(objAtt.attachment) != 'undefined'){
+        if(typeof(objAtt.attachment.length) != 'undefined'){
+            srlData = 's:11:"attachments";a:' + objAtt.attachment.length + ':{';
+            for(var m=0; m<objAtt.attachment.length; m++){
+                srlData += 's:1:"' + m + '";'
+                         + 'a:4:{'
+                         + 's:3:"pid";s:' + objAtt.attachment[m]["@id"].length + ':"' + objAtt.attachment[m]["@id"] + '";'
+                         + 's:4:"name";s:' + objAtt.attachment[m]["@name"].length + ':"' + objAtt.attachment[m]["@name"] + '";'
+                         + 's:8:"encoding";s:' + objAtt.attachment[m]["@encoding"].length + ':"' + objAtt.attachment[m]["@encoding"] + '";'
+                         + 's:5:"fsize";i:' + objAtt.attachment[m]["@size"] + ';'
+                         + '}';
+            }
+        }
+        //just one att
+        else{
+            srlData = 's:11:"attachments";a:1:{';
+            srlData += 's:1:"0";'
+                     + 'a:4:{'
+                     + 's:3:"pid";s:' + objAtt.attachment["@id"].length + ':"' + objAtt.attachment["@id"] + '";'
+                     + 's:4:"name";s:' + objAtt.attachment["@name"].length + ':"' + objAtt.attachment["@name"] + '";'
+                     + 's:8:"encoding";s:' + objAtt.attachment["@encoding"].length + ':"' + objAtt.attachment["@encoding"] + '";'
+                     + 's:5:"fsize";i:' + objAtt.attachment["@size"] + ';'
+                     + '}';
+        }
+        srlData += '}';            
+    }    
+    //No attachments data
+    else{
+        srlData = 's:11:"attachments";N;';
+    }
+    return(srlData);
+}
+
+MAPattern.prototype.toExpressoMailThumbs = function(thb){
+    var objMsg = expresso_mail_archive.getMessageServiceObject(thb);
+    var attData = objMsg.getAttachments();
+    var objAtt =  eval("(" + attData + ")");
+    var srlData = "";
+    var arrThumbs = new Array();
+    if(typeof(objAtt.attachment) != 'undefined'){       
+        //more than 1 att
+        if(typeof(objAtt.attachment.length) != 'undefined'){
+            for(var m=0; m<objAtt.attachment.length; m++){
+                //Only images has thums
+                if(objAtt.attachment[m]["@mediaType"].toLowerCase() == 'image')
+                    arrThumbs.push(objAtt.attachment[m]);
+            }
+        }
+        //just one att data
+        else{
+            if(objAtt.attachment["@mediaType"].toLowerCase() == 'image')
+                arrThumbs.push(objAtt.attachment);
+        }
+        //There are thumbs
+        if(arrThumbs.length > 0){
+            srlData = 's:6:"thumbs";a:'+arrThumbs.length+':{'
+            for(var n=0; n<arrThumbs.length; n++){
+                var thumblink = '<a onMouseDown=\'save_image(event,this,"image/'+arrThumbs[n]["@subType"]+'")\' href=\'#'+mail_archive_protocol+'://'+mail_archive_host+':'+mail_archive_port+'/temp/'+arrThumbs[n]["@id"]+'/'+arrThumbs[n]["@name"]+'\' onClick="window.open(\''+mail_archive_protocol+'://'+mail_archive_host+':'+mail_archive_port+'/temp/'+arrThumbs[n]["@id"]+'/' + arrThumbs[n]["@name"] + '\',\'mywindow\',\'width=700,height=600,scrollbars=yes\');"><IMG id=\''+arrThumbs[n]["@id"]+'\' style=\'border:2px solid #fde7bc;padding:5px\' title=\'Clique na imagem para Ampliar.\' src="'+mail_archive_protocol+'://'+mail_archive_host+':'+mail_archive_port+'/temp/'+arrThumbs[n]["@id"]+'/thumb/120/' + arrThumbs[n]["@name"] +'"></a>';
+                srlData += 's:1:"'+n+'";s:'+thumblink.length+':"'+thumblink+'";'
+            }
+            srlData += '}';    
+        }
+        //No thumbs
+        else
+            srlData = 's:6:"thumbs";N;';        
+    }   
+    //Something is wrong with attachments thumb behavior: return no thumbs
+    else{
+        srlData = 's:6:"thumbs";N;';
+    }
+    return(srlData);
+}
+
+MAPattern.prototype.toExpressoMailSignature = function(sgn){
+    return('s:9:"signature";N;');
+}
+
+MAPattern.prototype.toExpressoMailBaseHeaders = function(hdr){
+    var defMailHeaders = {'recent':' ','unseen': ' ','deleted': ' ','answered': ' ','draft': ' ','flagged': ' '};
+    var objMsg = expresso_mail_archive.getMessageServiceObject(hdr);
+    var tagData = objMsg.getTags();
+    var objTag = eval('(' + tagData + ')');
+    var tplHMail = "";
+    
+    if(objTag.tag){
+    //More than 1 attachment - because length will be 'undefined' if just one exists
+    if(objTag.tag.length >= 0){
+
+        //flaggs the tags
+        for(var k=0; k<objTag.tag.length; k++){
+            for(var j in defMailHeaders){
+                var tagvalue = objTag.tag[k]["@value"].toLowerCase();
+                if((tagvalue == j) && (defMailHeaders[j] != true))
+                    defMailHeaders[j] = true;
+                else
+                    defMailHeaders[j] = false;
+            }
+        }
+        
+        //serialize all needed headers       
+        if(defMailHeaders["recent"] == true)
+            tplHMail += 's:6:"Recent";s:1:"N";';
+        else
+            tplHMail += 's:6:"Recent";s:1:" ";';
+        if(defMailHeaders["unseen"] == true)
+            tplHMail += 's:6:"Unseen";s:1:"U";';
+        else
+            tplHMail += 's:6:"Unseen";s:1:" ";';
+        if(defMailHeaders["deleted"] == true)
+            tplHMail += 's:7:"Deleted";s:1:"D";';
+        else
+            tplHMail += 's:7:"Deleted";s:1:" ";';
+        if(defMailHeaders["answered"] == true)
+            tplHMail += 's:8:"Answered";s:1:"A";';
+        else
+            tplHMail += 's:8:"Answered";s:1:" ";';
+        if(defMailHeaders["draft"] == true)
+            tplHMail += 's:5:"Draft";s:1:"X";';
+        else
+            tplHMail += 's:5:"Draft";s:1:" ";';        
+        if(defMailHeaders["flagged"] == true)
+            tplHMail += 's:7:"Flagged";s:1:"F";';
+        else
+            tplHMail += 's:7:"Flagged";s:1:" ";';                      
+    }
+    }
+    
+    //No header to tag
+    else{
+        tplHMail += 's:6:"Recent";s:1:" ";';
+        tplHMail += 's:6:"Unseen";s:1:" ";';
+        tplHMail += 's:7:"Deleted";s:1:" ";';
+        tplHMail += 's:8:"Answered";s:1:" ";';
+        tplHMail += 's:5:"Draft";s:1:" ";';        
+        tplHMail += 's:7:"Flagged";s:1:" ";';              
+    }
+    return tplHMail;        
+}
+
+MAPattern.prototype.toExpressoMailArrayAttach = function(att){
+    var objMsg = expresso_mail_archive.getMessageServiceObject(att);
+    var attData = objMsg.getAttachments();
+    var objAtt =  eval("(" + attData + ")");
+    var srlData = "";
+
+    //There are attacments, map all them
+    if(typeof(objAtt.attachment) != 'undefined'){
+        srlData = 's:12:"array_attach";a:' + objAtt.attachment.length + ':{';
+        for(var m=0; m<objAtt.attachment.length; m++){
+            var urllink = mail_archive_protocol+'://'+mail_archive_host+':'+mail_archive_port+'/temp/download/'+objAtt.attachment[m]["@id"]+'/'+objAtt.attachment[m]["@name"];
+            srlData += 's:1:"' + m + '";'
+                     + 'a:3:{'
+                     + 's:4:"name";s:' + objAtt.attachment[m]["@name"].length + ':"' + objAtt.attachment[m]["@name"] + '";'
+                     + 's:3:"url";s:' + urllink.length + ':"' + urllink + '";'
+                     + 's:3:"pid";s:' + objAtt.attachment[m]["@id"].length + ':"' + objAtt.attachment[m]["@id"] + '";'
+                     + '}';
+        }
+        srlData += '}';
+    }    
+    //No one attachment
+    else{
+        srlData = 's:12:"array_attach";N;';
+    }
+    return(srlData);
+}
+
+MAPattern.prototype.toExpressoMailURLExportFile = function(path, file){
+    var srlData = 's:15:"url_export_file";';
+    var urllink = mail_archive_protocol+'://'+mail_archive_host+':'+mail_archive_port+'/mail/'+path+'/'+file;
+    srlData += 's:' + urllink.length + ':"' + urllink + '";'
+    return(srlData);
+}
+
+MAPattern.prototype.toExpressoMail = function(mheader, mbody){
+    var tplMessage = null;
+    var tplMessageData = null;
+    var tplMessageHeaderData = null;  
+    
+    //Decodes message headers first
+    var hdata = mheader;
+    var h_date = expresso_mail_archive.pattern.toExpressoDate(mheader["udate"]*1000);
+           
+    //Init message template
+    tplMessage = 'a:49{s:4:"body";N;'
++   expresso_mail_archive.pattern.toExpressoMailAttachment(expresso_mail_archive.currentmessage)
++   expresso_mail_archive.pattern.toExpressoMailThumbs(expresso_mail_archive.currentmessage)    
++   expresso_mail_archive.pattern.toExpressoMailSignature(expresso_mail_archive.currentmessage)
++   expresso_mail_archive.pattern.toExpressoMailBaseHeaders(expresso_mail_archive.currentmessage)
++   's:5:"udate";s:8:"' + h_date.split(" ")[1] +'";' //hours
++   's:7:"msg_day";s:10:"'+ h_date.split(" ")[0] +'";' //date
++   's:8:"msg_hour";s:8:"' + h_date.split(" ")[1] +'";' //hours
++   's:8:"fulldate";s:19:"' + h_date +'";' //full date + hours
++   's:9:"smalldate";s:8:"' + h_date.split(" ")[1] +'";' //hours
++   's:10:"msg_number";s:'+expresso_mail_archive.currentmessage.length+':"'+expresso_mail_archive.currentmessage+'";'
++   's:10:"msg_folder";s:'+(expresso_mail_archive.currentfolder.length+6)+':"local_'+expresso_mail_archive.currentfolder+'";'
++   's:4:"from";N;'
++    expresso_mail_archive.pattern.toExpressoSender(expresso_mail_archive.currentmessage)
++    expresso_mail_archive.pattern.toExpressoReplyTo(expresso_mail_archive.currentmessage)
++   's:10:"msg_sample";' + expresso_mail_archive.pattern.toExpressoPreview(expresso_mail_archive.currentmessage)
++    expresso_mail_archive.pattern.toExpressoAddress2(expresso_mail_archive.currentmessage)
++   's:9:"timestamp";i:'+ mheader["udate"]*1000 +';' //getback the lost miliseconds...
++   expresso_mail_archive.pattern.toExpressoDispositionNotificationTo(expresso_mail_archive.currentmessage)
++   's:5:"login";i:' + account_id
++   's:6:"header";' + expresso_mail_archive.pattern.toExpressoHeader(expresso_mail_archive.getMessageServiceObject(expresso_mail_archive.currentmessage)) 
++   expresso_mail_archive.pattern.toExpressoMailArrayAttach(expresso_mail_archive.currentmessage)
++   expresso_mail_archive.pattern.toExpressoMailURLExportFile(expresso_mail_archive.currentfolder, expresso_mail_archive.currentmessage)
++   's:2:"to";N;'
++   '}';
+
+    var strMailMessage = connector.unserialize(tplMessage);
+//    strMessage['from'] = mheader["from"];
+    //strMessage['from'] = expresso_mail_archive.toExpressoBody(mheader, mbody);
+//    strMessage['subject'] = mheader["subject"];
+    strMailMessage['body'] = mbody;
+//    strMessage['to'] = mheader["to"];
+//    strMessage['cc'] = mheader["cc"];
+    strMailMessage['local_message'] = true;
+    strMailMessage['folder'] = 'local_' + expresso_mail_archive.currentfolder;
+    //strMessage['msg_number'] = mheader["msg_number"];
+    //strMailMessage['msg_number'] = mheader["msg_number"];
+    return(strMailMessage);
+}
+
+MAPattern.prototype.toExpressoMessage = function(mheader, mbody){
+    var strMessage = null;
+    var strMessage1 = expresso_mail_archive.pattern.toExpressoBody(mheader);
+    strMessage = connector.unserialize(strMessage1);
+        
+    strMessage['from'] = mheader["from"];
+    //strMessage['from'] = expresso_mail_archive.toExpressoBody(mheader, mbody);
+    strMessage['subject'] = mheader["subject"];
+    strMessage['body'] = mbody;
+    strMessage['to'] = mheader["to"];
+    strMessage['cc'] = mheader["cc"];
+    strMessage['local_message'] = true;
+    strMessage['folder'] = 'local_' + expresso_mail_archive.currentfolder;
+    strMessage['msg_number'] = mheader["msg_number"];
+    return(strMessage);
+
+
+/*
+ *	retorno['from'] = connector.unserialize(rs.field(2));
+	retorno['subject'] = rs.field(3);
+	retorno['body'] = rs.field(4);
+	//Codigo que as imagens embutidas em emails (com multipart/related ou multipart/mixed) sejam corretamente mostradas em emails arquivados. Os links do
+	//tipo "./inc/show_embedded_attach.php?msg_folder=[folder]&msg_num=[msg_num]&msg_part=[part]"
+	//são substituidos pelos links dos anexos capturados pelo gears.
+
+	var thumbs= retorno.thumbs;
+	var anexos= retorno.array_attach;
+	for (i in anexos)
+	{
+	    if(anexos[i]['url'] && anexos[i]['url'].match(/((jpg)|(jpeg)|(png)|(gif)|(bmp))/gi))
+	    {
+		var er_imagens = new RegExp("\\.\\/inc\\/show_embedded_attach.php\\?msg_folder=[\\w/]+\\&msg_num=[0-9]+\\&msg_part="+anexos[i]['pid']);
+		var Result_imagens = er_imagens.exec(retorno['body']);
+		retorno['body'] = retorno['body'].replace(Result_imagens,anexos[i]['url']);
+		if(thumbs && thumbs[i]){
+		    er_imagens = new RegExp("\\.\\/inc\\/show_thumbs.php\\?file_type=image\\/[\\w]+\\&msg_num=[0-9]+\\&msg_folder=[\\w/%]+\\&msg_part="+anexos[i]['pid']);
+		    Result_imagens = er_imagens.exec(thumbs[i]);
+		    thumbs[i] = thumbs[i].replace(Result_imagens,"'"+anexos[i]['url']+"'");
+		    er_imagens = new RegExp("\\.\\/inc\\/show_img.php\\?msg_num=[0-9]+\\&msg_folder=[\\w/%]+\\&msg_part="+anexos[i]['pid']);
+		    Result_imagens = er_imagens.exec(thumbs[i]);
+		    thumbs[i] = thumbs[i].replace(Result_imagens,anexos[i]['url']);
+		    thumbs[i] = thumbs[i].replace(/<IMG/i,'<img width="120"'); 
+		}
+	    }
+	}
+
+	retorno['to'] = connector.unserialize(rs.field(5));
+	retorno['cc'] = connector.unserialize(rs.field(6));
+
+	retorno['local_message'] = true;
+	retorno['msg_folder'] = "local_"+rs.field(7); //Now it's a local folder
+	retorno['msg_number'] = rs.field(0)+plus_id; //the message number is the rowid
+ **/ 
+}
+
+MAPattern.prototype.tagConfig = function(taglist, arcidmsg, op){
+    //window.alert('no maexpressopattern.tagconfig:\n' + print_r(taglist));
+    if(taglist != null){
+        var tagdata = "";
+        //Código comentado para evitar inconsistência de flags quando mensagens passam pela pasta rascunhos
+        //var flag_draft = false;
+        
+        //first message to tag data
+        if(expresso_mail_archive.taglist == ""){
+
+            //Código comentado para evitar inconsistência de flags quando mensagens passam pela pasta rascunhos
+            /*
+            Draft folder, are "draft"
+            if(expresso_mail_archive.folder_destination == 'drafts'){
+                flag_draft = true;
+                tagdata += '<add value="draft"/>';
+                tagdata += '<remove value="answered"/>';
+                tagdata += '<remove value="forwarded"/>';
+                if (typeof(taglist) == 'object'){
+                    for(var x in taglist[0]){
+                        if (x != 'importance'){
+                            if(( x != 'unseen') && ( x != 'answered')){
+                                if((taglist[0][x] != '') && (taglist[0][x] != ' ') && (taglist[0][x] != null) && (x != 'msgid'))
+                                    tagdata += '<remove value="'+x+'"/>';
+                            }
+                            else{
+                                if( x == 'unseen'){
+                                    if (taglist[0][x] == ' ')
+                                        tagdata += '<remove value="seen"/>';
+                                    else
+                                        if((taglist[0][x] != '') && (taglist[0][x] != null))
+                                            tagdata += '<remove value="unseen"/>';                                
+                                }
+                                if( x == 'answered'){
+                                    if (taglist[0][x] == ' ')
+                                        tagdata += '<remove value="unanswered"/>';
+                                    else
+                                        if((taglist[0][x] != '') && (taglist[0][x] != null))
+                                            tagdata += '<remove value="answered"/>';                                                                    
+                                }                              
+                            }
+                        }
+                        else{
+                            if((taglist[0][x] != '') && (taglist[0][x] != ' ')){
+                                switch (taglist[0][x].toLowerCase()){
+                                    case 'high':
+                                        tagdata += '<remove value="importance_high"/>';
+                                        tagdata += '<remove value="flagged"/>';
+                                        break;
+                                    default:
+                                        tagdata += '<remove value="importance_normal"/>';
+                                        tagdata += '<remove value="unflagged"/>';
+                                        break;                                        
+                                }
+                            }
+                        }
+                    }
+                }
+                else{
+                     if(!flag_draft)
+                        tagdata += '<remove value="'+taglist+'"/>';
+                }
+            }
+            else
+               tagdata += '<remove value="draft"/>';
+            */
+
+            //Trash folder, are "deleted""
+            if(expresso_mail_archive.folder_destination == 'trash'){
+                tagdata += '<add value="deleted"/>';
+            }
+            else
+                tagdata += '<remove value="deleted"/>';
+        
+            //Código comentado para evitar inconsistência de flags quando mensagens passam pela pasta rascunhos
+            //if(!flag_draft){
+
+            var action;
+            if (op == 0)
+                action = 'add';
+            else
+                action = 'remove';
+    
+            //object data -used at archieve op
+            if (typeof(taglist) == 'object'){
+                for(var x in taglist[0]){
+                    if (x != 'importance'){
+                        if(( x != 'unseen') && ( x != 'answered')){
+                            if((taglist[0][x] != '') && (taglist[0][x] != ' ') && (taglist[0][x] != null) && (x != 'msgid'))
+                                tagdata += '<'+action+' value="'+x+'"/>';
+                        }
+                        else{
+                            if( x == 'unseen'){
+                                if (taglist[0][x] == ' ')
+                                    tagdata += '<'+action+' value="seen"/>';
+                                else
+                                    if((taglist[0][x] != '') && (taglist[0][x] != null))
+                                        tagdata += '<'+action+' value="unseen"/>';                                
+                            }
+                            if( x == 'answered'){
+                                if (taglist[0][x] == ' ')
+                                    tagdata += '<'+action+' value="unanswered"/>';
+                                else
+                                    if((taglist[0][x] != '') && (taglist[0][x] != null))
+                                        tagdata += '<'+action+' value="answered"/>';                                                                    
+                            }                            
+                        }
+                    }
+                    else{
+                        if((taglist[0][x] != '') && (taglist[0][x] != ' ')){
+                            switch (taglist[0][x].toLowerCase()){
+                                case 'high':
+                                    tagdata += '<'+action+' value="importance_high"/>';
+                                    tagdata += '<'+action+' value="flagged"/>';
+                                    break;
+                                default:
+                                    tagdata += '<'+action+' value="importance_normal"/>';
+                                    tagdata += '<'+action+' value="unflagged"/>';
+                                    break;                                        
+                            }
+                           
+                       }
+                       //if no importance data received, defaults is "Normal"
+                       else{
+                           tagdata += '<add value="importance_normal"/>';
+                           tagdata += '<add value="unflagged"/>';
+                       }
+                    }
+                }
+            }
+            //string data - used to tag a message when reading it (unseen and important, by now)
+            else{
+                if(taglist.indexOf(",") != -1){
+                    var vet_tags = taglist.split(",");
+                    for(var k=0; k<vet_tags.length; k++){
+                        tagdata += '<'+action+' value="'+vet_tags[k]+'"/>';
+                    }
+                }
+                else
+                    tagdata += '<'+action+' value="'+taglist+'"/>';
+            }
+
+            //Código comentado para evitar inconsistência de flags quando mensagens passam pela pasta rascunhos
+            //}
+
+            if(tagdata != ""){    
+                var tobject = '<tag>'
+                +              '<message id="'+arcidmsg+'">'
+                +              tagdata
+                +              '</message>'
+                +             '</tag>';
+                //window.alert('tagdata ret1 = ' + tobject);
+                return(tobject);
+            }
+        }
+        //more messages to add at tag block
+        else{
+            var endpoint = expresso_mail_archive.taglist.lastIndexOf("<");
+           
+            //Código comentado para evitar inconsistência de flags quando mensagens passam pela pasta rascunhos
+            /*
+            Draft folder, are "draft"
+            if(expresso_mail_archive.folder_destination == 'drafts'){
+                flag_draft = true;
+                tagdata += '<add value="draft"/>';
+                if (typeof(taglist) == 'object'){
+                    for(var x in taglist[0]){
+                        if (x != 'importance'){
+                            if(( x != 'unseen') && ( x != 'answered')){
+                                if((taglist[0][x] != '') && (taglist[0][x] != ' ') && (taglist[0][x] != null) && (x != 'msgid'))
+                                    tagdata += '<remove value="'+x+'"/>';
+                            }
+                            else{
+                                if( x == 'unseen'){
+                                    if (taglist[0][x] == ' ')
+                                        tagdata += '<remove value="seen"/>';
+                                    else
+                                        if((taglist[0][x] != '') && (taglist[0][x] != null))
+                                            tagdata += '<remove value="unseen"/>';                                
+                                }
+                                if( x == 'answered'){
+                                    if (taglist[0][x] == ' ')
+                                        tagdata += '<remove value="unanswered"/>';
+                                    else
+                                        if((taglist[0][x] != '') && (taglist[0][x] != null))
+                                            tagdata += '<remove value="answered"/>';                                                                    
+                                }                              
+                            }
+                        }
+                        else{
+                            if((taglist[0][x] != '') && (taglist[0][x] != ' ')){
+                                switch (taglist[0][x].toLowerCase()){
+                                    case 'high':
+                                        tagdata += '<'+action+' value="importance_high"/>';
+                                        tagdata += '<'+action+' value="flagged"/>';
+                                        break;
+                                    default:
+                                        tagdata += '<'+action+' value="importance_normal"/>';
+                                        tagdata += '<'+action+' value="unflagged"/>';
+                                        break;                                        
+                                }
+                               
+                            }
+                           //if no importance data received, defaults is "Normal"
+                           else{
+                               tagdata += '<add value="importance_normal"/>'; 
+                               tagdata += '<add value="unflagged"/>';
+                           }
+                        }
+                    }
+                }
+                else{
+                     if(!flag_draft)
+                        tagdata += '<remove value="'+taglist+'"/>';
+                }
+            }
+            else
+                tagdata += '<remove value="draft"/>';
+            */
+
+            //Trash folder, are "deleted""
+            if(expresso_mail_archive.folder_destination == 'trash'){
+                tagdata += '<add value="deleted"/>';
+            }
+            else
+                tagdata += '<remove value="deleted"/>';
+            
+            //Código comentado para evitar inconsistência de flags quando mensagens passam pela pasta rascunhos
+            //if(!flag_draft){
+
+            var action;
+            if (op == 0)
+                action = 'add';
+            else
+                action = 'remove';
+    
+            //object data -used at archieve op
+            if (typeof(taglist) == 'object'){
+                for(var x in taglist[0]){
+                    if (x != 'importance'){
+                        if(( x != 'unseen') && ( x != 'answered')){
+                            if((taglist[0][x] != '') && (taglist[0][x] != ' ') && (taglist[0][x] != null) && (x != 'msgid'))
+                                tagdata += '<'+action+' value="'+x+'"/>';
+                        }
+
+                        else{
+                            if( x == 'unseen'){
+                                if (taglist[0][x] == ' ')
+                                    tagdata += '<'+action+' value="seen"/>';
+                                else
+                                    if((taglist[0][x] != '') && (taglist[0][x] != null))
+                                        tagdata += '<'+action+' value="unseen"/>';                                
+                            }
+                            if( x == 'answered'){
+                                if (taglist[0][x] == ' ')
+                                    tagdata += '<'+action+' value="unanswered"/>';
+                                else
+                                    if((taglist[0][x] != '') && (taglist[0][x] != null))
+                                        tagdata += '<'+action+' value="answered"/>';                                                                    
+                            }                             
+                        }
+                    }
+                    else{
+                        if((taglist[0][x] != '') && (taglist[0][x] != ' ')){
+                            switch (taglist[0][x].toLowerCase()){
+                                case 'important':
+                                    tagdata += '<'+action+' value="importance_high"/>';
+                                    tagdata += '<'+action+' value="flagged"/>';
+                                    break;
+                                default:
+                                    tagdata += '<'+action+' value="importance_normal"/>';
+                                    tagdata += '<'+action+' value="unflagged"/>';
+                                    break;                                        
+                            }
+                            
+                        }
+                       //if no importance data received, defaults is "Normal"
+                       else{
+                           tagdata += '<add value="importance_normal"/>'; 
+                           tagdata += '<add value="unflagged"/>';
+                       }
+                    }
+                }
+            }
+            //string data - used to tag a message
+            else{
+                if(taglist.indexOf(",") != -1){
+                    var vet_tags = taglist.split(",");
+                    for(var k=0; k<vet_tags.length; k++){
+                        tagdata += '<'+action+' value="'+vet_tags[k]+'"/>';
+                    }
+                }
+                else
+                    tagdata += '<'+action+' value="'+taglist+'"/>';
+            }
+
+            //Código comentado para evitar inconsistência de flags quando mensagens passam pela pasta rascunhos
+            //}
+            
+            if(tagdata != ""){        
+                var tobject = expresso_mail_archive.taglist.substr(0, endpoint)
+                +              '<message id="'+arcidmsg+'">'
+                +              tagdata
+                +              '</message>'
+                +             '</tag>';
+                //window.alert('tagdata ret2 = ' + tobject);
+                return(tobject);
+            }            
+            
+        }
+        return(null);
+    }
+    return(null);
+}
+
+MAPattern.prototype.zipConfig = function(array_messages){
+    var tagdata ="";
+    if(typeof(array_messages) == 'object'){
+        if(!array_messages["format"])
+            var def_format = 'zip';
+        else
+            var def_format = array_messages["format"].toLowerCase();
+        var tobject = '<zip format="' + def_format + '">';
+        //Export from selected messages grid
+        if(array_messages["type"] == 'messages'){
+            for(var k=0; k<array_messages["messages"].length;k++){
+                tobject += '<message id="' + array_messages["messages"][k] + '"/>';
+            }   
+        }
+        //Export from folder management
+        else{
+            var folderid = array_messages["messages"];
+            if (!array_messages["recursive"])
+                var rec = false;
+            else
+                var rec = array_messages["recursive"];
+            tobject += '<folder id="' + array_messages["messages"] + '" recursive="' + rec + '"/>';
+        }
+        tobject += '</zip>';        
+        return(tobject);
+    }
+    return(null);
+}
+
+MAPattern.prototype.download_compressed_attachments = function(msgid,format){
+    var urldownload = mail_archive_protocol+'://'+mail_archive_host+':'+mail_archive_port+'/temp/download/parts_'+msgid+'.'+format;
+    return(urldownload);
+}
+
+MAPattern.prototype.message_source = function(msgid){
+    var urldownload = mail_archive_protocol+'://'+mail_archive_host+':'+mail_archive_port+'/mail/'+folder+'/'+msgid+'.eml';
+    return(urldownload);
+}
+-->
Index: trunk/expressoMail1_2/js/wfolders.js
===================================================================
--- trunk/expressoMail1_2/js/wfolders.js	(revision 6910)
+++ trunk/expressoMail1_2/js/wfolders.js	(revision 7414)
@@ -97,7 +97,9 @@
 		winSaveFile.next().css("background-color", "#E0EEEE");
 			
+		/*Insere a árvore de diretórios*/
 		var foldersTree = jQuery("#foldertree-container-sendFileMessage")
 		.removeClass('empty-container')
-		.html(DataLayer.render(BASE_PATH + 'api/templates/foldertree.ejs', {folders: [cp_tree1, cp_tree2, [] ]}))
+		//Adicionado parametro cp_tree3 para mensagens locais (MailArchiver)
+		.html(DataLayer.render(BASE_PATH + 'api/templates/foldertree.ejs', {folders: [cp_tree1, cp_tree2, cp_tree3 ]}))
 		.find("#foldertree").treeview()
 		.click(function(event)
Index: trunk/expressoMail1_2/js/draw_api.js
===================================================================
--- trunk/expressoMail1_2/js/draw_api.js	(revision 7371)
+++ trunk/expressoMail1_2/js/draw_api.js	(revision 7414)
@@ -108,4 +108,116 @@
 		}
 
+                
+                //MAILARCHIVER-01
+                //Create local folders main structure tree
+                if(preferences.use_local_messages=="1"){
+                    var disabled_local_span = document.getElementById('llocal_disabledtree_folders');
+
+                    //Services are disabled: because Mail Archiver is not running/installed or have just crashed. Link activation is created here
+                    if(!expresso_mail_archive.enabled){
+                        //window.alert('tem o nodo disabled? ' + tree_folders.getNodeById("local_disabled") + '[' + typeof(tree_folders.getNodeById('local_disabled')) + ']');
+                        if(typeof(tree_folders.getNodeById("local_disabled")) == 'undefined'){
+                          var n_LocalDisabled = new dNode({id: "local_disabled", caption: get_lang('Offline'), onClick: "services_retry()", plusSign:false});
+                          tree_folders.add(n_LocalDisabled, 'local_root');
+                        }
+
+                        tree_folders.getNodeById("local_disabled").alter({caption:get_lang('Offline'), onClick: "retry_local_folders()"});
+                        tree_folders.getNodeById("local_disabled")._refresh();
+                        
+                        if((disabled_local_span) && (!document.getElementById('services_retry'))){
+                            disabled_local_span.style.backgroundImage="url(../phpgwapi/templates/"+template+"/images/foldertree_services.png)";
+
+                            var service_retry = document.createElement("SPAN");
+                            service_retry.id = 'services_retry';
+                            service_retry.className = 'clean_trash';
+                            service_retry.style.cursor = 'pointer';
+                            service_retry.onclick = function () {services_retry();};
+                            service_retry.innerHTML = "["+get_lang("Retry")+"]";
+                            service_retry.title="Reconectar ao Mail Archiver";
+                            service_retry.onmouseover = function() {service_retry.style.color="red";};
+                            service_retry.onmouseout= function() {service_retry.style.color="#666666";}; //#114FA4
+                            disabled_local_span.parentNode.appendChild(service_retry);
+                        }
+                        else{
+                            //Creates the tree node and MA console linkage
+                            if((!disabled_local_span) && (!document.getElementById('services_retry'))){
+                                var n_LocalDisabled = new dNode({id: "local_disabled", caption: get_lang('Offline'), onClick: "services_retry()", plusSign:false});
+                                tree_folders.add(n_LocalDisabled, 'local_root');
+                            
+                                var disabled_local_span = document.getElementById('llocal_disabledtree_folders');
+                                disabled_local_span.style.backgroundImage="url(../phpgwapi/templates/"+template+"/images/foldertree_services.png)";
+                                var service_retry = document.createElement("SPAN");
+                                service_retry.id = 'services_retry';
+                                service_retry.className = 'clean_trash';
+                                service_retry.style.cursor = 'pointer';
+                                service_retry.onclick = function () {services_retry();};
+                                service_retry.innerHTML = "["+get_lang("Retry")+"]";
+                                service_retry.title= get_lang("Reconect to MailArchiver services");
+                                service_retry.onmouseover = function() {service_retry.style.color="red";};
+                                service_retry.onmouseout= function() {service_retry.style.color="#666666";}; //#114FA4
+                                disabled_local_span.parentNode.appendChild(service_retry);
+                            
+                                var div_ma_host = document.createElement('div');
+                                div_ma_host.id = 'div_login_ma_host';
+                                div_ma_host.style.position = 'absolute';
+                                div_ma_host.style.padding = '0px';
+                                div_ma_host.style.margin = '0px';
+                                div_ma_host.style.top = '25px';
+                                div_ma_host.style.left = '0px';
+                                div_ma_host.style.width = '145px';
+                                div_ma_host.style.height = '80px';
+                                div_ma_host.style.border = '1px solid #CCCCCC';
+                                div_ma_host.style.backgroundColor = '#F0F0F0';
+                                div_ma_host.style.fontWeight = 'normal';
+                                disabled_local_span.appendChild(div_ma_host);
+                                div_ma_host.innerHTML = '<p><b>'+get_lang('In trouble?')+'</b></p><p>&rarr; ' + get_lang('Try to access') + '<br/><a href="' + mail_archive_protocol + "://" + mail_archive_host + ":" + mail_archive_port + '/admin" target="_blank" title="MailArchiver Admin">'+get_lang('MailArchiver admin console')+'.</p>';                            
+                            }
+                            //Only creates the MA login linkage
+                            else{
+                                var div_ma_host = document.createElement('div');
+                                div_ma_host.id = 'div_login_ma_host';
+                                div_ma_host.style.position = 'absolute';
+                                div_ma_host.style.padding = '0px';
+                                div_ma_host.style.margin = '0px';
+                                div_ma_host.style.top = '25px';
+                                div_ma_host.style.left = '0px';
+                                div_ma_host.style.width = '145px';
+                                div_ma_host.style.height = '80px';
+                                div_ma_host.style.border = '1px solid #CCCCCC';
+                                div_ma_host.style.backgroundColor = '#F0F0F0';
+                                div_ma_host.style.fontWeight = 'normal';
+                                disabled_local_span.appendChild(div_ma_host);
+                                div_ma_host.innerHTML = '<p><b>'+get_lang('In trouble?')+'</b></p><p>&rarr; ' + get_lang('Try to access') + '<br/><a href="' + mail_archive_protocol + "://" + mail_archive_host + ":" + mail_archive_port + '/admin" target="_blank" title="MailArchiver Admin">'+get_lang('MailArchiver admin console')+'.</p>';                                                        
+                            }
+                        }
+                    }
+                    //Services enabled: list folders service must be invoqued
+                    else{
+                        var services_retry_span = document.getElementById('services_retry');
+
+                        if(services_retry_span){
+                            //window.alert('Tem services_retry -> vai remover o disabled_local_span');
+                            var node_disabled_to_remove = document.getElementById('nlocal_disabledtree_folders');
+                            //document.getElementById('chlocal_roottree_folders').removeChild('nlocal_disabledtree_folders');
+                            //services_retry_span.parentNode.removeChild(services_retry_span);
+                            node_disabled_to_remove.parentNode.removeChild(node_disabled_to_remove);
+                        }
+                        //else
+                          //  window.alert('Sem services retry');
+
+                        //tree_folders.getNodeById("local_disabled").alter({caption:get_lang('List_Folders')});
+                                                
+                       //expresso_mail_archive.getFoldersList('FERNANDAO22', "");
+                       var drawinginfo = {treeObject: tree_folders, treeName: 'tree_folders'};
+                       expresso_mail_archive.drawdata = drawinginfo;
+                       //expresso_mail_archive.getFoldersList("");                        
+                        
+                        //tree_folders.getNodeById("local_root")._refresh();
+
+                        if(disabled_local_span)
+                            disabled_local_span.style.backgroundImage="url(../phpgwapi/templates/"+template+"/images/foldertree_folder.png)";                       
+                    }      
+                }
+
 		return;
 	}
@@ -148,5 +260,30 @@
 		}
 
-
+                
+                //MAILARCHIVER-02
+                //Create local folders main structure tree
+                if(preferences.use_local_messages=="1"){   
+                    //Add the local_root node
+                    var root_local = new dNode({id: "local_root", caption: get_lang('local folders'), plusSign: true});
+                    tree_folders.add(root_local, "root");   
+                    
+                    //Services are disabled: because Mail Archiver is not running/installed or have just crashed. Link activation is created here
+                    if(!expresso_mail_archive.enabled){
+                        var n_LocalDisabled = new dNode({id: "local_disabled", caption: get_lang('Offline'), onClick: "services_retry()", plusSign:false});
+                        tree_folders.add(n_LocalDisabled, 'local_root');
+                        
+                    }
+                    
+                    //Services enabled: list folders service must be invoqued
+                    else{
+                        var drawinginfo = {treeObject: tree_folders, treeName: 'tree_folders'};
+                        expresso_mail_archive.drawdata = drawinginfo;
+                        //expresso_mail_archive.getFoldersList("");
+                    }
+                    
+                    //Opens the local folders tree view
+                    //tree_folders.getNodeById("local_root").open();
+                    
+                }
 
 		var handlerChannel = function(data){
@@ -183,49 +320,4 @@
 		 * Pastas locais
 		 */
-		if (preferences.use_local_messages==1 || expresso_offline) {
-			    //verifica se gears esta installado ou o offline
-			if( (!window.google || !google.gears) &&
-			     !expresso_local_messages.installGears() ){
-                                preferences.use_local_messages = 0;
-			}
-			else if( !expresso_local_messages.is_offline_installed() )
-				preferences.use_local_messages = 0;
-			else{
-				if (expresso_offline)
-					tree_folders = new dFTree({
-						name: 'tree_folders'
-					});
-				var root_local = new dNode({
-					id: "local_root",
-					caption: get_lang('local folders')
-				});
-				tree_folders.add(root_local, "root"); //coloca root local
-				var local_folders = expresso_local_messages.list_local_folders();
-				for (var i in local_folders) { //Coloca as pastas locais.
-					var node_root = "local_root";
-					var new_caption = local_folders[i][0];
-					if (local_folders[i][0].indexOf("/") != "-1") {
-						final_pos = local_folders[i][0].lastIndexOf("/");
-						node_root = "local_" + local_folders[i][0].substr(0, final_pos);
-						new_caption = local_folders[i][0].substr(final_pos + 1);
-					}
-					if (local_folders[i][1] > 0)
-						var nodeLocal = new dNode({
-							id: "local_" + local_folders[i][0],
-							caption: lang_folder(new_caption) + '<font style=color:red>&nbsp(</font><span id="local_unseen" style=color:red>' + local_folders[i][1] + '</span><font style=color:red>)</font>',
-							onClick: "change_folder('local_" + local_folders[i][0] + "','" + new_caption + "')",
-							plusSign: local_folders[i][2]
-						});
-					else
-						var nodeLocal = new dNode({
-							id: "local_" + local_folders[i][0],
-							caption: lang_folder(new_caption),
-							onClick: "change_folder('local_" + local_folders[i][0] + "','" + new_caption + "')",
-							plusSign: local_folders[i][2]
-						});
-						tree_folders.add(nodeLocal, node_root);
-					}
-				}
-			}
 
 		/*tree_folders.draw(Element('content_folders'));
@@ -276,4 +368,24 @@
 
 
+                //MAILARCHIVER-04
+                if ((disabled_local_span) && (!expresso_mail_archive.enabled)){
+                    disabled_local_span.style.backgroundImage="url(../phpgwapi/templates/"+template+"/images/foldertree_services.png)";
+                        //div to login at MA Admin console
+                        var div_ma_host = document.createElement('div');
+                        div_ma_host.id = 'div_login_ma_host';
+                        div_ma_host.style.position = 'absolute';
+                        div_ma_host.style.padding = '0px';
+                        div_ma_host.style.margin = '0px';
+                        div_ma_host.style.top = '25px';
+                        div_ma_host.style.width = '145px';
+                        div_ma_host.style.height = '80px';
+                        div_ma_host.style.border = '1px solid #CCCCCC';
+                        div_ma_host.style.backgroundColor = '#F0F0F0';
+                        div_ma_host.style.fontWeight = 'normal';
+                        disabled_local_span.appendChild(div_ma_host);
+                        div_ma_host.innerHTML = '<p><b>'+get_lang('In trouble?')+'</b></p><p>&rarr; ' + get_lang('Try to access') + '<br/><a href="' + mail_archive_protocol + "://" + mail_archive_host + ":" + mail_archive_port + '/admin" target="_blank" title="MailArchiver Admin">'+get_lang('MailArchiver admin console')+'.</p>';
+                }
+
+
 		draw_paging(Element('tot_m').innerHTML);
 		if(document.getElementById(mount_url_folder(["nINBOX",special_folders["Trash"]])+"tree_folders"))
@@ -305,8 +417,24 @@
 			   }
 
-		if(!expresso_offline)
+        //MAILARCHIVER-05
+        if(document.getElementById("nlocal_disabledtree_folders") && (!expresso_mail_archive.enabled) && (!document.getElementById('services_retry')))
+        {
+            var service_retry = document.createElement("SPAN");
+            service_retry.id = 'services_retry';
+            service_retry.className = 'clean_trash';
+            service_retry.style.cursor = 'pointer';
+            service_retry.onclick = function () {services_retry();};
+            service_retry.innerHTML = "["+get_lang("Retry")+"]";
+            service_retry.title="Reconectar ao Mail Archiver";
+            service_retry.onmouseover = function() {service_retry.style.color="red";};
+            service_retry.onmouseout= function() {service_retry.style.color="#666666";}; //#114FA4
+            document.getElementById("nlocal_disabledtree_folders").appendChild(service_retry);
+        }
+
+            //MAILARCHIVER-00
+		//if(!expresso_offline)
 			var display_unseen_in_mailbox = tree_folders.getNodeById( 'root' );
-		else
-			var display_unseen_in_mailbox = tree_folders.getNodeById( 'local_root' );
+		//else
+			//var display_unseen_in_mailbox = tree_folders.getNodeById( 'local_root' );
 		display_unseen_in_mailbox.alter({caption:get_lang("My Folders")});
 		display_unseen_in_mailbox._refresh();
@@ -391,52 +519,62 @@
 
 function draw_tree_local_folders() {
-	/**
-	 * Pastas locais
-	 */
-		if(preferences.use_local_messages==1 || expresso_offline) {
-			var local_folders = expresso_local_messages.list_local_folders();
-			var has_changes = false;
-			for (var i in local_folders) { //Coloca as pastas locais.
-
-				var new_caption = local_folders[i][0];
-				if(local_folders[i][0].indexOf("/")!="-1") {
-					final_pos = local_folders[i][0].lastIndexOf("/");
-					new_caption = local_folders[i][0].substr(final_pos+1);
-				}
-
-				var folder_unseen = Element('dftree_local_'+local_folders[i][0]+'_unseen');
-
-				if ((folder_unseen) && (local_folders[i][1] > 0))
-				{
-					folder_unseen.innerHTML = local_folders[i][1];
-					has_changes = true;
-				}
-				else if (local_folders[i][1] > 0)
-				{
-					tree_folders.getNodeById("local_"+local_folders[i][0]).alter({caption:lang_folder(new_caption) + '<font style=color:red>&nbsp(</font><span id="dftree_local_'+local_folders[i][0]+'_unseen" style=color:red>'+local_folders[i][1]+'</span><font style=color:red>)</font>'});
-					tree_folders.getNodeById("local_"+local_folders[i][0])._refresh();
-					has_changes = true;
-				}
-				else if (local_folders[i][1] <= 0)
-				{
-					tree_folders.getNodeById("local_"+local_folders[i][0]).alter({caption:lang_folder(new_caption)});
-					tree_folders.getNodeById("local_"+local_folders[i][0])._refresh();
-					has_changes = true;
-				}
-
-			if("local_"+local_folders[i][0] == get_current_folder()){
-					var old_new_m = isNaN(parseInt(Element('new_m').innerHTML)) ? parseInt(Element('new_m').firstChild.innerHTML) : parseInt(Element('new_m').innerHTML);
-					if(!isNaN(old_new_m) && old_new_m < local_folders[i][1]){
-						Element('tot_m').innerHTML = parseInt(Element('tot_m').innerHTML) + (parseInt(local_folders[i][1])-old_new_m);
-					}
-					Element('new_m').innerHTML = local_folders[i][1] ? '<font color="RED">'+local_folders[i][1]+'</font>' : 0;
-					draw_paging(Element('tot_m').innerHTML);
-					has_changes = true;
-			}
-		}
-			if(has_changes)
-				tree_folders.getNodeById("local_root").open();
- 	}
-}
+    /**
+     * Pastas locais
+     */
+        //MAILARCHIVER-04
+        if ( preferences.use_local_messages=="1" ) {
+            var local_folders_list = expresso_mail_archive.getFoldersList("");
+        }
+}
+
+// function draw_tree_local_folders() {
+// 	/**
+// 	 * Pastas locais
+// 	 */
+// 		if(preferences.use_local_messages==1 || expresso_offline) {
+// 			var local_folders = expresso_local_messages.list_local_folders();
+// 			var has_changes = false;
+// 			for (var i in local_folders) { //Coloca as pastas locais.
+
+// 				var new_caption = local_folders[i][0];
+// 				if(local_folders[i][0].indexOf("/")!="-1") {
+// 					final_pos = local_folders[i][0].lastIndexOf("/");
+// 					new_caption = local_folders[i][0].substr(final_pos+1);
+// 				}
+
+// 				var folder_unseen = Element('dftree_local_'+local_folders[i][0]+'_unseen');
+
+// 				if ((folder_unseen) && (local_folders[i][1] > 0))
+// 				{
+// 					folder_unseen.innerHTML = local_folders[i][1];
+// 					has_changes = true;
+// 				}
+// 				else if (local_folders[i][1] > 0)
+// 				{
+// 					tree_folders.getNodeById("local_"+local_folders[i][0]).alter({caption:lang_folder(new_caption) + '<font style=color:red>&nbsp(</font><span id="dftree_local_'+local_folders[i][0]+'_unseen" style=color:red>'+local_folders[i][1]+'</span><font style=color:red>)</font>'});
+// 					tree_folders.getNodeById("local_"+local_folders[i][0])._refresh();
+// 					has_changes = true;
+// 				}
+// 				else if (local_folders[i][1] <= 0)
+// 				{
+// 					tree_folders.getNodeById("local_"+local_folders[i][0]).alter({caption:lang_folder(new_caption)});
+// 					tree_folders.getNodeById("local_"+local_folders[i][0])._refresh();
+// 					has_changes = true;
+// 				}
+
+// 			if("local_"+local_folders[i][0] == get_current_folder()){
+// 					var old_new_m = isNaN(parseInt(Element('new_m').innerHTML)) ? parseInt(Element('new_m').firstChild.innerHTML) : parseInt(Element('new_m').innerHTML);
+// 					if(!isNaN(old_new_m) && old_new_m < local_folders[i][1]){
+// 						Element('tot_m').innerHTML = parseInt(Element('tot_m').innerHTML) + (parseInt(local_folders[i][1])-old_new_m);
+// 					}
+// 					Element('new_m').innerHTML = local_folders[i][1] ? '<font color="RED">'+local_folders[i][1]+'</font>' : 0;
+// 					draw_paging(Element('tot_m').innerHTML);
+// 					has_changes = true;
+// 			}
+// 		}
+// 			if(has_changes)
+// 				tree_folders.getNodeById("local_root").open();
+//  	}
+// }
 
 
@@ -539,31 +677,45 @@
 			return true;
 		}
-		$.ajax({			
-			url: "controller.php?" + $.param( {action: "$this.imap_functions.getMessagesIds", 
-				folder: 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);
-				
-				}
-			},
-			beforeSend: function( jqXHR, settings ){
-				connector.showProgressBar();
-			},
-			complete: function( jqXHR, settings ){
-				connector.hideProgressBar();
-			}
-		});
+		//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
+            selectAllFolderMsgs(false);
+            //Método chamado para retornar todos os ids de mensagens por folder
+            expresso_mail_archive.listAllMessagesByFolder(folder.replace("local_messages_",""));
+            populateSelectedMsgs(expresso_mail_archive.allmessagesbyfolder);
+        }
+        else { //se não, processamento normal da pasta
+    		$.ajax({
+    			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[index].msg_number){
+    							_data[data[index].msg_number] = data[index].msg_number;
+    						}
+    					});
+    					populateSelectedMsgs(_data);
+    					_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);
 	}
@@ -1573,5 +1725,5 @@
 	if ( !currentTab )
 		alternate_border(numBox);
-	draw_footer_box(headers_msgs.num_msgs);
+	draw_footer_box(headers_msgs.length);
 	Element('main_table').style.display = '';
 	if(is_ie6)	  // Stupid Fixing on IE6.
@@ -1667,4 +1819,5 @@
 
 		tr_element.msg_sample = "";
+        tr_element.tip = "";
 		//if(headers_msgs.msg_sample && headers_msgs.msg_sample.preview_msg_subject != "")
 		if(headers_msgs.msg_sample && preferences.preview_msg_subject == "1" && headers_msgs.msg_sample.body !== "")
@@ -1674,14 +1827,42 @@
 			else
 				tr_element.msg_sample = html_entities(Base64.decode(headers_msgs.msg_sample.body).substr(0,120) + "..."); //trecho do body que sera exibido com o assunto;
-		}
-
-		tr_element.tip = "";
-		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(preferences.use_local_messages==1 && !expresso_offline) { //MailArchive
+                if(proxy_mensagens.is_local_folder(current_folder)) {
+                    // preferencia da pre-visualizacao
+                    if (cssForResizing) {//Colunas redimensionaveis - nao trunca
+                        tr_element.msg_sample = headers_msgs.msg_sample.body.substr(0,180) + "..."; //trecho do body que sera exibido com o assunto; //blabla
+                    } else {
+                        tr_element.msg_sample = 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 = headers_msgs.msg_sample.body.substr(3,300) + "..."; //trecho do body que sera exibido no tool-tip;
+                    }
+
+                }
+
+            /*}*/ else { //IMAP
+                 // preferencia da pre-visualizacao
+			     if (cssForResizing) { //Colunas redimensionaveis - nao trunca
+                    /*problema no decode, se ele for utilizado, nao lista as mensagens -> CORRIGIDO em mail_archiver.js*/
+                    //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 {
+				    //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;
+                }
+            }
+        }
+
+		
 		if ((headers_msgs.Unseen == 'U') || (headers_msgs.Recent == 'N')){
-			if ((headers_msgs.Flagged == 'F') || headers_msgs.Importance.toLowerCase().indexOf("high")!=-1 )
+			if ((headers_msgs.Flagged == 'F') || ( headers_msgs.Importance !== undefined && headers_msgs.Importance.toLowerCase().indexOf("high")!=-1 ) )
 				add_className(tr_element, 'flagged_msg');
 			add_className(tr_element, 'tr_msg_unread');
@@ -1717,5 +1898,5 @@
 
 		td_element2 = createTDElement(0,1,"td_msg");
-		if (headers_msgs.attachment == 1)
+		if (headers_msgs.attachment == 1 || headers_msgs.attachment.number_attachments> 0)
 			td_element2.innerHTML = "<img src ='templates/"+template+"/images/clip.gif' >";
 
@@ -1887,5 +2068,5 @@
 		else
 		{
-			td_element4.innerHTML += headers_msgs.subject + "<span style=\"color:#b3b3b3;\">  " + tr_element.msg_sample + "</span>";//modificacao feita para exibir o trecho do body ao lado do assunto da mensagem;
+			td_element4.innerHTML += ($.trim(headers_msgs.subject) == "" ? "("+get_lang("No Subject")+")" : headers_msgs.subject) + "<span style=\"color:#b3b3b3;\">  " + tr_element.msg_sample + "</span>";//modificacao feita para exibir o trecho do body ao lado do assunto da mensagem;
 		}
 
@@ -1906,8 +2087,13 @@
 		}
 		
-		td_element26 = createTDElement(0,6,"td_msg","center","td_message_followup_"+headers_msgs.msg_number);
-		$(td_element26).addClass("td-followup-flag");
-		td_element26.innerHTML = '<div class="flag-edited" style="width:8px;height:6px;"><img src="../prototype/modules/mail/img/flagEditor.png"></div>';
-	
+		  td_element26 = createTDElement(0,6,"td_msg","center","td_message_followup_"+headers_msgs.msg_number);
+		  $(td_element26).addClass("td-followup-flag");
+
+        if(get_current_folder().split("_")[0] != "local"){
+		  td_element26.innerHTML = '<div class="flag-edited" style="width:8px;height:6px;"><img src="../prototype/modules/mail/img/flagEditor.png"></div>';
+	    } else {
+            td_element26.innerHTML = "";
+        }
+        
 		if (headers_msgs.followupflagged) {
 			if(headers_msgs.followupflagged.followupflag.id < 7){
@@ -2125,5 +2311,6 @@
 	search_box_type = search;
 	if (typeof(clean_selected) == "undefined"){	
-		$.ajax({			
+		
+        $.ajax({			
 			url: "controller.php?" + $.param( {action: "$this.imap_functions.getMessagesIds", 
 				folder: get_current_folder(),					
@@ -2151,4 +2338,5 @@
 			}
 		});
+        
 	}	
 	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);
@@ -2430,12 +2618,14 @@
 	var _maxChar = menuHidden ? 40 : 15;
 
-	if (info_msg.from.name)
-	{
-		var spanName = document.createElement("SPAN");
-			spanName.innerHTML = info_msg.from.name;
-		_name = spanName.innerHTML.length > _maxChar ? spanName.innerHTML.substring(0,_maxChar) + "..." : spanName.innerHTML;
-	}
-	else
-		_name = info_msg.from.email.length > _maxChar ? info_msg.from.email.substring(0,_maxChar) + "..." : info_msg.from.email;
+    if(info_msg.from){
+    	if (info_msg.from.name)
+    	{
+    		var spanName = document.createElement("SPAN");
+    			spanName.innerHTML = info_msg.from.name;
+    		_name = spanName.innerHTML.length > _maxChar ? spanName.innerHTML.substring(0,_maxChar) + "..." : spanName.innerHTML;
+    	}
+    	else
+    		_name = info_msg.from.email.length > _maxChar ? info_msg.from.email.substring(0,_maxChar) + "..." : info_msg.from.email;
+    }
 
 	td.innerHTML = _name.bold() + ', ' + info_msg.smalldate;
@@ -2516,6 +2706,6 @@
 	var option_mark_as_unseen = document.createElement("SPAN");
 		option_mark_as_unseen.className = "reply_options";
-	option_mark_as_unseen.onclick = function () {changeLinkState(this,'seen');
-		proxy_mensagens.proxy_set_message_flag(folder_id,'unseen');
+	    option_mark_as_unseen.onclick = function () {changeLinkState(this,'seen');
+		proxy_mensagens.proxy_set_message_flag(folder_id,'unseen',null,ID.split("_r_")[0]);
 		write_msg(get_lang('Message marked as ')+get_lang("Unseen"));
 	};
@@ -2532,17 +2722,13 @@
 		option_mark_important.onclick = function() {
 			var _this = this;
-			proxy_mensagens.proxy_set_message_flag(folder_id,'unflagged', function(success){
-				if (success) {
-					changeLinkState(_this, 'important');
-					write_msg(get_lang('Message marked as ') + get_lang("Normal"));
-				}
-			} );
-
+            changeLinkState(_this, 'important');
+			proxy_mensagens.proxy_set_message_flag(folder_id,'unflagged',null,ID.split("_r_")[0]);
+            write_msg(get_lang('Message marked as ')+get_lang("Normal"));
 		};
-		option_mark_important.innerHTML = get_lang("Normal");
+        option_mark_important.innerHTML = get_lang("Normal");
 	}
 	else{
-		option_mark_important.onclick = function() {changeLinkState(this,'normal');
-			proxy_mensagens.proxy_set_message_flag(folder_id,'flagged');
+		option_mark_important.onclick = function() {changeLinkState(this,'normal',null,ID.substr(0, ID.length-2));
+			proxy_mensagens.proxy_set_message_flag(folder_id,'flagged',null,ID.split("_r_")[0]);
 			write_msg(get_lang('Message marked as ')+get_lang("Important"));
 		};
@@ -2994,8 +3180,10 @@
 	var tr1 = document.createElement("TR");
 	tr1.className = "tr_message_header";
-	var td1 = document.createElement("TD");
-	td1.innerHTML = get_lang("From: ");
-	td1.appendChild(deny_email(info_msg.from.email));
-	td1.width = "7%";
+    if(info_msg.from){
+    	var td1 = document.createElement("TD");
+    	td1.innerHTML = get_lang("From: ");
+    	td1.appendChild(deny_email(info_msg.from.email));
+    	td1.width = "7%";
+    }
 
 	if (info_msg.sender){
@@ -3022,5 +3210,7 @@
 	var from = document.createElement("TD");
 	from.id = "from_"+ID;
-	from.innerHTML = info_msg.from.full;
+    if(info_msg.from){
+	   from.innerHTML = info_msg.from.full;
+    }
 	if (info_msg.Draft != "X"){
 		from.innerHTML += draw_plugin_cc(ID, info_msg.from);
@@ -3031,5 +3221,7 @@
 	from_values.id = "from_values_"+ID;
 	from_values.type = "HIDDEN";
-	from_values.value = info_msg.from.full; //Veio do IMAP, sem images nem links.
+    if(info_msg.from){
+    	from_values.value = info_msg.from.full; //Veio do IMAP, sem images nem links.
+    }
 
 	var local_message = document.createElement("INPUT");
@@ -3039,5 +3231,7 @@
 	local_message.value = (info_msg.local_message)?"1":"0";
 
-	tr1.appendChild(td1);
+    if(info_msg.from){
+	   tr1.appendChild(td1);
+    }
 	tr1.appendChild(from);
 	tr1.appendChild(from_values);
@@ -5126,4 +5320,10 @@
 
 function build_quota(data){
+    //MAILARCHIVE
+    // se for a pasta de mensagens locais
+    if(proxy_mensagens.is_local_folder(current_folder)) {
+        return;        
+    }
+
 	id = "content_quota";
 	q_limit = data['quota_limit'];
@@ -5466,9 +5666,16 @@
 		((expresso_offline)?" ":'<span class="message_options_export"><span ' + change_font_color + ' title="'+get_lang("Export")+'" class="message_options" onclick="proxy_mensagens.export_all_messages()">'+get_lang("Export")+'</span></span>') +
 		((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>');
-	if(preferences.use_local_messages==1 && !expresso_offline)
-		if(proxy_mensagens.is_local_folder(current_folder))
-			span_options.innerHTML += '&nbsp; <span id="localOption" ' + change_font_color + ' title="'+get_lang("Unarchive")+'" class="message_options" onclick="expresso_local_messages.unarchive_msgs(\''+folder+'\',null)">'+get_lang("Unarchive")+'</span>';
-		else
-			span_options.innerHTML += '&nbsp; <span id="localOption" ' + change_font_color + ' title="'+get_lang("Archive")+'" class="message_options" onclick="archive_msgs(\''+folder+'\',null)">'+get_lang("Archive")+'</span>';
+
+    //Link arquivar e desarquivar com ação
+    //MAILARCHIVER
+    if(preferences.use_local_messages==1){
+        if(expresso_mail_archive.enabled){
+           if(proxy_mensagens.is_local_folder(current_folder))//Unarchive link
+             span_options.innerHTML += '&nbsp; <span title="'+get_lang("Unarchive")+'" class="message_options" onclick="expresso_mail_archive.unarchieve(\''+folder+'\', null, null);">'+get_lang("Unarchive")+'</span>';
+           else//Archive link                 
+             span_options.innerHTML += '&nbsp; <span title="'+get_lang("Archive")+'" class="message_options" onclick="archive_msgs(\''+folder+'\',null,null)">'+get_lang("Archive")+'</span>';
+        }
+    }
+
 	if (use_spam_filter) {
 		if ( current_folder == 'INBOX'+cyrus_delimiter+'Spam' )	{
@@ -5487,4 +5694,7 @@
 		span_R.appendChild(span_D);
 	}
+    
+    var answer = '<span ' + change_font_color + ' id="span_flag_ANSWERED" class="'+(search_box_type == 'ANSWERED' ? 'message_options_over' : 'message_options')+'" title="'+get_lang("title_answered")+'" onclick="if(\'ANSWERED\' == \''+search_box_type+'\') return false;sort_box(\'ANSWERED\',\''+sort_box_type+'\')">'+get_lang("l_answered")+'</span>, ';
+
 	span_D.innerHTML =
    		 get_lang("List")+': '+
@@ -5492,5 +5702,5 @@
    	'<span ' + change_font_color + ' id="span_flag_UNSEEN" class="'+(search_box_type == 'UNSEEN' ? 'message_options_over' : 'message_options')+'" title="'+get_lang("l_unseen")+'" onclick="if(\'UNSEEN\' == \''+search_box_type+'\') return false;sort_box(\'UNSEEN\',\''+sort_box_type+'\')">'+get_lang("l_unseen")+'</span>, '+
   	'<span ' + change_font_color + ' id="span_flag_SEEN" class="'+(search_box_type == 'SEEN' ? 'message_options_over' : 'message_options')+'" title="'+get_lang("l_seen")+'" onclick="if(\'SEEN\' == \''+search_box_type+'\') return false;sort_box(\'SEEN\',\''+sort_box_type+'\')">'+get_lang("l_seen")+'</span>, '+
-   	'<span ' + change_font_color + ' id="span_flag_ANSWERED" class="'+(search_box_type == 'ANSWERED' ? 'message_options_over' : 'message_options')+'" title="'+get_lang("title_answered")+'" onclick="if(\'ANSWERED\' == \''+search_box_type+'\') return false;sort_box(\'ANSWERED\',\''+sort_box_type+'\')">'+get_lang("l_answered")+'</span>, '+
+   	answer+
    	'<span ' + change_font_color + ' id="span_flag_FLAGGED" class="'+(search_box_type == 'FLAGGED' ? 'message_options_over' : 'message_options')+'" title="'+get_lang("l_important")+'" onclick="if(\'FLAGGED\' == \''+search_box_type+'\') return false;sort_box(\'FLAGGED\',\''+sort_box_type+'\')">'+get_lang("l_important")+'</span>&nbsp;&nbsp;';
 	draw_paging(num_msgs);
Index: trunk/expressoMail1_2/js/doiMenuData.js
===================================================================
--- trunk/expressoMail1_2/js/doiMenuData.js	(revision 7222)
+++ trunk/expressoMail1_2/js/doiMenuData.js	(revision 7414)
@@ -1,373 +1,412 @@
-function labeledMessages(isLabel){
-			if (isLabel) {
-				var label = {
-					id: isLabel
-				}	
-				var lableleds = new Array();
-				var msg_folder = current_folder;
-				var messages = new Array();
-				if(currentTab == 0){
-					var id = get_selected_messages().split(',');
-					for (i = 0; i < id.length; i++){
-						messages.push({
-							msg_number: id[i],
-							msg_folder: msg_folder
-						});
-					}
-				}else{
-					// var id = get_selected_messages_search().split(',');
-					// var id_border = currentTab.replace(/[a-zA-Z_]+/, "");
-					// for (i = 0; i < id.length; i++){
-						// var tr = Element(id[i]+'_s'+id_border);
-						// msg_folder = tr.getAttribute('name'); 
-						// messages.push({
-							// "msg_number": id[i],
-							// "msg_folder": msg_folder,
-						// });
-					// }	
-					
-					var roles = get_selected_messages_search_role().split(',');
-					for (i = 0; i < roles.length; i++){
-						var tr = $('[role="'+roles[i]+'"]');
-						msg_folder = $(tr).attr('name'); 
-						var id = $(tr).attr('id'); 
-						messages.push({
-							"msg_number": id.replace(/_[a-zA-Z0-9]+/,""),
-							"msg_folder": msg_folder
-						});
-					}
-				}
-
-				for (var i=0; i < messages.length; i++) {
-					var hasLabel = DataLayer.get('labeled', {
-						filter: [
-							'AND',
-							['=', 'labelId', label.id], 
-							['=', 'folderName', messages[i].msg_folder], 
-							['=', 'messageNumber', messages[i].msg_number]
-					]});
-					if (!hasLabel || hasLabel == "") {
-						lableleds.push(
-							DataLayer.put('labeled', {
-								labelId:label.id, 
-								folderName:messages[i].msg_folder, 
-								messageNumber:messages[i].msg_number
-							})
-						);
-						
-					}
-				}
-				DataLayer.commit(false, false, function(data){
-					for (var i=0; i < messages.length; i++) {
-						updateLabelsColumn({msg_number:messages[i].msg_number, boxname:messages[i].msg_folder, labels:false});
-					}		
-				});
-				
-
-			}
-}
-
-function openListUsers(border_id) {
-	connector.loadScript("QuickCatalogSearch");
-	if (typeof(QuickCatalogSearch) == 'undefined'){
-					setTimeout('openListUsers('+border_id+')',500);
-					return false;
-				}
-	QuickCatalogSearch.showCatalogList(border_id);
-}
-
-
-/**
- * Cria a lista de marcadores para o submenu "Marcadores"
- */
-function getLabels(){
-	var labels = DataLayer.get('label',{criteria:{order: 'name'}});
-	var menuLabelItems = {};
-		menuLabelItems["new"] = {
-			"name" : get_lang('New Label'),
-			callback:function() {configureLabels({applyToSelectedMessages:true});}
-		};
-	for(var i=0; i<labels.length; i++) {
-		menuLabelItems["label"+labels[i].id] = {
-			"name" : labels[i].name
-		}
-	}
-	return menuLabelItems;
-}
-
-/**
- *	Carrega o menu de opção de uma mensagem
- */
-function loadMenu(){
-	var labelItems = getLabels();
-	$.contextMenu({
-		selector: ".table_box tbody tr",
-		callback: function(key, options) {
-			//TODO - default actions
-			
-			/** 
-			 * Apply labels to selected messages
-			 */
-			var isLabel = key.match(/label(.*)/);
-			if (isLabel && isLabel.length > 1) {
-				labeledMessages(isLabel[1]);
-			}
-			selectAllFolderMsgs(false);
-		},
-		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'); }},
-			
-			"sep1": "---------",
-			"label": { "name": get_lang("Labels"), "items": labelItems},
-			"follouwpflag":{"name": get_lang("Follow up"), callback: function(key, opt){ configureFollowupflag(); } },
-			
-			"sep2": "---------",
-			"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(); }}
-		}
-	});
-}
-/*FIM*/
-loadMenu();
-
-if (!expresso_offline) {
-	var menuToolsItems = {
-		"i01": {"name": get_lang("Preferences"), "icon": "preferences-mail", callback: preferences_mail },
-		"i02": {"name": get_lang("Search"), "icon": "search-mail", callback: function(key, opt){ search_emails(""); }},
-		"103": {"name": get_lang("Edit filters"), "icon": "filter", callback: filterbox2 },
-		"i05": {"name": get_lang("Share mailbox"), "icon": "share-mailbox", callback: sharebox },
-		"i06": {"name": get_lang("Labels"), "icon": "tag", callback: configureLabels }, 
-		"i08": {"name": get_lang("Empty trash"), "icon": "empty-trash", callback: function(key, opt){ empty_trash_imap(); }}
-	};
-		
-	if(preferences.use_local_messages==1) {
-		if(expresso_local_messages.is_offline_installed()) {
-			menuToolsItems["i09"] = {"name": get_lang("Send from queue"), "icon": "queue", callback: force_check_queue };
-		}
-	}
-} else {
-	var menuToolsItems = {
-		"i01": {"name": get_lang("Search"), "icon": "search-mail", callback: function(key, opt){ search_emails(""); }}
-	}
-}
-$.contextMenu({
-	selector: "#link_tools",
-	trigger: 'hover',
-	className: 'context-menu-tools',
-	position: function($menu, x, y){
-		$menu.$menu.position({ my: "center top", at: "center bottom", of: this, offset:"0 0"});
-	},
-	determinePosition: function($menu, x, y){
-		$menu.css('display', 'block').position({ my: "center top", at: "center bottom", of: this}).css('display', 'none');
-	},
-	delay:500,
-	autoHide:true,
-	events: {
-		show: function(opt) {
-			var $trigger = $(opt.selector).css({'background-color': '#ffffff', 'border': '1px solid #CCCCCC'});
-			$('.context-menu-tools.context-menu-list.context-menu-root').css({'width': $trigger.css('width') });
-			$('.context-menu-tools.context-menu-list').css({'background': '#ffffff'})
-			.find(".context-menu-item").css({'background-color': '#ffffff'}).hover(
-				function(){
-					$(this).css({'background-color': '#CCCCCC'});
-				}, 
-				function(){
-					$(this).css({'background-color': '#ffffff'});
-				}
-			);
-			return true;
-		},
-		hide: function(opt) {
-			$(opt.selector).css({'background-color': '', 'border': 'none'});
-			return true;
-		}
-	},
-	callback: function(key, options) {
-		//TODO - default actions
-
-	},
-	items: menuToolsItems
-});
-var reComplexEmail = /<([^<]*)>[\s]*$/;
-$.contextMenu({
-	selector: ".box",
-	autoHide:true,
-	items: {
-		"add" : {name: get_lang("Quick Add"), icon : "quick-add",callback: function(key, opt){ var fname = $(opt.$trigger).find("input").val().split('"')[1];ccQuickAddOne.showList(','+fname+', ,'+$.trim($(opt.$trigger).find("input").val()).match(reComplexEmail)[1]); }},
-		"remove" : {name:get_lang("Remove recipient"), icon:"delete-box",callback: function(key, opt){ $(opt.$trigger).remove(); }},
-		"sep1": "---------",
-		"quick_search" : {name:get_lang("Quick search of messages"), icon: "quick-search-contact",callback: function(key, opt){ search_emails($.trim($(opt.$trigger).find("input").val()).match(reComplexEmail)[1]); }},
-		"full_search" : {name:get_lang("Search messages of ..."), icon: "quick-search-contact",callback: function(key, opt){ search_emails("", $.trim($(opt.$trigger).find("input").val()).match(reComplexEmail)[1]);}}		
-	}
-});
-
-function updateLabelsColumn(messageInfo) {
-	var msg_number = messageInfo.msg_number;
-	//uid é o numero da mensagem quando os dados são carregados na busca rapida.
-	if(messageInfo.uid != '' && messageInfo.uid != 'undefined' && messageInfo.uid != null){
-		msg_number = messageInfo.uid;
-	}
-	var msg_folder = current_folder;
-	if(messageInfo.boxname != '' && messageInfo.boxname != 'undefined' && messageInfo.boxname != null){
-		msg_folder = messageInfo.boxname;
-	}
-	
-	 if(current_folder == msg_folder || !current_folder){
-		 $('#td_message_labels_' + msg_number +', tr[role="'+msg_number+'_'+msg_folder+'"] #td_message_labels_search_' + msg_number)
-		 .html('<img src="../prototype/modules/mail/img/tag.png">');
-	}else{
-		$('tr[role="'+msg_number+'_'+msg_folder+'"] #td_message_labels_search_' + msg_number)
-		.html('<img src="../prototype/modules/mail/img/tag.png">');
-	}
-	
-	var menuItems = {};
-	if (messageInfo.labels) {
-		if($.isArray(messageInfo.labels)){
-			var labels = messageInfo.labels;
-			messageInfo.labels = {};
-			for(var i in labels)
-				messageInfo.labels[labels[i].id] = {backgroundColor: labels[i]['backgroundColor'],
-					borderColor: labels[i]['borderColor'],
-					fontColor: labels[i]['fontColor'], id: labels[i]['id'], name: labels[i]['name'], 
-					uid: labels[i]['uid'] }
-		}	
-		menuItems = messageInfo.labels;
-	} else {
-		var labeleds = DataLayer.get('labeled', {
-			criteria: {deepness: '2'},
-			filter: [
-				'AND',
-				['=', 'folderName', msg_folder], 
-				['=', 'messageNumber', msg_number]
-			]
-			
-		});
-		if (labeleds) {
-			for (var i=0; i < labeleds.length; i++)
-				menuItems[labeleds[i].label.id] = labeleds[i].label;
-		} else {
-			$('#td_message_labels_' + msg_number +', tr[role="'+msg_number+'_'+msg_folder+'"] #td_message_labels_search_' + msg_number)
-			.html('');
-			//$.contextMenu( 'destroy', '#td_message_labels_' + msg_number +', #td_message_labels_search_' + msg_number+':first');
-			$.contextMenu( 'destroy', '#td_message_labels_' + msg_number +', tr[role="'+msg_number+'_'+msg_folder+'"] #td_message_labels_search_' + msg_number);
-			return false;
-		}
-	}
-	var menuItensLabel = {};
-	for(index in menuItems){
-		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>')
-            .appendTo(this);
-		$(this).find('span.removeLabeled').click(function(){
-			//TODO Mudar quando API abstrair atualizações no cache
-			DataLayer.remove('labeled', false);
-			DataLayer.get('labeled');
-			DataLayer.remove('labeled', item.id);
-			DataLayer.commit(false, false, function(){
-				updateLabelsColumn({msg_number:msg_number, boxname:msg_folder, labels:false});
-			});
-		});
-	};
-	if(current_folder == msg_folder || !current_folder){
-		$.contextMenu( 'destroy', '#td_message_labels_' + msg_number +', tr[role="'+msg_number+'_'+msg_folder+'"] #td_message_labels_search_' + msg_number);
-		$.contextMenu({
-			selector: '#td_message_labels_' + msg_number +', tr[role="'+msg_number+'_'+msg_folder+'"] #td_message_labels_search_' + msg_number,
-			trigger: 'hover',
-			delay:100,
-			autoHide:true,
-			callback: function(key, options) {
-				//TODO - default actions
-			},
-			items: menuItensLabel
-		});
-	}else{
-		$.contextMenu( 'destroy', 'tr[role="'+msg_number+'_'+msg_folder+'"] #td_message_labels_search_' + msg_number);
-
-		$.contextMenu({
-			selector: 'tr[role="'+msg_number+'_'+msg_folder+'"] #td_message_labels_search_' + msg_number,
-			trigger: 'hover',
-			delay:100,
-			autoHide:true,
-			callback: function(key, options) {
-				//TODO - default actions
-			},
-			items: menuItensLabel 
-		});	
-	}
-}
-
-function loadExtraLDAPBox(data, element){
-
-    if(!!data[0]){
-        var decoded = {};
-
-        $.each(data, function(i, e){
-            decoded[e.name] = e.value;
-        });
-
-        data = decoded;
-    }
-
-	menuItensLabel = {};
-	menuItensLabel["Name"] = {name: "<b>"+data.name+"</b>", disabled: true};
-	menuItensLabel["Email"] = {name: data.email, disabled: true};
-	if(!!data.telephone){
-		menuItensLabel["TelefoneLabel"] = {name: "<b>"+get_lang("Telephone")+"</b>", disabled: true};
-		menuItensLabel["TelefoneValue"] = {name: data.telephone, disabled: true};
-	}
-	if(data.vacationActive){
-		if(data.vacationActive == "TRUE"){
-			menuItensLabel["outOffice"] = {name: "<b>"+get_lang("Out of office")+"</b>", disabled: true};
-			menuItensLabel["outOfficeValue"] = {name: data.vacationInfo.substring(0, 20), disabled: true};
-		}
-	}
-	$.contextMenu({
-		selector: "#content_id_"+currentTab+" "+element+" .box-info",
-		trigger: 'hover',
-		delay:100,
-		autoHide:true,
-		items: menuItensLabel
-	});	
-}
-
-function loadGroupBox(data, element){
-	menuItensLabel = {};
-	menuItensLabel["ContactGroupLabelAll"] = {name:"<b>"+get_lang("Group contacts")+"</b>", disabled: true};
-	menuItensLabel["sep1"] = "---------";
-	if(data.itens){
-		var aux = 0;
-		var ctcName = "";
-		for(var item in data.itens){
-			if(parseInt(item) <= 4){
-				ctcName = data.itens[item].data[0].value;
-				ctcName = ctcName.length > 2 ? ctcName : data.itens[item].data[2].value.substr(0,data.itens[item].data[2].value.indexOf("@"));
-				menuItensLabel["ContactGroupLabel"+item] = {name: "<b>"+ctcName+"</b>", disabled: true};
-				menuItensLabel["ContactGroupValue"+item] = {name: data.itens[item].data[2].value, disabled: true};
-			}else{
-				aux++;
-				if(aux == 1)
-					menuItensLabel["MoreContactGroupValue"] = {name : get_lang("And more %1 contact", aux), disabled: true };
-				else
-					menuItensLabel["MoreContactGroupValue"] = {name : get_lang("And more %1 contact", aux)+"s", disabled: true };
-			}
-		}
-	}
-	$.contextMenu({
-		selector: "#content_id_"+currentTab+" "+element+" .box-info",
-		trigger: 'hover',
-		delay:100,
-		autoHide:true,
-		items: menuItensLabel
-	});	
-}
-
-
-
-
-
+    function labeledMessages(isLabel){
+        if(get_current_folder().split("_")[0] == "local"){
+            alert("Pastas locais não fornece suporte para adição de marcadores.")
+            return true;
+        }
+    			if (isLabel) {
+    				var label = {
+    					id: isLabel
+    				}	
+    				var lableleds = new Array();
+    				var msg_folder = current_folder;
+    				var messages = new Array();
+    				if(currentTab == 0){
+    					var id = get_selected_messages().split(',');
+    					for (i = 0; i < id.length; i++){
+    						messages.push({
+    							msg_number: id[i],
+    							msg_folder: msg_folder
+    						});
+    					}
+    				}else{
+    					// var id = get_selected_messages_search().split(',');
+    					// var id_border = currentTab.replace(/[a-zA-Z_]+/, "");
+    					// for (i = 0; i < id.length; i++){
+    						// var tr = Element(id[i]+'_s'+id_border);
+    						// msg_folder = tr.getAttribute('name'); 
+    						// messages.push({
+    							// "msg_number": id[i],
+    							// "msg_folder": msg_folder,
+    						// });
+    					// }	
+    					
+    					var roles = get_selected_messages_search_role().split(',');
+    					for (i = 0; i < roles.length; i++){
+    						var tr = $('[role="'+roles[i]+'"]');
+    						msg_folder = $(tr).attr('name'); 
+    						var id = $(tr).attr('id'); 
+    						messages.push({
+    							"msg_number": id.replace(/_[a-zA-Z0-9]+/,""),
+    							"msg_folder": msg_folder
+    						});
+    					}
+    				}
+
+    				for (var i=0; i < messages.length; i++) {
+    					var hasLabel = DataLayer.get('labeled', {
+    						filter: [
+    							'AND',
+    							['=', 'labelId', label.id], 
+    							['=', 'folderName', messages[i].msg_folder], 
+    							['=', 'messageNumber', messages[i].msg_number]
+    					]});
+    					if (!hasLabel || hasLabel == "") {
+    						lableleds.push(
+    							DataLayer.put('labeled', {
+    								labelId:label.id, 
+    								folderName:messages[i].msg_folder, 
+    								messageNumber:messages[i].msg_number
+    							})
+    						);
+    						
+    					}
+    				}
+    				DataLayer.commit(false, false, function(data){
+    					for (var i=0; i < messages.length; i++) {
+    						updateLabelsColumn({msg_number:messages[i].msg_number, boxname:messages[i].msg_folder, labels:false});
+    					}		
+    				});
+    				
+
+    			}
+    }
+
+    function openListUsers(border_id) {
+    	connector.loadScript("QuickCatalogSearch");
+    	if (typeof(QuickCatalogSearch) == 'undefined'){
+    					setTimeout('openListUsers('+border_id+')',500);
+    					return false;
+    				}
+    	QuickCatalogSearch.showCatalogList(border_id);
+    }
+
+
+    /**
+     * Cria a lista de marcadores para o submenu "Marcadores"
+     */
+    function getLabels(){
+    	var labels = DataLayer.get('label',{criteria:{order: 'name'}});
+    	var menuLabelItems = {};
+    		menuLabelItems["new"] = {
+    			"name" : get_lang('New Label'),
+    			callback:function() {configureLabels({applyToSelectedMessages:true});}
+    		};
+    	for(var i=0; i<labels.length; i++) {
+    		menuLabelItems["label"+labels[i].id] = {
+    			"name" : labels[i].name
+    		}
+    	}
+    	return menuLabelItems;
+    }
+
+    /**
+     *	Carrega o menu de opção de uma mensagem
+     */
+    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 = "";
+        }
+
+    	var labelItems = getLabels();
+    	$.contextMenu({
+    		selector: ".table_box tbody tr",
+            build: function($trigger, e) {
+
+                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'); }},
+                    "sep1": "---------"
+                }
+
+                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(); }},
+                    "archive": archive
+                }
+
+                var realItens = {};
+
+                if(currentTab == 0){
+                    if(get_current_folder().split("local").length > 1){
+                        realItens = $.extend(items, lastItens);
+                    }else{
+                        realItens = $.extend(items, itensNotLocal);
+                        realItens = $.extend(realItens, lastItens);
+                    }
+                }else if(currentTab.split("local").length > 1){
+                    realItens = $.extend(items, lastItens);
+                }else{
+                    realItens = $.extend(items, itensNotLocal);
+                    realItens = $.extend(realItens, lastItens);
+                }
+
+        		return { 
+                    callback: function(key, options) {
+        			//TODO - default actions
+        			
+        			/** 
+        			 * Apply labels to selected messages
+        			 */
+            			var isLabel = key.match(/label(.*)/);
+            			if (isLabel && isLabel.length > 1) {
+            				labeledMessages(isLabel[1]);
+            			}
+            			selectAllFolderMsgs(false);
+            		},
+            		items: realItens
+                }
+            }
+    	});
+    }
+    /*FIM*/
+    loadMenu();
+
+    if (!expresso_offline) {
+    	var menuToolsItems = {
+    		"i01": {"name": get_lang("Preferences"), "icon": "preferences-mail", callback: preferences_mail },
+    		"i02": {"name": get_lang("Search"), "icon": "search-mail", callback: function(key, opt){ search_emails(""); }},
+    		"103": {"name": get_lang("Edit filters"), "icon": "filter", callback: filterbox2 },
+    		"i05": {"name": get_lang("Share mailbox"), "icon": "share-mailbox", callback: sharebox },
+    		"i06": {"name": get_lang("Labels"), "icon": "tag", callback: configureLabels }, 
+    		"i08": {"name": get_lang("Empty trash"), "icon": "empty-trash", callback: function(key, opt){ empty_trash_imap(); }}
+    	};
+    		
+    	if(preferences.use_local_messages==1) {
+    		if(expresso_local_messages.is_offline_installed()) {
+    			menuToolsItems["i09"] = {"name": get_lang("Send from queue"), "icon": "queue", callback: force_check_queue };
+    		}
+    	}
+    } else {
+    	var menuToolsItems = {
+    		"i01": {"name": get_lang("Search"), "icon": "search-mail", callback: function(key, opt){ search_emails(""); }}
+    	}
+    }
+    $.contextMenu({
+    	selector: "#link_tools",
+    	trigger: 'hover',
+    	className: 'context-menu-tools',
+    	position: function($menu, x, y){
+    		$menu.$menu.position({ my: "center top", at: "center bottom", of: this, offset:"0 0"});
+    	},
+    	determinePosition: function($menu, x, y){
+    		$menu.css('display', 'block').position({ my: "center top", at: "center bottom", of: this}).css('display', 'none');
+    	},
+    	delay:500,
+    	autoHide:true,
+    	events: {
+    		show: function(opt) {
+    			var $trigger = $(opt.selector).css({'background-color': '#ffffff', 'border': '1px solid #CCCCCC'});
+    			$('.context-menu-tools.context-menu-list.context-menu-root').css({'width': $trigger.css('width') });
+    			$('.context-menu-tools.context-menu-list').css({'background': '#ffffff'})
+    			.find(".context-menu-item").css({'background-color': '#ffffff'}).hover(
+    				function(){
+    					$(this).css({'background-color': '#CCCCCC'});
+    				}, 
+    				function(){
+    					$(this).css({'background-color': '#ffffff'});
+    				}
+    			);
+    			return true;
+    		},
+    		hide: function(opt) {
+    			$(opt.selector).css({'background-color': '', 'border': 'none'});
+    			return true;
+    		}
+    	},
+    	callback: function(key, options) {
+    		//TODO - default actions
+
+    	},
+    	items: menuToolsItems
+    });
+    var reComplexEmail = /<([^<]*)>[\s]*$/;
+    $.contextMenu({
+    	selector: ".box",
+    	autoHide:true,
+    	items: {
+    		"add" : {name: get_lang("Quick Add"), icon : "quick-add",callback: function(key, opt){ var fname = $(opt.$trigger).find("input").val().split('"')[1];ccQuickAddOne.showList(','+fname+', ,'+$.trim($(opt.$trigger).find("input").val()).match(reComplexEmail)[1]); }},
+    		"remove" : {name:get_lang("Remove recipient"), icon:"delete-box",callback: function(key, opt){ $(opt.$trigger).remove(); }},
+    		"sep1": "---------",
+    		"quick_search" : {name:get_lang("Quick search of messages"), icon: "quick-search-contact",callback: function(key, opt){ search_emails($.trim($(opt.$trigger).find("input").val()).match(reComplexEmail)[1]); }},
+    		"full_search" : {name:get_lang("Search messages of ..."), icon: "quick-search-contact",callback: function(key, opt){ search_emails("", $.trim($(opt.$trigger).find("input").val()).match(reComplexEmail)[1]);}}		
+    	}
+    });
+
+    function updateLabelsColumn(messageInfo) {
+    	var msg_number = messageInfo.msg_number;
+    	//uid é o numero da mensagem quando os dados são carregados na busca rapida.
+    	if(messageInfo.uid != '' && messageInfo.uid != 'undefined' && messageInfo.uid != null){
+    		msg_number = messageInfo.uid;
+    	}
+    	var msg_folder = current_folder;
+    	if(messageInfo.boxname != '' && messageInfo.boxname != 'undefined' && messageInfo.boxname != null){
+    		msg_folder = messageInfo.boxname;
+    	}
+    	
+    	 if(current_folder == msg_folder || !current_folder){
+    		 $('#td_message_labels_' + msg_number +', tr[role="'+msg_number+'_'+msg_folder+'"] #td_message_labels_search_' + msg_number)
+    		 .html('<img src="../prototype/modules/mail/img/tag.png">');
+    	}else{
+    		$('tr[role="'+msg_number+'_'+msg_folder+'"] #td_message_labels_search_' + msg_number)
+    		.html('<img src="../prototype/modules/mail/img/tag.png">');
+    	}
+    	
+    	var menuItems = {};
+    	if (messageInfo.labels) {
+    		if($.isArray(messageInfo.labels)){
+    			var labels = messageInfo.labels;
+    			messageInfo.labels = {};
+    			for(var i in labels)
+    				messageInfo.labels[labels[i].id] = {backgroundColor: labels[i]['backgroundColor'],
+    					borderColor: labels[i]['borderColor'],
+    					fontColor: labels[i]['fontColor'], id: labels[i]['id'], name: labels[i]['name'], 
+    					uid: labels[i]['uid'] }
+    		}	
+    		menuItems = messageInfo.labels;
+    	} else {
+    		var labeleds = DataLayer.get('labeled', {
+    			criteria: {deepness: '2'},
+    			filter: [
+    				'AND',
+    				['=', 'folderName', msg_folder], 
+    				['=', 'messageNumber', msg_number]
+    			]
+    			
+    		});
+    		if (labeleds) {
+    			for (var i=0; i < labeleds.length; i++)
+    				menuItems[labeleds[i].label.id] = labeleds[i].label;
+    		} else {
+    			$('#td_message_labels_' + msg_number +', tr[role="'+msg_number+'_'+msg_folder+'"] #td_message_labels_search_' + msg_number)
+    			.html('');
+    			//$.contextMenu( 'destroy', '#td_message_labels_' + msg_number +', #td_message_labels_search_' + msg_number+':first');
+    			$.contextMenu( 'destroy', '#td_message_labels_' + msg_number +', tr[role="'+msg_number+'_'+msg_folder+'"] #td_message_labels_search_' + msg_number);
+    			return false;
+    		}
+    	}
+    	var menuItensLabel = {};
+    	for(index in menuItems){
+    		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>')
+                .appendTo(this);
+    		$(this).find('span.removeLabeled').click(function(){
+    			//TODO Mudar quando API abstrair atualizações no cache
+    			DataLayer.remove('labeled', false);
+    			DataLayer.get('labeled');
+    			DataLayer.remove('labeled', item.id);
+    			DataLayer.commit(false, false, function(){
+    				updateLabelsColumn({msg_number:msg_number, boxname:msg_folder, labels:false});
+    			});
+    		});
+    	};
+    	if(current_folder == msg_folder || !current_folder){
+    		$.contextMenu( 'destroy', '#td_message_labels_' + msg_number +', tr[role="'+msg_number+'_'+msg_folder+'"] #td_message_labels_search_' + msg_number);
+    		$.contextMenu({
+    			selector: '#td_message_labels_' + msg_number +', tr[role="'+msg_number+'_'+msg_folder+'"] #td_message_labels_search_' + msg_number,
+    			trigger: 'hover',
+    			delay:100,
+    			autoHide:true,
+    			callback: function(key, options) {
+    				//TODO - default actions
+    			},
+    			items: menuItensLabel
+    		});
+    	}else{
+    		$.contextMenu( 'destroy', 'tr[role="'+msg_number+'_'+msg_folder+'"] #td_message_labels_search_' + msg_number);
+
+    		$.contextMenu({
+    			selector: 'tr[role="'+msg_number+'_'+msg_folder+'"] #td_message_labels_search_' + msg_number,
+    			trigger: 'hover',
+    			delay:100,
+    			autoHide:true,
+    			callback: function(key, options) {
+    				//TODO - default actions
+    			},
+    			items: menuItensLabel 
+    		});	
+    	}
+    }
+
+    function loadExtraLDAPBox(data, element){
+
+        if(!!data[0]){
+            var decoded = {};
+
+            $.each(data, function(i, e){
+                decoded[e.name] = e.value;
+            });
+
+            data = decoded;
+        }
+
+        menuItensLabel = {};
+        menuItensLabel["Name"] = {name: "<b>"+data.name+"</b>", disabled: true};
+        menuItensLabel["Email"] = {name: data.email, disabled: true};
+        if(!!data.telephone){
+            menuItensLabel["TelefoneLabel"] = {name: "<b>"+get_lang("Telephone")+"</b>", disabled: true};
+            menuItensLabel["TelefoneValue"] = {name: data.telephone, disabled: true};
+        }
+        if(data.vacationActive){
+            if(data.vacationActive == "TRUE"){
+                menuItensLabel["outOffice"] = {name: "<b>"+get_lang("Out of office")+"</b>", disabled: true};
+                menuItensLabel["outOfficeValue"] = {name: data.vacationInfo.substring(0, 20), disabled: true};
+            }
+        }
+        $.contextMenu({
+            selector: "#content_id_"+currentTab+" "+element+" .box-info",
+            trigger: 'hover',
+            delay:100,
+            autoHide:true,
+            items: menuItensLabel
+        }); 
+    }
+
+    function loadGroupBox(data, element){
+    	menuItensLabel = {};
+    	menuItensLabel["ContactGroupLabelAll"] = {name:"<b>"+get_lang("Group contacts")+"</b>", disabled: true};
+    	menuItensLabel["sep1"] = "---------";
+    	if(data.itens){
+    		var aux = 0;
+    		var ctcName = "";
+    		for(var item in data.itens){
+    			if(parseInt(item) <= 4){
+    				ctcName = data.itens[item].data[0].value;
+    				ctcName = ctcName.length > 2 ? ctcName : data.itens[item].data[2].value.substr(0,data.itens[item].data[2].value.indexOf("@"));
+    				menuItensLabel["ContactGroupLabel"+item] = {name: "<b>"+ctcName+"</b>", disabled: true};
+    				menuItensLabel["ContactGroupValue"+item] = {name: data.itens[item].data[2].value, disabled: true};
+    			}else{
+    				aux++;
+    				if(aux == 1)
+    					menuItensLabel["MoreContactGroupValue"] = {name : get_lang("And more %1 contact", aux), disabled: true };
+    				else
+    					menuItensLabel["MoreContactGroupValue"] = {name : get_lang("And more %1 contact", aux)+"s", disabled: true };
+    			}
+    		}
+    	}
+    	$.contextMenu({
+    		selector: "#content_id_"+currentTab+" "+element+" .box-info",
+    		trigger: 'hover',
+    		delay:100,
+    		autoHide:true,
+    		items: menuItensLabel
+    	});	
+    }
+
+
+
+
+
