Index: /trunk/prototype/services/iCal.php
===================================================================
--- /trunk/prototype/services/iCal.php	(revision 7695)
+++ /trunk/prototype/services/iCal.php	(revision 7702)
@@ -64,5 +64,6 @@
 			    if (( isset($v['repeat']) ) && ( isset($v['repeat']['frequency']) && $v['repeat']['frequency'] && $v['repeat']['frequency'] != 'none' )) 
 				    $vevent->setProperty('rrule', $this->formatIcalRepeat($v['repeat']));
-			    
+
+                $vevent->setProperty('dtstamp', array('timestamp' => ($v['dtstamp'] / 1000) ));
 
 			    if (isset($v['allDay']) && $v['allDay'] == 1)
@@ -200,4 +201,6 @@
                 $eTime->setTimezone($apTimezoneOBJ);
 
+                $vevent->setProperty('dtstamp', array('timestamp' => ($v['dtstamp'] / 1000) ));
+
                 if (isset($v['allDay']) && $v['allDay'] == 1) {
                     $todo->setProperty('dtstart', $sTime->format(DATE_RFC822), array("VALUE" => "DATE"));
@@ -281,4 +284,6 @@
 			    $vevent->setProperty('location', $v['location']);
 			    $vevent->setProperty('tranp', (isset($v['tranparent']) && $v['tranparent'] == TRANSP_TRANSPARENT ) ? 'TRANSPARENT' : 'OPAQUE' );
+
+                $vevent->setProperty('dtstamp', array('timestamp' => ($v['dtstamp'] / 1000) ));
 
 			    $timezone = new DateTimeZone('UTC');
@@ -348,4 +353,6 @@
             $todo->setProperty('status', $this->_getStatusTodo($v['status']));
 
+            $vevent->setProperty('dtstamp', array('timestamp' => ($v['dtstamp'] / 1000) ));
+
             $timezone = new DateTimeZone('UTC');
             $apTimezone = self::nomalizeTZID(( isset($v['timezone']) && $v['timezone'] != 'null' ) ? $v['timezone'] : $params['defaultTZI']);
@@ -543,4 +550,5 @@
 		case 'VEVENT':
 
+
 		    switch ($method) {
 			case 'PUBLISH':
@@ -610,5 +618,7 @@
                             //Verifica a importação de eventos em que não participo
                             if ($pID) {
+
                                 $interation['participant://' . $pID]['status'] = $params['status'];
+
                             }
                         }
@@ -848,6 +858,5 @@
 			    break;
 		    }
-	
-		    
+
 		    $return[] = $interation;
 		    break;
@@ -1562,5 +1571,5 @@
     	$objTimezone = new DateTimeZone($schedulable['timezone']);
 
-    	if (isset($startTime['params']['VALUE']) && $startTime['params']['VALUE'] === 'DATE' && isset($params['calendar_timezone'])) {
+        if (isset($startTime['params']['VALUE']) && $startTime['params']['VALUE'] === 'DATE' ) {
     	    $schedulable['allDay'] = 1;
     	    $schedulable['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC', $schedulable['timezone'], '@' . self::date2timestamp($startTime['value'])) . '000';
@@ -1667,5 +1676,5 @@
     	    $intUser = Controller::find(array('concept' => 'user'), array('id', 'isExternal'), array('filter' => array('OR', array('=', 'mail', $mailUser), array('=', 'mailAlternateAddress', $mailUser))));
 
-    	    $user = null;
+            $user = null;
     	    if ($intUser && count($intUser) > 0) {
     		$participant['isExternal'] = isset($intUser[0]['isExternal']) ? $intUser[0]['isExternal'] : 0;
@@ -1689,32 +1698,40 @@
 
     	if ($property = $component->getProperty('organizer', FALSE, TRUE)) {
-    	    $participant = array();
+
     	    $mailUser = trim(str_replace('MAILTO:', '', $property['value']));
 
-    	    $participantID = mt_rand() . '2(Formatter)';
-
-    	    $participant['schedulable'] = $eventID;
-    	    $participant['status'] = (isset($property['params']['PARTSTAT']) && constant('STATUS_' . $property['params']['PARTSTAT']) !== null ) ? constant('STATUS_' . $property['params']['PARTSTAT']) : STATUS_UNANSWERED;
-    	    $participant['isOrganizer'] = '1';
-    	    $participant['acl'] = 'rowi';
+
+            if($participant = self::_getParticipantByMail($mailUser, $schedulable['participants'], true)){
+
+                $participantID = $participant['id'];
+
+            }else{
+
+                $participant = array();
+
+                $participantID = mt_rand() . '2(Formatter)';
+                $participant['schedulable'] = $eventID;
+                $participant['status'] = (isset($property['params']['PARTSTAT']) && constant('STATUS_' . $property['params']['PARTSTAT']) !== null ) ? constant('STATUS_' . $property['params']['PARTSTAT']) : STATUS_UNANSWERED;
+                $participant['isOrganizer'] = '1';
+                $participant['acl'] = 'rowi';
+            }
 
     	    /* Verifica se este usuario é um usuario interno do ldap */
     	    $intUser = Controller::find(array('concept' => 'user'), array('id', 'isExternal'), array('filter' => array('OR', array('=', 'mail', $mailUser), array('=', 'mailAlternateAddress', $mailUser))));
-
     	    $user = null;
     	    if ($intUser && count($intUser) > 0) {
-    		$participant['isExternal'] = isset($intUser[0]['isExternal']) ? $intUser[0]['isExternal'] : 0;
-    		$participant['user'] = $intUser[0]['id'];
+                $participant['isExternal'] = isset($intUser[0]['isExternal']) ? $intUser[0]['isExternal'] : 0;
+                $participant['user'] = $intUser[0]['id'];
     	    } else {
-    		$participant['isExternal'] = 1;
-    		/* Gera um randon id para o contexto formater */
-    		$userID = mt_rand() . '4(Formatter)';
-
-    		$user['mail'] = $mailUser;
-    		$user['name'] = ( isset($property['params']['CN']) ) ? $property['params']['CN'] : '';
-    		$user['participants'] = array($participantID);
-    		$user['isExternal'] = '1';
-    		$participant['user'] = $userID;
-    		$interation['user://' . $userID] = $user;
+                $participant['isExternal'] = 1;
+                /* Gera um randon id para o contexto formater */
+                $userID = mt_rand() . '4(Formatter)';
+
+                $user['mail'] = $mailUser;
+                $user['name'] = ( isset($property['params']['CN']) ) ? $property['params']['CN'] : '';
+                $user['participants'] = array($participantID);
+                $user['isExternal'] = '1';
+                $participant['user'] = $userID;
+                $interation['user://' . $userID] = $user;
     	    }
 
@@ -1828,5 +1845,5 @@
     	$interation['schedulable://' . $eventID] = $schedulable;
 
-    	return $interation;
+        return $interation;
     }
     
@@ -1956,10 +1973,18 @@
 	    $mailUser = trim(str_replace('MAILTO:', '', $property['value']));
 
-	    $participantID = mt_rand() . '2(Formatter)';
-
-	    $participant['schedulable'] = $todoID;
-	    $participant['status'] = (isset($property['params']['PARTSTAT']) && constant('STATUS_' . $property['params']['PARTSTAT']) !== null ) ? constant('STATUS_' . $property['params']['PARTSTAT']) : STATUS_UNANSWERED;
-	    $participant['isOrganizer'] = '1';
-	    $participant['acl'] = 'rowi';
+        if($participant = self::_getParticipantByMail($mailUser, $schedulable['participants'], true)){
+
+            $participantID = $participant['id'];
+
+        }else{
+
+            $participant = array();
+
+            $participantID = mt_rand() . '2(Formatter)';
+            $participant['schedulable'] = $todoID;
+            $participant['status'] = (isset($property['params']['PARTSTAT']) && constant('STATUS_' . $property['params']['PARTSTAT']) !== null ) ? constant('STATUS_' . $property['params']['PARTSTAT']) : STATUS_UNANSWERED;
+            $participant['isOrganizer'] = '1';
+            $participant['acl'] = 'rowi';
+        }
 
 	    /* Verifica se este usuario é um usuario interno do ldap */
Index: /trunk/prototype/config/schedulable.ini
===================================================================
--- /trunk/prototype/config/schedulable.ini	(revision 7590)
+++ /trunk/prototype/config/schedulable.ini	(revision 7702)
@@ -17,4 +17,5 @@
 
 [before.find]
+findDeepnessOne = modules/calendar/interceptors/DBMapping.php
 findSchedulable = modules/calendar/interceptors/DBMapping.php
 findTask = modules/calendar/interceptors/DBMapping.php
Index: /trunk/prototype/modules/calendar/interceptors/DBMapping.php
===================================================================
--- /trunk/prototype/modules/calendar/interceptors/DBMapping.php	(revision 7696)
+++ /trunk/prototype/modules/calendar/interceptors/DBMapping.php	(revision 7702)
@@ -194,53 +194,55 @@
 
     public function findSchedulable(&$uri, &$params, &$criteria, $original) {
-	if (isset($criteria['filter'][2][1]) && $criteria['filter'][2][1] == 'calendar') {
-
-	    $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.priority as "priority", calendar_object.due as "due", '
-        .'calendar_object.percentage as "percentage", calendar_object.status as "status", '
-		.'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 ( calendar_to_calendar_object.calendar_id IN (\'' . implode('\',\'', $criteria['filter'][2][2]) . '\')) '
-		.'AND calendar_to_calendar_object.calendar_object_id = calendar_object.id '
-        .'AND calendar_object.id NOT IN(select calendar_object_task_id from calendar_task_to_activity_object where owner = \'' . Config::me('uidNumber') . '\') ';	
-	    
-	    if(isset($criteria['searchEvent']) && $criteria['searchEvent']){
-		$where = 'AND (((upper("summary") like upper(\'%'.$criteria['filter'][1][1][2].'%\') OR upper("description") like upper(\'%'.$criteria['filter'][1][2][2].'%\')))) ORDER BY dtstart LIMIT '.$criteria['limit'].'  OFFSET '.$criteria['offset'].' ';
-		$params = Controller::service('PostgreSQL')->execResultSql($sql.$where);
-
-	    }else{
-		$start = array( $criteria['filter'][1][1][1][2] , $criteria['filter'][1][2][1][2], $criteria['filter'][1][3][1][2] );
-		$end = array( $criteria['filter'][1][1][2][2] , $criteria['filter'][1][2][2][2], $criteria['filter'][1][3][2][2] );
-
-		$ids = array();
-		$occ = array();
-
-		if ($occurrences = self::checkOccurrences($start[0], $end[0], $criteria['filter'][2][2]))
-		    foreach ($occurrences as $id => $occurrence) {
-			$ids[] = $id;
-			$occ[] = $occurrence;
-		    }	
-
-		$where = 'AND ((range_end >= \'' . $start[0] . '\' AND range_end <= \'' . $end[0] . '\') OR '
-			.'(range_start >= \'' . $start[1] . '\' AND range_start <= \'' . $end[1] . '\') OR '
-			.'(range_start <= \'' . $start[2] . '\' AND range_end >= \'' . $end[2] . '\')) '
-		.(!empty($ids) ? ' ' .'AND calendar_object.id NOT IN (\'' . implode('\',\'', $ids) . '\') ' : ' ')
-		.'AND calendar_object.dtstart NOT IN (SELECT calendar_repeat_occurrence.occurrence from calendar_repeat_occurrence, '
-		.'calendar_repeat where (calendar_repeat_occurrence.repeat_id = calendar_repeat.id) '
-		.'AND (calendar_repeat.object_id = calendar_object.id))';
-
-		$params = Controller::service('PostgreSQL')->execResultSql($sql.$where);
-		$params = array_merge($params, $occ);		
-	    }
-	    $params = self::deepnessFindEvent($uri, $params, $criteria, $original);
-	    return false;
-	}
+        if (isset($criteria['customQuery']) && $criteria['customQuery'] == '1') {
+
+            $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.priority as "priority", calendar_object.due as "due", '
+            .'calendar_object.percentage as "percentage", calendar_object.status as "status", '
+            .'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 ( calendar_to_calendar_object.calendar_id IN (\'' . implode('\',\'', $criteria['calendar']) . '\')) '
+            .'AND calendar_to_calendar_object.calendar_object_id = calendar_object.id '
+            .'AND calendar_object.id NOT IN(select calendar_object_task_id from calendar_task_to_activity_object where owner = \'' . Config::me('uidNumber') . '\') ';
+
+            if(isset($criteria['searchEvent']) && $criteria['searchEvent']){
+                $where = 'AND (((upper("summary") like upper(\'%'.$criteria['filter'][1][1][2].'%\') OR upper("description") like upper(\'%'.$criteria['filter'][1][2][2].'%\')))) ORDER BY dtstart LIMIT '.$criteria['limit'].'  OFFSET '.$criteria['offset'].' ';
+                $params = Controller::service('PostgreSQL')->execResultSql($sql.$where);
+
+            }else{
+                $start = $criteria['rangeStart'];
+                $end = $criteria['rangeEnd'];
+
+                $ids = array();
+                $occ = array();
+
+                if ($occurrences = self::checkOccurrences($start, $end, $criteria['calendar']))
+                    foreach ($occurrences as $id => $occurrence) {
+                        $ids[] = $id;
+                        $occ[] = $occurrence;
+                    }
+
+                $where = 'AND ((range_end >= \'' . $start . '\' AND range_end <= \'' . $end . '\') OR '
+                    .'(range_start >= \'' . $start . '\' AND range_start <= \'' . $end . '\') OR '
+                    .'(range_start <= \'' . $start . '\' AND range_end >= \'' . $end . '\')) '
+                .(!empty($ids) ? ' ' .'AND calendar_object.id NOT IN (\'' . implode('\',\'', $ids) . '\') ' : ' ')
+                .'AND calendar_object.dtstart NOT IN (SELECT calendar_repeat_occurrence.occurrence from calendar_repeat_occurrence, '
+                .'calendar_repeat where (calendar_repeat_occurrence.repeat_id = calendar_repeat.id) '
+                .'AND (calendar_repeat.object_id = calendar_object.id))';
+
+                $params = Controller::service('PostgreSQL')->execResultSql($sql.$where);
+                $params = array_merge($params, $occ);
+            }
+
+
+            $params = self::deepnessFindEvent($uri, $params, $criteria, $original);
+            return false;
+        }
     }
 
@@ -841,7 +843,36 @@
     }
 
+    //TODO: Remover apos suporte a deepness na api
+    public function findDeepnessOne(&$uri, &$params, &$criteria, $original){
+
+        if (isset($criteria['findOne']) && $criteria['findOne'] == '1') {
+
+            $sql = ' SELECT DISTINCT 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.priority as "priority", calendar_object.due as "due", '
+                .'calendar_object.percentage as "percentage", calendar_object.status as "status", '
+                .'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" '
+                .'FROM calendar_object '
+                .'WHERE ( calendar_object.id = '. $criteria['schedulable'] .')';
+
+            $params = Controller::service('PostgreSQL')->execResultSql($sql);
+
+            $params = self::deepnessFindEvent($uri, $params, $criteria, $original);
+            return false;
+        }
+
+
+
+    }
+
     //TODO: Remover apos suporte a deepness na api 
     public function deepnessFindEvent(&$uri, &$result, &$criteria, $original) {
-        if (isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0) {
+        if ((isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0) ) {
 
             $date = new DateTime('now', new DateTimeZone('UTC'));
Index: /trunk/prototype/modules/calendar/constants.php
===================================================================
--- /trunk/prototype/modules/calendar/constants.php	(revision 7077)
+++ /trunk/prototype/modules/calendar/constants.php	(revision 7702)
@@ -97,3 +97,7 @@
 define('STATUS_TODO_COMPLETED', 3);
 define('STATUS_TODO_CANCELLED', 4);
+
+define('EVENT_NOT_EDITABLE', 0);
+define('EVENT_EDITABLE', 1);
+define('EVENT_EDITABLE_FROM_PERMISSION', 2)
 ?>
Index: /trunk/prototype/modules/calendar/schedules.php
===================================================================
--- /trunk/prototype/modules/calendar/schedules.php	(revision 7702)
+++ /trunk/prototype/modules/calendar/schedules.php	(revision 7702)
@@ -0,0 +1,177 @@
+<?php
+/**
+ * Created by JetBrains PhpStorm.
+ * User: Adriano
+ * Date: 28/12/12
+ * Time: 18:36
+ * To change this template use File | Settings | File Templates.
+ */
+if(!defined('ROOTPATH'))
+    define('ROOTPATH', dirname(__FILE__).'/../..');
+
+require_once ROOTPATH.'/api/controller.php';
+require_once ROOTPATH.'/modules/calendar/constants.php';
+require_once ROOTPATH.'/modules/calendar/interceptors/DBMapping.php';
+
+use prototype\api\Config as Config;
+
+class Schedule{
+
+    function findEventsRange( $start, $end, $calendars, $timezones ){
+
+        $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.priority as "priority", calendar_object.due as "due", '
+                .'calendar_object.percentage as "percentage", calendar_object.status as "status", '
+                .'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 ( calendar_to_calendar_object.calendar_id IN (\'' . implode('\',\'', $calendars) . '\')) '
+                .'AND calendar_to_calendar_object.calendar_object_id = calendar_object.id '
+                .'AND calendar_object.id NOT IN(select calendar_object_task_id from calendar_task_to_activity_object where owner = \'' . Config::me('uidNumber') . '\') ';
+
+        $ids = array();
+        $occ = array();
+
+        if ($occurrences = DBMapping::checkOccurrences($start, $end, $calendars))
+            foreach ($occurrences as $id => $occurrence) {
+                $ids[] = $id;
+                $occ[] = $occurrence;
+            }
+
+        $where =
+            ' AND ((range_end >= \'' . $start . '\' AND range_end <= \'' . $end . '\') OR '
+                .'(range_start >= \'' . $start . '\' AND range_start <= \'' . $end . '\') OR '
+                .'(range_start <= \'' . $start . '\' AND range_end >= \'' . $end . '\')) '
+                .(!empty($ids) ? ' ' .'AND calendar_object.id NOT IN (\'' . implode('\',\'', $ids) . '\') ' : ' ')
+                .'AND calendar_object.dtstart NOT IN (SELECT calendar_repeat_occurrence.occurrence from calendar_repeat_occurrence, '
+                .'calendar_repeat where (calendar_repeat_occurrence.repeat_id = calendar_repeat.id) '
+                .'AND (calendar_repeat.object_id = calendar_object.id))';
+
+        $params = Controller::service('PostgreSQL')->execResultSql($sql.$where);
+        $params = array_merge($params, $occ);
+
+        return $this->normalizeEvents( $params, $timezones );
+    }
+
+    function findEventsSearch( $summary, $description, $calendars, $timezones, $limit, $offset ){
+
+        $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.priority as "priority", calendar_object.due as "due", '
+            .'calendar_object.percentage as "percentage", calendar_object.status as "status", '
+            .'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 ( calendar_to_calendar_object.calendar_id IN (\'' . implode('\',\'', $calendars) . '\')) '
+            .'AND calendar_to_calendar_object.calendar_object_id = calendar_object.id '
+            .'AND calendar_object.id NOT IN(select calendar_object_task_id from calendar_task_to_activity_object where owner = \'' . Config::me('uidNumber') . '\') ';
+
+
+            $where = 'AND (((upper("summary") like upper(\'%'.$summary.'%\') OR upper("description") like upper(\'%'.$description.'%\')))) ORDER BY dtstart LIMIT '.$limit.'  OFFSET '.$offset.' ';
+            $params = Controller::service('PostgreSQL')->execResultSql($sql.$where);
+
+
+
+        return $this->normalizeEvents( $params, $timezones );
+    }
+
+    function normalizeEvents( &$result, $timezones ){
+
+        $date = new DateTime('now', new DateTimeZone('UTC'));
+        $DayLigth = array();
+
+        foreach ($result as $i => $v) {
+
+            $currentTimezone = (isset($v['calendar']) && isset($timezones[$v['calendar']])) ? $timezones[$v['calendar']] : $v['timezone'];
+
+            $date->setTimestamp((int) ($v['startTime'] / 1000));
+            $date->setTimezone( new DateTimeZone( $v['timezone'] ));
+            $DayLigth['event']['startTime'] = ($date->getTimestamp() + $date->getOffset()).'000';
+
+            $date->setTimezone( new DateTimeZone($currentTimezone));
+            $DayLigth['calendar']['startTime'] = ($date->getTimestamp() + $date->getOffset()).'000';
+
+            $date->setTimestamp((int) ($v['endTime'] / 1000));
+            $date->setTimezone( new DateTimeZone($currentTimezone));
+            $DayLigth['event']['endTime'] = ($date->getTimestamp() + $date->getOffset()).'000';
+
+            if(isset($v['due']) && $v['due'] != '0'){
+                $date->setTimestamp((int) ($v['due'] / 1000));
+                $DayLigth['event']['due'] = ($date->getTimestamp() + $date->getOffset()).'000';
+            }else{
+                $DayLigth['event']['due'] = $v['due'];
+            }
+
+            $date->setTimezone( new DateTimeZone($currentTimezone));
+            $DayLigth['calendar']['endTime'] = ($date->getTimestamp() + $date->getOffset()).'000';
+
+            $result[$i]['DayLigth'] = $DayLigth;
+
+            if(isset( $v['occurrences'] ) && count( $v['occurrences'] ) > 0){
+
+                foreach( $result[$i]['occurrences'] as &$o){
+
+                    $date->setTimestamp((int) ($o / 1000));
+                    $o = ($date->getTimestamp() + $date->getOffset()).'000';
+
+                }
+            }
+
+            $attend = Controller::read(array('concept' => 'participant'), null, array('filter' => array('AND', array('=','schedulable',$v['id']), array('=','user', Config::me('uidNumber'))  )));
+
+            if(count($attend) > 0 && !empty($attend)){
+
+                if(array_key_exists(0, $attend))
+                    $attend = $attend[0];
+
+                $result[$i]['editable'] = (strstr($attend['acl'],"w") || strstr($attend['acl'],"o")) ? 1 : 0;
+
+            }else{
+
+               $result[$i]['editable'] = $v['type'] == '2' ? 0 : 2;
+
+            }
+        }
+
+        return $this->toUtf8( $result );
+    }
+
+    function srtToUtf8($data) {
+        return mb_convert_encoding($data, 'UTF-8', 'UTF-8 , ISO-8859-1');
+    }
+
+    function toUtf8($data) {
+        if (is_array($data)) {
+            $return = array();
+            foreach ($data as $i => $v)
+                $return[$this->srtToUtf8($i)] = (is_array($v)) ? $this->toUtf8($v) : $this->srtToUtf8($v);
+
+            return $return;
+        }else
+            return $this->srtToUtf8($data);
+    }
+
+}
+
+$params = $_GET;
+$schedule = new Schedule();
+
+if(isset( $params['rangeStart'] ))
+    $events = $schedule->findEventsRange( $params['rangeStart'], $params['rangeEnd'], $params['calendar'], $params['timezones'] );
+else
+    $events = $schedule->findEventsSearch( $params['summary'], $params['description'], $params['calendar'], $params['timezones'], $params['limit'], $params['offset'] );
+
+echo json_encode( $events );
+?>
Index: /trunk/prototype/modules/calendar/js/calendar.codecs.js
===================================================================
--- /trunk/prototype/modules/calendar/js/calendar.codecs.js	(revision 7680)
+++ /trunk/prototype/modules/calendar/js/calendar.codecs.js	(revision 7702)
@@ -73,8 +73,5 @@
 		    if( Calendar.currentViewKey !== viewKey ){
 			Calendar.currentViewKey = viewKey;
-			Calendar.currentView = DataLayer.get( 'schedulable:calendar', {
-			    start: start, 
-			    end: end
-			} );
+			Calendar.currentView =  DataLayer.encode('schedulable:calendar', DataLayer.dispatch('modules/calendar/schedules', DataLayer.criteria('schedulable:calendar', {start: start,end: end}))  );   //DataLayer.get( 'schedulable:calendar', {start: start,end: end} );
 		    }
 		    var view = Calendar.currentView[ signature.calendar.id ];
@@ -199,9 +196,12 @@
   
     if( status === 'serverclient' ){
-	DataLayer.commit( false, false, function(){	
+        DataLayer.commit( false, false, function(){
+            //Clean cache client after commit
+            DataLayer.remove('schedulable', false);
+
             Calendar.rerenderView(true);
-	    if(updateActivity)
-		refreshTaskActivity();
-	});
+            if(updateActivity)
+                refreshTaskActivity();
+        });
     }
 });
@@ -1337,8 +1337,8 @@
 function encodeRepeat( repeat ){
   
-    if( !repeat )
-	return( false );
+    if( !repeat || repeat == '0' )
+	    return( false );
     if(typeof(repeat) == "object")
-	return repeat;
+	    return repeat;
 
     return DataLayer.get( 'repeat', repeat );
@@ -1436,80 +1436,146 @@
 
     encoder: function( evtObj ){
-	if(!(!!evtObj))
-	    return undefined;
-
-	var notArray = false;
-		  
-	if( notArray = $.type(evtObj) !== "array" )
-	    evtObj = [ evtObj ];
-
-	var pref = User.preferences;
-    var res = [];
-
-    for(var i = 0; i < evtObj.length; i++){
-	   res.push(DataLayer.encode('schedulable:' + (evtObj[i].type == '1' ?  'preview' : ( !!evtObj[i].taskToActivity ? 'activity': 'task')) , evtObj[i]));
-    }
-
-	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'
+        if(!(!!evtObj))
+            return undefined;
+
+        var notArray = false;
+
+        if( notArray = $.type(evtObj) !== "array" )
+            evtObj = [ evtObj ];
+
+        var pref = User.preferences;
+        var res = [];
+
+        for(var i = 0; i < evtObj.length; i++){
+           res.push(DataLayer.encode('schedulable:' + (evtObj[i].type == '1' ?  'preview' : ( !!evtObj[i].taskToActivity ? 'activity': 'task')) , evtObj[i]));
+        }
+
+        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++) {
+
+                res[i].type = (res[i].type == '2' && !!res[i].tasks) ? '3' : res[i].type;
+
+                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() ];
+
+                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();
+
+                    res[i].startDate = currentDate.toString( User.preferences.dateFormat );
+                    res[i].endDate = new Date( occurrences[ii] + duration ).toString( User.preferences.dateFormat );
+
+                    if(res[i].repeat)
+                        res[i].repeat = typeRepeat[res[i].repeat.frequency];
+                }
+            }
 	    }
 
-	    for (var i=0; i < res.length; i++) {
-
-        res[i].type = (res[i].type == '2' && !!res[i].tasks) ? '3' : res[i].type;
-			  
-		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() ];
-				
-		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 )
-			} );
-
-		    if(res[i].repeat)
-                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
-	    };
-	}
-
-	return notArray ? res[0] : res;
+	    return notArray ? res[0] : res;
+    }
+
+});
+
+DataLayer.codec( "schedulable", "list", {
+
+    decoder: function( evtObj ){},
+
+
+    encoder: function( evtObj ){
+        if(!(!!evtObj))
+            return undefined;
+
+        var notArray = false;
+
+        if( notArray = $.type(evtObj) !== "array" )
+            evtObj = [ evtObj ];
+
+        var pref = User.preferences;
+        var res = [];
+
+        for(var i = 0; i < evtObj.length; i++){
+            res.push(DataLayer.encode('schedulable:' + (evtObj[i].type == '1' ?  'preview' : ( !!evtObj[i].taskToActivity ? 'activity': 'task')) , evtObj[i]));
+        }
+
+        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++) {
+
+                res[i].type = (res[i].type == '2' && !!res[i].tasks) ? '3' : res[i].type;
+
+                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() ];
+
+                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 )
+                    } );
+
+                    if(res[i].repeat)
+                        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
+            };
+        }
+
+        return notArray ? res[0] : res;
     }
 
@@ -1693,48 +1759,35 @@
 		
 		var taskEditable = function(idTask){
-			for(var i = 0; i < evt.participants.length; i++){
-				attendee = DataLayer.get('participant', evt.participants[i]);
-				if(attendee.user == User.me.id)
-					return attendee.isOrganizer == '1' ? 
-					{
-						editable: true, 
-						disableResizing: false, 
-						disableDragging: false,
-						className: 'fullcalendar-context-menu  event-type-2 event-id-'+idTask+' calendar-id-'+calendar.id
-					} 
-					: 
-					{
-						editable: false, 
-						disableResizing: true, 
-						disableDragging: true,
-						className: 'blocked-event-permision  fullcalendar-not-context-menu event-id-'+idTask
-					};
-			}
+
+            return evt.editable == '1' ?
+                {
+                    editable: true,
+                    disableResizing: false,
+                    disableDragging: false,
+                    className: 'fullcalendar-context-menu  event-type-2 event-id-'+idTask+' calendar-id-'+calendar.id
+                }
+                :
+                {
+                    editable: false,
+                    disableResizing: true,
+                    disableDragging: true,
+                    className: 'blocked-event-permision  fullcalendar-not-context-menu event-id-'+idTask
+                };
 		}
 		
 	    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-type-1 event-id-'+idEvent+' calendar-id-'+calendar.id+ (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+' calendar-id-'+calendar.id,  
-					selectable: true, 
-					disableDragging: isRecurrence
-				};
-			}
-			else{
+
+                return (evt.editable == '1' ) ?
+                {
+                    selectable: true,
+                    className: 'fullcalendar-context-menu  event-type-1 event-id-'+idEvent+' calendar-id-'+calendar.id+ (isRecurrence ? ' isRecurrence Recurrence-id-'+Recurrence : '')
+                } : {
+                    editable: false,
+                    selectable: true ,
+                    className: 'blocked-event-permision  fullcalendar-not-context-menu event-id-'+idEvent
+                };
+
+			}else{
 				var aclSignature = Calendar.signatureOf[calendar.id].permission;
 					
@@ -1799,37 +1852,20 @@
     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', 
-			['OR',
-			    ['AND', 
-				['>=', 'rangeEnd', filter.start.getTime()], 
-				['<=', 'rangeEnd', filter.end.getTime()]
-			    ],
-			    ['AND', 
-				['>=', 'rangeStart', filter.start.getTime()], 
-				['<=', 'rangeStart', filter.end.getTime()]
-			    ],
-			    ['AND', 
-				['<=', 'rangeStart', filter.start.getTime()], 
-				['>=', 'rangeEnd', filter.end.getTime()]
-			    ]
-			],
-			['IN', 'calendar',  $.merge( Calendar.calendarIds, Calendar.groupIds )]
-		], 
-	    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 {
+            timezones: timezone,
+            rangeStart: filter.start.getTime(),
+            rangeEnd: filter.end.getTime(),
+            calendar: $.merge( [], Calendar.calendarIds, Calendar.groupIds )
+        }
+    }
 });
 
Index: /trunk/prototype/modules/calendar/js/load.js
===================================================================
--- /trunk/prototype/modules/calendar/js/load.js	(revision 7599)
+++ /trunk/prototype/modules/calendar/js/load.js	(revision 7702)
@@ -13,5 +13,7 @@
 
 	    DataLayer.task( this.clookRefresh , function(){
-		Calendar.rerenderView(true);
+
+            DataLayer.remove('schedulable', false);
+            Calendar.rerenderView(true);
 	    });
 	}
Index: /trunk/prototype/modules/calendar/js/helpers.js
===================================================================
--- /trunk/prototype/modules/calendar/js/helpers.js	(revision 7661)
+++ /trunk/prototype/modules/calendar/js/helpers.js	(revision 7702)
@@ -1964,5 +1964,5 @@
 	    if(clicked == 'Sim'){
 
-		var schedulable = DataLayer.get('schedulable', ''+eventId);
+		var schedulable = getSchedulable( eventId, '');
 		schedulable.calendar = ''+idCalendar;
 		var schudableDecode = DataLayer.encode( "schedulable:preview", schedulable);
@@ -1982,9 +1982,8 @@
 
 function mount_exception(eventID, idException){
-    
-    var schedulable = DataLayer.get('schedulable', ''+eventID);
-    var edit = {
-	repeat: (DataLayer.get('repeat', schedulable.repeat))
-	};                                   
+
+    getSchedulable( eventID.toString() , '');
+    var schedulable = DataLayer.get('schedulable', eventID.toString() )
+    var edit = { repeat: (DataLayer.get('repeat', schedulable.repeat)) };
 
     edit.repeat.startTime = new Date(parseInt(edit.repeat.startTime)).toString('yyyy-MM-dd HH:mm:00');
@@ -2502,7 +2501,5 @@
 	case 'basicDay':
 	case 'agendaDay':
-	    rangeStart = new Date.today().add({
-		days: page_index
-	    }).getTime();
+	    rangeStart = new Date.today().add({ days: page_index }).getTime();
 	    rangeEnd = rangeStart + 86400000;
 	    break;
@@ -2510,31 +2507,22 @@
 	    var dateStart = new Date().moveToDayOfWeek(dateCalendar.dayOfWeek[User.preferences.weekStart]); 
 	    var dateEnd = new Date().moveToDayOfWeek(dateCalendar.dayOfWeek[User.preferences.weekStart]); 
-	    rangeStart = dateStart.add({
-		days: (7 * page_index)
-		}).getTime();
-	    rangeEnd = dateEnd.add({
-		days: (7 * page_index)+7
-		}).getTime();
+	    rangeStart = dateStart.add({ days: (7 * page_index)	}).getTime();
+	    rangeEnd = dateEnd.add({ days: (7 * page_index)+7 }).getTime();
 	    break;
 	case 'month':
-	    var date = Date.today().add({
-		months: page_index
-	    }) 
+	    var date = Date.today().add({ months: page_index })
 	    rangeStart = date.moveToFirstDayOfMonth().getTime();
 	    rangeEnd = date.moveToLastDayOfMonth().getTime();
 	    break;
 	case 'year':
-	    var dateStart = new Date().add({
-		years: page_index
-	    });	
-	    var dateEnd = new Date().add({
-		years: page_index
-	    });
+	    var dateStart = new Date().add({ years: page_index });
+	    var dateEnd = new Date().add({ years: page_index });
 	    if(dateStart.getMonth() != 0)
-		dateStart.moveToMonth(0, -1)
+		    dateStart.moveToMonth(0, -1)
 	    if(dateEnd.getMonth() != 11)
-		dateEnd.moveToMonth(11)	
-	    rangeStart =    dateStart.moveToFirstDayOfMonth().getTime();
-	    rangeEnd = dateEnd.moveToLastDayOfMonth().getTime();
+            dateEnd.moveToMonth(11)
+
+        rangeStart = dateStart.moveToFirstDayOfMonth().getTime();
+        rangeEnd = dateEnd.moveToLastDayOfMonth().getTime();
 	    break;  
     }
@@ -2542,31 +2530,13 @@
     var timezone = {};
     for(var i in Calendar.signatureOf)
-	timezone[i] = Calendar.signatureOf[i].calendar.timezone;		
-	
-    return {
-	 filter: ['AND', 
-		    ['OR', 
-			['AND', 
-			    ['>=', 'rangeEnd', rangeStart], 
-			    ['<=', 'rangeEnd', rangeEnd]
-			],
-			['AND', 
-			    ['>=', 'rangeStart', rangeStart], 
-			    ['<=', 'rangeStart', rangeEnd]
-			],
-			['AND', 
-			    ['<=', 'rangeStart', rangeStart], 
-			    ['>=', 'rangeEnd', rangeEnd]
-			]
-		    ],
-		    ['IN', 'calendar',  calerdars_selecteds]
-		], 
-	criteria: {
-	    deepness: 2, 
+	    timezone[i] = Calendar.signatureOf[i].calendar.timezone;
+	
+    return  {
+        rangeStart: rangeStart,
+        rangeEnd: rangeEnd,
 	    order: 'startTime', 
-	    timezones: timezone
-	}
-    }; 
-
+	    timezones: timezone,
+        calendar: calerdars_selecteds
+	};
 }
 
@@ -2581,26 +2551,38 @@
     
 	if(!selecteds && (keyword != '' && keyword != null)){	
-	jQuery('#'+tab_selector[type] + ((Base64.encode(keyword)).replace(/[^\w\s]/gi, "")|| '')).html(
-	    '<div title="'+tab_title[type]+'" class="events-list events-list-win active empty">' +
-	    '<label>'+label_noselect_calendar[type]+'</label>' +
-	    '</div>'
-	    );
+        jQuery('#'+tab_selector[type] + ((Base64.encode(keyword)).replace(/[^\w\s]/gi, "")|| '')).html(
+            '<div title="'+tab_title[type]+'" class="events-list events-list-win active empty">' +
+            '<label>'+label_noselect_calendar[type]+'</label>' +
+            '</div>'
+        );
     }else{
-	var criteria = null;
-	if(keyword == '' || keyword == null)
-	    criteria = mountCriteriaList(!!view ? view : User.preferences.defaultCalView, page_index, selecteds)
-	else
-	    criteria =  {
-		filter: ['AND', ['OR', ["i*", "summary", keyword], ["i*", "description", keyword]], ['IN', 'calendar',  selecteds]], 
-		criteria: {
-		    searchEvent: true,
-		    order: 'startTime', 
-		    offset: (25 * page_index), 
-		    limit: (((25 * page_index) + 25) + 1), 
-		    deepness: 2
-		}
-	    };
-    var results = DataLayer.get('schedulable:detail', criteria);
-    keyword = ( keyword || '' ).replace( /\s+/g, "_" );	
+        var criteria = null;
+        if(keyword == '' || keyword == null){
+
+            criteria = mountCriteriaList(!!view ? view : User.preferences.defaultCalView, page_index, selecteds);
+
+        }else{
+
+            var timezone = {};
+            for(var i in Calendar.signatureOf)
+                timezone[i] = Calendar.signatureOf[i].calendar.timezone;
+
+            criteria =  {
+
+                searchEvent: true,
+                order: 'startTime',
+                offset: (25 * page_index),
+                limit: (((25 * page_index) + 25) + 1),
+                summary: keyword,
+                description: keyword,
+                calendar: selecteds,
+                timezones: timezone
+
+            };
+        }
+
+        var results = DataLayer.encode('schedulable:list', DataLayer.dispatch('modules/calendar/schedules', criteria));
+        //var results = DataLayer.get('schedulable:detail', criteria);
+        keyword = ( keyword || '' ).replace( /\s+/g, "_" );
 	}
 // não há resultados	
@@ -2627,5 +2609,27 @@
 			$(".event-details-item").parent().click(function(event){
 			event.stopImmediatePropagation();
-			$(this).siblings("div.details-event-list").toggleClass("hidden")
+            var container = $(this).siblings("div.details-event-list");
+
+
+            //lazy data
+            if( container.hasClass('hidden') ){
+
+                //only first click
+                if(!container.find('fieldset').length){
+
+                   $(this).append( '<span style="width: 20px;" class="load-event-detail"><img style="width: 20px;" src="'+DataLayer.dispatchPath+'/modules/calendar/img/loading.gif"></img></span>');
+
+                    var schedulable = container.find('input[name="eventid"]').val();
+                    schedulable = DataLayer.encode('schedulable:detail', [getSchedulable( schedulable, '' )]);
+
+                    schedulable = $.isArray( schedulable ) ? schedulable[0] : schedulable;
+
+                    container.prepend( DataLayer.render( 'templates/event_detail_list.ejs', {'_event': schedulable}));
+
+                    $(this).find('span.load-event-detail').remove();
+                }
+            }
+
+            container.toggleClass("hidden")
 			.find('.button.delete').click(function(event){
 				var eventId = $(this).siblings('[name="eventid"]').val();
@@ -2635,13 +2639,16 @@
 			})
 			.end().find('.button.edit').click(function(event){
+
+                var schedulable = $(this).siblings('[name="eventid"]').val();
                 switch($(this).siblings('[name="eventtype"]').val()){
+
                     case '1':
-                        eventDetails( DataLayer.get( "schedulable", $(this).siblings('[name="eventid"]').val() ), true );
+                        eventDetails( getSchedulable( schedulable, '' ), true );
                     break;
                     case '2':
-                        taskDetails( DataLayer.get( "schedulable", $(this).siblings('[name="eventid"]').val() ), true );
+                        taskDetails( getSchedulable( schedulable, '' ), true );
                     break;
                     case '3':
-                        activityDetails( DataLayer.get( "schedulable", $(this).siblings('[name="eventid"]').val() ), true );
+                        activityDetails( getSchedulable( schedulable, '' ), true );
                     break; 
                 }
@@ -2829,5 +2836,6 @@
 	type = $('.calendar-copy-move input[name="typeEvent"]').val();
 
-    var schedulable = DataLayer.get('schedulable', event+'');
+    getSchedulable(event,'');
+    var schedulable = DataLayer.get('schedulable', event.toString());
     schedulable['class'] = '1';
         
@@ -2843,5 +2851,5 @@
 		
 	schedulable.lastCalendar = schedulable.calendar;
-        schedulable.calendar = calendar;	
+    schedulable.calendar = calendar;
 	DataLayer.put('schedulable', schedulable);
 	
@@ -2868,6 +2876,6 @@
 	    delete repeat.schedulable;
 	    delete repeat.id;
-	    repeat.startTime = new Date(parseInt(repeat.startTime)).toString('yyyy-MM-dd HH:mm:00');
-	    repeat.endTime = new Date(parseInt(repeat.endTime)).toString('yyyy-MM-dd HH:mm:00');
+	    repeat.startTime = repeat.startTime == '' ? '' : new Date(parseInt(repeat.startTime)).toString('yyyy-MM-dd HH:mm:00');
+	    repeat.endTime = repeat.endTime == '' ? '' : new Date(parseInt(repeat.endTime)).toString('yyyy-MM-dd HH:mm:00');
                     
 	    var exceptions = DataLayer.get('repeatOccurrence', {
@@ -2892,5 +2900,5 @@
 	delete schedulable.occurrences;
                 
-	schedulable.calendar = DataLayer.copy(calendar);	
+	schedulable.calendar = DataLayer.copy(calendar);
 		
 	var participants = DataLayer.copy(schedulable.participants);
@@ -2925,6 +2933,6 @@
 	    return newSchedulable;
 	}
-	newSchedulable.endTime = new Date(parseInt(newSchedulable.endTime) - (newSchedulable.allDay ? 86400000 : 0)).toString('yyyy-MM-dd hh:mm:00');
-	newSchedulable.startTime = new Date(parseInt(newSchedulable.startTime)).toString('yyyy-MM-dd hh:mm:00'); 
+	newSchedulable.endTime = new Date(parseInt(newSchedulable.endTime) - (parseInt(newSchedulable.allDay) ? 86400000 : 0)).toString('yyyy-MM-dd HH:mm:00');
+	newSchedulable.startTime = new Date(parseInt(newSchedulable.startTime)).toString('yyyy-MM-dd HH:mm:00');
 	
 	DataLayer.put('schedulable', newSchedulable);
Index: /trunk/prototype/modules/calendar/js/init.js
===================================================================
--- /trunk/prototype/modules/calendar/js/init.js	(revision 7653)
+++ /trunk/prototype/modules/calendar/js/init.js	(revision 7702)
@@ -15,6 +15,9 @@
 		},
 		show: function( event, ui ){
-			delete Calendar.currentViewKey;
-			$('#calendar').fullCalendar('refetchEvents');
+
+            if( $('#tabs').tabs('option' ,'selected') == 0){
+                delete Calendar.currentViewKey;
+                $('#calendar').fullCalendar('refetchEvents');
+            }
 		}
 	})
@@ -397,57 +400,58 @@
 		eventDrop: function( evt, event, view  ){
 			evt.id = evt.id.split('-')[0];
-                        if(!evt.disableDragging){
+            if(!evt.disableDragging){
                             
-                             if(evt.isRepeat){
-                                 var schedulable = copyAndMoveTo(false , evt.id , false, "3", evt);
+                if(evt.isRepeat){
+                    var schedulable = copyAndMoveTo(false , evt.id , false, "3", evt);
                                  
-                                 var repeat = mount_exception(evt.id, evt.occurrence);
-                                 DataLayer.remove('repeat', false);
-                                 DataLayer.put('repeat', repeat);
-                                 DataLayer.commit('repeat', false, function(data){
+                    var repeat = mount_exception(evt.id, evt.occurrence);
+                    DataLayer.remove('repeat', false);
+                    DataLayer.put('repeat', repeat);
+                    DataLayer.commit('repeat', false, function(data){
                                     
-                                    DataLayer.remove('schedulable', repeat.schedulable, false); 
-                                    DataLayer.put('schedulable', schedulable);
+                        DataLayer.remove('schedulable', repeat.schedulable, false);
+                        DataLayer.put('schedulable', schedulable);
                                      
-                                 });
-
-                             }else{                                 
-                                DataLayer.put( "schedulable:calendar", evt );
-
-				event.editable = false;
-				event.className = "blocked-event";
-				calendar.fullCalendar( 'updateEvent', evt );
-                             }
+                     });
+
+                }else{
+                    DataLayer.put( "schedulable:calendar", evt );
+
+				    event.editable = false;
+				    event.className = "blocked-event";
+				    calendar.fullCalendar( 'updateEvent', evt );
+                }
                              
 			}else
-                            Calendar.rerenderView(true);
+                Calendar.rerenderView(true);
 		},
 
 		eventResize: function( evt, event, view ){
-                        evt.id = evt.id.split('-')[0];
+            evt.id = evt.id.split('-')[0];
 			if(!evt.disableDragging){
-                             if(evt.isRepeat){
-                                 var schedulable = copyAndMoveTo(false , evt.id , false, "3", evt);
-                                 
-                                 //Normaliza a data para o backend
-                                 schedulable.startTime = new Date(parseInt(schedulable.startTime)).toString('yyyy-MM-dd hh:mm:00');
-                                 schedulable.endTime = new Date(parseInt(schedulable.endTime)).toString('yyyy-MM-dd hh:mm:00');
-                                 
-                                 var repeat = mount_exception(evt.id, evt.occurrence);
-                                 
-                                 DataLayer.remove('repeat', false);
-                                 DataLayer.put('repeat', repeat);
-                                 DataLayer.commit('repeat', false, function(data){
-                                     
-                                    DataLayer.remove('schedulable', repeat.schedulable, false); 
-                                    DataLayer.put('schedulable', schedulable);
-                                     
-                                 });
-                             }else{                                 
-                                DataLayer.put( "schedulable:calendar", evt );   
-                                evt.editable = false;
-                                evt.className = "blocked-event";
-                                calendar.fullCalendar( 'updateEvent', evt );
-                             }
+                if(evt.isRepeat){
+                    var schedulable = copyAndMoveTo(false , evt.id , false, "3", evt);
+
+                    //Normaliza a data para o backend
+                    schedulable.startTime = new Date(parseInt(schedulable.startTime)).toString('yyyy-MM-dd hh:mm:00');
+                    schedulable.endTime = new Date(parseInt(schedulable.endTime)).toString('yyyy-MM-dd hh:mm:00');
+
+                    var repeat = mount_exception(evt.id, evt.occurrence);
+
+                    DataLayer.remove('repeat', false);
+                    DataLayer.put('repeat', repeat);
+                    DataLayer.commit('repeat', false, function(data){
+
+                        DataLayer.remove('schedulable', repeat.schedulable, false);
+                        DataLayer.put('schedulable', schedulable);
+
+                    });
+                }else{
+
+                    DataLayer.put( "schedulable:calendar", evt );
+                    evt.editable = false;
+                    evt.className = "blocked-event";
+                    calendar.fullCalendar( 'updateEvent', evt );
+                }
                         
 			}else
@@ -469,5 +473,7 @@
                                 'onClose':  function(clicked) {
                                     if(clicked == 'Editar todas ocorrências') {
-                                        eventDetails( DataLayer.get( "schedulable", evt.id), true);
+
+                                        eventDetails(  getSchedulable(evt.id, ''), true);
+
                                     }else if (clicked == 'Editar essa ocorrência'){
                                         /*
@@ -485,20 +491,20 @@
                             });
                         }else{
-                            var schedulable = DataLayer.get( "schedulable", evt.id);
+                            var schedulable = getSchedulable(evt.id, '');
                             schedulable.calendar = evt.calendar;
                             eventDetails( schedulable, true);
                             }
-                        }
-                        break;
-                    case 2:
-                        var task = DataLayer.get( "schedulable", evt.id);
-                        task.group = evt.calendar;
-                        taskDetails( task, true);
-                        break;
-                    case 3:
-                        var activity = DataLayer.get( "schedulable", evt.id);
-                        activity.group = evt.calendar;
-                        activityDetails( activity, true);
-                        break;
+                    }
+                    break;
+                case 2:
+                    var task = getSchedulable(evt.id, '');
+                    task.group = evt.calendar;
+                    taskDetails( task, true);
+                    break;
+                case 3:
+                    var activity = getSchedulable(evt.id, '');
+                    activity.group = evt.calendar;
+                    activityDetails( activity, true);
+                    break;
             }
 		},
@@ -558,4 +564,13 @@
 });
 
+function getSchedulable(id, codec){
+
+    var schedule = DataLayer.get(('schedulable' + (codec != '' ? ':'+codec : '')), id, false );
+
+    if(schedule == false)
+        DataLayer.get(('schedulable' + (codec != '' ? ':'+codec : '')), {filter: ['id', '=', id], criteria: {deepness: 2, findOne: 1, schedulable: id}} );
+
+    return DataLayer.get(('schedulable' + (codec != '' ? ':'+codec : '')), id.toString());
+}
 
 function useDesktopNotification(){
Index: /trunk/prototype/modules/calendar/templates/event_list.ejs
===================================================================
--- /trunk/prototype/modules/calendar/templates/event_list.ejs	(revision 7022)
+++ /trunk/prototype/modules/calendar/templates/event_list.ejs	(revision 7702)
@@ -6,7 +6,7 @@
 
 <div title="<%=data.tab_title%>" class="events-list events-list-win active">
-	
-	
-		<div class="events-list pagination">			
+
+
+		<div class="events-list pagination">
 			<input name="results" type="hidden" value="<%=data.count%>"></input>
 			<input name="page_index" type="hidden" value="<%=data.page_index%>"></input>
@@ -37,9 +37,9 @@
 							<% } %>
 						<% } else {  %>
-								<tr> 
+								<tr>
 								<% if (j>0) %>
 									<!-- coluna 1 - evento unico na mesma data -->
 									<th width='100' class="start-date">
-										<span><%= data.events_list[i].startDate %></span> <% 
+										<span><%= data.events_list[i].startDate %></span> <%
 								} %>
 									</th>
@@ -108,133 +108,12 @@
 						</span>	
 						<div class="details-event-list hidden <%= (title_type == "Evento" ? "details-event" : "details-task")  %>">
-							<fieldset class="fields-details-event-list">							
-								<%if(_event.allDay){%>
-									<p class="input-group date-info">
-										<label>Duração:</label>
-										<span class="">Dia inteiro</span>
-									</p>
-								<%}else{%>
-								
-									<p class="input-group date-info">
-										<label>Início:</label>
-										<span class=""><%= _event.startDate %> às </span>
-										<span class=""><%= _event.startHour %></span> 
-										
-									</p>
-									<p class="input-group">
-										<label>Término:</label>
-										<span class=""><%= _event.endDate %> às </span>
-										<span class=""><%= _event.endHour %></span>
-										<span><%= _event.timeZone %></span>
-									</p>
-								<%}%>
-								<%if(_event.type == '1'){
-									if(_event.repeat ){%>
-								    <p class="input-group">
-									<label>Repetição</label>
-									<span><%= _event.repeat %></span>
-								    </p>
-								<%}}%>
-								<p class="input-group">
-									<label>Lembretes:</label>
-									<% if(_event.alarms) { 
-											var string_alarm = "";
-											if(_event.type == '1')
-												string_alarm = 'do evento'; 
-											if(_event.type == '2')
-												string_alarm = 'da tarefa';
-											if(_event.type == '3')
-												string_alarm = 'da atividade';
-											%>
-										<span class="large" >
-											<% for (var l=0; l < _event.alarms.length; l++) { %>
-												<span class="large" >Você será notificado por um <%=dateCalendar.alarmtype[_event.alarms[l].type]%> <%= _event.alarms[l].time %> <%= dateCalendar.timeunit[_event.alarms[l].unit]%><%=_event.alarms[l].time > 1 ? 's' : '' %> antes <%=string_alarm%></span>
-											<% } %>
-										</span>
-									<% } %>
-								</p>
-								<%if(_event.type == '1'){%>
-								<p class="input-group">
-									<label>Local:</label>
-									<span><%= _event.location %></span>
-								</p>
-								<%}%>
-								<p class="input-group">
-									<label>Descrição:</label>
-									<span class="large" ><%= _event.description %></span>
-								</p>
-								<%if(_event.type != '1'){%>
-								<p class="input-group">
-									<label>Prioridade:</label>
-									<span><%= decoder['priority'][_event.priority] %></span>
-								</p>
-								<p class="input-group">
-									<label>% Conlusão:</label>
-									<span><%= _event.percentage %>%</span>
-								</p>
-								<p class="input-group">
-									<label>Status:</label>
-									<span><%= decoder['status'][_event.status] %></span>
-								</p>
-								<% } %>
-								<!-- <p class="input-group">
-									<label>Privacidade</label>
-									<span><%= _event.privacy %></span>
-								</p> -->
-								<%if(_event.organizer && _event.organizer.user){%>
-    								<p class="input-group">
-    									<label>Organizador:</label>
-    									<span class="large"><%= _event.organizer.user ? _event.organizer.user.name : _event.organizer.name %>  (<%= _event.organizer.user ? _event.organizer.user.mail : _event.organizer.mail %>)</span>
-    								</p>
-                                <%}%>
-								<%if(_event.type != '3'){%>
-								<p class="input-group">
-									<label>Participantes:</label>
-									<% if(_event.attendee) { %>
-										<span class="large" >
-											<% for (var m=0; m < _event.attendee.length; m++) { %>
-												<span class="large"><%=_event.attendee[m].name%>  (<%= _event.attendee[m].mail %>)</span>
-											<%}%>
-										</span>
-									<% } %>
-								</p>
-								<%}
-								if(_event.type == '3'){%>
-								<p class="input-group">
-									<label>Tarefas</label>
-									<% if(_event.tasks) { %>
-										<span class="large" >
-											<% for (var m in _event.tasks) { %>
-												<span class="large"><%=_event.tasks[m].description%></span>
-											<%}%>
-										</span>
-									<% } %>
-								</p>
-								<%}%>
-								
-								<p class="input-group">
-									<label>Presença:</label>
-									<span>
-                                        <% var status_name;
-                                            if (_event.status == 1)
-                                                status_name = "Eu vou";
-                                            else if (_event.status == 2)
-                                                status_name = "Talvez";
-                                            else if (_event.status == 3)
-                                                status_name = "Eu não vou";
-                                        %>
-                                        <%= status_name %>
-                                    </span> <!-- Ta hardcodificado isso aqui? -->
-								</p>
-
-							</fieldset>
-							<div class="menu-container footer-container">
-								<input name="eventid" type="hidden" value="<%=_event.id%>"></input>
-								<input name="eventtype" type="hidden" value="<%=_event.type%>"></input>
-                                <input name="calendarid" type="hidden" value="<%=_event.calendar ? _event.calendar : _event.group%>"></input>
-								<a title="Imprimir" class="button print" href="#">Imprimir</a>
-								<a title="Excluir" class="button delete" href="#">Excluir</a>
-								<a title="Editar" class="button edit" href="#">Editar</a>
-							</div>
+                            <div class="menu-container footer-container">
+                                <input name="eventid" type="hidden" value="<%=_event.id%>"/>
+                                <input name="eventtype" type="hidden" value="<%=_event.type%>"/>
+                                <input name="calendarid" type="hidden" value="<%=_event.calendar ? _event.calendar : _event.group%>"/>
+                                <a title="Imprimir" class="button print" href="#">Imprimir</a>
+                                <a title="Excluir" class="button delete" href="#">Excluir</a>
+                                <a title="Editar" class="button edit" href="#">Editar</a>
+                            </div>
 						</div>
 	
Index: /trunk/prototype/modules/calendar/templates/event_detail_list.ejs
===================================================================
--- /trunk/prototype/modules/calendar/templates/event_detail_list.ejs	(revision 7702)
+++ /trunk/prototype/modules/calendar/templates/event_detail_list.ejs	(revision 7702)
@@ -0,0 +1,112 @@
+<%
+
+    var encoder = {};
+    encoder.alarm = {'1':'do evento','2':'da tarefa','3':'da atividade'};
+    encoder.status = {'1':'Eu vou', '2':'Talvez', '3':'Eu não vou'};
+    encoder.statusEvent = {1: 'Sem ações', 2: 'Em processo', 3: 'Completo', 4: 'Cancelado'};
+    encoder.priority = {1: 'Alta', 2: 'Normal', 3: 'Baixa'};
+
+    var _event = data['_event'];
+%>
+
+<fieldset class="fields-details-event-list">
+    <%if(_event.allDay){%>
+    <p class="input-group date-info">
+        <label>Duração:</label>
+        <span class="">Dia inteiro</span>
+    </p>
+    <%}else{%>
+    <p class="input-group date-info">
+        <label>Início:</label>
+        <span class=""><%= _event.startDate %> às </span>
+        <span class=""><%= _event.startHour %></span>
+
+    </p>
+    <p class="input-group">
+        <label>Término:</label>
+        <span class=""><%= _event.endDate %> às </span>
+        <span class=""><%= _event.endHour %></span>
+        <span><%= _event.timezone %></span>
+    </p>
+    <%}%>
+
+    <%if(_event.type == '1'){
+    if(_event.repeat ){%>
+    <p class="input-group">
+        <label>Repetição</label>
+        <span><%= _event.repeat %></span>
+    </p>
+    <%}}%>
+
+    <p class="input-group">
+        <label>Lembretes:</label>
+            <span class="large" >
+                <% for (var l=0; l < _event.alarms.length; l++) { %>
+                    <span class="large" >Você será notificado por um <%= dateCalendar.alarmtype[_event.alarms[l].type]%> <%= _event.alarms[l].time %> <%= dateCalendar.timeunit[_event.alarms[l].unit]%><%=_event.alarms[l].time > 1 ? 's' : '' %> antes <%= encoder.alarm[ event.type ] %></span>
+                <% } %>
+            </span>
+    </p>
+
+
+    <%if(_event.type == '1'){%>
+    <p class="input-group">
+        <label>Local:</label>
+        <span><%= _event.location %></span>
+    </p>
+    <%}%>
+    <p class="input-group">
+        <label>Descrição:</label>
+        <span class="large" ><%= _event.description %></span>
+    </p>
+    <%if(_event.type != '1'){%>
+    <p class="input-group">
+        <label>Prioridade:</label>
+        <span><%= encoder.priority[_event.priority] %></span>
+    </p>
+    <p class="input-group">
+        <label>% Conlusão:</label>
+        <span><%= _event.percentage %>%</span>
+    </p>
+    <p class="input-group">
+        <label>Status:</label>
+        <span><%= encoder.statusEvent[_event.status] %></span>
+    </p>
+    <%}%>
+
+    <%if(_event.organizer && _event.organizer.user){%>
+    <p class="input-group">
+        <label>Organizador:</label>
+        <span class="large"><%= _event.organizer.user ? _event.organizer.user.name : _event.organizer.name %>  (<%= _event.organizer.user ? _event.organizer.user.mail : _event.organizer.mail %>)</span>
+    </p>
+    <%}%>
+    <%if(_event.type != '3'){%>
+    <p class="input-group">
+        <label>Participantes:</label>
+        <% if(_event.attendee) { %>
+                <span class="large" >
+                <% for (var m=0; m < _event.attendee.length; m++) { %>
+                    <span class="large"><%=_event.attendee[m].name%>  (<%= _event.attendee[m].mail %>)</span>
+                <%}%>
+                </span>
+        <%}%>
+    </p>
+    <%}
+    if(_event.type == '3'){%>
+    <p class="input-group">
+        <label>Tarefas</label>
+        <% if(_event.tasks) { %>
+                <span class="large" >
+                <% for (var m in _event.tasks) { %>
+                    <span class="large"><%=_event.tasks[m].description%></span>
+                <%}%>
+                </span>
+        <%}%>
+    </p>
+    <%}%>
+
+    <p class="input-group">
+        <label>Presença:</label>
+        <span> <%= encoder.status[ _event.status ] %> </span>
+    </p>
+
+</fieldset>
