Index: sandbox/2.5.0-expresso1/info.php
===================================================================
--- sandbox/2.5.0-expresso1/info.php	(revision 7146)
+++ sandbox/2.5.0-expresso1/info.php	(revision 7146)
@@ -0,0 +1,38 @@
+<?php
+$BALANCEID = '';
+if(isset($_COOKIE['BALANCEID'])) {
+    $BALANCEID = $_COOKIE['BALANCEID'];
+}
+echo "BALANCEID:$BALANCEID\n";
+
+$sessionid = '';
+if(isset($_COOKIE['sessionid'])) {
+    $sessionid = $_COOKIE['sessionid'];
+}
+echo "sessionid:$sessionid\n";
+
+$session_save_path = ini_get('session.save_path');
+$session_save_path = trim($session_save_path);
+$last_char = $session_save_path[strlen($session_save_path)-1];
+if(($last_char != '/') && ($last_char != '\\')) {
+    $session_save_path .= '/';
+}
+$session_file = $session_save_path . 'sess_' . $_COOKIE['sessionid'];
+echo "session_file:$session_file\n";
+
+$user_id = '';
+if(is_file($session_file)) {
+
+    $session_contents = file_get_contents($session_file);
+    $session_contents_array = explode('|', $session_contents);
+
+    for($k = 0; $k < count($session_contents_array); $k++) {
+        $ss = unserialize($session_contents_array[$k]);
+        if(($ss['session_lid']) && ($ss['session_id']) && ($ss['session_id'] == $_COOKIE['sessionid'])) {
+            $user_id = $ss['session_lid'];
+            break;
+        }
+    }
+}
+echo "user_id:$user_id\n";
+?>
Index: sandbox/2.5.0-expresso1/prototype/modules/mail/js/foldertree.js
===================================================================
--- sandbox/2.5.0-expresso1/prototype/modules/mail/js/foldertree.js	(revision 7091)
+++ sandbox/2.5.0-expresso1/prototype/modules/mail/js/foldertree.js	(revision 7146)
@@ -62,5 +62,34 @@
 	
 	var folders = DataLayer.get("folder", true);
-	
+    
+    if(preferences.use_local_messages==1 && !expresso_offline) { //MailArchive
+	    //pega pastas locais do mailarchiver e insere no array de pastas
+	    var local_folders = new Array();
+	    for (var i=0; i<expresso_mail_archive.folders.length; i++) {
+	        var local_folder = {
+	            id: 'local_messages_'+expresso_mail_archive.folders[i].id,
+	            commonName: expresso_mail_archive.folders[i].name,
+	            messageCount: {
+	                total: expresso_mail_archive.folders[i].messages,
+	                unseen: expresso_mail_archive.folders[i].unseen
+	            }
+	        };
+	        folders.push(local_folder);
+	    }
+	}
+
+    //var local_folders = { id: 'local_messages', commonName: 'Pasta Local', messageCount: {total:200, unseen:20} };
+    //var local_folders = expresso_mail_archive.folders;
+
+    //folders.push(local_folders);
+ //    folders[24] = new Array();
+	// folders[24].id = 'local_messages';
+ //    folders[24].commonName = 'Pasta Local';
+ //    //folders[20].parentFolder = 'root';
+ //    folders[24].messageCount = { total: 200, unseen: 20};
+
+ //    console.log(folders);
+ //    console.log(folders.length);
+
 	if(!selected){
 		selected = "INBOX";
Index: sandbox/2.5.0-expresso1/expressoMail1_2/index.php
===================================================================
--- sandbox/2.5.0-expresso1/expressoMail1_2/index.php	(revision 7110)
+++ sandbox/2.5.0-expresso1/expressoMail1_2/index.php	(revision 7146)
@@ -348,5 +348,42 @@
     // End Set Imap Folder names options
 	//User info
-	echo "<script language='javascript'> var account_id = ".$GLOBALS['phpgw_info']['user']['account_id'].";var expresso_offline = false;</script>";
+    echo "<script language='javascript'> var account_id = ".$GLOBALS['phpgw_info']['user']['account_id'].";var expresso_offline = false; var mail_archive_host = '127.0.0.1';</script>\n";
+        
+    //MAILARCHIVER-02
+    //todo: remover a linha abaixo e implementar a configuração
+    //$GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['use_local_messages'] = true;
+        if ( $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['use_local_messages'] == true ) {
+        $mail_archiver_host = '127.0.0.1';
+        //Check protocol in use (https or http)
+        if($_SERVER['HTTPS'] != 'on'){
+            $mail_archiver_protocol = "http";
+            $mail_archiver_port = "4333";
+        }
+        else{
+            $mail_archiver_protocol = "https";
+            $mail_archiver_port = "4334";
+        }
+    
+        //JS Variables (to add on jscripts variables, needed by dependence scripts following)
+        echo '<script type="text/javascript">var mail_archive_protocol="'.$mail_archiver_protocol.'"; var mail_archive_port="'.$mail_archiver_port.'";</script>';
+    
+        //CXF custom js files, from MailArchiver ArcServUtil JS files repository, intended to be running already: CORS support and custom TRANSPORT object
+        echo '<script type="text/javascript" src="'.$mail_archiver_protocol.'://'.$mail_archiver_host.':'.$mail_archiver_port.'/arcservutil/cxf-addon-xdr-adapter.js"></script>';
+        echo '<script type="text/javascript" src="'.$mail_archiver_protocol.'://'.$mail_archiver_host.':'.$mail_archiver_port.'/arcservutil/cxf-addon-cors-request-object.js"></script>';
+        echo '<script type="text/javascript" src="'.$mail_archiver_protocol.'://'.$mail_archiver_host.':'.$mail_archiver_port.'/arcservutil/cxf-addon-cors-utils.js"></script>';
+
+        //CXF UTILS MAIN FILE
+        echo '<script type="text/javascript" src="'.$mail_archiver_protocol.'://'.$mail_archiver_host.':'.$mail_archiver_port.'/arcserv/ArchiveServices?js&nojsutils"></script>';
+    
+        //QueryConfig add on
+        echo '<script src="js/MAQueryConfig.js?'.$update_version.'"></script>';        
+        //Expresso serialized format add on
+        echo '<script src="js/MAExpressoPattern.js?'.$update_version.'"></script>';        
+    
+        //echo $obj -> getFilesJs("js/mail_archiver.js," . $GLOBALS['phpgw_info']['flags']['update_version']);
+        echo '<script src="js/mail_archiver.js?'.$update_version.'"></script>';
+    
+    }
+	//echo "<script language='javascript'> var account_id = ".$GLOBALS['phpgw_info']['user']['account_id'].";var expresso_offline = false;</script>";
 
 	$obj = createobject("expressoMail1_2.functions");
Index: sandbox/2.5.0-expresso1/expressoMail1_2/inc/class.user.inc.php
===================================================================
--- sandbox/2.5.0-expresso1/expressoMail1_2/inc/class.user.inc.php	(revision 5509)
+++ sandbox/2.5.0-expresso1/expressoMail1_2/inc/class.user.inc.php	(revision 7146)
@@ -50,5 +50,28 @@
 			return $_SESSION['phpgw_info']['expressomail']['user']['email'];	
 		}
-		
+
+        //MailArchiver login validate operations
+        function get_mailarchiver_authid(){
+            if((isset($_COOKIE["BALANCEID"])) && ($_COOKIE["BALANCEID"] != null) && ($_COOKIE["BALANCEID"] != " "))
+                $cookie_balancer = $_COOKIE["BALANCEID"];
+            else
+                $cookie_balancer = "";
+            if((isset($_COOKIE["sessionid"])) && ($_COOKIE["sessionid"] != null) && ($_COOKIE["sessionid"] != " "))
+                $cookie_session = $_COOKIE["sessionid"];
+            else
+                $cookie_session = "";
+            if(isset($_SESSION['phpgw_info']['expressomail']['user']['userid']) && ($_SESSION['phpgw_info']['expressomail']['user']['userid'] != null) && ($_SESSION['phpgw_info']['expressomail']['user']['userid'] != " "))
+                $cookie_user = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
+            else
+                $cookie_user = "";
+            
+            if(isset($_SESSION['phpgw_info']['expressomail']['user']['passwd']) && ($_SESSION['phpgw_info']['expressomail']['user']['passwd'] != null) && ($_SESSION['phpgw_info']['expressomail']['user']['passwd'] != " "))
+                $cookie_pass = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
+            else
+                $cookie_pass = "";
+            
+            return(array($cookie_balancer, $cookie_session, $cookie_user, $cookie_pass));                    
+        }
+
 	}
 ?>
Index: sandbox/2.5.0-expresso1/expressoMail1_2/js/mail_archiver.js
===================================================================
--- sandbox/2.5.0-expresso1/expressoMail1_2/js/mail_archiver.js	(revision 7146)
+++ sandbox/2.5.0-expresso1/expressoMail1_2/js/mail_archiver.js	(revision 7146)
@@ -0,0 +1,2014 @@
+<!--
+/* 
+ * Mail Archive JS API
+ * 
+ * This JavaScript file is the core to use MailArchiver embeded at Expresso suite.
+ * It contains all the resources used to handle local messages stored at the brand
+ * new solution Mail Archiver (a embeded application server running at client side).
+ *
+ * This feature is a replacement for Google Gears(obsolete by now), used by
+ * Expresso to store local messages at user workstation hard disk.
+ * 
+ * @author Fernando Wendt [fernando-alberto.wendt@serpro.gov.br]
+ *
+ * @status under development
+ */
+
+//var sessid = 'sessionId';
+
+function zeroFill(d){
+    if(parseInt(d) < 10)
+        return('0' + d);
+    else
+        return(d);
+}
+
+//+ Jonas Raoni Soares Silva
+//@ http://jsfromhell.com/geral/utf-8 [v1.0]
+
+UTF8 = {
+	encode: function(s){
+		for(var c, i = -1, l = (s = s.split("")).length, o = String.fromCharCode; ++i < l;
+			s[i] = (c = s[i].charCodeAt(0)) >= 127 ? o(0xc0 | (c >>> 6)) + o(0x80 | (c & 0x3f)) : s[i]
+		);
+		return s.join("");
+	},
+	decode: function(s){
+		for(var a, b, i = -1, l = (s = s.split("")).length, o = String.fromCharCode, c = "charCodeAt"; ++i < l;
+			((a = s[i][c](0)) & 0x80) &&
+			(s[i] = (a & 0xfc) == 0xc0 && ((b = s[i + 1][c](0)) & 0xc0) == 0x80 ?
+			o(((a & 0x03) << 6) + (b & 0x3f)) : o(128), s[++i] = "")
+		);
+		return s.join("");
+	}
+};
+
+
+/**
+ * Concatenates the values of a variable into an easily readable string
+ * by Matt Hackett [scriptnode.com]
+ * @param {Object} x The variable to debug
+ * @param {Number} max The maximum number of recursions allowed (keep low, around 5 for HTML elements to prevent errors) [default: 10]
+ * @param {String} sep The separator to use between [default: a single space ' ']
+ * @param {Number} l The current level deep (amount of recursion). Do not use this parameter: it's for the function's own use
+ */
+function print_r(x, max, sep, l) {
+
+	l = l || 0;
+	max = max || 100;
+	sep = sep || ' ';
+
+	if (l > max) {
+		return "[WARNING: Too much recursion]\n";
+	}
+
+	var
+		i,
+		r = '',
+		t = typeof x,
+		tab = '';
+
+	if (x === null) {
+		r += "(null)\n";
+	} else if (t == 'object') {
+
+		l++;
+
+		for (i = 0; i < l; i++) {
+			tab += sep;
+		}
+
+		if (x && x.length) {
+			t = 'array';
+		}
+
+		r += '(' + t + ") :\n";
+
+		for (i in x) {
+			try {
+				r += tab + '[' + i + '] : ' + print_r(x[i], max, sep, (l + 1));
+			} catch(e) {
+				return "[ERROR: " + e + "]\n";
+			}
+		}
+
+	} else {
+
+		if (t == 'string') {
+			if (x == '') {
+				x = '(empty)';
+			}
+		}
+
+		r += '(' + t + ') ' + x + "\n";
+
+	}
+
+	return r;
+
+};
+var_dump = print_r;
+
+
+
+//Main object structure: object property data definition
+function MailArchiver() { 
+    this.enabled = null;
+    this.interval = 500;
+    this.timer = null;
+    this.counter = 0;
+    this.service_count = 0;
+    this.service_count_tryouts = 0;
+    this.message_list = new Array();
+    this.search_message_list = new Array();
+    this.messageslisted = new Array();
+    this.total_messages = 0;
+    this.messages_processed = 0;
+    this.messages_fail = 0;
+    this.folder_origin = null;
+    this.folder_destination = null;
+    this.folders = null;
+    this.currentfolder = 'local_root';
+    this.currentmessage = null;
+    this.currentheaders = null;
+    this.drawdata = null;
+    this.onprocess = false;
+    this.folder_data = false;
+    this.queryconfig = new MAQueryConfig();
+    this.search_queryconfig = new MAQueryConfig();
+    this.pattern = new MAPattern();
+    this.messagesourcehandler = null;
+    this.ServiceReturnObjectList = null;
+    this.ServiceReturnObjectSearch = null;
+    
+    this.specialfolders = {
+                            "inbox":"local_inbox", 
+                            "sent":"local_sent", 
+                            "drafts":"local_drafts", 
+                            "outbox":"local_outbox", 
+                            "trash":"local_trash"
+                          };                          
+    this.unarchivecounter = 0;
+    this.archivefolder = null;
+    this.unarchievefolder = null;
+    this.unarchievenewfolder = null;
+    this.taglist = "";   
+    this.currenttag = "";   
+    this.tagmsg = false;
+    this.progressbar = null;
+    this.tmp_att_datasource = null;
+    this.tmp_att_data = null;
+    this.isbusy = false;
+    this.update_counters = false;
+    this.exportformat = 'zip';
+    this.querydata = null;
+    this.queryresult = null;
+    this.search_queryresult = null;
+    this.balancerid = null;
+    this.sessionid = null;
+    this.logonid = null;
+    this.session = null;
+    this.selectedfolder = null;
+}
+
+//Invoked at some possible MA crash issue
+MailArchiver.prototype.resetObject = function(){
+    expresso_mail_archive.message_list = new Array();
+    expresso_mail_archive.messagelisted = new Array();
+    expresso_mail_archive.total_messages = 0;
+    expresso_mail_archive.messages_processed = 0;
+    expresso_mail_archive.messages_fail = 0;
+    //expresso_mail_archive.folder_origin = null;
+    //expresso_mail_archive.folder_destination = null;
+    //expresso_mail_archive.folder = null;
+    expresso_mail_archive.isbusy = false;
+    //window.alert('ResetedObject, deixando current folder como "' + expresso_mail_archive.currentfolder + '"\nfolder destination "' + expresso_mail_archive.folder_destination+ '"');
+}
+
+/*SystemCheck method: test if MailArchive is installed and/or running at user workstation
+*Try to get a instance of ArchiveServices object - the handler of services provided by
+*the MailArchive services provider interface, from user workstation.
+*/
+MailArchiver.prototype.SystemCheck = function(){
+    expresso_mail_archive.enabled = ((ArchiveServices) ? true : false);    
+    if(expresso_mail_archive.enabled){
+        expresso_mail_archive.getAuthId();
+    }
+    else{
+        
+    }
+}
+
+//Check if preference is setted to use default local folders, try to create them
+MailArchiver.prototype.CreateDefaultStructrure = function(){
+    if(expresso_mail_archive.enabled){
+       //Base request object is a CXF Add-on CORS compatible component
+       var reqHandler = new cxf_cors_request_object();
+       reqHandler.init();
+       this.messagesourcehandler = reqHandler.handler;  
+       if(preferences.auto_create_local == 1){
+           expresso_mail_archive.createFolder("","Trash");
+           expresso_mail_archive.createFolder("","Drafts");
+           expresso_mail_archive.createFolder("","Sent");
+           expresso_mail_archive.createFolder("","Outbox");
+           expresso_mail_archive.createFolder("","Spam");
+       }
+       this.ActivateStatusListener(this);
+    }    
+}
+
+
+//Turns on the listener timer to check services availability
+MailArchiver.prototype.ActivateStatusListener = function(obj){
+    if (document.getElementById('mail_archiver_retry'))
+        tem_tag = true;
+    else
+        tem_tag = false;
+    try{
+        if (obj.enabled){
+            obj.interval = 500; //set default timer to 1ms (imediate lauching)
+            //draw_footer_box(get_current_folder());
+            obj.getServicesStatus(obj);
+        }
+        else{
+            throw "this is not enabled: " + obj;
+            window.alert('Nope: obj.enabled is not true...');
+        }
+    }
+    catch (e){
+        window.alert('ActivateStatusListener error: ' + e);
+    }
+}
+
+//Turns off the service status listener, at a crash issue
+MailArchiver.prototype.DeactivateStatusListener = function(obj){
+    window.clearInterval(obj.timer);
+    obj.enabled = null;
+    obj.timer=null;
+    obj.interval = 500;
+    ArchiveServices = null;
+    connector.purgeCache();
+    draw_footer_box(get_current_folder());
+    //auto_refresh();
+    if(document.getElementById('mail_archiver_retry')){
+        document.getElementById('mail_archiver_retry').parentNode.removeChild(document.getElementById('mail_archiver_retry'));
+    }
+    else{
+        //Redraw "Offline" linkage, intended to recoonect MailArchiver link    
+        connector.purgeCache();
+        ttreeBox.name_folder = "root";
+        ttreeBox.update_folder();
+        draw_tree_local_folders();
+        ttreeBox.update_folder();
+        change_folder('INBOX', 'INBOX', ttreeBox);  
+    }
+}
+
+//ServiceStatus callback OK
+MailArchiver.prototype.getServicesStatusOK = function(serviceData){
+    //window.alert('getServicesStatusOK com servicedata = ' + serviceData.getReturn());
+    expresso_mail_archive.service_count = expresso_mail_archive.counter;
+    if ((serviceData.getReturn().toUpperCase() == "STARTED") || (serviceData.getReturn().toUpperCase() == "RUNNING")){
+        //If there is no timer activated to services check interval, set it up.
+        if(expresso_mail_archive.enabled){
+           if(expresso_mail_archive.timer == null){
+                expresso_mail_archive.interval = 15000;
+                expresso_mail_archive.timer = window.setInterval(expresso_mail_archive.getServicesStatus, expresso_mail_archive.interval);
+                var drawinginfo = {treeObject: tree_folders, treeName: 'tree_folders', folderName: 'local_root'};
+                expresso_mail_archive.currentfolder = 'local_root';
+                expresso_mail_archive.drawdata = drawinginfo;
+                expresso_mail_archive.getFoldersList();
+           }
+        }
+        else{
+            window.clearInterval(expresso_mail_archive.timer);
+            write_msg(get_lang('MailArchiver does not seems to be running or installed at this workstation, local messages are disabled. Check it out!'),true);
+        }
+    }
+    else{
+        window.clearInterval(expresso_mail_archive.timer);
+        write_msg(get_lang('MailArchiver does not seems to be running or installed at this workstation, local messages are disabled. Check it out!'),true);
+        expresso_mail_archive.enabled = false;        
+    }
+    //window.alert('fooArc set to null');
+    fooArc = null;
+}
+
+//Dettach resources handler
+MailArchiver.prototype.DeactivateResources = function(obj){   
+    if(obj.timer)
+        window.clearInterval(obj.timer);
+    write_msg(get_lang('Mail Archiver is not responding. There is some communicating issue hang it up. Some services may not work properly. Check it out!'));
+    obj.DeactivateStatusListener(obj);
+    return;
+}
+
+//Services Status Fail callback
+MailArchiver.prototype.getServicesStatusFailure = function(serviceData){
+    window.alert('getServicesStatusFailure incomming');
+    window.alert('getServicesStatusFailure feature: ' + serviceData);
+}
+
+//Service Status handler
+MailArchiver.prototype.getServicesStatus = function(obj){
+    //window.alert('em getServicesStatus obj.enabled = ' + obj.enabled + '\nArchiveServices.enabled = ' + ArchiveServices.enabled + '\nArchiveServices = ' + ArchiveServices);
+    try{
+        //window.alert('on try 01');
+        expresso_mail_archive.service_count_tryouts++;
+        //window.alert('service_count_tryouts = ' + expresso_mail_archive.service_count_tryouts + '\nservice_count = ' + expresso_mail_archive.service_count);
+        
+        if((expresso_mail_archive.service_count_tryouts - expresso_mail_archive.service_count) > 1){
+            //window.alert('problema -> deve desligar');
+            expresso_mail_archive.DeactivateResources(expresso_mail_archive);            
+        }
+        else
+            //window.alert('ok');
+        
+        var fooArc = new web_service_mailarchiver_serpro__ArchiveServices();
+        fooArc.url = mail_archive_protocol + "://" + mail_archive_host + ":" + mail_archive_port + "/arcserv/ArchiveServices";
+        //window.alert('typeof(fooArc) = ' + typeof(fooArc) + '\nfooArc = ' + fooArc);
+        if(fooArc){
+            try{
+                //window.alert('on try 02');
+                fooArc.getState(expresso_mail_archive.getServicesStatusOK, expresso_mail_archive.getServicesStatusFailure, "true");
+                fooArc = null;
+            }catch (e){
+                throw "Service failure status: getState";
+            }
+        }
+        else {
+            throw "No ArchiveServices object present. Sorry, but leaving now...";
+        }
+    }catch (e){
+        //window.alert('getServiceStatus exception:' + e);
+    }
+    expresso_mail_archive.counter = expresso_mail_archive.counter +1;
+}
+
+/*Restart method: re-initializes all the Mail Archive structure
+ **/
+MailArchiver.prototype.Restart = function(obj){
+    obj.SystemCheck();
+    obj.ActivateStatusListener(obj);
+    connector.resetProgressBarText();
+    //auto_refresh();
+}
+
+/*Startup method: initializes all the Mail Archive structure to work so far as possible
+ *Looks like the old 'gears_init', from Gears
+ **/
+MailArchiver.prototype.Startup = function(){
+    this.SystemCheck();  
+}
+
+MailArchiver.prototype.serializeToExpresso = function(data){
+    return(connector.serialize(data));
+}
+
+MailArchiver.prototype.unserializeFromExpresso = function(data){
+    return(connector.unserialize(data));
+}
+
+
+MailArchiver.prototype.CreateMessageList = function(msg_list){
+    //window.alert('criando messagelist de arquivamento.');
+    
+//    for(var j=0; j<expresso_mail_archive.messageslisted.length; j++){
+//        window.alert('\nAnswered = ' + expresso_mail_archive.messageslisted[j]["Answered"] + '\nFlagged = ' + expresso_mail_archive.messageslisted[j]["Flagged"] + '\nUnseen = ' + expresso_mail_archive.messageslisted[j]["Unseen"] + '\nDraft = ' + expresso_mail_archive.messageslisted[j]["Draft"]);
+//    }
+    
+    if((msg_list != null) && (msg_list != "") && (msg_list != " ")){
+        if (expresso_mail_archive.message_list.length == 0){
+            //Get all the messages ids by pass at msgs_id to "message_list" object array propertie - if more than one exists
+            if(msg_list.indexOf(',') != -1){
+                var tmp_list = msg_list.split(',');
+                for(var i=0; i < tmp_list.length; i++){
+                    expresso_mail_archive.message_list.push(tmp_list[i]);
+                }
+            }
+            
+            //Push message list to process the only one
+            else {
+                //window.alert('testando marcadores default...\n->Answered = ' +expresso_mail_archive.messageslisted[i]["Answered"] + '\n->Unseen = '+expresso_mail_archive.messageslisted[i]["Unseen"]);
+                expresso_mail_archive.message_list.push(msg_list);
+            }
+        }
+    }
+    //msg_list is corrupted. aborting population
+    else expresso_mail_archive.message_list = new Array();
+}
+
+
+//Archive Operation
+MailArchiver.prototype.Archive = function(source_folder,destination_folder,msgs_id){
+    //window.alert('tentando arquivar a mensagem [' + msgs_id + '], do folder ['+source_folder+'] para a pasta destino ['+destination_folder+']');
+    modal('archive_queue');
+    
+    try{
+        
+        //Sets the folders properties: destination and origin
+        expresso_mail_archive.folder_origin = source_folder;
+        
+        expresso_mail_archive.CreateMessageList(msgs_id);
+        var tagsHandler = function(data){
+            if(data){
+                var datah = eval(data);
+                //window.alert('unseen = ' +datah["unseen"] + '\nrecent = ' + datah["recent"] + '\nflagged = ' + datah["flagged"] + '\ndraft = ' + datah["draft"] + '\nanswered = ' + datah["answered"] + '\ndeleted = ' + datah["deleted"] + '\nforwarded = ' + datah["forwarded"]);
+                expresso_mail_archive.taglist = datah;
+                //Sets the message counter and busy state
+                if(expresso_mail_archive.isbusy == false){
+                    expresso_mail_archive.total_messages = expresso_mail_archive.message_list.length;
+                    expresso_mail_archive.isbusy =  true;
+                }
+           
+                var fcaption = "";
+                
+                if(destination_folder.substr(0,5) == 'local'){
+                    expresso_mail_archive.folder_destination = destination_folder.substr(6,destination_folder.length);
+                }
+                else{
+                    expresso_mail_archive.folder_destination = destination_folder;
+                }
+                
+                if(!expresso_mail_archive.archivefolder){
+                    expresso_mail_archive.getFolderInfo(expresso_mail_archive.folder_destination);
+                    if(typeof(expresso_mail_archive.folder) != "undefined"){
+                        //window.alert('folder.path -> ' + expresso_mail_archive.folder.path);
+                        expresso_mail_archive.archivefolder = expresso_mail_archive.folder.path;
+                        //window.alert('folder.path2 -> ' + expresso_mail_archive.folder.path);
+                    }
+                    else{
+                     //window.alert('ainda, sem folder.path');   
+                     //window.alert('testando folder.path agora ' + expresso_mail_archive.folder.path);
+                    }
+                }   
+
+                fcaption = expresso_mail_archive.archivefolder;
+                            
+                //Special folders translation
+                if (fcaption && ((fcaption.toLowerCase() == 'inbox') || (fcaption.toLowerCase() == 'outbox') || (fcaption.toLowerCase() == 'sent') || (fcaption.toLowerCase() == 'drafts') || (fcaption.toLowerCase() == 'trash')))
+                    fcaption = get_lang(fcaption);
+            
+            
+                var arch_handler = function(data){
+                    //Store the message source from Ajax request by now (string data)
+                    var js_var = new String(data);
+                    try{
+                        //Archive services needs session id, message source and destination folder
+                        ArchiveServices.archive(expresso_mail_archive.getArchiveOperationOK, expresso_mail_archive.getArchiveOperationFailure, expresso_mail_archive.session.id, expresso_mail_archive.folder_destination, data);
+                    }
+                    catch(e){
+                        expresso_mail_archive.getFaultInfo();
+                    }
+                }
+                
+                //document.getElementById('main_title').innerHTML = get_lang('Archiving message %1 of %2 on folder %3', expresso_mail_archive.messages_processed, expresso_mail_archive.total_messages, fcaption);
+                document.getElementById('text_archive_queue').innerHTML = get_lang('Archiving message %1 of %2 on folder %3', expresso_mail_archive.messages_processed+1, expresso_mail_archive.total_messages, fcaption);
+                cExecute("$this.exporteml.js_source_var",arch_handler,"folder="+url_decode(source_folder)+"&msgs_to_export="+expresso_mail_archive.message_list[0]);                
+            }
+            else{
+                close_lightbox();
+                write_msg(get_lang('Archive operation error: getting online message flags fails. Achievement will not be done'),true);
+                expresso_mail_archive.archivefolder = null;
+            }
+        }
+
+       if((expresso_mail_archive.message_list.length > 0) && (expresso_mail_archive.message_list[0] != '')){
+
+            //Get all tags from current archiving message
+           if(!expresso_mail_archive.folder_origin){
+                var aux1_folder = expresso_mail_archive.message_list[0].split(';')[0];
+                var aux1_msg_number = expresso_mail_archive.message_list[0].split(';')[1];
+            }
+            else{
+                var aux1_folder = expresso_mail_archive.folder_origin;
+                var aux1_msg_number = expresso_mail_archive.message_list[0];
+            }
+            //var pardata = "&folder=" + url_encode(expresso_mail_archive.folder_origin)+ "&msg_number="+ expresso_mail_archive.message_list[0]; 
+            var pardata = "&folder=" + url_encode(aux1_folder)+ "&msg_number="+ aux1_msg_number;
+            cExecute("$this.imap_functions.get_msg_flags", tagsHandler, pardata);
+        }
+        else throw('Archive operation error: message list stack is empty');
+    }
+    catch(e){
+        //window.alert(get_lang("Archive error: %1", (e.description)?e.description:e));
+        expresso_mail_archive.getFaultInfo();
+    }
+}
+
+//Archive callback OK
+MailArchiver.prototype.getArchiveOperationOK = function(status_message){
+    //message must be tagged
+    var arcid = status_message.getReturn().getId();
+    var tlist = expresso_mail_archive.pattern.tagConfig(expresso_mail_archive.taglist, arcid, 0);
+    if(tlist != null){
+        try{
+            expresso_mail_archive.drawdata = null //removes any draw parameter to archive msgs
+            ArchiveServices.tagMessages(expresso_mail_archive.tagMessagesOperationOK, expresso_mail_archive.tagMessagesOperationFailure, expresso_mail_archive.session.id, tlist);
+        }catch (e){
+            expresso_mail_archive.getFaultInfo();
+        }
+    }
+
+    //if user preference is setted to move messages, here, whe will call a delete message at mailserver
+    if(preferences.keep_archived_messages == 0){
+        proxy_mensagens.delete_msgs(expresso_mail_archive.folder_origin,expresso_mail_archive.message_list[0],null,false,true);
+    }else{
+        if (Element("check_box_message_" + expresso_mail_archive.message_list[0])) {
+            Element("check_box_message_" + expresso_mail_archive.message_list[0]).checked = false;
+            remove_className(Element(expresso_mail_archive.message_list[0]), 'selected_msg');
+        }
+    }
+
+    //archivement allready done, update controll data and interface
+    expresso_mail_archive.messages_processed++;
+    if(expresso_mail_archive.message_list.length > 1){
+       //document.getElementById('main_title').innerHTML = get_lang("Message %1 of %2 successfully archived", expresso_mail_archive.messages_processed, expresso_mail_archive.total_messages);
+       expresso_mail_archive.message_list.shift();
+       expresso_mail_archive.Archive(expresso_mail_archive.folder_origin, expresso_mail_archive.folder_destination, expresso_mail_archive.message_list);
+    }
+    else{
+        document.getElementById('main_title').innerHTML = get_lang("All done. End of archive messages operation");
+        expresso_mail_archive.resetObject();
+        expresso_mail_archive.archivefolder = null;
+        window.setTimeout("eval('document.getElementById(\"main_title\").innerHTML =\"Expresso Mail\"')",3000);        
+        connector.purgeCache();
+        //ttreeBox.name_folder = "local_" + expresso_mail_archive.currentfolder;
+        ttreeBox.name_folder = "local_inbox";
+        draw_tree_local_folders();
+        //ttreeBox.update_folder(true);    
+    }
+    
+    close_lightbox();
+}
+//Archive callback Fail
+MailArchiver.prototype.getArchiveOperationFailure = function(error_message){
+    window.alert('Hi! getArchiveOperationFailure comes with ' + error_message.getReturn());
+    window.setTimeout("eval('document.getElementById(\"main_title\").innerHTML =\"Expresso Mail\"')",3000);
+}
+
+/**
+ *Unarchieve Message
+ *
+ *@author Cassiano Dal Pizzol [cassiano.dalpizzol@serpro.gov.br]
+ *
+ *@param folder Original Folder of the message
+ *@param new_folder The new folder of the message
+ *@param msgs_number id of the messages
+ */
+MailArchiver.prototype.unarchieve = function (folder, new_folder, msgs_number){
+    try{ 
+        document.getElementById('main_title').innerHTML = get_lang("Starting to unarchive messages");
+        if(currentTab.toString().indexOf("_r") != -1){
+            msgs_number = currentTab.toString().substr(0,currentTab.toString().indexOf("_r"));
+        }
+
+        if(!msgs_number)
+            msgs_number = get_selected_messages();        
+                
+        if (parseInt(msgs_number) > 0 || msgs_number.length > 0){       
+            expresso_mail_archive.message_list = new Array();
+            expresso_mail_archive.CreateMessageList(msgs_number);
+            if((expresso_mail_archive.message_list.length > 0) && (expresso_mail_archive.message_list[0] != '')) {
+                expresso_mail_archive.unarchivecounter = 0;
+                expresso_mail_archive.unarchive_error_counter=0;
+                expresso_mail_archive.getFolderInfo(folder.substr(6, folder.length));
+                expresso_mail_archive.unarchievefolder = expresso_mail_archive.folder.name;
+                (new_folder != null)?expresso_mail_archive.unarchievenewfolder = new_folder:expresso_mail_archive.unarchievenewfolder='INBOX';
+                expresso_mail_archive.unarchieveHandler();
+            }
+            else{
+                write_msg(get_lang('No selected message.'));
+            }                               
+        }
+        else
+            write_msg(get_lang('No selected message.'));
+    }
+    catch (e){
+        write_msg(get_lang('Unarchive error: ' + e));
+    }
+}
+
+/**
+ *
+ *Unarchieve Message Handler
+ *
+ *@author Cassiano Dal Pizzol [cassiano.dalpizzol@serpro.gov.br]
+ *
+ **/
+MailArchiver.prototype.unarchieveHandler = function(){
+    try{
+        var email = mail_archive_protocol+'://'+mail_archive_host+':'+mail_archive_port+'/mail/' + expresso_mail_archive.session.id +'/'+ expresso_mail_archive.folder.path + '/'+ expresso_mail_archive.message_list[expresso_mail_archive.unarchivecounter] + '.eml';    
+    
+        //Creates a new object to unarchive messages. It's a CXF Add-on CORS component
+        var UnarchiveReqHandler = new cxf_cors_request_object();
+        UnarchiveReqHandler.init();
+
+        //Both XDomainRequest and XMLHttpRequest L2 supports onload event
+        UnarchiveReqHandler.handler.onload = function(){            
+            for (var w=0; w < expresso_mail_archive.messageslisted.length; w++){
+                                
+                if(expresso_mail_archive.messageslisted[w]["msg_number"] == expresso_mail_archive.message_list[expresso_mail_archive.unarchivecounter]){
+                    var timestamp = expresso_mail_archive.messageslisted[w]["timestamp"];
+                    
+                    //Get local tagged message data
+                    var flags = new String("");
+                    
+                    //Forwarded is special one: marks as "answered" and "draft"
+                    if(expresso_mail_archive.messageslisted[w]["Forwarded"]){
+                        if(expresso_mail_archive.messageslisted[w]["Forwarded"] == 'F')
+                            flags += 'A:X';                                  
+                    }
+                    else{
+                        //Answered tag
+                        if(expresso_mail_archive.messageslisted[w]["Answered"])
+                            if(expresso_mail_archive.messageslisted[w]["Answered"] == 'A')
+                                flags += 'A';
+                            else
+                                flags += ':';
+                        else
+                            flags += ':';                    
+
+                        //Draft tag
+                        if(expresso_mail_archive.messageslisted[w]["Draft"])
+                            if(expresso_mail_archive.messageslisted[w]["Draft"] == 'X')
+                                flags += 'D'+':';                    
+                            else
+                                flags += ':';
+                        else
+                            flags += ':';
+                    }
+                    
+                    //Flagged tag
+                    if(expresso_mail_archive.messageslisted[w]["Flagged"])
+                        if(expresso_mail_archive.messageslisted[w]["Flagged"] == true)
+                            flags += 'F'+':';                                        
+                        else
+                            flags += ':';
+                    else
+                        flags += ':';
+                    
+                    //Unseen tag
+                    if(expresso_mail_archive.messageslisted[w]["Unseen"])
+                        if(expresso_mail_archive.messageslisted[w]["Unseen"] == 'U')
+                            flags += 'U';     
+                        else
+                            flags += '';
+                    else
+                        flags += '';
+                    
+                    //Imap tag hash id
+                    flags += "#@#@#@";                    
+                    
+                    break;
+                }
+            }
+            var id = expresso_mail_archive.message_list[expresso_mail_archive.unarchivecounter];
+            var source =  encodeURIComponent(UnarchiveReqHandler.handler.responseText) + "#@#@#@";
+            var params = 
+            "&folder="      + escape(expresso_mail_archive.unarchievenewfolder) +
+            "&source="      + source + 
+            "&timestamp="   + timestamp + 
+            "&madata=true"  + 
+            "&flags="       + flags +
+            "&id="          + id;
+        
+            var handler_unarchive = function(data){
+                expresso_mail_archive.unarchieveController(data);
+            }
+            //write_msg(get_lang('Unarchiving message %1 of %2', (expresso_mail_archive.unarchivecounter + 1), expresso_mail_archive.message_list.length));
+            document.getElementById('main_title').innerHTML = get_lang('Unarchiving message %1 of %2', (expresso_mail_archive.unarchivecounter + 1), expresso_mail_archive.message_list.length);
+            cExecute ("$this.imap_functions.unarchive_mail&", handler_unarchive, params);
+
+        }
+        
+        document.getElementById('main_title').innerHTML = get_lang('Opening message %1 to unarchive', (expresso_mail_archive.unarchivecounter + 1));
+    
+        UnarchiveReqHandler.handler.open("GET", email, true);
+        if(UnarchiveReqHandler.handler.overrideMimeType){
+            UnarchiveReqHandler.handler.overrideMimeType("message/rfc822; charset=windows-1252"); 
+        }
+    
+        UnarchiveReqHandler.handler.send();
+    }
+    catch(e){
+        write_msg(get_lang('Unarchive error: ' + e));
+    }
+}
+
+/**
+ *
+ *Unarchieve Message Controller
+ *
+ *@author Cassiano Dal Pizzol [cassiano.dalpizzol@serpro.gov.br]
+ *
+ **/
+MailArchiver.prototype.unarchieveController = function(data){
+    expresso_mail_archive.unarchivecounter++;
+    
+    if (data)
+    {
+        if (data.error)
+        {
+            expresso_mail_archive.unarchive_error_counter++;
+        }
+        
+        if (data.archived && preferences.keep_archived_messages == "0")
+        {
+            // apaga
+            expresso_mail_archive.deleteMessages(data.archived[0]);
+        }
+        
+    }
+
+    if (expresso_mail_archive.unarchivecounter < expresso_mail_archive.message_list.length){
+        expresso_mail_archive.unarchieveHandler();
+    }
+    else
+    {
+        if (expresso_mail_archive.unarchive_error_counter == 0)
+        {    
+            if (expresso_mail_archive.message_list.length==1){
+                //write_msg(get_lang('Message successfully unarchived'));
+                document.getElementById('main_title').innerHTML = get_lang('Message successfully unarchived');
+                window.setTimeout("eval('document.getElementById(\"main_title\").innerHTML =\"Expresso Mail\"')",3000);  
+            }
+            else{
+                //write_msg(get_lang('Messages successfully unarchived'));
+                document.getElementById('main_title').innerHTML = get_lang('Messages successfully unarchived');
+                window.setTimeout("eval('document.getElementById(\"main_title\").innerHTML =\"Expresso Mail\"')",3000);  
+            }
+        }
+        else
+            {
+                if (expresso_mail_archive.message_list.length==1){
+                    //write_msg(get_lang('Message successfully unarchived'));
+                    document.getElementById('main_title').innerHTML = get_lang("Coudn't unarchive message");
+                    window.setTimeout("eval('document.getElementById(\"main_title\").innerHTML =\"Expresso Mail\"')",3000);  
+                }
+                else if (expresso_mail_archive.unarchive_error_counter == expresso_mail_archive.message_list.length)
+                    {
+                        //write_msg(get_lang('Message successfully unarchived'));
+                        document.getElementById('main_title').innerHTML = get_lang("No messages were unarchived");
+                        window.setTimeout("eval('document.getElementById(\"main_title\").innerHTML =\"Expresso Mail\"')",3000);
+                    }
+                    else{
+                        //write_msg(get_lang('Messages successfully unarchived'));
+                        document.getElementById('main_title').innerHTML = get_lang("Some messages weren't successfully unarchived");
+                        window.setTimeout("eval('document.getElementById(\"main_title\").innerHTML =\"Expresso Mail\"')",3000);  
+                    }
+                    
+            }
+        //clear message list
+        expresso_mail_archive.message_list = new Array();
+    }
+}
+
+/**
+ *Archieve Delete Message
+ *
+ *@author Cassiano Dal Pizzol [cassiano.dalpizzol@serpro.gov.br]
+ *
+ *@param msgs_number Unique identification of the message
+ */
+MailArchiver.prototype.deleteMessages = function(msgs_number){
+    try{
+        // This is necessary 'couse we can get a delete operation while an unarchive operation
+        // is still executing
+        expresso_mail_archive._temp_list = expresso_mail_archive.message_list;
+        expresso_mail_archive.message_list = new Array();
+        
+        expresso_mail_archive.CreateMessageList(msgs_number);
+        if((expresso_mail_archive.message_list.length > 0) && (expresso_mail_archive.message_list[0] != '')) {
+            ArchiveServices.deleteMessages(expresso_mail_archive.deleteMessagesOperationOK, 
+                                           expresso_mail_archive.deleteMessagesOperationFailure, 
+                                           expresso_mail_archive.session.id, 
+                                           expresso_mail_archive.message_list);
+        }
+        else{
+            write_msg(get_lang('No selected message.'));
+        }
+    }
+    catch (e){
+        window.alert('Delete error: ' + e);
+    }
+}
+
+/**
+ *Archieve Delete Message Ok
+ *
+ *@author Cassiano Dal Pizzol [cassiano.dalpizzol@serpro.gov.br]
+ *
+ */
+MailArchiver.prototype.deleteMessagesOperationOK = function(){
+/*    var drawinginfo = {treeObject: tree_folders, treeName: 'tree_folders'};
+    expresso_mail_archive.drawdata = drawinginfo;
+    expresso_mail_archive.drawFolderTree();
+    expresso_mail_archive.listMessages();
+    */
+    connector.purgeCache();
+    //ttreeBox.update_folder(true);
+    if(expresso_mail_archive.message_list.length > 1){
+        write_msg(get_lang("The messages were deleted."));
+    }else{
+        write_msg(get_lang("The message was deleted."));
+    } 
+    expresso_mail_archive.update_counters = true;
+    expresso_mail_archive.messageslisted = new Array();
+    expresso_mail_archive.message_list = new Array();  
+    expresso_mail_archive.listMessages(expresso_mail_archive.currentfolder);    
+    tree_folders.getNodeById('local_trash')._select();    
+    /*connector.purgeCache();
+    ttreeBox.name_folder = "local_" + expresso_mail_archive.currentfolder;
+    //draw_tree_local_folders();
+    ttreeBox.update_folder(true);
+    expresso_mail_archive.listMessages();    
+    
+    //window.alert('logo depois: msglist.lengtht = ' + expresso_mail_archive.message_list.length);
+    if(expresso_mail_archive.message_list.length > 1){
+        write_msg(get_lang("The messages were deleted."));
+    }else{
+        write_msg(get_lang("The message was deleted."));
+    } 
+    */
+   
+    // This is necessary 'couse we can get a delete operation while an unarchive operation
+    // is still executing
+    expresso_mail_archive.message_list = expresso_mail_archive._temp_list;
+    expresso_mail_archive._temp_list = null;
+   
+}
+
+/**
+ *Archieve Delete Message Operation Failure
+ *
+ *@author Cassiano Dal Pizzol [cassiano.dalpizzol@serpro.gov.br]
+ *
+ */
+MailArchiver.prototype.deleteMessagesOperationFailure = function(error_message){
+    if(expresso_mail_archive.message_list.length > 1){
+        write_msg(get_lang("Error deleting messages.") + ' ' + error_message.getReturn());
+    }else{
+        write_msg(get_lang("Error deleting message.") + ' ' + error_message.getReturn());
+    }
+    
+    // This is necessary 'couse we can get a delete operation while an unarchive operation
+    // is still executing
+    expresso_mail_archive.message_list = expresso_mail_archive._temp_list;
+    expresso_mail_archive._temp_list = null;
+}
+
+/**
+ *Move message
+ *
+ *@param folder Folder where the message will be moved
+ *@param msgs_number Unique Id of the message
+ *
+ *@author Cassiano Dal Pizzol [cassiano.dalpizzol@serpro.gov.br]
+ *
+ */
+MailArchiver.prototype.moveMessages = function(folder, msgs_number){    
+    try{
+        document.getElementById('main_title').innerHTML = get_lang("Starting to move messages");
+        expresso_mail_archive.CreateMessageList(msgs_number);
+        expresso_mail_archive.folder_destination = folder;
+        //window.alert('invocando o moveMessages com lista = ' + expresso_mail_archive.message_list.length + ' e folder destino =' + folder + '.\nFolder corrente ï¿œ ' + expresso_mail_archive.currentfolder);
+        
+        if((expresso_mail_archive.message_list.length > 0) && (expresso_mail_archive.message_list[0] != '')) {
+            expresso_mail_archive.total_messages = expresso_mail_archive.message_list.length;
+            expresso_mail_archive.moveMessagesHandler();           
+        }
+        else{
+            write_msg(get_lang('No selected message.'));
+        }
+    }
+    catch (e){
+        expresso_mail_archive.getFaultInfo();
+    }
+}
+
+MailArchiver.prototype.moveMessagesHandler = function(){
+    
+    if((ttreeBox.name_folder != null) && (ttreeBox.name_folder != '') && (ttreeBox.name_folder.length >0)){
+        expresso_mail_archive.currentfolder = ttreeBox.name_folder.substr(6, ttreeBox.name_folder.length);
+    } 
+
+    if((expresso_mail_archive.message_list.length > 0) && (expresso_mail_archive.message_list[0] != '')) {
+        document.getElementById('main_title').innerHTML = get_lang('Moving message %1 of %2', expresso_mail_archive.messages_processed, expresso_mail_archive.total_messages);
+        
+        ArchiveServices.moveMessages(expresso_mail_archive.moveMessagesOperationOK, 
+                                     expresso_mail_archive.moveMessagesOperationFailure,
+                                     expresso_mail_archive.session.id, 
+                                     expresso_mail_archive.folder_destination,
+                                     new Array(expresso_mail_archive.message_list[parseInt(expresso_mail_archive.messages_processed)])
+                                     );
+    }
+    else{
+        window.alert('Moving handler messagelist caught:\n ' + expresso_mail_archive.message_list.length);        
+    }    
+}
+
+/**
+ *Move Message Ok
+ *
+ *@author Cassiano Dal Pizzol [cassiano.dalpizzol@serpro.gov.br]
+ *
+ */
+MailArchiver.prototype.moveMessagesOperationOK = function(){ 
+    //archivement allready done, update controll data and interface
+    expresso_mail_archive.messages_processed++;
+    
+    if(parseInt(expresso_mail_archive.messages_processed) < parseInt(expresso_mail_archive.total_messages)){
+       window.setTimeout(expresso_mail_archive.moveMessagesHandler,1);       
+    }
+    else{
+        document.getElementById('main_title').innerHTML = get_lang("All done. Message(s) moved successfully");
+        window.setTimeout("eval('document.getElementById(\"main_title\").innerHTML =\"Expresso Mail\"')",3000);
+        
+        //Tag messages moved
+        for(var i=0; i<expresso_mail_archive.message_list.length; i++){
+            var tlist = expresso_mail_archive.pattern.tagConfig(expresso_mail_archive.taglist, expresso_mail_archive.message_list[i], 0);
+            if(tlist != null){
+                try{
+                    expresso_mail_archive.drawdata = null;
+                    ArchiveServices.tagMessages(expresso_mail_archive.tagMessagesOperationOK, expresso_mail_archive.tagMessagesOperationFailure, expresso_mail_archive.session.id, tlist);
+                }
+                catch(e){
+                    expresso_mail_archive.getFaultInfo();
+                }
+            }            
+        }          
+        
+        expresso_mail_archive.update_counters = true;
+        expresso_mail_archive.messageslisted = new Array();
+        expresso_mail_archive.message_list = new Array();  
+
+        expresso_mail_archive.getFolderInfo(expresso_mail_archive.currentfolder);
+        expresso_mail_archive.getFolderInfo(expresso_mail_archive.folder_destination);
+        expresso_mail_archive.listMessages(expresso_mail_archive.currentfolder); 
+              
+
+        if(expresso_mail_archive.currentfolder.substr(0,6) == 'local_'){
+            ttreeBox.name_folder = expresso_mail_archive.currentfolder;
+        }
+        else{
+            ttreeBox.name_folder = "local_" + expresso_mail_archive.currentfolder;
+        }
+        //ttreeBox.update_folder(true);
+        expresso_mail_archive.resetObject();
+    }
+}
+
+/**
+ *Move Message Failure
+ *
+ *@author Cassiano Dal Pizzol [cassiano.dalpizzol@serpro.gov.br]
+ *
+ */
+MailArchiver.prototype.moveMessagesOperationFailure = function(error_message){
+    if(expresso_mail_archive.message_list.length > 1){
+        write_msg(get_lang("Error moving messages.") + ' ' + error_message.getReturn());
+    }else{
+        write_msg(get_lang("Error moving message.") + ' ' + error_message.getReturn());
+    } 
+}
+
+
+//getFolderList Operation
+MailArchiver.prototype.getFoldersList = function(basefolder){   
+    try{
+        connector.showProgressBar();
+        //window.alert('no expresso_mail_archive.getFoldersList com basefolder = ' + basefolder);
+        if(basefolder == 'local_root')
+            basefolder = "";
+        //window.alert('folderlist com basefolder = ' + basefolder);
+        //ArchiveServices.listFolders(expresso_mail_archive.getFoldersListOperationOK, expresso_mail_archive.getFoldersListOperationFailure, sessid, basefolder);
+        ArchiveServices.listFolders(expresso_mail_archive.getFoldersListOperationOK, expresso_mail_archive.getFoldersListOperationFailure, expresso_mail_archive.session.id, basefolder);
+        
+    }
+    catch (e){
+        expresso_mail_archive.getFaultInfo();
+    } 
+}
+
+//getFolderList callback OK
+MailArchiver.prototype.getFoldersListOperationOK = function(folderlist){
+    //Internal variable used to map all XML data return from WS invokated
+    var lfolders = new Array();
+    
+    //Mapping XML data to a handler data structure
+    if(folderlist.getReturn().length > 0){
+        var lfolders = new Array();
+        for(i=0; i<folderlist.getReturn().length; i++){
+            (folderlist.getReturn()[i].getFolderCount() > 0 ) ? folderChild = 1 : folderChild = 0;
+
+            //Store folder data at this format: {folder name, number of messages contained, folder has child nodes, folder id, folder parent id, folder full path}
+            //var folderData = new Array(folderlist.getReturn()[i].getName(), folderlist.getReturn()[i].getMessageCount(), folderChild, folderlist.getReturn()[i].getId(), folderlist.getReturn()[i].getParentId(), folderlist.getReturn()[i].getPath());
+            var folderData = {name: folderlist.getReturn()[i].getName(), messages: folderlist.getReturn()[i].getMessageCount(), haschild: folderChild, id: folderlist.getReturn()[i].getId(), parentid: folderlist.getReturn()[i].getParentId(), path: folderlist.getReturn()[i].getPath(), unseen: folderlist.getReturn()[i].getUnseenCount()};
+            //window.alert('folder ' + folderData.name + ' tem ' + folderData.messages + ' mensagens, sendo ' + folderData.unseen + ' nï¿œo lidas');
+            lfolders.push(folderData);
+        }
+
+        //Sets folders property at main object
+        expresso_mail_archive.folders = lfolders;
+        
+        //Sets current folder, only if no one is setted
+        //if(expresso_mail_archive.currentfolder == null){
+            if(expresso_mail_archive.folders[0]["parentid"] == "home"){ // change from "" to "home"(12/12/2011)
+                expresso_mail_archive.currentfolder = 'local_root';
+            }
+            else
+                expresso_mail_archive.currentfolder = expresso_mail_archive.folders[0]["parentid"];
+        //}
+        
+        
+        //Folders dumping :)
+        /*var strFolders = '---';
+        for (var w=0; w < expresso_mail_archive.folders.length; w++){
+            strFolders += '\nFolder ' + w + ' -->';
+            for (x in expresso_mail_archive.folders[w]){
+                strFolders += '\n----------' + x + ':= ' + expresso_mail_archive.folders[w][x];
+            }
+            strFolders += '\n<---';
+        }
+        strFolders += '\n---';
+        alert(lfolders.length + ' folders mapeados, com default = ' + expresso_mail_archive.currentfolder + '\nfolders list:\n\n' + strFolders);
+        */
+        //window.alert('foldersListOperationOK com drawdata:\n' + expresso_mail_archive.drawdata);
+        //If something UI related have been flagged, handle it
+        if (expresso_mail_archive.drawdata){
+            //window.alert('com drawdata e treeName = ' + expresso_mail_archive.drawdata.treeName);
+            expresso_mail_archive.drawFolderTree();
+        }
+    }
+    connector.hideProgressBar();
+}
+
+//getFolderList callback Fail
+MailArchiver.prototype.getFoldersListOperationFailure = function(error, http_msg){
+    window.alert('List folders mistake:' + error + '\nhttp_error = ' + http_msg);
+    connector.hideProgressBar();
+}
+
+//drawFolderTree operation, if requested to
+MailArchiver.prototype.drawFolderTree = function(){  
+    var localBaseName  = 'local_';
+    var objectTree = expresso_mail_archive.drawdata.treeObject;
+    var evalobjectTree = (typeof(expresso_mail_archive.drawdata.treeObject) == 'object') ? expresso_mail_archive.drawdata.treeObject: eval( '(' + expresso_mail_archive.drawdata.treeName + ')');
+        
+    if((expresso_mail_archive.drawdata.treeName == 'search_folders') && (Element('dftree_search_folders')))
+        evalobjectTree = folders_tree;
+    else{
+        if((expresso_mail_archive.drawdata.treeName == 'folders_tree') && (Element('dftree_folders_tree')))
+            evalobjectTree = folders_tree;
+    }
+        
+    //Add nodes to tree    
+    if(typeof(evalobjectTree) == 'object'){
+        //window.alert('caiu pra dentro, com ' + expresso_mail_archive.folders.length + ' folders.');
+        evalobjectTree._drawn = true;
+        if(expresso_mail_archive.folders.length > 0){
+            for(i=0; i<expresso_mail_archive.folders.length; i++){
+                var folder_caption;
+                //window.alert('iterando nodo ' + expresso_mail_archive.folders[i]["name"]);
+            
+                //Special folders treatment: Inbox, Outbox, Drafts, Sent and Trash folders               
+                if((expresso_mail_archive.folders[i]["name"] == 'Inbox') || (expresso_mail_archive.folders[i]["name"] == 'Outbox') || (expresso_mail_archive.folders[i]["name"] == 'Drafts') || (expresso_mail_archive.folders[i]["name"] == 'Sent') || (expresso_mail_archive.folders[i]["name"] == 'Trash')){
+                    folder_caption = get_lang(expresso_mail_archive.folders[i]["name"]);
+                }
+                else{
+                    folder_caption = expresso_mail_archive.folders[i]["name"];
+                }
+                
+                var onClickVar = '';                               
+                if((evalobjectTree.name != "folders_tree") && (evalobjectTree.name != "search_folders")){
+                    onClickVar =  "change_folder('"+ localBaseName + expresso_mail_archive.folders[i]["id"] +"','"+ localBaseName + expresso_mail_archive.folders[i]["id"]+"', '" + expresso_mail_archive.drawdata.treeName + "')";
+                    if(expresso_mail_archive.folders[i]["unseen"] != "0")
+                        folder_caption = folder_caption + '<font style=color:red>&nbsp(</font><span id="dftree_local_'+expresso_mail_archive.folders[i]["id"]+'_unseen" style=color:red>'+expresso_mail_archive.folders[i]["unseen"]+'</span><font style=color:red>)</font>'
+                }
+     
+                var n_demo = new dNode({id: localBaseName + expresso_mail_archive.folders[i]["id"], caption: folder_caption, onClick: onClickVar, plusSign:expresso_mail_archive.folders[i]["haschild"]});
+                //var n_demo = new dNode({id: localBaseName + expresso_mail_archive.folders[i]["name"], caption: folder_caption, onClick: "change_folder('"+ localBaseName + expresso_mail_archive.folders[i]["name"] +"','"+ localBaseName + expresso_mail_archive.folders[i]["name"]+"', '" + expresso_mail_archive.drawdata.treeName + "')", plusSign:expresso_mail_archive.folders[i]["haschild"]});
+            
+                //Adjust the id node names
+                if(expresso_mail_archive.currentfolder){
+                    if(expresso_mail_archive.currentfolder.substr(0,5) != 'local'){
+                        evalobjectTree.add(n_demo, localBaseName + expresso_mail_archive.currentfolder);
+                    }
+                    else{
+                        evalobjectTree.add(n_demo,expresso_mail_archive.currentfolder);
+                    }
+                }
+                else {
+                    expresso_mail_archive.currentfolder = 'local_root';
+                    evalobjectTree.add(n_demo,expresso_mail_archive.currentfolder);
+                }            
+            }
+        }
+        //Set special folders icons   
+        if (document.getElementById('llocal_senttree_folders')){
+            document.getElementById('llocal_senttree_folders').style.backgroundImage="url(../phpgwapi/templates/"+template+"/images/foldertree_sent.png)";
+        }
+        if (document.getElementById('llocal_trashtree_folders')){
+            document.getElementById('llocal_trashtree_folders').style.backgroundImage="url(../phpgwapi/templates/"+template+"/images/foldertree_trash.png)";
+        }
+        if (document.getElementById('llocal_draftstree_folders')){
+            document.getElementById('llocal_draftstree_folders').style.backgroundImage="url(../phpgwapi/templates/"+template+"/images/foldertree_draft.png)";
+        }
+        if (document.getElementById('llocal_outboxtree_folders')){
+            document.getElementById('llocal_outboxtree_folders').style.backgroundImage="url(../phpgwapi/templates/"+template+"/images/foldertree_sent.png)";
+        }         
+    }
+    else {
+        //does nothing
+    }
+}
+
+//getFaultInfo operation
+MailArchiver.prototype.getFaultInfo = function(){
+    try{
+        //ArchiveServices.getFaultInfo(expresso_mail_archive.getFaultInfoOperationOK, expresso_mail_archive.getFaultInfoOperationFailure, sessid);
+         ArchiveServices.getFaultInfo(expresso_mail_archive.getFaultInfoOperationOK, expresso_mail_archive.getFaultInfoOperationFailure, expresso_mail_archive.session.id);
+         connector.hideProgressBar();
+    }    
+    catch(e){
+        if(!expresso_mail_archive.enabled)
+            write_msg(get_lang('MailArchiver does not seems to be running or installed at this workstation, local messages are disabled. Check it out!'),false);
+        else{
+            window.clearInterval(expresso_mail_archive.timer);
+            write_msg(get_lang('There is something wrong with MailArchiver environment. Contact you support'),true);
+            expresso_mail_archive.enabled = false;
+            expresso_mail_archive.turnOffLocalTreeStructure();
+        }
+        connector.hideProgressBar();
+    }
+}
+
+//getFaultInfo callback OK
+MailArchiver.prototype.getFaultInfoOperationOK = function(faultinfo){
+    try{
+        write_msg(get_lang('MailArchiver remote service reports the following error:', true) + faultinfo.getReturn().getSoapFaultString());
+    } catch(e){
+        write_msg(get_lang('The archive service reports a unknown error. Try to refresh your browser screen', true));
+    }
+    expresso_mail_archive.resetObject();
+    expresso_mail_archive.archivefolder = null;
+    window.setTimeout("eval('document.getElementById(\"main_title\").innerHTML =\"Expresso Mail\"')",3000);        
+    connector.purgeCache();
+}
+
+//getFaultInfo callback Fail
+MailArchiver.prototype.getFaultInfoOperationFailure = function(errorCode, errorDesc){
+    try{
+        write_msg(get_lang('SoapFault capture fails at:' + errorCode + ' | ' + errorDesc, true));
+    } catch(e){
+        write_msg(get_lang('Service error mapping', true));
+    }    
+}
+
+//createFolder operation
+MailArchiver.prototype.createFolder = function(parentFolder, folderName){
+    
+    try{
+        //ArchiveServices.createFolder(expresso_mail_archive.createFolderOperationOK, expresso_mail_archive.createFolderOperationFailure, sessid, parentFolder, folderName);
+        ArchiveServices.createFolder(expresso_mail_archive.createFolderOperationOK, expresso_mail_archive.createFolderOperationFailure, expresso_mail_archive.session.id, parentFolder, folderName);
+    }
+    catch (e){
+        expresso_mail_archive.getFaultInfo();
+    } 
+    
+}
+
+//createFolder callback OK
+MailArchiver.prototype.createFolderOperationOK = function (folderObject){
+    //window.alert('callback de createfolderoperationok');
+    draw_tree_local_folders();
+    expresso_mail_archive.drawdata.treeObject._drawn = true;
+    ttreeBox.update_folder();    
+}
+
+//createFolder callback Fail
+MailArchiver.prototype.createFolderOperationFailure = function (message){
+    window.alert('Folder creation fails...\n->' + message.getReturn()); 
+}
+
+//deleteFolder operation
+MailArchiver.prototype.deleteFolder = function(folderName){
+    try{
+        ArchiveServices.deleteFolder(expresso_mail_archive.deleteFolderOperationOK, expresso_mail_archive.deleteFolderOperationFailure, expresso_mail_archive.session.id, folderName, true);
+    }
+    catch (e){
+        expresso_mail_archive.getFaultInfo();
+    } 
+    
+}
+
+//deleteFolder callback OK
+MailArchiver.prototype.deleteFolderOperationOK = function (folderObject){
+    write_msg(get_lang("The local folder \"%1\" was successfully removed", expresso_mail_archive.drawdata.folderName));
+    connector.purgeCache();
+    ttreeBox.name_folder = "root";
+    ttreeBox.update_folder();
+    draw_tree_local_folders();
+    ttreeBox.update_folder();	
+}
+
+//deleteFolder callback Fail
+MailArchiver.prototype.deleteFolderOperationFailure = function (message){
+    expresso_mail_archive.getFaultInfo();
+}
+
+//renameFolder operation
+MailArchiver.prototype.renameFolder = function(folderId, newFolderName){
+    try{
+        //ArchiveServices.renameFolder(expresso_mail_archive.renameFolderOperationOK, expresso_mail_archive.renameFolderOperationFailure, sessid, folderId, newFolderName);
+        ArchiveServices.renameFolder(expresso_mail_archive.renameFolderOperationOK, expresso_mail_archive.renameFolderOperationFailure, expresso_mail_archive.session.id, folderId, newFolderName);
+    }
+    catch (e){
+        expresso_mail_archive.getFaultInfo();
+    } 
+    
+}
+
+//renameFolder callback OK
+MailArchiver.prototype.renameFolderOperationOK = function (returnService){
+    var evalobjectTree = eval(expresso_mail_archive.drawdata.treeName);
+    evalobjectTree.update_folder();
+}
+
+//renameFolder callback Fail
+MailArchiver.prototype.renameFolderOperationFailure = function (ServiceFault){
+    expresso_mail_archive.getFaultInfo();
+}
+
+//getFolderInfo operation
+MailArchiver.prototype.getFolderInfo = function (folderId){
+    try{
+        if(folderId == 'local_root')
+            folderId = "";
+        ArchiveServices.getFolderInfo(expresso_mail_archive.getFolderInfoOperationOK, expresso_mail_archive.getFolderInfoOperationFailure, expresso_mail_archive.session.id, folderId);
+    }
+    catch (e){
+        expresso_mail_archive.getFaultInfo();
+    }     
+}
+
+//getFolderInfo callback OK
+MailArchiver.prototype.getFolderInfoOperationOK = function(returnService){
+   var folder_info = {id : returnService.getReturn().getId(), name : returnService.getReturn().getName(), parent : returnService.getReturn().getParentId(), numfolders: returnService.getReturn().getFolderCount(), nummessages: returnService.getReturn().getMessageCount(), unseen: returnService.getReturn().getUnseenCount(), path: returnService.getReturn().getPath()};
+   expresso_mail_archive.folder = folder_info;
+   expresso_mail_archive.updateCounter();
+}
+
+//getFolderInfo callback Fail
+MailArchiver.prototype.getFolderInfoOperationFailure = function (ServiceFault){
+    window.alert('getFolderInfo service fails...\n->' + ServiceFault.getReturn()); 
+    expresso_mail_archive.folder_data = true;
+}
+
+function foo(){
+    var a = 0;
+    a++;
+}
+
+//listMessages operation
+//OLD local_messages.prototype.get_local_range_msgs = function(folder,msg_range_begin,emails_per_page,sort,sort_reverse,search,preview_msg_subject,preview_msg_tip) {
+//ONLINE messages_proxy.prototype.messages_list = function(folder,msg_range_begin,emails_per_page,sort_box_type,search_box_type,sort_box_reverse,preview_msg_subject,preview_msg_tip,call_back,tree_name) {
+//sys call = proxy_mensagens.messages_list(current_folder,1,preferences.max_email_per_page,sort,search,sort_box_reverse,preferences.preview_msg_subject,preferences.preview_msg_tip,handler_draw_box);
+MailArchiver.prototype.listMessages = function(){
+    try{
+        connector.showProgressBar();
+        var getcurrent = get_current_folder();       
+        //tree_folders.getNodeById(get_current_folder())._select();
+        var folderid = this.currentfolder; //getcurrent.substr(6,getcurrent.length);
+        var objfolder = new Object();
+        objfolder.folder = folderid;        
+        //var testing_data_xml = '<?xml version="1.0" encoding="UTF-8"?><query lowerIndex="0" upperIndex="50"><folder id="'+folderid+'"/><order asc="date"/><order desc="subject"/></query>';
+        //var testing_data_json_mapped = '{"query":{"@lowerIndex":"0", "@upperIndex":"50", "folder":[{"@id":"'+folderid+'"}], "order":[{"@asc":"date", "@desc":"subject"}]}}';
+        var query_data = expresso_mail_archive.queryconfig.query(objfolder);
+        expresso_mail_archive.getFolderInfo(folderid);
+        expresso_mail_archive.currentfolder = folderid;
+        
+        //ArchiveServices.listMessages(expresso_mail_archive.listMessagesOperationOK, expresso_mail_archive.listMessagesOperationFailure, sessid, query_data);
+        ArchiveServices.listMessages(expresso_mail_archive.listMessagesOperationOK, expresso_mail_archive.listMessagesOperationFailure, expresso_mail_archive.session.id, query_data);
+    }
+    catch (e){
+        expresso_mail_archive.getFaultInfo();
+    }
+}
+
+//listMessages callback OK
+MailArchiver.prototype.listMessagesOperationOK = function(returnService){
+    var msglist = new Array();
+    expresso_mail_archive.ServiceReturnObjectList = new Array();
+    //window.alert('messages data\n\n' + print_r(returnService.getReturn().length));
+    /*window.alert('Dados da mensagem:\n->From ' + returnService.getReturn()[0].getFrom()
+                                      +'\n->To ' + returnService.getReturn()[0].getTo()
+                                      +'\n->Subject ' + returnService.getReturn()[0].getSubject()
+                                      +'\n->Date ' + returnService.getReturn()[0].getDate()
+                                      +'\n->Date ' + returnService.getReturn()[0].getSize()
+                                      +'\n->ID ' + returnService.getReturn()[0].getId());
+    */
+    var msg_unseen_count = 0;
+    for(var i=0; i< returnService.getReturn().length; i++){
+        var ExpSerialized = expresso_mail_archive.pattern.toExpressoHeader(returnService.getReturn()[i]);
+        var msgitem = connector.unserialize(ExpSerialized);
+        //counts unseen messages
+        if(msgitem.Unseen == 'U')
+            msg_unseen_count++;
+      
+        // fernando
+        // correÃ§Ã£o para por no padrao certo, se nao fizer isso buga a listagem
+        msgitem_temp = msgitem.msg_sample;
+        msgitem.msg_sample = { "body": msgitem_temp };
+        msglist.push(msgitem);//usando connector.unserialize sobre o header mapeado no layout abaixo
+        expresso_mail_archive.ServiceReturnObjectList.push(returnService.getReturn()[i]); //add each one service return data into this embeded object array
+    }
+    var tab_counters = expresso_mail_archive.getFolderCounters();
+    
+    //msglist["num_msgs"] = returnService.getReturn().length;
+    //window.alert('service return length = ' + returnService.getReturn().length + '\nfolder.nummessages = ' + expresso_mail_archive.folder.nummessages);
+    
+    //window.alert('folder counters:\n' + print_r(tab_counters));
+
+    //msglist["num_msgs"] = expresso_mail_archive.folder.nummessages;
+    msglist["num_msgs"] = tab_counters[0];
+    //window.alert('num msgs');
+    //(expresso_mail_archive.folder.unseen) ? msglist["tot_unseen"] = expresso_mail_archive.folder.unseen : msglist["tot_unseen"] = 0;
+    (tab_counters[1] != 0) ? msglist["tot_unseen"] = tab_counters[1] : msglist["tot_unseen"] = 0;
+//    window.alert('num unseen');
+    //window.alert('print_r\n\n' + print_r(msglist));
+   
+    //expresso_mail_archive.updateCounter(returnService.getReturn().length, msg_unseen_count);    
+    expresso_mail_archive.messageslisted = msglist;
+    expresso_mail_archive.drawdata = {messagesList:msglist};
+    //expresso_mail_archive.drawMessagesList();
+    //expresso_mail_archive.drawMessagesList(returnService.getReturn().length, msg_unseen_count);
+    //expresso_mail_archive.drawMessagesList(msglist["num_msgs"], msg_unseen_count);
+    //add by fernando: desenha a lista de mensagens no expressomail
+    expresso_mail_archive.drawMessagesList(msglist["num_msgs"], msglist['tot_unseen']);
+    connector.hideProgressBar();
+}
+
+//listMessages callback Fail
+MailArchiver.prototype.listMessagesOperationFailure = function(ServiceFault){
+    window.alert('listmessages FALHOU!\n' + ServiceFault.getReturn());
+}
+
+MailArchiver.prototype.getFolderMessagesNumber = function(){
+    var n = 0;
+    for(var i=0; i < expresso_mail_archive.folders.length; i++){
+        if(expresso_mail_archive.folders[i]["id"] == expresso_mail_archive.currentfolder){
+            n = expresso_mail_archive.folders[i]["messages"];
+        }
+    }
+    return(n);
+}
+
+MailArchiver.prototype.drawMessagesList = function(msgtot, msgunseen){
+    //window.alert('no drawMessagesList com folder = ' + expresso_mail_archive.currentfolder  + '\nudatecounters = ' + expresso_mail_archive.udatecounters);
+    var data_to_draw = expresso_mail_archive.drawdata.messagesList;  
+    //window.alert('data to draw =  ' + data_to_draw.length + '\ndata_to_draw[0].from.full = ' + print_r(data_to_draw));
+    //window.alert('Current folder = ' + expresso_mail_archive.currentfolder + ' com ' + expresso_mail_archive.folders.length + ' folders.');
+    var fcaption = expresso_mail_archive.currentfolder;
+    
+    /*for (var w=0; w < expresso_mail_archive.folders.length; w++){
+        //window.alert('comparando folder "' + expresso_mail_archive.folders[w]["id"] + '" com o corrente "' + expresso_mail_archive.currentfolder + '"\nEnquanto que o folder.name obtido do getfolderinfo Ã© "' + expresso_mail_archive.folder.name + '"');
+        if(expresso_mail_archive.folders[w]["id"] == expresso_mail_archive.currentfolder){
+            fcaption = expresso_mail_archive.folders[w]["name"];
+            window.alert('folder found!\n -> ' + fcaption);
+            break;
+        }
+    }*/
+    
+    var fcaption = expresso_mail_archive.folder.name;
+    
+    /*window.alert('fcaption = ' + fcaption);
+    var udate_tree_folder = expresso_mail_archive.drawdata.treefolder;
+    window.alert('atualizar contador da ï¿œrvore : ' + udate_tree_folder);
+    var udate_tab_folder = expresso_mail_archive.drawdata.tabfolder;
+    window.alert('atualizar contador da tab : ' + udate_tab_folder);*/
+    //var folder_num_msgs = expresso_mail_archive.getFolderMessagesNumber();
+    var folder_num_msgs = expresso_mail_archive.folder.nummessages;
+    //window.alert('num = ' + folder_num_msgs);
+    alternate_border(0);
+    Element("border_id_0").innerHTML = "&nbsp;" + lang_folder(fcaption) + '&nbsp;<font face="Verdana" size="1" color="#505050">[<span id="new_m">&nbsp;</span> / <span id="tot_m"></span>]</font>';
+    draw_box(data_to_draw, 'local_' + expresso_mail_archive.currentfolder, true);
+    //draw_paging(expresso_mail_archive.drawdata.messagesList.length);
+    //draw_paging(preferences.max_email_per_page);
+    draw_paging(folder_num_msgs);    
+    if(((msgtot) && (msgunseen)) || ((parseInt(msgtot)==0)&&(parseInt(msgunseen)==0))){
+        expresso_mail_archive.updateCounter(msgtot, msgunseen);
+    }
+    else{
+        Element("tot_m").innerHTML = folder_num_msgs;
+        Element('new_m').innerHTML = data_to_draw['tot_unseen'] ? '<font color="RED">'+data_to_draw['tot_unseen']+'</font>' : 0;
+    }
+}
+
+MailArchiver.prototype.getMessageHeaders = function(msgId){
+    var msgfound = false;
+    var headerMsg;
+        
+    //Get message header info, from message list operation previously invoked
+    for (var w=0; w < expresso_mail_archive.messageslisted.length; w++){
+        if(expresso_mail_archive.messageslisted[w]["msg_number"] == msgId){
+            headerMsg = expresso_mail_archive.messageslisted[w];
+            msgfound = true;
+            break;
+        }
+    }
+    
+    //Message does not exists at default message list previouslly invoked. Then, will be tryed to get it at possible search criteria existing tab.
+    if(!msgfound){
+        //Try to discover if desired message is at a search local data tab
+        if(currentTab.toString().indexOf("search_local") != -1){
+	    var msgId2 = msgId.substr(0,msgId.indexOf("_s"));            
+            for (var w=0; w < expresso_mail_archive.search_message_list.length; w++){
+                if(expresso_mail_archive.search_message_list[w]["msg_number"] == msgId2){
+                    headerMsg = expresso_mail_archive.search_message_list[w];
+                    msgfound = true;
+                    break;
+                }
+            }
+       
+        }
+    }
+    
+    //The message was found, as well the her headers
+    if(msgfound){
+        expresso_mail_archive.currentheaders = headerMsg;
+        return(headerMsg);
+    }
+    //The message was not found   
+    else{
+        headerMsg = null;
+        expresso_mail_archive.currentheaders = headerMsg;        
+        return;
+    }
+}
+    
+
+MailArchiver.prototype.getMessage = function(msgdata){
+    try{
+        if((msgdata.length <= 0) || (msgdata == null)){
+            return;
+        }
+        expresso_mail_archive.currentmessage = expresso_mail_archive.getMessageHeaders(msgdata)["msg_number"];
+        ArchiveServices.getMessageBody(expresso_mail_archive.getMessageOperationOK, expresso_mail_archive.getMessageOperationFailure, expresso_mail_archive.session.id, expresso_mail_archive.currentmessage);
+    }
+    catch(e){
+        expresso_mail_archive.getFaultInfo();
+    }
+}
+
+MailArchiver.prototype.getMessageOperationOK = function(returnService){    
+    if(returnService.getReturn().length <= 0){
+        window.alert('Oh no: service return data is zero length...');
+        return;
+    }    
+    var msgBody = returnService.getReturn();
+    //var msgHeaders = expresso_mail_archive.getMessageHeaders(expresso_mail_archive.currentmessage);
+    var msgHeaders = expresso_mail_archive.currentheaders;
+    var expSerializedMessage = expresso_mail_archive.pattern.toExpressoMail(msgHeaders, msgBody);
+    
+    // Unset \\Unseen flag
+    for (i=0; i < expresso_mail_archive.messageslisted.length; i++)
+    {
+        if (expresso_mail_archive.messageslisted[i].msg_number == expresso_mail_archive.currentmessage)
+        {
+            expresso_mail_archive.messageslisted[i]['Unseen'] = '';
+        }
+    }
+    
+    //window.alert('Serialized data\n\n' + print_r(expSerializedMessage));
+    //expresso_mail_archive.showEmbededImage(msgBody);
+    show_msg(expSerializedMessage);    
+    window.setTimeout("expresso_mail_archive.setEmbeddedLink()", 1);
+}
+MailArchiver.prototype.getMessageOperationFailure = function(ServiceFault){
+    window.alert('Message fails do be loaded.');
+}
+
+/*
+ *getMessageServiceObjet: search for a remote webservice object in memory to use
+ *draw interface. Look at messages list first, then, search list. Returns desired
+ *object, or null (if not found)
+ **/
+MailArchiver.prototype.getMessageServiceObject = function(msgid){
+    var flag_found = false;
+    var rtn_obj = null;
+    
+    //Message list
+    if(expresso_mail_archive.ServiceReturnObjectList != null){
+        for(var i=0; i < expresso_mail_archive.ServiceReturnObjectList.length; i++){
+            if (expresso_mail_archive.ServiceReturnObjectList[i].getId() == msgid){
+                flag_found = true;
+                rtn_obj = expresso_mail_archive.ServiceReturnObjectList[i];
+            }
+        }
+    }
+       
+    //Search list
+    if(!flag_found){
+        if(expresso_mail_archive.ServiceReturnObjectSearch != null){
+            for(var i=0; i < expresso_mail_archive.ServiceReturnObjectSearch.length; i++){
+                if (expresso_mail_archive.ServiceReturnObjectSearch[i].getId() == msgid){
+                    flag_found = true;
+                    rtn_obj = expresso_mail_archive.ServiceReturnObjectSearch[i];
+                }
+            }
+        }        
+    }
+    return(rtn_obj);
+}
+
+
+MailArchiver.prototype.tagMessage = function(taglist){
+    try{
+        if(!taglist)
+            taglist = expresso_mail_archive.taglist;
+        //ArchiveServices.tagMessages(expresso_mail_archive.tagMessagesOperationOK, expresso_mail_archive.tagMessagesOperationFailure, sessid, taglist);
+        ArchiveServices.tagMessages(expresso_mail_archive.tagMessagesOperationOK, expresso_mail_archive.tagMessagesOperationFailure, expresso_mail_archive.session.id, taglist);
+    } catch (e){
+        //window.alert('TagMessage fails at: ' + (e.description)?e.description:e);
+        expresso_mail_archive.getFaultInfo();
+    }     
+}
+
+MailArchiver.prototype.tagMessagesOperationOK = function(serviceData){
+    //ajustar os contadores de lida/nao lida etc...
+    if((expresso_mail_archive.currenttag != '') && (expresso_mail_archive.tagmsg == true)){
+        write_msg(get_lang('Messages marked as "%1"', get_lang(expresso_mail_archive.currenttag)));
+        expresso_mail_archive.tagmsg = false;
+    }
+    
+    expresso_mail_archive.currenttag = "";
+    expresso_mail_archive.taglist = "";
+
+    //window.alert('expresso_mail_archive.folder_origin = ' + expresso_mail_archive.folder_origin  + '\nexpresso_mail_archive.current_folder = ' + get_current_folder());
+
+    if((expresso_mail_archive.drawdata) && (get_current_folder() == expresso_mail_archive.folder_origin)){
+        expresso_mail_archive.drawFolderTree();
+        expresso_mail_archive.listMessages();
+        //expresso_mail_archive.drawdata = null;
+        window.clearTimeout(expresso_mail_archive.progressbar);
+    }
+    else{
+        /*
+        connector.purgeCache();
+        ttreeBox.name_folder = "local_" + expresso_mail_archive.currentfolder;
+        draw_tree_local_folders();
+        ttreeBox.update_folder(true);*/
+    }
+}
+
+MailArchiver.prototype.tagMessagesOperationFailure = function(serviceData){
+    var str_tag_fail = serviceData.getReturn();
+    expresso_mail_archive.getFaultInfo();
+}
+
+MailArchiver.prototype.download_all_msg_attachments = function(msgid){
+    var default_format = 'zip'; //tar, jar, gzip, bz2 supports too
+    var url = expresso_mail_archive.pattern.download_compressed_attachments(msgid, default_format);
+    //window.open(url,"mywindow","width=1,height=1,scrollbars=no");
+    location.href = url;
+}
+
+MailArchiver.prototype.download_msg_source = function (format){
+    //Default export format is zip
+    if(!format)
+        format = 'zip';
+    
+    expresso_mail_archive.exportformat = format;
+    
+    if (openTab.type[currentTab] > 1){
+	var msgs_id = currentTab.substring(0,currentTab.length-2,currentTab);
+    }else{
+	var msgs_id = get_selected_messages();
+    }    
+    
+    var vetmsg = msgs_id.split(",");
+    if(vetmsg.length > 0){
+        var arr_msg = new Array();
+        for(var k=0; k<vetmsg.length; k++){
+            arr_msg.push(vetmsg[k]);
+        }            
+    }
+    else var arr_msg = new Array(msgs_id);
+   
+    var messages_array = {"format": format, "type": 'messages', "messages": arr_msg};
+    var texp = expresso_mail_archive.pattern.zipConfig(messages_array);
+    
+    if(texp != null){
+        try{
+            //ArchiveServices.zipMessages(expresso_mail_archive.download_mgs_sourceOperationOK, expresso_mail_archive.download_msg_sourceOperationFailure, sessid, texp);
+            ArchiveServices.zipMessages(expresso_mail_archive.download_mgs_sourceOperationOK, expresso_mail_archive.download_msg_sourceOperationFailure, expresso_mail_archive.session.id, texp);
+        }
+        catch(e){
+            //window.alert('Export local messages fails: ' + (e.description)?e.description:e);
+            expresso_mail_archive.getFaultInfo();
+        }
+    }
+}
+
+MailArchiver.prototype.download_mgs_sourceOperationOK = function(serviceData){
+  if(serviceData.getReturn().length > 0){
+      window.location.href = mail_archive_protocol + "://" + mail_archive_host + ":" + mail_archive_port + "/temp/mails_" + serviceData.getReturn() + '.' + expresso_mail_archive.exportformat;
+  }
+  else{
+      
+  }
+}
+
+MailArchiver.prototype.download_mgs_sourceOperationFailure = function(serviceFail){
+  window.alert('ZipMessages FAIL:' + serviceFail.getReturn());  
+}
+
+MailArchiver.prototype.export_local_messages = function(folderid, recursive, format){
+    //Default export format is zip
+    if(!format)
+        format = 'zip';
+    
+    expresso_mail_archive.exportformat = format;    
+    if(folderid == 'root')//export root local folder
+        var messages_array = {"format": format, "type": 'folder', "recursive" : true, "messages": ""};
+    else//export local folder entry
+        var messages_array = {"format": format, "type": 'folder', "recursive" : recursive, "messages": folderid};
+    var texp = expresso_mail_archive.pattern.zipConfig(messages_array);
+    
+    if(texp != null){
+        try{
+            ArchiveServices.zipMessages(expresso_mail_archive.download_mgs_sourceOperationOK, expresso_mail_archive.download_msg_sourceOperationFailure, expresso_mail_archive.session.id, texp);
+        }
+        catch(e){
+            //window.alert('Export local messages fails: ' + (e.description)?e.description:e);
+            expresso_mail_archive.getFaultInfo();
+        }
+    }    
+}
+
+MailArchiver.prototype.updateCounter = function(a,b){
+    //window.alert('updateCounter reached');
+    if(((a) && (b)) || ((parseInt(a)==0)&&(parseInt(b)==0))){
+        Element("tot_m").innerHTML = a;
+        Element('new_m').innerHTML = (b>0) ? '<font color="RED">'+b+'</font>' : 0; 
+        return;
+    }
+    
+    if(expresso_mail_archive.update_counters == true){
+        connector.purgeCache();
+        var elm_tree = Element('llocal_'+expresso_mail_archive.folder.id+'tree_folders');
+        
+        if(elm_tree){
+        
+        //search appropriate "unseen" span to handle with
+        for(var j=0; j<elm_tree.childNodes.length; j++){
+            if (elm_tree.childNodes[j].nodeName.toLowerCase() == 'span'){
+                var elm = elm_tree.childNodes[j];
+                break;
+            }        
+        }
+    
+        if(expresso_mail_archive.folder.unseen > 0){
+            if (elm){
+                elm.innerHTML = expresso_mail_archive.folder.unseen;
+            }                
+            else{
+                var htm_el = document.createElement('font');
+                htm_el.style.color = 'red';
+                document.getElementById('llocal_'+expresso_mail_archive.folder.id+'tree_folders').appendChild(htm_el);    
+                htm_el.innerHTML = '&nbsp(';
+                
+                var spn_el = document.createElement('span');
+                spn_el.id = 'dftree_'+expresso_mail_archive.folder.id+'_unseen';
+                spn_el.style.color = 'red';
+                document.getElementById('llocal_'+expresso_mail_archive.folder.id+'tree_folders').appendChild(spn_el);
+                spn_el.innerHTML = expresso_mail_archive.folder.unseen;
+                
+                var htm2_el = document.createElement('font');
+                htm2_el.style.color = 'red';
+                document.getElementById('llocal_'+expresso_mail_archive.folder.id+'tree_folders').appendChild(htm2_el);    
+                htm2_el.innerHTML = ')';
+            }
+        }
+        else{
+            if(elm){
+                var spn = elm.parentNode.parentNode;
+                elm.parentNode.removeChild(elm.previousSibling);
+                elm.parentNode.removeChild(elm.nextSibling);
+                elm.parentNode.removeChild(elm);
+            }
+        }
+
+        //reset pointer to re-do working to move messages (2 folders envolved)
+        if (expresso_mail_archive.folder_destination != null){
+            if(expresso_mail_archive.currentfolder == expresso_mail_archive.folder_destination){
+                expresso_mail_archive.update_counters = false;
+            }
+            else{
+                //window.alert('aqui, queima o folder_destination');
+                //expresso_mail_archive.folder_destination = null;
+            }            
+        }
+        else{
+            expresso_mail_archive.update_counters = false;
+        }
+    }
+    }
+    //no counter needs 
+    else return;
+}
+
+MailArchiver.prototype.getBase64PartData = function(partid, field){
+    var spid = new String(partid);
+    if(parseInt(spid.length) > 0){
+        expresso_mail_archive.tmp_att_datasource = field;
+        try{
+            //ArchiveServices.getRawBinaryBody(expresso_mail_archive.getBase64PartDataOK, expresso_mail_archive.getBase64PartDataFailure, sessid, partid);
+            ArchiveServices.getRawBinaryBody(expresso_mail_archive.getBase64PartDataOK, expresso_mail_archive.getBase64PartDataFailure, expresso_mail_archive.session.id, partid);
+        }
+        catch(e){
+            //window.alert('Fail to getRawBinaryBody data from part id ' + partid + ':\n' + (e.description)?e.description:e);
+            expresso_mail_archive.getFaultInfo();
+        }
+    }
+    else {
+        return(null);
+    }
+}
+
+MailArchiver.prototype.getBase64PartDataOK = function(serviceData){
+    var encdata = serviceData.getReturn();
+    if(encdata.length <= 0){
+        window.alert('Oh no: service return data is zero length...');
+        this.tmp_att_data = null;
+    }    
+    else{
+        expresso_mail_archive.tmp_att_datasource.value = encdata;
+    }
+}
+
+MailArchiver.prototype.getBase64PartDataFailure = function(serviceReturn){
+    window.alert('There are erros on getting binary data part:' + serviceReturn.getReturn());
+}
+
+MailArchiver.prototype.search = function(folders,fields){
+    try{
+        connector.showProgressBar();
+        if((folders) && (fields)){
+            expresso_mail_archive.search_queryconfig.reset();
+            var folderlist = expresso_mail_archive.search_queryconfig.pharseFolders(folders);
+            var filters = eval('(' + expresso_mail_archive.queryconfig.pharseSearchFields(fields) + ')');
+
+            if(folderlist.indexOf("#") != -1)
+                filters.folder = folderlist.substr(0, folderlist.indexOf("#"));
+            else
+                filters.folder = folderlist;
+            if(folderlist.toLowerCase().indexOf("#recursive") != -1)
+                expresso_mail_archive.search_queryconfig.folder_recursive = true;
+            else
+                expresso_mail_archive.search_queryconfig.folder_recursive = false;
+
+            expresso_mail_archive.querydata = expresso_mail_archive.search_queryconfig.query(filters);
+            
+            //var query_data = '<?xml version="1.0" encoding="UTF-8"?><query subject="teste"><folder id="inbox"/><order asc="date"/></query>';
+            ArchiveServices.listMessages(expresso_mail_archive.searchOperationOK, expresso_mail_archive.searchOperationFailure, expresso_mail_archive.session.id, expresso_mail_archive.querydata);        
+        }
+        //changing order view criteria (sorting result)
+        else{    
+            ArchiveServices.listMessages(expresso_mail_archive.searchOperationOK, expresso_mail_archive.searchOperationFailure, expresso_mail_archive.session.id, expresso_mail_archive.querydata);        
+        }
+    }catch (e){
+        expresso_mail_archive.getFaultInfo();
+    }
+}
+
+MailArchiver.prototype.searchOperationOK = function(returnService){
+    
+    if(returnService.getReturn().length > 0){
+        var msglist = new Array();
+        var msglist2 = new Array();
+        expresso_mail_archive.ServiceReturnObjectSearch = new Array();
+
+        for(var i=0; i< returnService.getReturn().length; i++){
+            var ExpSerialized = expresso_mail_archive.pattern.toExpressoSearchHeader(returnService.getReturn()[i]);
+            var ExpSerialized2 = expresso_mail_archive.pattern.toExpressoHeader(returnService.getReturn()[i]);
+            var msgitem = connector.unserialize(ExpSerialized);
+            var msgitem2 = connector.unserialize(ExpSerialized2);
+      
+            msglist.push(msgitem);//usando connector.unserialize sobre o header mapeado no layout abaixo
+            msglist2.push(msgitem2);
+            expresso_mail_archive.ServiceReturnObjectSearch.push(returnService.getReturn()[i]); //add each one service return data into this embeded object array
+            
+        }
+        msglist["num_msgs"] = returnService.getReturn().length;
+        msglist2["num_msgs"] = returnService.getReturn().length;
+            
+        //expresso_mail_archive.queryresult = msglist;        
+        expresso_mail_archive.search_queryresult = msglist;    
+        //expresso_mail_archive.messageslisted = msglist2;
+        expresso_mail_archive.search_message_list = msglist2;
+        //window.alert('temos ' + expresso_mail_archive.search_message_list.length + ' mensagens de resultado da pesquisa mapeadas em memï¿œria');
+    }
+    else{expresso_mail_archive.messageslisted =
+        expresso_mail_archive.queryresult = null;
+    } 
+    connector.hideProgressBar();
+}
+
+MailArchiver.prototype.searchOperationFailure = function(){
+    write_msg(get_lang('MailArchiver search operation fails', true));
+    connector.hideProgressBar();
+}
+
+MailArchiver.prototype.getAuthId = function(){
+    var handler_get_logon = function(data){
+        if(data){
+            expresso_mail_archive.balancerid = data[0];
+            expresso_mail_archive.sessionid = data[1];
+            expresso_mail_archive.logonid = new Array(data[2],data[3]);
+            expresso_mail_archive.login();
+        }
+        else{
+            window.alert('Login credentials call failure');
+            expresso_mail_archive.session = null;
+        }
+    }
+    cExecute("$this.user.get_mailarchiver_authid",handler_get_logon);     
+}
+
+MailArchiver.prototype.login = function(){
+    try{
+        ArchiveServices.login(expresso_mail_archive.loginOperationOK, expresso_mail_archive.loginOperationFailure, expresso_mail_archive.logonid[0], expresso_mail_archive.logonid[1], expresso_mail_archive.sessionid, expresso_mail_archive.balancerid);
+    }
+    catch(e){
+        expresso_mail_archive.getFaultInfo();
+    }
+}
+
+MailArchiver.prototype.loginOperationOK = function(returnService){
+    if((typeof(returnService.getReturn()) == 'object') && (returnService.getReturn() != null)){
+        expresso_mail_archive.session = new Object();
+        expresso_mail_archive.session.expiration = returnService.getReturn().getExpiration();
+        expresso_mail_archive.session.id = returnService.getReturn().getId();
+        expresso_mail_archive.session.permissions = returnService.getReturn().getPermissions();
+        expresso_mail_archive.CreateDefaultStructrure();
+    }
+    else{
+        //not logged in MailArchiver
+        expresso_mail_archive.session = null;
+        write_msg(get_lang('MailArchiver user login fail', true));
+        expresso_mail_archive.enabled = false;
+        expresso_mail_archive.timer=null;
+        expresso_mail_archive.interval = 500;
+        ArchiveServices = null;
+        connector.purgeCache();        
+        draw_tree_folders();
+        //expresso_mail_archive.DeactivateStatusListener(expresso_mail_archive);
+    }
+}
+
+MailArchiver.prototype.getFolderCounters = function(){
+    var vetreturn = new Array();
+    /*for(var k=0; k<expresso_mail_archive.folders.length; k++){
+        if(expresso_mail_archive.folders[k]["id"] == expresso_mail_archive.currentfolder){
+            vetreturn.push(expresso_mail_archive.folders[k]["messages"], expresso_mail_archive.folders[k]["unseen"]);
+            break;
+        }
+    }*/
+    vetreturn.push(expresso_mail_archive.folder.nummessages, expresso_mail_archive.folder.unseen);
+    return(vetreturn);
+}
+
+MailArchiver.prototype.setEmbeddedLink = function(){
+    var img_objects = document.getElementsByTagName('img');
+    for(var k = 0; k < img_objects.length; k++){
+        if(img_objects[k].name.indexOf('embedded_img_') != -1) {
+            var obj_link = img_objects[k].name.split('embedded_img_');
+            var txt_link = obj_link[1];
+            var img_base_link = mail_archive_protocol + "://" + mail_archive_host + ":" + mail_archive_port + "/temp/" + txt_link;
+            img_objects[k].src = img_base_link;
+        }
+    }
+}
+/*
+MailArchiver.prototype.getFolderPath = function(folder){
+    try{
+        ArchiveServices.getFolderInfo(expresso_mail_archive.getFolderPathOperationOK, expresso_mail_archive.getFolderPathOperationFailure, expresso_mail_archive.session.id, folder);
+    }
+    catch(e){
+        window.alert('getFolderPath fails');
+    }
+}
+
+MailArchiver.prototype.getFolderPathOperationOK = function(serviceReturn){
+    window.alert('service return from getFolderPathOperationOK = ' + serviceReturn().getFolderPath());
+    if(serviceReturn().length>0){
+        window.alert('ok');
+    }
+    else{
+        window.alert('nope');
+    }
+}
+
+MailArchiver.prototype.getFolderPathOperationFailure = function(serviceFault){
+    window.alert('fails at gettting folder path');
+}
+*/
+
+MailArchiver.prototype.getMessageInfo = function(msgId){
+    try{
+        ArchiveServices.getMessageInfo(expresso_mail_archive.getMessageInfoOperationOK, expresso_mail_archive.getMessageInfoOperationFailure, expresso_mail_archive.session.id, msgId);
+    }
+    catch(e){
+        window.alert('getMessageInfo fails');
+    }    
+}
+
+MailArchiver.prototype.getMessageInfoOperationOK = function(serviceReturn){
+    //window.alert('service return from getMessageInfoOperationOK = ' + serviceReturn.getReturn() + '\n' + typeof(serviceReturn.getReturn()) + '\n' + print_r(serviceReturn.getReturn()));
+    if(typeof(serviceReturn.getReturn() == 'object')){
+        var ExpSerialized2 = expresso_mail_archive.pattern.toExpressoHeader(serviceReturn.getReturn());
+        var msgitem2 = connector.unserialize(ExpSerialized2);
+        expresso_mail_archive.messageslisted.push(msgitem2);    
+        window.alert('vai chamar de volta o getMessageHeaders com: \nid => ' + serviceReturn.getReturn().getId());
+        expresso_mail_archive.getMessageHeaders(serviceReturn.getReturn().getId());
+    }
+    else{
+        window.alert('getMessageInfoOperationOK nope');
+    }
+}
+
+MailArchiver.prototype.turnOffLocalTreeStructure = function (){
+    var disabled_local_span = document.getElementById('llocal_disabledtree_folders');
+
+    if((!disabled_local_span) && (!document.getElementById('services_retry'))){
+        var n_LocalDisabled = new dNode({id: "local_disabled", caption: get_lang('Offline'), onClick: "services_retry()", plusSign:false});
+        tree_folders.add(n_LocalDisabled, 'local_root');
+                            
+        var disabled_local_span = document.getElementById('llocal_disabledtree_folders');
+        disabled_local_span.style.backgroundImage="url(../phpgwapi/templates/"+template+"/images/foldertree_services.png)";
+        var service_retry = document.createElement("SPAN");
+        service_retry.id = 'services_retry';
+        service_retry.className = 'clean_trash';
+        service_retry.style.cursor = 'pointer';
+        service_retry.onclick = function () {services_retry();};
+        service_retry.innerHTML = "["+get_lang("Retry")+"]";
+        service_retry.title= get_lang("Reconect to MailArchiver services");
+        service_retry.onmouseover = function() {service_retry.style.color="red";};
+        service_retry.onmouseout= function() {service_retry.style.color="#666666";}; //#114FA4
+        disabled_local_span.parentNode.appendChild(service_retry);
+                            
+        var div_ma_host = document.createElement('div');
+        div_ma_host.id = 'div_login_ma_host';
+        div_ma_host.style.position = 'absolute';
+        div_ma_host.style.padding = '0px';
+        div_ma_host.style.margin = '0px';
+        div_ma_host.style.top = '25px';
+        div_ma_host.style.left = '0px';
+        div_ma_host.style.width = '145px';
+        div_ma_host.style.height = '80px';
+        div_ma_host.style.border = '1px solid #CCCCCC';
+        div_ma_host.style.backgroundColor = '#F0F0F0';
+        div_ma_host.style.fontWeight = 'normal';
+        disabled_local_span.appendChild(div_ma_host);
+        div_ma_host.innerHTML = '<p><b>'+get_lang('In trouble?')+'</b></p><p>&rarr; ' + get_lang('Try to access') + '<br/><a href="' + mail_archive_protocol + "://" + mail_archive_host + ":" + mail_archive_port + '/admin" target="_blank" title="MailArchiver Admin">'+get_lang('MailArchiver admin console')+'.</p>';                            
+    }
+    //Only creates the MA login linkage
+    else{
+        var div_ma_host = document.createElement('div');
+        div_ma_host.id = 'div_login_ma_host';
+        div_ma_host.style.position = 'absolute';
+        div_ma_host.style.padding = '0px';
+        div_ma_host.style.margin = '0px';
+        div_ma_host.style.top = '25px';
+        div_ma_host.style.width = '145px';
+        div_ma_host.style.height = '80px';
+        div_ma_host.style.border = '1px solid #CCCCCC';
+        div_ma_host.style.backgroundColor = '#F0F0F0';
+        div_ma_host.style.fontWeight = 'normal';
+        disabled_local_span.appendChild(div_ma_host);
+        div_ma_host.innerHTML = '<p><b>'+get_lang('In trouble?')+'</b></p><p>&rarr; ' + get_lang('Try to access') + '<br/><a href="' + mail_archive_protocol + "://" + mail_archive_host + ":" + mail_archive_port + '/admin" target="_blank" title="MailArchiver Admin">'+get_lang('MailArchiver admin console')+'.</p>';                                                        
+    }    
+}
+
+MailArchiver.prototype.getMessageInfoOperationFailure = function(serviceFault){
+    window.alert('fails at gettting message info');
+}
+
+MailArchiver.prototype.loginOperationFailure = function(ServiceFaillure){
+    write_msg(get_lang('MailArchiver login operation fail', true));
+}
+
+MailArchiver.prototype.logout = function(){
+    write_msg(get_lang('MailArchiver user logged out', true));
+}
+/*
+ *The all pourpose JavaScript variable, used by all related functionalityes at
+ *Expresso Mail to handle this object at user gui.
+ */
+
+var expresso_mail_archive;
+expresso_mail_archive = new MailArchiver();
+-->
Index: sandbox/2.5.0-expresso1/expressoMail1_2/js/MAQueryConfig.js
===================================================================
--- sandbox/2.5.0-expresso1/expressoMail1_2/js/MAQueryConfig.js	(revision 7146)
+++ sandbox/2.5.0-expresso1/expressoMail1_2/js/MAQueryConfig.js	(revision 7146)
@@ -0,0 +1,637 @@
+<!--
+/**
+ *MailArchiver Query Config API
+ *
+ *This api is intended to be used with MailArquiver JavaScript API.
+ *Basicly, it is responsable to provide a standard data format conversion
+ *to handle queryes under MailArquiver web services pooling. *
+ *
+ */
+
+
+//MailArchiver Query Config data structure
+var MAQueryConfig = function(){
+  this.lowerIndex = null;
+  this.upperIndex = null;
+  this.from = null;
+  this.to = null;
+  this.cc = null;
+  this.subject = null;
+  this.body = null;
+  this.date = null;
+  this.dateLower = null;
+  this.dateUpper = null;  
+  this.tag = null;
+  this.folder = null;
+  this.folder_recursive = null;
+  this.order = null;
+  this.preview_message = null;
+  this.preview_tooltip = null;
+  this.defaults = null;
+}
+
+//Set up all criteria list received
+MAQueryConfig.prototype.setCriteriaList = function(cl){
+  //window.alert('dumpando setCriteriaList:\n' + print_r(cl));
+  for(var p in cl){
+    //window.alert('p = ' + p + '\ncl = ' + cl + '\ncl[p] = ' + cl[p] + '\np[cl] = ' + p[cl]);
+    //Decode the criteria for search.
+    cl[p] = url_decode_s(cl[p]);
+    if(p.toLowerCase() == 'all')
+      this.setSubject(cl[p]);
+    if(p.toLowerCase() == 'lowerindex')
+      this.setLowerIndex(cl[p]);    
+    if(p.toLowerCase() == 'upperindex')
+      this.setUpperIndex(cl[p]);      
+    if(p.toLowerCase() == 'from')
+      this.setFrom(cl[p]);
+    if(p.toLowerCase() == 'to')
+      this.setTo(cl[p]);
+    if(p.toLowerCase() == 'cc')
+      this.setCc(cl[p]);
+    if(p.toLowerCase() == 'subject')
+      this.setSubject(cl[p]);
+    if(p.toLowerCase() == 'body')
+      this.setBody(cl[p]);
+    if(p.toLowerCase() == 'on')
+      this.setDate('on',cl[p]);
+    if(p.toLowerCase() == 'since')
+      this.setDate('lower',cl[p]);  
+    if(p.toLowerCase() == 'before')
+      this.setDate('upper',cl[p]);  
+    if(p.toLowerCase() == 'flags')
+      this.setTag(cl[p]);
+    if(p.toLowerCase() == 'folder')
+      this.setFolder(cl[p]);
+    if(p.toLowerCase() == 'order')
+      this.setOrder(cl[p]);
+
+    //search tags window criteria mapping
+    if(p.toLowerCase() == 'flagged'){
+        var oexptag = eval('({"contains":"flagged"})'); 
+        this.setTags(oexptag);        
+    }
+    if(p.toLowerCase() == 'unflagged'){
+        var oexptag = eval('({"contains":"unflagged"})'); 
+        this.setTags(oexptag);        
+    }    
+    if(p.toLowerCase() == 'seen'){        
+        var oexptag = eval('({"contains":"seen"})'); 
+        this.setTags(oexptag);                
+    }    
+    if(p.toLowerCase() == 'unseen'){
+        var oexptag = eval('({"contains":"unseen"})'); 
+        this.setTags(oexptag);                
+    }
+    if(p.toLowerCase() == 'answered'){
+        var oexptag = eval('({"contains":"answered"})'); 
+        this.setTags(oexptag);                
+    }        
+    if(p.toLowerCase() == 'unanswered'){
+        var oexptag = eval('({"contains":"unanswered"})'); 
+        this.setTags(oexptag);                
+    }            
+  }
+}
+
+MAQueryConfig.prototype.setDefaults = function(defaults){
+    this.defaults = defaults;
+}
+
+MAQueryConfig.prototype.setExpressoDefaults = function(data_default){
+    //Expresso defaults came from "messages_controller.js": here, we maps
+    //each array entry from messages_list intended to run by our own behavior
+    if(data_default.length != 8)
+        return;
+   //expresso default argument list => new Array(baseFolder,msg_range_begin,emails_per_page,sort_box_type,search_box_type, sort_box_reverse,preview_msg_subject,preview_msg_tip);
+   this.setFolder(data_default[0]);
+   this.setLowerIndex(data_default[1]);
+   this.setUpperIndex(data_default[2]);
+   
+   if (parseInt(data_default[5]) == 0)
+       var oexpor = 'asc';
+   else
+       var oexpor = 'desc';
+   
+   //window.alert('NO MAQueryconfig setExpressoDefaults\n\nbase_folder = ' + data_default[0] + '\nmsg_range_begin = ' + data_default[1] + '\nemails_per_page = ' + data_default[2] + '\nsort_box_type =' + data_default[3].toLowerCase() + '\nsearch_box_type= ' + data_default[4] + '\nsort_box_reverse = ' + data_default[5] + '\npreview_msg_subject = ' + data_default[6] + '\npreview_msg_tip = ' + data_default[7]);
+   
+   //sets tag data filter
+   switch(data_default[4].toLowerCase()){
+    case 'unseen':
+        var tagtolist_criteria = 'contains';
+        var tagtolist_value = 'unseen';
+        break;
+    case 'seen':
+        var tagtolist_criteria = 'contains';
+        var tagtolist_value = 'seen';        
+        break;
+    case 'answered':
+        var tagtolist_criteria = 'contains';
+        var tagtolist_value = 'answered';        
+        break;
+    case 'unanswered':
+        var tagtolist_criteria = 'contains';
+        var tagtolist_value = 'unanswered';        
+        break;        
+    case 'flagged':
+        var tagtolist_criteria = 'contains';
+        var tagtolist_value = 'flagged';        
+        break;  
+    case 'unflagged':
+        var tagtolist_criteria = 'contains';
+        var tagtolist_value = 'unflagged';        
+        break;        
+    default:
+        var tagtolist_criteria = null;
+        var tagtolist_value = null;        
+   }
+
+   //sets TagConfig
+   var oexptag = eval('({"' + tagtolist_criteria + '":"' + tagtolist_value + '"})'); 
+   this.setTags(oexptag);
+
+
+   //sets order criteria
+   switch(data_default[3].toLowerCase()){
+       case 'sortfrom':
+           var oexpcrt = 'from';
+           break;
+       case 'sortsubject':
+           var oexpcrt = 'subject';
+           break;
+       case 'sortsize':
+           var oexpcrt = 'size';
+           break;
+       default:
+           var oexpcrt = 'date';
+           break;
+   }   
+
+   var oexporder = eval('({"' + oexpcrt + '":"' + oexpor + '"})');
+   this.setOrder(oexporder);
+}
+
+//PharseCriteria receives data to pharse structure format fields from, to, cc and subject
+MAQueryConfig.prototype.pharseCriteria = function(field, data, criteria){
+  //window.alert('pharseCriteria input data:\n\n-> field = ' + field + '\ndata = ' + data + '\ncriteria = ' + criteria);
+  if(!criteria)
+      criteria = 'none';
+  
+  var stdout = '"'+field+'":[';
+  switch (criteria.toLowerCase()){
+      case "equals":
+          stdout += '{"@equals":"'+data+'"},';
+          break;
+      case "equalsic":
+          stdout += '{"@equalsIgnoreCase":"'+data+'"},';
+          break;
+      case "like":
+          stdout += '{"@like":"'+data.like+'"},';
+          break;
+      default:
+          stdout+= '{"@likeIgnoreCase":"'+data+'"},';
+  }
+  stdout = stdout.substr(0,stdout.length-1) + '],';
+  return(stdout);
+}
+
+//setbounds up and down
+MAQueryConfig.prototype.setLowerIndex = function(low){
+  //window.alert('setbounds low = ' + low + ' high = ' + high);
+  this.lowerIndex = '"@lowerIndex":"'+(parseInt(low)-1)+'", ';
+}
+
+MAQueryConfig.prototype.setUpperIndex = function(high){
+  //window.alert('setbounds low = ' + low + ' high = ' + high);
+  this.upperIndex = '"@upperIndex":"'+(parseInt(high))+'", ';
+}
+ 
+//From receives a array of structutred data, by the model
+MAQueryConfig.prototype.setFrom = function(data){
+  if(data.length <= 0){
+    this.from = null;
+    return;
+  }
+  
+  //subdata = this.pharseCriteria('from', data);
+  this.from = '"@from":"' + data + '",';
+}
+
+//To receives a array of structutred data, by the model
+MAQueryConfig.prototype.setTo = function(data){
+  if(data.length <= 0){
+    this.to = null;
+    return;
+  }
+
+  //subdata = this.pharseCriteria('to', data);
+  this.to = '"@to":"' + data + '",';
+}
+
+//Cc data
+MAQueryConfig.prototype.setCc = function(data){
+  if(data.length <= 0){
+    this.cc = null;
+    return;
+  }
+
+  //subdata = this.pharseCriteria('cc', data);
+  this.cc = '"@cc":"' + data + '",';
+}
+
+//Subject data
+MAQueryConfig.prototype.setSubject = function(sub){
+  if(sub.length <= 0){
+    this.subject = null;
+    return;
+  }
+
+  //subdata = this.pharseCriteria('subject', sub);
+  this.subject = '"@subject":"' + sub + '",';
+}
+
+//PREGMatch date format
+MAQueryConfig.prototype.validateDate = function (dat){
+ var dateregex = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/;
+ if (dateregex.test(dat))
+   return true;
+ else
+   return false;
+}
+
+//PREGMatch time format
+MAQueryConfig.prototype.validateTime = function (tim){
+  //var timeregex = /^([1-9]|1[0-2]):[0-5]\d(:[0-5]\d(\.\d{1,3})?)?$/;
+  //var timeregex = /^[0-2][0-9]:[0-5][0-9]:[0-5][0-9]$/;
+  var timeregex = /^\d{1,2}[:]\d{2}([:]\d{2})?$/;
+  if (timeregex.test(tim))
+    return true;
+  else
+    return false;
+}
+
+//toStdDate returns date time as long. Format input:'DD/MM/YYYY HH:MM:SS'
+MAQueryConfig.prototype.toStdDate = function(dt){ 
+  if (dt.length <= 0)
+    return;
+
+  var date_time_picker = dt.split(" ");
+  var date_part = date_time_picker[0];
+  var time_part = date_time_picker[1];
+
+  //window.alert('date_part = ' + date_time_picker[0] + '\ntime_part = ' + date_time_picker[1]);
+
+  if ((this.validateDate(date_part)) && (this.validateTime(time_part))){
+    var date_split = date_part.split("/");
+    var ddd = date_split[1]+'/'+date_split[0]+'/'+date_split[2] + ' ' + time_part;
+    var ndate = new Date(ddd);   
+    
+    //window.alert('Date.parse (' + ddd + ') = ' + Date.parse(ndate));
+    return(Date.parse(ndate));
+  }
+  else
+    return("");
+}
+
+//Date data
+MAQueryConfig.prototype.setDate = function(date_field, date_data){
+  if((!date_field) || (!date_data)){
+    this.date = null;
+    this.dateLower = null;
+    this.dateUppder = null;
+    return;
+  }
+    
+  if(date_field == 'lower'){
+    if(date_data.indexOf('%') != -1)
+        var dt1b = this.pharseStdDate(date_data);
+    else
+        var dt1b = this.toStdDate(date_data);
+    this.dateLower = '"@lowerDate":"'+dt1b+'",';
+  }
+  if(date_field == 'upper'){
+    if(date_data.indexOf('%') != -1)
+        var dt2b = this.pharseStdDate(date_data);
+    else
+        var dt2b = this.toStdDate(date_data);
+    this.dateUpper = '"@upperDate":"'+dt2b+'",';
+  }
+  if(date_field == 'on'){
+    if(date_data.indexOf('%') != -1)
+        var dt3b = this.pharseStdDate(date_data);
+    else
+        var dt3b = this.toStdDate(date_data);
+    this.date = '"@date":"'+dt3b+'",';
+  }
+}
+
+//flags data
+MAQueryConfig.prototype.setTag = function(flaglist){
+  if(flaglist.flags.length <= 0){
+    this.tag = null;
+    return;
+  }
+
+  this.tag = '"flag":[';
+  var flag_data = flaglist.flags.split(',');
+  if(flag_data.length > 0){
+    for(var k=0; k<flag_data.length; k++){
+      this.tag += '{"@value":"'+flag_data[k]+'"},'
+    }
+    this.tag = this.tag.substr(0,this.tag.length-1);
+  }
+  else{
+    this.tag += '{"@value":"'+flaglist.flags+'"},';
+  }
+  this.tag += '],';
+}
+
+//Folder data
+MAQueryConfig.prototype.setFolder = function(folderslist){
+  if(folderslist.length <= 0){
+    this.folder = null;
+    return;
+  }
+  this.folder = '"folder":[';
+  if(this.folder_recursive){
+      var pfrec = ', "@recursive":"true"';
+  }
+  else
+      var pfrec = '';
+  
+  if (folderslist.indexOf(',') != -1){
+    var folder_data = folderslist.split(',');
+    if(folder_data.length > 0){
+        for(var k=0; k<folder_data.length; k++){
+            this.folder += '{"@id":"'+folder_data[k]+'"' + pfrec + '},'
+        }
+        this.folder = this.folder.substr(0,this.folder.length-1);
+    }
+    else{
+        this.folder += '{"@id":"'+folderslist+'"' + pfrec + '"}';
+    }
+  }
+  else{
+      this.folder += '{"@id":"' + folderslist +'"' + pfrec + '}';
+  }
+  this.folder += '],';
+}
+
+//Order criteria
+MAQueryConfig.prototype.setOrder = function(order){
+  if(typeof(order) != 'object'){
+    this.order = null;
+    return;
+  }
+
+  this.order = '"order":[';
+  for(var k in order){
+    if(k.toLowerCase().indexOf("date") != -1)
+      this.order += '{"@date":"'+order[k]+'"},';
+    if(k.toLowerCase().indexOf("from") != -1)
+      this.order += '{"@from":"'+order[k]+'"},';
+    if(k.toLowerCase().indexOf("subject") != -1)
+      this.order += '{"@subject":"'+order[k]+'"},';
+    if(k.toLowerCase().indexOf("size") != -1)
+      this.order += '{"@size":"'+order[k]+'"},';
+  }
+  this.order = this.order.substr(0,this.order.length-1) + ']';
+}
+
+//Tags criteria
+MAQueryConfig.prototype.setTags = function(taglist){
+  if(typeof(taglist) != 'object'){
+    this.tag = null;
+    return;
+  }
+  //Adding tag criteria
+  if(this.tag != null)
+    this.tag = this.tag.substr(0, this.tag.length-2) + ', ';
+  //Creating tag criteria
+  else
+    this.tag = '"tags":[';
+  
+  for(var k in taglist){
+    if(k != null){
+        if(k.toLowerCase() == "contains"){
+            this.tag += '{"@contains":"'+taglist[k]+'"},';
+        }
+    }
+  }
+  //if no tag data was parametrizided, no one tag data will be returned
+  if(this.tag.length > 8)
+    this.tag = this.tag.substr(0,this.tag.length-1) + '],';
+  else
+    this.tag = null;
+}
+
+//Body structrure
+MAQueryConfig.prototype.setBody = function(data){
+/*  if(body_data.length <= 0){
+    this.body = null;
+    return;
+  }
+  this.body = '"body":[';
+  for(var k in body_data){
+    if(k.toLowerCase() == "like")
+      this.body += '{"@like":"'+body_data[k]+'"},';
+    if(k.toLowerCase() == "likeic")
+      this.body += '{"@likeIgnoreCase":"'+body_data[k]+'"},';
+  }
+  this.body = this.body.substr(0,this.body.length-1) + '],';
+  */
+  if(data.length <= 0){
+    this.body = null;
+    return;
+  }
+  
+  //subdata = this.pharseCriteria('from', data);
+  this.body = '"@body":"' + data + '",';  
+}
+
+MAQueryConfig.prototype.pharseSearchFields = function(fields){
+   if(fields.length <= 0) 
+       return;
+   
+   var filters = fields.replace(/^##|##$/g,"").split('##');
+   if(filters.length > 0){
+     var filter_object = '{' ;
+     for(var k=0; k<filters.length; k++){
+       var filter_entry = filters[k].split('<=>');
+       filter_object += filter_entry[0].toLowerCase() + ':"' + filter_entry[1] + '", ';
+     }
+     filter_object = filter_object.substr(0, filter_object.length-2);
+     filter_object += '}';
+     return(filter_object);
+   }
+   else
+       return;
+}
+
+MAQueryConfig.prototype.pharseFolders = function(folderslist){
+    var folder_string_list = "";
+    if (folderslist.length > 1){
+        for(var k=0; k<folderslist.length; k++){
+            var f_criteria = folderslist[k].split("#");
+            var f_name = f_criteria[0];
+            var f_recursive = f_criteria[1];
+            folder_string_list += f_name + ',';
+        }
+        folder_string_list = folder_string_list.substr(0, folder_string_list.length-1) + '#' + f_recursive + ',';
+        folder_string_list = folder_string_list.substr(0, folder_string_list.length-1);
+    }
+    else{
+        folder_string_list = folderslist[0];
+    }
+    //window.alert('pharsefolders return = ' + folder_string_list);
+    return(folder_string_list);
+}
+
+MAQueryConfig.prototype.getLowerIndex = function(){
+  //  (this.lowerIndex != null) ? retdata = this.lowerIndex : retdata = '"@lowerIndex":"0", ';
+    (this.lowerIndex != null) ? retdata = this.lowerIndex : retdata = '';
+    return(retdata);
+}
+
+MAQueryConfig.prototype.getUpperIndex = function(){
+//    (this.upperIndex != null) ? retdata = this.upperIndex : retdata = '"@upperIndex":"' + preferences.max_email_per_page+ '", ';
+    (this.upperIndex != null) ? retdata = this.upperIndex : retdata = '';
+    return(retdata);
+}
+
+MAQueryConfig.prototype.getFrom = function(){
+    (this.from != null) ? retdata = this.from : retdata = "";
+    return(retdata);
+}
+
+MAQueryConfig.prototype.getTo = function(){
+    (this.to != null) ? retdata = this.to : retdata = "";
+    return(retdata);    
+}
+
+MAQueryConfig.prototype.getCc = function(){
+    (this.cc != null) ? retdata = this.cc : retdata = "";
+    return(retdata);    
+}
+
+MAQueryConfig.prototype.getSubject = function(){
+    (this.subject != null) ? retdata = this.subject : retdata = "";
+    return(retdata);    
+}
+
+MAQueryConfig.prototype.getBody = function(){
+    (this.body != null) ? retdata = this.body : retdata = "";
+    return(retdata);    
+}
+
+MAQueryConfig.prototype.getDate = function(){
+    (this.date != null) ? retdata = this.date : retdata = "";
+    return(retdata);    
+}
+
+MAQueryConfig.prototype.getDateLower = function(){
+    (this.dateLower != null) ? retdata = this.dateLower : retdata = "";
+    return(retdata);    
+}
+
+MAQueryConfig.prototype.getDateUpper = function(){
+    (this.dateUpper != null) ? retdata = this.dateUpper : retdata = "";
+    return(retdata);    
+}
+
+MAQueryConfig.prototype.getTag = function(){
+    (this.tag != null) ? retdata = this.tag : retdata = "";
+    return(retdata);    
+}
+
+MAQueryConfig.prototype.getFolder = function(){
+    if (this.folder != null){
+        if (this.folder_recursive){
+            var tmp_root_id = this.folder.substr(this.folder.indexOf("@id")+6, 4);
+            if(tmp_root_id == 'root')
+                retdata = "";
+            else
+                retdata = this.folder;
+        }
+        else
+            retdata = this.folder;
+    }
+    else retdata = "";
+    return(retdata);    
+}
+
+MAQueryConfig.prototype.getOrder = function(){
+    //defaults order criteria is date asc
+    (this.order != null) ? retdata = this.order : retdata = '"order":[{"@date":"desc"}]';
+    return(retdata);    
+}
+
+//Query criteria (core api)
+MAQueryConfig.prototype.query = function(criterialist){
+  //window.alert('MAQueryConfig.query\n\n - > CriteriaList:\n ' + criterialist + '[' + typeof(criterialist) + ']\ndump:\n' + print_r(criterialist));
+
+  if (criterialist){
+    this.setCriteriaList(criterialist);
+  }
+  
+  //window.alert('em qc.query com lower = ' + this.lowerIndex + ' e upper = ' + this.upperIndex);
+  var querystring = '{"query":{';
+  querystring += this.getLowerIndex();
+  querystring += this.getUpperIndex();
+  querystring += this.getDateLower();
+  querystring += this.getDateUpper();
+  querystring += this.getDate();  
+  querystring += this.getFrom();
+  querystring += this.getTo();
+  querystring += this.getCc();
+  querystring += this.getSubject();
+  querystring += this.getBody();
+  querystring += this.getTag();
+  querystring += this.getFolder();
+  querystring += this.getOrder();
+  
+  var lastchar = querystring.substr(querystring.length-1,querystring.length);
+  if(lastchar == ',')
+      querystring = querystring.substr(0, querystring.length-1);
+  
+  querystring += '}}';
+  //window.alert('queryconfig output\n\n' + querystring);
+  return(querystring);
+}
+
+MAQueryConfig.prototype.reset = function(){
+  this.lowerIndex = null;
+  this.upperIndex = null;
+  this.from = null;
+  this.to = null;
+  this.cc = null;
+  this.subject = null;
+  this.body = null;
+  this.date = null;
+  this.dateLower = null;  
+  this.dateUpper = null;  
+  this.tag = null;
+  this.folder = null;
+  this.order = null;
+  this.preview_message = null;
+  this.preview_tooltip = null;
+  this.defaults = null;    
+}
+
+MAQueryConfig.prototype.pharseStdDate = function(date){
+    var data_decoded = decodeURIComponent(date);
+    var data_array = data_decoded.split("/");
+    var data_day = data_array[0];
+    var data_month = data_array[1];
+    var data_year = data_array[2];
+
+    var date_object = new Date();
+    date_object.setDate(data_day);
+    date_object.setMonth(data_month-1);
+    date_object.setFullYear(data_year);
+    
+    var date_number = date_object.getTime();
+    return(date_number);
+    //return(new String(date_number)+'L');
+}
+-->
Index: sandbox/2.5.0-expresso1/expressoMail1_2/js/common_functions.js
===================================================================
--- sandbox/2.5.0-expresso1/expressoMail1_2/js/common_functions.js	(revision 6996)
+++ sandbox/2.5.0-expresso1/expressoMail1_2/js/common_functions.js	(revision 7146)
@@ -20,4 +20,14 @@
 
 var message = "Não Informado";
+
+//MAILARCHIVER-01
+try{
+   var ArchiveServices = new web_service_mailarchiver_serpro__ArchiveServices();
+   ArchiveServices.url = mail_archive_protocol + "://" + mail_archive_host + ":" + mail_archive_port + "/arcserv/ArchiveServices";
+   ArchiveServices.synchronous = true;
+}
+catch (e){
+    var ArchiveServices = null;
+}
 
 function config_events(pObj, pEvent, pHandler)
Index: sandbox/2.5.0-expresso1/expressoMail1_2/js/main.js
===================================================================
--- sandbox/2.5.0-expresso1/expressoMail1_2/js/main.js	(revision 7129)
+++ sandbox/2.5.0-expresso1/expressoMail1_2/js/main.js	(revision 7146)
@@ -1,4 +1,13 @@
 // Tempo do auto refresh (em milisegundos)
 var time_refresh = 300000;
+
+//MAILARCHIVER-01
+// Intervalo de tempo de verificacao de comunicacao com o MailArchiver (milisegundos)
+var check_services_interval = 2000;
+// Numero de tentativas de reconexao
+var check_services_tryouts = 1;
+// Limite de tentativas de reconexao
+var check_services_tryouts_limit = 5;
+
 
 // tempo do auto save (em milisegundos)
@@ -93,4 +102,9 @@
 		Element('tableDivAppbox').width = '100%';
 
+    //MailArchiver save offset to gmt user preference data to list correctly date/time from messages list
+    var save_gmtoffset = function(data){
+        gmtoffset = data;
+    }
+
 	var save_preferences = function(data){
 
@@ -110,5 +124,5 @@
 		current_folder="INBOX";
 		
-		if( (window.google && google.gears) && !google.gears.factory.getPermission())
+		/*if( (window.google && google.gears) && !google.gears.factory.getPermission())
 		    preferences.use_local_messages=0;
                 
@@ -127,6 +141,17 @@
 			setTimeout('auto_archiving()', 30000);
 			
-		}
+		}*/
 		/*Carrega a lista de mensagens*/
+
+        //MAILARCHIVER-02
+        //Try to get ArchiveServices object directly
+        if(ArchiveServices)
+            expresso_mail_archive.Startup();
+        //ArchiveServices not runnnig: catch the user preferences to set up message at header
+        else{
+            if(preferences.use_local_messages=="1")
+                write_msg(get_lang('Sorry, but Mail Archiver does not seems to be running or installed at this workstation. By now, we are turning off local messages!'));
+        }
+
 		var  handler_populateSelectedMsgs = function(data){
 			populateSelectedMsgs(data);
@@ -693,4 +718,5 @@
 				{
 					selectedPagingMsgs[data[i].msg_number] = false;
+					totalFolderMsgs++;
 					updateSelectedMsgs(false,data[i].msg_number);
 					var new_msg = this.make_tr_message(data[i], current_folder, data.offsetToGMT);
@@ -1188,6 +1214,9 @@
 				return false;
 			}else{
-				data = data.split("/").reverse(); //Recupera o nome da pasta do array
-				write_msg(get_lang('Error moving message.')+" "+get_lang('Permission denied to folder "%1".', data[0]));
+				write_msg(get_lang('Error moving message.')+" "+get_lang('Permission denied to folder "%1".', new_folder_name));
+				/*Verifica se a pasta destino é a "Trash" e se a pasta origem e destino são do mesma estrutura compartilhada*/
+				if(new_folder_name == "Trash" && folder.split("/")[1] == new_folder.split("/")[1]){
+					alert(get_lang("You can not remove the message with the preference 'Send to Trash' enabled. There is no permission to move messages to the trash folder."));
+				}
 				return false;
 			}
@@ -1315,4 +1344,5 @@
 			draw_paging(n_total_msg);
 			Element('tot_m').innerHTML = n_total_msg;
+			totalFolderMsgs -= data.msgs_number.length;
 		}
 		refresh();
@@ -1339,5 +1369,5 @@
 
 	// se a aba estiver aberta e selecionada, apenas a msg da aba é movida
-	if(currentTab.toString().indexOf("_r") != -1)
+	if(currentTab.toString().indexOf("_r") != -1 && currentTab == border_ID)
         {
                 //se a aba for aberta atraves de uma pesquisa
@@ -3142,18 +3172,18 @@
 
 function set_messages_flag_search_local(flag){
-	var msgs_flag = this.get_selected_messages_search();
-	if(local_messages.prototype.set_messages_flag(msgs_flag, flag, true)){
-		var id_border = currentTab.replace(/[a-zA-Z_]+/, "");
-		var msgs = msgs_flag.split(',');
-		for(var i = 0; i < msgs.length; i++){
-			Element("search_local_msg"+id_border+"_check_box_message_"+msgs[i]).checked = false;
-		}
-		draw_tree_folders();
-		Element('chk_box_select_all_messages_search_local').checked = false;
-		refresh();
-		write_msg(get_lang('The messages were marked with success!'));		
-	}else{
-		write_msg(get_lang('Error marking messages.'));
-	}
+	// var msgs_flag = this.get_selected_messages_search();
+	// if(local_messages.prototype.set_messages_flag(msgs_flag, flag, true)){
+	// 	var id_border = currentTab.replace(/[a-zA-Z_]+/, "");
+	// 	var msgs = msgs_flag.split(',');
+	// 	for(var i = 0; i < msgs.length; i++){
+	// 		Element("search_local_msg"+id_border+"_check_box_message_"+msgs[i]).checked = false;
+	// 	}
+	// 	draw_tree_folders();
+	// 	Element('chk_box_select_all_messages_search_local').checked = false;
+	// 	refresh();
+	// 	write_msg(get_lang('The messages were marked with success!'));		
+	// }else{
+	// 	write_msg(get_lang('Error marking messages.'));
+	// }
 }
 
@@ -4751,3 +4781,117 @@
 DataLayer.poll('message',30);
 
-
+//MAILARCHIVER-04
+function services_retry(){
+	console.log("services_retry");
+    try{
+        connector.purgeCache(); 
+        //window.alert('expresso var dump:\nenabled = ' + expresso_mail_archive.enabled + '\ntimer = ' + expresso_mail_archive.timer +'\ncounter = ' + expresso_mail_archive.counter);
+
+        if ((expresso_mail_archive.enabled == null) && (expresso_mail_archive.timer == null) && (expresso_mail_archive.counter > 0)){
+            connector.hideProgressBar();
+            connector.resetProgressBarText();
+            write_msg(get_lang('Sorry, but you need to reload this web page. Click at reload page at web browsing top navigation.'));
+            return;
+        }
+
+        if (arguments.length == 0){
+           connector.setProgressBarText(get_lang('Trying to communicate with Mail Archiver...'));
+        }
+
+        connector.showProgressBar();
+        var head = document.getElementById('send_queue');
+        
+        var script_xdr= document.createElement('script');
+        var script_xdr_tag_id = 'mail_archiver_retry_xdr';    
+        
+        var script_request= document.createElement('script');
+        var script_request_tag_id = 'mail_archiver_retry_request';                
+        
+        var script_cors= document.createElement('script');
+        var script_cors_tag_id = 'mail_archiver_retry_cors';
+        
+        var script_utils= document.createElement('script');
+        var script_utils_tag_id = 'mail_archiver_retry_utils';
+
+        if(document.getElementById(script_xdr_tag_id)){
+            document.getElementById(script_xdr_tag_id).parentNode.removeChild(document.getElementById(script_xdr_tag_id));
+        }
+
+        if(document.getElementById(script_request_tag_id)){
+            document.getElementById(script_request_tag_id).parentNode.removeChild(document.getElementById(script_request_tag_id));
+        }
+
+        if(document.getElementById(script_cors_tag_id)){
+            document.getElementById(script_cors_tag_id).parentNode.removeChild(document.getElementById(script_cors_tag_id));
+        }
+        
+        if(document.getElementById(script_utils_tag_id)){
+            document.getElementById(script_utils_tag_id).parentNode.removeChild(document.getElementById(script_utils_tag_id));
+        }        
+
+        //IE XDR ADAPTER
+        script_xdr.type= 'text/javascript';
+        script_xdr.src=  mail_archive_protocol + '://' + mail_archive_host + ':' + mail_archive_port  + '/arcservutil/cxf-addon-xdr-adapter.js';
+        script_xdr.id= script_xdr_tag_id;
+        head.appendChild(script_xdr);
+
+        //CXF TRANSPORT OBJECT
+        script_request.type= 'text/javascript';
+        script_request.src= mail_archive_protocol + '://' + mail_archive_host + ':' + mail_archive_port  + '/arcservutil/cxf-addon-cors-request-object.js';
+        script_request.id= script_request_tag_id;
+        head.appendChild(script_request);
+
+        //CXF CORS OBJECT
+        script_cors.type= 'text/javascript';
+        script_cors.src= mail_archive_protocol + '://' + mail_archive_host + ':' + mail_archive_port  + '/arcservutil/cxf-addon-cors-utils.js';
+        script_cors.id= script_cors_tag_id;
+        head.appendChild(script_cors);
+
+        //CXF CORE
+        script_utils.type= 'text/javascript';
+        script_utils.src= mail_archive_protocol + '://' + mail_archive_host + ':' + mail_archive_port  + '/arcserv/ArchiveServices?js&nojsutils';
+        script_utils.id= script_utils_tag_id;
+        head.appendChild(script_utils);
+
+        ttintval = window.setTimeout('check_services_restart()', 1000);
+    }
+    catch (e){
+        write_msg(get_lang('Sorry, but Mail Archiver still seems to be sleeping. Check out your system services!'));
+        connector.hideProgressBar();
+        connector.resetProgressBarText();
+        check_services_tryouts = 1;
+    }
+}
+
+//MAILARCHIVER-05
+function check_services_restart(){
+    try{
+        connector.setProgressBarText(get_lang('Wait: attempt %1 from %2...', check_services_tryouts, check_services_tryouts_limit));
+        if(check_services_tryouts <= 5){
+            try{
+                ArchiveServices = new web_service_mailarchiver_serpro__ArchiveServices();
+                ArchiveServices.url = mail_archive_protocol + "://" + mail_archive_host + ":" + mail_archive_port + "/arcserv/ArchiveServices";
+                window.clearInterval(ttintval2);
+                expresso_mail_archive.Restart(expresso_mail_archive);
+            }
+            catch (e){
+                check_services_tryouts++;
+                window.clearInterval(ttintval);
+                ttintval2 = window.setTimeout('services_retry(true)',1);
+            }
+        }
+        else{
+            write_msg(get_lang('Sorry, but Mail Archiver still seems to be sleeping. Check out your system services!'));
+            connector.hideProgressBar();
+            connector.resetProgressBarText();
+            check_services_tryouts = 1;
+        }
+    }
+    catch (e){
+        write_msg(get_lang('Sorry, but Mail Archiver still seems to be sleeping. Check out your system services!'));
+        connector.hideProgressBar();
+        connector.resetProgressBarText();
+        check_services_tryouts = 1;
+    }
+}
+
Index: sandbox/2.5.0-expresso1/expressoMail1_2/js/messages_controller.js
===================================================================
--- sandbox/2.5.0-expresso1/expressoMail1_2/js/messages_controller.js	(revision 7005)
+++ sandbox/2.5.0-expresso1/expressoMail1_2/js/messages_controller.js	(revision 7146)
@@ -9,5 +9,74 @@
  * Retorna os cabeçalhos das mensagens a serem desenhadas na caixa de email.
  */
-	messages_proxy.prototype.messages_list = function(folder,msg_range_begin,emails_per_page,sort_box_type,search_box_type,sort_box_reverse,preview_msg_subject,preview_msg_tip,call_back) {
+    messages_proxy.prototype.messages_list = function(folder,msg_range_begin,emails_per_page,sort_box_type,search_box_type,sort_box_reverse,preview_msg_subject,preview_msg_tip,call_back) {
+        if(this.is_local_folder(folder)) {
+
+            //MAILARCHIVER-01
+            
+            //var baseFolder = folder.substr(6);
+            var baseFolder = folder.replace('local_messages_', '');
+            var tree_name;
+            //var drawinginfo = {treeObject: tree_name, treeName: tree_name, folderName: baseFolder};
+            var drawinginfo = {};
+            expresso_mail_archive.update_counters = false;
+            expresso_mail_archive.currentfolder = baseFolder;
+            expresso_mail_archive.getFolderInfo(expresso_mail_archive.currentfolder);
+            expresso_mail_archive.drawdata = drawinginfo;
+
+            if(tree_name == 'tree_folders'){ //only the 'tree_folders' must show messages. 'folders_tree' are just for managment operation
+                console.log('if 1');
+                var exp_dfs = new Array(baseFolder,msg_range_begin,emails_per_page,sort_box_type,search_box_type, sort_box_reverse,preview_msg_subject,preview_msg_tip);
+                expresso_mail_archive.queryconfig.setExpressoDefaults(exp_dfs);
+                expresso_mail_archive.listMessages();
+            }
+            else{
+                if (!tree_name){
+                    console.log('if 2');
+                    //window.alert('sem arvore para atualizar, com sort_box_type =' + sort_box_type + ' e search_box_type= ' + search_box_type + ' reverse -- ' + sort_box_reverse);
+                    var exp_dfs = new Array(baseFolder,msg_range_begin,emails_per_page,sort_box_type,search_box_type,sort_box_reverse,preview_msg_subject,preview_msg_tip);
+                    console.log(exp_dfs);
+                    expresso_mail_archive.queryconfig.setExpressoDefaults(exp_dfs);
+                    expresso_mail_archive.listMessages();
+                }
+                if(tree_name == 'folders_tree'){
+                    console.log('if 3   ');
+                    /*var div_export_local = document.createElement('div');
+                    div.style.width
+                    var lbl_check = document.createElement('label');
+                    var check_export_local_recursive = document.createElement('input');
+                    var lbl_combo = document.createElement('label');
+                    var combo_export_local_format = document.createElement('select');*/
+                    //window.alert('alert td content = ' + Element('div_buttons').getElementsByTagName('table')[0].tbody[0].tr[4].td[0].innerHTML);
+                    //Element('div_buttons').appendChild(div_export_local);
+                }
+            }
+
+        }else {
+            $.ajax({
+                url: "controller.php?" + $.param( {action: "$this.imap_functions.get_range_msgs3", 
+                                    folder: folder, 
+                                    msg_range_begin: msg_range_begin, 
+                                    msg_range_end: emails_per_page, 
+                                    sort_box_type: sort_box_type, 
+                                    search_box_type: search_box_type, 
+                                    sort_box_reverse: sort_box_reverse } ),
+
+                  success: function( data ){
+                    data = connector.unserialize(data);
+                    
+                    if( data )
+                        call_back( data );
+                  },
+                  beforeSend: function( jqXHR, settings ){
+                    connector.showProgressBar();
+                  },
+                  complete: function( jqXHR, settings ){
+                    connector.hideProgressBar();
+                  }
+              
+            });
+        }
+    }
+	messages_proxy.prototype.messages_list_old = function(folder,msg_range_begin,emails_per_page,sort_box_type,search_box_type,sort_box_reverse,preview_msg_subject,preview_msg_tip,call_back) {
 		if(this.is_local_folder(folder)) {
 			var real_folder = folder.substr(6);		
@@ -53,9 +122,13 @@
 	messages_proxy.prototype.get_msg = function(msg_number,msg_folder,set_flag,call_back) {
 		if(this.is_local_folder(msg_folder)) {
-			if(set_flag)
-				expresso_local_messages.set_messages_flag(msg_number,"seen");
-			var data = expresso_local_messages.get_local_mail(msg_number);	
-
-			eval("call_back(data)");
+			
+
+            //if(set_flag)
+			// 	expresso_local_messages.set_messages_flag(msg_number,"seen");
+			// var data = expresso_local_messages.get_local_mail(msg_number);	
+            //MAILARCHIVER-02
+            expresso_mail_archive.getMessage(msg_number);
+
+			//eval("call_back(data)");
 		}else{
 		    $.ajax({
@@ -119,7 +192,10 @@
 
 		if(info_msg.local_message==true) {
-			return "javascript:download_local_attachment('"+
-					expresso_local_messages.get_url_anexo(info_msg.msg_number,info_msg.attachments[numero_ordem_anexo].pid)+
-					"')";
+            //ma serpro
+			// return "javascript:download_local_attachment('"+
+			// 		expresso_local_messages.get_url_anexo(info_msg.msg_number,info_msg.attachments[numero_ordem_anexo].pid)+
+			// 		"')";
+            //MAILARCHIVER-04
+            return "javascript:download_local_attachment('"+ mail_archive_protocol+'://'+mail_archive_host+':'+mail_archive_port+'/temp/download/' +info_msg.attachments[numero_ordem_anexo].pid + "')";
 		}
 		else {
@@ -140,5 +216,6 @@
 	messages_proxy.prototype.proxy_set_messages_flag = function (flag,msg_number){
 		if(this.is_local_folder(get_current_folder())) {
-			expresso_local_messages.set_messages_flag(msg_number,flag);
+            //mail archiver
+			//expresso_local_messages.set_messages_flag(msg_number,flag);
 		}
 		else {
Index: sandbox/2.5.0-expresso1/expressoMail1_2/js/local_messages.js
===================================================================
--- sandbox/2.5.0-expresso1/expressoMail1_2/js/local_messages.js	(revision 5264)
+++ sandbox/2.5.0-expresso1/expressoMail1_2/js/local_messages.js	(revision 7146)
@@ -157,5 +157,8 @@
 
 local_messages.prototype.init_local_messages = function(){ //starts only database operations
-		
+		return 'retorno local_messages.prototype.init_local_messages';
+}
+
+local_messages.prototype.init_local_messages_old = function(){
     if(this.dbGears==null || this.localServer==null || this.store == null)
 	this.create_objects();
@@ -835,5 +838,7 @@
 
 local_messages.prototype.get_local_range_msgs = function(folder,msg_range_begin,emails_per_page,sort,sort_reverse,search,preview_msg_subject,preview_msg_tip) {
-
+        this.init_local_messages();
+}
+local_messages.prototype.get_local_range_msgs_old = function(folder,msg_range_begin,emails_per_page,sort,sort_reverse,search,preview_msg_subject,preview_msg_tip) {
     this.init_local_messages();
     var retorno = new Array();
Index: sandbox/2.5.0-expresso1/expressoMail1_2/js/MAExpressoPattern.js
===================================================================
--- sandbox/2.5.0-expresso1/expressoMail1_2/js/MAExpressoPattern.js	(revision 7146)
+++ sandbox/2.5.0-expresso1/expressoMail1_2/js/MAExpressoPattern.js	(revision 7146)
@@ -0,0 +1,1649 @@
+<!--
+/* 
+ * MailArchiver Expresso Pattern serialized format
+ * ---
+ * This resources intended to be used on converting data formats, to make
+ * it work on ExpressoMail pattern.
+ * 
+ * Basicly, it gets all the service return data (almost enveloped at SOAP 
+ * webservices spec i.e XML data), and then transform it to the serialized
+ * pattern used by Expresso (somethink almost close or near JSON Javascript 
+ * objects).
+ * 
+ * @author Fernando Wendt [fernando-alberto.wendt@serpro.gov.br]
+ *
+ * @status under development
+ * 
+ */
+var MAPattern = function(){
+    
+}
+// -----------------------------------SERIALIZED DATA TEMPLATES ----------------
+MAPattern.prototype.toExpressoAddress = function(data){   
+    if((typeof(data) != 'undefined') && (data.length > 0)){
+
+        if((typeof(data) != 'string') || (data.indexOf("{") == -1)){
+            var objMsg = expresso_mail_archive.getMessageServiceObject(data);
+            var attData = objMsg.getTo();
+            var Fromdata = attData ? eval("(" + attData + ")") : null;
+            if (Fromdata == null)
+                return('N;');
+        }
+        else{
+            var Fromdata = data ?  eval("(" + data + ")") : null;
+            if (Fromdata == null){
+                return('N;');     
+            }
+            else{
+                if((!Fromdata.mailbox) && (!Fromdata.groupbox)){
+                    var nofrom = get_lang('Sender not identified');
+                    return('a:2{s:4:"name";s:' + nofrom.length + ':"' + nofrom + '";s:5:"email";s:'+nofrom.length +':"'+nofrom +'";}');
+                }
+            }
+        }       
+        
+        //var Fromdata = eval("(" + data + ")");
+        if(Fromdata.mailbox){
+            //just one address to pharse: length is undefined
+            if(typeof(Fromdata.mailbox.length) == 'undefined'){
+                var objfrom = Fromdata.mailbox;
+                flag1 = 1;
+            }
+            else{
+                var objfrom = Fromdata.mailbox[0];
+                flag1 = 2;
+            }
+            
+            if(objfrom["@name"] != 'null')
+                var dataName = (objfrom["@name"]);
+            else
+                var dataName = "";
+                
+            if(objfrom["@localPart"] != 'null')
+                var dataEmailPart = (objfrom["@localPart"]);
+            else 
+                var dataEmailpart = "";
+                
+            if(objfrom["@domain"] != 'null')
+                var dataEmailDomain = (objfrom["@domain"]);
+            else
+                var dataEmailDomain = "";
+                
+            if(dataEmailDomain != "")
+                var dataEmail =  dataEmailPart + '@' + dataEmailDomain;
+            else
+                var dataEmail =  dataEmailPart;
+                                
+            if(dataName == '')
+                dataName = dataEmail;
+                
+            var dataTmp = '\"'+dataName+'\"&lt;'+dataEmail+'&gt;'
+            var tplFrom = 'a:3:{'
++                         's:4:"name";'
++                         's:'+dataName.length+':"'+dataName+'";'
++                         's:5:"email";'
++                         's:'+dataEmail.length+':"'+dataEmail+'";'
++                         's:4:"full";'
++                         's:'+(dataTmp.length)+':"'+dataTmp+'";'
++                         '}';                
+        }
+        else{
+            if(Fromdata.group){
+                //just one address to pharse: length is undefined
+                if(typeof(Fromdata.group.length) == 'undefined'){
+                    if(Fromdata.group["@name"]){
+                        var dataName = Fromdata.group["@name"];
+                    }
+                    else
+                        var dataName = null;
+                    
+                    if(Fromdata.group["@localPart"]){
+                        var dataEmail = Fromdata.group["@localPart"] + '@' + Fromdata.group["@domain"];
+                    }
+                    else
+                        var dataEmail = null;
+                    
+                    if(dataName == 'null')
+                        dataName = dataEmail;
+                }
+                //address list to pharse, but to header(folder list messages action), only first metters
+                else{
+                    var dataName = Fromdata.group[0]["@name"];
+                    var dataEmail = Fromdata.group[0]["@localPart"] + '@' + Fromdata.group[0]["@domain"];
+                    if(dataName == 'null')
+                        dataName = dataEmail;
+                }
+            
+            if((dataName != null) && (dataEmail != null)){
+                var dataTmp = '\"'+dataName+'\"&lt;'+dataEmail+'&gt;'
+                var tplFrom = 'a:3:{'
++                         's:4:"name";'
++                         's:'+dataName.length+':"'+dataName+'";'
++                         's:5:"email";'
++                         's:'+dataEmail.length+':"'+dataEmail+'";'
++                         's:4:"full";'
++                         's:'+(dataTmp.length)+':"'+dataTmp+'";'
++                         '}';               
+            }
+            else{
+                if(dataName!= null){
+                var tplFrom = 'a:2:{'
++                         's:4:"name";'
++                         's:'+dataName.length+':"'+dataName+'";'
++                         's:4:"full";'
++                         's:'+(dataName.length)+':"'+dataName+'";'
++                         '}';                     
+                }
+                else{
+                    if(dataEmail != null){
+                    var tplFrom = 'a:2:{'
++                         's:4:"email";'
++                         's:'+dataEmail.length+':"'+dataEmail+'";'
++                         's:4:"full";'
++                         's:'+(dataEmail.length)+':"'+dataEmail+'";'
++                         '}';                         
+                    }
+                    else tplFrom = 'a:2{s:4:"name";s:14:"Unknow mailbox";s:5:"email";s:15:"Unknow_mailbox";}';
+                }
+            }
+           }   
+           //Data adrress from mailbox is empty, null, or canot be correctly returned by service invocation (will return 'unknow mailbox' string)
+           else {
+                tplFrom = 'N;';
+           }       
+        }
+    }
+    else{
+        tplFrom = 'N;';
+    }
+    return(tplFrom);
+}
+
+MAPattern.prototype.toExpressoCc = function(data){
+    if((typeof(data) != 'undefined') && (data.length > 0)){
+        var Fromdata = eval("(" + data + ")");
+        if(Fromdata.mailbox){
+        //just one address to pharse: length is undefined
+            if(typeof(Fromdata.mailbox.length) == 'undefined'){
+                var dataName = Fromdata.mailbox["@name"];
+                var dataEmail = Fromdata.mailbox["@localPart"] + '@' + Fromdata.mailbox["@domain"];
+                if (dataName == 'null')
+                    var dataFull = 's:'+(dataEmail.length)+':"'+dataEmail+'";';
+                else{
+                    var dataTmp = '\"'+dataName+'\"&lt;'+dataEmail+'&gt;'
+                    var dataFull = 's:'+(dataTmp.length)+':"'+dataTmp+'";'
+                }
+            }
+            //address list to pharse, but to header(folder list messages action), only first metters
+            else{
+                    var dataTmp = '';
+                    for( i in Fromdata.mailbox){
+                        var dataName = Fromdata.mailbox[i]["@name"];
+                        var dataEmail = Fromdata.mailbox[i]["@localPart"] + '@' + Fromdata.mailbox[i]["@domain"];
+                        if (dataName == 'null')
+                             dataTmp = dataTmp + dataEmail+',';
+                        else{
+                             dataTmp = dataTmp + '\"'+dataName+'\"&lt;'+dataEmail+'&gt;,';
+                            }
+                }
+                dataTmp = dataTmp.substring(0,(dataTmp.length - 1));
+                 var dataFull = 's:'+(dataTmp.length)+':"'+dataTmp+'";'
+
+            }
+
+            var tplCc = dataFull;
+
+        }
+        else {
+            tplCc = 'N;';
+        }
+    }
+    //Data adrress from mailbox is empty, null, or canot be correctly returned by service invocation (will return 'unknow mailbox' string)
+    else {
+        tplCc = 'N;';
+    }
+    
+    return(tplCc);
+    
+}
+
+MAPattern.prototype.toExpressoDispositionNotificationTo = function(data){
+    var objMsg = expresso_mail_archive.getMessageServiceObject(data);
+    var dntData = objMsg.getDispositionNotificationTo();
+
+    if((typeof(dntData) != 'undefined') && (dntData.length > 0)){
+        var notificationData = eval("(" + dntData + ")");
+        if(notificationData.mailbox){
+            //just one address to pharse: length is undefined
+            if(typeof(notificationData.mailbox.length) == 'undefined'){
+                var dataEmail = notificationData.mailbox["@localPart"] + '@' + notificationData.mailbox["@domain"];
+            }
+            //address list to parse, but to header(folder list messages action), only first matters
+            else{
+                var dataEmail = notificationData.mailbox[0]["@localPart"] + '@' + notificationData.mailbox[0]["@domain"];
+            }
+
+            var tplNotification = 's:25:"DispositionNotificationTo";s:' + dataEmail.length + ':"' + dataEmail + '";'
+        }
+        //Data adrress from mailbox is empty, null, or canot be correctly returned by service invocation (will return 'unknow mailbox' string)
+        else {
+            tplNotification = 's:25:"DispositionNotificationTo";N;';
+        }
+    }
+    else {
+        tplNotification = 's:25:"DispositionNotificationTo";N;';
+    }
+
+    return tplNotification;
+}
+
+MAPattern.prototype.toExpressoAddress2 = function(data){
+    if((typeof(data) != 'undefined') && (data.length > 0)){
+        if((typeof(data) != 'string') || (data.indexOf("{") == -1)){
+            var objMsg = expresso_mail_archive.getMessageServiceObject(data);
+            var attData = objMsg.getTo();
+            var Fromdata = attData ? eval("(" + attData + ")") : null;
+            if (Fromdata == null){                
+                var noto = get_lang("without destination");
+                return('s:10:"toaddress2";s:' + noto.length + ':"'+noto+'";');
+            }
+        }
+        else{
+            var Fromdata = data ?  eval("(" + data + ")") : null;
+            if (Fromdata == null)
+                return('s:10:"toaddress2";N;');                        
+        }       
+       
+        if(Fromdata && Fromdata.mailbox){
+            //just one address to pharse: length is undefined
+            if(typeof(Fromdata.mailbox.length) == 'undefined'){
+                var dataEmail = Fromdata.mailbox["@localPart"] + '@' + Fromdata.mailbox["@domain"];
+            }
+            //address list to pharse, but to header(folder list messages action), only first metters
+            else{
+                var datatmp = "";
+                for(var k=0; k<Fromdata.mailbox.length; k++){                    
+                    if(Fromdata.mailbox[k]["@name"] != 'null'){
+                        datatmp += '"' + Fromdata.mailbox[k]["@name"] + '" ';
+                        if(Fromdata.mailbox[k]["@localPart"] != 'null')
+                            datatmp += '&lt;' + Fromdata.mailbox[k]["@localPart"];
+                        if(Fromdata.mailbox[k]["@domain"] != 'null')
+                            datatmp += '@' + Fromdata.mailbox[k]["@domain"] + '&gt;';                    
+                        else
+                            datatmp += '&gt;';
+                    }
+                    else{
+                        if(Fromdata.mailbox[k]["@localPart"] != 'null')
+                            datatmp += Fromdata.mailbox[k]["@localPart"];
+                        if(Fromdata.mailbox[k]["@domain"] != 'null')
+                            datatmp += '@' + Fromdata.mailbox[k]["@domain"];
+                    }
+                    if(datatmp != '')
+                        datatmp += ', ';
+                }
+                datatmp = datatmp.substr(0, datatmp.length -2);
+                var dataEmail = datatmp;
+                
+                //var dataEmail = Fromdata.mailbox[0]["@localPart"] + '@' + Fromdata.mailbox[0]["@domain"];
+            }
+
+            //var tplAddr2 = 's:10:"toaddress2";s:' + dataEmail.length + ':"' + dataEmail + '";'
+            var tplAddr2 = 's:10:"toaddress2";s:' + dataEmail.length + ':"' + dataEmail + '";'
+        }
+        else{
+            if(Fromdata && Fromdata.group){
+                //just one address group to pharse
+                if(typeof(Fromdata.group.length) == 'undefined'){   
+                    //there is a group email identifier
+                    if(Fromdata.group['@localPart']){
+                        var dataEmail = Fromdata.group["@localPart"] + '@' + Fromdata.group["@domain"];
+                    }
+                    //there is no email identifier, will try by name
+                    else{
+                        if(Fromdata.group['@name']){
+                            var dataEmail = '"' + Fromdata.group['@name'] + '"';                        
+                        }
+                        else{
+                            dataEmail = 'N';
+                        }
+                    } 
+
+                }
+                //group address list to pharse, but to header(folder list messages action), only first metters
+                else{
+                    var dataEmail = Fromdata.group[0]["@localPart"] + '@' + Fromdata.group[0]["@domain"];
+                }
+
+                var tplAddr2 = 's:10:"toaddress2";s:' + dataEmail.length + ':"' + dataEmail + '";'                
+            }
+            //Data adrress from mailbox is empty, null, or canot be correctly returned by service invocation (will return 'unknow mailbox' string)
+            else {
+                tplAddr2 = 's:10:"toaddress2";s:1:"N";';
+            }
+        }
+
+    }
+    else{
+        //tplAddr2 = 's:10:"toaddress2";s:1:"";';
+        var noto = get_lang("without destination");
+        tplAddr2 = 's:10:"toaddress2";s:' + noto.length + ':"'+noto+'";';
+    }
+    return(tplAddr2);
+}
+
+
+MAPattern.prototype.toExpressoSender = function(data){
+    if((typeof(data) != 'undefined') && (data.length > 0)){
+        if((typeof(data) != 'string') || (data.indexOf("{") == -1)){
+            var objMsg = expresso_mail_archive.getMessageServiceObject(data);
+            var attData = objMsg.getSender();
+            var Fromdata = attData ? eval("(" + attData + ")") : null;
+            if (Fromdata == null)
+                return('s:6:"sender";N;');
+        }
+        else{
+            var Fromdata = data ?  eval("(" + data + ")") : null;
+            if (Fromdata == null)
+                return('s:6:"sender";N;');                        
+        }       
+        
+        //var Fromdata = eval("(" + data + ")");
+        if(Fromdata.mailbox){
+            //just one address to pharse: length is undefined
+            if(typeof(Fromdata.mailbox.length) == 'undefined'){
+                var objfrom = Fromdata.mailbox;
+                flag1 = 1;
+            }
+            else{
+                var objfrom = Fromdata.mailbox[0];
+                flag1 = 2;
+            }
+            
+            if(objfrom["@name"] != 'null')
+                var dataName = (objfrom["@name"]);
+            else
+                var dataName = "";
+                
+            if(objfrom["@localPart"] != 'null')
+                var dataEmailPart = (objfrom["@localPart"]);
+            else 
+                var dataEmailpart = "";
+                
+            if(objfrom["@domain"] != 'null')
+                var dataEmailDomain = (objfrom["@domain"]);
+            else
+                var dataEmailDomain = "";
+                
+            if(dataEmailDomain != "")
+                var dataEmail =  dataEmailPart + '@' + dataEmailDomain;
+            else
+                var dataEmail =  dataEmailPart;
+                
+            if(dataName == '')
+                dataName = dataEmail;
+                
+            var dataTmp = '\"'+dataName+'\"&lt;'+dataEmail+'&gt;'
+            
+            var tplFrom = 'a:3:{'
++                         's:4:"name";'
++                         's:'+dataName.length+':"'+dataName+'";'
++                         's:5:"email";'
++                         's:'+dataEmail.length+':"'+dataEmail+'";'
++                         's:4:"full";'
++                         's:'+(dataTmp.length)+':"'+dataTmp+'";'
++                         '}';                
+            }
+            else{
+                if(Fromdata.group){
+                    //just one address to pharse: length is undefined
+                    if(typeof(Fromdata.group.length) == 'undefined'){
+                        if(Fromdata.group["@name"]){
+                            var dataName = Fromdata.group["@name"];
+                        }
+                        else
+                            var dataName = null;
+                    
+                        if(Fromdata.group["@localPart"]){
+                            var dataEmail = Fromdata.group["@localPart"] + '@' + Fromdata.group["@domain"];
+                        }
+                        else
+                            var dataEmail = null;
+                    
+                        if(dataName == 'null')
+                            dataName = dataEmail;
+                    }
+                    //address list to pharse, but to header(folder list messages action), only first metters
+                    else{
+                        var dataName = Fromdata.group[0]["@name"];
+                        var dataEmail = Fromdata.group[0]["@localPart"] + '@' + Fromdata.group[0]["@domain"];
+                        if(dataName == 'null')
+                            dataName = dataEmail;
+                    }
+            
+                if((dataName != null) && (dataEmail != null)){
+                    var dataTmp = '\"'+dataName+'\"&lt;'+dataEmail+'&gt;'
+                    var tplFrom = 'a:3:{'
++                         's:4:"name";'
++                         's:'+dataName.length+':"'+dataName+'";'
++                         's:5:"email";'
++                         's:'+dataEmail.length+':"'+dataEmail+'";'
++                         's:4:"full";'
++                         's:'+(dataTmp.length)+':"'+dataTmp+'";'
++                         '}';               
+                }
+                else{
+                    if(dataName!= null){
+                    var tplFrom = 'a:2:{'
++                         's:4:"name";'
++                         's:'+dataName.length+':"'+dataName+'";'
++                         's:4:"full";'
++                         's:'+(dataName.length)+':"'+dataName+'";'
++                         '}';                     
+                    }
+                    else{
+                        if(dataEmail != null){
+                        var tplFrom = 'a:2:{'
++                         's:4:"email";'
++                         's:'+dataEmail.length+':"'+dataEmail+'";'
++                         's:4:"full";'
++                         's:'+(dataEmail.length)+':"'+dataEmail+'";'
++                         '}';                         
+                        }
+                        else tplFrom = 'a:2{s:4:"name";s:14:"Unknow mailbox";s:5:"email";s:15:"Unknow_mailbox";}';
+                    }
+                }
+            }   
+           else {
+                tplFrom = 'N;';
+           }       
+        }
+    }
+    else{
+        tplFrom = 'N;';
+    }
+    return('s:6:"sender";' + tplFrom);
+}
+
+MAPattern.prototype.toExpressoReplyTo = function(data){
+    if((typeof(data) != 'undefined') && (data.length > 0)){
+
+        if((typeof(data) != 'string') || (data.indexOf("{") == -1)){
+            var objMsg = expresso_mail_archive.getMessageServiceObject(data);
+            var attData = objMsg.getReplyTo();
+            var Fromdata = attData ? eval("(" + attData + ")") : null;
+            if (Fromdata == null)
+                return('s:8:"reply_to";N;');            
+        }
+        else{
+            var Fromdata = data ?  eval("(" + data + ")") : null;
+            if (Fromdata == null)
+                return('s:8:"reply_to";N;');                        
+        }       
+        
+        //var Fromdata = eval("(" + data + ")");        
+        if(Fromdata.mailbox){
+            //just one address to pharse: length is undefined
+            if(typeof(Fromdata.mailbox.length) == 'undefined'){
+                var objfrom = Fromdata.mailbox;
+                flag1 = 1;
+            }
+            else{
+                var objfrom = Fromdata.mailbox[0];
+                flag1 = 2;
+            }
+            
+            if(objfrom["@name"] != 'null')
+                var dataName = (objfrom["@name"]);
+            else
+                var dataName = "";
+                
+            if(objfrom["@localPart"] != 'null')
+                var dataEmailPart = (objfrom["@localPart"]);
+            else 
+                var dataEmailpart = "";
+                
+            if(objfrom["@domain"] != 'null')
+                var dataEmailDomain = (objfrom["@domain"]);
+            else
+                var dataEmailDomain = "";
+                
+            if(dataEmailDomain != "")
+                var dataEmail =  dataEmailPart + '@' + dataEmailDomain;
+            else
+                var dataEmail =  dataEmailPart;
+                
+            if(dataName == '')
+                tplFrom = dataEmail;
+            else
+                tplFrom = '\"'+dataName+'\" &lt;'+dataEmail+'&gt;'                
+            
+           
+            //tplFrom = dataEmail;
+            
+            }
+            else{
+                if(Fromdata.group){
+                    //just one address to pharse: length is undefined
+                    if(typeof(Fromdata.group.length) == 'undefined'){
+                        if(Fromdata.group["@name"]){
+                            var dataName = Fromdata.group["@name"];
+                        }
+                        else
+                            var dataName = null;
+                    
+                        if(Fromdata.group["@localPart"]){
+                            var dataEmail = Fromdata.group["@localPart"] + '@' + Fromdata.group["@domain"];
+                        }
+                        else
+                            var dataEmail = null;
+                    
+                        if(dataName == 'null')
+                            tplFrom = dataEmail;
+                        else
+                            tplFrom = '\"'+dataName+'\" &lt;'+dataEmail+'&gt;'    
+                        
+                    }
+                    //address list to pharse, but to header(folder list messages action), only first metters
+                    else{
+                        var dataName = Fromdata.group[0]["@name"];
+                        var dataEmail = Fromdata.group[0]["@localPart"] + '@' + Fromdata.group[0]["@domain"];
+                        
+                        if(dataName == 'null')
+                            tplFrom = dataEmail;
+                        else
+                            tplFrom = '\"'+dataName+'\" &lt;'+dataEmail+'&gt;'    
+                    }
+                }   
+                //Data adrress from mailbox is empty, null, or canot be correctly returned by service invocation (will return 'unknow mailbox' string)
+                else {
+                    tplFrom = 'N;';
+                    return('');
+                }       
+            }
+        }
+        else{
+            tplFrom = 'N;';
+            return('')
+        }
+        return('s:8:"reply_to";s:' + tplFrom.length + ':"' + tplFrom + '";');
+}
+
+MAPattern.prototype.toExpressoSearchFrom = function(data){
+    if((typeof(data) != 'undefined') && (data.length > 0)){
+
+        if((typeof(data) != 'string') || (data.indexOf("{") == -1)){
+            var objMsg = expresso_mail_archive.getMessageServiceObject(data);
+            var attData = objMsg.getFrom();
+            var Fromdata = attData ? eval("(" + attData + ")") : null;
+            if (Fromdata == null)
+                return('N;');
+        }
+        else{
+            var Fromdata = data ?  eval("(" + data + ")") : null;
+            if (Fromdata == null)
+                return('N;');            
+        }       
+        
+        //var Fromdata = eval("(" + data + ")");
+        if(Fromdata.mailbox){
+            //just one address to pharse: length is undefined
+            if(typeof(Fromdata.mailbox.length) == 'undefined'){
+                var objfrom = Fromdata.mailbox;
+            }
+            else{
+                var objfrom = Fromdata.mailbox[0];
+            }
+            
+            if(objfrom["@name"] != 'null')
+                var tplSearchFrom = (objfrom["@name"]);
+            else{                
+                if(objfrom["@localPart"] != 'null')
+                   var dataEmailPart = (objfrom["@localPart"]);
+                else 
+                   var dataEmailpart = "";
+                
+                if(objfrom["@domain"] != 'null')
+                    var dataEmailDomain = (objfrom["@domain"]);
+                else
+                    var dataEmailDomain = "";
+                
+                if(dataEmailDomain != "")
+                    var tplSearchFrom =  dataEmailPart + '@' + dataEmailDomain;
+                else
+                    var tplSearchFrom =  dataEmailPart;
+            }
+        }
+        else{
+            if(Fromdata.group){
+                //just one address to pharse: length is undefined
+                if(typeof(Fromdata.group.length) == 'undefined'){
+                    if(Fromdata.group["@name"]){
+                        var tplSearchFrom = Fromdata.group["@name"];
+                    }
+                    else{
+                    
+                        if(Fromdata.group["@localPart"]){
+                            var tplSearchFrom = Fromdata.group["@localPart"] + '@' + Fromdata.group["@domain"];
+                        }
+                        else
+                            var tplSearchFrom = null;
+                    }
+                    
+                }
+                //address list to pharse, but to header(folder list messages action), only first metters
+                else{
+                    var dataName = Fromdata.group[0]["@name"];
+                    var dataEmail = Fromdata.group[0]["@localPart"] + '@' + Fromdata.group[0]["@domain"];
+                    if(dataName == 'null')
+                        var tplSearchFrom = dataEmail;
+                    else
+                        var tplSearchFrom = dataName;
+                }
+            
+        }
+    }
+    }
+    else{
+        var tplSearchFrom = 'N;';
+    }
+    //window.alert('from search = ' + tplSearchFrom);
+    return(tplSearchFrom);
+}
+
+
+MAPattern.prototype.toExpressoSubject = function(data){
+    if((typeof(data) != 'undefined') && (data.length > 0)){
+        var tplSbj = 's:'+data.length+':"'+data+'";'
+    }
+    //Subject is empty, null, or canot be correctly returned by service invocation (will return 'Message without subject' string)
+    else {
+        tplSbj = 's:25:"[Message without subject]";';
+    }
+    return(tplSbj);
+}
+
+MAPattern.prototype.toExpressoPreview = function(data){
+    //var objMsg = expresso_mail_archive.getMessageServiceObject(data);
+    var prwData = data;
+    
+    
+    if(prwData){
+        if((typeof(prwData) != 'undefined') && (prwData.length > 0)){
+            var tplSbj = 's:'+prwData.length+':"'+prwData+'";'
+        }
+        else {
+            tplSbj = 's:1:" ";';
+        }
+    }
+    else
+        tplSbj = 's:1:" ";';
+    return(tplSbj);
+}
+
+MAPattern.prototype.toExpressoAttachmentsHeader = function(data){
+    if((typeof(data) != 'undefined') && (data.length > 2)){
+        var Attdata = eval("(" + data + ")");
+        if(typeof(Attdata.attachment) != 'undefined'){                    
+            var tplAttatch = 'a:2:{'
++               's:5:"names";';
+            //More than 1 attachment - because length will be 'undefined' if just one exists
+            if(Attdata.attachment.length > 0){
+                var strnamesatt = "";
+                for(var x=0; x<Attdata.attachment.length; x++){
+                  var attId = Attdata.attachment[x]["@id"];
+                  var attName = Attdata.attachment[x]["@name"];
+                  var attSize = Attdata.attachment[x]["@size"];
+                  var attMediaType = Attdata.attachment[x]["@mediaType"];
+                  var attSubType = Attdata.attachment[x]["@subType"];
+                  var attEncoding = Attdata.attachment[x]["@encoding"];
+                  
+                  strnamesatt += attName + ', ';
+                }
+                strnamesatt = strnamesatt.substr(0, strnamesatt.length-2);
+                var intnumberatt = Attdata.attachment.length;
+            }
+            //Just one attachment
+            else{
+                var attId = Attdata.attachment["@id"];
+                var attName = Attdata.attachment["@name"];
+                var attSize = Attdata.attachment["@size"];
+                var attMediaType = Attdata.attachment["@mediaType"];
+                var attSubType = Attdata.attachment["@subType"];
+                var attEncoding = Attdata.attachment["@encoding"];
+                strnamesatt = attName;
+                var intnumberatt = 1;
+            }
+            
+            tplAttatch += 's:'+strnamesatt.length+':"'+strnamesatt+'";'
++               's:18:"number_attachments";i:' +intnumberatt+';'
++           '}';
+        }
+        else {
+            tplAttatch = 'a:2:{s:5:"names";b:0;s:18:"number_attachments";i:0;}';    
+        }
+    }
+    //No attatch data
+    else {
+        tplAttatch = 'a:2:{s:5:"names";b:0;s:18:"number_attachments";i:0;}';
+    }
+    return(tplAttatch);
+}
+
+MAPattern.prototype.toExpressoDate = function(data){
+    var ndate = new Date(data);
+    var odate = zeroFill(ndate.getDate()) + '/' + zeroFill(ndate.getMonth()+1) + '/' + zeroFill(ndate.getFullYear() + ' ' + zeroFill(ndate.getHours()) + ':' + zeroFill(ndate.getMinutes()) + ':' + zeroFill(ndate.getSeconds()));
+    return(odate);
+}
+
+MAPattern.prototype.toExpressoFlags = function(data){
+    if((data.length > 0) && (typeof(data) != 'undefined')){
+        var Tagdata = eval("(" + data + ")");
+        if(typeof(Tagdata.tag) != 'undefined'){ 
+        //More than 1 attachment: length will be 'undefined' if just one exists
+        if(Tagdata.tag.length >= 0){
+            var strnamestag = "";
+            for(var x=0; x<Tagdata.tag.length; x++){
+                var tagvalue = Tagdata.tag[x]["@value"];
+                if(tagvalue.toLowerCase() == 'recent')
+                    strnamestag += 's:6:"Recent";s:1:"N";';
+                if(tagvalue.toLowerCase() == 'unseen')
+                    strnamestag += 's:6:"Unseen";s:1:"U";';
+                if(tagvalue.toLowerCase() == 'seen')
+                    strnamestag += 's:6:"Unseen";s:1:" ";';                
+                if(tagvalue.toLowerCase() == 'deleted')
+                    strnamestag += 's:7:"Deleted";s:1:"D";';
+                if(tagvalue.toLowerCase() == 'answered')
+                    strnamestag += 's:8:"Answered";s:1:"A";';
+                if(tagvalue.toLowerCase() == 'unanswered')
+                    strnamestag += 's:8:"Answered";s:1:" ";';                
+                if(tagvalue.toLowerCase() == 'forwarded')
+                    strnamestag += 's:9:"Forwarded";s:1:"F";';
+                if(tagvalue.toLowerCase() == 'draft')
+                    strnamestag += 's:5:"Draft";s:1:"X";';
+                if(tagvalue.toLowerCase() == 'importance_high')
+                    strnamestag += 's:10:"Importance";s:4:"High";';
+                if(tagvalue.toLowerCase() == 'flagged')
+                    strnamestag += 's:7:"Flagged";s:1:"F";';
+                if(tagvalue.toLowerCase() == 'unflagged')
+                    strnamestag += 's:7:"Flagged";b:0;';                
+            } 
+            var tplTags = strnamestag; 
+          }
+          
+          else{
+            var strnamestag = "";
+            var tagvalue = Tagdata.tag["@value"];
+                if(tagvalue.toLowerCase() == 'recent')
+                    strnamestag += 's:6:"Recent";s:1:"N";';
+                if(tagvalue.toLowerCase() == 'unseen')
+                    strnamestag += 's:6:"Unseen";s:1:"U";';
+                if(tagvalue.toLowerCase() == 'seen')
+                    strnamestag += 's:6:"Unseen";s:1:" ";';                
+                if(tagvalue.toLowerCase() == 'deleted')
+                    strnamestag += 's:7:"Deleted";s:1:"D";';
+                if(tagvalue.toLowerCase() == 'answered')
+                    strnamestag += 's:8:"Answered";s:1:"A";';
+                if(tagvalue.toLowerCase() == 'unanswered')
+                    strnamestag += 's:8:"Answered";s:1:" ";';                
+                if(tagvalue.toLowerCase() == 'forwarded')
+                    strnamestag += 's:9:"Forwarded";s:1:"F";';
+                if(tagvalue.toLowerCase() == 'draft')
+                    strnamestag += 's:5:"Draft";s:1:"X";';
+                if(tagvalue.toLowerCase() == 'importance_high')
+                    strnamestag += 's:10:"Importance";s:4:"High";';
+                if(tagvalue.toLowerCase() == 'flagged')
+                    strnamestag += 's:7:"Flagged";s:1:"F";';
+                if(tagvalue.toLowerCase() == 'unflagged')
+                    strnamestag += 's:7:"Flagged";b:0;';   
+            var tplTags = strnamestag;
+          }
+      }
+      //Something is wrong with tags: return defaults is no one tag
+      else{
+        tplTags = 's:6:"Recent";s:1:" ";s:6:"Unseen";s:1:" ";s:7:"Deleted";s:1:" ";s:8:"Answered";s:1:" ";s:9:"Forwarded";s:1:" ";s:5:"Draft";s:1:" ";s:10:"Importance";s:6:"Normal";s:7:"Flagged";b:0;';
+      }
+      return(tplTags);
+    }
+}
+
+MAPattern.prototype.toExpressoSearchFlags = function(data){
+    if((data.length > 0) && (typeof(data) != 'undefined')){
+        var Tagdata = eval("(" + data + ")");
+        if(typeof(Tagdata.tag) != 'undefined'){ 
+        //More than 1 attachment: length will be 'undefined' if just one exists
+        var tflagged = false;
+        if(Tagdata.tag.length >= 0){
+            var strnamestag = '';
+            for(var x=0; x<Tagdata.tag.length; x++){
+                var tagvalue = Tagdata.tag[x]["@value"];
+                if(tagvalue.toLowerCase() == 'recent')
+                    strnamestag += 'N';
+                if(tagvalue.toLowerCase() == 'unseen')
+                    strnamestag += 'U';
+                if(tagvalue.toLowerCase() == 'draft')
+                    strnamestag += 'X';
+                if(tagvalue.toLowerCase() == 'flagged')
+                    tflagged = true;
+                if((tagvalue.toLowerCase() == 'importance_high') && tflagged)
+                        strnamestag += 'F';
+            } 
+            var tplTags = strnamestag; 
+          }
+          
+          else{
+            var strnamestag = "";
+            var tflagged = false;
+            var tagvalue = Tagdata.tag["@value"];
+                if(tagvalue.toLowerCase() == 'recent')
+                    strnamestag += 'N';
+                if(tagvalue.toLowerCase() == 'unseen')
+                    strnamestag += 'U';
+                if(tagvalue.toLowerCase() == 'draft')
+                    strnamestag += 'X';
+                /*if(tagvalue.toLowerCase() == 'importance_high')
+                    strnamestag += 'F';
+                if(tagvalue.toLowerCase().indexOf('flagged')!= -1)
+                    strnamestag += 'F';*/
+                if(tagvalue.toLowerCase() == 'flagged')
+                    tflagged = true;
+                if((tagvalue.toLowerCase() == 'importance_high') && tflagged)
+                        strnamestag += 'F';
+            var tplTags = strnamestag;
+          }
+          var tplSearchTags = 's:4:"flag";s:' + tplTags.length + ':"' + tplTags + '";'
+      }
+      //Something is wrong with tags: return defaults is no one tag
+      else{
+        var tplSearchTags = 's:4:"flag";s:1:" ";';
+      }
+      //window.alert('tags to search data\n' + tplSearchTags);
+      return(tplSearchTags);
+    }
+}
+
+MAPattern.prototype.toExpressoHeader = function(data){   
+    var tplHeader = 'a:40:{'
++           's:11:"ContentType";'
++           's:' + data.getContentType().length + ':"' + data.getContentType() + '";'
++           expresso_mail_archive.pattern.toExpressoFlags(data.getTags())
++           's:10:"msg_number";'
++           's:'+data.getId().length+':"'+data.getId()+'";'
++           's:5:"udate";'
++           'i:' + parseInt(data.getDate()/1000) + ';'
++           's:9:"timestamp";'
++           'i:' + parseInt(data.getDate()/1000) + ';'
++           's:4:"from";'
++           expresso_mail_archive.pattern.toExpressoAddress(data.getFrom())
+//+           's:6:"sender":' xpresso_mail_archive.pattern.toExpressoSender(expresso_mail_archive.currentmessage)
++           's:2:"to";'
++           expresso_mail_archive.pattern.toExpressoAddress(data.getTo())
++           expresso_mail_archive.pattern.toExpressoAddress2(data.getTo())
++           's:2:"cc";'
++           expresso_mail_archive.pattern.toExpressoCc(data.getCc())
++           's:3:"bcc";'
++           expresso_mail_archive.pattern.toExpressoCc(data.getBcc())
++           's:7:"subject";'
++           expresso_mail_archive.pattern.toExpressoSubject(data.getSubject())
++           's:4:"Size";'
++           'i:'+data.getSize()+';'
++           's:10:"msg_sample";' + expresso_mail_archive.pattern.toExpressoPreview(data.getPreview())
++           's:10:"attachment";'
++           expresso_mail_archive.pattern.toExpressoAttachmentsHeader(data.getAttachments())
++           '}';
+    return(tplHeader);
+}
+
+MAPattern.prototype.toExpressoSearchHeader = function(data){   
+    //var accid = new String(account_id);
+    var accid = new String(data.getId());
+    //var fdata = data.getFolderId();
+    var fdata = data.getFolderPath();
+    var fname = fdata;
+       
+    var tplHeader = 'a:16:{'
++           's:11:"ContentType";'
++           's:' + data.getContentType().length + ':"' + data.getContentType() + '";'
++           expresso_mail_archive.pattern.toExpressoSearchFlags(data.getTags())
++           's:10:"msg_number";'
++           's:'+data.getId().length+':"'+data.getId()+'";'
++           's:5:"udate";'
++           'i:' + parseInt(data.getDate()/1000) + ';'
++           's:9:"timestamp";'
++           'i:' + parseInt(data.getDate()/1000) + ';'
++           's:4:"from";'
++           's:' + expresso_mail_archive.pattern.toExpressoSearchFrom(data.getFrom()).length + ':"' + expresso_mail_archive.pattern.toExpressoSearchFrom(data.getFrom()) + '";'
+//+           's:6:"sender":' expresso_mail_archive.pattern.toExpressoSender(expresso_mail_archive.currentmessage)
++           's:2:"to";'
++           expresso_mail_archive.pattern.toExpressoAddress(data.getTo())
++           expresso_mail_archive.pattern.toExpressoAddress2(data.getTo())
++           's:2:"cc";'
++           expresso_mail_archive.pattern.toExpressoCc(data.getCc())
++           's:3:"bcc";'
++           expresso_mail_archive.pattern.toExpressoCc(data.getBcc())
++           's:7:"subject";'
++           expresso_mail_archive.pattern.toExpressoSubject(data.getSubject())
++           's:4:"size";'
++           'i:'+data.getSize()+';'
++           's:3:"uid";'
++           's:'+ accid.length + ':"' + accid + '";'
++           's:7:"boxname";'
++           's:'+(fname.length + 6)+':"local_' + fname + '";'
++           's:10:"msg_sample";' + expresso_mail_archive.pattern.toExpressoPreview(data.getPreview())
++           's:10:"attachment";'
++           expresso_mail_archive.pattern.toExpressoAttachmentsHeader(data.getAttachments())
++           '}';
+
+    //window.alert('return from TplSearchHeader:\n' + tplHeader);
+    
+    return(tplHeader);
+}
+
+/*
+MAPattern.prototype.toExpressoBody = function(mheader){
+    var tplBody = 'a:33:{'
++                   's:4:"body";N;'
++                   's:11:"attachments";N;'
++                   's:6:"thumbs";N;'
++                   's:9:"signature";N;'
++                   's:10:"Importance";s:6:"Normal";'
++                   's:6:"Recent";s:1:" ";'
++                   's:6:"Unseen";s:1:"N";'
++                   's:7:"Deleted";s:1:" ";'
++                   's:7:"Flagged";b:0;'
++                   's:8:"Answered";s:1:" ";'
++                   's:5:"Draft";s:1:" ";'
++                   's:10:"msg_number";s:4:"2241";'
++                   's:10:"msg_folder";s:5:"INBOX";'
++                   's:5:"udate";s:5:"10:01";'
++                   's:7:"msg_day";s:10:"10/05/2011";'
++                   's:8:"msg_hour";s:5:"10:02";'
++                   's:8:"fulldate";s:36:"10/05/2011 10:01 (05:35 horas atras)";'
++                   's:9:"smalldate";s:5:"10:04";'
++                   's:4:"from";N;'
++                   's:6:"sender";a:3:{'
++                       's:4:"name";N;'
++                       's:5:"email";s:46:"listaregional-pae-bounces@grupos.serpro.gov.br";'
++                       's:4:"full";s:46:"listaregional-pae-bounces@grupos.serpro.gov.br";'
++                   '}'
++                   's:10:"toaddress2";s:32:"comunicacao.social@serpro.gov.br";'
++                   's:2:"cc";N;'
++                   's:3:"bcc";N;'
++                   's:8:"reply_to";N;'
++                   's:7:"subject";N;'
++                   's:4:"Size";s:4:"1234";'
++                   's:15:"reply_toaddress";s:45:"com.social <comunicacao.social@serpro.gov.br>";'
++                   's:9:"timestamp";i:1305032476;'
++                   's:5:"login";i:944889240;'
++                   's:6:"header";a:16:{'
++                      's:11:"ContentType";s:6:"normal";'
++                      's:10:"Importance";s:6:"Normal";'
++                      's:6:"Recent";s:1:" ";'
++                      's:6:"Unseen";s:1:"N";'
++                      's:8:"Answered";s:1:" ";'
++                      's:5:"Draft";s:1:" ";'
++                      's:7:"Deleted";s:1:" ";'
++                      's:7:"Flagged";b:0;'
++                      's:10:"msg_number";s:4:"2251";'
++                      's:5:"udate";s:10:"10/05/2011";'
++                      's:11:"offsetToGMT";i:-10800;'
++                      's:8:"aux_date";N;'
++                      's:4:"from";a:2:{'
++                         's:4:"name";s:10:"com.social";'
++                         's:5:"email";s:32:"comunicacao.social@serpro.gov.br";'
++                      '}'
++                      's:2:"to";a:2:{'
++                         's:4:"name";s:32:"comunicacao.social@serpro.gov.br";'
++                         's:5:"email";s:32:"comunicacao.social@serpro.gov.br";'
++                      '}'
++                      's:7:"subject";s:28:"Primeira leitura - 10/5/2011";'
++                      's:4:"Size";N;'
++                      's:10:"attachment";a:2:{'
++                         's:5:"names";b:0;'
++                         's:18:"number_attachments";i:0;'
++                      '}'
++                  '}'
++                  's:12:"array_attach";N;'
++                  's:15:"url_export_file";s:160:"inc/gotodownload.php?idx_file=/var/www/expressov2/expressoMail1_2/inc/../tmpLclAtt/source_38a3e960115351578aa182ae1d6c2b7b.txt&newfilename=fonte_da_mensagem.txt";'
++                  's:2:"to";N;'
++              '}';
+    return(tplBody);
+}
+*/
+
+MAPattern.prototype.toExpressoMailDataHeader = function(msgid){
+    var tplHMail = "";
+    var tmpHead = expresso_mail_archive.getMessageHeaders(msgid);
+    return tplHMail;    
+}
+
+MAPattern.prototype.toExpressoMailData = function(msg){
+    var tplBMail = "";
+    
+    return(tplBMail);
+}
+
+MAPattern.prototype.toExpressoMailAttachment = function(att){    
+    var objMsg = expresso_mail_archive.getMessageServiceObject(att);
+    var attData = objMsg.getAttachments();
+    var objAtt =  eval("(" + attData + ")");
+    var srlData = "";
+
+    //There are attachments
+    if(typeof(objAtt.attachment) != 'undefined'){
+        if(typeof(objAtt.attachment.length) != 'undefined'){
+            srlData = 's:11:"attachments";a:' + objAtt.attachment.length + ':{';
+            for(var m=0; m<objAtt.attachment.length; m++){
+                srlData += 's:1:"' + m + '";'
+                         + 'a:4:{'
+                         + 's:3:"pid";s:' + objAtt.attachment[m]["@id"].length + ':"' + objAtt.attachment[m]["@id"] + '";'
+                         + 's:4:"name";s:' + objAtt.attachment[m]["@name"].length + ':"' + objAtt.attachment[m]["@name"] + '";'
+                         + 's:8:"encoding";s:' + objAtt.attachment[m]["@encoding"].length + ':"' + objAtt.attachment[m]["@encoding"] + '";'
+                         + 's:5:"fsize";i:' + objAtt.attachment[m]["@size"] + ';'
+                         + '}';
+            }
+        }
+        //just one att
+        else{
+            srlData = 's:11:"attachments";a:1:{';
+            srlData += 's:1:"0";'
+                     + 'a:4:{'
+                     + 's:3:"pid";s:' + objAtt.attachment["@id"].length + ':"' + objAtt.attachment["@id"] + '";'
+                     + 's:4:"name";s:' + objAtt.attachment["@name"].length + ':"' + objAtt.attachment["@name"] + '";'
+                     + 's:8:"encoding";s:' + objAtt.attachment["@encoding"].length + ':"' + objAtt.attachment["@encoding"] + '";'
+                     + 's:5:"fsize";i:' + objAtt.attachment["@size"] + ';'
+                     + '}';
+        }
+        srlData += '}';            
+    }    
+    //No attachments data
+    else{
+        srlData = 's:11:"attachments";N;';
+    }
+    return(srlData);
+}
+
+MAPattern.prototype.toExpressoMailThumbs = function(thb){
+    var objMsg = expresso_mail_archive.getMessageServiceObject(thb);
+    var attData = objMsg.getAttachments();
+    var objAtt =  eval("(" + attData + ")");
+    var srlData = "";
+    var arrThumbs = new Array();
+    if(typeof(objAtt.attachment) != 'undefined'){       
+        //more than 1 att
+        if(typeof(objAtt.attachment.length) != 'undefined'){
+            for(var m=0; m<objAtt.attachment.length; m++){
+                //Only images has thums
+                if(objAtt.attachment[m]["@mediaType"].toLowerCase() == 'image')
+                    arrThumbs.push(objAtt.attachment[m]);
+            }
+        }
+        //just one att data
+        else{
+            if(objAtt.attachment["@mediaType"].toLowerCase() == 'image')
+                arrThumbs.push(objAtt.attachment);
+        }
+        //There are thumbs
+        if(arrThumbs.length > 0){
+            srlData = 's:6:"thumbs";a:'+arrThumbs.length+':{'
+            for(var n=0; n<arrThumbs.length; n++){
+                var thumblink = '<a onMouseDown=\'save_image(event,this,"image/'+arrThumbs[n]["@subType"]+'")\' href=\'#'+mail_archive_protocol+'://'+mail_archive_host+':'+mail_archive_port+'/temp/'+arrThumbs[n]["@id"]+'/'+arrThumbs[n]["@name"]+'\' onClick="window.open(\''+mail_archive_protocol+'://'+mail_archive_host+':'+mail_archive_port+'/temp/'+arrThumbs[n]["@id"]+'/' + arrThumbs[n]["@name"] + '\',\'mywindow\',\'width=700,height=600,scrollbars=yes\');"><IMG id=\''+arrThumbs[n]["@id"]+'\' style=\'border:2px solid #fde7bc;padding:5px\' title=\'Clique na imagem para Ampliar.\' src="'+mail_archive_protocol+'://'+mail_archive_host+':'+mail_archive_port+'/temp/'+arrThumbs[n]["@id"]+'/thumb/120/' + arrThumbs[n]["@name"] +'"></a>';
+                srlData += 's:1:"'+n+'";s:'+thumblink.length+':"'+thumblink+'";'
+            }
+            srlData += '}';    
+        }
+        //No thumbs
+        else
+            srlData = 's:6:"thumbs";N;';        
+    }   
+    //Something is wrong with attachments thumb behavior: return no thumbs
+    else{
+        srlData = 's:6:"thumbs";N;';
+    }
+    return(srlData);
+}
+
+MAPattern.prototype.toExpressoMailSignature = function(sgn){
+    return('s:9:"signature";N;');
+}
+
+MAPattern.prototype.toExpressoMailBaseHeaders = function(hdr){
+    var defMailHeaders = {'recent':' ','unseen': ' ','deleted': ' ','answered': ' ','draft': ' ','flagged': ' '};
+    var objMsg = expresso_mail_archive.getMessageServiceObject(hdr);
+    var tagData = objMsg.getTags();
+    var objTag = eval('(' + tagData + ')');
+    var tplHMail = "";
+    
+    if(objTag.tag){
+    //More than 1 attachment - because length will be 'undefined' if just one exists
+    if(objTag.tag.length >= 0){
+
+        //flaggs the tags
+        for(var k=0; k<objTag.tag.length; k++){
+            for(var j in defMailHeaders){
+                var tagvalue = objTag.tag[k]["@value"].toLowerCase();
+                if((tagvalue == j) && (defMailHeaders[j] != true))
+                    defMailHeaders[j] = true;
+                else
+                    defMailHeaders[j] = false;
+            }
+        }
+        
+        //serialize all needed headers       
+        if(defMailHeaders["recent"] == true)
+            tplHMail += 's:6:"Recent";s:1:"N";';
+        else
+            tplHMail += 's:6:"Recent";s:1:" ";';
+        if(defMailHeaders["unseen"] == true)
+            tplHMail += 's:6:"Unseen";s:1:"U";';
+        else
+            tplHMail += 's:6:"Unseen";s:1:" ";';
+        if(defMailHeaders["deleted"] == true)
+            tplHMail += 's:7:"Deleted";s:1:"D";';
+        else
+            tplHMail += 's:7:"Deleted";s:1:" ";';
+        if(defMailHeaders["answered"] == true)
+            tplHMail += 's:8:"Answered";s:1:"A";';
+        else
+            tplHMail += 's:8:"Answered";s:1:" ";';
+        if(defMailHeaders["draft"] == true)
+            tplHMail += 's:5:"Draft";s:1:"X";';
+        else
+            tplHMail += 's:5:"Draft";s:1:" ";';        
+        if(defMailHeaders["flagged"] == true)
+            tplHMail += 's:7:"Flagged";s:1:"F";';
+        else
+            tplHMail += 's:7:"Flagged";s:1:" ";';                      
+    }
+    }
+    
+    //No header to tag
+    else{
+        tplHMail += 's:6:"Recent";s:1:" ";';
+        tplHMail += 's:6:"Unseen";s:1:" ";';
+        tplHMail += 's:7:"Deleted";s:1:" ";';
+        tplHMail += 's:8:"Answered";s:1:" ";';
+        tplHMail += 's:5:"Draft";s:1:" ";';        
+        tplHMail += 's:7:"Flagged";s:1:" ";';              
+    }
+    return tplHMail;        
+}
+
+MAPattern.prototype.toExpressoMailArrayAttach = function(att){
+    var objMsg = expresso_mail_archive.getMessageServiceObject(att);
+    var attData = objMsg.getAttachments();
+    var objAtt =  eval("(" + attData + ")");
+    var srlData = "";
+
+    //There are attacments, map all them
+    if(typeof(objAtt.attachment) != 'undefined'){
+        srlData = 's:12:"array_attach";a:' + objAtt.attachment.length + ':{';
+        for(var m=0; m<objAtt.attachment.length; m++){
+            var urllink = mail_archive_protocol+'://'+mail_archive_host+':'+mail_archive_port+'/temp/download/'+objAtt.attachment[m]["@id"]+'/'+objAtt.attachment[m]["@name"];
+            srlData += 's:1:"' + m + '";'
+                     + 'a:3:{'
+                     + 's:4:"name";s:' + objAtt.attachment[m]["@name"].length + ':"' + objAtt.attachment[m]["@name"] + '";'
+                     + 's:3:"url";s:' + urllink.length + ':"' + urllink + '";'
+                     + 's:3:"pid";s:' + objAtt.attachment[m]["@id"].length + ':"' + objAtt.attachment[m]["@id"] + '";'
+                     + '}';
+        }
+        srlData += '}';
+    }    
+    //No one attachment
+    else{
+        srlData = 's:12:"array_attach";N;';
+    }
+    return(srlData);
+}
+
+MAPattern.prototype.toExpressoMailURLExportFile = function(path, file){
+    var srlData = 's:15:"url_export_file";';
+    var urllink = mail_archive_protocol+'://'+mail_archive_host+':'+mail_archive_port+'/mail/'+path+'/'+file;
+    srlData += 's:' + urllink.length + ':"' + urllink + '";'
+    return(srlData);
+}
+
+MAPattern.prototype.toExpressoMail = function(mheader, mbody){
+    var tplMessage = null;
+    var tplMessageData = null;
+    var tplMessageHeaderData = null;  
+    
+    //Decodes message headers first
+    var hdata = mheader;
+    var h_date = expresso_mail_archive.pattern.toExpressoDate(mheader["udate"]*1000);
+           
+    //Init message template
+    tplMessage = 'a:49{s:4:"body";N;'
++   expresso_mail_archive.pattern.toExpressoMailAttachment(expresso_mail_archive.currentmessage)
++   expresso_mail_archive.pattern.toExpressoMailThumbs(expresso_mail_archive.currentmessage)    
++   expresso_mail_archive.pattern.toExpressoMailSignature(expresso_mail_archive.currentmessage)
++   expresso_mail_archive.pattern.toExpressoMailBaseHeaders(expresso_mail_archive.currentmessage)
++   's:5:"udate";s:8:"' + h_date.split(" ")[1] +'";' //hours
++   's:7:"msg_day";s:10:"'+ h_date.split(" ")[0] +'";' //date
++   's:8:"msg_hour";s:8:"' + h_date.split(" ")[1] +'";' //hours
++   's:8:"fulldate";s:19:"' + h_date +'";' //full date + hours
++   's:9:"smalldate";s:8:"' + h_date.split(" ")[1] +'";' //hours
++   's:10:"msg_number";s:'+expresso_mail_archive.currentmessage.length+':"'+expresso_mail_archive.currentmessage+'";'
++   's:10:"msg_folder";s:'+(expresso_mail_archive.currentfolder.length+6)+':"local_'+expresso_mail_archive.currentfolder+'";'
++   's:4:"from";N;'
++    expresso_mail_archive.pattern.toExpressoSender(expresso_mail_archive.currentmessage)
++    expresso_mail_archive.pattern.toExpressoReplyTo(expresso_mail_archive.currentmessage)
++   's:10:"msg_sample";' + expresso_mail_archive.pattern.toExpressoPreview(expresso_mail_archive.currentmessage)
++    expresso_mail_archive.pattern.toExpressoAddress2(expresso_mail_archive.currentmessage)
++   's:9:"timestamp";i:'+ mheader["udate"]*1000 +';' //getback the lost miliseconds...
++   expresso_mail_archive.pattern.toExpressoDispositionNotificationTo(expresso_mail_archive.currentmessage)
++   's:5:"login";i:' + account_id
++   's:6:"header";' + expresso_mail_archive.pattern.toExpressoHeader(expresso_mail_archive.getMessageServiceObject(expresso_mail_archive.currentmessage)) 
++   expresso_mail_archive.pattern.toExpressoMailArrayAttach(expresso_mail_archive.currentmessage)
++   expresso_mail_archive.pattern.toExpressoMailURLExportFile(expresso_mail_archive.currentfolder, expresso_mail_archive.currentmessage)
++   's:2:"to";N;'
++   '}';
+
+    var strMailMessage = connector.unserialize(tplMessage);
+//    strMessage['from'] = mheader["from"];
+    //strMessage['from'] = expresso_mail_archive.toExpressoBody(mheader, mbody);
+//    strMessage['subject'] = mheader["subject"];
+    strMailMessage['body'] = mbody;
+//    strMessage['to'] = mheader["to"];
+//    strMessage['cc'] = mheader["cc"];
+    strMailMessage['local_message'] = true;
+    strMailMessage['folder'] = 'local_' + expresso_mail_archive.currentfolder;
+    //strMessage['msg_number'] = mheader["msg_number"];
+    //strMailMessage['msg_number'] = mheader["msg_number"];
+    return(strMailMessage);
+}
+
+MAPattern.prototype.toExpressoMessage = function(mheader, mbody){
+    var strMessage = null;
+    var strMessage1 = expresso_mail_archive.pattern.toExpressoBody(mheader);
+    strMessage = connector.unserialize(strMessage1);
+        
+    strMessage['from'] = mheader["from"];
+    //strMessage['from'] = expresso_mail_archive.toExpressoBody(mheader, mbody);
+    strMessage['subject'] = mheader["subject"];
+    strMessage['body'] = mbody;
+    strMessage['to'] = mheader["to"];
+    strMessage['cc'] = mheader["cc"];
+    strMessage['local_message'] = true;
+    strMessage['folder'] = 'local_' + expresso_mail_archive.currentfolder;
+    strMessage['msg_number'] = mheader["msg_number"];
+    return(strMessage);
+
+
+/*
+ *	retorno['from'] = connector.unserialize(rs.field(2));
+	retorno['subject'] = rs.field(3);
+	retorno['body'] = rs.field(4);
+	//Codigo que as imagens embutidas em emails (com multipart/related ou multipart/mixed) sejam corretamente mostradas em emails arquivados. Os links do
+	//tipo "./inc/show_embedded_attach.php?msg_folder=[folder]&msg_num=[msg_num]&msg_part=[part]"
+	//sÃ£o substituidos pelos links dos anexos capturados pelo gears.
+
+	var thumbs= retorno.thumbs;
+	var anexos= retorno.array_attach;
+	for (i in anexos)
+	{
+	    if(anexos[i]['url'] && anexos[i]['url'].match(/((jpg)|(jpeg)|(png)|(gif)|(bmp))/gi))
+	    {
+		var er_imagens = new RegExp("\\.\\/inc\\/show_embedded_attach.php\\?msg_folder=[\\w/]+\\&msg_num=[0-9]+\\&msg_part="+anexos[i]['pid']);
+		var Result_imagens = er_imagens.exec(retorno['body']);
+		retorno['body'] = retorno['body'].replace(Result_imagens,anexos[i]['url']);
+		if(thumbs && thumbs[i]){
+		    er_imagens = new RegExp("\\.\\/inc\\/show_thumbs.php\\?file_type=image\\/[\\w]+\\&msg_num=[0-9]+\\&msg_folder=[\\w/%]+\\&msg_part="+anexos[i]['pid']);
+		    Result_imagens = er_imagens.exec(thumbs[i]);
+		    thumbs[i] = thumbs[i].replace(Result_imagens,"'"+anexos[i]['url']+"'");
+		    er_imagens = new RegExp("\\.\\/inc\\/show_img.php\\?msg_num=[0-9]+\\&msg_folder=[\\w/%]+\\&msg_part="+anexos[i]['pid']);
+		    Result_imagens = er_imagens.exec(thumbs[i]);
+		    thumbs[i] = thumbs[i].replace(Result_imagens,anexos[i]['url']);
+		    thumbs[i] = thumbs[i].replace(/<IMG/i,'<img width="120"'); 
+		}
+	    }
+	}
+
+	retorno['to'] = connector.unserialize(rs.field(5));
+	retorno['cc'] = connector.unserialize(rs.field(6));
+
+	retorno['local_message'] = true;
+	retorno['msg_folder'] = "local_"+rs.field(7); //Now it's a local folder
+	retorno['msg_number'] = rs.field(0)+plus_id; //the message number is the rowid
+ **/ 
+}
+
+MAPattern.prototype.tagConfig = function(taglist, arcidmsg, op){
+    //window.alert('no maexpressopattern.tagconfig:\n' + print_r(taglist));
+    if(taglist != null){
+        var tagdata = "";
+        var flag_draft = false;
+        
+        //first message to tag data
+        if(expresso_mail_archive.taglist == ""){
+            //Draft folder, are "draft"
+            if(expresso_mail_archive.folder_destination == 'drafts'){
+                flag_draft = true;
+                tagdata += '<add value="draft"/>';
+                tagdata += '<remove value="answered"/>';
+                tagdata += '<remove value="forwarded"/>';
+                if (typeof(taglist) == 'object'){
+                    for(var x in taglist[0]){
+                        if (x != 'importance'){
+                            if(( x != 'unseen') && ( x != 'answered')){
+                                if((taglist[0][x] != '') && (taglist[0][x] != ' ') && (taglist[0][x] != null) && (x != 'msgid'))
+                                    tagdata += '<remove value="'+x+'"/>';
+                            }
+                            else{
+                                if( x == 'unseen'){
+                                    if (taglist[0][x] == ' ')
+                                        tagdata += '<remove value="seen"/>';
+                                    else
+                                        if((taglist[0][x] != '') && (taglist[0][x] != null))
+                                            tagdata += '<remove value="unseen"/>';                                
+                                }
+                                if( x == 'answered'){
+                                    if (taglist[0][x] == ' ')
+                                        tagdata += '<remove value="unanswered"/>';
+                                    else
+                                        if((taglist[0][x] != '') && (taglist[0][x] != null))
+                                            tagdata += '<remove value="answered"/>';                                                                    
+                                }                              
+                            }
+                        }
+                        else{
+                            if((taglist[0][x] != '') && (taglist[0][x] != ' ')){
+                                switch (taglist[0][x].toLowerCase()){
+                                    case 'high':
+                                        tagdata += '<remove value="importance_high"/>';
+                                        tagdata += '<remove value="flagged"/>';
+                                        break;
+                                    default:
+                                        tagdata += '<remove value="importance_normal"/>';
+                                        tagdata += '<remove value="unflagged"/>';
+                                        break;                                        
+                                }
+                            }
+                        }
+                    }
+                }
+                else{
+                     if(!flag_draft)
+                        tagdata += '<remove value="'+taglist+'"/>';
+                }
+            }
+            else
+                tagdata += '<remove value="draft"/>';
+        
+            //Trash folder, are "deleted""
+            if(expresso_mail_archive.folder_destination == 'trash'){
+                tagdata += '<add value="deleted"/>';
+            }
+            else
+                tagdata += '<remove value="deleted"/>';
+        
+            if(!flag_draft){
+                var action;
+                if (op == 0)
+                    action = 'add';
+                else
+                    action = 'remove';
+        
+                //object data -used at archieve op
+                if (typeof(taglist) == 'object'){
+                    for(var x in taglist[0]){
+                        if (x != 'importance'){
+                            if(( x != 'unseen') && ( x != 'answered')){
+                                if((taglist[0][x] != '') && (taglist[0][x] != ' ') && (taglist[0][x] != null) && (x != 'msgid'))
+                                    tagdata += '<'+action+' value="'+x+'"/>';
+                            }
+                            else{
+                                if( x == 'unseen'){
+                                    if (taglist[0][x] == ' ')
+                                        tagdata += '<'+action+' value="seen"/>';
+                                    else
+                                        if((taglist[0][x] != '') && (taglist[0][x] != null))
+                                            tagdata += '<'+action+' value="unseen"/>';                                
+                                }
+                                if( x == 'answered'){
+                                    if (taglist[0][x] == ' ')
+                                        tagdata += '<'+action+' value="unanswered"/>';
+                                    else
+                                        if((taglist[0][x] != '') && (taglist[0][x] != null))
+                                            tagdata += '<'+action+' value="answered"/>';                                                                    
+                                }                            
+                            }
+                        }
+                        else{
+                            if((taglist[0][x] != '') && (taglist[0][x] != ' ')){
+                                switch (taglist[0][x].toLowerCase()){
+                                    case 'high':
+                                        tagdata += '<'+action+' value="importance_high"/>';
+                                        tagdata += '<'+action+' value="flagged"/>';
+                                        break;
+                                    default:
+                                        tagdata += '<'+action+' value="importance_normal"/>';
+                                        tagdata += '<'+action+' value="unflagged"/>';
+                                        break;                                        
+                                }
+                               
+                           }
+                           //if no importance data received, defaults is "Normal"
+                           else{
+                               tagdata += '<add value="importance_normal"/>';
+                               tagdata += '<add value="unflagged"/>';
+                           }
+                        }
+                    }
+                }
+                //string data - used to tag a message when reading it (unseen and important, by now)
+                else{
+                    if(taglist.indexOf(",") != -1){
+                        var vet_tags = taglist.split(",");
+                        for(var k=0; k<vet_tags.length; k++){
+                            tagdata += '<'+action+' value="'+vet_tags[k]+'"/>';
+                        }
+                    }
+                    else
+                        tagdata += '<'+action+' value="'+taglist+'"/>';
+                }
+            }
+            if(tagdata != ""){    
+                var tobject = '<tag>'
+                +              '<message id="'+arcidmsg+'">'
+                +              tagdata
+                +              '</message>'
+                +             '</tag>';
+                //window.alert('tagdata ret1 = ' + tobject);
+                return(tobject);
+            }
+        }
+        //more messages to add at tag block
+        else{
+            var endpoint = expresso_mail_archive.taglist.lastIndexOf("<");
+           
+            //Draft folder, are "draft"
+            if(expresso_mail_archive.folder_destination == 'drafts'){
+                flag_draft = true;
+                tagdata += '<add value="draft"/>';
+                if (typeof(taglist) == 'object'){
+                    for(var x in taglist[0]){
+                        if (x != 'importance'){
+                            if(( x != 'unseen') && ( x != 'answered')){
+                                if((taglist[0][x] != '') && (taglist[0][x] != ' ') && (taglist[0][x] != null) && (x != 'msgid'))
+                                    tagdata += '<remove value="'+x+'"/>';
+                            }
+                            else{
+                                if( x == 'unseen'){
+                                    if (taglist[0][x] == ' ')
+                                        tagdata += '<remove value="seen"/>';
+                                    else
+                                        if((taglist[0][x] != '') && (taglist[0][x] != null))
+                                            tagdata += '<remove value="unseen"/>';                                
+                                }
+                                if( x == 'answered'){
+                                    if (taglist[0][x] == ' ')
+                                        tagdata += '<remove value="unanswered"/>';
+                                    else
+                                        if((taglist[0][x] != '') && (taglist[0][x] != null))
+                                            tagdata += '<remove value="answered"/>';                                                                    
+                                }                              
+                            }
+                        }
+                        else{
+                            if((taglist[0][x] != '') && (taglist[0][x] != ' ')){
+                                switch (taglist[0][x].toLowerCase()){
+                                    case 'high':
+                                        tagdata += '<'+action+' value="importance_high"/>';
+                                        tagdata += '<'+action+' value="flagged"/>';
+                                        break;
+                                    default:
+                                        tagdata += '<'+action+' value="importance_normal"/>';
+                                        tagdata += '<'+action+' value="unflagged"/>';
+                                        break;                                        
+                                }
+                               
+                            }
+                           //if no importance data received, defaults is "Normal"
+                           else{
+                               tagdata += '<add value="importance_normal"/>'; 
+                               tagdata += '<add value="unflagged"/>';
+                           }
+                        }
+                    }
+                }
+                else{
+                     if(!flag_draft)
+                        tagdata += '<remove value="'+taglist+'"/>';
+                }
+            }
+            else
+                tagdata += '<remove value="draft"/>';
+        
+            //Trash folder, are "deleted""
+            if(expresso_mail_archive.folder_destination == 'trash'){
+                tagdata += '<add value="deleted"/>';
+            }
+            else
+                tagdata += '<remove value="deleted"/>';
+            
+            if(!flag_draft){
+                var action;
+                if (op == 0)
+                    action = 'add';
+                else
+                    action = 'remove';
+        
+                //object data -used at archieve op
+                if (typeof(taglist) == 'object'){
+                    for(var x in taglist[0]){
+                        if (x != 'importance'){
+                            if(( x != 'unseen') && ( x != 'answered')){
+                                if((taglist[0][x] != '') && (taglist[0][x] != ' ') && (taglist[0][x] != null) && (x != 'msgid'))
+                                    tagdata += '<'+action+' value="'+x+'"/>';
+                            }
+
+                            else{
+                                if( x == 'unseen'){
+                                    if (taglist[0][x] == ' ')
+                                        tagdata += '<'+action+' value="seen"/>';
+                                    else
+                                        if((taglist[0][x] != '') && (taglist[0][x] != null))
+                                            tagdata += '<'+action+' value="unseen"/>';                                
+                                }
+                                if( x == 'answered'){
+                                    if (taglist[0][x] == ' ')
+                                        tagdata += '<'+action+' value="unanswered"/>';
+                                    else
+                                        if((taglist[0][x] != '') && (taglist[0][x] != null))
+                                            tagdata += '<'+action+' value="answered"/>';                                                                    
+                                }                             
+                            }
+
+
+                          
+                        }
+                        else{
+                            if((taglist[0][x] != '') && (taglist[0][x] != ' ')){
+                                switch (taglist[0][x].toLowerCase()){
+                                    case 'important':
+                                        tagdata += '<'+action+' value="importance_high"/>';
+                                        tagdata += '<'+action+' value="flagged"/>';
+                                        break;
+                                    default:
+                                        tagdata += '<'+action+' value="importance_normal"/>';
+                                        tagdata += '<'+action+' value="unflagged"/>';
+                                        break;                                        
+                                }
+                                
+                            }
+                           //if no importance data received, defaults is "Normal"
+                           else{
+                               tagdata += '<add value="importance_normal"/>'; 
+                               tagdata += '<add value="unflagged"/>';
+                           }
+                        }
+                    }
+                }
+                //string data - used to tag a message
+                else{
+                    if(taglist.indexOf(",") != -1){
+                        var vet_tags = taglist.split(",");
+                        for(var k=0; k<vet_tags.length; k++){
+                            tagdata += '<'+action+' value="'+vet_tags[k]+'"/>';
+                        }
+                    }
+                    else
+                        tagdata += '<'+action+' value="'+taglist+'"/>';
+                }
+            }
+            
+            if(tagdata != ""){        
+                var tobject = expresso_mail_archive.taglist.substr(0, endpoint)
+                +              '<message id="'+arcidmsg+'">'
+                +              tagdata
+                +              '</message>'
+                +             '</tag>';
+                //window.alert('tagdata ret2 = ' + tobject);
+                return(tobject);
+            }            
+            
+        }
+        return(null);
+    }
+    return(null);
+}
+
+MAPattern.prototype.zipConfig = function(array_messages){
+    var tagdata ="";
+    if(typeof(array_messages) == 'object'){
+        if(!array_messages["format"])
+            var def_format = 'zip';
+        else
+            var def_format = array_messages["format"].toLowerCase();
+        var tobject = '<zip format="' + def_format + '">';
+        //Export from selected messages grid
+        if(array_messages["type"] == 'messages'){
+            for(var k=0; k<array_messages["messages"].length;k++){
+                tobject += '<message id="' + array_messages["messages"][k] + '"/>';
+            }   
+        }
+        //Export from folder management
+        else{
+            var folderid = array_messages["messages"];
+            if (!array_messages["recursive"])
+                var rec = false;
+            else
+                var rec = array_messages["recursive"];
+            tobject += '<folder id="' + array_messages["messages"] + '" recursive="' + rec + '"/>';
+        }
+        tobject += '</zip>';        
+        return(tobject);
+    }
+    return(null);
+}
+
+MAPattern.prototype.download_compressed_attachments = function(msgid,format){
+    var urldownload = mail_archive_protocol+'://'+mail_archive_host+':'+mail_archive_port+'/temp/download/parts_'+msgid+'.'+format;
+    return(urldownload);
+}
+
+MAPattern.prototype.message_source = function(msgid){
+    var urldownload = mail_archive_protocol+'://'+mail_archive_host+':'+mail_archive_port+'/mail/'+folder+'/'+msgid+'.eml';
+    return(urldownload);
+}
+-->
Index: sandbox/2.5.0-expresso1/expressoMail1_2/js/draw_api.js
===================================================================
--- sandbox/2.5.0-expresso1/expressoMail1_2/js/draw_api.js	(revision 7128)
+++ sandbox/2.5.0-expresso1/expressoMail1_2/js/draw_api.js	(revision 7146)
@@ -108,4 +108,116 @@
 		}
 
+                
+                //MAILARCHIVER-01
+                //Create local folders main structure tree
+                if(preferences.use_local_messages=="1"){
+                    var disabled_local_span = document.getElementById('llocal_disabledtree_folders');
+
+                    //Services are disabled: because Mail Archiver is not running/installed or have just crashed. Link activation is created here
+                    if(!expresso_mail_archive.enabled){
+                        //window.alert('tem o nodo disabled? ' + tree_folders.getNodeById("local_disabled") + '[' + typeof(tree_folders.getNodeById('local_disabled')) + ']');
+                        if(typeof(tree_folders.getNodeById("local_disabled")) == 'undefined'){
+                          var n_LocalDisabled = new dNode({id: "local_disabled", caption: get_lang('Offline'), onClick: "services_retry()", plusSign:false});
+                          tree_folders.add(n_LocalDisabled, 'local_root');
+                        }
+
+                        tree_folders.getNodeById("local_disabled").alter({caption:get_lang('Offline'), onClick: "retry_local_folders()"});
+                        tree_folders.getNodeById("local_disabled")._refresh();
+                        
+                        if((disabled_local_span) && (!document.getElementById('services_retry'))){
+                            disabled_local_span.style.backgroundImage="url(../phpgwapi/templates/"+template+"/images/foldertree_services.png)";
+
+                            var service_retry = document.createElement("SPAN");
+                            service_retry.id = 'services_retry';
+                            service_retry.className = 'clean_trash';
+                            service_retry.style.cursor = 'pointer';
+                            service_retry.onclick = function () {services_retry();};
+                            service_retry.innerHTML = "["+get_lang("Retry")+"]";
+                            service_retry.title="Reconectar ao Mail Archiver";
+                            service_retry.onmouseover = function() {service_retry.style.color="red";};
+                            service_retry.onmouseout= function() {service_retry.style.color="#666666";}; //#114FA4
+                            disabled_local_span.parentNode.appendChild(service_retry);
+                        }
+                        else{
+                            //Creates the tree node and MA console linkage
+                            if((!disabled_local_span) && (!document.getElementById('services_retry'))){
+                                var n_LocalDisabled = new dNode({id: "local_disabled", caption: get_lang('Offline'), onClick: "services_retry()", plusSign:false});
+                                tree_folders.add(n_LocalDisabled, 'local_root');
+                            
+                                var disabled_local_span = document.getElementById('llocal_disabledtree_folders');
+                                disabled_local_span.style.backgroundImage="url(../phpgwapi/templates/"+template+"/images/foldertree_services.png)";
+                                var service_retry = document.createElement("SPAN");
+                                service_retry.id = 'services_retry';
+                                service_retry.className = 'clean_trash';
+                                service_retry.style.cursor = 'pointer';
+                                service_retry.onclick = function () {services_retry();};
+                                service_retry.innerHTML = "["+get_lang("Retry")+"]";
+                                service_retry.title= get_lang("Reconect to MailArchiver services");
+                                service_retry.onmouseover = function() {service_retry.style.color="red";};
+                                service_retry.onmouseout= function() {service_retry.style.color="#666666";}; //#114FA4
+                                disabled_local_span.parentNode.appendChild(service_retry);
+                            
+                                var div_ma_host = document.createElement('div');
+                                div_ma_host.id = 'div_login_ma_host';
+                                div_ma_host.style.position = 'absolute';
+                                div_ma_host.style.padding = '0px';
+                                div_ma_host.style.margin = '0px';
+                                div_ma_host.style.top = '25px';
+                                div_ma_host.style.left = '0px';
+                                div_ma_host.style.width = '145px';
+                                div_ma_host.style.height = '80px';
+                                div_ma_host.style.border = '1px solid #CCCCCC';
+                                div_ma_host.style.backgroundColor = '#F0F0F0';
+                                div_ma_host.style.fontWeight = 'normal';
+                                disabled_local_span.appendChild(div_ma_host);
+                                div_ma_host.innerHTML = '<p><b>'+get_lang('In trouble?')+'</b></p><p>&rarr; ' + get_lang('Try to access') + '<br/><a href="' + mail_archive_protocol + "://" + mail_archive_host + ":" + mail_archive_port + '/admin" target="_blank" title="MailArchiver Admin">'+get_lang('MailArchiver admin console')+'.</p>';                            
+                            }
+                            //Only creates the MA login linkage
+                            else{
+                                var div_ma_host = document.createElement('div');
+                                div_ma_host.id = 'div_login_ma_host';
+                                div_ma_host.style.position = 'absolute';
+                                div_ma_host.style.padding = '0px';
+                                div_ma_host.style.margin = '0px';
+                                div_ma_host.style.top = '25px';
+                                div_ma_host.style.left = '0px';
+                                div_ma_host.style.width = '145px';
+                                div_ma_host.style.height = '80px';
+                                div_ma_host.style.border = '1px solid #CCCCCC';
+                                div_ma_host.style.backgroundColor = '#F0F0F0';
+                                div_ma_host.style.fontWeight = 'normal';
+                                disabled_local_span.appendChild(div_ma_host);
+                                div_ma_host.innerHTML = '<p><b>'+get_lang('In trouble?')+'</b></p><p>&rarr; ' + get_lang('Try to access') + '<br/><a href="' + mail_archive_protocol + "://" + mail_archive_host + ":" + mail_archive_port + '/admin" target="_blank" title="MailArchiver Admin">'+get_lang('MailArchiver admin console')+'.</p>';                                                        
+                            }
+                        }
+                    }
+                    //Services enabled: list folders service must be invoqued
+                    else{
+                        var services_retry_span = document.getElementById('services_retry');
+
+                        if(services_retry_span){
+                            //window.alert('Tem services_retry -> vai remover o disabled_local_span');
+                            var node_disabled_to_remove = document.getElementById('nlocal_disabledtree_folders');
+                            //document.getElementById('chlocal_roottree_folders').removeChild('nlocal_disabledtree_folders');
+                            //services_retry_span.parentNode.removeChild(services_retry_span);
+                            node_disabled_to_remove.parentNode.removeChild(node_disabled_to_remove);
+                        }
+                        //else
+                          //  window.alert('Sem services retry');
+
+                        //tree_folders.getNodeById("local_disabled").alter({caption:get_lang('List_Folders')});
+                                                
+                       //expresso_mail_archive.getFoldersList('FERNANDAO22', "");
+                       var drawinginfo = {treeObject: tree_folders, treeName: 'tree_folders'};
+                       expresso_mail_archive.drawdata = drawinginfo;
+                       //expresso_mail_archive.getFoldersList("");                        
+                        
+                        //tree_folders.getNodeById("local_root")._refresh();
+
+                        if(disabled_local_span)
+                            disabled_local_span.style.backgroundImage="url(../phpgwapi/templates/"+template+"/images/foldertree_folder.png)";                       
+                    }      
+                }
+
 		return;
 	}
@@ -148,5 +260,30 @@
 		}
 
-
+                
+                //MAILARCHIVER-02
+                //Create local folders main structure tree
+                if(preferences.use_local_messages=="1"){   
+                    //Add the local_root node
+                    var root_local = new dNode({id: "local_root", caption: get_lang('local folders'), plusSign: true});
+                    tree_folders.add(root_local, "root");   
+                    
+                    //Services are disabled: because Mail Archiver is not running/installed or have just crashed. Link activation is created here
+                    if(!expresso_mail_archive.enabled){
+                        var n_LocalDisabled = new dNode({id: "local_disabled", caption: get_lang('Offline'), onClick: "services_retry()", plusSign:false});
+                        tree_folders.add(n_LocalDisabled, 'local_root');
+                        
+                    }
+                    
+                    //Services enabled: list folders service must be invoqued
+                    else{
+                        var drawinginfo = {treeObject: tree_folders, treeName: 'tree_folders'};
+                        expresso_mail_archive.drawdata = drawinginfo;
+                        //expresso_mail_archive.getFoldersList("");
+                    }
+                    
+                    //Opens the local folders tree view
+                    //tree_folders.getNodeById("local_root").open();
+                    
+                }
 
 		var handlerChannel = function(data){
@@ -183,49 +320,4 @@
 		 * Pastas locais
 		 */
-		if (preferences.use_local_messages==1 || expresso_offline) {
-			    //verifica se gears esta installado ou o offline
-			if( (!window.google || !google.gears) &&
-			     !expresso_local_messages.installGears() ){
-                                preferences.use_local_messages = 0;
-			}
-			else if( !expresso_local_messages.is_offline_installed() )
-				preferences.use_local_messages = 0;
-			else{
-				if (expresso_offline)
-					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 (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);
-					}
-				}
-			}
 
 		/*tree_folders.draw(Element('content_folders'));
@@ -276,4 +368,24 @@
 
 
+                //MAILARCHIVER-04
+                if ((disabled_local_span) && (!expresso_mail_archive.enabled)){
+                    disabled_local_span.style.backgroundImage="url(../phpgwapi/templates/"+template+"/images/foldertree_services.png)";
+                        //div to login at MA Admin console
+                        var div_ma_host = document.createElement('div');
+                        div_ma_host.id = 'div_login_ma_host';
+                        div_ma_host.style.position = 'absolute';
+                        div_ma_host.style.padding = '0px';
+                        div_ma_host.style.margin = '0px';
+                        div_ma_host.style.top = '25px';
+                        div_ma_host.style.width = '145px';
+                        div_ma_host.style.height = '80px';
+                        div_ma_host.style.border = '1px solid #CCCCCC';
+                        div_ma_host.style.backgroundColor = '#F0F0F0';
+                        div_ma_host.style.fontWeight = 'normal';
+                        disabled_local_span.appendChild(div_ma_host);
+                        div_ma_host.innerHTML = '<p><b>'+get_lang('In trouble?')+'</b></p><p>&rarr; ' + get_lang('Try to access') + '<br/><a href="' + mail_archive_protocol + "://" + mail_archive_host + ":" + mail_archive_port + '/admin" target="_blank" title="MailArchiver Admin">'+get_lang('MailArchiver admin console')+'.</p>';
+                }
+
+
 		draw_paging(Element('tot_m').innerHTML);
 		if(document.getElementById(mount_url_folder(["nINBOX",special_folders["Trash"]])+"tree_folders"))
@@ -305,8 +417,24 @@
 			   }
 
-		if(!expresso_offline)
+        //MAILARCHIVER-05
+        if(document.getElementById("nlocal_disabledtree_folders") && (!expresso_mail_archive.enabled) && (!document.getElementById('services_retry')))
+        {
+            var service_retry = document.createElement("SPAN");
+            service_retry.id = 'services_retry';
+            service_retry.className = 'clean_trash';
+            service_retry.style.cursor = 'pointer';
+            service_retry.onclick = function () {services_retry();};
+            service_retry.innerHTML = "["+get_lang("Retry")+"]";
+            service_retry.title="Reconectar ao Mail Archiver";
+            service_retry.onmouseover = function() {service_retry.style.color="red";};
+            service_retry.onmouseout= function() {service_retry.style.color="#666666";}; //#114FA4
+            document.getElementById("nlocal_disabledtree_folders").appendChild(service_retry);
+        }
+
+            //MAILARCHIVER-00
+		//if(!expresso_offline)
 			var display_unseen_in_mailbox = tree_folders.getNodeById( 'root' );
-		else
-			var display_unseen_in_mailbox = tree_folders.getNodeById( 'local_root' );
+		//else
+			//var display_unseen_in_mailbox = tree_folders.getNodeById( 'local_root' );
 		display_unseen_in_mailbox.alter({caption:get_lang("My Folders")});
 		display_unseen_in_mailbox._refresh();
@@ -391,52 +519,62 @@
 
 function draw_tree_local_folders() {
-	/**
-	 * Pastas locais
-	 */
-		if(preferences.use_local_messages==1 || expresso_offline) {
-			var local_folders = expresso_local_messages.list_local_folders();
-			var has_changes = false;
-			for (var i in local_folders) { //Coloca as pastas locais.
-
-				var new_caption = local_folders[i][0];
-				if(local_folders[i][0].indexOf("/")!="-1") {
-					final_pos = local_folders[i][0].lastIndexOf("/");
-					new_caption = local_folders[i][0].substr(final_pos+1);
-				}
-
-				var folder_unseen = Element('dftree_local_'+local_folders[i][0]+'_unseen');
-
-				if ((folder_unseen) && (local_folders[i][1] > 0))
-				{
-					folder_unseen.innerHTML = local_folders[i][1];
-					has_changes = true;
-				}
-				else if (local_folders[i][1] > 0)
-				{
-					tree_folders.getNodeById("local_"+local_folders[i][0]).alter({caption:lang_folder(new_caption) + '<font style=color:red>&nbsp(</font><span id="dftree_local_'+local_folders[i][0]+'_unseen" style=color:red>'+local_folders[i][1]+'</span><font style=color:red>)</font>'});
-					tree_folders.getNodeById("local_"+local_folders[i][0])._refresh();
-					has_changes = true;
-				}
-				else if (local_folders[i][1] <= 0)
-				{
-					tree_folders.getNodeById("local_"+local_folders[i][0]).alter({caption:lang_folder(new_caption)});
-					tree_folders.getNodeById("local_"+local_folders[i][0])._refresh();
-					has_changes = true;
-				}
-
-			if("local_"+local_folders[i][0] == get_current_folder()){
-					var old_new_m = isNaN(parseInt(Element('new_m').innerHTML)) ? parseInt(Element('new_m').firstChild.innerHTML) : parseInt(Element('new_m').innerHTML);
-					if(!isNaN(old_new_m) && old_new_m < local_folders[i][1]){
-						Element('tot_m').innerHTML = parseInt(Element('tot_m').innerHTML) + (parseInt(local_folders[i][1])-old_new_m);
-					}
-					Element('new_m').innerHTML = local_folders[i][1] ? '<font color="RED">'+local_folders[i][1]+'</font>' : 0;
-					draw_paging(Element('tot_m').innerHTML);
-					has_changes = true;
-			}
-		}
-			if(has_changes)
-				tree_folders.getNodeById("local_root").open();
- 	}
-}
+    /**
+     * Pastas locais
+     */
+        //MAILARCHIVER-04
+        if ( preferences.use_local_messages=="1" ) {
+            var local_folders_list = expresso_mail_archive.getFoldersList("");
+        }
+}
+
+// function draw_tree_local_folders() {
+// 	/**
+// 	 * Pastas locais
+// 	 */
+// 		if(preferences.use_local_messages==1 || expresso_offline) {
+// 			var local_folders = expresso_local_messages.list_local_folders();
+// 			var has_changes = false;
+// 			for (var i in local_folders) { //Coloca as pastas locais.
+
+// 				var new_caption = local_folders[i][0];
+// 				if(local_folders[i][0].indexOf("/")!="-1") {
+// 					final_pos = local_folders[i][0].lastIndexOf("/");
+// 					new_caption = local_folders[i][0].substr(final_pos+1);
+// 				}
+
+// 				var folder_unseen = Element('dftree_local_'+local_folders[i][0]+'_unseen');
+
+// 				if ((folder_unseen) && (local_folders[i][1] > 0))
+// 				{
+// 					folder_unseen.innerHTML = local_folders[i][1];
+// 					has_changes = true;
+// 				}
+// 				else if (local_folders[i][1] > 0)
+// 				{
+// 					tree_folders.getNodeById("local_"+local_folders[i][0]).alter({caption:lang_folder(new_caption) + '<font style=color:red>&nbsp(</font><span id="dftree_local_'+local_folders[i][0]+'_unseen" style=color:red>'+local_folders[i][1]+'</span><font style=color:red>)</font>'});
+// 					tree_folders.getNodeById("local_"+local_folders[i][0])._refresh();
+// 					has_changes = true;
+// 				}
+// 				else if (local_folders[i][1] <= 0)
+// 				{
+// 					tree_folders.getNodeById("local_"+local_folders[i][0]).alter({caption:lang_folder(new_caption)});
+// 					tree_folders.getNodeById("local_"+local_folders[i][0])._refresh();
+// 					has_changes = true;
+// 				}
+
+// 			if("local_"+local_folders[i][0] == get_current_folder()){
+// 					var old_new_m = isNaN(parseInt(Element('new_m').innerHTML)) ? parseInt(Element('new_m').firstChild.innerHTML) : parseInt(Element('new_m').innerHTML);
+// 					if(!isNaN(old_new_m) && old_new_m < local_folders[i][1]){
+// 						Element('tot_m').innerHTML = parseInt(Element('tot_m').innerHTML) + (parseInt(local_folders[i][1])-old_new_m);
+// 					}
+// 					Element('new_m').innerHTML = local_folders[i][1] ? '<font color="RED">'+local_folders[i][1]+'</font>' : 0;
+// 					draw_paging(Element('tot_m').innerHTML);
+// 					has_changes = true;
+// 			}
+// 		}
+// 			if(has_changes)
+// 				tree_folders.getNodeById("local_root").open();
+//  	}
+// }
 
 
@@ -539,34 +677,42 @@
 			return true;
 		}
-		$.ajax({			
-			url: "controller.php?" + $.param( {action: "$this.imap_functions.get_range_msgs3", 
-				folder: folder,
-				 msg_range_begin: "0",
-				 msg_range_end: "0", 					
-				sort_box_type: "SORTARRIVAL", 
-				search_box_type: search_box_type,
-				sort_box_reverse: "1"
-				}),
-			success: function(data){
-				data = connector.unserialize(data);
-				if(data){
-					var _data = {};
-					$.each(data,function(index,value){
-						if (data[index] && data[index].msg_number){
-							_data[data[index].msg_number] = data[index].msg_number;
-						}
-					});
-					populateSelectedMsgs(_data);
-					_data = {};
-				
-				}
-			},
-			beforeSend: function( jqXHR, settings ){
-				connector.showProgressBar();
-			},
-			complete: function( jqXHR, settings ){
-				connector.hideProgressBar();
-			}
-		});
+		//MAILARCHIVE-fernando
+        //se for pasta local
+        if (/^local_messages/.test(current_folder)) {
+            console.log('buscar mensaens locais');
+            $(".folders-loading").removeClass("folders-loading"); //remove o icone de loading ao clicar nas pastas locais
+        }
+        else { //se não, processamento normal da pasta
+    		$.ajax({
+    			url: "controller.php?" + $.param( {action: "$this.imap_functions.get_range_msgs3", 
+    				folder: folder,
+    				 msg_range_begin: "0",
+    				 msg_range_end: "0", 					
+    				sort_box_type: "SORTARRIVAL", 
+    				search_box_type: search_box_type,
+    				sort_box_reverse: "1"
+    				}),
+    			success: function(data){
+    				data = connector.unserialize(data);
+    				if(data){
+    					var _data = {};
+    					$.each(data,function(index,value){
+    						if (data[index] && data[index].msg_number){
+    							_data[data[index].msg_number] = data[index].msg_number;
+    						}
+    					});
+    					populateSelectedMsgs(_data);
+    					_data = {};
+    				
+    				}
+    			},
+    			beforeSend: function( jqXHR, settings ){
+    				connector.showProgressBar();
+    			},
+    			complete: function( jqXHR, settings ){
+    				connector.hideProgressBar();
+    			}
+    		});
+        }
 		proxy_mensagens.messages_list(current_folder,1,preferences.max_email_per_page,sort_box_type,search_box_type,sort_box_reverse,preferences.preview_msg_subject,preferences.preview_msg_tip,handler_draw_box);
 	}
@@ -1657,21 +1803,48 @@
 
 		tr_element.msg_sample = "";
+        tr_element.tip = "";
 		//if(headers_msgs.msg_sample && headers_msgs.msg_sample.preview_msg_subject != "")
 		if(headers_msgs.msg_sample && preferences.preview_msg_subject == "1" && headers_msgs.msg_sample.body !== "")
 		{
-			if (cssForResizing) //Colunas redimensionaveis - nao trunca
-				tr_element.msg_sample = Base64.decode(headers_msgs.msg_sample.body).substr(0,180) + "..."; //trecho do body que sera exibido com o assunto;
-			else
-				tr_element.msg_sample = Base64.decode(headers_msgs.msg_sample.body).substr(0,120) + "..."; //trecho do body que sera exibido com o assunto;
-		}
-
-		tr_element.tip = "";
-		if(headers_msgs.msg_sample && preferences.preview_msg_tip == "1" && headers_msgs.msg_sample.body !== "")
-		{
-			tr_element.tip = Base64.decode(headers_msgs.msg_sample.body).substr(3,300) + "..."; //trecho do body que sera exibido no tool-tip;
-		}
+            //if(preferences.use_local_messages==1 && !expresso_offline) { //MailArchive
+                if(proxy_mensagens.is_local_folder(current_folder)) {
+
+                    // preferencia da pre-visualizacao
+                    if (cssForResizing) {//Colunas redimensionaveis - nao trunca
+                        tr_element.msg_sample = headers_msgs.msg_sample.body.substr(0,180) + "..."; //trecho do body que sera exibido com o assunto; //blabla
+                    } else {
+                        tr_element.msg_sample = headers_msgs.msg_sample.body.substr(0,120) + "..."; //trecho do body que sera exibido com o assunto;
+                    }
+
+                    // preferencia dos tooltips
+                    if(headers_msgs.msg_sample && preferences.preview_msg_tip == "1" && headers_msgs.msg_sample.body !== "") {
+                        tr_element.tip = headers_msgs.msg_sample.body.substr(3,300) + "..."; //trecho do body que sera exibido no tool-tip;
+                    }
+
+                }
+
+            /*}*/ else { //IMAP
+                 // preferencia da pre-visualizacao
+			     if (cssForResizing) { //Colunas redimensionaveis - nao trunca
+                    /*problema no decode, se ele for utilizado, nao lista as mensagens -> CORRIGIDO em mail_archiver.js*/
+                    //if (headers_msgs.msg_sample.body.length > 0)
+				    tr_element.msg_sample = Base64.decode(headers_msgs.msg_sample.body).substr(0,180) + "..."; //trecho do body que sera exibido com o assunto; //blabla
+			     } else {
+				    //if (headers_msgs.msg_sample.body.length > 0)
+					tr_element.msg_sample = Base64.decode(headers_msgs.msg_sample.body).substr(0,120) + "..."; //trecho do body que sera exibido com o assunto;
+		          }
+
+                // preferencia dos tooltips
+                if(headers_msgs.msg_sample && preferences.preview_msg_tip == "1" && headers_msgs.msg_sample.body !== "") {
+                    tr_element.tip = Base64.decode(headers_msgs.msg_sample.body).substr(3,300) + "..."; //trecho do body que sera exibido no tool-tip;
+                }
+            }
+        }
+
+		
+		
 
 		if ((headers_msgs.Unseen == 'U') || (headers_msgs.Recent == 'N')){
-			if ((headers_msgs.Flagged == 'F') || headers_msgs.Importance.toLowerCase().indexOf("high")!=-1 )
+			if ((headers_msgs.Flagged == 'F') || ( headers_msgs.Importance !== undefined && headers_msgs.Importance.toLowerCase().indexOf("high")!=-1 ) )
 				add_className(tr_element, 'flagged_msg');
 			add_className(tr_element, 'tr_msg_unread');
@@ -5084,4 +5257,10 @@
 
 function build_quota(data){
+    //MAILARCHIVE - fernando
+    // se for a pasta de mensagens locais
+    if(proxy_mensagens.is_local_folder(current_folder)) {
+        return;        
+    }
+
 	id = "content_quota";
 	q_limit = data['quota_limit'];
