Index: /trunk/preferences/index.php
===================================================================
--- /trunk/preferences/index.php	(revision 1231)
+++ /trunk/preferences/index.php	(revision 1518)
@@ -23,11 +23,12 @@
 		'pref' => 'index.tpl'
 	);
-
-	//Check preferences that influences the hooks
-	$c = CreateObject('phpgwapi.config','expressoMail1_2');
-    $c->read_repository();
-    $current_config = $c->config_data;
-	$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['enable_expresso_offline'] = $current_config['enable_expresso_offline'];
-
+	//Check preferences that influences the hooks 
+ 	$c = CreateObject('phpgwapi.config','expressoMail1_2'); 
+ 	$c->read_repository(); 
+ 	$current_config = $c->config_data; 
+ 	$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['enable_expresso_offline'] = $current_config['enable_expresso_offline']; 
+	/*print_r($GLOBALS['phpgw_info']['user']['preferences']['expressoMail']);
+	exit;*/
+	
 	$pref_tpl->set_file($templates);
 
@@ -145,4 +146,7 @@
 			if($text == 'Expresso Offline' && 
 				$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['enable_expresso_offline']!='True')
+				continue;
+			if($text == 'Programed Archiving' &&  
+				$GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['use_local_messages']!='1')
 				continue;			
 			section_item($url,lang($text));
Index: /trunk/expressoMail1_2/index.php
===================================================================
--- /trunk/expressoMail1_2/index.php	(revision 1507)
+++ /trunk/expressoMail1_2/index.php	(revision 1518)
@@ -73,5 +73,7 @@
     $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['num_max_certs_to_cipher'] = $GLOBALS['phpgw_info']['server']['num_max_certs_to_cipher'] ?  $GLOBALS['phpgw_info']['server']['num_max_certs_to_cipher'] : "10";
     $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_signature_cripto'] = $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['use_signature_cripto'] ? $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['use_signature_cripto'] : "0";
-$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size'] = $current_config['expressoMail_Max_attachment_size'] ? $current_config['expressoMail_Max_attachment_size']."M" : ini_get('upload_max_filesize'); 
+	$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['keep_after_auto_archiving'] = $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['keep_after_auto_archiving'] ? $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['keep_after_auto_archiving'] : "0";
+
+	$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size'] = $current_config['expressoMail_Max_attachment_size'] ? $current_config['expressoMail_Max_attachment_size']."M" : ini_get('upload_max_filesize'); 
 	$template = CreateObject('phpgwapi.Template',PHPGW_APP_TPL);
 	$template->set_var("txt_loading",lang("Loading"));
@@ -166,4 +168,5 @@
 							"js/messages_proxy.js," .
 							"js/rich_text_editor.js," .
+							"js/mail_sync.js," .
 							"js/wfolders.js,",
 							$GLOBALS['phpgw_info']['flags']['update_version']);
Index: /trunk/expressoMail1_2/templates/default/programed_archiving.tpl
===================================================================
--- /trunk/expressoMail1_2/templates/default/programed_archiving.tpl	(revision 1518)
+++ /trunk/expressoMail1_2/templates/default/programed_archiving.tpl	(revision 1518)
@@ -0,0 +1,63 @@
+<script language="javascript">
+	var account_id = {account_id};
+</script>
+{libs}
+
+<center>
+<form name="formu" method="POST" action="{save_action}" id="form_auto_arch">
+<input type="hidden" name="save" value="save">
+<table width="500" border="0" cellspacing="2" cellpadding="2">
+	<tr bgcolor="{th_bg}">
+		<td colspan="3" align="center"> 
+			{lang_folders_to_sync}
+		</td>
+	</tr>
+	
+	 <tr bgcolor="{tr_color1}">
+		<td width="25%" bgcolor="#DDDDDD">
+			<select id="combo_sync_folders" name="folders_1" style="width: 200px" multiple size="13"></select>
+		</td>
+		
+		<td valign="middle" align="center" bgcolor="#DDDDDD">
+			<button type="button" onClick="javascript:expresso_mail_sync.add_folder(document.getElementById('combo_sync_folders'),document.getElementById('combo_all_folders'));"><img src="templates/default/images/add.png" style="vertical-align: middle;" >&nbsp;{lang_add}</button>
+			<br><br>
+			<button type="button" onClick="javascript:expresso_mail_sync.remove_folder(document.getElementById('combo_sync_folders'));"><img src="templates/default/images/rem.png" style="vertical-align: middle;" >&nbsp;{lang_rem}</button>
+		</td>
+		
+		<td valign="bottom" bgcolor="#DDDDDD">
+			<select id="combo_all_folders" name="folders_2" style="width: 200px" multiple size="13">{all_folders}</select>
+		</td>
+	</tr>
+	<tr>
+		<td>{lang_keep_messages_on_server?}</td>
+		<td>
+		
+		</td>
+	</tr>
+	<tr bgcolor="{tr_color2}" >
+        <td colspan="2">{lang_Would_you_like_to_keep_messages_on_server_?}</td>
+        <td >
+        	<select name="keep_after_auto_archiving" id="remove_after_auto_archiving" >
+				<option {keep_after_auto_archiving_No_selected} value="0">{lang_No}</option>
+				<option {keep_after_auto_archiving_Yes_selected} value="1">{lang_Yes}</option>
+			</select>
+        </td>
+    </tr>
+	 <tr>
+    	<td colspan="3">
+			<table width="100%" border="0" cellspacing="2" cellpadding="2">
+	    		<tr>
+	        		<td align="center" >
+	        			<input type="button" name="install_off" value="{lang_save}" onclick="close_lightbox_div=true;expresso_mail_sync.configure_sync(document.getElementById('combo_sync_folders').options,document.getElementById('form_auto_arch'));">
+	        		</td>
+	        	</tr>
+			</table>
+		</td>
+	</tr>
+	
+</table>
+</form>
+<script language="javascript">
+	expresso_mail_sync.fill_combos_of_folders(document.getElementById('combo_sync_folders'));
+</script>
+</center>
Index: /trunk/expressoMail1_2/programed_archiving.php
===================================================================
--- /trunk/expressoMail1_2/programed_archiving.php	(revision 1518)
+++ /trunk/expressoMail1_2/programed_archiving.php	(revision 1518)
@@ -0,0 +1,121 @@
+<?php
+	/**************************************************************************/
+	ini_set("display_errors","1");
+	$GLOBALS['phpgw_info']['flags'] = array(
+		'currentapp' => 'expressoMail1_2',
+		'noheader'   => True, 
+		'nonavbar'   => True,
+		'enable_nextmatchs_class' => True
+	);
+
+	
+	require_once('../header.inc.php');
+
+	
+	if($_POST["save"]=="save") {
+		if ($GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['keep_after_auto_archiving'])
+			$GLOBALS['phpgw']->preferences->change('expressoMail','keep_after_auto_archiving',$_POST['keep_after_auto_archiving']);
+		else
+			$GLOBALS['phpgw']->preferences->add('expressoMail','keep_after_auto_archiving',$_POST['keep_after_auto_archiving']);
+
+		$GLOBALS['phpgw']->preferences->save_repository();
+		$url = ($GLOBALS['phpgw']->link('/'.'expressoMail1_2'));
+		$GLOBALS['phpgw']->redirect($url);
+	}
+	else {
+		$GLOBALS['phpgw']->preferences->read_repository();
+		if ($GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['keep_after_auto_archiving'])
+			$GLOBALS['phpgw']->template->set_var('keep_after_auto_archiving_Yes_selected','selected');
+		else {
+			$GLOBALS['phpgw']->template->set_var('keep_after_auto_archiving_No_selected','');
+			$GLOBALS['phpgw']->template->set_var('keep_after_auto_archiving_Yes_selected','');
+		}
+		
+		$boemailadmin	= CreateObject('emailadmin.bo');
+		$emailadmin_profile = $boemailadmin->getProfileList();
+		$_SESSION['phpgw_info']['expressomail']['email_server'] = $boemailadmin->getProfile($emailadmin_profile[0]['profileID']);
+		$_SESSION['phpgw_info']['expressomail']['user'] = $GLOBALS['phpgw_info']['user'];
+		$_SESSION['phpgw_info']['expressomail']['server'] = $GLOBALS['phpgw_info']['server'];
+		$_SESSION['phpgw_info']['expressomail']['ldap_server'] = $ldap_manager ? $ldap_manager->srcs[1] : null;
+		$_SESSION['phpgw_info']['expressomail']['user']['email'] = $GLOBALS['phpgw']->preferences->values['email'];
+		
+		$GLOBALS['phpgw']->common->phpgw_header();
+		print parse_navbar();
+	
+		$GLOBALS['phpgw']->template->set_file(array(
+			'expressoMail_prefs' => 'programed_archiving.tpl'
+		));
+		
+		//Checa gears instalado
+		$check_gears = "if (!window.google || !google.gears) {
+					temp = confirm('".lang('To use local messages you have to install google gears. Would you like to be redirected to gears installation page?')."');
+					if (temp) {
+						location.href = \"http://gears.google.com/?action=install&message=\"+
+						\"Para utilizar o recurso de mensagens locais, instale o google gears&return=\" + document.location.href;
+					}
+					else {
+						alert('".lang('Impossible install offline without Google Gears')."');
+						location.href='../preferences/';
+					}
+			}";
+		
+		//Bibliotecas JS.
+		$obj = createobject("expressoMail1_2.functions");
+		$libs =  $obj -> getFilesJs("js/main.js," .
+								"js/gears_init.js," .
+								"js/local_messages.js," .
+								"js/offline_access.js," .
+								"js/mail_sync.js," .
+								"js/md5.js,",
+								$GLOBALS['phpgw_info']['flags']['update_version']);
+		
+		$GLOBALS['phpgw']->template->set_var('libs',$libs);
+		$GLOBALS['phpgw']->template->set_var('lib_modal',"<script src='js/modal/modal.js'>");
+	
+	
+		//combo folders
+		$imap_functions = CreateObject('expressoMail1_2.imap_functions');
+		$all_folders = $imap_functions->get_folders_list();
+		$options = " ";
+		foreach($all_folders as $folder) {
+			if(strpos($folder['folder_id'],'user')===false && is_array($folder)) {
+				$folder_name = (strtoupper($folder['folder_name'])=="INBOX" ||
+								strtoupper($folder['folder_name'])=="SENT" ||
+								strtoupper($folder['folder_name'])=="TRASH" ||
+								strtoupper($folder['folder_name'])=="DRAFTS")?lang($folder['folder_name']):$folder['folder_name'];
+				$options.="<option value='".$folder['folder_id']."'>".$folder_name."</option>";
+			}
+				
+		}
+		$GLOBALS['phpgw']->template->set_var('all_folders',$options);
+	
+	
+	
+		$GLOBALS['phpgw']->template->set_var('lang_Would_you_like_to_keep_messages_on_server_?',lang("Would you like to keep archived messages?"));
+		$GLOBALS['phpgw']->template->set_var('lang_check_redirect',$check_gears);
+		$GLOBALS['phpgw']->template->set_var('lang_folders_to_sync',lang('Folders to sync'));
+		$GLOBALS['phpgw']->template->set_var('lang_add',lang('Add'));
+		$GLOBALS['phpgw']->template->set_var('lang_save',lang('Save'));
+		$GLOBALS['phpgw']->template->set_var('lang_Yes',lang('Yes'));
+		$GLOBALS['phpgw']->template->set_var('lang_No',lang('No'));
+		$GLOBALS['phpgw']->template->set_var('account_id',$GLOBALS['phpgw_info']['user']['account_id']);
+		$GLOBALS['phpgw']->template->set_var('lang_rem',lang('Remove'));
+		$GLOBALS['phpgw']->template->set_var('go_back','../preferences/');
+	
+		$GLOBALS['phpgw']->template->set_var('value_save_in_folder',$o_folders);
+		$GLOBALS['phpgw']->template->set_var('lang_save',lang('Save'));
+		$GLOBALS['phpgw']->template->set_var('lang_cancel',lang('Cancel'));
+		
+		$GLOBALS['phpgw']->template->set_var('save_action',$GLOBALS['phpgw']->link('/'.'expressoMail1_2'.'/programed_archiving.php'));
+		$GLOBALS['phpgw']->template->set_var('th_bg',$GLOBALS['phpgw_info']["theme"][th_bg]);
+	
+		$tr_color = $GLOBALS['phpgw']->nextmatchs->alternate_row_color($tr_color);
+		$GLOBALS['phpgw']->template->set_var('tr_color1',$GLOBALS['phpgw_info']['theme']['row_on']);
+		$GLOBALS['phpgw']->template->set_var('tr_color2',$GLOBALS['phpgw_info']['theme']['row_off']);
+	
+		$GLOBALS['phpgw']->template->parse('out','expressoMail_prefs',True);
+		$GLOBALS['phpgw']->template->p('out');
+	}
+	
+	
+?>
Index: /trunk/expressoMail1_2/inc/hook_preferences.inc.php
===================================================================
--- /trunk/expressoMail1_2/inc/hook_preferences.inc.php	(revision 1121)
+++ /trunk/expressoMail1_2/inc/hook_preferences.inc.php	(revision 1518)
@@ -13,5 +13,6 @@
 	$file = array(
 		'Preferences'     		=> $GLOBALS['phpgw']->link('/preferences/preferences.php','appname='.$appname),
-		'Expresso Offline'			=> $GLOBALS['phpgw']->link('/expressoMail1_2/offline_preferences.php')
+		'Expresso Offline'			=> $GLOBALS['phpgw']->link('/expressoMail1_2/offline_preferences.php'),
+		'Programed Archiving' => $GLOBALS['phpgw']->link('/expressoMail1_2/programed_archiving.php')
 	);
 	//Do not modify below this line
Index: /trunk/expressoMail1_2/inc/class.imap_functions.inc.php
===================================================================
--- /trunk/expressoMail1_2/inc/class.imap_functions.inc.php	(revision 1489)
+++ /trunk/expressoMail1_2/inc/class.imap_functions.inc.php	(revision 1518)
@@ -13,5 +13,6 @@
 		'get_info_msgs'					=> True,
 		'get_folders_list'				=> True,
-		'import_msgs'					=> True
+		'import_msgs'					=> True,
+		'msgs_to_archive'				=> True
 	);
 
@@ -364,4 +365,28 @@
 		return $return;
 
+	}
+	
+	function msgs_to_archive($params) {
+		
+		$folder = $params['folder'];
+		$all_ids = $this-> get_msgs($folder, 'SORTSIZE', false, 0,-1,-1);
+
+		$messages_not_to_copy = explode(",",$params['mails']);
+		$ids = array();
+		
+		foreach($all_ids as $each_id=>$value) {
+			if(!in_array($each_id,$messages_not_to_copy))
+				array_push($ids,$each_id);
+		}
+
+		if (empty($ids))
+			return array();
+
+		$params = array("folder"=>$folder,"msgs_number"=>implode(",",$ids));
+		
+		
+		return $this->get_info_msgs($params);
+		
+		
 	}
 
@@ -2047,5 +2072,9 @@
 			foreach($imapsort as $iuid)
 				$sort[$iuid] = "";
-			$slice_array = true;
+			
+			if ($offsetBegin == -1 && $offsetEnd ==-1 )
+				$slice_array = false;
+			else
+				$slice_array = true;
 		}
 		else
Index: /trunk/expressoMail1_2/inc/class.exporteml.inc.php
===================================================================
--- /trunk/expressoMail1_2/inc/class.exporteml.inc.php	(revision 1377)
+++ /trunk/expressoMail1_2/inc/class.exporteml.inc.php	(revision 1518)
@@ -318,5 +318,9 @@
 			$fileNameReal = $this->remove_accents($attachment['name']);
 			$ContentType = $this->getFileType($fileNameReal);
-			$fileName = $fileNameReal . ".php";
+			$fileName = $fileNameReal;
+			if(strpos($ContentType,"text")!==false ||
+					strpos($ContentType,"image")!==false ||
+					strpos($ContentType,"audio")!==false)
+			 	$fileName.= ".php";
 			$f = fopen($tempDir . '/'.$tempSubDir.'/'.$fileName,"wb");
 			if(!$f)
@@ -326,18 +330,33 @@
 			$urlPath = 'tmpLclAtt/'.$tempSubDir.'/'.$fileName;
 			
-			$headers = "<?php header('Content-Type: ".$ContentType."');
-				header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
-				header('Pragma: public');
-				header('Expires: 0'); // set expiration time
-	 	 		header('Content-Disposition: attachment; filename=\"". addslashes($fileNameReal) ."\"');\n echo ";
-			
-			if($attachment['encoding'] == 'base64') {
-				$headers.=" imap_base64('".$fileContent."');?>";
-			}
-			else if($attachment['encoding'] == 'quoted_printable_decode') {
-				$headers.=" quoted_printable_decode('".$fileContent."');?>";
+			if(strpos($ContentType,"text")!==false ||
+					strpos($ContentType,"image")!==false ||
+					strpos($ContentType,"audio")!==false) {
+				$headers = "<?php header('Content-Type: ".$ContentType."');
+					header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
+					header('Pragma: public');
+					header('Expires: 0'); // set expiration time
+		 	 		header('Content-Disposition: attachment; filename=\"". addslashes($fileNameReal) ."\"');\n echo ";
+			
+				if($attachment['encoding'] == 'base64') {
+					$headers.="imap_base64('".$fileContent."');?>";
+				}
+				else if($attachment['encoding'] == 'quoted_printable_decode') {
+					$headers.="quoted_printable_decode('".$fileContent."');?>";
+				}
+				else {
+					$headers.="'".$fileContent."';?>";
+				}
 			}
 			else {
-				$headers.=" '".$fileContent."';?>";
+				if($attachment['encoding'] == 'base64') {
+					$headers=imap_base64($fileContent);
+				}
+				else if($attachment['encoding'] == 'quoted_printable_decode') {
+					$headers=quoted_printable_decode($fileContent);
+				}
+				else {
+					$headers=$fileContent;
+				}
 			}
 			
@@ -366,4 +385,6 @@
 	   	if ($strFileType == ".gif")
 	   		$ContentType = "image/gif";
+		if ($strFileType == ".png")
+	   		$ContentType = "image/png";
 	   	if ($strFileType == ".jpg" || $strFileType == "jpeg")
 	   		$ContentType = "image/jpeg";
Index: /trunk/expressoMail1_2/js/common_functions.js
===================================================================
--- /trunk/expressoMail1_2/js/common_functions.js	(revision 1503)
+++ /trunk/expressoMail1_2/js/common_functions.js	(revision 1518)
@@ -73,9 +73,15 @@
 
 function unloadMess(){
-	var mess = get_lang("Your message has not been sent and will be discarted.");
-	for(var i = 0; i < BordersArray.length;i++) {
-		var body = Element('body_'+BordersArray[i].sequence);
-		if (body && body.contentWindow && body.contentWindow.document.designMode.toLowerCase() == 'on')	{
-			return mess;
+	if (expresso_mail_sync.folders.length != 0) {
+		var mess = get_lang("You're about archiving your e-mails from server. Do you really want to stop this action?");
+		return mess;
+	}
+	else {
+		var mess = get_lang("Your message has not been sent and will be discarted.");
+		for (var i = 0; i < BordersArray.length; i++) {
+			var body = Element('body_' + BordersArray[i].sequence);
+			if (body && body.contentWindow && body.contentWindow.document.designMode.toLowerCase() == 'on') {
+				return mess;
+			}
 		}
 	}
Index: /trunk/expressoMail1_2/js/main.js
===================================================================
--- /trunk/expressoMail1_2/js/main.js	(revision 1443)
+++ /trunk/expressoMail1_2/js/main.js	(revision 1518)
@@ -24,4 +24,15 @@
 		ConstructMenuTools();
 
+		if ((preferences.use_local_messages==1) && (!window.google || !google.gears)) {
+			temp = confirm(get_lang("To use local messages you have to install google gears. Would you like to be redirected to gears installation page?"));
+			if (temp) {
+				location.href = "http://gears.google.com/?action=install&message="+
+				"Para utilizar o recurso de mensagens locais, instale o google gears&return=" + document.location.href;
+			}
+			else {
+				preferences.use_local_messages=0;
+			}
+		}
+
         // Insere a applet de criptografia
         if (preferences.use_signature_digital_cripto == '1'){
@@ -51,7 +62,10 @@
 	cExecute ("$this.functions.get_preferences", save_preferences);
 	setTimeout('auto_refresh()', time_refresh);
-	if(window.google && google.gears)
-		if(expresso_local_messages.is_offline_installed())
+	if (window.google && google.gears) {
+		setTimeout('auto_archiving()', 30000);
+		if (expresso_local_messages.is_offline_installed()) {
 			check_mail_in_queue();
+		}
+	}
 }
 
@@ -357,4 +371,9 @@
 	refresh(preferences.alert_new_msg);
 	setTimeout('auto_refresh()', time_refresh);
+}
+
+function auto_archiving() {
+	expresso_mail_sync.start_sync();
+	setTimeout('auto_archiving()',600000);
 }
 
Index: /trunk/expressoMail1_2/js/mail_sync.js
===================================================================
--- /trunk/expressoMail1_2/js/mail_sync.js	(revision 1518)
+++ /trunk/expressoMail1_2/js/mail_sync.js	(revision 1518)
@@ -0,0 +1,366 @@
+/**
+ * @author diogenes
+ */
+	function mail_sync() {
+		this.dbGears = null;
+		this.localServer = null;
+		this.store = null;
+		this.folders = new Array();
+		this.messages = null;
+		this.attachs = null;
+		this.url_attachs = null;
+		this.main_title = null;
+	}
+	
+	mail_sync.prototype.open_conn = function(){
+		var db_in_other_use = true;
+		while (db_in_other_use) {
+			try {
+				this.dbGears.open('database-test');
+				db_in_other_use = false;
+			} 
+			catch (ex) {
+				db_in_other_use=true;
+			}
+		}
+	}
+	
+	mail_sync.prototype.start_sync = function() {
+		if(this.folders.length!=0) {
+			//Já está sincronizando...
+			return;
+		}
+		this.main_title = document.getElementById('main_title').innerHTML;
+		this.dbGears = google.gears.factory.create('beta.database');
+		this.localServer = google.gears.factory.create('beta.localserver');
+		this.store = this.localServer.createStore('test-store');	
+		this.messages = null;
+		this.attachs = null;
+		this.url_attachs = null;
+		
+		this.open_conn();
+
+		var rs = this.dbGears.execute("select id_folder,folder_name from folders_sync where uid_usuario=?",[account_id]);
+		document.getElementById('main_title').innerHTML = get_lang("Creating folders structure");
+		while(rs.isValidRow()) {
+			var temp = new Array();
+			temp[0] = rs.field(0);
+			temp[1] = rs.field(1);
+			temp[2] = null;
+			var rs2 = this.dbGears.execute("select mail.original_id from mail inner join folder on mail.id_folder=folder.rowid where folder.folder = ? and mail.uid_usuario=?",[temp[1]==get_lang('Inbox')?'Inbox':temp[1],account_id]);
+			while(rs2.isValidRow()) {
+				if(temp[2]==null)
+					temp[2]=rs2.field(0)+",";
+				else
+					temp[2]+=rs2.field(0)+",";
+				rs2.next();
+			}
+			this.folders.push(temp);
+			
+			
+			//Criando estrutura de pastas...
+			var folders_to_check = temp[0].split("/");//Todas as pastas tem ao menos INBOX/
+			if (folders_to_check.length == 1) 
+				var actual_check = "Inbox";
+			else {
+				folders_to_check = folders_to_check.slice(1);
+				var actual_check = folders_to_check[0];
+			}
+			for (var i in folders_to_check) {
+
+				var rs2 = this.dbGears.execute("select rowid from folder where folder=? and uid_usuario=?", [actual_check, account_id]);
+				
+				if (!rs2.isValidRow()) {
+					this.dbGears.execute("insert into folder (folder,uid_usuario) values (?,?)", [actual_check, account_id]);
+					ttreeBox.update_folder();
+				}
+				if(i+1<folders_to_check.length)
+					actual_check += "/"+folders_to_check[parseInt(i)+1];
+			}
+
+			rs.next();
+		}
+		this.dbGears.close();
+		this.syncronize_folders();
+	}
+	
+	mail_sync.prototype.syncronize_folders = function() {
+		if (this.folders.length == 0) {
+			document.getElementById('main_title').innerHTML = get_lang("Deleting downloadeds msgs...");
+			expresso_mail_sync.remove_archived_mails();
+			return;
+		}
+		var folder_to_sync = this.folders.pop();
+		folder_to_sync[1] = folder_to_sync[0].toUpperCase()=="INBOX"?"Inbox":folder_to_sync[1];
+		
+		var start_sync_mails = function(data) {
+			expresso_mail_sync.messages=data;
+			document.getElementById('main_title').innerHTML = get_lang("Auto archiving")+" "+lang_folder(folder_to_sync[1])+": 0 / "+data.length;
+
+			expresso_mail_sync.syncronize_mails(folder_to_sync[1]);
+		}
+		document.getElementById('main_title').innerHTML = get_lang("Starting to sync folder ")+lang_folder(folder_to_sync[1]);
+		cExecute("$this.imap_functions.msgs_to_archive&folder=" + folder_to_sync[0]+"&mails="+folder_to_sync[2] , start_sync_mails);
+	}
+	
+	mail_sync.prototype.syncronize_mails = function(folder_dest) {
+		if (expresso_mail_sync.messages == null || expresso_mail_sync.messages.length == 0) {
+			expresso_mail_sync.syncronize_folders();
+			return;
+		}
+		
+		msg_to_sync = expresso_mail_sync.messages.pop();
+		
+		//refresh loading
+		var value_to_change = document.getElementById('main_title').innerHTML.match(/\d+ \//);
+		value_to_change += "";
+		var new_value = value_to_change.replace(" /","");
+		new_value = parseInt(new_value) + 1;
+		document.getElementById('main_title').innerHTML = document.getElementById('main_title').innerHTML.replace(value_to_change,new_value+" /");
+		
+		msg_to_sync = connector.unserialize(msg_to_sync);
+		var source_msg = new Array();
+		source_msg['url'] = msg_to_sync.url_export_file;
+		
+		if (typeof(msg_to_sync['array_attach'])=='object'&&(msg_to_sync['array_attach'] instanceof Array))
+			expresso_mail_sync.attachs = msg_to_sync['array_attach'].slice();
+		else
+			expresso_mail_sync.attachs = new Array();
+		expresso_mail_sync.attachs.push(source_msg);
+		expresso_mail_sync.download_attachs(msg_to_sync,folder_dest);
+	}
+	
+	mail_sync.prototype.download_attachs = function(msg,folder_dest) {
+		if (expresso_mail_sync.attachs == null || expresso_mail_sync.attachs.length == 0) {
+			expresso_mail_sync.insert_mail(msg, folder_dest);
+			return;
+		}
+		
+		attach_to_capt = expresso_mail_sync.attachs.pop();
+		
+		var call_back = function(url,success,captureId) {
+			//TODO: Tratar se houver erro ao baixar anexo...
+			expresso_mail_sync.download_attachs(msg,folder_dest);
+		}
+		expresso_mail_sync.store.capture(attach_to_capt['url'],call_back);
+	}
+	
+	mail_sync.prototype.insert_mail = function(msg,folder) {
+		
+		try {
+		//	document.getElementById('div_menu_c3').innerHTML = document.getElementById('div_menu_c3').innerHTML.replace(/(\d+) de/,(((int)"$1")+1)+" de");
+//			document.getElementById('div_menu_c3').innerHTML += expresso_mail_sync.messages.length + "restantes";
+			
+			expresso_mail_sync.open_conn();
+			
+			var msg_info = msg;
+			var msg_header = msg['header'];
+			var anexos = msg['array_attach'];
+			
+			
+			var unseen = 0;
+			var login = msg_info.login;
+			var original_id = msg_info.msg_number;
+			var original_folder = msg_info.msg_folder;
+			
+			//Os campos abaixo precisam estar isolados para busca de mensagens em cima deles.
+			var from = connector.serialize(msg_info.from);
+			var subject = msg_info.subject;
+			var body = msg_info.body;
+			var to = connector.serialize(msg_info.toaddress2);
+			var cc = connector.serialize(msg_info.cc);
+			var size = msg_header.Size;
+	
+			//Zero os campos que foram isolados para não ter informações duplicadas
+			msg_info.from = null;
+			msg_info.subject = null;
+			msg_info.body = null;
+			msg_info.to = null;
+			msg_info.cc = null;
+			msg_header.Size=null;
+			
+			//A data no header pode vir como horário ao invés de data, caso o usuário tenha arquivado no mesmo
+			//dia que recebeu a msg. Para esses casos, usar a data aux que vem com o dia.
+			if(msg_header.udate.indexOf(":")!=-1) {
+				msg_header.udate = msg_header.aux_date;
+			}
+			
+			/**
+			 * The importance attribute can be empty, and javascript consider as null causing nullpointer.
+			 */
+			if((msg_header.Importance == null) ||  (msg_header.Importance == ""))
+				msg_header.Importance = "Normal";
+			
+			msg_header.aux_date = null; //esse dado não é mais preciso no email.
+			
+			var mail = connector.serialize(msg_info);
+			var header = connector.serialize(msg_header);
+	
+			var timestamp = msg_info.timestamp;
+			var id_folder;
+			
+			var rs = this.dbGears.execute("select rowid from folder where folder=? and uid_usuario=?", [folder, account_id]);
+			id_folder = rs.field(0);
+	
+			
+			if(msg_info.Unseen=="U")
+				unseen = 1;
+			this.dbGears.execute("insert into mail (mail,original_id,original_folder,header,timestamp,uid_usuario,unseen,id_folder,ffrom,subject,fto,cc,body,size) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[mail,original_id,original_folder,header,timestamp,login,unseen,id_folder,from,subject,to,cc,body,size]);
+			
+			//Preenche os anexos.
+			var id_mail = this.dbGears.lastInsertRowId;
+
+			for (var i = 0; i < anexos.length; i++) {
+				this.dbGears.execute("insert into anexo (id_mail,nome_anexo,url,pid) values (?,?,?,?)", [id_mail, anexos[i]['name'],anexos[i]['url'],anexos[i]['pid']]);
+			}
+			
+			if(preferences.keep_after_auto_archiving!=1)
+				this.dbGears.execute("insert into msgs_to_remove (id_msg,folder,uid_usuario) values (?,?,?)",[original_id,original_folder,account_id]);
+			
+			
+		} catch (error) {
+			//TODO: O que fazer se der erro ao baixar um email?
+		}
+		this.dbGears.close();
+		this.syncronize_mails(folder);
+	}
+	
+	mail_sync.prototype.remove_archived_mails = function() {
+		
+		expresso_mail_sync.open_conn();
+
+		var rs = this.dbGears.execute("select distinct(folder) from msgs_to_remove where uid_usuario=?",[account_id]);
+		if(rs.isValidRow()) {
+			var folder_to_remove_msgs = rs.field(0);
+			var rs2 = this.dbGears.execute("select id_msg from msgs_to_remove where folder=? and uid_usuario=?",[folder_to_remove_msgs,account_id]);
+			
+			var msgs = null;
+			while(rs2.isValidRow()) {
+				if(msgs==null)
+					msgs = rs2.field(0);
+				else
+					msgs += ","+rs2.field(0);
+				rs2.next();
+			}
+			
+			
+			var handler_delete_msgs = function(data){
+				if (current_folder == data.folder) {
+					mail_msg = Element("tbody_box");
+					var msg_to_delete;
+					for (var i = 0; i < data.msgs_number.length; i++) {
+						msg_to_delete = Element(data.msgs_number[i]);
+						if (msg_to_delete) {
+							mail_msg.removeChild(msg_to_delete);
+						}
+					}
+					Element('tot_m').innerHTML = parseInt(Element('tot_m').innerHTML) - data.msgs_number.length;
+				}
+				refresh();
+				expresso_mail_sync.remove_archived_mails();
+			}
+			
+			cExecute ("$this.imap_functions.delete_msgs&folder="+folder_to_remove_msgs+"&msgs_number="+msgs, handler_delete_msgs);
+			this.dbGears.execute("delete from msgs_to_remove where folder=? and uid_usuario=?",[folder_to_remove_msgs,account_id]);
+			this.dbGears.close();
+			
+		}
+		else {
+			this.dbGears.close();
+			document.getElementById('main_title').innerHTML = get_lang("End of auto download messages");
+			window.setTimeout("eval('document.getElementById(\"main_title\").innerHTML =expresso_mail_sync.main_title')",3000);
+		}
+		
+	}
+	
+	mail_sync.prototype.configure_sync = function(folders,formul) {
+		this.dbGears = google.gears.factory.create('beta.database');
+		this.localServer = google.gears.factory.create('beta.localserver');
+		this.store = this.localServer.createStore('test-store');	
+		this.dbGears.open('database-test');
+		this.dbGears.execute("delete from folders_sync where uid_usuario=?",[account_id]);
+		for (var i=0;i<folders.length;i++) {
+			var pos = folders[i].value.indexOf("/");
+			if(pos=="-1")
+				var folder_name = folders[i].text;
+			else
+				var folder_name = folders[i].value.substr(pos+1);
+			this.dbGears.execute("insert into folders_sync (id_folder,folder_name,uid_usuario) values (?,?,?)",[folders[i].value,folder_name,account_id]);
+		}
+		this.dbGears.close();
+		formul.submit();
+	}
+	
+	mail_sync.prototype.fill_combos_of_folders = function(combo_sync) {
+		var folders = expresso_local_messages.get_folders_to_sync();
+
+		for(var i=0;i<folders.length;i++) {
+			var option = document.createElement('option');
+			option.value = folders[i][0];
+			if (folders[i][1].indexOf("/") != "-1") {
+				final_pos = folders[i][1].lastIndexOf("/");
+				option.text =folders[i][1].substr(final_pos+1);
+			}
+			else
+				option.text = folders[i][1];
+			try {
+				combo_sync.add(option,null);
+			}catch (ex) {// I.E
+				combo_sync.add(option);
+			}
+
+		}
+	}
+	
+	mail_sync.prototype.add_folder = function (select_sync_folders,select_available_folders)
+	{
+		var count_available_folders = select_available_folders.length;
+		var count_sync_folders = select_sync_folders.options.length;
+		var new_options = '';
+		
+		for (i = 0 ; i < count_available_folders ; i++)
+		{
+			if (select_available_folders.options[i].selected)
+			{
+				if(document.all)
+				{
+					if ( (select_sync_folders.innerHTML.indexOf('value='+select_available_folders.options[i].value)) == '-1' )
+					{
+						new_options +=  '<option value='
+									+ select_available_folders.options[i].value
+									+ '>'
+									+ select_available_folders.options[i].text
+									+ '</option>';
+					}
+				}
+				else
+				{
+					if ( (select_sync_folders.innerHTML.indexOf('value="'+select_available_folders.options[i].value+'"')) == '-1' )
+					{
+						new_options +=  '<option value='
+									+ select_available_folders.options[i].value
+									+ '>'
+									+ select_available_folders.options[i].text
+									+ '</option>';
+					}
+				}
+			}
+		}
+	
+		if (new_options != '')
+		{
+			select_sync_folders.innerHTML = '&nbsp;' + new_options + select_sync_folders.innerHTML;
+			select_sync_folders.outerHTML = select_sync_folders.outerHTML;
+		}
+	}
+	
+	mail_sync.prototype.remove_folder = function(select_sync_folders)
+	{
+		for(var i = 0;i < select_sync_folders.options.length; i++)
+			if(select_sync_folders.options[i].selected)
+				select_sync_folders.options[i--] = null;
+	}
+	
+	var expresso_mail_sync;
+	expresso_mail_sync = new mail_sync();
+	
Index: /trunk/expressoMail1_2/js/local_messages.js
===================================================================
--- /trunk/expressoMail1_2/js/local_messages.js	(revision 1477)
+++ /trunk/expressoMail1_2/js/local_messages.js	(revision 1518)
@@ -31,5 +31,28 @@
 		if(this.store==null)
 			this.store = this.localServer.createStore('test-store');			
-		this.dbGears.open('database-test');
+		
+		var db_in_other_use = true;
+		while (db_in_other_use) {
+			try {
+				this.dbGears.open('database-test');
+				db_in_other_use = false;
+			} 
+			catch (ex) {
+				db_in_other_use=true;
+			}
+		}
+		
+		/*var db_is_opened = true;
+		while (db_is_opened) {
+			try {
+				this.dbGears.open('database-test');
+				db_is_opened = true;
+			} 
+			catch (ex) {
+				db_is_opened=false;
+			}
+		}*/
+		
+//		this.dbGears.open('database-test');
 		this.dbGears.execute('create table if not exists folder (folder text,uid_usuario int,unique(folder,uid_usuario))');
 		this.dbGears.execute('create table if not exists mail' +
@@ -38,4 +61,7 @@
 		this.dbGears.execute('create table if not exists anexo' +
 		' (id_mail int,nome_anexo text,url text,pid int)');
+		this.dbGears.execute('create table if not exists folders_sync' +
+		' (id_folder text,folder_name text,uid_usuario int)');
+		this.dbGears.execute('create table if not exists msgs_to_remove (id_msg int,folder text,uid_usuario int)');
 
 		//some people that used old version of local messages could not have the size column. If it's the first version
@@ -908,4 +934,19 @@
 	}
 	
+	local_messages.prototype.get_folders_to_sync = function() {
+		this.init_local_messages();
+		var rs = this.dbGears.execute("select id_folder,folder_name from folders_sync where uid_usuario="+account_id);
+		var retorno = new Array();
+		while(rs.isValidRow()) {
+			temp = new Array();
+			temp[0] = rs.field(0);
+			temp[1] = rs.field(1);
+			retorno.push(temp);
+			rs.next();
+		}
+		this.finalize();
+		return retorno;
+	}
+	
 	local_messages.prototype.install_offline = function(urlOffline,urlIcone,uid_usuario,login,pass,redirect) {
 		if (!window.google || !google.gears) {
Index: /trunk/expressoMail1_2/js/globals.js
===================================================================
--- /trunk/expressoMail1_2/js/globals.js	(revision 1507)
+++ /trunk/expressoMail1_2/js/globals.js	(revision 1518)
@@ -38,5 +38,5 @@
 	'<tr>'+
 	'<td style="padding-left:17px" width=33% id="content_quota" align=left></td>'+
-	'<td class="divAppboxHeader" width=33%>Expresso Mail</td>'+
+	'<td class="divAppboxHeader" width=33% id="main_title">Expresso Mail</td>'+
 	'<td width=33% id="div_menu_c3" align=right></td>'+
 	'</tr></table>';
Index: /trunk/expressoMail1_2/js/draw_api.js
===================================================================
--- /trunk/expressoMail1_2/js/draw_api.js	(revision 1495)
+++ /trunk/expressoMail1_2/js/draw_api.js	(revision 1518)
@@ -179,35 +179,50 @@
 			}
 			else{
-				if (expresso_offline) 
-					tree_folders = new dFTree({name: 'tree_folders'});
-				var root_local = new dNode({
-					id: "local_root",
-					caption: get_lang('local folders')
-				});
-				tree_folders.add(root_local, "root"); //coloca root local
-				var local_folders = expresso_local_messages.list_local_folders();
-				for (var i in local_folders) { //Coloca as pastas locais.
-					var node_root = "local_root";
-					var new_caption = local_folders[i][0];
-					if(local_folders[i][0].indexOf("/")!="-1") {
-						final_pos = local_folders[i][0].lastIndexOf("/");
-						node_root = "local_"+local_folders[i][0].substr(0,final_pos);
-						new_caption = local_folders[i][0].substr(final_pos+1);
+				if (!window.google || !google.gears) {
+					temp = confirm(get_lang("To use local messages you have to install google gears. Would you like to be redirected to gears installation page?"));
+					if (temp) {
+						location.href = "http://gears.google.com/?action=install&message=" +
+						"Para utilizar o recurso de mensagens locais, instale o google gears&return=" +
+						document.location.href;
 					}
-					if (local_folders[i][1] > 0) 
-						var nodeLocal = new dNode({
-							id: "local_" + local_folders[i][0],
-							caption: lang_folder(new_caption) + '<font style=color:red>&nbsp(</font><span id="local_unseen" style=color:red>' + local_folders[i][1] + '</span><font style=color:red>)</font>',
-							onClick: "change_folder('local_" + local_folders[i][0] + "','" + new_caption + "')",
-							plusSign: local_folders[i][2]
+					else {
+						preferences.use_local_messages = 0;
+					}
+				}
+				else {
+					if (expresso_offline) 
+						tree_folders = new dFTree({
+							name: 'tree_folders'
 						});
-					else 
-						var nodeLocal = new dNode({
-							id: "local_" + local_folders[i][0],
-							caption: lang_folder(new_caption),
-							onClick: "change_folder('local_" + local_folders[i][0] + "','" + new_caption + "')",
-							plusSign: local_folders[i][2]
-						});
-					tree_folders.add(nodeLocal, node_root);
+					var root_local = new dNode({
+						id: "local_root",
+						caption: get_lang('local folders')
+					});
+					tree_folders.add(root_local, "root"); //coloca root local
+					var local_folders = expresso_local_messages.list_local_folders();
+					for (var i in local_folders) { //Coloca as pastas locais.
+						var node_root = "local_root";
+						var new_caption = local_folders[i][0];
+						if (local_folders[i][0].indexOf("/") != "-1") {
+							final_pos = local_folders[i][0].lastIndexOf("/");
+							node_root = "local_" + local_folders[i][0].substr(0, final_pos);
+							new_caption = local_folders[i][0].substr(final_pos + 1);
+						}
+						if (local_folders[i][1] > 0) 
+							var nodeLocal = new dNode({
+								id: "local_" + local_folders[i][0],
+								caption: lang_folder(new_caption) + '<font style=color:red>&nbsp(</font><span id="local_unseen" style=color:red>' + local_folders[i][1] + '</span><font style=color:red>)</font>',
+								onClick: "change_folder('local_" + local_folders[i][0] + "','" + new_caption + "')",
+								plusSign: local_folders[i][2]
+							});
+						else 
+							var nodeLocal = new dNode({
+								id: "local_" + local_folders[i][0],
+								caption: lang_folder(new_caption),
+								onClick: "change_folder('local_" + local_folders[i][0] + "','" + new_caption + "')",
+								plusSign: local_folders[i][2]
+							});
+						tree_folders.add(nodeLocal, node_root);
+					}
 				}
 			}
