Index: /trunk/expressoCalendar/setup/tables_current.inc.php
===================================================================
--- /trunk/expressoCalendar/setup/tables_current.inc.php	(revision 5514)
+++ /trunk/expressoCalendar/setup/tables_current.inc.php	(revision 5592)
@@ -102,5 +102,5 @@
             
             
-            'calendar_object' => array(
+        'calendar_object' => array(
             'fd' => array(
                 'id' => array( 'type' => 'auto', 'nullable' => False),
@@ -114,7 +114,7 @@
                 'class_id' => array( 'type' => 'int', 'precision' => '8', 'nullable' => True),
                 'last_update' => array( 'type' => 'int', 'precision' => '8', 'nullable' => False),
-                'range_end' => array( 'type' => 'date', 'nullable' => True),
+                'range_end' => array( 'type' => 'bigint', 'precision' => '16', 'nullable' => True),
                 'summary' => array( 'type' => 'varchar', 'precision' => '255', 'nullable' => True),
-                'range_start' => array( 'type' => 'date', 'nullable' => False),
+                'range_start' => array( 'type' => 'bigint', 'precision' => '16', 'nullable' => True),
                 'allday' => array( 'type' => 'int', 'precision' => '2', 'default' => 0, 'nullable' => True),
                 'repeat' => array( 'type' => 'int', 'precision' => '2', 'default' => 0, 'nullable' => True),
@@ -152,6 +152,6 @@
                 'id' => array( 'type' => 'auto', 'nullable' => False),
                 'action_id' => array( 'type' => 'int', 'precision' => '8', 'nullable' => False),
-                'range_end' => array('type' => 'date', 'nullable' => False),
-                'range_start' => array('type' => 'date', 'nullable' => False),
+                'range_end' => array( 'type' => 'bigint', 'precision' => '16', 'nullable' => True),
+                'range_start' => array( 'type' => 'bigint', 'precision' => '16', 'nullable' => True),
                 'unit' => array('type' => 'varchar','precision' => '20','nullable' => True),
                 'time' => array('type' => 'varchar','precision' => '50','nullable' => True),
@@ -203,5 +203,5 @@
                 'object_id' => array(  'type' => 'int', 'precision' => '8', 'nullable' => False),
                 'object_type' => array(  'type' => 'int', 'precision' => '8', 'nullable' => False),
-                'permision' => array(  'type' => 'varchar','precision' => '50', 'nullable' => False)
+                'permission' => array(  'type' => 'varchar','precision' => '50', 'nullable' => False)
             ),
             'pk' => array('id'),
Index: /trunk/prototype/services/iCal.php
===================================================================
--- /trunk/prototype/services/iCal.php	(revision 5528)
+++ /trunk/prototype/services/iCal.php	(revision 5592)
@@ -511,5 +511,5 @@
                 $objTimezone =  new DateTimeZone($schedulable['timezone']);  
                 
-                if($startTime['params']['VALUE'] === 'DATE' && isset($params['calendar_timezone']) )
+                if(isset($startTime['params']['VALUE']) &&  $startTime['params']['VALUE'] === 'DATE' && isset($params['calendar_timezone']) )
                 {
                     $schedulable['allDay'] = 1;
@@ -555,13 +555,13 @@
         
 
-            $schedulable['summary'] = mb_convert_encoding ( $component->getProperty( 'summary' , false , false ) , 'UTF-8' , 'UTF-8,ISO-8859-1');
+            $schedulable['summary'] = mb_convert_encoding ( $component->getProperty( 'summary' , false , false ) , 'ISO-8859-1' , 'UTF-8,ISO-8859-1');
 
             /* Definindo Description */
                 if($desc = $component->getProperty( 'description' , false , false ))
-                    $schedulable['description'] = mb_convert_encoding (str_ireplace (array('\n','\t'), array("\n","\t"), $desc) ,'UTF-8' , 'UTF-8,ISO-8859-1');
+                    $schedulable['description'] = mb_convert_encoding (str_ireplace (array('\n','\t'), array("\n","\t"), $desc) ,'ISO-8859-1'  , 'UTF-8,ISO-8859-1');
 
              /* Definindo location */
                 if($location = $component->getProperty( 'location' , false , false ))
-                    $schedulable['location'] = mb_convert_encoding ( $location , 'UTF-8' , 'UTF-8,ISO-8859-1') ;
+                    $schedulable['location'] = mb_convert_encoding ( $location , 'ISO-8859-1' , 'UTF-8,ISO-8859-1') ;
 
 
@@ -701,5 +701,5 @@
       
             /* Definindo TRANSP */
-            if(($tranp = $component->getProperty( 'transp', false , true )) && strtoupper($tranp) == 'OPAQUE')
+            if(($tranp = $component->getProperty( 'transp', false , true )) && $tranp && strtoupper($tranp) == 'OPAQUE')
                 $schedulable['transparent'] = 1;
 
Index: /trunk/prototype/config/expressoCalendar.ini
===================================================================
--- /trunk/prototype/config/expressoCalendar.ini	(revision 5438)
+++ /trunk/prototype/config/expressoCalendar.ini	(revision 5592)
@@ -1,5 +1,9 @@
 folder = "calendar"
 useCaldav = false
+onRemoveCascadeCalDav = false
 
 ;Utilizar ou não caldav {TRUE or FALSE}
 ;useCaldav = TRUE
+
+; onRemoveCascadeCalDav Remover agenda no caldav automaticamente ao remover no expresso (TRUE or FALSE)
+;onRemoveCascadeCalDav = true
Index: /trunk/prototype/config/calendarSignatureAlarm.ini
===================================================================
--- /trunk/prototype/config/calendarSignatureAlarm.ini	(revision 5514)
+++ /trunk/prototype/config/calendarSignatureAlarm.ini	(revision 5592)
@@ -10,9 +10,7 @@
 [before.update]
 encodeSignatureAlarmType = modules/calendar/interceptors/DBMapping.php
-encodeUpdateConcept = modules/calendar/interceptors/DBMapping.php
 
 [before.create]
 encodeSignatureAlarmType = modules/calendar/interceptors/DBMapping.php
-encodeCreateConcept = modules/calendar/interceptors/DBMapping.php
 
 [before.delete]
Index: /trunk/prototype/config/calendar.ini
===================================================================
--- /trunk/prototype/config/calendar.ini	(revision 5514)
+++ /trunk/prototype/config/calendar.ini	(revision 5592)
@@ -4,4 +4,5 @@
 [model.hasMany]
 signatures = calendarSignature.calendar
+permissions = calendarToPermission.calendar
 
 [before.create]
@@ -15,5 +16,4 @@
 davcalDeleteCollection = modules/calendar/interceptors/DBMapping.php
 
-
 [PostgreSQL.mapping]
 id = "id"
Index: /trunk/prototype/config/calendarToPermission.ini
===================================================================
--- /trunk/prototype/config/calendarToPermission.ini	(revision 5592)
+++ /trunk/prototype/config/calendarToPermission.ini	(revision 5592)
@@ -0,0 +1,15 @@
+service = PostgreSQL
+PostgreSQL.concept = calendar_permission
+
+[model.depends]
+calendar = calendar.permissions
+
+[after.find]
+deepnessFindCalendarShared = modules/calendar/interceptors/DBMapping.php
+
+[PostgreSQL.mapping]
+id = id
+user = uidnumber
+calendar = object_id
+type = object_type
+acl = permission
Index: /trunk/prototype/config/attachment.ini
===================================================================
--- /trunk/prototype/config/attachment.ini	(revision 5514)
+++ /trunk/prototype/config/attachment.ini	(revision 5592)
@@ -17,3 +17,3 @@
 name = "name"
 size = "size"
-
+owner = "owner"
Index: /trunk/prototype/modules/calendar/interceptors/DBMapping.php
===================================================================
--- /trunk/prototype/modules/calendar/interceptors/DBMapping.php	(revision 5514)
+++ /trunk/prototype/modules/calendar/interceptors/DBMapping.php	(revision 5592)
@@ -9,11 +9,18 @@
     public function encodeCreateSchedulable( &$uri , &$params , &$criteria , $original ){			
         $params['type_id'] = EVENT_ID;
-              
-        $params['rangeStart'] = gmdate( 'd-m-Y' , (int)($params['startTime'] / 1000) );
+	
+		$params['startTime'] =  strtotime( $params['startTime'] . ' ' .$params['timezone']).'000';
+	
+		$params['endTime'] =   strtotime( $params['endTime'] . ' ' .$params['timezone']).'000';
+		
+		if($params['allDay'])
+			$params['endTime'] =  $params['endTime']  + 86400000;
 
     //        if( !isset( $new['repeat'] ))
     //            $new['range_end'] = '7287926400'; // 12/12/2200
     //        else
-            $params['rangeEnd'] = gmdate( 'd-m-Y' , (int)($params['endTime'] / 1000) );
+            $params['rangeEnd'] = $params['endTime'];
+			$params['rangeStart'] =  $params['startTime'];
+
             ///////////////////////////////////////////////////////////////////
 
@@ -24,4 +31,5 @@
             
         }	
+		
     public function encodeCreateAlarm( &$uri , &$params , &$criteria , $original ){
       	
@@ -59,5 +67,6 @@
 				$params =  $_FILES[$params['source']];
 		
-		//$params['source'] = base64_encode( $params['source'] );	
+		if(isset($params['owner']))
+			$params['owner'] = Config::me('uidNumber');
 		
 	}
@@ -112,7 +121,7 @@
     public function encodeUpdateSchedulable( &$uri , &$params , &$criteria , $original ){	
         if(isset($params['startTime']))
-	       	$params['rangeStart'] = gmdate( 'd-m-Y' , (int)($params['startTime'] / 1000) );
+	       	$params['rangeStart'] = $params['startTime'] ;
 	if(isset($params['endTime']))
-   		$params['rangeEnd'] = gmdate( 'd-m-Y' , (int)($params['endTime'] / 1000) );       
+   		$params['rangeEnd'] = $params['endTime'] ;       
         	
                 
@@ -172,11 +181,73 @@
 	}
      
+	 public function deepnessFindCalendarShared( &$uri , &$result , &$criteria , $original ){				
+		if(isset($original['criteria']['deepness']) && 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)
+					$value['user'] = Controller::read( array( 'concept' => 'user' , 'id' => $value['user'] ));
+			}
+
+
+		$result = $newResult;
+		}
+    }	
+ 
     //TODO: Remover apos suporte a deepness na api 
     public function deepnessFindEvent( &$uri , &$result , &$criteria , $original ){		
-       
+
        if(isset($original['criteria']['deepness']))
        {
+			
+			$Time = new DateTime( 'now', new DateTimeZone('UTC') );
+			$DayLigth = array();
            foreach ($result as $i => $v)
            {
+
+				if(!isset($currentTimezone) || $currentTimezone  != $original['criteria']['timezones'][$v['calendar']]){
+					$currentTimezone = $original['criteria']['timezones'][$v['calendar']];
+					$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']))
                 {
@@ -195,5 +266,7 @@
                     }       
                     $result[$i]['participants'] = $participants;
-                
+					
+					
+					
 					$attachmentRelation = Controller::find( array( 'concept' => 'schedulableToAttachment' ) , false ,array( 'filter' => array('=', 'schedulable'  ,  $v['id']) )); 
 					if(is_array($attachmentRelation)){
@@ -214,5 +287,5 @@
        
    } 
-   
+
     //TODO: Remover apos suporte a deepness na api 
     public function deepnessReadEvent( &$uri , &$result , &$criteria , $original ){		
@@ -295,5 +368,29 @@
                 if(isset($v['calendar'])){
                     $result[$i]['calendar'] = Controller::read( array( 'concept' => 'calendar' , 'id' => $v['calendar'])); 
-					$result[$i]['defaultAlarms'] = Controller::find( array( 'concept' => 'calendarSignatureAlarm' ) , false ,array( 'filter' => array('=', 'calendarSignature'  ,  $v['id']) ));     
+					$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  ){
+							ob_start();
+							var_dump($permission);
+							
+							$output = ob_get_clean();
+							file_put_contents( "/tmp/acoutinho.log",  $output , FILE_APPEND);
+							$permission = Controller::find( array( 'concept' => 'calendarToPermission'), false ,array( 'filter' => array('AND', array('=', 'calendar' ,  $v['calendar']), array('=', 'type', '1' ) ) ) );    
+							
+							ob_start();
+						var_dump($permission);
+						
+						$output = ob_get_clean();
+						file_put_contents( "/tmp/acoutinho.log",  $output , FILE_APPEND);
+							
+						}
+						$result[$i]['permission'] = $permission[0];
+					}
 				}
            }
@@ -627,6 +724,4 @@
 			}         
         }
- 
-		
 	}
 
@@ -640,5 +735,5 @@
     
    public function davcalDeleteCollection( &$uri , &$params , &$criteria , $original ){	
-        if( Config::module('useCaldav') )
+        if( Config::module('useCaldav') &&  Config::module('onRemoveCascadeCalDav'))
         {
            require_once ROOTPATH.'/modules/calendar/interceptors/DAViCalAdapter.php';
Index: /trunk/prototype/modules/calendar/constants.php
===================================================================
--- /trunk/prototype/modules/calendar/constants.php	(revision 5514)
+++ /trunk/prototype/modules/calendar/constants.php	(revision 5592)
@@ -11,5 +11,4 @@
 define('STATUS_DELEGATED', 5);
 
-
 define('ALARM_ALERT', 1);
 define('ALARM_MAIL', 2);
@@ -23,5 +22,4 @@
 define('CLASS_CONFIDENTIAL', 3);
 
-
 define('ICAL_ACTION_IMPORT', 1);
 define('ICAL_ACTION_UPDATE', 2);
@@ -31,3 +29,17 @@
 define('ICAL_ACTION_SUGGESTION', 6);
 
+define('ATTENDEE_ACL_ORGANIZATION', 'o');
+define('ATTENDEE_ACL_WRITE', 2);
+define('ATTENDEE_ACL_PARTICIPATION_REQUIRED', 'w');
+define('ATTENDEE_ACL_INVITE_GUESTES', 'i');
+define('ATTENDEE_ACL_READ', 'r');
+
+define('CALENDAR_PRIVATE', 0);
+define('CALENDAR_PUBLIC', 1);
+
+define('CALENDAR_ACL_WRITE', 'w');
+define('CALENDAR_ACL_READ', 'r');
+define('CALENDAR_ACL_REMOVE', 'd');
+define('CALENDAR_ACL_BUSY', 'b');
+define('CALENDAR_ACL_SHARED', 's');
 ?>
Index: /trunk/prototype/modules/calendar/css/layout.css
===================================================================
--- /trunk/prototype/modules/calendar/css/layout.css	(revision 5515)
+++ /trunk/prototype/modules/calendar/css/layout.css	(revision 5592)
@@ -34,5 +34,6 @@
 
 #wrap .search-field input { 
-	width: 150px; 
+	width: 160px; 
+	padding: 0 0 0 3px;
 }
 
@@ -88,4 +89,14 @@
 .fg-menu-container {
 	z-index: 999;
+	min-width: 134px !important;
+}
+
+.fg-menu-container.evt-option{
+	min-width: 85px !important;
+	padding: 0;
+}
+
+.fg-menu-container.evt-option a{
+	padding: 0.1em 3%;
 }
 
@@ -181,9 +192,11 @@
 	display: inline-block;
 	border: none;
+	width: 215px;
 }
 
 fieldset.search-field span {
 	display: inline-block;
-	margin:0 0 -3px 5px;
+	margin:0 0 -3px 0px;
+	cursor: pointer;
 }
 /* #search area definition */
@@ -225,5 +238,5 @@
 
 fieldset.block-add-attendee .add-attendee-search { max-width: 250px; margin: 5px;}
-fieldset.block-add-attendee .add-attendee-search input { max-width: 215px; width: 215px;}
+fieldset.block-add-attendee .add-attendee-search input { max-width: 220px; width: 220px;}
 fieldset.block-add-attendee .search-result-list { width: 255px; max-height: 215px; overflow: auto;}
 fieldset.block-add-attendee .search-result-list .ui-widget-content { border: none;}
@@ -409,4 +422,11 @@
 }
 
+.evt-list-options.my-evt-list-options{
+	position: absolute;
+	width: 110px;
+	display: block;
+	
+}
+
 
 .colors-options { padding-left: 5px; }
@@ -428,6 +448,43 @@
 }
 
+.user-list .hover-user { background-color: #DFEFFC;}
+
+.user-acls-shared-calendar{
+	width: 130px;
+	float: right;
+	margin-right: 20px;
+}
+
+.user-acls-shared-calendar.calendar{
+	text-align: right;
+}
+
+
+.calendars-list .search-field.calendar-shared-search {
+	max-width: 193px !important;
+	width: 193px !important;
+	float: right;
+}
+
+.calendars-list .search-field input.search{
+	width:165px !important;
+}
+
+.calendars-list .status-list-shared{
+	display: inline-block;
+	margin: 0 0 -4px -5px;
+	cursor: pointer;
+}
+
+.calendars-list .title-signed-calendars{
+	cursor: pointer;
+}
+
 .my-calendars a.new-calendar .ui-button-text {
     padding: 0;
+}
+
+.new-calendar-shared{
+	float: right;
 }
 
@@ -436,4 +493,96 @@
 	padding-top: 3px;
 	padding-bottom: 3px;
+}
+
+dl.block-add-user {
+	max-width: 290px;
+	min-height: 260px;
+	display: block;
+	float:right;
+	margin: 0 10px 10px 0;
+}
+
+dl.block-add-calendar {
+	max-width: 290px;
+	min-height: 185px;
+	display: block;
+	float:right;
+	margin: 0 10px 10px 0;
+}
+
+dl.block-public-calendar {
+	max-width: 290px;
+	min-height: 30px;
+	display: block;
+	float:right;
+	margin: 0 10px 1px 0;
+}
+
+fieldset.block-add-user, .block-add-user li{
+	border: none;
+}
+
+fieldset.add-user-search{
+	margin: 0 0 5px 0;
+}
+
+dl.block-user-list{
+	float:left;
+	margin: 0 0 10px 10px;
+}
+
+dt.user-list{
+	width: 117px;
+	margin-right: 5px;
+}
+
+dt.calendar-list{
+	width: 144px;
+	margin-right: 5px;
+}
+
+dt.calendar-shared, dt.user-list, dt.add-user, dt.calendar-list, dt.calendar-public{
+	background-color: white;
+	margin: 5px 0 -6px 5px;
+	font-weight: bold;
+	display: table;
+	position: relative;
+}
+
+dd.add-user{height: 240px;}
+dd.add-user-calendar{height: 192px;}
+
+dd.calendar-public{height: 23px;}
+
+dd.add-user-calendar, dd.calendar, dd.user-list, dd.add-user, dd.calendar-list, dd.calendar-public{
+	border: 1px solid #BFBFBF;
+	border-image: initial;
+	width: 330px;
+	padding: 7px 0px 4px 4px;
+}
+
+dd.add-user-calendar ul{
+	width: 250px;
+	max-height: 166px;
+}
+
+dd.add-user-calendar, dd.add-user,  dd.calendar-public{
+	width: 250px;
+}
+
+div.shared-calendar fieldset.shared-calendar-configure{
+	margin-top: 10px;
+}
+
+.add-user fieldset.block-add-user{
+	width: 245px;
+}
+
+dd.user-list{
+	height: 193px;
+}
+
+dd.calendar-list{
+	height: 240px;
 }
 
Index: /trunk/prototype/modules/calendar/css/style.css
===================================================================
--- /trunk/prototype/modules/calendar/css/style.css	(revision 5532)
+++ /trunk/prototype/modules/calendar/css/style.css	(revision 5592)
@@ -47,5 +47,5 @@
 
 .new-event-win fieldset { border: none;	margin: 0; padding: 0; }
-.new-event-win fieldset.tab-level2 { padding: 15px 5px; }
+.new-event-win fieldset.tab-level2 { padding: 0px 5px; }
 .new-event-win fieldset fieldset, .new-event-win fieldset.tab-level2 fieldset { padding: 5px 0; }
 
Index: /trunk/prototype/modules/calendar/js/calendar.contentMenu.js
===================================================================
--- /trunk/prototype/modules/calendar/js/calendar.contentMenu.js	(revision 5592)
+++ /trunk/prototype/modules/calendar/js/calendar.contentMenu.js	(revision 5592)
@@ -0,0 +1,55 @@
+function contentMenu(){
+	$('.fullcalendar-not-context-menu').bind('contextmenu', function(event){
+		event.preventDefault();
+	});
+	 
+	$('.fullcalendar-context-menu').bind('contextmenu', function(event){
+		event.preventDefault();
+		var classes = $(this).attr('class').split(" ");
+		var idCalendar = false;
+		var idEvent = false;
+		
+		//recupera o id do calendar eo id do evento para tratamento
+		for(var i = 0; i < classes.length; i++){
+			if(classes[i].indexOf("calendar-") >= 0 ){
+				idCalendar = classes[i].replace(/[a-zA-Z-]+/g, '');
+			}else if (classes[i].indexOf("event-id-") >= 0 ){
+				idEvent = classes[i].replace(/[a-zA-Z-]+/g, '');
+			}
+			if(idCalendar && idEvent)
+				break;
+		};
+		
+		var template = DataLayer.render( 'templates/menu_context_event.ejs', {event: idEvent,top: (event.clientY - 135), left: (event.clientX - 445), signature: Calendar.signatureOf[idCalendar], calendars: Calendar.calendars});
+		
+		$('#context-menu-event').html(template);
+		
+		$('#context-menu-event').find('li.menu-item').hover(
+			function () {
+				$(this).addClass("li-hover").find('a').addClass('ui-state-hover');
+				if($(this).hasClass('copy') || $(this).hasClass('move')) {
+					
+					$(this).parents().find('.calendar-copy-move input[name="typeEvent"]').val( ($(this).hasClass('copy') ? '0' : '1' ));
+					$(this).parents().find('.calendar-copy-move').show();
+				
+				}	
+			},
+			function () {
+				$(this).removeClass("li-hover").find('a').removeClass('ui-state-hover');
+				if(!$(this).hasClass('copy') && !$(this).hasClass('move') )
+					$(this).parents().find('.calendar-copy-move').hide()
+			}
+		);	
+		
+		$('#context-menu-event').find('li.calendar-list').hover(
+			function () {
+				$(this).addClass("li-hover").find('a').addClass('ui-state-hover');
+			},
+			function () {
+				$(this).removeClass("li-hover").find('a').removeClass('ui-state-hover');
+			}
+		);	
+	
+		event.preventDefault();
+	});
+}
Index: /trunk/prototype/modules/calendar/js/calendar.codecs.js
===================================================================
--- /trunk/prototype/modules/calendar/js/calendar.codecs.js	(revision 5530)
+++ /trunk/prototype/modules/calendar/js/calendar.codecs.js	(revision 5592)
@@ -39,9 +39,18 @@
 }
 
+constantsCalendarShared = {
+	'r' : 'read',
+	'w' : 'write',
+	'd' : 'remove',
+	'b' : 'busy',
+	's' : 'shared'
+}
+
 UI = {
 	dialogs: {
 		addEvent: null,
 		importCalendar: null,
-		sharedCalendar: null
+		sharedCalendar: null,
+		copyCalendar: null
 	}
 }
@@ -74,4 +83,59 @@
 });
 
+DataLayer.codec( "calendarToPermission", "detail", {
+	decoder: function( evtObj ){
+/*		Encoder.EncodeType = "entity";
+		
+		if( notArray = $.type(evtObj) !== "array" )
+			evtObj = [ evtObj ];
+		
+		var res = $.map(evtObj, function( form){
+			return [$.map(form.user , function( user, i){
+				return { 
+					calendar: form.calendar,
+					user: user,
+					acl: form.attendeeAcl[i],
+					type: 0
+				};
+			})];
+		});
+	
+	return notArray ? res[0] : res;
+	*/
+	},
+
+    encoder: function( evtObj ){
+	
+		if(evtObj == "")
+			return "";
+			
+		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
+			};
+		});	
+	return notArray ? res[0] : res;
+	}
+});
+
+
 Calendar = {
   
@@ -82,5 +146,5 @@
 		*  quando forçado um get do banco, deverá ser criado uma condição para o mesmo
 		*/
-		var descart = DataLayer.get("calendarSignature", {filter: ['=', 'user', User.me.id], criteria: {deepness: 2}})
+		var descart = DataLayer.get("calendarSignature", {filter: ['=', 'user', User.me.id], criteria: {deepness: 2}});
 		this.signatures  = DataLayer.get("calendarSignature", {filter: ['=', 'user', User.me.id], criteria: {deepness: 2}}, true);
 	  
@@ -104,4 +168,6 @@
 
 		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];
 		}
@@ -128,5 +194,5 @@
 Alarms = {
 	load: function(){
-		var eventsDay = DataLayer.get('alarm:schedulable',['=', 'date', new Date().toString("yyyy-MM-dd")]);
+		var eventsDay = DataLayer.get('alarm:schedulable',['=', 'date', Date.today().getTime()]);
 		for(var i = 0; i < eventsDay.length; i++){
 			this.addAlarm( eventsDay[i] );
@@ -197,6 +263,8 @@
     if( status === 'serverclient' ){
 		DataLayer.commit( false, false, function(){	
-			if(!!$('#calendar').fullCalendar)
+			if(!!$('#calendar').fullCalendar){
 				Calendar.rerenderView(true);
+				contentMenu();
+			}
 			//Atualiza a listagem de eventos apenas se estiver na aba de listagem
 			if((typeof($tabs) != "undefined") && $tabs.tabs('option' ,'selected') != 0)
@@ -334,5 +402,5 @@
 					sendTime: objEvent.sendTime,
 					schedulable: {
-						startTime: dateCalendar.formatDate(Timezone.setDateTimezone(new Date(time), objEvent.schedulable.timezone, true), User.preferences.hourFormat),
+						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,
@@ -363,6 +431,6 @@
 			return {
 				participant : meAttendee(form.attendee), 
-				startTime: Timezone.getDateUTC(Date.parseExact(form.startDate + (!!form.allDay ? " 00:00": " "+$.trim(form.startHour)) , formatString ), tzId).getTime(),
-				endTime:  parseInt(Timezone.getDateUTC(Date.parseExact(form.endDate + ( !!form.allDay ? " 00:00": " "+$.trim(form.endHour)), formatString ), tzId).getTime()) + (!!form.allDay ? 86400000 : 0) ,
+				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
@@ -450,6 +518,6 @@
 									participant: me.id,
 									type: 'suggestion',
-									startTime: Timezone.getDateUTC(Date.parseExact(form.startDate + (!!form.allDay ? " 00:00": " "+$.trim(form.startHour)) , formatString ), tzId).getTime(),
-									endTime:  parseInt(Timezone.getDateUTC(Date.parseExact(form.endDate + ( !!form.allDay ? " 00:00": " "+$.trim(form.endHour)), formatString ), tzId).getTime()) + (!!form.allDay ? 86400000 : 0) ,
+									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
@@ -484,4 +552,7 @@
 	var res = $.map(evtObj, function( objEvent ){			
 		    
+			if(!(typeof(objEvent) == 'object'))
+				return (null);
+			
 			var participantInfo = {}, delegatedFrom = {}, me = DataLayer.copy(User.me);
 			
@@ -506,7 +577,7 @@
 			    timezones: Timezone.timezones,
 			    startDate: new Date( parseInt(objEvent.startTime) ).setTimezoneOffset( Timezone.timezone( objEvent.timezone ) ).toString( User.preferences.dateFormat ),
-			    startHour: dateCalendar.formatDate(Timezone.setDateTimezone(new Date( parseInt(objEvent.startTime)), objEvent.timezone, objEvent.calendar), User.preferences.hourFormat),
+			    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.setDateTimezone(new Date(parseInt(objEvent.endTime)), objEvent.timezone, objEvent.calendar), User.preferences.hourFormat),
+			    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 ){
@@ -566,6 +637,7 @@
 			    alarms: !!participantInfo.user ? participantInfo.user.alarms : [],
 			    status: !!participantInfo.user ? participantInfo.user.status : 1,
-				acl: !!participantInfo.user ? constantAcl(participantInfo.user.acl) : constantAcl('rowi'),
-			    me: !!participantInfo.user ? DataLayer.merge(participantInfo.user, me) : DataLayer.merge(me, {acl: 'rowi', delegatedFrom: 0, receiveNotification: 1}),
+				acl: !!participantInfo.user ? constantAcl(participantInfo.user.acl) : constantAcl( 'rowi' ),
+				isShared: objEvent.calendar && Calendar.signatureOf[objEvent.calendar].isOwner ? true : false,
+			    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,
 				statusParticipants: statusParticipants
@@ -598,6 +670,6 @@
 		    return {
 			      "class": form["class"],
-				  startTime: Timezone.getDateUTC(Date.parseExact(form.startDate + (!!form.allDay ? " 00:00": " "+$.trim(form.startHour)) , formatString ), tzId).getTime(),
-				  endTime:  parseInt(Timezone.getDateUTC(Date.parseExact(form.endDate + ( !!form.allDay ? " 00:00": " "+$.trim(form.endHour)), formatString ), tzId).getTime()) + (!!form.allDay ? 86400000 : 0) ,
+				  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,
@@ -837,4 +909,7 @@
 
 	$.map(filtered, function( evt ){
+		
+		if(!(typeof(evt) == 'object') || (evt.id.indexOf('java') >= 0))
+			return (null);
 
 		evt.calendar = evt.calendar || "1";
@@ -845,18 +920,39 @@
 		var calendar = DataLayer.get('calendar', evt.calendar);
 		
-		var eventEditable = function(){
-			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 ) ? true : false;
+		var eventEditable = function(idEvent){
+			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} : {editable: false, 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};
 			}
+			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 ' : '');
+					returns += 'event-id-'+idEvent;
+					return returns;
+				}				
+				return DataLayer.merge({
+					editable: aclSignature.acl['write'],
+					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});
+			}
+			
 		}
 		  
 		grouped[ evt.calendar ].push( DataLayer.merge({ id: evt.URI || evt.id,
 						title: Encoder.htmlDecode(evt.summary),
-						start: Timezone.getDateTimezone(new Date(parseInt( evt.startTime )), calendar.timezone, false),
-						end:   Timezone.getDateTimezone(new Date(parseInt( evt.endTime ) - (!!parseInt(evt.allDay) ? 86400000 : 0)), calendar.timezone, false ),
-						allDay: parseInt( evt.allDay ) }, eventEditable() ? {} : {editable: false, className: 'blocked-event-permision'}) );
+						start: Timezone.getDateCalendar(new Date(parseInt( evt.startTime )), calendar.timezone,  !!evt.DayLigth ? evt.DayLigth.calendar.startTime : Timezone.daylightSaving),
+						end:   Timezone.getDateCalendar(new Date(parseInt( evt.endTime ) - (!!parseInt(evt.allDay) ? 86400000 : 0)), calendar.timezone, !!evt.DayLigth ? evt.DayLigth.calendar.startTime : Timezone.daylightSaving),
+						allDay: parseInt( evt.allDay ) }, eventEditable(evt.id) ) );
 	});
 
@@ -871,12 +967,16 @@
 			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.toString( "dd-MM-yyyy" ) ],
-					[ "<=", "rangeEnd", filter.end.toString( "dd-MM-yyyy" ) ],
+					[ ">=", "rangeStart", filter.start.getTime() ],
+					[ "<=", "rangeEnd", filter.end.getTime() ],
 					[ "IN", "calendar", Calendar.calendarIds ]
 
 				  ], 
-		 criteria: { deepness: 2 } }
+		 criteria: { deepness: 2, timezones: timezone } }
     }
 });
Index: /trunk/prototype/modules/calendar/js/timezone.js
===================================================================
--- /trunk/prototype/modules/calendar/js/timezone.js	(revision 5550)
+++ /trunk/prototype/modules/calendar/js/timezone.js	(revision 5592)
@@ -6,7 +6,8 @@
 
 var objTime = DataLayer.dispatch( "timezones" );
+
 Timezone = {
-  
-	daylightSaving:  isNaN(objTime.isDaylightSaving) ? parseInt( objTime.isDaylightSaving ) : 0,
+	currentOffset : new Date().getUTCOffset(),
+	daylightSaving: isNaN(parseInt( objTime.isDaylightSaving )) ? 0 : parseInt( objTime.isDaylightSaving ),
 
 	timezones: objTime.timezones,	  
@@ -16,40 +17,6 @@
 
 	},
-
-	compareTZID: function( fromTZID, toTZID ){
-
-		return( this.timezones[ fromTZID ] === this.timezones[ toTZID ] );
-
-	},
-
-	checkTimezoneCalendar: function(idCalendar, tzId){
-
-		return idCalendar && this.compareTZID( DataLayer.get('calendar', idCalendar).timezone, tzId );
-
-	},
 	
-	setDateTimezone: function (date, tzId, idCalendar){
-	
-		if( !!!tzId || this.checkTimezoneCalendar(idCalendar, tzId) )
-			return date;
-
-		var timezone = this.timezone( tzId );
-
-		var timezoneOffset = parseInt(timezone.substr(2)) - this.daylightSaving * 100;
-
-		var timeCurrent = parseInt((date.getTimezoneOffset()/60)+'00') * ( ( timezone.charAt(0) != date.getUTCOffset().charAt(0) )? 1 : -1 );
-
-		var times = timezoneOffset + timeCurrent;
-
-		if(times == 0)
-			return date;		
-		else if(times > 0)
-			return date.setTimezoneOffset('-0'+(times));
-		else
-			return date.setTimezoneOffset('+0'+((times * -1)));
-	},
-
-	getDateTimezone: function(date, tzId, recursive){
-
+	getDateCalendar: function(date, tzId, isDay){
 		var timezone = this.timezone( tzId );
 
@@ -57,47 +24,30 @@
 			return date;
 
-		var currentTimezone = parseInt((date.getTimezoneOffset()/60)+'00');
+	 	date = this.normalizeDate(date, false, true);
 
-		var timezoneOffset = parseInt(timezone.substr(2)) - this.daylightSaving * 100;
-
-		var times =  timezoneOffset - currentTimezone;
-
-		if(times == 0){
-			if((timezone.charAt(0) == date.getUTCOffset().charAt(0)) && recursive)
-				return date.setTimezoneOffset( timezone.charAt(0)+'0'+(currentTimezone));
-
-			return  date;
-		}else if (times > 0)
-			return date.setTimezoneOffset('+0'+(times));
-		else{
-			return date.setTimezoneOffset('-0'+((times * -1) + (currentTimezone * 2)));
-		}
+		return date.add({hours: parseInt(timezone.charAt(0) + timezone.charAt(2))  +  parseInt(isDay) });
 	},
 	
-	getDateUTC: function (date, tzId){
+	getDateEvent: function(date, tzId, idCalendar, isDay, type){
+		var timezone = this.timezone( tzId );
+		var timezoneCurrent = this.timezone(DataLayer.get('calendar', idCalendar).timezone);
 
-			var timezone = this.timezone( tzId ), currentTimezone = parseInt(timezone.substr(2)) - this.daylightSaving * 100;
-			return(date.setTimezoneOffset(timezone.charAt(0)+'0'+currentTimezone));
+		if(timezone == timezoneCurrent)
+			return date;
+		
+		var to = parseInt(timezone.charAt(0) + timezone.charAt(2)) + parseInt(isDay.event[type]);
+		var current = parseInt(timezoneCurrent.charAt(0) + timezoneCurrent.charAt(2)) + parseInt(isDay.calendar[type]);
+		
+		if(timezone.charAt(0) == timezoneCurrent.charAt(0))
+			hours =   (  to + (current * - 1)) ;
+		else
+			hours =  to + (( current ) * (timezone.charAt(0) ==  '+'  ? -1 : 1)) ;
+		
+		return date.add({hours: hours});
 	},
-
-	createDateTimezone: function(date, tzId, idCalendar){			
-		if(this.checkTimezoneCalendar(idCalendar, tzId))
-			return this.getDateTimezone(date, tzId, true);
-
-		var times = 0, timezone = this.timezone( tzId );
-		
-		if(timezone.charAt(0) == '+')
-			times = parseInt(timezone.substr(2)) - parseInt((date.getTimezoneOffset()/60)+'00');
-		else
-			times = (parseInt(timezone.substr(2)) + parseInt((date.getTimezoneOffset()/60)+'00')) * (-1);
-		if(times == 0)
-			return date.setTimezoneOffset('0000');
-		else if (times > 0)
-			return date.setTimezoneOffset('+0'+times);
-		else
-			return date.setTimezoneOffset('-0'+(times * -1));
+	
+	normalizeDate: function(date, current, inverse){
+		var offsetDate = !!current ? this.currentOffset : date.getUTCOffset();
+		return date.add({hours: (parseInt(offsetDate.charAt(0) + offsetDate.charAt(2)) * (!!inverse ? -1 : 1) )});
 	}
-
-
-
 }
Index: /trunk/prototype/modules/calendar/js/calendar.shared.js
===================================================================
--- /trunk/prototype/modules/calendar/js/calendar.shared.js	(revision 5592)
+++ /trunk/prototype/modules/calendar/js/calendar.shared.js	(revision 5592)
@@ -0,0 +1,449 @@
+function show_modal_shared(calendarId){
+	var html = DataLayer.render('templates/shared_calendar.ejs', {calendar: Calendar.calendars});	
+	
+	//Variaval global para manipulação dos usuários
+	//melhor perforface
+	currentUsers = [];
+	currentUsers[User.me.id] = true;
+	changePublic = false;
+	
+	if (!UI.dialogs.sharedCalendar) {
+			UI.dialogs.sharedCalendar = jQuery('#calendarShared').append('<div title="Compatilhamento de Agenda" class="shared-calendar active"> <div>').find('.shared-calendar.active').html(html).dialog({
+				resizable: false, 
+				modal:true, 
+				autoOpen: false,
+				width:620, 
+				position: 'center', 
+				close: function(event, ui) {
+					//Implementações de cancelar
+					currentUsers = [];
+				}
+			});
+		} else {
+			UI.dialogs.sharedCalendar.html(html);
+		}
+		
+		/*Seleciona a agenda selecionada para compartilhamento*/
+		UI.dialogs.sharedCalendar.find('option[value="'+calendarId+'"]').attr('selected','selected').trigger('change');
+		
+		UI.dialogs.sharedCalendar.find('input[name="isPublic"]').change(function(event){
+			$(this).parent().find('.free-busy').toggleClass('hidden');
+			changePublic = changePublic ? false: true;
+		});
+		
+		UI.dialogs.sharedCalendar.find('.button').button()
+		.filter('.cancel').click(function(evt){
+			UI.dialogs.sharedCalendar.dialog("close");
+		}).end()
+		.filter('.save').click(function(evt){
+			//TODO - API ainda não suporta
+			//UI.dialogs.sharedCalendar.find('form').submit();
+			var calendarSelected = UI.dialogs.sharedCalendar.find('option:selected').val();
+			var save = function(){
+				if($('li.not-user').length == 0)
+				$.each(UI.dialogs.sharedCalendar.find('.user-list li'), function( i , element ){
+					var user = $(element).find('input[name="user[]"]').val();
+					var acl = $(element).find('input[name="attendeeAcl[]"]').val();
+					if(acl == "")
+						return true;
+					DataLayer.put('calendarToPermission', {calendar: calendarSelected, type: 0, user: user, acl: acl});
+				});
+				DataLayer.commit(false, false, function(data){
+					UI.dialogs.sharedCalendar.dialog("close");
+				});
+			};
+
+			//Trata a criação de um acesso público a agenda
+			if(changePublic){
+				if(UI.dialogs.sharedCalendar.find('input[name="isPublic"]').is(':checked')){
+					var acl = UI.dialogs.sharedCalendar.find('input[name="busy"]').is(':checked') ? 'b' : 'w';
+					DataLayer.put('calendarToPermission', {calendar: calendarSelected, type: '1', user: '0', acl: acl});
+				}else{
+					//TODO - remover quando for implementado remove com criteria
+					var permission = DataLayer.get('calendarPermission', {filter: [AND, ['=', 'calendar', calendarId], ['=', 'user', '0']]}, true);
+					DataLayer.remove('calendarToPermission', permission.id);
+				}
+			}
+			if(!!UI.dialogs.sharedCalendar.find('.user-list li input[name="attendeeAcl[]"][value=""]').length){
+				$.Zebra_Dialog('Alguns usuários estão sem permissões e serão automáticamente removidos, deseja continuar ?', {
+					'type':     'question',
+					'overlay_opacity': '0.5',
+					'buttons':  ['Continuar', 'Cancelar'],
+					'onClose':  function(clicked) {
+						if(clicked == 'Continuar') {
+							save();
+						}
+					}
+				});
+			}else
+				save();		
+		});
+		
+		UI.dialogs.sharedCalendar.find('.add-user-search .ui-icon-search').click(function(event) {
+			UI.dialogs.sharedCalendar.find('.add-user-search input').keydown();
+		});
+		
+		var incompatibleAcl = function (obj, acls, buttons){
+			for (var i = 0; i < acls.length; i++){
+				var objremove = obj.parent().find('.'+buttons[i]+'');
+				if(objremove.hasClass('attendee-permissions-change-button'))
+					changeAcl(objremove, acls[i]);
+			}
+		}
+
+		var removeAcl = function(current, acl){
+			var acls = '';
+			for(var i = 0; i < current.length; i++)
+				if(current.charAt(i) != acl)
+					acls += current.charAt(i) ;
+			return acls;
+		}
+
+		var dependsAcl = function(obj, acls, buttons){
+			for (var i = 0; i < acls.length; i++){
+				var objremove = obj.parent().find('.'+buttons[i]+'');
+				if(!objremove.hasClass('attendee-permissions-change-button'))
+					changeAcl(objremove, acls[i]);
+			}
+		}
+		
+		var changeAcl = function(obj, acl){
+			if(obj.hasClass('attendee-permissions-change-button')){
+				 obj.parent().siblings('input[name="attendeeAcl[]"]').val(removeAcl( obj.parent().siblings('input[name="attendeeAcl[]"]').val(), acl)) ; 
+			}else{
+				var acls = obj.parent().siblings('input[name="attendeeAcl[]"]').val();
+				obj.parent().siblings('input[name="attendeeAcl[]"]').val(acls + acl);
+			}
+			obj.toggleClass('attendee-permissions-change-button')
+			.find('span:first').toggleClass('attendee-permissions-change').end();  
+		}
+		
+		
+		UI.dialogs.sharedCalendar.find('.add-user-search input').keydown(function(event) {
+			if(event.keyCode == '13' || typeof(event.keyCode) == 'undefined') {						
+				var result = DataLayer.get('user', ["*", "name", $(this).val()], true);
+				/**
+				* TODO: trocar por template
+				*/
+				UI.dialogs.sharedCalendar.find('ul.search-result-list').empty().css('overflow', 'hidden');
+				if (!result) {
+					UI.dialogs.sharedCalendar.find('ul.search-result-list').append('<li><label class="empty">Nenhum resultado encontrado.</label></li>');
+				}
+
+				for(i=0; i<result.length; i++)
+					result[i].enabled = currentUsers[result[i].id] ? false : true;
+
+				UI.dialogs.sharedCalendar.find('ul.search-result-list').append(DataLayer.render( 'templates/participants_search_itemlist.ejs', result));
+
+				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();
+						
+						currentUsers [id] = {
+							id: id,
+							name: old_item.find('.name').html(),
+							mail: old_item.find('.mail').html()
+						};
+											
+						UI.dialogs.sharedCalendar.find('dd.user-list ul.user-list')
+						.append(DataLayer.render('templates/user_shared_add_itemlist.ejs', [{id: id, name: currentUsers [id] .name, mail: currentUsers [id] .mail}]))
+						.scrollTo('max');
+						
+						$('li.not-user').remove();
+						callbackSharedCotactsAdd();
+						old_item.remove();
+					}
+				});
+				event.preventDefault();
+			}
+		});
+
+		var callbackSharedCotactsAdd = function(event){
+			UI.dialogs.sharedCalendar.find('.button').filter(".read.new").button({
+				icons: {
+					primary: "ui-icon-circle-zoomin"
+				},
+				text: false
+			}).click(function () {
+				incompatibleAcl($(this), ['b'], ['busy']);
+				changeAcl($(this), 'r');
+			})
+			.addClass('tiny disable ui-button-disabled ui-state-disabled')
+			.removeClass('new').end()
+			
+			.filter(".write.new").button({
+				icons: {
+					primary: "ui-icon-key"
+				},
+				text: false
+			}).click(function () {
+				incompatibleAcl($(this), ['b'], ['busy']);
+				dependsAcl($(this), ['r'], ['read']);
+				changeAcl($(this), 'w');
+			})
+			.addClass('tiny disable ui-button-disabled ui-state-disabled')
+			.removeClass('new').end()
+			
+			.filter(".remove.new").button({
+				icons: {
+					primary: "ui-icon-trash"
+				},
+				text: false
+			}).click(function () {
+				incompatibleAcl($(this), ['b'], ['busy']);
+				dependsAcl($(this), ['r'], ['read']);
+				changeAcl($(this), 'd');
+			})
+			.addClass('tiny disable ui-button-disabled ui-state-disabled')
+			.removeClass('new').end()
+			
+			.filter(".busy.new").button({
+				icons: {
+					primary: "ui-icon-clock"
+				},
+				text: false
+			}).click(function () {
+				//Remove incompativbilidade de acls
+				incompatibleAcl($(this), ['r', 'w', 'd', 's' ], ['read', 'write', 'remove', 'shared']);
+				changeAcl($(this), 'b');
+			})
+			.addClass('tiny disable ui-button-disabled ui-state-disabled')
+			.removeClass('new').end()
+			
+			.filter(".shared.new").button({
+				icons: {
+					primary: "ui-icon-transferthick-e-w"
+				},
+				text: false
+			}).click(function () {
+				incompatibleAcl($(this), ['b',], ['busy']);
+				dependsAcl($(this), ['r'], ['read']);
+				changeAcl($(this), 's');
+			})
+			.addClass('tiny disable ui-button-disabled ui-state-disabled')
+			.removeClass('new').end()
+
+			.filter(".close.new").button({
+				icons: {
+					primary: "ui-icon-close"
+				},
+				text: false
+			}).click(function () {
+				currentUsers[$(this).parents().find('input[name="user[]"]').val()] = false;
+				$(this).parents('li').remove();
+			})
+			.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
+	var dataCurrent = DataLayer.get('calendarToPermission:detail', {filter: ['=','calendar', calendarId]  , criteria: {deepness: 2}}, true);
+	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="isPublic"]').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}]))
+						.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');
+}
+
+function show_modal_search_shared(){
+
+	var html = DataLayer.render('templates/shared_calendar.ejs', {});	
+	
+	//Variaval global para manipulação dos usuários
+	//melhor perforface
+	currentCalendars = [];
+	
+	if (!UI.dialogs.sharedCalendar) {
+			UI.dialogs.sharedCalendar = jQuery('#calendarShared').append('<div title="Pesquisar Agendas" class="shared-calendar active"> <div>').find('.shared-calendar.active').html(html).dialog({
+				resizable: false, 
+				modal:true, 
+				autoOpen: false,
+				width:620, 
+				position: 'center', 
+				close: function(event, ui) {
+					//Implementações de cancelar :D
+					currentCalendars = [];
+					$('.signed-calendars').find('.calendar-shared-search input').val('').Watermark('Pesquisar agendas...');
+				}
+			});
+		} else {
+			UI.dialogs.sharedCalendar.html(html);
+		}
+	
+		UI.dialogs.sharedCalendar.find('.button').button()
+		.filter('.cancel').click(function(evt){
+			UI.dialogs.sharedCalendar.dialog("close");
+		}).end()
+		.filter('.save').click(function(evt){
+				$.each(UI.dialogs.sharedCalendar.find('.user-list li'), function( i , element ){
+					var idPermission = $(element).find('input[name="idpermission[]"]').val();
+					var calendarId = $(element).find('input[name="calendar[]"]').val();
+					var type = parseInt($(element).find('input[name="type[]"]').val());
+					DataLayer.put('calendarSignature', DataLayer.merge({calendar: calendarId, isOwner: 0, user: User.me.id, fontColor: '120d0d', backgroundColor: (!!type ? 'fbec88' : '8c8c8c'), borderColor: (!!type ? 'fad24e' : '120d0d')}, !!idPermission ? {id: idPermission} : {} ));
+				});
+				
+			UI.dialogs.sharedCalendar.dialog("close");
+		
+		});
+		
+		UI.dialogs.sharedCalendar.find('.add-user-search .ui-icon-search').click(function(event) {
+			UI.dialogs.sharedCalendar.find('.add-user-search input').keydown();
+		});
+	
+		UI.dialogs.sharedCalendar.find('.add-user-search input').keydown(function(event) {
+			if(event.keyCode == '13' || typeof(event.keyCode) == 'undefined') {						
+				var result = DataLayer.get('calendarToPermission', {filter: ['AND', ['=','user',User.me.id],   ['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++){
+						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/participants_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');
+						
+						$('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 () {
+				currentCalendars[$(this).parents().find('input[name="calendar[]"]').val()] = false;
+				$(this).parents('li').remove();
+			})
+			.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};
+			
+			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');
+}
+
+function cancel_signature(signatureId){
+	$.Zebra_Dialog('Confirma a remoção desta assinatura ?', {
+		'type':     'question',
+		'overlay_opacity': '0.5',
+		'buttons':  ['Sim', 'Não'],
+		'onClose':  function(clicked) {
+			if(clicked == 'Sim'){
+				DataLayer.remove('calendarSignature', ''+signatureId);
+				DataLayer.commit();
+			}
+		}
+	});
+}
Index: /trunk/prototype/modules/calendar/js/helpers.js
===================================================================
--- /trunk/prototype/modules/calendar/js/helpers.js	(revision 5530)
+++ /trunk/prototype/modules/calendar/js/helpers.js	(revision 5592)
@@ -59,5 +59,5 @@
 */
 
-function eventDetails( objEvent, decoded, path)
+function eventDetails( objEvent, decoded, path, isMail)
 {
 	if(path == undefined)
@@ -67,4 +67,5 @@
 	    objEvent = DataLayer.decode( "schedulable:calendar", objEvent );
 
+	if(!isMail)
 	objEvent = DataLayer.encode( "schedulable:preview", objEvent );
 	
@@ -730,7 +731,9 @@
 					if (user){
 						if (!skipAddNewLine) {
-							user[0].id =  DataLayer.put('participant', {user: user[0].id, isExternal: isExternal});
+							user[0].id =  DataLayer.put('participant', {user: user[0].id, isExternal: isExternal, acl: 'r'});
+							user[0].acl = objEvent.acl
+
 							blkAddAtendee.find('dd.attendee-list ul.attendee-list').append(
-								DataLayer.render(path+'templates/participants_add_itemlist.ejs', {user:user, acl: objEvent.acl})
+								DataLayer.render(path+'templates/participants_add_itemlist.ejs', user)
 							)
 							.scrollTo('max');
@@ -794,7 +797,12 @@
 			* Trata a busca de usuários para adição de participantes
 			*/
+			blkAddAtendee.find('.add-attendee-search .ui-icon-search').click(function(event) {
+				blkAddAtendee.find('.add-attendee-search input').keydown();
+			});
+			
+			
 			blkAddAtendee.find('.add-attendee-search input').keydown(function(event) {
 
-				if(event.keyCode == '13') {			
+				if(event.keyCode == '13' || typeof(event.keyCode) == 'undefined') {			
 					var result = DataLayer.get('user', ["*", "name", $(this).val()], true);
 
@@ -899,5 +907,5 @@
 		sequentialUploads: true,
 		add: function (e, data) {
-			if(data.files[0].size < 30000000)
+			if(data.files[0].size < 2000000)
 				data.submit();
 		},
@@ -909,10 +917,10 @@
 					attach.fileName = file.name.substr(0, 6) + file.name.substr(file.name.length-4, file.name.length);
 				attach.fileSize = formatBytes(file.size);
-				if(file.size > 30000000)
+				if(file.size > 2000000)
 					attach.error = 'Tamanho de arquivo nao permitido!!'
 				
 				$('.attachments-list').append(DataLayer.render(path+'templates/attachment_add_itemlist.ejs', {file : attach}));
 				
-				if(file.size < 30000000){
+				if(file.size < 2000000){
 					$('.fileinput-button.new').append(data.fileInput[0]).removeClass('new');
 					$('.attachments-list').find('[type=file]').addClass('hidden');
@@ -1034,7 +1042,24 @@
 			canDiscardEventDialog = false;
 	});	
-		
-		
-		UI.dialogs.addEvent.dialog('open');
+	
+	if(objEvent.isShared){
+		
+		var acls = Calendar.signatureOf[objEvent.calendar].permission.acl;
+		
+		if(!acls.write){
+			UI.dialogs.addEvent.find(':input').attr('disabled', 'disabled');
+			UI.dialogs.addEvent.find('.button').hide();
+		}
+		
+		if(acls.remove)
+			UI.dialogs.addEvent.find('.button.remove').show();
+		
+		UI.dialogs.addEvent.find('.button.cancel').show();
+		
+	
+	}
+	
+		
+	UI.dialogs.addEvent.dialog('open');
 }
 
@@ -1368,4 +1393,19 @@
 }
 
+function remove_event(eventId){
+	$.Zebra_Dialog('Tem certeza que deseja excluir o evento?', {
+		'type':     'question',
+		'overlay_opacity': '0.5',
+		'buttons':  ['Sim', 'Não'],
+		'onClose':  function(clicked) {
+			if(clicked == 'Sim'){
+				DataLayer.remove('schedulable', ''+eventId);
+				window.setTimeout(function() {DataLayer.commit();}, 500);
+			}
+		}
+	});	
+}
+
+
 function remove_calendar(){
 	/* Pode ser assim $('.cal-list-options-btn.ui-state-active').attr('class').replace(/[a-zA-Z-]+/g, ''); */
@@ -1377,12 +1417,7 @@
 			if(clicked == 'Sim'){
 				var idCalendar =  $('.cal-list-options-btn.ui-state-active').attr('class').match(/[0-9]+/g);
-				var signature = '';
-				for(var i =0; i < Calendar.signatures.length; i++){
-					if(idCalendar[0] == Calendar.signatures[i].calendar.id){
-						signature = Calendar.signatures[i].id;
-						break;
-					}
-				}
-				DataLayer.remove('calendarSignature', signature);
+				
+				DataLayer.remove('calendarSignature', Calendar.signatureOf[idCalendar[0]].id );
+				
 				if(idCalendar == User.preferences.defaultCalendar)
 					DataLayer.remove( 'modulePreference', User.preferenceIds['defaultCalendar']);
@@ -1428,6 +1463,5 @@
  	});         
 	
-	
-	meu_container.find(".button.new").button({
+	meu_container.find(".button.new-calendar").button({
 		icons: {
             primary: "ui-icon-plus"
@@ -1462,5 +1496,5 @@
 			})
 			.click(function(){
-				meu_container.find(".button.new").qtip('destroy');
+				meu_container.find(".button.new-calendar").qtip('destroy');
 			});
 			//TODO emplementar tratamento de duplicação de valores no location
@@ -1543,4 +1577,24 @@
 	    });   
         
+		meu_container.find(".button.new-calendar-shared").button({
+		icons: {
+            primary: "ui-icon-plus"
+        },
+        text: false
+		}).click(function (event) {
+			show_modal_search_shared();
+		});
+		
+		
+		//TODO Implementar ocultar agendas.
+		meu_container.find('.title-signed-calendars').click(function(evt){
+			var status = $(this).parent().find('.status-list-shared');
+			
+			if(status.hasClass('ui-icon-triangle-1-s'))
+				status.removeClass('ui-icon-triangle-1-s').addClass('ui-icon-triangle-1-e');
+			else
+				status.removeClass('ui-icon-triangle-1-e').addClass('ui-icon-triangle-1-s');
+		});
+		
 	    $('.calendar-view').click(function(evt){
 			if($tabs.tabs('option' ,'selected') == 1){
@@ -1715,5 +1769,5 @@
 		case 'basicDay':
 		case 'day':
-                        rangeStart = new Date().add({days: page_index}).toString("yyyy-MM-dd");
+                        rangeStart = new Date().add({days: page_index}).getTime();
                         rangeEnd = rangeStart;
                          break;
@@ -1722,11 +1776,11 @@
 			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)}).toString("yyyy-MM-dd");
-                        rangeEnd = dateEnd.add({days: (7 * page_index)+7}).toString("yyyy-MM-dd");
+                        rangeStart = dateStart.add({days: (7 * page_index)}).getTime();
+                        rangeEnd = dateEnd.add({days: (7 * page_index)+7}).getTime();
                         break;
 		case 'month':
-			var date = new Date().add({months: page_index}) 
-                        rangeStart = date.moveToFirstDayOfMonth().toString("yyyy-MM-dd");
-                        rangeEnd = date.moveToLastDayOfMonth().toString("yyyy-MM-dd");
+			var date = Date.today().add({months: page_index}) 
+                        rangeStart = date.moveToFirstDayOfMonth().getTime();
+                        rangeEnd = date.moveToLastDayOfMonth().getTime();
                          break;
 		case 'year':
@@ -1737,6 +1791,6 @@
 			if(dateEnd.getMonth() != 11)
 				dateEnd.moveToMonth(11)	
-                         rangeStart =    dateStart.moveToFirstDayOfMonth().toString("yyyy-MM-dd");
-                         rangeEnd = dateEnd.moveToLastDayOfMonth().toString("yyyy-MM-dd");
+                         rangeStart =    dateStart.moveToFirstDayOfMonth().getTime();
+                         rangeEnd = dateEnd.moveToLastDayOfMonth().getTime();
                            break;  
 			}
@@ -1872,2 +1926,58 @@
     });
 }
+
+function copyAndMoveTo(calendar, eventId){
+
+    var type = $('.calendar-copy-move input[name="typeEvent"]').val();
+
+	var schedulable = DataLayer.get('schedulable' , ''+eventId);
+	
+	if(typeof(schedulable) == "array")
+		schedulable = schedulable[0];
+	
+	//Move eventos entre agendas
+	if(!!parseInt(type)){
+		
+		schedulable.calendar = calendar;	
+		DataLayer.put('schedulable', schedulable);
+	
+		DataLayer.commit();
+	//copia eventos entre agendas
+	}else{
+	
+		var newSchedulable = schedulable;
+	
+		delete newSchedulable.id;
+		delete newSchedulable.uid;
+		delete newSchedulable.sequence;
+		delete newSchedulable.dtstamp;
+		delete schedulable.calendar;
+		
+		schedulable.calendar = calendar;	
+	
+		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'); 
+		
+		var participants = DataLayer.copy(schedulable.participants);
+		delete schedulable.participants;
+		
+		schedulable.participants =  $.map( participants, function( attendee, i ){
+			
+			var participant = DataLayer.get('participant', attendee);
+			
+			if(typeof(participant) == 'array')
+				participant = participant[0];
+	
+			delete participant.id;
+			
+			return participant ;
+        });
+	
+	
+	
+		DataLayer.put('schedulable', newSchedulable);
+
+	}
+	
+
+}
Index: /trunk/prototype/modules/calendar/js/init.js
===================================================================
--- /trunk/prototype/modules/calendar/js/init.js	(revision 5510)
+++ /trunk/prototype/modules/calendar/js/init.js	(revision 5592)
@@ -97,5 +97,11 @@
 		}
 	});
-				
+	
+	//efetua pesquisas pelo click na lupa de pesquisa
+	$('.main-search span.ui-icon-search').click(function(event){
+			add_events_list($(this).parent().find('input.search').val());
+			$(this).parent().find('input.search').val();
+	});
+	
 	$('.block-horizontal-toolbox .main-config-menu').menu({
 		content: $('.main-config-menu-content').html(),
@@ -226,4 +232,16 @@
 
 		eventDrop: function( event ){
+			if(!event.disableDragging){
+				DataLayer.put( "schedulable:calendar", event );
+
+				event.editable = false;
+				event.className = "blocked-event";
+				calendar.fullCalendar( 'updateEvent', event );
+			}else
+				Calendar.rerenderView(true);
+		},
+
+		eventResize: function( event ){
+			if(!event.disableDragging){
 			DataLayer.put( "schedulable:calendar", event );
 
@@ -231,19 +249,20 @@
 			event.className = "blocked-event";
 			calendar.fullCalendar( 'updateEvent', event );
-		},
-
-		eventResize: function( event ){
-			DataLayer.put( "schedulable:calendar", event );
-
-			event.editable = false;
-			event.className = "blocked-event";
-			calendar.fullCalendar( 'updateEvent', event );
+			}else
+				Calendar.rerenderView(true);
 		},
 
 		eventClick: function( evt, event, view ){
-			eventDetails( DataLayer.get( "schedulable", evt.id), true);
+			if(evt.selectable)
+				eventDetails( DataLayer.get( "schedulable", evt.id), true);
 		}
 	}, dateCalendar));
-	  
+ 
+	contentMenu();
+	 
+	 $('body').click(function(){
+		$('#context-menu-event').html('');
+	 });
+	 
 	if($(window).height() < $('body').height()){
 		var hei = $('body').height() - $(window).height();
Index: /trunk/prototype/modules/calendar/templates/shared_calendar.ejs
===================================================================
--- /trunk/prototype/modules/calendar/templates/shared_calendar.ejs	(revision 5592)
+++ /trunk/prototype/modules/calendar/templates/shared_calendar.ejs	(revision 5592)
@@ -0,0 +1,72 @@
+<fieldset class="shared-calendar-configure">
+	<form method="POST" action="calendarToPermission:detail" class="form-addevent content">
+	<fieldset>
+		<dl class="block-user-list users-list">
+			<%if(data.calendar){%>
+				<dt class="calendar-shared">Calendario selecionado</dt>
+				<dd class="calendar">
+					<select class="calendar" name="calendar">
+							<%for(var i = 0; i < data.calendar.length; i++){%>
+								<option value="<%=data.calendar[i].id%>"><%=data.calendar[i].name%></option>
+							<%}%>
+					</select>
+					</dd>
+			<%}%>
+			<dt class="<%=data.calendar ? "user-list" : "calendar-list"%>"><%=data.calendar ? 'Compartilhar com' : 'Agendas Selecionadas'%></dt>
+			<dd class="<%=data.calendar ? "user-list" : "calendar-list"%>">
+				<ul class="user-list">
+				<% if (false) {
+					for (var i=0; i< data.event.user.length; i++) {%>
+						<li class="user"> 
+							<div style="overflow:hidden; width:100%; display:table;">
+								<input type="checkbox" value="">
+								<input type="hidden" name="user[]" value="">
+								<label class="name"></label>
+								<label class="mail"></label>
+							</div> 
+							<div class="shared-acl">
+									<a class="button edit user-options-button-edit new">Editar permissões</a>
+									<a class="button close new">Remover</a>
+							</div>
+						</li>	
+					<%} 
+				} else { %>
+					<li class="not-user"><%=data.calendar ? "Não compartilhado." : "Nenhuma agenda selecionada"%></li>
+				<% } %>
+				</ul>
+			</dd>	
+		</dl>
+
+		<%if(data.calendar){%>
+			<dl class="block-public-calendar">
+				<dt class="calendar-public">Agenda pública</dt>
+				<dd class="calendar-public">
+						<ul>
+							<input type="checkbox" name="isPublic"/><label>Pública</label>
+							<input type="checkbox" name="busy" class="free-busy hidden"/><label class="free-busy hidden">Livre/Ocupado</label>
+						</ul>
+				</dd>
+			</dl>
+		<%}%>
+		<dl class="<%=data.calendar ? "block-add-calendar" : "block-add-user"%> search ">
+			<dt class="add-user search"><%=data.calendar ? 'Adicionar outros usuários' : 'Adicionar outras agendas'%></dt>
+			<dd class="<%=data.calendar ? "add-user-calendar" : "add-user"%>">
+				<fieldset class="block-add-user" title="Usuários">
+					<fieldset class="add-user-search search-field ui-corner-all">
+						<input class="search" type="text" />
+						<span class="ui-icon ui-icon-search"></span>
+						
+					</fieldset>
+					<ul class="search-result-list ui-corner-all">
+
+					</ul>
+				</fieldset>
+			</dd>
+		</dl>
+	</fieldset>
+	<div class="menu-container footer-container menu-addevent">
+		<a class="button cancel" href="#">Cancelar</a>
+	    <a class="button save" href="#">Salvar</a>
+    </div>
+	</form>
+</fieldset>
Index: /trunk/prototype/modules/calendar/templates/menu_context_event.ejs
===================================================================
--- /trunk/prototype/modules/calendar/templates/menu_context_event.ejs	(revision 5592)
+++ /trunk/prototype/modules/calendar/templates/menu_context_event.ejs	(revision 5592)
@@ -0,0 +1,30 @@
+<%var signature = data.signature%>
+<div class="evt-list-options my-evt-list-options fg-menu-container ui-widget ui-widget-content ui-corner-all evt-option" style="top: <%=data.top%>px;left: <%=data.left%>px">
+	<ul class="fg-menu ui-corner-all evt-option">
+		<%if(signature.isOwner == "1"){%>
+			<li role="menuitem" class="copy menu-item"><a href="#" class="ui-corner-all">Copiar para</a></li>
+			<li role="menuitem" class="move menu-item"><a href="#" class="ui-corner-all">Mover para</a></li>
+			<li role="menuitem" class="menu-item"><a href="../prototype/modules/calendar/export.php?event=<%=data.event%>" class="ui-corner-all">Exportar</a></li>
+			<li role="menuitem" class="menu-item"><a href="#" onclick="remove_event(<%= data.event%>);" class="ui-corner-all">Remover</a></li>
+		<%}else{%>
+			<li role="menuitem" class="copy menu-item"><a href="#" class="ui-corner-all copy">Copiar para</a></li>
+			<%if(signature.permission.acl['write']){%>
+				<li role="menuitem" class="move menu-item"><a href="#" class="ui-corner-all move">Mover para</a></li>
+			<%}%>
+			<li role="menuitem" class="menu-item"><a href="../prototype/modules/calendar/export.php?event=<%=data.event%>" class="ui-corner-all">Exportar</a></li>
+			<%if(signature.permission.acl['write'] || signature.permission.acl['remove']){%>
+				<li role="menuitem" class="menu-item"><a href="#" onclick="remove_event(<%= data.event%>);" class="ui-corner-all">Remover</a></li>
+			<%}%>
+		<%}%>
+	</ul>
+</div>
+
+ 
+<div class="calendar-copy-move evt-list-options my-evt-list-options fg-menu-container ui-widget ui-widget-content ui-corner-all evt-option" style="top: <%= data.top%>px;left: <%=data.left + 100%>px; display:none;">
+	<input type="hidden" name="typeEvent"/>
+	<ul class="fg-menu ui-corner-all evt-option">
+		<% for( var i = 0; i < data.calendars.length; i++ ){ %>
+			<li role="menuitem" class="calendar-list"><a href="#"  onclick="copyAndMoveTo(<%=data.calendars[i].id %> ,<%= data.event%>);" class="ui-corner-all"><%=data.calendars[i].name %></a></li>
+		<% } %>
+	</ul>
+</div>
Index: /trunk/prototype/modules/calendar/templates/attendee_add.ejs
===================================================================
--- /trunk/prototype/modules/calendar/templates/attendee_add.ejs	(revision 5514)
+++ /trunk/prototype/modules/calendar/templates/attendee_add.ejs	(revision 5592)
@@ -160,6 +160,6 @@
 		<fieldset class="block-add-attendee" title="Participantes">
 			<fieldset class="add-attendee-search search-field ui-corner-all">
+				<input class="search" type="text" />
 				<span class="ui-icon ui-icon-search"></span>
-				<input class="search" type="text" />
 			</fieldset>
 			<ul class="search-result-list ui-corner-all">
Index: /trunk/prototype/modules/calendar/templates/calendar_list.ejs
===================================================================
--- /trunk/prototype/modules/calendar/templates/calendar_list.ejs	(revision 5399)
+++ /trunk/prototype/modules/calendar/templates/calendar_list.ejs	(revision 5592)
@@ -1,4 +1,4 @@
 <div class="all-list-calendars">
-<% var agendas_usuario = data.calendars %>
+<% var signature = data.signatures %>
 <% var external = false %>
 <div class="my-calendars">
@@ -7,28 +7,25 @@
 	<a href="#" class="button new new-calendar">Nova Agenda</a>
 	<ul class="list-calendars my-list-calendars">
-				<% for (var i=0; i < agendas_usuario.length; i++) {
-
-					if(data.signatureOf[agendas_usuario[i].id].isOwner == 1){
-					
-						var assinatures = data.signatureOf[agendas_usuario[i].id];
-
+				<% for (var i=0; i < signature.length; i++) {
+					if(signature[i].isOwner == 1){
 				%>
-					<li class="list-calendars-item list-calendars-item-<%= agendas_usuario[i].id %>">
+					<li class="list-calendars-item list-calendars-item-<%= signature[i].calendar.id %>">
 						
 						<div>
-							<input class="calendar-view" type="checkbox" name="" value="<%= agendas_usuario[i].id %>" checked="checked"/>
-							<label><%= agendas_usuario[i].name %></label>
+							<input class="calendar-view" type="checkbox" name="" value="<%= signature[i].calendar.id %>" checked="checked"/>
+							<label><%= signature[i].calendar.name %></label>
 							
 						</div> 
-							<a class="cal-list-options-btn my-cal-list-options-btn-<%= agendas_usuario[i].id %>" style="background-color:#<%=assinatures.backgroundColor%>; border-color:#<%= assinatures.borderColor%>;">
+							<a class="cal-list-options-btn my-cal-list-options-btn-<%= signature[i].calendar.id %>" style="background-color:#<%=signature[i].backgroundColor%>; border-color:#<%= signature[i].borderColor%>;">
 								<img src="../prototype/modules/calendar/img/arrow_down.png" width="10" height="10" class="cal-list-img"/>
 							</a>
 							
 							
-						<div class="cal-list-options my-cal-list-options-<%= agendas_usuario[i].id %> hidden">
+						<div class="cal-list-options my-cal-list-options-<%= signature[i].calendar.id %> hidden">
 							<ul>
-								<li><a href="#" onclick="add_tab_configure_calendar(<%= agendas_usuario[i].id%>);">Configurações</a></li>
-								<li><a href="#" onclick="show_modal_import_export(0, <%= agendas_usuario[i].id%>);">Importar</a></li>
-								<li><a href="#" onclick="show_modal_import_export(1, <%= agendas_usuario[i].id%>);">Exportar</a></li>
+								<li><a href="#" onclick="add_tab_configure_calendar(<%= signature[i].calendar.id%>);">Configurações</a></li>
+								<li><a href="#" onclick="show_modal_import_export(0, <%= signature[i].calendar.id%>);">Importar</a></li>
+								<li><a href="#" onclick="show_modal_import_export(1, <%= signature[i].calendar.id%>);">Exportar</a></li>
+								<li><a href="#" onclick="show_modal_shared(<%= signature[i].calendar.id%>);">Compartilhar agenda</a></li>
                                 <li><a href="#" onclick="remove_calendar();">Remover agenda</a></li>
 							</ul>
@@ -44,25 +41,30 @@
 	</ul>
 </div>
-<% if (external) { %>
+
 <div class="signed-calendars">
 	<a title='Agendas assinadas' class="title-signed-calendars" aria-expanded='false' role='button' tabindex='0'>Agendas assinadas</a>			
+	<span class="status-list-shared ui-icon ui-icon-triangle-1-s"></span>
+	<a href="#" class="button new new-calendar-shared tiny">Nova Agenda</a>
+	
+	<% if (external) { %>	
 		<ul class="list-calendars signed-list-calendars">
-			
-					<% for (var i=0; i < agendas_usuario.length; i++) {
-						if(data.signatureOf[agendas_usuario[i].id].isOwner == 0){
+				<% for (var i=0; i < signature.length; i++) {
+						if(signature[i].isOwner == 0){
 					%>
-						<li class="list-calendars-item list-calendars-item-<%= agendas_usuario[i].id %>">
-							<input class="calendar-view" type="checkbox" name="" value="<%= agendas_usuario[i].id %>" checked="checked"/>
-							<label><%= agendas_usuario[i].name %></label>
+						<li class="list-calendars-item list-calendars-item-<%= signature[i].calendar.id %>">
+							<input class="calendar-view" type="checkbox" name="" value="<%= signature[i].calendar.id %>" checked="checked"/>
+							<label><%= signature[i].calendar.name %></label>
 
-							<a class="cal-list-options-btn signed-cal-list-options-btn-<%= agendas_usuario[i].id %>" onclick="show_cal_list_options('signed-cal-list-options-', <%= agendas_usuario[i].id %>)"  style="background-color:#<%=assinatures.backgroundColor%>; border-color:#<%= assinatures.borderColor%>"><img src="img/arrow_down.png" width="10" height="10" class="cal-list-img"></a>
-							<div class="cal-list-options signed-cal-list-options-<%= agendas_usuario[i].id %> hidden">
+							<a class="cal-list-options-btn my-cal-list-options-btn-<%= signature[i].calendar.id %>" style="background-color:#<%=signature[i].backgroundColor%>; border-color:#<%= signature[i].borderColor%>;">
+							<img src="../prototype/modules/calendar/img/arrow_down.png" width="10" height="10" class="cal-list-img"/></a>
+							<div class="cal-list-options my-cal-list-options-<%= signature[i].calendar.id  %> hidden">
 								<ul>
-									<li><a href="#">Configurações</a></li>
-									<li><a href="#">Importar</a></li>
-									<li><a href="#">Exportar</a></li>
-                                    <li><a href="#">Cancelar assinatura</a></li>
+									<li><a href="#" onclick="add_tab_configure_calendar(<%= signature[i].calendar.id %>);">Configurações</a></li>
+									<li><a href="#" onclick="show_modal_import_export(0, <%= signature[i].calendar.id %>);">Importar</a></li>
+									<li><a href="#" onclick="show_modal_import_export(1, <%= signature[i].calendar.id %>);">Exportar</a></li>
+									<li><a href="#" onclick="cancel_signature(<%= signature[i].id %>);">Cancelar assinatura</a></li>
 								</ul>
-							</div>
+
+						</div>
 
 						</li>
@@ -72,5 +74,5 @@
 					%>
 		</ul>
+	<% } %>
 	</div>
-<% } %>
 </div>
Index: /trunk/prototype/modules/calendar/templates/index.ejs
===================================================================
--- /trunk/prototype/modules/calendar/templates/index.ejs	(revision 5514)
+++ /trunk/prototype/modules/calendar/templates/index.ejs	(revision 5592)
@@ -68,4 +68,5 @@
 <script type="text/javascript" src="<?= PLUGINSURL ?>/fgmenu/fg.menu.js"></script>
 <script type="text/javascript" src="<?= PLUGINSURL ?>/qtip/jquery.qtip-1.0.0-rc3.min.js"></script>
+<script type="text/javascript" src="<?= PLUGINSURL ?>/contextmenu/jquery.contextMenu.js"></script>
 
 <!-- JPicker -->
@@ -84,8 +85,10 @@
 
 <script type='text/javascript' src='<?= MODULESURL ?>/js/helpers.js'></script>
+<script type='text/javascript' src='<?= MODULESURL ?>/js/calendar.shared.js'></script>
 <script type='text/javascript' src='<?= MODULESURL ?>/js/timezone.js'></script>
 <script type='text/javascript' src='<?= MODULESURL ?>/js/calendar.codecs.js'></script>
 
 <script type='text/javascript' src='<?= MODULESURL ?>/js/I18n.js'></script>
+<script type='text/javascript' src='<?= MODULESURL ?>/js/calendar.contentMenu.js'></script>
 <script type="text/javascript" src="<?= MODULESURL ?>/js/init.js"></script>
 
@@ -105,6 +108,6 @@
 			</div>		
 			<fieldset class="search-field main-search ui-corner-all">
+				<input class="search" type="text" />
 				<span class="ui-icon ui-icon-search"></span>
-				<input class="search" type="text" />
 			</fieldset>
 		</div>
@@ -129,8 +132,11 @@
 			<div id="tab_events_list_"> </div>
 			<div id="sandbox2">	</div>
+			<div id="calendarShared">	</div>
+			<div id="context-menu-event">	</div>
 		</div>
 		
 		<div id="sandbox" class="expresso-calendar-container hidden"> </div>
 		<div id="div-import-export-calendar" class="expresso-calendar-container"> </div>
+		<div id="div-copy-move-calendar" class="expresso-calendar-container"> </div>
 		<div id="div-alarm" class="expresso-alarm-container"> </div>
 	</div>
Index: /trunk/prototype/modules/calendar/templates/user_shared_add_itemlist.ejs
===================================================================
--- /trunk/prototype/modules/calendar/templates/user_shared_add_itemlist.ejs	(revision 5592)
+++ /trunk/prototype/modules/calendar/templates/user_shared_add_itemlist.ejs	(revision 5592)
@@ -0,0 +1,32 @@
+<li class="user-list"> 
+	<div style="overflow:hidden; width:100%; display:table;">
+		<%if(data[0].isCalendar){%>
+			<div class="user-acls-shared-calendar calendar">
+					<a class="button close new">Remover</a>
+			</div>
+			
+			<input type="checkbox" name="idPermission" value="<%=data[0].idPermission%>">
+			<input type="hidden" name="calendar[]" value="<%=data[0].id%>">
+			<input type="hidden" name="type[]" value="<%=data[0].type%>">
+			<label title="<%=data[0].description%>" class="name"><%= data[0].name ? data[0].name : '' %></label>
+		<%}else{%>
+			<div class="user-acls-shared-calendar">
+					<a class="button read user-options-button-view new">Ver</a>
+					<a class="button write user-options-button-edit-new new">Criar/Editar</a>
+					<a class="button remove user-options-button-remove new">Excluir</a>
+					<a class="button busy user-options-button-free-bussy new">Livre/Ocupado</a>
+					<a class="button shared user-options-button-shared new">Compartilhar</a>
+					<a class="button close new">Remover</a>
+			</div>
+		
+		<input type="checkbox" value="<%=data[0].id%>">
+		
+		<input type="hidden" name="user[]" value="<%=data[0].id%>">
+		<input type="hidden" name="attendeeAcl[]" value="<%=data[0].aclValue%>">
+		
+		<label title="<%=data[0].name%>" class="name"><%= data[0].name ? data[0].name : '' %></label>
+		<label title="<%=data[0].mail%>" class="mail <%= data[0].name ? 'hidden' : ''%>"><%= data[0].mail ? data[0].mail : '' %></label>
+		<%}%>
+	</div>
+	
+</li>
Index: /trunk/prototype/modules/calendar/templates/event_add.ejs
===================================================================
--- /trunk/prototype/modules/calendar/templates/event_add.ejs	(revision 5515)
+++ /trunk/prototype/modules/calendar/templates/event_add.ejs	(revision 5592)
@@ -123,13 +123,13 @@
 				<label>Avisar-me por </label>
 				<select name="alarmType[]">
-					<option value="alert" <%= data.event.alarms[i].type=='alert' ? 'selected="selected"':'' %>>Alerta</option>
-					<option value="mail" <%= data.event.alarms[i].type=='mail' ? 'selected="selected"':'' %>>E-mail</option>
+				<!--<option value="alert" <%= data.event.alarms[i].type=='alert' ? 'selected="selected"':'' %>>Alerta</option>
+					<option value="mail" <%= data.event.alarms[i].type=='mail' ? 'selected="selected"':'' %>>E-mail</option>-->
 					<option value="sms" <%= data.event.alarms[i].type=='sms' ? 'selected="selected"':'' %>>SMS</option>
 				</select>
 				<input type="text" name="alarmTime[]" class="number input-small" value="<%= data.event.alarms[i].time %>"/>
 				<select name="alarmUnit[]">
+					<option value="m" <%= data.event.alarms[i].unit=='m' ? 'selected="selected"':'' %>>Minutos</option>
+					<option value="h" <%= data.event.alarms[i].unit=='h' ? 'selected="selected"':'' %>>Horas</option>
 					<option value="d" <%= data.event.alarms[i].unit=='d' ? 'selected="selected"':'' %>>Dias</option>
-					<option value="h" <%= data.event.alarms[i].unit=='h' ? 'selected="selected"':'' %>>Horas</option>
-					<option value="m" <%= data.event.alarms[i].unit=='m' ? 'selected="selected"':'' %>>Minutos</option>
 				</select>
 				<input type="hidden" name="alarmId[]" value="<%=data.event.useAlarmDefault ? '' : data.event.alarms[i].id%>" />
Index: /trunk/prototype/api/datalayer.js
===================================================================
--- /trunk/prototype/api/datalayer.js	(revision 5539)
+++ /trunk/prototype/api/datalayer.js	(revision 5592)
@@ -1067,14 +1067,12 @@
 	
 	var result = false;
-
-	/*
-	*  TODO - Para correta aplicaÃ§Ã£o de filtros campos com valores de datas
-	* devem ter tratamento diferenciado, sendo que como string os mesmos nÃ£o serÃ£o 
-	* corretamente tratados. 
-	*/
 	
 	if( bothSides || !oneSide )
-	    //result = this.check( concept, id || filter );
-		result = concept == 'schedulable' ? false : this.check( concept, id || filter );
+	    result = this.check( concept, id || filter );
+	
+	if (bothSides && filter.filter && filter.criteria)
+		result = false;
+
+		
 	if( !result && (bothSides || oneSide) )
 	{
@@ -1116,22 +1114,34 @@
 	return( filtered );
     },
+
+	converterType: function( filter ){
+
+			return isNaN(parseInt(filter)) ? filter : parseInt(filter);
+		
+	},
+
     
     compare: function( operator, base, test ){
       
-      switch( operator )
-      {
-	  case '*':  return RegExp( ".*" + test + ".*" ).test( base );
-	  case '^':  return RegExp( "^" + test +  ".*" ).test( base );
-	  case '$':  return RegExp( ".*"  + test + "$" ).test( base );
-
-	  case '&':  return ( base && test );
-	  case '|':  return ( base || test );
-
-	  case '=':  return ( base == test );
-	  case '<=': return ( base <= test );
-	  case '>=': return ( base >= test );
-	  case '>':  return ( base <  test );
-	  case '<':  return ( base >  test );
-      }
+	base = this.converterType(base);
+	test = this.converterType(test);
+	 
+    switch( operator ){
+	
+	case '*':  return RegExp( ".*" + test + ".*" ).test( base );
+	case '^':  return RegExp( "^" + test +  ".*" ).test( base );
+	case '$':  return RegExp( ".*"  + test + "$" ).test( base );
+
+	case '&':  return ( base && test );
+	case '|':  return ( base || test );
+
+	case '=':  return ( base == test );
+	case '<=': return ( base <= test );
+	case '>=': return ( base >= test );
+	case '>':  return ( base <  test );
+	case '<':  return ( base >  test );
+	
+	default: return true;
+	}
       
     },
Index: /trunk/prototype/post.php
===================================================================
--- /trunk/prototype/post.php	(revision 5514)
+++ /trunk/prototype/post.php	(revision 5592)
@@ -22,5 +22,5 @@
 	} 
 	
-	$_FILES = $files;
+	$_FILES = $files;	
 }
 
Index: /trunk/expressoMail1_2/templates/default/expressoMail_reset.css
===================================================================
--- /trunk/expressoMail1_2/templates/default/expressoMail_reset.css	(revision 5389)
+++ /trunk/expressoMail1_2/templates/default/expressoMail_reset.css	(revision 5592)
@@ -58,5 +58,23 @@
 	quotes: "" "";
 }
-
+.new-event-win.active .mail.name-special, .new-event-win.active .name.name-special{
+  padding: 0 0 0 35px;
+}
+
+.new-event-win.active .add-attendee-search.search-field {
+  width: 249px;
+ }
+ 
+ .new-event-win.active #calendar_addevent_details4 {
+  margin: 10px 0 0 0;
+ } 
+ 
+ .new-event-win.active input{
+  color: #000;
+ } 
+ 
+ .new-event-win.active #calendar_addevent_details5 {
+  margin: 10px 0 11px 0;
+ }
 
 .new-event-win.active select {
Index: /trunk/expressoMail1_2/js/draw_api.js
===================================================================
--- /trunk/expressoMail1_2/js/draw_api.js	(revision 5588)
+++ /trunk/expressoMail1_2/js/draw_api.js	(revision 5592)
@@ -2884,150 +2884,72 @@
 			var endEvent = function(date){ 
 				if(!!User.preferences.defaultCalendar){ 
-					return  parseInt(date.getTime()) + 
-						(	!!Calendar.signatureOf[User.preferences.defaultCalendar].calendar.defaultDuration ?  
+					return  new Date(parseInt(date.getTime()) + 
+						    (!!Calendar.signatureOf[User.preferences.defaultCalendar].calendar.defaultDuration ?  
 							(Calendar.signatureOf[User.preferences.defaultCalendar].calendar.defaultDuration * 60000) :
 							(User.preferences.defaultDuration * 60000)
-						);
+						));
 				}else 
-					return parseInt(date.getTime()) + (User.preferences.defaultDuration * 60000); 
+					return new Date(parseInt(date.getTime()) + (User.preferences.defaultDuration * 60000)); 
 			};       
+
+			var emails = $("#to_values_"+ID).val().split(',');
+			
+			
+			//Normalização dos dados evita ter que reemplementar toda as funcionalidades do calendar
 			eventDetails({ 
+					
+					acl: {inviteGuests: true, organization: true ,participationRequired: false, read: true, write: true},
+					alarms: [],
+					allDay: false,
+					attachments: [],
+					attendee: '',//TODOOOOOO,
+					calendar: User.preferences.defaultCalendar ? User.preferences.defaultCalendar : Calendar.calendars[0],
+					calendars: Calendar.calendars,
+					category: '',
+					class: '1',
+					delegatedFrom: {},
+					endDate: startEvent.toString(User.preferences.dateFormat),
+					startDate: endEvent(startEvent).toString(User.preferences.dateFormat),
+					startHour: startEvent.toString(User.preferences.hourFormat),
+					endHour: endEvent(startEvent).toString(User.preferences.hourFormat),
+					timezone: User.preferences.defaultCalendar ? Calendar.calendarOf[User.preferences.defaultCalendar].timezone : User.preferences.timezone,
 					summary : $("#subject_"+ID).text(),
 					description : $("#body_" + ID).text(),
 					startTime: startEvent.getTime(),
-					endTime: endEvent(startEvent)
-			}, true, path);
-			
-			//TimePicker Não está funcionando corretamente, o motivo ainda é desconhecido.
-			/*
-			$(".new-event-win").find('input.time').timepicker({ 
-				closeText: 'Ok',
-				hourGrid: 4,
-				minuteGrid: 10,
-				//ampm : ((User.preferences.hourFormat.length > 5) ? true: false),
-				timeFormat: "hh:mm tt",
-				onSelect: function (selectedDateTime){
-					if(!(User.preferences.hourFormat.length == 5))
-						$(this).val(selectedDateTime.replace(/[\.]/gi, ""));								
-				},
-				onClose : function (selectedDateTime){
-					if(!(User.preferences.hourFormat.length == 5))
-						$(this).val(selectedDateTime.replace(/[\.]/gi, ""));
-				}
-			});
-			*/
-			
-			var emails = $("#to_values_"+ID).val();
-			emails = emails.split(",");
-			var blkAddAtendee = UI.dialogs.addEvent.find('#calendar_addevent_details6');
-			var onShowToolTip = function(arg0) {
-				$('.qtip-active .button.close').button({
-					icons: {primary: "ui-icon-close"},
-					text: false
-				});
-				$('.qtip-active .button').button()
-				.filter('.save').click(function(event, ui) {
-					if (saveContact()) {						
-						lastEditAttendeeToolTip.qtip("destroy");
-					} else {
-						return false;
-					}
-				}).end()
-				.filter('.cancel').click(function(event, ui) {
-					lastEditAttendeeToolTip.qtip("destroy");
-				})
-
-				/** 
-				 * Trata o ENTER no campo da tooltip, equivalente a salvar 
-				 * o novo convidado.
-				 */
-				$('.qtip-active input').keydown(function(event) {
-					if (event.keyCode == '13') {						
-						if (saveContact()) {						
-							lastEditAttendeeToolTip.qtip("destroy");
-						}
-
-						lastEditAttendeeToolTip.qtip("destroy");
-						event.preventDefault();
-					}
-				})
-				.filter('[name="name"]').Watermark("informe o nome do contato").end()
-				.filter('[name="mail"]').Watermark("informe o email do contato");
-			}
+					endTime: endEvent(startEvent),
+					timezones: Timezone.timezones,
+					me: {name: User.me.name, mail: User.me.mail, acl: 'rowi', status: '1', delegatedFrom: '0', id: User.me.id},
+					organizer: {name: User.me.name, mail: User.me.mail, acl: 'rowi', status: '1', delegatedFrom: '0' , id: User.me.id},
+					statusParticipants: {accepted: 0, cancelled: 0, tentative: 0, unanswered:emails.length},
+					location: '',
+					attendee: $.map(emails, function( mail ){			
+						
+						var decoded =  Encoder.htmlDecode(mail);
+						var newAttendeeName = "";
+
+						var user = DataLayer.get('user', ["=", "mail", decoded.match(/<([^<]*)>[\s]*$/) ? decoded.match(/<([^<]*)>[\s]*$/)[1].toLowerCase() : decoded], true);
+						
+						if( $.type(user) == "array")
+								user = user[0];
+
+						if(!user)
+							user = {name : decoded.match(/"([^"]*)"/)[1] , mail : decoded.match(/[\w-]+(\.[\w-]+)*@(([A-Za-z\d][A-Za-z\d-]{0,61}[A-Za-z\d]\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])/)[1]};
+
+						if(User.me.mail == user.mail)
+							return(null);
+							
+						user.isExternal = (!!user && !(!!user.isExternal)) ? 0 : 1;
+
+						return  DataLayer.merge({
+							name: user.name,
+							mail: user.mail,
+							acl:  'r',
+							delegatedFrom: '0',
+							status: '4'
+						}, !!user.id ? {id : DataLayer.put('participant', {user: user.id, isExternal: user.isExternal}) } : {id: DataLayer.put('participant', {user: user})}); 
+				
+					})	
 					
-			$.each(emails, function(index, value) { 
-				var decoded =  Encoder.htmlDecode(value);
-				var newAttendeeName = "";
-				if(decoded.match(/<([^<]*)>[\s]*$/)){
-					var user = DataLayer.get('user', ["=", "mail", decoded.match(/<([^<]*)>[\s]*$/)[1].toLowerCase()], true);
-					if(!(!!user)){
-						newAttendeeName = decoded.match(/"([^"]*)"/)[1];
-						var newAttendeeEmail = decoded.match(/<([^<]*)>[\s]*$/)[1];
-					}
-				}
-				else{
-					var user = DataLayer.get('user', ["=", "mail", decoded], true);
-					if(!(!!user)){
-						if(decoded.match(/^[\w!#$%&'*+\/=?^`{|}~-]+(\.[\w!#$%&'*+\/=?^`{|}~-]+)*@(([\w-]+\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/))
-							var newAttendeeEmail = decoded;
-						else{
-							var newAttendeeEmail = "";
-							newAttendeeName = decoded;
-						}
-					}
-				}
-					
-				var isExternal = (!!user && !(!!user.isExternal)) ? 0 : 1;
-				var add = false;
-				if(user){
-					if(!(blkAddAtendee.find('label.mail[title="' + user[0].mail + '"]').length)){
-						user[0].id =  DataLayer.put('participant', {user: user[0].id, isExternal: isExternal});
-						blkAddAtendee.find('dd.attendee-list ul.attendee-list').append(
-							DataLayer.render(path+'templates/participants_add_itemlist.ejs', user)
-						)
-						.find('.button.close').addClass('small').button({text:false, icons:{primary:'ui-icon-close'}}).click(function() {
-							DataLayer.remove('participant', $(this).parent().find('[type=checkbox]').val());
-							$(this).parent().remove();
-						}).end()
-						.scrollTo('max');
-						add = true;
-					}
-				}else{
-					userId = DataLayer.put('user', {name: newAttendeeName, mail: newAttendeeEmail, isExternal: isExternal});
-					newAttendeeId = DataLayer.put('participant', {user: userId, isExternal: isExternal});
-					
-					blkAddAtendee.find('dd.attendee-list ul.attendee-list').append(
-						DataLayer.render(path+'templates/participants_add_itemlist.ejs', [{id:newAttendeeId, name: newAttendeeName, mail: newAttendeeEmail, isExternal: 1}])
-					).find('.button.close').addClass('small').button({text:false, icons:{primary:'ui-icon-close'}}).click(function() {
-						DataLayer.remove('participant', $(this).parent().find('[type=checkbox]').val());
-						$(this).parent().remove();
-					}).end()
-					.scrollTo('max');
-					add = true;
-				}
-				if(add){
-					lastEditAttendeeToolTip = blkAddAtendee.find('dd.attendee-list li:last');
-					lastEditAttendeeToolTip.qtip({
-						show: {ready: false, solo: true, when: {event: 'click'}},
-						hide: false,
-						content: {
-							text: $('<div></div>').html( DataLayer.render( path+'templates/attendee_quick_edit.ejs', {attendee:{name:( (!!user ? (!!user[0] ? (!!user[0].name ? user[0].name : newAttendeeName): newAttendeeName) : newAttendeeName)), mail:(!!user ? (!!user[0] ? (!!user[0].mail ? user[0].mail : newAttendeeEmail): newAttendeeEmail) : newAttendeeEmail)}} ) ), 
-							title: {
-								text:'Detalhes do participante', 
-								button: '<a class="button close" href="#">close</a>'
-							}
-						},
-						style: {name: 'blue', tip: {corner: 'leftMiddle'}, border: {width: 4, radius: 8}, width: {min: 230, max:230}},
-						position: {
-							corner: {
-								target: 'rightMiddle',
-								tooltip: 'leftMiddle'
-							},
-							adjust: {x:0, y:0}
-						}
-					});
-					lastEditAttendeeToolTip.qtip("api").onShow = onShowToolTip;
-				}
-			});						
+			}, true, path, true);
 		}
 		subject.appendChild(new_event_logo);
