Index: /trunk/expressoMail1_2/programed_archiving.php
===================================================================
--- /trunk/expressoMail1_2/programed_archiving.php	(revision 1518)
+++ /trunk/expressoMail1_2/programed_archiving.php	(revision 1595)
@@ -9,5 +9,5 @@
 	);
 
-	
+
 	require_once('../header.inc.php');
 
@@ -89,6 +89,6 @@
 		}
 		$GLOBALS['phpgw']->template->set_var('all_folders',$options);
-	
-	
+		echo '<script language="javascript">var array_lang = new Array();</script>';
+		include("inc/load_lang.php");	
 	
 		$GLOBALS['phpgw']->template->set_var('lang_Would_you_like_to_keep_messages_on_server_?',lang("Would you like to keep archived messages?"));
Index: /trunk/expressoMail1_2/inc/class.exporteml.inc.php
===================================================================
--- /trunk/expressoMail1_2/inc/class.exporteml.inc.php	(revision 1558)
+++ /trunk/expressoMail1_2/inc/class.exporteml.inc.php	(revision 1595)
@@ -277,5 +277,7 @@
 		$body		= $this-> getBody($id_msg);
 		
-		$file = "source_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].".php";
+		$tempSubDir = md5($_SESSION[ 'phpgw_session' ][ 'session_id' ].microtime());
+		$file = "source_".$tempSubDir.".php";
+		//$file = "source_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].".php";
 		$f = fopen($tempDir.'/'.$file,"w");
 		fputs($f,$phpheader.$header ."\r\n\r\n". $body);
Index: /trunk/expressoMail1_2/js/common_functions.js
===================================================================
--- /trunk/expressoMail1_2/js/common_functions.js	(revision 1526)
+++ /trunk/expressoMail1_2/js/common_functions.js	(revision 1595)
@@ -73,5 +73,5 @@
 
 function unloadMess(){
-	if (expresso_mail_sync.folders.length != 0) {
+	if (expresso_mail_sync.working) {
 		var mess = get_lang("You're about archiving your e-mails from server. Do you really want to stop this action?");
 		return mess;
Index: /trunk/expressoMail1_2/js/main.js
===================================================================
--- /trunk/expressoMail1_2/js/main.js	(revision 1531)
+++ /trunk/expressoMail1_2/js/main.js	(revision 1595)
@@ -767,5 +767,17 @@
 		return;
 	}
-	var has_local_messages_before = expresso_local_messages.has_local_mails(); //vejo se já tinha mensagens locais
+
+	if(!id_msgs)
+		id_msgs = get_selected_messages();
+	
+	if(folder_dest=='local_root' || folder_dest==null) //Caso seja o primeiro arquivamento...
+		folder_dest = 'local_Inbox';
+	
+	if (parseInt(id_msgs) > 0 || id_msgs.length > 0)
+		expresso_mail_sync.archive_msgs(folder,folder_dest,id_msgs); 
+		//cExecute("$this.imap_functions.get_info_msgs&folder=" + folder + "&msgs_number=" + id_msgs , handler_arquivar_mensagens);
+	else 
+		write_msg(get_lang('No selected message.'));
+	/*var has_local_messages_before = expresso_local_messages.has_local_mails(); //vejo se já tinha mensagens locais
 	var handler_arquivar_mensagens = function(data) {
 		var sucess = true;
@@ -819,5 +831,5 @@
 		cExecute("$this.imap_functions.get_info_msgs&folder=" + folder + "&msgs_number=" + id_msgs , handler_arquivar_mensagens);
 	else 
-		write_msg(get_lang('No selected message.'));
+		write_msg(get_lang('No selected message.'));*/
 	
 }
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 1595)
@@ -2,17 +2,34 @@
  * @author diogenes
  */
+
+	/**
+	 *  @param folders:
+	 * 		1 - rowid of folder in sqlite
+	 * 		2 - folder name in sqlite
+	 * 		3 - ids to not download(for auto archiving) or ids to download(for archiving)
+	 * 		4 - true for auto archiving and false for normal archiving.
+	 */
 	function mail_sync() {
-		this.dbGears = null;
-		this.localServer = null;
-		this.store = null;
+//		this.dbGears = null;
+//		this.localServer = null;
+//		this.store = null;
 		this.folders = new Array();
 		this.messages = null;
 		this.attachs = null;
 		this.url_attachs = null;
+		this.working = false;
+		this.is_auto = null;
+		this.errors = new Array();
+//		this.main_title = null;
+		
 		this.main_title = null;
+		this.dbGears = google.gears.factory.create('beta.database');
+		this.localServer = google.gears.factory.create('beta.localserver');
+		this.store = this.localServer.createStore('test-store');
 	}
 	
 	mail_sync.prototype.open_conn = function(){
 		var db_in_other_use = true;
+		var start_trying = new Date().getTime();
 		while (db_in_other_use) {
 			try {
@@ -21,5 +38,7 @@
 			} 
 			catch (ex) {
-				db_in_other_use=true;
+				if(new Date.getTime()-start_trying>10000) { //too much time trying, throw an exception
+					throw ex;
+				}
 			}
 		}
@@ -27,12 +46,13 @@
 	
 	mail_sync.prototype.start_sync = function() {
-		if(this.folders.length!=0) {
+		if(this.working) {
 			//Já está sincronizando...
 			return;
 		}
-		this.main_title = document.getElementById('main_title').innerHTML;
-		this.dbGears = google.gears.factory.create('beta.database');
+		//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.store = this.localServer.createStore('test-store');	*/
+		this.working=true;
 		this.messages = null;
 		this.attachs = null;
@@ -48,4 +68,5 @@
 			temp[1] = rs.field(1);
 			temp[2] = null;
+			temp[3] = false;
 			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()) {
@@ -85,21 +106,72 @@
 	}
 	
+	mail_sync.prototype.archive_msgs = function(folder,folder_dest,ids) {
+		//this.main_title = document.getElementById('main_title').innerHTML;
+		var temp = new Array();
+		temp[0] = folder;
+		temp[1] = folder_dest.substr(6);
+		temp[2] = ids;
+		temp[3] = true;
+		this.folders.push(temp);
+		Element('chk_box_select_all_messages').checked = false;
+		
+		array_ids = ids.split(",");
+		for (var i in array_ids) {
+			if (Element("check_box_message_" + array_ids[i])) 
+				Element("check_box_message_" + array_ids[i]).checked = false;
+			remove_className(Element(array_ids[i]), 'selected_msg');
+		}
+		if(!this.working) {
+			this.working=true;
+			this.syncronize_folders();
+		}
+		else {
+			write_msg(get_lang("An archiving is in process, but dont worry, expresso will process this messages after the actual archiving"));
+		}
+	}
+	
 	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();
+			this.working=false;
+			update_menu();
 			return;
 		}
 		var folder_to_sync = this.folders.pop();
-		folder_to_sync[1] = folder_to_sync[0].toUpperCase()=="INBOX"?"Inbox":folder_to_sync[1];
+		folder_to_sync[1] = folder_to_sync[0].toUpperCase()=="INBOX" && !folder_to_sync[3]?"Inbox":folder_to_sync[1];
+		
+		if(folder_to_sync[3]) { //Em caso de arquivamento normal, pode ser que a pasta inbox ainda não tenha sido criada.
+			expresso_mail_sync.open_conn()
+			if(!expresso_mail_sync.has_local_mails()) {
+				expresso_mail_sync.dbGears.execute("insert into folder (folder,uid_usuario) values (?,?)",["Inbox",account_id]);
+			}
+			expresso_mail_sync.dbGears.close();
+			ttreeBox.update_folder();
+			
+		}
 		
 		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;
+			if(expresso_mail_sync.is_auto)
+				document.getElementById('main_title').innerHTML = get_lang("Auto archiving")+" "+lang_folder(folder_to_sync[1])+": 0 / "+data.length;
+			else
+				document.getElementById('main_title').innerHTML = get_lang("Archiving messages on folder")+" "+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);
+		
+
+		if (folder_to_sync[3]) {
+			document.getElementById('main_title').innerHTML = get_lang("Starting to archive messages");
+			cExecute("$this.imap_functions.get_info_msgs&folder=" + folder_to_sync[0] + "&msgs_number=" + folder_to_sync[2], start_sync_mails);
+			this.is_auto = false;
+		}
+		else {
+			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);
+			this.is_auto = true;
+		}
+			
 	}
 	
@@ -118,9 +190,9 @@
 		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();
@@ -134,4 +206,5 @@
 		if (expresso_mail_sync.attachs == null || expresso_mail_sync.attachs.length == 0) {
 			expresso_mail_sync.insert_mail(msg, folder_dest);
+			
 			return;
 		}
@@ -140,6 +213,28 @@
 		
 		var call_back = function(url,success,captureId) {
-			//TODO: Tratar se houver erro ao baixar anexo...
-			expresso_mail_sync.download_attachs(msg,folder_dest);
+			
+			if (!success) {
+				/*
+				 * 0 - original id
+				 * 1 - message subject
+				 * 2 - original folder
+				 */
+				var mail_error = new Array();
+				mail_error[0] = msg.msg_number;
+				mail_error[1] = msg.subject;
+				mail_error[2] = msg.msg_folder;
+				expresso_mail_sync.errors.push(mail_error);
+				alert('erro ao baixar: '+url);
+				
+				/*if (typeof(msg['array_attach']) == 'object' && (msg['array_attach'] instanceof Array)) {
+					for (var i in msg['array_attach']) { //remove os anexos que já foram baixados para essa mensagem...
+						expresso_mail_sync.store.remove(msg['array_attach'][i]['url']);
+					}
+				}*/
+				expresso_mail_sync.syncronize_mails(folder_dest); //Pula para o próximo e-mail.
+			}
+			else {
+				expresso_mail_sync.download_attachs(msg, folder_dest);//continua baixando o próximo anexo
+			}
 		}
 		expresso_mail_sync.store.capture(attach_to_capt['url'],call_back);
@@ -147,11 +242,8 @@
 	
 	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'];
@@ -162,6 +254,6 @@
 			var login = msg_info.login;
 			var original_id = msg_info.msg_number;
-			var original_folder = msg_info.msg_folder;
-			
+			var original_folder = msg_info.msg_folder=='INBOX/Lixeira/tmpMoveToLocal'?msg_info.msg_folder+(Date.parse(new Date)):msg_info.msg_folder;
+
 			//Os campos abaixo precisam estar isolados para busca de mensagens em cima deles.
 			var from = connector.serialize(msg_info.from);
@@ -182,7 +274,8 @@
 			//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) {
+			if(msg_header.udate.indexOf("/")==-1) {
 				msg_header.udate = msg_header.aux_date;
 			}
+		
 			
 			/**
@@ -203,9 +296,10 @@
 			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;
@@ -215,13 +309,44 @@
 			}
 			
-			if(preferences.keep_after_auto_archiving!=1)
+			var check_remove;
+			if(this.is_auto)
+				check_remove = preferences.keep_after_auto_archiving;
+			else
+				check_remove = preferences.keep_archived_messages;
+			
+			
+			
+			if(check_remove!=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?
+			/*
+			 * 0 - original id
+			 * 1 - message subject
+			 * 2 - original folder
+			 */
+			var mail_error = new Array();
+			mail_error[0] = original_id;
+			mail_error[1] = subject;
+			mail_error[2] = original_folder;
+			this.errors.push(mail_error);
+			
+			if (typeof(msg_info['array_attach'])=='object'&&(msg_info['array_attach'] instanceof Array)) { 
+				for(var i in msg_info['array_attach']) { //remove os anexos que já foram baixados para essa mensagem...
+					this.store.remove(msg_info['array_attach'][i]['url']);
+				}
+			}
+
 		}
 		this.dbGears.close();
 		this.syncronize_mails(folder);
+	}
+	
+	mail_sync.prototype.has_local_mails = function() {//This function considers that the connection with base is already opened.
+		var rs = this.dbGears.execute("select rowid from folder limit 0,1");
+		if(rs.isValidRow())
+			return true;
+		else 
+			return false;
 	}
 	
@@ -257,4 +382,5 @@
 					Element('tot_m').innerHTML = parseInt(Element('tot_m').innerHTML) - data.msgs_number.length;
 				}
+				ttreeBox.update_folder();
 				refresh();
 				expresso_mail_sync.remove_archived_mails();
@@ -268,6 +394,11 @@
 		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);
+			document.getElementById('main_title').innerHTML = get_lang("End of archive messages");
+			if(this.errors.length>0) {
+				//TODO: Tratar melhor quando existirem erros...
+				write_msg(get_lang("at least, one of selected mails is already archived, expresso tried to archive the others, check them later"));
+				this.errors=new Array();
+			}
+			window.setTimeout("eval('document.getElementById(\"main_title\").innerHTML =\"Expresso Mail\"')",3000);
 		}
 		
Index: /trunk/expressoMail1_2/js/local_messages.js
===================================================================
--- /trunk/expressoMail1_2/js/local_messages.js	(revision 1518)
+++ /trunk/expressoMail1_2/js/local_messages.js	(revision 1595)
@@ -33,4 +33,5 @@
 		
 		var db_in_other_use = true;
+		var start_trying = new Date().getTime();
 		while (db_in_other_use) {
 			try {
@@ -39,5 +40,7 @@
 			} 
 			catch (ex) {
-				db_in_other_use=true;
+				if(new Date.getTime()-start_trying>10000) { //too much time trying, throw an exception
+					throw ex;
+				}
 			}
 		}
@@ -934,5 +937,5 @@
 	}
 	
-	local_messages.prototype.get_folders_to_sync = function() {
+	local_messages.prototype.get_folders_to_sync = function() {//Precisa ter visibilidade ao array de linguagens.
 		this.init_local_messages();
 		var rs = this.dbGears.execute("select id_folder,folder_name from folders_sync where uid_usuario="+account_id);
@@ -941,5 +944,11 @@
 			temp = new Array();
 			temp[0] = rs.field(0);
-			temp[1] = rs.field(1);
+			if(temp[0]=='INBOX/Drafts' ||temp[0]=='INBOX/Trash' || temp[0]=='INBOX/Sent') {
+				temp[1] = array_lang[rs.field(1).toLowerCase()];
+			}
+			else {
+				temp[1] = rs.field(1);	
+			}
+			
 			retorno.push(temp);
 			rs.next();
Index: /trunk/expressoMail1_2/js/draw_api.js
===================================================================
--- /trunk/expressoMail1_2/js/draw_api.js	(revision 1564)
+++ /trunk/expressoMail1_2/js/draw_api.js	(revision 1595)
@@ -1279,5 +1279,5 @@
 	var option_reply_without_history		= '<span onmouseover="this.className=\'message_options_active\'" onmouseout="this.className=\'message_options\'" class="message_options" onclick=new_message("reply_without_history","'+ID+'");>'+get_lang("Reply without history")+'</span> | ';
 	var option_reply_to_all_without_history	= '<span onmouseover="this.className=\'message_options_active\'" onmouseout="this.className=\'message_options\'" class="message_options" onclick=new_message("reply_to_all_without_history","'+ID+'");>'+get_lang("Reply to all without history")+'</span> |';
-	var option_source_msg = '<span class="message_options" onclick=source_msg("'+ID+'","'+url_encode(info_msg.msg_folder)+'");>'+get_lang("Message Font")+'</span> </div>';		
+	var option_source_msg = '<span class="message_options" onclick=proxy_mensagens.proxy_source_msg("'+ID+'","'+url_encode(info_msg.msg_folder)+'");>'+get_lang("Message Font")+'</span> </div>';		
 
 	div_other_options.innerHTML = option_reply_to_all + option_reply_without_history + option_reply_to_all_without_history + option_source_msg;
