<?php
//                echo "pr-->".$_REQUEST['preview'];
//$_SYSTEM['DisableAddonLoader'] = true;
$html_field_name='students';
$email_field = 'CFIELD_50012';
$plural = "students";

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

if($_REQUEST['sent']=='true')
{
    DisplayHeader('<IMG SRC=images/check.gif> '.sprintf(_('Report cards has been emailed to the selected %s.'),$plural));
}

if($_REQUEST['mp_arr'])
{
	foreach($_REQUEST['mp_arr'] as $mp)
		$mp_list .= ",'$mp'";
	$mp_list = substr($mp_list,1);
	$last_mp = $mp;
}
$attendance_codes = db_request(db_execute("SELECT SHORT_NAME,ID FROM ATTENDANCE_CODES_SETTINGS WHERE SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."' AND (DEFAULT_CODE!='Y' OR DEFAULT_CODE IS NULL) AND TABLE_NAME='0'"));

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

$addition['second_col'] .= '<TR><TD colspan=2><TABLE cellspasing=0>';
	$addition['second_col'] .= '<TR>';
	$addition['second_col'] .= '<TD><INPUT type=checkbox name=options[grade] id=options[grade] value=Y CHECKED><label for=options[grade]>'._('Grade').'</label></TD>';
	if(SystemPreferences('REPORT_CARD')!='grade')
		$addition['second_col'] .= '<TD><INPUT type=checkbox name=options[percent] id=options[percent] value=Y CHECKED><label for=options[percent]>'._('Percent Grade').'</label></TD>';
	else
		$addition['second_col'] .= '<TD></TD>';
/*
	$addition['second_col'] .= '</TR><TR>';
	$addition['second_col'] .= '<TD><INPUT type=checkbox name=options[gpa] value=Y >'._('GPA').'</TD>';
	if(SystemPreferences('WEIGHTED_GPA')=='Y')
		$addition['second_col'] .= '<TD><INPUT type=checkbox name=options[weighted_gpa] value=Y >'._('Weighted GPA').'</TD>';
	$addition['second_col'] .= '</TR><TR>';
	$addition['second_col'] .= '<TD colspan=2><INPUT type=checkbox name=options[average_percent_grade] value=Y >'._('Average Percent Grade').'</TD>';
*/	$addition['second_col'] .= '</TR><TR>';
	$addition['second_col'] .= '<TD><INPUT type=checkbox name=options[teacher] id=options[teacher] value=Y CHECKED><label for=options[teacher]>'._('Teacher Name').'</label></TD>';
	$addition['second_col'] .= '<TD><INPUT type=checkbox name=options[period_absences] id=options[period_absences] value=Y CHECKED><label for=options[period_absences]>'._('Amount of Absence Periods').'</label></TD>';
	$addition['second_col'] .= '</TR><TR>';
	if(SystemPreferences('USE_CREDITS')=='Y')
		$addition['second_col'] .= '<TD><INPUT type=checkbox name=options[credits] id=options[credits] value=Y><label for=options[credits]>'._('Credits').'</label></TD>';

	$addition['second_col'] .= '<TD><INPUT type=checkbox name=options[grade_descr] id=options[grade_descr] value=Y><label for=options[grade_descr]>'._('Grade Description').'</label></TD>';
	if($_REQUEST['servicefunction']=='gradelist')
	{
		$addition['second_col'] .= '</TR><TR>';
		$addition['second_col'] .= '<TD><INPUT type=checkbox name=options[classlevel] id=options[classlevel] value=Y><label for=options[classlevel]>'._('Class Level').'</label></TD>';
		if(Preferences('DISPLAY_GROUP')=='Y')
			$addition['second_col'] .= '<TD><INPUT type=checkbox name=options[group] id=options[group] value=Y><label for=options[group]>'._('Class Group').'</label></TD>';
	}
	$addition['second_col'] .= '</TR><TR>';
	$addition['second_col'] .= '<TD colspan=2><INPUT type=checkbox name=options[course_num] value=Y >'._('Course Number').'</TD>';
	$addition['second_col'] .= '</TR><TR><TD COLSPAN=2>';
	$addition['second_col'] .= '<fieldset style="border:1px solid gray;"><legend>'._('Lowest/Highest scores & Course Rank').'</legend><TABLE><TR>';
	$addition['second_col'] .= '<TD><INPUT type=checkbox name=options[low_high] id=options[low_high] value=Y><label for=options[low_high]>'._('Lowest & Highest Scores').'</label></TD>';
	$addition['second_col'] .= '<TD><INPUT type=checkbox name=options[course_rank] id=options[course_rank] value=Y><label for=options[course_rank]>'._('Course Rank').'</label></TD>';
	$addition['second_col'] .= '<TD><INPUT type=checkbox name=options[course_avg] id=options[course_avg] value=Y><label for=options[course_avg]>'._('Course Average').'</label></TD>';
	$addition['second_col'] .= '<TR><TD COLSPAN=2 ALIGN=CENTER><INPUT type=checkbox name=options[print_last] id=options[print_last] value=Y><label for=options[print_last]>'._('Print L/H & CR for last School Term Only').'</label></TD></TR>';
	$addition['second_col'] .= '</TABLE></fieldset></TD></TR><TR>';
	$addition['second_col'] .= '<TD><INPUT type=checkbox name=options[comments] id=options[comments] value=Y CHECKED><label for=options[comments]>'._('Comments').'</label></TD>';
	$addition['second_col'] .= '<TD><INPUT type=checkbox name=options[comments_legend] id=options[comments_legend] value=Y CHECKED><label for=options[comments_legend]>'._('Comment Codes Description').'</label></TD>';
	$addition['second_col'] .= '</TR><TR>';
	$addition['second_col'] .= '<TD valign=top><INPUT type=checkbox name=options[conduct] id=options[conduct] value=Y CHECKED><label for=options[conduct]>'._('Conduct').'</label><BR><BR></TD>';
	$addition['second_col'] .= '<TD valign=top><INPUT type=checkbox name=options[ilp] id=options[ilp] value=Y onclick=\'if(this.checked==true || document.getElementById("div_options_ilp_checkbox").style.display=="block")switchMenu("div_options_ilp_checkbox");document.getElementById("options[ilp_page_break]").checked=false;\'><label for=options[ilp]>'._('Long Comments').'</label></td><TD valign=top><div style="display:none;" id=div_options_ilp_checkbox><INPUT type=checkbox id=options[ilp_page_break] name=options[ilp_page_break] value=Y><label for="options[ilp_page_break]">'._('Include a Page Break before Long Comments').'</label></div></TD>';
/*
	$addition['second_col'] .= '</TR><TR>';
	$addition['second_col'] .= '<TD colspan=2><INPUT type=checkbox name=options[ytd_absences] value=Y >'._('Year-to-date Daily Absences').'</TD>';
	$addition['second_col'] .= '</TR><TR>';
	$addition['second_col'] .= '<TD colspan=2><INPUT type=checkbox name=options[mp_absences] value=Y >'._('Daily Absences this quarter').'</TD>';
	$addition['second_col'] .= '</TR><TR>';
	$addition['second_col'] .= '<TD colspan=2><INPUT type=checkbox name=options[ytd_tardies] value=Y>'._('Other Attendance Year-to-date').': <SELECT name="ytd_tardies_code">';
	foreach($attendance_codes as $code)
		$addition['second_col'] .= '<OPTION value='.$code['ID'].'>'.$code['SHORT_NAME'].'</OPTION>';
	$addition['second_col'] .= '</SELECT></TD>';
	$addition['second_col'] .= '</TR><TR>';
	$addition['second_col'] .= '<TD colspan=2><INPUT type=checkbox name=options[mp_tardies] value=Y>'._('Other Attendance this quarter').': <SELECT name="mp_tardies_code">';
	foreach($attendance_codes as $code)
		$addition['second_col'] .= '<OPTION value='.$code['ID'].'>'.$code['SHORT_NAME'].'</OPTION>';
	$addition['second_col'] .= '</SELECT></TD>';
*/
	$addition['second_col'] .= '</TR><TR>';
$addition['second_col'] .= '</TR>';
$addition['second_col'] .= '</TABLE></TD></TR>';
$addition['second_col'] .= '<TR><TD >';
$addition['second_col'] .= '<fieldset style="border:1px solid gray;"><legend>'._('School Terms').'</legend><TABLE cellspasing=0 >';

$mps_array = db_request(db_execute("SELECT SEMESTER_ID,SCHOOL_TERM_ID,SHORT_NAME FROM SCHOOL_QUARTERS WHERE SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."' ORDER BY SORT_ORDER"),array(),array('SEMESTER_ID'));
//echo "mem: ".memory_get_usage()."<br>";
$cnt = 0;
foreach($mps_array as $sem=>$quarters)
{
	$addition['second_col'] .= '<TR>';
	foreach($quarters as $qtr)
	{
		$pro = get_child_school_term('PRO',$qtr['SCHOOL_TERM_ID']);
		if($pro)
		{
			$pros = explode(',',str_replace("'",'',$pro));
			foreach($pros as $pro)
			{
				if(get_school_term($pro,'POST_START_DATE'))
					$addition['second_col'] .= '<TD><INPUT type=checkbox name=mp_arr[] id=mp_arr'.$cnt.' value='.$pro.'><label for=mp_arr'.$cnt++.'>'.get_school_term($pro,'SHORT_NAME').'</label></TD>';
			}
		}
		if(SystemPreferences('QTR_EXAMS')=='Y')
			$addition['second_col'] .= '<TD width=100><INPUT type=checkbox name=mp_arr[] id=mp_arr'.$cnt.' value=E'.$qtr['SCHOOL_TERM_ID'].'><label for=mp_arr'.$cnt++.'>'.$qtr['SHORT_NAME'].' '._('Exam').'</label></TD>';
			
		$addition['second_col'] .= '<TD width=100><INPUT type=checkbox name=mp_arr[] id=mp_arr'.$cnt.' value='.$qtr['SCHOOL_TERM_ID'].($qtr['SCHOOL_TERM_ID']==get_user_school_term()?' CHECKED':'').'><label for=mp_arr'.$cnt++.'>'.$qtr['SHORT_NAME'].'</label></TD>';
	}
	if(SystemPreferences('FINAL_EXAMS')=='Y')
		$addition['second_col'] .= '<TD><INPUT type=checkbox name=mp_arr[] id=mp_arr'.$cnt.' value=E'.$sem.'><label for=mp_arr'.$cnt++.'>'.get_school_term($sem,'SHORT_NAME').' '._('Exam').'</label></TD>';
	$addition['second_col'] .= '<TD width=100><INPUT type=checkbox name=mp_arr[] id=mp_arr'.$cnt.' value='.$sem.'><label for=mp_arr'.$cnt++.'>'.get_school_term($sem,'SHORT_NAME').'</label></TD>';
	$addition['second_col'] .= '</TR>';
}
//echo "mem2: ".memory_get_usage()."<br>";
$addition['second_col'] .= '<TR align=middle><TD align=middle colspan=6><HR>';


$fy_array = db_request(db_execute("SELECT SCHOOL_TERM_ID FROM SCHOOL_YEARS WHERE SCHOOL_ID='".get_school_id()."' AND SCHOOL_YEAR='".get_school_year()."'"));
if(SystemPreferences('FY_EXAMS')=='Y')
	$addition['second_col'] .= '<INPUT type=checkbox name=mp_arr[] id=mp_arr'.$cnt.' value=E'.$fy_array[1]['SCHOOL_TERM_ID'].'><label for=mp_arr'.$cnt++.'>'.get_school_term('E'.$fy_array[1]['SCHOOL_TERM_ID'],'SHORT_NAME').'</label>';

$addition['second_col'] .= '&nbsp; &nbsp; <INPUT type=checkbox name=mp_arr[] id=mp_arr'.$cnt.' value='.$fy_array[1]['SCHOOL_TERM_ID'].'><label for=mp_arr'.$cnt++.'>'.get_school_term($fy_array[1]['SCHOOL_TERM_ID'],'SHORT_NAME').'</label></TD>';


$addition['second_col'] .= '</TABLE></fieldset> ';
//$addition['second_col'] .= '</TD></TR><TR align=middle><TD align=middle>';

$addition['second_col'] .= '</TR></TABLE></fieldset>';

$periods_array = db_request(db_execute("SELECT SCHOOL_PERIOD_ID,SHORT_NAME,TITLE FROM SCHOOL_PERIODS WHERE SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."' ORDER BY SORT_ORDER,TITLE"));
$addition['second_col'] .= '<script language=javascript>
	function doSortingOnChange(select)
	{
		if(select.options[select.selectedIndex].value!="student")
			document.getElementById("sort_teacher_checkbox_div").style.display="block";
		else
			document.getElementById("sort_teacher_checkbox_div").style.display="none";		
	}
</script>';
$addition['second_col'] .= '<TABLE align=left><TR><TD width=150 align=left>'._('Page Orienation').'</TD><TD><SELECT name=orient> <OPTION value=auto>'._('Auto').'</OPTION>';
$addition['second_col'] .= '<OPTION value=portrait>'._('Portrait').'</OPTION>';
$addition['second_col'] .= '<OPTION value=landscape>'._('Landscape').'</OPTION>';
$addition['second_col'] .= '</SELECT></TD></TR>';
//Grading scale selector
$grading_scale_array = db_request(db_execute("SELECT ID,TITLE FROM GRADES_CARD_TYPES WHERE SCHOOL_YEAR = ".get_school_year()." AND SCHOOL_ID = ".get_school_id()));
foreach($grading_scale_array as $num=>$garray)
	$goptions .= '<OPTION value='.$garray['ID'].'>'.$garray['TITLE'].'</OPTION>';
$addition['second_col'] .= '<TR><TD width=150 align=left>'._('Grading scale').'</TD><TD><SELECT name=grading_scale> <OPTION value=auto>'._('Auto').'</OPTION>';
$addition['second_col'] .= $goptions;
$addition['second_col'] .= '</SELECT></TD></TR>';

$addition['second_col'] .= '<TR><TD width=150 align=left>'._('Sort Report Cards ').'</TD><TD><SELECT name=sorting onchange="doSortingOnChange(this);"><OPTION value=student>'._('Alphabetically by Student Name').'</OPTION>';

foreach($periods_array as $period)
{
	$addition['second_col'] .= '<OPTION value=p'.$period['SCHOOL_PERIOD_ID'].'>'.$period['TITLE'].' '._('Teacher Name').'</OPTION>';
}
	$addition['second_col'] .= '<OPTION value=p'.$period['SCHOOL_PERIOD_ID'].'>'.$period['TITLE'].' '._('Teacher Name').'</OPTION>';
	$addition['second_col'] .= '</SELECT><DIV id=sort_teacher_checkbox_div style="display:none;"><INPUT type=checkbox name=options[sort_teacher] id=options[sort_teacher] value=Y ><label for="options[sort_teacher]">'._('Display this Teacher on Each Report Card').'</label></DIV></TD></TR></TABLE><BR>';


if($_REQUEST['servicefunction']!='gradelist')
{
	Widgets('document_template');
	Widgets('mailing_labels');
	//echo "mem 10: ".memory_get_usage()."<br>";	
}

if(isset($_REQUEST[$html_field_name]) && $_REQUEST['delete']!='true')
{
    $addition['SELECT'] .= ",sg1.SCHOOL_YEAR as GRADE_SCHOOL_YEAR,sg1.COURSE_ID,sg1.GRADE_TYPE_ID,sg1.GRADE_TITLE,sg1.PERCENT_GRADE,sg1.COMMENT AS COMMENT_TITLE,sg1.CONDUCT,sg1.STUDENT_ID,sg1.COURSE_TITLE,sg1.COURSE_NUM,sg1.SCHOOL_TERM_ID,sg1.TEACHER,sp.SORT_ORDER,sg1.COURSE_SECTION_ID,

		COALESCE(CAST(sg1.COURSE_ID AS VARCHAR)".CCAT."sg1.COURSE_CREDIT_TITLE,sg1.COURSE_TITLE) AS COURSE,".db_case(array("sg1.CARRIES_CREDITS","'Y'","sg1.CREDITS","'0'"))." AS CREDITS";
//		ssr.COURSE_RANK,ssr.LOW_SCORE||'/'||ssr.HIGH_SCORE AS LOW_HIGH,		
    if($_REQUEST['options']['course_avg'])
    {
        $addition['SELECT'] .=	" ,((SELECT sum(sg2.PERCENT_GRADE) FROM STUDENT_GRADES_CARD sg2 WHERE sg1.COURSE_ID=sg2.COURSE_ID)/(SELECT count(sg3.STUDENT_ID) FROM STUDENT_GRADES_CARD sg3 WHERE sg1.COURSE_ID=sg3.COURSE_ID)) AS COURSE_AVG";
    }
    if($_REQUEST['options']['period_absences'])
    {
        $addition['SELECT'] .=	" ,(SELECT count(*) FROM STUDENT_ATTENDANCE_PERIODS ap,ATTENDANCE_CODES_SETTINGS ac
                        WHERE ac.ID=ap.ATTENDANCE_CODE AND ac.STATE_CODE='A' AND ap.COURSE_SECTION_ID=sg1.COURSE_SECTION_ID AND ap.STUDENT_ID=ssm.STUDENT_ID) AS YTD_ABSENCES,
                    (SELECT count(*) FROM STUDENT_ATTENDANCE_PERIODS ap,ATTENDANCE_CODES_SETTINGS ac
                        WHERE ac.ID=ap.ATTENDANCE_CODE AND ac.STATE_CODE='A' AND ap.COURSE_SECTION_ID=sg1.COURSE_SECTION_ID AND sg1.SCHOOL_TERM_ID=CAST(ap.SCHOOL_TERM_ID AS TEXT) AND ap.STUDENT_ID=ssm.STUDENT_ID) AS MP_ABSENCES ";
    }
    $addition['FROM'] .= ",STUDENT_GRADES_CARD sg1     

			LEFT OUTER JOIN COURSE_SECTIONS rc_cp ON (rc_cp.COURSE_SECTION_ID=sg1.COURSE_SECTION_ID) LEFT OUTER JOIN SCHOOL_PERIODS sp ON (sp.SCHOOL_PERIOD_ID=rc_cp.SCHOOL_PERIOD_ID)";
    $addition['WHERE'] .= " AND sg1.SCHOOL_TERM_ID IN (".$mp_list.") AND sg1.STUDENT_ID=ssm.STUDENT_ID ";
//		        LEFT OUTER JOIN STUDENTS_SCORES_RATING ssr ON (sg1.STUDENT_ID=ssr.STUDENT_ID AND sg1.COURSE_ID=ssr.COURSE_ID AND sg1.SCHOOL_TERM_ID=ssr.SCHOOL_TERM_ID)
    $students = array();
//    var_dump($_REQUEST[$html_field_name]);
    foreach($_REQUEST[$html_field_name] as $k => $v)
  
    {
        $students []= $k;
    }
    $stu_list[] = $students;

    //echo count($students)."|<br>";
//    var_dump($stu_list);
    $students = implode("','", $students);
    //echo $students;
//    echo "AND ssm.STUDENT_ID IN ('".$students."')";
    if($students)
        $addition['WHERE'].= "AND ssm.STUDENT_ID IN ('".$students."')";

    // perhaps this should be done in a separate query.  If performance is a problem, then use php sorting across the separate array
    if(substr($_REQUEST['sorting'],0,1)=='p')
    {
        if(!($current_mp = get_current_school_term('QTR',get_db_date(),false)))
            $current_mp = get_user_school_term();

        $addition['ORDER_BY'] = '('.db_limit("SELECT sta.LAST_NAME".CCAT."', '".CCAT."sta.FIRST_NAME AS NAME FROM USERS sta,STUDENT_SCHEDULE sched,COURSE_SECTIONS cp WHERE cp.COURSE_SECTION_ID=sched.COURSE_SECTION_ID AND sta.USER_ID=cp.TEACHER_ID AND sched.STUDENT_ID=ssm.STUDENT_ID AND sched.SCHOOL_YEAR=cp.SCHOOL_YEAR AND sched.SCHOOL_YEAR=ssm.SCHOOL_YEAR AND cp.SCHOOL_TERM_ID IN (".get_all_school_term('QTR',$current_mp).") AND cp.SCHOOL_PERIOD_ID='".substr($_REQUEST['sorting'],1)."' AND ('".get_db_date('postgres')."' BETWEEN sched.START_DATE AND sched.END_DATE OR (sched.START_DATE<='".get_db_date('postgres')."' AND sched.END_DATE IS NULL))",1).') ASC,s.LAST_NAME,s.FIRST_NAME,s.MIDDLE_NAME,sp.SORT_ORDER,sg1.COURSE_TITLE';
        $addition['SELECT'] .= ',('.db_limit("SELECT sta.LAST_NAME".CCAT."', '".CCAT."sta.FIRST_NAME AS NAME FROM USERS sta,STUDENT_SCHEDULE sched,COURSE_SECTIONS cp WHERE cp.COURSE_SECTION_ID=sched.COURSE_SECTION_ID AND sta.USER_ID=cp.TEACHER_ID AND sched.STUDENT_ID=ssm.STUDENT_ID AND sched.SCHOOL_YEAR=cp.SCHOOL_YEAR AND sched.SCHOOL_YEAR=ssm.SCHOOL_YEAR AND cp.SCHOOL_TERM_ID IN (".get_all_school_term('QTR',$current_mp).") AND cp.SCHOOL_PERIOD_ID='".substr($_REQUEST['sorting'],1)."' AND ('".get_db_date('postgres')."' BETWEEN sched.START_DATE AND sched.END_DATE OR (sched.START_DATE<='".get_db_date('postgres')."' AND sched.END_DATE IS NULL))",1).') AS SORT_TEACHER';
    }
    else
        $addition['ORDER'] .= ",sp.SORT_ORDER,sg1.COURSE_TITLE";

    $addition['group']	= array('STUDENT_ID');
    if($_REQUEST['mailing_labels']=='Y')
        $addition['group'][] = 'ADDRESS_ID';
    $addition['group'][] = 'COURSE'; // was course_section_id -> changed so that students will only have one line on the report card if they switch classes in the middle of the year
    $addition['group'][] = 'SCHOOL_TERM_ID';
}
else
{
    Widgets('all');

    if($_REQUEST['servicefunction']!='gradelist')
        ;//$addition['action'] .= "&CREATEPDF=true";
    else
        $addition['action'] .= '&servicefunction=gradelist';
    $addition['force_search'] = true;
    $addition['search_button_title'] = _('Next');
    $addition['link']['FULL_NAME'] = false;
    $addition['SELECT'].=",'' as CHECKBOX, CFIELD_50012";

    $addition['columns_before'] = array('CHECKBOX'=>'</A><INPUT type=checkbox value=Y name=controller onclick="checkAll(this.form,this.checked,\''.$html_field_name.'\');CheckAll_hilite(this.form,this.form.controller.checked,\''.$html_field_name.'\');"><A>');
    $addition['functions']=array('CHECKBOX'=>'_makeChooseCheckbox1');
    $addition['options']['onclick']="check_clicked(this);";
}

if($_REQUEST['delete']=='true')
{
	if(DeletePrompt(_('final grade')))
	{
		db_execute("DELETE FROM STUDENT_GRADES_CARD WHERE SCHOOL_YEAR='".get_school_year()."' AND STUDENT_ID='".$_REQUEST['student_id']."' AND COURSE_SECTION_ID='".$_REQUEST['course_section_id']."' AND SCHOOL_TERM_ID='".$_REQUEST['school_term_id']."'");
		$_REQUEST['delete'] = 'false';
	}
}

if(!(!$_REQUEST['search_servicefunction'] || $_REQUEST['search_servicefunction']=='search' || $_SYSTEM['modules_search']) && !isset($_REQUEST['CREATEPDF']))
{
    $singular = 'student';
    //echo "<form name=letters_form method=post action='modloader.php?servicemod=$_REQUEST[servicemod]&servicefunction=$_REQUEST[servicefunction]&report=$_REQUEST[report]&CREATEPDF=true' enctype=multipart/form-data>";
    echo "<form name=letters_form method=post action='".SetRequestOptions()."&CREATEPDF=true' enctype=multipart/form-data>";
    echo '<script language=javascript>
		function changeto_address()
		{
			for(var i=0;i<document.letters_form.to_address.length;i++)
			{
				if(document.letters_form.to_address[i].checked)
					var to_address_value = document.letters_form.to_address[i].value;
			}

			if(to_address_value.substr(0,5)=="email")
			{
				document.getElementById("email_options_div").style.display="block";
				document.getElementById("email_subject_input").focus();
				document.getElementById("top_submit_button").value = "'._('Send Emails').'";
				if(document.getElementById("bottom_submit_button"))document.getElementById("bottom_submit_button").value = "'._('Send Emails').'";
				//document.getElementById("top_submit_button_1").value="'._('Send Emails & Add Log Entries for Each Student').'";
				}
				else
				{
				document.getElementById("email_options_div").style.display="none";
				document.getElementById("top_submit_button").value = "'._('Print').'";
				if(document.getElementById("bottom_submit_button"))document.getElementById("bottom_submit_button").value = "'._('Print').'";
				//document.getElementById("top_submit_button_1").value="'._('Print Letters & Add Log Entries for Each Student').'";
			}
		}
		</script>
		';
    $max_attach = 5;
    echo "<script>
            var num_attach = 0;
            var max_attach = ".(isset($max_attach)?$max_attach:5)."; //maximum available attachments
            var id_attach = 0;

            function update_attach_label()
            {
                var link = document.getElementById('attach_label');
                var label = '';
                var more = max_attach - num_attach;
                if(num_attach>0)
                    label = '"._('Attach another file')." (' + more + ' "._('more').")';
                else
                    label = '"._('Attach file')." (' + more + ' "._('more').")';

                link.innerHTML = label;
                link.style.display=(num_attach>=max_attach)?'none':'';
            }

            function insertAttachment()
            {
                if(num_attach<max_attach)
                {
                    var newrow = document.createElement('tr');
                    var td=document.createElement('td');
                    td.setAttribute('colspan','2');
                    td.innerHTML= '<INPUT type=file name=email_attach'+id_attach+' >&nbsp;<a href=# onclick=removeAttachment(this.parentNode.parentNode);>"._('Remove')."</a>';
                    newrow.appendChild(td);
                    var table = document.getElementById('email_table');
                    table.firstChild.insertBefore(newrow, document.getElementById('attach_row'));

                    num_attach++;
                    id_attach++;

                    update_attach_label();
                }
            }

            function removeAttachment(row)
            {
                document.getElementById('email_table').firstChild.removeChild(row);
                num_attach--;

                update_attach_label();
            }
        </script>";

    $left = '<TABLE style="display:inline;" >';
    $left .= '<TR><TD style="padding-right:30px;"><B>'._('Print Report Card:').'</B></TD><TD><B>'._('Send Report Card by Email:').'</B></TD></TR>';
    if ($singular == 'student')
    {
    	$left .= '<TR><TD><INPUT type=radio name=to_address value=print_students CHECKED id="to_address_student" onclick="changeto_address();"><label for="to_address_student">'._('For each ')._('student').'</label></TD><TD><INPUT type=radio name=to_address value="email_students" id="to_address_email_students" onclick="changeto_address();"><label for="to_address_email_students">'._('To each ')._('student').'</label></TD></TR>';
    }else{
	$left .= '<TR><TD><INPUT type=radio name=to_address value=print_students CHECKED id="to_address_student" onclick="changeto_address();"><label for="to_address_student">'._('For each ').$singular.'</label></TD><TD><INPUT type=radio name=to_address value="email_students" id="to_address_email_students" onclick="changeto_address();"><label for="to_address_email_students">'._('To each ').$singular.'</label></TD></TR>';
    }
    if($students_table!='USERS')
    {
        $left .= '<TR><TD></TD><TD><INPUT type=radio name=to_address value="email_parents" id="to_address_email_parents" onclick="changeto_address();"><label for="to_address_email_parents">'._('To each Custodial Contact').'</label></TD></TR>';
    }
    $left .= '<TR><TD colspan=2 align=left>';
    $left .= '<DIV style="display:none;" id="email_options_div"><table id=email_table><tbody>';
    $left .= '<tr><td>'._('Email Subject').'</td><td><INPUT size=50 type=text name=email_subject id=email_subject_input value="'._('Progress Report - ').strip_tags(ProperDate(get_db_date())).'"></td></tr>';
    $left .= '<tr><td>'._('CC').'</td><td><input type=text name=email_cc size=50 ></td></tr>';
    if(get_user('EMAIL'))
        $left .= '<tr><td colspan=2><INPUT type=checkbox name=CCme value=Y id=ccme CHECKED><label for=ccme>'._('Send a Copy to Myself').' ('.get_user('EMAIL').')</label></td></tr>';
    $left .= '<tr id=attach_row><td colspan=2><a id=attach_label href=# onclick=insertAttachment();>'._('Attach file').' ('.$max_attach._(' more').')'.'</a></td></tr>';
    $left .= '</tbody></table></DIV>';
    $left .= '</TD></TR></TABLE>';
    DisplayHeader($left);
    DisplayHeader('','<INPUT TYPE=button value="'._('Preview').'" onclick="this.form.target=\'_blank\';this.form.preview.value=\'true\';this.form.submit();">'.' &nbsp; <INPUT type=submit value="'._('Print').'" id="top_submit_button" onclick="this.form.target=\'blank\';this.form.preview.value=\'false\';"">'/*.' &nbsp; <INPUT type=submit name=printandlog value="'._('Print Letters & Add Log Entries for Each Student').'" id="top_submit_button_1" onclick="this.form.target=\'\';this.form.preview.value=\'false\';"">'*/);//Print Letters & add Log Entries for Each Student
//    DisplayHeader('','<INPUT TYPE=button value="'._('Preview').'" onclick="this.form.target=\'_blank\';this.form.preview.value=\'true\';this.form.submit();">'.' &nbsp; <INPUT type=submit value="'._('Print').'" id="top_submit_button" onclick="this.form.target=\'\';this.form.preview.value=\'false\';"">'/*.' &nbsp; <INPUT type=submit name=printandlog value="'._('Print Letters & Add Log Entries for Each Student').'" id="top_submit_button_1" onclick="this.form.target=\'\';this.form.preview.value=\'false\';"">'*/);//Print Letters & add Log Entries for Each Student
    echo '<HR>';
    echo '<INPUT type=hidden name=preview value="false">';
}
//var_dump($_REQUEST[$html_field_name]);
//var_dump($_REQUEST['delete']);
//die();
if(!isset($_REQUEST[$html_field_name])) //(!$_REQUEST['search_servicefunction'] || $_REQUEST['search_servicefunction']=='search' || $_SYSTEM['modules_search']) && $_REQUEST['delete']!='true')
{
	$addition['new'] = true;
	Search('student_id',$addition);
}
elseif($_REQUEST['delete']!='true')
{
	if(!$_REQUEST['mp_arr'])
		BackPrompt(_('You must choose at least one school term'));
//echo "mem3: ".memory_get_usage()."<br>";
	unset($array);
//	echo "<br><br>-------1<br><br>";
	$array = get_student_list($addition);
//	echo "<br><br>-------<br><br>";
//echo "mem4: ".memory_get_usage()."<br>";
	$grade_descr = db_request(db_execute("SELECT SCHOOL_YEAR,SCALE_ID,TITLE,DESCRIPTION FROM GRADES_CARD_SETTINGS"),array(),array('SCHOOL_YEAR','SCALE_ID','TITLE'));
//	echo "mem11: ".memory_get_usage()."<br>";
//var_dump($mp_list);
//echo "<br><br>-------2<br><br>";
	if($_REQUEST['options']['low_high']=='Y' || $_REQUEST['options']['course_rank']=='Y')	
		$lh_rating = db_request(db_execute("SELECT * FROM STUDENTS_SCORES_RATING WHERE STUDENT_ID IN ('".$students."') AND SCHOOL_TERM_ID IN (".$mp_list.")"),array(),array('STUDENT_ID','COURSE_ID','SCHOOL_TERM_ID'));
//echo "<br><br>-------3<br><br>";
//	$lh_rating = db_request(db_execute("SELECT * FROM STUDENTS_SCORES_RATING"),array(),array());
//echo "mem12: ".memory_get_usage()."<br>";	
	// since this column is added if searching for inactive students
	unset($addition['columns_after']['ACTIVE']);

	if($_REQUEST['options']['comments'])
	{
		if($DBType == 'mssql')
			$comments_array = db_request(db_execute("SELECT ID,TITLE, LEFT(TITLE, CHARINDEX('.', TITLE) - 1) AS SHORT_NAME FROM GRADES_CARD_COMMENTS WHERE SCHOOL_ID='".get_school_id()."' AND SCHOOL_YEAR='".get_school_year()."' ORDER BY TITLE"),array(),array('SHORT_NAME'));
		else
			$comments_array = db_request(db_execute("SELECT ID,TITLE,trim(trailing '.' from SUBSTR(TITLE,1,2)) AS SHORT_NAME FROM GRADES_CARD_COMMENTS WHERE SCHOOL_ID='".get_school_id()."' AND SCHOOL_YEAR='".get_school_year()."' ORDER BY TITLE"),array(),array('SHORT_NAME'));
	}
	if($_REQUEST['options']['mp_tardies']=='Y' || $_REQUEST['options']['ytd_tardies']=='Y')
	{
		unset($addition);
		$addition['SELECT_ONLY'] .= "ap.SCHOOL_DATE,ap.COURSE_SECTION_ID,ac.ID AS ATTENDANCE_CODE,ap.SCHOOL_TERM_ID,ssm.STUDENT_ID ";
		$addition['FROM'] .= ",ATTENDANCE_CODES_SETTINGS ac,STUDENT_ATTENDANCE_PERIODS ap ";
		$addition['WHERE'] .= " AND ac.ID=ap.ATTENDANCE_CODE AND (ac.DEFAULT_CODE!='Y' OR ac.DEFAULT_CODE IS NULL) AND ac.SCHOOL_YEAR=ssm.SCHOOL_YEAR AND ap.STUDENT_ID=ssm.STUDENT_ID";
		$addition['group'][] = 'STUDENT_ID';
		$addition['group'][] = 'ATTENDANCE_CODE';
		$addition['group'][] = 'SCHOOL_TERM_ID';
		Widgets('all');
//		echo "nnnnn";
		$attendance_array = get_student_list($addition);
	}

	if($_REQUEST['options']['mp_absences']=='Y' || $_REQUEST['options']['ytd_absences']=='Y')
	{
		unset($addition);
		$addition['SELECT_ONLY'] .= "ad.SCHOOL_DATE,ad.SCHOOL_TERM_ID,ad.STATE_VALUE,ssm.STUDENT_ID ";
		$addition['FROM'] .= ",STUDENT_ATTENDANCE_DAYS ad ";
		$addition['WHERE'] .= " AND ad.STUDENT_ID=ssm.STUDENT_ID AND ad.SCHOOL_YEAR=ssm.SCHOOL_YEAR AND (ad.STATE_VALUE='0.0' OR ad.STATE_VALUE='.5') AND ad.SCHOOL_DATE<='".get_school_term($last_mp,'END_DATE')."'";
		$addition['group'][] = 'STUDENT_ID';
		$addition['group'][] = 'SCHOOL_TERM_ID';
		Widgets('all');
//		echo "vvvvv";
		$attendance_day_array = get_student_list($addition);
	}
	
	if($_REQUEST['options']['average_percent_grade']=='Y' || $_REQUEST['options']['gpa']=='Y' || $_REQUEST['options']['weighted_gpa']=='Y')
	{
		unset($addition);
		$addition['SELECT_ONLY'] .= 'ssm.STUDENT_ID,sgc.GPA,sgc.WEIGHTED_GPA,sgc.CLASS_RANK,'."(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' AND asrcg.PERCENT_GRADE!='-1') AS AVERAGE_PERCENT_GRADE";
		$addition['functions']['AVERAGE_PERCENT_GRADE'] = 'Percent';
		$addition['functions']['GPA'] = $addition['functions']['WEIGHTED_GPA'] = '_roundGPA';

		if(strpos($addition['FROM'],'STUDENT_GPA_TOTALS sgc')===false)
		{
			$addition['FROM'] .= " LEFT OUTER JOIN STUDENT_GPA_TOTALS sgc ON (sgc.STUDENT_ID=ssm.STUDENT_ID AND sgc.SCHOOL_TERM_ID='".$last_mp."')";
		}
		$addition['group'][] = 'STUDENT_ID';
		Widgets('all');
//		echo "bbbbbb";
		$gpa_array = get_student_list($addition);
	}

	if($_REQUEST['options']['ilp']=='Y')
	{
		unset($addition);
		$addition['SELECT_ONLY'] .= 'ssm.STUDENT_ID,smc.COMMENT';

		$addition['FROM'] .= " LEFT OUTER JOIN STUDENT_TERM_COMMENTS smc ON (smc.STUDENT_ID=ssm.STUDENT_ID AND smc.SCHOOL_TERM_ID='".$last_mp."')";

		$addition['group'][] = 'STUDENT_ID';
		Widgets('all');
		$ilp_array = get_student_list($addition);
	}
	if(count($array))
	{
//		echo "mem 11: ".memory_get_usage()."<br>";
		if($_REQUEST['servicefunction']=='gradelist')
		{
//		echo "grdaelist";
//			$grademsg = DisplayHeader(".:".ProgramTitle().":.");
			$grademsg = DisplayHeaderBuffered(".:".ProgramTitle().":.",null,null,null);
			if($_REQUEST['stuid'])
				DrawStudentHeader();
			$i = 0;
			foreach($array as $student_id=>$course_sections)
			{
				$course_section_id = key($course_sections);
				$grades_array[$i+1]['FULL_NAME'] = $course_sections[$course_section_id][key($course_sections[$course_section_id])][1]['FULL_NAME'];
				$columns = array('FULL_NAME'=>_('Student Name'),'CLASSLEVEL_ID'=>_('Class Level'),'GROUP_ID'=>_('Class Group'),'COURSE_TITLE'=>_('Course Name'));
				if($_REQUEST['options']['course_num']=='Y')
					$columns += array('COURSE_NUM'=>_('Course Number'));
				$columns += array('ABSENCES'=>_('Abs. Periods'));
				if($_REQUEST['options']['period_absences']!='Y')
					unset($columns['ABSENCES']);
				if($_REQUEST['options']['classlevel']!='Y')
					unset($columns['CLASSLEVEL_ID']);
				if($_REQUEST['options']['group']!='Y')
					unset($columns['GROUP_ID']);

				// .'<BR>'._('YTD').' / '._('MP')
				if($addition['columns_after'])
				{
					$columns += $addition['columns_after'];
					foreach($addition['columns_after'] as $column=>$title)
						$grades_array[$i+1][$column] = $course_sections[$course_section_id][key($course_sections[$course_section_id])][1][$column];
				}
				$grades_array[$i+1]['bgcolor'] = 'FFFFFF';
				foreach($course_sections as $course_section_id=>$mps)
				{
					$i++;
					if($_REQUEST['GridSortingBy'] || $_REQUEST['msr_rule_value'])
						$grades_array[$i]['FULL_NAME'] = $course_sections[$course_section_id][key($course_sections[$course_section_id])][1]['FULL_NAME'];
					if($_REQUEST['options']['classlevel']=='Y' && !$cadded[$student_id][$course_sections[$course_section_id][key($course_sections[$course_section_id])][1]['CLASSLEVEL_ID']])
					{
						$cadded[$student_id][$course_sections[$course_section_id][key($course_sections[$course_section_id])][1]['CLASSLEVEL_ID']] = true;
						$grades_array[$i]['CLASSLEVEL_ID'] = $course_sections[$course_section_id][key($course_sections[$course_section_id])][1]['CLASSLEVEL_ID'];
					}
					if($_REQUEST['options']['group']=='Y' && !$cadded2[$student_id][$course_sections[$course_section_id][key($course_sections[$course_section_id])][1]['GROUP_ID']])
					{
						$cadded2[$student_id][$course_sections[$course_section_id][key($course_sections[$course_section_id])][1]['GROUP_ID']] = true;
						$grades_array[$i]['GROUP_ID'] = $course_sections[$course_section_id][key($course_sections[$course_section_id])][1]['GROUP_ID'];
					}
					if($_REQUEST['options']['course_num']=='Y')
						$grades_array[$i]['COURSE_NUM'] = $course_sections[$course_section_id][key($course_sections[$course_section_id])][1]['COURSE_NUM'];
					$grades_array[$i]['STUDENT_ID'] = $student_id;
					$grades_array[$i]['COURSE_SECTION_ID'] = $course_section_id;
					$grades_array[$i]['SCHOOL_TERM_ID'] = key($mps);
					$grades_array[$i]['COURSE_TITLE'] = $mps[key($mps)][1]['COURSE_TITLE'];
					foreach($_REQUEST['mp_arr'] as $mp)
					{
						if($mps[$mp])
						{
							$grades_array[$i][$mp] = ' ';
							if($_REQUEST['options']['percent']=='Y' && $mps[$mp][1]['PERCENT_GRADE'])
								$grades_array[$i][$mp] = $mps[$mp][1]['PERCENT_GRADE'].'% ';
							if($_REQUEST['options']['grade']=='Y')
								$grades_array[$i][$mp] .= $mps[$mp][1]['GRADE_TITLE'];	
//							if($_REQUEST['options']['grade_descr']=='Y')
//							    if($grade_descr[$mps[$mp][1]['GRADE_SCHOOL_YEAR']][$mps[$mp][1]['GRADE_TYPE_ID']][$mps[$mp][1]['GRADE_TITLE']][1]['DESCRIPTION'])
//								$grades_array[$i][$mp] .= " (".$grade_descr[$mps[$mp][1]['GRADE_SCHOOL_YEAR']][$mps[$mp][1]['GRADE_TYPE_ID']][$mps[$mp][1]['GRADE_TITLE']][1]['DESCRIPTION'].")";

							// If the final exam is graded or delayed
							if($mps[$mp][1]['PERCENT_GRADE']=='-1')
								$grades_array[$i][$mp] = _('Delayed');	
						}
					}
					$grades_array[$i]['TEACHER'] = $mps[$last_mp][1]['TEACHER'];
					$grades_array[$i]['COMMENT'] = $mps[$last_mp][1]['COMMENT_TITLE'];
					$grades_array[$i]['CONDUCT'] = $mps[$last_mp][1]['CONDUCT'];
					$grades_array[$i]['ABSENCES'] = $mps[$last_mp][1]['YTD_ABSENCES'];
					$grades_array[$i]['CREDITS'] = $mps[$last_mp][1]['CREDITS'];
				}
			}

			if($_REQUEST['options']['teacher']=='Y')
				$columns += array('TEACHER'=>_('Teacher Name'));
			if($_REQUEST['options']['period_absences']=='Y')
				$columns += array('ABSENCES'=>_('Absences').'<BR>'._('FY').' / '._('MP'));
			if($addition['columns_after'])
				$columns += $addition['columns_after'];
			foreach($_REQUEST['mp_arr'] as $mp)
				$columns[$mp] = get_school_term($mp);
			if($_REQUEST['options']['conduct']=='Y')
				$columns['CONDUCT'] = _('Conduct');
			if($_REQUEST['options']['credits']=='Y')
				$columns['CREDITS'] = _('Credits');
			if($_REQUEST['options']['comments']=='Y')
				$columns['COMMENT'] = _('Comments');
//			if($_REQUEST['options']['course_rank']=='Y')
//				$columns['COURSE_RANK'] = _('Course Rank');
			
			if(count($_REQUEST['mp_arr'])==1)
			{
		//		$link['remove']['link'] = SetRequestOptions(null,array('student_id','course_section_id','school_term_id','delete_ok'))."&amp;delete=true";
		//		$link['remove']['variables'] = array('student_id'=>'STUDENT_ID','course_section_id'=>'COURSE_SECTION_ID','school_term_id'=>'SCHOOL_TERM_ID');
			}
//			echo '<FORM action="'.SetRequestOptions(null,array('msr_rule_column','msr_rule_op','msr_rule_value','msr_rule_cond')).'" method=POST>';
			//$message .= GridoutputBuffered($grades_array,$columns,'','',array(),array(),array('print'=>false));
//			$grademsg .= Gridoutput($grades_array, $columns, '', '', $link, null, array('filter' => true));
			$grademsg .= GridoutputBuffered($grades_array, $columns, '', '', $link, array(), array('print'=>false));
//			echo '</FORM>';
			$mode = 'print_students';			
//			echo "--->".$mode;
		} //if($_REQUEST['servicefunction']=='gradelist') //end grade list
		else
		{ 
	    	        $mode = $_REQUEST['to_address'];
//echo "---->".$_REQUEST['preview'];
	                //PDF engine setup
	                if($mode == 'print_students' && $_REQUEST['preview']!='true')
	                {
        		        $cols_count = count($_REQUEST['mp_arr']);
		                if($_REQUEST['options']['teacher'])
            			        $cols_count += 2;
		                if($_REQUEST['options']['comments'])
		                        $cols_count += 2;

				if($_REQUEST['orient'] == 'auto')
				{
		            		if($cols_count<9)
            			    		$orientation = 'portrait';
			                else
	            			        $orientation = 'landscape';
	            		}
	            		else
	            			$orientation = $_REQUEST['orient'];

		                $handle = PDFStart("--webpage --quiet -t pdf12 --no-links --".$orientation." --footer t --header . --left 0.5in --top 0.5in");
            		} //if($mode == 'print_students')
	                else
	                {
		                switch($mode)
		                {
		                        case 'print_students':
		                        break;

		                        case 'email_parents':
			                        $_REQUEST['fields']['FATHER_NAME'] = true;
                    				$_REQUEST['fields']['FATHER_EMAIL'] = true;
			                        $_REQUEST['fields']['MOTHER_NAME'] = true;
			                        $_REQUEST['fields']['MOTHER_EMAIL'] = true;
			                        $_REQUEST['fields']['SCHOOL_ID'] = true;
		                        break;

		                        case 'email_students':
		        	                $_REQUEST['fields'][$email_field] = true;
			                        $_REQUEST['fields']['SCHOOL_ID'] = true;
		                        break;
		                } //switch

		                require_once $staticpath."js/Swift/lib/Swift.php";
//		    	    echo "mem 9: ".memory_get_usage()."<br>";
            			if($_REQUEST['fields'])
		                {
		                        $contacts = array('FATHER'=>_('Parent/Father'),'MOTHER'=>_('Parent/Mother'),'EMERGENCY'=>_('3rd Contact/Emergency'),'CONTACT'=>_('4th Contact'));
		                        $elems = array('NAME'=>_('Name'),
		                		   'CELL'=>_('Cell Phone'),
		                		   'WORK'=>_('Work Phone'),
		                		   'EMPLOYER'=>_('Employer'),
		                		   'OCCUPATION'=>_('Occupation'),
		                		   'EMAIL'=>_('E-mail'),
            					   'ADDRESS'=>_('Address'),
                				   'CITY'=>_('City'),
		                		   'STATE'=>_('State'),
		                		   'ZIPCODE'=>_('Zipcode'),
		                    		   'HOMEPHONE'=>_('Home Phone'),
            					   'STUDENTRELATION'=>_('Relationship'),
		                		   'CUSTODY'=>_('Has Custody'),
		                		   'EMERGENCY'=>_('Is Emergency'));

				                    //include($staticpath.'modules/mod_portal/ExternalLinker.php');
				                    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)
			                                $elem_list .= "OR LOWER(pjc.TITLE) LIKE '".strtolower($elem)."%' ";
			                        $elem_list = substr($elem_list,3);

			                        $addition2 = array(); // $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
			                        if($addition2['FROM_ADDED_TO'] == 'end')
			                                $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)'.$addition2['FROM'];
			                        else
			                                $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();
//			                        echo "mem before: ".memory_get_usage()."<br>";
                    				$contacts_array = get_student_list($addition2);
//                    				echo "mem after: ".memory_get_usage()."<br>";
		                	}
		                } //if($_REQUEST['fields'])

            			if(get_user('EMAIL') && $_Config['allow_nonsender_email']!==false)
	                    	    $from_address = get_user('EMAIL');
		                else //*/
		                {
		                        $from_address = $_Mail['from'];
		                        if(get_user('EMAIL'))
			                        $reply_to = get_user('EMAIL');
		                }
		                if(get_user('PROFILE')=='teacher' || get_user('PROFILE')=='admin')
	    	                	$from_name = get_user('NAME').' - '.$GeneralTitle;
	        	        else
	                	        $from_name = get_school(get_school_id());
	                } //end email mode setup
//			echo "mem 8: ".memory_get_usage()."<br>";
			foreach($array as $student_id=>$course_sections)
			{
//				echo "mem 7: ".memory_get_usage()."<br>";
		                $message = "";
				
		                $student['FATHER_EMAIL'] = $contacts_array[$student_id]['father'][1]['EMAIL'];
		                $student['MOTHER_EMAIL'] = $contacts_array[$student_id]['mother'][1]['EMAIL'];

				$comments_arr = array();
				if(substr($_REQUEST['sorting'],0,1)=='p' && $_REQUEST['options']['sort_teacher']!='Y')
				{
					if($_REQUEST['mailing_labels']=='Y')
					{
						$first_course_period = $course_sections[key($course_sections)];
						$first_course_period = $first_course_period[key($first_course_period)];
						$first_course_period = $first_course_period[key($first_course_period)];
						$new_sort_teacher = $first_course_period[1]['SORT_TEACHER'];
						if($new_sort_teacher != $last_sort_teacher)
//							$message .= '<h3>'._('End of').' '.$last_sort_teacher.'</h3><BR><BR><h1>'._('Beginning ').$new_sort_teacher.'</h1><!-- NEW PAGE -->';
							$message .= '<h3>'._('End of').' '.$last_sort_teacher.'</h3><BR><BR><h1>'._('Beginning ').$new_sort_teacher.'</h1><!-- NEW PAGE -->';
	            			        if($_REQUEST['options']['ilp_page_break']=='Y') // print a second new page since the school is probably printing these report cards front / back
		                               $message .= '<BR><!-- NEW PAGE -->';
//              		                  $message .= '<BR>';
					} //if($_REQUEST['mailing_labels']=='Y')
					else
					{
						$first_course_period = $course_sections[key($course_sections)];
						$first_course_period = $first_course_period[key($first_course_period)];
						$new_sort_teacher = $first_course_period[1]['SORT_TEACHER'];
						if($last_sort_teacher && $new_sort_teacher != $last_sort_teacher)
						{
//							$message .= '<h3>'._('End of').' '.$last_sort_teacher.'</h3><BR><BR><h1>'._('Beginning ').$new_sort_teacher.'</h1><!-- NEW PAGE -->';
							$message .= '<h3>'._('End of').' '.$last_sort_teacher.'</h3><BR><BR><h1>'._('Beginning ').$new_sort_teacher.'</h1><!-- NEW PAGE -->';
							if($_REQUEST['options']['ilp_page_break']=='Y') // print a second new page since the school is probably printing these report cards front / back
								$message .= '<BR><!-- NEW PAGE -->';
								$message .= '<BR>';
						}
						$last_sort_teacher = $new_sort_teacher;
					} //else if($_REQUEST['mailing_labels']=='Y')
				} //if(substr($_REQUEST['sorting'],0,1)=='p' && $_REQUEST['options']['sort_teacher']!='Y')
			
	            		$first_course_period = $course_sections[key($course_sections)];
	                        $first_course_period = $first_course_period[key($first_course_period)];
		                $student[$email_field] = $first_course_period[1][$email_field];
	    		        $student['FULL_NAME'] =  $first_course_period[1]['FULL_NAME'];

				if($_REQUEST['mailing_labels']=='Y')
				{
					foreach($course_sections as $address_id=>$address)
					{
						unset($_SYSTEM['DisplayHeader']);
						unset($grades_array);
						$i = 0;
					
						foreach($address as $course_section_id=>$mps)
						{
							$i++;
							if($_REQUEST['options']['course_num']=='Y' && isset($mps[key($mps)][1]['COURSE_NUM']))
							    $grades_array[$i]['COURSE_NUM'] = $mps[key($mps)][1]['COURSE_NUM'];
							$grades_array[$i]['COURSE_TITLE'] = $mps[key($mps)][1]['COURSE_TITLE'];
							foreach($_REQUEST['mp_arr'] as $mp)
							{
								if($mps[$mp])
	    							{
									$grades_array[$i][$mp] = '';
									if($_REQUEST['options']['percent']=='Y' && $mps[$mp][1]['PERCENT_GRADE'])
										$grades_array[$i][$mp] = $mps[$mp][1]['PERCENT_GRADE'].'% ';
									if($_REQUEST['options']['grade']=='Y')
										$grades_array[$i][$mp] .= "&nbsp;&nbsp;".$mps[$mp][1]['GRADE_TITLE'];
	    								if($_REQUEST['options']['grade_descr']=='Y')
		    								if($grade_descr[$mps[$mp][1]['GRADE_SCHOOL_YEAR']][$mps[$mp][1]['GRADE_TYPE_ID']][$mps[$mp][1]['GRADE_TITLE']][1]['DESCRIPTION'])
											$grades_array[$i][$mp] .= " &nbsp;&nbsp;(".$grade_descr[$mps[$mp][1]['GRADE_SCHOOL_YEAR']][$mps[$mp][1]['GRADE_TYPE_ID']][$mps[$mp][1]['GRADE_TITLE']][1]['DESCRIPTION'].")";
									if($_REQUEST['options']['low_high']=='Y')
									if($lh_rating[$mps[$mp][1]['STUDENT_ID']][$mps[$mp][1]['COURSE_ID']][$mp][1]['LOW_SCORE'])
										$grades_array[$i][$mp.'LH'] = "".
									$lh_rating[$mps[$mp][1]['STUDENT_ID']][$mps[$mp][1]['COURSE_ID']][$mp][1]['LOW_SCORE']."/".
									$lh_rating[$mps[$mp][1]['STUDENT_ID']][$mps[$mp][1]['COURSE_ID']][$mp][1]['HIGH_SCORE'];
									if($_REQUEST['options']['course_rank']=='Y')
										$grades_array[$i][$mp.'CR'] = $lh_rating[$mps[$mp][1]['STUDENT_ID']][$mps[$mp][1]['COURSE_ID']][$mp][1]['COURSE_RANK'];
									if($_REQUEST['options']['course_avg']=='Y')
										$grades_array[$i][$mp.'CA'] = round($mps[$mp][1]['COURSE_AVG'],2);


									// If the final exam is excused
									if($mps[$mp][1]['PERCENT_GRADE']=='-1')
										$grades_array[$i][$mp] = _('Delayed');

									$last_mp = $mp;
								}
							}
							$grades_array[$i]['TEACHER'] = $mps[$last_mp][1]['TEACHER'];
							$grades_array[$i]['COMMENT'] = '<span class=GridOutput_fieldint>'.$mps[$last_mp][1]['COMMENT_TITLE'].'</span>';
							if($_REQUEST['options']['comments']=='Y' && is_numeric(preg_replace('/[^0-9]+/','',$grades_array[$i]['COMMENT'])))
							{
								$comments = explode(',',preg_replace('/[^0-9,]+/','',preg_replace('/,? +/',',',$grades_array[$i]['COMMENT'])));
								if(count($comments))
								{
									foreach($comments as $comment)
										$comments_arr[$comment] = true;
								}
							}
							$grades_array[$i]['ABSENCES'] = $mps[$last_mp][1]['YTD_ABSENCES'].' / '.$mps[$last_mp][1]['MP_ABSENCES'];
							$grades_array[$i]['CREDITS'] = $mps[$last_mp][1]['CREDITS'];
							$grades_array[$i]['CONDUCT'] = $mps[$last_mp][1]['CONDUCT'];
						}
					
						$columns = array('COURSE_TITLE'=>_('Course Name'));
						if($_REQUEST['options']['course_num']=='Y')
    							$columns += array('COURSE_NUM'=>_('Course Number'));
						if($_REQUEST['options']['teacher']=='Y')
    							$columns += array('TEACHER'=>_('Teacher Name'));
						if($_REQUEST['options']['period_absences']=='Y')
							$columns += array('ABSENCES'=>_('Absences'));
						// .'<BR>'._('YTD').' / '._('MP')
						if($addition['columns_after'])
							$columns += $addition['columns_after'];
						$st_count=0;
						$total_st_count = count($_REQUEST['mp_arr']);
						
						foreach($_REQUEST['mp_arr'] as $mp)
						{
							$columns[$mp] = get_school_term($mp);						
							$st_count++;
							if($_REQUEST['options']['print_last']=='Y' && $st_count == $total_st_count)
							{
								if($_REQUEST['options']['low_high']=='Y')
	//								$columns[$mp.'LH'] = get_school_term($mp).' '._('L/H Scores %');
									$columns[$mp.'LH'] = _('L/H Scores %');
								if($_REQUEST['options']['course_rank']=='Y')
//										$columns[$mp.'CR'] = get_school_term($mp).' '._('Course Rank');
									$columns[$mp.'CR'] = _('Course Rank');
								if($_REQUEST['options']['course_avg']=='Y')
									$columns[$mp.'CA'] = _('Course Avg');

							}
							elseif($_REQUEST['options']['print_last']!='Y')
							{
								if($_REQUEST['options']['low_high']=='Y')
//										$columns[$mp.'LH'] = get_school_term($mp).' '._('L/H Scores %');
									$columns[$mp.'LH'] = _('L/H Scores %');
								if($_REQUEST['options']['course_rank']=='Y')
//									$columns[$mp.'CR'] = get_school_term($mp).' '._('Course Rank');
									$columns[$mp.'CR'] = _('Course Rank');
								if($_REQUEST['options']['course_avg']=='Y')
									$columns[$mp.'CA'] = _('Course Avg');

						
							}
						
/*						if($_REQUEST['options']['low_high']=='Y')
							$columns[$mp]['LOW_HIGH'] = _('L/H Scores %');
						if($_REQUEST['options']['course_rank']=='Y')
							$columns[$mp]['COURSE_RANK'] = _('Course Rank');
*/
						}
						if($_REQUEST['options']['conduct']=='Y')
							$columns['CONDUCT'] = _('Conduct');
						if($_REQUEST['options']['credits']=='Y')
							$columns['CREDITS'] = _('Credits');
						if($_REQUEST['options']['comments']=='Y')
							$columns['COMMENT'] = _('Comments');
//						if($_REQUEST['options']['grade_descr']=='Y')
	    //						$columns['GRADE_DESCR'] = _('Grade Description');
						if(!$_REQUEST['_template_id'])
							$message .= '<BR><BR><BR>';
						$_REQUEST['DrawAlign'] = 'LEFT';
						$message .= DisplayHeaderBuffered(_('Student Report Card'),null,null,null,null,null,null,true);
	//					$message .= DisplayHeaderBuffered(_('Student Report Card'));
						//$message .= "mem $student_id: ".memory_get_usage()."<br>";
						$message .= DisplayHeaderBuffered($address[$course_section_id][key($address[$course_section_id])][1]['FULL_NAME'].' ('.$address[$course_section_id][key($address[$course_section_id])][1]['STUDENT_ID'].')');
						$message .= DisplayHeaderBuffered(_('Class Level').': '.$address[$course_section_id][key($address[$course_section_id])][1]['CLASSLEVEL_ID'],get_school(get_school_id()));
						if(substr($_REQUEST['sorting'],0,1)=='p' && $_REQUEST['options']['sort_teacher'])
						{
							$_SYSTEM['DisplayHeader'] = 'bgcolor=#FFFFFF'; // so that the following line won't be printed in bold
							$message .= DisplayHeaderBuffered(get_period(substr($_REQUEST['sorting'],1)).' '._('Teacher Name').': <b>'.$address[$course_section_id][key($address[$course_section_id])][1]['SORT_TEACHER'].'</b>',null,null,'white',null,true);
						}
						$count_lines = 3;
									
						$message .= DisplayHeaderBuffered(ProperDate(get_db_date()));					
						unset($_REQUEST['DrawAlign']);
						if(!$_REQUEST['_template_id'])
						{
							$count_lines++;
							for($i=$count_lines;$i<=6;$i++)
								$message .= '<BR>';
							
							$message .= '<TABLE><TR><TD width=50>&nbsp;</TD><TD width=300>'.$address[$course_section_id][key($address[$course_section_id])][1]['MAILING_LABEL'].'</TD></TR></TABLE>';
						}
						$m_school_period_id = key($array[$student_id][$student_id][key($array[$student_id][$student_id])]);
						$course_class = $array[$student_id][$student_id][key($array[$student_id][$student_id])][$m_school_period_id][1]['CLASSLEVEL_ID'];

						//_makeCourseRank($address[$course_section_id][key($address[$course_section_id])][1]['STUDENT_ID'],$m_school_period_id,$course_class);
					
						$message .= GridoutputBuffered($grades_array,$columns,'','',array(),array(),array('print'=>false));
						if($_REQUEST['options']['comments']=='Y' && count($comments_arr))
						{
							foreach($comments_arr as $comment=>$true)
							{
								if(!$comments_array[$comment][1]['TITLE'] && !$comments_array['0'.$comment][1]['TITLE'])
									unset($comments_arr[$comment]);
							}
						}
						if($_REQUEST['options']['comments']=='Y' && $_REQUEST['options']['comments_legend']=='Y' && count($comments_arr))
						{
							$message .= '<TABLE width=100%><TR><TD colspan=2><b>'._('Explanation of Comment Codes').'</b></TD>';
							$i=3;
							foreach($comments_arr as $comment=>$true)
							{
								if($i%3==0)
									$message .= '</TR><TR>';
								if(!$comments_array[$comment][1]['TITLE'] && $comments_array['0'.$comment][1]['TITLE'])
									$comment = '0'.$comment;
								$message .= '<TD>'.$comments_array[$comment][1]['TITLE'].'</TD>';
								$i++;
							}
							$message .= '</TR></TABLE>';
						}
						if($_REQUEST['options']['ilp'])
						{
							if($_REQUEST['options']['ilp_page_break']=='Y')
								$message .= '<!-- NEW PAGE -->';
//							$message .= '';
							$message .= '<CENTER><BR><TABLE width=90%><TR><TD><b>'._('Teacher Comments').'</b><BR><BR>';
							$message .= str_replace("\n","<BR>",str_replace("\r\n","<BR>",charset_decode_utf8($ilp_array[$student_id][1]['COMMENT'])));
							$message .= '</TD></TR></TABLE></CENTER>';
							
						}
						$message .= DrawTemplateHeaderBuffered($student_id,'footer');
						$message .= '<!-- NEW PAGE -->';
//						$message .= '';
						unset($lh_rating[$student_id]);
					}
				} //if($_REQUEST['mailing_labels']=='Y')
				else
				{
					unset($_SYSTEM['DisplayHeader']);
					unset($grades_array);
					$i = 0;
					foreach($course_sections as $course_section_id=>$mps)
					{
						$i++;
						if($_REQUEST['options']['course_num']=='Y' && isset($mps[key($mps)][1]['COURSE_NUM']))
						    $grades_array[$i]['COURSE_NUM'] = $mps[key($mps)][1]['COURSE_NUM'];
						$grades_array[$i]['COURSE_TITLE'] = $mps[key($mps)][1]['COURSE_TITLE'];
						foreach($_REQUEST['mp_arr'] as $mp)
						{
						    if($mps[$mp])
						    {
							$grades_array[$i][$mp] = '';
							if($_REQUEST['options']['percent']=='Y' && isset($mps[$mp][1]['PERCENT_GRADE']))
								$grades_array[$i][$mp] = $mps[$mp][1]['PERCENT_GRADE'].'% ';
							if($_REQUEST['options']['grade']=='Y')
								$grades_array[$i][$mp] .= "&nbsp;&nbsp;".$mps[$mp][1]['GRADE_TITLE'];
							if($_REQUEST['options']['grade_descr']=='Y')
							    if($grade_descr[$mps[$mp][1]['GRADE_SCHOOL_YEAR']][$mps[$mp][1]['GRADE_TYPE_ID']][$mps[$mp][1]['GRADE_TITLE']][1]['DESCRIPTION'])
								$grades_array[$i][$mp] .= " &nbsp;&nbsp;(".$grade_descr[$mps[$mp][1]['GRADE_SCHOOL_YEAR']][$mps[$mp][1]['GRADE_TYPE_ID']][$mps[$mp][1]['GRADE_TITLE']][1]['DESCRIPTION'].")";
							if($mps[$mp][1]['PERCENT_GRADE']=='-1')
								$grades_array[$i][$mp] = _('Delayed');
							if($_REQUEST['options']['low_high']=='Y')
							    if($lh_rating[$mps[$mp][1]['STUDENT_ID']][$mps[$mp][1]['COURSE_ID']][$mp][1]['LOW_SCORE'])
								$grades_array[$i][$mp.'LH'] = "".
									    $lh_rating[$mps[$mp][1]['STUDENT_ID']][$mps[$mp][1]['COURSE_ID']][$mp][1]['LOW_SCORE']."/".
									    $lh_rating[$mps[$mp][1]['STUDENT_ID']][$mps[$mp][1]['COURSE_ID']][$mp][1]['HIGH_SCORE'];
							if($_REQUEST['options']['course_rank']=='Y')
								$grades_array[$i][$mp.'CR'] = $lh_rating[$mps[$mp][1]['STUDENT_ID']][$mps[$mp][1]['COURSE_ID']][$mp][1]['COURSE_RANK'];
							if($_REQUEST['options']['course_avg']=='Y')
								$grades_array[$i][$mp.'CA'] = round($mps[$mp][1]['COURSE_AVG'],2);

								
							$last_mp = $mp;
						} //if($mps[$mp])
					} //foreach($_REQUEST['mp_arr'] as $mp)
					$grades_array[$i]['TEACHER'] = $mps[$last_mp][1]['TEACHER'];
					$grades_array[$i]['ABSENCES'] = $mps[$last_mp][1]['YTD_ABSENCES'];
					$grades_array[$i]['CREDITS'] = $mps[$last_mp][1]['CREDITS'];
					$grades_array[$i]['CONDUCT'] = $mps[$last_mp][1]['CONDUCT'];
					// .' / '.$mps[$last_mp][1]['MP_ABSENCES']
					$grades_array[$i]['COMMENT'] = '<span class=GridOutput_fieldint>'.$mps[$last_mp][1]['COMMENT_TITLE'].'</span>';
					if($_REQUEST['options']['comments']=='Y' && is_numeric(preg_replace('/[^0-9]+/','',$grades_array[$i]['COMMENT'])))
					{
						$comments = explode(',',preg_replace('/[^0-9,]+/','',preg_replace('/,? +/',',',$grades_array[$i]['COMMENT'])));
						if(count($comments))
						{
							foreach($comments as $comment)
								$comments_arr[$comment] = true;
						} //if(count($comments))
					} //if($_REQUEST['options']['comments']=='Y' && is_numeric(ereg_replace('[^0-9]+','',$grades_array[$i]['COMMENT'])))
			} //foreach($course_sections as $course_section_id=>$mps)
				
			$columns = array('COURSE_TITLE'=>_('Course Name'));
			if($_REQUEST['options']['course_num']=='Y')
    				$columns += array('COURSE_NUM'=>_('Course Number'));
			if($_REQUEST['options']['teacher']=='Y')
				$columns += array('TEACHER'=>_('Teacher Name'));
			if($_REQUEST['options']['period_absences']=='Y')
				$columns += array('ABSENCES'=>_('Amount of Absences'));
			//.'<BR>'._('YTD').' / '._('MP'));
			if($addition['columns_after'])
				$columns += $addition['columns_after'];
			
			if(($orientation=='portrait' && count($_REQUEST['mp_arr'])>4) || ($orientation=='landscape' && count($_REQUEST['mp_arr'])>6))
				$mp_TITLE = 'SHORT_NAME';
			else
				$mp_TITLE = 'TITLE';
			$st_count=0;
			$total_st_count = count($_REQUEST['mp_arr']);
			
			foreach($_REQUEST['mp_arr'] as $mp)
			{
				$columns[$mp] = get_school_term($mp,$mp_TITLE);
				$st_count++;
				if($_REQUEST['options']['print_last']=='Y' && $st_count == $total_st_count)
				{
					if($_REQUEST['options']['low_high']=='Y')
				//			$columns[$mp.'LH'] = get_school_term($mp,$mp_TITLE).' '._('L/H Scores %');
						$columns[$mp.'LH'] = _('L/H Scores %');
					if($_REQUEST['options']['course_rank']=='Y')
//								$columns[$mp.'CR'] = get_school_term($mp,$mp_TITLE).' '._('Course Rank');
						$columns[$mp.'CR'] = _('Course Rank');
					if($_REQUEST['options']['course_avg']=='Y')
						$columns[$mp.'CA'] = _('Course Avg');

				}
				elseif($_REQUEST['options']['print_last']!='Y')
				{
					if($_REQUEST['options']['low_high']=='Y')
//						$columns[$mp.'LH'] = get_school_term($mp,$mp_TITLE).' '._('L/H Scores %');
						$columns[$mp.'LH'] = _('L/H Scores %');
					if($_REQUEST['options']['course_rank']=='Y')
//						$columns[$mp.'CR'] = get_school_term($mp,$mp_TITLE).' '._('Course Rank');
						$columns[$mp.'CR'] = _('Course Rank');
					if($_REQUEST['options']['course_avg']=='Y')
						$columns[$mp.'CA'] = _('Course Avg');

				
				}
/*					
					if($_REQUEST['options']['low_high']=='Y')
						$columns[$mp.'LH'] = get_school_term($mp,$mp_TITLE).' '._('L/H Scores %');
					if($_REQUEST['options']['course_rank']=='Y')
						$columns[$mp.'CR'] = get_school_term($mp,$mp_TITLE).' '._('Course Rank');
*/
			}
			if($_REQUEST['options']['conduct']=='Y')
				$columns['CONDUCT'] = _('Conduct');
			if($_REQUEST['options']['credits']=='Y')
				$columns['CREDITS'] = _('Credits');
			if($_REQUEST['options']['comments']=='Y')
				$columns['COMMENT'] = _('Comments');
//			if($_REQUEST['options']['low_high']=='Y')
//				$columns['LOW_HIGH'] = _('L/H Scores %');
//			if($_REQUEST['options']['grade_descr']=='Y')
//				$columns['GRADE_DESCR'] = _('Grade Description');
//			if($_REQUEST['options']['course_rank']=='Y')
//				$columns['COURSE_RANK'] = _('Course Rank');
			$_REQUEST['DrawAlign'] = 'ALIGN_LEFT';
			$old_student_id = $student_id;
			$message .= DisplayHeaderBuffered(_('Student Report Card'),null,null,null,null,null,null,true);
			$student_id = $old_student_id;
//			$message .= "mem $student_id: ".memory_get_usage()."<br>";
			$message .= DisplayHeaderBuffered($course_sections[$course_section_id][key($course_sections[$course_section_id])][1]['FULL_NAME'].' ('.$course_sections[$course_section_id][key($course_sections[$course_section_id])][1]['STUDENT_ID'].')');
			$message .= DisplayHeaderBuffered(_('Class Level').': '.$course_sections[$course_section_id][key($course_sections[$course_section_id])][1]['CLASSLEVEL_ID'],get_school(get_school_id()));
			if(Preferences('DISPLAY_GROUP') == 'Y')
				$message .= DisplayHeaderBuffered(_('Class Group').': '.$course_sections[$course_section_id][key($course_sections[$course_section_id])][1]['GROUP_ID']);
			if(substr($_REQUEST['sorting'],0,1)=='p' && $_REQUEST['options']['sort_teacher']=='Y')
				$message .= DisplayHeaderBuffered(get_period(substr($_REQUEST['sorting'],1)).' '._('Teacher Name').': '.$course_sections[$course_section_id][key($course_sections[$course_section_id])][1]['SORT_TEACHER'],null,null,null,null,true);
			
			$message .= '<BR>';
			unset($_REQUEST['DrawAlign']);
			$course_class = $array[$student_id][key($array[$student_id])][$mp][1]['CLASSLEVEL_ID'];
			$course_class = $course_sections[$course_section_id][key($course_sections[$course_section_id])][1]['CLASSLEVEL_ID'];
					
			$reload = false;
			if ($cur_classname <> $course_class)
			{
				$cur_classname = $course_class;
				$reload = true;
			}
			//_makeCourseRank($student_id,$mp,$course_class,$reload);
			
			$message .= GridoutputBuffered($grades_array,$columns,'','',array(),array(),array('print'=>false,'center'=>false));
			if($_REQUEST['options']['comments']=='Y' && count($comments_arr))
			{
				foreach($comments_arr as $comment=>$true)
				{
					if(!$comments_array[$comment][1]['TITLE'] && !$comments_array['0'.$comment][1]['TITLE'])
						unset($comments_arr[$comment]);
				}
			}
			if($_REQUEST['options']['comments']=='Y' && count($comments_arr))
			{
				$message .= '<BR><TABLE width=100%><TR><TD colspan=2><b>'._('Explanation of Comment Codes').'</b></TD>';
				$i=3;
				foreach($comments_arr as $comment=>$true)
				{
					if($i%3==0)
						$message .= '</TR><TR>';
					if(!$comments_array[$comment][1]['TITLE'] && $comments_array['0'.$comment][1]['TITLE'])
						$comment = '0'.$comment;
					$message .= '<TD>'.$comments_array[$comment][1]['TITLE'].'</TD>';
					$i++;
				}
				$message .= '</TR></TABLE>';
			}
			if($_REQUEST['options']['ilp'])
			{
				if($_REQUEST['options']['ilp_page_break']=='Y')
					$message .= '<!-- NEW PAGE -->';
//					$message .= '';
				$message .= '<CENTER><BR><TABLE width=90%><TR><TD><b>'._('Teacher Comments').'</b><BR><BR>';
				$message .= str_replace("\n","<BR>",str_replace("\r\n","<BR>",charset_decode_utf8($ilp_array[$student_id][1]['COMMENT'])));
				$message .= '</TD></TR></TABLE></CENTER>';
			}
			$message .= DrawTemplateHeaderBuffered($student_id,'footer');
			$message .= '<!-- NEW PAGE -->';
//			$message .= '';
			unset($lh_rating[$student_id]);
		} //else if($_REQUEST['mailing_labels']=='Y')

	            if($mode=='print_students' || $_REQUEST['preview']=='true')
	            {
	                    print $message;
	                    if($_REQUEST['preview']=='true')
		                    print "<br><hr><br>";
	            }
	            else
	            {
	        	    $options['cc'] = "".$_REQUEST['email_cc']."";
	                    $options['attachment'] = 'email_attach';
	                    if($_REQUEST['CCme'])
	                    {
		                    $myemail = get_user('EMAIL');
		                    $options['cc'] = strlen($options['cc']) > 0 ? $options['cc'].', '.$myemail : $myemail;
	                    }

        		    $to = new Swift_RecipientList();
	                    switch($mode)
	                    {
		                    case 'email_parents':
		                            if($student['FATHER_EMAIL'])
		                            {
	    		                            $to->addTo($student['FATHER_EMAIL'], $student['FATHER_NAME']);
			                            $has_email = true;
	            	            	    }
		                            if($student['MOTHER_EMAIL'])
	        		            {
	                    		    	    $to->addTo($student['MOTHER_EMAIL'], $student['MOTHER_NAME']);
			                            $has_email = true;
		                    	    }
	                            break;
        		            case 'email_students':
	        	                    if($student[$email_field])
		                            {
			                            $to->addTo($student[$email_field], $student['FULL_NAME']);
			                            $has_email = true;
		                            }
	                            break;
	                    } //switch

                	    $options['to'] = $to;
	                    $to_address = $student[$email_field];
	                    $to_name = $student['FULL_NAME'];
		            $subject = $_REQUEST['email_subject'];
	                    if($reply_to)
	                            $options['reply'] = $reply_to;

	                    if($has_email && SendEmail($to_address, $to_name, $from_address, $from_name, $subject, $message, $options))
	        	    {
	                    }
	                    else
	                    {
		                    switch($_REQUEST['to_address'])
            			    {
		                            case 'email_parents':
                		                $errors[] = _("Message was not sent to ").$to_name." "._('parents.');
		                            break;
		                            case 'email_students':
                			            $errors[] = _("Message was not sent to ").$to_name." (".($to_address?$to_address:_('No Email entered')).")";
		                            break;
		                    } //switch
            		    }
	            }
	    } //foreach($array as $student_id=>$course_sections)
	        //Вывод непосредственно на пдф
//    	        echo"fff";
//echo "mem5: ".memory_get_usage()."<br>";
                if($mode=='print_students' && $_REQUEST['preview']!='true')
                {
                	PDFStop($handle);
                }
                elseif($errors)
                {
	                echo "<br>";
    		        Basic('header');
	                DisplayBlock(_('Errors'),ErrorMessage($errors),'error');
	                Basic('footer');
                }
                elseif($_REQUEST['preview']!='true' && $_REQUEST['servicemod'])
                {
	                echo '<script language=javascript>document.location.href="modloader.php?servicemod='.$_REQUEST['servicemod'].'&report='.$_REQUEST['report'].'&servicefunction='.$_REQUEST['servicefunction'].'&search_servicefunction='.$_REQUEST['search_servicefunction'].'&sent=true"</script>';
                }
	}//end of gradelist
//	                echo "-->".$_REQUEST['preview']." ".$mode;
	if($mode=='print_students' && $_REQUEST['servicefunction']=='gradelist' && $_REQUEST['preview']!='true')
        {
//              echo "pr-->".$_REQUEST['preview'];
		if($_REQUEST['orient'] == 'auto')
		{	
	                if($cols_count<9)
    			        $orientation = 'portrait';
		        else
	    		        $orientation = 'landscape';
	    	}
	    	else
	    		$orientation = $_REQUEST['orient'];
	    		
                $handle = PDFStart("--webpage --quiet -t pdf12 --no-links --".$orientation." --footer t --header . --left 0.5in --top 0.5in");
		print $grademsg;
            	PDFStop($handle);
        }
        elseif($mode=='print_students' && $_REQUEST['servicefunction']=='gradelist' && $_REQUEST['preview']=='true')
        {
    		print $grademsg;
        }
//	echo "gggg";
	}// if no data in $array
	else
		BackPrompt(_('Selected students do not have grades.'));
}

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

function _makeTeacher($teacher,$column)
{
	return substr($teacher,strrpos(str_replace(' - ',' ^ ',$teacher),'^')+2);
}

function _roundGPA($gpa,$column)
{
	return round($gpa,SystemPreferences('ROUND_GPA_POINTS'));
}

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

	$student_id_field="STUDENT_ID";

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

			if(!$stu_array || $reload)

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

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

			if($_REQUEST['options']['low_high'])
			{
				foreach($perc_array as $perc)
				{
					for($a=1;$a<count($perc)+1;$a++)
					{
						if($perc[$a]['PERCENT_GRADE']>$high_score)
							$high_score = $perc[$a]['PERCENT_GRADE'];
						elseif($perc[$a]['PERCENT_GRADE']<$low_score && $perc[$a]['PERCENT_GRADE'] != '0')
							$low_score = $perc[$a]['PERCENT_GRADE'];
					}
				}
			}
			foreach($perc_array as $perc)
			{
				$course_rank++;
				for($i=1;$i<count($perc)+1;$i++)
				{
					if($perc[$i]['STUDENT_ID'] == $student_id)
					{
						if($_REQUEST['options']['course_rank'])
							$grades_array[$y]['QTR_COURSE_RANK'] = $course_rank;
						if($_REQUEST['options']['low_high'])
							$grades_array[$y]['LOW_HIGH'] = $low_score." / ".$high_score;
					}
				}
			}
		}
	}
}
unset($lh_rating);
unset($array);
//echo "mem20: ".memory_get_usage()."<br>";
//$_SYSTEM['DisableAddonLoader'] = false;
//die();
?>