Index: /trunk/prototype/services/PostgreSQL.php
===================================================================
--- /trunk/prototype/services/PostgreSQL.php	(revision 5514)
+++ /trunk/prototype/services/PostgreSQL.php	(revision 5637)
@@ -18,11 +18,11 @@
     }
 
-   public function read ( $uri, $justthese = false ){
+   public function read ( $uri, $justthese = false , $criteria = false){
       
-      $map =  Config::get($uri['concept'], 'PostgreSQL.mapping');
-       
+      $map =  Config::get($uri['concept'], 'PostgreSQL.mapping');   
       $justthese = self::parseJustthese($justthese, $map);
-
-      return $this->execResultSql( 'SELECT '.$justthese['select'].' FROM '. (Config::get($uri['concept'],'PostgreSQL.concept')) .' WHERE id = \''.addslashes( $uri['id'] ).'\'', true );
+      $criteria = ($criteria !== false) ? $this->parseCriteria ( $criteria , $map , ' WHERE id = \''.addslashes( $uri['id'] ).'\'') : '';
+      
+      return $this->execResultSql( 'SELECT '.$justthese['select'].' FROM '. (Config::get($uri['concept'],'PostgreSQL.concept')) .$criteria , true );
     }
 	
@@ -174,7 +174,5 @@
     }
 	
-    private static function parseCriteria( $criteria  , &$map ){               
-	    
-	    $result = '';
+    private static function parseCriteria( $criteria  , &$map , $query = '' ){               
 	
 	    if( isset($criteria["filter"]) && $criteria["filter"] !== NULL )
@@ -190,6 +188,5 @@
 		  *	    array( '=' , 'campo' , 'valor' )
 		*/
-
-		    $result .= 'WHERE ('.self::parseFilter( $criteria['filter'] , $map).')';
+                $query .= ($query === '') ?  'WHERE ('.self::parseFilter( $criteria['filter'] , $map).')' : ' AND ('.self::parseFilter( $criteria['filter'] , $map).')';
 	    }
 	    /*
@@ -200,26 +197,26 @@
 	    {
 		foreach ($criteria["join"] as $i => $v)
-		    $result .= ' AND '.$i.' = '.$v.' ';
+		    $query .= ' AND '.$i.' = '.$v.' ';
 	    }
 	    
 	    if( isset($criteria["group"]) )
 	    {
-		    $result .= ' GROUP BY '.( is_array($criteria["group"]) ? implode(', ', $criteria["group"]) : $criteria["group"] ).' ';
+		    $query .= ' GROUP BY '.( is_array($criteria["group"]) ? implode(', ', $criteria["group"]) : $criteria["group"] ).' ';
 	    }
 	    
 	    if( isset($criteria["order"]) )
 	    {
-		    $result .= ' ORDER BY '.self::parseOrder( $criteria["order"], $map ).' ';
+		    $query .= ' ORDER BY '.self::parseOrder( $criteria["order"], $map ).' ';
 	    }
 	    if( isset($criteria["limit"]) )
 	    {
-		    $result .= ' LIMIT '. $criteria["limit"] .' ';
+		    $query .= ' LIMIT '. $criteria["limit"] .' ';
 	    }
 	    if( isset($criteria["offset"]) )
 	    {
-		    $result .= ' OFFSET '. $criteria["offset"] .' ';
-	    }
-	    
-	    return $result;
+		    $query .= ' OFFSET '. $criteria["offset"] .' ';
+	    }
+	    
+	    return $query;
     }
     
Index: /trunk/prototype/config/mailAttachment.ini
===================================================================
--- /trunk/prototype/config/mailAttachment.ini	(revision 5604)
+++ /trunk/prototype/config/mailAttachment.ini	(revision 5637)
@@ -4,4 +4,10 @@
 [before.create]
 encodeCreateAttachment = modules/mail/interceptors/Attachments.php
+
+[before.read]
+securityOwner = modules/mail/interceptors/Attachments.php
+
+[before.find]
+securityOwner = modules/mail/interceptors/Attachments.php
 
 [PostgreSQL.mapping]
Index: /trunk/prototype/modules/mail/interceptors/Attachments.php
===================================================================
--- /trunk/prototype/modules/mail/interceptors/Attachments.php	(revision 5604)
+++ /trunk/prototype/modules/mail/interceptors/Attachments.php	(revision 5637)
@@ -3,20 +3,21 @@
 class Attachments {	
 	
-	public function encodeCreateAttachment( &$uri , &$params , &$criteria , $original ){
-                        
-		if(!isset($params['source'])) return false;
-		
-		if(isset($_FILES[$params['source']]))
-			if(isset($params['id']))
-				$params =  array_merge($_FILES[$params['source']], array('id' => $params['id']));
-			else
-				$params =  $_FILES[$params['source']];
-				
-                  $params['owner'] = Config::me('uidNumber'); 
-                                   
-                  $params['disposition'] = $original['properties']['disposition'];
-                  $params['dtstamp'] = time();
+	public function encodeCreateAttachment( &$uri , &$params , &$criteria , $original ){            
+            if(!isset($params['source'])) return false;
+
+            if(isset($_FILES[$params['source']]))
+                $params =  $_FILES[$params['source']];
+
+                $params['owner'] = Config::me('uidNumber'); 
+
+                $params['disposition'] = $original['properties']['disposition'];
+                $params['dtstamp'] = time();
 	}
-  
+        
+        public function securityOwner(  &$uri , &$params , &$criteria , $original )
+        {
+            $criteria['filter'] = isset( $criteria['filter'] ) ? array('AND', $criteria['filter'] , array('=' , 'owner', Config::me('uidNumber')) ) :  array('=' , 'owner', Config::me('uidNumber'));   
+        }
+
 }
 
Index: /trunk/prototype/modules/mail/cleanMailAttachments.php
===================================================================
--- /trunk/prototype/modules/mail/cleanMailAttachments.php	(revision 5637)
+++ /trunk/prototype/modules/mail/cleanMailAttachments.php	(revision 5637)
@@ -0,0 +1,5 @@
+<?php
+define('ROOTPATH', dirname(__FILE__).'/../..');
+require_once ROOTPATH.'/api/controller.php';
+Controller::deleteALL( array('concept' => 'mailAttachment'), false ,array( 'filter' => array( '<'  , 'dtstamp' , (gmmktime() - 86400 ))));
+?>
Index: /trunk/prototype/api/controller.php
===================================================================
--- /trunk/prototype/api/controller.php	(revision 5539)
+++ /trunk/prototype/api/controller.php	(revision 5637)
@@ -516,5 +516,5 @@
 			case 'find': $return = $params['service']->find( $params['URI'], $params['properties'], $params['criteria'] ); break;
 
-			case 'read': $return = $params['service']->read( $params['URI'], $params['properties']/*, $criteria*/ ); break;
+			case 'read': $return = $params['service']->read( $params['URI'], $params['properties'] , $params['criteria'] ); break;
 
 			case 'create': $return = $params['service']->create( $params['URI'], $params['properties']/*, $criteria*/ ); break;
Index: /trunk/expressoMail1_2/js/abas.js
===================================================================
--- /trunk/expressoMail1_2/js/abas.js	(revision 5626)
+++ /trunk/expressoMail1_2/js/abas.js	(revision 5637)
@@ -5,5 +5,5 @@
 var msgAttachments = new Array();
 var uidsSave = new Array(); 
-
+var zebraDiscardEventDialog = false;
 function setBorderAttributes(ID)
 {
@@ -315,5 +315,5 @@
 					return $(DataLayer.render('../prototype/modules/mail/templates/draggin_box.ejs', {texto : borderTitle, type: "messages"}));
 			},
-			cursorAt: { cursor: "move", top: 5, left: 56 },
+			cursorAt: {cursor: "move", top: 5, left: 56},
 			refreshPositions: true ,
 			scroll: true, 
@@ -394,65 +394,73 @@
 }
 
-opened_alert = false;
 
 function draftTests(ID, msg_sent){
-	var cancel = new LertButton(get_lang('cancel'), function() {
-        Element("border_id_"+ID).onclick = function () { alternate_border(ID);}; 
-        var setFocus = function(ID){
-			if ($.trim($("#to_"+ID).val()) == "")
-				$("#to_"+ID).focus();
-			else if ($("#tr_cc_"+ID).css('display') != 'none' && $.trim($("#cc_"+ID).val()) == "")
-				$("#cc_"+ID).focus();
-			else if ($("#tr_cco_"+ID).css('display') != 'none' && $.trim($("#cco_"+ID).val()) == "")
-				$("#cco_"+ID).focus();		
-			else if ($.trim($("#subject_"+ID).val()) == "")
-				$("#subject_"+ID).focus();
-			else{
-				if (RichTextEditor.plain[id] != true) 
-					setTimeout("RichTextEditor.focus("+ID+")",100);                  
-				else  
-					$('#body_'+ID).focus(); 
-			}
-		}
-		setFocus(ID);  
-        opened_alert = false;
-    });
+    
+       
+        if( openTab.toPreserve[ID] = false)
+        {
+            close_delete(ID, msg_sent);
+            delete(openTab.type[ID]);
+        }    
+        else  
+        {
+             var msg = 'Existem alterações não salvas na mensagem.';
+             var buttons = ['Descartar alterações', 'Salvar e fechar'];
+             var width = 330;
+             if($('#fileupload_msg'+ID).find('.in-progress').length)
+             {
+                 msg = 'Existem arqivos sendo enviados para o servidor.';
+                 buttons = ['Descartar alterações e anexos', 'Salvar estado atual fechar', 'Continuar editando']; 
+                 width = 560;
+             }
+             zebraDiscardEventDialog = true;
+             window.setTimeout(function() {
+                $.Zebra_Dialog(msg, {
+                            'type':     'question',
+                            'overlay_opacity': '0.5',
+                            'buttons':  buttons,
+                            'width' : width,
+                            'onClose':  function(clicked) {
+                                    if(clicked == 'Descartar alterações' || clicked == 'Descartar alterações e anexos' ) {
+                                        if (openTab.imapBox[ID] && !openTab.toPreserve[ID])
+                                            openTab.toPreserve[ID] = false;
+
+                                        delete(openTab.type[ID]);
+                                        close_delete(ID, msg_sent);
+                                    }
+                                    else if(clicked == 'Salvar e fechar' || clicked == 'Salvar estado atual fechar')
+                                    {
+                                        save_msg(ID);
+                                        openTab.toPreserve[ID] = false;
+                                        close_delete(ID, msg_sent);
+                                        delete(openTab.type[ID]);
+                                    }    
+                                    else{
+
+                                        Element("border_id_"+ID).onclick = function () {alternate_border(ID);}; 
+                                        var setFocus = function(ID){
+                                                        if ($.trim($("#to_"+ID).val()) == "")
+                                                                $("#to_"+ID).focus();
+                                                        else if ($("#tr_cc_"+ID).css('display') != 'none' && $.trim($("#cc_"+ID).val()) == "")
+                                                                $("#cc_"+ID).focus();
+                                                        else if ($("#tr_cco_"+ID).css('display') != 'none' && $.trim($("#cco_"+ID).val()) == "")
+                                                                $("#cco_"+ID).focus();		
+                                                        else if ($.trim($("#subject_"+ID).val()) == "")
+                                                                $("#subject_"+ID).focus();
+                                                        else{
+                                                                if (RichTextEditor.plain[id] != true) 
+                                                                        setTimeout("RichTextEditor.focus("+ID+")",100);                  
+                                                                else  
+                                                                        $('#body_'+ID).focus(); 
+                                                        }
+                                                }
+                                                setFocus(ID);  
+                                    }
+                                    window.setTimeout(function() {
+                                            zebraDiscardEventDialog = false;
+                                    }, 500);
+                            }})}, 300);    
+        }
 	
-    var yes = new LertButton(get_lang('Save'), function() {
-        save_msg(ID, 'undefined', true);
-        openTab.toPreserve[ID] = false;
-        close_delete(ID, msg_sent);
-        delete(openTab.type[ID]);
-		//write_msg(get_lang('Your message was save as draft in folder %1.', lang_folder('Drafts')));
-		
-    });
-    var discard = new LertButton(get_lang('Discard'), function() {
-			if (openTab.imapBox[ID] && !openTab.toPreserve[ID])
-            {
-                //delete_msgs(openTab.imapBox[ID], openTab.imapUid[ID].toString(), 0)
-                //delete(openTab.imapBox[ID]);
-                openTab.toPreserve[ID] = false;
-            }
-			delete(openTab.type[ID]);
-            close_delete(ID, msg_sent);
-    });
-	if( $("#save_message_options_"+ID).attr("disabled") == "disabled") {
-		openTab.toPreserve[ID] = false;
-        close_delete(ID, msg_sent);
-        delete(openTab.type[ID]);
-	}else{
-		var titulo = '<b>' + get_lang('Warning') + '!</b>';
-		var message = get_lang("Your changes are not saved. What to do?");
-		var multConfirm = new Lert(
-			titulo,
-			message,
-			[cancel,discard,yes],
-			{
-					defaultButton:yes,
-					icon:'js/lert/images/dialog-help.gif'
-			});
-		multConfirm.display();
-		opened_alert = true;
-	}
 }
 
@@ -486,5 +494,6 @@
             if (editTest(ID)){
                 bolExecuteClose = false;
-                return(draftTests(ID, msg_sent));
+                if(zebraDiscardEventDialog === false)
+                    return(draftTests(ID, msg_sent));
             }
 	}
Index: /trunk/expressoMail1_2/js/main.js
===================================================================
--- /trunk/expressoMail1_2/js/main.js	(revision 5636)
+++ /trunk/expressoMail1_2/js/main.js	(revision 5637)
@@ -2335,5 +2335,5 @@
     uidsSave[border_id] = [];
     DataLayer.commit(false,false,function(data){
-        if(data != null && data['message://'+idJavascript].id !== undefined )
+        if(data != null && data['message://'+idJavascript] !== undefined && data['message://'+idJavascript].id !== undefined )
         {
             uidsSave[border_id].push(data['message://'+idJavascript].id);
@@ -2341,5 +2341,8 @@
         }
         else
-            write_msg('Erro ao salvar sua menssagem!');
+        {
+            write_msg('Erro ao salvar sua menssagem! Nova tentativa em '+(autosave_time / 1000) + ' segundos.');
+            setTimeout( 'save_msg('+border_id+');', autosave_time);
+        }    
     });
 
Index: /trunk/expressoMail1_2/js/draw_api.js
===================================================================
--- /trunk/expressoMail1_2/js/draw_api.js	(revision 5630)
+++ /trunk/expressoMail1_2/js/draw_api.js	(revision 5637)
@@ -4012,18 +4012,4 @@
 	tbody_message.appendChild(tr5);
 
-        /**
- 	* event to enable autosave_draft on file attachment
- 	*/
- 	function save_onchange_attachment_handler () {
-		away = false;
-		var save_link = Element("save_message_options_"+ID);
-		save_link.onclick = function onclick(event) {
-			openTab.toPreserve[ID] = true;
-			save_msg(ID);
-		};
-		$("#save_message_options_"+ID).button({disabled: false});
-	};
-
-
 	var tr5 = document.createElement("TR");
 	var td5_link = document.createElement("TD");
