Index: trunk/expressoMail1_2/setup/setup.inc.php
===================================================================
--- trunk/expressoMail1_2/setup/setup.inc.php	(revision 197)
+++ trunk/expressoMail1_2/setup/setup.inc.php	(revision 271)
@@ -12,5 +12,5 @@
 	$setup_info['expressoMail1_2']['name']      	= 'expressoMail1_2';
 	$setup_info['expressoMail1_2']['title']     	= 'ExpressoMail 1.2';
-	$setup_info['expressoMail1_2']['version']   	= '1.2210';
+	$setup_info['expressoMail1_2']['version']   	= '1.2211';
 	$setup_info['expressoMail1_2']['app_order'] 	= 2;
 //	$setup_info['expressoMail1_2']['tables'][]    	= 'phpgw_expressoMail1_2';
Index: trunk/expressoMail1_2/preferences.php
===================================================================
--- trunk/expressoMail1_2/preferences.php	(revision 197)
+++ trunk/expressoMail1_2/preferences.php	(revision 271)
@@ -53,4 +53,9 @@
 			$GLOBALS['phpgw']->template->set_var('checked_shortcuts','');
 
+		if ($GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['auto_save_draft'])
+			$GLOBALS['phpgw']->template->set_var('checked_auto_save_draft','checked');
+		else
+			$GLOBALS['phpgw']->template->set_var('checked_auto_save_draft','');
+
 		if ($GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['signature'])
 			$GLOBALS['phpgw']->template->set_var('text_signature',$GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['signature']);
@@ -109,4 +114,9 @@
 		else
 			$GLOBALS['phpgw']->preferences->add('expressoMail','use_shortcuts',$_POST['use_shortcuts']);
+			
+		if ($GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['auto_save_draft'])
+			$GLOBALS['phpgw']->preferences->change('expressoMail','auto_save_draft',$_POST['auto_save_draft']);
+		else
+			$GLOBALS['phpgw']->preferences->add('expressoMail','auto_save_draft',$_POST['auto_save_draft']);	
 
 		if ($GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['signature'])
@@ -161,4 +171,5 @@
 	$GLOBALS['phpgw']->template->set_var('lang_font_size',lang('What the font size in the list of messages?'));
 	$GLOBALS['phpgw']->template->set_var('lang_use_shortcuts',lang('Use shortcuts?'));
+	$GLOBALS['phpgw']->template->set_var('lang_auto_save_draft',lang('Auto save draft'));
 	$GLOBALS['phpgw']->template->set_var('lang_signature',lang('Signature'));
 	$GLOBALS['phpgw']->template->set_var('lang_none',lang('None'));
Index: trunk/expressoMail1_2/inc/class.imap_functions.inc.php
===================================================================
--- trunk/expressoMail1_2/inc/class.imap_functions.inc.php	(revision 205)
+++ trunk/expressoMail1_2/inc/class.imap_functions.inc.php	(revision 271)
@@ -840,5 +840,5 @@
 		
 		$msg_to_insert  = array_diff($msgs_in_the_server, $msgs_in_the_client);
-		//$msg_to_delete = array_diff($msgs_in_the_client, $msgs_in_the_server);
+		$msg_to_delete = array_diff($msgs_in_the_client, $msgs_in_the_server);
 		
 		$msgs_to_exec = array();
@@ -867,11 +867,4 @@
 			}
 		}
-		/*if (count($msg_to_delete))
-		{
-			foreach($msg_to_delete as $index => $msg_number)
-			{
-				$msgs_to_exec[$msg_number] = 'Apagar mensage numero ' . $msg_number;
-			}
-		}*/
 		
 		$return = array();
@@ -930,4 +923,5 @@
 		}
 		$return['new_msgs'] = imap_num_recent($this->mbox);
+		$return['msgs_to_delete'] = $msg_to_delete;
 		if($this->mbox)
 			imap_close($this->mbox);
@@ -1094,4 +1088,5 @@
 		$ccoaddress = implode(',',$db->getAddrs(explode(',',$params['input_cco'])));
 		$subject = $params['input_subject'];
+		$msg_uid = $params['msg_id'];
 		$return_receipt = $params['input_return_receipt'];
 		$body = $params['body'];
@@ -1113,8 +1108,4 @@
 ////////////////////////////////////////////////////////////////////////////////////////////////////
 		$mail->SMTPDebug = false;
-		
-		//$mail->SMTPAuth = true;
-		//$mail->Username = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
-		//$mail->Password = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
 				
 		$mail->IsSMTP();
@@ -1136,4 +1127,52 @@
 		$mail->IsHTML(true);
 		$mail->Body = $params['body'];
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+		//	Build CID for embedded Images!!!
+		$pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&amp;msg_num=(.+)?&amp;msg_part=(.+)?)"/isU';
+		$cid_imgs = '';
+		$name_cid_files = array();
+		preg_match_all($pattern,$mail->Body,$cid_imgs,PREG_PATTERN_ORDER);
+		$cid_array = array();
+		foreach($cid_imgs[4] as $j => $val){
+				if ( !array_key_exists($cid_imgs[3][$j].$val, $cid_array) )
+      			{
+                $cid_array[$cid_imgs[3][$j].$val] = base_convert(microtime(), 10, 36);
+		        }
+		        $cid = $cid_array[$cid_imgs[3][$j].$val]; 
+        		$mail->Body = str_replace($cid_imgs[1][$j], "cid:".$cid, $mail->Body);
+        		
+				if ($msg_uid != $cid_imgs[3][$j]) // The image isn't in the same mail?
+				{
+					$fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[3][$j], $cid_imgs[4][$j], 'base64');
+					$fileName = "image_".($j).".jpg";
+					$fileCode = "base64";
+					$fileType = "image/jpg";
+				}
+				else
+				{
+					$attach_img = $forwarding_attachments[$cid_imgs[4][$j]-2];
+					$file_description = unserialize(rawurldecode($attach_img));
+
+					foreach($file_description as $i => $descriptor){				
+						$file_description[$i]  = eregi_replace('\'*\'','',$descriptor);
+					}
+					$fileContent = $this->get_forwarding_attachment($file_description[0], $msg_uid, $file_description[3], 'base64');
+					$fileName = $file_description[2];
+					$fileCode = $file_description[4];
+					$fileType = $this->get_file_type($file_description[2]);
+					unset($forwarding_attachments[$cid_imgs[4][$j]-2]);
+				}
+				$tempDir = ini_get("session.save_path");
+				$file = "cid_image_".base_convert(microtime(), 10, 36).".dat";					
+				$f = fopen($tempDir.'/'.$file,"w");
+				fputs($f,$fileContent);
+				fclose($f);
+				if ($fileContent)
+					$mail->AddEmbeddedImage($tempDir.'/'.$file, $cid, $fileName, $fileCode, $fileType);
+				//else
+				//	return "Error loading image attachment content";						
+
+		}
 ////////////////////////////////////////////////////////////////////////////////////////////////////
 		//	Build Uploading Attachments!!!
@@ -1151,34 +1190,5 @@
 		}			
 ////////////////////////////////////////////////////////////////////////////////////////////////////
-		//	Build CID for embedded Images!!!
-		$pattern = '/show_embedded_attach.php\?msg_folder=INBOX&(.+)&(.+)">/isU';
-		$cid_imgs = '';
-		$name_cid_files = array();
-		if(preg_match_all($pattern,$mail->Body,$cid_imgs,PREG_PATTERN_ORDER)){		
-			include("class.imap_attachment.inc.php");
-			$imap_attachment = new imap_attachment();	   		
-		}
-		for($i = 0; $i < count($cid_imgs);$i++){
-			if($i == 1) {
-				for($j = 0; $j < count($cid_imgs[$i]);$j++){
-					$cid = base_convert(microtime(), 10, 36);
-					$msg_num = explode("=",$cid_imgs[$i][$j]); 
-					$msg_part = explode("=",$cid_imgs[$i+1][$j]);
-					$fileContent = imap_base64(imap_fetchbody($this->open_mbox(), $msg_num[1], $msg_part[1], FT_UID));
-					$pattern = './inc/show_embedded_attach.php?msg_folder=INBOX&amp;msg_num='.$msg_num[1].'&amp;msg_part='.$msg_part[1];
-					$replace = "cid:".$cid;
-					$mail->Body = str_replace($pattern,$replace,$mail->Body);
-					$tempDir = ini_get("session.save_path");
-					$file = "cid_image_".base_convert(microtime(), 10, 36).".dat";					
-					$f = fopen($tempDir.'/'.$file,"w");
-					fputs($f,$fileContent);
-					fclose($f);		
-					$name_cid_files[$j] = "image_".($j).".jpg";			
-					$mail->AddEmbeddedImage("$tempDir/$file", $cid, "image_".($j).".jpg", "base64", "image/jpg");
-				}
-			}		
-		}
-////////////////////////////////////////////////////////////////////////////////////////////////////
-		//	Build Forwarding Attachments!!!		
+		//	Build Forwarding Attachments!!!
 		if (count($forwarding_attachments) > 0)
 		{
@@ -1191,12 +1201,14 @@
 			foreach($forwarding_attachments as $forwarding_attachment)
 			{
-				$file_description = unserialize(rawurldecode($forwarding_attachment));
-				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];
-				if(!array_search(trim($fileName),$name_cid_files)) {
-					$mail->AddStringAttachment($fileContent, $fileName, $file_description[4], $this->get_file_type($file_description[2]));
+					$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)) {
+						$mail->AddStringAttachment($fileContent, $fileName, $file_description[4], $this->get_file_type($file_description[2]));
 				}
 			}
@@ -1452,43 +1464,133 @@
 	function save_msg($params)
 	{
-		$folder_id = $params['folder_id'];
-		$folder_id =  mb_convert_encoding($folder_id, "UTF7-IMAP", "UTF-8");
-		$folder_name = $params['folder_name'];
-		$folder_name =  mb_convert_encoding($folder_name, "ISO-8859-1", "UTF-8");
-		$border_id = $params['border_id'];
-		$imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
-		$mbox_stream = $this->open_mbox();		
-		
-		$from = '"' . $_SESSION['phpgw_info']['expressomail']['user']['fullname'] . '" <' . $_SESSION['phpgw_info']['expressomail']['user']['email'] . '>';				
-		$to = $params['to'];
-		$cc = $params['cc'];
-		$subject = $params['subject'];
+		
+		include_once("class.phpmailer.php");
+		$mail = new PHPMailer();
+		include_once("class.db_functions.inc.php");
+		$toaddress = $params['input_to'];
+		$ccaddress = $params['input_cc'];
+		$subject = $params['input_subject'];
 		$body = $params['body'];
 		$body = str_replace("%nbsp;","&nbsp;",$params['body']);
 		$body = preg_replace("/\n/"," ",$body);
 		$body = preg_replace("/\r/","",$body);
-		
-		$header = 	"From: " . $from . "\r\n"
-					. "To: " . $to . "\r\n"
-					. "Cc: " . $cc . "\r\n";
+		$forwarding_attachments = $params['forwarding_attachments'];
+		$attachments = $params['FILES'];
+		$return_files = $params['FILES'];
+		 
+		$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.
 					
-		$header =  mb_convert_encoding($header, "ISO-8859-1", "UTF-8");
-		$header =	$header
-					. "Subject: " . $subject . "\r\n"
-					. "\r\n"
-					. $body . "\r\n";
-		
-		$return = array();
-		$return['append'] = imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder_id, $header, "\\Seen \\Draft");
-		$return['folder_name'] = $folder_name;
-		$return['border_id'] = $border_id;
+		$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);
+		$mail->Subject = $subject;
+		$mail->IsHTML(true);
+		$mail->Body = $body;
+		
+	
+	//	Build Forwarding Attachments!!!		
+		if (count($forwarding_attachments) > 0)
+		{
+			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 = $tmp;
+				
+				$fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
+				$fileName = $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]));
+			}
+		}
+		
+		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!!!
+		if (count($attachments))
+			foreach ($attachments as $attach)
+				$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();
+        
+       	if ($_SESSION['phpgw_info']['expressomail']['email_server']['imapTLSEncryption'] == 'yes')
+		{
+			$imap_options = '/tls/novalidate-cert';
+		}
+		else
+		{
+			$imap_options = '/notls/novalidate-cert';
+		}
+		$username = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
+		$password = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
+		$imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
+		$imap_port 	= $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
+		$mbox_stream = imap_open("{".$imap_server.":".$imap_port.$imap_options."}".$folder, $username, $password);
+	
+		$new_header = str_replace("\n", "\r\n", $header);
+		$new_body = str_replace("\n", "\r\n", $body);
+		
+		$return['append'] = imap_append($mbox_stream, "{".$imap_server.":".$imap_port."}".$folder, $new_header . $new_body, "\\Seen \\Draft");
+		$status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
+		$return['msg_no'] = $status->uidnext - 1;
+		$return['folder_id'] = $folder;
 		
 		if($mbox_stream)
 			imap_close($mbox_stream);
-		
+				
+		foreach ($return_files as $index => $_attachment) {
+			if (array_key_exists("name",$_attachment)){
+				unset($return_files[$index]);
+				$return_files[$index] = $_attachment['name']."_SIZE_".$return_files[$index][1] = $_attachment['size'];
+			}
+			else
+			{
+				unset($return_files[$index]);
+				$return_files[$index] = $_attachment[2]."_SIZE_". $return_files[$index][1] = $_attachment[5];
+			}
+		}
+		
+		$return['files'] = serialize($return_files);
+				
 		if (!$return['append'])
 			$return['append'] = imap_last_error();
-		else
-			$return['header'] = $header;
+		
 		return $return;
 	}
@@ -1916,22 +2018,32 @@
 	function search_msg($params = ''){
 		$retorno = "";
+		$mbox_stream = "";
 		$search = explode(",",$params['condition']);
 		if($search){
 			$search_criteria = '';
-			foreach($search as $tmp){
+			foreach($search as $tmp)
+			{
 				$tmp1 = explode("##",$tmp);
 				$name_box = $tmp1[0];
 				$criteria = explode("<=>",rawurldecode($tmp1[1]));				
 				$criteria[1] = $this->remove_accents($criteria[1]);
-				$mbox_stream = $this->open_mbox($name_box);
+				
+				if(!is_resource($mbox_stream))
+					$mbox_stream = $this->open_mbox();
+				else
+					imap_reopen($mbox_stream, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$name_box);
 				
 				if($criteria[0] == "ALL ") {					
-					$all_criterias = array ("TO","SUBJECT","FROM","CC");								
-					foreach($all_criterias as $criteria_fixed){						
-						$search_criteria = imap_search($mbox_stream,$criteria_fixed." \"".$criteria[1]."\"", SE_UID);
-						if($search_criteria && count($search_criteria) < 50) {
+					$all_criterias = array ("TO","SUBJECT","FROM","CC");
+					foreach($all_criterias as $criteria_fixed)
+					{
+						$filter = $criteria_fixed . ' "' . $criteria[1] . '"';
+						$search_criteria = imap_search($mbox_stream, $filter, SE_UID);
+						
+						if($search_criteria && count($search_criteria) < 50)
+						{
 							foreach($search_criteria as $new_search){
-								$m_token = trim("##".$name_box . "--" . $this->get_msg($new_search,$name_box) . "--".$new_search."##"."\n");
-								if(!strstr($retorno,$m_token))
+								$m_token = trim("##".$name_box . "--" . $this->get_msg($new_search,$name_box,$mbox_stream) . "--".$new_search."##"."\n");
+								if(!@strstr($retorno,$m_token))
 									$retorno .= $m_token;
 							}
@@ -1940,23 +2052,26 @@
 							return "many results";						
 					}
-				}				
+				}
 				else {
-					$search_criteria = imap_search($mbox_stream,$criteria[0]."\"".$criteria[1]."\"", SE_UID);						
+					$filter = $criteria[0] . '"' . $criteria[1] . '"';
+					$search_criteria = imap_search($mbox_stream, $filter, SE_UID);
+											
 					if($search_criteria) {
 						foreach($search_criteria as $new_search){
-							$retorno .= trim("##".$name_box . "--" . $this->get_msg($new_search,$name_box) . "--".$new_search."##"."\n");
+							$retorno .= trim("##".$name_box . "--" . $this->get_msg($new_search,$name_box,$mbox_stream) . "--".$new_search."##"."\n");
 						}
 					}
 				}
-				if($mbox_stream)
-					imap_close($mbox_stream);		
-			}
-		}		
+			}
+		}
+		if($mbox_stream)
+			imap_close($mbox_stream);		
+						
 		return $retorno ? $retorno : "none";
 	}
 	
-	function get_msg($uid_msg,$name_box){		
-		$mbox_stream = $this->open_mbox($name_box);
-		$header = @imap_headerinfo($mbox_stream, imap_msgno($mbox_stream, $uid_msg), 80, 255); 		
+	function get_msg($uid_msg,$name_box, $mbox_stream )
+	{
+		$header = @imap_headerinfo($mbox_stream, imap_msgno($mbox_stream, $uid_msg), 80, 255);         
 		$subject = $this->decode_string($header->fetchsubject);
 		$from = $header->from[0]->mailbox;
@@ -1964,7 +2079,7 @@
 			$from = $header->from[0]->personal;
 		$ret_msg = $this->decode_string($from) . "--" . $subject . "--". date("d/m/Y",$header ->udate)."--". $this->size_msg($header->Size);
-		return $ret_msg;					
-	}
-
+		return $ret_msg;                    
+	}	
+	
 	function size_msg($size){
 		$var = floor($size/1024);
Index: trunk/expressoMail1_2/inc/class.imap_attachment.inc.php
===================================================================
--- trunk/expressoMail1_2/inc/class.imap_attachment.inc.php	(revision 2)
+++ trunk/expressoMail1_2/inc/class.imap_attachment.inc.php	(revision 271)
@@ -63,5 +63,6 @@
 			{
 				$array_parts_attachments[$i]['pid'] = $msg->pid[$msgno][$index];
-				$array_parts_attachments[$i]['name'] = $this->flat_mime_decode($fname);
+				$array_parts_attachments[$i]['name'] = $this->decode_mimeheader($fname);
+				//$array_parts_attachments[$i]['name'] = $this->flat_mime_decode($fname);
 				$array_parts_attachments[$i]['name'] = $array_parts_attachments[$i]['name'] ? $array_parts_attachments[$i]['name'] : "attachment.bin";
 				$array_parts_attachments[$i]['encoding'] = $msg->encoding[$msgno][$index];
@@ -75,4 +76,7 @@
 	}
 	
+	function decode_mimeheader($string) {
+        return mb_decode_mimeheader($string);
+    }
 	function flat_mime_decode($string) {
 	   	$array = imap_mime_header_decode($string);
Index: trunk/expressoMail1_2/inc/class.ldap_functions.inc.php
===================================================================
--- trunk/expressoMail1_2/inc/class.ldap_functions.inc.php	(revision 243)
+++ trunk/expressoMail1_2/inc/class.ldap_functions.inc.php	(revision 271)
@@ -76,10 +76,10 @@
 			if (($field != 'null') && ($ID != 'null'))
 			{
-				$filter="(&(|(phpgwAccountType=u)(phpgwAccountType=l))(|(cn=*$search_for*)(mail=$search_for*)))";
+				$filter="(& (|(phpgwAccountType=u)(phpgwAccountType=l)) (|(cn=*$search_for*)(mail=$search_for*)) (!(phpgwaccountvisible=-1)) )";
 				$justthese = array("cn", "mail", "telephoneNumber", "mobile", "phpgwAccountVisible", "uid");
 			}
 			else
 			{
-				$filter="(& (phpgwAccountType=u)(cn=*$search_for*) )";
+				$filter="(& (phpgwAccountType=u)(cn=*$search_for*) (!(phpgwaccountvisible=-1)) )";
 				$justthese = array("cn", "mail", "telephoneNumber", "mobile", "phpgwAccountVisible", "jpegPhoto", "uid");
 			}
@@ -87,5 +87,13 @@
 			$sr=ldap_search($this->ds, $this->ldap_context, $filter, $justthese);
 			$count_entries = ldap_count_entries($this->ds,$sr);
-			
+
+			// Get user org dn.			
+			$user_dn = $_SESSION['phpgw_info']['expressomail']['user']['account_dn'];
+			$user_sector_dn = ldap_explode_dn ( $user_dn, false );
+			array_shift($user_sector_dn);
+			array_shift($user_sector_dn);
+			$user_sector_dn = implode(",", $user_sector_dn);
+			
+			// New search only on user sector
 			if ($count_entries > 200)
 			{
@@ -96,11 +104,4 @@
 				$this->ldapRootConnect(true);
 				
-				$user_dn = $_SESSION['phpgw_info']['expressomail']['user']['account_dn'];
-				$user_sector_dn = ldap_explode_dn ( $user_dn, false );
-				array_shift($user_sector_dn);
-				array_shift($user_sector_dn);
-				$user_sector_dn = implode(",", $user_sector_dn);
-				
-				// New search only on user sector
 				$sr=ldap_search($this->ds, $user_sector_dn, $filter, $justthese);
 				$count_entries = ldap_count_entries($this->ds,$sr);
@@ -117,18 +118,38 @@
 				}
 			}
+			
 			$info = ldap_get_entries($this->ds, $sr);
-
+			
 			$tmp = array();
+			$tmp_users_from_user_org = array();
 			for ($i=0; $i<$info["count"]; $i++)
 			{
-				if ($info[$i]["phpgwaccountvisible"][0] == '-1')
-					continue;
-				$tmp[$info[$i]["mail"][0] . '%' . $info[$i]["telephonenumber"][0] . '%'. $info[$i]["mobile"][0] . '%' . $info[$i]["uid"][0] . '%' . $info[$i]["jpegphoto"]['count']] = $info[$i]["cn"][0];
-			}
+				// Usuario sempre serao da minha org.
+				if ($quickSearch_only_in_userSector)
+				{
+					$tmp[$info[$i]["mail"][0] . '%' . $info[$i]["telephonenumber"][0] . '%'. $info[$i]["mobile"][0] . '%' . $info[$i]["uid"][0] . '%' . $info[$i]["jpegphoto"]['count']] = $info[$i]["cn"][0];
+				}
+				else
+				{
+					if (preg_match("/$user_sector_dn/i", $info[$i]['dn']))
+					{
+						$tmp_users_from_user_org[$info[$i]["mail"][0] . '%' . $info[$i]["telephonenumber"][0] . '%'. $info[$i]["mobile"][0] . '%' . $info[$i]["uid"][0] . '%' . $info[$i]["jpegphoto"]['count']] = $info[$i]["cn"][0];
+					}
+					else
+					{
+						$tmp[$info[$i]["mail"][0] . '%' . $info[$i]["telephonenumber"][0] . '%'. $info[$i]["mobile"][0] . '%' . $info[$i]["uid"][0] . '%' . $info[$i]["jpegphoto"]['count']] = $info[$i]["cn"][0];
+					}
+				}
+			}
+			natcasesort($tmp_users_from_user_org);
 			natcasesort($tmp);
 			
-			$i = 0;
 			if (($field != 'null') && ($ID != 'null'))
 			{
+				$i = 0;
+				
+				$tmp = array_merge($tmp, $tmp_users_from_user_org);
+				natcasesort($tmp);
+				
 				foreach ($tmp as $info => $cn)
 				{
@@ -142,57 +163,64 @@
 			else
 			{
+				$options_users_from_user_org = '';
 				$options = '';
-				
+
+				/* List of users from user org */
+				$i = 0;
+				foreach ($tmp_users_from_user_org as $info => $cn)
+				{
+					$contacts_result[$i] = array();
+					$options_users_from_user_org .= $this->make_quicksearch_card($info, $cn);
+					$i++;
+				}
+
+				/* List of users from others org */
 				foreach ($tmp as $info => $cn)
 				{
 					$contacts_result[$i] = array();
-					$contacts_result[$i]["cn"] = $cn;
-					list ($contacts_result[$i]["mail"], $contacts_result[$i]["phone"], $contacts_result[$i]["mobile"], $contacts_result[$i]["uid"], $contacts_result[$i]["jpegphoto"]) = split ('%', $info);
-					
-					if ($contacts_result[$i]['jpegphoto'])
-						$photo_link = '<img src="./inc/show_user_photo.php?mail='.$contacts_result[$i]['mail'].'">';
-					else
-						$photo_link = '<img src="./templates/default/images/photo.png">';
-					
-					// '<tr class="quicksearchcontacts_unselected" onClick="javascript:QuickSearchUser.select_cc(this)">' .
-					$phoneUser = $contacts_result[$i]['phone'];
-					
-					if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['voip_enabled'] && $phoneUser) {
-						$phoneUser = '<a title="'.$functions->getLang("Call to Comercial Number").'" href="#" onclick="InfoContact.connectVoip(\''.$phoneUser.'\',\'com\')">'.$phoneUser.'</a>';
-						if($contacts_result[$i]['mobile']){
-						$phoneUser .= ' / <a title="'.$functions->getLang("Call to Mobile Number").'" href="#" onclick="InfoContact.connectVoip(\''.$contacts_result[$i]['mobile'].'\',\'mob\')">'.$contacts_result[$i]['mobile'].'</a>';
-						}
-					}
-					$options .=
-						'<tr class="quicksearchcontacts_unselected">' .
-							'<td class="cc" width="1%">' .
-								'<a title="'.$functions->getLang("Write message").'" onClick="javascript:QuickSearchUser.create_new_message(\''.$contacts_result[$i]["cn"].'\', \''.$contacts_result[$i]["mail"].'\')">' .
-									$photo_link .
-								'</a>' .
-							'</td>' .
-							'<td class="cc">' .
-								'<span name="cn">' . $contacts_result[$i]['cn'] . '</span>' . '<br>' .
-								'<a title="'.$functions->getLang("Write message").'" onClick="javascript:QuickSearchUser.create_new_message(\''.$contacts_result[$i]["cn"].'\', \''.$contacts_result[$i]["mail"].'\')">' .
-									'<font color=blue>' .
-										'<span name="mail">' . $contacts_result[$i]['mail'] . '</span>' . '<br>' .
-									'</font>' .
-								'</a>' .
-								$phoneUser .
-							'</td>' .
-						'</tr>';
+					$options .= $this->make_quicksearch_card($info, $cn);
 					$i++;
 				}
-				$contacts_result = $options;
 				
 				if ($quickSearch_only_in_userSector)
 				{
-					$head_option =
-						'<tr class="quicksearchcontacts_unselected">' .
-							'<td colspan="2" width="100%" align="center">' .
-								$functions->getLang('More than 200 results were found') . '.<br>' .
-								$functions->getLang('Showing only the results found in your organization') . '.';
-							'</td>' .
-						'</tr>';
-					$contacts_result = $head_option . $contacts_result;
+					if ($options != '')
+					{
+						$head_option =
+							'<tr class="quicksearchcontacts_unselected">' .
+								'<td colspan="2" width="100%" align="center">' .
+									$functions->getLang('More than 200 results were found') . '.<br>' .
+									$functions->getLang('Showing only the results found in your organization') . '.';
+								'</td>' .
+							'</tr>';
+						$contacts_result = $head_option . $options_users_from_user_org . $options;
+					}
+					else
+					{
+						$return = array();
+						$return['status'] = false;
+						$return['error'] = "many results";
+						return $return;
+					}
+				}
+				else
+				{
+					if (($options_users_from_user_org != '') && ($options != ''))
+					{
+						$head_option0 =
+							'<tr class="quicksearchcontacts_unselected">' .
+								'<td colspan="2" width="100%" align="center" style="background:#EEEEEE"><B>' .
+									$functions->getLang('Users from your organization') . '.';
+								'</B></td>' .
+							'</tr>';
+
+						$head_option1 =
+							'<tr class="quicksearchcontacts_unselected">' .
+								'<td colspan="2" width="100%" align="center" style="background:#EEEEEE"><B>' .
+									$functions->getLang('Users from others organizations') . '.';
+								'</B></td>' .
+							'</tr>';
+					}
+					$contacts_result = $head_option0 . $options_users_from_user_org . $head_option1 . $options;
 				}
 			}
@@ -200,4 +228,46 @@
 		ldap_close($this->ds);
 		return $contacts_result;
+	}
+
+	function make_quicksearch_card($info, $cn)
+	{
+		include_once("class.functions.inc.php");
+		$functions = new functions;						
+		
+		$contacts_result = array();
+		$contacts_result["cn"] = $cn;
+		list ($contacts_result["mail"], $contacts_result["phone"], $contacts_result["mobile"], $contacts_result["uid"], $contacts_result["jpegphoto"]) = split ('%', $info);
+					
+		if ($contacts_result['jpegphoto'])
+			$photo_link = '<img src="./inc/show_user_photo.php?mail='.$contacts_result['mail'].'">';
+		else
+			$photo_link = '<img src="./templates/default/images/photo.png">';
+					
+		$phoneUser = $contacts_result['phone'];
+					
+		if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['voip_enabled'] && $phoneUser) {
+			$phoneUser = '<a title="'.$functions->getLang("Call to Comercial Number").'" href="#" onclick="InfoContact.connectVoip(\''.$phoneUser.'\',\'com\')">'.$phoneUser.'</a>';
+			if($contacts_result['mobile']){
+				$phoneUser .= ' / <a title="'.$functions->getLang("Call to Mobile Number").'" href="#" onclick="InfoContact.connectVoip(\''.$contacts_result['mobile'].'\',\'mob\')">'.$contacts_result['mobile'].'</a>';
+			}
+		}
+		$option =
+			'<tr class="quicksearchcontacts_unselected">' .
+				'<td class="cc" width="1%">' .
+					'<a title="'.$functions->getLang("Write message").'" onClick="javascript:QuickSearchUser.create_new_message(\''.$contacts_result["cn"].'\', \''.$contacts_result["mail"].'\')">' .
+						$photo_link .
+					'</a>' .
+				'</td>' .
+				'<td class="cc">' .
+					'<span name="cn">' . $contacts_result['cn'] . '</span>' . '<br>' .
+					'<a title="'.$functions->getLang("Write message").'" onClick="javascript:QuickSearchUser.create_new_message(\''.$contacts_result["cn"].'\', \''.$contacts_result["mail"].'\')">' .
+						'<font color=blue>' .
+							'<span name="mail">' . $contacts_result['mail'] . '</span>' . '<br>' .
+						'</font>' .
+					'</a>' .
+					$phoneUser .
+				'</td>' .
+			'</tr>';
+		return $option;
 	}
 
Index: trunk/expressoMail1_2/js/search.js
===================================================================
--- trunk/expressoMail1_2/js/search.js	(revision 163)
+++ trunk/expressoMail1_2/js/search.js	(revision 271)
@@ -266,4 +266,9 @@
 		table.id    = "table_resultsearch_" + search_tabs;
 		table.width = "100%";
+		table.borderColorDark = "#bbbbbb";
+		table.frame = "void";
+		table.rules = "rows";
+		table.cellPadding = "0";
+		table.cellSpacing = "0";
 
 		var tbody = document.createElement("TBODY");
@@ -275,6 +280,5 @@
 		for( var i=0; i < nw_array.length; i++){
 			var tr = document.createElement("TR");
-	    	//var color = "#F0F0F0";
-			//tr.style.background  =  color;
+			tr.style.height = "30px";
 			tr.className = 'tr_msg_read';
 
@@ -326,4 +330,6 @@
 					if( j == 3){
 						var subject_encode = url_encode(aux[2]);
+						if (! subject_encode)
+							aux[2] = get_lang("no subject") + "...";
 						td.width = "30%";					
 						var td1  = '<div style="width:100%;overflow:hidden"><a href=javascript:void(0) onclick=EsearchE.open_msg(\"' + url_encode(mailbox) + '\",\"' + uid_msg + '\",\"' + subject_encode + '\")>' + aux[2] +'</a></div>';
@@ -345,6 +351,11 @@
 				}
 			}
-			aux.splice(0,(aux.length));
-			tbody.appendChild(tr);
+			aux.splice(0,(aux.length));	
+
+		subject = tr.firstChild;
+		subject = subject.nextSibling.nextSibling.nextSibling.firstChild.firstChild.innerHTML;
+//		_dragArea.makeDragged(tr, msg_number, subject, true);
+		_dragArea.makeDragged(tr, tr.firstChild.firstChild.id.substr(tr.firstChild.firstChild.id.indexOf(';')+1), subject, true);
+		tbody.appendChild(tr);
 		}
 		table.appendChild(tbody);
@@ -376,5 +387,4 @@
 		var table_element = document.createElement("TABLE");
 		var tbody_element = document.createElement("TBODY");
-		table_element.border = 1;
 		table_element.setAttribute("id", "table_message_header_box");
 		table_element.className = "table_message_header_box";
@@ -447,5 +457,5 @@
 		content_search.appendChild(div_scroll_result);	
 		if (span_options)
-			content_search.appendChild(span_options);	
+			content_search.appendChild(span_options);
 	}
 
Index: trunk/expressoMail1_2/js/abas.js
===================================================================
--- trunk/expressoMail1_2/js/abas.js	(revision 245)
+++ trunk/expressoMail1_2/js/abas.js	(revision 271)
@@ -69,28 +69,4 @@
 	}
 	
-	/*var span_options = document.getElementById("span_options");	
-	if (span_options){
-		span_options.parentNode.removeChild(span_options);
-		var span_options = document.createElement("SPAN");	
-		span_options.setAttribute("id","span_options");	
-	}
-		
-	if ((span_options) && (ID == 0)){
-		var span_D = Element("span_D");
-		span_options.innerHTML = 
-		'<span title="'+get_lang("Delete")+'" style="margin-left:8px;" class="message_options" onclick=delete_msgs(\'null\',\'selected\',\'null\')>'+get_lang("Delete")+'</span> | '+
-		'<span title="'+get_lang("Move")+'" class="message_options" onclick=wfolders.makeWindow(\"\",\"move_to\")>'+get_lang("Move")+'</span> | '+
-   		'<span title="'+get_lang("Print")+'" class="message_options" onclick=print_all()>'+get_lang("Print")+'</span> | '+
-	   	'<span title="'+get_lang("Export")+'" class="message_options" onclick="export_all_selected_msgs()">'+get_lang("Export")+'</span>';	
-	   	span_options.setAttribute('style',"font-size:5px;");
-		span_D.parentNode.insertBefore(span_options,span_D);	
-	} else
-		if ((span_options) && (ID != 0)){		
-			span_options.innerHTML = '<span title="'+get_lang("Delete")+'" style="margin-left:8px" class="message_options" onclick=delete_search_msgs('+content.id+')>'+get_lang("Delete")+'</span> | '+
-				'<span title="'+get_lang("Move")+'" class="message_options" onclick=wfolders.makeWindow(\"border_id_'+content.id.substr(11)+'\",\"move_to\")>'+get_lang("Move")+'</span>';
-		var span_D = Element("span_D");				
-		span_D.parentNode.insertBefore(span_options,span_D);	
-	   	}
-	*/
 	return ID;
 }
@@ -108,5 +84,12 @@
 	}
 	Element("footer_menu").style.display = 'none';
-	var ID = id_value ? id_value : parseInt(BordersArray[(BordersArray.length-1)].sequence) + 1;
+	
+	if (! id_value) // Is new message?
+		var ID = parseInt(BordersArray[(BordersArray.length-1)].sequence) + 1;
+	else{
+		var ID = id_value;
+		if (document.getElementById("border_id_"+id_value+"_r")) // Edit message? if yes treat like new
+					var id_value = null;
+	}
 	
 	td = document.createElement("TD");
@@ -204,4 +187,5 @@
 	if(!ID)
 		return false;
+	
 	if (msg_sent == 'false')
 	{
@@ -211,5 +195,6 @@
 			try
 			{
-				if (body.contentWindow.document.designMode.toLowerCase() == 'on')
+				var save_link = Element("save_message_options");
+				if ((body.contentWindow.document.designMode.toLowerCase() == 'on') && (save_link.onclick != ''))
 				{
 					var discard_msg = confirm(get_lang("Your message has not been sent. Discard your message?"), "");
@@ -220,4 +205,6 @@
 					else
 					{
+						if (! newMessageTab.toPreserve[ID])
+							cExecute ("$this.imap_functions.delete_msgs&folder="+newMessageTab.imapBox[ID]+"&msgs_number="+newMessageTab.imapUid[ID],function(data){ return });
 						Element('to_'+ID).focus();
 					}
@@ -229,4 +216,7 @@
 		}
 	}
+
+	newMessageTab.toPreserve[ID] = false;
+	newMessageTab.imapUid[ID] = 0;
 
 	hold_session = false;
Index: trunk/expressoMail1_2/js/common_functions.js
===================================================================
--- trunk/expressoMail1_2/js/common_functions.js	(revision 197)
+++ trunk/expressoMail1_2/js/common_functions.js	(revision 271)
@@ -45,5 +45,14 @@
 // onUnload edit message
 if(!is_ie)
-	window.onbeforeunload = unloadMess;
+{
+	var beforeunload = window.onbeforeunload;
+	window.onbeforeunload = function()
+	{
+		if ( typeof beforeunload == 'function' )
+			beforeunload();
+
+		return unloadMess();
+	};
+}
 function unloadMess(){
 	var mess = get_lang("Your message has not been sent and will be discarted.");
@@ -154,5 +163,5 @@
 }
 
-function download_attachments(msg_folder, msg_number, idx_file, msg_part, encoding, new_file_name){
+function download_attachments(msg_folder, msg_number, idx_file, msg_part, encoding, new_file_name, show_iframe){
 	div_attachment = document.getElementById("id_div_attachment");
 	var params = '';
@@ -167,6 +176,8 @@
 	if(encoding)
 		params += "&encoding="+encoding;
+
 	div_attachment.innerHTML="<iframe style='display:none;width:0;height:0' name='attachment' src='inc/gotodownload.php?msg_folder="+msg_folder+"&msg_number="+msg_number+"&idx_file="+idx_file+"&msg_part="+msg_part+params+"'></iframe>";
 }
+
 function download_all_attachments(msg_folder, msg_number){
 	var handler_source = function(data){		
@@ -176,23 +187,32 @@
 }
 // Add Input File Dynamically.
-var countFiles = 0;
 function addFile(id_border){
 	divFiles = document.getElementById("divFiles_"+id_border);
-	countFiles++;
+	
+	if (divFiles.lastChild)
+		var countDivFiles = parseInt(divFiles.lastChild.id.split('_')[2]) + 1;
+
+	if (! countDivFiles)
+		var countDivFiles = 1;
+	
 	divFile = document.createElement('DIV');
-	inputFile = document.createElement("INPUT");
+	
+	var inputFile = document.createElement("INPUT");
 	
 	var tmp_id_border = document.createAttribute('id_border');
 	tmp_id_border.value = id_border;
+	
 	inputFile.setAttributeNode(tmp_id_border);
-	inputFile.id = "inputFile_"+id_border+countFiles;
+	inputFile.id = "inputFile_"+id_border+"_"+countDivFiles;
 	inputFile.onchange = function () {validateFileExtension(this.value, this.id.replace("input","div"), this.getAttribute('id_border'));};
 	inputFile.type = 'file';
 	inputFile.size = 50;
 	inputFile.maxLength = 255;
-	inputFile.name='file_'+countFiles;
+	inputFile.name='file_'+countDivFiles;
+	
 	divFile.appendChild(inputFile);
-	linkFile = document.createElement("A");
-	linkFile.id = "linkFile_"+id_border+countFiles;
+	
+	var linkFile = document.createElement("A");
+	linkFile.id = "linkFile_"+id_border+"_"+countDivFiles;
 	linkFile.href='javascript:void(0)';
 	linkFile.onclick=function () {removeFile(this.id.replace("link","div"));};
@@ -200,9 +220,10 @@
 	//divFile.innerHTML += "&nbsp;&nbsp;";
 	divFile.appendChild(linkFile);
-	divFile.id = "divFile_"+id_border+countFiles;	
+	divFile.id = "divFile_"+id_border+"_"+countDivFiles;	
 	divFiles.appendChild(divFile);
 }
 //	Remove Input File Dynamically.
 function removeFile(id){
+	var border_id = id.substr(8,1);
 	var el = Element(id);
 	el.parentNode.removeChild(el);
@@ -210,16 +231,33 @@
 
 function validateFileExtension(fileName, id, id_border){
-	var fileExtension = fileName.split(".");
+	var error_flag  = false;
+	if (fileName[0] != '/'){ // file name is windows format?
+		var file = fileName.substr(fileName.lastIndexOf('\\') + 1, fileName.length);
+		if ((fileName.indexOf(':\\') != 1) && (fileName.indexOf('\\\\') != 0)) // Is stored in partition or a network file?
+			error_flag = true;	
+	}
+	else // is nix
+		var file = fileName.substr(fileName.lastIndexOf('/') + 1, fileName.length);						
+
+	var fileExtension = file.split(".");
 	fileExtension = fileExtension[(fileExtension.length-1)];
-	
 	for(var i=0; i<denyFileExtensions.length; i++)
 	{
 		if(denyFileExtensions[i] == fileExtension)
 		{
-			alert(get_lang('File extension forbidden') + '.');
-			removeFile(id);
-			addFile(id_border);
-		}
-	}
+			error_flag = true;
+			break;
+		}
+			
+	}
+
+	if (error_flag == true){
+		alert(get_lang('File extension forbidden or invalid file') + '.');
+		removeFile(id);
+		addFile(id_border);
+		return false;
+	}
+	return true;
+	
 }
 
Index: trunk/expressoMail1_2/js/main.js
===================================================================
--- trunk/expressoMail1_2/js/main.js	(revision 245)
+++ trunk/expressoMail1_2/js/main.js	(revision 271)
@@ -1,4 +1,6 @@
 // Tempo do auto refresh (em milisegundos)
 var time_refresh = 300000;
+var autosave_time = 60000;
+
 function init(){
 	if (!is_ie)
@@ -38,4 +40,77 @@
 	setTimeout('auto_refresh()', time_refresh);
 }
+
+var away = false;
+var away_timer;
+function setAway ()
+{
+	away_timer = setTimeout("setAway()", 5000);
+	away=true;
+}
+
+function auto_save_msg(border_id)
+{
+	if (document.getElementById('border_id_'+border_id))
+	{	
+		var	 keypress_handler = function stop_counting ()
+		{
+			clearTimeout(away_timer);
+			away=false;
+			away_timer = setTimeout('setAway()',5000);
+		};
+		
+		var obj = document.getElementById('body_'+border_id).contentWindow.document;
+		if ( obj.addEventListener )
+				obj.addEventListener('keypress', keypress_handler, false);
+		else if ( obj.attachEvent )
+			obj.attachEvent('onkeypress', keypress_handler);
+
+		if (away)
+			{
+				var save_link = Element("save_message_options");
+				if (save_link.onclick !=  '')
+					save_msg(border_id);
+				else
+					setTimeout('auto_save_msg('+border_id+')',autosave_time);
+			}
+			else
+				setTimeout('auto_save_msg('+border_id+')',3000);
+	}
+}
+
+function watch_changes_in_msg(border_id)
+{
+	if (document.getElementById('border_id_'+border_id))
+	{	
+		function keypress_handler ()
+		{
+			away=false;
+			var save_link = Element("save_message_options");
+			save_link.onclick = function onclick(event) { newMessageTab.toPreserve[border_id] = true; save_msg(border_id); } ;
+			save_link.style.color = '#0000ff';
+		};
+		
+		var obj = document.getElementById('body_'+border_id).contentWindow.document;
+		if ( obj.addEventListener )
+				obj.addEventListener('keypress', keypress_handler, false);
+		else if ( obj.attachEvent )
+			obj.attachEvent('onkeypress', keypress_handler);
+			
+		var subject_obj = document.getElementById('subject_'+border_id);
+		if ( subject_obj.addEventListener )
+				subject_obj.addEventListener('keypress', keypress_handler, false);
+		else if ( subject_obj.attachEvent )
+			subject_obj.attachEvent('onkeypress', keypress_handler);
+			
+		var to_obj = document.getElementById('to_'+border_id);
+		if ( to_obj.addEventListener )
+				to_obj.addEventListener('keypress', keypress_handler, false);
+		else if ( to_obj.attachEvent )
+			to_obj.attachEvent('onkeypress', keypress_handler);
+		
+	}
+}
+
+
 
 function show_msg(msg_info){
@@ -105,14 +180,19 @@
 			var box = Element("tbody_box");
 			table_element.appendChild(box);
-			var len = data.length;
-			for (var i=0; i<len; i++){
+			for (var i=0; i<data.length; i++){
 				var new_msg = this.make_tr_message(data[i], current_folder);
 				_dragArea.makeDragged(new_msg, data[i].msg_number, data[i].subject, true);
 				eval(data[i].command);
 			}
+			
+			for (var i=0; i<data.msgs_to_delete.length; i++){
+				var remove_msg = document.getElementById(data.msgs_to_delete[i]);
+				if (remove_msg)
+					remove_msg.parentNode.removeChild(remove_msg);
+			}
 			if(parseInt(alert_new_msg) && data.new_msgs > 0)
 				alert(get_lang("You have %1 new", data['new_msgs'])+" "+(data['new_msgs'] > 1 ? get_lang("messages") : get_lang("message")) +"!");
 			if(data.new_msgs > 0){
-			Element('tot_m').innerHTML = parseInt(Element('tot_m').innerHTML) + parseInt(data.new_msgs);
+			Element('tot_m').innerHTML = parseInt(Element('tot_m').innerHTML) + parseInt(data.new_msgs); //refresh tab title
 			update_quota();
 			}
@@ -368,5 +448,9 @@
 
 function new_message(type, border_ID){
-	var new_border_ID = draw_new_message();	
+
+	var new_border_ID = draw_new_message(parseInt(border_ID));
+	if (preferences.auto_save_draft == 1)
+		setTimeout('auto_save_msg('+new_border_ID+')', autosave_time);		
+	
 	// Salva a pasta da mensagem respondida ou encaminhada:
 	var folder_message = Element("input_folder_"+border_ID);
@@ -596,4 +680,7 @@
 			break;
 		case "edit":
+			newMessageTab.imapBox[new_border_ID] = folder_message.value
+			newMessageTab.imapUid[new_border_ID] = parseInt(border_ID.substr(0,border_ID.indexOf("_")));
+			document.getElementById('font_border_id_'+new_border_ID).innerHTML = data.subject;
 			data.to = Element("to_values_" + border_ID).value;
 			data.to = data.to.replace(/&lt;/gi,"<");
@@ -610,4 +697,20 @@
 			Element("subject_" + new_border_ID).value = data.subject;
 			
+			var divFiles = Element("divFiles_"+new_border_ID);
+			if (Element("attachments_" + border_ID)){
+				var attachments = document.getElementById("attachments_" + border_ID).childNodes;
+				for (var i = (attachments.length > 1 ? 1 : 0); i < attachments.length; i++){
+					var link_attachment = document.createElement("A");
+					link_attachment.setAttribute("href", attachments[i].href);
+					link_attachment.innerHTML = attachments[i].innerHTML;
+					var tmp = link_attachment.href.replace("javascript:download_attachments(", "").replace(")", "");
+					var a_tmp = tmp.split(',');
+					tmp = link_attachment.innerHTML.substring(0,link_attachment.innerHTML.lastIndexOf("("));
+					a_tmp[2] = "'"+tmp.substring(0,tmp.length-1)+"'";
+					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);
+				}
+			}
 			var body = Element("body_" + new_border_ID);
 			body.contentWindow.document.open();
@@ -682,5 +785,4 @@
 			set_message_flag(msg_number_forwarded.value, 'forwarded');
 		}
-		
 		delete_border(ID,'true');
 		if(wfolders.alert){
@@ -699,13 +801,19 @@
 			write_msg(data);
 	}
+	if ((! newMessageTab.toPreserve[ID]) && (newMessageTab.imapUid[ID] != 0))
+		cExecute ("$this.imap_functions.delete_msgs&folder="+newMessageTab.imapBox[ID]+"&msgs_number="+newMessageTab.imapUid[ID],function(data){ return });
 }
 
 function send_message(ID, folder, folder_name){
+	var save_link = Element("save_message_options");
+	save_link.onclick = '';
+	save_link.style.color = '#999';
+	
 	ID_tmp = ID;
-	
+
 	var handler_send_message = function(data){
-		send_message_return(data, this.ID_tmp);
-	}
-
+		send_message_return(data, this.ID_tmp); // this is a hack to escape quotation form connector bug
+	};
+		
 	var textArea = document.createElement("TEXTAREA");
 	textArea.style.display='none';
@@ -719,4 +827,8 @@
 	input_folder.name = "folder";
 	input_folder.value = folder;
+	var msg_id = document.createElement("INPUT");
+	msg_id.style.display='none';
+	msg_id.name = "msg_id";
+	msg_id.value = newMessageTab.imapUid[ID];
 	
 	if (is_ie){
@@ -730,4 +842,5 @@
 	form.appendChild(textArea);
 	form.appendChild(input_folder);
+	form.appendChild(msg_id);
 
 	var _subject = trim(Element("subject_"+ID).value);
@@ -736,43 +849,182 @@
 		return;
 	}
-
-	cExecuteForm ("$this.imap_functions.send_mail", form, handler_send_message);
-}
-
-function save_msg(border_id, folder_id, folder_name){
-	var handler_save_msg = function(data){
-		if(!verify_session(data))
-			return;
-		if (data.append){
-			write_msg(get_lang('Your message was save as draft in folder %1.', data.folder_name));
-			delete_border(data.border_id,'true');
-		}
-		else
-			write_msg('ERRO saving your message.');
-	}
-	
-	var msg_data = new Array();
-	if (document.getElementById("to_" + border_id))
-		msg_data.to = Element("to_" + border_id).value;
-	
-	if (document.getElementById("cc_" + border_id))
-		msg_data.cc = Element("cc_" + border_id).value;
-	
-	if (document.getElementById("cco_" + border_id))	
-		msg_data.cco = Element("cco_" + border_id).value;	
-	
-	if (document.getElementById("subject_" + border_id))	
-		msg_data.subject = Element("subject_" + border_id).value;
-	
-	if (document.getElementById("body_" + border_id))		
-		msg_data.body = Element("body_" + border_id).contentWindow.document.body.innerHTML;
-		
-	var args   = "$this.imap_functions.save_msg";	
-	var body = msg_data.body.replace(/&nbspl/g, "%nbsp;");
-	body = url_encode(msg_data.body);
-	msg_data.subject = url_encode(msg_data.subject);
-	var params = "folder_id="+folder_id+"&folder_name="+folder_name+"&border_id="+border_id+"&to="+msg_data.to+"&cc="+msg_data.cc+"&cco="+msg_data.cco+"&subject="+msg_data.subject+"&body="+body;
-	cExecute( args, handler_save_msg, params);
-}
+	
+	cExecuteForm ("$this.imap_functions.send_mail", form, handler_send_message, ID);
+}
+
+function return_save(data,border_id,folder_name,folder_id,message_id)
+{
+	var handler_delete_msg = function(data){ refresh(preferences.alert_new_msg); };
+	RichTextEditor.saveFlag = 1;
+
+	if (! data)
+		write_msg('ERROR saving your message.');
+	else
+	{
+		newMessageTab.imapUid[border_id] = data.msg_no;
+		newMessageTab.imapBox[border_id] = data.folder_id;
+		
+		var newTitle = document.getElementById('subject_'+border_id).value;
+		if (newTitle.length > 18)
+			newTitle = newTitle.substr(18) + '...';
+		else if (newTitle == '')
+				newTitle = get_lang("No subject");
+		document.getElementById('font_border_id_'+border_id).innerHTML = newTitle;
+		
+		// Replace the embedded images for new uids
+		var mainField = document.getElementById('body_'+border_id).contentWindow;
+		var content_body =  mainField.document.getElementsByTagName('body').item(0).innerHTML;
+		var body_images = content_body.match(/msg_num=\d*/g);
+		if (body_images)
+		{
+			for (var i=0; i<body_images.length; i++){
+				content_body = 	content_body.replace(body_images[i],"msg_num="+newMessageTab.imapUid[border_id]);
+			}
+			mainField.document.getElementsByTagName('body').item(0).innerHTML = content_body;
+			// This is not just stupid, it refresh screen to avoid broken images
+			mainField.document.getElementsByTagName('body').item(0).innerHTML = mainField.document.getElementsByTagName('body').item(0).innerHTML;	
+		}	
+				
+		//Replace all files to new files
+		var divFiles = Element("divFiles_"+border_id);
+		var divParent = divFiles.parentNode;
+		divParent.removeChild(divFiles);
+		divFiles = document.createElement('DIV');
+		divFiles.id = "divFiles_"+border_id;
+		divParent.appendChild(divFiles);
+		
+		var attach_files = connector.unserialize(data.files);
+		if (attach_files != null) {
+			newMessageTab.countFile[border_id] = attach_files.length;
+		for (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 + " ("+parseInt(fileSize)+" kb)";
+
+			var href = "'"+folder_id+"','"+data.msg_no+"','"+(att_index)+"','"+(att_index+2)+"','base64'";
+
+			link_attachment.setAttribute("href", "javascript:download_attachments("+href+")");
+
+			var a_tmp = href.split(',');
+			a_tmp[2] = fileName;
+			s_tmp = escape(connector.serialize(a_tmp));
+					
+			var check_attachment = document.createElement("INPUT");
+			check_attachment.type = 'CHECKBOX';
+			check_attachment.name = 'forwarding_attachments[]';
+			check_attachment.value = s_tmp;
+
+			divFiles.appendChild(check_attachment);
+			divFiles.appendChild(link_attachment);
+			divFiles.appendChild(document.createElement("BR"));
+
+			check_attachment.checked = true;
+		}
+	}
+		if (message_id)
+			cExecute ("$this.imap_functions.delete_msgs&folder="+newMessageTab.imapBox[border_id]+"&msgs_number="+message_id,handler_delete_msg);
+		
+		if (preferences.auto_save_draft == 1)
+				setTimeout('auto_save_msg('+border_id+')', autosave_time);		
+
+		var save_link = Element("save_message_options");
+		save_link.onclick = '';
+		save_link.style.color = '#999';
+		watch_changes_in_msg(border_id);
+		
+		write_msg(get_lang('Your message was save as draft in folder %1.', folder_name));
+	}		
+}
+
+function save_msg(border_id){
+	if (newMessageTab.imapBox[border_id]) //Gets the imap folder
+		var folder_id = newMessageTab.imapBox[border_id];
+	else
+		var	folder_id = "INBOX/"+draftsfolder;
+
+	if (folder_id == 'INBOX') // and folder name from border
+		var folder_name = get_lang(folder_id);
+	else
+		var folder_name = folder_id.substr(6);
+		
+	// hack to avoid form connector bug,  escapes quotation. Please see #179
+	tmp_border_id=border_id;
+	tmp_folder_name=folder_name;
+	tmp_folder_id=folder_id;
+	message_id = newMessageTab.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 textArea = document.createElement("TEXTAREA");
+	textArea.style.display='none';
+	textArea.name = "body";
+	body = document.getElementById("body_"+border_id);
+	textArea.value += '<body>\r\n';
+	textArea.value += body.contentWindow.document.body.innerHTML;
+	textArea.value += '\r\n</body>';
+	var input_folder = document.createElement("INPUT");
+	input_folder.style.display='none';
+	input_folder.name = "folder";
+	input_folder.value = folder_id;
+	
+	if (is_ie){
+		var i = 0;
+		while (document.forms(i).name != "form_message_"+border_id){i++}
+		form = document.forms(i);
+	}
+	else
+		form = document.forms["form_message_"+border_id];
+	form.appendChild(textArea);
+	form.appendChild(input_folder);
+
+	cExecuteForm ("$this.imap_functions.save_msg", form, handler_save_msg,border_id);	
+}
+
+function return_saveas(data,border_id,folder_name)
+{
+	if(!verify_session(data))
+		return;
+	if (data.append)
+	{
+		delete_border(border_id,null);
+		write_msg(get_lang('Your message was save as draft in folder %1.', folder_name));
+	}
+	else
+		write_msg('ERROR saving your message.');					
+}
+
+
+function save_as_msg(border_id, folder_id, folder_name){
+	// hack to avoid form connector bug,  escapes quotation. Please see #179
+	tmp_border_id=border_id;
+	tmp_folder_name=folder_name;
+	var handler_save_msg = function(data){ return_saveas(data,this.tmp_border_id,this.tmp_folder_name); }	
+	var textArea = document.createElement("TEXTAREA");
+	textArea.style.display='none';
+	textArea.name = "body";
+	body = document.getElementById("body_"+border_id);
+	textArea.value += '<body>\r\n';
+	textArea.value += body.contentWindow.document.body.innerHTML;
+	textArea.value += '\r\n</body>';
+	
+	var input_folder = document.createElement("INPUT");
+	input_folder.style.display='none';
+	input_folder.name = "folder";
+	input_folder.value = folder_id;
+	
+	if (is_ie){
+		var i = 0;
+		while (document.forms(i).name != "form_message_"+border_id){i++}
+		form = document.forms(i);
+	}
+	else
+		form = document.forms["form_message_"+border_id];
+	form.appendChild(textArea);
+	form.appendChild(input_folder);
+	
+	cExecuteForm ("$this.imap_functions.save_msg", form, handler_save_msg,border_id);
+}
+
 
 // Get checked messages
Index: trunk/expressoMail1_2/js/wfolders.js
===================================================================
--- trunk/expressoMail1_2/js/wfolders.js	(revision 197)
+++ trunk/expressoMail1_2/js/wfolders.js	(revision 271)
@@ -47,5 +47,5 @@
 			wfolders.arrayWin[el.id].close();
 			if (type == 'save'){
-				save_msg(border_id, wfolders_tree._selected.id, wfolders_tree._selected.caption);
+				save_as_msg(border_id, wfolders_tree._selected.id, wfolders_tree._selected.caption,true);
 			}
 			else if (type == 'send_and_file'){
Index: trunk/expressoMail1_2/js/filter.js
===================================================================
--- trunk/expressoMail1_2/js/filter.js	(revision 246)
+++ trunk/expressoMail1_2/js/filter.js	(revision 271)
@@ -370,6 +370,5 @@
 				_this.out_officeF = false;
 				//Save outoffice in prefs:
-				if(!prefe)
-					connector.loadScript("preferences");
+				connector.loadScript("preferences");
 				prefe.save("outoffice", _this.out_officeF);
 			}
@@ -530,6 +529,5 @@
 				_this.out_officeF = (aux[4].replace("\n","") == "off") ? false : true;
 				//Save outoffice in prefs:
-				if(!prefe)
-					connector.loadScript("preferences");
+				connector.loadScript("preferences");
 				prefe.save("outoffice", _this.out_officeF);
 		}
Index: trunk/expressoMail1_2/js/draw_api.js
===================================================================
--- trunk/expressoMail1_2/js/draw_api.js	(revision 252)
+++ trunk/expressoMail1_2/js/draw_api.js	(revision 271)
@@ -871,6 +871,30 @@
 		var option_edit	  = '<span class="message_options" onclick="new_message(\'edit\',\''+ID+'\');">'+get_lang('Edit')+'</span> | ';
 		var option_print = '<span class="message_options" onclick="print_msg(\''+info_msg.msg_folder+'\',\''+info_msg.msg_number+'\',\''+ID+'\');">'+get_lang('Print')+'</span> | ';
-		var option_delete = '<span class="message_options" onclick="delete_msgs(\''+info_msg.msg_folder+'\',\''+info_msg.msg_number+'\',\''+ID+'\');">'+get_lang('Delete')+'</span>';
+		var option_delete = '<span class="message_options" onclick="delete_msgs(\''+info_msg.msg_folder+'\',\''+info_msg.msg_number+'\',\''+ID+'\');">'+get_lang('Delete')+'</span> | ';		
+		var option_hide_more = document.createElement("SPAN");
+		option_hide_more.className = 'message_options';
+		options.align = 'right';
+		option_hide_more.value = 'more_options';
+		option_hide_more.id = 'option_hide_more_'+ID;
+		option_hide_more.innerHTML = get_lang('Options');
+		option_hide_more.onclick = function(){
+			var _height = Element("div_message_scroll_"+ID).style.height;
+			_height = parseInt(_height.replace("px",""));
+			var _offset = 35;
+			if (this.value == 'more_options'){
+				this.innerHTML = "<b><u>"+get_lang('Options')+"</u></b>";
+				this.value = 'hide_options';
+				Element("div_message_scroll_"+ID).style.height = (_height - _offset)+"px";
+				Element('table_message_others_options_'+ID).style.display = '';
+			}
+			else{
+				this.innerHTML = get_lang('Options');
+				this.value = 'more_options';
+				Element("div_message_scroll_"+ID).style.height = (_height + _offset)+"px";
+				Element('table_message_others_options_'+ID).style.display = 'none';
+			}
+		};
 		options.innerHTML = option_edit + option_print + option_delete;
+		options.appendChild(option_hide_more);
 		tr.appendChild(td);
 		tr.appendChild(options);
@@ -896,4 +920,5 @@
 	var td1 = document.createElement("TD");
 	td1.innerHTML = get_lang("From: ");
+	td1.appendChild(deny_email(info_msg.from.email));
 	td1.width = "7%";
 	
@@ -903,4 +928,5 @@
 		var td111 = document.createElement("TD");
 		td111.innerHTML = get_lang("Sent by")+": ";
+		td111.appendChild(deny_email(info_msg.sender.email));
 		td111.setAttribute("noWrap","true");
 		var sender = document.createElement("TD");
@@ -911,5 +937,4 @@
 		sender_values.value = info_msg.sender.full; //Veio do IMAP, sem images nem links.
 		sender.innerHTML += draw_plugin_cc(ID, info_msg.sender.full);
-		sender.appendChild(deny_email(info_msg.sender.email));		
 		sender.className = "header_message_field";
 		tr111.appendChild(td111);
@@ -925,5 +950,4 @@
 	if (info_msg.Draft != "X"){
 		from.innerHTML += draw_plugin_cc(ID, info_msg.from);
-		from.appendChild(deny_email(info_msg.from.email));
 		tbody_message_others_options.appendChild(tr1);
 	}
@@ -1197,6 +1221,6 @@
 }
 
-function draw_new_message(){
-	var ID = create_border("");
+function draw_new_message(border_ID){
+	var ID = create_border("",border_ID);
 	hold_session = true;
 /////////////////////////////////////////////////////////////////////////////////////////////////////////
@@ -1241,5 +1265,6 @@
 		wfolders.alert = true;
 	}
-	var option_save			= '<span class="message_options" onclick=wfolders.makeWindow("'+ID+'","save");>'+get_lang("Save")+'</span> | ';
+//	var option_save_as		= '<span class="message_options" onclick=wfolders.makeWindow("'+ID+'","save");>'+get_lang("Save as")+'</span> | ';
+	var option_save			= '<span id="save_message_options" class="message_options" onclick="newMessageTab.toPreserve['+ID+'] = true; save_msg('+ID+');">'+get_lang("Save")+'</span> | ';
 	var option_search		= '<span class="message_options" onclick=openListUsers("'+ID+'");>'+get_lang("Search")+'</span>';
 	td_menu_new_message.innerHTML = option_send + option_send_and_file + option_save + option_search;
@@ -2046,5 +2071,5 @@
 		dn_em.setAttribute("title",get_lang("Block Sender"));
 		dn_em.style.cursor = "pointer";		
-		dn_em.innerHTML = "<img onclick=filter.new_rule('"+email+"') src='./templates/default/images/deny.gif'>";
+		dn_em.innerHTML = "<img align='top' onclick=filter.new_rule('"+email+"') src='./templates/default/images/deny.gif'>";
 	return dn_em;
 	
Index: trunk/expressoMail1_2/js/connector.js
===================================================================
--- trunk/expressoMail1_2/js/connector.js	(revision 197)
+++ trunk/expressoMail1_2/js/connector.js	(revision 271)
@@ -506,5 +506,5 @@
 	//	url: 'module.class.method'
 	//	form: form element (for upload files)	
-	function cExecuteForm(url, form, handler){
+	function cExecuteForm(url, form, handler,id){
 		connector.buildBar();
 		isExecuteForm = true;		
@@ -526,9 +526,15 @@
 		}
 
-		if(countFiles) {			
+		var divFiles = Element("divFiles_"+id);		
+		if (divFiles.firstChild) {
 			el			= document.createElement('input');
 			el.type	= 'hidden';	
 			el.name	= 'countFiles';
-			el.value 	= countFiles;
+			var countDivFiles = 0;
+			try{
+				countDivFiles = parseInt(divFiles.lastChild.firstChild.id.split('_')[2]) + 1; // The id of last file 
+				}
+			catch (e) { var countDivFiles = 0; };
+			el.value	= countDivFiles ;
 			form.appendChild(el);						
 		}		
Index: trunk/expressoMail1_2/js/QuickCatalogSearch.js
===================================================================
--- trunk/expressoMail1_2/js/QuickCatalogSearch.js	(revision 128)
+++ trunk/expressoMail1_2/js/QuickCatalogSearch.js	(revision 271)
@@ -11,5 +11,4 @@
 		_this = this;
 
-		var title = get_lang('Select a name') + ':';
 		var el = document.createElement("DIV");
 		el.style.visibility = "hidden";
@@ -23,10 +22,15 @@
 		el.innerHTML = "";
 		
-		if (data.quickSearch_only_in_userSector)
-			title += "<font color='BLACK' nowrap> ("+get_lang('Showing only the results found in your organization')+".)</font>"
-		
-		el.innerHTML = "&nbsp;&nbsp;<b><font color='BLUE' nowrap>"+title+"</font></b><br>&nbsp;&nbsp;";
-		
 		if (document.getElementById('select_QuickCatalogSearch') == null){
+
+			var title_innerHTML = get_lang('Select a name') + ':';
+			if (data.quickSearch_only_in_userSector)
+				title_innerHTML += "<font color='BLACK' nowrap> ("+get_lang('Showing only the results found in your organization')+".)</font>"
+
+			var title = document.createElement("SPAM");
+			title.id = 'window_QuickCatalogSearch_title';
+			title.innerHTML = "&nbsp;&nbsp;<b><font color='BLUE' nowrap>"+title_innerHTML+"</font></b><br>&nbsp;&nbsp;";
+			el.appendChild(title);
+			
 			var cmb = document.createElement("SELECT");
 			cmb.id = "select_QuickCatalogSearch";
@@ -83,4 +87,11 @@
 		}
 		else{
+			var title_innerHTML = get_lang('Select a name') + ':';
+			if (data.quickSearch_only_in_userSector)
+				title_innerHTML += "<font color='BLACK' nowrap> ("+get_lang('Showing only the results found in your organization')+".)</font>"
+
+			var title = Element('window_QuickCatalogSearch_title');
+			title.innerHTML = "&nbsp;&nbsp;<b><font color='BLUE' nowrap>"+title_innerHTML+"</font></b><br>&nbsp;&nbsp;";
+			
 			var cmb = document.getElementById('select_QuickCatalogSearch');
 			cmb.onkeypress = function (e)
@@ -109,6 +120,5 @@
 				}
 			};
-			
-			
+
 			for (i=0; i<cmb.length; i++)
 				cmb.options[i--] = null;
Index: trunk/expressoMail1_2/js/rich_text_editor.js
===================================================================
--- trunk/expressoMail1_2/js/rich_text_editor.js	(revision 163)
+++ trunk/expressoMail1_2/js/rich_text_editor.js	(revision 271)
@@ -1,7 +1,18 @@
+var newMessageTab = {
+		'imapUid' : [], // Stores the imap email number of current tab
+		'countFile' : [0,0,0,0,0,0,0,0,0,0], // Stores the number of files attached in current tab
+		'imapBox' : [], // Stores the folder name
+		'toPreserve' : [] // Check if the message should be removed from draft after send
+		};
+		
+var defaultDraftFolder = '';
+
 function cRichTextEditor(){
+	this.emwindow   = new Array;
 	this.editor;
 	this.table;
 	this.id;
 	this.buildEditor();
+	this.saveFlag = 0;
 }
 
@@ -151,5 +162,5 @@
 	
 	var buttons = ['bold', 'italic', 'underline', 'forecolor', 'justifyleft', 'justifycenter', 'justifyright', 'justifyfull',
-				   'undo', 'redo', 'insertorderedlist', 'insertunorderedlist', 'outdent', 'indent', 'link', 'signature'];
+				   'undo', 'redo', 'insertorderedlist', 'insertunorderedlist', 'outdent', 'indent', 'link', 'signature', 'image', 'table'];
 
 	for (var i=0; i<buttons.length; i++){
@@ -166,4 +177,8 @@
 		else if (buttons[i] == 'link')
 			img.onclick = function () {RichTextEditor.createLink();};
+		else if (buttons[i] == 'image')
+			img.onclick = function () {RichTextEditor.createImage();};
+		else if (buttons[i] == 'table')
+			img.onclick = function () {RichTextEditor.createTable();};
 		else
 			img.onclick = function () {RichTextEditor.editorCommand(this.id,'');};
@@ -181,6 +196,6 @@
 
 cRichTextEditor.prototype.editorCommand = function(command, option) {
-	var mainField = document.getElementById(this.editor).contentWindow;
 	try {
+		var mainField = document.getElementById(this.editor).contentWindow;
 		mainField.focus();
 		if (command == 'signature'){
@@ -198,8 +213,23 @@
 			}
 		}
-		else
-			mainField.document.execCommand(command, false, option);
+		else if (command == 'CreateLink')
+			mainField.document.execCommand('CreateLink', false, option);
+		else if (command == 'Table'){
+			if (is_ie){
+				var sel = document.selection;
+				if (sel!=null)
+				{
+				    var rng = sel.createRange();
+				    if (rng!=null)
+			        rng.pasteHTML(option);
+				}
+			}
+			else 
+				mainField.document.execCommand('inserthtml', false, option);
+			}
+		else // command == Image
+			mainField.document.execCommand('InsertImage', false, option);
 		//mainField.focus();
-    } catch (e) {}
+    } catch (e) { alert(e.description); }
 }
 
@@ -222,4 +252,172 @@
 		this.editorCommand("CreateLink", szURL);
 	}
+}
+
+// It include the image file in emails body
+// It saves and attach in drafts folder and open it
+cRichTextEditor.prototype.addInputFile = function()
+{
+	var id = this.editor.substr(5); // border_id
+	divFiles = document.getElementById("divFiles_"+id);
+	var countDivFiles = divFiles.childNodes.length + 1;
+
+	var inputFile = document.getElementById('inputFile_img');
+	var divFiles = document.getElementById('divFiles_'+id);
+	inputFile.id = 'inputFile_'+id +"_"+countDivFiles;
+	inputFile.name = 'file_'+countDivFiles;
+	divFile = document.createElement('DIV');
+	divFile.appendChild(inputFile);
+	divFiles.appendChild(divFile);
+
+	var form_upload = document.getElementById('form_upload');
+	form_upload.parentNode.removeChild(form_upload);
+	win.close();
+	
+	if (! validateFileExtension(inputFile.value, inputFile.id , id))
+	return false;
+
+	RichTextEditor.saveFlag = 0; // See if save function finished
+	save_msg(id);
+	setTimeout("RichTextEditor.insertImgHtml("+id+")",1000);
+}
+
+cRichTextEditor.prototype.insertImgHtml = function (id){
+	if (RichTextEditor.saveFlag == 0)
+		setTimeout("RichTextEditor.insertImgHtml("+id+")",500);
+	else
+			this.editorCommand('Image', './inc/show_embedded_attach.php?msg_folder=INBOX/'+draftsfolder+'&msg_num='+newMessageTab.imapUid[id]+'&msg_part='+(newMessageTab.countFile[id]+1));
+			// this.editorCommand('Image', '.inc/gotodownload.php?msg_folder="+msg_folder+"&msg_number="+msg_number+"&idx_file="+idx_file+"&msg_part="+msg_part+params'));
+}
+
+cRichTextEditor.prototype.insertTableHtml = function (){
+	var id = this.editor.substr(5); // border_id
+	var	rows = document.getElementById('rows').selectedIndex;
+	var	cols = document.getElementById('cols').selectedIndex;
+	var insertTable = '<table border="1px"><tbody>';
+	for (var i = 0; i <= rows; i++){
+		insertTable += "<tr>";	
+		for (var j = 0; j <= cols; j++)
+			insertTable += "<td>&nbsp;</td>";	
+		insertTable += "</tr>";
+	}
+	insertTable += "</tbody></table>";
+	this.editorCommand('Table', insertTable);
+}
+
+cRichTextEditor.prototype.createTable = function(){
+	var form = document.getElementById("table_window");
+	if (form == null){
+		form = document.createElement("DIV");
+		form.id  = "table_window";
+		form.style.visibility = "hidden";
+		form.style.position = "absolute";
+		form.style.background = "#eeeeee";
+		form.style.left = "0px";
+		form.style.top  = "0px"; 
+		form.style.width = "0px";
+		form.style.height = "0px";
+		document.body.appendChild(form);
+	}
+		
+		var form_table = document.createElement("DIV");
+		form_table.id = "form_table";
+		form_table.style.position = "absolute";
+		form_table.style.top = "5px";
+		form_table.style.left = "5px";
+		form_table.style.width = "170px";
+		form_table.style.height = "120px";
+		form_table.name = get_lang("Insert Table");
+		form_table.innerHTML = get_lang('Select the table size')+':<br><br>'+
+								get_lang('Rows')+':&nbsp;&nbsp;&nbsp;'+	get_lang('Cols')+':<br>'+
+									'<select name="rows" id="rows"><option value="1">1</option>'+
+									'<option value="2">2</option>'+
+									'<option value="3">3</option>'+
+									'<option value="4">4</option>'+
+									'<option value="5">5</option>'+
+									'<option value="6">6</option>'+
+									'<option value="7">7</option>'+
+									'<option value="8">8</option>'+
+									'<option value="9">9</option></select>&nbsp;&nbsp;&nbsp;'+
+									'<select name="cols" id="cols"><option value="1">1</option>'+
+									'<option value="2">2</option>'+
+									'<option value="3">3</option>'+
+									'<option value="4">4</option>'+
+									'<option value="5">5</option>'+
+									'<option value="6">6</option>'+
+									'<option value="7">7</option>'+
+									'<option value="8">8</option>'+
+									'<option value="9">9</option></select><br><br>'+
+  								'<input title="Close"  value="' + get_lang('Close') + '" type="button" onclick="win.close()">&nbsp;'+
+								'<input title="Include"  value="' + get_lang('Include') + '" type="button" onclick="RichTextEditor.insertTableHtml();win.close();">';
+		form.appendChild(form_table);
+		
+		this.showWindow(form);
+		}
+
+cRichTextEditor.prototype.createImage = function(){
+	var form = document.getElementById("attachment_window");
+	if (form == null){
+		form = document.createElement("DIV");
+		form.id  = "attachment_window";
+		form.style.visibility = "hidden";
+		form.style.position = "absolute";
+		form.style.background = "#eeeeee";
+		form.style.left = "0px";
+		form.style.top  = "0px"; 
+		form.style.width = "0px";
+		form.style.height = "0px";
+		document.body.appendChild(form);
+	}
+		
+		var form_upload = document.createElement("DIV");
+		form_upload.id = "form_upload";
+		form_upload.style.position = "absolute";
+		form_upload.style.top = "5px";
+		form_upload.style.left = "5px";
+		form_upload.name = get_lang("Upload File");
+		form_upload.style.width = "450px";
+		form_upload.style.height = "75px";
+		form_upload.innerHTML = get_lang('Select the desired image file')+':<br>'+
+								'<input name="image_at" maxlength="255" size="50" id="inputFile_img" type="file"><br>' +
+								'<input title="Include"  value="' + get_lang('Include') + '"' + 'type="button" onclick="RichTextEditor.addInputFile();">&nbsp;' +
+								'<input title="Close"  value="' + get_lang('Close') + '"' +
+								' type="button" onclick="win.close()">';
+		form.appendChild(form_upload);
+		
+		this.showWindow(form);
+}
+cRichTextEditor.prototype.showWindow = function (div){
+
+		if(! div) {
+			return;
+		}
+		
+		if(! this.emwindow[div.id]) {
+			div.style.width  =  div.firstChild.style.width;
+			div.style.height = div.firstChild.style.height;
+			div.style.zIndex = "10000";			
+			var title = div.firstChild.name;
+			var wHeight = div.offsetHeight + "px";
+			var wWidth =  div.offsetWidth   + "px";
+			div.style.width = div.offsetWidth - 5;
+
+			win = new dJSWin({
+				id: 'win_'+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 });
+			
+			this.emwindow[div.id] = win;
+			win.draw();
+		}
+		else
+			win = this.emwindow[div.id];
+		win.open();	
 }
 
Index: trunk/expressoMail1_2/js/preferences.js
===================================================================
--- trunk/expressoMail1_2/js/preferences.js	(revision 244)
+++ trunk/expressoMail1_2/js/preferences.js	(revision 271)
@@ -73,4 +73,6 @@
 				"<option value='15'>"+get_lang("Big")+"</option>"+
 				"</select></td></tr>"+
+				"<tr><td> - " + get_lang("Auto save draft") + "?</td>"+
+				"<td><input type='checkBox' id='auto_save_draft' name='auto_save_draft'></td></tr>"+
 				"<tr><td> - " + get_lang("Use shortcuts?") + "</td>"+
 				"<td><input type='checkBox' id='use_shortcuts' name='use_shortcuts'></td></tr>"+
@@ -131,5 +133,6 @@
 			txt_signature.value = preferences.signature;
 		
-		if( preferences.use_shortcuts == 1){Element("use_shortcuts").checked = true;}
+		if( preferences.use_shortcuts == 1) Element("use_shortcuts").checked = true;
+		if( preferences.auto_save_draft == 1) Element("auto_save_draft").checked = true;
 	}
 	
@@ -152,4 +155,6 @@
 			reload_page = true;
 	    else if(preferences.use_shortcuts != Element("use_shortcuts").checked)
+			reload_page = true;
+	    else if(preferences.auto_save_draft != Element("auto_save_draft").checked)
 			reload_page = true;
 				
@@ -166,4 +171,6 @@
 		preferences.signature = Element("txt_signature").value;
 		preferences.use_shortcuts = Element("use_shortcuts").checked ? 1 : 0;
+		preferences.auto_save_draft = Element("auto_save_draft").checked ? 1 : 0;
+		
 		var _this = this;
 		
@@ -217,5 +224,5 @@
 		
 		if(! this.prefeW[div.id]) {
-			div.style.height = is_ie ? "355px" : "365px";
+			div.style.height = is_ie ? "385px" : "370px";
 			div.style.width = "510px";
 			div.style.visibility = "hidden";
Index: trunk/expressoMail1_2/index.php
===================================================================
--- trunk/expressoMail1_2/index.php	(revision 242)
+++ trunk/expressoMail1_2/index.php	(revision 271)
@@ -28,5 +28,5 @@
 		'nonavbar' => False,
 		'currentapp' => 'expressoMail1_2',
-		'update_version'	=> '1.2210',
+		'update_version'	=> '1.2211',
 		'enable_nextmatchs_class' => True
 	);
@@ -66,5 +66,6 @@
     		'line_height' 						=> $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['line_height'] ? $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['line_height'] : "30",
     		'font_size' 						=> $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['font_size'] ? $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['font_size'] : "11",
-    		'use_shortcuts' 					=> $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['use_shortcuts'] ? $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['use_shortcuts'] : "0"
+    		'use_shortcuts' 					=> $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['use_shortcuts'] ? $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['use_shortcuts'] : "0",
+    		'auto_save_draft'					=> $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['auto_save_draft'] ? $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['auto_save_draft'] : "0"
     		
 	);
Index: trunk/expressoMail1_2/templates/default/preferences.tpl
===================================================================
--- trunk/expressoMail1_2/templates/default/preferences.tpl	(revision 197)
+++ trunk/expressoMail1_2/templates/default/preferences.tpl	(revision 271)
@@ -98,4 +98,13 @@
 		</td>
     </tr>
+    
+    <tr bgcolor="{tr_color1}">
+        <td>
+			{lang_auto_save_draft}
+		</td>
+		<td align="center">
+			<input type="checkbox" name="auto_save_draft" value=1 {checked_auto_save_draft}>
+		</td>
+    </tr>
 
     <tr bgcolor="{tr_color2}">
