<?php
include_once($staticpath.'classes/InputButton.php');
$submitButton = new InputButton;

require_once ($staticpath."modules/mod_portal/date_to_ru.php");
$button = new Button();
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']--;
	if($_SESSION['AttdManagement.php']['date'] && $_SESSION['AttdManagement.php']['date']!=$date)
	{
		unset($_REQUEST['attendance']);
		unset($_REQUEST['attendance_day']);
	}
}
else
{
	$date = get_db_date();
	$_REQUEST['day_date'] = date('d');
	$_REQUEST['month_date'] = date('m');
	$_REQUEST['year_date'] = date('Y');
}
$day = date('D',mktime(0,0,0,(MonthNWSwitch($_REQUEST['month_date'],'tonum')*1),($_REQUEST['day_date']*1),$_REQUEST['year_date']));
/*
if (Preferences('LANGUAGE') == 'ru_RU')
{
    switch($day)
    {
	case 'Sun':
		$day = 'Вс';
	break;
	case 'Thu':
		$day = 'Чт';
	break;
	default:
//		$day = substr($day,0,2);
	    $day = change_date_ru('days_replace',$day);
	break;
    }
}
else
{
    switch($day)
    {
	case 'Sun':
	    $day = 'U';
	break;
	case 'Thu':
	    $day = 'H';
	break;
	default:
	    $day = substr($day,0,1);
	break;
    }
}
*/
if(!$_REQUEST['table'])
	$_REQUEST['table'] = '0';

if($_REQUEST['table']==0)
{
	$table = 'STUDENT_ATTENDANCE_PERIODS';
	$addition_sql = '';
}
else
{
	$table = 'LUNCH_PERIOD';
	$addition_sql = " AND TABLE_NAME='$_REQUEST[table]'";
}

$_SESSION['AttdManagement.php']['date'] = $date;
$current_array = db_request(db_execute("SELECT ATTENDANCE_TEACHER_CODE,ATTENDANCE_CODE,ATTENDANCE_REASON,STUDENT_ID,ADMIN,COURSE_SECTION_ID FROM $table WHERE SCHOOL_DATE='".$date."'".$addition_sql),array(),array('STUDENT_ID','COURSE_SECTION_ID'));
if($_REQUEST['attendance'] && $_POST['attendance'] && AllowEdit())
{
	foreach($_REQUEST['attendance'] as $student_id=>$values)
	{
		foreach($values as $period=>$columns)
		{
			if($current_array[$student_id][$period])
			{
				$sql = "UPDATE $table SET ADMIN='Y',";
				
				foreach($columns as $column=>$value)
					$sql .= $column."='".str_replace("\'","''",$value)."',";

				$sql = substr($sql,0,-1) . " WHERE SCHOOL_DATE='".$date."' AND COURSE_SECTION_ID='".$period."' AND STUDENT_ID='".$student_id."'".$addition_sql;
				db_execute($sql);
			}
			else
			{
				$school_period_id = db_request(db_execute("SELECT SCHOOL_PERIOD_ID FROM COURSE_SECTIONS WHERE COURSE_SECTION_ID='$period'"));
				$school_period_id = $school_period_id[1]['SCHOOL_PERIOD_ID'];

				$sql = "INSERT INTO $table ";
	
				$fields = 'STUDENT_ID,SCHOOL_DATE,SCHOOL_PERIOD_ID,SCHOOL_TERM_ID,COURSE_SECTION_ID,ADMIN,';
				$values = "'".$student_id."','".$date."','".$school_period_id."','".get_current_school_term('QTR',$date)."','".$period."','Y',";
				if($table=='LUNCH_PERIOD')
				{
					$fields .= 'TABLE_NAME,';
					$values .= "'".$_REQUEST['table']."',";
				}
				
				$go = 0;
				foreach($columns as $column=>$value)
				{
					if($value)
					{
						$fields .= $column.',';
						$values .= "'".str_replace("\'","''",$value)."',";
						$go = true;
					}
				}
				$sql .= '(' . substr($fields,0,-1) . ') values(' . substr($values,0,-1) . ')';
				
				if($go)
					db_execute($sql);
			}
		}
		UpdateAttendanceDaily($student_id,$date,($_REQUEST['attendance_day'][$student_id]['COMMENT']?$_REQUEST['attendance_day'][$student_id]['COMMENT']:false));
		unset($_REQUEST['attendance_day'][$student_id]);
	}
	$current_array = db_request(db_execute("SELECT ATTENDANCE_TEACHER_CODE,ATTENDANCE_CODE,ATTENDANCE_REASON,STUDENT_ID,ADMIN,COURSE_SECTION_ID FROM $table WHERE SCHOOL_DATE='".$date."'".$addition_sql),array(),array('STUDENT_ID','COURSE_SECTION_ID'));
	unset($_REQUEST['attendance']);
	unset($_SESSION['_REQUEST_vars']['attendance']);
	unset($_SESSION['_REQUEST_vars']['attendance_day']);
}
if($_REQUEST['attendance_day'])
{
	foreach($_REQUEST['attendance_day'] as $student_id=>$comment)
		UpdateAttendanceDaily($student_id,$date,$comment['COMMENT']);
	unset($_REQUEST['attendance_day']);
}

$codes_array = db_request(db_execute("SELECT ID,SHORT_NAME,TITLE FROM ATTENDANCE_CODES_SETTINGS WHERE SCHOOL_ID='".get_school_id()."' AND SCHOOL_YEAR='".get_school_year()."' AND TABLE_NAME='$_REQUEST[table]' ORDER BY SORT_ORDER,SHORT_NAME"));
$periods_array = db_request(db_execute("SELECT SCHOOL_PERIOD_ID,SHORT_NAME,TITLE FROM SCHOOL_PERIODS WHERE SCHOOL_ID='".get_school_id()."' AND SCHOOL_YEAR='".get_school_year()."' AND ATTENDANCE='Y' ORDER BY SORT_ORDER"));

if($_REQUEST['student_id'] && $_REQUEST['student_id']!='new')
{
	if(get_student_id() != $_REQUEST['student_id'])
	{
		$_SESSION['student_id'] = $_REQUEST['student_id'];
		if(!$_REQUEST['CREATEPDF'] && Preferences('MENU')=='Side')
			echo '<script language=JavaScript>parent.side.location="'.$_SESSION['Side_PHP_SELF'].'?modcat="+parent.side.document.forms[0].modcat.value;</script>';
	}
	$functions = array('ATTENDANCE_CODE'=>'_makeCodePulldown','ATTENDANCE_TEACHER_CODE'=>'_makeCode','ATTENDANCE_REASON'=>'_makeReasonInput');
//	echo "->".get_all_school_term('QTR',get_current_school_term('QTR',$date));

	$schedule_array = db_request(db_execute("SELECT 
				s.STUDENT_ID,c.TITLE ".CCAT."' - '".CCAT."s.COURSE_CREDIT_TITLE AS COURSE,cp.SCHOOL_PERIOD_ID,cp.COURSE_SECTION_ID,cp.TITLE AS PERIOD_TITLE,
				'' AS ATTENDANCE_CODE,'' AS ATTENDANCE_TEACHER_CODE,'' AS ATTENDANCE_REASON,cp.DAYS
					FROM 
				STUDENT_SCHEDULE s,COURSES c,COURSE_SECTIONS cp,SCHOOL_PERIODS p 
					WHERE 
				s.SCHOOL_YEAR='".get_school_year()."' AND s.SCHOOL_ID='".get_school_id()."' AND s.SCHOOL_TERM_ID IN (".get_all_school_term('QTR',get_current_school_term('QTR',$date)).")
				AND s.COURSE_ID=c.COURSE_ID 
				AND s.COURSE_SECTION_ID=cp.COURSE_SECTION_ID AND cp.SCHOOL_PERIOD_ID=p.SCHOOL_PERIOD_ID AND cp.DOES_ATTENDANCE='Y'
				AND s.STUDENT_ID='".$_REQUEST['student_id']."' AND ('$date' BETWEEN s.START_DATE AND s.END_DATE OR (s.END_DATE IS NULL AND '$date'>=s.START_DATE))
				ORDER BY p.SORT_ORDER"),$functions);
				
	$columns = array('PERIOD_TITLE'=>_('School Period - Days - Course Name - Teacher Name'),
			'COURSE'=>_('Course Title'),
			'ATTENDANCE_CODE'=>_('Attendance Code'),
			'ATTENDANCE_TEACHER_CODE'=>_('Attendance Code From Teacher'),
			'ATTENDANCE_REASON'=>_('Comments'));
	echo "<FORM action=modloader.php?servicemod=$_REQUEST[servicemod]&servicefunction=student&student_id=$_REQUEST[student_id] method=POST>";
	DisplayHeader(".:".ProgramTitle().":.");
	DisplayHeader(' &nbsp; &nbsp; <B>'._('Report Date').': </B>'.PrepareDate($date,'_date',false,array('submit'=>true)),$submitButton->createIButton(_('Update')));
	Gridoutput($schedule_array,$columns,_('Courses'),_('Amount of Courses'));
	echo '</FORM>';
}
else
{
	if($_REQUEST['customised_view']!='true')
        {
//            if($_REQUEST['state_value']=='0')
            {
//		$addition['WHERE'] = $addition2['WHERE'] = " AND EXISTS (SELECT '' FROM $table ap,STUDENT_ATTENDANCE_DAYS sad,ATTENDANCE_CODES_SETTINGS ac WHERE ap.SCHOOL_DATE='".$date."' AND ap.STUDENT_ID=sad.STUDENT_ID AND sad.STATE_VALUE=0.0 AND ap.ATTENDANCE_CODE=ac.ID AND ac.SCHOOL_ID=ssm.SCHOOL_ID AND ac.SCHOOL_YEAR=ssm.SCHOOL_YEAR ".str_replace('TABLE_NAME','ac.TABLE_NAME',$addition_sql);
//            }else{
                $addition['WHERE'] = $addition2['WHERE'] = " AND EXISTS (SELECT '' FROM $table ap,ATTENDANCE_CODES_SETTINGS ac WHERE ap.SCHOOL_DATE='".$date."' AND ap.STUDENT_ID=ssm.STUDENT_ID AND ap.ATTENDANCE_CODE=ac.ID AND ac.SCHOOL_ID=ssm.SCHOOL_ID AND ac.SCHOOL_YEAR=ssm.SCHOOL_YEAR ".str_replace('TABLE_NAME','ac.TABLE_NAME',$addition_sql);
            }
        }else{
		$addition['WHERE'] = " AND EXISTS (SELECT '' FROM $table ap,ATTENDANCE_CODES_SETTINGS ac WHERE ap.SCHOOL_DATE='".$date."' AND ap.STUDENT_ID=ssm.STUDENT_ID AND ap.ATTENDANCE_CODE=ac.ID AND ac.SCHOOL_ID=ssm.SCHOOL_ID AND ac.SCHOOL_YEAR=ssm.SCHOOL_YEAR ".str_replace('TABLE_NAME','ac.TABLE_NAME',$addition_sql);
        }
	if($_REQUEST['codes'])
	{
		$REQ_codes = $_REQUEST['codes'];
		foreach($REQ_codes as $key=>$value)
		{
			if(!$value)
				unset($REQ_codes[$key]);
			elseif($value=='A')
				$abs = true;
		
		}
	}
	else
		$abs = true;
	if($REQ_codes && !$abs)
	{
		$addition['WHERE'] .= "AND ac.ID IN (";
		foreach($REQ_codes as $code)
			$addition['WHERE'] .= "'".$code."',";
		if($_REQUEST['customised_view']!='true')
			$addition2['WHERE'] = $addition['WHERE'] = substr($addition['WHERE'],0,-1) . ')';
		else
			$addition['WHERE'] = substr($addition['WHERE'],0,-1) . ')';
	}
	elseif($abs)
	{
		$array = db_request(db_execute("SELECT ID FROM ATTENDANCE_CODES_SETTINGS WHERE SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."' AND (DEFAULT_CODE!='Y' OR DEFAULT_CODE IS NULL) AND TABLE_NAME='$_REQUEST[table]'"));
		if(count($array))
		{
			$addition['WHERE'] .= "AND ac.ID IN (";
			foreach($array as $code)
				$addition['WHERE'] .= "'".$code['ID']."',";
		
			if($_REQUEST['customised_view']!='true')
				$addition2['WHERE'] = $addition['WHERE'] = substr($addition['WHERE'],0,-1) . ')';	
			else
				$addition['WHERE'] = substr($addition['WHERE'],0,-1) . ')';
		}
	}
        if($_REQUEST['state_value']=='0')
        {
            $state_value = db_request(db_execute("SELECT STUDENT_ID FROM STUDENT_ATTENDANCE_DAYS WHERE SCHOOL_DATE='".$date."' AND STATE_VALUE=0.0"));
            if($state_value)
            {
                $addition['WHERE'] .= "AND ssm.STUDENT_ID IN (";

                foreach($state_value as $value)
                {
                    $addition['WHERE'] .= "'".$value['STUDENT_ID']."',";
                }
                $addition['WHERE'] = substr($addition['WHERE'],0,-1) . ')';
                unset($_REQUEST['state_value']);
            }
        }

	$addition['WHERE'] .= ')';

        // EXPANDED VIEW BREAKS THIS QUERY.  PLUS, PHONE IS ALREADY AN OPTION IN EXPANDED VIEW
	if($_REQUEST['customised_view']!='true' && $_REQUEST['CREATEPDF']!='true')
	{
		$addition2['WHERE'] .= ')';
		$addition2['SELECT_ONLY'] = 'ssm.STUDENT_ID,p.PERSON_ID,p.FIRST_NAME,p.LAST_NAME,sjp.STUDENT_RELATION,pjc.TITLE,pjc.VALUE,a.PHONE,p.EMAIL,sjp.ADDRESS_ID ';
		$addition2['FROM'] .= ',ADDRESS a,STUDENTS_IN_ADDRESS sja LEFT OUTER JOIN STUDENTS_IN_SR sjp ON (sja.STUDENT_ID=sjp.STUDENT_ID AND sja.ADDRESS_ID=sjp.ADDRESS_ID AND (sjp.CUSTODY=\'Y\' OR sjp.EMERGENCY=\'Y\')) LEFT OUTER JOIN STUDENT_RELATIONS p ON (p.PERSON_ID=sjp.PERSON_ID) LEFT OUTER JOIN STUDENT_RELATIONS_IN_CONTACTS pjc ON (pjc.PERSON_ID=p.PERSON_ID) ';
		$addition2['WHERE'] .= ' AND a.ADDRESS_ID=sja.ADDRESS_ID AND sja.STUDENT_ID=ssm.STUDENT_ID ';
		if($addition2['ORDER_BY'])
			$addition2['ORDER_BY'] .= ',';
		$addition2['ORDER_BY'] .= 'COALESCE(sjp.CUSTODY,\'N\') DESC';
		$addition2['group'] = array('STUDENT_ID','PERSON_ID');

		$contacts_array = get_student_list($addition2);
		$addition['columns_before']['PHONE'] = _('Contact Info');
	}
	
	// GET THE STATE VALUES & COMMENTS
	$addition2['ORDER_BY'] = '';
	$addition2['SELECT_ONLY'] = 'ssm.STUDENT_ID,ad.STATE_VALUE,ad.COMMENT';
	$addition2['FROM'] = $addition['FROM'] . ',STUDENT_ATTENDANCE_DAYS ad ';
	$addition2['WHERE'] = $addition['WHERE'] . " AND ad.STUDENT_ID=ssm.STUDENT_ID AND ad.SCHOOL_DATE='$date'";
	$addition2['group'] = array('STUDENT_ID');
	$daily_array = get_student_list($addition2);

	// GET THE COURSE_SECTION_ID OF EACH SECTION IN THE STUDENT'S STUDENT_SCHEDULE
	$addition2['ORDER_BY'] = '';
	$addition2['SELECT_ONLY'] = 'ssm.STUDENT_ID,cp.SCHOOL_PERIOD_ID,cp.COURSE_SECTION_ID';
	$addition2['FROM'] = $addition['FROM'] . ',STUDENT_SCHEDULE ss,COURSE_SECTIONS cp ';
	$addition2['WHERE'] = $addition['WHERE'] . " AND ss.STUDENT_ID=ssm.STUDENT_ID AND ss.SCHOOL_YEAR=ssm.SCHOOL_YEAR AND ss.SCHOOL_ID=ssm.SCHOOL_ID AND cp.COURSE_SECTION_ID = ss.COURSE_SECTION_ID AND cp.DOES_ATTENDANCE='Y' AND cp.DAYS LIKE '%$day%' AND ss.SCHOOL_TERM_ID IN (".get_all_school_term('QTR',get_current_school_term('QTR',$date,false)).") AND ('$date' BETWEEN ss.START_DATE AND ss.END_DATE OR (ss.END_DATE IS NULL AND '$date'>=ss.START_DATE))";
	$addition2['group'] = array('STUDENT_ID','SCHOOL_PERIOD_ID');
	$current_schedule_array = get_student_list($addition2);
	//$current_schedule_array[$THIS_array['STUDENT_ID']] = db_request(db_execute("SELECT cp.SCHOOL_PERIOD_ID,cp.COURSE_SECTION_ID FROM STUDENT_SCHEDULE s,COURSE_SECTIONS cp WHERE s.STUDENT_ID='".$THIS_array['STUDENT_ID']."' AND s.SCHOOL_YEAR='".get_school_year()."' AND s.SCHOOL_ID='".get_school_id()."' AND cp.COURSE_SECTION_ID = s.COURSE_SECTION_ID AND cp.DOES_ATTENDANCE='Y' AND cp.DAYS LIKE '%$day%' AND s.SCHOOL_TERM_ID IN (".get_all_school_term('QTR',get_current_school_term('QTR',$date)).") AND ('$date' BETWEEN s.START_DATE AND s.END_DATE OR (s.END_DATE IS NULL AND '$date'>=s.START_DATE)) ORDER BY s.START_DATE ASC"),array(),array('SCHOOL_PERIOD_ID'));

	
	$columns = array();
	$addition['SELECT'] .= ',NULL AS STATE_VALUE,NULL AS DAILY_COMMENT,NULL AS PHONE';
        $addition['functions']['PHONE'] = '_makePhone';
	$addition['functions']['STATE_VALUE'] = '_makeStateValue';
	$addition['functions']['DAILY_COMMENT'] = '_makeStateValue';
	if($_REQUEST['table']=='0' || !$_REQUEST['table'])
		$addition['columns_after']['STATE_VALUE'] = _('Attendance Status');
	$addition['columns_after']['DAILY_COMMENT'] = _('Comment');
	$addition['link']['FULL_NAME']['link'] = "modloader.php?servicemod=$_REQUEST[servicemod]&month_date=$_REQUEST[month_date]&day_date=$_REQUEST[day_date]&year_date=$_REQUEST[year_date]";
	$addition['link']['FULL_NAME']['variables'] = array('student_id'=>'STUDENT_ID');
	$addition['BackPrompt'] = false;
	$addition['Redirect'] = false;
	$addition['new'] = true;
	foreach($periods_array as $period)
	{
		$addition['SELECT'] .= ",'' AS PERIOD_".$period['SCHOOL_PERIOD_ID'];
		$addition['functions']['PERIOD_'.$period['SCHOOL_PERIOD_ID']] = '_makeCodePulldown';
		$addition['columns_after']['PERIOD_'.$period['SCHOOL_PERIOD_ID']] = $period['SHORT_NAME'];
	}
	$addition['DATE'] = $date;

	$tmp_REQUEST = $_REQUEST;
	unset($tmp_REQUEST['day_date']);unset($tmp_REQUEST['month_date']);unset($tmp_REQUEST['year_date']);unset($tmp_REQUEST['codes']);
	$action = SetRequestOptions($tmp_REQUEST);
	echo "<FORM action=$action method=POST>";
	DisplayHeader(".:".ProgramTitle().":.");
	
	if($REQ_codes)
	{
		foreach($REQ_codes as $code)
			$code_pulldowns .= _makeCodeSearch($code);
	}
	elseif($abs)
		$code_pulldowns = _makeCodeSearch('A');
	else
		$code_pulldowns = _makeCodeSearch();
	if(get_student_id())
		$current_student_link = _('Manage attendance for ')."<B><A HREF=modloader.php?servicemod=$_REQUEST[servicemod]&servicefunction=student&month_date=$_REQUEST[month_date]&day_date=$_REQUEST[day_date]&year_date=$_REQUEST[year_date]&student_id=".get_student_id().">"._('Current Student')."</A></B></TD><TD>";

	if(!$_REQUEST['CREATEPDF'])
		$add_button = button('add',_('Add another filter').'&nbsp;',"# onclick='javascript:addHTML(\"".str_replace('"','\"',_makeCodeSearch())."\",\"code_pulldowns\"); return false;'");
//	DisplayHeader(_('Choose a date to manage attendance ').PrepareDate($date,'_date',false,array('submit'=>true)),$current_student_link,'<TABLE border="0"><TR><TD>'.
//		    $add_button.'</TD><TD><DIV id=code_pulldowns>'.$code_pulldowns.'</DIV></TD><TD> &nbsp; &nbsp; </TD><TD>'.$submitButton->createIButton(_('OK')).'</TD></TR></TABLE>');
//	$_REQUEST['DrawAlign'] = 'LEFT';
//	DisplayHeader(_('Choose a date to manage attendance ').PrepareDate($date,'_date',false,array('submit'=>true)),$current_student_link);
	echo '<TABLE width=100%><TR><TD align=center>'._('Choose a date to manage attendance ').PrepareDate($date,'_date',false,array('submit'=>false,'format'=>'postgres')).'</TD></TR></TABLE>';
	echo '<TABLE align=right><TR><TD align=right>'.$current_student_link.'</TD></TR></TABLE>';
	echo '<TABLE border="0"><TR><TD>'.$add_button.'</TD><TD><DIV id=code_pulldowns>'.$code_pulldowns.'</DIV></TD><TD> &nbsp; &nbsp; </TD><TD>'.$submitButton->createIButton(_('Update')).'</TD></TR></TABLE>';
//	unset($_REQUEST['DrawAlign']);
//		$add_button = button('add',_('Add another filter').'&nbsp;',"# onclick='javascript:addHTML(\"".str_replace('"','\"',_makeCodeSearch())."\",\"code_pulldowns\"); return false;'");
//		$add_button = button('add','',"# onclick='javascript:addHTML(\"".str_replace('"','\"',_makeCodeSearch())."\",\"code_pulldowns\"); return false;'");
	//DisplayHeader(PrepareDate($date,'_date',false,array('submit'=>true)),'<TABLE><TR><TD>'.$current_student_link.$add_button.'</TD><TD><DIV id=code_pulldowns>'.$code_pulldowns.'</DIV></TD><TD> &nbsp; &nbsp; </TD><TD>'.$submitButton->createIButton(_('Update')).'</TD></TR></TABLE>');
//	echo '<TABLE align=center border="1"><TR><TD>'._('Choose a date to manage attendance ').PrepareDate($date,'_date',false,array('submit'=>true)).'</TD></TR><TR><TD COLSPAN=2>'._('Choose a filter by the short name of attendance code').'&nbsp;'.$code_pulldowns.'&nbsp; &nbsp;'.$add_button.''.$submitButton->createIButton(_('OK')).$current_student_link.'</TD></TR></TABLE>';
	$categories_array = db_request(db_execute("SELECT ID,TITLE FROM ATTENDANCE_CODE_CATS_SETTINGS WHERE SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."'"));
	$tmp_REQUEST = $_REQUEST;
	unset($tmp_REQUEST['table']);unset($tmp_REQUEST['codes']);

	$tmp_PHP_SELF = SetRequestOptions($tmp_REQUEST);
	if(count($categories_array))
	{
		if($_REQUEST['table']!=='0')
			$header .= $button->createText(_('Attendance'),$tmp_PHP_SELF.'&amp;table=0');
		else
			$header .= $button->createButton(_('Attendance'),$tmp_PHP_SELF.'&amp;table=0');

		foreach($categories_array as $category)
		{
			if($_REQUEST['table']!==$category['ID'])
				$header .= $button->createText($category['TITLE'],$tmp_PHP_SELF.'&amp;table='.$category['ID']);
			else
				$header .= $button->createButton($category['TITLE'],$tmp_PHP_SELF.'&amp;table='.$category['ID']);
		}
		echo '<table align=center width=30%><tr><td>'.TabsHeader($header).'</td></tr></table>';
	}
	echo '<HR>';
	$addition['tabs_header'] = false; // this is needed because the "Search" tab wasn't working
	$_REQUEST['search_servicefunction'] = 'list';
	Search('student_id',$addition);
	echo '<HR>';
	echo '<BR><CENTER>'.$submitButton->createIButton(_('Update')).'</CENTER>';
	echo "</FORM>";
}

function _makePhone($value,$column)
{	global $THIS_array,$contacts_array;

	if(count($contacts_array[$THIS_array['STUDENT_ID']]))
	{
		foreach($contacts_array[$THIS_array['STUDENT_ID']] as $person)
		{
			if($person[1]['FIRST_NAME'] || $person[1]['LAST_NAME'])
				$tipmessage .= '<B>'.$person[1]['STUDENT_RELATION'].': '.$person[1]['FIRST_NAME'].' '.$person[1]['LAST_NAME'].'</B><BR>';
			$tipmessage .= '<TABLE>';
			if($person[1]['PHONE'])
				$tipmessage .= '<TR><TD align='.ALIGN_RIGHT.'><font color=gray size=1 face=Verdana,Arial,Helvetica>'._('Home Phone').'</font> </TD><TD><font size=1 face=Verdana,Arial,Helvetica>'.$person[1]['PHONE'].'</font></TD></TR>';
			if($person[1]['EMAIL'])
				$tipmessage .= '<TR><TD align='.ALIGN_RIGHT.'><font color=gray size=1 face=Verdana,Arial,Helvetica>'._('Email').'</font> </TD><TD><font size=1 face=Verdana,Arial,Helvetica>'.$person[1]['EMAIL'].'</font></TD></TR>';
			foreach($person as $info)
			{
				if($info['TITLE'] || $info['VALUE'])
					$tipmessage .= '<TR><TD align='.ALIGN_RIGHT.'><font color=gray size=1 face=Verdana,Arial,Helvetica>'.$info['TITLE'].'</font></TD><TD><font size=1 face=Verdana,Arial,Helvetica>'.$info['VALUE'].'</font></TD></TR>';
			}
			$tipmessage .= '</TABLE>';
		}
	}
	else
		$tipmessage = _('This student has no contact information.');
	return button('phone','','# onclick=\'location.href="modloader.php?servicemod=mod_students/Students.php&include=stuaddresstab&category_id=3&student_id='.$THIS_array['STUDENT_ID'].'"\' onMouseOver=\'stm(["'._('Contact Information').'","'.str_replace("'","&rsquo;",$tipmessage).'"],["white","#333366","","","",,"black","#e8e8ff","","","",,,,2,"#333366",2,,,,,"",,,,]);\' onMouseOut=\'htm()\'',20);
}

function _makeCodePulldown($value,$title)
{	global $THIS_array,$codes_array,$current_array,$current_schedule_array,$date,$day;

	if(!is_array($current_schedule_array[$THIS_array['STUDENT_ID']]))
	{
		$current_schedule_array[$THIS_array['STUDENT_ID']] = db_request(db_execute("SELECT cp.SCHOOL_PERIOD_ID,cp.COURSE_SECTION_ID FROM STUDENT_SCHEDULE s,COURSE_SECTIONS cp WHERE s.STUDENT_ID='".$THIS_array['STUDENT_ID']."' AND s.SCHOOL_YEAR='".get_school_year()."' AND s.SCHOOL_ID='".get_school_id()."' AND cp.COURSE_SECTION_ID = s.COURSE_SECTION_ID AND cp.DOES_ATTENDANCE='Y' AND cp.DAYS LIKE '%$day%' AND s.SCHOOL_TERM_ID IN (".get_all_school_term('QTR',get_current_school_term('QTR',$date)).") AND ('$date' BETWEEN s.START_DATE AND s.END_DATE OR (s.END_DATE IS NULL AND '$date'>=s.START_DATE)) ORDER BY s.START_DATE ASC"),array(),array('SCHOOL_PERIOD_ID'));
		if(!$current_schedule_array[$THIS_array['STUDENT_ID']])
			$current_schedule_array[$THIS_array['STUDENT_ID']] = array();
	}
	if($THIS_array['COURSE'])
	{
		$period = $THIS_array['COURSE_SECTION_ID'];
		$school_period_id = $THIS_array['SCHOOL_PERIOD_ID'];
		
		foreach($codes_array as $code)
			$options[$code['ID']] = $code['TITLE'];
	}
	else
	{
		$school_period_id = substr($title,7);
		$period = $current_schedule_array[$THIS_array['STUDENT_ID']][$school_period_id][1]['COURSE_SECTION_ID'];
		
		foreach($codes_array as $code)
			$options[$code['ID']] = $code['SHORT_NAME'];	
	}
	
	$val = $current_array[$THIS_array['STUDENT_ID']][$period][1]['ATTENDANCE_CODE'];

	if($current_schedule_array[$THIS_array['STUDENT_ID']][$school_period_id])
		return SelectInput($val,'attendance['.$THIS_array['STUDENT_ID'].']['.$period.'][ATTENDANCE_CODE]','',$options,'','','force');
	else
		return false;
}

function _makeCode($value,$title)
{	global $THIS_array,$codes_array,$current_array;

	foreach($codes_array as $code)
	{
		if($current_array[$THIS_array['STUDENT_ID']][$THIS_array['COURSE_SECTION_ID']][1]['ATTENDANCE_TEACHER_CODE']==$code['ID'])
			return $code['TITLE'];
	}
}

function _makeReasonInput($value,$title)
{	global $THIS_array,$codes_array,$current_array;

	$val = $current_array[$THIS_array['STUDENT_ID']][$THIS_array['COURSE_SECTION_ID']][1]['ATTENDANCE_REASON'];

	return TextInput($val,'attendance['.$THIS_array['STUDENT_ID'].']['.$THIS_array['COURSE_SECTION_ID'].'][ATTENDANCE_REASON]','','','force');
}

function _makeCodeSearch($value='')
{	global $codes_array,$code_search_selected;

	$return = '<SELECT name=codes[]><OPTION value="">'._('All').'</OPTION><OPTION value="A"'.(($value=='A')?' SELECTED':'').'>NP</OPTION>';
	if(count($codes_array))
	{
		foreach($codes_array as $code)
		{
			if($value==$code['ID'])
				$return .= "<OPTION value=$code[ID] SELECTED>$code[SHORT_NAME]</OPTION>";
			else
				$return .= "<OPTION value=$code[ID]>$code[SHORT_NAME]</OPTION>";
		}
	}
	$return .= '</SELECT>';
	
	return $return;
}

function _makeStateValue($value,$name)
{	global $THIS_array,$date,$daily_array;
	
	//$value = db_request(db_execute("SELECT STATE_VALUE,COMMENT FROM STUDENT_ATTENDANCE_DAYS WHERE STUDENT_ID='$THIS_array[STUDENT_ID]' AND SCHOOL_DATE='$date'"));
	$value = $daily_array[$THIS_array['STUDENT_ID']];
	if($name=='STATE_VALUE')
	{
		$value  = $value[1]['STATE_VALUE'];

		if($value=='0.0')
			return _('None');
		elseif($value=='.5')
			return _('Half-Day');
		else
			return _('Full-Day');
	}
	else
		return TextInput($value[1]['COMMENT'],'attendance_day['.$THIS_array['STUDENT_ID'].'][COMMENT]','','','force');
}
?>