Index: branches/2.5/prototype/modules/attach_message/attach_message.js
===================================================================
--- branches/2.5/prototype/modules/attach_message/attach_message.js	(revision 7543)
+++ branches/2.5/prototype/modules/attach_message/attach_message.js	(revision 8232)
@@ -216,5 +216,5 @@
 		for (var message in selectedMessages[folder]) {
 			if (selectedMessages[folder][message]) {
-				byte_size += parseInt(onceOpenedMessages[folder][message].size);
+				byte_size += parseInt(onceOpenedHeadersMessages[folder][message].size);
 				total_messages++;
 			}
@@ -227,8 +227,30 @@
 var msgAttacherGrid = $("#message_attacher_grid"), msgsTotal = $("#selected_messages_number");
 var lastLoadedMessages = [];
-var onceOpenedMessages = [];
 var selectedMessages   = {};
 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,6 +276,42 @@
 	
     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;
+}
+
+function archive_flag_search( flagObj ){
+    var flags = {};
+    var returns = '';
+
+    flagObj = flagObj.split("");
+    $.each( flagObj , function(i, flag){
+        flags[ flag ] = true;
+    });
+
+    returns += (flags['U'] ? '1,' : '0,') ;
+    returns += (flags['A'] && !flags['X'] ? '1,' : '0,') ;
+    returns += (flags['X'] ? '1,' : '0,') ;
+    returns += (flags['F'] ? '1,' : '0,') ;
+    returns += '0,0';
+            
+    return returns;
+}
+
 
 $mailpreview_tabs_label_length = 15;
@@ -271,4 +329,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 +361,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 +371,5 @@
 		.find("#foldertree").treeview()
 		.click(function(event){
+
 			//request new selected folder messages
 			var target = $(event.target);
@@ -325,14 +398,56 @@
 			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'), 
@@ -360,5 +475,46 @@
 			],
 			jsonReader : {
-				  root:"rows",
+				  root: function(obj){
+				  	obj['data'] = {};
+		            obj.data = {rows : obj.rows};
+				  	if(obj.rows){
+				  		if(!obj.rows[0].flag){
+					  		var msgs = [];
+						  	$.each(obj.rows, function(i, msg){
+								flag = msg['flags'];
+		                        id = msg['msg_number'];
+		                        var message = {};
+		                     
+		                        message['msg_number'] = id;
+		                        message['flags'] = flag;
+		                        message['to'] = {
+		                                name: msg['toaddress2'],
+		                                email: msg['toaddress2']
+		                        };
+		
+		                        if(msg['from'] != undefined &&  msg['header']['from'] != undefined){
+		                                message['from'] = {
+		                                        'email' : msg['from']['email'],
+		                                        'name' : msg['header']['from']['name']
+		                                }
+		                            }else{
+		                                message['from'] = {
+		                                        'email' : '',
+		                                        'name' : 'Rascunho'
+		                                }
+		                            }
+		                        //message['from']['name'] = msg['from']['name'];
+		                        message['subject'] = msg['subject'] ? msg['subject'] : "(sem assunto)";
+		                        message['timestamp'] = parseInt(msg['timestamp']);
+		                        message['size'] = msg['size'];
+		                        message['id'] = id;
+		                        msgs.push( message );
+			                });
+							obj['data'] = {};
+			                obj.data = {rows : msgs};
+			            }
+	                }
+				  	return obj.data.rows;
+				  },
 				  page: "page",
 				  total: "total",
@@ -367,4 +523,5 @@
 				  id: "0"
 			},
+			hidegrid:false,
 			rowNum:10,
 			rowList:[10,25,50],
@@ -377,5 +534,6 @@
 			loadComplete: function(data) {
 				lastLoadedMessages = data.rows;
-				
+				$("#mailgrid-container").find(".loading").hide();
+
 				// aplica o contador
 				jQuery('.timable').each(function (i) {
@@ -401,119 +559,362 @@
 				
 			},
-			onSelectRow: function (id, selected) {
-				var message = false;
-				for (var i=0; i<lastLoadedMessages.length; i++){
-					if (lastLoadedMessages[i].msg_number == id) {
-						message = lastLoadedMessages[i];
-						break;
-					}
-				}
-				
-				var tabPanelTemplateId = 'mailpreview_tab_' + selectedFolder.id.replace(/[.\/]/g, '_') + '_' + message.msg_number;
-				var tabPanelTemplateId = tabPanelTemplateId.replace(/[\s\/]/g, '-'); 
-				
-				if (selected) {	
-					if (onceOpenedMessages[selectedFolder.id] && onceOpenedMessages[selectedFolder.id][message.msg_number]) {
-						if (!selectedMessages[selectedFolder.id])
-							selectedMessages[selectedFolder.id] = {};
-							
-						selectedMessages[selectedFolder.id][message.msg_number] = true;
-						$('#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) + '...';
-						
-						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);
-						} else {
-							$mailpreview_tabs.tabs('select', '#' + tabPanelTemplateId)
-							.find('#' + tabPanelTemplateId + ', [href="#' + tabPanelTemplateId + '"]').removeClass('preview-message-unselected');
-						}
-						
-					} else {
-						jQuery('#mailpreview_container').block({  
-							message: '<div id="loading-content"><div class="image"></div></div>',  
-							css: {  
-								backgroundImage: 'url('+BASE_PATH+'modules/attach_message/images/loading.gif)',  
-								backgroundRepeat: 'no-repeat', 
-								backgroundPosition: 'center', 
-								backgroundColor: 'transparent', 
-								width: '32px', 
-								height: '32px', 
-								border:'none'  
-							}, 
-							overlayCSS: {  
-								backgroundColor: '#CCC',  
-								opacity:         0.5 
-							}  
-						}); 
-
-						var offlineCase = "";
-						
-						if( !selectedFolder.id.indexOf( 'local_messages/' ) )
-						    offlineCase = ":offline";
-					  
-						if (!selectedMessages[selectedFolder.id])
-							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');
-								}
-							}
-						});
-					}
-				} else {
-					/**
-					 * if you wants to remove tab on unselect message,
-					 * but still needs to uselect message on remove tab.
-					 * 
-					 */
-					/*
-					if ($('#' + tabPanelTemplateId).length) {
-						$mailpreview_tabs.tabs('remove', '#' + tabPanelTemplateId);
-					}
-					 */
-					selectedMessages[selectedFolder.id][message.msg_number] = false;
-					$mailpreview_tabs.find('#' + tabPanelTemplateId + ', [href="#' + tabPanelTemplateId + '"]').addClass('preview-message-unselected');
-				}
-				
-				if (onceOpenedMessages[selectedFolder.id] && onceOpenedMessages[selectedFolder.id][message.msg_number])
-					selectedMessagesCount();
-			},
+            onSelectRow: function(id, selected)
+            {
+                /* Funções auxiliares:*/
+
+                /*
+                    Marca a mensagem como selecionada no grid de anexar mensagena.
+                    Parâmetros:
+                        folder: folder em que a mensagem a ser selecionada se encontra.
+                        msg_number: id da mensagem a ser selecionada.
+                */
+                var mark_as_selected = function (folder, msg_number) {
+                    if(!selectedMessages[folder])
+                    {
+                        selectedMessages[folder] = {};
+                    }
+                    selectedMessages[folder][msg_number] = true;
+                }
+
+                /*
+                    Adiciona uma mensagem ao cache de mensagens.
+                        cache: vetor de cache de mensagens.
+                        msg: mensagem a ser armazenada.
+                */
+                var add_msg_to_cache = function (cache, msg) {
+                    if(!cache[selectedFolder.id])
+                    {
+                        cache[selectedFolder.id] = {};
+                    }
+                    cache[selectedFolder.id][msg.msg_number] = msg;
+                }
+
+                /*
+                    Adiciona uma aba de preview para cada mensagem selecionada.
+                        subject: assunto da mensagem.
+                        body: corpo da mensagem.
+                */
+                var add_preview_tab = function (subject, body) {
+                    // Trunca o assunto, para caber na aba de preview:
+                    var tabPanelTemplateLabel = html_entities(subject);
+                    if(tabPanelTemplateLabel.length > $mailpreview_tabs_label_length + 3)
+                    {
+                        tabPanelTemplateLabel = tabPanelTemplateLabel.substring(0, $mailpreview_tabs_label_length) + '...';
+                    }
+
+                    // Se a aba não tiver sido adicionada:
+                    if(!$('#' + tabPanelTemplateId).length)
+                    {
+                        // adiciona-a:
+                        $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
+                    {
+                        // Senão, só a seleciona:
+                        $mailpreview_tabs
+                        .tabs('select', '#' + tabPanelTemplateId)
+                        .find('#' + tabPanelTemplateId + ', [href="#' + tabPanelTemplateId + '"]')
+                        .removeClass('preview-message-unselected');
+                    }
+                }
+
+                var message = false;
+                for(var i = 0; i < lastLoadedMessages.length; i++)
+                {
+                    if(lastLoadedMessages[i].msg_number == id)
+                    {
+                        message = lastLoadedMessages[i];
+                        break;
+                    }
+                }
+                var tabPanelTemplateId = 'mailpreview_tab_' + selectedFolder.id.replace(/[.\/]/g, '_') + '_' + message.msg_number;
+                var tabPanelTemplateId = tabPanelTemplateId.replace(/[\s\/]/g, '-');
+
+                if(selected)
+                {
+                    // Se a já mensagem (com preview) já estiver no cache:
+                    if(onceOpenedHeadersMessages[selectedFolder.id] && onceOpenedHeadersMessages[selectedFolder.id][message.msg_number]  && onceOpenedHeadersMessages[selectedFolder.id][message.msg_number].body)
+                    {
+
+                        mark_as_selected(selectedFolder.id, message.msg_number);
+
+                        add_preview_tab(
+                            onceOpenedHeadersMessages[selectedFolder.id][message.msg_number].subject,
+                            onceOpenedHeadersMessages[selectedFolder.id][message.msg_number].body
+                        );
+                    }
+                    else // Mensagem não está no cache:
+                    {
+                        jQuery('#mailpreview_container').block(
+                        {
+                            message: '<div id="loading-content"><div class="image"></div></div>',
+                            css: {
+                                backgroundImage: 'url(' + BASE_PATH + 'modules/attach_message/images/loading.gif)',
+                                backgroundRepeat: 'no-repeat',
+                                backgroundPosition: 'center',
+                                backgroundColor: 'transparent',
+                                width: '32px',
+                                height: '32px',
+                                border: 'none'
+                            },
+                            overlayCSS: {
+                                backgroundColor: '#CCC',
+                                opacity: 0.5
+                            }
+                        });
+
+                        mark_as_selected(selectedFolder.id, message.msg_number);
+
+                        // Se for mensagem local:
+                        if(selectedFolder['id'].indexOf("local_messages_") != -1)
+                        {
+                            expresso_mail_archive.getPreviewToAttach(id);
+
+                            var body = expresso_mail_archive.bodyPreview;
+                            var subject = expresso_mail_archive.subjectPreview;
+
+                            add_preview_tab(subject, body);
+
+                            $('#mailpreview_container').unblock();
+
+                            add_msg_to_cache(onceOpenedHeadersMessages, message);
+                        }
+                        else
+                        {
+                            proxy_mensagens.get_msg(id, selectedFolder.id, '', function (data) {
+                                message = $.extend(true, message, data);
+
+                                add_preview_tab(message.subject, message.body);
+
+                                $('#mailpreview_container').unblock();
+
+                                add_msg_to_cache(onceOpenedHeadersMessages, message);
+
+
+                            })
+                        }
+                    }
+                }
+                else
+                {
+                    /**
+                     * if you wants to remove tab on unselect message,
+                     * but still needs to uselect message on remove tab.
+                     *
+                     */
+                    selectedMessages[selectedFolder.id][message.msg_number] = false;
+                    $mailpreview_tabs
+                    .find('#' + tabPanelTemplateId + ', [href="#' + tabPanelTemplateId + '"]')
+                    .addClass('preview-message-unselected');
+                }
+
+                selectedMessagesCount();
+            },
+            
 			caption: '<span class="'+selectedFolder['class']+'">'+selectedFolder.name+'</span>'
 		});
-		//.jqGrid('navGrid','#message_attacher_grid_pager',{edit:false,add:false,del:false});
+
+        var search_local_messsages = function(param, folder){
+            if(preferences.use_local_messages != 0)
+            {
+                folder = folder.split("_")[2];
+
+                var local_folders   = [];
+                expresso_mail_archive.search_queryresult = null;
+                
+                local_folders.push(folder);
+                
+                tmp = [];
+
+                groupResult = [];
+                    expresso_mail_archive.search(local_folders, "SUBJECT " +  "<=>" +url_encode(param) + "##");
+                        groupResult.push( expresso_mail_archive.search_queryresult );
+                    expresso_mail_archive.search(local_folders, "FROM " + "<=>" + url_encode(param) + "##");
+                        groupResult.push( expresso_mail_archive.search_queryresult );
+                    expresso_mail_archive.search(local_folders, "TO " + "<=>" + url_encode(param) + "##");
+                        groupResult.push( expresso_mail_archive.search_queryresult );
+                    expresso_mail_archive.search(local_folders, "CC " + "<=>" + url_encode(param) + "##");
+                        groupResult.push( expresso_mail_archive.search_queryresult );
+                    
+                if($("#gbox_message_attacher_grid .attach-message-search-checkbox").is(":checked")){
+                    expresso_mail_archive.search(local_folders, "BODY " + "<=>" + url_encode(param) + "##");
+                        groupResult.push( expresso_mail_archive.search_queryresult );
+                }
+
+                
+                 $.each(groupResult, function(i, result){
+                        if(result != null){
+
+                                var existsMessage = true;
+
+                                $.each(result, function(i, each){
+
+                                        $.each(tmp, function(i, ids){
+
+                                            if(each.msg_number == ids.msg_number){
+
+                                                    existsMessage = false;
+                                                    return false;
+
+                                            }
+
+                                        });
+
+                                        if(existsMessage) tmp.push(each);
+                                });
+
+                        }
+                });
+
+
+                if(tmp == null)
+                {
+                    tmp = new Object();
+                    tmp.length = 0;
+                }
+
+                msgs = [];
+
+                $.each(tmp, function(i, msg){
+
+                    flag = msg['flag'];
+                    id = msg['msg_number'];
+
+                    var message = {};
+
+                    var stamp =  msg['timestamp'];
+                    stamp = stamp.toString() + "000";
+                    stamp = parseInt(stamp);
+
+                    message['msg_number'] = id;
+                    message['flags'] = archive_flag_search(flag);//"1,1,1,1,1,1";//
+                    message['from.name'] = msg['from'];
+                    message['subject'] = msg['subject'];
+                    message['timestamp'] = stamp;
+                    message['size'] = msg['size'];
+                    message['id'] = id;
+                    msgs.push( message );
+                });
+                return msgs;
+            }
+        }
+        var search_imap_messages = function(param, folder){
+        	var grid = $("#message_attacher_grid");
+
+        	DataLayer.storage.cache = {};
+        	if( $(".attach-message-search-checkbox:checked").length > 0 ){
+	            var filters = [
+	        		[
+	        		 	'from',
+	        			'*',
+	        			param
+	        		],       	
+	        		[
+	            		'OR',
+	            		'to',
+	            		'*',
+	            		param
+	            	],
+	        		[
+	            		'OR',
+	            		'subject',
+	            		'*',
+	            		param
+	            	],
+	            	[
+	            		'OR',
+	            		'folder',
+	            		'*',
+	            		folder
+	            	],
+	            	[
+	            		'OR',
+	            		'body',
+	            		'*',
+	            		param
+	            	]
+	            ];
+	        }else{
+	        	var filters = [
+	        		[
+	        		 	'from',
+	        			'*',
+	        			param
+	        		],       	
+	        		[
+	            		'OR',
+	            		'to',
+	            		'*',
+	            		param
+	            	],
+	        		[
+	            		'OR',
+	            		'subject',
+	            		'*',
+	            		param
+	            	],
+	            	[
+	            		'OR',
+	            		'folder',
+	            		'*',
+	            		folder
+	            	]
+	            ];
+	        }
+			
+            var data = DataLayer.get( 'message', { filter: filters, criteria: { properties: { context: { folder: folder } } } }, true );
+
+            if(DataLayer.criterias['message:jqGridSearch']){
+				delete DataLayer.criterias['message:jqGridSearch'];	
+			}
+
+        	DataLayer.register( 'criterias', 'message:jqGridSearch', function( crit ){
+			    crit.properties = { context: { folder: folder } };
+
+			    return { filter: [ "msgNumber", "IN", data ], criteria: crit };
+			});
+            if(typeof(data) == 'object'){
+				grid.jqGrid("clearGridData", true);
+				grid.jqGrid('setGridParam',{datatype: "json", url: 'message:jqGridSearch'}).trigger("reloadGrid");
+
+            }else{
+            	$("#mailgrid-container").find(".loading").hide();
+            	grid.jqGrid("clearGridData", true);
+            }
+        }
+
+		var search_messages = function(param){
+            var grid = $("#message_attacher_grid");
+            var folder = $("#foldertree li span.selected").parent().attr("id");
+            
+            if(param == ""){
+                $('#foldertree [id="'+folder+'"]').trigger("click");
+                return;
+            }
+            $(".attach-message-search-input").val("");
+            if(folder.indexOf("local_messages_") == 0){
+                // Pesquisa pelas mensagens locais...
+                msgs = search_local_messsages(param, folder);
+            } else {
+                // Pesquisa pelo Imap...
+                return search_imap_messages(param, folder);
+            }
+
+            // Monta as mensagens na grid...
+            grid.jqGrid("clearGridData", true);
+            grid.jqGrid('setGridParam',{datatype: "local",data: msgs})
+            .trigger("reloadGrid");
+            //.jqGrid('setCaption', '<span class="'+child.attr('class')+'">'+child.attr('title')+'</span>');
+		}
+
 		var title = [get_lang("First page"), get_lang("Prev page"), get_lang("Next page"), get_lang("Last page")];
 		$("#first_message_attacher_grid_pager").attr("title",title[0]);
@@ -521,4 +922,43 @@
 		$("#next_message_attacher_grid_pager").attr("title",title[2]);
 		$("#last_message_attacher_grid_pager").attr("title",title[3]);
+		$("#mailgrid-container .ui-jqgrid-titlebar")
+		.append( DataLayer.render("../prototype/modules/attach_message/attachment_search.ejs") ).find(".ui-jqgrid-titlebar-close").hide()
+		.end().find(".attach-message-search-input").Watermark("Pesquisa...").keydown(function(e){
+			var param = $(this).val();
+			if($.ui.keyCode.ENTER == e.keyCode){
+				$("#mailgrid-container").find(".loading").show("fast", function(){
+					search_messages(param);
+				});
+			}
+			
+		}).end().find(".attach-message-search-checkbox").click(function(){
+            var msg;
+            if($(this).is(":checked")){
+                msg = get_lang("take off this option to disregard the message body in the search.");
+            } else {
+                msg = get_lang("take on this option to regard the message body in the search.");
+            }
+            $(".attach-message-search-div .button-body-msg-title").attr("title",msg);
+        });
+
+		$("#attach-message-search").button({
+			text: false,
+			icons: {
+				primary: "ui-icon-search"
+			}
+		}).next().button({
+			text: false,
+			icons: {
+				primary: "ui-icon-script"
+			}
+		});
+		$("#attach-message-search").parent().buttonset();
+
+		$("#attach-message-search").click(function(){
+			var param = $(this).parents(".attach-message-search-div:first").find(".attach-message-search-input").val();
+			$("#mailgrid-container").find(".loading").show("fast", function(){
+				search_messages(param);
+			});	
+		});
 	}
 });
