Index: trunk/expressoMail1_2/preferences.php
===================================================================
--- trunk/expressoMail1_2/preferences.php	(revision 5075)
+++ trunk/expressoMail1_2/preferences.php	(revision 5134)
@@ -40,4 +40,9 @@
 		else
 			$GLOBALS['phpgw']->template->set_var('checked_save_deleted_msg','');
+
+		if ($GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['default_fields_quick_search'])		
+			$GLOBALS['phpgw']->template->set_var('checked_default_fields_quick_search','checked');
+		else
+			$GLOBALS['phpgw']->template->set_var('checked_default_fields_quick_search','');
 
 		if($GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['delete_trash_messages_after_n_days'])
@@ -129,13 +134,11 @@
 			$GLOBALS['phpgw']->template->set_var('text_signature','');
 		
-		if($GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['type_signature']){
-			$GLOBALS['phpgw']->template->set_var('type_signature_option_'.$GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['type_signature'].'_selected','selected');
-			$GLOBALS['phpgw']->template->set_var('type_signature_td_'.($GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['type_signature'] == 'html' ? 'text' : 'html'),'display:none');
-		}
-		else{
-			$GLOBALS['phpgw']->template->set_var('type_signature_option_text_selected','selected');
-			$GLOBALS['phpgw']->template->set_var('type_signature_td_html','display:none');
-		}
-
+
+                if($GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['catalog_search']) 
+                {
+                    
+		}
+
+                
 		// BEGIN FCKEDITOR
 		$oFCKeditor = new FCKeditor('html_signature') ;
@@ -263,4 +266,10 @@
 		
 		
+				if ($GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['default_fields_quick_search']) 
+                       $GLOBALS['phpgw']->preferences->change('expressoMail', 'default_fields_quick_search', $_POST['default_fields_quick_search']); 
+                else  
+                       $GLOBALS['phpgw']->preferences->add('expressoMail', 'default_fields_quick_search', $_POST['default_fields_quick_search']);     
+                
+                
 		if ($GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['use_shortcuts'])
 			$GLOBALS['phpgw']->preferences->change('expressoMail','use_shortcuts',$_POST['use_shortcuts']);
@@ -300,9 +309,4 @@
 			$GLOBALS['phpgw']->preferences->add('expressoMail','signature',$_POST['signature']);
 
-		if ($GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['type_signature'])
-			$GLOBALS['phpgw']->preferences->change('expressoMail','type_signature',$_POST['type_signature']);
-		else
-			$GLOBALS['phpgw']->preferences->add('expressoMail','type_signature',$_POST['type_signature']);
-
 		if ($GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['hide_folders'])
 			$GLOBALS['phpgw']->preferences->change('expressoMail','hide_folders',$_POST['check_menu']);
@@ -334,4 +338,8 @@
 			$GLOBALS['phpgw']->preferences->add('expressoMail','keep_archived_messages',$_POST['keep_archived_messages']);			
 
+		if ($GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['default_fields_quick_search'])
+			$GLOBALS['phpgw']->preferences->change('expressoMail','default_fields_quick_search',$_POST['default_fields_quick_search']);
+		else
+			$GLOBALS['phpgw']->preferences->add('expressoMail','default_fields_quick_search',$_POST['default_fields_quick_search']);	
 		$GLOBALS['phpgw']->preferences->save_repository();
 		
@@ -376,5 +384,4 @@
 	$GLOBALS['phpgw']->template->set_var('html_text',lang('Rich Text'));
 	$GLOBALS['phpgw']->template->set_var('lang_config_signature',lang('Signature Configuration'));
-	$GLOBALS['phpgw']->template->set_var('lang_type_signature',lang('Signature type'));
 	$GLOBALS['phpgw']->template->set_var('big',lang('Big'));
     //$GLOBALS['phpgw']->template->set_var('lang_use_signature_digital_cripto',lang('Possibilitar <b>assinar/criptografar</b> digitalmente a mensagem?'));
@@ -392,4 +399,5 @@
  	$GLOBALS['phpgw']->template->set_var('lang_personal_catalog', lang('Personal Catalog')); 
  	$GLOBALS['phpgw']->template->set_var('lang_all_catalog', lang('All Catalogs')); 
+        $GLOBALS['phpgw']->template->set_var('lang_default_fields_quick_search', lang('Show default fields in the quick search screen'));
 	
 	$GLOBALS['phpgw']->template->set_var('url_offline','offline.php');
@@ -427,4 +435,5 @@
 		$GLOBALS['phpgw']->template->set_var('checked_mainscreen_showmail','checked');
 		$GLOBALS['phpgw']->template->set_var('checked_show_name_print_messages','checked'); 
+		$GLOBALS['phpgw']->template->set_var('checked_default_fields_quick_search','checked'); 
 		$save_in_folder_selected = "INBOX".$e_server['imapDelimiter'].$specialFolders["Sent"];
 	}
Index: trunk/expressoMail1_2/index.php
===================================================================
--- trunk/expressoMail1_2/index.php	(revision 5083)
+++ trunk/expressoMail1_2/index.php	(revision 5134)
@@ -20,5 +20,6 @@
  	                <script src='../library/ckeditor/ckeditor.js' language='javascript'></script> 
  	                <script src='../library/ckeditor/adapters/jquery.js' language='javascript'></script> 
- 	                <script src='js/rich_text_editor.js' type='text/javascript'></script>"; 
+                <script src='js/rich_text_editor.js' type='text/javascript'></script>
+                <script src='js/base64.js' type='text/javascript'></script>";
  	        //---------------------------// 
         echo '<link href="js/lert/lert.css" rel="stylesheet" type="text/css"/>';
@@ -26,4 +27,5 @@
 	echo "<script src='js/globals.js?".$update_version."' type='text/javascript'></script>";
 	echo "<script src='js/sniff_browser.js?".$update_version."' type='text/javascript'></script>";
+	echo "<script src='js/QuickCatalogSearch.js' type='text/javascript'></script>";
 	echo "<style type='text/css'>@import url(../phpgwapi/js/jscalendar/calendar-win2k-1.css);</style>";
 	echo "<script src='../phpgwapi/js/jscalendar/calendar.js?".$update_version."' type='text/javascript'></script>";
@@ -33,22 +35,35 @@
 		<script type="text/javascript" src="../phpgwapi/js/dJSWin/dJSWin.js?'.$update_version.'"></script>';
 
+	echo '
+	<script type="text/javascript" src="../prototype/app/plugins/view/jquerymx-1.0.custom.min.js"></script>
+	<script type="text/javascript" src="../prototype/app/plugins/treeview/jquery.treeview.js"></script>
+	<script type="text/javascript" src="../prototype/app/plugins/block/jquery.blockUI.js"></script>
+
+	<link rel="stylesheet" href="../prototype/app/plugins/treeview/jquery.treeview.css" type="text/css" media="screen" />
+	<script src="../prototype/app/plugins/jqgrid/js/i18n/grid.locale-pt-br.js" type="text/javascript"></script>
+	<script src="../prototype/app/plugins/jqgrid/js/jquery.jqGrid.min.js" type="text/javascript"></script>
+	<link rel="stylesheet" href="../prototype/app/plugins/jqgrid/css/ui.jqgrid.css" type="text/css" />	
+	<link rel="stylesheet" href="../prototype/app/plugins/jqgrid/themes/prognusone/jquery-ui-1.8.2.custom.css" type="text/css" />	
+
+	<script src="../prototype/app/plugins/countdown/jquery.countdown.min.js" type="text/javascript"></script>
+	<script src="../prototype/app/plugins/countdown/jquery.countdown-pt-BR.js" type="text/javascript"></script>	
+	';
 
 	/*
-	 * TODO: implementar o controle como preferência do usuário
+	 * TODO: implementar o controle como preferÃªncia do usuÃ¡rio 
 	 *
 	 */
 	$jcarousel = false;
 	if ($jcarousel) {
-		//jquery
-		echo "\n".'<script src="../library/jquery/jquery-1.6.1.min.js" type="text/javascript"></script>';
 		//jcarousel
+		echo "\n".'<link rel="stylesheet" type="text/css" href="../library/jcarousel/skins/default/skin.css" />';
 		echo "\n".'<script src="../library/jcarousel/lib/jquery.jcarousel.min.js" type="text/javascript"></script>';
-		echo "\n".'<link rel="stylesheet" type="text/css" href="../library/jcarousel/skins/default/skin.css" />';
+
 		//fancybox
+		echo "\n".'<link rel="stylesheet" type="text/css" href="../library/fancybox/jquery.fancybox-1.3.4.css" />';		
 		echo "\n".'<script src="../library/fancybox/jquery.fancybox-1.3.4.pack.js" type="text/javascript"></script>';
-		echo "\n".'<script src="../library/fancybox/jquery.easing-1.4.pack.js" type="text/javascript"></script>';
-		echo "\n".'<script src="../library/fancybox/jquery.mousewheel-3.0.4.pack.js" type="text/javascript"></script>';	
-		echo "\n".'<link rel="stylesheet" type="text/css" href="../library/fancybox/jquery.fancybox-1.3.4.css" />';		
-	}
+	}
+
+	echo "<div id='overlay' style='background-color: #AAAAAAA; opacity: .50; filter:Alpha(Opacity=50); height: 100%; width: 100%; position: absolute; top: 0; left: 0; visibility: hidden; z-index: 30000000000000000000000'></div>";
 
 	
@@ -83,4 +98,7 @@
     $current_config = $c->config_data;    
 
+        //Carrega Configuração global do expressoMail 
+ 	$_SESSION['phpgw_info']['expresso']['expressoMail'] =  $current_config; 
+    
 	$_SESSION['phpgw_info']['expressomail']['email_server'] = $boemailadmin->getProfile($emailadmin_profile[0]['profileID']);
 //	$_SESSION['phpgw_info']['expressomail']['user'] = $GLOBALS['phpgw_info']['user'];
@@ -114,5 +132,5 @@
 	$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['keep_after_auto_archiving'] = $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['keep_after_auto_archiving'] ? $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['keep_after_auto_archiving'] : "0";
 
-	$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size'] = $current_config['expressoMail_Max_attachment_size'] ? $current_config['expressoMail_Max_attachment_size']."M" : ini_get('upload_max_filesize');
+	$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size'] = $current_config['expressoMail_Max_attachment_size'] ? $current_config['expressoMail_Max_attachment_size']."M" : '';
 	$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_msg_size'] = $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['max_msg_size'] ? $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['max_msg_size'] : "0";
 	$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['imap_max_folders'] = $current_config['expressoMail_imap_max_folders'];
Index: trunk/expressoMail1_2/templates/default/preferences.tpl
===================================================================
--- trunk/expressoMail1_2/templates/default/preferences.tpl	(revision 1121)
+++ trunk/expressoMail1_2/templates/default/preferences.tpl	(revision 5134)
@@ -215,4 +215,24 @@
         </td>
     </tr>
+
+    <tr bgcolor="{tr_color1}">
+        <td>{lang_catalog_search}</td>
+        <td align="center">
+			<select name="catalog_search">
+				<option {global_selected} value="1">{lang_global_catalog}</option>
+				<option {personal_selected} value="2">{lang_personal_catalog}</option>
+				<option {all_selected} value="3">{lang_all_catalog}</option>
+			</select>
+        </td>
+    </tr>
+	<tr bgcolor="{tr_color2}">
+        <td>
+			{lang_default_fields_quick_search}
+		</td>
+		<td align="center">
+			<input type="checkbox" name="use_signature" value=1 {checked_default_fields_quick_search}>
+		</td>
+    </tr>
+
     <tr bgcolor="{th_bg}">
     	<td colspan="2" >
Index: trunk/expressoMail1_2/templates/default/expressomail.css
===================================================================
--- trunk/expressoMail1_2/templates/default/expressomail.css	(revision 4492)
+++ trunk/expressoMail1_2/templates/default/expressomail.css	(revision 5134)
@@ -7,27 +7,94 @@
 
 /* thumbs list on message screen */
-.expressomail-thumbs { font-size:11px; width:100%; margin:20px 0 0 0; border-top:1px solid #AAA;}
+.expressomail-thumbs { font-size:11px; width:100%; max-width:100%; margin:20px 0 0 0; border-top:1px solid #AAA; float: left}
 .expressomail-thumbs-label {}
 .message_options {}
 .expressomail-thumbs span.message_tips { display:block; padding-left:18px; line-height:18px;height:18px; background-image: url(images/menu/ktip.png); background-repeat:no-repeat;}
 ul.expressomail-thumbs-list { list-style:none; margin:0; padding:0;}
-ul.expressomail-thumbs-list li {height:80px; max-width:120x; max-height:80px; display:block; float:left; margin: 5px; padding:0;}
-ul.expressomail-thumbs-list li img {width:100%; height:100%; border: 2px solid #FDE7BC;}
+ul.expressomail-thumbs-list li {height:80px;  max-width:120px; max-height:80px; display:block; float:left; margin: 5px; padding:0;}
+ul.expressomail-thumbs-list li img {width:auto; height:100%; border: 2px solid #FDE7BC;}
 .expressomail-thumbs-link { font-size:11px;}
+ .jcarousel-container { width: auto;}
+ 
+
+
 
 /* todo o resto */
 table.expressomail-message-body {width:100%; height:100%;}
-table.table_message {background-image: url(../../../phpgwapi/templates/default/images/fundo_msg.png); background-repeat:repeat-x;}
-.table_message{
-	cursor: default;
-	border-width: 1px;
-	border-spacing: 0px 0px;
-	border-style: outset;
+table.table_message {
+background: #96b3d3; /* Old browsers */
+background: -moz-linear-gradient(top, #96b3d3 0%, #b4c9e4 30%, #d9e6ef 65%, #e2e9f1 70%, #e9f0f8 78%, #e8f1fa 83%, #dbe5ef 96%, #d9e3ed 100%); /* FF3.6+ */
+background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#96b3d3), color-stop(30%,#b4c9e4), color-stop(65%,#d9e6ef), color-stop(70%,#e2e9f1), color-stop(78%,#e9f0f8), color-stop(83%,#e8f1fa), color-stop(96%,#dbe5ef), color-stop(100%,#d9e3ed)); /* Chrome,Safari4+ */
+background: -webkit-linear-gradient(top, #96b3d3 0%,#b4c9e4 30%,#d9e6ef 65%,#e2e9f1 70%,#e9f0f8 78%,#e8f1fa 83%,#dbe5ef 96%,#d9e3ed 100%); /* Chrome10+,Safari5.1+ */
+background: -o-linear-gradient(top, #96b3d3 0%,#b4c9e4 30%,#d9e6ef 65%,#e2e9f1 70%,#e9f0f8 78%,#e8f1fa 83%,#dbe5ef 96%,#d9e3ed 100%); /* Opera 11.10+ */
+background: -ms-linear-gradient(top, #96b3d3 0%,#b4c9e4 30%,#d9e6ef 65%,#e2e9f1 70%,#e9f0f8 78%,#e8f1fa 83%,#dbe5ef 96%,#d9e3ed 100%); /* IE10+ */
+background: linear-gradient(top, #96b3d3 0%,#b4c9e4 30%,#d9e6ef 65%,#e2e9f1 70%,#e9f0f8 78%,#e8f1fa 83%,#dbe5ef 96%,#d9e3ed 100%); /* W3C */
+filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#96b3d3', endColorstr='#d9e3ed',GradientType=0 ); /* IE6-9 */
+}
+table.expressomail-message-body tr{vertical-align:top;}
+
+
+
+
+.table_message_options{
+	background-color: #000;
+	
+	/* Apenas para ie qualquer versao */
+	-moz-border-collapse: separate;
 	border-color: gray;
-	border-collapse: separate;
-	border-radius: 3px;
+
+    border-spacing: 0;
+    border-style: outset;
+    border-width: 0.01;
+    cursor: default;
+    padding: 1px;
 	-moz-border-radius: 3px;
 	-webkit-border-radius: 3px;
+	
+	
+}
+
+.table_message_options_ie{
+
+	border-collapse: collapse;
+	background-color: #000;
+	border-color: gray;
+    border-spacing: 0;
+    border-style: outset;
+    border-width: 1;
+    cursor: default;
+    padding: 1px;
+	-moz-border-radius: 3px;
+	-webkit-border-radius: 3px;
+	
+	
+}
+
+.table_message{
+	background-color: #000;
+	
+	/* Apenas para ie qualquer versao */
+	-moz-border-collapse: separate;
+	border-color: gray;
+	border-radius: 3px 3px 3px 3px;
+    border-spacing: 0;
+    border-style: outset;
+    border-width: 1px;
+    cursor: default;
+    padding: 1px;
+	-moz-border-radius: 3px;
+	-webkit-border-radius: 3px;
+	
+	
 }
 
 .div_message_scroll { background: none repeat scroll 0% 0% WHITE; overflow: auto; padding-right: 5px;}
+a.message-attach-link { margin-left: 20px;}
+
+.messagescol td label {padding-right:20px;}
+.messagescol td.message-general-options .checkbox {margin: 5px 5px 0 0;}
+
+.ui-dialog-dragging {
+	opacity:0.4;
+	filter:alpha(opacity=40); /* For IE8 and earlier */
+}
Index: trunk/expressoMail1_2/templates/default/config.tpl
===================================================================
--- trunk/expressoMail1_2/templates/default/config.tpl	(revision 4832)
+++ trunk/expressoMail1_2/templates/default/config.tpl	(revision 5134)
@@ -103,5 +103,6 @@
     <td>{lang_Max_attachment_size}</td>
     <td>
-    <input size="1" name="newsettings[expressoMail_Max_attachment_size]" value="{value_expressoMail_Max_attachment_size}">&nbsp;Mb<span style='position:relative; left:20px;'>Max: {php_upload_limit}Mb.</span> 
+    <input size="2" name="newsettings[expressoMail_Max_attachment_size]" value="{value_expressoMail_Max_attachment_size}">&nbsp;Mb<span style='position:relative; left:20px;'>Max: {php_upload_limit}Mb.</span> 
+    <span style="color: red;margin-left: 30px"> *Valor 0 ou vazio = desativa a funcionalidade	</span>
     <input type="hidden" name="valida_alert" value="{lang_Value_exceeds_the_PHP_upload_limit_for_this_server}" /> 
     </td>
@@ -121,4 +122,22 @@
     <input size="80" name="newsettings[expressoMail_googlegears_url]" value="{value_expressoMail_googlegears_url}"> 
     </td>
+    </tr>
+        <tr bgcolor="{row_off}">
+        <td>{lang_gears_firefox_windows_url}</td>
+        <td>
+        <input size="60" name="newsettings[expressoMail_gears_firefox_windows]" value="{value_expressoMail_gears_firefox_windows}">
+        </td>
+    </tr>
+    <tr bgcolor="{row_on}">
+        <td>{lang_gears_firefox_linux_url}</td>
+        <td>
+        <input size="60" name="newsettings[expressoMail_gears_firefox_linux]" value="{value_expressoMail_gears_firefox_linux}">
+        </td>
+    </tr>
+   <tr bgcolor="{row_off}">
+        <td>{lang_gears_ie_url}</td>
+        <td>
+        <input size="60" name="newsettings[expressoMail_gears_ie]" value="{value_expressoMail_gears_ie}">
+        </td>
     </tr>
     <tr bgcolor="{row_on}">
@@ -157,23 +176,4 @@
 	   </tr> 
 
-
-    <tr bgcolor="{row_off}">
-        <td>{lang_gears_firefox_windows_url}</td>
-        <td>
-        <input size="60" name="newsettings[expressoMail_gears_firefox_windows]" value="{value_expressoMail_gears_firefox_windows}">
-        </td>
-    </tr>
-    <tr bgcolor="{row_on}">
-        <td>{lang_gears_firefox_linux_url}</td>
-        <td>
-        <input size="60" name="newsettings[expressoMail_gears_firefox_linux]" value="{value_expressoMail_gears_firefox_linux}">
-        </td>
-    </tr>
-   <tr bgcolor="{row_off}">
-        <td>{lang_gears_ie_url}</td>
-        <td>
-        <input size="60" name="newsettings[expressoMail_gears_ie]" value="{value_expressoMail_gears_ie}">
-        </td>
-    </tr>
 <!-- END body -->
 <!-- BEGIN footer -->
Index: trunk/expressoMail1_2/templates/default/index.tpl
===================================================================
--- trunk/expressoMail1_2/templates/default/index.tpl	(revision 5083)
+++ trunk/expressoMail1_2/templates/default/index.tpl	(revision 5134)
@@ -22,6 +22,7 @@
 							<td>
 								<div id="search_div" align="center" style="white-space:nowrap"></div>
-								<input type="text" id="em_message_search" size="16" maxlength="22" onfocus="javascript:onFocusQuickSearchEmail(this); return false;"/>
+								<input type="text" id="em_message_search" size="18" />
 								<a style="padding:1 8px; width:16px; height:16px; background: url(templates/default/images/search.gif) no-repeat center; margin: 0 3px;" class="" onMouseOut="window.status='';return true;" title='{lang_Open_Search_Window}' onMouseOver="window.status='{lang_Open_Search_Window}';return true;" href="javascript:void(0);"  onClick="javascript:search_emails(Element('em_message_search').value)"></a> 
+								
 								<a style="padding:1 8px; width:16px; height:16px; background: url(templates/default/images/users.gif) no-repeat center;" class="" onMouseOut="window.status='';return true;" title='{lang_search_user}' onMouseOver="window.status='{lang_search_user}' ;return true;" href="javascript:void(0);"  onClick="javascript:emQuickSearch(Element('em_message_search').value, 'null', 'null')"></a> 
 							</td>
@@ -131,25 +132,17 @@
 	</table>
 </div>
-<link href="../library/jquery/css/redmond/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css">
- 		<script type="text/javascript" src="../library/jquery/jquery-ui.min.js"></script> 
- 		<link href="templates/default/quick_search.css" rel="stylesheet" type="text/css"> 
- 		<div style="display:none; width: auto; min-height: 0px; height: 410px;" id="dialog-modal" title="{lang_quick_search_users_dialog_title}"> 
- 		    <div style="width:910px;height:410px;">                      
- 		            <div class="acc-list" style="width:370px;height:85%;float:left;border:1px solid #DDD;background-color:#EEE;border-radius:3px;margin-left:1px;"> 
- 		                    <h3 id="title_usuarios"></h3> 
- 		                    <ul id="selectable" style="width:370px; height:350px;"></ul>   
- 		                    <div class="demo" style="width:100%;margin-top:-5px;"> 
- 		                        <div id="slider"></div> 
- 		                            <p> 
- 		                                <label for="amount">{lang_page}: </label> 
- 		                                <input type="text" id="amount" style="border:0; font-weight:bold; width:85%" /> 
- 		                            </p>             
- 		                    </div> 
- 		            </div> 
- 		            <div style="width:525px;height:90%;float:left;">  
+<link href="../library/jquery/css/redmond/jquery-ui.css" rel="stylesheet" type="text/css">
+<script type="text/javascript" src="../library/jquery/jquery-ui.min.js"></script>
+                                       
+<script type="text/javascript" src="js/QuickCatalogSearch.js"></script>
+<link href="templates/default/quick_search.css" rel="stylesheet" type="text/css">
+<div style="display:none; width: auto; min-height: 0px; height: 410px; overflow: hidden" id="dialog-modal" class="dialog-modal expressomail-qs-container" title="{lang_quick_search_users_dialog_title}">
  		                <div id="accordion"> 
  		                        <div class="ui-widget" align="right"> 
- 		                            <label>{lang_search}: </label> 
- 		                                <input type="text" id="busca" size=30></input>                             
+							<fieldset class="search-field ui-corner-all" style>
+								<span class="ui-icon ui-icon-search"></span>
+								<input class="search" id="busca" onFocus="setFocus();" onBlur="removeFocus();" onkeypress="javascript: if(checkEnter(event)) {buscaContato(this.value); }" type="text" />
+							</fieldset>
+							<fieldset class="search-catalog-options ui-corner-all">
  		                            <select id="combobox"> 
  		                                <!-- Pegar essas opções das preferências --> 
@@ -158,14 +151,37 @@
  		                                <option value="all">{lang_all_catalogs}</option> 
  		                            </select> 
- 		                            <input type="button" value="Buscar" onClick=buscaContato(busca.value); /> 
- 		                            <input type="button" value="?" onClick="alert('Busca rápida de contatos versão 0.1\nPrognus Software Livre')" /> 
- 		                        </div> 
- 		                        <fieldset id="fieldset1" style="width:490px;height:85%;float:right;"> 
- 		                            <legend>{lang_contact_details}</legend> 
- 		                                <div style="float:left;"> <span id="detalhes_contato">---</span> </div> 
  		                        </fieldset>     
+                            <input class="button" type="button" value="Buscar" onClick="buscaContato(busca.value);"/>
+                            <input class="button" type="button" value="?" onClick="show_help()" />
  		                 </div>   
  		             </div> 
+		                <fieldset id="fieldset1" class="details-container ui-corner-all">
+                            <legend>{lang_contact_details}</legend>
+                            <div style="overflow: auto; height: 230px;" id="detalhes_contato"></div>
+                        </fieldset>    
+            <div class="acc-list"> <ul id="selectable"></ul></div>
+                    <div class="demo" style="float: left; margin-top: 10px; width: 100%; height: 20px; padding:5px 0 0 0;">
+                        <div id="slider" style="width: 448px;"></div>
+                            <p style="margin-top: -15px; margin-bottom: 0pt; margin-left: 453px; float: left;">
+                                <label for="amount">{lang_page}: </label>
+                                <input type="text" id="amount-text" style="border:0; font-weight:bold;" readonly="true" />
+                            </p>            
  		        </div> 
+</div>
+<div style="display:none; width: auto; min-height: 0px; height: 380px;" id="dialog-modal_help" title="{lang_dialog_help} Help busca rápida de contatos"> 
+	<fieldset id="fieldset2">
+        <legend>{lang_help} Busca rápida de contatos</legend>
+		<div>
+			<strong>Para a utilização dessa funcionalidade, podem ser usados os seguintes atalhos:</strong><br><br><br>
+			<ul>
+				<li>Ir para a página anterior - Seta para esquerda</li>
+				<li>Mover para contato acima - Seta para cima</li>
+				<li>Mover para contato abaixo - Seta para baixo</li>
+				<li>Mover para a próxima página - Seta para direita</li>
+				<li>Adicionar contato selecionado - Enter</li>
+				<li>Fechar - Esc</li>
+			</ul> 
  		</div> 
+	</fieldset>   
+</div>
 <!-- END list -->
Index: trunk/expressoMail1_2/templates/default/quick_search.css
===================================================================
--- trunk/expressoMail1_2/templates/default/quick_search.css	(revision 5075)
+++ trunk/expressoMail1_2/templates/default/quick_search.css	(revision 5134)
@@ -1,58 +1,112 @@
 /* Estilos da tela de busca rápida de contatos */
 
-                body { font-size:11px;} 
-                fieldset, div {margin:0;}
-                .ui-autocomplete-input { height:22px; width:200px; margin-right:-1px; }
-                #wrap-progressbar { height:22px; width:122px;  float:left; }
-                #wrap-progressbar #inner-progressbar { text-align:center; width:100px; }
-                #wrap-progressbar #inner-progressbar span { font-size:10px; line-height:12px; }
-                #wrap-progressbar #inner-progressbar #progressbar { width:100px; height:10px; }
-                .clear {clear:both;}
-                #fieldset1 label {width:495px;display:inline-block; border:4px solid #72A9D3;}
-                fieldset { border:1px solid #AAA; border-radius:5px; margin:5px; }
-                ul {list-style:none; margin:0; padding:0;}
-                
-                #list-acc-users li, #search-result-users li {margin-right:5px;border-radius:3px;}
-                #list-acc-mails li {margin-right:5px;padding-bottom:4px;border-radius:3px;}
-                #list-acc-users li:hover, #list-acc-mails li:hover, #search-result-users li:hover {background-color:#DDD;}
-                #list-acc-users li span.ui-icon, #list-acc-mails li span.ui-icon, #search-result-users li span.ui-icon {display:none; margin:2px;}
-                #list-acc-users li input, #list-acc-mails li input, #search-result-users li input {margin-top:5px;}
-                #list-acc-users li label, #list-acc-mails li label, #search-result-users li label {margin-top:-5px;}
-                #list-acc-users li:hover span, #list-acc-mails li:hover span, #search-result-users li:hover span {display:inline;}
-                #search-result-users li span.ui-icon {display:none;}
-                .ui-icon {float:right;}
-                #icon-bar1 .ui-icon {float:left; margin:0 3px;}
-                 #icon-bar1 span {float:left; margin:2px 3px 0 0;}
-                .ui-icon-trash, .ui-icon-edit, .ui-icon-close, .ui-icon-plus, .ui-icon-pencil {background-color:#EEE;}
-                .ui-icon-trash:hover, .ui-icon-edit:hover, .ui-icon-close:hover, .ui-icon-plus:hover, .ui-icon-pencil:hover {background-color:#BBB;}
-                .ui-autocomplete-input {width:170px;}
-                .ui-accordion .ui-accordion-content{padding:5px;}
+.expressomail-qs-container { font-size:11px;} 
+.expressomail-qs-container legend { font-size:1.1em; font-weight: bold; } 
+.expressomail-qs-container #accordion { margin: 5px;} 
+.expressomail-qs-container fieldset, .expressomail-qs-container div {margin:0;}
+.expressomail-qs-container .ui-autocomplete-input { height:22px; width:200px; margin-right:-1px; }
+.expressomail-qs-container #wrap-progressbar { height:22px; width:122px;  float:left; }
+.expressomail-qs-container #wrap-progressbar #inner-progressbar { text-align:center; width:100px; }
+.expressomail-qs-container #wrap-progressbar #inner-progressbar span { font-size:10px; line-height:12px; }
+.expressomail-qs-container #wrap-progressbar #inner-progressbar #progressbar { width:100px; height:10px; }
+.expressomail-qs-container .clear {clear:both;}
+/*.expressomail-qs-container #fieldset1 label {width:495px;display:inline-block; border:4px solid #72A9D3;}*/
+.expressomail-qs-container fieldset { border:1px solid #AAA; border-radius:5px; margin:5px; }
+.expressomail-qs-container #ul {list-style:none; margin:0; padding:0;}
+.expressomail-qs-container #fieldset1 {color:#444;}
+.expressomail-qs-container #fieldset1 label {font-weight:bold; display:block;}
 
-                .foot-note {width:905px; padding:5px;margin-top:20px;border-top:1px solid #ddd;}
-                .acc-list {font-family: "Trebuchet MS", Tahoma, Verdana, Arial, sans-serif; font-size:11px; color:#555; }
-                .acc-list h3{font-family: "Trebuchet MS", Tahoma, Verdana, Arial, sans-serif; font-size:11px; color:#555; margin:0; padding:5px 3px; background-color:#fff;}
-                .acc-list ul{ margin:5px 0;}
-                .acc-list ul li{ border-radius:3px; padding:10px;}
-                .acc-list ul li:hover {background-color:#DDD;}
-                .acc-list ul li.active {background-color:#EB8F00;}
-                .acc-list ul li strong {display:block;}
-                .acc-list ul li em {display:block;}
+.expressomail-qs-container #list-acc-users li, .expressomail-qs-container #search-result-users li {margin-right:5px;border-radius:3px;}
+.expressomail-qs-container #list-acc-mails li {margin-right:5px;padding-bottom:4px;border-radius:3px;}
+.expressomail-qs-container #list-acc-users li:hover, .expressomail-qs-container #list-acc-mails li:hover, .expressomail-qs-container #search-result-users li:hover {background-color:#DDD;}
+.expressomail-qs-container #list-acc-users li span.ui-icon, .expressomail-qs-container #list-acc-mails li span.ui-icon, .expressomail-qs-container #search-result-users li span.ui-icon {display:none; margin:2px;}
+.expressomail-qs-container #list-acc-users li input, .expressomail-qs-container #list-acc-mails li input, .expressomail-qs-container #search-result-users li input {margin-top:5px;}
+.expressomail-qs-container #list-acc-users li label, .expressomail-qs-container #list-acc-mails li label, .expressomail-qs-container #search-result-users li label {margin-top:-5px;}
+.expressomail-qs-container #list-acc-users li:hover span, .expressomail-qs-container #list-acc-mails li:hover span, .expressomail-qs-container #search-result-users li:hover span {display:inline;}
+.expressomail-qs-container #search-result-users li span.ui-icon {display:none;}
+.expressomail-qs-container .ui-icon {float:right;}
+.expressomail-qs-container #icon-bar1 .ui-icon {float:left; margin:0 3px;}
+.expressomail-qs-container #icon-bar1 span {float:left; margin:2px 3px 0 0;}
+.expressomail-qs-container .ui-icon-trash, .expressomail-qs-container .ui-icon-edit, .expressomail-qs-container .ui-icon-close, .expressomail-qs-container .ui-icon-plus, .expressomail-qs-container .ui-icon-pencil {background-color:#EEE;}
+.expressomail-qs-container .ui-icon-trash:hover, .expressomail-qs-container .ui-icon-edit:hover, .expressomail-qs-container .ui-icon-close:hover, .expressomail-qs-container .ui-icon-plus:hover, .expressomail-qs-container .ui-icon-pencil:hover {background-color:#BBB;}
+.expressomail-qs-container .ui-autocomplete-input {width:170px;}
+.expressomail-qs-container .ui-accordion .ui-accordion-content{padding:5px;}
 
-                /*Específico do selectable*/
-                #feedback { font-size: 1.4em; }
-                #selectable .ui-selecting { background: #DDECF7; }
-                /* #selectable .ui-selected { background: #F39814; color: white; }   Aqui eu troquei a cor de quando era selecionada a linha */
-                #selectable .ui-selected { background: #72A9D3; color: white; }
-                
-                #selectable { list-style-type: none; margin: 0; padding: 0; width: 100%; }
-                ul#selectable { overflow: hidden; width: 370px;}
-                ul#selectable li { width: 300px; overflow:hidden; }
-                ul#selectable li.ui-selected { width: 81%;  }
-                ul#selectable li div { width: 6000px; }
-                .ui-button-icon-only { width: 1.2em; }
-                .ui-icon { margin-left: -8px; }
-                .ui-widget button { border: 0 solid; } 
-            
-                #dialog-modal { height: 416px; }
+.expressomail-qs-container .foot-note {width:905px; padding:5px;margin-top:20px;border-top:1px solid #ddd;}
+.expressomail-qs-container .acc-list {font-family: "Trebuchet MS", Tahoma, Verdana, Arial, sans-serif; font-size:11px; color:#555; }
+.expressomail-qs-container .acc-list h3{font-family: "Trebuchet MS", Tahoma, Verdana, Arial, sans-serif; font-size:11px; color:#555; margin:0; padding:5px 3px; background-color:#fff;}
+.expressomail-qs-container .acc-list ul{ margin:5px 0;}
+.expressomail-qs-container .acc-list ul li{ border-radius:3px; padding:5px;}
+.expressomail-qs-container .acc-list ul li:hover {background-color:#DDD;}
+.expressomail-qs-container .acc-list ul li.active {background-color:#EB8F00;}
+.expressomail-qs-container .acc-list ul li strong {display:block;}
+.expressomail-qs-container .acc-list ul li em {display:block;}
+
+/*Específico do selectable*/
+.expressomail-qs-container #feedback { font-size: 1.4em; }
+.expressomail-qs-container #selectable .ui-selecting { background: #DDECF7; }
+/* #selectable .ui-selected { background: #F39814; color: white; }   Aqui eu troquei a cor de quando era selecionada a linha */
+.expressomail-qs-container #selectable .ui-selected { background: #72A9D3; color: white; }
+
+.expressomail-qs-container #selectable { list-style-type: none; margin: 0; padding: 0; width: 100%; }
+.expressomail-qs-container ul#selectable { overflow: hidden; width: 444px; height: 250px;}
+.expressomail-qs-container ul#selectable li { width: 435px; overflow:hidden; }
+.expressomail-qs-container ul#selectable li.ui-selected { width: 100%;  }
+.expressomail-qs-container ul#selectable li div { width: 6000px; }
+.expressomail-qs-container .ui-button-icon-only { width: 1.2em; }
+.expressomail-qs-container .ui-icon { margin-left: -8px; }
+.expressomail-qs-container .ui-widget button { border: 0 solid; } 
+
+.expressomail-qs-container .menu-control { float:right; margin-left:380px; position: absolute; z-index: 100; padding-top:5px;}
+.expressomail-qs-container .acc-list { width:444px;height:250px;float:left;border:1px solid #DDD;background-color:#EEE;border-radius:3px;margin-left:1px; margin: 10px 5px 5px 1px;}
+.expressomail-qs-container .details-container { width:300px;height:246px; float:right; margin: 5px 0;}
+
+.expressomail-qs-container .acc-list .demo {width:100%;margin-top:20px;}
+
+.dialog-modal.expressomail-qs-container  { height: 416px; padding:5px; }
+
+.ui-dialog .ui-dialog-buttonpane { padding: 0; border:none; margin: 0;}
+.expressomail-qs-container .menu-control .ui-button-text-only .ui-button-text { padding: 0.1em 0.6em; }
+
+/* search area definition */
+fieldset.search-field, fieldset.search-catalog-options {
+	border:1px solid #CFCFCF;
+	padding: 5px;
+}
+
+fieldset.search-field input, fieldset.search-catalog-options select{
+	display: inline-block;
+	border: none;
+	background-color: #FFF;
+}
+
+fieldset.search-field span {
+	display: inline-block;
+	margin:0 0 -3px 5px;
+}
+
+/* #search area definition */
+fieldset.search-field { max-width: 190px; width: 190px; margin: 0px; text-align: left; display: inline;}
+fieldset.search-field input { max-width: 165px; width: 165px; }
+
+fieldset.search-catalog-options { max-width: 124px; width: 120px; margin: 0px; text-align: left; display: inline;}
+fieldset.search-catalog-options select { max-width: 120px; width: 120px; }
+
+
+.ui-dialog .ui-dialog-titlebar-minimize {
+    height: 18px;
+    margin: -10px 0 0;
+    padding: 1px;
+    position: absolute;
+    right: 1.8em;
+    top: 50%;
+    width: 19px;
+}
+
+.ui-dialog-buttonpane .ui-button {
+	margin-top: 0;
+	padding-top: 0;
+}
 
  
+.button-mod { margin-top: -2.5em; }
Index: trunk/expressoMail1_2/templates/default/main.css
===================================================================
--- trunk/expressoMail1_2/templates/default/main.css	(revision 4815)
+++ trunk/expressoMail1_2/templates/default/main.css	(revision 5134)
@@ -8,10 +8,10 @@
 	word-wrap: break-word !important; /* Internet Explorer 5.5+ */
 	font-family: monospace !important;	
+	/*font-size: 10pt !important;*/
 	font-size: 11px !important;
 }
-
-* {
+/** {
 	font-family: Verdana, Arial, Helvetica, sans-serif;	
-}
+}*/
 
 .checkbox{
@@ -33,5 +33,5 @@
 	background: #ffffff;
 	border-bottom: 1px solid #f4f8fb;
-	font-family: Arial;
+	font-family: Verdana, Arial, Helvetica, sans-serif;;
 	font-size: 13px;
 	cursor: pointer;
@@ -151,5 +151,5 @@
 	border-collapse: collapse;
 	border-color: #bbbbbb;
-	font-family: Arial;
+	font-family: Verdana,Arial,Helvetica,sans-serif;
 	font-size: 13px;	
 	cursor: pointer;
@@ -188,4 +188,6 @@
     -moz-border-radius: 9px 9px 0px 0px;
     -moz-user-select: none;
+    -webkit-border-radius: 9px 9px 0px 0px;
+    border-radius: 9px 9px 0px 0px;
     cursor: pointer;	
 }
@@ -202,4 +204,6 @@
     -moz-border-radius: 9px 9px 0px 0px;
     -moz-user-select: none;
+    -webkit-border-radius: 9px 9px 0px 0px;
+    border-radius: 9px 9px 0px 0px;
     cursor: pointer;
 }
@@ -223,4 +227,5 @@
 .tr_message_header{
 	background-color: #EEEEEE;
+	font-family: Verdana, Arial, Helvetica, sans-serif;
 	cursor: default;
 	border-style: none none none none;
@@ -552,7 +557,10 @@
 /* hack para o chrome */
 @media screen and (-webkit-min-device-pixel-ratio:0){
-	input[type="file"]
-	{
-		      width:500px;
+	input[type="file"]{
+	background-color: #FFF;
+	border: 1px solid #e4e4e4;
+	height: 20px;
+	width: 350px;
+	vertical-align: middle;
 	}
 }
Index: trunk/expressoMail1_2/setup/phpgw_es-es.lang
===================================================================
--- trunk/expressoMail1_2/setup/phpgw_es-es.lang	(revision 4843)
+++ trunk/expressoMail1_2/setup/phpgw_es-es.lang	(revision 5134)
@@ -596,5 +596,4 @@
 zip mails to import	expressoMail1_2	es-es	Archivo .zip o .eml:
 Show TO: in place of FROM: only in Automatic SEND folder	expressoMail1_2	es-es	Cambiar remitente por destinatário en la columna QIUEM solamente en la carpeta Enviado
-You cant manipulate messages from multiple folders on search	expressoMail1_2	es-es	Imposible manipular mensajes de varias carpetas a partir de una busqueda.
 View the user name in the header of the messages printed?	expressoMail1_2	es-es	Ver el nombre de usuario en el encabezado de los mensajes impresos?	
 Displays the user name in the header print email	expressoMail1_2	es-es	Muestra el nombre de usuario en el correo electrónico imprimir el encabezado 	
Index: trunk/expressoMail1_2/setup/phpgw_en.lang
===================================================================
--- trunk/expressoMail1_2/setup/phpgw_en.lang	(revision 4843)
+++ trunk/expressoMail1_2/setup/phpgw_en.lang	(revision 5134)
@@ -449,3 +449,2 @@
 Send this mail as text plain	expressoMail1_2	en	Send this mail as text plain
 The text format will be lost	expressoMail1_2	en	The text format will be lost
-You cant manipulate messages from multiple folders on search	expressoMail1_2	en	You cant manipulate messages from multiple folders on search
Index: trunk/expressoMail1_2/setup/phpgw_pt-br.lang
===================================================================
--- trunk/expressoMail1_2/setup/phpgw_pt-br.lang	(revision 5083)
+++ trunk/expressoMail1_2/setup/phpgw_pt-br.lang	(revision 5134)
@@ -63,4 +63,5 @@
 cannot create folder. try other folder name	expressoMail1_2	pt-br	Erro ao criar a pasta. Certifique-se de que não tentou criá-la com um nome que contém a palavra \"local_\" ou que possui algum caractere especial.
 cannot rename folder. try other folder name	expressoMail1_2	pt-br	Impossível renomear pasta, tente outro nome.
+Cannot import target event. Please check if the format is right.	expressoMail1_2	pt-br	ImpossÃ­vel importar o e-mail, Por favor cheque se o formato estÃ¡ correto.
 Caracter "#" is not allowed!	expressoMail1_2	pt-br	Caracter "#" não é permitido!
 CC	expressoMail1_2	pt-br	Com Cópia
@@ -102,4 +103,6 @@
 Delete automatically the messages in trash folder in how many days	expressoMail1_2	pt-br	Apagar automaticamente as mensagens na pasta lixeira após quantos dias
 Delete	expressoMail1_2	pt-br	Apagar
+Default font editor	expressoMail1_2	pt-br	Fonte padrão do editor
+Default font size editor	expressoMail1_2	pt-br	Tamanho de fonte padrão do editor
 Delete folder	expressoMail1_2	pt-br	Excluir pasta
 Delete trash messages after how many days?	expressoMail1_2	pt-br	Apagar mensagens após quantos dias na lixeira?
@@ -164,5 +167,5 @@
 ERROR saving your message.	expressoMail1_2	pt-br	Ocorreu um ERRO ao salvar sua mensagem.
 ERROR emptying your Spam folder.	expressoMail1_2	pt-br	Ocorreu um ERRO ao limpar sua pasta Spam.
-Everytime you receive new messages you will be informed	expressoMail1_2	pt-br	Cada vez que você receber novas mensagens que você será informado
+Everytime you receive new messages you will be informed	expressoMail1_2	pt-br	Cada vez que você receber novas mensagens você será informado
 Exclusion	expressoMail1_2	pt-br	Exclusão
 Export	expressoMail1_2	pt-br	Exportar
@@ -252,4 +255,7 @@
 Invalid signature	expressoMail1_2	pt-br	Erro indeterminado: Não foi possível validar a assinatura digital da mensagem.
 italic	expressoMail1_2	pt-br	Italico
+The %1 folder is not created. It is necessary to finish your request.	expressoMail1_2	pt-br	Sua pasta \"%1\" não está criada. É necessário criá-la para que funcione corretamente.
+ERROR saving your message. 	expressoMail1_2	pt-br	Ocorreu um ERRO ao salvar sua mensagem.
+In the local file attachments, including images, will be disregarded. To forward / reply with the attachments, please first make the reopening of the message	expressoMail1_2	pt-br	No arquivamento local os anexos, incluindo imagens, serão desconsiderados. Para encaminhar/responder com os anexos, por favor, primeiro faça o desarquivamento da mensagem
 It allow you to remove attachments from messages	expressoMail1_2	pt-br	Permite que você remova anexos de mensagens
 It allow you to send emails with important flag, but you can receive unwanted messages with important flag	expressoMail1_2	pt-br	Ela permite que você envie e-mails com sinalização de importante, mas você pode receber mensagens indesejadas com sinalização de importante
@@ -293,4 +299,5 @@
 Mark as	expressoMail1_2	pt-br	Marcar como
 Mark as Spam	expressoMail1_2	pt-br	Marcar como Spam
+Is Spam	expressoMail1_2	pt-br	Spam
 Max size	expressoMail1_2	pt-br	Tamanho máximo
 Medium	expressoMail1_2	pt-br	Médio
@@ -311,10 +318,10 @@
 Message untouched and authentic	expressoMail1_2	pt-br	Mensagem íntegra e autêntica
 Message untouched with signer different from sender	expressoMail1_2	pt-br	Mensagem Íntegra, com e-mail do signatário diferente do remetente
-message without receiver	expressoMail1_2	pt-br	Você deve fornecer pelo menos um endereço de destinatário de email.
+Message without receiver	expressoMail1_2	pt-br	Você deve fornecer pelo menos um endereço de destinatário de email.
 Message with read notification	expressoMail1_2	pt-br	Mensagem com confirmação de leitura.
 minute ago	expressoMail1_2	pt-br	minuto atrás
 minutes ago	expressoMail1_2	pt-br	minutos atrás
 Monday	expressoMail1_2	pt-br	Segunda-feira
-More actions	expressoMail1_2	pt-br	Mais ações
+More actions	expressoMail1_2	pt-br	Mais Ações
 More	expressoMail1_2	pt-br	Mais
 More options	expressoMail1_2	pt-br	Mais opções
@@ -537,9 +544,10 @@
 To use local messages, install Google Gears	expressoMail1_2	pt-br	Para utilizar mensagens locais no expresso, instale o Google Gears
 To use local messages you have to install google gears. Would you like to install it now?	expressoMail1_2	pt-br	Para utilizar o recurso de mensagens locais, é preciso instalar o Google Gears. Você gostaria de instala-lo agora mesmo?
+To use local messages you have to install google gears. Would you like to be redirected to gears installation page?	expressoMail1_2	pt-br	Para utilizar o recurso de mensagens locais, é preciso instalar o Google Gears. Você gostaria de ser encaminhado para a página de instalação do mesmo?
 Trash	expressoMail1_2	pt-br	Lixeira
 Trash Folder name	admin	pt-br	Nome da pasta lixeira
 Tuesday	expressoMail1_2	pt-br	Terça-feira
 Type the subject of the message for receiving a phone warning	expressoMail1_2	pt-br	Digite o assunto da mensagem que deseja ser alertado por telefone
-Type without spaces, dots or special characters!	expressoMail1_2	pt-br	Digite sem espaços, pontos ou caracteres especiais!
+Type without spaces, dots or special characters!	expressoMail1_2	pt-br	Digite sem pontos ou caracteres especiais!
 Unanswered/Unforwarded	expressoMail1_2	pt-br	Não Respondida/Encaminhada
 Unarchive	expressoMail1_2	pt-br	Desarquivar
@@ -563,4 +571,5 @@
 Users from your organization	expressoMail1_2	pt-br	Usuários da sua organização
 Use shortcuts?	expressoMail1_2	pt-br	Usar teclas de atalho?
+Use plain text editor with standard ?	expressoMail1_2	pt-br	Usar editor de texto simples como padrão ?
 Validity of certificate: 	expressoMail1_2	pt-br	Validade do certificado:
 View HTML source	expressoMail1_2	pt-br	Ver código html
@@ -577,8 +586,8 @@
 What is your timezone?	expressoMail1_2	pt-br	Qual o seu fuso-horário?
 When delete message, send it automatically to trash folder	expressoMail1_2	pt-br	Ao excluir um mensagem, mover automaticamente esta mensagem para a pasta lixeira
-When user send an email with image in body message, it changes the size	expressoMail1_2	pt-br	Quando o usuário envia um e-mail com a imagem no corpo da mensagem, ela muda o tamanho
+When user send an email with image in body message, it changes the size	expressoMail1_2	pt-br	Quando o usuário envia um e-mail com a imagem no corpo da mensagem ela muda o tamanho
 When you are away from computer it saves automatically the message you are writing	expressoMail1_2	pt-br	Quando você estiver longe do computador. Isto salva automaticamente a mensagem que está a escrever
-Where should the quick search be performed by default?	expressoMail1_2	pt-br	Aonde a pesquisa rápida deve atuar por padrão?
-It is where the keyword should be searched when the user executes a quick search.	expressoMail1_2	pt-br	Aonde a busca deve ser realizada quando o usuário realizar uma pesquisa rápida.
+Where should the quick search be performed by default?	expressoMail1_2	pt-br	Onde a pesquisa rápida deve atuar por padrão?
+It is where the keyword should be searched when the user executes a quick search.	expressoMail1_2	pt-br	Onde a busca deve ser realizada quando o usuário realizar uma pesquisa rápida.
 Who	expressoMail1_2	pt-br	Quem
 With all	expressoMail1_2	pt-br	com todas
@@ -617,4 +626,5 @@
 Your message to %1 has not been saved or sent. To %2 will be necessary open it again. Discard your message?	expressoMail1_2	pt-br	Sua mensagem para %1 não foi salva ou enviada. Para %2 será preciso abrir novamente. Descartar sua mensagem?
 Your message was rejected by antivirus. Perhaps your attachment has been infected.	expressoMail1_2	pt-br	Sua mensagem foi rejeitada pelo anti-virus. Seu anexo pode estar infectado.
+Invalid recipients in the message	expressoMail1_2	pt-br	Destinatario(s) invalido(s) na mensagem
 Your message was save as draft in folder %1.	expressoMail1_2	pt-br	Sua mensagem foi salva como rascunho na pasta %1.
 Your message was sent and save.	expressoMail1_2	pt-br	Sua mensagem foi enviada e salva.
@@ -622,5 +632,4 @@
 Your message was sent to queue	expressoMail1_2	pt-br	Sua mensagem foi enviada com sucesso para a fila
 Your search argument must be longer than %1 characters.	expressoMail1_2	pt-br	Seus argumentos para a pesquisa precisam ter mais que %1 dígitos.
-Your search argument must be longer than %1 characters. Use quotes to refine your search	expressoMail1_2	pt-br	Seus argumentos para a pesquisa precisam ter mais que %1 dígitos. Use aspas para refinar a sua pesquisa.
 Your session could not be verified.	expressoMail1_2	pt-br	Sua sessão expirou. Entre novamente no Expresso.
 Your Spam folder was empty.	expressoMail1_2	pt-br	Sua pasta Spam foi limpa.
@@ -646,5 +655,5 @@
 View extended information about users	expressoMail1_2	pt-br	Ver informações extendidas nas buscas por usuários?
 Do you want to use SpellChecker in email editor?	expressoMail1_2	pt-br	Quer usar o corretor ortográfico no editor de emails?
-It allow you to check the spelling of your emails	expressoMail1_2	pt-br	Possiblita a correção ortográfica de emails.
+It allow you to check the spelling of your emails	expressoMail1_2	pt-br	Possibilita a correção ortográfica de emails.
 Increases th maximum size of show messages?	expressoMail1_2	pt-br	Você quer que se aumente o limite de tamanho de emails que são mostrados?
 Increases the maximum size of show emails from 100kb to 1mb'	expressoMail1_2	pt-br	Essa opção aumenta o tamanho máximo dos emails mostrados de 100KB para 1MB.
@@ -656,8 +665,8 @@
 Warning	expressoMail1_2	pt-br	Atenção
 Discard	expressoMail1_2	pt-br	Descartar
-Send messages with return recipient option by default	expressoMail1_2	pt-br	Sempre enviar mensagens com confirmação de leitura?
-With this option every new email will get the return recipient option marked	expressoMail1_2	pt-br	Com essa opção ativa todo novo e-mail terá marcada a opção de Confirmação de leitura padrão.
-You must manualy close one of your tabs before opening a new one	expressoMail1_2	pt-br	Você deve fechar uma de suas abas de edição manualmente para poder abrir outra.
-Auto close the first tab on reaching the maximum number of tabs?	expressoMail1_2	pt-br	Fechar automáticamente a primeira aba ao atingir o número máximo de abas?
+Send messages with return recipient option by default	expressoMail1_2	pt-br	Sempre enviar mensagens com solicitação de confirmação de leitura?
+With this option every new email will get the return recipient option marked	expressoMail1_2	pt-br	Com essa opção ativa todo novo e-mail terá marcada a opção de confirmação de leitura padrão
+You must manually close one of your tabs before opening a new one	expressoMail1_2	pt-br	Você deve fechar uma de suas abas de edição manualmente para poder abrir outra
+Auto close the first tab on reaching the maximum number of tabs?	expressoMail1_2	pt-br	Fechar automaticamente a primeira aba ao atingir o número máximo de abas?
 gears firefox windows url	expressoMail1_2	pt-br	URL de instalação do Gears para o Firefox - windows
 gears firefox linux url	expressoMail1_2	pt-br	URL de instalação do Gears para o Firefox - linux
@@ -670,9 +679,9 @@
 Error exporting messages, try again latter	expressoMail1_2	pt-br	Não foi possível exportar as mensagens selecionadas.
 Exporting selected messages, this can take some time.	expressoMail1_2	pt-br	Exportando mensagens, isso pode levar algum tempo.
-You cant manipulate messages from multiple folders on search	expressoMail1_2	pt-br	Impossível manipular mensagens de múltiplas pastas a partir de uma busca.
 Report error    expressoMail1_2 pt-br   Reportar erro 
-Describe the problem to report to technical support (optional)  expressoMail1_2 pt-br   Descreva o problema para reportar para a equipe de suporte técnico (opcional) 
-Attention! The original message will be sent along with the original source of the email message        expressoMail1_2 pt-br   Atenção! A mensagem original será enviado junto com a fonte original da mensagem de e-mail
+More information about the problem (opcional)	expressoMail1_2	pt-br	Maiores informações sobre o problema (opcional)
+Attention! The information contained in the e-mail will be sent to the support team	expressoMail1_2	pt-br	Atenção! As informações do contidas no e-mail serão enviadas para a equipe de suporte
 allow hidden copy       expressoMail1_2 pt-br   Liberar todos os usuários a enviar email com cópia oculta 
+Email report error	expressoMail1_2	pt-br	Reportar erro de e-mail
 Results expressoMail1_2 pt-br   Resultados 
 Please, enter a parameter to search expressoMail1_2 pt-br   Por favor, insira um parâmetro para a busca 
@@ -685,4 +694,36 @@
 Quick Search Contacts   expressoMail1_2 pt-br   Busca rápida de contatos 
 All Catalogs    expressoMail1_2 pt-br   Todos catálogos 
-Use plain text editor with standard ?   expressoMail1_2 pt-br   Usar editor de texto simples como padrão ?
+of	expressoMail1_2	pt-br	de
+ERROR saving your message.	expressoMail1_2	pt-br	Erro ao salvar mensagem.
+Messages: add+	expressoMail1_2	pt-br	Mensagens: adicionar+
+no folder found	expressoMail1_2	pt-br	nenhuma pasta encontrada
+no folder selected	expressoMail1_2	pt-br	nenhuma pasta selecionada
+select a message to preview	expressoMail1_2	pt-br	selecione uma mensagem para pre-visualizar
+Select messages to attach...	expressoMail1_2	pt-br	Selecione mensagens para anexar...
+My folders	expressoMail1_2	pt-br	Minhas pastas
+Shared folders	expressoMail1_2	pt-br	Pastas compartilhadas
+Local folders	expressoMail1_2	pt-br	Pastas locais
+Attach	expressoMail1_2	pt-br	Anexar
+Your message have %1 characters, the message needs to have less then 10000 characters	expressoMail1_2	pt-br	Sua mensagem tem %1 caracteres, a mensagem precisa ter menos de 10 mil caracteres
+Wait a moment, your image is uploading ...	expressoMail1_2	pt-br	Espere um momento, sua imagem está sendo carregada ... 
+Reached maximum tab limit. Want to close this tab	expressoMail1_2	pt-br	Limite máximo de abas foi atingido. Deseja fechar esta aba?
+It's not possible rename this folder. try other folder name	expressoMail1_2	pt-br	Erro ao renomear a pasta. Certifique-se de que não tentou renomea-la com um nome que contém a palavra \"local_\" ou que possui algum caractere especial.
+SMTP Error: The following recipient addresses failed: %1	expressoMail1_2	pt-br	Erro de SMTP: Os endereços de destinatário a seguir falharam: %1
+The recipients addresses failed %1	expressoMail1_2	pt_br	Os destinatarios são invalidos : %1   
+Message size greater than allowed(Default rule)	expressoMail_2	pt_br	Tamanho da mensagem maior do que o permitido(Regra Padrão)
+(no subject)   	expressoMail1_2	pt_br	(sem assunto)
+Message file too big.	expressoMail1_2	pt_br	Tamanho da mensagem muito grande.
+<strong>Tip:</strong> <span>For faster save, click over the image with <em>right button</em>.</span>	expressoMail1_2	pt-br	<strong>Dica:</strong> <span>Para salvar rapidamente, clique sobre a imagem com o <em>botão direito</em> do mouse.</span>
+Shortcut: %1	expressoMail1_2	pt-br	Atalho: %1
+Open message	expressoMail1_2	pt-br	Abrir mensagem
+Simple text mode	expressoMail1_2	pt-br	Modo texto simples
+Please enter a parameter to search	expressoMail1_2	pt-br	Por favor, insira um parâmetro para a busca
+this exhibits a sample of message within the message subject column	preferences	pt-br	Exibe uma amostra da mensagem com o conteúdo da coluna Assunto
+this exhibits a sample of message within a tool-tip box	preferences	pt-br	Exibe uma amostra da mensagem em uma caixa tool-tip
+This exhibits employeenumber and ou from LDAP in searchs	preferences	pt-br	Exibe informações adicionais nas buscas do LDAP
+what is the minimum number of characters in searching contacts	preferences	pt-br	Qual é o número mínimo de caracteres ao pesquisar contatos
+Increases the maximum size of show emails from 100kb to 1mb	preferences	pt-br	Aumenta o tamanho máximo de emails mostrados de 100kb para 1mb
+How to show nested messages	preferences	pt-br	Como mostrar mensagens aninhadas
+ERROR saving your message over quota.	expressoMail1_2	pt-br	Mensagem não salva pois excede a quota.
+Display default fields on the quick search screen?	preferences	pt-br	Mostrar campos padrão na tela de busca rápida de contatos?
 
Index: trunk/expressoMail1_2/setup/tables_update.inc.php
===================================================================
--- trunk/expressoMail1_2/setup/tables_update.inc.php	(revision 4306)
+++ trunk/expressoMail1_2/setup/tables_update.inc.php	(revision 5134)
@@ -111,3 +111,13 @@
  	    return $setup_info['expressoMail1_2']['currentver']; 
  	} 
+	$test[] = '2.2.2'; 
+ 	function expressoMail1_2_upgrade2_2_2() { 
+ 	    $setup_info['expressoMail1_2']['currentver'] = '2.2.4'; 
+ 	    return $setup_info['expressoMail1_2']['currentver']; 
+ 	}
+	$test[] = '2.2.4'; 
+ 	function expressoMail1_2_upgrade2_2_4() { 
+ 	    $setup_info['expressoMail1_2']['currentver'] = '2.4.0'; 
+ 	    return $setup_info['expressoMail1_2']['currentver']; 
+ 	}
 ?>
Index: trunk/expressoMail1_2/setup/setup.inc.php
===================================================================
--- trunk/expressoMail1_2/setup/setup.inc.php	(revision 4306)
+++ trunk/expressoMail1_2/setup/setup.inc.php	(revision 5134)
@@ -12,5 +12,5 @@
 	$setup_info['expressoMail1_2']['name']      	= 'expressoMail1_2';
 	$setup_info['expressoMail1_2']['title']     	= 'Expresso Mail';
-	$setup_info['expressoMail1_2']['version']   	= '2.2.2';
+	$setup_info['expressoMail1_2']['version']   	= '2.4.0';
 	$setup_info['expressoMail1_2']['app_order'] 	= 2;
 	$setup_info['expressoMail1_2']['tables'][]		= 'phpgw_expressomail_contacts';
@@ -37,5 +37,5 @@
 	$setup_info['expressoMail1_2']['depends'][] = array(
 		'appname' => 'phpgwapi',
-		'versions' => Array('2.2')
+		'versions' => Array('2.4.0')
 	);
 ?>
Index: trunk/expressoMail1_2/controller.php
===================================================================
--- trunk/expressoMail1_2/controller.php	(revision 1738)
+++ trunk/expressoMail1_2/controller.php	(revision 5134)
@@ -8,4 +8,5 @@
 }
 require_once '../header.session.inc.php';
+require_once '../API/class.servicelocator.php';
 
 	//	Explode action from cExecuteForm function
@@ -16,15 +17,18 @@
 			$array_files = array(); 		
  			for($idx = 1; $idx <= $count_files; $idx++) { 		
- 				if($_FILES['file_'.$idx] && !$_FILES['file_'.$idx]['error'])
+ 				if(array_key_exists('file_'.$idx , $_FILES) && $_FILES['file_'.$idx] && !$_FILES['file_'.$idx]['error'])
  					$array_files[] = $_FILES['file_'.$idx]; 					 
  			}
  			$_POST['FILES'] = $array_files;
  		} 		  		
- 		list($app,$class,$method) = explode('.',@$_POST['_action']);
+		$get_p = explode('.',@$_POST['_action']);
+
  		$cExecuteFormReturn = true;
  	}
  	//	Explode action from cExecute function
- 	else if($_GET['action'])
-		list($app,$class,$method) = explode('.',@$_GET['action']);
+ 	else if(array_key_exists('action', $_GET))
+			$get_p = explode('.',@$_GET['action']);
+			
+
 	// NO ACTION
 	else
@@ -32,13 +36,13 @@
 	
 	// Load dinamically class file.
-	if($app == '$this')
-		$filename = 'inc/class.'.$class.'.inc.php';
+	if($get_p[0] == '$this')
+		$filename = 'inc/class.'.$get_p[1].'.inc.php';
 	else
-		$filename = '../'.$app.'/inc/class.'.$class.'.inc.php';
+		$filename = '../'.$get_p[0].'/inc/class.'.$get_p[1].'.inc.php';
 		
 	include_once($filename);	
 	
 	// Create new Object  (class loaded).	
-	$obj = new $class;
+	$obj = new $get_p[1];
 	
 	// Prepare parameters for execution.	
@@ -60,12 +64,15 @@
 	// if params is not empty, then class method with parameters.	
 	if($params)
-		$result = $obj -> $method($params);
+		$result = $obj -> $get_p[2]($params);
 	else 		
-		$result = $obj -> $method();
+		$result = $obj -> $get_p[2]();
 		
 	// Return result serialized.	
 	
 
-	if(!$cExecuteFormReturn)
+	if(!$cExecuteFormReturn /*&& (!$_REQUEST['isPost'])*/ )
+		if(array_key_exists(3,$get_p))
+			echo $result;
+		else
 		echo serialize($result);
 	else
Index: trunk/expressoMail1_2/inc/class.db_functions.inc.php
===================================================================
--- trunk/expressoMail1_2/inc/class.db_functions.inc.php	(revision 3018)
+++ trunk/expressoMail1_2/inc/class.db_functions.inc.php	(revision 5134)
@@ -210,7 +210,6 @@
 	
 	function get_dropdown_contacts(){
-		
-		$contacts = $this -> get_cc_contacts();
-		$groups = $this -> get_cc_groups();
+		$contacts = $this->get_cc_contacts();
+		$groups = $this->get_cc_groups();
 		
 		if(($contacts) && ($groups))
@@ -223,6 +222,5 @@
 			$stringDropDownContacts = $groups;
 					
-		if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['number_of_contacts'] &&
-			$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_dynamic_contacts']) {
+		if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_dynamic_contacts']) {
 			// Free others requests 
                         session_write_close(); 
@@ -270,7 +268,5 @@
 	{				
 		// Pesquisa os emails e ultima inserção nos contatos dinamicos.
- 		if(!$this->db->select('phpgw_expressomail_contacts','data',
-						  'id_owner ='.$this -> user_id,
-						  __LINE__,__FILE__))
+ 		if(!$this->db->select('phpgw_expressomail_contacts','data','id_owner ='.$this->user_id,__LINE__,__FILE__))
 		{
         	return $this->db->Error;
@@ -295,8 +291,29 @@
 	function update_contacts($contacts=array())
 	{			
+		
+	
+		if(!$this->db->select('phpgw_expressomail_contacts','data','id_owner ='.$this->user_id,__LINE__,__FILE__))
+        {
+            $result['dberr1'] = $this->db->Error;
+        }
+		$regs = array();
+		while($this->db->next_record())
+        {
+            $regs[] = $this->db->row();
+        }
+		$old_contatacts = array();
+		foreach($regs as $old){
+			$old_contatacts = unserialize($old['data']);
+		}
+		 
+		foreach($old_contatacts as $i => $v)
+			foreach($contacts as $ii => $vv)
+				if(trim($v['email']) == trim($vv['email']))
+					unset($old_contatacts[$i]);
+		
+		 
+		 $old_contatacts = array_merge( $old_contatacts , $contacts);		
 		// Atualiza um email nos contatos dinamicos.
-		if(!$this->db->update('phpgw_expressomail_contacts ','data=\''.serialize($contacts).'\'',
-			'id_owner ='.$this -> user_id,
-			__LINE__,__FILE__))
+		if(!$this->db->update('phpgw_expressomail_contacts ','data=\''.serialize($old_contatacts).'\'','id_owner ='.$this->user_id,__LINE__,__FILE__))
 		{
 			return $this->db->Error;
@@ -344,31 +361,43 @@
 		$msg_part = $params['msg_part'];
 		$msg_folder = $params['msg_folder'];
+            $from_ajax = $params['from_ajax'];
 		$encoding = strtolower($params['encoding']);
 		$fileContent = "";
-
-		if($msg_number && $msg_part && $msg_folder && (intval($idx_file == '0' ? '1' : $idx_file))) {
-			$mbox_stream = $objImap->open_mbox($msg_folder);   	
-			$fileContent = imap_fetchbody($mbox_stream, $msg_number, $msg_part, FT_UID);
-			include_once('class.imap_attachment.inc.php');
-			$imap_attachment = new imap_attachment();
-			$a = $imap_attachment->download_attachment($mbox_stream, $msg_number);
-			$filename = $a[$idx_file]['name'];
+            $cirus_delimiter = $params['cirus_delimiter'];
+            $expFolder = explode($cirus_delimiter, $msg_folder);
+
+            if($msg_number != null && $msg_part != null && $msg_folder != null && (intval($idx_file == '0' ? '1' : $idx_file)))
+            {
+                require_once $_SESSION['rootPath'].'/expressoMail1_2/inc/class.attachment.inc.php';
+                $attachmentObj = new attachment();
+                $attachmentObj->setStructureFromMail($msg_folder,$msg_number);
+                $fileContent = $attachmentObj->getAttachment($msg_part);
+                $info = $attachmentObj->getAttachmentInfo($msg_part);
+                $filename = $info['name'];
 		}
 		else
 			$filename = $idx_file;
 					
-		if($fileContent) {
-			if($encoding == 'base64')
-				$calendar = imap_base64($fileContent);
-			else if($encoding == 'quoted-printable')
-				$calendar = quoted_printable_decode($fileContent);
-			else
-				$calendar = $fileContent;
-		}
 		// It's necessary to access calendar method. 
+            $GLOBALS['phpgw_info']['flags']['noappheader'] = True;
+            $GLOBALS['phpgw_info']['flags']['noappfooter'] = True;
+            $GLOBALS['phpgw_info']['flags']['currentapp'] = 'calendar';
 		include_once(PHPGW_INCLUDE_ROOT.'/header.inc.php'); 
-			
 		$uiicalendar = CreateObject("calendar.uiicalendar");
-		return $uiicalendar = $uiicalendar->import_from_mail($calendar);
+
+            if(strtoupper($expFolder[0]) == 'USER' && $expFolder[1]) // IF se a conta o ical estiver em uma conta compartilhada
+            {
+                include_once('class.ldap_functions.inc.php');
+                $ldap = new ldap_functions();
+                $account['uid'] = $expFolder[1];
+                $account['uidnumber']  = $ldap->uid2uidnumber($expFolder[1]);
+                $account['mail']  = $ldap->getMailByUid($expFolder[1]);
+
+                return $uiicalendar->import_from_mail($fileContent, $from_ajax,$account);
+            }
+            else
+                return $uiicalendar->import_from_mail($fileContent, $from_ajax);
+            
+            
 	}
 
@@ -439,4 +468,144 @@
 	}
 
+	
+	/**
+     * @abstract Recupera o valor da regra padrão.
+     * @return retorna o valor da regra padrão.
+     */
+	function get_default_max_size_rule()
+	{
+		$query = "SELECT config_value FROM phpgw_config WHERE config_name = 'expressoAdmin_default_max_size'";
+		if(!$this->db->query($query))
+            return false;
+
+        $return = array();
+			
+		while($this->db->next_record())
+            array_push($return, $this->db->row());
+			
+		return $return;
+	}
+	
+	/**
+     * @abstract Recupera a regra de um usuário.
+     * @return retorna a regra que o usuário pertence. Caso o usuário não participe de nenhuma regra, retorna false.
+     */
+	function get_rule_by_user($id_user) 
+	{
+		$return = array();	
+		$query = "SELECT email_max_recipient FROM phpgw_expressoadmin_configuration WHERE email_user='$id_user' AND configuration_type='MessageMaxSize'";
+		
+		if(!$this->db->query($query))
+            return false;
+		
+		while($this->db->next_record())
+            array_push($return, $this->db->row());
+			
+		return $return;
+	}
+	
+	
+	function get_rule_by_user_in_groups($id_group)
+	{
+		$return = array();
+		$query = "SELECT email_max_recipient FROM phpgw_expressoadmin_configuration WHERE configuration_type='MessageMaxSize' AND email_user_type='G' AND email_user='".$id_group."'";
+
+		if(!$this->db->query($query))	
+			return false;	
+			
+		while($this->db->next_record())
+			array_push($return, $this->db->row());
+
+		return $return; 
+	}
+        function getMaximumRecipientsUser($pUserUID)
+        {
+
+           $query = 'SELECT email_max_recipient FROM phpgw_expressoadmin_configuration WHERE email_user = \''.$pUserUID.'\' AND configuration_type = \'LimitRecipient\' AND email_user_type = \'U\' ';
+           $this->db->query($query);
+
+           $return = array();
+
+            while($this->db->next_record())
+              $return =  $this->db->row();
+
+            return $return['email_max_recipient'];
+        }
+
+        function getMaximumRecipientsGroup($pGroupsGuidnumbers)
+        {
+           $groupsGuidNumbers = '';
+
+           foreach ($pGroupsGuidnumbers as $guidNumber => $cn)
+             $groupsGuidNumbers .= $guidNumber.', ';
+
+           $groupsGuidNumbers = substr($groupsGuidNumbers,0,-2);
+
+           $query = 'SELECT email_max_recipient FROM phpgw_expressoadmin_configuration WHERE email_user IN ('.$groupsGuidNumbers.') AND configuration_type = \'LimitRecipient\' AND email_user_type = \'G\' ';
+           $this->db->query($query);
+
+           $return = array();
+
+            while($this->db->next_record())
+              $return[] =  $this->db->row();
+
+            $maxSenderReturn = 0;
+
+            foreach ($return as $maxSender)
+            {
+                if($maxSender['email_max_recipient'] > $maxSenderReturn)
+                    $maxSenderReturn = $maxSender['email_max_recipient'];
+            }
+
+            return $maxSenderReturn;
+        }
+
+	function validadeSharedAccounts($user,$grups,$accountsMails)
+        {
+
+             $arrayMailsBlocked = array();
+
+             $query = 'SELECT * FROM phpgw_expressoadmin_configuration WHERE email_user = \''.$user.'\' AND email_recipient = \'*\'  AND configuration_type = \'InstitutionalAccountException\' AND email_user_type = \'U\' ';
+             $this->db->query($query);
+             $this->db->next_record();
+                 if($this->db->row())
+                   return $arrayMailsBlocked;
+
+            foreach ($grups as $guidNumber => $cn)
+            {
+                 $query = 'SELECT * FROM phpgw_expressoadmin_configuration WHERE email_user = \''.$guidNumber.'\' AND email_recipient = \'*\'  AND configuration_type = \'InstitutionalAccountException\' AND email_user_type = \'G\' ';
+                 $this->db->query($query);
+                 $this->db->next_record();
+                 if($this->db->row())
+                     return $arrayMailsBlocked;
+
+            }
+
+            foreach ($accountsMails as $mail)
+            {
+               
+               $blocked = true;
+
+               $query = 'SELECT * FROM phpgw_expressoadmin_configuration WHERE email_recipient = \''.$mail.'\' AND configuration_type = \'InstitutionalAccountException\' ';
+               $this->db->query($query);
+           
+                while($this->db->next_record())
+                {
+                    $row =  $this->db->row();
+                    
+                    if(($row['email_user'] == '*' ||  $row['email_user'] == $user) && ($row['email_user_type'] == 'T' || $row['email_user_type'] == 'U'))
+                        $blocked = false;
+                    else if(array_key_exists($row['email_user'], $grups) && $row['email_user_type'] == 'G')
+                         $blocked = false; 
+
+                }
+
+                if($blocked == true)
+                    array_push ($arrayMailsBlocked, $mail);
+            }
+
+            return $arrayMailsBlocked;
+        }
+
 }
 ?>
Index: trunk/expressoMail1_2/inc/class.imap_functions.inc.php
===================================================================
--- trunk/expressoMail1_2/inc/class.imap_functions.inc.php	(revision 5083)
+++ trunk/expressoMail1_2/inc/class.imap_functions.inc.php	(revision 5134)
@@ -27,6 +27,11 @@
 	var $foldersLimit;
 	var $imap_sentfolder;
+	var $rawMessage;
 
 	function imap_functions (){
+		$this->init();
+	}
+	
+	function init(){
 		$this->foldersLimit = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['imap_max_folders'] ?  $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['imap_max_folders'] : 20000; //Limit of folders (mailboxes) user can see
 	 	$this->username 	  = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
@@ -53,5 +58,5 @@
 	function open_mbox($folder = False,$force_die=true)
 	{
-		$folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
+		$folder = mb_convert_encoding($folder, "UTF7-IMAP", mb_detect_encoding($folder.'x', 'UTF-8, ISO-8859-1, UTF7-IMAP'));
 		if (is_resource($this->mbox))
                 {
@@ -80,11 +85,24 @@
 	 }
 
-	function parse_error($error){
+	function parse_error($error, $field = ''){
 		// This error is returned from Imap.
 		if(strstr($error,'Connection refused')) {
 			return str_replace("%1", $this->functions->getLang("Mail"), $this->functions->getLang("Connection failed with %1 Server. Try later."));
 		}
-		elseif(strstr($error,'virus')) {
+		else if(strstr($error,'virus')) {
 			return str_replace("%1", $this->functions->getLang("Mail"), $this->functions->getLang("Your message was rejected by antivirus. Perhaps your attachment has been infected."));
+		}
+		else if(strstr($error,'Failed to add recipient:')) {
+			preg_match_all('/:\s([\s\.";@!a-z0-9]+)\s\[SMTP:/', $error, $res);
+			return  str_replace("%1", $res['1']['0'], $this->functions->getLang("SMTP Error: The following recipient addresses failed: %1"));
+		}
+		else if(strstr($error,'Recipient address rejected')) {
+			return str_replace("%1", $this->functions->getLang("Mail"), $this->functions->getLang("Invalid recipients in the message").'.');
+		}
+		else if(strstr($error,'Invalid Mail:')) {
+			return  str_replace("%1", $field, $this->functions->getLang("The recipients addresses failed %1"));
+		}
+		else if(strstr($error,'Message file too big')) {
+			return ($this->functions->getLang("Message file too big."));
 		}
 		// This condition verifies if SESSION is expired.
@@ -102,14 +120,7 @@
 		$msg_range_begin = $params['msg_range_begin'];
 		$msg_range_end = $params['msg_range_end'];
-		$sort_box_type = $params['sort_box_type'];
-		$sort_box_reverse = $params['sort_box_reverse'];
-		$search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
-
-                $folder 			= $params['folder'];
-                $msg_range_begin	= $params['msg_range_begin'];
-                $msg_range_end		= $params['msg_range_end'];
-                $sort_box_type		= $params['sort_box_type'];
-                $sort_box_reverse	= $params['sort_box_reverse'];
-                $search_box_type	= $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
+                $sort_box_type		= isset($params['sort_box_type']) ? $params['sort_box_type'] : '';
+                $sort_box_reverse	= isset($params['sort_box_reverse']) ? $params['sort_box_reverse'] : '';
+                $search_box_type	= (isset($params['search_box_type']) && $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" )? $params['search_box_type'] : false;
 
                 if( !$this->mbox || !is_resource( $this->mbox ) )
@@ -138,5 +149,5 @@
 				{
 					$temp = $this->get_info_head_msg($msg_number);
-					//$temp['msg_sample'] = $this->get_msg_sample($msg_number,$folder);
+					$temp['msg_sample'] = $this->get_msg_sample($msg_number,$folder);
 					if(!$temp)
 						return false;
@@ -238,13 +249,18 @@
                 }
 
+		if(isset($header->from))
 		$from = $header->from;
 		$head_array['from'] = array();
 		$head_array['from']['name'] = ( isset( $from[0]->personal ) ) ? $this->decode_string($from[0]->personal) : NULL;
+		if(isset($from))
 		$head_array['from']['email'] = $this->decode_string($from[0]->mailbox) . "@" . $from[0]->host;
-		if(!$head_array['from']['name'])
+		else
+			$head_array['from']['email'] = $this->decode_string($from[0]->mailbox) . "@";
+		if(!$head_array['from']['name'] || trim($head_array['from']['name']) === '' )
 			$head_array['from']['name'] = $head_array['from']['email'];
+		if(isset($header->to))
 		$to = $header->to;
 		$head_array['to'] = array();
-		if($to[1] && $to[1]->host == ".SYNTAX-ERROR.") { //E-mails que não possuem o campo "para", vêm com o recipiente preenchido, porém com um recipiente a mais alegando erro de sintaxe.
+		if(isset($to[1]) && $to[1]->host == ".SYNTAX-ERROR.") { //E-mails que não possuem o campo "para", vêm com o recipiente preenchido, porém com um recipiente a mais alegando erro de sintaxe.
 			$head_array['to']['name'] = $head_array['to']['email'] = NULL;
 		}
@@ -256,11 +272,19 @@
 				$head_array['to']['name'] = $head_array['to']['email'];
 		}
+		$cc = null;
+		$cco = null;
+		if(isset($header->cc)){
 		$cc = $header->cc;
+		}
+		if(isset($header->bcc)){
 		$cco = $header->bcc;
+		}
 		if ( ($cc) && (!$head_array['to']['name']) ){
 			$head_array['to']['name'] = ( isset( $cc[0]->personal ) ) ? $this->decode_string($cc[0]->personal) : NULL;
 			$head_array['to']['email'] = $this->decode_string($cc[0]->mailbox) . "@" . $cc[0]->host;
-			if(!$head_array['to']['name'])
-				$head_array['to']['name'] = $head_array['from']['email'];
+			if(!$head_array['to']['name']){
+				$head_array['to']['name'] = $head_array['from']['name'];
+				//$head_array['to']['email'] = $head_array['from']['email'];
+			}
 		}
 		else if ( ($cco) && (!$head_array['to']['name']) ){
@@ -268,7 +292,15 @@
 			$head_array['to']['email'] = $this->decode_string($cco[0]->mailbox) . "@" . $cco[0]->host;
 			if(!$head_array['to']['name'])
-				$head_array['to']['name'] = $head_array['from']['email'];
+				$head_array['to']['name'] = $head_array['from']['name'];
 		}
 		$head_array['subject'] = ( isset( $header->fetchsubject ) ) ? $this->decode_string($header->fetchsubject) : '';
+		if($head_array['subject'] == "" || $head_array['subject'] == '' || $head_array['subject'] == null ){
+			$head_array['subject'] = $this->functions->getLang("(no subject)   ");
+		}
+	
+		if($head_array['to']['name'] == 'undisclosed-recipients@' || $head_array['to']['name'] == '@'){
+			$head_array['to']['name'] = $head_array['from']['name'];
+			$head_array['to']['email'] = $head_array['from']['email'];
+		}
 
 		$head_array['Size'] = $header->Size;
@@ -280,12 +312,9 @@
 	}
 
-	
 	/**
-	* Decodifica a string da mensagem
 	*
 	* @license    http://www.gnu.org/copyleft/gpl.html GPL
-	* @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
-	* @sponsor    Caixa Econômica Federal
-	* @param      $string
+	* @param      string $string String a ser decodificada
+	* @return     string
 	* @todo       Verificar a possibilidade de se utilizar a função iconv_mime_decode, que é capaz de identificar a codificação por si só, mas que pode ser interpretada de forma diversa dependendo da implementação do sistema
 	* @todo       Executar testes suficientes para validar a funçao iconv_mime_decode em substituição à este método decode_string
@@ -293,7 +322,8 @@
 	function decode_string($string)
 	{
+        $return = '';
+        $decoded = '';
 		if ((strpos(strtolower($string), '=?iso-8859-1') !== false) || (strpos(strtolower($string), '=?windows-1252') !== false))
 		{
-            $retun = '';
 			$tmp = imap_mime_header_decode($string);
 			foreach ($tmp as $tmp1)
@@ -335,6 +365,6 @@
  	 
  	    }
-        else if (eregi('=?', $string))
-            return iconv_mime_decode($string);
+        else if( strpos( $string , '=?' ) !== false ) 
+            return $this->htmlspecialchars_encode(iconv_mime_decode( $string ));
         
 
@@ -409,7 +439,20 @@
 									$email
 									);
-			if(!$status){
+			if(!$status) {
+				//TODO: remover zip_entry pois ele é tratado apenas ao importar mensagens zipadas
 				array_push($errors,zip_entry_name($zip_entry));
 				zip_entry_close($zip_entry);
+			}
+			
+			if ( isset( $tmp_box ) && ! sizeof( $errors ) ) {
+				$mc = imap_check($this->mbox);
+
+				$result = imap_fetch_overview( $this -> mbox, "1:{$mc -> Nmsgs}", 0 );
+
+				$ids = array( );
+				foreach ($result as $overview)
+					$ids[ ] = $overview -> uid;
+
+				return implode( ',', $ids );
 			}
 		}
@@ -457,5 +500,5 @@
 		}
 
-		$msg = &new message_components($this->mbox);
+		$msg = new message_components($this->mbox);
 		$msg->fetch_structure($params["msg_num"]);/* O fetchbody tava trazendo o email com problemas na acentuação.
 							     Então uso essa classe para verificar a codificação e o charset,
@@ -492,9 +535,9 @@
 					"\r\n".
 					"\r\n".
-					str_replace("\n","\r\n",$this->decodeBody(
+					str_replace("\n","\r\n",preg_replace("/<img[^>]+\>/i", " ", $this->decodeBody(
 							imap_fetchbody($this->mbox,imap_msgno($this->mbox, $params["msg_num"]),$body_part_to_show),
 							$all_body_encoding, $all_body_charset
-							)
-					), "\\Seen"); //Append do novo email, só com header e conteúdo sem anexos.
+							))
+					), "\\Seen"); //Append do novo email, só com header e conteúdo sem anexos. //Remove imagens do corpo, pois estas estão na lista de anexo e serão removidas.
 
 		if(!$status)
@@ -570,5 +613,4 @@
 			$attach_params["num_msg"] = $msg_number;
 			$msg_info['array_attach'] = $exporteml->get_attachments_in_array($attach_params);
-			$msg_info['url_export_file'] = $exporteml->export_to_archive($msg_number,$params["folder"]);
 			imap_close($this->mbox);
 			$this->mbox=false;
@@ -589,10 +631,7 @@
 
 	/**
-	* Retorna a linha do Header da mensagem
-	*
 	* @license    http://www.gnu.org/copyleft/gpl.html GPL
 	* @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
-	* @sponsor    Caixa Econômica Federal
-	* @param      $msg_number
+	* @param     $msg_number numero da mensagem
 	*/
 	function getRawHeader($msg_number)
@@ -601,12 +640,8 @@
 	}
 	
-	
 	/**
-	* Retorna a linha do Corpo da mensagem
-	*
 	* @license    http://www.gnu.org/copyleft/gpl.html GPL
 	* @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
-	* @sponsor    Caixa Econômica Federal
-	* @param      $msg_number
+	* @param     $msg_number numero da mensagem
 	*/
 	function getRawBody($msg_number)
@@ -617,10 +652,7 @@
 	
 	/**
-	* Constrói o Header da mensagem
-	*
 	* @license    http://www.gnu.org/copyleft/gpl.html GPL
 	* @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
-	* @sponsor    Caixa Econômica Federal
-	* @param      $msg
+	* @param     $msg mensagem
 	*/
 	function builderMsgHeader($msg)
@@ -654,12 +686,7 @@
 	
 	/**
-	* Constrói o corpo da mensagem
-	*
-	* @license    http://www.gnu.org/copyleft/gpl.html GPL
-	* @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
-	* @sponsor    Caixa Econômica Federal
-	* @param      $structure
-	* @param      $content
-	* @param      $printHeader
+        * Constroe o corpo da msg direto na variavel de conteudo
+        * @param Mail_mimeDecode $structure
+        * @param <type> $content Ponteiro para Variavel de conteudo da msg
 	*/
         function builderMsgBody($structure , &$content , $printHeader = false)
@@ -676,5 +703,5 @@
                     {
                        case 'text':
-                           $disposition = strtolower($part->disposition);
+                           $disposition = isset($part->disposition) ? strtolower($part->disposition) : '';
                            if($disposition != 'attachment')
                            {
@@ -694,6 +721,6 @@
                                    $content .= '<pre>'. htmlentities($this->decodeMailPart($part->body,$part->ctype_parameters['charset'],false)).'</pre>';
                                 }
-
-
+                                if(strtolower($part->ctype_secondary) == 'calendar')
+                                    $content.= $this->builderMsgCalendar($this->decodeMailPart($part->body, $part->ctype_parameters['charset']));
 
                            }
@@ -735,6 +762,7 @@
                    {
                        case 'text':
-                           
-                           $disposition = strtolower($part->disposition);
+                           $disposition = '';
+                           if(isset($part->disposition))
+                           $disposition = isset($part->disposition) ? strtolower($part->disposition) : '';
                            if($disposition != 'attachment')
                            {
@@ -754,5 +782,6 @@
                                    $content .= '<pre>'. htmlentities($this->decodeMailPart($part->body,$part->ctype_parameters['charset'],false)).'</pre>';
                                 }
-
+                                if(strtolower($part->ctype_secondary) == 'calendar')
+                                    $content .= $this->builderMsgCalendar($part->body);
                         
                            }
@@ -767,5 +796,6 @@
                             break;
                        case 'message':
-
+                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['nested_messages_are_shown'] != '1')
+                        {
                             if(!is_array($part->parts))
                             {
@@ -781,17 +811,15 @@
             }
         }
-	
+        }
 	
 	
 	/**
-	* Retorna o 
-	*
 	* @license    http://www.gnu.org/copyleft/gpl.html GPL
 	* @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
-	* @sponsor    Caixa Econômica Federal
-	* @param      $msg_number
+	* @param     $msg_number numero da mensagem
 	*/
 	function get_msg_sample($msg_number)
 	{
+        $content = '';
 
 		$return = ""; 
@@ -804,8 +832,8 @@
 
 		include_once("class.message_components.inc.php");
-		$msg = &new message_components($this->mbox);
+		$msg = new message_components($this->mbox);
 		$msg->fetch_structure($msg_number);  
 
-		if(!$msg->structure[$msg_number]->parts)
+		if(!isset($msg->structure[$msg_number]->parts))
 		{
 			$content = '';
@@ -827,16 +855,39 @@
 			}
 		}
-		$content = $this->replace_special_characters($content);
+      
 		$tags_replace = array("<br>","<br/>","<br />");
-		$content = str_replace($tags_replace," ", $content);
-		$content = strip_tags($content);
-		$content = str_replace(array("{","}","&nbsp;"), " ", $content);
-		$content = trim($content);
-		$content = html_entity_decode(substr($content,0,300));
+		$content = str_replace($tags_replace," ", nl2br($content));
+		$content = $this->html2txt($content);	
 		$content != "" ? $return['body'] = " - " . $content: $return['body'] = "";
+                $return['body'] = base64_encode(mb_convert_encoding(substr($return['body'], 0, 305),'ISO-8859-1'));
 		return $return;
 	}
+    function html2txt($document){
+        $search = array('@<script[^>]*?>.*?</script>@si',  // Strip out javascript
+                       '@<[\/\!]*?[^<>]*?>@si',            // Strip out HTML tags
+                       '@<style[^>]*?>.*?</style>@siU',    // Strip style tags properly
+                       '@<![\s\S]*?--[ \t\n\r]*>@si'         // Strip multi-line comments including CDATA                    
+        );
+        $text = preg_replace($search, '', $document);
+        return html_entity_decode($text);
+    } 
+
+    function ope_msg_part($params)
+    {
+        $return = array();
+        require_once $_SESSION['rootPath'].'/expressoMail1_2/inc/class.attachment.inc.php';
 	
+        $atObj = new attachment();
+        $atObj->setStructureFromMail($params['msg_folder'],$params['msg_number']);
+        $mbox_stream = $this->open_mbox($params['save_folder']);
+        $return['append'] = imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$params['save_folder'], $atObj->getAttachment($params['msg_part']), "\\Seen \\Draft");
+        $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$params['save_folder'], SA_UIDNEXT);
 	
+        $return['msg_folder']  = $params['save_folder'];
+        $return['msg_number'] = $status->uidnext - 1;        
+
+        return $return;
+
+    }
 	
 	function get_info_msg($params)
@@ -846,5 +897,5 @@
 		$msg_folder = urldecode($params['msg_folder']);
 		
-		if(preg_match('(.+)(_[a-zA-Z0-9]+)',$msg_number,$matches)) { //Verifies if it comes from a tab diferent of the main one. 
+		if(preg_match('/(.+)(_[a-zA-Z0-9]+)/',$msg_number,$matches)) { //Verifies if it comes from a tab diferent of the main one. 
 			$msg_number = $matches[1];
 			$plus_id = $matches[2];
@@ -879,5 +930,5 @@
 	    $return['attachments'] 	= $return_get_body['attachments'];
 	    $return['thumbs'] 		= $return_get_body['thumbs'];
-	    $return['signature']	= $return_get_body['signature'];
+	    //$return['signature']	= $return_get_body['signature'];
 		}
 		$pattern = '/^[ \t]*Disposition-Notification-To:[ ]*<?[[:alnum:]\._-]+@[[:alnum:]_-]+[\.[:alnum:]]+>?/sm';
@@ -906,20 +957,32 @@
 		$return['msg_folder'] = $msg_folder;
 
-		$date_msg = gmdate("d/m/Y",$header->udate);
-		if (date("d/m/Y") == $date_msg)
-			$return['udate'] = gmdate("H:i",$header->udate);
-		else
-			$return['udate'] = $date_msg;
+		
+		
+		$msgTimesTamp = $header->udate + $this->functions->CalculateDateOffset(); //Aplica offset do usuario
+		$date_msg = gmdate("d/m/Y",$msgTimesTamp);
+
+//      Removido codigo pois a o método send_nofication precisa da data completa.
+//		if (date("d/m/Y") == $date_msg)
+//			$return['udate'] = gmdate("H:i",$header->udate);
+//		else
+
+//      Passa o a data completa para mensagem.		
+		$return['udate'] = $header->udate;
 
 		$return['msg_day'] = $date_msg;
-		$return['msg_hour'] = gmdate("H:i",$header->udate);
+		$return['msg_hour'] = gmdate("H:i",$msgTimesTamp);
 
 		if (date("d/m/Y") == $date_msg) //no dia
 		{
-			$return['fulldate'] = gmdate("d/m/Y H:i",$header->udate);
-			$return['smalldate'] = gmdate("H:i",$header->udate);
-
-			$timestamp_now = strtotime("now") + $offset;
-			$timestamp_msg_time = $header->udate;
+			$return['fulldate'] = gmdate("d/m/Y H:i",$msgTimesTamp);
+			$return['smalldate'] = gmdate("H:i",$msgTimesTamp);
+			
+
+				$timestamp_now = strtotime("now");
+			//	removido offset nao esta sendo parametrizado
+			//	$timestamp_now = strtotime("now") + $offset;
+			
+			
+			$timestamp_msg_time = $msgTimesTamp;
 			// $timestamp_now is GMT and $timestamp_msg_time is MailDate TZ. 
 			// The variable $timestamp_diff is calculated without MailDate TZ.
@@ -945,11 +1008,11 @@
 		}
 		else{
-			$return['fulldate'] = gmdate("d/m/Y H:i",$header->udate);
-			$return['smalldate'] = gmdate("d/m/Y",$header->udate);
+			$return['fulldate'] = gmdate("d/m/Y H:i",$msgTimesTamp);
+			$return['smalldate'] = gmdate("d/m/Y",$msgTimesTamp);
 		}
 
 		$from = $header->from;
 		$return['from'] = array();
-		$return['from']['name'] = $this->decode_string($from[0]->personal);
+		$return['from']['name'] = isset($sender[0]->personal) ? $this->decode_string($from[0]->personal) : '';
 		$return['from']['email'] = $this->decode_string($from[0]->mailbox . "@" . $from[0]->host);
 		if ($return['from']['name'])
@@ -966,6 +1029,7 @@
 		$sender = $header->sender;
 		$return['sender'] = array();
-		$return['sender']['name'] = $this->decode_string($sender[0]->personal);
+		$return['sender']['name'] = isset($sender[0]->personal) ? $this->decode_string($sender[0]->personal): '';
 		$return['sender']['email'] = $this->decode_string($sender[0]->mailbox . "@" . $sender[0]->host);
+		
 		if ($return['sender']['name'])
 		{
@@ -1014,5 +1078,5 @@
 			$return['toaddress2'] = "";
 		}	
-
+		if(isset($header->cc))
 		$cc = $header->cc;
 		$return['cc'] = "";
@@ -1027,5 +1091,9 @@
 					$return['cc'] .= " ";
 					$return['cc'] .= "&lt;";
+					if ($tmp_cc->host != 'unspecified-domain')
 					$return['cc'] .= $tmp_cc->mailbox . "@" . $tmp_cc->host;
+					else
+						$return['cc'] .= $tmp_cc->mailbox;
+					//$return['cc'] .= $tmp_cc->mailbox . "@" . $tmp_cc->host;
 					$return['cc'] .= "&gt;";
 					$return['cc'] .= ", ";
@@ -1033,5 +1101,9 @@
 				else
 				{
+					if ($tmp_cc->host != 'unspecified-domain')
 					$return['cc'] .= $tmp_cc->mailbox . "@" . $tmp_cc->host;
+					else
+						$return['cc'] .= $tmp_cc->mailbox;
+					//$return['cc'] .= $tmp_cc->mailbox . "@" . $tmp_cc->host;
 					$return['cc'] .= ", ";
 				}
@@ -1049,6 +1121,7 @@
 		# @BRIEF Adding the BCC field.
 		##
-                
+        if(isset($header->bcc)){        
 		$bcc = $header->bcc;
+		}
 		$return['bcc'] = "";
 		if (!empty($bcc))
@@ -1062,5 +1135,8 @@
 					$return['bcc'] .= " ";
 					$return['bcc'] .= "&lt;";
+					if ($tmp_bcc->host != 'unspecified-domain')
 					$return['bcc'] .= $tmp_bcc->mailbox . "@" . $tmp_bcc->host;
+					else
+						$return['bcc'] .= $tmp_bcc->mailbox;
 					$return['bcc'] .= "&gt;";
 					$return['bcc'] .= ", ";
@@ -1068,5 +1144,9 @@
 				else
 				{
+					if ($tmp_bcc->host != 'unspecified-domain')
 					$return['bcc'] .= $tmp_bcc->mailbox . "@" . $tmp_bcc->host;
+					else
+						$return['bcc'] .= $tmp_bcc->mailbox;
+					//$return['bcc'] .= $tmp_bcc->mailbox . "@" . $tmp_bcc->host;
 					$return['bcc'] .= ", ";
 				}
@@ -1107,4 +1187,11 @@
 		$return['reply_to'] = $this->decode_string($return['reply_to']);
 		$return['subject'] = $this->decode_string($header->fetchsubject);
+
+		if($return['subject'] == $this->functions->getLang("(no subject)   ")){
+			$return['subject'] = str_replace(" ","", $return['subject']);
+		}
+		if($return['subject'] == '' || $return['subject'] == null){
+			$return['subject'] = $this->functions->getLang("(no subject)   ");
+		}
 		$return['Size'] = $header->Size;
 		$return['reply_toaddress'] = $header->reply_toaddress;
@@ -1115,16 +1202,19 @@
 		$return['reply_toaddress'] = $header->reply_toaddress;
                 
+		if(($return['from']['email'] ==  '@unspecified-domain' || $return['sender']['email'] == null) && $return['msg_folder'] == 'INBOX/Drafts'){
+			$return['from']['email'] = "Rascunho";
+		}
+		if($return['toaddress2'] == 'undisclosed-recipients@, @'){
+			$return['toaddress2'] = $this->functions->getLang('without destination');
+		}
 		return $return;
 	}
 
 	
- 	/**
+	/* 
 	* Converte textos utf8 para o padrão html.
-	*
-	* @license    http://www.gnu.org/copyleft/gpl.html GPL
-	* @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
-	* @sponsor    Caixa Econômica Federal
+	 * Modificado por Cristiano Corrêa Schmidt
+ 	 * @link http://php.net/manual/en/function.utf8-decode.php 
 	* @author     luka8088 <luka8088@gmail.com> 
-	* @param      $data
 	*/	
  	function utf8_to_html ($data) 
@@ -1138,20 +1228,14 @@
 		foreach((str_split(strrev(chr((ord($data{0}) % 252 % 248 % 240 % 224 % 192) + 128) . substr($data, 1)))) as $k => $v) 
 			$ret += (ord($v) % 128) * pow(64, $k); 
- 		    return "&#$ret;"; 
+ 		    return html_entity_decode("&#$ret;" , ENT_QUOTES); 
 		} 
  	//------------------------------------------------------------------------------// 
 
 
-	
-	
 		/**
-		* Decodifica a parte do email
-		*
-		* @license    http://www.gnu.org/copyleft/gpl.html GPL
-		* @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
-		* @sponsor    Caixa Econômica Federal
-		* @param      $part
-		* @param      $encode
-		* @param      $html
+         * Decodifica uma part da mensagem para iso-8859-1
+         * @param <type> $part parte do email
+         * @param <type> $encode codificação da parte
+         * @return <type> string decodificada
 		*/
         function decodeMailPart($part, $encode, $html = true)
@@ -1164,8 +1248,6 @@
 
                 case 'utf-8':
-                    if ($html) 
-						return  $this->utf8_to_html($part); 
-		else
-						return  utf8_decode ($part);
+                    if ($html) return  $this->utf8_to_html($part);
+                    else       return  utf8_decode ($part);
                     break;
 
@@ -1185,15 +1267,19 @@
             require_once $_SESSION['rootPath'].'/library/mime/mimeDecode.php';
             require_once $_SESSION['rootPath'].'/expressoMail1_2/inc/class.attachment.inc.php';
-		include_once("class.message_components.inc.php");
+            //include_once("class.message_components.inc.php");
             //--------------------------------------------------------------------//
 
             $return = array();
 
-		$msg = &new message_components($this->mbox);
-		$msg->fetch_structure($msg_number);
+//            $msg = new message_components($this->mbox);
+//            $msg->fetch_structure($msg_number);
 
             $content = '';
 
-            $rawMessageData = $this->getRawHeader($msg_number).$this->getRawBody($msg_number);
+            /* 
+            * Chamada original  $this->getRawHeader($msg_number)."\r\n".$this->getRawBody($msg_number); 
+            * Inserido replace para corrigir um bug que acontece raramente em mensagens vindas do outlook com muitos destinatarios 
+            */ 
+            $rawMessageData = str_replace("\r\n\t", '', $this->getRawHeader($msg_number))."\r\n".$this->getRawBody($msg_number); 
 
             $decoder = new Mail_mimeDecode($rawMessageData);
@@ -1202,4 +1288,6 @@
             $params['decode_bodies']  = true;
             $params['decode_headers'] = true;
+			if(array_key_exists('nested_messages_are_shown', $_SESSION['phpgw_info']['user']['preferences']['expressoMail']) && ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['nested_messages_are_shown'] == '1'))
+				$params['rfc_822bodies']  = true;
             $structure = $decoder->decode($params);
 
@@ -1227,5 +1315,5 @@
 		{
                     $return['thumbs']    = $this->get_thumbs($images,$msg_number,$msg_folder);
-			$return['signature'] = $this->get_signature($msg,$msg_number,$msg_folder);
+               // $return['signature'] = $this->get_signature($msg,$msg_number,$msg_folder);
 		}
 
@@ -1241,13 +1329,17 @@
 
                         $msg_subtype = strtolower($structure->ctype_secondary);
+                    if(isset($structure->disposition))
                         $disposition = strtolower($structure->disposition);
+                    else
+                        $disposition = '';
 
                         if(($msg_subtype == "html" || $msg_subtype == 'plain') && ($disposition != 'attachment'))
 			{
-
-
                                 if(strtolower($msg_subtype) == 'plain')
 					{ 
+                        if(isset($structure->ctype_parameters['charset']))
                                         $content = $this->decodeMailPart($structure->body, $structure->ctype_parameters['charset'],false);
+                        else
+                            $content = $this->decodeMailPart($structure->body, null,false);
 						$content = str_replace( array( '<', '>' ), array( ' #$<$# ', ' #$>$# ' ), $content ); 
 						$content = htmlentities( $content ); 
@@ -1260,13 +1352,17 @@
 								$content = $this->decodeMailPart($structure->body, $structure->ctype_parameters['charset']);
 				}
+                    if(strtolower($structure->ctype_secondary) == 'calendar')
+                           $content .= $this->builderMsgCalendar($structure->body);
 
                     break;
 
                case 'multipart':
-                    $this-> builderMsgBody($structure , $content);
+                    $this->builderMsgBody($structure , $content);
 
                     break;
 
                case 'message':
+                    if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['nested_messages_are_shown'] != 1)
+                    {
                     if(!is_array($structure->parts))
 				{
@@ -1277,15 +1373,47 @@
                                             else
                         $this->builderMsgBody($structure , $content,true);
-
+                    }
                     break;
 
+            case 'application':
+                if(strtolower($structure->ctype_secondary) == 'x-pkcs7-mime')
+                {   
+                  //  $return['body']='isCripted';
+                  // return $return;
+				  
+				  //TODO: Descartar código após atualização do módulo de segurança da SERPRO
+					$rawMessageData2 = $this->extractSignedContents($rawMessageData); 
+					if($rawMessageData2 === false){ 
+						$return['body']='isCripted'; 
+						return $return; 
+					} 
+					$decoder2 = new Mail_mimeDecode($rawMessageData2); 
+ 		            $structure2 = $decoder2->decode($params); 
+ 		            $this-> builderMsgBody($structure2 , $content);  
+ 		 
+ 		            $attachmentManager->setStructure($structure2); 
+ 		            /* 
+ 		            * Monta informações dos anexos para o cabecarios 
+ 		            */ 
+ 		            $attachments = $attachmentManager->getAttachmentsInfo(); 
+ 	                $return['attachments'] = $attachments; 
+
+ 		            //----------------------------------------------// 
+ 		 
+ 		            /* 
+	                * Monta informações das imagens 
+ 		            */ 
+ 		            $images = $attachmentManager->getEmbeddedImagesInfo(); 
+ 		            //----------------------------------------------// 
+ 		 
+ 		            if(!$this->has_cid){ 
+ 		                $return['thumbs']    = $this->get_thumbs($images,$msg_number,$msg_folder); 
+ 		                $return['signature'] = $this->get_signature($msg,$msg_number,$msg_folder); 
+ 		            }
+                }
+			///////////////////////////////////////////////////////////////////////////////////////////
                default:
                     if(count($attachments) > 0)
                        $content .= '';
-                    else 
-								{ 
-                       $content .= $this->functions->getLang('Message not supported') . '. ';
-		       $content .= $this->functions->getLang('Type') . ': ' . $structure->ctype_primary . '/' . $structure->ctype_secondary;
-								} 
                     break;
 								} 
@@ -1301,4 +1429,181 @@
 	}
 
+	
+	//TODO: Descartar código após atualização do módulo de segurança da SERPRO
+	function extractSignedContents( $data ) 
+    { 
+		$pipes_desc = array( 
+			0 => array('pipe', 'r'), 
+			1 => array('pipe', 'w') 
+	    ); 
+	 
+	    $fp = proc_open( 'openssl smime -verify -noverify -nochain', $pipes_desc, $pipes); 
+	    if (!is_resource($fp)) { 
+			return false; 
+	    } 
+	 
+	    $output = ''; 
+	 
+ 		/* $pipes[0] => writeable handle connected to child stdin 
+ 		$pipes[1] => readable handle connected to child stdout */ 
+ 	    fwrite($pipes[0], $data); 
+ 	    fclose($pipes[0]); 
+ 	 
+ 	    while (!feof($pipes[1])) { 
+			$output .= fgets($pipes[1], 1024); 
+ 	    } 
+ 	    fclose($pipes[1]); 
+ 	    proc_close($fp); 
+ 	 
+ 	    return $output; 
+ 	}
+    ///////////////////////////////////////////////////////////////////////////////////////
+    
+        function builderMsgCalendar($calendar)
+        {
+            $icalService = ServiceLocator::getService('ical');
+
+            $codificao =  mb_detect_encoding($calendar.'x', 'UTF-8, ISO-8859-1');
+            if($codificao == 'UTF-8')
+                $calendar = utf8_decode($calendar);
+
+            if($icalService->setIcal($calendar))
+            {
+                $content = '';
+
+                switch ($icalService->getMethod()) {
+
+                    case 'REPLY':
+                          include_once($_SESSION['rootPath'].'/header.inc.php');
+                          include_once($_SESSION['rootPath'].'/calendar/inc/class.boicalendar.inc.php');
+                          $boicalendar = new boicalendar();
+
+                          $ical = $icalService->getComponent('vevent');
+                          $content.= '<b>'.$this->functions->getLang('Event Calendar').'</b><br /><br />';
+                          $content.= '<span style="font-size: 12" >';
+                          $notExist = false;
+
+                          foreach ($ical['attendee'] as $attendee)
+                          {
+                                if($attendee['params']['PARTSTAT'] == 'ACCEPTED')
+                                {
+                                    if($boicalendar->updateExParticipantState($ical['uid']['value'],$attendee['value'],'ACCEPTED',$attendee['params']['CN']))
+                                    {
+                                        $content.= $this->functions->getLang('User').' ';
+                                        if($attendee['params']['CN'])
+                                            $content.= '<b>'.$attendee['params']['CN'].'</b> ';
+                                        else
+                                            $content.= '<b>'.$attendee['value'].'</b> ';
+
+                                        $content.= $this->functions->getLang('accepted your event');
+                                    }
+                                    else
+                                        $notExist = true;
+                                }
+
+                                if($attendee['params']['PARTSTAT'] == 'TENTATIVE')
+                                {
+                                    if($boicalendar->updateExParticipantState($ical['uid']['value'],$attendee['value'],'TENTATIVE',$attendee['params']['CN']))
+                                    {
+                                        $content.= $this->functions->getLang('User').' ';
+                                        if($attendee['params']['CN'])
+                                            $content.= '<b>'.$attendee['params']['CN'].'</b> ';
+                                        else
+                                            $content.= '<b>'.$attendee['value'].'</b> ';
+
+                                        if($ical['description']['value'])
+                                            $content.= ' <br /> '.str_replace('\n','<br />',nl2br($ical['description']['value']));
+                                        else
+                                            $content.= $this->functions->getLang('provisionally accepted you event');
+                                    }
+                                    else
+                                         $notExist = true;
+                                }
+
+                                if($attendee['params']['PARTSTAT'] == 'DECLINED')
+                                {
+                                    if($boicalendar->updateExParticipantState($ical['uid']['value'],$attendee['value'],'DECLINED',$attendee['params']['CN']))
+                                    {
+                                        $content.= $this->functions->getLang('User').' ';
+                                        if($attendee['params']['CN'])
+                                            $content.= '<b>'.$attendee['params']['CN'].'</b> ';
+                                        else
+                                            $content.= '<b>'.$attendee['value'].'</b> ';
+
+                                        if($ical['description']['value'])
+                                            $content.= ' <br /> '.str_replace('\n','<br />',nl2br($ical['description']['value']));
+                                        else
+                                            $content.= $this->functions->getLang('provisionally decline you event');
+                                    }
+                                    else
+                                        $notExist = true;
+                                }
+                          }
+                          if($notExist)
+                            $content.= '<b><span style="color:red">'.$this->functions->getLang('This event does not exist on its agenda').'.</span></b>';
+                          $content.= '</span><br /><br />';
+
+                        break;
+
+                      case 'CANCEL':
+
+                          $ical = $icalService->getComponent('vevent');
+                          $content.= '<b>'.$this->functions->getLang('Event Calendar').'</b><br /><br />';
+                          $content.= '<span style="font-size: 12" >';
+                          $content.= '<b><span style="color:red">'.$this->functions->getLang('Your event has been canceled').'</span></b>';
+   
+                          if($ical['description']['value'])
+                              $content.= ' <br /> <br /> '.str_replace('\n','<br />',nl2br($ical['description']['value']));
+
+                          $content.= '<br /><b>* '.$this->functions->getLang('To remove the event from your calendar to import the iCal file attached').'.</b>';
+                          $content.= '</span><br /><br />';
+                        break;
+
+                    case 'REQUEST':
+
+                        $ical = $icalService->getComponent('vevent');
+                        if($ical['dtstart']['value']['tz'] == 'Z')
+                        {
+                            $tz = $_SESSION['phpgw_info']['user']['preferences']['common']['tz_offset'];
+                            $ical['dtstart']['value']['hour'] += $tz;
+                            $ical['dtend']['value']['hour'] += $tz;
+                        }
+                        
+                        $content.= '<b>'.$this->functions->getLang('Event Calendar').'</b><br />'.
+                                   ' <br /> <b>'.$this->functions->getLang('Title').': </b>'.$ical['summary']['value'].
+                                   ' <br /> <b>'.$this->functions->getLang('Location').': </b>'.$ical['location']['value'].
+                                   ' <br /> <b>'.$this->functions->getLang('Details').': </b>'. str_replace('\n','<br />',nl2br($ical['description']['value']));
+                        $content.= ' <br /> <b>'.$this->functions->getLang('Start') . ':  </b>' . $ical['dtstart']['value']['day'] . "/" . $ical['dtstart']['value']['month']  . "/" . $ical['dtstart']['value']['year']  . " - " . $ical['dtstart']['value']['hour']  . ":" . $ical['dtstart']['value']['min'] ;
+                        $content.= ' <br /> <b>'.$this->functions->getLang('End') . ': </b>' . $ical['dtend']['value']['day'] . "/" . $ical['dtend']['value']['month']  . "/" . $ical['dtend']['value']['year']  . " - " . $ical['dtend']['value']['hour']  . ":" . $ical['dtend']['value']['min'] ;
+
+                        if($ical['organizer']['params']['CN'])
+                             $content.= ' <br /> <b>'.$this->functions->getLang('Organizer').': </b>'.$ical['organizer']['params']['CN'].' -  <a href="MAILTO:'.$ical['organizer']['value'].'">'.$ical['organizer']['value'].'</a></li>' ;
+                        else
+                             $content.= ' <br /> <b>'.$this->functions->getLang('Organizer').': </b> <a href="MAILTO:'.$ical['organizer']['value'].'">'.$ical['organizer']['value'].'</a>' ;
+
+                        if($ical['attendee'])
+                        {
+                            $att = ' <br /> <b>'.$this->functions->getLang('Participants').': </b>';
+                            $att .= '<ul> ';
+                            foreach ($ical['attendee'] as $attendee)
+                            {
+                                if($attendee['params']['CN'])
+                                    $att .= '<li>'.$attendee['params']['CN'].' -  <a href="MAILTO:'.$attendee['value'].'">'.$attendee['value'].'</a></li>'  ;
+                                else
+                                    $att .= '<li><a href="MAILTO:'.$attendee['value'].'">'.$attendee['value'].'</a></li>'  ;
+                            }
+                            $att .= '</ul> <br />'  ;
+                        }
+                        $content.= $att;
+
+                        break;
+                    default:
+                        break;
+                }
+      
+            }
+            return $content;
+        }
+        
 	function htmlfilter($body)
 	{
@@ -1454,8 +1759,11 @@
                 $image['cid'] = eregi_replace("<", "", $image['cid']);
                 $image['cid'] = eregi_replace(">", "", $image['cid']);
+				//if is Draft Ticket #1256
+				$image['cid'] = str_replace("@localhost", "@prognus.org", $image['cid']);
 				$body = eregi_replace("<br/>", "", $body);
-                $body = str_replace("src=\"cid:".$image['cid']."\"", " src=\"./inc/show_embedded_attach.php?msg_folder=$msg_folder&msg_num=$msgno&msg_part=".$image['pid']."\" ", $body);
-                $body = str_replace("src='cid:".$image['cid']."'", " src=\"./inc/show_embedded_attach.php?msg_folder=$msg_folder&msg_num=$msgno&msg_part=".$image['pid']."\" ", $body);
-                $body = str_replace("src=cid:".$image['cid'], " src=\"./inc/show_embedded_attach.php?msg_folder=$msg_folder&msg_num=$msgno&msg_part=".$image['pid']."\" ", $body);   
+				
+                $body = str_replace("src=\"cid:".$image['cid']."\"", " src=\"./inc/get_archive.php?msgFolder=$msg_folder&msgNumber=$msgno&indexPart=".$image['pid']."\" ", $body);
+                $body = str_replace("src='cid:".$image['cid']."'", " src=\"./inc/get_archive.php?msgFolder=$msg_folder&msgNumber=$msgno&indexPart=".$image['pid']."\"", $body);
+                $body = str_replace("src=cid:".$image['cid'], " src=\"./inc/get_archive.php?msgFolder=$msg_folder&msgNumber=$msgno&indexPart=".$image['pid']."\"", $body); 
 			}
 		return $body;
@@ -1474,7 +1782,13 @@
                 $body = @mb_eregi_replace("POSITION: ABSOLUTE;","",$body);
 
+		//Remove Comentario Expresso 
+				$findExpCom[] = '<!-- TAG <'; 
+				$findExpCom[] = '> Removed by ExpressoMail -->'; 
+				$body = str_replace($findExpCom, '', $body); 
+		///--------------------------------// 
+
 		// tags to be removed doe to security reasons
 		$tag_list = Array(
-			'head','blink','object','frame','iframe',
+			'blink','object','frame','iframe',
 			'layer','ilayer','plaintext','script',
 			'applet','embed','frameset','xml','xmp'
@@ -1482,6 +1796,9 @@
 
 		foreach($tag_list as $index => $tag) {
-			$body = @mb_eregi_replace("<$tag\\b[^>]*>(.*?)</$tag>", "<!-- TAG <$tag> Removed by ExpressoMail -->", $body); 
-			}
+			$body = @mb_eregi_replace("<$tag\\b[^>]*>(.*?)</$tag>", '', $body); 
+			}
+		
+		$body = @mb_eregi_replace("<meta[^>]*>", '', $body);
+		$body = @mb_eregi_replace("<base[^>]*>", '', $body); 
 		
 		//try to wrap CSS code instead of remove STYLE tags
@@ -1492,4 +1809,5 @@
 		$regs_found = array(); 
 		$tags_found = @mb_eregi("<style\b[^>]*>(.*?)</style>", $body, $regs_found);
+		$wrapper_class = 'ExpressoCssWrapper'.time();
 		
 		foreach ($regs_found as $block_found) { 
@@ -1504,4 +1822,5 @@
 			
 			$prefix = ".$wrapper_class "; 
+            if( isset($css->css[41]) && count($css->css[41] > 0))
 			foreach ($css->css[41] as $key => $value) {
 						//explode multiple selectors per block 
@@ -1541,35 +1860,18 @@
 	    //--------------------------------------------------------------------------------------------// 	
 
-		//$body = $this->replace_links($body);
-
 		//Remoção de tags <span></span> para correção de erro no firefox
-//               if($_SESSION['phpgw_session']['phpgw_app_sessions']['phpgwapi']['browser_agent']['content'] != 'IE'){
-//                   $body = mb_eregi_replace("<span><span>","",$body);
-//                   $body = mb_eregi_replace("</span></span>","",$body);
-//               }
-
-                $body = mb_ereg_replace("(<p[^>]*)(text-indent:[^>;]*-[^>;]*;)([^>]*>)","\\1\\3",$body);
-                $body = mb_ereg_replace("(<p[^>]*)(margin-right:[^>;]*-[^>;]*;)([^>]*>)","\\1\\3",$body);
-                $body = mb_ereg_replace("(<p[^>]*)(margin-left:[^>;]*-[^>;]*;)([^>]*>)","\\1\\3",$body);
-//Correção para compatibilização com Outlook, ao visualizar a mensagem 
+		//Comentado pois estes replaces geram erros no html da msg, não se pode garantir que o os </span></span> sejam realmente os fechamentos dos <span><span>.
+		//Caso realmente haja a nescessidade de remover estes spans deve ser repensado a forma de como faze-lo.
+		//		$body = mb_eregi_replace("<span><span>","",$body);
+		//		$body = mb_eregi_replace("</span></span>","",$body);
+
+		//Correção para compatibilização com Outlook, ao visualizar a mensagem
 		$body = mb_ereg_replace('<!--\[','<!-- [',$body); 
 		$body = mb_ereg_replace('&lt;!\[endif\]--&gt;', '<![endif]-->', $body);
-                $body = mb_ereg_replace('<!\[endif\]-->', '<!--[endif]--->', $body);
-		$body = str_replace("\x00", '', $body);
 		
 		return  "<div class=\"$wrapper_class\"><span>".$body.'</span></div>';
-	}
-
-
-
+
+	}
 	
-	/**
-	* Substitui os links do callback
-	*
-	* @license    http://www.gnu.org/copyleft/gpl.html GPL
-	* @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
-	* @sponsor    Caixa Econômica Federal
-	* @param      $matches
-	*/
 	function replace_links_callback($matches)  
 	{
@@ -1595,8 +1897,4 @@
 		$replacement = '<a href="://$4$5" target="_blank">$4$5</a>'; 
  	    $body = preg_replace_callback($pattern,array( &$this, 'replace_links_callback'), $body);
-		// E-mail address in the text should create a new e-mail on ExpressoMail
-		$pattern = '/( |<|&lt;|>)([A-Za-z0-9\.~?\/_=#\-]*@[A-Za-z0-9\.~?\/_=#\-]*)( |>|&gt;|<)/im'; 
-		$replacement = '$1<a href="mailto:$2">$2</a>$3';
-		$body = preg_replace( $pattern, $replacement, $body );
 
 	}
@@ -1716,20 +2014,13 @@
 	{
 
-		$thumbs_array = array();
-		$i = 0;
-
-            foreach ($images as $x => $image)
-    	{
-                 if($x && $x == 'names')
-                    continue;
-                 
-                 $img = "<img id='".$msg_folder.";;".$msg_number.";;".$i.";;".$image['pid'].";;".$image['encoding']."' title='".$this->functions->getLang("Click here do view (+)")."'src=./inc/show_thumbs.php?&msg_num=".$msg_number."&msg_folder=".$msg_folder."&msg_part=".$image['pid']." />";
-                 $href = "./inc/show_img.php?msg_num=".$msg_number."&msg_folder=".$msg_folder."&msg_part=".$image['pid'];
-				 $anchor = "<a class=\"expressomail-thumbs-link\" onMouseDown='save_image(event,this,\"".$image['type']."\")' href=\"".$href."\" onclick=\"window.open('".$href."','mywindow','width=700,height=600,scrollbars=yes');return false;\">". $img ."</a>";
-                 $thumbs_array[] = $anchor; 
-    			$i++;
+		if (!count($images)) return '';
                
+		foreach ($images as $key => $value) { 
+			$images[$key]['width']  = 160; 
+			$images[$key]['height'] = 120; 
+			$images[$key]['url']    = "inc/get_archive.php?msgFolder=".$msg_folder."&msgNumber=".$msg_number."&indexPart=".$image['pid']."&image=true"; 
     		}
-    	return $thumbs_array;
+
+		return json_encode($images); 
 	}
 
@@ -1755,9 +2046,11 @@
 		$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'];
-
+		else
+			$border_ID = '';
 		$return = array();
 
-		if ($params['get_previous_msg']){
+		if (array_key_exists('get_previous_msg' , $params) &&  $params['get_previous_msg']){
 			$return['previous_msg'] = $this->get_info_previous_msg($params);
 			// Fix problem in unserialize function JS.
@@ -1786,4 +2079,6 @@
 	{
 
+		$return = array();
+		$return['new_msgs'] = 0;
 		$folder = $params['folder'];
 		$msg_range_begin = $params['msg_range_begin'];
@@ -1799,17 +2094,36 @@
 			return array();
 
+		$return['new_msgs'] = imap_num_recent($this->mbox);
 		$num_msgs = (count($msgs_in_the_server) - imap_num_recent($this->mbox));
+
 		$msgs_in_the_client = explode(",", $msgs_existent);
 
 		$msg_to_insert  = array_diff($msgs_in_the_server, $msgs_in_the_client);
+
+		if(count($msg_to_insert) > 0 && $return['new_msgs'] == 0 && $msgs_in_the_client[0] != ""){
+			$aux = 0;
+			while(array_key_exists($aux, $msg_to_insert)){
+				if($msg_to_insert[$aux] > $msgs_in_the_client[0]){
+					$return['new_msgs'] += 1;
+				}
+				$aux++;
+			}
+		}else if(count($msg_to_insert) > 0 && $msgs_in_the_server && $msgs_in_the_client[0] != "" && $return['new_msgs'] == 0){
+			$aux = 0;
+			while(array_key_exists($aux, $msg_to_insert)){
+				if($msg_to_insert[$aux] == $msgs_in_the_server[$aux]){
+					$return['new_msgs'] += 1;
+				}
+				$aux++;
+			}
+		}else if($num_msgs < $msg_range_end && $return['new_msgs'] == 0 && count($msg_to_insert) > 0){
+			$return['tot_msgs'] = $num_msgs;
+		}
+		
 		$msg_to_delete = array_diff($msgs_in_the_client, $msgs_in_the_server);
-
 		$msgs_to_exec = array();
 		foreach($msg_to_insert as $msg_number)
 			$msgs_to_exec[] = $msg_number;
 		//sort($msgs_to_exec);
-
-		$return = array();
-                $return['new_msgs'] = imap_num_recent($this->mbox);
 		$i = 0;
 		foreach($msgs_to_exec as $msg_number)
@@ -1864,5 +2178,5 @@
 			$return[$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
 			//$return[$i]['from']['full'] ='"' . $return[$i]['from']['name'] . '" ' . '<' . $return[$i]['from']['email'] . '>';
-			if(!$return[$i]['from']['name'])
+			if(!$return[$i]['from']['name'] || trim($return[$i]['from']['name']) === '')
 				$return[$i]['from']['name'] = $return[$i]['from']['email'];
 
@@ -1873,18 +2187,33 @@
 			$to = $header->to;
 			$return[$i]['to'] = array();
+			if(isset($to[0]->personal))
 			$tmp = imap_mime_header_decode($to[0]->personal);
+			if(trim($return[$i]['to']['name']) === '')
+				$return[$i]['to']['name'] = $to[0]->mailbox . "@" . $to[0]->host;
+			else
 			$return[$i]['to']['name'] = $tmp[0]->text;
 			$return[$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
 			$return[$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
+			if(isset($header->cc))
 			$cc = $header->cc;
-			if ( ($cc) && (!$return[$i]['to']['name']) ){
+
+			if ( isset($cc) && (!$return[$i]['to']['name'] || $return[$i]['to']['name'] == '@') ){
 				$return[$i]['to']['name'] =  $cc[0]->personal;
 				$return[$i]['to']['email'] = $cc[0]->mailbox . "@" . $cc[0]->host;
 			}
-			$return[$i]['subject'] = $this->decode_string($header->fetchsubject);
-
+                        $return[$i]['subject'] = ( isset( $header->fetchsubject ) ) ? $this->decode_string($header->fetchsubject) : '';
+                        if($return[$i]['subject'] == "" || $return[$i]['subject'] == '' || $return[$i]['subject'] == null ){
+				$return[$i]['subject'] = $this->functions->getLang("(no subject)   ");
+			}
 			$return[$i]['Size'] = $header->Size;
 			$return[$i]['reply_toaddress'] = $header->reply_toaddress;
 
+			if($return[$i]['to']['email'] == '@' || $return[$i]['to']['email'] =='undisclosed-recipients@' || $return[$i]['to']['name'] =='undisclosed-recipients@'
+				|| $return[$i]['to']['name'] == null){
+				$return[$i]['to']['email'] = $return[$i]['from']['email'];
+				$return[$i]['to']['name'] = $return[$i]['from']['name'];
+				$return[$i]['to']['full'] = $return[$i]['reply_toaddress'];
+			}
+			
 			$return[$i]['attachment'] = array();
 			if (!isset($imap_attachment))
@@ -1949,14 +2278,17 @@
 	{
 		$mbox_stream = $this->open_mbox();
-		if($params && $params['onload'] && $_SESSION['phpgw_info']['expressomail']['server']['certificado']){
+		if($params &&  array_key_exists('onload', $params)   &&  $params['onload'] && $_SESSION['phpgw_info']['expressomail']['server']['certificado']){
 			$this->delete_mailbox(array("del_past" => "INBOX".$this->imap_delimiter."decifradas"));
 		}
 
 		$inbox = 'INBOX';
+		$drafts = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultDraftsFolder'];
+		$sent = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder'];
+		$spam = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSpamFolder'];
 		$trash = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder'];
-		$drafts = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultDraftsFolder'];
-		$spam = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSpamFolder'];
-		$sent = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder'];
+		if(array_key_exists('uid2cn', $_SESSION['phpgw_info']['user']['preferences']['expressoMail'] ))
 		$uid2cn = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn']; 
+		else
+			$uid2cn = false;
 		// Free others requests 
 		session_write_close(); 
@@ -1964,5 +2296,5 @@
 		$serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}"; 
 		
-		if ( $params && $params['noSharedFolders'] )
+		if ( $params && isset($params['noSharedFolders']) )
 			$folders_list = array_merge(imap_getmailboxes($mbox_stream, $serverString, 'INBOX' ), imap_getmailboxes($mbox_stream, $serverString, 'INBOX/*' ) );
 		else
@@ -1973,5 +2305,9 @@
 		$tmp = array(); 
 		$resultMine = array(); 
+		$resultSharedMine = array(); 
 		$resultDefault = array(); 
+		$resultSharedDefault = array(); 
+		$aux = "";
+		$qtd = -1 ;
 
 		if (is_array($folders_list)) {
@@ -1994,9 +2330,6 @@
                             if( $folderUser != "INBOX" && $folderUser != "" )
                             {
-                               $Permission = imap_getacl( $mbox_stream, $folderUser );
+                               $Permission = @imap_getacl( $mbox_stream, $folderUser );
                             }
-
-                            if( $Permission )
-                            {
                                 $tmp_folder_id[1] = mb_convert_encoding( $tmp_folder_id[1], "ISO-8859-1", "UTF7-IMAP" );
 
@@ -2005,5 +2338,8 @@
 					continue;
 				}
+				
+				if(isset($status->unseen))
 				$result[$i]['folder_unseen'] = $status->unseen;
+				
 				$folder_id = $tmp_folder_id[1];
 				$result[$i]['folder_id'] = $folder_id;
@@ -2027,15 +2363,37 @@
 				else
 					$result[$i]['folder_hasChildren'] = 0;
-
+				$user = explode($this->imap_delimiter , $tmp_folder_id[1]);
 				switch ($tmp_folder_id[1]) {
 					case $inbox:
+					case $drafts:
 					case $sent:
-					case $drafts:
 					case $spam:
 					case $trash:
 						$resultDefault[]=$result[$i];
 						break;
+					case "user". $this->imap_delimiter . $user[1]:
+					case "user". $this->imap_delimiter . $user[1] . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultDraftsFolder']:
+					case "user". $this->imap_delimiter . $user[1] . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder']:
+					case "user". $this->imap_delimiter . $user[1] . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSpamFolder']:
+					case "user". $this->imap_delimiter . $user[1] . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder']:
+						if($aux != $user[1]){
+							$aux = $user[1];
+							$qtd += 1;
+						}
+						if( isset($resultSharedDefault[$qtd]) && !is_array($resultSharedDefault[$qtd]))
+							$resultSharedDefault[$qtd] = array();
+						$resultSharedDefault[$qtd][]=$result[$i];
+						break;	
 					default:
+						if($user[0] == $inbox)
 						$resultMine[]=$result[$i];
+						else{
+							if($aux != $user[1]){
+								$aux = $user[1];
+								$qtd += 1;
+							}
+							if(!is_array($resultSharedDefault[$qtd]))
+								$resultSharedMine[$qtd] = array();
+							$resultSharedMine[$qtd][]=$result[$i];
 				}
 
@@ -2045,8 +2403,8 @@
 		}
 
-		if ( $params && !$params['noQuotaInfo'] ) {
+		if ( $params && !array_key_exists('noQuotaInfo',$params) ) {
 			//Get quota info of current folder
 			$current_folder = "INBOX";
-			if($params && $params['folder'])
+			if($params && isset($params['folder']))
 				$current_folder = $params['folder'];
 
@@ -2078,8 +2436,8 @@
 					$resultDefault2[0] = $resultDefault[$key];
 					break;
-				case $sent: 
+				case $drafts: 
 					$resultDefault2[1] = $resultDefault[$key];
 					break;
-				case $drafts: 
+				case $sent: 
 					$resultDefault2[2] = $resultDefault[$key];
 					break;
@@ -2093,13 +2451,45 @@
 		}
 		
-		if ( $params && $params['folderType'] && $params['folderType'] == 'default' )
+		$shareds = array();
+		if(!empty($resultSharedDefault))
+		for($i = 0; $i <= $qtd; $i++){			
+			foreach ($resultSharedDefault[$i] as $key => $folder_id)
+			{
+				$user = explode($this->imap_delimiter , $resultSharedDefault[$i][$key]['folder_id']);
+
+				switch ($resultSharedDefault[$i][$key]['folder_id']) {
+					case "user". $this->imap_delimiter . $user[1]: 
+						$resultSharedDefault2[0] = $resultSharedDefault[$i][$key];
+						break;
+					case "user". $this->imap_delimiter . $user[1]. $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultDraftsFolder']:  
+						$resultSharedDefault2[1] = $resultSharedDefault[$i][$key];
+						break;	
+					case "user". $this->imap_delimiter . $user[1]. $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder']:  
+						$resultSharedDefault2[2] = $resultSharedDefault[$i][$key];
+						break;
+					case "user". $this->imap_delimiter . $user[1]. $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSpamFolder']:  
+						$resultSharedDefault2[3] = $resultSharedDefault[$i][$key];
+						break;
+					case "user". $this->imap_delimiter . $user[1] . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder']:
+						$resultSharedDefault2[4] = $resultSharedDefault[$i][$key];
+						break;
+				}
+			}
+			if($resultDefault2 != null)
+				$shareds = array_merge($shareds, $resultSharedDefault2);
+			if(isset($resultSharedMine[$i]) && $resultSharedMine[$i] != null)
+				$shareds = array_merge($shareds, $resultSharedMine[$i]);
+			$resultSharedDefault2 = array();
+		}
+		if ( $params && isset($params['folderType']) && $params['folderType'] == 'default' )
 			return array_merge($resultDefault2, $arr_quota_info);
 
-		if ( $params && $params['folderType'] && $params['folderType'] == 'personal' )
+		if ( $params && array_key_exists('folderType', $params) && $params['folderType'] == 'personal' )
 			return array_merge($result2, $arr_quota_info);
 
 		// Merge default folders and personal
 		$result2 = array_merge($resultDefault2, $result2);
-		
+		if(!empty($shareds))
+			$result2 = array_merge($result2, $shareds);
 		return array_merge($result2, $arr_quota_info);
 	}
@@ -2214,9 +2604,12 @@
 	function send_mail($params)
 	{
-		include_once("class.phpmailer.php");
-		$mail = new PHPMailer();
+		require_once $_SESSION['rootPath'] . '/API/class.servicelocator.php';
+		$mailService = ServiceLocator::getService('mail');
+
 		include_once("class.db_functions.inc.php");
 		$db = new db_functions();
 		$fromaddress = $params['input_from'] ? explode(';',$params['input_from']) : "";
+		$message_attachments_contents = (isset($params['message_attachments_content'])) ? $params['message_attachments_content'] : false; 
+		
 		##
 		# @AUTHOR Rodrigo Souza dos Santos
@@ -2238,4 +2631,14 @@
 		$ccaddress = implode(',',$db->getAddrs(explode(',',$params['input_cc'])));
 		$ccoaddress = implode(',',$db->getAddrs(explode(',',$params['input_cco'])));
+
+		$toaddress  = preg_replace('/<\s+/', '<', $toaddress);			
+		$toaddress  = preg_replace('/\s+>/', '>', $toaddress);
+			
+		$ccaddress  = preg_replace('/<\s+/', '<', $ccaddress);
+		$ccaddress  = preg_replace('/\s+>/', '>', $ccaddress);
+		
+		$ccoaddress = preg_replace('/<\s+/', '<', $ccoaddress);
+		$ccoaddress = preg_replace('/\s+>/', '>', $ccoaddress);
+		
 		$replytoaddress = $params['input_replyto'];
 		$subject = $params['input_subject'];
@@ -2246,5 +2649,114 @@
 		$signed = $params['input_return_digital'];
 
-		if($params['smime'])
+		$message_attachments = $params['message_attachments'];
+                 
+                if(substr($params['input_to'],-1) == ',')
+                    $params['input_to'] = substr($params['input_to'],0,-1);
+
+                if(substr($params['input_cc'],-1) == ',')
+                    $params['input_cc'] = substr($params['input_cc'],0,-1);
+
+                if(substr($params['input_cco'],-1) == ',')
+                    $params['input_cco'] = substr($params['input_cco'],0,-1);
+                
+
+                // Valida numero Maximo de Destinatarios 
+                if($_SESSION['phpgw_info']['expresso']['expressoMail']['expressoAdmin_maximum_recipients'] > 0) 
+                { 
+                    $sendersNumber = count(explode(',',$params['input_to'])); 
+
+                    if($params['input_cc']) 
+                        $sendersNumber +=  count(explode(',',$params['input_cc'])); 
+                    if($params['input_cco']) 
+                        $sendersNumber +=  count(explode(',',$params['input_cco'])); 
+
+                    $userMaxmimumSenders = $db->getMaximumRecipientsUser($this->username); 
+                    if($userMaxmimumSenders) 
+                    { 
+                        if($sendersNumber > $userMaxmimumSenders) 
+                            return $this->functions->getLang('Number of recipients greater than allowed'); 
+                    } 
+                    else 
+                    { 
+                        $ldap = new ldap_functions(); 
+                        $groupsToUser = $ldap->get_user_groups($this->username); 
+
+                        $groupMaxmimumSenders = $db->getMaximumRecipientsGroup($groupsToUser); 
+
+                        if($groupMaxmimumSenders > 0) 
+                        { 
+                            if($sendersNumber > $groupMaxmimumSenders) 
+                                return $this->functions->getLang('Number of recipients greater than allowed'); 
+                        } 
+                        else 
+                        { 
+                             if($sendersNumber > $_SESSION['phpgw_info']['expresso']['expressoMail']['expressoAdmin_maximum_recipients']) 
+                             return $this->functions->getLang('Number of recipients greater than allowed'); 
+                        } 
+                    } 
+
+                } 
+                //Fim Valida numero maximo de destinatarios 
+                
+                
+                //Valida envio de email para shared accounts
+                if($_SESSION['phpgw_info']['expresso']['expressoMail']['expressoMail_block_institutional_comunication'] == 'true')
+                {
+                    $ldap = new ldap_functions();
+                    $arrayF = explode(';', $params['input_from']);
+
+                    /*
+                     * Verifica se o remetente n?o ? uma conta compartilhada
+                     */
+                    if(!$ldap->isSharedAccountByMail($arrayF[1]))
+                    {
+                        $groupsToUser = $ldap->get_user_groups($this->username);
+                        $sharedAccounts = $ldap->returnSharedsAccounts($toaddress, $ccaddress, $ccoaddress);
+
+                        /*
+                         * Pega o UID do remetente
+                         */
+                        $uidFrom = $ldap->mail2uid($arrayF[1]);
+
+                         /*
+                         * Remove a conta compartilhada caso o uid do remetente exista na conta compartilhada
+                         */
+                        foreach ($sharedAccounts as $key => $value)
+                        {
+                            if($value)
+                                 $acl = $this->getaclfrombox($value);
+
+                             if (array_key_exists($uidFrom, $acl))
+                                 unset($sharedAccounts[$key]);
+
+                        }
+
+                        /*
+                         * Caso ainda exista contas compartilhadas, verifica se existe alguma exce??o para estas contas
+                         */
+                        if(count($sharedAccounts) > 0)
+                          $accountsBlockeds = $db->validadeSharedAccounts($this->username, $groupsToUser, $sharedAccounts);
+
+                        /*
+                         * Retorna as contas compartilhadas bloqueadas
+                         */
+                        if(count($accountsBlockeds) > 0)
+                        {
+                            $return = '';
+
+                            foreach ($accountsBlockeds as $accountBlocked)
+                                $return.= $accountBlocked.', ';
+
+                             $return = substr($return,0,-2);
+
+                             return $this->functions->getLang('you are blocked  from sending mail to the following addresses').': '.$return;
+                        }
+                    }
+                }
+                // Fim Valida envio de email para shared accounts
+                
+                
+//	    TODO - implementar tratamento SMIME no novo serviço de envio de emails e retirar o AND false abaixo
+	    if($params['smime'] AND false)
         {
             $body = $params['smime'];
@@ -2285,9 +2797,8 @@
         else
         {
-            $body = $params['body'];
 	    //Compatibilização com Outlook, ao encaminhar a mensagem
-	    $body = mb_ereg_replace('<!--\[','<!-- [',$body);
+			$body = mb_ereg_replace('<!--\[', '<!-- [', $params['body']);
         }
-		//echo "<script language=\"javascript\">javascript:alert('".$body."');</script>";
+
 		$attachments = $_FILES;
 		$forwarding_attachments = $params['forwarding_attachments'];
@@ -2298,56 +2809,58 @@
 			//build shared folder path
 			$newfolder = "user".$this->imap_delimiter.$fromaddress[3].$this->imap_delimiter.$this->imap_sentfolder;
-			if( $this->folder_exists($newfolder) ) $folder = $newfolder;
-			else $folder =  $params['folder'];  			
+			if($this->folder_exists($newfolder)) 
+				$folder = $newfolder;
+			else 
+				$folder = $params['folder'];
+			
 		} else	{
 			$folder = $params['folder'];			
 		}
 		
-		$folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
+		$folder = mb_convert_encoding($folder, 'UTF7-IMAP','ISO_8859-1');
+		$folder = preg_replace('/INBOX[\/.]/i', 'INBOX'.$this->imap_delimiter, $folder);
 		$folder_name = $params['folder_name'];
-		// Fix problem with cyrus delimiter changes.
-		// Dots in names: enabled/disabled.
-		$folder = @eregi_replace("INBOX/", "INBOX".$this->imap_delimiter, $folder);
-		$folder = @eregi_replace("INBOX.", "INBOX".$this->imap_delimiter, $folder);
-		// End Fix.
-		if ($folder != 'null'){
-			$mail->SaveMessageInFolder = $folder;
-		}
-////////////////////////////////////////////////////////////////////////////////////////////////////
-		$mail->SMTPDebug = false;
-
-		if($signed && !$params['smime'])
+
+//		TODO - tratar assinatura e remover o AND false
+		if($signed && !$params['smime'] AND false)
 		{
             $mail->Mailer = "smime";
 			$mail->SignedBody = true;
 		}
-		else
-            $mail->IsSMTP();
-
-		$mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
-		$mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
-		$mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
-		$mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
-		if($fromaddress){
-			$mail->Sender = $mail->From;
-			$mail->SenderName = $mail->FromName;
-			$mail->FromName = $fromaddress[0];
-			$mail->From = $fromaddress[1];
-		}
-
-		$this->add_recipients("to", $toaddress, &$mail);
-		$this->add_recipients("cc", $ccaddress, &$mail);
+
+
+		if($fromaddress)
+                	$mailService->setFrom ('"'.$fromaddress[0].'" <'.$fromaddress[1].'>');
+               else
+                	$mailService->setFrom ('"'.$_SESSION['phpgw_info']['expressomail']['user']['firstname'].' '.$_SESSION['phpgw_info']['expressomail']['user']['lastname'].'" <'.$_SESSION['phpgw_info']['expressomail']['user']['email'].'>');
+		//$mailService->addTo($toaddress);
+		//$mailService->addCc($ccaddress);
+		$bol = $this->add_recipients('to', $toaddress, $mailService);
+		if(!$bol){
+			return $this->parse_error("Invalid Mail:", $toaddress);
+		}
+		$bol = $this->add_recipients('cc', $ccaddress, $mailService);
+		if(!$bol){
+			return $this->parse_error("Invalid Mail:", $ccaddress);
+		}
 		$allow = $_SESSION['phpgw_info']['server']['expressomail']['allow_hidden_copy']; 
  		 
- 		                if( $allow ) 
+		if($allow) 
  		                { 
-		$this->add_recipients("cco", $ccoaddress, &$mail);
+			//$mailService->addBcc($ccoaddress);
+			$bol = $this->add_recipients('cco', $ccoaddress, $mailService);
+
+			if(!$bol){
+				return $this->parse_error("Invalid Mail:", $ccoaddress);
+			}
  		                }
-		$mail->AddReplyTo($replytoaddress);
-		$mail->Subject = $subject;
-		$mail->IsHTML( ( array_key_exists( 'type', $params ) && in_array( strtolower( $params[ 'type' ] ), array( 'html', 'plain' ) ) ) ? strtolower( $params[ 'type' ] ) != 'plain' : true );
-		$mail->Body = $body;
-
-        if (($encrypt && $signed && $params['smime']) || ($encrypt && !$signed))	// a msg deve ser enviada cifrada...
+
+		$mailService->setSubject($subject);
+		$isHTML = ( (array_key_exists('type', $params) && in_array(strtolower($params['type']), array('html', 'plain')) ) ? 
+						strtolower($params['type']) != 'plain' : true );
+	
+
+//		TODO - tratar mensagem criptografada e remover o AND false abaixo
+        if (($encrypt && $signed && $params['smime']) || ($encrypt && !$signed) AND false)	// a msg deve ser enviada cifrada...
 		{
 			$email = $this->add_recipients_cert($toaddress . ',' . $ccaddress. ',' .$ccoaddress);
@@ -2440,6 +2953,7 @@
             $mail->Certs_crypt = $aux_mails;
         }
-                // Build CID images 
-		$this->buildEmbeddedImages($mail,$msg_uid,$forwarding_attachments); 
+						
+		if( count($forwarding_attachments) > 0 )// Build CID images 
+			$this->buildEmbeddedImages($mailService,$msg_uid,$forwarding_attachments, $body); 
 
 		//	Build Uploading Attachments!!!
@@ -2447,5 +2961,4 @@
 		{
 			$total_uploaded_size = 0;
-			$upload_max_filesize = str_replace("M","",$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size']) * 1024 * 1024;
 			foreach ($attachments as $attach)
 			{
@@ -2454,8 +2967,12 @@
 				if($attach['name']=='Unknown')
 					continue;
-				$mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));  // optional name
+				$mailService->addFileAttachment($attach['tmp_name'], $attach['name'], $this->get_file_type($attach['name']), 'base64', 'attachment');
 				$total_uploaded_size = $total_uploaded_size + $attach['size'];
 			}
-			if( $total_uploaded_size > $upload_max_filesize){
+                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size'])
+                        {
+         
+                            $upload_max_filesize = str_replace('M','',$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size']) * 1024 * 1024;
+                            if( $total_uploaded_size > $upload_max_filesize)
 				return $this->parse_error("message file too big");
 			}
@@ -2464,5 +2981,5 @@
 
 			$total_uploaded_size = 0;
-			$upload_max_filesize = str_replace("M","",ini_get('upload_max_filesize')) * 1024 * 1024;
+			
 			foreach($local_attachments as $local_attachment) {
 				$file_description = unserialize(rawurldecode($local_attachment));
@@ -2471,11 +2988,15 @@
 					$tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
 				}
-				$mail->AddAttachment($_FILES[$tmp[1]]['tmp_name'], $tmp[2], "base64", $this->get_file_type($tmp[2]));  // optional name
+				$mailService->addFileAttachment($_FILES[$tmp[1]]['tmp_name'], $tmp[2], $this->get_file_type($tmp[2]), 'base64', 'attachment');
 				$total_uploaded_size = $total_uploaded_size + $_FILES[$tmp[1]]['size'];
 			}
-			if( $total_uploaded_size > $upload_max_filesize)
-				return 'false';
-		}
-////////////////////////////////////////////////////////////////////////////////////////////////////
+			if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size'])
+                        {
+                            $upload_max_filesize = str_replace('M','',$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size']) * 1024 * 1024;
+                            if( $total_uploaded_size > $upload_max_filesize)
+                                   return $this->parse_error("message file too big");
+                        }
+		}
+
 		//	Build Forwarding Attachments!!!
 		if (count($forwarding_attachments) > 0)
@@ -2490,34 +3011,157 @@
 			foreach($forwarding_attachments as $forwarding_attachment)
 			{
-					$file_description = unserialize(rawurldecode($forwarding_attachment));
-					$tmp = array_values($file_description);
-					foreach($file_description as $i => $descriptor){
-						$tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
+				$file_description = unserialize(rawurldecode($forwarding_attachment));
+				$tmp = array_values($file_description);
+				foreach($file_description as $i => $descriptor){
+					$tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
+				}
+				$file_description = $tmp;
+				$fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
+				$fileName = $file_description[2];
+				if(!array_search(trim($fileName),$name_cid_files)) {
+					$filename_dec = html_entity_decode(rawurldecode($fileName));
+					$mailService->addStringAttachment($fileContent, $filename_dec, $this->get_file_type($file_description[2]), $file_description[4] );
+
+				}
+			}
+		}
+		
+		//Build Message Attachments!!!
+		if(count($message_attachments) > 0 ) 
+		{
+			foreach($message_attachments as $folder_name => $messages)
+			{
+				foreach ($messages as $message_number => $message_subject) 
+				{
+					if (!$message_subject)
+						$message_subject  = 'no title.eml';
+					else 
+						$message_subject .= '.eml';
+					
+					if( $message_attachments_contents &&  isset($message_attachments_contents[$folder_name]) )
+						$rawmsg = base64_decode( $message_attachments_contents[$folder_name][$message_number] );
+					else{
+						$mbox_stream = $this->open_mbox($folder_name);
+						$rawmsg = $this->getRawHeader($message_number) . "\r\n\r\n" . $this->getRawBody($message_number);
 					}
-					$file_description = $tmp;
-					$fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
-					$fileName = $file_description[2];
-					if(!array_search(trim($fileName),$name_cid_files)) {
-						$mail->AddStringAttachment($fileContent,html_entity_decode(rawurldecode($fileName)), $file_description[4], $this->get_file_type($file_description[2]));
-				}
-			}
-		}
-
-////////////////////////////////////////////////////////////////////////////////////////////////////
-		// Important message
+							
+					$return_forward[] = array( 'name' => $message_subject, 'size' => mb_strlen($rawmsg));
+					$mailService->addStringAttachment($rawmsg, $message_subject, 'message/rfc822', '7bit', 'attachment' );
+				}
+			}
+		}
+		
+		$message_size_total += strlen($params['body']);   /* Tamanho do corpo da mensagem. */
+		$message_size_total += $total_uploaded_size;      /* Incrementa com os anexos da nova mensagem, se houver. */
+		
+		////////////////////////////////////////////////////////////////////////////////////////////////////	
+		/** 
+		* Faz a validação pelo tamanho máximo de mensagem permitido para o usuário. Se o usuário não estiver em nenhuma regra, usa o tamanho padrão.
+		 */
+		$default_max_size_rule = $db->get_default_max_size_rule();	
+		if(!$default_max_size_rule)
+		{
+			$default_max_size_rule = str_replace("M","",ini_get('upload_max_filesize')) * 1024 * 1024; /* hack para não bloquear o envio de email quando não for configurado um tamanho padrão */
+		}
+		else
+		{
+			foreach($default_max_size_rule as $i=>$value)
+			{		
+				$default_max_size_rule = $value['config_value'];
+			}				
+		}
+		
+		$default_max_size_rule = $default_max_size_rule * 1024 * 1024;		  /* Tamanho da regra padrão, em bytes */
+		$id_user = $_SESSION['phpgw_info']['expressomail']['user']['userid'];	
+		
+		
+		$ldap = new ldap_functions();
+		$groups_user = $ldap->get_user_groups($id_user);
+
+		$size_rule_by_group = array();	
+		foreach($groups_user as $k=>$value_)
+		{	
+			$rule_in_group = $db->get_rule_by_user_in_groups($k);
+			if ($rule_in_group != "")
+				array_push($size_rule_by_group, $rule_in_group);
+		}	
+		
+		$n_rule_groups = 0;
+		$maior_valor_regra_grupo = 0;
+		foreach($size_rule_by_group as $i=>$value)
+		{
+			if(is_array($value[0]))
+			{
+				$n_rule_groups++;
+				if($value[0]['email_max_recipient'] > $maior_valor_regra_grupo)
+					$maior_valor_regra_grupo = $value[0]['email_max_recipient'];
+			}
+		}
+		
+		if($default_max_size_rule)
+		{
+			$size_rule = $db->get_rule_by_user($_SESSION['phpgw_info']['expressomail']['user']['userid']);
+
+			if(!$size_rule && $n_rule_groups == 0) /* O usuário não está em nenhuma regra por usuário nem por grupo. Vai usar a regra padrão. */
+			{
+				if($message_size_total > $default_max_size_rule)
+					return $this->functions->getLang("Message size greateruler than allowed (Default rule)");
+			}
+
+			else 
+			{
+				if(count($size_rule) > 0) /* Verifica se existe regra por usuário. Se houver, ela vai se sobresair das regras por grupo. */
+				{
+					$regra_mais_permissiva = 0;
+					foreach($size_rule as $i=>$value)
+					{	
+						if($regra_mais_permissiva < $value['email_max_recipient'])
+							$regra_mais_permissiva = $value['email_max_recipient'];
+					}
+					$regra_mais_permissiva = $regra_mais_permissiva * 1024 * 1024;			
+					if($message_size_total > $regra_mais_permissiva)
+						return $this->functions->getLang("Message size greater than allowed (Rule By User)");
+				}
+				else /* Regra por grupo */
+				{		
+					$maior_valor_regra_grupo = $maior_valor_regra_grupo * 1024 * 1024;			
+					if($message_size_total > $maior_valor_regra_grupo)
+						return $this->functions->getLang("Message size greater than allowed (Rule By Group)");	
+				
+				
+				}
+			}
+		}
+		/** 
+         * Fim da validação do tamanho da regra do tamanho de mensagem.
+		 */
+		 ////////////////////////////////////////////////////////////////////////////////////////////////////
+		
+		
+		
+		
+		
+		if($isHTML)
+			$mailService->setBodyHtml($body);
+		else
+			$mailService->setBodyText($body);
+
 		if($is_important)
-			$mail->isImportant();
-
-////////////////////////////////////////////////////////////////////////////////////////////////////
-		// Disposition-Notification-To
-		if ($return_receipt)
-			$mail->ConfirmReadingTo = $_SESSION['phpgw_info']['expressomail']['user']['email'];
-////////////////////////////////////////////////////////////////////////////////////////////////////
-
-		$sent = $mail->Send();
-
-		if(!$sent)
-		{
-   			return $this->parse_error($mail->ErrorInfo);
+			$mailService->addHeaderField('Importance','High');
+
+		if($return_receipt)
+			$mailService->addHeaderField('Disposition-Notification-To', $_SESSION['phpgw_info']['expressomail']['user']['email']);
+
+
+		if ($folder != 'null'){
+			$mbox_stream = $this->open_mbox($folder);
+			@imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, $mailService->getMessage(), "\\Seen");
+		}
+
+		$sent = $mailService->send();
+
+		if($sent !== true)
+		{
+   			return $this->parse_error($sent);
 		}
 		else
@@ -2536,6 +3180,5 @@
    				error_log("$now - $userip - $sent [$subject] - $userid => $addrs\r\n", 3, "/home/expressolivre/mail_senders.log");
 			}
-			if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['number_of_contacts'] &&
-		   	   $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_dynamic_contacts']) {
+			if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_dynamic_contacts']) {
 				$contacts = new dynamic_contacts();
 				$new_contacts = $contacts->add_dynamic_contacts($toaddress.",".$ccaddress.",".$ccoaddress);
@@ -2554,43 +3197,46 @@
 	* @param     $forwarding_attachments anexos
 	*/
-	function buildEmbeddedImages(&$mail,$msg_uid,&$forwarding_attachments) 
+
+	function buildEmbeddedImages(&$mail,$msg_uid,&$forwarding_attachments ,&$body)
 	{ 
-		//      Build CID for embedded Images!!! 
-		$pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&(amp;)?msg_num=(.+)?&(amp;)?msg_part=(.+)?)"/isU'; 
+		//Procura e retorna em $cids_imgs imagens embarcadas no corpo do e-mail
+		$pattern = '/src=("[^"]*?get_archive.php\?msgFolder=(.+)?&(amp;)?msgNumber=(.+)?&(amp;)?indexPart=(.+)?")/isU';
 		$cid_imgs = ''; 
-		preg_match_all($pattern,$mail->Body,$cid_imgs,PREG_PATTERN_ORDER); 
-		$cid_array = array(); 
-
-		foreach($cid_imgs[6] as $j => $val){ 
-			if ( !array_key_exists($cid_imgs[4][$j].$val, $cid_array) ) 
-			{ 
-				$cid_array[$cid_imgs[4][$j].$val] = base_convert(microtime(), 10, 36); 
-			} 
-			$cid = $cid_array[$cid_imgs[4][$j].$val];  
-
-			$mail->Body = str_replace($cid_imgs[1][$j], "cid:".$cid, $mail->Body); 
-
+		preg_match_all( $pattern , $body , $cid_imgs , PREG_PATTERN_ORDER );
+		//-------------------------------------------------------------------//
+
+		$attPostions = array(); //Array que linka a possição da imagem com o indice que esta se encontra no array $forwarding_attachments
+
+		foreach ($forwarding_attachments as $i => $v){ // Monta o  array de link
+			$desc = unserialize(rawurldecode($v));
+			$attPostions[$desc[3]] = $i;
+		}
+
+		//Intera as imagens encontradas
+		foreach($cid_imgs[6] as $j => $val)
+        {		
+			$cid = base_convert(microtime().$j, 10, 36); //Gera um cid
+			$body = str_replace($cid_imgs[1][$j], '"cid:'.$cid.'@'.$_SESSION['phpgw_info']['expressomail']['server']['domain_name'].'"', $body ); //tira o src da imagem e coloca o cid, ele e concatenado com o domain do servidor por que a biblioteaca mime faz isso na hora de gerar o mime.
 			$count    = strlen($cid_imgs[6][$j]);
-			$position = substr($cid_imgs[6][$j], 2, $count);
-			$position--;
 					
-			$attach_img = $forwarding_attachments[$position];
+			$attach_img = $forwarding_attachments[$attPostions['\''.$cid_imgs[6][$j].'\'']];
 			$file_description = unserialize(rawurldecode($attach_img));
 			
 			if (is_array($file_description))
 				foreach($file_description as $i => $descriptor)				
-					$file_description[$i]  = eregi_replace('\'*\'','',$descriptor);
+                      $file_description[$i] = mb_ereg_replace('\'*\'','',$descriptor);
 
 			// The image is not in the same mail?
 			if ($msg_uid != $cid_imgs[4][$j]) 
 			{ 
-				$fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64'); 
-				$fileName = ($msg_uid != 'undefined') ? "image_".($j).".jpg" : $file_description[2];
-				$fileCode = "base64"; 
-				$fileType = "image/jpg"; 
+                $fa = $this->get_forwarding_attachment2($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');
+                $fileContent = &$fa['binary'];
+				$fileName = $fa['name'];
+				$fileCode = $fa['encoding'];
+				$fileType =  $fa['type'];
 				$file_attached[0] = $cid_imgs[2][$j]; 
 				$file_attached[1] = $cid_imgs[4][$j]; 
 				$file_attached[2] = $fileName; 
-				$file_attached[3] = '0.'.($j+1);
+				$file_attached[3] = '0.'.(string)($j+1);
 				$file_attached[4] = 'base64'; 
 				$file_attached[5] = strlen($fileContent); //Size of file 
@@ -2599,5 +3245,5 @@
 
  				if ($file_attached[3] == $file_description[3] || $msg_uid == 'undefined')
-					unset($forwarding_attachments[$position]);
+					unset($forwarding_attachments[$attPostions['\''.$cid_imgs[6][$j].'\'']]);
 				
 			} 
@@ -2607,8 +3253,8 @@
 				$fileName = $file_description[2]; 
 				$fileCode = $file_description[4]; 
-				$file_description[3] = '0.'.($j+1);
+				$file_description[3] = '0.'.(string)($j+1);
 				$file_description[6] = $cid_imgs[6][$j];
 				$fileType = $this->get_file_type($file_description[2]); 
-				unset($forwarding_attachments[$position]);
+				unset($forwarding_attachments[$attPostions['\''.$cid_imgs[6][$j].'\'']]);
 				if (!empty($file_description)) 
 				{ 
@@ -2617,12 +3263,7 @@
 				} 
 			} 
-			$tempDir = '/tmp';
-			$file = "cidimage_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].$cid_imgs[6][$j].".dat";                                        
-			$f = fopen($tempDir.'/'.$file,"w"); 
-			fputs($f,$fileContent); 
-			fclose($f); 
 
 			if ($fileContent) 
-				$mail->AddEmbeddedImage($tempDir.'/'.$file, $cid, $fileName, $fileCode, $fileType); 
+				$mail->addStringImage($fileContent,$fileType,$fileName, $cid);					
 		}
 
@@ -2654,4 +3295,5 @@
 		$full_address = preg_replace("/, ?,/",",",$full_address);
 		$parse_address = imap_rfc822_parse_adrlist($full_address, "");
+		$bolean = true;
 		foreach ($parse_address as $val)
 		{
@@ -2665,11 +3307,11 @@
 				{
 					case "to":
-						$mail->AddAddress($val->mailbox."@".$val->host);
+						$mail->AddTo($val->mailbox."@".$val->host);
 						break;
 					case "cc":
-						$mail->AddCC($val->mailbox."@".$val->host);
+						$mail->AddCc($val->mailbox."@".$val->host);
 						break;
 					case "cco":
-						$mail->AddBCC($val->mailbox."@".$val->host);
+						$mail->AddBcc($val->mailbox."@".$val->host);
 						break;
 				}
@@ -2680,24 +3322,39 @@
 				{
 					case "to":
-						$mail->AddAddress($val->mailbox."@".$val->host, $val->personal);
+						$mail->AddTo($val->mailbox."@".$val->host, $val->personal);
 						break;
 					case "cc":
-						$mail->AddCC($val->mailbox."@".$val->host, $val->personal);
+						$mail->AddCc($val->mailbox."@".$val->host, $val->personal);
 						break;
 					case "cco":
-						$mail->AddBCC($val->mailbox."@".$val->host, $val->personal);
+						$mail->AddBcc($val->mailbox."@".$val->host, $val->personal);
 						break;
 				}
 			}
-		}
-		return true;
+			if($val->mailbox == "UNEXPECTED_DATA_AFTER_ADDRESS"){
+				$bolean = false;
+		}
+			
+		}
+		return $bolean;
 	}
 
 	function get_forwarding_attachment($msg_folder, $msg_number, $msg_part, $encoding)
+	{
+            include_once $_SESSION['rootPath'].'/expressoMail1_2/inc/class.attachment.inc.php';
+            $attachment = new attachment();
+			$attachment->decodeConf['rfc_822bodies'] = true; //Forçar a não decodificação de mensagens em anexo.
+            $attachment->setStructureFromMail($msg_folder, $msg_number);
+            return $attachment->getAttachment($msg_part);
+	}
+
+        function get_forwarding_attachment2($msg_folder, $msg_number, $msg_part, $encoding)
 	{
             include_once $_SESSION['rootPath'].'/expressoMail1_2/inc/class.attachment.inc.php';
             $attachment = new attachment();
             $attachment->setStructureFromMail($msg_folder, $msg_number);
-            return $attachment->getAttachment($msg_part);
+            $return = $attachment->getAttachmentInfo($msg_part);
+            $return['binary'] = $attachment->getAttachment($msg_part);
+            return $return;
 	}
 
@@ -2762,8 +3419,9 @@
 					else
 						$from = $header->from;
-
+					if(isset($from[0]->personal))
 					$tmp = imap_mime_header_decode($from[0]->personal);
-
-					if ($tmp[0]->text != "")
+					else
+						$tmp = null;
+					if (isset($tmp[0]->text))
 						$sort[$iuid] = $tmp[0]->text;
 					else
@@ -2786,7 +3444,9 @@
 				$sort = array_reverse($sort,true);
 		}
-
-		if(!is_array($sort))
+		if(empty($sort) or !is_array($sort)){
 			$sort = array();
+		}
+		
+			
 
 
@@ -2836,7 +3496,7 @@
 		$folder = $params['folder'];
 		$mbox_stream = $this->open_mbox($folder);
-                $newmailbox = urldecode($params['new_folder']);
+		$newmailbox = ($params['new_folder']);
                 $newmailbox = mb_convert_encoding($newmailbox, "UTF7-IMAP","ISO_8859-1");
-                $new_folder_name = urldecode($params['new_folder_name']);
+		$new_folder_name = $params['new_folder_name'];
                 $msgs_number = $params['msgs_number'];
 		$return = array('msgs_number' => $msgs_number,
@@ -2866,4 +3526,5 @@
         }
         //Este bloco tem a finalidade de transformar o CPF das pastas compartilhadas em common name
+        if(array_key_exists('uid2cn', $_SESSION['phpgw_info']['user']['preferences']['expressoMail'])){
         if ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn']){
             if (substr($new_folder_name,0,4) == 'user'){
@@ -2877,4 +3538,5 @@
             }
         }
+		}
 
 		// Caso estejamos no box principal, nao eh necessario pegar a informacao da mensagem anterior.
@@ -2883,4 +3545,5 @@
 			$return['previous_msg'] = $this->get_info_previous_msg($params);
 			// Fix problem in unserialize function JS.
+			if(array_key_exists('body', $return['previous_msg']))
 			$return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
 		}
@@ -2941,165 +3604,132 @@
 	}
 
+
 	function save_msg($params)
 	{
-
-		include_once("class.phpmailer.php");
-		$mail = new PHPMailer();
-		include_once("class.db_functions.inc.php");
-		$toaddress = $params['input_to'];
-		$ccaddress = $params['input_cc'];
-		$ccoaddress = $params['input_cco'];
+		require_once $_SESSION['rootPath'] . '/API/class.servicelocator.php';
+		$mailService = ServiceLocator::getService('mail');
+
 		$return_receipt = $params['input_return_receipt'];
 		$is_important = $params['input_important_message'];
-		$subject = $params['input_subject'];
+		
 		$msg_uid = $params['msg_id'];
 		$body = $params['body'];
 		$body = str_replace("%nbsp;","&nbsp;",$body);
 		$body = preg_replace("/\n/"," ",$body);
-		$body = preg_replace("/\r/","",$body);
+		$body = preg_replace("/\r/","" ,$body);
+		$body = html_entity_decode ( $body, ENT_QUOTES , 'ISO-8859-1' );
 		$forwarding_attachments = $params['forwarding_attachments'];
+		$message_attachments    = $params['message_attachments'];
 		$attachments = $params['FILES'];
 		$return_files = $params['FILES'];
+		$message_attachments_contents = (isset($params['message_attachments_content'])) ? $params['message_attachments_content'] : false; 
 
                 if(is_array($params['local_attachments'])){
                     foreach ($params['local_attachments'] as $key => $local_attach) {
                        $tmp = unserialize(urldecode($local_attach));
-                       $attachments[$key]['name'] = $tmp[2];
-                       $return_files[$key]['name'] = $tmp[2];
+			   $attachments[$key]['name'] = urldecode($tmp[2]);
+			   $return_files[$key]['name'] = urldecode($tmp[2]);
                     }
                 }
 
-
-		$folder = $params['folder'];
-		$folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
-		// Fix problem with cyrus delimiter changes.
-		// Dots in names: enabled/disabled.
-		$folder = @eregi_replace("INBOX/", "INBOX".$this->imap_delimiter, $folder);
-		$folder = @eregi_replace("INBOX.", "INBOX".$this->imap_delimiter, $folder);
-		// End Fix.
-
-		$mail->SaveMessageInFolder = $folder;
-		$mail->SMTPDebug = false;
-
-		$mail->IsSMTP();
-		$mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
-		$mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
-		$mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
-		$mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
-
-		$mail->Sender = $mail->From;
-		$mail->SenderName = $mail->FromName;
-		$mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
-		$mail->From =  $_SESSION['phpgw_info']['expressomail']['user']['email'];
-
-		$this->add_recipients("to", $toaddress, &$mail);
-		$this->add_recipients("cc", $ccaddress, &$mail);
-                $this->add_recipients("cco", $ccoaddress, &$mail);
-		$mail->AddReplyTo($replytoaddress);
-		$mail->Subject = $subject;
-		$mail->IsHTML(true);
-		$mail->Body = $body;
-		
-		$return_forward = $this->buildEmbeddedImages($mail,$msg_uid,$forwarding_attachments);
+		$folder = mb_convert_encoding($params['folder'], "UTF7-IMAP","ISO_8859-1");
+		$folder = @eregi_replace("INBOX[/.]", "INBOX".$this->imap_delimiter, $folder);
+
+		$mailService->setFrom ('"'.$fromaddress[0].'" <'.$fromaddress[1].'>');
+		$mailService->addTo($params['input_to']);
+		$mailService->addCc( $params['input_cc']);
+		$mailService->addBcc($params['input_cco']);
+		$mailService->setSubject($params['input_subject']);
+
+		if($is_important){
+			$mailService->addHeaderField('Importance','High');
+		}
+
+		if($return_receipt)
+			$mailService->addHeaderField('Disposition-Notification-To', $_SESSION['phpgw_info']['expressomail']['user']['email']);
+
+		$isHTML = ( ( array_key_exists( 'type', $params ) && in_array( strtolower( $params[ 'type' ] ), array( 'html', 'plain' ) ) ) ? strtolower( $params[ 'type' ] ) != 'plain' : true );
+
+		
+		if( count($forwarding_attachments) > 0 )
+			$return_forward = $this->buildEmbeddedImages($mailService, $msg_uid, $forwarding_attachments , $body);
+			
+		//Build Message Attachments!!!
+		if(count($message_attachments) > 0 ) 
+		{
+			foreach($message_attachments as $folder_name => $messages)
+			{
+				foreach ($messages as $message_number => $message_subject) 
+				{
+					if (!$message_subject)
+						$message_subject  = 'no title.eml';
+					else 
+						$message_subject .= '.eml';
+					
+					if( $message_attachments_contents &&  isset($message_attachments_contents[$folder_name]) )
+						$rawmsg = base64_decode( $message_attachments_contents[$folder_name][$message_number] );
+					else{
+						$mbox_stream = $this->open_mbox($folder_name);$mbox_stream = $this->open_mbox($folder_name);
+						$rawmsg = $this->getRawHeader($message_number) . "\r\n\r\n" . $this->getRawBody($message_number);
+					}
+											
+					$return_forward[] = array( 'name' => $message_subject, 'size' => mb_strlen($rawmsg));
+					$mailService->addStringAttachment($rawmsg, $message_subject, 'message/rfc822', '7bit', 'attachment' );
+				}
+			}
+		}
+		
 		$imagesParts = array(); 
 
+		if(count($return_forward) > 0 )
 		foreach ($return_forward as $value)
 			$imagesParts[$value[6]] = $value[3]; 	
 
-	//	Build Forwarding Attachments!!!
+		//Build Forwarding Attachments!!!
+		if(count($forwarding_attachments) > 0 ) 
+		{
 			foreach($forwarding_attachments as $forwarding_attachment)
 			{
 				$file_description = unserialize(rawurldecode($forwarding_attachment));
+						
+				
 			$file_description = array_values($file_description); 
  	                          	
-				foreach($file_description as $i => $descriptor){
+				foreach($file_description as $i => $descriptor)
   	  	 	                                $file_description[$i] = eregi_replace('\'*\'','',$descriptor); 
-				}
+				
 				$fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
-				$fileName = $file_description[2];
+				$file_description[2] = html_entity_decode($file_description[2]);
 
 				$file_description[5] = strlen($fileContent); //Size of file
 				$return_forward[] = $file_description;
-
-					$mail->AddStringAttachment($fileContent, $fileName, $file_description[4], $this->get_file_type($file_description[2]));
+				$mailService->addStringAttachment($fileContent, $file_description[2], $this->get_file_type($file_description[2]), $file_description[4] );
+			}
 			}
 
 		if ((count($return_forward) > 0) && (count($return_files) > 0))
-		{
 			$return_files = array_merge_recursive($return_forward,$return_files);
-		}
 		else if (count($return_files) < 1)
-		{
 				$return_files = $return_forward;
-		}
-
-		//	Build Uploading Attachments!!!
+
+		//Build Uploading Attachments!!!
 		$sizeof_attachments = count($attachments);
 		if ($sizeof_attachments)
-		{
 			foreach ($attachments as $numb => $attach)
-			{
-				if ($numb == ($sizeof_attachments-1) && $params['insertImg'] == 'true')
-				{ // Auto-resize image
-					list($width, $height,$image_type) = getimagesize($attach['tmp_name']);
-					switch ($image_type)
-					{
-					// Do not corrupt animated gif
-					//case 1: $image_big = imagecreatefromgif($attach['tmp_name']);break;
-						case 2: 
-							$image_big = imagecreatefromjpeg($attach['tmp_name']);  break;
-						case 3: 
-							$image_big = imagecreatefrompng($attach['tmp_name']); break;
-					case 6:
-						require_once("gd_functions.php");
-						$image_big = imagecreatefrombmp($attach['tmp_name']); break;
-					default:
-						$mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));
-						break;
-					}
-					header('Content-type: image/jpeg');
-					$max_resolution = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['image_size'];
-					$max_resolution = ($max_resolution==""?'65536':$max_resolution);
-					if ($width < $max_resolution && $height < $max_resolution)
-					{
-						$new_width = $width;
-						$new_height = $height;
-					}
-					else if ($width > $max_resolution)
-					{
-						$new_width = $max_resolution;
-						$new_height = $height*($new_width/$width);
-					}
-					else 
-					{
-						$new_height = $max_resolution;
-						$new_width = $width*($new_height/$height);
-					}
-					$image_new = imagecreatetruecolor($new_width, $new_height);
-					imagecopyresampled($image_new, $image_big, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
-                                        $tmpDir = '/tmp';
-
-                                       // $tmpDir = ini_get("session.save_path");
-					$_file = "/cidimage_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].".dat";
-					imagejpeg($image_new,$tmpDir.$_file, 85);
-					$mail->AddAttachment($tmpDir.$_file, $attach['name'], "base64", $this->get_file_type($tmpDir.$_file));
-				}else{
-					$mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));
-                                }// optional name
-			}
-		}
-
-		if(!empty($mail->AltBody))
-            $mail->ContentType = "multipart/alternative";
-
-		$mail->error_count = 0; // reset errors
-		$mail->SetMessageType();
-		$header = $mail->CreateHeader();
-		$body = $mail->CreateBody();
+				$mailService->addFileAttachment($attach['tmp_name'],  $attach['name'],$attach['type'],  'base64', 'attachment');
+
+
+		if (!$body)
+			$body = ' ';
+		
+		if($isHTML)
+			$mailService->setBodyHtml($body);
+		else
+			$mailService->setBodyText($body);
+
 
 		$mbox_stream = $this->open_mbox($folder);
-		$new_header = str_replace("\n", "\r\n", $header);
-		$new_body = str_replace("\n", "\r\n", $body);
-		$return['append'] = imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, $new_header . $new_body, "\\Seen \\Draft");
+		$return['append'] = imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, $mailService->getMessage(), "\\Seen \\Draft");
+
 		$status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
 		$return['msg_no'] = $status->uidnext - 1;
@@ -3110,5 +3740,8 @@
 			imap_close($mbox_stream);
 			
-		if (is_array($return_files))
+		$returnFiles = array();                  
+		$ii = 0;
+                		
+		if(count($return_files) > 0)
 		{
 			foreach ($return_files as $index => $_attachment) 
@@ -3116,21 +3749,19 @@
 				if (array_key_exists("name", $_attachment))
 				{
-				unset($return_files[$index]);
-				$return_files[$index] = $_attachment['name']."_SIZE_".$return_files[$index][1] = $_attachment['size'];
-			}
-			else
+					$returnFiles[$ii]['name'] = base64_encode($_attachment['name']);
+					$returnFiles[$ii]['size'] = $_attachment['size'];
+					$ii++;
+			}
+				else if($_attachment[2])
 			{
-				unset($return_files[$index]);
-				$return_files[$index] = $_attachment[2]."_SIZE_". $return_files[$index][1] = $_attachment[5];
-			}
-		}
-		}
-
-		$return['files'] = serialize($return_files);
-		$return["subject"] = $subject;
-
-		if (!$return['append'])
-			$return['append'] = imap_last_error();
-
+					$returnFiles[$ii]['name'] = base64_encode($_attachment[2]); 
+					$returnFiles[$ii]['size'] = $_attachment[5];         
+					$ii++;
+			}
+		}
+		}
+		$return['files'] = serialize($returnFiles);
+		$return["subject"] = $params['input_subject'];
+		if (!$return['append'])	$return['append'] = imap_last_error();
 		return $return;
 	}
@@ -3139,20 +3770,9 @@
 	{
 		$folder = $params['folder'];
-		$rowids_to_set = $params['msgs_to_set']; // contains the row ids
+		$msgs_to_set = $params['msgs_to_set'];
 		$flag = $params['flag'];
 		$return = array();
-		$return["rowids_to_set"] = $rowids_to_set;
+		$return["msgs_to_set"] = $msgs_to_set;
 		$return["flag"] = $flag;
-
-		$msgs_to_set = '';
-		foreach (explode(',',$rowids_to_set) as $msg) {//extracting message ids
-			$pos = strpos($msg,'_');
-			if ($pos===false)
-				$msgs_to_set .= ','.$msg;
-			else
-				$msgs_to_set .= ','.substr($msg,0,$pos);
-		}
-		$msgs_to_set = substr($msgs_to_set,1);
-		$return["msgs_to_set"] = $msgs_to_set;
 
 		if(!$this->mbox && !is_resource($this->mbox))
@@ -3213,4 +3833,6 @@
 		$file_name = strtolower($file_name);
 	   	$strFileType = strrev(substr(strrev($file_name),0,4));
+	   	if ($strFileType == ".eml")
+   			return "message/rfc822";
 	   	if ($strFileType == ".asf")
    			return "video/x-ms-asf";
@@ -3710,7 +4332,5 @@
 							{
 							    $filter .= '"'.$filter_array[1].'"';
-							}
-							if(trim($filter_array[0]) == 'BEFORE' )
-							{
+							}else if(trim($filter_array[0]) == 'BEFORE' ){
                                                             $filter .= '"'.$this->make_search_date($filter_array[1],true).'"';
 							}else{
@@ -3721,5 +4341,5 @@
 				}
 				
-				$name_box = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO_8859-1" );
+				$name_box = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO-8859-1" );
 				$filter = $this->remove_accents($filter);
 
@@ -3737,5 +4357,5 @@
 				}
 				else
-					$folder_name = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO_8859-1" );
+					$folder_name = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO-8859-1" );
 				
 				if(!is_resource($mbox_stream))
@@ -3760,5 +4380,5 @@
 							{
 								$elem = $this->get_msg_detail($new_search,$name_box,$mbox_stream); 
-								$elem['boxname'] = mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" ); 
+								$elem['boxname'] = mb_convert_encoding( $name_box, "ISO-8859-1", "UTF7-IMAP" ); 
 								$elem['uid'] = $new_search;
                                                                 /* compare dates in ordering */
@@ -3770,4 +4390,5 @@
 				}
 				else{
+					$search_criteria = imap_search($mbox_stream, $filter, SE_UID);
                                     if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag'])
                                     {
@@ -3785,26 +4406,17 @@
                                                 }
                                             }
-
-                                            $new_filter = trim(preg_replace('/UNFLAGGED|FLAGGED/','',$filter));
-
-                                            $search_without_flagged = imap_search($mbox_stream, $new_filter, SE_UID);
-
-                                            if (strpos($filter,"UNFLAGGED") === false)
+						if((count($flagged_msgs) >0) && (strpos($filter,"UNFLAGGED") === false))
                                             {
-                                                $search_criteria = array_intersect($search_without_flagged, $flagged_msgs);
-                                            }
-                                            else
+                                                    $arry_diff = is_array($search_criteria) ? array_diff($flagged_msgs,$search_criteria):$flagged_msgs;
+                                                    foreach($arry_diff as $msg)
                                             {
-                                                $search_criteria = array_diff($search_without_flagged,$flagged_msgs);
+							$search_criteria[] = $msg;
                                             }
                                         }
-                                        else
+						else if((count($flagged_msgs) >0) && (is_array($search_criteria)) && (!strpos($filter,"UNFLAGGED") === false))
                                         {
-                                            $search_criteria = imap_search($mbox_stream, $filter, SE_UID);
+                                                    $search_criteria = array_diff($search_criteria,$flagged_msgs);
                                         }
                                     }
-                                    else
-                                    {
-                                        $search_criteria = imap_search($mbox_stream, $filter, SE_UID);
                                     }
 
@@ -3814,5 +4426,5 @@
                                         {
                                             $elem = $this->get_msg_detail($new_search,$name_box,$mbox_stream);
-                                            $elem['boxname'] = mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" );
+							$elem['boxname'] = mb_convert_encoding( $name_box, "ISO-8859-1", "UTF7-IMAP" ); 
                                             $elem['uid'] = $new_search;
                                             /* compare dates in ordering */
@@ -4036,6 +4648,9 @@
 		$mbox_acl = imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
 		else
-		  $mbox_acl = imap_getacl($mbox_stream, $user);
+		  $mbox_acl = @imap_getacl($mbox_stream, $user);
+                if(isset($mbox_acl[$this->username]))
 		return $mbox_acl[$this->username];
+                else 
+                    return '';
 	}
 
@@ -4166,4 +4781,15 @@
 	
 	
+/**
+* Descrição do método
+*
+* @license    http://www.gnu.org/copyleft/gpl.html GPL
+* @author     
+* @sponsor    Caixa Econômica Federal
+* @author     
+* @param      <tipo> <$msg_number> <Número da mensagem>
+* @return     <cabeçalho da mensagem>
+* @access     <public>
+*/	
 	function get_header($msg_number)
 	{
@@ -4172,5 +4798,5 @@
 			return false;
 
-		if($header->Flagged != "F" && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
+		if($header->Flagged != "F" ) {
 			$flag = preg_match('/importance *: *(.*)\r/i',
 						imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
@@ -4191,9 +4817,12 @@
         $imap_port 	= $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
         $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())
-        {
+        
+        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) 
@@ -4205,6 +4834,6 @@
         	fputs($f,base64_encode($source));
             fclose($f);
-		   $command = "python ".$_SESSION['rootPatch']."/expressoMail1_2/imap.py ".escapeshellarg($imap_server)." ".escapeshellarg($imap_port)." ".escapeshellarg($username)." ".escapeshellarg($password)." ".escapeshellarg($timestamp)." ".escapeshellarg($folder)." ".escapeshellarg($file);
-            $return['command']=exec(escapeshellcmd($command));
+            $command = "python ".$_SESSION['rootPath']."/expressoMail1_2/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");
@@ -4230,4 +4859,9 @@
                   imap_setflag_full($mbox_stream, $return['msg_no'], $flags_fixed, ST_UID);
                 }
+	
+        //Ignorando erro de AUTH=Plain
+        if($return['error'] === 'SECURITY PROBLEM: insecure server advertised AUTH=PLAIN')
+            $return['error'] = false;
+                                
         if($mbox_stream)
             imap_close($mbox_stream);
@@ -4235,18 +4869,20 @@
     }
 
-    function show_decript($params){
+        function show_decript($params,$dec=0){ 
         $source = $params['source'];
-        //error_log("source: $source\nversao: " . PHP_VERSION, 3, '/tmp/teste.log'); 
- 		        $source = str_replace(" ", "+", $source,$i); 
  		 
+        //error_log("source: $source\nversao: " . PHP_VERSION); 	 
+        if ($dec == 0) 
+        { 
+            $source = str_replace(" ", "+", $source,$i); 
  		        if (version_compare(PHP_VERSION, '5.2.0', '>=')){ 
  		            if(!$source = base64_decode($source,true)) 
- 		                return "error ".$source."Espaços ".$i; 
+                    return "error ".$source."Espaï¿?os ".$i; 
  		 
  		        } 
  		        else { 
  		            if(!$source = base64_decode($source)) 
- 		                return "error ".$source."Espaços ".$i;
-
+                    return "error ".$source."Espaï¿?os ".$i; 
+            } 
         }
 
@@ -4316,16 +4952,14 @@
         $dest_folder = $params['folder'];
         $sources = explode("#@#@#@",$params['source']);
-        $timestamps = explode("#@#@#@",$params['timestamp']);
+        //Add user timeszone
+        $timestamps 	= $params['timestamp'] + $this->functions->CalculateDateOffset(); 
         $flags = explode("#@#@#@",$params['flags']);
 
-        foreach($sources as $index=>$src)
-        {
-            if($src!="")
-            {
+		foreach($sources as $index=>$src) {
+			if($src!=""){
 		$source = $this->treat_base64_from_post($src);
-		$insert = $this->insert_email($source,$dest_folder,$timestamps[$index],$flags[$index]);
+ 		        $insert = $this->insert_email($source, mb_convert_encoding( $dest_folder,"ISO-8859-1","UTF-8"), $timestamps,$flags[$index]); 
             }
 	}
-        
         return $insert;
     }
@@ -4357,10 +4991,4 @@
 			$msg_user = "Sem mensagem!"; 
  		         
-		$toaddresses = $_SESSION['phpgw_info']['expressomail']['server']['sugestoes_email_to'];  
- 		$toaddress   = explode(",", $toaddresses);       
- 		                 
- 		for($i=0; $i<count($toaddress); $i++) 
-			$toaddress[$i] = trim($toaddress[$i]); 
- 		                 
 		$toname       = $_SESSION['phpgw_info']['expressomail']['user']['fullname']; 
  		 
@@ -4372,10 +5000,155 @@
  		                "$msg_user</body><br><br><hr>"; 
  		             
+ 		require_once $_SESSION['rootPath'] . '/API/class.servicelocator.php';
  		$mailService = ServiceLocator::getService('mail');      
- 		$mailService->addAttachment($mail_content, 'report.eml', 'application/text'); 
- 		$mailService->send($toaddress, $GLOBALS['phpgw_info']['user']['email'], $title, $body); 
+ 		$mailService->addStringAttachment($mail_content, 'report.eml', 'application/text'); 
+ 		$mailService->sendMail($_SESSION['phpgw_info']['expressomail']['server']['sugestoes_email_to'], $GLOBALS['phpgw_info']['user']['email'], $title, $body); 
 	} 
 	
+	function array_msort($array, $cols)
+	{
+		$colarr = array();
+		foreach ($cols as $col => $order) {
+			$colarr[$col] = array();
+			foreach ($array as $k => $row) { $colarr[$col]['_'.$k] = strtolower($row[$col]); }
+		}
+		$params = array();
+		foreach ($cols as $col => $order) {
+			$params[] =& $colarr[$col];
+			$params = array_merge($params, (array)$order);
+		}
+		call_user_func_array('array_multisort', $params);
+		$ret = array();
+		$keys = array();
+		$first = true;
+		foreach ($colarr as $col => $arr) {
+			foreach ($arr as $k => $v) {
+				if ($first) { $keys[$k] = substr($k,1); }
+				$k = $keys[$k];
+				if (!isset($ret[$k])) $ret[$k] = $array[$k];
+				$ret[$k][$col] = $array[$k][$col];
+			}
+			$first = false;
+		}
+		
+		return $ret;
+
+	}
+        
+        function parseCriteriaSearchMail($search)
+        {
+            $criteria = '';
+            $searchArray = explode(' ', $search);
+
+            foreach ($searchArray as $v)
+                if(trim($v) !== '' )
+                    $criteria .= 'TEXT "'.$v.'" ' ;
+           
+            return $criteria;
+        }
+        
+	function quickSearchMail( $params )
+	{
+		$return = array();
+		$return['folder'] = $params['folder'];
+		if(!is_array($params['folder']))
+			$params['folder'] = array( $params['folder'] );
+		
+		if(!isset($params['sort']))
+			$params['sort'] = SORTDATE;
+				
+		$params['search'] = mb_convert_encoding($params['search'], 'UTF-8',mb_detect_encoding($params['search'].'x', 'UTF-8, ISO-8859-1'));
+		
+		$i = 0;		
+		if(!isset($params['page'])) $params['page'] = 0;
+		$end = ($this->prefs['max_email_per_page'] * ((int)$params['page'] + 1));	
+		$ini = $end - $this->prefs['max_email_per_page'] ;
+		$count = 0;
+		
+                $search = $this->parseCriteriaSearchMail($params['search']);
+		                
+		foreach ($params['folder'] as $folder) 
+		{
+			$imap = $this->open_mbox( $folder ) ;
+			$msgIds = imap_sort( $imap , SORTDATE , 0 , SE_UID , $search ,'UTF-8');
+						
+			$count += count($msgIds);  
+			
+			foreach ($msgIds as $ii => $v)
+			{				
+				$msg = imap_headerinfo ( $imap,  imap_msgno($imap, $v) );
+				$return['msgs'][$i]['from'] = '';
+				
+				$from = $msg->from[0]->mailbox;
+				if($msg->from[0]->personal != "")
+					$from = $msg->from[0]->personal;
+				$return['msgs'][$i]['from'] 	= mb_convert_encoding($this->decode_string($from), 'UTF-8'); 
+				
+				$return['msgs'][$i]['subject'] = ' ';
+				
+				$subject = imap_mime_header_decode($msg->subject);
+				foreach ($subject as $tmp)
+					$return['msgs'][$i]['subject'] .= mb_convert_encoding($tmp->text, 'UTF-8');
+				
+				$return['msgs'][$i]['flag'] = ' ';
+				$return['msgs'][$i]['flag'] .= $msg->Unseen ? $msg->Unseen : '';
+				$return['msgs'][$i]['flag'] .= $msg->Recent ? $msg->Recent : '';	
+				$return['msgs'][$i]['flag'] .= $msg->Flagged ? $msg->Flagged : '';	
+				$return['msgs'][$i]['flag'] .= $msg->Draft ? $msg->Draft : '';	
+				$return['msgs'][$i]['flag'] .= $msg->Answered ? $msg->Answered : '';	
+				$return['msgs'][$i]['flag'] .= $msg->Deleted ? $msg->Deleted : '';	
+				
+				$return['msgs'][$i]['udate'] = gmdate("d/m/Y",$msg->udate + $this->functions->CalculateDateOffset()); 
+				$return['msgs'][$i]['udatecomp'] = substr ($return['msgs'][$i]['udate'], -4) ."-". substr ($return['msgs'][$i]['udate'], 3, 2) ."-". substr ($return['msgs'][$i]['udate'], 0, 2);
+			    $return['msgs'][$i]['date'] =   $msg->udate;
+				$return['msgs'][$i]['size'] =  $msg->Size;
+				$return['msgs'][$i]['boxname'] = $folder;
+				$return['msgs'][$i]['uid'] = $v;
+				$i++;
+			} 	
+		}
+		
+		$return['num_msgs'] = $count;
+		
+		if(!isset($return['msgs']))
+			$return['msgs'] = array();
+		
+		define('SORTBOX', 69);
+		define('SORTWHO', 2);
+		define('SORTBOX_REVERSE', 69);
+		define('SORTWHO_REVERSE', 2);
+		define('SORTDATE_REVERSE', 0);
+		define('SORTSUBJECT_REVERSE', 3);
+		define('SORTSIZE_REVERSE', 6);
+		
+		switch (constant( $params['sort'] )){
+			case 0 : $sA = 'date'; break;
+			case 2 : $sA = 'from'; break;
+			case 69 : $sA = 'boxname'; break;
+			case 3 : $sA = 'subject'; break;
+			case 6 : $sA = 'size'; break;
+	} 
 	
+		$return['msgs'] = $this->array_msort($return['msgs'] , array( $sA => SORT_ASC));
+			
+		if(strpos($params['sort'],'REVERSE') !== false)
+			$return['msgs'] = array_reverse($return['msgs']);	
+				
+		
+		$k = -1;
+		$nMsgs = array();
+		
+		foreach ($return['msgs'] as $v)
+		{		
+			$k++;
+			if($k < $ini || $k >= $end ) continue;			
+			$nMsgs[] = $v;
+		}
+		$return['msgs'] = $nMsgs;
+		$return = json_encode($return);		
+		$return = base64_encode($return);
+	
+		return $return;
+	}
 	
     function get_quota_folders(){ 
@@ -4416,4 +5189,23 @@
 	    return $data; 
     }  
+    
+    function getaclfrombox($mail)
+        {
+                $mailArray = explode('@', $mail);
+                $boxacl = $mailArray[0];
+                $return = array();
+
+                if(!$this->mbox)
+                     $this->open_mbox();
+
+                $mbox_acl = imap_getacl($this->mbox, 'user' . $this->imap_delimiter . $boxacl);
+
+                foreach ($mbox_acl as $user => $acl)
+                {
+                        if ($user != $boxacl )
+                            $return[$user] = $acl;
+                }
+                return $return;
+        }
 }
 ?>
Index: trunk/expressoMail1_2/inc/class.exporteml.inc.php
===================================================================
--- trunk/expressoMail1_2/inc/class.exporteml.inc.php	(revision 5079)
+++ trunk/expressoMail1_2/inc/class.exporteml.inc.php	(revision 5134)
@@ -17,12 +17,4 @@
 	var $tempDir;
 	
-	
-	/**
-	* Construtor da classe ExportEml
-	*
-	* @license    http://www.gnu.org/copyleft/gpl.html GPL
-	* @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
-	* @sponsor    Caixa Econômica Federal
-	*/
 	function ExportEml() {
 	   
@@ -303,19 +295,17 @@
     }
 
+    function export_eml( $params ){
+
+	return $this->export_msg_data( $params['msgs_to_export'],
+				       $params['folder'] );
+    }
+
 	function export_msg($params) {
-		$this-> folder = $params['folder'];
-		$this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","ISO_8859-1");
-		$id_number = $params['msgs_to_export'];
 		$tempDir = $this->tempDir;
-		$this->connectImap();
-		$header	 	= $this-> getHeader($id_number);
-		$body		= $this-> getBody($id_number);
-		
 		$file = "source_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].".php";
 		$f = fopen($tempDir.'/'.$file,"w");
-		fputs($f,$header ."\r\n\r\n". $body);
+		fputs($f, $this->export_msg_data( $params['msgs_to_export'], $params['folder'] ) );
 		fclose($f);
 		
-		imap_close($this->mbox_stream);
 		return $tempDir.'/'.$file;
 	}
@@ -336,7 +326,6 @@
 
 		function export_to_archive($id_msg,$folder) {
-		$this-> folder = $folder; 
+		$this->folder = $folder;
  		$this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","ISO_8859-1");
- 	           
  		$tempDir = $this->tempDir;
  		                 
@@ -344,74 +333,17 @@
  		$header         = $this-> getHeader($id_msg); 
  		$body           = $this-> getBody($id_msg); 
- 		$name = md5($_SESSION[ 'phpgw_session' ][ 'session_id' ].microtime());
  		
-		//$file = $_SESSION[ 'phpgw_session' ][ 'session_id' ].$name;
- 		$file = "source_".$_SESSION[ 'phpgw_session' ][ 'session_id' ]."_".time().".php"; //source_[sessao]_[timestamp].php 
-		$f = fopen($tempDir . '/'.$file,"w");
- 		fputs($f,utf8_encode($header) ."\r\n\r\n". utf8_encode($body));
+		$file = tempnam ($tempDir, 'source_#'.$id_msg);
+		$file .= '.php';
+		$fileName = basename ($file);
+		$f = fopen($file, "w");
+		fputs($f,$phpheader.$header ."\r\n\r\n". $body);
  		fclose($f); 
+		$urlPath = 'tmpLclAtt/' . $fileName;
  		                 
  		imap_close($this->mbox_stream); 
 		return "inc/gotodownload.php?idx_file=".$tempDir . '/'.$file."&newfilename=fonte_da_mensagem.txt";
+        }
  		                 
-        }
-
-	function get_attachments_in_array($params) {
-		$return_attachments = array();
-
-		$id_number = $params['num_msg'];		
-		$attachments =unserialize(rawurldecode($params['s_attachments']));
-		
-		$tempDir = dirname( __FILE__ ) . '/../tmpLclAtt';
-		$tempSubDir = md5(microtime());
-		exec('mkdir ' . $tempDir . '/'.$tempSubDir.'; cd ' . $tempDir . '/'.$tempSubDir);
-		
-		$this-> folder = $params['folder'];
-		$this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","UTF-8");
-		$this->connectImap();
-
-		include_once("class.imap_attachment.inc.php");
-
-		$imap_attachment = new imap_attachment();
-		$attachments = $imap_attachment->download_attachment($this->mbox_stream, $id_number);
-		foreach($attachments as $i => $attachment){
-			if($i && $i == 'names')
-				continue;
-			$fileNameReal = $this->remove_accents($attachment['name']);
-			$ContentType = $this->getFileType($fileNameReal);
-			$fileName = $fileNameReal . ".php";
-			$f = fopen($tempDir . '/'.$tempSubDir.'/'.$fileName,"wb");
-			if(!$f)
-				return $tempDir . '/'.$tempSubDir.'/'.$fileName;			
-
-			$fileContent = imap_fetchbody($this->mbox_stream, $id_number,$attachment['pid'], FT_UID);
-			$urlPath = 'tmpLclAtt/'.$tempSubDir.'/'.$fileName;
-			
-			$headers = "<?php header('Content-Type: ".$ContentType."');
-				header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
-				header('Pragma: public');
-				header('Expires: 0'); // set expiration time
-	 	 		header('Content-Disposition: attachment; filename=\"". addslashes($fileNameReal) ."\"');\n echo ";
-			
-			if($attachment['encoding'] == 'base64') {
-				$headers.=" imap_base64('".$fileContent."');?>";
-			}
-			else if($attachment['encoding'] == 'quoted_printable_decode') {
-				$headers.=" quoted_printable_decode('".$fileContent."');?>";
-			}
-			else {
-				$headers.=" '".$fileContent."';?>";
-			}
-			
-			fputs($f,$headers);
-
-			array_push($return_attachments,array('name' => $fileName,'url' => $urlPath,'pid' =>$attachment['pid']));
-			fclose($f);
-		}
-		imap_close($this->mbox_stream);
-		return $return_attachments;
-        }
-
-
 	function remove_accents($string) {
 		/*
@@ -423,7 +355,52 @@
 			"áàâãäéèêëíìîïóòôõöúùûüç?\"'!@#$%š&*()-=+Ž`[]{}~^,<>;:/?\\|¹²³£¢¬§ªº°ÁÀÂÃÄÉÈÊËÍÌÎÏÓÒÔÕÖÚÙÛÜÇ",
 			"aaaaaeeeeiiiiooooouuuuc___________________________________________AAAAAEEEEIIIIOOOOOUUUUC");
-	}
-	
-
+        }
+
+	function get_attachments_headers( $folder, $id_number ){
+
+	    $this->folder = mb_convert_encoding($folder, "UTF7-IMAP","UTF-8");
+		
+	    $return_attachments = array();
+		
+	    include_once("class.attachment.inc.php");
+
+	    $imap_attachment = new attachment();
+	    $imap_attachment->setStructureFromMail( $folder, $id_number );
+	    $attachments = $imap_attachment->getAttachmentsInfo();
+
+		foreach($attachments as $i => $attachment){
+
+		    $fileContent = $imap_attachment->getAttachment( $attachment['pid'] );
+			
+		    $headers = "<?php header('Content-Type: {$attachment['type']}');
+				header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
+				header('Pragma: public');
+				header('Expires: 0'); // set expiration time
+				      header('Content-Disposition: attachment; filename=\"{$attachment['name']}\"');\n
+				      echo '$fileContent';?>";
+			
+		    $return_attachments[ $attachment['name'] ] = array( "content" => $headers, "pid" => $attachment['pid'] );
+			}
+
+	    return( $return_attachments );
+			}
+			
+	function get_attachments_in_array($params) {
+		$return_attachments = array();
+
+		$attachments = $this->get_attachments_headers( $params['folder'], $params['num_msg'] );
+
+		if( !empty( $attachments ) )
+		{
+		    foreach($attachments as $fileNameReal => $attachment){
+
+			    array_push($return_attachments,array('name' => $fileNameReal, 'pid' =>$attachment['pid'], 'contentType' => $this->getFileType( $fileNameReal  ) ));
+		}
+        }
+
+		return $return_attachments;
+
+	}
+	
 	private function getFileType($nameFile) {
 		$strFileType = strrev(substr(strrev(strtolower($nameFile)),0,4));
@@ -529,4 +506,6 @@
 	   	if ($strFileType == ".eml")
 	   		$ContentType = "text/plain";
+		if ($strFileType == ".png")
+			$ContentType = "image/png";
 		return $ContentType;
 	}
@@ -534,7 +513,9 @@
 	function download_all_attachments($params) {
 		
+		require_once $_SESSION['rootPath'].'/expressoMail1_2/inc/class.attachment.inc.php';
+		$atObj = new attachment();
+		$atObj->setStructureFromMail($params['folder'],$params['num_msg']);
+		$attachments = $atObj->getAttachmentsInfo();
 		$id_number = $params['num_msg'];		
-		$attachments =unserialize(rawurldecode($params['s_attachments']));
-		
 		$tempDir = $this->tempDir;
 		$tempSubDir = $_SESSION['phpgw_session']['session_id'];
@@ -543,8 +524,4 @@
 		$this-> folder = $params['folder'];
 		$this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","UTF-8");
-		$this->connectImap();
-		include("class.imap_attachment.inc.php");
-		$imap_attachment = new imap_attachment();
-		$attachments = $imap_attachment->download_attachment($this->mbox_stream, $id_number);
 		
 		$fileNames = Array();
@@ -583,9 +560,5 @@
 			if(!$f)
 				return False;			
-						
-			$fileContent = imap_fetchbody($this->mbox_stream, $id_number,$attachments[$i]['pid'], FT_UID);
-			if($attachments[$i]['encoding'] == 'base64')
-				fputs($f,imap_base64($fileContent));
-			else		
+			$fileContent = $atObj->getAttachment( $attachments[$i]['pid'] );	
 				fputs($f,$fileContent);
 				
Index: trunk/expressoMail1_2/inc/class.dynamic_contacts.inc.php
===================================================================
--- trunk/expressoMail1_2/inc/class.dynamic_contacts.inc.php	(revision 1059)
+++ trunk/expressoMail1_2/inc/class.dynamic_contacts.inc.php	(revision 5134)
@@ -79,5 +79,5 @@
 			{
 				foreach($this->contacts as $item => $valor)
-					$contact .= ';'.$this->contacts[$item]['email'] . ',';
+					$contact .= str_replace("#",";",$this->contacts[$item]['email']) . ',';
 				//Retira ultima virgula.
 				$contact = substr($contact,0,(strlen($contact) - 1));
@@ -106,5 +106,5 @@
 		{
 			// Trim all whitespaces and duplicated commas from full_email_address
-			$full_email_address = preg_replace('{(,)\1+}',',',ereg_replace( ' +', '', $full_email_address));
+			$full_email_address = preg_replace('{(,)\1+}',',',$full_email_address);
 			$parse_address = imap_rfc822_parse_adrlist($full_email_address, "");
 			$new_contacts = array();
@@ -118,7 +118,7 @@
 				if(!$this->contacts) // Used one time to insert the first contact in database
 				{
-					$this->db->insert_contact($val->mailbox."@".$val->host);
+					$this->db->insert_contact($val->personal."#".$val->mailbox."@".$val->host);
 					// Just new contact added.
-					$new_contacts[] = $val->mailbox."@".$val->host;
+					$new_contacts[] = $val->personal.";".$val->mailbox."@".$val->host; 
 					$this->contacts = $this->db->get_dynamic_contacts();
 				}
@@ -129,5 +129,5 @@
 					foreach($this->contacts as $item => $valor)
 					{
-						if($this->contacts[$item]['email'] == $val->mailbox."@".$val->host) // check if email already exists
+						if($this->contacts[$item]['email'] == $val->personal."#".$val->mailbox."@".$val->host) // check if email already exists
 						{	
 							$this->contacts[$item]['timestamp'] = time(); //update timestamp of email
@@ -143,14 +143,14 @@
 					{
 						// Just new contact added.
-						$new_contacts[] = $val->mailbox."@".$val->host;
+						$new_contacts[] = $val->personal.";".$val->mailbox."@".$val->host;
 						if($this->number_of_contacts > count($this->contacts))
 						{
 							$this->contacts[] = array( 'timestamp'	=> time(),
-														'email'		=> $val->mailbox."@".$val->host);
+														'email'         => $val->personal."#".$val->mailbox."@".$val->host);
 						}
 						if($this->number_of_contacts <= count($this->contacts))
 						{
 							$this->contacts[$older_contact] = array( 'timestamp'	=> time(),
-																		'email'		=> $val->mailbox."@".$val->host);
+																		'email'         => $val->personal."#".$val->mailbox."@".$val->host);
 						}
 					}
Index: trunk/expressoMail1_2/inc/gotodownload.php
===================================================================
--- trunk/expressoMail1_2/inc/gotodownload.php	(revision 4842)
+++ trunk/expressoMail1_2/inc/gotodownload.php	(revision 5134)
@@ -50,6 +50,4 @@
 	$newfilename = $newfilename ? $newfilename 	: $filename;
 	$strFileType = strrev(substr(strrev(strtolower($filename)),0,4));
-	if(strpos($strFileType ,"." )===false) 
- 		$strFileType = strrev(substr(strrev(strtolower($newfilename)),0,4)); 
 
 	downloadFile($strFileType, $filename, $newfilename, $fileContent, $encoding);
Index: trunk/expressoMail1_2/inc/class.ScriptS.inc.php
===================================================================
--- trunk/expressoMail1_2/inc/class.ScriptS.inc.php	(revision 4986)
+++ trunk/expressoMail1_2/inc/class.ScriptS.inc.php	(revision 5134)
@@ -215,26 +215,11 @@
 
     function convert_specialchar($input) {
-        $special_char = false;
-        for ($i = 0; $i < strlen($input); $i++) {
-            if (preg_match('/[^a-z0-9.@~_+=&\'*^\ \-\[\]]/i', $input[$i])) {
-                $special_char = true;
-                $input = preg_replace('/\\' . $input[$i] . '/', '=' . bin2hex($input[$i]), $input);
-            }
-        }
-
-        if ($special_char) {
-            /*             *
-             * When using arrays with pattern and replacement,
-             * the keys are processed in the order they appear in the array.
-             * See preg_replace in php.net/preg_replace
-             * */
-            $patterns[0] = '/=c3/i';
-            $patterns[1] = '/ /';
-            $replacements[1] = '';
+	$temp_input = $input;  
+	$temp_input = imap_8bit($temp_input); 
+
+	$patterns[0] = '/ /'; 
             $replacements[0] = '_';
-            $input = preg_replace($patterns, $replacements, $input);
-        }
-
-        return($input);
+	$temp_input = preg_replace($patterns, $replacements, $temp_input);  
+	return ($temp_input);
     }
 
@@ -522,5 +507,5 @@
         // Lê as regras fora do escritório;
         if ($this->newout != "") {
-            $newscriptfoot .= preg_replace("/[\\n\\r]/", "%0A", $this->newout) . "\n";
+            $newscriptfoot .= preg_replace("/[\\n\\r]/", " ", $this->newout) . "\n";
         }
         $newscriptfoot .= "#mode&&basic\n";
Index: trunk/expressoMail1_2/inc/class.attachment.inc.php
===================================================================
--- trunk/expressoMail1_2/inc/class.attachment.inc.php	(revision 5079)
+++ trunk/expressoMail1_2/inc/class.attachment.inc.php	(revision 5134)
@@ -32,19 +32,11 @@
      * @param integer $msgNumber Imap menssagem number
      */
-    function attachment($rootPath = false)
+    function attachment()
     {
         /*
          * Requires
          */
-        if($rootPath)
-        {
-            require_once $rootPath.'/library/mime/mimePart.php';
-            require_once $rootPath.'/library/mime/mimeDecode.php';
-        }
-        else
-        {
             require_once $_SESSION['rootPath'].'/library/mime/mimePart.php';
             require_once $_SESSION['rootPath'].'/library/mime/mimeDecode.php';
-        }
         //----------------------------------------------------------//
 
@@ -52,4 +44,7 @@
         $this->decodeConf['decode_bodies']  = true;
         $this->decodeConf['decode_headers'] = true;
+	
+	if( array_key_exists('nested_messages_are_shown', $_SESSION['phpgw_info']['user']['preferences']['expressoMail']) && ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['nested_messages_are_shown'] == '1'))
+	    $this->decodeConf['rfc_822bodies']  = true;
     }
     //----------------------------------------------------------------------------//
@@ -86,4 +81,10 @@
         $this->structure = $decoder->decode($this->decodeConf);
 
+		//TODO: Descartar código após atualização do módulo de segurança da SERPRO 
+		if($this->isSignedMenssage()) 
+			$this->convertSignedMenssage($rawMessageData); 
+		//////////////////////////////////////////////////////
+			
+			
         /*
          * Clean memory and close imap connection
@@ -95,4 +96,52 @@
     }
 
+	//TODO: Descartar código após atualização do módulo de segurança da SERPRO 
+	private function isSignedMenssage() 
+ 	{ 
+		if(strtolower($this->structure->ctype_primary) == 'application' && strtolower($this->structure->ctype_secondary) == 'x-pkcs7-mime' ) 
+			return true; 
+		else 
+			return false;      
+	} 
+    //////////////////////////////////////////////////////////////////////////
+
+   //TODO: Descartar código após atualização do módulo de segurança da SERPRO 
+   private function convertSignedMenssage($rawMessageData) 
+	{ 
+		$decoder = new Mail_mimeDecode($this->extractSignedContents($rawMessageData)); 
+		$this->structure = $decoder->decode($this->decodeConf);          
+	} 
+	///////////////////////////////////////////////////////////////////////////
+	
+	//TODO: Descartar código após atualização do módulo de segurança da SERPRO 
+	private function extractSignedContents( $data ) 
+ 		    { 
+ 		        $pipes_desc = array( 
+ 		            0 => array('pipe', 'r'), 
+ 		            1 => array('pipe', 'w') 
+ 		        ); 
+ 		 
+ 		        $fp = proc_open( 'openssl smime -verify -noverify -nochain', $pipes_desc, $pipes); 
+ 		        if (!is_resource($fp)) { 
+ 		           return false; 
+ 		        } 
+ 		 
+ 		        $output = ''; 
+ 		 
+ 		        /* $pipes[0] => writeable handle connected to child stdin 
+ 		           $pipes[1] => readable handle connected to child stdout */ 
+ 		        fwrite($pipes[0], $data); 
+ 		        fclose($pipes[0]); 
+ 		 
+ 		        while (!feof($pipes[1])) { 
+ 		            $output .= fgets($pipes[1], 1024); 
+ 		        } 
+ 		        fclose($pipes[1]); 
+ 		        proc_close($fp); 
+ 		 
+ 		        return $output; 
+ 		    } 
+	/////////////////////////////////////////////////////////////////////////////////////
+	
     /**
      * Set Stucture from Mail_mimeDecode Structure
@@ -116,4 +165,9 @@
         $decoder = new Mail_mimeDecode($rawMail);
         $this->structure = $decoder->decode($this->decodeConf);
+		
+		//TODO: Descartar código após atualização do módulo de segurança da SERPRO 
+		if($this->isSignedMenssage()) 
+			$this->convertSignedMenssage($rawMessageData);  
+		//////////////////////////////////////////////////////////////////////////
     }
 
@@ -169,5 +223,5 @@
         $attachment = array();
         $this->_getPartInfo($this->structure,$partNumber,$attachment);
-        return $attachment;
+        return $attachment[0];
     }
 
@@ -180,5 +234,9 @@
     private function _getRaw()
     {
-        return imap_fetchheader($this->mbox, $this->msgNumber, FT_UID).imap_body($this->mbox, $this->msgNumber, FT_UID);
+			/* 
+ 	         * Chamada original imap_fetchheader($this->mbox, $this->msgNumber, FT_UID)."\r\n".imap_body($this->mbox, $this->msgNumber, FT_UID); 
+ 	         * Inserido replace para corrigir um bug que acontece raramente em mensagens vindas do outlook com muitos destinatarios 
+ 	         */ 
+ 	        return str_replace("\r\n\t", '', imap_fetchheader($this->mbox, $this->msgNumber, FT_UID))."\r\n".imap_body($this->mbox, $this->msgNumber, FT_UID);
     }
 
@@ -202,10 +260,10 @@
                 else
                 {
-                    if(strtolower($part->ctype_primary) == 'message' && is_array($part->parts))
+                    if(strtolower($part->ctype_primary) == 'message' && is_array($part->parts) && $this->decodeConf['rfc_822bodies'] !== true )
                             $this->_getPartContent($part,$soughtIndex,$body,$pIndex.'.'.$index);
                     else
                     {
                         $currentIndex = $pIndex.'.'.$index;
-                        if($currentIndex == $soughtIndex)
+                        if($currentIndex === $soughtIndex)
                         {
                             $body = $part->body;
@@ -235,10 +293,10 @@
                 else
                 {
-                    if(strtolower($part->ctype_primary) == 'message' && is_array($part->parts))
+                    if(strtolower($part->ctype_primary) == 'message' && is_array($part->parts) && $this->decodeConf['rfc_822bodies'] !== true)
                          $this->_getPartInfo($part,$soughtIndex,$info,$pIndex.'.'.$index);
                     else
                     {
                         $currentIndex = $pIndex.'.'.$index;
-                        if($currentIndex == $soughtIndex)
+                        if($currentIndex === $soughtIndex)
                         {
 							$this->_pushAttachmentsInfo($part,$info,$currentIndex);
@@ -262,5 +320,5 @@
     {
 
-        if($structure->parts)
+        if(isset($structure->parts))
         {
             foreach ($structure->parts  as $index => $part)
@@ -270,5 +328,5 @@
                 else
                 {
-                    if(strtolower($part->ctype_primary) == 'message' && is_array($part->parts))
+                    if(strtolower($part->ctype_primary) == 'message' && is_array($part->parts) && $this->decodeConf['rfc_822bodies'] !== true)
                        $this->_getAttachmentsInfo($part,$attachments,$pIndex.'.'.$index);
                     else
@@ -293,19 +351,46 @@
 	/**
 	* Write in $$attachments, array with the information of attachment 
-	*
-	* @license    http://www.gnu.org/copyleft/gpl.html GPL
-	* @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
-	* @sponsor    Caixa Econômica Federal
-	* @param      $structure
-	* @param      $attachments
-	* @param      $pIndex
+ 	* @param <type> $structure 
+ 	* @param <type> $attachments 
+ 	* @param <type> $pIndex 
 	*/	
  	private function _pushAttachmentsInfo(&$structure, &$attachments, $pIndex = '0') 
  	{ 
- 		        $name = false; 
- 		        if($structure->d_parameters['filename']) $name = $structure->d_parameters['filename']; 
- 		        else if($structure->ctype_parameters['name']) $name = $structure->ctype_parameters['name']; 
+			$name = '';                                
+ 		        if((isset($structure->d_parameters['filename']))&& ($structure->d_parameters['filename'])) $name = $structure->d_parameters['filename']; 
+ 		        else if((isset($structure->ctype_parameters['name']))&&($structure->ctype_parameters['name'])) $name = $structure->ctype_parameters['name'];
  		        else if(strtolower($structure->ctype_primary) == 'text' &&  strtolower($structure->ctype_secondary) == 'calendar') $name = 'calendar.ics'; 
  		 
+                            //Attachments com nomes grandes são quebrados em varias partes VER RFC2231
+                            if( !$name && isset($structure->disposition) && (strtolower($structure->disposition) === 'attachment' || strtolower($structure->ctype_primary) == 'image'))
+					foreach ($structure->d_parameters as $i => $v)
+						if(strpos($i , 'filename') !== false)
+							$name .= urldecode(str_ireplace(array('ISO-8859-1','UTF-8','US-ASCII'),'',$v));
+			     if( !$name && isset($structure->disposition) && (strtolower($structure->disposition) === 'attachment' || strtolower($structure->ctype_primary) == 'image') )
+					foreach ($structure->ctype_parameters as $i => $v)
+						if(strpos($i , 'name') !== false)
+							$name .= urldecode(str_ireplace(array('ISO-8859-1','UTF-8','US-ASCII'),'',$v));		
+			   ////////////////////////////////////////////////////////////////////////////////////
+						
+
+                        if($structure->ctype_primary == 'message') {
+                                $attach = new attachment();
+                                $attach->setStructureFromRawMail($structure->body);
+
+                                if (!$name)
+                                        $name = ($attach->structure->headers['subject']) ? $attach->structure->headers['subject'] : 'no title';
+
+                                if (!preg_match("/\.eml$/", $name))
+                                        $name .= '.eml';
+                        }		                               
+
+                        if(!$name && strtolower($structure->ctype_primary) == 'image')
+                        {
+                            if(strlen($structure->ctype_secondary) === 3)
+                                $ext = strtolower($structure->ctype_secondary);
+
+                            $name = 'Embedded-Image.'.$ext;
+                        }
+				
  		        if($name) 
  		        { 
@@ -316,4 +401,5 @@
  		            $definition['name'] = addslashes(mb_convert_encoding($name, "ISO-8859-1")); 
  		            $definition['encoding'] = $structure->headers['content-transfer-encoding']; 
+                            $definition['type'] = strtolower($structure->ctype_primary).'/'.strtolower($structure->ctype_secondary);                                       
  		            $definition['fsize'] = mb_strlen($structure->body, $structure->headers['content-transfer-encoding']); 
  		 
@@ -334,4 +420,5 @@
      private function _getEmbeddedImagesInfo($structure, &$images, $pIndex = '0')
      {
+		if(isset($structure->parts))
         foreach ($structure->parts  as $index => $part)
         {
@@ -340,20 +427,30 @@
             else
             {
-                if(strtolower($part->ctype_primary) == 'message' && is_array($part->parts))
+                if(strtolower($part->ctype_primary) == 'message' && is_array($part->parts) && $this->decodeConf['rfc_822bodies'] !== true)
                         $this->_getEmbeddedImagesInfo($part,$images,$pIndex.'.'.$index);
                 else
                 {
-                    if(!$part->ctype_parameters['name'])
+                    if(is_array($part->ctype_parameters) && !array_key_exists('name', $part->ctype_parameters))
+                        if(isset($part->d_parameters['filename']))
                          $name = $part->d_parameters['filename'];
                     else
+                          $name = null;
+                    else
                          $name = $part->ctype_parameters['name'];
 
-                    $type =  strtolower(substr($name, -4));
+                    if($name && (strlen($name) - (strrpos($name, '.')+1) === 3 )) 
+                        $ext = strtolower(substr ( $name , (strrpos($name, '.')+1) ));		
+                    else if(strlen($structure->ctype_secondary) === 3)
+                        $ext = strtolower($structure->ctype_secondary);
+                    
+                    if(!$name && strtolower($structure->ctype_primary) == 'image') $name = 'Embedded-Image.'.$ext;
+					
                     $ctype = strtolower($part->ctype_primary.'/'.$part->ctype_secondary);
-                    if(strtolower($part->ctype_primary) == 'image' ||  ($ctype == 'application/octet-stream' && ($type == '.png' || $type == '.jpg' || $type == '.gif')))
+        
+                    if(strtolower($part->ctype_primary) == 'image' ||  ($ctype == 'application/octet-stream' && ($ext == 'png' || $ext == 'jpg' || $ext == 'gif' || $ext == 'bmp' || $ext == 'tif')))
                     {
                         $definition['pid'] = $pIndex.'.'.$index;
                         $definition['name'] = addslashes($name);
-                        $definition['type'] = 'image/'.strtolower($part->ctype_secondary);
+                        $definition['type'] = $ctype;
                         $definition['encoding'] = $part->headers['content-transfer-encoding'];
                         $definition['cid'] = $part->headers['content-id'];
Index: trunk/expressoMail1_2/inc/class.message_components.inc.php
===================================================================
--- trunk/expressoMail1_2/inc/class.message_components.inc.php	(revision 3858)
+++ trunk/expressoMail1_2/inc/class.message_components.inc.php	(revision 5134)
@@ -105,5 +105,6 @@
 
                     $ftype        = (empty($parts[$p]->type))?           $this->data_types[0].'/'.strtolower($parts[$p]->subtype) : $this->data_types[$parts[$p]->type].'/'.strtolower($parts[$p]->subtype);
-                    $encoding     = (empty($parts[$p]->encoding))?       $this->encoding_types[0] : $this->encoding_types[$parts[$p]->encoding];
+                    $encoding     = (isset($parts[$p]->encoding) && !empty($parts[$p]->encoding) && isset($this->encoding_types[$parts[$p]->encoding]) )?      $this->encoding_types[$parts[$p]->encoding]  : $this->encoding_types[0];
+                  
                     if(!preg_match("/5./",phpversion()))
 	                    $charset      = $parts[$p]->parameters[0]->value;
Index: trunk/expressoMail1_2/inc/class.imap_attachment.inc.php
===================================================================
--- trunk/expressoMail1_2/inc/class.imap_attachment.inc.php	(revision 3289)
+++ trunk/expressoMail1_2/inc/class.imap_attachment.inc.php	(revision 5134)
@@ -26,5 +26,5 @@
 		include_once("class.message_components.inc.php");
 
-		$msg =& new message_components($mbox);
+		$msg = new message_components($mbox);
 		$msg->fetch_structure($msgno);
 
@@ -50,5 +50,5 @@
 		include_once("class.message_components.inc.php");
 
-		$msg =& new message_components($mbox);
+		$msg = new message_components($mbox);
 		$msg->fetch_structure($msgno);
 		$array_parts_attachments = array();		
Index: trunk/expressoMail1_2/inc/get_archive.php
===================================================================
--- trunk/expressoMail1_2/inc/get_archive.php	(revision 5069)
+++ trunk/expressoMail1_2/inc/get_archive.php	(revision 5134)
@@ -1,40 +1,3 @@
 <?php
-/**
-*
-* Copyright (C) 2011 Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
-*
-* This program is free software; you can redistribute it and/or modify it under
-* the terms of the GNU Affero General Public License version 3 as published by
-* the Free Software Foundation with the addition of the following permission
-* added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
-* WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
-* WARRANTY OF NON INFRINGEMENT  OF THIRD PARTY RIGHTS.
-*
-* This program is distributed in the hope that it will be useful, but WITHOUT
-* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-* FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
-* details.
-*
-* You should have received a copy of the GNU Affero General Public License
-* along with this program; if not, see www.gnu.org/licenses or write to
-* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
-* MA 02110-1301 USA.
-*
-* This code is based on the OpenXchange Connector and on the Prognus pSync
-* Connector both developed by the community and licensed under the GPL
-* version 2 or above as published by the Free Software Foundation.
-*
-* You can contact Prognus Software Livre headquarters at Av. Tancredo Neves,
-* 6731, PTI, Bl. 05, Esp. 02, Sl. 10, Foz do Iguaçu - PR - Brasil or at
-* e-mail address prognus@prognus.com.br.
-*
-*
-* @package    expressoMail
-* @license    http://www.gnu.org/copyleft/gpl.html GPL
-* @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
-* @version    1.0
-* @sponsor    Caixa Econômica Federal
-*/
-
 /*
  * Definitions
@@ -52,9 +15,4 @@
 //-----------------------//
 
-/*
- * Requires
- */
-require_once 'class.attachment.inc.php';
-require_once '../../header.inc.php';
 //-----------------------//
 
@@ -62,183 +20,223 @@
  * Get variables
  */
-$newFilename = urldecode($_GET['newFilename']);
-$indexFile = $_GET['idx_file'];
+if(array_key_exists('newFilename', $_GET ) && urldecode($_GET['newFilename']) !== 'application.octet-stream')
+	$newFilename = urldecode($_GET['newFilename']);
+else
+	$newFilename = null;
+if(array_key_exists('idx_file', $_GET ))
+	$indexFile = $_GET['idx_file'];
+else
+	$indexFile = null;
+
 $indexPart = $_GET['indexPart'];
 $msgNumber = $_GET['msgNumber'];
 $msgFolder = $_GET['msgFolder'];
+if(array_key_exists('fileType', $_GET ))
+	$ContentType = $_GET['fileType'];
+else
+	$ContentType = null;
+if(array_key_exists('image', $_GET ))
+	$image = $_GET['image'];
+else
+	$image = null;
 //----------------------------------------------//
 
-
-/**
-* Método que faz o download do arquivo
-*
-* @license    http://www.gnu.org/copyleft/gpl.html GPL
-* @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
-* @sponsor    Caixa Econômica Federal
-* @param  $strFileType
-* @param  $strFileName
-* @param  $newFileName
-* @param  $fileContent
-*/
-function downloadFile($strFileType, $strFileName, $newFileName, $fileContent) {
-
-        $ContentType = "application/octet-stream";
-
-        if ($strFileType == ".asf")
-                $ContentType = "video/x-ms-asf";
-        if ($strFileType == ".avi")
-                $ContentType = "video/avi";
-        if ($strFileType == ".doc")
-                $ContentType = "application/msword";
-        if ($strFileType == ".zip")
-                $ContentType = "application/zip";
-        if ($strFileType == ".xls")
-                $ContentType = "application/vnd.ms-excel";
-        if ($strFileType == ".gif")
-                $ContentType = "image/gif";
-        if ($strFileType == ".jpg" || $strFileType == "jpeg")
-                $ContentType = "image/jpeg";
-        if ($strFileType == ".wav")
-                $ContentType = "audio/wav";
-        if ($strFileType == ".mp3")
-                $ContentType = "audio/mpeg3";
-        if ($strFileType == ".mpg" || $strFileType == "mpeg")
-                $ContentType = "video/mpeg";
-        if ($strFileType == ".rtf")
-                $ContentType = "application/rtf";
-        if ($strFileType == ".htm" || $strFileType == "html")
-                $ContentType = "text/html";
-        if ($strFileType == ".xml")
-                $ContentType = "text/xml";
-        if ($strFileType == ".xsl")
-                $ContentType = "text/xsl";
-        if ($strFileType == ".css")
-                $ContentType = "text/css";
-        if ($strFileType == ".php")
-                $ContentType = "text/php";
-        if ($strFileType == ".asp")
-                $ContentType = "text/asp";
-        if ($strFileType == ".pdf")
-                $ContentType = "application/pdf";
-        if ($strFileType == ".txt")
-                $ContentType = "text/plain";
-        if ($strFileType == ".log")
-                $ContentType = "text/plain";
-        if ($strFileType == ".wmv")
-                $ContentType = "video/x-ms-wmv";
-        if ($strFileType == ".sxc")
-                $ContentType = "application/vnd.sun.xml.calc";
-        if ($strFileType == ".odt")
-                $ContentType = "application/vnd.oasis.opendocument.text";
-        if ($strFileType == ".stc")
-                $ContentType = "application/vnd.sun.xml.calc.template";
-        if ($strFileType == ".sxd")
-                $ContentType = "application/vnd.sun.xml.draw";
-        if ($strFileType == ".std")
-                $ContentType = "application/vnd.sun.xml.draw.template";
-        if ($strFileType == ".sxi")
-                $ContentType = "application/vnd.sun.xml.impress";
-        if ($strFileType == ".sti")
-                $ContentType = "application/vnd.sun.xml.impress.template";
-        if ($strFileType == ".sxm")
-                $ContentType = "application/vnd.sun.xml.math";
-        if ($strFileType == ".sxw")
-                $ContentType = "application/vnd.sun.xml.writer";
-        if ($strFileType == ".sxq")
-                $ContentType = "application/vnd.sun.xml.writer.global";
-        if ($strFileType == ".stw")
-                $ContentType = "application/vnd.sun.xml.writer.template";
-        if ($strFileType == ".ps")
-                $ContentType = "application/postscript";
-        if ($strFileType == ".pps")
-                $ContentType = "application/vnd.ms-powerpoint";
-        if ($strFileType == ".odt")
-                $ContentType = "application/vnd.oasis.opendocument.text";
-        if ($strFileType == ".ott")
-                $ContentType = "application/vnd.oasis.opendocument.text-template";
-        if ($strFileType == ".oth")
-                $ContentType = "application/vnd.oasis.opendocument.text-web";
-        if ($strFileType == ".odm")
-                $ContentType = "application/vnd.oasis.opendocument.text-master";
-        if ($strFileType == ".odg")
-                $ContentType = "application/vnd.oasis.opendocument.graphics";
-        if ($strFileType == ".otg")
-                $ContentType = "application/vnd.oasis.opendocument.graphics-template";
-        if ($strFileType == ".odp")
-                $ContentType = "application/vnd.oasis.opendocument.presentation";
-        if ($strFileType == ".otp")
-                $ContentType = "application/vnd.oasis.opendocument.presentation-template";
-        if ($strFileType == ".ods")
-                $ContentType = "application/vnd.oasis.opendocument.spreadsheet";
-        if ($strFileType == ".ots")
-                $ContentType = "application/vnd.oasis.opendocument.spreadsheet-template";
-        if ($strFileType == ".odc")
-                $ContentType = "application/vnd.oasis.opendocument.chart";
-        if ($strFileType == ".odf")
-                $ContentType = "application/vnd.oasis.opendocument.formula";
-        if ($strFileType == ".odi")
-                $ContentType = "application/vnd.oasis.opendocument.image";
-        if ($strFileType == ".ndl")
-                $ContentType = "application/vnd.lotus-notes";
-        if ($strFileType == ".eml")
-                $ContentType = "text/plain";
-
-        header ("Content-Type: $ContentType");
-        header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
-        header("Pragma: public");
-        header("Expires: 0"); // set expiration time
-        header ("Content-Disposition: attachment; filename=\"". addslashes($newFileName)."\"");
-
-        if($fileContent)
+/*
+ * Requires
+ */
+if( $indexFile )
+    require_once '../../header.inc.php';
+else
+    require_once '../../header.session.inc.php';
+
+
+/*
+ * Functions
+ */
+
+function unhtmlentities($string)
+{
+    $string = utf8_encode($string);
+    
+    static $trans_tbl;
+ 
+    $string = preg_replace('~&#x([0-9a-f]+);~ei', 'code2utf(hexdec("\\1"))', $string);
+    $string = preg_replace('~&#([0-9]+);~e', 'code2utf(\\1)', $string);
+
+    if (!isset($trans_tbl))
         {
-          echo $fileContent;
+        $trans_tbl = array();
+       
+        foreach (get_html_translation_table(HTML_ENTITIES) as $val=>$key)
+            $trans_tbl[$key] = utf8_encode($val);
         }
-        else
-        {
-                $tempDir = $GLOBALS['phpgw_info']['server']['download_temp_dir'];
-                if (preg_match("#^".$tempDir."/(".$GLOBALS['phpgw']->session->sessionid."/)*[A-z0-9_]+_".$GLOBALS['phpgw']->session->sessionid."[A-z0-9]*(\.[A-z]{3,4})?$#",$strFileName))
-                {
-                //avoid stuck request
-                        session_write_close();
-
-                        //reset time limit for big files
-                        set_time_limit(0);
-                        ob_end_flush();
-
-                        if ($fp = fopen ($strFileName, 'rb'))
-                        {
-                                $bufferSize=1024;
-                                for ($i=$bufferSize; $i<=(filesize($strFileName)+$bufferSize); $i+=$bufferSize)
+    return strtr($string, $trans_tbl);
+}
+
+function code2utf($num)
+{
+    if ($num < 128) return chr($num);
+    if ($num < 2048) return chr(($num >> 6) + 192) . chr(($num & 63) + 128);
+    if ($num < 65536) return chr(($num >> 12) + 224) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
+    if ($num < 2097152) return chr(($num >> 18) + 240) . chr((($num >> 12) & 63) + 128) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
+    return '';
+}
+
+//-----------------------//
+
+/*
+ * Main
+ */
+
+
+if($msgNumber != 'null' && $indexPart !== null && $msgFolder)
+{
+    require_once $_SESSION['rootPath'].'/expressoMail1_2/inc/class.attachment.inc.php';
+
+    $attachment = new attachment();
+    $attachment->setStructureFromMail($msgFolder, $msgNumber);
+    $fileContent = $attachment->getAttachment($indexPart);
+    $info = $attachment->getAttachmentInfo($indexPart);
+    $filename = $newFilename ? $newFilename : $info['name'];       
+    $filename = unhtmlentities($filename);
+}
+else
+{
+    if( $image && $_SESSION['phpgw_info']['expressomail']['contact_photo'] )
                                 {
-                                        echo fread($fp, $i);
-                                        flush();
-                                }
-                                fclose ($fp);
-                        }
-
-                        //removendo pelo php, garante a suportabilidade cross-platform
-                        cleanup( dirname( $strFileName ) );
-
+	$image = "thumbnail";
+
+	$photo = array( 'width' => 60, 'height' => 80, 'quality' => 100 );
+
+	$fileContent = $_SESSION['phpgw_info']['expressomail']['contact_photo'][0];
+	unset( $_SESSION['phpgw_info']['expressomail']['contact_photo'] );
                 }
+
+    $filename = $indexFile;
+}
+
+$filename = $filename 	? $filename 	: "attachment.bin";
+$newFilename = $newFilename ? $newFilename 	: $filename;
+$newFilename = unhtmlentities($newFilename);
+$disposition = $image ? "inline" : "attachment; filename=\"". addslashes($newFilename)."\"";
+
+if( !$ContentType || $ContentType == 'application/octet-stream')
+{
+    
+    if( strstr($_SERVER['HTTP_USER_AGENT'],'MSIE') && $disposition != 'inline' )
+        $ContentType = 'application-download';
                 else
                 {
-                        if (preg_match("#^".dirname( __FILE__ ) . '/../tmpLclAtt'."/source_#",$strFileName)) {
-                                readfile($strFileName);
+        function guessContentType( $fileName )
+        {
+            $strFileType = strtolower(substr ( $fileName , strrpos($fileName, '.') ));
+                         
+	    switch( $strFileType )
+	    {
+		case ".asf": return "video/x-ms-asf";
+		case ".avi": return "video/avi";
+		case ".doc": return "application/msword";
+		case ".zip": return "application/zip";
+		case ".xls": return "application/vnd.ms-excel";
+		case ".gif": return "image/gif";
+                case ".bmp": return "image/bmp";
+		case ".jpeg":
+		case ".jpg": return "image/jpeg";
+		case ".wav": return "audio/wav";
+		case ".mp3": return "audio/mpeg3";
+		case ".mpeg":
+		case ".mpg": return "video/mpeg";
+		case ".rtf": return "application/rtf";
+		case ".html":
+		case ".htm": return "text/html";
+		case ".xml": return "text/xml";
+		case ".xsl": return "text/xsl";
+		case ".css": return "text/css";
+		case ".php": return "text/php";
+		case ".asp": return "text/asp";
+		case ".pdf": return "application/pdf";
+		case ".png": return "image/png";
+		case ".txt": return "text/plain";
+		case ".log": return "text/plain";
+		case ".wmv": return "video/x-ms-wmv";
+		case ".sxc": return "application/vnd.sun.xml.calc";
+		case ".odt": return "application/vnd.oasis.opendocument.text";
+		case ".stc": return "application/vnd.sun.xml.calc.template";
+		case ".sxd": return "application/vnd.sun.xml.draw";
+		case ".std": return "application/vnd.sun.xml.draw.template";
+		case ".sxi": return "application/vnd.sun.xml.impress";
+		case ".sti": return "application/vnd.sun.xml.impress.template";
+		case ".sxm": return "application/vnd.sun.xml.math";
+		case ".sxw": return "application/vnd.sun.xml.writer";
+		case ".sxq": return "application/vnd.sun.xml.writer.global";
+		case ".stw": return "application/vnd.sun.xml.writer.template";
+		case ".pps": return "application/vnd.ms-powerpoint";
+		case ".odt": return "application/vnd.oasis.opendocument.text";
+		case ".ott": return "application/vnd.oasis.opendocument.text-template";
+		case ".oth": return "application/vnd.oasis.opendocument.text-web";
+		case ".odm": return "application/vnd.oasis.opendocument.text-master";
+		case ".odg": return "application/vnd.oasis.opendocument.graphics";
+		case ".otg": return "application/vnd.oasis.opendocument.graphics-template";
+		case ".odp": return "application/vnd.oasis.opendocument.presentation";
+		case ".otp": return "application/vnd.oasis.opendocument.presentation-template";
+		case ".ods": return "application/vnd.oasis.opendocument.spreadsheet";
+		case ".ots": return "application/vnd.oasis.opendocument.spreadsheet-template";
+		case ".odc": return "application/vnd.oasis.opendocument.chart";
+		case ".odf": return "application/vnd.oasis.opendocument.formula";
+		case ".odi": return "application/vnd.oasis.opendocument.image";
+		case ".ndl": return "application/vnd.lotus-notes";
+		case ".eml": return "text/plain";
+		case ".ps" : return "application/postscript";
+		default    : return "application/octet-stream";
                         }
                 }
+
+        $ContentType = guessContentType( $filename );
         }
 }
 
-
-/**
-* Método que limpa o diretório
-*
-* @license    http://www.gnu.org/copyleft/gpl.html GPL
-* @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
-* @sponsor    Caixa Econômica Federal
-* @param  $dir
-*/
-function cleanup( $dir )
-{
+header("Content-Type: $ContentType");
+header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
+header("Pragma: public");
+header("Expires: 0"); // set expiration time
+header("Content-Disposition: $disposition");
+
+if( $fileContent )
+{
+    header("Content-transfer-encoding: ".$info["encoding"] );
+
+    if( $image === "thumbnail" )
+    {
+	$pic = imagecreatefromstring( $fileContent );
+
+	if( $pic )
+	{
+	    $width = imagesx($pic);
+	    $height = imagesy($pic);
+
+	    if(!isset($photo))
+			$photo = array( 'width' => 160, 'height' => max( ( 160 * $height / $width ), 1 ) );
+
+	    $thumb = imagecreatetruecolor( $photo['width'], $photo['height'] );
+
+	    if(array_key_exists('quality', $photo)  && $photo['quality'] )
+			imagecopyresampled($thumb, $pic, 0, 0, 0, 0, $photo['width'], $photo['height'], $width, $height);
+	    else
+		imagecopyresized($thumb, $pic, 0, 0, 0, 0, $photo['width'], $photo['height'], $width, $height); # resize image into thumb
+
+	    imagejpeg( $thumb,"", 100 ); # Thumbnail as JPEG
+	}
+    }
+    else
+	echo $fileContent;
+}
+else
+{
+    /**
+    * Delete Diretorio
+    * @param string $dir 
+    */
+    function cleanup( $dir )
+    {
     if ( is_dir( $dir ) )
     {
@@ -260,40 +258,28 @@
     }
 
-}
-//-----------------------//
-
-/*
- * Main
- */
-
-
-if($msgNumber != 'null' && $indexPart !== null && $msgFolder)
-{
-
-    $attachment = new attachment(PHPGW_INCLUDE_ROOT);
-    $attachment->setStructureFromMail($msgFolder, $msgNumber);
-    $fileContent = $attachment->getAttachment($indexPart);
-
-    if($newFilename)
-        $filename = $newFilename;
+    }
+
+    $tempDir = $GLOBALS['phpgw_info']['server']['download_temp_dir'];
+
+    if (preg_match("#^".$tempDir."/(".$GLOBALS['phpgw']->session->sessionid."/)*[A-z0-9_]+_".$GLOBALS['phpgw']->session->sessionid."[A-z0-9]*(\.[A-z]{3,4})?$#",$filename))
+    {
+        session_write_close();
+        set_time_limit(0);
+        ob_clean();
+        flush();
+        readfile($filename);
+
+        //removendo pelo php, garante a suportabilidade cross-platform
+	cleanup(  $filename  );
+
+    }
     else
     {
-        $info = $attachment->getAttachmentInfo($indexPart);
-        $filename = $info['name'];
-    }
-
-
-}
-else
-    $filename = $indexFile;
-
-
-$filename 	 = $filename 	? $filename 	: "attachment.bin";
-$newFilename = $newFilename ? $newFilename 	: $filename;
-
-
-$strFileType = strrev(substr(strrev(strtolower($filename)),0,4));
-
-downloadFile($strFileType,  $filename, $newFilename, $fileContent)
+	    if (preg_match("#^".dirname( __FILE__ ) . '/../tmpLclAtt'."/source_#",$filename)) {
+		    readfile($filename);
+	    }
+    }
+}
+
 //-----------------------//
 
Index: trunk/expressoMail1_2/inc/class.ldap_functions.inc.php
===================================================================
--- trunk/expressoMail1_2/inc/class.ldap_functions.inc.php	(revision 5075)
+++ trunk/expressoMail1_2/inc/class.ldap_functions.inc.php	(revision 5134)
@@ -24,4 +24,5 @@
 		@include("../contactcenter/setup/external_catalogs.inc.php");
 		$this->ldapService = ServiceLocator::getService('ldap');
+		if(isset($external_srcs))
 		$this->external_srcs = $external_srcs;
 		$this->max_result = $this->ldapService->limit;
@@ -65,5 +66,5 @@
 		ldap_set_option($ds, LDAP_OPT_REFERRALS, $refer);
 		if ($refer)
-			ldap_set_rebind_proc($ds, ldapRebind);
+			ldap_set_rebind_proc($ds, 'rebind');
 		@ldap_bind($ds, $_SESSION['phpgw_info']['expressomail']['ldap_server']['acc'],$_SESSION['phpgw_info']['expressomail']['ldap_server']['pw']);
 
@@ -88,18 +89,4 @@
 		$functions = new functions;
 
-//		$search_for	= utf8_encode($params['search_for']);
-  //Testa se a busca foi realizada com aspas
-		$search_for	= utf8_encode($params['search_for']);
-                $search_len = (strlen($search_for)) - 1;
-                $quote_status=false;
-
-                if((($search_for{0}) == "\"") && (($search_for{$search_len}) == "\"")){
-                    $search_for{0} = " ";
-                    $search_for{$search_len} = " ";
-                    $quote_status=true;
-                }
-
-
-
 		$field		= $params['field'];
 		$ID			= $params['ID'];
@@ -118,30 +105,5 @@
 		if ($this->ds)
 		{
-			if (($field != 'null') && ($ID != 'null'))
-			{
-				$filter="(& (&(|(phpgwAccountType=u)(phpgwAccountType=g)(phpgwAccountType=l))(mail=*)) (|(cn=*$search_for*)(mail=*$search_for*)) (!(phpgwaccountvisible=-1)) )";
-				if($extendedinfo)
-				$justthese = array("cn", "mail", "telephoneNumber", "mobile", "phpgwAccountVisible", "uid", "employeeNumber", "ou");
-				else
-				    $justthese = array("cn", "mail", "telephoneNumber", "mobile", "phpgwAccountVisible", "uid");
-			}
-			else
-			{
-				if($quote_status){
-                                	$filter="(& (phpgwAccountType=u) (|(cn=* $search_for *)(cn=$search_for *)(cn=* $search_for)) (!(phpgwaccountvisible=-1)) )";
-                            	}
-                            	else{
-					$filter="(& (phpgwAccountType=u)(cn=*$search_for*) (!(phpgwaccountvisible=-1)) )";
-                            	}
-			//	$filter="(& (phpgwAccountType=u)(cn=*$search_for*) (!(phpgwaccountvisible=-1)) )";
-				if($extendedinfo)
-				$justthese = array("cn", "mail", "telephoneNumber", "mobile", "phpgwAccountVisible","jpegPhoto", "uid", "employeeNumber", "ou");
-				else
-				    $justthese = array("cn", "mail", "telephoneNumber", "mobile", "phpgwAccountVisible","jpegPhoto", "uid");
-			}
-			$sr=@ldap_search($this->ds, $this->ldap_context, $filter, $justthese, 0, $this->max_result + 1);
-			if(!$sr)
-				return null;
-			$count_entries = ldap_count_entries($this->ds,$sr);
+                    $ldapService->connection = $this->ds;
 
                 $justthese = array("cn", "mail", "telephonenumber", "mobile", "phpgwaccountvisible", "uid", "employeenumber", "ou");
@@ -301,9 +263,4 @@
              
             include_once $_SESSION['rootPath']. '/header.inc.php';
-            
-                      
-            if (stripos( $params['search_for'] , '@' ) !== false) 
-                $params['search_for'] = substr($params['search_for'], 0 , stripos( $params['search_for'] , '@' ) ); 
-            
             
             if($modal)
@@ -383,4 +340,8 @@
                 $results['type_catalog'] = "P";
             $results['search_for'] = $params['search_for'];
+			
+			foreach($results as $i=>$value)
+				$results[$i]['type_contact'] = "P";
+			
 			return $results;
         } 
@@ -408,5 +369,5 @@
                 if (is_numeric($parts[3]) && $parts[1]=='attribute')
                 {    
-                    if($parts[2] == 'searchable' && $value == 'true')
+                    if($parts[2] == 'searchable' /*&& $value == 'true'*/)
                         $searchable_fields[$all_data['cc_attribute_ldapname_' . $parts[3]]] = $all_data['cc_attribute_name_' . $parts[3]];   
                 }
@@ -485,4 +446,7 @@
             $info_return['search_for'] = $params['search_for'];
 			$info_return['extra_ldap_fields'] = $campos_extras; 
+			
+			foreach($info_return as $i=>$value)
+				$info_return[$i]['type_contact'] = "G";
             return $info_return;
         } 
@@ -640,23 +604,33 @@
 			$_SESSION['phpgw_info']['expressomail']['server']['ldap_root_pw']);
 
-			$groups = $ldapService->accountSearch($params['filter'], array("gidNumber","cn"), $params['context'] , 'g', 'cn'); 
-			$users = $ldapService->accountSearch($params['filter'], array("uidNumber","cn"), $params['context'] , 'u', 'cn');
+			$groups = $ldapService->accountSearch($params['filter'], array("gidNumber","cn", 'uid'), $params['context'] , 'g', 'cn'); 
+			$users = $ldapService->accountSearch($params['filter'], array("uidNumber","cn", 'uid'), $params['context'] , 'u', 'cn');
+			$compartilhadas = $ldapService->accountSearch($params['filter'], array("uidNumber","cn",'uid'), $params['context'] , 's', 'cn');
+			
+
 			$group_options = array();
 			$user_options  = array();
+			$shared_options = array();
+
 			foreach($groups as $group)
 	        {
-				$group_options[] = '"'.$group['gidNumber'].'U'.'":"'.$group['cn'].'"';
+	                	$group_options[] = '"'.$group['gidnumber'].'U'.'":"'.$group['cn'].' ('.$group['uid'].')"';
 	        }
-
 	        foreach($users as $user) 
 	            {
-				if($owner != $user['uidNumber'])
-					$user_options[] = '"'.$user['uidNumber'].'U'.'":"'.$user['cn'].'"';
+	            		if($owner != $user['uidnumber'])  
+			                $user_options[] = '"'.$user['uidnumber'].'U'.'":"'.$user['cn'].' ('.$user['uid'].')"';
+		        }	
+        		foreach($compartilhadas as $shared)
+                	{
+	            		if($owner != $shared['uidnumber'])  
+			                $shared_options[] = '"'.$shared['uidnumber'].'U'.'":"'.$shared['cn'].' ('.$shared['uid'].')"';
 	            }
 	
 			$user_options = '{'.implode( ',', $user_options ).'}';
 			$group_options = '{'.implode( ',', $group_options ).'}';
-
-	        return array("users" => $user_options, "groups" => $group_options);
+	                $shared_options = '{'.implode( ',', $shared_options ).'}';
+
+	         return '{"users":'.$user_options.',"groups":'.$group_options.',"shared":'. $shared_options .'}';
         }
 
@@ -996,4 +970,154 @@
 		return false;
 	}
+	
+	function get_user_groups($uid)
+	{
+
+		$organizations = array();
+	
+		$this->ldapRootConnect();
+
+                $justthese = array("gidnumber","cn");
+                $filter="(&(phpgwAccountType=g)(memberuid=".$uid."))";
+
+                $search = ldap_search($this->ds, $this->ldap_context, $filter, $justthese);
+
+                $result = array();
+                $entries = ldap_get_entries($this->ds, $search);
+
+
+                for ($i=0; $i<$entries['count']; $i++)
+                {
+                        $result[ $entries[$i]['gidnumber'][0] ] = $entries[$i]['cn'][0];
+                }
+
+		return $result;
+	}
+        
+       function getMailByUid($pUid)
+        {
+                // do not follow the referral
+                $this->ldapRootConnect(false);
+                if ($this->ds)
+                {
+                        $filter="(&(|(phpgwAccountType=u)(phpgwAccountType=s)(phpgwAccountType=l))(uid=$pUid))";
+                        $justthese = array("mail");
+                        $sr=@ldap_search($this->ds, $this->ldap_context, $filter, $justthese);
+                        if(!$sr)
+                                return false;
+                        $info = ldap_get_entries($this->ds, $sr);
+
+
+                        return utf8_decode($info[0]["mail"][0]);
+                }
+                return false;
+        } 
+  
+        function mail2uid($mail)
+	{
+                if(!$this-ds)
+                    $this->ldapRootConnect(false);
+
+                $filter="(&(|(phpgwAccountType=u)(phpgwAccountType=s)(phpgwAccountType=i)(phpgwAccountType=g))(mail=$mail))";
+                $justthese = array("uid");
+                $sr=@ldap_search($this->ds, $this->ldap_context, $filter, $justthese);
+                if(!$sr)
+                    return false;
+                $info = ldap_get_entries($this->ds, $sr);
+                return $info[0]["uid"][0];
+	}
+
+        
+        /**
+         * Retorna as contas compartilhas
+         * @param string $toaddress emails
+         * @param string $ccaddress emails
+         * @param string $ccoaddress emails
+         * @param array $groups array com os grupos que o usuario pertence
+         * @return array
+         */
+        function returnSharedsAccounts($toaddress,$ccaddress,$ccoaddress)
+        {
+
+          $arrayAllAddres = array();
+          $arrayAllAddres =  array_merge($arrayAllAddres , explode(',',$toaddress));
+          $arrayAllAddres =  array_merge($arrayAllAddres, explode(',',$ccaddress));
+          $arrayAllAddres = array_merge($arrayAllAddres, explode(',',$ccoaddress));
+
+          $mailsArray = array();
+
+           foreach ($arrayAllAddres as $toAddres)
+           {
+
+               if(strchr($toAddres,'@') && strchr($toAddres,'<') && strchr($toAddres,'>'))
+               {
+                    $alias = substr($toAddres, strpos($toAddres,'<'), strpos($toAddres,'>'));
+                    $alias = str_replace('<','', str_replace('>','',$alias));
+                    array_push($mailsArray, $alias);
+               }
+               else if(strchr($toAddres,'@'))
+               {
+                    array_push($mailsArray, $toAddres);
+               }
+           }
+           $arraySharedAccounts = array();
+
+           $conexao = $this->ldapConnect2(true);
+
+
+           $mailFilter = '';
+
+           foreach ($mailsArray as $mail)
+             $mailFilter .= '(|(mail='.$mail.')(mailAlternateAddress='.$mail.'))';
+
+
+           $filter = '(&(phpgwAccountType=s)(|'.$mailFilter.') )';
+           $ldap_context = $_SESSION['phpgw_info']['expressomail']['server']['ldap_context'];
+           $justthese = array('cn','uid','mail');
+
+           if ($conexao)
+           {
+                $search = @ldap_search($conexao, $ldap_context, $filter, $justthese);
+                if($search)
+                {
+                    $results = ldap_get_entries($conexao, $search);
+
+                    foreach ($results as $result)
+                    {
+                        if($result['mail'][0])
+                            array_push($arraySharedAccounts, $result['mail'][0]);
+                    }
+                }
+
+           }
+
+           return $arraySharedAccounts;
+        }
+        /**
+        * Verifica se um email é uma conta compartilhada
+        *
+        * @license    http://www.gnu.org/copyleft/gpl.html GPL
+        * @author     Cons?rcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
+        * @author     Cristiano Corrêa Schmidt
+        * @param      String $mail Email a ser verificado
+        * @return     bolean
+        * @access     public
+        */
+        function isSharedAccountByMail($mail)
+        {
+            $return = false;
+            $conexao = $this->ldapConnect2(true);
+            $filter = '(&(phpgwAccountType=s)(mail='.$mail.'))';
+            $ldap_context = $_SESSION['phpgw_info']['expressomail']['server']['ldap_context'];
+            $justthese = array('cn','uid','mail');
+            if ($conexao)
+            {
+                $search = @ldap_search($conexao, $ldap_context, $filter, $justthese);
+                if(ldap_count_entries ($conexao , $search))
+                    $return = true;
+            }
+
+            return $return;
+        }
 }
 ?>
Index: trunk/expressoMail1_2/inc/hook_settings.inc.php
===================================================================
--- trunk/expressoMail1_2/inc/hook_settings.inc.php	(revision 5083)
+++ trunk/expressoMail1_2/inc/hook_settings.inc.php	(revision 5134)
@@ -19,12 +19,27 @@
 	*  option) any later version.                                              *
 	\**************************************************************************/
-
+//include_once("fckeditor.php");
+//include_once("class.functions.inc.php");
 $type = isset($_GET['type']) ? $_GET['type']:$GLOBALS['type']; // FIX ME
 
 //if ($type == 'user' || $type == ''){
+global $prefs;
+// 	create_select_box('Signature Type','',$default,'','','','onchange="javascript:changeType(this.value);"');
 create_script('function exibir_ocultar()
 {
     var type = ("'.$type.'" == "") ? "user" : "'.$type.'";
-    var use_signature_digital_cripto = document.getElementsByName(type+"[use_signature_digital_cripto]")[0];
+    var use_signature_digital_cripto = null;
+
+    if (document.all)
+    {
+        // is_ie
+        use_signature_digital_cripto = document.getElementsByName(type+"[use_signature_digital_cripto]")[1];
+    }
+    else
+    {
+        // not_ie
+        use_signature_digital_cripto = document.getElementsByName(type+"[use_signature_digital_cripto]")[0];
+    }
+
     var default_signature_digital_cripto = "'.$GLOBALS['phpgw_info']['default']['preferences']['expressoMail']['use_signature_digital_cripto'].'";
 
@@ -287,7 +302,11 @@
 	document.getElementById( "user_signature" + counter ).value = old_signature;
     }
-}');
+    }
+');
 //}
-
+$default = false;
+create_check_box('Do you want to show common name instead of UID?','uid2cn',$default,
+	'Do you want to show common name instead of UID?');
+create_check_box('Do you want to automatically display the message header?','show_head_msg_full',$default,'');
 $default = array(
 	'25'	=> '25',
@@ -297,8 +316,15 @@
 );
 
-// Cria nova opÃ§Ã£o nas preferÃªncias do ExpressoMail 
+create_select_box('What is the maximum number of messages per page?','max_email_per_page',$default,'This is the number of messages shown in your mailbox per page');
+
 create_check_box('View the user name in the header of the messages printed?', 'show_name_print_messages', 'Displays the user name in the header print email');
 
-create_select_box('What is the maximum number of messages per page?','max_email_per_page',$default,'This is the number of messages shown in your mailbox per page');
+//$default = 0;
+create_check_box('Preview message text within subject column','preview_msg_subject','this exhibits a sample of message within the message subject column');
+
+//$default = 0;
+create_check_box('Preview message text within a tool-tip box','preview_msg_tip','this exhibits a sample of message within a tool-tip box');
+
+create_check_box('View extended information about users','extended_info','This exhibits employeenumber and ou from LDAP in searchs');
 create_check_box('Save deleted messages in trash folder?','save_deleted_msg','When delete message, send it automatically to trash folder');
 $default = array(
@@ -310,7 +336,10 @@
 );
 
+$arquived_messages = array(true => lang("Copy"), false => lang("Move"));
+
 create_select_box('Delete trash messages after how many days?','delete_trash_messages_after_n_days',$default,'Delete automatically the messages in trash folder in how many days');
 create_check_box('Would you like to use local messages?','use_local_messages','Enabling this options you will be able to store messages in your local computer');
-create_check_box('Would you like to keep archived messages?','keep_archived_messages','After store email in your local computer delete it from server');
+create_select_box('Desired action to archive messages to local folders','keep_archived_messages',$arquived_messages,'After store email in your local computer delete it from server');
+create_check_box('Automaticaly create Default local folders?','auto_create_local','Enable this option if you want to automaticaly create the Inbox, Draft, Trash and Sent folders');
 create_check_box('Show previous message, after delete actual message?','delete_and_show_previous_message','Enable this option if you want to read the next message everytime you delete a message');
 create_check_box('Do you wanna receive an alert for new messages?','alert_new_msg','Everytime you receive new messages you will be informed');
@@ -318,7 +347,17 @@
 create_check_box('Do you want to use remove attachments function?','remove_attachments_function','It allow you to remove attachments from messages');
 create_check_box('Do you want to use important flag in email editor?','use_important_flag','It allow you to send emails with important flag, but you can receive unwanted messages with important flag');
-
+create_check_box('Do you want to use SpellChecker in email editor?','use_SpellChecker','It allow you to check the spelling of your emails');
 //Use user folders from email
+
+require_once('class.imap_functions.inc.php');
+$boemailadmin = CreateObject('emailadmin.bo');
+$emailadmin_profile = $boemailadmin->getProfileList();
+$_SESSION['phpgw_info']['expressomail']['email_server'] = $boemailadmin->getProfile($emailadmin_profile[0]['profileID']);
+$_SESSION['phpgw_info']['expressomail']['user'] = $GLOBALS['phpgw_info']['user'];
+$e_server = $_SESSION['phpgw_info']['expressomail']['email_server'];
+$imap = CreateObject('expressoMail1_2.imap_functions');
+
 if ($type != "" && $type != "user"){
+	
 	$trash = $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder'];
 	$drafts = $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultDraftsFolder'];
@@ -328,19 +367,12 @@
 	$default = Array(
 		'INBOX' =>      lang('INBOX'), 
-		'INBOX'.$delimiter.$trash => $trash,  
-		'INBOX'.$delimiter.$drafts => $drafts,
-		'INBOX'.$delimiter.$spam => $spam,
-		'INBOX'.$delimiter.$sent => $sent
+		'INBOX' . $imap->imap_delimiter . $drafts => lang($drafts),
+		'INBOX' . $imap->imap_delimiter . $spam => lang($spam),
+		'INBOX' . $imap->imap_delimiter . $trash => lang($trash),  
+		'INBOX' . $imap->imap_delimiter . $sent => lang($sent)
 	);
 }
 else
 {
-require_once('class.imap_functions.inc.php');
-$boemailadmin = CreateObject('emailadmin.bo');
-$emailadmin_profile = $boemailadmin->getProfileList();
-$_SESSION['phpgw_info']['expressomail']['email_server'] = $boemailadmin->getProfile($emailadmin_profile[0]['profileID']);
-$_SESSION['phpgw_info']['expressomail']['user'] = $GLOBALS['phpgw_info']['user'];
-$e_server = $_SESSION['phpgw_info']['expressomail']['email_server'];
-$imap = CreateObject('expressoMail1_2.imap_functions');
 $save_in_folder_selected = $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['save_in_folder'];
 
@@ -378,5 +410,21 @@
 }
 create_select_box('Save sent messages in folder','save_in_folder',$default,'Save automatically sent messages in selected folder');
+create_check_box('Show TO: in place of FROM: only in Automatic SEND folder','from_to_sent','Show TO: in place of FROM: only in Automatic SEND folder');
+
+
 create_check_box('Hide menu folders?','hide_folders','You can use it if your screen does not have good resolution');
+
+
+$default =  array(
+    '50'    => '50',
+    '100'   => '100',
+    '150'   => '150',
+    '200'   => '200',
+    '300'   => '300',
+    '400'   => '400',
+    '65536' => lang('unlimited')
+);
+
+create_select_box('What is the maximum number of results in an e-mail search?','search_result_number',$default,'');
 
 $default =  array(
@@ -390,14 +438,31 @@
 create_select_box('What is the minimum number of characters in searching contacts?','search_characters_number',$default,'what is the minimum number of characters in searching contacts');
 
-$default = array(
+	$default = array( 
 	'20' => lang('normal'),
 	'30' => lang('medium'),
 	'40' => lang('big')
-);
+	);
+
 
 create_select_box('What is the height of the lines in the list of messages?','line_height',$default,'');
+create_check_box('Increases th maximum size of show messages?','max_msg_size','Increases the maximum size of show emails from 100kb to 1mb');
 create_check_box('Use dynamic contacts?','use_dynamic_contacts','Store your\'s most used contacts');
-create_check_box('Use shortcuts?','use_shortcuts','');
+create_check_box('Use shortcuts?','use_shortcuts','n key (Open new message)<br>ESC key (Close tab)<br>i key (print)<br>e key (forward)<br>r key (reply)<br>DELETE key (delete the current message)<br>Ctrl + up (go to previous message)<br>Ctrl + down (go to next message)<br>Shift + up or down (select multiple messages)<br>F9  key (search at catalog)<br>');
 create_check_box('Auto save draft','auto_save_draft','When you are away from computer it saves automatically the message you are writing');
+create_check_box('Send messages with return recipient option by default','return_recipient_deafault','With this option every new email will get the return recipient option marked');
+
+unset($default);
+$functions = new functions();
+$zones = $functions->getTimezones();
+$default = array(sprintf("%s", array_search('America/Sao_Paulo', $zones)) => 'America/Sao_Paulo');
+create_select_box('What is your timezone?', 'timezone', $zones, 'The Timezone you\'re in.', $default);
+
+$default =  array(
+    '1' => lang('contacts'),
+    '2' => lang('email')
+);
+
+create_select_box('Where should the quick search be performed by default?','quick_search_default',$default,'It is where the keyword should be searched when the user executes a quick search.');
+
 $default =  array(
 	'65536' => lang('unlimited'),
@@ -416,8 +481,9 @@
  		    'personal'   => lang("Personal catalog"), 
  		    'all' => lang("All catalogs") 
- 		); 
- 		 
- 	create_select_box('The dynamic search will use the catalog','catalog_search',$default,'Seleciona o catálogo que será usado para fazer a busca'); 
-
+);
+
+create_select_box('The dynamic search will use the catalog','catalog_search',$default,'Seleciona o catálogo que será usado para fazer a busca');
+$default = false;
+create_check_box('Display default fields on the quick search screen?','default_fields_quick_search', $default, 'Mostrar o nome, email e telefone do contato por padrão');
 
 
@@ -441,20 +507,50 @@
 	'html' => lang('rich text')
 );
+create_check_box('Auto close the first tab on reaching the maximum number of tabs?','auto_close_first_tab','');
 create_check_box('Insert signature automatically in new messages?','use_signature','');
 
+$default = array('0' => lang('nested in the same tab of the main message'), '1' => lang('in your own tab, one for each attached message'));
+create_select_box('Nested messages are shown','nested_messages_are_shown', $default,'How to show nested messages');
+
+$default = array(
+    'Arial'     => 'Arial',
+    'Verdana'   => 'Verdana',
+    'Times new roman'   => 'Times New Roman',
+    'Tahoma'   => 'Tahoma',
+);
+create_select_box( 'Default font editor' , 'font_family_editor' , $default );
+
+$default = array(
+    '8pt'     => '8',
+    '9pt'     => '9',
+    '10pt'    => '10',
+    '11pt'    => '11',
+    '12pt'    => '12',
+    '14pt'    => '14',
+    '16pt'    => '16',
+    '18pt'    => '18',
+    '20pt'    => '20',
+    '22pt'    => '22',
+    '24pt'    => '24',
+    '26pt'    => '26',
+    '28pt'    => '28',
+    '36pt'    => '36',
+    '48pt'    => '48',
+    '72pt'    => '72',
+);
+
+create_select_box( 'Default font size editor' , 'font_size_editor' , $default );
+
 if ($type == 'user' || $type == ''){
-
-	global $prefs;
-// 	create_select_box('Signature Type','type_signature',$default,'','','','onchange="javascript:changeType(this.value);"');
-
 	$vars = $GLOBALS['phpgw']->preferences->user['expressoMail'];
 
-create_html_code("signature","<script src='../library/jquery/jquery.js' language='javascript'></script> 
+
+	create_html_code("signature","<script src='../library/jquery/jquery.js' language='javascript'></script>
  		            <script src='../library/ckeditor/ckeditor.js' language='javascript'></script> 
  		            <script src='../library/ckeditor/adapters/jquery.js' language='javascript'></script>
+            
 	<input type='hidden' id='counter' value='0'>
 	<input type='hidden' id='signatures' name='user[signatures]' value='". $vars['signatures']."'>
 	<input type='hidden' id='signature_default' name='user[signature_default]' value='".$vars['signature_default']."'>
-	<input type='hidden' id='type_signature' name='user[type_signature]' value='".$vars['type_signature']."'>
 	<input type='hidden' id='signature' name='user[signature]' value='","' >
 	<input type='hidden' id='signature_types' name='user[signature_types]' value='".$vars['signature_types']."'>
@@ -503,5 +599,5 @@
 
 	document.getElementById( 'counter' ).value = ++counter;
-	}
+}
 
 function removeSignature( el )
@@ -513,11 +609,8 @@
 
     return( false );
-	    }
+}
 </script>
 <input id='add_signature' type='button' onclick='addSignature();' value='Adicionar Assinatura'>
 ");
-	}else{
-	create_select_box('Signature Type','type_signature',$default,'','','','');
-
 }
 ?>
Index: trunk/expressoMail1_2/js/drag_area.js
===================================================================
--- trunk/expressoMail1_2/js/drag_area.js	(revision 4845)
+++ trunk/expressoMail1_2/js/drag_area.js	(revision 5134)
@@ -63,5 +63,7 @@
 	
 		if(_button == 2 || _button == 3) {
-			var _checkb = Element("check_box_message_" + msg_number + getTabSufix());
+			var _checkb = Element("check_box_message_"+ msg_number);
+
+			var _checkb = Element(getTabPrefix() + "check_box_message_" + msg_number);
 
 			if(_checkb) {
@@ -96,5 +98,5 @@
 
 	var msg_number = _dragArea.from_list ? _dragArea.msg_number : _dragArea.msg_number.replace('_r','');
-	var _checkbox_element = Element("check_box_message_"+msg_number+getTabSufix());
+	var _checkbox_element = Element(getTabPrefix()+"check_box_message_"+msg_number);
 	if(_dragArea.from_list) {
 
@@ -166,9 +168,9 @@
 	else if(_dragArea.msg_number && _target.type != 'checkbox') {
 		_dragArea.mouseMoveDrag(e);
+	}
 	if (is_ie) 
 		window.event.returnValue = false; 
 	else 
 		e.returnValue = false; 
-	} 
 };
 
@@ -178,4 +180,5 @@
 	var	_target = is_ie ? _event.srcElement : _event.target;
 	var _button = is_ie ? _event.button : _event.which;
+	var _tab_prefix = getTabPrefix();
 	var _msg_id;
 
@@ -192,5 +195,5 @@
 				for(var i = 0; id_messages_to_drag && i < id_messages_to_drag.length; i++) {			
 					_msg_id = getMessageIdFromRowId(id_messages_to_drag[i]);
-					Element("check_box_message_"+id_messages_to_drag[i]).checked = false;
+					Element(_tab_prefix+"check_box_message_"+_msg_id).checked = false;
 					changeBgColor(_event ,_msg_id);
 				}
@@ -244,5 +247,5 @@
 				for(var i = 0; id_messages_to_drag && i < id_messages_to_drag.length; i++) {				
 					_msg_id = getMessageIdFromRowId(id_messages_to_drag[i]);
-					Element("check_box_message_"+id_messages_to_drag[i]).checked = false;
+					Element(_tab_prefix+"check_box_message_"+_msg_id).checked = true;
 					changeBgColor(_event ,_msg_id);
 				}
Index: trunk/expressoMail1_2/js/abas.js
===================================================================
--- trunk/expressoMail1_2/js/abas.js	(revision 5083)
+++ trunk/expressoMail1_2/js/abas.js	(revision 5134)
@@ -2,4 +2,6 @@
 BordersArray[0] = new setBorderAttributes(0);
 var countBorders = 0; 
+var partMsgs = new Array(); 
+
 
 function setBorderAttributes(ID)
@@ -42,7 +44,13 @@
 
 	var footer_menu = Element("footer_menu");	
-	if (footer_menu) {
+	var aba = Element('border_id_'+ID);
+	if (footer_menu != null) {
 		footer_menu.style.display = (openTab.type[ID] != 4 ? '' : 'none');
-	}
+		if((aba.id.indexOf("_r") < 0) && (aba.id.indexOf("_0") < 0) && (aba.id.indexOf("id_search_") < 0)){
+			spanD.style.display = 'none';
+			footer_menu.style.display = 'none';			
+		}
+	}
+
 
 	var len = BordersArray.length;
@@ -77,4 +85,5 @@
 	}
 
+	numBox = getNumBoxFromTabId(ID);
 	if (typeof(ID)=='number') {
                  numBox = ID;
@@ -114,6 +123,6 @@
             var str_continue = '';
             var bolContinue = true;
+			str_continue = '\n' + get_lang('You must manually close one of your tabs before opening a new one');
             if (preferences.auto_close_first_tab == 1){
-                str_continue = '\n' + get_lang('You must manualy close one of your tabs before opening a new one');
                 var children = Element('border_tr').childNodes;
                 var bolDelete = true;
@@ -127,15 +136,20 @@
                             bolDelete = false;
                         }
-                        if (bolDelete){
+                        if (bolDelete || bolContinue){
+							str_fechar = '\n' + get_lang('Reached maximum tab limit. Want to close this tab');
+							var confirmacao = confirm(str_fechar);
+                            if(confirmacao){
                             bolContinue = false;
                             delete_border(num_child, 'false');
                             break;
+							}else{
+								return 'maximo';
                         }
                     }
                 }
             }
-            if (bolContinue){
+            }else{			
                 alert(get_lang('Reached maximum tab limit') + str_continue );
-                return 0;
+                return 'maximo';
             }
         }
@@ -250,5 +264,5 @@
         }
 	var caption = "";
-        Element("font_"+border.id).style.width = (border_width - 25)+'px';
+        Element("font_"+border.id).style.width = (border_width - 30)+'px';
 	Element("font_"+border.id).innerHTML = title;
 	return(title);
@@ -257,12 +271,16 @@
 function draftTests(ID, msg_sent){
     var cancel = new LertButton(get_lang('cancel'), function() {
-        Element("border_id_"+ID).onclick = function () {alternate_border(ID);};
+        Element("border_id_"+ID).onclick = function () { alternate_border(ID);}; 
+        cRichTextEditor.prototype.focus(ID);
+            
     });
+	
     var yes = new LertButton(get_lang('Save'), function() {
-        save_msg(ID);
+        save_msg(ID, 'undefined', true);
         openTab.toPreserve[ID] = false;
         close_delete(ID, msg_sent);
         delete(openTab.type[ID]);
-		write_msg(get_lang('Your message was save as draft in folder %1.', lang_folder('Drafts')));
+		//write_msg(get_lang('Your message was save as draft in folder %1.', lang_folder('Drafts')));
+		
     });
     var discard = new LertButton(get_lang('Discard'), function() {
@@ -306,6 +324,7 @@
 function delete_border(ID, msg_sent)
 {
+    
         var bolExecuteClose = true;
-	var borderElem = Element("border_id_" + ID)
+	var borderElem = Element("border_id_" + ID);
 	if (borderElem){
             borderElem.onclick = null; // It's avoid a FF3 bug
@@ -368,5 +387,28 @@
 	resizeWindow();
 	RichTextEditor.destroy( 'body_'+ID );
+        
+        //Caso for uma mensagem anexada tem que deletar ela da lixeira apos fechar a aba
+            var isPartMsg = false;
+            var id2 = ID.replace('_r','');
+            for(var ii = 0; ii < partMsgs.length; ii++)
+               if(partMsgs[ii] == id2){           
+                  isPartMsg = true;
+                  partMsgs[ii] = null;
+               }     
+
+            if(isPartMsg === true){
+                var handler_delete_msg = function(){};
+                cExecute ("$this.imap_functions.delete_msgs&folder=INBOX"+cyrus_delimiter+trashfolder+"&msgs_number="+id2,handler_delete_msg);
+            }
+        ///////////////////////////////////////////////////////////////////////////////////
+        
 	return true;
+}
+
+function getTabPrefix() { // define o prefixo para os checkboxes das mensagens
+	if (typeof(currentTab)!='number')
+		return currentTab+"_";
+	else
+		return "";
 }
 
@@ -388,9 +430,2 @@
 	}
 }
-
-function getTabSufix() {
-	if (typeof(currentTab)=='number')
-		return '';
-	else
-		return '_s' + numBox.toString();
-}
Index: trunk/expressoMail1_2/js/filters.js
===================================================================
--- trunk/expressoMail1_2/js/filters.js	(revision 4855)
+++ trunk/expressoMail1_2/js/filters.js	(revision 5134)
@@ -43,7 +43,7 @@
 		form_buttons.style.position = "absolute";
 		form_buttons.style.display = "";
-		form_buttons.style.top = "347px";
+		form_buttons.style.top = "372px";
 		form_buttons.style.left = "5px";
-		form_buttons.style.width = "655px";
+		form_buttons.style.width = "675px";
 		form_buttons.innerHTML = "<input type='button' value="+get_lang("Enable")+" onclick='filter.enabled_disabled(\"ENABLED\");'>"+
 								 "&nbsp;<input type='button' value="+get_lang("Disable")+" onclick='filter.enabled_disabled(\"DISABLED\");'>"+	
@@ -52,4 +52,16 @@
 
 		form.appendChild(form_buttons);
+		
+		var form_buttons2 = document.createElement("DIV");
+		form_buttons2.id = "Edit_form_buttons";
+		form_buttons2.style.position = "absolute";
+		form_buttons2.style.display = "none";
+		form_buttons2.style.top = "372px";
+		form_buttons2.style.left = "5px";
+		form_buttons2.style.width = "675px";
+		form_buttons2.innerHTML = "<span align='right'><input type='button' value="+get_lang("Back")+" onclick='filter.form_m()'></span>"+
+							      "<span align='right'><input type='button' value="+get_lang("Save")+" onclick='filter.saved_rules()'></span>";
+
+		form.appendChild(form_buttons2);
 		
 		var form_body = document.createElement("DIV");
@@ -58,6 +70,6 @@
 		form_body.style.left = "5px";
 		form_body.style.top = "5px";
-		form_body.style.width = "668px";
-                form_body.style.height = "337px";
+		form_body.style.width = "688px";
+                form_body.style.height = "357px";
 		form_body.style.borderStyle = "outset";
 		form_body.style.borderColor = "black";
@@ -187,5 +199,5 @@
         {
 		var aux = outOffice.split("&&");
-		return get_lang("Rule") + " - <a href='javascript:void(0)' onclick=filter.form_out()> " + "<b>" + get_lang("Status") + " : </b><font color='red'>" + (aux[4].replace("\n","") === "off" ? get_lang("Disabled") : get_lang("Enabled")) + "</font></a>";
+		return get_lang("Rule") + " - <a href='javascript:void(0)' onclick=filter.form_out()> " + "<b>" + get_lang("Status") + " : </b><font color='red'>" + (aux[4] == "off" ? get_lang("Disabled") : get_lang("Enabled")) + "</font></a>";
 	}
 	
@@ -197,4 +209,5 @@
 		filter.ac_form = "new_rule";
 		Element('form_buttons').style.display = 'none';
+		Element('Edit_form_buttons').style.display = '';
 		filter.sel_boxes();
 
@@ -207,4 +220,5 @@
 		Element('div_vacation').style.display = "block";			
 		Element('form_buttons').style.display = 'none';
+		Element('Edit_form_buttons').style.display = '';
 		filter.ac_form = "new_out";	
 	}
@@ -236,6 +250,6 @@
 	{
 		if(! this.filter_Sh[div.id]) {
-			div.style.width = "680px";
-			div.style.height = "372px";
+			div.style.width = "700px";
+			div.style.height = "400px";
 			div.style.visibility = "hidden";
 			div.style.position = "absolute";
Index: trunk/expressoMail1_2/js/sharemailbox.js
===================================================================
--- trunk/expressoMail1_2/js/sharemailbox.js	(revision 4457)
+++ trunk/expressoMail1_2/js/sharemailbox.js	(revision 5134)
@@ -43,20 +43,28 @@
 			Element('em_input_saveAcl').checked = false;
 			Element('em_input_saveAcl').disabled = true;
+                        Element('em_input_deleteAcl').disabled = true;
+                        Element('em_input_writeAcl').disabled = true;
 			
 			if (data[user].indexOf('lrs',0) >= 0)
 			{
 				Element('em_input_sendAcl').disabled = false;
+                                Element('em_input_deleteAcl').disabled = false;
+                                Element('em_input_writeAcl').disabled = false ;
 				Element('em_input_readAcl').checked = true;
 			}
 			else
+			{
 				Element('em_input_sendAcl').disabled = true;
 				
+                        }
 			if (data[user].indexOf('d',0) >= 0)
 			{
 				Element('em_input_deleteAcl').checked = true;
+                                Element('em_input_deleteAcl').disabled = false;
 			}
 			if (data[user].indexOf('wi',0) >= 0)
 			{
 				Element('em_input_writeAcl').checked = true;
+                                Element('em_input_writeAcl').disabled = false
 			}
 			
@@ -91,4 +99,6 @@
 		if (Element('em_input_readAcl').checked) {
 			Element('em_input_sendAcl').disabled = false;
+                        Element('em_input_deleteAcl').disabled = false;
+                        Element('em_input_writeAcl').disabled = false;
 			acl = 'lrs';
 		}
@@ -96,4 +106,9 @@
 			Element('em_input_sendAcl').disabled = true;
 			Element('em_input_sendAcl').checked = false;
+                        Element('em_input_deleteAcl').disabled = true;
+                        Element('em_input_deleteAcl').checked = false;
+                        Element('em_input_writeAcl').disabled = true;
+                        Element('em_input_writeAcl').checked = false;
+                        
 		}
 				
@@ -174,8 +189,8 @@
 							"<td valign='bottom'><br>"+
 								get_lang('Organization')+":&nbsp;" + 
-								"<select id='em_combo_org' onchange='javascript:sharemailbox.get_available_users(this.value);'></select>"+
+								"<select id='em_combo_org'></select>"+
 								
 								"<br><br>"+get_lang('Search user')+":<br>" +
-								'<input id="em_input_searchUser" size="35" autocomplete="off"  onkeyup="javascript:sharemailbox.optionFinderTimeout(this)"><br>'+
+								'<input id="em_input_searchUser" size="35" autocomplete="off"  onkeyup="javascript:sharemailbox.optionFinderTimeout(this, event);"><br>'+
 								
 								'<font color="red"><span id="em_span_searching">&nbsp;</span></font><br>'+
@@ -291,4 +306,6 @@
 		Element('em_input_sendAcl').disabled = true;
 		Element('em_input_saveAcl').disabled = true;
+                Element('em_input_deleteAcl').disabled = true;
+                Element('em_input_writeAcl').disabled = true;
 		win.open();
 	}
@@ -305,29 +322,13 @@
 	}
 	
-	cShareMailbox.prototype.optionFinder = function(id)
-	{
-		var oWait = document.getElementById("em_span_searching");
-		var oText = document.getElementById(id);
-			
-		//Limpa todo o select
-		
-		var select_available_users_tmp = document.getElementById('em_select_available_users')
-		for(var i = 0;i < select_available_users_tmp.options.length; i++)
-			select_available_users_tmp.options[i--] = null;
-
-		var RegExp_name = new RegExp("\\b"+oText.value, "i");
-		
-		//Inclui usuário começando com a pesquisa
-                if (typeof(select_available_users_clone)  != "undefined"){
-                    for(i = 0; i < select_available_users_clone.length; i++){
-                            if (RegExp_name.test(select_available_users_clone[i].text))
-                            {
-                                    sel = select_available_users_tmp.options;
-                                    option = new Option(select_available_users_clone[i].text,select_available_users_clone[i].value);
-                                    sel[sel.length] = option;
-                            }
-                    }
-                }
-		oWait.innerHTML = '&nbsp;';
+	cShareMailbox.prototype.optionFinder = function(id) {
+			
+		var sentence = Element(id).value;
+		
+		var url = '$this.ldap_functions.get_available_users2&context=' +
+			    Element('em_combo_org').value +
+			    ( sentence ? '&sentence=' + sentence: '' );
+
+		return userFinder( sentence, 'em_select_available_users', url, 'em_span_searching');
 	}
 	
Index: trunk/expressoMail1_2/js/common_functions.js
===================================================================
--- trunk/expressoMail1_2/js/common_functions.js	(revision 5075)
+++ trunk/expressoMail1_2/js/common_functions.js	(revision 5134)
@@ -18,4 +18,6 @@
 
 window.onresize = resizeWindow;
+
+var message = "Não Informado";
 
 function config_events(pObj, pEvent, pHandler)
@@ -144,5 +146,4 @@
 	remove_className(tr_message, 'selected_msg');
 	add_className(tr_message, 'tr_msg_unread');
-	if( document.getElementById("td_message_unseen_"+msg_number) != null )
 	Element("td_message_unseen_"+msg_number).innerHTML = "<img src ='templates/"+template+"/images/unseen.gif' title='"+get_lang('Unseen')+"'>";
 }
@@ -152,5 +153,4 @@
 	remove_className(msg, 'selected_msg');
 	add_className(msg, 'flagged_msg');
-	if( document.getElementById("td_message_important_"+msg_number) != null )
 	Element("td_message_important_"+msg_number).innerHTML = "<img src ='templates/"+template+"/images/important.gif' title='"+get_lang('Important')+"'>";
 }
@@ -160,5 +160,4 @@
 	remove_className(msg, 'selected_msg');
 	remove_className(msg, 'flagged_msg');
-	if( document.getElementById("td_message_important_"+msg_number) != null )
 	Element("td_message_important_"+msg_number).innerHTML = "&nbsp;&nbsp;&nbsp;";
 }
@@ -185,4 +184,13 @@
 	else
 		return false;
+}
+
+//Remove as linhas da tabela sem deletar o corrent_box
+function remove_rows(el){
+	while (el.rows.length > 0)  {
+		el.deleteRow(0);
+	} 
+	Element("tot_m").innerHTML = 0 
+	Element("new_m").innerHTML = 0 
 }
 
@@ -234,6 +242,6 @@
 	}
 	if(new_file_name) {
-		var extension = new_file_name.substring(new_file_name.length-4, new_file_name.length);
-		if (extension == ".eml") // if the extension is .eml
+		var extension = /\.[^.]*$/.exec(new_file_name);
+		if (extension == ".eml")
 			params = "&newFilename="+new_file_name; //name_of_message.eml
 		else // when more than one message
@@ -256,5 +264,5 @@
 function addForwardedFile(id_border,file_name,link,divFiles){
 	if(!divFiles)
-		divFiles = document.getElementById("divFiles_"+id_border);
+		var divFiles = document.getElementById("divFiles_"+id_border);
 
 	if (! divFiles)
@@ -267,11 +275,9 @@
 		var countDivFiles = 1;
 
-	divFile = document.createElement('DIV');
-
-
+	var divFile = document.createElement('DIV');
+
+	var inputFile = document.createElement("INPUT");
 	if (!expresso_offline) {
 		if (!is_ie) {
-			var inputFile = document.createElement("INPUT");
-
 			var tmp_id_border = document.createAttribute('id_border');
 			tmp_id_border.value = id_border;
@@ -286,5 +292,5 @@
 		}
 		else {
-			var inputFile = document.createElement("link");
+			inputFile = document.createElement("link");
 
 			var tmp_id_border = document.createAttribute('id_border');
@@ -300,5 +306,4 @@
 	}
 	else {
-		var inputFile = document.createElement("input");
 		inputFile.type = 'hidden';
 		inputFile.name = 'offline_forward_' + countDivFiles;
@@ -315,4 +320,5 @@
 	checkbox.id = "checkbox_"+id_border+"_"+countDivFiles;
 	checkbox.name = "local_attachments[]";
+	checkbox.setAttribute("checked", "checked");
 
 	checkbox.value = s_tmp;
@@ -329,5 +335,4 @@
 	divFiles.appendChild(divFile);
 
-	checkbox.checked = true; //IncrÃ­vel, mas no Internet Explorer o checked sÃ³ funciona efetivamente se o elemente jÃ¡ estiver renderizado... por isso sÃ³ aqui eu seleciono ele...
 	return inputFile;
 }
@@ -476,6 +481,6 @@
 	to = to.replace("<","&lt;");
 	to = to.replace(">","&gt;");
-	block_quoted_body ="<br><br>";
-	block_quoted_body += get_lang('At %1, %2 hours, %3 wrote:', date_day, date_hour, to);
+	block_quoted_body ='<div>';
+	block_quoted_body += get_lang('At %1, %2 hours, %3 wrote:', date_day, date_hour, to) + '<br type="_moz"></div>';
 	block_quoted_body += "<blockquote style=\"border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;\">";
 	block_quoted_body += body;
@@ -489,13 +494,13 @@
 	to = to.replace(/</g,"&lt;");
 	to = to.replace(/>/g,"&gt;");
-	var forward_body = '<BR><BR>---------- ' + get_lang('Forwarded message') + ' ----------<BR>';
-	forward_body += get_lang('From') + ': ' + from + '<BR>';
-	forward_body += get_lang('Date') + ': ' + date + '<BR>';
-	forward_body += get_lang('Subject') + ': ' + subject + '<BR>';
-	forward_body += get_lang('To') + ': ' + to+ '<BR>';
+	var forward_body = '<div>---------- ' + get_lang('Forwarded message') + ' ----------<br type="_moz"></div><div>';
+	forward_body += get_lang('From') + ': ' + from + '<br type="_moz"></div><div>';
+	forward_body += get_lang('Date') + ': ' + date + '<br type="_moz"></div><div>';
+	forward_body += get_lang('Subject') + ': ' + subject + '<br type="_moz"></div><div>';
+	forward_body += get_lang('To') + ': ' + to+ '<br type="_moz"></div><div>';
 	if(cc != undefined){
 		cc = cc.replace(/</g,"&lt;");
 		cc = cc.replace(/>/g,"&gt;");
-		forward_body += get_lang('CC') + ': ' + cc+ '<BR><BR>';
+		forward_body += get_lang('CC') + ': ' + cc+ '<br type="_moz"></div><<div><br type="_moz"></div><div><br type="_moz"></div>';
 	}
 	forward_body += body;
@@ -603,6 +608,5 @@
 
 	if (search_for.length < preferences.search_characters_number){
-            //alert(get_lang('Your search argument must be longer than %1 characters.', preferences.search_characters_number));
-	    alert(get_lang('Your search argument must be longer than %1 characters. Use quotes to refine your search', preferences.search_characters_number));
+            alert(get_lang('Your search argument must be longer than %1 characters.', preferences.search_characters_number));
             return false;
 	}
@@ -698,4 +702,5 @@
 
 function url_encode(str){
+	if(str === null) return false;
     var hex_chars = "0123456789ABCDEF";
     var noEncode = /^([a-zA-Z0-9\_\-\.])$/;
@@ -730,17 +735,15 @@
 	return strDecode;
 }
-
+//Método que remove os hexadecimais criados no enconde
+//e retorna string corretamente
 function url_decode_s(str) {
-	var n, strCode, strDecode = "";
-	for (n = 0; n < str.length; n++) {
-	    if (str.charAt(n) == "%") {
-	        strCode = str.charAt(n + 1) + str.charAt(n + 2);
-	        strDecode += String.fromCharCode(parseInt(strCode, 16));
-	        n += 2;
-	    } else {
-	        strDecode += str.charAt(n);
-	    }
-	}
-	return strDecode;
+	    var result = "";
+
+     for (var i = 0; i < str.length; i++) {
+          if (str.charAt(i) == "+") result += " ";
+          else result += str.charAt(i);
+	}
+          return unescape(result);
+     
 }
 
@@ -963,4 +966,19 @@
 }
 
+//Verifica se ainda existem mensagens marcadas, se não desmarca
+//o selecionar todas.
+function remove_chk_box_select_all_messages(){
+	var main = Element("tbody_box");
+	var main_list = main.childNodes;
+	var len_main_list = main_list.length;
+	for (i=0; i<len_main_list; i++)
+	{
+		if (Element("check_box_message_"+main_list[i].id).checked){
+				return;
+		}
+	}
+	 document.getElementById("chk_box_select_all_messages").checked = false;
+}
+
 function select_all_messages(select)
 {
@@ -974,6 +992,6 @@
 		{
 			Element("check_box_message_"+main_list[i].id).checked = true;
-			add_className(Element(main_list[i].id), 'selected_msg'); // one by one to add only if does not exist yet
-			add_className(Element(main_list[i].id), 'selected_shortcut_msg'); // one by one to add only if does not exist yet
+			remove_className(Element(main_list[i].id), 'selected_msg');
+			add_className(Element(main_list[i].id), 'selected_msg selected_shortcut_msg');
 		}
 	}
@@ -983,6 +1001,5 @@
 		{
 			Element("check_box_message_"+main_list[i].id).checked = false;
-			remove_className(Element(main_list[i].id), 'selected_msg'); // one by one to remove
-			remove_className(Element(main_list[i].id), 'selected_shortcut_msg'); // one by one to remove
+			remove_className(Element(main_list[i].id), 'selected_msg selected_shortcut_msg');
 		}
 	}
@@ -1006,4 +1023,13 @@
 	else
 		return (size/gbyte).toFixed(1) + ' GB';
+}
+
+//valida se a primeira data é menor que a segunda data
+function validate_date_order(dateStart, dateEnd){
+	if ( parseInt( dateEnd.split( "/" )[2].toString() + dateEnd.split( "/" )[1].toString() + dateEnd.split( "/" )[0].toString() ) >= parseInt( dateStart.split( "/" )[2].toString() + dateStart.split( "/" )[1].toString() + dateStart.split( "/" )[0].toString() ) ){
+		return true;
+	}else{
+		return false;
+	}
 }
 
Index: trunk/expressoMail1_2/js/main.js
===================================================================
--- trunk/expressoMail1_2/js/main.js	(revision 5083)
+++ trunk/expressoMail1_2/js/main.js	(revision 5134)
@@ -5,4 +5,7 @@
 var autosave_time = 20000;
 
+var results_search_messages = ""; 
+var cabecalho = '<h4>ExpressoLivre - ExpressoMail</h4>'; 
+
 function init(){
 	if (!is_ie)
@@ -20,9 +23,16 @@
 
 		preferences = data;
+                
+		
+ 	                if(preferences.show_name_print_messages == "1") { 
+							var getUserName = document.getElementById("user_info"); 
+ 	                        var userName = getUserName.innerHTML; 
+ 	                        var position = userName.indexOf("-"); 
+ 	                        var userName = userName.substring(3, position); 
+ 	                        cabecalho = '<h4>' + userName; 
+ 	                }
+		
+		
 		current_folder="INBOX";
-                
-                version = (navigator.userAgent.match( /.+ie\s([\d.]+)/i ) || [])[1];
-		if(parseInt(version)==7 && (/trident\/\d/i.test(navigator.userAgent)))
-                        preferences.use_local_messages="0";
 		
 		if( (window.google && google.gears) && !google.gears.factory.getPermission())
@@ -318,5 +328,9 @@
 		// Call function to draw message
 		// If needed, delete old border
-		if (openTab.type[currentTab] == 2 || openTab.type[currentTab] == 3)
+                var isPartMsg = false;
+                for(var ii = 0; ii < partMsgs.length; ii++)
+                     if(partMsgs[ii] == ID) isPartMsg = true;               
+
+		if ((openTab.type[currentTab] == 2 || openTab.type[currentTab] == 3) && isPartMsg === false)
 			delete_border(currentTab,'false');
 
@@ -394,4 +408,5 @@
 		if(!verify_session(data))
 			return;
+		var total_messages_element = Element('tot_m');
 			
 		var box = Element("tbody_box");
@@ -415,7 +430,10 @@
 
 			var box = Element("tbody_box");
-			table_element.insertBefore(box, Element("colgroup_main_"+numBox)); // keeps colgroup as the last child
-
-			if (data.msgs_to_delete.length > 0)
+			//table_element.insertBefore(box, Element("colgroup_main_"+numBox)); // keeps colgroup as the last child
+			//table_element.appendChild(Element("colgroup_main_"+numBox));
+			
+			$(table_element).append(Element("colgroup_main_"+numBox));
+
+			if (data.msgs_to_delete.length > 0){
 				for (var i=0; i<data.msgs_to_delete.length; i++){
 					if ( (data.msgs_to_delete[i] != undefined) && (data.msgs_to_delete[i] != "")){
@@ -423,10 +441,7 @@
 					}
 				}
-
+			}
 			if (data[0].msg_folder != current_folder) // Bad request
 				return false;
-
-			var total_messages_element = Element('tot_m');
-
 			for (var i=0; i<data.length; i++){
 				var existent = document.getElementById(data[i].msg_number);
@@ -437,6 +452,10 @@
 					
 					if( data[i].next_msg_number != undefined && data[i].next_msg_number != null ){
-						try { box.insertBefore(new_msg, box.childNodes[data[i].msg_key_position]); }
-						catch (e) { box.insertBefore(new_msg, box.firstChild); }
+						try {
+							box.insertBefore(new_msg, box.childNodes[data[i].msg_key_position]);							
+						}
+						catch (e){
+							$(box).append(new_msg);
+						}
 					}
 					else if (data[i].Recent == 'N'){
@@ -446,12 +465,4 @@
 						box.appendChild(new_msg);
 					}
-//					if( data[i].next_msg_number != undefined && data[i].next_msg_number != null )
-//						box.insertBefore(new_msg, Element(data[i].next_msg_number));
-//					else if (data[i].Recent == 'N')
-//						box.insertBefore(new_msg,box.firstChild);
-//					else
-//						box.appendChild(new_msg);
-
-//					total_messages_element.innerHTML = parseInt( total_messages_element.innerHTML ) + 1;
 				}
 			}
@@ -460,4 +471,9 @@
 				alert(data['new_msgs'] > 1 ? get_lang("You have %1 new messages", data['new_msgs']) + "!" : get_lang("You have 1 new message") +"!");
 			build_quota(data['quota']);
+		}
+		if(data.new_msgs){
+			total_messages_element.innerHTML = parseInt( total_messages_element.innerHTML ) + data.new_msgs;
+		}else if(data.tot_msgs){
+			total_messages_element.innerHTML = data.tot_msgs;
 		}
 		// Update Box BgColor
@@ -494,5 +510,11 @@
 }
 
-	function delete_msgs(folder, msgs_number, border_ID, show_success_msg,archive){      
+function delete_msgs(folder, msgs_number, border_ID, show_success_msg,archive){
+			
+			if( preferences.use_local_messages == 1 && expresso_local_messages.isArchiving( msgs_number, folder ) ){
+			  alert( "Impossivel deletar mensagens que estão ainda estão sendo arquivadas." );
+			  return;
+			}
+				
  		        var userTrashFolder = ''; 
  		       
@@ -507,6 +529,9 @@
 				else userTrashFolder = 'INBOX'+cyrus_delimiter+trashfolder; 
  	 
- 		        if(openTab.type[currentTab] == 1) return move_search_msgs('content_id_'+currentTab,userTrashFolder,trashfolder); 
-				if(currentTab.toString().indexOf("_r") != -1) msgs_number = currentTab.toString().substr(0,currentTab.toString().indexOf("_r")); 
+ 		        if(openTab.type[currentTab] == 1) 
+					return move_search_msgs('content_id_'+currentTab,userTrashFolder,trashfolder); 
+					
+				if(currentTab.toString().indexOf("_r") != -1) 
+					msgs_number = currentTab.toString().substr(0,currentTab.toString().indexOf("_r")); 
  		         
  		        if (!archive && (parseInt(preferences.save_deleted_msg)) && (folder != userTrashFolder)){ 
@@ -574,4 +599,10 @@
 
 function move_search_msgs(border_id, new_folder, new_folder_name){
+  
+	if( preferences.use_local_messages == 1 && expresso_local_messages.isArchiving( msgs_number, folder ) ){
+	  alert( "Impossivel mover mensagens que estão ainda estão sendo arquivadas." );
+	  return;
+	}
+
 	var selected_messages = '';
 	var temp_msg;
@@ -663,5 +694,11 @@
 }
 
-function move_msgs2(folder, msgs_number, border_ID, new_folder, new_folder_name,show_success_msg){
+function move_msgs2(folder, msgs_number, border_ID, new_folder, new_folder_name,show_success_msg, not_opem_previus){
+	not_opem_previus = typeof(not_opem_previus) != 'undefined' ? not_opem_previus : false;
+	if( preferences.use_local_messages == 1 && expresso_local_messages.isArchiving( msgs_number, folder ) ){
+	    alert( "Impossivel mover mensagens que estão ainda estão sendo arquivadas." );
+	    return;
+	}
+
 	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());
@@ -689,8 +726,10 @@
 		}
 		mail_msg = ( Element("divScrollMain_"+numBox) ) ? Element("divScrollMain_"+numBox).firstChild.firstChild : Element("divScrollMain_0").firstChild.firstChild;
-		if (data.msgs_number.length == 1)
+		if (data.msgs_number.length == 1){
 			write_msg(get_lang("The message was moved to folder ") + lang_folder(data.new_folder_name));
-		else
+		}
+		else{
 			write_msg(get_lang("The messages were moved to folder ") + lang_folder(data.new_folder_name));
+		}
 
 		if (openTab.type[currentTab] > 1){
@@ -701,11 +740,14 @@
 					var previous_msg = msg_to_delete.previousSibling.id;
 					//cExecute("$this.imap_functions.get_info_msg&msg_number="+previous_msg+"&msg_folder=" + current_folder, show_msg);
+					if(!not_opem_previus){
 					cExecute("$this.imap_functions.get_info_msg&msg_number="+previous_msg+"&msg_folder=" + url_encode(folder), show_msg);
+				}
 				}
 				else
 					delete_border(currentTab,'false');
 			}
-			else
+			else{
 				delete_border(currentTab,'false');
+			}
 			if(msg_to_delete)
 				mail_msg.removeChild(msg_to_delete);
@@ -715,4 +757,7 @@
 			if(box.childNodes.length > 0){
 				updateBoxBgColor(box.childNodes);
+			}
+			if(folder == get_current_folder()){
+				Element('tot_m').innerHTML = parseInt(Element('tot_m').innerHTML) - 1;
 			}
 			return;
@@ -770,7 +815,7 @@
 				delete_border(data.border_ID,'false');
 		}
-		if(folder == get_current_folder())
+		if(folder == get_current_folder()){
 			Element('tot_m').innerHTML = parseInt(Element('tot_m').innerHTML) - data.msgs_number.length;
-
+		}
 		refresh();
 	}
@@ -796,21 +841,58 @@
 		}
 
-	if(currentTab.toString().indexOf("_r") != -1){
-		msgs_number = currentTab.toString().substr(0,currentTab.toString().indexOf("_r"));
-                if(msgs_number.indexOf("_s1"))
-                           msgs_number = msgs_number.replace('_s1', '');
+	// se a aba estiver aberta e selecionada, apenas a msg da aba é movida
+	if(currentTab.toString().indexOf("_r") != -1)
+        {
+                //se a aba for aberta atraves de uma pesquisa
+                if(currentTab.toString().indexOf('_s') != -1)
+                   msgs_number = currentTab.toString().substr(0,currentTab.toString().indexOf('_s'));
+                else
+                    msgs_number = currentTab.toString().substr(0,currentTab.toString().indexOf('_r'));
 	}
 
 	if (parseInt(msgs_number) > 0 || msgs_number.length > 0){
-            var params = "&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="+escape(new_folder)+"&new_folder_name="+escape(new_folder_name)+"&get_previous_msg="+preferences.delete_and_show_previous_message;
-            cExecute ("$this.imap_functions.move_messages",handler_move_msgs,params);
+		if(!not_opem_previus){
+			cExecute ("$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="+preferences.delete_and_show_previous_message, handler_move_msgs);
+		}else{
+			cExecute ("$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="+false, handler_move_msgs);
         }
-	else
+	}else
 		write_msg(get_lang('No selected message.'));
 
 }
 
-function move_msgs(folder, msgs_number, border_ID, new_folder, new_folder_name) {
-	move_msgs2(folder, msgs_number, border_ID, new_folder, new_folder_name,true);
+function move_msgs(folder, msgs_number, border_ID, new_folder, new_folder_name, not_opem_previus) {
+	move_msgs2(folder, msgs_number, border_ID, new_folder, new_folder_name,true, not_opem_previus);
+}
+
+//Caso deseja-se que não se abra a mensagem anterior independente da 
+//preferencia do usuario
+function move_msgs_not_previus(folder, msgs_number, border_ID, new_folder, new_folder_name) {
+	move_msgs2(folder, msgs_number, border_ID, new_folder, new_folder_name,true, true);
+}
+
+function normalizeMsgNumber( msgNumber ){
+  
+      if (msgNumber || msgNumber == 'selected')
+	  msgNumber = get_selected_messages();
+
+
+      // se a aba estiver aberta e selecionada, apenas a msg da aba é movida
+      if(currentTab.toString().indexOf("_r") != -1)
+      {
+	    //se a aba for aberta atraves de uma pesquisa
+	    if(currentTab.toString().indexOf('_s') != -1)
+		msgNumber = currentTab.toString().substr(0,currentTab.toString().indexOf('_s'));
+	    else
+		msgNumber = currentTab.toString().substr(0,currentTab.toString().indexOf('_r'));
+      }
+      
+      if (parseInt(msgNumber) <= 0 || msgNumber.length <= 0){
+	    write_msg(get_lang('No selected message.'));
+	    return( false );
+      }
+      
+      return( msgNumber );
+
 }
 
@@ -828,13 +910,90 @@
 		id_msgs = get_selected_messages();
 
+	if ( parseInt(id_msgs) <= 0 || id_msgs.length <= 0 )
+	    return write_msg(get_lang('No selected message.'));
+	
 	if(folder_dest=='local_root' || folder_dest==null) //Caso seja o primeiro arquivamento...
 		folder_dest = 'local_Inbox';
 
-	if (parseInt(id_msgs) > 0 || id_msgs.length > 0)
-		expresso_mail_sync.archive_msgs(folder,folder_dest,id_msgs);
-		//cExecute("$this.imap_functions.get_info_msgs&folder=" + folder + "&msgs_number=" + id_msgs , handler_arquivar_mensagens);
-	else
-		write_msg(get_lang('No selected message.'));
-
+	id_msgs = expresso_local_messages.checkArchived( id_msgs, folder_dest );
+
+	 if( !id_msgs ){
+	      write_msg( "Todas as mensagens já foram arquivadas anteriormente." );
+	      return;
+	  }
+  
+	document.getElementById("overlay").style.visibility = "visible";
+
+	var handler_arquivar_mensagens = function(data) {
+	  
+	    var msgs_info = [];
+	  
+	    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();
+	    
+	    expresso_local_messages.insert_mails( msgs_info, folder_dest, function( s, f ){complete_archiving( s, f, h )} );
+
+	    document.getElementById("overlay").style.visibility = "hidden";
+	}
+
+	cExecute( "$this.imap_functions.get_info_msgs&folder=" + folder + "&msgs_number=" + id_msgs, handler_arquivar_mensagens );
+}
+
+function complete_archiving( success, fails, has_local_messages_before )
+{
+    var msgs_to_remove = {};
+    var target = 'INBOX' + cyrus_delimiter + trashfolder + cyrus_delimiter + 'tmpMoveToLocal';
+    
+    success = expresso_local_messages.select_mail( [ 'original_id', 'original_folder' ], success );
+
+    for (var i = 0; i < success.length; i++) {
+	
+	var msg_info = success[i];
+
+// 	if ( msg_info.dest_folder == target )
+// 	{
+// 		msg_info.msg_folder += (Date.parse(new Date));
+// 	}
+
+	//////////////// deselecionando ////////////////
+	Element('chk_box_select_all_messages').checked = false;
+
+	if ( Element("check_box_message_" + msg_info.original_id) ) 
+	{
+		Element("check_box_message_" + msg_info.original_id).checked = false;
+	}
+	if ( Element(msg_info.original_id) )
+	{
+		remove_className(Element(msg_info.original_id), 'selected_msg');
+	}
+
+// 	if ( tree_folders._selected.id.indexOf( 'local_' ) == 0 || msg_info.dest_folder.indexOf( target ) == 0 )
+// 	{
+// 		openTab.imapBox[0] = '';
+// 		tree_folders.getNodeById( 'local_Inbox' )._select( );
+// 		change_folder('local_Inbox','Inbox');
+// 	}
+	/////////////////////////////////////////////////
+
+	//As mensagens arquivadas devem ser removidas, caso o usuario tenha isso configurado.
+	msgs_to_remove[ msg_info.original_folder ] = msgs_to_remove[ msg_info.original_folder ] || [];
+	msgs_to_remove[ msg_info.original_folder ].push( msg_info.original_id );
+    }
+
+    if (preferences.keep_archived_messages == 0) {
+	    //Remove as mensagens
+	    for( var folder in msgs_to_remove ){
+		if(folder != 'undefined')
+			delete_msgs(folder, msgs_to_remove[folder],'null',false,true);
+	    }
+    }
+
+    if( !has_local_messages_before && expresso_local_messages.has_local_mails() )
+	    ttreeBox.update_folder();
+    else
+	    update_menu();
 }
 
@@ -853,11 +1012,7 @@
 
 	// Get all TR (messages) in tBody.
-        if(currentTab.toString().indexOf("_r") != -1){
-            return currentTab.toString().substr(0,currentTab.toString().indexOf("_r"));
-        }
-
 	var main_list = main.childNodes;
 
-	var _check_box;
+	var _tab_prefix = getTabPrefix();
 	var selected_messages = '';
 	var selected_messages_by_shortcuts = '';
@@ -865,7 +1020,13 @@
 	for (j; j<(main_list.length); j++)
 	{
-		_check_box = Element("check_box_message_" + main_list[j].id);
-
-		if ( (_check_box) && (_check_box.checked) )
+
+if ( (!isNaN(parseInt(numBox))) && (numBox == 0)) { 
+ 		                        check_box = Element("check_box_message_" + main_list[j].id); 
+ 		                } else { 
+ 		                        id_mensagem = main_list[j].id.split('_'); 
+								check_box = Element("search_" + numBox + "_check_box_message_" + id_mensagem[0]); 
+ 		                }        
+ 		                 
+ 		                if ( (check_box) && (check_box.checked) ) 
 		    selected_messages += main_list[j].id + ',';
 
@@ -880,4 +1041,14 @@
 	selected_messages = selected_messages.substring(0,(selected_messages.length-1));
 
+ 		         
+ 		        /* Verifica se está na tela de pesquisa. */ 
+ 		        if(selected_messages.indexOf("_") != -1) 
+ 		        { 
+ 		                results_search_messages = selected_messages; 
+ 		                /* Retira a informação da aba */ 
+ 		                selected_messages = selected_messages.substring(0,selected_messages.indexOf("_"));
+	}
+	
+
 	if (preferences.use_shortcuts == '1')
 	{
@@ -897,42 +1068,4 @@
 	else
 		return selected_messages;
-}
-
-function get_selected_messages_folder(){
-	var _main;
-	var _main_list;
-	try{
-		_main = document.getElementById("divScrollMain_"+numBox).firstChild.firstChild;
-	}catch(e){
-	};
-
-	if (! _main)
-		_main = Element("tbody_box_"+numBox);
-
-	if (! _main)
-		_main = Element("tbody_box");
-
-	// Get all TR (messages) in tBody.
-	_main_list = _main.childNodes;
-
-	var _check_box;
-	var selected_messages_folder;
-//	var selected_messages_by_shortcuts = '';
-	var j = 0;
-	for (j; j<(_main_list.length); j++)
-	{
-
-		_check_box = Element("check_box_message_" + _main_list[j].id);
-
-		if ( (_check_box) && (_check_box.checked) && (_main_list[j].name) ) {
-			if (!selected_messages_folder)
-				selected_messages_folder = _main_list[j].name;
-			else {
-				if (selected_messages_folder!=_main_list[j].name)
-					return false;
-			}
-		}
-	}
-	return selected_messages_folder;
 }
 
@@ -971,5 +1104,5 @@
 					9 : get_lang("Reply without history"),
 					10: get_lang("Reply to all without history")};
-
+			if(new_border_ID != 0)
 			if(!confirm(get_lang("Your message to %1 has not been saved or sent. "+
 						"To %2 will be necessary open it again. Discard your message?",
@@ -982,4 +1115,8 @@
 			}
 		}
+	}
+	if (new_border_ID == 'maximo'){
+		RichTextEditor.editorReady = true;
+		return false;
 	}
 	if (new_border_ID == false)
@@ -1039,4 +1176,7 @@
 	if (document.getElementById("subject_" + border_ID))
 		data.subject = document.getElementById("subject_" + border_ID).innerHTML;
+	if(data.subject == get_lang("(no subject)   "))
+		data.subject = '';
+		
 	if (document.getElementById("body_" + border_ID))
 		data.body = document.getElementById("body_" + border_ID).innerHTML;
@@ -1052,6 +1192,8 @@
 		data.date_hour = Element('date_hour_' + border_ID).value;
 	}
+        
 	var signature = RichTextEditor.getSignatureDefault();
-	if(type!="new" && type!="edit")
+        
+	if(type!="new" && type!="edit" && document.getElementById("is_local_"+border_ID) != null)
 		data.is_local_message = (document.getElementById("is_local_"+border_ID).value=="1")?true:false;
 	switch(type){
@@ -1061,5 +1203,15 @@
 			title = "Re: " + data.subject;
 			Element("subject_" + new_border_ID).value = "Re: " + data.subject;			
-			useOriginalAttachments(new_border_ID,border_ID,data.is_local_message);
+
+	if (data.is_local_message){  
+		alert(get_lang("In the local file attachments, including images, will be disregarded. To forward / reply with the attachments, please first make the reopening of the message")+'.');  
+        var imagens = data.body.match(/<img[^>]*>/g);  
+        if(imagens != null)  
+			for (var x = 0; x < imagens.length; x++)  
+				data.body = data.body.replace(imagens[x],'');  
+	}else{
+		useOriginalAttachments(new_border_ID,border_ID);			
+	}      
+
 			// Insert the signature automaticaly at message body if use_signature preference is set
 			if (preferences.use_signature == "1"){  
@@ -1077,5 +1229,14 @@
 			Element("subject_" + new_border_ID).value = "Re: " + data.subject;
 			Element("to_" + new_border_ID).value = data.to;
-			useOriginalAttachments(new_border_ID,border_ID,data.is_local_message);
+			if(data.is_local_message){
+				alert(get_lang("In the local file attachments, including images, will be disregarded. To forward / reply with the attachments, please first make the reopening of the message")+'.');  
+                var imagens = data.body.match(/<img[^>]*>/g);  
+                if(imagens != null)  
+					for (var x = 0; x < imagens.length; x++)  
+						data.body = data.body.replace(imagens[x],'');  
+			}else{
+				useOriginalAttachments(new_border_ID,border_ID);
+			}
+			
 			block_quoted_body = make_body_reply(data.body, data.to, data.date_day, data.date_hour);
 			// Insert the signature automaticaly at message body if use_signature preference is set
@@ -1112,5 +1273,13 @@
 				Element('space_link_' + new_border_ID).style.display='none';
 			}
-			useOriginalAttachments(new_border_ID,border_ID,data.is_local_message);
+			if (data.is_local_message){  
+				alert(get_lang("In the local file attachments, including images, will be disregarded. To forward / reply with the attachments, please first make the reopening of the message")+'.');  
+                var imagens = data.body.match(/<img[^>]*>/g);  
+                if(imagens != null)  
+					for (var x = 0; x < imagens.length; x++)  
+						data.body = data.body.replace(imagens[x],'');  
+                     }      
+                else useOriginalAttachments(new_border_ID,border_ID);  
+
 			// Insert the signature automaticaly at message body if use_signature preference is set
 			if (preferences.use_signature == "1")  
@@ -1160,5 +1329,5 @@
 			break;
 		case "forward":
-			data.is_local_message = (document.getElementById("is_local_"+border_ID).value=="1")?true:false;
+			
 			msg_forward_from = document.createElement('input');
 			msg_forward_from.id = "msg_forward_from_" + new_border_ID;
@@ -1169,9 +1338,24 @@
 			document.getElementById("subject_" + new_border_ID).value = "Fw: " + data.subject;
 			var divFiles = Element("divFiles_"+new_border_ID);
+			
+			
+			if (data.is_local_message) {//Local messages  
+				document.getElementById("is_local_forward"+new_border_ID).value = "1";  
+                alert(get_lang("In the local file attachments, including images, will be disregarded. To forward / reply with the attachments, please first make the reopening of the message")+'.');  
+                var imagens = data.body.match(/<img[^>]*>/g);  
+                if(imagens != null)  
+					for (var x = 0; x < imagens.length; x++)  
+						data.body = data.body.replace(imagens[x],'');    
+                    }
+                else{  
+
+			
+			
 			var campo_arquivo;
+                        
 			if (Element("attachments_" + border_ID)){
 				var attachments = document.getElementById("attachments_" + border_ID).getElementsByTagName("a");
 				
-				for (var i = (attachments.length > 1 ? 1 : 0); i < attachments.length; i++){
+				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)))
@@ -1191,6 +1375,6 @@
 						}
 						else {
-							var tempNomeArquivo = attachments[i].firstChild.nodeValue.split("(");
-							var nomeArquivo = trim(tempNomeArquivo[0]);
+							var tempNomeArquivo = tmp.split("&newfilename=");
+							var nomeArquivo = tempNomeArquivo[tempNomeArquivo.length - 1];
 						}
 
@@ -1218,6 +1402,7 @@
 				}
 			}
+			}
 			// Insert the signature automaticaly at message body if use_signature preference is set
-if (preferences.use_signature == "1")   
+			if (preferences.use_signature == "1")  
  		                            RichTextEditor.setInitData(new_border_ID,'<div><br type="_moz"></div>' + signature + '<div><br type="_moz"></div>'+ make_forward_body(data.body, data.to, data.date, data.subject, data.to_all, data.cc)); 
  		                        else   
@@ -1266,10 +1451,14 @@
 			Element("to_" + new_border_ID).value = data.to;
 			if (data.cc){
+				data.cc = data.cc.replace(/&lt;/gi,"<");
+				data.cc = data.cc.replace(/&gt;/gi,">");
 				Element("cc_" + new_border_ID).value = data.cc;
-				Element("space_link_" + new_border_ID).style.display = 'none';
 				Element("a_cc_link_" + new_border_ID).style.display = 'none';
+				if(Element("cco_" + new_border_ID) != null)
+					Element("space_link_" + new_border_ID).style.display = 'none';
 				Element("tr_cc_"+ new_border_ID).style.display = '';
 			}
 			if (data.cco){
+				if(Element("cco_" + new_border_ID) != null){
 				Element("cco_" + new_border_ID).value = data.cco;
 				Element("space_link_" + new_border_ID).style.display = 'none';
@@ -1277,4 +1466,5 @@
 				Element("tr_cco_"+ new_border_ID).style.display = '';
 			}
+			}
 			Element("subject_" + new_border_ID).value = data.subject;
 			
@@ -1284,5 +1474,7 @@
 			var element_important_message = Element("important_message_" + new_border_ID);
 			if(element_important_message) {
-				if(Element("is_important_" + border_ID).value == "1") element_important_message.checked = true;
+					
+				if(Element("disposition_important_" + border_ID))
+					element_important_message.checked = true;				
 			}
 
@@ -1301,5 +1493,6 @@
 					tmp = link_attachment.innerHTML.substring(0,link_attachment.innerHTML.lastIndexOf("("));
 					a_tmp[2] = "'"+tmp.substring(0,tmp.length-1)+"'";
-					s_tmp = trim(escape(connector.serialize(a_tmp)));
+					s_tmp = escape(connector.serialize(a_tmp));
+
 					divFiles.innerHTML += "<input style='border:0' type='CHECKBOX' name='forwarding_attachments[]' checked value=\""+s_tmp+"\"/>";
 					divFiles.appendChild(link_attachment);
@@ -1315,5 +1508,6 @@
 	set_border_caption("border_id_" + new_border_ID, title);
 
-
+	resizeWindow();
+	//save_msg(new_border_ID);
 	return new_border_ID; //Preciso retornar o ID da nova mensagem.
 }
@@ -1484,15 +1678,14 @@
 	{
 		var handler = function(data){
-                        if(typeof(expresso_local_messages) != "undefined"){
+
 			if(data.msg_day == '')
 			{
 				header=expresso_local_messages.get_msg_date(data.original_ID, proxy_mensagens.is_local_folder(get_current_folder()));
-                                if(header){
+
 				data.fulldate=header.fulldate;
 				data.smalldate=header.smalldate;
 				data.msg_day = header.msg_day;
 				data.msg_hour = header.msg_hour;
-			}
-			}
+
                       }
 			this.show_msg(data);
@@ -1564,8 +1757,27 @@
 	mail_as_plain = ( mail_as_plain ) ? mail_as_plain.checked : false;
 
+       var content_body  = RichTextEditor.getData('body_'+ID);
+       //Remove imagens do corpo que estao com o checkbox desmarcados
+       var files_checkbox =  $("#divFiles_"+ID+" input:checkbox");
+       var files_unchecked = new Array();
+       for (var i = 0; i < files_checkbox.length; i++)
+            if(files_checkbox[i].checked !== true)
+                files_unchecked.push(connector.unserialize(unescape(trim(files_checkbox[i].value))));
+
+       var imagens = content_body.match(/<img[^>]*>/g);
+       
+       if(imagens != null)
+            for (var x = 0; x < imagens.length; x++)
+                for (var xx = 0; xx < files_unchecked.length; xx++)
+                    if(imagens[x].indexOf('indexPart='+files_unchecked[xx][3].replace(/'/g,'')) !== -1)
+                         content_body = content_body.replace(imagens[x],'');
+                
+        //--------------------------------------------------------------------------//
+        
 	var textArea = document.createElement("TEXTAREA");
 	textArea.style.display='none';
 	textArea.name = "body";
-	textArea.value = RichTextEditor.getData('body_'+ID); 
+	textArea.value = content_body;
+   
 	var input_folder = document.createElement("INPUT");
 	input_folder.style.display='none';
@@ -1633,6 +1845,35 @@
 		handler_send_message(data_return,ID);
 	}
-	else
+	else{
 		cExecuteForm("$this.imap_functions.send_mail", form, handler_send_message, ID);
+	}
+}
+function is_valid_email(campo){	
+	var invalidEmail = searchEmail(campo);
+	var semicolon = campo.split(";");
+	
+	if((campo.replace(/^\s+|\s+$/g,"")) != ""){
+			if(invalidEmail[0] == true){
+				write_msg("Erro de SMTP: Os endereços de destinatário a seguir falharam: "+ invalidEmail[1]);
+				return false;
+			}else{
+				if(semicolon.length > 1){
+					var stringError = "Erro de SMTP: Os endereços devem ser separados apenas por vígula: ";
+					for(var i= 0; i < semicolon.length; i++){
+						stringError = stringError + semicolon[i];
+						if(i+1 < semicolon.length)
+							stringError = stringError + " ; ";
+					}
+					write_msg(stringError);
+					return false;
+				}else {
+					return true;
+				}
+			}
+	}
+	else{
+		write_msg(get_lang("Message without receiver"));
+		return false;
+	}		
 }
 function change_tr_properties(tr_element, newUid, newSubject){
@@ -1657,13 +1898,18 @@
 {
 	Element("send_button_"+border_id).style.visibility="visible";
-	var handler_delete_msg = function(data){refresh(preferences.alert_new_msg);};
-
- 	if (data == null || data.append != true )
+	var handler_delete_msg = function(data){refresh(preferences.alert_new_msg);RichTextEditor.execPosInstance('body_'+border_id);};
+        if(data === null)
 	{
-		RichTextEditor.saveFlag = 0;
-		if (! data.append)
-                    if(data == 'Post-Content-Length')
-                        write_msg(get_lang('The size of this message has exceeded  the limit (%1B).', preferences.max_attachment_size ? preferences.max_attachment_size : Element('upload_max_filesize').value));
-		else
+            write_msg(get_lang('ERROR saving your message.'));
+            return null;
+        }
+
+	if(data.append === "Over quota"){
+		write_msg(get_lang('ERROR saving your message over quota.'));
+		return;
+	}
+	else if ( data.append !== true )
+	{
+		if (data.append == null)
                     write_msg(get_lang('ERROR saving your message.'));
 		else
@@ -1685,105 +1931,70 @@
 	{
 		var newImage = false;
+		RichTextEditor.saveFlag = 1;
 		openTab.imapUid[border_id] = data.msg_no;
 		openTab.imapBox[border_id] = data.folder_id;
 
 		var newTitle = document.getElementById('subject_'+border_id).value;
-		if (newTitle == '')
+		if (newTitle.length > 18)
+                    newTitle = newTitle.substr(18) + '...';
+                else if (newTitle == '')
                     newTitle = get_lang("No subject");
-		set_border_caption('border_id_'+border_id, newTitle);
+		document.getElementById('font_border_id_'+border_id).innerHTML = newTitle;                 
+                Element('border_id_'+border_id).title = newTitle; 
 
 		// Replace the embedded images for new uids
 		var content_body  = RichTextEditor.getData('body_'+border_id);
-
-                if (is_ie)
+		var body_images   = content_body.match(/msgNumber=\d*/g);
+		var folder_images = content_body.match(/msgFolder=[^&]*&/g); 		
+
+                if (body_images != null)
                 {
-                    var content_body =  mainField.document.getElementsByTagName('body').item(0).innerHTML;
-                    var body_images = content_body.match(/msg_num=\d*/g);
-                    var images_part = content_body.match(/msg_part=\d*/g);
-                    if (body_images)
+                    for (var i=0; i<body_images.length; i++)
                     {
-                        for (var i=0; i<body_images.length; i++){
-                            content_body = content_body.replace(body_images[i],"msg_num="+openTab.imapUid[border_id]);
+                        if( folder_images != null)
+                          content_body = content_body.replace(folder_images[i], "msgFolder=INBOX" + cyrus_delimiter + draftsfolder +"&");
+
+
+                            
+                        
+                        content_body = content_body.replace(body_images[i],"msgNumber="+openTab.imapUid[border_id]);
+                    }
+
+                    var images_part   = content_body.match(/indexPart=[0-9.]*/g);
+
+                    if(images_part != null)
+                                {
+                        for (var x = 0; x < images_part.length; x++)
+                                {
+                            var position = images_part[x].substr(10,images_part[x].length);
+                            content_body = content_body.replace(images_part[x],'indexPart(||.|||.||)='+data.imagesParts[position]);
+                                }
+
                         }
-
-                        var allImgs = new Array (images_part.length);
-                        //var j=-1;
-                        for (var i in images_part){
-
-                            if (i == 0)
-                                var image_number = parseInt(images_part[i].substr(9));
-                            else
-                                image_number = "null";
-                            
-                            if (! isNaN(image_number))
-                            {
-                                if (! allImgs[image_number])
-                                {
-                                    allImgs[image_number] = true;
-                                    //j--;
-                                }
-                                //content_body = content_body.replace(images_part[i],'msg_part='+j);
-                            }
-                            //content_body = content_body.replace(/msg_part=-/g,'msg_part=');
-                        }
-                        
+               	    content_body = content_body.replace(/indexPart\(\|\|\.\|\|\|\.\|\|\)=/g,'indexPart=');             
                     }
-                }
-                else
-                    {
-                        for (var i = 0; i < bodyChildNodes.length; i++){
-                            if (typeof(bodyChildNodes[i].tagName) != 'undefined' && bodyChildNodes[i].tagName.search(/img/i) != -1)
-                            {
-                                bodyChildNodes[i].src =  bodyChildNodes[i].src.replace(/msg_num=\d*/g, "msg_num="+openTab.imapUid[border_id]);
-
-                                var allImgs = new Array();
-                                var image_number = parseInt(bodyChildNodes[i].src.match(/msg_part=\d*/g)[0].substr(9));
-                                if (! allImgs[image_number])
-                                {
-                                    allImgs[image_number] = true;
-                                }
-                            }
-                            else
-                                {
-                                    continue;
-                                }
-
-                        }
-                    }
+
+                   
 
 		//Replace all files to new files
 		var divFiles = Element("divFiles_"+border_id);
-		elFiles = divFiles.getElementsByTagName("input");
-		var countCheck =0;
-		for (var i=0; i<elFiles.length; i++) {
-                    if(elFiles[i].value !=""){
-                        if (elFiles[i].type == "checkbox") {
-                            var tmpData = connector.unserialize(decodeURIComponent(elFiles[i].value));
-                            tmpData[1] = data.msg_no;
-                            elFiles[i].value = encodeURIComponent(connector.serialize(tmpData));
-                            countCheck++;
-                        }
-                        else {
-                            elFiles[i].value ="";
-                            parantNodeFile = elFiles[i].parentNode.parentNode;
-                            parantNodeFile.removeChild(elFiles[i].parentNode);
-                            i--;
-                        }
-                    }
-		}
+		divFiles.innerHTML = '';
+
 
 		var attach_files = connector.unserialize(data.files);
 		if (attach_files != null) {
                     openTab.countFile[border_id] = attach_files.length;
-                    att_index = countCheck;
-                    for (att_index; att_index < attach_files.length; att_index++)
-                    {
+                    for (var att_index = 0; att_index < attach_files.length; att_index++){
 
                         var link_attachment = document.createElement("a");
-			var fileName = attach_files[att_index].substr(0,attach_files[att_index].indexOf('_SIZE_'));
-			var fileSize = parseInt(attach_files[att_index].substr(attach_files[att_index].indexOf('_SIZE_')+6))/1024
-			link_attachment.innerHTML = fileName + " ("+borkb((parseInt(fileSize)*1024))+")";
-
-                        var href = "'"+folder_id+"','"+data.msg_no+"','"+(att_index)+"','"+(att_index+2)+"','base64'";
+
+                        var fileName = Base64.decode(attach_files[att_index].name);
+                        var fileSize = attach_files[att_index].size / 1024;
+                        
+                        
+                        link_attachment.innerHTML = fileName + " ("+parseInt(fileSize)+" kb)";
+						
+						var encoding = /\.eml$/.exec(fileName)? '7bit' : 'base64';
+                        var href = "'"+folder_id+"','"+data.msg_no+"','"+(att_index)+"','0."+(att_index+1)+"','"+encoding+"'";
 
                         link_attachment.setAttribute("href", "javascript:download_attachments("+href+")");
@@ -1793,27 +2004,18 @@
                         s_tmp = escape(connector.serialize(a_tmp));
 
-                        var check_attachment = document.createElement("INPUT");
+                        var check_attachment = document.createElement("input");
 			check_attachment.type = 'CHECKBOX';
 			check_attachment.name = 'forwarding_attachments[]';
-			check_attachment.value = trim(s_tmp);
-
-                        if (!divFiles.childNodes[0])
-                        {
-                            divFiles.appendChild(document.createElement("BR"));
-                        }
-                        else
-                            {
-                                divFiles.insertBefore(document.createElement("BR"),divFiles.childNodes[0]);
-                            }
-
-                        divFiles.insertBefore(link_attachment,divFiles.childNodes[0]);
-                        divFiles.insertBefore(check_attachment,divFiles.childNodes[0]);
-
-                        check_attachment.checked = true;
-                        check_attachment.setAttribute("checked", "checked");
+                        check_attachment.value = s_tmp;
+
+
 
                         divFiles.appendChild(check_attachment);
                         divFiles.appendChild(link_attachment);
+
                         divFiles.appendChild(document.createElement("br"));
+						
+						check_attachment.checked = true;
+                        check_attachment.setAttribute("checked", "checked");
                     }
 					} 
@@ -1843,18 +2045,12 @@
                         change_tr_properties(tr_msg, data.msg_no, data.subject);
                     }
-		} else {
-                    refresh();
-		}
-
-		var save_link = Element("save_message_options_"+border_id);
-		save_link.onclick = '';
-		save_link.className = 'message_options_inactive';
-		watch_changes_in_msg(border_id);
-		write_msg(get_lang('Your message was save as draft in folder %1.', lang_folder(folder_name)));
-                setTimeout( function(){RichTextEditor.saveFlag = 1;}, 1000 );
-	}
-}
-
-function save_msg(border_id,withImage){
+
+	}
+                setTimeout( function(){RichTextEditor.saveFlag = 1;RichTextEditor.execPosInstance('body_'+border_id);}, 1000 );
+	}
+        return null;
+}
+
+function save_msg(border_id,withImage, out){
 	if (typeof(withImage) == 'undefined')
 		withImage = false;
@@ -1867,5 +2063,5 @@
 		var folder_id = openTab.imapBox[border_id];
 	else
-		var folder_id = "INBOX/"+draftsfolder;
+		var folder_id = "INBOX" + cyrus_delimiter + draftsfolder;
 
 	if (folder_id == 'INBOX') // and folder name from border
@@ -1879,13 +2075,62 @@
 	tmp_folder_id=folder_id;
 	message_id = openTab.imapUid[border_id];
-	var handler_save_msg = function(data){return_save(data,this.tmp_border_id,this.tmp_folder_name,this.tmp_folder_id,this.message_id);}
+	var handler_save_msg = function(data){
+		if(typeof(out) == 'undefined'){
+			return_save(data,this.tmp_border_id,this.tmp_folder_name,this.tmp_folder_id,this.message_id);
+			var save_link = Element("save_message_options_"+border_id);
+			if(!withImage){
+				if(data.append === true){
+					save_link.className = 'message_options_inactive';
+					save_link.onclick = '';
+					watch_changes_in_msg(border_id);	
+					write_msg(get_lang('Your message was save as draft in folder %1.', lang_folder(folder_name)));
+				}
+				if(auto){
+					auto = false;
+				}
+			}
+			else{
+				write_msg(get_lang('Wait a moment, your image is uploading ...'));
+				var auto = true;
+				setTimeout( function(){save_msg(border_id)}, 1000 );
+			}
+		}else{
+			if(data.append === true){
+				write_msg(get_lang('Your message was save as draft in folder %1.', lang_folder(folder_name)));
+			}else if(data.append == null){
+				write_msg(get_lang('ERROR saving your message.'));
+			}if(data.append === "Over quota"){
+				write_msg(get_lang('ERROR saving your message over quota.'));
+			}
+		}
+		
+	}
 
         var mail_as_plain = document.getElementById( 'textplain_rt_checkbox_' + border_id );
 	mail_as_plain = ( mail_as_plain ) ? mail_as_plain.checked : false;
 
+        var content_body  = RichTextEditor.getData("body_"+border_id);
+       //Remove imagens do corpo que estao com o checkbox desmarcados
+       var files_checkbox =  $("#divFiles_"+border_id+" input:checkbox");
+       var files_unchecked = new Array();
+       for (var i = 0; i < files_checkbox.length; i++)
+            if(files_checkbox[i].checked !== true)
+                files_unchecked.push(connector.unserialize(unescape(trim(files_checkbox[i].value))));
+
+       var imagens = content_body.match(/<img[^>]*>/g);
+       if(imagens != null)
+            for (var x = 0; x < imagens.length; x++)
+                for (var xx = 0; xx < files_unchecked.length; xx++)
+                    if(imagens[x].indexOf('indexPart='+files_unchecked[xx][3].replace(/'/g,'')) !== -1)
+                         content_body = content_body.replace(imagens[x],'');
+        
+        if(files_unchecked.length > 0)
+            RichTextEditor.setData("body_"+border_id,content_body);
+            
+        
 	var textArea = document.createElement("TEXTAREA");
 	textArea.style.display='none';
 	textArea.name = "body";
-	textArea.value = RichTextEditor.getData("body_"+border_id);
+	textArea.value = content_body;
 	var input_folder = document.createElement("INPUT");
 	input_folder.style.display='none';
@@ -1948,5 +2193,5 @@
 	}
 	else
-		write_msg('ERROR saving your message.');
+		write_msg(get_lang('ERROR saving your message.'));
 }
 
@@ -1957,8 +2202,25 @@
 	tmp_folder_name=folder_name;
 	var handler_save_msg = function(data){return_saveas(data,this.tmp_border_id,this.tmp_folder_name);}
+        
+       var content_body  = RichTextEditor.getData("body_"+border_id);
+       //Remove imagens do corpo que estao com o checkbox desmarcados
+       var files_checkbox =  $("#divFiles_"+border_id+" input:checkbox");
+       var files_unchecked = new Array();
+       for (var i = 0; i < files_checkbox.length; i++)
+            if(files_checkbox[i].checked !== true)
+                files_unchecked.push(connector.unserialize(unescape(trim(files_checkbox[i].value))));
+
+       var imagens = content_body.match(/<img[^>]*>/g);
+       
+       if(imagens != null)
+            for (var x = 0; x < imagens.length; x++)
+                for (var xx = 0; xx < files_unchecked.length; xx++)
+                    if(imagens[x].indexOf('indexPart='+files_unchecked[xx][3].replace(/'/g,'')) !== -1)
+                         content_body = content_body.replace(imagens[x],'');
+        
 	var textArea = document.createElement("TEXTAREA");
 	textArea.style.display='none';
 	textArea.name = "body";
-	textArea.value = RichTextEditor.getData("body_"+border_id);
+	textArea.value = content_body;
 
 	var input_folder = document.createElement("INPUT");
@@ -1984,11 +2246,7 @@
 function set_messages_flag(flag, msgs_to_set){
 	var handler_set_messages_flag = function (data){
-		var _tab_sufix = getTabSufix();
-		var _chk_box;
-		var _fld_box;
 		if(!verify_session(data))
 			return;
-		var msgs_to_set = data.msgs_to_set.split(","); // messages ids
-		var rowids_to_set = data.rowids_to_set.split(","); // rows ids
+		var msgs_to_set = data.msgs_to_set.split(",");
 
 		if(!data.status) {
@@ -1996,6 +2254,6 @@
 			Element('chk_box_select_all_messages').checked = false;
 			for (var i = 0; i < msgs_to_set.length; i++) {
-				Element("check_box_message_" + rowids_to_set[i]).checked = false;
-				remove_className(Element(rowids_to_set[i]), 'selected_msg');
+				Element("check_box_message_" + msgs_to_set[i]).checked = false;
+				remove_className(Element(msgs_to_set[i]), 'selected_msg');
 			}
 			if(!data.msgs_unflageds)
@@ -2027,33 +2285,32 @@
 				}
 				proxy_mensagens.get_msg(msgs_to_set[i],current_folder, false, setFlag);
-			}
-
-			_chk_box = Element("check_box_message_" + rowids_to_set[i]);
-			_fld_box = (_tab_sufix ? Element("check_box_message_" + msgs_to_set[i]) : null);
-			if(_chk_box){
+
+
+			}
+			if(Element("check_box_message_" + msgs_to_set[i])){
 				switch(data.flag){
 					case "unseen":
-						set_msg_as_unread(rowids_to_set[i]);
-						if (_fld_box)
 						    set_msg_as_unread(msgs_to_set[i]);
-						_chk_box.checked = false;
+						if(results_search_messages != "") 
+							set_msg_as_unread(results_search_messages, true);
+						Element("check_box_message_" + msgs_to_set[i]).checked = false;
 						break;
 					case "seen":
-						set_msg_as_read(rowids_to_set[i], false);
-						if (_fld_box)
-							set_msg_as_read(msgs_to_set[i]);
-						_chk_box.checked = false;
+						set_msg_as_read(msgs_to_set[i], false);
+						if(results_search_messages != "") 
+							set_msg_as_read(results_search_messages, false, true);
+						Element("check_box_message_" + msgs_to_set[i]).checked = false;
 						break;
 					case "flagged":
-						set_msg_as_flagged(rowids_to_set[i]);
-						if (_fld_box)
 						    set_msg_as_flagged(msgs_to_set[i]);
-						_chk_box.checked = false;
+						if(results_search_messages != "") 
+							set_msg_as_flagged(results_search_messages, true);
+						document.getElementById("check_box_message_" + msgs_to_set[i]).checked = false;
 						break;
 					case "unflagged":
-						set_msg_as_unflagged(rowids_to_set[i]);
-						if (_fld_box)
 						    set_msg_as_unflagged(msgs_to_set[i]);
-						_chk_box.checked = false;
+						if(results_search_messages != "") 
+ 	                        set_msg_as_unflagged(results_search_messages, true);
+						Element("check_box_message_" + msgs_to_set[i]).checked = false;
 						break;
 				}
@@ -2064,21 +2321,10 @@
 
 	var folder = get_current_folder();
-	if (msgs_to_set == 'get_selected_messages') {
+	if (msgs_to_set == 'get_selected_messages')
 		var msgs_to_set = this.get_selected_messages();
-		if ( (msgs_to_set) && (msgs_to_set.match(/_s/)) ) {
-			folder = get_selected_messages_folder();
-			if (!folder) {
-				alert(get_lang("You cant manipulate messages from multiple folders on search"));
-				return;
-			}
-		}
-	}
 	else
 		folder = Element("input_folder_"+msgs_to_set+"_r").value;
 
 	if (msgs_to_set)
-		if (folder && proxy_mensagens.is_local_folder(folder))
-			expresso_local_messages.set_messages_flag(msgs_to_set, flag); //expresso_local_messages.set_messages_flag(msgs_to_set.replace(/_s[^,]*/g,""), flag);
-		else
 		cExecute ("$this.imap_functions.set_messages_flag&folder="+folder+"&msgs_to_set="+msgs_to_set+"&flag="+flag, handler_set_messages_flag);
 	else
@@ -2137,5 +2383,15 @@
 	var folder= Element('border_id_0').innerHTML;
 	var thead = Element('divScrollHead_'+numBox).firstChild.firstChild.innerHTML;
+	
+	msgs_number = get_selected_messages();
+	if(msgs_number == false){
 	var tbody = Element('divScrollMain_'+numBox).firstChild.firstChild.innerHTML;
+	}else{
+		msgs_number = msgs_number.split(",");
+		var tbody = "";
+		for(var i = 0; i < msgs_number.length; i++){
+			tbody += "<tr id="+msgs_number[i]+" class=\"tr_msg_unread tr_msg_read2\">"+ Element(msgs_number[i]).innerHTML+"</tr>";
+		}	
+	}
 	var print_width = screen.width - 200;
 	var x = ((screen.width - print_width) / 2);
@@ -2151,5 +2407,6 @@
 	thead = thead.replace(seekDot, "style='display:none'");
 	tbody = tbody.replace(seekDot, "style='display:none'");
-
+	thead = thead.replace("<td style=\"cursor: pointer;\"></td>", "");		
+	thead = thead.replace("<td style=\"cursor: pointer;\" style='display:none'><input title=\"Selecionar todas as mensagens.\" class=\"checkbox\" id=\"chk_box_select_all_messages\" type=\"checkbox\"></td>", "");
 	while (1){
 		try{
@@ -2157,5 +2414,5 @@
 			var html = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html>'
 			+ '<head><link rel="stylesheet" type="text/css" href="templates/'+template+'/print.css"></head>'
-			+ '<body class="print-all-messages"><h1>ExpressoLivre - ExpressoMail</h1>'
+	 	    + cabecalho + '</h4><hr>' 
 			+ '<h2>'+folder+'</h2><hr/><blockquote><font size="2">'
 			+ '<table width="100%" cellpadding="0" cellspacing="0">'
@@ -2204,24 +2461,9 @@
 		else if(countAtt > 1) 
 			for (var i = 1; i <attachments.getElementsByTagName('a').length; i++) 
-				att += attachments.getElementsByTagName('a')[i].innerHTML + " | "; 
+				att += " | " + attachments.getElementsByTagName('a')[i].innerHTML; 
  	} 
  	        
 	var body = Element('body_'+border_ID); 
 	
-        if(!is_ie)
-            {
-                var link = location.href.replace(/\/expressoMail1_2\/(.*)/, "");
-                var tab_tags = body.getElementsByTagName("IMG");
-                for(var i = 0; i < tab_tags.length;i++)
-                    {
-                        var _img = document.createElement("IMG");
-                        _img.src = tab_tags[i].src;
-                        if(tab_tags[i].src.toUpperCase().indexOf('/INC/SHOW_EMBEDDED_ATTACH.PHP?MSG_FOLDER=') > -1)
-                            {
-                                _img.src = link + '/expressoMail1_2'+tab_tags[i].src.substr(tab_tags[i].src.toUpperCase().indexOf('/INC/SHOW_EMBEDDED_ATTACH.PHP?MSG_FOLDER='));
-                            }
-                        tab_tags[i].parentNode.replaceChild(_img,tab_tags[i]);
-                    }
-            }
 	var print_width = screen.width - 200;
 	var x = ((screen.width - print_width) / 2);
@@ -2258,5 +2500,5 @@
 		try{
 			var html ='<body>';
-			html += "<h4>ExpressoLivre - ExpressoMail</h4><hr>";
+			html += cabecalho + '</h4><hr>';
 			html += '<table><tbody>';
 			if(sender)
@@ -2289,12 +2531,15 @@
 			html += "</tbody></table><hr>";
 			window_print.document.write(html + body.innerHTML);
-			if(!is_ie){
+
 				var tab_tags = window_print.document.getElementsByTagName("IMG");
+                        var link = location.href.replace(/\/expressoMail1_2\/(.*)/, "");
 				for(var i = 0; i < tab_tags.length;i++){
-					var _img = document.createElement("IMG");
-					_img.src = tab_tags[i].src;
+                                var _img = tab_tags[i].cloneNode(true);
+                                if(tab_tags[i].src.toUpperCase().indexOf('INC/GET_ARCHIVE.PHP?MSGFOLDER=') > -1)
+                                    _img.src = link + '/expressoMail1_2/'+tab_tags[i].src.substr(tab_tags[i].src.toUpperCase().indexOf('INC/GET_ARCHIVE.PHP?MSGFOLDER='));
+
 					tab_tags[i].parentNode.replaceChild(_img,tab_tags[i]);
 				}
-			}
+                        
 			break;
 		}
@@ -2319,5 +2564,5 @@
 			if (get_current_folder() == 'INBOX'+cyrus_delimiter+trashfolder){
 				draw_paging(0);
-				kill_current_box();
+				remove_rows(document.getElementById("table_box"));				
 				Element('tot_m').innerHTML = 0;
 				Element('new_m').innerHTML = 0;
@@ -2339,5 +2584,5 @@
 		if (get_current_folder() == 'INBOX'+cyrus_delimiter+spamfolder){
 			draw_paging(0);
-			kill_current_box();
+			remove_rows(document.getElementById("table_box"));
 		}
 		tree_folders.getNodeById('INBOX'+cyrus_delimiter+spamfolder).alter({caption: get_lang("Spam")});
@@ -2367,6 +2612,11 @@
 			write_msg(get_lang('Error compressing messages (ZIP). Contact the administrator.'));
 		}
-		else
-			download_attachments(null, null, data, null,null,'mensagens.zip');
+		else{
+			var filename = 'mensagens.zip'; 
+			if (data.match(/\.eml$/gi)) { 
+	                        filename = 'fonte_da_mensagem.eml'; 
+			} 
+			download_attachments(null, null, data, null,null,filename);
+		}
 	}
 
@@ -2379,19 +2629,23 @@
 }
 
-function select_all_search_messages(select, id){
-	var search_box = Element("table_resultsearch_" + getNumBoxFromTabId(id)).firstChild;
-	var felement = search_box.firstChild;
-	while(felement)
-	{
-		if (select) {
-			felement.firstChild.firstChild.checked = true;
-			add_className(felement, 'selected_msg');
-		}
-		else {
-			felement.firstChild.firstChild.checked = false;
-			remove_className(felement, 'selected_msg');
-		}
-		felement = felement.nextSibling;
-	}
+function select_all_search_messages(select, aba){
+	   jQuery(function() {
+        if(select){
+			jQuery("#"+aba+" tr").each(function(i, o) {
+			
+				o.firstChild.firstChild.checked = true;
+				add_className(o, 'selected_msg');
+			});		
+		}else{
+			jQuery("#"+aba+" tr").each(function(i, o) {
+			
+				o.firstChild.firstChild.checked = false;
+				remove_className(o, 'selected_msg');
+			});
+	}
+	});
+
+	
+
 }
 
@@ -2426,9 +2680,20 @@
 	}
 }
+function save_image2(info){ 
+	var obj = jQuery.parseJSON(unescape(info)); 
+	download_attachments(obj.folder, obj.message, obj.thumbIndex, obj.pid, obj.encoding, obj.type.replace("/",".")); 
+} 
 
 function nospam(msgs_number, border_ID, folder){
 	if (folder == 'null')
 		folder = get_current_folder();
-	var new_folder 	= 'INBOX';
+	var new_folder = '';
+	if(folder.substr(0,4) == 'user'){
+		arrayFolder = folder.split(cyrus_delimiter);
+		new_folder = 'user'+cyrus_delimiter+arrayFolder[1];
+	}
+	else{
+		new_folder = 'INBOX';
+	}
 	var new_folder_name = get_lang('INBOX');
 	var handler_move_msgs = function(data){
@@ -2449,5 +2714,5 @@
 
 	if (parseInt(msgs_number) > 0 || msgs_number.length > 0)
-		cExecute ("$this.imap_functions.spam&folder="+folder+"&spam=false"+"&msgs_number="+msgs_number+"&border_ID="+border_ID+"&sort_box_type="+sort_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="+preferences.delete_and_show_previous_message+"&cyrus_delimiter="+cyrus_delimiter, handler_move_msgs);
+		cExecute ("$this.imap_functions.spam&folder="+folder+"&spam=false"+"&msgs_number="+msgs_number+"&border_ID="+border_ID+"&sort_box_type="+sort_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="+0+"&cyrus_delimiter="+cyrus_delimiter, handler_move_msgs);
 	else
 		write_msg(get_lang('No selected message.'));
@@ -2457,10 +2722,22 @@
 	if (folder == 'null')
 		folder = get_current_folder();
-	var new_folder = 'INBOX'+cyrus_delimiter+'Spam';
+	var new_folder = '';
+	if(folder.substr(0,4) == 'user')
+	{       
+		arrayFolder = folder.split(cyrus_delimiter);
+		new_folder = 'user'+cyrus_delimiter+arrayFolder[1]+cyrus_delimiter+spamfolder;
+	}
+	else
+	{
+		new_folder = 'INBOX' + cyrus_delimiter + spamfolder;
+	}
 	var new_folder_name = 'Spam';
+	var not_opem_previus = true;
 	var handler_move_msgs = function(data){
-		proxy_mensagens.proxy_move_messages(folder, msgs_number, border_ID, new_folder, new_folder_name);
-		if (openTab.type[currentTab] > 1)
+		proxy_mensagens.proxy_move_messages(folder, msgs_number, border_ID, new_folder, new_folder_name, not_opem_previus);
+		if (openTab.type[currentTab] > 1){
+			if(preferences.delete_and_show_previous_message == 1)
 			delete_border(currentTab,'false');
+	}
 	}
 
@@ -2471,5 +2748,5 @@
 
 	if(parseInt(msgs_number) > 0 || msgs_number.length > 0)
-		cExecute ("$this.imap_functions.spam&folder="+folder+"&spam=true"+"&msgs_number="+msgs_number+"&border_ID="+border_ID+"&sort_box_type="+sort_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="+preferences.delete_and_show_previous_message+"&cyrus_delimiter="+cyrus_delimiter, handler_move_msgs);
+		cExecute ("$this.imap_functions.spam&folder="+folder+"&spam=true"+"&msgs_number="+msgs_number+"&border_ID="+border_ID+"&sort_box_type="+sort_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="+0+"&cyrus_delimiter="+cyrus_delimiter, handler_move_msgs);
 	else
 		write_msg(get_lang('No selected message.'));
@@ -2565,6 +2842,7 @@
 			if ( er.test(wfolders_tree._selected.id) )
 			{
-				archive_msgs('INBOX/Lixeira/tmpMoveToLocal',wfolders_tree._selected.id,data);
-				cExecute('$this.imap_functions.delete_mailbox',function(){},'del_past=INBOX/Lixeira/tmpMoveToLocal');
+				alert( "Mensagens não podem ser importadas em pastas locais" );
+				//archive_msgs('INBOX/Lixeira/tmpMoveToLocal',wfolders_tree._selected.id,data);
+				//cExecute('$this.imap_functions.delete_mailbox',function(){},'del_past=INBOX/Lixeira/tmpMoveToLocal');
 			}
 						 else{
@@ -2614,12 +2892,40 @@
 }
 function import_calendar(data){
+    var import_url = '$this.db_functions.import_vcard&msg_folder='+data;
+
 	function handler_import_calendar(data){
 		if(data === true){
 			write_msg(get_lang("The event was imported successfully."));
 		}
+            else if( data['url'] )
+            {
+                var form = document.createElement( "form" );
+
+                form.setAttribute( "action", DEFAULT_URL + data['url'] + '&isPost=true' );
+                form.setAttribute( "method", "POST" );
+
+                document.body.appendChild( form );
+
+                form.submit();
+            }
+            else
+                write_msg(get_lang(data));
 	}
 	if(confirm(get_lang("Do you confirm this import to your Calendar?"))){
-			cExecute('$this.db_functions.import_vcard&msg_folder='+data,handler_import_calendar);
-	}
+                    cExecute( import_url +'&from_ajax=true',handler_import_calendar);
+    }
+}
+function open_msg_part(data){
+	var handler_open_msg_part = function (data)
+        {
+            if(data.append == 1)
+            {
+                proxy_mensagens.get_msg(data.msg_number,data.msg_folder,false,show_msg);
+                partMsgs.push(data.msg_number);
+	}
+            else
+               write_msg(data.append);
+	}
+        cExecute('$this.imap_functions.ope_msg_part&msg_folder='+data+'&save_folder=INBOX'+cyrus_delimiter+trashfolder , handler_open_msg_part);	
 }
 function hack_sent_queue(data,rowid_message) {
@@ -2696,5 +3002,5 @@
 		var er_Email =  new RegExp("<(.*?)>"); 
                 // TODO Use validateEmail of common functions !
-		var er_ValidaEmail = new RegExp("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$");
+		var er_ValidaEmail = new RegExp("^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,3})$");
 
 		for (i=0; i < arrayEmailsFull.length; i++){
@@ -2702,10 +3008,10 @@
 			tempEmail = email == null  ? arrayEmailsFull[i]:email[1];
 			tempEmail = tempEmail.replace(/^\s+|\s+$/g,"");
+			
 			if (tempEmail != '') {
 				singleEmail = er_ValidaEmail.exec(tempEmail);
-
 				if (singleEmail == null) {
 					arrayInvalidEmails[0] = true;
-					arrayInvalidEmails[1] += (email == null ? arrayEmailsFull[i] : email[1]) + "; ";
+					arrayInvalidEmails[1] += (email == null ? arrayEmailsFull[i] : email[1]) + "";
 				}
 			}
Index: trunk/expressoMail1_2/js/connector.js
===================================================================
--- trunk/expressoMail1_2/js/connector.js	(revision 4760)
+++ trunk/expressoMail1_2/js/connector.js	(revision 5134)
@@ -428,13 +428,15 @@
 	}
 	// Cancel Request Connector
-	cConnector.prototype.cancelRequest = function (){
-
-                if (!this.requests[this.tid]){
+	cConnector.prototype.cancelRequest = function (id){
+
+		id = id || this.tid;
+
+                if (!this.requests[id]){
 			return false;
 		}
 		//this.oxmlhttp.onreadystatechange = null;
-                this.requests[this.tid].abort();
-                delete this.requests[this.tid];
-		this.requests[this.tid] = null;
+                this.requests[id].abort();
+                delete this.requests[id];
+		this.requests[id] = null;
 		
 		this.hideProgressBar();
Index: trunk/expressoMail1_2/js/search.js
===================================================================
--- trunk/expressoMail1_2/js/search.js	(revision 4993)
+++ trunk/expressoMail1_2/js/search.js	(revision 5134)
@@ -16,5 +16,4 @@
 		this.txtfields 		= new Array("txt_ass","txt_de","txt_body","txt_para","txt_cc","txt_cco", "since_date", "before_date", "on_date");
 		this.selectFields	= new Array("flagged", "seen", "answered", "recent");
-                this.localResults   = 0;
 	}
 
@@ -227,5 +226,5 @@
 
     	// Gears - local
-		if (preferences.use_local_messages == 1 && EsearchE.localResults != 0)
+		if ( preferences.use_local_messages == 1 )
 		{
 			temp = expresso_local_messages.list_local_folders();
@@ -234,14 +233,12 @@
 				local_folders.push(temp[x][0]);
 			}
+ 		}
+		
                     if ( local_folders.length > 0 )
 			_gears = expresso_local_messages.search( local_folders, expresso_local_messages.getFilter() );
-                        _data['gears_num_msgs']	= _gears.length;
-		}else{
-                    _data['gears_num_msgs']	= 0;
-                }
 
 		_data['data'] 			= data['data'];
 		_data['num_msgs']		= data['num_msgs'];
-		
+		_data['gears_num_msgs']	= _gears.length;
 
 		delete_border( data['currentTab'], false);
@@ -263,5 +260,5 @@
  
 		if(size > parseInt(preferences.max_email_per_page)) { 
-			this.totalPages = parseInt(size/preferences.max_email_per_page); 
+			this.totalPages = Math.ceil(size/preferences.max_email_per_page); 
 			if((size/preferences.max_email_per_page) > this.totalPages) 
 			this.totalPages++; 
@@ -270,6 +267,10 @@
 		if(this.page != 0) { 
 			_link = document.createElement("A"); 
+		if( this.value )
+		  _link.href  = 'javascript:EsearchE.quickSearchMail( false, '+0+', false, "'+currentTab+'" )'; 
+		else{
             _link.href  = 'javascript:EsearchE.page=0;'; 
             _link.href += 'cExecute("$this.imap_functions.search_msg",openpage,"condition='+this.condition+'&sort_type='+this.sort_type+'&page=0&current_tab='+currentTab+'");'; 
+        } 
         } 
         else { 
@@ -319,6 +320,10 @@
 				var _link = document.createElement('A'); 
 				_link.innerHTML = ( _page + 1 ) + "&nbsp;&nbsp;"; 
+				if( this.value )
+				_link.href = 'javascript: EsearchE.quickSearchMail( false, '+i+', false, "'+currentTab+'" )';
+				else{
 				_link.href  = 'javascript:EsearchE.page='+i+';'; 
 				_link.href += 'cExecute("$this.imap_functions.search_msg",openpage,"condition='+this.condition+'&sort_type='+this.sort_type+'&page='+_page+'&current_tab='+currentTab+'");'; 
+			} 
 			} 
 			_link.innerHTML = "&nbsp;...&nbsp;"; 
@@ -339,6 +344,10 @@
 			if(this.page != (this.totalPages - 1)) { 
 				_link = document.createElement("A"); 
+				if( this.value )
+				_link.href = 'javascript: EsearchE.quickSearchMail( false, '+(this.totalPages-1)+', false, "'+currentTab+'" )';
+				else{
 				_link.href  = 'javascript:EsearchE.page='+(this.totalPages-1)+';'; 
 				_link.href += 'cExecute("$this.imap_functions.search_msg",openpage,"condition='+this.condition+'&sort_type='+this.sort_type+'&page='+(this.totalPages-1)+'&current_tab='+currentTab+'");'; 
+			} 
 			} 
         	else { 
@@ -360,4 +369,7 @@
 		var sort_type	= sortType;
 
+		if( this.value )
+		  return this.quickSearchMail( false, false, sortType, border_id );
+ 
 		var is_local = border_id.match('.*_local_.*');
 
@@ -383,5 +395,5 @@
     			if ( local_folders.length > 0 ){
                             expresso_local_messages.setSortType(sortType);
-                            gears = expresso_local_messages.search( expresso_local_messages.getFolders(), expresso_local_messages.getFilter() );
+                            gears = expresso_local_messages.search( local_folders, expresso_local_messages.getFilter() );
                         }
     		}
@@ -396,8 +408,5 @@
             if (gears.length > 0)
             {
-                this.localResults = gears.length;
                 allMsg['data_gears']                    = gears;
-            }else{
-                 this.localResults = 0;
             }
         	
@@ -434,5 +443,5 @@
 
 			if ( local_folders.length > 0 )
-				gears = expresso_local_messages.search( expresso_local_messages.getFolders(), expresso_local_messages.getFilter() );
+				gears = expresso_local_messages.search( local_folders, expresso_local_messages.getFilter() );
 
 			data['data_gears']	= gears;
@@ -473,4 +482,5 @@
 		{
 			var td = document.createElement("TD");
+                        add_className(td, 'td_msg');
 			if (j == 0)
 			{
@@ -480,6 +490,6 @@
 					chk_onclick = "changeBgColor(window.event,"+uid_msg+");";
 				else
-					chk_onclick = "changeBgColor(event,"+uid_msg+");";
-				var td1 = '<input type="checkbox" onclick="' + chk_onclick + '" id="check_box_message_'+tr.id+'"></input>';
+					chk_onclick = "changeBgColor(event,"+uid_msg+");";				//'search_' + numBox
+				var td1 = '<input type="checkbox" onclick="' + chk_onclick + '" id="' + border_id + '_check_box_message_'+uid_msg+'"></input>';
 
 			}
@@ -510,5 +520,5 @@
 			{
 				td.setAttribute("width", colSizes[1][3]);
-				td.id = "td_message_important_"+tr.id;
+				td.id = "td_message_important_"+uid_msg;
 				if (aux.flag.match("F"))
 				{
@@ -551,5 +561,5 @@
 			if( j == 6 )
 			{
-				if (aux.from.length > 29)
+				if ( aux.from !== null && aux.from.length > 29)
 					aux.from = aux.from.substr(0,29) + "...";
 
@@ -634,5 +644,5 @@
 
 	// Form resultado
-	searchE.prototype.mount_result = function( Data, sort_type, keep_border )
+	searchE.prototype.mount_result = function( Data, sort_type, keep_border, keep_filled, division )
 	{
 		var data = ( Data['data'] ) ? Data['data'] : Data['data_gears'];
@@ -648,17 +658,15 @@
 			sort_type = this.sort_type;
 
-                var tab = numBox;
-
 		if ( keep_border ) {
 			var border_id = currentTab;
 		}
 		else {
-			tab = count_borders() + 1;
+			numBox++;
 
 			if( Data['data'] )
-				var border_id = create_border(get_lang("Server Results"), "search_" + tab);
+				var border_id = create_border(get_lang("Server Results"), "search_" + numBox);
 
 			if( Data['data_gears'])
-				var border_id = create_border(get_lang("Local Results"), "search_local_msg" + tab);
+				var border_id = create_border(get_lang("Local Results"), "search_local_msg" + numBox);
 		}
 
@@ -667,5 +675,5 @@
 
         currentTab = border_id;
-        openTab.content_id[currentTab] = Element('content_id_search_' + tab);
+        openTab.content_id[currentTab] = Element('content_id_search_' + numBox);
         openTab.type[currentTab] = 1;
 		openTab.condition[currentTab] = this.condition;
@@ -673,10 +681,14 @@
 		if ( keep_border ) {
 			var content_search =  Element('content_id_' + border_id);
-			var div_scroll_result = Element("divScrollMain_"+tab);
+			var div_scroll_result = Element("divScrollMain_"+numBox);
+
 			content_search.removeChild(div_scroll_result);
+
+			if( !keep_filled )
+			    div_scroll_result = false;
 		}
 
 		var table = document.createElement("TABLE");
-			table.id    = "table_resultsearch_" + tab;
+			table.id    = "table_resultsearch_" + numBox;
 			table.frame = "void";
 			table.rules = "rows";
@@ -686,12 +698,13 @@
 
 		var tbody		= document.createElement("TBODY");
-			tbody.id	= "tbody_box_" + tab;
+			tbody.id	= "tbody_box_" + numBox;
 
 		for( var i=0; i < data.length; i++)
 		{
+			if(data[i] !== null){
 			var tr = EsearchE.make_tr_message(data[i],border_id,i);
-
             tbody.appendChild(tr);
 		}
+		}
 		
 		//global_search++; //Tabs from search must not have the same id on its tr's // use numBox instead of this!
@@ -700,10 +713,13 @@
 
 		var colgr_element = buildColGroup(1);
-		colgr_element.setAttribute("id","colgroup_main_"+tab);
+		colgr_element.setAttribute("id","colgroup_main_"+numBox);
 		table.appendChild(colgr_element);
 
 		var content_search =  Element('content_id_' + border_id);
+		
+		if( !div_scroll_result )
+		{
 		var div_scroll_result = document.createElement("DIV");
-		div_scroll_result.id = "divScrollMain_"+tab;
+		    div_scroll_result.id = "divScrollMain_"+numBox;
 		div_scroll_result.style.overflowY = "scroll";
 		div_scroll_result.style.overflowX = "hidden";
@@ -714,4 +730,12 @@
 			div_scroll_result.style.width	="100%";
 		}
+		}
+		if( division )
+		{
+		    var _div = document.createElement("div");
+		    _div.className = 'local-messages-search-warning';
+		    _div.innerHTML = division;
+		    div_scroll_result.appendChild(_div);
+		}
 
 		if(is_ie)
@@ -730,5 +754,5 @@
 			table_element.addEventListener("mousedown",startColResize,false);
 		}
-		table_element.setAttribute("id", "table_message_header_box_"+tab);
+		table_element.setAttribute("id", "table_message_header_box_"+numBox);
 		table_element.className = "table_message_header_box";
 		if (!is_ie)
@@ -772,5 +796,5 @@
 		
 		// Ordernar Pasta
-		if ( sort_type == 'SORTBOX')
+		if ( sort_type == 'SORTBOX' /*|| sort_type == 'SORTBOX_REVERSE'*/ )
 		{
 			if( Data['data'] )
@@ -801,5 +825,5 @@
 		td_element2 = createTDElement(1,6,"th_resizable","left");
 
-		if (sort_type == 'SORTFROM')
+		if (sort_type == 'SORTFROM' || sort_type == 'SORTWHO' /*|| sort_type == 'SORTWHO_REVERSE' || sort_type == 'SORTFROM_REVERSE'*/ )
 		{
 			if(Data['data'])
@@ -830,5 +854,5 @@
 		td_element3 = createTDElement(1,7,"th_resizable","left");
 		
-		if (sort_type == 'SORTSUBJECT')
+		if (sort_type == 'SORTSUBJECT' /*|| sort_type == 'SORTSUBJECT_REVERSE'*/)
 		{
 			if( Data['data'])
@@ -859,5 +883,5 @@
 		td_element4 = createTDElement(1,8,"th_resizable","center");
 		
-		if ( sort_type == 'SORTDATE' )
+		if ( sort_type == 'SORTDATE' /*|| sort_type == 'SORTDATE_REVERSE'*/ )
 		{
 			if( Data['data'] )
@@ -888,5 +912,5 @@
 		td_element5 = createTDElement(1,9,"th_resizable","center");
 		
-		if ( sort_type == 'SORTSIZE' )
+		if ( sort_type == 'SORTSIZE' /*|| sort_type == 'SORTSIZE_REVERSE'*/ )
 		{
 			if( Data['data'] )
@@ -928,8 +952,8 @@
 
 		var colgr_element = buildColGroup(1);
-		colgr_element.setAttribute("id","colgroup_head_"+tab);
+		colgr_element.setAttribute("id","colgroup_head_"+numBox);
 		table_element.appendChild(colgr_element);
 
-		if( parseInt( Data['gears_num_msgs'] ) > 0 && !Data['data_gears'])
+		if( parseInt( Data['gears_num_msgs'] ) > 0 && !keep_filled)
 		{
 			var _div_gears = document.createElement("div");
@@ -941,9 +965,13 @@
 		}		
 
-		var _divScroll = document.getElementById("divScrollHead_"+tab);
-
-		if(!_divScroll){
+		var _divScroll = document.getElementById("divScrollHead_"+numBox);
+		
+		if( _divScroll ){
+			content_search.removeChild(_divScroll);
+			_divScroll = false;
+		}
+
 			_divScroll = document.createElement("DIV");
-			_divScroll.id = "divScrollHead_"+tab;
+		_divScroll.id = "divScrollHead_"+numBox;
 			_divScroll.style.overflowY = "hidden";
 			_divScroll.style.overflowX = "hidden";
@@ -955,5 +983,5 @@
 			_divScroll.appendChild(table_element);
 			content_search.appendChild(_divScroll);
-		}
+
 		/*end of "put header"*/
 		if ( !expresso_offline )
@@ -1067,5 +1095,5 @@
 
 	// Search;
-	searchE.prototype.func_search = function(value)
+	searchE.prototype.func_search_complex = function()
 	{
 		var fields = "##";
@@ -1111,5 +1139,10 @@
                     }
             }
-
+			if ((trim(Element("since_date").value) != "") && (trim(Element("before_date").value) != "")){
+				if(!(validate_date_order(trim(Element("since_date").value), trim(Element("before_date").value)))){
+					alert(get_lang('Invalid date on field %1', get_lang('Before Date')));
+                    return false;
+				}
+			}
             if(trim(Element("on_date").value) != "")
             {
@@ -1171,9 +1204,4 @@
                 }
             }
-
-            if ( value )
-            {
-				fields = "##ALL " +  "<=>" +url_encode(value) + "##";
-			}
 
 		if(fields == "##")
@@ -1234,4 +1262,5 @@
             {
                 var allMsg 	= [3];
+        	var count  	= ( data['num_msgs'] ) ?  data['num_msgs'] : "0";
                 var tmp		= [];
 
@@ -1241,6 +1270,5 @@
                     tmp = expresso_local_messages.search( local_folders, fields );
                 }
-                var count = data['num_msgs'] ?  data['num_msgs'] : tmp.length > 0 ? tmp.length : "0";
-                 EsearchE.localResults = tmp.length;
+
                 if( data['num_msgs'] )
                 {
@@ -1254,5 +1282,5 @@
                 }
 
-                if( data['num_msgs'] == 0 && tmp.length < 0)
+        	if( ( data['num_msgs'] ) == 0 )
                 {
                     alert( get_lang("None result was found.") );
@@ -1260,13 +1288,16 @@
                 else
                 {
-                    if(tmp.length > 0 && !data['num_msgs'])
+            	if( (tmp.length > 0) && (!data['num_msgs']) ) 
                     {
-                        allMsg['data_gears'] = tmp;
+            		EsearchE.viewLocalMessage();
                     }
-                   
+            	else
+            	{
+					if(count > 0)
+						EsearchE.func_clean();
                      write_msg( count + " " + get_lang("results found") );
                     EsearchE.mount_result( allMsg, 'SORTDATE' );
                 }
-
+            }
             }
 
@@ -1280,7 +1311,134 @@
             else
                     cExecute( args, handler, params);
+	}
+	
+	searchE.prototype.func_search = function(value, page, sort, border_id)
+	{
+	  if( !value )
+	      this.func_search_complex();
+	  else
+	    this.quickSearchMail( value, page, sort, border_id );
+	}
+	
+	searchE.prototype.quickSearchMail = function(value, page, sort, border_id)
+	{
+		var local_folders = new Array();
+		var temp;
+		var not_found_corrent_folder = true;
+
+//		if( Element("check_all_msg").checked )
+//		{
+			this.all_mailboxes();
+			var nm_box = new Array;
+			for(var i=0; i < EsearchE.all_boxes.length; i++)
+			{
+				nm_box[i] = EsearchE.all_boxes[i]/* + fields*/;
+			}
+			if (preferences.use_local_messages == 1)
+			{
+				temp = expresso_local_messages.list_local_folders();
+				for (var x in temp)
+				{
+					local_folders.push(temp[x][0]);
+				}
+			}
+		this.sort		= sort || this.sort || "SORTDATE";
+		this.page		= isNaN(page) ? ( value ? 0 : this.page ) : page;
+		this.value		= value || this.value || false;
+		
+		if( !this.value )
+		    return alert( "Busca sem caracteres." );
+
+		var args		= "$this.imap_functions.quickSearchMail";
+		var params		= { page: this.page, sort: this.sort, search: this.value };
+
+		var selection1 = [], selection2 = [];
+
+		for( var i = 0; i < nm_box.length; i++ )
+		    if( nm_box[i] === current_folder )
+			continue;
+		    else if( /^user/.test(nm_box[i]) )
+			selection2[selection2.length] = nm_box[i];
+		    else
+			selection1[selection1.length] = nm_box[i];
+
+		 if( expresso_offline )
+			    handler('none');
+		 else
+		 {
+			    var url = [], labels = [];
+
+			    params['folder'] = current_folder;
+			    url[0] = args + "&" +  $.param( params );
+			    labels[0] = "mensagem na sua pasta atual";
+
+			    if(selection1.length)
+			    {
+					params['folder'] = selection1;
+					url[1] = args + "&" +  $.param( params );
+					labels[1] = "mensagens nas suas outras pastas";
+				}
+				if(selection2.length)
+			    {
+					params['folder'] = selection2;
+					url[2] = args + "&" +  $.param( params );
+					labels[2] = "mensagens nas suas pastas compartilhadas";
+				}
+			    var link = ' <a href="#" onclick="connector.cancelRequest(); clean_msg(); return false;">cancelar<a/>';
+
+			    write_msg( "pesquisando " + labels[0] + link, true );
+			    
+			    var keepFilled = false;
+
+			    var handler = function( data )
+			    {
+					data = $.parseJSON( Base64.decode(data) );
             
+					var allMsg 	= {
+						num_msgs: ( data['num_msgs'] || 0 ),
+						data: ( data['data'] || data['msgs'] || data )
+					};
+
+					// 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;
         }
-	// clean;
+
+					if( !allMsg['num_msgs'] && !url.length && not_found_corrent_folder){
+						clean_msg();
+						//alert( get_lang("None result was found.") );
+						return EsearchE.viewLocalMessage();
+					}
+
+					if( allMsg['num_msgs'] )
+						EsearchE.total = allMsg['num_msgs'] = Math.max( (EsearchE.total || 0), allMsg['num_msgs'] );	
+
+					EsearchE.mount_result( allMsg, EsearchE.sort, ( keepFilled || border_id === currentTab ), keepFilled, "Foram encontradas " + data['msgs'].length + " "+labels.shift()+"." );
+					
+					keepFilled = true;
+					
+					write_msg( "pesquisando " + labels[0] + link, true );
+
+					if( url.length )
+						cExecute( url.shift(), handler );
+					else
+						clean_msg();
+			    }
+
+			    cExecute( url.shift(), handler );
+		    }
+	}
+	
+// clean;
 	searchE.prototype.func_clean = function()
 	{
Index: trunk/expressoMail1_2/js/messages_controller.js
===================================================================
--- trunk/expressoMail1_2/js/messages_controller.js	(revision 4826)
+++ trunk/expressoMail1_2/js/messages_controller.js	(revision 5134)
@@ -13,5 +13,14 @@
 			var real_folder = folder.substr(6);		
 			var msgs = expresso_local_messages.get_local_range_msgs(real_folder,msg_range_begin,preferences.max_email_per_page,sort_box_type,sort_box_reverse,search_box_type,preferences.preview_msg_subject,preferences.preview_msg_tip);
-			eval('call_back(msgs)');
+			if(call_back) 
+				call_back(msgs);
+			else{
+				call_back = function(data)
+				{
+					alternate_border(0); 
+					draw_box(data, get_current_folder());
+				} 
+				call_back(msgs);
+			}
 			draw_tree_local_folders();
 		}else {
@@ -38,11 +47,17 @@
 		if (msgs_number == 'selected')
 			msgs_number = get_selected_messages();
-			
-		if (!this.is_local_folder(folder)) 
+		if (!this.is_local_folder(folder)){
 			delete_msgs(folder, msgs_number, border_ID);
-		else {
+		}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();
+				refresh(); 
+			}else{
 			expresso_local_messages.delete_msgs(msgs_number, border_ID);
 			draw_tree_local_folders();
-                         update_local_box();
+				refresh();
+			}
 		}
 	}
@@ -236,12 +251,18 @@
 		else 
 			if ((!this.is_local_folder(folder)) && (!this.is_local_folder(new_folder))) { //Move entre pastas locais...
+				if(new_folder_name == 'Spam'){
+					move_msgs_not_previus(folder, msgs_number, border_ID, new_folder, new_folder_name);
+				}else{
 				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))) {
+			}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 {
@@ -290,8 +311,17 @@
 	
 	messages_proxy.prototype.aux_interface_remove_mails = function(msgs_number,new_folder_name,border_ID,previous_msg) {
+		if(!msgs_number)
+			msgs_number = currentTab.toString().substr(0,currentTab.toString().indexOf("_r")); 
+			
+		if(msgs_number === ""){
+			write_msg(get_lang('No selected message.')); 
+			return;
+		}
+		
 		Element('chk_box_select_all_messages').checked = false;
 		mail_msg = Element("tbody_box");
 		msgs_number = msgs_number.split(",");
 		var msg_to_delete;
+		this.previous = 0;
 		for (var i=0; i<msgs_number.length; i++){
 			msg_to_delete = Element(msgs_number[i]);
@@ -299,4 +329,17 @@
 				if ( (msg_to_delete.style.backgroundColor != '') && (preferences.use_shortcuts == '1') )
 					select_msg('null', 'down');
+					
+				  if (parseInt(preferences.delete_and_show_previous_message) && msg_to_delete && currentTab.toString().indexOf("_r") > 0)
+				for(var ii=0; ii < mail_msg.rows.length; ii++){
+					if(mail_msg.rows[ii] === msg_to_delete){
+						if(ii == 0){
+							break;
+						}else{
+							this.previous = mail_msg.rows[(ii - 1)].attributes[0];
+							this.previous = parseInt(this.previous.value); 
+							break;
+						}
+					}
+				}
 				mail_msg.removeChild(msg_to_delete);
 			}
@@ -307,11 +350,15 @@
 			write_msg(get_lang("The messages were moved to folder ") + new_folder_name);
 
+		if (parseInt(preferences.delete_and_show_previous_message) && msg_to_delete && this.previous){
+			proxy_mensagens.get_msg(this.previous, folder, true, show_msg);
+		}else if(currentTab != 0){
 		if (border_ID != '' && border_ID != 'null'){
 				delete_border(border_ID,'false');
+			}else{
+				delete_border(currentTab,'false');
+			}
 		}
 		if(folder == get_current_folder())
 			Element('tot_m').innerHTML = parseInt(Element('tot_m').innerHTML) - msgs_number.length;			
-		refresh();		
-		
 	}
 
Index: trunk/expressoMail1_2/js/shortcut.js
===================================================================
--- trunk/expressoMail1_2/js/shortcut.js	(revision 4787)
+++ trunk/expressoMail1_2/js/shortcut.js	(revision 5134)
@@ -23,5 +23,5 @@
 		}
 		
-		var ele = opt.target
+		var ele = opt.target;
 		if(typeof opt.target == 'string') ele = document.getElementById(opt.target);
 		var ths = this;
@@ -266,4 +266,5 @@
 shortcut.add("E",function(){exec_msg_action('forward');},{'disable_in_input':true});
 shortcut.add("R",function(){exec_msg_action('reply');},{'disable_in_input':true});
+shortcut.add("T",function(){ var msg_id = get_msg_id(); if(msg_id) new_message("reply_to_all_with_history",msg_id);},{'disable_in_input':true});
 shortcut.add("O",function(){show_head_option();},{'disable_in_input':true});
 shortcut.add("M",function(){show_address_full();},{'disable_in_input':true});
@@ -362,6 +363,6 @@
 else
 {
-	shortcut.add("down",function(){select_msg('null', 'down');},{'type':'keypress', 'disable_in_input':false});
-	shortcut.add("up",function(){select_msg('null', 'up');},{'type':'keypress', 'disable_in_input':false});
+	shortcut.add("Up",function(){select_msg('null', 'up', true);},{'disable_in_input':false});
+	shortcut.add("Down",function(){select_msg('null', 'down', true);},{'disable_in_input':false});
 	
 	shortcut.add("Shift+down",function(){
Index: trunk/expressoMail1_2/js/mail_sync.js
===================================================================
--- trunk/expressoMail1_2/js/mail_sync.js	(revision 4988)
+++ trunk/expressoMail1_2/js/mail_sync.js	(revision 5134)
@@ -275,4 +275,6 @@
 			
 			var unseen = 0;
+			var flagged = 0; 
+	                var answered = 0;
 			var login = msg_info.login;
 			var original_id = msg_info.msg_number;
@@ -313,10 +315,7 @@
 			if(msg_info.Unseen=="U")
 				unseen = 1;
-
-                        //parse header
-                        var parser = new FlagsParser(msg_header);
-                        var flags = parser.parse();
-
-			this.dbGears.execute("insert into mail (mail,original_id,original_folder,header,timestamp,uid_usuario,unseen,id_folder,ffrom,subject,fto,cc,body,size,flagged,answered,recent) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[mail,original_id,original_folder,header,timestamp,login,unseen,id_folder,from,subject,to,cc,body,size,flags.getFlagged(),flags.getAnswered(),flags.getRecent()]);
+			this.dbGears.execute("insert into mail (mail,original_id,original_folder,header,timestamp,uid_usuario,unseen,id_folder,ffrom,subject,fto,cc,body,size,flagged,answered) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[mail,original_id,original_folder,header,timestamp,login,unseen,id_folder,from,subject,to,cc,body,size,flagged,answered]);
+
+
 			
 			//Preenche os anexos.
Index: trunk/expressoMail1_2/js/local_messages.js
===================================================================
--- trunk/expressoMail1_2/js/local_messages.js	(revision 4939)
+++ trunk/expressoMail1_2/js/local_messages.js	(revision 5134)
@@ -8,5 +8,4 @@
     this.store = null;
     this.filterSerch = "";
-    this.folders = [];
     this.sortType = "";
 }
@@ -122,17 +121,26 @@
 
 local_messages.prototype.installGears = function (){
-    temp = confirm(get_lang("To use local messages you have to install google gears. Would you like to install it now?"));
-    if (temp && typeof(preferences.googlegears_url) != 'undefined'){
-	if (is_ie)
-	    location.href = preferences.googlegears_url + "/gears.exe";
+    
+    var ua = navigator.userAgent.toLowerCase(); // captura o userAgent
+//     alert( parseFloat(ua.substring(ua.indexOf("firefox") + 8))  );
+    var is_ff = ( ua.indexOf("linux") != -1 || ua.indexOf("windows") != -1) &&
+		  ua.indexOf("mozilla") != -1 &&
+		( ua.indexOf("firefox") != -1 && parseFloat(ua.substring(ua.indexOf("firefox") + 8)) <= 3.6 );
+
+    if ( is_ff )
+      ext = "xpi";
+    else
+    if( typeof is_ie !== "undefined" && is_ie )
+      ext = "exe"
 	else
-	    location.href = preferences.googlegears_url + "/gears.xpi";
 	return false;
-    }
-    if (temp) {
-	location.href = "http://gears.google.com/?action=install&message="+
-	get_lang("To use local messages, install Google Gears")+"&return=" + document.location.href;
-    }
-    else return false;
+      
+    var confirmation = confirm(get_lang("To use local messages you have to install google gears. Would you like to install it now?"));
+
+    if ( confirmation && typeof(preferences.googlegears_url) != 'undefined' )
+	    location.href = preferences.googlegears_url + "/gears." + ext;
+
+
+    return false;
 }
 
@@ -171,7 +179,7 @@
     this.dbGears.execute('create table if not exists mail' +
 	' (mail blob,original_id int,original_folder text,header blob,timestamp int,uid_usuario int,unseen int,id_folder int,' +
-	' ffrom text, subject text, fto text, cc text, body text, size int,unique (original_id,original_folder,uid_usuario,id_folder))');
+	' ffrom text, subject text, fto text, cc text, body text, size int, visible bool default true, unique (original_id,original_folder,uid_usuario,id_folder))');
     this.dbGears.execute('create table if not exists anexo' +
-	' (id_mail int,nome_anexo text,url text,pid int)');
+	' (id_mail int,nome_anexo text,url text,pid int, contentType text)');
     this.dbGears.execute('create table if not exists folders_sync' +
 	' (id_folder text,folder_name text,uid_usuario int)');
@@ -184,7 +192,20 @@
     try {
 	this.dbGears.execute('alter table mail add column size int');
-    }catch(Exception) {
+    }
+    catch(Exception) {
 			
     }
+    try {
+	this.dbGears.execute('alter table mail add column visible bool default true');
+    }
+    catch(Exception) {
+    }
+    try {
+	this.dbGears.execute('alter table anexo add column contentType text');
+    }
+    catch(Exception) {
+    }
+
+
     var rs = this.dbGears.execute('select rowid,header from mail where size is null');
     while(rs.isValidRow()) {
@@ -246,4 +267,376 @@
 }
 	
+sync = { length: 0, fails: [], success: [], mails: {}, archived: [] };
+
+local_messages.prototype.insert_mails = function( msgs_info, folder, complete ){
+  
+    sync.length += msgs_info.length;
+    
+    write_msg( ( sync.archived.length ?  sync.archived.length + " mensagens ja arquivadas anteriormente, " : "" )
+	      + "Preparando o arquivamento de "+sync.length+ " mensagens...", true );
+
+    for( var i = 0; i < msgs_info.length; i++ )
+    {      
+	var original = url = DEFAULT_URL + "$this.exporteml.export_eml.raw&folder=" + msgs_info[i].msg_folder
+	+ "&msgs_to_export=" + msgs_info[i].msg_number;
+
+	msgs_info[i].url_export_file = url;
+	msgs_info[i].dest_folder = folder;
+
+	for( var ii = 0; ii < msgs_info[i].array_attach.length; ii++ )
+	{
+	    var anexo = msgs_info[i].array_attach[ii];
+
+	    anexo.url = "inc/get_archive.php?msgFolder=" + msgs_info[i].msg_folder + "&msgNumber=" + msgs_info[i].msg_number + "&indexPart=" + anexo.pid;
+
+	    msgs_info[i].array_attach[ii] = anexo;
+
+	    sync.mails[ anexo.url ] = url;
+
+	    url = anexo.url;
+	}
+
+	sync.mails[ original ] = parseInt( this.store_mail( msgs_info[i] ) );
+
+	this.capture( url, complete );
+    }
+    
+    write_msg( ( sync.archived.length ?  sync.archived.length + " mensagens ja arquivadas anteriormente, " : "" )
+	      + "arquivando " + sync.length + " mensagens...", true );
+}
+
+local_messages.prototype.checkArchived = function( msgsNumber, folder ){
+    
+    var levels = [], newtree = [];
+    
+    for( var i = 0; i < oldtree.length; i++ ){
+      
+      var element = oldtree[i];
+      
+      var current = element.parent, hierarchy = [];
+      
+      while( !levels[ current.id ] )
+      {
+	  levels[ current.id ] = [];
+	  
+	  hierarchy.push( current.id );
+
+	  for( var ii = 0; ii < hierarchy.length; ii++ )
+	    levels[ hierarchy[ii] ].push( 0 );
+
+	  current = current.parent;
+      }
+      
+      var parent = newtree;
+	  
+      for( var ii = 0; ii < levels[ element.parent ].length; ii++ )
+	    parent = parent[ levels[element.parent][ii] ];
+      
+      parent[ levels[ element.id ] = parent.length ] = element;
+    }
+}
+
+local_messages.prototype.checkArchived = function( msgsNumber, folder ){
+    
+    var isArray = false;
+  
+    if( msgsNumber.join ){
+	isArray = true;
+	msgsNumber = msgsNumber.join(",");
+    }
+
+    var archived = this.isArchived( msgsNumber, folder );
+    
+    if( !archived )
+	return( isArray ? msgsNumber.split(",") : msgsNumber );
+
+    msgsNumber = "," + msgsNumber;
+    
+    for( var i = 0; i < archived.length; i++ ){
+	sync.archived[ sync.archived.length ] = archived[i];
+	msgsNumber = msgsNumber.replace( "," + archived[i], "" );
+    }
+    
+    if( !msgsNumber )
+	this.cleanup();
+
+    return( isArray ? msgsNumber.substr(1).split(",") : 
+		    ( msgsNumber ? msgsNumber.substr(1) : msgsNumber ));
+}
+
+local_messages.prototype.isArchiving = function( msgsNumber, folder ){
+    return this.isArchived( msgsNumber, folder, true );
+}
+
+local_messages.prototype.isArchived = function( msgsNumber, folder, archiving ){
+  
+    if( msgsNumber.join )
+	msgsNumber = msgsNumber.join(",");
+    
+    folder = this.get_folder_id( folder );
+    
+    var archived = [];
+  
+  try{
+      this.init_local_messages();
+
+      var sql = "select original_id from mail where id_folder = ? and original_id IN ("+msgsNumber+")" + ( archiving ? " and visible = ?" : "" );
+      var params = archiving ? [ folder, false ]: [ folder ];
+      
+      if(folder != false){
+		for( var rs = this.dbGears.execute(sql, params); rs.isValidRow() || rs.close(); rs.next() ){
+			archived[ archived.length ] = rs.field(0);
+		}
+	}
+    }
+    catch( error ){
+		//Removido alert pois o mÃ©todo
+		//Ã© usado quando move mensagens entre pastas
+ //     alert( error );
+      return( false );
+    }
+    finally{
+      this.finalize();
+    }
+    
+    return( archived.length ? archived : false );
+}
+
+local_messages.prototype.capture = function( uri, complete ){
+
+    var _this = this;
+
+    var callback = function( url, ok ){
+
+	//check if its a chained attachment url. 
+	if( typeof sync.mails[url] === "string" )
+	{
+	    var content = _this.get_src( url );
+
+	    //if its successful, continue to capture the chain
+	    if( ok = ok || content )
+		return _this.capture( sync.mails[url], complete );
+
+	    //If it's not, don't need to continue loading the attachments. 
+	    //Just break the chain, search the last one chained (the message url) and finalize the process
+	    while( sync.mails[url].length )
+		    url = sync.mails[url];
+	}
+
+	sync[ ok ? 'success' : 'fails' ].push( sync.mails[url] );
+
+	sync.length--;
+
+	if( sync.length )
+	    return write_msg( ( sync.archived.length ?  sync.archived.length + " mensagens ja arquivadas anteriormente, " : "" )
+			      + "arquivando " + sync.length + " mensagens...", true );
+
+	clean_msg();
+	write_msg( ( sync.success.length ? "Foram arquivadas corretamente " + sync.success.length + " mensagens" : "Nenhuma mensagem arquivada" )
+		 + ( sync.archived.length ? ", " + sync.archived.length + " mensagens ja arquivadas anteriormente" : "" )
+		 + ( sync.fails.length ? ", " + sync.fails.length + " falharam" : "" ) + "." );
+
+	_this.update_mails( sync.success, sync.fails, complete );
+    }
+
+    try{
+	this.init_local_messages();
+	this.store.capture( uri, callback );
+    }
+    catch( error ){
+	console && console.log(error);
+    }
+    finally{
+	this.finalize();
+    }
+}
+
+local_messages.prototype.store_mail = function( msg_info ){
+
+    var id_mail = false;
+  
+    try {
+
+	    var id_folder = this.get_folder_id( msg_info.dest_folder );
+      
+	    this.init_local_messages();
+
+	    //This fields needs to be separeted to search.
+	    var msg_header = msg_info.header;
+	    var anexos = msg_info.array_attach;
+	    var login = msg_info.login;
+	    var original_id = msg_info.msg_number;
+	    var original_folder = msg_info.msg_folder;
+	    var subject = msg_info.subject;
+	    var body = msg_info.body;
+	    var timestamp = msg_info.timestamp;
+	    var size = msg_header.Size;
+	    var from = connector.serialize(msg_info.from);
+	    var to = connector.serialize(msg_info.toaddress2);
+	    var cc = connector.serialize(msg_info.cc);
+	    var unseen = (msg_info.Unseen == "U" )? 1 : 0;
+
+	    //If the mail was archieved in the same date the user received it, the date cames with the time.
+	    //here I solved it
+	    msg_header.udate = (String(msg_header.udate).indexOf(":")==-1)? msg_header.udate : msg_header.aux_date;
+	    // The importance attribute can be empty, and javascript consider as null causing nullpointer.
+	    msg_header.Importance = msg_header.Importance || "Normal";
+
+	    //do not duplicate this information
+	    msg_info.from = null;
+	    msg_info.subject = null;
+	    msg_info.body = null;
+	    msg_info.to = null;
+	    msg_info.cc = null;
+	    msg_header.Size=null;
+	    msg_header.aux_date = null;
+
+	    var mail = connector.serialize(msg_info);
+	    var header = connector.serialize(msg_header);
+
+	    //parse header
+	    var parser = new FlagsParser(msg_header);
+	    var flags = parser.parse();
+
+	    this.dbGears.execute("insert into mail (mail,original_id,original_folder,header,timestamp,uid_usuario,unseen,id_folder,ffrom,subject,fto,cc,body,size,answered,flagged,recent, visible) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
+						   [mail,original_id,original_folder,header,timestamp,login,unseen,id_folder,from,subject,to,cc,body,size,flags.getAnswered(),flags.getFlagged(),flags.getRecent(), false]);
+
+	    id_mail = this.dbGears.lastInsertRowId;
+
+	    //insert_mail already close and open gears.
+	    for (var i = 0; i < anexos.length; i++)
+		this.dbGears.execute("insert into anexo (id_mail,nome_anexo,url,pid) values (?,?,?,?)", 
+							[id_mail, anexos[i]['name'],anexos[i]['url'],anexos[i]['pid']]);
+    }
+    catch (error) {
+	return( false );
+    }
+    finally{
+	this.finalize();
+    }
+
+    return( id_mail );
+}
+
+local_messages.prototype.get_folder_id = function( folder ){
+
+    var id_folder;
+    
+    folder = ( folder && folder != "local_root" )? folder.substr(6) : "Inbox";
+  
+    try
+    {
+	this.init_local_messages();
+
+	var rs = this.dbGears.execute("select rowid from folder where folder=? and uid_usuario=?",[folder,account_id]);
+
+	if(rs.isValidRow())
+	      id_folder = rs.field(0);
+	else {
+	      this.dbGears.execute("insert into folder (folder,uid_usuario) values (?,?)",["Inbox",account_id]);
+	      id_folder = this.dbGears.lastInsertRowId;
+	}
+	
+	rs.close();
+    }
+    catch( error ){
+	return( false );
+    }
+    finally{
+	this.finalize();
+    }
+
+    return( id_folder );
+}
+
+local_messages.prototype.update_mails = function( success, fails, callback ){
+    try
+    {		
+      this.init_local_messages();
+      
+      this.dbGears.execute('update mail set visible=? where rowid IN (' + success.join(",") + ')',[ true ]);
+
+      var sql = 'select url, contentType from anexo where id_mail = ' +success;
+
+      for( var rs = this.dbGears.execute(sql); rs.isValidRow() || rs.close(); rs.next() )
+      {
+		var url = rs.field(0), contentType = rs.field(1);
+		var blob = this.store.getAsBlob( url );
+	  
+		this.store.captureBlob( blob, url + "&image=thumbnail", "image/jpeg" );
+		this.store.captureBlob( blob, url + "&image=true", "image/jpeg" );
+      } 
+    }
+    catch (error) {
+		status = false;
+    }
+    finally{
+		this.finalize();
+    }
+    
+    if( callback )
+		callback( success, fails );
+		this.cleanup();
+    
+    return( status );
+}
+
+local_messages.prototype.cleanup = function(){
+
+  try{
+    this.init_local_messages();
+    
+    this.dbGears.execute('delete from mail where visible=?', [ false ]);
+    
+    sync.success = [], sync.fails = [], sync.archived = [], sync.mails = {};
+  }
+  catch(error){
+    return( false );
+  }
+  finally{
+    this.finalize();
+  }
+  
+  return( true );
+}
+
+
+
+local_messages.prototype.select_mail = function( columns, rowIds ){
+  
+    try
+    {
+	this.init_local_messages();
+	
+	if( rowIds.join )
+	    rowIds = rowIds.join( "," ); 
+	
+	if( columns.join )
+	    columns = columns.join( "," );
+
+	var sql = 'select '+columns+' from mail where rowid IN (' + rowIds + ')';
+	
+	var result = [];
+
+	for( var i = 0, rs = this.dbGears.execute(sql); rs.isValidRow() || rs.close() || delete ii; rs.next( i++ ) )
+
+	    for( ii = 0, result[i] = {}; ii < rs.fieldCount(); ii++ )
+
+		  result[i][ rs.fieldName( ii ) ] = rs.field( ii );
+
+    }
+    catch (error) {
+	status = false;
+    }
+    finally{
+	this.finalize();
+    }
+  
+    if( result.length === 1 )
+	result = result[0];
+    
+    return( result );
+}
+
 local_messages.prototype.insert_mail = function(msg_info,msg_header,anexos,folder) {
     try {
@@ -391,12 +784,12 @@
 	    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 er_imagens = new RegExp("\\.\\/get_archive.php\\?msgFolder=[\\w/]+\\&msgNumber=[0-9]+\\&indexPart="+(anexos[i]['pid']-1));
 		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']);
+		    er_imagens = new RegExp("\\.\\/inc\\/get_archive.php\\?&&msgFolder=[\\w/%]+\\msgNumber=[0-9]+\\&indexPart=0."+(anexos[i]['pid']-1)+"&image=thumbnail");
 		    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']);
+		    er_imagens = new RegExp("\\.\\/inc\\/get_archive.php\\?&msgFolder=[\\w/%]+\\msgNumber=[0-9]+\\&indexPart=0."+(anexos[i]['pid']-1)+"&image=true");
 		    Result_imagens = er_imagens.exec(thumbs[i]);
 		    thumbs[i] = thumbs[i].replace(Result_imagens,anexos[i]['url']);
@@ -475,5 +868,5 @@
     'ltrim(ltrim(substr(UPPER(ffrom),21,length(ffrom)),\':\'),\'"\') ' +
     'end ' +
-    'end as order_from,mail.subject from mail inner join folder on mail.id_folder=folder.rowid where mail.uid_usuario=? and folder.folder=? ' +
+    'end as order_from,mail.subject from mail inner join folder on mail.id_folder=folder.rowid where mail.uid_usuario=? and folder.folder=? and mail.visible=? ' +
     mail_filter + ' order by ';
 		
@@ -496,8 +889,8 @@
 
 
-    var rs = this.dbGears.execute(sql,['%'+Element("user_email").value+'%',account_id,folder,msg_range_begin,emails_per_page]);
+    var rs = this.dbGears.execute(sql,['%'+Element("user_email").value+'%',account_id,folder,true,msg_range_begin,emails_per_page]);
     var cont = 0;
 		
-    var rs3 = this.dbGears.execute('select count(*) from mail inner join folder on mail.id_folder=folder.rowid where mail.uid_usuario=? and folder.folder=?'+mail_filter,[account_id,folder]);
+    var rs3 = this.dbGears.execute('select count(*) from mail inner join folder on mail.id_folder=folder.rowid where mail.uid_usuario=? and folder.folder=? and mail.visible=?'+mail_filter,[account_id,folder,true]);
 				
     while (rs.isValidRow()) {
@@ -528,16 +921,6 @@
 
 	retorno[cont]['msg_sample'] = new Array();
-
-	if( (preview_msg_subject == 0) && (preview_msg_tip == 0) )
-	{
 	    retorno[cont]['msg_sample']['body'] = "";
-	}
-	else
-	{
-	    msg_body += ">";
-	    msg_body=this.strip_tags(msg_body);
-	    msg_body=msg_body.replace(/\&nbsp;/ig," ");
-	    retorno[cont]['msg_sample']['body'] = " - " + msg_body.substr(2,msg_body.length-1);
-	}
+
 
 	cont++;
@@ -562,5 +945,5 @@
     var retorno;
     var rs = this.dbGears.execute("select url from anexo where id_mail="+msg_number+" and pid = '"+pid+"'");
-    retorno = rs.field(0)
+    retorno = rs.field(0);
     this.finalize();
 		
@@ -576,10 +959,13 @@
 
 local_messages.prototype.finalize = function() {
+    if(this.dbGears)
     this.dbGears.close();
     this.dbGears = null;
 }
 
-local_messages.prototype.delete_msgs = function(msgs_number,border_ID) {
-    this.init_local_messages();
+local_messages.prototype.remove_msgs = function(msgs_number)
+{
+    this.init_local_messages();
+	 
     var rs = this.dbGears.execute("select url from anexo where id_mail in ("+msgs_number+")");
     while(rs.isValidRow()) {
@@ -590,11 +976,19 @@
     this.dbGears.execute("delete from mail where rowid in ("+msgs_number+")");
     this.finalize();
-    if (msgs_number.length == 1)
-	write_msg(get_lang("The message was deleted."));
-    else
-	write_msg(get_lang("The messages were deleted."));
-		
-    mail_msg = Element("tbody_box");
-
+}
+		
+local_messages.prototype.delete_msgs = function(msgs_number,border_ID) {
+
+	if(!msgs_number)
+		msgs_number = currentTab.toString().substr(0,currentTab.toString().indexOf("_r")); 
+    
+	if(msgs_number === ""){
+		 write_msg(get_lang('No selected message.')); 
+		 return;
+	}
+
+    this.remove_msgs( msgs_number );
+	
+    mail_msg = Element("tbody_box");	
     try {
 	msgs_exploded = msgs_number.split(",");
@@ -603,4 +997,5 @@
 	msgs_exploded[0] = msgs_number;
     }
+	this.previous = 0;
     var msg_to_delete;
     for (var i=0; i<msgs_exploded.length; i++){
@@ -609,12 +1004,33 @@
 	    if ( (msg_to_delete.style.backgroundColor != '') && (preferences.use_shortcuts == '1') )
 		select_msg('null', 'down');
+	    if (parseInt(preferences.delete_and_show_previous_message) && msg_to_delete && currentTab.toString().indexOf("_r") > 0)
+		for(var ii=0; ii < mail_msg.rows.length; ii++){
+			if(mail_msg.rows[ii] === msg_to_delete){
+				if(ii == 0){
+					break;
+				}else{
+					this.previous = mail_msg.rows[(ii - 1)].attributes[0];
+					this.previous = parseInt(this.previous.value); 
+					break;
+				}
+			}
+		}
+		
 	    mail_msg.removeChild(msg_to_delete);
-	    decrement_folder_unseen();
-	}
-    }
+		Element('tot_m').innerHTML = parseInt(Element('tot_m').innerHTML) - 1;
+	}
+	}
+	if (msgs_exploded.length == 1){
+	write_msg(get_lang("The message was deleted."));
+    }
+    else
+	write_msg(get_lang("The messages were deleted."));
     Element('chk_box_select_all_messages').checked = false;
-    if (border_ID != 'null')
-	delete_border(border_ID,'false');
-		
+		
+	 if (parseInt(preferences.delete_and_show_previous_message) && msg_to_delete && this.previous){
+		proxy_mensagens.get_msg(this.previous, folder, true, show_msg);
+	}else if(currentTab != 0){
+		delete_border(currentTab,'false');
+	}
 }
 	
@@ -635,32 +1051,19 @@
     this.init_local_messages();
 	var no_errors = true;
-	var rowids_to_set; // rows ids
-    var msgs_to_set; // messages ids
+    var msgs_to_set;
 	var one_message = false;
     if (msgs_number == 'get_selected_messages') {
-		msgs_to_set = get_selected_messages();
-		rowids_to_set = msgs_to_set.split(",");
-		msgs_to_set = msgs_to_set.replace(/_s[^,]*/g,"").split(",");
-    }
-    else {
-	if(isNaN(parseInt(msgs_number))){	//message(s) sent to function
-            rowids_to_set = msgs_number.split(",");
-            msgs_to_set = msgs_number.replace(/_s[^,]*/g,"").split(",");
-            if (msgs_to_set.length==1) {
-                            //Just one message
-                one_message = true;
-            }
-        }else{
-            rowids_to_set = new Array();
-            msgs_to_set = new Array()
-            msgs_to_set[0] = parseInt(msgs_number);
-            rowids_to_set[0] = parseInt(msgs_number);
+		var msgs_to_set = get_selected_messages();
+		msgs_to_set= msgs_to_set.split(",");
+    }
+    else { //Just one message
             one_message = true;
-        }
+		msgs_to_set = new Array();
+		msgs_to_set[0] = msgs_number;
     }
     for (var i in msgs_to_set) {
 			
 	var matches = '';//Messages comming from other tabs.
-	if(matches === this.parse_id_mail(msgs_to_set[i])) {
+	if(matches = this.parse_id_mail(msgs_to_set[i])) {
 	    msgs_to_set[i] = matches[1];
 	}
@@ -674,5 +1077,5 @@
 	switch(flag) {
 	    case "unseen":
-			set_msg_as_unread(rowids_to_set[i]);
+			set_msg_as_unread(msgs_to_set[i]);
 			header["Unseen"] = "U";
 			mail["Unseen"] = "U";
@@ -681,5 +1084,5 @@
 			break;
 	    case "flagged":
-			set_msg_as_flagged(rowids_to_set[i]);
+			set_msg_as_flagged(msgs_to_set[i]);
 			header["Flagged"] = "F";
 			mail["Flagged"] = "F";
@@ -691,5 +1094,5 @@
 				no_errors = false;
 			else {
-			    set_msg_as_unflagged(rowids_to_set[i]);
+			    set_msg_as_unflagged(msgs_to_set[i]);
 			    header["Flagged"] = "N";
 				mail["Flagged"] = "N";
@@ -702,5 +1105,5 @@
 			mail["Unseen"] = "N";
 			mail["header"]["Unseen"] = "N";
-			set_msg_as_read(rowids_to_set[i],true);
+			set_msg_as_read(msgs_to_set[i],true);
 			unseen = 0;
 			break;
@@ -729,6 +1132,6 @@
 	rs.close();
 			
-	if(Element("check_box_message_" + rowids_to_set[i]))
-	    Element("check_box_message_" + rowids_to_set[i]).checked = false;
+	if(Element("check_box_message_" + msgs_to_set[i]))
+	    Element("check_box_message_" + msgs_to_set[i]).checked = false;
         var smail=connector.serialize(mail);
         smail =smail.replace(/([^'])'([^'])('?)/g,"$1''$2$3$3");
@@ -815,5 +1218,5 @@
 	    temp[2] = 0;
 
-	if(sentfolder ==  preferences.save_in_folder.replace("INBOX/","") || preferences.save_in_folder.replace("INBOX/","") == trashfolder || preferences.save_in_folder.replace("INBOX/","") == draftsfolder)
+	if(sentfolder ==  preferences.save_in_folder.replace("INBOX" + cyrus_delimiter,"") || preferences.save_in_folder.replace("INBOX" + cyrus_delimiter,"") == trashfolder || preferences.save_in_folder.replace("INBOX" + cyrus_delimiter,"") == draftsfolder)
 	    achouSentConf= true;
 
@@ -835,5 +1238,5 @@
 		achouDrafts = true;
 		break;
-	    case preferences.save_in_folder.replace("INBOX/",""):
+	    case preferences.save_in_folder.replace("INBOX" + cyrus_delimiter,""):
 		retorno_defaults[2] = temp;
 		achouSentConf = true;
@@ -862,5 +1265,5 @@
 	    this.create_folder(draftsfolder);
 	if(!achouSentConf)
-	    this.create_folder(preferences.save_in_folder.replace("INBOX/",""));
+	    this.create_folder(preferences.save_in_folder.replace("INBOX" + cyrus_delimiter,""));
 	return this.list_local_folders();
     }
@@ -930,4 +1333,8 @@
 
 local_messages.prototype.move_messages = function(new_folder,msgs_number) {
+    
+	if(!msgs_number)
+		msgs_number = currentTab.toString().substr(0,currentTab.toString().indexOf("_r")); 
+	
     this.init_local_messages();
     var rs = this.dbGears.execute("select rowid from folder where folder=? and uid_usuario=?",[new_folder,account_id]);
@@ -938,14 +1345,4 @@
 }
 
-local_messages.prototype.setFolders = function(sFolders)
-{
-    this.folders = sFolders;
-}
-
-local_messages.prototype.getFolders = function()
-{
-    return this.folders;
-}
-
 local_messages.prototype.setFilter = function(sFilter)
 {
@@ -972,7 +1369,5 @@
 local_messages.prototype.search = function(folders,sFilter) {
     this.init_local_messages();
-    //sFilter = unescape(sFilter);
     this.setFilter(sFilter);
-    this.setFolders(folders);
     var filters = sFilter.replace(/^##|##$/g,"").split('##');
     var friendly_filters = new Array();
@@ -1017,5 +1412,5 @@
 	}
     }
-    var sql = "select mail.header,folder.folder,mail.rowid,size from mail inner join folder on mail.id_folder=folder.rowid where mail.uid_usuario="+account_id + " and folder.folder in (";
+    var sql = "select mail.header,folder.folder,mail.rowid,size from mail inner join folder on mail.id_folder=folder.rowid where visible=? and mail.uid_usuario="+account_id + " and folder.folder in (";
     for(var fnum in folders) {
 	sql+="'"+folders[fnum]+"'";
@@ -1069,5 +1464,5 @@
     sql += this.getSortType().match('^.*_REVERSE$') ? ' asc' : ' desc';
 
-    var rs = this.dbGears.execute(sql);
+    var rs = this.dbGears.execute(sql,[true]);
     var retorno = [];
     var numRec = 0;
@@ -1226,5 +1621,5 @@
     }
 
-    AJAX.open('get', url, false);
+    AJAX.open('get', encodeURI(url), false);
     AJAX.send(null);
     return AJAX.responseText;
@@ -1233,60 +1628,57 @@
 //Por Bruno Costa(bruno.vieira-costa@serpro.gov.br - Dessarquiva msgs locais pegando o codigo fonte das mesmas e mandando via POST para o servidor
 //para que elas sejam inseridas no imap pela funÃ§Ã£o  imap_functions.unarchive_mail.
-local_messages.prototype.unarchive_msgs = function (folder,new_folder,msgs_number){
-
-    if(!new_folder)
-	new_folder='INBOX';
-    this.init_local_messages();
-    // alert(folder+new_folder+msgs_number);
-    var handler_unarchive = function(data)
-    {
-		if(data.error == '')
-		    write_msg(get_lang('All messages are successfully unarchived'));
-		else
-		    alert(data.error);
-    }
-
-	if(currentTab.toString().indexOf("_r") != -1){
+    local_messages.prototype.unarchive_msgs = function (folder,new_folder,msgs_number){
+
+    this.init_local_messages();
+
+	// se a aba estiver aberta e selecionada, apenas a msg da aba Ã© movida
+	if(currentTab.toString().indexOf("_r") != -1)
             msgs_number = currentTab.toString().substr(0,currentTab.toString().indexOf("_r"));
-    }
-	
-    if(msgs_number =='selected' || !msgs_number)
-    {
-		msgs_number = get_selected_messages()
-		if (!msgs_number){
-		    write_msg(get_lang('No selected message.'));
-		    return;
-		}
-		var rs = this.dbGears.execute("select mail,timestamp from mail where rowid in ("+msgs_number+")");
-		var source="";
-		var flags="";
-                var timestamp="";
+	
+        if( msgs_number =='selected' || !msgs_number )
+	    msgs_number = get_selected_messages();
+
+	if( !msgs_number )
+	    return write_msg(get_lang('No selected message.'));
+
+	document.getElementById("overlay").style.visibility = "";
+
+	var rs = this.dbGears.execute("select mail,timestamp from mail where rowid in (" + msgs_number + ")");
+
+	var source = [], flags = [], timestamp = [];
 		
 		while(rs.isValidRow()) {
-			mail=connector.unserialize(rs.field(0));
-			mail.msg_source?source_tmp = escape(mail.msg_source):source_tmp = escape(this.get_src(mail.url_export_file));
-			flags+="#@#@#@"+mail["Answered"]+":"+mail["Draft"]+":"+mail["Flagged"]+":"+mail["Unseen"];
-                        source+="#@#@#@"+source_tmp;
-			timestamp+="#@#@#@"+rs.field(1);
+
+	    var mail = connector.unserialize(rs.field(0));
+
+	    flags.push( mail["Answered"]+":"+mail["Draft"]+":"+mail["Flagged"]+":"+mail["Unseen"] );
+	    source.push( escape( mail.msg_source || this.get_src( mail.url_export_file ) ) );
+	    timestamp.push( rs.field(1) );
+
 			rs.next();
 		}
+
 		rs.close();
 		this.finalize();
-    }
-    else
-    {
-		var rs = this.dbGears.execute("select mail,timestamp from mail where rowid="+msgs_number);
-		mail=connector.unserialize(rs.field(0));
-		var source ="";
-
-		mail.msg_source?source = escape(mail.msg_source):source = escape(this.get_src(mail.url_export_file));
-		flags = mail["Answered"]+":"+mail["Draft"]+":"+mail["Flagged"]+":"+mail["Unseen"];
-		timestamp=rs.field(1);
-		rs.close();
-		this.finalize();
-    }
-    params="&folder="+new_folder+"&source="+source+"&timestamp="+timestamp+"&flags="+flags;
-    cExecute ("$this.imap_functions.unarchive_mail&", handler_unarchive, params);
-}
+
+	write_msg( "Desarquivando " + source.length + " mensagens... ", true );
+
+	var sep = "#@#@#@";
+
+	var params = "&folder=" + ( new_folder || 'INBOX' ) +
+		     "&source=" + source.join(sep) +
+		     "&timestamp=" + timestamp.join(sep) +
+		     "&flags=" + flags.join(sep);
+
+	cExecute ("$this.imap_functions.unarchive_mail&", function(data){
+
+	    clean_msg();
+	    document.getElementById("overlay").style.visibility = "hidden";
+	    write_msg( get_lang( data.error || 'All messages are successfully unarchived' ) );
+
+        }, params);
+        
+        update_menu(); 
+    }
 
 local_messages.prototype.get_msg_date = function (original_id, is_local){
@@ -1309,9 +1701,4 @@
 	rs = this.dbGears.execute("select mail from mail where original_id="+original_id);
     }
-        if(!rs.field(0)){
-          ret=null;
-    }
-    else
-        {
     var tmp = connector.unserialize(rs.field(0));
     var ret = new Array();
@@ -1320,5 +1707,5 @@
     ret.msg_day = tmp.msg_day;
     ret.msg_hour = tmp.msg_day;
-        }
+
     rs.close();
     this.finalize();
@@ -1356,9 +1743,17 @@
     var flag = true;
     var handler_local_mesgs_to_export = function(data){
+			var filename = 'mensagens.zip';
+
+			if (data.match(/\.eml$/gi)) {
+				fn_regex = /[^\/]*\.eml$/i;
+				filename = fn_regex.exec(data);
+			}
+
         document.getElementById('lertOverlay').style.display='none';
         document.getElementById('lertContainer').style.display='none';
         document.getElementById('lertContainer').innerHTML = '';
         flag = false;
-	download_attachments(null, null, data, null,null,'mensagens.zip');
+
+			download_attachments(null, null, data, null, null, filename);
     }
 
@@ -1510,4 +1905,15 @@
 }
 	
+local_messages.prototype.as_trash = function(){//verifica se o usuario tem a pasta lixeira no arquivamento local
+	this.init_local_messages();
+    var rs = this.dbGears.execute("select folder from folder where uid_usuario="+account_id+" and folder = \"Trash\"");
+	var check = rs.isValidRow();
+	this.finalize();
+    if(check)
+		return true;
+	else
+		return false;
+}
+
 local_messages.prototype.get_folders_to_sync = function() {//Precisa ter visibilidade ao array de linguagens.
     this.init_local_messages();
@@ -1517,5 +1923,5 @@
 	temp = new Array();
 	temp[0] = rs.field(0);
-	if(temp[0]=='INBOX/Drafts' ||temp[0]=='INBOX/Trash' || temp[0]=='INBOX/Sent') {
+	if(temp[0]=='INBOX' + cyrus_delimiter + 'Drafts' ||temp[0]=='INBOX' + cyrus_delimiter + 'Trash' || temp[0]=='INBOX' + cyrus_delimiter + 'Sent') {
 	    temp[1] = array_lang[rs.field(1).toLowerCase()];
 	}
@@ -1533,10 +1939,6 @@
 local_messages.prototype.install_offline = function(urlOffline,urlIcone,uid_usuario,login,pass,redirect) {
     if (!window.google || !google.gears) {
-	temp = confirm(document.getElementById('lang_gears_redirect').value);
-	if (temp) {
 	    expresso_local_messages.installGears();
-	}
 	return;
-
     }
 		
Index: trunk/expressoMail1_2/js/TreeS.js
===================================================================
--- trunk/expressoMail1_2/js/TreeS.js	(revision 4772)
+++ trunk/expressoMail1_2/js/TreeS.js	(revision 5134)
@@ -18,6 +18,6 @@
 		tree.style.position   = "absolute";
 		tree.style.left 	  = "0px";
+		tree.style.width 	  = "0px";
 		tree.style.top 		  = "0px";
-		tree.style.width 	  = "0px";
 		tree.style.height 	  = "0px";
 		tree.id				  = "window_tree";
@@ -32,9 +32,9 @@
 		div_buttons.style.left = "440px";
 		div_buttons.style.top = "20px"		
-		div_buttons.style.width = "130px";
+		div_buttons.style.width = "10px";
 		div_buttons.style.height = "214px";
 		div_buttons.innerHTML = "<table border='0' cellpading='0' cellspacing='0'>"+
 							    "<tr>"+
-							    "<td><input type='button' value='"+get_lang('New folder')+"' onclick='proxy_mensagens.proxy_create_folder()'></td>"+
+							    "<td><input type='button' value='"+get_lang('New folder')+"' onclick='proxy_mensagens.proxy_create_folder()' "+ (is_ie ? "style=\"width:85px\"": "") +"></td>"+
 							    "</tr>"+
 							    "<tr>"+
@@ -42,9 +42,9 @@
 							    "</tr>"+
 							    "<tr>"+
-							    "<td><input type='button' value='"+get_lang('Rename folder')+"' onclick='proxy_mensagens.proxy_rename_folder()'></td>"+
+							    "<td><input type='button' value='"+get_lang('Rename folder')+"' onclick='proxy_mensagens.proxy_rename_folder()' "+ (is_ie ? "style=\"width:108px\"": "") +"></td>"+
 							    "</tr>"+
 							    "<tr>"+
                                                             //Por Bruno Costa(bruno.vieira-costa@serpro.gov.br - Chama o proxy_mensagens para que uma pasta local também possa ser exportada
-                                                            "<td><input type='button' value='"+get_lang('Export messages')+"' onclick='proxy_mensagens.proxy_export_all_msg()'></td>"+
+                                                            "<td><input type='button' value='"+get_lang('Export messages')+"' onclick='proxy_mensagens.proxy_export_all_msg()' "+ (is_ie ? "style=\"width:130px\"": "") +"></td>"+
 							    "</tr>"+
 							    "<tr><td><br><br><br><br><br></td></tr>"+
@@ -176,9 +176,12 @@
 				if(data[i].folder_parent != 'root') {
 					var node_parent = folders_tree.getNodeById(data[i].folder_parent);
+					if(typeof node_parent != 'undefined'){
 					node_parent.plusSign = true;
 					folders_tree.alter(node_parent);
-				}
-				
+				
+					}
+				}
 				folders_tree.add(nn,data[i].folder_parent);
+				
 			}
 		}
Index: trunk/expressoMail1_2/js/globals.js
===================================================================
--- trunk/expressoMail1_2/js/globals.js	(revision 4802)
+++ trunk/expressoMail1_2/js/globals.js	(revision 5134)
@@ -46,3 +46,3 @@
 var denyFileExtensions = new Array('exe','com','reg','chm','cnf','hta','ins','jse','job','lnk','pif','src','scf','sct','shb','vbe','vbs','wsc','wsf','wsh','cer','its','mau','','mda','mar','mdz','prf','pst');
 var mobile_device = false;
-
+var previous = 0;
Index: trunk/expressoMail1_2/js/filter.js
===================================================================
--- trunk/expressoMail1_2/js/filter.js	(revision 4855)
+++ trunk/expressoMail1_2/js/filter.js	(revision 5134)
@@ -51,7 +51,6 @@
 			var handler_sieve = function(data)
 			{
-				if(data.toString().indexOf('Error:') == 0) 
-				{
-
+				if (data.toString().indexOf('Error:') == 0) 
+				{
 					_this.criticalError = true;
 					alert(get_lang('The filters service is out of service, try again later...'));
@@ -69,15 +68,12 @@
 					}
 				}
-                                if(typeof(data.vacation[0]) == 'undefined'){
-                                    _this.out_officeR = "";
-                                }
-                                else
-                                    _this.out_officeR = url_decode_s(data.vacation[0]);
+				_this.out_officeR = data.vacation[0];
+				_this.out_officeR = _this.out_officeR ? trim(_this.out_officeR.toString().replace("\n","")) : "";
+				if(data.mode.length > 0){_this.mode_in = data.mode[0];}
 				}
 				catch(e){
 					_this.criticalError = true;
-					alert(get_lang('==> The filters service is out of service, try again later...'));
-				}
-				if(data.mode.length > 0){_this.mode_in = data.mode[0];}
+					alert(get_lang('The filters service is out of service, try again later...'));
+				}
 				if (typeof(posHandler) == 'function')  
 					posHandler(param);  
@@ -93,4 +89,5 @@
 		Element('form_body').innerHTML = "";
 		Element('form_buttons').style.display = '';
+		Element('Edit_form_buttons').style.display = 'none';
 		filters.mount_list();
 		this.ac_form = "";		
@@ -109,4 +106,6 @@
 		Element('form_body').innerHTML = "";
 		Element('form_body').innerHTML = this.forms_();
+		Element('Edit_form_buttons').style.display = '';
+		Element('form_buttons').style.display = 'none';
 		this.ind = pos;		
 		
@@ -221,4 +220,7 @@
 			var mark_values = this.values[fields[8]].split(",");
 			for(var i=0; i < mark_values.length; i++){
+				if( mark_values[i] == "checkBox1" || mark_values[i] == "checkBox2"){
+					document.getElementById(mark_values[i]).checked = true;
+				}
 				if( mark_values[i] == "checkBox2"){
 					document.getElementById(mark_values[i]).checked = true;
@@ -313,4 +315,7 @@
 			 var form = "";
 				 form = "<div id='div_rule' style='display:none'><table id='table_rule' border='0' cellpading='0' cellspacing='0' width='100%'>"+
+						"<tr><td colspan='2'><input type='checkBox' id='checkBox1' name='checkb'>"+get_lang('Also check message against next rule') + "</td></tr>"+
+						//"<tr><td colspan='2'><input type='checkBox' id='checkBox2' onclick='filter.disable_radio3();' name='checkb'>"+get_lang('Keep a copy of the message at your Inbox')+ "</td><tr>"+
+						"<tr><td colspan='2'><hr size='1' width='100%'></td></tr><tr>"+
 					 "<tr><td colspan='2'><b>"+get_lang("Criteria")+":</b></td></tr><tr>"+
 					 "<td rowspan='4' width='20%'>"+get_lang('Find items')+":<br><select id='select_rules' name='select_rules'>"+
@@ -338,12 +343,12 @@
 						//"<tr><td colspan='3'><br>"+get_lang('Subject')+".: <input type='text' id='field7' name='field7' size='35' maxlength='200'/></td></tr>"+
 						"<tr><td colspan='3'><br>"+get_lang('With the following message')+".:</td>"+
-	 					"</tr><tr><td colspan='3'><textarea id='field8' onkeypress='return charCounter(this);' rows='8' cols='50'></textarea></td></tr></table></div>" +
+	 					"</tr><tr><td colspan='3'><textarea id='field8' rows='8' cols='50'></textarea></td></tr></table></div>" +
 						"<div id='div_voipFilter' style='display:none'>" +
 						"<br/><table id='table_voipFilter'>" +
 						"<tr><td>"+get_lang("Type the subject of the message for receiving a phone warning")+" .:"+
 						"</td></tr><tr><td><input type='text' id='field9' size='50' maxlength='200'>" +
-						"</td></tr><br/></table></div>" +
-				 		"<span align='right'><input type='button' value="+get_lang("Back")+" onclick='filter.form_m()'></span>"+
-				 		"<span align='right'><input type='button' value="+get_lang("Save")+" onclick='filter.saved_rules()'></span>";
+						"</td></tr><br/></table></div>";// +
+				 		//"<span align='right'><input type='button' value="+get_lang("Back")+" onclick='filter.form_m()'></span>"+
+				 		//"<span align='right'><input type='button' value="+get_lang("Save")+" onclick='filter.saved_rules()'></span>";
 		return form;
 	}
@@ -487,8 +492,4 @@
 				//Save outoffice in prefs:
                                 connector.loadScript("preferences");
-				if(typeof(prefe) == 'undefined'){
-					setTimeout("filter.delete_r();",500);
-                                }
-				else
 					prefe.save("outoffice", _this.out_officeF);
 			}
@@ -573,11 +574,16 @@
 			}
 
-			if(LTrim(Element("field1").value) == "" && LTrim(Element("field2").value) == "" && LTrim(Element("field3").value) == "" && Element("field4").value == "")
+			if(LTrim(Element("field1").value) == "" && LTrim(Element("field2").value) == "" && LTrim(Element("field3").value) == "" && LTrim(Element("field4").value).length == 0)
 			{
 				alert(get_lang("Define some criterion to the fields Sender, To and Subject with more than 3 characters!"));
 				return false;
 			}
-
-			if((LTrim(Element("field1").value).length <= 3) && (LTrim(Element("field2").value).length <= 3) && (LTrim(Element("field3").value).length <= 3 && Element("field4").value == "")){
+			if((LTrim(Element("field1").value).length <= 3) && LTrim(Element("field1").value) != ""){
+				alert(get_lang("Define some criterion to the fields Sender, To and Subject with more than 3 characters!"));
+				return false;
+			}if((LTrim(Element("field2").value).length <= 3) && LTrim(Element("field2").value) != ""){
+				alert(get_lang("Define some criterion to the fields Sender, To and Subject with more than 3 characters!"));
+				return false;
+			}if((LTrim(Element("field3").value).length <= 3) && LTrim(Element("field3").value) != ""){
 				alert(get_lang("Define some criterion to the fields Sender, To and Subject with more than 3 characters!"));
 				return false;
@@ -649,4 +655,7 @@
 			}
 			var opts = "";
+			if(Element("checkBox1").checked == true){
+                            opts += ",checkBox1";
+                        }
 			if(Element("checkBox2").checked == true){
                             opts += ",checkBox2";
@@ -691,4 +700,8 @@
 				return false;
 			}
+			else if(fld_men.value.length > 10000){
+				alert(get_lang("Your message have %1 characters, the message needs to have less then 10000 characters",fld_men.value.length));
+				return false;
+			}
 			this.out_officeR = mount_rule;
 		}
@@ -740,4 +753,5 @@
 		
 		Element('form_buttons').style.display = '';
+		Element('Edit_form_buttons').style.display = 'none';
 		this.reload_rules();
 	}
@@ -824,5 +838,4 @@
 	}
 
-    connector.loadScript("preferences");
 // build object
    var filter;
Index: trunk/expressoMail1_2/js/draw_api.js
===================================================================
--- trunk/expressoMail1_2/js/draw_api.js	(revision 5083)
+++ trunk/expressoMail1_2/js/draw_api.js	(revision 5134)
@@ -51,6 +51,8 @@
 					else if (data[i].folder_unseen <= 0)
 					{
+						if(tree_folders.getNodeById(data[i].folder_id)){
 						tree_folders.getNodeById(data[i].folder_id).alter({caption:lang_folder(data[i].folder_name)});
 						tree_folders.getNodeById(data[i].folder_id)._refresh();
+					}
 					}
 
@@ -152,25 +154,11 @@
 		 */
 		if (preferences.use_local_messages==1 || expresso_offline) {
-			if (!window.google || !google.gears) {
-				if (!expresso_local_messages.installGears())
-					preferences.use_local_messages=0;
-			}
-			else{
-				if (!window.google || !google.gears) {
-				temp = confirm(get_lang("To use local messages you have to install google gears. Would you like to be redirected to gears installation page?"));
-				if (temp) {
-                                       //if(is_win && is_gecko && preferences.gears_firefox_windows != "")
-                                        //    location.href = preferences.gears_firefox_windows;
-                                       //else if(!is_win && is_gecko && preferences.gears_firefox_linux != "")
-                                         //  location.href = preferences.gears_firefox_linux;
-                                       //else if(is_ie && preferences.gears_ie != "")
-                                           //location.href = preferences.gears_ie;
-                                       //else
-							expresso_local_messages.installGears();
-				}
-				else {
-					preferences.use_local_messages=0;
-				}
-			}
+			    //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)
@@ -210,10 +198,9 @@
 				}
 			}
-		}
 
 		tree_folders.draw(Element('content_folders'));
 		if (!expresso_offline) {
-			//n_root.changeState();
-			//tree_folders.getNodeById('INBOX')._select();
+			n_root.changeState();
+			tree_folders.getNodeById('INBOX')._select();
 		}
 		else {
@@ -260,5 +247,5 @@
 
 		draw_paging(Element('tot_m').innerHTML);
-		if(document.getElementById("nINBOX/"+trashfolder+"tree_folders"))
+		if(document.getElementById("nINBOX"+cyrus_delimiter+trashfolder+"tree_folders"))
 		{
 			var trash = document.createElement("SPAN");
@@ -271,7 +258,7 @@
 			trash.onmouseover = function() {trash.style.color="red";};
 			trash.onmouseout= function() {trash.style.color="#666666";};
-			document.getElementById("nINBOX/"+trashfolder+"tree_folders").appendChild(trash);
-		}
-		if(document.getElementById("nINBOX/"+spamfolder+"tree_folders"))
+			document.getElementById("nINBOX"+cyrus_delimiter+trashfolder+"tree_folders").appendChild(trash);
+		}
+		if(document.getElementById("nINBOX"+cyrus_delimiter+spamfolder+"tree_folders"))
 		{
 						var spam = document.createElement("SPAN");
@@ -285,5 +272,5 @@
 						spam.onmouseover = function() {spam.style.color="red";};
 						spam.onmouseout= function() {spam.style.color="#666666";};
-						document.getElementById("nINBOX/"+spamfolder+"tree_folders").appendChild(spam);
+						document.getElementById("nINBOX"+cyrus_delimiter+spamfolder+"tree_folders").appendChild(spam);
 			   }
 
@@ -540,5 +527,6 @@
   	if(current_page != 1) {
 	  	lnk_page = document.createElement("A");
-		lnk_page.setAttribute("href", "javascript:current_page=1;kill_current_box(); draw_paging("+num_msgs+"); proxy_mensagens.messages_list(get_current_folder(),"+msg_range_begin+","+msg_range_end+",'"+sort_box_type+"','"+search_box_type+"',"+sort_box_reverse+","+preferences.preview_msg_subject+","+preferences.preview_msg_tip+",function handler(data){alternate_border(0); draw_box(data, get_current_folder());});");
+		//lnk_page.setAttribute("href", "javascript:current_page=1;kill_current_box(); draw_paging("+num_msgs+"); proxy_mensagens.messages_list(get_current_folder(),"+msg_range_begin+","+msg_range_end+",'"+sort_box_type+"','"+search_box_type+"',"+sort_box_reverse+","+preferences.preview_msg_subject+","+preferences.preview_msg_tip+",function handler(data){alternate_border(0); draw_box(data, get_current_folder());});");
+		lnk_page.setAttribute("href", "javascript:current_page=1; draw_paging("+num_msgs+"); proxy_mensagens.messages_list(get_current_folder(),"+msg_range_begin+","+msg_range_end+",'"+sort_box_type+"','"+search_box_type+"',"+sort_box_reverse+","+preferences.preview_msg_subject+","+preferences.preview_msg_tip+",function handler(data){alternate_border(0); draw_box(data, get_current_folder());});");
   	}
   	else {
@@ -579,5 +567,6 @@
   			msg_range_begin = ((i*preferences.max_email_per_page)-(preferences.max_email_per_page-1));
 			msg_range_end = (i*preferences.max_email_per_page);
-			lnk_page.setAttribute("href", "javascript:current_page="+i+";kill_current_box(); draw_paging("+num_msgs+"); proxy_mensagens.messages_list(get_current_folder(),"+msg_range_begin+","+msg_range_end+",'"+sort_box_type+"','"+search_box_type+"',"+sort_box_reverse+","+preferences.preview_msg_subject+","+preferences.preview_msg_tip+",function handler(data){alternate_border(0); draw_box(data, get_current_folder());});");
+			//lnk_page.setAttribute("href", "javascript:current_page="+i+";kill_current_box(); draw_paging("+num_msgs+"); proxy_mensagens.messages_list(get_current_folder(),"+msg_range_begin+","+msg_range_end+",'"+sort_box_type+"','"+search_box_type+"',"+sort_box_reverse+","+preferences.preview_msg_subject+","+preferences.preview_msg_tip+",function handler(data){alternate_border(0); draw_box(data, get_current_folder());});");
+			lnk_page.setAttribute("href", "javascript:current_page="+i+"; draw_paging("+num_msgs+"); proxy_mensagens.messages_list(get_current_folder(),"+msg_range_begin+","+msg_range_end+",'"+sort_box_type+"','"+search_box_type+"',"+sort_box_reverse+","+preferences.preview_msg_subject+","+preferences.preview_msg_tip+",function handler(data){alternate_border(0); draw_box(data, get_current_folder());});");
   		}
   		lnk_page.innerHTML = "&nbsp;...&nbsp;";
@@ -593,5 +582,6 @@
   		msg_range_begin = ((total_pages*preferences.max_email_per_page)-(preferences.max_email_per_page-1));
 		msg_range_end = (total_pages*preferences.max_email_per_page);
-		lnk_page.setAttribute("href", "javascript:current_page="+total_pages+";kill_current_box(); draw_paging("+num_msgs+"); proxy_mensagens.messages_list(get_current_folder(),"+msg_range_begin+","+msg_range_end+",'"+sort_box_type+"','"+search_box_type+"',"+sort_box_reverse+","+preferences.preview_msg_subject+","+preferences.preview_msg_tip+",function handler(data){alternate_border(0); draw_box(data, get_current_folder());});");
+		//lnk_page.setAttribute("href", "javascript:current_page="+total_pages+";kill_current_box(); draw_paging("+num_msgs+"); proxy_mensagens.messages_list(get_current_folder(),"+msg_range_begin+","+msg_range_end+",'"+sort_box_type+"','"+search_box_type+"',"+sort_box_reverse+","+preferences.preview_msg_subject+","+preferences.preview_msg_tip+",function handler(data){alternate_border(0); draw_box(data, get_current_folder());});");
+		lnk_page.setAttribute("href", "javascript:current_page="+total_pages+"; draw_paging("+num_msgs+"); proxy_mensagens.messages_list(get_current_folder(),"+msg_range_begin+","+msg_range_end+",'"+sort_box_type+"','"+search_box_type+"',"+sort_box_reverse+","+preferences.preview_msg_subject+","+preferences.preview_msg_tip+",function handler(data){alternate_border(0); draw_box(data, get_current_folder());});");
 	}
 	else {
@@ -788,5 +778,6 @@
 	else
 		hT = getFirstParentOfType(el,"TABLE");
-	return (hT.parentNode.nextSibling.childNodes[0]);
+	return (hT.parentNode.nextSibling.childNodes[0].className !== "local-messages-search-warning"?
+		hT.parentNode.nextSibling.childNodes[0] : hT.parentNode.nextSibling.childNodes[1]);
 }
 
@@ -969,4 +960,6 @@
 		document.getElementById("border_table").width = "99.5%";
 
+	numBox = 0; //As pastas sempre estarão na aba 0
+	
 	openTab.content_id[numBox] = document.getElementById("content_id_"+numBox);
 	openTab.content_id[numBox].innerHTML = "";
@@ -1246,16 +1239,16 @@
 		tr_element.msg_sample = "";
 		//if(headers_msgs.msg_sample && headers_msgs.msg_sample.preview_msg_subject != "")
-		if(headers_msgs.msg_sample && preferences.preview_msg_subject == "1")
+		if(headers_msgs.msg_sample && preferences.preview_msg_subject == "1" && headers_msgs.msg_sample.body !== "")
 		{
 			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;
+				tr_element.msg_sample = Base64.decode(headers_msgs.msg_sample.body).substr(0,180) + "..."; //trecho do body que sera exibido com o assunto;
 			else
-				tr_element.msg_sample = headers_msgs.msg_sample.body.substr(0,120) + "..."; //trecho do body que sera exibido com o assunto;
+				tr_element.msg_sample = 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")
+		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;
+			tr_element.tip = Base64.decode(headers_msgs.msg_sample.body).substr(3,300) + "..."; //trecho do body que sera exibido no tool-tip;
 		}
 
@@ -1266,5 +1259,5 @@
 		}
 		else{
-			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');
 		}
@@ -1342,5 +1335,5 @@
 		td_element23 = createTDElement(0,4,"td_msg",null,"td_message_important_"+headers_msgs.msg_number);
 
-		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 )) 
 		{
 			td_element23.innerHTML = "<img src ='templates/"+template+"/images/important.gif' title='"+get_lang('Important')+"'>";
@@ -1370,8 +1363,8 @@
 
 		test = true;
-		if(msg_folder.indexOf(sentfolder) !=-1 ||msg_folder.indexOf(preferences.save_in_folder) !=-1 || msg_folder.replace("local_","INBOX/").indexOf(preferences.save_in_folder) !=-1)
+		if(msg_folder.indexOf(sentfolder) !=-1 ||msg_folder.indexOf(preferences.save_in_folder) !=-1 || msg_folder.replace("local_","INBOX"+cyrus_delimiter).indexOf(preferences.save_in_folder) !=-1)
 		    test = false;
 
-		if(headers_msgs.from.email.toLowerCase() == Element("user_email").value.toLowerCase() && !(preferences.from_to_sent == "1" && test) && !(msg_folder.substr(0,5) == "user/"))
+		if( (headers_msgs.from != undefined) && headers_msgs.from.email.toLowerCase() == Element("user_email").value.toLowerCase() && !(preferences.from_to_sent == "1" && test) && !(msg_folder.substr(0,5) == "user/"))
 		{
 			td_element3.onmouseover = function () {this.title=headers_msgs.to.email;};
@@ -1402,4 +1395,5 @@
 				spanSender.onmouseover = function (event) {this.style.textDecoration = "underline";try {InfoContact.begin(this,headers_msgs.from.email)} catch(e){};};
 				spanSender.onmouseout = function (){try {this.style.textDecoration = "none";clearTimeout(InfoContact.timeout);} catch(e){}};
+				if ( headers_msgs.from !== undefined )
 				spanSender.innerHTML =  headers_msgs.from.name != null ? headers_msgs.from.name : headers_msgs.from.email;
 				if (spanSender.innerHTML.indexOf(" ") == '-1' && spanSender.innerHTML.length > 25){
@@ -1458,5 +1452,5 @@
 
                 // old local messages can capture headers_msgs.udate as "hh:mm" or "dd/mm/yyyy"
-                if (headers_msgs.udate.toString().match(/\d{2}:\d{2}/) || headers_msgs.udate.toString().match(/\d{2}\/\d{2}\/\d{4}/))
+                if ( (headers_msgs.udate !== undefined) && (headers_msgs.udate.toString().match(/\d{2}:\d{2}/) || headers_msgs.udate.toString().match(/\d{2}\/\d{2}\/\d{4}/)) )
                 {
                     temp_msg_day = headers_msgs.msg_day.split('/');
@@ -1562,5 +1556,21 @@
 	document.getElementById("message_header_"+(sort_box_type.lastIndexOf("SORT") != "-1" ? sort_box_type : "SORTARRIVAL")+"_"+numBox ).innerHTML = "<B>"+type_name+"</B><img src ='templates/"+template+"/images/arrow_"+(sort_box_reverse == 1 ? 'desc' : 'asc')+"endant.gif'>";
 }
-
+function verifyOption(name, id){
+	var str = name + '' + id;
+	if(!Element(str).style.display == ""){
+		var option_reply_options = document.getElementById('msg_opt_reply_options_'+id);
+		option_reply_options.value = 'show';
+		option_reply_options.src= '../expressoMail1_2/templates/default/images/down.png';
+		Element('tr_other_options_'+id).style.display = 'none';
+		var option_more_options = document.getElementById('msg_opt_more_options_'+id);
+		option_more_options.value = 'show';
+		option_more_options.src= '../expressoMail1_2/templates/default/images/down.png';
+		Element('tr_other_more_options_'+id).style.display = 'none';
+		var option_mark_as_options = document.getElementById('msg_opt_mark_options_'+id);
+		option_mark_as_options.value = 'show';
+		option_mark_as_options.src= '../expressoMail1_2/templates/default/images/down.png';
+		Element('tr_other_mark_options_'+id).style.display = 'none';
+	}
+}
 function draw_message(info_msg, ID){
 	var content = document.getElementById('content_id_' + ID);
@@ -1589,13 +1599,10 @@
 		folder = Element(info_msg.msg_number);
 		
-	if (!folder){
-		delete_border(ID);
-		return;
-		}
+
 	if (folder){ // mensagem local criptografada nao tem ID da pasta local
 		if (folder.nextSibling){
 			var nextMsgBox = folder.nextSibling.name?folder.nextSibling.name:info_msg.msg_folder;
 
-			if (nextMsgBox == "INBOX/decifradas")// teste para ver se a mensagem vem da pasta oculta decifradas
+			if (nextMsgBox == "INBOX" + cyrus_delimiter + "decifradas")// teste para ver se a mensagem vem da pasta oculta decifradas
 					nextMsgBox = get_current_folder();
 
@@ -1605,4 +1612,5 @@
 				openTab.type[ID] = 2;
 				proxy_mensagens.get_msg(folder.nextSibling.id,nextMsgBox,true,show_msg);
+				select_msg('null', 'down', true);
 			};
 		}
@@ -1635,8 +1643,5 @@
 	img_previous_msg.style.cursor = 'pointer';
 
-	if (!folder){
-			delete_border(ID);
-		return;
-		}
+
 	if (folder){ // mensagem local criptografada nao tem ID da pasta local
 		if (folder.previousSibling)
@@ -1652,4 +1657,5 @@
 				openTab.type[ID] = 2;
 				proxy_mensagens.get_msg(folder.previousSibling.id,previousMsgBox,true,show_msg);
+				select_msg('null', 'up', true);
 			};
 		}
@@ -1730,4 +1736,8 @@
 	}
 
+	if (info_msg.Flagged == 'F')
+	{
+		td.innerHTML += '&nbsp;<img id="disposition_important_'+ID+'" style="cursor:pointer" alt="'+ get_lang('Important message') + '" title="'+ get_lang('Important message') + '" src="templates/'+template+'/images/important.gif">';
+	}
 	// NORMAL MSG
 	if(info_msg.Draft != 'X')
@@ -1736,4 +1746,6 @@
 	options.width = "30%";
 	options.setAttribute("noWrap","true");
+		
+		//BEGIN: DESENHA MOSTRA DETALHES, OCULTAR DETALHES
 	var option_hide_more = document.createElement("SPAN");
 	option_hide_more.className = 'message_options';
@@ -1756,23 +1768,42 @@
 		resizeWindow();
 	};
-	var option_mark = document.createElement('TD');
-	option_mark.align = "left";
-	option_mark.width = "50%";
-	var option_mark_as = '<span>'+get_lang("Mark as")+'</span>: ';
+		//END: DESENHA MOSTRA DETALHES, OCULTAR DETALHES
+		
+		//OPCAO PARA MARCAR COMO
+		var option_mark_as = document.createElement("SPAN");
+		option_mark_as.innerHTML = "<b>"+get_lang('Mark as')+"</b>";
+		option_mark_as.className = 'message_options';
+		option_mark_as.onmouseover=function () {this.className='message_options_active';};
+		option_mark_as.onmouseout=function () {this.className='message_options'};
+		option_mark_as.onclick = function(){
+			verifyOption('tr_other_mark_options_', ID);
+			var thi = document.getElementById('msg_opt_mark_options_'+ID);
+			if (thi.value != 'hide'){
+				thi.value = 'hide';
+				option_mark_as_options.src= '../expressoMail1_2/templates/default/images/pressed.png';
+				Element('tr_other_mark_options_'+ID).style.display = '';
+
+			}
+			else{
+				thi.value = 'show';
+				option_mark_as_options.src= '../expressoMail1_2/templates/default/images/down.png';
+				Element('tr_other_mark_options_'+ID).style.display = 'none';
+			}
+		};
+		//DESENHA OPCOES DO MARCAR COMO
 	var option_mark_as_unseen = document.createElement("SPAN");
-	option_mark_as_unseen.className = "message_options";
+		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');
 		write_msg(get_lang('Message marked as ')+get_lang("Unseen"));
 	};
-	option_mark_as_unseen.onmouseover=function () {this.className='message_options_active';};
-	option_mark_as_unseen.onmouseout=function () {this.className='message_options'};
+		option_mark_as_unseen.onmouseover=function () {this.className='reply_options_active'};
+		option_mark_as_unseen.onmouseout=function () {this.className='reply_options'};
 	option_mark_as_unseen.innerHTML = get_lang("Unseen");
 
 	var option_mark_important = document.createElement("SPAN");
-	option_mark_important.className = 'message_options';
-	option_mark_important.style.paddingLeft = "10px";
-	option_mark_important.onmouseover=function () {this.className='message_options_active';};
-	option_mark_important.onmouseout=function () {this.className='message_options'};
+		option_mark_important.className = 'reply_options';		
+		option_mark_important.onmouseover=function () {this.className='reply_options_active';};
+		option_mark_important.onmouseout=function () {this.className='reply_options'};
 
 	if (info_msg.Flagged == "F"){
@@ -1796,9 +1827,54 @@
 		option_mark_important.innerHTML = get_lang("Important");
 	}
-	option_mark.innerHTML = option_mark_as;
-	option_mark.appendChild(option_mark_as_unseen);
-	option_mark.appendChild(option_mark_important);
+		//option_mark.appendChild(option_mark_as_unseen);
+		//option_mark.appendChild(option_mark_important);
+
+		
 	option_hide_more.innerHTML = get_lang('Show details');
+		option_hide_more.title = (preferences.use_shortcuts == '1') ? get_lang('Shortcut: %1', 'O') : get_lang('Show details');
+	
+		var space3 = document.createElement("SPAN");
+		space3.innerHTML = '&nbsp;|&nbsp;';
+		
+		var option_mark_as_options = document.createElement('IMG');
+		option_mark_as_options.id = 'msg_opt_mark_options_'+ID;
+		option_mark_as_options.src = '../expressoMail1_2/templates/default/images/down.png';
+		option_mark_as_options.value = 'show';
+
+		option_mark_as_options.onmouseover = function(){
+			option_mark_as_options.src= '../expressoMail1_2/templates/default/images/over.png';
+			option_mark_as.className = 'message_options_active';
+		};
+		option_mark_as_options.onmouseout = function(){
+			option_mark_as.className = 'message_options';
+			if (this.value == 'show')
+			{
+				option_mark_as_options.src= '../expressoMail1_2/templates/default/images/down.png';
+			}
+			else
+			{
+				option_mark_as_options.src= '../expressoMail1_2/templates/default/images/pressed.png';
+			}
+		};
+		option_mark_as_options.onclick = function(){
+			verifyOption('tr_other_mark_options_', ID);
+			if (this.value != 'hide'){
+				this.value = 'hide';
+				option_mark_as_options.src= '../expressoMail1_2/templates/default/images/pressed.png';
+				Element('tr_other_mark_options_'+ID).style.display = '';
+
+			}
+			else{
+				this.value = 'show';
+				option_mark_as_options.src= '../expressoMail1_2/templates/default/images/down.png';
+				Element('tr_other_mark_options_'+ID).style.display = 'none';
+			}
+		};
+		
 	options.appendChild(option_hide_more);
+		options.appendChild(space3);
+		options.appendChild(option_mark_as_options);				
+		options.appendChild(option_mark_as);
+		//FIM OPCAO PARA MARCAR COMO
 
 	var space0 = document.createElement("SPAN");
@@ -1809,13 +1885,69 @@
 	space2.innerHTML = '&nbsp;|&nbsp;';
 
-	var option_forward = document.createElement("SPAN");
-	option_forward.id = 'msg_opt_forward_'+ID;
-	option_forward.className = 'message_options';
-	option_forward.onclick = function(){new_message('forward', ID);};
-	option_forward.onmouseover=function () {this.className='message_options_active';};
-        option_forward.onmouseout=function () {this.className='message_options'};
-	option_forward.innerHTML = get_lang('Forward');
+		//OPCAO PARA MAIS ACOES
+		var option_more = document.createElement("SPAN");
+		option_more.id = 'msg_opt_more_actions_'+ID;
+		option_more.className = 'message_options';
+		//option_more.onclick = function(){new_message('forward', ID);};
+		option_more.onmouseover=function () {this.className='message_options_active';};
+        option_more.onmouseout=function () {this.className='message_options'};
+		option_more.onclick = function(){
+			verifyOption('tr_other_more_options_', ID);
+			if (option_more_options.value != 'hide'){
+				option_more_options.value = 'hide';
+				option_more_options.src= '../expressoMail1_2/templates/default/images/pressed.png';
+				Element('tr_other_more_options_'+ID).style.display = '';
+
+			}
+			else{
+				option_more_options.value = 'show';
+				option_more_options.src= '../expressoMail1_2/templates/default/images/down.png';
+				Element('tr_other_more_options_'+ID).style.display = 'none';
+			}
+		};
+		option_more.innerHTML = get_lang('More Actions');
+		
+		//CRIA IMG DE MAIS ACOES
+		var option_more_options = document.createElement('IMG');
+		option_more_options.id = 'msg_opt_more_options_'+ID;
+		option_more_options.src = '../expressoMail1_2/templates/default/images/down.png';
+		option_more_options.value = 'show';
+
+		option_more_options.onmouseover = function(){
+			option_more.className = 'message_options_active';
+			option_more_options.src= '../expressoMail1_2/templates/default/images/over.png';
+		};
+		option_more_options.onmouseout = function(){
+			option_more.className = 'message_options';
+			if (this.value == 'show')
+			{
+				option_more_options.src= '../expressoMail1_2/templates/default/images/down.png';
+			}
+			else
+			{
+				option_more_options.src= '../expressoMail1_2/templates/default/images/pressed.png';
+			}
+		};
+		option_more_options.onclick = function(){
+			verifyOption('tr_other_more_options_',ID);
+			
+			if (this.value != 'hide'){
+				this.value = 'hide';
+				option_more_options.src= '../expressoMail1_2/templates/default/images/pressed.png';
+				Element('tr_other_more_options_'+ID).style.display = '';
+
+			}
+			else{
+				this.value = 'show';
+				option_more_options.src= '../expressoMail1_2/templates/default/images/down.png';
+				Element('tr_other_more_options_'+ID).style.display = 'none';
+			}
+		};
 	options.appendChild(space1);
-	options.appendChild(option_forward);
+		options.appendChild(option_more_options);
+		options.appendChild(option_more);
+		//FIM OPCAO PARA MAIS ACOES
+		
+		//OPCAO PARA RESPONDER
 	var option_reply = document.createElement("SPAN");
 	option_reply.id = 'msg_opt_reply_'+ID;
@@ -1825,4 +1957,5 @@
 	option_reply.onmouseover=function () {this.className='message_options_active';};
 	option_reply.onmouseout=function () {this.className='message_options'};
+		option_reply.title = (preferences.use_shortcuts == '1') ? get_lang('Shortcut: %1', 'R') : get_lang('Reply');
 
 	options.appendChild(space2);
@@ -1847,4 +1980,5 @@
 	};
 	option_reply_options.onclick = function(){
+			verifyOption('tr_other_options_', ID);
 		if (this.value != 'hide'){
 			this.value = 'hide';
@@ -1861,7 +1995,42 @@
 	options.appendChild(option_reply_options);
 	options.appendChild(option_reply);
+		//FIM OPCAO PARA RESPONDER
+		
+		//OPCAO PARA ENCAMINHAR
+		var option_forward = document.createElement("SPAN");
+		option_forward.id = 'msg_opt_forward_'+ID;
+		option_forward.className = 'message_options';
+		option_forward.innerHTML = get_lang('Forward');
+		option_forward.onclick = function(){new_message('forward', ID);};
+		option_forward.onmouseover=function () {this.className='message_options_active';};
+        option_forward.onmouseout=function () {this.className='message_options'};
+		option_forward.title = (preferences.use_shortcuts == '1') ? get_lang('Shortcut: %1', 'E') : get_lang('Forward');
+		
+		var space9 = document.createElement("SPAN");
+		space9.innerHTML = '&nbsp;|&nbsp;';
+		
+		options.appendChild(space9);
+		options.appendChild(option_forward);
+		//FIM DA OPCAO PARA ENCAMINHAR
+		
+		//OPCAO PARA DELETAR
+		var option_delete = document.createElement("SPAN");
+		option_delete.id = 'msg_opt_delete_'+ID;
+		option_delete.className = 'message_options';
+		option_delete.onclick = function(){proxy_mensagens.delete_msgs('null','selected','null');};
+		option_delete.innerHTML = get_lang('Delete');
+		option_delete.onmouseover=function () {this.className='message_options_active';};
+		option_delete.onmouseout=function () {this.className='message_options'};
+		option_delete.title = (preferences.use_shortcuts == '1') ? get_lang('Shortcut: %1', 'Delete') : get_lang('Delete');
+
+		var space6 = document.createElement("SPAN");
+		space6.innerHTML = '&nbsp;|&nbsp;';
+		
+		options.appendChild(space6);
+		options.appendChild(option_delete);
+		//FIM OPCAO PARA DELETAR
 
 	tr.appendChild(td);
-	tr.appendChild(option_mark);
+		//tr.appendChild(option_mark);
 	tr.appendChild(options);
 	tr.appendChild(next_previous_msg_td);
@@ -1870,31 +2039,67 @@
 	////////// OTHER OPTIONS ////////////////////
 	var tr_other_options = document.createElement("TR");
+		var tr_other_mark_options = document.createElement("TR");
+		var tr_other_more_options = document.createElement("TR");
+		
+		tr_other_mark_options.id = 'tr_other_mark_options_' + ID;
+		tr_other_mark_options.style.display = 'none';
+		tr_other_mark_options.style.backgroundColor = '#205C8E';
 	tr_other_options.id = 'tr_other_options_' + ID;
 	tr_other_options.style.display = 'none';
+		tr_other_options.style.backgroundColor = '#205C8E';
+		tr_other_more_options.id = 'tr_other_more_options_' + ID;
+		tr_other_more_options.style.display = 'none';
+		tr_other_more_options.style.backgroundColor = '#205C8E';		
 
 	var td_other_options = document.createElement("TD");
+		var td_other_mark_options = document.createElement("TD");
+		var td_other_more_options = document.createElement("TD");
+		
 	td_other_options.colSpan = '3';
+		td_other_mark_options.colSpan = '3';
+		td_other_more_options.colSpan = '3';
+
 	var div_other_options = document.createElement("DIV");
-
-	var option_mark_as_unseen = '<span class="message_options" onclick="proxy_mensagens.proxy_set_messages_flag(\'unseen\','+info_msg.msg_number+');write_msg(\''+get_lang('Message marked as ')+get_lang("Unseen")+'.\');">'+get_lang("Unseen")+'</span>, ';
-	var option_mark_as_important			= '<span class="message_options" onclick="proxy_mensagens.proxy_set_messages_flag(\'flagged\','+info_msg.msg_number+');write_msg(\''+get_lang('Message marked as ')+get_lang("Important")+'.\');">'+get_lang("Important")+'</span>, ';
-	var option_mark_as_normal				= '<span class="message_options" onclick="proxy_mensagens.proxy_set_messages_flag(\'unflagged\','+info_msg.msg_number+');write_msg(\''+get_lang('Message marked as ')+get_lang("Normal")+'.\');">'+get_lang("Normal")+'</span> | ';
-
-	var option_move	= '<span class="message_options" onclick=wfolders.makeWindow("'+ID+'","move_to");>'+get_lang("Move")+'</span> | ';
-	var option_reply_to_all = '<span onmouseover="this.className=\'reply_options_active\'" onmouseout="this.className=\'reply_options\'" class="reply_options" onclick=new_message("reply_to_all_with_history","'+ID+'");>'+get_lang("Reply to all")+'</span> | ';
+		var div_other_mark_options = document.createElement("DIV");
+		var div_other_more_options = document.createElement("DIV");
+
+		//var option_mark_as_unseen = '<span class="message_options" onclick="proxy_mensagens.proxy_set_messages_flag(\'unseen\','+info_msg.msg_number+');write_msg(\''+get_lang('Message marked as ')+get_lang("Unseen")+'.\');">'+get_lang("Unseen")+'</span>, ';
+		//var option_mark_as_important			= '<span class="message_options" onclick="proxy_mensagens.proxy_set_messages_flag(\'flagged\','+info_msg.msg_number+');write_msg(\''+get_lang('Message marked as ')+get_lang("Important")+'.\');">'+get_lang("Important")+'</span>, ';
+		//var option_mark_as_normal				= '<span class="message_options" onclick="proxy_mensagens.proxy_set_messages_flag(\'unflagged\','+info_msg.msg_number+');write_msg(\''+get_lang('Message marked as ')+get_lang("Normal")+'.\');">'+get_lang("Normal")+'</span> | ';
+		var block_user = '<span onmouseover="this.className=\'reply_options_active\'" onmouseout="this.className=\'reply_options\'" class="reply_options" onclick ="filter.new_rule(\''+info_msg.from.email+'\');">'+get_lang("Block Sender")+'</span> | ';	
+		//var option_forward = '<span onclick="new_message(\'forward\',\''+ ID+'\');" onmouseover="this.className=\'reply_options_active\'" onmouseout="this.className=\'reply_options\'" class="reply_options">'+get_lang("Forward")+'</span> | ';
+		var option_move	= '<span onmouseover="this.className=\'reply_options_active\'" onmouseout="this.className=\'reply_options\'" class="reply_options" onclick=wfolders.makeWindow("'+ID+'","move_to");>'+get_lang("Move")+'</span> | ';
+		var option_print = '<span onclick="print_all()" onmouseover="this.className=\'reply_options_active\'" onmouseout="this.className=\'reply_options\'" class="reply_options">'+get_lang("Print")+'</span> | ';
+		var option_export = '<span onclick="proxy_mensagens.export_all_messages()" onmouseover="this.className=\'reply_options_active\'" onmouseout="this.className=\'reply_options\'" class="reply_options">'+get_lang("Export")+'</span> | ';
+
+		option_reply_to_all__title = (preferences.use_shortcuts == '1') ? get_lang('Shortcut: %1', 'T') : '';
+		var option_reply_to_all = '<span onmouseover="this.className=\'reply_options_active\'" onmouseout="this.className=\'reply_options\'" class="reply_options" onclick="new_message(\'reply_to_all_with_history\',\''+ID+'\');" title="'+option_reply_to_all__title+'">'+get_lang("Reply to all")+'</span> | ';
 	var option_reply_without_history = '<span onmouseover="this.className=\'reply_options_active\'" onmouseout="this.className=\'reply_options\'" class="reply_options" onclick=new_message("reply_without_history","'+ID+'");>'+get_lang("Reply without history")+'</span> | ';
-	var option_reply_to_all_without_history	= '<span onmouseover="this.className=\'reply_options_active\'" onmouseout="this.className=\'reply_options\'" class="reply_options" onclick=new_message("reply_to_all_without_history","'+ID+'");>'+get_lang("Reply to all without history")+'</span>';
-
-	div_other_options.innerHTML = option_reply_to_all + option_reply_without_history + option_reply_to_all_without_history;
+		var option_reply_to_all_without_history	= '<span onmouseover="this.className=\'reply_options_active\'" onmouseout="this.className=\'reply_options\'" class="reply_options" onclick=new_message("reply_to_all_without_history","'+ID+'");>'+get_lang("Reply to all without history")+'</span>  | ';
+
+		var report_error        = '<span onmouseover="this.className=\'reply_options_active\'" onmouseout="this.className=\'reply_options\'" class="reply_options" onclick=reports_window("'+currentTab+'");>'+get_lang("Report error")+'</span> | '; 
+
+		div_other_more_options.innerHTML += option_move + option_print + option_export + block_user + report_error;
+		
+		div_other_options.innerHTML += option_reply_without_history + option_reply_to_all_without_history + option_reply_to_all;
 	if (use_spam_filter) {
-		if(info_msg.msg_folder == 'INBOX'+cyrus_delimiter+'Spam')
-			div_other_options.innerHTML += ' | <span class="message_options" onclick="nospam('+info_msg.msg_number+',\'null\', \''+info_msg.msg_folder+'\')";>'+get_lang("Not Spam")+'</span>';
-		else
-			div_other_options.innerHTML += ' | <span class="message_options" onclick="spam(\''+info_msg.msg_folder+'\', '+info_msg.msg_number+',\'null\')";>'+get_lang("Mark as Spam")+'</span>';
-	}
+			if(info_msg.msg_folder == 'INBOX'+cyrus_delimiter+'Spam' || (info_msg.msg_folder.match(/^user/) && info_msg.msg_folder.match(/Spam$/))){
+				div_other_mark_options.innerHTML += '<span onmouseover="this.className=\'reply_options_active\'" onmouseout="this.className=\'reply_options\'" class="reply_options" onclick="nospam('+info_msg.msg_number+',\'null\', \''+info_msg.msg_folder+'\');">'+get_lang("Not Spam")+'</span> | ';
+	}
+			else{
+				div_other_mark_options.innerHTML += '<span onmouseover="this.className=\'reply_options_active\'" onmouseout="this.className=\'reply_options\'" class="reply_options" onclick="spam(\''+info_msg.msg_folder+'\', '+info_msg.msg_number+',\'null\');">'+get_lang("Is Spam")+'</span> | ';
+			}
+		}
+		var space5 = document.createElement("SPAN");
+		space5.innerHTML = '&nbsp;|&nbsp;';
 	
-	var report_error        = ' | <span onmouseover="this.className=\'message_options_active\'" onmouseout="this.className=\'message_options\'" class="message_options" onclick=reports_window("'+currentTab+'");>'+get_lang("Report error")+'</span> |'; 
- 		         
- 	div_other_options.innerHTML += report_error;
+		div_other_mark_options.appendChild(option_mark_as_unseen);
+		var space4 = document.createElement("SPAN");
+		space4.innerHTML = '&nbsp;|&nbsp;';
+		div_other_mark_options.appendChild(space4);
+		div_other_mark_options.appendChild(option_mark_important); 
+		var space7 = document.createElement("SPAN");
+		space7.innerHTML = '&nbsp;|&nbsp;';
+		div_other_mark_options.appendChild(space7);
 	
 	td_other_options.align = 'right';
@@ -1902,7 +2107,21 @@
 	td_other_options.appendChild(div_other_options);
 
+		td_other_mark_options.align = 'right';
+		td_other_mark_options.style.paddingTop = '3px';
+		td_other_mark_options.appendChild(div_other_mark_options);
+		
+		td_other_more_options.align = 'right';
+		td_other_more_options.style.paddingTop = '3px';
+		td_other_more_options.appendChild(div_other_more_options);
+
 
 	tr_other_options.appendChild(td_other_options);
 	tbody_message_options.appendChild(tr_other_options);
+		
+		tr_other_more_options.appendChild(td_other_more_options);
+		tbody_message_options.appendChild(tr_other_more_options);
+		
+		tr_other_mark_options.appendChild(td_other_mark_options);
+		tbody_message_options.appendChild(tr_other_mark_options);
 	////////// END OTHER OPTIONS ////////////////
 
@@ -1939,15 +2158,8 @@
                          td_signature.innerHTML += '<span style=color:red><strong>'+get_lang(info_msg.signature[i].substring(0,info_msg.signature[i].indexOf("#@#")))+'</strong> '+info_msg.signature[i].substring(info_msg.signature[i].indexOf("#@#")+3)+'</span> <br /> ';
                         }
-                    else
-                        {
                             if(info_msg.signature[i].indexOf("###") > -1)
                                 {
                                     td_signature.innerHTML += '<span><strong>'+get_lang(info_msg.signature[i].substring(0,info_msg.signature[i].indexOf("###")))+'</strong> '+info_msg.signature[i].substring(info_msg.signature[i].indexOf("###")+3)+'</span> <br /> ';
                                 }
-                            else
-                                {
-                                    td_signature.innerHTML += '<span><strong>'+get_lang(info_msg.signature[i])+'</strong></span> <br /> ';
-                                }
-                        }
                 }
             var signature_status_pos = info_msg.signature[0].indexOf('Message untouched');
@@ -2051,5 +2263,10 @@
 	table_message_others_options.width = "100%";
 	table_message_others_options.style.display = 'none';
-	table_message_others_options.className = "table_message";
+	if(navigator.appName.indexOf('Internet Explorer')>0){
+		table_message_others_options.className = "table_message_options_ie";
+	}else{
+		table_message_others_options.className = "table_message_options";
+	}
+	
 	var tbody_message_others_options = document.createElement("TBODY");
 	var tr1 = document.createElement("TR");
@@ -2129,4 +2346,5 @@
 	tr2.className = "tr_message_header";
 	var td2 = document.createElement("TD");
+	td2.width = "7%";
 	td2.innerHTML = get_lang("To: ");
 	var to = document.createElement("TD");
@@ -2293,24 +2511,17 @@
 	if ( info_msg.attachments && info_msg.attachments.length > 0 )
 	{
-		var div_attach = document.createElement("DIV");
-		div_attach.setAttribute("class", "expressomail-attachments");
-		div_attach.setAttribute("className", "expressomail-attachments"); //for IE
-
-		var div_attach_lbl = document.createElement("span");
-		div_attach_lbl.setAttribute("class", "expressomail-attachments-label");
-		div_attach_lbl.setAttribute("className", "expressomail-attachments-label"); //for IE
-		div_attach_lbl.innerHTML = get_lang("Attachments: ");
+		//Código no padrão expresso 2.2
+	var tr6 = document.createElement("TR");
+		tr6.className = "tr_message_header";
+		var td6 = document.createElement("TD");
+		td6.innerHTML = get_lang("Attachments: ");
 		
-		var div_attach_list = document.createElement("UL");
-		div_attach_list.setAttribute("id", "attachments_" + ID);
-		div_attach_list.setAttribute("class", "expressomail-attachments-list");
-		div_attach_list.setAttribute("className", "expressomail-attachments-list"); //for IE
 		
+		var attachments = document.createElement("TD");
+		td6.valign = "top";
+		attachments.align = 'left';
+		if(info_msg.attachments.length >= 1){
 			if(info_msg.attachments.length > 1) {
-			var li_link_attachment = document.createElement("LI");
 				var link_attachment	 = document.createElement("A");
-			link_attachment.setAttribute("class", "expressomail-attachments-link");
-			link_attachment.setAttribute("className", "expressomail-attachments-link"); //for IE
-	
 				 if(proxy_mensagens.is_local_folder(current_folder))
 					link_attachment.setAttribute("href", "javascript:expresso_local_messages.download_all_local_attachments('"+info_msg.msg_folder+"','"+info_msg.msg_number+"')");
@@ -2318,28 +2529,23 @@
 					link_attachment.setAttribute("href", "javascript:download_all_attachments('"+info_msg.msg_folder+"','"+info_msg.msg_number+"')");
 				link_attachment.innerHTML = " "+info_msg.attachments.length+' '+get_lang('files')+' :: '+get_lang('Download all atachments');
-			li_link_attachment.appendChild(link_attachment);
-			div_attach_list.appendChild(li_link_attachment);
-			}
-		
+                    attachments.appendChild(link_attachment);
+			}
 			if(parseInt(preferences.remove_attachments_function))
 			{
-			var li_link_attachment = document.createElement("LI");
-			var link_attachment	= document.createElement("A");
-			link_attachment.setAttribute("class", "expressomail-attachments-link");
-			link_attachment.setAttribute("className", "expressomail-attachments-link"); //for IE
-			link_attachment.setAttribute("href", "javascript:remove_all_attachments('"+info_msg.msg_folder+"','"+info_msg.msg_number+"')");
-			link_attachment.innerHTML = get_lang('remove all attachments');
-
-			li_link_attachment.appendChild(link_attachment);
-			div_attach_list.appendChild(li_link_attachment);
-			}
-
+                    attachments.appendChild(document.createTextNode('  '));
+                    var del_attachments = document.createElement("A");
+                    del_attachments.setAttribute("href", "javascript:remove_all_attachments('"+info_msg.msg_folder+"','"+info_msg.msg_number+"')");
+                    del_attachments.innerHTML = get_lang('remove all attachments');
+                    attachments.appendChild(del_attachments);
+			}
+                attachments.appendChild(document.createElement('BR'));
+        }
+		attachments.id = "attachments_" + ID;
 		for (var i=0; i<info_msg.attachments.length; i++)
 		{
-			var li_link_attachment = document.createElement("LI");
-			var link_attachment = document.createElement("A");
+			var link_attachment = document.createElement("a");
 			link_attachment.setAttribute("href", proxy_mensagens.link_anexo(info_msg,i));
 			link_attachment.innerHTML = url_decode(info_msg.attachments[i].name) + " ("+borkb(info_msg.attachments[i].fsize)+")";
-			link_attachment.setAttribute("name", url_decode(info_msg.attachments[i].name));
+			//link_attachment.innerHTML += " ("+borkb(info_msg.attachments[i].fsize)+")";
 
 			//k trocar por match???
@@ -2357,28 +2563,36 @@
 			}
 
-			li_link_attachment.appendChild(link_attachment);
-			div_attach_list.appendChild(li_link_attachment);
-		}
-		div_attach.appendChild(div_attach_lbl);
-		div_attach.appendChild(div_attach_list);
+                        if((url_decode(info_msg.attachments[i].name).indexOf(".eml") != -1))
+			{
+				//Link para importar calendário
+				var link_open_msg = new Image();
+				link_open_msg.src = "templates/"+template+"/images/email.png";
+				//link_open_msg.setAttribute("onclick","javascript:import_calendar('"+info_msg.msg_folder+"&msg_number="+info_msg.msg_number+"&msg_part="+info_msg.attachments[i].pid+"&idx_file="+i+"&encoding="+info_msg.attachments[i].encoding+"'); return false;");
+				link_open_msg.setAttribute("onclick","javascript:open_msg_part('"+info_msg.msg_folder+"&msg_number="+info_msg.msg_number+"&msg_part="+info_msg.attachments[i].pid+"'); return false;");
+				link_open_msg.title = get_lang("Open message");
+				link_open_msg.align = "top";
+				link_open_msg.style.marginLeft = "5px";
+				link_open_msg.style.cursor = "pointer";
+				link_attachment.appendChild(link_open_msg);
+		}
 		
-		var tr6 = document.createElement("TR");
-		tr6.className = "tr_message_header";
-		var td6 = document.createElement("TD");
-		td6.setAttribute("colspan", "2");
-		td6.vAlign = "top";
-		td6.appendChild(div_attach);
+            link_attachment.innerHTML += '<br/>';
+            attachments.appendChild(link_attachment);
+            }
 		tr6.appendChild(td6);
+            tr6.appendChild(attachments);
 		tbody_message_others_options.appendChild(tr6);
 	}
+
 	//k!!
 	var div = document.createElement("DIV");
 	div.id = "div_message_scroll_"+ID;
-	div.setAttribute('class', 'div_message_scroll');
-	div.setAttribute('className', 'div_message_scroll'); //for IE
+        div.style.background = 'WHITE';
+        div.style.overflow = "auto";
 	table_message_others_options.appendChild(tbody_message_others_options);
 	var tr = document.createElement("TR");
+		tr.className = "tr_message_header";
 	var td = document.createElement("TD");
-	td.colSpan = '2';
+		td.colspan = '2';
 	td.style.fontSize = '10pt'; 
  	td.style.fontFamily = 'Arial,Verdana'; 
@@ -2401,5 +2615,5 @@
 				for (var i = 0; i < domains.length; i++)
 				{
-					if (imgTag[j].match(/cid:([\w\d]){5,}/) || imgTag[j].match(/src=\"\.\/inc\/show_embedded_attach\.php/g))
+					if (imgTag[j].match(/cid:([\w\d]){5,}/) || imgTag[j].match(/src=\"\.\/inc\/get_archive\.php/g)) 
 					{
 						forbidden = false;
@@ -2412,5 +2626,5 @@
 				if (forbidden)
 				{
-					newBody = newBody.replace(imgTag[j],"<img src='templates/"+template+"/images/forbidden.jpg'>");
+					newBody = newBody.replace(imgTag[j],"<img src='templates/"+template+"/images/forbidden.png'>");
 					blocked=true;
 				}
@@ -2441,11 +2655,11 @@
 	newBody = newBody.replace("<body","<span");
 	newBody = newBody.replace("<BODY","<span");
-	//while ( ( /<span[^>]*><span[^>]*>/ig ).test( newBody ) )
-        //       newBody = newBody.replace( /(<span[^>]*>)<span[^>]*>/ig, '$1' );
+	while ( ( /<span[^>]*><span[^>]*>/ig ).test( newBody ) )
+		newBody = newBody.replace( /(<span[^>]*>)<span[^>]*>/ig, '$1' );
 
 	var _body = document.createElement( 'div' );
 	_body.id = 'body_' + ID;
 	_body.innerHTML = newBody;
-	_body.style.fontSize = '16px';
+	//_body.style.fontSize = '16px';
 
 	var _elements = _body.getElementsByTagName( '*' );
@@ -2487,5 +2701,7 @@
 	
 	if ((info_msg.thumbs)&&(info_msg.thumbs.length > 0)){
-		var div_thumbs = document.createElement("DIV");
+		var thumbs = jQuery.parseJSON(info_msg.thumbs);
+		var div_thumbs = document.createElement("div");
+		
 		div_thumbs.setAttribute("class", "expressomail-thumbs");
 		div_thumbs.setAttribute("className", "expressomail-thumbs"); //for IE
@@ -2526,13 +2742,43 @@
 		ul_thumbs_list.setAttribute("className", "expressomail-thumbs-list"); //for IE
 
-		for (var i=0; i<info_msg.thumbs.length; i++){
-			var li = document.createElement("LI");
-			li.innerHTML += info_msg.thumbs[i];
-			ul_thumbs_list.appendChild(li);
-		}
+	                var msg = info_msg.msg_number; 
+	                var fdr = info_msg.msg_folder; 
+					var i = 0;
+				//verifica se está no novo padrão de montagem das mensagens ou no antigo, necessário
+				//para exibir as imagens no arquivamento local arquivamento local.
+				if(thumbs){
+	                jQuery.each(thumbs, function(i, thumb) {
+							if(fdr.indexOf("local_") >= 0){
+								var href = info_msg.array_attach[i].url + '&image=true'; 
+								var src  = info_msg.array_attach[i].url+ '&image=thumbnail'; 
+								i++;
+							}else{
+								var href = './inc/get_archive.php?msgFolder=' + fdr + '&msgNumber=' + msg + '&indexPart=' + thumb.pid + '&image=true'; 
+								//var href = thumb.url; 
+								var src  = 'inc/get_archive.php?msgFolder=' + fdr + '&msgNumber=' + msg + '&indexPart=' + thumb.pid + '&image=thumbnail'; 
+	                        }
+	                        var msgid= fdr+";;"+msg+";;"+i+";;"+thumb.pid+";;"+thumb.encoding; 
+	                        var image_info = '{"folder":"'+fdr+'","message":"'+msg+'","thumbIndex":"'+i+'","pid":"'+thumb.pid+'","encoding":"'+thumb.encoding+'","type":"'+thumb.type+'"}'; 
+	                         
+	                        var image= '<img id="' + msgid + '" title="' +  
+	                                                        get_lang('Click here do view (+)') + '" src="' + src + '" style="width:auto;height:100%;" />'; 
+	                                                 
+	                        var content = '<a title="'+thumb.name+ '" rel="thumbs'+ID+'" class="expressomail-thumbs-link" onMouseDown="save_image(event,this,\'' +thumb.type+'\')" href="'+href+'" onclick="window.open(\''+href+'\',\'mywindow\',\'width=700,height=600,scrollbars=yes\');return false;">'+image+'</a>'; 
+	                        content += '<input id="thumb_'+ID+'_'+i+'" type="hidden" value="' +escape(image_info) +'" />'; 
+	                        jQuery(ul_thumbs_list).append('<li>'+content+'</li>'); 
+	                         
+	                });    
 		
 		div_thumbs.appendChild(div_thumbs_lbl);
 		div_thumbs.appendChild(div_thumbs_lbl_sp2);
 		div_thumbs.appendChild(ul_thumbs_list);
+		
+				}else{
+					div_thumbs.appendChild(div_thumbs_lbl);
+					div_thumbs.appendChild(div_thumbs_lbl_sp2);
+					div_thumbs.innerHTML = div_thumbs.innerHTML + info_msg.thumbs;
+					
+					
+				}
 		
 		div.appendChild(div_thumbs);
@@ -2560,5 +2806,4 @@
 	}
 
-	//k!
 	/*
 	 * TODO: implementar o controle como preferência do usuário
@@ -2566,24 +2811,44 @@
 	 */
 	var jcarousel = false;
-	
 	if (jcarousel) {
+		//carousel 
 		jQuery(document).ready(function() {
-			jQuery('.expressomail-thumbs-list').attr('id', 'expressomail-thumbs-list'+ID);
-			jQuery('.expressomail-thumbs-list').addClass('jcarousel-skin-default');
-			jQuery('#expressomail-thumbs-list'+ID).jcarousel({
-				// Configuration
-			});
-		});
+	 		jQuery('.expressomail-thumbs-list').attr('id', 'expressomail-thumbs-list'+ID) 
+	 	    .addClass('jcarousel-skin-default').jcarousel(); 
+
+			jQuery('.expressomail-thumbs-link img').attr('style', ''); 
 		
 		//fancybox
-		jQuery(document).ready(function() {
 			jQuery(".expressomail-thumbs-list li a").attr('onclick', 'return true;');
 			jQuery(".expressomail-thumbs-list li a").fancybox({
 				'hideOnContentClick': true,
-				'type': 'image'
+					'type': 'image', 
+					'titlePosition': 'over',                                         
+					'titleFormat' : function(name, currentArray, currentIndex, currentOpts) {                        
+							var image_info = $('#thumb_'+ID+'_'+currentIndex).val(); 
+
+							return '<div id="fancybox-title" class="fancybox-title-over" style="width: 100%; display: block;">' + 
+										'<div id="fancybox-title-over">' + 
+											'<a title="Anterior" onclick="javascript:$.fancybox.prev();" style="float:left;">' + 
+													'<img src="./templates/'+template+'/images/left_arrow_white.png" width="30" height="30" />' + 
+											'</a>'+ 
+											'<a title="Baixar imagem" onclick="javascript:save_image2(\''+image_info+'\');" style="padding:0 5px;">' + 
+													'<img src="./templates/'+template+'/images/image_down.png" width="22" height="22" />' + 
+											'</a>'+ 
+											'<a title="Baixar todas de uma vez" onclick="javascript:download_all_attachments(\''+info_msg.msg_folder+"','"+info_msg.msg_number+'\')" style="padding:0 5px;">'+ 
+													'<img src="./templates/'+template+'/images/package_down.png" width="26" height="26" />' + 
+											'</a>'+ 
+											'<span style="margin-left:5px; margin-top:7px; position:absolute;">'+name+'</span>'+ 
+											'<a title="Próxima" onclick="javascript:$.fancybox.next();" style="float:right;">' + 
+												'<img src="./templates/'+template+'/images/right_arrow_white.png" width="30" height="30" />' + 
+											'</a>' + 
+										'</div>' + 
+									'</div>'; 
+					} 
 			});
 		});
-}
-	//k!!
+	}
+	
+    resizeWindow(); 
 }
  
@@ -2630,5 +2895,4 @@
 function draw_new_message(border_ID){
 	connector.loadScript("color_palette");
-	connector.loadScript("rich_text_editor");
 	connector.loadScript('wfolders');
 	if(typeof(RichTextEditor) == 'undefined' || typeof(ColorPalette) == 'undefined' || typeof(wfolders) == 'undefined')
@@ -2638,4 +2902,6 @@
 	if (ID == 0)
 		return 0;
+	else if(ID == 'maximo')
+		return 'maximo';
 	hold_session = true;
 
@@ -2675,6 +2941,6 @@
 
 	if ((preferences.save_in_folder == '-1') || (preferences.save_in_folder == '')){
-		//var option_send = '<span class="message_options" onclick=send_message("'+ID+'","null","null");>'+get_lang("Send")+'</span> | ';
-		var option_send   = '<input type="button" id="send_button_'+ID+'" class="em_button_like_span" tabindex="1" value="'+get_lang("Send and not file")+'" onclick=send_message("'+ID+'","null","null");>' + ' | ';
+		var option_send = '<span id="send_button_'+ID+'" class="message_options" onclick=send_message("'+ID+'","null","null");>'+get_lang("Send")+'</span> | ';
+		//var option_send   = '<input type="button" id="send_button_'+ID+'" class="em_button_like_span" tabindex="1" value="'+get_lang("Send and not file")+'" onclick=send_message("'+ID+'","null","null");>' + ' | ';
 		if(!expresso_offline)
 			var option_send_and_file= '<span class="message_options" onclick=wfolders.makeWindow("'+ID+'","send_and_file");>'+get_lang("Send and file")+'</span> | ';
@@ -2683,6 +2949,6 @@
 	}
 	else{
-		//var option_send = '<span class="message_options" onclick="send_message(\''+ID+'\',\''+preferences.save_in_folder+'\',\'null\');">'+get_lang("Send")+'</span> | ';
-		var option_send   = '<input type="button" id="send_button_'+ID+'" class="em_button_like_span" tabindex="1" value="'+get_lang("Send")+'" onclick="send_message(\''+ID+'\',\''+preferences.save_in_folder+'\',\'null\');">' + ' | ';
+		var option_send = '<span id="send_button_'+ID+'" class="message_options" onclick="send_message(\''+ID+'\',\''+preferences.save_in_folder+'\',\'null\');">'+get_lang("Send")+'</span> | ';
+		//var option_send   = '<input type="button" id="send_button_'+ID+'" class="em_button_like_span" tabindex="1" value="'+get_lang("Send")+'" onclick="send_message(\''+ID+'\',\''+preferences.save_in_folder+'\',\'null\');">' + ' | ';
 		var option_send_and_file='';
 		wfolders.alert = true;
@@ -2797,5 +3063,7 @@
         var img_search = document.createElement("IMG");
 	img_search.src = "./templates/"+template+"/images/search.gif";
-	img_search.onclick = function () {emQuickSearch(document.getElementById('replyto_'+ID).value, 'replyto', ID)}
+	img_search.onclick = function () {
+            emQuickSearch(document.getElementById('replyto_'+ID).value, 'replyto', ID)
+        }
 	img_search.title = get_lang('Search') + " | " + get_lang('Use F9 Key as shortcut.');
         var span_search = document.createElement("SPAN");
@@ -2887,5 +3155,7 @@
 		img_search.src = "./templates/"+template+"/images/search.gif";
 		img_search.title = get_lang('Search') + " | " + get_lang('Use F9 Key as shortcut.');
-		img_search.onclick = function () {emQuickSearch(document.getElementById('to_'+ID).value, 'to', ID);};
+                img_search.onclick = function () {
+                    emQuickSearch(document.getElementById('to_'+ID).value, 'to', ID);
+                };
 	}
 	else {
@@ -2974,5 +3244,7 @@
 	var img_search = document.createElement("IMG");
 	img_search.src = "./templates/"+template+"/images/search.gif";
-	img_search.onclick = function () {emQuickSearch(document.getElementById('cc_'+ID).value, 'cc', ID)}
+	img_search.onclick = function () {            
+            emQuickSearch(document.getElementById('cc_'+ID).value, 'cc', ID)
+        }
 	img_search.title = get_lang('Search') + " | " + get_lang('Use F9 Key as shortcut.');
 	var span_search = document.createElement("SPAN");
@@ -3062,5 +3334,7 @@
 	img_search.src = "./templates/"+template+"/images/search.gif";
 	img_search.title = get_lang('Search') + " | " + get_lang('Use F9 Key as shortcut.');
-	img_search.onclick = function () {emQuickSearch(document.getElementById('cco_'+ID).value, 'cco', ID);};
+ 		            img_search.onclick = function () {
+                                emQuickSearch(document.getElementById('cco_'+ID).value, 'cco', ID);
+                            }; 
 	var span_search = document.createElement("SPAN");
 	span_search.innerHTML = get_lang('Search');
@@ -3090,17 +3364,12 @@
 	a_cc_link.setAttribute("href","javascript:void(0)");
 	a_cc_link.setAttribute("tabIndex","-1");
-	a_cc_link.onclick = function () {this.style.display='none';document.getElementById('tr_cc_'+ID).style.display='';document.getElementById('space_link_'+ID).style.display='none';input_cc.focus();return false;}
+	a_cc_link.onclick = function () {
+		this.style.display='none';
+		document.getElementById('tr_cc_'+ID).style.display='';
+		if(document.getElementById('space_link_'+ID) !== null)
+			document.getElementById('space_link_'+ID).style.display='none';
+		input_cc.focus();
+		return false;};
 	td2_link.appendChild(a_cc_link);
-	var space = document.createElement("span");
-	space.id ="space_link_"+ID;
-	space.innerHTML="&nbsp;|&nbsp;";
-	td2_link.appendChild(space);
-	var a_cco_link = document.createElement('A');
-	a_cco_link.innerHTML = get_lang('Add BCC');
-	a_cco_link.id = "a_cco_link_"+ID;
-	a_cco_link.setAttribute("href","javascript:void(0)");
-	a_cco_link.setAttribute("tabIndex","-1");
-	a_cco_link.onclick = function () {this.style.display='none';document.getElementById('tr_cco_'+ID).style.display='';document.getElementById('space_link_'+ID).style.display='none';input_cco.focus();return false;}
-	td2_link.appendChild(a_cco_link);
 	var space = document.createElement("span");
 	
@@ -3115,5 +3384,11 @@
  		            a_cco_link.setAttribute("href","javascript:void(0)"); 
  		            a_cco_link.setAttribute("tabIndex","-1"); 
- 		            a_cco_link.onclick = function () {this.style.display='none';document.getElementById('tr_cco_'+ID).style.display='';document.getElementById('space_link_'+ID).style.display='none';input_cco.focus(); return false;} 
+            a_cco_link.onclick = function () {
+		this.style.display='none';
+		document.getElementById('tr_cco_'+ID).style.display='';
+		if(document.getElementById('space_link_'+ID) !== null)
+			document.getElementById('space_link_'+ID).style.display='none';
+			input_cco.focus();
+			return false;}; 
  		            td2_link.appendChild(a_cco_link); 
  		        }
@@ -3151,146 +3426,48 @@
 //////////////////////////////////////////////////////////////////////////////////////////////////////
 	var tr5 = document.createElement("TR");
-	var td5 = document.createElement("TD");
-	td5.innerHTML = "&nbsp;";
-	var td_return_receipt = document.createElement("TD");
-	td_return_receipt.setAttribute("noWrap","true");
-	td_return_receipt.innerHTML = get_lang("Return receipt")+":";
-		if (is_ie)
-		{
-			var input_return_receipt = document.createElement('input name=input_return_receipt');
-		}
-		else
-		{
-			var input_return_receipt = document.createElement('input');
-			input_return_receipt.name = "input_return_receipt";
-		}
-	input_return_receipt.type = "checkbox";
-	input_return_receipt.className = "checkbox";
-	input_return_receipt.id = "return_receipt_"+ID;
-
-        if(preferences.return_recipient_deafault != '0'){
-             if (is_ie){
-        	input_return_receipt.checked=true;
-             }
-             else{
-                input_return_receipt.defaultChecked=true;
-             }
-        }
-
-	input_return_receipt.setAttribute("tabIndex","-1");
-	td_return_receipt.appendChild(input_return_receipt);
-
-	// Workaround para resolver problema ao enviar e-mails
-	if((preferences.use_assinar_criptografar != '0'))
-	{
-		if(parseInt(preferences.use_signature_digital_cripto)==1)
-		{
-			td_return_receipt.innerHTML +=  "&nbsp;&nbsp;" + get_lang("Digitally sign message?")+"";
-
-			if (is_ie)
-			{
-				var input_return_digital = document.createElement('input name=input_return_digital');
-			}
-			else
-			{
-			var input_return_digital = document.createElement('input');
-				input_return_digital.name = "input_return_digital";
-			}
-
-			input_return_digital.type = "checkbox";
-			input_return_digital.className = "checkbox";
-			input_return_digital.id = "return_digital_"+ID;
-			input_return_digital.setAttribute("tabIndex","-1");
-			if(parseInt(preferences.use_signature_digital)==1)
-			{
-                            if (is_ie)
+	var td_content = '';
+
+	if((preferences.use_assinar_criptografar != '0')) {
+		if(parseInt(preferences.use_signature_digital_cripto)==1) {
+			var input_return_digital_chk = (parseInt(preferences.use_signature_digital)==1) ? 'checked="checked"' : '';
+			var input_return_digital = '<input type="checkbox" class="checkbox" name="input_return_digital" id="return_digital_'+ID+'" tabIndex="-1" '+input_return_digital_chk+' />';
+			var label_return_digital = '<label for="return_digital_'+ID+'">'+get_lang("Digitally sign message?")+'</label>';
+
+			td_content += input_return_digital + label_return_digital;
+
+			var input_return_cripto_chk = (parseInt(preferences.use_signature_cripto)==1) ? 'checked="checked"' : '';
+			var input_return_cripto = '<input type="checkbox" class="checkbox" name="input_return_cripto" id="return_cripto_'+ID+'" tabIndex="-1" '+input_return_cripto_chk+' />';
+			var label_return_cripto = '<label for="return_cripto_'+ID+'">'+get_lang("Digitally crypt message?")+'</label>';
+
+			td_content += input_return_cripto + label_return_cripto;
+                            }
+			}
+
+	var input_return_receipt_chk = (preferences.return_recipient_deafault != '0') ? 'checked="checked"' : '';
+	var input_return_receipt = '<input type="checkbox" class="checkbox" name="input_return_receipt" id="return_receipt_'+ID+'" tabIndex="-1" '+input_return_receipt_chk+' />';
+	var label_return_receipt = '<label for="return_receipt_'+ID+'">'+get_lang("Return receipt")+'</label>';
+
+	td_content += input_return_receipt + label_return_receipt;
+
+	if (parseInt(preferences.use_important_flag))
                             {
-				input_return_digital.checked=true;
-                            }
-                            else
-                            {
-                                input_return_digital.defaultChecked=true;
-                            }
-			}
-			td_return_receipt.appendChild(input_return_digital);
-			td_return_receipt.innerHTML +=  "&nbsp;&nbsp;" + get_lang("Digitally crypt message?")+"";
-
-			if (is_ie)
-			{
-				var input_return_cripto = document.createElement('input name=input_return_cripto');
-			}
-			else
-			{
-			var input_return_cripto = document.createElement('input');
-				input_return_cripto.name = "input_return_cripto";
-			}
-
-			input_return_cripto.type = "checkbox";
-			input_return_cripto.className = "checkbox";
-			input_return_cripto.id = "return_cripto_"+ID;
-			input_return_cripto.setAttribute("tabIndex","-1");
-			input_return_cripto.defaultChecked=false;
-
-			if(parseInt(preferences.use_signature_cripto)==1)
-			{
-                            if (is_ie)
-                            {
-				input_return_cripto.checked=true;
-                            }
-                            else
-                            {
-				input_return_cripto.defaultChecked=true;
-                            }
-			}
-
-			td_return_receipt.appendChild(input_return_cripto);
-		}
-	}
-	td_return_receipt.innerHTML += "";
-	tr5.appendChild(td5);
-	tr5.appendChild(td_return_receipt);
-
-        if ( ! expresso_offline )
-	{
-		var text_plain = td_return_receipt.appendChild(
-			document.createElement( 'span' )
-		).appendChild(
-			document.createTextNode( ' | ' )
-		).parentNode.appendChild(
-			document.createTextNode( get_lang('Send this mail as text plain') + '.')
-                ).parentNode.appendChild(
-                        document.createElement( 'input' )
-		);
-                text_plain.setAttribute( 'tabIndex', '-1' );
-                text_plain.id = 'textplain_rt_checkbox_' + ID ;
-                text_plain.type = "checkbox";
-                text_plain.onclick = function ()
-		{
-		RichTextEditor.setPlain( this.checked, ID );
-		};
+		var input_important = '<input type="checkbox" class="checkbox" id="important_message_'+ID+'" name="input_important_message" tabIndex="-1"/>';
+		var label_important = '<label for="important_message_'+ID+'">'+get_lang("Important message")+'</label>';
+		//jQuery(tbody_message).append('<tr><td> </td><td>'+input_important+label_important+'</td</tr>');
+
+		td_content += input_important + label_important;
+	}
+
+	if (!expresso_offline) {
+		var onclk_text_plain = 'javascript:RichTextEditor.setPlain(this.checked, '+ID+');';
+		var input_text_plain = '<input type="checkbox" class="checkbox" name="textplain_rt_checkbox" id="textplain_rt_checkbox_'+ID+'" tabIndex="-1" onclick="'+onclk_text_plain+'"/>';
+		var label_text_plain = '<label for="textplain_rt_checkbox_'+ID+'">'+get_lang('Simple text mode')+'</label>';
 			
-	}
-
+		td_content += input_text_plain + label_text_plain;
+	}
+
+	jQuery(tr5).append('<td>&nbsp;</td><td class="message-general-options">'+td_content+'</td>');
 	
 	tbody_message.appendChild(tr5);
-	if (parseInt(preferences.use_important_flag))
-	{
-		var trn = document.createElement("TR");
-		var tdn = document.createElement("TD");
-		tdn.innerHTML = "&nbsp;";
-		var td_important_msg = document.createElement("TD");
-		td_important_msg.setAttribute("noWrap","true");
-		td_important_msg.innerHTML = get_lang("Important message")+":";
-		var input_important_message = document.createElement('input');
-		input_important_message.type = "checkbox";
-		input_important_message.className = "checkbox";
-		input_important_message.id = "important_message_"+ID;
-		input_important_message.name = "input_important_message";
-		input_important_message.setAttribute("tabIndex","-1");
-		td_important_msg.appendChild(input_important_message);
-		trn.appendChild(tdn);
-		trn.appendChild(td_important_msg);
-		tbody_message.appendChild(trn);
-	}
 
         /**
@@ -3319,6 +3496,52 @@
 	add_files.innerHTML =  get_lang("Attachments: add+");
 	add_files.setAttribute("tabIndex","-1");
+	
+	var add_msgs = document.createElement("A");
+	add_msgs.setAttribute("href", "javascript:void(0)");
+	is_ie ? add_msgs.setAttribute("className", 'message-attach-link') : add_msgs.setAttribute("class", 'message-attach-link');
+	add_msgs.innerHTML =  get_lang("Messages: add+");
 	var divfiles = document.createElement("DIV");
 	divfiles.id = "divFiles_"+ID;
+
+	jQuery(add_msgs).click(function(event){
+		jQuery('#message-attach-dialog').html("../prototype/modules/attach_message/attach_message.ejs", {data:{}}).dialog({
+			width:920,
+			height:550,
+			resizable:false,
+			modal: true,
+			closeOnEscape:true,
+			close:function(event, ui) {event.stopPropagation();},
+			autoOpen:false
+		});
+		jQuery.getScript("../prototype/modules/attach_message/attach_message.js", function(){
+			jQuery('#message-attach-dialog').dialog('open');
+			
+			jQuery('#message-attach-attach-btn').click(function(event){
+				//alert(dump(selectedMessages));../
+				jQuery.each(selectedMessages, function(folder_name, messages) {
+				  
+					var isOffline = /^local_messages/.test(folder_name);
+
+					jQuery.each(selectedMessages[folder_name], function(message_number, message) { 
+						if (message) {
+							var subject = onceOpenedMessages[folder_name][message_number].subject;
+							var text_input  = '<input type="text" name="message_attachments['+folder_name+']['+message_number+']" value="'+subject+'"/>';
+							    text_input += '<a href="javascript:void(0)" onclick="javascript:this.parentNode.parentNode.removeChild(this.parentNode);">' + get_lang("Remove")+'</a>';
+
+							    if( isOffline )
+								text_input += '<input type="hidden" name="message_attachments_content['+folder_name+']['+message_number+']" value="'+Base64.encode( onceOpenedMessages[folder_name][message_number].eml )+'"/>';
+							jQuery(divfiles).append('<div>'+text_input+'</div>');
+						}
+
+					});
+				});
+				
+				jQuery('#message-attach-dialog').dialog('close');
+			});
+			jQuery('#message-attach-cancel-btn').click(function(event){
+				jQuery('#message-attach-dialog').dialog('close');
+			});
+		});
+	});
 	var tr5 = document.createElement("TR");
 	var td5_link = document.createElement("TD");
@@ -3328,4 +3551,6 @@
 	td5_link.setAttribute("colSpan","2");
 	td5_link.appendChild(add_files);
+	td5_link.appendChild(add_msgs);
+	$(td5_link).append('<div id="message-attach-dialog" title="'+get_lang('Select messages to attach...')+'"> </div>');
 	tr5.appendChild(td5_input);
 	tr5.appendChild(td5_link);
@@ -3426,14 +3651,17 @@
 		if(data.length > 0) {
 			tr1_1.style.display = '';
+                        var mycn = typeof(data.myname != 'undefined') ? data.myname : '';
 			var _option = document.createElement("OPTION");
-			_option.text =  '"'+data.myname+'" <'+Element("user_email").value+'>';
-			_option.value  = data.myname+";"+Element("user_email").value;
+			_option.text =  '"'+mycn+'" <'+Element("user_email").value+'>';
+			_option.value  = mycn+";"+Element("user_email").value;
 			sel_from.options[sel_from.options.length] = _option;
 
 			var options = '';
+                        var cn = '';
 			for (var x = 0; x < data.length; x++)	{
+                                cn = typeof(data[x].cn[0] != 'undefined') ? data[x].cn[0] : '';
 				var _option = document.createElement("OPTION");
-				_option.text = '"'+data[x].cn[0] + '" <'+data[x].mail[0]+'>';
-				_option.value = data[x].cn[0] + ';'+data[x].mail[0]+';'+data[x].save_shared[0]+';'+data[x].uid[0];
+				_option.text = '"'+cn+'" <'+data[x].mail[0]+'>';
+				_option.value = cn+';'+data[x].mail[0]+';'+data[x].save_shared[0]+';'+data[x].uid[0];
 				sel_from.options[sel_from.options.length] = _option	;
 			}
@@ -3452,8 +3680,11 @@
 
 function changeBgColorToON(all_messages, begin, end){
+	var _tab_prefix = getTabPrefix();
+	var _msg_id;
 	for (begin; begin<=end; begin++)
 	{
+		_msg_id = getMessageIdFromRowId(all_messages[begin].id);
 		add_className(all_messages[begin], 'selected_msg');
-		Element("check_box_message_" + all_messages[begin].id).checked = true;
+		Element(_tab_prefix + "check_box_message_" + _msg_id).checked = true;
 	}
 }
@@ -3502,8 +3733,19 @@
 	else{
 		//if ( exist_className(actual_tr, 'selected_msg') )
-		if ( Element('check_box_message_' + _element_id).checked )
+		if ( document.getElementById(getTabPrefix()+'check_box_message_' + msg_number).checked ){
+			if( document.getElementById("chk_box_select_all_messages").checked) {
+				add_className(actual_tr, 'selected_msg selected_shortcut_msg'); 
+			}else
 			add_className(actual_tr, 'selected_msg');
-		else
+		}else{
+			if( document.getElementById("chk_box_select_all_messages").checked){
+				remove_className(actual_tr, 'selected_msg selected_shortcut_msg');
+				remove_className(actual_tr, 'selected_msg');
+				remove_chk_box_select_all_messages();
+				if(actual_tr.className == 'selected_msg')
 			remove_className(actual_tr, 'selected_msg');
+			}else
+				remove_className(actual_tr, 'selected_msg');
+		}
 	}
 	last_message_selected = _element_id;
Index: trunk/expressoMail1_2/js/doiMenuData.js
===================================================================
--- trunk/expressoMail1_2/js/doiMenuData.js	(revision 3388)
+++ trunk/expressoMail1_2/js/doiMenuData.js	(revision 5134)
@@ -18,5 +18,5 @@
 		if(preferences.use_local_messages==1) {
 			if(expresso_local_messages.is_offline_installed()) {
-				itens.push("force_check_queue()|" + get_lang("Send from queue") + "|queue.jpg");
+				itens.push("force_check_queue()|" + get_lang("Send from queue") + "|queue.png");
 			}
 		}
Index: trunk/expressoMail1_2/js/DropDownContacts.js
===================================================================
--- trunk/expressoMail1_2/js/DropDownContacts.js	(revision 4304)
+++ trunk/expressoMail1_2/js/DropDownContacts.js	(revision 5134)
@@ -79,5 +79,9 @@
 	var REG_EXP = /^[^\#|^\$|^\%|^\!|^\?|^\"|^\']+$/;
 	var match_cont = "";
-	for (var i=0; i<match_contacts.length; i++)
+	var limit_index;
+	
+	match_contacts.length > 30? limit_index = 30 : limit_index = match_contacts.length; 
+	
+	for (var i=0; i<limit_index; i++)
 	{
 		match_contacts[i] = unescape(match_contacts[i]); 
@@ -95,9 +99,8 @@
 	}
 
-	
-	if (document.getElementById('tipDiv')){ 
-		document.getElementById('tipDiv').focus(); 
- 	} 
-
+    //Removido pois retirava o focus no ie	a cada letra digitada
+	//if (document.getElementById('tipDiv')){ 
+	//	document.getElementById('tipDiv').focus(); 
+ 	//} 
 
 	// treat especials keys
Index: trunk/expressoMail1_2/js/lert/lert.css
===================================================================
--- trunk/expressoMail1_2/js/lert/lert.css	(revision 3977)
+++ trunk/expressoMail1_2/js/lert/lert.css	(revision 5134)
@@ -24,5 +24,5 @@
 	font-weight:normal;
 	font-size:1em;
-	font-family: Tahoma, Verdana, Sans;
+	//font-family: Tahoma, Verdana, Sans;
 	border:4px double #aaa;
 	width:40%;
Index: trunk/expressoMail1_2/js/QuickCatalogSearch.js
===================================================================
--- trunk/expressoMail1_2/js/QuickCatalogSearch.js	(revision 5075)
+++ trunk/expressoMail1_2/js/QuickCatalogSearch.js	(revision 5134)
@@ -7,4 +7,5 @@
 	}
         
+	/* showlist */	
 	emQuickCatalogSearch.prototype.showList = function(data, begin, end, ID, field)
 	{
@@ -16,14 +17,8 @@
 
 			keypress_read(data);
-            init_results(data);
             configure_slider(data);
+		create_list(data, true);
             details_results(data);
 			
-  		    connector.loadScript("ccQuickAdd");
-
-            if(preferences.use_shortcuts == '0'){
-                connector.loadScript("shortcut");
-            }
-		
 		id = '1';
 		_this = this;
@@ -46,180 +41,108 @@
         
         
-    function keypress_read(data) 
-	{
-		$("#dialog-modal").keypress(function (e) 
-		{
-			var keyCode = e.keyCode || e.which,
-			arrow = {left: 37, up: 38, right: 39, down: 40, enter: 13, esc: 27 };
+    /* Leitura das teclas de atalho */    
+    function keypress_read(data) {	
+		$("#dialog-modal").keydown(function (e) {
+			var keyCode = e.keyCode;
+			arrow = {left: 37, up: 38, right: 39, down: 40, enter: 13, esc: 27};
 			var slider = $( "#slider"  );
 			switch (keyCode) 
 			{
 				case arrow.enter:
-					add_contact_field(document.getElementsByClassName("ui-selected")[0].getElementsByClassName("name_contact")[0].innerHTML);
+					if(!search_focus){
+						i = $(".ui-selected:last").attr("value") + 1;
+						add_contact_field($("#contact_" + i).html());
+						document.getElementById("busca").value = "";
+						$("#dialog-modal").unbind('keydown');
 					$("#dialog-modal").dialog("close");
+					}
 					break;
-				
 				case arrow.left:
-					slider.slider( "value", $( "#slider" ).slider( "value" ) - 1);
-					create_list(data_);					
+					slider.slider("value", $( "#slider" ).slider( "value" ) - 1);
+					create_list(data_, false);		
 					break;
-				
 				case arrow.right:
-					if( (($( "#slider" ).slider( "value" ))) == Math.ceil(data_.length/7) )
-					{
-						alert("Não há mais páginas");
+					if((($( "#slider" ).slider( "value" ))) == Math.ceil(data_.length/6))
 						break;
-					}
 					slider.slider( "value", $( "#slider" ).slider( "value" ) + 1);					
-					create_list(data_);						
+					create_list(data_, false);							
 					break;
-				
 				case arrow.up:
-					id_contact = document.getElementsByClassName("ui-selected")[0].value;
-					if(id_contact == (($( "#slider" ).slider( "value" ) -1)*7))
+					show_detail(data_, "up");
+					break;
+				case arrow.down:
+					show_detail(data_, "down");
 						break;
-					var line_contact = $('li.ui-selected');
-					$('li.ui-selected').prev().removeClass("ui-selectee").addClass("ui-selected"); //css('background-color', '#72A9D3');
-					line_contact.removeClass("ui-selected").addClass("ui-selectee");
-					var details = $("#detalhes_contato").empty();                                 
-						$( ".ui-selected", this ).each(function() {
-                            if(data_['type_catalog'] == 'G')
-                            {                                         
-                                var extra_fields = (data_['extra_ldap_fields']).split("#");   
-                                /* Default fields */
-                                details.append("<strong>" + utf8_decoder(data_[this.value].cn[0]));
-                                details.append("<br />" + data_[this.value].mail[0]);
-                                details.append("<br /><br /><strong>Matrícula<br />");
-                                details.append(data_[this.value].employeenumber[0] + "<br />");
-                                details.append("<br /><strong> Telefone <br />");
-                                details.append(data_[this.value].telephonenumber[0] + "<br />");
-                                details.append(data_[this.value].telephonenumber[0]);
-                                for (var i=0; i<extra_fields.length-1; i++)
-                                {
-                                    var campo = extra_fields[i].substr(extra_fields[i].indexOf("|")+1);    
-                                    var valor = extra_fields[i].substr(0, (extra_fields[i].indexOf("|")));                                          
-                                    if(data_[this.value][valor] != undefined)
-                                    {    
-                                        details.append("<br /><br /><strong>" + campo);
-                                        details.append("<br />" + data_[this.value][valor][0]);
-                                    }
                                 }
+		});	
 							}
-                            else
-                            {
-                                    if(data_['type_catalog'] == 'P')
-                                    {
-                                        /* Default fields */
-                                        details.append("<strong>" + utf8_decoder(data_[this.value].cn));
-                                        details.append("<br />" + data_[this.value].mail);
-                                        if(data_[this.value].telephonenumber != "")
-                                        {
-                                            details.append("<br /><br /><br /><strong> Telefone <br />");
-                                            details.append(data_[this.value].telephonenumber + "<br />");  
+	
+	
+	/* Mostra os detalhes do contato selecionado */
+	function show_detail(data_, direction) {
+		id_contact = $(".ui-selected:last").attr("value");
+		if(direction == "down") {
+			if((id_contact == (((((parseInt($( "#slider" ).slider( "value" )) - 1)*6))+6)-1)) || id_contact == data_.length - 1 || data_.length == 1)
+				return;	
+			var line_contact = $('li.ui-selected');
+			$('li.ui-selected').next().addClass("ui-selected"); 
+			id_contact++;
                                         }
+		else {
+			if(id_contact == (($( "#slider" ).slider( "value" ) -1)*6)) 
+				return;
+			var line_contact = $('li.ui-selected');
+			$('li.ui-selected').prev().addClass("ui-selected"); 
+			id_contact--;
                                     } 
-                                    else
-                                    {
+		line_contact.removeClass("ui-selected").addClass("ui-selectee");
+		var details = $("#detalhes_contato").empty();                                 
+		switch(data_['type_catalog']) {
+			case 'G':
                                         var extra_fields = (data_['extra_ldap_fields']).split("#");   
-                                        /* Default fields */
-                                        details.append("<strong>" + utf8_decoder(data_[this.value].cn));
-                                        details.append("<br />" + data_[this.value].mail);
-                                        if(data_[this.value].telephonenumber != "")
-                                        {
-                                            details.append("<br /><br /><br /><strong> Telefone <br />");
-                                            details.append(data_[this.value].telephonenumber + "<br />");  
+				if(preferences.default_fields_quick_search != 0) {
+					details.append('<p><label class="attribute">' + utf8_decoder(data_[id_contact].cn[0]) + "</label>" + '<span class="value">' + data_[id_contact].mail[0] + '</span></p>');
+					details.append('<p><label class="attribute">Telefone </label>' + '<span class="value">' + data_[id_contact].telephonenumber[0] + '</span></p>');           
                                         }
-                                        if(data_[this.value].mail[0].length > 1) 
-                                        {
-                                            for (var i=0; i<extra_fields.length-1; i++)
+				for (var i=0; i<=extra_fields.length-1; i++)
                                             {
                                                 var campo = extra_fields[i].substr(extra_fields[i].indexOf("|")+1);    
                                                 var valor = extra_fields[i].substr(0, (extra_fields[i].indexOf("|")));                                          
-                                                if(data_[this.value][valor] != undefined)
-                                                {    
-                                                    details.append("<br /><br /><strong>" + campo);
-                                                    details.append("<br />" + data_[this.value][valor][0]);
+					if(data_[id_contact][valor.toLowerCase()] != undefined) {
+						var tmp_campo = '<p><label class="attribute">' + campo + "</label>" ;
+						for(j=0; j<data_[id_contact][valor.toLowerCase()].length; j++) {
+							details.append(tmp_campo + '<span class="value">' + data_[id_contact][valor.toLowerCase()][j] + "</span></p>");
+							tmp_campo = "";
+                                            }
+                                        }
+                                    }
+					break;
+			case 'P':
+				details.append('<p><label class="attribute">' + utf8_decoder(data_[id_contact].cn) + '</label>' + '<span class="value">' + data_[id_contact].mail + '</span></p>');
+                if(data_[id_contact].telephonenumber != null)
+                    details.append('<p><label class="attribute">Telefone</label>' + '<span class="value">' + data_[id_contact].telephonenumber + '</span></p>');
+						break;	
+			default:
+                                var extra_fields = (data_['extra_ldap_fields']).split("#");   
+                if(preferences.default_fields_quick_search != 0 || data_[id_contact].type_contact == "P") {
+					details.append('<p><label class="attribute">' + utf8_decoder(data_[id_contact].cn) + '</label>' + '<span class="value">' + data_[id_contact].mail + '</span></p>');
+					if(data_[id_contact].telephonenumber != null)
+						details.append('<p><label class="attribute">Telefone</label>' + '<span class="value">' + data_[id_contact].telephonenumber + '</span></p>');
+							}
+				if(data_[id_contact].mail[0].length > 1) {
+					for (var i=0; i<=extra_fields.length-1; i++) {
+                                                var campo = extra_fields[i].substr(extra_fields[i].indexOf("|")+1);    
+                                                var valor = extra_fields[i].substr(0, (extra_fields[i].indexOf("|")));                                          
+						if(data_[id_contact][valor.toLowerCase()] != undefined) {
+							var tmp_campo = '<p><label class="attribute">' + campo + "</label>" ;
+							for(j=0; j<data_[id_contact][valor.toLowerCase()].length; j++) {
+								details.append(tmp_campo + '<span class="value">' + data_[id_contact][valor.toLowerCase()][j] + "</span></p>");
+								tmp_campo = "";
                                                 }
                                             }
                                         }
                                     }
-                            }
-						});
-					break;
-				
-				case arrow.down:
-					id_contact = document.getElementsByClassName("ui-selected")[0].value;
-					if((id_contact == (((((parseInt($( "#slider" ).slider( "value" )) - 1)*7))+7)-1)) || id_contact == data_.length - 2 || data_.length == 1)
-						break;	
-					var line_contact = $('li.ui-selected');
-					$('li.ui-selected').next().removeClass("ui-selectee").addClass("ui-selected"); 
-					line_contact.removeClass("ui-selected").addClass("ui-selectee");
-					var details = $("#detalhes_contato").empty();                                 
-                        $( ".ui-selected", this ).each(function() {
-                            if(data_['type_catalog'] == 'G')
-                            {                                         
-                                var extra_fields = (data_['extra_ldap_fields']).split("#");   
-                                /* Default fields */
-                                details.append("<strong>" + utf8_decoder(data_[this.value].cn[0]));
-                                details.append("<br />" + data_[this.value].mail[0]);
-                                details.append("<br /><br /><strong>Matrícula<br />");
-                                details.append(data_[this.value].employeenumber[0] + "<br />");
-                                details.append("<br /><strong> Telefone <br />");
-                                details.append(data_[this.value].telephonenumber[0] + "<br />");
-                                details.append(data_[this.value].telephonenumber[0]);
-                                for (var i=0; i<extra_fields.length-1; i++)
-                                {
-                                    var campo = extra_fields[i].substr(extra_fields[i].indexOf("|")+1);    
-                                    var valor = extra_fields[i].substr(0, (extra_fields[i].indexOf("|")));                                          
-                                    if(data_[this.value][valor] != undefined)
-                                    {    
-                                        details.append("<br /><br /><strong>" + campo);
-                                        details.append("<br />" + data_[this.value][valor][0]);
-                                    }
-                                }
-							}
-                            else
-                            {
-                                    if(data_['type_catalog'] == 'P')
-                                    {
-                                        /* Default fields */
-                                        details.append("<strong>" + utf8_decoder(data_[this.value].cn));
-                                        details.append("<br />" + data_[this.value].mail);
-                                        if(data_[this.value].telephonenumber != "")
-                                        {
-                                            details.append("<br /><br /><br /><strong> Telefone <br />");
-                                            details.append(data_[this.value].telephonenumber + "<br />");  
-                                        }
-                                    } 
-                                    else
-                                    {
-                                        var extra_fields = (data_['extra_ldap_fields']).split("#");   
-                                        /* Default fields */
-                                        details.append("<strong>" + utf8_decoder(data_[this.value].cn));
-                                        details.append("<br />" + data_[this.value].mail);
-                                        if(data_[this.value].telephonenumber != "")
-                                        {
-                                            details.append("<br /><br /><br /><strong> Telefone <br />");
-                                            details.append(data_[this.value].telephonenumber + "<br />");  
-                                        }
-                                        if(data_[this.value].mail[0].length > 1) 
-                                        {
-                                            for (var i=0; i<extra_fields.length-1; i++)
-                                            {
-                                                var campo = extra_fields[i].substr(extra_fields[i].indexOf("|")+1);    
-                                                var valor = extra_fields[i].substr(0, (extra_fields[i].indexOf("|")));                                          
-                                                if(data_[this.value][valor] != undefined)
-                                                {    
-                                                    details.append("<br /><br /><strong>" + campo);
-                                                    details.append("<br />" + data_[this.value][valor][0]);
-                                                }
-                                            }
-                                        }
-                                    }
-                            }
-						});
 					break;
 			}
-		});	
 	}
 			
@@ -229,46 +152,112 @@
 		* Método que cria a lista de contatos
 		*/
-		function create_list(data)
-		{
+	function create_list(data, begin, uiValue) {
+		var sliderValue = 1;
+		if(typeof($( "#slider" ).slider( "value" )) != "object")
+			sliderValue = $( "#slider" ).slider( "value" );
+		if(uiValue)
+			sliderValue = uiValue;
 					$("#detalhes_contato").empty();
-					var paginas = Math.ceil(data.length/7) - 1; 
+		var paginas = Math.ceil(data.length/6); 
 					$("#title_usuarios").html( get_lang("Results") );
-					var string_results = $( "#slider" ).slider( "value" ) + " " + get_lang("of") + " " + paginas + " (" + data.length + " " + get_lang("Results") + ")"; 
                         var selectable = $("#selectable");
 						selectable.empty();
                         var Ul = document.createElement("ul");
+		for (i=((sliderValue -1)*6)+1; i<(((sliderValue -1)*6)+1)+6; i++) {
                         var Op = document.createElement("li");
-						for (i=(($( "#slider" ).slider( "value" ) -1)*7)+1; i<((($( "#slider" ).slider( "value" ) -1)*7)+1)+7; i++) 
-                        {
-							if(i >= data.length)
+			if(i > data.length)
 								break;
 							if (data['type_catalog'] != 'G' && (data[i-1].mail == null || data[i-1].mail == ""))
                                 data[i-1].mail = "No mail"; 
-                            if(i == ((($( "#slider" ).slider( "value" ) -1)*7)+1)){
+				
+			if(i == (((sliderValue -1)*6)+1)) {
 								Op.setAttribute("class", "ui-selected");
+				Op.setAttribute("className", "ui-selected");
 							}
 							else {	
 								Op.setAttribute("class", "ui-selectee");
+				Op.setAttribute("className", "ui-selectee");
 							}
 							var contact_name = utf8_decoder(data[i-1].cn);
-							if(contact_name.substring(contact_name.toLowerCase().indexOf(data.search_for.toLowerCase())) != -1)									
+			if(contact_name.toLowerCase().indexOf(data.search_for.toLowerCase()) != -1 && data.search_for.indexOf(" ") == -1 && data.search_for.indexOf("@") == -1)									
 								contact_name = contact_name.substring(0, contact_name.toLowerCase().indexOf(data.search_for.toLowerCase())) + "<u>" + contact_name.substr(contact_name.toLowerCase().indexOf(data.search_for.toLowerCase()), data.search_for.length) + "</u>" + contact_name.substring(contact_name.toLowerCase().indexOf(data.search_for.toLowerCase()) + data.search_for.length);
-							Op.innerHTML = '<span style="float:right; left:335px; position: absolute; z-index: 100; background-color: #EEE; padding:0"><button onClick="add_contact_field(contact_' + i + '.innerHTML)">+</button><button onClick="remove_contact_field(contact_' + i + '.innerHTML)">x</button></span><div id=contact_' + i + ' onDblClick="add_contact_field(this.innerHTML)"><div class="name_contact"><strong>' + contact_name + '</strong><em>' + utf8_decoder(data[i-1].mail) + '</em></div></div>';
+			Op.innerHTML = '<span class="menu-control"><button onClick="add_contact_field(document.getElementById(\'contact_' + i + '\').innerHTML)">+</button><button onClick="remove_contact_field(document.getElementById(\'contact_' + i + '\').innerHTML)">x</button></span><div id="contact_' + i + '" onDblClick="add_contact_field(this.innerHTML)"><div class="name_contact"><strong>' + contact_name + '</strong><em>' + utf8_decoder(data[i-1].mail) + '</em></div></div>';
                             $(Op).val(i - 1);
-                            Ul.appendChild(Op);
-                            selectable.append(Ul.innerHTML);
+            selectable.append(Op);
                         }
-                        $( "#amount" ).val( string_results );
-						$( "#amount" ).val( $( "#slider" ).slider( "value" ) + " " + get_lang("of") + " " + paginas + " (" + data.length + " " + get_lang("Results") + ")");   
-						document.getElementById("amount").focus();	
+		selectable.append(Ul);
+		var first_contact;
+		begin ? first_contact = 0 : first_contact = ((sliderValue* 6) -6);			
+		if(first_contact == 0) {
+			$(document).ready(function(){
+				$('#combobox option').each(function(){
+					if($(this).val() == preferences.catalog_search){
+						$(this).attr('selected',true);
+					}
+				});
+			});
+		}
+		var details = $("#detalhes_contato").empty();                                 
+		switch (data['type_catalog']) {
+			case 'G':
+				var extra_fields = (data['extra_ldap_fields']).split("#");   
+				if(preferences.default_fields_quick_search != 0) {  				
+					details.append('<p><label class="attribute">' + utf8_decoder(data[first_contact].cn[0]) + "</label>" + '<span class="value">' + data[first_contact].mail[0] + "</span></p>");
+					details.append('<p><label class="attribute">Telefone</label>' + '<span class="value">' + data[first_contact].telephonenumber[0] + '</span></p>');
+				}
+				for (var i=0; i<=extra_fields.length-1; i++) {
+					var campo = extra_fields[i].substr(extra_fields[i].indexOf("|")+1);    
+					var valor = extra_fields[i].substr(0, (extra_fields[i].indexOf("|")));                                          
+					if(data[0][valor.toLowerCase()] != undefined)
+					{
+						var tmp_campo = '<p><label class="attribute">' + campo + "</label>" ;
+						for(j=0; j<data[first_contact][valor.toLowerCase()].length; j++) {
+							details.append(tmp_campo + '<span class="value">' + data[first_contact][valor.toLowerCase()][j] + "</span></p>");
+							tmp_campo = "";
+						}
+					}
+				}			
+				break;
+			case 'P':
+				details.append('<p><label class="attribute">' + utf8_decoder(data[first_contact].cn) + '</label>' + '<span class="value">' + data[first_contact].mail + '</span></p>');
+                if(data[first_contact].telephonenumber != null)
+					details.append('<p><label class="attribute">Telefone</label>' + '<span class="value">' + data[first_contact].telephonenumber  + '</span></p>');
+				break;
+			default:
+				var extra_fields = (data['extra_ldap_fields']).split("#");   
+				if(preferences.default_fields_quick_search != 0 || data[first_contact].type_contact == "P") {
+					details.append('<p><label class="attribute">' + utf8_decoder(data[first_contact].cn) + "</label>" + '<span class="value">' + data[first_contact].mail + "</span></p>");
+					if(data[first_contact].telephonenumber != null)
+						details.append('<p><label class="attribute">Telefone</label>' + '<span class="value">' + data[first_contact].telephonenumber + "</span></p>");
+				}
+				if(data[first_contact].mail != "No mail") {
+					if(data[first_contact].mail[0].length > 1) {
+						for (var i=0; i<=extra_fields.length-1; i++) {
+							var campo = extra_fields[i].substr(extra_fields[i].indexOf("|")+1);    
+							var valor = extra_fields[i].substr(0, (extra_fields[i].indexOf("|")));                                          
+							if(data[first_contact][valor.toLowerCase()] != undefined) {
+								var tmp_campo = '<p><label class="attribute">' + campo + "</label>" ;
+								for(j=0; j<data[first_contact][valor.toLowerCase()].length; j++) {
+									details.append(tmp_campo + '<span class="value">' + data[first_contact][valor.toLowerCase()][j] + "</span></p>");
+									tmp_campo = "";
+								}	
+							}	
+						}
+					}
+				}
+				break;
+		}
+		var string_results = sliderValue + " " + get_lang("of") + " " + paginas + " (" + data.length + " " + get_lang("Results") + ")"; 		
+		$( "#amount-text" ).val( string_results );
+		$("button").button();
+		if(!is_ie)
+			document.getElementById("amount-text").focus();	
+		$("#selectable li:first button:first").focus();
+		removeFocus();
 		}	
 		
 		
-		
-		
-		
-		
-		function details_results(data) 
-        {
+	/* Método que configura os detalhes do resultado da busca */
+	function details_results(data) {
 				$(function() {
                     $( "#selectable" ).selectable({
@@ -276,64 +265,49 @@
 								var details = $("#detalhes_contato").empty();                                 
                                 $( ".ui-selected", this ).each(function() {
-                                    if(data['type_catalog'] == 'G')
-                                    {                                         
+                        switch(data['type_catalog']) {
+							case 'G':
                                         var extra_fields = (data['extra_ldap_fields']).split("#");   
-                                        /* Default fields */
-                                        details.append("<strong>" + utf8_decoder(data[this.value].cn[0]));
-                                        details.append("<br />" + data[this.value].mail[0]);
-                                        details.append("<br /><br /><strong>Matrícula<br />");
-                                        details.append(data[this.value].employeenumber[0] + "<br />");
-                                        details.append("<br /><strong> Telefone <br />");
-                                        details.append(data[this.value].telephonenumber[0] + "<br />");
-                                        details.append(data[this.value].telephonenumber[0]);
-                                        for (var i=0; i<extra_fields.length-1; i++)
-                                        {
+								if(preferences.default_fields_quick_search != 0) {	
+									details.append('<p><label class="attribute">' + utf8_decoder(data[this.value].cn[0]) + "</label>" + '<span class="value">' + data[this.value].mail[0] + "</span></p>");
+									details.append('<p><label class="attribute">Telefone</label>' + '<span class="value">' + data[this.value].telephonenumber[0] + "</span></p>");
+								}
+								for (var i=0; i<=extra_fields.length-1; i++) {
                                             var campo = extra_fields[i].substr(extra_fields[i].indexOf("|")+1);    
                                             var valor = extra_fields[i].substr(0, (extra_fields[i].indexOf("|")));                                          
-                                            if(data[this.value][valor] != undefined)
-                                            {    
-                                                details.append("<br /><br /><strong>" + campo);
-                                                details.append("<br />" + data[this.value][valor][0]);
+									if(data[this.value][valor.toLowerCase()] != undefined) {
+										var tmp_campo = '<p><label class="attribute">' + campo + "</label>" ;
+										for(j=0; j<data[this.value][valor.toLowerCase()].length; j++) {
+											details.append(tmp_campo + '<span class="value">' + data[this.value][valor.toLowerCase()][j] + "</span></p>");
+											tmp_campo = "";
                                             }
                                         }
                                     }
-                                    else
-                                    {
-                                        if(data['type_catalog'] == 'P')
-                                        {
-                                            /* Default fields */
-                                            details.append("<strong>" + utf8_decoder(data[this.value].cn));
-                                            details.append("<br />" + data[this.value].mail);
-                                            if(data[this.value].telephonenumber != "")
-                                            {
-                                                details.append("<br /><br /><br /><strong> Telefone <br />");
-                                                details.append(data[this.value].telephonenumber + "<br />");  
-                                            }
-                                        } 
-                                        else
-                                        {
+								break;
+							case 'P':
+								details.append('<p><label class="attribute">' + utf8_decoder(data[this.value].cn) + "</label>" + '<span class="value">' + data[this.value].mail + "</span></p>");
+                                if(data[this.value].telephonenumber != null)
+                                    details.append('<p><label class="attribute">Telefone</label>' + '<span class="value">' + data[this.value].telephonenumber + "</span></p>");
+								break;
+							default:
                                                 var extra_fields = (data['extra_ldap_fields']).split("#");   
-                                                /* Default fields */
-                                                details.append("<strong>" + utf8_decoder(data[this.value].cn));
-                                                details.append("<br />" + data[this.value].mail);
-                                                if(data[this.value].telephonenumber != "")
-                                                {
-                                                    details.append("<br /><br /><br /><strong> Telefone <br />");
-                                                    details.append(data[this.value].telephonenumber + "<br />");  
+                                if(preferences.default_fields_quick_search != 0 || data[this.value].type_contact == "P") {
+									details.append('<p><label class="attribute">' + utf8_decoder(data[this.value].cn) + "</label>" + '<span class="value">' + data[this.value].mail + "</span></p>");
+									if(data[this.value].telephonenumber != null)
+										details.append('<p><label class="attribute">Telefone</label>' + '<span class="value">' + data[this.value].telephonenumber + "</span></p>");
                                                 }
-                                                if(data[this.value].mail[0].length > 1) 
-                                                {
-                                                    for (var i=0; i<extra_fields.length-1; i++)
-                                                    {
+								if(data[this.value].mail[0].length > 1) {
+									for (var i=0; i<=extra_fields.length-1; i++) {
                                                         var campo = extra_fields[i].substr(extra_fields[i].indexOf("|")+1);    
                                                         var valor = extra_fields[i].substr(0, (extra_fields[i].indexOf("|")));                                          
-                                                        if(data[this.value][valor] != undefined)
-                                                        {    
-                                                            details.append("<br /><br /><strong>" + campo);
-                                                            details.append("<br />" + data[this.value][valor][0]);
+										if(data[this.value][valor.toLowerCase()] != undefined) {
+											var tmp_campo = '<p><label class="attribute">' + campo + "</label>" ;
+											for(j=0; j<data[this.value][valor.toLowerCase()].length; j++) {
+												details.append(tmp_campo + '<span class="value">' + data[this.value][valor.toLowerCase()][j] + "</span></p>");
+												tmp_campo = "";
                                                         }
                                                     }
                                                 }
                                         }
+								break;
                                     }
 								});
@@ -345,44 +319,8 @@
         
         /* 
-         * Método que inicializa a tela de contatos 
-         */
-        function init_results(data)
-        {			
-			var Op = null;
-			var Ul = null;
-			var selectable = $("#selectable");
-            selectable.empty();
-            Ul = document.createElement("ul");
-            Op = document.createElement("li");
-			var limit = data.length < 7 ? data.length : 7;
-			for (i=1; i<=limit; i++) 
-            {
-				Op.setAttribute("class", "ui-selectee");
-				if(i == 1)
-					Op.setAttribute("class", "ui-selected");
-				var contact_name = utf8_decoder(data[i-1].cn);
-				if(data['type_catalog'] != 'G' && (data[i-1].mail == null || data[i-1].mail == ""))
-				{
-					data[i-1].mail = "No mail"; 
-				}
-				
-				if(contact_name.substring(contact_name.toLowerCase().indexOf(data.search_for.toLowerCase())) != -1)									
-					contact_name = contact_name.substring(0, contact_name.toLowerCase().indexOf(data.search_for.toLowerCase())) + "<u>" + contact_name.substr(contact_name.toLowerCase().indexOf(data.search_for.toLowerCase()), data.search_for.length) + "</u>" + contact_name.substring(contact_name.toLowerCase().indexOf(data.search_for.toLowerCase()) + data.search_for.length);
-				Op.innerHTML = '<span style="float:right; left:335px; position: absolute; z-index: 100; background-color: #EEE; padding:0"><button onClick="add_contact_field(contact_' + i + '.innerHTML)">+</button><button onClick="remove_contact_field(contact_' + i + '.innerHTML)">x</button></span><div class="id_contact_field" id=contact_' + i + ' onDblClick="add_contact_field(this.innerHTML)"><div class="name_contact"><strong>' + contact_name + '</strong><em>' + utf8_decoder(data[i-1].mail) + '</em></div></div>';
-                $(Op).val(i - 1);
-                Ul.appendChild(Op);
-                selectable.append(Ul.innerHTML);
-            }
-			$("#adds").html("Foram adicionados " + quantidade_contatos + " contatos.");
-        }
-        
-        
-        /* 
          * Método que configura o slider e os resultados 
          */
-        function configure_slider(data) 
-        {	
-			$("#detalhes_contato").empty();
-            var paginas = Math.ceil(data.length/7); 
+    function configure_slider(data) {	
+        var paginas = (Math.ceil(data.length/6)); 
             $("#title_usuarios").html( get_lang("Results") );
             $(function() {
@@ -392,80 +330,53 @@
 					max: paginas,
 					step: 1,
-                        slide: function( event, ui ) 
-                        {
+				slide: function( event, ui ) {
+					create_list(data, false, ui.value); 
 								var string_results = ui.value + " " + get_lang("of") + " " + paginas + " (" + data.length + " " + get_lang("Results") + ")"; 
-                                var selectable = $("#selectable");
-                                selectable.empty();
-                                var Ul = document.createElement("ul");
-                                var Op = document.createElement("li");
-								for (i=((ui.value-1)*7)+1; i<(((ui.value-1)*7)+1)+7; i++) 
-                                {
-                                    if(data['type_catalog'] != 'G' && (data[i-1].mail == null || data[i-1].mail == ""))
-									{
-										data[i-1].mail = "No mail"; 
-									}	
-									var contact_name = utf8_decoder(data[i].cn);
-									if(contact_name.substring(contact_name.toLowerCase().indexOf(data.search_for.toLowerCase())) != -1)									
-										contact_name = contact_name.substring(0, contact_name.toLowerCase().indexOf(data.search_for.toLowerCase())) + "<u>" + contact_name.substr(contact_name.toLowerCase().indexOf(data.search_for.toLowerCase()), data.search_for.length) + "</u>" + contact_name.substring(contact_name.toLowerCase().indexOf(data.search_for.toLowerCase()) + data.search_for.length);
-									
-                                    Op.setAttribute("class", "ui-selectee");
-									Op.innerHTML = '<span style="float:right; left:335px; position: absolute; z-index: 100; background-color: #EEE; padding:0"><button onClick="add_contact_field(contact_' + i + '.innerHTML)">+</button><button onClick="remove_contact_field(contact_' + i + '.innerHTML)">x</button></span><div class="id_contact_field" id=contact_' + i + ' onDblClick="add_contact_field(this.innerHTML)"><div class="name_contact"><strong>' + contact_name + '</strong><em>' + utf8_decoder(data[i].mail) + '</em></div></div>';
-                                    $(Op).val(i);
-                                    Ul.appendChild(Op);
-                                    selectable.append(Ul.innerHTML);
-                                }
-                                $( "#amount" ).val( string_results );
-								$(this).unbind('keypress');
-								document.getElementById("amount").focus();
+					$( "#amount-text" ).val( string_results );
 						}
                     });
-                    $( "#amount" ).val( $( "#slider" ).slider( "value" ) + " " + get_lang("of") + " " + paginas + " (" + data.length + " " + get_lang("Results") + ")");         
+			$("#selectable li:first button:first").focus();
                 });
         }
         
+	var search_focus = false;
 
-		
-        function checkEnter(e) 
-		{
+	function setFocus() {search_focus = true;return;}
+		
+	function removeFocus() {search_focus = false;return;}
+		
+    function checkEnter(e) {
 			var kC = window.event ? event.keyCode :
             e && e.keyCode ? e.keyCode :
             e && e.which ? e.which : null;
-            if (kC) { 
-				//$("#dialog-modal").unbind('keypress');
+        if (kC) 
 				return kC == 13;
-			}
-            else{ 
+        else
 				return false;
 			}
-		}
+        
         
         /* 
          * Faz a busca direto da tela modal  
          */
-        function buscaContato(param)
-        {
-			$("#busca").empty();
-			if(param.length == 0)
-            {
-                alert(get_lang("Please enter a parameter to search."));
-                return false;
+    function buscaContato(param) {
+		$("#busca, #detalhes_contato, #selectable").empty();
+		if(param.length == 0) {
+            alert(get_lang("Please enter a parameter to search"));
+            return;
             }
-            if(param.length < preferences.search_characters_number)
-            {
+		if(param.length < preferences.search_characters_number) {
                 alert(get_lang("parameter must be at least") + " " +  preferences.search_characters_number + " " + get_lang("characters"));
                 return false;
             }
             var catalog = $("#combobox").val();
-            var handler_emQuickSearch = function(data) 
-            {
+        var handler_emQuickSearch = function(data) {
                 data_ = data;
-				if(data_.length > 0)
-                {        
-                    init_results(data_);
+			if(data_.length > 0) {        
                     configure_slider(data_);    
+                create_list(data_, true);
                     details_results(data_);
                 }
-                else
-                {
+            else {
                     $("#detalhes_contato, #selectable").empty();
                     configure_slider(data); 
@@ -476,17 +387,14 @@
 		
         
-		quantidade_contatos = 0;
         /* 
          * Método que adiciona o contato selecionado no campo do email (To, CC, CCo) 
          */
-        function add_contact_field(contact)
-        {
-			quantidade_contatos++;
-            $("#adds").html("Foram adicionados " + quantidade_contatos + " contatos.");
+    function add_contact_field(contact) {
 			var emailList      = document.getElementById(field_ + "_" + id_).value; 
-            var contact_parsed = contact.replace(/<\/?[^>]+>/gi, ' ');
+		var contact_parsed = contact.replace(/<[\/]*u>/gi, '');
+		contact_parsed     = contact_parsed.replace(/<u[^>]*>/gi, '');
+		contact_parsed     = contact_parsed.replace(/<\/?[^>]+>/gi, ' ');
             contact_parsed     = contact_parsed.replace(/^\s+|\s+$/gi, "").replace(/\s{2,}/gi, "|");
             var tokens_contact = contact_parsed.split("|");
-
             if (tokens_contact[1].indexOf("(") > 0)
                 tokens_contact[1] = tokens_contact[1].substr(0, (tokens_contact[1].indexOf("("))-2);
@@ -494,21 +402,31 @@
 			var final_contact;
 			if(tokens_contact[2] == undefined)
-				final_contact = "\"" + tokens_contact[0] + " " + "\" <" + tokens_contact[1] + ">, ";
+			final_contact = "\"" + tokens_contact[0] + "" + "\" <" + tokens_contact[1] + ">, ";
 			else
 			{			
 				if(tokens_contact[3] == undefined)               
-					final_contact =  "\"" + tokens_contact[0] + " " +  tokens_contact[1] + "\" <" + tokens_contact[2] + ">, ";
+				final_contact =  "\"" + tokens_contact[0] + "" +  tokens_contact[1] + "\" <" + tokens_contact[2] + ">, ";
 				else
-					final_contact =  "\"" + tokens_contact[0] + " " +  tokens_contact[1] + " " +  tokens_contact[2] + "\" <" + tokens_contact[3] + ">, ";
+				final_contact =  "\"" + tokens_contact[0] + "" +  tokens_contact[1] + "" +  tokens_contact[2] + "\" <" + tokens_contact[3] + ">, ";
             }
-            if (emailList[0] != '"')
+        if (emailList[0] != '"' && emailList.indexOf(",") < 0)
                 emailList = emailList.substr(end_);
+            if(emailList.lastIndexOf(",") > 0)
+			emailList = emailList.substr(0, emailList.lastIndexOf(",") + 1);
             
-            if(emailList.lastIndexOf(",") > 0)
-                emailList = emailList.substr(0, emailList.lastIndexOf(",") + 2);
-            
+		final_contact = final_contact.replace(/\/n/, "");
             new_emailList = emailList + final_contact;    
             document.getElementById(field_ + "_" + id_).value = new_emailList;
+		
+		if (is_ie) { 
+			var range= document.getElementById(field_ + "_" + id_).createTextRange(); 
+			range.collapse(false); 
+			range.select(); 
+		} else { 
 			document.getElementById(field_ + "_" + id_).focus();   
+		} 
+		
+		
+		
 			$(this).unbind('keypress');
 			$(this).dialog("close");
@@ -518,10 +436,9 @@
          * Método que remove o contato selecionado no campo do email (To, CC, CCo) 
          */
-		function remove_contact_field(contact)
-		{
+	function remove_contact_field(contact) {
 			var contact_parsed = contact.replace(/<\/?[^>]+>/gi, ' ');
             contact_parsed     = contact_parsed.replace(/^\s+|\s+$/gi, "").replace(/\s{2,}/gi, "|");
-			var tokens_contact = contact_parsed.split("|");
 			
+		var tokens_contact = contact_parsed.split("|");	
 			if (tokens_contact[2].indexOf("(") > 0)
                 tokens_contact[2] = tokens_contact[2].substr(0, (tokens_contact[2].indexOf("("))-2);
@@ -532,53 +449,32 @@
 				final_contact =  "\"" + tokens_contact[0] + " " +  tokens_contact[1] + " " +  tokens_contact[2] + "\" <" + tokens_contact[3] + ">";
 			
-			if(quantidade_contatos ==0)
-			{
-				alert("Nenhum contato adicionado!");
-				return false;
-			}
-			
-			var encontrou = false;
-			var emailList = document.getElementById(field_ + "_" + id_).value; 
+		var exist = false;
+		var emailList = $("#" + field_ + "_" + id_).val();
 			var emails_adicionados = emailList.split(",");
-			var quantidade_excluidos = 0;
-			for(i=0; i<emails_adicionados.length -1; i++)
-			{
-				if(emails_adicionados[i].trim() == final_contact)
-				{
+		for(i=0; i<emails_adicionados.length -1; i++) {
+			emails_adicionados[i].replace(/^\s+|\s+$/g, ''); 
+			if(emails_adicionados[i] == final_contact) {
 					emails_adicionados[i] = "%";
-					quantidade_excluidos++;
-					encontrou = true;
+				exist = true;
 				}
 			}
-			if (encontrou == false) 
-			{
-				alert("Não pode excluir um contato que ainda não adicionou.");
+		if (exist == false) 
 				return false;
-			}
-			
-			quantidade_contatos -= quantidade_excluidos;
-            $("#adds").html("Foram adicionados " + quantidade_contatos + " contatos.");
-			
 			var novos_contatos = emails_adicionados.join(",");  
             novos_contatos = novos_contatos.replace(/%,/g, "");
-			document.getElementById(field_ + "_" + id_).value = novos_contatos;
+		$("#" + field_ + "_" + id_).val(novos_contatos);
 		}
         
 	      
-        function utf8_decoder ( str_data ) 
-        {
+	/* Decoder utf8 */	
+    function utf8_decoder ( str_data ) {
             var tmp_arr = [], i = 0, ac = 0, c1 = 0, c2 = 0, c3 = 0;
-            
             str_data += '';
-            
-            while ( i < str_data.length ) 
-            {
+        while ( i < str_data.length ) {
                 c1 = str_data.charCodeAt(i);
-                if (c1 < 128) 
-                {
+            if (c1 < 128) {
                     tmp_arr[ac++] = String.fromCharCode(c1);
                     i++;
-                } else if ((c1 > 191) && (c1 < 224)) 
-                       {
+            } else if ((c1 > 191) && (c1 < 224)) {
                             c2 = str_data.charCodeAt(i+1);
                             tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
@@ -596,14 +492,12 @@
         
               
-    function show_help()
-	{
+	/* Mostra tela de help */	
+    function show_help() {
 		$(function() {
 			$( "#dialog-modal_help" ).dialog({
 						resizable: false,
-						height: 230,
 						width: 540,
 						modal: true,
-						closeOnEscape: true,
-
+						closeOnEscape: true
 			});
 		});
@@ -611,483 +505,66 @@
 		  
               
-	emQuickCatalogSearch.prototype.showWindow = function (div)
-	{
-				$(this).bind('keypress');
+	emQuickCatalogSearch.prototype.showWindow = function (div) {
+		$(this).bind('keydown');
 				$(function() {
                     $( "#dialog:ui-dialog" ).dialog( "destroy" );                    
                     $( "#dialog-modal" ).dialog({
 						resizable: false,
-						height: 530,
-						width: 940,
+//			height: "auto",
+			width: 780,
 						modal: true,
+			position: 'bottom',
 						closeOnEscape: true,
 						close: function (event, ui) {
 							event.stopPropagation();
-							$(this).unbind('keypress');
+				$(this).unbind('keydown');
+				if (is_ie) { 
+					var range= document.getElementById(field_ + "_" + id_).createTextRange(); 
+					range.collapse(false); 
+					range.select(); 
+				} else { 
+					document.getElementById(field_ + "_" + id_).focus();    
+				} 
+			},
+			open: function () {
+				$("#selectable li:first button:first").focus();    
 						},
 						focus: function (event, ui) {
-							$(this).bind('keypress');
+				//$(this).unbind('keydown');
 						},
 						beforeClose: function (event, ui) {
-							$(this).bind('keypress');
+				$(this).unbind('keydown');
 						},
-						buttons:{
-							'Fechar' : function(){
+			buttons:[
+						{
+							text: "Fechar",
+							click: function(){
 								$("#detalhes_contato, #selectable, #busca").empty();
 								$(this).dialog("close");
+												if (is_ie) { 
+													var range= document.getElementById(field_ + "_" + id_).createTextRange(); 
+													range.collapse(false); 
+													range.select(); 
+												} else { 
+														document.getElementById(field_ + "_" + id_).focus();    
 							} 
+											 },
+							style: "margin-top: -2.1em" 
 						}
+					]
 					});
                 });
+		$(".ui-dialog .ui-dialog-titlebar")
+		.append('<a href="#" class="ui-dialog-titlebar-minimize ui-corner-all" role="button"><span class="ui-icon ui-icon-minusthick">minimize</span></a>')
+		.find('.ui-dialog-titlebar-minimize').click(function() {
+			$(".ui-dialog-buttonpane, .ui-dialog-content").toggle();
+			$(".ui-icon-minusthick, .ui-icon-newwin").toggleClass('ui-icon-minusthick').toggleClass('ui-icon-newwin');
+		});
 	
-                
-                
-        if(! div) {
-			alert(get_lang('The list has no participant.'));
-			return;
-		}
-							
-		if(! this.arrayWin[div.id]) {
-			div.style.width = "700px";
-			div.style.height = "230px";
-			var title = get_lang('The results were found in the Global Catalog')+':';
-			var wHeight = div.offsetHeight + "px";
-			var wWidth =  div.offsetWidth   + "px";
-			div.style.width = div.offsetWidth - 5;
-
-			win = new dJSWin({			
-				id: 'QuickCatalogSearch_'+div.id,
-				content_id: div.id,
-				width: wWidth,
-				height: wHeight,
-				title_color: '#3978d6',
-				bg_color: '#eee',
-				title: title,						
-				title_text_color: 'white',
-				button_x_img: '../phpgwapi/images/winclose.gif',
-				border: true,
-                                onclose: 'QuickCatalogSearch.restoreShortcuts("'+ div.id +'")'});
-
-			this.arrayWin[div.id] = win;
-			win.draw();
-		}
-		else {
-			win = this.arrayWin[div.id];
-		}
-		//document.getElementById("window_QuickCatalogSearch").style.visibility = "visible";
-		//win.open();
-		//document.getElementById('select_QuickCatalogSearch').focus();
-
-                if(is_ie && (preferences.use_shortcuts == '1')){
-                    shortcut.remove('down');
-                    shortcut.remove('up');
-                    shortcut.remove('return');
-                }
-	}
-	
-	emQuickCatalogSearch.prototype.transfer_result = function (field, ID, begin, end){
-		cm = document.getElementById('select_QuickCatalogSearch');
-		option_selected = cm.options[cm.selectedIndex].value + ", ";
-		emailList = document.getElementById(field + "_" + ID).value;
-		
-		new_emailList = emailList.substring(0, begin) + option_selected + emailList.substring((parseInt(end) + 2), emailList.length);
-		document.getElementById(field + "_" + ID).value = new_emailList;
-		document.getElementById(field + "_" + ID).focus();
-		this.arrayWin['window_QuickCatalogSearch_A'].close();
-                document.getElementById("window_QuickCatalogSearch").style.visibility = "hidden";
-	}
-
-	emQuickCatalogSearch.prototype.close_QuickSearch_window = function (field, ID){
-		//document.getElementById('QuickCatalogSearch_window_QuickCatalogSearch').style.display = "none";
-		document.getElementById(field + "_" + ID).focus();
-		this.arrayWin['window_QuickCatalogSearch_A'].close();
-                document.getElementById("window_QuickCatalogSearch").style.visibility = "hidden";
-                if(typeof shortcut.all_shortcuts['down'] == 'undefined'){
-                    if(is_ie  && (preferences.use_shortcuts == '1'))
-                    {
-                        shortcut.add("down",function(){select_msg('null', 'down');},{'disable_in_input':false});
-                        shortcut.add("up",function(){select_msg('null', 'up');},{'disable_in_input':false});
-                        shortcut.add("return",function(){
-                            if ( Element('border_id_0').className==='menu-sel' )
-                            {
-                                    all_messages = Element('tbody_box').childNodes;
-                                    for (var i=0; i < all_messages.length; i++)
-                                    {
-                                            if ( exist_className(all_messages[i], 'selected_shortcut_msg') )
-                                            {
-                                                    Element("td_who_" + all_messages[i].id).onclick();
-                                                    return;
-                                            }
-                                    }
-                            }
-                        },{'disable_in_input':true});
-                    }
-                }
-	}
-
-        emQuickCatalogSearch.prototype.restoreShortcuts = function(id) {
-
-            var search_win = document.getElementById(id);
-            if(typeof shortcut.all_shortcuts['down'] == 'undefined'){
-                if (search_win.style.visibility == 'visible')
-                {
-                    shortcut.add("down",function(){select_msg('null', 'down');},{'disable_in_input':false});
-                    shortcut.add("up",function(){select_msg('null', 'up');},{'disable_in_input':false});
-                    shortcut.add("return",function(){
-                        if ( Element('border_id_0').className==='menu-sel' )
-                        {
-                                all_messages = Element('tbody_box').childNodes;
-                                for (var i=0; i < all_messages.length; i++)
-                                {
-                                        if ( exist_className(all_messages[i], 'selected_shortcut_msg') )
-                                        {
-                                                Element("td_who_" + all_messages[i].id).onclick();
-                                                return;
-                                        }
-                                }
-                        }
-                    },{'disable_in_input':true});
-                }
-            }
-            search_win.style.visibility = 'hidden';
-
-        }
-
-	emQuickCatalogSearch.prototype.close_window = function(id) {
-                this.arrayWin[id].close();
-		var group_values = Element('list_values');
-		var user_values = Element('user_values');
-	}
-	emQuickCatalogSearch.prototype.showCatalogList = function (border_id){
-		var el = Element('catalog_list');
-
-		if(el) {
-			Element('border_id').value = border_id;
-			win = this.arrayWin[el.id];
-			win.open();
-			return;		
-		}
-		var border_input   = document.createElement("INPUT");
-		border_input.type  = 'hidden';
-		border_input.id    = 'border_id';
-		border_input.value = border_id;
-		document.body.appendChild(border_input);
-		el = document.createElement("DIV");		
-		el.id = 'catalog_list';
-		document.body.appendChild(el);			
-		el.style.visibility = "hidden";
-		el.style.position = "absolute";
-		el.style.width = "700px";
-		el.style.height = is_ie ? "360px" : "375px";		
-		el.style.left = "0px";
-		el.style.top = "0px";			
-		el.innerHTML = "<table border='0' cellpading='0' cellspacing='0' width='100%'>"+
-					   "<tr><td id='td1' style='cursor:pointer' align='center' onclick='QuickCatalogSearch.select_div(\"tab1\")'><a href='#' class='catalog' onclick='QuickCatalogSearch.select_div(\"tab1\");'>"+get_lang('Global Catalog')+"</a></td>"+
-					   "<td id='td2' style='background:#cecece;cursor:pointer' onclick='QuickCatalogSearch.select_div(\"tab2\")' align='center'><a href='#' class='catalog' onclick='QuickCatalogSearch.select_div(\"tab2\");'>"+get_lang('Personal Catalog')+"</a></td></tr>"+
-					   '</table>'+
-					   '<div id="tab1" align="center"><br>'+
-					   '<table border="0" cellpading="0" cellspacing="0">'+
-					   '<tr><td>'+get_lang("Select an organization and click on button <b>Search</b>")+'&nbsp;:</td></tr>'+
-  					'<tr><td><select style="display:none;width:150px" id="select_catalog" name="select_catalog" onchange="javascript:QuickCatalogSearch.update_organizations();"></select>&nbsp'+
-					'<select id="select_organization" style="width:150px" name="select_organization"></select>&nbsp;'+   
-					'<input type="text" id="search_for" name="search_for" value="" size="30" maxlength="30"/>&nbsp;<input type="button" onclick="QuickCatalogSearch.searchCatalogList(true)" class="button" value="'+get_lang('Search')+'">&nbsp;<input style="display:visible" type="button" onclick="QuickCatalogSearch.searchCatalogList(false)" class="button" value="'+get_lang('List All')+'"></td></tr>'+
-					   '<tr><td><input onclick="javascript:QuickCatalogSearch.changeOptions(this.value)" id="type_l" type="radio" name="type" value="l"/>'+get_lang('Public Lists')+'&nbsp;&nbsp;<input type="radio" id="type_u" name="type" value="u" onclick="javascript:QuickCatalogSearch.changeOptions(this.value)" checked/>'+get_lang('Users')+'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'+
-					   '<span style="visibility:hidden;background:#cc4444" id=msg_search>&nbsp;&nbsp;<font face="Verdana" size="1" color="WHITE">'+get_lang('Search in Catalog')+'...</font>&nbsp;</span></td></tr>'+
-					   '<tr><td>'+
-				  	   '<span id="list_span"><select multiple style="display:none;width:580px" size="14" id="list_values"></select></span>'+
-				  	   '<span id="user_span"><select multiple style="width:580px" size="14" id="user_values"></select></span>'+
-				 	   '</td></tr>'+
-					   '<tr><td nowrap><center>'+get_lang('Click here to add into the fields')+':&nbsp;<input type="button" class="button" value="'+get_lang('TO')+'" onClick="javascript:QuickCatalogSearch.addContacts(\'to\')">&nbsp;'+
-				  	   '<input type="button" class="button" value="'+get_lang('CC')+'" onClick="javascript:QuickCatalogSearch.addContacts(\'cc\')">&nbsp;'+( allow_hidden_copy ?  
- 	                   '<input type="button" class="button" value="'+get_lang('CCo')+'" onClick="javascript:QuickCatalogSearch.addContacts(\'cco\')">' : '' )+
-				  	   '</center></td></tr><tr><td nowrap><center><input type="button" value="'+get_lang('Close')+'" onClick="javascript:QuickCatalogSearch.close_window(\'catalog_list\')"></center></td></tr>'+
-					   '</table>'+
-					   '</div>'+
-					   '<div style="display:none" id="tab2" align="center">'+
-					   '<br><br><br>'+
-					   '<table border="0" cellpading="0" cellspacing="0">'+
-					   '<tr><td>'+get_lang("Select the type of contact that you want to view")+'&nbsp;:</td></tr>'+
-					   '<tr><td><input onclick="javascript:QuickCatalogSearch.changeOptions(this.value)" type="radio" name="type" value="p"/>' + get_lang('People') + '&nbsp;&nbsp;<input type="radio" name="type" value="g" onclick="javascript:QuickCatalogSearch.changeOptions(this.value)"/>' + get_lang('Groups') + ' &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'+
-					   '<tr><td>'+
-				  	   '<span id="personal_span"><select multiple style="width:580px" size="14" id="list_personal"></select></span>'+
-				  	   '<span id="groups_span"><select multiple style="display:none;width:580px" size="14" id="list_groups"></select></span>'+
-				 	   '</td></tr>'+
-					   '<tr><td nowrap><center>'+get_lang('Click here to add into the fields')+':&nbsp;<input type="button" class="button" value="'+get_lang('TO')+'" onClick="javascript:QuickCatalogSearch.addContacts(\'to1\')">&nbsp;'+
-				  	   '<input type="button" class="button" value="'+get_lang('CC')+'" onClick="javascript:QuickCatalogSearch.addContacts(\'cc1\')">&nbsp;'+ ( allow_hidden_copy ? 
- 	                   '<input type="button" class="button" value="'+get_lang('CCo')+'" onClick="javascript:QuickCatalogSearch.addContacts(\'cco1\')">' : '' )+
-				  	   '</center></td></tr><tr><td nowrap><center><input type="button" value="'+get_lang('Close')+'" onClick="javascript:QuickCatalogSearch.close_window(\'catalog_list\')"></center></td></tr>'+
-					   '</table>'+
-					   '</div>';
-
-		var title = get_lang('Search in the Global Catalog');
-		var wHeight = el.offsetHeight - (is_ie ? 10 : 0) + "px";
-		var wWidth =  el.offsetWidth   + "px";
-		el.style.width = el.offsetWidth;
-		
-		Element('search_for').onkeypress = function (e) {
-			if ((is_ie && (window.event.keyCode == 13)) || (!is_ie && e.keyCode == 13)) {
-				QuickCatalogSearch.searchCatalogList(true);
-			}
-		};
-
-		win = new dJSWin({			
-			id: 'win_'+el.id,
-			content_id: el.id,
-			width: wWidth,
-			height: wHeight,
-			title_color: '#3978d6',
-			bg_color: '#eee',
-			title: title,						
-			title_text_color: 'white',
-			button_x_img: '../phpgwapi/images/winclose.gif',
-			border: true});
-			
-		this.arrayWin[el.id] = win;		
-		win.draw();
-		win.open();
-
-		var handler_catalogs = function(data){
-			var user_catalog = get_lang("Global Catalog");
-			if(data.length > 1) {
-				Element('select_catalog').style.display = '';
-				for(i = 0; i < data.length; i++) {		
-					Element('select_catalog').options[i] = new Option(data[i],i);
-					if(user_catalog.toUpperCase() == data[i].toUpperCase())
-						Element('select_catalog').options[i].selected = true;
-				}
-			}
-		}
-		cExecute ("$this.ldap_functions.get_catalogs", handler_catalogs);		
-		
-		this.update_organizations();
-		var handler_cc_contacts= function(data){
-			if(data && data.length > 0){
-				var aux = data.split(",");
-				for(var i=0; i< aux.length; i++){
-					QuickCatalogSearch.cc_contacts[QuickCatalogSearch.cc_contacts.length] = aux[i];				
-				}
-			}
-		}
-		cExecute("$this.db_functions.get_cc_contacts",handler_cc_contacts);
-
-		var handler_cc_groups = function(data){
-			if(data && data.length > 0){
-				var aux = data.split(",");
-				for(var i=0; i < data.length; i++){
-					QuickCatalogSearch.cc_groups[QuickCatalogSearch.cc_groups.length] = aux[i];								
-				}	
-			}
-		}
-		cExecute("$this.db_functions.get_cc_groups",handler_cc_groups);
-	
-	}
-	
-	emQuickCatalogSearch.prototype.select_div = function(element){
-		if(element == 'tab1'){
-		   Element('tab1').style.display = '';
-		   Element('tab2').style.display = 'none';
-		   Element('td1').style.background = '#eee';	
-		   Element('td2').style.background = '#cecece';
-		}
-		if(element == 'tab2'){
-		   Element('tab1').style.display = 'none';
-		   Element('tab2').style.display = '';
-		   Element('td1').style.background = '#cecece';
-		   Element('td2').style.background = '#eee';		   
-
-		}
-	}
-	
-	emQuickCatalogSearch.prototype.load_catalog = function(){
-	
-		var _this = this;
-		var content = new Array;
-		var select = Element('list_personal').style.display == 'none'? Element('list_groups'): Element('list_personal');
-		
-		if(Element('list_personal').style.display == 'none'){
-			content = _this.cc_groups;
-		}else{
-			content = _this.cc_contacts;
-		}
-		if(select.options.length > 0){
-			for(var i=0; i < select.options.length; i++){
-				select.options[i] = null;
-				i--;
-			}
-		}
-		for(var i=0; i < content.length; i++){
-			if(content[i] != undefined){
-				var aux = content[i].split(";");
-				var opt = new Option(aux[0] + ' (' + aux[1] + ')','"' + aux[0] + '" ' + '<' + aux[1] + '>',false,false);
-				select[select.length] = opt;
-			}
-		}
-		content.splice(0,(content.lenght));
-	}
-
-	emQuickCatalogSearch.prototype.update_organizations = function(){
-		while(Element('select_organization').options.length > 0) {
-			Element('select_organization').remove(0);
-		}
-	 	var handler_org = function(data){
-			Element('select_organization').options[0] = new Option(get_lang('all'),'all');
-			if (data != null){
-				var user_organization = Element('user_organization').value;
-				for(x = 0; x < data.length; x++) {
-					Element('select_organization').options[x+1] = new Option(data[x].toUpperCase(),data[x]);
-					if(user_organization.toUpperCase() == data[x].toUpperCase())
-						Element('select_organization').options[x+1].selected = true;
-				}
-			}
-		}		
-		cExecute ("$this.ldap_functions.get_organizations&referral=false&catalog="+Element('select_catalog').value, handler_org);		
-	}
-
-	emQuickCatalogSearch.prototype.changeOptions = function(type){	
-
-		switch(type){
-			case 'u':
-				Element('list_values').style.display = 'none';
-				Element('user_values').style.display = '';
-				break;
-			
-			case 'l':		
-				Element('user_values').style.display = 'none';
-				Element('list_values').style.display = '';		
-				break;
-
-			case 'p':
-				Element('list_personal').style.display = '';
-				Element('list_groups').style.display = 'none'
-				QuickCatalogSearch.load_catalog();				
-				break;
-			
-			case 'g':
-				Element('list_personal').style.display = 'none';
-				Element('list_groups').style.display = ''
-				QuickCatalogSearch.load_catalog();
-				break;
-		}
-
-	}
-
-	emQuickCatalogSearch.prototype.addContacts = function(field) {
-		
-		var border_id 	= Element('border_id').value;
- 		var select		= Element('user_values').style.display == 'none' ? Element('list_values') : Element('user_values');
-		if(field == "to1" || field == "cc1" || field == "cco1"){
-			field = field.substr(0,field.length - 1);
-			var select = Element('list_personal').style.display == 'none' ? Element('list_groups') : Element('list_personal');
-		}
-		var fieldOpener = Element(field+"_"+border_id);
-		var not_selected = true;
-		
-		for (i = 0 ; i < select.length ; i++) {
-			if (select.options[i].selected && select.options[i].value != '-1') {
-				if(fieldOpener.value.length > 0 && (fieldOpener.value.lastIndexOf(',') != (fieldOpener.value.length - 1))){
-					fieldOpener.value += ",";
-				}
-				fieldOpener.value += select.options[i].value + ",";
-				not_selected = false;
-				select.options[i].selected = false;
-			}
-		}
-		
-		if(not_selected)
-			return false;
-			
-		if(field != 'to'){
- 			a_link = Element("a_"+field+"_link_"+border_id);
- 			if(a_link)
- 				a_link.onclick();
- 		}
-	}
-	
-	emQuickCatalogSearch.prototype.searchCatalogList = function (itemSearch){
-
-		if(itemSearch && Element('search_for').value.length < preferences.search_characters_number){
-			alert(get_lang('Your search argument must be longer than %1 characters.', preferences.search_characters_number));
-			Element('search_for').focus();
-			return false;
-		}
-		var organization = Element('select_organization').value;		
-		var search		 = itemSearch ? Element('search_for').value : '';
-		var catalog		 = Element('select_catalog').value;
-
-		var handler_searchResults = function(data){
-			Element('msg_search').style.visibility = 'hidden';
-			if(data.error){
-				alert(get_lang('More than %1 results. Please, try to refine your search.',data.maxResult));
-				return false;
-			}else if(data.users.length == 0 && data.groups.length == 0){
-				alert(get_lang('None result was found.'));
-			}
-
-			
-			var group = Element('list_span');
-			var user  = Element('user_span');	
-			if(is_ie){
-				group.innerHTML = '';
-				user.innerHTML = '';
-			}
-			else {
-				group = Element('list_values');
-				user  = Element('user_values');	
-				for(var i = 0;i < group.options.length; i++)				
-					group.options[i--] = null;
-				for(var i = 0;i < user.options.length; i++)				
-					user.options[i--] = null;
-			}
-
-			var arr 	= new Array(data.maxResult);
-
-			for(i = 0; data.groups && i < data.groups.length; i++) {
-				// Maneiras diferentes de se montar uma tag OPTION, pois no IE o objeto Option é muito lento.
-				if(is_ie)
-					arr[i] = '<option value="'+'&quot;'+data.groups[i].name+'&quot; &lt;'+data.groups[i].email+'&gt;">'+data.groups[i].name+' ('+data.groups[i].email+')'+'</option>';
-				else
-					group.options[i] = new Option(data.groups[i].name+' ('+data.groups[i].email+')','"'+data.groups[i].name+'" <'+data.groups[i].email+'>');
-			}
-	
-			
-			if(is_ie)
-				group.innerHTML = '<select multiple style="display:none;width:580px" size="14" id="list_values">'+ arr.join() +'</select>';
-
-			arr = new Array(data.maxResult);
-			
-			for(i = 0; data.users && i < data.users.length; i++) {
-			/*******************************************************************************************/
-			/* O resultado pratico do bloco de codigo a seguir eh a exibicao dos valores em tela,
-			ja que vai verificar se o departamento e o email estao vazios ou nulos e a partir dai o
-			resultado apresentado em tela sera exibido de maneira mais apresentavel;
-			*/
-				//verifica se departamento eh null ou nao;
-				var department = data.users[i].department ? " - " + data.users[i].department : "";
-				//verifica se email eh null ou nao;
-				var email = data.users[i].email ? data.users[i].email : "";
-
-				// Maneiras diferentes de se montar uma tag OPTION, pois no IE o objeto Option é muito lento.
-				if(is_ie)
-					arr[i] = '<option value="'+'&quot;'+data.users[i].name+'&quot; &lt;'+email+'&gt;">'+data.users[i].name+' ('+email+')'+department+'</option>';
-				else {
-					user.options[i] = new Option(data.users[i].name+' ('+email+')'+department,'"'+data.users[i].name+'" <'+email+'>'); // incluido data.users[i].department para exibir setor na opcao "Pesquisar" do email;
-				}
-			}
-	
-			if(is_ie)
-				user.innerHTML = '<select multiple style="width:580px" size="14" id="user_values">'+ arr.join() +'</select>';
-
-			// Display entries found.
-			var type = (data.groups.length > 0 && data.users.length == 0) ? 'l' : 'u';
-			Element("type_"+type).checked = true;
-			QuickCatalogSearch.changeOptions(type);
-		}
-
-		Element('msg_search').style.visibility = 'visible';
-		cExecute ("$this.ldap_functions.catalogsearch&organization="+organization+"&search_for="+search+"&catalog="+catalog, handler_searchResults);
+		$("#dialog-modal button, input.button").button();				
 	}
 
 	
-/* Build the Object */
+	/* Build the Object */
 	//QuickCatalogSearch;
 	QuickCatalogSearch = new emQuickCatalogSearch();
Index: trunk/expressoMail1_2/js/rich_text_editor.js
===================================================================
--- trunk/expressoMail1_2/js/rich_text_editor.js	(revision 5083)
+++ trunk/expressoMail1_2/js/rich_text_editor.js	(revision 5134)
@@ -99,5 +99,4 @@
         var textArea = document.createElement("TEXTAREA");
         textArea.id = pObj;
-        textArea.style.height = '500';
         textArea.style.width = '100%';
         parentDiv.appendChild(textArea);
@@ -367,9 +366,21 @@
            if(selection !== undefined && selection !== null) var selectionRanges = selection.getRanges(); 
 
-           editor.insertHtml('<div><br type="_moz"></div>'+data);
+           var fontSize = '';
+           var fontFamily = '';
            
-          if(selection !== null) selection.selectRanges(selectionRanges); 
+           if(typeof(preferences.font_size_editor) !== 'undefined')
+               fontSize = 'font-size:' + preferences.font_size_editor;
+               
+           if(fontSize != '') 
+               fontFamily = ';'
+           
+           if(typeof(preferences.font_family_editor) !== 'undefined')
+               fontFamily += 'font-family:' + preferences.font_family_editor + ';'; 
+            
+           var divBr = '<div style="'+fontSize+fontFamily+'"><br type="_moz"></div>';
           
-          editor.execCommand("autogrow"); //Atualiza tamanho do editor
+           editor.insertHtml(divBr+divBr+divBr+data);
+           
+           if(selection !== null) selection.selectRanges(selectionRanges); 
           
           //Caso não for uma resposta votla o foco para o input to
@@ -396,8 +407,12 @@
          CKEDITOR.remove(CKEDITOR.instances[id]);
      
+    var height = document.body.scrollHeight;
+    height -= 425;
+     
      $('#'+id).ckeditor( 
           function() {RichTextEditor.execPosInstance(id)},
           {
-              toolbar:'mail'      
+              toolbar:'mail',
+              height: height
           }); 
 
Index: trunk/expressoMail1_2/js/report_window.js
===================================================================
--- trunk/expressoMail1_2/js/report_window.js	(revision 4830)
+++ trunk/expressoMail1_2/js/report_window.js	(revision 5134)
@@ -11,5 +11,5 @@
 	report_window.prototype.make_report_window = function(ID_msg){
 		_this = this;
-		var title = get_lang("Describe the problem to report to technical support (optional)");
+		var title = get_lang("More information about the problem (optional)");
 		
 		tree 				  = document.createElement("DIV");
@@ -52,5 +52,5 @@
 			msg_confirmation.style.width = "240px";
 			msg_confirmation.style.height = "350px";
-			msg_confirm = get_lang("Attention! The original message will be sent along with the original source of the email message");
+			msg_confirm = get_lang("Attention! The information contained in the e-mail will be sent to the support team");
 			msg_confirmation.innerHTML = "<br><b><font color='BLACK' nowrap>"+msg_confirm+"</font></b>";
 				tree.appendChild(msg_confirmation);
