<?php

include_once($staticpath.'classes/Button.php');
$button = new Button;
include_once($staticpath.'classes/InputButton.php');
$submitButton = new InputButton;

$_SYSTEM['set_js_onchange'] = true;

/*//uncomment this to synchronize days
$defaults_array = db_request(db_execute("SELECT STUDENT_SCHEDULE.ID, STUDENT_SCHEDULE.DAYS as SDAYS, cs.DAYS, cs.CFIELD_25, c.CFIELD_2, cs.CFIELD_3 FROM STUDENT_SCHEDULE INNER JOIN COURSE_SECTIONS cs ON (SCHEDULE.COURSE_SECTION_ID=cs.COURSE_SECTION_ID) INNER JOIN COURSES c ON (SCHEDULE.COURSE_ID=c.COURSE_ID);"));
foreach($defaults_array as $def)
{
	db_execute("UPDATE STUDENT_SCHEDULE SET DAYS = '".$def["DAYS"]."' WHERE STUDENT_SCHEDULE.ID='".$def['ID']."'");
}
//*/
//print "<pre>"; print_r($defaults_array); print "</pre>";
//print "<pre>"; print_r($_REQUEST); print "</pre>";

if($_REQUEST['servicefunction']!='XMLHttpRequest')
{
    if(isset($_REQUEST['GridOutputCount']))
    {
	$tmp_REQUEST = $_REQUEST;
	unset($tmp_REQUEST['GridOutputCount']);
	unset($tmp_REQUEST['values']);
	unset($tmp_REQUEST['address_id']);
	unset($tmp_REQUEST['person_id']);
	unset($tmp_REQUEST['student_id']);
	unset($tmp_REQUEST['discipline_ir_id']);
	// search_servicefunction can probably be unset in any case
	//if($tmp_REQUEST['search_servicefunction']=='result')
	unset($tmp_REQUEST['search_servicefunction']);
	// since we need this for the referrals screen
	unset($tmp_REQUEST['stuid']);
	// since GrdPrintStudGrades has issues with the MP tabs ... this probably applies to any program, but why chance it...
	if($_REQUEST['servicemod']=='mod_grades/GrdPrintStudGrades.php')
	    unset($tmp_REQUEST['search_servicefunction']);
//die('jjjj');
	if($_REQUEST['GridOutputCount']>1)
	{
	    $but_left =  '<A HREF='.SetRequestOptions($tmp_REQUEST).'&GridOutputCount='.((int)$_REQUEST['GridOutputCount']-1).'><IMG SRC=images/arrow_left.gif border=0></A>';
	}
	if($_SESSION['student_list'] && $_REQUEST['GridOutputCount']<count($_SESSION['student_list']))
	{
	    $but_right =  '<A HREF='.SetRequestOptions($tmp_REQUEST).'&GridOutputCount='.((int)$_REQUEST['GridOutputCount']+1).'><IMG SRC=images/arrow_right.gif border=0></A>';
	}
    }
    //check for other modules
    elseif($_REQUEST['servicefunction']!='choose_course' && $_REQUEST['servicefunction']!='insert_course')
    {
	unset($_SESSION['student_list']);
    }
    get_student_info();
}
//die('*******');
Widgets('all');
Search('student_id',$addition);
//print_r($addition);
if($_REQUEST['student_id'] || get_student_id())
    if($_REQUEST['servicefunction']!='choose_course' && $_REQUEST['servicefunction']!='insert_course') 
	DrawStudentHeader();

if(!function_exists('_makeTitle'))
{
	function _makeTitle($value,$column='')
	{	global $_SYSTEM,$THIS_array;
	
		return $value.(SystemPreferences('WEIGHTS')=='Y'?' - '.$THIS_array['COURSE_CREDIT_TITLE']:'');
	}
	
	function _makeLock($value,$column)
	{	global $THIS_array;
	
		if($value=='Y')
			$img = 'locked';
		else
			$img = 'unlocked';
	
		return '<IMG SRC=images/'.$img.'.gif '.(AllowEdit()?'onclick="if(this.src.indexOf(\'images/locked.gif\')!=-1) {this.src=\'images/unlocked.gif\'; document.getElementById(\'lock'.$THIS_array['ID'].'\').value=\'\';} else {this.src=\'images/locked.gif\'; document.getElementById(\'lock'.$THIS_array['ID'].'\').value=\'Y\';}"':'').'><INPUT type=hidden name=schedule['.$THIS_array['ID'].'][SCHEDULER_LOCK] id=lock'.$THIS_array['ID'].' value='.$value.'>';
	}
	
	function _makePeriodSelect($course_section_id,$column='')
	{	global $_SYSTEM,$THIS_array,$min_date;
	
		$sql = "SELECT cs.COURSE_SECTION_ID,cs.PARENT_ID,cs.TITLE,cs.SCHOOL_TERM_ID,COALESCE(cs.TOTAL_SEATS-cs.FILLED_SEATS,0) AS AVAILABLE_SEATS FROM COURSE_SECTIONS cs LEFT OUTER JOIN SCHOOL_PERIODS sp ON (sp.SCHOOL_PERIOD_ID=cs.SCHOOL_PERIOD_ID) WHERE cs.COURSE_ID='$THIS_array[COURSE_ID]' AND cs.COURSE_CREDIT_TITLE='$THIS_array[COURSE_CREDIT_TITLE]' ORDER BY sp.SORT_ORDER";
		$QI = db_execute($sql);
		$orders_array = db_request($QI);
		
		foreach($orders_array as $value)
		{
			if($value['COURSE_SECTION_ID']!=$value['PARENT_ID'])
			{
            
            //print_r($value['PARENT_ID']);
            
         //   die('kjkjkj');
				$parent = db_request(db_execute("SELECT SHORT_NAME FROM COURSE_SECTIONS WHERE COURSE_SECTION_ID='".$value['PARENT_ID']."'"));
				$parent = $parent[1]['SHORT_NAME'];
			}
			$periods[$value['COURSE_SECTION_ID']] = $value['TITLE'].(($value['SCHOOL_TERM_ID']!=0 && $value['COURSE_SECTION_ID']!=$course_section_id)?' ('.get_school_term($value['SCHOOL_TERM_ID']).')':'').($value['COURSE_SECTION_ID']!=$course_section_id?' ('.$value['AVAILABLE_SEATS'].' seats)':'').(($value['COURSE_SECTION_ID']!=$course_section_id && $parent)?' -> '.$parent:'');
		}
	
		/*
		if(!$min_date)
		{
			$min_date = db_request(db_execute("SELECT min(SCHOOL_DATE) AS MIN_DATE FROM SCHOOL_CALENDAR_DAYS WHERE SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."'"));
			if($min_date[1]['MIN_DATE'] && get_db_date('postgres')>=$min_date[1]['MIN_DATE'])
				return $periods[$course_section_id];
			else
				return SelectInput($course_section_id,'schedule['.$THIS_array['ID'].'][COURSE_SECTION_ID]','',$periods,false);
		}
		else
		*/
		
		if($min_date[1]['MIN_DATE'] && get_db_date('postgres')>=$min_date[1]['MIN_DATE'])
			return $periods[$course_section_id];
		else
			return SelectInput($course_section_id,'schedule['.$THIS_array['ID'].'][COURSE_SECTION_ID]','',$periods,false);
	}
	
	function _makeMPSelect($mp_id,$name='')
	{	global $_SYSTEM,$THIS_array;
	
		if(!$_SYSTEM['_makeMPSelect'])
		{
			$semesters_array = db_request(db_execute("SELECT SCHOOL_TERM_ID,TITLE,NULL AS SEMESTER_ID FROM SCHOOL_SEMESTERS WHERE SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."' ORDER BY SORT_ORDER"));
			$quarters_array = db_request(db_execute("SELECT SCHOOL_TERM_ID,TITLE,SEMESTER_ID FROM SCHOOL_QUARTERS WHERE SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."' ORDER BY SORT_ORDER"));
			
			$_SYSTEM['_makeMPSelect']['0'][1] = array('SCHOOL_TERM_ID'=>'0','TITLE'=>_('Full Year'),'SEMESTER_ID'=>'');
			foreach($semesters_array as $sem)
				$_SYSTEM['_makeMPSelect']['0'][] = $sem;
			foreach($quarters_array as $qtr)
				$_SYSTEM['_makeMPSelect']['0'][] = $qtr;
			
			$quarters_QI = db_execute("SELECT SCHOOL_TERM_ID,TITLE,SEMESTER_ID FROM SCHOOL_QUARTERS WHERE SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."' ORDER BY SORT_ORDER");
			$quarters_indexed_array = db_request($quarters_QI,array(),array('SEMESTER_ID'));
	
			foreach($semesters_array as $sem)
			{
				$_SYSTEM['_makeMPSelect'][$sem['SCHOOL_TERM_ID']][1] = $sem;
				foreach($quarters_indexed_array[$sem['SCHOOL_TERM_ID']] as $qtr)
					$_SYSTEM['_makeMPSelect'][$sem['SCHOOL_TERM_ID']][] = $qtr;
			}
			
			foreach($quarters_array as $qtr)
				$_SYSTEM['_makeMPSelect'][$qtr['SCHOOL_TERM_ID']][] = $qtr;
		}
   if(is_array($_SYSTEM['_makeMPSelect'][$mp_id]) && !empty($_SYSTEM['_makeMPSelect'][$mp_id])){
		foreach($_SYSTEM['_makeMPSelect'][$mp_id] as $value)
			$mps[$value['SCHOOL_TERM_ID']] = $value['TITLE'];
   }
		if($THIS_array['SCHOOL_TERM_ID']!=$mp_id)
			$mps[$THIS_array['SCHOOL_TERM_ID']] = '* '.$mps[$THIS_array['SCHOOL_TERM_ID']];
		
		return SelectInput($THIS_array['SCHOOL_TERM_ID'],'schedule['.$THIS_array['ID'].'][SCHOOL_TERM_ID]','',$mps,false);
	}
	
	function _makeDate($value,$column)
	{	global $THIS_array;
	
		if($column=='START_DATE')
			$allow_na = false;
		else
			$allow_na = true;

		return DateInput($value,'schedule['.$THIS_array['ID'].']['.$column.']','','force',$allow_na);
	}
	
	function _makeSearchTitle($value,$column)
	{
		return button('add').$value;
	}

	function _make_state_CheckBoxInput($value,$name)
	{
		global $THIS_array,$_SYSTEM;

		$id = $THIS_array['ID'];

		return CheckBoxInput($value,'schedule['.$id.']['.$name.']','','',$new,'<IMG SRC=images/check.gif height=14>','<IMG SRC=images/x_small.gif>','force');
	}

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

		$id = $THIS_array['ID'];

		//return $_SYSTEM['config']['select_options'][$column][$value]; //
		return SelectInput($value, 'schedule['.$id.']['.$column.']', '', $_SYSTEM['config']['select_options']['STUDENT_SCHEDULE'][$column], false, '', 'force', null, false);
	}

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

		$id = $THIS_array['ID'];

		if($_SYSTEM['config']['max_length']['STUDENT_SCHEDULE'][$column])
			$options = ' maxlength='.$_SYSTEM['config']['max_length']['STUDENT_SCHEDULE'][$column].' size='.$_SYSTEM['config']['max_length']['STUDENT_SCHEDULE'][$column];
		else
			$options = '';

		//return $value; //
		return TextInput($value, 'schedule['.$id.']['.$column.']','',$options,'force');
	}

	function _makeDays($value,$name)
	{	global $_SYSTEM,$THIS_array;

		$header = '';
		$id = $THIS_array['ID'];
//		if(AllowEdit())
//var_dump($THIS_array);
		{
			$header = '<DIV id=divdays'.$id.'><div id=innerdivdays'.$THIS_array[$_SYSTEM['Setup_id_col'][$_SYSTEM['Setup_table'][$name]]].' onclick=\'addHTML("';
			$days_str = '';
			$header .= '<TABLE><TR>';
		//	if(Preferences('LANGUAGE') == 'ru_RU')
		//	{
			    if(Preferences('CALENDAR') == 'Mon')
			    	$days = array('Mon','Tue','Wed','Thu','Fri','Sat','Sun');
			    else
			    	$days = array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');
			    $_SYSTEM['no_inner_ids']=true;
			    $empty_day = _('No days were chosen');			    
			    foreach($days as $day)
			    {
			    	if(strpos($value,$day)!==false)
			    	{
			    	    $empty_day = '';
			    	    $days_str .= _($day).' ';
                                    $val = 'Y';
                                    
                                    $header .= '<TD>'.str_replace('"','\"',CheckboxInput($val,'schedule['.$id.']['.$name.']['.$day.']',_($day),$checked,false,'','',false)).'</TD>';
				}
				elseif(strpos($THIS_array['SECTION_DAYS'],$day) !== false)
				{
                                    $val = '';
                                    if(AllowEdit() || get_user('PROFILE') == 'admin')
                                	    $header .= '<TD>'.str_replace('"','\"',CheckboxInput($val,'schedule['.$id.']['.$name.']['.$day.']',_($day),'',false,'','',false)).'</TD>';
                                }
			    }
		/*	}else{
			    if(Preferences('CALENDAR') == 'Mon')
				$days = array('Mon','Tue','Wed','Thu','Fri','Sat','Sun');
			    else
				$days = array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');
			    $_SYSTEM['no_inner_ids']=true;
			    $empty_day = _('No days were chosen');
			    foreach($days as $day)
			    {
				if(strpos($value,$day)!==false)
				{
				    $empty_day = '';
				    $days_str .= $day.' ';
				    $val = 'Y';

                                    $header .= '<TD>'.str_replace('"','\"',CheckboxInput($val,'schedule['.$id.']['.$name.']['.$day.']',$day,$checked,false,'','',false)).'</TD>';
				}else{
				    $val = '';
				    if(AllowEdit() || get_user('PROFILE') == 'admin')
                                	    $header .= '<TD>'.str_replace('"','\"',CheckboxInput($val,'schedule['.$id.']['.$name.']['.$day.']',$day,'',false,'','',false)).'</TD>';
				}
			    }
			}
			*/
			$_SYSTEM['no_inner_ids']=false;
			$header .= '</TR></TABLE>';
			if(!$value)
				$show_value = '-';
			else
				$show_value = $value;
			$header .= '","divdays'.$id.'",true);\'><span class="clickable">'.$days_str.$empty_day.'</span></div></DIV>';
		}
//		else
//			$header = $value;

		return $header;
	}
	
	function _makeCourseNum($value,$column)
	{	global $_SYSTEM,$THIS_array;
	
		if(SystemPreferences('WEIGHTS')=='Y')
			return $value.'-'.$THIS_array['COURSE_CREDIT_TITLE'];
		else
			return $value;
	}
	
	function _makeChildren($value,$column)
	{	global $THIS_array,$_SYSTEM;
	
		$children_array = db_request(db_execute("SELECT cs.SCHOOL_PERIOD_ID,cs.SCHOOL_TERM_ID FROM COURSE_SECTIONS cs,SCHOOL_PERIODS sp WHERE cs.SCHOOL_PERIOD_ID=sp.SCHOOL_PERIOD_ID AND cs.PARENT_ID='".$THIS_array['COURSE_SECTION_ID']."' ORDER BY cs.SCHOOL_TERM_ID,sp.SORT_ORDER"),null,array('SCHOOL_TERM_ID'));
		
		foreach($children_array[$THIS_array['SCHOOL_TERM_ID']] as $child)
		{
			$periods_list .= ', '.get_period($child['SCHOOL_PERIOD_ID'],null,'SHORT_NAME');
		}
		$periods_list = substr($periods_list,2);
		unset($children_array[$THIS_array['SCHOOL_TERM_ID']]);
		if(count($children_array))
		{
			foreach($children_array as $mp=>$children)
			{
				$periods_list .= ' &mdash; <B>'.get_school_term($mp,'SHORT_NAME').': </B>';
				foreach($children as $child)
					$periods_list .= get_period($child['SCHOOL_PERIOD_ID'],null,'SHORT_NAME').', ';
				$periods_list = substr($periods_list,0,-2);
			}
		}
		return $periods_list;
	}
}


// GET THE FIRST DAY OF SCHOOL. THIS IS USED IN SEVERAL PLACES
if(!$min_date || !$_SYSTEM['PrintSchedules'])
	$min_date = db_request(db_execute("SELECT min(SCHOOL_DATE) AS MIN_DATE FROM SCHOOL_CALENDAR_DAYS WHERE SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."'"));

if($_REQUEST['month_date'] && $_REQUEST['day_date'] && $_REQUEST['year_date'])
{
	while(!VerifyDate($date = $_REQUEST['year_date'].'-'.$_REQUEST['month_date'].'-'.$_REQUEST['day_date']))
		$_REQUEST['day_date']--;
}
else
{
	if($min_date[1]['MIN_DATE'] && get_db_date('postgres')<$min_date[1]['MIN_DATE'])
		$date = $min_date[1]['MIN_DATE'];
	else
		$date = get_db_date();
}

if(!$days_array || !$_SYSTEM['PrintSchedules'])
	$days_array = db_request(db_execute("SELECT DISTINCT DAYS FROM COURSE_SECTIONS WHERE SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."'"));


if($_REQUEST['month_schedule'] && $_POST['month_schedule'])
{
	foreach($_REQUEST['month_schedule'] as $id=>$columns)
	{
		foreach($columns as $column=>$value)
		{
			$_REQUEST['schedule'][$id][$column] = $_REQUEST['year_schedule'][$id][$column].'-'.$value.'-'.$_REQUEST['day_schedule'][$id][$column];
			if($_REQUEST['schedule'][$id][$column]=='--')
				$_REQUEST['schedule'][$id][$column] = '';
			if(!VerifyDate($_REQUEST['schedule'][$id][$column]))
				unset($_REQUEST['schedule'][$id][$column]);
		}
	}
	unset($_REQUEST['month_schedule']);
	unset($_REQUEST['day_schedule']);
	unset($_REQUEST['year_schedule']);
	unset($_SESSION['_REQUEST_vars']['month_schedule']);
	unset($_SESSION['_REQUEST_vars']['day_schedule']);
	unset($_SESSION['_REQUEST_vars']['year_schedule']);
	$_POST['schedule'] = $_REQUEST['schedule'];
}

if($_REQUEST['schedule'] && $_POST['schedule'])
{
	foreach($_REQUEST['schedule'] as $id=>$columns)
	{
		$current_array = db_request(db_execute("SELECT COURSE_SECTION_ID FROM STUDENT_SCHEDULE WHERE ID='".$id."'"));
		$course_section_id = $current_array[1]['COURSE_SECTION_ID'];
		if($columns['COURSE_SECTION_ID'])
		{
			if($columns['COURSE_SECTION_ID']!=$course_section_id)
			{
				db_execute("UPDATE COURSE_SECTIONS SET FILLED_SEATS=FILLED_SEATS+1 WHERE COURSE_SECTION_ID='".$columns['COURSE_SECTION_ID']."'");
				db_execute("UPDATE COURSE_SECTIONS SET FILLED_SEATS=FILLED_SEATS-1 WHERE COURSE_SECTION_ID='".$course_section_id."'");
			}			
		}
		if($columns['SCHOOL_TERM_ID'])
			$columns['MP'] = get_school_termTable(get_school_term($columns['SCHOOL_TERM_ID'],'MP_TABLE'));
		if($columns['DAYS'])
		{
			$this_days = '';
			foreach($columns['DAYS'] as $day=>$y)
			{
				if($y=='Y')
					$this_days .= $day;
			}
			$_REQUEST['schedule'][$id]['DAYS'] = $this_days;
			$columns['DAYS'] = $this_days;
		}
		$sql = "UPDATE STUDENT_SCHEDULE SET ";
		
		if(count($columns))
		{
			foreach($columns as $column=>$value)
			{
				$sql .= $column."='".str_replace("\'","''",$value)."',";
			}
			$sql = substr($sql,0,-1) . " WHERE STUDENT_ID='".get_student_id()."' AND ID='".$id."'";
			db_execute($sql);

			if($columns['START_DATE'] || $columns['END_DATE'])
			{
				$start_end_array = db_request(db_execute("SELECT ID,START_DATE,END_DATE FROM STUDENT_SCHEDULE WHERE STUDENT_ID='".get_student_id()."' AND ID='".$id."' AND END_DATE<START_DATE"));
				if(count($start_end_array))
				{
					db_execute("DELETE FROM STUDENT_SCHEDULE WHERE STUDENT_ID='".get_student_id()."' AND ID='".$id."' AND END_DATE IS NOT NULL AND END_DATE<START_DATE");
					db_execute("UPDATE COURSE_SECTIONS SET FILLED_SEATS=FILLED_SEATS-1 WHERE COURSE_SECTION_ID='".$course_section_id."'");
				}
			}
			// User should be asked if he wants absences to be deleted
			// ALSO, ATTENDANCE SHOULD NOT BE DELETED IF ANOTHER SECTION OF THIS EXISTS IN THE STUDENT_SCHEDULE.
			if($columns['END_DATE'])
				db_execute("DELETE FROM STUDENT_ATTENDANCE_PERIODS WHERE STUDENT_ID='".get_student_id()."' AND COURSE_SECTION_ID='".$course_section_id."' AND SCHOOL_DATE > '".$columns['END_DATE']."'");
		}
	}
	unset($_SESSION['_REQUEST_vars']['schedule']);
	unset($_REQUEST['schedule']);
}
if($_REQUEST['servicefunction']=='student_drop')
{
	$cp_array = db_request(db_execute("SELECT cs.COURSE_SECTION_ID,cs.MP,cs.SCHOOL_TERM_ID,c.TITLE,c.COURSE_ID,cs.COURSE_CREDIT_TITLE,cs.DAYS,cs.SCHOOL_PERIOD_ID,cs.TEACHER_ID,cs.SCHOOL_TERM_ID,COALESCE(cs.TOTAL_SEATS,0) AS TOTAL_SEATS,COALESCE(cs.FILLED_SEATS,0) AS FILLED_SEATS FROM COURSE_SECTIONS cs, COURSES c WHERE cs.COURSE_ID=c.COURSE_ID AND (cs.COURSE_SECTION_ID='".$_REQUEST['course_section_id']."' OR cs.PARENT_ID='".$_REQUEST['course_section_id']."')"));
	$message = '<TABLE>
	<TR><TD align='.ALIGN_RIGHT.'><font color=gray>'._('Course Name').':</font></TD><TD>'.$cp_array[1]['TITLE'].(SystemPreferences('WEIGHTS')=='Y'?' - '.$cp_array[1]['COURSE_CREDIT_TITLE']:'').'</TD></TR>';
	if(count($cp_array)>1)
	{
		$message .= '<TR><TD align='.ALIGN_RIGHT.' valign=top><font color=gray>'._('Meeting Times').':</font></TD><TD>';
		foreach($cp_array as $cp)
		{
			if(count($days_array)>1)
				$days = $cp['DAYS'];
			else
				$days = '';
			$message .= get_period($cp['SCHOOL_PERIOD_ID']).' '.$days.'<BR>';
		}
		$message .= '</TD></TR>';
	}
	else
	{
		if(count($days_array)>1)
			$days = $cp_array[1]['DAYS'];
		else
			$days = '';
		$message .= '<TR><TD align='.ALIGN_RIGHT.'><font color=gray>'._('Meeting Time').':</font></TD><TD>'.get_period($cp_array[1]['SCHOOL_PERIOD_ID']).' '.$days.'</TD></TR>';
	}
	$message .= '<TR><TD align='.ALIGN_RIGHT.'><font color=gray>'._('Instructor').':</font></TD><TD>'.GetTeacher($cp_array[1]['TEACHER_ID']).'</TD></TR>';
	if($cp_array[1]['ROOM'])
		$message .= '<TR><TD align='.ALIGN_RIGHT.'><font color=gray>'._('Room').'</font></TD><TD>'.$cp_array[1]['ROOM'].'</TD></TR>';
	$message .= '</TABLE>';
	if(Prompt(_('Drop Confirmation'),_('Do you want to drop this course?'),$message))
	{
		foreach($cp_array as $cp)
		{
			db_execute("DELETE FROM STUDENT_SCHEDULE WHERE COURSE_SECTION_ID='".$cp['COURSE_SECTION_ID']."' AND STUDENT_ID='".get_student_id()."'");
			db_execute("UPDATE COURSE_SECTIONS SET FILLED_SEATS=FILLED_SEATS-1 WHERE COURSE_SECTION_ID='".$cp['COURSE_SECTION_ID']."'");
		}
		unset($_REQUEST['servicefunction']);
	}
}

if($_REQUEST['servicefunction']=='student_add')
{
	//$min_date = db_request(db_execute("SELECT min(SCHOOL_DATE) AS MIN_DATE FROM SCHOOL_CALENDAR_DAYS WHERE SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."'"));
	if($min_date[1]['MIN_DATE'] && get_db_date('postgres')<$min_date[1]['MIN_DATE'])
		$date = $min_date[1]['MIN_DATE'];
	else
		$date = get_db_date();
	
	$cp_array = db_request(db_execute("SELECT cs.COURSE_SECTION_ID,c.PREREQUISITES,cs.MP,cs.SCHOOL_TERM_ID,c.TITLE,c.COURSE_ID,cs.COURSE_CREDIT_TITLE,cs.DAYS,cs.WEEK,cs.SCHOOL_PERIOD_ID,cs.TEACHER_ID,cs.SCHOOL_TERM_ID,cs.TOTAL_SEATS,COALESCE(cs.FILLED_SEATS,0) AS FILLED_SEATS FROM COURSE_SECTIONS cs, COURSES c WHERE cs.COURSE_ID=c.COURSE_ID AND (cs.COURSE_SECTION_ID='".$_REQUEST['course_section_id']."' OR cs.PARENT_ID='".$_REQUEST['course_section_id']."')"));
	if(is_numeric($cp_array[1]['TOTAL_SEATS']) && $cp_array[1]['TOTAL_SEATS']<=$cp_array[1]['FILLED_SEATS'])
		$warnings[] = _('That section is already full.');
	
	$current_array = db_request(db_execute("SELECT COURSE_SECTION_ID FROM STUDENT_SCHEDULE WHERE STUDENT_ID='".get_student_id()."' AND COURSE_ID='".$cp_array[1]['COURSE_ID']."' AND COURSE_CREDIT_TITLE='".$cp_array[1]['COURSE_CREDIT_TITLE']."' AND (START_DATE<='".get_db_date()."' AND (END_DATE IS NULL OR '".get_db_date()."'<=END_DATE))"));
	if(count($current_array) && !$_Scheduling['dont_warn_conflict_course'])
		$warnings[] = _('You are already scheduled into this course.');

	$days_conflict = false;
	$school_periods_array = db_request(db_execute("SELECT LENGTH FROM SCHOOL_PERIODS WHERE SCHOOL_PERIOD_ID='".$cp_array[1]['SCHOOL_PERIOD_ID']."'"));
	if($school_periods_array[1]['LENGTH']>0)
	{
		$period_array = db_request(db_execute("SELECT cs.DAYS,cs.WEEK FROM STUDENT_SCHEDULE s,COURSE_SECTIONS cs WHERE cs.COURSE_SECTION_ID=s.COURSE_SECTION_ID AND s.STUDENT_ID='".get_student_id()."' AND cs.SCHOOL_PERIOD_ID='".$cp_array[1]['SCHOOL_PERIOD_ID']."' AND s.SCHOOL_TERM_ID IN (".get_all_school_term(get_school_termTable(get_school_term($cp_array[1]['SCHOOL_TERM_ID'],'MP_TABLE')),$cp_array[1]['SCHOOL_TERM_ID']).") AND ('".get_db_date('postgres')."' BETWEEN s.START_DATE AND s.END_DATE OR s.END_DATE IS NULL)"));
//		var_dump($period_array);
		foreach($cp_array as $new)
		{
			foreach($period_array as $existing)
			{
				if(strlen($new['DAYS'])+strlen($existing['DAYS'])>21)
					$days_conflict = true;
				else
				{
					$days_len = strlen($new['DAYS']);
//					for($i=0;$i<$days_len;$i++)
					for($i=0;$i<$days_len;$i+=3)
					{
						if(SystemPreferences('ODD_EVEN_WEEKS','system') == 'Y')
						{
//						echo "QQQQQQQQQ:".$existing['DAYS'].' '.$existing['WEEK']."<BR>";
//						echo $new['DAYS'].' '.$new['WEEK'];
							if(strpos($existing['DAYS'],substr($new['DAYS'],$i,3))!==false)// && $existing['WEEK'] == $new['WEEK'] && $new['WEEK'] != 'A')
							{
//							echo "day!!!";
								if($existing['WEEK'] == $new[1]['WEEK'] && $new[1]['WEEK'] != 'A')
								{
									$days_conflict = true;
									break 2;
								}
								elseif($existing['WEEK'] != $new[1]['WEEK'] && $new[1]['WEEK'] == 'A')
								{
									$days_conflict = true;
									break 2;
								}
								elseif($existing['WEEK'] != $new[1]['WEEK'] && $existing['WEEK'] == 'A')
								{
									$days_conflict = true;
									break 2;
								}
							}
/*
							if(strpos($existing['DAYS'],substr($new['DAYS'],$i,3))!==false && $existing['WEEK'] == $new['WEEK'])
							{
								$days_conflict = true;
								break;
							}
*/							
						}
						else
							if(strpos($existing['DAYS'],substr($new['DAYS'],$i,3))!==false)
							{
								$days_conflict = true;
								break;
							}
					}
				}			
			}
		}
		if($days_conflict)
//			$warnings[] = _('There is already a course scheduled in that period.');
			$warnings[] = _('A course is already scheduled for this school period.');
	}

	$cp_array[1]['PREREQUISITES'] = str_replace("\n","\r",str_replace("\r\n","\r",$cp_array[1]['PREREQUISITES']));
	if($cp_array[1]['PREREQUISITES'])
		$cp_array[1]['PREREQUISITES'] = explode("\r",$cp_array[1]['PREREQUISITES']);
	else
		$cp_array[1]['PREREQUISITES'] = array();
	if(count($cp_array[1]['PREREQUISITES']))
	{
		$nums = '';
		foreach($cp_array[1]['PREREQUISITES'] as $course_num)
		{
			$nums .= ",'".$course_num."'";
		}
		$nums = substr($nums,1);
		$grades_array = db_request(db_execute("SELECT CARRIES_CREDITS,COURSE_NUM FROM STUDENT_GRADES_CARD WHERE STUDENT_ID='".get_student_id()."' AND COURSE_NUM IN (".$nums.")"),array(),array('COURSE_NUM'));
		// make sure all pre-reqs have been taken
		if(count($grades_array)<count($cp_array[1]['PREREQUISITES']))
			$warnings[] = _('Not all of necessary courses have been taken for adding course section.');
		// make sure all the pre-reqs have been passed
		foreach($grades_array as $course_num=>$grades)
		{
			foreach($grades as $grade)
			{
				if($grade['CARRIES_CREDITS']!='Y')
				{
					$warnings[] = _('At least one of the necassary courses has not been passing graded.');
					break 2;
				}
			}
		}
		// note, this was copied from choose_course, below
	}

	if(!$warnings)
	{
		$message = '<TABLE>
		<TR><TD align='.ALIGN_RIGHT.'><font color=gray>'._('Course Name').':</font></TD><TD>'.$cp_array[1]['TITLE'].(SystemPreferences('WEIGHTS')=='Y'?' - '.$cp_array[1]['COURSE_CREDIT_TITLE']:'').'</TD></TR>';
		if(count($cp_array)>1)
		{
			$message .= '<TR><TD align='.ALIGN_RIGHT.' valign=top><font color=gray>'._('Meeting Times').':</font></TD><TD>';
			foreach($cp_array as $cp)
			{
				if(count($days_array)>1)
					$days = $cp['DAYS'];
				else
					$days = '';
				$message .= get_period($cp['SCHOOL_PERIOD_ID']).' '.$days.'<BR>';
			}
			$message .= '</TD></TR>';
		}
		else
		{
			if(count($days_array)>1)
				$days = $cp_array[1]['DAYS'];
			else
				$days = '';
			$message .= '<TR><TD align='.ALIGN_RIGHT.'><font color=gray>'._('Meeting Time').':</font></TD><TD>'.get_period($cp_array[1]['SCHOOL_PERIOD_ID']).' '.$days.'</TD></TR>';
		}
		$message .= '<TR><TD align='.ALIGN_RIGHT.'><font color=gray>'._('Instructor').':</font></TD><TD>'.GetTeacher($cp_array[1]['TEACHER_ID']).'</TD></TR>';
		if($cp_array[1]['ROOM'])
			$message .= '<TR><TD align='.ALIGN_RIGHT.'><font color=gray>'._('Class-room').'</font></TD><TD>'.$cp_array[1]['ROOM'].'</TD></TR>';
		$message .= '</TABLE>';
	
		if(Prompt(_('Confirm to Add'),_('Do you want to add this course to your personal timetable?'),$message))
		{
			foreach($cp_array as $new)
			{
				$enroll_student = get_student_id();
			    $enrolStudent_query = db_request(db_execute("Select * from students Where STUDENT_ID='".$enroll_student."'"));
			    $enroll_student_Data = pg_fetch_all(pg_query($iomadDBconn, "Select * from mdl_user where username='".$enrolStudent_query[1]['USERNAME']."'"));
			    $form2_data =   db_request(db_execute("select * from form2 where id='9'"));

			    $form2_data =   db_request(db_execute("select * from form2 where id='9'"));
			    $enrollment_Iomad = array();
			    $enrollment_Iomad['domain'] = $form2_data[1]['URL'] ;
			    $enrollment_Iomad['token'] = $form2_data[1]['TOKEN'] ;   
			    $enrollment_Iomad['function'] = "enrol_manual_enrol_users"; 
			    $enrollment_Iomad['user_id'] = $enroll_student_Data[0]['id']; 
			    $enrollment_Iomad['role_id'] = 5; 
			    $course_id = $_REQUEST['course_id'];
			   //dheeraj
			    $checkIomadCourse_Query = pg_query($iomadDBconn, "SELECT * FROM mdl_course WHERE idnumber='".$course_id."'");
				$checkIomadCourse_Data = pg_fetch_all($checkIomadCourse_Query)[0];
			            
			    $data = db_request(db_execute("SELECT * FROM COURSE_CREDITS  WHERE course_id ='".$course_id."'"));
				   if($data['STUDENT_SCHEDULEABLE']=='Y') {
				    $enrollment_Iomad['course_id'] = $checkIomadCourse_Data['id'];
				    include($staticpath.'iomadAPI/enroll.php');
				   } 
			    
			     
				db_execute("INSERT INTO STUDENT_SCHEDULE (ID,SCHOOL_YEAR,SCHOOL_ID,STUDENT_ID,START_DATE,COURSE_ID,COURSE_CREDIT_TITLE,COURSE_SECTION_ID,MP,SCHOOL_TERM_ID) values(".db_seq_nextval('STUDENT_SCHEDULE_SEQ').",'".get_school_year()."','".get_school_id()."','".get_student_id()."','".$date."','".$_REQUEST['course_id']."','".$_REQUEST['course_credits']."','".$new['COURSE_SECTION_ID']."','".$new['MP']."','".$new['SCHOOL_TERM_ID']."')");
				db_execute("UPDATE COURSE_SECTIONS SET FILLED_SEATS=FILLED_SEATS+1 WHERE COURSE_SECTION_ID='".$new['COURSE_SECTION_ID']."'");
				$defaults_array = db_request(db_execute("SELECT cs.DAYS, cs.CFIELD_25, c.CFIELD_2, cs.CFIELD_3 FROM STUDENT_SCHEDULE INNER JOIN COURSE_SECTIONS cs ON (STUDENT_SCHEDULE.COURSE_SECTION_ID=cs.COURSE_SECTION_ID) INNER JOIN COURSES c ON (STUDENT_SCHEDULE.COURSE_ID=c.COURSE_ID) WHERE STUDENT_SCHEDULE.ID='".db_seq_currval('STUDENT_SCHEDULE_SEQ')."'"));
				if(count($defaults_array))
				{
					db_execute("UPDATE STUDENT_SCHEDULE SET DAYS = '".$defaults_array[1]["DAYS"]."', CFIELD_25='".$defaults_array[1]["CFIELD_25"]."',CFIELD_5='".$defaults_array[1]["CFIELD_2"]."',CFIELD_10='".$defaults_array[1]["CFIELD_3"]."' WHERE STUDENT_SCHEDULE.ID='".db_seq_currval('STUDENT_SCHEDULE_SEQ')."'");
				}
			}
			echo "<script language=javascript>document.location.href = 'modloader.php?servicemod=".$_REQUEST['servicemod']."&GridOutputCount=".$_REQUEST['GridOutputCount']."';</script>";
		}
	}
	else
	{
		$list = '<BR>'.ErrorMessage($warnings,'error');
		$list .= '<A onclick="javascript:history.go(-1);"><IMG SRC=images/back.gif height=15></A><A onclick="javascript:history.go(-1);"><font color=blue>'._('Back').'</font></A>';
		echo $list;
	}
}
// insert course is used by the search below the schedule since choose_course 
// does not useontop, etc.
if($_REQUEST['servicefunction']=='choose_course' || $_REQUEST['servicefunction']=='insert_course') 
{
	if($_REQUEST['course_id'])
	{
		$weights_array = db_request(db_execute("SELECT COURSE_CREDIT_TITLE FROM COURSE_CREDITS WHERE COURSE_ID='$_REQUEST[course_id]'"));
		if(count($weights_array)==1)
			$_REQUEST['course_credits'] = $weights_array[1]['COURSE_CREDIT_TITLE'];
	}
	if(!$_REQUEST['course_section_id'])
	{
		include $staticpath."modules/mod_curriculum/ScdCourseProperties.php";
	}
	else
	{
		//$min_date = db_request(db_execute("SELECT min(SCHOOL_DATE) AS MIN_DATE FROM SCHOOL_CALENDAR_DAYS WHERE SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."'"));
		if($min_date[1]['MIN_DATE'] && get_db_date('postgres')<$min_date[1]['MIN_DATE'])
			$date = $min_date[1]['MIN_DATE'];
		else
			$date = get_db_date();
		
		$cp_array = db_request(db_execute("SELECT c.PREREQUISITES,cs.MP,cs.SCHOOL_TERM_ID,cs.DAYS,cs.WEEK,cs.SCHOOL_PERIOD_ID,cs.SCHOOL_TERM_ID,
				    cs.TOTAL_SEATS,COALESCE(cs.FILLED_SEATS,0) AS FILLED_SEATS FROM COURSE_SECTIONS cs,COURSES c WHERE c.COURSE_ID=cs.COURSE_ID 
				    AND cs.COURSE_SECTION_ID='".$_REQUEST['course_section_id']."'"));
		if(is_numeric($cp_array[1]['TOTAL_SEATS']) && $cp_array[1]['TOTAL_SEATS']<=$cp_array[1]['FILLED_SEATS'])
		{
			$warnings[] = _('That course section is already full.');
			if(!(AllowEdit('mod_curriculum/ScdCourseProperties.php') || AllowEdit('mod_curriculum/ScdMSReport.php')))
				$errors[] = _('That course section is already full.');
		}

		$current_array = db_request(db_execute("SELECT COURSE_SECTION_ID,".db_to_char('START_DATE','YYYY-MM-DD')." AS START_DATE FROM STUDENT_SCHEDULE WHERE STUDENT_ID='".get_student_id()."' AND COURSE_ID='".$_REQUEST['course_id']."' AND COURSE_CREDIT_TITLE='".$_REQUEST['course_credits']."' AND COURSE_SECTION_ID='".$_REQUEST['course_section_id']."' AND (START_DATE<='".get_db_date()."' AND (END_DATE IS NULL OR '".get_db_date()."'<=END_DATE))"));
		if(count($current_array) && !$_Scheduling['dont_warn_conflict_course'])
		{
//			$warnings[] = _('This student is already scheduled for this course.');
			$errors[] = _('This student is already scheduled for this course.');
//			$attention = true;
		}
		$current_array = db_request(db_execute("SELECT COURSE_SECTION_ID,".db_to_char('START_DATE','YYYY-MM-DD')." AS START_DATE FROM STUDENT_SCHEDULE WHERE STUDENT_ID='".get_student_id()."' AND COURSE_ID='".$_REQUEST['course_id']."' AND COURSE_CREDIT_TITLE='".$_REQUEST['course_credits']."' AND COURSE_SECTION_ID='".$_REQUEST['course_section_id']."' AND (START_DATE<='".get_db_date()."' AND (END_DATE IS NULL OR '".get_db_date()."'<=END_DATE))"));
		// eliminate a problem where double-clicking a section results in an error
		$attention = false;
		if(count($current_array))// || $current_array[1]['START_DATE']!=get_db_date('postgres'))
		{
			$days_conflict = false;
			$period_array = db_request(db_execute("SELECT cs.DAYS,cs.WEEK FROM STUDENT_SCHEDULE s,COURSE_SECTIONS cs WHERE cs.COURSE_SECTION_ID=s.COURSE_SECTION_ID AND s.STUDENT_ID='".get_student_id()."' AND cs.SCHOOL_PERIOD_ID='".$cp_array[1]['SCHOOL_PERIOD_ID']."' AND s.SCHOOL_TERM_ID IN (".get_all_school_term(get_school_termTable(get_school_term($cp_array[1]['SCHOOL_TERM_ID'],'MP_TABLE')),$cp_array[1]['SCHOOL_TERM_ID']).") AND (s.START_DATE<='".get_db_date()."' AND (s.END_DATE IS NULL OR '".get_db_date()."'<=s.END_DATE))"));
//			var_dump($period_array);
			foreach($period_array as $existing)
			{
				if(strlen($cp_array[1]['DAYS'])+strlen($existing['DAYS'])>21)
				{
					$days_conflict = true;
					break;
				}
				else
				{
					$days_len = strlen($cp_array[1]['DAYS']);
//					echo "dl:$days_len";
					for($i=0;$i<$days_len;$i+=3)
					{
//					echo "i:$i";
//					echo strpos($existing['DAYS'],substr($cp_array[1]['DAYS'],$i,3));
//					echo substr($cp_array[1]['DAYS'],$i,3);
//echo $existing['DAYS'];
						if(SystemPreferences('ODD_EVEN_WEEKS','system') == 'Y')
						{
//						echo "WWWWWWWWWWW: ".$existing['DAYS'].' '.$existing['WEEK']."<BR>";
//						echo $cp_array[1]['DAYS'].' '.$new['WEEK'];
/*
							if(strpos($existing['DAYS'],substr($new['DAYS'],$i,3))!==false && $existing['WEEK'] == $new['WEEK'])
							{
								$days_conflict = true;
								$attention = true;
								break 2;
							}
*/
							if(strpos($existing['DAYS'],substr($cp_array[1]['DAYS'],$i,3))!==false)// && $existing['WEEK'] == $new['WEEK'] && $new['WEEK'] != 'A')
							{
								if($existing['WEEK'] == $cp_array[1]['WEEK'] && $cp_array[1]['WEEK'] != 'A')
								{
									$days_conflict = true;
									break 2;
								}
								elseif($existing['WEEK'] != $cp_array[1]['WEEK'] && $cp_array[1]['WEEK'] == 'A')
								{
									$days_conflict = true;
									break 2;
								}
								elseif($existing['WEEK'] != $cp_array[1]['WEEK'] && $existing['WEEK'] == 'A')
								{
									$days_conflict = true;
									break 2;
								}
							}
						}
						else						
							if(strpos($existing['DAYS'],substr($cp_array[1]['DAYS'],$i,3))!==false)
							{
								$days_conflict = true;
								$attention = true;
								break 2;
							}
					}
				}			
			}
		}
		if(!count($current_array) || $current_array[1]['START_DATE']!=get_db_date('postgres') || $attention)
//		if(!count($current_array) || $attention)
		{
		
//		echo "jkhgkjhk-".$cp_array[1]['SCHOOL_PERIOD_ID'];
			$days_conflict = false;
			$period_array = db_request(db_execute("SELECT cs.DAYS,cs.WEEK FROM STUDENT_SCHEDULE s,COURSE_SECTIONS cs WHERE cs.COURSE_SECTION_ID=s.COURSE_SECTION_ID 
					    AND s.STUDENT_ID='".get_student_id()."' AND cs.SCHOOL_PERIOD_ID='".$cp_array[1]['SCHOOL_PERIOD_ID']."' AND s.SCHOOL_TERM_ID 
					    IN (".get_all_school_term(get_school_termTable(get_school_term($cp_array[1]['SCHOOL_TERM_ID'],'MP_TABLE')),$cp_array[1]['SCHOOL_TERM_ID']).") 
					    AND (s.START_DATE<='".get_db_date()."' AND (s.END_DATE IS NULL OR '".get_db_date()."'<=s.END_DATE))"));
//			var_dump($period_array);
			foreach($period_array as $existing)
			{
				if(strlen($cp_array[1]['DAYS'])+strlen($existing['DAYS'])>21)
				{
					$days_conflict = true;
					break;
				}
				else
				{
					$days_len = strlen($cp_array[1]['DAYS']);
//					echo "dl:$days_len";
					for($i=0;$i<$days_len;$i+=3)
					{
//					echo "i:$i";
//					echo strpos($existing['DAYS'],substr($cp_array[1]['DAYS'],$i,3));
//					echo substr($cp_array[1]['DAYS'],$i,3);
//echo $existing['DAYS'];
						if(SystemPreferences('ODD_EVEN_WEEKS','system') == 'Y')
						{
//						echo "ZZZZZZZZZZZZ:".$existing['DAYS'].' '.$existing['WEEK']."<BR>";
//						echo "new: ".$cp_array[1]['DAYS'].'-'.$cp_array[1]['WEEK'].'=='.$i.'>'.substr($cp_array[1]['DAYS'],$i,3)."|";
							if(strpos($existing['DAYS'],substr($cp_array[1]['DAYS'],$i,3))!==false)// && $existing['WEEK'] == $new['WEEK'] && $new['WEEK'] != 'A')
							{
//							echo "day!!!";
								if($existing['WEEK'] == $cp_array[1]['WEEK'] && $cp_array[1]['WEEK'] != 'A')
								{
									$days_conflict = true;
									break 2;
								}
								elseif($existing['WEEK'] != $cp_array[1]['WEEK'] && $cp_array[1]['WEEK'] == 'A')
								{
									$days_conflict = true;
									break 2;
								}
								elseif($existing['WEEK'] != $cp_array[1]['WEEK'] && $existing['WEEK'] == 'A')
								{
									$days_conflict = true;
									break 2;
								}
							}
						}
						else
							if(strpos($existing['DAYS'],substr($cp_array[1]['DAYS'],$i,3))!==false)
							{
								$days_conflict = true;
								break 2;
							}
					}
				}
			}
//			var_dump($days_conflict);
			if($days_conflict)
//				$warnings[] = _('There is already a course scheduled in that period.');
				$warnings[] = _('A course is already scheduled for this school period.');
			
			$cp_array[1]['PREREQUISITES'] = str_replace("\n","\r",str_replace("\r\n","\r",$cp_array[1]['PREREQUISITES']));
			if($cp_array[1]['PREREQUISITES'])
				$cp_array[1]['PREREQUISITES'] = explode("\r",$cp_array[1]['PREREQUISITES']);
			else
				$cp_array[1]['PREREQUISITES'] = array();
			if(count($cp_array[1]['PREREQUISITES']))
			{
				$nums = '';
				foreach($cp_array[1]['PREREQUISITES'] as $course_num)
				{
					$nums .= ",'".$course_num."'";
				}
				$nums = substr($nums,1);
				$grades_array = db_request(db_execute("SELECT CARRIES_CREDITS,COURSE_NUM FROM STUDENT_GRADES_CARD WHERE STUDENT_ID='".get_student_id()."' AND COURSE_NUM IN (".$nums.")"),array(),array('COURSE_NUM'));
				// make sure all pre-reqs have been taken
				if(count($grades_array)<count($cp_array[1]['PREREQUISITES']))
					$warnings[] = _('Not all of necessary courses have been taken for adding course section.');
				// make sure all the pre-reqs have been passed
				foreach($grades_array as $course_num=>$grades)
				{
					foreach($grades as $grade)
					{
						if($grade['CARRIES_CREDITS']!='Y')
						{
							$warnings[] = _('At least one of the necassary courses has not been passing graded.');
							break 2;
						}
					}
				}
				// then, copy to student_add, and to requests
			}
			if(!$errors)
			{
//				if ((count($warnings)==0) || (count($warnings)>0 && Prompt(_('Confirm to Add'),_('There is a problem.').'<BR>'._('You can add this course section, but some course is already scheduled for this school period.'),ErrorMessage($warnings,'attention'))))
				if ((count($warnings)==0) || (count($warnings)>0 && Prompt(_('Confirm to Add'),_('There is a problem.'),ErrorMessage($warnings,'attention'))))
				{
					$id = db_request(db_execute("SELECT ".db_seq_nextval('STUDENT_SCHEDULE_SEQ'). " AS NEXT")); $id = $id[1]['NEXT'];
					db_execute("INSERT INTO STUDENT_SCHEDULE (ID,SCHOOL_YEAR,SCHOOL_ID,STUDENT_ID,START_DATE,COURSE_ID,COURSE_CREDIT_TITLE,COURSE_SECTION_ID,MP,SCHOOL_TERM_ID) values('".$id."','".get_school_year()."','".get_school_id()."','".get_student_id()."','".$date."','".$_REQUEST['course_id']."','".$_REQUEST['course_credits']."','".$_REQUEST['course_section_id']."','".$cp_array[1]['MP']."','".$cp_array[1]['SCHOOL_TERM_ID']."')");
					db_execute("UPDATE COURSE_SECTIONS SET FILLED_SEATS=FILLED_SEATS+1 WHERE COURSE_SECTION_ID='".$_REQUEST['course_section_id']."'");
		
					//make defaults
					$additional_defaults = "";
					if($_SYSTEM['config']['SCHEDULE_DEFAULTS'])
					{
						foreach($_SYSTEM['config']['SCHEDULE_DEFAULTS'] as $sched=>$field)
						{
							$additional_defaults .= ", ".$field;
						}
					}
					$defaults_array = db_request(db_execute("SELECT COURSE_SECTIONS.DAYS $additional_defaults FROM STUDENT_SCHEDULE INNER JOIN COURSE_SECTIONS ON (STUDENT_SCHEDULE.COURSE_SECTION_ID=COURSE_SECTIONS.COURSE_SECTION_ID) INNER JOIN COURSES ON (STUDENT_SCHEDULE.COURSE_ID=COURSES.COURSE_ID) WHERE STUDENT_SCHEDULE.ID='".$id."'"));
					if(count($defaults_array))
					{
						db_execute("UPDATE STUDENT_SCHEDULE SET DAYS = '".$defaults_array[1]["DAYS"]."' WHERE STUDENT_SCHEDULE.ID='".$id."'");
						if($_SYSTEM['config']['SCHEDULE_DEFAULTS'])
						{
							foreach($_SYSTEM['config']['SCHEDULE_DEFAULTS'] as $sched=>$field)
							{
								if($sched != '' && $field != '' && strpos($field,'.') !== false)
								{
									$fld = substr($field,strpos($field,'.')+1);
									db_execute("UPDATE STUDENT_SCHEDULE SET $sched='".$defaults_array[1][$fld]."' WHERE STUDENT_SCHEDULE.ID='".$id."';");
								}
							}
						}
					}
					
					if($_REQUEST['servicefunction']=='choose_course')
					{
						echo "<script language=javascript>opener.document.location = 'modloader.php?servicemod=".$_REQUEST['servicemod']."&time=".time()."&GridOutputCount=".$_REQUEST['GridOutputCount']."'; window.close();</script>";
						unset($_REQUEST['servicefunction']);
						unset($_SESSION['_REQUEST_vars']['servicefunction']);
					}
					elseif($_REQUEST['servicefunction']=='insert_course')
						$_REQUEST['servicefunction'] = 'reg_search';
					else
					{
						unset($_REQUEST['servicefunction']);
						unset($_SESSION['_REQUEST_vars']['servicefunction']);
					}
					
				}
			}
			else
			{
//				$list = '<BR>';
//				$list = '<A onclick="javascript:history.go(-1);"><IMG SRC=images/back.gif height=15></A><A onclick="javascript:history.go(-1);"><font color=blue>'._('Back').'</font></A>';
				$list = '<INPUT TYPE=BUTTON id=backbutton VALUE = '._('Back').' onclick="javascript:history.go(-1);">';
				if(Prompt(_('Error'),'<FONT color="red">'._('Invalid action!!!').'</FONT>',ErrorMessage($errors,'error').'<BR>'.$list,'','Cel',null,null,'get',false));

//				echo $list;
				
			}
		}
		else
		{
        		if(!count($current_array) || $attention || $errors)
        		{
				$list = '<INPUT TYPE=BUTTON id=backbutton VALUE = '._('Back').' onclick="javascript:history.go(-1);">';
				Prompt(_('Error'),'<FONT color="red">'._('Invalid action!!!').'</FONT>',ErrorMessage($errors,'error').'<BR>'.$list,'','Cel',null,null,'get',false);
        		}
        		else
        		{
				if($_REQUEST['servicefunction']=='insert_course')
					$_REQUEST['servicefunction'] = 'reg_search';
				else
				{
					unset($_REQUEST['servicefunction']);
					unset($_SESSION['_REQUEST_vars']['servicefunction']);
					echo "<script language=javascript>window.close();</script>";
				}
			}
		}
	}
}

if(get_student_id() && $_REQUEST['servicefunction']!='choose_course' && $_REQUEST['servicefunction']!='student_drop')
{
	$time = time();
	
	if(!$semesters_array || !$_SYSTEM['PrintSchedules'])
	{
		$semesters_array = db_request(db_execute("SELECT SCHOOL_TERM_ID,TITLE FROM SCHOOL_SEMESTERS WHERE SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."' ORDER BY SORT_ORDER"));
		$quarters_array = db_request(db_execute("SELECT SCHOOL_TERM_ID,TITLE FROM SCHOOL_QUARTERS WHERE SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."' ORDER BY SORT_ORDER"));
	}

	//$show_state_fields = !$_REQUEST['btn_hide_state_fields'] && $_REQUEST['btn_show_adv_fields'];
	//if(!$show_state_fields && $_REQUEST['btn_show_group2_fields']=='Y')
		$show_state_fields = true;

	if(!isset($_REQUEST['school_term_id']) && get_user('PROFILE')=='student')
	{
		// IF THERE'S NO school term SET, AND USER IS A STUDENT, ENTER FIRST AVAILABLE MP FOR REGISTRATION
		foreach($quarters_array as $quarter)
		{
			if(get_school_term($quarter['SCHOOL_TERM_ID'],'REGISTRATION_START_DATE') && ($time >= strtotime(get_school_term($quarter['SCHOOL_TERM_ID'],'REGISTRATION_START_DATE')) && $time <= strtotime(get_school_term($quarter['SCHOOL_TERM_ID'],'REGISTRATION_END_DATE'))))
			{
				$_REQUEST['school_term_id'] = $quarter['SCHOOL_TERM_ID'];
				break;
			}
		}
		foreach($semesters_array as $quarter)
		{
			if(get_school_term($quarter['SCHOOL_TERM_ID'],'REGISTRATION_START_DATE') && ($time >= strtotime(get_school_term($quarter['SCHOOL_TERM_ID'],'REGISTRATION_START_DATE')) && $time <= strtotime(get_school_term($quarter['SCHOOL_TERM_ID'],'REGISTRATION_END_DATE'))))
			{
				$_REQUEST['school_term_id'] = $quarter['SCHOOL_TERM_ID'];
				break;
			}
		}
	}
	
	if(!$_REQUEST['school_term_id'])
		$_REQUEST['school_term_id'] = '0';

	if(get_school_term($_REQUEST['school_term_id'],'REGISTRATION_START_DATE') && ($time >= strtotime(get_school_term($_REQUEST['school_term_id'],'REGISTRATION_START_DATE')) && $time <= strtotime(get_school_term($_REQUEST['school_term_id'],'REGISTRATION_END_DATE'))))
		$allow_register = true;
	//check for correct work
	if(!$warnings || $_REQUEST['delete_ok']) 
	    if(!$_REQUEST['servicemod']=='mod_curriculum/ScdPRStudSchedWorkspace.php')
		DrawStudentHeader();

	if($_REQUEST['include_scheduler']=='true')
	{
		$_REQUEST['student_id'] = get_student_id();
		include($staticpath."modules/mod_curriculum/ScdStudSchedWizard.php");
		unset($_REQUEST['include_scheduler']);
	}
	if(get_user('PROFILE') == 'student' || get_user('PROFILE') == 'parent')
		echo "<FORM action=modloader.php?servicemod=$_REQUEST[servicemod]&GridOutputCount=".$_REQUEST['GridOutputCount']."&servicefunction=&school_term_id=".$_REQUEST['school_term_id']."&useontop=".$_REQUEST['useontop'].($show_state_fields?"&btn_show_adv_fields=1":"")." METHOD=POST>";
	else
		echo "<FORM action=modloader.php?servicemod=$_REQUEST[servicemod]&GridOutputCount=".$_REQUEST['GridOutputCount']."&servicefunction=modify&school_term_id=".$_REQUEST['school_term_id']."&useontop=".$_REQUEST['useontop'].($show_state_fields?"&btn_show_adv_fields=1":"")." METHOD=POST>";

	if(!$_REQUEST['dftype'])
		$_REQUEST['dftype'] = 'course_list';

	if(!$_REQUEST['CREATEPDF'] && (!$warnings || $_REQUEST['delete_ok']))
	{
		$left .= ' &nbsp; '.CheckBoxOnclick('include_inactive',_('Include Inactive Courses'));
	
		if($_REQUEST['dftype']=='course_list')
		{
			$header .= $button->createButton(_('Course List'),SetRequestOptions(null,array('dftype','search_servicefunction')).'&amp;dftype=course_list');
			$header .= $button->createText(_('Timetable for Week'),SetRequestOptions(null,array('dftype','search_servicefunction')).'&amp;dftype=timetable');
		}
		elseif($_REQUEST['dftype']=='timetable')
		{
			$header .= $button->createText(_('Course List'),SetRequestOptions(null,array('dftype','search_servicefunction')).'&amp;dftype=course_list');
			$header .= $button->createButton(_('Timetable for Week'),SetRequestOptions(null,array('dftype','search_servicefunction')).'&amp;dftype=timetable');
		}
	}

	if(!$warnings || $_REQUEST['delete_ok'])
	{
		if(get_user('PROFILE')=='admin' && $_REQUEST['servicemod']!='mod_curriculum/ScdPRStudSchedWorkspace.php')
		{
			$left = ' &nbsp; &nbsp; <B>'._('Date of Actuality').': </B>'.PrepareDate($date,'_date').$left;
	
			if(!$_REQUEST['CREATEPDF'])
			{
				if($_SYSTEM['config']['group2']['STUDENT_SCHEDULE'])
					$state_fields_buttons = CheckboxOnclick("btn_show_adv_fields",_('Show').' '.$_SYSTEM['config']['state_name'].' '._('Fields')).'<BR>'.CheckboxOnclick("btn_show_group2_fields",_('Show').' '.$_SYSTEM['config']['group2']['STUDENT_SCHEDULE'].' '._('Fields'));
				else
					$state_fields_buttons = $submitButton->createIButton(_(($show_state_fields?"Hide":"Show"))._(' '.$_SYSTEM['config']['state_name'].' Fields'), "btn_".($show_state_fields?"hide":"show")."_state_fields");
			}
			
			//DisplayHeader($left,'<TABLE><TR>'.$header.'<TD>'.(StateFieldsSet("STUDENT_SCHEDULE")&&AllowEdit()?$state_fields_buttons:"").$submitButton->createIButton(_('Save'),'',' id=top_submit onclick="rb_submit=true;"').'</TD></TR></TABLE>','','white');
			echo '<TABLE align=center><TR><TD>'.TabsHeader($header).'</TD></TR></TABLE>';
			DisplayHeader($left,(StateFieldsSet("STUDENT_SCHEDULE")&&AllowEdit()?$state_fields_buttons:"").$submitButton->createSButton(_('Save'),'',' id=top_submit onclick="rb_submit=true;"'));
		}
		else
		{
			echo TabsHeader($header);
		}
	}

	if(!$_SYSTEM['PrintSchedules']['schedule_array'])
	{
		$state_fields = $show_state_fields ? ",".StateFieldsSQL("STUDENT_SCHEDULE","s","STUDENT_SCHEDULE") : "";
                $state_fields = ($state_fields==',')?'':$state_fields;
		$sql = "SELECT 
					s.ID,s.COURSE_ID,s.COURSE_CREDIT_TITLE,s.COURSE_SECTION_ID,cs.PARENT_ID,cs.TEACHER_ID AS TFULL_NAME,c.SUBJECT_ID,c.SHORT_NAME AS COURSE_NUM,cs.SHORT_NAME AS CP_SHORT_NAME,cs.TEACHER_ID,
					s.SCHOOL_TERM_ID,s.START_DATE,s.END_DATE,
					cs.SCHOOL_PERIOD_ID,cs.SCHOOL_TERM_ID as COURSE_SCHOOL_TERM_ID,s.MP,sp.SORT_ORDER,
					c.TITLE,cs.COURSE_SECTION_ID AS PERIOD_PULLDOWN,
					s.STUDENT_ID,cs.ROOM,cs.WEEK,s.DAYS,cs.DAYS AS SECTION_DAYS,s.SCHEDULER_LOCK,NULL AS CHILDREN{$state_fields}
				FROM STUDENT_SCHEDULE s,COURSES c,COURSE_SECTIONS cs LEFT OUTER JOIN SCHOOL_PERIODS sp ON (sp.SCHOOL_PERIOD_ID = cs.SCHOOL_PERIOD_ID AND cs.SCHOOL_ID = sp.SCHOOL_ID)
				WHERE
					s.COURSE_ID = c.COURSE_ID AND s.COURSE_ID = cs.COURSE_ID
					AND s.COURSE_SECTION_ID = cs.COURSE_SECTION_ID
					AND s.SCHOOL_YEAR = c.SCHOOL_YEAR 
					AND s.STUDENT_ID='".get_student_id()."' 
					AND s.SCHOOL_YEAR='".get_school_year()."'
					AND s.SCHOOL_ID = '".get_school_id()."'";
		if($_Config['scheduling_multiple_periods']===true && $_REQUEST['dftype']=='course_list')
			$sql .= " AND EXISTS (SELECT '' FROM COURSE_SECTIONS cs2 WHERE cp2.PARENT_ID=cs.COURSE_SECTION_ID) ";

		if($_REQUEST['school_term_id']!='0')
			$sql .= " AND s.SCHOOL_TERM_ID IN (".get_all_school_term(false,$_REQUEST['school_term_id']).')';
	
		if($_REQUEST['include_inactive']!='Y')
			$sql .= " AND ('".$date."' BETWEEN s.START_DATE AND s.END_DATE OR (s.END_DATE IS NULL)) ";
		if($_Config['scheduling_multiple_periods']===true && $_REQUEST['servicemod']=='mod_curriculum/ScdPRStudSchedWorkspace.php')
			$sql .= " ORDER BY s.SCHOOL_TERM_ID,sp.SORT_ORDER,s.START_DATE";
		else
			$sql .= " ORDER BY sp.SORT_ORDER,s.SCHOOL_TERM_ID,s.START_DATE";

		$functions = array('TITLE'=>'_makeTitle','PERIOD_PULLDOWN'=>'_makePeriodSelect','CHILDREN'=>'_makeChildren','COURSE_SCHOOL_TERM_ID'=>'_makeMPSelect','SCHEDULER_LOCK'=>'_makeLock','START_DATE'=>'_makeDate','END_DATE'=>'_makeDate','DAYS'=>'_makeDays','TFULL_NAME'=>'get_teacher_last_fm');
		if($_Config['scheduling_multiple_periods']!==true)
			unset($functions['CHILDREN']);
		elseif($_REQUEST['servicemod']=='mod_curriculum/ScdPRStudSchedWorkspace.php')
		{
			$functions['TEACHER_ID'] = 'GetTeacher';
			unset($functions['PERIOD_PULLDOWN']);
		}

		if($_REQUEST['dftype']=='timetable')
			unset($functions['DAYS']);

		if($show_state_fields)
			$functions += StateFieldsFunctions("STUDENT_SCHEDULE", "_make_state_CheckboxInput", "_make_state_SelectInput", "_make_state_TextInput", "_makeDate");
		if(SystemPreferences('ODD_EVEN_WEEKS','system') == 'Y')
			$functions +=array('WEEK'=>'get_week');
		$get_school_id_buffer = $_SESSION['get_school_id'];

		$QI = db_execute($sql);
		$schedule_array = db_request($QI,$functions);
	}
	else
		$schedule_array = $_SYSTEM['PrintSchedules']['schedule_array'][get_student_id()];

	if(!$mps_array || !$_SYSTEM['PrintSchedules']) // this might come from being included repeatedly in print schedules
		$mps_array = db_request(db_execute("SELECT DISTINCT MP FROM STUDENT_SCHEDULE WHERE STUDENT_ID='".get_student_id()."' AND SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."'"));

	foreach($mps_array as $mp)
	{
		if($mp['MP']=='QTR')
			$qtr_courses = true;
		elseif($mp['MP']=='SEM')
			$sem_courses = true;
	}

	$tabs = array(array('title'=>_('Full Year'),'link'=>SetRequestOptions(null,array('school_term_id','search_servicefunction')).'&amp;school_term_id=0'));

	if($sem_courses)
	{
		foreach($semesters_array as $category)
			$tabs[] = array('title'=>$category['TITLE'],'link'=>SetRequestOptions(null,array('school_term_id','search_servicefunction')).'&amp;school_term_id='.$category['SCHOOL_TERM_ID']);
	}
	
	if($qtr_courses)
	{
		foreach($quarters_array as $category)
			$tabs[] = array('title'=>$category['TITLE'],'link'=>SetRequestOptions(null,array('school_term_id','search_servicefunction')).'&amp;school_term_id='.$category['SCHOOL_TERM_ID']);
	}

	$options = array('search'=>false);
	if(get_user('PROFILE')!='student')
	{
		$link['add']['link'] = "# onclick='window.open(\"modloader.php?servicemod=$_REQUEST[servicemod]&servicefunction=choose_course\",\"\",\"scrollbars=yes,resizable=yes,width=800,height=400\");' ";
		$link['add']['title'] = _('Add a Course Section');

		if(AllowUse('mod_curriculum/ScdCourseProperties.php'))
		{
			$link['TITLE']['link'] = "modloader.php?servicemod=mod_curriculum/ScdCourseProperties.php&useontop=false";
			$link['TITLE']['variables'] = array('subject_id'=>'SUBJECT_ID','course_id'=>'COURSE_ID','course_credits'=>'COURSE_CREDIT_TITLE');
			$link['TITLE']['js'] = true;		
		}
	}
	elseif($allow_register==true)
	{
		$link['remove']['link'] = 'modloader.php?servicemod='.$_REQUEST['servicemod'].'&servicefunction=student_drop';
		$link['remove']['variables'] = array('id'=>'ID','course_section_id'=>'PARENT_ID','course_id'=>'COURSE_ID');
		$options['add'] = true;
	}
	$columns = array('TITLE'=>_('Course Name'),
			 'PERIOD_PULLDOWN'=>_('Period - Days - Course - Teacher name'),
			 'CHILDREN'=>_('All Periods'),
			 'DAYS'=>_('Course Days'),
			 'WEEK'=>_('Week'),
			 'ROOM'=>_('Class-room'),
			 'COURSE_SCHOOL_TERM_ID'=>_('School Term'),
			 'SCHEDULER_LOCK'=>'<IMG SRC=images/locked.gif border=0>',
			 'START_DATE'=>_('Course Start Date'),
			 'END_DATE'=>_('Course End Date'));
	if($_Config['scheduling_multiple_periods']!==true)
		unset($columns['CHILDREN']);
	if(SystemPreferences('ODD_EVEN_WEEKS','system') != 'Y')
		unset($columns['WEEK']);
	if($show_state_fields)
	{
		$columns += array('COURSE_NUM'=>_('Course Number'),
				  'CP_SHORT_NAME'=>_('Course Section'));
		$columns += StateFieldsArray("STUDENT_SCHEDULE");
		$options['yscroll']=true;
		$options['yscroll_numcols'] = 1;
	}

	if(count($days_array)==1)
		unset($columns['DAYS']);

	if($_REQUEST['CREATEPDF'] || !AllowEdit() || get_user('PROFILE')!='admin' || ($min_date[1]['MIN_DATE'] && get_db_date('postgres')>=$min_date[1]['MIN_DATE']))
		unset($columns['SCHEDULER_LOCK']);
	else
	{
		$link['remove']['link'] = 'modloader.php?servicemod='.$_REQUEST['servicemod'].'&servicefunction=student_drop';
		$link['remove']['variables'] = array('id'=>'ID','course_section_id'=>'COURSE_SECTION_ID','course_id'=>'COURSE_ID');
	}
	if(get_user('PROFILE')=='student' || $_REQUEST['servicemod']=='mod_curriculum/ScdPRStudSchedWorkspace.php')
	{
		unset($columns['START_DATE']);
		unset($columns['END_DATE']);
		//unset($link['remove']);
	}

	if($_REQUEST['servicemod']=='mod_curriculum/ScdPRStudSchedWorkspace.php' && $_Config['scheduling_multiple_periods']===true)
	{
		unset($columns['PERIOD_PULLDOWN']);
		$columns['TEACHER_ID'] = _('Teacher Name');
	}

	echo '<BR>';
	$_SYSTEM['selected_tab'] = SetRequestOptions(null,array('school_term_id','search_servicefunction')).'&amp;school_term_id='.$_REQUEST['school_term_id'];
	if(count($schedule_array)==0)
	{

		echo PopTable('header',$tabs,'width=45%');
		Gridoutput($schedule_array,$columns,_('Classes'),_('Amount of Classes'),$link,array(),$options);
		echo PopTable('footer');
	}
	else
	{
		if(count($tabs)>1 && $_REQUEST['servicemod']!='mod_curriculum/ScdPRStudSchedWorkspace.php')
		{
			$options['middle'] = WrapTabs($tabs,$_SYSTEM['selected_tab']);
		}
		$options['xscroll'] = true;

		if($_REQUEST['dftype']=='timetable')
		{
			if(!$periods_array || !$_SYSTEM['PrintSchedules'])
			{
				if($periods_extra)
					$periods_extra = ' AND SCHOOL_PERIOD_ID IN ('.substr($periods_extra,1).') ';			
				if(Preferences('LAST_LOGIN_FORMAT') == '12')
					$periods_array = db_request(db_execute("SELECT SCHOOL_PERIOD_ID,TITLE,".db_to_char('START_TIME','HH12:MI AM')." AS START_TIME,".db_to_char('END_TIME','HH12:MI AM')." AS END_TIME,".db_to_char('START_TIME_SUN','HH12:MI AM')." AS START_TIME_SUN,".db_to_char('END_TIME_SUN','HH12:MI AM')." AS END_TIME_SUN,".db_to_char('START_TIME_MON','HH12:MI AM')." AS START_TIME_MON,".db_to_char('END_TIME_MON','HH12:MI AM')." AS END_TIME_MON,".db_to_char('START_TIME_TUE','HH12:MI AM')." AS START_TIME_TUE,".db_to_char('END_TIME_TUE','HH12:MI AM')." AS END_TIME_TUE,".db_to_char('START_TIME_WED','HH12:MI AM')." AS START_TIME_WED,".db_to_char('END_TIME_WED','HH12:MI AM')." AS END_TIME_WED,".db_to_char('START_TIME_THU','HH12:MI AM')." AS START_TIME_THU,".db_to_char('END_TIME_THU','HH12:MI AM')." AS END_TIME_THU,".db_to_char('START_TIME_FRI','HH12:MI AM')." AS START_TIME_FRI,".db_to_char('END_TIME_FRI','HH12:MI AM')." AS END_TIME_FRI,".db_to_char('START_TIME_SAT','HH12:MI AM')." AS START_TIME_SAT,".db_to_char('END_TIME_SAT','HH12:MI AM')." AS END_TIME_SAT,
						LENGTH,LENGTH_SUN,LENGTH_MON,LENGTH_TUE,LENGTH_WED,LENGTH_THU,LENGTH_FRI,LENGTH_SAT,
						NULL AS SUN,NULL AS MON,NULL AS TUE,NULL AS WED,NULL AS THU,NULL AS FRI,NULL AS SAT FROM SCHOOL_PERIODS WHERE SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."' ".$periods_extra." ORDER BY SORT_ORDER,TITLE"),array(),array('SCHOOL_PERIOD_ID'));
				else
					$periods_array = db_request(db_execute("SELECT SCHOOL_PERIOD_ID,TITLE,".db_to_char('START_TIME','HH24:MI')." AS START_TIME,".db_to_char('END_TIME','HH24:MI')." AS END_TIME,".
	    								db_to_char('START_TIME_SUN','HH24:MI')." AS START_TIME_SUN,".db_to_char('END_TIME_SUN','HH24:MI')." AS END_TIME_SUN,".
									db_to_char('START_TIME_MON','HH24:MI')." AS START_TIME_MON,".db_to_char('END_TIME_MON','HH24:MI')." AS END_TIME_MON,".
									db_to_char('START_TIME_TUE','HH24:MI')." AS START_TIME_TUE,".db_to_char('END_TIME_TUE','HH24:MI')." AS END_TIME_TUE,".
									db_to_char('START_TIME_WED','HH24:MI')." AS START_TIME_WED,".db_to_char('END_TIME_WED','HH24:MI')." AS END_TIME_WED,".
									db_to_char('START_TIME_THU','HH24:MI')." AS START_TIME_THU,".db_to_char('END_TIME_THU','HH24:MI')." AS END_TIME_THU,".
									db_to_char('START_TIME_FRI','HH24:MI')." AS START_TIME_FRI,".db_to_char('END_TIME_FRI','HH24:MI')." AS END_TIME_FRI,".
									db_to_char('START_TIME_SAT','HH24:MI')." AS START_TIME_SAT,".db_to_char('END_TIME_SAT','HH24:MI')." AS END_TIME_SAT,
						LENGTH,LENGTH_SUN,LENGTH_MON,LENGTH_TUE,LENGTH_WED,LENGTH_THU,LENGTH_FRI,LENGTH_SAT,
						NULL AS SUN,NULL AS MON,NULL AS TUE,NULL AS WED,NULL AS THU,NULL AS FRI,NULL AS SAT FROM SCHOOL_PERIODS WHERE SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."' ".$periods_extra." ORDER BY SORT_ORDER,TITLE"),array(),array('SCHOOL_PERIOD_ID'));
				
				$orig_periods_array = $periods_array;
			}
			else
				$periods_array = $orig_periods_array;		
			
		}
//		var_dump($schedule_array);//[2]['DAYS']);
//		echo '<br>';
//		
		if($_REQUEST['dftype']=='course_list')
		{
			$days = array('Mon','Tue','Wed','Thu','Fri','Sat','Sun');

			foreach($schedule_array as $key=>$value)
			{
				foreach($days as $day)
				{
					$schedule_array[$key]['PERIOD_PULLDOWN'] = str_replace($day,_($day).' ',$schedule_array[$key]['PERIOD_PULLDOWN']);
				}
			}
			Gridoutput($schedule_array,$columns,_('Classes'),_('Amount of Classes'),$link,array(),$options);
		}	
		elseif($_REQUEST['dftype']=='timetable' && count($periods_array)<35)
		{
			if($_REQUEST['CREATEPDF'])
				$_SESSION['orientation'] = 'landscape';

			if(Preferences('CALENDAR')=='Mon')
			{
			    $columns = array('TITLE'=>'','Mon'=>_('Monday'),'Tue'=>_('Tuesday'),'Wed'=>_('Wednesday'),'Thu'=>_('Thursday'),'Fri'=>_('Friday'),'Sat'=>_('Saturday'),'San'=>_('Sunday'));
			}else{
			    $columns = array('TITLE'=>'','Sun'=>_('Sunday'),'Mon'=>_('Monday'),'Tue'=>_('Tuesday'),'Wed'=>_('Wednesday'),'Thu'=>_('Thursday'),'Fri'=>_('Friday'),'Sat'=>_('Saturday'));
			}

			if(!$days_array || !$_SYSTEM['PrintSchedules'])
				$days_array = db_request(db_execute("SELECT DISTINCT DAYS FROM COURSE_SECTIONS WHERE SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."'"));
			foreach($days_array as $days)
			{
				$days = $days['DAYS'];
				for($i=0;$i<strlen($days);$i+=3)
					$meeting_days[substr($days,$i,3)] = true;
			}
			if(!$meeting_days['Sun'])
				unset($columns['Sun']);
			if(!$meeting_days['Sat'])
				unset($columns['Sat']);

			foreach($schedule_array as $course)
			{
				foreach($columns as $d=>$day)
				{
					if(strpos($course['DAYS'],$d)!==false)
					{
						// don't print the class if the period meets for 0 minutes this day.
						if(SystemPreferences('VARIABLE_PERIOD_LENGTH')=='Y' && $periods_array[$course['SCHOOL_PERIOD_ID']][1]['LENGTH_'.strtoupper($d)]==0)
							continue;

						if(SystemPreferences('VARIABLE_PERIOD_LENGTH')=='Y' && $periods_array[$course['SCHOOL_PERIOD_ID']][1]['START_TIME_'.strtoupper($d)])
						{
							$periods_array[$course['SCHOOL_PERIOD_ID']][1][$d] = '<TABLE class=GridOutput_fieldint width=100%><TR><TD valign=top width=42%>'.$periods_array[$course['SCHOOL_PERIOD_ID']][1]['START_TIME_'.strtoupper($d)];
							if($periods_array[$course['SCHOOL_PERIOD_ID']][1]['END_TIME_'.strtoupper($d)])
								$periods_array[$course['SCHOOL_PERIOD_ID']][1][$d] .= ' <BR>'.$periods_array[$course['SCHOOL_PERIOD_ID']][1]['END_TIME_'.strtoupper($d)].'';
							$periods_array[$course['SCHOOL_PERIOD_ID']][1][$d] .= '</TD><TD valign=top width=58%>';
						
						}
						elseif($periods_array[$course['SCHOOL_PERIOD_ID']][1][$d])
							$periods_array[$course['SCHOOL_PERIOD_ID']][1][$d] .= '<BR>';

						$periods_array[$course['SCHOOL_PERIOD_ID']][1][$d] .= $course['TITLE']."<br>".str_replace(",","",$course['TFULL_NAME']);

						if($course['ROOM'])
							$periods_array[$course['SCHOOL_PERIOD_ID']][1][$d] .= '<BR>&nbsp; '.$course['ROOM'];
						if(SystemPreferences('ODD_EVEN_WEEKS','system') == 'Y')
							$periods_array[$course['SCHOOL_PERIOD_ID']][1][$d] .= ' - '.$course['WEEK'];
						if(SystemPreferences('VARIABLE_PERIOD_LENGTH')=='Y' && $periods_array[$course['SCHOOL_PERIOD_ID']][1]['START_TIME_'.strtoupper($d)])
							$periods_array[$course['SCHOOL_PERIOD_ID']][1][$d] .= '</TD></TR></TABLE><BR>';
					}
				}
			}
			$array = array();
			$array[0] = '';
			foreach($periods_array as $i=>$period)
			{
				if(SystemPreferences('VARIABLE_PERIOD_LENGTH')!='Y' && $period[1]['START_TIME'])
				{
					$period[1]['TITLE'] .= ' &nbsp; &nbsp; '.$period[1]['START_TIME'];
					if($period[1]['END_TIME'])
						$period[1]['TITLE'] .= ' - '.$period[1]['END_TIME'];
					$period[1]['TITLE'] .= '<BR><BR>';
				}
				else
					$period[1]['TITLE'] = ''.$period[1]['TITLE'].'<BR><BR>';
				$array[] = $period[1];
			}
			unset($array[0]);
			Gridoutput($array,$columns,'','',array(),array(),$options);
		}
		elseif($_REQUEST['dftype']=='timetable')
		{
			$_REQUEST['student_id'] = get_student_id();
			echo $options['middle'];
			echo "</TR><TR>";
			include($staticpath.'modules/mod_ssetup/SchInventoryCenter.php');
			echo "</TR>";
		}
		if(AllowEdit())
			echo '<BR><CENTER>'.$submitButton->createSButton(_('Save'),'',' id=bottom_submit onclick="rb_submit=true;"').'</CENTER><BR>';
	}
	echo '</FORM>';

	if((get_user('PROFILE')=='student' && $allow_register) || (get_user('PROFILE')=='admin' && AllowEdit()))
	{
		echo '<FORM action=modloader.php?servicemod='.$_REQUEST['servicemod'].'&servicefunction=reg_search&school_term_id='.$_REQUEST['school_term_id'].'&dftype='.$_REQUEST['dftype'].'#search_block method=POST>';
		$subjects_array = db_request(db_execute("SELECT SUBJECT_ID,TITLE FROM COURSE_SUBJECTS WHERE SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."'"));
		$subjects = '<SELECT name=subject_id><option value="">'._('Any Subject').'</option>';
		foreach($subjects_array as $subject)
        
			$subjects .= "<OPTION value=$subject[SUBJECT_ID]".($_REQUEST['subject_id']==$subject['SUBJECT_ID']?' SELECTED':'').">".$subject['TITLE'].'</OPTION>';
		$subjects .= '</SELECT>';

		$periods_array = db_request(db_execute("SELECT SCHOOL_PERIOD_ID,TITLE FROM SCHOOL_PERIODS WHERE SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."' ORDER BY SORT_ORDER,TITLE"));
		$periods = '<SELECT name=school_period_id><option value="">'._('Any School Period').'</option>';
		foreach($periods_array as $period)
			$periods .= "<OPTION value=$period[SCHOOL_PERIOD_ID]".($_REQUEST['school_period_id']==$period['SCHOOL_PERIOD_ID']?' SELECTED':'').">".$period['TITLE'].'</OPTION>';
		$periods .= '</SELECT>';

		$teachers_array = db_request(db_execute("SELECT USER_ID,LAST_NAME".CCAT."', '".CCAT."FIRST_NAME AS TITLE FROM USERS WHERE SCHOOLS LIKE '%,".get_school_id().",%' AND PROFILE='teacher' ORDER BY LAST_NAME,FIRST_NAME"));
		$teachers = '<SELECT name=teacher_id><option value="">'._('Any Teacher').'</option>';
		foreach($teachers_array as $teacher)
			$teachers .= "<OPTION value=$teacher[USER_ID]".($_REQUEST['teacher_id']==$teacher['USER_ID']?' SELECTED':'').">".$teacher['TITLE'].'</OPTION>';
		$teachers .= '</SELECT>';

		$subjects_array = db_request(db_execute("SELECT ID,TITLE FROM GRADUATION_REQ_SUBJECTS WHERE SCHOOL_ID='".get_school_id()."'"));
		if(count($subjects_array))
		{
			$grad_subjects = '<SELECT name=grad_subject_id><option value="">'._('Any Graduation Requirement').'</option>';
			foreach($subjects_array as $subject)
				$grad_subjects .= "<OPTION value=$subject[ID]".($_REQUEST['grad_subject_id']==$subject['ID']?' SELECTED':'').">".$subject['TITLE'].'</OPTION>';
			$grad_subjects .= '</SELECT>';
		}

		$mp_array = db_request(db_execute("SELECT SCHOOL_TERM_ID,SHORT_NAME,'2' AS MP_TABLE,SORT_ORDER FROM SCHOOL_QUARTERS WHERE SCHOOL_ID='".get_school_id()."' AND SCHOOL_YEAR='".get_school_year()."' UNION SELECT SCHOOL_TERM_ID,SHORT_NAME,'1' AS MP_TABLE,SORT_ORDER FROM SCHOOL_SEMESTERS WHERE SCHOOL_ID='".get_school_id()."' AND SCHOOL_YEAR='".get_school_year()."' ORDER BY 3,4"));

		if(count($mp_array))
		{
			$school_terms = '<SELECT name=school_term_id><option value="">'._('Any Term').'</option>';
			$school_terms .= "<OPTION value=0".($_REQUEST['school_term_id']==='0'?' SELECTED':'').">"._('Full Year').'</OPTION>';
			foreach($mp_array as $mp)
			{
				$school_terms .= "<OPTION value=$mp[SCHOOL_TERM_ID]".($_REQUEST['school_term_id']==$mp['SCHOOL_TERM_ID']?' SELECTED':'').">".$mp['SHORT_NAME'].'</OPTION>';
			}
			$school_terms .= '</SELECT>';
		}
		

		if($_REQUEST['servicefunction']=='reg_search')
		{
			unset($link);
			if($_REQUEST['subject_id'] || $_REQUEST['course_title'] || $_REQUEST['course_num'] || $_REQUEST['school_period_id'] || $_REQUEST['teacher_id'] || $_REQUEST['grad_subject_id'] || $_REQUEST['school_term_id'])
			{
				if(!$_REQUEST['GridSortingBy'])
					$group = array('PARENT_ID');
				else
					$group = null;

				$sections_array = db_request(db_execute("SELECT cs.PARENT_ID,cs.COURSE_SECTION_ID,c.COURSE_ID,c.TITLE,w.COURSE_CREDIT_TITLE,cs.SCHOOL_PERIOD_ID,cs.DAYS,cs.WEEK,w.CREDITS,cs.TEACHER_ID,cs.TOTAL_SEATS,cs.FILLED_SEATS,cs.SCHOOL_TERM_ID,
					(COALESCE(cs.TOTAL_SEATS,0)-COALESCE(cs.FILLED_SEATS,0)) AS AVAILABLE_SEATS,CAST(COALESCE(cs.TOTAL_SEATS,0)-COALESCE(cs.FILLED_SEATS,0) AS VARCHAR)".CCAT."' / '".CCAT."CAST(COALESCE(cs.TOTAL_SEATS,0) AS VARCHAR) AS SEATS,cs.ROOM,
					c.SHORT_NAME AS COURSE_NUM,cs.SHORT_NAME AS SECTION_SHORT_NAME
					FROM COURSES c,COURSE_CREDITS w,COURSE_SECTIONS cs WHERE "
				.($_REQUEST['subject_id']?"c.SUBJECT_ID='".$_REQUEST['subject_id']."' AND ":'')
				.($_REQUEST['course_title']?"UPPER(c.TITLE) LIKE '%".strtoupper($_REQUEST['course_title'])."%' AND ":'')
				.($_REQUEST['course_num']?"UPPER(c.SHORT_NAME) LIKE '".strtoupper($_REQUEST['course_num'])."%' AND ":'')
				.($_REQUEST['section_short_name']?"UPPER(cs.SHORT_NAME) LIKE '".strtoupper($_REQUEST['section_short_name'])."%' AND ":'')
				.($_REQUEST['school_period_id']?"cs.SCHOOL_PERIOD_ID='".$_REQUEST['school_period_id']."' AND ":'')
				.($_REQUEST['teacher_id']?"cs.TEACHER_ID='".$_REQUEST['teacher_id']."' AND ":'')
				//." w.STUDENT_SCHEDULEABLE='Y' AND "
				.($_REQUEST['grad_subject_id']?"c.GRAD_SUBJECT_ID='".$_REQUEST['grad_subject_id']."' AND ":'')
				.($_REQUEST['school_term_id']?"cs.SCHOOL_TERM_ID='".$_REQUEST['school_term_id']."' AND ":'')
				." cs.SCHOOL_TERM_ID IN (".get_all_school_term(false,$_REQUEST['school_term_id']).') AND '
				." c.COURSE_ID=w.COURSE_ID AND cs.COURSE_ID=c.COURSE_ID AND cs.COURSE_CREDIT_TITLE=w.COURSE_CREDIT_TITLE AND c.SCHOOL_YEAR='".get_school_year()."' AND c.SCHOOL_ID='".get_school_id()."'
				ORDER BY ".db_case(array('cs.COURSE_SECTION_ID','cs.PARENT_ID',"'1'","'2'"))." ASC,c.TITLE,AVAILABLE_SEATS,cs.SCHOOL_PERIOD_ID
				"),array('SCHOOL_PERIOD_ID'=>'get_period','TEACHER_ID'=>'GetTeacher','TITLE'=>'_makeSearchTitle','SCHOOL_TERM_ID'=>'get_school_term','COURSE_NUM'=>'_makeCourseNum','WEEK'=>'get_week','DAYS'=>'get_days'),$group);

				if(get_user('PROFILE')=='student')
				{
					$link['TITLE']['link'] = 'modloader.php?servicemod='.$_REQUEST['servicemod'].'&servicefunction=student_add&school_term_id='.$_REQUEST['school_term_id'];
					$link['TITLE']['variables'] = array('course_section_id'=>'COURSE_SECTION_ID','course_id'=>'COURSE_ID','course_credits'=>'COURSE_CREDIT_TITLE');
				}
				else
				{
					$link['TITLE']['link'] = SetRequestOptions(null,array('servicefunction')).'&servicefunction=insert_course';
					$link['TITLE']['variables'] = array('course_section_id'=>'COURSE_SECTION_ID','course_id'=>'COURSE_ID','course_credits'=>'COURSE_CREDIT_TITLE');
				}
				$columns = array('TITLE'=>_('Course Name'),
						 'COURSE_NUM'=>_('Course Number'),
						 'SCHOOL_PERIOD_ID'=>_('School Period'),
						 'TEACHER_ID'=>_('Teacher Name'),
						 'SECTION_SHORT_NAME'=>_('Section ID'),
						 'ROOM'=>_('Class-room'),
						 'SCHOOL_TERM_ID'=>_('School Term'),
						 'DAYS'=>_('Course Days'),
						 'WEEK'=>_('Week'),
						 'CREDITS'=>_('Credits'),
						 'SEATS'=>_('Seats: Vacant / Total'));
				if($_Config['require_course_num']!=true)
				{
					unset($columns['COURSE_NUM']);
					unset($columns['SECTION_SHORT_NAME']);
				}
				if(count($days_array)==1)
					unset($columns['DAYS']);
				if(SystemPreferences('ODD_EVEN_WEEKS','system') != 'Y')
					unset($columns['WEEK']);

				$list = GridoutputBuffered($sections_array,$columns,_('Course Sections'),_('Amount of Course Sections'),$link,array(array('PARENT_ID','TITLE')),array('search'=>false));
			}
			else
				$list = '<B>'._('You have to enter search criteria, if you want to find  and add a course section.').'</B>';
		}

		if($_REQUEST['servicefunction']!='student_drop' && $_REQUEST['servicefunction']!='student_add' && !$_REQUEST['CREATEPDF'])
		{
			if(get_user('PROFILE')=='student')
				$contents = _('Registration open until').' '.ProperDate(get_school_term($_REQUEST['school_term_id'],'REGISTRATION_END_DATE')).'<BR><BR>';
//			$contents .= '<TABLE width=100% class=BoxContents><TR><TD align='.ALIGN_RIGHT.'>'._('Subject Name').'</TD><TD>'.$subjects.'</TD>';
			$contents .= '<TABLE width=100% class=BoxContents><TR>
		<TD><fieldset color=gray><legend>'._('Subject Name').'</legend>'.$subjects.'</fieldset></TD>';
			if($_Config['require_course_num']==true)
			{
				$contents .= '<TD align='.ALIGN_RIGHT.'>'._('Course Number').'</TD><TD><INPUT type=text id=course_num name=course_num value="'.$_REQUEST['course_num'].'" size=8></TD>
				<TD><fieldset><legend>'._('Course Name').'</legend><INPUT type=text id=course_title name=course_title value="'.$_REQUEST['course_title'].'" size=10></fieldset></TD>
				<TD><fieldset><legend>'._('Course Section ID').'</legend><INPUT type=text id=section_short_name name=section_short_name value="'.$_REQUEST['section_short_name'].'" size=5></fieldset></TD>';
			}
			else
			{
				$contents .= '<TD><fieldset><legend>'._('Course Name').'</legend><INPUT type=text id=course_title name=course_title value="'.$_REQUEST['course_title'].'" size=10></fieldset></TD>
				<TD><fieldset><legend>'._('Course Number').'</legend><INPUT type=text id=course_num name=course_num value="'.$_REQUEST['course_num'].'" size=8></fieldset></TD>';
			}
			$contents .= '<TD><fieldset><legend>'._('School Period').'</legend>'.$periods.'</fieldset></TD>
				<TD><fieldset><legend>'._('Teacher Name').'</legend>'.$teachers.'</fieldset></TD>
				<TD><fieldset><legend>'._('School Term').'</legend>'.$school_terms.'</fieldset></TD>
				<TD><INPUT type=submit value='._('Search').'></TD></TR>
				</TABLE>';
			if(!$errors) $contents .= $list;
			
			if(get_user('PROFILE')=='student')
				$title = _('Course Registration: Search for a Course to Add');
			else
				$title = _('Search for a course section to add');
			
			echo '<A style="text-decoration:none;" name=search_block>';
			DisplayBlock($title,$contents);
			echo '</A>';
			echo '<BR><BR>';

			// 			<TD align='.ALIGN_RIGHT.'>'._('Graduation Requirement').'</TD><TD>'.$grad_subjects.'</TD>
		}
		echo '</FORM>';
	}

	if(AllowEdit() && get_user('PROFILE')=='admin' && $_REQUEST['servicemod']!='mod_curriculum/ScdPRStudSchedWorkspace.php' && $_REQUEST['servicefunction']!='reg_search' && $_REQUEST['servicefunction']!='insert_course')
	{
		$old_REQUEST = array('CREATEPDF'=>$_REQUEST['CREATEPDF']);
		unset($_REQUEST);
		$_REQUEST = $old_REQUEST;
		$_REQUEST['servicemod'] = 'mod_curriculum/Curriculum.php';
		$_REQUEST['stuid'] = get_student_id();
		$_REQUEST['search_servicefunction'] = 'list';

		$addition['link']['COURSE']['link'] = "modloader.php?servicemod=$_REQUEST[servicemod]&servicefunction=choose_course&useontop=false";
		$addition['link']['COURSE']['variables'] = array('subject_id'=>'SUBJECT_ID','course_id'=>'COURSE_ID','course_credits'=>'COURSE_CREDIT_TITLE');
		$addition['link']['COURSE']['js'] = true;

		$list_PHP_SELF = $_SESSION['List_PHP_SELF'];
		include($staticpath.'modules/mod_curriculum/ScdReqUnActList.php');
		$_SESSION['List_PHP_SELF'] = $list_PHP_SELF;
	}
}

?>