Index: sandbox/expressoServiceImap/prototype/services/ImapServiceAdapter.php
===================================================================
--- sandbox/expressoServiceImap/prototype/services/ImapServiceAdapter.php	(revision 6457)
+++ sandbox/expressoServiceImap/prototype/services/ImapServiceAdapter.php	(revision 6486)
@@ -89,23 +89,24 @@
 			{
 				//begin: for grid	
-				$page  = isset($criteria['page']) ? $criteria['page'] : 1 ; //{1}    get the requested page
-				$limit = isset($criteria['rows']) ? $criteria['rows'] : 10 ; //{10}   get how many rows we want to have into the grid
-				$sidx  = isset($criteria['sidx']) ? $criteria['sidx'] : 0; //{id}   get index row - i.e. user click to sort
-				$sord  = isset($criteria['sord']) ? $criteria['sord'] : ''; //{desc} get the direction
+// 				$page  = isset($criteria['page']) ? $criteria['page'] : 1 ; //{1}    get the requested page
+// 				$limit = isset($criteria['rows']) ? $criteria['rows'] : 10 ; //{10}   get how many rows we want to have into the grid
+// 				$sidx  = isset($criteria['sidx']) ? $criteria['sidx'] : 0; //{id}   get index row - i.e. user click to sort
+// 				$sord  = isset($criteria['sord']) ? $criteria['sord'] : ''; //{desc} get the direction
 
 				$filter =  isset($criteria['filter']) ? $criteria['filter'] : '';
 
-				if( !$sidx ) $sidx = 1;
+// 				if( !$sidx ) $sidx = 1;
 
 				$folder_name =  isset($URI['folder']) ?  $URI['folder'] : str_replace( '.', $this->imap_delimiter, isset($context['folder']) ?  $context['folder'] : 'INBOX');
 			
 				$count = imap_num_msg( $this->open_mbox( $folder_name ) );
-
-				$total_pages = $count > 0 ? ceil( $count/$limit ) : 0;
-
-				if( $page > $total_pages )
-					$page = $total_pages;
-
-				$start = $limit * $page - $limit;
+// 
+// 				$total_pages = $count > 0 ? ceil( $count/$limit ) : 0;
+// 
+// 				if( $page > $total_pages )
+// 					$page = $total_pages;
+// 
+// 				$start = $limit * $page - $limit;
+
 				// do not put $limit*($page - 1)
 				//end: for grid
@@ -162,25 +163,25 @@
 					if( $filter[0] !== 'msgNumber' )
 					{
-					for( $i = 0; $i < count($filter); $i++ )
-					{
-						if( count( $filter[$i] ) === 4 )
-						$criteria['isExact'] = ( array_shift( $filter[$i] ) === 'AND' );
-
-						$criteria[ $filter[$i][0] ] = array( 'criteria' => $filter[$i][2], 'filter' => $filter[$i][1] );
-					}
-
-					return $this->searchSieveRule($criteria);
-					}
-
-					$msgNumber = array();
-
-					for( $i = $start; $i < $start + $limit && isset( $filter[2][$i] ); $i++ )
-					  $msgNumber[] = $filter[2][$i];
-
-					if( empty( $msgNumber ) )
-					return( false );
+					    for( $i = 0; $i < count($filter); $i++ )
+					    {
+						    if( count( $filter[$i] ) === 4 )
+						    $criteria['isExact'] = ( array_shift( $filter[$i] ) === 'AND' );
+
+						    $criteria[ $filter[$i][0] ] = array( 'criteria' => $filter[$i][2], 'filter' => $filter[$i][1] );
+					    }
+
+					    return $this->searchSieveRule($criteria);
+					}
+
+// 					$msgNumber = array();
+// 
+// 					for( $i = $start; $i < $start + $limit && isset( $filter[2][$i] ); $i++ )
+// 					  $msgNumber[] = $filter[2][$i];
+// 
+// 					if( empty( $msgNumber ) )
+// 					return( false );
 
 					$result = $this->get_info_msgs( array( 'folder' => $folder_name, 
-									   'msgs_number' => implode( ',', $msgNumber ) ) );
+									   'msgs_number' => implode( ',', $filter[2] ) ) );
 
 					foreach( $result as $i => $val )
@@ -193,6 +194,6 @@
 						array( 
 							'folder' => $folder_name, //INBOX
-							'msg_range_begin' => $start + 1, //??
-							'msg_range_end' => $start + $limit, //$limit = $_GET['rows']; // get how many rows we want to have into the grid
+							'msg_range_begin' => $criteria['offset'] + 1, //??
+							'msg_range_end' => $criteria['limit'], //$limit = $_GET['rows']; // get how many rows we want to have into the grid
 							'sort_box_type' => 'SORTARRIVAL', 
 							'search_box_type' => 'ALL',
@@ -203,5 +204,7 @@
 				//return var_export($result);
 
-				$response = array( "page" => $page, "total" => $total_pages, "records" => $count );
+				$response = array( "page" => $count > 0 ? ceil( $criteria['offset'] / $criteria['limit'] ) + 1 : 0, 
+						   "total" => $count > 0 ? ceil( $count/$criteria['limit'] ) : 0, 
+						   "records" => $count );
 				
 				for ($i=0; $i<count($result); $i++)
Index: sandbox/expressoServiceImap/prototype/Sync.php
===================================================================
--- sandbox/expressoServiceImap/prototype/Sync.php	(revision 6328)
+++ sandbox/expressoServiceImap/prototype/Sync.php	(revision 6486)
@@ -152,4 +152,11 @@
 	  $dt = prepare( $concept, $id, $dt, $data, $oldIds, $mounted, $synced );
 
+	  ob_start();
+        print "\n";
+        print "dt: ";
+        print_r( $dt );
+        $output = ob_get_clean();
+        file_put_contents( "/tmp/prototype233.log", $output , FILE_APPEND );
+        
 	  try{
 	      $result = Controller::put( array( 'concept' => $concept, 'id' => $id ), $dt );
@@ -160,4 +167,17 @@
 	      continue;
 	  }
+	  
+	ob_start();
+        print "\n";
+        print "result: ";
+        print_r( $result );
+        $output = ob_get_clean();
+        file_put_contents( "/tmp/prototype233.log", $output , FILE_APPEND );
+        ob_start();
+        print "\n";
+        print "old ids ";
+        print_r( $oldIds );
+        $output = ob_get_clean();
+        file_put_contents( "/tmp/prototype233.log", $output , FILE_APPEND );
 
 	  if( !$result )
Index: sandbox/expressoServiceImap/prototype/config/OpenLDAP.srv
===================================================================
--- sandbox/expressoServiceImap/prototype/config/OpenLDAP.srv	(revision 6173)
+++ sandbox/expressoServiceImap/prototype/config/OpenLDAP.srv	(revision 6486)
@@ -4,5 +4,5 @@
 idAtribute = "uidNumber"
 host = 127.0.0.1
-context = "LDAP_DN"
+context = "dc=prognus"
 ; Caso o LDAP requisite autenticacao, configure os parametros a seguir
 ;user = 
Index: sandbox/expressoServiceImap/prototype/config/PostgreSQL.srv
===================================================================
--- sandbox/expressoServiceImap/prototype/config/PostgreSQL.srv	(revision 6081)
+++ sandbox/expressoServiceImap/prototype/config/PostgreSQL.srv	(revision 6486)
@@ -7,6 +7,5 @@
 ;host = 127.0.0.1
 port = 5432
-dbname = expresso
-user = postgres
-; Caso o usuario tenha senha...
+dbname= expresso24natan
+user=postgres
 ;password=
Index: sandbox/expressoServiceImap/prototype/modules/attach_message/attach_message.js
===================================================================
--- sandbox/expressoServiceImap/prototype/modules/attach_message/attach_message.js	(revision 6303)
+++ sandbox/expressoServiceImap/prototype/modules/attach_message/attach_message.js	(revision 6486)
@@ -6,73 +6,5 @@
 dashes = /\//gi;
 flags = [ 'Attachment', 'Forwarded' ,'Recent', 'Unseen',  'Answered',  'Draft',  'Deleted', 'Flagged', 'Followupflag', 'Label' ];
-
-$.ajaxPrefilter(function( options, originalOptions, jqXHR ){
-
-      var offlineAction = isOffline.exec( options.url );
-
-      if( offlineAction )
-      {
-	  offlineAction = offlineAction[1] || "";
-	
-	  jqXHR.abort();
-
-	  var params = {};
-	  
-	  if( offlineAction )
-	      offlineAction +=  options.data ? "&" +  options.data : "";
-
-	  offlineAction = offlineAction.split( breakParams );
-
-	  for( var i = 0; i < offlineAction.length; )
-	      params[ offlineAction[i++] ] = offlineAction[i++];
-
-	  rest = params["q"].split("/");
-
-	  if( !(rest.length % 2) )
-	      var id = rest.pop();
-
-	  var concept = rest.pop();
-
-	  for( var i = 0; i < rest.length; )
-	    params[ rest[i++] ] = rest[ i++ ];
-
-	  switch( concept )
-	  {
-	    case "message":
-	    {
-		if( id ){
-		    var mail = expresso_local_messages.get_local_mail( id );
-		    mail.eml = expresso_local_messages.get_src( mail.url_export_file );
-
-		    ( options.success || options.complete )( mail );
-		    return;
-		}
-
-		var msgs = expresso_local_messages.get_local_range_msgs( params["folder"].replace(dots, "/").replace("local_messages/", ""),
-									  params["rows"] * ( params["page"] - 1 ) + 1,
-									  params["rows"], "SORTARRIVAL", (params["sord"] == "desc"),
-									  "ALL", 1, 1 );
-
-		for( var i = 0; i < msgs.length; i++ )
-		{
-		      msgs[i].size = msgs[i].Size;
-		      msgs[i].timestamp = msgs[i].udate * 1000;
-		      msgs[i].flags = [];
-
-		      for( var ii = 0; ii < flags.length; ii++ )
-			  if( f = $.trim( msgs[i][ flags[ii] ] ) )
-			      msgs[i].flags[ msgs[i].flags.length ] =  f;
-
-		      msgs[i].flags = msgs[i].flags.join(',');
-		}
-
-		( options.success || options.complete )( {"rows": msgs, 
-							   "records": msgs.length,
-							   "page": params["page"], 
-							   "total": Math.ceil( msgs.num_msgs / params["rows"] )} );
-	    }
-	  }
-      }
-});
+months = ['Jan','Feb','Mar','Apr','May','June','July','Aug','Sept','Oct','Nov','Dec'];
 
 var BASE_PATH = '../prototype/';
@@ -146,33 +78,4 @@
 }
 
-function numberMonths (months){
-	switch(months){
-		case 'Jan':
-			return 1;
-		case 'Feb':
-			return 2;
-		case 'Mar':
-			return 3;
-		case 'Apr':
-			return 4;
-		case 'May':
-			return 5;
-		case 'June':
-			return 6;
-		case 'July':
-			return 7;
-		case 'Aug':
-			return 8;
-		case 'Sept':
-			return 9;
-		case 'Oct':
-			return 10;
-		case 'Nov':
-			return 11;
-		case 'Dec':
-			return 12;
-	}	
-}
-
 NormaliseFrom = function(cellvalue, options, rowObject) {
 	rowObject['flags'] = rowObject['flags'].split(",");
@@ -189,4 +92,6 @@
 date2Time = function (timestamp) {
 	date = new Date();
+	if( typeof timestamp === "string" )
+	    timestamp = parseInt( timestamp, 10 );
 	dat = new Date(timestamp);
 	if ((date.getTime() - timestamp) < (24*60*60*1000)) {
@@ -196,5 +101,5 @@
 		if(is_ie){
 			var b = date.toString().split(' ');
-			var c = b[2] + "/" + numberMonths(b[1]) + "/" + b[5];
+			var c = b[2] + "/" + months.indexOf(b[1]) + "/" + b[5];
 			return '<span class="datable">' + c + '</span>';
 		}else{
@@ -209,5 +114,4 @@
 //	jQuery('#foldertree').attr('tabIndex', '1').focus();
 }
-
 
 selectedMessagesCount = function() {
@@ -231,30 +135,4 @@
 var selectedFolder     = {};
 
-function adaptOffline( data )
-{
-    if( preferences.use_local_messages == 1 || expresso_offline)
-    {
-	var folders = expresso_local_messages.list_local_folders();
-	
-	var stripParents = /^(.*)\/([^\/]*)/;
-
-	$.each( folders, function( i, folder ){
-		
-		  if(typeof(folder) == 'undefined')  return;
-		  
-	      var id = 'local_messages/' + folder[0];
-
-	      var parts = stripParents.exec( id );
-	  
-	      data[data.length] = {'id' : id,
-				    'commonName' : parts[2],
-				    'parentFolder' : parts[1]};
-	});
-    }
-	
-    return( data );
-	
-}
-
 $mailpreview_tabs_label_length = 15;
 
@@ -263,268 +141,224 @@
 jQuery('#buttons-container .button').button();
 
-jQuery.ajax({
-	url: BASE_PATH + "REST.php?q=folder",
-	dataType: 'json',
-
-	success: function( data ){
-
-		data = adaptOffline( data );
-
-		var tree1 = new Array();
-		var tree2 = new Array();
-		var tree3 = new Array();
-		for (var i=0; i<data.length; i++) {
-
-			if (/^INBOX/.test(data[i].id)) {
-				if (!unorphanize(tree1, data[i])) {
-					data[i].children = new Array();
-					tree1.push(data[i]);
-				}
-			}
-			else if (/^user/.test(data[i].id)) {
-				if (!unorphanize(tree2, data[i])) {
-					data[i].children = new Array();
-					tree2.push(data[i]);
-				}
-			}
-			else if (/^local_messages/.test(data[i].id)) {
-				if (!unorphanize(tree3, data[i])) {
-					data[i].children = new Array();
-					tree3.push(data[i]);
-				}
-			}
-			
-		}
-
-		var firstFolder = jQuery("#foldertree-container")
-		.removeClass('empty-container')
-		.html(DataLayer.render(BASE_PATH + 'api/templates/foldertree.ejs', {folders: [tree1, tree2, tree3]}))
-		.find("#foldertree").treeview()
-		.click(function(event){
-			//request new selected folder messages
-			var target = $(event.target);
-
-			if( target.is('.collapsable-hitarea, .expandable-hitarea, .lastCollapsable, .lastExpandable, .treeview') )
-			    return;
-
-			if( !target.attr('id') )
-			    target = target.parent();
-
-            if (target.attr('id') == "foldertree") return;
-			
-			var targetId = target.attr('id');
-			var child = target.find('.folder');
-              
-			$('.filetree span.folder.selected').removeClass('selected');
-			if(!target.is('#foldertree > .expandable, #foldertree > .collapsable'))
-				$(target).children('.folder').addClass('selected');
-			
-			selectedFolder = {
-			    id: targetId, 
-			    name: child.attr('title'),
-			    'class': child.attr('class')
-			};
-
-			var grid = $("#message_attacher_grid"), offlineCase = "";
-			
-			if( !targetId.indexOf( 'local_messages/' ) )
-			    offlineCase = ":offline";
-			
-
-			grid.jqGrid('setGridParam',{url:BASE_PATH + 'REST.php'+offlineCase+'?q=folder/'+targetId.replace(dashes, '.')+'/message'})
-			    .trigger("reloadGrid")
-			    .jqGrid('setCaption', '<span class="'+child.attr('class')+'">'+child.attr('title')+'</span>');
-		})
-		.find('span:first-child');
-		$('span.folder.inbox').addClass('selected');
-		selectedFolder = {
-			id: firstFolder.parent().attr('id'), 
-			name: firstFolder.attr('title'),
-			'class': firstFolder.attr('class')
-		};
-
-		//jqgrid
-		jQuery("#mailgrid-container")
-		.removeClass('empty-container')
-		.html(DataLayer.render(BASE_PATH + 'api/templates/messagegrid.ejs', {}))
-		.find("#message_attacher_grid")
-		.jqGrid({
-			url:BASE_PATH + 'REST.php?q=folder/INBOX/message',
-			datatype: "json",
-			mtype: 'GET',
-			colNames:['#',' ', 'De', 'Assunto', 'Data', 'Tamanho'],
-			colModel:[
-				{name:'msg_number',index:'msg_number', width:45, hidden:true, sortable:false},
-				{name:'flags',index:'msg_number',edittype: 'image', width:100, sortable:false, formatter:flags2Class, title :false},
-				{name:'from.name',index:'msg_number', width:70, sortable:false, formatter:NormaliseFrom},
-				{name:'subject',index:'subject', width:245, sortable:false,formatter:NormaliseSubject},
-				{name:'timestamp',index:'timestamp', width:65, align:"center", sortable:false, formatter:date2Time},
-				{name:'size',index:'size', width:55, align:"right", sortable:false, formatter:bytes2Size}
-			],
-			jsonReader : {
-				  root:"rows",
-				  page: "page",
-				  total: "total",
-				  records: "records",
-				  repeatitems: false,
-				  id: "0"
-			},
-			rowNum:10,
-			rowList:[10,25,50],
-			pager: '#message_attacher_grid_pager',
-			sortname: 'id',
-			viewrecords: true,
-			sortorder: "desc",
-			multiselect: true,
-			autowidth: true,
-			loadComplete: function(data) {
-				lastLoadedMessages = data.rows;
-				
-				// aplica o contador
-				jQuery('.timable').each(function (i) {
-					jQuery(this).countdown({
-						since: new Date(parseInt(this.title)), 
-						significant: 1,
-						layout: 'h&aacute; {d<}{dn} {dl} {d>}{h<}{hn} {hl} {h>}{m<}{mn} {ml} {m>}{s<}{sn} {sl}{s>}', 
-						description: ' atr&aacute;s'
-					});					
-				});
-				
-				// reconstrói a seleção das mensagens mesmo depois da mudança de pasta
-				if (selectedMessages[selectedFolder.id]) {
-					for (var message in selectedMessages[selectedFolder.id]){
-						for (var j=0; j<data.rows.length; j++){	
-							if (selectedMessages[selectedFolder.id][message] && message == data.rows[j].msg_number) {
-								jQuery("#message_attacher_grid").setSelection(jQuery("#message_attacher_grid").getDataIDs()[j], false);
-							}
-						}
-					}
-				}
-				$('#cb_message_attacher_grid').css('display', 'none');
-				
-			},
-			onSelectRow: function (id, selected) {
-				var message = false;
-				for (var i=0; i<lastLoadedMessages.length; i++){
-					if (lastLoadedMessages[i].msg_number == id) {
-						message = lastLoadedMessages[i];
-						break;
-					}
-				}
-				
-				var tabPanelTemplateId = 'mailpreview_tab_' + selectedFolder.id.replace(/[.\/]/g, '_') + '_' + message.msg_number;
-				var tabPanelTemplateId = tabPanelTemplateId.replace(/[\s\/]/g, '-'); 
-				
-				if (selected) {	
-					if (onceOpenedMessages[selectedFolder.id] && onceOpenedMessages[selectedFolder.id][message.msg_number]) {
-						if (!selectedMessages[selectedFolder.id])
-							selectedMessages[selectedFolder.id] = {};
-							
-						selectedMessages[selectedFolder.id][message.msg_number] = true;
-						$('#mailpreview-container').unblock();						
-
-						var tabPanelTemplateLabel = html_entities(onceOpenedMessages[selectedFolder.id][message.msg_number].subject);
-						if (tabPanelTemplateLabel.length > $mailpreview_tabs_label_length + 3)
-							tabPanelTemplateLabel = tabPanelTemplateLabel.substring(0, $mailpreview_tabs_label_length) + '...';
-						
-						if (!$('#' + tabPanelTemplateId).length) {								
-							$mailpreview_tabs.tabs("add", '#' + tabPanelTemplateId, tabPanelTemplateLabel)
-							.find('.message.empty-container').hide().end()
-							.find('#' + tabPanelTemplateId).html(onceOpenedMessages[selectedFolder.id][message.msg_number].body);
-						} else {
-							$mailpreview_tabs.tabs('select', '#' + tabPanelTemplateId)
-							.find('#' + tabPanelTemplateId + ', [href="#' + tabPanelTemplateId + '"]').removeClass('preview-message-unselected');
-						}
-						
-					} else {
-						jQuery('#mailpreview_container').block({  
-							message: '<div id="loading-content"><div class="image"></div></div>',  
-							css: {  
-								backgroundImage: 'url('+BASE_PATH+'modules/attach_message/images/loading.gif)',  
-								backgroundRepeat: 'no-repeat', 
-								backgroundPosition: 'center', 
-								backgroundColor: 'transparent', 
-								width: '32px', 
-								height: '32px', 
-								border:'none'  
-							}, 
-							overlayCSS: {  
-								backgroundColor: '#CCC',  
-								opacity:         0.5 
-							}  
-						}); 
-
-						var offlineCase = "";
-						
-						if( !selectedFolder.id.indexOf( 'local_messages/' ) )
-						    offlineCase = ":offline";
-					  
-						if (!selectedMessages[selectedFolder.id])
-							selectedMessages[selectedFolder.id] = {};
-						selectedMessages[selectedFolder.id][message.msg_number] = true;
-						$.ajax({
-							accepts: 'text/html',
-							url: BASE_PATH + 'REST.php'+offlineCase+'?q=folder/'+selectedFolder.id.replace(dashes, '.')+'/message/'+id,
-							dataType: 'json',
-							success: function( mail_preview ){		
-								//selectedMessagesCount();
-								if (!onceOpenedMessages[selectedFolder.id])
-									onceOpenedMessages[selectedFolder.id] = {};
-								onceOpenedMessages[selectedFolder.id][message.msg_number] = jQuery.extend(true, message, mail_preview);
-
-								$('#mailpreview_container').unblock();
-
-								var tabPanelTemplateLabel = html_entities(onceOpenedMessages[selectedFolder.id][message.msg_number].subject);
-								if (tabPanelTemplateLabel.length > $mailpreview_tabs_label_length + 3)
-									tabPanelTemplateLabel = tabPanelTemplateLabel.substring(0, $mailpreview_tabs_label_length) + '...';
-							selectedMessagesCount();
-								
-								if (!$('#' + tabPanelTemplateId).length) {								
-									$mailpreview_tabs.tabs("add", '#' + tabPanelTemplateId, tabPanelTemplateLabel)
-									.find('.message.empty-container').hide().end()
-									.find('#' + tabPanelTemplateId).html(onceOpenedMessages[selectedFolder.id][message.msg_number].body)
-									.prepend(
-										'<div class="mailpreview-message-info">' + 
-											get_lang('Subject') + ': ' +
-											html_entities(onceOpenedMessages[selectedFolder.id][message.msg_number].subject) + 
-										'</div>'
-									)
-									.find('[class^="ExpressoCssWrapper"]').addClass("mailpreview-message-body");
-								} else {
-									$mailpreview_tabs.tabs('select', '#' + tabPanelTemplateId)
-									.find('#' + tabPanelTemplateId + ', [href="#' + tabPanelTemplateId + '"]').removeClass('preview-message-unselected');
-								}
-							}
-						});
-					}
-				} else {
-					/**
-					 * if you wants to remove tab on unselect message,
-					 * but still needs to uselect message on remove tab.
-					 * 
-					 */
-					/*
-					if ($('#' + tabPanelTemplateId).length) {
-						$mailpreview_tabs.tabs('remove', '#' + tabPanelTemplateId);
-					}
-					 */
-					selectedMessages[selectedFolder.id][message.msg_number] = false;
-					$mailpreview_tabs.find('#' + tabPanelTemplateId + ', [href="#' + tabPanelTemplateId + '"]').addClass('preview-message-unselected');
-				}
-				
-				if (onceOpenedMessages[selectedFolder.id] && onceOpenedMessages[selectedFolder.id][message.msg_number])
-					selectedMessagesCount();
-			},
-			caption: '<span class="'+selectedFolder['class']+'">'+selectedFolder.name+'</span>'
-		});
-		//.jqGrid('navGrid','#message_attacher_grid_pager',{edit:false,add:false,del:false});
-		var title = [get_lang("First page"), get_lang("Prev page"), get_lang("Next page"), get_lang("Last page")];
-		$("#first_message_attacher_grid_pager").attr("title",title[0]);
-		$("#prev_message_attacher_grid_pager").attr("title",title[1]);
-		$("#next_message_attacher_grid_pager").attr("title",title[2]);
-		$("#last_message_attacher_grid_pager").attr("title",title[3]);
-	}
+var firstFolder = jQuery("#foldertree-container")
+.removeClass('empty-container')
+.html(DataLayer.render(BASE_PATH + 'api/templates/foldertree.ejs', 'folder:tree', false, false, true))
+.find("#foldertree").treeview()
+.click(function(event){
+	//request new selected folder messages
+    var target = $(event.target);
+
+    if( target.is('.collapsable-hitarea, .expandable-hitarea, .lastCollapsable, .lastExpandable, .treeview') )
+	return;
+
+    if( !target.attr('id') )
+	target = target.parent();
+
+    if (target.attr('id') == "foldertree") return;
+
+    var targetId = target.attr('id');
+    var child = target.find('.folder');
+
+    $('.filetree span.folder.selected').removeClass('selected');
+    if(!target.is('#foldertree > .expandable, #foldertree > .collapsable'))
+	    $(target).children('.folder').addClass('selected');
+
+    selectedFolder = {
+	id: targetId, 
+	name: child.attr('title'),
+	'class': child.attr('class')
+    };
+    
+    current_folder = targetId.replace(dashes, '.');
+
+     $("#message_attacher_grid").trigger("reloadGrid")
+	.jqGrid('setCaption', '<span class="'+child.attr('class')+'">'+child.attr('title')+'</span>');
+})
+.find('span:first-child');
+$('span.folder.inbox').addClass('selected');
+selectedFolder = {
+    id: firstFolder.parent().attr('id'), 
+    name: firstFolder.attr('title'),
+    'class': firstFolder.attr('class')
+};
+
+//jqgrid
+jQuery("#mailgrid-container")
+.removeClass('empty-container')
+.html(DataLayer.render(BASE_PATH + 'api/templates/messagegrid.ejs', {}))
+.find("#message_attacher_grid")
+.jqGrid({
+    url: 'message:jqGrid',
+    datatype: "json",
+    mtype: 'GET',
+    colNames:['#',' ', 'De', 'Assunto', 'Data', 'Tamanho'],
+    colModel:[
+	    {name:'msg_number',index:'msg_number', width:45,  sortable:false, hidden:true},
+	    {name:'flags',     index:'msg_number', width:100, sortable:false, formatter:flags2Class, edittype: 'image', title :false},
+	    {name:'from.name', index:'msg_number', width:70,  sortable:false, formatter:NormaliseFrom},
+	    {name:'subject',   index:'subject',    width:245, sortable:false, formatter:NormaliseSubject},
+	    {name:'timestamp', index:'timestamp',  width:65,  sortable:false, formatter:date2Time,  align:"center"},
+	    {name:'size',      index:'size',       width:55,  sortable:false, formatter:bytes2Size, align:"right"}
+    ],
+    jsonReader : {
+	      root:"rows",
+	      page: "page",
+	      total: "total",
+	      records: "records",
+	      repeatitems: false,
+	      id: "0"
+    },
+    rowNum:10,
+    rowList:[10,25,50],
+    pager: '#message_attacher_grid_pager',
+    sortname: 'id',
+    viewrecords: true,
+    sortorder: "desc",
+    multiselect: true,
+    autowidth: true,
+    loadComplete: function(data) {
+	    lastLoadedMessages = data.rows;
+	    
+	    // aplica o contador
+	    jQuery('.timable').each(function (i) {
+		    jQuery(this).countdown({
+			    since: new Date(parseInt(this.title)), 
+			    significant: 1,
+			    layout: 'h&aacute; {d<}{dn} {dl} {d>}{h<}{hn} {hl} {h>}{m<}{mn} {ml} {m>}{s<}{sn} {sl}{s>}', 
+			    description: ' atr&aacute;s'
+		    });					
+	    });
+	    
+	    // reconstrói a seleção das mensagens mesmo depois da mudança de pasta
+	    if (selectedMessages[selectedFolder.id]) {
+		    for (var message in selectedMessages[selectedFolder.id]){
+			    for (var j=0; j<data.rows.length; j++){	
+				    if (selectedMessages[selectedFolder.id][message] && message == data.rows[j].msg_number) {
+					    jQuery("#message_attacher_grid").setSelection(jQuery("#message_attacher_grid").getDataIDs()[j], false);
+				    }
+			    }
+		    }
+	    }
+	    $('#cb_message_attacher_grid').css('display', 'none');
+	    
+    },
+    onSelectRow: function (id, selected) {
+	    var message = false;
+	    for (var i=0; i<lastLoadedMessages.length; i++){
+		    if (lastLoadedMessages[i].msg_number == id) {
+			    message = lastLoadedMessages[i];
+			    break;
+		    }
+	    }
+	    
+	    var tabPanelTemplateId = 'mailpreview_tab_' + selectedFolder.id.replace(/[.\/]/g, '_') + '_' + message.msg_number;
+	    var tabPanelTemplateId = tabPanelTemplateId.replace(/[\s\/]/g, '-'); 
+	    
+	    if (selected) {	
+		    if (onceOpenedMessages[selectedFolder.id] && onceOpenedMessages[selectedFolder.id][message.msg_number]) {
+			    if (!selectedMessages[selectedFolder.id])
+				    selectedMessages[selectedFolder.id] = {};
+				    
+			    selectedMessages[selectedFolder.id][message.msg_number] = true;
+			    $('#mailpreview-container').unblock();						
+
+			    var tabPanelTemplateLabel = html_entities(onceOpenedMessages[selectedFolder.id][message.msg_number].subject);
+			    if (tabPanelTemplateLabel.length > $mailpreview_tabs_label_length + 3)
+				    tabPanelTemplateLabel = tabPanelTemplateLabel.substring(0, $mailpreview_tabs_label_length) + '...';
+			    
+			    if (!$('#' + tabPanelTemplateId).length) {								
+				    $mailpreview_tabs.tabs("add", '#' + tabPanelTemplateId, tabPanelTemplateLabel)
+				    .find('.message.empty-container').hide().end()
+				    .find('#' + tabPanelTemplateId).html(onceOpenedMessages[selectedFolder.id][message.msg_number].body);
+			    } else {
+				    $mailpreview_tabs.tabs('select', '#' + tabPanelTemplateId)
+				    .find('#' + tabPanelTemplateId + ', [href="#' + tabPanelTemplateId + '"]').removeClass('preview-message-unselected');
+			    }
+			    
+		    } else {
+			    jQuery('#mailpreview_container').block({  
+				    message: '<div id="loading-content"><div class="image"></div></div>',  
+				    css: {  
+					    backgroundImage: 'url('+BASE_PATH+'modules/attach_message/images/loading.gif)',  
+					    backgroundRepeat: 'no-repeat', 
+					    backgroundPosition: 'center', 
+					    backgroundColor: 'transparent', 
+					    width: '32px', 
+					    height: '32px', 
+					    border:'none'  
+				    }, 
+				    overlayCSS: {  
+					    backgroundColor: '#CCC',  
+					    opacity:         0.5 
+				    }  
+			    }); 
+		      
+			    if (!selectedMessages[selectedFolder.id])
+				    selectedMessages[selectedFolder.id] = {};
+			    selectedMessages[selectedFolder.id][message.msg_number] = true;
+			    
+			    var folder = selectedFolder.id.replace(dashes, '.'), mail_preview = null;
+			    
+			    if( !folder.indexOf( 'local_messages/' ) )
+			    {
+			      mail_preview = expresso_local_messages.get_local_mail( id );
+			      mail_preview.eml = expresso_local_messages.get_src( mail_preview.url_export_file );
+			    }
+			    else
+			      mail_preview = DataLayer.get( 'message', { filter: id, criteria: { properties: {context:{folder:folder}} } } );
+
+			      if (!onceOpenedMessages[selectedFolder.id])
+				      onceOpenedMessages[selectedFolder.id] = {};
+			      onceOpenedMessages[selectedFolder.id][message.msg_number] = jQuery.extend(true, message, mail_preview);
+
+			      $('#mailpreview_container').unblock();
+
+			      var tabPanelTemplateLabel = html_entities(onceOpenedMessages[selectedFolder.id][message.msg_number].subject);
+			      if (tabPanelTemplateLabel.length > $mailpreview_tabs_label_length + 3)
+				      tabPanelTemplateLabel = tabPanelTemplateLabel.substring(0, $mailpreview_tabs_label_length) + '...';
+			      selectedMessagesCount();
+			      
+			      if (!$('#' + tabPanelTemplateId).length) {								
+				      $mailpreview_tabs.tabs("add", '#' + tabPanelTemplateId, tabPanelTemplateLabel)
+				      .find('.message.empty-container').hide().end()
+				      .find('#' + tabPanelTemplateId).html(onceOpenedMessages[selectedFolder.id][message.msg_number].body)
+				      .prepend(
+					      '<div class="mailpreview-message-info">' + 
+						      get_lang('Subject') + ': ' +
+						      html_entities(onceOpenedMessages[selectedFolder.id][message.msg_number].subject) + 
+					      '</div>'
+				      )
+				      .find('[class^="ExpressoCssWrapper"]').addClass("mailpreview-message-body");
+			      } else {
+				      $mailpreview_tabs.tabs('select', '#' + tabPanelTemplateId)
+				      .find('#' + tabPanelTemplateId + ', [href="#' + tabPanelTemplateId + '"]').removeClass('preview-message-unselected');
+			      }
+		    }
+	    } else {
+		    /**
+		      * if you wants to remove tab on unselect message,
+		      * but still needs to uselect message on remove tab.
+		      * 
+		      */
+		    /*
+		    if ($('#' + tabPanelTemplateId).length) {
+			    $mailpreview_tabs.tabs('remove', '#' + tabPanelTemplateId);
+		    }
+		      */
+		    selectedMessages[selectedFolder.id][message.msg_number] = false;
+		    $mailpreview_tabs.find('#' + tabPanelTemplateId + ', [href="#' + tabPanelTemplateId + '"]').addClass('preview-message-unselected');
+	    }
+	    
+	    if (onceOpenedMessages[selectedFolder.id] && onceOpenedMessages[selectedFolder.id][message.msg_number])
+		    selectedMessagesCount();
+    },
+    caption: '<span class="'+selectedFolder['class']+'">'+selectedFolder.name+'</span>'
 });
-
+//.jqGrid('navGrid','#message_attacher_grid_pager',{edit:false,add:false,del:false});
+var title = [get_lang("First page"), get_lang("Prev page"), get_lang("Next page"), get_lang("Last page")];
+$("#first_message_attacher_grid_pager").attr("title",title[0]);
+$("#prev_message_attacher_grid_pager").attr("title",title[1]);
+$("#next_message_attacher_grid_pager").attr("title",title[2]);
+$("#last_message_attacher_grid_pager").attr("title",title[3]);
 
 var $mailpreview_tabs = $( "#mailpreview_container").tabs({
Index: sandbox/expressoServiceImap/prototype/modules/filters/filters.js
===================================================================
--- sandbox/expressoServiceImap/prototype/modules/filters/filters.js	(revision 6452)
+++ sandbox/expressoServiceImap/prototype/modules/filters/filters.js	(revision 6486)
@@ -1,3 +1,3 @@
-/* Verifica se a regra fora de escritório está ativa */
+/* Verifica se a regra fora de escritÃ³rio estÃ¡ ativa */
 function outOfficeVerify() {
 	DataLayer.remove('filter', false);
@@ -18,5 +18,5 @@
 }
 
-/* Valida as informações do formulário de filtro de mensagens */
+/* Valida as informaÃ§Ãµes do formulÃ¡rio de filtro de mensagens */
 valid_save = function(){
 	var accord = list_container.find(".rule-details-container").accordion({autoHeight: false});
@@ -154,5 +154,5 @@
 }
 
-/* Mostra os detalhes do filtro para edição */
+/* Mostra os detalhes do filtro para ediÃ§Ã£o */
 showDetails = function( filter ){
 
@@ -311,9 +311,9 @@
 var allMessages = false;
 
-/* Bloqueio de usuários na tela de mensagem do ExpressoMail */
+/* Bloqueio de usuÃ¡rios na tela de mensagem do ExpressoMail */
 function block_user_email(email) {
 	delete selectedMessages;
 	var idd = urlencode(email);
-	/** TODO - Mudar quando API abstrair atualizações no cache */
+	/** TODO - Mudar quando API abstrair atualizaÃ§Ãµes no cache */
 	DataLayer.remove('filter', false);
 	var filters = DataLayer.get('filter');
@@ -400,12 +400,28 @@
 							}
 						});
+	
+	var numRows = 10;
 
 	var data = DataLayer.get( 'message', { filter: criterias_, criteria: { properties: { context: { folder: 'INBOX' } } } }, true );
 
+	var total = data.length ? Math.ceil( data.length / numRows ) : 0;
+
+	delete DataLayer.criterias['message:jqGrid'];	
 	DataLayer.register( 'criterias', 'message:jqGrid', function( crit ){
 
-		    crit.properties = { context: { folder: 'INBOX' } };
-
-		    return { filter: [ "msgNumber", "IN", data ], criteria: crit };
+		    if( crit.page > total )
+			crit.page = total;
+
+		    var start = crit.rows * ( crit.page - 1 );
+
+		    var msgNumber = [];
+
+		    for( var i = start; i < start + crit.rows && !!data[i]; i++ )
+			msgNumber.push( data[i] );
+
+		    if( !msgNumber.length )
+			return( false );
+
+		    return { filter: [ "msgNumber", "IN", msgNumber ], criteria: { properties: { context: { folder: 'INBOX' }, order: crit.sidx } } };
 	});
 
@@ -438,5 +454,5 @@
 			id: "0"
 		},
-		rowNum:10,
+		rowNum:numRows,
 		//rowList:[10,25,50],
 		rowList:[10],
@@ -483,5 +499,5 @@
 }
 
-/* Gerencia a listagem de filtros do usuário */
+/* Gerencia a listagem de filtros do usuÃ¡rio */
 function list_filters(html){
 	outOfficeVerify();
@@ -589,5 +605,5 @@
 					});
 				}).end().filter('.button.search').click(function() {
-					/* Valida se o usuário preencheu as informações */
+					/* Valida se o usuÃ¡rio preencheu as informaÃ§Ãµes */
 					if(valid_save())
 						showGridMessages($(this));
@@ -650,5 +666,5 @@
 			'onClose':  function(caption) {
 				if(caption == get_lang('Yes')){
-				/** TODO - Mudar quando API abstrair atualizações no cache */
+				/** TODO - Mudar quando API abstrair atualizaÃ§Ãµes no cache */
 					DataLayer.remove('filter', false);
 					DataLayer.get('filter');
@@ -689,5 +705,5 @@
 			'onClose':  function(caption) {
 				if(caption == get_lang('Yes')){
-				/** TODO - Mudar quando API abstrair atualizações no cache */
+				/** TODO - Mudar quando API abstrair atualizaÃ§Ãµes no cache */
 					DataLayer.remove('filter', false);
 					DataLayer.get('filter');
Index: sandbox/expressoServiceImap/prototype/api/newcontroller.php
===================================================================
--- sandbox/expressoServiceImap/prototype/api/newcontroller.php	(revision 5715)
+++ sandbox/expressoServiceImap/prototype/api/newcontroller.php	(revision 6486)
@@ -125,5 +125,5 @@
 		    $return = array();
 
-		    for( $data as $concept => $dt )
+		    foreach( $data as $concept => $dt )
 			 $return[] = self::put( $dt, array_merge( array( 'concept' => $concept ), $options ) );
 			
@@ -176,5 +176,5 @@
 
 		if( $txId )
-		    return self::commit( $options['service'], $txId );
+		  return self::commit( $options['service'], $txId );
 	    }
 	    catch( Exception $e )
Index: sandbox/expressoServiceImap/expressoMail1_2/js/draw_api.js
===================================================================
--- sandbox/expressoServiceImap/expressoMail1_2/js/draw_api.js	(revision 6469)
+++ sandbox/expressoServiceImap/expressoMail1_2/js/draw_api.js	(revision 6486)
@@ -3829,6 +3829,5 @@
 			autoOpen:false
 		});
-		
-		
+
 		jQuery.getScript("../prototype/modules/attach_message/attach_message.js", function(){
 			jQuery('#message-attach-dialog').dialog('open');
@@ -3879,6 +3878,99 @@
 				jQuery('#message-attach-dialog').dialog('close');
 			});			
-		});
+		}).fail(function( jqxhr, settings, exception ){
+
+			alert( exception );
+			console.log( exception );
+		  
+		})
 	});
+	
+	DataLayer.codec( 'folder', 'tree', {
+
+		    encoder: function( data ){
+		
+			if( preferences.use_local_messages == 1 || expresso_offline)
+			{
+			    var folders = expresso_local_messages.list_local_folders();
+			    
+			    var stripParents = /^(.*)\/([^\/]*)/;
+
+			    $.each( folders, function( i, folder ){
+				    
+				    if(typeof(folder) == 'undefined')  return;
+				      
+				    var id = 'local_messages/' + folder[0];
+
+				    var parts = stripParents.exec( id );
+				
+				    data[data.length] = { 'id' : id,
+							  'commonName' : parts[2],
+							  'parentFolder' : parts[1] };
+			    });
+			}
+
+			var trees = [[],[],[]],
+
+			root = { inbox: /^INBOX/, share: /^user/, local: /^local_messages/ };
+
+			for (var i = 0; i < data.length; i++ )
+			{
+			    var index = root.inbox.test(data[i].id) ? 0 :
+					root.share.test(data[i].id) ? 1 :
+					root.local.test(data[i].id) ? 2 :
+					'false';
+
+			    if( isNaN(index) ) continue;
+
+			    if (!unorphanize(trees[index], data[i]))
+			    {
+				data[i].children = [];
+				trees[index].push(data[i]);
+			    }
+			}
+
+			return( { folders: trees } );
+		    }
+	    } );
+
+	    current_folder = 'INBOX';
+
+	    DataLayer.codec( 'message', 'jqGrid', {
+
+		  encoder: function( data, crit ){
+
+			if( !crit.criteria.properties.context.folder.indexOf( 'local_messages/' ) )
+			{
+			    var msgs = expresso_local_messages.get_local_range_msgs( crit.criteria.properties.context.folder.replace(dots, "/").replace("local_messages/", ""),
+										      crit.offset + 1, crit.limit, "SORTARRIVAL", crit.orderDesc, "ALL", 1, 1 );
+
+			    for( var i = 0; i < msgs.length; i++ )
+			    {
+				  msgs[i].size = msgs[i].Size;
+				  msgs[i].timestamp = msgs[i].udate * 1000;
+				  msgs[i].flags = [];
+
+				  for( var ii = 0; ii < flags.length; ii++ )
+				      if( f = $.trim( msgs[i][ flags[ii] ] ) )
+					  msgs[i].flags[ msgs[i].flags.length ] =  f;
+
+				  msgs[i].flags = msgs[i].flags.join(',');
+			    }
+
+			    return( {"rows": msgs, 
+				      "records": msgs.length,
+				      "page": crit.page, 
+				      "total": Math.ceil( msgs.num_msgs / crit.limit )} );
+			}
+
+			return( data );
+		  },
+		  criteria: function( crit ){
+
+			return { criteria: { properties: {context:{folder: current_folder || 'INBOX'}}, offset: crit.rows * ( crit.page - 1 ), limit: crit.rows, orderDesc: crit.sord == "desc" } };
+
+		  }
+	    });
+
 	return ID;
 }
