<?php

function _makeNextSchool($value,$column)
{	global $THIS_array,$_SYSTEM,$html_field_name,$student_id_field;

	$values[get_school_id()] = _('Next Class Level at Current School');
	$values['0'] = _('Retain');
	$values['-1'] = _('Do not register in for the next school year');
	if(!$_SYSTEM['_makeNextSchool']['schools_array'])
		$_SYSTEM['_makeNextSchool']['schools_array'] = db_request(db_execute("SELECT ID,TITLE FROM SCHOOLS ORDER BY TITLE"));
	foreach($_SYSTEM['_makeNextSchool']['schools_array'] as $school)
	{
		if($school['ID']!=get_school_id())
			$values[$school['ID']] = $school['TITLE'];
	}

	return SelectInput($value,'student_registration'.'['.$THIS_array[$student_id_field].']['.$column.']','',$values,$allow_na,$addition,'force');

}

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

	if(!$calendars_array)
		$calendars_array = db_request(db_execute("SELECT CALENDAR_ID,DEFAULT_CALENDAR,TITLE FROM SCHOOL_CALENDARS WHERE SCHOOL_YEAR='".get_school_year()."'"),array(),array('CALENDAR_ID'));

	return $calendars_array[$value][1]['TITLE'];
}

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

	$column = explode('_',strtolower($column));
	if($THIS_array['ADDRESS_ID'])
		$record = $contacts_array[$THIS_array['STUDENT_ID']][$THIS_array['ADDRESS_ID']];
	else
		$record = $contacts_array[$THIS_array['STUDENT_ID']];

	if($record[$column[0]])
	{
		if($column[1]=='name')
			return $record[$column[0]][1]['NAME'];
		if($column[1]=='home')
			return $record[$column[0]][1]['PHONE'];
		if($column[1]=='email' && $record[$column[0]][1]['EMAIL'])
			return $record[$column[0]][1]['EMAIL'];
		if($column[1]=='studentrelation')
			return $record[$column[0]][1]['STUDENT_RELATION'];
		if($column[1]=='custody')
			return $record[$column[0]][1]['CUSTODY'];
		if($column[1]=='emergency')
			return $record[$column[0]][1]['EMERGENCY'];
		if($column[1]=='address')
			return $record[$column[0]][1]['ADDRESS'];
		if($column[1]=='city')
			return $record[$column[0]][1]['CITY'];
		if($column[1]=='state')
			return $record[$column[0]][1]['STATE'];
		if($column[1]=='zipcode')
			return $record[$column[0]][1]['ZIPCODE'];
		if($column[1]=='homephone')
			return $record[$column[0]][1]['HOMEPHONE'];
			
		foreach($record[$column[0]] as $info)
		{
			if(strpos($info['TITLE'],$column[1])===0 && $info['VALUE'])
				return $info['VALUE'];
		}
		// we should only reach here if the parent exists, but the contact info requested doesn't
		return;
	}
	// there isn't a contact called Father / Dad ... so, return any contact called parent instead
	if(($column[0]=='father' || $column[0]=='mother'))
	{
		if(!$record['parent']) $record['parent'] = array();
		foreach($record['parent'] as $i=>$info)
		{
			$return = false;
			if($column[1]=='name')
				$return = $record['parent'][$i]['NAME'];
			if($column[1]=='home')
				$return = $record['parent'][$i]['PHONE'];
			if($column[1]=='email')
				$return = $record['parent'][$i]['EMAIL'];
			if($column[1]=='studentrelation')
				$return = $record['parent'][$i]['STUDENT_RELATION'];
			if($column[1]=='custody')
				$return = $record['parent'][$i]['CUSTODY'];
			if($column[1]=='emergency')
				$return = $record['parent'][$i]['EMERGENCY'];
			if($column[1]=='address')
				$return = $record['parent'][$i]['ADDRESS'];
			if($column[1]=='city')
				$return = $record['parent'][$i]['CITY'];
			if($column[1]=='state')
				$return = $record['parent'][$i]['STATE'];
			if($column[1]=='zipcode')
				$return = $record['parent'][$i]['ZIPCODE'];
			if($column[1]=='homephone')
				$return = $record['parent'][$i]['HOMEPHONE'];

			if(strpos($info['TITLE'],$column[1])===0 && $info['VALUE'])
				$return = $info['VALUE'];

			if($return)
			{
				// this contact has already been used by the other parent ... 
				if(($THIS_array[$column[0]] && $THIS_array[$column[0]]!=$info['PERSON_ID']) || ($column[0]=='father' && $THIS_array['mother']==$info['PERSON_ID']) || ($column[0]=='mother' && $THIS_array['father']==$info['PERSON_ID']))
					continue;
				// set the person_id of the contact for this parent (either mother or father) ... this will be reset each time $THIS_array is reset
				$THIS_array[$column[0]] = $info['PERSON_ID'];
				return $return;
			}
		}

		// the parent doesn't exist, or the contact info requested doesn't
		return;
	}
	// this is the 4th contact or there isn't a contact that starts with Emergency ... so, return any other contact instead
	if($column[0]=='emergency' || $column[0]=='contact')
	{
		if(!$record['other']) $record['other'] = array();
		foreach($record['other'] as $i=>$info)
		{
			$return = false;
			if($column[1]=='name')
				$return = $record['other'][$i]['NAME'];
			if($column[1]=='home')
				$return = $record['other'][$i]['PHONE'];
			if($column[1]=='email')
				$return = $record['other'][$i]['EMAIL'];
			if($column[1]=='studentrelation')
				$return = $record['other'][$i]['STUDENT_RELATION'];
			if($column[1]=='custody')
				$return = $record['other'][$i]['CUSTODY'];
			if($column[1]=='emergency')
				$return = $record['other'][$i]['EMERGENCY'];
			if($column[1]=='address')
				$return = $record['other'][$i]['ADDRESS'];
			if($column[1]=='city')
				$return = $record['other'][$i]['CITY'];
			if($column[1]=='state')
				$return = $record['other'][$i]['STATE'];
			if($column[1]=='zipcode')
				$return = $record['other'][$i]['ZIPCODE'];
			if($column[1]=='homephone')
				$return = $record['other'][$i]['HOMEPHONE'];

			if(strpos($info['TITLE'],$column[1])===0 && $info['VALUE'])
				$return = $info['VALUE'];
			if($return)
			{
				// this contact has already been used by the other contact ... 
				if(($THIS_array[$column[0]] && $THIS_array[$column[0]]!=$info['PERSON_ID']) || ($column[0]=='emergency' && $THIS_array['contact']==$info['PERSON_ID']) || ($column[0]=='contact' && $THIS_array['emergency']==$info['PERSON_ID']))
					continue;
				// set the person_id of the contact for this parent (either emergency or other) ... this will be reset each time $THIS_array is reset
				$THIS_array[$column[0]] = $info['PERSON_ID'];
				return $return;
			}
		}
		/*
		// if there is no emergency contact or other contact, look for more parents
		if(!$THIS_array[$column[0]])

		*/
		// the contact doesn't exist, or the contact info requested doesn't
		return;
	}

	// we should never reach this point
	return ;
}

function _runCalc($value,$column)
{	global $row,$_SYSTEM,$num,$_runCalc_num;

	if(!isset($num))
		$num = 0;
	if(!isset($_runCalc_num))
		$_runCalc_num = $num;

	$_runCalc_start_REQUEST = $_REQUEST;
	$row++;
	if(!$_SYSTEM['Calc'.substr($column,12)])
	{
		$url_array = db_request(db_execute("SELECT URL FROM INFO_SAVES WHERE ID='".substr($column,12)."'"));
		$url = $url_array[1]['URL'];
		$url = urldecode($url);
		$vars = substr($url,(strpos($url,'?')+1));
		$servicemod = substr($url,0,strpos($url,'?'));
		
		$vars = str_replace('&amp;','&',$vars);
		$vars = explode('&',$vars);
		$_REQUEST = array();
		foreach($vars as $code)
		{
			$equals = strpos($code,'=');
	
			if(strpos($code,'[')!==false)
				$code = "\$_REQUEST[".ereg_replace('([^]])\[','\1][',substr($code,0,$equals))."='".substr($code,$equals+1)."';";
			else
				$code = "\$_REQUEST['".substr($code,0,$equals)."']='".substr($code,$equals+1)."';";
			eval($code);
		}
		$_SYSTEM['Calc'.substr($column,12)] = $_REQUEST;
	}
	else
		$_REQUEST = $_SYSTEM['Calc'.substr($column,12)];

	for($i=1;$i<=15;$i++)
	{
		$_REQUEST['screen'][$i]['stuid'] = $value;
	}
	$num = $_runCalc_num;
	// so Calculations.php doesn't include the functions within this function
	$_REQUEST['servicefunction'] = 'mod_portal/ExternalLinker.php';
	$_REQUEST['servicefunction'] = 'echoXMLHttpRequest';
	$return = include("modules/mod_savedinfo/SInfoCalculations.php");
	$_REQUEST = $_runCalc_start_REQUEST;
	
	if(!isset($_SYSTEM['_runCalc_max'][$column]) || $_SYSTEM['_runCalc_max'][$column]<$return)
		$_SYSTEM['_runCalc_max'][$column] = $return;
	
	return $return;
}

function _createGraphs(& $array)
{	global $_SYSTEM,$calculations_array;

	$last = count($array);
	for($i=1;$i<=$last;$i++)
	{
		foreach($calculations_array as $calc)
		{
			if($_REQUEST['fields']['GRAPH_'.$calc['ID']]=='Y')
			{
				$scale = (100/$_SYSTEM['_runCalc_max']['CALCULATION_'.$calc['ID']]);
				//$array[$i]['GRAPH_'.$calc['ID']] = '<!--'.((int) ($array[$i]['CALCULATION_'.$calc['ID']]*$scale)) . '--><IMG SRC=images/pixel_grey.gif class=GridOutput_fieldint width=' . ((int) ($array[$i]['CALCULATION_'.$calc['ID']]*$scale)) . ' height=10> '.$array[$i]['CALCULATION_'.$calc['ID']];
				$array[$i]['GRAPH_'.$calc['ID']] = '<IMG SRC=images/pixel_grey.gif class=GridOutput_fieldint width=' . ((int) ($array[$i]['CALCULATION_'.$calc['ID']]*$scale)) . ' height=10> '.$array[$i]['CALCULATION_'.$calc['ID']];
			}
		}
	}
}

function _makeTextInput($value,$column)
{	global $THIS_array,$html_field_name,$html_log_entries_name,$student_id_field, $border, $editRules, $forceFieldName;

	if(substr($column,'0','3')=='LOG' && $_REQUEST['logging_field'])
		$name = $html_log_entries_name.'['.$THIS_array[$student_id_field].']['.$column.']';
	else
		$name = $html_field_name.'['.$THIS_array[$student_id_field].']['.$column.']';

	$req = array($column => $value);
	
	_setSessionCustomValuesArray();
	$errorStr = _chkEditRules($req, $html_field_name, $editRules, $html_field_name.'['.$THIS_array[$student_id_field].']');
	
	if($errorStr['override_error'][0] or $errorStr['err'][0] || ($fields_array[substr($column,7)][1]['REQUIRED']=='Y' && !$value))
		$border[] = $name;	

	return TextInput($value,$name,'','','force');
}

function _makeSelectInput($value,$column)
{	global $THIS_array,$fields_array,$html_field_name,$student_id_field, $border, $editRules;

	$select_options = str_replace("\n","\r",str_replace("\r\n","\r",$fields_array[substr($column,7)][1]['SELECT_OPTIONS']));
	$select_options = explode("\r",$select_options);
	if(count($select_options))
	{
		foreach($select_options as $option)
			$options[$option] = $option;
	}

	if($fields_array[substr($column,7)][1]['REQUIRED']!='Y')
		$allow_na = _('N/A');
	else
		$allow_na = false;	

	$req = array($column => $value);
	_setSessionCustomValuesArray();
	$errorStr = _chkEditRules($req, $html_field_name, $editRules, $html_field_name.'['.$THIS_array[$student_id_field].']');
	
	if($errorStr['override_error'][0] || $errorStr['err'][0] || ($fields_array[substr($column,7)][1]['REQUIRED']=='Y' && !$value))
		$border[] = $html_field_name.'['.$THIS_array[$student_id_field].']['.$column.']';	

	$addition = 'style="max-width:250;"';
	return SelectInput($value,$html_field_name.'['.$THIS_array[$student_id_field].']['.$column.']','',$options,$allow_na,$addition,'force');
}

function _create_select_box($value,$column)
{	global $THIS_array,$fields_array,$html_field_name,$student_id_field, $border, $editRules;

	$select_options = str_replace("\n","\r",str_replace("\r\n","\r",$fields_array[substr($column,7)][1]['SELECT_OPTIONS']));
	$select_options = explode("\r",$select_options);
	if(count($select_options))
	{
		foreach($select_options as $option)
			$options[$option] = $option;
	}

	if($fields_array[substr($column,7)][1]['REQUIRED']!='Y')
		$allow_na = _('N/A');
	else
		$allow_na = false;	

	$req = array($column => $value);
	_setSessionCustomValuesArray();
	$errorStr = _chkEditRules($req, $html_field_name, $editRules, $html_field_name.'['.$THIS_array[$student_id_field].']');
	
	if($errorStr['override_error'][0] || $errorStr['err'][0] || ($fields_array[substr($column,7)][1]['REQUIRED']=='Y' && !$value))
		$border[] = $html_field_name.'['.$THIS_array[$student_id_field].']['.$column.']';	

	$addition = 'style="max-width:250;"';
	return make_select_box($value,$html_field_name.'['.$THIS_array[$student_id_field].']['.$column.']','',$options,$allow_na,$addition,'force');
}

function _makeMultipleInput($value,$column)
{	global $THIS_array,$fields_array,$html_field_name,$student_id_field, $border, $editRules, $advRep;

	$select_options = str_replace("\n","\r",str_replace("\r\n","\r",$fields_array[substr($column,7)][1]['SELECT_OPTIONS']));
	$select_options = explode("\r",$select_options);
	if(count($select_options))
	{
		foreach($select_options as $option)
			$options[$option] = $option;
	}

	if($fields_array[substr($column,7)][1]['REQUIRED']!='Y')
		$allow_na = _('N/A');
	else
		$allow_na = false;	

	_setSessionCustomValuesArray();
	$advRep = $html_field_name.'['.$THIS_array[$student_id_field].']['.$column.']';	
	
	$addition = 'style="max-width:250;"';
	return SelectMultipleInput($value,$html_field_name.'['.$THIS_array[$student_id_field].']['.$column.']','',$options,$allow_na,$addition,'force');
}

function _makeCheckboxInput($value,$column)
{	global $THIS_array,$fields_array,$html_field_name,$student_id_field, $border, $editRules, $advRep;
	
	$name = $html_field_name.'['.$THIS_array[$student_id_field].']['.$column.']';
	_setSessionCustomValuesArray();
	$advRep = $name;	
	
	return CheckboxInput($value,$name,'','',false);
}

function _makeDateInput($value,$column)
{	global $THIS_array,$fields_array,$html_field_name,$student_id_field, $border, $editRules;

	$req = array($column => $value);
	_setSessionCustomValuesArray();
	$errorStr = _chkEditRules($req, $html_field_name, $editRules, $html_field_name.'['.$THIS_array[$student_id_field].']');
	
	if($errorStr['override_error'][0] || $errorStr['err'][0] || ($fields_array[substr($column,7)][1]['REQUIRED']=='Y' && !$value))
		$border[] = $html_field_name.'['.$THIS_array[$student_id_field].']['.$column.']';	

	return DateInput($value,$html_field_name.'['.$THIS_array[$student_id_field].']['.$column.']',null,'force');
}

function _getRegistrationCode($id,$column='TITLE')
{	global $_SYSTEM;
	
	if($column!='TITLE' && $column!='SHORT_NAME' && $column!='TYPE')
		$column = 'TITLE';

	if(!$_SYSTEM['_getRegistrationCode'])
	{
		$QI=db_execute("SELECT ID,TITLE,SHORT_NAME,TYPE FROM STUDENT_REGISTRATION_SETTINGS WHERE SCHOOL_YEAR='".get_school_year()."'");
		$_SYSTEM['_getRegistrationCode'] = db_request($QI,array(),array('ID'));
	}

	return $_SYSTEM['_getRegistrationCode'][$id][1][$column];
}

function _makeAttDaysPres($null,$column)
{	global $THIS_array;

	if($column=='ATT_DAYS_PRES')
		return $THIS_array['ATT_DAYS_ENROLLED'] - $THIS_array['ATT_DAYS_ABS'];
	elseif($column=='ATT_QTR_DAYS_PRES')
		return $THIS_array['ATT_QTR_DAYS_ENROLLED'] - $THIS_array['ATT_QTR_DAYS_ABS'];
}

function _makeAttTotal($null,$column)
{	global $THIS_array,$_SYSTEM;

	if($_SYSTEM['array_'.$column][$THIS_array['STUDENT_ID']][1]['ATT_SUM'])
		return str_replace('.0','',$_SYSTEM['array_'.$column][$THIS_array['STUDENT_ID']][1]['ATT_SUM']);
	else
		return '0';
}

function _makeTextareaInput($value,$column)
{	
	//die('jjiiiiiiijij');
	global $THIS_array,$html_field_name,$student_id_field, $border, $editRules;
	$name = $html_field_name.'['.$THIS_array[$student_id_field].']['.$column.']';
	//echo "hello";die;	
	$req = array($column => $value);
	_setSessionCustomValuesArray();
	$errorStr = _chkEditRules($req,  $html_field_name, $editRules, $html_field_name.'['.$THIS_array[$student_id_field].']');

	if($errorStr['override_error'][0] or $errorStr['err'][0])
			$style = 'class = errorTextField'; 	
		
	if(in_array($name, $border))
			$style = 'class = errorTextField'; 		
			
	if($style)
		$border[] = $name;
			
	return "<DIV id='div$name'><div id='innerdiv$name' $style ><span class='clickable'>".(($value!='')?"".str_replace("'","&rsquo;",$value)."":'<br>').'</span>'."</div></DIV>";		
}


function _chkEditRules($request, $borderName, $editRules, $borderPrefix = '')
{ 	global $border, $html_field_name;
	return $errorRulesArr = _executeEditRulesAndGetMsg($request, $borderName, $editRules, $borderPrefix);
}

function _setSessionCustomValuesArray()
{ 	global $THIS_array;
	
	if($THIS_array)	
	{	/*
			we need to set the $_SESSION["customValues"] values, for using the
			Edit Rules 
		*/
		foreach ($THIS_array as $key => $value)
		{
			$_SESSION["customValues"][$key] = $value;
		}
	}
}

function _showErrorValues($retArray, $columnNames, $htmlFieldName, $stud_id_name)
{ 	global $border, $advRep;

	asort($border);
	
	$newRetArray = array();
	$errStudIdArray = array();
	foreach($border as $redBorder)
	{
		$item = explode('][', $redBorder);
		
		$studId = str_replace($htmlFieldName.'[', '', $item[0]);
		$studId = str_replace(']','', $studId);
		
		/* if we have the student_id value */
		if($item[1])
		{
			$item[1] = str_replace(']','',$item[1]);
			if(array_key_exists($item[1], $columnNames))
				$errStudIdArray[] = $studId;
		}
	}
	/* array with student ids, which has the error fields */
	$errStudIdArray = array_unique($errStudIdArray);
	
	/*	make a new array with students information, instead of $array */
	foreach($retArray as $key => $value)
	{
		if(in_array($value[$stud_id_name], $errStudIdArray))
			$newRetArray[] = $retArray[$key];
	}
	asort($newRetArray);
	
	if(!empty($newRetArray))
		return $newRetArray;
	else 
		return $retArray;
}


function _make($value,$column)
{
	if(substr_count($value,'-')==2 && VerifyDate($value))
		$value = ProperDate($value);
	elseif(is_numeric($value))
		$value = ((strpos($value,'.')===false)?$value:rtrim(rtrim($value,'0'),'.'));
	return str_replace('||',',<BR>',trim($value,'|'));
}


?>