Index: /trunk/prototype/modules/attach_message/attach_message.js
===================================================================
--- /trunk/prototype/modules/attach_message/attach_message.js	(revision 7543)
+++ /trunk/prototype/modules/attach_message/attach_message.js	(revision 7907)
@@ -231,4 +231,27 @@
 var selectedFolder     = {};
 
+function mount_children_localfolders_list(folder){ 
+    folder.children = new Array();
+    folder.id_search = folder.id;
+    folder.id = 'local_messages_'+folder.id,
+    folder.commonName =  folder.name,
+    folder.parentId = folder.parentid,
+    folder.type = 'localFolder',
+    folder.name = folder.id,
+    folder.messageCount = {
+                             total: folder.messages,
+                             unseen: folder.unseen
+                          }
+
+    if(folder.haschild){
+        expresso_mail_archive.getFoldersList(folder.id_search);
+        folder.children = expresso_mail_archive.folders;
+
+        for(var i = 0; i < folder.children.length; i++){
+            mount_children_localfolders_list(folder.children[i]);
+        }
+
+    }
+}
 function adaptOffline( data )
 {
@@ -254,5 +277,22 @@
 	
     return( data );
-	
+}
+
+function archive_flag( flagObj ){
+
+    var flags = {};
+    var returns = '';
+
+    $.each( flagObj.tag , function(i, flag){
+        flags[ flag['@value'] ] = true;
+    });
+
+	returns += (flags['seen'] ? '0,' : '1,') ;
+	returns += (flags['answered'] && !flags['forwarded'] ? '1,' : '0,') ;
+	returns += (flags['forwarded'] ? '1,' : '0,') ;
+	returns += (flags['flagged'] || flags['importance_high'] ? '1,' : '0,') ;
+	returns += '0,0';
+            
+    return returns;
 }
 
@@ -271,4 +311,21 @@
 		var tree2 = new Array();
 		var tree3 = new Array();
+
+        if(preferences.use_local_messages == 1){
+            if(expresso_mail_archive.folders && !expresso_offline && expresso_mail_archive.enabled == true) { //MailArchive
+                //pega pastas locais do mailarchiver e insere no array de pastas
+                    expresso_mail_archive.getFoldersList("home");
+                    treeFolders = expresso_mail_archive.folders;
+
+                    for(var i=0; i<treeFolders.length; i++ ){
+                        mount_children_localfolders_list(treeFolders[i]);
+                    }
+                    
+                    for(var i = 0; i < treeFolders.length; i++){
+                        data.push(treeFolders[i]);
+                    }
+            }
+        }
+
 		for (var i=0; i<data.length; i++) {
 
@@ -286,8 +343,5 @@
 			}
 			else if (/^local_messages/.test(data[i].id)) {
-				if (!unorphanize(tree3, data[i])) {
-					data[i].children = new Array();
 					tree3.push(data[i]);
-				}
 			}
 			
@@ -299,4 +353,5 @@
 		.find("#foldertree").treeview()
 		.click(function(event){
+
 			//request new selected folder messages
 			var target = $(event.target);
@@ -325,14 +380,57 @@
 			var grid = $("#message_attacher_grid"), offlineCase = "";
 			
-			if( !targetId.indexOf( 'local_messages/' ) )
-			    offlineCase = ":offline";
-			
-
-			grid.jqGrid('setGridParam',{url:BASE_PATH + 'REST.php'+offlineCase+'?q=folder/'+targetId.replace(dashes, '.')+'/message'})
-			    .trigger("reloadGrid")
-			    .jqGrid('setCaption', '<span class="'+child.attr('class')+'">'+child.attr('title')+'</span>');
+            if(targetId.indexOf( 'local_messages' ) == 0){
+                 //Entrar caso: Clicar em uma pasta que seja do arquivamento local
+                targetId = targetId.split("_")[2];
+
+                expresso_mail_archive.getMessagesByFolder(targetId,"ALL");
+
+                msgAll = expresso_mail_archive.msgAll;                
+
+                var msgs = new Array();
+                var from = '';
+                var flag = '';
+                
+                $.each(msgAll, function(i, msg){
+                    from = $.parseJSON(msg['_from']);
+
+                    if(!from){
+                        from = {"mailbox":{"name":"null","route":"null","localPart":"null","domain":"null"}};
+                    }
+
+                    flag = $.parseJSON(msg['_tags']);
+                    id = msg['_id'];
+
+                    var message = {};
+                    
+                    message['msg_number'] = id;
+                    message['flags'] = archive_flag( flag );
+                    message['from.name'] = from['mailbox']['@name'];
+                    message['subject'] = msg['_subject'];
+                    message['timestamp'] = msg['_receivedDate'];
+                    message['size'] = msg['_size'];
+                    message['id'] = id;
+                    msgs.push( message );
+
+                });
+
+            grid.jqGrid("clearGridData", true);
+            grid.jqGrid('setGridParam',{datatype: "local",data: msgs})
+                    .trigger("reloadGrid")
+                    .jqGrid('setCaption', '<span class="'+child.attr('class')+'">'+child.attr('title')+'</span>');
+
+            } else {
+                if( !targetId.indexOf( 'local_messages/' ) )
+                    offlineCase = ":offline";
+
+                grid.jqGrid('setGridParam',{datatype: "json", url:BASE_PATH + 'REST.php'+offlineCase+'?q=folder/'+targetId.replace(dashes, '.')+'/message'})
+                    .trigger("reloadGrid")
+                    .jqGrid('setCaption', '<span class="'+child.attr('class')+'">'+child.attr('title')+'</span>');
+            }
+
+
 		})
 		.find('span:first-child');
-		$('span.folder.inbox').addClass('selected');
+		$('span.folder.inbox').parents(".ui-dialog").find("li#INBOX span").addClass('selected');
 		selectedFolder = {
 			id: firstFolder.parent().attr('id'), 
@@ -409,10 +507,34 @@
 					}
 				}
-				
 				var tabPanelTemplateId = 'mailpreview_tab_' + selectedFolder.id.replace(/[.\/]/g, '_') + '_' + message.msg_number;
 				var tabPanelTemplateId = tabPanelTemplateId.replace(/[\s\/]/g, '-'); 
 				
 				if (selected) {	
+                   if(selectedFolder['id'].indexOf("local_messages_") != -1){
+
+                        expresso_mail_archive.getPreviewToAttach(id);
+
+                        var body = expresso_mail_archive.bodyPreview;
+                        var subject = expresso_mail_archive.subjectPreview;
+                        tabPanelTemplateLabel =  subject.substring(0, $mailpreview_tabs_label_length) + '...';
+
+                        if (!$('#' + tabPanelTemplateId).length) {
+                            $mailpreview_tabs.tabs("add", '#' + tabPanelTemplateId, tabPanelTemplateLabel)
+                            .find('.message.empty-container').hide().end()
+                            .find('#' + tabPanelTemplateId).html(body)
+                            .prepend(
+                                '<div class="mailpreview-message-info">' + 
+                                    get_lang('Subject') + ': ' +
+                                    html_entities(subject) + 
+                                '</div>'
+                            )
+                            .find('[class^="ExpressoCssWrapper"]').addClass("mailpreview-message-body");
+                        } else {
+                            $mailpreview_tabs.tabs('select', '#' + tabPanelTemplateId)
+                            .find('#' + tabPanelTemplateId + ', [href="#' + tabPanelTemplateId + '"]').removeClass('preview-message-unselected');
+                        }
+                    }
 					if (onceOpenedMessages[selectedFolder.id] && onceOpenedMessages[selectedFolder.id][message.msg_number]) {
+
 						if (!selectedMessages[selectedFolder.id])
 							selectedMessages[selectedFolder.id] = {};
@@ -425,5 +547,5 @@
 							tabPanelTemplateLabel = tabPanelTemplateLabel.substring(0, $mailpreview_tabs_label_length) + '...';
 						
-						if (!$('#' + tabPanelTemplateId).length) {								
+						if (!$('#' + tabPanelTemplateId).length) {
 							$mailpreview_tabs.tabs("add", '#' + tabPanelTemplateId, tabPanelTemplateLabel)
 							.find('.message.empty-container').hide().end()
@@ -433,5 +555,7 @@
 							.find('#' + tabPanelTemplateId + ', [href="#' + tabPanelTemplateId + '"]').removeClass('preview-message-unselected');
 						}
-						
+
+                        
+
 					} else {
 						jQuery('#mailpreview_container').block({  
@@ -460,38 +584,57 @@
 							selectedMessages[selectedFolder.id] = {};
 						selectedMessages[selectedFolder.id][message.msg_number] = true;
-						$.ajax({
-							accepts: 'text/html',
-							url: BASE_PATH + 'REST.php'+offlineCase+'?q=folder/'+selectedFolder.id.replace(dashes, '.')+'/message/'+id,
-							dataType: 'json',
-							success: function( mail_preview ){		
-								//selectedMessagesCount();
-								if (!onceOpenedMessages[selectedFolder.id])
-									onceOpenedMessages[selectedFolder.id] = {};
-								onceOpenedMessages[selectedFolder.id][message.msg_number] = jQuery.extend(true, message, mail_preview);
-
-								$('#mailpreview_container').unblock();
-
-								var tabPanelTemplateLabel = html_entities(onceOpenedMessages[selectedFolder.id][message.msg_number].subject);
-								if (tabPanelTemplateLabel.length > $mailpreview_tabs_label_length + 3)
-									tabPanelTemplateLabel = tabPanelTemplateLabel.substring(0, $mailpreview_tabs_label_length) + '...';
-							selectedMessagesCount();
-								
-								if (!$('#' + tabPanelTemplateId).length) {								
-									$mailpreview_tabs.tabs("add", '#' + tabPanelTemplateId, tabPanelTemplateLabel)
-									.find('.message.empty-container').hide().end()
-									.find('#' + tabPanelTemplateId).html(onceOpenedMessages[selectedFolder.id][message.msg_number].body)
-									.prepend(
-										'<div class="mailpreview-message-info">' + 
-											get_lang('Subject') + ': ' +
-											html_entities(onceOpenedMessages[selectedFolder.id][message.msg_number].subject) + 
-										'</div>'
-									)
-									.find('[class^="ExpressoCssWrapper"]').addClass("mailpreview-message-body");
-								} else {
-									$mailpreview_tabs.tabs('select', '#' + tabPanelTemplateId)
-									.find('#' + tabPanelTemplateId + ', [href="#' + tabPanelTemplateId + '"]').removeClass('preview-message-unselected');
-								}
-							}
-						});
+
+
+                        if(selectedFolder['id'].indexOf("local_messages_") != -1){
+                            $('#mailpreview_container').unblock();
+                            if (!onceOpenedMessages[selectedFolder.id])
+                                    onceOpenedMessages[selectedFolder.id] = {};
+                                onceOpenedMessages[selectedFolder.id][message.msg_number] = message;
+
+                            var tabPanelTemplateLabel = html_entities(onceOpenedMessages[selectedFolder.id][message.msg_number].subject);
+                                    if (tabPanelTemplateLabel.length > $mailpreview_tabs_label_length + 3)
+                                        tabPanelTemplateLabel = tabPanelTemplateLabel.substring(0, $mailpreview_tabs_label_length) + '...';
+                            selectedMessagesCount();
+                        } else {
+    						$.ajax({
+    							accepts: 'text/html',
+    							url: BASE_PATH + 'REST.php'+offlineCase+'?q=folder/'+selectedFolder.id.replace(dashes, '.')+'/message/'+id,
+    							dataType: 'json',
+    							success: function( mail_preview ){		
+    								//selectedMessagesCount();
+    								if (!onceOpenedMessages[selectedFolder.id])
+    									onceOpenedMessages[selectedFolder.id] = {};
+    								onceOpenedMessages[selectedFolder.id][message.msg_number] = jQuery.extend(true, message, mail_preview);
+
+    								$('#mailpreview_container').unblock();
+
+    								var tabPanelTemplateLabel = html_entities(onceOpenedMessages[selectedFolder.id][message.msg_number].subject);
+    								if (tabPanelTemplateLabel.length > $mailpreview_tabs_label_length + 3)
+    									tabPanelTemplateLabel = tabPanelTemplateLabel.substring(0, $mailpreview_tabs_label_length) + '...';
+    							selectedMessagesCount();
+    								
+    								if (!$('#' + tabPanelTemplateId).length) {	
+                                       
+
+                                    //tabPanelTemplateId - mailpreview_tab_INBOX_1110
+                                    //tabPanelTemplateLabel - Re: asduiahdih
+
+    									$mailpreview_tabs.tabs("add", '#' + tabPanelTemplateId, tabPanelTemplateLabel)
+    									.find('.message.empty-container').hide().end()
+    									.find('#' + tabPanelTemplateId).html(onceOpenedMessages[selectedFolder.id][message.msg_number].body)
+    									.prepend(
+    										'<div class="mailpreview-message-info">' + 
+    											get_lang('Subject') + ': ' +
+    											html_entities(onceOpenedMessages[selectedFolder.id][message.msg_number].subject) + 
+    										'</div>'
+    									)
+    									.find('[class^="ExpressoCssWrapper"]').addClass("mailpreview-message-body");
+    								} else {
+    									$mailpreview_tabs.tabs('select', '#' + tabPanelTemplateId)
+    									.find('#' + tabPanelTemplateId + ', [href="#' + tabPanelTemplateId + '"]').removeClass('preview-message-unselected');
+    								}
+    							}
+    						});
+                        }      
 					}
 				} else {
Index: /trunk/expressoMail1_2/setup/phpgw_pt-br.lang
===================================================================
--- /trunk/expressoMail1_2/setup/phpgw_pt-br.lang	(revision 7892)
+++ /trunk/expressoMail1_2/setup/phpgw_pt-br.lang	(revision 7907)
@@ -972,4 +972,5 @@
 MailArchiver user logged out	expressoMail1_2	pt-br	Usuário desconectado do MailArchiver
 Error trying to send the message. Retry in a few seconds...	expressoMail1_2	pt-br	Erro ao tentar enviar a mensagem. Nova tentativa em alguns segundos...
+Create filter from message	expressoMail1_2	pt-br	Criar filtro a partir da mensagem
 Sending the message...	expressoMail1_2	pt-br	Enviando a mensagem...
-Create filter from message	expressoMail1_2	pt-br	Criar filtro a partir da mensagem 
+Please, Wait the messages from archieve be ready.	expressoMail1_2	pt-br	Por favor, Aguarde as mensagens arquivadas ficarem prontas.
Index: /trunk/expressoMail1_2/inc/class.imap_functions.inc.php
===================================================================
--- /trunk/expressoMail1_2/inc/class.imap_functions.inc.php	(revision 7902)
+++ /trunk/expressoMail1_2/inc/class.imap_functions.inc.php	(revision 7907)
@@ -2174,8 +2174,9 @@
 	function delete_msgs($params)
 	{
-
 		$folder = $params['folder'];
 		$folder =  mb_convert_encoding($folder, "UTF7-IMAP","ISO-8859-1");
+
 		$msgs_number = explode(",",$params['msgs_number']);
+
 		if(array_key_exists('border_ID' ,$params))
 		$border_ID = $params['border_ID'];
@@ -2193,5 +2194,7 @@
 	 	$mbox_stream = @imap_open("{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$folder, $this->username, $this->password) or die(serialize(array('imap_error' => $this->parse_error(imap_last_error()))));
 
-		foreach ($msgs_number as $msg_number)
+        
+
+        foreach ($msgs_number as $msg_number)
 		{
 			if (imap_delete($mbox_stream, $msg_number, FT_UID));
@@ -2681,5 +2684,22 @@
 		return $return;
 	}
-	
+
+    function get_info_msg_archiver($params){
+         $folder = "INBOX/Trash";
+         $mbox_stream = $this->open_mbox($folder);
+
+        foreach($params['idMsgs'] as $i => $id){
+            $name = imap_headerinfo($mbox_stream, imap_msgno($mbox_stream ,$id));
+            $return[] =  array(
+                'uid' => $id,
+                'folder' => "archiver",
+                'type' => "imapMSG",
+                'name' => base64_encode($name->subject.".eml")
+            );
+        }
+        
+        return json_encode($return);
+    }
+
 	function send_mail($params) {
             require_once dirname(__FILE__) . '/../../services/class.servicelocator.php';
@@ -2752,4 +2772,7 @@
             $encrypt = $params['input_return_cripto'];
             $signed = $params['input_return_digital'];
+
+
+            //$params['attachments'] = $params['attachments']['imap'];
 
 			$params['attachments'] = mb_convert_encoding($params['attachments'], "UTF7-IMAP","UTF-8, ISO-8859-1, UTF7-IMAP");
@@ -2904,5 +2927,5 @@
 					$arr_new_folder['base_path'] = $base_path;
 
-					$this->create_mailbox($arr_new_folder);					
+					$this->create_mailbox($arr_new_folder);	
 					$has_new_folder = true;
                     $folder = $newfolder;
@@ -2953,4 +2976,5 @@
 
             $header = $this->get_header($msg_numb);
+
             $header_ = imap_fetchheader($this->mbox, $msg_numb, FT_UID);
             $pattern = '/^[ \t]*Disposition-Notification-To:.*/mi';
@@ -3055,6 +3079,8 @@
             foreach ($attachment as &$value) 
             {
+                /*Volta aqui*/
                 if((int)$value > 0) //BD attachment
                 {
+                    ob_start();
                      $att = Controller::read(array('id'=> $value , 'concept' => 'mailAttachment'));
 
@@ -3072,5 +3098,10 @@
                 else //message attachment
                 {
+
                     $value = json_decode($value, true);
+
+                    if($value["folder"] == "archiver"){
+                        $value['folder'] = "INBOX/Trash";
+                    }
 
                     switch ($value['type']) {
@@ -3080,5 +3111,5 @@
                                 if(strstr($body,'src="./inc/get_archive.php?msgFolder='.$value['folder'].'&msgNumber='.$value['uid'].'&indexPart='.$value['part'].'"') !== false)//Embeded IMG
                                 {    
-                                    $body = str_ireplace('src="./inc/get_archive.php?msgFolder='.$value['folder'].'&msgNumber='.$value['uid'].'&indexPart='.$value['part'].'"' , 'src="'.$att['name'].'"', $body);
+                                    $body = str_ireplace('src="./inc/get_archive.php?msgFolder='.$value['folder'].  '&msgNumber='.$value['uid'].'&indexPart='.$value['part'].'"' , 'src="'.$att['name'].'"', $body);
                                     $mailService->addStringImage($att['source'], $att['type'],mb_convert_encoding($att['name'], 'ISO-8859-1' , 'UTF-8,ISO-8859-1') );
                                 }
@@ -3091,7 +3122,10 @@
                             case 'imapMSG':
                                 $mbox_stream = $this->open_mbox(mb_convert_encoding($value['folder'] , 'ISO-8859-1' , 'UTF7-IMAP'));
+
                                 $rawmsg = $this->getRawHeader($value['uid']) . "\r\n\r\n" . $this->getRawBody($value['uid']);
                                 
                                 $mailService->addStringAttachment($rawmsg, mb_convert_encoding(base64_decode($value['name']), 'ISO-8859-1' , 'UTF-8,ISO-8859-1'), 'message/rfc822', '7bit', 'attachment' );
+                                /*envia o anexo para o email*/
+
                                 $message_size_total += mb_strlen($rawmsg); //Adiciona o tamanho do anexo a variavel que controlao tamanho da msg.
                                 unset($rawmsg);
@@ -3176,4 +3210,6 @@
             {
                 $this->rfc2397ToEmbeddedAttachment($mailService , $body);
+                
+
 
                 $defaultStyle = '';
@@ -4863,8 +4899,13 @@
         $error = array();
 
+
+
         foreach($sources as $index=>$src)
         {
             if($src!="")
             {
+                    
+                
+
                 //If it is a MailArchiver incomming data
                 if($params['madata'])
@@ -4878,4 +4919,7 @@
 				$insert = $this->insert_email($source,$dest_folder,$timestamps[$index],$flags[$index]);
 
+                //volta aqui
+                $return['idsMsg'] = $insert['msg_no'];
+
                 if($insert['error'])
                 {
@@ -4884,4 +4928,5 @@
                 else 
                 {
+                    // volta aqui
                     $archived[] = $ids[$index];
                 }
Index: /trunk/expressoMail1_2/js/mail_archiver.js
===================================================================
--- /trunk/expressoMail1_2/js/mail_archiver.js	(revision 7685)
+++ /trunk/expressoMail1_2/js/mail_archiver.js	(revision 7907)
@@ -575,19 +575,11 @@
 }
 
-
-
-
-/**
- *Unarchieve Message
- *
- *@author Cassiano Dal Pizzol [cassiano.dalpizzol@serpro.gov.br]
- *
- *@param folder Original Folder of the message
- *@param new_folder The new folder of the message
- *@param msgs_number id of the messages
- */
-MailArchiver.prototype.unarchieve = function (folder, new_folder, msgs_number){
-    try{ 
-        write_msg(get_lang("Starting to unarchive messages"));
+MailArchiver.prototype.unarchieveToAttach = function (folder, new_folder, msgs_number){
+    try{
+
+        if(typeof(expresso_mail_archive.idMsgsToAttach) == "undefined"){
+            expresso_mail_archive.idMsgsToAttach = new Array();
+        }
+        //write_msg(get_lang("Starting to unarchive messages"));
         expresso_mail_archive.isArchiveOperation = true;
         if(currentTab.toString().indexOf("_r") != -1){
@@ -599,7 +591,8 @@
                 
         if (parseInt(msgs_number) > 0 || msgs_number.length > 0){       
-            expresso_mail_archive.message_list = new Array();
-            expresso_mail_archive.CreateMessageList(msgs_number);
-            if((expresso_mail_archive.message_list.length > 0) && (expresso_mail_archive.message_list[0] != '')) {
+           
+            expresso_mail_archive.messageToAttach = msgs_number;
+            if(expresso_mail_archive.messageToAttach) {
+                
                 expresso_mail_archive.unarchivecounter = 0;
                 expresso_mail_archive.unarchive_error_counter=0;
@@ -608,5 +601,5 @@
                 (new_folder != null)?expresso_mail_archive.unarchievenewfolder = new_folder:expresso_mail_archive.unarchievenewfolder='INBOX';
                 
-                expresso_mail_archive.unarchieveHandler();
+                expresso_mail_archive.unarchieveToAttachHandler();
                 
                 if(currentTab.toString().indexOf("_r") != -1){
@@ -628,14 +621,7 @@
 }
 
-/**
- *
- *Unarchieve Message Handler
- *
- *@author Cassiano Dal Pizzol [cassiano.dalpizzol@serpro.gov.br]
- *
- **/
-MailArchiver.prototype.unarchieveHandler = function(){
-    try{
-        var email = mail_archive_protocol+'://'+mail_archive_host+':'+mail_archive_port+'/mail/' + expresso_mail_archive.session.id +'/'+ expresso_mail_archive.folder.path + '/'+ expresso_mail_archive.message_list[expresso_mail_archive.unarchivecounter] + '.eml';    
+MailArchiver.prototype.unarchieveToAttachHandler = function(){
+    try{
+        var email = mail_archive_protocol+'://'+mail_archive_host+':'+mail_archive_port+'/mail/' + expresso_mail_archive.session.id +'/'+ expresso_mail_archive.folder.path + '/'+ expresso_mail_archive.messageToAttach + '.eml';    
     
         //Creates a new object to unarchive messages. It's a CXF Add-on CORS component
@@ -647,5 +633,5 @@
             for (var w=0; w < expresso_mail_archive.allcompletemessagesbyfolder.length; w++){
                                 
-                if(expresso_mail_archive.allcompletemessagesbyfolder[w]["msg_number"] == expresso_mail_archive.message_list[expresso_mail_archive.unarchivecounter]){
+                if(expresso_mail_archive.allcompletemessagesbyfolder[w]["msg_number"] == expresso_mail_archive.messageToAttach){
                     var timestamp = expresso_mail_archive.allcompletemessagesbyfolder[w]["timestamp"];
                     
@@ -702,4 +688,182 @@
                 }
             }
+            var id = expresso_mail_archive.messageToAttach;
+            var source =  encodeURIComponent(UnarchiveReqHandler.handler.responseText) + "#@#@#@";
+            var params = 
+            "&folder="      + escape(expresso_mail_archive.unarchievenewfolder) +
+            "&source="      + source + 
+            "&timestamp="   + timestamp + 
+            "&madata=true"  + 
+            "&flags="       + flags +
+            "&id="          + id;
+
+
+            var handler_unarchive = function(data){
+                expresso_mail_archive.unarchieveToAttachController(data);
+            }
+            write_msg(get_lang("Please, Wait the messages from archieve be ready."));
+            
+             $.ajax({
+                url: "controller.php?action=$this.imap_functions.unarchive_mail",
+                success: function(data){
+                    data = connector.unserialize(data);
+                    expresso_mail_archive.idMsgsToAttach.push(data.idsMsg);
+                    handler_unarchive(data);
+                },
+                async: false,
+                data:  params,
+                type: 'POST',
+                
+            });
+
+        }
+
+        
+        UnarchiveReqHandler.handler.open("GET", email, true);
+        if(UnarchiveReqHandler.handler.overrideMimeType){
+            UnarchiveReqHandler.handler.overrideMimeType("message/rfc822; charset=windows-1252"); 
+        }
+        UnarchiveReqHandler.handler.send();
+    }
+    catch(e){
+        write_msg(get_lang('Unarchive error: ' + e));
+    }
+}
+
+MailArchiver.prototype.unarchieveToAttachController = function(data){
+    
+    if (data){
+        if (data.error != "") {
+            expresso_mail_archive.unarchive_error_counter++;
+        }
+        
+    }
+}
+
+
+/**
+ *Unarchieve Message
+ *
+ *@author Cassiano Dal Pizzol [cassiano.dalpizzol@serpro.gov.br]
+ *
+ *@param folder Original Folder of the message
+ *@param new_folder The new folder of the message
+ *@param msgs_number id of the messages
+ */
+MailArchiver.prototype.unarchieve = function (folder, new_folder, msgs_number){
+    try{ 
+        write_msg(get_lang("Starting to unarchive messages"));
+        expresso_mail_archive.isArchiveOperation = true;
+        if(currentTab.toString().indexOf("_r") != -1){
+            msgs_number = currentTab.toString().substr(0,currentTab.toString().indexOf("_r"));
+        }
+
+        if(!msgs_number)
+            msgs_number = get_selected_messages();        
+                
+        if (parseInt(msgs_number) > 0 || msgs_number.length > 0){       
+            expresso_mail_archive.message_list = new Array();
+            expresso_mail_archive.CreateMessageList(msgs_number);
+            if((expresso_mail_archive.message_list.length > 0) && (expresso_mail_archive.message_list[0] != '')) {
+                expresso_mail_archive.unarchivecounter = 0;
+                expresso_mail_archive.unarchive_error_counter=0;
+                expresso_mail_archive.getFolderInfo(folder.replace("local_messages_",""));
+                expresso_mail_archive.unarchievefolder = expresso_mail_archive.folder.name;
+                (new_folder != null)?expresso_mail_archive.unarchievenewfolder = new_folder:expresso_mail_archive.unarchievenewfolder='INBOX';
+                
+                expresso_mail_archive.unarchieveHandler();
+                
+                if(currentTab.toString().indexOf("_r") != -1){
+                    delete_border(currentTab,'false');  
+                }
+            }
+            else{
+                write_msg(get_lang('No selected message.'));
+            }
+        }                               
+        else
+            write_msg(get_lang('No selected message.'));
+        
+        clear_selected_messages();
+    }
+    catch (e){
+        write_msg(get_lang('Unarchive error: ' + e));
+    }
+}
+
+/**
+ *
+ *Unarchieve Message Handler
+ *
+ *@author Cassiano Dal Pizzol [cassiano.dalpizzol@serpro.gov.br]
+ *
+ **/
+MailArchiver.prototype.unarchieveHandler = function(){
+    try{
+        var email = mail_archive_protocol+'://'+mail_archive_host+':'+mail_archive_port+'/mail/' + expresso_mail_archive.session.id +'/'+ expresso_mail_archive.folder.path + '/'+ expresso_mail_archive.message_list[expresso_mail_archive.unarchivecounter] + '.eml';    
+    
+        //Creates a new object to unarchive messages. It's a CXF Add-on CORS component
+        var UnarchiveReqHandler = new cxf_cors_request_object();
+        UnarchiveReqHandler.init();
+
+        //Both XDomainRequest and XMLHttpRequest L2 supports onload event
+        UnarchiveReqHandler.handler.onload = function(){            
+            for (var w=0; w < expresso_mail_archive.allcompletemessagesbyfolder.length; w++){
+                                
+                if(expresso_mail_archive.allcompletemessagesbyfolder[w]["msg_number"] == expresso_mail_archive.message_list[expresso_mail_archive.unarchivecounter]){
+                    var timestamp = expresso_mail_archive.allcompletemessagesbyfolder[w]["timestamp"];
+                    
+                    //Get local tagged message data
+                    var flags = new String("");
+                    
+                    //Forwarded is special one: marks as "answered" and "draft"
+                    if(expresso_mail_archive.allcompletemessagesbyfolder[w]["Forwarded"]){
+                        if(expresso_mail_archive.allcompletemessagesbyfolder[w]["Forwarded"] == 'F')
+                            flags += 'A:X'+':';                                  
+                    }
+                    else{
+                        //Answered tag
+                        if(expresso_mail_archive.allcompletemessagesbyfolder[w]["Answered"])
+                            if(expresso_mail_archive.allcompletemessagesbyfolder[w]["Answered"] == 'A')
+                                flags += 'A'+':';
+                            else
+                                flags += ':';
+                        else
+                            flags += ':';                    
+
+                        //Draft tag
+                        if(expresso_mail_archive.allcompletemessagesbyfolder[w]["Draft"])
+                            if(expresso_mail_archive.allcompletemessagesbyfolder[w]["Draft"] == 'X')
+                                flags += 'D'+':';                    
+                            else
+                                flags += ':';
+                        else
+                            flags += ':';
+                    }
+                    
+                    //Flagged tag
+                    if(expresso_mail_archive.allcompletemessagesbyfolder[w]["Flagged"])
+                        if(expresso_mail_archive.allcompletemessagesbyfolder[w]["Flagged"] == 'F')
+                            flags += 'F'+':';                                        
+                        else
+                            flags += ':';
+                    else
+                        flags += ':';
+                    
+                    //Unseen tag
+                    if(expresso_mail_archive.allcompletemessagesbyfolder[w]["Unseen"])
+                        if(expresso_mail_archive.allcompletemessagesbyfolder[w]["Unseen"] == 'U')
+                            flags += 'U';     
+                        else
+                            flags += '';
+                    else
+                        flags += '';
+                    
+                    //Imap tag hash id
+                    flags += "#@#@#@";                    
+                    
+                    break;
+                }
+            }
             var id = expresso_mail_archive.message_list[expresso_mail_archive.unarchivecounter];
             var source =  encodeURIComponent(UnarchiveReqHandler.handler.responseText) + "#@#@#@";
@@ -717,5 +881,18 @@
             write_msg(get_lang('Unarchiving message %1 of %2', (expresso_mail_archive.unarchivecounter + 1), expresso_mail_archive.message_list.length));
             
-            cExecute ("$this.imap_functions.unarchive_mail&", handler_unarchive, params);
+            //cExecute ("$this.imap_functions.unarchive_mail&", handler_unarchive, params);
+
+            $.ajax({
+                url: "controller.php?action=$this.imap_functions.unarchive_mail",
+                data:  params,
+                type: 'POST',
+                async: false,
+                success: function(data){
+                    handler_unarchive(connector.unserialize(data));
+                },
+            });
+
+
+
         }
         
@@ -1398,4 +1575,47 @@
 }
 
+
+MailArchiver.prototype.getMessagesByFolder = function(folderid, searchType){
+    try{
+        if(searchType == "ALL")
+            var query_messages = '{"query":{"folder":[{"@id":"'+folderid+'"}], "order":[{"@asc":"date"}]}}';
+        else
+            var query_messages = '{"query":{"folder":[{"@id":"'+folderid+'"}], "tags":[{"@contains":"'+searchType+'"}], "order":[{"@asc":"date"}]}}';
+        ArchiveServices.listMessages(expresso_mail_archive.getMessagesByFolderOperationOK, expresso_mail_archive.getMessagesByFolderOperationFailure, expresso_mail_archive.session.id, query_messages);
+    }
+    catch (e){
+        expresso_mail_archive.getFaultInfo();
+    }
+}
+
+MailArchiver.prototype.getMessagesByFolderOperationOK = function(returnService){
+    var msglist = new Array();
+    var msglistcomplete = new Array();
+    var msgAll = new Array();
+    for(var i=0; i< returnService.getReturn().length; i++){
+        //Array montado apenas com ids para tratamento de seleÃ§Ã£o de mensagens independente de paginaÃ§Ã£o
+        msglist.push(returnService.getReturn()[i]._id);
+
+        msgAll.push(returnService.getReturn()[i]);
+
+        //Incremento de contadores para atualizaÃ§Ã£o da aba de listagem
+        if(returnService.getReturn()[i]._tags.indexOf("unseen") != -1){
+            expresso_mail_archive.tot_unseen_msgs_tab++;
+        }
+        expresso_mail_archive.tot_msgs_tab++;
+        //Array montado para operaÃ§Ã£o de desarquivamento
+        var ExpSerialized = expresso_mail_archive.pattern.toExpressoHeader(returnService.getReturn()[i]);
+        msglistcomplete.push(connector.unserialize(ExpSerialized));
+    }
+    expresso_mail_archive.allmessagesbyfolder = msglist;
+    expresso_mail_archive.allcompletemessagesbyfolder = msglistcomplete;
+    expresso_mail_archive.msgAll = msgAll;
+}
+
+MailArchiver.prototype.getMessagesByFolderOperationFailure = function(ServiceFault){
+    window.alert('listAllmessagesByFolder FALHOU!\n' + ServiceFault.getReturn());
+}
+
+
 //List all messages by folder given and set a array with all messages ids
 MailArchiver.prototype.listAllMessagesByFolder = function(folderid, searchType){
@@ -1515,4 +1735,5 @@
     if(msgfound){
         expresso_mail_archive.currentheaders = headerMsg;
+        expresso_mail_archive.subjectPreview = headerMsg.subject;
         return(headerMsg);
     }
@@ -1537,4 +1758,5 @@
             bodies.push(temp);
         }
+        expresso_mail_archive.bodyPreview = temp.getReturn();
         return bodies;
     }
@@ -1542,4 +1764,10 @@
         expresso_mail_archive.getFaultInfo();
     }
+}
+
+
+MailArchiver.prototype.getPreviewToAttach = function(id){
+    expresso_mail_archive.getMessageInfo(id);
+    expresso_mail_archive.getMessageBodies([id]);
 }
 
@@ -1618,4 +1846,5 @@
         return;
     }    
+    expresso_mail_archive.te = returnService.getReturn();
     var msgBody = returnService.getReturn();
     //var msgHeaders = expresso_mail_archive.getMessageHeaders(expresso_mail_archive.currentmessage);
@@ -2092,4 +2321,5 @@
         expresso_mail_archive.messageslisted.push(msgitem2);    
         expresso_mail_archive.getMessageHeaders(serviceReturn.getReturn().getId());
+
     }
     else{
Index: /trunk/expressoMail1_2/js/abas.js
===================================================================
--- /trunk/expressoMail1_2/js/abas.js	(revision 7889)
+++ /trunk/expressoMail1_2/js/abas.js	(revision 7907)
@@ -708,5 +708,28 @@
 function listAttachment(ID)
 {
-   return (typeof(msgAttachments[ID]) == 'undefined') ? '' : JSON.stringify(msgAttachments[ID]); 
-}
-
+    var imap     = new Array();
+    var archiver = new Array();
+    
+    if(typeof msgAttachments[ID] == "undefined"){
+        return "";
+    }
+
+    $.each(msgAttachments[ID], function(i, each){
+       
+         if(typeof(each) == "undefined")  return true;
+        
+       if($.parseJSON(each).folder.indexOf("local_messages_") != -1){
+            archiver.push($.parseJSON(each));
+       } else {
+            imap.push(each);
+       }
+    });
+
+    context = {
+        "imap" : imap,
+        "archiver" : archiver
+    };
+
+   return (typeof(msgAttachments[ID]) == 'undefined') ? '' : context;
+}
+
Index: /trunk/expressoMail1_2/js/main.js
===================================================================
--- /trunk/expressoMail1_2/js/main.js	(revision 7899)
+++ /trunk/expressoMail1_2/js/main.js	(revision 7907)
@@ -1027,6 +1027,6 @@
 				
  		        var userTrashFolder = ''; 
- 		       
- 		        if (arguments.length <= 6) show_success_msg = true; 
+
+ 		        if (arguments.length <= 6 && typeof(show_success_msg) == "undefined") show_success_msg = true; 
  		        if (folder == 'null') folder = current_folder; 
  		 
@@ -1164,4 +1164,5 @@
 		params_to_delete += "&search_box_type="+search_box_type;
 		params_to_delete += "&sort_box_reverse="+sort_box_reverse;
+
 		cExecute ("$this.imap_functions.delete_msgs", handler_delete_msgs, params_to_delete);
 	}
@@ -3533,36 +3534,107 @@
 		mailData.input_from = $(content).find('select[name="input_from"]').val();
 
-
-	if(stringEmail != ""){
-		$.ajax({
-			url: "controller.php?action=$this.imap_functions.send_mail",
-            data:  mailData,
-            type: 'POST',
-
-            beforeSend: function(jqXHR, settings){
-
-                write_msg( get_lang( 'Sending the message...' ) );
-                $(content).find('button.send').button('option', 'disabled', true);
-
-
-            },
-            success: function(data){
-                send_message_return(connector.unserialize(data),ID);
-			},
-			error: function(){
-				write_msg(get_lang( 'Error trying to send the message. Retry in a few seconds...' ) );
-                $(content).find('button.send').button('option', 'disabled', false);
-                var interval = setInterval(function(){
-						send_valided_message(ID,folder,folder_name);
-						clearInterval(interval);
-				},15000);
-				return;
-			}
-		});
-	}else{
-		write_msg(get_lang("message without receiver"));
-		return;
-	}
-
+    // VERIFY IF EXISTS MESSAGE TO ATTACH
+    if(typeof mailData.attachments == "object"){
+
+        // VERIFY IF EXISTS MESSAGE OF ARCHIVE
+        if(mailData.attachments.archiver.length){
+
+            // CREATE ONE VARIABLE TO STORE ALL THE MESSAGES INFORMATION
+            var archiver = new Array();
+
+            // UNARCHIEVE ALL THE MESSAGES TO IMAP TRASH
+           $.each(mailData.attachments.archiver, function(i, each){
+             expresso_mail_archive.unarchieveToAttach(each.folder,"INBOX/Trash",each.uid);
+           });
+
+            // FIX THE PROBLEM WITH ASYNC
+            // noReady is calling always that the variable is not complete with all the messages ids
+            notReady = function(){
+                setTimeout(function(){
+                if(mailData.attachments.archiver.length == expresso_mail_archive.idMsgsToAttach.length){
+                    // THIS FUNCTION IS FOR TO GET THE INFORMATION OF THE MESSAGE NEWLY UNARCHIVED
+                    readyToFetch();
+                    // THIS FUNCTION IS FOR TO SEND THE MESSAGE WITH ATTACHMENT
+                    readyToSend();
+                } else {
+                    // IF THE ARRAY DON'T HAVE ALL THE MESSAGES IDS, OKAY, NO PROBLEM... CALL THIS FUNCTION AGAIN!
+                    noReady();
+                }
+              },30);
+            };
+            notReady();
+
+             // THIS FUNCTION IS FOR TO GET THE INFORMATION OF THE MESSAGE NEWLY UNARCHIVED
+             readyToFetch = function(){
+                 $.ajax({
+                        url: "controller.php?action=$this.imap_functions.get_info_msg_archiver",
+                        data:  {"idMsgs":expresso_mail_archive.idMsgsToAttach},
+                        type: 'POST',
+                        async: false,
+                        success: function(data){
+                            data = connector.unserialize(data);
+                            archiver.push(data);
+                        },
+                  });
+
+                // HERE, THE MESSAGES IMAP ARE READY FOR TO SEND...
+                mailData.attachments = mailData.attachments.imap;
+
+                // BUT, I NEED TO PREPARE THE MESSAGE ARCHIVE FOR TO SEND.
+                archiver = $.parseJSON(archiver[0]);
+                if(archiver.length){
+                    $.each(archiver, function(i, each){
+                        mailData.attachments.push(JSON.stringify(archiver[i]));
+                    });
+                }
+
+                // GOOD, NOW THE ATTACHMENTS ARE READY TO SEND!
+                mailData.attachments = JSON.stringify(mailData.attachments);
+            };
+        } else {
+            // IF THIS MESSAGE JUST HAVE IMAP MESSAGES
+            mailData.attachments = JSON.stringify(mailData.attachments.imap);
+            setTimeout(function(){ readyToSend() }, 30);
+        }
+    } else {
+        // IF THIS MESSAGE DON'T HAVE ATTACHMENT, CALL READYTOSEND.
+        setTimeout(function(){ readyToSend() }, 30);
+        mailData.attachments = [];
+    }
+
+    // THIS FUNCTION IS FOR TO SEND THE MESSAGE WITH ATTACHMENT OR NOT.
+    readyToSend = function(){
+    
+    	if(stringEmail != ""){
+    		$.ajax({
+    			url: "controller.php?action=$this.imap_functions.send_mail",
+                data:  mailData,
+                type: 'POST',
+                async: false,
+                beforeSend: function(jqXHR, settings){
+                    write_msg( get_lang( 'Sending the message...' ) );
+                    $(content).find('button.send').button('option', 'disabled', true);
+                },
+                success: function(data){
+                    send_message_return(connector.unserialize(data),ID);
+                    // HERE, I NEED TO DELETE THE MESSAGES THAT WERE UNARCHIVE FROM ARCHIVE.
+                    delete_msgs("INBOX/Trash",expresso_mail_archive.idMsgsToAttach, false, false);
+    			},
+    			error: function(){
+    				write_msg(get_lang( 'Error trying to send the message. Retry in a few seconds...' ) );
+                    $(content).find('button.send').button('option', 'disabled', false);
+                    var interval = setInterval(function(){
+    						send_valided_message(ID,folder,folder_name);
+    						clearInterval(interval);
+    				},15000);
+    				return;
+    			}
+    		});
+    	}else{
+    		write_msg(get_lang("message without receiver"));
+    		return;
+    	}
+        delete(expresso_mail_archive.idMsgsToAttach);
+    };
 
 }
Index: /trunk/expressoMail1_2/js/draw_api.js
===================================================================
--- /trunk/expressoMail1_2/js/draw_api.js	(revision 7899)
+++ /trunk/expressoMail1_2/js/draw_api.js	(revision 7907)
@@ -4765,10 +4765,10 @@
     att.uid = message_number; 
     att.type = 'imapMSG'; 
-    att.name = Base64.encode(onceOpenedHeadersMessages[folder_name][message_number].subject + '.eml'); 
+    att.name = Base64.encode(onceOpenedMessages[folder_name][message_number].subject + '.eml'); 
     var idATT = JSON.stringify(att); 
     addAttachment(ID, idATT); 
     var attach = {}; 
-    attach.fileName = onceOpenedHeadersMessages[folder_name][message_number].subject + '.eml'; 
-    attach.fullFileName = onceOpenedHeadersMessages[folder_name][message_number].subject + '.eml'; 
+    attach.fileName = onceOpenedMessages[folder_name][message_number].subject + '.eml'; 
+    attach.fullFileName = onceOpenedMessages[folder_name][message_number].subject + '.eml'; 
     if(attach.fileName.length > 20)  
     { 
@@ -4778,5 +4778,5 @@
     attach.error = false; 
     attach.OK = true; 
-    attach.fileSize = formatBytes(onceOpenedHeadersMessages[folder_name][message_number].Size); 
+    attach.fileSize = formatBytes(onceOpenedMessages[folder_name][message_number].size); 
     var upload = $(DataLayer.render("../prototype/modules/mail/templates/attachment_add_itemlist.ejs", { 
         file: attach 
