Index: trunk/prototype/modules/attach_message/attach_message.js
===================================================================
--- trunk/prototype/modules/attach_message/attach_message.js	(revision 7951)
+++ trunk/prototype/modules/attach_message/attach_message.js	(revision 7972)
@@ -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,5 +227,4 @@
 var msgAttacherGrid = $("#message_attacher_grid"), msgsTotal = $("#selected_messages_number");
 var lastLoadedMessages = [];
-var onceOpenedMessages = [];
 var selectedMessages   = {};
 var selectedFolder     = {};
@@ -536,5 +535,5 @@
 				lastLoadedMessages = data.rows;
 				$("#mailgrid-container").find(".loading").hide();
-          		//$(".attach-message-search-input").val("");
+
 				// aplica o contador
 				jQuery('.timable').each(function (i) {
@@ -560,154 +559,152 @@
 				
 			},
-			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(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');
+            onSelectRow: function(id, selected)
+            {
+                /* Funções auxiliares:*/
+
+                var mark_as_selected = function (folder, msg_number) {
+                    if(!selectedMessages[folder])
+                    {
+                        selectedMessages[folder] = {};
+                    }
+                    selectedMessages[folder][msg_number] = true;
+                }
+
+                var add_msg_to_cache = function (cache, msg) {
+                    if(!cache[selectedFolder.id])
+                    {
+                        cache[selectedFolder.id] = {};
+                    }
+                    cache[selectedFolder.id][msg.msg_number] = msg;
+                }
+
+                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ó 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);
                         }
-                    }
-					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;
-
-
-                        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 ){		
-    								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.
-					 * 
-					 */
-					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();
-			},
+                        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){
