Index: trunk/prototype/modules/calendar/interceptors/DBMapping.php
===================================================================
--- trunk/prototype/modules/calendar/interceptors/DBMapping.php	(revision 6011)
+++ trunk/prototype/modules/calendar/interceptors/DBMapping.php	(revision 6066)
@@ -1,200 +1,191 @@
 <?php
+
 //Definindo Constantes
-require_once ROOTPATH.'/modules/calendar/constants.php';
-
-require_once ROOTPATH.'/modules/calendar/interceptors/Helpers.php';
-
-class DBMapping extends Helpers {	
-           
-    public function encodeCreateSchedulable( &$uri , &$params , &$criteria , $original ){
+require_once ROOTPATH . '/modules/calendar/constants.php';
+
+require_once ROOTPATH . '/modules/calendar/interceptors/Helpers.php';
+
+class DBMapping extends Helpers {
+
+    public function encodeCreateSchedulable(&$uri, &$params, &$criteria, $original) {
 	$params['type_id'] = EVENT_ID;
 
-	if(!is_numeric($params['startTime']) )
-	  $params['startTime'] =   self::parseTimeDate( $params['startTime'], $params['timezone'] ); 
-		
-	if (!is_numeric($params['endTime'])){
-	  $params['endTime'] =    self::parseTimeDate( $params['endTime'], $params['timezone'] ); 
-
-	  if($params['allDay'])
-	    $params['endTime'] =  $params['endTime']  + 86400000;
-	}
-    //        if( !isset( $new['repeat'] ))
-    //            $new['range_end'] = '7287926400'; // 12/12/2200
-    //        else
-            $params['rangeEnd'] = $params['endTime'];
-	    $params['rangeStart'] =  $params['startTime'];
-
-            ///////////////////////////////////////////////////////////////////
-
-            $params['dtstamp'] = (isset($params['dtstamp'])) ? $params['dtstamp'] :time().'000'; 
-            $params['lastUpdate'] = (isset($params['lastUpdate'])) ? $params['lastUpdate'] :time().'000'; 
-            $params['type'] = EVENT_ID;
-            $params['uid'] = isset($params['uid']) ? $params['uid'] : $this->_makeUid();
-    }
-
-    static function parseTimeDate($time, $timezone){
-	return strtotime( $time . ' ' .$timezone).'000';         
-   }	
-		
-    public function encodeCreateAlarm( &$uri , &$params , &$criteria , $original ){
-      	
-        if(!isset($params['schedulable']) || !isset($params['rangeStart']) || !isset($params['rangeEnd']) )
-        {
-            $participant = Controller::read( array( 'concept' => 'participant' , 'id' => $params['participant'] ) , array('schedulable')  ); 
-            $schedulable = Controller::read( array( 'concept' => 'schedulable' , 'id' => $participant['schedulable'] ) , array('startTime' , 'endTime' )  );
-
-            $params['schedulable'] = $participant['schedulable'];
-            $params['rangeStart'] = strtotime('- '.$params['time'].' '.self::codeAlarmUnit($params['unit']) , (int)($schedulable['startTime'] / 1000)).'000';
-            $params['rangeEnd'] = $schedulable['endTime'];
-        }
-        
-        $params['type']	= self::codeAlarmType($params['type']);
-        
-        }  
-	
-	public function encodeCreateSuggestion( &$uri , &$params , &$criteria , $original ){			
-    	$params['dtstamp'] = (isset($params['dtstamp'])) ? $params['dtstamp'] :time().'000';          
-    }	
-	
-	public function encodeUpdateAlarm( &$uri , &$params , &$criteria , $original ){
-            if(isset($params['type']))
-                $params['type'] = self::codeAlarmType($params['type']);
-	}
-        
-    public function encodeCreateAttachment( &$uri , &$params , &$criteria , $original ){
-	
-		if(!isset($params['source'])) return false;
-		
-		if(isset($_FILES[$params['source']]))
-			if(isset($params['id']))
-				$params =  array_merge($_FILES[$params['source']], array('id' => $params['id']));
-			else
-				$params =  $_FILES[$params['source']];
-		
-		if(isset($params['owner']))
-			$params['owner'] = Config::me('uidNumber');
-		
-	}
+	if (!is_numeric($params['startTime']))
+	    $params['startTime'] = self::parseTimeDate($params['startTime'], $params['timezone']);
+
+	if (!is_numeric($params['endTime'])) {
+	    $params['endTime'] = self::parseTimeDate($params['endTime'], $params['timezone']);
+
+	    if ($params['allDay'])
+		$params['endTime'] = $params['endTime'] + 86400000;
+	}
+	//        if( !isset( $new['repeat'] ))
+	//            $new['range_end'] = '7287926400'; // 12/12/2200
+	//        else
+	$params['rangeEnd'] = $params['endTime'];
+	$params['rangeStart'] = $params['startTime'];
+
+	///////////////////////////////////////////////////////////////////
+
+	$params['dtstamp'] = (isset($params['dtstamp'])) ? $params['dtstamp'] : time() . '000';
+	$params['lastUpdate'] = (isset($params['lastUpdate'])) ? $params['lastUpdate'] : time() . '000';
+	$params['type'] = EVENT_ID;
+	$params['uid'] = isset($params['uid']) ? $params['uid'] : $this->_makeUid();
+    }
+
+    static function parseTimeDate($time, $timezone) {
+	return strtotime($time . ' ' . $timezone) . '000';
+    }
+
+    public function encodeCreateAlarm(&$uri, &$params, &$criteria, $original) {
+
+	if (!isset($params['schedulable']) || !isset($params['rangeStart']) || !isset($params['rangeEnd'])) {
+	    $participant = Controller::read(array('concept' => 'participant', 'id' => $params['participant']), array('schedulable'));
+	    $schedulable = Controller::read(array('concept' => 'schedulable', 'id' => $participant['schedulable']), array('startTime', 'endTime'));
+
+	    $params['schedulable'] = $participant['schedulable'];
+	    $params['rangeStart'] = strtotime('- ' . $params['time'] . ' ' . self::codeAlarmUnit($params['unit']), (int) ($schedulable['startTime'] / 1000)) . '000';
+	    $params['rangeEnd'] = $schedulable['endTime'];
+	}
+
+	$params['type'] = self::codeAlarmType($params['type']);
+    }
+
+    public function encodeCreateSuggestion(&$uri, &$params, &$criteria, $original) {
+	$params['dtstamp'] = (isset($params['dtstamp'])) ? $params['dtstamp'] : time() . '000';
+    }
+
+    public function encodeUpdateAlarm(&$uri, &$params, &$criteria, $original) {
+	if (isset($params['type']))
+	    $params['type'] = self::codeAlarmType($params['type']);
+    }
+
+    public function encodeCreateAttachment(&$uri, &$params, &$criteria, $original) {
+
+	if (!isset($params['source']))
+	    return false;
+
+	if (isset($_FILES[$params['source']]))
+	    if (isset($params['id']))
+		$params = array_merge($_FILES[$params['source']], array('id' => $params['id']));
+	    else
+		$params = $_FILES[$params['source']];
+
+	if (isset($params['owner']))
+	    $params['owner'] = Config::me('uidNumber');
+    }
 
 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
-	
-    public function encodeSignatureAlarmType( &$uri , &$params , &$criteria , $original ){
-	$params['type']	= self::codeAlarmType($params['type']);
-    }  
-	
-
-    public function insertOwnerLink (&$uri , &$params , &$criteria , $original ){
-            $params['owner'] = Config::me('uidNumber'); 
-      }  
-       
-    public function encodeServiceUser (&$uri , &$params , &$criteria , $original ){
-           if(isset($params['isExternal']) && $params['isExternal'] == '1')
-                $uri['service'] = 'PostgreSQL'; 
-    }
-
-    public function prepareRepeat(&$uri , &$params , &$criteria , $original ){
-
-	if( isset($params['startTime']) || isset($params['endTime']) )
-	{
-	  $timezone = Controller::read( array( 'concept' => 'schedulable', 'id' => $params['schedulable'] ), array('timezone') );
-
-	  if( isset($params['startTime']) )
-	    $params['startTime'] = self::parseTimeDate( $params['startTime'], $timezone['timezone'] );
-	  if( isset($params['endTime']) )
-	    $params['endTime'] = self::parseTimeDate( $params['endTime'], $timezone['timezone'] );
-	}
-    }
-      
-    public function findSchedulable( &$uri , &$params , &$criteria , $original )
-   {
-       if(isset($criteria['filter'][3][1]) && $criteria['filter'][3][1] == 'calendar')
-       {
-	  $start = $criteria['filter'][1][2];
-	  $end = $criteria['filter'][2][2];
-
-	  $ids = array();
-	  $occ = array();
-
-	  if( $occurrences = self::checkOccurrences( $start, $end ) )
-	      foreach( $occurrences as $id => $occurrence )
-	      {
-		  $ids[] = $id;
-		  $occ[] = $occurrence;
-	      }
-
-         $sql = ' SELECT calendar_object.id as id ,calendar_object.cal_uid as "uid", calendar_object.type_id as "type", calendar_object.dtstart as "startTime", calendar_object.summary as "summary", calendar_object.description as "description", calendar_object.dtend as "endTime" , calendar_object.location as "location", calendar_object.allday as "allDay", calendar_object.transp as "transparent", calendar_object.class_id as "class", calendar_object.repeat as "repeat", calendar_object.range_start as "rangeStart",calendar_object.range_end as "rangeEnd", calendar_object.last_update as "lastUpdate", calendar_object.dtstamp as "dtstamp", calendar_object.sequence as "sequence",  calendar_object.tzid as "timezone" ,calendar_to_calendar_object.calendar_id as calendar FROM calendar_to_calendar_object , calendar_object WHERE (range_start >= \''.$start.'\' AND range_end <= \''.$end.'\' AND calendar_to_calendar_object.calendar_id IN (\''.  implode('\',\'', $criteria['filter'][3][2]).'\')) AND calendar_to_calendar_object.calendar_object_id = calendar_object.id'.( !empty($ids) ? ' AND calendar_object.id NOT IN (\'' .implode( '\',\'', $ids ). '\')' : '');
-
-	 $params = Controller::service('PostgreSQL')->execResultSql($sql);
-
-	 $params = array_merge( $params, $occ );
-         $params = self::deepnessFindEvent( $uri , $params , $criteria , $original);
-
-         return false;
-       }
-   }
-
-  public function deepnessFindRepeatOccurrence( &$uri , &$result , &$criteria , $original )
-  {
-
-    if( !isset($criteria['deepness']) || $criteria['deepness'] == 0 )
-	  return;
-
-      foreach( $result as $i => &$res )
-	  if( isset($res['repeat']) )
-	      $res['repeat'] = Controller::read( array( 'concept' => 'repeat', 'id' => $res['repeat'] ), false, array( 'deepness' => intval( $criteria['deepness'] ) - 1 ) );
-  }
-
-  public function deepnessRepeat( &$uri , &$result , &$criteria , $original )
-  {
-
-      if( !isset($criteria['deepness']) || $criteria['deepness'] == 0 )
-	  return;
-
-	$result['schedulable'] = Controller::find( array( 'concept' => 'schedulable' ), false, array( 'filter' => array( '=', 'id', $result['schedulable'] ), 'deepness' => intval( $criteria['deepness'] ) - 1 ) );
+
+    public function encodeSignatureAlarmType(&$uri, &$params, &$criteria, $original) {
+	$params['type'] = self::codeAlarmType($params['type']);
+    }
+
+    public function insertOwnerLink(&$uri, &$params, &$criteria, $original) {
+	$params['owner'] = Config::me('uidNumber');
+    }
+
+    public function encodeServiceUser(&$uri, &$params, &$criteria, $original) {
+	if (isset($params['isExternal']) && $params['isExternal'] == '1')
+	    $uri['service'] = 'PostgreSQL';
+    }
+
+    public function prepareRepeat(&$uri, &$params, &$criteria, $original) {
+
+	if (isset($params['startTime']) || isset($params['endTime'])) {
+	    $timezone = Controller::read(array('concept' => 'schedulable', 'id' => $params['schedulable']), array('timezone'));
+
+	    if (isset($params['startTime']))
+		$params['startTime'] = self::parseTimeDate($params['startTime'], $timezone['timezone']);
+	    if (isset($params['endTime']))
+		$params['endTime'] = self::parseTimeDate($params['endTime'], $timezone['timezone']);
+	}
+    }
+
+    public function findSchedulable(&$uri, &$params, &$criteria, $original) {
+	if (isset($criteria['filter'][3][1]) && $criteria['filter'][3][1] == 'calendar') {
+	    $start = $criteria['filter'][1][2];
+	    $end = $criteria['filter'][2][2];
+
+	    $ids = array();
+	    $occ = array();
+
+	    if ($occurrences = self::checkOccurrences($start, $end))
+		foreach ($occurrences as $id => $occurrence) {
+		    $ids[] = $id;
+		    $occ[] = $occurrence;
+		}
+
+	    $sql = ' SELECT calendar_object.id as id ,calendar_object.cal_uid as "uid", calendar_object.type_id as "type", calendar_object.dtstart as "startTime", calendar_object.summary as "summary", calendar_object.description as "description", calendar_object.dtend as "endTime" , calendar_object.location as "location", calendar_object.allday as "allDay", calendar_object.transp as "transparent", calendar_object.class_id as "class", calendar_object.repeat as "repeat", calendar_object.range_start as "rangeStart",calendar_object.range_end as "rangeEnd", calendar_object.last_update as "lastUpdate", calendar_object.dtstamp as "dtstamp", calendar_object.sequence as "sequence",  calendar_object.tzid as "timezone" ,calendar_to_calendar_object.calendar_id as calendar FROM calendar_to_calendar_object , calendar_object WHERE (range_start >= \'' . $start . '\' AND range_end <= \'' . $end . '\' AND calendar_to_calendar_object.calendar_id IN (\'' . implode('\',\'', $criteria['filter'][3][2]) . '\')) AND calendar_to_calendar_object.calendar_object_id = calendar_object.id' . (!empty($ids) ? ' AND calendar_object.id NOT IN (\'' . implode('\',\'', $ids) . '\')' : '');
+
+	    $params = Controller::service('PostgreSQL')->execResultSql($sql);
+
+	    $params = array_merge($params, $occ);
+	    $params = self::deepnessFindEvent($uri, $params, $criteria, $original);
+
+	    return false;
+	}
+    }
+
+    public function deepnessFindRepeatOccurrence(&$uri, &$result, &$criteria, $original) {
+
+	if (!isset($criteria['deepness']) || $criteria['deepness'] == 0)
+	    return;
+
+	foreach ($result as $i => &$res)
+	    if (isset($res['repeat']))
+		$res['repeat'] = Controller::read(array('concept' => 'repeat', 'id' => $res['repeat']), false, array('deepness' => intval($criteria['deepness']) - 1));
+    }
+
+    public function deepnessRepeat(&$uri, &$result, &$criteria, $original) {
+
+	if (!isset($criteria['deepness']) || $criteria['deepness'] == 0)
+	    return;
+
+	$result['schedulable'] = Controller::find(array('concept' => 'schedulable'), false, array('filter' => array('=', 'id', $result['schedulable']), 'deepness' => intval($criteria['deepness']) - 1));
 	$result['schedulable'] = $result['schedulable'][0];
-  }
-
-public function saveOccurrences( &$uri , &$result , &$criteria , $original ){
-        $ranges = Controller::find( array( 'concept' => 'repeatRange' ), array( 'rangeStart', 'rangeEnd' ),  array( 'filter' => array( '=', 'user', Config::me("uidNumber") ) ) );
-
-	if( !is_array( $ranges ) || !isset( $ranges[0]['rangeStart'] ) || !isset( $ranges[0]['rangeEnd'] ) )
+    }
+
+    public function saveOccurrences(&$uri, &$result, &$criteria, $original) {
+	$ranges = Controller::find(array('concept' => 'repeatRange'), array('rangeStart', 'rangeEnd'), array('filter' => array('=', 'user', Config::me("uidNumber"))));
+
+	if (!is_array($ranges) || !isset($ranges[0]['rangeStart']) || !isset($ranges[0]['rangeEnd']))
 	    return;
 
-	if( isset( $result['id'] ) )
-	     $id = $result['id'];
+	if (isset($result['id']))
+	    $id = $result['id'];
 	else
-	     $id = $uri['id']; 
-
-	$repeat = Controller::read( array( 'concept' => 'repeat', 'id' => $id ) );
-
-	unset( $repeat['schedulable'] );
-	unset( $repeat['id'] );
+	    $id = $uri['id'];
+
+	$repeat = Controller::read(array('concept' => 'repeat', 'id' => $id));
+
+	unset($repeat['schedulable']);
+	unset($repeat['id']);
 
 	$exceptions = array();
 
-	if( isset( $original['properties']['exceptions'] ) )
-	{
-	    $exceptions = explode( ',', $original['properties']['exceptions'] );
-	    unset( $repeat['exceptions'] );
-	}
-
-        $lastExceptions = Controller::find( array( 'concept' => 'repeatOccurrence' ), array("occurrence") , array( 'filter' => array('AND', array( '=', 'repeat', $id ) , array( '=', 'exception', 1 ) ) ));
-	
-        //Recurepa as execeções anteriores caso exista
-        if(isset($lastExceptions) && count($lastExceptions) && $lastExceptions)
-            foreach($lastExceptions as $key => $value)
-                array_push($exceptions, $lastExceptions[$key]['occurrence']);
-        
-	$params = array_diff( self::decodeRepeat( $repeat, $ranges[0]['rangeStart'], $ranges[0]['rangeEnd'] ), $exceptions );
-        
-	Controller::delete( array( 'concept' => 'repeatOccurrence' ), false, array( 'filter' => array( '=', 'repeat', $id ) ) );
-
-	if( !empty($params) )
-	    Controller::service('PostgreSQL')->execResultSql( "INSERT INTO calendar_repeat_occurrence(repeat_id,exception,occurrence)VALUES('".$id."','0','".implode( "'),('".$id."','0','", $params )."')".( empty($exceptions) ? "" : ",('".$id."','1','".implode( "'),('".$id."','1','", $exceptions )."')" ) );
-    }
-
-    public function checkOccurrences( $start, $end ){
-
-	$ranges = Controller::find( array( 'concept' => 'repeatRange' ), array( 'rangeStart', 'rangeEnd' ),  array( 'filter' => array( '=', 'user', Config::me("uidNumber") ) ) );
+	if (isset($original['properties']['exceptions'])) {
+	    $exceptions = explode(',', $original['properties']['exceptions']);
+	    unset($repeat['exceptions']);
+	}
+
+	$lastExceptions = Controller::find(array('concept' => 'repeatOccurrence'), array("occurrence"), array('filter' => array('AND', array('=', 'repeat', $id), array('=', 'exception', 1))));
+
+	//Recurepa as execeções anteriores caso exista
+	if (isset($lastExceptions) && count($lastExceptions) && $lastExceptions)
+	    foreach ($lastExceptions as $key => $value)
+		array_push($exceptions, $lastExceptions[$key]['occurrence']);
+
+	$params = array_diff(self::decodeRepeat($repeat, $ranges[0]['rangeStart'], $ranges[0]['rangeEnd']), $exceptions);
+
+	Controller::delete(array('concept' => 'repeatOccurrence'), false, array('filter' => array('=', 'repeat', $id)));
+
+	if (!empty($params))
+	    Controller::service('PostgreSQL')->execResultSql("INSERT INTO calendar_repeat_occurrence(repeat_id,exception,occurrence)VALUES('" . $id . "','0','" . implode("'),('" . $id . "','0','", $params) . "')" . ( empty($exceptions) ? "" : ",('" . $id . "','1','" . implode("'),('" . $id . "','1','", $exceptions) . "')" ));
+    }
+
+    public function checkOccurrences($start, $end) {
+
+	$ranges = Controller::find(array('concept' => 'repeatRange'), array('rangeStart', 'rangeEnd'), array('filter' => array('=', 'user', Config::me("uidNumber"))));
 	$ranges = $ranges[0];
 
@@ -202,9 +193,8 @@
 	$origEnd = $end;
 
-	if( $initialized = (isset($ranges['rangeStart']) && isset($ranges['rangeEnd'])) )
-	{
-	    if( $ranges['rangeStart'] <= $start )
+	if ($initialized = (isset($ranges['rangeStart']) && isset($ranges['rangeEnd']))) {
+	    if ($ranges['rangeStart'] <= $start)
 		$start = false;
-	    if( $ranges['rangeEnd'] >= $end )
+	    if ($ranges['rangeEnd'] >= $end)
 		$end = false;
 	}
@@ -212,5 +202,5 @@
 	$repeats = self::findRepeats();
 
-	if( !is_array( $repeats ) || empty( $repeats ) )
+	if (!is_array($repeats) || empty($repeats))
 	    return( false );
 
@@ -218,73 +208,69 @@
 	$ids = array();
 
-	foreach( $repeats as $repeat )
-	{
-	    $ids[] = $id = $repeat['id']; unset( $repeat['id'] ); 
-
-	    if( !isset( $result[ $id ] ) )
-                $result[ $id ] = !$initialized ?  array( $repeat['startTime'] ) : array();
-
-	    if( !$initialized )
-		$result[ $id ] = array_merge( $result[ $id ], self::decodeRepeat( $repeat, $start, $end ) );
-	    else
-	    {
-		if( $start )
-		    $result[ $id ] = array_merge( $result[ $id ], self::decodeRepeat( $repeat, $start, $ranges['rangeStart'] ) );
-
-		if( $end )
-		    $result[ $id ] = array_merge( $result[ $id ], self::decodeRepeat( $repeat, $ranges['rangeEnd'], $end ) );
-	    }
-
-	    if( empty( $result[ $id ] ) )
-		unset( $result[ $id ] );
-	}
-
-	if( $start || $end )
-	{
-	    Controller::begin( array( 'service' => 'PostgreSQL') );
-
-	    foreach( $result as $id => $res )
-		Controller::service('PostgreSQL')->execResultSql( "INSERT INTO calendar_repeat_occurrence(repeat_id,occurrence)VALUES('".$id."','".implode( "'),('".$id."', '", $res )."')" );
+	foreach ($repeats as $repeat) {
+	    $ids[] = $id = $repeat['id'];
+	    unset($repeat['id']);
+
+	    if (!isset($result[$id]))
+		$result[$id] = !$initialized ? array($repeat['startTime']) : array();
+
+	    if (!$initialized)
+		$result[$id] = array_merge($result[$id], self::decodeRepeat($repeat, $start, $end));
+	    else {
+		if ($start)
+		    $result[$id] = array_merge($result[$id], self::decodeRepeat($repeat, $start, $ranges['rangeStart']));
+
+		if ($end)
+		    $result[$id] = array_merge($result[$id], self::decodeRepeat($repeat, $ranges['rangeEnd'], $end));
+	    }
+
+	    if (empty($result[$id]))
+		unset($result[$id]);
+	}
+
+	if ($start || $end) {
+	    Controller::begin(array('service' => 'PostgreSQL'));
+
+	    foreach ($result as $id => $res)
+		Controller::service('PostgreSQL')->execResultSql("INSERT INTO calendar_repeat_occurrence(repeat_id,occurrence)VALUES('" . $id . "','" . implode("'),('" . $id . "', '", $res) . "')");
 
 	    $data = array();
 
-	    if( $start )
+	    if ($start)
 		$data['rangeStart'] = $start;
 
-	    if( $end )
+	    if ($end)
 		$data['rangeEnd'] = $end;
 
-	    if( !$initialized )
-		$data['user'] = Config::me( 'uidNumber' );
-
-	    Controller::call( ( $initialized ? 'replace' : 'create' ), array( 'concept' => 'repeatRange' ), $data, array( 'filter' => array( '=', 'user', Config::me('uidNumber') ) ) );
-
-	    Controller::commit( array( 'service' => 'PostgreSQL' ) );
+	    if (!$initialized)
+		$data['user'] = Config::me('uidNumber');
+
+	    Controller::call(( $initialized ? 'replace' : 'create'), array('concept' => 'repeatRange'), $data, array('filter' => array('=', 'user', Config::me('uidNumber'))));
+
+	    Controller::commit(array('service' => 'PostgreSQL'));
 	}
 
 // 	$return = Controller::find( array( 'concept' => 'repeatOccurrence' ), false, array( 'filter' => array( 'AND', array( '>=', 'occurrence', $origStart ), array( '<=', 'occurrence', $origEnd ), array( 'IN', 'repeat', $ids ) ), 'deepness' => $deep ) );
 
-	$return = Controller::service('PostgreSQL')->execResultSql( 'SELECT calendar_repeat_occurrence.occurrence as "occurrence", calendar_repeat.object_id as "schedulable" FROM calendar_repeat, calendar_repeat_occurrence WHERE calendar_repeat_occurrence.occurrence >= \''.$origStart.'\' AND calendar_repeat_occurrence.occurrence <= \''.$origEnd.'\' AND calendar_repeat_occurrence.repeat_id IN (\''.implode( '\',\'', $ids ).'\') AND calendar_repeat.id = calendar_repeat_occurrence.repeat_id AND calendar_repeat_occurrence.exception != 1' );
-
-	if( !is_array( $return ) )
-	  return( false );
+	$return = Controller::service('PostgreSQL')->execResultSql('SELECT calendar_repeat_occurrence.occurrence as "occurrence", calendar_repeat.object_id as "schedulable" FROM calendar_repeat, calendar_repeat_occurrence WHERE calendar_repeat_occurrence.occurrence >= \'' . $origStart . '\' AND calendar_repeat_occurrence.occurrence <= \'' . $origEnd . '\' AND calendar_repeat_occurrence.repeat_id IN (\'' . implode('\',\'', $ids) . '\') AND calendar_repeat.id = calendar_repeat_occurrence.repeat_id AND calendar_repeat_occurrence.exception != 1');
+
+	if (!is_array($return))
+	    return( false );
 
 	$result = array();
 	$params = array();
 
-	foreach( $return as $ret )
-	{
-	      $currentId = $ret['schedulable'];
-
-	      if( !isset( $result[ $currentId ] ) )
-	      {
-		    $result[ $currentId ] = Controller::read( array( 'concept' => 'schedulable', 'id' => $currentId ) );
-		    $result[ $currentId ][ 'occurrences' ] = array();
-
-		    $calendarToCalendarObj = self::schedulable2calendarToObject( $currentId );
-		    $result[ $currentId ]['calendar'] = $calendarToCalendarObj[0]['calendar_id'];
-	      }
-      
-	      $result[ $currentId  ][ 'occurrences' ][] = $ret['occurrence'];
+	foreach ($return as $ret) {
+	    $currentId = $ret['schedulable'];
+
+	    if (!isset($result[$currentId])) {
+		$result[$currentId] = Controller::read(array('concept' => 'schedulable', 'id' => $currentId));
+		$result[$currentId]['occurrences'] = array();
+
+		$calendarToCalendarObj = self::schedulable2calendarToObject($currentId);
+		$result[$currentId]['calendar'] = $calendarToCalendarObj[0]['calendar_id'];
+	    }
+
+	    $result[$currentId]['occurrences'][] = $ret['occurrence'];
 	}
 
@@ -292,539 +278,498 @@
     }
 
-    public static function findRepeats()
-    {
-	return Controller::service('PostgreSQL')->execResultSql( 'SELECT calendar_repeat.wkst as "wkst", calendar_repeat.byweekno as "byweekno", calendar_repeat.byminute as "byminute", calendar_repeat.bysecond as "bysecond", calendar_repeat.byyearday as "byyearday", calendar_repeat.bymonthday as "bymonthday", calendar_repeat.bysetpos as "bysetpos", calendar_repeat.byday as "byday", calendar_repeat.byhour as "byhour", calendar_repeat.interval as "interval", calendar_repeat.frequency as "frequency", calendar_repeat.until as "endTime", calendar_repeat.id as "id", calendar_repeat.count as "count", calendar_repeat.dtstart as "startTime" FROM calendar_repeat, calendar_participant WHERE calendar_repeat.object_id = calendar_participant.object_id AND calendar_participant.user_info_id = \''.Config::me('uidNumber').'\'' );
-    }
-	
+    public static function findRepeats() {
+	return Controller::service('PostgreSQL')->execResultSql('SELECT calendar_repeat.wkst as "wkst", calendar_repeat.byweekno as "byweekno", calendar_repeat.byminute as "byminute", calendar_repeat.bysecond as "bysecond", calendar_repeat.byyearday as "byyearday", calendar_repeat.bymonthday as "bymonthday", calendar_repeat.bysetpos as "bysetpos", calendar_repeat.byday as "byday", calendar_repeat.byhour as "byhour", calendar_repeat.interval as "interval", calendar_repeat.frequency as "frequency", calendar_repeat.until as "endTime", calendar_repeat.id as "id", calendar_repeat.count as "count", calendar_repeat.dtstart as "startTime" FROM calendar_repeat, calendar_participant WHERE calendar_repeat.object_id = calendar_participant.object_id AND calendar_participant.user_info_id = \'' . Config::me('uidNumber') . '\'');
+    }
+
 //HELPERS
-    public static function decodeRepeat( $repeat , $start , $end ) {
-
-    date_default_timezone_set( 'UTC' );
-
-    require_once ROOTPATH.'/plugins/when/When.php';
-
-    $r = new When();
-
-    if( $repeat['frequency'] === 'none' )
-	return( array() );
- 
-    //Nao deve ser usando o horário da repeticao pois nela contem apenas o dias,
-    //deve se recuperar o horário do evento para um correto calculo.
-    if(max( $start, $repeat['startTime']  ) != $repeat['startTime']){
-	$time = new DateTime( '@'.(int)( $repeat['startTime'] / 1000 ), new DateTimeZone('UTC') );
-	
-	$hoursOcurrence = new DateTime( '@'.(int)( $start / 1000 ), new DateTimeZone('UTC') );
-	$hoursOcurrence = $hoursOcurrence->format('H');
-	
-	$diffTime = ((($time->format('H') - $hoursOcurrence) * (3600000)) + ($time->format('i') * (60000)));
-	$start =  new DateTime( '@'.(int)( ( $start + $diffTime )  / 1000 ), new DateTimeZone('UTC') );    
-	
-	
-    }else
-	$start =  new DateTime( '@'.(int)( max( $start, $repeat['startTime']  ) / 1000 ), new DateTimeZone('UTC') );    
-    
-    foreach($repeat as $rule => $value)
-    {
-	    if( !isset( $value ) || !$value || $value === "0" )
+    public static function decodeRepeat($repeat, $start, $end) {
+
+	date_default_timezone_set('UTC');
+
+	require_once ROOTPATH . '/plugins/when/When.php';
+
+	$r = new When();
+
+	if ($repeat['frequency'] === 'none')
+	    return( array() );
+
+	//Nao deve ser usando o horário da repeticao pois nela contem apenas o dias,
+	//deve se recuperar o horário do evento para um correto calculo.
+	if (max($start, $repeat['startTime']) != $repeat['startTime']) {
+	    $time = new DateTime('@' . (int) ( $repeat['startTime'] / 1000 ), new DateTimeZone('UTC'));
+
+	    $hoursOcurrence = new DateTime('@' . (int) ( $start / 1000 ), new DateTimeZone('UTC'));
+	    $hoursOcurrence = $hoursOcurrence->format('H');
+
+	    $diffTime = ((($time->format('H') - $hoursOcurrence) * (3600000)) + ($time->format('i') * (60000)));
+	    $start = new DateTime('@' . (int) ( ( $start + $diffTime ) / 1000 ), new DateTimeZone('UTC'));
+	}else
+	    $start = new DateTime('@' . (int) ( max($start, $repeat['startTime']) / 1000 ), new DateTimeZone('UTC'));
+
+	foreach ($repeat as $rule => $value) {
+	    if (!isset($value) || !$value || $value === "0")
 		continue;
 
-            switch(strtolower($rule))
-            {
-		    case "starttime": break;
-		    case "frequency":
-			    $r->recur( $start, $value );
-			    break;
-		    case "endtime":
-                            $r->until( new DateTime( '@'.(int)( $value / 1000 ) ) );
-                            break;
-                    case "count": case "interval":  case "wkst":
-                            $r->$rule( $value );
-                            break;
-                    default :
-                            $r->$rule( !is_array( $value ) ? explode( ',' , $value ) : $value );
-                            break;
-            }
-    }
-
-    $return = array();
-    
-    while($result = $r->next())
-    { 
-       $u = $result->format('U') * 1000;
-
-       if( $u  > $end ) //data da repetição atual maior que a data final da busca do usuario ?
-           break;
-
-      $return[] = $u;
-    }
-
-    return( $return );
-}
-   
+	    switch (strtolower($rule)) {
+		case "starttime": break;
+		case "frequency":
+		    $r->recur($start, $value);
+		    break;
+		case "endtime":
+		    $r->until(new DateTime('@' . (int) ( $value / 1000 )));
+		    break;
+		case "count": case "interval": case "wkst":
+		    $r->$rule($value);
+		    break;
+		default :
+		    $r->$rule(!is_array($value) ? explode(',', $value) : $value );
+		    break;
+	    }
+	}
+
+	$return = array();
+
+	while ($result = $r->next()) {
+	    $u = $result->format('U') * 1000;
+
+	    if ($u > $end) //data da repetição atual maior que a data final da busca do usuario ?
+		break;
+
+	    $return[] = $u;
+	}
+
+	return( $return );
+    }
+
 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
 
-    public function updateCalendar( &$uri , &$params , &$criteria , $original ){
-        if( isset($params['calendar']))
-        { 
-            $calendarObjects = self::schedulable2calendarToObject( $uri['id'] );
-            $params2['calendar'] = $params['calendar']; 
-           
-            foreach ($calendarObjects as $calendarObject)
-                Controller::update( array('concept' => 'calendarToSchedulable' , 'id' => $calendarObject['calendar_to_calendar_object']) , $params2 );
-         
-            unset( $params['calendar'] );
-            
-            if(count($params) < 1) return false;
-        }
-    } 
-     
+    public function updateCalendar(&$uri, &$params, &$criteria, $original) {
+	if (isset($params['calendar'])) {
+	    $calendarObjects = self::schedulable2calendarToObject($uri['id']);
+	    $params2['calendar'] = $params['calendar'];
+
+	    foreach ($calendarObjects as $calendarObject)
+		Controller::update(array('concept' => 'calendarToSchedulable', 'id' => $calendarObject['calendar_to_calendar_object']), $params2);
+
+	    unset($params['calendar']);
+
+	    if (count($params) < 1)
+		return false;
+	}
+    }
+
 //Encode Update
 
-    public function encodeUpdateSchedulable( &$uri , &$params , &$criteria , $original ){	
-	
-		$event = Controller::find( array( 'concept' => 'schedulable' , array('timezone', 'allDay') ,'id' => $params['id'] ) );	
-		
-		if(isset($params['startTime'])){
-			
-			if(!is_numeric($params['startTime']) )
-				$params['startTime'] =  strtotime( $params['startTime'] . ' ' .$event['timezone']).'000';
-			
-			$params['rangeStart'] = $params['startTime'] ;
-		   
-		}if(isset($params['endTime'])){
-			
-			if (!is_numeric($params['endTime'])){
-				$params['endTime'] =   strtotime( $params['endTime'] . ' ' .$event['timezone']).'000';
-				
-				if($event['allDay'])
-					$params['endTime'] =  $params['endTime']  + 86400000;
+    public function encodeUpdateSchedulable(&$uri, &$params, &$criteria, $original) {
+
+	$event = Controller::find(array('concept' => 'schedulable', array('timezone', 'allDay'), 'id' => $params['id']));
+
+	if (isset($params['startTime'])) {
+
+	    if (!is_numeric($params['startTime']))
+		$params['startTime'] = strtotime($params['startTime'] . ' ' . $event['timezone']) . '000';
+
+	    $params['rangeStart'] = $params['startTime'];
+	}if (isset($params['endTime'])) {
+
+	    if (!is_numeric($params['endTime'])) {
+		$params['endTime'] = strtotime($params['endTime'] . ' ' . $event['timezone']) . '000';
+
+		if ($event['allDay'])
+		    $params['endTime'] = $params['endTime'] + 86400000;
+	    }
+	    $params['rangeEnd'] = $params['endTime'];
+	}
+    }
+
+    static function putEvent(&$uri, &$result, &$criteria, $original) {
+	if (Config::module('useCaldav', 'expressoCalendar')) { //Ignorar Put dos eventos ja vindos do caldav
+	    require_once ROOTPATH . '/modules/calendar/interceptors/DAViCalAdapter.php';
+
+	    $eventID = (isset($result['id'])) ? $result['id'] : $uri['id'];
+	    $event = Controller::read(array('concept' => 'schedulable', 'id' => $eventID));
+
+	    $participants = Controller::find(array('concept' => 'participant'), false, array('filter' => array('=', 'schedulable', $eventID)));
+
+	    if (is_array($participants) && count($participants) > 0)
+		foreach ($participants as $ii => $vv) {
+		    if ($vv['isExternal'] == 1)
+			$participants[$ii]['user'] = Controller::read(array('concept' => 'user', 'id' => $vv['user'], 'service' => 'PostgreSQL'));
+		    else
+			$participants[$ii]['user'] = Controller::read(array('concept' => 'user', 'id' => $vv['user']));
+		}
+
+	    $event['URI']['concept'] = 'schedulable';
+	    $event['participants'] = $participants;
+
+	    $ical = Controller::format(array('service' => 'iCal'), array($event));
+	    $calendars = self::schedulable2calendarToObject($original['properties']['id']); //Busca os calendarios do usuario logado que contenham o evento
+	    if (is_array($calendars))
+		foreach ($calendars as $calendar)
+		    DAViCalAdapter::putIcal($ical, array('uid' => $event['uid'], 'location' => $calendar['calendar_location']));
+	}
+    }
+
+///////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+    public function verifyCalendarLocation(&$uri, &$params, &$criteria, $original) {
+	if (!isset($params['location']))
+	    $params['location'] = Config::me('uid') . '/' . $params['name'];
+    }
+
+    //TODO: Remover apos suporte a ManytoMany na api 
+    public function createCalendarToSchedulable(&$uri, &$result, &$criteria, $original) {
+
+	Controller::create(array('concept' => 'calendarToSchedulable'), array('calendar' => $original['properties']['calendar'], 'schedulable' => $result['id']));
+    }
+
+    public function createCreateSchedulableToAttachment(&$uri, &$params, &$criteria, $original) {
+	if (array_key_exists('attachments', $original['properties']))
+	    foreach ($original['properties']['attachments'] as $key => $value) {
+		if (isset($params['id']))
+		    Controller::create(array('concept' => 'schedulableToAttachment'), array('attachment' => $value['attachment'], 'schedulable' => $params['id']));
+	    }
+    }
+
+    public function deepnessFindCalendarShared(&$uri, &$result, &$criteria, $original) {
+	if (isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != '0' && count($result) > 0) {
+	    $calendarIds = array();
+	    foreach ($result as $key => $value)
+		array_push($calendarIds, $value['calendar']);
+
+	    $calendar = Controller::find(array('concept' => 'calendar'), false, array('filter' => array('AND', array('IN', 'id', $calendarIds), $original['criteria']['filter'])));
+
+	    if (!is_array($calendar))
+		$result = '';
+
+	    $newResult = array();
+	    foreach ($calendar as $key => $value) {
+		foreach ($result as $k => $r) {
+
+		    if ($r['calendar'] == $value['id']) {
+			$r['calendar'] = $value;
+			array_push($newResult, $r);
+		    }
+		}
+	    }
+
+	    foreach ($newResult as $key => &$value) {
+		if ($value['user'] != 0) {
+		    $user = $value['user'];
+		    $value['user'] = Controller::read(array('concept' => 'user', 'id' => $user));
+
+		    if (!$value['user'])
+			$value['user'] = Controller::read(array('concept' => 'group', 'id' => $user));
+		}
+	    }
+
+
+	    $result = $newResult;
+	}
+    }
+
+    //TODO: Remover apos suporte a deepness na api 
+    public function deepnessFindEvent(&$uri, &$result, &$criteria, $original) {
+	if (isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0) {
+
+	    $Time = new DateTime('now', new DateTimeZone('UTC'));
+	    $DayLigth = array();
+	    foreach ($result as $i => $v) {
+
+		if (!isset($currentTimezone) || $currentTimezone != $original['criteria']['timezones'][$v['calendar']]) {
+		    $currentTimezone = isset($original['criteria']['timezones'][$v['calendar']]) ? $original['criteria']['timezones'][$v['calendar']] : $v['timezone'];
+		    $Time->setTimezone(new DateTimeZone($currentTimezone));
+		}
+
+		$Time->setTimestamp((int) ($v['startTime'] / 1000));
+		$DayLigth['calendar']['startTime'] = $Time->format('I') ? 1 : 0;
+
+		$Time->setTimestamp((int) ($v['endTime'] / 1000));
+		$DayLigth['calendar']['endTime'] = $Time->format('I') ? 1 : 0;
+
+		if ($currentTimezone != $v['timezone']) {
+		    $currentTimezone = $v['timezone'];
+		    $Time->setTimezone(new DateTimeZone($v['timezone']));
+
+		    $Time->setTimestamp((int) ($v['startTime'] / 1000));
+		    $DayLigth['event']['startTime'] = $Time->format('I') ? 1 : 0;
+
+		    $Time->setTimestamp((int) ($v['endTime'] / 1000));
+		    $DayLigth['event']['endTime'] = $Time->format('I') ? 1 : 0;
+		}else
+		    $DayLigth['event'] = $DayLigth['calendar'];
+
+
+		$result[$i]['DayLigth'] = $DayLigth;
+
+		if (isset($v['id'])) {
+		    $participants = Controller::find(array('concept' => 'participant'), false, array('filter' => array('=', 'schedulable', $v['id'])));
+
+		    if (is_array($participants) && count($participants) > 0)
+			foreach ($participants as $ii => $vv) {
+			    if ($vv['isExternal'] == 1)
+				$participants[$ii]['user'] = Controller::read(array('concept' => 'user', 'id' => $vv['user'], 'service' => 'PostgreSQL'));
+			    else
+				$participants[$ii]['user'] = Controller::read(array('concept' => 'user', 'id' => $vv['user']));
+
+			    if ($participants[$ii]['user']['id'] == Config::me('uidNumber'))
+				$participants[$ii]['alarms'] = Controller::find(array('concept' => 'alarm'), null, array('filter' => array('AND', array('=', 'participant', $vv['id']), array('=', 'schedulable', $v['id']))));
 			}
-			$params['rangeEnd'] = $params['endTime'] ;       
-				
-		}    
-     }        
-     
-    static function putEvent(&$uri , &$result , &$criteria , $original)
-    {          
-            if(Config::module('useCaldav' , 'expressoCalendar')) //Ignorar Put dos eventos ja vindos do caldav
-            {
-                require_once ROOTPATH.'/modules/calendar/interceptors/DAViCalAdapter.php';
-
-                $eventID = (isset($result['id'])) ? $result['id'] : $uri['id'];
-                $event = Controller::read( array( 'concept' => 'schedulable' , 'id' => $eventID ) );
-
-                $participants = Controller::find( array( 'concept' => 'participant' ) , false ,array( 'filter' => array('=' ,  'schedulable' ,  $eventID) )); 
-
-                if(is_array($participants) && count($participants) > 0)
-                    foreach ($participants as $ii => $vv)
-                    {
-                        if($vv['isExternal'] == 1 )
-                            $participants[$ii]['user'] = Controller::read( array( 'concept' => 'user' , 'id' => $vv['user'] , 'service' => 'PostgreSQL' ) );
-                        else
-                           $participants[$ii]['user'] = Controller::read( array( 'concept' => 'user' , 'id' => $vv['user'] ));
-                    } 
-
-                $event['URI']['concept'] = 'schedulable';
-                $event['participants'] = $participants;
-               
-                $ical = Controller::format( array( 'service' => 'iCal' ) , array($event) );                  
-                $calendars =  self::schedulable2calendarToObject($original['properties']['id']); //Busca os calendarios do usuario logado que contenham o evento
-                if( is_array($calendars) )
-                    foreach ($calendars as $calendar)
-                        DAViCalAdapter::putIcal($ical , array('uid' => $event['uid'] , 'location' => $calendar['calendar_location'] ));
-            }
-    } 
-///////////////////////////////////////////////////////////////////////////////////////////////////////////////
-    
-    public function verifyCalendarLocation( &$uri , &$params , &$criteria , $original ){
-        if(!isset($params['location']))
-            $params['location'] = Config::me('uid').'/'.$params['name'];
-    } 
-    
-      
-    //TODO: Remover apos suporte a ManytoMany na api 
-    public function createCalendarToSchedulable( &$uri , &$result , &$criteria , $original ){		
-
-		Controller::create(array('concept' => 'calendarToSchedulable'), array('calendar' => $original['properties']['calendar'], 'schedulable' => $result['id'] ));
-
-   }
-
-	public function createCreateSchedulableToAttachment( &$uri , &$params , &$criteria , $original ){		
-		if(array_key_exists('attachments', $original['properties']))	
-			foreach($original['properties']['attachments'] as $key => $value){				
-				if(isset($params['id']))
-					Controller::create(array('concept' => 'schedulableToAttachment'), array('attachment' => $value['attachment'], 'schedulable' => $params['id'] ));
-			}
-	}
-     
-	 public function deepnessFindCalendarShared( &$uri , &$result , &$criteria , $original ){				
-		if(isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != '0' && count($result) > 0){
-			$calendarIds = array();
-			foreach($result as $key => $value)
-				array_push($calendarIds, $value['calendar']);
-			
-			$calendar = Controller::find( array( 'concept' => 'calendar' ) , false ,array( 'filter' => array('AND', array('IN','id', $calendarIds), $original['criteria']['filter']))); 
-			
-			if(!is_array($calendar))
-				$result = '';
-
-			$newResult = array();
-			foreach($calendar as $key => $value){
-				foreach($result as $k => $r){
-
-					if($r['calendar'] == $value['id']){
-						$r['calendar'] = $value;
-						array_push($newResult, $r);
-					}
-				}
-			}
-			
-			foreach($newResult as $key => &$value){
-                                if($value['user']  != 0){
-                                    $user = $value['user'];
-                                    $value['user'] = Controller::read( array( 'concept' => 'user' , 'id' => $user ));
-
-                                    if(!$value['user'])
-                                        $value['user'] = Controller::read( array( 'concept' => 'group' , 'id' => $user ));
-                                }
-			}
-
-
-		$result = $newResult;
-		}
-    }	
- 
-    //TODO: Remover apos suporte a deepness na api 
-    public function deepnessFindEvent( &$uri , &$result , &$criteria , $original ){
-       if(isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0)
-       {
-			
-            $Time = new DateTime( 'now', new DateTimeZone('UTC') );
-            $DayLigth = array();
-           foreach ($result as $i => $v)
-           {
-
-				if(!isset($currentTimezone) || $currentTimezone  != $original['criteria']['timezones'][$v['calendar']]){
-					$currentTimezone = isset($original['criteria']['timezones'][$v['calendar']]) ?  $original['criteria']['timezones'][$v['calendar']] : $v['timezone'];
-					$Time->setTimezone(new DateTimeZone($currentTimezone));
-				}
-
-				$Time->setTimestamp( (int)($v['startTime'] / 1000));
-				$DayLigth['calendar']['startTime'] =  $Time->format('I') ? 1 : 0;
-				
-				$Time->setTimestamp( (int)($v['endTime'] / 1000));
-				$DayLigth['calendar']['endTime'] =  $Time->format('I') ? 1 : 0;
-				
-				if($currentTimezone != $v['timezone']){
-					$currentTimezone = $v['timezone'];
-					$Time->setTimezone(new DateTimeZone($v['timezone']));
-				
-					$Time->setTimestamp( (int)($v['startTime'] / 1000));
-					$DayLigth['event']['startTime'] =  $Time->format('I') ? 1 : 0;
-
-					$Time->setTimestamp( (int)($v['endTime'] / 1000));
-					$DayLigth['event']['endTime'] =  $Time->format('I') ? 1 : 0;
-				}else
-					$DayLigth['event'] = $DayLigth['calendar'];
-					
-				
-				$result[$i]['DayLigth'] = $DayLigth;
-				
-		if(isset($v['id']))
-		{
-                    $participants = Controller::find( array( 'concept' => 'participant' ) , false ,array( 'filter' => array('=', 'schedulable'  ,  $v['id']) )); 
-                    
-                    if(is_array($participants) && count($participants) > 0)
-                    foreach ($participants as $ii => $vv)
-                    {
-                        if($vv['isExternal'] == 1 )
-                            $participants[$ii]['user'] = Controller::read( array( 'concept' => 'user' , 'id' => $vv['user'] , 'service' => 'PostgreSQL' ) );
-                        else
-                           $participants[$ii]['user'] = Controller::read( array( 'concept' => 'user' , 'id' => $vv['user'] ));
-                    
-                        if($participants[$ii]['user']['id'] == Config::me('uidNumber'))
-                           $participants[$ii]['alarms'] = Controller::find( array( 'concept' => 'alarm' ) , null , array('filter' => array('AND' , array('=', 'participant' ,$vv['id'] ) ,array('=' , 'schedulable', $v['id'])) ) ); 
-                    }       
-                    $result[$i]['participants'] = $participants;
-					
-					
-		    
-		    $attachmentRelation = Controller::find( array( 'concept' => 'schedulableToAttachment' ) , false ,array( 'filter' => array('=', 'schedulable'  ,  $v['id']) )); 
-		    if(is_array($attachmentRelation)){
-			    $attachments = array();
-			    foreach($attachmentRelation as $key => $value)
-				    if(isset($value['attachment']) || !!$value['attachment'])
-					    $attachments[$key]  = $value['attachment'];
-			    //Pega os anexos sem source
-			    $result[$i]['attachments'] = Controller::find( array( 'concept' => 'attachment' ) , array('id', 'name', 'type', 'size') ,array( 'filter' => array('IN', 'id' , $attachments) )); 
+		    $result[$i]['participants'] = $participants;
+
+
+
+		    $attachmentRelation = Controller::find(array('concept' => 'schedulableToAttachment'), false, array('filter' => array('=', 'schedulable', $v['id'])));
+		    if (is_array($attachmentRelation)) {
+			$attachments = array();
+			foreach ($attachmentRelation as $key => $value)
+			    if (isset($value['attachment']) || !!$value['attachment'])
+				$attachments[$key] = $value['attachment'];
+			//Pega os anexos sem source
+			$result[$i]['attachments'] = Controller::find(array('concept' => 'attachment'), array('id', 'name', 'type', 'size'), array('filter' => array('IN', 'id', $attachments)));
 		    }
 
-		    $repeat = Controller::find( array( 'concept' => 'repeat' ), false, array( 'filter' => array( '=', 'schedulable', $v['id'] ) ) );
-
-		    unset( $result[$i]['repeat'] );
-
-		    if( is_array($repeat) )
+		    $repeat = Controller::find(array('concept' => 'repeat'), false, array('filter' => array('=', 'schedulable', $v['id'])));
+
+		    unset($result[$i]['repeat']);
+
+		    if (is_array($repeat))
 			$result[$i]['repeat'] = $repeat[0];
 		}
-                
-           }
-       }
-       
-       return $result;
-       
-   } 
+	    }
+	}
+
+	return $result;
+    }
 
     //TODO: Remover apos suporte a deepness na api 
-    public function deepnessReadEvent( &$uri , &$result , &$criteria , $original ){		
-       
-       if(isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0)
-       {
-            if(isset($result['id']))
-            {
-                $participants = Controller::find( array( 'concept' => 'participant' ) , false ,array( 'filter' => array('=' ,  'schedulable' ,  $result['id']) )); 
-                if(is_array($participants))
-                    foreach ($participants as $ii => $vv)
-                    {
-                        if($vv['isExternal'] == 1 )
-                            $participants[$ii]['user'] = Controller::read( array( 'concept' => 'user' , 'id' => $vv['user'] , 'service' => 'PostgreSQL' ) );
-                        else
-                           $participants[$ii]['user'] = Controller::read( array( 'concept' => 'user' , 'id' => $vv['user'] ));
-
-                        if($participants[$ii]['user']['id'] == Config::me('uidNumber'))
-                           $participants[$ii]['alarms'] = Controller::find( array( 'concept' => 'alarm' ) , null , array('filter' => array('AND' , array('=', 'participant' ,$vv['id'] ) ,array('=' , 'schedulable', $result['id'])) ) ); 
-               }  
-		$repeat =  Controller::find( array( 'concept' => 'repeat' ), false, array( 'filter' => array( '=', 'schedulable', $result['id'] ) ) );
-                if(is_array($repeat))
-		    $result['repeat'] = $repeat[0] ;
-		
+    public function deepnessReadEvent(&$uri, &$result, &$criteria, $original) {
+
+	if (isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0) {
+	    if (isset($result['id'])) {
+		$participants = Controller::find(array('concept' => 'participant'), false, array('filter' => array('=', 'schedulable', $result['id'])));
+		if (is_array($participants))
+		    foreach ($participants as $ii => $vv) {
+			if ($vv['isExternal'] == 1)
+			    $participants[$ii]['user'] = Controller::read(array('concept' => 'user', 'id' => $vv['user'], 'service' => 'PostgreSQL'));
+			else
+			    $participants[$ii]['user'] = Controller::read(array('concept' => 'user', 'id' => $vv['user']));
+
+			if ($participants[$ii]['user']['id'] == Config::me('uidNumber'))
+			    $participants[$ii]['alarms'] = Controller::find(array('concept' => 'alarm'), null, array('filter' => array('AND', array('=', 'participant', $vv['id']), array('=', 'schedulable', $result['id']))));
+		    }
+		$repeat = Controller::find(array('concept' => 'repeat'), false, array('filter' => array('=', 'schedulable', $result['id'])));
+		if (is_array($repeat))
+		    $result['repeat'] = $repeat[0];
+
 		$result['participants'] = $participants;
-                }
-       }
-   } 
-   
+	    }
+	}
+    }
+
     //TODO: Remover apos suporte a deepness na api
-    public function deepnessReadParticipant( &$uri , &$result , &$criteria , $original ){		
-       
-       if(isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0)
-       {
-            if(isset($result['id']))
-            {
-                if($result['isExternal'] == 1 )
-                    $result['user'] = Controller::read( array( 'concept' => 'user' , 'id' => $result['user'] , 'service' => 'PostgreSQL' ) );
-                else
-                   $result['user'] = Controller::read( array( 'concept' => 'user' , 'id' => $result['user'] ));
-            }
-       }
-
-   } 
-   
+    public function deepnessReadParticipant(&$uri, &$result, &$criteria, $original) {
+
+	if (isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0) {
+	    if (isset($result['id'])) {
+		if ($result['isExternal'] == 1)
+		    $result['user'] = Controller::read(array('concept' => 'user', 'id' => $result['user'], 'service' => 'PostgreSQL'));
+		else
+		    $result['user'] = Controller::read(array('concept' => 'user', 'id' => $result['user']));
+	    }
+	}
+    }
+
     //TODO: Remover apos suporte a deepness na api 
-    public function deepnessFindParticipant( &$uri , &$result , &$criteria , $original ){		
-       
-       if(isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0)
-       {
-           foreach ($result as $i => $v)
-           {
-                if(isset($v['id']))
-                {
-                    if($result[$i]['isExternal'] == 1 )
-                        $result[$i]['user'] = Controller::read( array( 'concept' => 'user' , 'id' => $result[$i]['user'] , 'service' => 'PostgreSQL' ) );
-                    else
-                       $result[$i]['user'] = Controller::read( array( 'concept' => 'user' , 'id' => $result[$i]['user'] ));
-                }
-           }
-       }
-       
-   } 
-   
+    public function deepnessFindParticipant(&$uri, &$result, &$criteria, $original) {
+
+	if (isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0) {
+	    foreach ($result as $i => $v) {
+		if (isset($v['id'])) {
+		    if ($result[$i]['isExternal'] == 1)
+			$result[$i]['user'] = Controller::read(array('concept' => 'user', 'id' => $result[$i]['user'], 'service' => 'PostgreSQL'));
+		    else
+			$result[$i]['user'] = Controller::read(array('concept' => 'user', 'id' => $result[$i]['user']));
+		}
+	    }
+	}
+    }
+
     //TODO: Remover apos suporte a deepness na api 
-    public function deepnessReadCalendarSignature( &$uri , &$result , &$criteria , $original ){		
-       
-       if(isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0)
-            if(isset($result['calendar'])){
-                $result['calendar'] = Controller::read( array( 'concept' => 'calendar' , 'id' => $result['calendar'])); 
-				$result['defaultAlarms'] = Controller::find( array( 'concept' => 'calendarSignatureAlarm' ) , false ,array( 'filter' => array('=', 'calendarSignature'  ,  $result['id']) ));     
+    public function deepnessReadCalendarSignature(&$uri, &$result, &$criteria, $original) {
+
+	if (isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0)
+	    if (isset($result['calendar'])) {
+		$result['calendar'] = Controller::read(array('concept' => 'calendar', 'id' => $result['calendar']));
+		$result['defaultAlarms'] = Controller::find(array('concept' => 'calendarSignatureAlarm'), false, array('filter' => array('=', 'calendarSignature', $result['id'])));
+	    }
+    }
+
+    //TODO: Remover apos suporte a deepness na api 
+    public function deepnessFindCalendarSignature(&$uri, &$result, &$criteria, $original) {
+
+	if (isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0) {
+	    foreach ($result as $i => $v) {
+		if (isset($v['calendar'])) {
+		    $result[$i]['calendar'] = Controller::read(array('concept' => 'calendar', 'id' => $v['calendar']), false, false);
+		    $result[$i]['defaultAlarms'] = Controller::find(array('concept' => 'calendarSignatureAlarm'), false, array('filter' => array('=', 'calendarSignature', $v['id'])));
+		    //Caso não seja o dono da agenda retorna o objeto permission com as acls
+		    if ($result[$i]['isOwner'] == 0) {
+			$permission = Controller::find(array('concept' => 'calendarToPermission'), false, array('filter' => array('AND', array('=', 'calendar', $v['calendar']), array('=', 'user', Config::me('uidNumber')))));
+
+			if (!is_array($permission) || !$permission) {
+
+			    $permission = Controller::find(array('concept' => 'calendarToPermission'), false, array('filter' => array('AND', array('=', 'calendar', $v['calendar']), array('=', 'type', '1'))));
 			}
-            
-   } 
-   
-     //TODO: Remover apos suporte a deepness na api 
-    public function deepnessFindCalendarSignature( &$uri , &$result , &$criteria , $original ){		
-
-	if(isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0)
-       {
-           foreach ($result as $i => $v)
-           {
-                if(isset($v['calendar'])){
-                    $result[$i]['calendar'] = Controller::read( array( 'concept' => 'calendar' , 'id' => $v['calendar']), false, false); 
-                    $result[$i]['defaultAlarms'] = Controller::find( array( 'concept' => 'calendarSignatureAlarm' ) , false ,array( 'filter' => array('=', 'calendarSignature'  ,  $v['id']) ));    
-                    //Caso não seja o dono da agenda retorna o objeto permission com as acls
-                    if($result[$i]['isOwner'] == 0){
-                            $permission = Controller::find( array( 'concept' => 'calendarToPermission'), false ,array( 'filter' => array('AND', array('=', 'calendar' ,  $v['calendar']), array('=', 'user', Config::me('uidNumber') ) ) ) ); 
-
-                            if(!is_array($permission) || !$permission  ){
-
-                                    $permission = Controller::find( array( 'concept' => 'calendarToPermission'), false ,array( 'filter' => array('AND', array('=', 'calendar' ,  $v['calendar']), array('=', 'type', '1' ) ) ) );    
-
-                            }
-                            $result[$i]['permission'] = $permission[0];
-                    }
-            }
-            //TODO - Padronizar retorno do deepness
-            if(isset($v['user']))
-                $result[$i]['user'] = Controller::read( array( 'concept' => 'user' , 'id' => $v['user']), false, false); 
-          }
-       }       
-   } 
+			$result[$i]['permission'] = $permission[0];
+		    }
+		}
+		//TODO - Padronizar retorno do deepness
+		if (isset($v['user']))
+		    $result[$i]['user'] = Controller::read(array('concept' => 'user', 'id' => $v['user']), false, false);
+	    }
+	}
+    }
+
 //Decode Find       
-    public function decodeFindConcept( &$uri , &$result , &$criteria , $original ){		
-	if($result && is_array($result) ) 
-        {
-            $m = array_flip(self::${$uri['concept'].'Map'});
-            $new = array();
-            foreach ($result as $i => $v)
-                $new[$i] = self::parseConcept( $result[$i] , $m );
-
-
-            $result = $new;
-        }
-    }
-    
-    public function decodeFindSchedulable( &$uri , &$result , &$criteria , $original ){		
-	if($result && is_array($result) ) 
-        {
-            $m = array_flip(self::${$uri['concept'].'Map'});
-            $m['calendar_id'] = 'calendar';
-            $new = array();
-            foreach ($result as $i => $v)
-                $new[$i] = self::parseConcept( $result[$i] , $m );
-
-
-            $result = $new;
-        }
-    }
-
-    public function decodeFindAttachment( &$uri , &$result , &$criteria , $original ){		
-		if(isset($result))
-		foreach($result as $key => &$value)
-			$value['source'] = base64_decode($value['source']);
-    }
-
-	
-	public function decodeSignatureAlarmType( &$uri , &$result , &$criteria , $original ){	
-            if( is_array($result) )
-            foreach($result as &$param)
-                if(isset($param['type']))
-                    $param['type'] = self::decodeAlarmType($param['type']);
-	
-    }
-	
+    public function decodeFindConcept(&$uri, &$result, &$criteria, $original) {
+	if ($result && is_array($result)) {
+	    $m = array_flip(self::${$uri['concept'] . 'Map'});
+	    $new = array();
+	    foreach ($result as $i => $v)
+		$new[$i] = self::parseConcept($result[$i], $m);
+
+
+	    $result = $new;
+	}
+    }
+
+    public function decodeFindSchedulable(&$uri, &$result, &$criteria, $original) {
+	if ($result && is_array($result)) {
+	    $m = array_flip(self::${$uri['concept'] . 'Map'});
+	    $m['calendar_id'] = 'calendar';
+	    $new = array();
+	    foreach ($result as $i => $v)
+		$new[$i] = self::parseConcept($result[$i], $m);
+
+
+	    $result = $new;
+	}
+    }
+
+    public function decodeFindAttachment(&$uri, &$result, &$criteria, $original) {
+	if (isset($result))
+	    foreach ($result as $key => &$value)
+		$value['source'] = base64_decode($value['source']);
+    }
+
+    public function decodeSignatureAlarmType(&$uri, &$result, &$criteria, $original) {
+	if (is_array($result))
+	    foreach ($result as &$param)
+		if (isset($param['type']))
+		    $param['type'] = self::decodeAlarmType($param['type']);
+    }
+
 /////////////////////////////////////////////////////////////////////////
-    
-    static function dayAlarm( &$uri , &$params , &$criteria , $original ) {     
-        if(isset($criteria['filter'][1]) && $criteria['filter'][1] == 'date')
-        {
-            $filter = array( 'AND', 
-                      array( '='  , 'sent' , '0') ,  
-                      array( '='  , 'type' ,  ALARM_ALERT) ,  
-                      array( '>=' , 'rangeStart' , $criteria['filter'][2]) ,
-                      array( '<=' , 'rangeEnd' , $criteria['filter'][2] + 86400000) ); 
-
-            //Busca os Alarmes no Range
-            $al = Controller::find( array('concept' => 'alarm'), false ,array( 'filter' => $filter));
-            
-            if(is_array($al))
-            foreach ($al as $i => $v)
-            {
-                $ev =  Controller::read( array( 'concept' => 'schedulable' , 'id' => $v['schedulable']) ) ;
-
-                $unit = 0;
-                switch (strtolower($v['unit'])) {
-                        case 'm': $unit = 60; break;
-                        case 'H': $unit = 3600; break;
-                        case 'd': $unit = 216000; break; }
-                
-                  $al[$i]['sendTime'] = (((int)( $ev['startTime'] / 1000 )) - ( $v['time'] * $unit ));
-                  $al[$i]['schedulable'] =   $ev;
-                        
-            }
-            
-            $params = $al;
-            return false;
-        }
-    } 
-
-    public function deleteSchedulable( &$uri , &$params , &$criteria , $original ){
-
-       if(Config::module('useCaldav' , 'expressoCalendar'))
-            require_once ROOTPATH.'/modules/calendar/interceptors/DAViCalAdapter.php';
-
-        $calendarsToSchedulable = self::schedulable2calendarToObject($uri['id']);
-        
-        if( !self::ownerSchedulable($uri['id']) && !self::isAllowDeleteInCalendar($calendarsToSchedulable[0]['calendar_id']))
-        {
-            
-             foreach ($calendarsToSchedulable as $i => $v)
-             {
-                   Controller::delete(array('concept' => 'calendarToSchedulable' , 'id' => $v['calendar_to_calendar_object']));
-                   
-                   if(Config::module('useCaldav' , 'expressoCalendar'))
-                        DAViCalAdapter::deleteEvent($uri['id'], array('location' => $v['calendar_location']));
-             }
-             
-             /* Seta o participante como rejeitado */
-             Controller::update(array('concept' => 'participant'), array('status' => STATUS_CANCELLED) , 
-             array('filter' => 
-                 array('AND',
-                        array('=' , 'user'  ,Config::me('uidNumber') ),
-                        array('=' , 'schedulable'  , $uri['id'] )
-                     )));
-            
-            return false; /* Mata o restante da execução */
-        } 
-        	
-        if(Config::module('useCaldav' , 'expressoCalendar'))
-            foreach ($calendarsToSchedulable as $i => $v)
-                DAViCalAdapter::deleteEvent($uri['id'], array('location' => $v['calendar_location']));
-
-     }
-     
-     
-    public function deleteCalendarToPermissionDependences( &$uri , &$params , &$criteria , $original ){
-	$permission = Controller::read($uri, array('user','calendar'));
-
-	$calendarSignature = Controller::find( array( 'concept' => 'calendarSignature' ) , array('id') ,array( 'filter' => array('AND', array('=','calendar', $permission['calendar']), array('=','user',$permission['user']), array('=','isOwner','0')))); 
-
-	if($calendarSignature)
+
+    static function dayAlarm(&$uri, &$params, &$criteria, $original) {
+	if (isset($criteria['filter'][1]) && $criteria['filter'][1] == 'date') {
+	    $filter = array('AND',
+		array('=', 'sent', '0'),
+		array('=', 'type', ALARM_ALERT),
+		array('>=', 'rangeStart', $criteria['filter'][2]),
+		array('<=', 'rangeEnd', $criteria['filter'][2] + 86400000));
+
+	    //Busca os Alarmes no Range
+	    $al = Controller::find(array('concept' => 'alarm'), false, array('filter' => $filter));
+
+	    if (is_array($al))
+		foreach ($al as $i => $v) {
+		    $ev = Controller::read(array('concept' => 'schedulable', 'id' => $v['schedulable']));
+
+		    $unit = 0;
+		    switch (strtolower($v['unit'])) {
+			case 'm': $unit = 60;
+			    break;
+			case 'H': $unit = 3600;
+			    break;
+			case 'd': $unit = 216000;
+			    break;
+		    }
+
+		    $al[$i]['sendTime'] = (((int) ( $ev['startTime'] / 1000 )) - ( $v['time'] * $unit ));
+		    $al[$i]['schedulable'] = $ev;
+		}
+
+	    $params = $al;
+	    return false;
+	}
+    }
+
+    public function deleteSchedulable(&$uri, &$params, &$criteria, $original) {
+
+	if (Config::module('useCaldav', 'expressoCalendar'))
+	    require_once ROOTPATH . '/modules/calendar/interceptors/DAViCalAdapter.php';
+
+	$calendarsToSchedulable = self::schedulable2calendarToObject($uri['id']);
+
+	if (!self::ownerSchedulable($uri['id']) && !self::isAllowDeleteInCalendar($calendarsToSchedulable[0]['calendar_id'])) {
+
+	    foreach ($calendarsToSchedulable as $i => $v) {
+		Controller::delete(array('concept' => 'calendarToSchedulable', 'id' => $v['calendar_to_calendar_object']));
+
+		if (Config::module('useCaldav', 'expressoCalendar'))
+		    DAViCalAdapter::deleteEvent($uri['id'], array('location' => $v['calendar_location']));
+	    }
+
+	    /* Seta o participante como rejeitado */
+	    Controller::update(array('concept' => 'participant'), array('status' => STATUS_CANCELLED), array('filter' =>
+		array('AND',
+		    array('=', 'user', Config::me('uidNumber')),
+		    array('=', 'schedulable', $uri['id'])
+		    )));
+
+	    return false; /* Mata o restante da execução */
+	}
+
+	if (Config::module('useCaldav', 'expressoCalendar'))
+	    foreach ($calendarsToSchedulable as $i => $v)
+		DAViCalAdapter::deleteEvent($uri['id'], array('location' => $v['calendar_location']));
+    }
+
+    public function deleteCalendarToPermissionDependences(&$uri, &$params, &$criteria, $original) {
+	$permission = Controller::read($uri, array('user', 'calendar'));
+
+	$calendarSignature = Controller::find(array('concept' => 'calendarSignature'), array('id'), array('filter' => array('AND', array('=', 'calendar', $permission['calendar']), array('=', 'user', $permission['user']), array('=', 'isOwner', '0'))));
+
+	if ($calendarSignature)
 	    Controller::delete(array('concept' => 'calendarSignature', 'id' => $calendarSignature[0]['id']));
     }
 
-    public function deleteCalendarSignatureDependences( &$uri , &$params , &$criteria , $original ){
-         $signature = Controller::read($uri,array('isOwner','calendar'));
-            
-        if($signature['isOwner'] == '1')
-        {
-           $calendarToSchedulables = Controller::find(array('concept' => 'calendarToSchedulable') , null , array('filter' => array('=' , 'calendar' , $signature['calendar'] )));
-           
-           $schedulables = array();
-           if(is_array($calendarToSchedulables))
-           foreach ($calendarToSchedulables as $key => $calendarToSchedulable) 
-                 $schedulables[] = $calendarToSchedulable['schedulable'] ; 
-            
-	   if( !empty( $schedulables ) )
-	      Controller::deleteALL(array('concept' => 'schedulable'),null , array('filter' => array('IN' , 'id' , $schedulables)));
-
-           Controller::delete(array('concept' => 'calendar', 'id' => $signature['calendar']));
-        }
-        
-     } 
-	 
-	public function deleteAttachmentDependences( &$uri , &$params , &$criteria , $original ){
-
-		if(isset($original['URI']['id']))
-			Controller::delete(array('concept' => 'schedulableToAttachment', null , array('filter' => array('=' , 'attachment' , $original['URI']['id']))));
-    }
-
-    public function createDefaultSignature( &$uri , &$result , &$criteria , $original ){
+    public function deleteCalendarSignatureDependences(&$uri, &$params, &$criteria, $original) {
+	$signature = Controller::read($uri, array('isOwner', 'calendar'));
+
+	if ($signature['isOwner'] == '1') {
+	    $calendarToSchedulables = Controller::find(array('concept' => 'calendarToSchedulable'), null, array('filter' => array('=', 'calendar', $signature['calendar'])));
+
+	    $schedulables = array();
+	    if (is_array($calendarToSchedulables))
+		foreach ($calendarToSchedulables as $key => $calendarToSchedulable)
+		    $schedulables[] = $calendarToSchedulable['schedulable'];
+
+	    if (!empty($schedulables))
+		Controller::deleteALL(array('concept' => 'schedulable'), null, array('filter' => array('IN', 'id', $schedulables)));
+
+	    Controller::delete(array('concept' => 'calendar', 'id' => $signature['calendar']));
+	}
+    }
+
+    public function deleteAttachmentDependences(&$uri, &$params, &$criteria, $original) {
+
+	if (isset($original['URI']['id']))
+	    Controller::delete(array('concept' => 'schedulableToAttachment', null, array('filter' => array('=', 'attachment', $original['URI']['id']))));
+    }
+
+    public function createDefaultSignature(&$uri, &$result, &$criteria, $original) {
 
 	//Caso uma busca não retorne nenhum resultado e foi buscado pelas assinaturas do usuario logado apenas
@@ -832,219 +777,210 @@
 
 	//Veirifica pois o usuário pode ter varias assinaturas mas não ser dona de nenhuma
-	if(count($result) > 0){
-	    foreach($result as $key){	
-		if($key['isOwner'] != 0)
+	if (count($result) > 0) {
+	    foreach ($result as $key) {
+		if ($key['isOwner'] != 0)
 		    $isValidSignature = true;
 	    }
 	}
 
-    if(!$isValidSignature && 
-            ( $original['criteria']['filter'][1][0] == '=' &&
-              $original['criteria']['filter'][1][1] == 'user' &&
-              $original['criteria']['filter'][1][2] == $_SESSION['phpgw_session']['account_id']
-            ))
-    {        
-        
-        if( Config::module('useCaldav' , 'expressoCalendar') )
-        {
-            require_once ROOTPATH.'/modules/calendar/interceptors/DAViCalAdapter.php';
-            
-            $calendario = DAViCalAdapter::findCalendars();
-        }
-        
-        if( Config::module('useCaldav' , 'expressoCalendar') && is_array($calendario) && count($calendario) > 0)
-        {     
-            foreach ($calendario as $i => $v)
-            {
-                
-                $urlA = explode('/', $v->url);
-                $name = isset($v->displayname)? $v->displayname : $urlA[ (count($urlA)-2) ];
-                $cal = array('name' => $name,
-                             'description' =>  isset($v->description)? $v->description : $name,
-                             'timezone' => isset($v->timezone) ? $v->timezone : (date_default_timezone_get()) ? date_default_timezone_get() : 'America/Sao_Paulo',
-                             'dtstamp' => time().'000',
-                             'location' => $urlA[ (count($urlA)-3) ].'/'.$urlA[ (count($urlA)-2) ]
-                            );
-
-                $calCreated =  Controller::create( array('concept' => 'calendar') , $cal );  
-                
-                
-
-                $sig = array( 'user' => $_SESSION['wallet']['user']['uidNumber'],
-                                  'calendar' => $calCreated['id'],
-                                  'isOwner' => '1',
-                                  'dtstamp' => time().'000',
-                                  'fontColor' => 'FFFFFF',
-                                  'backgroundColor' => '3366CC',
-                                  'borderColor' => '3366CC',
-                                );
-
-                $sigCreated =  Controller::create( array('concept' => 'calendarSignature') , $sig );
-               
-  
-               DAViCalAdapter::importCollection($v->url , $calCreated['id']);
-             
-            }
-        }
-        else
-        {
-         //Criaremos uma agenda padrão
-          $cal = array('name' => 'Calendario',
-                         'description' => 'Calendario Padrão',
-                         'timezone' =>  (date_default_timezone_get()) ? date_default_timezone_get() : 'America/Sao_Paulo',
-                         'dtstamp' => time().'000'
-                        ); 
-          
-          $calCreated =  Controller::create( array('concept' => 'calendar') , $cal );  
-          
-          $sig = array( 'user' => $_SESSION['wallet']['user']['uidNumber'],
-                          'calendar' => $calCreated['id'],
-                          'isOwner' => '1',
-                          'dtstamp' => time().'000',
-                          'fontColor' => 'FFFFFF',
-                          'backgroundColor' => '3366CC',
-                          'borderColor' => '3366CC',
-                        );
-            
-          $sigCreated =  Controller::create( array('concept' => 'calendarSignature') , $sig );
-        }
-        
-        $result = Controller::find($original['URI'] , $original['properties'] ? $original['properties'] : null , $original['criteria']  );
-        return false;  
-    }
-    
+	if (!$isValidSignature &&
+		( $original['criteria']['filter'][1][0] == '=' &&
+		$original['criteria']['filter'][1][1] == 'user' &&
+		$original['criteria']['filter'][1][2] == $_SESSION['phpgw_session']['account_id']
+		)) {
+
+	    if (Config::module('useCaldav', 'expressoCalendar')) {
+		require_once ROOTPATH . '/modules/calendar/interceptors/DAViCalAdapter.php';
+
+		$calendario = DAViCalAdapter::findCalendars();
+	    }
+
+	    if (Config::module('useCaldav', 'expressoCalendar') && is_array($calendario) && count($calendario) > 0) {
+		foreach ($calendario as $i => $v) {
+
+		    $urlA = explode('/', $v->url);
+		    $name = isset($v->displayname) ? $v->displayname : $urlA[(count($urlA) - 2)];
+		    $cal = array('name' => $name,
+			'description' => isset($v->description) ? $v->description : $name,
+			'timezone' => isset($v->timezone) ? $v->timezone : (date_default_timezone_get()) ? date_default_timezone_get() : 'America/Sao_Paulo',
+			'dtstamp' => time() . '000',
+			'location' => $urlA[(count($urlA) - 3)] . '/' . $urlA[(count($urlA) - 2)]
+		    );
+
+		    $calCreated = Controller::create(array('concept' => 'calendar'), $cal);
+
+
+
+		    $sig = array('user' => $_SESSION['wallet']['user']['uidNumber'],
+			'calendar' => $calCreated['id'],
+			'isOwner' => '1',
+			'dtstamp' => time() . '000',
+			'fontColor' => 'FFFFFF',
+			'backgroundColor' => '3366CC',
+			'borderColor' => '3366CC',
+		    );
+
+		    $sigCreated = Controller::create(array('concept' => 'calendarSignature'), $sig);
+
+
+		    DAViCalAdapter::importCollection($v->url, $calCreated['id']);
+		}
+	    } else {
+		//Criaremos uma agenda padrão
+		$cal = array('name' => 'Calendario',
+		    'description' => 'Calendario Padrão',
+		    'timezone' => (date_default_timezone_get()) ? date_default_timezone_get() : 'America/Sao_Paulo',
+		    'dtstamp' => time() . '000'
+		);
+
+		$calCreated = Controller::create(array('concept' => 'calendar'), $cal);
+
+		$sig = array('user' => $_SESSION['wallet']['user']['uidNumber'],
+		    'calendar' => $calCreated['id'],
+		    'isOwner' => '1',
+		    'dtstamp' => time() . '000',
+		    'fontColor' => 'FFFFFF',
+		    'backgroundColor' => '3366CC',
+		    'borderColor' => '3366CC',
+		);
+
+		$sigCreated = Controller::create(array('concept' => 'calendarSignature'), $sig);
+	    }
+
+	    $result = Controller::find($original['URI'], $original['properties'] ? $original['properties'] : null, $original['criteria']);
+	    return false;
+	}
+    }
+
+    //TODO - Criar conceito separado para participantes externos e remover o criterio notExternal
+    public function findExternalPaticipants(&$uri, &$result, &$criteria, $original) {
+	if (Config::me('uidNumber') && !isset($criteria['notExternal'])) {
+	    $newuri['concept'] = 'user';
+	    $newuri['service'] = 'PostgreSQL';
+
+	    $newCriteria = $original['criteria'];
+	    $valid = true;
+
+	    $newCriteria['filter'] = array('AND', $newCriteria['filter'], array('=', 'owner', Config::me('uidNumber')));
+	    $externalUsers = Controller::find($newuri, $original['properties'] ? $original['properties'] : null, $newCriteria);
+
+	    if (is_array($externalUsers)) {
+		foreach ($externalUsers as $i => $v)
+		    $externalUsers[$i]['isExternal'] = '1';
+	    }
+	    else
+		$externalUsers = array();
+
+	    if (!is_array($result))
+		$result = array();
+
+	    return array_merge($result, $externalUsers);
+	}
+    }
+
+    public function davcalCreateCollection(&$uri, &$params, &$criteria, $original) {
+	if (Config::module('useCaldav', 'expressoCalendar')) {
+	    require_once ROOTPATH . '/modules/calendar/interceptors/DAViCalAdapter.php';
+	    DAViCalAdapter::mkcalendar($params['location'], $params['name'], isset($params['description']) ? $params['description'] : '' );
+	}
+    }
+
+    public function davcalDeleteCollection(&$uri, &$params, &$criteria, $original) {
+	if (Config::module('useCaldav', 'expressoCalendar') && Config::module('onRemoveCascadeCalDav')) {
+	    require_once ROOTPATH . '/modules/calendar/interceptors/DAViCalAdapter.php';
+	    $calendar = Controller::read($uri);
+	    DAViCalAdapter::rmCalendar($calendar['location']);
+	}
+    }
+
+    public function davcalUpdateCollection(&$uri, &$params, &$criteria, $original) {
+	if (Config::module('useCaldav', 'expressoCalendar')) {
+	    require_once ROOTPATH . '/modules/calendar/interceptors/DAViCalAdapter.php';
+	    if (isset($params['location'])) {
+		$calendar = Controller::read($uri);
+		if ($calendar['location'] !== $params['location'])
+		    DAViCalAdapter::mvcalendar($calendar['location'], $params['location']);
+	    }
+	}
+    }
+
+    private function _makeUid() {
+
+	$date = date('Ymd\THisT');
+	$unique = substr(microtime(), 2, 4);
+	$base = 'aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPrRsStTuUvVxXuUvVwWzZ1234567890';
+	$start = 0;
+	$end = strlen($base) - 1;
+	$length = 6;
+	$str = null;
+	for ($p = 0; $p < $length; $p++)
+	    $unique .= $base{mt_rand($start, $end)};
+
+	return $date . $unique . '@expresso-calendar';
+    }
+
+    private function getStatus($id) {
+	$a = array(
+	    STATUS_CONFIRMED => 'CONFIRMED',
+	    STATUS_CANCELLED => 'CANCELLED',
+	    STATUS_TENATIVE => 'TENATIVE',
+	    STATUS_UNANSWERED => 'NEEDS-ACTION',
+	    STATUS_DELEGATED => 'DELEGATED'
+	);
+	return $a[$id];
+    }
+
+    private static function decodeAlarmType($id) {
+	$a = array(ALARM_ALERT => 'alert',
+	    ALARM_MAIL => 'mail',
+	    ALARM_SMS => 'sms');
+
+	return $a[$id];
+    }
+
+    private static function codeAlarmType($type) {
+	$a = array('alert' => ALARM_ALERT,
+	    'mail' => ALARM_MAIL,
+	    'sms' => ALARM_SMS);
+
+	return $a[$type];
+    }
+
+    private static function codeAlarmUnit($u) {
+	if ($u === 'd')
+	    return 'days';
+	if ($u === 'm')
+	    return 'minutes';
+	if ($u === 'H')
+	    return 'hours';
+    }
+
+    private static function ownerSchedulable($id) {
+
+	$isOwner = Controller::find(array('concept' => 'participant'), array('id'), array('filter' =>
+		    array('AND',
+			array('=', 'isOrganizer', '1'),
+			array('=', 'user', $_SESSION['wallet']['user']['uidNumber']),
+			array('=', 'schedulable', $id)
+			)));
+
+	return ( isset($isOwner[0]['id']) ) ? true : false;
+    }
+
+    private static function schedulable2calendarToObject($Schedulable) {
+	return Controller::service('PostgreSQL')->execResultSql('SELECT calendar_to_calendar_object.id as calendar_to_calendar_Object , calendar.name as calendar_name ,calendar.location as calendar_location, calendar.id as calendar_id FROM calendar_to_calendar_object , calendar , calendar_signature'
+			. ' WHERE calendar_signature.user_uidnumber = ' . $_SESSION['wallet']['user']['uidNumber']
+			//      .' AND calendar_signature.is_owner = 1'
+			. ' AND calendar_signature.calendar_id = calendar.id'
+			. ' AND calendar_to_calendar_object.calendar_id = calendar.id'
+			. ' AND calendar_to_calendar_object.calendar_object_id = ' . addslashes($Schedulable));
+    }
+
+    protected static function isAllowDeleteInCalendar($calendar) {
+	$f = Controller::find(array('concept' => 'calendarToPermission'), false, array('filter' => array('AND', array('=', 'user', Config::me('uidNumber')), array('=', 'calendar', $calendar))));
+	return (strpos($f[0]['acl'], CALENDAR_ACL_REMOVE) === false) ? false : true;
+    }
+
 }
-    //TODO - Criar conceito separado para participantes externos e remover o criterio notExternal
-    public function findExternalPaticipants( &$uri , &$result , &$criteria , $original ) {
-        if(Config::me('uidNumber') && !isset($criteria['notExternal']))
-        {
-            $newuri['concept'] = 'user';
-            $newuri['service'] = 'PostgreSQL';
-           
-            $newCriteria = $original['criteria'];
-            $valid = true;
-            
-            $newCriteria['filter'] = array('AND',$newCriteria['filter'] , array('=' , 'owner', Config::me('uidNumber')) );        
-            $externalUsers = Controller::find( $newuri , $original['properties'] ? $original['properties'] : null , $newCriteria );
-            
-            if(is_array($externalUsers))
-            {
-                 foreach ($externalUsers as $i => $v)
-                    $externalUsers[$i]['isExternal'] = '1';
-            }
-            else
-                $externalUsers = array();
-
-            if(!is_array($result))
-                $result = array();
-
-            return array_merge($result, $externalUsers);    
-        }
-       
-    }
-
-    public function davcalCreateCollection( &$uri , &$params , &$criteria , $original ){	
-        if( Config::module('useCaldav' , 'expressoCalendar') )
-        {
-           require_once ROOTPATH.'/modules/calendar/interceptors/DAViCalAdapter.php';
-	   DAViCalAdapter::mkcalendar($params['location'] , $params['name'], isset($params['description']) ? $params['description'] : '' );
-        }
-    }
-    
-   public function davcalDeleteCollection( &$uri , &$params , &$criteria , $original ){	
-        if( Config::module('useCaldav' , 'expressoCalendar') &&  Config::module('onRemoveCascadeCalDav'))
-        {
-           require_once ROOTPATH.'/modules/calendar/interceptors/DAViCalAdapter.php';
-           $calendar = Controller::read($uri);
-           DAViCalAdapter::rmCalendar($calendar['location']);
-        }
-    }
-	
-   public function davcalUpdateCollection( &$uri , &$params , &$criteria , $original ){	
-        if( Config::module('useCaldav' , 'expressoCalendar') )
-        {
-           require_once ROOTPATH.'/modules/calendar/interceptors/DAViCalAdapter.php';
-           if(isset($params['location']))
-           {
-                $calendar = Controller::read($uri);
-                if($calendar['location'] !== $params['location'])
-                    DAViCalAdapter::mvcalendar($calendar['location'], $params['location']);
-           }
-        }
-    }
-
-    private function _makeUid() {
-
-            $date   = date('Ymd\THisT');
-            $unique = substr(microtime(), 2, 4);
-            $base   = 'aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPrRsStTuUvVxXuUvVwWzZ1234567890';
-            $start  = 0;
-            $end    = strlen( $base ) - 1;
-            $length = 6;
-            $str    = null;
-            for( $p = 0; $p < $length; $p++ )
-              $unique .= $base{mt_rand( $start, $end )};
-
-            return $date.$unique.'@expresso-calendar';
-    }
-    private function getStatus( $id ){
-             $a = array(
-                                            STATUS_CONFIRMED =>  'CONFIRMED',
-                                            STATUS_CANCELLED =>  'CANCELLED',
-                                            STATUS_TENATIVE =>   'TENATIVE',
-                                            STATUS_UNANSWERED => 'NEEDS-ACTION',
-                                            STATUS_DELEGATED =>  'DELEGATED'
-                                            );
-             return $a[ $id ];
-    }
-    private static function decodeAlarmType( $id ){
-             $a = array(	ALARM_ALERT =>  'alert',
-				ALARM_MAIL =>  'mail',
-				ALARM_SMS =>   'sms' );
-
-             return $a[ $id ];
-    }
-    private static function codeAlarmType( $type ){
-             $a = array(	'alert' => ALARM_ALERT  ,
-				'mail' => ALARM_MAIL   ,
-				'sms' => ALARM_SMS   );
-
-             return $a[ $type ];
-    }
-    private static function codeAlarmUnit( $u ){
-		if($u === 'd') return 'days';
-		if($u === 'm') return 'minutes';
-		if($u === 'H') return 'hours';
-	}   
-  
-    private static function ownerSchedulable( $id ){
-        
-       $isOwner = Controller::find(array('concept' => 'participant'), array('id') , 
-             array('filter' => 
-                 array('AND', 
-                        array('=' , 'isOrganizer' , '1'),
-                        array('=' , 'user'  ,$_SESSION['wallet']['user']['uidNumber'] ),
-                        array('=' , 'schedulable'  ,$id )
-                     )));
-       
-        return ( isset( $isOwner[0]['id'] ) ) ? true : false; 
-    }
-
-    private static function schedulable2calendarToObject($Schedulable)
-    {
-      return Controller::service('PostgreSQL')->execResultSql('SELECT calendar_to_calendar_object.id as calendar_to_calendar_Object , calendar.name as calendar_name ,calendar.location as calendar_location, calendar.id as calendar_id FROM calendar_to_calendar_object , calendar , calendar_signature' 
-                .' WHERE calendar_signature.user_uidnumber = '.$_SESSION['wallet']['user']['uidNumber']
-          //      .' AND calendar_signature.is_owner = 1'
-                .' AND calendar_signature.calendar_id = calendar.id'
-                .' AND calendar_to_calendar_object.calendar_id = calendar.id'
-                .' AND calendar_to_calendar_object.calendar_object_id = '.addslashes($Schedulable));
-    }
-		
-    protected static function isAllowDeleteInCalendar( $calendar ) {
-         $f = Controller::find(array('concept' => 'calendarToPermission') , false , array('filter' => array('AND' , array('=', 'user' , Config::me('uidNumber') ) , array('=', 'calendar' , $calendar))));       
-         return (strpos($f[0]['acl'], CALENDAR_ACL_REMOVE) === false) ? false : true;        
-    }
-    
-}
 
 ?>
Index: trunk/prototype/modules/calendar/js/calendar.codecs.js
===================================================================
--- trunk/prototype/modules/calendar/js/calendar.codecs.js	(revision 5953)
+++ trunk/prototype/modules/calendar/js/calendar.codecs.js	(revision 6066)
@@ -2,81 +2,87 @@
   
     init: function(){
-		this.moduleName = 'expressoCalendar'; 
-		this.me = DataLayer.dispatch( "me" );
-		
-		
-		this.timezones = Timezone.timezones;
-		this.isDaylightSaving = Timezone.daylightSaving;
-		this.load();      
+	this.moduleName = 'expressoCalendar'; 
+	this.me = DataLayer.dispatch( "me" );
+		
+		
+	this.timezones = Timezone.timezones;
+	this.isDaylightSaving = Timezone.daylightSaving;
+	this.load();      
     },             
   
     load: function(){
 
-		var defaultPreferences = { dateFormat: "dd/MM/yyyy",
-			hourFormat: "HH:mm",
-			defaultCalView: "month",
-			defaultDuration: 30,
-			backgroundColor: "36C",
-			borderColor: "36C",
-			fontColor: "fff",
-			timezone: 'America/Sao_Paulo',
-			weekStart: 'SUN'
-		  };
-
-		var pref = DataLayer.get( "modulePreference:detail", ['and',[ "=", "user", this.me.id ], [ "=", "module", this.moduleName ]] );
-
-		this.preferences = DataLayer.merge( defaultPreferences, pref.values || {} );
-		this.preferenceIds = pref.ids;
+	var defaultPreferences = {
+	    dateFormat: "dd/MM/yyyy",
+	    hourFormat: "HH:mm",
+	    defaultCalView: "month",
+	    defaultDuration: 30,
+	    backgroundColor: "36C",
+	    borderColor: "36C",
+	    fontColor: "fff",
+	    timezone: 'America/Sao_Paulo',
+	    weekStart: 'SUN'
+	};
+
+	var pref = DataLayer.get( "modulePreference:detail", ['and',[ "=", "user", this.me.id ], [ "=", "module", this.moduleName ]] );
+
+	this.preferences = DataLayer.merge( defaultPreferences, pref.values || {} );
+	this.preferenceIds = pref.ids;
     }
 }
 
 constantsParticipant = {
-	'o' : 'organization',
-	'w' : 'write',
-	'p' : 'participationRequired',
-	'i' : 'inviteGuests',
-	'r' : 'read'
+    'o' : 'organization',
+    'w' : 'write',
+    'p' : 'participationRequired',
+    'i' : 'inviteGuests',
+    'r' : 'read'
 }
 
 constantsCalendarShared = {
-	'r' : 'read',
-	'w' : 'write',
-	'd' : 'remove',
-	'b' : 'busy',
-	's' : 'shared',
-        'p' : 'required'
+    'r' : 'read',
+    'w' : 'write',
+    'd' : 'remove',
+    'b' : 'busy',
+    's' : 'shared',
+    'p' : 'required'
 }
 
 UI = {
-	dialogs: {
-		addEvent: null,
-		importCalendar: null,
-		sharedCalendar: null,
-		copyCalendar: null
-	}
+    dialogs: {
+	addEvent: null,
+	importCalendar: null,
+	sharedCalendar: null,
+	copyCalendar: null
+    }
 }
 
 DataLayer.codec( "calendarSignature", "calendar", {
   
-	decoder: function(){},
+    decoder: function(){},
       
-	encoder: function( signatures ){
-		return $.map( signatures, function( signature ){
-			return { events: function( start, end, callback ){
-				var viewKey = start + ':' + end;
-				if( Calendar.currentViewKey !== viewKey ){
-				    Calendar.currentViewKey = viewKey;
-				    Calendar.currentView = DataLayer.get( 'schedulable:calendar', { start: start, end: end } );
-				}
-				var view = Calendar.currentView[ signature.calendar.id ];
-				callback( view && !view.hidden ? view : [] );
-			   },
-
-			   backgroundColor: '#' + signature.backgroundColor || User.preferences.backgroundColor,
-			   borderColor: '#' + signature.borderColor || User.preferences.borderColor,
-			   textColor: '#' + signature.fontColor || User.preferences.fontColor,
-			   editable:  signature.isOwner }
-	       });
-      }
+    encoder: function( signatures ){
+	return $.map( signatures, function( signature ){
+	    return {
+		events: function( start, end, callback ){
+		    var viewKey = start + ':' + end;
+		    if( Calendar.currentViewKey !== viewKey ){
+			Calendar.currentViewKey = viewKey;
+			Calendar.currentView = DataLayer.get( 'schedulable:calendar', {
+			    start: start, 
+			    end: end
+			} );
+		    }
+		    var view = Calendar.currentView[ signature.calendar.id ];
+		    callback( view && !view.hidden ? view : [] );
+		},
+
+		backgroundColor: '#' + signature.backgroundColor || User.preferences.backgroundColor,
+		borderColor: '#' + signature.borderColor || User.preferences.borderColor,
+		textColor: '#' + signature.fontColor || User.preferences.fontColor,
+		editable:  signature.isOwner
+		}
+	});
+    }
 
       
@@ -84,6 +90,6 @@
 
 DataLayer.codec( "calendarToPermission", "detail", {
-	decoder: function( evtObj ){
-/*		Encoder.EncodeType = "entity";
+    decoder: function( evtObj ){
+    /*		Encoder.EncodeType = "entity";
 		
 		if( notArray = $.type(evtObj) !== "array" )
@@ -103,36 +109,36 @@
 	return notArray ? res[0] : res;
 	*/
-	},
+    },
 
     encoder: function( evtObj ){
 	
-		if(evtObj == "")
-			return "";
+	if(evtObj == "")
+	    return "";
 			
-		var notArray = false;
+	var notArray = false;
 		  
-		if( notArray = $.type(evtObj) !== "array" )
-			evtObj = [ evtObj ];
-		
-		var constantAcl = function(acl){
-			var returns = {};
-			for (var i in constantsCalendarShared){
-				returns[constantsCalendarShared[i]] = acl.indexOf(i) >= 0 ? true : false
-			}
-			return returns;
-		};
-
-		var res = $.map(evtObj, function( objEvent ){			
-			return {
-			    id: objEvent.id,
-			    type: objEvent.type,
-			    calendar: objEvent.calendar,
-			    user: objEvent.user,
-				acl: constantAcl(objEvent.acl)	,
-				aclValues: objEvent.acl
-			};
-		});	
+	if( notArray = $.type(evtObj) !== "array" )
+	    evtObj = [ evtObj ];
+		
+	var constantAcl = function(acl){
+	    var returns = {};
+	    for (var i in constantsCalendarShared){
+		returns[constantsCalendarShared[i]] = acl.indexOf(i) >= 0 ? true : false
+	    }
+	    return returns;
+	};
+
+	var res = $.map(evtObj, function( objEvent ){			
+	    return {
+		id: objEvent.id,
+		type: objEvent.type,
+		calendar: objEvent.calendar,
+		user: objEvent.user,
+		acl: constantAcl(objEvent.acl)	,
+		aclValues: objEvent.acl
+	    };
+	});	
 	return notArray ? res[0] : res;
-	}
+    }
 });
 
@@ -140,126 +146,144 @@
 Calendar = {
   
-	load: function(){
-		this.lastView = 0;
-		var filter = ['=', 'user', User.me.id];
-		if(!!User.me.gidNumber){
-			if(!$.isArray(User.me.gidNumber))
-				User.me.gidNumber = [User.me.gidNumber];
-
-			filter = ['OR', filter, ['IN', 'user', User.me.gidNumber]];
-		}
-
-		//var descart = DataLayer.get("calendarSignature", {filter: filter, criteria: {deepness: 2}});
-		this.signatures  = DataLayer.get("calendarSignature", {filter: filter, criteria: {deepness: 2}});
+    load: function(){
+	this.lastView = 0;
+	var filter = ['=', 'user', User.me.id];
+	if(!!User.me.gidNumber){
+	    if(!$.isArray(User.me.gidNumber))
+		User.me.gidNumber = [User.me.gidNumber];
+
+	    filter = ['OR', filter, ['IN', 'user', User.me.gidNumber]];
+	}
+
+	//var descart = DataLayer.get("calendarSignature", {filter: filter, criteria: {deepness: 2}});
+	this.signatures  = DataLayer.get("calendarSignature", {
+	    filter: filter, 
+	    criteria: {
+		deepness: 2
+	    }
+	});
 	  
-		var prevSources = this.sources;
-
-		this.sources = DataLayer.encode( "calendarSignature:calendar", this.signatures );
-
-		if( prevSources ){     
-			var newSources = DataLayer.diff( { 'diff': prevSources }, { 'diff': this.sources } ).diff;
-
-			for( var i = 0; i < newSources.length; i++ )
-				$('#calendar').fullCalendar( 'addEventSource', newSources[i] );
-
-			var removeSources = DataLayer.diff( { 'diff': newSources }, { 'diff': prevSources } ).diff;
-
-			for( var i = 0; i < removeSources.length; i++ )
-				$('#calendar').fullCalendar( 'removeEventSource', removeSources[i] );
-		}
-
-		this.calendarIds = [], this.signatureOf = {}, this.calendars = [], this.calendarOf= {};
-
-		for( var i = 0; i < this.signatures.length; i++ ){
-			if(this.signatures[i].isOwner == "0")
-				this.signatures[i].permission =  DataLayer.encode('calendarToPermission:detail', this.signatures[i].permission);
-			this.signatureOf[ this.calendarIds[i] = ( this.calendars[ this.calendars.length ] = this.calendarOf[ this.signatures[i].id ] = this.signatures[i].calendar ).id ] = this.signatures[i];
-		}
-
-		delete Calendar.currentViewKey;
-	},
-
-	rerenderView: function(force){
-
-		if(force){
-                        delete Calendar.currentViewKey;
+    var prevSources = this.sources;
+
+    this.sources = DataLayer.encode( "calendarSignature:calendar", this.signatures );
+
+    if( prevSources ){     
+	var newSources = DataLayer.diff( {
+	    'diff': prevSources
+	}, {
+	    'diff': this.sources
+	    } ).diff;
+
+	for( var i = 0; i < newSources.length; i++ )
+	    $('#calendar').fullCalendar( 'addEventSource', newSources[i] );
+
+	var removeSources = DataLayer.diff( {
+	    'diff': newSources
+	}, {
+	    'diff': prevSources
+	} ).diff;
+
+	for( var i = 0; i < removeSources.length; i++ )
+	    $('#calendar').fullCalendar( 'removeEventSource', removeSources[i] );
+    }
+
+    this.calendarIds = [], this.signatureOf = {}, this.calendars = [], this.calendarOf= {};
+
+    for( var i = 0; i < this.signatures.length; i++ ){
+	if(this.signatures[i].isOwner == "0")
+	    this.signatures[i].permission =  DataLayer.encode('calendarToPermission:detail', this.signatures[i].permission);
+	this.signatureOf[ this.calendarIds[i] = ( this.calendars[ this.calendars.length ] = this.calendarOf[ this.signatures[i].id ] = this.signatures[i].calendar ).id ] = this.signatures[i];
+    }
+
+    delete Calendar.currentViewKey;
+},
+
+rerenderView: function(force){
+
+    if(force){
+	delete Calendar.currentViewKey;
                         
-			$('#calendar').fullCalendar( 'refetchEvents' );
-		}
-
-		var calendarNotSelected = getSelectedCalendars( true );
-		for(var i = 0; i < calendarNotSelected.length; i++)
-			if(!!Calendar.currentView[ calendarNotSelected[i] ])
-				Calendar.currentView[ calendarNotSelected[i] ].hidden = true;
-
-		$('#calendar').fullCalendar( 'refetchEvents' );	
+	$('#calendar').fullCalendar( 'refetchEvents' );
+    }
+
+    var calendarNotSelected = getSelectedCalendars( true );
+    for(var i = 0; i < calendarNotSelected.length; i++)
+	if(!!Calendar.currentView[ calendarNotSelected[i] ])
+	    Calendar.currentView[ calendarNotSelected[i] ].hidden = true;
+
+    $('#calendar').fullCalendar( 'refetchEvents' );	
                 
-                contentMenu();
+    contentMenu();
+}
+}
+
+Alarms = {
+    load: function(){
+	var eventsDay = DataLayer.get('alarm:schedulable',['=', 'date', Date.today().getTime()]);
+	for(var i = 0; i < eventsDay.length; i++){
+	    this.addAlarm( eventsDay[i] );
 	}
+    },
+	
+    addAlarm: function( eventDay ){            
+	if(!DataLayer.tasks[parseInt(eventDay.sendTime)]){
+	    DataLayer.task( parseInt(eventDay.sendTime) , function( timestamp ){
+		var path = User.moduleName == 'expressoCalendar' ? '' : '../prototype/modules/calendar/';
+		DataLayer.render(path+'templates/alarm.ejs',{
+		    event: eventDay
+		}, function( html ){                                
+		    $.Zebra_Dialog(html , {
+			'type':     'question',
+			'overlay_opacity': '0.5',
+			'buttons':  ['Fechar'],
+			'onClose':  function(clicked) {}
+		    });
+		});
+	    });
+	}
+    }
 }
 
-Alarms = {
-	load: function(){
-		var eventsDay = DataLayer.get('alarm:schedulable',['=', 'date', Date.today().getTime()]);
-		for(var i = 0; i < eventsDay.length; i++){
-			this.addAlarm( eventsDay[i] );
-		}
-        },
-	
-	addAlarm: function( eventDay ){            
-                if(!DataLayer.tasks[parseInt(eventDay.sendTime)]){
-                    DataLayer.task( parseInt(eventDay.sendTime) , function( timestamp ){
-                        var path = User.moduleName == 'expressoCalendar' ? '' : '../prototype/modules/calendar/';
-                        DataLayer.render(path+'templates/alarm.ejs',{event: eventDay}, function( html ){                                
-                                $.Zebra_Dialog(html , {
-                                    'type':     'question',
-                                    'overlay_opacity': '0.5',
-                                    'buttons':  ['Fechar'],
-                                    'onClose':  function(clicked) {}
-                               });
-			});
-                    });
-                }
+DataLayer.codec( "modulePreference", "detail", {
+    decoder: function( evtObj ){
+
+	if( notArray = $.type(evtObj) !== "array" )
+	    evtObj = [ evtObj ];
+		
+	var res = $.map(evtObj, function( form ){
+
+	    var returns = [];
+
+	    for (var name in form)
+		returns[ returns.length ] = {
+		    name: name,
+		    user: User.me.id,
+		    value: form[name],
+		    module: User.moduleName,
+		    id: User.preferenceIds[ name ] || undefined
+		};
+
+	    return [returns];
+	});
+	
+	return notArray ? res[0] : res;
+    },
+
+    encoder: function( evtObj ){
+	var val = {}, id = {};
+	for (var i in evtObj){
+			
+	    if( evtObj[i].value && evtObj[i].id )
+	    {
+		val[evtObj[i].name] = evtObj[i].value;
+		id[evtObj[i].name] = evtObj[i].id;
+	    }
 	}
-}
-
-DataLayer.codec( "modulePreference", "detail", {
-	decoder: function( evtObj ){
-
-	if( notArray = $.type(evtObj) !== "array" )
-		evtObj = [ evtObj ];
-		
-		var res = $.map(evtObj, function( form ){
-
-			var returns = [];
-
-			for (var name in form)
-				returns[ returns.length ] = {
-					name: name,
-					user: User.me.id,
-					value: form[name],
-					module: User.moduleName,
-					id: User.preferenceIds[ name ] || undefined
-				};
-
-			return [returns];
-		});
-	
-	return notArray ? res[0] : res;
-	},
-
-    encoder: function( evtObj ){
-		var val = {}, id = {};
-		for (var i in evtObj){
-			
-			if( evtObj[i].value && evtObj[i].id )
-			{
-			    val[evtObj[i].name] = evtObj[i].value;
-			    id[evtObj[i].name] = evtObj[i].id;
-			}
-		}
-		return {values: val,ids: id};
-	
-	}
+	return {
+	    values: val,
+	    ids: id
+	};
+	
+    }
 });
 
@@ -273,12 +297,12 @@
   
     if( status === 'serverclient' ){
-		DataLayer.commit( false, false, function(){	
-			if((typeof($tabs) != "undefined") && $tabs.tabs('option' ,'selected') == 0){
-                                Calendar.rerenderView(true);
-			}else if((typeof($tabs) != "undefined") && $tabs.tabs('option' ,'selected') != 0)
-				pageselectCallback($('.events-list-win.active [name=keyword]').val(), 0);
-                        //Recarrega os alarmes de eventos    
-                        Alarms.load();
-		});
+	DataLayer.commit( false, false, function(){	
+	    if((typeof($tabs) != "undefined") && $tabs.tabs('option' ,'selected') == 0){
+		Calendar.rerenderView(true);
+	    }else if((typeof($tabs) != "undefined") && $tabs.tabs('option' ,'selected') != 0)
+		pageselectCallback($('.events-list-win.active [name=keyword]').val(), 0);
+	    //Recarrega os alarmes de eventos    
+	    Alarms.load();
+	});
     }
 });
@@ -304,10 +328,11 @@
 
     switch( status ){
-		case 'serverclient':  DataLayer.commit( false, false, function(){
-			User.load();
-		});
-		break;
-		case 'client':  
-		break;
+	case 'serverclient':
+	    DataLayer.commit( false, false, function(){
+	    User.load();
+	});
+	break;
+	case 'client':
+	    break;
     }
 
@@ -316,5 +341,5 @@
 DataLayer.listen( "alarm", function( created, updated, deleted ){
 
-});
+    });
 
 /*DataLayer.listen( "calendar", function( status, updateData ){
@@ -335,42 +360,51 @@
 
 DataLayer.codec( "calendarSignature", "configure", {
-	decoder: function( evtObj ){
-		Encoder.EncodeType = "entity";
-		
-		if( notArray = $.type(evtObj) !== "array" )
-			evtObj = [ evtObj ];
-		
-		var res = $.map(evtObj, function( form ){
-			return{
-				id: form.signature,
-				user: User.me.id,	
-				calendar: {
-					id: Calendar.calendarOf[form.signature].id,
-					name: Encoder.htmlEncode(form.name),
-					description: Encoder.htmlEncode(form.description),
-					timezone: form.timezone,
-					defaultDuration: form.duration != "" ? form.duration : 30,
-					location: form.location
-				},
-			//	isOwner: 1,
-				fontColor: Encoder.htmlEncode(form.fontColor.substring(1)),
-				backgroundColor: Encoder.htmlEncode(form.backgroundColor.substring(1)),
-				borderColor: Encoder.htmlEncode(form.borderColor.substring(1)),
-				msgAdd: Encoder.htmlEncode(form.msgAdd),
-				msgCancel: Encoder.htmlEncode(form.msgCancel),
-				msgUpdate: Encoder.htmlEncode(form.msgUpdate),
-				msgReply: Encoder.htmlEncode(form.msgReply),
-				msgAlarm: Encoder.htmlEncode(form.msgAlarm),
-				calendarSignatureAlarms: $.map( form.alarmTime || [], function( alarmTime, i ){
-					return (!!form.alarmId[i] ?
-							{type: form.alarmType[i],	unit: form.alarmUnit[i], time: form.alarmTime[i], id: form.alarmId[i]} :
-							{type: form.alarmType[i],	unit: form.alarmUnit[i], time: form.alarmTime[i]});
-				})
-			};
-		
-		});
+    decoder: function( evtObj ){
+	Encoder.EncodeType = "entity";
+		
+	if( notArray = $.type(evtObj) !== "array" )
+	    evtObj = [ evtObj ];
+		
+	var res = $.map(evtObj, function( form ){
+	    return{
+		id: form.signature,
+		user: User.me.id,	
+		calendar: {
+		    id: Calendar.calendarOf[form.signature].id,
+		    name: Encoder.htmlEncode(form.name),
+		    description: Encoder.htmlEncode(form.description),
+		    timezone: form.timezone,
+		    defaultDuration: form.duration != "" ? form.duration : 30,
+		    location: form.location
+		},
+		//	isOwner: 1,
+		fontColor: Encoder.htmlEncode(form.fontColor.substring(1)),
+		backgroundColor: Encoder.htmlEncode(form.backgroundColor.substring(1)),
+		borderColor: Encoder.htmlEncode(form.borderColor.substring(1)),
+		msgAdd: Encoder.htmlEncode(form.msgAdd),
+		msgCancel: Encoder.htmlEncode(form.msgCancel),
+		msgUpdate: Encoder.htmlEncode(form.msgUpdate),
+		msgReply: Encoder.htmlEncode(form.msgReply),
+		msgAlarm: Encoder.htmlEncode(form.msgAlarm),
+		calendarSignatureAlarms: $.map( form.alarmTime || [], function( alarmTime, i ){
+		    return (!!form.alarmId[i] ?
+		    {
+			type: form.alarmType[i],	
+			unit: form.alarmUnit[i], 
+			time: form.alarmTime[i], 
+			id: form.alarmId[i]
+			} :
+{
+			type: form.alarmType[i],	
+			unit: form.alarmUnit[i], 
+			time: form.alarmTime[i]
+			});
+		})
+	    };
+		
+	});
 	
 	return notArray ? res[0] : res;
-	},
+    },
 
     encoder: function( evtObj ){}
@@ -381,28 +415,28 @@
     decoder: function( evtObj ){},
 	
-	encoder: function (evtObjt){
-	
-			if(notArray = typeof(evtObjt) == 'array' )
-				evtObjt = [evtObjt];
+    encoder: function (evtObjt){
+	
+	if(notArray = typeof(evtObjt) == 'array' )
+	    evtObjt = [evtObjt];
 			
-			var res = $.map(evtObjt, function( objEvent ){	
-
-				var time = parseInt(objEvent.schedulable.startTime);
+	var res = $.map(evtObjt, function( objEvent ){	
+
+	    var time = parseInt(objEvent.schedulable.startTime);
 											
-				return{
-					id: objEvent.id,
-					event_start: new Date( time ).setTimezoneOffset(Timezone.timezones[objEvent.schedulable.timezone]).toString( User.preferences.dateFormat),
-					sendTime: objEvent.sendTime,
-					schedulable: {
-						startTime: dateCalendar.formatDate(Timezone.getDateEvent(new Date(time), objEvent.schedulable.timezone, objEvent.schedulable.DayLigth, 'startTime'), User.preferences.hourFormat),
-						id: objEvent.schedulable.id,
-						summary: objEvent.schedulable.summary,
-						time: objEvent.time,	
-						unit: dateCalendar.timeunit[objEvent.unit.toLowerCase()] + ( parseInt(objEvent.time) > 1 ? 's' : '' )
-					}
-				}
-			});
-		return notArray ? res[0] : res;
-	}
+	    return{
+		id: objEvent.id,
+		event_start: new Date( time ).setTimezoneOffset(Timezone.timezones[objEvent.schedulable.timezone]).toString( User.preferences.dateFormat),
+		sendTime: objEvent.sendTime,
+		schedulable: {
+		    startTime: dateCalendar.formatDate(Timezone.getDateEvent(new Date(time), objEvent.schedulable.timezone, objEvent.schedulable.DayLigth, 'startTime'), User.preferences.hourFormat),
+		    id: objEvent.schedulable.id,
+		    summary: objEvent.schedulable.summary,
+		    time: objEvent.time,	
+		    unit: dateCalendar.timeunit[objEvent.unit.toLowerCase()] + ( parseInt(objEvent.time) > 1 ? 's' : '' )
+		}
+	    }
+	});
+	return notArray ? res[0] : res;
+    }
 });
 
@@ -410,30 +444,30 @@
 
     decoder: function( evtObj ){
-		if( notArray = $.type(evtObj) !== "array" )
-			evtObj = [ evtObj ];
-
-
-
-		var meAttendee = function(attendees){
-			for(var i = 0; i < attendees.length; i++)
-				if(DataLayer.get('participant', attendees[i]).user == User.me.id)
-					return attendee;
-		};
-
-		var res = $.map(evtObj, function( form ){	
-			return {
-				participant : meAttendee(form.attendee), 
-				startTime: Date.parseExact(form.startDate + (!!form.allDay ? " 00:00": " "+$.trim(form.startHour)) , formatString ).toString('yyyy-MM-dd HH:mm:00'),
-				endTime:  Date.parseExact(form.endDate + ( !!form.allDay ? " 00:00": " "+$.trim(form.endHour)), formatString ).toString('yyyy-MM-dd HH:mm:00'),
-				allDay: ( !!form.allDay ? 1 : 0 ),
-				schedulable: form.idEvent
-			}
-		});	
+	if( notArray = $.type(evtObj) !== "array" )
+	    evtObj = [ evtObj ];
+
+
+
+	var meAttendee = function(attendees){
+	    for(var i = 0; i < attendees.length; i++)
+		if(DataLayer.get('participant', attendees[i]).user == User.me.id)
+		    return attendee;
+	};
+
+	var res = $.map(evtObj, function( form ){	
+	    return {
+		participant : meAttendee(form.attendee), 
+		startTime: Date.parseExact(form.startDate + (!!form.allDay ? " 00:00": " "+$.trim(form.startHour)) , formatString ).toString('yyyy-MM-dd HH:mm:00'),
+		endTime:  Date.parseExact(form.endDate + ( !!form.allDay ? " 00:00": " "+$.trim(form.endHour)), formatString ).toString('yyyy-MM-dd HH:mm:00'),
+		allDay: ( !!form.allDay ? 1 : 0 ),
+		schedulable: form.idEvent
+	    }
+	});	
 	
 
 	return notArray ? res[0] : res;
-	},
-	
-	encoder: function( evtObj ){}
+    },
+	
+    encoder: function( evtObj ){}
 	
 });
@@ -441,18 +475,20 @@
 DataLayer.codec( "attachment", "detail", {
   
-	decoder: function(evtObj){
-	
-		if( notArray = $.type(evtObj) !== "array" )
-			evtObj = [ evtObj ];
-
-		var res = $.map(evtObj, function( form){
-			return [$.map(form.files , function( files){
-					return { source: files };
-				})];
-		});
+    decoder: function(evtObj){
+	
+	if( notArray = $.type(evtObj) !== "array" )
+	    evtObj = [ evtObj ];
+
+	var res = $.map(evtObj, function( form){
+	    return [$.map(form.files , function( files){
+		return {
+		    source: files
+		};
+	    })];
+	});
 	return notArray ? res[0] : res;
-	},
+    },
       
-	encoder: function(){}
+    encoder: function(){}
 
       
@@ -462,69 +498,78 @@
 
     decoder: function( evtObj ){
-		Encoder.EncodeType = "entity";
-	
-		if( notArray = $.type(evtObj) !== "array" )
-			evtObj = [ evtObj ];
-
-		var pref = User.preferences;
-		
-		var Owner = decodeOwnerCalendar(evtObj.calendar);	
-
-		var res = $.map(evtObj, function( form ){
+	Encoder.EncodeType = "entity";
+	
+	if( notArray = $.type(evtObj) !== "array" )
+	    evtObj = [ evtObj ];
+
+	var pref = User.preferences;
+		
+	var Owner = decodeOwnerCalendar(evtObj.calendar);	
+
+	var res = $.map(evtObj, function( form ){
 			
-			return {
-				id: form.idEvent,
-				calendar: form.calendar,
-				participants : $.map(form.attendee, function( attendee, i ){
-					if(isNaN(attendee)){
-					    return{
-						    id: attendee,
-						    acl: form.attendeeAcl[i],
-						    delegatedFrom: !!form.delegatedFrom[i] ? form.delegatedFrom[i] : 0,
-						    isOrganizer: (form.attendee_organizer == attendee ? 1 : 0 ),
-						    isExternal: !!parseInt(form.attendeeType[i]) ? 1 : 0,
-						    acl: form.attendeeAcl[i].replace('o', '')
-					    };
-					}else{
-						if(DataLayer.get('participant', attendee).user == Owner.id){
-							var me = {
-							    user: User.id,
-							    status: form.status,
-							    id: attendee,
-							    isOrganizer: 0,
-							    receiveNotification : (!!form.receiveNotification ? 1 : 0),
-							    alarms: typeof(form.alarmTime) != 'undefined' ? 
-								$.map( form.alarmTime || [], function( alarmTime, i ){
-
-								    if( alarmTime === "" )
-									    return( null );
-
-								    return !!form.alarmId[i] ?
-									    { type: form.alarmType[i], unit: form.alarmUnit[i], time: form.alarmTime[i], id: form.alarmId[i] } : 
-									    { type: form.alarmType[i],unit: form.alarmUnit[i], time: form.alarmTime[i] };
-								    }) : []
-						    };
+	    return {
+		id: form.idEvent,
+		calendar: form.calendar,
+		participants : $.map(form.attendee, function( attendee, i ){
+		    if(isNaN(attendee)){
+			return{
+			    id: attendee,
+			    acl: form.attendeeAcl[i],
+			    delegatedFrom: !!form.delegatedFrom[i] ? form.delegatedFrom[i] : 0,
+			    isOrganizer: (form.attendee_organizer == attendee ? 1 : 0 ),
+			    isExternal: !!parseInt(form.attendeeType[i]) ? 1 : 0,
+			    acl: form.attendeeAcl[i].replace('o', '')
+			};
+		    }else{
+			if(DataLayer.get('participant', attendee).user == Owner.id){
+			    var me = {
+				user: User.id,
+				status: form.status,
+				id: attendee,
+				isOrganizer: 0,
+				receiveNotification : (!!form.receiveNotification ? 1 : 0),
+				alarms: typeof(form.alarmTime) != 'undefined' ? 
+				$.map( form.alarmTime || [], function( alarmTime, i ){
+
+				    if( alarmTime === "" )
+					return( null );
+
+				    return !!form.alarmId[i] ?
+				    {
+					type: form.alarmType[i], 
+					unit: form.alarmUnit[i], 
+					time: form.alarmTime[i], 
+					id: form.alarmId[i]
+					} : 
+{
+					type: form.alarmType[i],
+					unit: form.alarmUnit[i], 
+					time: form.alarmTime[i]
+					};
+				}) : []
+			    };
 							
-							if(form.startDate){
-								var tzId =  DataLayer.get('schedulable', form.idEvent).timezone || User.preferences.timezone,
-								formatString = ( typeof form.allDay !== "undefined" && !!form.allDay )? pref.dateFormat+" HH:mm" : pref.dateFormat + " " + pref.hourFormat;
+			    if(form.startDate){
+				var tzId =  DataLayer.get('schedulable', form.idEvent).timezone || User.preferences.timezone,
+				formatString = ( typeof form.allDay !== "undefined" && !!form.allDay )? pref.dateFormat+" HH:mm" : pref.dateFormat + " " + pref.hourFormat;
 								
-								DataLayer.put('notification', {
-								    participant: me.id,
-								    type: 'suggestion',
-								    startTime: Date.parseExact(form.startDate + (!!form.allDay ? " 00:00": " "+$.trim(form.startHour)) , formatString ).toString('yyyy-MM-dd HH:mm:00'),
-								    endTime:  Date.parseExact(form.endDate + ( !!form.allDay ? " 00:00": " "+$.trim(form.endHour)), formatString ).toString('yyyy-MM-dd HH:mm:00'),
-								    allDay: ( !!form.allDay ? 1 : 0 ),
-								    schedulable: form.idEvent
-								});
+				DataLayer.put('notification', {
+				    participant: me.id,
+				    type: 'suggestion',
+				    startTime: Date.parseExact(form.startDate + (!!form.allDay ? " 00:00": " "+$.trim(form.startHour)) , formatString ).toString('yyyy-MM-dd HH:mm:00'),
+				    endTime:  Date.parseExact(form.endDate + ( !!form.allDay ? " 00:00": " "+$.trim(form.endHour)), formatString ).toString('yyyy-MM-dd HH:mm:00'),
+				    allDay: ( !!form.allDay ? 1 : 0 ),
+				    schedulable: form.idEvent
+				});
 							
-							}
-							return me;
-						}else return(null);
-					};
-				})
-			}
-		});
-		return notArray ? res[0] : res;
+			    }
+			    return me;
+			}else return(null);
+		    };
+		})
+	    }
+	});
+	return notArray ? res[0] : res;
     },
 
@@ -543,106 +588,117 @@
 	
 	for( var i = 0; i < statusLabels.length; i++ )
-		statusParticipants[ statusLabels[i] ] = 0;
+	    statusParticipants[ statusLabels[i] ] = 0;
 	
 	var res = $.map(evtObj, function( objEvent ){			
 		    
-			if(!(typeof(objEvent) == 'object'))
-				return (null);
-
-			var Owner = decodeOwnerCalendar(objEvent.calendar);
-
-			var participantInfo = {}, delegatedFrom = {}, me = DataLayer.copy( Owner );
+	    if(!(typeof(objEvent) == 'object'))
+		return (null);
+
+	    var isAttendee = false;
+	    var Owner = decodeOwnerCalendar(objEvent.calendar);
+
+	    var participantInfo = {}, delegatedFrom = {}, me = DataLayer.copy( Owner );
 			
-			var constantAcl = function(acl){
-			var returns = {};
-			for (var i in constantsParticipant){
-				returns[constantsParticipant[i]] = acl.indexOf(i) >= 0 ? true : false
-			}
-			return returns;
+	    var constantAcl = function(acl){
+		var returns = {};
+		for (var i in constantsParticipant){
+		    returns[constantsParticipant[i]] = acl.indexOf(i) >= 0 ? true : false
+		}
+		return returns;
+	    };
+
+	    return {
+		"class": objEvent["class"],
+		id: objEvent.id,
+		repeat: encodeRepeat( objEvent.repeat ),
+		location: objEvent.location,
+		category: objEvent.category,
+		calendars: Calendar.calendars,
+		calendar: objEvent.calendar,
+		summary: objEvent.summary,
+		description: objEvent.description,
+		timezone: objEvent.timezone,
+		timezones: Timezone.timezones,
+		startDate: new Date( parseInt(objEvent.startTime) ).setTimezoneOffset( Timezone.timezone( objEvent.timezone ) ).toString( User.preferences.dateFormat ),
+		startHour: dateCalendar.formatDate(Timezone.getDateEvent(new Date( parseInt(objEvent.startTime)), objEvent.timezone, objEvent.calendar, objEvent.DayLigth, 'startTime'), User.preferences.hourFormat),
+		endDate: new Date( parseInt(objEvent.endTime) - (!!parseInt(objEvent.allDay) ? 86400000 : 0)  ).setTimezoneOffset( Timezone.timezone( objEvent.timezone ) ).toString( User.preferences.dateFormat ),
+		endHour: dateCalendar.formatDate(Timezone.getDateEvent(new Date(parseInt(objEvent.endTime)),  objEvent.timezone, objEvent.calendar, objEvent.DayLigth, 'endTime'), User.preferences.hourFormat),
+		allDay: !!parseInt( objEvent.allDay ),
+		attachments: $.map(objEvent.attachments || [], function( attachment, i ){
+		    var attach = DataLayer.get('schedulableToAttachment', attachment, false);
+		    var ext = attach.name.split('.');
+		    attach.name = attach.name.length < 10 ?  attach.name : ( ext.length == 1 ? attach.name.substr(0, 10) : (attach.name.substr(0, 6) + '.' +  ext[ext.length -1]));
+		    attach.size = formatBytes(attach.size);
+		    return attach;
+		}),						
+		attendee: $.map(objEvent.participants || [], function( participant, i ){						
+
+		    if(delegateAttendee[participant])
+			return(null);
+
+		    var attend = DataLayer.get('participant', (participant.id || participant));
+		    attend.user = DataLayer.get('user', attend.user);
+
+		    statusParticipants[ statusLabels[attend.status] ]++;  	
+
+		    if(attend.user.mail == User.me.mail)
+			isAttendee = true;
+
+		    if( attend.user.id ===  me.id ){
+			participantInfo.user = {
+			    id: attend.id,
+			    status : attend.status,
+			    delegatedFrom: attend.delegatedFrom || '0',
+			    acl: attend.acl,
+			    receiveNotification : attend.receiveNotification,
+			    alarms : $.map(attend.alarms || [], function( alarm ){
+				var alarm = DataLayer.get('alarm', alarm);
+				return (alarm == "" ? (null) : alarm);
+			    })
 			};
-
-		    return {
-			    "class": objEvent["class"],
-			    id: objEvent.id,
-			    repeat: encodeRepeat( objEvent.repeat ),
-			    location: objEvent.location,
-			    category: objEvent.category,
-			    calendars: Calendar.calendars,
-			    calendar: objEvent.calendar,
-			    summary: objEvent.summary,
-			    description: objEvent.description,
-			    timezone: objEvent.timezone,
-			    timezones: Timezone.timezones,
-			    startDate: new Date( parseInt(objEvent.startTime) ).setTimezoneOffset( Timezone.timezone( objEvent.timezone ) ).toString( User.preferences.dateFormat ),
-			    startHour: dateCalendar.formatDate(Timezone.getDateEvent(new Date( parseInt(objEvent.startTime)), objEvent.timezone, objEvent.calendar, objEvent.DayLigth, 'startTime'), User.preferences.hourFormat),
-			    endDate: new Date( parseInt(objEvent.endTime) - (!!parseInt(objEvent.allDay) ? 86400000 : 0)  ).setTimezoneOffset( Timezone.timezone( objEvent.timezone ) ).toString( User.preferences.dateFormat ),
-			    endHour: dateCalendar.formatDate(Timezone.getDateEvent(new Date(parseInt(objEvent.endTime)),  objEvent.timezone, objEvent.calendar, objEvent.DayLigth, 'endTime'), User.preferences.hourFormat),
-			    allDay: !!parseInt( objEvent.allDay ),
-			    attachments: $.map(objEvent.attachments || [], function( attachment, i ){
-					var attach = DataLayer.get('schedulableToAttachment', attachment, false);
-                                        var ext = attach.name.split('.');
-					attach.name = attach.name.length < 10 ?  attach.name : ( ext.length == 1 ? attach.name.substr(0, 10) : (attach.name.substr(0, 6) + '.' +  ext[ext.length -1]));
-					attach.size = formatBytes(attach.size);
-					return attach;
-				}),						
-			    attendee: $.map(objEvent.participants || [], function( participant, i ){						
-
-				if(delegateAttendee[participant])
-					return(null);
-
-				var attend = DataLayer.get('participant', (participant.id || participant));
-				attend.user = DataLayer.get('user', attend.user);
-
-				statusParticipants[ statusLabels[attend.status] ]++;  	
-
-				if( attend.user.id ===  me.id ){
-				    participantInfo.user = {
-					id: attend.id,
-					status : attend.status,
-					delegatedFrom: attend.delegatedFrom || '0',
-					acl: attend.acl,
-					receiveNotification : attend.receiveNotification,
-					alarms : $.map(attend.alarms || [], function( alarm ){
-					    var alarm = DataLayer.get('alarm', alarm);
-					    return (alarm == "" ? (null) : alarm);
-					})
-				    };
-				    me.id = attend.id;
-				    return(null);
-				};
-
-				var person = {
-				    id: attend.id,
-				    name: attend.user.name != 'false' ? attend.user.name : '',
-				    mail: attend.user.mail,
-				    status : attend.status,
-				    isExternal: attend.isExternal,
-				    acl: attend.acl,
-				    delegatedFrom: attend.delegatedFrom
-				};
-
-				if(!!parseInt(attend.delegatedFrom)){
-				    delegatedFrom[attend.delegatedFrom] = DataLayer.copy(person);
-					return(null);
-				}
-
-				if( !!parseInt(attend.isOrganizer )){
-				    participantInfo.organizer = DataLayer.copy(person);
-					return(null);
-				};					
-
-				return (person);
-			    }),
-			    organizer: participantInfo.organizer || me,
-			    alarms: !!participantInfo.user ? participantInfo.user.alarms : [],
-			    status: !!participantInfo.user ? participantInfo.user.status : 1,
-				acl: !!participantInfo.user ? constantAcl(participantInfo.user.acl) : constantAcl( 'rowi' ),
-				isShared: !this.id ? false : (!!objEvent.calendar) && parseInt(Calendar.signatureOf[objEvent.calendar].isOwner) ? false : true,
-			    me: !!participantInfo.user ? DataLayer.merge(participantInfo.user, me) : DataLayer.merge(this.isShared ? this.organizer :  me, {acl:  !this.isShared ? 'rowi' : Calendar.signatureOf[objEvent.calendar].permission.aclValues, delegatedFrom: 0, receiveNotification: 1}),
-				delegatedFrom: delegatedFrom,
+			me.id = attend.id;
+			return(null);
+		    };
+
+		    var person = {
+			id: attend.id,
+			name: attend.user.name != 'false' ? attend.user.name : '',
+			mail: attend.user.mail,
+			status : attend.status,
+			isExternal: attend.isExternal,
+			acl: attend.acl,
+			delegatedFrom: attend.delegatedFrom
+		    };
+
+		    if(!!parseInt(attend.delegatedFrom)){
+			delegatedFrom[attend.delegatedFrom] = DataLayer.copy(person);
+			return(null);
+		    }
+
+		    if( !!parseInt(attend.isOrganizer )){
+			participantInfo.organizer = DataLayer.copy(person);
+			return(null);
+		    };					
+
+		    return (person);
+		}),
+		organizer: participantInfo.organizer || me,
+		alarms: !!participantInfo.user ? participantInfo.user.alarms : [],
+		status: !!participantInfo.user ? participantInfo.user.status : 1,
+		acl: !!participantInfo.user ? constantAcl(participantInfo.user.acl) : ( ( !objEvent.id || isAttendee ) ? constantAcl( 'rowi' ) : constantAcl( 'r' )),
+		isShared: !this.id ? false : (!!objEvent.calendar) && parseInt(Calendar.signatureOf[objEvent.calendar].isOwner) ? false : true,
+		isAttendee: (isAttendee ? true : (objEvent.id && !this.isShared ? false : true)),
+		me: ((!objEvent.id) || ( objEvent.id && isAttendee)) ? (!!participantInfo.user ? DataLayer.merge(participantInfo.user, me) : DataLayer.merge(this.isShared ? this.organizer :  me, {
+		    acl:  !this.isShared ? 'rowi' : Calendar.signatureOf[objEvent.calendar].permission.aclValues, 
+		    delegatedFrom: 0, 
+		    receiveNotification: 1
+		})) : (DataLayer.merge( ( participantInfo.organizer || me), {
+		    acl: 'r'
+		} ) ),
+		delegatedFrom: delegatedFrom,
 				
-				statusParticipants: statusParticipants
-			};
-		});
+		statusParticipants: statusParticipants
+	    };
+	});
 	return (notArray ? res[0] : res);
     }
@@ -652,12 +708,17 @@
 function decodeOwnerCalendar(calendar){
     if(calendar && !parseInt(Calendar.signatureOf[calendar].isOwner)){
-	var Owner = DataLayer.get('calendarSignature', {filter: ['AND', ['=','calendar', calendar], ['=','isOwner','1']], criteria: {deepness: 2}});
-
-	if($.isArray(Owner))
-	    Owner = Owner[0];
-	
-	return Owner.user;
-    }
-    return User.me;
+	var Owner = DataLayer.get('calendarSignature', {
+	    filter: ['AND', ['=','calendar', calendar], ['=','isOwner','1']], 
+	    criteria: {
+		deepness: 2
+	    }
+	});
+
+    if($.isArray(Owner))
+	Owner = Owner[0];
+	
+    return Owner.user;
+}
+return User.me;
 
     
@@ -666,57 +727,57 @@
 function decodeRepeat ( form ) {
 
-	var patati = {};
-	
-	if( form.repeatId )
-	    patati['id'] = form.repeatId;
-
-	patati['frequency'] = form.frequency;
-
- 	patati['bymonthday'] = patati['byyearday'] = patati['byday'] = '';
-	
-	patati['interval'] = patati['endTime'] = patati['count'] = patati['startTime'] = 0;
-	
-	if( form.frequency === 'none' )
-	    return( patati );
-	
-	var day = [];
-
-	$("input[type=checkbox][name='repeatweekly[]']:checked").each(function() { 
-		day[ day.length ] = $(this).val();
-	});
-
-	patati['byday'] = day.join(',');
-
-	var formatString = ( typeof form.allDay !== "undefined" && !!form.allDay )? User.preferences.dateFormat+" HH:mm" : User.preferences.dateFormat + " " + User.preferences.hourFormat;
-
-	var date = Date.parseExact( form.startDate + (!!form.allDay ? " 00:00": " "+$.trim(form.startHour)) , formatString );
-	
-	patati['startTime'] = date.toString('yyyy-MM-dd HH:mm:00');
-	
-	if( !patati['byday'] )
-	      switch(form.frequency) {
-	      case 'weekly':      
-		      break;
-	      case 'daily':
-		      break;
-	      case 'monthly':
-		      patati['bymonthday'] = date.getDate();
-		      break;
-	      case 'yearly':
-		      patati['byyearday'] = date.getDayOfYear();
-		      break;
-	      default :
-		      return patati;
-	      }
-
-	if (($(".endRepeat").val() == 'occurrences')) 
-		patati['count'] = $(".occurrencesEnd").val(); 
-	
-	if (($(".endRepeat").val() == 'customDate'))
-		patati['endTime'] = Date.parseExact( $(".customDateEnd").val() + (!!form.allDay ? " 00:00": " "+$.trim(form.endHour)) , formatString ).toString('yyyy-MM-dd HH:mm:00');
-	
-	patati['interval']  = $(".eventInterval").val();
-
-	/**
+    var patati = {};
+	
+    if( form.repeatId )
+	patati['id'] = form.repeatId;
+
+    patati['frequency'] = form.frequency;
+
+    patati['bymonthday'] = patati['byyearday'] = patati['byday'] = '';
+	
+    patati['interval'] = patati['endTime'] = patati['count'] = patati['startTime'] = 0;
+	
+    if( form.frequency === 'none' )
+	return( patati );
+	
+    var day = [];
+
+    $("input[type=checkbox][name='repeatweekly[]']:checked").each(function() { 
+	day[ day.length ] = $(this).val();
+    });
+
+    patati['byday'] = day.join(',');
+
+    var formatString = ( typeof form.allDay !== "undefined" && !!form.allDay )? User.preferences.dateFormat+" HH:mm" : User.preferences.dateFormat + " " + User.preferences.hourFormat;
+
+    var date = Date.parseExact( form.startDate + (!!form.allDay ? " 00:00": " "+$.trim(form.startHour)) , formatString );
+	
+    patati['startTime'] = date.toString('yyyy-MM-dd HH:mm:00');
+	
+    if( !patati['byday'] )
+	switch(form.frequency) {
+	    case 'weekly':
+		break;
+	    case 'daily':
+		break;
+	    case 'monthly':
+		patati['bymonthday'] = date.getDate();
+		break;
+	    case 'yearly':
+		patati['byyearday'] = date.getDayOfYear();
+		break;
+	    default :
+		return patati;
+	}
+
+    if (($(".endRepeat").val() == 'occurrences')) 
+	patati['count'] = $(".occurrencesEnd").val(); 
+	
+    if (($(".endRepeat").val() == 'customDate'))
+	patati['endTime'] = Date.parseExact( $(".customDateEnd").val() + (!!form.allDay ? " 00:00": " "+$.trim(form.endHour)) , formatString ).toString('yyyy-MM-dd HH:mm:00');
+	
+    patati['interval']  = $(".eventInterval").val();
+
+    /**
 	wkst = [ 'MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU' ]
 	weekno = number
@@ -740,10 +801,10 @@
 function encodeRepeat( repeat ){
   
-	if( !repeat )
-	    return( false );
-	if(typeof(repeat) == "object")
-	    return repeat;
-
-	return DataLayer.get( 'repeat', repeat );
+    if( !repeat )
+	return( false );
+    if(typeof(repeat) == "object")
+	return repeat;
+
+    return DataLayer.get( 'repeat', repeat );
 }
 
@@ -755,5 +816,5 @@
 	
 	if( notArray = $.type(evtObj) !== "array" )
-		evtObj = [ evtObj ];
+	    evtObj = [ evtObj ];
 
 	var pref = User.preferences;
@@ -761,59 +822,75 @@
 	var res = $.map(evtObj, function( form ){
     
-		    var tzId =  form.timezone || Calendar.signatureOf[form.calendar].calendar.timezone || User.preferences.timezone,
-
-		    formatString = ( typeof form.allDay !== "undefined" && !!form.allDay )? pref.dateFormat+" HH:mm" : pref.dateFormat + " " + pref.hourFormat;
-
-		    var Owner = decodeOwnerCalendar(form.calendar);
-
+	    var tzId =  form.timezone || Calendar.signatureOf[form.calendar].calendar.timezone || User.preferences.timezone,
+
+	    formatString = ( typeof form.allDay !== "undefined" && !!form.allDay )? pref.dateFormat+" HH:mm" : pref.dateFormat + " " + pref.hourFormat;
+
+	    var Owner = decodeOwnerCalendar(form.calendar);
+
+	    return {
+		"class": form["class"],
+		startTime: Date.parseExact(form.startDate + (!!form.allDay ? " 00:00": " "+$.trim(form.startHour)) , formatString ).toString('yyyy-MM-dd HH:mm:00'),
+		endTime:  Date.parseExact(form.endDate + ( !!form.allDay ? " 00:00": " "+$.trim(form.endHour)), formatString ).toString('yyyy-MM-dd HH:mm:00'),  //+ (!!form.allDay ? 86400000 : 0) ,
+		allDay: ( !!form.allDay ? 1 : 0 ),       
+		id: form.idEvent,
+		location: form.location,
+		category: form.category,
+		calendar: form.calendar,
+		summary: form.summary,
+		description: form.description,
+		timezone: tzId,
+		attachments: $.map(form.attachment || [], function( attachment, i ){
 		    return {
-			    "class": form["class"],
-			    startTime: Date.parseExact(form.startDate + (!!form.allDay ? " 00:00": " "+$.trim(form.startHour)) , formatString ).toString('yyyy-MM-dd HH:mm:00'),
-			    endTime:  Date.parseExact(form.endDate + ( !!form.allDay ? " 00:00": " "+$.trim(form.endHour)), formatString ).toString('yyyy-MM-dd HH:mm:00'),  //+ (!!form.allDay ? 86400000 : 0) ,
-			    allDay: ( !!form.allDay ? 1 : 0 ),       
-			    id: form.idEvent,
-			    location: form.location,
-			    category: form.category,
-			    calendar: form.calendar,
-			    summary: form.summary,
-			    description: form.description,
-			    timezone: tzId,
-			    attachments: $.map(form.attachment || [], function( attachment, i ){
-					return {attachment: attachment}
+			attachment: attachment
+		    }
+		}),
+		repeat: this.decodeRepeat( form ),
+		participants: $.map( form.attendee || [], function( attendee, i ){
+
+		    if( !attendee || attendee === "" )
+			return( null );
+
+		    var participant = {};
+		    participant.user = (attendee!= User.me.id) ? DataLayer.get('participant', attendee).user : attendee ;
+
+		    if( participant.user === Owner.id ){
+			return DataLayer.merge({
+			    id: attendee,
+			    isOrganizer: (form.attendee_organizer == attendee ? 1 : 0 ),
+			    acl: form.attendee_organizer == attendee ? (form.attendeeAcl[i].indexOf('o') < 0 ? form.attendeeAcl[i]+'o' : form.attendeeAcl[i]) : form.attendeeAcl[i].replace('o', ''),
+			    alarms: participant.alarms = $.map( form.alarmTime || [], function( alarmTime, i ){
+				if( alarmTime === "" )
+				    return( null );
+				return !!form.alarmId[i] ? {
+				    type: form.alarmType[i], 
+				    unit: form.alarmUnit[i], 
+				    time: form.alarmTime[i], 
+				    id: form.alarmId[i]
+				    }:
+
+				    {
+				    type: form.alarmType[i],
+				    unit: form.alarmUnit[i], 
+				    time: form.alarmTime[i]
+				    };
 			    }),
-			    repeat: this.decodeRepeat( form ),
-			    participants: $.map( form.attendee || [], function( attendee, i ){
-
-				if( !attendee || attendee === "" )
-				    return( null );
-
-				var participant = {};
-				participant.user = (attendee!= User.me.id) ? DataLayer.get('participant', attendee).user : attendee ;
-
-				if( participant.user === Owner.id ){
-				    return DataLayer.merge({
-				    id: attendee,
-				    isOrganizer: (form.attendee_organizer == attendee ? 1 : 0 ),
-				    acl: form.attendee_organizer == attendee ? (form.attendeeAcl[i].indexOf('o') < 0 ? form.attendeeAcl[i]+'o' : form.attendeeAcl[i]) : form.attendeeAcl[i].replace('o', ''),
-				    alarms: participant.alarms = $.map( form.alarmTime || [], function( alarmTime, i ){
-					if( alarmTime === "" )
-					    return( null );
-					return !!form.alarmId[i] ? { type: form.alarmType[i], unit: form.alarmUnit[i], time: form.alarmTime[i], id: form.alarmId[i] }:
-					    { type: form.alarmType[i],unit: form.alarmUnit[i], time: form.alarmTime[i] };
-					}),
-				    status: !!form.status ? form.status : 3
-				    }, form.delegatedFrom[i] != '0' ? {delegatedFrom: form.delegatedFrom[i]} : {});
-				}else{
-				    return DataLayer.merge({
-					id: attendee,
-					acl: form.attendeeAcl[i],
-					isOrganizer: (form.attendee_organizer == attendee ? 1 : 0 ),
-					isExternal: !!parseInt(form.attendeeType[i]) ? 1 : 0,
-					acl: form.attendee_organizer == attendee ? (form.attendeeAcl[i].indexOf('o') < 0 ? form.attendeeAcl[i]+'o' : form.attendeeAcl[i]) : form.attendeeAcl[i].replace('o', '')
-				    }, form.delegatedFrom[i] != '0' ? {delegatedFrom: form.delegatedFrom[i]} : {});
-				};
-			    })
-			};
-		    });
+			    status: !!form.status ? form.status : 3
+			}, (form.delegatedFrom[i] != '0' && form.delegatedFrom[i] != '')  ? {
+			    delegatedFrom: form.delegatedFrom[i]
+			    } : {});
+		    }else{
+			return DataLayer.merge({
+			    id: attendee,
+			    acl: form.attendeeAcl[i],
+			    isOrganizer: (form.attendee_organizer == attendee ? 1 : 0 ),
+			    isExternal: !!parseInt(form.attendeeType[i]) ? 1 : 0,
+			    acl: form.attendee_organizer == attendee ? (form.attendeeAcl[i].indexOf('o') < 0 ? form.attendeeAcl[i]+'o' : form.attendeeAcl[i]) : form.attendeeAcl[i].replace('o', '')
+			}, form.delegatedFrom[i] != '0' ? {
+			    delegatedFrom: form.delegatedFrom[i]
+			    } : {});
+		    };
+		})
+	    };
+	});
 
 	return notArray ? res[0] : res;
@@ -823,68 +900,77 @@
     encoder: function( evtObj ){
 	
-		if(!(!!evtObj))
-			return undefined;
-
-		var notArray = false;
+	if(!(!!evtObj))
+	    return undefined;
+
+	var notArray = false;
 		  
-		if( notArray = $.type(evtObj) !== "array" )
-			evtObj = [ evtObj ];
-
-		var pref = User.preferences;
-
-		var res =  DataLayer.encode('schedulable:preview', evtObj);
-
-		if( !notArray ){
-			var dates = {};
-			var typeRepeat = {'none': false, 
-					'daily': 'Repetição diária',
-					'weekly': 'Repetição semanal',
-					'monthly': 'Repetição mensal',
-					'yearly': 'repetição anual'}
-
-			for (var i=0; i < res.length; i++) {
+	if( notArray = $.type(evtObj) !== "array" )
+	    evtObj = [ evtObj ];
+
+	var pref = User.preferences;
+
+	var res =  DataLayer.encode('schedulable:preview', evtObj);
+
+	if( !notArray ){
+	    var dates = {};
+	    var typeRepeat = {
+		'none': false, 
+		'daily': 'Repetição diária',
+		'weekly': 'Repetição semanal',
+		'monthly': 'Repetição mensal',
+		'yearly': 'repetição anual'
+	    }
+
+	    for (var i=0; i < res.length; i++) {
 			  
-				var startDate = Date.parseExact( res[i]['startDate'], User.preferences.dateFormat );
-				var endDate   = Date.parseExact( res[i]['endDate'], User.preferences.dateFormat );
+		var startDate = Date.parseExact( res[i]['startDate'], User.preferences.dateFormat );
+		var endDate   = Date.parseExact( res[i]['endDate'], User.preferences.dateFormat );
 			  
-				var duration = parseInt( endDate.getTime() ) - parseInt( startDate.getTime() );
-		
-				var occurrences = [ startDate.getTime() ];
+		var duration = parseInt( endDate.getTime() ) - parseInt( startDate.getTime() );
+		
+		var occurrences = [ startDate.getTime() ];
 				
-				if( res[i].occurrences )
-				{
-				    occurrences = res[i].occurrences;
-				}
-
-				for( var ii = 0; ii < occurrences.length; ii++ )
-				{
-				    var currentDate = new Date( occurrences[ii] );
-				    var counter = currentDate.clone();
+		if( res[i].occurrences )
+		{
+		    occurrences = res[i].occurrences;
+		}
+
+		for( var ii = 0; ii < occurrences.length; ii++ )
+		{
+		    var currentDate = new Date( occurrences[ii] );
+		    var counter = currentDate.clone();
 				    
-				    var res2 = $.extend( {}, res[i], {'startDate': currentDate.toString( User.preferences.dateFormat ), 'endDate': new Date( occurrences[ii] + duration ).toString( User.preferences.dateFormat ) } );
+		    var res2 = $.extend( {}, res[i], {
+			'startDate': currentDate.toString( User.preferences.dateFormat ), 
+			'endDate': new Date( occurrences[ii] + duration ).toString( User.preferences.dateFormat )
+			} );
 				  
 				  
 				  
 				  
-				    res2.repeat = typeRepeat[res[i].repeat.frequency];
+		    res2.repeat = typeRepeat[res[i].repeat.frequency];
 				  
-				    while (counter.compareTo( currentDate ) == 0) {
-
-					    if (!dates[counter.toString(User.preferences.dateFormat)]) 
-						    dates[counter.toString(User.preferences.dateFormat)] = { startDate:false, events:[] };
-					    if (!dates[counter.toString(User.preferences.dateFormat)].startDate) 
-						    dates[counter.toString(User.preferences.dateFormat)].startDate = counter.toString(User.preferences.dateFormat);
-
-					    dates[counter.toString(User.preferences.dateFormat)].events.push(res2);
-					    counter.addDays(-1);
-				    }      
-				}
-			}
-			res = { events_list: dates,
-					count : res.length
-				};
+		    while (counter.compareTo( currentDate ) == 0) {
+
+			if (!dates[counter.toString(User.preferences.dateFormat)]) 
+			    dates[counter.toString(User.preferences.dateFormat)] = {
+				startDate:false, 
+				events:[]
+			    };
+			if (!dates[counter.toString(User.preferences.dateFormat)].startDate) 
+			    dates[counter.toString(User.preferences.dateFormat)].startDate = counter.toString(User.preferences.dateFormat);
+
+			dates[counter.toString(User.preferences.dateFormat)].events.push(res2);
+			counter.addDays(-1);
+		    }      
 		}
-
-		return notArray ? res[0] : res;
+	    }
+	    res = {
+		events_list: dates,
+		count : res.length
+	    };
+	}
+
+	return notArray ? res[0] : res;
     }
 
@@ -895,9 +981,9 @@
     encoder: function( participants ){
 
-		var result = {};
-		for( var i = 0; i< participants.length; i++ ){
-			result[ participants[i].user.id || participants[i].user ] = participants[i];
-		}
-		return( result );
+	var result = {};
+	for( var i = 0; i< participants.length; i++ ){
+	    result[ participants[i].user.id || participants[i].user ] = participants[i];
+	}
+	return( result );
     }
 });
@@ -907,14 +993,19 @@
     encoder: function( calendars ){
 
-		var result = { my_calendars: [], others_calendars: [] };
-
-		for( var i = 0; i < calendars.length; i++ )
-		{
-			!!Calendar.signatureOf[ calendars[i].id ].isOwner ?
-				result.my_calendars.push( calendars[i] ) :
-				result.others_calendars.push( calendars[i] );
-		}
-
-		return { agendas_usuario: result };
+	var result = {
+	    my_calendars: [], 
+	    others_calendars: []
+	};
+
+	for( var i = 0; i < calendars.length; i++ )
+	{
+	    !!Calendar.signatureOf[ calendars[i].id ].isOwner ?
+	    result.my_calendars.push( calendars[i] ) :
+	    result.others_calendars.push( calendars[i] );
+	}
+
+	return {
+	    agendas_usuario: result
+	};
 
     }
@@ -931,10 +1022,11 @@
 	var res = $.map(evtObj, function( evt ){
 
-		    return { id: evt.id,
-			     summary: evt.title,
-			     startTime: evt.start.getTime(),
-			     endTime: ( !!evt.allDay ? (( evt.end || evt.start ).getTime() + 86400000) :( evt.end || evt.start ).getTime()),
-			     allDay: ( !!evt.allDay ? 1 : 0 )
-			     /*calendar: evt.id && User.calendarOf[ evt.id ].id*/ };
+	    return {
+		id: evt.id,
+		summary: evt.title,
+		startTime: evt.start.getTime(),
+		endTime: ( !!evt.allDay ? (( evt.end || evt.start ).getTime() + 86400000) :( evt.end || evt.start ).getTime()),
+		allDay: ( !!evt.allDay ? 1 : 0 )
+	    /*calendar: evt.id && User.calendarOf[ evt.id ].id*/ };
 	});
 
@@ -948,71 +1040,90 @@
 
 	var filtered = evtObj;
-// 
+	// 
 	var grouped = {};
 
 	$.map(filtered, function( evt ){
 		
-		if(!(typeof(evt) == 'object') || (evt.id.indexOf('java') >= 0))
-			return (null);
-
-		evt.calendar = evt.calendar || "1";
-
-		if( !grouped[ evt.calendar ] )
-		    grouped[ evt.calendar ] = [];
+	    if(!(typeof(evt) == 'object') || (evt.id.indexOf('java') >= 0))
+		return (null);
+
+	    evt.calendar = evt.calendar || "1";
+
+	    if( !grouped[ evt.calendar ] )
+		grouped[ evt.calendar ] = [];
 			
-		var calendar = DataLayer.get('calendar', evt.calendar);
-		
-		var eventEditable = function(idEvent, isRecurrence, Recurrence){
-			if(Calendar.signatureOf[calendar.id].isOwner == "1"){
-				var attendee = {};
-				for(var i = 0; i < evt.participants.length; i++){
-					attendee = DataLayer.get('participant', evt.participants[i]);
-						if(attendee.user == User.me.id)
-							return (attendee.acl.indexOf('w') >= 0 || attendee.acl.indexOf('o') >= 0 ) ? {selectable: true, className: 'fullcalendar-context-menu  event-id-'+idEvent+ (isRecurrence ? ' isRecurrence Recurrence-id-'+Recurrence : '')} : { editable: false, selectable: true ,className: 'blocked-event-permision  fullcalendar-not-context-menu event-id-'+idEvent};
-				}
-				return {editable: false, className: 'blocked-event-permision  fullcalendar-not-context-menu event-id-'+idEvent,  selectable: true, disableDragging: isRecurrence };
-			}
-			else{
-				var aclSignature = Calendar.signatureOf[calendar.id].permission;
+	    var calendar = DataLayer.get('calendar', evt.calendar);
+		
+	    var eventEditable = function(idEvent, isRecurrence, Recurrence){
+		if(Calendar.signatureOf[calendar.id].isOwner == "1"){
+		    var attendee = {};
+		    for(var i = 0; i < evt.participants.length; i++){
+			attendee = DataLayer.get('participant', evt.participants[i]);
+			if(attendee.user == User.me.id)
+			    return (attendee.acl.indexOf('w') >= 0 || attendee.acl.indexOf('o') >= 0 ) ? {
+				selectable: true, 
+				className: 'fullcalendar-context-menu  event-id-'+idEvent+ (isRecurrence ? ' isRecurrence Recurrence-id-'+Recurrence : '')
+				} : {
+				editable: false, 
+				selectable: true ,
+				className: 'blocked-event-permision  fullcalendar-not-context-menu event-id-'+idEvent
+				};
+		    }
+		    return {
+			editable: false, 
+			className: 'blocked-event-permision  fullcalendar-not-context-menu event-id-'+idEvent,  
+			selectable: true, 
+			disableDragging: isRecurrence
+		    };
+		}
+		else{
+		    var aclSignature = Calendar.signatureOf[calendar.id].permission;
 				
-				var mountClass =  function(acl){
-					var returns = ""
-					returns += acl['write'] ? "" :  'blocked-event-permision ';
-					returns += acl['busy'] ? 'fullcalendar-not-context-menu ' : (acl['read']  ?  'fullcalendar-context-menu '+ idEvent + (isRecurrence ? ' isRecurrence Recurrence-id-'+Recurrence : '') : '');
-					returns += 'event-id-'+idEvent;
-					return returns;
-				}				
-				return DataLayer.merge({
-					editable: aclSignature.acl['write'] && !isRecurrence,
-					disableResizing : (((aclSignature.acl['busy'] && !aclSignature.acl['write']) || (!aclSignature.acl['write'] && aclSignature.acl['read'])) ? true : false),
-					disableDragging  : (((aclSignature.acl['busy'] && !aclSignature.acl['write']) || (!aclSignature.acl['write'] && aclSignature.acl['read'])) ? true: false),
-					className: mountClass(aclSignature.acl)
-				}, aclSignature.acl['busy'] ? {title: 'Ocupado', selectable: false } : {selectable: true});
-			}
+		    var mountClass =  function(acl){
+			var returns = ""
+			returns += acl['write'] ? "" :  'blocked-event-permision ';
+			returns += acl['busy'] ? 'fullcalendar-not-context-menu ' : (acl['read']  ?  'fullcalendar-context-menu '+ idEvent + (isRecurrence ? ' isRecurrence Recurrence-id-'+Recurrence : '') : '');
+			returns += 'event-id-'+idEvent;
+			return returns;
+		    }				
+		    return DataLayer.merge({
+			editable: aclSignature.acl['write'] && !isRecurrence,
+			disableResizing : (((aclSignature.acl['busy'] && !aclSignature.acl['write']) || (!aclSignature.acl['write'] && aclSignature.acl['read'])) ? true : false),
+			disableDragging  : (((aclSignature.acl['busy'] && !aclSignature.acl['write']) || (!aclSignature.acl['write'] && aclSignature.acl['read'])) ? true: false),
+			className: mountClass(aclSignature.acl)
+		    }, aclSignature.acl['busy'] ? {
+			title: 'Ocupado', 
+			selectable: false
+		    } : {
+			selectable: true
+		    });
+		}
 			
-		}
-		
-		var duration = parseInt( evt.endTime ) - parseInt( evt.startTime ), isRepeat = false;
-		
-		var occurrences = [];
-		
-		if( evt.occurrences )
-		{
-		    isRepeat = true;
-		    occurrences = evt.occurrences;
-		}else
-                    occurrences[ occurrences.length ] = evt.startTime;
-
-		//occurrences = DataLayer.unique( occurrences ).sort();
+	    }
+		
+	    var duration = parseInt( evt.endTime ) - parseInt( evt.startTime ), isRepeat = false;
+		
+	    var occurrences = [];
+		
+	    if( evt.occurrences )
+	    {
+		isRepeat = true;
+		occurrences = evt.occurrences;
+	    }else
+		occurrences[ occurrences.length ] = evt.startTime;
+
+	    //occurrences = DataLayer.unique( occurrences ).sort();
 		  
-		for( var i = 0; i < occurrences.length; i++ )
-		    grouped[ evt.calendar ].push( DataLayer.merge({ id: evt.URI || evt.id+ '-' + i,
-                    title: Encoder.htmlDecode(evt.summary),
-                    start: Timezone.getDateCalendar(new Date( parseInt( occurrences[i] ) ), calendar.timezone,  !!evt.DayLigth ? evt.DayLigth.calendar.startTime : Timezone.daylightSaving),
-                    end:   Timezone.getDateCalendar(new Date( parseInt( occurrences[i] ) + duration - (!!parseInt(evt.allDay) ? 86400000 : 0)), calendar.timezone, !!evt.DayLigth ? evt.DayLigth.calendar.startTime : Timezone.daylightSaving),
-                    allDay: parseInt( evt.allDay ),
-                    isRepeat: isRepeat,
-                    occurrence: i,
-		    calendar: evt.calendar}, eventEditable(evt.id, isRepeat, i ) ) );
+	    for( var i = 0; i < occurrences.length; i++ )
+		grouped[ evt.calendar ].push( DataLayer.merge({
+		    id: evt.URI || evt.id+ '-' + i,
+		    title: Encoder.htmlDecode(evt.summary),
+		    start: Timezone.getDateCalendar(new Date( parseInt( occurrences[i] ) ), calendar.timezone,  !!evt.DayLigth ? evt.DayLigth.calendar.startTime : Timezone.daylightSaving),
+		    end:   Timezone.getDateCalendar(new Date( parseInt( occurrences[i] ) + duration - (!!parseInt(evt.allDay) ? 86400000 : 0)), calendar.timezone, !!evt.DayLigth ? evt.DayLigth.calendar.startTime : Timezone.daylightSaving),
+		    allDay: parseInt( evt.allDay ),
+		    isRepeat: isRepeat,
+		    occurrence: i,
+		    calendar: evt.calendar
+		    }, eventEditable(evt.id, isRepeat, i ) ) );
 	});
 
@@ -1022,22 +1133,27 @@
     criteria: function( filter ){
       
-		if( $.type(filter.start) !== 'date' )
-			filter.start = new Date( filter.start * 1000 );
-		if( $.type(filter.end) !== 'date' )
-			filter.end = new Date( filter.end * 1000 );
-
-		var timezone = {};
-		for(var i in Calendar.signatureOf)
-			timezone[i] = Calendar.signatureOf[i].calendar.timezone;
-		
-		return { filter: ["AND", 
-
-					[ ">=", "rangeStart", filter.start.getTime() ],
-					[ "<=", "rangeEnd", filter.end.getTime() ],
-					[ "IN", "calendar", Calendar.calendarIds ]
-
-				  ], 
-		 criteria: { deepness: 2, timezones: timezone } }
-    }
+	if( $.type(filter.start) !== 'date' )
+	    filter.start = new Date( filter.start * 1000 );
+	if( $.type(filter.end) !== 'date' )
+	    filter.end = new Date( filter.end * 1000 );
+
+	var timezone = {};
+	for(var i in Calendar.signatureOf)
+	    timezone[i] = Calendar.signatureOf[i].calendar.timezone;
+		
+	return {
+	    filter: ["AND", 
+
+	    [ ">=", "rangeStart", filter.start.getTime() ],
+	    [ "<=", "rangeEnd", filter.end.getTime() ],
+	    [ "IN", "calendar", Calendar.calendarIds ]
+
+	    ], 
+	    criteria: {
+		deepness: 2, 
+		timezones: timezone
+	    }
+	}
+}
 });
 
@@ -1045,28 +1161,33 @@
 DataLayer.codec( "preference", "detail", {
   
-	decoder:function( pref ){
-	
-		var res = [];
-
-		pref.defaultAlarm = $.map( pref.alarmTime || [], function( alarmTime, i ){
+    decoder:function( pref ){
+	
+	var res = [];
+
+	pref.defaultAlarm = $.map( pref.alarmTime || [], function( alarmTime, i ){
 		  
-			return { type: pref.alarmType[i], 
-				time: alarmTime,
-				unit: pref.alarmUnit[i] };
-			});
-
-		$.each( pref, function( i, el ){
-
-			res[ res.length ] = { name: i, value: el };
-
-		});
-		
-		return( res );
+	    return {
+		type: pref.alarmType[i], 
+		time: alarmTime,
+		unit: pref.alarmUnit[i]
+		};
+	});
+
+	$.each( pref, function( i, el ){
+
+	    res[ res.length ] = {
+		name: i, 
+		value: el
+	    };
+
+	});
+		
+	return( res );
       
-	},
-
-	encoder:function( pref ){
-		return( pref );
-	}
+    },
+
+    encoder:function( pref ){
+	return( pref );
+    }
 
 });
@@ -1074,5 +1195,5 @@
 DataLayer.codec( "schedulable", "export", {
   
-	decoder: function(){},
+    decoder: function(){},
       
     encoder: function( signatures ){},
@@ -1080,11 +1201,14 @@
     criteria: function( filter ){
 	
-		if( isCal  = filter && filter.calendar )
-			filter = filter.calendar;
-			return {
-				filter: filter ? [  "=", ( isCal ? "calendar" : "id" ), filter ] : false,
-				criteria: { format: 'iCal', deepness: 2 }
-			};
-		}
+	if( isCal  = filter && filter.calendar )
+	    filter = filter.calendar;
+	return {
+	    filter: filter ? [  "=", ( isCal ? "calendar" : "id" ), filter ] : false,
+	    criteria: {
+		format: 'iCal', 
+		deepness: 2
+	    }
+	};
+    }
 });
 
Index: trunk/prototype/modules/calendar/js/calendar.shared.js
===================================================================
--- trunk/prototype/modules/calendar/js/calendar.shared.js	(revision 6052)
+++ trunk/prototype/modules/calendar/js/calendar.shared.js	(revision 6066)
@@ -2,5 +2,5 @@
     var html = DataLayer.render('templates/shared_calendar.ejs', {
 	calendar: Calendar.calendars
-	});	
+    });	
 	
     //Variaval global para manipulação dos usuários
@@ -92,5 +92,5 @@
 		var permission = DataLayer.get('calendarToPermission', {
 		    filter: ['AND', ['=', 'calendar', calendarId], ['=', 'user', '0']]
-		    }, true);
+		}, true);
 		if($.isArray(permission))
 		    permission = permission[0];
@@ -186,5 +186,5 @@
 			name: currentUsers [id] .name, 
 			mail: currentUsers [id] .mail
-			}]))
+		    }]))
 		    .scrollTo('max');
 						
@@ -300,38 +300,38 @@
 	}
     });
-if(dataCurrent){
-    for(var i = 0; i < dataCurrent.length; i++){
-	if(dataCurrent[i].user == "0"){
-	    UI.dialogs.sharedCalendar.find('input[name="isPublic"]').attr('checked', 'checked')
-	    .parent().find('.free-busy').toggleClass('hidden');
-	    if(dataCurrent[i].acl['busy'])
-		UI.dialogs.sharedCalendar.find('input[name="busy"]').attr('checked', 'checked');
-	}else{
-	    currentUsers[dataCurrent[i].user.id] = true;
-
-	    UI.dialogs.sharedCalendar.find('dd.user-list ul.user-list')
-	    .append(DataLayer.render('templates/user_shared_add_itemlist.ejs', [{
-		id: dataCurrent[i].user.id, 
-		name: dataCurrent[i].user.name, 
-		mail: dataCurrent[i].user.mail, 
-		acl:dataCurrent[i].acl, 
-		aclValue: dataCurrent[i].aclValues, 
-		current: true, 
-		idPermission: dataCurrent[i].id
-	    }]))
-	    .scrollTo('max');
-	    $('li.not-user').remove();
-	    callbackSharedCotactsAdd();
-
-	    for (var f in dataCurrent[i].acl){
-		if(dataCurrent[i].acl[f]){
-		    UI.dialogs.sharedCalendar.find('.'+f+':last').toggleClass('attendee-permissions-change-button')
-		    .find('span:first').toggleClass('attendee-permissions-change').end();  
-		}
-	    }
-	}
-    }
-}
-UI.dialogs.sharedCalendar.dialog('open');
+    if(dataCurrent){
+	for(var i = 0; i < dataCurrent.length; i++){
+	    if(dataCurrent[i].user == "0"){
+		UI.dialogs.sharedCalendar.find('input[name="isPublic"]').attr('checked', 'checked')
+		.parent().find('.free-busy').toggleClass('hidden');
+		if(dataCurrent[i].acl['busy'])
+		    UI.dialogs.sharedCalendar.find('input[name="busy"]').attr('checked', 'checked');
+	    }else{
+		currentUsers[dataCurrent[i].user.id] = true;
+
+		UI.dialogs.sharedCalendar.find('dd.user-list ul.user-list')
+		.append(DataLayer.render('templates/user_shared_add_itemlist.ejs', [{
+		    id: dataCurrent[i].user.id, 
+		    name: dataCurrent[i].user.name, 
+		    mail: dataCurrent[i].user.mail, 
+		    acl:dataCurrent[i].acl, 
+		    aclValue: dataCurrent[i].aclValues, 
+		    current: true, 
+		    idPermission: dataCurrent[i].id
+		}]))
+		.scrollTo('max');
+		$('li.not-user').remove();
+		callbackSharedCotactsAdd();
+
+		for (var f in dataCurrent[i].acl){
+		    if(dataCurrent[i].acl[f]){
+			UI.dialogs.sharedCalendar.find('.'+f+':last').toggleClass('attendee-permissions-change-button')
+			.find('span:first').toggleClass('attendee-permissions-change').end();  
+		    }
+		}
+	    }
+	}
+    }
+    UI.dialogs.sharedCalendar.dialog('open');
 }
 
@@ -378,5 +378,5 @@
 		backgroundColor: (!!type ? 'fbec88' : '8c8c8c'), 
 		borderColor: (!!type ? 'fad24e' : '120d0d')
-		}, !!idPermission ? {
+	    }, !!idPermission ? {
 		id: idPermission
 	    } : {} ));
@@ -405,141 +405,141 @@
 		}
 	    }, true);
-	var resultPublic = DataLayer.get('calendarToPermission', {
-	    filter: ['AND', ['=','type',1],   ['OR', ['i*','name',$(this).val()], ["i*", "description", $(this).val()]]]  , 
-	    criteria: {
-		deepness: 2
-	    }
-	}, true);
-
-    /**
+	    var resultPublic = DataLayer.get('calendarToPermission', {
+		filter: ['AND', ['=','type',1],   ['OR', ['i*','name',$(this).val()], ["i*", "description", $(this).val()]]]  , 
+		criteria: {
+		    deepness: 2
+		}
+	    }, true);
+
+	    /**
     * TODO: trocar por template
     */
-    UI.dialogs.sharedCalendar.find('ul.search-result-list').empty().css('overflow', 'hidden');
-	if (!result && !resultPublic) {
-	    UI.dialogs.sharedCalendar.find('ul.search-result-list').append('<li><label class="empty">Nenhum resultado encontrado.</label></li>');
-	}
-				
-	if(resultPublic){
-	    var notConflict = [];
-	    var conflit = false;
-	    for(var i = 0; i < resultPublic.length; i++){
-		for(var j = 0; j < result.length; j++){
-		    if(resultPublic[i].id == result[j].calendar.id)
-			conflit = true;
-		}
-		if(!conflit){
-		    notConflict.push(resultPublic[i]);
-		    conflit = false;
-		}
-	    }
-	}
-	resultPublic = notConflict;
-				
-	var resultNormalize = [];
-	for(i=0; i<result.length; i++){
-	    resultNormalize.push({
-		id: result[i].calendar.id, 
-		name:result[i].calendar.name, 
-		mail: result[i].calendar.description, 
-		type: 0
-	    })
-	    resultNormalize[i].enabled = currentCalendars[result[i].id] ? false : true;
-	}
-	if(resultPublic)
-	    for(i=0; i<resultPublic.length; i++){
+	    UI.dialogs.sharedCalendar.find('ul.search-result-list').empty().css('overflow', 'hidden');
+	    if (!result && !resultPublic) {
+		UI.dialogs.sharedCalendar.find('ul.search-result-list').append('<li><label class="empty">Nenhum resultado encontrado.</label></li>');
+	    }
+				
+	    if(resultPublic){
+		var notConflict = [];
+		var conflit = false;
+		for(var i = 0; i < resultPublic.length; i++){
+		    for(var j = 0; j < result.length; j++){
+			if(resultPublic[i].id == result[j].calendar.id)
+			    conflit = true;
+		    }
+		    if(!conflit){
+			notConflict.push(resultPublic[i]);
+			conflit = false;
+		    }
+		}
+	    }
+	    resultPublic = notConflict;
+				
+	    var resultNormalize = [];
+	    for(i=0; i<result.length; i++){
 		resultNormalize.push({
-		    id: resultPublic[i].calendar.id, 
-		    name:resultPublic[i].calendar.name, 
-		    mail: resultPublic[i].calendar.description,
-		    type: 1
+		    id: result[i].calendar.id, 
+		    name:result[i].calendar.name, 
+		    mail: result[i].calendar.description, 
+		    type: 0
 		})
-		resultNormalize[i].enabled = currentCalendars[resultPublic[i].id] ? false : true;
-	    }
-				
-	UI.dialogs.sharedCalendar.find('ul.search-result-list').append(DataLayer.render( 'templates/calendar_search_itemlist.ejs', resultNormalize));
-
-	UI.dialogs.sharedCalendar.find('ul.search-result-list li').click(function(event, ui){
-	    if ($(event.target).is('input')) {
-		old_item = $(event.target).parents('li');
-		var id = old_item.find('.id').html();
+		resultNormalize[i].enabled = currentCalendars[result[i].id] ? false : true;
+	    }
+	    if(resultPublic)
+		for(i=0; i<resultPublic.length; i++){
+		    resultNormalize.push({
+			id: resultPublic[i].calendar.id, 
+			name:resultPublic[i].calendar.name, 
+			mail: resultPublic[i].calendar.description,
+			type: 1
+		    })
+		    resultNormalize[i].enabled = currentCalendars[resultPublic[i].id] ? false : true;
+		}
+				
+	    UI.dialogs.sharedCalendar.find('ul.search-result-list').append(DataLayer.render( 'templates/calendar_search_itemlist.ejs', resultNormalize));
+
+	    UI.dialogs.sharedCalendar.find('ul.search-result-list li').click(function(event, ui){
+		if ($(event.target).is('input')) {
+		    old_item = $(event.target).parents('li');
+		    var id = old_item.find('.id').html();
 						
-		for(var i = 0; i<resultNormalize.length; i++){
-		    if(resultNormalize[i].id == id)
-			currentCalendars[id] = {
-			    id: id, 
-			    name: resultNormalize[i].name, 
-			    description: resultNormalize[i].description, 
-			    type: resultNormalize[i].type, 
-			    isCalendar: true
-			};
-		}
-
-		UI.dialogs.sharedCalendar.find('dd.calendar-list ul.user-list')
-		.append(DataLayer.render('templates/user_shared_add_itemlist.ejs', [currentCalendars[id]]))
-		.scrollTo('max');
+		    for(var i = 0; i<resultNormalize.length; i++){
+			if(resultNormalize[i].id == id)
+			    currentCalendars[id] = {
+				id: id, 
+				name: resultNormalize[i].name, 
+				description: resultNormalize[i].description, 
+				type: resultNormalize[i].type, 
+				isCalendar: true
+			    };
+		    }
+
+		    UI.dialogs.sharedCalendar.find('dd.calendar-list ul.user-list')
+		    .append(DataLayer.render('templates/user_shared_add_itemlist.ejs', [currentCalendars[id]]))
+		    .scrollTo('max');
 						
-		$('li.not-user').remove();
-		callbackSharedCalendarAdd();
-		old_item.remove();
-	    }
-	});
-	event.preventDefault();
-    }
-});
-		
-var callbackSharedCalendarAdd = function(event){
-		
-    UI.dialogs.sharedCalendar.find('.button').filter(".close.new").button({
-	icons: {
-	    primary: "ui-icon-close"
-	},
-	text: false
-    }).click(function () {
-	var id = $(this).parents('li').find('input[name="idPermission"]').val();
-	currentCalendars[$(this).parents().find('input[name="calendar[]"]').val()] = false;
-	$(this).parents('li').remove();
-	if(!!id)
-	DataLayer.remove('calendarSignature', id);
-    })
-    .addClass('tiny disable ui-button-disabled ui-state-disabled')
-    .removeClass('new').end();
-
-    UI.dialogs.sharedCalendar.find('.user-list li').hover(
-	function () {
-	    $(this).addClass("hover-user");
-	    $(this).find('.button').removeClass('disable ui-button-disabled ui-state-disabled').end()
-	    .find('.user-acls-shared-calendar').addClass('hover-user');
-	},
-	function () {
-	    $(this).removeClass("hover-user");
-	    $(this).find('.button').addClass('disable ui-button-disabled ui-state-disabled').end()
-	    .find('.user-acls-shared-calendar').removeClass('hover-user');;
-	}
-	);		
-}
-
-//Carrega os dados já cadastrados
-for (var i = 0; i < Calendar.signatures.length; i++)
-    if(Calendar.signatures[i].isOwner == "0"){
-	var dataCurrent = Calendar.signatures[i].calendar;
-	currentCalendars[Calendar.signatures[i].permission.id] = {
-	    id: dataCurrent.id, 
-	    idPermission:Calendar.signatures[i].id ,
-	    name: dataCurrent.name, 
-	    description: dataCurrent.description, 
-	    type: Calendar.signatures[i].permission.type, 
-	    isCalendar: true,
-	    current: true
-	};
+		    $('li.not-user').remove();
+		    callbackSharedCalendarAdd();
+		    old_item.remove();
+		}
+	    });
+	    event.preventDefault();
+	}
+    });
+		
+    var callbackSharedCalendarAdd = function(event){
+		
+	UI.dialogs.sharedCalendar.find('.button').filter(".close.new").button({
+	    icons: {
+		primary: "ui-icon-close"
+	    },
+	    text: false
+	}).click(function () {
+	    var id = $(this).parents('li').find('input[name="idPermission"]').val();
+	    currentCalendars[$(this).parents().find('input[name="calendar[]"]').val()] = false;
+	    $(this).parents('li').remove();
+	    if(!!id)
+		DataLayer.remove('calendarSignature', id);
+	})
+	.addClass('tiny disable ui-button-disabled ui-state-disabled')
+	.removeClass('new').end();
+
+	UI.dialogs.sharedCalendar.find('.user-list li').hover(
+	    function () {
+		$(this).addClass("hover-user");
+		$(this).find('.button').removeClass('disable ui-button-disabled ui-state-disabled').end()
+		.find('.user-acls-shared-calendar').addClass('hover-user');
+	    },
+	    function () {
+		$(this).removeClass("hover-user");
+		$(this).find('.button').addClass('disable ui-button-disabled ui-state-disabled').end()
+		.find('.user-acls-shared-calendar').removeClass('hover-user');;
+	    }
+	    );		
+    }
+
+    //Carrega os dados já cadastrados
+    for (var i = 0; i < Calendar.signatures.length; i++)
+	if(Calendar.signatures[i].isOwner == "0"){
+	    var dataCurrent = Calendar.signatures[i].calendar;
+	    currentCalendars[Calendar.signatures[i].permission.id] = {
+		id: dataCurrent.id, 
+		idPermission:Calendar.signatures[i].id ,
+		name: dataCurrent.name, 
+		description: dataCurrent.description, 
+		type: Calendar.signatures[i].permission.type, 
+		isCalendar: true,
+		current: true
+	    };
 			
-	UI.dialogs.sharedCalendar.find('dd.calendar-list ul.user-list')
-	.append(DataLayer.render('templates/user_shared_add_itemlist.ejs', [currentCalendars[Calendar.signatures[i].permission.id]]))
-	.scrollTo('max');
-				
-	$('li.not-user').remove();
-	callbackSharedCalendarAdd();
-    }
-		
-UI.dialogs.sharedCalendar.dialog('open');
+	    UI.dialogs.sharedCalendar.find('dd.calendar-list ul.user-list')
+	    .append(DataLayer.render('templates/user_shared_add_itemlist.ejs', [currentCalendars[Calendar.signatures[i].permission.id]]))
+	    .scrollTo('max');
+				
+	    $('li.not-user').remove();
+	    callbackSharedCalendarAdd();
+	}
+		
+    UI.dialogs.sharedCalendar.dialog('open');
 }
 
Index: trunk/prototype/modules/calendar/templates/event_repeat.ejs
===================================================================
--- trunk/prototype/modules/calendar/templates/event_repeat.ejs	(revision 5715)
+++ trunk/prototype/modules/calendar/templates/event_repeat.ejs	(revision 6066)
@@ -5,5 +5,5 @@
 	<p class="input-group">
 		<label for="frequency">Repetição:</label>
-		<select name="frequency" class="frequency">
+		<select name="frequency" class="frequency" <%= ((data.event.acl.write || data.event.acl.organization) && data.event.isAttendee) ? '' : 'disabled'%>>
 			<option value="none">Sem repetição</option>
 			<option value="daily">Diária</option>
Index: trunk/prototype/modules/calendar/templates/attendee_add.ejs
===================================================================
--- trunk/prototype/modules/calendar/templates/attendee_add.ejs	(revision 5592)
+++ trunk/prototype/modules/calendar/templates/attendee_add.ejs	(revision 6066)
@@ -5,5 +5,5 @@
 		<dt class="me"><%= data.event.me.name %></dt>
 		<dd class="me">
-			<select class="status" name="status">
+		    <select class="status" name="status" <%= data.event.isAttendee ? '' : 'disabled' %>>
 				<%if(!data.event.delegatedFrom[data.event.me.id]){%>
 					<option value="1" <%= data.event.status=='1' ? 'selected="selected"':'' %>>Eu vou</option>
@@ -17,5 +17,5 @@
 				<%}%>
 			</select>
-			<% if (!data.event.acl.organization && !data.event.acl.write && !data.event.acl.inviteGuests && !data.event.acl.participationRequired && !data.event.delegatedFrom[data.event.me.id] ) { %>
+			<% if ((!data.event.acl.organization && !data.event.acl.write && !data.event.acl.inviteGuests && !data.event.acl.participationRequired && !data.event.delegatedFrom[data.event.me.id]) && data.event.isAttendee) { %>
 				<fieldset class="add-attendee-options-read">
 					<a href="#" class="button participant-delegate add-attendee-options-button">Delegar participação a um novo participante</a>
@@ -39,5 +39,5 @@
 		<dd class="attendee-list">
 			<ul class="attendee-list">
-				<li class="organizer <%= (data.event.acl.organization) ? "hidden" : "" %>"> 
+				<li class="organizer <%= (data.event.acl.organization || !data.event.isAttendee) ? "hidden" : "" %>"> 
 					<div style="overflow:hidden; width:100%; display:table;">
 						<span class="space-status ui-icon <%=iconStatus[data.event.organizer.status]%>" title="<%=legendStatus[data.event.organizer.status]%>"></span>
@@ -126,5 +126,5 @@
 			</ul>
 		</dd>
-		<dd class="attendee-list-add">
+		<dd class="attendee-list-add <%= data.event.acl.write && data.event.isAttendee ? '' : 'hidden' %>">
 			<fieldset class="add-attendee-input input-field-rounded ui-corner-all">
 				<span class="ui-icon ui-icon-plus"></span>
Index: trunk/prototype/modules/calendar/templates/event_add.ejs
===================================================================
--- trunk/prototype/modules/calendar/templates/event_add.ejs	(revision 5916)
+++ trunk/prototype/modules/calendar/templates/event_add.ejs	(revision 6066)
@@ -26,5 +26,5 @@
 			</select>
 			
-			<a class="button suggestion-hours small <%=(data.event.acl.organization || data.event.acl.write) ? "hidden" : '' %>" href="#">Sugerir horário</a>
+			<a class="button suggestion-hours small <%=(data.event.acl.organization || data.event.acl.write || !data.event.isAttendee) ? "hidden" : '' %>" href="#">Sugerir horário</a>
 			
 		</p>
