<?php
$html_field_name='students';
$email_field = 'CFIELD_50012';
$plural = "students";

if(!isset($_REQUEST['CREATEPDF']))
{
    DisplayHeader(".:".ProgramTitle().":.");
}

$addition['second_col'] .= '<fieldset style="border:1px solid gray;"><legend>'._('Include in Year Report Card').'</legend><TABLE cellspasing=0>';

$addition['second_col'] .= '<TR><TD>';
	$addition['second_col'] .= '<INPUT type=checkbox name=elements[course_rank] id=elements[course_rank] value=Y><label for=elements[course_rank]>'._('Course Rank').'</label></TD><TD>';
	$addition['second_col'] .= '<INPUT type=checkbox name=elements[comments] id=elements[comments] value=Y><label for=elements[comments]>'._('Comments').'</label></TD>';
	$addition['second_col'] .= '</TR><TR>';
	$addition['second_col'] .= 'Report time (in years): <SELECT name=year_range>';
	for($i=1;$i<7;$i++)
	{
		$addition['second_col'] .= '<option value="'.$i.'">'.$i.'</option>';
	}
	$addition['second_col'] .= '</SELECT>';
	$addition['second_col'] .= '</TR></TABLE>';
$periods_array = db_request(db_execute("SELECT SCHOOL_PERIOD_ID,SHORT_NAME,TITLE FROM SCHOOL_PERIODS WHERE SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."' ORDER BY SORT_ORDER,TITLE"));
$addition['second_col'] .= '<script language=javascript>
	function doSortingOnChange(select)
	{
		if(select.options[select.selectedIndex].value!="student")
			document.getElementById("sort_teacher_checkbox_div").style.display="block";
		else
			document.getElementById("sort_teacher_checkbox_div").style.display="none";		
	}
</script>';
$addition['second_col'] .= '</fieldset>';
$class_array = db_request(db_execute("SELECT * FROM SCHOOL_CLASSLEVELS WHERE SCHOOL_ID=".get_school_id()." ORDER BY SORT_ORDER"));
$ygr_array = db_request(db_execute("SELECT * FROM YEAR_GRADE_REPORT"),array(),array('CLASSLEVEL_ID'));
//$year_array = db_request(db_execute("SELECT * FROM SCHOOL_YEARS WHERE SCHOOL_ID=".get_school_id()." AND SCHOOL_YEAR=".get_school_year()));
//$semester_array = db_request(db_execute("SELECT * FROM SCHOOL_SEMESTERS WHERE SCHOOL_ID=".get_school_id()." AND SCHOOL_YEAR=".get_school_year()." ORDER BY SHORT_NAME"));
$school_terms_array = db_request(db_execute("SELECT SCHOOL_TERM_ID,SCHOOL_YEAR,SHORT_NAME,TITLE,SORT_ORDER FROM SCHOOL_YEARS WHERE SCHOOL_ID='".get_school_id()."' AND SCHOOL_YEAR=".get_school_year()." UNION
	                    SELECT SCHOOL_TERM_ID,SCHOOL_YEAR,SHORT_NAME,TITLE,SORT_ORDER FROM SCHOOL_SEMESTERS WHERE SCHOOL_ID='".get_school_id()."' AND SCHOOL_YEAR=".get_school_year()." UNION
	            	    SELECT SCHOOL_TERM_ID,SCHOOL_YEAR,SHORT_NAME,TITLE,SORT_ORDER FROM SCHOOL_QUARTERS WHERE SCHOOL_ID='".get_school_id()."' AND SCHOOL_YEAR=".get_school_year()." UNION
	        	    SELECT SCHOOL_TERM_ID,SCHOOL_YEAR,SHORT_NAME,TITLE,SORT_ORDER FROM SCHOOL_WEEKS WHERE SCHOOL_ID='".get_school_id()."' AND SCHOOL_YEAR=".get_school_year()." ORDER BY SORT_ORDER"),array(),array());
//	        	    SELECT SCHOOL_TERM_ID,SCHOOL_YEAR,SHORT_NAME FROM SCHOOL_WEEKS WHERE SCHOOL_ID='".$school_id."'"),array(),array('SCHOOL_YEAR','SHORT_NAME'));
$addition['second_col'] .= '<fieldset style="border:1px solid gray;"><legend>'._('Class Settings').'</legend><TABLE cellspasing=0>';
$mp_string = '';
//foreach($year_array as $key=>$value)
//{
//	$mp_string .= "'".$value['SCHOOL_TERM_ID']."',";
//	$year_options[$value['SCHOOL_TERM_ID']] = $value['SHORT_NAME']; 
//}
foreach($school_terms_array as $key=>$value)
{
	$mp_string .= "'".$value['SCHOOL_TERM_ID']."',";
	$year_options[$value['SCHOOL_TERM_ID']] = $value['SHORT_NAME'];
	$st_names_array[$value['SHORT_NAME']] = $value['SCHOOL_TERM_ID'];
}
$mp_string = substr($mp_string,0,-1);
foreach ($class_array as $key=>$class)
{

	$addition['second_col'] .= '<TR><TD>';
/*	$addition['second_col'] .= SelectInput($ygr_array[$class['ID']][1]['VALUE1'],str_replace(' ','','class[value1]['.$class['TITLE'].']'),$class['TITLE'].' =',$year_options).'</TD><TD>'.
							TextInput($ygr_array[$class['ID']][1]['VALUE2'],'class[value2]['.$class['TITLE'].']','').'</TD><TD>'.
							TextInput($ygr_array[$class['ID']][1]['VALUE3'],'class[value3]['.$class['TITLE'].']','').'</TD><TD>'.
							SelectInput($ygr_array[$class['ID']][1]['VALUE4'],str_replace(' ','','class[value4]['.$class['TITLE'].']'),'',$year_options).'</TD><TD>'.
							TextInput($ygr_array[$class['ID']][1]['VALUE5'],'class[value5]['.$class['TITLE'].']','');
*/							

	$addition['second_col'] .= SelectInput($ygr_array[$class['ID']][1]['VALUE1'],str_replace(' ','','class[value1]['.$class['ID'].']'),$class['TITLE'].' =',$year_options).'</TD><TD>'.
							TextInput($ygr_array[$class['ID']][1]['VALUE2'],'class[value2]['.$class['ID'].']','').'</TD><TD>'.
							TextInput($ygr_array[$class['ID']][1]['VALUE3'],'class[value3]['.$class['ID'].']','').'</TD><TD>'.
							SelectInput($ygr_array[$class['ID']][1]['VALUE4'],str_replace(' ','','class[value4]['.$class['ID'].']'),'',$year_options).'</TD><TD>'.
							TextInput($ygr_array[$class['ID']][1]['VALUE5'],'class[value5]['.$class['ID'].']','');
	$addition['second_col'] .= '</TD></TR>';
}
$addition['second_col'] .= '</TABLE>';
if($_REQUEST['servicefunction']!='gradelist')
{
	Widgets('document_template');
	Widgets('mailing_labels');
}

if(isset($_REQUEST[$html_field_name]) && $_REQUEST['delete']!='true')
{
$formula_array = db_request(db_execute("SELECT * FROM YEAR_GRADE_REPORT"),array(),array('CLASSLEVEL_ID'));
	foreach($formula_array as $key=>$value)
	{
		$icount++;
		$sta_value = $value[1]['VALUE1'];
		$sta_value2 = $value[1]['VALUE4'];
		if((!$st_added[$sta_value] || !$st_added[$sta_value2]))
		{
			if($sta_value2)
				$st_added[$sta_value2] = true;
			if($sta_value)
				$st_added[$sta_value] = true;
		}
	}
	
	foreach($st_added as $key=>$value)
	{
		$sta_string .= "'".$key."',";
	}
	$sta_string = substr($sta_string,0,-1);

	$addition['SELECT'] .= ",sg1.SCHOOL_YEAR as GRADE_SCHOOL_YEAR,sg1.COURSE_TITLE,sg1.GRADE_TYPE_ID,sg1.GRADE_TITLE,sg1.PERCENT_GRADE,sg1.COMMENT AS COMMENT_TITLE,sg1.CONDUCT,sg1.STUDENT_ID,sg1.COURSE_TITLE,sg1.SCHOOL_TERM_ID,sg1.TEACHER,sp.SORT_ORDER,sg1.COURSE_SECTION_ID,COALESCE(CAST(sg1.COURSE_ID AS VARCHAR)".CCAT."sg1.COURSE_CREDIT_TITLE,sg1.COURSE_TITLE) AS COURSE,".db_case(array("sg1.CARRIES_CREDITS","'Y'","sg1.CREDITS","'0'"))." AS CREDITS";
        $addition['FROM'] .= ",STUDENT_GRADES_CARD sg1 LEFT OUTER JOIN COURSE_SECTIONS rc_cp ON (rc_cp.COURSE_SECTION_ID=sg1.COURSE_SECTION_ID) LEFT OUTER JOIN SCHOOL_PERIODS sp ON (sp.SCHOOL_PERIOD_ID=rc_cp.SCHOOL_PERIOD_ID)";
	$addition['WHERE'] .= " AND sg1.STUDENT_ID=ssm.STUDENT_ID AND sg1.SCHOOL_TERM_ID IN (".$sta_string.") ";
//	$addition['WHERE'] .= " AND sg1.STUDENT_ID=ssm.STUDENT_ID AND sg1.SCHOOL_TERM_ID=333 ";

        $addition['group'][] = 'STUDENT_ID';        


//    $addition['group'][] = 'SCHOOL_TERM_ID';

}
else
{
    Widgets('all');

    if($_REQUEST['servicefunction']!='gradelist')
        ;
    else
        $addition['action'] .= '&servicefunction=gradelist';
    $addition['force_search'] = true;
    $addition['search_button_title'] = _('Next');
    $addition['SELECT'].=",'' as CHECKBOX";
    $addition['link']['FULL_NAME'] = false;
    $addition['columns_before'] = array('CHECKBOX'=>'</A><INPUT type=checkbox value=Y checked name=controller onclick="checkAll(this.form,this.checked,\''.$html_field_name.'\');CheckAll_hilite(this.form,this.form.controller.checked,\''.$html_field_name.'\');"><A>');
    $addition['functions']=array('CHECKBOX'=>'_makeChooseCheckbox1');
    $addition['options']['onclick']="check_clicked(this);";
}
/*
if($_REQUEST['delete']=='true')
{
	if(DeletePrompt(_('final grade')))
	{
		db_execute("DELETE FROM STUDENT_GRADES_CARD WHERE SCHOOL_YEAR='".get_school_year()."' AND STUDENT_ID='".$_REQUEST['student_id']."' AND COURSE_SECTION_ID='".$_REQUEST['course_section_id']."' AND SCHOOL_TERM_ID='".$_REQUEST['school_term_id']."'");
		$_REQUEST['delete'] = 'false';
	}
}
*/
if(!(!$_REQUEST['search_servicefunction'] || $_REQUEST['search_servicefunction']=='search' || $_SYSTEM['modules_search']) && !isset($_REQUEST['CREATEPDF']))
{
    $singular = 'student';
    //echo "<form name=letters_form method=post action='modloader.php?servicemod=$_REQUEST[servicemod]&servicefunction=$_REQUEST[servicefunction]&report=$_REQUEST[report]&CREATEPDF=true' enctype=multipart/form-data>";
    echo "<form name=letters_form method=post action='".SetRequestOptions()."&is_report=true' enctype=multipart/form-data>";
    //DisplayHeader('','This button is not work <INPUT TYPE=button value="'._('Create Report').'">');
    if($_REQUEST['is_report']==true)
    	DisplayHeader('','<INPUT TYPE=button value="'._('Back to search').'" onclick="document.location=\'modloader.php?servicemod=mod_grades/GrdYearStudGradeReport.php?servicefunction=gradelist\';">');
    else 
		DisplayHeader('','<INPUT TYPE=button value="'._('Create Report').'" onclick="this.form.preview.value=\'true\';this.form.submit();">');
    echo '<INPUT type=hidden name=preview value="false">';

    
}
$class_array = db_request(db_execute("SELECT ID,TITLE,SCHOOL_ID FROM SCHOOL_CLASSLEVELS WHERE SCHOOL_ID=".get_school_id()),array(),array('TITLE'));
//$classlevel_id_array = db_request(db_execute("SELECT ID,TITLE FROM SCHOOL_CLASSLEVELS WHERE SCHOOL_ID=".get_school_id()),array(),array('ID'));
if(!isset($_REQUEST[$html_field_name]))
{
//echo "hghhhh".$_REQUEST['class']."--".$_POST['class'];
	if($_REQUEST['class'] && $_POST['class'])
	{
		foreach($_REQUEST['class'] as $key=>$value)
		{
			foreach($value as $k=>$v)
			{
//				$sql = "UPDATE YEAR_GRADE_REPORT SET $key='".$v."' WHERE CLASSLEVEL_ID='".$class_array[$k][1]['ID']."'";
				$sql = "UPDATE YEAR_GRADE_REPORT SET $key='".$v."' WHERE CLASSLEVEL_ID='".$k."'";
				db_execute($sql);
			}
		}
	}
	$addition['new'] = true;
	Search('student_id',$addition);
	echo "<script language=javascript>CheckAll_hilite(document.forms[1],true,'students')</script>";
}
elseif($_REQUEST['delete']!='true')
{
	$school_terms_agreed = array();
	$icount=0;
	foreach($formula_array as $key=>$value)
	{
		$icount++;
//		echo $value[1]['VALUE1']."|";
//		echo $value[1]['VALUE4']."|";
//		echo "<BR><BR>";
		{	
			$st_value = $value[1]['VALUE1'];
			if($value[1]['VALUE1'] && !$st_added['ST'][$value[1]['CLASSLEVEL_ID']][$st_value])
			{
				$st_array[]=array('CLASSLEVEL_ID'=>$value[1]['CLASSLEVEL_ID'],'SCHOOL_TERM_ID'=>$value[1]['VALUE1']);
				if($value[1]['VALUE2'])
					$st2_array[$value[1]['CLASSLEVEL_ID']][$value[1]['VALUE1']]=$value[1]['VALUE2'];
				else
					$st2_array[$value[1]['CLASSLEVEL_ID']][$value[1]['VALUE1']]='|';
//				$st_array[$value[1]['CLASSLEVEL_ID']]=$value[1]['VALUE1'];
				//$st_list .= "".$value[1]['VALUE1'].",";
    				$st_added['ST'][$value[1]['CLASSLEVEL_ID']][$st_value] = true;
    			}
			$st_value = $value[1]['VALUE4'];
			if($value[1]['VALUE4'] && !$st_added['ST'][$value[1]['CLASSLEVEL_ID']][$st_value])
			{
				$st_array[]=array('CLASSLEVEL_ID'=>$value[1]['CLASSLEVEL_ID'],'SCHOOL_TERM_ID'=>$value[1]['VALUE4']);
				if($value[1]['VALUE5'])
					$st2_array[$value[1]['CLASSLEVEL_ID']][$value[1]['VALUE4']]=$value[1]['VALUE5'];
				else
					$st2_array[$value[1]['CLASSLEVEL_ID']][$value[1]['VALUE4']]='|';
//				$st_array[$value[1]['CLASSLEVEL_ID']]=$value[1]['VALUE4'];
//				$st_list .= "".$value[1]['VALUE4'].",";
				$st_added['ST'][$value[1]['CLASSLEVEL_ID']][$st_value] = true;
			}
	//		$st_added['ST'][$value[1]['VALUE4']] = true;

		}
	}
//	$st_list = substr($st_list,0,-1);
//	$st_array = explode(",",$st_list);
//		var_dump($st_array);
	//var_dump($addition);
////	    	echo "==>".$_REQUEST['year_range'];
	$columns = array(
			'FULL_NAME'=>_('Student name'),
			'CLASSLEVEL_ID'=>_('Class Level'),
			'SCHOOL_TERM_ID'=>_('Report School Terms'),
	);

	$temp_array = get_student_list($addition);
	//var_dump($temp_array);
	foreach($temp_array as $student_id=>$stu_grade_array)
//	foreach($temp_array as $student_id=>$value)
	{
//		foreach($school_term_array as $key=>$value)
		foreach($stu_grade_array as $key=>$value)
		{
//		$i++;
//			var_dump($value);
//echo "==>".$value[$i]['COURSE_TITLE'];
//			var_dump($stu_grade_array);
//			echo'<br><br>';
			$school_term_id = $value['SCHOOL_TERM_ID'];
//echo $school_term_id." ";

			$columns[strtoupper(str_replace(' ','',$value['COURSE_TITLE']))] = $value['COURSE_TITLE'];
			$columns[strtoupper(str_replace(' ','',$value['COURSE_TITLE'])).'TOTAL'] = $value['COURSE_TITLE'].' TOTAL';
			$addition['functions'][strtoupper(str_replace(' ','',$value['COURSE_TITLE']))] = '_makeTitleGrade';
			$addition['functions'][strtoupper(str_replace(' ','',$value['COURSE_TITLE'])).'TOTAL'] = '_schoolTermParser';
			$addition['functions']['SCHOOL_TERM_ID'] = '_getSchoolTerm';
			if(strpos($addition['SELECT'],',NULL AS '.str_replace('.','',str_replace('&','and',str_replace(' ','',$value['COURSE_TITLE']))))===false)
			{
//			echo $value['COURSE_TITLE']."<br>";
				$addition['SELECT'] .= ',NULL AS '.str_replace('.','',str_replace('&','and',str_replace(' ','',$value['COURSE_TITLE'])));
				$addition['SELECT'] .= ',NULL AS '.str_replace('.','',str_replace('&','and',str_replace(' ','',$value['COURSE_TITLE']))).'TOTAL';
			}
			else
			{
//				$addition['SELECT'] .= ',NULL AS '.str_replace('&','and',str_replace(' ','',$value['COURSE_TITLE']));
//				$addition['SELECT'] .= ',NULL AS '.str_replace('&','and',str_replace(' ','',$value['COURSE_TITLE'])).'TOTAL';
			}
			
			$old[$value['STUDENT_ID']][$school_term_id][strtoupper(str_replace(' ','',$value['COURSE_TITLE']))] = $value['PERCENT_GRADE'];
			$old[$value['STUDENT_ID']][$school_term_id][strtoupper(str_replace(' ','',$value['COURSE_TITLE'])).'TOTAL'] = $value['CLASSLEVEL_ID'];
			$old[$value['STUDENT_ID']][$school_term_id]['PERCENT_GRADE'][strtoupper(str_replace(' ','',$value['COURSE_TITLE'])).'TOTAL'] = $value['PERCENT_GRADE'];
			$old[$value['STUDENT_ID']][$school_term_id]['SCHOOL_TERM_ID'] = $year_options[$value['SCHOOL_TERM_ID']];
		}
	}
//	var_dump($addition);
//	die();
	$temp_array = get_student_list($addition);
//	var_dump($st2_array);
//	var_dump($temp_array);
	$tt=array();
	$in_temp_array = $temp_array;
	foreach($temp_array as $student_id=>$students_array)
	{
	
		//var_dump($students_array);		
		foreach($students_array as $count=>$stud_info_array)
		{
//			echo "MAINLEVEL: $count -->".$stud_info_array['FULL_NAME']."<BR>";
//			echo $stud_info_array['SCHOOL_TERM_ID'];
			$classlevel_id = $class_array[$stud_info_array['CLASSLEVEL_ID']][1]['ID'];
			$stud_school_term_id = $st_names_array[$stud_info_array['SCHOOL_TERM_ID']];
//			echo "MAINLEVEL: $count -->".$stud_info_array['FULL_NAME']."$classlevel_id-$stud_school_term_id"."<BR>";
//			echo "==".var_dump($st2_array)."<br>";
			if(!$st2_array[$classlevel_id][$stud_school_term_id])// && ($formula_array[$classlevel_id][1]['VALUE2'] && $formula_array[$classlevel_id][1]['VALUE1']))
			{
//			echo "xxxx";
				unset($temp_array[$student_id][$count]);
				unset($students_array[$count]);
			}
			else
			{
			    if($st_id[$stud_info_array['STUDENT_ID']][$stud_school_term_id])
			    {
				unset($temp_array[$student_id][$count]);
			    }
			    else
			    {
				$st_id[$stud_info_array['STUDENT_ID']][$stud_school_term_id] = true;
//				echo "||".$formula_array[$classlevel_id][1]['VALUE3']."||";
			    if($formula_array[$classlevel_id][1]['VALUE3'])
			    {
//				echo "SUBLEVEL: ".$stud_info_array['FULL_NAME']."(".$stud_info_array['STUDENT_ID'].")-$classlevel_id-$stud_school_term_id->".$st2_array[$classlevel_id][$stud_school_term_id]."<br>";			
				$sid = $stud_info_array['STUDENT_ID'];
				$sign = $formula_array[$classlevel_id][1]['VALUE3'];
				$st1 = $year_options[$formula_array[$classlevel_id][1]['VALUE1']];
				$st2 = $year_options[$formula_array[$classlevel_id][1]['VALUE4']];
				$mn1 = $formula_array[$classlevel_id][1]['VALUE2'];
				$mn2 = $formula_array[$classlevel_id][1]['VALUE5'];
//				echo "-->".$stud_info_array['SCHOOL_TERM_ID'];
//				var_dump($students_array);
//				die();
//						$grds = '';
				foreach($students_array as $key=>$value)
				{
//				    echo var_dump($value)."|";
//				    echo "SID: ".$value['STUDENT_ID']." - ".$value['SCHOOL_TERM_ID']."<br>";
				    
				    foreach($columns as $column=>$info)
				    {
//				    echo $column;
					if(strpos($value[$column],'%') && isset($value[$column]))
					{
					
					    if(!$gcourse[$value['STUDENT_ID']][$value['SCHOOL_TERM_ID']][$column][$value[$column]])
					    {
						if($value['SCHOOL_TERM_ID'] == $st1)
						    $grd[1][$column] = $value[$column];
						if($value['SCHOOL_TERM_ID'] == $st2)
						    $grd[2][$column] = $value[$column];
						$gcourse[$value['STUDENT_ID']][$value['SCHOOL_TERM_ID']][$column][$value[$column]] = true;
					    }
					    else
					    {
						$students_array[$count][$column] = $grd[1][$column]." | ".$grd[2][$column];
						$total = "(".str_replace('%','',$grd[1][$column]).$mn1.")".$sign."(".str_replace('%','',$grd[2][$column]).$mn2.")";
						$students_array[$count][$column.'TOTAL'] = calculate_string($total);
//						$students_array[$count][$column.'TOTAL'] = $total;
					    }
					    
					}
				    }
				}

				$students_array[$count]['SCHOOL_TERM_ID'] = $year_options[$formula_array[$classlevel_id][1]['VALUE1']]." $sign ".$year_options[$formula_array[$classlevel_id][1]['VALUE4']];	
			    }
			//calculate w/o sign
			    else
			    {
//			    echo "vvv";
				$sid = $stud_info_array['STUDENT_ID'];
				$st1 = $year_options[$formula_array[$classlevel_id][1]['VALUE1']];
				$mn1 = $formula_array[$classlevel_id][1]['VALUE2'];
				if($mn1 == '|') $mn1 = '';
				foreach($students_array as $key=>$value)
				{
				    foreach($columns as $column=>$info)
				    {
					if(strpos($value[$column],'%') && isset($value[$column]))
					{
					
					    if(!$gcourse[$value['STUDENT_ID']][$value['SCHOOL_TERM_ID']][$column][$value[$column]])
					    {
						if($value['SCHOOL_TERM_ID'] == $st1)
						    $grd[1][$column] = $value[$column];
						$gcourse[$value['STUDENT_ID']][$value['SCHOOL_TERM_ID']][$column][$value[$column]] = true;
					    }
					    else
					    {
						$total = str_replace('%','',$grd[1][$column]).$mn1;
						$students_array[$count][$column.'TOTAL'] = calculate_string($total);
//						$students_array[$count][$column.'TOTAL'] = $total;
					    }
					    
					}
				    }
				}
    			    }
			    if(!$ST[$student_id])
			    {
				$tt[] =$students_array[$count];
				$ST[$student_id] = true;
			    }
			}
		}
	}
}
//var_dump($tt);
foreach($tt as $stu=>$inf)
{
        foreach($columns as $column=>$info)
        {
    		if(strpos($inf[$column],'%') && isset($inf[$column]))
    		{
//    		echo $column;
    			$iscolumn[] = $column;
//			echo ">>".$inf[$column];
		}
	}
}
//var_dump($columns);
foreach($columns as $column=>$value)
{
	if(!in_array($column,$iscolumn) && $column!='FULL_NAME' && $column!='CLASS_LEVEL_ID' && $column!='SCHOOL_TERM_ID' && strpos($column,'TOTAL') == 0)
	{
		unset($columns[$column]);
		unset($columns[$column.'TOTAL']);
	}
	//    if($column!='FULL_NAME' && $column!='CLASS_LEVEL_ID' && $column!='SCHOOL_TERM_ID')
}
	$link['FULL_NAME']['link'] = 'modloader.php?servicemod=mod_grades/GrdPrintStudGrades.php';
        $link['FULL_NAME']['variables']['student_id'] = 'STUDENT_ID';
        $_REQUEST['GridSortingBy'] = 'FULL_NAME';
	$get_school_year = get_school_year().'-'.(strval(get_school_year())+1);
//var_dump($columns);
	Gridoutput($tt,$columns,_('Students'),_('Amount of Students').' '._('for school year ').$get_school_year,$link,array(),array());
}

if(!(!$_REQUEST['search_servicefunction'] || $_REQUEST['search_servicefunction']=='search' || $_SYSTEM['modules_search']))
    echo "</form>";

function _schoolTermParser($value,$column)
{	global $old,$THIS_array,$class_array,$formula_array,$st2_array;
//	var_dump($THIS_array);
	$formula = $formula_array[$class_array[$old[$THIS_array['STUDENT_ID']][$THIS_array['SCHOOL_TERM_ID']][$column]][1]['ID']];
	//var_dump($formula);
	if($formula)
	{
//		var_dump($formula);
		$class_level_id = $THIS_array['CLASSLEVEL_ID'];
		foreach($formula as $key=>$value)
		{
//			$class_level = $THIS_array['CLASSLEVEL_ID'];
			$formula_class_level_id = $value['CLASSLEVEL_ID'];
			if($class_level_id == $formula_class_level_id)
			{
				$stud_school_term_id = $THIS_array['SCHOOL_TERM_ID'];
				$school_term1 = $value['VALUE1'];
	    			$school_term2 = $value['VALUE4'];
				if(($stud_school_term_id == $school_term1) || ($stud_school_term_id == $school_term2))
				{
	    //				echo "$class_level ";
					$percent_grade = $THIS_array['PERCENT_GRADE'];					
					$action = $value['VALUE3'];					
					$mn1 = $value['VALUE2'];
					if($mn1 && $mn1!='|')
					{
						$total1 = $percent_grade.$mn1;
						$t1_calc = calculate_string($total1);
			//			echo $total1.' -->'.calculate_string($total1);
//						echo "-->".$total1;
						return $t1_calc;
					}
					$mn2 = $value['VALUE5'];
					if($mn2 && $mn2!='|')
					{
						$total2 = $percent_grade.$mn2;
						$t2_calc = calculate_string($total2);
			//			echo $total2.' -->'.calculate_string($total2);
//						echo "-->".$total1;
						return $t2_calc;
					}


/*
					for($len=1;$len <= strlen($mn1);$len++)
					{
					        $symbol = substr($mn1,$len,1);
					        if($symbol == '*' || $symbol == '+' || $symbol == '-' || $symbol == '/')
					        {
					    		$symbol_array['ID']=$symbol;
					        }
					        else
					        {
					    		$digits .= substr($symbol,$len,1);
					        }
						switch($symbol)
						{
						    case '*':
							$percent_grade = "";
						    break;
						    case '/':
						    break;
						    case '+':
						    break;
						    case '-':
						    default:
						    break;
    							
						}
					        
					    
					}
					*/


//					echo "calc: ($school_term1)$percent_grade $mn1 - $mn2";
					$total = $percent_grade;
		//			echo var_dump($value).'<br>';			
				}
			}
		}
	}
//	return 'Not calc';
//	return $old[$THIS_array['STUDENT_ID']][$THIS_array['SCHOOL_TERM_ID']]['PERCENT_GRADE'][$column];
//	return $formula_array[$class_array[$old[$THIS_array['STUDENT_ID']][$column]][1]['ID']][1]['VALUE1'];
}

function calculate_string($mathString)
{  
	$mathString = trim($mathString);     // trim white spaces  
	$mathString = ereg_replace ('[^0-9\+-\*\/\(\) ]', '', $mathString);    // remove any non-numbers chars; exception for math operators  
	$compute = create_function("", "return (" . $mathString . ");" );  
	return 0 + $compute();  
}  

    

function _makeTitleGrade($value,$column)
{	global $old,$THIS_array;

	if($old[$THIS_array['STUDENT_ID']][$THIS_array['SCHOOL_TERM_ID']][$column])
		return $old[$THIS_array['STUDENT_ID']][$THIS_array['SCHOOL_TERM_ID']][$column].'%';
}
function _getSchoolTerm($value,$column)
{	global $old,$THIS_array;

	if($old[$THIS_array['STUDENT_ID']][$THIS_array['SCHOOL_TERM_ID']][$column])
		return $old[$THIS_array['STUDENT_ID']][$THIS_array['SCHOOL_TERM_ID']][$column];
}
function _makeTeacher($teacher,$column)
{
	return substr($teacher,strrpos(str_replace(' - ',' ^ ',$teacher),'^')+2);
}

function _makeChooseCheckbox1($value,$title='')
{	global $THIS_array, $html_field_name;

	$student_id_field="STUDENT_ID";

	return "<INPUT onchange='hl_cb(this)' type=checkbox name=".$html_field_name."[".$THIS_array[$student_id_field]."] value=Y checked>";
}
function _makeCourseRank($student_id='',$school_term_id='',$course_class='',$reload=false)
{
	global $grades_array,$array,$stu_array,$students, $cur_classname;
	
	if(($_REQUEST['elements']['course_rank'] || $_REQUEST['elements']['low_high']) && $student_id)
	{
		for($y=1;$y<count($grades_array)+1;$y++)
		{
			$course_title = $grades_array[$y]['COURSE_TITLE'];
			
			$grade_array = db_request(db_execute("SELECT ID FROM SCHOOL_CLASSLEVELS WHERE TITLE = '".substr($course_class,-3)."'"));

			if(!$stu_array || $reload)

			$stu_array = db_request(db_execute("SELECT STUDENT_ID FROM STUDENT_REGISTRATION WHERE CLASSLEVEL_ID = '".$grade_array[1]['ID']."'"),array(),array('STUDENT_ID'));
			$lines_ID = '';
			foreach($stu_array as $key)
			{
				$lines_ID .= $key[1]['STUDENT_ID'].",";
			}
			$lines_ID = substr($lines_ID,0,-1);
			$perc_array = db_request(db_execute("SELECT PERCENT_GRADE,STUDENT_ID FROM STUDENT_GRADES_CARD WHERE STUDENT_ID IN ($lines_ID) AND COURSE_TITLE = '".$course_title."' AND SCHOOL_TERM_ID ='".$school_term_id."' ORDER BY PERCENT_GRADE DESC"),array(),array('PERCENT_GRADE'));

			$course_rank = 0;
			$high_score = 0;
			$low_score = 500;

			if($_REQUEST['elements']['low_high'])
			{
				foreach($perc_array as $perc)
				{
					for($a=1;$a<count($perc)+1;$a++)
					{
						if($perc[$a]['PERCENT_GRADE']>$high_score)
							$high_score = $perc[$a]['PERCENT_GRADE'];
						elseif($perc[$a]['PERCENT_GRADE']<$low_score && $perc[$a]['PERCENT_GRADE'] != '0')
							$low_score = $perc[$a]['PERCENT_GRADE'];
					}
				}
			}
			foreach($perc_array as $perc)
			{
				$course_rank++;
				for($i=1;$i<count($perc)+1;$i++)
				{
					if($perc[$i]['STUDENT_ID'] == $student_id)
					{
						if($_REQUEST['elements']['course_rank'])
							$grades_array[$y]['QTR_COURSE_RANK'] = $course_rank;
						if($_REQUEST['elements']['low_high'])
							$grades_array[$y]['LOW_HIGH'] = $low_score." / ".$high_score;
					}
				}
			}
		}
	}
}
?>