<?php

include_once($staticpath.'classes/Button.php');
require_once($staticpath.'modules/mod_portal/date_to_ru.php');

$button = new Button;
include_once($staticpath.'classes/InputButton.php');
$submitButton = new InputButton;
if(!isset($_REQUEST['CREATEPDF']) && !$_REQUEST['student_id'] && !$_REQUEST['user_id'])
	DisplayHeader(".:".ProgramTitle().":.");
	
echo GetBaseJavaFunc();
if(!$_REQUEST['setup'])
	$_REQUEST['setup'] = 'false';

unset($_SESSION['_REQUEST_vars']['resource_id']);
unset($_SESSION['_REQUEST_vars']['category_id']);
unset($_SESSION['_REQUEST_vars']['servicefunction']);
// since printing needs those vars that were just unset
$_SESSION['_REQUEST_vars']['bottom_print_resource_id'] = $_REQUEST['resource_id'];
$_SESSION['_REQUEST_vars']['bottom_print_servicemod'] = $_REQUEST['servicemod'];

if(!$_REQUEST['CREATEPDF'] && $_REQUEST['servicefunction']!='detail' && $_REQUEST['choose_room']!='true')
{
	if($_REQUEST['setup']=='false')
	{
		$header .= $button->createButton(_('Schedule Resources'),SetRequestOptions(null,array('setup','values','categories')).'&amp;setup=false');
		$header .= $button->createText(_('Setup the Resources'),SetRequestOptions(null,array('setup','values','categories')).'&amp;setup=true');

		$header .= '</TR><TR>';
		$header .= $button->createText(_('Weekly'),'modloader.php?servicemod='.$_REQUEST['servicemod'].'&date='.$_REQUEST['date'].'&resource_id='.$_REQUEST['resource_id'].'&choose_room='.$_REQUEST['choose_room'].'&course_section_id='.$_REQUEST['course_section_id'].'&choose_room='.$_REQUEST['choose_room'].'&useontop='.$_REQUEST['useontop']);
		$header .= $button->createText(_('Monthly Calendar'),'modloader.php?servicemod='.$_REQUEST['servicemod'].'&date='.$_REQUEST['date'].'&resource_id='.$_REQUEST['resource_id'].'&choose_room='.$_REQUEST['choose_room'].'&course_section_id='.$_REQUEST['course_section_id'].'&choose_room='.$_REQUEST['choose_room'].'&useontop='.$_REQUEST['useontop'].'&rTypec=M');

              	  	if($_REQUEST['resource_id'])
		   $header .= "</tr><table><table style='float:right;margin-right:5%;'><tr><TD width=10%></TD><TD><A HREF=# onclick='javascript:window.open(\"modloader.php?servicemod=$_REQUEST[servicemod]&servicefunction=detail&event_id=new&resource_id=$_REQUEST[resource_id]&date=$_REQUEST[date]&useontop=false\",\"blank\",\"width=500,height=400,scrollbars=1,resizable=1\"); return false;' style='text-decoration:none;font-weight:bold;color:#666666;' onmouseover='this.style.color=\"#000000\";' onmouseout='this.style.color=\"#666666\";'>"._('Add an Event').'</A></TD>';


	}
	else
	{
		$header .= $button->createText(_('Schedule Resources'),SetRequestOptions(null,array('setup')).'&amp;setup=false');
		$header .= $button->createButton(_('Setup the Resources'),SetRequestOptions(null,array('setup','values','categories')).'&amp;setup=true');
		if($_REQUEST['servicefunction']!='remove' || $_REQUEST['delete_ok']=='1')
		{
			echo "<FORM action=modloader.php?servicemod=$_REQUEST[servicemod]&setup=true&servicefunction=update&category_id=$_REQUEST[category_id] method=POST>";
			$save_button = $submitButton->createSButton(_('Save'));

		}
	
	}
	if(!isset($_REQUEST['CREATEPDF']) && !$_REQUEST['student_id'] && !$_REQUEST['user_id'])
	{
		echo TabsHeader($header,$save_button);
	}
}
if($_REQUEST['setup']=='true')
{	
	include($staticpath.'modules/mod_portal/ModuleSetup.php');
}

elseif($_REQUEST['servicefunction']=='detail')
{
	if($_REQUEST['month_values'] && $_REQUEST['day_values'] && $_REQUEST['year_values'])
	{
		$_REQUEST['values']['SCHOOL_DATE'] = $_REQUEST['year_values']['SCHOOL_DATE'].'-'.$_REQUEST['month_values']['SCHOOL_DATE'].'-'.$_REQUEST['day_values']['SCHOOL_DATE'];
		if(!VerifyDate($_REQUEST['values']['SCHOOL_DATE']))
			BackPromt("You did not choose a valid date.");
	}

	if($_POST['button']==_('Save') && AllowEdit())
	{	
		if($_REQUEST['values'])
		{
			if(substr($_REQUEST['resource_id'],0,1)=='T')
				$users = ",'".substr($_REQUEST['resource_id'],1)."'";
			else
				$resources = ",'".$_REQUEST['resource_id']."'";
				
			if($_REQUEST['resource2'] && substr($_REQUEST['resource2'],0,1)=='T')
				$users .= ",'".substr($_REQUEST['resource2'],1)."'";
			elseif($_REQUEST['resource2'])
				$resources .= ",'".$_REQUEST['resource2']."'";

			if($_REQUEST['resource3'] && substr($_REQUEST['resource3'],0,1)=='T')
				$users .= ",'".substr($_REQUEST['resource3'],1)."'";
			elseif($_REQUEST['resource3'])
				$resources .= ",'".$_REQUEST['resource3']."'";

			if($_REQUEST['resource4'] && substr($_REQUEST['resource4'],0,1)=='T')
				$users .= ",'".substr($_REQUEST['resource4'],1)."'";
			elseif($_REQUEST['resource4'])
				$resources .= ",'".$_REQUEST['resource4']."'";
			
			// if moving the date, then we still have to make this check.
			if($_REQUEST['values']['START_TIME'] && $_REQUEST['values']['END_TIME'])
			{
				if(Preferences('LOGIN_DATE_FORMAT') == '12')
				{
					$convertTime = substr($_REQUEST['values']['START_TIME'],-2);
					$convertTime2 = substr($_REQUEST['values']['END_TIME'],-2);
					if(strtoupper($convertTime) != "PM" && strtoupper($convertTime) != "AM")
						$_REQUEST['values']['START_TIME'] .= ' AM';
					if(strtoupper($convertTime2) != "PM" && strtoupper($convertTime2) != "AM" && strval(substr($convertTime2,0,2)) < 12)
						$_REQUEST['values']['END_TIME'] .= ' AM';
					else
						$_REQUEST['values']['END_TIME'] .= ' PM';

					$_REQUEST['values']['START_TIME'] = substr($_REQUEST['values']['START_TIME'],0,-2);
					$_REQUEST['values']['END_TIME'] = substr($_REQUEST['values']['END_TIME'],0,-2);
					if(strtoupper($convertTime) == "PM")
					{
						$_REQUEST['values']['START_TIME'] = (substr($_REQUEST['values']['START_TIME'],0,2)+12).":".substr($_REQUEST['values']['START_TIME'],3,2);
						$_REQUEST['values']['END_TIME'] = (substr($_REQUEST['values']['END_TIME'],0,2)+12).":".substr($_REQUEST['values']['END_TIME'],3,2);
	    				}					
				}
				if($_REQUEST['event_id']!='new')
					$event_id_extra = " AND re.ID!='".$_REQUEST['event_id']."'";
				if($resources)
				{
					$resources = substr($resources,1);
					$sql = "SELECT r.TITLE AS RESOURCE_TITLE,re.TITLE AS EVENT_TITLE FROM RESBASE r,RESBASE_EVENTS re,RESBASE_IN_EVENTS rje WHERE CAST(r.ID AS VARCHAR)=rje.RESOURCE_ID AND re.SCHOOL_DATE='".$_REQUEST['values']['SCHOOL_DATE']."' AND re.ID=rje.EVENT_ID AND rje.RESOURCE_ID IN (".$resources.") AND ('".$_REQUEST['values']['START_TIME']."' BETWEEN re.START_TIME AND re.END_TIME OR '".$_REQUEST['values']['END_TIME']."' BETWEEN re.START_TIME AND re.END_TIME) ".$event_id_extra;
				}
				
				if($resources && $users)
					$sql .= ' UNION ';
				
				if($users)
				{
					$users = substr($users,1);
					$sql .= "SELECT r.LAST_NAME".CCAT."', '".CCAT."r.FIRST_NAME AS RESOURCE_TITLE,re.TITLE AS EVENT_TITLE FROM USERS r,RESBASE_EVENTS re,RESBASE_IN_EVENTS rje WHERE ('T'".CCAT."CAST(r.USER_ID AS VARCHAR))=rje.RESOURCE_ID AND re.SCHOOL_DATE='".$_REQUEST['values']['SCHOOL_DATE']."' AND re.ID=rje.EVENT_ID AND r.USER_ID IN (".$users.") AND ('".$_REQUEST['values']['START_TIME']."' BETWEEN re.START_TIME AND re.END_TIME OR '".$_REQUEST['values']['END_TIME']."' BETWEEN re.START_TIME AND re.END_TIME) ".$event_id_extra;
				}
				$current_array = db_request(db_execute($sql));
			}
			elseif($_REQUEST['event_id']=='new')
				BackPrompt(_('You must choose a start time and an end time.'));
			if(count($current_array))
			{
				if(count($current_array)==1)
					BackPrompt(_('This event overlaps with ').$current_array[1]['EVENT_TITLE']._(' scheduled for ').$current_array[1]['RESOURCE_TITLE'].'.');
				else
				{
					$message = _('This event overlaps with other events.');
					BackPrompt($message);
				}
			}

			$go = 0;
			if($_REQUEST['event_id']!='new')
			{
				$sql = "UPDATE RESBASE_EVENTS SET ";

				foreach($_REQUEST['values'] as $column=>$value)
					$sql .= $column."='".str_replace("\'","''",$value)."',";

				$sql = substr($sql,0,-1) . " WHERE ID='$_REQUEST[event_id]'";
				db_execute($sql);
				
				$sql="DELETE FROM RESBASE_IN_EVENTS WHERE event_id='$_REQUEST[event_id]'";
				db_execute($sql);
	
				$go = true;
			
			}
			else
			{				
				$sql = "INSERT INTO RESBASE_EVENTS ";

				$fields = 'ID,';
				$values = db_seq_nextval('RESBASE_EVENTS_SEQ').",";
					
				$go = 0;
				foreach($_REQUEST['values'] as $column=>$value)
				{
					if($value || $value==='0')
					{
						$fields .= $column.',';
						$values .= "'".str_replace("\'","''",$value)."',";
						$go = true;
					}
				}
				$sql .= '(' . substr($fields,0,-1) . ') values(' . substr($values,0,-1) . ')';
				
				db_execute($sql);
			}
			
			if($go)
			{
				if($_REQUEST['event_id']!='new') 
					$event_id = $_REQUEST['event_id'];
				else 
					$event_id = db_seq_currval('RESBASE_EVENTS_SEQ');
				
				db_execute("INSERT INTO RESBASE_IN_EVENTS (EVENT_ID,RESOURCE_ID) values($event_id,'".$_REQUEST['resource_id']."')");
				if($_REQUEST['resource2'])
					db_execute("INSERT INTO RESBASE_IN_EVENTS (EVENT_ID,RESOURCE_ID) values($event_id,'".$_REQUEST['resource2']."')");
				if($_REQUEST['resource3'])
					db_execute("INSERT INTO RESBASE_IN_EVENTS (EVENT_ID,RESOURCE_ID) values($event_id,'".$_REQUEST['resource3']."')");
				if($_REQUEST['resource4'])
					db_execute("INSERT INTO RESBASE_IN_EVENTS (EVENT_ID,RESOURCE_ID) values($event_id,'".$_REQUEST['resource4']."')");
			}
				
		    echo '<SCRIPT language=javascript>opener.document.location = "modloader.php?servicemod='.$_REQUEST['servicemod'].'&date='.$_REQUEST['date'].'&resource_id='.$_REQUEST['resource_id'].'"; window.close();</script>';
			unset($_REQUEST['values']);
			unset($_SESSION['_REQUEST_vars']['values']);
		}
	}
	elseif($_REQUEST['button']==_('Delete'))
	{
		if(DeletePrompt(_('event')))
		{
			db_execute("DELETE FROM RESBASE_EVENTS WHERE ID='$_REQUEST[event_id]'");
			
			echo '<SCRIPT language=javascript>opener.document.location = "modloader.php?servicemod='.$_REQUEST['servicemod'].'&date='.$_REQUEST['date'].'&resource_id='.$_REQUEST['resource_id'].'"; window.close();</script>';
			unset($_REQUEST['values']);
			unset($_SESSION['_REQUEST_vars']['values']);
			unset($_REQUEST['button']);
			unset($_SESSION['_REQUEST_vars']['button']);
		}
	}
	else
	{
		if($_REQUEST['event_id'])
		{
			
			if($_REQUEST['event_id']!='new')
			{
				if(Preferences('LOGIN_DATE_FORMAT') == '12')
					$array = db_request(db_execute("SELECT TITLE,DESCRIPTION,COLOR,".db_to_char('SCHOOL_DATE','dd-MON-yy')." AS SCHOOL_DATE,".db_to_char('START_TIME','HH12:MI AM')." AS START_TIME,".db_to_char('END_TIME','HH12:MI AM')." AS END_TIME FROM RESBASE_EVENTS WHERE ID='$_REQUEST[event_id]'"));
				else
					$array = db_request(db_execute("SELECT TITLE,DESCRIPTION,COLOR,".db_to_char('SCHOOL_DATE','dd-MON-yy')." AS SCHOOL_DATE,".db_to_char('START_TIME','HH24:MI')." AS START_TIME,".db_to_char('END_TIME','HH24:MI')." AS END_TIME FROM RESBASE_EVENTS WHERE ID='$_REQUEST[event_id]'"));
				$title = $array[1]['TITLE'];				
			}
			else
			{
				$title = _('New Event');
				$array[1]['SCHOOL_DATE'] = $_REQUEST['date'];
			}
			echo "<FORM action=modloader.php?servicemod=$_REQUEST[servicemod]&servicefunction=detail&event_id=$_REQUEST[event_id]&date=$_REQUEST[date]&resource_id=$_REQUEST[resource_id]&category_id=$_REQUEST[category_id]&useontop=false METHOD=POST>";
		}

		echo '<BR>';
                echo '<script type="text/javascript" src="js/jquery.maskedinput-1.2.2.min.js" ></script>';
		PopTable('header',$title);
                echo '<script>';
                    //echo "jQuery.mask.definitions['g']='[ ]';\n";
                    echo "jQuery.mask.definitions['T']='[aApP]';\n";
                    echo "jQuery.mask.definitions['L']='[mM]';\n";
                    echo "jQuery.mask.definitions['H']=".((Preferences('LOGIN_DATE_FORMAT') == '12')?"'[01]'":"'[012]'").";\n";
                    echo "jQuery.mask.definitions['M']='[012345]';\n";
                echo '</script>';
		echo '<TABLE>';
		echo '<TR><TD><font color=gray>'._('Date').'</font></TD><TD>'.DateInput($array[1]['SCHOOL_DATE'],'values[SCHOOL_DATE]','',false).'</TD></TR>';
		echo '<TR><TD><font color=gray>'._('Start Time').'</font></TD><TD>'._TimeInput($array[1]['START_TIME'],'values[START_TIME]','',false,'values_START_TIME').'</TD></TR>';
		echo '<TR><TD><font color=gray>'._('End Time').'</font></TD><TD>'._TimeInput($array[1]['END_TIME'],'values[END_TIME]','',false,'values_END_TIME').'</TD></TR>';
		echo '<TR><TD><font color=gray>'._('Title').'</font></TD><TD>'.TextInput($array[1]['TITLE'],'values[TITLE]').'</TD></TR>';
		echo '<TR><TD><font color=gray>'._('Description').'</font></TD><TD>'.TextAreaInput($array[1]['DESCRIPTION'],'values[DESCRIPTION]').'</TD></TR>';
		echo '<TR><TD><font color=gray>'._('Label Color').'</font></TD><TD>'._ColorInput($array[1]['COLOR'],'values[COLOR]').'</TD></TR>';
		
		echo '<TR><TD width=70><font color=gray>'._('Use more resources in this event?').'</font></TD><TD>'._AnotherResourceInput($array[1]['END_TIME'],'another_resource','',false).'</TD></TR>';	
                echo '<script>';
                    echo "jQuery(\"#inputvalues_START_TIME\").mask(\"H9:M9".((Preferences('LOGIN_DATE_FORMAT') == '12')?'gTL':'')."\");\n";
                    echo "jQuery(\"#inputvalues_END_TIME\").mask(\"H9:M9".((Preferences('LOGIN_DATE_FORMAT') == '12')?'gTL':'')."\");\n";
                echo '</script>';
		if(AllowEdit())
		{
			echo '<TR><TD colspan=2 align=center><INPUT type=submit name=button value='._('Save').'>';
			if($_REQUEST['event_id']!='new')
				echo '<INPUT type=submit name=button value='._('Delete').'>';
			echo '</TD></TR>';
		}
		echo '</TABLE>';
		PopTable('footer');
		echo '</FORM>';

		unset($_REQUEST['values']);
		unset($_SESSION['_REQUEST_vars']['values']);
		unset($_REQUEST['button']);
		unset($_SESSION['_REQUEST_vars']['button']);
	}
	/*
		echo '<script language="javascript" src="js/jstime/mootools.v1.11.js"></script>';		
			echo ' <script language="javascript" src="js/jstime/nogray_time_picker.js"></script>';
			*/
			/*
			  <style>
					.table_list {border-collapse:collapse;
					border:solid #cccccc 1px;
					width:100%;}
					.table_list td {padding:5px;
					border:solid #efefef 1px;}
					.table_list tr.odd {background:#e1eff5;}
					.time_picker_div {padding:5px;
					background:#'.Preferences('ROLLOVER_HIGHLIGHT').';
					border: 1px solid #'.Preferences('HIGHLIGHT').';
					}
			  </style>';
			  */
}elseif(isset($_REQUEST['rTypec'])){
	include($staticpath."modules/mod_ssetup/SchCalendarStd.php");
}else{
    include($staticpath."modules/mod_ssetup/ResourceBase.php");
    include($staticpath."modules/mod_ssetup/includes/js_calendar.php");
}

function _TimeInput($value,$name,$title,$div,$id)
{
	$hour = 6;
	$minutes = 0;
	$am = 'AM';
	$display_hour = $hour;

	for($i=0;$i<=192;$i++)
	{
		$options[(str_pad($hour,2,'0',STR_PAD_LEFT).':'.str_pad($minutes,2,'0',STR_PAD_LEFT)).' '.$am] = $display_hour.':'.str_pad($minutes,2,'0',STR_PAD_LEFT).' '.$am;
		$minutes += 5;
		if($minutes>=60)
		{
			$hour++;
			$minutes = 0;
		}
		if($hour>12)
			$display_hour = $hour - 12;
		else
			$display_hour = $hour;
		
		if($hour==12)
			$am = 'PM';
	}
	
	return TimeInput($value,$name,'','',true,$id);
	//return SelectInput($value,$name,'',$options,'',$div);
}

function _ColorInput($value,$name)
{
	if(!$value)
		$value = Preferences('COLOR');

	$colors = array('FFCCFF','9999FF','D0D0FF','CCFFCC','FFFFCC','FFCCCC','CCCCCC');
	$return = '<TABLE><TR>';
	foreach($colors as $color)
		$return .= '<TD bgcolor=#'.$color.'><INPUT type=radio name='.$name.' value='.$color.(($value==$color)?' CHECKED':'').'></TD>';
	$return .= '</TR></TABLE>';	
	
	return $return;
}

function _makeColor($value,$column)
{	global $_SYSTEM,$THIS_array;

	$colors = array('FFCCFF','9999FF','D0D0FF','CCFFCC','FFFFCC','FFCCCC','CCCCCC');
	if($_SYSTEM['colors'][$THIS_array['COURSE_ID']])
		return $_SYSTEM['colors'][$THIS_array['COURSE_ID']];
	else
	{
		if(!isset($_SYSTEM['colors_index']) || !$colors[$_SYSTEM['colors_index']] || $_SYSTEM['colors_index']==6)
			$_SYSTEM['colors_index'] = 0;
		else
			$_SYSTEM['colors_index']++;
		$_SYSTEM['colors'][$THIS_array['COURSE_ID']] = $colors[$_SYSTEM['colors_index']];
		return $colors[$_SYSTEM['colors_index']];
	}
}

function _AnotherResourceInput($value,$name,$title,$div)
{
	$categories_array = db_request(db_execute("SELECT * FROM RESBASE_CATEGORIES WHERE SCHOOL_ID='".get_school_id()."' ORDER BY TITLE"));
	$resources_array = db_request(db_execute("SELECT * FROM RESBASE WHERE SCHOOL_ID='".get_school_id()."' ORDER BY TITLE"),array(),array('CATEGORY_ID'));

	$categories_array[] = array('ID'=>'user','TITLE'=>_('Staff'));
	$user_array = db_request(db_execute("SELECT LAST_NAME".CCAT."', '".CCAT."FIRST_NAME AS FULL_NAME,USER_ID FROM USERS WHERE SCHOOLS LIKE '%".get_school_id()."%'"));

	$my_event_id = 0;
	if ($_REQUEST['event_id'] != "new") $my_event_id = $_REQUEST['event_id'];

	$my_resource_id = 0;
	if (isset($_REQUEST['resource_id'])) $my_resource_id = $_REQUEST['resource_id'];
	
	$eventResource = array();
	$i = 0;
	
	$resources_join_array = db_request(db_execute("SELECT RESOURCE_ID FROM RESBASE_IN_EVENTS WHERE EVENT_ID = '$my_event_id' AND RESOURCE_ID != '$my_resource_id'"));
  
  	foreach($resources_join_array as $val)
		$eventResource[$i++] = $val['RESOURCE_ID'];
	
			
	foreach($user_array as $user)
	{
		$resources_array['user'][] = array('ID'=>'T'.$user['USER_ID'],'TITLE'=>$user['FULL_NAME'],'CATEGORY_ID'=>'user');
	}

	$select = '<SELECT name=resource2><OPTION value="">'._('If applicable, choose another resource').'</OPTION>';
	if(count($categories_array))	
	{
		foreach($categories_array as $category)
		{	
			$category_id = $category['ID'];
			$select .= '<OPTGROUP label="'.$category['TITLE'].'">';
			foreach($resources_array[$category_id] as $field)
			{
				// if($field['ID']==$_REQUEST['resource_id']) continue;
				$selected = isset($eventResource[0]) ? ($field['ID'] == $eventResource[0] ? ' SELECTED':'') : '';
				$select .= '<OPTION value='.$field['ID']. $selected . '>'.$field['TITLE'].'</OPTION>';
			}
			$select .= '</OPTGROUP>';
		}
	}
	$select .= '</SELECT><BR>';
	$select .= '<SELECT name=resource3><OPTION value="">'._('If applicable, choose another resource').'</OPTION>';
	if(count($categories_array))
	{
		foreach($categories_array as $category)
		{
			$category_id = $category['ID'];
			$select .= '<OPTGROUP label="'.$category['TITLE'].'">';
			foreach($resources_array[$category_id] as $field)
			{
				// if($field['ID']==$_REQUEST['resource_id']) continue;
				$selected = isset($eventResource[1]) ? ($field['ID'] == $eventResource[1] ? ' SELECTED':'') : '';
				$select .= '<OPTION value='.$field['ID']. $selected . '>'.$field['TITLE'].'</OPTION>';
			}
			$select .= '</OPTGROUP>';
		}
	}
	$select .= '</SELECT><BR>';
	$select .= '<SELECT name=resource4><OPTION value="">'._('If applicable, choose another resource').'</OPTION>';
	if(count($categories_array))
	{
		foreach($categories_array as $category)
		{
			$category_id = $category['ID'];
			$select .= '<OPTGROUP label="'.$category['TITLE'].'">';
			foreach($resources_array[$category_id] as $field)
			{
				// if($field['ID']==$_REQUEST['resource_id']) continue;
				$selected = isset($eventResource[2]) ? ($field['ID'] == $eventResource[2] ? ' SELECTED':'') : '';
				$select .= '<OPTION value='.$field['ID']. $selected . '>'.$field['TITLE'].'</OPTION>';
			}
			$select .= '</OPTGROUP>';
		}
	}
	$select .= '</SELECT>';

	return $select;
}
?>