Index: trunk/phpgwapi/templates/default/css/base.css
===================================================================
--- trunk/phpgwapi/templates/default/css/base.css	(revision 5141)
+++ trunk/phpgwapi/templates/default/css/base.css	(revision 5172)
@@ -83,5 +83,5 @@
 }
 
-#ul
+ul
 {
 	list-style-image: url( "../images/orange-ball.png" );
Index: trunk/services/class.db.php
===================================================================
--- trunk/services/class.db.php	(revision 5130)
+++ trunk/services/class.db.php	(revision 5172)
@@ -110,5 +110,6 @@
 				$query .= ' where '
                                         . 'A.id_owner=' . $_SESSION['phpgw_info']['expressomail']['user']['account_id']
-                                        . ' and lower(to_ascii(names_ordered)) LIKE lower(to_ascii(\'%' . $search_for . '%\'))';                         
+                                        . ' and lower(translate(names_ordered, \'áàâãäéèêëíìïóòôõöúùûüÁÀÂÃÄÉÈÊËÍÌÏÓÒÔÕÖÚÙÛÜçÇñÑ\',\'aaaaaeeeeiiiooooouuuuAAAAAEEEEIIIOOOOOUUUUcCnN\'))'
+										. ' LIKE lower(translate(\'%' . $search_for . '%\', \'áàâãäéèêëíìïóòôõöúùûüÁÀÂÃÄÉÈÊËÍÌÏÓÒÔÕÖÚÙÛÜçÇñÑ\',\'aaaaaeeeeiiiooooouuuuAAAAAEEEEIIIOOOOOUUUUcCnN\'))';                    
                                 
         if (!$this->db->query($query))
@@ -251,4 +252,37 @@
 	}
 
+	function search_groups($search_for)
+    { 
+        $result = array();
+		$query = 'select'
+						. ' G.oid,'
+						. ' G.title,'
+						. ' G.short_name';
+		$query .= ' from'
+                        . ' phpgw_cc_groups G';
+		$query .= ' where '
+						. ' G.owner=' . $_SESSION['phpgw_info']['expressomail']['user']['account_id']
+						. ' and lower(translate(G.title, \'áàâãäéèêëíìïóòôõöúùûüÁÀÂÃÄÉÈÊËÍÌÏÓÒÔÕÖÚÙÛÜçÇñÑ\',\'aaaaaeeeeiiiooooouuuuAAAAAEEEEIIIOOOOOUUUUcCnN\'))' 
+						. ' LIKE lower(translate(\'%' . $search_for . '%\', \'áàâãäéèêëíìïóòôõöúùûüÁÀÂÃÄÉÈÊËÍÌÏÓÒÔÕÖÚÙÛÜçÇñÑ\',\'aaaaaeeeeiiiooooouuuuAAAAAEEEEIIIOOOOOUUUUcCnN\'))';        
+						
+		if (!$this->db->query($query))
+             return null;
+         
+         while($this->db->next_record())
+            $result[] = $this->db->row();
+
+		$all_contacts = array(); 
+		foreach( $result as $i => $object )
+		{
+			if ( ! array_key_exists( $object[ 'oid' ], $all_contacts ) )
+				$all_contacts[ $object[ 'oid' ] ] = array(
+					'title' => '',
+					'short_name' => '',
+				);
+				$all_contacts[ $object[ 'oid' ] ]['title'] = $object['title'];
+				$all_contacts[ $object[ 'oid' ] ]['short_name'] = $object['short_name'];
+		}
+		return array_values($all_contacts);
+	}
 }
 
Index: trunk/prototype/app/plugins/treeview/jquery.treeview.css
===================================================================
--- trunk/prototype/app/plugins/treeview/jquery.treeview.css	(revision 5136)
+++ trunk/prototype/app/plugins/treeview/jquery.treeview.css	(revision 5172)
@@ -70,5 +70,7 @@
 .filetree li { padding: 3px 0 2px 16px; }
 .filetree span.folder, .filetree span.file { padding: 1px 0 1px 16px; display: block; }
-.filetree span.folder { background: url(images/folder.gif) 0 0 no-repeat; }
+.filetree span.folder { background: url(images/folder.gif) 0 0 no-repeat; cursor: pointer;}
+.filetree span.folder:hover {color: red; cursor: pointer;}
+.filetree span.folder.selected {font-weight: bold; cursor: pointer; }
 .filetree li.expandable span.folder { background: url(images/folder-closed.gif) 0 0 no-repeat; }
 .filetree span.file { background: url(images/file.gif) 0 0 no-repeat; }
Index: trunk/prototype/modules/attach_message/attach_message.js
===================================================================
--- trunk/prototype/modules/attach_message/attach_message.js	(revision 5136)
+++ trunk/prototype/modules/attach_message/attach_message.js	(revision 5172)
@@ -253,6 +253,12 @@
 			    target = target.parent();
 
+            if (target.attr('id') == "foldertree") return;
+			
 			var targetId = target.attr('id');
-			var child = target.find('span');
+			var child = target.find('.folder');
+              
+			$('.filetree span.folder.selected').removeClass('selected');
+			if(!target.is('#foldertree > .expandable, #foldertree > .collapsable'))
+				$(target).children('.folder').addClass('selected');
 			
 			selectedFolder = {
Index: trunk/expressoMail1_2/templates/default/index.tpl
===================================================================
--- trunk/expressoMail1_2/templates/default/index.tpl	(revision 5134)
+++ trunk/expressoMail1_2/templates/default/index.tpl	(revision 5172)
@@ -153,5 +153,5 @@
  		                        </fieldset>     
                             <input class="button" type="button" value="Buscar" onClick="buscaContato(busca.value);"/>
-                            <input class="button" type="button" value="?" onClick="show_help()" />
+							<input class="button" type="button" onClick="show_help()" style="background-image: url('./templates/default/images/information.png'); background-repeat: no-repeat;"/>
  		                 </div>   
  		             </div> 
@@ -164,6 +164,6 @@
                         <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" />
+                                <label for="amount" style="padding-left: 6px;">{lang_page}: </label>
+                                <input type="text" id="amount-text" style="padding-left: 3px; border:0; font-weight:bold; width: 175px;" readonly="true"/>
                             </p>            
  		        </div> 
Index: trunk/expressoMail1_2/templates/default/quick_search.css
===================================================================
--- trunk/expressoMail1_2/templates/default/quick_search.css	(revision 5134)
+++ trunk/expressoMail1_2/templates/default/quick_search.css	(revision 5172)
@@ -58,5 +58,5 @@
 .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 .menu-control { float:right; margin-left:400px; 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;}
Index: trunk/expressoMail1_2/setup/phpgw_pt-br.lang
===================================================================
--- trunk/expressoMail1_2/setup/phpgw_pt-br.lang	(revision 5158)
+++ trunk/expressoMail1_2/setup/phpgw_pt-br.lang	(revision 5172)
@@ -727,3 +727,6 @@
 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?
+No mail	expressoMail1_2	pt-br	Sem e-mail
+It is not possible to add this contact as a recipient because it does not have email	expressoMail1_2	pt-br	Não é possível adicionar esse contato como destinatário, porque ele não tem e-mail
+Unable to remove the message (s) of shared folders which you do not have permission.	expressoMail1_2	pt-br	Não foi possível remover as mensagens da(s) pastas compartilhadas as quais você não possui permissão.
 
Index: trunk/expressoMail1_2/inc/class.imap_functions.inc.php
===================================================================
--- trunk/expressoMail1_2/inc/class.imap_functions.inc.php	(revision 5158)
+++ trunk/expressoMail1_2/inc/class.imap_functions.inc.php	(revision 5172)
@@ -595,4 +595,59 @@
 	function get_info_msgs($params) {
 		include_once("class.exporteml.inc.php");
+		
+		if(array_key_exists('messages', $params)){
+			$sel_msgs = explode(",", $params['messages']);
+			@reset($sel_msgs);
+			$sorted_msgs = array();
+			foreach($sel_msgs as $idx => $sel_msg) {
+				$sel_msg = explode(";", $sel_msg);
+				if(array_key_exists($sel_msg[0], $sorted_msgs)){
+					$sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
+				}
+				else {
+					$sorted_msgs[$sel_msg[0]] = $sel_msg[1];
+				}
+			}
+			unset($sorted_msgs['']);	
+		
+			$return = array();
+			$array_names_keys = array_keys($sorted_msgs);
+			
+			for($i = 0; $i < count($sorted_msgs); $i++){
+			
+				$new_params = array();
+				$attach_params = array();
+			
+				$new_params["msg_folder"]= $array_names_keys[$i];
+				$attach_params["folder"] = $params["folder"];
+				$msgs = explode(",",$sorted_msgs[$array_names_keys[$i]]);
+				$exporteml = new ExportEml();
+				$unseen_msgs = array();
+				foreach($msgs as $msg_number) {
+					$new_params["msg_number"] = $msg_number;
+					//ini_set("display_errors","1");
+					$msg_info = $this->get_info_msg($new_params);
+
+					$this->mbox = $this->open_mbox($array_names_keys[$i]); //Não sei porque, mas se não abrir de novo a caixa dá erro.
+					$msg_info['header'] = $this->get_info_head_msg($msg_number);
+
+					$attach_params["num_msg"] = $msg_number;
+					$msg_info['array_attach'] = $exporteml->get_attachments_in_array($attach_params);
+					imap_close($this->mbox);
+					$this->mbox=false;
+					array_push($return,serialize($msg_info));
+				
+					if($msg_info['Unseen'] == "U" || $msg_info['Recent'] == "N"){
+							array_push($unseen_msgs,$msg_number);
+					}
+				}
+			}
+			if($unseen_msgs){
+				$msgs_list = implode(",",$unseen_msgs);
+				$array_msgs = array('folder' => $new_params["msg_folder"], "msgs_to_set" => $msgs_list, "flag" => "unseen");
+				$this->set_messages_flag($array_msgs);
+			}
+			return $return;
+		}else{
 		$return = array();
 		$new_params = array();
@@ -626,6 +681,6 @@
 			$this->set_messages_flag($array_msgs);
 		}
-
 		return $return;
+	}
 	}
 
@@ -2069,4 +2124,6 @@
 		if($mbox_stream)
 			imap_close($mbox_stream, CL_EXPUNGE);
+			
+		$return['status'] = true;
 		return $return;
 	}
@@ -3469,9 +3526,11 @@
 	}
 
-
-	function move_search_messages($params){
-		$params['selected_messages'] = urldecode($params['selected_messages']);
-		$params['new_folder'] = urldecode($params['new_folder']);
-		$params['new_folder_name'] = urldecode($params['new_folder_name']);
+	function move_delete_search_messages($params){
+		$move = false;
+		$msg_no_move = "";
+	
+		$params['selected_messages'] = urldecode($params['selected_messages_move']);
+		$params['new_folder'] = urldecode($params['new_folder_move']);
+		$params['new_folder_name'] = urldecode($params['new_folder_name_move']);
 		$sel_msgs = explode(",", $params['selected_messages']);
 		@reset($sel_msgs);
@@ -3485,5 +3544,5 @@
 				$sorted_msgs[$sel_msg[0]] = $sel_msg[1];
 			 }
-		}
+		}		
 		@ksort($sorted_msgs);
 		$last_return = false;
@@ -3491,12 +3550,108 @@
 			$params['msgs_number'] = $msgs_number;
 			$params['folder'] = $folder;
-			if($params['new_folder'] && $folder != $params['new_folder']){
-				$last_return = $this -> move_messages($params);
-			}
-			elseif(!$params['new_folder'] || $params['delete'] ){
-				$last_return = $this -> delete_msgs($params);
+				
+			$last_return = $this->move_messages($params);
+			
+			if($last_return['status']){
+				$move = true;
+			}else{
+				$msg_no_move =  $params['msgs_number'];
+			}
+		}
+		$sel_msgs = null;		
+		$params['selected_messages'] = urldecode($params['selected_messages_delete']);
+		$params['new_folder'] = urldecode($params['new_folder_delete']);
+		$params['new_folder_name'] = urldecode($params['new_folder_name_delete']);
+		$sel_msgs = explode(",", $params['selected_messages']);
+		@reset($sel_msgs);
+		$sorted_msgs = array();
+		foreach($sel_msgs as $idx => $sel_msg) {
+			$sel_msg = explode(";", $sel_msg);
+			 if(array_key_exists($sel_msg[0], $sorted_msgs)){
+			 	$sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
+			 }
+			 else {
+				$sorted_msgs[$sel_msg[0]] = $sel_msg[1];
+			 }
+		}
+		@ksort($sorted_msgs);
+		$last_return = false;
+		foreach($sorted_msgs as $folder => $msgs_number) {
+			$params['msgs_number'] = $msgs_number;
+			$params['folder'] = $folder;
+		
+			$params['folder'] = $params['new_folder_delete'];
+			$last_return = $this->delete_msgs($params);
+			$last_return['deleted'] = true;
+			if($last_return['status']){
+				$move = true;
+			}else{
+				$msg_no_move =  $params['msgs_number'];
+			}
+		
+		}
+	
+		if($move)
+			$last_return['move'] = true;
+			
+		if($msg_no_move != "")
+			$last_return['no_move'] = $msg_no_move;
+		
+		return $last_return;
+	}
+
+	function move_search_messages($params){
+		$params['selected_messages'] = urldecode($params['selected_messages']);
+		$params['new_folder'] = urldecode($params['new_folder']);
+		$params['new_folder_name'] = urldecode($params['new_folder_name']);
+		$sel_msgs = explode(",", $params['selected_messages']);
+		$move = false;
+		$msg_no_move = "";
+		
+		@reset($sel_msgs);
+		$sorted_msgs = array();
+		foreach($sel_msgs as $idx => $sel_msg) {
+			$sel_msg = explode(";", $sel_msg);
+			 if(array_key_exists($sel_msg[0], $sorted_msgs)){
+			 	$sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
+			 }
+			 else {
+				$sorted_msgs[$sel_msg[0]] = $sel_msg[1];
+			 }
+		}
+		@ksort($sorted_msgs);
+		$last_return = false;
+		foreach($sorted_msgs as $folder => $msgs_number) {
+			$params['msgs_number'] = $msgs_number;
+			$params['folder'] = $folder;
+			
+		if($params['delete'] === 'true'){
+			$params['folder'] = $params['new_folder'];
+			$last_return = $this->delete_msgs($params);
 				$last_return['deleted'] = true;
-			}
-		}
+			
+			if($last_return['status']){
+				$move = true;
+			}else{
+				$msg_no_move =  $params['msgs_number'];
+			}
+			
+		}else{
+				$last_return = $this->move_messages($params);
+				
+				if($last_return['status']){
+					$move = true;
+				}else{
+					$msg_no_move =  $params['msgs_number'];
+			}
+		}
+		}
+		
+		if($move)
+			$last_return['move'] = true;
+			
+		if($msg_no_move != "")
+			$last_return['no_move'] = $msg_no_move;
+			
 		return $last_return;
 	}
@@ -5066,5 +5221,5 @@
 		
 		if(!isset($params['sort']))
-			$params['sort'] = SORTDATE;
+			$params['sort'] = 'SORTDATE_REVERSE';
 				
 		$params['search'] = mb_convert_encoding($params['search'], 'UTF-8',mb_detect_encoding($params['search'].'x', 'UTF-8, ISO-8859-1'));
@@ -5081,5 +5236,5 @@
 		{
 			$imap = $this->open_mbox( $folder ) ;
-			$msgIds = imap_sort( $imap , SORTDATE , 0 , SE_UID , $search ,'UTF-8');
+			$msgIds = imap_sort( $imap , SORTDATE , 1 , SE_UID , $search ,'UTF-8');
 						
 			$count += count($msgIds);  
@@ -5140,9 +5295,10 @@
 	} 
 	
-		$return['msgs'] = $this->array_msort($return['msgs'] , array( $sA => SORT_ASC));
 			
+		if($params['sort'] !== 'SORTDATE_REVERSE')
 		if(strpos($params['sort'],'REVERSE') !== false)
-			$return['msgs'] = array_reverse($return['msgs']);	
-				
+				$return['msgs'] = $this->array_msort($return['msgs'] , array( $sA => SORT_DESC));
+			else
+				$return['msgs'] = $this->array_msort($return['msgs'] , array( $sA => SORT_ASC));
 		
 		$k = -1;
Index: trunk/expressoMail1_2/inc/class.exporteml.inc.php
===================================================================
--- trunk/expressoMail1_2/inc/class.exporteml.inc.php	(revision 5134)
+++ trunk/expressoMail1_2/inc/class.exporteml.inc.php	(revision 5172)
@@ -183,5 +183,139 @@
 	// apenas um arquivo a ser exportado, 
 	// não seja criado em zip 
+	//
+	// Funcao altarada para exportar uma ou
+	// varia mensagens de um pesquisa
+
 	function makeAll($params) {
+	//Exporta menssagens selecionadas na pesquisa
+	if($params['folder'] === 'false'){
+		
+		$this->folder = $params['folder'];
+		$error = False;
+		$fileNames = "";
+		
+		$sel_msgs = explode(",", $params['msgs_to_export']);
+		@reset($sel_msgs);
+		$sorted_msgs = array();
+		foreach($sel_msgs as $idx => $sel_msg) {
+			$sel_msg = explode(";", $sel_msg);
+			if(array_key_exists($sel_msg[0], $sorted_msgs)){
+				$sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
+			}
+			else {
+				$sorted_msgs[$sel_msg[0]] = $sel_msg[1];
+			}
+		}
+			
+		unset($sorted_msgs['']);			
+
+		
+		// Verifica se as n mensagens selecionadas
+		// se encontram em um mesmo folder
+		if (count($sorted_msgs)==1){
+							
+			$array_names_keys = array_keys($sorted_msgs);
+			$this->folder = mb_convert_encoding($array_names_keys[0], "UTF7-IMAP","UTF-8, ISO-8859-1, UTF7-IMAP");
+			$msg_number = explode(',', $sorted_msgs[$array_names_keys[0]]);
+			$tempDir = $this->tempDir;
+			$this->connectImap();
+			
+			//verifica se apenas uma mensagem foi selecionada e exportar em .eml			
+			if(count($msg_number) == 1){
+				$header         = $this->getHeader($msg_number[0]);
+				$body           = $this->getBody($msg_number[0]);                       
+				$sEMLData       = $this->parseEml($header, $body);                     
+				$fileName       = $this->CreateFileEml($sEMLData, $tempDir, $msg_number[0]."_".$_SESSION[ 'phpgw_session' ][ 'session_id' ]);
+		
+				
+				imap_close($this->mbox_stream);
+				if (!$fileName) {
+					return false;
+				}else{
+					return $tempDir.'/'.$fileName;
+				}
+			}
+			
+			//cria um .zip com as mensagens selecionadas
+			for($i = 0; $i < count($msg_number); $i++) 
+			{
+				$header         = $this-> getHeader($msg_number[$i]);                                                                                   
+				$body           = $this-> getBody($msg_number[$i]);                     
+				$sEMLData       = $this -> parseEml($header, $body);                   
+				$fileName       = $this -> CreateFileEml($sEMLData, $tempDir, $msg_number[$i]);
+
+				if(!$fileName) 
+				{
+					$error = True;                                 
+					break;
+				} else{
+					$fileNames .= "\"".$fileName."\" ";                     
+				}
+			}
+			imap_close($this->mbox_stream);
+
+			$nameFileZip = 'False';                 
+			if($fileNames && !$error) 
+			{
+				$nameFileZip = $this -> createFileZip($fileNames, $tempDir);
+				if($nameFileZip) 
+				{               
+					$file = $tempDir.'/'.$nameFileZip;
+				} else {
+					$file = false;
+				}                                                               
+			}
+			else 
+			{
+				$file = false;
+			}
+
+			return $file;
+		
+		//exporta mensagens de diferentes pastas
+		}else{
+			$array_names_keys = array_keys($sorted_msgs);
+			
+			for($i = 0; $i < count($array_names_keys); $i++){ 
+				$this->folder = mb_convert_encoding($array_names_keys[$i], "UTF7-IMAP","UTF-8, ISO-8859-1, UTF7-IMAP");
+				$msg_number = explode(',', $sorted_msgs[$array_names_keys[$i]]);
+				$tempDir = $this->tempDir;
+				$this->connectImap();
+				
+				for($j = 0; $j < count($msg_number); $j++) 
+				{
+					$header         = $this-> getHeader($msg_number[$j]);                                                                                   
+					$body           = $this-> getBody($msg_number[$j]);                     
+					$sEMLData       = $this -> parseEml($header, $body);                   
+					$fileName       = $this -> CreateFileEml($sEMLData, $tempDir, $msg_number[$j]);
+
+					if(!$fileName) 
+					{
+						$error = True;                                 
+						break;
+					} else{
+						$fileNames .= "\"".$fileName."\" ";                     
+					}
+				}
+				imap_close($this->mbox_stream);
+			}
+			$nameFileZip = 'False';                 
+			if($fileNames && !$error) 
+			{
+				$nameFileZip = $this -> createFileZip($fileNames, $tempDir);
+				if($nameFileZip) 
+				{               
+					$file = $tempDir.'/'.$nameFileZip;
+				} else {
+					$file = false;
+				}                                                               
+			}
+			else 
+			{
+				$file = false;
+			}
+			return $file;
+		}
+	}else{
 		// Exportacao de mensagens arquivadas localmente
 		if($params['l_msg'] == "t")
@@ -235,5 +369,5 @@
 		{
 			$this-> folder = $params['folder'];
-			$this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","UTF-8");
+				$this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","UTF-8, ISO-8859-1, UTF7-IMAP");
 			$array_ids = explode(',', $params['msgs_to_export']);
 			$error = False;
@@ -293,4 +427,5 @@
 			return $file;
 		}
+    }
     }
 
Index: trunk/expressoMail1_2/inc/class.attachment.inc.php
===================================================================
--- trunk/expressoMail1_2/inc/class.attachment.inc.php	(revision 5134)
+++ trunk/expressoMail1_2/inc/class.attachment.inc.php	(revision 5172)
@@ -363,9 +363,9 @@
  		 
                             //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'))
+                            if( !$name && isset($structure->disposition) && (strtolower($structure->disposition) === 'attachment' || strtolower($structure->ctype_primary) == 'image' ||  strtolower($structure->ctype_primary.'/'.$structure->ctype_secondary) == 'application/octet-stream'))
 					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') )
+			     if( !$name && isset($structure->disposition) && (strtolower($structure->disposition) === 'attachment' || strtolower($structure->ctype_primary) == 'image' ||  strtolower($structure->ctype_primary.'/'.$structure->ctype_secondary) == 'application/octet-stream') )
 					foreach ($structure->ctype_parameters as $i => $v)
 						if(strpos($i , 'name') !== false)
@@ -439,4 +439,15 @@
                          $name = $part->ctype_parameters['name'];
 
+                     //Attachments com nomes grandes são quebrados em varias partes VER RFC2231
+                        if( !$name && isset($part->disposition) && (strtolower($part->disposition) === 'attachment' || strtolower($part->ctype_primary) == 'image' ||  strtolower($part->ctype_primary.'/'.$part->ctype_secondary) == 'application/octet-stream') )
+                                    foreach ($part->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($part->disposition) && (strtolower($part->disposition) === 'attachment' || strtolower($part->ctype_primary) == 'image' ||  strtolower($part->ctype_primary.'/'.$part->ctype_secondary) == 'application/octet-stream') )
+                                    foreach ($part->ctype_parameters as $i => $v)
+                                            if(strpos($i , 'name') !== false)
+                                                    $name .= urldecode(str_ireplace(array('ISO-8859-1','UTF-8','US-ASCII'),'',$v));		
+                       ////////////////////////////////////////////////////////////////////////////////////
+                    
                     if($name && (strlen($name) - (strrpos($name, '.')+1) === 3 )) 
                         $ext = strtolower(substr ( $name , (strrpos($name, '.')+1) ));		
Index: trunk/expressoMail1_2/inc/class.ldap_functions.inc.php
===================================================================
--- trunk/expressoMail1_2/inc/class.ldap_functions.inc.php	(revision 5134)
+++ trunk/expressoMail1_2/inc/class.ldap_functions.inc.php	(revision 5172)
@@ -316,6 +316,7 @@
             //$retorno = $retorno_personal + $retorno_global;
             $retorno = array_merge($retorno_personal, $retorno_global);
-            $retorno['search_for'] = $params['search_for'];
+			
 			$retorno['type_catalog'] = "A";
+			$retorno['search_for'] = $params['search_for'];
             return $retorno;
         }
@@ -336,12 +337,15 @@
             $DBService = ServiceLocator::getService('db');
             $results   = $DBService->search_contacts($params['search_for']);
+			$DBService = ServiceLocator::getService('db');
+            $results2   = $DBService->search_groups($params['search_for']);
+            $results   = array_merge($results, $results2);
             
             if(!$all)
                 $results['type_catalog'] = "P";
-            $results['search_for'] = $params['search_for'];
 			
 			foreach($results as $i=>$value)
 				$results[$i]['type_contact'] = "P";
 			
+			$results['search_for'] = $params['search_for'];
 			return $results;
         } 
@@ -444,9 +448,10 @@
                 $info_return['type_catalog'] = "G";
             
-            $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";
+				
+			$info_return['search_for'] = $params['search_for'];
             return $info_return;
         } 
Index: trunk/expressoMail1_2/js/abas.js
===================================================================
--- trunk/expressoMail1_2/js/abas.js	(revision 5134)
+++ trunk/expressoMail1_2/js/abas.js	(revision 5172)
@@ -155,7 +155,11 @@
         }
 	
-	if (! id_value) // Is new message?
+	if (! id_value){ // Is new message?
 		var ID = parseInt(BordersArray[(BordersArray.length-1)].sequence) + 1;
-	else
+			if(isNaN(ID)){
+				var aux = BordersArray[(BordersArray.length-1)].sequence.split("_");
+				ID = parseInt(aux[1]) + 1;
+			}
+        }else
 	{
 		if (Element("border_id_"+id_value)) // It's opened already!
Index: trunk/expressoMail1_2/js/common_functions.js
===================================================================
--- trunk/expressoMail1_2/js/common_functions.js	(revision 5134)
+++ trunk/expressoMail1_2/js/common_functions.js	(revision 5172)
@@ -684,4 +684,40 @@
 
 function search_emails(value){
+	var resize = false;
+        resize = resize_borders();
+        if (!resize){
+            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){				                
+                var children = Element('border_tr').childNodes;
+                var bolDelete = true;
+                for (var i=0; i<children.length; i++) {
+                    if ((children[i].nodeName === 'TD') && (children[i].id!=='border_id_0') && (children[i].id!=='border_blank'))
+                    {
+                        bolDelete = true;
+                        var num_child = children[i].id.toString().substr(10);
+                        alternate_border(num_child);
+                        if (editTest(num_child)){
+                            bolDelete = false;
+                        }
+                        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');
+								return;
+							}else{
+								return;
+							}
+						}
+                    }
+				}				
+            }else{			
+                alert(get_lang('Reached maximum tab limit') + str_continue );
+                return;
+            }
+        }
 	connector.loadScript("TreeS");
 	connector.loadScript("search");
@@ -691,5 +727,5 @@
 	}
 	EsearchE.showForms(value);
-}
+	}
 
 function source_msg(id_msg,folder){
Index: trunk/expressoMail1_2/js/main.js
===================================================================
--- trunk/expressoMail1_2/js/main.js	(revision 5158)
+++ trunk/expressoMail1_2/js/main.js	(revision 5172)
@@ -603,35 +603,41 @@
 
 
-function move_search_msgs(border_id, new_folder, new_folder_name){
   
-	if( preferences.use_local_messages == 1 && expresso_local_messages.isArchiving( msgs_number, folder ) ){
+function move_search_msgs(border_id, new_folder, new_folder_name, action){
+
+	var msg_to_delete = "";
+	var msg_to_move = "";
+	var selected_messages = '';
+	var temp_msg;
+	var remove_currente_folder = "";
+	var id_border = currentTab.replace(/[a-zA-Z_]+/, "");
+	
+	var delete_msg = false;
+	
+	if(new_folder_name == special_folders['Trash']){
+		delete_msg = true;
+		}
+	selected_messages = get_selected_messages_search();
+	
+	if( preferences.use_local_messages == 1 && expresso_local_messages.isArchiving( selected_messages, folder ) ){
 	  alert( "Impossivel mover mensagens que estão ainda estão sendo arquivadas." );
 	  return;
 	}
-
-	var selected_messages = '';
-	var temp_msg;
-	var main_list = Element("tbody_box_"+getNumBoxFromTabId(currentTab)).childNodes;
-	for (j = 0; j < main_list.length; j++)	{
-		var check_box = main_list[j].firstChild.firstChild;
-		if(check_box && check_box.checked) {
-			if (proxy_mensagens.is_local_folder(main_list[j].getAttribute('name'))) {
-				alert(get_lang("You cant manipulate local messages on search"));
-				return;
-			}
-			selected_messages += main_list[j].id + ',';
-		}
-	}
-	selected_messages = selected_messages.substring(0,(selected_messages.length-1));
 	var handler_move_search_msgs = function(data){
 		if(!data || !data.msgs_number)
 			return;
 		else if(data.deleted) {
-			if (data.msgs_number.length == 1)
+			if(data.no_move && data.move)
+				alert(get_lang("Unable to remove the message (s) of shared folders which you do not have permission."));
+			else if (data.msgs_number.length == 1)
 				write_msg(get_lang("The message was deleted."));
 			else
 				write_msg(get_lang("The messages were deleted."));
-		}
-		else{
+		}else if(data.status == false && data.move ){
+					alert(get_lang("Unable to remove the message (s) of shared folders which you do not have permission."));
+		}else if(data.status == false){
+					alert(get_lang("You don't have permission for this operation in this shared folder!"));
+					return false;
+		}else{
 			if (data.msgs_number.length == 1)
 				write_msg(get_lang("The message was moved to folder ") + lang_folder(data.new_folder_name));
@@ -640,15 +646,51 @@
 		}
 
+		if(data.no_move){
+			var no_remove = data.no_move.split(',');
+			var continua = true;
+			
 		selected_messages = selected_messages.split(",");
 		for (i = 0; i < selected_messages.length; i++){
-			removeAll(selected_messages[i]);
-		}
+				for(j = 0; j < no_remove.length; j++)
+					if(selected_messages[i] == no_remove[j])
+						continua = false;
+				if(continua)	
+					removeAll(selected_messages[i]+'_s'+id_border);
+				continua = true;
+		}
+		}else{
+			selected_messages = selected_messages.split(",");
+			for (i = 0; i < selected_messages.length; i++){
+				removeAll(selected_messages[i]+'_s'+id_border);
+		
+			}
+		}
+		
 		// Update Box BgColor
 		var box = Element("tbody_box_"+getNumBoxFromTabId(currentTab)).childNodes;
-		if(main_list.length > 1){
+		if(box.length > 1){
 			updateBoxBgColor(box);
 		}
 		connector.purgeCache();
 
+		
+		if(remove_currente_folder != ""){
+			var mail_msg = Element('tbody_box').childNodes;
+			remove_currente_folder = remove_currente_folder.substring(0,(remove_currente_folder.length-1));
+			remove_currente_folder = remove_currente_folder.split(",");
+			for(i = 0; i < remove_currente_folder.length; i++)
+				removeAll(remove_currente_folder[i]);
+
+			// Update Box BgColor
+			var box = Element("tbody_box");
+			if(box.childNodes.length > 0){
+				updateBoxBgColor(box.childNodes);
+			}
+			if(folder == get_current_folder()){
+				Element('tot_m').innerHTML = parseInt(Element('tot_m').innerHTML) - remove_currente_folder.length;
+			}
+		}
+		
+		draw_tree_folders();
 		EsearchE.refresh();
 	}
@@ -660,38 +702,61 @@
 			selected_msg_array = selected_messages.split(",");
 			for (i = 0; i < selected_msg_array.length; i++){
-				var tr = Element(selected_msg_array[i]);
-				if (tr.getAttribute('name') == new_folder)
+				var tr = Element(selected_msg_array[i]+'_s'+id_border);
+				if(tr.getAttribute('name') == current_folder)
+					remove_currente_folder += tr.id.replace(/_[a-zA-Z0-9]+/,"")+',';
+				if ((action == 'delete' && tr.getAttribute('name') == 'INBOX'+cyrus_delimiter+special_folders['Trash']) || !(parseInt(preferences.save_deleted_msg)))
 				{
+					msg_to_delete +=   ','+special_folders['Trash']+';'+tr.id.replace(/_[a-zA-Z0-9]+/,"");
+				}
+				else if (!(tr.getAttribute('name') == new_folder && action != 'delete'))
+				{
+					msg_to_move = (tr.getAttribute('name') == null?get_current_folder():tr.getAttribute('name'));
+					selected_param += ','+msg_to_move+';'+tr.id.replace(/_[a-zA-Z0-9]+/,"");
+				}else{
 					write_msg(get_lang('At least one message have the same origin'));
 					return false;
 				}
-				trfolder = (tr.getAttribute('name') == null?get_current_folder():tr.getAttribute('name'));
-					selected_param += ','+trfolder+';'+tr.id.replace(/_[a-zA-Z0-9]+/,"");
 			}
 		}
 		else
 		{
-			var tr=Element(selected_messages);
-			if (tr.getAttribute('name') == new_folder)
-			{
+			var tr=Element(selected_messages+'_s'+id_border);
+			if(tr.getAttribute('name') == current_folder)
+					remove_currente_folder += tr.id.replace(/_[a-zA-Z0-9]+/,"")+',';
+			if((action == 'delete' && tr.getAttribute('name') == 'INBOX'+cyrus_delimiter+special_folders['Trash']) || !(parseInt(preferences.save_deleted_msg))){
+				msg_to_delete = special_folders['Trash']+';'+tr.id.replace(/_[a-zA-Z0-9]+/,"");
+			}else if (!(tr.getAttribute('name') == new_folder && action != 'delete')){
+				trfolder = (tr.getAttribute('name') == null?get_current_folder():tr.getAttribute('name'));
+				selected_param=trfolder+';'+tr.id.replace(/_[a-zA-Z0-9]+/,"");
+			}else{
 				write_msg(get_lang('The origin folder and the destination folder are the same.'));
 				return false;
 			}
-			trfolder = (tr.getAttribute('name') == null?get_current_folder():tr.getAttribute('name'));
-			selected_param=trfolder+';'+tr.id.replace(/_[a-zA-Z0-9]+/,"");
 		}
 		var params = "";
-		if (!new_folder && parseInt(preferences.save_deleted_msg)){
+		if(msg_to_delete != "" && msg_to_move != ""){
+			params += "&selected_messages_move="+url_encode(selected_param);
+			params += "&new_folder_move="+url_encode(new_folder);
+			params += "&new_folder_name_move="+url_encode(new_folder_name);
+		
 			new_folder = 'INBOX'+cyrus_delimiter+trashfolder;
 			new_folder_name = trashfolder;
-			params = "&delete=true";
-		}
-
-		params += "&selected_messages="+url_encode(selected_param);
-		if(new_folder && parseInt(preferences.save_deleted_msg)) {
+			params += "&selected_messages_delete="+url_encode(msg_to_delete);
+			params += "&new_folder_delete="+url_encode(new_folder);
+			cExecute ("$this.imap_functions.move_delete_search_messages", handler_move_search_msgs, params);
+		}else if(msg_to_delete != ""){
+			new_folder = 'INBOX'+cyrus_delimiter+trashfolder;
+			new_folder_name = trashfolder;
+			params += "&delete=true";
+			params += "&selected_messages="+url_encode(msg_to_delete);
+			params += "&new_folder="+url_encode(new_folder);
+			cExecute ("$this.imap_functions.move_search_messages", handler_move_search_msgs, params);
+		}else{
+			params = "&selected_messages="+url_encode(selected_param);
+			params += "&delete=false";
 			params += "&new_folder="+url_encode(new_folder);
 			params += "&new_folder_name="+url_encode(new_folder_name);
-		}
 		cExecute ("$this.imap_functions.move_search_messages", handler_move_search_msgs, params);
+	}
 	}
 	else
@@ -902,4 +967,53 @@
 }
 
+function archive_search_msgs(folder_dest) {
+	
+	var id_msgs = "";
+	id_msgs = get_selected_messages_search();
+	var msg_to_arquive = "";
+	var messages = "";
+	var id_border = currentTab.replace(/[a-zA-Z_]+/, "");
+
+	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';
+
+	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";
+	}
+
+	id_msgs =  id_msgs.split(',');
+	for (i = 0; i < id_msgs.length; i++){
+		var tr = Element(id_msgs[i]+'_s'+id_border);
+		msg_to_arquive = (tr.getAttribute('name') == null?get_current_folder():tr.getAttribute('name'));
+		messages += ','+msg_to_arquive+';'+tr.id.replace(/_[a-zA-Z0-9]+/,"");
+	}
+	
+	cExecute( "$this.imap_functions.get_info_msgs&messages=" + messages+"&folder="+folder_dest , handler_arquivar_mensagens );
+}
+
+
 function archive_msgs(folder,folder_dest,id_msgs) {
 	if(proxy_mensagens.is_local_folder(folder)) {
@@ -912,6 +1026,11 @@
         }
 
-	if(!id_msgs)
+	if(!id_msgs){
+		if (currentTab != 0 && currentTab.indexOf("search_")  >= 0){
+			archive_search_msgs(folder_dest);
+			return;
+		}else
 		id_msgs = get_selected_messages();
+	}	
 
 	if ( parseInt(id_msgs) <= 0 || id_msgs.length <= 0 )
@@ -1002,4 +1121,46 @@
 	    update_menu();
 }
+
+function action_msg_selected_from_search(aba, evento){
+	if(evento == "delete")
+		move_search_msgs(aba,'INBOX/Trash', 'Trash', 'delete');
+}
+
+function get_all_messages_search(){
+	var aba = document.getElementById('content_id_'+currentTab);
+	var messages = "";
+	jQuery(function() {
+ 	    jQuery("#"+aba.id+" tr").each(function(i, main_list) { 
+				messages += main_list.id.replace(/_[a-zA-Z0-9]+/,"") + ',' ;
+ 	    });              
+ 	     
+	});
+	if(messages.indexOf(',') == 0)
+		messages = messages.substring(1,(messages.length));
+	return messages.substring(0,(messages.length-1));
+}
+
+function get_selected_messages_search(){
+	var aba = document.getElementById('content_id_'+currentTab);
+	var selected_messages = "";
+	jQuery(function() {
+ 	    jQuery("#"+aba.id+" tr").each(function(i, main_list) { 
+		var check_box = main_list.firstChild.firstChild;
+			if(check_box && check_box.checked) {
+				selected_messages += main_list.id.replace(/_[a-zA-Z0-9]+/,"") + ',' ;
+			};
+ 	    });              
+ 	     
+	});
+	if (selected_messages != ""){
+		if(selected_messages.indexOf(',') == 0)
+			selected_messages = selected_messages.substring(1,(selected_messages.length));
+		selected_messages = selected_messages.substring(0,(selected_messages.length-1));
+		return selected_messages;
+	}else{
+		return false;
+	}
+}
+
 
 function get_selected_messages(){
@@ -1517,5 +1678,6 @@
 				}
 			}
-			RichTextEditor.setInitData(new_border_ID,'<div><br type="_moz"></div>' + data.body);
+			RichTextEditor.setInitData(new_border_ID, data.body, 'edit');
+      
 			break;
 		default:
@@ -2404,8 +2566,70 @@
 }
 
+function print_search_msg(){		
+	var folder = "<h2>&nbsp;Resultado da Pesquisa&nbsp;<font color=\"#505050\" face=\"Verdana\" size=\"1\"></h2>";
+	msgs_number = get_selected_messages_search();
+	var tbody = Element('divScrollMain_'+numBox).firstChild.firstChild.innerHTML;
+	var id_border = currentTab.replace(/[a-zA-Z_]+/, "");
+	
+	if(msgs_number){
+		msgs_number = msgs_number.split(",");
+		var tbody = "";
+		for(var i = 0; i < msgs_number.length; i++){
+			tbody += "<tr id=\""+msgs_number[i]+"_s"+id_border+"\" class=\"tr_msg_unread tr_msg_read2\">"+ Element(msgs_number[i]+'_s'+id_border).innerHTML+"</tr>";
+		}
+	}else{
+		msgs_number = get_all_messages_search();
+		msgs_number = msgs_number.split(",");
+		var tbody = "";
+		for(var i = 0; i < msgs_number.length; i++){
+			tbody += "<tr id=\""+msgs_number[i]+"_s"+id_border+"\" class=\"tr_msg_unread tr_msg_read2\">"+ Element(msgs_number[i]+'_s'+id_border).innerHTML+"</tr>";
+		}
+	}
+
+	
+	var print_width = screen.width - 200; 
+	var x = ((screen.width - print_width) / 2); 
+	var y = ((screen.height - 400) / 2) - 35; 
+	var window_print = window.open('','ExpressoMail','width='+print_width+',height=400,resizable=yes,scrollbars=yes,left='+x+',top='+y); 
+	seekDot = (is_ie ? /width=24/gi : /width="24"/gi); 
+
+	var thead = "<tr class=\"message_header\"><td id=\"message_header_FOLDER_0\" class=\"th_resizable\" align=\"left\" width=\"20%\">Pasta</td><td id=\"message_header_SORTFROM_0\" class=\"th_resizable\" align=\"left\" width=\"20%\">De</td><td id=\"message_header_SORTSUBJECT_0\" class=\"th_resizable\" align=\"left\" width=\"*\">Assunto</td><td id=\"message_header_SORTARRIVAL_0\" class=\"th_resizable\" align=\"center\" width=\"11%\"><b>Data</b><img src=\"templates/default/images/arrow_descendant.gif\"></td><td id=\"message_header_SORTSIZE_0\" class=\"th_resizable\" align=\"left\" width=\"11%\">Tamanho</td></tr>";
+	tbody = tbody.replace(seekDot, "style='display:none'"); 
+	seekDot = (is_ie ? /width=16/gi : /width="16"/gi); 
+
+	tbody = tbody.replace(seekDot, "style='display:none'"); 
+	seekDot = (is_ie ? /width=12/gi : /width="12"/gi); 
+
+	tbody = tbody.replace(seekDot, "style='display:none'"); 
+	while (1){ 
+		try{ 
+			window_print.document.open(); 
+	 	    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>' 
+	 	    + cabecalho + '</h4><hr>' 
+	 	    + '<h2>'+folder+'</h2><hr/><blockquote><font size="2">' 
+	 	    + '<table width="100%" cellpadding="0" cellspacing="0">' 
+	 	    + '<thead>' + thead + '</thead><tbody>' + tbody + '</tbody>' 
+	 	    + '</table></font></blockquote></body></html>'; 
+	 	    window_print.document.write(html); 
+	 	    window_print.document.close(); 
+	 	    break; 
+		} 
+		catch(e){ 
+			//alert(e.message); 
+		} 
+	} 
+	window_print.document.close(); 
+	window_print.print(); 
+}
+
 function print_all(){
 	if (openTab.type[currentTab] == 2)
 		return print_msg(current_folder,currentTab.substr(0,currentTab.indexOf("_r")),currentTab);
 
+	if (currentTab != 0 && currentTab.indexOf("search_")  >= 0){
+		return print_search_msg();
+	}
+		
 	var folder= Element('border_id_0').innerHTML;
 	//var thead = Element('divScrollHead_'+numBox).firstChild.firstChild.innerHTML; 
@@ -2631,6 +2855,24 @@
 		return;
 	}
-	var msgs_to_export = this.get_selected_messages();
-
+	var search = false;
+	var id_border = currentTab.replace(/[a-zA-Z_]+/, "");
+
+	if(currentTab != 0 && currentTab.indexOf("search_")  >= 0){
+		var msgs_to_export = this.get_selected_messages_search();
+		if (!msgs_to_export){
+			write_msg(get_lang('No selected message.'));
+			return;
+		}
+		var selected_param = "";
+		msgs_to_export = msgs_to_export.split(",");
+		search = true;
+		for (i = 0; i < msgs_to_export.length; i++){
+			var tr = Element(msgs_to_export[i]+'_s'+id_border);
+			msg_to_move = (tr.getAttribute('name') == null?get_current_folder():tr.getAttribute('name'));
+			selected_param += ','+msg_to_move+';'+tr.id.replace(/_[a-zA-Z0-9]+/,"");
+		}
+	}else{
+		var msgs_to_export = this.get_selected_messages();
+	}
 	var handler_export_all_selected_msgs = function(data){
 
@@ -2647,5 +2889,7 @@
 	}
 
-	if (msgs_to_export) {
+	if(search){
+		cExecute ("$this.exporteml.makeAll", handler_export_all_selected_msgs, "folder=false&msgs_to_export="+selected_param);
+	}else if (msgs_to_export) {
 		cExecute ("$this.exporteml.makeAll", handler_export_all_selected_msgs, "folder="+get_current_folder()+"&msgs_to_export="+msgs_to_export);
 		write_msg(get_lang('You must wait while the messages will be exported...'));
@@ -2770,5 +3014,10 @@
 	if(currentTab.toString().indexOf("_r") != -1)
 		msgs_number = currentTab.toString().substr(0,currentTab.toString().indexOf("_r"));
-	else if(msgs_number == 'selected')
+	else if(currentTab != 0 && currentTab.indexOf("search_")  >= 0){
+		var content_search = document.getElementById('content_id_'+currentTab);  'INBOX/Trash', 'Trash',
+		move_search_msgs('content_id_'+currentTab,  'INBOX'+cyrus_delimiter+special_folders['Spam'], special_folders['Spam']);
+		refresh();
+		return;
+	}else if(msgs_number == 'selected')
 		msgs_number = get_selected_messages();
 
Index: trunk/expressoMail1_2/js/search.js
===================================================================
--- trunk/expressoMail1_2/js/search.js	(revision 5134)
+++ trunk/expressoMail1_2/js/search.js	(revision 5172)
@@ -108,5 +108,5 @@
 			Element("check_all_msg").checked = true;
 			EsearchE.all_mailboxes();
-			EsearchE.func_search(value);
+			EsearchE.func_search(value, null, 'SORTDATE_REVERSE');
 		}
 
@@ -662,4 +662,8 @@
 		}
 		else {
+			if(isNaN(numBox)){
+				var aux = numBox.split("_");
+				numBox = parseInt(aux[0]) + 1;
+			}else
 			numBox++;
 
Index: trunk/expressoMail1_2/js/messages_controller.js
===================================================================
--- trunk/expressoMail1_2/js/messages_controller.js	(revision 5158)
+++ trunk/expressoMail1_2/js/messages_controller.js	(revision 5172)
@@ -47,4 +47,13 @@
 		if (msgs_number == 'selected')
 			msgs_number = get_selected_messages();
+		if(currentTab != 0 && currentTab.indexOf("search_")  >= 0){
+			var content_search = document.getElementById('content_id_'+currentTab);
+			action_msg_selected_from_search(content_search.id, 'delete');
+			refresh();
+			//draw_tree_folders();
+			//update_local_box(); 
+			return;
+		}
+			
 		if (!this.is_local_folder(folder)){
 			delete_msgs(folder, msgs_number, border_ID);
Index: trunk/expressoMail1_2/js/local_messages.js
===================================================================
--- trunk/expressoMail1_2/js/local_messages.js	(revision 5134)
+++ trunk/expressoMail1_2/js/local_messages.js	(revision 5172)
@@ -1636,7 +1636,10 @@
             msgs_number = currentTab.toString().substr(0,currentTab.toString().indexOf("_r"));
 	
-        if( msgs_number =='selected' || !msgs_number )
+        if( msgs_number =='selected' || !msgs_number ){
+		if (currentTab != 0 && currentTab.indexOf("search_")  >= 0)
+			msgs_number = get_selected_messages_search();
+		else
 	    msgs_number = get_selected_messages();
-
+		}
 	if( !msgs_number )
 	    return write_msg(get_lang('No selected message.'));
Index: trunk/expressoMail1_2/js/QuickCatalogSearch.js
===================================================================
--- trunk/expressoMail1_2/js/QuickCatalogSearch.js	(revision 5134)
+++ trunk/expressoMail1_2/js/QuickCatalogSearch.js	(revision 5172)
@@ -10,15 +10,15 @@
 	emQuickCatalogSearch.prototype.showList = function(data, begin, end, ID, field)
 	{
-			data_    = data;	
-			id_    = ID;
-            field_ = field;
-            begin_ = begin;
-            end_   = end;
+		data_  = data;	
+		id_    = ID;
+        field_ = field;
+        begin_ = begin;
+        end_   = end;
 
-			keypress_read(data);
-            configure_slider(data);
+		keypress_read(data);
+		configure_slider(data);
 		create_list(data, true);
-            details_results(data);
-			
+		details_results(data);
+
 		id = '1';
 		_this = this;
@@ -36,45 +36,68 @@
 		func_add_contact = function () { 	
 		};		
-		
         _this.showWindow(el_A);	
 	}
-        
-        
+     
+	 
     /* Leitura das teclas de atalho */    
     function keypress_read(data) {	
-		$("#dialog-modal").keydown(function (e) {
+		$("#dialog-modal").unbind('keydown').keydown(function (e) {
 			var keyCode = e.keyCode;
-			arrow = {left: 37, up: 38, right: 39, down: 40, enter: 13, esc: 27};
-			var slider = $( "#slider"  );
+			arrow = {left: 37, up: 38, right: 39, down: 40, enter: 13, esc: 27, space: 32};
+			var slider = $( "#slider" );
 			switch (keyCode) 
 			{
-				case arrow.enter:
+				case arrow.enter:					
 					if(!search_focus){
 						i = $(".ui-selected:last").attr("value") + 1;
-						add_contact_field($("#contact_" + i).html());
+						if($("#actions_"+i).clone().find(".ui-button-text").text() == '+')
+							add_contact_field(document.getElementById("contact_"+i).innerHTML, document.getElementById("actions_"+i), "contact_"+i);
+						else{
+							remove_contact_field(document.getElementById("contact_"+i).innerHTML, document.getElementById("actions_"+i), "contact_"+i);
+						}
 						document.getElementById("busca").value = "";
-						$("#dialog-modal").unbind('keydown');
-					$("#dialog-modal").dialog("close");
+						$("#dialog-modal").dialog("close");
 					}
 					break;
 				case arrow.left:
-					slider.slider("value", $( "#slider" ).slider( "value" ) - 1);
-					create_list(data_, false);		
+					if(!search_focus){
+						slider.slider("value", $( "#slider" ).slider( "value" ) - 1);
+						create_list(data_, false);	
+					}
 					break;
 				case arrow.right:
-					if((($( "#slider" ).slider( "value" ))) == Math.ceil(data_.length/6))
-						break;
-					slider.slider( "value", $( "#slider" ).slider( "value" ) + 1);					
-					create_list(data_, false);							
+					if(!search_focus){
+						if((($( "#slider" ).slider( "value" ))) == Math.ceil(data_.length/6))
+							break;
+						slider.slider( "value", $( "#slider" ).slider( "value" ) + 1);					
+						create_list(data_, false);							
+					}
 					break;
 				case arrow.up:
-					show_detail(data_, "up");
+					if(!search_focus){
+						show_detail(data_, "up");
+					}
 					break;
 				case arrow.down:
-					show_detail(data_, "down");
-						break;
-                                }
+					if(!search_focus){
+						show_detail(data_, "down");
+					}
+					break;
+				case arrow.space:
+
+					if(!search_focus){
+						i = $(".ui-selected:last").attr("value") + 1;
+						if($("#actions_"+i).clone().find(".ui-button-text").text() == '+')
+						{
+							add_contact_field(document.getElementById("contact_"+i).innerHTML, document.getElementById("actions_"+i), "contact_"+i);
+						}else{
+							remove_contact_field(document.getElementById("contact_"+i).innerHTML, document.getElementById("actions_"+i), "contact_"+i);
+						}
+						document.getElementById("busca").value = "";
+					}
+					break;
+			}
 		});	
-							}
+	}
 	
 	
@@ -88,5 +111,5 @@
 			$('li.ui-selected').next().addClass("ui-selected"); 
 			id_contact++;
-                                        }
+		}
 		else {
 			if(id_contact == (($( "#slider" ).slider( "value" ) -1)*6)) 
@@ -95,18 +118,18 @@
 			$('li.ui-selected').prev().addClass("ui-selected"); 
 			id_contact--;
-                                    } 
+		}					
 		line_contact.removeClass("ui-selected").addClass("ui-selectee");
-		var details = $("#detalhes_contato").empty();                                 
+		var details = $("#detalhes_contato").empty();    
 		switch(data_['type_catalog']) {
 			case 'G':
-                                        var extra_fields = (data_['extra_ldap_fields']).split("#");   
+				var extra_fields = (data_['extra_ldap_fields']).split("#");   
 				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>');           
-                                        }
+				}
 				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("|")));                                          
+				{
+					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>" ;
@@ -114,24 +137,32 @@
 							details.append(tmp_campo + '<span class="value">' + data_[id_contact][valor.toLowerCase()][j] + "</span></p>");
 							tmp_campo = "";
-                                            }
-                                        }
-                                    }
-					break;
+						}
+					}
+				}
+				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(utf8_decoder(data_[id_contact].cn) == 'undefined')
+					details.append('<p><label class="attribute">' + utf8_decoder(data_[id_contact].title) + '</label>' + '<span class="value">' + data_[id_contact].short_name + '</span></p>');
+				else
+					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;	
+				break;
 			default:
-                                var extra_fields = (data_['extra_ldap_fields']).split("#");   
+				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(utf8_decoder(data_[id_contact].cn) == 'undefined')
+						details.append('<p><label class="attribute">' + utf8_decoder(data_[id_contact].title) + '</label>' + '<span class="value">' + data_[id_contact].short_name + '</span></p>');
+					else
+						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] == 'undefined')
+					break;
 				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("|")));                                          
+						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>" ;
@@ -139,17 +170,16 @@
 								details.append(tmp_campo + '<span class="value">' + data_[id_contact][valor.toLowerCase()][j] + "</span></p>");
 								tmp_campo = "";
-                                                }
-                                            }
-                                        }
-                                    }
-					break;
-			}
+							}
+						}
+					}
+				}
+			break;
+		}				
 	}
+
 			
-			
-			
-		/*
-		* Método que cria a lista de contatos
-		*/
+	/*
+	* Método que cria a lista de contatos
+	*/
 	function create_list(data, begin, uiValue) {
 		var sliderValue = 1;
@@ -158,32 +188,78 @@
 		if(uiValue)
 			sliderValue = uiValue;
-					$("#detalhes_contato").empty();
+		$("#detalhes_contato").empty();
 		var paginas = Math.ceil(data.length/6); 
-					$("#title_usuarios").html( get_lang("Results") );
-                        var selectable = $("#selectable");
-						selectable.empty();
-                        var Ul = document.createElement("ul");
+		$("#title_usuarios").html( get_lang("Results") );
+        var selectable = $("#selectable");
+		selectable.empty();
+		var acento = data.search_for;
+        var Ul = document.createElement("ul");
+		var caracteresInvalidos = 'àèìòùâêîôûäëïöüáéíóúãõÀÈÌÒÙÂÊÎÔÛÄËÏÖÜÁÉÍÓÚÃÕ';
+		var caracteresValidos =   'aeiouaeiouaeiouaeiouaoAEIOUAEIOUAEIOUAEIOUAO';	
+		
+		var i = new Number();
+		var j = new Number();
+		var cString = new String();
+		var varRes = '';
+
+		for (i = 0; i < data.search_for.length; i++) {
+			cString = data.search_for.substring(i, i + 1);
+			for (j = 0; j < caracteresInvalidos.length; j++) {
+				if (caracteresInvalidos.substring(j, j + 1) == cString){
+					cString = caracteresValidos.substring(j, j + 1);
+				}
+			}
+			varRes += cString;
+		}
+		data.search_for = varRes;
+		
 		for (i=((sliderValue -1)*6)+1; i<(((sliderValue -1)*6)+1)+6; i++) {
-                        var Op = document.createElement("li");
+			var Op = document.createElement("li");
 			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"; 
+				break;
+			if (data['type_catalog'] != 'G' && (data[i-1].mail == null || data[i-1].mail == ""))
+				data[i-1].mail = get_lang("No mail"); 
 				
 			if(i == (((sliderValue -1)*6)+1)) {
-								Op.setAttribute("class", "ui-selected");
+				Op.setAttribute("class", "ui-selected");
 				Op.setAttribute("className", "ui-selected");
-							}
-							else {	
-								Op.setAttribute("class", "ui-selectee");
+			}	
+			else { 	
+				Op.setAttribute("class", "ui-selectee");
 				Op.setAttribute("className", "ui-selectee");
-							}
-							var contact_name = utf8_decoder(data[i-1].cn);
-			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 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);
+			}
+			var contact_name = utf8_decoder(data[i-1].cn);
+			if(contact_name == 'undefined'){
+				contact_name = utf8_decoder(data[i-1].title);
+				if(contact_name != 'undefined'){
+					data[i-1].mail = data[i-1].short_name;
+				}
+			}
+			var exist = "add_contact_field";
+			var signal = "+";
+			var btnClass = "add";
+			var emailList = $("#" + field_ + "_" + id_).val();
+			var emails_adicionados = emailList.split(",");
+			for(aux=0; aux<emails_adicionados.length -1; aux++) {
+				if(emails_adicionados[aux].match(/<([^<]*)>[\s]*$/)[1] == utf8_decoder(data[i-1].mail)){
+					emails_adicionados[aux] = "%";
+					exist = "remove_contact_field";
+					signal = "x";
+					btnClass = "remove";
+				}
+			}
+			
+			if(contact_name.toLowerCase().indexOf(acento.toLowerCase()) != -1 && acento.indexOf(" ") == -1 && acento.indexOf("@") == -1)									
+				contact_name = contact_name.substring(0, contact_name.toLowerCase().indexOf(acento.toLowerCase())) + "<u>" + contact_name.substr(contact_name.toLowerCase().indexOf(acento.toLowerCase()), acento.length) + "</u>" + contact_name.substring(contact_name.toLowerCase().indexOf(acento.toLowerCase()) + acento.length);
+			else 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);
+			var line = '<span class="menu-control"><button class="'+btnClass+'" id="actions_'+i+'" onClick="'+exist+'(document.getElementById(\'contact_' + i + '\').innerHTML, this, \'contact_' + i + '\')">'+ signal +'</button></span><div id="contact_' + i + '" onDblClick="'+exist+'(this.innerHTML, document.getElementById(\'actions_'+i+'\'), \'contact_' + i + '\')"><div class="name_contact"><strong class="name">' + contact_name + '</strong><em class="email">' + utf8_decoder(data[i-1].mail) + '</em></div></div>';
+			Op.innerHTML = line;
+            $(Op).val(i - 1);
             selectable.append(Op);
-                        }
+			$("#contact_"+i).click(function(){
+				document.getElementById("amount-text").focus();
+			});
+        }
 		selectable.append(Ul);
 		var first_contact;
@@ -198,5 +274,6 @@
 			});
 		}
-		var details = $("#detalhes_contato").empty();                                 
+		var details = $("#detalhes_contato").empty();   
+		
 		switch (data['type_catalog']) {
 			case 'G':
@@ -220,17 +297,23 @@
 				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(utf8_decoder(data[first_contact].cn) != 'undefined')
+					details.append('<p><label class="attribute">' + utf8_decoder(data[first_contact].cn) + '</label>' + '<span class="value">' + data[first_contact].mail + '</span></p>');
+				else
+					details.append('<p><label class="attribute">' + utf8_decoder(data[first_contact].title) + '</label>' + '<span class="value">' + data[first_contact].short_name + '</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:
+			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(utf8_decoder(data[first_contact].cn) != 'undefined')
+						details.append('<p><label class="attribute">' + utf8_decoder(data[first_contact].cn) + '</label>' + '<span class="value">' + data[first_contact].mail + '</span></p>');
+					else
+						details.append('<p><label class="attribute">' + utf8_decoder(data[first_contact].title) + '</label>' + '<span class="value">' + data[first_contact].short_name + '</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) {
+				if(data[first_contact].mail != get_lang("No mail")) {
+					if(data[first_contact].mail.length > 1) {
 						for (var i=0; i<=extra_fields.length-1; i++) {
 							var campo = extra_fields[i].substr(extra_fields[i].indexOf("|")+1);    
@@ -251,53 +334,31 @@
 		$( "#amount-text" ).val( string_results );
 		$("button").button();
+		//$("button.remove").button({icons:{primary:"ui-icon-close"}, text: false});
+		//$("button.add").button({icons:{primary:"ui-icon-plus"}, text: false});
 		if(!is_ie)
 			document.getElementById("amount-text").focus();	
-		$("#selectable li:first button:first").focus();
+		$("#selectable li:first").focus();
 		removeFocus();
-		}	
+	}	
 		
 		
 	/* Método que configura os detalhes do resultado da busca */
 	function details_results(data) {
-				$(function() {
-                    $( "#selectable" ).selectable({
-						stop: function() {
-								var details = $("#detalhes_contato").empty();                                 
-                                $( ".ui-selected", this ).each(function() {
-                        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[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.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;
-							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("#");   
-                                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) {
+		$(function() {
+			$( "#selectable" ).selectable({
+				stop: function() {
+					var details = $("#detalhes_contato").empty();                                 
+                    $( ".ui-selected", this ).each(function() {
+						if(data.length > 0){
+							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[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("|")));                                          
+										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.toLowerCase()] != undefined) {
 											var tmp_campo = '<p><label class="attribute">' + campo + "</label>" ;
@@ -305,59 +366,95 @@
 												details.append(tmp_campo + '<span class="value">' + data[this.value][valor.toLowerCase()][j] + "</span></p>");
 												tmp_campo = "";
-                                                        }
-                                                    }
-                                                }
-                                        }
-								break;
-                                    }
-								});
-						}
-                    });
-                });
-        }
-        
-        
-        /* 
-         * Método que configura o slider e os resultados 
-         */
+											}
+										}
+									}
+									break;
+								case 'P':
+									if(utf8_decoder(data[this.value].cn) == 'undefined')
+										details.append('<p><label class="attribute">' + utf8_decoder(data[this.value].title) + "</label>" + '<span class="value">' + data[this.value].short_name + "</span></p>");
+									else
+										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("#");   
+									if(preferences.default_fields_quick_search != 0 || data[this.value].type_contact == "P") {
+										if(utf8_decoder(data[this.value].cn) == 'undefined')
+											details.append('<p><label class="attribute">' + utf8_decoder(data[this.value].title) + "</label>" + '<span class="value">' + data[this.value].short_name + "</span></p>");
+										else
+											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] == 'undefined')
+											break;
+									if(data[this.value].mail[0] != get_lang("No mail")) {
+										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.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;
+							}
+						}
+					});
+				}
+            });
+        });
+    }
+     
+	 
+    /* 
+    * Método que configura o slider e os resultados 
+    */
     function configure_slider(data) {	
         var paginas = (Math.ceil(data.length/6)); 
-            $("#title_usuarios").html( get_lang("Results") );
-            $(function() {
-                $( "#slider" ).slider({
-					value:1,
-					min: 1,
-					max: paginas,
-					step: 1,
+        $("#title_usuarios").html( get_lang("Results") );
+        $(function() {
+            $( "#slider" ).slider({
+				value:1,
+				min: 1,
+				max: paginas,
+				step: 1,
 				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 string_results = ui.value + " " + get_lang("of") + " " + paginas + " (" + data.length + " " + get_lang("Results") + ")"; 		
 					$( "#amount-text" ).val( string_results );
-						}
-                    });
+				}
+            });
 			$("#selectable li:first button:first").focus();
-                });
-        }
+		});
+    }
         
 	var search_focus = false;
-
+		
 	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;
+		var kC = window.event ? event.keyCode :
+        e && e.keyCode ? e.keyCode :
+        e && e.which ? e.which : null;
         if (kC) 
-				return kC == 13;
+			return kC == 13;
         else
-				return false;
-			}
+			return false;
+	}
         
-        
-        /* 
-         * Faz a busca direto da tela modal  
-         */
+		
+    /* 
+     * Faz a busca direto da tela modal  
+     */
     function buscaContato(param) {
 		$("#busca, #detalhes_contato, #selectable").empty();
@@ -365,131 +462,187 @@
             alert(get_lang("Please enter a parameter to search"));
             return;
+        }            
+		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) {
+            data_ = data;
+			if(data_.length > 0) {     
+				configure_slider(data_);
+				create_list(data, true);
+				details_results(data_);
             }
-		if(param.length < preferences.search_characters_number) {
-                alert(get_lang("parameter must be at least") + " " +  preferences.search_characters_number + " " + get_lang("characters"));
-                return false;
+            else {
+				$("#detalhes_contato, #selectable").empty();
+				var selectable = $("#selectable");
+				var Ul = document.createElement("ul");
+				Ul.onclick = function(){
+				};
+				var Op = document.createElement("li");
+				Op.innerHTML = '<span class="menu-control"></span><div id="no_results"><div class="name_contact"><strong class="name">Nenhum Resultado Encontrado</strong></div></div>';
+				selectable.append(Op);
+				selectable.append(Ul);
+				var string_results = "0 " + get_lang("of") + " 0 (0 "  + get_lang("Results") + ")"; 		
+				$( "#amount-text" ).val( string_results );
+				details_results(data);
+                configure_slider(data); 
             }
-            var catalog = $("#combobox").val();
-        var handler_emQuickSearch = function(data) {
-                data_ = data;
-			if(data_.length > 0) {        
-                    configure_slider(data_);    
-                create_list(data_, true);
-                    details_results(data_);
-                }
-            else {
-                    $("#detalhes_contato, #selectable").empty();
-                    configure_slider(data); 
-                }
-            }
-            cExecute ("$this.ldap_functions.quicksearchcontact&search_for="+param+"&field=TO&ID=0&catalog="+catalog, handler_emQuickSearch);
         }
-		
+        cExecute ("$this.ldap_functions.quicksearchcontact&search_for="+param+"&field=TO&ID=0&catalog="+catalog, handler_emQuickSearch);
+    }
+		
+	function verifyEmails(emailAux, contato) {	
+		var contact_id = contato.split("_");		
+		if(contact_id[1] != 0)
+		{
+			var ini = parseInt((contact_id[1]/6).toFixed(0));
+			if(ini != 0 && ini != 1){
+				ini = ini * 6;
+				var fim = ini+1;
+			}
+			else{
+				ini = 1;
+				var fim = ini;
+			}
+			fim = fim +5;
+			var contact2 = "";
+			for(aux = ini; aux <= fim; aux++){
+				if(contact_id[1] != aux){
+					if($("#"+contact_id[0]+"_"+aux).find('.email').text() == emailAux){
+						contact2 = contact_id[0]+"_"+aux;
+						var button = document.getElementById("actions_"+aux);
+						var div = document.getElementById(contact2);
+						if($("#actions_"+aux).find('.ui-button-text').text() == '+'){
+							button.onclick = function(){
+								remove_contact_field(div.innerHTML, button, contact2);
+							};
+							div.ondblclick = function(){
+								remove_contact_field(div.innerHTML, button, contact2);
+							};
+							$("#actions_"+aux).find('.ui-button-text').text('x');
+						}
+						else{
+							button.onclick = function(){
+								add_contact_field(div.innerHTML, button, contact2);
+							};
+							div.ondblclick = function(){
+								add_contact_field(div.innerHTML, button, contact2);
+							};
+							$("#actions_"+aux).find('.ui-button-text').text('+');
+						}
+					}
+				}
+			}
+		}
+	}
+    /* 
+    * Método que adiciona o contato selecionado no campo do email (To, CC, CCo) 
+    */
+    function add_contact_field(contact, button, divs) {
+	
+		var nome = $(contact).clone().find('.name').text();
+		var email = $(contact).clone().find('.email').text();
+		
+		if(email == get_lang("No mail")){
+			alert(get_lang("It is not possible to add this contact as a recipient because it does not have email"));
+			if(!is_ie)
+				document.getElementById("amount-text").focus();
+			return;
+		}
+		
+		verifyEmails(email, divs);
+		
+		final_contact = "\""+nome +"\" <"+email+">, ";
+		
+		var emailList      = document.getElementById(field_ + "_" + id_).value; 
+		
+        if (emailList[0] != '"' && emailList.indexOf(",") < 0)
+			emailList = emailList.substr(end_);
+        if(emailList.lastIndexOf(",") > 0) 
+			emailList = emailList.substr(0, emailList.lastIndexOf(",") + 1);
         
-        /* 
-         * Método que adiciona o contato selecionado no campo do email (To, CC, CCo) 
-         */
-    function add_contact_field(contact) {
-			var emailList      = document.getElementById(field_ + "_" + id_).value; 
-		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);
-				
-			var final_contact;
-			if(tokens_contact[2] == undefined)
-			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] + ">, ";
-				else
-				final_contact =  "\"" + tokens_contact[0] + "" +  tokens_contact[1] + "" +  tokens_contact[2] + "\" <" + tokens_contact[3] + ">, ";
-            }
-        if (emailList[0] != '"' && emailList.indexOf(",") < 0)
-                emailList = emailList.substr(end_);
-            if(emailList.lastIndexOf(",") > 0)
-			emailList = emailList.substr(0, emailList.lastIndexOf(",") + 1);
-            
 		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");
-        }
-		
-		/* 
-         * Método que remove o contato selecionado no campo do email (To, CC, CCo) 
-         */
-	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("|");	
-			if (tokens_contact[2].indexOf("(") > 0)
-                tokens_contact[2] = tokens_contact[2].substr(0, (tokens_contact[2].indexOf("("))-2);
-			var final_contact;
-			if(tokens_contact[3] == undefined)               
-				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] + ">";
-			
+		new_emailList = emailList + final_contact;    
+        document.getElementById(field_ + "_" + id_).value = new_emailList;
+		
+		button.onclick = function(){
+			remove_contact_field(document.getElementById(divs).innerHTML, button, divs);
+		};
+		var div = document.getElementById(divs);
+		
+		div.ondblclick = function(){
+			remove_contact_field(div.innerHTML, button, divs);
+		};
+		
+		button.innerHTML = '<span class="ui-button-text" style="">x</span>';
+    }
+		
+		
+	/* 
+    * Método que remove o contato selecionado no campo do email (To, CC, CCo) 
+    */
+	function remove_contact_field(contact, button, divs) {
+		var email = $(contact).clone().find('.email').text();
 		var exist = false;
+		
 		var emailList = $("#" + field_ + "_" + id_).val();
-			var emails_adicionados = emailList.split(",");
+		var emails_adicionados = emailList.split(",");
+		
+		verifyEmails(email, divs);
+		
 		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] = "%";
+
+			if(emails_adicionados[i].match(/<([^<]*)>[\s]*$/)[1] == email) {
+				emails_adicionados[i] = "%";
 				exist = true;
-				}
-			}
+			}
+		}
+		
 		if (exist == false) 
-				return false;
-			var novos_contatos = emails_adicionados.join(",");  
-            novos_contatos = novos_contatos.replace(/%,/g, "");
+			return false;
+		var novos_contatos = emails_adicionados.join(",");  
+		novos_contatos = novos_contatos.replace(/%,/g, "");
 		$("#" + field_ + "_" + id_).val(novos_contatos);
-		}
+		
+		button.onclick = function(){
+			add_contact_field(document.getElementById(divs).innerHTML, button, divs);
+		};
+		
+		var div = document.getElementById(divs);
+		
+		div.ondblclick = function(){
+			add_contact_field(div.innerHTML, button, divs);
+		};
+		
+		button.innerHTML = '<span class="ui-button-text" style="">+</span>';
+	}
         
-	      
+	 
 	/* Decoder utf8 */	
     function utf8_decoder ( str_data ) {
-            var tmp_arr = [], i = 0, ac = 0, c1 = 0, c2 = 0, c3 = 0;
-            str_data += '';
+        var tmp_arr = [], i = 0, ac = 0, c1 = 0, c2 = 0, c3 = 0;     
+        str_data += '';    
         while ( i < str_data.length ) {
-                c1 = str_data.charCodeAt(i);
+            c1 = str_data.charCodeAt(i);
             if (c1 < 128) {
-                    tmp_arr[ac++] = String.fromCharCode(c1);
-                    i++;
+				tmp_arr[ac++] = String.fromCharCode(c1);
+                i++;
             } else if ((c1 > 191) && (c1 < 224)) {
-                            c2 = str_data.charCodeAt(i+1);
-                            tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
-                            i += 2;
-                        } else {
-                                    c2 = str_data.charCodeAt(i+1);
-                                    c3 = str_data.charCodeAt(i+2);
-                                    tmp_arr[ac++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
-                                    i += 3;
-                                }
-            }
- 
-            return tmp_arr.join('');
+                        c2 = str_data.charCodeAt(i+1);
+                        tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
+                        i += 2;
+                      } else {
+                                c2 = str_data.charCodeAt(i+1);
+                                c3 = str_data.charCodeAt(i+2);
+                                tmp_arr[ac++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
+                                i += 3;
+                             }
         }
+        return tmp_arr.join('');
+    }
         
-              
+    
 	/* Mostra tela de help */	
     function show_help() {
@@ -499,23 +652,32 @@
 						width: 540,
 						modal: true,
-						closeOnEscape: true
+						closeOnEscape: true,
+						close : function (event, ui) {
+									$( "#amount-text" ).focus();
+									event.stopPropagation();
+								}
 			});
 		});
 	}	
-		  
-              
+	
+	$("#dialog-modal_help").live("dialogclose", function(){
+		if(!is_ie)
+			$( "#amount-text" ).focus();
+	});
+
+          
 	emQuickCatalogSearch.prototype.showWindow = function (div) {
 		$(this).bind('keydown');
-				$(function() {
-                    $( "#dialog:ui-dialog" ).dialog( "destroy" );                    
-                    $( "#dialog-modal" ).dialog({
-						resizable: false,
+		$(function() {
+        $( "#dialog:ui-dialog" ).dialog( "destroy" );                    
+        $( "#dialog-modal" ).dialog({
+			resizable: false,
 //			height: "auto",
 			width: 780,
-						modal: true,
+			modal: true,
 			position: 'bottom',
-						closeOnEscape: true,
-						close: function (event, ui) {
-							event.stopPropagation();
+			closeOnEscape: true,
+			close: function (event, ui) {
+				event.stopPropagation();
 				$(this).unbind('keydown');
 				if (is_ie) { 
@@ -528,18 +690,20 @@
 			},
 			open: function () {
-				$("#selectable li:first button:first").focus();    
-						},
-						focus: function (event, ui) {
+				removeFocus();
+				$("#selectable li:first").focus();
+				document.getElementById("amount-text").focus();	
+			},
+			focus: function (event, ui) {
 				//$(this).unbind('keydown');
-						},
-						beforeClose: function (event, ui) {
+			},
+			beforeClose: function (event, ui) {
 				$(this).unbind('keydown');
-						},
+			},
 			buttons:[
 						{
 							text: "Fechar",
 							click: function(){
-								$("#detalhes_contato, #selectable, #busca").empty();
-								$(this).dialog("close");
+												$("#detalhes_contato, #selectable, #busca").empty();
+												$(this).dialog("close");
 												if (is_ie) { 
 													var range= document.getElementById(field_ + "_" + id_).createTextRange(); 
@@ -548,11 +712,11 @@
 												} 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>')
@@ -561,5 +725,5 @@
 			$(".ui-icon-minusthick, .ui-icon-newwin").toggleClass('ui-icon-minusthick').toggleClass('ui-icon-newwin');
 		});
-	
+		
 		$("#dialog-modal button, input.button").button();				
 	}
