<?
/* 
   This file is part of the 'Science Fair In A Box' project
   SFIAB Website: http://www.sfiab.ca

   Copyright (C) 2005 Sci-Tech Ontario Inc <info@scitechontario.org>
   Copyright (C) 2005 James Grant <james@lightbox.org>

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public
   License as published by the Free Software Foundation, version 2.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; see the file COPYING.  If not, write to
   the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
   Boston, MA 02111-1307, USA.
*/
?>
<?
 require("common.inc.php");
 require_once("schedule.inc.php");

if($_SESSION['schoolid'] && $_SESSION['schoolaccesscode']){
	// we're logged in, make sure the school is good
	$q=mysql_query("SELECT * FROM schools WHERE id='".$_SESSION['schoolid']."' AND accesscode='".$_SESSION['schoolaccesscode']."'");
	echo mysql_error();
	$school=mysql_fetch_object($q);
	if($school) {

 if($_GET['action']=="loadschedule") {
	 $date=$_POST['date'];
	 
	 //cant change this
	 $q=mysql_query("SELECT MIN(hour) AS minhour, MAX(hour) AS maxhour, CEIL(MAX(hour)+duration/60) AS maxfinish FROM schedule WHERE conferences_id='{$conference['id']}' AND date='{$date}'");
	 $parameters=mysql_fetch_object($q);

	 $starthour=$parameters->minhour;
	 $endhour=$parameters->maxfinish;

	 //do some sanity checks
	 if($starthour<0 || $starthour>24) $starthour=8;
	 if($endhour<$starthour)
		 $endhour=$starthour+10;
	 if($endhour<0 || $endhour>24) $endhour=15;

	 //minute increment
	 $increment=15;

	 if(!eregi("[0-9]{4}-[0-9]{2}-[0-9]{2}",$date)) {
		 echo "Invalid date";
		 exit;
	 }
	 echo "<h3>".i18n("Schedule for %1",array(format_date($date)))."</h3>";
	 $q=mysql_query("SELECT * FROM locations WHERE conferences_id='{$conference['id']}' ORDER BY name");
	 while($r=mysql_fetch_object($q)) {
		 $locations[$r->id]=$r->name;
	 }
	 if(!count($locations)) {
		 echo error(i18n("There are no locations defined."));
		 exit;
	 }

	echo "<table class=\"schedule\" id=\"schedule\">\n";
	echo "<tr>";
	echo "<th style=\"width: 50px;\">&nbsp;</th>";
	foreach($locations AS $id=>$name) {
		echo " <th>$name</th>\n";
	}
	for($h=$starthour;$h<$endhour;$h++) {
		for($m=0;$m<60;$m+=$increment) {
			echo "<tr>";
			echo " <td class=\"scheduletime\">";
			if($m==0) {
				echo format_time("$h:$m");
			}
			echo "</td>";
			foreach($locations AS $id=>$name) {
				echo "<td id=\"{$h}_{$m}_{$id}\">";
				echo "</td>";
			}
			echo "</tr>";
		}
	}
	echo "</table>\n";

	$js="var eventdivs=new Array();\n";
	
	//now make all our DIV's for the events that are scheduled in the database
	$x=0;
	//they will be moved by javascript after the fact
	$q=mysql_query("SELECT schedule.*, events.name, events.eventtype FROM schedule JOIN events ON schedule.events_id=events.id WHERE schedule.conferences_id='{$conference['id']}' AND date='{$date}'");
	echo mysql_error();
	while($r=mysql_fetch_object($q)) {
		echo "<div class=\"scheduleevent scheduleevent_{$r->eventtype}\" id=\"event_{$r->id}\" onclick=\"viewEvent($r->id)\">";
		echo "<span class=\"scheduleevent_title\">";
		echo $r->title;
		echo "</span>";
		echo "<br />";
		$starttime=strtotime($r->hour.":".$r->minute);
		$endtime=$starttime+$r->duration*60;
		echo format_time($starttime);
		echo " to ";
		echo format_time($endtime);

		if($r->eventtype=="scienceolympic") {
			echo "<br />";
			echo i18n("Capacity").": ";
			$regteams=getNumRegistrations($r->id);
			$maxteams=$r->somaxteams;
			echo i18n("%1 of %2",array($regteams,$maxteams))."<br />";

			$regq=mysql_query("SELECT so_teams.name 
				FROM schedule_registrations 
				JOIN so_teams ON so_teams_id=so_teams.id 
				WHERE schedule_registrations.conferences_id='{$conference['id']}' 
				AND so_teams.schools_id={$school->id} 
				AND schedule_registrations.schedule_id='$r->id'");
			echo mysql_error();
			while($regr=mysql_fetch_object($regq)) {
				echo "<div style=\"padding: 2px; border: 1px solid black; background-color: yellow;\">";
				echo $regr->name;
				echo "</div>";
			}
		}

		echo "</div>";
		$js.="eventdivs[$r->id]={hour:$r->hour,minute:$r->minute,location:$r->locations_id,duration:$r->duration,title:'".rawurlencode($r->title)."',eventtype:'$r->eventtype'};\n";
		$x++;
	}
	echo "<script type=\"text/javascript\">\n";
	echo $js;
	echo "</script>";
 }
 else if($_GET['action']=="loadevent") {
 }
 else if($_GET['action']=="saveevent") {
 }
 else {

 send_header("Event Registration", 
 	array('School Home' => 'schoolaccess.php'),
        "events_scheduling" );
 echo "<br />";
 ?>
 <script type="text/javascript">
 $(document).ready(function() {
	$(".date").datepicker({ dateFormat: 'yy-mm-dd' });
	changeDate();

	/* Setup the editor dialog */
	$("#event_dialog").dialog({
			bgiframe: true, autoOpen: false,
			modal: true, resizable: false,
			draggable: false,
			buttons: { 
				"<?=i18n('Close')?>": function() { 
					$(this).dialog("close"); 
					changeDate();
				}
			} 
		});
	$(window).resize(function() {
		placeEvents();
	}
	);
 });

 function changeDate() {
	 $("#schedulediv").load("schoolschedule.php?action=loadschedule",{date:$("#date").val()},function() {
		 placeEvents();
	 });
 }

 function placeEvents() {
	 $('.scheduleevent').each(function(idx,item) {
		 var eventid=item.id.substr(6);
		 var eventobj=eventdivs[eventid];

		 var tablecellid=eventobj.hour+'_'+eventobj.minute+'_'+eventobj.location;

		 if($("#"+tablecellid).length) {
			 var eheight=((eventobj.duration/15)*<?=$ROWHEIGHT?>)-<? echo $BORDERSIZE*2; ?>;
			 var ewidth=$("#"+tablecellid).width()-<? echo $BORDERSIZE; ?>;
			 var p=$("#"+tablecellid).offset();
			 $("#"+item.id).css(p);
			 $("#"+item.id).show();
			 $("#"+item.id).height(eheight);
			 $("#"+item.id).width(ewidth);
		 }
		 else {
			 $("#"+item.id).hide();
		 }
	 }
	 );
 }

 var scheduleId;
 function viewEvent(id) {
	scheduleId=id;
	var eventobj=eventdivs[id];

	if(id) {
		var eventobj=eventdivs[id];
		$("#event_dialog").dialog('option','title',unescape(eventobj.title));
		$("#event_dialog").dialog('option','width',600);
		$("#event_dialog").dialog('option','height',400);
		$("#event_dialog").dialog('open');
		$("#event_tabs").tabs('select',0);

		if(eventobj.eventtype=='scienceolympic')
			$("#event_tabs").tabs('option','disabled',[]);
		else
			$("#event_tabs").tabs('option','disabled',[1]);
		update_tab_summary();

	}

 }

 function saveEvent() {
	 var o=$("#edit_event_form").serializeArray();
	 //alert(o);
	 $("#debug").load("schoolschedule.php?action=saveevent",o,function() {
		 changeDate();
	 });
 }
 </script>

 <?
 $q=mysql_query("SELECT DISTINCT(date) AS date FROM schedule WHERE conferences_id='{$conference['id']}' ORDER BY date");
 $dates=array();
 while($r=mysql_fetch_object($q)) {
	$dates[]=$r->date;
 }
 if(count($dates)) 
	 $editdate=$dates[0];
 else
	 list($editdate,$bla)=explode(" ",$config['dates']['fairdate']);

 echo "<form method=\"post\">\n";
 echo i18n("Schedule date").": ";
 echo "<select id=\"date\" name=\"date\" onchange=\"changeDate()\">";
 foreach($dates AS $d) {
	 echo "<option value=\"$d\">".format_date($d)."</option>\n";
 }
 echo "</select>";
 echo "</form>\n";
 ?>
 <hr />
 <div id="schedulediv">
 </div>
 <div id="event_dialog">
<? include "schoolschedule_event_dialog.php"; ?>
 </div>
 <?

 send_footer();

 }
}
}
?>
