Index: trunk/prototype/services/iCal.php
===================================================================
--- trunk/prototype/services/iCal.php	(revision 6321)
+++ trunk/prototype/services/iCal.php	(revision 6331)
@@ -243,5 +243,5 @@
 
 			    if ($schedulable) { //Caso o evento exista
-				if (!self::_existInMyCalendars($schedulable['id'])) {
+				if (!self::_existInMyCalendars($schedulable['id'], $params['owner'])) {
 				    $calendarToSchedulable = array();
 				    $calendarToSchedulable['calendar'] = $params['calendar'];
@@ -250,7 +250,7 @@
     
 				    if (isset($params['status'])) {
-					if(isset($params['fromPermission'])){					    
-					    $signaturesOfOwner = Controller::Read(array('concept' => 'calendarSignature'), false, array('filter' => array('AND', array('=', 'calendar', $params['fromPermission']) , array('=','isOwner','1')), 'deepness' => 2 ));					    
-					    $pID = self::_getParticipantByMail($signaturesOfOwner[0]['user']['mail'], $schedulable['participants']);
+					if($params['owner'] != Config::me("uidNumber")){					    
+					    $user = Controller::Read(array('concept' => 'user'), false, array('filter' => array('=', 'id', $params['owner'])) );					    
+					    $pID = self::_getParticipantByMail($user[0]['mail'], $schedulable['participants']);
 					}else
 					    $pID = self::_getParticipantByMail(Config::me('mail'), $schedulable['participants']);
@@ -269,7 +269,7 @@
 
 				    if (isset($params['status'])) {
-					if(isset($params['fromPermission'])){					    
-					    $signaturesOfOwner = Controller::Read(array('concept' => 'calendarSignature'), false, array('filter' => array('AND', array('=', 'calendar', $params['fromPermission']) , array('=','isOwner','1')), 'deepness' => 2 ));
-					    $pID = self::_getParticipantByMail($signaturesOfOwner[0]['user']['mail'], $schedulable['participants']);
+					if($params['owner'] != Config::me("uidNumber")){					    
+					   $user = Controller::Read(array('concept' => 'user'), false, array('filter' => array('=', 'id', $params['owner'])) );					    
+					    $pID = self::_getParticipantByMail($user[0]['mail'], $schedulable['participants']);
 					}else
 					    $pID = self::_getParticipantByMail(Config::me('mail'), $schedulable['participants']);
@@ -478,5 +478,5 @@
 
 				$schedulable = self::_getSchedulable($uid);
-				$params['calendar'] = self::_existInMyCalendars($schedulable['id']);
+				$params['calendar'] = self::_existInMyCalendars($schedulable['id'], $params['owner']);
 
 				$interation = self::_makeCOUNTER($schedulable, $component, $params);
@@ -503,5 +503,5 @@
 				$interation = self::_makeVEVENT($schedulable, $component, $params);
 
-				if (!self::_existInMyCalendars($schedulable['id'])) {
+				if (!self::_existInMyCalendars($schedulable['id'], $params['owner'])) {
 				    $calendarToSchedulable = array();
 				    $calendarToSchedulable['calendar'] = $params['calendar'];
@@ -527,5 +527,4 @@
 	    }
 	}
-
 	return $return;
     }
@@ -558,10 +557,10 @@
 
 				foreach ($schedulable['participants'] as $value)
-				    if ($value['user']['id'] == Config::me('uidNumber')) {
+				    if ($value['user']['id'] == $params['owner']) {
 					$isParticipant = true;
 					if ($value['isOrganizer'])
 					    $isOrganizer = true;
 
-					if (!self::_existInMyCalendars($schedulable['id'])) {
+					if (!self::_existInMyCalendars($schedulable['id'], $params['owner'])) {
 					    $interation = ICAL_ACTION_UPDATE;
 					    $interation = ( strrpos($value['acl'], ATTENDEE_ACL_PARTICIPATION_REQUIRED) ) ? ICAL_ACTION_IMPORT_REQUIRED : ICAL_ACTION_IMPORT;
@@ -579,4 +578,20 @@
 			    }else
 				$interation = ICAL_ACTION_IMPORT;
+			    
+			    if(($interation != ICAL_ACTION_NONE) && ($interation != ICAL_ACTION_ORGANIZER_NONE) && ($interation != ICAL_ACTION_ORGANIZER_UPDATE) && ($interation != ICAL_ACTION_NONE)) {
+				if($params['owner'] != Config::me("uidNumber")){
+				    $sig = Controller::find(array('concept' => 'calendarSignature'), array('calendar'), array('filter' => array('AND', array('=', 'user', $params['owner']), array('=', 'isOwner', '1'))));
+				    $calendars = array();
+				    foreach ($sig as $val)
+					$calendars[] = $val['calendar'];
+				
+				    $calendarsPermission = Controller::find(array('concept' => 'calendarToPermission'), array('calendar'), array('filter' => array('AND', array('=', 'user', Config::me("uidNumber")), array('IN', 'calendar', $calendars))));   
+				    
+				    foreach ($calendarsPermission as $val)
+					$ids[] = $val['calendar'];
+
+				    $interation = array('action' => ICAL_ACTION_IMPORT_FROM_PERMISSION ,'calendar' => $ids);
+				}
+			    }
 
 			    break;
@@ -675,5 +690,5 @@
 		    $eventoFromCalendar = Controller::read( array( 'concept' => 'calendarToSchedulable') , false, array('filter' => array('AND', array('=','schedulable',$schedulable['id']), array('=','calendar', $value['calendar']['id']))));
 
-		    return  ($eventoFromCalendar && isset($eventoFromCalendar[0])) ? ICAL_ACTION_NONE_FROM_PERMISSION : array('action' => ICAL_ACTION_IMPORT_FROM_PERMISSION, 'calendar' => $value['calendar']['id'] );
+		    return  ($eventoFromCalendar && isset($eventoFromCalendar[0])) ? ICAL_ACTION_NONE_FROM_PERMISSION : array('action' => ICAL_ACTION_IMPORT_FROM_PERMISSION, 'calendar' => array($value['calendar']['id']) );
 		}
 	    }    
@@ -1064,6 +1079,6 @@
     }
 
-    static private function _existInMyCalendars($id) {
-	$sig = Controller::find(array('concept' => 'calendarSignature'), array('user', 'calendar', 'isOwner'), array('filter' => array('AND', array('=', 'user', Config::me('uidNumber')), array('=', 'isOwner', '1'))));
+    static private function _existInMyCalendars($id, $owner) {
+	$sig = Controller::find(array('concept' => 'calendarSignature'), array('user', 'calendar', 'isOwner'), array('filter' => array('AND', array('=', 'user', $owner), array('=', 'isOwner', '1'))));
 	$calendars = array();
 	foreach ($sig as $val)
Index: trunk/prototype/modules/calendar/interceptors/Notifications.php
===================================================================
--- trunk/prototype/modules/calendar/interceptors/Notifications.php	(revision 6190)
+++ trunk/prototype/modules/calendar/interceptors/Notifications.php	(revision 6331)
@@ -92,4 +92,5 @@
 	if (isset($updated)) {
 	    $psUpdated = Controller::find(array('concept' => 'participant'), false, array('deepness' => '1', 'filter' => array('IN', 'id', $updated)));
+
 	    foreach ($psUpdated as $i => $pUpdated) {
 		if ($pUpdated['isOrganizer'] == '1')
@@ -237,5 +238,4 @@
      */
     public static function participantDelegatedStatusChange(&$partID, &$schedulable, $organizer, &$type = false) {
-
 	$delegatedParams = array();
 
@@ -270,5 +270,5 @@
     }
 
-    public static function mountStruture($partID, &$schedulable, $type = false, &$data, &$subject, &$ical, &$part = false, &$method, &$notificationType, $regSet = false) {
+    public static function mountStruture(&$partID, &$schedulable, $type = false, &$data, &$subject, &$ical, &$part = false, &$method, &$notificationType, $regSet = false) {
 
 	if ((Config::regGet('ical://' . $schedulable['id'] . '/' . $method) === false) || ($method == 'CANCEL')) { //Verifica se o ical ja não esta no reg
@@ -327,4 +327,5 @@
 		$part = self::_getAttendeeById($partID, $schedulable);
 		$data['participant'] = isset($part['user']['name']) ? $part['user']['name'] : $part['user']['mail'];
+		$partID = $part;
 		break;
 	    case 'othersAttendees':
@@ -344,5 +345,5 @@
 	$subject['endDate'] = date_format($eTime, 'd/m/Y');
 	$subject['endTime'] = ($schedulable['allDay']) ? '' : date_format($eTime, 'H:i');
-	$subject['participant'] = Config::me('uid');
+	$subject['participant'] = (is_array($partID) && isset($partID['user']) )? $partID['user']['uid'] : Config::me('uid');
     }
 
@@ -379,5 +380,5 @@
      * @access     public
      */
-    public static function participantStatusChange(&$partID, &$schedulable, &$organizer, $type, $delegatedParams = false) {
+    public static function participantStatusChange(&$partID, &$schedulable, &$organizer, $type, $delegatedParams = false) {	
 	$method = 'REPLY';
 	$notificationType = 'Convite Aceito';
@@ -412,5 +413,5 @@
 	}
 
-	self::sendMail($data, $ical, $organizer['user']['mail'], $subject, $tpl, false);
+	self::sendMail($data, $ical, $organizer['user']['mail'], $subject, $tpl, $partID);
     }
 
Index: trunk/prototype/modules/calendar/interceptors/DBMapping.php
===================================================================
--- trunk/prototype/modules/calendar/interceptors/DBMapping.php	(revision 6299)
+++ trunk/prototype/modules/calendar/interceptors/DBMapping.php	(revision 6331)
@@ -373,10 +373,15 @@
 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
 
-    public function updateCalendar(&$uri, &$params, &$criteria, $original) {
-	if (isset($params['calendar'])) {
-	    $calendarObjects = self::schedulable2calendarToObject($uri['id']);
-	    $params2['calendar'] = $params['calendar'];
-
-	    foreach ($calendarObjects as $calendarObject)
+    public function updateCalendar(&$uri, &$params, &$criteria, $original) {       
+        if (isset($params['calendar'])) {
+            if(isset($params['lastCalendar'])){
+                $calendarObjects = self::referenceCalendarToObject($uri['id'], $params['lastCalendar']);
+                $params2['calendar'] = $params['calendar'];
+            }else{
+                $calendarObjects = self::schedulable2calendarToObject($uri['id']);
+                $params2['calendar'] = $params['calendar'];
+            }
+	    
+            foreach ($calendarObjects as $calendarObject)
 		Controller::update(array('concept' => 'calendarToSchedulable', 'id' => $calendarObject['calendar_to_calendar_object']), $params2);
 
@@ -717,5 +722,5 @@
 	    $idCalendar = $criteria['filter'][2][2];
 	    
-	    if(!self::ownerSchedulable($idSchedulable)){
+	    if(!self::ownerSchedulable($idSchedulable, $criteria['filter'][3][2])){
 		$isPermissionFromOwner = self::permissionFromCalendarSignature($idCalendar, $idSchedulable);
 		
@@ -727,5 +732,13 @@
 
 		    foreach($calendarsToSchedulable as $value)
-			if($value['calendar_id'] == $idCalendar){
+			if($value['calendar_id'] == $idCalendar){    
+
+			    $participant = Controller::read(array('concept' => 'participant'), array('id'), array('filter' =>
+				array('AND',
+				    array('=', 'user', $criteria['filter'][3][2]),
+				    array('=', 'schedulable', $idSchedulable)
+				)));
+
+			    Controller::call(('update'), array('concept' => 'participant', 'id' => $participant[0]['id']), array('status' => STATUS_CANCELLED));
 			    Controller::delete(array('concept' => 'calendarToSchedulable', 'id' => $value['calendar_to_calendar_object']));
 			    break;
@@ -740,5 +753,5 @@
 	$calendarsToSchedulable = self::schedulable2calendarToObject($uri['id']);
 
-	if (!self::ownerSchedulable($uri['id']) && !self::isAllowDeleteInCalendar($calendarsToSchedulable[0]['calendar_id'])) {
+	if (!self::ownerSchedulable($uri['id'], Config::me('uidNumber')) && !self::isAllowDeleteInCalendar($calendarsToSchedulable[0]['calendar_id'])) {
 
 	    foreach ($calendarsToSchedulable as $i => $v) {
@@ -750,9 +763,11 @@
 
 	    /* Seta o participante como rejeitado */
-	    Controller::update(array('concept' => 'participant'), array('status' => STATUS_CANCELLED), array('filter' =>
+	    $participant = Controller::read(array('concept' => 'participant'), array('id'), array('filter' =>
 		array('AND',
 		    array('=', 'user', Config::me('uidNumber')),
-		    array('=', 'schedulable', $uri['id'])
-		    )));
+		    array('=', 'schedulable', $idSchedulable)
+		)));
+
+	    Controller::call(('update'), array('concept' => 'participant', 'id' => $participant[0]['id']), array('status' => STATUS_CANCELLED));
 
 	    return false; /* Mata o restante da execução */
@@ -1017,10 +1032,10 @@
     
     
-    private static function ownerSchedulable($id) {
+    private static function ownerSchedulable($id, $me) {
 
 	$isOwner = Controller::find(array('concept' => 'participant'), array('id'), array('filter' =>
 		    array('AND',
 			array('=', 'isOrganizer', '1'),
-			array('=', 'user', $_SESSION['wallet']['user']['uidNumber']),
+			array('=', 'user', $me),
 			array('=', 'schedulable', $id)
 			)));
@@ -1028,5 +1043,12 @@
 	return ( isset($isOwner[0]['id']) ) ? true : false;
     }
-
+    
+    
+    private static function referenceCalendarToObject($schedulable, $calendar) {
+        return Controller::service('PostgreSQL')->execResultSql('SELECT calendar_to_calendar_object.id as calendar_to_calendar_Object FROM calendar_to_calendar_object'
+            . ' WHERE calendar_to_calendar_object.calendar_id = '. $calendar
+            . ' AND calendar_to_calendar_object.calendar_object_id = ' . addslashes($schedulable));
+    }
+    
     private static function schedulable2calendarToObject($Schedulable) {
 	return Controller::service('PostgreSQL')->execResultSql('SELECT calendar_to_calendar_object.id as calendar_to_calendar_Object , calendar.name as calendar_name ,calendar.location as calendar_location, calendar.id as calendar_id FROM calendar_to_calendar_object , calendar , calendar_signature'
Index: trunk/prototype/modules/calendar/js/calendar.codecs.js
===================================================================
--- trunk/prototype/modules/calendar/js/calendar.codecs.js	(revision 6300)
+++ trunk/prototype/modules/calendar/js/calendar.codecs.js	(revision 6331)
@@ -153,10 +153,12 @@
 	delete DataLayer.tasks[this.clookRefresh];
 	
-	this.clookRefresh = (parseInt(($.now()) / 1000) + this.timeRefresh);
-	
-	DataLayer.task( this.clookRefresh , function(){
-	    Calendar.rerenderView(true);
-	});
-
+	//Realiza agendamentos de atualização de view somente se o módulo aberto for expressoCalendar
+	if(User.moduleName == "expressoCalendar"){
+	    this.clookRefresh = (parseInt(($.now()) / 1000) + this.timeRefresh);
+
+	    DataLayer.task( this.clookRefresh , function(){
+		Calendar.rerenderView(true);
+	    });
+	}
     }
 }
@@ -516,11 +518,10 @@
 	var pref = User.preferences;
 		
-	var Owner = decodeOwnerCalendar(evtObj.calendar);	
+	var Owner = decodeOwnerCalendar(evtObj[0].calendar);	
 
 	var res = $.map(evtObj, function( form ){
 			
-	    return {
+	    return DataLayer.merge({
 		id: form.idEvent,
-		calendar: form.calendar,
 		participants : $.map(form.attendee, function( attendee, i ){
 		    if(isNaN(attendee)){
@@ -536,5 +537,5 @@
 			if(DataLayer.get('participant', attendee).user == Owner.id){
 			    var me = {
-				user: User.id,
+				user: Owner.id,
 				status: form.status,
 				id: attendee,
@@ -580,5 +581,5 @@
 		    };
 		})
-	    }
+	    }, (Owner.id == User.me.id) ? (form.calendar != form.lastCalendar ? {calendar: form.calendar, lastCalendar: form.lastCalendar} : {}) : {})
 	});
 	return notArray ? res[0] : res;
@@ -641,5 +642,5 @@
 		attachments: $.map(objEvent.attachments || [], function( attachment, i ){
 		    var attach = DataLayer.get('schedulableToAttachment', attachment, false);
-		    //TODO - Verificar na API retorno de id sobre os conceitos em que são utilizados tabelas de ligação
+		    //TODO - Verificar na API retorno de id sobre os conceitos em que s?o utilizados tabelas de liga??o
 		    if(!attach.name) return(null); 
 		    
@@ -838,5 +839,5 @@
 	    var Owner = decodeOwnerCalendar(form.calendar);
 
-	    return {
+	    return DataLayer.merge({
 		"class": form["class"],
 		startTime: Date.parseExact(form.startDate + (!!form.allDay ? " 00:00": " "+$.trim(form.startHour)) , formatString ).toString('yyyy-MM-dd HH:mm:00'),
@@ -846,5 +847,4 @@
 		location: form.location,
 		category: form.category,
-		calendar: form.calendar,
 		summary: form.summary,
 		description: form.description,
@@ -901,5 +901,5 @@
 		    };
 		})
-	    };
+	    }, form.lastCalendar ? (( form.lastCalendar == form.calendar ) ? {} : {calendar: form.calendar, lastCalendar: form.lastCalendar}) : {calendar: form.calendar});
 	});
 
Index: trunk/prototype/modules/calendar/js/helpers.js
===================================================================
--- trunk/prototype/modules/calendar/js/helpers.js	(revision 6286)
+++ trunk/prototype/modules/calendar/js/helpers.js	(revision 6331)
@@ -623,13 +623,10 @@
     $(this).parent().remove().find('li').is(':empty');
 });
-		
-/*Seleciona a agenda padrão para criação de um evento*/
-
-if(objEvent.calendar != undefined)
-    var selectedCalendar = objEvent.calendar;
-else
-    var selectedCalendar = User.preferences.defaultCalendar;
-
-UI.dialogs.addEvent.find('option[value="'+selectedCalendar+'"]').attr('selected','selected').trigger('change');
+
+var myCalendar = function(){
+	for(var i in Calendar.signatures)
+	    if(Calendar.signatures[i].isOwner == "1")
+		return Calendar.signatures[i].calendar.id;
+}
 		
 /*Adicionar alarms padrões, quando alterado a agenda do usuário*/		
@@ -691,10 +688,6 @@
     .filter('.mail').html(User.me.mail).attr('title',User.me.mail);
 }
-			
-			
-			
-			
 });
-		
+
 /*Checkbox adicionar alarms padrões*/
 UI.dialogs.addEvent.find('input[name="defaultAlarm"]').click(function(){
@@ -781,5 +774,5 @@
 		canDiscardEventDialog = true;
 		/* Remove por filtro */
-		DataLayer.removeFilter('schedulable', {filter: ['AND', ['=', 'id', objEvent.id], ['=', 'calendar', objEvent.calendar]]});
+		DataLayer.removeFilter('schedulable', {filter: ['AND', ['=', 'id', objEvent.id], ['=', 'calendar', objEvent.calendar], ['=','user',(objEvent.me.user ? objEvent.me.user.id : objEvent.me.id)]]});
 		Calendar.rerenderView(true);
 		/********************/
@@ -1510,5 +1503,9 @@
 
 disponibily(objEvent, path, attendees);
-	 
+
+/*Seleciona a agenda padrão para criação de um evento*/
+var selectedCalendar = (objEvent.calendar != undefined) ? objEvent.calendar : (User.preferences.defaultCalendar ? User.preferences.defaultCalendar : myCalendar());
+UI.dialogs.addEvent.find('option[value="'+selectedCalendar+'"]').attr('selected','selected').trigger('change');
+
 UI.dialogs.addEvent.find(':input').change(function(event){
     if (event.keyCode != '27' && event.keyCode != '13')
@@ -1915,5 +1912,13 @@
 	'onClose':  function(clicked) {
 	    if(clicked == 'Sim'){
-		DataLayer.removeFilter('schedulable', {filter: ['AND', ['=','id',eventId], ['=','calendar',idCalendar]]})
+
+		var schedulable = DataLayer.get('schedulable', '88');
+		
+		schedulable.calendar = idCalendar;
+		
+		var schudableDecode = DataLayer.encode( "schedulable:preview", schedulable);
+		var me = schudableDecode.me.user ? schudableDecode.me.user.id : schudableDecode.me.id;
+
+		DataLayer.removeFilter('schedulable', {filter: ['AND', ['=','id',eventId], ['=','calendar',idCalendar], ['=','user', me]]})
 		Calendar.rerenderView(true);
 	    }
@@ -2635,5 +2640,5 @@
 
     var schedulable = DataLayer.get('schedulable', event+'');
-	
+        
     calendar = !!calendar ? calendar : schedulable.calendar;
         
@@ -2644,5 +2649,6 @@
     if(parseInt(type) == 0){
 		
-	schedulable.calendar = calendar;	
+	schedulable.lastCalendar = schedulable.calendar;
+        schedulable.calendar = calendar;	
 	DataLayer.put('schedulable', schedulable);
 	
Index: trunk/prototype/modules/calendar/templates/event_add.ejs
===================================================================
--- trunk/prototype/modules/calendar/templates/event_add.ejs	(revision 6302)
+++ trunk/prototype/modules/calendar/templates/event_add.ejs	(revision 6331)
@@ -8,4 +8,7 @@
 			<% if( data.event.id ){ %>
 				<input type="hidden" class="id-event" name="idEvent" value="<%= data.event.id %>"/>
+			<% } %>
+                        <% if( data.event.calendar ){ %>
+				<input type="hidden" class="last-calendar" name="lastCalendar" value="<%= data.event.calendar %>"/>
 			<% } %>
 		</p>
