Index: /trunk/phpgwapi/templates/default/css/base.css
===================================================================
--- /trunk/phpgwapi/templates/default/css/base.css	(revision 5486)
+++ /trunk/phpgwapi/templates/default/css/base.css	(revision 5533)
@@ -360,2 +360,3 @@
 {
 }
+.context-menu-item.icon-preferences-mail { background-image: url(../images/preferences.png); }
Index: /trunk/prototype/services/ImapServiceAdapter.php
===================================================================
--- /trunk/prototype/services/ImapServiceAdapter.php	(revision 5416)
+++ /trunk/prototype/services/ImapServiceAdapter.php	(revision 5533)
@@ -7,160 +7,419 @@
     public function open( $config )
     {
-	$this->init();
+		$this->init();
     }
 
 //     public function connect( $config )
 //     {
-// 	$this->init();
+// 			$this->init();
 //     }
 	
     public function find( $URI, $justthese = false, $criteria = false )
 	{ 
-	$context = $justthese['context'];
-	    $URI = $URI['concept'];
-
-	switch( $URI )
-	{
-	    case 'folder':
-	    {
-		$result = $this->to_utf8($this->get_folders_list());
-
-		foreach ($result as $res) {
-
-		    $response[] = array(
-				    'id' => $res['folder_id'],
-				    'commonName' => $res['folder_name'],
-				    'parentFolder' => $res['folder_parent'],
-				    'messageCount' => array('unseen' => isset($res['folder_unseen']) ? $res['folder_unseen'] : null, 'total' => null)
-			    );
+		$context = $justthese['context'];
+		$URI = $URI['concept'];
+
+		switch( $URI )
+		{
+			case 'folder':
+			{
+				$result = $this->to_utf8($this->get_folders_list());
+
+				foreach ($result as $res) {
+
+					$response[] = array(
+							'id' => $res['folder_id'],
+							'commonName' => $res['folder_name'],
+							'parentFolder' => $res['folder_parent'],
+							'messageCount' => array('unseen' => isset($res['folder_unseen']) ? $res['folder_unseen'] : null, 'total' => null)
+						);
+				}
+
+				return $response;
+			}
+			case 'message':
+			{
+				//begin: for grid	
+				$page  = $criteria['page']; //{1}    get the requested page
+				$limit = $criteria['rows']; //{10}   get how many rows we want to have into the grid
+				$sidx  = $criteria['sidx']; //{id}   get index row - i.e. user click to sort
+				$sord  = $criteria['sord']; //{desc} get the direction
+
+				$filter = $criteria['filter'];
+
+				if( !$sidx ) $sidx = 1;
+
+				$folder_name = str_replace( '.', $this->imap_delimiter, $context['folder'] );
+				
+				$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;
+
+				// do not put $limit*($page - 1)
+				//end: for grid
+
+				if( $filter )
+				{
+					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 );
+
+					$result = $this->get_info_msgs( array( 'folder' => $folder_name, 
+									   'msgs_number' => implode( ',', $msgNumber ) ) );
+
+					foreach( $result as $i => $val )
+					$result[$i] = unserialize( $val );
+
+				}
+				else
+				{
+					$result = $this->get_range_msgs2( 
+						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
+							'sort_box_type' => 'SORTARRIVAL', 
+							'search_box_type' => 'ALL',
+							'sort_box_reverse' => 1 
+						) 
+					);
+				}
+				//return var_export($result);
+
+				$response = array( "page" => $page, "total" => $total_pages, "records" => $count );
+				
+				for ($i=0; $i<count($result); $i++)
+				{
+					$flags_enum = array('Recent', 'Unseen',  'Answered',  'Draft',  'Deleted', 'Flagged');
+
+					foreach ($flags_enum as $key => $flag)
+					{
+						if ( !isset($result[$i][$flag]) || !trim($result[$i][$flag]) || trim($result[$i][$flag]) == '') 
+							unset($flags_enum[$key]);
+
+						unset($result[$i][$flag]);
+					}
+
+					if (array_key_exists($i, $result))
+					{
+						$response["rows"][$i] = $result[$i];
+						$response["rows"][$i]['timestamp'] = ( ( $result[$i]['udate'] + $this->functions->CalculateDateOffset() ) * 1000 );
+						$response["rows"][$i]['flags'] = implode(',', $flags_enum);
+						$response["rows"][$i]['size'] = $response["rows"][$i]['Size'];
+						//$response["rows"][$i]['udate'] = ( $result[$i]['udate'] + $this->functions->CalculateDateOffset()  * 1000 );
+						unset($response["rows"][$i]['Size']);
+					}
+				 }
+
+				return $this->to_utf8($response);
+			}
+			
+			/**
+			 * Filtros suportados:
+			 * - ['=', 'folderName', $X]
+			 * - [
+			 * 		'AND',
+			 * 		[
+			 * 			'AND',
+			 * 			['=', 'folderName', $X],
+			 * 			['IN', 'messageNumber', $Ys]
+			 * 		],
+			 * 		['IN', 'labelId', $Zs]
+			 * ]
+			 * - ['=', 'labelId', $X]
+			 * - [
+			 * 		'AND',
+			 * 		['=', 'folderName', $X],
+			 * 		['=', 'labelId', $Y]
+			 * ]
+			 * - ['IN', 'labelId', $Ys]
+			 * - [
+			 * 		'AND',
+			 * 		['=', 'folderName', $X],
+			 * 		['IN', 'labelId', $Ys]
+			 * ]			
+			 */
+			case 'labeled':
+			{
+				$result = array ( );
+				if (isset($criteria["filter"]) && is_array($criteria['filter'])) {
+					//melhorar o tratamento do filter com a lista de todos os labelIds dado pelo interceptor
+					$map = array(
+						'id' => array(),
+						'folderName' => array(),
+						'messageNumber' => array(),
+						'labelId' => array()
+					);
+					
+					self::parseFilter($criteria["filter"], &$map);
+					
+					if (count($map['folderName']) == 0) {
+						$folders = $this->get_folders_list();
+						foreach ($folders as $folder)
+							if (isset($folder['folder_id'])) 
+								$map['folderName'][] = $folder['folder_id'];
+					}
+
+					foreach ($map['folderName'] as $folder) {
+						$this->mbox = $this->open_mbox($folder);
+						
+						foreach ($map['labelId'] as $label) {
+							$messagesLabeleds = imap_search($this->mbox, 'UNDELETED KEYWORD "$Label'.$label.'"', SE_UID);
+							
+							foreach ($messagesLabeleds as $messageLabeled) {
+								if (count($map['messageNumber']) > 0 && !in_array($messageLabeled, $map['messageNumber']))
+									continue;
+									
+								$result[] = array (
+									'id' => $folder . '/' . $messageLabeled . '#' . $label, 
+									'folderName' => $folder,
+									'messageNumber' => $messageLabeled,
+									'labelId' => $label
+								);
+							}
+						}
+						
+						imap_close($this->mbox);
+						$this->mbox = false;
+					}
+				}
+				
+				return $result;
+			}
+			
+			case 'followupflagged':
+			{
+			
+				$result = array ( );
+				if (isset($criteria["filter"]) && is_array($criteria['filter'])) {
+					//melhorar o tratamento do filter com a lista de todos os labelIds dado pelo interceptor
+					$map = array(
+						'id' => array(),
+						'folderName' => array(),
+						'messageNumber' => array()
+					);
+					
+					self::parseFilter($criteria["filter"], &$map);
+					
+					if (empty($map['folderName'])) {
+						$folders = $this->get_folders_list();
+						foreach ($folders as $folder)
+							if (isset($folder['folder_id'])) 
+								$map['folderName'][] = $folder['folder_id'];
+					}
+
+					foreach ($map['folderName'] as $folder) {
+						$this->mbox = $this->open_mbox($folder);
+						
+						foreach ($map['id'] as $followupflagged) {
+							$messagesFlaggeds = imap_search($this->mbox, 'UNDELETED KEYWORD "$Followupflag'.$followupflagged.'"', SE_UID);
+							
+							foreach ($messagesFlaggeds as $messageFlagged) {
+								if (count($map['messageNumber']) > 0 && !in_array($messageFlagged, $map['messageNumber']))
+									continue;
+									
+								$result[] = array (
+									'id' => $folder . '/' . $messageFlagged . '#' . $followupflagged, 
+									'folderName' => $folder,
+									'messageNumber' => $messageFlagged
+								);
+							}
+						}
+						
+						imap_close($this->mbox);
+						$this->mbox = false;
+					}
+				}
+						
+				return $result;				
+			}
 		}
-
-		break;
-	    }
-	    case 'message':
-	    {
-		//begin: for grid	
-		$page  = $criteria['page']; //{1}    get the requested page
-		$limit = $criteria['rows']; //{10}   get how many rows we want to have into the grid
-		$sidx  = $criteria['sidx']; //{id}   get index row - i.e. user click to sort
-		$sord  = $criteria['sord']; //{desc} get the direction
-
-		$filter = $criteria['filter'];
-
-		if( !$sidx ) $sidx = 1;
-
-		$folder_name = str_replace( '.', $this->imap_delimiter, $context['folder'] );
-		
-		$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;
-
-		// do not put $limit*($page - 1)
-		//end: for grid
-
-		if( $filter )
+    }
+
+    public function read( $URI, $justthese = false )
+    {
+
+		switch( $URI['concept'] )
 		{
-		    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 );
-
-		    $result = $this->get_info_msgs( array( 'folder' => $folder_name, 
-							   'msgs_number' => implode( ',', $msgNumber ) ) );
-
-		    foreach( $result as $i => $val )
-			$result[$i] = unserialize( $val );
-
+			case 'message':
+			{
+				return $this->to_utf8( 
+					$this->get_info_msg( array('msg_number'=>$URI['id'],
+					'msg_folder'=>str_replace( '.', $this->imap_delimiter, $justthese['context']['folder'] )) ) 
+				);
+			}
+			case 'labeled':
+			{
+				/**
+				 * id looks like 'folder/subfolder/subsubfolder/65#13', meaning messageId#labelId
+				 */
+				list($messageId, $labelId) = explode('#', $URI['id']);
+				$folderName = basename($messageId);
+				$messageNumber = dirname($messageId);
+				
+				$result = array();
+
+				if ($folderName && $messageNumber && $labelId) {
+					$this->mbox = $this->open_mbox($folderName);
+					$messagesLabeleds = imap_search($this->mbox, 'UNDELETED KEYWORD "$Label'.$labelId.'"', SE_UID);
+					
+					if (in_array($messageNumber, $messagesLabeleds)) {
+						$result = array (
+							'id' => $URI['id'], 
+							'folderName' => $folderName,
+							'messageNumber' => $messageNumber,
+							'labelId' => $labelId
+						);
+					}
+					imap_close($this->mbox);
+					$this->mbox = false;
+				}
+				
+				return $result;
+			}
+			
+			case 'followupflagged':
+			{
+				/**
+				 * id looks like 'folder/subfolder/subsubfolder/65#13', meaning messageId#followupflaggedId
+				 */
+				list($messageId, $followupflaggedId) = explode('#', $URI['id']);
+				$folderName = basename($messageId);
+				$messageNumber = dirname($messageId);
+				
+				$result = array();
+
+				if ($folderName && $messageNumber && $followupflaggedId) {
+					$this->mbox = $this->open_mbox($folderName);
+					$messagesFlaggeds = imap_search($this->mbox, 'UNDELETED KEYWORD "$Followupflag'.$followupflaggedId.'"', SE_UID);
+					
+					if (in_array($messageNumber, $messagesFlaggeds)) {
+						$result = array (
+							'id' => $URI['id'], 
+							'folderName' => $folderName,
+							'messageNumber' => $messageNumber
+						);
+					}
+					imap_close($this->mbox);
+					$this->mbox = false;
+				}
+				
+				return $result;
+			}
 		}
-		else
+    }
+
+    public function create( $URI, $data)
+    {
+
+		switch( $URI['concept'] )
 		{
-		    $result = $this->get_range_msgs2( 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
-					 'sort_box_type' => 'SORTARRIVAL', 
-					 'search_box_type' => 'ALL',
-							     'sort_box_reverse' => 1 ) );
+			case 'labeled':
+			{
+				if (isset($data['folderName']) && isset($data['messageNumber']) && isset($data['labelId'])) {
+					$this->mbox = $this->open_mbox($data['folderName']);
+					imap_setflag_full($this->mbox, $data['messageNumber'], '$Label' . $data['labelId'], ST_UID);
+
+					imap_close($this->mbox);
+					$this->mbox = false;
+
+					return array ('id' => $data['folderName'].'/'.$data['messageNumber'].'#'.$data['labelId']);
+				}
+				return array ();
+			}
+			case 'followupflagged':
+			{
+				//tem que gravar no banco primeiro, obter o id e depois mandar gravar no imap passando o id no data
+				if (isset($data['folderName']) && isset($data['messageNumber']) && isset($data['id'])) {
+					list($messageId, $followupflaggedId) = explode('#', $data['id']);
+					
+					$this->mbox = $this->open_mbox($data['folderName']);
+					imap_setflag_full($this->mbox, $data['messageNumber'], '$Followupflag' . $followupflaggedId, ST_UID);
+
+					imap_close($this->mbox);
+					$this->mbox = false;
+
+					return array ('id' => $data['id']);
+				}
+				return array ();
+			}
 		}
-		//return var_export($result);
-
-		$response = array( "page" => $page, "total" => $total_pages, "records" => $count );
-		
-		for ($i=0; $i<count($result); $i++)
+	}
+
+    public function delete( $URI, $justthese = false, $criteria = false )
+    {
+		switch( $URI['concept'] )
 		{
-		    $flags_enum = array('Recent', 'Unseen',  'Answered',  'Draft',  'Deleted', 'Flagged');
-
-		    foreach ($flags_enum as $key => $flag)
-		    {
-			if ( !isset($result[$i][$flag]) || !trim($result[$i][$flag]) || trim($result[$i][$flag]) == '') 
-				unset($flags_enum[$key]);
-			unset($result[$i][$flag]);
-		    }
-
-		    if (array_key_exists($i, $result))
-		    {
-				$response["rows"][$i] = $result[$i];
-			$response["rows"][$i]['timestamp'] = ( ( $result[$i]['udate'] + $this->functions->CalculateDateOffset() ) * 1000 );
-				$response["rows"][$i]['flags'] = implode(',', $flags_enum);
-				$response["rows"][$i]['size'] = $response["rows"][$i]['Size'];
-// 			$response["rows"][$i]['udate'] = ( $result[$i]['udate'] + $this->functions->CalculateDateOffset()  * 1000 );
-				unset($response["rows"][$i]['Size']);
-		    }
-		 }
-
-		$response = $this->to_utf8($response);
-
-		break;
-	    }
+			case 'labeled':
+			{
+				list($messageId, $labelId) = explode('#', $URI['id']);
+				$folderName = basename($messageId);
+				$messageNumber = dirname($messageId);
+			
+				if ($folderName && $messageNumber && $labelId) {
+					$this->mbox = $this->open_mbox($folderName);
+					imap_clearflag_full($this->mbox, $messageNumber, '$Label' . $labelId, ST_UID);
+
+					imap_close($this->mbox);
+					$this->mbox = false;
+				}
+			}
+			case 'followupflagged':
+			{
+				list($messageId, $followupflaggedId) = explode('#', $URI['id']);
+				$folderName = basename($messageId);
+				$messageNumber = dirname($messageId);
+			
+				if ($folderName && $messageNumber && $followupflaggedId) {
+					$this->mbox = $this->open_mbox($folderName);
+					imap_clearflag_full($this->mbox, $messageNumber, '$Followupflag' . $followupflaggedId, ST_UID);
+
+					imap_close($this->mbox);
+					$this->mbox = false;
+				}
+			}
+		}
+
+		//TODO - return
 	}
-	return $response;
-    }
+
+    public function deleteAll( $URI, $justthese = false, $criteria = false ) // avaliar
+    {}
+
+    public function update( $URI, $data, $criteria = false )
+    {
+		//TODO - remove
+		//TODO - create
+	}
 
 //     public function retrieve( $concept, $id, $parents, $justthese = false, $criteria = false )
 //     {
-// 	return $this->read( array( 'id' => $id, 
+// 			return $this->read( array( 'id' => $id, 
 // 			    'concept' => $concept, 
 // 			    'context' => $parents ), $justthese );
 //     }
 
-    public function read( $URI, $justthese = false )
-    {
-
-	return $this->to_utf8( $this->get_info_msg( array('msg_number'=>$URI['id'],
-													  'msg_folder'=>str_replace( '.', $this->imap_delimiter, $justthese['context']['folder'] )) ) );
-    }
-
-    public function create( $URI, $data )
-    {}
-
-    public function delete( $URI, $justthese = false, $criteria = false )
-    {}
-
-    public function deleteAll( $URI, $justthese = false, $criteria = false ) // avaliar
-    {}
-
-    public function update( $URI, $data, $criteria = false )
-    {}
-
     public function replace( $URI, $data, $criteria = false )
     {}
@@ -187,15 +446,38 @@
     function to_utf8($in) 
     { 
-	if (is_array($in)) { 
-		foreach ($in as $key => $value) { 
-			$out[$this->to_utf8($key)] = $this->to_utf8($value); 
+		if (is_array($in)) { 
+			foreach ($in as $key => $value) { 
+				$out[$this->to_utf8($key)] = $this->to_utf8($value); 
+			} 
+		} elseif(is_string($in)) { 
+				return mb_convert_encoding( $in , 'UTF-8' , 'UTF-8 , ISO-8859-1' ); 
+		} else { 
+			return $in; 
 		} 
-	} elseif(is_string($in)) { 
-			return mb_convert_encoding( $in , 'UTF-8' , 'UTF-8 , ISO-8859-1' ); 
-	} else { 
-		return $in; 
-	} 
-	return $out; 
+		return $out; 
     }
-
+	
+	    
+    private static function parseFilter( $filter ,&$map){
+		
+		if( !is_array( $filter ) || count($filter) <= 0) return null;
+					
+		$op = array_shift( $filter );
+		switch(strtolower($op))
+		{
+			case 'and': {
+				foreach ($filter as $term)
+					self::parseFilter($term ,&$map);
+				return;
+			}
+			case 'in': {
+				$map[$filter[0]] = array_merge($map[$filter[0]], $filter[1]);
+				return;
+			}
+			case '=': {
+				$map[$filter[0]][] = $filter[1];
+			}
+		}
+	}
+	
 }
Index: /trunk/prototype/config/followupflag.ini
===================================================================
--- /trunk/prototype/config/followupflag.ini	(revision 5533)
+++ /trunk/prototype/config/followupflag.ini	(revision 5533)
@@ -0,0 +1,17 @@
+service = PostgreSQL
+PostgreSQL.concept = expressomail_followupflag
+
+[before.find]
+addVerifyOwnerFilter = modules/mail/interceptors/FollowupflagSecure.php
+addDefaultElementsFilter = modules/mail/interceptors/FollowupflagSecure.php
+
+;[after.find]
+;addDefaultFollowupflags = modules/mail/interceptors/Helpers.php
+
+;[before.delete]
+;clearAllFlaggedOfFollowupflag = modules/mail/interceptors/Helpers.php
+
+[PostgreSQL.mapping]
+id = id
+uid = user_id
+name = name
Index: /trunk/prototype/config/label.ini
===================================================================
--- /trunk/prototype/config/label.ini	(revision 5533)
+++ /trunk/prototype/config/label.ini	(revision 5533)
@@ -0,0 +1,17 @@
+service = PostgreSQL
+PostgreSQL.concept = expressomail_label
+
+[before.find]
+addVerifyOwnerFilter = modules/mail/interceptors/LabelSecure.php
+
+[before.delete]
+clearAllLabeledsOfLabel = modules/mail/interceptors/Helpers.php
+
+[PostgreSQL.mapping]
+id = id
+uid = user_id
+name = name
+borderColor = border_color
+backgroundColor = background_color
+fontColor = font_color
+
Index: /trunk/prototype/config/followupflagged.ini
===================================================================
--- /trunk/prototype/config/followupflagged.ini	(revision 5533)
+++ /trunk/prototype/config/followupflagged.ini	(revision 5533)
@@ -0,0 +1,50 @@
+service = PostgreSQL
+
+PostgreSQL.concept = expressomail_message_followupflag
+;Imap.concept = followupflag
+
+[before.find]
+addVerifyOwnerFilter = modules/mail/interceptors/FollowupflagSecure.php
+
+[after.find]
+deepnessFollowupflaggeds = modules/mail/interceptors/Helpers.php
+
+[PostgreSQL.before.create]
+letFollowupflaggedKeepUnique = modules/mail/interceptors/Helpers.php
+
+[PostgreSQL.after.create]
+doImapCreate = modules/mail/interceptors/Helpers.php
+
+[PostgreSQL.before.find]
+doImapFind = modules/mail/interceptors/Helpers.php
+
+[PostgreSQL.before.read]
+doImapRead = modules/mail/interceptors/Helpers.php
+
+[PostgreSQL.before.delete]
+doImapDelete = modules/mail/interceptors/Helpers.php
+
+[PostgreSQL.before.update]
+doImapUpdate = modules/mail/interceptors/Helpers.php
+
+
+[PostgreSQL.mapping]
+id = id
+uid = user_id
+followupflagId = followupflag_id
+;TODO - retirar folderName e messageNumber do banco
+folderName = folder_name
+messageNumber = message_id
+alarmDeadline = alarm_deadline
+doneDeadline = done_deadline
+isDone = is_done
+borderColor = border_color
+backgroundColor = background_color
+fontColor = font_color
+
+[Imap.mapping]
+id = id
+followupflagId = followupflag_id
+folderName = folder_name
+messageNumber = message_id
+
Index: /trunk/prototype/config/labeled.ini
===================================================================
--- /trunk/prototype/config/labeled.ini	(revision 5533)
+++ /trunk/prototype/config/labeled.ini	(revision 5533)
@@ -0,0 +1,19 @@
+;service = PostgreSQL
+;PostgreSQL.concept = expressomail_message_label
+service = Imap
+Imap.concept = label
+
+
+[before.find]
+makeLabelListFilter = modules/mail/interceptors/Helpers.php
+
+[after.find]
+deepnessLabeleds = modules/mail/interceptors/Helpers.php
+
+[Imap.mapping]
+id = id
+labelId = label_id
+folderName = folder_name
+messageNumber = message_id
+
+;TODO - interceptor para evitar que existam mais de um entrada com os campos "folderName", "messageNumber" e "labelId" identicos
Index: /trunk/prototype/config/OpenLDAP.srv
===================================================================
--- /trunk/prototype/config/OpenLDAP.srv	(revision 5399)
+++ /trunk/prototype/config/OpenLDAP.srv	(revision 5533)
@@ -5,5 +5,5 @@
 host = 127.0.0.1
 
-;context = dc=exemplo.com
+context = "dc=prognus"
 ;user = 
 ;password = 
Index: /trunk/prototype/config/PostgreSQL.srv
===================================================================
--- /trunk/prototype/config/PostgreSQL.srv	(revision 5523)
+++ /trunk/prototype/config/PostgreSQL.srv	(revision 5533)
@@ -3,10 +3,10 @@
 [config]
 port = 5432
-dbname= expresso
+dbname= expresso24douglasz
 user=postgres
 host = /var/run/postgresql
-;conexão via tcp
+;conexï¿œo via tcp
 ;host = 127.0.0.1
 
-;user=
-;password=
+user = expressodev
+password = prognus
Index: /trunk/prototype/modules/mail/interceptors/Helpers.php
===================================================================
--- /trunk/prototype/modules/mail/interceptors/Helpers.php	(revision 5533)
+++ /trunk/prototype/modules/mail/interceptors/Helpers.php	(revision 5533)
@@ -0,0 +1,195 @@
+<?php
+include_once ROOTPATH."/../expressoMail1_2/inc/class.imap_functions.inc.php";
+
+class Helpers {    
+
+/**
+ * LABELS
+ */ 
+	public function deepnessLabeleds( &$uri , &$result , &$criteria , $original ){                
+
+		if(isset($original['criteria']['deepness']))
+		{
+			foreach ($result as $i => $v)
+			{
+				if(isset($v['labelId']))
+				{
+					$labels = Controller::find( array( 'concept' => 'label' ) , false, array( 'filter' => array('=', 'id'  ,  $v['labelId']) ));     
+					$result[$i]['label'] = $labels[0];
+				}              
+
+			}
+		}
+
+		return $result;
+	}
+	
+	/**
+	 * MÃ©todo a ser chamado na exclusÃ£o de um label, procedendo com a
+	 * desvinculaÃ§Ã£o deste label com todas as mensagens a que estava vinculado
+	 */
+	public function clearAllLabeledsOfLabel( &$uri , &$result , &$criteria , $original ){
+		
+		$labeleds = Controller::find( array( 'concept' => 'labeled' ) , false, array( 'filter' => array('=', 'labelId'  ,  $uri['id']) ));
+		if (empty($labeleds))
+			return;
+		
+		$labeledsIds = array();
+		foreach ($labeleds as $e) {
+				$labeledsIds[] = $e['id'];
+		}
+		
+		Controller::delete( array( 'concept' => 'labeled' ), false, array( 'filter' => array( 'IN', 'id', $labeledsIds )) );
+
+		//return $result;
+	}
+	/**
+	 * MÃ©todo a ser chamado ao listar os labeleds, uma vez que as funÃ§Ã£o de IMAP do PHP nÃ£o sÃ£o capazes de 
+	 * obter a lista de todos os labels e nem sÃ£o capazes de obter os labels de uma dada mensagem
+	 */
+	public function makeLabelListFilter( &$uri , &$result , &$criteria , $original ){
+
+		if (!isset($criteria['filter']) || !self::in_arrayr('labelId', $criteria['filter'])) {
+			$labels = Controller::find( array( 'concept' => 'label' ) );
+
+			$list = array();
+			foreach ($labels as $label)
+				$list[] = $label['id'];
+				
+			$filter = array( 'IN' , 'labelId' , $list );
+			
+			if (isset($criteria['filter']) && $criteria['filter']!=NULL && count($criteria['filter']) != 0)
+				$criteria['filter'] = array( 'AND', $criteria['filter'], $filter );
+			else
+				$criteria['filter'] =  $filter;
+		}
+	}
+	
+	public static function in_arrayr($needle, $haystack) {
+		foreach ($haystack as $v) {
+				if ($needle == $v) return true;
+				elseif (is_array($v)) return self::in_arrayr($needle, $v);
+		}
+		return false;
+	} 
+		
+	
+/**
+ * FOLLOWUPFLAGS
+ */ 
+
+	public function deepnessFollowupflaggeds( &$uri , &$result , &$criteria , $original ){                
+	
+		if(isset($original['criteria']['deepness']))
+		{
+			foreach ($result as $i => $v)
+			{
+				if(isset($v['followupflagId']))
+				{
+					$followupflag = Controller::find( array( 'concept' => 'followupflag' ) , false, array( 'filter' => array('=', 'id'  ,  $v['followupflagId']) ));     
+					$result[$i]['followupflag'] = $followupflag[0];
+				}
+				
+				if(isset($v['messageNumber']) && isset($v['folderName']))
+				{
+					$details = $criteria['deepness'] == '1' ? 'headers' : 'all';
+					
+					$imapService = new imap_functions();
+					$message = $imapService->getMessages(array('messages' => array($v['folderName'] => array($v['messageNumber'])), 'details' => $details));
+					$result[$i]['message'] = $message[$v['folderName']][0];				
+				}     
+			}
+		}
+
+		return $result;
+	}	
+
+	public function letFollowupflaggedKeepUnique (&$uri , &$params , &$criteria , $original ){
+		if (isset($params['folderName']) && isset($params['messageNumber'])) {
+			$filter = array ( 'AND', array('=', 'folderName', $params['folderName']), array('=', 'messageNumber', $params['messageNumber']) );
+			Controller::delete( array( 'concept' => 'followupflagged' ), false, array( 'filter' => $filter));
+		}
+	}
+
+/*	
+	public function clearAllFlaggedOfFollowupflag( &$uri , &$result , &$criteria , $original ){
+		//TODO - filter
+		return $result;
+	}
+*/	
+
+	//PostgreSQL.after.create
+	public function doImapCreate( &$uri , &$params , &$criteria , $original ) {
+	
+		$imap_uri = $uri;
+		$imap_uri['service'] = 'Imap';
+		
+		$imap_params = $params + $original['properties'];
+		if ($imap_params['folderName'] && $imap_params['messageNumber'] && $imap_params['id']) {
+			$imap_uri['id'] = $imap_params['folderName'] . '/' . $imap_params['messageNumber'] . '#' . $imap_params['id']; 
+			$imap_params['id'] = $imap_params['folderName'] . '/' . $imap_params['messageNumber'] . '#' . $imap_params['id']; 
+			$result = Controller::create($imap_uri, $imap_params);
+		}
+		
+	}
+	
+	//PostgreSQL.before.find
+	public function doImapFind( &$uri , &$params , &$criteria , $original ) {
+		$imap_uri = $uri;
+		$imap_uri['service'] = 'Imap';
+		$result = Controller::find($imap_uri, $params, $criteria);
+		
+		if($result) {
+			/** TODO:
+			 *	- se achar no Imap, passar as referencias para o PostgresSQL para que
+			 *  seja conferida a consistÃªncia dos dados no postgres (Nota: os dados podem
+			 *  ficar inconsistentes no postgres se a mensagem for movida no Imap, assim
+			 *  messageNumber e/ou folderName podem estar desatualizados no postgres)
+			 */
+		}
+	}
+	
+	//PostgreSQL.before.read
+	public function doImapRead( &$uri , &$params , &$criteria , $original ) {
+		$imap_uri = $uri;
+		$imap_uri['service'] = 'Imap';
+		$result = Controller::read($imap_uri, $params, $criteria);
+	}
+	
+	//PostgreSQL.before.delete
+	public function doImapDelete( &$uri , &$params , &$criteria , $original ) {
+		$toGetURI = $uri;
+		$flagged = Controller::read($toGetURI);
+
+		//assumindo que $criteria['filter'] venha sempre vazio no delete
+		$imap_criteria['filter'] = array();
+		foreach ($flagged as $key => $value) {
+			$imap_criteria['filter'][] = array('=', $key, $value); 
+		}
+		if($imap_criteria['filter']) array_unshift($imap_criteria['filter'], 'AND');
+		
+		$imap_uri = $uri;
+		$imap_uri['service'] = 'Imap';
+		if ($flagged && $flagged['id']) {
+			$flagged['id']  = $flagged['folderName'] . '/' . $flagged['messageNumber'] . '#' . $flagged['id']; 
+			$imap_uri['id'] = $flagged['id']; 
+		}
+
+		$result = Controller::delete($imap_uri, $params, $imap_criteria);		
+	}
+	
+	//PostgreSQL.before.update
+	public function doImapUpdate( &$uri , &$params , &$criteria , $original ) {
+		//TODO - update
+		//$imap_uri = $uri;
+		//$imap_uri['service'] = 'Imap';
+		//$result = Controller::update($imap_uri, $params, $criteria);
+	}
+	/*
+    public function createCalendarToSchedulable( &$uri , &$result , &$criteria , $original ){
+		Controller::create(array('concept' => 'calendarToSchedulable'), array('calendar' => $original['properties']['calendar'], 'schedulable' => $result['id'] ));
+	}
+	*/
+}
+
+?>
Index: /trunk/prototype/modules/mail/interceptors/LabelSecure.php
===================================================================
--- /trunk/prototype/modules/mail/interceptors/LabelSecure.php	(revision 5533)
+++ /trunk/prototype/modules/mail/interceptors/LabelSecure.php	(revision 5533)
@@ -0,0 +1,17 @@
+<?php
+class LabelSecure {	
+
+	public function addVerifyOwnerFilter (&$uri , &$params , &$criteria , $original ){
+		
+		$ownerFilter = array( '=' , 'uid' , Config::me('uidNumber') );
+		
+		if (isset($criteria['filter']) && $criteria['filter']!=NULL && count($criteria['filter']) != 0)
+			$criteria['filter'] = array( 'AND', $criteria['filter'], $ownerFilter );
+		else
+			$criteria['filter'] =  $ownerFilter;
+			
+	}  
+
+}
+
+?>
Index: /trunk/prototype/modules/mail/interceptors/FollowupflagSecure.php
===================================================================
--- /trunk/prototype/modules/mail/interceptors/FollowupflagSecure.php	(revision 5533)
+++ /trunk/prototype/modules/mail/interceptors/FollowupflagSecure.php	(revision 5533)
@@ -0,0 +1,28 @@
+<?php
+class FollowupflagSecure {	
+	
+	public function addVerifyOwnerFilter (&$uri , &$params , &$criteria , $original ){
+		
+		$ownerFilter = array( '=' , 'uid' , Config::me('uidNumber') );
+		
+		if (isset($criteria['filter']) && $criteria['filter']!=NULL && count($criteria['filter']) != 0)
+			$criteria['filter'] = array( 'AND', $criteria['filter'], $ownerFilter );
+		else
+			$criteria['filter'] =  $ownerFilter;
+			
+	}  
+
+	public function addDefaultElementsFilter (&$uri , &$params , &$criteria , $original ){
+		
+		$defaultsFilter = array( 'IN' , 'id' , array('1','2','3','4','5','6') );
+		
+		if (isset($criteria['filter']) && $criteria['filter']!=NULL && count($criteria['filter']) != 0)
+			$criteria['filter'] = array( 'OR', $criteria['filter'], $defaultsFilter );
+		else
+			$criteria['filter'] =  $defaultsFilter;
+		
+	}  
+     
+}
+
+?>
Index: /trunk/prototype/modules/mail/css/label.css
===================================================================
--- /trunk/prototype/modules/mail/css/label.css	(revision 5533)
+++ /trunk/prototype/modules/mail/css/label.css	(revision 5533)
@@ -0,0 +1,102 @@
+.label-configure-win fieldset { border: 1px solid #CCC; border-radius:5px; margin:5px;}
+.label-configure-win legend { color: #707070; }
+.label-configure-win ul{text-align:left; margin: 0; padding: 0;}
+
+.label-configure-win { margin: 5px;}
+.label-configure-win .input-nome { width: 200px; outline:0; background:#FFF; }
+.label-configure-win .lebals-colorpicker { border: 1px solid #CCC; height: 210px; } 
+.label-configure-win .label-conf { float: left;}
+.label-configure-win .buttons { float:right; margin:5px 5px 0 0; }
+.label-configure-win .button-close-window { float:right; margin:6px 5px 0 0; }
+.label-configure-win .colorpicker { float: right; margin: 0 30px 0 0; } 
+.label-configure-win .preview-label-inner { margin: 2px 0 0 10px; float: left; }
+
+.label-configure-win .preview-label-outer { 
+	margin: 5px; 
+	float:left; 
+	width: 151px; 
+	height: 20px;  
+	margin: 20px 0 0 130px; 
+	-moz-border-radius: 4px; 
+	-webkit-border-radius: 4px; 
+	border: 1px solid #333;
+}
+.label-configure-win .colorwell { margin: 0; outline: 0; width: 151px; }
+.label-configure-win .label-cor { float:left; width: 130px;} 
+.label-configure-win .imgTriangle { width: 5px; height: 5px; background: #333;}
+
+.acc-list {
+	font-family: "Trebuchet MS", Tahoma, Verdana, Arial, sans-serif; 
+	font-size:11px;
+	color:#555; 
+}
+
+.acc-list h3{
+	font-family: "Trebuchet MS", Tahoma, Verdana, Arial, sans-serif; 
+	font-size:11px; 
+	color:#555; 
+	margin:0; 
+	padding:5px 3px; 
+	background-color:#fff;
+}
+
+.acc-list ul{ margin:5px 0;}
+.acc-list ul li{ border-radius:3px; padding:3px;}
+.label-configure-win .acc-list ul li:hover {background-color:#DDD;}
+.label-configure-win .acc-list ul li.active {background-color:#EB8F00;}
+.label-configure-win .acc-list ul li strong {display:block;}
+.label-configure-win .acc-list ul li em {display:block;}
+
+.label-configure-win .configure-label-content {
+	width:590px;
+	height:335px;
+	float:right;
+	border: 1px solid #A6C9E2; 
+	margin:2px 5px 0 0;
+	-moz-border-radius: 5px; 
+	-webkit-border-radius: 5px;
+}
+.label-configure-win .acc-list.list-label-content{
+	width:190px;
+	height:368px;
+	float:left;
+	margin:2px 10px 0 5px;
+	border: 1px solid #A6C9E2;
+	-moz-border-radius: 5px; 
+	-webkit-border-radius: 5px;
+}
+.label-configure-win .acc-list.list-label{
+	width:150px; 
+	height:70%; 
+	-moz-border-radius: 5px; 
+	-webkit-border-radius: 5px; 
+	margin:10px 0 0 0;
+}
+
+.label-configure-win .label-list-container .label-list { overflow: auto; height: 293px; margin:0px;}
+.label-configure-win .label-list-container .label-list li{ background: #FFF; margin:3px 2px 0 2px; border:1px solid #CCC; width: 162px; height:18px;}
+.label-configure-win .label-list-container .label-list .acc-list ul li{ border-radius:3px; padding:2px;}
+.label-configure-win .label-list-container .label-list li:hover { cursor:pointer; background:#ECEDFF}
+.label-configure-win .label-list-container .label-list li.empty-item { border:0px;}
+.label-configure-win .label-list-container .label-list li.empty-item:hover { cursor : auto; background:white;}
+.label-configure-win .label-list li .button { display:none;}
+.label-configure-win .label-list li:hover .button { display:block; }
+
+#MyMarckersList.list-label .my-labels {margin: 10px 0 0 20px; text-align:left; position: relative;}
+#MyMarckersList.list-label .title-my-labels{margin:0 0 0 5px;}
+#MyMarckersList.list-label .status-list-labels{display:inline-block; position: absolute;}
+#MyMarckersList.list-label ul {height: 60%; margin: 5px 0 0 6px; padding:0; list-style:none; }
+#MyMarckersList.list-label.acc-list ul li{ border-radius:3px;  padding:2px 2px 3px 2px;}
+#MyMarckersList.list-label li{ background: #FFF; margin:2px 2px 0 12px; border:1px solid #CCC; width: 150px; height:13px; }
+#MyMarckersList.list-label li:hover { cursor:pointer; background:#ECEDFF}
+
+.label-configure-win .insert-label{width: 200px; outline:0; background:#FFF;}
+.label-configure-win .attendee-list-add fieldset { height:15px; width: 178px; background:#FFF; margin:5px 2px 20px 2px;}
+.label-configure-win .attendee-list-add fieldset .insert-label{ width:130px; border:#FFF; outline: 0 none; margin:0; }
+.label-configure-win .color-suggestions { margin: 10px 0 30px 0; }
+.label-configure-win .form-item { margin: 5px 0;}
+.label-configure-win .selectedDefault { background: #fed4b4; border: 1px solid #fb8c37; -moz-border-radius: 5px; -webkit-border-radius:5px; }
+.label-configure-win .edit-value-list { opacity:0.65; margin-top:0; width:125px;}
+
+#listMarkers{width: 800px !important;}
+.label-configure-win .add-label-button { float:right; cursor: pointer; }
Index: /trunk/prototype/modules/mail/css/followupflag.css
===================================================================
--- /trunk/prototype/modules/mail/css/followupflag.css	(revision 5533)
+++ /trunk/prototype/modules/mail/css/followupflag.css	(revision 5533)
@@ -0,0 +1,72 @@
+.ZebraDialog_Body .footerMais,.footerMenos {cursor: pointer; color: #0f1dff;}
+.ZebraDialog_Body .footerMais2,.footerMenos2 {cursor: pointer; color: #0f1dff;}
+.ZebraDialog_Body .alert-flags a{ cursor: pointer;}
+.ZebraDialog_Body .alert-flags li:hover{ text-decoration: underline;}
+
+.followupflag-configure-win { width:543px; height:412px !important;  } 
+.followupflag-container { 
+	width:530px; 
+	height:398px; 
+	border: 1px solid #A6C9E2; 
+	float:left; 
+	-moz-border-radius: 5px; 
+	-webkit-border-radius: 5px; 
+	margin:5px;
+}
+
+.followupflag-configure-win .followupflag-container  fieldset{border: 1px solid #CCC; border-radius:5px; margin:5px;}
+.followupflag-configure-win .followupflag-container  legend {color: #707070; font-weight:bold;}
+
+.followupflag-configure-win .followupflag-configure button { height:20px; margin: 0; top:4px; }
+.followupflag-container .followupflag-configure { float: left; width: 270px }
+.followupflag-container .followupflag-configure .label-name{display: block;}
+
+.followupflag-container .alarm-fields{ display: block; margin-top:15px; width:265px;}
+.followupflag-container .date,
+.followupflag-container .time{ -moz-border-radius: 5px; -webkit-border-radius: 5px; outline: 0; }
+.followupflag-container .alarm-datetime-fields {float:right;}
+.followupflag-container .completed-followup{margin-top:6px;}
+
+.followupflag-container .right-data {margin: 5px 0; width: 195px; float: right;}
+.followupflag-container .right-data label {display: block;}
+
+.followupflag-container .date-begin { 
+	margin: 0 0 5px 44px; 
+	-moz-border-radius: 5px; 
+	-webkit-border-radius: 5px; 
+	outline: 0; 
+}
+
+.followupflag-container .date-conclusion { 
+	margin: 0 0 0 16px; 
+	-moz-border-radius: 5px;
+	-webkit-border-radius: 5px; 
+	 outline: 0; 
+ }
+.followupflag-container .followupflag-color.sample-list .sample-item { padding: 5px; margin:0 5px; }
+
+.followupflag-container .followupflag-color.sample-list .sample-item.selected { 
+	background: #fed4b4; 
+	border: 1px solid #fb8c37; 
+	-moz-border-radius: 5px; 
+	-webkit-border-radius:5px; 
+}
+
+.left-seletor-flag { float: left; margin: 3px 20px 3px 0; }
+.color-followup-flag { float: left; width: 400px; }
+.form-item { margin: 5px 0;}
+.flag-label { float: left; margin: 0 5px 0 0; } 
+.followupflag-container .background-color  {margin:0; outline: 0; width: 100px; -moz-border-radius: 5px; -webkit-border-radius:5px; float: left; }
+.flag-edit { background: #00820F; width: 8px; height: 6px; float:left; margin: 4px 0 -3px 5px; }
+.flag-edited{ width: 8px; height: 6px;}
+.colorpicker { float: right; margin: -15px 0 0 0; }
+
+.followupflag-configure-win .followupflag-container .menu-configure-followupflag{ 
+	position:absolute; 
+	bottom:14px; 
+	right:11px; 
+	background:transparent; 
+	width:auto; 
+	margin:0;
+	padding:0;
+}
Index: /trunk/prototype/modules/mail/js/label.js
===================================================================
--- /trunk/prototype/modules/mail/js/label.js	(revision 5533)
+++ /trunk/prototype/modules/mail/js/label.js	(revision 5533)
@@ -0,0 +1,533 @@
+function colors_suggestions(){
+	return [
+				{name:'Padrão', border:'#3366cc', font:'#ffffff', background:'#3366cc'},
+				{name:'Coala', border:'#123456', font:'#ffffff', background:'#385c80'},
+				{name:'Tomate', border:'#d5130b', font:'#111111', background:'#e36d76'},
+				{name:'Limão', border:'#32ed21', font:'#1f3f1c', background:'#b2f1ac'},
+				{name:'Alto contraste', border:'#000000', font:'#ffffff', background:'#222222'}
+			]		
+}
+function rgb2hex(rgb){
+ rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
+ return "#" +
+  ("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
+  ("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
+  ("0" + parseInt(rgb[3],10).toString(16)).slice(-2);
+}
+
+function init_label(data){
+
+	winElement = data.window;
+
+	var configureLabel = function(event, ui){
+		var idmarkernow = $(this).find('[name="labelItemId"]').val();
+		winElement.find('.edit-label').val(idmarkernow);
+		winElement.find('.input-nome').val($(this).find("span").text());
+		
+		var colorpicker = winElement.find('.lebals-colorpicker');
+		colorpicker.find('input[name="backgroundColor"]').val(rgb2hex($(this).css("backgroundColor")))
+		.css("background-color", $(this).css("backgroundColor")).focus().end()
+		.find('input[name="fontColor"]').val(rgb2hex($(this).css("color"))).css("background-color", $(this).css("color")).focus().end()
+		.find('input[name="borderColor"]').val(rgb2hex($(this).css("border-left-color"))).css("background-color", $(this).css("border-left-color")).focus().end()
+		.find('.preview-label-outer').css({
+			'background-color':$(this).css("backgroundColor"),
+			'color':$(this).css("color"),
+			'border-color':$(this).css("border-left-color")
+		})		
+		winElement.find(".preview-label-inner").text($(this).text());
+	}
+	//TODO Mudar quando API abstrair atualizações no cache
+	DataLayer.remove('label',false);
+	labels = DataLayer.get('label',{criteria:{order: 'name'}});
+	
+	if(labels){
+		Label_List = winElement
+		.find(".label-list-container").html(DataLayer.render("../prototype/modules/mail/templates/label_list.ejs", {labels: labels}));
+		
+	}else{
+		/**
+		* Quando não existir marcadores cadastrados
+		* exibe a mensagem informando o usuário de que não há
+		* nenhum marcador cadastrado.
+		*/
+		Label_List = winElement
+		.find(".label-list-container").html('<ul class="label-list"><li class="empty-item">Nenhum Marcador Cadastrado.</li></ul>');
+		
+	}
+	Label_List.end()
+	.find('.button').button()
+	.filter('.edit').button({icons:{primary:'ui-icon-pencil'}, text:false}).end()
+	.filter('.close').button({icons:{primary:'ui-icon-close'}, text:false}); 	
+	
+	var editLabel = function(){	
+		var conteudoSpan = $(this).parent().find(".text-list").text();
+		var span = $(this).parent().find(".text-list");
+		$(this).parent().trigger('click').unbind('click', configureLabel).find("span.text-list")
+		.html('<input name="edit-value-list" class="edit-value-list" type="text" value="'+conteudoSpan+'">').find("input[name='edit-value-list']").keydown(function(event){
+			event.stopPropagation();
+			$("input.edit-value-list").keyup(function () {
+				var value = $(this).val();
+				winElement.find('.input-nome').val(value);
+			}).keyup();
+			if(event.keyCode == 13){
+				$(span).html($(".label-list").find(".edit-value-list").val())
+				.parent().find('.edit').removeClass("hidden").parents("li").click(configureLabel).trigger("click");
+				winElement.find(".buttons .save-label").trigger("click");
+			}else if( event.keyCode == 27){
+				$(this).trigger("focusout");
+			}
+		}).focusout(function(){
+			$(span).html(conteudoSpan)
+			.parent().find('.edit').removeClass("hidden").parents("li").click(configureLabel);
+		}).focus();
+		$(this).addClass("hidden");
+	}
+	
+	winElement.find('.edit').click(editLabel);
+	winElement.find('.close').click(function(event){
+		var id = $(this).parents(".label-item").attr("class").match(/label-item-([\d]+[()a-zA-Z]*)/)[1];
+		confirmDelete(id);
+		event.stopImmediatePropagation();
+	});
+	/**
+	* Testa novamente se existem marcadores cadastrados, 
+	* pois nesse momento os botões Excluir, Desfazer e Salvar já existem
+	* e os marcadores já estão listados na tela,
+	* então é possível alterar o text do Salvar para Criar,
+	* caso não exista nenhum marcador cadastrado e listado na tela de configuração dos marcadores,
+	* ou "marcar" o primeiro marcador listado com o "triangulo", caracterizando que o mesmo está selecionado.
+	*/
+	
+	//marca 'd agua e adicionar label na lista.
+	winElement.find(".insert-label").Watermark(winElement.find(".insert-label").val());
+	
+	$("input.insert-label").keyup(function () {
+		$.Watermark.HideAll();
+		var value = $(this).val();
+		winElement.find('.input-nome').val(value);
+	}).keyup();
+	
+	if (!(labels)){
+		winElement.find(".buttons .save-label .ui-button-text").text('Criar');
+		$(".delete-label").button("disable");
+	}else{
+		winElement.find(".label-list li:first").addClass("selected").prepend("<img src='../prototype/modules/mail/img/triangle.png' style='margin: 0 5px 0 -5px;'>");
+	}
+	$(".save-label").button("disable");
+	/**
+	* seta a ação de click para os marcadores listados na tela
+	*/
+	winElement.find(".label-list li").not(".empty-item").click(configureLabel);
+	
+	if (data.selectedItem)
+		winElement.find(".label-list li.label-item-"+data.selectedItem).trigger("click");
+	else
+		winElement.find(".label-list li:first").trigger("click");
+		
+	var dataColorPicker = {
+		colorsSuggestions: colors_suggestions()
+	};
+	
+	winElement.find('select.color-suggestions').change(function() {
+		$(".save-label").button("enable");
+		var colorpicker = winElement.find('.lebals-colorpicker');
+		var colors;
+		if(colors = dataColorPicker.colorsSuggestions[$(this).val()]) {	
+			colorpicker
+			.find('input[name="fontColor"]').val(colors.font).focus().end()	
+			.find('input[name="backgroundColor"]').val(colors.background).focus().end()
+			.find('input[name="borderColor"]').val(colors.border).focus().end()
+
+			.find('.preview-label-outer').css({
+				'background-color':dataColorPicker.colorsSuggestions[$(this).val()].background,
+				'border-color':dataColorPicker.colorsSuggestions[$(this).val()].border,
+				'color':dataColorPicker.colorsSuggestions[$(this).val()].font 
+			});
+		}					
+	});
+	var colorpickerPreviewChange = function(color) {
+			
+		var pickedup = winElement.find('.colorwell-selected').val(color).css('background-color', color);
+
+		$(".save-label").button("enable");
+		
+		var colorpicker = winElement.find('.lebals-colorpicker');			
+
+		if (pickedup.is('input[name="backgroundColor"]')) {
+			colorpicker.find('.preview-label-outer').css('background-color',color);
+		} else if (pickedup.is('input[name="fontColor"]')) {
+			colorpicker.find('.preview-label-outer').css('color',color);
+		} else if (pickedup.is('input[name="borderColor"]')) {
+			colorpicker.find('.preview-label-outer').css('border-color',color);
+		}		
+	} 
+		
+	var f = $.farbtastic(winElement.find('.colorpicker'), colorpickerPreviewChange);
+	var selected;
+				
+	winElement.find('.colorwell').each(function () {
+		f.linkTo(this);
+	})
+	.focus(function() {
+		if (selected) {
+			$(selected).removeClass('colorwell-selected');
+		}
+		$(selected = this).addClass('colorwell-selected');
+		f.linkTo(this, colorpickerPreviewChange);
+		f.linkTo(colorpickerPreviewChange);
+	});
+	
+
+	
+	winElement.find(".add-label-button").click(function (event) {
+		$.Watermark.HideAll();
+		var name = winElement.find(".insert-label").val();
+		if(name.length >= 2){
+			DataLayer.put('label', {name: name, uid: User.me.id});
+			
+			$(".add-label-button").removeClass("ui-icon ui-icon-plus")
+			.html('<img alt="Carregando" title="Carregando" style="margin-left:10px;" src="../prototype/modules/mail/img/loader.gif" />');
+			
+			DataLayer.commit(false, false, function(){
+
+				labels = DataLayer.get('label',{criteria:{order: 'id'}}, true);
+				newLabel = {
+					id: labels[labels.length -1 ].id, 
+					name : labels[labels.length -1].name,
+					uid: User.me.id
+				};
+
+				$(".label-list-container ul").find(".empty-item").css("display","none");
+				
+				$(".label-list-container ul, .list-label ul")
+				.prepend(DataLayer.render("../prototype/modules/mail/templates/label_listitem.ejs", newLabel))
+				.find("li:first")
+				.fadeIn("slow").click(configureLabel);
+				
+				$(".label-list-container .label-list li").not(".empty-item").click(function(){
+					$(".save-label").button("disable");
+					$(".label-list-container .label-list li").find("img").remove();
+					$(".label-list-container .label-list li.label-item").removeClass("selected");
+					$(this).prepend("<img src='../prototype/modules/mail/img/triangle.png' style='margin: 0 5px 0 -5px;'>");
+					$(this).addClass("selected");
+				});
+				
+				$(".label-list-container .label-list li").find('.button').button()
+				.filter('.edit').button({icons:{primary:'ui-icon-pencil'}, text:false}).end()
+				.filter('.close').button({icons:{primary:'ui-icon-close'}, text:false});
+					
+				winElement.find('.edit').unbind("click").click(editLabel);
+				
+				winElement.find('.close').click(function(event){
+					var id = $(this).parents(".label-item").attr("class").match(/label-item-([\d]+[()a-zA-Z]*)/)[1];
+					confirmDelete(id);
+					event.stopImmediatePropagation();
+				});
+				
+				$.Watermark.ShowAll();
+				winElement.find(".insert-label").val("");
+				
+				//posiciona para edição o label inserido			
+				winElement.find("ul.label-list li:first").trigger("click");			
+				winElement.find(".buttons .save-label .ui-button-text").text('Salvar');
+				$(".delete-label").button("enable");		
+
+				//Remove o título da lista de Marcadores da tela principal do módulo
+				$(".my-labels").removeClass("hidden");
+				/**
+				* atualiza menu
+				* Remove o menu presente em cada mensagem listada em uma pasta 
+				* e carrega novamente para que os dados sejam atualizados
+				*/
+				$.contextMenu( 'destroy', ".table_box tbody tr");
+				loadMenu();
+				$(".add-label-button").empty()
+				.addClass("ui-icon ui-icon-plus");
+			});
+			} else {
+				alert("Mínimo 2 caracteres");
+			}
+
+		event.stopImmediatePropagation();
+	});
+	
+	winElement.find('.insert-label').keydown(function(event, ui) {
+		if (event.keyCode == 13)
+			winElement.find(".add-label-button").trigger('click');
+	});
+
+	function confirmDelete(id){
+
+		$.Zebra_Dialog('<strong>Deseja excluir esse marcador?</strong>', {
+			'type':     'question',
+			'title':    'Atenção',
+			'buttons': ['Sim','Não'],	
+			'onClose':  function(caption) {
+				if(caption == 'Sim'){
+					deleteLabel(id);
+				}
+			}
+		});	
+	}	
+		
+	function deleteLabel(id){
+		$(".label-list li").each(function () {
+			var regex_match = $(this).attr("class").match(/label-item-([\d]+[()a-zA-Z]*)/);
+			if (regex_match && regex_match[1] && regex_match[1] == id) {	
+				$(this).remove();
+			}
+		});
+		DataLayer.remove('label', id);
+		DataLayer.commit();
+		winElement.find(".label-list li:first").trigger("click");
+		
+		if($(".label-list li").length == 0){
+			winElement.find(".label-list-container").html('<ul class="label-list"><li class="empty-item">Nenhum Marcador Cadastrado.</li></ul>');			
+		} 
+		var qtdLi = $(".label-list-container ul").find("li").not(".empty-item").length;
+		if (qtdLi == 0){
+			$(".my-labels").addClass("hidden");
+			$(".label-list-container ul").find(".empty-item").css("display","");
+			winElement.find(".buttons .save-label .ui-button-text").text('Criar');
+			$(".delete-label").button("disable");	
+					
+			winElement.find('.input-nome').val("");
+			winElement.find(".preview-label-inner").text("");
+		
+			var colorpicker = winElement.find('.lebals-colorpicker');
+			colorpicker.find('input[name="backgroundColor"]').val("#ffffff")
+			.css("background-color", "#ffffff").focus().end()
+			.find('input[name="fontColor"]').val("#444444").css("background-color", "#000000").focus().end()
+			.find('input[name="borderColor"]').val("#cccccc").css("background-color", "#000000").focus().end()
+			.find('.preview-label-outer').css({
+				'background-color':"#ffffff",
+				'color':"#444444",
+				'border-color':"#cccccc"
+			});
+			$(".input-nome").keyup(function () {
+				var value = $(this).val();
+				winElement.find('.preview-label-inner').text(value);
+			}).keyup();				
+		}		
+	}
+	//excluir marcador {deve ser para o botão grande na janela de edição e nao o pequeno da lista}
+	winElement.find(".buttons .delete-label").click(function(event){
+		var id = winElement.find(".edit-label").val();
+		confirmDelete(id);
+		event.stopImmediatePropagation();
+	});
+	$(".label-list-container .label-list li").not(".empty-item").click(function(){
+		$(".label-list-container .label-list li").find("img").remove();
+		$(".label-list-container .label-list li.label-item").removeClass("selected");
+		$(this).prepend("<img src='../prototype/modules/mail/img/triangle.png' style='margin: 0 5px 0 -5px;'>");
+		$(this).addClass("selected");
+	});
+		
+	//salvar/criar marcador
+	winElement.find(".buttons .save-label").click(function(){
+		$(".save-label").button("disable");
+		var labelEdited = {
+			id : winElement.find(".edit-label").val(),
+			uid: User.me.id,
+			name : winElement.find('.input-nome').val(),
+			backgroundColor : winElement.find("input[name='backgroundColor']").val(),
+			fontColor : winElement.find("input[name='fontColor']").val(),
+			borderColor : winElement.find("input[name='borderColor']").val()
+		}
+		var qtdLi = $(".label-list-container ul").find("li").not(".empty-item").length;	
+		// salvar marcador
+		if(qtdLi > 0){
+			$(".label-list-container .label-list li").each(function(){
+				var regex_match_2 = $(this).attr("class").match(/label-item-([\d]+[()a-zA-Z]*)/);
+				
+				 if(regex_match_2 && regex_match_2[1] && regex_match_2[1] == labelEdited.id){
+				   $(this).html("<input type='hidden' name='labelItemId' class='id-item-list' value='"+labelEdited.id+"'>"+"<span class='text-list'>"+labelEdited.name+"</span><div class='button close tiny' style='float: right'></div><div class='button edit tiny' style='float: right'></div>").css({
+					"background" : labelEdited.backgroundColor,
+					"color" : labelEdited.fontColor, 
+					"border-color" : labelEdited.borderColor	
+				   });
+				 }	
+			});
+			
+			$("#MyMarckersList .label-list li").each(function(){
+				var regex_match_2 = $(this).attr("class").match(/label-item-([\d]+[()a-zA-Z]*)/);
+				
+				if(regex_match_2 && regex_match_2[1] && regex_match_2[1] == labelEdited.id){
+					$(this).html("<input type='hidden' name='labelItemId' class='id-item-list' value='"+labelEdited.id+"'>"+"<span>"+labelEdited.name+"</span>");
+					$(this).find(".square-color").css('background', labelEdited.backgroundColor);
+				}	
+			});
+			DataLayer.put('label', labelEdited.id, labelEdited);
+			DataLayer.commit(false, false, function(){
+				$("#MyMarckersList")
+				.html(
+					"<div class='my-labels'>" +
+						"<img src='../prototype/modules/mail/img/tag.png'/>" +
+						"<a class='title-my-labels' tabindex='0' role='button' aria-expanded='false' title='Meus marcadores'>Meus marcadores</a>" +
+						
+						"<span class='status-list-labels ui-icon ui-icon-triangle-1-s'></span>" +
+					"</div>"
+				)
+				.append(DataLayer.render("../prototype/modules/mail/templates/label_list.ejs", {labels:DataLayer.get('label', true)} ))
+				.find("li.label-item").css({"background-color":"#ffffff", "border-color":"#CCCCCC", "color":"#444444"})
+				.find(".square-color").css("display","").click(function(){
+					$(this).parent(".label-item").each(function(){
+						configureLabels({selectedItem: $(this).attr('class').match(/label-item-([\d]+[()a-zA-Z]*)/)[1]});
+					});
+				});
+				
+				$("#MyMarckersList a.title-my-labels").click(function() {
+					$("#MyMarckersList ul.label-list").toggleClass("hidden")
+					$('#MyMarckersList .status-list-labels').toggleClass("ui-icon-triangle-1-s");
+					$('#MyMarckersList .status-list-labels').toggleClass("ui-icon-triangle-1-n");
+				 });
+	 
+				$.Watermark.ShowAll();
+				winElement.find(".insert-label").val("");
+				$(".label-list-container .label-list li").find('.button').button()
+					.filter('.edit').button({icons:{primary:'ui-icon-pencil'}, text:false}).end()
+					.filter('.close').button({icons:{primary:'ui-icon-close'}, text:false});
+				winElement.find('.edit').unbind("click").click(editLabel);
+				
+				winElement.find('.close').click(function(event){
+					var id = $(this).parents(".label-item").attr("class").match(/label-item-([\d]+[()a-zA-Z]*)/)[1];
+					confirmDelete(id);
+					event.stopImmediatePropagation();
+				});
+			});
+		// criar marcador
+		} else{
+			var nameLabel = winElement.find(".input-nome").val();
+			var labelCreated = {
+				uid: User.me.id,
+				name : nameLabel,
+				backgroundColor : winElement.find("input[name='backgroundColor']").val(),
+				fontColor : winElement.find("input[name='fontColor']").val(),
+				borderColor : winElement.find("input[name='borderColor']").val()
+			}
+			
+			if(nameLabel.length >= 2){
+				DataLayer.put('label', labelCreated);
+				DataLayer.commit(false, false, function(){
+
+					labels = DataLayer.get('label',{criteria:{order: 'id'}}, true);
+					newLabel = {
+						id: labels[labels.length - 1].id, 
+						name : labels[labels.length- 1].name,
+						uid: User.me.id,
+						bgColor : winElement.find("input[name='backgroundColor']").val(),
+						fontColor : winElement.find("input[name='fontColor']").val(),
+						borderColor : winElement.find("input[name='borderColor']").val()
+					};
+
+					$(".label-list-container ul").find(".empty-item").css("display","none");
+					$(".label-list-container ul")
+					.prepend(DataLayer.render("../prototype/modules/mail/templates/label_listitem.ejs", newLabel))
+					.find("li:first")
+					.fadeIn("slow").click(configureLabel);
+					
+					$("#MyMarckersList")
+					.html(
+						"<div class='my-labels'>" +
+							"<img src='../prototype/modules/mail/img/tag.png'/>" +
+							"<a class='title-my-labels' tabindex='0' role='button' aria-expanded='false' title='Meus marcadores'>Meus marcadores</a>" +
+							
+							"<span class='status-list-labels ui-icon ui-icon-triangle-1-s'></span>" +
+						"</div>"
+					)
+					
+					.append(DataLayer.render("../prototype/modules/mail/templates/label_list.ejs", {labels:DataLayer.get('label', true)} ))
+					.find("li.label-item").css({"background-color":"#ffffff", "border-color":"#CCCCCC", "color":"#444444"})
+					.find(".square-color").css("display","").click(function(){
+						$(this).parent(".label-item").each(function(){
+							configureLabels({selectedItem: $(this).attr('class').match(/label-item-([\d]+[()a-zA-Z]*)/)[1]});
+						});
+					});
+					$("#MyMarckersList a.title-my-labels").click(function() {
+						$("#MyMarckersList ul.label-list").toggleClass("hidden")
+						$('#MyMarckersList .status-list-labels').toggleClass("ui-icon-triangle-1-s");
+						$('#MyMarckersList .status-list-labels').toggleClass("ui-icon-triangle-1-n");
+					 });
+	 
+					$(".label-list-container .label-list li").not(".empty-item").click(function(){
+						$(".label-list-container .label-list li").find("img").remove();
+						$(".label-list-container .label-list li.label-item").removeClass("selected");
+						$(this).prepend("<img src='../prototype/modules/mail/img/triangle.png' style='margin: 0 5px 0 -5px;'>");
+						$(this).addClass("selected");
+					});
+					
+					$(".label-list-container .label-list li").find('.button').button()
+					.filter('.edit').button({icons:{primary:'ui-icon-pencil'}, text:false}).end()
+					.filter('.close').button({icons:{primary:'ui-icon-close'}, text:false});
+					$.Watermark.ShowAll();
+					winElement.find(".insert-label").val("");
+					
+					//posiciona para edição o label inserido			
+					winElement.find("ul.label-list li:first").trigger("click");			
+					winElement.find(".buttons .save-label .ui-button-text").text('Salvar');
+					$(".delete-label").button("enable");
+					
+					winElement.find('.edit').unbind("click").click(editLabel);
+				
+					winElement.find('.close').click(function(event){
+						var id = $(this).parents(".label-item").attr("class").match(/label-item-([\d]+[()a-zA-Z]*)/)[1];
+						confirmDelete(id);
+						event.stopImmediatePropagation();
+					});
+					
+					$(".my-labels").removeClass("hidden");
+				});
+			} else {
+				alert("Mínimo 2 caracteres");
+			}		
+		}		
+		/**
+		* atualiza menu
+		* Remove o menu presente em cada mensagem listada em uma pasta 
+		* e carrega novamente para que os dados sejam atualizados
+		*/
+		$.contextMenu( 'destroy', ".table_box tbody tr");
+		loadMenu();
+		
+		$(".label-list-container .label-list").find(".label-item-"+labelEdited.id).trigger("click");
+	});	
+	//desfazer marcador
+	winElement.find(".buttons .undo-label").click(function(event){
+		var edit = winElement.find(".edit-label").val();		
+		$(".label-list-container .label-list li").each(function(){
+			var regex_match_3 = $(this).attr("class").match(/label-item-([\d]+[()a-zA-Z]*)/);
+			if(regex_match_3 && regex_match_3[1] && regex_match_3[1] == edit){
+				$(this).trigger("click");
+			}
+		});
+	});
+	
+	//fechar
+	$(".button-close-window .close-window").click(function(){
+		$(".label-configure-win").dialog("close");
+	});	
+			
+	$(".configure-label-content").find("input[type='text']").focus(function () {
+		$(this).keyup(function(){
+			var value = $(this).val();
+			if(value){
+				$(".save-label").button("enable");	
+			}else{
+				$(".save-label").button("disable");	
+			}
+		});
+
+	});	
+	
+	$(".input-nome").keyup(function () {
+				var value = $(this).val();
+				winElement.find('.preview-label-inner').text(value);
+	}).keyup();
+	
+}
+
+/**
+ * TODO:
+ * * Qunado excluir um marcador deve ser removido das mensagens sem que seja necessario atualizar o Expresso.
+ * * Fazer abrir a configuração do Marcador pela lista do modulo principal apenas quando criado um marcador sem clicar no botão "salvar".
+ */
Index: /trunk/prototype/modules/mail/js/followupflag.js
===================================================================
--- /trunk/prototype/modules/mail/js/followupflag.js	(revision 5533)
+++ /trunk/prototype/modules/mail/js/followupflag.js	(revision 5533)
@@ -0,0 +1,418 @@
+//se  caso não existir nenhuma mensagem concluida para o dia atual, ele não mostra a modal.
+ if($.cookie("fadeAlarm") != (new Date).toString("dd/MM/yyyy")){
+	var alarmInRange = DataLayer.get('followupflagged', {filter: ['AND', ['>', 'alarmDeadline', (new Date()).set({hour:0, minute:0, second:0}).toString('yyyy-MM-dd 00:00:00')], ['<', 'alarmDeadline', (new Date()).set({hour:0, minute:0, second:0}).addHours(24).toString('yyyy-MM-dd 00:00:00')]], criteria: {deepness: 1}});
+	if(alarmInRange.length > 0){
+		for(var i=0; i<alarmInRange.length; i++){
+			var date = Date.parseExact(alarmInRange[i].alarmDeadline, 'yyyy-MM-dd hh:mm:ss');
+			alarmInRange[i].alarmDeadline = date.toString('hh:mm');
+		}
+		var data = {alarmInRange : alarmInRange};
+		var valueZebra = DataLayer.render("../prototype/modules/mail/templates/followupflag_alarm_list.ejs", data);
+		
+		new $.Zebra_Dialog(valueZebra, {
+		'buttons':  ['Ok'],
+		'modal': false,
+		'position': ['right - 20', 'bottom - 30'],
+		'custom_class': 'zebraClass2',
+		});	
+		
+	$(".ZebraDialog_Body .footerMenos").hide()
+
+		$(".ZebraDialog_Body .footerMais").click(function(){
+			$('.ZebraDialog').css('visibility','hidden');
+			$(this).parents('.ZebraDialog').css("visibility","visible");
+			$(this).parents('.ZebraDialog').animate( { top: '-=300px' } , 280)
+			.find("ul.alert-flags").animate( { height: 375 } , 300);
+			$(".ZebraDialog_Body .footerMais").hide();
+			$(".ZebraDialog_Body .footerMenos").show();
+		});
+		$(".ZebraDialog_Body .footermenos").click(function(){
+			$('.ZebraDialog').css('visibility','visible');
+			$(this).parents('.ZebraDialog').animate( { top: '+=300px' } , 280)
+			.find("ul.alert-flags").animate( { height: 70 } , 300);
+			
+			$(this).parents('.ZebraDialog').css({
+			});
+			$(".ZebraDialog_Body .footerMenos").hide();
+			$(".ZebraDialog_Body .footerMais").show();
+		});
+		
+		
+		$("ul.alert-flags li").css({
+			'width': '270px',
+			'white-space': 'nowrap',
+			'overflow': 'hidden',
+			'text-overflow': 'ellipsis'
+		});
+		
+		$("span.exc-ocul").css({
+			'float' : 'right',
+			'margin-right' : '0',
+			'color' : '#2363a4',
+			'cursor' : 'pointer'
+		}).parent("ul").css();
+		
+		$(".zebraClass2 .ZebraDialog_Buttons .ZebraDialog_Button0").click(function(){
+			var countCheckbox2 = $("input:checked").length;
+
+			if(countCheckbox2 == 1){
+				date2 = (new Date).toString("dd/MM/yyyy");
+				$.cookie("fadeAlarm", date2 , { expires: 1 });
+			}
+		});
+	}		
+}
+
+if($.cookie("fadeCompleted") != (new Date).toString("dd/MM/yyyy")){	
+	var doneInRange = DataLayer.get('followupflagged', {filter: ['AND', ['>', 'doneDeadline', (new Date()).set({hour:0, minute:0, second:0}).toString('yyyy-MM-dd 00:00:00')], ['<', 'doneDeadline', (new Date()).set({hour:0, minute:0, second:0}).addHours(24).toString('yyyy-MM-dd 00:00:00')]], criteria: {deepness: 1}});
+	if(doneInRange.length > 0){
+		for(var i=0; i<doneInRange.length; i++){
+			var date = Date.parseExact(doneInRange[i].doneDeadline, 'yyyy-MM-dd hh:mm:ss');
+			doneInRange[i].doneDeadline = date.toString('hh:mm');
+		}
+		var data = {doneInRange : doneInRange};
+		var valueZebra = DataLayer.render("../prototype/modules/mail/templates/followupflag_completed_list.ejs", data);
+		
+		//verificando se a primeira "model de alarme" está oculta ou não..
+		//caso ela esteja caira nesse primeiro if, que coloca a model de "concluidos" no lugar da model de alarme.
+		if($(".zebraClass2").length == 0){
+			new $.Zebra_Dialog(valueZebra, {
+				'buttons':  ['Ok'],
+				'modal': false,
+				'position': ['right - 20', 'bottom - 30' ],
+				'custom_class': 'zebraClass',
+				});	 	 
+		}else{
+			new $.Zebra_Dialog(valueZebra, {
+				'buttons':  ['Ok'],
+				'modal': false,
+				'position': ['right - 20', 'bottom - 275' ],
+				'custom_class': 'zebraClass',
+				});	
+		}
+		
+	$(".ZebraDialog_Body .footerMenos2").hide()
+
+		$(".ZebraDialog_Body .footerMais2").click(function(){
+			$('.ZebraDialog').css('visibility','hidden');
+			$(this).parents('.ZebraDialog').css("visibility","visible");
+			if($.cookie("fadeAlarm") != (new Date).toString("dd/MM/yyyy")){
+				$(this).parents('.ZebraDialog').animate( { top: '-=60px' } , 280)
+				.find("ul.alert-flags").animate( { height: 360 } , 300);
+			} else {
+				$(this).parents('.ZebraDialog').animate( { top: '-=300px' } , 280)
+				.find("ul.alert-flags").animate( { height: 360 } , 300);
+			}
+			
+			$(".ZebraDialog_Body .footerMais2").hide();
+			$(".ZebraDialog_Body .footerMenos2").show();
+		});
+		$(".ZebraDialog_Body .footermenos2").click(function(){
+			$('.ZebraDialog').css('visibility','visible');
+			if($.cookie("fadeAlarm") != (new Date).toString("dd/MM/yyyy")){
+				$(this).parents('.ZebraDialog').animate( { top: '+=60px' } , 280)
+				.find("ul.alert-flags").animate( { height: 70 } , 300);
+			} else {
+				$(this).parents('.ZebraDialog').animate( { top: '+=300px' } , 280)
+				.find("ul.alert-flags").animate( { height: 70 } , 300);
+			}
+			$(this).parents('.ZebraDialog').css({
+			});
+			$(".ZebraDialog_Body .footerMenos2").hide();
+			$(".ZebraDialog_Body .footerMais2").show();
+		});
+		
+		
+		$("ul.alert-flags li").css({
+			'width': '270px',
+			'white-space': 'nowrap',
+			'overflow': 'hidden',
+			'text-overflow': 'ellipsis'
+		});
+		
+		$("span.exc-ocul").css({
+			'float' : 'right',
+			'margin-right' : '0',
+			'color' : '#2363a4',
+			'cursor' : 'pointer'
+		}).parent("ul").css();
+		
+		$(".zebraClass .ZebraDialog_Buttons .ZebraDialog_Button0").click(function(){
+		
+			var countCheckbox1 = $("input:checked").length;
+
+			if(countCheckbox1 == 1){
+				date1 = (new Date).toString("dd/MM/yyyy");
+				$.cookie("fadeCompleted", date1 , { expires: 1 });
+			}
+		});
+	}		
+}
+function init_followup(data){
+
+	winElement = data.window;
+	selectedMessageIds = data.selectedMessages;
+	folder = current_folder;
+
+	/**
+	 * Implementação do widget de input-combobox
+	 */
+	(function( $ ) {
+		$.widget( "ui.combobox", {
+			_create: function() {
+				var self = this,
+					select = this.element.hide(),
+					selected = select.children( ":selected" ),
+					value = selected.val() ? selected.text() : "";
+				var input = this.input = $( "<input>" )
+					.insertAfter( select )
+					.val( value )
+					.autocomplete({
+						delay: 0,
+						minLength: 0,
+						source: function( request, response ) {
+							var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
+							response( select.children( "option" ).map(function() {
+								var text = $( this ).text();
+								if ( this.value && ( !request.term || matcher.test(text) ) )
+									return {
+										label: text.replace(
+											new RegExp(
+												"(?![^&;]+;)(?!<[^<>]*)(" +
+												$.ui.autocomplete.escapeRegex(request.term) +
+												")(?![^<>]*>)(?![^&;]+;)", "gi"
+											), "<strong>$1</strong>" ),
+										value: text,
+										option: this
+									};
+							}) );
+						},
+						select: function( event, ui ) {
+							ui.item.option.selected = true;
+							self._trigger( "selected", event, {
+								item: ui.item.option
+							});
+						},
+						change: function( event, ui ) {
+							if ( !ui.item ) {
+								var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ),
+									valid = false;
+								select.children( "option" ).each(function() {
+									if ( $( this ).text().match( matcher ) ) {
+										this.selected = valid = true;
+										return false;
+									}
+								});
+								if ( !valid ) {
+									// remove invalid value, as it didn't match anything
+									$( this ).val( "" );
+									select.val( "" );
+									input.data( "autocomplete" ).term = "";
+									return false;
+								}
+							}
+						}
+					})
+					.addClass( "ui-widget ui-widget-content ui-corner-left" );
+
+				input.data( "autocomplete" )._renderItem = function( ul, item ) {
+					return $( "<li></li>" )
+						.data( "item.autocomplete", item )
+						.append( "<a>" + item.label + "</a>" )
+						.appendTo( ul );
+				};
+
+				this.button = $( "<button type='button'>&nbsp;</button>" )
+					.attr( "tabIndex", -1 )
+					.attr( "title", "Show All Items" )
+					.insertAfter( input )
+					.button({
+						icons: {
+							primary: "ui-icon-triangle-1-s"
+						},
+						text: false
+					})
+					.removeClass( "ui-corner-all" )
+					.addClass( "ui-corner-right ui-button-icon" )
+					.click(function() {
+						// close if already visible
+						if ( input.autocomplete( "widget" ).is( ":visible" ) ) {
+							input.autocomplete( "close" );
+							return;
+						}
+
+						// work around a bug (likely same cause as #5265)
+						$( this ).blur();
+
+						// pass empty string as value to search for, displaying all results
+						input.autocomplete( "search", "" );
+						input.focus();
+					});
+			},
+
+			destroy: function() {
+				this.input.remove();
+				this.button.remove();
+				this.element.show();
+				$.Widget.prototype.destroy.call( this );
+			}
+		});
+	})( jQuery );
+	/**
+	 * #END: Implementação do widget de input-combobox
+	 */
+
+	winElement.find('.button').button()
+	.filter('.menu-configure-followupflag .cancel').click(function(){
+		winElement.dialog("close");
+	}).end()
+	
+	.filter('.menu-configure-followupflag .save').click(function(){	
+				
+		var backgroundColor = winElement.find('[name="backgroundColor"]').val();
+		var followupflagId  = winElement.find('[name="name"] option:selected').val();
+		var isDone = winElement.find('[name="done"]').is(':checked') ? 1 : 0;
+		var alarmDate = false;
+		var doneDate  = false;
+		
+		for (var i=0; i < selectedMessageIds.length; i++ ){
+			var messageNumber   = selectedMessageIds[i];
+			//var followupflag = DataLayer.get('followupflag', followupflagId.toString()),
+			var followupflagged = {
+				uid : User.me.id,
+				followupflagId : followupflagId, 
+				folderName : current_folder, 
+				messageNumber : messageNumber, 
+				//alarmDeadline : winElement.find('[name="alarmDate"]').datepicker("getDate"), 
+				//doneDeadline: winElement.find('[name="doneDate"]').datepicker("getDate"),
+				isDone: isDone,
+				backgroundColor : backgroundColor
+			}
+			
+			if (alarmDate = winElement.find('[name="alarmDate"]').datepicker("getDate")) {
+				if (alarmTime = winElement.find('[name="alarmTime"]').datepicker("getDate")) {
+					alarmDate.set({hour:alarmTime.getHours(), minute:alarmTime.getMinutes()});
+				}
+				followupflagged.alarmDeadline = alarmDate.toString('yyyy-MM-dd hh:mm:ss');
+			}
+
+			if (doneDate = winElement.find('[name="doneDate"]').datepicker("getDate")) {
+				if (doneTime = winElement.find('[name="doneTime"]').datepicker("getDate")) {
+					doneDate.set({hour:doneTime.getHours(), minute:doneTime.getMinutes()});
+				}
+				followupflagged.doneDeadline = doneDate.toString('yyyy-MM-dd hh:mm:ss');
+			}
+			
+			if(isDone){
+				$('#td_message_followup_' + messageNumber + ', ' + 
+				'#td_message_followup_search_' + messageNumber).find(".flag-edited")
+				.find("img").attr("src", "../prototype/modules/mail/img/flagChecked.png")
+				.css("margin-left","-3px");
+			}
+			
+			$('#td_message_followup_' + messageNumber + ', ' + 
+			  '#td_message_followup_search_' + messageNumber).find(".flag-edited").css("background", backgroundColor);
+			  
+			DataLayer.put('followupflagged', followupflagged);
+		}
+		DataLayer.commit();
+		
+		//onceOpenedHeadersMessages[current_folder][followupflagged.messageNumber]['followupflagged']['followupflag'] = {};
+		var extend = DataLayer.get('followupflagged', {
+		filter: ['AND', ['IN', 'messageNumber', selectedMessageIds], ['=', 'folderName', current_folder]],criteria: {deepness: 1}});
+		if(extend != "" || extend != 'undefined' || extend != []){
+			for(var ex = 0; ex < extend.length; ex++){
+				onceOpenedHeadersMessages[current_folder][extend[ex].messageNumber]['followupflagged'] = {};
+				DataLayer.merge(onceOpenedHeadersMessages[current_folder][extend[ex].messageNumber]['followupflagged'], extend[ex]);
+			}
+		} else {
+			alert('erro ao salvar');
+		}
+	}).end()
+	
+	.filter('.menu-configure-followupflag .delete').click(function(){
+		for(i = 0; i < selectedMessageIds.length; i++){
+			var messageNumber   = selectedMessageIds[i];
+			var flag_id = onceOpenedHeadersMessages[current_folder][messageNumber]['followupflagged'].id;
+			DataLayer.remove('followupflagged', flag_id);
+			$('#td_message_followup_' + messageNumber + ', ' + 
+			  '#td_message_followup_search_' + messageNumber).find(".flag-edited").css("background", '#CCC');
+			$('#td_message_followup_' + messageNumber + ', ' + 
+				'#td_message_followup_search_' + messageNumber).find(".flag-edited")
+				.find("img").attr("src", "../prototype/modules/mail/img/flagEditor.png").css("margin-left","0");;
+		}
+		DataLayer.commit();
+		winElement.dialog("close");
+	});
+
+	winElement.find('.date').datepicker();
+	winElement.find('.time').timepicker({});
+	winElement.find('[name="name"]').combobox();
+	
+	
+	winElement.find('[name="alarmDate"],[name="alarmTime"]').attr("disabled","disabled");
+	winElement.find('[name="alarm"]').click(function(){
+		if($(this).is(":checked")){
+			winElement.find('[name="alarmDate"],[name="alarmTime"]').removeAttr("disabled");			
+		}else{
+			winElement.find('[name="alarmDate"],[name="alarmTime"]').attr("disabled","disabled");
+		}
+	});	
+	winElement.find('[name="done"]').click(function(){
+		if($(this).is(":checked")){
+			winElement.find(".input-done input").attr("disabled","disabled");
+		}else{
+			winElement.find(".input-done input").removeAttr("disabled");
+		}
+	});
+
+
+	winElement.find(".followupflag-color-fields").hide();
+	winElement.find(".followupflag-color.sample-list .sample-item").click(function(){
+		winElement.find(".followupflag-color.sample-list .sample-item").removeClass("selected");
+		$(this).addClass("selected");
+		var color = $(this).attr('alt');
+		winElement.find('[name="backgroundColor"]').css('background-color', color).val(color)
+	});
+	
+	winElement.find(".followupflag-color.sample-list .sample-item.selected").trigger('click');
+				
+	winElement.find('[name="setColor"]').change(function(){		
+		if(winElement.find('[name="setColor"]').val() == "default"){
+			winElement.find(".followupflag-color.sample-list").show("fast");
+			winElement.find(".followupflag-color-fields").hide();
+			winElement.find(".followupflag-color.sample-list .sample-item.selected").trigger('click');
+		} else if(winElement.find('[name="setColor"]').val() == "custom"){
+			winElement.find(".followupflag-color-fields").show("fast");
+			winElement.find(".followupflag-color.sample-list").hide();
+			winElement.find(".colorwell").focus();
+		}		
+	});
+	
+	if(winElement.find("#selectCor option:selected").val() == "custom"){
+		winElement.find("#selectCor").trigger("change");
+	}
+
+	var colorpickerPreviewChange = function(color) {
+		winElement.find('.colorwell-selected').val(color).css('background-color', color);
+		winElement.find('.flag-color-preview').css('background',color);
+	} 
+
+	var f = $.farbtastic(winElement.find('.colorpicker'), colorpickerPreviewChange);
+	var selected;					
+	winElement.find('.colorwell').each(function () {
+		f.linkTo(this);
+	}).focus(function() {
+		if (selected) {
+			$(selected).removeClass('colorwell-selected');
+		}
+		$(selected = this).addClass('colorwell-selected');
+		f.linkTo(this, colorpickerPreviewChange);
+		f.linkTo(colorpickerPreviewChange);
+		
+	});
+	if(winElement.find("#selectCor option:selected").val() == "custom"){
+		winElement.find(".colorwell").focus();
+	}
+
+}
Index: /trunk/prototype/modules/mail/templates/label_configure.ejs
===================================================================
--- /trunk/prototype/modules/mail/templates/label_configure.ejs	(revision 5533)
+++ /trunk/prototype/modules/mail/templates/label_configure.ejs	(revision 5533)
@@ -0,0 +1,55 @@
+<link rel="stylesheet" href="../prototype/modules/mail/css/label.css" type="text/css" />	
+<link rel="stylesheet" href='../prototype/plugins/farbtastic/farbtastic.css' type="text/css" >
+
+<div class="acc-list list-label-content">
+	<h3>Meus marcadores</h3>
+		<div class="attendee-list-add">
+			<fieldset class="add-attendee-search search-field ui-corner-all">
+					<span class="ui-icon ui-icon-plus add-label-button"></span>
+					<input class="insert-label" type="text" value="Adicionar Marcador" maxlength="15" >
+			</fieldset>
+		</div>
+		<div class="label-list-container"></div>
+</div>
+<div class="configure-label-content">
+	<fieldset>
+	<legend>Básico</legend>
+		Nome do marcador: <input type="text" class="input-nome" value="" name="marcador">
+		<input type="hidden" class="edit-label" value="" name="marcador">
+	</fieldset>
+	  <fieldset class="lebals-colorpicker">
+	  <legend>Cor do marcador</legend>
+		<div class="label-conf">
+			<select class="color-suggestions">		
+				  <option value="0">Padrão</option>		
+				  <option value="1">Coala</option>		
+				  <option value="2">Tomate</option>		
+				  <option value="3">Limão</option>		
+				  <option value="4">Alto contraste</option>		
+				  <option value="custom" selected="selected">Personalizada</option>
+			</select>
+			<div class="form-item">
+			  <label for="backgroundColor" class="label-cor">Cor do marcador:</label>
+			  <input type="text" name="backgroundColor" id="background" class="colorwell" value="#ffffff" />
+			</div>
+			<div class="form-item">
+			  <label for="fontColor" class="label-cor">Cor do texto:</label>
+			  <input type="text" name="fontColor" class="colorwell" value="#444444" />
+			</div>
+			<div class="form-item">
+			  <label for="borderColor" class="label-cor">Cor da borda:</label>
+			  <input type="text" name="borderColor" class="colorwell" value="#ccccccc" />
+			</div>			  
+			<div class="preview-label-outer">
+			  <span class="preview-label-inner"></span>
+			</div>
+		</div>				
+		<div class="colorpicker"></div>				  
+	  </fieldset>
+	<div class="buttons">
+		<span class="button delete-label">Excluir</span><span class="button undo-label">Desfazer</span><span class="button save-label">Salvar</span>
+	</div>
+</div>
+<div class="button-close-window">
+	<span class="button close-window">Fechar</span>
+</div>
Index: /trunk/prototype/modules/mail/templates/followupflag_configure.ejs
===================================================================
--- /trunk/prototype/modules/mail/templates/followupflag_configure.ejs	(revision 5533)
+++ /trunk/prototype/modules/mail/templates/followupflag_configure.ejs	(revision 5533)
@@ -0,0 +1,121 @@
+
+<%
+	if (data.messages.length == 1) {
+		var followupflagged = data.messages[0].followupflagged ? data.messages[0].followupflagged : followupflagged = { followupflag: {} };
+		if (followupflagged.doneDeadline)
+			followupflagged.doneDeadline = Date.parseExact(followupflagged.doneDeadline, 'yyyy-MM-dd hh:mm:ss');
+		if (followupflagged.alarmDeadline)
+			followupflagged.alarmDeadline = Date.parseExact(followupflagged.alarmDeadline, 'yyyy-MM-dd hh:mm:ss');
+			
+	} else if (data.messages.length > 1) {
+		var followupflagged = {
+			followupflag: {name: true},
+			isDone: true,
+			doneDeadline: true,
+			alarmDeadline: true,
+			backgroundColor: true
+		}
+		/**
+		 * O campo só fica preenchido se o valor for igual para todas as mensagens
+		 */
+		for (var i=1; i<data.messages.length; i++) {
+			if (!data.messages[i].followupflagged) {
+				followupflagged = { followupflag: {} };
+				break;
+			}
+			followupflagged.followupflag.name = (followupflagged.followupflag.name && data.messages[i].followupflagged.followupflag.name == data.messages[i-1].followupflagged.followupflag.name) ?
+				data.messages[i].followupflagged.followupflag.name : false;
+				
+			followupflagged.isDone = (followupflagged.isDone && data.messages[i].followupflagged.followupflag.isDone == data.messages[i-1].followupflagged.followupflag.isDone) ?
+				data.messages[i].followupflagged.followupflag.isDone : false;
+				
+			followupflagged.doneDeadline = (followupflagged.doneDeadline && data.messages[i].followupflagged.followupflag.doneDeadline == data.messages[i-1].followupflagged.followupflag.doneDeadline) ?
+				Date.parseExact(data.messages[i].followupflagged.followupflag.doneDeadline, 'yyyy-MM-dd hh:mm:ss') : false;
+				
+			followupflagged.alarmDeadline = (followupflagged.alarmDeadline && data.messages[i].followupflagged.followupflag.alarmDeadline == data.messages[i-1].followupflagged.followupflag.alarmDeadline) ?
+				Date.parseExact(data.messages[i].followupflagged.followupflag.alarmDeadline, 'yyyy-MM-dd hh:mm:ss') : false;
+				
+			followupflagged.backgroundColor = (followupflagged.backgroundColor && data.messages[i].followupflagged.followupflag.backgroundColor == data.messages[i-1].followupflagged.followupflag.backgroundColor) ?
+				data.messages[i].followupflagged.followupflag.backgroundColor : false;
+		}
+	}
+//typeFlag = DataLayer.get("followupflag", id = data.messages[0].followupflagged.followupflagId ).name;
+//followupflagged.followupflag.name
+%>
+<div class="followupflag-container">
+	<fieldset class="basic-fields">
+		<legend>Básico</legend>
+		<div class="followupflag-configure">
+			<label class="label-name">Sinalizar como:</label> 
+			<select name="name">
+				<% for(var i=0; i<data.followupflags.length; i++) {  %>
+					
+					<% var selected = (data.followupflags[i].name == followupflagged.followupflag.name ) ? 'selected="selected"' : '' %> 
+					<option value="<%= data.followupflags[i].id %>" <%= selected %>><%= data.followupflags[i].name %></option>
+				<% } %>
+			</select>
+			<div class="alarm-fields">
+				<input type="checkbox" name="alarm" <%=(followupflagged.alarmDeadline) ? 'checked="checked"' : '' %> /><label>Alarme: </label>
+				<input type="text" name="alarmDate" class="date" size="9" value="<%=(followupflagged.alarmDeadline) ? followupflagged.alarmDeadline.toString('dd/MM/yyyy') : '' %>" /> ás 
+				<input type="text" name="alarmTime" class="time" size="8" value="<%=(followupflagged.alarmDeadline) ? followupflagged.alarmDeadline.toString('hh:mm') : '' %>" />
+			</div>		
+		   <div class="completed-followup">
+				<input type="checkbox" name="done" <%=(followupflagged.isDone && followupflagged.isDone != '0') ? 'checked="checked"' : '' %> /><label>Concluido</label>
+		   </div>		
+		</div>
+		<div class="right-data input-done">
+			<label>Conclusão:</label>
+			<input <%=(followupflagged.isDone && followupflagged.isDone != '0') ? 'disabled="disabled"' : '' %> type="text" name="doneDate" class="date" size="8" value="<%=(followupflagged.doneDeadline) ? followupflagged.doneDeadline.toString('dd/MM/yyyy') : '' %>" /> ás 
+			<input <%=(followupflagged.isDone && followupflagged.isDone != '0') ? 'disabled="disabled"' : '' %> type="text" name="doneTime" class="time" size="8" value="<%=(followupflagged.doneDeadline) ? followupflagged.doneDeadline.toString('hh:mm') : '' %>" />
+		</div> 
+	</fieldset>
+
+	<fieldset class="followups-colorpicker color-fields">
+		<legend>Cor do sinalizador</legend>
+		<div class="left-seletor-flag">
+			<% 
+				var defaultColor = false;
+				var a = ["#00820F", "#E4D000", "#004DD6", "#FF2016", "#F96300"];
+				if (followupflagged.backgroundColor) {
+					for(var i = 0; i < a.length; i++) {
+						if(a[i] == followupflagged.backgroundColor) {
+							defaultColor = a[i];
+							break;
+						}
+					}
+				}
+			%>
+			<select id="selectCor" name="setColor">
+				<option value="default" <%= (defaultColor) ? 'selected="selected"' : ''%> >Padrão</option>
+				<option value="custom" <%= (!defaultColor) ? 'selected="selected"' : ''%> >Personalizado</option>
+			</select>
+		</div>
+		<div class="followupflag-color sample-list">
+			<img src="../prototype/modules/mail/img/flagDefault1.png" alt="#00820F" class="sample-item <%= (!followupflagged.backgroundColor || followupflagged.backgroundColor == '#00820F') ? 'selected' : '' %>"">
+			<img src="../prototype/modules/mail/img/flagDefault2.png" alt="#E4D000" class="sample-item <%= (followupflagged.backgroundColor == '#E4D000') ? 'selected' : '' %>"">
+			<img src="../prototype/modules/mail/img/flagDefault3.png" alt="#004DD6" class="sample-item <%= (followupflagged.backgroundColor == '#004DD6') ? 'selected' : '' %>"">
+			<img src="../prototype/modules/mail/img/flagDefault4.png" alt="#FF2016" class="sample-item <%= (followupflagged.backgroundColor == '#FF2016') ? 'selected' : '' %>"">
+			<img src="../prototype/modules/mail/img/flagDefault5.png" alt="#F96300" class="sample-item <%= (followupflagged.backgroundColor == '#F96300') ? 'selected' : '' %>"">
+		</div>
+		<div class="followupflag-color-fields">
+			<div class="form-item">
+				<label class="flag-label">Cor: </label>
+				<input type="text" name="backgroundColor" class="colorwell background-color" value="<%=(followupflagged.backgroundColor) ? followupflagged.backgroundColor : '#00820F' %>"/>
+				<div class="flag-edit flag-color-preview" style="background: <%=(followupflagged.backgroundColor) ? followupflagged.backgroundColor : '#00820F' %>">
+					<img src="../prototype/modules/mail/img/flagEditor.png">
+				</div>
+			</div>
+			<div class="colorpicker"></div>
+		</div>
+	</fieldset>
+	<div class="menu-container footer-container menu-configure-followupflag">
+		<span class="button delete">Remover</span>
+		<span class="button save">Aplicar</span>
+		<span class="button cancel">Cancelar</span>
+	</div>
+</div> 
+
+<!--
+	TODO
+	** Vai ter que ser arrumado a parte de buscar o tipo do sinalizador atual.
+-->
Index: /trunk/prototype/modules/mail/templates/detailedfoldertree.ejs
===================================================================
--- /trunk/prototype/modules/mail/templates/detailedfoldertree.ejs	(revision 5500)
+++ /trunk/prototype/modules/mail/templates/detailedfoldertree.ejs	(revision 5533)
@@ -52,3 +52,5 @@
   </li>
   <%}%>
+  <li><span class="folder head_folder all_accomp">Para acompanhamento</span>
+  </li>
 </ul>
Index: /trunk/prototype/modules/mail/templates/followupflag_alarm_list.ejs
===================================================================
--- /trunk/prototype/modules/mail/templates/followupflag_alarm_list.ejs	(revision 5533)
+++ /trunk/prototype/modules/mail/templates/followupflag_alarm_list.ejs	(revision 5533)
@@ -0,0 +1,17 @@
+<p class="title"><strong>Você tem <%= data.alarmInRange.length %> <%= (data.alarmInRange.length == 1) ? 'mensagem sinalizada para hoje.' : 'mensagens sinalizadas para hoje.'%> </p></strong>
+					<ul class="alert-flags" style="overflow: hidden; height: 70px;">
+	
+<%
+for(var i=0; i<data.alarmInRange.length; i++){
+%>
+
+	<li><a onclick="cExecute('$this.imap_functions.get_info_msg&msg_number=<%=data.alarmInRange[i].messageNumber %>&msg_folder=<%= data.alarmInRange[i].folderName %>', show_msg);"><%= data.alarmInRange[i].alarmDeadline %> - <%= data.alarmInRange[i].followupflag.name %> - <%= data.alarmInRange[i].message.headers.subject %></a></li>
+<%
+}
+%>
+					</ul> 
+					
+<br>
+<a class="footerMais">ver mais</a><a class="footerMenos">ver menos</a>
+<br><br>
+	<input type="checkbox" name="fadeModel2"> Não mostrar essa janela por hoje.
Index: /trunk/prototype/modules/mail/templates/label_listitem.ejs
===================================================================
--- /trunk/prototype/modules/mail/templates/label_listitem.ejs	(revision 5533)
+++ /trunk/prototype/modules/mail/templates/label_listitem.ejs	(revision 5533)
@@ -0,0 +1,11 @@
+	<li class="label-item label-item-<%= data.id%>" style="background: <%= (data.bgColor) ? data.bgColor : '#ffffff' %>; 
+		color: <%= (data.fontColor) ? data.fontColor : '#444444' %>;
+		border: 1px solid <%= (data.borderColor) ? data.borderColor : '#cccccc' %>;">		
+		
+		<input type="hidden" value="<%= data.id%>" name="labelItemId" class="id-item-list" />
+		<span class="text-list"><%= data.name %></span>
+		<div class="button close tiny" style="float: right"></div>
+		<div class="button edit tiny" style="float: right"></div>
+					
+	</li>
+	
Index: /trunk/prototype/modules/mail/templates/label_list.ejs
===================================================================
--- /trunk/prototype/modules/mail/templates/label_list.ejs	(revision 5533)
+++ /trunk/prototype/modules/mail/templates/label_list.ejs	(revision 5533)
@@ -0,0 +1,21 @@
+	<ul class="label-list">
+		<%for (var i=0; i<data.labels.length; i++){ %>
+			
+			<li class="label-item label-item-<%= (data.labels[i].id) ? data.labels[i].id : ''%>" style="
+				background: <%= (data.labels[i].backgroundColor) ? data.labels[i].backgroundColor : '#ffffff' %>;
+				color: <%= (data.labels[i].fontColor) ? data.labels[i].fontColor : '#000000' %>;
+				border-color: <%= (data.labels[i].borderColor) ? data.labels[i].borderColor : '#CCCCCC' %>;">
+			   
+				<span class="text-list"><%= (data.labels[i].name) ? data.labels[i].name : '' %></span>
+				<!--<input type="hidden" value="<%= (data.labels[i].id) ? data.labels[i].id : ''%>" name="labelItemId" class="id-item-list" />-->
+				<input type="hidden" value="<%= data.labels[i].id%>" name="labelItemId" class="id-item-list" />
+				
+				<div class="square-color" style="display:none;width:17px;height:12px;margin-top:1px;-moz-border-radius:3px;-webkit-border-radius:3px;
+						background: <%= (data.labels[i].backgroundColor) ? data.labels[i].backgroundColor : '#ffffff' %>; float:right;"></div>
+
+				<div class="button close tiny" style="float: right"></div>
+				<div class="button edit tiny" style="float: right"></div>
+			</li>
+		<%}%>
+	</ul>
+
Index: /trunk/prototype/modules/attach_message/attach_message.js
===================================================================
--- /trunk/prototype/modules/attach_message/attach_message.js	(revision 5399)
+++ /trunk/prototype/modules/attach_message/attach_message.js	(revision 5533)
@@ -319,5 +319,5 @@
 			datatype: "json",
 			mtype: 'GET',
-			colNames:['#', ' ', 'De', 'Assunto', 'Data', 'Tamanho'],
+			colNames:['#',' ', 'De', 'Assunto', 'Data', 'Tamanho'],
 			colModel:[
 				{name:'msg_number',index:'msg_number', width:45, hidden:true, sortable:false},
Index: /trunk/expressoMail1_2/index.php
===================================================================
--- /trunk/expressoMail1_2/index.php	(revision 5530)
+++ /trunk/expressoMail1_2/index.php	(revision 5533)
@@ -44,4 +44,5 @@
 					<script src="../prototype/plugins/ejs/ejs.js" language="javascript"></script>
 					<script src="../prototype/plugins/store/jquery.store.js" language="javascript"></script>
+					<script src="../prototype/plugins/farbtastic/farbtastic.js" language="javascript"></script>
 					<script src="../prototype/api/datalayer.js" language="javascript"></script>					
 					<script type="text/javascript" src="../prototype/plugins/scrollto/jquery.scrollTo.js"></script>
@@ -57,4 +58,5 @@
 					<link rel="stylesheet" type="text/css" href="../prototype/plugins/zebradialog/css/zebra_dialog.css"></link>
 					<link rel="stylesheet" type="text/css" href="../prototype/plugins/fileupload/jquery.fileupload-ui.css"></link>
+					<link rel="stylesheet" href="../prototype/plugins/farbtastic/farbtastic.css" type="text/css" >
 					<script type="text/javascript" src="../prototype/plugins/zebradialog/javascript/zebra_dialog.js"></script>
 					<script type="text/javascript" src="../prototype/plugins/datejs/date-pt-BR.js"></script>
@@ -115,8 +117,17 @@
 	<script src="../prototype/plugins/countdown/jquery.countdown.min.js" type="text/javascript"></script>
 	<script src="../prototype/plugins/countdown/jquery.countdown-pt-BR.js" type="text/javascript"></script>		
+	
+		
 	';
 	
+	echo '<script src="../prototype/modules/mail/js/label.js" type="text/javascript"></script>';	
+	echo '<script src="../prototype/modules/mail/js/followupflag.js" type="text/javascript"></script>';
+	
+		
+	//followupflags
+	echo'<link rel="stylesheet" href="../prototype/modules/mail/css/followupflag.css" type="text/css" />';
+	
 	/*
-	 * TODO: implementar o controle como preferÃªncia do usuÃ¡rio 
+	 * TODO: implementar o controle como preferência do usuário 
 	 *
 	 */
@@ -348,4 +359,8 @@
 	echo '
 	<link rel="stylesheet" href="../prototype/modules/attach_message/attach_message.css" type="text/css" />
+	
+					<script type="text/javascript" src="../prototype/plugins/jquery/i18n/jquery.ui.datepicker-pt-BR.js"></script>
+					<script type="text/javascript" src="../prototype/plugins/timepicker/jquery-ui-timepicker-addon.js"></script>
+					<script type="text/javascript" src="../prototype/plugins/timepicker/localization/jquery-ui-timepicker-pt-BR.js"></script>
 	<script type="text/javascript">
 		init();
@@ -373,4 +388,5 @@
 <body scroll="no" style="overflow:hidden">
 <link rel="stylesheet" href="../prototype/modules/attach_message/attach_message.css" type="text/css" />
+<link rel="stylesheet" href="../prototype/modules/mail/css/label.css" type="text/css" />	
 <link rel='stylesheet' type='text/css' href='../prototype/modules/calendar/css/layout.css' />
 <link rel='stylesheet' type='text/css' href='../prototype/modules/calendar/css/style.css' />
Index: /trunk/expressoMail1_2/templates/default/expressomail.css
===================================================================
--- /trunk/expressoMail1_2/templates/default/expressomail.css	(revision 5523)
+++ /trunk/expressoMail1_2/templates/default/expressomail.css	(revision 5533)
@@ -119,7 +119,4 @@
 }
 
-
-
-
 .context-menu-item.icon-important { background-image: url(images/important.gif); background-position: 6px 5px !important}
 .context-menu-item.icon-export { background-image: url(images/export.png); }
@@ -131,5 +128,4 @@
 
 
-
 .context-menu-item.icon-search-mail { background-image: url(images/menu/search.png); }
 .context-menu-item.icon-filter { background-image: url(images/menu/filters.png); }
@@ -137,5 +133,5 @@
 .context-menu-item.icon-share-mailbox { background-image: url(images/menu/usersfolders.png); }
 .context-menu-item.icon-label { background-image: url(images/menu/usersfolders.png); }
+.context-menu-item.icon-tag { background-image: url(images/menu/tag.png); margin: 3px; }
 .context-menu-item.icon-empty-trash { background-image: url(images/menu/trash.png); }
 .context-menu-item.icon-queue { background-image: url(images/menu/queue.png); }
-
Index: /trunk/expressoMail1_2/templates/default/index.tpl
===================================================================
--- /trunk/expressoMail1_2/templates/default/index.tpl	(revision 5525)
+++ /trunk/expressoMail1_2/templates/default/index.tpl	(revision 5533)
@@ -207,3 +207,5 @@
 <div id="sandbox" class="expresso-calendar-container hidden">
 </div>
+<div id="windowLabels" class="label-configure-win"></div>
+<div id="followupFlag" class="followupflag-configure-win hidden"></div>
 <!-- END list -->
Index: /trunk/expressoMail1_2/inc/class.imap_functions.inc.php
===================================================================
--- /trunk/expressoMail1_2/inc/class.imap_functions.inc.php	(revision 5520)
+++ /trunk/expressoMail1_2/inc/class.imap_functions.inc.php	(revision 5533)
@@ -157,5 +157,5 @@
 
 	function get_range_msgs2($params)
-	{ 
+	{ 	
             // Free others requests
             session_write_close();
@@ -193,5 +193,5 @@
                                     $sample = true;
                                             
-                                    $return[$i] = $this->get_info_head_msg( $msg_number , $sample ) ;
+                                    $return[$i] = $this->get_info_head_msg( $msg_number , $sample );
                                     $i++;
                             }
@@ -228,5 +228,43 @@
                 return $return;
     }
-    
+	
+	
+	function getMessages($params) {
+		$result = array();
+
+		$exporteml = new ExportEml();
+		$unseen_msgs = array();
+		
+		foreach($params['messages'] as $folder => $messages) {
+			foreach($messages as $msg_number) {
+
+				$this->mbox = $this->open_mbox($folder);
+			
+				if (isset($params['details']) && $params['details'] == 'all') {
+					$message = $this->get_info_msg(array('msg_number' => $msg_number, 'msg_folder' =>urlencode($folder)));
+				} else {
+					$message['headers'] = $this->get_info_head_msg($msg_number, true);
+					//$message['attachments'] = $exporteml->get_attachments_in_array(array("num_msg" => $msg_number));
+				}
+
+				imap_close($this->mbox);
+				$this->mbox = false;
+
+				if($msg_info['Unseen'] == "U" || $msg_info['Recent'] == "N") {
+					array_push($unseen_msgs,$msg_number);
+				}
+				
+				$result[$folder][] = $message;
+			}
+			if($unseen_msgs){
+				$msgs_list = implode(",",$unseen_msgs);
+				$array_msgs = array('folder' => $folder, "msgs_to_set" => $msgs_list, "flag" => "unseen");
+				$this->set_messages_flag($array_msgs);
+			}
+		}
+		
+		return $result;
+	}	
+
         /**
         *  Decodifica uma string no formato mime RFC2047
@@ -731,8 +769,9 @@
 			$array_msgs = array('folder' => $new_params["msg_folder"], "msgs_to_set" => $msgs_list, "flag" => "unseen");
 			$this->set_messages_flag($array_msgs);
-		}
+		}					
+					
 		return $return;
 	}
-	}
+}
 
 	/**
@@ -5084,18 +5123,19 @@
 	}
         
-        function parseCriteriaSearchMail($search)
-        {
-            $criteria = '';
-            $searchArray = explode(' ', $search);
-
-            foreach ($searchArray as $v)
-                if(trim($v) !== '' )
-                    $criteria .= 'TEXT "'.$v.'" ' ;
-           
-            return $criteria;
-        }
+	function parseCriteriaSearchMail($search)
+	{
+		$criteria = '';
+		$searchArray = explode(' ', $search);
+
+		foreach ($searchArray as $v)
+			if(trim($v) !== '' )
+				$criteria .= 'TEXT "'.$v.'" ' ;
+	   
+		return $criteria;
+	}
         
 	function quickSearchMail( $params )
 	{
+		include '../prototype/api/controller.php';
 		$return = array();
 		$return['folder'] = $params['folder'];
@@ -5114,6 +5154,10 @@
 		$count = 0;
 		
-                $search = $this->parseCriteriaSearchMail($params['search']);
-		                
+		if (!preg_match('/KEYWORD/i', $params['search'])){
+			$search = $this->parseCriteriaSearchMail($params['search']);
+		} else {
+			$search = $params['search'];
+		}
+	
 		foreach ($params['folder'] as $folder) 
 		{
@@ -5139,5 +5183,26 @@
 					$return['msgs'][$i]['subject'] .= mb_convert_encoding($tmp->text, 'UTF-8', 'UTF-8 , ISO-8859-1');
 				
-				
+				$filter = array('AND', array('=', 'folderName', $folder), array('=','messageNumber', $v));
+				$followupflagged = Controller::find(
+					array('concept' => 'followupflagged'),
+					false, 
+					array('filter' => $filter, 'criteria' => array('deepness' => '2'))
+				);
+				foreach ($followupflagged as $i => $v)
+					{
+						if(isset($v['followupflagId']))
+						{
+							$followupflag = Controller::find( array( 'concept' => 'followupflag' ) , false, array( 'filter' => array('=', 'id'  ,  $v['followupflagId']) ));     
+							$followupflagged[$i]['followupflag'] = $followupflag[0];
+						}
+
+					}
+					
+				$labeleds = Controller::find(
+					array('concept' => 'labeled'),
+					false, 
+					array('filter' => $filter, 'criteria' => array('deepness' => '2'))
+				);
+						
 				$return['msgs'][$i]['flag'] = ' ';
 				$return['msgs'][$i]['flag'] .= $msg->Unseen ? $msg->Unseen : '';
@@ -5154,4 +5219,6 @@
 				$return['msgs'][$i]['boxname'] = $folder;
 				$return['msgs'][$i]['uid'] = $v;
+				$return['msgs'][$i]['followupflagged'] = $followupflagged[0];
+				$return['msgs'][$i]['labels'] = $labeleds;
 				$i++;
 			} 	
Index: /trunk/expressoMail1_2/js/drag_area.js
===================================================================
--- /trunk/expressoMail1_2/js/drag_area.js	(revision 5368)
+++ /trunk/expressoMail1_2/js/drag_area.js	(revision 5533)
@@ -27,5 +27,5 @@
 	
 }
-
+/*
 DragArea.prototype.makeMenuBox = function(element){
 
@@ -52,4 +52,5 @@
 	
 }
+*/
 
 DragArea.prototype.makeDragged = function(element, msg_number, subject, from_list, folder){
@@ -72,5 +73,5 @@
 					changeBgColor(is_ie ? window.event : e, msg_number);
 				}
-				ConstructRightMenu(is_ie ? window.event : e);
+				//ConstructRightMenu(is_ie ? window.event : e);
 			}			
 			return false;
Index: /trunk/expressoMail1_2/js/common_functions.js
===================================================================
--- /trunk/expressoMail1_2/js/common_functions.js	(revision 5497)
+++ /trunk/expressoMail1_2/js/common_functions.js	(revision 5533)
@@ -657,4 +657,72 @@
 	}
 	cExecute ("$this.imap_functions.getacl", handler_imap_getacl);
+}
+
+function configureLabels(data){
+
+	dialogElement = $('.label-configure-win').html(DataLayer.render("../prototype/modules/mail/templates/label_configure.ejs", {}))
+	
+	dialogElement.dialog({
+		width:821,
+		height:410,
+		title:' Configuração do Marcador',
+		resizable:false,
+		modal: true,
+		closeOnEscape:true,
+		close:function(event, ui) {event.stopPropagation();},
+		autoOpen:false,
+		dialogClass: 'dialog-configure-label'
+	});
+	init_label({window:dialogElement, selectedItem:data.selectedItem});	
+	dialogElement.dialog("open");
+}
+
+function configureFollowupflag(){
+
+	var messages = new Array();
+	var selectedMessageIds = new Array();
+	var folder_name;
+	if (currentTab == 0) {
+		selectedMessageIds = get_selected_messages().split(",");
+	} else {
+		selectedMessageIds = get_selected_messages_search().split(",");
+		var id_border = currentTab.replace(/[a-zA-Z_]+/, "");
+	}
+	
+	
+	for (var i=0; i<selectedMessageIds.length; i++) {
+		if (currentTab == 0) {
+			folder_name = current_folder;
+		}else{
+			var tr = Element(selectedMessageIds[i]+'_s'+id_border);
+			folder_name = tr.getAttribute('name');
+		}
+		messages.push(onceOpenedHeadersMessages[folder_name][selectedMessageIds[i]]);
+	}
+
+	if(!User.followupflags)
+		User.followupflags = DataLayer.get('followupflag',true);
+	var data = {
+		followupflags: User.followupflags,
+		messages: messages
+	};
+	dialogElement = $('.followupflag-configure-win').html(DataLayer.render("../prototype/modules/mail/templates/followupflag_configure.ejs", data))
+
+	dialogElement.dialog({
+		width:542,
+		height:420,
+		title:get_lang('Acompanhamento'),
+		resizable:false,
+		modal: true,
+		closeOnEscape:true,
+		close:function(event, ui) {
+			$('.followupflag-configure-win').addClass('hidden');
+			event.stopPropagation();
+		},
+		autoOpen:false
+	});	
+	init_followup({window:dialogElement, selectedMessages:selectedMessageIds});
+	$('.followupflag-configure-win').removeClass('hidden');
+	dialogElement.dialog("open");
 }
 
Index: /trunk/expressoMail1_2/js/main.js
===================================================================
--- /trunk/expressoMail1_2/js/main.js	(revision 5524)
+++ /trunk/expressoMail1_2/js/main.js	(revision 5533)
@@ -322,4 +322,5 @@
 
 function show_msg_img(msg_number,folder){
+alert(msg_number+folder);
 	var call_back = function(data){
 	   data.showImg = true;
Index: /trunk/expressoMail1_2/js/search.js
===================================================================
--- /trunk/expressoMail1_2/js/search.js	(revision 5506)
+++ /trunk/expressoMail1_2/js/search.js	(revision 5533)
@@ -16,5 +16,5 @@
 		this.elementChecked = false;
 	}
-
+	
 	//Monta os forms dentro da janela;
 	searchE.prototype.showForms = function(value)
@@ -442,8 +442,19 @@
 	
 	searchE.prototype.make_tr_message = function(aux,border_id,i) {
+	console.log(aux);
+	/**
+	 * Preenche a estrutura de cache de mensagens para posterior consulta de 
+	 * informações sobre as mensagens no escopo global.
+	 */
+		if (!onceOpenedHeadersMessages[aux.boxname])
+			onceOpenedHeadersMessages[aux.boxname] = {};
+		onceOpenedHeadersMessages[aux.boxname][aux.uid] = aux;	
+	
 		var tr = document.createElement("TR");
 		if(typeof(preferences.line_height) != 'undefined')
 			tr.style.height = preferences.line_height;
-
+			
+		var msg_folder = get_current_folder(); 
+				
 		var mailbox = aux.boxname;
 		var uid_msg = aux.uid;
@@ -455,5 +466,5 @@
 		tr.setAttribute('name',mailbox);
 		tr.name = mailbox;
-
+		
 		if ( aux.flag.match("U") )
 			add_className(tr,'tr_msg_unread');
@@ -466,5 +477,5 @@
 		};
 
-		for(var j=0 ; j <= 10 ; j++)
+		for(var j=0 ; j <= 11 ; j++)
 		{
 			var td = document.createElement("TD");
@@ -519,11 +530,73 @@
 			{
 				td.setAttribute("width", colSizes[1][4]);
+				td.id = "td_message_followup_search_"+uid_msg;
+				td.setAttribute("class","search-result-item");
+				//td1 = "<img src ='../prototype/modules/mail/img/flagDefault.png' title='"+get_lang('Followup')+"'>";
+				td1 = '<div class="flag-edited" style="width:9px;height:6px;"><img src="../prototype/modules/mail/img/flagEditor.png"></div>';
+						
+				$(td).click(function(event, ui){	
+					var messageClickedId = $(this).attr('id').match(/td_message_followup_search_([\d]+)/)[1];
+					var flagged = DataLayer.get('followupflagged', {filter: [
+						'AND', 
+						['=', 'messageNumber', messageClickedId], 
+						['=', 'folderName', mailbox]
+					]});
+					if(flagged == '' || flagged == [] || flagged == 'undefined'){
+						/**
+						* Aplica followupflag de Acompanhamento
+						*/
+						aux.followupflagged = {
+							uid : User.me.id,
+							folderName : mailbox, 
+							messageNumber : messageClickedId, 
+							alarmTime : false, 
+							backgroundColor : '#FF2016',
+							followupflagId: '1',
+							followupflag: DataLayer.get('followupflag', '1')
+						};
+						$(this).find(".flag-edited").css("background", aux.followupflagged.backgroundColor);
+						aux.followupflagged.id = DataLayer.put('followupflagged', aux.followupflagged);
+						
+					}else if(aux.followupflagged.id){
+						/**
+						* Remover followupflag de Acompanhamento (DFD0078:RI25)
+						*/
+						$(this).find(".flag-edited").css("background", "#cccccc");
+
+
+						DataLayer.remove('followupflagged', flagged[0].id);
+						$('#td_message_followup_' + messageClickedId + ', ' + 
+						'#td_message_followup_search_' + messageClickedId).find(".flag-edited")
+						.find("img").attr("src", "../prototype/modules/mail/img/flagEditor.png").css("margin-left","0");
+					} else {
+						//TODO - open dialog
+					}
+					if(!DataLayer.commit()){}
+
+				});				
+			}
+			if (j == 5)
+			{
+				td.setAttribute("width", colSizes[1][5]);
+				td.id = "td_message_labels_search_"+uid_msg;
+				td.setAttribute("class","td-label-search");				
+				
+				if (aux.labels) {
+					td1 = '<img src="../prototype/modules/mail/img/tag.png">';
+					updateLabelsColumn(aux)		
+				} else {
+					td1 = '';
+				}
+			}
+			if (j == 6)
+			{
+				td.setAttribute("width", colSizes[1][6]);
 				td.id = "td_message_sent_"+uid_msg;
 				td1 = '';
 			}
 
-			if ( j == 5 )
-			{
-				td.setAttribute("width", colSizes[1][5]);
+			if ( j == 7 )
+			{
+				td.setAttribute("width", colSizes[1][7]);
 				td.className = "td_resizable";
 				td.onclick = _onclick;
@@ -536,15 +609,12 @@
 
 				var td1  = get_lang(td1).substr(get_lang(td1).length-1) == "*"?td1:get_lang(td1);
-
-									td1 = translateFolder(td1);
-
-
-				if( proxy_mensagens.is_local_folder(td1))
-				{
+				td1 = translateFolder(td1);
+
+				if (proxy_mensagens.is_local_folder(td1)) {
 					var td1 = this.aux_local_folder_display(td1);
 				}
 			}
 
-			if( j == 6 )
+			if( j == 8 )
 			{
 				var name;
@@ -557,5 +627,5 @@
 					name = name.substr(0,29) + "...";
 
-				td.setAttribute("width", colSizes[1][6]);
+				td.setAttribute("width", colSizes[1][8]);
 				td.className = "td_resizable";
 				td.onclick = _onclick;
@@ -566,5 +636,5 @@
 			}
 
-			if( j == 7 )
+			if( j == 9 )
 			{
 				var subject_encode = url_encode(subject);
@@ -575,5 +645,5 @@
 					aux.subject = aux.subject.substr(0,70) + "...";
 
-				td.setAttribute("width", colSizes[1][7]);
+				td.setAttribute("width", colSizes[1][9]);
 				td.className = "td_resizable td_msg_search_subject";
 				td.onclick = _onclick;
@@ -584,7 +654,7 @@
 			}
 
-			if( j == 8 )
-			{
-				td.setAttribute("width", colSizes[1][8]);
+			if( j == 10 )
+			{
+				td.setAttribute("width", colSizes[1][10]);
 				td.className = "td_resizable";
 				td.align		= "center";
@@ -609,5 +679,5 @@
 			}
 
-			if( j == 9 )
+			if( j == 11 )
 			{
 				td.setAttribute("width", "9.4%");//alinhamento dos campos data e tamanho
@@ -623,5 +693,5 @@
 			}
 
-			if( j == 10 )
+			if( j == 12 )
 			{
 				if (aux.flag.match("U"))
@@ -631,6 +701,20 @@
 				var td1 = '';
 			}
-			if (j<10) {
+			if (j<12) {
 				td.innerHTML = td1;
+				
+				//Carregar os followupflag nos resultados.
+				if (aux.followupflagged) {
+					$(td).attr('title', aux.followupflagged.followupflag.name)
+					.find(".flag-edited").css("background",aux.followupflagged.backgroundColor);
+					if(aux.followupflagged.isDone == "1"){
+						$(td).find(".flag-edited").find("img")
+						.attr("src", "../prototype/modules/mail/img/flagChecked.png")
+						.css("margin-left","-3px");
+					}
+				} else {
+					$(td).find(".flag-edited").css("background","#cccccc");
+				}
+				
 				tr.appendChild(td);
 			}
@@ -692,8 +776,9 @@
 			scrollSpeed: 100,
 			containment: "#divAppbox"
-		}).bind("contextmenu", function(){
-			if($(this).find("input:checkbox").attr("checked") != "checked"){
-				$(this).find("input:checkbox").trigger('click');
-				$(this).addClass("selected_msg");
+		}).bind("mouseup", function(event){
+			if(event.button == 2)
+				if($(this).find("input:checkbox").attr("checked") != "checked"){
+					$(this).find("input:checkbox").trigger('click');
+					$(this).addClass("selected_msg");
 			}
 		});
@@ -705,8 +790,7 @@
 	{
 		var data = ( Data['data'] ) ? Data['data'] : Data['data_gears'];
-		
 		if ( data == undefined )
 			return;
-		
+	
 		var cont = parseInt(0);
 
@@ -859,5 +943,7 @@
 		td_element03 = createTDElement(1,3);
 		td_element04 = createTDElement(1,4);
-		td_element1 = createTDElement(1,5,"th_resizable","left");
+		td_element05 = createTDElement(1,5);
+		td_element06 = createTDElement(1,6);
+		td_element1 = createTDElement(1,7,"th_resizable","left");
 		
 		var arrow_ascendant = function(Text)
@@ -865,5 +951,5 @@
 			return "<b>" + Text + "</b><img src='templates/"+template+"/images/arrow_ascendant.gif'>";
 		}
-		
+
 		// Ordernar Pasta
 		if ( sort_type == 'SORTBOX' /*|| sort_type == 'SORTBOX_REVERSE'*/ )
@@ -894,5 +980,5 @@
 		
 		// Ordernar Quem
-		td_element2 = createTDElement(1,6,"th_resizable","left");
+		td_element2 = createTDElement(1,8,"th_resizable","left");
 
 		if (sort_type == 'SORTFROM' || sort_type == 'SORTWHO' /*|| sort_type == 'SORTWHO_REVERSE' || sort_type == 'SORTFROM_REVERSE'*/ )
@@ -923,5 +1009,5 @@
 		
 		// Ordernar Subject
-		td_element3 = createTDElement(1,7,"th_resizable","left");
+		td_element3 = createTDElement(1,9,"th_resizable","left");
 		
 		if (sort_type == 'SORTSUBJECT' /*|| sort_type == 'SORTSUBJECT_REVERSE'*/)
@@ -952,5 +1038,5 @@
 		
 		// Ordernar Data
-		td_element4 = createTDElement(1,8,"th_resizable","center");
+		td_element4 = createTDElement(1,10,"th_resizable","center");
 		
 		if ( sort_type == 'SORTDATE' /*|| sort_type == 'SORTDATE_REVERSE'*/ )
@@ -981,5 +1067,5 @@
 
 		// Ordernar Tamanho
-		td_element5 = createTDElement(1,9,"th_resizable","center");
+		td_element5 = createTDElement(1,11,"th_resizable","center");
 		
 		if ( sort_type == 'SORTSIZE' /*|| sort_type == 'SORTSIZE_REVERSE'*/ )
@@ -1008,4 +1094,7 @@
 			td_element5.innerHTML	= ( sort_type == 'SORTSIZE_REVERSE' ) ? arrow_ascendant(get_lang("size")) : get_lang("size");
 		}
+		
+		//Abrir a Tela de de Configuracao de Acompanhamento
+		
 		
 		tr_element.appendChild(td_element0);
@@ -1014,4 +1103,6 @@
 		tr_element.appendChild(td_element03);
 		tr_element.appendChild(td_element04);
+		tr_element.appendChild(td_element05);
+		tr_element.appendChild(td_element06);
 		tr_element.appendChild(td_element1);
 		tr_element.appendChild(td_element2);
@@ -1022,4 +1113,5 @@
 		table_element.appendChild(tbody_element);
 
+		
 		var colgr_element = buildColGroup(1);
 		colgr_element.setAttribute("id","colgroup_head_"+numBox);
@@ -1624,2 +1716,3 @@
 // Cria o objeto
 var EsearchE = new searchE();
+var EsearchE = new searchE();
Index: /trunk/expressoMail1_2/js/draw_api.js
===================================================================
--- /trunk/expressoMail1_2/js/draw_api.js	(revision 5527)
+++ /trunk/expressoMail1_2/js/draw_api.js	(revision 5533)
@@ -1,3 +1,14 @@
- var openTab = {
+/**
+ * Estrutura que guarda em cache as mensagens abertas, a exemplo da estrutura utilizada
+ * na funcionalidade de anexar mensagens.
+ * Isto reduz a necessidade de acessar estruturas da tela para obter informações sobre 
+ * as mensagens, como tem sido para encaminhar, responder, etc.
+ * Manter os dados 'limpos' em uma estrutura 'somente-leitura' permite maior flexibilidade
+ * para mudar a tela e menos processamento de limpeza de dados (por exemplo retirar tags de 
+ * formatação, etc.) 
+ */
+onceOpenedHeadersMessages = {};
+
+var openTab = {
 	'type' : [], // 8 types of tabs, further info. see expressolivre.org/dev/wiki/mail/Documentacao
 	'content_id' : [],
@@ -153,4 +164,7 @@
 			var noden=document.getElementById('lnews_roottree_folders');
 			noden.style.backgroundImage="url(templates/"+template+"/images/menu/rss.png)";
+			
+			
+			
 		}
 //		cExecute('$this.rss.getChannels',handlerChannel);
@@ -206,5 +220,5 @@
 			}
 
-		/*tree_folders.draw(Element('content_folders'));
+		tree_folders.draw(Element('content_folders'));
 		if (!expresso_offline) {
 			n_root.changeState();
@@ -214,10 +228,10 @@
 			root_local.changeState();
 			tree_folders.getNodeById('local_Inbox')._select();
-		}*/
-
+		}
+		
 		var trash_span = document.getElementById(mount_url_folder(["lINBOX",special_folders["Trash"]])  + 'tree_folders'); 
-                var draft_span = document.getElementById(mount_url_folder(["lINBOX",special_folders["Drafts"]]) + 'tree_folders'); 
-                var sent_span  = document.getElementById(mount_url_folder(["lINBOX",special_folders["Sent"]]) + 'tree_folders'); 
-                var spam_span  = document.getElementById(mount_url_folder(["lINBOX",special_folders["Spam"]]) + 'tree_folders');
+		var draft_span = document.getElementById(mount_url_folder(["lINBOX",special_folders["Drafts"]]) + 'tree_folders'); 
+		var sent_span  = document.getElementById(mount_url_folder(["lINBOX",special_folders["Sent"]]) + 'tree_folders'); 
+		var spam_span  = document.getElementById(mount_url_folder(["lINBOX",special_folders["Spam"]]) + 'tree_folders');
 		//local folders
 		var sent_local_conf = this.preferences.save_in_folder.replace(mount_url_folder(["INBOX",""]),"local_");
@@ -321,5 +335,39 @@
 		}
 	}
-
+}
+
+function draw_tree_labels(){
+	labels = DataLayer.get('label',{criteria:{order: 'name'}});
+
+	$('#content_folders').append("<div id='MyMarckersList' class='acc-list list-label' ></div>").find("#MyMarckersList")
+	.append("<div class='my-labels'>" +
+				"<img src='../prototype/modules/mail/img/tag.png'/>" +
+				"<a class='title-my-labels' tabindex='0' role='button' aria-expanded='false' title='Meus marcadores'>Meus marcadores</a>" +
+				
+				"<span class='status-list-labels ui-icon ui-icon-triangle-1-s'></span>" +
+			"</div>"
+	)
+	.append(DataLayer.render("../prototype/modules/mail/templates/label_list.ejs", {labels: labels} ))
+	.find("li.label-item").css({"background-color":"#ffffff", "border-color":"#CCCCCC", "color":"#444444"}).click(function(){
+		var labelId = $(this).attr('class').match(/label-item-([\d]+[()a-zA-Z]*)/)[1];
+		search_emails("UNDELETED KEYWORD \"$Label"+labelId+"\"");
+	})
+	.find(".square-color").css("display","").click(function(){
+		$(this).parent(".label-item").each(function(){
+			configureLabels({selectedItem: $(this).attr('class').match(/label-item-([\d]+[()a-zA-Z]*)/)[1]});
+			var id_label_item = $(this).attr('class').match(/label-item-([\d]+[()a-zA-Z]*)/)[1];
+			$(".label-list-container .label-list").find(".label-item-"+id_label_item).trigger("click");
+		});
+	});
+	
+	$("#MyMarckersList a.title-my-labels").click(function() {
+		$("#MyMarckersList ul.label-list").toggleClass("hidden")
+		$('#MyMarckersList .status-list-labels').toggleClass("ui-icon-triangle-1-s");
+		$('#MyMarckersList .status-list-labels').toggleClass("ui-icon-triangle-1-n");
+	 });
+	 
+	if (!labels){
+		$(".my-labels").addClass("hidden");
+	}
 }
 
@@ -436,4 +484,5 @@
 		}
 		draw_new_tree_folder();	
+		draw_tree_labels();
 }
 
@@ -601,5 +650,6 @@
 // stores the percentages of the cells
 //var colSizes = [ ["24","24","12","12","12","16","16","20%","58%","11%","11%"], ["16","16","12","12","12","20%","20%","*","10%","10%"] ];
-var colSizes = [ ["2%","2%","1%","1%","1%","1%","2%","20%","48%","11%","11%"], ["16","16","12","12","12","20%","20%","*","10%","10%"] ];
+//var colSizes = [ ["2%","2%","1%","1%","1%","1%","2%","2%","20%","46%","11%","11%"], ["16","16","12","12","12","20%","20%","*","10%","10%"] ];
+var colSizes = [ ["2%","2%","1%","1%","1%","1%","2%","2%","2%","20%","46%","11%","11%"], ["2%","1%","1%","1%","1%","1%","1%","20%","20%","*","10%","9%"] ];
 // stores the alignments of the cells
 var colAligns = [ ['','','','','','','','left','left','center','center'], ['','','','','','left','left','left','center','center'] ];
@@ -942,5 +992,5 @@
 // Draw the inbox and another folders
 function draw_box(headers_msgs, msg_folder, alternate){
-        /*
+	/*
 	 * When the paging response is not in the correct folder you need to change folder
 	 * This occurs when the Ajax response is not fast enough and the user click in outher
@@ -968,4 +1018,60 @@
 	}
 	/* --- */
+	 
+	/**
+	 * Get the labels aplyed to the messages and saves the information 
+	 * into message array 
+	 */
+	var messageNumbers = new Array();
+	for (var i=0; i<headers_msgs.length; i++) {
+		messageNumbers.push(headers_msgs[i].msg_number);
+	}
+	var labeleds = DataLayer.get('labeled', {
+			filter: ['AND', ['IN', 'messageNumber', messageNumbers], ['=', 'folderName', msg_folder]],
+			criteria: {deepness: 2}
+		});
+
+	if(labeleds) {
+		for (var i=0; i<headers_msgs.length; i++) {
+			for (var j=0; j<labeleds.length; j++) {
+				if (labeleds[j].messageNumber == headers_msgs[i].msg_number) {
+					if (!headers_msgs[i].labels)
+						headers_msgs[i].labels = {};
+					headers_msgs[i].labels[labeleds[j].label.id] = labeleds[j].label;
+				}
+			}
+		}
+	}
+	
+	/**
+	 * Get the followupflags aplyed to the messages and saves the information 
+	 * into message array 
+	 */
+	var followupflaggeds = DataLayer.get('followupflagged', {
+			filter: ['AND', ['IN', 'messageNumber', messageNumbers], ['=', 'folderName', msg_folder]],
+			criteria: {deepness: 1}
+		});
+
+	if(followupflaggeds) {
+		for (var i=0; i<headers_msgs.length; i++) {
+			for (var j=0; j<followupflaggeds.length; j++) {
+				if (followupflaggeds[j].messageNumber == headers_msgs[i].msg_number) {
+					if (!headers_msgs[i].followupflagged)
+						headers_msgs[i].followupflagged = {};
+					headers_msgs[i].followupflagged = followupflaggeds[j];
+				}
+			}
+		}
+	}
+	
+	/**
+	 * Preenche a estrutura de cache de mensagens para posterior consulta de 
+	 * informações sobre as mensagens no escopo global.
+	 */
+	for (var i=0; i<headers_msgs.length; i++) { 
+		if (!onceOpenedHeadersMessages[current_folder])
+			onceOpenedHeadersMessages[current_folder] = {};
+		onceOpenedHeadersMessages[current_folder][headers_msgs[i].msg_number] = headers_msgs[i];
+	}
 
 	if (alternate)
@@ -1030,17 +1136,17 @@
 
 		td_element2 = createTDElement(0,1);
-		td_element3 = createTDElement(0,7,"th_resizable","left","message_header_SORTFROM_"+numBox);
+		td_element3 = createTDElement(0,8,"th_resizable","left","message_header_SORTFROM_"+numBox);
 		td_element3.onclick = function () {sort_box(search_box_type,'SORTFROM');};
 		td_element3.innerHTML = get_lang("From");
 
-		td_element4 = createTDElement(0,8,"th_resizable","left","message_header_SORTSUBJECT_"+numBox);
+		td_element4 = createTDElement(0,9,"th_resizable","left","message_header_SORTSUBJECT_"+numBox);
 		td_element4.onclick = function () {sort_box(search_box_type,'SORTSUBJECT');};
 		td_element4.innerHTML = get_lang("Subject");
 
-		td_element5 = createTDElement(0,9,"th_resizable","center","message_header_SORTARRIVAL_"+numBox);
+		td_element5 = createTDElement(0,10,"th_resizable","center","message_header_SORTARRIVAL_"+numBox);
 		td_element5.onclick = function () {sort_box(search_box_type,'SORTARRIVAL');};
 		td_element5.innerHTML = get_lang("Date");
 
-		td_element6 = createTDElement(0,10,"th_resizable","left","message_header_SORTSIZE_"+numBox);
+		td_element6 = createTDElement(0,11,"th_resizable","left","message_header_SORTSIZE_"+numBox);
 		td_element6.onclick = function () {sort_box(search_box_type,'SORTSIZE');}
 		td_element6.innerHTML = get_lang("Size");
@@ -1060,7 +1166,15 @@
 		var td_element24 = createTDElement(0,5);
 		td_element24.innerHTML = "&nbsp;";
-
-		var td_element25 = createTDElement(0,6);
+			
+		
+		var td_element25 = createTDElement(0,7);
 		td_element25.innerHTML = "&nbsp;";
+		
+		var td_element27 = createTDElement(0,8);
+		td_element25.innerHTML = "&nbsp;";
+		
+		var td_element26 = createTDElement(0,6);
+		td_element26.innerHTML = "&nbsp;";
+		
 
 		tr_element.appendChild(td_element21);
@@ -1068,5 +1182,8 @@
 		tr_element.appendChild(td_element23);
 		tr_element.appendChild(td_element24);
+		tr_element.appendChild(td_element26);
+		tr_element.appendChild(td_element27);
 		tr_element.appendChild(td_element25);
+		
 		tr_element.appendChild(td_element3);
 		tr_element.appendChild(td_element4);
@@ -1211,8 +1328,5 @@
 				},
 				helper: function(event){
-					if($(this).find("input:checkbox").attr("checked") != "checked"){
-						$(this).find("input:checkbox").trigger('click');
-						$(this).addClass("selected_msg");
-					}
+					$(this).find("input:checkbox").attr("checked", true);
 					if($("#table_box").find("tr input:checked").length > 1)
 						return $(DataLayer.render('../prototype/modules/mail/templates/draggin_box.ejs', {texto : (($("#table_box").find("tr input:checked")).length+" mensagens selecionadas"), type: "messages"}));
@@ -1228,8 +1342,9 @@
 				scrollSpeed: 100,
 				containment: "#divAppbox"
-			}).bind("contextmenu", function(){
-				if($(this).find("input:checkbox").attr("checked") != "checked"){
-					$(this).find("input:checkbox").trigger('click');
-					$(this).addClass("selected_msg");
+			}).bind("mouseup", function(event){
+				if(event.button == 2)
+					if($(this).find("input:checkbox").attr("checked") != "checked"){
+						$(this).find("input:checkbox").trigger('click');
+						$(this).addClass("selected_msg");
 				}
 			});
@@ -1255,4 +1370,5 @@
 		alert("Carregou em "+(_eTime - _bTime)+" ms");
 	}
+	
 	var msg_folder = Element('msg_folder').value;
 	var msg_number = Element('msg_number').value;
@@ -1271,5 +1387,5 @@
 	if(Element("table_quota"))
 		connector.loadScript("InfoQuota");
-
+	
 	// creates the dotted ruler which helps user to visualize resizing of columns
 	var ruler_element = document.getElementById("table_message_ruler");
@@ -1281,5 +1397,5 @@
 		document.getElementById("exmail_main_body").appendChild(ruler_element);
     }
-
+				
 }
 
@@ -1303,9 +1419,10 @@
 // Passar o parâmetro offset para esta função
 function make_tr_message(headers_msgs, msg_folder, offsetToGMT){
-                if (typeof offsetToGMT == 'undefined')
-                {
-                    // In older local messages headers_msgs.offsetToGMT is undefined.
-                    offsetToGMT = typeof headers_msgs.offsetToGMT != 'undefined'?headers_msgs.offsetToGMT:0;
-                }
+
+		if (typeof offsetToGMT == 'undefined')
+		{
+			// In older local messages headers_msgs.offsetToGMT is undefined.
+			offsetToGMT = typeof headers_msgs.offsetToGMT != 'undefined'?headers_msgs.offsetToGMT:0;
+		}
 		var tr_element = document.createElement('tr');
 		if(typeof(preferences.line_height) != 'undefined')
@@ -1350,8 +1467,6 @@
 		chk_box_element.className = "checkbox";
 		chk_box_element.setAttribute("id", "check_box_message_"+headers_msgs.msg_number);
-		chk_box_element.onclick = function(e){
-			if (is_ie)
-				changeBgColor(window.event,headers_msgs.msg_number);
-			else
+		chk_box_element.onchange = function(e){
+			//if (is_ie)
 				changeBgColor(e,headers_msgs.msg_number);
 		};
@@ -1415,5 +1530,5 @@
 
 
-		td_element25 = createTDElement(0,6,"td_msg",null,"td_message_unseen_"+headers_msgs.msg_number);
+		td_element25 = createTDElement(0,7,"td_msg",null,"td_message_unseen_"+headers_msgs.msg_number);
 		if ((headers_msgs.Unseen == 'U') || (headers_msgs.Recent == 'N'))
 			td_element25.innerHTML = "<img src ='templates/"+template+"/images/unseen.gif' title='"+get_lang('Unseen')+"'>";
@@ -1422,5 +1537,5 @@
 
 
-		td_element3 = createTDElement(0,7,"td_msg td_resizable","left","td_from_"+ headers_msgs.msg_number);
+		td_element3 = createTDElement(0,8,"td_msg td_resizable","left","td_from_"+ headers_msgs.msg_number);
 		var _onclick = function(){InfoContact.hide();proxy_mensagens.get_msg(headers_msgs.msg_number, msg_folder,true, show_msg);};
 		td_element3.onclick = _onclick;
@@ -1483,5 +1598,5 @@
 		}
 
-		td_element4 = createTDElement(0,8,"td_msg td_resizable","left");
+		td_element4 = createTDElement(0,9,"td_msg td_resizable","left");
 		td_element4.className += " td_msg_subject";
 		td_element4.onclick = _onclick;
@@ -1511,9 +1626,84 @@
 			td_element4.innerHTML += "</a>";
 		}
-
-
-		td_element5 = createTDElement(0,9,"td_msg td_resizable","center");
+		
+		td_element5 = createTDElement(0,10,"td_msg td_resizable","center");
 		td_element5.onclick = _onclick;
-
+		
+		td_element27 = createTDElement(0,7,"td_msg",null,"td_message_labels_"+headers_msgs.msg_number);
+		$(td_element27).addClass("td-label");
+
+		if (headers_msgs.labels) {
+			td_element27.innerHTML = '<img src="../prototype/modules/mail/img/tag.png">';
+			updateLabelsColumn(headers_msgs)		
+		}
+		
+		td_element26 = createTDElement(0,6,"td_msg",null,"td_message_followup_"+headers_msgs.msg_number);
+		$(td_element26).addClass("td-followup-flag");
+		td_element26.innerHTML = '<div class="flag-edited" style="width:9px;height:6px;"><img src="../prototype/modules/mail/img/flagEditor.png"></div>';
+	
+		if (headers_msgs.followupflagged) {
+			$(td_element26).attr('title', headers_msgs.followupflagged.followupflag.name)
+			.find(".flag-edited").css("background",headers_msgs.followupflagged.backgroundColor);
+			if(headers_msgs.followupflagged.isDone == "1"){
+				$(td_element26).find(".flag-edited").find("img")
+				.attr("src", "../prototype/modules/mail/img/flagChecked.png")
+				.css("margin-left","-3px");
+			}
+		} else {
+			$(td_element26).find(".flag-edited").css("background","#cccccc");
+		}
+		
+		/**
+		 * Clique para aplicar sinalizador
+		 */
+		$(td_element26).click(function() {	
+			
+			var messageClickedId = $(this).attr('id').match(/td_message_followup_([\d]+)/)[1];
+			 /**
+				* Hack:
+				* headers_msgs.followupflagged.id não vai funcionar porque já foi feito DataLayer.commit()
+				* por isso o id deve ser obtido do banco
+				* também para verificar se há ou não sinalizador nesta mensagem
+			*/
+			var flagged = DataLayer.get('followupflagged', {filter: [
+				'AND', 
+				['=', 'messageNumber', messageClickedId], 
+				['=', 'folderName', msg_folder]
+			]});
+			if (flagged == '' || flagged == [] || flagged == 'undefined') {
+				/**
+				 * Aplica followupflag de Acompanhamento
+				 */
+
+				headers_msgs.followupflagged = {
+					uid : User.me.id,
+					folderName : msg_folder, 
+					messageNumber : messageClickedId, 
+					alarmTime : false, 
+					backgroundColor : '#FF2016',
+					followupflagId: '1',
+					followupflag: DataLayer.get('followupflag', '1')
+				};
+				$(this).find(".flag-edited").css("background", headers_msgs.followupflagged.backgroundColor);
+				headers_msgs.followupflagged.id = DataLayer.put('followupflagged', headers_msgs.followupflagged);
+				
+			} else if (headers_msgs.followupflagged.followupflag.name == 'Follow up') {
+				/**
+				 * Remover followupflag de Acompanhamento (DFD0078:RI25)
+				 */
+				 $(this).find(".flag-edited").css("background", "#cccccc");
+
+
+				DataLayer.remove('followupflagged', flagged[0].id);
+				$('#td_message_followup_' + messageClickedId + ', ' + 
+				'#td_message_followup_search_' + messageClickedId).find(".flag-edited")
+				.find("img").attr("src", "../prototype/modules/mail/img/flagEditor.png").css("margin-left","0");
+			} else {
+				$(tr_element).addClass('selected_msg').find(':checkbox').trigger('click');
+				configureFollowupflag();
+			}
+			
+		});	
+		
 		var norm = function (arg) {return (arg < 10 ? '0'+arg : arg);};
 		var weekDays = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
@@ -1557,5 +1747,5 @@
 		td_element5.alt = td_element5.title;
 
-		td_element6 = createTDElement(0,10,"td_msg td_resizable","center");
+		td_element6 = createTDElement(0,11,"td_msg td_resizable","center");
 		td_element6.onclick = _onclick;
 		td_element6.setAttribute("noWrap","true");
@@ -1567,6 +1757,9 @@
 		tr_element.appendChild(td_element22);
 		tr_element.appendChild(td_element23);
-			tr_element.appendChild(td_element24);
+		tr_element.appendChild(td_element24);
+		tr_element.appendChild(td_element26);
+		tr_element.appendChild(td_element27);
 		tr_element.appendChild(td_element25);
+
 		tr_element.appendChild(td_element3);
 		tr_element.appendChild(td_element4);
@@ -3386,5 +3579,5 @@
             if ((e.keyCode) == 120) //F9
 			{
-                emQuickSearch(input_replyto.value, 'replyto', ID, undefined,true);
+                emQuickSearch(input_replyto.value, 'replyto', ID);
 			}
 			else
@@ -3412,5 +3605,5 @@
 			if ((window.event.keyCode) == 120) //F9
 			{
-					emQuickSearch(input_replyto.value, 'replyto', ID, undefined,true);
+					emQuickSearch(input_replyto.value, 'replyto', ID);
 			}
 			else
@@ -3453,5 +3646,5 @@
 			if ((e.keyCode) == 120) //F9
 			{
-				emQuickSearch(input_to.value, 'to', ID, undefined,true);
+				emQuickSearch(input_to.value, 'to', ID);
 			}
 			else
@@ -3479,5 +3672,5 @@
 			if ((window.event.keyCode) == 120) //F9
 			{
-				emQuickSearch(input_to.value, 'to', ID, undefined,true);
+				emQuickSearch(input_to.value, 'to', ID);
 			}
 			else
@@ -3536,5 +3729,5 @@
 			if ((e.keyCode) == 120) //F9
 			{
-				emQuickSearch(input_cc.value, 'cc', ID, undefined,true);
+				emQuickSearch(input_cc.value, 'cc', ID);
 			}
 			else
@@ -3562,5 +3755,5 @@
 			if ((window.event.keyCode) == 120) //F9
 			{
-				emQuickSearch(input_cc.value, 'cc', ID, undefined,true);
+				emQuickSearch(input_cc.value, 'cc', ID);
 			}
 			else
@@ -3608,5 +3801,5 @@
 				if ((e.keyCode) == 120) //F9
 				{
-					emQuickSearch(input_cco.value, 'cco', ID, undefined,true);
+					emQuickSearch(input_cco.value, 'cco', ID);
 				}
 				else
@@ -3633,5 +3826,5 @@
 				if ((window.event.keyCode) == 120) //F9
 				{
-					emQuickSearch(input_cco.value, 'cco', ID, undefined,true);
+					emQuickSearch(input_cco.value, 'cco', ID);
 				}
 				else
@@ -3656,5 +3849,4 @@
 	var cc_load = "";
 	a_cc_link.onclick = function () {
-		var rm = false;
 		var remove = function(){
 			document.getElementById('tr_cc_'+ID).style.display = 'none';
@@ -3662,5 +3854,4 @@
 			$("#cc_"+ID).val("");
 			$("#a_cc_link_"+ID).toggleClass("expressomail-button-icon-ative");
-			rm = true;
 		}
 		if(!($("#cc_"+ID).parent().find("div")[0])){
@@ -3682,8 +3873,6 @@
 			}
 		}
-		if (rm)
-			input_to.focus();
-		else	
-			input_cc.focus();		
+		input_cc.focus();
+		
 		return false;
 	};
@@ -4014,8 +4203,4 @@
 		$("#"+$(this).attr("name")).attr("checked", (!check ? true : false));
 		//$(this).button({ disabled: false });
-		if (RichTextEditor.plain[id] != true)
-			setTimeout("RichTextEditor.focus("+ID+")",100);			
-		else 
-			$('#body_'+ID).focus();
 	});
 	
Index: /trunk/expressoMail1_2/js/doiMenuData.js
===================================================================
--- /trunk/expressoMail1_2/js/doiMenuData.js	(revision 5497)
+++ /trunk/expressoMail1_2/js/doiMenuData.js	(revision 5533)
@@ -8,29 +8,89 @@
 }
 
-$.contextMenu({
-	selector: ".table_box tbody tr",
-	callback: function(key, options) {
-		//TODO - default actions
-		//TODO - aply labels actions
-
-	},
-	items: {
-		"flagSeen":      {"name": get_lang("Mark as") + " " + get_lang('seen'), "icon": "seen", callback: function(key, opt){ proxy_mensagens.proxy_set_messages_flag('seen','get_selected_messages'); }},
-		"flagUnseen":    {"name": get_lang("Mark as") + " " + get_lang('unseen'), "icon": "unseen", callback: function(key, opt){ proxy_mensagens.proxy_set_messages_flag('unseen','get_selected_messages'); }},
-		"flagFlagged":   {"name": get_lang("Mark as") + " " + get_lang('important'), "icon": "important", callback: function(key, opt){ proxy_mensagens.proxy_set_messages_flag('flagged','get_selected_messages'); }},
-		"flagUnflagged": {"name": get_lang("Mark as") + " " + get_lang('normal'), callback: function(key, opt){ proxy_mensagens.proxy_set_messages_flag('unflagged','get_selected_messages'); }},
-		
-		
-		"sep2": "---------",
-		"move": {"name": get_lang("Move to")+"...", "icon": "move", callback: function(key, opt){ wfolders.makeWindow('', 'move_to'); }},
-		"remove": {"name": get_lang("Delete"),      "icon": "delete", callback: function(key, opt){ proxy_mensagens.delete_msgs('null','selected','null'); }},
-		"export": {"name": get_lang("Export"),      "icon": "export", callback: function(key, opt){ proxy_mensagens.export_all_messages(); }}
-	}
-});
-
 
 /**
- * Cria a lista de itens para o menu ferramentas
+ * Cria a lista de marcadores para o submenu "Marcadores"
  */
+function getLabels(){
+	var labels = DataLayer.get('label',{criteria:{order: 'name'}});
+	var menuLabelItems = {};
+	for(var i=0; i<labels.length; i++) {
+		menuLabelItems["label"+labels[i].id] = {
+			"name" : labels[i].name,
+		}
+	}
+	return menuLabelItems;
+}
+
+/**
+ *	Carrega o menu de opÃ§Ã£o de uma mensagem
+ */
+function loadMenu(){
+	var labelItems = getLabels();
+	$.contextMenu({
+		selector: ".table_box tbody tr",
+		callback: function(key, options) {
+			//TODO - default actions
+			
+			/** 
+			 * Aply labels to selected messages
+			 */
+			var isLabel = key.match(/label(.*)/);
+			if (isLabel && isLabel.length > 1) {
+				var label = {
+					id: isLabel[1]
+				}	
+				var lableleds = new Array();
+				
+				if(currentTab == 0){
+					var messages = get_selected_messages().split(',');
+				}else{
+					var messages = get_selected_messages_search().split(',');
+				}
+
+				for (var i=0; i < messages.length; i++) {
+					var hasLabel = DataLayer.get('labeled', [
+							'AND',
+							['=', 'labelId', label.id], 
+							['=', 'folderName', current_folder], 
+							['=', 'messageNumber', messages[i]]
+					]);
+					if (!hasLabel) {
+						lableleds.push(
+							DataLayer.put('labeled', {
+								labelId:label.id, 
+								folderName:current_folder, 
+								messageNumber:messages[i]
+							})
+						);
+						
+					}
+				}
+				DataLayer.commit();
+				for (var i=0; i < messages.length; i++) {
+					updateLabelsColumn({msg_number:messages[i], labels:false});
+				}
+			}
+		},
+		items: {
+			"flagSeen":      {"name": get_lang("Mark as") + " " + get_lang('seen'), "icon": "seen", callback: function(key, opt){ proxy_mensagens.proxy_set_messages_flag('seen','get_selected_messages'); }},
+			"flagUnseen":    {"name": get_lang("Mark as") + " " + get_lang('unseen'), "icon": "unseen", callback: function(key, opt){ proxy_mensagens.proxy_set_messages_flag('unseen','get_selected_messages'); }},
+			"flagFlagged":   {"name": get_lang("Mark as") + " " + get_lang('important'), "icon": "important", callback: function(key, opt){ proxy_mensagens.proxy_set_messages_flag('flagged','get_selected_messages'); }},
+			"flagUnflagged": {"name": get_lang("Mark as") + " " + get_lang('normal'), callback: function(key, opt){ proxy_mensagens.proxy_set_messages_flag('unflagged','get_selected_messages'); }},
+			
+			"sep1": "---------",
+			"label": { "name": get_lang("Labels"), "items": labelItems},
+			"follouwpflag":{"name": get_lang("Follow up"), callback: function(key, opt){ configureFollowupflag(); } },
+			
+			"sep2": "---------",
+			"move": {"name": get_lang("Move to")+"...", "icon": "move", callback: function(key, opt){ wfolders.makeWindow('', 'move_to'); }},
+			"remove": {"name": get_lang("Delete"),      "icon": "delete", callback: function(key, opt){ proxy_mensagens.delete_msgs('null','selected','null'); }},
+			"export": {"name": get_lang("Export"),      "icon": "export", callback: function(key, opt){ proxy_mensagens.export_all_messages(); }}
+		}
+	});
+}
+/*FIM*/
+loadMenu();
+
 if (!expresso_offline) {
 	var menuToolsItems = {
@@ -40,6 +100,6 @@
 		"i04": {"name": get_lang("Edit folders"), "icon": "edit-folder", callback: folderbox },
 		"i05": {"name": get_lang("Share mailbox"), "icon": "share-mailbox", callback: sharebox },
-
-		"i08": {"name": get_lang("Empty trash"), "icon": "empty-trash", callback: function(key, opt){ empty_trash_imap() } }
+		"i06": {"name": get_lang("Labels"), "icon": "tag", callback: configureLabels }, 
+		"i08": {"name": get_lang("Empty trash"), "icon": "empty-trash", callback: function(key, opt){ empty_trash_imap }}
 	};
 		
@@ -56,7 +116,4 @@
 }
 
-/**
- * Aplica o menu ferramentas
- */
 $.contextMenu({
 	selector: "#link_tools",
@@ -70,7 +127,4 @@
 	events: {
 		show: function(opt) {
-			/**
-			 * Modifica cor do elemento de trigger para o menu
-			 */
 			var $trigger = $(opt.selector).css({'background-color': '#EEEEEE', 'border': '1px solid #CCCCCC'});
 			$('.context-menu-list.context-menu-root').css({'width': $trigger.css('width') });
@@ -78,7 +132,4 @@
 		},
 		hide: function(opt) {
-			/**
-			 * Modifica cor do elemento de trigger para o menu
-			 */
 			$(opt.selector).css({'background-color': '', 'border': 'none'});
 			return true;
@@ -86,7 +137,54 @@
 	},
 	callback: function(key, options) {
-		//TODO - default actions		
+		
 	},
 	items: menuToolsItems
 });
 
+
+function updateLabelsColumn(messageInfo) {
+	$('#td_message_labels_' + messageInfo.msg_number +', #td_message_labels_search_' + messageInfo.msg_number)
+	.html('<img src="../prototype/modules/mail/img/tag.png">');
+
+	var menuItems = {};
+	if (messageInfo.labels) {
+		menuItems = messageInfo.labels;
+	} else {
+		var labeleds = DataLayer.get('labeled', {
+			filter: [
+				'AND',
+				['=', 'folderName', current_folder], 
+				['=', 'messageNumber', messageInfo.msg_number]
+			],
+			criteria: {deepness: 2}
+		});
+		if (labeleds) {
+			for (var i=0; i < labeleds.length; i++)
+				menuItems[labeleds[i].label.id] = labeleds[i].label;
+		} else {
+			//nÃ£o tem labels
+			return false;
+		}
+	}
+
+	$.contextMenu( 'destroy', '#td_message_labels_' + messageInfo.msg_number +', #td_message_labels_search_' + messageInfo.msg_number);
+
+	$.contextMenu({
+		selector: '#td_message_labels_' + messageInfo.msg_number +', #td_message_labels_search_' + messageInfo.msg_number,
+		trigger: 'hover',
+		delay:100,
+		autoHide:true,
+		callback: function(key, options) {
+			//alert($(this).attr('id'));
+		},
+		items: menuItems
+	});
+}
+
+/**
+ * TODO
+ * * ao clicar com o botao direito em cima da mensagem, selecionar a mensagem
+ * * clarear a cor do menu ferramentas
+ * * pintar o botao ferramentas, quando clicado, da cor do menu
+ * 
+ */
