<?php
	require_once($staticpath.'functions/extra/CategoriesSelection.fnc.php'); 
	require_once($staticpath.'functions/extra/StudentsFunctional.fnc.php');
	include_once($staticpath.'classes/InputButton.php');
	include_once($staticpath.'classes/Documents.class.php');
	include_once($staticpath.'classes/NumToText.class.php');

	$submitButton = new InputButton;
	$javaButton = new InputButton;
	$Document = new Documents;
	$NumToText = new NumToText;

	if(!$_REQUEST['CREATEPDF']){
		print_r($_REQUEST['CREATEPDF']);
		echo GetBaseJavaFunc();
  
	}

	if(LOADED_BY_MODULES!==true){
		DisplayBlock(_('Error'),_('Use the right way to load modules. Try to log into AIS Integral.'));
		exit;
	}

if($run_report_require_request_vars)
	$_REQUEST = $run_report_require_request_vars;

if($_REQUEST['servicemod']=='mod_users/UsrAdvancedReport.php' || $_SYSTEM['user_search']==true)
{
	$custom_fields_table = 'USER_FIELDS';
	$categories_table = 'USER_FIELD_CATEGORIES';
	$students_table = 'USERS';
	$student_id_field = 'USER_ID';
	$address_table = 'ADDRESS';
	$address_id_field = 'ADDRESS_ID';
	$singular = _('Users');
	$plural = _('Amount of Users');
	$search_function_parameter = 'user_id';
	$search_servicefunction = 'users_search_servicefunction';
	$students_program = 'mod_users/Users.php';
	$get_student_list = 'get_user_list';
	$html_field_name = 'user';
	$html_log_entries_name = 'user_lf_data';
	$search_form_name = 'user_search_form';
	$student_log_entries_table = 'USER_LF_DATA';
	$student_field_id_field = 'USER_FIELD_ID';
	$student_fields_join_categories = 'USER_FIELDS_IN_CATS';
}
elseif($_REQUEST['servicemod']=='mod_discipline/DisAdvancedReportWizard.php')
{
	$custom_fields_table = 'DISCIPLINE_INCIDENT_FIELDS';
	$categories_table = 'DISCIPLINE_INCIDENT_CATEGORIES';
	$students_table = 'STUDENT_DISCIPLINE_INCIDENTS';
	$student_id_field = 'ID';
	$singular = _('Incidents');
	$plural = _('Amount of Incidents');
	$search_function_parameter = 'incident_id';
	$search_servicefunction = 'incident_search_servicefunction';
	$students_program = 'mod_discipline/DisIncidentList.php';
	$get_student_list = 'get_incident_list';
	$html_field_name = 'incident';
	$search_form_name = 'incident_search_form';
	$student_fields_join_categories = 'DISCIPLINE_INCIDENTS_FIELDS_IN_CATS';
}
else //if($_REQUEST['servicemod']=='mod_users/UsrAdvancedReport.php')
{
	$custom_fields_table = 'STUDENT_FIELDS';
	$categories_table = 'STUDENT_FIELD_CATEGORIES';
	$students_table = 'STUDENTS';
	$student_id_field = 'STUDENT_ID';
	$address_table = 'ADDRESS';
	$address_id_field = 'ADDRESS_ID';
	if($_REQUEST['system_tab'] == 'AppAdvancedReport.php' || $_REQUEST['servicemod'] == 'mod_apply/AppAdvancedReport.php' || $_REQUEST['servicemod'] == 'mod_apply/Applicants.php' || $app_savedinfo_enabled === true)
	{
		$singular = _('Applicants');
		$plural = _('Amount of Applicants');
		$students_program = 'mod_apply/Applicants.php';
		$addition['APPLY_MODE'] = true;
	}
	else
	{
		$singular = _('Students');
		$plural = _('Amount of Students');
		$students_program = 'mod_students/Students.php';
//		$addition['APPLY_MODE'] = false;
	}
	$search_function_parameter = 'student_id';
	$search_servicefunction = 'search_servicefunction';
	$get_student_list = 'get_student_list';
	$html_field_name = 'students ';
	$html_log_entries_name = 'student_log_entries';
	$search_form_name = 'student_search_form';
	$student_log_entries_table = 'STUDENT_LF_DATA';
	$student_field_id_field = 'STUDENT_FIELD_ID';
	$student_fields_join_categories = 'STUDENT_FIELDS_IN_CATS';
}

//if($_REQUEST['servicemod']=='mod_students/StuAdvancedReport.php')
//	$_REQUEST['servicemod']=='mod_portal/ExternalLinker.php';
	
//var_dump($_REQUEST['servicemod']);
$fields_array = db_request(db_execute("SELECT * FROM ".$custom_fields_table." ORDER BY SORT_ORDER,TITLE"),array(),array('ID'));

//TITLE,ID,TYPE,SELECT_OPTIONS,REQUIRED
//THE FIELDS LIST WAS REPLACED WITH * FOR THE SAKE OF ALL THE LOGGING FIELD COLUMNS

if ($students_table=='STUDENTS')
	$school_fields_array = db_request(db_execute("SELECT * FROM SCHOOL_FIELDS ORDER BY SORT_ORDER,TITLE"),array(),array('ID'));

include_once($staticpath.'functions/extra/MakeExpFunc.fnc.php');

if(!$_REQUEST['CREATEPDF'] && $_REQUEST['servicemod'] !== 'applicants_online')
{
	echo '<SCRIPT language=javascript>';
	echo "function disableRadios(form)
	{
		for(i=0;i<form.elements.length;i++)
		{
			if(form.elements[i].type=='radio')
				form.elements[i].disabled = true;
		}
	}
	";
	echo '</SCRIPT>';
	echo '<style>
		.names_title
		{
			border-right:2px solid lightGray;
			padding-right:4px;
			padding-left:4px;
			border-bottom:20px solid #'.Preferences('COLOR').';
		}
	</style>
	';
}

if(is_array($_REQUEST['month_'.$html_field_name]))
{
	foreach($_REQUEST['month_'.$html_field_name] as $id=>$columns)
	{
		foreach($columns as $column=>$value)
		{
			$_REQUEST[$html_field_name][$id][$column] = $_REQUEST['year_'.$html_field_name][$id][$column].'-'.$_REQUEST['month_'.$html_field_name][$id][$column].'-'.$_REQUEST['day_'.$html_field_name][$id][$column];
			if($_REQUEST[$html_field_name][$id][$column]=='--')
				$_REQUEST[$html_field_name][$id][$column] = '';
			elseif(!VerifyDate($_REQUEST[$html_field_name][$id][$column]))
			{
				unset($_REQUEST[$html_field_name][$id][$column]);
				$note = _("The invalid date could not be saved.");
			}
		}
	}
}
unset($_REQUEST['day_'.$html_field_name]); unset($_REQUEST['month_'.$html_field_name]); unset($_REQUEST['year_'.$html_field_name]);
// unset columns since it messes up the column order
unset($columns);

// THIS IS COPIED DIRECTLY BELOW
if(is_array($_REQUEST['students']))
{
	foreach($_REQUEST['students'] as $student_id=>$student)
	{
		$sql = "UPDATE ".$students_table." SET ";
    		$go = false;
    		if(!$student) $student = array();
    		if(is_array($student))
		foreach($student as $column_name=>$value)
		{
			if(!is_array($value))
				$sql .= "$column_name='".str_replace("\'","''",str_replace('``','"',$value))."',";
			else
			{
				$sql .= $column_name."='||";
				foreach($value as $val)
				{
					if($val)
						$sql .= str_replace("\'","''",str_replace('``','"',$val)).'||';
				}
				$sql .= "',";
			}
        		$go = true;
		}
		$sql = substr($sql,0,-1) . " WHERE ".$student_id_field."='$student_id'";
		if($go)
        		db_execute($sql);
	}
	unset($_REQUEST['students']);
	unset($_SESSION['_REQUEST_vars']['students']);
}
if(is_array($_REQUEST['address']))
{
	foreach($_REQUEST['address'] as $address_id=>$address)
	{
		$sql = "UPDATE ".$address_table." SET ";
		foreach($address as $column_name=>$value)
		{
			if(!is_array($value))
				$sql .= "$column_name='".str_replace("\'","''",str_replace('``','"',$value))."',";
			else
			{
				$sql .= $column_name."='||";
				foreach($value as $val)
				{
					if($val)
						$sql .= str_replace("\'","''",str_replace('``','"',$val)).'||';
				}
				$sql .= "',";
			}
		}
		$sql = substr($sql,0,-1) . " WHERE ".$address_id_field."='$address_id'";
		db_execute($sql);
	}
	unset($_REQUEST['address']);
	unset($_SESSION['_REQUEST_vars']['address']);
}

//die();
if(is_array($_REQUEST['student_registration']))
{
	foreach($_REQUEST['student_registration'] as $student_id=>$student)
	{
		$sql = "UPDATE STUDENT_REGISTRATION SET ";
		foreach($student as $column_name=>$value)
		{
			if(!is_array($value))
				$sql .= "$column_name='".str_replace("\'","''",str_replace('``','"',$value))."',";
		}
		$sql = substr($sql,0,-1) . " WHERE ".$student_id_field."='$student_id' AND SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."' ";
		// this should probably also just do the active records
		db_execute($sql);
	}
	unset($_REQUEST['students']);
	unset($_SESSION['_REQUEST_vars']['students']);
}

if(is_array($_REQUEST['user']))
{
	foreach($_REQUEST['user'] as $student_id=>$student)
	{
		$sql = "UPDATE ".$students_table." SET ";
		foreach($student as $column_name=>$value)
		{
			if(!is_array($value))
				$sql .= "$column_name='".str_replace("\'","''",str_replace('``','"',$value))."',";
			else
			{
				$sql .= $column_name."='||";
				foreach($value as $val)
				{
					if($val)
						$sql .= str_replace("\'","''",str_replace('``','"',$val)).'||';
				}
				$sql .= "',";
			}
		}
		$sql = substr($sql,0,-1) . " WHERE ".$student_id_field."='$student_id'";
		db_execute($sql);
	}
	unset($_REQUEST['user']);
	unset($_SESSION['_REQUEST_vars']['user']);
}

if(is_array($_REQUEST['replog_values']))
{
        $sfid = db_request(db_execute("SELECT STUDENT_FIELD_ID,ID FROM STUDENT_LF_DATA WHERE ID IN ("."'".implode("','",array_keys($_REQUEST['replog_values']))."'".")"),array(),array('ID'));
	foreach($_REQUEST['replog_values'] as $student_id=>$student)
	{
		$sql = "UPDATE ".$student_log_entries_table." SET ";
    		$go = false;
    		if(!$student) $student = array();
                if($student[$_Config['NumToLetter']['CFIELD_'.$sfid[$student_id][1]['STUDENT_FIELD_ID']]['FROM']]<>'')
                    $student[$_Config['NumToLetter']['CFIELD_'.$sfid[$student_id][1]['STUDENT_FIELD_ID']]['TO']] = $NumToText->Convert(intval($student[$_Config['NumToLetter']['CFIELD_'.$sfid[$student_id][1]['STUDENT_FIELD_ID']]['FROM']]));
    		if(is_array($student))
		foreach($student as $column_name=>$value)
		{
			if(!is_array($value))
				$sql .= "$column_name='".str_replace("\'","''",str_replace('``','"',$value))."',";
			else
			{
				$sql .= $column_name."='||";
				foreach($value as $val)
				{
					if($val)
						$sql .= str_replace("\'","''",str_replace('``','"',$val)).'||';
				}
				$sql .= "',";
			}
        		$go = true;
		}
		$sql = substr($sql,0,-1) . " WHERE ID='$student_id'";
		if($go)
//		echo $sql."<br>";
        		db_execute($sql);
	}
	unset($_REQUEST['replog_values']);
	unset($_SESSION['_REQUEST_vars']['replog_values']);
}

//var_dump($_REQUEST['log_values']);
//var_dump($_POST);
if($_REQUEST['servicemod']=='mod_portal/ExternalLinker.php'  || $_REQUEST['system_tab'] == 'AppAdvancedReport.php' || $_REQUEST['servicemod']=='mod_apply/AppAdvancedReport.php' || $_REQUEST['servicemod']=='mod_students/StuAdvancedReport.php' || $_REQUEST['servicemod']=='mod_users/UsrAdvancedReport.php' || substr($_REQUEST['servicemod'],0,28)=='mod_savedinfo/SIRunLink.php?' || $_REQUEST['servicemod'] == 'mod_discipline/DisAdvancedReportWizard.php')
{
	DisplayHeader(".:".ProgramTitle().":.");
	if($_REQUEST['servicemod']!='mod_users/UsrAdvancedReport.php')
	{
		Widgets('all');
	
		$addition['search'] .= '<TABLE><TR><TD align='.ALIGN_RIGHT.' width=40>'._('Include courses active as of').' </TD><TD>'.PrepareDate('','_include_active_date').'</TD></TR>';
		$addition['search'] .= '<TR><TD colspan=2><INPUT type=hidden name=relation></TD></TR></TABLE>';
	}
}

$addition['search'] .= '<TABLE><TR><TD align=center colspan=2><TABLE><TR><TD><DIV id=fields_div></DIV></TD></TR></TABLE></TD></TR></TABLE>';
$addition['new'] = true;
$addition['force_search'] = true;
// Since printClassLists.php might have set this already
if(!$addition['search_button_title'])
	$addition['search_button_title'] = _('Create Report');

$contacts = array('FATHER'=>_('Parent/Father'),
		  'MOTHER'=>_('Parent/Mother'),
		  'EMERGENCY'=>_('3rd Contact/Emergency'),
		  'CONTACT'=>_('4th Contact'));
if(substr($_REQUEST['servicemod'],0,9)=='mod_apply')
{
	unset($contacts['EMERGENCY']);
	unset($contacts['CONTACT']);
}
$elems = array('NAME'=>_('Name'),
	       'CELL'=>_('Cell Phone'),
	       'WORK'=>_('Work Phone'),
	       'EMPLOYER'=>_('Employer'),
	       'OCCUPATION'=>_('Occupation'),
	       'EMAIL'=>_('Email'),
	       'ADDRESS'=>_('Address'),
	       'CITY'=>_('City'),
	       'STATE'=>_('State'),
	       'ZIPCODE'=>_('Zipcode'),
	       'HOMEPHONE'=>_('Home Phone'),
	       'STUDENTRELATION'=>_('Relationship'),
	       'CUSTODY'=>_('Has Custody'),
	       'EMERGENCY'=>_('Is Emergency'));

if($_REQUEST['servicemod']=='mod_discipline/DisAdvancedReportWizard.php')
{
	unset($contacts);
	unset($elems);
}
//echo "begins";
//var_dump($_REQUEST['fields']);
//echo "ends<br><br><br><br>";
//var_dump($_REQUEST['fields_order']);
if($_REQUEST['fields_order'])
{
	$_REQUEST['fields'] = array();

	//print_r($_REQUEST['fields_order']);

	$rep = str_replace(' ','_',$_REQUEST['fields_order']);
	
	echo "<br>";

	//print_r($rep);

	// var_dump($_REQUEST['fields_order']);
	// print_r(explode('|',$rep));
	$fields_order = explode('|',$rep);
	foreach($fields_order as $field)
		$_REQUEST['fields'][$field] = 'Y';
}
elseif($_REQUEST['fields']) 
{
	foreach($_REQUEST['fields'] as $field=>$y)
	{
		$_REQUEST['fields_order'] .= '|'.$field;
	}
	$_REQUEST['fields_order'] = substr($_REQUEST['fields_order'],1);
}

$_SYSTEM['CustomFields'] = true;

if($_REQUEST['fields']['ADDRESS'] || $_REQUEST['fields']['CITY'] || $_REQUEST['fields']['STATE'] || $_REQUEST['fields']['ZIPCODE'] || $_REQUEST['fields']['PHONE'] || $_REQUEST['fields']['ADDRESS_USERNAME'] || $_REQUEST['fields']['ADDRESS_PASSWORD'] || $_REQUEST['fields']['MAIL_ADDRESS'] || $_REQUEST['fields']['MAIL_CITY'] || $_REQUEST['fields']['MAIL_STATE'] || $_REQUEST['fields']['MAIL_ZIPCODE'] || $_REQUEST['fields']['PARENTS'] || $_REQUEST['fields']['MAILTO_LABEL'] || $_REQUEST['fields']['CITY_STATE'] || $_REQUEST['fields']['MAIL_CITY_STATE'] || $_REQUEST['fields']['ENTIRE_ADDRESS'] || $_REQUEST['fields']['ENTIRE_MAIL_ADDRESS'] || $_REQUEST['fields']['FED_REGION'] || $_REQUEST['fields']['MAIL_FED_REGION'] || $_REQUEST['fields']['SETTLEMENT'] || $_REQUEST['fields']['MAIL_SETTLEMENT'])
{
	$addition['SELECT'] .= ',a.ADDRESS_ID,a.ADDRESS,a.CITY,a.STATE,a.SETTLEMENT,a.MAIL_SETTLEMENT,a.MAIL_FED_REGION,a.FED_REGION,a.ZIPCODE,a.PHONE,a.USERNAME AS ADDRESS_USERNAME,a.PASSWORD as ADDRESS_PASSWORD,COALESCE(a.MAIL_ADDRESS,a.ADDRESS) AS MAIL_ADDRESS,COALESCE(a.MAIL_CITY,a.CITY) AS MAIL_CITY,COALESCE(a.MAIL_STATE,a.STATE) AS MAIL_STATE,COALESCE(a.MAIL_ZIPCODE,a.ZIPCODE) AS MAIL_ZIPCODE';
	$addition['addr'] = true;
	if($_REQUEST['fields']['MAIL_ADDRESS'])
		$addition['STUDENTS_IN_ADDRESS'] .= " AND sam.MAILING='Y'";
}
if($_REQUEST['fields']['PARENTS'])
{
	$addition['SELECT'] .= ',ssm.STUDENT_ID AS PARENTS';
	$view_other_array['ALL_CONTACTS'][1]['VALUE']='Y';
	if($_REQUEST['relation']!='')
	{
		$_SYSTEM['makeParents'] = $_REQUEST['relation'];
		$addition['STUDENTS_IN_ADDRESS'] .= " AND EXISTS (SELECT '' FROM STUDENTS_IN_SR sjp WHERE sjp.ADDRESS_ID=sam.ADDRESS_ID AND LOWER(sjp.STUDENT_RELATION) LIKE '".strtolower($_REQUEST['relation'])."%') ";
	}
}
if($_REQUEST['fields']['MAILTO_LABEL'])
	$addition['SELECT'] .= ',NULL AS MAILTO_LABEL';

if($students_program=='mod_users/Users.php')
	$addition['SELECT'] .= ',s.*';
elseif($students_table != 'STUDENT_DISCIPLINE_INCIDENTS')
{
	//this line gets fields from students table with values s.*
	$addition['SELECT'] .= ',ssm.NEXT_SCHOOL,ssm.CALENDAR_ID,ssm.SCHOOL_YEAR,'.db_to_char('ssm.START_DATE', 'yyyy-mm-dd').' AS START_DATE,ssm.ENROLLMENT_CODE,'.db_to_char('ssm.END_DATE', 'yyyy-mm-dd').' AS END_DATE,ssm.DROP_CODE,ssm.CFIELD_1,ssm.CFIELD_2,s.*';
}

if($_REQUEST['fields']['FIRST_INIT'])
	$addition['SELECT'] .= ','.db_substr('s.FIRST_NAME',1,1).' AS FIRST_INIT';

if(!$addition['functions'])
	$addition['functions'] = array('NEXT_SCHOOL'=>'_makeNextSchool','CALENDAR_ID'=>'_makeCalendar','SCHOOL_ID'=>'get_school','PARENTS'=>'makeParents','MAILTO_LABEL'=>'MailToLabel','START_DATE'=>'ProperDate','END_DATE'=>'ProperDate','ENROLLMENT_CODE'=>'_getRegistrationCode','DROP_CODE'=>'_getRegistrationCode','CONTACT_INFO'=>'makeContactInfo'); //,'LAST_LOGIN'=>'ProperDate');

if($_REQUEST['fields']['CONTACT_INFO'])
{
	$addition['SELECT'] .= ',NULL AS CONTACT_INFO ';

	$addition2 = $addition;
	$addition2['addr'] = false;
	$addition2['GridOutputCount'] = false;
	$addition2['DisableSearchResDisplay'] = true;
	$addition2['SELECT'] = '';
	$addition2['SELECT_ONLY'] = 'ssm.STUDENT_ID,p.PERSON_ID,p.FIRST_NAME,p.LAST_NAME,sjp.STUDENT_RELATION,pjc.TITLE,pjc.VALUE,addr.PHONE,sjp.ADDRESS_ID,COALESCE(sjp.CUSTODY,\'N\') AS CUSTODY,COALESCE(sjp.EMERGENCY,\'N\') AS EMERGENCY,addr.ADDRESS,addr.CITY,addr.STATE,addr.ZIPCODE,addr.SETTLEMENT,addr.FED_REGION';
	$addition2['FROM'] .= ',ADDRESS addr,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 addr.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','ADDRESS_ID','PERSON_ID');
	$addition2['functions'] = array();
	$addition2['link'] = array();
	
	$_SYSTEM['makeContactInfo'] = get_student_list($addition2);
}

//var_dump($_REQUEST[$search_servicefunction]);
if($_REQUEST[$search_servicefunction]=='list' && !$_SYSTEM['modules_search'])
{

	if(!$fields_list)
	{
 
		$fields_list = array('FULL_NAME'=>_('Last, First M'),
				     'FIRST_NAME'=>_('First'),
				     'FIRST_INIT'=>_('First Initial'),
				     'LAST_NAME'=>_('Last'),
				     'MIDDLE_NAME'=>_('Middle'),
                     'CFIELD_2' =>_('Email'),        
				     'NAME_SUFFIX'=>_('Suffix'),
				     'STUDENT_ID'=>_('Student ID number'),
				     'USER_ID'=>_('User ID'),
				     'CLASSLEVEL_ID'=>_('Class Level'),
				     'GROUP_ID'=>_('Class Group'),
				     'SCHOOL_ID'=>_('School Name'),
				     'NEXT_SCHOOL'=>_('Rolling Options'),
				     'CALENDAR_ID'=>_('School Calendar'),
				     'CFIELD_1'=>_('Order Number'),
				     //'CFIELD_2'=>_('Order Date'),
				     'START_DATE'=>_('Date of Student Enrollment'),
				     'ENROLLMENT_CODE'=>_('Enrollment Code'),
				     'END_DATE'=>_('Student Dropped Date'),
				     'DROP_CODE'=>_('Drop Code'),
				     'USERNAME'=>_('Login Name'),
				     'PASSWORD'=>_('Password'),
				     'LAST_LOGIN'=>_('Last Date of Login'),
				     'ADDRESS'=>_('Address'),
				     'CITY'=>_('City'),
				     'STATE'=>_('State'),
				     'ZIPCODE'=>_('Zip Code'),
				     'PHONE'=>_('Home Phone'),
                      'EMAIL' =>_('Email'),
				     'ADDRESS_USERNAME'=>_('Parent Login Name'),
				     'ADDRESS_PASSWORD'=>_('Parent Password'),
				     'MAIL_ADDRESS'=>_('Mailing Address'),
				     'MAIL_CITY'=>_('Mailing City'),
				     'MAIL_STATE'=>_('Mailing State'),
				     'MAIL_ZIPCODE'=>_('Mailing Zipcode'),
				     'PARENTS'=>_('Contacts'),
				     'MAILTO_LABEL'=>_('Mail Label'),
				     'CITY_STATE'=>_('City, State'),
				     'MAIL_CITY_STATE'=>_('Mailing City, State'),
				     'ENTIRE_ADDRESS'=>_('Address City, State Zipcode'),
				     'ENTIRE_MAILING_ADDRESS'=>_('Mailing Address City, State Zipcode'));
	
		if($addition['field_names'])
			$fields_list += $addition['field_names'];

		if($_REQUEST['system_tab'] == 'AppAdvancedReport.php' || $_REQUEST['servicemod'] == 'mod_apply/AppAdvancedReport.php')
			$fields_list += array('CFIELD_888100'=>_('Competitive Group Title'),'CFIELD_888101'=>_('School Name'),'CFIELD_888102'=>_('Faculty Title'),'CFIELD_888103'=>_('Major Title'),'CFIELD_888104'=>_('Special Subject Title'),'CFIELD_888105'=>_('Competitive Category Title'),'CFIELD_888106'=>_('Form of Education'));
/*
		foreach($_REQUEST['fields'] as $field=>$on)
		{
			if(strpos($field,'+') !== false)
			{
				foreach($fields_array as $lid=>$lfield)
				{
					if('CFIELD_'.$lid == substr($field,strpos($field,'+')+1))
					{
						$ftitle = $lfield[1]['TITLE'];
						$log_title = $lfield[1][substr($field,0,strpos($field,'+')).'_TITLE'];
						$fields_list[str_replace('+','_',$field)] = $ftitle.': '.$log_title;
					}
				}
			}
		}
		*/
		$periods_array = db_request(db_execute("SELECT TITLE,SCHOOL_PERIOD_ID,SHORT_NAME FROM SCHOOL_PERIODS WHERE SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."' ORDER BY SORT_ORDER"));
		foreach($periods_array as $period)
			$fields_list['PERIOD_'.$period['SCHOOL_PERIOD_ID']] = $period['TITLE'].' '._('Teacher - Room');
		$codes_array = db_request(db_execute("SELECT ID,TITLE,IS_DAILY_CODE,SHORT_NAME FROM ATTENDANCE_CODES_SETTINGS WHERE SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."'"));
		foreach($codes_array as $code)
		{
			$fields_list['ATT_'.str_replace(' ','_',$code['SHORT_NAME'])] = _('School Periods').' '.$code['TITLE']._(' YTD');
			$fields_list['ATT_QTR_'.$code['SHORT_NAME']] = _('School Periods').' '.$code['TITLE'].' '.get_school_term(get_user_school_term(),'SHORT_NAME');
		}
		$fields_list['ATT_DAYS_ABS'] = _('Days Absent').' '._('YTD');
		$fields_list['ATT_QTR_DAYS_ABS'] = _('Days Absent').' '.get_school_term(get_user_school_term(),'SHORT_NAME');

		foreach($codes_array as $code)
		{
			if($code['IS_DAILY_CODE']=='Y')
			{
				$fields_list['ATT_DAYS__'.$code['SHORT_NAME']] = _('Days').' '.$code['TITLE'].' '._('YTD');
				$fields_list['ATT_QTR_DAYS__'.$code['SHORT_NAME']] = _('Days').' '.$code['TITLE'].' '.get_school_term(get_user_school_term(),'SHORT_NAME');
			}
		}

		if ($students_table=='STUDENTS')
		{
			foreach($school_fields_array as $school_id=>$school_field)
			{
				if(!$fields_list['SCHOOLS_CFIELD_'.$school_id])
					$fields_list['SCHOOLS_CFIELD_'.$school_id] = $school_field[1]['TITLE'];
			}

			$fields_list['SCHOOL_TITLE'] = _('School Name');
		}

		$fields_list['ATT_DAYS_PRES'] = _('Days Present')._(' YTD');
		$fields_list['ATT_QTR_DAYS_PRES'] = _('Days Present').' '.get_school_term(get_user_school_term(),'SHORT_NAME');

		$fields_list['ATT_DAYS_ENROLLED'] = _('Days Enrolled')._(' YTD');
		$fields_list['ATT_QTR_DAYS_ENROLLED'] = _('Days Enrolled').' '.get_school_term(get_user_school_term(),'SHORT_NAME');

		$fields_list['LAST_MP'] = _('School Term');
		$fields_list['SCHOOL_YEAR'] = _('School Year');
		$fields_list['REPORT_TITLE'] = _('Report Title');
		$fields_list['CURRENT_DATE'] = _('Current Date');
		$fields_list['CURRENT_TIME'] = _('Current Time');
		$gradelevels_array = db_request(db_execute("SELECT ID,SCHOOL_ID,TITLE FROM SCHOOL_CLASSLEVELS WHERE SCHOOL_ID='".get_school_id()."' ORDER BY SORT_ORDER"));
		foreach($gradelevels_array as $gradelevel)
		{
			$fields_list['SEM_GPA_'.$gradelevel['ID']] = $gradelevel['TITLE']._(' Semester GPA');
			$fields_list['SEM_WEIGHTED_GPA_'.$gradelevel['ID']] = $gradelevel['TITLE']._(' Semester Weighted GPA');
			$fields_list['QTR_GPA_'.$gradelevel['ID']] = $gradelevel['TITLE']._(' Quarter GPA');
			$fields_list['QTR_WEIGHTED_GPA_'.$gradelevel['ID']] = $gradelevel['TITLE']._(' Quarter Weighted GPA');
		}
		$fields_list['SEM_GPA'] = _('Cumulative Semester GPA');
		if(SystemPreferences('WEIGHTED_GPA')=='Y')
			$fields_list['SEM_WEIGHTED_GPA'] = _('Cumulative Semester Weighted GPA');
		$fields_list['QTR_GPA'] = _('Cumulative Quarter GPA');
		if(SystemPreferences('WEIGHTED_GPA')=='Y')
			$fields_list['QTR_WEIGHTED_GPA'] = _('Cumulative Quarter Weighted GPA');

		$fields_list['THIS_SEM_GPA'] = _('This Semester GPA');
		if(SystemPreferences('WEIGHTED_GPA')=='Y')
			$fields_list['THIS_SEM_WEIGHTED_GPA'] = _('This Semester Weighted GPA');
		$fields_list['THIS_QTR_GPA'] = _('This Quarter GPA');
		if(SystemPreferences('WEIGHTED_GPA')=='Y')
			$fields_list['THIS_QTR_WEIGHTED_GPA'] = _('This Quarter Weighted GPA');

		$fields_list['YEAR_CLASS_RANK'] = _('Student Rating in Class for Year');
		$fields_list['SEM_CLASS_RANK'] = _('Student Rating in Class for Semester');
		$fields_list['QTR_CLASS_RANK'] = _('Student Rating in Class for Quarter');
		$fields_list['YEAR_GROUP_CLASS_RANK'] = _('Student Rating in Class Group for Year');
		$fields_list['SEM_GROUP_CLASS_RANK'] = _('Student Rating in Class Group for Semester');
		$fields_list['QTR_GROUP_CLASS_RANK'] = _('Student Rating in Class Group for Quarter');
		$fields_list['SEM_CREDITS'] = _('Semester Credits');
		$fields_list['QTR_CREDITS'] = _('Quarter Credits');
		$fields_list['THIS_QTR_AVG_PERCENT'] = _('Current Quarter Average Percent Grade');
		$fields_list['THIS_SEM_AVG_PERCENT'] = _('Current Semester Average Percent Grade');
		$fields_list['ALL_QTR_AVG_PERCENT'] = _('Cumulative Quarter Average Percent Grade');
		$fields_list['ALL_SEM_AVG_PERCENT'] = _('Cumulative Semester Average Percent Grade');
		$fields_list['ALL_YEAR_AVG_PERCENT'] = _('Cumulative Year Average Percent Grade');
    if($contacts){
	foreach($contacts as $contact=>$contact_title)
		{
			foreach($elems as $elem=>$elem_title)
				$fields_list[$contact.'_'.$elem] = $contact_title.': '.$elem_title;
		}
    }
    
		$calculations_array = db_request(db_execute("SELECT ID,TITLE,URL FROM INFO_SAVES ORDER BY TITLE"));
		foreach($calculations_array as $calc)
		{
			$fields_list['CALCULATION_'.$calc['ID']] = $calc['TITLE'];
			$fields_list['GRAPH_'.$calc['ID']] = $calc['TITLE'];
		}
	}
	//here are getting functions and titles by cfields 
	foreach($fields_array as $id=>$field)
	{
		if(!$fields_list['CFIELD_'.$id])
			$fields_list['CFIELD_'.$id] = $field[1]['TITLE'];

			if($students_table == 'STUDENT_DISCIPLINE_INCIDENTS')
				$addition['functions']['CFIELD_'.$id] = '_make';
	}

	// we need a $last_qtr_mp which is the last quarter on the report card for the attendance numbers
	if(!$last_mp)
		$last_mp = get_user_school_term();
	foreach($periods_array as $period)
	{
		if($_REQUEST['month_include_active_date'])
			$date = $_REQUEST['year_include_active_date'].'-'.$_REQUEST['month_include_active_date'].'-'.$_REQUEST['day_include_active_date'];
		else
			$date = get_db_date();
		if($_REQUEST['fields']['PERIOD_'.$period['SCHOOL_PERIOD_ID']])
		{
			if(get_school_id() && $_REQUEST['_search_all_schools']!='Y')
			{
				$schools_extra = " SCHOOL_ID='".get_school_id()."' ";
				$periods_extra = " cp.SCHOOL_PERIOD_ID='".$period['SCHOOL_PERIOD_ID']."'";
				$mp_extra = " AND ss.SCHOOL_TERM_ID IN (".get_all_school_term('QTR',get_user_school_term()).") ";
			}
			else
			{
				$schools = substr(str_replace(",","','",get_user('SCHOOLS')),2,-2);
				if($schools)
				{
						$schools_extra = " SCHOOL_ID IN ($schools) ";
				}
				else
				{
					$schools_extra = 'true';
				}

				if($period['SHORT_NAME'])
					$short_names_array = db_request(db_execute("SELECT SCHOOL_PERIOD_ID FROM SCHOOL_PERIODS WHERE SHORT_NAME='".$period['SHORT_NAME']."' AND ".$schools_extra));
				$periods_extra = " cp.SCHOOL_PERIOD_ID IN (";
				foreach($short_names_array as $id)
					$periods_extra .= "'".$id['SCHOOL_PERIOD_ID']."',";
				$periods_extra = substr($periods_extra,0,-1);
				$periods_extra .= ") ";
				$mp_extra = '';
			}
			$addition['SELECT'] .= ",(".db_limit("SELECT COALESCE(st.FIRST_NAME,' ')".CCAT."' '".CCAT."COALESCE(st.LAST_NAME,' ')".CCAT."' - '".CCAT."COALESCE(cp.ROOM,' ') FROM USERS st,STUDENT_SCHEDULE ss,COURSE_SECTIONS cp WHERE ss.STUDENT_ID=ssm.STUDENT_ID AND cp.COURSE_SECTION_ID=ss.COURSE_SECTION_ID AND cp.TEACHER_ID=st.USER_ID AND ".$periods_extra." AND ('".$date."' BETWEEN ss.START_DATE AND ss.END_DATE OR ('".$date."'>=ss.START_DATE AND ss.END_DATE IS NULL)) ".$mp_extra." ORDER BY ss.START_DATE ",1).") AS PERIOD_".$period['SCHOOL_PERIOD_ID'];
		}
	}
	foreach($codes_array as $code)
	{
		if($_REQUEST['fields']['ATT_'.str_replace(' ','_',$code['SHORT_NAME'])])
		{
			$end_date = get_db_date();
			$min_date = db_request(db_execute("SELECT ".db_to_char('min(SCHOOL_DATE)', 'yyyy-mm-dd')." 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'])
				$start_date = $min_date[1]['MIN_DATE'];
			else
				$start_date = (get_school_year()).'-08-01';

			$att_extra['ap'.str_replace(' ','_',$code['SHORT_NAME'])] = $addition;
			$att_extra['ap'.str_replace(' ','_',$code['SHORT_NAME'])]['allow_duplicates'] = true;
			$old_include_inactive = $_REQUEST['include_inactive'];
			$_REQUEST['include_inactive'] = 'Y';

			unset($att_extra['ap'.str_replace(' ','_',$code['SHORT_NAME'])]['SELECT']);
			$att_extra['ap'.str_replace(' ','_',$code['SHORT_NAME'])]['SELECT_ONLY'] = 'COUNT(*) AS ATT_SUM,ssm.STUDENT_ID';

			$att_extra['ap'.str_replace(' ','_',$code['SHORT_NAME'])]['FROM'] .= ',STUDENT_ATTENDANCE_PERIODS ap,ATTENDANCE_CODES_SETTINGS ac,STUDENT_SCHEDULE sched';
			$att_extra['ap'.str_replace(' ','_',$code['SHORT_NAME'])]['WHERE'] .= " AND ap.STUDENT_ID=ssm.STUDENT_ID AND sched.STUDENT_ID=ssm.STUDENT_ID AND sched.COURSE_SECTION_ID=ap.COURSE_SECTION_ID
								AND ap.SCHOOL_DATE BETWEEN '$start_date' AND '$end_date'
								AND ap.ATTENDANCE_CODE=ac.ID AND ac.SHORT_NAME='".$code['SHORT_NAME']."'
								AND (ap.SCHOOL_DATE BETWEEN ssm.START_DATE AND ssm.END_DATE OR (ssm.END_DATE IS NULL AND ap.SCHOOL_DATE>=ssm.START_DATE))
								AND (ap.SCHOOL_DATE BETWEEN sched.START_DATE AND sched.END_DATE OR (sched.END_DATE IS NULL AND ap.SCHOOL_DATE>=sched.START_DATE))
								";
			$att_extra['ap'.str_replace(' ','_',$code['SHORT_NAME'])]['GROUP'] = 'ssm.STUDENT_ID';
			$att_extra['ap'.str_replace(' ','_',$code['SHORT_NAME'])]['group'] = array('STUDENT_ID');

			$_SYSTEM['array_ATT_'.str_replace(' ','_',$code['SHORT_NAME'])] = get_student_list($att_extra['ap'.str_replace(' ','_',$code['SHORT_NAME'])]);
			$_REQUEST['include_inactive'] = $old_include_inactive;

//var_dump($att_extra);
//var_dump($addition['functions']);

			$addition['SELECT'] .= ",NULL AS ATT_".str_replace(' ','_',$code['SHORT_NAME']);
			$addition['functions']['ATT_'.str_replace(' ','_',$code['SHORT_NAME'])] = '_makeAttTotal';
		}

		// COPIED FROM ABOVE ALMOST EXACTLY
		if($_REQUEST['fields']['ATT_QTR_'.str_replace(' ','_',$code['SHORT_NAME'])])
		{
			// get attendance this quarter -- date to present, unless the quarter is already over
			if($last_mp && get_school_term($last_mp,'MP_TABLE')=='SCHOOL_WEEKS' && get_school_term($last_mp,'POSTGRES_END_DATE'))
				$att_mp = $last_mp;
			else
				$att_mp = get_user_school_term();

			$start_date = get_school_term($att_mp,'START_DATE');
			// get the att this quarter - date to present, unless the quarter is already over.
			if(str_replace('-','',get_db_date('postgres'))<str_replace('-','',get_school_term($att_mp,'POSTGRES_END_DATE')))
				$end_date = get_db_date();
			else
				$end_date = get_school_term($att_mp,'END_DATE');

			$att_extra['aqp'.$code['SHORT_NAME']] = $addition;
			// allow_duplicates & include_inactive must be true so that all attendance records are counted if the student left the school and came back
			$att_extra['aqp'.$code['SHORT_NAME']]['allow_duplicates'] = true;
			$old_include_inactive = $_REQUEST['include_inactive'];
			$_REQUEST['include_inactive'] = 'Y';

			unset($att_extra['aqp'.$code['SHORT_NAME']]['SELECT']);
			$att_extra['aqp'.$code['SHORT_NAME']]['SELECT_ONLY'] = 'COUNT(*) AS ATT_SUM,ssm.STUDENT_ID';

			$att_extra['aqp'.$code['SHORT_NAME']]['FROM'] .= ',STUDENT_ATTENDANCE_PERIODS ap,ATTENDANCE_CODES_SETTINGS ac,STUDENT_SCHEDULE sched';
			$att_extra['aqp'.$code['SHORT_NAME']]['WHERE'] .= " AND ap.STUDENT_ID=ssm.STUDENT_ID AND sched.STUDENT_ID=ssm.STUDENT_ID AND sched.COURSE_SECTION_ID=ap.COURSE_SECTION_ID
								AND ap.SCHOOL_DATE BETWEEN '$start_date' AND '$end_date'
								AND ap.ATTENDANCE_CODE=ac.ID AND ac.SHORT_NAME='".$code['SHORT_NAME']."'
								AND (ap.SCHOOL_DATE BETWEEN ssm.START_DATE AND ssm.END_DATE OR (ssm.END_DATE IS NULL AND ap.SCHOOL_DATE>=ssm.START_DATE))
								AND (ap.SCHOOL_DATE BETWEEN sched.START_DATE AND sched.END_DATE OR (sched.END_DATE IS NULL AND ap.SCHOOL_DATE>=sched.START_DATE))
								";
			$att_extra['aqp'.$code['SHORT_NAME']]['GROUP'] = 'ssm.STUDENT_ID';
			$att_extra['aqp'.$code['SHORT_NAME']]['group'] = array('STUDENT_ID');

			$_SYSTEM['array_ATT_QTR_'.$code['SHORT_NAME']] = get_student_list($att_extra['aqp'.$code['SHORT_NAME']]);
			$_REQUEST['include_inactive'] = $old_include_inactive;

			$addition['SELECT'] .= ",NULL AS ATT_QTR_".$code['SHORT_NAME'];
			$addition['functions']['ATT_QTR_'.$code['SHORT_NAME']] = '_makeAttTotal';
		}
	}

	foreach($codes_array as $code)
	{
		if($code['IS_DAILY_CODE']=='Y')
		{
			if($_REQUEST['fields']['ATT_DAYS__'.$code['SHORT_NAME']])
			{
				$end_date = get_db_date();
				$min_date = db_request(db_execute("SELECT ".db_to_char('min(SCHOOL_DATE)', 'yyyy-mm-dd')." 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'])
					$start_date = $min_date[1]['MIN_DATE'];
				else
					$start_date = (get_school_year()).'-08-01';
				$att_extra['ad'.$code['SHORT_NAME']] = $addition;
				unset($att_extra['ad'.$code['SHORT_NAME']]['SELECT']);
				$att_extra['ad'.$code['SHORT_NAME']]['SELECT_ONLY'] = 'COALESCE((SUM((ad.STATE_VALUE-1))*-1),0.0) AS ATT_SUM,ssm.STUDENT_ID';

				$att_extra['ad'.$code['SHORT_NAME']]['FROM'] .= ',STUDENT_ATTENDANCE_DAYS ad,SCHOOL_CALENDAR_DAYS ac ';
				$att_extra['ad'.$code['SHORT_NAME']]['WHERE'] .= " AND ad.STUDENT_ID=ssm.STUDENT_ID AND ad.SCHOOL_DATE=ac.SCHOOL_DATE AND ac.CALENDAR_ID=ssm.CALENDAR_ID
									AND ad.SCHOOL_DATE BETWEEN '$start_date' AND '$end_date'
									AND ad.DAILY_CODE='".$code['SHORT_NAME']."'
									AND (ad.SCHOOL_DATE BETWEEN ssm.START_DATE AND ssm.END_DATE OR (ssm.END_DATE IS NULL AND ad.SCHOOL_DATE>=ssm.START_DATE))";
				$att_extra['ad'.$code['SHORT_NAME']]['GROUP'] = 'ssm.STUDENT_ID';
				$att_extra['ad'.$code['SHORT_NAME']]['group'] = array('STUDENT_ID');

				$_SYSTEM['array_ATT_DAYS__'.$code['SHORT_NAME']] = get_student_list($att_extra['ad'.$code['SHORT_NAME']]);

				// We have to do both these subqueries for ATT_DAYS_PRES
				$addition['SELECT'] .= ",NULL AS ATT_DAYS__".str_replace(' ','_',$code['SHORT_NAME']);
				$addition['functions']['ATT_DAYS__'.str_replace(' ','_',$code['SHORT_NAME'])] = '_makeAttTotal';
			}
			// copied almost exactly from above
			if($_REQUEST['fields']['ATT_QTR_DAYS__'.$code['SHORT_NAME']])
			{
			// get attendance this quarter -- date to present, unless the quarter is already over
				$start_date = get_school_term(get_user_school_term(),'START_DATE');
				if(str_replace('-','',get_db_date('postgres'))<str_replace('-','',get_school_term(get_user_school_term(),'POSTGRES_END_DATE')))
					$end_date = get_db_date();
				else
					$end_date = get_school_term(get_user_school_term(),'END_DATE');
				if($start_date && $end_date)
				{
					$att_extra['aqd'.$code['SHORT_NAME']] = $addition;
					unset($att_extra['aqd'.$code['SHORT_NAME']]['SELECT']);
					$att_extra['aqd'.$code['SHORT_NAME']]['SELECT_ONLY'] = 'COALESCE((SUM((ad.STATE_VALUE-1))*-1),0.0) AS ATT_SUM,ssm.STUDENT_ID';

					$att_extra['aqd'.$code['SHORT_NAME']]['FROM'] .= ',STUDENT_ATTENDANCE_DAYS ad,SCHOOL_CALENDAR_DAYS ac ';
					$att_extra['aqd'.$code['SHORT_NAME']]['WHERE'] .= " AND ad.STUDENT_ID=ssm.STUDENT_ID  AND ad.SCHOOL_DATE=ac.SCHOOL_DATE AND ac.CALENDAR_ID=ssm.CALENDAR_ID
										AND ad.SCHOOL_DATE BETWEEN '$start_date' AND '$end_date'
										AND ad.DAILY_CODE='".$code['SHORT_NAME']."'
										AND (ad.SCHOOL_DATE BETWEEN ssm.START_DATE AND ssm.END_DATE OR (ssm.END_DATE IS NULL AND ad.SCHOOL_DATE>=ssm.START_DATE))";
					$att_extra['aqd'.$code['SHORT_NAME']]['GROUP'] = 'ssm.STUDENT_ID';
					$att_extra['aqd'.$code['SHORT_NAME']]['group'] = array('STUDENT_ID');

					$_SYSTEM['array_ATT_QTR_DAYS__'.$code['SHORT_NAME']] = get_student_list($att_extra['aqd'.$code['SHORT_NAME']]);

					// We have to do both these subqueries for ATT_DAYS_PRES
					$addition['SELECT'] .= ",NULL AS ATT_QTR_DAYS__".$code['SHORT_NAME'];
					$addition['functions']['ATT_QTR_DAYS__'.$code['SHORT_NAME']] = '_makeAttTotal';
				}
			}
		}
	}

	// days fy
	if($_REQUEST['fields']['ATT_DAYS_ABS'] || $_REQUEST['fields']['ATT_DAYS_ENROLLED'] || $_REQUEST['fields']['ATT_DAYS_PRES'])
	{
		if(!$_REQUEST['attendance_end_date'])
			$end_date = get_db_date();
		else
			$end_date = $_REQUEST['attendance_end_date'];
		$min_date = db_request(db_execute("SELECT ".db_to_char('min(SCHOOL_DATE)', 'yyyy-mm-dd')." 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'])
			$start_date = $min_date[1]['MIN_DATE'];
		else
			$start_date = (get_school_year()).'-08-01';

		// We have to do both these subqueries for ATT_DAYS_PRES
		$addition['SELECT'] .= ",(SELECT COALESCE((SUM((STATE_VALUE-1))),0.0)*-1 FROM STUDENT_ATTENDANCE_DAYS ad,SCHOOL_CALENDAR_DAYS ac
						WHERE ad.STUDENT_ID=ssm.STUDENT_ID AND ad.SCHOOL_DATE=ac.SCHOOL_DATE AND ac.CALENDAR_ID=ssm.CALENDAR_ID
						AND ad.SCHOOL_DATE BETWEEN '$start_date' AND '$end_date'
						AND (ad.SCHOOL_DATE BETWEEN ssm.START_DATE AND ssm.END_DATE OR (ssm.END_DATE IS NULL AND ad.SCHOOL_DATE>=ssm.START_DATE))
						) AS ATT_DAYS_ABS";

		$addition['SELECT'] .= ",(SELECT COUNT(*) FROM SCHOOL_CALENDAR_DAYS ac
						WHERE ac.CALENDAR_ID=ssm.CALENDAR_ID
						AND ac.SCHOOL_DATE BETWEEN '$start_date' AND '$end_date'
						AND (ac.SCHOOL_DATE BETWEEN ssm.START_DATE AND ssm.END_DATE OR (ssm.END_DATE IS NULL AND ac.SCHOOL_DATE>=ssm.START_DATE))
						) AS ATT_DAYS_ENROLLED";

		$addition['SELECT'] .= ',NULL AS ATT_DAYS_PRES';
		if(!$addition['functions']['ATT_DAYS_PRES']) // MICHIGAN SRSD REPORTS CALLS _makeAttDaysPres, but does additional formatting
			$addition['functions']['ATT_DAYS_PRES'] = '_makeAttDaysPres';

	}

	// days qtr
	if($_REQUEST['fields']['ATT_QTR_DAYS_ABS'] || $_REQUEST['fields']['ATT_QTR_DAYS_ENROLLED'] || $_REQUEST['fields']['ATT_QTR_DAYS_PRES'])
	{
		$start_date = get_school_term(get_user_school_term(),'START_DATE');
		// get the att this quarter - date to present, unless the quarter is already over.
		if(str_replace('-','',get_db_date('postgres'))<str_replace('-','',get_school_term(get_user_school_term(),'POSTGRES_END_DATE')))
			$end_date = get_db_date();
		else
			$end_date = get_school_term(get_user_school_term(),'END_DATE');

		if($start_date && $end_date)
		{
			// We have to do both these subqueries for ATT_DAYS_PRES
			$addition['SELECT'] .= ",(SELECT COALESCE((SUM((STATE_VALUE-1))),0.0)*-1 FROM STUDENT_ATTENDANCE_DAYS ad,SCHOOL_CALENDAR_DAYS ac
							WHERE ad.STUDENT_ID=ssm.STUDENT_ID AND ad.SCHOOL_DATE=ac.SCHOOL_DATE AND ac.CALENDAR_ID=ssm.CALENDAR_ID
							AND ad.SCHOOL_DATE BETWEEN '$start_date' AND '$end_date'
							AND (ad.SCHOOL_DATE BETWEEN ssm.START_DATE AND ssm.END_DATE OR (ssm.END_DATE IS NULL AND ad.SCHOOL_DATE>=ssm.START_DATE))
							) AS ATT_QTR_DAYS_ABS";

			$addition['SELECT'] .= ",(SELECT COUNT(*) FROM SCHOOL_CALENDAR_DAYS ac
							WHERE ac.CALENDAR_ID=ssm.CALENDAR_ID
							AND ac.SCHOOL_DATE BETWEEN '$start_date' AND '$end_date'
							AND (ac.SCHOOL_DATE BETWEEN ssm.START_DATE AND ssm.END_DATE OR (ssm.END_DATE IS NULL AND ac.SCHOOL_DATE>=ssm.START_DATE))
							) AS ATT_QTR_DAYS_ENROLLED";

			$addition['SELECT'] .= ',NULL AS ATT_QTR_DAYS_PRES';
			$addition['functions']['ATT_QTR_DAYS_PRES'] = '_makeAttDaysPres';
		}
	}

	// ITEMS FROM OLD DisplayHeader(), Doc Templates
	if($_REQUEST['fields']['CITY_STATE'])
		$addition['SELECT'] .= ",a.CITY".CCAT."', '".CCAT."a.STATE AS CITY_STATE";

	if($_REQUEST['fields']['MAIL_CITY_STATE'])
		$addition['SELECT'] .= ",COALESCE(a.MAIL_CITY,a.CITY)".CCAT."', '".CCAT."COALESCE(a.MAIL_STATE,a.STATE) AS MAIL_CITY_STATE";

	if($_REQUEST['fields']['ENTIRE_ADDRESS'])
		$addition['SELECT'] .= ",a.ADDRESS".CCAT."' '".CCAT."a.CITY".CCAT."', '".CCAT."a.STATE".CCAT."' '".CCAT."a.ZIPCODE AS ENTIRE_ADDRESS";

	if($_REQUEST['fields']['ENTIRE_MAILING_ADDRESS'])
		$addition['SELECT'] .= ",COALESCE(a.MAIL_ADDRESS,a.ADDRESS)".CCAT."' '".CCAT."COALESCE(a.MAIL_CITY,a.CITY)".CCAT."', '".CCAT."COALESCE(a.MAIL_STATE,a.STATE)".CCAT."' '".CCAT."COALESCE(a.MAIL_ZIPCODE,a.ZIPCODE) AS ENTIRE_MAILING_ADDRESS";

	if($_REQUEST['fields']['SEM_GPA'])
	{
		$addition['SELECT'] .= ',('.db_limit('SELECT sgc.CUMULATIVE_GPA FROM STUDENT_GPA_TOTALS sgc,SCHOOL_SEMESTERS m WHERE sgc.STUDENT_ID=ssm.STUDENT_ID AND sgc.SCHOOL_TERM_ID=m.SCHOOL_TERM_ID ORDER BY m.SCHOOL_YEAR DESC,m.SORT_ORDER DESC,m.TITLE DESC ',1).') AS SEM_GPA';
		$addition['functions']['SEM_GPA'] = 'RoundGPA';
	}

	if($_REQUEST['fields']['QTR_GPA'])
	{
		$addition['SELECT'] .= ',('.db_limit('SELECT sgc.CUMULATIVE_GPA FROM STUDENT_GPA_TOTALS sgc,SCHOOL_QUARTERS m WHERE sgc.STUDENT_ID=ssm.STUDENT_ID AND sgc.SCHOOL_TERM_ID=m.SCHOOL_TERM_ID ORDER BY m.SCHOOL_YEAR DESC,m.SORT_ORDER DESC,m.TITLE DESC ',1).') AS QTR_GPA';
		$addition['functions']['QTR_GPA'] = 'RoundGPA';
	}

	if($_REQUEST['fields']['SEM_WEIGHTED_GPA'])
	{
		$addition['SELECT'] .= ',('.db_limit('SELECT sgc.CUMULATIVE_WEIGHTED_GPA FROM STUDENT_GPA_TOTALS sgc,SCHOOL_SEMESTERS m WHERE sgc.STUDENT_ID=ssm.STUDENT_ID AND sgc.SCHOOL_TERM_ID=m.SCHOOL_TERM_ID ORDER BY m.SCHOOL_YEAR DESC,m.SORT_ORDER DESC,m.TITLE DESC ',1).') AS SEM_WEIGHTED_GPA';
		$addition['functions']['SEM_WEIGHTED_GPA'] = 'RoundGPA';
	}

	if($_REQUEST['fields']['QTR_WEIGHTED_GPA'])
	{
		$addition['SELECT'] .= ',('.db_limit('SELECT sgc.CUMULATIVE_WEIGHTED_GPA FROM STUDENT_GPA_TOTALS sgc,SCHOOL_QUARTERS m WHERE sgc.STUDENT_ID=ssm.STUDENT_ID AND sgc.SCHOOL_TERM_ID=m.SCHOOL_TERM_ID ORDER BY m.SCHOOL_YEAR DESC,m.SORT_ORDER DESC,m.TITLE DESC ',1).') AS QTR_WEIGHTED_GPA';
		$addition['functions']['QTR_WEIGHTED_GPA'] = 'RoundGPA';
	}

	if($_REQUEST['fields']['THIS_SEM_GPA'])
	{
		$addition['SELECT'] .= ',('.db_limit('SELECT sgc.GPA FROM STUDENT_GPA_TOTALS sgc,SCHOOL_SEMESTERS m WHERE sgc.STUDENT_ID=ssm.STUDENT_ID AND sgc.SCHOOL_TERM_ID=m.SCHOOL_TERM_ID ORDER BY m.SCHOOL_YEAR DESC,m.SORT_ORDER DESC,m.TITLE DESC ',1).') AS THIS_SEM_GPA';
		$addition['functions']['THIS_SEM_GPA'] = 'RoundGPA';
	}

	if($_REQUEST['fields']['THIS_QTR_GPA'])
	{
		$addition['SELECT'] .= ',('.db_limit('SELECT sgc.GPA FROM STUDENT_GPA_TOTALS sgc,SCHOOL_QUARTERS m WHERE sgc.STUDENT_ID=ssm.STUDENT_ID AND sgc.SCHOOL_TERM_ID=m.SCHOOL_TERM_ID ORDER BY m.SCHOOL_YEAR DESC,m.SORT_ORDER DESC,m.TITLE DESC ',1).') AS THIS_QTR_GPA';
		$addition['functions']['THIS_QTR_GPA'] = 'RoundGPA';
	}

	if($_REQUEST['fields']['THIS_SEM_WEIGHTED_GPA'])
	{
		$addition['SELECT'] .= ',('.db_limit('SELECT sgc.WEIGHTED_GPA FROM STUDENT_GPA_TOTALS sgc,SCHOOL_SEMESTERS m WHERE sgc.STUDENT_ID=ssm.STUDENT_ID AND sgc.SCHOOL_TERM_ID=m.SCHOOL_TERM_ID ORDER BY m.SCHOOL_YEAR DESC,m.SORT_ORDER DESC,m.TITLE DESC ',1).') AS THIS_SEM_WEIGHTED_GPA';
		$addition['functions']['THIS_SEM_WEIGHTED_GPA'] = 'RoundGPA';
	}

	if($_REQUEST['fields']['THIS_QTR_WEIGHTED_GPA'])
	{
		$addition['SELECT'] .= ',('.db_limit('SELECT sgc.WEIGHTED_GPA FROM STUDENT_GPA_TOTALS sgc,SCHOOL_QUARTERS m WHERE sgc.STUDENT_ID=ssm.STUDENT_ID AND sgc.SCHOOL_TERM_ID=m.SCHOOL_TERM_ID ORDER BY m.SCHOOL_YEAR DESC,m.SORT_ORDER DESC,m.TITLE DESC ',1).') AS THIS_QTR_WEIGHTED_GPA';
		$addition['functions']['THIS_QTR_WEIGHTED_GPA'] = 'RoundGPA';
	}

	foreach($gradelevels_array as $gradelevel)
	{
		if($_REQUEST['fields']['SEM_GPA_'.$gradelevel['ID']])
		{
			$addition['SELECT'] .= ',('.db_limit('SELECT sgc.CUMULATIVE_GPA FROM STUDENT_GPA_TOTALS sgc,SCHOOL_SEMESTERS m WHERE sgc.STUDENT_ID=ssm.STUDENT_ID AND sgc.SCHOOL_TERM_ID=m.SCHOOL_TERM_ID AND sgc.CLASSLEVEL_ID=\''.$gradelevel['ID'].'\' ORDER BY m.SCHOOL_YEAR DESC,m.SORT_ORDER DESC,m.TITLE DESC ',1).') AS SEM_GPA_'.$gradelevel['ID'];
			$addition['functions']['SEM_GPA_'.$gradelevel['ID']] = 'RoundGPA';
		}

		if($_REQUEST['fields']['QTR_GPA_'.$gradelevel['ID']])
		{
			$addition['SELECT'] .= ',('.db_limit('SELECT sgc.CUMULATIVE_GPA FROM STUDENT_GPA_TOTALS sgc,SCHOOL_QUARTERS m WHERE sgc.STUDENT_ID=ssm.STUDENT_ID AND sgc.SCHOOL_TERM_ID=m.SCHOOL_TERM_ID AND sgc.CLASSLEVEL_ID=\''.$gradelevel['ID'].'\' ORDER BY m.SCHOOL_YEAR DESC,m.SORT_ORDER DESC,m.TITLE DESC ',1).') AS QTR_GPA_'.$gradelevel['ID'];
			$addition['functions']['QTR_GPA_'.$gradelevel['ID']] = 'RoundGPA';
		}

		if($_REQUEST['fields']['SEM_WEIGHTED_GPA_'.$gradelevel['ID']])
		{
			$addition['SELECT'] .= ',('.db_limit('SELECT sgc.CUMULATIVE_WEIGHTED_GPA FROM STUDENT_GPA_TOTALS sgc,SCHOOL_SEMESTERS m WHERE sgc.STUDENT_ID=ssm.STUDENT_ID AND sgc.SCHOOL_TERM_ID=m.SCHOOL_TERM_ID AND sgc.CLASSLEVEL_ID=\''.$gradelevel['ID'].'\' ORDER BY m.SCHOOL_YEAR DESC,m.SORT_ORDER DESC,m.TITLE DESC ',1).') AS SEM_WEIGHTED_GPA_'.$gradelevel['ID'];
			$addition['functions']['SEM_WEIGHTED_GPA_'.$gradelevel['ID']] = 'RoundGPA';
		}

		if($_REQUEST['fields']['QTR_WEIGHTED_GPA_'.$gradelevel['ID']])
		{
			$addition['SELECT'] .= ',('.db_limit('SELECT sgc.CUMULATIVE_WEIGHTED_GPA FROM STUDENT_GPA_TOTALS sgc,SCHOOL_QUARTERS m WHERE sgc.STUDENT_ID=ssm.STUDENT_ID AND sgc.SCHOOL_TERM_ID=m.SCHOOL_TERM_ID AND sgc.CLASSLEVEL_ID=\''.$gradelevel['ID'].'\' ORDER BY m.SCHOOL_YEAR DESC,m.SORT_ORDER DESC,m.TITLE DESC ',1).') AS QTR_WEIGHTED_GPA_'.$gradelevel['ID'];
			$addition['functions']['QTR_WEIGHTED_GPA_'.$gradelevel['ID']] = 'RoundGPA';
		}
	}
	if($_REQUEST['fields']['YEAR_CLASS_RANK'])
//		$addition['SELECT'] .= ",(SELECT trunc(AVG(sgc.CLASS_RANK),1)".CCAT."'/'".CCAT."trunc(AVG(sgc.GRADE_TOTAL)) FROM STUDENT_GPA_TOTALS sgc,SCHOOL_SEMESTERS m WHERE sgc.STUDENT_ID=ssm.STUDENT_ID AND sgc.SCHOOL_TERM_ID IN (".GetAllTerms('SCHOOL_SEMESTERS').") ) AS YEAR_CLASS_RANK";
//		$addition['SELECT'] .= ",(".db_limit("SELECT sgc.CLASS_RANK,".CCAT."'/'".CCAT."sgc.GRADE_TOTAL FROM STUDENT_GPA_TOTALS sgc,SCHOOL_SEMESTERS m WHERE sgc.STUDENT_ID=ssm.STUDENT_ID AND sgc.SCHOOL_TERM_ID IN (".GetAllTerms('SCHOOL_SEMESTERS').") ) AS YEAR_CLASS_RANK";
		$addition['SELECT'] .= ",(".db_limit("SELECT ".db_cast("sgc.CLASS_RANK","VARCHAR").CCAT."'/'".CCAT.db_cast("sgc.GRADE_TOTAL","VARCHAR")." FROM STUDENT_GPA_TOTALS sgc,SCHOOL_SEMESTERS m WHERE sgc.STUDENT_ID=ssm.STUDENT_ID AND sgc.SCHOOL_TERM_ID=m.SCHOOL_TERM_ID ORDER BY m.SCHOOL_YEAR DESC,m.SORT_ORDER DESC,m.TITLE DESC ",1).") AS YEAR_CLASS_RANK";
		//$addition['SELECT'] .= ",(".db_limit("SELECT sgc.CLASS_RANK".CCAT."'/'".CCAT."sgc.GRADE_TOTAL FROM STUDENT_GPA_TOTALS sgc,SCHOOL_SEMESTERS m WHERE sgc.STUDENT_ID=ssm.STUDENT_ID AND sgc.SCHOOL_TERM_ID=336 ORDER BY m.SCHOOL_YEAR DESC,m.SORT_ORDER DESC,m.TITLE DESC ",1).") AS YEAR_CLASS_RANK";
	
	if($_REQUEST['fields']['SEM_CLASS_RANK'])
		$addition['SELECT'] .= ",(".db_limit("SELECT ".db_cast("sgc.CLASS_RANK","VARCHAR").CCAT."'/'".CCAT.db_cast("sgc.GRADE_TOTAL","VARCHAR")." FROM STUDENT_GPA_TOTALS sgc,SCHOOL_SEMESTERS m WHERE sgc.STUDENT_ID=ssm.STUDENT_ID AND sgc.SCHOOL_TERM_ID=m.SCHOOL_TERM_ID ORDER BY m.SCHOOL_YEAR DESC,m.SORT_ORDER DESC,m.TITLE DESC ",1).") AS SEM_CLASS_RANK";

	if($_REQUEST['fields']['QTR_CLASS_RANK'])
		$addition['SELECT'] .= ",(".db_limit("SELECT ".db_cast("sgc.CLASS_RANK","VARCHAR").CCAT."'/'".CCAT.db_cast("sgc.GRADE_TOTAL","VARCHAR")." FROM STUDENT_GPA_TOTALS sgc,SCHOOL_QUARTERS m WHERE sgc.STUDENT_ID=ssm.STUDENT_ID AND sgc.SCHOOL_TERM_ID=m.SCHOOL_TERM_ID ORDER BY m.SCHOOL_YEAR DESC,m.SORT_ORDER DESC,m.TITLE DESC ",1).") AS QTR_CLASS_RANK";

	if($_REQUEST['fields']['SEM_CREDITS'])
		$addition['SELECT'] .= ',(SELECT SUM(CREDITS) FROM STUDENT_GRADES_CARD WHERE CARRIES_CREDITS=\'Y\' AND STUDENT_ID=ssm.STUDENT_ID AND SCHOOL_TERM_ID IN ('.GetAllTerms('SCHOOL_SEMESTERS').')) AS SEM_CREDITS';

	if($_REQUEST['fields']['QTR_CREDITS'])
		$addition['SELECT'] .= ',(SELECT SUM(CREDITS) FROM STUDENT_GRADES_CARD WHERE CARRIES_CREDITS=\'Y\' AND STUDENT_ID=ssm.STUDENT_ID AND SCHOOL_TERM_ID IN ('.GetAllTerms('SCHOOL_QUARTERS').')) AS QTR_CREDITS';

	if($_REQUEST['fields']['THIS_QTR_AVG_PERCENT'])
	{
		$addition['SELECT'] .= ",(SELECT AVG(asrcg.PERCENT_GRADE)/100 FROM STUDENT_GRADES_CARD asrcg WHERE asrcg.STUDENT_ID=ssm.STUDENT_ID AND asrcg.SCHOOL_TERM_ID='".$last_mp."') AS THIS_QTR_AVG_PERCENT";
		$addition['functions']['THIS_QTR_AVG_PERCENT'] = 'Percent';
	}

	if($_REQUEST['fields']['THIS_QTR_AVG_GRADE'])
	{
		$addition['SELECT'] .= ",(SELECT AVG(asrcg.PERCENT_GRADE)/100 FROM STUDENT_GRADES_CARD asrcg WHERE asrcg.STUDENT_ID=ssm.STUDENT_ID AND asrcg.SCHOOL_TERM_ID='".$last_mp."') AS THIS_QTR_AVG_GRADE";
		$addition['functions']['THIS_QTR_AVG_GRADE'] = 'getLetterGrade';
	}

	if($_REQUEST['fields']['THIS_SEM_AVG_PERCENT'])
	{
//		echo ">>".get_all_school_termByDate(date("Y-m-d"),'POSTGRES',get_school_id(),'SCHOOL_SEMESTERS');
//		echo ">>".get_all_school_termByDate(date("Y-m-d"),'POSTGRES',0,'SCHOOL_SEMESTERS');
		if(!get_parent_school_term('SEM',$last_mp))
		{
//			$cur_sem = get_school_term_by_date
			$cur_sem = get_all_school_termByDate(date("Y-m-d"),'POSTGRES',0,'SCHOOL_SEMESTERS');
			$cur_sem = substr($cur_sem,1,strlen($cur_sem)-2);
//			echo "|$cur_sem|";
		}
		else
			$cur_sem = get_parent_school_term('SEM',$last_mp);
//			var_dump($last_mp);
//		var_dump($cur_sem);
		$addition['SELECT'] .= ",(SELECT AVG(asrcg.PERCENT_GRADE)/100 FROM STUDENT_GRADES_CARD asrcg WHERE asrcg.STUDENT_ID=ssm.STUDENT_ID AND asrcg.SCHOOL_TERM_ID IN ('".$cur_sem."')) AS THIS_SEM_AVG_PERCENT";
//		$addition['SELECT'] .= ",(SELECT AVG(asrcg.PERCENT_GRADE)/100 FROM STUDENT_GRADES_CARD asrcg WHERE asrcg.STUDENT_ID=ssm.STUDENT_ID AND asrcg.SCHOOL_TERM_ID='".$last_mp."') AS THIS_SEM_AVG_PERCENT";
		$addition['functions']['THIS_SEM_AVG_PERCENT'] = 'Percent';
//		echo "last st====>".$last_mp."==".get_parent_school_term('SEM',$last_mp);
	}

	if($_REQUEST['fields']['THIS_SEM_AVG_GRADE'])
	{
		if(!get_parent_school_term('SEM',$last_mp))
		{
			$cur_sem = get_all_school_termByDate(date("Y-m-d"),'POSTGRES',0,'SCHOOL_SEMESTERS');
			$cur_sem = substr($cur_sem,1,strlen($cur_sem)-2);
		}
		else
			$cur_sem = get_parent_school_term('SEM',$last_mp);
		$addition['SELECT'] .= ",(SELECT AVG(asrcg.PERCENT_GRADE)/100 FROM STUDENT_GRADES_CARD asrcg WHERE asrcg.STUDENT_ID=ssm.STUDENT_ID AND asrcg.SCHOOL_TERM_ID IN ('".$cur_sem."')) AS THIS_SEM_AVG_GRADE";
		$addition['functions']['THIS_SEM_AVG_GRADE'] = 'getLetterGrade';
	}

	if($_REQUEST['fields']['THIS_SEM_AVG_GRADE_DESC'])
	{
		if(!get_parent_school_term('SEM',$last_mp))
		{
			$cur_sem = get_all_school_termByDate(date("Y-m-d"),'POSTGRES',0,'SCHOOL_SEMESTERS');
			$cur_sem = substr($cur_sem,1,strlen($cur_sem)-2);
		}
		else
			$cur_sem = get_parent_school_term('SEM',$last_mp);
		$addition['SELECT'] .= ",(SELECT AVG(asrcg.PERCENT_GRADE)/100 FROM STUDENT_GRADES_CARD asrcg WHERE asrcg.STUDENT_ID=ssm.STUDENT_ID AND asrcg.SCHOOL_TERM_ID IN ('".$cur_sem."')) AS THIS_SEM_AVG_GRADE_DESC";
		$addition['functions']['THIS_SEM_AVG_GRADE_DESC'] = 'getLetterGradeDesc';
	}

	if($_REQUEST['fields']['ALL_QTR_AVG_GRADE'])
	{
		$addition['SELECT'] .= ",(SELECT AVG(asrcg.PERCENT_GRADE)/100 FROM STUDENT_GRADES_CARD asrcg WHERE asrcg.STUDENT_ID=ssm.STUDENT_ID AND asrcg.SCHOOL_TERM_ID IN (".GetAllTerms('SCHOOL_QUARTERS').")) AS ALL_QTR_AVG_GRADE";
		$addition['functions']['ALL_QTR_AVG_GRADE'] = 'getLetterGrade';
	}

	if($_REQUEST['fields']['ALL_QTR_AVG_GRADE_DESC'])
	{
		$addition['SELECT'] .= ",(SELECT AVG(asrcg.PERCENT_GRADE)/100 FROM STUDENT_GRADES_CARD asrcg WHERE asrcg.STUDENT_ID=ssm.STUDENT_ID AND asrcg.SCHOOL_TERM_ID IN (".GetAllTerms('SCHOOL_QUARTERS').")) AS ALL_QTR_AVG_GRADE_DESC";
		$addition['functions']['ALL_QTR_AVG_GRADE_DESC'] = 'getLetterGradeDesc';
	}

	if($_REQUEST['fields']['ALL_SEM_AVG_GRADE'])
	{
		$addition['SELECT'] .= ",(SELECT AVG(asrcg.PERCENT_GRADE)/100 FROM STUDENT_GRADES_CARD asrcg WHERE asrcg.STUDENT_ID=ssm.STUDENT_ID AND asrcg.SCHOOL_TERM_ID IN (".GetAllTerms('SCHOOL_SEMESTERS').")) AS ALL_SEM_AVG_GRADE";
		$addition['functions']['ALL_SEM_AVG_GRADE'] = 'getLetterGrade';
	}

	if($_REQUEST['fields']['ALL_SEM_AVG_GRADE_DESC'])
	{
		$addition['SELECT'] .= ",(SELECT AVG(asrcg.PERCENT_GRADE)/100 FROM STUDENT_GRADES_CARD asrcg WHERE asrcg.STUDENT_ID=ssm.STUDENT_ID AND asrcg.SCHOOL_TERM_ID IN (".GetAllTerms('SCHOOL_SEMESTERS').")) AS ALL_SEM_AVG_GRADE_DESC";
		$addition['functions']['ALL_SEM_AVG_GRADE_DESC'] = 'getLetterGradeDesc';
	}

	if($_REQUEST['fields']['ALL_QTR_AVG_PERCENT'])
	{
		$addition['SELECT'] .= ",(SELECT AVG(asrcg.PERCENT_GRADE)/100 FROM STUDENT_GRADES_CARD asrcg WHERE asrcg.STUDENT_ID=ssm.STUDENT_ID AND asrcg.SCHOOL_TERM_ID IN (".GetAllTerms('SCHOOL_QUARTERS').")) AS ALL_QTR_AVG_PERCENT";
		$addition['functions']['ALL_QTR_AVG_PERCENT'] = 'Percent';
	}

	if($_REQUEST['fields']['ALL_SEM_AVG_PERCENT'])
	{
		$addition['SELECT'] .= ",(SELECT AVG(asrcg.PERCENT_GRADE)/100 FROM STUDENT_GRADES_CARD asrcg WHERE asrcg.STUDENT_ID=ssm.STUDENT_ID AND asrcg.SCHOOL_TERM_ID IN (".GetAllTerms('SCHOOL_SEMESTERS').")) AS ALL_SEM_AVG_PERCENT";
		$addition['functions']['ALL_SEM_AVG_PERCENT'] = 'Percent';
	}
	if($_REQUEST['fields']['ALL_YEAR_AVG_PERCENT'])
	{
		$addition['SELECT'] .= ",(SELECT AVG(asrcg.PERCENT_GRADE)/100 FROM STUDENT_GRADES_CARD asrcg WHERE asrcg.STUDENT_ID=ssm.STUDENT_ID AND asrcg.SCHOOL_TERM_ID IN (".get_school_terms_by_year('SCHOOL_YEARS',get_school_year()).")) AS ALL_YEAR_AVG_PERCENT";
		$addition['functions']['ALL_YEAR_AVG_PERCENT'] = 'Percent';
	}
	if($_REQUEST['fields']['ALL_YEAR_AVG_GRADE'])
	{
		$addition['SELECT'] .= ",(SELECT AVG(asrcg.PERCENT_GRADE)/100 FROM STUDENT_GRADES_CARD asrcg WHERE asrcg.STUDENT_ID=ssm.STUDENT_ID AND asrcg.SCHOOL_TERM_ID IN (".get_school_terms_by_year('SCHOOL_YEARS',get_school_year()).")) AS ALL_YEAR_AVG_GRADE";
		$addition['functions']['ALL_YEAR_AVG_GRADE'] = 'getLetterGrade';
	}

	if($_REQUEST['fields']['ALL_YEAR_AVG_GRADE_DESC'])
	{
		$addition['SELECT'] .= ",(SELECT AVG(asrcg.PERCENT_GRADE)/100 FROM STUDENT_GRADES_CARD asrcg WHERE asrcg.STUDENT_ID=ssm.STUDENT_ID AND asrcg.SCHOOL_TERM_ID IN (".get_school_terms_by_year('SCHOOL_YEARS',get_school_year()).")) AS ALL_YEAR_AVG_GRADE_DESC";
		$addition['functions']['ALL_YEAR_AVG_GRADE_DESC'] = 'getLetterGradeDesc';
	}

	if($_REQUEST['fields']['SCHOOL_YEAR'] && !$addition['functions']['SCHOOL_YEAR'])
	{
		$addition['functions']['SCHOOL_YEAR'] = 'makeSchoolYear';

		if($students_table != 'STUDENT_DISCIPLINE_INCIDENTS')
			$addition['SELECT'] .= ',ssm.SCHOOL_YEAR';
	}

	if($_REQUEST['fields']['LAST_MP'])
		$addition['SELECT'] .= ",'".get_school_term($last_mp)."' AS LAST_MP";

	if($_REQUEST['fields']['CURRENT_DATE'])
		if($DBType == 'mssql')
			$addition['SELECT'] .= ",'".ProperDate(get_db_date())."' AS [CURRENT_DATE]";
		else
			$addition['SELECT'] .= ",'".ProperDate(get_db_date())."' AS CURRENT_DATE";

	if($_REQUEST['fields']['CURRENT_TIME'])
		if($DBType == 'mssql')
			$addition['SELECT'] .= ",'".date('g:i A')."' AS [CURRENT_TIME]";
		else
			$addition['SELECT'] .= ",'".date('g:i A')."' AS CURRENT_TIME";
	/*misc user name, dates, etc*/
	if($_REQUEST['fields']['USER_LASTFM'])
		$addition['SELECT'] .= ",'".get_teacher_last_fm(get_user('USER_ID'))."' AS USER_LASTFM";
	if($_REQUEST['fields']['USER_FIRSTMLAST'])
		$addition['SELECT'] .= ",'".get_teacher_first_m_last(get_user('USER_ID'))."' AS USER_FIRSTMLAST";
	if($_REQUEST['fields']['USER_LASTFIRSTMIDDLE'])
		$addition['SELECT'] .= ",'".get_teacher_fullname(get_user('USER_ID'))."' AS USER_LASTFIRSTMIDDLE";
/*
						'DATEYMD'=>_('Date YYYY-MM-DD'),
						'DATEDMY'=>_('Date DD-MM-YYYY'),
						'DATEDMYS'=>_('Date DD/MM/YYYY'),
						'INTUDATE'=>_('Date ').$user_date,
						'INTUSHDATE'=>_('Date ').$sh_user_date,
						'RDMYDATE'=>_('Date DD.MM.YYYY'),
						'RDMYYDATE'=>_('Date DD.MM.YY'));
*/
	include($staticpath.'modules/mod_portal/includes/fields_conv.inc.php');
	$work_date = $_SESSION['WORK_DATE'];
	$user_date = ProperDate($work_date,'long');
	$_SYSTEM['PROPDATE']['disable_day'] = true;
	$sh_user_date = ProperDate($work_date);
	$_SYSTEM['PROPDATE']['disable_day'] = false;
	$unixtime = strtotime($work_date);
	$dmy1 = date("d-m-Y",$unixtime);
	$dmy2 = str_replace('-','/',date("d-m-Y",$unixtime));
	$dmy3 = str_replace('-','.',date("d-m-Y",$unixtime));
	$dmy4 = str_replace('-','.',date("d-m-y",$unixtime));

	if($_REQUEST['fields']['DATEYMD'])
		$addition['SELECT'] .= ",'".$work_date."' AS DATEYMD";
	if($_REQUEST['fields']['DATEDMY'])
		$addition['SELECT'] .= ",'".$dmy1."' AS DATEDMY";
	if($_REQUEST['fields']['DATEDMYS'])
		$addition['SELECT'] .= ",'".$dmy2."' AS DATEDMYS";
	if($_REQUEST['fields']['INTUDATE'])
		$addition['SELECT'] .= ",'".$user_date."' AS INTUDATE";
	if($_REQUEST['fields']['INTUSHDATE'])
		$addition['SELECT'] .= ",'".$sh_user_date."' AS INTUSHDATE";
	if($_REQUEST['fields']['RDMYDATE'])
		$addition['SELECT'] .= ",'".$dmy3."' AS RDMYDATE";
	if($_REQUEST['fields']['RDMYYDATE'])
		$addition['SELECT'] .= ",'".$dmy4."' AS RDMYYDATE";


	/* used for the School Fileds */
	if($students_table=='STUDENTS')
	{
		foreach($school_fields_array as $school_id=>$school_field)
		{
				$schoolFiledsTMPArr['SCHOOLS_CFIELD_'.$school_id] = 'CFIELD_'.$school_id;
		}

		$schoolFiledsArr = array(
			'SCHOOL_TITLE' => 'TITLE'
			);

		$schoolFiledsArr += $schoolFiledsTMPArr;

		foreach($schoolFiledsArr as $schoolKey => $schoolValue)
		{
			if($_REQUEST['fields'][$schoolKey])
			if($DBType == 'mssql')
				$addition['SELECT'] .= ",'".str_replace("'","''",get_school(get_school_id(),NULL, $schoolValue))."' AS [".$schoolKey."]";
			else
				$addition['SELECT'] .= ",'".str_replace("'","''",get_school(get_school_id(),NULL, $schoolValue))."' AS ".$schoolKey;		
		}
	}

	if($_REQUEST['fields']['REPORT_TITLE'])
	{
		if($_REQUEST['servicemod']=='mod_grades/GrdStudentPrintGC.php')
			$report_title = _('Student Transcript');
		elseif($_REQUEST['servicemod']=='mod_grades/GrdPrintStudentReportCards.php')
			$report_title = _('Student Report Card');
		elseif(strpos(ProgramTitle(),_('Print'))!==false)
		{
			$report_title = str_replace(_('Print'),'',ProgramTitle());
			if(substr($report_title,-1)=='s')
				$report_title = substr($report_title,0,-1);
		}
		$addition['SELECT'] .= ",'".$report_title."' AS REPORT_TITLE";
	}
if($contacts){
	foreach($contacts as $contact=>$contact_title)
	{
		foreach($elems as $elem=>$elem_title)
		{
			if($_REQUEST['fields'][$contact.'_'.$elem])
			{
				$contact_fields = true;
				$addition['SELECT'] .= ',NULL AS '.$contact.'_'.$elem;
				$addition['functions'][strtoupper($contact.'_'.$elem)] = '_makeContactInfo';
			}
		}
	}
}
	//Доработать до многозяычных локализаций
	if($contact_fields===true)
	{
		$elem_list = '';
		foreach($elems as $elem=>$elem_title)
		{
			if(strtolower($elem)!='work')
				$elem_list .= "OR LOWER(pjc.TITLE) LIKE '".strtolower($elem)."%' ";
			else // in case there is a "work place" or "workplace" or "work location"
				$elem_list .= "OR LOWER(pjc.TITLE)='work' OR LOWER(pjc.TITLE) LIKE 'work ph%'";
		}
		//необходима доработка для многоязычных локализаций
		// in case the information isn't labeled office or cell.
		$elem_list .= "OR LOWER(pjc.TITLE) LIKE 'office%' ";
		$elem_list .= "OR LOWER(pjc.TITLE) LIKE 'mobile%' ";
		$elem_list = substr($elem_list,3);

		$addition2 = $addition;
		$addition2['DisableSearchResDisplay'] = true;
		$addition2['SELECT_ONLY'] = "sjp.ADDRESS_ID,ssm.STUDENT_ID,p.PERSON_ID,p.FIRST_NAME".CCAT."' '".CCAT."p.LAST_NAME AS NAME,p.EMAIL,COALESCE(sjp.CUSTODY,'N') AS CUSTODY,COALESCE(sjp.EMERGENCY,'N') AS EMERGENCY,sjp.STUDENT_RELATION,LOWER(pjc.TITLE) AS TITLE,pjc.VALUE,elemsa.ADDRESS,elemsa.CITY,elemsa.STATE,elemsa.ZIPCODE,elemsa.PHONE AS HOMEPHONE,";
		// addr.PHONE
		$addition2['SELECT_ONLY'] .= db_case(array('LOWER(sjp.STUDENT_RELATION)',"'"._('father')."'".' OR LOWER(sjp.STUDENT_RELATION)='."'"._('dad')."'","'father'","'"._('mother')."'".' OR LOWER(sjp.STUDENT_RELATION)='."'"._('mom')."'","'mother'","'"._('parent')."'"." OR sjp.CUSTODY='Y'","'parent'","'"._('emergency').'%\'',"'emergency'","'other'")).' AS CONTACT_TYPE ';
		// LEFT OUTER JOIN ON THE ADDRESS TABLE IF ADDRESSES ARE INCLUDED IN THE ADV REPORT
		$addition2['FROM'] .= 'LEFT OUTER JOIN STUDENTS_IN_SR sjp on (sjp.STUDENT_ID=ssm.STUDENT_ID) 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 AND ('.$elem_list.')) LEFT OUTER JOIN STUDENTS_IN_SR sjp2 on (sjp2.PERSON_ID=pjc.PERSON_ID AND sjp2.STUDENT_ID=ssm.STUDENT_ID) LEFT OUTER JOIN STUDENTS_IN_ADDRESS sja on (sja.ADDRESS_ID=sjp.ADDRESS_ID) LEFT OUTER JOIN ADDRESS elemsa on (sja.ADDRESS_ID=elemsa.ADDRESS_ID) ';
		if($addition['addr'])
			$addition2['group'] = array('STUDENT_ID','ADDRESS_ID','CONTACT_TYPE');
		else
			$addition2['group'] = array('STUDENT_ID','CONTACT_TYPE');

		$addition2['functions'] = array();
		$addition2['link'] = array();
		$contacts_array = get_student_list($addition2);
	}

	foreach($calculations_array as $calc)
	{
		if($_REQUEST['fields']['CALCULATION_'.$calc['ID']])
		{
			$addition['SELECT'] .= ',ssm.STUDENT_ID AS CALCULATION_'.$calc['ID'];
			$addition['functions']['CALCULATION_'.$calc['ID']] = '_runCalc';
			include_once('functions/extra/ReportProcessing.php');
		}
		if($_REQUEST['fields']['GRAPH_'.$calc['ID']])
		{
			// 'Y' might cause a problem if calculations were ever used in state reports
			if($_REQUEST['fields']['CALCULATION_'.$calc['ID']]!='Y')
			{
				$addition['SELECT'] .= ',ssm.STUDENT_ID AS CALCULATION_'.$calc['ID'];
				$addition['functions']['CALCULATION_'.$calc['ID']] = '_runCalc';
				include_once('functions/extra/ReportProcessing.php');
			}
			$addition['SELECT'] .= ',ssm.STUDENT_ID AS GRAPH_'.$calc['ID'];
			$graph = true;
		}
	}
//	var_dump($_REQUEST['fields']);
//	echo $_REQUEST['servicemod'];
//	var_dump($fields_list);
	if($_REQUEST['fields'])// || $_REQUEST['servicemod'] == 'mod_apply/AppPrintSpecDocs.php')
	{
		foreach($_REQUEST['fields'] as $field=>$on)
		{
			//here gridoutput gets column names
			$columns[$field] = $fields_list[$field];
        		if($_REQUEST['CREATEPDF'] && !$addition['functions'][$field] && substr($field,0,7)=='CFIELD_' && $fields_array[substr($field,7)][1]['TYPE']=='multiple')
            			$addition['functions'][$field] = 'prepareMultiple';
            		// this is for advanced report
			if($_REQUEST['servicemod']=='mod_portal/ExternalLinker.php' || $_REQUEST['servicemod']=='mod_students/StuAdvancedReport.php' || $_REQUEST['servicemod']=='mod_users/UsrAdvancedReport.php' || substr($_REQUEST['servicemod'],0,28)=='mod_savedinfo/SIRunLink.php?' || $_REQUEST['system_tab'] == 'AppAdvancedReport.php' || $_REQUEST['servicemod']=='mod_apply/AppAdvancedReport.php')
			{
				if((substr($field,0,7)!='CFIELD_' || !$fields_array[substr($field,7)]) && $field != "ADDRESS")
				{}
				elseif($fields_array[substr($field,7)][1]['TYPE']=='date' && !$addition['functions'][$field])
					$addition['functions'][$field] = '_makeDateInput';
				elseif(($fields_array[substr($field,7)][1]['TYPE']=='text' || $fields_array[substr($field,7)][1]['TYPE']=='numeric') && !$addition['functions'][$field])
					$addition['functions'][$field] = '_makeTextInput';
				elseif($fields_array[substr($field,7)][1]['TYPE']=='multiple' && !$addition['functions'][$field])
					$addition['functions'][$field] = '_makeMultipleInput';
				elseif(($fields_array[substr($field,7)][1]['TYPE']=='select' || $fields_array[substr($field,7)][1]['TYPE']=='select_one') && !$addition['functions'][$field])
					$addition['functions'][$field] = '_makeSelectInput';
				elseif($fields_array[substr($field,7)][1]['TYPE']=='radio' && !$addition['functions'][$field])
					$addition['functions'][$field] = '_makeCheckboxInput';
				elseif($fields_array[substr($field,7)][1]['TYPE']=='textarea')
					$addition['functions'][$field] = '_makeTextareaInput';
				elseif($fields_array[substr($field,7)][1]['TYPE']=='log')
				{

//				var_dump($columns[$field]);
					unset($columns[$field]);

					$logging_cols = array(
							'radio'=>'_makeLogCheckbox',
							'select'=>'_makeLogSelect',
							'date'=>'_makeLogDate',
							'text'=>'_makeLogTextInt',
							'numeric'=>'_makeLogTextInt',
							'textarea'=>'_makeLogTextArea',
							'time'=>'_makeTimeInput');
//var_dump($_REQUEST['fields']);
					if(count($_REQUEST['fields']) == 1)
					{
						$addition['SELECT'] .= ',sle'.substr($field,7).'.ID AS LF_ID'.substr($field,7);
   						for($i = 1; $i<= 20; $i++)
						{
							if(!empty($fields_array[substr($field,7)][1]['LOG_FIELD'.$i]))
							{
								$addition['SELECT'] .= ',sle'.substr($field,7).'.LOG_FIELD'.$i.' AS '.$field.'_LOG_FIELD'.$i;
								$columns[$field.'_LOG_FIELD'.$i] = str_replace("\\","\\\\",$fields_array[substr($field,7)][1]['LOG_FIELD'.$i.'_TITLE']);
                                                                //$fields_list[$field].' '.
							}
						}

						// THIS WILL NOT WORK FOR USERS, SINCE THERE IS NO ssm.
						if($student_id_field=='STUDENT_ID')
							$ssm = 'ssm';
						else
							$ssm = 's';
						$addition['FROM'] .= " INNER JOIN ".$student_log_entries_table." sle".substr($field,7)." ON (".$ssm.".".$student_id_field."=sle".substr($field,7).".".str_replace('USER_ID','USER_ID',$student_id_field)." AND sle".substr($field,7).".".$student_field_id_field."='".substr($field,7)."')";
					}else{
//					echo "s1231231231231231";
						$addition['SELECT'] .= ',sle'.substr($field,7).'.ID AS LF_ID'.substr($field,7);
						for($i = 1; $i<= 20; $i++)
						{
							if(!empty($fields_array[substr($field,7)][1]['LOG_FIELD'.$i]))
							{
								$addition['SELECT'] .= ',sle'.substr($field,7).'.LOG_FIELD'.$i.' AS '.$field.'_LOG_FIELD'.$i;
								if($fields_array[substr($field,7)][1]['LOG_FIELD'.$i] == 'numeric')
									$addition['functions'][$field.'_LOG_FIELD'.$i] = $logging_cols[$fields_array[substr($field,7)][1]['LOG_FIELD'.$i]];
								elseif($fields_array[substr($field,7)][1]['LOG_FIELD'.$i] == 'text')
									$addition['functions'][$field.'_LOG_FIELD'.$i] = $logging_cols[$fields_array[substr($field,7)][1]['LOG_FIELD'.$i]];
								$columns[$field.'_LOG_FIELD'.$i] = $fields_array[substr($field,7)][1]['LOG_FIELD'.$i.'_TITLE'];
                                                                //$fields_list[$field].' '.
							}
						}
																																	
						// THIS WILL NOT WORK FOR USERS, SINCE THERE IS NO ssm.
						if($student_id_field=='STUDENT_ID')
							$ssm = 'ssm';
						else
							$ssm = 's';
						$addition['FROM'] .= " INNER JOIN ".$student_log_entries_table." sle".substr($field,7)." ON (".$ssm.".".$student_id_field."=sle".substr($field,7).".".str_replace('USER_ID','USER_ID',$student_id_field)." AND sle".substr($field,7).".".$student_field_id_field."='".substr($field,7)."')";
					}
				}
				if(substr($field,0,11) == 'CFIELD_8881')
				{
					$addition['functions'][$field] = getStaticFuncByField($field);
				}
			}
			elseif($_REQUEST['servicemod']=='mod_students/StuLetterWorkspace.php' || $_REQUEST['servicemod']=='mod_users/UsrLetterWorkspace.php')
			{
				if((substr($field,0,7)!='CFIELD_' || !$fields_array[substr($field,7)]) && $field != "ADDRESS")
				{}
				elseif($fields_array[substr($field,7)][1]['TYPE']=='date' && !$addition['functions'][$field])
					$addition['functions'][$field] = 'ProperDate';
			}
		}
//		echo "3-->".date("H:m:s",time())."<br>";
//echo "1-->".memory_get_usage()."<br>";
                //var_dump($columns);
		foreach($columns as $key => $value)
			$names[] = "'".str_replace("'", "''", $value)."'";
		/* get Edit Rules for all the fields */
		$name = implode(',', $names);
		//	if($name == '') $name = "''";
	    	$field_Edits_array = db_request(db_execute("SELECT ID, FIELD_EDITS FROM ".$custom_fields_table." WHERE TITLE IN (".$name.") AND TYPE != 'log' AND FIELD_EDITS IS NOT NULL"), array(), array('ID'));

		foreach($field_Edits_array as $editKey => $editValue)
		{
			$editRules[$editKey] = $editValue[1]['FIELD_EDITS'];
		}

		if($_REQUEST['logging_field'] && $_REQUEST['logging_field_cols'])
		{
			foreach($_REQUEST['logging_field_cols'] as $col=>$y)
			{
				$logging_field_array = db_request(db_execute("SELECT * FROM STUDENT_FIELDS WHERE ID='".$_REQUEST['logging_field']."'"));
				$columns[$col] = $logging_field_array[1][$col.'_TITLE'];
			}
			$singular = $logging_field_array[1]['TITLE'].' '._('Entry');
			$plural = $logging_field_array[1]['TITLE'].' '._('Entries');
		}
//		echo "4-->".date("H:m:s",time())."<br>";
//		var_dump($addition['SELECT']);
//		var_dump($addition['WHERE']);
//var_dump($_REQUEST['fields']);
//echo "2-->".memory_get_usage()."<br>";
		if(!$logging_field_array)
		{
			if(!$_SYSTEM['log_fields']) $_SYSTEM['log_fields'] = array();
			$logging_field_array = db_request(db_execute("SELECT * FROM STUDENT_FIELDS WHERE TYPE = 'log'"),array(),array('ID'));
			foreach($logging_field_array as $lfield_id=>$flds)
			{
				$lf_sql .= "'' AS CFIELD_".$lfield_id.",";
				$lf_line .= "CFIELD_".$lfield_id.",";
			}
			$lf_sql = substr($lf_sql,0,-1);
			$lf_elem_array = substr($lf_line,0,-1);
			$_SYSTEM['lf_sql'] = $lf_sql;
			$_SYSTEM['log_fields'] = explode(",",$lf_elem_array);
		//	echo $lf_sql;
		}
		$logfields = false;
		//var_dump($_REQUEST['fields']);
//		var_dump($_SYSTEM['log_fields']);

		unset($spec_sql);
		unset($spec_line);
//		echo "5-->".date("H:m:s",time())."<br>";
//echo "3-->".memory_get_usage()."<br>";
		if($_REQUEST['fields'])
		{
        		foreach($_REQUEST['fields'] as $log_field=>$bull)
			{
				if(substr($log_field,0,3) == 'LOG' || in_array($log_field,$_SYSTEM['log_fields']) || strpos($log_field,'LOG_FIELD'))
					$logfields = true;
			}
        		foreach($_REQUEST['fields'] as $spec_field=>$bull)
			{
				if(substr($spec_field,7,4) == '8881')
				{
					$spec_sql .= "s.STUDENT_ID AS ".$spec_field.",";
				}
			}			
			$spec_line = ','.substr($spec_sql,0,-1);
			if(strlen($spec_sql) < 3) unset($spec_line);
		}
		if($_SYSTEM['lf_sql'].$spec_line)
			$addition['SELECT'] .= ','.$_SYSTEM['lf_sql'].$spec_line;
//		var_dump($_POST);
//var_dump($_SYSTEM);
		if($_SYSTEM['DisplayHeaderCall'] === true)
		{
                    if($_REQUEST['fields']['COUNTER']==true)
                    {
                        $Document->Doc_Id = $_REQUEST['doc_id'];
                        $addition['SELECT'] .= ", '0' AS COUNTER ";
                    }
//                    var_dump($_REQUEST['student']);
                    if(isset($_REQUEST['student']))
			$st_list = '\''.implode('\',\'',$_REQUEST['student']).'\'';
		    elseif(isset($_POST['students']))
		    {
			unset($st_list);
			foreach($_POST['students'] as $stu_id=>$checked)
			    $st_list .= "'".$stu_id."',";
			$st_list = substr($st_list,0,-1);
		    }
		    elseif(isset($_POST['STUDENT_ID']) && is_array($_POST['STUDENT_ID']))
		    {
		    	unset($st_list);
			foreach($_POST['STUDENT_ID'] as $stu_id=>$checked)
			    $st_list .= "'".$stu_id."',";
			$st_list = substr($st_list,0,-1);

		    }
		    $addition['WHERE'] = " AND s.".$student_id_field." IN ($st_list)";
		}
//		var_dump($addition);
//		echo "6-->".date("H:m:s",time())."<br>";
//var_dump($addition);
//var_dump($_POST);
		$array = $get_student_list($addition);
//		echo "7-->".date("H:m:s",time())."<br>";
//		var_dump($array);
//		echo "||||".count($array)."|||<BR>";
//		var_dump($_REQUEST['fields']);
		if($logfields === true)
		{	
			if(strpos($addition['WHERE'],'AND s.') !== false)
			{
				$where_stu = str_replace('AND s.',' ',$addition['WHERE']);
				//echo $where_stu;
//				echo "SELECT * FROM ".$student_log_entries_table." WHERE ".$where_stu."";
//				$lf_array = db_request(db_execute(db_limit("SELECT * FROM ".$student_log_entries_table." WHERE ".$where_stu." ORDER BY ID DESC",10)),array(),array('STUDENT_ID','STUDENT_FIELD_ID'));
				$lf_array = db_request(db_execute("SELECT * FROM ".$student_log_entries_table." WHERE ".$where_stu),array(),array('STUDENT_ID','STUDENT_FIELD_ID'));
				$sc = count($array);
			}
		}
//echo "4-->".memory_get_usage()."<br>";
//echo "8-->".date("H:m:s",time())."<br>";
		foreach($array as &$item)
		{
			$inputName = "address[" . $item["ADDRESS_ID"] . "][ADDRESS]";
			$item["ADDRESS"] = TextInput($item["ADDRESS"], $inputName,'','','force');
		}

		if($addition['array_function'] && function_exists($addition['array_function']))
			$addition['array_function']($array);
		if($graph===true)
		{
			_createGraphs($array);
		}

		if(($_REQUEST['servicemod']=='mod_students/StuAdvancedReport.php' || $_REQUEST['servicemod']=='mod_apply/AppAdvancedReport.php' || $_REQUEST['servicemod']=='mod_portal/ExternalLinker.php') && $fields_array[substr($field,7)][1]['TYPE']=='log')
		{
			$stack = array();
			foreach($array as $key=>$value)
			{
				$repeat = false;
				for($i=0;$i<count($stack);$i++)
				{
					if($stack[$i] == $value)
					{
						$repeat = true;
					}
				}
				if($repeat == false)
				{
					array_push($stack,$value);
				}
			}
			$array = $stack;
		}
		//advanced report
//		var_dump($addition);
		if($addition['dont_print_array']!==true)
		{
			if(!$_REQUEST['CREATEPDF'])
			{
				echo '<FORM action='.SetRequestOptions().' id=advancedReportForm method=POST>';
                                $_REQUEST['DrawAlign'] = 'LEFT';
				DisplayHeader('<A HREF=modloader.php?servicemod='.$_REQUEST['servicemod'].'&search_servicefunction=search&selected_menu='.
						$_REQUEST['selected_menu'].'&link_menu='.$_REQUEST['link_menu'].'&fields_order='.$_REQUEST['fields_order'].
						'><IMG SRC=images/back.gif height=15 border=0>'._('Modify Report').'</A>',$submitButton->createSButton(_('Save data only'),null,null,'submit').'&nbsp;&nbsp;'.$javaButton->createSButton(_('Save'),null,null,'button','location.href="modloader.php?servicemod=mod_savedinfo/SISaveLink.php&servicefunction=new"'));
			}       unset($_REQUEST['DrawAlign']);
			//search criteria
			if($_SYSTEM['SearchTerms'])
				DisplayHeader($_SYSTEM['SearchTerms']);

			if(is_array($addition['columns_before']))
				$columns += $addition['columns_before']; // to make sure to include "Course" and "Digit/Letter Grade" when searching for all students who failed a course

			$addition['Gridoutput_options']['filter'] = true;
			// needed to cause the report to split between 2 pages horizontally
			$addition['Gridoutput_options']['split_pages'] = true;

			if($_REQUEST['showerror'] == true)
				$array = _showErrorValues($array, $columns, $html_field_name, $student_id_field);
//echo $singular.$plural;
//var_dump($_REQUEST['servicemod']);
//			var_dump($columns);
			Gridoutput($array,$columns,$singular,$plural,array(),array(),$addition['Gridoutput_options']);
			if(!$_REQUEST['CREATEPDF'])
				echo '</FORM>';
		}
	}
	else
		BackPrompt(_('You must choose at least one field. Drag fields into the Report\'s column and try again.'));
		
}
//used for FCK
else
{
//echo "-->".$_SESSION['_REQUEST_vars']['servicemod'];
//die();
	if($_SESSION['_REQUEST_vars']['servicemod'] != 'mod_apply/AppDocTemplate.php' && $_SESSION['_REQUEST_vars']['servicemod'] != 'mod_apply/AppPrintSpecDocs.php' && substr($_SESSION['_REQUEST_vars']['servicemod'],0,9) != 'mod_apply')
	{
		if($students_table == 'STUDENTS')
		{
			$categories_array = db_request(db_execute("SELECT ID,TITLE FROM ".$categories_table." WHERE USED_APPLICANTS IS NULL OR USED_APPLICANTS != 'Y' ORDER BY SORT_ORDER,TITLE"),array(),array('ID'));
//			$custom_array = db_request(db_execute("SELECT TITLE,ID,TYPE,CATEGORY_ID FROM ".$custom_fields_table." WHERE TYPE!='holder' AND TYPE!='file' AND (USE_STUDENTS IS NULL OR USE_STUDENTS = 'Y') ORDER BY SORT_ORDER,TITLE"),array(),array('CATEGORY_ID'));
			$custom_array = db_request(db_execute("SELECT * FROM ".$custom_fields_table." WHERE TYPE!='holder' AND TYPE!='file' AND (USE_STUDENTS IS NULL OR USE_STUDENTS = 'Y') ORDER BY SORT_ORDER,TITLE"),array(),array('ID'));

/*
		$categories_array = db_request(db_execute("SELECT ID,TITLE FROM STUDENT_FIELD_CATEGORIES WHERE (ID IN
                                (SELECT CATEGORY_ID FROM STUDENT_FIELDS WHERE FOR_APPLICANTS = 'Y')
                                OR ID IN (SELECT CATEGORY_ID FROM STUDENT_FIELDS_IN_CATS WHERE FIELD_ID IN
                                (SELECT FIELD_ID FROM STUDENT_FIELDS WHERE FOR_APPLICANTS = 'Y')) OR ID = 1) OR USED_APPLICANTS = 'Y'
                                ORDER BY SORT_ORDER,TITLE"),array(),array('ID'));
*/		
//		var_dump($categories_array);
			$custom_categories_array = db_request(db_execute("SELECT FIELD_ID,CATEGORY_ID FROM STUDENT_FIELDS_IN_CATS"),array(),array('FIELD_ID','CATEGORY_ID'));
//		$custom_array = db_request(db_execute("SELECT * FROM ".$custom_fields_table." WHERE TYPE!='holder' AND TYPE!='file' AND ((CATEGORY_ID = 1 AND FOR_APPLICANTS = 'Y') OR FOR_APPLICANTS = 'Y') AND (USE_STUDENTS IS NULL OR USE_APPLICANTS = 'Y') ORDER BY SORT_ORDER,TITLE"),array(),array('ID'));
//	    var_dump($custom_categories_array);
//	    die();

		}
		else
		{
			$categories_array = db_request(db_execute("SELECT ID,TITLE FROM ".$categories_table." ORDER BY SORT_ORDER,TITLE"),array(),array('ID'));
			$custom_array = db_request(db_execute("SELECT TITLE,ID,TYPE,CATEGORY_ID FROM ".$custom_fields_table." WHERE TYPE!='holder' AND TYPE!='file' ORDER BY SORT_ORDER,TITLE"),array(),array('ID'));
		}

		/*----------- Multiple Categories Start -----------*/
		$custom_array = _joinAdditionalFields($custom_fields_table, $student_fields_join_categories, $custom_array);
		/*----------- Multiple Categories End-----------*/

		if($_REQUEST['servicemod']!='mod_discipline/DisAdvancedReportWizard.php')
		{
			$general_title = $categories_array[1][1]['TITLE'];
			$address_title = $categories_array[3][1]['TITLE'];
		}
	
	    	if(!$fields_list && $_REQUEST['servicemod']!='mod_discipline/DisAdvancedReportWizard.php')
		{
			if($students_program=='mod_users/Users.php')
			{
				if(AllowUse('mod_users/Users.php&category_id=1'))
					$fields_list[$general_title] = array('FULL_NAME'=>_('Last, First M'),'FIRST_NAME'=>_('First'),'FIRST_INIT'=>_('First Initial'),'LAST_NAME'=>_('Last'),'MIDDLE_NAME'=>_('Middle'),'EMAIL'=>_('Email'),'USER_ID'=>_('User ID'),
                                                         
      'USERNAME'=>_('Username'),'PASSWORD'=>_('Password'),'LAST_LOGIN'=>_('Last Login Date'));
        /*    echo "<pre>";
            print_r($fields_list[$general_title]);die;
            echo "</pre>"; */
				if(!AllowEdit('mod_users/Users.php&category_id=1'))
					unset($fields_list[$general_title]['PASSWORD']);
			}
			else
			{

				if(AllowUse('mod_students/Students.php&category_id=1'))
				$fields_list[$general_title] = array('FULL_NAME'=>_('Last, First M'),
					    'FIRST_NAME'=>_('First'),
					    'FIRST_INIT'=>_('First Initial'),
					    'LAST_NAME'=>_('Last'),
					    'MIDDLE_NAME'=>_('Middle'),
                        'CFIELD_2'=>_('Email'),
					    'NAME_SUFFIX'=>_('Suffix'),
					    'STUDENT_ID'=>_('Student ID number'),
					    'CLASSLEVEL_ID'=>_('Class Level'),
					    'GROUP_ID'=>_('Class Group'),
					    'SCHOOL_ID'=>_('School Name'),
					    'NEXT_SCHOOL'=>_('Rolling Options'),
					    'CFIELD_1'=>_('Order Number'),
					   // 'CFIELD_2'=>_('Order Date'),
					    'START_DATE'=>_('Date of Student Enrollment'),
					    'ENROLLMENT_CODE'=>_('Enrollment Code'),
					    'END_DATE'=>_('Student Dropped Date'),
					    'DROP_CODE'=>_('Drop Code'),
					    'CALENDAR_ID'=>_('School Calendar'),
					    'USERNAME'=>_('Login Name'),
					    'PASSWORD'=>_('Password'),
					    'LAST_LOGIN'=>_('Last Date of Login'));
				if(!AllowEdit('mod_students/Students.php&category_id=1'))
					unset($fields_list[$general_title]['PASSWORD']);


				if(AllowUse('mod_students/Students.php&category_id=3'))
				{
					$fields_list[$address_title] = array('ADDRESS'=>_('Address'),
					    'CITY'=>_('City'),
					    'STATE'=>_('State'),
					    'ZIPCODE'=>_('Zip Code'),
					    'PHONE'=>_('Home Phone'),
					    'FED_REGION'=>_('Страна/Субъект'),
					    'SETTLEMENT'=>_('Поселок/Населенный пункт'),
					    'MAIL_ADDRESS'=>_('Mailing Address'),
					    'MAIL_CITY'=>_('Mailing City'),
					    'MAIL_STATE'=>_('Mailing State'),
					    'MAIL_ZIPCODE'=>_('Mailing Zipcode'),
					    'ADDRESS_USERNAME'=>_('Parent Login Name'),
					    'ADDRESS_PASSWORD'=>_('Parent Password'),
					    'PARENTS'=>_('Contacts'),
					    'MAILTO_LABEL'=>_('Mailing Label'),
					    'CONTACT_INFO'=>_('List of Contact Info'),
					    'CITY_STATE'=>_('City, State'),
					    'MAIL_CITY_STATE'=>_('Mailing City, State'),
					    'ENTIRE_ADDRESS'=>_('Address City, State Zipcode'),
					    'ENTIRE_MAIL_ADDRESS'=>_('Mailing Address, City State Zipcode'));


				foreach($elems as $elem=>$elem_title)
				{
					foreach($contacts as $contact=>$contact_title)
						$fields_list[$contact_title][$contact.'_'.$elem] = $contact_title.': '.$elem_title;
				}
                            }
                            $fields_list[_('Other Fields')] = array(
                                    'COUNTER'=>_('Counter')
                                    );
		}

		if($addition['field_names'])
			$fields_list[$general_title] += $addition['field_names'];
	}
        
	foreach($categories_array as $cat_id=>$cats)
	{
		$ctitle = $cats[1]['TITLE'];
                $i=0;
		if(AllowUse($students_program.'&category_id='.$cat_id) || $_REQUEST['servicemod']=='mod_discipline/DisAdvancedReportWizard.php')
		foreach($custom_array as $id=>$field)
		{
                        $i++;
			$key = 'CFIELD_'.$field[1]['ID'];
			$value = $field[1]['TITLE'];
//			echo "$id-".$key.'-'.$value.'-'.$cat_id.'-'.$field[1]['ID'].'<br>';
			$custom_fcat_id = $custom_categories_array[$field[1]['ID']][$cat_id][1]['CATEGORY_ID'];
			$custom_field_id = $custom_array[$field[1]['ID']][1]['CATEGORY_ID'];
                        //$custom_field_id = $custom_array[$cat_id][$i]['CATEGORY_ID'];
                        //var_dump($custom_field_id,$cat_id);
//			echo $key.'-'.$value.'-'.$custom_fcat_id.'-'.$custom_field_id.'<br>';
			if(!$fields_list[$ctitle]) $fields_list[$ctitle] = array();
			if(($custom_fcat_id == $cat_id) || ($custom_field_id == $cat_id))
			{
				if($field[1]['TYPE'] == 'log')
				{
					$fields_list[$ctitle] += array($key=>$value);
					if($_REQUEST['servicemod']!='mod_students/StuAdvancedReport.php')
					{
						for($lf=1;$lf<=20;$lf++)
						{
							$lf_title = $field[1]['LOG_FIELD'.$lf.'_TITLE'];
							$lf_key = 'LOG_FIELD'.$lf.'+'.$key;
							if($lf_title)
								$fields_list[$ctitle] += array($lf_key=>$value.': '.$lf_title);
							for($vkey=1;$vkey<=$_Config['LF_record_count'];$vkey++)
							{
								$lf_key = $vkey.'+LOG_FIELD'.$lf.'+'.$key;
								if($lf_title)
									$fields_list[$ctitle] += array($lf_key=>$value.': '.$lf_title.': '._('Value #').$vkey);
							}
						}
					}
				}
				else
					$fields_list[$ctitle] += array($key=>$value);
			}
		}
	}

	if($_REQUEST['system_tab'] !== 'AppAdvancedReport.php' && $_REQUEST['servicemod']!='mod_apply/AppAdvancedReport.php')
	{
		$user_date = ProperDate(get_db_date());
		$_SYSTEM['PROPDATE']['disable_day'] = true;
		$sh_user_date = ProperDate(get_db_date());
		$_SYSTEM['PROPDATE']['disable_day'] = false;
		$cpttitle = _('Misc');
		$fields_list[$cpttitle] = array('USER_LASTFM'=>_('Logged User\'s Last F M'),
					'USER_FIRSTMLAST'=>_('Logged User\'s First M Last'),
					'USER_LASTFIRSTMIDDLE'=>_('Logged User\'s Last First Middle'),
					'DATEYMD'=>_('Date YYYY-MM-DD'),
					'DATEDMY'=>_('Date DD-MM-YYYY'),
					'DATEDMYS'=>_('Date DD/MM/YYYY'),
					'INTUDATE'=>_('Date ').$user_date,
					'INTUSHDATE'=>_('Date ').$sh_user_date,
					'RDMYDATE'=>_('Date DD.MM.YYYY'),
					'RDMYYDATE'=>_('Date DD.MM.YY'));
	}


//die();
/*

	foreach($custom_array as $category_id=>$fields)
	{
		if(AllowUse($students_program.'.php&category_id='.$category_id) || $_REQUEST['servicemod']=='mod_discipline/DisAdvancedReportWizard.php')
		{
			foreach($fields as $field)
				$fields_list[$categories_array[$category_id][1]['TITLE']]['CFIELD_'.$field['ID']] = str_replace("'",'&rsquo;',$field['TITLE']);
		}
	}
*/
	/* remove the Schedule item from the Discipline Report */
	if(AllowUse('mod_curriculum/Curriculum.php') && ($students_program!='mod_users/Users.php' && $students_program !='mod_discipline/DisIncidentList.php'))
	{
		$periods_array = db_request(db_execute("SELECT TITLE,SCHOOL_PERIOD_ID FROM SCHOOL_PERIODS WHERE SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."' ORDER BY SORT_ORDER"));
		foreach($periods_array as $period)
			$fields_list[_('Schedule')]['PERIOD_'.$period['SCHOOL_PERIOD_ID']] = $period['TITLE'].' '._('Teacher Name - Class-room');
	}

	/* remove the Attendance this school year item from the Discipline Report */
	if((AllowUse('mod_attendance/AttdByDays.php') || AllowUse('mod_attendance/AttdStuSumAttendance.php')) && ($students_program!='mod_users/Users.php' && $students_program !='mod_discipline/DisIncidentList.php'))
	{
		$codes_array = db_request(db_execute("SELECT ID,TITLE,SHORT_NAME,IS_DAILY_CODE FROM ATTENDANCE_CODES_SETTINGS WHERE SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."'"));

		$fields_list[_('Attendance this school year')]['ATT_DAYS_ABS'] = _('Days Absent');
		$fields_list[sprintf(_('Attendance in %s'),get_school_term(get_user_school_term()))]['ATT_QTR_DAYS_ABS'] = _('Days Absent');

		foreach($codes_array as $code)
		{
			if($code['IS_DAILY_CODE']=='Y')
			{
				$fields_list[_('Attendance this school year')]['ATT_DAYS__'.$code['SHORT_NAME']] = _('Days').' '.$code['TITLE'].' '._('YTD');
				$fields_list[sprintf(_('Attendance in %s'),get_school_term(get_user_school_term()))]['ATT_QTR_DAYS__'.$code['SHORT_NAME']] = _('Days').' '.$code['TITLE'].' '.get_school_term(get_user_school_term(),'SHORT_NAME');
			}
		}

		$fields_list[_('Attendance this school year')]['ATT_DAYS_PRES'] = _('Days Present');
		$fields_list[sprintf(_('Attendance in %s'),get_school_term(get_user_school_term()))]['ATT_QTR_DAYS_PRES'] = _('Days Present');

		$fields_list[_('Attendance this school year')]['ATT_DAYS_ENROLLED'] = _('Days Enrolled');
		$fields_list[sprintf(_('Attendance in %s'),get_school_term(get_user_school_term()))]['ATT_QTR_DAYS_ENROLLED'] = _('Days Enrolled');

		foreach($codes_array as $code)
		{
			$fields_list[_('Attendance this school year')]['ATT_'.$code['SHORT_NAME']] = _('Periods').' '.$code['TITLE'];
			$fields_list[sprintf(_('Attendance in %s'),get_school_term(get_user_school_term()))]['ATT_QTR_'.$code['SHORT_NAME']] = _('Periods').' '.$code['TITLE'];
		}
	}

	/* remove the Grades item from the Discipline Report */
	if(AllowUse('mod_grades/GrdPrintStudGrades.php') && ($students_program!='mod_users/Users.php' && $students_program !='mod_discipline/DisIncidentList.php'))
	{
		$gradelevels_array = db_request(db_execute("SELECT ID,SCHOOL_ID,TITLE FROM SCHOOL_CLASSLEVELS WHERE SCHOOL_ID='".get_school_id()."' ORDER BY SORT_ORDER"));
		foreach($gradelevels_array as $gradelevel)
		{
			$fields_list[_('Gradelevel GPA')]['SEM_GPA_'.$gradelevel['ID']] = $gradelevel['TITLE']._(' Semester GPA');
			$fields_list[_('Gradelevel GPA')]['SEM_WEIGHTED_GPA_'.$gradelevel['ID']] = $gradelevel['TITLE']._(' Semester Weighted GPA');
			$fields_list[_('Gradelevel GPA')]['QTR_GPA_'.$gradelevel['ID']] = $gradelevel['TITLE']._(' Quarter GPA');
			$fields_list[_('Gradelevel GPA')]['QTR_WEIGHTED_GPA_'.$gradelevel['ID']] = $gradelevel['TITLE']._(' Quarter Weighted GPA');
		}

		$fields_list[_('Grades')]['SEM_GPA'] = _('Cumulative Semester GPA');
		if(SystemPreferences('WEIGHTED_GPA')=='Y')
			$fields_list[_('Grades')]['SEM_WEIGHTED_GPA'] = _('Cumulative Semester Weighted GPA');
		$fields_list[_('Grades')]['QTR_GPA'] = _('Cumulative Quarter GPA');
		if(SystemPreferences('WEIGHTED_GPA')=='Y')
			$fields_list[_('Grades')]['QTR_WEIGHTED_GPA'] = _('Cumulative Quarter Weighted GPA');

		$fields_list[_('Grades')]['THIS_SEM_GPA'] = _('Current Semester GPA');
		if(SystemPreferences('WEIGHTED_GPA')=='Y')
			$fields_list[_('Grades')]['THIS_SEM_WEIGHTED_GPA'] = _('Current Semester Weighted GPA');
		$fields_list[_('Grades')]['THIS_QTR_GPA'] = _('Current Quarter GPA');
		if(SystemPreferences('WEIGHTED_GPA')=='Y')
			$fields_list[_('Grades')]['THIS_QTR_WEIGHTED_GPA'] = _('Current Quarter Weighted GPA');

		$fields_list[_('Grades')]['YEAR_CLASS_RANK'] = _('Student Rating in Class for Year');
		$fields_list[_('Grades')]['SEM_CLASS_RANK'] = _('Student Rating in Class for Semester');
		$fields_list[_('Grades')]['QTR_CLASS_RANK'] = _('Student Rating in Class for Quarter');

		$fields_list[_('Grades')]['YEAR_GROUP_CLASS_RANK'] = _('Student Rating in Class Group for Year');
		$fields_list[_('Grades')]['SEM_GROUP_CLASS_RANK'] = _('Student Rating in Class Group for Semester');
		$fields_list[_('Grades')]['QTR_GROUP_CLASS_RANK'] = _('Student Rating in Class Group for Quarter');		

		$fields_list[_('Grades')]['SEM_CREDITS'] = _('Semester Credits');
		$fields_list[_('Grades')]['QTR_CREDITS'] = _('Quarter Credits');
		$fields_list[_('Grades')]['THIS_QTR_AVG_PERCENT'] = _('Current Quarter Average Percent Grade');
		$fields_list[_('Grades')]['THIS_QTR_AVG_GRADE'] = _('Current Quarter Average Letter Grade');
		$fields_list[_('Grades')]['THIS_QTR_AVG_GRADE_DESC'] = _('Current Quarter Average Letter Grade Desc');
		$fields_list[_('Grades')]['THIS_SEM_AVG_PERCENT'] = _('Current Semester Average Percent Grade');
		$fields_list[_('Grades')]['THIS_SEM_AVG_GRADE'] = _('Current Semester Average Letter Grade');
		$fields_list[_('Grades')]['THIS_SEM_AVG_GRADE_DESC'] = _('Current Semester Average Letter Grade Desc');
		$fields_list[_('Grades')]['ALL_QTR_AVG_PERCENT'] = _('Cumulative Quarter Average Percent Grade');
		$fields_list[_('Grades')]['ALL_SEM_AVG_PERCENT'] = _('Cumulative Semester Average Percent Grade');
		$fields_list[_('Grades')]['ALL_QTR_AVG_GRADE'] = _('Cumulative Quarter Average Letter Grade');
		$fields_list[_('Grades')]['ALL_QTR_AVG_GRADE_DESC'] = _('Cumulative Quarter Average Letter Grade Desc');
		$fields_list[_('Grades')]['ALL_SEM_AVG_GRADE'] = _('Cumulative Semester Average Letter Grade');
		$fields_list[_('Grades')]['ALL_SEM_AVG_GRADE_DESC'] = _('Cumulative Semester Average Letter Grade Desc');

		$fields_list[_('Grades')]['ALL_YEAR_AVG_PERCENT'] = _('Cumulative Year Average Percent Grade');
		$fields_list[_('Grades')]['ALL_YEAR_AVG_GRADE'] = _('Cumulative Average Letter Grade');
		$fields_list[_('Grades')]['ALL_YEAR_AVG_GRADE_DESC'] = _('Cumulative Average Letter Grade Desc');

	}

	$fields_list[_('Report Details')]['LAST_MP'] = _('School Term');
	$fields_list[_('Report Details')]['SCHOOL_YEAR'] = _('School Year');
	$fields_list[_('Report Details')]['REPORT_TITLE'] = _('Report Title');
	$fields_list[_('Report Details')]['CURRENT_DATE'] = _('Current Date');
	$fields_list[_('Report Details')]['CURRENT_TIME'] = _('Current Time');

	if($students_table=='STUDENTS')
	{
		$fields_list[_('School Fields')]['SCHOOL_TITLE'] = _('School Name');

		foreach($school_fields_array as $school_id=>$school_field)
		{
			if(!$fields_list[_('School Fields')]['SCHOOLS_CFIELD_'.$school_id])
				$fields_list[_('School Fields')]['SCHOOLS_CFIELD_'.$school_id] = $school_field[1]['TITLE'];
		}
	}

	if($students_program!='mod_users/Users.php')
	{
		//	THIS CODE REFERENCES CALCULATIONS FEATURES WHICH AREN'T YET IMPLEMENTED
		$calculations_array = db_request(db_execute("SELECT ID,TITLE,URL FROM INFO_SAVES ORDER BY TITLE"));
		foreach($calculations_array as $calc)
		{
			$fields_list[_('Calculations')]['CALCULATION_'.$calc['ID']] = $calc['TITLE'];
			$fields_list[_('Calculations')]['GRAPH_'.$calc['ID']] = $calc['TITLE'].' '._('Graph');
		}
	}
	$_REQUEST['DrawAlign'] = 'LEFT';
	echo '<TABLE align=center><TR><TD>';
	if($_REQUEST['servicemod']!='mod_curriculum/ScdPReportStudClassList.php')
		DisplayHeader('<DIV style="width:800;">'.
		//sprintf(_('ss: %s')).
		sprintf(_('This function can be used to create and save special customised reports.').'<OL><LI>'._('You can add students to the report using the search function on the left side of the screen.').'</LI><LI>'.
			_('The fields from the categories in the middle of the screen can be dragged to the report\'s column on the right side of the screen.').'</LI><LI>'._('If you want to rearrange the order of the fields, you can drag them up or down in the list.').'</LI><LI>'.
			_('If you want remove fields from your report\'s column, you can drag them back to the source fields list.').'</LI><LI>'.
			_('Press Create Report to run the advanced report. *').'</LI></OL><HR>'.
			_('* You can save the report configuration by clicking the Save Info button at the right top part of the screen after pressed Create Report.').'<HR>',strtolower($plural)).'</DIV>','<BR>');
	echo '</TD></TR></TABLE><TABLE>';
	unset($_REQUEST['DrawAlign']);
	$addition['action'] .= " onsubmit='changeOrder();' ";

	include($staticpath.'modules/mod_portal/includes/advreport_iface.inc.php');
	
		if($_REQUEST['fields_order'])
		{
			$fields_order = explode('|',$_REQUEST['fields_order']);
			$_REQUEST['fields_order'] = array();
			foreach($fields_order as $field)
				$_REQUEST['fields_order'][$field] = true;
		}
		elseif($_REQUEST['servicemod']=='mod_curriculum/ScdPReportStudClassList.php')
		$_REQUEST['fields_order'] = array('FULL_NAME'=>true,'STUDENT_ID'=>true,'CLASSLEVEL_ID'=>true);

		$addition['second_col'] .= '<font color=#'.Preferences('HIGHLIGHT').'><BR><b>'._('Available Fields:').'</b></font><BR>';
		$i = 0;

		foreach($fields_list as $category=>$fields)
		{
			$i++;
			$count_fields = count($fields);
			$addition['second_col'] .= '<A onclick="switchMenu(\'drag'.$i.'_table\');expandRight(\'drag'.$i.'_table\','.$count_fields.')" style="cursor:pointer;margin-left:1em;"><IMG SRC=images/arrow_right.gif id=drag'.$i.'_table_arrow> <B>'.$category.'</B></A><BR><DIV width=100% id=drag'.$i.'_table style="display:none;">';
			$addition['second_col'] .= '<ul id="left'.$i.'" class="sortable boxy" style="margin-left: 1em;">';
			foreach($fields as $field=>$title)
			{
				if(!$_REQUEST['fields_order'][$field])
					$addition['second_col'] .= '<li id="'.$field.'">'.$title.'</li>';
				else
					$field_titles[$field] = $title;
			}
			$addition['second_col'] .= '</ul></div>';
		}
		$addition['second_col'] .= '</TD><TD valign=top><font color=#'.Preferences('HIGHLIGHT').'><b>'._('Report\'s column:').'</b></font><BR>';
		$addition['second_col'] .= '<ul id="right" class="sortable boxier" style="height:600px;margin-left:1em;border:1px dashed #AAAAAA;">';
		if(is_array($_REQUEST['fields_order']))
		{
			foreach($_REQUEST['fields_order'] as $field=>$true)
				$addition['second_col'] .= '<li id="'.$field.'">'.$field_titles[$field].'</li>';
		}
		$addition['second_col'] .= '</ul>';
//	$addition['second_col'] .= '</TD></TR></TABLE>';
                
		echo '<table align=center><tr><td>';
		Search($search_function_parameter,$addition);
		echo '</TD></TR></TABLE>';
	}
	else //fields for applicants *************************************************************************************************************************
	{
//		$categories_array = db_request(db_execute("SELECT ID,TITLE FROM ".$categories_table." ORDER BY SORT_ORDER,TITLE"),array(),array('ID'));
		$categories_array = db_request(db_execute("SELECT ID,TITLE FROM STUDENT_FIELD_CATEGORIES WHERE (ID IN
                                (SELECT CATEGORY_ID FROM STUDENT_FIELDS WHERE FOR_APPLICANTS = 'Y')
                                OR ID IN (SELECT CATEGORY_ID FROM STUDENT_FIELDS_IN_CATS WHERE FIELD_ID IN
                                (SELECT FIELD_ID FROM STUDENT_FIELDS WHERE FOR_APPLICANTS = 'Y')) OR ID = 1) OR USED_APPLICANTS = 'Y'
                                ORDER BY SORT_ORDER,TITLE"),array(),array('ID'));
		
//		var_dump($categories_array);
		$custom_categories_array = db_request(db_execute("SELECT FIELD_ID,CATEGORY_ID FROM STUDENT_FIELDS_IN_CATS"),array(),array('FIELD_ID','CATEGORY_ID'));
//		var_dump($custom_categories_array);
//		$custom_array = db_request(db_execute("SELECT TITLE,ID,TYPE,CATEGORY_ID FROM ".$custom_fields_table." WHERE TYPE!='holder' AND TYPE!='file' AND ((CATEGORY_ID = 1 AND FOR_APPLICANTS = 'Y') OR FOR_APPLICANTS = 'Y') ORDER BY SORT_ORDER,TITLE"),array(),array('CATEGORY_ID'));
//		$custom_array = db_request(db_execute("SELECT TITLE,ID,TYPE,CATEGORY_ID FROM ".$custom_fields_table." WHERE TYPE!='holder' AND TYPE!='file' AND ((CATEGORY_ID = 1 AND FOR_APPLICANTS = 'Y') OR FOR_APPLICANTS = 'Y') ORDER BY SORT_ORDER,TITLE"),array(),array('ID'));
		$custom_array = db_request(db_execute("SELECT * FROM ".$custom_fields_table." WHERE TYPE!='holder' AND TYPE!='file' AND ((CATEGORY_ID = 1 AND FOR_APPLICANTS = 'Y') OR FOR_APPLICANTS = 'Y') AND (USE_STUDENTS IS NULL OR USE_APPLICANTS = 'Y') ORDER BY SORT_ORDER,TITLE"),array(),array('ID'));
//		$logging_array = db_request(db_execute("SELECT TITLE,ID,TYPE,CATEGORY_ID FROM ".$student_log_entries_table." WHERE TYPE='log' ORDER BY SORT_ORDER,TITLE"),array(),array('CATEGORY_ID'));
//		var_dump($custom_array);
//		var_dump($student_fields_join_categories);

//	echo "SELECT TITLE,ID,TYPE,CATEGORY_ID FROM ".$custom_fields_table." WHERE TYPE!='holder' AND TYPE!='file' AND ((CATEGORY_ID = 1 AND FOR_APPLICANTS = 'Y') OR FOR_APPLICANTS = 'Y') ORDER BY SORT_ORDER,TITLE";
//var_dump($custom_array);
//		$custom_array = _joinAppAddlFields($custom_fields_table, $student_fields_join_categories, $custom_array);
//		var_dump($custom_array);
//		die();				
//var_dump($categories_array);
		$general_title = $categories_array[1][1]['TITLE'];
		$address_title = $categories_array[3][1]['TITLE'];
//var_dump(AllowUse('mod_apply/Applicants.php&category_id=1'));		
//	die();

		if(AllowUse('mod_apply/Applicants.php&category_id=1'))
			$fields_list[$general_title] = array('FULL_NAME'=>_('Last, First M'),
					    'FIRST_NAME'=>_('First'),
					    'FIRST_INIT'=>_('First Initial'),
					    'LAST_NAME'=>_('Last'),
					    'MIDDLE_NAME'=>_('Middle'),
					    'NAME_SUFFIX'=>_('Suffix'),
					    'STUDENT_ID'=>_('Applicant ID number'),
//					    'CLASSLEVEL_ID'=>_('Class Level'),
//					    'GROUP_ID'=>_('Class Group'),
					    'CFIELD_1'=>_('Order Number'),
					    'CFIELD_2'=>_('Order Date'),
					    'SCHOOL_ID'=>_('School Name'),
					    'NEXT_SCHOOL'=>_('Rolling Options'),
					    'START_DATE'=>_('Date of Applicant Enrolled'),
					    'ENROLLMENT_CODE'=>_('Enrollment Code'),
					    'END_DATE'=>_('Applicant Dropped Date'),
					    'DROP_CODE'=>_('Drop Code'),
					    'USERNAME'=>_('Login Name'),
					    'PASSWORD'=>_('Password'));
		if(AllowUse('mod_apply/Applicants.php&category_id=3'))
		{
			$fields_list[$address_title] = array('ADDRESS'=>_('Address'),
					    'CITY'=>_('City'),
//					    'STATE'=>_('State'),
					    'STATE'=>_('District'),
					    'FED_REGION'=>_('Страна/Субъект'),
					    'SETTLEMENT'=>_('Поселок/Населенный пункт'),
					    'ZIPCODE'=>_('Zip Code'),
					    'PHONE'=>_('Home Phone'),
					    'MAIL_ADDRESS'=>_('Mailing Address'),
					    'MAIL_CITY'=>_('Mailing City'),
					    'MAIL_STATE'=>_('Mailing State'),
					    'MAIL_FED_REGION'=>_('Почтовый: Страна/Субъект'),
					    'MAIL_SETTLEMENT'=>_('Почтовый: Поселок/Населенный пункт'),
					    'MAIL_ZIPCODE'=>_('Mailing Zipcode'),
					    'ADDRESS_USERNAME'=>_('Parent Login Name'),
					    'ADDRESS_PASSWORD'=>_('Parent Password'),
					    'PARENTS'=>_('Contacts'),
					    'MAILTO_LABEL'=>_('Mailing Label'),
					    'CONTACT_INFO'=>_('List of Contact Info'),
					    'CITY_STATE'=>_('City, State'),
					    'MAIL_CITY_STATE'=>_('Mailing City, State'),
					    'ENTIRE_ADDRESS'=>_('Address City, State Zipcode'),
					    'ENTIRE_MAIL_ADDRESS'=>_('Mailing Address, City State Zipcode'));

			foreach($elems as $elem=>$elem_title)
			{
				foreach($contacts as $contact=>$contact_title)
					$fields_list[$contact_title][$contact.'_'.$elem] = $contact_title.': '.$elem_title;
			}
		}
//			echo "-->".$_REQUEST['servicemod'];
		foreach($categories_array as $cat_id=>$cats)
		{
//			$ctitle = $categories_array[$cat_id][1]['TITLE'];
			$ctitle = $cats[1]['TITLE'];
//			echo $ctitle."-$cat_id<br>";
			if(AllowUse('mod_apply/Applicants.php&category_id='.$cat_id))
			foreach($custom_array as $id=>$field)
			{
				$key = 'CFIELD_'.$field[1]['ID'];
				$value = $field[1]['TITLE'];
	//			echo $key.'-'.$value.'-'.$custom_fcat_id.'-'.$custom_field_id.'<br>';
//				echo $key.'-'.$value.'-'.$cat_id.'-'.$field[1]['ID'].'<br>';
				$custom_fcat_id = $custom_categories_array[$field[1]['ID']][$cat_id][1]['CATEGORY_ID'];
				$custom_field_id = $custom_array[$field[1]['ID']][1]['CATEGORY_ID'];
//				echo $key.'-'.$value.'-'.$custom_fcat_id.'-'.$custom_field_id.'<br>';
				if(!$fields_list[$ctitle]) $fields_list[$ctitle] = array();
				if(($custom_fcat_id == $cat_id) || ($custom_field_id == $cat_id))
				{
					if($field[1]['TYPE'] == 'log')
					{
						$fields_list[$ctitle] += array($key=>$value);
						if($_REQUEST['system_tab'] !== 'AppAdvancedReport.php' && $_REQUEST['servicemod']!='mod_apply/AppAdvancedReport.php')
						{
							for($lf=1;$lf<=20;$lf++)
							{
								$lf_title = $field[1]['LOG_FIELD'.$lf.'_TITLE'];
								$lf_key = 'LOG_FIELD'.$lf.'+'.$key;
								if($lf_title)
									$fields_list[$ctitle] += array($lf_key=>$value.': '.$lf_title);
								for($vkey=1;$vkey<=$_Config['LF_record_count'];$vkey++)
								{
									$lf_key = $vkey.'+LOG_FIELD'.$lf.'+'.$key;
									if($lf_title)
										$fields_list[$ctitle] += array($lf_key=>$value.': '.$lf_title.': '._('Value #').$vkey);
								}
							}
						}
					}
					else
						$fields_list[$ctitle] += array($key=>$value);
//				echo $key.' '.$value.'<br>';						
				}
			}
		}
		$cpttitle = _('Major Program');
		$fields_list[$cpttitle] = array('CFIELD_888100'=>_('Competitive Group Title'),
						'CFIELD_888101'=>_('School Name'),
						'CFIELD_888102'=>_('Faculty Title'),
						'CFIELD_888103'=>_('Major Title'),
						'CFIELD_888104'=>_('Special Subject Title'),
						'CFIELD_888105'=>_('Competitive Category Title'),
						'CFIELD_888106'=>_('Form of Education'));
		if($students_table=='STUDENTS')
		{
			$fields_list[_('School Fields')]['SCHOOL_TITLE'] = _('School Name');
	    		foreach($school_fields_array as $school_id=>$school_field)
			{
				if(!$fields_list[_('School Fields')]['SCHOOLS_CFIELD_'.$school_id])
					$fields_list[_('School Fields')]['SCHOOLS_CFIELD_'.$school_id] = $school_field[1]['TITLE'];
			}
		}
		if($_REQUEST['system_tab'] !== 'AppAdvancedReport.php' && $_REQUEST['servicemod']!='mod_apply/AppAdvancedReport.php')
		{
			$user_date = ProperDate(get_db_date());
			$_SYSTEM['PROPDATE']['disable_day'] = true;
			$sh_user_date = ProperDate(get_db_date());
			$_SYSTEM['PROPDATE']['disable_day'] = false;
			$cpttitle = _('Misc');
			$fields_list[$cpttitle] = array('USER_LASTFM'=>_('Logged User\'s Last F M'),
						'USER_FIRSTMLAST'=>_('Logged User\'s First M Last'),
						'USER_LASTFIRSTMIDDLE'=>_('Logged User\'s Last First Middle'),
						'DATEYMD'=>_('Date YYYY-MM-DD'),
						'DATEDMY'=>_('Date DD-MM-YYYY'),
						'DATEDMYS'=>_('Date DD/MM/YYYY'),
						'INTUDATE'=>_('Date ').$user_date,
						'INTUSHDATE'=>_('Date ').$sh_user_date,
						'RDMYDATE'=>_('Date DD.MM.YYYY'),
						'RDMYYDATE'=>_('Date DD.MM.YY'));
		}
//		var_dump($fields_list);
//die();
/*
		foreach($custom_array as $cat_id=>$fields)
		{
			$ctitle = $categories_array[$cat_id][1]['TITLE'];
			foreach($fields as $field)
			{
				$key = 'CFIELD_'.$field['ID'];
				$value = $field['TITLE'];
				if(!$fields_list[$ctitle]) $fields_list[$ctitle] = array();
				$fields_list[$ctitle] += array($key=>$value);
			}
		}
*/		
//		var_dump($fields_list);
//			die();


		if($_REQUEST['system_tab'] == 'AppAdvancedReport.php' || $_REQUEST['servicemod']=='mod_apply/AppAdvancedReport.php')
		{
			$_REQUEST['DrawAlign'] = 'LEFT';
			echo '<TABLE align=center><TR><TD>';
			if($_REQUEST['servicemod']!='mod_curriculum/ScdPReportStudClassList.php')
			DisplayHeader('<DIV style="width:800;">'.
			sprintf(_('This function can be used to create and save special customised reports.').'<OL><LI>'._('You can add students to the report using the search function on the left side of the screen.').'</LI><LI>'.
				_('The fields from the categories in the middle of the screen can be dragged to the report\'s column on the right side of the screen.').'</LI><LI>'._('If you want to rearrange the order of the fields, you can drag them up or down in the list.').'</LI><LI>'.
				_('If you want remove fields from your report\'s column, you can drag them back to the source fields list.').'</LI><LI>'.
				_('Press Create Report to run the advanced report. *').'</LI></OL><HR>'.
				_('* You can save the report configuration by clicking the Save Info button at the right top part of the screen after pressed Create Report.').'<HR>',strtolower($plural)).'</DIV>','<BR>');
			echo '</TD></TR></TABLE><TABLE>';
		    	unset($_REQUEST['DrawAlign']);
			$addition['action'] .= " onsubmit='changeOrder();' ";
			
			include($staticpath.'modules/mod_portal/includes/advreport_iface.inc.php');
				
			if($_REQUEST['fields_order'])
			{
				$fields_order = explode('|',$_REQUEST['fields_order']);
				$_REQUEST['fields_order'] = array();
				foreach($fields_order as $field)
					$_REQUEST['fields_order'][$field] = true;
			}

			$addition['second_col'] .= '<font color=#'.Preferences('HIGHLIGHT').'><BR><b>'._('Available Fields:').'</b></font><BR>';
			$i = 0;

			foreach($fields_list as $category=>$fields)
			{
				$i++;
				$count_fields = count($fields);
				$addition['second_col'] .= '<A onclick="switchMenu(\'drag'.$i.'_table\');expandRight(\'drag'.$i.'_table\','.$count_fields.')" style="cursor:pointer;margin-left:1em;"><IMG SRC=images/arrow_right.gif id=drag'.$i.'_table_arrow> <B>'.$category.'</B></A><BR><DIV width=100% id=drag'.$i.'_table style="display:none;">';
				$addition['second_col'] .= '<ul id="left'.$i.'" class="sortable boxy" style="margin-left: 1em;">';
				foreach($fields as $field=>$title)
				{
					if(!$_REQUEST['fields_order'][$field])
						$addition['second_col'] .= '<li id="'.$field.'">'.$title.'</li>';
					else
						$field_titles[$field] = $title;
				}
				$addition['second_col'] .= '</ul></div>';
			}
			$addition['second_col'] .= '</TD><TD valign=top><font color=#'.Preferences('HIGHLIGHT').'><b>'._('Report\'s column:').'</b></font><BR>';
			$addition['second_col'] .= '<ul id="right" class="sortable boxier" style="height:600px;margin-left:1em;border:1px dashed #AAAAAA;">';
			if(count($_REQUEST['fields_order']))
			{
		    		foreach($_REQUEST['fields_order'] as $field=>$true)
					$addition['second_col'] .= '<li id="'.$field.'">'.$field_titles[$field].'</li>';
			}
			$addition['second_col'] .= '</ul>';
			echo '<table align=center><tr><td>';
			$addition['APPLY_MODE'] = true;
			Search($search_function_parameter,$addition);
			echo '</TD></TR></TABLE>';
		}

	
	}
	
}

if(!$_REQUEST['CREATEPDF'])
{
/*	echo "
	<script>
	function displayRecordsWithErrors()
	{
		var form = document.getElementById('advancedReportForm');
		form.action = form.action + '&showerror=true';
		form.submit();
	}
	</script>";
*/
}
/*
function _makeLogText($value,$column)
{       global $THIS_array,$table;
//var_dump($THIS_array);
        if(!$THIS_array['STUDENT_ID'] || $THIS_array['STUDENT_ID']=='new')
        {
                $THIS_array['STUDENT_ID'] = $THIS_array['STUDENT_ID'];
                $div = false;
        }
	else
    	        $div = 'force';
        if($_SESSION['SIZE'][$column]<>'')
                $addition = ' size='.intval($_SESSION['SIZE'][$column]);

	 return TextInput($value,'log_values['.$THIS_array['ID'].']['.$THIS_array['STUDENT_ID'].']['.$column.']','',$addition,$div);
}
*/
/*
function _makeLogText($value,$column)
{       global $THIS_array,$table;

        if(!$THIS_array['ID'] || $THIS_array['ID']=='new')
        {
                $THIS_array['ID'] = 'new';
                $div = false;
        }
        else
                $div = 'force';
        if($_SESSION['SIZE'][$column]<>'')
	$addition = ' size='.intval($_SESSION['SIZE'][$column]);

        return TextInput($value,'log_values['.$table.']['.$THIS_array['ID'].']['.$column.']','',$addition,$div);
}
*/
/*
function _makeLogTextInt($value,$column)
{       global $THIS_array,$table;
//var_dump($THIS_array['FULL_NAME']);
//var_dump($THIS_array);
//var_dump($THIS_array['ID']);
        if(!$THIS_array['STUDENT_ID'])// || $THIS_array['ID']=='new')
        {
//                $THIS_array['ID'] = 'new';
                $div = false;
        }
        else
                $div = 'force';
        if($_SESSION['SIZE'][$column]<>'')
	$addition = ' size='.intval($_SESSION['SIZE'][$column]);

//        return TextInput($value,'log_values['.$THIS_array['STUDENT_ID'].']['.$column.']['.str_replace(' ','_',$THIS_array['CFIELD_114_LOG_FIELD1']).']','',$addition,$div);
//        return TextInput($value,'log_values['.$THIS_array['STUDENT_ID'].']['.$column.']['.$THIS_array['LF_ID'].']','',$addition,$div);
        return TextInput($value,'log_values['.$THIS_array['LF_ID'].']['.substr($column,strpos($column,'LOG')).']','',$addition,$div);
}
*/
?>