Index: trunk/calendar/setup/setup.inc.php
===================================================================
--- trunk/calendar/setup/setup.inc.php	(revision 4186)
+++ trunk/calendar/setup/setup.inc.php	(revision 5132)
@@ -12,6 +12,5 @@
 
 	$setup_info['calendar']['name']    = 'calendar';
-	$setup_info['calendar']['title']    = 'Calendar';
-	$setup_info['calendar']['version'] = '2.2.1';
+	$setup_info['calendar']['version'] = '2.0.008';
 	$setup_info['calendar']['app_order'] = 3;
 	$setup_info['calendar']['enable']  = 1;
@@ -53,4 +52,4 @@
 	$setup_info['calendar']['depends'][] = array(
 		 'appname' => 'phpgwapi',
-		 'versions' => Array('2.2')
+		 'versions' => Array('2.4.0')
 	);
Index: trunk/calendar/setup/default_records.inc.php
===================================================================
--- trunk/calendar/setup/default_records.inc.php	(revision 3557)
+++ trunk/calendar/setup/default_records.inc.php	(revision 5132)
@@ -10,12 +10,6 @@
 	\**************************************************************************/
 
-    // Alterando dois campos da tabela phpgw_cal e phpgw_cal_holidays
-	$oProc->query("ALTER TABLE phpgw_cal ALTER COLUMN cal_id set default nextval(('seq_phpgw_cal'::text)::regclass);");
-	$oProc->query("ALTER TABLE phpgw_cal_holidays ALTER COLUMN hol_id set default nextval(('seq_phpgw_cal_holidays'::text)::regclass);");
 	
-	$oProc->query("SELECT pg_catalog.setval('seq_phpgw_cal', 1, false);");
-	$oProc->query("SELECT pg_catalog.setval('seq_phpgw_cal_holidays', 1, false);");
-
-	// Adicionando dois campos a tabela phpgw_cal
-	$oProc->query("ALTER TABLE phpgw_cal ADD COLUMN last_status char(1) DEFAULT 'N'::bpchar;");
-	$oProc->query("ALTER TABLE phpgw_cal ADD COLUMN last_update bigint DEFAULT (date_part('epoch'::text, ('now'::text)::timestamp(3) with time zone) * (1000)::double precision);");
+	// enable auto-loading of holidays from localhost by default
+	$oProc->query("INSERT INTO phpgw_config (config_app, config_name, config_value) VALUES ('phpgwapi','auto_load_holidays','True')");
+	$oProc->query("INSERT INTO phpgw_config (config_app, config_name, config_value) VALUES ('phpgwapi','holidays_url_path','localhost')");
Index: trunk/calendar/setup/tables_current.inc.php
===================================================================
--- trunk/calendar/setup/tables_current.inc.php	(revision 4316)
+++ trunk/calendar/setup/tables_current.inc.php	(revision 5132)
@@ -25,12 +25,8 @@
 				'cal_type' => array('type' => 'varchar','precision' => '10','nullable' => True),
 				'is_public' => array('type' => 'int','precision' => '8','nullable' => False,'default' => '1'),
-				'title' => array('type' => 'varchar','precision' => '300','nullable' => False,'default' => '1'),
+				'title' => array('type' => 'varchar','precision' => '80','nullable' => False,'default' => '1'),
 				'description' => array('type' => 'text','nullable' => True),
-				'notifications_owner' => array('type' => 'int','precision' => '1','nullable' => False,'default' => '0'),
-				'observations' => array('type' => 'text','nullable' => True),
-                                'attachment' => array('type' => 'text','nullable' => True),
 				'location' => array('type' => 'varchar','precision' => '255','nullable' => True),
 				'reference' => array('type' => 'int','precision' => '8','nullable' => False,'default' => '0'),
-				'alter_by' => array('type'=> 'varchar','precision' => '160','nullable' => True),
 				'ex_participants' => array('type' => 'text','nullable' => True),
 			),
@@ -64,5 +60,5 @@
 				'recur_interval' => array('type' => 'int','precision' => '8','nullable' => True,'default' => '1'),
 				'recur_data' => array('type' => 'int','precision' => '8','nullable' => True,'default' => '1'),
-				'recur_exception' => array('type' => 'varchar','nullable' => True,'default' => '')
+				'recur_exception' => array('type' => 'varchar','precision' => '255','nullable' => True,'default' => '')
 			),
 			'pk' => array(),
Index: trunk/calendar/setup/tables_update.inc.php
===================================================================
--- trunk/calendar/setup/tables_update.inc.php	(revision 4318)
+++ trunk/calendar/setup/tables_update.inc.php	(revision 5132)
@@ -19,5 +19,42 @@
 		$GLOBALS['phpgw_setup']->db->query("ALTER TABLE ".$table." ADD COLUMN ".$column." ".$attrs);
 	}  
-/// Since Expresso 1.2 using Calendar 0.9.3 
+	$test[] = '0.9.2';
+	function calendar_upgrade0_9_2()
+	{
+		$GLOBALS['setup_info']['calendar']['currentver'] = '0.9.17';
+		return $GLOBALS['setup_info']['calendar']['currentver'];
+	}
+	$test[] = '0.9.17';
+	function calendar_upgrade0_9_17()
+	{
+		$GLOBALS['setup_info']['calendar']['currentver'] = '0.9.21';
+		return $GLOBALS['setup_info']['calendar']['currentver'];
+	}
+	$test[] = '0.9.20';
+	function calendar_upgrade0_9_20()
+	{
+		$GLOBALS['setup_info']['calendar']['currentver'] = '0.9.21';
+		return $GLOBALS['setup_info']['calendar']['currentver'];
+	}	
+	$test[] = '0.9.21';
+	function calendar_upgrade0_9_21()
+	{
+		addSpecialColumn("phpgw_cal","last_status","char(1) DEFAULT 'N'::bpchar");
+		addSpecialColumn("phpgw_cal","last_update","int8 DEFAULT (date_part('epoch'::text, ('now'::text)::timestamp(3) with time zone) * (1000)::double precision)");
+		$GLOBALS['setup_info']['calendar']['currentver'] = '0.9.22';
+		return $GLOBALS['setup_info']['calendar']['currentver'];
+	}	
+	$test[] = '0.9.22';
+	function calendar_upgrade0_9_22()
+	{
+		$GLOBALS['setup_info']['calendar']['currentver'] = '0.9.23';
+		return $GLOBALS['setup_info']['calendar']['currentver'];
+	}
+	$test[] = '0.9.23';
+	function calendar_upgrade0_9_23()
+	{
+		$GLOBALS['setup_info']['calendar']['currentver'] = '0.9.3';
+		return $GLOBALS['setup_info']['calendar']['currentver'];
+	}	
 	$test[] = '0.9.3';
 	function calendar_upgrade0_9_3()
@@ -63,37 +100,13 @@
 	}	
 	$test[] = '2.0.006';
-	function calendar_upgrade2_0_006()
-	{
+	function calendar_upgrade2_0_006() {
 		$GLOBALS['setup_info']['calendar']['currentver'] = '2.0.007';
+		$GLOBALS['phpgw_setup']->db->query("ALTER TABLE phpgw_cal ALTER COLUMN title TYPE character varying(1024);");
 		return $GLOBALS['setup_info']['calendar']['currentver'];
 	}		
 	$test[] = '2.0.007';
-	function calendar_upgrade2_0_007()
-	{
-		$GLOBALS['setup_info']['calendar']['currentver'] = '2.1.000';
-		return $GLOBALS['setup_info']['calendar']['currentver'];
-	}
-	$test[] = '2.1.000';
-	function calendar_upgrade2_1_000()
-	{
-		$GLOBALS['setup_info']['calendar']['currentver'] = '2.2.000';
-		return $GLOBALS['setup_info']['calendar']['currentver'];
-	}
-	$test[] = '2.2.000';
-	function calendar_upgrade2_2_000()
-	{
-		$GLOBALS['setup_info']['calendar']['currentver'] = '2.2.003'; 
- 	    return $GLOBALS['setup_info']['calendar']['currentver']; 
-	} 
- 	$test[] = '2.2.003'; 
- 	function calendar_upgrade2_2_003() 
- 	{ 
-	    $GLOBALS['phpgw_setup']->db->query("ALTER TABLE phpgw_cal ADD COLUMN notifications_owner INT NOT NULL default '0'");
-		$GLOBALS['phpgw_setup']->db->query("ALTER TABLE phpgw_cal ADD COLUMN observations text");
-	    $GLOBALS['phpgw_setup']->db->query("ALTER TABLE phpgw_cal ADD COLUMN alter_by varchar(160)");
-	    $GLOBALS['phpgw_setup']->db->query("ALTER TABLE phpgw_cal ADD COLUMN attachment text");
-            $GLOBALS['phpgw_setup']->db->query("ALTER TABLE phpgw_cal ALTER title TYPE varchar(300)");
-            $GLOBALS['phpgw_setup']->db->query("ALTER TABLE phpgw_cal_repeats ALTER recur_exception TYPE varchar");
-	    $GLOBALS['setup_info']['calendar']['currentver'] = '2.2.1';
+	function calendar_upgrade2_0_007() {
+		$GLOBALS['setup_info']['calendar']['currentver'] = '2.0.008';
+		$GLOBALS['phpgw_setup']->db->query("ALTER TABLE phpgw_cal ADD COLUMN organizer character varying(255);"); 
 	    return $GLOBALS['setup_info']['calendar']['currentver'];
 	}
Index: trunk/calendar/setup/phpgw_alarm_es-es.lang
===================================================================
--- trunk/calendar/setup/phpgw_alarm_es-es.lang	(revision 3531)
+++ trunk/calendar/setup/phpgw_alarm_es-es.lang	(revision 5132)
@@ -2,9 +2,9 @@
 Description	calendar	es-es	descripción
 External Participants	calendar	es-es	Participantes Externos
-Category	calendar	es-es	Categoría
+Category	calendar	es-es	Categoria
 Location	calendar	es-es	Lugar
 Start Date/Time	calendar	es-es	Fecha/Hora Inicio
 End Date/Time	calendar	es-es	La fecha/hora de finalización
-Low	calendar	es-es	Baja
+Low	calendar	es-es	Baixa
 Normal	calendar	es-es	Normal
 High	calendar	es-es	Alta
@@ -12,10 +12,7 @@
 Created By	calendar	es-es	Creado por
 Updated	calendar	es-es	Actualizado
-Access	calendar	es-es	Acceso
+Access	calendar	es-es	Acesso
 Groups	calendar	es-es	Grupos
 Participants	calendar	es-es	Participantes
-Alarm for %1 at %2 in %3	calendar	es-es	Alarma para %1 a %2 en el %3
-Here is your requested alarm.	calendar	es-es	Aquí está la alarma solicitada.
-You have a meeting scheduled for %1	calendar	es-es	Usted posee un compromiso agendado para %1.
-Your meeting scheduled for %1 has been canceled	calendar	es-es	Su compromiso agendado para %1 fue cancelado.
-Your meeting that had been scheduled for %1 has been rescheduled to %2	calendar	es-es	Su compromiso que habia sido agendado para %1 fue reagendado para %2
+here is your requested alarm.	calendar	es-es	Aquí está la alarma solicitada.
+Alarm for %1 at %2 in %3	calendar	es-es	Alarma para %1 en %2 in %3
Index: trunk/calendar/inc/class.bocustom_fields.inc.php
===================================================================
--- trunk/calendar/inc/class.bocustom_fields.inc.php	(revision 4316)
+++ trunk/calendar/inc/class.bocustom_fields.inc.php	(revision 5132)
@@ -31,9 +31,5 @@
 			'updated'     => 'Updated',
 			'alarm'       => 'Alarm',
-			'recure_type' => 'Repetition',
-			'observations' => 'Observations',
-			'alter_by'   =>  'Alter by',
-            'attachment' => 'attachment',
-			'notifications_owner' => 'notifications_owner'
+			'recure_type' => 'Repetition'
 		);
 
Index: trunk/calendar/inc/class.uialarm.inc.php
===================================================================
--- trunk/calendar/inc/class.uialarm.inc.php	(revision 204)
+++ trunk/calendar/inc/class.uialarm.inc.php	(revision 5132)
@@ -136,5 +136,9 @@
 				if ($alarm_time <= time())
 				{
-					echo lang('Alarm is older than now!!!');
+					echo	'<center>'.lang('Alarm is older than now!!!').'</center><center>'.
+							'<form method="POST" action="'.$GLOBALS['phpgw']->link('/index.php',Array('menuaction'=>'calendar.uialarm.manager')).'">'.
+							'<input type="hidden" value="'.$this->bo->cal_id.'" name="cal_id">'.
+							'<input type="hidden" value="'.$_POST['return_to'].'" name="return_to">'.
+							'<center><input type="submit" value="'.lang("Back").'"/></center></form></center>' ;
 					$GLOBALS['phpgw']->common->phpgw_exit(True);
 				}
@@ -143,5 +147,9 @@
 					if ($object['time'] == $alarm_time)
 					{
-						echo '<center>'.lang('Alarm already added!!!').'</center>';
+						echo '<center>'.lang("Alarm already added!!!").'</center><center>'.
+							 '<form method="POST" action="'.$GLOBALS['phpgw']->link('/index.php',Array('menuaction'=>'calendar.uialarm.manager')).'">'.
+							 '<input type="hidden" value="'.$this->bo->cal_id.'" name="cal_id">'.
+							 '<input type="hidden" value="'.$_POST['return_to'].'" name="return_to">'.
+							 '<center><input type="submit" value="'.lang("Back").'"/></center></form></center>' ;
 						$GLOBALS['phpgw']->common->phpgw_exit(True);
 					}
@@ -151,4 +159,14 @@
 				{
 					echo '<center>'.lang('You do not have permission to add alarms to this event !!!').'</center>';
+					$GLOBALS['phpgw']->common->phpgw_exit(True);
+				}
+				
+				if ($time == 0)
+				{
+					echo '<center>'.lang("Invalid Alarm!!!").'</center><center>'.
+							 '<form method="POST" action="'.$GLOBALS['phpgw']->link('/index.php',Array('menuaction'=>'calendar.uialarm.manager')).'">'.
+							 '<input type="hidden" value="'.$this->bo->cal_id.'" name="cal_id">'.
+							 '<input type="hidden" value="'.$_POST['return_to'].'" name="return_to">'.
+							 '<center><input type="submit" value="'.lang("Back").'"/></center></form></center>' ;
 					$GLOBALS['phpgw']->common->phpgw_exit(True);
 				}
@@ -189,5 +207,4 @@
 						'data'     => lang('Email Notification'),
 						'owner'    => $GLOBALS['phpgw']->common->grab_owner_name($alarm['owner']),
-						'enabled'  => $this->html->image('calendar',$alarm['enabled']?'enabled':'disabled',$alarm['enabled']?'enabled':'disabled','width="13" height="13"'),
 						'select'   => $this->html->checkbox("alarm[$alarm[id]]")
 					);
@@ -198,6 +215,5 @@
 					$this->output_template_array('rows','list',$var);
 				}
-				$this->template->set_var('enable_button',$this->html->submit_button('enable','Enable'));
-				$this->template->set_var('disable_button',$this->html->submit_button('disable','Disable'));
+
 				if ($to_delete)
 				{
@@ -222,6 +238,4 @@
 					'return_to' => $_POST['return_to']
 				)),
-				'lang_enable'	=> lang('Enable'),
-				'lang_disable'	=> lang('Disable'),
 				'input_cancel'  => $this->html->submit_button('cancel','Cancel')
 			));
Index: trunk/calendar/inc/class.bocalendar.inc.php
===================================================================
--- trunk/calendar/inc/class.bocalendar.inc.php	(revision 4935)
+++ trunk/calendar/inc/class.bocalendar.inc.php	(revision 5132)
@@ -97,6 +97,4 @@
 		);
 
-                var $wdays;
-
                 var $debug = False;
 //		var $debug = True;
@@ -111,9 +109,9 @@
 		var $year;
 		var $prefs;
-
+                var $wdays; 
 		var $owner;
 		var $holiday_color;
 		var $printer_friendly = False;
-
+                var $repetido;
 		var $cached_holidays;
 
@@ -142,4 +140,10 @@
        	var $async = false;
 
+                var $alreadyNotifieds;
+                var $alreadyExtNotifieds = array();
+                
+                var $extAdded;
+                var $extDeleted;
+                
 		function bocalendar($session=0)
 		{
@@ -300,5 +304,5 @@
 				MCAL_RECUR_DAILY	=> 'Daily',
 				MCAL_RECUR_WEEKLY	=> 'Weekly',
-            //MCAL_RECUR_MONTHLY_WDAY	=> 'Monthly (by day)',
+				MCAL_RECUR_MONTHLY_WDAY	=> 'Monthly (by day)',
 				MCAL_RECUR_MONTHLY_MDAY	=> 'Monthly (by date)',
 				MCAL_RECUR_YEARLY	=> 'Yearly'
@@ -382,37 +386,4 @@
                         $this->wdays = Array(MCAL_M_SUNDAY,MCAL_M_MONDAY,MCAL_M_TUESDAY,MCAL_M_WEDNESDAY,
                             MCAL_M_THURSDAY,MCAL_M_FRIDAY,MCAL_M_SATURDAY);
-		}
-
-		function delegar($idDelegador,$idDelegado,$idEvento) {
-
-			$this->so->cal->stream->lock(array("phpgw_cal_user"));
-			
-			if(substr($idDelegado,-1) == 'U') {
-			    $idDelegado = substr($idDelegado,0,-1);
-			}
-
-			$sql = "SELECT * FROM phpgw_cal_user where cal_id=$idEvento and cal_login=$idDelegado";
-
-			if($idDelegado != '')
-			{
-				$this->so->cal->stream->query($sql,__LINE__,__FILE__);
-				if($this->so->cal->stream->next_record())
-				{
-					throw new Exception("The selected User is already included in this event");
-				}else{
-					$sql = "update phpgw_cal_user set cal_login = $idDelegado,cal_status='U' where cal_id=$idEvento 
-						and cal_login=$idDelegador";
-
-					$this->so->cal->stream->query($sql,__LINE__,__FILE__,0,-1,true);
-				
-					$event = $this->so->read_entry($idEvento);
-
-					$this->send_update(MSG_ADDED,array($idDelegado => 'U'),$event,$event);
-				}
-			}else {
-				throw new Exception('999');
-			}
-
-			$this->so->cal->stream->unlock();
 		}
 
@@ -656,5 +627,5 @@
 //				print_debug('exception time',$event['recur_exception'][count($event['recur_exception']) -1]);
 //				print_debug('count event exceptions',count($event['recur_exception']));
-				$this->so->add_entry($event);
+				$this->so->add_entry($event,true,$event['owner']);
 				$cd = 16;
 
@@ -756,5 +727,5 @@
 				if($this->check_perms(PHPGW_ACL_DELETE,$event))
 				{
-					$this->send_update(MSG_DELETED,$event['participants'],$event);
+					$this->send_update(MSG_DELETED,$event['participants'],$event,false,$event['owner']);
 				}
 				else
@@ -815,11 +786,4 @@
                     $participants = $event['participants'];
 
-            //        $new_event = Array();
-            //        $new_event['owner'] = $owner;
-            //        $new_event['participants'] = $participants;
-            //        $new_event['start'] = $event['start'];
-            //        $new_event['end'] = $event['end'];
-            //
-            //        $return[] = $new_event;
 
                     switch($event['recur_type']) {
@@ -998,15 +962,8 @@
 		function update($params='')
 		{
+			$prefix = ( $params['from_mobile'] ? "mobile.ui_mobile" : "calendar.ui" ) . "calendar";
 			
-			if($params['from_mobile']) {
-				$ui_return = "mobile.ui_mobilecalendar.edit";
-				$ui_index = "mobile.ui_mobilecalendar.index";
-				$ui_overlap = "mobile.ui_mobilecalendar.overlap";
-			}
-			else {
-				$ui_return = "calendar.uicalendar.edit";
-				$ui_index = "calendar.uicalendar.index";		
-				$ui_overlap = "calendar.uicalendar.overlap";
-			}
+			$ui_return = "$prefix.edit";
+			$ui_index = "$prefix.index";
 			
 			if(!is_object($GLOBALS['phpgw']->datetime))
@@ -1014,41 +971,14 @@
 				$GLOBALS['phpgw']->datetime = createobject('phpgwapi.date_time');
 			}
-
 			$l_cal = (@isset($params['cal']) && $params['cal']?$params['cal']:$_POST['cal']);
-
-                        $post_max_size = ini_get('post_max_size');
-                        $mul = substr($post_max_size, -1);
-                        $mul = ($mul == 'M' ? 1048576 : ($mul == 'K' ? 1024 : ($mul == 'G' ? 1073741824 : 1)));
-                        if ($_SERVER['CONTENT_LENGTH'] > $mul*(int)$post_max_size && $post_max_size)
-                             $l_cal['attachment'] = 'ERROR';
-
-                        if(count($_FILES['cal']) > 0){
-
-                            if($l_cal['attachment'] != '')
-                               $attachments = unserialize($l_cal['attachment']);
-                            else
-                               $attachments = Array();
-
-                            foreach ($_FILES['cal']['error']['attachment'] as $key => $error) {
-
-                                if ($error == UPLOAD_ERR_OK) {
-
-                                    $new_file= $GLOBALS['phpgw_info']['server']['temp_dir'].'/'.$_SESSION[ 'phpgw_session' ][ 'session_id' ].md5($attachment['name'].microtime());
-                                    move_uploaded_file($_FILES['cal']['tmp_name']['attachment'][$key], $new_file);
-                                    $attach = Array('tmp_name' => $new_file, 'name' => $_FILES['cal']['name']['attachment'][$key], 'type' =>  $_FILES['cal']['type']['attachment'][$key]);
-
-                                    $attachments[] = $attach;
-
-                                }elseif($error == UPLOAD_ERR_INI_SIZE){
-                                    $attachments = 'ERROR';
-                                    break;
-
-                                }
-                            }
-                            $l_cal['attachment'] = $attachments;
-
-                        }
 			$l_participants = (@$params['participants']?$params['participants']:$_POST['participants']);
-			$this->ex_participants = (@$params['ex_participants']?$params['ex_participants']:$_POST['ex_participants']);
+
+                        require_once($_SESSION['rootPath'].'/calendar/inc/class.ex_participants.inc.php');
+                        $this->ex_participants = new exParticipants();
+                        $this->ex_participants->setParticipantsByString(@$params['ex_participants']?$params['ex_participants']:$_POST['ex_participants']);
+
+                        if(@$params['h_exParticipants']?$params['h_exParticipants']:$_POST['h_exParticipants'])
+                             $this->ex_participants->updateAttribBySerializable(@$params['h_exParticipants']?$params['h_exParticipants']:$_POST['h_exParticipants']);
+
 			$l_categories = (@$params['categories']?$params['categories']:$_POST['categories']);
 			$l_start = (@isset($params['start']) && $params['start']?$params['start']:$_POST['start']);
@@ -1083,5 +1013,5 @@
 					}
 				}
-				unset($l_cal['participants']);
+
 
 				if (!is_object($GLOBALS['phpgw']->categories))
@@ -1120,5 +1050,4 @@
 				$event['title'] = stripslashes($event['title']);
 				$event['description'] = stripslashes($event['description']);
-				$event['observations'] = stripslashes($event['observations']);
 				$event['ex_participants'] = stripslashes($event['ex_participants']);
 				$datetime_check = $this->validate_update($event);
@@ -1136,5 +1065,5 @@
 						return;
 				}
-				$overlapping_events = False;
+				//$overlapping_events = False;
 			}
 			else
@@ -1163,5 +1092,5 @@
 				if(!isset($l_cal['ex_participants']))
 				{
-					$l_cal['ex_participants'] = $this->ex_participants;
+					$l_cal['ex_participants'] = $this->ex_participants->getParticipantsSerializable();
 				}
 
@@ -1173,5 +1102,11 @@
 				$is_public = ($l_cal['type'] != 'private' && $l_cal['type'] != 'privateHiddenFields');
 				$this->so->event_init();
+
+                                if($l_cal['uid'])
 				$this->add_attribute('uid',$l_cal['uid']);
+                                else
+                                $this->add_attribute('uid',time().'@Expresso');
+                                
+
 				$this->add_attribute('type',$l_cal['type']);
 				if($l_cal['ex_participants']) {
@@ -1188,7 +1123,4 @@
 				$this->so->set_title($l_cal['title']);
 				$this->so->set_description($l_cal['description']);
-				$this->so->set_observations($l_cal['observations']);
-				$this->so->set_notifications_owner($l_cal['notifications_owner']);
-				$this->so->set_attachment($l_cal['attachment']);
 				$this->so->set_ex_participants($l_cal['ex_participants']);
 				$this->so->set_start($l_start['year'],$l_start['month'],$l_start['mday'],$l_start['hour'],$l_start['min'],0);
@@ -1197,8 +1129,4 @@
 				$this->so->add_attribute('reference',(@isset($l_cal['reference']) && $l_cal['reference']?$l_cal['reference']:0));
 				$this->so->add_attribute('location',(@isset($l_cal['location']) && $l_cal['location']?$l_cal['location']:''));
-				$this->so->add_attribute('repeat',(@isset($l_cal['recur_type']) && $l_cal['recur_type']?$l_cal['recur_type']:''));
-				$this->so->add_attribute('alarmd',(@isset($l_cal['alarmdays'])?$l_cal['alarmdays']:0));
-				$this->so->add_attribute('alarmh',(@isset($l_cal['alarmhours'])?$l_cal['alarmhours']:0));
-				$this->so->add_attribute('alarmm',(@isset($l_cal['alarmminutes'])?$l_cal['alarmminutes']:0));
 				if($l_cal['id'])
 				{
@@ -1222,7 +1150,5 @@
 						$this->so->set_recur_none();
 
-						$repetido = (int)$l_cal['recur_type']; // recebe o tipo de repeticao;
-						$this->so->add_attribute('recur_type',(@isset($repetido) && $repetido?$repetido:0));
-						$this->so->add_attribute('rpt_end_use',(@isset($l_cal['rpt_use_end']) && $l_cal['rpt_use_end']?$l_cal['rpt_use_end']:''));
+						$this->repetido = (int)$l_cal['recur_type']; // recebe o tipo de repeticao;
 
 						break;
@@ -1230,6 +1156,5 @@
 						$this->so->set_recur_daily((int)$l_recur_enddate['year'],(int)$l_recur_enddate['month'],(int)$l_recur_enddate['mday'],(int)$l_cal['recur_interval']);
 
-						$repetido = (int)$l_cal['recur_type']; // recebe o tipo de repeticao;
-						$this->so->add_attribute('recur_type',(@isset($repetido) && $repetido?$repetido:0));
+						$this->repetido = (int)$l_cal['recur_type']; // recebe o tipo de repeticao;
 
 						$tmp_init = explode("/",$_POST['start']['str']); // recebe a data inicial da repeticao;
@@ -1238,5 +1163,4 @@
 						if($l_cal['rpt_use_end'] == 'y') // verifica se foi indicada data final da repeticao, se sim:
 						{
-							$this->so->add_attribute('rpt_end_use',(@isset($l_cal['rpt_use_end']) && $l_cal['rpt_use_end']?$l_cal['rpt_use_end']:''));
 							
 							$tmp_end = explode("/",$_POST['recur_enddate']['str']); // recebe data final da repeticao;
@@ -1250,6 +1174,5 @@
 					case MCAL_RECUR_WEEKLY:
 
-						$repetido = (int)$l_cal['recur_type']; // recebe o tipo de repeticao;
-						$this->so->add_attribute('recur_type',(@isset($repetido) && $repetido?$repetido:0));
+						$this->repetido = (int)$l_cal['recur_type']; // recebe o tipo de repeticao;
 
 						$tmp_init = explode("/",$_POST['start']['str']); // recebe a data inicial da repeticao;
@@ -1259,5 +1182,4 @@
 						{
 
-							$this->so->add_attribute('rpt_end_use',(@isset($l_cal['rpt_use_end']) && $l_cal['rpt_use_end']?$l_cal['rpt_use_end']:''));
 							$tmp_end = explode("/",$_POST['recur_enddate']['str']); // recebe data final da repeticao;
 							$end_rept = mktime($_POST['start']['hour'],$_POST['start']['min'],0,intval($tmp_end[1]),$tmp_end[0],$tmp_end[2]); // transforma a data inicial + hora e minuto de inicio da repeticao em UNIX timestamp;
@@ -1280,5 +1202,4 @@
 							}
 						}
-						$this->so->add_attribute('rpt_wdays',(@isset($rpt_wdays) && $rpt_wdays?$rpt_wdays:''));
 						$this->so->set_recur_weekly((int)$l_recur_enddate['year'],(int)$l_recur_enddate['month'],(int)$l_recur_enddate['mday'],(int)$l_cal['recur_interval'],$l_cal['recur_data']);
 						break;
@@ -1286,6 +1207,5 @@
 						$this->so->set_recur_monthly_mday((int)$l_recur_enddate['year'],(int)$l_recur_enddate['month'],(int)$l_recur_enddate['mday'],(int)$l_cal['recur_interval']);
 
-						$repetido = (int)$l_cal['recur_type']; // recebe o tipo de repeticao;
-						$this->so->add_attribute('recur_type',(@isset($repetido) && $repetido?$repetido:0));
+						$this->repetido = (int)$l_cal['recur_type']; // recebe o tipo de repeticao;
 
 						$tmp_init = explode("/",$_POST['start']['str']); // recebe a data inicial da repeticao;
@@ -1294,5 +1214,5 @@
 						if($l_cal['rpt_use_end'] == 'y') // verifica se foi indicada data final da repeticao, se sim:
 						{
-							$this->so->add_attribute('rpt_end_use',(@isset($l_cal['rpt_use_end']) && $l_cal['rpt_use_end']?$l_cal['rpt_use_end']:''));
+
 							$tmp_end = explode("/",$_POST['recur_enddate']['str']); // recebe data final da repeticao;
 							$end_rept = mktime($_POST['start']['hour'],$_POST['start']['min'],0,intval($tmp_end[1]),$tmp_end[0],$tmp_end[2]); // transforma a data inicial + hora e minuto de inicio da repeticao em UNIX timestamp;
@@ -1309,6 +1229,5 @@
 						$this->so->set_recur_yearly((int)$l_recur_enddate['year'],(int)$l_recur_enddate['month'],(int)$l_recur_enddate['mday'],(int)$l_cal['recur_interval']);
 
-						$repetido = (int)$l_cal['recur_type']; // recebe o tipo de repeticao;
-						$this->so->add_attribute('recur_type',(@isset($repetido) && $repetido?$repetido:0));
+						$this->repetido = (int)$l_cal['recur_type']; // recebe o tipo de repeticao;
 
 						$tmp_init = explode("/",$_POST['start']['str']); // recebe a data inicial da repeticao;
@@ -1317,5 +1236,5 @@
 						if($l_cal['rpt_use_end'] == 'y') // verifica se foi indicada data final da repeticao, se sim:
 						{
-							$this->so->add_attribute('rpt_end_use',(@isset($l_cal['rpt_use_end']) && $l_cal['rpt_use_end']?$l_cal['rpt_use_end']:''));
+
 							$tmp_end = explode("/",$_POST['recur_enddate']['str']); // recebe data final da repeticao;
 							$end_rept = mktime($_POST['start']['hour'],$_POST['start']['min'],0,intval($tmp_end[1]),$tmp_end[0],$tmp_end[2]); // transforma a data inicial + hora e minuto de inicio da repeticao em UNIX timestamp;
@@ -1340,5 +1259,5 @@
 						}
 						$acct_type = $GLOBALS['phpgw']->accounts->get_type((int)$parts[$i]);
-						if($acct_type == 'u')
+						if($acct_type == 'u' || $acct_type == 's')
 						{
 							$part[(int)$parts[$i]] = $accept_type;
@@ -1422,6 +1341,5 @@
 				$event = $this->get_cached_event();
 
-				if ($l_cal['alarmdays'] > 0 || $l_cal['alarmhours'] > 0 ||
-						$l_cal['alarmminutes'] > 0)
+				if ($l_cal['alarmdays'] > 0 || $l_cal['alarmhours'] > 0 ||$l_cal['alarmminutes'] > 0)
 				{
 					$offset = ($l_cal['alarmdays'] * 24 * 3600) +
@@ -1435,5 +1353,5 @@
 						'owner'   => $this->owner,
 						'enabled' => 1,
-						'repeat'  => $repetido, // para repetir alarme;
+						'repeat'  => $this->repetido, // para repetir alarme;
 						'init_rept' => $init_rept, // inicio repeticao;
 						'end_rept' => $end_rept, // fim repeticao;
@@ -1463,4 +1381,96 @@
 				}
 
+			    $overlapping_events = $this->event_overlap( $event, $send_to_ui, $prefix );
+
+			    if( $overlapping_events )
+				return( $overlapping_events );
+			}
+
+				$event['ex_participants'] = $this->ex_participants->getParticipantsSerializable();
+			
+                        if($event['owner'] != $GLOBALS['phpgw_info']['user']['account_id']) $userSend = $event['owner'];
+                        else $userSend = false;
+       
+			if(!$event['id'])
+			{
+                                /** Whenever a recurrent event is edit in a way that a new  
+                                 * exception is created, an exception must be added to 
+                                 * the old event. This is necessary to keep consistency 
+                                 * with synchornization solutions in accordancy to 
+                                 * the iCalendar RFC. 
+                                 */ 
+                                $old_event = $this->so->read_entry($_POST['cal']['reference']); 
+
+                                $date = $_POST['cal']['date']; 
+                                $year  = substr($date,0,4); 
+                                $month = substr($date,4,2); 
+                                $day   = substr($date,6,2); 
+
+                                $exception_time = mktime($old_event['start']['hour'],$old_event['start']['min'],0,$month,$day,$year) - $GLOBALS['phpgw']->datetime->tz_offset; 
+                                $old_event['recur_exception'][] = (int)$exception_time; 
+                                $this->so->add_entry($old_event,false); 
+                            
+                            
+                                $this->so->add_entry($event,false);
+				print_debug('New Event ID',$event['id']);
+                                $send_type = MSG_ADDED;
+			}
+			else
+			{
+				print_debug('Updating Event ID',$event['id']);
+				$new_event = $event;
+				$old_event = $this->read_entry($event['id']);
+				// if old event has alarm and the start-time changed => update them
+				//echo "<p>checking ".count($old_event['alarm'])." alarms of event #$event[id] start moved from ".print_r($old_event['start'],True)." to ".print_r($event['start'],True)."</p>\n";
+				if ($old_event['alarm'] &&
+					$this->maketime($old_event['start']) != $this->maketime($event['start']))
+				{
+					$this->so->delete_alarms($old_event['id']);
+					foreach($old_event['alarm'] as $id => $alarm)
+					{
+						$alarm['time'] = $this->maketime($event['start']) - $alarm['offset'];
+						$event['alarm'][] = $alarm;
+					}
+					//echo "updated alarms<pre>".print_r($event['alarm'],True)."</pre>\n";
+				}
+				$this->so->cal->event = $event;
+				$this->so->add_entry($event,false);
+				$this->prepare_recipients($new_event,$old_event,$userSend);
+                                $send_type = MSG_MODIFIED;
+			}
+                     
+                        //Retira da lista usuarios ja notificados
+                        $to_notify = $event['participants'];
+                        foreach ($this->alreadyNotifieds as $key => $value) 
+                            if(array_key_exists($value,$to_notify))
+                                unset ($to_notify[$value]);
+                        //------------------------------------------------//
+                           
+                        if(count($to_notify) > 0 && $userSend !== -2)    
+                            $this->send_update( $send_type,$to_notify,'',$this->get_cached_event(),$userSend);
+
+			$date = sprintf("%04d%02d%02d",$event['start']['year'],$event['start']['month'],$event['start']['mday']);
+			if($send_to_ui)
+			{
+				$this->read_sessiondata();
+				if ($this->return_to)
+				{
+					$GLOBALS['phpgw']->redirect_link('/index.php','menuaction='.$this->return_to);
+					$GLOBALS['phpgw']->common->phpgw_exit();
+				}
+				Execmethod($ui_index);
+			}
+			else
+			{
+				return (int)$event['id'];
+			}
+
+			return True;
+		}
+
+		function event_overlap( $event, $send_to_ui = false, $prefix = "calendar.uicalendar" ,$user = false)
+		{
+		    $event_ids = array();
+
 				if($event['id'])
 				{
@@ -1472,5 +1482,6 @@
 				}
 
-				if (isset($repetido) and $repetido > 0){
+                    if (isset($this->repetido) and $this->repetido > 0)
+                    { 
                                     $events = $this->expand_repetition($event);
                                     $overlapping_events = False;
@@ -1492,5 +1503,6 @@
                                     }
                                 }
-                                else {
+                    else 
+                    { 
                                     $overlapping_events = $this->overlap(
                                         $this->maketime($event['start']),
@@ -1501,78 +1513,28 @@
                                     );
                                 }
-			}
-			if(!$this->ex_participants)
-				$this->ex_participants = $event['ex_participants'];			
+                                      
 			if($overlapping_events)
 			{
+                            $this->store_to_appsession( $event );
 				if($send_to_ui)
 				{
-					$event['ex_participants'] = $this->ex_participants;
 					unset($GLOBALS['phpgw_info']['flags']['noheader']);
 					unset($GLOBALS['phpgw_info']['flags']['nonavbar']);
-					ExecMethod($ui_overlap,
+				    ExecMethod("$prefix.overlap",
 						Array(
 							'o_events'	=> $overlapping_events,
-							'this_event'	=> $event
+						    'this_event'	=> $event,
+                                                    'this_account' => $user
 						)
 					);
-					if(!$params['from_mobile'])
+
+				    if( $prefix === "calendar.uicalendar" )
 						$GLOBALS['phpgw']->common->phpgw_exit(True);
-					else
-						return;
-				}
-				else
-				{
-					return $overlapping_events;
-				}
-			}
-			else
-			{
-				if(!$event['id'])
-				{
-					$this->so->add_entry($event);
-					$this->send_update(MSG_ADDED,$event['participants'],'',$this->get_cached_event());
-					print_debug('New Event ID',$event['id']);
-				}
-				else
-				{
-					print_debug('Updating Event ID',$event['id']);
-					$new_event = $event;
-					$old_event = $this->read_entry($event['id']);
-					// if old event has alarm and the start-time changed => update them
-					//echo "<p>checking ".count($old_event['alarm'])." alarms of event #$event[id] start moved from ".print_r($old_event['start'],True)." to ".print_r($event['start'],True)."</p>\n";
-					if ($old_event['alarm'] &&
-						$this->maketime($old_event['start']) != $this->maketime($event['start']))
-					{
-						$this->so->delete_alarms($old_event['id']);
-						foreach($old_event['alarm'] as $id => $alarm)
-						{
-							$alarm['time'] = $this->maketime($event['start']) - $alarm['offset'];
-							$event['alarm'][] = $alarm;
-						}
-						//echo "updated alarms<pre>".print_r($event['alarm'],True)."</pre>\n";
-					}
-					$this->so->cal->event = $event;
-					$this->so->add_entry($event);
-					$this->prepare_recipients($new_event,$old_event);
-				}
-
-				$date = sprintf("%04d%02d%02d",$event['start']['year'],$event['start']['month'],$event['start']['mday']);
-				if($send_to_ui)
-				{
-					$this->read_sessiondata();
-					if ($this->return_to)
-					{
-						$GLOBALS['phpgw']->redirect_link('/index.php','menuaction='.$this->return_to);
-						$GLOBALS['phpgw']->common->phpgw_exit();
-					}
-					Execmethod($ui_index);
-				}
-				else
-				{
-					return (int)$event['id'];
-				}
-			}
-			return True;
+				}
+
+			    return( $overlapping_events );
+			}
+
+		    return( false );
 		}
 
@@ -1700,57 +1662,13 @@
 				$error = 43;
 			}
-			elseif ($event['type'] != 'hourAppointment' && $event['title'] == '')
+			elseif ($event['title'] == '')
 			{
 				$error = 40;
 			}
-			elseif ($event['repeat'] != 0)
-			{
-				if( $event['rpt_end_use'] != 'y')
-				{
-					$error = 46;
-				}
-			//}
-			  if ($event['repeat'] == 2)
-			  {
-    				if($event['rpt_wdays'] == '') {
-        				$error = 44;
-            			}
-				if( $event['rpt_end_use'] != 'y')
-				{
-					$error = 46;
-				}
-
-                    		if (  ( isset($event['alarmd'])  && ($event['alarmd'] != 0) ) || ( isset($event['alarmh'])  && ($event['alarmh'] != 0) ) || ( isset($event['alarmm'])  && ($event['alarmm'] != 0) ) )
-                    		{
-		                    	if( isset($event['recur_type']) && ($event['recur_type'] != 0) )
-                    			{
-		                    		if( $event['rpt_end_use'] != 'y')
-	                    			{
-		                    			$error = 45;
-                		    		}
-                    			}
-                    		}
-			   }
-
-			//}
-		  if (  ( isset($event['alarmd'])  && ($event['alarmd'] != 0) ) || ( isset($event['alarmh'])  && ($event['alarmh'] != 0) ) || ( isset($event['alarmm'])  && ($event['alarmm'] != 0) ) )
-                  {
-                	if( isset($event['recur_type']) && ($event['recur_type'] != 0) )
-                	{
-                		if( $event['rpt_end_use'] != 'y')
-                		{
-                			$error = 45;
-                		}
-                	}
-                  }
-		}
 			elseif (($GLOBALS['phpgw']->datetime->time_valid($event['start']['hour'],$event['start']['min'],0) == False) || ($GLOBALS['phpgw']->datetime->time_valid($event['end']['hour'],$event['end']['min'],0) == False))
 			{
 				$error = 41;
 			}
-			elseif (($GLOBALS['phpgw']->datetime->date_valid($event['start']['year'],$event['start']['month'],$event['start']['mday']) == False) 
-				|| ($GLOBALS['phpgw']->datetime->date_valid($event['end']['year'],$event['end']['month'],$event['end']['mday']) == False)
-				|| ($GLOBALS['phpgw']->datetime->date_compare($event['start']['year'],$event['start']['month'],$event['start']['mday'],$event['end']['year'],$event['end']['month'],$event['end']['mday']) == 1)
-				|| $event['start']['year'] > 2037 || $event['end']['year'] > 2037)
+			elseif (($GLOBALS['phpgw']->datetime->date_valid($event['start']['year'],$event['start']['month'],$event['start']['mday']) == False) || ($GLOBALS['phpgw']->datetime->date_valid($event['end']['year'],$event['end']['month'],$event['end']['mday']) == False) || ($GLOBALS['phpgw']->datetime->date_compare($event['start']['year'],$event['start']['month'],$event['start']['mday'],$event['end']['year'],$event['end']['month'],$event['end']['mday']) == 1))
 			{
 				$error = 42;
@@ -1758,12 +1676,9 @@
 			elseif ($GLOBALS['phpgw']->datetime->date_compare($event['start']['year'],$event['start']['month'],$event['start']['mday'],$event['end']['year'],$event['end']['month'],$event['end']['mday']) == 0)
 			{
-				if ( ($GLOBALS['phpgw']->datetime->time_compare($event['start']['hour'],$event['start']['min'],0,$event['end']['hour'],$event['end']['min'],0) == 1)
-                                   ||($GLOBALS['phpgw']->datetime->time_compare($event['start']['hour'],$event['start']['min'],0,$event['end']['hour'],$event['end']['min'],0) == 0) )
-				{
-					$error = 47;
-				}
-			}
-                        if($event['attachment'] == 'ERROR')
-                            $error = 99;
+				if ($GLOBALS['phpgw']->datetime->time_compare($event['start']['hour'],$event['start']['min'],0,$event['end']['hour'],$event['end']['min'],0) == 1)
+				{
+					$error = 42;
+				}
+			}
                         
 			return $error;
@@ -1789,16 +1704,4 @@
 		}
 		
-		function participants_unanswered($participants,$event)
-		{
-			foreach($participants as $uid => $status)
-			{				
-				if (isset($event['participants'][$uid]) && $event['participants'][$uid] == 'U' && $status == 'U')
-				{
-					return False;
-				}
-			}
-			return True;
-		}
-
 		function overlap($starttime,$endtime,$participants,$owner=0,$id=0,$restore_cache=False)
 		{
@@ -1909,5 +1812,5 @@
 								$temp_start_time >= $temp_event_start &&
 								$temp_end_time <= $temp_event_end) &&
-								$this->participants_not_rejected($participants,$event) && $this->participants_unanswered($participants,$event))
+								$this->participants_not_rejected($participants,$event))
 							{
 								if($this->debug)
@@ -2080,5 +1983,9 @@
 		function get_short_field($event,$is_private=True,$field='')
 		{
-			if($is_private)
+			if($is_private && $event['type'] == 'E')
+			{
+				return lang('Restrict');
+			}
+			else if($is_private && $event['type'] == 'P')
 			{
 				return lang('private');
@@ -2342,5 +2249,5 @@
 			$search_date_day = date('d',$datetime);
 			$search_date_dow = date('w',$datetime);
-			$search_beg_day = mktime(12,0,0,$search_date_month,$search_date_day,$search_date_year);
+			$search_beg_day = mktime(0,0,0,$search_date_month,$search_date_day,$search_date_year);
 			if($this->debug)
 			{
@@ -2409,5 +2316,5 @@
 							break;
 						case MCAL_RECUR_WEEKLY:
-							if (floor(($search_beg_day - $event_beg_day)/604800)  % ($freq ? $freq : 1))
+							if ((floor($search_beg_day / 604800) - floor($event_beg_day / 604800)) % $freq)
 							{
 								continue;
@@ -2934,5 +2841,5 @@
 		@abstract set the participant response $status for event $cal_id and notifies the owner of the event
 		*/
-		function set_status($cal_id,$status)
+		function set_status($cal_id,$status,$user = false)
 		{
 			$status2msg = array(
@@ -2946,13 +2853,24 @@
 			}
 			$event = $this->so->read_entry($cal_id);
-			$account_id = $GLOBALS['phpgw_info']['user']['account_id'];
+                        if($user) $account_id = $user;
+                        else $account_id = $GLOBALS['phpgw_info']['user']['account_id'];
 			if(($status2msg[$status] == "5" && $event['participants'][$account_id] == "A") ||
 			 ($status2msg[$status] == "3" && $event['participants'][$account_id] == "R")) {
 				return True;
 			}
-			$this->so->set_status($cal_id,$status);
+			$this->so->set_status($cal_id,$status,$account_id);
 			$event = $this->so->read_entry($cal_id);
-			$this->send_update($status2msg[$status],$event['participants'],$event);
-
+			$this->send_update($status2msg[$status],$event['participants'],$event,false,$account_id);
+
+			$sts = array_values( $event['participants'] );
+
+			//verifica se todos os participantes rejeitaram o evento
+			while( $sts[0] && $sts[0] === 'R' ) array_pop( $sts );
+
+			if( empty( $sts ) )
+			{
+				$this->so->delete_entry( $cal_id );
+				$this->so->expunge();
+			}
 		}
 
@@ -3015,79 +2933,388 @@
 		}
 
-		function create_vcard($event_arrays)
-		{
+
+		function create_vcard($event_arrays , $metodo = 'PUBLISH', $externo = false,$importAccount = false)
+		{
+                    if(!$importAccount)
+                        $importAccount['mail'] = $GLOBALS['phpgw_info']['user']['email'];
+
             if(!is_array($event_arrays))
 				return null;
 
-                        $sender = $GLOBALS['phpgw_info']['user']['email'];
-                        $uid_dono = $GLOBALS['phpgw_info']['user']['account_lid'];
-			$tmpattach="BEGIN:VCALENDAR\n"
-			."PRODID:-//Expresso Livre//Calendar//EN\n"
-			."VERSION:1.0\n";
-            foreach ($event_arrays as $event)
-            {
-				// It translates int to string
-				if (!is_object($event) && !is_array($event) || !array_key_exists  ('end', $event))
-					$event = $event_arrays;
-
-				//set to GMT
-				//Aqui estou pegando o horário do evento e setando para GMT de acordo com o fuso horário estabelecido nas configurações do expresso.
-				$start_time = mktime($event['start']['hour'],$event['start']['min'],$event['start']['sec'],$event['start']['month'],$event['start']['mday'],$event['start']['year']) - $GLOBALS['phpgw']->datetime->tz_offset;
-				$end_time = mktime($event['end']['hour'],$event['end']['min'],$event['end']['sec'],$event['end']['month'],$event['end']['mday'],$event['end']['year']) - $GLOBALS['phpgw']->datetime->tz_offset;
-				
-				$start_time = date("Ymd\THis\Z", $start_time);
-				$end_time = date("Ymd\THis\Z", $end_time);
+                    $tmpattach="BEGIN:VCALENDAR\r\n"
+                        ."PRODID:-//Expresso Livre//Calendar//EN\r\n"
+                        ."VERSION:2.0\r\n"
+                        ."CALSCALE:GREGORIAN\r\n"
+                        ."METHOD:".$metodo."\r\n";
+
+		    //$offset = ((int)substr(date('O',$GLOBALS['phpgw']->datetime->users_localtime), 0, 3));
+		    $offset = (($GLOBALS['phpgw']->datetime->tz_offset)/60)/60;
 	
-				// Necessário espaços após quebra-de-linha, na descrição, caso contrário 
-				// ocorrerá erro ao importar o agendamento no Outlook (erro lunar).
-				$description = str_replace("\n","\n ", $event['description']);
-				
-				$tmpattach.="BEGIN:VEVENT\r\n"
-				."DTSTART:".$start_time."\r\n"
-				."DTEND:".$end_time."\r\n"
+                        foreach ($event_arrays as $event_array)
+                        {
+                            $sy = $event_array['start']['year'];
+                            $sm = $event_array['start']['month'];
+                            $sd = $event_array['start']['mday'];
+                            $sh = $event_array['start']['hour'] -= $offset;
+                            $sn = $event_array['start']['min'];
+                            $dtstart = sprintf("%04d%02d%02dT%02d%02d00Z", $sy, $sm, $sd, $sh, $sn);
+
+                            $ey = $event_array['end']['year'];
+                            $em = $event_array['end']['month'];
+                            $ed = $event_array['end']['mday'];
+                            $eh = $event_array['end']['hour'] -= $offset;
+                            $en = $event_array['end']['min'];
+                            $dtend = sprintf("%04d%02d%02dT%02d%02d00Z", $ey, $em, $ed, $eh, $en);
+
+                            // NecessÃ¡rio espaÃ§os apÃ³s quebra-de-linha, na descriÃ§Ã£o, caso contrÃ¡rio
+                            // ocorrerÃ¡ erro ao importar o agendamento no Outlook (erro lunar).
+                            $description = str_replace("\n","\n ",$event_array['description']);
+                            $tmpattach.="BEGIN:VEVENT\r\n";
+							
+							if(isset($event_array['organizer']) && $event_array['owner'] != -2)
+							{
+                                $ldap = $this->getLdap();  
+                                $justthese = array("mail","cn");
+                                $filter="(&(|(phpgwAccountType=u)(phpgwAccountType=l)(phpgwAccountType=s)(phpgwAccountType=i))(uidNumber=".$event_array['owner']."))";
+                                $search = ldap_search($ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
+                                $entry = ldap_get_entries($ldap, $search);                                        
+								$organizer = 'ORGANIZER;CN='.$entry[0]['cn'][0].':mailto:'.$entry[0]['mail'][0]."\r\n";
+							}   
+							else{   
+								$email = explode('&lt;', $event_array['organizer']);
+								$email2 = explode('&gt;', $email[1]);
+                                $organizer = 'ORGANIZER;CN='.rtrim($email[0]).':mailto:'.$email2[0]."\r\n";
+							}
+								 
+                            if(!$externo)
+                            {
+							    $tmpattach.=
+                                "DTSTART:".$dtstart."\r\n"
+                                ."DTEND:".$dtend."\r\n"
 				."LAST-MODIFIED:".gmdate("Ymd\THis\Z")."\r\n" //Hora no formato UTC
-				//."UID:Expresso-".$event['id'].$event['uid']."\r\n"
-                                ."UID:Expresso-".$event[id]."@".$uid_dono."\n"
+								.$organizer
+                                ."UID:".$event_array['uid']."\r\n"
+								.$this->mb_wordwrap($this->getvCalendarParticipants($event_array['participants'],$event_array['id']),74,"\r\n ")
+								.$this->mb_wordwrap($this->getvCalendarExternalParticipants($event_array['id']),74,"\r\n ")
 				."DESCRIPTION:".$description."\r\n"
-				."SUMMARY:".$event['title']."\r\n"
-				."LOCATION:".$event['location']."\r\n"
-				."ORGANIZER:mailto:".$sender."\n";
-                                $expart=preg_split('/,/', $event['ex_participants']);
-
-                                foreach ($expart as $mail)
+                                ."SUMMARY:".$event_array['title']."\r\n"
+                                ."LOCATION:".$event_array['location']."\r\n"
+                                ."END:VEVENT\r\n";
+                            }
+                             else
+                            {
+								$tmpattach.=
+                                "DTSTART:".$dtstart."\r\n"
+                                ."DTEND:".$dtend."\r\n"
+                                ."DTSTAMP:".gmdate("Ymd\THis\Z")."\r\n" //Hora no formato UTC
+                                .$organizer
+                                .$this->mb_wordwrap("UID:".$event_array['uid']."\r\n",74,"\r\n ");
+
+                                switch ($metodo) {
+                                    case 'PUBLISH':
+                                          $tmpattach.=
+                                             $this->mb_wordwrap($this->getvCalendarParticipants($event_array['participants'],$event_array['id']),74,"\r\n ")
+											.$this->mb_wordwrap($this->getvCalendarExternalParticipants($event_array['id']),74,"\r\n ")
+                                            .$this->mb_wordwrap("DESCRIPTION:".$description."\r\n",74,"\r\n ")
+                                            .$this->mb_wordwrap("SUMMARY:".$event_array['title']."\r\n",74,"\r\n ")
+                                            .$this->mb_wordwrap("LOCATION:".$event_array['location']."\r\n",74,"\r\n ");
+                                        break;
+                                    case 'REPLY':
+                                            $tmpattach.=
+                                             $this->mb_wordwrap("ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=ACCEPTED;X-NUM-GUESTS=0:mailto:".$importAccount['mail']."\r\n",74,"\r\n ")
+                                            .'DESCRIPTION:\n'."\r\n"
+                                            .$this->mb_wordwrap("LAST-MODIFIED:".gmdate("Ymd\THis\Z")."\r\n",74,"\r\n ") //Hora no formato UTC
+                                            .$this->mb_wordwrap("LOCATION:".$event_array['location']."\r\n",74,"\r\n ")
+                                            ."SEQUENCE:0\r\n"
+                                            ."STATUS:CONFIRMED\r\n"
+                                            .$this->mb_wordwrap("SUMMARY:".$event_array['title']."\r\n",74,"\r\n ")
+                                            ."TRANSP:OPAQUE\r\n";
+                                        break;
+                                    default:
+                                           $tmpattach.=
+                                             "DESCRIPTION:".$description."\r\n"
+                                            ."SUMMARY:".$event_array['title']."\r\n"
+                                            ."LOCATION:".$event_array['location']."\r\n";
+                                        break;
+                                }
+                                  $tmpattach.= "END:VEVENT\r\n";
+                            }
+                            
+                        }
+                    $tmpattach.="END:VCALENDAR\r\n\r\n\r\n";
+                    return $tmpattach;
+		}
+
+                function mb_wordwrap($str, $width=74, $break="\r\n")
+                {
+                    // Return short or empty strings untouched
+                    if(empty($str) || mb_strlen($str, 'ISSO-8859-1') <= $width)
+                        return $str;
+
+                    $br_width  = mb_strlen($break, 'ISSO-8859-1');
+                    $str_width = mb_strlen($str, 'ISSO-8859-1');
+                    $return = '';
+                    $last_space = false;
+
+                    for($i=0, $count=0; $i < $str_width; $i++, $count++)
+                    {
+                        // If we're at a break
+                        if (mb_substr($str, $i, $br_width, 'ISSO-8859-1') == $break)
+                        {
+                            $count = 0;
+                            $return .= mb_substr($str, $i, $br_width, 'ISSO-8859-1');
+                            $i += $br_width - 1;
+                            continue;
+                        }
+
+                        // Keep a track of the most recent possible break point
+                        if(mb_substr($str, $i, 1, 'ISSO-8859-1') == " ")
+                        {
+                            $last_space = $i;
+                        }
+
+                        // It's time to wrap
+                        if ($count > $width)
                                 {
-                                    if($mail != "")
+                            // There are no spaces to break on!  Going to truncate :(
+                            if(!$last_space)
                                     {
-                                        $tmpattach.="ATTENDEE;RSVP=TRUE;PARTSTAT=NEEDS-ACTION;ROLE=REQ-PARTICIPANT:mailto:".$mail."\n";
+                                $return .= $break;
+                                $count = 0;
+                            }
+                            else
+                            {
+                                // Work out how far back the last space was
+                                $drop = $i - $last_space;
+
+                                // Cutting zero chars results in an empty string, so don't do that
+                                if($drop > 0)
+                                {
+                                    $return = mb_substr($return, 0, -$drop);
+                                }
+
+                                // Add a break
+                                $return .= $break;
+
+                                // Update pointers
+                                $i = $last_space + ($br_width - 1);
+                                $last_space = false;
+                                $count = 0;
                                     }
                                 }
                                 
-                                while (list($id,$status) = each($event['participants']))
+                        // Add character from the input string to the output
+                        $return .= mb_substr($str, $i, 1, 'ISSO-8859-1');
+                    }
+                    return $return;
+                }
+
+                function getvCalendarParticipants($pExtParticipants,$pCalId)
                                 {
-
-                                      $preferences = CreateObject('phpgwapi.preferences',$id);
-                                      $mail = $preferences->email_address($id);
-                                      if ( $sender != $mail)
+                    $participants = explode(',', $pExtParticipants);
+                    $return = '';
+
+                    foreach ($participants as $participant)
                                       {
-                                         if($status == 'U' ){
-                                                  $tmpattach.="ATTENDEE;RSVP=TRUE;PARTSTAT=NEEDS-ACTION;ROLE=REQ-PARTICIPANT:mailto:".$mail."\n";
+                        $array = explode('"', $participant);
+                        $mail = str_replace('<','', str_replace('>','',$array['2']));
+                        if($mail && $array['1'])
+                             $return .= 'ATTENDEE;CN='.$array['1'].';RSVP=TRUE:mailto:'.$mail."\r\n";
+                    }
+                    $db = $this->getDb();
+                    $db->query('SELECT cal_login FROM phpgw_cal_user WHERE cal_id = '.$pCalId);
+                    $parts = array();
+                    while($db->next_record())
+                        array_push($parts, $db->row());
+
+                    $ldap = $this->getLdap();
+                    foreach ($parts as $part)
+                    {
+                        $justthese = array('mail','cn');
+                        $filter="(&(|(phpgwAccountType=u)(phpgwAccountType=l))(uidNumber=".$part['cal_login']."))";
+                        $search = ldap_search($ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
+                        $entry = ldap_get_entries($ldap, $search);
+                        $return .= 'ATTENDEE;CN='.$entry[0]['cn'][0].';RSVP=TRUE:mailto:'.$entry[0]['mail'][0]."\r\n";
                                                         }
-                                         elseif($status == 'A' ){
-                                                 $tmpattach.="ATTENDEE;RSVP=TRUE;PARTSTAT=ACCEPTED;ROLE=REQ-PARTICIPANT:mailto:".$mail."\n";
+
+                    return $return;
                                                         }
-                                         elseif($status == 'T' ){
-                                                 $tmpattach.="ATTENDEE;RSVP=TRUE;PARTSTAT=TENTATIVE;ROLE=REQ-PARTICIPANT:mailto:".$mail."\n";
+				
+                function getCalendarParticipantsArray($pCalId)
+                {
+                    $db = $this->getDb();
+                    $db->query('SELECT cal_login FROM phpgw_cal_user WHERE cal_id = '.$pCalId);
+                    $parts = array();
+                    while($db->next_record())
+                        array_push($parts, $db->row());
+
+                    $ldap = $this->getLdap();
+                    foreach ($parts as $part)
+                    {
+                        $justthese = array('mail','cn');
+                        $filter="(&(|(phpgwAccountType=u)(phpgwAccountType=l))(uidNumber=".$part['cal_login']."))";
+                        $search = ldap_search($ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
+                        $entry = ldap_get_entries($ldap, $search);
+                        $return [$entry[0]['mail'][0]] = array( 'CN'=> $entry[0]['cn'][0],'RSVP'=> 'TRUE' ,'ROLE' => 'REQ-PARTICIPANT');
+                    }
+                    return $return;
+                }
+
+                function getvCalendarExternalParticipants($pCalId)
+                {
+
+                    $db = $this->getDb();
+                    $sql = "SELECT ex_participants FROM phpgw_cal WHERE cal_id = '$pCalId'";
+                                $db->query($sql);
+                                
+                    $parts = array();
+                    while($db->next_record())
+                        array_push($parts, $db->row());
+
+					$participants = explode(',', $parts[0]['ex_participants']);
+                    $return = '';
+					
+					$participants = unserialize(base64_decode($parts[0]['ex_participants']));
+
+                    foreach ($participants as $participant)
+                    {	
+                           $part = array();
+
+                           if(preg_match("(\"[^\"]*\"[ ]*<[^>]*@[^>]*>)", $participant['mail']))
+                           {
+                              $cn = null;
+                              $mail = null;
+                              preg_match ("(\"([^\"]*)\")", $participant['mail'], $cn);
+                              preg_match ('(<([^>]*@[^>]*)>)', $participant['mail'], $mail);
+
+                              if($mail[1])
+                              $part['mail'] =  $mail[1];
+
+                              if($cn[1])
+                                $part['cn'] =  $cn[1];
+
                                                          }
                                          else
+                           if(preg_match("(<[^>]*@[^>]*>)", $participant['mail']))
                                                   {
-                                                     $tmpattach.="ATTENDEE;RSVP=TRUE;PARTSTAT=DECLINED;ROLE=REQ-PARTICIPANT:mailto:".$mail."\n";
+                              $mail = null;
+                              preg_match ('(<([^>]*@[^>]*)>)', $participant['mail'], $mail);
+                              if($mail[1])
+                                $part['mail'] =  $mail[1];
+
                                                    }
+                           else
+                           if(preg_match("([^ ]*@[^ ]*)", $participant['mail']))
+                           {
+                              $mail = null;
+                              preg_match ('([^ ]*@[^ ]*)', $participant['mail'], $mail);
+                              if($mail[0])
+                                $part['mail'] =  $mail[0];
+
+                           }
+
+                          if(count($part) > 0)
+                          {
+                              if($part['cn']) 
+								$return .= 'ATTENDEE;CN='.$part['cn'].';RSVP=TRUE:mailto:'.$part['mail']."\r\n";
+                              else 
+								$return .= 'ATTENDEE;RSVP=TRUE:mailto:'.$part['mail']."\r\n";  
+                             
                                       }
                                 }
-                                $tmpattach.="END:VEVENT"."\n";
-                                //."END:VEVENT\r\n";
-			}
-                    $tmpattach.="END:VCALENDAR\r\n";
-                    return $tmpattach;
+
+                    return $return;
+			}
+
+
+                function getDb()
+                {
+                    include_once('../phpgwapi/inc/class.db.inc.php');
+                    // Conecta ao banco de dados
+                    if (is_array($_SESSION['phpgw_info']['expresso']['server']))
+                        $GLOBALS['phpgw_info']['server'] = $_SESSION['phpgw_info']['expresso']['server'];
+                    else
+                        $_SESSION['phpgw_info']['expresso']['server'] = $GLOBALS['phpgw_info']['server'];
+
+                    $db = new db();
+                    $db->Halt_On_Error = 'no';
+                    $db->connect(
+                                $_SESSION['phpgw_info']['expresso']['server']['db_name'],
+                                $_SESSION['phpgw_info']['expresso']['server']['db_host'],
+                                $_SESSION['phpgw_info']['expresso']['server']['db_port'],
+                                $_SESSION['phpgw_info']['expresso']['server']['db_user'],
+                                $_SESSION['phpgw_info']['expresso']['server']['db_pass'],
+                                $_SESSION['phpgw_info']['expresso']['server']['db_type']
+                                );
+                                // Fim Conecta Banco de dados
+                    return $db;
+                }
+
+                function getLdap()
+                {
+                    require_once($_SESSION['rootPath'].'/header.inc.php');
+                    require_once($_SESSION['rootPath'].'/phpgwapi/inc/class.common.inc.php');
+   
+                    $common = new common();
+                                
+                    if ( (!empty($GLOBALS['phpgw_info']['server']['ldap_master_host'])) &&
+                        (!empty($GLOBALS['phpgw_info']['server']['ldap_master_root_dn'])) &&
+                        (!empty($GLOBALS['phpgw_info']['server']['ldap_master_root_pw'])) )
+                        {
+                            $ldap = $common->ldapConnect($GLOBALS['phpgw_info']['server']['ldap_master_host'],
+                                                         $GLOBALS['phpgw_info']['server']['ldap_master_root_dn'],
+                                                         $GLOBALS['phpgw_info']['server']['ldap_master_root_pw']);
+                        }
+                        else
+                        {
+                            $ldap = $common->ldapConnect();
+                        }
+                       
+                    return $ldap;
+                }
+
+                function getvCalendarOrganizer($pOrganizer)
+                {
+
+                    
+                       $organizer = array();
+       
+                       if(preg_match("(\"[^\"]*\"[ ]*<[^>]*@[^>]*>)", $pOrganizer))
+                       {
+                          $cn = null;
+                          $mail = null;
+                          preg_match ("(\"([^\"]*)\")", $pOrganizer, $cn);
+                          preg_match ('(<([^>]*@[^>]*)>)', $pOrganizer, $mail);
+
+                          if($mail[1])
+                          $organizer['mail'] =  $mail[1];
+
+                          if($cn[1])
+                            $organizer['cn'] =  $cn[1];
+
+                       }
+                       else
+                       if(preg_match("(<[^>]*@[^>]*>)", $pOrganizer))
+                       {
+                          $mail = null;
+                          preg_match ('(<([^>]*@[^>]*)>)', $pOrganizer, $mail);
+                          if($mail[1])
+                            $organizer['mail'] =  $mail[1];
+
+                       }
+                       else
+                       if(preg_match("([^ ]*@[^ ]*)", $pOrganizer))
+                       {
+                          $mail = null;
+                          preg_match ('([^ ]*@[^ ]*)', $pOrganizer, $mail);
+                          if($mail[0])
+                            $organizer['mail'] =  $mail[0];
+
+                       }
+                       
+                       if($organizer['cn']) $return = 'ORGANIZER;CN="'.$organizer['cn'].'":MAILTO:'.$organizer['mail']."\r\n";
+                       else $return = 'ORGANIZER;MAILTO:'.$organizer['mail']."\r\n";
+                       
+                    return $return;
 		}
 
@@ -3101,35 +3328,41 @@
 		@param $new_event Event after the change
 		*/
-		function send_update($msg_type,$to_notify,$old_event,$new_event=False,$user=False)
-		{			
-			if (!is_array($to_notify))
-			{
-				$to_notify = array();
-			}
+		function send_update($msg_type,$to_notify,$old_event,$new_event = False, $user = False)
+			{
+          
+                        if (!is_array($to_notify)) $to_notify = array();
 			$owner = $old_event ? $old_event['owner'] : $new_event['owner'];
-			if ($owner && !isset($to_notify[$owner]) && $msg_type != MSG_ALARM)
-			{
-				$to_notify[$owner] = 'owner';	// always include the event-owner
-			}
+
+                        if($owner === -2)
+                            $to_notify[-2] = 'A'; 
+
 			$version = $GLOBALS['phpgw_info']['apps']['calendar']['version'];
-
 			$GLOBALS['phpgw_info']['user']['preferences'] = $GLOBALS['phpgw']->preferences->create_email_preferences();
-
-		    $preferences = CreateObject('phpgwapi.preferences',(int)$this->owner); 
- 		    $GLOBALS['phpgw']->accounts->get_account_name((int)$owner,$lid,$fname,$lname); 
  		 
-			if($new_event['notifications_owner'] == '1'){ 
- 		        $sender = $preferences->email_address((int)$owner); 
- 		        $sender_name = $fname.' '.$lname; 
- 		    }else{ 
- 		        $sender = $GLOBALS['phpgw_info']['user']['email']; 
- 		        $sender_name = $GLOBALS['phpgw_info']['user']['fullname']; 
+                        /*
+                         * Caso o evento seja de uma conta compartilha busca obusca o cn e o email da conta
+                         */ 
+                        if($user)
+                        {
+                            $ldap = $this->getLdap();  
+                            $justthese = array("mail","cn");
+                            $filter="(&(|(phpgwAccountType=u)(phpgwAccountType=l)(phpgwAccountType=s)(phpgwAccountType=i))(uidNumber=".$user."))";
+                            $search = ldap_search($ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
+                            $entry = ldap_get_entries($ldap, $search);
+                            $sMail = $entry[0]['mail'][0];
+                            $sCN = $entry[0]['cn'][0];
+                            $sUN = $user;
  		        } 
+                        else
+                        {
+                            $sMail = $GLOBALS['phpgw_info']['user']['email'];
+                            $sCN = $GLOBALS['phpgw_info']['user']['fullname'];
+                            $sUN = $GLOBALS['phpgw_info']['user']['account_id'];
+                        }
+                        //------------------------------------------------------------------------------------//
  		 
  		    $temp_tz_offset = $this->prefs['common']['tz_offset'];
-			
 			$temp_timeformat = $this->prefs['common']['timeformat'];
 			$temp_dateformat = $this->prefs['common']['dateformat'];
-
 			$tz_offset = ((60 * 60) * (int)$temp_tz_offset);
 
@@ -3138,16 +3371,11 @@
 				$t_old_start_time = $this->maketime($old_event['start']);
 				if($t_old_start_time < (time() - 86400))
-				{
 					return False;
 				}
-			}
 
 			$temp_user = $GLOBALS['phpgw_info']['user'];
-
-			if (!$user)
-			{
-				$user = $this->owner;
-			}
+			if (!$user) $user = $this->owner;
 			$GLOBALS['phpgw_info']['user']['preferences'] = $GLOBALS['phpgw']->preferences->create_email_preferences($user);
+                        $this->prefs = $GLOBALS['phpgw_info']['user']['preferences'];
 
 			$event = $msg_type == MSG_ADDED || $msg_type == MSG_MODIFIED ? $new_event : $old_event;
@@ -3216,7 +3444,6 @@
 			$notify_msg = $this->prefs['calendar']['notify'.$msg];
 			if (empty($notify_msg))
-			{
 				$notify_msg = $this->prefs['calendar']['notifyAdded'];	// use a default
-			}
+			
 			$details = array(			// event-details for the notify-msg
 				'id'          => $msg_type == MSG_ADDED ? $new_event['id'] : $old_event['id'],
@@ -3252,9 +3479,9 @@
 			$mail->Host = $emailadmin['smtpServer'];
 			$mail->Port = $emailadmin['smtpPort'];
-			$mail->From = $GLOBALS['phpgw']->preferences->values['email'];
-			$mail->FromName = $GLOBALS['phpgw_info']['user']['fullname'];
-			//$mail->IsHTML(true);
-                        $mail->IsCalendar(true);
-
+			$mail->From = $sMail;
+			$mail->FromName = $sCN;
+			$mail->IsHTML(true);
+                        //Inicializa vari?vel de retorno.
+                        $returncode=true;		
 			// Aqui e enviado o email
 			foreach($to_notify as $userid => $statusid) 
@@ -3264,12 +3491,11 @@
 				$userid = (int)$userid;
 
-				if ($statusid == 'R' || $GLOBALS['phpgw']->accounts->get_type($userid) == 'g')
-				{
-					continue;	// dont notify rejected participants
-				}
-				if($userid != $GLOBALS['phpgw_info']['user']['account_id'] || ($msg_type == MSG_ADDED && $userid != $owner) || $msg_type == MSG_ALARM || isset($new_event['attachment']))
-				//if($userid != $owner ||  $msg_type == MSG_ALARM || isset($new_event['attachment']))
+				if ($statusid == 'R' || $GLOBALS['phpgw']->accounts->get_type($userid) == 'g' || ($sUN == $userid &&  $msg_type != MSG_ALARM))
+                                    continue;	// dont notify rejected participants or to == send
+				
+				if($userid != $sUN  ||  $msg_type == MSG_ALARM)
 				{
 					print_debug('Msg Type',$msg_type);
+                                        
 					print_debug('UserID',$userid);
 
@@ -3285,4 +3511,10 @@
 
 					$to = $preferences->email_address($userid);
+					
+                                        
+					if( $userid === -2 )
+					{
+						$to = htmlspecialchars_decode( $event['organizer'] );
+					}
 					
 					if (empty($to) || $to[0] == '@' || $to[0] == '$')	// we have no valid email-address
@@ -3403,10 +3635,6 @@
 											if( trim($tmpmail) == trim($to) & trim($tmpuid) == trim($NewKey))
 											{
-													if( ( $typesend == 3 ) || ( $typesend == 2 ) )
+													if($typesend == 3)
 													{
-														$question = "";
-														
-														if( $typesend == 2 )
-															$question = lang("Do you wish to change your participation in this event?");
 
 														$lang1 = lang("To See Commitment");
@@ -3415,8 +3643,12 @@
 																		  		   </form>";
 														$lang2 = lang("To accept");
-														$varbuttom1 ="<input type='submit' value='$lang2' onClick='javascript:window.open(\"".$GLOBALS['phpgw_info']['server']['webserver_url']."/index.php?menuaction=calendar.uicalendar.set_action&cal_id=$event[id]&action=3&response=1&user_id=$userid\",\"frontpage\",\"height=200,width=450,statusbar=no,toolbar=no,scrollbars=no,menubar=no,left=300,top=200\")'>";
+														$varbuttom1 ="<input type='submit' value='$lang2' onClick='javascript:window.open(\"".$GLOBALS['phpgw_info']['server']['webserver_url']."/index.php?menuaction=calendar.uicalendar.set_action&cal_id=$event[id]&action=3&response=1&user=".$tmpuid."\",\"frontpage\",\"height=100,width=500,statusbar=no,toolbar=no,scrollbars=no,menubar=no,left=300,top=200\")'>";
+                                                                                                                
+                                                                                                                $lang6 = lang("Tentative");
+														$varbuttom5 ="<input type='submit' value='$lang6' onClick='javascript:window.open(\"".$GLOBALS['phpgw_info']['server']['webserver_url']."/index.php?menuaction=calendar.uicalendar.set_action&cal_id=$event[id]&action=2&response=3&user=".$tmpuid."\",\"frontpage\",\"height=100,width=500,statusbar=no,toolbar=no,scrollbars=no,menubar=no,left=300,top=200\")'>";
+														
 
 														$lang3 = lang("To reject");
-														$varbuttom2 ="<input type='submit' value='$lang3' onClick='javascript:window.open(\"".$GLOBALS['phpgw_info']['server']['webserver_url']."/index.php?menuaction=calendar.uicalendar.set_action&cal_id=$event[id]&action=0&response=0\",\"frontpage\",\"height=100,width=400,statusbar=no,toolbar=no,scrollbars=no,menubar=no,left=300,top=200\")'>";
+														$varbuttom2 ="<input type='submit' value='$lang3' onClick='javascript:window.open(\"".$GLOBALS['phpgw_info']['server']['webserver_url']."/index.php?menuaction=calendar.uicalendar.set_action&cal_id=$event[id]&action=0&response=2&user=".$tmpuid."\",\"frontpage\",\"height=100,width=500,statusbar=no,toolbar=no,scrollbars=no,menubar=no,left=300,top=200\")'>";
 														
 														$lang4 = lang("Alarm");
@@ -3426,11 +3658,8 @@
 																		  		   </form>";
 																				   
-														$lang5 = lang("Delegate");
-														$varbuttom4 = "<form action='".$GLOBALS['phpgw_info']['server']['webserver_url']."/index.php?menuaction=calendar.uicalendar.screen_delegate_event&id_event=$event[id]&date=$newall3&delegator=$tmpuid' method='POST'>
+														$lang5 = lang("Suggest new hour"); 
+														$varbuttom4 = "<form action=".$GLOBALS['phpgw_info']['server']['webserver_url']."/index.php?menuaction=calendar.uicalendar.view&cal_id=$event[id]&date=$newall3&type=1' method='POST'>
 																		  		  <input type='submit' value='$lang5'>
 																		  		   </form>";
-														
-														$lang6 = lang("Tentative");
-														$varbuttom5 ="<input type='submit' value='$lang6' onClick='javascript:window.open(\"".$GLOBALS['phpgw_info']['server']['webserver_url']."/index.php?menuaction=calendar.uicalendar.set_action&cal_id=$event[id]&action=2&response=1&user_id=$userid\",\"frontpage\",\"height=200,width=450,statusbar=no,toolbar=no,scrollbars=no,menubar=no,left=300,top=200\")'>";														
 													}
 													else
@@ -3466,7 +3695,8 @@
 							
 							// A constante PHPGW_APP_TPL nao existe para envio de alarmes (cront, asyncservice).
-							define ("PHPGW_APP_TPL",PHPGW_API_INC . "/../../calendar/templates/".$GLOBALS['phpgw_info']['user']['preferences']['common']['template_dir']."");
+							if(!PHPGW_APP_TPL)
+                                                         define ("PHPGW_APP_TPL",PHPGW_INCLUDE_ROOT . "/calendar/templates/".$GLOBALS['phpgw_info']['user']['preferences']['common']['template_set']."");
 							
-							$body = CreateObject('phpgwapi.Template',PHPGW_APP_TPL);
+								$body = CreateObject('phpgwapi.Template',PHPGW_INCLUDE_ROOT . "/calendar/templates/".$GLOBALS['phpgw_info']['user']['preferences']['common']['template_set']."");
 							$body->set_file(Array('calendar' => 'body_email.tpl'));
 							$body->set_block('calendar','list');
@@ -3486,5 +3716,4 @@
 								'var8'				=> $var8,
 								'vardata8'			=> $vardata8,
-								'question'			=> $question,															
 								'varbuttom'			=> $varbuttom,
 								'varbuttom1'		=> $varbuttom1,
@@ -3516,18 +3745,9 @@
 							break;
 					}
+                                       
 					$mail->AddAddress($to);
-					//$mail->Body = $tmpbody;
-                                        $tmpattach_n = $this->create_vcard($GLOBALS['bocalendar']->so->cal->event);
-                                        $tmpattach = str_replace("Expresso-","",$tmpattach_n);
-                                        $mail->Body = "This is a multi-part message in MIME format.";
-                                        $mail->Body .= "\n--01BD3665.3AF0D360\n";
-                                        $mail->Body .= "Content-Type: text/html; charset=\"iso-8859-1\"\nContent-Transfer-Encoding: 8bit\n";
-                                        $mail->Body .= $tmpbody;
-                                        $mail->Body .= "\n--01BD3665.3AF0D360\n";
-                                        $mail->Body .="Content-Type:text/calendar; method=REQUEST; charset=US-ASCII\nContent-Transfer-Encoding:7bit\n\n";
-                                        $mail->Body .= $tmpattach;
-                                        $mail->Body .= "\n--01BD3665.3AF0D360--\n";
-                                        $mail->From = $sender;
-					$mail->FromName = $sender_name;
+					$mail->Body = $tmpbody;      
+					$mail->From = $sMail;
+					$mail->FromName = $sCN;
 					$mail->Sender = $mail->From;
 					$mail->SenderName = $mail->FromName;
@@ -3535,29 +3755,36 @@
 					unset($vardata5);
 					unset($vardata6);
-				}
-			}
-
-			//Inicializa variï¿œvel de retorno.
-			$returncode=true;			
-			if(count($mail->to)) {
-
-                            if(isset($new_event['attachment'])){
-                                foreach($new_event['attachment'] as $attach){
-                                    $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $attach['type']);
+                                        
+                                        // Envia aviso ao participante.
+                                        if(!$mail->Send()) {				
+                                                $returncode = false;
+                                                $errorInfo['participants'] = $mail->ErrorInfo;
+			}
+
+                                        $mail->ClearAddresses();    
+
                                 }
                             }
-				// Envia aviso a todos os participantes.
-				if(!$mail->Send()) {				
-					$returncode = false;
-					$errorInfo['participants'] = $mail->ErrorInfo;
+
+                        if(!is_object($this->ex_participants))
+                        {
+                            include_once($_SESSION['rootPath'].'/calendar/inc/class.ex_participants.inc.php');
+                            $objexP = new exParticipants();
+                            $objexP->setParticipantsBySerializable($this->ex_participants);
 				}
 				else
-					$returncode =  true;
-			}
+                            $objexP = $this->ex_participants;
+
 			
-			if(count($to_notify) && $this->ex_participants){
+                        if($msg_type === MSG_ADDED && count($this->extAdded) > 0)
+                               $extMails = $this->extAdded;  
+                        else if($msg_type === MSG_DELETED && count($this->extDeleted) > 0)
+                                $extMails = $this->extDeleted;  
+                        else 
+                            $extMails = array_diff($objexP->getParticipantsMailsArray(), $this->alreadyExtNotifieds);
+                               
+			if(count($extMails) > 0){
 				$mail->ClearAllRecipients();
-				$var = explode(",",trim($this->ex_participants));
-                                $mail->IsHTML(true);
+                              
 				$to = array();
 				if(!$subject) {
@@ -3567,5 +3794,5 @@
 				}
 				
-				foreach($var as $index => $ex_participant){
+				foreach($extMails as $index => $ex_participant){
 					$ex_participant = trim($ex_participant);
 					$ex_participant = preg_replace('#"(.*)" <(.*)\@(.*)\.(.*)>#','\\2@\\3.\\4',$ex_participant);
@@ -3579,6 +3806,6 @@
 				$_body = explode("<hr size='1' width='100%'>",$tmpbody);
 				$tmpbody = $_body[0] ? $_body[0] : $subject ;
-				$tmpbody.= "<br><b>".lang("external participants").":: </b> ".htmlentities($this->ex_participants);
-				$tmpbody.= "<br>".lang("Summary").": ".$this->so->cal->event[title]."<br>";
+				$tmpbody.= "<br><b>".lang("external participants").":: </b> ".htmlentities($objexP->getParticipantsMailsString());
+				$tmpbody.= "<br>".lang("Summary").": ".$this->so->cal->event[description]."<br>";
 				$tmpbody.= "<br>".lang("Start time").": ".$GLOBALS['phpgw']->common->show_date($starttime)."<br>".lang("End date").": ".$GLOBALS['phpgw']->common->show_date($endtime)."<br>";
 				$tmpbody.= "<br><br><hr size='1' width='100%'><font color='red'>"
@@ -3592,16 +3819,57 @@
 				//attach extern vcalendar/icalendar (ics)			
 				// define('context','$GLOBALS.bocalendar.so.cal.event');
-				$tmpattach = $this->create_vcard($GLOBALS['bocalendar']->so->cal->event);
+				
+				$evt = $GLOBALS['bocalendar']->so->cal->event;
+                                                                 
+                                /*
+                                 * Cria Arqvuio ICS
+                                 */
+                                require_once $_SESSION['rootPath'].'/API/class.servicelocator.php';
+                                $icalService = ServiceLocator::getService('ical');
+
+                                if($msg_type == MSG_DELETED)
+                                {
+                                        $icalService->createICal(strtoupper($method));
+                                        $icalService->addEvent(
+                                            $old_event['start']['year'].'-'.$old_event['start']['month'].'-'.$old_event['start']['mday'].' '.$old_event['start']['hour'].':'.$old_event['start']['min'].':00',
+                                            $old_event['end']['year'].'-'.$old_event['end']['month'].'-'.$old_event['end']['mday'].' '.$old_event['end']['hour'].':'.$old_event['end']['min'].':00',
+                                            array($sMail => array('CN'=> $sCN)),
+                                            $old_event['title'],
+                                            $old_event['description'],
+                                            $old_event['location'],
+                                            false,
+                                            false,
+                                            false,
+                                            $old_event['uid']
+                                            );
+                                }
+                                else
+                                {
+                                        $attendee = array();
+                                        foreach($to as $value)
+                                            $attendee[$value] = array('RSVP' => 'TRUE','ROLE' => 'REQ-PARTICIPANT');
+
+                                        $attendee =  array_merge($attendee,$this->getCalendarParticipantsArray($evt['id']));
+                                        $icalService->createICal(strtoupper($method));
+                                        $icalService->addEvent(
+                                            $evt['start']['year'].'-'.$evt['start']['month'].'-'.$evt['start']['mday'].' '.$evt['start']['hour'].':'.$evt['start']['min'].':00',
+                                            $evt['end']['year'].'-'.$evt['end']['month'].'-'.$evt['end']['mday'].' '.$evt['end']['hour'].':'.$evt['end']['min'].':00',
+                                            array($sMail => array('CN'=> $sCN)),
+                                            $evt['title'],
+                                            $evt['description'],
+                                            $evt['location'],
+                                            $attendee,
+                                            false,
+                                            false,
+                                            $evt['uid']
+                                            );
+
+                                }
+
+
+				$tmpattach = $icalService->getICal();
+                                //-------------------------------------------------//
+                                
 				if($tmpattach){					
-					$tmpbody .="<a href='../index.php?menuaction=calendar.uicalendar.add&date="
-					.$GLOBALS['bocalendar']->so->cal->event[start][year]
-				.$event_month
-				.$GLOBALS['bocalendar']->so->cal->event[start][mday]
-					."&hour=".$GLOBALS['bocalendar']->so->cal->event[start][hour]
-					."&minute=".$GLOBALS['bocalendar']->so->cal->event[start][min]
-					."&title=".$GLOBALS['bocalendar']->so->cal->event['title']
-					."&description=".$GLOBALS['bocalendar']->so->cal->event['description']
-					."&location=".$GLOBALS['bocalendar']->so->cal->event['location']."'>"
-					."<h2>".lang("Add to my expresso")."</h2>";
 					$tempdir = $GLOBALS['phpgw_info']['server']['temp_dir'] . SEP;
 					srand((double)microtime()*1000000);
@@ -3614,13 +3882,6 @@
 					fclose($attach_fd);
 				}
-
-                                if(isset($new_event['attachment'])){
-                                    foreach($new_event['attachment'] as $attach){
-                                        $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $attach['type']);
-                                    }
-                                }
-                                
-				$mail->From = $sender;
-				$mail->FromName = $sender_name;
+				$mail->From = $sMail;
+				$mail->FromName = $sCN;
 				$mail->Sender = $mail->From;
 				$mail->SenderName = $mail->FromName;
@@ -3651,5 +3912,5 @@
 			$GLOBALS['phpgw_info']['user']['preferences']['common']['dateformat'] = $temp_dateformat;
 			
-			// Notifica por email o criador do compromisso, com as possï¿œveis falhas.						
+			// Notifica por email o criador do compromisso, com as poss?veis falhas.						
 			if($errorInfo) {
 				$tmpbody = "<font color='red'>".lang("The following commitment had problems for DELIVERING the NOTIFICATION messages.").".</font><br>";
@@ -3678,6 +3939,6 @@
 				$mail->Host = $emailadmin['smtpServer'];
 				$mail->Port = $emailadmin['smtpPort'];
-				$mail->From = $sender;
-				$mail->FromName = $sender_name;
+				$mail->From = $sMail;
+				$mail->FromName = $sCN;
 				$mail->Sender = $mail->From;
 				$mail->SenderName = $mail->FromName;
@@ -3685,5 +3946,5 @@
 				$mail->Subject = lang("calendar event")." - ".lang("email notification");							
 				$mail->Body = $tmpbody;					
-				$mail->AddAddress($sender);
+				$mail->AddAddress($sMail);
 				if(!$mail->Send())			
 					$returncode = false;
@@ -3693,4 +3954,106 @@
 			return $returncode;
 		}
+		
+		
+		
+		/**
+		 * @license http://www.gnu.org/copyleft/gpl.html GPL
+		 * @author Prognus Software Livre (http://www.prognus.com.br)
+		 */
+		function send_suggestion_external_owner($cal_id, $uid, $to, $time_suggest, $array_data_inicio, $array_data_final, $title, $description, $location, $ex_participants,$user = false)
+                {
+
+                    if($cal_id)
+                        $event =  $this->so->read_entry($cal_id);
+                    else
+                    {
+                        $event = $this->restore_from_appsession();
+                        $this->so->add_entry( $event , false);
+                    }
+                    
+                    $this->so->cal->set_status($event['id'],$user,2);
+
+
+                    if($user && $user != $GLOBALS['phpgw_info']['user']['account_id'])
+                    {
+                        $ldap = $this->getLdap();
+                        $justthese = array("mail","cn");
+                        $filter="(&(|(phpgwAccountType=u)(phpgwAccountType=l)(phpgwAccountType=s)(phpgwAccountType=i))(uidNumber=".$user."))";
+                        $search = ldap_search($ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
+                        $entry = ldap_get_entries($ldap, $search);
+                        $ownerMail = $entry[0]['mail'][0];
+                        $ownerCN = $entry[0]['cn'][0];
+                     }
+                     else
+                     {
+                        $ownerMail = $GLOBALS['phpgw_info']['user']['email'];
+                        $ownerCN = $GLOBALS['phpgw_info']['user']['fullname'];
+                     }
+                     
+                    require_once $_SESSION['rootPath'] . '/API/class.servicelocator.php';
+                    $icalService = ServiceLocator::getService('ical');
+                    $dia_inicio = $array_data_inicio[0];
+                    $mes_inicio = $array_data_inicio[1];
+                    $ano_inicio = $array_data_inicio[2];
+                    $hora_inicio = $time_suggest['hora_inicio'];
+                    $minuto_inicio = $time_suggest['minuto_inicio'];
+                    $dia_final = $array_data_final[0];
+                    $mes_final = $array_data_final[1];
+                    $ano_final = $array_data_final[2];
+                    $hora_final = $time_suggest['hora_final'];
+                    $minuto_final = $time_suggest['minuto_final'];
+
+                    $dtStart = $array_data_inicio[2] . '/' .
+                               $array_data_inicio[1] . '/' .
+                               $array_data_inicio[0] . ' ' .
+                               $time_suggest['hora_inicio'] . ':' .
+                               $time_suggest['minuto_inicio'] . ':00';
+
+                    $dtEnd = $array_data_final[2] . '/' .
+                             $array_data_final[1] . '/' .
+                             $array_data_final[0] . ' ' .
+                             $time_suggest['hora_final'] . ':' .
+                             $time_suggest['minuto_final'] . ':00';
+
+                    $icalService->createICal('REPLY');
+
+                    $other = array( 'X-MICROSOFT-CDO-IMPORTANCE' => '1',
+                                    'X-EXPRESSO-SUGGESTION-HOUR' => '1',
+                                    'CLASS' => 'PUBLIC',
+                                    'PRIORITY' => '5',
+                                    'SEQIENCE' => '0',
+                                    'TRANSP' => 'OPAQUE');
+
+                    /* Corpo do email */
+                    $tmpbody2 = lang("The sender suggested a new hours for the appointment");
+                    $tmpbody2.= " <br /> <b>" . lang("Title") . ":</b> $title";
+                    $tmpbody2.= " <br /> <b>" . lang("Details") . ":</b> <br /> <br /> <b>" . lang("Start") . "  </b>" . $dia_inicio . "/" . $mes_inicio . "/" . $ano_inicio . " - " . $hora_inicio . ":" . $minuto_inicio;
+                    $tmpbody2.= " <br /> <b>" . lang("End") . " </b>" . $dia_final . "/" . $mes_final . "/" . $ano_final . " - " . $hora_final . ":" . $minuto_final . "<br><br><br><br>";
+                    $tmpbody = lang("The sender suggested a new hours for the appointment");
+                    $tmpbody.= " \r\n " . lang("Title") . ": $title";
+                    $tmpbody.= " \r\n " . lang("Suggestion") . ": \r\n \r\n " . lang("Start") . "  " . $dia_inicio . "/" . $mes_inicio . "/" . $ano_inicio . " - " . $hora_inicio . ":" . $minuto_inicio;
+                    $tmpbody.= " \r\n " . lang("End") . " " . $dia_final . "/" . $mes_final . "/" . $ano_final . " - " . $hora_final . ":" . $minuto_final . "";
+
+                    $icalService->addEvent($dtStart,
+                            $dtEnd,
+                            $to,
+                            $title,
+                            utf8_encode($tmpbody),
+                            $location,
+                            array($ownerMail => array('CN' => $ownerCN, 'PARTSTAT' => 'TENTATIVE')),
+                            $other,
+                            false,
+                            $uid
+                    );
+                   
+                    $tmpattach =  $icalService->getICal();                   
+                    
+                    $mailService = ServiceLocator::getService('mail');
+                    $mailService->addStringAttachment($tmpattach, 'suggestion.ics', 'application/ics');
+                    $mailService->addStringAttachment($tmpattach, 'vcalendar.ics', 'text/calendar; charset=utf-8; method=REPLY;', '7bit', 'inline');
+                    $mailService->sendMail($to, $ownerMail, $title, $tmpbody2);
+                     
+                    return $event['id'];                    
+                }		
 		
 		function send_alarm($alarm)
@@ -3764,49 +4127,63 @@
 		}
 
-		function prepare_recipients(&$new_event,$old_event)
-		{
-						
-			// Find modified and deleted users.....
-			while(list($old_userid,$old_status) = each($old_event['participants']))
-			{
-				if(isset($new_event['participants'][$old_userid]))
-				{
-					print_debug('Modifying event for user',$old_userid);
-					$this->modified[(int)$old_userid] = $new_status;
-				}
-				else
-				{
-					print_debug('Deleting user from the event',$old_userid);
-					$this->deleted[(int)$old_userid] = $old_status;
-				}
-			}
-			// Find new users.....
-			while(list($new_userid,$new_status) = each($new_event['participants']))
-			{
-				if(!isset($old_event['participants'][$new_userid]))
-				{
-					print_debug('Adding event for user',$new_userid);
-					$this->added[$new_userid] = 'U';
-					$new_event['participants'][$new_userid] = 'U';
-				}
+		function prepare_recipients(&$new_event,$old_event,$userSend)
+		{
+                        //Verifica se ouve alguem deletado
+                        foreach($old_event['participants'] as $key => $value)
+                           if(!array_key_exists($key, $new_event['participants']))
+				{
+                               $this->deleted[$key] = $value;
+                               $this->alreadyNotifieds[] = $key; //Adiciona a variavel de ja notificados para não serem notificados 2 vezes;
+				}
+                        //Verifica se ouve alguem adicionado
+                        foreach($new_event['participants'] as $key => $value)
+                           if(!array_key_exists($key, $old_event['participants']))
+				{
+                               $this->added[$key] = $value;
+                               $this->alreadyNotifieds[] = $key; //Adiciona a variavel de ja notificados para não serem notificados 2 vezes;
 			}
 			
-			if(count($this->added) > 0 || count($this->modified) > 0 || count($this->deleted) > 0)
-			{
-				if(count($this->added) > 0)
-				{
-					$this->ex_participants = '';
-					$this->send_update(MSG_ADDED,$this->added,'',$new_event);
-				}
-				if(count($this->modified) > 0)
-				{
-					$this->send_update(MSG_MODIFIED,$this->modified,$old_event,$new_event);
-				}
-				if(count($this->deleted) > 0)
-				{
-					$this->ex_participants = '';
-					$this->send_update(MSG_DELETED,$this->deleted,$old_event);
-				}
-			}
+                        //Verifica se ouve alguem modificado
+                        foreach($new_event['participants'] as $key => $value)
+			{
+                            if(array_key_exists($key, $old_event['participants']))                       
+				{
+                                if($old_event['participants'][$key] != $value)
+				{
+                                    $this->modified[$key] = $value;  
+                                    $this->alreadyNotifieds[] = $key; //Adiciona a variavel de ja notificados para não serem notificados 2 vezes;
+				}
+				}
+			}
+                         //Verificando alterações em usuarios externos
+                         include_once($_SESSION['rootPath'].'/calendar/inc/class.ex_participants.inc.php');
+                         $extOld = new exParticipants();
+                         $extNew = new exParticipants();
+                         
+                         $extOld->setParticipantsBySerializable($old_event['ex_participants']);
+                         $extNew->setParticipantsBySerializable($new_event['ex_participants']);
+                        
+                         $oldArray = $extOld->getParticipantsMailsArray();
+                         $newArray = $extNew->getParticipantsMailsArray();
+                         
+                        //Verifica se ouve alguem deletado
+                        $this->extDeleted = array_diff($oldArray, $newArray);
+                        
+                        //Verifica se ouve alguem adicionado
+                        $this->extAdded = array_diff($newArray, $oldArray);
+                        
+                        $this->alreadyExtNotifieds = array_merge($this->alreadyExtNotifieds, $this->extDeleted);
+                        $this->alreadyExtNotifieds = array_merge($this->alreadyExtNotifieds, $this->extAdded);
+                        //---------------------------------------------------------------------------------//
+                        
+                        if(count($this->added) > 0 || count($this->extAdded))
+                                $this->send_update(MSG_ADDED,$this->added,'',$new_event,$userSend);
+                        
+                        if(count($this->modified) > 0)
+                                $this->send_update(MSG_MODIFIED,$this->modified,$old_event,$new_event,$userSend);
+                        
+                        if(count($this->deleted) > 0 || count($this->extDeleted))
+                                $this->send_update(MSG_DELETED,$this->deleted,$old_event,false,$userSend);
+                        			
 		}
 
@@ -4021,7 +4398,11 @@
 			);
 
+			$owner = $event['owner'];
+
+			$owner_name = ( $owner === -2 )? $event['organizer'] : $GLOBALS['phpgw']->common->grab_owner_name( $owner );
+
 			$var['owner'] = Array(
 				'field'	=> lang('Created By'),
-				'data'	=> $GLOBALS['phpgw']->common->grab_owner_name($event['owner'])
+				'data'  => $owner_name
 			);
 
@@ -4031,22 +4412,15 @@
 			);
 
-			$var['observations'] = Array(
-				'field'	=> $this->translate('Observations'),
-				'data'	=> $event['observations']
-			);
-			
-                        $var['attachment'] = Array(
-                                'field'	=> $this->translate('Attachment'),
-                                'data'	=> $event['attachment']
-                        );
-
-			$var['alter_by'] = Array(
-                                'field'	=> $this->translate('Alter by'),
-                                'data'	=> $event['alter_by']
-                        );
+			if($event['public']){
+				$type = lang('Public');
+			}else if (!$event['public'] && $event['type'] == 'E'){
+				$type = lang('Restrict');
+			}else{
+				$type = lang('Private');
+			}
 
 			$var['access'] = Array(
 				'field'	=> lang('Access'),
-				'data'	=> $event['public'] ? lang('Public') : lang('Private')
+				'data'	=> $type
 			);
 
Index: trunk/calendar/inc/hourReport.php
===================================================================
--- trunk/calendar/inc/hourReport.php	(revision 4931)
+++ trunk/calendar/inc/hourReport.php	(revision 5132)
@@ -95,5 +95,5 @@
 	$_SESSION['calendar']['server']['db_type']
 );
-if (IsSet($_POST['CAT']) && IsSet($_POST['CAL'])){
+if (IsSet($_POST['CAT'])){
 	if (!preg_match("/[a-zA-Z0-9]+/i",$_POST['CAT'][0])){
 		echo "Invalid entry:".$_POST['CAT'][0];
@@ -125,5 +125,5 @@
 		$query = "select cal_id,title,description,datetime,edatetime from phpgw_cal where ".(!$_POST['NORM']?"cal_type = 'H' and":" is_public = 1 and ")." owner = ".$user_id." and (category like '%,".$catid.",%' or category like '%,".$catid."' or category like '".$catid.",%' or category = '".$catid."')".(IsSet($initDate)?" and datetime > ".$initDate:"");
 		if(!$db->query($query)){
-			print("<br>Query failed.<br>");
+			print("<br>Query failed at host:<br>".$_SESSION['calendar']['server']['db_user']."@".$_SESSION['calendar']['server']['db_host'].":".$_SESSION['calendar']['server']['db_port']."<br>");
 			return;
 		}
Index: trunk/calendar/inc/hook_home_day.inc.php
===================================================================
--- trunk/calendar/inc/hook_home_day.inc.php	(revision 4322)
+++ trunk/calendar/inc/hook_home_day.inc.php	(revision 5132)
@@ -32,5 +32,6 @@
 		).'</td><td align="center"><table border="0" width="100%" cellspacing="0" cellpadding="0">'
 		. '<tr><td align="center">'.ExecMethod('calendar.bocalendar.long_date',time())
-		.'</td></tr><tr><td valign="top">'.ExecMethod('calendar.uicalendar.print_day_new',
+		.'</td></tr><tr><td bgcolor="'.$GLOBALS['phpgw_info']['theme']['bg_text']
+		.'" valign="top">'.ExecMethod('calendar.uicalendar.print_day',
 			Array(
 				'year'	=> $GLOBALS['g_year'],
Index: trunk/calendar/inc/class.boicalendar.inc.php
===================================================================
--- trunk/calendar/inc/class.boicalendar.inc.php	(revision 3736)
+++ trunk/calendar/inc/class.boicalendar.inc.php	(revision 5132)
@@ -1,83 +1,82 @@
 <?php
-  /**************************************************************************\
-  * eGroupWare - iCalendar Parser                                            *
-  * http://www.egroupware.org                                                *
-  * Written by Mark Peters <skeeter@phpgroupware.org>                        *
-  * --------------------------------------------                             *
-  *  This program is free software; you can redistribute it and/or modify it *
-  *  under the terms of the GNU General Public License as published by the   *
-  *  Free Software Foundation; either version 2 of the License, or (at your  *
-  *  option) any later version.                                              *
-  \**************************************************************************/
-
-
-	define('FOLD_LENGTH',75);
-
-	define('VEVENT',1);
-	define('VTODO',2);
-
-	define('NONE',0);
-	define('CHAIR',1);
-	define('REQ_PARTICIPANT',2);
-	define('OPT_PARTICIPANT',3);
-	define('NON_PARTICIPANT',4);
-
-	define('INDIVIDUAL',1);
-	define('GROUP',2);
-	define('RESOURCE',4);
-	define('ROOM',8);
-	define('UNKNOWN',16);
-
-	define('NEEDS_ACTION',0);
-	define('ACCEPTED',1);
-	define('DECLINED',2);
-	define('TENTATIVE',3);
-	define('DELEGATED',4);
-	define('COMPLETED',5);
-	define('IN_PROCESS',6);
-
-	/*
-	* Class
-	*/
-	define('_PRIVATE',0);
-	define('_PUBLIC',1);
-	define('_CONFIDENTIAL',3);
-
-	/*
-	* Transparency
-	*/
-	define('TRANSPARENT',0);
-	define('OPAQUE',1);
-
-	/*
-	* Frequency
-	*/
-	define('SECONDLY',1);
-	define('MINUTELY',2);
-	define('HOURLY',3);
-	define('DAILY',4);
-	define('WEEKLY',5);
-	define('MONTHLY',6);
-	define('YEARLY',7);
-
-	define('FREE',0);
-	define('BUSY',1);
-	define('BUSY_UNAVAILABLE',2);
-	define('BUSY_TENTATIVE',3);
-
-	define('THISANDPRIOR',0);
-	define('THISANDFUTURE',1);
-
-	define('START',0);
-	define('END',1);
-
-	define('_8BIT',0);
-	define('_BASE64',1);
-
-	define('OTHER',99);
-
-	class boicalendar
-	{
-		var $public_functions = array(
+
+/**************************************************************************\
+* eGroupWare - iCalendar Parser                                            *
+* http://www.egroupware.org                                                *
+* Written by Mark Peters <skeeter@phpgroupware.org>                        *
+* --------------------------------------------                             *
+*  This program is free software; you can redistribute it and/or modify it *
+*  under the terms of the GNU General Public License as published by the   *
+*  Free Software Foundation; either version 2 of the License, or (at your  *
+*  option) any later version.                                              *
+\**************************************************************************/
+
+define('FOLD_LENGTH', 75);
+
+define('VEVENT', 1);
+define('VTODO', 2);
+
+define('NONE', 0);
+define('CHAIR', 1);
+define('REQ_PARTICIPANT', 2);
+define('OPT_PARTICIPANT', 3);
+define('NON_PARTICIPANT', 4);
+
+define('INDIVIDUAL', 1);
+define('GROUP', 2);
+define('RESOURCE', 4);
+define('ROOM', 8);
+define('UNKNOWN', 16);
+
+define('NEEDS_ACTION', 0);
+define('ACCEPTED', 1);
+define('DECLINED', 2);
+define('TENTATIVE', 3);
+define('DELEGATED', 4);
+define('COMPLETED', 5);
+define('IN_PROCESS', 6);
+
+/*
+* Class
+*/
+define('_PRIVATE', 0);
+define('_PUBLIC', 1);
+define('_CONFIDENTIAL', 3);
+
+/*
+* Transparency
+*/
+define('TRANSPARENT', 0);
+define('OPAQUE', 1);
+
+/*
+* Frequency
+*/
+define('SECONDLY', 1);
+define('MINUTELY', 2);
+define('HOURLY', 3);
+define('DAILY', 4);
+define('WEEKLY', 5);
+define('MONTHLY', 6);
+define('YEARLY', 7);
+
+define('FREE', 0);
+define('BUSY', 1);
+define('BUSY_UNAVAILABLE', 2);
+define('BUSY_TENTATIVE', 3);
+
+define('THISANDPRIOR', 0);
+define('THISANDFUTURE', 1);
+
+define('START', 0);
+define('END', 1);
+
+define('_8BIT', 0);
+define('_BASE64', 1);
+
+define('OTHER', 99);
+
+class boicalendar {
+	var $public_functions = array (
 			'import' => True,
 			'export' => True,
@@ -87,11 +86,11 @@
 		var $ical;
 		var $line = 0;
-		var $event = Array();
-		var $todo = Array();
-		var $journal = Array();
-		var $freebusy = Array();
-		var $timezone = Array();
-		var $property = Array();
-		var $parameter = Array();
+	var $event = Array ();
+	var $todo = Array ();
+	var $journal = Array ();
+	var $freebusy = Array ();
+	var $timezone = Array ();
+	var $property = Array ();
+	var $parameter = Array ();
 		var $debug_str = False;
 		var $api = True;
@@ -102,687 +101,686 @@
 		*/
 
-		function boicalendar()
-		{
-			$this->property = Array(
-				'action'		=> Array(
+	function boicalendar() {
+		$this->property = Array (
+			'action' => Array (
 					'type'		=> 'text',
 					'to_text'	=> True,
-					'valarm'		=> Array(
+				'valarm' => Array (
 						'state'		=> 'required',
 						'multiples'	=> False
 					)
 				),
-				'attach'		=> Array(
+			'attach' => Array (
 					'type'		=> 'uri',
 					'to_text'	=> True,
-					'vevent'	=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					),
-					'vtodo'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					),
-					'vjournal'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					),
-					'valarm'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					)
-				),
-				'attendee'		=> Array(
+				'vevent' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					),
+				'vtodo' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					),
+				'vjournal' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					),
+				'valarm' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					)
+				),
+			'attendee' => Array (
 					'type'		=> 'cal-address',
 					'to_text'	=> False,
-					'vevent'	=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					),
-					'vtodo'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					),
-					'vjournal'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					),
-					'valarm'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					),
-					'vfreebusy'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					)
-				),
-				'categories'		=> Array(
+				'vevent' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					),
+				'vtodo' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					),
+				'vjournal' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					),
+				'valarm' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					),
+				'vfreebusy' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					)
+				),
+			'categories' => Array (
 					'type'		=> 'text',
 					'to_text'	=> True,
-					'vevent'	=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					),
-					'vtodo'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					),
-					'vjournal'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					)
-				),
-				'class'			=> Array(
+				'vevent' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					),
+				'vtodo' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					),
+				'vjournal' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					)
+				),
+			'class' => Array (
 					'type'		=> 'text',
 					'to_text'	=> True,
-					'vevent'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					),
-					'vtodo'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					),
-					'vjournal'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					)
-				),
-				'comment'		=> Array(
+				'vevent' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					),
+				'vtodo' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					),
+				'vjournal' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					)
+				),
+			'comment' => Array (
 					'type'		=> 'text',
 					'to_text'	=> True,
-					'daylight'	=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					),
-					'standard'	=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					),
-					'valarm'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					),
-					'vevent'	=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					),
-					'vfreebusy'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					),
-					'vjournal'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					),
-					'vtodo'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					)
-				),
-				'completed'		=> Array(
+				'daylight' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					),
+				'standard' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					),
+				'valarm' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					),
+				'vevent' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					),
+				'vfreebusy' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					),
+				'vjournal' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					),
+				'vtodo' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					)
+				),
+			'completed' => Array (
 					'type'		=> 'date-time',
 					'to_text'	=> False,
-					'vtodo'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					)
-				),
-				'contact'		=> Array(
+				'vtodo' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					)
+				),
+			'contact' => Array (
 					'type'		=> 'text',
 					'to_text'	=> True,
-					'vevent'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					),
-					'vfreebusy'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					),
-					'vjournal'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					)
-				),
-				'created'		=> Array(
+				'vevent' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					),
+				'vfreebusy' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					),
+				'vjournal' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					)
+				),
+			'created' => Array (
 					'type'		=> 'date-time',
 					'to_text'	=> False,
-					'vevent'	=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					),
-					'vtodo'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					),
-					'vjournal'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					)
-				),
-				'description'		=> Array(
+				'vevent' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					),
+				'vtodo' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					),
+				'vjournal' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					)
+				),
+			'description' => Array (
 					'type'		=> 'text',
 					'to_text'	=> True,
-					'vevent'	=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					),
-					'vtodo'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					),
-					'vjournal'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					),
-					'valarm'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					)
-				),
-				'dtend'			=> Array(
+				'vevent' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					),
+				'vtodo' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					),
+				'vjournal' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					),
+				'valarm' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					)
+				),
+			'dtend' => Array (
 					'type'		=> 'date-time',
 					'to_text'	=> False,
-					'vevent'	=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					),
-					'vfreebusy'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					)
-				),
-				'dtstamp'		=> Array(
+				'vevent' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					),
+				'vfreebusy' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					)
+				),
+			'dtstamp' => Array (
 					'type'		=> 'date-time',
 					'to_text'	=> False,
-					'vevent'	=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					),
-					'vtodo'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					),
-					'vjournal'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					),
-					'vfreebusy'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					)
-				),
-				'dtstart'		=> Array(
+				'vevent' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					),
+				'vtodo' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					),
+				'vjournal' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					),
+				'vfreebusy' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					)
+				),
+			'dtstart' => Array (
 					'type'		=> 'date-time',
 					'to_text'	=> False,
-					'daylight'	=> Array(
+				'daylight' => Array (
 						'state'		=> 'required',
 						'multiples'	=> False
 					),
-					'standard'	=> Array(
+				'standard' => Array (
 						'state'		=> 'required',
 						'multiples'	=> False
 					),
-					'vevent'	=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					),
-					'vfreebusy'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					),
-					'vjournal'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					),
-					'vtodo'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					)
-				),
-				'due'			=> Array(
+				'vevent' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					),
+				'vfreebusy' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					),
+				'vjournal' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					),
+				'vtodo' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					)
+				),
+			'due' => Array (
 					'type'		=> 'date-time',
 					'to_text'	=> False,
-					'vtodo'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					)
-				),
-				'duration'		=> Array(
+				'vtodo' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					)
+				),
+			'duration' => Array (
 					'type'		=> 'duration',
 					'to_text'	=> False,
-					'valarm'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					),
-					'vevent'	=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					),
-					'vfreebusy'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					),
-					'vtodo'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					)
-				),
-				'exdate'		=> Array(
+				'valarm' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					),
+				'vevent' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					),
+				'vfreebusy' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					),
+				'vtodo' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					)
+				),
+			'exdate' => Array (
 					'type'		=> 'date-time',
 					'to_text'	=> False,
-					'vevent'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					),
-					'vjournal'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					),
-					'vtodo'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					)
-				),
-				'exrule'		=> Array(
+				'vevent' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					),
+				'vjournal' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					),
+				'vtodo' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					)
+				),
+			'exrule' => Array (
 					'type'		=> 'recur',
 					'to_text'	=> False,
-					'vevent'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					),
-					'vjournal'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					),
-					'vtodo'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					)
-				),
-				'freebusy'		=> Array(
+				'vevent' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					),
+				'vjournal' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					),
+				'vtodo' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					)
+				),
+			'freebusy' => Array (
 					'type'		=> 'freebusy',
 					'to_text'	=> False,
-					'vfreebusy'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					)
-				),
-				'geo'			=> Array(
+				'vfreebusy' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					)
+				),
+			'geo' => Array (
 					'type'		=> 'float',
 					'to_text'	=> True,
-					'vevent'	=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					),
-					'vtodo'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					)
-				),
-				'last_modified'		=> Array(
+				'vevent' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					),
+				'vtodo' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					)
+				),
+			'last_modified' => Array (
 					'type'		=> 'date-time',
 					'to_text'	=> False,
-					'vevent'	=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					),
-					'vtodo'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					),
-					'vjournal'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					),
-					'vtimezone'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					)
-				),
-				'location'		=> Array(
+				'vevent' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					),
+				'vtodo' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					),
+				'vjournal' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					),
+				'vtimezone' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					)
+				),
+			'location' => Array (
 					'type'		=> 'text',
 					'to_text'	=> True,
-					'vevent'	=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					),
-					'vtodo'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					)
-				),
-				'method'			=> Array(
+				'vevent' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					),
+				'vtodo' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					)
+				),
+			'method' => Array (
 					'type'		=> 'text',
 					'to_text'	=> True,
-					'ical'	=> Array(
+				'ical' => Array (
 						'state'		=> 'required',
 						'multiples'	=> False
 					)
 				),
-				'organizer'		=> Array(
+			'organizer' => Array (
 					'type'		=> 'cal-address',
 					'to_text'	=> False,
-					'vevent'	=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					),
-					'vtodo'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					),
-					'vjournal'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					),
-					'vfreebusy'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					)
-				),
-				'percent_complete'	=> Array(
+				'vevent' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					),
+				'vtodo' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					),
+				'vjournal' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					),
+				'vfreebusy' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					)
+				),
+			'percent_complete' => Array (
 					'type'		=> 'integer',
 					'to_text'	=> False,
-					'vtodo'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					)
-				),
-				'priority'		=> Array(
+				'vtodo' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					)
+				),
+			'priority' => Array (
 					'type'		=> 'integer',
 					'to_text'	=> True,
-					'vevent'	=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					),
-					'vtodo'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					)
-				),
-				'prodid'			=> Array(
+				'vevent' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					),
+				'vtodo' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					)
+				),
+			'prodid' => Array (
 					'type'		=> 'text',
 					'to_text'	=> True,
-					'ical'	=> Array(
+				'ical' => Array (
 						'state'		=> 'required',
 						'multiples'	=> False
 					)
 				),
-				'rdate'			=> Array(
+			'rdate' => Array (
 					'type'		=> 'date-time',
 					'to_text'	=> False,
-					'daylight'	=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					),
-					'standard'	=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					),
-					'vevent'	=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					),
-					'vtodo'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					),
-					'vjournal'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					)
-				),
-				'recurrence_id'		=> Array(
+				'daylight' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					),
+				'standard' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					),
+				'vevent' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					),
+				'vtodo' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					),
+				'vjournal' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					)
+				),
+			'recurrence_id' => Array (
 					'type'		=> 'date-time',
 					'to_text'	=> False,
-					'vevent'	=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					),
-					'vjournal'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					),
-					'vtodo'	=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					)
-				),
-				'related_to'		=> Array(
+				'vevent' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					),
+				'vjournal' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					),
+				'vtodo' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					)
+				),
+			'related_to' => Array (
 					'type'		=> 'text',
 					'to_text'	=> False,
-					'vevent'	=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					),
-					'vjournal'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					),
-					'vtodo'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					)
-				),
-				'request_status'	=> Array(
+				'vevent' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					),
+				'vjournal' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					),
+				'vtodo' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					)
+				),
+			'request_status' => Array (
 					'type'		=> 'text',
 					'to_text'	=> True,
-					'vevent'	=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					),
-					'vtodo'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					),
-					'vjournal'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					),
-					'vfreebusy'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					)
-				),
-				'resources'		=> Array(
+				'vevent' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					),
+				'vtodo' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					),
+				'vjournal' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					),
+				'vfreebusy' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					)
+				),
+			'resources' => Array (
 					'type'		=> 'text',
 					'to_text'	=> False,
-					'vevent'	=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					),
-					'vtodo'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					)
-				),
-				'rrule'			=> Array(
+				'vevent' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					),
+				'vtodo' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					)
+				),
+			'rrule' => Array (
 					'type'		=> 'recur',
 					'to_text'	=> False,
-					'daylight'	=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					),
-					'standard'	=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					),
-					'vevent'	=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					),
-					'vtodo'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					),
-					'vjournal'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					)
-				),
-				'sequence'		=> Array(
+				'daylight' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					),
+				'standard' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					),
+				'vevent' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					),
+				'vtodo' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					),
+				'vjournal' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					)
+				),
+			'sequence' => Array (
 					'type'		=> 'integer',
 					'to_text'	=> True,
-					'vevent'	=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					),
-					'vjournal'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					),
-					'vtodo'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					)
-				),
-				'status'		=> Array(
+				'vevent' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					),
+				'vjournal' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					),
+				'vtodo' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					)
+				),
+			'status' => Array (
 					'type'		=> 'text',
 					'to_text'	=> True,
-					'vevent'	=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					),
-					'vjournal'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					),
-					'vtodo'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					)
-				),
-				'summary'		=> Array(
+				'vevent' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					),
+				'vjournal' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					),
+				'vtodo' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					)
+				),
+			'summary' => Array (
 					'type'		=> 'text',
 					'to_text'	=> True,
-					'vevent'	=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					),
-					'vtodo'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					),
-					'vjournal'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					),
-					'valarm'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					)
-				),
-				'transp'		=> Array(
+				'vevent' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					),
+				'vtodo' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					),
+				'vjournal' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					),
+				'valarm' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					)
+				),
+			'transp' => Array (
 					'type'		=> 'text',
 					'to_text'	=> True,
-					'vevent'	=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					)
-				),
-				'trigger'		=> Array(
+				'vevent' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					)
+				),
+			'trigger' => Array (
 					'type'		=> 'text',
 					'to_text'	=> True,
-					'valarm'	=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					)
-				),
-				'tzid'			=> Array(
+				'valarm' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					)
+				),
+			'tzid' => Array (
 					'type'		=> 'text',
 					'to_text'	=> True,
-					'vtimezone'		=> Array(
+				'vtimezone' => Array (
 						'state'		=> 'required',
 						'multiples'	=> False
 					)
 				),
-				'tzname'		=> Array(
+			'tzname' => Array (
 					'type'		=> 'text',
 					'to_text'	=> True,
-					'daylight'	=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					),
-					'standard'	=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> True
-					)
-				),
-				'tzoffsetfrom'		=> Array(
+				'daylight' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					),
+				'standard' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> True
+					)
+				),
+			'tzoffsetfrom' => Array (
 					'type'		=> 'utc-offset',
 					'to_text'	=> True,
-					'daylight'		=> Array(
+				'daylight' => Array (
 						'state'		=> 'required',
 						'multiples'	=> False
 					),
-					'standard'		=> Array(
+				'standard' => Array (
 						'state'		=> 'required',
 						'multiples'	=> False
 					)
 				),
-				'tzoffsetto'		=> Array(
+			'tzoffsetto' => Array (
 					'type'		=> 'utc-offset',
 					'to_text'	=> True,
-					'daylight'		=> Array(
+				'daylight' => Array (
 						'state'		=> 'required',
 						'multiples'	=> False
 					),
-					'standard'		=> Array(
+				'standard' => Array (
 						'state'		=> 'required',
 						'multiples'	=> False
 					)
 				),
-				'tzurl'			=> Array(
+			'tzurl' => Array (
 					'type'		=> 'uri',
 					'to_text'	=> True,
-					'vtimezone'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					)
-				),
-				'uid'			=> Array(
+				'vtimezone' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					)
+				),
+			'uid' => Array (
 					'type'		=> 'text',
 					'to_text'	=> True,
-					'vevent'	=> Array(
+				'vevent' => Array (
 						'state'		=> 'required',
 						'multiples'	=> False
 					),
-					'vfreebusy'		=> Array(
+				'vfreebusy' => Array (
 						'state'		=> 'required',
 						'multiples'	=> False
 					),
-					'vjournal'		=> Array(
+				'vjournal' => Array (
 						'state'		=> 'required',
 						'multiples'	=> False
 					),
-					'vtodo'		=> Array(
+				'vtodo' => Array (
 						'state'		=> 'required',
 						'multiples'	=> False
 					)
 				),
-				'url'			=> Array(
+			'url' => Array (
 					'type'		=> 'text',
 					'to_text'	=> True,
-					'vevent'	=> Array(
+				'vevent' => Array (
 						'state'		=> 'required',
 						'multiples'	=> False
 					),
-					'vfreebusy'		=> Array(
+				'vfreebusy' => Array (
 						'state'		=> 'required',
 						'multiples'	=> False
 					),
-					'vjournal'		=> Array(
-						'state'		=> 'optional',
-						'multiples'	=> False
-					),
-					'vtodo'	=> Array(
+				'vjournal' => Array (
+						'state'		=> 'optional',
+						'multiples'	=> False
+					),
+				'vtodo' => Array (
 						'state'		=> 'required',
 						'multiples'	=> False
 					)
 				),
-				'version'			=> Array(
+			'version' => Array (
 					'type'		=> 'text',
 					'to_text'	=> True,
-					'ical'	=> Array(
+				'ical' => Array (
 						'state'		=> 'required',
 						'multiples'	=> False
@@ -790,10 +788,10 @@
 				)
 			);
-			$this->parameter = Array(
-				'altrep'		=> Array(
+		$this->parameter = Array (
+			'altrep' => Array (
 					'type'		=> 'uri',
 					'quoted'		=> True,
 					'to_text'	=> True,
-					'properties'	=> Array(
+				'properties' => Array (
 						'comment'		=> True,
 						'description'	=> True,
@@ -805,213 +803,213 @@
 					)
 				),
-				'byday'		=> Array(
+			'byday' => Array (
 					'type'		=> 'text',
 					'quoted'		=> False,
 					'to_text'	=> False,
-					'properties'	=> Array(
+				'properties' => Array (
 						'rrule'		=> True
 					)
 				),
-				'byhour'		=> Array(
+			'byhour' => Array (
 					'type'		=> 'text',
 					'quoted'		=> False,
 					'to_text'	=> False,
-					'properties'	=> Array(
+				'properties' => Array (
 						'rrule'		=> True
 					)
 				),
-				'byminute'		=> Array(
+			'byminute' => Array (
 					'type'		=> 'text',
 					'quoted'		=> False,
 					'to_text'	=> False,
-					'properties'	=> Array(
+				'properties' => Array (
 						'rrule'		=> True
 					)
 				),
-				'bymonth'		=> Array(
+			'bymonth' => Array (
 					'type'		=> 'text',
 					'quoted'		=> False,
 					'to_text'	=> False,
-					'properties'	=> Array(
+				'properties' => Array (
 						'rrule'		=> True
 					)
 				),
-				'bymonthday'	=> Array(
+			'bymonthday' => Array (
 					'type'		=> 'text',
 					'quoted'		=> False,
 					'to_text'	=> False,
-					'properties'	=> Array(
+				'properties' => Array (
 						'rrule'		=> True
 					)
 				),
-				'bysecond'		=> Array(
+			'bysecond' => Array (
 					'type'		=> 'text',
 					'quoted'		=> False,
 					'to_text'	=> False,
-					'properties'	=> Array(
+				'properties' => Array (
 						'rrule'		=> True
 					)
 				),
-				'bysetpos'		=> Array(
+			'bysetpos' => Array (
 					'type'		=> 'text',
 					'quoted'		=> False,
 					'to_text'	=> False,
-					'properties'	=> Array(
+				'properties' => Array (
 						'rrule'		=> True
 					)
 				),
-				'byweekno'		=> Array(
+			'byweekno' => Array (
 					'type'		=> 'text',
 					'quoted'		=> False,
 					'to_text'	=> False,
-					'properties'	=> Array(
+				'properties' => Array (
 						'rrule'		=> True
 					)
 				),
-				'byyearday'		=> Array(
+			'byyearday' => Array (
 					'type'		=> 'text',
 					'quoted'		=> False,
 					'to_text'	=> False,
-					'properties'	=> Array(
+				'properties' => Array (
 						'rrule'		=> True
 					)
 				),
-				'class'			=> Array(
+			'class' => Array (
 					'type'		=> 'function',
 					'function'	=> 'switch_class',
 					'quoted'		=> False,
 					'to_text'	=> False,
-					'properties'	=> Array(
+				'properties' => Array (
 						'class'			=> True
 					)
 				),
-				'cn'			=> Array(
+			'cn' => Array (
 					'type'		=> 'text',
 					'quoted'		=> True,
 					'to_text'	=> False,
-					'properties'	=> Array(
+				'properties' => Array (
 						'attendee'		=> True,
 						'organizer'		=> True
 					)
 				),
-				'count'		=> Array(
+			'count' => Array (
 					'type'		=> 'integer',
 					'quoted'		=> False,
 					'to_text'	=> False,
-					'properties'	=> Array(
+				'properties' => Array (
 						'rrule'			=> True
 					)
 				),
-				'cu'			=> Array(
+			'cu' => Array (
 					'type'		=> 'function',
 					'function'	=> 'switch_cu',
 					'quoted'		=> False,
 					'to_text'	=> False,
-					'properties'	=> Array(
+				'properties' => Array (
 						'attendee'		=> True
 					)
 				),
-				'delegated_from'	=> Array(
+			'delegated_from' => Array (
 					'type'		=> 'function',
 					'function'	=> 'switch_mailto',
 					'quoted'		=> True,
 					'to_text'	=> False,
-					'properties'	=> Array(
+				'properties' => Array (
 						'attendee'		=> True
 					)
 				),
-				'delegated_to'	=> Array(
+			'delegated_to' => Array (
 					'type'		=> 'function',
 					'function'	=> 'switch_mailto',
 					'quoted'		=> True,
 					'to_text'	=> False,
-					'properties'	=> Array(
+				'properties' => Array (
 						'attendee'		=> True
 					)
 				),
-				'dir'			=> Array(
+			'dir' => Array (
 					'type'		=> 'dir',
 					'quoted'		=> True,
 					'to_text'	=> True,
-					'properties'	=> Array(
+				'properties' => Array (
 						'attendee'		=> True,
 						'organizer'		=> True
 					)
 				),
-				'dtend'		=> Array(
+			'dtend' => Array (
 					'type'		=> 'function',
 					'function'	=> 'switch_date',
 					'quoted'		=> False,
 					'to_text'	=> False,
-					'properties'	=> Array(
+				'properties' => Array (
 						'dtend'		=> True
 					)
 				),
-				'dtstamp'		=> Array(
+			'dtstamp' => Array (
 					'type'		=> 'function',
 					'function'	=> 'switch_date',
 					'quoted'		=> False,
 					'to_text'	=> False,
-					'properties'	=> Array(
+				'properties' => Array (
 						'dtstamp'		=> True
 					)
 				),
-				'dtstart'		=> Array(
+			'dtstart' => Array (
 					'type'		=> 'function',
 					'function'	=> 'switch_date',
 					'quoted'		=> False,
 					'to_text'	=> False,
-					'properties'	=> Array(
+				'properties' => Array (
 						'dtstart'		=> True
 					)
 				),
-				'encoding'	=> Array( // was enocding ???
+			'encoding' => Array (// was enocding ???
 					'type'		=> 'function',
 					'function'	=> 'switch_encoding',
 					'quoted'		=> False,
 					'to_text'	=> False,
-					'properties'	=> Array(
+				'properties' => Array (
 						'attach'			=> True
 					)
 				),
-				'fmttype'	=> Array(
+			'fmttype' => Array (
 					'type'		=> 'text',
 					'quoted'		=> False,
 					'to_text'	=> False,
-					'properties'	=> Array(
+				'properties' => Array (
 						'attach'			=> True
 					)
 				),
-				'fbtype'		=> Array(
+			'fbtype' => Array (
 					'type'		=> 'function',
 					'function'	=> 'switch_fbtype',
 					'quoted'		=> False,
 					'to_text'	=> False,
-					'properties'	=> Array(
+				'properties' => Array (
 						'attach'			=> True
 					)
 				),
-				'freq'		=> Array(
+			'freq' => Array (
 					'type'		=> 'function',
 					'function'	=> 'switch_freq',
 					'quoted'		=> False,
 					'to_text'	=> False,
-					'properties'	=> Array(
+				'properties' => Array (
 						'rrule'			=> True
 					)
 				),
-				'interval'		=> Array(
+			'interval' => Array (
 					'type'		=> 'integer',
 					'quoted'		=> False,
 					'to_text'	=> False,
-					'properties'	=> Array(
+				'properties' => Array (
 						'rrule'		=> True
 					)
 				),
-				'language'		=> Array(
+			'language' => Array (
 					'type'		=> 'text',
 					'quoted'		=> False,
 					'to_text'	=> False,
-					'properties'	=> Array(
+				'properties' => Array (
 						'categories'	=> True,
 						'comment'		=> True,
@@ -1027,94 +1025,94 @@
 					)
 				),
-				'last_modified'		=> Array(
+			'last_modified' => Array (
 					'type'		=> 'function',
 					'function'	=> 'switch_date',
 					'quoted'		=> False,
 					'to_text'	=> False,
-					'properties'	=> Array(
+				'properties' => Array (
 						'last_modified'	=> True
 					)
 				),
-				'mailto'		=> Array(
+			'mailto' => Array (
 					'type'		=> 'function',
 					'function'	=> 'switch_mailto',
 					'quoted'		=> False,
 					'to_text'	=> False,
-					'properties'	=> Array(
+				'properties' => Array (
 						'attendee'		=> True,
 						'organizer'		=> True
 					)
 				),
-				'member'		=> Array(
+			'member' => Array (
 					'type'		=> 'function',
 					'function'	=> 'switch_mailto',
 					'quoted'		=> True,
 					'to_text'	=> False,
-					'properties'	=> Array(
+				'properties' => Array (
 						'attendee'		=> True
 					)
 				),
-				'partstat'		=> Array(
+			'partstat' => Array (
 					'type'		=> 'function',
 					'function'	=> 'switch_partstat',
 					'quoted'		=> False,
 					'to_text'	=> False,
-					'properties'	=> Array(
+				'properties' => Array (
 						'attendee'		=> True,
 						'organizer'		=> True
 					)
 				),
-				'range'		=> Array(
+			'range' => Array (
 					'type'		=> 'function',
 					'function'	=> 'switch_range',
 					'quoted'		=> False,
 					'to_text'	=> False,
-					'properties'	=> Array(
+				'properties' => Array (
 						'recurrence_id'	=> True
 					)
 				),
-				'related'		=> Array(
+			'related' => Array (
 					'type'		=> 'function',
 					'function'	=> 'switch_related',
 					'quoted'		=> False,
 					'to_text'	=> False,
-					'properties'	=> Array(
+				'properties' => Array (
 						'related_to'	=> True
 					)
 				),
-				'role'		=> Array(
+			'role' => Array (
 					'type'		=> 'function',
 					'function'	=> 'switch_role',
 					'quoted'		=> False,
 					'to_text'	=> False,
-					'properties'	=> Array(
+				'properties' => Array (
 						'attendee'		=> True,
 						'organizer'		=> True
 					)
 				),
-				'rsvp'		=> Array(
+			'rsvp' => Array (
 					'type'		=> 'function',
 					'function'	=> 'switch_rsvp',
 					'quoted'		=> False,
 					'to_text'	=> False,
-					'properties'	=> Array(
+				'properties' => Array (
 						'attendee'		=> True
 					)
 				),
-				'sent_by'		=> Array(
+			'sent_by' => Array (
 					'type'		=> 'function',
 					'function'	=> 'parse_user_host',
 					'quoted'		=> True,
 					'to_text'	=> False,
-					'properties'	=> Array(
+				'properties' => Array (
 						'attendee'		=> True,
 						'organizer'		=> True
 					)
 				),
-				'tzid'		=> Array(
+			'tzid' => Array (
 					'type'		=> 'text',
 					'quoted'		=> False,
 					'to_text'	=> False,
-					'properties'	=> Array(
+				'properties' => Array (
 						'dtend'		=> True,
 						'due'			=> True,
@@ -1125,18 +1123,18 @@
 					)
 				),
-				'until'		=> Array(
+			'until' => Array (
 					'type'		=> 'function',
 					'function'	=> 'switch_date',
 					'quoted'		=> False,
 					'to_text'	=> False,
-					'properties'	=> Array(
+				'properties' => Array (
 						'rrule'		=> True
 					)
 				),
-				'value'		=> Array(
+			'value' => Array (
 					'type'		=> 'value',
 					'quoted'		=> False,
 					'to_text'	=> False,
-					'properties'	=> Array(
+				'properties' => Array (
 						'calscale'	=> True,
 						'prodid'		=> True,
@@ -1188,17 +1186,17 @@
 					)
 				),
-				'wkst'		=> Array(
+			'wkst' => Array (
 					'type'		=> 'string',
 					'quoted'		=> False,
 					'to_text'	=> False,
-					'properties'	=> Array(
+				'properties' => Array (
 						'rrule'		=> True
 					)
 				),
-				'x_type'		=> Array(
+			'x_type' => Array (
 					'type'		=> 'x_type',
 					'quoted'		=> False,
 					'to_text'	=> False,
-					'properties'	=> Array(
+				'properties' => Array (
 						'calscale'	=> True,
 						'method'		=> True,
@@ -1251,13 +1249,11 @@
 				)
 			);
-			if(!is_object($GLOBALS['phpgw']->datetime))
-			{
+		if (!is_object($GLOBALS['phpgw']->datetime)) {
 				$GLOBALS['phpgw']->datetime = createobject('phpgwapi.date_time');
 			}
 		}
 
-		function set_var(&$event,$type,$value)
-		{
-			$type = strtolower(str_replace('-','_',$type));
+	function set_var(& $event, $type, $value) {
+		$type = strtolower(str_replace('-', '_', $type));
 			$event[$type] = $value;
 			/*
@@ -1273,76 +1269,68 @@
 		}
 
-		function read_line_unfold($ical_text)
-		{
-			if($this->line < count($ical_text))
-			{
-				$str = str_replace(array("\r\n","\r","\n"), '', $ical_text[$this->line]);
+	function read_line_unfold($ical_text) {
+		if ($this->line < count($ical_text)) {
+			$str = str_replace(array (
+				"\r\n",
+				"\r",
+				"\n"
+			), '', $ical_text[$this->line]);
 
 				$this->line = $this->line + 1;
-				while(ereg("^[[:space:]]",$ical_text[$this->line]))
-				{
-					$str .= substr(str_replace("\r\n",'',$ical_text[$this->line]),1);
+			while (ereg("^[[:space:]]", $ical_text[$this->line])) {
+				$str .= substr(str_replace("\r\n", '', $ical_text[$this->line]), 1);
 					$this->line = $this->line + 1;
 				}
 				
-				// Corrige a codificacao dos caracteres
-				$str = trim ($str);
-				if ( mb_detect_encoding($str, 'auto') == 'UTF-8' )
-					$str = preg_replace("/([\xC2\xC3])([\x80-\xBF])/e","chr(ord('\\1')<<6&0xC0|ord('\\2')&0x3F)",$str);
+			// Corrige a codificacao dos caracteres, caso haja suporte a mesma.
+			$str = trim($str);
+			if (mb_detect_encoding($str, 'auto') == 'UTF-8')
+				if ($conv = preg_replace("/([\xC2\xC3])([\x80-\xBF])/e", "chr(ord('\\1')<<6&0xC0|ord('\\2')&0x3F)", $str))
+					$str = $conv;
 
 				//$this->debug("LINE : ".$str);
 				return $str;
-			}
-			else
-			{
+		} else {
 				return False;
 			}
 		}
 
-		function fold($str)
-		{
-			return $this->chunk_split==True ? chunk_split($str,FOLD_LENGTH,"\r\n") : $str."\r\n";
-		}
-
-		function strip_quotes($str)
-		{
-			return str_replace('"','',$str);
-		}
-
-		function from_text($str)
-		{
-			$str = str_replace("\\,",",",$str);
-			$str = str_replace("\\;",";",$str);
-			$str = str_replace("\\N","\n",$str);
-			$str = str_replace("\\n","\n",$str);
-			$str = str_replace("\\\\","\\",$str);
+	function fold($str) {
+		return $this->chunk_split == True ? chunk_split($str, FOLD_LENGTH, "\r\n") : $str . "\r\n";
+		}
+
+	function strip_quotes($str) {
+		return str_replace('"', '', $str);
+		}
+
+	function from_text($str) {
+		$str = str_replace("\\,", ",", $str);
+		$str = str_replace("\\;", ";", $str);
+		$str = str_replace("\\N", "\n", $str);
+		$str = str_replace("\\n", "\n", $str);
+		$str = str_replace("\\\\", "\\", $str);
 			return "$str";
 		}
 
-		function to_text($str)
-		{
-			$str = str_replace("\\","\\\\",$str);
-			$str = str_replace(",","\\,",$str);
-			$str = str_replace(";","\\;",$str);
-			$str = str_replace("\n","\\n",$str);
+	function to_text($str) {
+		$str = str_replace("\\", "\\\\", $str);
+		$str = str_replace(",", "\\,", $str);
+		$str = str_replace(";", "\\;", $str);
+		$str = str_replace("\n", "\\n", $str);
 			return "$str";
 		}
 
-		function from_dir($str)
-		{
-			return str_replace('=3D','=',str_replace('%20',' ',$str));
-		}
-
-		function to_dir($str)
-		{
-			return str_replace('=','=3D',str_replace(' ','%20',$str));
-		}
-
-		function find_parameters($property)
-		{
+	function from_dir($str) {
+		return str_replace('=3D', '=', str_replace('%20', ' ', $str));
+		}
+
+	function to_dir($str) {
+		return str_replace('=', '=3D', str_replace(' ', '%20', $str));
+		}
+
+	function find_parameters($property) {
 			static  $cached_returns;
 
-			if(isset($cached_returns[$property]))
-			{
+		if (isset ($cached_returns[$property])) {
 				reset($cached_returns[$property]);
 				return $cached_returns[$property];
@@ -1350,10 +1338,8 @@
 
 			reset($this->parameter);
-			while(list($key,$param_array) = each($this->parameter))
-			{
-				if($param_array['properties'][$property])
-				{
+		while (list ($key, $param_array) = each($this->parameter)) {
+			if ($param_array['properties'][$property]) {
 					$param[] = $key;
-					$this->debug('Property : '.$property.' = Parameter : '.$key);
+				$this->debug('Property : ' . $property . ' = Parameter : ' . $key);
 				}
 			}
@@ -1363,10 +1349,8 @@
 		}
 
-		function find_properties($ical_type)
-		{
+	function find_properties($ical_type) {
 			static  $cached_returns;
 
-			if(isset($cached_returns[$ical_type]))
-			{
+		if (isset ($cached_returns[$ical_type])) {
 				reset($cached_returns[$ical_type]);
 				return $cached_returns[$ical_type];
@@ -1374,8 +1358,6 @@
 
 			reset($this->property);
-			while(list($key,$param_array) = each($this->property))
-			{
-				if($param_array[$ical_type])
-				{
+		while (list ($key, $param_array) = each($this->property)) {
+			if ($param_array[$ical_type]) {
 					$prop[] = $key;
 				}
@@ -1386,7 +1368,6 @@
 		}
 
-		function new_ical()
-		{
-			return Array();
+	function new_ical() {
+		return Array ();
 		}
 
@@ -1395,9 +1376,7 @@
 		*/
 
-		function parse_geo(&$event,$value)
-		{
+	function parse_geo(& $event, $value) {
 			//		$return_value = $this->explode_param($value,True);
-			if(count($return_value) == 2)
-			{
+		if (count($return_value) == 2) {
 				$event['lat'] = $return_value[0];
 				$event['lon'] = $return_value[1];
@@ -1405,17 +1384,14 @@
 		}
 
-		function parse_xtype(&$event,$majortype,$value)
-		{
-			$temp_x_type['name'] = strtoupper(substr($majortype,2));
+	function parse_xtype(& $event, $majortype, $value) {
+		$temp_x_type['name'] = strtoupper(substr($majortype, 2));
 			$temp_x_type['value'] = $value;
 			$event['x_type'][] = $temp_x_type;
 		}
 
-		function parse_parameters(&$event,$majortype,$value)
-		{
+	function parse_parameters(& $event, $majortype, $value) {
 			//$this->debug ('value: '.$value);
-			if(!ereg('[\=\;]',$value))
-			{
-				$return_value[] = Array(
+		if (!ereg('[\=\;]', $value)) {
+			$return_value[] = Array (
 					'param'	=> $majortype,
 					'value'	=> $value
@@ -1423,21 +1399,18 @@
 				$value = '';
 			}
-			elseif(ereg('(.*(\:\\\\)?.*):(.*)',$value,$temp))
-			{
+		elseif (ereg('(.*(\:\\\\)?.*):(.*)', $value, $temp)) {
 				//$this->debug('Value : '._debug_array($temp,False));
 				//$this->debug('Param '.$majortype.' Value : '.$temp[3]);
-				if($temp[3])
-				{
-					$return_value[] = Array(
+			if ($temp[3]) {
+				$return_value[] = Array (
 						'param'	=> $majortype,
 						'value'	=> $temp[3]
 					);
-					$value = str_replace(':MAILTO','',$temp[1]);
-				}
-				while(ereg('(([A-Z\-]*)[=]([[:alnum:] \_\)\(\/\$\.\,\:\\\|\*\&\^\%\#\!\~\"\?\&\@\<\>\-]*))([\;]?)(.*)',$value,$temp))
-				{
+				$value = str_replace(':MAILTO', '', $temp[1]);
+				}
+			while (ereg('(([A-Z\-]*)[=]([[:alnum:] \_\)\(\/\$\.\,\:\\\|\*\&\^\%\#\!\~\"\?\&\@\<\>\-]*))([\;]?)(.*)', $value, $temp)) {
 					//$this->debug('Value : '._debug_array($temp,False));
 					//$this->debug('Param '.$temp[2].' Value : '.$temp[3]);
-					$return_value[] = Array(
+				$return_value[] = Array (
 						'param'	=> $temp[2],
 						'value'	=> $temp[3]
@@ -1446,17 +1419,14 @@
 					//$this->debug('Value would be = '.$value);
 				}
-			}
-			else
-			{
-				while(ereg('(([A-Z\-]*)[=]([[:alnum:] \_\)\(\/\$\.\,\:\\\|\*\&\^\%\#\!\~\"\?\&\@\<\>\-]*))([\;]?)(.*)',$value,$temp))
-				{
-					$this->debug('Value : '._debug_array($temp,False));
-					$this->debug('Param '.$temp[2].' Value : '.$temp[3]);
-					$return_value[] = Array(
+		} else {
+			while (ereg('(([A-Z\-]*)[=]([[:alnum:] \_\)\(\/\$\.\,\:\\\|\*\&\^\%\#\!\~\"\?\&\@\<\>\-]*))([\;]?)(.*)', $value, $temp)) {
+				$this->debug('Value : ' . _debug_array($temp, False));
+				$this->debug('Param ' . $temp[2] . ' Value : ' . $temp[3]);
+				$return_value[] = Array (
 						'param'	=> $temp[2],
 						'value'	=> $temp[3]
 					);
 					$value = chop($temp[5]);
-					$this->debug('Value would be = '.$value);
+				$this->debug('Value would be = ' . $value);
 				}
 			}
@@ -1464,25 +1434,17 @@
 			//$this->debug('parse_parameters array return_value: '._debug_array($return_value,False));
 
-			for($i=0;$i<count($return_value);$i++)
-			{
+		for ($i = 0; $i < count($return_value); $i++) {
 				$name = strtolower($return_value[$i]['param']);
 				$value = $this->strip_quotes($return_value[$i]['value']);
-				if(substr($name,0,2) == 'x-')
-				{
+			if (substr($name, 0, 2) == 'x-') {
 					$param = 'x_type';
-					$name = str_replace('-','_',$return_value[$i]['param']);
-				}
-				else
-				{
-					$param = str_replace('-','_',strtolower($name));
-					if(!isset($this->parameter[$param]) || $majortype == 'tzid')
-					{
-						if($majortype == 'attendee' || $majortype == 'organizer')
-						{
+				$name = str_replace('-', '_', $return_value[$i]['param']);
+			} else {
+				$param = str_replace('-', '_', strtolower($name));
+				if (!isset ($this->parameter[$param]) || $majortype == 'tzid') {
+					if ($majortype == 'attendee' || $majortype == 'organizer') {
 							$param = 'mailto';
 							$name = $param;
-						}
-						else
-						{
+					} else {
 							$param = 'value';
 						}
@@ -1490,41 +1452,36 @@
 				}
 				//$this->debug('name : '.$name.' : Param = '.$param);
-				if(@$this->parameter[$param]['properties'][$majortype])
-				{
-					switch(@$this->parameter[$param]['type'])
-					{
-						case 'dir':
-							$this->set_var($event,$name,$this->from_dir($value));
+			if (@ $this->parameter[$param]['properties'][$majortype]) {
+				switch (@ $this->parameter[$param]['type']) {
+					case 'dir' :
+						$this->set_var($event, $name, $this->from_dir($value));
 							break;
-						case 'text':
-							$this->set_var($event,$name,$value);
+					case 'text' :
+						$this->set_var($event, $name, $value);
 							break;
-						case 'x_type':
-							$this->parse_xtype($event,$name,$value);
+					case 'x_type' :
+						$this->parse_xtype($event, $name, $value);
 							break;
-						case 'function':
+					case 'function' :
 							$function = $this->parameter[$param]['function'];
-							$this->set_var($event,$name,$this->$function($value));
+						$this->set_var($event, $name, $this-> $function ($value));
 							break;
-						case 'uri':
-							if(@$this->parameter[$param]['to_text'])
-							{
+					case 'uri' :
+						if (@ $this->parameter[$param]['to_text']) {
 								$value = $this->to_text($value);
 							}
-							$this->set_var($event,$name,$value);
+						$this->set_var($event, $name, $value);
 							break;
-						case 'integer':
-							$this->set_var($event,$name,(int)$value);
+					case 'integer' :
+						$this->set_var($event, $name, (int) $value);
 							break;
-						case 'value':
-							if(@$this->property[$majortype]['type'] == 'date-time')
-							{
-								$this->set_var($event,$param,$this->switch_date($name));
+					case 'value' :
+						if (@ $this->property[$majortype]['type'] == 'date-time') {
+							$this->set_var($event, $param, $this->switch_date($name));
 							}
-							elseif($value <> "\\n" && $value)
-							{
-								$this->set_var($event[$majortype],$param,$value);
+						elseif ($value <> "\\n" && $value) {
+							$this->set_var($event[$majortype], $param, $value);
 							}
-							$this->debug('Event : '._debug_array($event,False));
+						$this->debug('Event : ' . _debug_array($event, False));
 							break;
 					}
@@ -1533,28 +1490,21 @@
 		}
 
-		function parse_value(&$event,$majortype,$value,$mode)
-		{
-			$var = Array();
+	function parse_value(& $event, $majortype, $value, $mode) {
+		$var = Array ();
 			//$this->debug('Mode : '.$mode.' Majortype : '.$majortype);
-			$this->parse_parameters($var,$majortype,$value);
-			if($this->property[$majortype][$mode]['multiples'])
-			{
+		$this->parse_parameters($var, $majortype, $value);
+		if ($this->property[$majortype][$mode]['multiples']) {
 				//$this->debug('parse_value var array: '._debug_array($var,False));
 				$event[$majortype][] = $var;
-			}
-			else
-			{
+		} else {
 				//$this->debug('Majortype : '.$majortype);
 				//$this->debug('Property : '.$this->property[$majortype]['type']);
-				if($this->property[$majortype]['type'] == 'date-time')
-				{
+			if ($this->property[$majortype]['type'] == 'date-time') {
 					//$this->debug('Got a DATE-TIME type!');
 					$t_var = $var[$majortype];
-					unset($var[$majortype]);
-					if ( $t_var )
-					{
+				unset ($var[$majortype]);
+				if ($t_var) {
 						reset($t_var);
-						while(list($key,$val) = each($t_var))
-						{
+					while (list ($key, $val) = each($t_var)) {
 							$var[$key] = $val;
 						}
@@ -1562,5 +1512,5 @@
 					}
 				}
-				$this->set_var($event,$majortype,$var);
+			$this->set_var($event, $majortype, $var);
 			}
 		}
@@ -1570,25 +1520,19 @@
 		 */
 
-		function build_xtype($x_type,$seperator='=')
-		{
+	function build_xtype($x_type, $seperator = '=') {
 			$quote = '';
-			if($seperator == '=')
-			{
+		if ($seperator == '=') {
 				$quote = '"';
 			}
 
-			$return_value = $this->fold('X-'.$x_type['name'].$seperator.$quote.$x_type['value'].$quote);
-			if($seperator == '=')
-			{
-				return str_replace("\r\n",'',$return_value);
-			}
-			else
-			{
+		$return_value = $this->fold('X-' . $x_type['name'] . $seperator . $quote . $x_type['value'] . $quote);
+		if ($seperator == '=') {
+			return str_replace("\r\n", '', $return_value);
+		} else {
 				return $return_value;
 			}
 		}
 
-		function build_parameters($event,$property)
-		{
+	function build_parameters($event, $property) {
 			$str = '';
 			$include_mailto = False;
@@ -1596,304 +1540,231 @@
 			$param = $this->find_parameters($property);
 
-			if($property == 'exdate')
-			{
-				while(list($key,$value) = each($event))
-				{
+		if ($property == 'exdate') {
+			while (list ($key, $value) = each($event)) {
 					$exdates[] = $this->switch_date($value);
 				}
-				return ':'.implode($exdates,',');
-			}
-			else
-			{
-				while(list($dumb_key,$key) = each($param))
-				{
-					if($key == 'value')
-					{
+			return ':' . implode($exdates, ',');
+		} else {
+			while (list ($dumb_key, $key) = each($param)) {
+				if ($key == 'value') {
 						continue;
 					}
-					if($key == 'mailto')
-					{
+				if ($key == 'mailto') {
 						$include_mailto = True;
 						continue;
 					}
-					$param_array = @$this->parameter[$key];
-					$type = @$this->parameter[$key]['type'];
-					if($type == 'date-time')
-					{
+				$param_array = @ $this->parameter[$key];
+				$type = @ $this->parameter[$key]['type'];
+				if ($type == 'date-time') {
 						$include_datetime = True;
 						continue;
 					}
-					$quote = (@$this->parameter[$key]['quoted']?'"':'');
-					if(isset($event[$key]) && @$this->parameter[$key]['properties'][$property])
-					{
-						$change_text = @$this->parameter[$key]['to_text'];
+				$quote = (@ $this->parameter[$key]['quoted'] ? '"' : '');
+				if (isset ($event[$key]) && @ $this->parameter[$key]['properties'][$property]) {
+					$change_text = @ $this->parameter[$key]['to_text'];
 						$value = $event[$key];
-						if($change_text && $type == 'text')
-						{
+					if ($change_text && $type == 'text') {
 							$value = $this->to_text($value);
 						}
-						switch($type)
-						{
-							case 'dir':
-								$str .= ';'.str_replace('_','-',strtoupper($key)).'='.$quote.$this->to_dir($value).$quote;
+					switch ($type) {
+						case 'dir' :
+							$str .= ';' . str_replace('_', '-', strtoupper($key)) . '=' . $quote . $this->to_dir($value) . $quote;
 								break;
-							case 'function':
-								$str .= ';'.str_replace('_','-',strtoupper($key)).'=';
+						case 'function' :
+							$str .= ';' . str_replace('_', '-', strtoupper($key)) . '=';
 								$function = $this->parameter[$key]['function'];
-								$this->debug($key.' Function Param : '.$value);
-								$str .= $quote.$this->$function($value).$quote;
+							$this->debug($key . ' Function Param : ' . $value);
+							$str .= $quote . $this-> $function ($value) . $quote;
 								break;
-							case 'text':
-							case 'string':
-								$str .= ';'.strtoupper($key).'='.$quote.$value.$quote;
+						case 'text' :
+						case 'string' :
+							$str .= ';' . strtoupper($key) . '=' . $quote . $value . $quote;
 								break;
-							case 'date-time':
-								$str .= ($key=='until'?':':';UNTIL=').date('Ymd\THis',mktime($event['hour'],$event['min'],$event['sec'],$event['month'],$event['mday'],$event['year'])).(!@isset($event['tzid'])?'Z':'');
+						case 'date-time' :
+							$str .= ($key == 'until' ? ':' : ';UNTIL=') . date('Ymd\THis', mktime($event['hour'], $event['min'], $event['sec'], $event['month'], $event['mday'], $event['year'])) . (!@ isset ($event['tzid']) ? 'Z' : '');
 								break;
 						}
-						unset($value);
-					}
-				}
-
-				if(!empty($event['x_type']))
-				{
+					unset ($value);
+					}
+				}
+
+			if (!empty ($event['x_type'])) {
 					$c_x_type = count($event['x_type']);
-					for($j=0;$j<$c_x_type;$j++)
-					{
-						$str .= ';'.$this->build_xtype($event['x_type'][$j],'=');
-					}
-				}
-				if(!empty($event['value']))
-				{
-					if($property == 'trigger')
-					{
+				for ($j = 0; $j < $c_x_type; $j++) {
+					$str .= ';' . $this->build_xtype($event['x_type'][$j], '=');
+					}
+				}
+			if (!empty ($event['value'])) {
+				if ($property == 'trigger') {
 						$seperator = ';';
-					}
-					else
-					{
+				} else {
 						$seperator = ':';
 					}
-					$str .= $seperator.($this->parameter['value']['to_text']?$this->to_text($event['value']):$event['value']);
-				}
-				if($include_mailto == True)
-				{
+				$str .= $seperator . ($this->parameter['value']['to_text'] ? $this->to_text($event['value']) : $event['value']);
+				}
+			if ($include_mailto == True) {
 					$key = 'mailto';
 					$function = $this->parameter[$key]['function'];
-					$ret_value = $this->$function($event[$key]);
-					$str .= ($ret_value?':'.$ret_value:'');
-				}
-				if($include_datetime == True || @$this->property[$property]['type'] == 'date-time')
-				{
-					$str .= ':'.date('Ymd\THis',mktime($event['hour'],$event['min'],$event['sec'],$event['month'],$event['mday'],$event['year'])).(!@isset($event['tzid'])?'Z':'');
-				}
-				return ($property=='rrule'?':'.substr($str,1):$str);
-			}
-		}
-
-		function build_text($event,$property)
-		{
+				$ret_value = $this-> $function ($event[$key]);
+				$str .= ($ret_value ? ':' . $ret_value : '');
+				}
+			if ($include_datetime == True || @ $this->property[$property]['type'] == 'date-time') {
+				$str .= ':' . date('Ymd\THis', mktime($event['hour'], $event['min'], $event['sec'], $event['month'], $event['mday'], $event['year'])) . (!@ isset ($event['tzid']) ? 'Z' : '');
+				}
+			return ($property == 'rrule' ? ':' . substr($str, 1) : $str);
+			}
+		}
+
+	function build_text($event, $property) {
 			$str = '';
 			$param = $this->find_parameters($property);
-			while(list($dumb_key,$key) = each($param))
-			{
-				if(!empty($event[$key]) && $key != 'value')
-				{
-					$type = @$this->parameter[$key]['type'];
-					$quote = @$this->parameter[$key]['quote'];
-					if(@$this->parameter[$key]['to_text'] == True)
-					{
+		while (list ($dumb_key, $key) = each($param)) {
+			if (!empty ($event[$key]) && $key != 'value') {
+				$type = @ $this->parameter[$key]['type'];
+				$quote = @ $this->parameter[$key]['quote'];
+				if (@ $this->parameter[$key]['to_text'] == True) {
 						$value = $this->to_text($event[$key]);
-					}
-					else
-					{
+				} else {
 						$value = $event[$key];
 					}
-					switch($type)
-					{
-						case 'text':
-						$str .= ';'.strtoupper($key).'='.$quote.$value.$quote;
-						break;
-					}
-				}
-			}
-			if(!empty($event['x_type']))
-			{
+				switch ($type) {
+					case 'text' :
+						$str .= ';' . strtoupper($key) . '=' . $quote . $value . $quote;
+						break;
+					}
+				}
+			}
+		if (!empty ($event['x_type'])) {
 				$c_x_type = count($event['x_type']);
-				for($j=0;$j<$c_x_type;$j++)
-				{
-					$str .= ';'.$this->build_xtype($event['x_type'][$j],'=');
-				}
-			}
-			if(!empty($event['value']))
-			{
-				$str .= ':'.($this->parameter['value']['to_text']?$this->to_text($event['value']):$event['value']);
+			for ($j = 0; $j < $c_x_type; $j++) {
+				$str .= ';' . $this->build_xtype($event['x_type'][$j], '=');
+				}
+			}
+		if (!empty ($event['value'])) {
+			$str .= ':' . ($this->parameter['value']['to_text'] ? $this->to_text($event['value']) : $event['value']);
 			}
 			return $str;
 		}
 
-		function build_card_internals($ical_item,$event)
-		{
+	function build_card_internals($ical_item, $event) {
 			$prop = $this->find_properties($ical_item);
 			reset($prop);
-			while(list($dumb_key,$key) = each($prop))
-			{
+		while (list ($dumb_key, $key) = each($prop)) {
 				$value  = $key;
 				$varray = $this->property[$key];
 				$type   = $varray['type'];
 				$to_text = $varray['to_text'];
-				$state  = @$varray[$ical_item]['state'];
-				$multiples  = @$varray[$ical_item]['multiples'];
-				switch($type)
-				{
-					case 'date-time':
-						if(!empty($event[$value]))
-						{
-							if($multiples && $value != 'exdate')
-							{
-								for($i=0;$i<count($event[$value]);$i++)
-								{
-									$str .= $this->fold(strtoupper(str_replace('_','-',$value)).$this->build_parameters($event[$value][$i],$value));
+			$state = @ $varray[$ical_item]['state'];
+			$multiples = @ $varray[$ical_item]['multiples'];
+			switch ($type) {
+				case 'date-time' :
+					if (!empty ($event[$value])) {
+						if ($multiples && $value != 'exdate') {
+							for ($i = 0; $i < count($event[$value]); $i++) {
+								$str .= $this->fold(strtoupper(str_replace('_', '-', $value)) . $this->build_parameters($event[$value][$i], $value));
+								}
+						} else {
+							$str .= $this->fold(strtoupper(str_replace('_', '-', $value)) . $this->build_parameters($event[$value], $value));
+							}
+						}
+					elseif ($value == 'dtstamp' || $value == 'created') {
+						$str .= $this->fold(strtoupper(str_replace('_', '-', $value)) . ':' . gmdate('Ymd\THis\Z'));
+						}
+						break;
+				case 'uri' :
+					if (!empty ($event[$value])) {
+						for ($i = 0; $i < count($event[$value]); $i++) {
+							$str .= $this->fold(strtoupper(str_replace('_', '-', $value)) . $this->build_parameters($event[$value][$i], $to_text));
+							}
+						}
+						break;
+				case 'recur' :
+					if (!empty ($event[$value])) {
+						if ($multiples) {
+							for ($i = 0; $i < count($event[$value]); $i++) {
+								$str .= $this->fold(strtoupper(str_replace('_', '-', $value)) . $this->build_parameters($event[$value][$i], $value));
+							}
+						} else {
+							$str .= $this->fold(strtoupper(str_replace('_', '-', $value)) . $this->build_parameters($event[$value], $value));
+							}
+						}
+						break;
+				case 'integer' :
+					if (!empty ($event[$value])) {
+						$str .= $this->fold(strtoupper(str_replace('_', '-', $value)) . ':' . $event[$value]);
+						}
+					elseif ($value == 'sequence' || $value == 'percent_complete') {
+						$str .= $this->fold(strtoupper(str_replace('_', '-', $value)) . ':0');
+						}
+						break;
+				case 'function' :
+					$str .= ';' . str_replace('_', '-', strtoupper($value)) . '=';
+					$function = @ $this->parameter[$key]['function'];
+					$str .= (@ $this->parameter[$key]['quoted'] ? '"' : '') . $this-> $function ($event[$key]) . (@ $this->parameter[$key]['quoted'] ? '"' : '');
+						break;
+				case 'float' :
+					if (!empty ($event[$value])) {
+						$str .= $this->fold(strtoupper(str_replace('_', '-', $value)) . ':' . $event[$value]['lat'] . ';' . $event[$value]['lon']);
+						}
+						break;
+				case 'text' :
+					if (isset ($event[$value])) {
+						if (@ $this->parameter[$key]['type'] != 'function') {
+							if ($multiples && count($event[$value]) > 1) {
+								for ($i = 0; $i < count($event[$value]); $i++) {
+									$str .= $this->fold(strtoupper(str_replace('_', '-', $value)) . $this->build_parameters($event[$value][$i], $value));
+								}
+							} else {
+								$str .= $this->fold(strtoupper(str_replace('_', '-', $value)) . $this->build_parameters($event[$value], $value));
+							}
+						} else {
+								$function = $this->parameter[$value]['function'];
+							if ($multiples) {
+								for ($i = 0; $i < count($event[$value]); $i++) {
+									$str .= $this->fold(strtoupper(str_replace('_', '-', $value)) . ':' . $this-> $function ($event[$value][$i]));
+								}
+							} else {
+								$str .= $this->fold(strtoupper(str_replace('_', '-', $value)) . ':' . $this-> $function ($event[$value]));
 								}
 							}
-							else
-							{
-								$str .= $this->fold(strtoupper(str_replace('_','-',$value)).$this->build_parameters($event[$value],$value));
+						}
+						break;
+				case 'cal-address' :
+					if (is_array($event[$value][0])) {
+						for ($j = 0; $j < count($event[$value]); $j++) {
+							$temp_output = $this->build_parameters($event[$value][$j], $value);
+							if ($temp_output) {
+								$str .= $this->fold(strtoupper(str_replace('_', '-', $value)) . $temp_output);
 							}
 						}
-						elseif($value == 'dtstamp' || $value == 'created')
-						{
-							$str .= $this->fold(strtoupper(str_replace('_','-',$value)).':'.gmdate('Ymd\THis\Z'));
-						}
-						break;
-					case 'uri':
-						if(!empty($event[$value]))
-						{
-							for($i=0;$i<count($event[$value]);$i++)
-							{
-								$str .= $this->fold(strtoupper(str_replace('_','-',$value)).$this->build_parameters($event[$value][$i],$to_text));
+					} else {
+						$temp_output = $this->build_parameters($event[$value], $value);
+						if ($temp_output) {
+							$str .= $this->fold(strtoupper(str_replace('_', '-', $value)) . $temp_output);
 							}
 						}
 						break;
-					case 'recur':
-						if(!empty($event[$value]))
-						{
-							if($multiples)
-							{
-								for($i=0;$i<count($event[$value]);$i++)
-								{
-									$str .= $this->fold(strtoupper(str_replace('_','-',$value)).$this->build_parameters($event[$value][$i],$value));
-								}
-							}
-							else
-							{
-								$str .= $this->fold(strtoupper(str_replace('_','-',$value)).$this->build_parameters($event[$value],$value));
-							}
-						}
-						break;
-					case 'integer':
-						if(!empty($event[$value]))
-						{
-							$str .= $this->fold(strtoupper(str_replace('_','-',$value)).':'.$event[$value]);
-						}
-						elseif($value == 'sequence' || $value == 'percent_complete')
-						{
-							$str .= $this->fold(strtoupper(str_replace('_','-',$value)).':0');
-						}
-						break;
-					case 'function':
-						$str .= ';'.str_replace('_','-',strtoupper($value)).'=';
-						$function = @$this->parameter[$key]['function'];
-						$str .= (@$this->parameter[$key]['quoted']?'"':'').$this->$function($event[$key]).(@$this->parameter[$key]['quoted']?'"':'');
-						break;
-					case 'float':
-						if(!empty($event[$value]))
-						{
-							$str .= $this->fold(strtoupper(str_replace('_','-',$value)).':'.$event[$value]['lat'].';'.$event[$value]['lon']);
-						}
-						break;
-					case 'text':
-						if(isset($event[$value]))
-						{
-							if(@$this->parameter[$key]['type'] != 'function')
-							{
-								if($multiples && count($event[$value]) > 1)
-								{
-									for($i=0;$i<count($event[$value]);$i++)
-									{
-										$str .= $this->fold(strtoupper(str_replace('_','-',$value)).$this->build_parameters($event[$value][$i],$value));
-									}
-								}
-								else
-								{
-									$str .= $this->fold(strtoupper(str_replace('_','-',$value)).$this->build_parameters($event[$value],$value));
-								}
-							}
-							else
-							{
-								$function = $this->parameter[$value]['function'];
-								if($multiples)
-								{
-									for($i=0;$i<count($event[$value]);$i++)
-									{
-										$str .= $this->fold(strtoupper(str_replace('_','-',$value)).':'.$this->$function($event[$value][$i]));
-									}
-								}
-								else
-								{
-									$str .= $this->fold(strtoupper(str_replace('_','-',$value)).':'.$this->$function($event[$value]));
-								}
-							}
-						}
-						break;
-					case 'cal-address':
-						if(is_array($event[$value][0]))
-						{
-							for($j=0;$j<count($event[$value]);$j++)
-							{
-								$temp_output = $this->build_parameters($event[$value][$j],$value);
-								if($temp_output)
-								{
-									$str .= $this->fold(strtoupper(str_replace('_','-',$value)).$temp_output);
-								}
-							}
-						}
-						else
-						{
-							$temp_output = $this->build_parameters($event[$value],$value);
-							if($temp_output)
-							{
-								$str .= $this->fold(strtoupper(str_replace('_','-',$value)).$temp_output);
-							}
-						}
-						break;
-				}
-			}
-			if(!empty($event['x_type']))
-			{
-				for($i=0;$i<count($event['x_type']);$i++)
-				{
-					$str .= $this->build_xtype($event['x_type'][$i],':');
-				}
-			}
-
-			if($ical_item == 'vtimezone')
-			{
-				if($event['tzdata'])
-				{
-					for($k=0;$k<count($event['tzdata']);$k++)
-					{
-						$str .= 'BEGIN:'.strtoupper($event['tzdata'][$k]['type'])."\r\n";
-						$str .= $this->build_card_internals(strtolower($event['tzdata'][$k]['type']),$event['tzdata'][$k]);
-						$str .= 'END:'.strtoupper($event['tzdata'][$k]['type'])."\r\n";
-					}
-				}
-			}
-			elseif($event['alarm'])
-			{
-				for($k=0;$k<count($event['alarm']);$k++)
-				{
-					$str .= 'BEGIN:VALARM'."\r\n";
-					$str .= $this->build_card_internals('valarm',$event['alarm'][$k]);
-					$str .= 'END:VALARM'."\r\n";
+				}
+			}
+		if (!empty ($event['x_type'])) {
+			for ($i = 0; $i < count($event['x_type']); $i++) {
+				$str .= $this->build_xtype($event['x_type'][$i], ':');
+				}
+			}
+
+		if ($ical_item == 'vtimezone') {
+			if ($event['tzdata']) {
+				for ($k = 0; $k < count($event['tzdata']); $k++) {
+					$str .= 'BEGIN:' . strtoupper($event['tzdata'][$k]['type']) . "\r\n";
+					$str .= $this->build_card_internals(strtolower($event['tzdata'][$k]['type']), $event['tzdata'][$k]);
+					$str .= 'END:' . strtoupper($event['tzdata'][$k]['type']) . "\r\n";
+					}
+				}
+			}
+		elseif ($event['alarm']) {
+			for ($k = 0; $k < count($event['alarm']); $k++) {
+				$str .= 'BEGIN:VALARM' . "\r\n";
+				$str .= $this->build_card_internals('valarm', $event['alarm'][$k]);
+				$str .= 'END:VALARM' . "\r\n";
 				}
 			}
@@ -1905,37 +1776,31 @@
 		*/
 		
-		function parse_user_host ($var)
-		{
+	function parse_user_host($var) {
 			return $this->switch_mailto($var);	
 		}
 
-		function switch_class($var)
-		{
-			if(is_string($var))
-			{
-				switch($var)
-				{
-					case '_PRIVATE':
+	function switch_class($var) {
+		if (is_string($var)) {
+			switch ($var) {
+				case '_PRIVATE' :
 						$var = _PRIVATE;
 						break;
-					case '_PUBLIC':
+				case '_PUBLIC' :
 						$var = _PUBLIC;
 						break;
-					case '_CONFIDENTIAL':
+				case '_CONFIDENTIAL' :
 						$var = _CONFIDENTIAL;
 						break;
 				}
 			}
-			elseif(is_int($var))
-			{
-				switch((int)$var)
-				{
-					case _PRIVATE:
+		elseif (is_int($var)) {
+			switch ((int) $var) {
+				case _PRIVATE :
 						$var = '_PRIVATE';
 						break;
-					case _PUBLIC:
+				case _PUBLIC :
 						$var = '_PUBLIC';
 						break;
-					case _CONFIDENTIAL:
+				case _CONFIDENTIAL :
 						$var = '_CONFIDENTIAL';
 						break;
@@ -1945,93 +1810,77 @@
 		}
 
-		function switch_cu($var)
-		{
-			if(gettype($var) == 'string')
-			{
-				switch($var)
-				{
-					case 'INDIVIDUAL':
+	function switch_cu($var) {
+		if (gettype($var) == 'string') {
+			switch ($var) {
+				case 'INDIVIDUAL' :
 						return INDIVIDUAL;
 						break;
-					case 'GROUP':
+				case 'GROUP' :
 						return GROUP;
 						break;
-					case 'RESOURCE':
+				case 'RESOURCE' :
 						return RESOURCE;
 						break;
-					case 'ROOM':
+				case 'ROOM' :
 						return ROOM;
 						break;
-					case 'UNKNOWN':
+				case 'UNKNOWN' :
 						return UNKNOWN;
 						break;
-					default:
+				default :
 						return OTHER;
 						break;
 				}
 			}
-			elseif(gettype($var) == 'integer')
-			{
-				switch($var)
-				{
-					case INDIVIDUAL:
+		elseif (gettype($var) == 'integer') {
+			switch ($var) {
+				case INDIVIDUAL :
 						return 'INDIVIDUAL';
 						break;
-					case GROUP:
+				case GROUP :
 						return 'GROUP';
 						break;
-					case RESOURCE:
+				case RESOURCE :
 						return 'RESOURCE';
 						break;
-					case ROOM:
+				case ROOM :
 						return 'ROOM';
 						break;
-					case UNKNOWN:
+				case UNKNOWN :
 						return 'UNKNOWN';
 						break;
-					default:
+				default :
 						return 'X-OTHER';
 						break;
 				}
-			}
-			else
-			{
+		} else {
 				return $var;
 			}
 		}
 
-		function switch_date($var)
-		{
-		$this->debug('SWITCH_DATE: gettype = '.gettype($var));
-			if(is_string($var))
-			{
-				$dtime = Array();
-				if(strpos($var,':'))
-				{
-					$pos = explode(':',$var);
+	function switch_date($var) {
+		$this->debug('SWITCH_DATE: gettype = ' . gettype($var));
+		if (is_string($var)) {
+			$dtime = Array ();
+			if (strpos($var, ':')) {
+				$pos = explode(':', $var);
 					$var = $pos[1];
 				}
-				$this->set_var($dtime,'year',(int)(substr($var,0,4)));
-				$this->set_var($dtime,'month',(int)(substr($var,4,2)));
-				$this->set_var($dtime,'mday',(int)(substr($var,6,2)));
-				if(substr($var,8,1) == 'T')
-				{
-					$this->set_var($dtime,'hour',(int)(substr($var,9,2)));
-					$this->set_var($dtime,'min',(int)(substr($var,11,2)));
-					$this->set_var($dtime,'sec',(int)(substr($var,13,2)));
-					if(strlen($var) > 14)
-					{
-						if(substr($var,14,1) != 'Z')
-						{
-							if($this->api)
-							{
+			$this->set_var($dtime, 'year', (int) (substr($var, 0, 4)));
+			$this->set_var($dtime, 'month', (int) (substr($var, 4, 2)));
+			$this->set_var($dtime, 'mday', (int) (substr($var, 6, 2)));
+			if (substr($var, 8, 1) == 'T') {
+				$this->set_var($dtime, 'hour', (int) (substr($var, 9, 2)));
+				$this->set_var($dtime, 'min', (int) (substr($var, 11, 2)));
+				$this->set_var($dtime, 'sec', (int) (substr($var, 13, 2)));
+				if (strlen($var) > 14) {
+					if (substr($var, 14, 1) != 'Z') {
+						if ($this->api) {
 								$dtime['hour'] -= $GLOBALS['phpgw_info']['users']['common']['tz_offset'];
-								if($dtime['hour'] < 0)
-								{
+							if ($dtime['hour'] < 0) {
 									$dtime['mday'] -= 1;
 									$dtime['hour'] = 24 - $dtime['hour'];
 								}
-								elseif($dtime['hour'] >= 24)
-								{
+							elseif ($dtime['hour'] >= 24) {
 									$dtime['mday'] += 1;
 									$dtime['hour'] = $dtime['hour'] - 24;
@@ -2039,7 +1888,5 @@
 							}
 						}
-					}
-					else
-					{
+				} else {
 						/*
 						* The time provided by the iCal is considered local time.
@@ -2062,20 +1909,15 @@
 						//					}
 					}
-				}
-				else
-				{
-					$this->set_var($dtime,'hour',0);
-					$this->set_var($dtime,'min',0);
-					$this->set_var($dtime,'sec',0);
-					if($this->api)
-					{
+			} else {
+				$this->set_var($dtime, 'hour', 0);
+				$this->set_var($dtime, 'min', 0);
+				$this->set_var($dtime, 'sec', 0);
+				if ($this->api) {
 						$dtime['hour'] -= $GLOBALS['phpgw_info']['users']['common']['tz_offset'];
-						if($dtime['hour'] < 0)
-						{
+					if ($dtime['hour'] < 0) {
 							$dtime['mday'] -= 1;
 							$dtime['hour'] = 24 - $dtime['hour'];
 						}
-						elseif($dtime['hour'] >= 24)
-						{
+					elseif ($dtime['hour'] >= 24) {
 							$dtime['mday'] += 1;
 							$dtime['hour'] = $dtime['hour'] - 24;
@@ -2083,479 +1925,401 @@
 					}
 				}
-				$this->debug('DATETIME : '._debug_array($dtime,False));
+			$this->debug('DATETIME : ' . _debug_array($dtime, False));
 				return $dtime;
 			}
-			elseif(is_array($var))
-			{
-				return date('Ymd\THis\Z',mktime($var['hour'],$var['min'],$var['sec'],$var['month'],$var['mday'],$var['year']));
-			}
-			else
-			{
+		elseif (is_array($var)) {
+			return date('Ymd\THis\Z', mktime($var['hour'], $var['min'], $var['sec'], $var['month'], $var['mday'], $var['year']));
+		} else {
 				return $var;
 			}
 		}
 
-		function switch_encoding($var)
-		{
-			if(is_string($var))
-			{
-				switch($var)
-				{
-					case '8BIT':
+	function switch_encoding($var) {
+		if (is_string($var)) {
+			switch ($var) {
+				case '8BIT' :
 						return _8BIT;
 						break;
-					case 'BASE64':
+				case 'BASE64' :
 						return _BASE64;
 						break;
-					default:
+				default :
 						return OTHER;
 						break;
 				}
 			}
-			elseif(is_int($var))
-			{
-				switch($var)
-				{
-					case _8BIT:
+		elseif (is_int($var)) {
+			switch ($var) {
+				case _8BIT :
 						return '8BIT';
 						break;
-					case _BASE64:
+				case _BASE64 :
 						return 'BASE64';
 						break;
-					case OTHER:
+				case OTHER :
 						return 'OTHER';
 						break;
 				}
-			}
-			else
-			{
+		} else {
 				return $var;
 			}
 		}
 
-		function switch_fbtype($var)
-		{
-			if(is_string($var))
-			{
-				switch($var)
-				{
-					case 'FREE':
+	function switch_fbtype($var) {
+		if (is_string($var)) {
+			switch ($var) {
+				case 'FREE' :
 						return FREE;
 						break;
-					case 'BUSY':
+				case 'BUSY' :
 						return BUSY;
 						break;
-					case 'BUSY-UNAVAILABLE':
+				case 'BUSY-UNAVAILABLE' :
 						return BUSY_UNAVAILABLE;
 						break;
-					case 'BUSY-TENTATIVE':
+				case 'BUSY-TENTATIVE' :
 						return BUSY_TENTATIVE;
 						break;
-					default:
+				default :
 						return OTHER;
 						break;
 				}
 			}
-			elseif(is_int($var))
-			{
-				switch($var)
-				{
-					case FREE:
+		elseif (is_int($var)) {
+			switch ($var) {
+				case FREE :
 						return 'FREE';
 						break;
-					case BUSY:
+				case BUSY :
 						return 'BUSY';
 						break;
-					case BUSY_UNAVAILABLE:
+				case BUSY_UNAVAILABLE :
 						return 'BUSY-UNAVAILABLE';
 						break;
-					case BUSY_TENTATIVE:
+				case BUSY_TENTATIVE :
 						return 'BUSY-TENTATIVE';
 						break;
-					default:
+				default :
 						return 'OTHER';
 						break;
 				}
-			}
-			else
-			{
+		} else {
 				return $var;
 			}
 		}
 
-		function switch_freq($var)
-		{
-			if(is_string($var))
-			{
-				switch($var)
-				{
-					case 'SECONDLY':
+	function switch_freq($var) {
+		if (is_string($var)) {
+			switch ($var) {
+				case 'SECONDLY' :
 						return SECONDLY;
 						break;
-					case 'MINUTELY':
+				case 'MINUTELY' :
 						return MINUTELY;
 						break;
-					case 'HOURLY':
+				case 'HOURLY' :
 						return HOURLY;
 						break;
-					case 'DAILY':
+				case 'DAILY' :
 						return DAILY;
 						break;
-					case 'WEEKLY':
+				case 'WEEKLY' :
 						return WEEKLY;
 						break;
-					case 'MONTHLY':
+				case 'MONTHLY' :
 						return MONTHLY;
 						break;
-					case 'YEARLY':
+				case 'YEARLY' :
 						return YEARLY;
 						break;
 				}
 			}
-			elseif(is_int($var))
-			{
-				switch($var)
-				{
-					case SECONDLY:
+		elseif (is_int($var)) {
+			switch ($var) {
+				case SECONDLY :
 						return 'SECONDLY';
 						break;
-					case MINUTELY:
+				case MINUTELY :
 						return 'MINUTELY';
 						break;
-					case HOURLY:
+				case HOURLY :
 						return 'HOURLY';
 						break;
-					case DAILY:
+				case DAILY :
 						return 'DAILY';
 						break;
-					case WEEKLY:
+				case WEEKLY :
 						return 'WEEKLY';
 						break;
-					case MONTHLY:
+				case MONTHLY :
 						return 'MONTHLY';
 						break;
-					case YEARLY:
+				case YEARLY :
 						return 'YEARLY';
 						break;
 				}
-			}
-			else
-			{
+		} else {
 				return $var;
 			}
 		}
 
-		function switch_mailto($var)
-		{
-			if(is_string($var))
-			{
-				$var = str_replace(array("\r\n", "\n", "\r"), "", $var);
-				if(strpos(' '.$var,':'))
-				{
-					$parts = explode(':',$var);
+	function switch_mailto($var) {
+		if (is_string($var)) {
+			$var = str_replace(array (
+				"\r\n",
+				"\n",
+				"\r"
+			), "", $var);
+			if (strpos(' ' . $var, ':')) {
+				$parts = explode(':', $var);
 					$var = $parts[1];
 				}
 
-				$parts = explode('@',$var);
+			$parts = explode('@', $var);
 				//$this->debug("Count of mailto parts : ".count($parts));
-				if(count($parts) == 2)
-				{
+			if (count($parts) == 2) {
 					//$this->debug("Splitting ".$parts[0]." @ ".$parts[1]);
-					$temp_address = Array();
+				$temp_address = Array ();
 					$temp_address['user'] = $parts[0];
 					$temp_address['host'] = $parts[1];
 					return $temp_address;
-				}
-				else
-				{
+			} else {
 					return False;
 				}
 			}
-			elseif(is_array($var))
-			{
-//				return 'MAILTO:'.$var['user'].'@'.$var['host'];
-				return $var['user'].'@'.$var['host'];
-			}
-		}
-
-		function switch_partstat($var)
-		{
-			$this->debug('PARTSTAT = '.$var);
-			if(is_string($var))
-			{
-				switch($var)
-				{
-					case 'NEEDS-ACTION':
+		elseif (is_array($var)) {
+			//				return 'MAILTO:'.$var['user'].'@'.$var['host'];
+			return $var['user'] . '@' . $var['host'];
+			}
+		}
+
+	function switch_partstat($var) {
+		$this->debug('PARTSTAT = ' . $var);
+		if (is_string($var)) {
+			switch ($var) {
+				case 'NEEDS-ACTION' :
 						return 0; // NEEDS_ACTION;
 						break;
-					case 'ACCEPTED':
+				case 'ACCEPTED' :
 						return 1; // ACCEPTED;
 						break;
-					case 'DECLINED':
+				case 'DECLINED' :
 						return 2; // DECLINED;
 						break;
-					case 'TENTATIVE':
+				case 'TENTATIVE' :
 						return 3; // TENTATIVE;
 						break;
-					case 'DELEGATED':
+				case 'DELEGATED' :
 						return 4; // DELEGATED;
 						break;
-					case 'COMPLETED':
+				case 'COMPLETED' :
 						return 5; // COMPLETED;
 						break;
-					case 'IN-PROCESS':
+				case 'IN-PROCESS' :
 						return 6; // IN_PROCESS;
 						break;
-					default:
+				default :
 						return 99; // OTHER;
 						break;
 				}
 			}
-			elseif(is_int($var))
-			{
-				switch((int)$var)
-				{
-					case 0: // NEEDS_ACTION:
+		elseif (is_int($var)) {
+			switch ((int) $var) {
+				case 0 : // NEEDS_ACTION:
 						return 'NEEDS-ACTION';
 						break;
-					case 1: //  ACCEPTED:
+				case 1 : //  ACCEPTED:
 						return 'ACCEPTED';
 						break;
-					case 2: // DECLINED:
+				case 2 : // DECLINED:
 						return 'DECLINED';
 						break;
-					case 3: // TENTATIVE:
+				case 3 : // TENTATIVE:
 						return 'TENTATIVE';
 						break;
-					case 4: // DELEGATED:
+				case 4 : // DELEGATED:
 						return 'DELEGATED';
 						break;
-					case 5: // COMPLETED:
+				case 5 : // COMPLETED:
 						return 'COMPLETED';
 						break;
-					case 6: // IN_PROCESS:
+				case 6 : // IN_PROCESS:
 						return 'IN-PROCESS';
 						break;
-					default:
+				default :
 						return 'X-OTHER';
 						break;
 				}
-			}
-			else
-			{
+		} else {
 				return $var;
 			}
 		}
 
-		function switch_range($var)
-		{
-			if(is_string($var))
-			{
-				switch($var)
-				{
-					case 'THISANDPRIOR':
+	function switch_range($var) {
+		if (is_string($var)) {
+			switch ($var) {
+				case 'THISANDPRIOR' :
 						return THISANDPRIOR;
 						break;
-					case 'THISANDFUTURE':
+				case 'THISANDFUTURE' :
 						return THISANDFUTURE;
 						break;
 				}
 			}
-			elseif(is_int($var))
-			{
-				switch($var)
-				{
-					case THISANDPRIOR:
+		elseif (is_int($var)) {
+			switch ($var) {
+				case THISANDPRIOR :
 						return 'THISANDPRIOR';
 						break;
-					case THISANDFUTURE:
+				case THISANDFUTURE :
 						return 'THISANDFUTURE';
 						break;
 				}
-			}
-			else
-			{
+		} else {
 				return $var;
 			}
 		}
 
-		function switch_related($var)
-		{
-			if(is_string($var))
-			{
-				switch($var)
-				{
-					case 'START':
+	function switch_related($var) {
+		if (is_string($var)) {
+			switch ($var) {
+				case 'START' :
 						return START;
 						break;
-					case 'END':
+				case 'END' :
 						return END;
 						break;
 				}
 			}
-			elseif(is_int($var))
-			{
-				switch($var)
-				{
-					case START:
+		elseif (is_int($var)) {
+			switch ($var) {
+				case START :
 						return 'START';
 						break;
-					case END:
+				case END :
 						return 'END';
 						break;
 				}
-			}
-			else
-			{
+		} else {
 				return $var;
 			}
 		}
 
-		function switch_reltype($var)
-		{
-			if(is_string($var))
-			{
-				switch($var)
-				{
-					case 'PARENT':
+	function switch_reltype($var) {
+		if (is_string($var)) {
+			switch ($var) {
+				case 'PARENT' :
 						return PARENT;
 						break;
-					case 'CHILD':
+				case 'CHILD' :
 						return CHILD;
 						break;
-					case 'SIBLING':
+				case 'SIBLING' :
 						return SIBLING;
 						break;
 				}
 			}
-			elseif(is_int($var))
-			{
-				switch($var)
-				{
-					case PARENT:
+		elseif (is_int($var)) {
+			switch ($var) {
+				case PARENT :
 						return 'PARENT';
 						break;
-					case CHILD:
+				case CHILD :
 						return 'CHILD';
 						break;
-					case SIBLING:
+				case SIBLING :
 						return 'SIBLING';
 						break;
 				}
-			}
-			else
-			{
+		} else {
+			return $var;
+			}
+		}
+
+	function switch_role($var) {
+		if (is_string($var)) {
+			switch ($var) {
+				case 'NONE' :
+						return NONE;
+						break;
+				case 'CHAIR' :
+						return CHAIR;
+						break;
+				case 'REQ-PARTICIPANT' :
+						return REQ_PARTICIPANT;
+						break;
+				case 'OPT-PARTICIPANT' :
+						return OPT_PARTICIPANT;
+						break;
+				case 'NON-PARTICIPANT' :
+						return NON_PARTICIPANT;
+						break;
+				}
+			}
+		elseif (is_int($var)) {
+			switch ($var) {
+				case NONE :
+						return 'NONE';
+						break;
+				case CHAIR :
+						return 'CHAIR';
+						break;
+				case REQ_PARTICIPANT :
+						return 'REQ-PARTICIPANT';
+						break;
+				case OPT_PARTICIPANT :
+						return 'OPT-PARTICIPANT';
+						break;
+				case NON_PARTICIPANT :
+						return 'NON-PARTICIPANT';
+						break;
+				}
+		} else {
 				return $var;
 			}
 		}
 
-		function switch_role($var)
-		{
-			if(is_string($var))
-			{
-				switch($var)
-				{
-					case 'NONE':
-						return NONE;
-						break;
-					case 'CHAIR':
-						return CHAIR;
-						break;
-					case 'REQ-PARTICIPANT':
-						return REQ_PARTICIPANT;
-						break;
-					case 'OPT-PARTICIPANT':
-						return OPT_PARTICIPANT;
-						break;
-					case 'NON-PARTICIPANT':
-						return NON_PARTICIPANT;
-						break;
-				}
-			}
-			elseif(is_int($var))
-			{
-				switch($var)
-				{
-					case NONE:
-						return 'NONE';
-						break;
-					case CHAIR:
-						return 'CHAIR';
-						break;
-					case REQ_PARTICIPANT:
-						return 'REQ-PARTICIPANT';
-						break;
-					case OPT_PARTICIPANT:
-						return 'OPT-PARTICIPANT';
-						break;
-					case NON_PARTICIPANT:
-						return 'NON-PARTICIPANT';
-						break;
-				}
-			}
-			else
-			{
+	function switch_rsvp($var) {
+		if (is_string($var)) {
+			if ($var == 'TRUE') {
+					return 1;
+				}
+			elseif ($var == 'FALSE') {
+					return 0;
+				}
+			}
+		elseif (is_int($var) || $var == False) {
+			if ($var == 1) {
+					return 'TRUE';
+				}
+			elseif ($var == 0) {
+					return 'FALSE';
+				}
+		} else {
 				return $var;
 			}
 		}
 
-		function switch_rsvp($var)
-		{
-			if(is_string($var))
-			{
-				if($var == 'TRUE')
-				{
-					return 1;
-				}
-				elseif($var == 'FALSE')
-				{
-					return 0;
-				}
-			}
-			elseif(is_int($var) || $var == False)
-			{
-				if($var == 1)
-				{
-					return 'TRUE';
-				}
-				elseif($var == 0)
-				{
-					return 'FALSE';
-				}
-			}
-			else
-			{
-				return $var;
-			}
-		}
-
-		function switch_transp($var)
-		{
-			if(is_string($var))
-			{
-				switch($var)
-				{
-					case 'TRANSPARENT':
+	function switch_transp($var) {
+		if (is_string($var)) {
+			switch ($var) {
+				case 'TRANSPARENT' :
 						return TRANSPARENT;
 						break;
-					case 'OPAQUE':
+				case 'OPAQUE' :
 						return OPAQUE;
 						break;
 				}
 			}
-			elseif(is_int($var))
-			{
-				switch($var)
-				{
-					case TRANSPARENT:
+		elseif (is_int($var)) {
+			switch ($var) {
+				case TRANSPARENT :
 						return 'TRANSPARENT';
 						break;
-					case OPAQUE:
+				case OPAQUE :
 						return 'OPAQUE';
 						break;
 				}
-			}
-			else
-			{
+		} else {
 				return $var;
 			}
@@ -2566,6 +2330,5 @@
 		 */
 
-		function parse($ical_text)
-		{
+	function parse($ical_text) {
 			$begin_regexp = '^';
 			$semi_colon_regexp = '[\;\:]';
@@ -2573,70 +2336,57 @@
 			$catch_all_regexp = '(.*)';
 			$end_regexp = '$';
-			$property_regexp = $begin_regexp.'([A-Z\-]*)'.$semi_colon_regexp.$catch_all_regexp.$end_regexp;
-			$param_regexp = $begin_regexp.$catch_all_regexp.':'.$catch_all_regexp.$end_regexp;
+		$property_regexp = $begin_regexp . '([A-Z\-]*)' . $semi_colon_regexp . $catch_all_regexp . $end_regexp;
+		$param_regexp = $begin_regexp . $catch_all_regexp . ':' . $catch_all_regexp . $end_regexp;
 
 			$mode = 'none';
 			$text = $this->read_line_unfold($ical_text);
-			while($text)
-			{
-//				if(strlen($ical_text[$i]) > 75)
-//				{
-//					continue;
-//				}
-
-				ereg($property_regexp,$text,$temp);
+		while ($text) {
+			//				if(strlen($ical_text[$i]) > 75)
+			//				{
+			//					continue;
+			//				}
+
+			ereg($property_regexp, $text, $temp);
 				//$this->debug ('Majortype dump: '._debug_array($temp, false) );
-				$majortype = str_replace('-','_',strtolower($temp[1]));
+			$majortype = str_replace('-', '_', strtolower($temp[1]));
 				$value = chop($temp[2]);
-
-				if($mode != 'none' && ($majortype != 'begin' && $majortype != 'end'))
-				{
+			if ($mode != 'none' && ($majortype != 'begin' && $majortype != 'end')) {
 					//$this->debug('PARSE:MAJORTYPE : '.$majortype);
-					if(isset($this->property[$majortype]))
-					{
-						$state = @$this->property[$majortype]["$mode"]['state'];
-						$type = @$this->property[$majortype]['type'];
-						$multiples = @$this->property[$majortype]["$mode"]['multiples'];
-						$do_to_text = @$this->property[$majortype]['to_text'];
-					}
-					elseif(substr($majortype,0,2) == 'x_')
-					{
+				if (isset ($this->property[$majortype])) {
+					$state = @ $this->property[$majortype]["$mode"]['state'];
+					$type = @ $this->property[$majortype]['type'];
+					$multiples = @ $this->property[$majortype]["$mode"]['multiples'];
+					$do_to_text = @ $this->property[$majortype]['to_text'];
+					}
+				elseif (substr($majortype, 0, 2) == 'x_') {
 						$state = 'optional';
 						$type = 'xtype';
 						$multiples = True;
 						$do_to_test = True;
-					}
-					else
-					{
+				} else {
 						$state = '';
 					}
-				}
-				else
-				{
+			} else {
 					$state = 'required';
 				}
 
-				if($majortype == 'duration')
-				{
+			if ($majortype == 'duration') {
 					// Unset dur var
-					unset($dur);
+				unset ($dur);
 
 					// Split DURATION
-					list($_f_['day_raw'], $_f_['time_raw']) = split('T', substr($value, 1, strlen($value)-1));
+				list ($_f_['day_raw'], $_f_['time_raw']) = split('T', substr($value, 1, strlen($value) - 1));
 
 					/* Datecode */
-					if(isset($_f_['day_raw']) OR $_f_['day_raw'])
-					{
+				if (isset ($_f_['day_raw']) OR $_f_['day_raw']) {
 						// Days
-//						if(ereg('D', $_f_['day_raw']))
-						if(strstr($_f_['day_raw'],'D'))
-						{
+					//						if(ereg('D', $_f_['day_raw']))
+					if (strstr($_f_['day_raw'], 'D')) {
 							$dur['days'] = eregi_replace("([0-9]+)D(.*)", "\\1", $_f_['day_raw']);
 						}
 
 						// Weeks
-//						if(ereg("W", $_f_["day_raw"]))
-						if(strstr($_f_['day_raw'],'W'))
-						{
+					//						if(ereg("W", $_f_["day_raw"]))
+					if (strstr($_f_['day_raw'], 'W')) {
 							$dur['weeks'] = eregi_replace("([^|.*]+D)?([0-9]+)W", "\\2", $_f_['day_raw']);
 						}
@@ -2644,10 +2394,8 @@
 
 					/* Timecode */
-					if(isset($_f_['time_raw']) OR $_f_['time_raw'])
-					{
+				if (isset ($_f_['time_raw']) OR $_f_['time_raw']) {
 						// Hours
-//						if(ereg("H", $_f_["time_raw"]))
-						if(strstr($_f_['time_raw'],'H'))
-						{
+					//						if(ereg("H", $_f_["time_raw"]))
+					if (strstr($_f_['time_raw'], 'H')) {
 							$dur['hours'] = eregi_replace("([0-9]+)H(.*)", "\\1", $_f_['time_raw']);
 						}
@@ -2655,7 +2403,6 @@
 						// Minutes
 						/* If you find better, contact me very quickly :) */
-//						if(ereg("M", $_f_["time_raw"]))
-						if(strstr($_f_['time_raw'],'M'))
-						{
+					//						if(ereg("M", $_f_["time_raw"]))
+					if (strstr($_f_['time_raw'], 'M')) {
 							$dur['minutes'] = eregi_replace("([^|.*]+H)?([0-9]+)M(.*)", "\\2", $_f_['time_raw']);
 						}
@@ -2663,12 +2410,11 @@
 						// Seconds
 						/* Same comment :) */
-//						if(ereg("S", $_f_["time_raw"]) )
-						if(strstr($_f_['time_raw'],'S'))
-						{
+					//						if(ereg("S", $_f_["time_raw"]) )
+					if (strstr($_f_['time_raw'], 'S')) {
 							$dur['seconds'] = eregi_replace("([^|.*]+M)?([0-9]+)S(.*)", "\\2", $_f_['time_raw']);
 						}
 					}
 
-					$dur['raw'] = Array(
+				$dur['raw'] = Array (
 						'timecode' => $_f_['time_raw'],
 						'datecode' => $_f_['day_raw'],
@@ -2679,97 +2425,87 @@
 				}
 
-				if($majortype == 'begin')
-				{
+			if ($majortype == 'begin') {
 					$tmode = $mode;
 					$mode = strtolower($value);
-					switch(strtolower($value))
-					{
-						case 'daylight':
-						case 'standard':
-							$t_event = Array();
+				switch (strtolower($value)) {
+					case 'daylight' :
+					case 'standard' :
+						$t_event = Array ();
 							$t_event = $event;
-							$event = Array();
+						$event = Array ();
 							break;
-						case 'valarm':
-							if($tmode == 'vevent' || $tmode == 'vtodo')
-							{
+					case 'valarm' :
+						if ($tmode == 'vevent' || $tmode == 'vtodo') {
 								$t_event = $event;
-								unset($event);
-								$event = Array();
-							}
-							else
-							{
+							unset ($event);
+							$event = Array ();
+						} else {
 								$mode = $tmode;
 							}
 							break;
-						case 'vcalendar':
+					case 'vcalendar' :
 							$ical = $this->new_ical();
 							break;
-						case 'vevent':
-						case 'vfreebusy':
-						case 'vjournal':
-						case 'vtimezone':
-						case 'vtodo':
-							$event = Array();
+					case 'vevent' :
+					case 'vfreebusy' :
+					case 'vjournal' :
+					case 'vtimezone' :
+					case 'vtodo' :
+						$event = Array ();
 							break;
 					}
 					$event['type'] = strtolower($value);
 				}
-				elseif($majortype == 'end')
-				{
+			elseif ($majortype == 'end') {
 					$mode = 'none';
-					switch(strtolower($value))
-					{
-						case 'daylight':
-						case 'standard':
+				switch (strtolower($value)) {
+					case 'daylight' :
+					case 'standard' :
 							$tzdata[] = $event;
-							unset($event);
+						unset ($event);
 							$event = $t_event;
-							unset($t_event);
+						unset ($t_event);
 							$mode = 'vtimezone';
 							break;
-						case 'valarm':
+					case 'valarm' :
 							$alarm[] = $event;
-							unset($event);
+						unset ($event);
 							$event = $t_event;
-							unset($t_event);
+						unset ($t_event);
 							$mode = $tmode;
 							break;
-						case 'vevent':
-							if(!empty($alarm))
-							{
+					case 'vevent' :
+						if (!empty ($alarm)) {
 								$event['alarm'] = $alarm;
-								unset($alarm);
+							unset ($alarm);
 							}
 							$this->event[] = $event;
-							unset($event);
+						unset ($event);
 							break;
-						case 'vfreebusy':
+					case 'vfreebusy' :
 							$this->freebusy[] = $event;
-							unset($event);
+						unset ($event);
 							break;
-						case 'vjournal':
+					case 'vjournal' :
 							$this->journal[] = $event;
-							unset($event);
+						unset ($event);
 							break;
-						case 'vtimezone':
-							if(!empty($tzdata))
-							{
+					case 'vtimezone' :
+						if (!empty ($tzdata)) {
 								$event['tzdata'] = $tzdata;
-								unset($tzdata);
+							unset ($tzdata);
 							}
 							$this->timezone[] = $event;
-							unset($event);
+						unset ($event);
 							break;
-						case 'vtodo':
-							if(!empty($alarm))
-							{
+					case 'vtodo' :
+						if (!empty ($alarm)) {
 								$event['alarm'] = $alarm;
-								unset($alarm);
+							unset ($alarm);
 							}
 							$this->todo[] = $event['alarm'];
-							unset($event);
+						unset ($event);
 							break;
-						case 'vcalendar':
+					case 'vcalendar' :
 							$this->ical = $ical;
 							$this->ical['event'] = $this->event;
@@ -2781,65 +2517,54 @@
 					}
 				}
-				elseif($majortype == 'prodid' || $majortype == 'version' || $majortype == 'method' || $majortype == 'calscale')
-				{
-					$this->parse_parameters($ical,$majortype,$this->from_text($value));
-				}
-				elseif($state == 'optional' || $state == 'required')
-				{
+			elseif ($majortype == 'prodid' || $majortype == 'version' || $majortype == 'method' || $majortype == 'calscale') {
+				$this->parse_parameters($ical, $majortype, $this->from_text($value));
+				}
+			elseif ($state == 'optional' || $state == 'required') {
 					//$this->debug('Mode : '.$mode.' Majortype : '.$majortype . ' Type : '.$type);
-					if($do_to_text)
-					{
+				if ($do_to_text) {
 						$value = $this->from_text($value);
 					}
-					switch($type)
-					{
-						case 'text':
-							$this->parse_parameters($event,$majortype,$value);
-							break;
-						case 'recur':
-						case 'date-time':
-						case 'cal-address':
-							$this->parse_value($event,$majortype,$value,$mode);
-							break;
-						case 'integer':
-							if($multiples)
-							{
-								$event[$majortype][] = (int)$value;
-							}
-							else
-							{
-								$this->set_var($event,$majortype,(int)$value);
-							}
-							break;
-						case 'float':
-							$event->$majortype = new class_geo;
-							$this->parse_geo($event->$majortype,$value);
-							break;
-						case 'utc-offset':
-							$this->set_var($event,$majortype,(int)$value);
-							break;
-						case 'uri':
-							$new_var = Array();
-							$this->parse_parameters($new_var,$majortype,$value);
-							if($multiples)
-							{
-								switch($mode)
-								{
-									case 'valarm':
+				switch ($type) {
+					case 'text' :
+						$this->parse_parameters($event, $majortype, $value);
+						break;
+					case 'recur' :
+					case 'date-time' :
+					case 'cal-address' :
+						$this->parse_value($event, $majortype, $value, $mode);
+						break;
+					case 'integer' :
+						if ($multiples) {
+							$event[$majortype][] = (int) $value;
+						} else {
+							$this->set_var($event, $majortype, (int) $value);
+						}
+						break;
+					case 'float' :
+						$event-> $majortype = new class_geo;
+						$this->parse_geo($event-> $majortype, $value);
+						break;
+					case 'utc-offset' :
+						$this->set_var($event, $majortype, (int) $value);
+						break;
+					case 'uri' :
+						$new_var = Array ();
+						$this->parse_parameters($new_var, $majortype, $value);
+						if ($multiples) {
+							switch ($mode) {
+								case 'valarm' :
 										$alarm['attach'][] = $new_var;
 										break;
-									default:
+								default :
 										$event[$majortype][] = $new_var;
 										break;
 								}
-							}
-							else
-							{
+						} else {
 								$event[$majortype] = $new_var;
 							}
-							unset($new_var);
+						unset ($new_var);
 							break;
-						case 'xtype':
-							$this->parse_xtype($event,$majortype,$value);
+					case 'xtype' :
+						$this->parse_xtype($event, $majortype, $value);
 							break;
 					}
@@ -2850,22 +2575,19 @@
 		}
 
-
-		function switch_to_phpgw_status($partstat)
-		{
-			switch($partstat)
-			{
-				case 0:
+	function switch_to_phpgw_status($partstat) {
+		switch ($partstat) {
+			case 0 :
 					return 'U';
 					break;
-				case 1:
+			case 1 :
 					return 'A';
 					break;
-				case 2:
+			case 2 :
 					return 'R';
 					break;
-				case 3:
+			case 3 :
 					return 'T';
 					break;
-				default:
+			default :
 					return 'U';
 					break;
@@ -2873,18 +2595,16 @@
 		}
 
-		function switch_phpgw_status($status)
-		{
-			switch($status)
-			{
-				case 'U':
+	function switch_phpgw_status($status) {
+		switch ($status) {
+			case 'U' :
 					return 0;
 					break;
-				case 'A':
+			case 'A' :
 					return 1;
 					break;
-				case 'R':
+			case 'R' :
 					return 2;
 					break;
-				case 'T':
+			case 'T' :
 					return 3;
 					break;
@@ -2892,116 +2612,122 @@
 		}
 
-		function is_owner($part_record)
-		{
-			if(($part_record['user'].'@'.$part_record['host'] == $GLOBALS['phpgw_info']['user']['preferences']['email']['address']) ||
-				($part_record['cn'] == $GLOBALS['phpgw_info']['user']['account_lid']))
-			{
+	function is_owner($part_record) {
+		if (($part_record['user'] . '@' . $part_record['host'] == $GLOBALS['phpgw_info']['user']['preferences']['email']['address']) || ($part_record['cn'] == $GLOBALS['phpgw_info']['user']['account_lid']) ||
+			($part_record['mailto']['user'] == $GLOBALS['phpgw_info']['user']['account_lid'])) {
 				return True;
-			}
-			else
-			{
+		} else {
 				return False;
 			}
 		}
 
-		function check_owner(&$event,$ical,$so_event)
-		{
-			if(!isset($event['participant'][$GLOBALS['phpgw_info']['user']['account_id']]))
-			{
-				if(isset($ical['organizer']))
-				{
-					if($this->is_owner($ical['organizer']))
-					{
-						$so_event->add_attribute('owner',$GLOBALS['phpgw_info']['user']['account_id']);
-						$so_event->add_attribute('participants',$this->switch_to_phpgw_status($ical['organizer']['partstat']),$GLOBALS['phpgw_info']['user']['account_id']);
-					}
-				}
-				elseif(isset($ical['attendee']))
-				{
+	function check_owner(& $event, $ical, $so_event) {
+		if (!isset ($event['participant'][$GLOBALS['phpgw_info']['user']['account_id']])) {
+			if (isset ($ical['organizer'])) {
+				if ($this->is_owner($ical['organizer'])) {
+					$so_event->add_attribute('owner', $GLOBALS['phpgw_info']['user']['account_id']);
+					$so_event->add_attribute('participants', $this->switch_to_phpgw_status($ical['organizer']['partstat']), $GLOBALS['phpgw_info']['user']['account_id']);
+					}
+				}
+			elseif (isset ($ical['attendee'])) {
 					$attendee_count = count($ical['attendee']);
 
-					for($j=0;$j<$attendee_count;$j++)
-					{
-						if($this->is_owner($ical['attendee'][$j]))
-						{
-							$so_event->add_attribute('participants',$this->switch_to_phpgw_status($ical['attendee'][$j]['partstat']),(int)$GLOBALS['phpgw_info']['user']['account_id']);
-						}
-					}
-				}
-				else
-				{
-					$so_event->add_attribute('owner',$GLOBALS['phpgw_info']['user']['account_id']);
-					$so_event->add_attribute('participants','A',$GLOBALS['phpgw_info']['user']['account_id']);
-				}
-			}
-		}
-
-		function import_file()
-		{
-			if($_FILES['uploadedfile']['tmp_name'] == 'none' || $_FILES['uploadedfile']['tmp_name'] == '')
-			{
-				Header('Location: ' . $GLOBALS['phpgw']->link('/index.php',
-						Array(
+				for ($j = 0; $j < $attendee_count; $j++) {
+					if ($this->is_owner($ical['attendee'][$j])) {
+						$so_event->add_attribute('participants', $this->switch_to_phpgw_status($ical['attendee'][$j]['partstat']), (int) $GLOBALS['phpgw_info']['user']['account_id']);
+						}
+					}
+			} else {
+				$so_event->add_attribute('owner', $GLOBALS['phpgw_info']['user']['account_id']);
+				$so_event->add_attribute('participants', 'A', $GLOBALS['phpgw_info']['user']['account_id']);
+				}
+			}
+		}
+
+	function import_file() {
+		if ($_FILES['uploadedfile']['tmp_name'] == 'none' || $_FILES['uploadedfile']['tmp_name'] == '') {
+			Header('Location: ' . $GLOBALS['phpgw']->link('/index.php', Array (
 							'menuaction'	=> 'calendar.uiicalendar.import',
 							'action'	=> 'GetFile'
-						)
-					)
-				);
+			)));
 				$GLOBALS['phpwg']->common->phpgw_exit();
 			}
 			$uploaddir = $GLOBALS['phpgw_info']['server']['temp_dir'] . SEP;
 
-			srand((double)microtime()*1000000);
-			$random_number = rand(100000000,999999999);
-			$newfilename = md5($_FILES['uploadedfile']['tmp_name'].", ".$uploadedfile_name.", "
-				. time() . getenv("REMOTE_ADDR") . $random_number );
+		srand((double) microtime() * 1000000);
+		$random_number = rand(100000000, 999999999);
+		$newfilename = md5($_FILES['uploadedfile']['tmp_name'] . ", " . $uploadedfile_name . ", " . time() . getenv("REMOTE_ADDR") . $random_number);
 
 			$filename = $uploaddir . $newfilename;
 
 			move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $filename);
-//			$ftp = fopen($uploaddir . $newfilename . '.info','wb');
-//			fputs($ftp,$uploadedfile_type."\n".$uploadedfile_name."\n");
-//			fclose($ftp);
+		//			$ftp = fopen($uploaddir . $newfilename . '.info','wb');
+		//			fputs($ftp,$uploadedfile_type."\n".$uploadedfile_name."\n");
+		//			fclose($ftp);
 			return $filename;
 		}
 
-		function import($mime_msg='', $from_ajax = false)
-		{
-			if($_FILES['uploadedfile']['tmp_name'] != 'none' && $_FILES['uploadedfile']['tmp_name'] != '')
-			{
+	function safeBitCheck($number, $comparison) {
+		$binNumber = base_convert($number, 10, 2);
+		$binComparison = strrev(base_convert($comparison, 10, 2));
+		$str = strlen($binNumber);
+
+		if (($str <= strlen($binComparison)) && ($binComparison {
+			$str -1 }
+		=== "1"))
+		return '1';
+else
+	return '0';
+}
+
+function import($mime_msg = '', $from_ajax = false, $importAccount = false) {
+	/*
+	 * Caso seja uma importação para conta compartilhada carrega as acls do usuario
+	 */
+	if ($importAccount != false) {
+		$colunas = array (
+			'acl_appname',
+			'acl_location',
+			'acl_account',
+			'acl_rights'
+		);
+		$where = array (
+			'acl_appname' => 'calendar',
+			'acl_account' => $importAccount['uidnumber'],
+			'acl_location' => $GLOBALS['phpgw_info']['user']['account_id']
+		);
+		$db = $GLOBALS['phpgw']->db;
+		$db->select('phpgw_acl', $colunas, $where, null, null);
+		$row = $db->row(true);
+
+		if (!$this->safeBitCheck(2, $row['acl_rights'])) //Se o usuario não tem permisão de adicionar eventos
+			return 'You do not have permission to add events';
+	}
+
+	if ($_FILES['uploadedfile']['tmp_name'] != 'none' && $_FILES['uploadedfile']['tmp_name'] != '') {
 				$filename = $this->import_file();
-				$fp=fopen($filename,'rt');
-				$mime_msg = explode("\n",fread($fp, filesize($filename)));
+		$fp = fopen($filename, 'rt');
+		$mime_msg = explode("\n", fread($fp, filesize($filename)));
 				fclose($fp);
 				unlink($filename);
 			}
-			elseif(!$mime_msg)
-			{
-				Header('Location: ' . $GLOBALS['phpgw']->link('/index.php',
-						Array(
+	elseif (!$mime_msg) {
+		Header('Location: ' . $GLOBALS['phpgw']->link('/index.php', Array (
 							'menuaction'	=> 'calendar.uiicalendar.import',
 							'action'	=> 'GetFile'
-						)
-					)
-				);
+		)));
 				$GLOBALS['phpwg']->common->phpgw_exit();
 			}
 
-			if(!is_object($GLOBALS['uicalendar']))
-			{
-				$so_event = createobject('calendar.socalendar',
-					Array(
+	if (!is_object($GLOBALS['uicalendar'])) {
+		$so_event = createobject('calendar.socalendar', Array (
 						'owner'	=> 0,
 						'filter'	=> '',
 						'category'	=> ''
-					)
-				);
-			}
-			else
-			{
+		));
+	} else {
 				$so_event = $GLOBALS['uicalendar']->bo->so;
 			}
 
-			$datetime_vars = Array(
+	$datetime_vars = Array (
 				'start'	=> 'dtstart',
 				'end'	=> 'dtend',
@@ -3010,5 +2736,5 @@
 			);
 
-			$date_array = Array(
+	$date_array = Array (
 				'Y'	=> 'year',
 				'm'	=> 'month',
@@ -3020,161 +2746,148 @@
 
 			// time limit should be controlled elsewhere
-			@set_time_limit(0);
-
+	@ set_time_limit(0);
 			$GLOBALS['phpgw_info']['user']['preferences'] = $GLOBALS['phpgw']->preferences->create_email_preferences();
 			$users_email = $GLOBALS['phpgw_info']['user']['preferences']['email']['address'];
 			$cats = CreateObject('phpgwapi.categories');
 			$ical = $this->parse($mime_msg);
-			switch($ical['version']['value'])
-			{
-				case '1.0':
+	switch ($ical['version']['value']) {
+		case '1.0' :
 					$cat_sep = ';';
 					break;
-				case '2.0':
-				default:
+		case '2.0' :
+		default :
 					$cat_sep = ',';
 					break;			
 			}
 					
-			$c_events = count($ical['event']);
-			for($i=0; $i<$c_events; $i++)
-			{
-				if($ical['event'][$i]['uid']['value'])
+	/*
+	 * Caso seja um Reply.
+	 */
+	if (strtoupper($ical['method']['value']) == 'REPLY') {
+		//atualiza evento caso seja evento externo
+		if (isset ($ical['event']['0']['x_type']))
+			foreach ($ical['event']['0']['x_type'] as $property)
+				if ($property['name'] === 'MICROSOFT_CDO_IMPORTANCE')
+					return $this->updateHour($ical);
+
+		//Ignora respostas externas
+		return 'The import was executed successfully.';
+				}
+
+	/*-------------------------------------------------------------*/
+
+	/*
+	 * Ativa a flag de cancelamento caso o ical for do method CANCEL
+	 */
+	$cancelEvent = false;
+	if (strtoupper($ical['method']['value']) == 'CANCEL')
+		$cancelEvent = true;
+	/*-------------------------------------------------------------*/
+
+	require_once ($_SESSION['rootPath'] . '/calendar/inc/class.ex_participants.inc.php');
+
+	$c_events = count($ical['event']);
+	for ($i = 0; $i < $c_events; $i++) {
+		$ex_participants = new exParticipants();
+
+		if ($ical['event'][$i]['uid']['value'])
+			$uid_exists = $so_event->find_cal_id($ical['event'][$i]['uid']['value']);
+				else
+					$uid_exists = False;
+
+		if ($cancelEvent) // If cancelamento
 				{
-					$uid_exists = $so_event->find_uid($ical['event'][$i]['uid']['value']);
-				}
-				else
-				{
-					$uid_exists = False;
-				}
-				if($uid_exists)
-				{
-					// $event = $so_event->read_entry($uid_exists);
-					// $this->check_owner($event,$ical['event'][$i],$so_event);
-					// $event = $so_event->get_cached_event();
-					// $so_event->add_entry($event);
-					Header('Location: ' . $GLOBALS['phpgw']->link('/index.php',
-							Array(
-								'menuaction'	=> 'calendar.uiicalendar.import',
-								'error_number'	=> 1
-							)
-						)
-					);
-					$GLOBALS['phpwg']->common->phpgw_exit();
-
-				}
-				else
-				{
+			if ($importAccount != false && !$this->safeBitCheck(8, $row['acl_rights'])) // se for em uma conta compartilhada e se tem permisão de deletar
+				return 'You do not have permission to delete events';
+
+			if ($uid_exists) // If o evento existe na agenda
+				$so_event->delete_entry($uid_exists); // Adicona o id a lista de eventos a deletar
+
+			continue; // Continua o for nenhum processamento mais é nescessario
+				}
+
+		if ($uid_exists) {
+			$event = $so_event->read_entry($uid_exists);
+			$this->check_owner($event, $ical['event'][$i], $so_event);
+		} else {
 					$so_event->event_init();
-					$so_event->add_attribute('id',0);
-					$so_event->add_attribute('reference',0);
-					if($ical['event'][$i]['uid']['value'])
-					{
-						$so_event->add_attribute('uid',$ical['event'][$i]['uid']['value']);
-					}
-					if($ical['event'][$i]['summary']['value'])
-					{
+			$so_event->add_attribute('id', 0);
+			$so_event->add_attribute('reference', 0);
+					}
+
+		if ($ical['event'][$i]['uid']['value']) {
+			$so_event->add_attribute('uid', $ical['event'][$i]['uid']['value']);
+		}
+		if ($ical['event'][$i]['summary']['value']) {
 						$so_event->set_title($ical['event'][$i]['summary']['value']);
 					}
-					if($ical['event'][$i]['description']['value'])
-					{
+		if ($ical['event'][$i]['description']['value']) {
 						$so_event->set_description($ical['event'][$i]['description']['value']);
 					}
-					if($ical['event'][$i]['ex_participants']['value'])
-					{
-						$so_event->set_ex_participants($ical['event'][$i]['ex_participants']['value']);
+		if ($ical['event'][$i]['ex_participants']['value']) {
+			$ex_participants->setParticipantsByString($ical['event'][$i]['ex_participants']['value']);
 					}
 					// Compatibilidade com agendamentos vindos do outlook/exchange
-					if ( isset ($ical['event'][$i]['attendee']) )
-					{
+		if (isset ($ical['event'][$i]['attendee'])) {
 						$c_attendees = count($ical['event'][$i]['attendee']);
 						$all_attendees = '';
-						for ( $a=0; $a < $c_attendees; $a++ )
-						{
-							$cname = '"'. $ical['event'][$i]['attendee'][$a]['cn'] .'"';
+			for ($a = 0; $a < $c_attendees; $a++) {
+				$cname = '"' . $ical['event'][$i]['attendee'][$a]['cn'] . '"';
 							$email = $ical['event'][$i]['attendee'][$a]['mailto']['user'];
-							if ( $email )
-							{
+				if ($email) {
 								// Remove os espaÃ§os, tabs e quebra-de-linha no dominio
 								//$email_domain = preg_replace('/\s*/m', '', $ical['event'][$i]['attendee'][$a]['mailto']['host']);
 								$email_domain = $ical['event'][$i]['attendee'][$a]['mailto']['host'];
-								$email = '<'. $email .'@'. $email_domain .'>';
-							}
-							else
+					$email = '<' . $email . '@' . $email_domain . '>';
+				} else
 								$email = '';
 							
-							$all_attendees .= $cname . $email .', ';
-						}
-						$this->debug ('All attendees: ' . $all_attendees);
-						$so_event->set_ex_participants($all_attendees);
-					}
-
-					if($ical['event'][$i]['location']['value'])
-					{
-						$so_event->add_attribute('location',$ical['event'][$i]['location']['value']);
-					}
-					if(isset($ical['event'][$i]['priority']))
-					{
-						$so_event->add_attribute('priority',$ical['event'][$i]['priority']);
-					}
-					else
-					{
-						$so_event->add_attribute('priority',2);
-					}
-					if(!isset($ical['event'][$i]['class']))
-					{
+				$all_attendees .= $cname . $email . ', ';
+					}
+			$this->debug('All attendees: ' . $all_attendees);
+
+			$ex_participants->setParticipantsByString($all_attendees);
+
+					}
+
+		if ($ical['event'][$i]['location']['value']) {
+			$so_event->add_attribute('location', $ical['event'][$i]['location']['value']);
+					}
+		if (isset ($ical['event'][$i]['priority'])) {
+			$so_event->add_attribute('priority', $ical['event'][$i]['priority']);
+		} else {
+			$so_event->add_attribute('priority', 2);
+					}
+		if (!isset ($ical['event'][$i]['class'])) {
 						$ical['event'][$i]['class'] = 1;
 					}
 					$so_event->set_class($ical['event'][$i]['class']);
 
-					@reset($datetime_vars);
-					while(list($e_datevar,$i_datevar) = each($datetime_vars))
-					{
-						if(isset($ical['event'][$i][$i_datevar]))
-						{
+		@ reset($datetime_vars);
+		while (list ($e_datevar, $i_datevar) = each($datetime_vars)) {
+			if (isset ($ical['event'][$i][$i_datevar])) {
 							$temp_time = $so_event->maketime($ical['event'][$i][$i_datevar]) + $GLOBALS['phpgw']->datetime->tz_offset;
-							
-							//verifica se o vcard importado tem a referÃªncia do timezone
-							if($ical['event'][$i][$i_datevar]['tzid']) {
-								$dateTimeZone = new DateTimeZone( $ical['event'][$i][$i_datevar]['tzid'] );
-								$dateTime = new DateTime("now", $dateTimeZone);
-								$timeOffset = $dateTimeZone->getOffset($dateTime);	
-								
-								//tira o time zone do vcard para sÃ³ ficar o time zone do sistema
-								$temp_time = $temp_time - $timeOffset;
+				@ reset($date_array);
+				while (list ($key, $var) = each($date_array)) {
+					$event[$e_datevar][$var] = (int) (date($key, $temp_time));
 							}
-							
-							@reset($date_array);
-							while(list($key,$var) = each($date_array))
-							{
-								$event[$e_datevar][$var] = (int)(date($key,$temp_time));
-							}
-							$so_event->set_date($e_datevar,$event[$e_datevar]['year'],$event[$e_datevar]['month'],$event[$e_datevar]['mday'],$event[$e_datevar]['hour'],$event[$e_datevar]['min'],$event[$e_datevar]['sec']);
-						}
-					}
-					if(!isset($ical['event'][$i]['categories']['value']) || !$ical['event'][$i]['categories']['value'])
-					{
+				$so_event->set_date($e_datevar, $event[$e_datevar]['year'], $event[$e_datevar]['month'], $event[$e_datevar]['mday'], $event[$e_datevar]['hour'], $event[$e_datevar]['min'], $event[$e_datevar]['sec']);
+						}
+					}
+		if (!isset ($ical['event'][$i]['categories']['value']) || !$ical['event'][$i]['categories']['value']) {
 						$so_event->set_category(0);
-					}
-					else
-					{
-						$ical_cats = Array();
-						if(strpos($ical['event'][$i]['categories']['value'],$cat_sep))
-						{
-							$ical_cats = explode($cat_sep,$ical['event'][$i]['categories']['value']);
-						}
-						else
-						{
+		} else {
+			$ical_cats = Array ();
+			if (strpos($ical['event'][$i]['categories']['value'], $cat_sep)) {
+				$ical_cats = explode($cat_sep, $ical['event'][$i]['categories']['value']);
+			} else {
 							$ical_cats[] = $ical['event'][$i]['categories']['value'];
 						}
 
-						@reset($ical_cats);
-						$cat_id_nums = Array();
-						while(list($key,$cat) = each($ical_cats))
-						{
-							if(!$cats->exists('appandmains',$cat))
-							{
-								$cats->add(
-									Array(
+			@ reset($ical_cats);
+			$cat_id_nums = Array ();
+			while (list ($key, $cat) = each($ical_cats)) {
+				if (!$cats->exists('appandmains', $cat)) {
+					$cats->add(Array (
 										'name'	=> $cat,
 										'descr'	=> $cat,
@@ -3182,43 +2895,30 @@
 										'access'	=> 'private',
 										'data'	=> ''
-									)
-								);
+					));
 							}
-//							$temp_id = $cats->name2id($cat);
-//							echo 'Category Name : '.$cat.' : Category ID :'.$temp_id."<br>\n";
-//							$cat_id_nums[] = $temp_id;
+				//							$temp_id = $cats->name2id($cat);
+				//							echo 'Category Name : '.$cat.' : Category ID :'.$temp_id."<br>\n";
+				//							$cat_id_nums[] = $temp_id;
 							$cat_id_nums[] = $cats->name2id($cat);
 						}
-						@reset($cat_id_nums);
-						if(count($cat_id_nums) > 1)
-						{
-							$so_event->set_category(implode($cat_id_nums,','));
-						}
-						else
-						{
+			@ reset($cat_id_nums);
+			if (count($cat_id_nums) > 1) {
+				$so_event->set_category(implode($cat_id_nums, ','));
+			} else {
 							$so_event->set_category($cat_id_nums[0]);
 						}
 					}
 
-//rrule
-					if(isset($ical['event'][$i]['rrule'])  OR isset($ical['event'][$i]['duration']) )
-					{
-// recur_enddate
-						if(isset($ical['event'][$i]['rrule']['until']))
-						{
-							$recur_enddate['year']  = (int)($ical['event'][$i]['rrule']['until']['year']);
-							$recur_enddate['month'] = (int)($ical['event'][$i]['rrule']['until']['month']);
-							$recur_enddate['mday']  = (int)($ical['event'][$i]['rrule']['until']['mday']);
-						}
-						elseif( isset($ical['event'][$i]['duration']) )
-						{
+		//rrule
+		if (isset ($ical['event'][$i]['rrule']) OR isset ($ical['event'][$i]['duration'])) {
+			// recur_enddate
+			if (isset ($ical['event'][$i]['rrule']['until'])) {
+				$recur_enddate['year'] = (int) ($ical['event'][$i]['rrule']['until']['year']);
+				$recur_enddate['month'] = (int) ($ical['event'][$i]['rrule']['until']['month']);
+				$recur_enddate['mday'] = (int) ($ical['event'][$i]['rrule']['until']['mday']);
+						}
+			elseif (isset ($ical['event'][$i]['duration'])) {
 							// Create timecode for strtotime
-							$ptimer = mktime($ical['event'][$i]['dtstart']['hour'],
-							$ical['event'][$i]['dtstart']['min'],
-							$ical['event'][$i]['dtstart']['sec'],
-							$ical['event'][$i]['dtstart']['month'],
-							$ical['event'][$i]['dtstart']['mday'],
-							$ical['event'][$i]['dtstart']['year']
-						);
+				$ptimer = mktime($ical['event'][$i]['dtstart']['hour'], $ical['event'][$i]['dtstart']['min'], $ical['event'][$i]['dtstart']['sec'], $ical['event'][$i]['dtstart']['month'], $ical['event'][$i]['dtstart']['mday'], $ical['event'][$i]['dtstart']['year']);
 
 						/*  -- Fixbug --
@@ -3230,15 +2930,7 @@
 
 							// Weeks::Day--
-							if( $ical['event'][$i]['duration']['weeks']
-							AND
-							( $ical['event'][$i]['duration']['hours'] == 0 )
-							AND
-							( $ical['event'][$i]['duration']['minutes'] == 0 )
-						)
-						{
-							$ical['event'][$i]['duration']['days'] = (
-								$ical['event'][$i]['duration']['days'] +
-								($ical['event'][$i]['duration']['weeks']*7))-1;
-								unset($ical['event'][$i]['duration']['weeks']);
+				if ($ical['event'][$i]['duration']['weeks'] AND ($ical['event'][$i]['duration']['hours'] == 0) AND ($ical['event'][$i]['duration']['minutes'] == 0)) {
+					$ical['event'][$i]['duration']['days'] = ($ical['event'][$i]['duration']['days'] + ($ical['event'][$i]['duration']['weeks'] * 7)) - 1;
+					unset ($ical['event'][$i]['duration']['weeks']);
 								$ical['event'][$i]['duration']['hours'] = "23";
 								$ical['event'][$i]['duration']['minutes'] = "59";
@@ -3246,12 +2938,5 @@
 							}
 							// Days::Day--
-							if(
-								$ical['event'][$i]['duration']['days']
-								AND
-								( $ical['event'][$i]['duration']['hours'] == 0 )
-								AND
-								( $ical['event'][$i]['duration']['minutes'] == 0 )
-							)
-							{
+				if ($ical['event'][$i]['duration']['days'] AND ($ical['event'][$i]['duration']['hours'] == 0) AND ($ical['event'][$i]['duration']['minutes'] == 0)) {
 								$ical['event'][$i]['duration']['days']--;
 								$ical['event'][$i]['duration']['hours'] = "23";
@@ -3262,35 +2947,23 @@
 							// Create string contains datetime for strtotime
 							$pdate = "+";
-							if( isset($ical['event'][$i]['duration']['weeks']) )
+				if (isset ($ical['event'][$i]['duration']['weeks']))
 							$pdate .= $ical['event'][$i]['duration']['weeks'] . " weeks ";
-							if( isset($ical['event'][$i]['duration']['days']) )
+				if (isset ($ical['event'][$i]['duration']['days']))
 							$pdate .= $ical['event'][$i]['duration']['days'] . " days ";
-							if( isset($ical['event'][$i]['duration']['hours']) )
+				if (isset ($ical['event'][$i]['duration']['hours']))
 							$pdate .= $ical['event'][$i]['duration']['hours'] . " hours ";
-							if( isset($ical['event'][$i]['duration']['minutes']) )
+				if (isset ($ical['event'][$i]['duration']['minutes']))
 							$pdate .= $ical['event'][$i]['duration']['minutes'] . " minutes ";
-							if( isset($ical['event'][$i]['duration']['seconds']) )
+				if (isset ($ical['event'][$i]['duration']['seconds']))
 							$pdate .= $ical['event'][$i]['duration']['seconds'] . " seconds ";
 
 							// What is datetime in 2192 ?
 							$enddate = strtotime($pdate, $ptimer);
-							list(   $recur_enddate['year'],
-							$recur_enddate['month'],
-							$recur_enddate['mday'],
-							$recur_enddate['hour'],
-							$recur_enddate['min'],
-							$recur_enddate['sec'] ) = split(":", date("Y:m:d:H:i:s", $enddate));
+				list ($recur_enddate['year'], $recur_enddate['month'], $recur_enddate['mday'], $recur_enddate['hour'], $recur_enddate['min'], $recur_enddate['sec']) = split(":", date("Y:m:d:H:i:s", $enddate));
 
 							// Set End of event
-							$so_event->set_end(     $recur_enddate['year'],
-							$recur_enddate['month'],
-							$recur_enddate['mday'],
-							$recur_enddate['hour'],
-							$recur_enddate['min'],
-							$recur_enddate['sec']);
-
-						}
-						else
-						{
+				$so_event->set_end($recur_enddate['year'], $recur_enddate['month'], $recur_enddate['mday'], $recur_enddate['hour'], $recur_enddate['min'], $recur_enddate['sec']);
+
+			} else {
 							$recur_enddate['year'] = 0;
 							$recur_enddate['month'] = 0;
@@ -3298,9 +2971,8 @@
 						}
 
-// recur_data
+			// recur_data
 						$recur_data = 0;
-						if(isset($ical['event'][$i]['rrule']['byday']))
-						{
-							$week_days = Array(
+			if (isset ($ical['event'][$i]['rrule']['byday'])) {
+				$week_days = Array (
 								MCAL_M_SUNDAY	=> 'SU',
 								MCAL_M_MONDAY	=> 'MO',
@@ -3311,9 +2983,7 @@
 								MCAL_M_SATURDAY	=> 'SA'
 							);
-							@reset($week_days);
-							while(list($key,$val) = each($week_days))
-							{
-								if(strpos(' '.$ical['event'][$i]['rrule']['byday'],$val))
-								{
+				@ reset($week_days);
+				while (list ($key, $val) = each($week_days)) {
+					if (strpos(' ' . $ical['event'][$i]['rrule']['byday'], $val)) {
 									$recur_data += $key;
 								}
@@ -3321,68 +2991,184 @@
 						}
 
-// interval
-						if(!isset($ical['event'][$i]['rrule']['interval']))
-						{
+			// interval
+			if (!isset ($ical['event'][$i]['rrule']['interval'])) {
 							$interval = 1;
-						}
-						else
-						{
-							$interval = (int)$ical['event'][$i]['rrule']['interval'];
-						}
-// recur_type
-						switch($ical['event'][$i]['rrule']['freq'])
-						{
-							case DAILY:
+			} else {
+				$interval = (int) $ical['event'][$i]['rrule']['interval'];
+						}
+			// recur_type
+			switch ($ical['event'][$i]['rrule']['freq']) {
+				case DAILY :
 								$recur_type = MCAL_RECUR_DAILY;
 								break;
-							case WEEKLY:
-								$so_event->set_recur_weekly($recur_enddate['year'],$recur_enddate['month'],$recur_enddate['mday'],$interval,$recur_data);
+				case WEEKLY :
+					$so_event->set_recur_weekly($recur_enddate['year'], $recur_enddate['month'], $recur_enddate['mday'], $interval, $recur_data);
 								break;
-							case MONTHLY:
-// Still need to determine if this is by day or by week for the month..
-//								$recur_type = MCAL_RECUR_M??????;
+				case MONTHLY :
+					// Still need to determine if this is by day or by week for the month..
+					//								$recur_type = MCAL_RECUR_M??????;
 								break;
-							case YEARLY:
-								$so_event->set_recur_yearly($recur_enddate['year'],$recur_enddate['month'],$recur_enddate['mday'],$interval);
+				case YEARLY :
+					$so_event->set_recur_yearly($recur_enddate['year'], $recur_enddate['month'], $recur_enddate['mday'], $interval);
 								break;
 						}
-					}
-					else
+		} else {
+						$so_event->set_recur_none();
+					}
+
+		// Owner
+		$organizer = $ical['event'][$i]['organizer'];
+
+		if (isset ($organizer)) {
+			if ($this->is_owner($organizer) || $organizer == -2) {
+				$so_event->add_attribute('owner', $GLOBALS['phpgw_info']['user']['account_id']);
+			} else {
+				$so_event->add_attribute('owner', -2);
+				$aux = explode(':', $organizer['cn']);
+				$so_event->add_attribute('organizer', '' . $aux[0] . ' <' . $organizer['mailto']['user'] . '@'. $organizer['mailto']['host'].'>');
+					}
+					}
+
+		// se for importação para conta compartilhada
+		$user = (int) ($importAccount ? $importAccount['uidnumber'] : $GLOBALS['phpgw_info']['user']['account_id']);
+		$userMail = $importAccount['mail'] ? $importAccount['mail'] : $GLOBALS['phpgw_info']['user']['email'];
+
+		$so_event->add_attribute('participants', 'A', $user);
+					$event = $so_event->get_cached_event();
+
+		/*
+		 * Remove Email do participantes externos
+		 */
+		$usersToRemove = array ();
+		$usersToRemove[] = $user;
+		foreach ($event['participants'] as $auxi=> $v)
+			$usersToRemove[] = $auxi;
+
+		$ldapService = ServiceLocator :: getService('ldap');
+		foreach ($usersToRemove as $v) {
+			$ex_participants->removeParticipant($ldapService->getMailByUidNumber($v));
+			$alternates = $ldapService->getMailAlternateByUidNumber($v);
+			foreach ($alternates as $ii => $vv)
+				$ex_participants->removeParticipant($vv);
+		}
+		$ex_participants->removeParticipant($event['organizer']);
+		/// -------------------------------------------------------- ///
+
+		$event['ex_participants'] = $ex_participants->getParticipantsSerializable();
+
+		if (!isset ($this->bo)) {
+			require_once ($_SESSION['rootPath'] . '/calendar/inc/class.bocalendar.inc.php');
+			$this->bo = new bocalendar();
+		}
+
+		if ($c_events < 2) //Ignora verificação de conflito quando o ical é de varios eventos
+		{
+			if ($overlapping_events = $this->bo->event_overlap($event, (!$from_ajax), null, $user)) {
+				if ($_GET['calendarImport'] == 1) //caso venha do modulo calendar
 					{
-						$so_event->set_recur_none();
-					}
-
-// Owner
-					if(!isset($ical['event'][$i]['organizer']) || (isset($ical['event'][$i]['organizer']) && $this->is_owner($ical['event'][$i]['organizer'])))
-					{
-						$so_event->add_attribute('owner',$GLOBALS['phpgw_info']['user']['account_id']);
-						$so_event->add_attribute('participants','A',(int)$GLOBALS['phpgw_info']['user']['account_id']);
-					}
-					else
-					{
-						$so_event->add_attribute('participants','A',(int)$GLOBALS['phpgw_info']['user']['account_id']);
-					}
-
-					$event = $so_event->get_cached_event();
-					$so_event->add_entry($event);
-//					$event = $so_event->get_cached_event();
-				}
-			}
-			if(!$from_ajax) {
-				Header('Location: '.$GLOBALS['phpgw']->link('/index.php',
-					Array(
+					$url = 'expressoMail1_2/controller.php?action=' . implode("&", array (
+						'calendar.uicalendar.overlap',
+						'o_events=' . implode(';', $overlapping_events),
+						'this_event=' . $event['id'],
+						'this_account=' . $user
+					));
+
+					echo "<script>document.location='" . $url . "'</script>";
+					exit;
+				} else
+					return array (
+						'url' => implode("&", array (
+							'calendar.uicalendar.overlap',
+							'o_events=' . implode(';', $overlapping_events),
+							'this_event=' . $event['id'],
+							'this_account=' . $user
+						))
+					);
+			}
+				}
+
+		if ($importAccount)
+			$so_event->add_entry($event, true, $importAccount);
+		else
+			$so_event->add_entry($event);
+
+			}
+
+	/*
+	 * Exclue os eventos que estão na lista para serem deletados
+	 */
+	if ($cancelEvent)
+		$so_event->expunge();
+	/*----------------------------------------------------------*/
+
+	if (!$from_ajax) {
+		Header('Location: ' . $GLOBALS['phpgw']->link('/index.php', Array (
 						'menuaction'	=> 'calendar.uicalendar.view',
 						'cal_id'	=> $event['id']
-						)
-					)
-				);
+		)));
 				$GLOBALS['phpgw']->common->phpgw_exit();
-			}
-			else 
+	} else // checando se o icalendar veio no formato esperado, ou seja, foi parseado corretamente
+		if (!empty ($ical))
 				return true;
-		}
-
-		function export($params)
-		{
+		else
+			return 'Cannot import target event. Please check if the format is right.';
+
+}
+
+function updateHour($ical) {
+
+	if (!is_object($GLOBALS['uicalendar'])) {
+		$so_event = createobject('calendar.socalendar', Array (
+			'owner' => 0,
+			'filter' => '',
+			'category' => ''
+		));
+	} else
+		$so_event = $GLOBALS['uicalendar']->bo->so;
+
+	$cal_id = $so_event->find_cal_id($ical['event'][0]['uid']['value']);
+
+	//Agendamento nao ecnontrado
+	if (!$cal_id)
+		return 'The event was not found in your calendar';
+
+	$event = $so_event->read_entry($cal_id);
+
+	$datetime_vars = Array (
+		'start' => 'dtstart',
+		'end' => 'dtend',
+		'modtime' => 'dtstamp',
+		'modtime' => 'last_modified'
+	);
+
+	$date_array = Array (
+		'Y' => 'year',
+		'm' => 'month',
+		'd' => 'mday',
+		'H' => 'hour',
+		'i' => 'min',
+		's' => 'sec'
+	);
+
+	@ reset($datetime_vars);
+	while (list ($e_datevar, $i_datevar) = each($datetime_vars)) {
+		if (isset ($ical['event'][0][$i_datevar])) {
+			$temp_time = $so_event->maketime($ical['event'][0][$i_datevar]);
+			@ reset($date_array);
+			while (list ($key, $var) = each($date_array))
+				$event[$e_datevar][$var] = (int) (date($key, $temp_time));
+
+			$so_event->set_date($e_datevar, $event[$e_datevar]['year'], $event[$e_datevar]['month'], $event[$e_datevar]['mday'], $event[$e_datevar]['hour'], $event[$e_datevar]['min'], $event[$e_datevar]['sec']);
+		}
+		}
+
+	$so_event->add_entry($event, false);
+	$bo_event = createobject('calendar.bocalendar');
+	$bo_event->send_update(MSG_MODIFIED, $event['participants'], $event, $event);
+
+	return 'Event successfully updated';
+}
+
+function export($params) {
 			$event_id = $params['l_event_id'] ? $params['l_event_id'] : $_GET['cal_id'];
 			$this->chunk_split = $params['chunk_split'];
@@ -3390,5 +3176,5 @@
 			$vtype = $params['vtype'] ? $params['vtype'] : 'event';
 
-			$string_array = Array(
+	$string_array = Array (
 				'summary'		=> 'description',
 				'location'		=> 'location',
@@ -3399,11 +3185,8 @@
 			$cats = CreateObject('phpgwapi.categories');
 
-			include(PHPGW_SERVER_ROOT.'/calendar/setup/setup.inc.php');
-			if(!is_array($event_id))
-			{
+	include (PHPGW_SERVER_ROOT . '/calendar/setup/setup.inc.php');
+	if (!is_array($event_id)) {
 				$ids[] = $event_id;
-			}
-			else
-			{
+	} else {
 				$ids = $event_id;
 			}
@@ -3411,45 +3194,33 @@
 			$ical = $this->new_ical();
 
-			$this->set_var($ical['prodid'],'value','-//eGroupWare//eGroupWare '.$setup_info['calendar']['version'].' MIMEDIR//'.strtoupper($GLOBALS['phpgw_info']['user']['preferences']['common']['lang']));
-			$this->set_var($ical['version'],'value','2.0');
-			$this->set_var($ical['method'],'value',strtoupper($method));
-
-			if(!$GLOBALS['phpgw_info']['flags']['included_classes']['uicalendar'])
-			{
-				if(!$GLOBALS['phpgw_info']['flags']['included_classes']['bocalendar'])
-				{
-					$so_event = createobject('calendar.socalendar',
-						Array(
+	$this->set_var($ical['prodid'], 'value', '-//eGroupWare//eGroupWare ' . $setup_info['calendar']['version'] . ' MIMEDIR//' . strtoupper($GLOBALS['phpgw_info']['user']['preferences']['common']['lang']));
+	$this->set_var($ical['version'], 'value', '2.0');
+	$this->set_var($ical['method'], 'value', strtoupper($method));
+
+	if (!$GLOBALS['phpgw_info']['flags']['included_classes']['uicalendar']) {
+		if (!$GLOBALS['phpgw_info']['flags']['included_classes']['bocalendar']) {
+			$so_event = createobject('calendar.socalendar', Array (
 							'owner'	=> 0,
 							'filter'	=> '',
 							'category'	=> ''
-						)
-					);
-				}
-				else
-				{
+			));
+		} else {
 					$so_event = $GLOBALS['bocalendar']->so;
 				}
-			}
-			else
-			{
+	} else {
 				$so_event = $GLOBALS['uicalendar']->bo->so;
 			}
 
-			foreach($ids as $event)
-			{
-				$ical_event = Array();
-				if (!is_array($event))
-				{
+	foreach ($ids as $event) {
+		$ical_event = Array ();
+		if (!is_array($event)) {
 					$event = $so_event->read_entry($event);
 				}
-				if($event['alarm'])
-				{
-					foreach($event['alarm'] as $alarm)
-					{
-						$ical_temp = Array();
+		if ($event['alarm']) {
+			foreach ($event['alarm'] as $alarm) {
+				$ical_temp = Array ();
 						$ical_temp['action']['value'] = 'DISPLAY';
 						$ical_temp['description']['value'] = $alarm['text'];
-						$this->set_var($ical_temp['trigger'],'value','VALUE=DATE-TIME:'.date('Ymd\THis\Z',$alarm['time']),'valarm');
+				$this->set_var($ical_temp['trigger'], 'value', 'VALUE=DATE-TIME:' . date('Ymd\THis\Z', $alarm['time']), 'valarm');
 						$ical_event['alarm'][] = $ical_temp;
 					}
@@ -3458,6 +3229,6 @@
 				// use system's date info for caluculating local timezone's offset in minutes
 				//
-				$gmt_offset = date('O',$GLOBALS['phpgw']->datetime->users_localtime);  // offset to GMT
-				$offset = (int)(substr($gmt_offset, 0, 3)) * 60 + (int)(substr($gmt_offset, 3, 2));
+		$gmt_offset = date('O', $GLOBALS['phpgw']->datetime->users_localtime); // offset to GMT
+		$offset = (int) (substr($gmt_offset, 0, 3)) * 60 + (int) (substr($gmt_offset, 3, 2));
 				$event['start']['min']   -= $offset;
 				$event['end']['min']     -= $offset;
@@ -3465,104 +3236,86 @@
 
 				$ical_event['priority'] = $event['priority'];
-				$ical_event['class'] = (int)$event['public'];
+		$ical_event['class'] = (int) $event['public'];
 				$dtstart_mktime = $so_event->maketime($event['start']);
-				$this->parse_value($ical_event,'dtstart',date('Ymd\THis\Z',$dtstart_mktime),'vevent');
+		$this->parse_value($ical_event, 'dtstart', date('Ymd\THis\Z', $dtstart_mktime), 'vevent');
 				$dtend_mktime = $so_event->maketime($event['end']);
-				$this->parse_value($ical_event,'dtend',date('Ymd\THis\Z',$dtend_mktime),'vevent');
+		$this->parse_value($ical_event, 'dtend', date('Ymd\THis\Z', $dtend_mktime), 'vevent');
 				$mod_mktime = $so_event->maketime($event['modtime']);
-				$this->parse_value($ical_event,'last_modified',date('Ymd\THis\Z',$mod_mktime),'vevent');
-				foreach($string_array as $ical_value => $event_value)
-				{
-					if($event[$event_value])
-					{
-						$this->set_var($ical_event[$ical_value],'value',$event[$event_value]);
-					}
-				}
-
-				if ($event['category'])
-				{
-					$cats->categories(0,'calendar');
-					foreach(explode(',',$event['category']) as $cat)
-					{
+		$this->parse_value($ical_event, 'last_modified', date('Ymd\THis\Z', $mod_mktime), 'vevent');
+		foreach ($string_array as $ical_value => $event_value) {
+			if ($event[$event_value]) {
+				$this->set_var($ical_event[$ical_value], 'value', $event[$event_value]);
+					}
+				}
+
+		if ($event['category']) {
+			$cats->categories(0, 'calendar');
+			foreach (explode(',', $event['category']) as $cat) {
 						$_cat = $cats->return_single($cat);
 						$cat_string[] = $_cat[0]['name'];
 					}
-					@reset($cat_string);
-					$this->set_var($ical_event['categories'],'value',implode($cat_string,','));
-				}
-
-				if(count($event['participants']) > 1)
-				{
-					if(!is_object($db))
-					{
+			@ reset($cat_string);
+			$this->set_var($ical_event['categories'], 'value', implode($cat_string, ','));
+				}
+
+		if (count($event['participants']) > 1) {
+			if (!is_object($db)) {
 						$db = $GLOBALS['phpgw']->db;
 					}
-					foreach($event['participants'] as $part => $status)
-					{
-						$GLOBALS['phpgw']->accounts->get_account_name($part,$lid,$fname,$lname);
-						$name = $fname.' '.$lname;
-
-						$owner_status = $this->switch_partstat((int)$this->switch_phpgw_status($event['participants'][$part]));
+			foreach ($event['participants'] as $part => $status) {
+				$GLOBALS['phpgw']->accounts->get_account_name($part, $lid, $fname, $lname);
+				$name = $fname . ' ' . $lname;
+
+				$owner_status = $this->switch_partstat((int) $this->switch_phpgw_status($event['participants'][$part]));
 
 						$mail_prefs = $GLOBALS['phpgw']->preferences->create_email_preferences($part);
 						$mailto = $mail_prefs['email']['address'];
 
-						$str = 'CN="'.$name.'";PARTSTAT='.$owner_status.':'.$mailto;
-						if($part == $event['owner'])
-						{
-							$str = 'ROLE=CHAIR;'.$str;
-						}
-						else
-						{
-							$str = 'ROLE=REQ-PARTICIPANT;'.$str;
-						}
-						if ($method != 'reply' || $part == $GLOBALS['phpgw_info']['user']['account_id'])
-						{
-							$this->parse_value($ical_event,'attendee',$str,'vevent');
-						}
-						if($part == $event['owner'])
-						{
-							$this->parse_value($ical_event,'organizer',$str,'vevent');
-						}
-					}
-				}
-				if($event['recur_type'])
-				{
+				$str = 'CN="' . $name . '";PARTSTAT=' . $owner_status . ':' . $mailto;
+				if ($part == $event['owner']) {
+					$str = 'ROLE=CHAIR;' . $str;
+				} else {
+					$str = 'ROLE=REQ-PARTICIPANT;' . $str;
+						}
+				if ($method != 'reply' || $part == $GLOBALS['phpgw_info']['user']['account_id']) {
+					$this->parse_value($ical_event, 'attendee', $str, 'vevent');
+						}
+				if ($part == $event['owner']) {
+					$this->parse_value($ical_event, 'organizer', $str, 'vevent');
+						}
+					}
+				}
+		if ($event['recur_type']) {
 					$str = '';
-					switch($event['recur_type'])
-					{
-						case MCAL_RECUR_DAILY:
+			switch ($event['recur_type']) {
+				case MCAL_RECUR_DAILY :
 							$str .= 'FREQ=DAILY';
 							break;
-						case MCAL_RECUR_WEEKLY:
+				case MCAL_RECUR_WEEKLY :
 							$str .= 'FREQ=WEEKLY';
-							if($event['recur_data'])
-							{
+					if ($event['recur_data']) {
 								$str .= ';BYDAY=';
-								for($i=1;$i<MCAL_M_ALLDAYS;$i=$i*2)
-								{
-									if($i & $event['recur_data'])
-									{
-										switch($i)
-										{
-											case MCAL_M_SUNDAY:
+						for ($i = 1; $i < MCAL_M_ALLDAYS; $i = $i * 2) {
+							if ($i & $event['recur_data']) {
+								switch ($i) {
+									case MCAL_M_SUNDAY :
 												$day[] = 'SU';
 												break;
-											case MCAL_M_MONDAY:
+									case MCAL_M_MONDAY :
 												$day[] = 'MO';
 												break;
-											CASE MCAL_M_TUESDAY:
+									CASE MCAL_M_TUESDAY :
 												$day[] = 'TU';
 												break;
-											case MCAL_M_WEDNESDAY:
+									case MCAL_M_WEDNESDAY :
 												$day[] = 'WE';
 												break;
-											case MCAL_M_THURSDAY:
+									case MCAL_M_THURSDAY :
 												$day[] = 'TH';
 												break;
-											case MCAL_M_FRIDAY:
+									case MCAL_M_FRIDAY :
 												$day[] = 'FR';
 												break;
-											case MCAL_M_SATURDAY:
+									case MCAL_M_SATURDAY :
 												$day[] = 'SA';
 												break;
@@ -3570,32 +3323,28 @@
 									}
 								}
-								$str .= implode(',',$day);
+						$str .= implode(',', $day);
 							}
 							break;
-						case MCAL_RECUR_MONTHLY_MDAY:
+				case MCAL_RECUR_MONTHLY_MDAY :
 							break;
-						case MCAL_RECUR_MONTHLY_WDAY:
+				case MCAL_RECUR_MONTHLY_WDAY :
 							break;
-						case MCAL_RECUR_YEARLY:
+				case MCAL_RECUR_YEARLY :
 							$str .= 'FREQ=YEARLY';
 							break;
 					}
-					if($event['recur_interval'])
-					{
-						$str .= ';INTERVAL='.$event['recur_interval'];
-					}
-					if($event['recur_enddate']['month'] != 0 && $event['recur_enddate']['mday'] != 0 && $event['recur_enddate']['year'] != 0)
-					{
+			if ($event['recur_interval']) {
+				$str .= ';INTERVAL=' . $event['recur_interval'];
+					}
+			if ($event['recur_enddate']['month'] != 0 && $event['recur_enddate']['mday'] != 0 && $event['recur_enddate']['year'] != 0) {
 						$recur_mktime = $so_event->maketime($event['recur_enddate']) - $GLOBALS['phpgw']->datetime->tz_offset;
-						$str .= ';UNTIL='.date('Ymd\THis\Z',$recur_mktime);
-					}
-					$this->parse_value($ical_event,'rrule',$str,'vevent');
+				$str .= ';UNTIL=' . date('Ymd\THis\Z', $recur_mktime);
+					}
+			$this->parse_value($ical_event, 'rrule', $str, 'vevent');
 
 					$exceptions = $event['recur_exception'];
-					if(is_array($exceptions))
-					{
-						foreach($exceptions as $except_datetime)
-						{
-							$ical_event['exdate'][] = $this->switch_date(date('Ymd\THis\Z',$except_datetime));
+			if (is_array($exceptions)) {
+				foreach ($exceptions as $except_datetime) {
+					$ical_event['exdate'][] = $this->switch_date(date('Ymd\THis\Z', $except_datetime));
 						}
 					}
@@ -3607,47 +3356,46 @@
 
 			// iCals are by default utf-8
-			return $GLOBALS['phpgw']->translation->convert($this->build_ical($ical),$GLOBALS['phpgw']->translation->charset(),'utf-8');
-		}
-
-		function freebusy($params=False)
-		{
-			if (!$params) $params = $_GET;
+	return $GLOBALS['phpgw']->translation->convert($this->build_ical($ical), $GLOBALS['phpgw']->translation->charset(), 'utf-8');
+}
+
+function freebusy($params = False) {
+	if (!$params)
+		$params = $_GET;
 			$user  = is_numeric($params['user']) ? (int) $params['user'] : $GLOBALS['phpgw']->accounts->name2id($params['user']);
-			$start = isset($params['start']) ? $params['start'] : date('Ymd');
-			$end   = isset($params['end']) ? $params['end'] : (date('Y')+1).date('md');
+	$start = isset ($params['start']) ? $params['start'] : date('Ymd');
+	$end = isset ($params['end']) ? $params['end'] : (date('Y') + 1) . date('md');
 
 			$this->bo = CreateObject('calendar.bocalendar');
-			$events_per_day = $this->bo->store_to_cache(array(
+	$events_per_day = $this->bo->store_to_cache(array (
 				'owner'  => $user,
-				'syear'  => (int) substr($start,0,4),
-				'smonth' => (int) substr($start,4,2),
-				'sday'   => (int) substr($start,6,2),
-				'eyear'  => (int) substr($end,0,4),
-				'emonth' => (int) substr($end,4,2),
-				'eday'   => (int) substr($end,6,2),
+		'syear' => (int) substr($start, 0, 4),
+		'smonth' => (int) substr($start, 4, 2),
+		'sday' => (int) substr($start, 6, 2),
+		'eyear' => (int) substr($end, 0, 4),
+		'emonth' => (int) substr($end, 4, 2),
+		'eday' => (int) substr($end, 6, 2),
 				'no_doubles' => True,	// report events only on the startday
+	
 			));
-			if (!is_array($events_per_day)) $events_per_day = array();
-			$ids = array();
-			foreach($events_per_day as $day => $events)
-			{
-				foreach($events as $event)
-				{
+	if (!is_array($events_per_day))
+		$events_per_day = array ();
+	$ids = array ();
+	foreach ($events_per_day as $day => $events) {
+		foreach ($events as $event) {
 					$ids[] = $event;
 				}
 			}
 			$browser = CreateObject('phpgwapi.browser');
-			$browser->content_header($GLOBALS['phpgw']->accounts->id2name($user).'.ifb','text/calendar');
-
-			echo $this->export(array(
+	$browser->content_header($GLOBALS['phpgw']->accounts->id2name($user) . '.ifb', 'text/calendar');
+
+	echo $this->export(array (
 				'vtype'      => 'freebusy',
 				'l_event_id' => $ids,
+		
 			));
-		}
-
-		function debug($str='')
-		{
-			if($this->debug_str)
-			{
+}
+
+function debug($str = '') {
+	if ($this->debug_str) {
 				//echo $str."<br>\n";
 				$log = fopen('/tmp/calendar.log', 'a') or die("nao foi possivel abrir o arquivo /tmp/calendar.log");
@@ -3655,5 +3403,26 @@
 				fclose($log);
 			}
-		}
-	}
+}
+
+function updateExParticipantState($cal_uid, $mail, $situation, $cn = false) {
+	$db = $GLOBALS['phpgw']->db;
+	$query = 'SELECT ex_participants FROM phpgw_cal WHERE uid = \'' . trim($cal_uid) . '\'';
+	if (!$db->query($query))
+		return false;
+	$row = $db->row(true);
+
+	if (!$row)
+		return false;
+
+	include_once ($_SESSION['rootPath'] . '/calendar/inc/class.ex_participants.inc.php');
+	$exParticipants = new exParticipants();
+	$exParticipants->setParticipantsBySerializable($row['ex_participants']);
+	$exParticipants->updateParticipant($mail, $situation, $cn);
+	$query = 'UPDATE phpgw_cal SET ex_participants = \'' . $exParticipants->getParticipantsSerializable() . '\' WHERE uid = \'' . trim($cal_uid) . '\'';
+	if (!$db->query($query))
+		return false;
+
+	return true;
+}
+}
 ?>
Index: trunk/calendar/inc/class.socalendar__.inc.php
===================================================================
--- trunk/calendar/inc/class.socalendar__.inc.php	(revision 4321)
+++ trunk/calendar/inc/class.socalendar__.inc.php	(revision 5132)
@@ -102,24 +102,4 @@
 		}
 
-		function set_observations($observations='')
-		{
-		    $this->add_attribute('observations',$observations);
-		}
-
-		function set_notifications_owner($notifications_owner='') 
-		{ 
- 	        $this->add_attribute('notifications_owner',$notifications_owner); 
- 	    } 
-		
-		function set_alter_by($alter_by='')
-		{
-		    $this->add_attribute('alter_by',$alter_by);
-		}
-
-                function set_attachment($attachment='')
-		{
-			$this->add_attribute('attachment',$attachment);
-		}
-
 		function set_ex_participants($ex_participants='')
 		{
Index: trunk/calendar/inc/class.uigroup_access.inc.php
===================================================================
--- trunk/calendar/inc/class.uigroup_access.inc.php	(revision 1684)
+++ trunk/calendar/inc/class.uigroup_access.inc.php	(revision 5132)
@@ -71,5 +71,6 @@
 				$scripts =	"<script src='".$module_name."/js/connector.js' type='text/javascript'></script>".
 							"<script type='text/javascript'>var DEFAULT_URL = '".$module_name."/controller.php?action=';</script> ".											
-							"<script src='calendar/js/search.js' type='text/javascript'></script>";				
+							"<script src='".$this->template_dir."/js/finder.js' type='text/javascript'></script>".
+							"<script src='".$this->template_dir."/js/search.js' type='text/javascript'></script>";				
 				// Fim				
 				
Index: trunk/calendar/inc/class.uiicalendar.inc.php
===================================================================
--- trunk/calendar/inc/class.uiicalendar.inc.php	(revision 3736)
+++ trunk/calendar/inc/class.uiicalendar.inc.php	(revision 5132)
@@ -17,4 +17,5 @@
 	{
 		var $bo;
+// 		var $ui;
 		var $template;
 
@@ -30,4 +31,6 @@
 		{
 			$this->bo = CreateObject('calendar.boicalendar');
+// 			$this->ui = CreateObject('calendar.uicalendar');
+
 			$this->template = $GLOBALS['phpgw']->template;
 			$GLOBALS['phpgw_info']['flags']['app_header'] = lang('Calendar - [iv]Cal Importer');
@@ -77,14 +80,8 @@
 		}
 
-		function import_from_mail($calendar) {
-			return $this->bo->import(explode("\n",$calendar),true);
+		function import_from_mail($calendar, $from_ajax, $importAccount = false) {
+			return $this->bo->import(explode("\n",$calendar),$from_ajax,$importAccount);
 		}
 		
-		function get_error_message($error_number) {
-			switch ($error_number) {
-				case 1:
-					return lang('event already exists');
-			}
-		}
 
 		function import()
@@ -108,17 +105,14 @@
 			}
 
- 			$this->template->set_file(array('vcalimport' => 'vcal_import.tpl'));
-			$this->template->set_block('vcalimport','page_block');
-			$this->template->set_block('vcalimport','error_block');
-			
-			if($GLOBALS['HTTP_GET_VARS']['error_number']) {
-				$this->template->set_var('error_message',$this->get_error_message( $GLOBALS['HTTP_GET_VARS']['error_number'] ) );
-				$this->template->parse('error_box','error_block',true);
-			}
+ 			$this->template->set_file(
+ 				Array(
+ 					'vcalimport' => 'vcal_import.tpl'
+ 				)
+ 			);
 			
 			$var = Array(
 				'vcal_header'	=> '<p>',
 				'ical_lang'		=> lang('(i/v)Cal'),
-				'action_url'	=> $GLOBALS['phpgw']->link('/index.php','menuaction=calendar.boicalendar.import'),
+				'action_url'	=> $GLOBALS['phpgw']->link('/index.php','menuaction=calendar.boicalendar.import&calendarImport=1'),
 				'lang_access'	=> lang('Access'),
 				'lang_groups'	=> lang('Which groups'),
@@ -128,6 +122,5 @@
 			);
 			$this->template->set_var($var);
-			$this->template->pfp('out', 'page_block');
-			// $this->template->pparse('out','page_block');
+			$this->template->pparse('out','vcalimport');
 		}
 	}
Index: trunk/calendar/inc/class.socalendar_sql.inc.php
===================================================================
--- trunk/calendar/inc/class.socalendar_sql.inc.php	(revision 4316)
+++ trunk/calendar/inc/class.socalendar_sql.inc.php	(revision 5132)
@@ -13,5 +13,11 @@
   *  option) any later version.                                              *
   \**************************************************************************/
-
+if($_SESSION['isCrun']){
+	$_SESSION['isCrun'] = false;
+	$_SESSION['rootPath'] = PHPGW_INCLUDE_ROOT;
+	require_once $_SESSION['rootPath'].'/API/class.servicelocator.php';
+}else{
+	require_once $_SESSION['rootPath'].'/API/class.servicelocator.php';
+}
 
 	if (@$GLOBALS['phpgw_info']['flags']['included_classes']['socalendar_'])
@@ -569,11 +575,8 @@
 				$this->set_title(stripslashes($GLOBALS['phpgw']->strip_html($this->stream->f('title'))));
 				$this->set_description(stripslashes($GLOBALS['phpgw']->strip_html($this->stream->f('description'))));
-				$this->set_observations(stripslashes($GLOBALS['phpgw']->strip_html($this->stream->f('observations'))));
-				$this->set_notifications_owner(stripslashes($GLOBALS['phpgw']->strip_html($this->stream->f('notifications_owner'))));
-				$this->set_alter_by(stripslashes($GLOBALS['phpgw']->strip_html($this->stream->f('alter_by'))));
-                                $this->set_attachment(stripslashes($GLOBALS['phpgw']->strip_html($this->stream->f('attachment'))));
 				$this->set_ex_participants(stripslashes($GLOBALS['phpgw']->strip_html($this->stream->f('ex_participants'))));
 				$this->add_attribute('uid',$GLOBALS['phpgw']->strip_html($this->stream->f('uid')));
 				$this->add_attribute('location',stripslashes($GLOBALS['phpgw']->strip_html($this->stream->f('location'))));
+				$this->add_attribute('organizer',stripslashes($GLOBALS['phpgw']->strip_html($this->stream->f('organizer'))));
 				$this->add_attribute('reference',(int)$this->stream->f('reference'));
 
@@ -737,5 +740,4 @@
 			else
 			{
-				//$user_where .= $this->user;
                                 $user_where .= $this->user . ') OR (phpgw_cal.owner=' . $this->user;
 			}
@@ -902,5 +904,5 @@
 		}
 
-		function save_event(&$event)
+		function save_event(&$event,$sendMail = true, $importAccount = false)
 		{
 
@@ -954,11 +956,6 @@
 			$enddate = $this->maketime($event['end']) - $GLOBALS['phpgw']->datetime->tz_offset;
 			$today = time() - $GLOBALS['phpgw']->datetime->tz_offset;
-//
-//			if($event['recur_type'] != MCAL_RECUR_NONE)
-//			{
-//				$type = 'M';
-//			}
-//			else
-//			{
+
+
 				if ($event['type'] == 'hourAppointment')
 					$type = 'H';
@@ -967,11 +964,5 @@
 				}else
 					$type = 'E';
-//			}
-                        if(is_array($event['attachment']))
-                            $sattach=serialize($event['attachment']);
-                        else if(is_array(unserialize($event['attachment'])))
-                            $sattach=$event['attachment'];
-                        else
-                            $sattach='';
+			
 
 			$sql = 'UPDATE phpgw_cal SET '
@@ -986,9 +977,6 @@
 					. "title='".$this->stream->db_addslashes($event['title'])."', "
 					. "description='".$this->stream->db_addslashes($event['description'])."', "
-					. "observations='".$this->stream->db_addslashes($event['observations'])."', "
-                    . 'notifications_owner='.(int)$event['notifications_owner'].','
-					. "attachment='".$this->stream->db_addslashes($sattach)."', "
-					. "alter_by='".$this->stream->db_addslashes($GLOBALS['phpgw_info']['user']['fullname'])."', "
 					. "ex_participants='".$this->stream->db_addslashes($event['ex_participants'])."', "
+					. "organizer='".$this->stream->db_addslashes($event['organizer'])."', "
 					. "location='".$this->stream->db_addslashes($event['location'])."', "
 					. ($event['groups']?"groups='".(count($event['groups'])>1?implode(',',$event['groups']):','.$event['groups'][0].',')."', ":'')
@@ -1095,6 +1083,53 @@
 			$GLOBALS['phpgw_info']['cal_new_event_id'] = $event['id'];
 			$this->event = $event;
+
+                        if($sendMail)
+                        {
+                            if($importAccount)
+                                $this->sendEmailEvendAccepted($event,$importAccount);
+                            else
+                                $this->sendEmailEvendAccepted($event);
+                        }
+	
 			return True;
 		}
+
+                function sendEmailEvendAccepted($event,$importAccount = false)
+                {
+
+                    if(!$importAccount)
+                        $importAccount['mail'] = $GLOBALS['phpgw_info']['user']['email'];
+
+                    //verifica se eh um evento externo se sim envia o vcard de aceitação em anexo
+                    if($event['owner'] == '-2')
+                    {
+                        $mailService = ServiceLocator::getService('mail');
+
+                        $tmpbody.= "<b>".lang("Event Accepted")."</b> ";
+                        $tmpbody.= "<br><br>".lang("name").": ".$event['title']."<br>";
+                        $tmpbody.= "<br>".lang("description").": ".$event['description']."<br>";
+
+                        $ev[0] = $event;
+
+                        $tmpattach=  $GLOBALS['calendar']->bocalendar->create_vcard($ev,'REPLY',true,$importAccount);
+                        
+                        $mailService->addStringAttachment($tmpattach, 'suggestion.ics', 'application/ics');
+                        $mailService->addStringAttachment($tmpattach, 'vcalendar.ics', 'utf-8', 'text/calendar; charset=utf-8; method=REPLY;', '7bit', '');
+                 
+                        if(strchr($event['organizer'],'@') && strchr($event['organizer'],'<') && strchr($event['organizer'],'>'))
+                        {
+                            $mail = substr($event['organizer'], strpos($event['organizer'],'<'), strpos($event['organizer'],'>'));
+                            $mail = str_replace('<','', str_replace('>','',$mail));
+                        }
+
+                        if($mail)
+                            $mailService->sendMail($mail,$importAccount['mail'],$event['title'],$tmpbody);
+
+                    }
+                    else
+                        $GLOBALS['calendar']->bocalendar->send_update(MSG_ACCEPTED, $event['participants'],$event);
+
+                    return;
+                }
 
 		function get_alarm($cal_id)
Index: trunk/calendar/inc/hook_sidebox_menu.inc.php
===================================================================
--- trunk/calendar/inc/hook_sidebox_menu.inc.php	(revision 4474)
+++ trunk/calendar/inc/hook_sidebox_menu.inc.php	(revision 5132)
@@ -24,9 +24,4 @@
 
 	$menu_title = $GLOBALS['phpgw_info']['apps'][$appname]['title'] . ' '. lang('Menu');
-	
-	$publicview_php_template_path = $GLOBALS['phpgw_info']['user']['preferences']['common']['template_set']; 
- 	if (!file_exists($GLOBALS['phpgw_info']['server']['webserver_url'].'/calendar/templates/'.$publicview_php_template_path.'/publicView.php')) 
- 	    $publicview_php_template_path = 'default';
-	
 	$file = Array(
 		'New Entry'   => $GLOBALS['phpgw']->link('/index.php','menuaction=calendar.uicalendar.add'),
@@ -41,5 +36,5 @@
 		'Import'=>$GLOBALS['phpgw']->link('/index.php','menuaction=calendar.uiicalendar.import'),
 		'Report of hours'=>$GLOBALS['phpgw']->link('/calendar/inc/hourReport.php',''),
-		'Public Calendars'=> "javascript:openwindow('calendar/templates/".$publicview_php_template_path."/publicView.php')"
+		'Public Calendars'=> "javascript:openwindow('calendar/templates/".$GLOBALS['phpgw_info']['user']['preferences']['common']['template_set']."/publicView.php')"
 	);
 	display_sidebox($appname,$menu_title,$file);
Index: trunk/calendar/inc/class.bogroup_access.inc.php
===================================================================
--- trunk/calendar/inc/class.bogroup_access.inc.php	(revision 580)
+++ trunk/calendar/inc/class.bogroup_access.inc.php	(revision 5132)
@@ -22,28 +22,25 @@
 	}
 
-	public final function search_user($params){			
-		$objLdap = new ldap_functions();
-		$objLdap -> ldapRootConnect();
-		$ldap = $objLdap -> ds;		
-		$search = $params['search'];
-		$accounttype = $params['type'];
-		$justthese = array("cn","uid", "uidNumber","gidNumber");
-    	$users_list=ldap_search($ldap, $_SESSION['phpgw_info']['expressomail']['server']['ldap_context'], "(&(phpgwAccountType=$accounttype) (|(cn=*$search*)(mail=$search*)) )", $justthese);    	
-    	if (ldap_count_entries($ldap, $users_list) == 0)
+        public final function search_user($params)
     	{
-    		$return['status'] = 'false';
-    		$return['msg'] = 'Nenhum resultado encontrado.';
-    		return $return;
-    	}    	
-    	ldap_sort($ldap, $users_list, "cn");    	
-    	$entries = ldap_get_entries($ldap, $users_list);    	    	
+	    $server = $_SESSION['phpgw_info']['expressomail']['server'];
+
+	    $t = $params['type'];
+
+	    $ldapService = ServiceLocator::getService('ldap');
+
+	    $ldapService->connect( $server['ldap_host'], $server['ldap_root_dn'], $server['ldap_root_pw'] );
+
+	    $entries = $ldapService->accountSearch($params['search'], array('cn', $t.'idNumber', $t.'id' ), $server['ldap_context'], $t, 'cn');
+
 		$options = '';
-		for ($i=0; $i<$entries['count']; $i++)
+
+	    foreach( $entries as $value )
 		{
-			$value = $entries[$i][$accounttype == "u" ? 'uidnumber' : 'gidnumber'][0];		
-			if($entries[$i]['mail'][0])
-				$mail = "(".$entries[$i]['mail'][0].")";
-			$options .= "<option value=" . $value. ">" . $entries[$i]['cn'][0] . " $mail" . "</option>";
+		$id = $value[$t.'id'] ? $value[$t.'id'] : $value[$t.'idnumber'];
+
+		$options .= '<option value='.$value[ $t.'idnumber' ].'>'.$value['cn'].'('.$id.')</option>';
 		}    	
+
     	return $options;		
 	} 
Index: trunk/calendar/inc/class.uipublicview.inc.php
===================================================================
--- trunk/calendar/inc/class.uipublicview.inc.php	(revision 3966)
+++ trunk/calendar/inc/class.uipublicview.inc.php	(revision 5132)
@@ -466,13 +466,4 @@
 					);
 				}
-                                if($event['attachment'] != '')
-				{
-					$picture[] = Array(
-						'pict'	=> $GLOBALS['phpgw']->common->image('calendar','circle'),
-						'width'	=> 9,
-						'height'=> 9,
-						'title' => lang('Has Attachment')
-					);
-				}
 				else
 				{
@@ -529,13 +520,4 @@
 			}
 
-                        if($event['attachment'] != '')
-			{
-                            $picture[] = Array(
-                                    'pict'	=> $GLOBALS['phpgw']->common->image('calendar','circle'),
-                                    'width'	=> 9,
-                                    'height'=> 9,
-                                    'title' => lang('Has Attachment')
-                            );
-			}
 			$description = $this->bo->get_short_field($event,$is_private,'description');
 			for($i=0;$i<count($picture);$i++)
Index: trunk/calendar/inc/class.uicalendar.inc.php
===================================================================
--- trunk/calendar/inc/class.uicalendar.inc.php	(revision 4844)
+++ trunk/calendar/inc/class.uicalendar.inc.php	(revision 5132)
@@ -57,6 +57,4 @@
 
 		var $public_functions = array(
-			'screen_delegate_event' => True,
-			'delegate_event' => True,
 			'mini_calendar' => True,
 			'index' => True,
@@ -67,4 +65,6 @@
 			'year' => True,
 			'view' => True,
+			//'suggest' => True,
+			'send_suggest_owner' => True,
 			'edit' => True,
 			'export'	=> True,
@@ -92,4 +92,9 @@
 		function uicalendar()
 		{
+		    $GLOBALS['phpgw_info']['flags']['noappheader'] = True;
+			$GLOBALS['phpgw_info']['flags']['noappfooter'] = True;
+                        $GLOBALS['phpgw_info']['flags']['currentapp'] = 'calendar';
+                        include_once( $_SESSION['rootPath'].'/header.inc.php' );
+
 			$GLOBALS['phpgw']->nextmatchs = CreateObject('phpgwapi.nextmatchs');
 			$GLOBALS['phpgw']->browser    = CreateObject('phpgwapi.browser');
@@ -163,92 +168,4 @@
 			}
 			$this->html = &$GLOBALS['phpgw']->html;
-		}
-
-		function screen_delegate_event($params=NULL) {
-			$module_name = 'expressoMail'.(str_replace("1.","1_",$GLOBALS['phpgw_info']['server']['cal_expressoMail']));
-
-			$sb = CreateObject('phpgwapi.sbox2');
-			$jscal = CreateObject('phpgwapi.jscalendar');	// before phpgw_header() !!!
-			unset($GLOBALS['phpgw_info']['flags']['noheader']);
-			unset($GLOBALS['phpgw_info']['flags']['nonavbar']);
-			$GLOBALS['phpgw_info']['flags']['noappheader'] = True;
-			$GLOBALS['phpgw_info']['flags']['noappfooter'] = True;
-			$GLOBALS['phpgw_info']['flags']['app_header'] = $event['id'] ? lang('Calendar - Edit') : lang('Calendar - Delegate Event'); 
-			$GLOBALS['phpgw']->common->phpgw_header();
-
-			$ldap_manager = CreateObject('contactcenter.bo_ldap_manager');
-			$_SESSION['phpgw_info']['expressomail']['user'] = $GLOBALS['phpgw_info']['user'];
-			$_SESSION['phpgw_info']['expressomail']['user']['owner'] = $event['owner'];
-			$_SESSION['phpgw_info']['expressomail']['server'] = $GLOBALS['phpgw_info']['server'];
-			$_SESSION['phpgw_info']['expressomail']['ldap_server'] = $ldap_manager ? $ldap_manager->srcs[1] : null;
-			$context = $GLOBALS['phpgw_info']['server']['ldap_context'];
-			$user_context = array();
-			foreach(explode(",",$GLOBALS['phpgw_info']['user']['account_dn']) as $i => $dn_part){
-				if($i)
-					$user_context[] = $dn_part;
-			}
-			// Prepara o contexto do usuario com sua OU raiz, pois ele pode pertencer a uma OU de nivel N.
-			$user_ou = explode(",",str_replace($context,"",implode(",",$user_context)));
-			$user_context = trim(strtolower($user_ou[count($user_ou) - 2].",".$context));
-			// Fim
-			// Verifica o tipo da visualização da árvore LDAP, configurado no admin da Agenda
-			$recursive = $GLOBALS['phpgw_info']['server']['cal_type_tree_participants'] == '1' ? true : false;
-			$combo_org = $this->get_organizations(trim(strtolower($context)),$user_context, $recursive);
-
-			$var = array(
-				"module_name"		=> $module_name,
-				"lang_loading"		=> lang("Loading"),
-				"lang_searching"	=> lang("Searching"),
-				"lang_users"		=> lang("Users"),
-				"lang_groups"		=> lang("Groups"),
-				"recursive"		=> ($recursive)?"":"search",
-				"options"		=> $combo_org,
-				"id_event"		=> $_REQUEST["id_event"],
-				"eventArray"		=> $_REQUEST["eventArray"],
-				"delegator"		=> $_REQUEST["delegator"],
-				"lang_avaliable_users"	=> lang("Available Users and Groups"),
-				"lang_search_for"	=> lang("Search for"),
-				"lang_ou"		=> lang("Organization"),
-				"min_num_characters"	=> $GLOBALS['phpgw_info']['server']['min_num_characters'],
-				"date"			=> $_REQUEST["date"],
-				"eventDelegation"	=> 1,
-				"Delegate"		=> lang("Delegate"),
-				'url_template'		=> 'calendar/templates/'.$_SESSION['phpgw_info']['calendar']['user']['preferences']['common']['template_set']
-			);
-
-			if(isset($_REQUEST["error"]))
-			{
-				if($_REQUEST["error"] == 999){
-					$var['error_msg'] = lang("Problems delegating. Make sure you have selected a user to delegate the appointment.");
-				}else {
-					$var['error_msg'] = lang("Problems delegating. Make sure you haven't delegated to a person that was also invited to the meeting");
-				}
-			}
-
-			$template = CreateObject('phpgwapi.Template',$this->template_dir);
-			$template->set_file(
-					array(
-						"screen"=>"delegate.tpl"
-					)
-				);
-			$template->set_var($var);
-			print $template->fp('out','screen');
-		}
-
-
-		function delegate_event($params=NULL) {
-			//$ldap = CreateObject('expressoMail1_2.ldap_functions');
-			//$delegated = $ldap->uid2uidnumber($_REQUEST['delegated']);
-
-			try {
-				$this->bo->delegar($_REQUEST['delegator'],$_REQUEST['delegated']/*$delegated*/,$_REQUEST['event']);
-				header("Location: index.php?menuaction=calendar.uicalendar.day&date=".$_REQUEST['date']);
-			}catch(Exception $e) {
-				if($e->getMessage() == '999') {
-					header("Location: index.php?menuaction=calendar.uicalendar.screen_delegate_event&id_event=". $_REQUEST["event"]."&delegator=".$_REQUEST["delegator"]."&date=".$_REQUEST["date"]."&error=999");
-				}else {
-					header("Location: index.php?menuaction=calendar.uicalendar.screen_delegate_event&id_event=". $_REQUEST["event"]."&delegator=".$_REQUEST["delegator"]."&date=".$_REQUEST["date"]."&error=1");
-				}
-			}
 		}
 
@@ -392,27 +309,5 @@
 						{
 //NDEE: class def what for?
-						    $dayToday = (int)(substr($today,6,2));
-						    $seleDay = (int)(substr($_GET['date'],6,2));
-						    if($day == $dayToday)
-						    {
-							if($dayToday == $seleDay)
-							{
-							    $day_params['class'] = 'minicaltodaysel';
-							}
-							else
-							{
-							    $day_params['class'] = 'minicaltoday';
-							}
-						    }
-
-						    if( isset($params['control']) && $params['control'] )
-						    {
-							if($day == $seleDay && $dayToday != $seleDay)
-							{
-							    $day_params['class'] = 'minicalnottoday';
-							}
-						    }
-
-                                                        $str = '<a href="'.$this->page($params['link'],'&date='.$date).'" class="'.$day_params['class'].'" ' . ($day_params['class']=='bminicalhol' || $day_params['class']=='minicalhol'?' title="' . $day_params['holidays'][0] . '" ' :'') . ' >'.$day.'</a>';
+							$str = '<a href="'.$this->page($params['link'],'&date='.$date).'" class="'.$day_params['class'].'">'.$day.'</a>';
 						}
 						else
@@ -473,19 +368,19 @@
 			$_SESSION['calendar']['categories'] = $this->cat->formated_list('select','all',$this->bo->cat_id,'True');
 			if((!isset($GLOBALS['phpgw_info']['server']['deny_user_grants_access']) || !$GLOBALS['phpgw_info']['server']['deny_user_grants_access']) && count($this->bo->grants) > 0)
+			{	
 				$_SESSION['calendar']['cals'] = $this->bo->list_cals();
+			}
 
 			if($this->bo->printer_friendly || $_GET['plain'] == 'True')
 			{	
-				$app_css_path = $_SESSION['phpgw_info']['calendar']['user']['preferences']['common']['template_set'];
-				$app_print_css_path = $app_css_path;
-				if (!file_exists($GLOBALS['phpgw_info']['server']['webserver_url'].'/calendar/templates/'.$app_css_path.'/app.css'))
-					$app_css_path = 'default';
-				if (!file_exists($GLOBALS['phpgw_info']['server']['webserver_url'].'/calendar/templates/'.$app_print_css_path.'/app_print.css'))
-					$app_print_css_path = 'default';
-
 				$new_body = '<html>'."\n"
 					.'<head>'."\n"
-					.'<LINK href="'.$GLOBALS['phpgw_info']['server']['webserver_url'].'/calendar/templates/'.$app_css_path.'/app.css" type=text/css rel=StyleSheet>'."\n"
-					.'<LINK href="'.$GLOBALS['phpgw_info']['server']['webserver_url'].'/calendar/templates/'.$app_print_css_path.'/app_print.css" type=text/css rel=StyleSheet media="print">'."\n"
+					.'<SCRIPT type="text/javascript">
+						window.onbeforeunload = function() {
+							return \'Gostaria realmente de fechar essa janela ?\';
+						}					
+					</SCRIPT>'
+					.'<LINK href="'.$GLOBALS['phpgw_info']['server']['webserver_url'].'/calendar/templates/'.$_SESSION['phpgw_info']['calendar']['user']['preferences']['common']['template_set'].'/app.css" type=text/css rel=StyleSheet>'."\n"
+					.'<LINK href="'.$GLOBALS['phpgw_info']['server']['webserver_url'].'/calendar/templates/'.$_SESSION['phpgw_info']['calendar']['user']['preferences']['common']['template_set'].'/app_print.css" type=text/css rel=StyleSheet media="print">'."\n"
 					.'</head>
 					<table id="calendar_print_main" class="calendar_print_main">						
@@ -493,6 +388,9 @@
 							<td id="calendar_print_content" class="calendar_print_content">'.$body.'</td>
 						</tr>
+						
 						<tr>
 						  <td>
+							<br/>
+							<br/>
 							<div>
 								<input class=button type="button" onClick="javascript:this.style.visibility=\'hidden\';window.print();window.close();" value="Imprimir esta p&aacute;gina">
@@ -516,33 +414,17 @@
 				
 				$GLOBALS['phpgw']->common->phpgw_header();
-				$new_body = $this->bo->debug_string.$body;				
 				
-			}
+				$new_body = $this->bo->debug_string.$body;								
+		}
+
+
+
+			
 			return $new_body;
-		}
+                        }
 
 		function month()
-		{
-                        if($_GET['month']||$_POST['month']){
-                            $params['month'] = $_GET['month']?(int)$_GET['month']:(int)$_POST['month'];
-                            $params['year'] = $_GET['year']?(int)$_GET['year']:(int)$_POST['year'];
-                            $params['day'] = 1;
-
-                        }else{
-                            $params['day'] = $_POST['date']?(int)substr($_POST['date'] , 6, 2):(int)substr($_GET['date'] , 6, 2);
-                            $params['month'] = $_POST['date']?(int)substr($_POST['date'] , 4, 2):(int)substr($_GET['date'] , 4, 2);
-                            $params['year'] = $_POST['date']?(int)substr($_POST['date'] , 0, 4):(int)substr($_GET['date'] , 0, 4);
-
-                        }
-
-			if($_GET['friendly']==1)
 			{
 			    echo $this->printer_friendly($this->get_month(),lang('Monthview'));
-			}
-			else
-			{
-			    echo $this->printer_friendly($this->print_month_new($params),lang('Monthview'));
-			}
-
 			$GLOBALS['phpgw']->common->phpgw_footer();
 		}
@@ -550,4 +432,6 @@
 		function get_month()
 		{
+			$this->bo->read_holidays();
+			
 			$m = mktime(0,0,0,$this->bo->month,1,$this->bo->year);
 
@@ -594,19 +478,45 @@
 				$minical_next = '';
 			}
-                        $this->bo->read_holidays($params['year']);
+
 			if($_POST['year']) {			
 	
 			}
 
+			$hoje = date('Ymd',$GLOBALS['phpgw']->datetime->gmtnow);
+			$mes_hoje = (int)substr($hoje,4,2);
+			$sday = 1;
+			if($_POST['day']) {
+				$day_ini = (int)$_POST['day'];
+			} 
+			elseif($_GET['sday']){
+				if($_GET['month'] == $mes_hoje)
+			{
+					$day_ini = $this->bo->day;
+				} 
+
+				else
+				{
+					$day_ini = (int)$_GET['sday'];
+				}
+			} 
+			elseif( ($_POST['dia_ini']) && ($_POST['dia_ini'] == $this->bo->day) )
+			{
+				$day_ini = (int)substr($hoje,6,2);
+			}
+			else
+			{
+				$day_ini = $this->bo->day;
+			}
+			if($_POST['qtd_dias'])
+			{
+				$num_dias = (int)$_POST['qtd_dias'];
+			} 
+			else
+			{
+				$num_dias = 0;
+			}
+
 			if (!$this->bo->printer_friendly)
 			{
-			    $account_name = $_POST['user'] ? $_POST['user'] : ($_GET['account_name'] ? $_GET['account_name'] : '');
-
-			    $accounts = CreateObject('phpgwapi.accounts');
-			    $accountId = $accounts->name2id($account_name);
-
-			    $prefs = CreateObject('phpgwapi.preferences', $accountId);
-			    $account_prefs = $prefs->read();
-
 			    $printer = '';
 			    $prev_month_link = '<a href="'.$this->page('month','&year='.$prevyear.'&month='.$prev.'&sday='.$sday).'">&lt;&lt;</a>';
@@ -614,24 +524,9 @@
 			    $param = '&year='.$this->bo->year.'&month='.$this->bo->month.'&friendly=1'.'&day_ini='.$day_ini.'&num_dias='.$num_dias;
 			    //$param = '&year='.$this->bo->year.'&month='.$this->bo->month.'&friendly=1';
-			    /*if($account_prefs['calendar']['type_month_print'] == '0')
-			    {
 			    $print = "<a href='javascript:void(0)' onClick=\"javascript:window.open('".$this->page('month'.$param).
 					    "','','width=600,height=600,toolbar=no,scrollbars=yes,resizable=no');\" onMouseOver=\"window.status = '".
 					    lang('Generate printer-friendly version')."'\">[".lang('Printer Friendly').']</a>';
-			    }
-			    else
-			    {
-			    $print =  '<a href="javascript:void(0)" onclick="scheduler.toPDF('."'calendar/js/dhtmlx/server/generate.php'".')">['.lang('Printer Friendly').']</a>';
-			    }*/
-
 			    //linha abaixo foi adicionada para exibir a pagina do mes em tela
-			    //$month,$year,$showyear,$owner=0;
-			    $params = Array(
-				'month'	=> $this->bo->month,
-				'year'	=> $this->bo->year,
-				'showyear'	=> True,
-				'owner'	=> $this->bo->owner
-			    );
-			    $large_month = $this->display_month($params);
+				$large_month = $this->display_month($this->bo->month,$this->bo->year,True,$this->bo->owner);				
 			}
 			else
@@ -643,24 +538,8 @@
 			    $GLOBALS['phpgw_info']['flags']['nofooter'] = True;
 			    //linha abaixo foi adicionada para exibir a pagina do mes para impressao
-
-			    //if($_GET['classic_print']==1)
-			    //	$large_month = $this->display_month($this->bo->month,$this->bo->year,True,$this->bo->owner);
-			    //else
 			    $large_month = $this->display_month_print($this->bo->month,$this->bo->year,True,$this->bo->owner);
 			}
 
 			$this->bo->read_holidays();
-
-			$aux_month_identifier = lang(strftime("%B",$m)).' '.$this->bo->year;
-			if(isset($_GET['friendly']) && $_GET['friendly'] ==1)
-			{
-			    if( isset($_GET['num_dias']) && ($_GET['num_dias'] == 1) )
-			    {
-				$year = $_GET['year'];
-				$month = $_GET['month'];
-				$day = $_GET['day_ini'];
-				$aux_month_identifier = $this->month_day_of_week($year,$month,$day).', '.$day.' de '.lang(strftime("%B",$m)).' de '.$this->bo->year;
-			    }
-			}
 
 			$var = Array(
@@ -669,8 +548,9 @@
 				'small_calendar_prev'	    => $minical_prev,
 				'prev_month_link'	    => $prev_month_link,
-				'month_identifier'	    => $aux_month_identifier,
+				'month_identifier'		=>	lang(strftime("%B",$m)).' '.$this->bo->year,
 				'username'		    => $GLOBALS['phpgw']->common->grab_owner_name($this->bo->owner),
 				'next_month_link'	    => $next_month_link,
 				'small_calendar_next'	    => $minical_next,
+				//'large_month'				=>	$this->display_month($this->bo->month,$this->bo->year,True,$this->bo->owner),
 				'large_month'		    => $large_month,
 				'print'			    => $print
@@ -700,19 +580,5 @@
 		function week()
 		{
-
-                        if($_GET['month']||$_POST['month']){
-                            $params['month'] = $_GET['month']?(int)$_GET['month']:(int)$_POST['month'];
-                            $params['year'] = $_GET['year']?(int)$_GET['year']:(int)$_POST['year'];
-                            $params['day'] = $_GET['day']?(int)$_GET['day']:(int)$_POST['day'];
-
-                        }else{
-                            $params['day'] = $_POST['date']?(int)substr($_POST['date'] , 6, 2):(int)substr($_GET['date'] , 6, 2);
-                            $params['month'] = $_POST['date']?(int)substr($_POST['date'] , 4, 2):(int)substr($_GET['date'] , 4, 2);
-                            $params['year'] = $_POST['date']?(int)substr($_POST['date'] , 0, 4):(int)substr($_GET['date'] , 0, 4);
-
-                        }
-
-			echo $this->printer_friendly($this->print_week_new($params),lang('Weekview'));
-			
+			echo $this->printer_friendly($this->get_week(),lang('Weekview'));
 			$GLOBALS['phpgw']->common->phpgw_footer();
 		}
@@ -727,4 +593,14 @@
 			if (isset($this->bo->prefs['calendar']['display_minicals']) && $this->bo->prefs['calendar']['display_minicals'] == "1" && !$this->bo->printer_friendly)
 			{
+				$minical_this = $this->mini_calendar(
+					Array(
+						'day'	=> $this->bo->day,
+						'month'	=> $this->bo->month,
+						'year'	=> $this->bo->year,
+						'link'	=> 'day',
+						'butons'	=> 'none',
+						'outside_month'	=> False
+					)
+				);
 				$minical_prev = $this->mini_calendar(
 					Array(
@@ -747,19 +623,9 @@
 					)
 				);
-                                $minical_this = $this->mini_calendar(
-					Array(
-						'day'	=> $this->bo->day,
-						'month'	=> $this->bo->month,
-						'year'	=> $this->bo->year,
-						'link'	=> 'day',
-						'butons'	=> 'none',
-						'outside_month'	=> False
-					)
-				);
 			}
 			else
 			{
 
-			//NDEE: printer-friendly what?
+//NDEE: printer-friendly what?
 				$minical_this = '';
 				$minical_prev = '';
@@ -773,12 +639,10 @@
 				$prev_week_link = '<a href="'.$this->page('week','&date='.$prev['full']).'">&lt;&lt;</a>';
 				$next_week_link = '<a href="'.$this->page('week','&date='.$next['full']).'">&gt;&gt;</a>';
-				$print = '<a href="javascript:void(0);" onclick="scheduler.toPDF('."'calendar/js/dhtmlx/server/generate.php'".')">['.lang('Printer Friendly').']</a>';
-				
-                                //$print = '<a href="'.$this->page('week','&friendly=1&date='.sprintf("%04d%02d%02d",$this->bo->year,$this->bo->month,$this->bo->day))."\" TARGET=\"cal_printer_friendly\" onMouseOver=\"window.status = '".lang('Generate printer-friendly version')."' \">[".lang('Printer Friendly').']</a>';
+				$print = '<a href="'.$this->page('week','&friendly=1&date='.sprintf("%04d%02d%02d",$this->bo->year,$this->bo->month,$this->bo->day))."\" TARGET=\"cal_printer_friendly\" onMouseOver=\"window.status = '".lang('Generate printer-friendly version')."'\">[".lang('Printer Friendly').']</a>';
 			}
 			else
 			{
 
-				//NDEE: printer-friendly (weekly-view)
+//NDEE: printer-friendly (weekly-view)
 				$printer = '<body bgcolor="'.$this->theme['bg_color'].'">';
 				$prev_week_link = '';
@@ -807,5 +671,5 @@
 				'print'			=>	$print
 			);
-			//todo
+//todo
 			$p = CreateObject('phpgwapi.Template',$this->template_dir);
 			$p->set_file(
@@ -968,5 +832,7 @@
 			);
 
-			$button_left = $button_center = $button_right = '';
+			$p->set_file(Array('form_button'			=> 'form_button_script.tpl'	));
+
+			$button_left = $button_center = $button_right = $button_right_suggestion = '';
 
 			if($this->bo->check_perms(PHPGW_ACL_EDIT,$event))
@@ -976,4 +842,6 @@
 					$var = Array(
 						'action_url_button'	=> $this->page('edit','&cal_id='.$cal_id),
+                                                // added date to the action parameteres so we can add an exception to an edited event 
+ 		                                'action_url_button'     => $this->page('edit','&cal_id='.$cal_id.'&date='.$date), 
 						'action_text_button'	=> lang('Edit Single'),
 						'action_confirm_button'	=> '',
@@ -1027,5 +895,5 @@
 						'action_url_button'	=> $this->page('delete','&cal_id='.$cal_id),
 						'action_text_button'	=> lang('Delete Single'),
-						'action_confirm_button'	=> "onClick=\"return confirm('".lang('Are you sure want to delete this single occurence?').'\\n'.lang('This will delete this entry for all users.')."')\"",
+						'action_confirm_button'	=> "onClick=\"return confirm('".lang('Are you sure want to delete this single occurence?\\nThis will delete this entry for all users.')."')\"",
 						'action_extra_field'	=> $this->html->input_hidden(array(
 							'delete_type' => 'single',
@@ -1092,4 +960,13 @@
 				}
 			}
+			$uid          	 = $event['uid'];
+			$owner        	 = $event['owner'];
+			$title       	 = $event['title'];
+			$description 	 = rtrim(utf8_encode($event['description'])); 
+			$location   	 = $event['location'];
+			$start			 = $event['start'];
+			$end		     = $event['end'];
+                       
+ 			$p->set_var( 'suggestion', $this->build_suggestion( $event , $GLOBALS['phpgw_info']['user']['account_id']) );
 
 			$var = Array(
@@ -1113,8 +990,13 @@
 				$button_left .= '<td>'.$p->fp('button','form_button').'</td>';
 			}
+                        
+                        $label_suggest = lang('Suggest new hour'); 
+                        $button_right_suggestion = "<td><input type=\"button\" style=\"height: 16px; width: 110px; font-size: 10px;\" value=\"" . $label_suggest . "\"onclick=\"show_suggestion()\";</td>"; 
+                        
 			$p->set_var(array(
 				'button_left'	=> $button_left,
 				'button_center'	=> $button_center,
-				'button_right'	=> $button_right
+				'button_right'	=> $button_right,
+				'button_right_suggestion' => $button_right_suggestion
 			));
 			$p->pfp('phpgw_body','view_event');
@@ -1128,4 +1010,144 @@
 		}
 
+		function build_suggestion( $event , $user = false )
+		{
+		    $p = $GLOBALS['phpgw']->template;
+
+		    $p->set_file(
+			    Array(
+				'suggestion'	=> 'suggestion.tpl'
+			    )
+		    );
+
+                   include_once($_SESSION['rootPath'].'/calendar/inc/class.ex_participants.inc.php');
+                   $exParticipants = new exParticipants();
+                   $exParticipants->setParticipantsBySerializable($event['ex_participants']);
+
+                    $cal_id              = $event['id'];
+		    $uid          	 = $event['uid'];
+		    $owner        	 = $event['owner'];
+		    $title       	 = $event['title'];
+		    $description 	 = rtrim(utf8_encode($event['description'])); 
+		    $location   	 = $event['location'];
+		    $start			 = $event['start'];
+		    $end		     = $event['end'];
+
+                    if( $owner == -2 )
+                    {
+                        $to = $event['organizer'];
+                        $mail = array();
+
+                        if( preg_match ('(<([^>]*@[^>]*)>)', $to, $mail ) )
+                            $to =  $mail[1];
+                    }
+                    else
+                    {
+                        $preferences = CreateObject('phpgwapi.preferences',$owner);
+                        $to = $preferences->email_address($owner);
+                    }
+      
+
+		    if(((int)$start['month']) < 10 && strlen($start['month']) == 1)
+			    $mes = "0" . $start['month'];
+		    else
+			    $mes = $start['month'];	
+
+		    if(((int)$start['mday']) < 10 && strlen($start['mday']) == 1)
+			    $dia = "0" . $start['mday'];
+		    else
+			    $dia = $start['mday'];		
+		    
+		    if(((int)$start['hour']) < 10 && strlen($start['hour']) == 1)
+			    $hor = "0" . $start['hour'];
+		    else
+			    $hor = $start['hour'];
+		    
+		    if(((int)$start['min']) < 10 && strlen($start['min']) == 1)
+			    $min = "0" . $start['min'];
+		    else
+			    $min = $start['min'];
+		    
+		    if(((int)$end['month']) < 10 && strlen($end['month']) == 1)
+			    $end['month'] = "0" . $end['month'];
+		    
+		    if(((int)$end['mday']) < 10 && strlen($end['mday']) == 1)
+			    $end['mday'] = "0" . $end['mday'];
+		    
+		    if(((int)$end['hour']) < 10 && strlen($end['hour']) == 1)
+			    $end['hour'] = "0" . $end['hour'];
+			    
+		    if(((int)$end['min']) < 10 && strlen($end['min']) == 1)
+			    $end['min'] = "0" . $end['min'];
+
+		    $start_date  = $dia . "/" . $mes . "/" . $start['year']; 
+		    $start_hour  = $hor . ":" . $min; 				
+		    $end_date    =  $end['mday'] . "/" . $mes . "/" . $start['year'];
+		    $end_hour    =  $end['hour'] . ":" . $end['min'];
+
+		    $notify_message = lang('suggest new hour');
+		    $start_h = substr($start_hour, 0, strpos($start_hour, ":"));
+		    $start_m = substr($start_hour, strpos($start_hour, ":")+1);
+		    $end_h   = substr($end_hour, 0, strpos($end_hour, ":"));
+		    $end_m   = substr($end_hour, strpos($end_hour, ":")+1);
+
+		    $p->set_var('notify_message', $notify_message);
+		    $p->set_var('action_form', $this->page('send_suggest_owner'));
+		    $p->set_var('lang_start_hour', lang('Start hour'));
+		    $p->set_var('lang_end_hour', lang('End hour'));
+		    $p->set_var('lang_start_date', lang('Start date'));
+		    $p->set_var('lang_end_date', lang('End date'));
+		    $p->set_var('lang_suggest_new_hour', lang('Suggest new hour'));
+		    $p->set_var('cal_id', $cal_id);
+		    $p->set_var('to', $to);
+		    $p->set_var('title', $title);
+		    $p->set_var('description', $description);
+		    $p->set_var('uid', $uid);
+		    $p->set_var('location', $location);
+		    $p->set_var('ex_participants', $exParticipants->getParticipantsMailsString());
+		    $p->set_var('start_date', $start_date);
+		    $p->set_var('start_hour', $start_h);
+		    $p->set_var('start_minute', $start_m);
+		    $p->set_var('end_date', $end_date);
+		    $p->set_var('end_hour', $end_h);
+		    $p->set_var('end_minute', $end_m);
+		    $p->set_var('url', $GLOBALS['phpgw_info']['server']['webserver_url']);
+                    $p->set_var('user', $user);
+
+		    return $p->fp( 'suggestion', 'suggestion' );
+		}
+
+		/**
+		 * @license http://www.gnu.org/copyleft/gpl.html GPL
+		 * @abstract: método que envia a sugestão para o criador do compromisso.
+		 * @author Prognus Software Livre (http://www.prognus.com.br)
+		 */
+		function send_suggest_owner()
+		{				
+			$array_data_inicio = explode('/',$_POST['data_inicio']);
+			$array_data_final  = explode('/',$_POST['data_final']);
+			$hora_inicio       = $_POST['hora_inicio'];
+			$minuto_inicio     = $_POST['minuto_inicio'];					
+			$hora_final        = $_POST['hora_final'];
+			$minuto_final      = $_POST['minuto_final'];
+			
+			$vars = $_GET['cal_id'];
+			$array_vars = explode(";", $vars);
+			$cal_id          = $array_vars[0];
+			$to              = $array_vars[1];
+			$title_          = $array_vars[2];
+			$description_    = $array_vars[3];
+			$uid             = $array_vars[4];
+			$location        = $array_vars[5];
+			$ex_participants = $array_vars[6];
+                        $user            = $array_vars[7];                      
+			$time_suggest      = array('hora_inicio' => $hora_inicio, 'hora_final' => $hora_final, 'minuto_inicio' => $minuto_inicio, 'minuto_final' => $minuto_final);
+
+			$cal_id = $this->bo->send_suggestion_external_owner($cal_id, $uid, $to, $time_suggest, $array_data_inicio, $array_data_final, $title_, $description_, $location, $ex_participants,$user);
+
+                        Header('Location: '.$this->page('view','&cal_id='.$cal_id));
+
+                }
+	
+		
 		function edit($params='')
 		{
@@ -1186,5 +1208,6 @@
 						'event' => $event,
 						'cd'	=> $cd,
-						'plain' => $plain
+						'plain' => $plain,
+                                                'date'  =>  $_GET['date'] 
 					)
 				);
@@ -1219,4 +1242,6 @@
 		function export($vcal_id=0)
 		{
+			$extern = true;
+			$method = 'PUBLISH';
 			$temp_path = $GLOBALS['phpgw_info']['server']['temp_dir'] . SEP;
 			srand((double)microtime()*1000000);
@@ -1227,7 +1252,8 @@
 			$cal_id = get_var('cal_id',array('GET','POST'),$vcal_id);
 			$event[0] = $this->bo->read_entry($cal_id);
+			
 			include_once('class.bocalendar.inc.php');
 			$cal = new bocalendar;
-			$tmpattach=$cal->create_vcard($event);
+			$tmpattach=$cal->create_vcard($event, $method, $extern);
 			fwrite($attach_fd,$tmpattach);
 			header ("Content-Type: text/plain"); 
@@ -1422,9 +1448,9 @@
 				}
 				// Add participants
-				//$participants = explode(";", $GLOBALS['phpgw']->session->appsession("participants") );
-				//for($_f_part=0; $_f_part<count($participants); $_f_part++)
-				//{
-				//	$this->bo->add_attribute('participants','A',$participants[$_f_part]);
-				//}
+				$participants = explode(";", $GLOBALS['phpgw']->session->appsession("participants") );
+				for($_f_part=0; $_f_part<count($participants); $_f_part++)
+				{
+					$this->bo->add_attribute('participants','A',$participants[$_f_part]);
+				}
 				// Add misc
 				$this->bo->add_attribute('participants','A',$this->bo->owner);
@@ -1487,4 +1513,30 @@
 		}
 
+		
+		
+		function getLdap()
+		{
+			include_once('../phpgwapi/inc/class.common.inc.php');
+			$GLOBALS['phpgw_info']['server'] = $_SESSION['phpgw_info']['expresso']['server'];
+			$common = new common();
+	
+			if ( (!empty($GLOBALS['phpgw_info']['server']['ldap_master_host'])) &&
+				(!empty($GLOBALS['phpgw_info']['server']['ldap_master_root_dn'])) &&
+				(!empty($GLOBALS['phpgw_info']['server']['ldap_master_root_pw'])) )
+				{
+					$ldap = $common->ldapConnect($GLOBALS['phpgw_info']['server']['ldap_master_host'],
+												$GLOBALS['phpgw_info']['server']['ldap_master_root_dn'],
+												$GLOBALS['phpgw_info']['server']['ldap_master_root_pw']);
+				}
+				else
+				{
+					$ldap = $common->ldapConnect();
+				}
+
+			return $ldap;
+		}	
+		
+		
+		
 		function disponibility($params) {
 
@@ -1505,18 +1557,49 @@
 			$str_participants = substr($_GET['participants'],0,strlen($_GET['participants'])-1); //remove the last comma
 			$participants= array();
-
 			$participants_splited = explode(",",$str_participants);
-			foreach($participants_splited as $participant) {
+			
+					
+			$ldap = $this->getLdap();
+			foreach ($participants_splited as $participant)
+            {
 				$participant = substr($participant,0,strlen($participant)-1);
+
+                $entry = array();
+				$extern_contact = false;
+				
+				$justthese = array('accountStatus');
+                $filter="(&(|(phpgwAccountType=u)(phpgwAccountType=l))(uidNumber=".(int)$participant."))";
+                $search = ldap_search($ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
+                $entry = ldap_get_entries($ldap, $search);
+	
+				if($entry[0]['accountstatus'][0] == "false")
+					$extern_contact = true;
+			
+				
 				$acct_type = $GLOBALS['phpgw']->accounts->get_type((int)$participant);
+			
 				if($acct_type=='g') {
 					$bo_groups = CreateObject('expressoAdmin1_2.group');
-					$users = $bo_groups->get_info($participant,true);
+					$users = $bo_groups->get_info($participant);
 					foreach($users['memberuid_info'] as $user) {
-						if($user['type']==u)
+						if($user['type']==u){
+							if (!$user['uidnumber']){
+								continue;
+							}
 							$participants[$user['uidnumber']] = 'U';
 					}
 				}
-				else {
+				}
+				else 
+				{
+					if($extern_contact)
+					{
+						$participants[$participant] = 'I';
+						continue;
+					}
+					
+					if (!$participant)
+						continue;
+						
 					$participants[$participant] = 'U';
 				}
@@ -1665,4 +1748,6 @@
 			";
 
+			$extra_ = "";
+			
 			$str.= "<table border=\'1\' bgcolor=\"#FFFFFF\" width=\"100%\" height=\"100%\"><tr><td>";
 
@@ -1679,5 +1764,11 @@
 			foreach($participants as $part => $nul)
 			{
+				$extra_ = "";
+				
+				if($nul == 'I')
+					$extra_ = "(externalI)";
+				
 				$participants[$part] = $GLOBALS['phpgw']->common->grab_owner_name($part);
+				$participants[$part].= $extra_;
 				// Much better for processor  :)
 				$participants_id[]  .= $part;
@@ -1691,12 +1782,5 @@
 				$GLOBALS['phpgw']->preferences->save_repository();
 			}
-			if($this->bo->prefs['calendar']['interval'] == '42')
-			{
-			    $increment = 30;
-			}
-			elseif($this->bo->prefs['calendar']['interval'] == '84')
-			{
-			    $increment = 15;
-			}
+			$increment = $this->bo->prefs['calendar']['interval'];
 			$interval = (int)(60 / $increment);
 
@@ -1727,4 +1811,12 @@
 			foreach($participants as $part => $fullname)
 			{
+				$external = false;
+				if(strpos($fullname,"(externalI)")) 
+				{
+					$tmp_name = str_replace("(externalI)","",$fullname);
+					$fullname = $tmp_name;
+					$external = true;
+				}
+				
 				$str .= '<tr align="center">'
 					. '<td width="15%" align="left"><font color="'.$this->theme['bg_text'].'" face="'.$this->theme['font'].'" size="-2">'.$fullname.'</font></td>';
@@ -1743,4 +1835,12 @@
 					)
 				);
+
+				if($external) 
+				{
+					$str .= '<td height="1" align="center" colspan="22" bgcolor="'.$this->theme['bg_color'].'" color="#999999">' .lang('Agenda not available') .'</td>';
+					$str .= '</tr>'
+					. '<tr><td height="1" colspan="'.((11 * $interval) + 1).'" bgcolor="#999999"><img src="'.$pix.'"></td></tr>';
+					continue;
+				}
 
 				if(!$this->bo->cached_events[$date['full']])
@@ -1772,4 +1872,5 @@
 									break;
 								case '-':
+									$time_slice[$index]['marker'] = "#";
 									$time_slice[$index]['color'] = $this->theme['bg11'];
 									$link = $this->page('view','&cal_id='.$time_slice[$index]['id'].'&date='.$date['full']);
@@ -1797,91 +1898,47 @@
 		{
 
-			$next = $GLOBALS['phpgw']->datetime->makegmttime(0,0,0,$this->bo->month,$this->bo->day + 1,$this->bo->year);
-			$prev = $GLOBALS['phpgw']->datetime->makegmttime(0,0,0,$this->bo->month,$this->bo->day - 1,$this->bo->year);
-
 			$this->bo->read_holidays();
 
-                        $legend_holiday = $this->bo->cached_holidays[$_GET['date']][0]['name']?'('.$this->bo->cached_holidays[$_GET['date']][0]['name'].')':'';
 			if (!$this->bo->printer_friendly || ($this->bo->printer_friendly && @$this->bo->prefs['calendar']['display_minicals']))
 			{
 				$minical = $this->mini_calendar(
 					Array(
-						'day'		=> 1,
+						'day'	=> $this->bo->day,
 						'month'		=> $this->bo->month,
 						'year'		=> $this->bo->year,
-						'link'		=> 'day',
-						'control'	=> True,
-						'outside_month'	=> False
+						'link'	=> 'day'
 					)
 				);
-				$minical1 = $this->mini_calendar(
-					Array(
-						'day'		=> 1,
-						'month'		=> $this->bo->month+1,
-						'year'		=> $this->bo->year,
-						'link'		=> 'day',
-						'control'	=> False,
-						'outside_month'	=> False
-					)
-				);
-				$minical2 = $this->mini_calendar(
-					Array(
-						'day'		=> 1,
-						'month'		=> $this->bo->month+2,
-						'year'		=> $this->bo->year,
-						'link'		=> 'day',
-						'control'	=> False,
-						'outside_month'	=> False
-					)
-				);
 			}
 			else
 			{
 
-				//NDEE: printer-friendly (what?)
+//NDEE: printer-friendly (what?)
 				$minical = '';
 			}
 
-			if(isset($_GET['date']))
-			{
-			    $dia = substr($_GET['date'],-2);
+			if (!$this->bo->printer_friendly)
+			{
+				$printer = '';
+				$param = '&date='.sprintf("%04d%02d%02d",$this->bo->year,$this->bo->month,$this->bo->day).'&friendly=1';
+			//	$print = '<a href="'.$this->page('day'.$param)."\" TARGET=\"cal_printer_friendly\" onMouseOver=\"window.status = '".lang('Generate printer-friendly version')."'\">[".lang('Printer Friendly').']</a>';
+			
+				//Adiciona modo que o mesmo abra uma nova janela nos navegadores IE e FF
+				$print = "<a href='javascript:void(0)' onClick=\"javascript:window.open('".$this->page('day'.$param).
+						"','','width=600,height=600,toolbar=no,scrollbars=yes,resizable=no');\" onMouseOver=\"window.status = '".
+						lang('Generate printer-friendly version')."'\">[".lang('Printer Friendly').']</a>';
+			
 			}
 			else
 			{
-			    $dia = $_POST['day'];
-			}
-
-			if (!$this->bo->printer_friendly)
-			{
-				$printer = '';
-				$prev_day_link = '<a href="'.$this->page('day','&date='.$prev['full']).'">&lt;&lt;</a>';
-				$next_day_link = '<a href="'.$this->page('day','&date='.$next['full']).'">&gt;&gt;</a>';
-				//$param = '&year='.$this->bo->year.'&month='.$this->bo->month.'&friendly=1'.'&day_ini='.$dia.'&num_dias=1'.'&d=1';
-				//$print = "<a href='javascript:void(0)' onClick=\"javascript:window.open('".$this->page('month'.$param).
-				//		"','','width=600,height=600,toolbar=no,scrollbars=yes,resizable=no');\" onMouseOver=\"window.status = '".
-				//		lang('Generate printer-friendly version')."'\">[".lang('Printer Friendly').']</a>';
-			}
-			else
-			{
-
-				//NDEE: printer-friendly (daily-view)
+
+//NDEE: printer-friendly (daily-view)
 				$GLOBALS['phpgw_info']['flags']['nofooter'] = True;
 				$printer = '<body bgcolor="'.$this->theme['bg_color'].'">';
-				//$print =	'';
-			}
-			$print =  '<a href="javascript:void(0)" id="printFriendly">['.lang('Printer Friendly').']</a>';
-
-			$param = '&year='.$this->bo->year.'&month='.$this->bo->month.'&friendly=1'.'&day_ini='.$dia.'&num_dias=1'.'&d=1';
+				$print =	'';
+			}
 
 			$now	= $GLOBALS['phpgw']->datetime->makegmttime(0, 0, 0, $this->bo->month, $this->bo->day, $this->bo->year);
 			$now['raw'] += $GLOBALS['phpgw']->datetime->tz_offset;
-
-                        $week_days = array(lang('Sunday'),
-								lang('Monday'),
-								lang('Tuesday'),
-								lang('Wednesday'),
-								lang('Thursday'),
-								lang('Friday'),
-								lang('Saturday'));
 
 			$p = $GLOBALS['phpgw']->template;
@@ -1898,5 +1955,5 @@
 				'printer_friendly'	    => $printer,
 				'bg_text'		    => $this->theme['bg_text'],
-				'daily_events'		    => $this->print_day_new(
+				'daily_events'		=> $this->print_day(
 					Array(
 						'year'	    => $this->bo->year,
@@ -1905,16 +1962,12 @@
 					)
 				),
-				'small_calendar'	    => $minical.'<br/>'.$minical1.'<br/>'.$minical2,
-				'date'			    => $this->bo->long_date($now) . $legend_holiday,
-				'day_of_week'		=> $week_days[$now['dow']],
+				'small_calendar'	=> $minical,
+				'date'				=> $this->bo->long_date($now),
 				'username'		    => $GLOBALS['phpgw']->common->grab_owner_name($this->bo->owner),
-				'prev_day_link'		    => $prev_day_link,
-				'next_day_link'		    => $next_day_link,
-				'iprint'		    => $print,
-				'param'			    => $param,
+				'print'				=> $print,
 				'lang_todos'		    => $todo_label,
 				'todos'			    => $this->bo->printer_friendly ? $todos :
 
-					//NDEE: todo's layout
+//NDEE: todo's layout
 					"<div style=\"overflow: auto; max-height: 200px\">\n$todos</div>\n"
 			);
@@ -1922,5 +1975,5 @@
 			$p->set_var($var);
 			$p->parse('day_events','day_event');
-			echo $this->printer_friendly($p->fp('out','day'),lang('Dayview'));
+			print $this->printer_friendly($p->fp('out','day'),lang('Dayview'));
 			$GLOBALS['phpgw']->common->phpgw_footer();
 		}
@@ -2042,5 +2095,5 @@
 						$notify_message = lang('This commitment has already been accepted!');
 				}	
-				else
+				else if($_GET['response'] == 2)
 				{					
 					if(!$duplicated_action)						
@@ -2048,4 +2101,11 @@
 					else
 						$notify_message = lang('This commitment has already been rejected!');
+				}
+                                else if($_GET['response'] == 3)
+				{					
+					if(!$duplicated_action)						
+						$notify_message = lang('The commitment was tentatived successfully!');
+					else
+						$notify_message = lang('This commitment has already been tentatived!');
 				}
 				
@@ -2057,104 +2117,4 @@
 				$tmpbody1 = $body1->pfp('out','list');
 		}
-		
-		function confirm_conflict($user_id,$event,$overlapping_events)
-		{
-			if(!$overlapping_events){					
-				$notify_message = lang('This event conflicts with your other event.');
-	
-				$action_ignore = $GLOBALS['phpgw']->link('/index.php',Array('menuaction'=>'calendar.uicalendar.set_action','cal_id' => $event[id], 'action' => 3, 'response' => 1,'user_id' => $user_id, 'ignore_conflict' => 1));
-				$action_reject = $GLOBALS['phpgw']->link('/index.php',Array('menuaction'=>'calendar.uicalendar.set_action','cal_id' => $event[id], 'action' => 0, 'response' => 0));
-	
-				$body1 = CreateObject('phpgwapi.Template',PHPGW_APP_TPL);
-				$body1->set_file(Array('calendar' => 'conflict.tpl'));
-				$body1->set_block('calendar','list');
-				$var = Array( 'notify_message'	=> $notify_message,
-							'action_url' => $action_url,
-							'ignore_conflict' => 'Ignorar Conflito',
-							'reject_event' => 'Rejeitar Evento',
-							'action_reject' => $action_reject,
-							'action_ignore' => $action_ignore);
-				$body1->set_var($var);
-				$tmpbody1 = $body1->pfp('out','list');
-			}
-			else
-			{				
-				$month = $event['start']['month'];
-				$mday = $event['start']['mday'];
-				$year = $event['start']['year'];
-	
-				$start = mktime($event['start']['hour'],$event['start']['min'],$event['start']['sec'],$month,$mday,$year) - $GLOBALS['phpgw']->datetime->tz_offset;
-				$end = $this->bo->maketime($event['end']) - $GLOBALS['phpgw']->datetime->tz_offset;
-	
-				$overlap = '';
-				for($i=0;$i<count($overlapping_events);$i++)
-				{
-					$overlapped_event = $this->bo->read_entry($overlapping_events[$i],True);
-					foreach($overlapped_event['participants'] as $id => $status)
-					{
-						$conflict = isset($event['participants'][$user_id]);
-						$overlap .= '<li>'.($conflict?'<b>':'').
-							$GLOBALS['phpgw']->common->grab_owner_name($id).
-							($conflict?'</b> - '.lang('Scheduling conflict'):'')."</li>";
-					}
-				 if ($this->bo->prefs['calendar']['hide_event_conflict'])
-					 $overlap .= '<ul><font size="1"><span>'.
-						 $this->normDec($overlapped_event['start']['hour']).":".
-						 $this->normDec($overlapped_event['start']['min'])."-".
-						 $this->normDec($overlapped_event['end']['hour']).":".
-						 $this->normDec($overlapped_event['end']['min']).
-						 '<br><b>'.lang('title').": ".lang("Hidden").
-						 '</b><br>'.lang('description').": ".lang("Hidden").'<br></span></ul><br>';
-				 else
-					 $overlap .= '<ul>'.$this->link_to_entry($overlapped_event,$month,$mday,$year)."</ul><br>";	
-				}
-	
-				unset($GLOBALS['phpgw_info']['flags']['noheader']);
-				unset($GLOBALS['phpgw_info']['flags']['nonavbar']);
-				$GLOBALS['phpgw_info']['flags']['noappheader'] = True;
-				$GLOBALS['phpgw_info']['flags']['noappfooter'] = True;
-				$GLOBALS['phpgw_info']['flags']['app_header'] = $GLOBALS['phpgw_info']['apps']['calendar']['title'].' - '.lang('Scheduling Conflict');
-				$GLOBALS['phpgw']->common->phpgw_header();
-	
-				$p = $GLOBALS['phpgw']->template;
-				$p->set_file(
-					Array(
-						'overlap'	=> 'overlap.tpl',
-	   					'form_button'	=> 'form_button_script.tpl'
-					)
-				);
-	
-				$var = Array(
-					'color'		=> $this->theme['bg_text'],
-					'overlap_title' => lang('Scheduling Conflict'),
-					'overlap_text'	=> lang('Your suggested time of <B> %1 - %2 </B> conflicts with the following existing calendar entries:',$GLOBALS['phpgw']->common->show_date($start),$GLOBALS['phpgw']->common->show_date($end)),
-					'overlap_list'	=> $overlap
-				);
-				$p->set_var($var);
-	
-				$date = sprintf("%04d%02d%02d",$this->bo->year,$this->bo->month,$this->bo->mday);
-				$var = Array(
-					'action_url_button'	=> $GLOBALS['phpgw']->link('/index.php',Array('menuaction'=>'calendar.uicalendar.set_action','cal_id' => $event[id], 'action' => 3, 'user_id' => $user_id, 'ignore_conflict' => 1)),
-					'action_text_button'	=> lang('Ignore Conflict'),
-					'action_confirm_button'	=> '',
-					'action_extra_field'	=> '',
-					'button_id'		=> 'ignore_button'
-				);				
-				$action_reject = $GLOBALS['phpgw']->link('/index.php',Array('menuaction'=>'calendar.uicalendar.set_action','cal_id' => $event[id], 'action' => 0, 'response' => 0));
-	
-				$this->output_template_array($p,'resubmit_button','form_button',$var);
-	
-				$var = Array(
-					'action_url_button'	=> $GLOBALS['phpgw']->link('/index.php',Array('menuaction'=>'calendar.uicalendar.set_action','cal_id' => $event[id], 'action' => 0)),
-					'action_text_button'	=> lang('Reject'),
-					'action_confirm_button'	=> '',
-					'action_extra_field'	=> '',
-					'button_id'		=> 'redit_button'
-				);
-				$this->output_template_array($p,'reedit_button','form_button',$var);
-				$p->pparse('out','overlap');
-			}
-		}
-		
 		function set_action()
 		{
@@ -2165,48 +2125,13 @@
 			}
 			
-			$overlapping_events = false;
-			$event = $this->bo->read_entry((int)$_GET['cal_id']);
-			if((!$_GET['response'] == 0 && !$_GET['ignore_conflict'] == 1) || 
-				(!isset($_GET['response']) && $_GET['action'] == 3 && !$_GET['ignore_conflict'] == 1))
-			{
-				if($event['id'])
-				{
-					$event_ids[] = $event['id'];
-				}
-				if($event['reference'])
-				{
-					$event_ids[] = $event['reference'];
-				}
-				
-				$event['participants'] = Array($_SESSION['phpgw_info']['expressomail']['user']['account_id'] => $event['participants'][$_SESSION['phpgw_info']['expressomail']['user']['account_id']]);
-
-				$overlapping_events = $this->bo->overlap(
-					$this->bo->maketime($event['start']),
-					$this->bo->maketime($event['end']),
-					$event['participants'],
-					$event['owner'],
-					$event_ids
-				);
-			}
+			$confirm_status = $this->bo->set_status((int)$_GET['cal_id'],(int)$_GET['action'],(int)$_GET['user']);
 
 			if(isset($_GET['response']))
 			{
-				if($overlapping_events)
-				{
-					$this->confirm_conflict($_GET['user_id'],$event);
-				}else
-				{
-					$confirm_status = $this->bo->set_status((int)$_GET['cal_id'],(int)$_GET['action']);
 					$this->confirm_action($confirm_status);
 					$GLOBALS['phpgw']->common->phpgw_exit(False);
 				}
-			}else
-			{
-				if($overlapping_events)
-				{					
-					$this->confirm_conflict($_GET['user_id'],$event,$overlapping_events);
-				}else
-				{
-				$confirm_status = $this->bo->set_status((int)$_GET['cal_id'],(int)$_GET['action']);
+			else
+				{
 					if ($this->bo->return_to)
 					{
@@ -2219,6 +2144,4 @@
 					$GLOBALS['phpgw']->common->phpgw_exit();
 				}
-			}
-			
 			
 		}
@@ -2293,4 +2216,5 @@
 				if ($this->always_app_header) $GLOBALS['phpgw_info']['flags']['app_header'] = $GLOBALS['phpgw_info']['apps']['calendar']['title'].' - '.lang('Group Planner');
 				$GLOBALS['phpgw']->common->phpgw_header();
+				$this->header();
 			}
 
@@ -2564,8 +2488,8 @@
 			if (!$is_private)
 			{
-				$opt .= ' title="'.lang('Title').": ".$event['title'];
+				$opt .= ' title="'.lang('Title').": ".$event['title']."&nbsp| ";
 				if ($event['description'])
 				{
-					$opt .= "\n".lang('Description').": ".$event['description'];
+					$opt .= "\n".lang('Description').": ".$event['description']."&nbsp| ";
 				}
 			}
@@ -2577,5 +2501,5 @@
 			$start = $GLOBALS['phpgw']->common->show_date($this->bo->maketime($event['start']) - $GLOBALS['phpgw']->datetime->tz_offset);
 			$end = $GLOBALS['phpgw']->common->show_date($this->bo->maketime($event['end']) - $GLOBALS['phpgw']->datetime->tz_offset);
-			$opt .= "\n".lang('Start Date/Time').": ".$start."\n".lang('End Date/Time').": ".$end;
+			$opt .= "\n".lang('Start Date/Time').": ".$start."&nbsp| ".lang('End Date/Time').": ".$end."&nbsp| ";
 
 			if ($event['location'] && !$is_private)
@@ -3053,5 +2977,13 @@
 					}
 				}
-				$GLOBALS['phpgw']->redirect_link('/index.php',$vars);
+
+				unset($GLOBALS['phpgw_info']['flags']['noheader']);
+				unset($GLOBALS['phpgw_info']['flags']['nonavbar']);
+				$GLOBALS['phpgw_info']['flags']['app_header'] = $GLOBALS['phpgw_info']['apps']['calendar']['title'].' - '.lang('Search Results');
+				$GLOBALS['phpgw']->common->phpgw_header();
+
+				echo '<b>'.lang('Error').':</b>'.lang('no matches found');
+				return;
+				//$GLOBALS['phpgw']->redirect_link('/index.php',$vars);
 			}
 
@@ -3252,5 +3184,4 @@
 					'footer'	=> 'footer.tpl',
 					'form_button'	=> 'form_button_script.tpl'
-                                        //'new_component'	=> 'new_component.tpl'
 				)
 			);
@@ -3294,5 +3225,5 @@
 				$str_ini .= '<option value="'.$i.'"'.($i == $day?' selected':'').'>'.$i.'</option>'."\n";
 			}
-			$str_qtd = '<option value="'.''.'"'.(!$_POST['qtd_dias']?' selected':'').'>'.''.'</option>'."\n";
+			$str_qtd = '<option value="'.''.'"'.($i == $_POST['qtd_dias']?' selected':'').'>'.''.'</option>'."\n";
 			for ($i = 1; $i <= 45; $i++)
 			{
@@ -3301,12 +3232,5 @@
 			$display = '';
 			$display_view = '';
-//                        if ($menuaction == 'calendar.uicalendar.month')
-//			{
-//                            $accounts = CreateObject('phpgwapi.accounts');
-//                            $accountId = $accounts->name2id($account_name);
-//                            $prefs = CreateObject('phpgwapi.preferences', $accountId);
-//                            $account_prefs = $prefs->read();
-//                        }
-			if ( ($menuaction == 'calendar.uicalendar.week') || ($menuaction == 'calendar.uicalendar.day') || ($menuaction == 'calendar.uicalendar.year') || ($menuaction == 'calendar.uicalendar.planner'))
+			if ( ($menuaction == 'calendar.uicalendar.week') || ($menuaction == 'calendar.uicalendar.day') )
 			{
 				$display = 'none';
@@ -3321,9 +3245,9 @@
 				'formname'		=> 'SelectDay',
 				'formonchange'		=> 'document.SelectDay.submit()',
-				'day_ini_label'		=> lang('print start day'),
+				'day_ini_label'		=> lang('print starting in'),
 				'num_dias_label'	=> lang('quantity of days'),
-				'tip'			=> lang('empty prints from the start day chosen to the end of the current month'),
-//				'day_ini_name'		=> 'day',
-//				'num_dias_name'		=> 'qtd_dias',
+				'tip'			=> lang('empty prints from the day chosen below to the end of the current month'),
+				'day_ini_name'		=> 'day',
+				'num_dias_name'		=> 'qtd_dias',
 				'row_ini'		=> $str_ini,
 				'row_qtd'		=> $str_qtd,
@@ -3360,5 +3284,5 @@
 				'form_onchange'	=> 'document.SelectMonth.submit()',
 				'row'		=> $str,
-//				'dia_ini'	=> $dia_ini,
+				'dia_ini'	=> $dia_ini,
 				'go'		=> lang('Go!')
 			);
@@ -3464,6 +3388,6 @@
 			$this->output_template_array($p,'b_row2','form_button',$var);
 
-			//$p->set_var('place_component','');
 			$p->parse('table_row','blank_row',True);
+
 			$p->pparse('out','footer_table');
 			unset($p);
@@ -3522,4 +3446,8 @@
 			$viewable = !$this->bo->printer_friendly && $this->bo->check_perms(PHPGW_ACL_READ,$event);
 
+			if(!$viewable && $event['type'] == 'E' && !$event['public']){
+				return "";
+			} 
+			
 			$starttime = $this->bo->maketime($event['start']) - $GLOBALS['phpgw']->datetime->tz_offset;
 			$endtime = $this->bo->maketime($event['end']) - $GLOBALS['phpgw']->datetime->tz_offset;
@@ -3546,12 +3474,13 @@
 				}
 
-				if($endtime >= ($rawdate_offset + 86400))
-				{
-					$end_time = $GLOBALS['phpgw']->common->show_date(mktime(23,59,59,$month,$day,$year) - $GLOBALS['phpgw']->datetime->tz_offset,$this->bo->users_timeformat);
-				}
-				else
-				{
+                              
+//				if($endtime >= ($rawdate_offset + 86400 ))
+//				{
+//                                    $end_time = $GLOBALS['phpgw']->common->show_date(mktime(23,59,59,$month,$day,$year) - $GLOBALS['phpgw']->datetime->tz_offset,$this->bo->users_timeformat);
+//				}
+//				else
+//				{
 					$end_time = $GLOBALS['phpgw']->common->show_date($endtime,$this->bo->users_timeformat);
-				}
+//				}
 				$time = $start_time.'-'.$end_time;
 			}
@@ -3582,29 +3511,7 @@
 			$texttime=$time;
 			$texttitle=$this->bo->get_short_field($event,$is_private,'title');
-
-			$account_name = $_POST['user'] ?
-							$_POST['user'] :
-							($_GET['account_name'] ?
-							 $_GET['account_name'] : '');
-
-			$accounts = CreateObject('phpgwapi.accounts');
-			$accountId = $accounts->name2id($account_name);
-
-			$prefs = CreateObject('phpgwapi.preferences', $accountId);
-			$account_prefs = $prefs->read();
-
-			$titleView = $account_prefs['calendar']['title_view'];
-			if($titleView == "1")
-			{
-			    $textdesc = '';
-			}
-			else
-			{
-			    $textdesc = (!$is_private && $event['description'] ? $this->bo->get_short_field($event,$is_private,'description'):'');
-			    $textdesc=nl2br($textdesc);
-			}
-
+			$textdesc=(!$is_private && $event['description'] ? $this->bo->get_short_field($event,$is_private,'description'):'');
 			// added $textlocation but this must be activated in the actual pict_link.tpl file of the used template set
-			$textlocation= $event['location']?"<br/><b>Local:</b> ".$this->bo->get_short_field($event,$is_private,'location'):'';
+			$textlocation=$this->bo->get_short_field($event,$is_private,'location');
 
 			if ($viewable)
@@ -3658,5 +3565,5 @@
 			}
 			else
-			{if ($texttitle)
+			{
 				$picture[] = Array(
 					'pict'	=>  $GLOBALS['phpgw']->common->image('calendar','single'),
@@ -3690,14 +3597,4 @@
 				}
 			}
-
-                        if($event['attachment'] != '')
-				{
-					$picture[] = Array(
-						'pict'	=> $GLOBALS['phpgw']->common->image('calendar','clip'),
-						'width'	=> 9,
-						'height'=> 9,
-						'title' => lang('Notification with attachments sent.')
-					);
-				}
 
 			$description = $this->bo->get_short_field($event,$is_private,'description');
@@ -3712,5 +3609,5 @@
 				$this->output_template_array($this->link_tpl,'picture','pict',$var);
 			}
-			if ($event['type'] == 'H' || $texttitle)
+			if ($texttitle)
 			{
 				$var = Array(
@@ -3720,5 +3617,5 @@
 					'users_status'=>$textstatus,
 					'desc'=> $textdesc,
-					'location'=> $textlocation
+					'location'=> "<br><b>Local:</b> ".$textlocation
 				);
 				$this->output_template_array($this->link_tpl,'picture','link_text',$var);
@@ -3785,8 +3682,12 @@
 			}
 			
-			$textTitlePrint = $textTimePrint = $textDescPrint = $textLocationPrint = $textObservationsPrint = $textstatus = '';
+			$texttitle = $texttime = $textdesc = $textlocation = $textstatus = '';
+
+			
 
 			if(!$is_private)
 			{
+				//$text .= $this->bo->display_status($event['users_status']);
+				
 				// split text for better display by templates, also see $texttime $texttitle $textdesc $textlocation	
 				$textstatus=$this->bo->display_status($event['users_status']); 
@@ -3794,36 +3695,11 @@
 			}
 
-			$account_name = $_POST['user'] ?
-							$_POST['user'] :
-							($_GET['account_name'] ?
-							 $_GET['account_name'] : '');
-			
-			$accounts = CreateObject('phpgwapi.accounts');
-			$accountId = $accounts->name2id($account_name);
-
-			$prefs = CreateObject('phpgwapi.preferences', $accountId);
-			$account_prefs = $prefs->read();
-
-
-			$textTimePrint = $time;
-			$textTitlePrint = $is_private ? lang('Private event. You are not allowed to print it.') : ( $event['type'] == 'H' ? 'Apontamento de horas' : $this->bo->get_short_field($event,$is_private,'title' ) );
-
-			$fieldsToPrint = $account_prefs['calendar']['fields_to_print'];
-			if($fieldsToPrint == "0")
-			{
-			    $textDescPrint = '';
-			}
-			elseif($fieldsToPrint == "1")
-			{
-			    $textDescPrint = (!$is_private && $event['description'] ? $this->bo->get_short_field($event,$is_private,'description'):'');
-			}
-			else
-			{
-			    $textDescPrint = (!$is_private && $event['description'] ? $this->bo->get_short_field($event,$is_private,'description'):'');
-			    $textObservationsPrint = $event['observations']?"<br /><b>Observações:</b> ".$this->bo->get_short_field($event,$is_private,'observations'):'';
-			}
-
+			$text = '<nobr>&nbsp;'.$time.'&nbsp;</nobr> '.$this->bo->get_short_field($event,$is_private,'title').$text.
+
+			$texttime=$time;
+			$texttitle=$this->bo->get_short_field($event,$is_private,'title');
+			$textdesc=(!$is_private && $event['description'] ? $this->bo->get_short_field($event,$is_private,'description'):'');
 			// added $textlocation but this must be activated in the actual pict_link.tpl file of the used template set
-			$textLocationPrint = $event['location']?"<br /><b>Local:</b> ".$this->bo->get_short_field($event,$is_private,'location'):'';
+			$textlocation=$this->bo->get_short_field($event,$is_private,'location');
 
 			if ($viewable)
@@ -3832,10 +3708,8 @@
 				$this->event_tpl->set_var('link_link',$this->page('view','&cal_id='.$event['id'].'&date='.$date));
 				$this->event_tpl->set_var('lang_view',lang('View this entry'));
-				$this->event_tpl->set_var('desc', $textDescPrint);
-				$this->event_tpl->set_var('location', $textLocationPrint);
-				$this->event_tpl->set_var('observations', $textObservationsPrint);
+				$this->event_tpl->set_var('desc', $textdesc);
+				$this->event_tpl->set_var('location', $textlocation);
 				$this->event_tpl->parse('picture','link_event_open',True);
 			}
-
 			if (!$is_private)
 			{
@@ -3925,15 +3799,13 @@
 				$this->output_template_array($this->event_tpl,'picture','event_pict',$var);
 			}
-
-			if ($textTitlePrint)
+			if ($texttitle)
 			{
 				$var = Array(
 			//		'text' => $text,
-					'time'=> $textTimePrint,
-					'title'=> $textTitlePrint,
+					'time'=> $texttime,
+					'title'=> $texttitle,
 					'users_status'=>$textstatus,
-					'desc'=> $textDescPrint,
-					'location'=> $textLocationPrint,
-					'observations'=> $textObservationsPrint
+					'desc'=> $textdesc,
+					'location'=> "<br><b>Local:</b> ".$textlocation
 				);
 				$this->output_template_array($this->event_tpl,'picture','link_event_text',$var);
@@ -3967,5 +3839,15 @@
 			{
 				$overlapping_events = $params['o_events'];
+
+                                if( is_string( $overlapping_events ))
+                                    $overlapping_events = explode( ';', $overlapping_events );
+
 				$event = $params['this_event'];
+
+                                if( is_string( $event ) )
+                                    $event = $this->bo->read_entry( $event );
+
+                                if( !$event )
+                                    $event = $this->bo->restore_from_appsession();
 			}
 
@@ -3986,5 +3868,5 @@
 					$overlap .= '<li>'.($conflict?'<b>':'').
 						$GLOBALS['phpgw']->common->grab_owner_name($id).
-						($conflict?'</b> - '.lang('Scheduling conflict'):'')."</li>";
+						($conflict?'</b> - '.lang('Scheduling conflict'):'').'</li>';
 				}
 			 if ($this->bo->prefs['calendar']['hide_event_conflict'])
@@ -3997,5 +3879,5 @@
 					 '</b><br>'.lang('description').": ".lang("Hidden").'<br></span></ul><br>';
 			 else
-				 $overlap .= '<ul>'.$this->link_to_entry($overlapped_event,$month,$mday,$year)."</ul><br>";	
+				 $overlap .= '<ul>'.$this->link_to_entry($overlapped_event,$month,$mday,$year).'"</ul><br>';                  
 			}
 
@@ -4007,4 +3889,8 @@
 			$GLOBALS['phpgw']->common->phpgw_header();
 
+			$porig = $GLOBALS['phpgw']->template;
+
+			$GLOBALS['phpgw']->template->root = $_SESSION['rootPath'].'/calendar/templates/'.$GLOBALS['phpgw_info']['server']['template_set'].'/';
+
 			$p = $GLOBALS['phpgw']->template;
 			$p->set_file(
@@ -4024,4 +3910,14 @@
 
 			$date = sprintf("%04d%02d%02d",$this->bo->year,$this->bo->month,$this->bo->mday);
+
+                        $var = Array(
+				'action_url_button'	=> $GLOBALS['phpgw']->link('/index.php',array('menuaction' => 'calendar.uicalendar.index')),
+				'action_text_button'	=> lang('Cancel'),
+				'action_confirm_button'	=> '',
+				'action_extra_field'	=> '',
+				'button_id'		=> 'cancel_button'
+			);
+			$this->output_template_array($p,'cancel_button','form_button',$var);
+
 			$var = Array(
 				'action_url_button'	=> $GLOBALS['phpgw']->link('/index.php',Array('menuaction'=>'calendar.bocalendar.update','readsess'=>1)),
@@ -4033,4 +3929,20 @@
 			$this->output_template_array($p,'resubmit_button','form_button',$var);
 
+                        if( $event['owner'] == -2 || $event['id'] != 0 )
+                        {
+                            $p->set_var( 'suggestion', $this->build_suggestion( $event , $params['this_account']) );
+
+                            $var = Array(
+                                'action_url_button'	=> '',
+                                'action_text_button'	=> lang('Suggest new hour'),
+                                'action_confirm_button'	=> 'onsubmit="javascript: return false;" onclick="javascript: return show_suggestion();"',
+                                'action_extra_field'	=> '',
+                                'button_id'		=> 'redit_button'
+                            );
+                        }
+                        else
+                        {
+                            $p->set_var( 'suggestion', '' );
+
 			$var = Array(
 				'action_url_button'	=> $GLOBALS['phpgw']->link('/index.php',Array('menuaction'=>'calendar.uicalendar.edit','readsess'=>1,'date'=>$date)),
@@ -4040,6 +3952,8 @@
 				'button_id'		=> 'redit_button'
 			);
+                        }
 			$this->output_template_array($p,'reedit_button','form_button',$var);
 			$p->pparse('out','overlap');
+                        //return 'OLA';
 		}
 
@@ -4357,5 +4271,8 @@
 				$month = (int)substr($date,4,2);
 				$day   = (int)substr($date,6,2);
-
+				$var   = Array(
+					'column_data' => '',
+					'extra' => ''
+				);
 				$p->set_var($var);
 				if ($weekly || ($date >= $monthstart && $date <= $monthend))
@@ -4366,10 +4283,10 @@
 					$id_aux = mktime(0,0,0,$month,$day,$year);
 					$month_identifier = substr(lang(strftime("%B",$id_aux)),0,3);
-					$day_number = $dia_semana . ",  " . $day_num;
+					$day_number = $month_identifier . " - " . $dia_semana . ",  " . $day_num;
 
 					$var = Array(
 						'extra'		=> $day_params['extra'],
 						'new_event_link'=> $new_event_link,
-						'day_number'	=> (isset($_GET['num_dias']) && ($_GET['num_dias'] > 1 || $_GET['num_dias'] == "")?$day_number:'')
+						'day_number'	=> $day_number
 					);
 
@@ -4383,137 +4300,8 @@
 						);
 						$p->set_var($var);
-						$eventsCached = $this->bo->cached_events[$date];
-
-						if($_GET['d'] == '1')
-						{
-
-						    for($i_events = 0; $i_events < count($eventsCached) ; $i_events++)
+						$events = $this->bo->cached_events[$date];
+						foreach($events as $event)
 							{
-							if ($eventsCached[$i_events]['users_status'] == 'R')
-							{
-								continue;	// user does not want to see rejected events
-							}
-							$events[] = $eventsCached[$i_events];
-						    }
-						    /*echo "<pre>";
-							print_r($events1);
-
-						    echo "</pre>";
-						    exit();*/
-
-						    $newEvents = Array();
-						    $eventAux = Array
-								(
-								    'owner' => '',
-								    'id' => '',
-								    'type' => '',
-								    'public' => '',
-								    'category' => '',
-								    'title' => '',
-								    'description' => '',
-								    'alter_by' => '',
-								    'observations' => '',
-								    'attachment' => '',
-								    'ex_participants' => '',
-								    'uid' => '',
-								    'location' => '',
-								    'reference' => '',
-								    'start' => Array
-									(
-									    'year' => '',
-									    'month' => '',
-									    'mday' => '',
-									    'hour' => '',
-									    'min' => '',
-									    'sec' => '',
-									    'alarm' => '',
-									),
-
-								    'modtime' => Array
-									(
-									),
-
-								    'end' => Array
-									(
-									    'year' => '',
-									    'month' => '',
-									    'mday' => '',
-									    'hour' => '',
-									    'min' => '',
-									    'sec' => '',
-									    'alarm' => '',
-									),
-
-								    'priority' => '',
-								    'users_status' => '',
-								    'participants' => Array
-									(
-									),
-
-								    'alarm' => Array
-									(
-									),
-
-								);
-
-						    $delta = 60; //em segundos
-						    for($i_events = 0; $i_events < count($events) ; $i_events++)
-						    {
-
-							$newEvents[] = $events[$i_events];
-
-							$hf_current = mktime($events[$i_events]['end']['hour'], 0, 0, $month, $day, $year);
-							$hi_prox = mktime($events[$i_events+1]['start']['hour'], 0, 0, $month, $day, $year);
-
-							if($events[$i_events]['end']['min'] > 0)
-							{
-							    $hf_current += 60*$delta;
-							}
-
-							while($hi_prox > $hf_current)
-							{
-
-							    $aux1 = date('Y:m:d:H:i:s',$hf_current);
-							    $aux2 = explode(':',$aux1);
-							    $eventAux['start']['year'] = $aux2[0];
-							    $eventAux['start']['month'] = $aux2[1];
-							    $eventAux['start']['mday'] = $aux2[2];
-							    $eventAux['start']['hour'] = $aux2[3];
-							    $eventAux['start']['min'] = $aux2[4];
-							    $eventAux['start']['sec'] = $aux2[5];
-
-							    //$aux3 = date('Y:m:d:H:i:s',$hf_current);
-							    //$aux4 = explode(':',$aux3);
-							    $eventAux['end']['year'] = $aux2[0];
-							    $eventAux['end']['month'] = $aux2[1];
-							    $eventAux['end']['mday'] = $aux2[2];
-							    $eventAux['end']['hour'] = $aux2[3];
-							    $eventAux['end']['min'] = $aux2[4];
-							    $eventAux['end']['sec'] = $aux2[5];
-
-							    $eventAux['owner'] = $GLOBALS['phpgw_info']['user']['account_id'];
-							    $eventAux['title'] = "\n\n\n";
-							    $eventAux['description'] = '';
-							    $eventAux['observations'] = '';
-							    $eventAux['location'] = '';
-
-							    $newEvents[] = $eventAux;
-							    $hf_current += 60*$delta;
-
-							}
-						    }
-
-						    foreach($newEvents as $event)
-						    {
-							$p->set_var('day_events',$this->link_to_month_entry($event,$month,$day,$year));
-							$p->parse('events','event',True);
-							$p->set_var('day_events','');
-						}
-					}
-						else
-						{
-						    foreach($eventsCached as $event)
-						    {
-							if ($this->bo->rejected_no_show($event) || $event['users_status'] == 'R')
+							if ($this->bo->rejected_no_show($event))
 							{
 								continue;	// user does not want to see rejected events
@@ -4522,12 +4310,5 @@
 							$p->parse('events','event',True);
 							$p->set_var('day_events','');
-						    }
 						}
-
-						/*echo "<pre>";
-						    print_r($newEvents);
-
-						echo "</pre>";
-						exit();*/
 					}
 					$p->parse('daily_events','day_event',True);
@@ -4552,4 +4333,12 @@
 			}
 
+/*			$this->bo->store_to_cache(
+				Array(
+					'syear'	=> $year,
+					'smonth'=> $month,
+					'sday'	=> 1
+				)
+			);
+*/
 			$day_ini = $_GET['day_ini'];// dia do inicio da impressao; o padrao e o dia atual;
 			$num_dias = $_GET['num_dias'];// quantidade de dias a partir do dia inicial;
@@ -4558,5 +4347,5 @@
 //			$monthend   = (int)(date('Ymd',mktime(0,0,0,$month + 1,0,$year)));
 
-			if($num_dias != '')
+			if($num_dias != 0)
 			{
 				//se a qtde de dias for informada, a data final para impressao considera a soma $day_ini+$num_dias;
@@ -4609,7 +4398,8 @@
 
 			$var = Array(
-				'cols'      => 1
-				//'day_events'=> ''
-			);
+				'cols'      => 1,
+				'day_events'=> '' //$this->month_week_header($month,$year,False)
+			);
+//			$this->output_template_array($p,'row','event',$var);
 
 			$cellcolor = $this->theme['row_on'];
@@ -4629,11 +4419,6 @@
 /***************************************************************************************/
 
-		function display_month($params) //($month,$year,$showyear,$owner=0)
-		{
-			$month = $params['month'];
-			$year = $params['year'];
-			$showyear = $params['showyear'];
-			$owner = $params['owner'];
-
+		function display_month($month,$year,$showyear,$owner=0)
+		{
 			if($this->debug)
 			{
@@ -4678,10 +4463,4 @@
 
 			$cellcolor = $this->theme['row_on'];
-
-			$result_events_json = $this->print_events_to_show_json($params);
-			$p->set_var('date','Date(2011,1,1)');
-			$p->set_var('hora_final',$result_events_json['hora_final']);
-			$p->set_var('events_json',json_encode($result_events_json['events_to_show_json'])?json_encode($result_events_json['events_to_show_json']):'null');
-
 
 			for($i = (int)($start + $GLOBALS['phpgw']->datetime->tz_offset);(int)(date('Ymd',$i)) <= $monthend;$i += 604800)
@@ -4789,11 +4568,16 @@
 			$p->set_block('view','hr','hr');
 
+                        include_once($_SESSION['rootPath'].'/calendar/inc/class.ex_participants.inc.php');
+                        $langp = array();
+                        $langp['ACCEPTED'] = lang('Accepted');
+                        $langp['DECLINED'] = lang('Declined');
+                        $langp['TENTATIVE'] = lang('Tentative');
+                        $langp['DELEGATED'] = lang('Delegated');
+                        $langp['NO ANSWER'] = lang('No answer');
+                        $exParticipants = new exParticipants($langp);
+                        $exParticipants->setParticipantsBySerializable($event['ex_participants']);
+                        $event['ex_participants'] = $exParticipants->getParticipantsView();
+
 			$vars = $this->bo->event2array($event);
-
-                        if($vars['attachment']['data'] == "")
-                            $vars['attachment']['data'] = lang('No Attachment');
-                        else{
-                            $vars['attachment']['data'] = lang('Has attachment(s)');
-                        }
                         
 			$vars['title']['tr_color'] = $this->theme['th_bg'];
@@ -4804,6 +4588,4 @@
 				{
 					$vars['participants']['data'][$user] = $parts[1].' (<a href="'.$this->page('edit_status','&cal_id='.$event['id'].'&owner='.$user).'">'.$parts[2].'</a>)';
-					$vars['participants']['data'][$user].='&nbsp;(<a href=\'index.php?menuaction=calendar.uicalendar.screen_delegate_event&id_event='.$event['id'].'&delegator='.$user.'&date='.$_REQUEST["date"].'&eventArray='.$event.'\'>'.lang("Delegate event").'</a>)';
-//system('echo "event: '.$event['start'].'" >>/tmp/controle');
 				}
 			}
@@ -5051,508 +4833,4 @@
 			return $p->fp('out','day');
 		}	// end function
-
-                //função para exibição do calendário novo.
-
-                function print_day_new($params){
-                        $this->bo->store_to_cache(
-			Array(
-					'syear'  => $params['year'],
-					'smonth' => $params['month'],
-					'sday'   => $params['day'],
-					'eyear'  => $params['year'],
-					'emonth' => $params['month'],
-					'eday'   => $params['day']
-				)
-			);
-
-			$p = CreateObject('phpgwapi.Template',$this->template_dir);
-			$p->set_unknowns('keep');
-
-			$tpl = 'day_cal.tpl';
-			//$new_component_tpl = 'new_component.tpl';
-
-			if((int)($GLOBALS['phpgw_info']['user']['preferences']['calendar']['mainscreen_showevents'])==2 &&
-				$GLOBALS['phpgw_info']['flags']['currentapp'] == 'home')
-			{
-				$tpl = 'day_list.tpl';
-			}
-
-			$templates = Array(
-				'day_cal'   => $tpl
-				//'new_component_tpl' => $new_component_tpl
-			);
-
-			$templateSet = $GLOBALS['phpgw_info']['server']['template_set'];
-
-			if(isset($_GET['date']))
-			{
-			    $dia = substr($_GET['date'],-2);
-			}
-			elseif(isset($_POST['day']))
-			{
-			    $dia = $_POST['day'];
-			}
-			else
-			{
-			    $dia = $params['day'];
-			}
-			
-			$print =  '<a href="javascript:void(0)" id="printFriendly">['.lang('Printer Friendly').']</a>';
-			$param = '&year='.$this->bo->year.'&month='.$this->bo->month.'&friendly=1'.'&day_ini='.$dia.'&num_dias=1'.'&d=1';
-
-			$p->set_file($templates);
-			$p->set_block('day_cal','day','day');
-			//$p->set_block('new_component_tpl','new_component','new_component');
-			$params['period'] = 1;
-                    	$result_events_json = $this->print_events_to_show_json($params);
-			$p->set_var('date',$result_events_json['date_events_json']);
-			$p->set_var('templateSet',$templateSet);
-			$p->set_var('iprint',$print);
-			$p->set_var('param',$param);
-			$p->set_var('hora_final',$result_events_json['hora_final']);
-			$p->set_var('hora_inicial',$result_events_json['hora_inicial']);
-			$p->set_var('hour_size_px',$result_events_json['hour_size_px']);
-
-			$p->set_var('events_json',json_encode($result_events_json['events_to_show_json'])?json_encode($result_events_json['events_to_show_json']):'null');
-                        return $p->fp('out','day');
-                }
-
-		function print_week_new($params){
-
-		    $p = CreateObject('phpgwapi.Template',$this->template_dir);
-		    $p->set_unknowns('keep');
-
-		    $tpl = 'new_week.tpl';
-
-		    if((int)($GLOBALS['phpgw_info']['user']['preferences']['calendar']['mainscreen_showevents'])==2 &&
-		    $GLOBALS['phpgw_info']['flags']['currentapp'] == 'home')
-		    {
-			$tpl = 'day_list.tpl';
-		    }
-
-		    $minical_prev = $this->mini_calendar(
-			Array(
-			    'day'		=> 1,
-			    'month'		=> $this->bo->month,
-			    'year'		=> $this->bo->year,
-			    'link'		=> 'week',
-			    'control'		=> False,
-			    'outside_month'	=> False
-			    )
-		    );
-
-		    $minical_next1 = $this->mini_calendar(
-			Array(
-			    'day'		=> 1,
-			    'month'		=> $this->bo->month+2,
-			    'year'		=> $this->bo->year,
-			    'link'		=> 'week',
-			    'control'		=> False,
-			    'outside_month'	=> False
-			)
-		    );
-
-		    $minical_next = $this->mini_calendar(
-			Array(
-			    'day'		=> 1,
-			    'month'		=> $this->bo->month+1,
-			    'year'		=> $this->bo->year,
-			    'link'		=> 'week',
-			    'control'		=> False,
-			    'outside_month'	=> False
-			)
-		    );
-                    $this->bo->read_holidays($params['year']);
-		    $next = $GLOBALS['phpgw']->datetime->makegmttime(0,0,0,$this->bo->month,$this->bo->day + 7,$this->bo->year);
-		    $prev = $GLOBALS['phpgw']->datetime->makegmttime(0,0,0,$this->bo->month,$this->bo->day - 7,$this->bo->year);
-		    $prev_week_link = '<a href="'.$this->page('week','&date='.$prev['full']).'">&lt;&lt;</a>';
-		    $next_week_link = '<a href="'.$this->page('week','&date='.$next['full']).'">&gt;&gt;</a>';
-
-		    $daily = $this->set_week_array($GLOBALS['phpgw']->datetime->get_weekday_start($params['year'],$params['month'],$params['day']),$this->theme['row_on'],True);
-		    foreach($daily as $key => $value)
-		    {
-			$dates[] = $key;
-		    }
-
-		    $day_ini = (int)substr($dates[0],6,2);
-
-		    $print =  '<a href="javascript:void(0)" id="printFriendly">['.lang('Printer Friendly').']</a>';
-
-		    $param = '&year='.$this->bo->year.'&month='.$this->bo->month.'&friendly=1'.'&day_ini='.$day_ini.'&num_dias=7';
-
-		    $m = mktime(0,0,0,$this->bo->month,1,$this->bo->year);
-
-		    $templates = Array(
-			'new_week'   => $tpl,
-		    );
-                    $feriados_do_ano = Array();
-                    foreach ($this->bo->cached_holidays as $key => $value)
-                        {
-                            $feriados_do_ano[$key] = utf8_encode($this->bo->cached_holidays[$key][0]['name']);
-                        }
-		    $p->set_file($templates);
-		    $p->set_block('new_week','day','day');
-		    $params['period'] = 2;
-		    $result_events_json = $this->print_events_to_show_json($params);
-		    $p->set_var('date',$result_events_json['date_events_json']);
-		    $p->set_var('hora_final',$result_events_json['hora_final']);
-		    $p->set_var('hora_inicial',$result_events_json['hora_inicial']);
-		    $p->set_var('minical',$minical_prev.'<br>'.$minical_next.'<br>'.$minical_next1);
-		    $p->set_var('iprint',$print);
-		    $p->set_var('param',$param);
-		    $p->set_var('title',$prev_week_link.'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;::'.$this->bo->get_week_label().'::&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.$next_week_link);
-                    $p->set_var('user',$GLOBALS['phpgw']->common->grab_owner_name($this->bo->owner));
-		    $p->set_var('events_json',json_encode($result_events_json['events_to_show_json'])?json_encode($result_events_json['events_to_show_json']):'null');
-                    $p->set_var('holidays_json',json_encode($feriados_do_ano)?json_encode($feriados_do_ano):null);
-		    return $p->fp('out','day');
-
-                }
-
-                function print_month_new($params){
-
-			$p = CreateObject('phpgwapi.Template',$this->template_dir);
-			$p->set_unknowns('keep');
-			$tpl = 'new_month.tpl';
-
-			if((int)($GLOBALS['phpgw_info']['user']['preferences']['calendar']['mainscreen_showevents'])==2 &&
-				$GLOBALS['phpgw_info']['flags']['currentapp'] == 'home')
-			{
-				$tpl = 'day_list.tpl';
-			}
-
-
-
-			$templates = Array(
-				'new_month'   => $tpl,
-			);
-
-                        $minical_prev = $this->mini_calendar(
-					Array(
-						'day'		=> 1,
-						'month'		=> $this->bo->month -1,
-						'year'		=> $this->bo->year,
-						'link'		=> 'day',
-						'control'	=> False,
-						'outside_month'	=> False
-					)
-				);
-
-                        $minical_next1 = $this->mini_calendar(
-					Array(
-						'day'		=> 1,
-						'month'		=> $this->bo->month + 2,
-						'year'		=> $this->bo->year,
-						'link'		=> 'day',
-						'control'	=> False,
-						'outside_month'	=> False
-					)
-				);
-
-			$minical_next = $this->mini_calendar(
-					Array(
-						'day'		=> 1,
-						'month'		=> $this->bo->month + 1,
-						'year'		=> $this->bo->year,
-						'link'		=> 'day',
-						'control'	=> False,
-						'outside_month'	=> False
-					)
-				);
-                        $this->bo->read_holidays($params['year']);
-			$print =  '<a href="javascript:void(0)" id="printFriendly">['.lang('Printer Friendly').']</a>';
-
-			$param = '&year='.$this->bo->year.'&month='.$this->bo->month.'&friendly=1';
-
-                        $next = $this->bo->month + 1;
-			$prev = $this->bo->month - 1;
-			$nextyear = $this->bo->year;
-			$prevyear = $this->bo->year;
-			if ($this->bo->month == 12)
-			{
-				$next = 1;
-				$nextyear = $nextyear + 1;
-			}
-			elseif ($this->bo->month == 1)
-			{
-				$prev = 12;
-				$prevyear = $prevyear - 1;
-			}
-
-                        $feriados_do_ano = Array();
-                        foreach ($this->bo->cached_holidays as $key => $value)
-                        {
-                            $feriados_do_ano[$key] = utf8_encode($this->bo->cached_holidays[$key][0]['name']);
-                        }
-                        $m = mktime(0,0,0,$this->bo->month,1,$this->bo->year);
-			$p->set_file($templates);
-			$p->set_block('new_month','day','day');
-			$params['period'] = 3;
-                    	$result_events_json = $this->print_events_to_show_json($params);
-                        $prev_month_link = '<a href="'.$this->page('month','&year='.$prevyear.'&month='.$prev.'&sday='.$sday).'">&lt;&lt;</a>';
-			$next_month_link = '<a href="'.$this->page('month','&year='.$nextyear.'&month='.$next.'&sday='.$sday).'">&gt;&gt;</a>';
-			$p->set_var('date',$result_events_json['date_events_json']);
-			$p->set_var('hora_final',$result_events_json['hora_final']);
-			$p->set_var('hora_inicial',$result_events_json['hora_inicial']);
-                        $p->set_var('minical',$minical_prev.'<br>'.$minical_next.'<br>'.$minical_next1);
-			$p->set_var('iprint',$print);
-			$p->set_var('param',$param);
-                        $p->set_var('title',$prev_month_link."&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;::".lang(strftime("%B",$m)).' '.$this->bo->year.'::&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.$next_month_link);
-                        $p->set_var('user',$GLOBALS['phpgw']->common->grab_owner_name($this->bo->owner));
-			$p->set_var('events_json',json_encode($result_events_json['events_to_show_json'])?json_encode($result_events_json['events_to_show_json']):'null');
-                        $p->set_var('holidays_json',json_encode($feriados_do_ano)?json_encode($feriados_do_ano):null);
-                        return $p->fp('out','day');
-                }
-
-		//função vai devolver os eventos do mês atual para exibição no novo componente da Agenda
-		function print_events_to_show_json($params)
-		{
-
-			if( (!isset($this->bo->prefs['calendar']['interval'])) || ( (isset($this->bo->prefs['calendar']['interval'])) && ( ($this->bo->prefs['calendar']['interval'] != 42) && ($this->bo->prefs['calendar']['interval'] != 84) ) ) )
-			{
-				$this->bo->prefs['calendar']['interval'] = 42;
-				$GLOBALS['phpgw']->preferences->add('calendar','interval',42);
-				$GLOBALS['phpgw']->preferences->save_repository();
-			}
-
-			if(!is_array($params))
-			{
-				$this->index();
-			}
-
-                        // $params['period'] pode ser 1 pra dia, 2 pra semana e 3 pra mes
-
-                        if(!$params['period'] || $params['period'] == '')
-                            $period = 3;
-                        else
-                            $period = $params['period'];
-			$accounts = CreateObject('phpgwapi.accounts');
-			$accountId = $accounts->name2id($account_name);
-                        $date_to_eval = sprintf("%04d%02d%02d",$params['year'],$params['month'],$params['day']);
-                        $dates = array();
-                        if($period == 1){
-                            $dates[] = $date_to_eval;
-                            $this->bo->store_to_cache(
-				Array(
-					'smonth'=> $params['month'],
-					'sday'	=> $params['day'],
-					'syear'	=> $params['year']
-				)
-                            );
-                        }else if($period == 2){
-                            $daily = $this->set_week_array($GLOBALS['phpgw']->datetime->get_weekday_start($params['year'],$params['month'],$params['day']),$this->theme['row_on'],True);
-
-                            foreach($daily as $key => $value)
-                                $dates[] = $key;
-
-                             $this->bo->store_to_cache(
-				Array(
-					'smonth'=> (int)substr($dates[0],4,2),
-					'sday'	=> (int)substr($dates[0],6),
-					'syear'	=> (int)substr($dates[0],0,4),
-                                        'eyear'	=> 0,
-					'emonth'=> 0,
-					'eday'	=> ((int)substr($dates[0],6))+6,
-				)
-                            );
-                        }else{
-                             $month_tmp = substr($date_to_eval, 0, 6);
-
-                             $this->bo->store_to_cache(
-				Array(
-					'smonth'=> (int)substr($date_to_eval,4,2),
-					'sday'	=> 1,
-					'syear'	=> (int)substr($date_to_eval,0,4),
-                                        'eyear'	=> 0,
-					'emonth'=> 0,
-					'eday'	=> ((int)substr($date_to_eval,6))+30,
-				)
-                            );
-                             for( $i=1 ; $i<=31; $i++){
-                                 if($i<10)
-                                     $day= $month_tmp."0".(string)$i;
-                                 else
-                                     $day=$month_tmp.(string)$i;
-                                 $dates[] = $day;
-
-                             }
-
-                        }
-
-                        $prefs = CreateObject('phpgwapi.preferences', $accountId);
-			$account_prefs = $prefs->read();
-			//print_debug('in print_day()');
-
-                        $month = (string)((Int)$params['month']-1);
-                        $date_events_json = 'Date('.$params['year'].','.$month.','.$params['day'].')';
-
-			print_debug('Date to Eval',$date_to_eval);
-
-			$hora_inicial = $account_prefs['calendar']['workdaystarts'];
-			$hora_final = $account_prefs['calendar']['workdayends']; //18;
-
-			$hour_size_px = $account_prefs['calendar']['interval'] ? $account_prefs['calendar']['interval'] : 42;
-
-			$title_view = $account_prefs['calendar']['title_view'];
-
-                        $events_to_show_json = array();
-			$templateSet = $GLOBALS['phpgw_info']['server']['template_set'];
-                        foreach($dates as $day)
-                        {
-
-                            $events = $this->bo->cached_events[$day];
-
-                            foreach($events as $event)
-                            {
-                                //$is_private = !$event['public'] && !$this->bo->check_perms(PHPGW_ACL_READ,$event);
-                                if($event['users_status'] == 'R' && $this->bo->prefs['calendar']['show_rejected'] == 0 && $event['owner']  != $GLOBALS['phpgw_info']['user']['account_id'])
-                                        continue;
-
-                                if($event['recur_type']){
-                                    $recur = $day;
-                                    $event['start']['year'] = (int)substr($day,0,4);
-                                    $event['start']['month'] = (int)substr($day,4,2);
-                                    $event['start']['mday'] = (int)substr($day,6,2);
-                                    $event['end']['year'] =  (int)substr($day,0,4);
-                                    $event['end']['month'] = (int)substr($day,4,2);
-                                    $event['end']['mday'] = (int)substr($day,6,2);
-                                    $event['id'] = $event['id'].'rc'.$day;
-                                }else{
-                                    $recur = false;
-                                }
-
-                                $isPublic = 1;
-                                if(($event['type'] == E && $event['public'] == 0))
-                                {
-                                    $isPublic = 0;
-                                    $isPublicTitle = lang('restrict');
-                                }
-
-                                if(($event['type'] == P && $event['public'] == 0))
-                                {
-                                    $isPublic = 0;
-                                    $isPublicTitle = lang('private');
-                                }
-
-                                $eventTime = ( (mktime($event['end']['hour'], $event['end']['min'], 0, $event['end']['month'], $event['end']['mday'], $event['end']['year'])-mktime($event['start']['hour'], $event['start']['min'], 0, $event['start']['month'], $event['start']['mday'], $event['start']['year']) )/60 );
-
-                                $participants = $this->planner_participants($event['participants']);
-				$intersection = FALSE;
-
-                                foreach($events as $ev)
-                                {
-                                    if($ev['id'] == $event['id']) continue;
-                                      if($ev['users_status'] == 'R') continue;
-                                      $event_start = 60*$event['start']['hour']+$event['start']['min'];
-                                      $event_end = 60*$event['end']['hour']+$event['end']['min'];
-                                      $event_i_start = 60*$ev['start']['hour']+$ev['start']['min'];
-                                      $event_i_end = 60*$ev['end']['hour']+$ev['end']['min'];
-                                    if((($event_start >= $event_i_start) && ($event_start < $event_i_end))||(($event_start < $event_i_start) && ($event_i_start < $event_end)))
-                                    {
-                                        $intersection = TRUE;
-                                        break;
-                                    }
-                                }
-                                if($event['users_status'] == 'R')
-				{
-                                    $rejected = TRUE;
-				}
-                                else
-				{
-                                    $rejected = FALSE;
-				}
-
-				$evDescription = '';
-				if($title_view == 0)
-				{
-				    $evDescription = " - ".$event['description'];
-				}
-
-				if($_GET['menuaction'] ==  'calendar.uicalendar.day')
-				{
-				    $text = $event['description'];
-				}
-				elseif($_GET['menuaction'] ==  'calendar.uicalendar.week')
-				{
-				    
-				    $text = ' - '.$event['end']['hour'].':'.$event['end']['min'];
-
-				    //is recurrent?
-				    $text .= (isset($recur) && $recur != false) ? ' ' . '<img width="10px" height="10px" border="0" title="'.lang('recurring event').'" src="calendar/templates/'.$templateSet.'/images/recur.png"/>' : '' ;
-
-				    //participants?
-				    if(count($event['participants']) > 1)
-				    {
-					$text .= " " . '<img width="11px" height="10px" border="0" title="'.$participants.'" src="calendar/templates/'.$templateSet.'/images/multi_3.png"/>';
-				    }
-				    else
-				    {
-					$text .= " " . '<img width="11px" height="10px" border="0" title="'.$participants.'" src="calendar/templates/'.$templateSet.'/images/single.png"/>';
-				    }
-
-				    //has attachments?
-				    $text .= (isset($event['attachment']) && $event['attachment'] != '') ? ' ' . '<img width="10px" height="10px" border="0" title="'.lang('email notifications with attachments has been sent').'" src="calendar/templates/'.$templateSet.'/images/clip.png"/>' : '' ;
-
-				    //is public?
-				    $text .= $isPublic == 0 ? ' ' . '<img width="11px" height="10px" border="0" title="'.$isPublicTitle.'" src="calendar/templates/'.$templateSet.'/images/private.png"/>' : '' ;
-
-				    //has alarm?
-				    $text .= (isset($event['alarm']) && count($event['alarm']) >= 1) ? ' ' . '<img width="11px" height="10px" border="0" title="'.lang('alarm').'" src="calendar/templates/'.$templateSet.'/images/alarm.png"/>' : '' ;
-
-				    $text .= ' - ' . $event['title'].$evDescription;
-				}
-				else
-				{
-				    $text = ' - '.$event['end']['hour'].':'.$event['end']['min'] . ' - '. $event['title'].$evDescription;
-				}
-
-                                $events_to_show_json[] = array(
-                                    start_date		    => $event['start']['year'].'-'.$event['start']['month'].'-'.$event['start']['mday'].' '.$event['start']['hour'].':'.$event['start']['min'],
-                                    end_date		    => $event['end']['year'].'-'.$event['end']['month'].'-'.$event['end']['mday'].' '.$event['end']['hour'].':'.$event['end']['min'] . ' - ' . utf8_encode($event['title']),
-                                    text		    => utf8_encode($text),
-				    textTitle		    => utf8_encode($event['description']), //week and month tooltip
-                                    descOnTitle		    => ($eventTime <= 57) ? 1 : 0,
-                                    title		    => utf8_encode($event['title']),
-                                    observation		    => utf8_encode($event['observations']),
-                                    location		    => utf8_encode($event['location']),
-                                    id			    => $event['id'],
-                                    participants	    => (count($event['participants']) > 1) ? 1 : 0,
-                                    participants_title	    => $participants,
-                                    attachments		    => $event['attachment'] ? 1 : 0 ,
-				    attachmentsTitle	    => utf8_encode(lang('email notifications with attachments has been sent')),
-                                    isPublic		    => $isPublic,
-                                    isPublicTitle	    => utf8_encode($isPublicTitle),
-                                    alarm		    => (isset($event['alarm']) && count($event['alarm']) >= 1) ? 1 : 0,
-				    alarmTitle		    => utf8_encode(lang('alarm')),
-                                    recur		    => $recur,
-				    recurTitle		    => utf8_encode(lang('recurring event')),
-                                    intersection	    => $intersection,
-                                    rejected                => $rejected,
-				    title_view		    => $title_view
-                                );
-
-				if($event['start']['hour'] < $hora_inicial)
-				{
-				    $hora_inicial = $event['start']['hour'];
-				}
-
-				if($event['end']['hour'] >= $hora_final)
-				{
-				    $hora_final = $event['end']['hour'] + 1;
-				}
-                            }
-                        }
-
-			$result = Array(
-			    'hora_inicial'	    => $hora_inicial,
-			    'hora_final'	    => $hora_final,
-			    'hour_size_px'	    => $hour_size_px,
-			    'date_events_json'	    => $date_events_json,
-			    'events_to_show_json'   => $events_to_show_json
-			);
-
-			return $result;
-		}	// end function
-
-
 
 		function timematrix($param)
@@ -5693,5 +4971,5 @@
 			{
 				$var = Array(
-					'action_url_button'	=> $this->page('set_action','&cal_id='.$cal_id.'&action='.$param.'&user_id='.$this->bo->owner),
+					'action_url_button'	=> $this->page('set_action','&cal_id='.$cal_id.'&action='.$param.'&user='.$this->bo->owner),
 					'action_text_button'	=> '  '.$text.'  ',
 					'action_confirm_button'	=> '',
@@ -5725,4 +5003,37 @@
 		function edit_form($param)
 		{
+                        $sHValue = '<option></option>
+                                    <option value="07:00">07:00</option>
+                                    <option value="07:30">07:30</option>
+                                    <option value="08:00">08:00</option>
+                                    <option value="08:30">08:30</option>
+                                    <option value="09:00">09:00</option>
+                                    <option value="09:30">09:30</option>
+                                    <option value="10:00">10:00</option>
+                                    <option value="10:30">10:30</option>
+                                    <option value="11:00">11:00</option>
+                                    <option value="11:30">11:30</option>
+                                    <option value="12:00">12:00</option>
+                                    <option value="12:30">12:30</option>
+                                    <option value="13:00">13:00</option>
+                                    <option value="13:30">13:30</option>
+                                    <option value="14:00">14:00</option>
+                                    <option value="14:30">14:30</option>
+                                    <option value="15:00">15:00</option>
+                                    <option value="15:30">15:30</option>
+                                    <option value="16:00">16:00</option>
+                                    <option value="16:30">16:30</option>
+                                    <option value="17:00">17:00</option>
+                                    <option value="17:30">17:30</option>
+                                    <option value="18:00">18:00</option>
+                                    <option value="18:30">18:30</option>
+                                    <option value="19:00">19:00</option>
+                                    <option value="19:30">19:30</option>
+                                    <option value="20:00">20:00</option>
+                                    <option value="20:30">20:30</option>
+                                    <option value="21:00">21:00</option>
+                                    <option value="21:30">21:30</option>
+                                    <option value="22:00">22:00</option>';
+                    
 			if(!is_array($param))
 			{
@@ -5735,6 +5046,15 @@
 			}
 			
+			include_once($_SESSION['rootPath'].'/calendar/inc/class.ex_participants.inc.php');
+                        $langp = array();
+                        $langp['ACCEPTED'] = lang('Accepted');
+                        $langp['DECLINED'] = lang('Declined');
+                        $langp['TENTATIVE'] = lang('Tentative');
+                        $langp['DELEGATED'] = lang('Delegated');
+                        $langp['NO ANSWER'] = lang('No answer');
+                        $exParticipants = new exParticipants($langp);
+                        $exParticipants->setParticipantsBySerializable($event['ex_participants']);
+                        $event['ex_participants'] = $exParticipants->getParticipantsMailsString();
 			$hourformat = substr($this->bo->users_timeformat,0,1);
-			
 			// $sb = CreateObject('phpgwapi.sbox');
 			$sb = CreateObject('phpgwapi.sbox2');
@@ -5764,5 +5084,5 @@
 			$p->set_block('edit','list','list');
 			$p->set_block('edit','hr','hr');
-			
+			$p->set_var('lang_set_participants', lang('set the participants'));
 			$vars = Array(
 				'font'			=> $this->theme['font'],
@@ -5771,4 +5091,5 @@
 				'accounts_link'		=> $GLOBALS['phpgw']->link('/index.php','menuaction=calendar.uicalendar.accounts_popup'),
 				'common_hidden'	=> '<input type="hidden" name="cal[id]" value="'.$event['id'].'">'."\n"
+                                        . '<input type="hidden" name="cal[date]" value="'.$param['date'].'">'."\n"
 					. '<input type="hidden" name="cal[owner]" value="'.$event['owner'].'">'."\n"
 					. '<input type="hidden" name="cal[uid]" value="'.$event['uid'].'">'."\n"
@@ -5786,5 +5107,5 @@
 				'tr_color' => $this->theme['th_bg'],
 				'field'	=> lang('Title'),
-				'data'	=> '<input name="cal[title]" size="103" maxlength="300" value="'.$event['title'].'">'
+				'data'	=> '<input name="cal[title]" size="45" maxlength="80" value="'.$event['title'].'">'
 			);
 
@@ -5792,5 +5113,5 @@
 			$var['description'] = Array(
 				'field'	=> lang('Full Description'),
-				'data'	=> '<textarea name="cal[description]" rows="5" cols="88" wrap="virtual" maxlength="2048">'.$event['description'].'</textarea>'
+				'data'	=> '<textarea name="cal[description]" rows="5" cols="40" wrap="virtual" maxlength="2048">'.$event['description'].'</textarea>'
 			);
 
@@ -5847,5 +5168,5 @@
 			$var['starttime'] = Array(
 				'field'	=> lang('Start Time'),
-				'data'	=> '<input name="start[hour]" id="start_hour" size="2" VALUE="'.$GLOBALS['phpgw']->common->show_date($start,$hourformat).'" maxlength="2">:<input name="start[min]" id="start_minute" size="2" value="'.$GLOBALS['phpgw']->common->show_date($start,'i').'" maxlength="2">'."\n".$str
+				'data'	=> '<input name="start[hour]" id="start_hour" size="2" VALUE="'.$GLOBALS['phpgw']->common->show_date($start,$hourformat).'" maxlength="2">:<input name="start[min]" id="start_minute" size="2" value="'.$GLOBALS['phpgw']->common->show_date($start,'i').'" maxlength="2">&nbsp;<select name="sStartHour" onchange="javascript:sChangeHour(this);">'.$sHValue.'</select>'."\n".$str	
 			);
 
@@ -5872,5 +5193,5 @@
 			$var['endtime'] = Array(
 				'field'	=> lang('End Time'),
-				'data'	=> '<input name="end[hour]" id="end_hour" size="2" VALUE="'.$GLOBALS['phpgw']->common->show_date($end,$hourformat).'" maxlength="2">:<input name="end[min]" id="end_minute" size="2" value="'.$GLOBALS['phpgw']->common->show_date($end,'i').'" maxlength="2">'."\n".$str
+				'data'	=> '<input name="end[hour]" id="end_hour" size="2" VALUE="'.$GLOBALS['phpgw']->common->show_date($end,$hourformat).'" maxlength="2">:<input name="end[min]" id="end_minute" size="2" value="'.$GLOBALS['phpgw']->common->show_date($end,'i').'" maxlength="2">&nbsp;<select name="sEndHour" onchange="javascript:sChangeHour(this);">'.$sHValue.'</select>'."\n".$str
 			);
 
@@ -5884,5 +5205,5 @@
 			$var['access'] = Array(
 			'field' => lang('Type'),
-			'data'  => '<select onchange="javascript:changeViewMode(this.value);" id="cal[type]" name="cal[type]" '.'><option value="normal" '.(($event['public'] && $event['type'] == 'E')?'SELECTED':'').' >'.lang('Normal').'</option><option value="private" '.((!$event['public'] && $event['type'] == 'E')?'SELECTED':'').' >'. lang('Restrict').'</option><option value="privateHiddenFields" '.($event['type']=='P'?'SELECTED':'').' >'. lang('Private').'</option><option value="hourAppointment" '.($event['type'] == 'H'?'SELECTED':'').' >'.lang('Hours Appointment').'</option></select>'
+			'data'  => '<select onchange="javascript:changeViewMode(this.value);" id="cal[type]" name="cal[type]" '.($event['type'] == 'H'?'DISABLED':'').'><option value="normal" '.(($event['public'] && $event['type'] == 'E')?'SELECTED':'').' >'.lang('Normal').'</option><option value="private" '.((!$event['public'] && $event['type'] == 'E')?'SELECTED':'').' >'. lang('Restrict').'</option><option value="privateHiddenFields" '.($event['type']=='P'?'SELECTED':'').' >'. lang('Private').'</option><option value="hourAppointment" '.($event['type'] == 'H'?'SELECTED':'').' >'.lang('Hours Appointment').'</option></select>'
 			); //event['public']
 
@@ -5898,5 +5219,5 @@
 							{
 								$str .= '<option value="' . $id.$event['participants'][$id] . '"'.($event['participants'][$id]?' selected':'').'>('.$GLOBALS['phpgw']->accounts->get_type($id)
-										.') ' . $GLOBALS['phpgw']->common->grab_owner_name($id) . '</option>' . "\n";
+										.') ' . $GLOBALS['phpgw']->common->grab_owner_name($id) . ' ('. $id.')</option>' . "\n";
 							}
 						}
@@ -5959,5 +5280,4 @@
 										</tr>
 										</table>
-										<script src='calendar/js/edit.js' type='text/javascript'></script>
 									"
 						);
@@ -5992,7 +5312,11 @@
 
 								if ($GLOBALS['phpgw_info']['server']['cal_type_tree_participants'] == '3'){
+									$context = preg_replace("/\\\([0-9A-Fa-f]{2})/e", "''.chr(hexdec('\\1')).''",$context);
+									$context = utf8_decode($context);
 									$combo_org = '<option value='.$context.'>'.strtoupper($context).'</option>';
 								}else{
 									$combo_org = $this->get_organizations(trim(strtolower($context)),$user_context, $recursive);
+									$combo_org = preg_replace("/\\\([0-9A-Fa-f]{2})/e", "''.chr(hexdec('\\1')).''",$combo_org);
+									$combo_org = utf8_decode($combo_org);
 								}
 
@@ -6007,23 +5331,28 @@
 								}
 
-								$edit_js_path = 'calendar/templates/'.$_SESSION['phpgw_info']['calendar']['user']['preferences']['common']['template_set'];
-								if (!file_exists($GLOBALS['phpgw_info']['server']['webserver_url'].$edit_js_path.'/js/edit.js'))
-									$edit_js_path = 'calendar';
-
 								$var['participants'] = array
 								(
 									'field'	=> '
-									<script src="'.$edit_js_path.'/js/edit.js" type="text/javascript"></script><div id=\'disponibility\' style=\'display:none;position:absolute\' bgcolor=\'#FFFFFF\'>
+									<script src="calendar/templates/'.$_SESSION['phpgw_info']['calendar']['user']['preferences']['common']['template_set'].'/js/edit.js" type="text/javascript"></script><div id=\'disponibility\' style=\'display:none;position:absolute\' bgcolor=\'#FFFFFF\'>
 	<iframe src=\'#\' id=\'frame_disponibility\' width=\'500\' marginHeight=\'0\' marginWidth=\'0\' height=\'200px\'></iframe>
-</div>
+									</div>
 									'.lang('Participants'),
-									'data'	=> '
-											<input type="hidden" id="txt_loading" value="'.lang("Loading").'">' .
+									'data'	=> 
+									        '<input type="hidden" id="txt_loading" value="'.lang("Loading").'">' . 
 											'<input type="hidden" id="txt_searching" value="'.lang("Searching").'">' .
 											'<input type="hidden" id="txt_users" value="'.lang("Users").'">' .							
 											'<input type="hidden" id="txt_groups" value="'.lang("Groups").'">' .
+                                                                                        '<input type="hidden" id="txt_shared_accounts" value="'.lang("shared accounts").'">' .
+											'<input type="hidden" id="txt_min_search" value="'.lang("Your search argument must be longer than 4 characters.").'">' .
+											'<input type="hidden" id="txt_none_result" value="'.lang("None result was found.").'">' .
+											'<input type="hidden" id="txt_Select_a_name" value="'.lang("Select a name").'">' .
+                                                                                        '<input type="hidden" id="txt_Close" value="'.lang("Close").'">' .
+											'<input type="hidden" id="txt_More_than_%1_results._Please,_try_to_refine_your_search" value="'.lang("More than %1 results. Please, try to refine your search",'%1').'">' .
+                                                                                        '<input type="hidden" id="txt_The_results_were_found_in_the_Global_Catalog" value="'.lang("The results were found in the Global Catalog").'">' . 
 											'<table width="100%" border="0">'.
 											'<tr>'.
-											'<td width="25%"><br><br>'.
+											'<td width="25%"><br>'.	
+											'<button type="button" onClick="javascript:add_user();"><img src="calendar/templates/'.$GLOBALS['phpgw_info']['user']['preferences']['common']['template_set'].'/images/add.png" style="vertical-align: middle;" >&nbsp;'.lang("Add").'</button>'.
+											'&nbsp;&nbsp;<button type="button" onClick="javascript:remove_user();"><img src="calendar/templates/'.$GLOBALS['phpgw_info']['user']['preferences']['common']['template_set'].'/images/rem.png" style="vertical-align: middle;" >&nbsp;'.lang("Remove").'</button>'.
 											'<br><br>&nbsp;&nbsp;<b>'.lang("Event's participants").'</b><br>'.
 											'	<select id="user_list" name="participants[]" style="width: 300px" multiple size="13">'.$str.'</select>'.
@@ -6033,28 +5362,24 @@
 											'<td valign="bottom">'.
 											'	'.lang("Organization").': '.
-											'	<select name="org_context" id="combo_org" onchange="javascript:get_available_users(\''.$module_name.'\',this.value,\''.($recursive ? "" : "search").'\',\''.$GLOBALS['phpgw_info']['server']['auto_search'].'\');">'.$combo_org.'</select>'.
+											'	<select name="org_context" id="combo_org">'.$combo_org.'</select>'.
 											'	<br>'.
 											'	<font color="red"><span id="cal_span_searching">&nbsp;</span></font>'.									
 											'	<br>'.lang("Search for").':'.
-											'	<input value="" id="cal_input_searchUser" size="35" autocomplete="off" onkeyup="javascript:optionFinderTimeout(this,'.$GLOBALS['phpgw_info']['server']['min_num_characters'].',\''.($recursive ? "" : "search").'\',\''.$GLOBALS['phpgw_info']['server']['auto_search'].'\')"><br>'.
+											'	<input value="" id="cal_input_searchUser" size="35" autocomplete="off" onkeypress="return optionFinderTimeout(this,'.$GLOBALS['phpgw_info']['server']['min_num_characters'].',\''.($recursive ? "" : "search").'\',\''.$GLOBALS['phpgw_info']['server']['auto_search'].'\', event);"><br>'.
 											'	<b>'.lang("Available users and groups").'</b><br>'.
 											'	<select id="user_list_in" style="width: 300px" multiple size="13"></select>'.
 											'</td>'.
 											'</tr>'.
-                                            '<tr>'.
-                                            '<td width="25%">'.
-                                            '<button type="button" id="time_map" onClick="javascript:show_disponibility();">'.lang("Disponibility map").'</button>'.
-                                            '</td>'.
-                                            '<td width="30px" valign="middle" align="center">&nbsp;'.
-											'</td>'.
-                                            '<td valign="bottom">'.
-                                            '<button type="button" onClick="javascript:add_user();"><img src="calendar/templates/'.$GLOBALS['phpgw_info']['user']['preferences']['common']['template_set'].'/images/add.png" style="vertical-align: middle;" >&nbsp;'.lang("Add").'</button>'.
-											'&nbsp;&nbsp;<button type="button" onClick="javascript:remove_user();"><img src="calendar/templates/'.$GLOBALS['phpgw_info']['user']['preferences']['common']['template_set'].'/images/rem.png" style="vertical-align: middle;" >&nbsp;'.lang("Remove").'</button>'.
-                                            '</td>'.
-											'</tr>'.
+											'<tr>' .
+											'<td>' .
+											'<button onclick="javascript:show_disponibility();" id="time_map" type="button">Mapa de disponibilidade</button><br>' .
+											'<b>'.lang("Can have users and groups that doesn't appears on the map").'</b><br>' .
+											'<td>' .
+											'</tr>' .
 											'</table>'. 
 											'<script type="text/javascript" src="phpgwapi/js/wz_dragdrop/wz_dragdrop.js"></script>'.
 											'<script type="text/javascript" src="phpgwapi/js/dJSWin/dJSWin.js"></script>'.		
-											"<script src='calendar/js/edit_exmail.js' type='text/javascript'></script>" .
+											"<script src='calendar/templates/".$GLOBALS['phpgw_info']['user']['preferences']['common']['template_set']."/js/finder.js' type='text/javascript'></script>" .
+											"<script src='calendar/templates/".$GLOBALS['phpgw_info']['user']['preferences']['common']['template_set']."/js/edit_exmail.js' type='text/javascript'></script>" .
 											$load_lang_vars.																			
 											"<script src='".$module_name."/js/connector.js' type='text/javascript'></script>".
@@ -6067,5 +5392,5 @@
 						}						
 						
-						$var['participants']['data'] .= '<br /><a id="a_ext_participants" title="'.lang("It types below the email addresses, if you want to invite other people out" .
+						$var['participants']['data'] .= '<a id="a_ext_participants" title="'.lang("It types below the email addresses, if you want to invite other people out" .
 							" of this system").'" name="a_ext_participants" onClick="javascript:showExParticipants(this,\''.$module_name.'\')" href="#a_ext_participants"><b>'.lang("Inform").' '.lang("external participants").'</b>&nbsp;<img align="top" ' .
 							'src="calendar/templates/'.$GLOBALS['phpgw_info']['user']['preferences']['common']['template_set'].'/images/sent.gif"></a><table id="tbl_ext_participants" width="100%" border="0" style="display:none">'.
@@ -6079,6 +5404,7 @@
 							'<td>'.	
 							'&nbsp;&nbsp;>> '.lang("It types below the email addresses, if you want to invite other people out of this system").':'.
-							'&nbsp;&nbsp;<br><textarea name="ex_participants" id="ex_participants" cols="70" rows="2">'.$event['ex_participants'].'</textarea><br>&nbsp;&nbsp;'.
-							//$footer_ext_participantes.
+							'&nbsp;&nbsp;<br> <input type="hidden" name="h_exParticipants" id="h_exParticipants" value="'.$exParticipants->getParticipantsSerializable().'" />
+                                                        <textarea name="ex_participants" id="ex_participants" cols="70" rows="2">'.$event['ex_participants'].'</textarea><br>&nbsp;&nbsp;'.
+							$footer_ext_participantes.
 							'</tr>'.							
 							'</table>';
@@ -6100,5 +5426,5 @@
 			}
 
-                        // Reminder
+// Reminder
 			// The user must use "Alarm Management" to change/modify an alarm
 			// so only display the email reminder fields if this is a new event
@@ -6182,24 +5508,4 @@
 				'data'	=> '<select name="cal[recur_type]">'."\n".$str.'</select>'."\n"
 			);
-
-
-                        $preferences = CreateObject('phpgwapi.preferences',(int)$this->owner);
-                       $selected_creator = $selected_owner = '';
-                       if($event['notifications_owner'] == 1)
-                           $selected_owner = ' selected';
-                       else
-                           $selected_creator = ' selected';
-                      
-                       $option = '<option value="0" '.$selected_creator.' >'.$GLOBALS['phpgw']->common->grab_owner_name((int)$_SESSION['phpgw_session']['account_id']).'</option>';
-                       if($_SESSION['phpgw_session']['account_id'] != $event['owner']){
-                           $option .= '<option value="1" '.$selected_owner.' >'.$GLOBALS['phpgw']->common->grab_owner_name((int)$event['owner']).'</option>';
-                       }
-
-
-                       $var['notifications_owner'] = Array(
-				'field'	=> lang('Send notificatios as'),
-				'data'	=> '<select name="cal[notifications_owner]" >'.$option.'</select>'
-			);
-
 
 			if($event['recur_enddate']['year'] != 0 && $event['recur_enddate']['month'] != 0 && $event['recur_enddate']['mday'] != 0)
@@ -6243,21 +5549,4 @@
 			);
 //			$this->output_template_array($p,'row','list',Array('data' => '<script src="simple_show_hide.js" type="text/javascript"></script>'));
-
-// Observations
-			$var['observations'] = Array(
-				'field'	=> lang('Observations'),
-				'data'	=> '<textarea name="cal[observations]" rows="5" cols="88" wrap="virtual" maxlength="2048">'.$event['observations'].'</textarea>'
-			);
-
-                        if ($event['attachment'] == '' || $event['attachment'] == 'ERROR' || is_array($event['attachment']))
-                            $data =  '<a onClick="javascript:addAttach()" href="#divFiles" >Anexos: adicionar+</a><div id="divFiles"></div>';
-                        else
-                            $data = '<input type="hidden" name="cal[attachment]" value='.$event["attachment"].'>'.lang('Notification with attachments sent.').'<br><a onClick="javascript:addAttach()" href="#divFiles" >Anexos: adicionar+</a><div id="divFiles"</div>';
-
-                        $var['attachment'] = Array(
-                                'field' => lang('Attachment'),
-                                //'data' => '<input  type="file" name="cal[attachment]" />'
-                                'data' => $data
-                        );
 
 			if (!isset($this->fields))
Index: trunk/calendar/inc/class.boholiday.inc.php
===================================================================
--- trunk/calendar/inc/class.boholiday.inc.php	(revision 3914)
+++ trunk/calendar/inc/class.boholiday.inc.php	(revision 5132)
@@ -256,12 +256,5 @@
 				}
 //				echo 'Loading from: '.$load_from.'/holidays.'.strtoupper($locale).'.csv'."<br>\n";
-                                if(isset($GLOBALS['phpgw_info']['server']['holidays_url_path']) && $GLOBALS['phpgw_info']['server']['holidays_url_path'] != 'localhost')
-                                {
                                     $lines = $network->gethttpsocketfile($load_from.'/holidays.'.strtoupper($locale).'.csv');
-                                }
-                                else
-                                {
-                                    $lines = explode(chr(0x0A),file_get_contents($load_from.'/holidays.'.strtoupper($locale).'.csv'));
-                                }
 				if (!$lines)
 				{
@@ -296,7 +289,7 @@
 		function add()
 		{
-			if(@$_POST['submit'])
-			{
 				$holiday = $_POST['holiday'];
+
+
 
 				if(empty($holiday['mday']))
@@ -349,5 +342,4 @@
 				}
 			}
-		}
 
 		function sort_holidays_by_date($holidays)
Index: trunk/calendar/inc/class.socalendar.inc.php
===================================================================
--- trunk/calendar/inc/class.socalendar.inc.php	(revision 4316)
+++ trunk/calendar/inc/class.socalendar.inc.php	(revision 5132)
@@ -193,5 +193,8 @@
 		function find_uid($uid)
 		{
-			$sql = " AND (phpgw_cal.uid = '".$uid."') ";
+			$uid_ = substr($uid, strpos($uid,"-")+1);				
+			$uid_ = substr($uid_, 0, strpos($uid_,"-"));				
+			
+			$sql = " AND (phpgw_cal.cal_id = '". (int)$uid_."') ";
 
 			$found = $this->cal->get_event_ids(False,$sql);
@@ -210,7 +213,68 @@
 		}
 
-		function add_entry(&$event)
-		{
-			return $this->cal->save_event($event);
+		
+		/*
+		 * @abstract: Retorna o email do organizer do evento. 
+		 */
+		function get_mail_organizer($cal_id)
+		{
+			$sql = 'SELECT organizer FROM phpgw_cal WHERE cal_id =' . $cal_id;	
+			$this->cal->stream->query($sql,__LINE__,__FILE__);
+			
+			while($this->cal->stream->next_record())
+			{
+				$ret[0] = $this->cal->stream->f('organizer');
+			}
+			
+			$return = $ret[0];
+			$pos = strpos($return, "<");
+			$return = substr($return, $pos);
+			$return = str_replace('"','',$return);
+			$return = str_replace('>','',$return);
+			$return = str_replace('<','',$return);
+			
+			return $return;
+		}
+		
+		
+		/*
+		 * @abstract: Retorna os emails dos participantes do evento.
+		 */
+		function get_mail_participants($cal_id)
+		{
+		
+		}
+		
+		
+		/*
+		 * @abstract: busca no banco pra verificar se já existe um compromisso com o mesmo cal_id
+		 */
+		function find_cal_id($cal_id)
+		{
+
+                        $uid_ = substr($cal_id, strpos($cal_id,"-")+1);
+                        $uid_ = substr($uid_, 0, strpos($uid_,"-"));
+
+                        $sql = " AND phpgw_cal.cal_id = '". (int)$uid_."' OR phpgw_cal.uid = '". $cal_id."' ";
+
+			$found = $this->cal->get_event_ids(False,$sql);
+			if(!$found)
+			{
+				$found = $this->cal->get_event_ids(True,$sql);
+			}
+			if(is_array($found))
+			{
+				return $found[0]; 
+			}
+			else
+			{
+				return False;
+			}
+		}
+		
+
+		function add_entry(&$event , $sendMail = true, $importAccount = false)
+		{
+			return $this->cal->save_event($event,$sendMail,$importAccount);
 		}
 
@@ -269,7 +333,8 @@
 		}
 
-		function set_status($id,$status)
-		{
-			$this->cal->set_status($id,$this->owner,$status);
+		function set_status($id,$status,$user = false)
+		{
+                    if($user) $this->cal->set_status($id,$user,$status);
+                    else $this->cal->set_status($id,$this->owner,$status);
 		}
 
@@ -369,20 +434,4 @@
 			$this->cal->set_description($description);
 		}
-
-		function set_observations($observations='')
-		{
-		    $this->cal->set_observations($observations);
-		}
-
-                function set_attachment($attachment='')
-		{
-			$this->cal->set_attachment($attachment);
-		}
-
-		function set_notifications_owner($notifications_owner='') 
-		{ 
- 	        $this->cal->set_notifications_owner($notifications_owner); 
- 	    }
-		
 		function set_ex_participants($ex_participants='')
 		{
Index: trunk/calendar/inc/hook_settings.inc.php
===================================================================
--- trunk/calendar/inc/hook_settings.inc.php	(revision 4565)
+++ trunk/calendar/inc/hook_settings.inc.php	(revision 5132)
@@ -125,6 +125,11 @@
 		'This defines the end of your dayview. Events after this time, are shown below the dayview.');
 	$intervals = array(
-		84	=> '15 ' . lang('minutes'),
-		42	=> '30 ' . lang('minutes')
+		5	=> '5',
+		10	=> '10',
+		15	=> '15',
+		20	=> '20',
+		30	=> '30',
+		45	=> '45',
+		60	=> '60'
 	);
 	create_select_box('Intervals in day view','interval',$intervals,
@@ -189,12 +194,2 @@
 	create_check_box('Leave my calendar public','public_view',
 		'This option allow everybody to view your calendar in readmode.');
-	create_select_box('Default view of your calendar','title_view',array(
-			'0' => lang('Title and Description'),
-			'1' => lang('Only Title')
-		),'This option enable or disable the meeting description view your calendar in readmode.');
-	create_select_box('Choose fields to print','fields_to_print',array(
-			'0' => lang('Only Title'),
-			'1' => lang('Title and Description'),
-			'2' => lang('Title, description and observations')
-		),'This option enables the choice of fields to print.');
-	
Index: trunk/calendar/templates/classic/edit.tpl
===================================================================
--- trunk/calendar/templates/classic/edit.tpl	(revision 3254)
+++ trunk/calendar/templates/classic/edit.tpl	(revision 5132)
@@ -15,23 +15,4 @@
 		Window1=window.open('{accounts_link}',"Search","width=800,height=600,toolbar=no,scrollbars=yes,resizable=yes");
 	}
-
-	function show_disponibility() {
-		participants = "";
-		combo = document.getElementById('user_list');
-		if(combo.length==0) {
-			alert('Selecione os participantes');
-			return;
-		}
-
-		for (i=0;i<combo.length;i++) {
-			participants+=combo[i].value+",";
-		}
-		url = 'index.php?menuaction=calendar.uicalendar.disponibility&participants='+participants+'&date='+document.getElementById('start[str]').value;
-
-		//alert(url);
-		document.getElementById('frame_disponibility').src = url;
-		document.getElementById('disponibility').style.display='';
-		//window.open(url);
-	}
 </script>
 <center>
@@ -40,5 +21,5 @@
 <form action="{action_url}" method="post" name="app_form">
 {common_hidden}
-<table id="editFormTable" border="0" width="90%"   class="prefTable">
+<table id="editFormTable" border="0" width="90%">
  <tr>
   <td colspan="2">
Index: trunk/calendar/templates/classic/listUsers.php
===================================================================
--- trunk/calendar/templates/classic/listUsers.php	(revision 1645)
+++ trunk/calendar/templates/classic/listUsers.php	(revision 5132)
@@ -22,5 +22,5 @@
 	$t->set_file(array('addUser_t' => '../../../calendar/templates/classic/listUsers.tpl'));
 	
-	$obj_account = CreateObject('phpgwapi.accounts',$owner);
+	$obj_account = CreateObject('phpgwapi.accounts',$this->bo->owner);
 
 	$post_select_organization = $_POST['select_organization'];
Index: trunk/calendar/templates/classic/listUsers.tpl
===================================================================
--- trunk/calendar/templates/classic/listUsers.tpl	(revision 1645)
+++ trunk/calendar/templates/classic/listUsers.tpl	(revision 5132)
@@ -48,3 +48,3 @@
 	</body>
 </html>
-<script src="../../js/edit.js" type="text/javascript"></script>
+<script src="js/edit.js" type="text/javascript"></script>
Index: trunk/calendar/templates/classic/body_email.tpl
===================================================================
--- trunk/calendar/templates/classic/body_email.tpl	(revision 3300)
+++ trunk/calendar/templates/classic/body_email.tpl	(revision 5132)
@@ -25,6 +25,4 @@
 <td width='2%' align='left' valign='top'>{varbuttom1}</td>
 <td width='2%' align='left' valign='top'>{varbuttom2}</td>
-<td width='2%' align='left' valign='top'>{varbuttom5}</td>
-<td width='2%' align='left' valign='top'>{varbuttom4}</td>
 <td width='94%' align='left' valign='top'>{varbuttom3}</td>
 </tr>
Index: trunk/calendar/templates/default/app_print.css
===================================================================
--- trunk/calendar/templates/default/app_print.css	(revision 4030)
+++ trunk/calendar/templates/default/app_print.css	(revision 5132)
@@ -3,17 +3,14 @@
 
 .calendar_print_main {
-	text-align:left;
+	text-align:center;
 	font-family: Verdana, Arial, Helvetica, sans-serif;
-	font-size: 11px;
+	font-size: 8px;
 	color: #000066;
 	background-color: #F7F7F7;
-	margin: 0px;
-	padding: 0px;
-	width: 98%;
-	position:absolute;
-	top: 10px;
-	bottom: 10px;
-	left: 15px;
-	right: 10px;
+	border: 1px solid #CCCCCC;
+	margin: 5px;
+	padding: 5px;
+	height: 700px;
+	width: 600px;
 }
 .button {
@@ -142,5 +139,5 @@
 }
 
-/*Mini Calendar*/
+//Mini Calendar
 
 .calendar_minical_table
@@ -270,5 +267,5 @@
 .calendar_month_identifier
 {
-	font-size:14px;
+	font-size:18px;
 	font-weight: bold;
 }
@@ -276,6 +273,6 @@
 .calendar_user_identifier
 {
-	font-size:10px;
-	color: #778899;
+	font-size:12px;
+	color: #009999;
 	font-weight: bold;
 }
Index: trunk/calendar/templates/default/holiday.tpl
===================================================================
--- trunk/calendar/templates/default/holiday.tpl	(revision 2)
+++ trunk/calendar/templates/default/holiday.tpl	(revision 5132)
@@ -1,3 +1,22 @@
 <!-- BEGIN form -->
+
+
+<script type="text/javascript">	
+	function valida(){
+		if (document.getElementsByName("holiday[locale]")[0].selectedIndex == 0){
+			 alert("Por favor, selecione um país para inclusão deste feríado.");
+			 return false;
+		}
+		if( (document.getElementsByName("holiday[mday]")[0].selectedIndex == 0) || 
+		   (document.getElementsByName("holiday[month_num]")[0].selectedIndex == 0) || 
+		   (document.getElementsByName("holiday[year]")[0].selectedIndex == 0) ){
+			 alert("Por favor, informe uma data.");
+			 return false;
+		}else{
+			document.forms["form"].submit();
+		}
+	}
+</script>
+
 <center>
 {message}<br>
@@ -11,5 +30,5 @@
     <tr>
      <td>
-      <input type="submit" name="submit" value="{lang_add}"></form>
+      <input type="button" onclick="javascript:valida();" value="{lang_add}"></form>
      </td>
      <td>
Index: trunk/calendar/templates/default/alarm.tpl
===================================================================
--- trunk/calendar/templates/default/alarm.tpl	(revision 3930)
+++ trunk/calendar/templates/default/alarm.tpl	(revision 5132)
@@ -18,9 +18,8 @@
 <!-- BEGIN alarm_headers -->
 	<tr bgcolor="{tr_color}">
-		<th align="left" width="25%">{lang_time}</th>
+		<th align="left" width="30%">{lang_time}</th>
 		<th align="left" width="30%">{lang_text}</th>
-		<th align="left" width="25%">{lang_owner}</th>
-		<th width="10%">{lang_enabled}</th>
-		<th width="10%">{lang_select}</th>
+		<th align="left" width="30%">{lang_owner}</th>
+		<th width="20%" colspan="2">{lang_select}</th>
 	</tr>
 <!-- END alarm_headers -->
@@ -37,8 +36,5 @@
 			{owner}
 		</td>
-		<td align="center">
-			{enabled}
-		</td>
-		<td align="center">
+		<td align="center" colspan="2">
 			{select}
 		</td>
Index: trunk/calendar/templates/default/footer.tpl
===================================================================
--- trunk/calendar/templates/default/footer.tpl	(revision 4114)
+++ trunk/calendar/templates/default/footer.tpl	(revision 5132)
@@ -37,20 +37,11 @@
 <td valign="top" width="30%">
  <font size="-1">
-    <form id="listPrint" action="{acao}" method="post" name="{formname}">
-
-	<span style="display: {display}">
-	    <b>{day_ini_label}:</b>
-	    <select id="dayIni" name="{day_ini_name}" >
-		{row_ini}
-	    </select>
-	</span>
-
-	<br /> <br />
-
+    <form action="{acao}" method="post" name="{formname}">
 	<span style="display: {display}" >
+ 
 	    <label>
 		<b>{num_dias_label}:</b>
 	    </label>
-	    <select id="numDays" name="{num_dias_name}" >
+	<select name="{num_dias_name}" onchange="{formonchange}"/>
 		{row_qtd}
 	    </select>
@@ -59,6 +50,13 @@
 		{tip}
 	    </span>
+	<br /> <br />
 	</span>
-	<input type="hidden" name="user" value="{user}">
+<span style="display: {display}">
+	<b>{day_ini_label}:</b>
+	<select name="{day_ini_name}" onchange="{formonchange}">
+	{row_ini}
+	</select>
+	</span>
+<input type="hidden" name="user" value="{user}">
 	<noscript><input type="submit" value="{go}"></noscript>
      </form>
Index: trunk/calendar/templates/default/overlap.tpl
===================================================================
--- trunk/calendar/templates/default/overlap.tpl	(revision 2)
+++ trunk/calendar/templates/default/overlap.tpl	(revision 5132)
@@ -17,4 +17,7 @@
 				<tr>
 					<td>
+						{cancel_button}
+					</td>
+					<td>
 						{resubmit_button}
 					</td>
@@ -28,3 +31,35 @@
 </table>
 </center>
+{suggestion}
+<style>
+	.even { background-color: #f4f8fb}
+	.odd { background-color: #fff}
+	.fields {
+		list-style-type: none;
+		list-style-image: none;
+		margin: 0;
+		padding: 0;
+	}
+	
+	.fields li{
+		text-align:center;
+		display: block;
+		width:100%;
+		margin: 0;
+		padding: 0;
+	}
+
+	.fields li div{
+		text-align:left;
+		display: inline-block;
+		float:center;
+		width:220px;
+	}	
+	
+	label {
+		margin: 0 3px 0 3px;
+		width: 100px;
+		display: inline-block;
+	}
+</style>
 <!-- END overlap -->
Index: trunk/calendar/templates/default/grant_group_access.tpl
===================================================================
--- trunk/calendar/templates/default/grant_group_access.tpl	(revision 1487)
+++ trunk/calendar/templates/default/grant_group_access.tpl	(revision 5132)
@@ -16,5 +16,5 @@
 <td align='center' valign="bottom"><br><b>{lang_User_to_grant_access}</b><br>
 	<font color="red"><span id="cal_span_searching1">&nbsp;</span></font>
-	<br>{lang_Search_for}: <input type="text" id="cal_input_searchUser1" name="cal_input_searchUser1" value="" size=30 autocomplete="off" onkeyup="javascript:search_object(this,'cal_span_searching1','user','u')"/>
+	<br>{lang_Search_for}: <input type="text" id="cal_input_searchUser1" name="cal_input_searchUser1" value="" size=30 autocomplete="off" onkeyup="javascript:search_object(this,'cal_span_searching1','user','u', event)"/>
 	<br><br>
 	<select id="user" style="width: 300px" size="13"></select>
@@ -31,5 +31,5 @@
 <td align='center' valign="bottom"><br><b>{lang_Group_to_share_calendar}</b><br>
 	<font color="red"><span id="cal_span_searching2">&nbsp;</span></font>
-	<br>{lang_Search_for}:	<input type="text" id="cal_input_searchUser2" name="cal_input_searchUser2" value="" size=30 autocomplete="off" onkeyup="javascript:search_object(this,'cal_span_searching2','group','g')"/><br><br>
+	<br>{lang_Search_for}:	<input type="text" id="cal_input_searchUser2" name="cal_input_searchUser2" value="" size=30 autocomplete="off" onkeyup="javascript:search_object(this,'cal_span_searching2','group','g', event)"/><br><br>
 	<select id="group" style="width: 300px" size="13"></select>
 </td>
Index: trunk/calendar/templates/default/app.css
===================================================================
--- trunk/calendar/templates/default/app.css	(revision 4184)
+++ trunk/calendar/templates/default/app.css	(revision 5132)
@@ -6,9 +6,9 @@
 	color: #000066;
 	background-color: #F7F7F7;
-	/*border: 1px solid #CCCCCC;*/
-	margin: 1px;
+	border: 1px solid #CCCCCC;
+	margin: 5px;
 	padding: 5px;
 	height: 156px;
-	width: 600px;
+	width: 480px;
 }
 
@@ -54,31 +54,4 @@
 	font-style: italic; 
 	font-size:10px; 
-}
-
-A.minicaltoday
-{
-	padding-left:3px;
-	padding-right:3px;
-	background: #B3DAFF;
-	color: black;
-	font-size: 10px; 
-}
-
-A.minicaltodaysel
-{
-	padding-left:3px;
-	padding-right:3px;
-	background: #42A1FF;
-	color: white;
-	font-size: 10px;
-}
-
-A.minicalnottoday
-{
-	padding-left:3px;
-	padding-right:3px;
-	background: #FFAD5C;
-	color: black;
-	font-size: 10px;
 }
 
Index: trunk/calendar/templates/default/view.tpl
===================================================================
--- trunk/calendar/templates/default/view.tpl	(revision 2)
+++ trunk/calendar/templates/default/view.tpl	(revision 5132)
@@ -1,4 +1,5 @@
 
 <!-- BEGIN view_event -->
+<!-- <script src="./calendar/templates/default/js/suggestion.js" type="text/javascript" language="JavaScript1.2"></script> -->
 <center>
 <table id="calendar_view_event" border="0" width="90%">
@@ -23,9 +24,12 @@
 				<tr>
 					{button_right}
-				</tr>
+					{button_right_suggestion}
 			</table>
 		</td>
 	</tr>
 </table>
+
+{suggestion}
+
 </center>
 <!-- END view_event -->
Index: trunk/calendar/templates/default/day.tpl
===================================================================
--- trunk/calendar/templates/default/day.tpl	(revision 4119)
+++ trunk/calendar/templates/default/day.tpl	(revision 5132)
@@ -7,5 +7,5 @@
 				<tr>
 					<td class="calendar_dayview_table_header">
-      					<b>{prev_day_link}</b> :: {day_of_week}, {date}&nbsp;<span class="calendar_user_identifier">:&nbsp;{username}&nbsp;:</span> :: <b>{next_day_link}</b>
+      					{date}&nbsp;<span class="calendar_user_identifier">:&nbsp;{username}&nbsp;:</span>
 						<br />
      				</td>
Index: trunk/calendar/templates/default/vcal_import.tpl
===================================================================
--- trunk/calendar/templates/default/vcal_import.tpl	(revision 3736)
+++ trunk/calendar/templates/default/vcal_import.tpl	(revision 5132)
@@ -1,6 +1,4 @@
-<!-- BEGIN page_block -->
 <!-- vcardin form -->
 {vcal_header}
-		{error_box}
     <form ENCTYPE="multipart/form-data" method="POST" action="{action_url}">
       <table border=0>
@@ -11,6 +9,2 @@
       </table>
      </form>
-<!-- END page_block -->
-<!-- BEGIN error_block -->
-<b><center>{error_message}</b></center><br><br>
-<!-- END error_block -->
Index: trunk/calendar/templates/default/edit.tpl
===================================================================
--- trunk/calendar/templates/default/edit.tpl	(revision 4473)
+++ trunk/calendar/templates/default/edit.tpl	(revision 5132)
@@ -10,43 +10,4 @@
 </style>
 <script language="JavaScript">
-
-        function addAttach(){
-            var divFiles = document.getElementById("divFiles");
-            if (! divFiles)
-                    return false;
-
-            if (divFiles.lastChild)
-                    var countDivFiles = parseInt(divFiles.lastChild.id.split('_')[1]) + 1;
-
-            if (! countDivFiles)
-                    var countDivFiles = 1;
-
-            divFile = document.createElement('DIV');
-
-
-            divFile.innerHTML = "<input type='file' size='50' maxLength='255' id='"+"inputFile_"+countDivFiles+"' name='cal[attachment][]'>";
-
-
-            var linkFile = document.createElement("A");
-            linkFile.id = "linkFile_"+countDivFiles;
-            linkFile.href='javascript:void(0)';
-            linkFile.onclick=function () {removeFile(this.id.replace("link","div")); return false;};
-            linkFile.innerHTML="Remove";
-            //divFile.innerHTML += "&nbsp;&nbsp;";
-            divFile.appendChild(linkFile);
-            divFile.id = "divFile_"+countDivFiles;
-            divFiles.appendChild(divFile);
-
-
-
-            return document.getElementById("inputFile_"+countDivFiles);
-        }
-
-        function removeFile(id){
-            var border_id = id.substr(8,1);
-            var el = Element(id);
-            el.parentNode.removeChild(el);
-        }
-
 	self.name="first_Window";
 	function accounts_popup()
@@ -54,30 +15,11 @@
 		Window1=window.open('{accounts_link}',"Search","width=800,height=600,toolbar=no,scrollbars=yes,resizable=yes");
 	}
-
-	function show_disponibility() {
-		participants = "";
-		combo = document.getElementById('user_list');
-		if(combo.length==0) {
-			alert('Selecione os participantes');
-			return;
-		}
-
-		for (i=0;i<combo.length;i++) {
-			participants+=combo[i].value+",";
-		}
-		url = 'index.php?menuaction=calendar.uicalendar.disponibility&participants='+participants+'&date='+document.getElementById('start[str]').value;
-
-		//alert(url);
-		document.getElementById('frame_disponibility').src = url;
-		document.getElementById('disponibility').style.display='';
-		//window.open(url);
-	}
 </script>
 <center>
 <font color="#000000" face="{font}">
-
-<form action="{action_url}" method="post" name="app_form" enctype="multipart/form-data">
+<form action="{action_url}" method="post" name="app_form" id="formEvent">
 {common_hidden}
 <table id="editFormTable" border="0" width="90%"   class="prefTable">
+<input id="set_participants" style="visibility: hidden;" value="{lang_set_participants}"></input>
  <tr>
   <td colspan="2">
@@ -94,5 +36,5 @@
 		var alert_field = '{alert_msg}';
 	</script>
-  	<input id="submit_button" style="font-size:10px" type="submit" value="{submit_button}" onClick="return submitValues(alert_field);"></div></form>
+  	<input id="submit_button" style="font-size:10px" type="button" value="{submit_button}"  onclick="javascript:submitValues(this);" ></div></form>
   </td>
   <td>{cancel_button}</td>
Index: trunk/calendar/templates/default/week.tpl
===================================================================
--- trunk/calendar/templates/default/week.tpl	(revision 3193)
+++ trunk/calendar/templates/default/week.tpl	(revision 5132)
@@ -1,25 +1,2 @@
-<table id="calendar_index_table" border="0" width="100%" cols="5">
-	<tr>
-		<td align="left" valign="top" width="20%">
-		</td>
-		<td align="center" valign="middle" width="15%">
-			<b>{prev_week_link}</b>
-		</td>
-		<td align="center" width="30%">
-			<span class="calendar_month_identifier">
-				{week_identifier}
-			</span>
-				<br />
-			<span class="calendar_user_identifier">
-				:&nbsp;{username}&nbsp;:
-			</span>
-		</td>
-		<td align="center" valign="middle" width="15%">
-			{next_week_link}
-		</td>
-		<td align="right" valign="top" width="20%">
-		</td>
-	</tr>
-</table>
 {week_display}
 <!-- from month_day.tpl -->
Index: trunk/calendar/templates/default/day_cal.tpl
===================================================================
--- trunk/calendar/templates/default/day_cal.tpl	(revision 4707)
+++ trunk/calendar/templates/default/day_cal.tpl	(revision 5132)
@@ -1,226 +1,24 @@
 <!-- BEGIN day -->
-
-
-<script src="calendar/js/dhtmlx/codebase/dhtmlxscheduler_debug.js" type="text/javascript" charset="utf-8"></script>
-<script src="calendar/js/dhtmlx/codebase/ext/dhtmlxscheduler_pdf.js"></script>
-<script src="calendar/js/dhtmlx/sources/locale_pt.js"></script>
-<script src="calendar/js/dhtmlx/sources/ext/ext_new_week.js"></script>
-<link rel="stylesheet" href="calendar/js/dhtmlx/codebase/dhtmlxscheduler.css" type="text/css" charset="utf-8">
-
-<div class="th" style='width:1000px; height:470px;'>
-
-    <div  id="scheduler_here" class="dhx_cal_container" style='width:100%; height:100%;'>
-	<div class="dhx_cal_navline" style="display: none;">
-	    <div class="dhx_cal_prev_button" style="display: none;">&nbsp;</div>
-	    <div class="dhx_cal_next_button" style="display: none;">&nbsp;</div>
-	    <div class="dhx_cal_today_button" style="display: none;" ></div>
-	    <div class="dhx_cal_date" style="display:none;"></div>
-	    <div class="dhx_cal_tab" name="day_tab" style="right:204px; display: none;"></div>
-	    <div class="dhx_cal_tab" name="week_tab" style="right:140px; display: none;"></div>
-	    <div class="dhx_cal_tab" name="month_tab" style="right:76px; display: none;"></div>
- </div>
-	<div class="dhx_cal_header" style="visibility: hidden;">
-	</div>
-	<div class="dhx_cal_data">
-	</div>
+<div class="th">
+ <table class="calendar_dayview_maintable" width="100%" cellpadding="0">
+{row}
+</table>
     </div>
-</div>
-
-<div style='clear:left;margin-left:50px;margin-right:50px;text-align:center'>
-<br />
-    {iprint}
-    <input type="radio" name="group1" id="list" value="list" onclick="printMode(this.value);" checked> Lista
-    <input type="radio" name="group1" id="grid" value="grid" onclick="printMode(this.value);" > Grade
-
-</div>
-
-<body onload="loadScheduler()"></body>
-
-<script>
-
-    function printMode(printType)
-    {
-	if(printType == "grid")
-	{
-	    //document.getElementById("listPrint").style.visibility = 'hidden';
-	    document.getElementById("printFriendly").onclick = function(){
-									    scheduler.toPDF('calendar/js/dhtmlx/server/generate.php');
-									 };
-	}
-	else if(printType =="list")
-	{
-	    //document.getElementById("listPrint").style.visibility = '';
-	    document.getElementById("printFriendly").onclick = function(){
-									    window.open("index.php?menuaction=calendar.uicalendar.month"+"{param}","","width=600,height=600,toolbar=no,scrollbars=yes,resizable=no");
-									 };
-	}
-    }
-
-    function loadScheduler()
-    {
-
-        //document.getElementById("listPrint").style.visibility = 'hidden';
-	document.getElementById("printFriendly").onclick = function(){
-									if(document.getElementById("grid").checked == true)
-									{
-									    //document.getElementById("listPrint").style.visibility = 'hidden';
-									    scheduler.toPDF('calendar/js/dhtmlx/server/generate.php');
-									}
-									else
-									{
-									    window.open("index.php?menuaction=calendar.uicalendar.month"+"{param}","","width=600,height=600,toolbar=no,scrollbars=yes,resizable=no");
-									}
-								     };
-
-	//inicializa o calendário
-	scheduler.showLightbox = function(id)
-	{
-
-	    var ev = scheduler.getEvent(id);
-
-	    var bgYea = ev.start_date.getFullYear().toString();
-	    var bgMon = (ev.start_date.getMonth() + 1).toString();
-
-	    if (bgMon.length < 2)
-	    {
-		bgMon = '0' + bgMon;
-	    }
-
-	    var bgDay = ev.start_date.getDate().toString();
-
-	    if (bgDay.length < 2)
-	    {
-		bgDay = '0' + bgDay;
-	    }
-
-	    var bgHou = ev.start_date.getHours();
-	    var bgMin = ev.start_date.getMinutes();
-
-	    window.location="index.php?menuaction=calendar.uicalendar.add&date=" + bgYea + bgMon + bgDay + "&hour=" + bgHou + "&minute=" + bgMin;
-
-	}
-
-        scheduler.templates.event_class=function(start,end,event){
-                  if (event.rejected)
-                    return "rejected";
-                  if (event.intersection)
-                     return "intersection";
-
-        }
-
-	scheduler.templates.event_header=function(start,end,event){
-
-	    var imgs = '';
-	    if(event.recur && event.recur != false)
-	    {
-		imgs += '<img width="10px" height="10px" border="0" title="'+event.recurTitle+'" src="calendar/templates/{templateSet}/images/recur.png"/>';
-	    }
-
-	    if(event.participants == 1)
-	    {
-		imgs += " " + '<img width="11px" height="10px" border="0" title="'+event.participants_title+'" src="calendar/templates/{templateSet}/images/multi_3.png"/>';
-	    }
-	    else
-	    {
-		imgs += " " + '<img width="11px" height="10px" border="0" title="'+event.participants_title+'" src="calendar/templates/{templateSet}/images/single.png"/>';
-	    }
-
-	    if(event.attachments == 1)
-	    {
-		imgs += " " + '<img width="10px" height="10px" border="0" title="'+event.attachmentsTitle+'" src="calendar/templates/{templateSet}/images/clip.png"/>';
-	    }
-
-	    if(event.isPublic == 0)
-	    {
-		imgs += " " + '<img width="11px" height="10px" border="0" title="'+event.isPublicTitle+'" src="calendar/templates/{templateSet}/images/private.png"/>';
-	    }
-
-	    if(event.alarm == 1)
-	    {
-		imgs += " " + '<img width="11px" height="10px" border="0" title="'+event.alarmTitle+'" src="calendar/templates/{templateSet}/images/alarm.png"/>';
-	    }
-
-	    if(event.title)
-	    {
-		var eventTitle = (" - ") + event.title;
-	    }
-	    else
-	    {
-		var eventTitle = "";
-	    }
-
-	    //hide/show event description according to the preference title_view
-	    if(event.title_view == 0)
-	    {
-		if(event.descOnTitle == 1) //to show, or not, description beside the title
-		{
-		    var eventDescOnTitle = (" - ") + event.text;
-		}
-		else
-		{
-		    var eventDescOnTitle = '';
-		}
-	    }
-	    else
-	    {
-		var eventDescOnTitle = '';
-	    }
-
-	    return imgs + " " + scheduler.templates.hour_scale(start) + " " + scheduler.templates.hour_scale(end) + eventTitle + eventDescOnTitle;
-	}
-
-	scheduler.xy.scale_height=0;
-	scheduler.xy.nav_height=0;
-	scheduler.config.hour_size_px = {hour_size_px} ;
-	scheduler.config.scroll_hour = 8;
-	scheduler.config.time_step = 30; //- {numeric} minimal date size step in minutes;
-	scheduler.config.start_on_monday = true; //{boolean} if true week starts from Monday ( if false, week start from Sunday);
-	scheduler.config.first_hour = {hora_inicial};
-	scheduler.config.last_hour = {hora_final};
-	scheduler.config.drag_resize = false;//- {boolean} allows resizing events by dnd;
-	scheduler.config.drag_move = false;//- {boolean} allows moving events by dnd;
-	scheduler.config.drag_create = false;// - {boolean} allows creating new events by dnd;
-	scheduler.config.dblclick_create = true;//- {boolean} allows creating new events by double click;
-	scheduler.config.edit_on_create = true;//- {boolean} shows form on new event creation;
-	scheduler.config.details_on_create = true;//- {boolean} uses extended form on new event creation by drag or by dbl-click (option doesn't affect monthly view - where details form is the only way to change data);
-	scheduler.config.details_on_dblclick = true;// - {boolean} uses extended form on event double-click (double-click on existing event).
-	scheduler.attachEvent("onClick",function(){ return false;});
-	scheduler.attachEvent("onDblClick",function(id){
-				var ev = scheduler.getEvent(id);
-				var id_mod = ev.id;
-				if(ev.recur!=false) id_mod = ev.id.split('rc',1)[0]+"&date="+ev.recur;
-				window.location="index.php?menuaction=calendar.uicalendar.view&cal_id="+id_mod;});
-
-	scheduler.config.xml_date="%Y-%m-%d %H:%i";
-	scheduler.init('scheduler_here',new {date},"day");
-	scheduler.parse({events_json},"json");
-
-    }
-
-    function callViewEvent(id) //double click on events title bar
-    {
-	var ev = scheduler.getEvent(id);
-	var id_mod = ev.id;
-	if(ev.recur!=false) id_mod = ev.id.split('rc',1)[0]+"&date="+ev.recur;
-	window.location="index.php?menuaction=calendar.uicalendar.view&cal_id="+id_mod;
-    }
-
-</script>
-
 <!-- END day -->
-<!-- BEGIN day_event_off -->
-	<!--<font class="event-on">{event}</font>-->
-<!-- END day_event_off -->
-<!-- BEGIN day_time -->
-	<!--{time}-->
-     <!--<td class="time" nowrap>{open_link}{time}{close_link}</td>-->
-<!-- END day_time -->
 <!-- BEGIN day_row -->
-    <!--<font style="font-size: 8pt;">{event}</font>-->
+    <tr>{time}{event}
+    </tr>
 <!-- END day_row -->
 <!-- BEGIN day_event_on -->
-	<!--<font class="event-on">{event}</font>-->
+     <td class="event-on"{extras}>&nbsp;{event}</td>
 <!-- END day_event_on -->
+<!-- BEGIN day_event_off -->
+     <td class="event-off"{extras}>&nbsp;{event}</td>
+<!-- END day_event_off -->
 <!-- BEGIN day_event_holiday -->
-	<!--{event}-->
+     <td class="event-holiday"{extras}>&nbsp;{event}</td>
 <!-- END day_event_holiday -->
+<!-- BEGIN day_time -->
+     <td class="time" nowrap>{open_link}{time}{close_link}</td>
+<!-- END day_time -->
+
Index: trunk/calendar/templates/default/event_link.tpl
===================================================================
--- trunk/calendar/templates/default/event_link.tpl	(revision 4001)
+++ trunk/calendar/templates/default/event_link.tpl	(revision 5132)
@@ -20,11 +20,11 @@
 
 <!-- BEGIN link_event_text -->
-	<tr style="font-size: 12px;background: #dddddd;">
-		<td valign="top" style="color: black;">
+	<tr style="font-size: 10px;background: #dddddd;">
+		<td valign="top" style="color: black; font-size: 11px;">
 			<span>
 				{time}
 			</span>
 		</td>
-		<td valign="top" style=" border: #b3b3b3 1px solid;" colspan="5">
+		<td style="font-size: 11px; border: #E8F0F0 1px solid;" colspan="3">
 			<span><b>{title}</b></span>
 			<br />
@@ -32,5 +32,4 @@
 			<span>{location}</span>
 			<br />
-			<span>{observations}</span>
 		</td>
 	</tr>
Index: trunk/calendar/templates/default/month_print.tpl
===================================================================
--- trunk/calendar/templates/default/month_print.tpl	(revision 4001)
+++ trunk/calendar/templates/default/month_print.tpl	(revision 5132)
@@ -2,15 +2,15 @@
 <table class="calendar_index_table" id="calendar_index_table"  width="100%" cols="5">
 	<tr>
-		<td align="left" width="27%">
+		<td align="left" width="33%">
 			<span class="calendar_user_identifier">
 					{username}
 			</span>
 		</td>
-		<td align="center" width="45%">
+		<td align="center" width="33%">
 			<span class="calendar_month_identifier">
 				{month_identifier}
 			</span>
 		</td>
-		<td align="right" style="width: 27%; font-size: 14px;">
+		<td align="right" style="width: 33%; font-size: 14px;">
 			<span class="calendar_user_identifier">
 				<p>Agenda de Eventos</p>
Index: trunk/calendar/templates/default/body_email.tpl
===================================================================
--- trunk/calendar/templates/default/body_email.tpl	(revision 3350)
+++ trunk/calendar/templates/default/body_email.tpl	(revision 5132)
@@ -21,5 +21,4 @@
 <hr size='1' width='100%'>
 <table border='0' cellpadding='4' cellspacing='4' width='100%'>
-<tr><td colspan='4'><b>{question}</b></td></tr>
 <tr>
 <td width='2%' align='left'>{varbuttom}</td>
@@ -27,6 +26,6 @@
 <td width='2%' align='left' valign='top'>{varbuttom2}</td>
 <td width='2%' align='left' valign='top'>{varbuttom5}</td>
-<td width='2%' align='left' valign='top'>{varbuttom4}</td>
-<td width='94%' align='left' valign='top'>{varbuttom3}</td>
+<td width='2%' align='left' valign='top'>{varbuttom3}</td>
+<td width='92%' align='left' valign='top'>{varbuttom4}</td>
 </tr>
 </table>
