<?php

/* $Id: index.php,v 1.208 2006/04/16 14:40:44 leyeti Exp $ */
error_reporting  (E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
$myEnv["module"] = "calendar";
$myEnv["output"] = "html";

header('P3P: CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM"'); //MSIE6 P3P header
include("../../config.inc.php");
include(INCLUDEPATH . "container.inc.php");
include(INCLUDEPATH . "mSelectBox.class.php");

// adding file revision into global array
if(function_exists("revisionInit")) revisionInit("\$Revision: 1.208 $", __FILE__);

//include(CAL1_INC_DIR."check_settings.inc.php");

//// |--| //// Date langage :
include(CAL1_INC_DIR."date_lang.php");
$_SESSION["date_lang"] = array ("language" => $_SESSION["MGW"]->spkz,
								"lang_dir" => CAL1_DIR."lang/"
								);
///////////////

/// |--| ////
//echo $conn->DBTimeStamp(1067533215)."<BR>";
/////////////
// |--| : temporaire:
//pour traiter le texte :
function text_process($text){
return $text;
}
///

if(!isset($_SESSION['calendarid'])) {
	$sql = "SELECT id, ".$conn->Concat("firstname", "' '", "lastname")." AS name FROM mgw_users WHERE NOT(level=".UDELETED.") AND id = ".(int)$_SESSION["MGW"]->userid;
	if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	$row = $res->FetchRow();
	$_SESSION['calendarid'] = $_SESSION["MGW"]->userid;
	$_SESSION['calendarname'] = $row["name"];	// Owner - Name of calendar
}

$date = (isset($_GET["date"])) ? $_GET["date"] : (IsSet($_POST["date"]) ? $_POST["date"] : "");
$end_date = (isset($_GET["end_date"])) ? $_GET["end_date"] : (IsSet($_POST["end_date"]) ? $_POST["end_date"] : "");

$newtype = (isset($_GET["newtype"])) ? $_GET["newtype"] : (IsSet($_POST["newtype"]) ? $_POST["newtype"] : "");
$parties = (isset($_GET["parties"])) ? $_GET["parties"] : (IsSet($_POST["parties"]) ? $_POST["parties"] : "");

$gotodate = IsSet($_POST["gotodate"]) ? $_POST["gotodate"] : "";
//action :
if(isset($_GET["action"]) || isset($_POST["action"])) $action = (isset($_GET["action"])) ? $_GET["action"] : $_POST["action"];

$new = (isset($_GET["new"])) ? $_GET["new"] : (IsSet($_POST["new"]) ? $_POST["new"] : "");

$update = (isset($_GET["update"])) ? $_GET["update"] : (IsSet($_POST["update"]) ? $_POST["update"] : "");
$tsupdate = (isset($_GET["tsupdate"])) ? $_GET["tsupdate"] : (IsSet($_POST["tsupdate"]) ? $_POST["tsupdate"] : "");
$participants = (isset($_GET["participants"])) ? $_GET["participants"] : (IsSet($_POST["participants"]) ? $_POST["participants"] : array());
//hack to prevent a participant to be more than one time in an appointment
$participants = array_unique($participants);

$ind = (isset($_GET["ind"])) ? $_GET["ind"] : (IsSet($_POST["ind"]) ? $_POST["ind"] : "");
$appointment_attribute = (isset($_GET["appointment_attribute"])) ? $_GET["appointment_attribute"] : (IsSet($_POST["appointment_attribute"]) ? $_POST["appointment_attribute"] : "");

$appointment_start = (isset($_GET["appointment_start"])) ? $_GET["appointment_start"] : (IsSet($_POST["appointment_start"]) ? $_POST["appointment_start"] : "");
$appointment_end = (isset($_GET["appointment_end"])) ? $_GET["appointment_end"] : (IsSet($_POST["appointment_end"]) ? $_POST["appointment_end"] : "");


$id_appt_type = (isset($_GET["id_appt_type"])) ? $_GET["id_appt_type"] : (IsSet($_POST["id_appt_type"]) ? $_POST["id_appt_type"] : "");
$id_location_type = (isset($_GET["id_location_type"])) ? $_GET["id_location_type"] : (IsSet($_POST["id_location_type"]) ? $_POST["id_location_type"] : "");
$availability = (isset($_GET["availability"])) ? $_GET["availability"] : (IsSet($_POST["availability"]) ? $_POST["availability"] : "");

$serial_start_month = (isset($_GET["serial_start_month"])) ? $_GET["serial_start_month"] : (IsSet($_POST["serial_start_month"]) ? $_POST["serial_start_month"] : "");
$serial_start_day = (isset($_GET["serial_start_day"])) ? $_GET["serial_start_day"] : (IsSet($_POST["serial_start_day"]) ? $_POST["serial_start_day"] : "");
$serial_start_year = (isset($_GET["serial_start_year"])) ? $_GET["serial_start_year"] : (IsSet($_POST["serial_start_year"]) ? $_POST["serial_start_year"] : "");

$serial_end_month = (isset($_GET["serial_end_month"])) ? $_GET["serial_end_month"] : (IsSet($_POST["serial_end_month"]) ? $_POST["serial_end_month"] : "");
$serial_end_day = (isset($_GET["serial_end_day"])) ? $_GET["serial_end_day"] : (IsSet($_POST["serial_end_day"]) ? $_POST["serial_end_day"] : "");
$serial_end_year = (isset($_GET["serial_end_year"])) ? $_GET["serial_end_year"] : (IsSet($_POST["serial_end_year"]) ? $_POST["serial_end_year"] : "");

$start_month = (isset($_GET["start_month"])) ? $_GET["start_month"] : (IsSet($_POST["start_month"]) ? $_POST["start_month"] : "");
$start_day = (isset($_GET["start_day"])) ? $_GET["start_day"] : (IsSet($_POST["start_day"]) ? $_POST["start_day"] : "");
$start_year = (isset($_GET["start_year"])) ? $_GET["start_year"] : (IsSet($_POST["start_year"]) ? $_POST["start_year"] : "");


// check if serial_start date isn't earlier than start date (fix bug #950796):
$serial_end_ts = mktime(0,0 ,0 , $serial_end_month , $serial_end_day, $serial_end_year);
$serial_start_ts = mktime(0,0 ,0 , $serial_start_month , $serial_start_day, $serial_start_year);
$start_ts = mktime(0,0 ,0 , $start_month , $start_day, $start_year);
if ($action=="editserial" && $serial_end_ts<$serial_start_ts) {
    $serial_end_month = $serial_start_month;
	$serial_end_day = $serial_start_day;
	$serial_end_year = $serial_start_year;
}
else if ($serial_end_ts<$start_ts) {
    $serial_end_month = $start_month;
	$serial_end_day = $start_day;
	$serial_end_year = $start_year;
}
//end check

// if start = end , so  $appointment_attribute = 0;
if ($action=="editserial"
	&& $serial_end_month == $serial_start_month
 	&& $serial_end_day == $serial_start_day
 	&&	$serial_end_year == $serial_start_year
	) {
    $appointment_attribute = 0;
}
else if ($serial_end_month == $start_month
 	&& $serial_end_day == $start_day
 	&&	$serial_end_year == $start_year
	) {
    $appointment_attribute = 0;
}


/* FROM v 1.185 unset by |--|
// check if start_day, start_month and start_year should override appointment_start (bug 771454)
// don't look at the code :/
if(isset($_POST['start_day'])){
    $target_start = mktime($_SESSION["MGW"]->settings["calendar_viewfrom"],0,0, $_POST['start_month'], $_POST['start_day'], $_POST['start_year']);
    if($date != $target_start && ($date == mktime($_SESSION["MGW"]->settings["calendar_viewfrom"],0,0, date('m'), date('d'), date('Y')))){
	$target_diff = $date - $target_start;echo "hallo::".date('H:i',$date).'::'.date('H:i',$target_start);
	$appointment_start = $appointment_start - $target_diff;
	$appointment_end = $appointment_end - $target_diff;
    }
}
*/


/*if (count($participants)>1) {
    $newtype="meeting";
}
*/

//create array to now if it's IMPOSED or SUBJECTED :
if ($newtype=="meeting") {
$part=array();
	for($i=0;$i<count($participants);$i++){
		if (isset($_POST["part_".$participants[$i]])) {
		   $part []= $_POST["part_".$participants[$i]];
		}
	}
//hack to prevent a participant to be more than one time in an appointment
$part = array_unique($part);
}


// redirect to default view
if($_SESSION["MGW"]->settings["calendar_defaultview"]!="" && (!isset($_GET['submenu']) || $_GET['submenu']!="yes") &&
   empty($date) && empty($gotodate) && empty($action) && empty($new) &&
   empty($update) && empty($tsupdate) && trim($_SESSION["MGW"]->settings["calendar_defaultview"])!="index.php"){
    redirect($_SESSION["MGW"]->settings["calendar_defaultview"]."?".SID);
}

$timemask = $_SESSION["MGW"]->settings["timefmt"];

// get the settings
$holitemp      = $_SESSION["MGW"]->settings["calendar_holiday_system"];			// calendar holiday system (country)
$interval      = $_SESSION["MGW"]->settings["calendar_interval"];			// calender interval length in minutes
$interval_sec  = 60 * $interval;					// calender interval length in seconds
$starthour     = $_SESSION["MGW"]->settings["calendar_viewfrom"];			// start hour of day-view
$endhour       = $_SESSION["MGW"]->settings["calendar_viewto"];			// last  hour of day-view

// SET variable $date
// if $date is not passed, set $date to today
// if $gotodate (is passed by submit for datesearch in main template of day-view) is set,
//    check validity of gotodate and set date to gotodate

if (empty($date) && empty($gotodate)) {
    $date = mktime(0,0,0, date("m", time()), date("d", time()), date("Y", time()));
}
else if (!empty($gotodate)) {
    // only present in wml template
    if (isset($_POST["gdatum"])) {
	$gtag = substr((int)$_POST["gdatum"],0,2);
	$gmonat = substr((int)$_POST["gdatum"],3,2);
	$gjahr = substr((int)$_POST["gdatum"],6,4);
    }
    else{
	$gmonat = (int)$_POST["gmonat"];
	$gtag = (int)$_POST["gtag"];
	$gjahr = (int)$_POST["gjahr"];
    }

    $gtag = ($gtag > 0) ? $gtag : $_SESSION['calendar_day'];
    $gmonat = ($gmonat > 0) ? $gmonat : $_SESSION['calendar_month'];
    $gjahr = ($gjahr > 0) ? $gjahr : $_SESSION['calendar_year'];

    if (checkdate($gmonat, $gtag, $gjahr)){
	$date  = mktime(0,0,0, $gmonat, $gtag, $gjahr);
	$_SESSION['calendar_day'] = $gtag;
	$_SESSION['calendar_month'] = $gmonat;
	$_SESSION['calendar_year']  = $gjahr;
    }
    else if (empty($date)) {
	$date = mktime(0,0,0, date("m", time()), date("d", time()), date("Y", time()));
    }
}

//coherence : if end_date is before date(start):
if ($end_date<$date+$interval_sec) {
    $end_date = $date;//+$interval_sec;
}


$date_str =  str_pad( date("d", $date).date("m", $date).date("Y", $date),8,"0",STR_PAD_LEFT);
$smarty->assign("date_str", $date_str);

//
// TODO: new/update app. should ALWAYS use $start_day!!!!
//

// set date to the start date of the new or updated appointment
if(!empty($new) || !empty($update) || !empty($tsupdate)) {
    if (isset($_POST["start_day"])) {
	$date = mktime(0, 0, 0, (int)$_POST["start_month"], (int)$_POST["start_day"], (int)$_POST["start_year"]);
    }
    else {
	$date = mktime(0, 0, 0, (int)$_POST["serial_start_month"], (int)$_POST["serial_start_day"], (int)$_POST["serial_start_year"]);
    }
}

// Set certain values for time-handling
$actual_date_arr = getdate($date);

// Start time (according to settings) of selected day
$start_time =  mktime(0,0,0, $actual_date_arr["mon"], $actual_date_arr["mday"], $actual_date_arr["year"]) + $starthour * 3600;
$app_start_time =  mktime(0,0,0, $actual_date_arr["mon"], $actual_date_arr["mday"], $actual_date_arr["year"]);
//$app_start_time = $start_time;

// End time (according to settings) of selected day
$end_time   =  mktime(0,0,0, $actual_date_arr["mon"], $actual_date_arr["mday"], $actual_date_arr["year"]) + $endhour   * 3600;
$app_end_time   =  mktime(0,0,0, $actual_date_arr["mon"], $actual_date_arr["mday"], $actual_date_arr["year"]) + 23.5 * 3600;
//$app_end_time = $end_time;




// ==============================================
// action : vCal export
// ==============================================
if(IsSet($action) && $action == "vCal") {
	$sql = "SELECT * FROM mgw_calendar WHERE id = ".(int) $_GET["id"];
	if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	$row = $res->FetchRow();

	$description = StrTr(str_decode($row["subject"]), "\xA9\xAB\xAE\xB9\xBB\xBE", "\x8A\x8D\x8E\x9A\x9D\x9E");
	$summary = StrTr(str_decode($row["subject_summ"]), "\xA9\xAB\xAE\xB9\xBB\xBE", "\x8A\x8D\x8E\x9A\x9D\x9E");
	// TODO ---> id_location type...
	$location = StrTr(str_decode($row["location"]), "\xA9\xAB\xAE\xB9\xBB\xBE", "\x8A\x8D\x8E\x9A\x9D\x9E");
	$vCalStart = SubStr($row['date'],0,8)."T".SubStr($row['date'],8,4)."00";
	$end = $row["duration"]*60 + mktime(SubStr($row["date"],8,2),SubStr($row["date"],10,2),SubStr($row["date"],12,2),SubStr($row["date"],4,2),SubStr($row["date"],6,2),SubStr($row["date"],0,4));
	$vCalEnd = date("Ymd\THi00", $end);

	$out  = "BEGIN:VCALENDAR\r\n";
	$out .= "PRODID:moreGroupWare\r\n";
	$out .= "VERSION:1.0\r\n";
	$out .= "BEGIN:VEVENT\r\n";
	$out .= "DTSTART:".$vCalStart."\r\n";
	$out .= "DTEND:".$vCalEnd."\r\n";
	$out .= "LOCATION;ENCODING=QUOTED-PRINTABLE:".quoted_printable_encode($location, StrLen("LOCATION;ENCODING=QUOTED-PRINTABLE:"))."\r\n";
	$out .= "UID:".strToUpper(md5("MGW".$_GET["id"]))."\r\n";
	$out .= "DESCRIPTION;ENCODING=QUOTED-PRINTABLE:".quoted_printable_encode($description, StrLen("DESCRIPTION;ENCODING=QUOTED-PRINTABLE:"))."\r\n";
	$out .= "SUMMARY;ENCODING=QUOTED-PRINTABLE:".quoted_printable_encode($summary, StrLen("SUMMARY;ENCODING=QUOTED-PRINTABLE:"))."\r\n";
	$out .= "PRIORITY:3\r\n";
	$out .= "END:VEVENT\r\n";
	$out .= "END:VCALENDAR\r\n";


	if (IsSet($_SESSION["MGW"]->settings["calendar_vcal_method"]) && $_SESSION["MGW"]->settings["calendar_vcal_method"] == "as_email") {
		$webmail_temp_dir = CACHE_FOLDER."../webmail2/";
		error_reporting (E_ERROR | E_PARSE);
		if (!is_writeable($webmail_temp_dir."sendmail/")) die("Could not write to Webmail2-Cache");
		error_reporting  (E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
		$email_filename=$webmail_temp_dir."sendmail/" . session_id() . "######" . "MGW".$_GET['id'].".vcs";

		$fp = fopen ($email_filename, "w");
		fwrite($fp,$out);
		fclose($fp);

		$start = mktime(SubStr($row["date"],8,2),SubStr($row["date"],10,2),SubStr($row["date"],12,2),SubStr($row["date"],4,2),SubStr($row["date"],6,2),SubStr($row["date"],0,4));
		$end = $row["duration"]*60 + mktime(SubStr($row["date"],8,2),SubStr($row["date"],10,2),SubStr($row["date"],12,2),SubStr($row["date"],4,2),SubStr($row["date"],6,2),SubStr($row["date"],0,4));

		$start = date("l, d. F Y H:i:s (T)",$start);
		$end = date("l, d. F Y H:i:s (T)",$end);

		$HTTP_SESSION_VARS["webmail2_compose_attach_msgbody"]="Start: ".$start."\nEnd: ".$end."\nWhere: ".$location;
		$HTTP_SESSION_VARS["webmail2_compose_attach_subject"]="MGW calendar event: ".$summary;

		header("Location: ../webmail2/index.php?rightframe=sendmail.php?import=true");
	} else {
		header('Content-Type: text/x-vCalendar');
		header('Content-Length: '. StrLen($out));
		header('Content-Disposition: inline; filename="MGW'.$_GET['id'].'.vcs";');
		header('Expires: Wed, 11 Nov 1998 11:11:11 GMT');
		header('Cache-Control: no-cache');
		header('Cache-Control: must-revalidate');

	  echo $out;
	}
	die;
}

/// |--| ///
// ==============================================
// action : validate a subjected appointment : class 0 -> class 2
// ==============================================
if (IsSet($action) && $action=="validate") {


	$id = (int) $_GET["id"];
	$userid=$_SESSION["MGW"]->userid;
	// verif:
	$sql = "SELECT userid FROM mgw_calendar where id = '".$id."' and userid='$userid'";
	if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	if ($res->NumRows() > 0) {//if it's an appointment of current user => ok

		// validate ONE appointment for ONE participant :
		//determine if appointment can be validated or just on standby (wait for others validations)
		$onStandby = FALSE;
		$sql = "SELECT id_class FROM mgw_calendar WHERE id='$id' AND userid!='$userid'";
		if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
		while ($row=$res->FetchRow()) {
			// if at least one of all is aborted(3) OR subjected(0) => new class = standby
			$onStandby = $onStandby || ( ($row["id_class"]==3 || $row["id_class"]==0) );
		}
		// if at least one of all is aborted OR subjected => new class = standby
		if ($onStandby) {
			$sql = "UPDATE mgw_calendar SET id_class='1', date=date Where id='$id' and userid='$userid'";
			if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
		}
		else {
		// if all are on standby => ALL must be validated (class=2)
		$sql = "UPDATE mgw_calendar SET id_class='2', date=date Where id='$id'";
		if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
		}

	}
	else exit(Lang::getLanguageString("forbidden")."<br> <a href=\"javascript:history.go(-1);\">back</a>");

	unset($action);
	redirect("index.php?&date=$date&".SID);

}

/*
*
*  rien est réellement supprimé: ABORT :  -> class=3
*  les class=3 (abort) ne sont jamais affichés (day, week, month)
*/
// ==============================================
// action : abort a subjected OR onStandby appointment : class 0/1 -> class 3
// ==============================================
if (IsSet($action) && $action=="abort") {
	$id = (int) $_GET["id"];
	$userid=$_SESSION["MGW"]->userid;
	// verif:
	$sql = "SELECT userid,id_class FROM mgw_calendar where id = '".$id."' and userid='$userid'";
    if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
   	//if the appointment is that of the current user  AND if the appointment can be aborted=> ok
	$row=$res->FetchRow();
	if ($res->NumRows() > 0 && ($row["id_class"]==0 || $row["id_class"]==1)) {
		$sql = "UPDATE mgw_calendar SET id_class='3' Where id='$id' and userid='$userid'";
		if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	}
	else exit(Lang::getLanguageString("forbidden")."<br> <a href=\"javascript:history.go(-1);\">back</a>");
    unset($action);
	redirect("index.php?&date=$date&".SID);
}


////////////

// ==============================================
// action : delete an appointment in database
// ==============================================
if (isset($_POST["db_delete"])) {
    /*db_delete_date_rep((int)$_POST["id"], (int)$_POST["rep_opt"], (int)$_POST["tn_opt"], $_SESSION["MGW"]->userid);
    unset($action);*/


	$id = (int)$_POST["id"];
	$rep_opt = isset($_POST["rep_opt"]) ? (int)$_POST["rep_opt"] : "";
	$tn_opt = isset($_POST["tn_opt"]) ? (int)$_POST["tn_opt"] : "";
	$userid = $_SESSION['calendarid']; //$_SESSION["MGW"]->userid;

	// check if current user can delete :
	if (!is_modifiable_by_current_user($id,$userid)) {
	    exit(Lang::getLanguageString("forbidden")."<br> <a href=\"javascript:history.go(-1);\">back</a>");
	}

	$sql_part =" ( ";
	//get participants:
	$sql  = "SELECT a.*, b.username FROM mgw_calendar a, mgw_users b WHERE NOT(b.level=".UDELETED.") AND a.id = $id AND b.id = a.userid";
    if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    while($row  = $res->FetchRow()){
		if (IsSet($_POST["del_".$row["userid"]]) && $_POST["del_".$row["userid"]]!=""){
		    $sql_part .= $row["userid"].", ";

			// NOTIFY participants :
			// MAIL:
		//		$GLOBALS['notify']->message($msg, NOTIFY_MAIL, 'u:'.$row["username"]);
			// + send on screen message
		//		$GLOBALS['notify']->message($msg, NOTIFY_SCREEN, 'u:'.$row["username"]);
		}
	}// end while

	$sql_part .= "0 )";

	$sql  = "SELECT * FROM mgw_calendar WHERE id = $id AND userid = ".$userid;
    if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    $row  = $res->FetchRow();
    $group_id = $row["dategroup_id"];
    $sdate  = $row["date"];
    if ($group_id == 0){ $rep_opt=0; }

    // NO repeat: ONLY this appointment, delete for selected users:
	if ($rep_opt==0 && $id > 0 && $userid > 0) $sql2 = "DELETE FROM mgw_calendar WHERE id = $id and userid IN $sql_part";

	//elseif ($rep_opt==0 && $tn_opt==1 && $id > 0) $sql2 = "DELETE FROM mgw_calendar WHERE id = $id";

	//REPEAT : all appointments from this one, delete for selected users:
    elseif ($rep_opt==2 && $group_id > 0 && $userid > 0) $sql2 = "DELETE FROM mgw_calendar WHERE dategroup_id = $group_id and userid IN $sql_part and date >= '$sdate'";

	//elseif ($rep_opt==2 && $tn_opt==1 && $group_id > 0) $sql2 = "DELETE FROM mgw_calendar WHERE dategroup_id = $group_id and date >= '$sdate'";
    //REPEAT : all appointments of the series, delete for selected users:
	elseif ($rep_opt==3 && $group_id > 0 && $userid > 0) $sql2 = "DELETE FROM mgw_calendar WHERE dategroup_id = $group_id and userid IN $sql_part";
    //elseif ($rep_opt==3 && $tn_opt==1 && $group_id > 0) $sql2 = "DELETE FROM mgw_calendar WHERE dategroup_id = $group_id";

	if($sql2 == "") return; // HACK (or FIX?) for bug 608097
    if(!$res = $conn->Execute($sql2)) exit(showSQLerror($sql2, $conn->ErrorMsg(), __LINE__, __FILE__));


	 unset($action);
}


// ============================================================
// action: change owner of calender
// 	       set session-variables calendarid / calendarnames
// ============================================================
if (isset($_POST["new_calendarid"])) {
    if ($_POST["new_calendarid"]=="all") { // selected calendar for all users
	$_SESSION['calendarid'] = "all";
	$_SESSION['calendarname'] = Lang::getLanguageString("calendarownerall"); // translated all
    }
    else {
	$sql = "SELECT id, ".$conn->Concat("firstname", "' '", "lastname")." AS name FROM mgw_users WHERE NOT(level=".UDELETED.") AND id = ".(int)$_POST["new_calendarid"];
	if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	$row = $res->FetchRow();
	$_SESSION['calendarid'] = (int)$_POST["new_calendarid"];	// Owner - ID of calendar
	$_SESSION['calendarname'] = $row["name"];	// Owner - Name of calendar
    }
    unset($chgcal);
}



// ==============================================
// action: create/update appointment in database
// NOTE: timeseries are changed via action tsupdate, but created here!
// ==============================================
if (!empty($new) || !empty($update)){
    // appointment for day :  $appointment_start => start_time / $appointment_end => end_time
    // if vacation: $appointment_start => start_time / $appointment_end => end_time

	///// |--| /////
	/*if ((IsSet($_POST["day"]) && $_POST["day"]==true) || (IsSet($_POST["holiday"]) && $_POST["holiday"]==true)) {
  	  $day_ind = 1;				// indicator whether appointment belongs to complete day
	  $appointment_start = $start_time;		// timestamp of appointment start
	  $appointment_end   = $end_time;		// timestamp of appointment end

	  // if vacation: $appointment_start => start_time / $appointment_end => end_time
	  if ($_POST["holiday"] == true) {
	    $holi_ind = 1; 		// indicator whether appointment belongs to vacation day
	    $thema = "'".Lang::getLanguageString("vacation")."'";
	  }	else {
	    $holi_ind = 0;
	    $thema = $conn->quote($_POST["thema"]);
	  }
    }
    else {
	$day_ind = 0;
	$holi_ind = 0;
	$thema = $conn->quote($_POST["thema"]);
    }
	*/

	  $id_scheduling = 0 ; // default = time

	  if (IsSet($_POST["scheduling"])){

	  $id_scheduling = $_POST["scheduling"];

	  switch($id_scheduling){

	  	case 3 :	// indicator whether appointment belongs to complete day
					$appointment_start = $start_time;		// timestamp of appointment start
				  	$appointment_end   = $end_time;		// timestamp of appointment end
	 				break;

		case 2 : 	// indicator whether appointment belongs to afternoon
				  	$appointment_start = $start_time + ($end_time-$start_time)/2;		// timestamp of appointment start
				  	$appointment_end   = $end_time;		// timestamp of appointment end
					break;

		case 1 :	// indicator whether appointment belongs to morning
					$appointment_start = $start_time;		// timestamp of appointment start
					$appointment_end   = $start_time + ($end_time-$start_time)/2;		// timestamp of appointment end
					break;

		default :  	//create timestamp with date and appointement(time)
					$appt_start_array = getdate($appointment_start);// infos about hour-minute
					$date_start_array = getdate($date);				// infos about day-month-year
					$tmp_duration = $appointment_end-$appointment_start;
					$appointment_start = mktime($appt_start_array["hours"],$appt_start_array["minutes"],0,$date_start_array["mon"],$date_start_array["mday"],$date_start_array["year"]);
					$appointment_end = $appointment_start + $tmp_duration;
					break; // includes case '0'
	  	}
		// ?? a enlever + tard :
			$holi_ind = 0;
	    ////

		//echo "APPT START: ".$conn->DBTimeStamp($appointment_start)."<BR>";
		//echo "APPT END: ".$conn->DBTimeStamp($appointment_end)."<BR>";

	} // end if


	 //$thema = $conn->quote($_POST["thema"]);
	 $thema = $conn->QMagic(str_encode($_POST["thema"]));
	 /// |--| ///
	 $subject_summ = $conn->QMagic(str_encode($_POST["subject_summ"]));
	 if($_POST["availability"]==0) $telephone = "";
	 else $telephone = $_POST["telephone"];
	 $telephone = $conn->QMagic($telephone);
	 ////////
	/////////////////

    // $sql_appointment_start	: start of appointment in MySQL-dateformat
    // $duration 			: duration of appointment in minutes
    // $pr				: 1 if appointment is private

    $sql_appointment_start = $conn->DBTimeStamp($appointment_start);
    //echo $sql_appointment_start;
	$duration = ($appointment_end-$appointment_start)/60;

    $pr = ((IsSet($_POST["private"]) && $_POST["private"]!="") ? 1 : 0);

    unset($appointment_list);
    unset($conflict_list);

    //escaping string vars
    $location = $conn->QMagic(str_encode($_POST["location"]));
    $external = $conn->QMagic(str_encode($_POST["external"]));

    // ======================
    /// new appointment : CREATE IN DATABASE
    // ======================
    if (isset($new) and $new != "") {

	// in case of holiday list set attribute to 4
	if ( (IsSet($_POST["holiday"]) && $_POST["holiday"] == true) && date("YmdHis",mktime(0,0,0, $serial_end_month, $serial_end_day, $serial_end_year)) > date("YmdHis",$date))
	    $appointment_attribute = 4;

	// if creator wants to be participant, we add him at the end of array
	if(IsSet($_POST["i_will"]) && $_POST["i_will"]==true) $participants[] = $_SESSION["MGW"]->userid;

	// a) no serie of appointments
	if ($appointment_attribute == 0) {

	    // get new ids
	    $new_id  = mgw_genID('mgw__seq_calendar');
	    $new_id2 = mgw_genID('mgw__seq_calendar_tmp');
	    if ($new_id2 > $new_id && $new_id2 > 0) $new_id = $new_id2;

	    // create temporary record in calendar_tmp for all participants
	    for ($i=0; $i < count($participants); $i++) {

		$user_id_value = $participants[$i];

		$appointment_list[] = $appointment_start;
		///// |--| /////
			if ($newtype=="meeting") {
				//my appointment : on standby
				if ($user_id_value == $_SESSION["MGW"]->userid) {
				    $id_class = 1;
				}
				else {
					// imposed :
					if (isset($part[$i]) && $part[$i]=="I") {
					    $id_class = 1;
					}
					else $id_class = 0; //:subjected
				}
			}
			else $id_class = 2;
		$sql = "INSERT INTO mgw_calendar_tmp (id, id_class, id_scheduling, date, userid, id_appt_type, id_location_type, subject_summ, subject, location, private, duration, availability, telephone, external,	inituserid, dategroup_id, repeat_mode, rep_from, rep_until, holiday_id) VALUES($new_id, $id_class, $id_scheduling, $sql_appointment_start, $user_id_value, $id_appt_type, $id_location_type, $subject_summ, $thema, $location, $pr, $duration, $availability, $telephone, $external, ".$_SESSION["MGW"]->userid.", 0, 0, NULL, NULL, 0)";

		// ancienne ligne: $sql = "INSERT INTO mgw_calendar_tmp (id, date, userid, subject, location, private, duration, external,	inituserid, day_ind, dategroup_id, repeat_mode, rep_from, rep_until, holiday_id) VALUES($new_id, $sql_appointment_start, $user_id_value, $thema, $location, $pr, $duration, $external, ".$_SESSION["MGW"]->userid.", $day_ind, 0, 0, NULL, NULL, 0)";
		/////////

		if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

		if ($i != count($participants)) {
		    edit_conflict_list("new", $appointment_start, $appointment_end, $user_id_value, $new_id);
		}
	    }
	}

	// b) serials of appointments
	else if ($appointment_attribute > 0) {


	    // set start and end of serial
	    $serial_start   = $conn->DBTimeStamp($appointment_start);
	    $serial_end     = $conn->DBTimeStamp(mktime(23,59,59, $serial_end_month, $serial_end_day, $serial_end_year));
	    $serial_end_time = mktime(23,59,59, $serial_end_month, $serial_end_day, $serial_end_year);

	    // create array with each appointment of serial ==> fill $appointment_list
//echo "1: ".$appointment_attribute."<br>";
//echo "2: ".$appointment_start."<br>";
//echo "3: ".$serial_end_time."<br>";

	    //$appointment_list = array();
		$appointment_list = get_appointment_list($appointment_attribute, $appointment_start, $serial_end_time);

//		$appointment_list = get_appointment_list($appointment_attribute, $appointment_start, $appointment_start);
//echo "a";
//print_r($appointment_list);
	    // set new group_id of timeserial
	    $max_id = get_new_id("dategroup_id", "mgw_calendar", 0, "");

	    // create every appointment in time serial for each participant
	    foreach( $appointment_list as $appointment) {
		// get new ids
		$new_id  = mgw_genID('mgw__seq_calendar');
		$new_id2 = mgw_genID('mgw__seq_calendar_tmp');
		if ($new_id2 > $new_id && $new_id2 > 0) $new_id = $new_id2;

		// daylight date shifting
		$sql_appointment_tmp = $conn->DBTimeStamp($appointment/*+date("Z")*/);

		$appointment_end = $appointment+$duration*60;

		for ($i=0; $i < count($participants); $i++) {
		    $user_id_value = $participants[$i];

		    // insert in temporary table calendar_tmp
		    ///// |--| ////
$id_class=2;
			$sql = "INSERT INTO mgw_calendar_tmp(id, id_class, id_scheduling, date, userid, id_appt_type, id_location_type, subject_summ, subject, location, private, duration, availability,  telephone, external, inituserid, dategroup_id, repeat_mode, rep_from, rep_until, holiday_id) VALUES( $new_id, $id_class, $id_scheduling, $sql_appointment_tmp, $user_id_value, $id_appt_type, $id_location_type, $subject_summ, $thema, $location, $pr, $duration, $availability, $telephone, $external, ".$_SESSION["MGW"]->userid.", $max_id, $appointment_attribute, $serial_start, $serial_end, $holi_ind)";
			//$sql = "INSERT INTO mgw_calendar_tmp(id, date, userid, subject, location, private, duration, external, inituserid, day_ind, dategroup_id, repeat_mode, rep_from, rep_until, holiday_id) VALUES( $new_id, $sql_appointment_tmp, $user_id_value, $thema,$location, $pr, $duration, $external, ".$_SESSION["MGW"]->userid.", $day_ind, $max_id, $appointment_attribute, $serial_start, $serial_end, $holi_ind)";
		    ////////////////

		    if(!$conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

		    if ($i != count($participants)) {
			edit_conflict_list("new", $appointment, $appointment_end, $user_id_value, $new_id);
		    }
		}
	    }
	}
    }

    // ==================================
    /// edit appointment
    // ==================================
    else if (isset($update)) {
	$id = (int) $_POST["id"];
	// get appointment details from database and store in $old_database_row
	$sql = "SELECT * FROM mgw_calendar WHERE id = ".$id." AND userid = ".$_SESSION['calendarid']; //$_SESSION["MGW"]->userid;
	if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

	$old_database_row = $res->FetchRow();

	//small security:
	if( !is_modifiable_by_current_user($old_database_row["id"]))
		exit(Lang::getLanguageString("forbidden")."<br> <a href=\"javascript:history.go(-1);\">back</a>");

	unset($appointment_list);
	unset($conflict_list);

	//if creator wants to be participant, we add him at the end of array
	if(IsSet($_POST["i_will"]) && ($_POST["i_will"]==true || $_POST["i_will"]=="on")) $participants[] = $_SESSION["MGW"]->userid;

	$thema = $conn->QMagic(str_encode($_POST["thema"]));
	/// |--| ///
	$subject_summ = $conn->QMagic(str_encode($_POST["subject_summ"]));
	if($_POST["availability"]==0) $telephone = "";
	else $telephone = $_POST["telephone"];
	$telephone = $conn->QMagic($telephone);

	////
	/// there are different cases for updating an appointment
	/// a) just update single appointment / time series information
	/// b) extend a single appointment to a time serie
	/// c) reduce a time serie to a single appointment

	// a) single appointment => single appointment
		// time series
	if ($old_database_row["repeat_mode"] > 0) {

	    // a1) edit an single appointment which is part of a time serie
	    // edit appointment_start if necessary

	    $serial_end_day = ($appointment_end-mktime(0,0,0, date("m", $date), date("d", $date), date("Y", $date))) + mktime(0,0,0, $serial_start_month, $serial_start_day, $serial_start_year);
	    $serial_start = $conn->DBTimeStamp($old_database_row["rep_from"]);
	    $serial_end = $conn->DBTimeStamp($old_database_row["rep_until"]);
	    $appointment_attribute = $old_database_row["repeat_mode"];
	    $max_id = $old_database_row["dategroup_id"];
	    $sql_appointment_start = $conn->DBTimeStamp($appointment_start);

//echo "<BR>ARF: ".$appointment_start;
//exit();

		$duration = ($appointment_end-$appointment_start)/60;

	    // get new appointment id
	    $new_id  = mgw_genID('mgw__seq_calendar');
	    $new_id2 = mgw_genID('mgw__seq_calendar_tmp');
	    if ($new_id2 > $new_id && $new_id2 > 0) $new_id = $new_id2;

	    // create new appointment in temporary table
	    for ($i=0; $i < count($participants); $i++) {
		$user_id_value = $participants[$i];

		///// |--| /////
		//get id_class for each participant :
		$sql_old = "SELECT id_class FROM mgw_calendar WHERE id='".$old_database_row["id"]."' AND userid='$user_id_value'";
		if(!$res_old = $conn->Execute($sql_old)) exit(showSQLerror($sql_old, $conn->ErrorMsg(), __LINE__, __FILE__));
		$row_old = $res_old->FetchRow();
		$id_class = !empty($row_old["id_class"]) ? $row_old["id_class"] : 2;
		//$id_class=2;

			if ($newtype=="meeting" && $part[$i]=="I") { // if appt is meeting and participant is imposed
				$id_class = 1;
			}

		$sql = "INSERT INTO mgw_calendar_tmp(id, id_class, id_scheduling, date, userid, id_appt_type, id_location_type, subject_summ, subject, location, private, duration, availability,  telephone, external, inituserid, dategroup_id, repeat_mode, rep_from, rep_until, holiday_id) VALUES( $new_id, $id_class, $id_scheduling, $sql_appointment_start, $user_id_value, $id_appt_type, $id_location_type, $subject_summ, $thema, $location, $pr, $duration, $availability, $telephone, $external, ".$_SESSION["MGW"]->userid.", $max_id, $appointment_attribute, $serial_start, $serial_end,0)";

		//$sql = "INSERT INTO mgw_calendar_tmp(id, date, userid, subject, location, private, duration, external, inituserid, day_ind, dategroup_id, repeat_mode, rep_from, rep_until, holiday_id) VALUES( $new_id, $sql_appointment_start, $user_id_value, $thema, $location, $pr, $duration, $external, ".$_SESSION["MGW"]->userid.", $day_ind, $max_id, $appointment_attribute, $serial_start, $serial_end,0)";
		////////////////

		if(!$conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

		if ($i != count($participants)) {
		    edit_conflict_list("update", $appointment_start, $appointment_end, $user_id_value, $id);
		}
	    }
	}

	// edit time series
	else if ($old_database_row["repeat_mode"] == 0) {


//echo "<BR>appt start: ".$conn->DBTimeStamp($appointment_start);
//echo "<BR>appt end: ".$conn->DBTimeStamp($appointment_end);
//echo "<BR>serial start D-M-Y: ".$serial_start_day."-".$serial_start_month."-".$serial_start_year;
//echo "<BR>serial end D-M-Y: ".$serial_end_day."-".$serial_end_month."-".$serial_end_year;

		// single appointment ==> single appointment / time series
	    // get new group id / appointment id
	    // get appointment list

		/// |--| ///
		/* ancien code :
		* $adate = ($appointment_start
		      - mktime(0,0,0, date("m", $appointment_start), date("d", $appointment_start), date("Y", $appointment_start)))
		      + mktime(0,0,0, $serial_start_month, $serial_start_day, $serial_start_year);
		*/
		// code ci-dessus -> peut-être mettre le nom de la mSelectBox 'start_day' à 'serial_start_day' et remettre l'ancien code ?

		$adate = $appointment_start;
		/////////////
//echo "<BR>adate: ".$conn->DBTimeStamp($adate);
	    $bdate = (  $appointment_end
			- mktime(0,0,0, date("m", $appointment_end), date("d", $appointment_end), date("Y", $appointment_end)))
		        + mktime(0,0,0, $serial_end_month, $serial_end_day,  $serial_end_year);
//echo "<BR>bdate: ".$conn->DBTimeStamp($bdate);
//exit();
	    $start_array = getdate($adate);
	    $end_array   = getdate($bdate);
	    $duration  = ($appointment_end - $appointment_start)/60;

	    $sst_ts    = $start_array[0];
	    $sen_ts    = $end_array[0];

	    $serial_start =  $conn->DBTimeStamp($sst_ts);
	    $serial_end   =  $conn->DBTimeStamp($sen_ts);

		$appointment_list = array();
	    if ($appointment_attribute > 0) get_appointment_list($appointment_attribute, $sst_ts, $sen_ts);
	    else if ($appointment_attribute == 0) $appointment_list[] = /*|--|: $adate*/ $appointment_start;

	    // get max id
	    if ($appointment_attribute > 0) {
		$max_id = get_new_id("dategroup_id", "mgw_calendar", 0, "");
	    }
	    else if ($appointment_attribute == 0) {
		$max_id = 0;
	    }

	    // create time serie
	    foreach($appointment_list as $appointment) {
		// daylight date shifting
		$sql_appointment_tmp = $conn->DBTimeStamp($appointment/* |--| : (decalage horaire) +date("Z")*/);
		$appointment_end = $appointment+$duration*60;
		// get new appointment id
		$new_id  = mgw_genID('mgw__seq_calendar');
		$new_id2 = mgw_genID('mgw__seq_calendar_tmp');
		if ($new_id2 > $new_id && $new_id2 > 0) $new_id = $new_id2;
		for ($i=0; $i<count($participants); $i++) {
		    $user_id_value = $participants[$i];

		    // insert into temporary table
		    //// |--| ////
			//echo "ID: ".$old_database_row["id"]."<br>";
			//echo "user: ".$user_id_value."<br>";
			$sql_old = "SELECT id_class FROM mgw_calendar WHERE id='".$old_database_row["id"]."' AND userid='$user_id_value'";
			if(!$res_old = $conn->Execute($sql_old)) exit(showSQLerror($sql_old, $conn->ErrorMsg(), __LINE__, __FILE__));
			$row_old = $res_old->FetchRow();
			$id_class = !empty($row_old["id_class"]) ? $row_old["id_class"] : 2;
			//$id_class=2;
			if ($newtype=="meeting" && isset($part[$i]) && $part[$i]=="I") { // if appt is meeting and participant is imposed
				$id_class = 1;
			}
			$sql = "INSERT INTO mgw_calendar_tmp(id, id_class, id_scheduling, date, userid, id_appt_type, id_location_type, subject_summ, subject, location, private, duration, availability, telephone, external, inituserid, dategroup_id, repeat_mode, rep_from, rep_until, holiday_id) VALUES( $new_id, $id_class, $id_scheduling, $sql_appointment_tmp, $user_id_value, $id_appt_type, $id_location_type, $subject_summ, $thema, $location, $pr, $duration, $availability, $telephone, $external, ".$_SESSION["MGW"]->userid.", $max_id, $appointment_attribute, $serial_start, $serial_end, $holi_ind)";
			//$sql = "INSERT INTO mgw_calendar_tmp(id, date, userid, subject, location, private, duration, external, inituserid, day_ind, dategroup_id, repeat_mode, rep_from, rep_until, holiday_id) VALUES( $new_id, $sql_appointment_tmp, $user_id_value, $thema, $location, $pr, $duration, $external, ".$_SESSION["MGW"]->userid.", $day_ind, $max_id, $appointment_attribute, $serial_start, $serial_end, $holi_ind)";
			///////////////

		    if(!$conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

		    if ($i != count($participants)) {
			edit_conflict_list("update", $appointment, $appointment_end, $user_id_value, $id);
		    }
		}
	    }
	}
    }// if isset(update)

    // ========================================
    // check for conflict in appointment_list
    // if conflict, display conflict-template
    // ========================================
    if(count($conflict_list) > 0) {
	if (!isset($id)) $id=0;

// ?? // SUBJECT !!!!!
	$smarty->assign("subject", short_string(substr($thema,1,-1),$max_subject_length));
	$smarty->assign('username', $_SESSION["MGW"]->username);
	$smarty->assign('appointment',   date_lang($_SESSION["MGW"]->settings["datefmt"] , $appointment_start));
	$smarty->assign('time_start',    date($timemask,  $appointment_start));
	$smarty->assign('time_end',      date($timemask,  $appointment_end));

//showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__);
	foreach($appointment_list as $appointment){
	    if (isset($conflict_list[$appointment])) {
		$appointment_end = $appointment_end + $duration * 60;
	    }
	    for($i=0;$i < count($conflict_list[$appointment]);$i++)
		$smarty->append("td", $conflict_list[$appointment][$i]);
	}

	if ($appointment_attribute > 0)
	    $smarty->assign('edit', "index.php?action=edittsconflict&date=$date&id=$new_id&".SID);
	else
	    $smarty->assign('edit', "index.php?action=editconflict&date=$date&tmpid=$new_id&id=$id&".SID);
	$smarty->assign('book',    "index.php?action=book&old_id=$id&date=$date&id=$new_id&".SID);
	$smarty->assign('notbook', "index.php?action=notbook&id=$new_id&date=$date&".SID);

	$smarty->display('calendar_date_conflict.tpl');
	exit();
    }

    else if (!isset($conflict_list)) {
	/// if there is no conflict, inform participants via email
	/// copy temporary appointments into table calendar and delete temporary rows
	if (isset($new) and $new != "") {
	    db_copy_date_from_tmp($new_id);
	    db_delete_date_from_tmp($new_id);
	    //if($_SESSION["MGW"]->settings["calendar_remindermail"])
		new_date_notify($new_id);
	}
	else if (isset($update)){
	    db_delete_date_rep($id, 0, 1, $_SESSION["MGW"]->userid);
	    db_copy_date_from_tmp($new_id);
	    db_delete_date_from_tmp($new_id);
	}
	unset($action);
    }
}


// =================================================================
// edit timeseries (delete old serie, create new one) in DATABASE
// =================================================================
if (isset($_POST["tsupdate"])) {
    $id = (int) $_POST["id"];

	// check if current user can modify :
	if (!is_modifiable_by_current_user($id,$_SESSION["calendarid"])) {
	    exit(Lang::getLanguageString("forbidden")."<br> <a href=\"javascript:history.go(-1);\">back</a>");
	}

    $thema = $conn->QMagic(str_encode($_POST["thema"]));
    /// |--| ///
	$subject_summ = $conn->QMagic(str_encode($_POST["subject_summ"]));
	if($_POST["availability"]==0) $telephone = "";
	else $telephone = $_POST["telephone"];
	$telephone = $conn->QMagic($telephone);
	/////
	$location = $conn->QMagic(str_encode($_POST["location"]));
    $external = $conn->QMagic(str_encode($_POST["external"]));
    $sql = "SELECT * FROM mgw_calendar WHERE id = $id AND userid = ".$_SESSION["MGW"]->userid;
    $participants = $_POST["participants"];

    if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    $row = $res->FetchRow();

    // appointment for day :  $appointment_start => start_time / $appointment_end => end_time
    // if vacation: $appointment_start => start_time / $appointment_end => end_time

	///// |--| /////

	$id_scheduling = 0 ; // default = time

	  if (IsSet($_POST["scheduling"])){

	  $id_scheduling = $_POST["scheduling"];

	  switch($id_scheduling){

	  	case 3 :	// indicator whether appointment belongs to complete day
					$appointment_start = $start_time;		// timestamp of appointment start
				  	$appointment_end   = $end_time;		// timestamp of appointment end
	 				break;

		case 2 : 	// indicator whether appointment belongs to afternoon
				  	$appointment_start = $start_time + ($end_time-$start_time)/2;		// timestamp of appointment start
				  	$appointment_end   = $end_time;		// timestamp of appointment end
					break;

		case 1 :	// indicator whether appointment belongs to morning
					$appointment_start = $start_time;		// timestamp of appointment start
					$appointment_end   = $start_time + ($end_time-$start_time)/2;		// timestamp of appointment end
					break;

		default : 	//create timestamp with date and appointement(time)
					$appt_start_array = getdate($appointment_start);// infos about hour-minute
					$date_start_array = getdate($date);				// infos about day-month-year
					$tmp_duration = $appointment_end-$appointment_start;
					$appointment_start = mktime($appt_start_array["hours"],$appt_start_array["minutes"],0,$date_start_array["mon"],$date_start_array["mday"],$date_start_array["year"]);
					$appointment_end = $appointment_start + $tmp_duration;
					break; // includes case '0'
	  	}
		// ?? a enlever + tard :
			$holi_ind = 0;
	    ////

	} // end if

	$thema = $conn->QMagic(str_encode($_POST["thema"]));
	 /// |--| ///
	$subject_summ = $conn->QMagic(str_encode($_POST["subject_summ"]));
	if($_POST["availability"]==0) $telephone = "";
	else $telephone = $_POST["telephone"];
	$telephone = $conn->QMagic($telephone);
	////
	/*  ancien bloc :
	if ($_POST["day"]==true || $_POST["holiday"]==true) {
	$day_ind = 1;				// indicator whether appointment belongs to complete day
	$appointment_start = $start_time;	// timestamp of appointment start
	$appointment_end   = $end_time;		// timestamp of appointment end

	// if vacation: $appointment_start => start_time / $appointment_end => end_time
	if ($_POST["holiday"]==true) {
	    $holi_ind = 1;			// indicator whether appointment belongs to vacation day
	    $appointment_attribute = 4;			// attribute = 4
	    $thema = "'".Lang::getLanguageString("vacation")."'"; //
	}
	else {
	    $holi_ind = 0;
	}
    }
    else{
	$day_ind = 0;
	$holi_ind = 0;
    }
	*/
	/////////////////

    $pr = (isset($_POST["private"]) && $_POST["private"]!="") ? 1 : 0;
    unset($appointment_list);
    unset($conflict_list);

    //echo "<BR>APPT START: ".$conn->DBTimeStamp($appointment_start)."<BR>";
	//echo "<BR>serial start D-M-Y: ".$serial_start_day."-".$serial_start_month."-".$serial_start_year;
	//echo "<BR>serial end D-M-Y: ".$serial_end_day."-".$serial_end_month."-".$serial_end_year;


	// compute new start/ new end of time serie
    $s_time = getdate($appointment_start);
    $e_time = getdate($appointment_end);
    $f_start = mktime($s_time["hours"], $s_time["minutes"], 0, $serial_start_month, $serial_start_day, $serial_start_year);
    $f_ende = mktime($e_time["hours"], $e_time["minutes"], 0, $serial_end_month, $serial_end_day, $serial_end_year);
    $start_array = getdate($f_start);
    $end_array = getdate($f_ende);
    $duration = ($appointment_end - $appointment_start)/60;

    $serial_start = $conn->DBTimeStamp($f_start);
    $serial_end = $conn->DBTimeStamp($f_ende);

    // get all appointments according to time serie
    if ($appointment_attribute > 0)
	get_appointment_list($appointment_attribute, $f_start, $f_ende);
    else if ($appointment_attribute == 0)
	$appointment_list[0] = $f_start;

    $max_id  = get_new_id("dategroup_id", "mgw_calendar", 0, "");
    if(IsSet($_POST["i_will"]) && $_POST["i_will"]==true) $participants[] = $_SESSION["MGW"]->userid;

    // create appointments
    foreach($appointment_list as $appointment) {
	$sql_appointment_tmp = $conn->DBTimeStamp($appointment);

	$new_id  = mgw_genID('mgw__seq_calendar');
	$new_id2 = mgw_genID('mgw__seq_calendar_tmp');
	if ($new_id2 > $new_id && $new_id2 > 0) $new_id = $new_id2;

	for ($i=0; $i<count($participants); $i++) {
	    $user_id_value = $participants[$i];
	    // insert into temporary table

		//// |--| /////
$id_class=2;
		$sql = "INSERT INTO mgw_calendar_tmp(id, id_class, id_scheduling, date, userid, id_appt_type, id_location_type, subject_summ, subject, location, private, duration, availability, telephone, external, inituserid, dategroup_id, repeat_mode, rep_from, rep_until, holiday_id) VALUES($new_id, $id_class, $id_scheduling, $sql_appointment_tmp, $user_id_value, $id_appt_type, $id_location_type, $subject_summ, $thema, $location, $pr, $duration, $availability, $telephone, $external, ".$_SESSION["MGW"]->userid.", $max_id, $appointment_attribute, $serial_start,$serial_end, $holi_ind)";
		//$sql = "INSERT INTO mgw_calendar_tmp(id, date, userid, subject, location, private, duration, external, inituserid, day_ind, dategroup_id, repeat_mode, rep_from, rep_until, holiday_id) VALUES($new_id, $sql_appointment_tmp, $user_id_value, $thema, $location, $pr, $duration, $external, ".$_SESSION["MGW"]->userid.", $day_ind, $max_id, $appointment_attribute, '$serial_start','$serial_end', $holi_ind)";
		////////////////

	    if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

	    if ($i != count($participants))
		edit_conflict_list("update", $appointment, $appointment_end, $user_id_value, $id);
	}

    }

    // =================================================================
    // check for conflict in appointment_list
    // if conflict, display conflict-template
    // =================================================================
    if (isset($conflict_list)) {

	// SUBJECT !!!
	$smarty->assign("subject", substr($thema,1,-1));
	$smarty->assign('username', $_SESSION["MGW"]->username);
 	$smarty->assign('appointment',   date_lang($_SESSION["MGW"]->settings["datefmt"] , $appointment_start));
	$smarty->assign('time_start',    date($timemask,  $appointment_start));
	$smarty->assign('time_end',      date($timemask,  $appointment_end));

	foreach($appointment_list as $appointment) {
	    if (isset($conflict_list[$appointment]))
		$appointment_end = $appointment + $duration * 60;
	    for($i=0;$i < count($conflict_list[$appointment]);$i++)
		$smarty->append("td", $conflict_list[$appointment][$i]);
	}

	if (!isset($id)) $id=0;

	$smarty->assign('edit',    "index.php?action=edittsconflict&date=$date&tmpid=$new_id&id=$id&".SID);
	$smarty->assign('book',    "index.php?action=book&old_id=$id&date=$date&id=$new_id&".SID);
	$smarty->assign('notbook', "index.php?action=notbook&id=$new_id&date=$date&".SID);

	$smarty->display('calendar_date_conflict.tpl');
	exit();
    }

    else if (!isset($conflict_list)) {
	// ===========================================================================
	// if there is no conflict, inform participants via email
	// copy temporary appointments into table calendar and delete temporary rows
	// ===========================================================================
	db_delete_date_rep($id, 3, 1, $_SESSION["calendarid"] /*$_SESSION["MGW"]->userid*/);
	db_copy_date_from_tmp($new_id);
	db_delete_date_from_tmp($new_id);
	unset($action);
    }
}

// ==========================================
// Show Template : delete appointment
// ==========================================
if (IsSet($action) && $action=="del") {
	$id = (int) $_GET["id"];

	$delete = (isset($_GET["delete"])) ? $_GET["delete"] : (IsSet($_POST["delete"]) ? $_POST["delete"] : "");
	$smarty->assign("delete",$delete);

	// i don't know...
	$sql_class = ($delete!="all" ? " AND a.id_class !='3'" : "");
	//$sql_class = " AND a.id_class !='3'";

	//  get appointment details
	$sql  = "SELECT a.*, b.id as user_id, ".$conn->Concat("b.firstname", "' '", "b.lastname")." AS name, ".$conn->Concat("c.firstname", "' '", "c.lastname")." AS initusername FROM mgw_calendar a, mgw_users b, mgw_users c WHERE NOT(b.level=".UDELETED.") AND a.id = ".$id." AND a.userid = b.id AND a.inituserid = c.id ".$sql_class ;

	if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	$nbpart = $res->NumRows();
	//if more than one participant : NOTIFY...
	$smarty->assign("notify","yes");

	$row  = $res->FetchRow();
	$date = $res->UnixTimeStamp($row["date"]);

	//----- DAY and TIME  assign variables to template
	$smarty->assign('appointment_day', date_lang( Lang::getLanguageString("gentemp_date_format_php"), $res->UnixTimeStamp($row["date"])));
	$smarty->assign('from', date($timemask, $res->UnixTimeStamp($row["date"])));
	$smarty->assign('to', date($timemask, $res->UnixTimeStamp($row["date"]) + $row["duration"] * 60));

	$smarty->assign('date', $res->UnixTimeStamp($row["date"]));
	$smarty->assign('id', $id);

	//----- private
	$private = array("id" 	=> $row["private"],
					 "text"	=> ($row["private"] == 0 ) ? Lang::getLanguageString("gentemp_no") : Lang::getLanguageString("gentemp_yes")
					);
	$smarty->assign('private', $private);

	//---- repeater
	if ($row["repeat_mode"] < 1 || $row["repeat_mode"]>4) {
		$smarty->assign("repeater", Lang::getLanguageString("gentemp_repeater_0"));
		$smarty->assign("repeater_0", "yes");
	} else {
		$rep1  = date_lang(Lang::getLanguageString("gentemp_date_format_php"),  $res->UnixTimeStamp($row["rep_from"]));
		$rep2  = date_lang(Lang::getLanguageString("gentemp_date_format_php"),  $res->UnixTimeStamp($row["rep_until"]));
		$smarty->assign("repeater", Lang::getLanguageString("gentemp_repeater_".$row["repeat_mode"]).", ".Lang::getLanguageString("gentemp_from")." ".$rep1." ".Lang::getLanguageString("gentemp_to")." ".$rep2);
		$smarty->assign("repeater_0", "no");
	}

	//---- subject
	$smarty->assign("subject_summ", str_decode($row["subject_summ"]));
	$smarty->assign('subject', str_decode($row["subject"]));



	//----- scheduling_type:
	$scheduling = $row["id_scheduling"];
	 //search string
	$sql_sched = "SELECT * FROM mgw_calendar_scheduling_type WHERE id = $scheduling";
	if(!$res_sched = $conn->Execute($sql_sched)) exit(showSQLerror($sql_sched, $conn->ErrorMsg(), __LINE__, __FILE__));
	$row_sched = $res_sched->FetchRow();
	$scheduling = array("id" 	=> $scheduling,
						 "type" => Lang::getLanguageString("gentemp_".$row_sched["type"])
						);
	$smarty->assign("scheduling",$scheduling);

	//----- location type and location
	$id_loc = $row["id_location_type"];
	$sql_loc = "SELECT * FROM mgw_calendar_location_type WHERE id=$id_loc";
	if(!$res_loc = $conn->Execute($sql_loc)) exit(showSQLerror($sql_loc, $conn->ErrorMsg(), __LINE__, __FILE__));
	$row_loc = $res_loc->FetchRow();
	$location_type = Lang::getLanguageString("gentemp_".$row_loc["location_type"]);
	$smarty->assign("location_type",$location_type);
	$smarty->assign('location', str_decode($row["location"]));

	//----- appointment type :
	$id_appt_type = $row["id_appt_type"];
	$sql_appt_type = "SELECT * FROM mgw_calendar_appt_type WHERE id=$id_appt_type";
	if(!$res_appt_type = $conn->Execute($sql_appt_type)) exit(showSQLerror($sql_appt_type, $conn->ErrorMsg(), __LINE__, __FILE__));
	$row_appt_type = $res_appt_type->FetchRow();
	$appointment_type = array( 	"text" => Lang::getLanguageString("gentemp_".$row_appt_type["type"]),
								"color"=> $row_appt_type["color"]
							 );
	$smarty->assign("appt_type",$appointment_type);

	//----- availability and telephone:
	 $availability = $row["availability"];
		if($availability==1)
			{
			$availability = Lang::getLanguageString("gentemp_can_be_disturbed");
			$telephone = $row["telephone"];
			}
		else
			{
			$availability = Lang::getLanguageString("gentemp_can_not_be_disturbed");
			$telephone = "";
			}
	 $smarty->assign("availability",$availability);
	 $smarty->assign("telephone",$telephone);

	if ($delete=="all") {
	    $smarty->assign('back', "subj_followup.php?action=view&".SID);
	}
	else {
		if ($ind == 1) $smarty->assign('back', "index.php?action=sel&date=$date&".SID);
		else if ($ind==2) $smarty->assign('back', "week.php?date=$date&.".SID);
		else $smarty->assign('back',"index.php?date=$date&".SID);
	}

	//---- inituser
	$smarty->assign('inituser', $row["initusername"]);

	//---- participants who don't have aborted the appointment
	$res->Move(0);
	while($row = $res->FetchRow()) {
		$p_ar = array( 	"id" => $row["user_id"],
						"name" => $row["name"],
						"can_be_deleted" => is_modifiable_by_current_user($id,$row["userid"]),
						"chk" => ( ($row["user_id"] == $_SESSION['calendarid']) || ($delete=="all") ? "CHECKED" : ""),
						"already_aborted" => ( $row["id_class"] == "3"  ? true : false)
						);

		$smarty->append("partie", $p_ar);
	}
	//---- external participants
	$smarty->assign('external', $row["external"]);

	if($res->NumRows() > 1) $smarty->assign("showdelopt",true);


	$smarty->assign("temp_subject_summarized",Lang::getLanguageString("temp_subject_summarized"));
	$smarty->assign("temp_subject_detailed",Lang::getLanguageString("temp_subject_detailed"));
	$smarty->assign("temp_appt_type",Lang::getLanguageString("temp_appt_type"));
	$smarty->assign("temp_availability",Lang::getLanguageString("temp_availability"));




  $smarty->display('calendar_date_delete.tpl');
}


// ===================================
// step one month back in calendar
// ===================================
if (isset($_GET['action']) && $_GET['action']=="mback") {
	if ($_SESSION['calendar_month'] == 1) {
		$_SESSION['calendar_month'] = 12;
		$_SESSION['calendar_year']--;
	} else {
		$_SESSION['calendar_month']--;
	}
	 unset($_GET['action']);
}

// ===================================
// step one month forward in calendar
// ===================================
if (IsSet($_GET['action']) && $_GET['action']=="mforw") {
	if ($_SESSION['calendar_month'] == 12) {
		$_SESSION['calendar_month'] = 1;
		$_SESSION['calendar_year']++;
	} else {
		$_SESSION['calendar_month']++;
	}
	unset($_GET['action']);
}

// ===================================
// step one year back in calendar
// ===================================
if (IsSet($_GET['action']) && $_GET['action']=="yback") {
	$_SESSION['calendar_year']--;
	unset($_GET['action']);
}

// ===================================
// step one year forward in calendar
// ===================================
if (IsSet($_GET['action']) && $_GET['action']=="yforw") {
	$_SESSION['calendar_year']++;
	unset($_GET['action']);
}

// ===========================================
// book appointment in spite of conflict case
// ===========================================
if (isset($_GET['action']) && $_GET['action']=="book") {
	db_copy_date_from_tmp($_GET['id']);
	db_delete_date_from_tmp($_GET['id']);
	if ($_GET['old_id'] != "") db_delete_date_rep($_GET['old_id'],0,1,$_SESSION["MGW"]->userid);
	else ///if ($_SESSION["MGW"]->settings["calendar_remindermail"])
	new_date_notify($_GET['id']);
	unset($_GET['action']);
}

// ======================================
//dont book appointment in conflict case
// ======================================
if (IsSet($_GET['action']) && $_GET['action']=="notbook") {
	db_delete_date_from_tmp($_GET['id']);
	unset($_GET['action']);
}

// For "select all" special case
$smarty->assign("calendarid",$_SESSION['calendarid']);

// ======================================
// Show Template : calendar day-view
// ======================================
if(! (isset($_GET['action']) || isset($_POST['action']))) {

    $icons = getIconStrings();
    $cal_icons = getCalIconStrings();
	$icons = array_merge($icons,$cal_icons);
    // =========================================================
    // set calenderid = userid if calendarid is not set
    // =========================================================
    if ($_SESSION["calendarid"] == "") {
	$_SESSION["calendarid"] = $_SESSION["MGW"]->userid;
	$_SESSION["calendarname"] = $_SESSION["MGW"]->fullusername;
    }

    // =========================================================
    // set calendar month-view (if not registered in session)
    // =========================================================
    if (!session_is_registered('calendar_month') && !session_is_registered('calendar_year')) {
	$_SESSION['calendar_day'] = date("d", $date);
	$_SESSION['calendar_month'] = date("m", $date);
	$_SESSION['calendar_year'] = date("Y", $date);
    }

    /*
	// =========================================================
    // show user list as possible calendar owners
    // =========================================================
    $sql = "SELECT id, ".$conn->Concat("firstname", "' '", "lastname")." AS name FROM mgw_users WHERE NOT(level=".UDELETED.") ORDER BY 2";

    if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    while ($row = $res->FetchRow()) {
		if($row["id"]== $_SESSION["MGW"]->userid){
		$td2_ar = array("id" => $row["id"],
						"name" => "-->".$row["name"]."<--");
		$smarty->append("td2", $td2_ar);
		}
		else $smarty->append("td2", $row);
    }
	*/

	////////////////////////////////////////////////////////////////////////
    // show user list as possible calendar owners
    ////////////////////////////////////////////////////////////////////////
	include_once(CAL1_INC_DIR."user_list.inc.php");

    $smarty->assign('action', Lang::getLanguageString("action"));

    // =========================================================
    // get appointments of day $date
    // =========================================================
    $sql_tag  = date("Ymd", $date);
    if ($_SESSION['calendarid']=="all") {
	$sql_owner_part="";
    }
    else {
	$sql_owner_part="userid=".$_SESSION['calendarid']." AND";
    }

//	$sql = "SELECT id_class, date, id_appt_type, id_location_type, subject_summ, subject, location, private, id, duration, availability, telephone, dategroup_id, COUNT(DISTINCT subject) AS appointment_count, inituserid FROM mgw_calendar WHERE ".$sql_owner_part." SUBSTRING(date,1,8) = '$sql_tag' AND id_class!='3' GROUP BY date, subject_summ, subject, location, private, id, duration, dategroup_id, inituserid ORDER BY date";
//	$sql = "SELECT id_class, date, id_appt_type, id_location_type, subject_summ, subject, location, private, id, duration, availability, telephone, dategroup_id, COUNT(DISTINCT id) AS appointment_count, inituserid FROM mgw_calendar WHERE ".$sql_owner_part." SUBSTRING(date,1,8) = '$sql_tag' AND id_class!='3' GROUP BY date, subject_summ, subject, location, private, id, duration, dategroup_id, inituserid, id_class, id_appt_type, id_location_type, availability, telephone ORDER BY date";

 	//$sql = "SELECT id_class, date, id_appt_type, id_location_type, subject_summ, subject, location, private, id, duration, availability, telephone, dategroup_id, COUNT(DISTINCT id) AS appointment_count, inituserid
	$sql = "SELECT id_class, date, id_appt_type, id_location_type, subject_summ, subject, location, private, id, duration, availability, telephone, dategroup_id, 1 AS appointment_count, inituserid
        	FROM mgw_calendar
			WHERE ".$sql_owner_part." date >= ".$conn->DBTimeStamp(mktime(0,0,0, date("m",$date), date("d",$date), date("Y",$date)) )." AND
            date <= ".$conn->DBTimeStamp( mktime(23,59,59, date("m",$date), date("d",$date), date("Y",$date)) )." AND
                    id_class!='3'
			GROUP BY date, subject_summ, subject, location, private, id, duration, dategroup_id, inituserid, id_class, id_appt_type, id_location_type, availability, telephone
			ORDER BY date";
//echo "SQL<br>$sql <br>SQL<br>";
    if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    $row = $res->FetchRow();
    $num = $res->RecordCount();


    if (get_celebrate_days($date, $holitemp) != "") $additionaltext = "[". Lang::getLanguageString("gentemp_holiday"). "]";
    else if ( date("w", $date) == 0 || date("w", $date) == 6) $additionaltext = "[". Lang::getLanguageString("gentemp_weekend"). "]";
    else if ( date("dmY", $date) == date("dmY", time())) $additionaltext = "[". Lang::getLanguageString("today"). "]";
    else $additionaltext = "";

    // get birthdays
    if($_SESSION["MGW"]->settings["calendar_show_birthdays"]){
	$concat = $conn->Concat("'".Lang::getLanguageString('birthday').": '","firstname","' '","lastname");
	$bdsql = "SELECT $concat AS jubilee, SUBSTRING(birthday,1,4) as yofb FROM mgw_contacts WHERE SUBSTRING(birthday,6,12)='".date("m-d",$date)."' AND (ispublic='1' OR owner='".$_SESSION["MGW"]->userid."')";
	if(!$bdres = $conn->Execute($bdsql)) exit(showSQLerror($bdsql, $conn->ErrorMsg(), __LINE__, __FILE__));
	while($bdrow = $bdres->FetchRow()){
	    $zeile = array("start" => "",
			   "to" => "",
			   "topic" => $bdrow["jubilee"]. " (".$bdrow["yofb"].")",
			   "class" => "feiertag",
			   "location" => "",
			   "rowactions" =>  ""
			   );
	    $smarty->append("td", $zeile);
	}
    }

    if ($num > 0) {
	// =========================================================
	// check for each interval of day and parse into template
	// compute certain hits for several cases (see case list below)
	// =========================================================
	// Cases
	// =========================================================
	// 1. case: more than 1 appointment starting in current time slot
	//    Bed.: $row["appointment_count"] > 1 && $vmin >= $t && $vmin < $r
	// 	     $row["private"] == 0
	// =========================================================
	// 2. case: more than 1 appointment starting in current time slot
	//    Bed.: $row["appointment_count"] > 1 && $vmin >= $t && $vmin < $r
	// 	     $row["private"] == 1 && $userid == $calendarid
	// =========================================================
	// 3. case: 1 appointment starts in current time slot, non private
	//    Bed.: $row["appointment_count"] == 1 && $vmin >= $t && $vmin < $r
	// 	     $row["private"] == 0
	// =========================================================
	// 4. case: 1 appointment starts in current time slot, app. is private
	//    Bed.: $row["appointment_count"] == 1 && $vmin >= $t && $vmin < $r
	// 	     $row["private"] == 1 && $userid == $calendarid
	// =========================================================
	// 5. case: no starting appointment
	//    Bed.: $t > $vmin && $t < $bmin)
	// =========================================================

	for( $t=$app_start_time; $t<=$app_end_time; $t+=$interval_sec) {

	    $rowclass = ($t >= $start_time && $t < $end_time) ? "tab" : "outer";
//echo "start: $t, end: ".($t+$interval_sec)."<br>";
	    require(CAL1_INC_DIR."dayview.inc.php");

	    //-----------------------------------------------------
	    // compute hits in time slot
	    //-----------------------------------------------------
	    $hits = $tr_m0 + $tr_m1 + $tr_10 + $tr_11 + $tr_lfd;

	    if ($hits==0 && $t > $start_time && $t < $end_time) {
		//my calendar, empty line
		if ($_SESSION['calendarid'] == $_SESSION["MGW"]->userid) {
		    $zeile = array("start" => "<a class=\"edit\" href=\"index.php?action=new1&date=$t&".SID."\">". date_lang($timemask, $t)."</a>",
				   "to" => "<a class=\"edit\" href=\"index.php?action=new2&date=$t&".SID."\">". date_lang($timemask, $r)."</a>",
				   "topic" => "",
				   "class" => "tab",
				   "location" => "",
				   "rowactions" =>  ""
				   );
		}

		//calendar of another user, empty line
		else if ($_SESSION['calendarid'] != $_SESSION["MGW"]->userid) {
		    $zeile = array("start" 	=> date($timemask, $t),
				   "to" => date($timemask, $r),
				   "topic" => "",
				   "class" => "tab",
				   "location"   => "",
				   "rowactions"	=> ""
				   );
		}
		$smarty->append("td", $zeile);
	    }

	    else if ($tr_m0 !=0) $smarty->append("td", $zeile_m0);
	    else if ($tr_m1 !=0) $smarty->append("td", $zeile_m1);
	    else if ($tr_10 !=0) $smarty->append("td", $zeile_10);
	    else if ($tr_11 !=0) $smarty->append("td", $zeile_11);
	    else if ($tr_lfd!=0) $smarty->append("td", $zeile_lfd);
	}   // for
    }
    else if ($num==0) {
	// no date at actual day
	for($t=$start_time; $t<$end_time; $t+=$interval_sec) {
	    $r = $t+$interval_sec;
	    $leer = array("start" => "<a class=\"edit\"  href=\"index.php?action=new1&date=$t&".SID."\">". date_lang($timemask, $t)."</a>",
			  "class" => "tab",
			  "to" => "<a class=\"edit\"  href=\"index.php?action=new2&date=$t&".SID."\">". date_lang($timemask, $r)."</a>");
	    $smarty->append("td", $leer);
	}
    }

    // create monthview-calendar, based on $date
    $calendar = get_monthview_static( $date, $_SESSION['calendar_year'], $_SESSION['calendar_month']);

    // check if $date is celebration date
    $celebration_day = get_celebrate_days($date, $holitemp);
    if ($celebration_day != ""){
	$smarty->assign('holiday', 1);
	$smarty->assign('celebration_day', $celebration_day);
    }

    // computation for assign variables
    $dayforward = "<a class=\"navlink\" href=\"index.php?date=".($date+3600*24)."&".SID."\" style=\"text-decoration:none;\">". Lang::getLanguageString("temp_header_nav_forw"). " &gt;&gt;</a>";
    $dayback    = "<a class=\"navlink\" href=\"index.php?date=".($date-3600*24)."&".SID."\" style=\"text-decoration:none;\">&lt;&lt; ".Lang::getLanguageString("temp_header_nav_back"). "</a>";
    $day_index  = "gentemp_weekday_" . (date("w", $date) + 1);
    // |--| //

	$text = Lang::getLanguageString("$day_index")."&nbsp; ".date_lang(Lang::getLanguageString("gentemp_date_format_php"), $date)."&nbsp;";

    // assign variables to template
    $smarty->assign('month_calendar', 	$calendar);
    $smarty->assign('calendar_owner', 	$_SESSION['calendarname']);
    $smarty->assign("nav_links",	"$dayback");
    $smarty->assign("nav_rechts",	"$dayforward");
    $smarty->assign('header_date',	$text . " $additionaltext");
    $smarty->assign('cur_date', 	date(Lang::getLanguageString("gentemp_date_format_php"), $date));
    $smarty->assign('SID', 		SID);
    $smarty->assign('date', 		$date);
    if( Date("Ymd")==Date("Ymd",$date) ) {
	$smarty->assign('menu_today', "yes");
    }
    else {
	$smarty->assign('menu_today', "no");
    }

    $smarty->assign("timefmt", $_SESSION["MGW"]->settings["timefmt"]);

    $smarty->assign("priv",Lang::getLanguageString("gentemp_short_private"));
	$smarty->assign("avail",Lang::getLanguageString("gentemp_short_available"));
	$smarty->assign("part",Lang::getLanguageString("gentemp_short_participants"));

	//appt type legend :
	$smarty->assign("appt_type_legend",get_appt_type_legend());

	$smarty->display('calendar_day.tpl');
    $smarty->clear_assign('action');
    $smarty->clear_assign('holiday');
    $smarty->clear_assign('celebration_day');
    exit();
}


// ===========================================
// Show Template : create new appointment
// ===========================================
if ($action=="new1" || $action=="new2" || $action=="new") {


	if($newtype=="meeting") {
		// parties are already selected
		$ar_parties=explode("|",$parties);
		$nb_part = sizeof($ar_parties);

		$sql_spart = "SELECT id as userid, ".$conn->Concat("firstname", "' '", "lastname")." AS name
			 		  FROM mgw_users
					  WHERE NOT(level=".UDELETED.") AND ( ";
		for ($i=0;$i<$nb_part;$i++)
			{
			//format sql with selected participants
			$sql_spart.="id = '".$ar_parties[$i]."' OR ";
			}
	   $sql_spart.=" (1=0) )
			    	 ORDER BY lastname";

		if(!$res = $conn->Execute($sql_spart)) die(showSQLerror($sql_spart, $conn->ErrorMsg(), __LINE__, __FILE__));
		while ($row = $res->FetchRow()) {
			$spart_ar = array(	"userid" => $row["userid"],
								"name"	=> $row["name"],
								"can_be_imposed" => current_user_can_create_for($row["userid"]),
								"I_chk" => "",
								"S_chk" => "CHECKED"
								);
			$smarty->append("spartie", $spart_ar);
		}
	}
	else {
		// according to settings : select current user by default:
	    if ($_SESSION["MGW"]->settings['calendar_be_participant']==1) {
			$currentuser = array( 	"userid" => $_SESSION["MGW"]->userid ,
									"name" => $_SESSION["MGW"]->fullusername);

			$smarty->append("spartie", $currentuser);
	    }
	}


	// subject all participants that current user can create for,   EXCEPT current user:
	$sql = "SELECT a.id_owner as userid,".$conn->Concat("b.firstname", "' '", "b.lastname")." as name
			FROM mgw_calendar_rights a, mgw_users b
			WHERE 	NOT(b.level=".UDELETED.") AND a.id_user = '".$_SESSION["MGW"]->userid."'
				AND	a.modify = '1'
				AND	a.id_owner = b.id
			ORDER BY b.lastname";


	/*$sql  = "SELECT id as userid, ".$conn->Concat("firstname", "' '", "lastname")." AS name
		FROM mgw_users
		WHERE NOT(level=".UDELETED.") AND username <> '".$_SESSION["MGW"]->username."'
		ORDER BY lastname";
	*/
	if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
		while ($row = $res->FetchRow()) {
			$smarty->append("partie", $row);
		}

	//// |--| ////
	//$smarty->assign("--"," :: -- :: ");
	///////////////

	// create selectboxes
	$sdate=getDate($date);

	// days
	$sdays = new mSelectBox("start_day");
	$sdays->setHandler("OnChange", "start_day_change()");
	if ($newtype=="meeting") {
	 	$sdays->setEnabled(false);
	}
	$smarty->assign("serial_start_day", $sdays->getSB_Day($sdate["mday"], false));

	// months
	$smonths = new mSelectBox("start_month");
	$smonths->setHandler("OnChange", "start_month_change()");
	if ($newtype=="meeting") {
	 	$smonths->setEnabled(false);
	}
	$smarty->assign("serial_start_month", $smonths->getSB_Month($sdate["mon"],false));

	// years
	$syears = new mSelectBox("start_year");
	$syears->setHandler("OnChange", "start_year_change()");
	if ($newtype=="meeting") {
	 	$syears->setEnabled(false);
	}
	$smarty->assign("serial_start_year", $syears->getSB_Year(date("Y",time()),date("Y",time())+30,$sdate["year"],false));


///// |--| /////
  	// create selectboxes for end date-lists

	// days
	$sdays = new mSelectBox("serial_end_day");
	$smarty->assign("serial_end_day", $sdays->getSB_Day($sdate["mday"], false));

	// months
	$smonths = new mSelectBox("serial_end_month");
	$smonths->setHandler("OnChange", "keep_nbday_coherence('serial_end')");
	$smarty->assign("serial_end_month", $smonths->getSB_Month($sdate["mon"],false));

	// years
	$syears = new mSelectBox("serial_end_year");
	$syears ->setHandler("OnChange", "keep_nbday_coherence('serial_end')");
	$smarty->assign("serial_end_year", $syears->getSB_Year(date("Y",time()),date("Y",time())+30,$sdate["year"],false));







	// temporaire
	/*
	$smarty->assign("telephone",$telephone);
	$smarty->assign("disponibility",$disponibility);
	$smarty->assign("subject_summ",$subject_summ);
	$smarty->assign("location",$location);
	$smarty->assign("thema",$thema);
	*/

	// $app_start_time : debut de la journee (fixé dans les reglages)
	// $app_end_time : fin de la journee (fixé dans les reglages)
	// $timemask : format d'affichage des heures (fixé dans les reglages)

	//$appt_start_default_id = 0;
	//////////

	for( $t=$app_start_time, $i=1; $t <= $app_end_time; $t+=$interval_sec, $i++) {
		$appointment_start_list = array(
			"timestamp" 	=> $t,
			"time_label"  	=> date($timemask, $t),
			"sel" 		=> ($date==$t ? " selected" : "")
		);

		/////// |--|////////
		if ($t==$start_time) {
			$id_day_start_time = $i;
		}
		//////

		$appointment_end_list = array(
			"timestamp" => ($t+$interval_sec),
			"time_label" => date($timemask, ($t+$interval_sec)),
			"sel"   => ($end_date==$t ? " selected" : "")
		);

		/////// |--|////////
		if ($t==$end_time) {
			$id_day_end_time = $i;
		}
		//////

		$smarty->append("appointment_start_list", $appointment_start_list);
		$smarty->append("appointment_end_list", $appointment_end_list);
	}

//echo $id_day_start_time."&nbsp;".$id_day_end_time."<br>";

	$smarty->assign('id_day_start_time',$id_day_start_time);
	$smarty->assign('id_day_end_time',$id_day_end_time);


	$smarty->assign('newtype',$newtype);
	$smarty->assign('date',  $date);
	if ($newtype == "meeting") {
		$smarty->assign('back',  substr($_SERVER["HTTP_REFERER"],0,strpos($_SERVER["HTTP_REFERER"],"?"))."?action=view&serial_week=".get_weeknumber($date)."&serial_year=".date("Y",$date)."&parties=$parties&appointment_duration=".(mktime(0,0,0,1,1,1971)+$end_date-$date+$interval_sec)."&".SID);
	}
	else $smarty->assign('back',  "index.php?date=$date&".SID);

	$smarty->assign('id_current_user',$_SESSION["MGW"]->userid);
	$smarty->assign('sname', "new");
	$smarty->assign('datum', date(Lang::getLanguageString("gentemp_date_format_php"), $date));
	$smarty->assign('temp_err_no_start', Lang::getLanguageString("temp_err_no_start"));
	$smarty->assign('temp_err_no_end', Lang::getLanguageString("temp_err_no_end"));
	$smarty->assign('temp_err_end_before', Lang::getLanguageString("temp_err_no_before"));
	$smarty->assign('temp_err_thema_long', Lang::getLanguageString("temp_err_thema_long"));
	$smarty->assign('temp_err_external_long', Lang::getLanguageString("temp_err_external_long"));

	$smarty->assign('temp_i_will', Lang::getLanguageString("i_will_part"));
	$smarty->assign("temp_title", Lang::getLanguageString("temp_newappointment"));
	$smarty->assign("submenu", 1);
	$smarty->assign("suvalue", Lang::getLanguageString("temp_create"));
	$smarty->assign("appointment_attribute",0);
	$smarty->assign("telephone","");

	///// |--| /////
		//default values
		$sched_type = 0;
		$id_appt_type = 0;
		$id_appt_loc_type = 0;
		$availability	= 1;
	initialise_objects($sched_type,$id_appt_type,$id_appt_loc_type,$availability);


	$smarty->display('calendar_date_edit_v2.tpl'); //new.tpl
	////////////////

//	$smarty->display('calendar_date_edit_v2.tpl'); //new.tpl

} // FIN IF NEW1




// ===========================================
// Show Template : edit appointment
// ===========================================
if ($action=="editform" || $action=="editconflict") {  // edit in conflict case
    $id = (int) $_GET["id"];

    // check initial user
    $sql  = "SELECT DISTINCT inituserid FROM mgw_calendar WHERE id = ".$id;

    if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    $row = $res->FetchRow();
    $iu = $row["inituserid"];

    if(isset($_GET["tmpid"])){
	$tmpid = (int) $_GET["tmpid"];
	$sql2  = "SELECT DISTINCT inituserid FROM mgw_calendar_tmp WHERE id = ".$tmpid;

	if(!$res2 = $conn->Execute($sql2)) exit(showSQLerror($sql2, $conn->ErrorMsg(), __LINE__, __FILE__));
	$row2 = $res2->FetchRow();
	$iu2 = $row2["inituserid"];
    }

    if (!isset($iu) && isset($iu2)) $iu = $iu2;

    if ($action=="editform") {

	//check if appointment is subjected:
	$sql_check = 	"SELECT DISTINCT id FROM mgw_calendar
					WHERE id='$id' AND (id_class='0' OR id_class='1')";
    if(!$res_check = $conn->Execute($sql_check)) exit(showSQLerror($sql_check, $conn->ErrorMsg(), __LINE__, __FILE__));
	// if subjected : newtype = meeting : disable date changing
	if ($res_check->NumRows() > 0) $newtype = "meeting";

	// get participants
	$sql_sel = "SELECT b.id AS userid, ".$conn->Concat("b.firstname", "' '", "b.lastname")." AS name, a.id_class FROM mgw_users b, mgw_calendar a WHERE NOT(b.level=".UDELETED.") AND a.userid = b.id AND a.id = ".$id." ORDER BY b.lastname";
	$sql_not_in = " NOT IN (";
	$current_is_selected = FALSE;
	// assign selected participants
    if(!$res = $conn->Execute($sql_sel)) exit(showSQLerror($sql_sel, $conn->ErrorMsg(), __LINE__, __FILE__));
	while ($row = $res->FetchRow()) {
		$sql_not_in .=$row["userid"]."," ;
		if ($row["userid"]==$_SESSION["MGW"]->userid) {
		    $current_is_selected = TRUE;
		}
		$spart_ar = array(	"userid" => $row["userid"],
								"name"	=> $row["name"],
								"can_be_imposed" => current_user_can_create_for($row["userid"]),
								"I_chk" => (current_user_can_create_for($row["userid"]) && $row["id_class"]=="1" ? "CHECKED" : ""),
								"S_chk" => (current_user_can_create_for($row["userid"]) && $row["id_class"]=="1" ? "" : "CHECKED")
								);
		$smarty->append("spartie", $spart_ar);
	}
	$sql_not_in .="0 )" ;



	// select all participants that current user can create for ,   EXCEPT current user:
	$sql_subj = "SELECT a.id_owner as userid,".$conn->Concat("b.firstname", "' '", "b.lastname")." as name
			FROM mgw_calendar_rights a, mgw_users b
			WHERE 	NOT(b.level=".UDELETED.") AND a.id_user = '".$_SESSION["MGW"]->userid."'
				AND	a.modify = '1'
				AND	a.id_owner = b.id
				AND a.id_owner $sql_not_in
			ORDER BY b.lastname";

	// assign available participants
    if(!$res = $conn->Execute($sql_subj)) exit(showSQLerror($sql_subj, $conn->ErrorMsg(), __LINE__, __FILE__));
	while ($row = $res->FetchRow()) {
		$smarty->append("partie", $row);
	}
	if (!$current_is_selected) {
		$spart_ar = array(	"userid" => $_SESSION["MGW"]->userid,
							"name" => $_SESSION["MGW"]->fullusername);
		$smarty->append("partie", $spart_ar);
	}

	//$sql = "SELECT a.date, b.id AS userid, ".$conn->Concat("b.lastname", "', '", "b.firstname")." AS name FROM mgw_users b LEFT OUTER JOIN mgw_calendar a ON a.userid = b.id AND a.id = ".$id./*" AND a.userid <> ".$_SESSION["MGW"]->userid.*/" ORDER BY b.lastname";

	//read appointment from DB
	//$sql2  = "SELECT * FROM	mgw_calendar WHERE id = ".$id.($_SESSION["MGW"]->rights["calendar"]->modify_others || is_modifiable_by_current_user($id) ? "" : " AND userid = ".$_SESSION["MGW"]->userid);
	$sql2  = "SELECT * FROM mgw_calendar WHERE id = ".$id.(queryRights2_bool('root_modules_calendar_modifyothers') ? "" : " AND userid = ".$_SESSION["MGW"]->userid);
    }

    else if ($action=="editconflict") {
	// select partipicians
	$sql  = "SELECT a.date, b.id as userid, ".$conn->Concat("b.lastname", "', '", "b.firstname")." AS name FROM mgw_users b LEFT OUTER JOIN mgw_calendar_tmp a ON a.userid = b.id AND a.id = ".$tmpid./*" AND a.userid <> ".$_SESSION["MGW"]->userid.*/" WHERE NOT(b.level=".UDELETED.") ORDER BY b.lastname";

	while ($row = $res->FetchRow()) {
	 if ($row["userid"] != $_SESSION["MGW"]->userid) {

	    if ($row["date"]) $smarty->append("spartie", $row);
	    else $smarty->append("partie", $row);
	 }
	}
	//read appointment from DB
	$sql2  = "SELECT * FROM	mgw_calendar_tmp WHERE id = ".$tmpid;
    }







/*    $temp_will_selected = false;
    while ($row = $res->FetchRow()) {
	if ($row["userid"] != $_SESSION["MGW"]->userid) {

	    if ($row["date"]) $smarty->append("spartie", $row);
	    else $smarty->append("partie", $row);
	}
	else {
	    $temp_will_selected = true;
	}

    }
    $smarty->assign('temp_will_selected', $temp_will_selected);
*/

    if(!$res2 = $conn->Execute($sql2)) exit(showSQLerror($sql2, $conn->ErrorMsg(), __LINE__, __FILE__));

    $row2 = $res2->FetchRow();

    if ($row2["repeat_mode"] > 0) {
	$bdate = $res->UnixTimeStamp($row2["rep_until"]);
    }
    else {
	$bdate = $res->UnixTimeStamp($row2["date"]);
    }

    // create selectboxes
// |--| //

	// days
	$sdays = new mSelectBox("start_day");
	if ($newtype=="meeting") {
	 	$sdays->setEnabled(false);
	}
	$sdays->setHandler("OnChange", "start_day_change()");
	$smarty->assign("serial_start_day", $sdays->getSB_Day(date("d",$res->UnixTimeStamp($row2["date"])), false));

	// months
	$smonths = new mSelectBox("start_month");
	if ($newtype=="meeting") {
	 	$smonths->setEnabled(false);
	}
	$smonths->setHandler("OnChange", "start_month_change()");
	$smarty->assign("serial_start_month", $smonths->getSB_Month(date("m",$res->UnixTimeStamp($row2["date"])),false));

	// years
	$syears = new mSelectBox("start_year");
	if ($newtype=="meeting") {
	 	$syears->setEnabled(false);
	}
	$syears->setHandler("OnChange", "start_year_change()");
	$smarty->assign("serial_start_year", $syears->getSB_Year(date("Y",time()),date("Y",time())+30,date("Y",$res->UnixTimeStamp($row2["date"])),false));


  	// create selectboxes for end date-lists
	// days
	$sdays = new mSelectBox("serial_end_day");
	$smarty->assign("serial_end_day", $sdays->getSB_Day(date("d",$bdate), false));

	// months
	$smonths = new mSelectBox("serial_end_month");
	$smonths->setHandler("OnChange", "keep_nbday_coherence('serial_end')");
	$smarty->assign("serial_end_month", $smonths->getSB_Month(date("m",$bdate),false));

	// years
	$syears = new mSelectBox("serial_end_year");
	$syears->setHandler("OnChange", "keep_nbday_coherence('serial_end')");
	$smarty->assign("serial_end_year", $syears->getSB_Year(date("Y",time()),date("Y",time())+30,date("Y",$bdate),false));


	/*
	$smarty->assign("serial_start_day",   select_tag(       $res->UnixTimeStamp($row2["date"]), "serial_start_day"));
    $smarty->assign("serial_start_month", select_monat(     $res->UnixTimeStamp($row2["date"]), "serial_start_month"));
    $smarty->assign("serial_start_year",  select_jahr( $res->UnixTimeStamp($row2["date"]), "serial_start_year"));

    $smarty->assign("serial_end_day",     select_tag(	$bdate, "serial_end_day"));
    $smarty->assign("serial_end_month",   select_monat(	$bdate, "serial_end_month"));
    $smarty->assign("serial_end_year",    select_jahr(  $bdate, "serial_end_year"));
	*/


	$smarty->assign("subject_summ", str_decode($row2["subject_summ"]));
	$smarty->assign("telephone", $row2["telephone"]);

	///
    $smarty->assign("thema", str_decode($row2["subject"]));
    $smarty->assign("location", str_decode($row2["location"]));
    $smarty->assign("external", str_decode($row2["external"]));

    $smarty->assign("prsel", ($row2["private"]==0 ? "" : " checked"));
    //// |--| : a voir : holiday
	//$smarty->assign("daysel", ($row2["day_ind"]==0 ? "" : " checked"));
    //$smarty -> assign("holisel", ($row2["holiday_id"]==0 ? "" : " checked"));

	/*$smarty->assign("morning_sel", ($row2["id_scheduling"]==1 ? " checked" : ""));
	$smarty->assign("afternoon_sel", ($row2["id_scheduling"]==2 ? " checked" : ""));
	$smarty->assign("wholeday_sel", ($row2["id_scheduling"]==3 ? " checked" : ""));
	///////
	*/

    $smarty -> assign("appointment_attribute", $row2["repeat_mode"]);

    $old_appointment_start = $res->UnixTimeStamp($row2["date"]);
    $old_appointment_to = $old_appointment_start + 60 * $row2["duration"];
    $date = $old_appointment_start;

    // Set new values for time-handling
    $actual_date_arr = getdate($date);

    //Start time (according to settings) of selected day
    $start_time = mktime(0,0,0, $actual_date_arr["mon"], $actual_date_arr["mday"], $actual_date_arr["year"]) + $starthour * 3600;

    // End time (according to settings) of selected day
    $end_time = mktime(0,0,0, $actual_date_arr["mon"], $actual_date_arr["mday"], $actual_date_arr["year"]) + $endhour   * 3600;

    // Application Start time (according to settings) of selected day
    $app_start_time = mktime(0,0,0, $actual_date_arr["mon"], $actual_date_arr["mday"], $actual_date_arr["year"]);


    // Application End time (according to settings) of selected day
    $app_end_time = mktime(0,0,0, $actual_date_arr["mon"], $actual_date_arr["mday"], $actual_date_arr["year"]) + 23.5 * 3600;

    for( $t=$app_start_time; $t < $app_end_time; $t+=$interval_sec) {
	$appointment_start_list = array(
					"timestamp" => $t,
					"time_label" => date($timemask, $t),
					"sel" => ($t == $old_appointment_start ? " selected" : "")
					);
	//echo "<BR>START : ";
	//print_r($appointment_start_list);
	$appointment_end_list = array(
				      "timestamp"   => ($t+$interval_sec),
				      "time_label"  => date($timemask, ($t+$interval_sec)),
				      "sel"   => ($t+$interval_sec == $old_appointment_to ? " selected" : "")
				      );
	//echo "<BR>END : ";
	//print_r($appointment_end_list);

	$smarty->append("appointment_start_list", $appointment_start_list);
	$smarty->append("appointment_end_list", $appointment_end_list);
    }

    $smarty->assign('date', $date);

    if ($ind==1) $smarty->assign('back', "index.php?action=sel&date=$date&".SID);
    else $smarty->assign('back', "index.php?date=$date&".SID);

    if ($action=="editconflict") {
	db_delete_date_from_tmp($tmpid);
    }

    $smarty->assign('datum', date(Lang::getLanguageString("gentemp_date_format_php"), $date));
    $smarty->assign('sname', "update");
    $smarty->assign('id', $id);
    $smarty->assign("temp_title", Lang::getLanguageString("temp_editappointment"));
    $smarty->assign("submenu", -1);
    $smarty->assign("suvalue", Lang::getLanguageString("temp_edit"));
    $smarty->assign('temp_i_will', Lang::getLanguageString("i_will_part"));


	///// |--| /////

	$id_class = $row2["id_class"];
	if ($id_class!=2) {
	    // appointment is subjected or on standby:
		$sql_class = "SELECT * FROM mgw_calendar_class WHERE id=$id_class";
		if(!$res_class = $conn->Execute($sql_class)) exit(showSQLerror($sql_class, $conn->ErrorMsg(), __LINE__, __FILE__));
		$row_class = $res_class->FetchRow();
		$class = array( "text" => Lang::getLanguageString("class_".$row_class["class"]),
						"color" => $row_class["color"]
					);
	}
	else {
		$class = array( "text" => "",
						"color" => ""
					);
	}

	$smarty->assign('class',$class);

	$smarty->assign('id_current_user',$_SESSION["MGW"]->userid);
	$smarty->assign('newtype',$newtype);

		//default values
		$sched_type = $row2["id_scheduling"];
		$id_appt_type = $row2["id_appt_type"];
		$id_appt_loc_type = $row2["id_location_type"];
		$availability	= $row2["availability"];

	initialise_objects($sched_type,$id_appt_type,$id_appt_loc_type,$availability);
	///////////

    $smarty->display('calendar_date_edit_v2.tpl');
}

// ===========================================
// Show Template : edit time serial
// ===========================================
if ($action=="editserial" || $action=="edittsconflict") {
    $id = (int) $_GET["id"];
    $tmpid = isset($_GET["tmpid"]) ? (int) $_GET["tmpid"] : "";

    // check initial user
    $sql  = "SELECT DISTINCT inituserid FROM mgw_calendar WHERE id = ".$id;

    if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    $row  = $res->FetchRow();
    $iu = $row["inituserid"];

    $sql2  = "SELECT DISTINCT inituserid FROM mgw_calendar_tmp WHERE id = ".$id;

    if(!$res2 = $conn->Execute($sql2)) exit(showSQLerror($sql2, $conn->ErrorMsg(), __LINE__, __FILE__));
    $row2  = $res2->FetchRow();
    $iu2 = $row2["inituserid"];

    if (!isset($iu) && isset($iu2)) $iu = $iu2;

    if($action=="editserial"){
	//select partipiciants
	//$sql  = "SELECT a.date, b.id, ".$conn->Concat("b.lastname", "', '", "b.firstname")." AS name FROM mgw_users b LEFT OUTER JOIN mgw_calendar a ON a.userid = b.id AND a.id = $id ORDER BY b.lastname";

	// get participants

	$sql_sel = "SELECT b.id AS userid, ".$conn->Concat("b.firstname", "' '", "b.lastname")." AS name FROM mgw_users b, mgw_calendar a WHERE NOT(b.level=".UDELETED.") AND a.userid = b.id AND a.id = ".$id." ORDER BY b.lastname";
	$sql_not_in = " NOT IN (";
	$current_is_selected = FALSE;
	// assign selected participants
    if(!$res = $conn->Execute($sql_sel)) exit(showSQLerror($sql_sel, $conn->ErrorMsg(), __LINE__, __FILE__));
	while ($row = $res->FetchRow()) {
		$sql_not_in .=$row["userid"]."," ;
		if ($row["userid"]==$_SESSION["MGW"]->userid) {
		    $current_is_selected = TRUE;
		}
		$smarty->append("spartie", $row);
	}
	$sql_not_in .="0 )" ;

	// subject all participants that current user can create for ,   EXCEPT current user:
	$sql_subj = "SELECT a.id_owner as userid,".$conn->Concat("b.firstname", "' '", "b.lastname")." as name
			FROM mgw_calendar_rights a, mgw_users b
			WHERE 	NOT(b.level=".UDELETED.") AND a.id_user = '".$_SESSION["MGW"]->userid."'
				AND	a.modify = '1'
				AND	a.id_owner = b.id
				AND a.id_owner $sql_not_in
			ORDER BY b.lastname";

	// assign available participants
    if(!$res = $conn->Execute($sql_subj)) exit(showSQLerror($sql_subj, $conn->ErrorMsg(), __LINE__, __FILE__));
	while ($row = $res->FetchRow()) {
		$smarty->append("partie", $row);
	}
	if (!$current_is_selected) {
		$spart_ar = array(	"userid" => $_SESSION["MGW"]->userid,
							"name" => $_SESSION["MGW"]->fullusername);
		$smarty->append("partie", $spart_ar);
	}

	$sql2  = "SELECT * FROM mgw_calendar WHERE id = ".$id;
    }
    elseif($action=="edittsconflict"){
	//select partipiciants
	$sql  = "SELECT a.date, b.id, ".$conn->Concat("b.lastname", "', '", "b.firstname")." AS name FROM mgw_users b LEFT OUTER JOIN mgw_calendar_tmp a ON a.userid = b.id AND a.id = $tmpid WHERE NOT(b.level=".UDELETED.") ORDER BY b.lastname";
	while ($row = $res->FetchRow()) {
	 if ($row["userid"] != $_SESSION["MGW"]->userid) {

	    if ($row["date"]) $smarty->append("spartie", $row);
	    else $smarty->append("partie", $row);
	 }
	}

	$sql2  = "SELECT * FROM mgw_calendar_tmp WHERE id = ".$tmpid;
    }

    if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

    /*
	$temp_will_selected = false;
    while ($row = $res->FetchRow()) {
	if ($row["userid"] != $_SESSION["MGW"]->userid) {
	    if ($row["date"]) $smarty->append("spartie", $row);
	    else $smarty->append("partie", $row);
	}
	else {
	    $temp_will_selected = true;
	}

    }
    $smarty->assign('temp_will_selected', $temp_will_selected);
	*/

    if(!$res2 = $conn->Execute($sql2)) die(showSQLerror($sql2, $conn->ErrorMsg(), __LINE__, __FILE__));
    $row2  = $res2->FetchRow();

    $edate = $res->UnixTimeStamp($row2["rep_from"]);
    $bdate = $res->UnixTimeStamp($row2["rep_until"]);

    //---- Start day
	// days
	$sdays = new mSelectBox("serial_start_day");
	$smarty->assign("serial_start_day", $sdays->getSB_Day(date("d",$edate), false));

	// months
	$smonths = new mSelectBox("serial_start_month");
	$smonths->setHandler("OnChange", "start_date_change()");
	$smarty->assign("serial_start_month", $smonths->getSB_Month(date("m",$edate),false));

	// years
	$syears = new mSelectBox("serial_start_year");
	$syears->setHandler("OnChange", "start_date_change()");
	$smarty->assign("serial_start_year", $syears->getSB_Year(date("Y",time()),date("Y",time())+30,date("Y",$edate),false));


	//---- End day
	// days
	$sdays = new mSelectBox("serial_end_day");
	$smarty->assign("serial_end_day", $sdays->getSB_Day(date("d",$bdate), false));

	// months
	$smonths = new mSelectBox("serial_end_month");
	$smonths->setHandler("OnChange", "end_date_change()");
	$smarty->assign("serial_end_month", $smonths->getSB_Month(date("m",$bdate),false));

	// years
	$syears = new mSelectBox("serial_end_year");
	$syears->setHandler("OnChange", "end_date_change()");
	$smarty->assign("serial_end_year", $syears->getSB_Year(date("Y",time()),date("Y",time())+30,date("Y",$bdate),false));

	/*
	// Auswahlisten Datum
    $smarty->assign("serial_end_day",   select_tag(       $bdate, "serial_end_day"));
    $smarty->assign("serial_end_month", select_monat(     $bdate, "serial_end_month"));
    $smarty->assign("serial_end_year",  select_jahr(2010, $bdate, "serial_end_year"));

    $smarty->assign("serial_start_day",   select_tag(     $edate, "serial_start_day"));
    $smarty->assign("serial_start_month", select_monat(   $edate, "serial_start_month"));
    $smarty->assign("serial_start_year",  select_jahr(2010, $edate, "serial_start_year"));
	*/

	/// |--| ///
    $smarty -> assign("subject_summ", str_decode($row2["subject_summ"]));
	$smarty -> assign("telephone", $row2["telephone"]);
	///////
    $smarty -> assign("thema", str_decode($row2["subject"]));
    $smarty -> assign("location", str_decode($row2["location"]));
    $smarty -> assign("external", str_decode($row2["external"]));

	//// |--| : a voir :private et holiday
   /* $smarty->assign("prsel", ($row2["private"]==0 ? "" : " checked"));
    $smarty->assign("daysel", ($row2["day_ind"]==0 ? "" : " checked"));
    $smarty->assign("holisel", ($row2["holiday_id"]==0 ? "" : " checked"));
   */

    $smarty -> assign("appointment_attribute", $row2["repeat_mode"]);

    $from2 = $res->UnixTimeStamp($row2["date"]);
    $to2 = $from2 + 60 * $row2["duration"];
    $date = $from2;

    $actual_date_arr     = getdate($date);
    $start_time =  mktime(0,0,0, $actual_date_arr["mon"], $actual_date_arr["mday"], $actual_date_arr["year"]) + $starthour *3600;
    $end_time   =  mktime(0,0,0, $actual_date_arr["mon"], $actual_date_arr["mday"], $actual_date_arr["year"]) + $endhour*3600;

    for( $t=$app_start_time; $t < $app_end_time; $t+=$interval_sec) {
	$sstr = date("Hi", $t);
	$estr = date("Hi", $t+$interval_sec);
	$fromstr = date("Hi", $from2);
	$tostr = date("Hi", $to2);
	$appointment_start_list = array(
					"timestamp"   => $t,
					"time_label"  => date($timemask, $t),
					"sel" 	=> ($sstr == $fromstr ? " selected " : "")
					);

	$appointment_end_list = array(
				      "timestamp"   => ($t+$interval_sec),
				      "time_label"  => date($timemask, ($t+$interval_sec)),
				      "sel"   => ($estr == $tostr ? " selected " : "")
				      );

	$smarty->append("appointment_start_list", $appointment_start_list);
	$smarty->append("appointment_end_list",   $appointment_end_list);
    }

    $smarty->assign('date', $date);

    if ($ind==1) $smarty->assign('back', "index.php?action=sel&date=$date&".SID);
    else $smarty->assign('back', "index.php?date=$date&".SID);

    if ($action=="edittsconflict") db_delete_date_from_tmp($tmpid);

    $smarty->assign('temp_i_will', Lang::getLanguageString("i_will_part"));
   // $smarty->assign('datum', date( Lang::getLanguageString("gentemp_date_format_php"), $date));
    $smarty->assign('sname', "tsupdate");
    $smarty->assign('id', $id);
    $smarty->assign('svalue', Lang::getLanguageString("temp_editappointment"));
    $smarty->assign('contentheader', Lang::getLanguageString("temp_editappointment"));


	///// |--| /////
		//default values
		$sched_type = $row2["id_scheduling"];
		$id_appt_type = $row2["id_appt_type"];
		$id_appt_loc_type = $row2["id_location_type"];
		$availability	= $row2["availability"];

	initialise_objects($sched_type,$id_appt_type,$id_appt_loc_type,$availability);
	///////////

    if ($iu == $_SESSION["MGW"]->userid) $smarty->display('calendar_dateserie_edit.tpl');
}// FIN edit serial

// ===================================================================================
// Show Template : Appointment list (if two or more appointments start at same time)
// ===================================================================================
if($action=="sel") {
    $icons = getIconStrings();
    $sql_appointment_start  = $conn->DBTimeStamp($date);

    if ($_SESSION['calendarid']=="all") {
	$sql_owner_part="";
    }
    elseif($_SESSION['calendarid']!="") {
	$sql_owner_part="userid = ".(int)$_SESSION['calendarid']." AND";
    }

    $sql = "SELECT * FROM mgw_calendar WHERE $sql_owner_part date = ".$sql_appointment_start." ORDER BY duration";

    if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    $num = $res->RecordCount();

    while ($row = $res->FetchRow()) {
	$appointment_start = $res->UnixTimeStamp($row["date"]);
	$appointment_end   = $appointment_start + $row["duration"] * 60;


	if ($_SESSION["MGW"]->userid == $_SESSION['calendarid']) {
	    $myid = $row["id"];
	    $detlink  = "<a CLASS=\"edit\" href=\"details.php?id=$myid&userid=".$_SESSION["MGW"]->userid."&".SID."\">" . $icons["details"] . "</a>";
	    $editlink = "<a CLASS=\"edit\" href=\"index.php?action=editform&ind=1&id=$myid&".SID."\">" . $icons["edit"] . "</a>";
	    $dellink  = "<a CLASS=\"delete\" href=\"index.php?action=del&id=$myid&".SID."\">" . $icons["delete"] . "</a>";
	    if ($row["dategroup_id"] > 0) $tseditlink = "<a CLASS=\"edit\" href=\"index.php?action=editserial&ind=1&id=$myid&".SID."\">" . Lang::getLanguageString("temp_row_action_label_serialedit") . "</a>";
	    else $tseditlink = "";
	    $template_row = array( "from" 	  	=> "<strong>". date($timemask,  $appointment_start)."</strong>",
				   "to" => "<strong>". date($timemask,  $appointment_end)."</strong>",
				   //SUBJECT !!!
				   "topic" =>  short_string(str_decode($row["subject_summ"]),$max_subject_length),
				   "class" => "tab",
				   "location" 	=>  str_decode($row["location"]),
				   "rowactions" =>  $detlink . $icons["space"] . $editlink . $icons["space"] . $dellink . $icons["space"] . $tseditlink
				   );
			$smarty->append("td", $template_row);
	}

	else if ($row["private"] == 0 && $_SESSION["MGW"]->userid != $_SESSION['calendarid']) {
	    $myid = $row["id"];
	    $detlink  = "<a CLASS=\"edit\" href=\"details.php?id=$myid&userid=".$_SESSION["MGW"]->userid."&".SID."\">" . $icons["details"] . "</a>";
	    $template_row = array( "from" 	 	=> "<strong>".date($timemask,  $appointment_start)."</strong>",
				   "to" => "<strong>".date($timemask,  $appointment_end)."</strong>",
				   "inituser" => getRealUsername($row["inituserid"]),
				   //SUBJECT !!
				   "topic" =>  short_string(str_decode($row["subject_summ"]),$max_subject_length),
				   "class" => "tab",
				   "location" =>  str_decode($row["location"]),
				   "rowactions" =>  $detlink
				   );
		/* if calendarid==all, remove duplicate entries */
		if ($_SESSION['calendarid']=="all") {
			$templatevars=$smarty->get_template_vars();
			if (!$templatevars["td"]||!in_array_buggyphp($template_row,$templatevars["td"])) {
				$smarty->append("td", $template_row);
			}
		} else {
			$smarty->append("td", $template_row);
		}
	}

	else if ($row["private"] == 1 && $_SESSION["MGW"]->userid != $_SESSION['calendarid']) {
	    $myid = $row["id"];
	    $template_row = array( "from" 	  	=> "<strong>".date($timemask,  $appointment_start)."</strong>",
				   "to" => "<strong>".date($timemask,  $appointment_end)."</strong>",
				   "topic" =>  Lang::getLanguageString("gentemp_private"),
				   "class" => "tab",
				   "location" 	=> "",
				   "rowactions" => ""
				   );
	$smarty->append("td", $template_row);
	}
    }


    $smarty->assign('date', $date);

    if ($ind == 1)  $smarty->assign("back_url", "index.php?date=$date&".SID);
    else if ($ind == 2)  $smarty->assign("back_url", "week.php?date=$date&".SID);

    // create monthview-calendar, based on $date
    $month_cal = get_monthview_static( $date, $_SESSION['calendar_year'], $_SESSION['calendar_month']);
    $smarty->assign('month_cal',   $month_cal);

    $smarty->assign('header_date', Lang::getLanguageString("temp_header_text") . " " .  date( Lang::getLanguageString("gentemp_date_format_php").", ".$timemask , $appointment_start));
    $smarty->assign('datum',       date( Lang::getLanguageString("gentemp_date_format_php") , $date));

    $smarty->display('calendar_select_date.tpl');
}





//|--| : ALL CASE :

function initialise_objects($sched_type,$id_appt_type,$id_appt_loc_type,$availability){
/* used variables :
	$sched_type 		//scheduling type (0..3)
	$id_appt_type		//appointment type (0..4)
	$id_appt_loc_type	//location type (0/1)
	$availability		//availability (0/1)
*/
global $conn,$smarty;

// create radioboxes for scheduling types ( time, morning, afternoon, wholeday)
	$sql_sched = "SELECT * FROM mgw_calendar_scheduling_type";
	if(!$res_sched = $conn->Execute($sql_sched)) die(showSQLerror($sql_sched, $conn->ErrorMsg(), __LINE__, __FILE__));
	while ($row_sched = $res_sched->FetchRow()) {

		$scheduling_list = array( "id" => $row_sched["id"] ,
								  "type" => $row_sched["type"] , // type in english
								  "text" => Lang::getLanguageString("gentemp_".$row_sched["type"]) , // type translated
								  "chk" => ($row_sched["id"]==$sched_type ? " checked" : "") // checked or not
								);

		$smarty->append("scheduling_list", $scheduling_list);
	}

	// create selectbox for appointment types ( rest, formation, meeting, appointment )

	function generate_sql_vars(&$sql, &$res, &$row, $type){
		$sql = "sql_".$type;
		$res = "res_".$type;
		$row = "row_".$type;
	}

	$script_appt_type_color  = array ( "script_name" => "appt_type_colorize",
								 "script_code" =>  "function appt_type_colorize(obj_select){
								 					\nfor(i=0;i<obj_select.length;i++)
													\n{"
								);
	generate_sql_vars($sql_var,$res_var,$row_var,"type");

	$$sql_var = "SELECT * FROM mgw_calendar_appt_type";
	if(!$$res_var = $conn->Execute($$sql_var)) die(showSQLerror($$sql_var, $conn->ErrorMsg(), __LINE__, __FILE__));
	while ($$row_var = $$res_var->FetchRow()) {

		$row_tmp = array();
		$row_tmp = $$row_var;

		$appointment_type = array( "id" => $row_tmp["id"] ,
								  "type" => Lang::getLanguageString("gentemp_".$row_tmp["type"]) , // type
								  "color" => $row_tmp["color"] , // color
								  "sel" => ($row_tmp["id"]==$id_appt_type ? " selected" : "") // checked or not
								);
		$appt_id = $appointment_type["id"];
		$appt_color = $appointment_type["color"];
		$script_appt_type_color["script_code"] .= "\nif (obj_select.options[i].value==$appt_id) obj_select.options[i].style.backgroundColor='$appt_color';";

		$smarty->append("appointment_type", $appointment_type);
	}

	$script_appt_type_color["script_code"] .= "\n}\n}\n\n";
	$smarty->assign("script_appt_type_color",$script_appt_type_color);


	//Appointment location type ( in-house / outside)
	generate_sql_vars($sql_var,$res_var,$row_var,"loc_type");

	$$sql_var = "SELECT * FROM mgw_calendar_location_type";
	if(!$$res_var = $conn->Execute($$sql_var)) die(showSQLerror($$sql_var, $conn->ErrorMsg(), __LINE__, __FILE__));
	while ($$row_var = $$res_var->FetchRow()) {

		$row_tmp = array();
		$row_tmp = $$row_var;

		$appointment_location_type = array( "id" => $row_tmp["id"] ,
								  "type" => Lang::getLanguageString("gentemp_".$row_tmp["location_type"]), // type
								  "sel" => ($row_tmp["id"]==$id_appt_loc_type ? " selected" : "") // checked or not
								);
		$smarty->append("appointment_location_type", $appointment_location_type);
	}


	/// availability :
	$disp1 =				array (	"id" => 0,
									"type" => "can_not_be_disturbed",
									"text" => Lang::getLanguageString("gentemp_can_not_be_disturbed") , // type translated
									"chk" => ($availability==0 ? " checked" : "") // checked or not
						         );

	$disp2 = 		array( "id" => 1,
							"type" => "can_be_disturbed",
							"text" => Lang::getLanguageString("gentemp_can_be_disturbed") , // type translated
							"chk" => ($availability==1 ? " checked" : "") // checked or not
						  );

	$availability_list = array($disp1,$disp2);
	$smarty->assign("availability_list",$availability_list);


	$smarty->assign("gentemp_telephone",Lang::getLanguageString("gentemp_telephone"));
	$smarty->assign("temp_subject_summarized",Lang::getLanguageString("temp_subject_summarized"));
	$smarty->assign("temp_subject_detailed",Lang::getLanguageString("temp_subject_detailed"));
	$smarty->assign("temp_appt_type",Lang::getLanguageString("temp_appt_type"));
	$smarty->assign("temp_availability",Lang::getLanguageString("temp_availability"));


}//end function
////////////////////




?>
