<?php
//include_once($staticpath.'/classes/Button.php');
require_once($staticpath.'classes/Students.class.php');
require_once($staticpath.'classes/Calendar_calc.php');
$Student_class = new Students();
$Calendar_class = new Calendar_func();
function DisplayHeaderBuffered($left='',$right='',$center='',$style='',$b_border=true,$required=false,$widths=false,$underline=false,$not_extend=false)
{
	global $_SYSTEM,$last_mp,$StudentPicturesPath;
	$result = "";
	$s_border = "";
	if($_REQUEST['CREATEPDF'] && $_REQUEST['_template_id'] && !$style)
	{
		if(!$_SYSTEM['DisplayHeader'])
		{
			return DrawTemplateHeaderBuffered(); // Print the template's headers instead of this one
		}
		if(!$required)
			return; // if printing with a template, and this header isn't one of the templates, don't display it
	}
	if($_SYSTEM['uri'])
	{
		$uri = $_SYSTEM['uri'];
	}

//die('ggggg');
	if(!isset($_SYSTEM['DisplayHeader']) && !$_REQUEST['CREATEPDF'] && !$style)
	{
		$_SYSTEM['DisplayHeader'] = "class='StandartBGStyle'";
		if(!((get_user('PROFILE')!='admin' && get_user('PROFILE')!='teacher') || Preferences('MENU')=='Top'))
			$s_border = 'style="border-width:2;border-style:none none none none;"';
   // die('uuuuu');
		if($_SYSTEM['HeaderIcon'])
			$left = '<BR><IMG SRC='.$uri.'images/pixel_trans.gif height=1 width=4><font size=+1>'.$left.'</font>';
		if(!$right && $_REQUEST['useontop']=='false' && ($_REQUEST['student_id'] || $_REQUEST['GridOutputCount']))
		{
			Search('student_id');
			$view_fields_array = db_request(db_execute("SELECT cf.ID,cf.TYPE,cf.TITLE FROM SYSTEM_USER_SETTINGS puc,STUDENT_FIELDS cf WHERE puc.TITLE=CAST(cf.ID AS TEXT) AND puc.PROGRAM='StudentFieldsView' AND puc.USERNAME='".get_user('USERNAME')."' AND puc.VALUE='Y'"));
		
			if(!count($view_fields_array) && !isset($view_address_array) && !isset($view_other_array['CONTACT_INFO']))
			{
				$titles = array('STUDENT_ID'=>_('ID number'),'CFIELD_50000'=>_('Gender'),'CFIELD_50001'=>_('Ethnicity'));
				$select = ',STUDENT_ID,CFIELD_50000,CFIELD_50001';
			}
			else
			{
				$select = ',STUDENT_ID';
				$titles['STUDENT_ID'] = _('ID number');
				foreach($view_fields_array as $field)
				{
					$titles['CFIELD_'.$field['ID']] = $field['TITLE'];
					if($field['TYPE']=='date')
						$functions['CFIELD_'.$field['ID']] = 'ProperDate';
					if($field['TYPE']=='numeric')
						$functions['CFIELD_'.$field['ID']] = 'removeDot00';
					$select .= ',CFIELD_'.$field['ID'];
				}
			}
			$array = db_request(db_execute("SELECT FIRST_NAME,LAST_NAME,MIDDLE_NAME,NAME_SUFFIX".$select." FROM STUDENTS WHERE STUDENT_ID='".get_student_id()."'"));
			$full_name = $array[1]['FIRST_NAME'].'&nbsp;'.($array[1]['MIDDLE_NAME']?$array[1]['MIDDLE_NAME'].' ':'').$array[1]['LAST_NAME'].'&nbsp;'.$array[1]['NAME_SUFFIX'];
			//	$tab = DrawTab($full_name,','FFFFFF','333333','_circle',array('tabcolor'=>Preferences('HIGHLIGHT'),'textcolor'=>'FFFFFF'),'style="display:inline;"');
			//	$tab = '<A HREF="modloader.php?servicemod=mod_students/Students.php">'.$full_name.'</A>';
//			$tab = '<SPAN onMouseOver=\'stm(["'.str_replace("'",'&rsquo;',$full_name).'","';
//			if($StudentPicturesColumn && $StudentPicturesColumn!='STUDENT_ID')
//			{
//				$photo_name = db_request(db_execute("SELECT ".$StudentPicturesColumn." AS NAME FROM STUDENTS WHERE STUDENT_ID='".get_student_id()."'"));
//				$photo_name = $photo_name[1]['NAME'];
//			}
//			else
//				$photo_name = get_student_id();
//			if($StudentPicturesPath && $_REQUEST['student_id']!='new' && ($file = @fopen($StudentPicturesPath.($school_year = get_school_year()).'/'.$photo_name.($jpg = '.JPG'),'r') || $file = @fopen($StudentPicturesPath.($school_year = get_school_year()).'/'.$photo_name.($jpg = '.jpg'),'r') || $file = @fopen($StudentPicturesPath.($school_year = (get_school_year()-1)).'/'.$photo_name.($jpg = '.JPG'),'r') || $file = @fopen($StudentPicturesPath.($school_year = (get_school_year()-1)).'/'.$photo_name.($jpg = '.jpg'),'r')))
//				$tab .= '<IMG SRC='.str_replace('\\','\\\\',$StudentPicturesPath).$school_year.'/'.$photo_name.$jpg.'><BR>';
//			foreach($titles as $col=>$title)
//				$tab .= str_replace("'","`",$title.': '.$array[1][$col]).'<BR>';
//			$tab .= '"],["white","#333366","","","",,"black","#e8e8ff","","","",,,,2,"#333366",2,,,,,"",,,,]);\' onMouseOut=\'htm()\'> <B><A HREF="modloader.php?servicemod=mod_students/Students.php" style="text-decoration:none;">'.$full_name.'</A></B></SPAN>';
			$right = $tab;
		}
	}	
	elseif((!isset($_SYSTEM['DisplayHeader']) || $style=='blue') && !($style && $style!='blue'))
		$_SYSTEM['DisplayHeader'] = 'bgcolor=#FFFFFF';
	elseif($style=='white')
		$_SYSTEM['DisplayHeader'] = 'bgcolor=#FFFFFF';		
	elseif($style=='gray')
		$_SYSTEM['DisplayHeader'] = 'bgcolor=#F0F0F1';

	if($style && $b_border)
		$_SYSTEM['DisplayHeader'] = Preferences('HIGHLIGHT_MENU');// ' class="WhiteDisplayHeader" ';
	if($_SYSTEM['DisplayHeader'] === "class='StandartBGStyle'")
	{
		$attribute = 'B';
//		$font_color = 'FFFFFF';
//		if(Preferences('THEME')=='Ocean' || Preferences('THEME')=='Wood-Grain' || Preferences('THEME')=='Midnight')
//			$font_color = 'FFFFFF';
//		$font_color .= ' class=BottomButton';
	}
	elseif($_SYSTEM['DisplayHeader']==='bgcolor=#333366')
	{
		$attribute = 'B';
		$font_color = 'FFFFFF';
	}
	else
	{
		$attribute = 'FONT size=-1';
		$font_color = '333333';
	}
        
	if($_REQUEST['servicefunction'] && $_REQUEST['servicemod'] !== 'applicants_online')
		$result .='<TABLE toborder="right" border=0 cellpadding=0 cellspacing=0></TABLE>';
		if($not_extend !== 'no')
		{
		    $class = (!$not_extend && substr($left,0,2)=='.:')?'right_both2':'right_both';
		}
		else
		{
		    $class = '';
		}
		    

        if($_REQUEST['servicemod'] !== 'applicants_online')
	$result .= '<TABLE class="'.$class.'" width=100%  toborder="right" border=0 cellpadding=0 cellspacing=0 '.$s_border.$_SYSTEM['DisplayHeader'].'><TR >';
	if($widths)
	{
		foreach($widths as $i=>$width)
			$widths[$i] = ' width='.$width.'%';
	}
	elseif($center && $center!='' && (($left && trim($left)!='') || ($right && trim(str_replace('&nbsp;','',$right))!='')))
		$widths['left'] = $widths['center'] = $widths['right'] = ' width=33% ';
	if((!$style || $style=='') && strpos(strtolower($left),'<div')!==false)
	{
		$space =' &nbsp;';
	}
	if($_REQUEST['NOWRAP'] == 'true')
		$nowrap = 'NOWRAP';
		
	if($left)
	{
		if($_REQUEST['CREATEPDF'])
		{
			if(strpos('.:',$left))
				$underline = true;
			$left = str_replace('.:','',$left);
			$left = str_replace(':.','',$left);
		}
		if(!$_REQUEST['DrawAlign'] && !$_REQUEST['CREATEPDF'])
			$_REQUEST['DrawAlign'] = 'CENTER';
		elseif($_REQUEST['DrawAlign'] == 'LEFT' || $_REQUEST['DrawAlign'] == 'ALIGN_LEFT')
			$_REQUEST['DrawAlign'] = 'LEFT';
		if($attribute)
		{
			$attribute_s = '<'.$attribute.'>';
			$attribute_e = '</'.substr($attribute,0,4).'>';
		}
		if(strpos($left,ProgramTitle()))			
//			$result .= '<TD '.$_SYSTEM['DisplayHeader'].$widths['left'].' align='.$_REQUEST['DrawAlign'].' style="border-width:1px;border-style:none none solid none;border-color:black;">'.$space.'<font color=#'.$font_color.'><'.$attribute.'>'.$left.'</'.substr($attribute,0,4).'></font></TD>';
$result .= '<TD '.$_SYSTEM['DisplayHeader'].$widths[is_array('left')].' align='.$_REQUEST['DrawAlign'].' style="border-width:1px;border-style:none none dotted none;border-color:gray;">'.$space.'<font color=#'.$font_color.'>'.$attribute_s.$left.$attribute_e.'</font></TD>';
		else			
		        $result .= '<TD '.$nowrap.' '.$_SYSTEM['DisplayHeader'].$widths[is_array('left')].' align='.$_REQUEST['DrawAlign'].' >'.$space.'<font color=#'.$font_color.'>'.$attribute_s.$left.$attribute_e.'</font></TD>';
	}
	else
	    if($_REQUEST['CREATEPDF'])
		$result .= '<TD>&nbsp;</TD>';
//		$result .= '<TD '.$_SYSTEM['DisplayHeader'].$widths['left'].' align='.$_REQUEST['DrawAlign'].' style="border-width:1px;border-style:none none solid none;border-color:black;">'.$space.'<font color=#'.$font_color.'><'.$attribute.'>'.'</'.substr($attribute,0,4).'></font></TD>';
	
	if($center)
	{
		if($attribute)
		{
			$attribute_s = '<'.$attribute.'>';
			$attribute_e = '</'.$attribute.'>';
		}
		$result .= '<TD '.$nowrap.' '.$_SYSTEM['DisplayHeader'].$widths['center'].' align=center><font color=#'.$font_color.'>'.$attribute_s.$center.$attribute_e.'</font></TD>';
	}
	//разобраться почему без этого не работало, а теперь работает...
	else
	    if($_REQUEST['CREATEPDF'])
	    {
		$result .= '<TD>&nbsp;</TD>';
//		$result .= '<TD '.$_SYSTEM['DisplayHeader'].$widths['left'].' align='.$_REQUEST['DrawAlign'].' style="border-width:1px;border-style:none none solid none;border-color:black;">'.$space.'<font color=#'.$font_color.'><'.$attribute.'>'.'</'.substr($attribute,0,4).'></font></TD>';
//		$space = ' &nbsp;';
//	$result .= '<TD '.$_SYSTEM['DisplayHeader'].$widths['left'].' align='.$_REQUEST['DrawAlign'].' style="border-width:1px;border-style:none none dotted none;border-color:gray;">'.$space.'</TD>';
	    }
	    else
	    {
		if($_SYSTEM['DHparam']['downline'] == true)
		{
			$space = ' &nbsp;';
			$result .= '<TD '.$_SYSTEM['DisplayHeader'].$widths['left'].' align='.$_REQUEST['DrawAlign'].' style="border-width:1px;border-style:none none solid none;border-color:black;">'.$space.'</TD>';
		}
	    }
		
//$right=array();
	
	if($right)
	{
		if($attribute)
			//echo($attribute);
		{
			$attribute_s = '<'.$attribute.'>';
			$attribute_e = '</'.$attribute.'>';
			}	
			
		if(strpos($right,'Last date of login'))
					$result .= '<TD  align='.ALIGN_RIGHT.' '.$_SYSTEM['DisplayHeader'].$widths[is_array('right')].' valign=top ><font color=#'.$font_color.'>'.$attribute_s.$right.''.$attribute_e.'</font></TD>';
		elseif($_SYSTEM['DHparam']['downline'] == true)
			$result .= '<TD '.$_SYSTEM['DisplayHeader'].$widths['right'].' align=RIGHT style="border-width:1px;border-style:none none solid none;border-color:black;">'.$right.'</TD>';
		else
			$result .= '<TD  align='.ALIGN_RIGHT.' '.$_SYSTEM['DisplayHeader'].$widths[is_array('right')].' valign=top ><font color=#'.$font_color.'>'.$attribute_s.''.$right.'&nbsp;'.$attribute_e.'</font></TD>';
//		$result .= '<TD align=right '.$_SYSTEM['DisplayHeader'].$widths['right'].' valign=top><font color=#'.$font_color.'><'.$attribute.'>'.$right.'</'.substr($attribute,0,4).'></font></TD>';
	}
	else
	    if($_REQUEST['CREATEPDF'])
		$result .= '<TD>&nbsp;</TD>';
	    else
		if($_SYSTEM['DHparam']['downline'] == true)
			$result .= '<TD '.$_SYSTEM['DisplayHeader'].$widths['right'].' align='.$_REQUEST['DrawAlign'].' style="border-width:1px;border-style:none none solid none;border-color:black;">'.$space.'<font color=#'.$font_color.'><'.$attribute.'>'.'</'.substr($attribute,0,4).'></font></TD>';	

        if($_REQUEST['servicemod'] !== 'applicants_online')
	$result .= '</TR>';
	if($_REQUEST['CREATEPDF'] && $underline)
	{
		$result .= '<TR><TD colspan=3 BGCOLOR=black HEIGHT=2px></TD></TR>';
//		$result .= '<TR><TD VALIGN=TOP BGCOLOR=white>'; //incorrect
//		$result .= '<HR>';
//		$result .= '</TD></TR>';
	}
        if($_REQUEST['servicemod'] !== 'applicants_online')
	$result .= '</TABLE>';

	if(($_SYSTEM['DisplayHeader'] == "class='StandartBGStyle'" || $_SYSTEM['DisplayHeader'] = Preferences('HIGHLIGHT_BACKGROUND')) && !$_REQUEST['CREATEPDF'])
	{
		$_SYSTEM['DisplayHeader'] = Preferences('HIGHLIGHT_BACKGROUND');		
		//DrawTemplateHeaders();
	}
	elseif($_SYSTEM['DisplayHeader'] == 'bgcolor=#333366' && !($style && $_REQUEST['CREATEPDF']))
	{
		$_SYSTEM['DisplayHeader'] = 'class="GrayDisplayHeader"';
		//DrawTemplateHeaders();	
	}
	else
		$_SYSTEM['DisplayHeader'] = 'class="GrayDisplayHeader"';
        return $result;
        
}

function DisplayHeader($left='',$right='',$center='',$style='',$b_border=true,$required=false,$widths=false,$underline=false,$not_extend=false)
{
	echo DisplayHeaderBuffered($left, $right, $center, $style, $b_border, $required, $widths,$underline,$not_extend);
}

function DrawTemplateHeaderBuffered($studentid='',$type='header')
{	
    global $functions,$student_id,$_SYSTEM,$last_mp,$address_id,$DBType,$school_fields_array,$contacts_array,$lf_array,$logging_field_array,$Student_class,$fields_array,$Calendar_class,$_Config,$staticpath,$_REQUEST,$Document,$dates;

        $result = "";
	if(!$studentid && $student_id)
		$studentid = $student_id;
	if(!$studentid && $_SESSION['student_id'])
		$studentid = $_SESSION['student_id'];
	if($_REQUEST['_template_id'] && !$_SYSTEM['DrawTemplateHeaders_header_array'])
	{
		$old_REQUEST = $_REQUEST;
                if(($_REQUEST['servicemod'] == 'applicants_online')){
                    $template_array = db_request(db_execute("SELECT HEADER,FOOTER FROM LH_TEMPLATES WHERE ID='".$_REQUEST['_template_id']."' "));
                }
		elseif($_REQUEST['servicemod'] != 'mod_apply/AppPrintSpecDocs.php' && $_REQUEST['servicemod'] != 'mod_students/StuPrintSpecDocs.php')
                {
			$template_array = db_request(db_execute("SELECT HEADER,FOOTER FROM LH_TEMPLATES WHERE ID='".$_REQUEST['_template_id']."' AND (SCHOOL_ID='".get_school_id()."' OR SCHOOL_ID='0')"));
                }
		else
		{
			$template_array = db_request(db_execute("SELECT HEADER,FOOTER FROM DOCS_TEMPLATES WHERE ID='".$_REQUEST['_template_id']."'"));
			if(substr($_REQUEST['servicemod'],0,9) == 'mod_apply')
				$addition['APPLY_MODE'] = true;
		}
		// copied from letters
		// HEADER ....
//		$addition['SELECT'] = 'ssm.STUDENT_ID';
		$letter_text = stripslashes($template_array[1]['HEADER']);
//		echo htmlspecialchars($letter_text);
		$letter_text = preg_replace('/<button [^_]+_field_column="([^"]+)"[^>]*>[^<]*<\/button>/','<_field[\1] />',str_replace("`","'",str_replace("``",'"',str_replace('&#160;',' ',$letter_text))));
//		$letter_text = preg_replace('/<button *_field_column="([^"]+)"[^>]*>[^<]*<\/button>/','<_field[\1] />',str_replace("`","'",str_replace("``",'"',str_replace('&#160;',' ',$letter_text))));
		$_SYSTEM['DrawTemplateHeaders_header_text'] = $letter_text;
		while(preg_match('<_field\[([^]]+)\] />',$letter_text,$regs))
		{
			$_REQUEST['fields'][$regs[1]] = true;
			$letter_text = str_replace($regs[0],'',$letter_text);
			$count++;
		}

		$addition['dont_print_array'] = true;
		$_REQUEST['search_servicefunction'] = 'list';
		$_REQUEST['Gridoutput_store'] = true;
		$addition['functions'] = array('NEXT_SCHOOL'=>'_makeNextSchool','CALENDAR_ID'=>'_makeCalendar','SCHOOL_ID'=>'get_school','PARENTS'=>'makeParents','START_DATE'=>'ProperDate','END_DATE'=>'ProperDate','ENROLLMENT_CODE'=>'_getRegistrationCode','DROP_CODE'=>'_getRegistrationCode','CONTACT_INFO'=>'makeContactInfo','MAILTO_LABEL'=>'MailToLabel');
		$addition['functions']['CLASSLEVEL_ID'] = 'get_classlevel';
		$addition['group'] = array('STUDENT_ID');
		$addition['FROM'] = '';
/*
		foreach($_REQUEST['fields'] as $column=>$true)
		{
			if(strpos($addition['SELECT'],$column)===false && substr($column,0,7)!='CFIELD_' && !in_array($column,array('FIRST_NAME','LAST_NAME','MIDDLE_NAME','ADDRESS','CITY','STATE','ZIPCODE',$student_id_field,'CLASSLEVEL_ID','SCHOOL_ID','START_DATE','DROP_CODE','END_DATE','DATE_ENTERED','MAILTO_LABEL')))
				$addition['SELECT'] .= ',NULL AS '.ereg_replace('[^A-Za-z_0-9]','',$column);
		}
*/

		/* we need this block for mod_students/StuLetterWorkspace.php to display the SCHOOL fields */
		if($school_fields_array)
		{
			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($DBType == 'mssql')
					$addition['SELECT'] .= ",'".get_school(get_school_id(),NULL, $schoolValue)."' AS [".$schoolKey."]";
				else
					$addition['SELECT'] .= ",'".get_school(get_school_id(),NULL, $schoolValue)."' AS ".$schoolKey;		
			}
		}
//		echo "44====>".memory_get_usage()."<BR>";
//	echo "22-->".date("H:m:s",time())."<br>";
		if($_REQUEST['fields'])
		{
			if($students_table=='USERS')
			{
				$_SYSTEM['user_search'] = true;
				$_REQUEST['users_search_servicefunction'] = 'list';
			}
			unset($_REQUEST['fields_order']);//fix 10.06.2010 �������� ������ ��������� � ���������.
//var_dump($_REQUEST);
			$_SYSTEM['DisplayHeaderCall'] = true;
			include($staticpath.'modules/mod_portal/ExternalLinker.php');
			$_SYSTEM['DisplayHeaderCall'] = false;
			$_SYSTEM['DrawTemplateHeaders_header_array'] = $array;
//		var_dump($_SYSTEM['DrawTemplateHeaders_header_array']);			
		}
//		echo "33-->".date("H:m:s",time())."<br>";
//	echo "77====>".memory_get_usage()."<BR>";
		// FOOTER ......
		$addition = array();
//		$addition['SELECT'] = 'ssm.STUDENT_ID';
		$_REQUEST['fields'] = array();
		unset($_REQUEST['fields_order']);
		$array = array();

		$letter_text = stripslashes($template_array[1]['FOOTER']);
//		$letter_text = ereg_replace('<button [^_]+_field_column="([^"]+)"[^>]+>[^<]+</button>','<_field[\1] />',str_replace("`","'",str_replace("``",'"',str_replace('&#160;',' ',$letter_text))));
		$letter_text = preg_replace('/<button [^_]+_field_column="([^"]+)"[^>]*>[^<]*<\/button>/','<_field[\1] />',str_replace("`","'",str_replace("``",'"',str_replace('&#160;',' ',$letter_text))));
		$_SYSTEM['DrawTemplateHeaders_footer_text'] = $letter_text;

		while(preg_match('<_field\[([^]]+)\] />',$letter_text,$regs))
		{
			$_REQUEST['fields'][$regs[1]] = true;
			$letter_text = str_replace($regs[0],'',$letter_text);
			$count++;
		}

		$addition['dont_print_array'] = true;
		$_REQUEST['search_servicefunction'] = 'list';
		$_REQUEST['Gridoutput_store'] = true;
		$addition['functions'] = array('NEXT_SCHOOL'=>'_makeNextSchool','CALENDAR_ID'=>'_makeCalendar','SCHOOL_ID'=>'get_school','PARENTS'=>'makeParents','START_DATE'=>'ProperDate','END_DATE'=>'ProperDate','ENROLLMENT_CODE'=>'_getRegistrationCode','DROP_CODE'=>'_getRegistrationCode','CONTACT_INFO'=>'makeContactInfo','MAILTO_LABEL'=>'MailToLabel');
		$addition['functions']['CLASSLEVEL_ID'] = 'get_classlevel';
		$addition['group'] = array('STUDENT_ID');
		// empty these variables which were set above
		$addition['FROM'] = '';
		$addition['SELECT'] = '';

/*
		foreach($_REQUEST['fields'] as $column=>$true)
		{
			if(strpos($addition['SELECT'],$column)===false && substr($column,0,7)!='CFIELD_' && !in_array($column,array('FIRST_NAME','LAST_NAME','MIDDLE_NAME','ADDRESS','CITY','STATE','ZIPCODE',$student_id_field,'CLASSLEVEL_ID','SCHOOL_ID','START_DATE','DROP_CODE','END_DATE','DATE_ENTERED','MAILTO_LABEL')))
				$addition['SELECT'] .= ',NULL AS '.ereg_replace('[^A-Za-z_0-9]','',$column);
		}
*/
//	echo "44-->".date("H:m:s",time())."<br>";
		if($_REQUEST['fields'])
		{
			if($students_table=='USERS')
			{
				$_SYSTEM['user_search'] = true;
				$_REQUEST['users_search_servicefunction'] = 'list';
			}
			$_SYSTEM['DisplayHeaderCall'] = true;
			include($staticpath.'modules/mod_portal/ExternalLinker.php');
			$_SYSTEM['DisplayHeaderCall'] = false;
			$_SYSTEM['DrawTemplateHeaders_footer_array'] = $array;
		}

		$_REQUEST = $old_REQUEST;
	}
//	echo "55-->".date("H:m:s",time())."<br>";
//	echo "55====>".memory_get_usage()."<BR>";
	$Student_class->setStudentId($student_id);
        $_SYSTEM['DisplayHeader'] = true;
        $log_fields_rec_count = $_Config['LF_record_count'];
	if($type=='header')
	{
//	var_dump($lf_array);
//echo "-->".$studentid;
		if($address_id && count($_SYSTEM['DrawTemplateHeaders_header_array'][$studentid])>1 && $_SYSTEM['DrawTemplateHeaders_header_array'][$studentid][1]['ADDRESS_ID']!=$address_id)
		{
			$which_student_record = false;
			for($i=1;$i<=count($_SYSTEM['DrawTemplateHeaders_header_array'][$studentid]);$i++)
			{
				if($_SYSTEM['DrawTemplateHeaders_header_array'][$studentid][$i]['ADDRESS_ID'] == $address_id)
				{
					$which_student_record = $i;
					break;
				}
			}
			if(!$which_student_record)
				$which_student_record = 1;
			$student = $_SYSTEM['DrawTemplateHeaders_header_array'][$studentid][$which_student_record];
		}
		else
			$student = $_SYSTEM['DrawTemplateHeaders_header_array'][$studentid][1];
			
//			var_dump($student);
		$letter_text = $_SYSTEM['DrawTemplateHeaders_header_text'];
		if(!$student) $student = array();
		foreach($student as $column=>$true)
		{
			$log_fields = $lf_array[$studentid][substr($column,strpos($column,'_')+1,4)];
//			var_dump($log_fields);
			if($log_fields)
			{
				$lc=1;
				unset($lf_stud);
				unset($lfields);
//var_dump($logging_field_array);
				foreach($log_fields as $count=>$field_data)
				{
					$i=0;
					foreach($field_data as $fieldname=>$field_info)
					{
						if(substr($fieldname,0,3) == 'LOG' && $logging_field_array[substr($column,strpos($column,'_')+1,4)][1][$fieldname.'_TITLE'])// && $field_info)
						{
						        $i++;
							$lf_stud[$lc][$fieldname] = $field_info;
    							$lfields[$i] = $fieldname;
					        }
					}
					$lc++;
				}
				$fic = count($lf_stud);
				$lfcnt = count($lfields);
				unset($lfd);
				$fc=1;
				foreach($lf_stud as $fld_name=>$info)
				{
					if($fc == 1)
					{
						$lfd[$column] = '<TABLE BORDER=1><TR>';
//						for($xx=1;$xx<=count($info);$xx++)
						foreach($lfields as $lcolumn)
							$lfd[$column] .= '<TD>'.$logging_field_array[substr($column,strpos($column,'_')+1,4)][1][$lcolumn.'_TITLE'].'</TD>';
						$lfd[$column] .= '</TR>';
					}
					$tt=1;
					foreach($info as $lcolumn=>$x)
					{
						if($tt == 1)
							$lfd[$column] .= '<TR>';
//							echo "==>".$lcolumn.($info[$lcolumn]?$info[$lcolumn]:'22')."<br>";
						$lffield_type = $logging_field_array[substr($column,strpos($column,'_')+1,4)][1][$lcolumn];
						if($lffield_type == 'date' && $_Config['DefaultDateFormat'])
						{
		    					$Calendar_class->dconvto = $_Config['DefaultDateFormat'];
							$info[$lcolumn] = $Calendar_class->ConvertDate($info[$lcolumn]);
						}
						$lfd[$column] .= '<TD>'.($info[$lcolumn]?$info[$lcolumn]:'&nbsp;').'</TD>';
						if($tt == count($info))
						{	
							$tds = $lfcnt - count($info);
							if($tds > 0)
								for($tdxx=1;$tdxx<=$tds;$tdxx++)
									$lfd[$column] .= '<TD>&nbsp;</TD>';
							$lfd[$column] .= '</TR>';
						}
						$tt++;
						
					}
					if($fic == $fc)
						$lfd[$column] .= '</TABLE>';
					$fc++;

				}
				$letter_text = str_replace('<_field['.$column.'] />',charset_decode_utf8(str_replace("\n","<BR>",str_replace("\r\n","<BR>",$lfd[$column]))),$letter_text);
			}

			if($log_fields)
			{
				$lc=1;
				unset($lf_stud);
				unset($lfields);
				foreach($log_fields as $count=>$field_data)
				{
					$el=1;
					foreach($field_data as $fieldname=>$field_info)
					{
						if(substr($fieldname,0,3) == 'LOG' && $field_info)
						{
							if($el > $elem_cnt)
						    		$elem_cnt = $el;
							$el++;
						        $lf_stud[$lc][$fieldname] = $field_info;
							$lfields[] = $fieldname;
						}
						
					}
					$lc++;
				}				
//				var_dump($lf_stud);
				$fic = count($lf_stud);
//				echo "-->".$fic.'--'.$fc.'=='.$elem_cnt.'}';
				unset($lfd);
				$fc=1;
				if($fic > 1)
					$lf_border = '1';
				else
					$lf_border = '0';
				$log_entrs = array();
				$fcxx=0;
				foreach($lf_stud as $fld_name=>$info)
				{
//					echo $fld_name;
//					var_dump($info);
					$fcxx++;
//					echo "00>".count($info);
					foreach($info as $lcolumn=>$x)
					{
//						echo "-->fic:".$fic.'--fc:'.$fc.'=='.$elem_cnt.'}<br>';					
						if($fc == 1)
//							$lfd[$lcolumn] = '<TABLE><TR><TD>'.$logging_field_array[substr($column,strpos($column,'_')+1,4)][1][$lcolumn.'_TITLE'].'</TD><TD><TABLE BORDER=1>';
							$lfd[$lcolumn] = '<TABLE BORDER='.$lf_border.' WIDTH="100%">';
						if(strpos($lfd[$lcolumn],'<TABLE') === false)
							$lfd[$lcolumn] = '<TABLE BORDER='.$lf_border.' WIDTH="100%">'.$lfd[$lcolumn];
						$lffield_type = $logging_field_array[substr($column,strpos($column,'_')+1,4)][1][$lcolumn];
						if($lffield_type == 'date' && $_Config['DefaultDateFormat'])
						{
		    					$Calendar_class->dconvto = $_Config['DefaultDateFormat'];
							$info[$lcolumn] = $Calendar_class->ConvertDate($info[$lcolumn]);
						}
						//echo $lcolumn.'='.$info[$lcolumn];
						$lfd[$lcolumn] .= '<TR><TD>'.$info[$lcolumn].'</TD></TR>';
						$log_entrs[$column][$lcolumn][$fc] = $info[$lcolumn];

						if($fic == $fc)
						{
							$lfd[$lcolumn] .= '</TABLE>';
						}
					}
					
					$fc++;
				}
//				var_dump($lfd);
//				echo "==>".$fc;
				//here is placing values to individual logging field
				foreach($lfields as $lcolumn)
				{
					$letter_text = str_replace('<_field['.$lcolumn.'+'.$column.'] />',charset_decode_utf8(str_replace("\n","<BR>",str_replace("\r\n","<BR>",$lfd[$lcolumn]))),$letter_text);
				}	
				for($ivkey=1;$ivkey<=$log_fields_rec_count;$ivkey++)
				{
					foreach($lfields as $lcolumn)
					{
						$lffield_type = $logging_field_array[substr($column,strpos($column,'_')+1,4)][1][$lcolumn];
						if($lffield_type == 'date' && $_Config['DefaultDateFormat'])
						{
		    					$Calendar_class->dconvto = $_Config['DefaultDateFormat'];
							$log_entrs[$column][$lcolumn][$ivkey] = $Calendar_class->ConvertDate($log_entrs[$column][$lcolumn][$ivkey]);
						}
						$letter_text = str_replace('<_field['.$ivkey.'+'.$lcolumn.'+'.$column.'] />',charset_decode_utf8(str_replace("\n","<BR>",str_replace("\r\n","<BR>",$log_entrs[$column][$lcolumn][$ivkey]))),$letter_text);
					}
				}
			}
			elseif($logging_field_array[substr($column,strpos($column,'_')+1,4)][1]['ID'] <> '' && !$log_fields)
			{
				$fake_lfd = array('LOG_FIELD1','LOG_FIELD2','LOG_FIELD3','LOG_FIELD4','LOG_FIELD5','LOG_FIELD6','LOG_FIELD7','LOG_FIELD8','LOG_FIELD9','LOG_FIELD10','LOG_FIELD11','LOG_FIELD12','LOG_FIELD13','LOG_FIELD14','LOG_FIELD15','LOG_FIELD16','LOG_FIELD17');
				foreach($fake_lfd as $lcolumn)
					$letter_text = str_replace('<_field['.$lcolumn.'+'.$column.'] />',charset_decode_utf8(str_replace("\n","<BR>",str_replace("\r\n","<BR>",''))),$letter_text);
				for($ivkey=1;$ivkey<=$log_fields_rec_count;$ivkey++)
					foreach($fake_lfd as $lcolumn)
						$letter_text = str_replace('<_field['.$ivkey.'+'.$lcolumn.'+'.$column.'] />',charset_decode_utf8(str_replace("\n","<BR>",str_replace("\r\n","<BR>",''))),$letter_text);
				$letter_text = str_replace('<_field['.$column.'] />',charset_decode_utf8(str_replace("\n","<BR>",str_replace("\r\n","<BR>",''))),$letter_text);
			}
			elseif(substr($column,7,4) === '8881')
			{
				$_SYSTEM['DisplayHeaderCall'] = true;
				$letter_text = str_replace('<_field['.$column.'] />',charset_decode_utf8(str_replace("\n","<BR>",str_replace("\r\n","<BR>",$Student_class->getDataByField($column)))),$letter_text);
				$_SYSTEM['DisplayHeaderCall'] = false;
			}
                        elseif($column == 'COUNTER')
                        {
                                $_SYSTEM['DisplayHeaderCall'] = true;
                                $Document->Doc_Id = $_REQUEST['doc_id'];
                                $letter_text = str_replace('<_field['.$column.'] />',charset_decode_utf8(str_replace("\n","<BR>",str_replace("\r\n","<BR>",$Document->MakeDocNum()))),$letter_text);
				$_SYSTEM['DisplayHeaderCall'] = false;
                        }
			else
			{
				$cfield_type = $fields_array[substr($column,strpos($column,'_')+1)][1]['TYPE'];
				$f_id = substr($column,strpos($column,'_')+1);
				$f_id = intval($f_id);
				if($cfield_type == 'date' && $_Config['DefaultDateFormat'])
				{
					$Calendar_class->dconvto = $_Config['DefaultDateFormat'];
					$student[$column] = $Calendar_class->ConvertDate($student[$column]);
				}
				elseif($f_id < 20 && $dates[$column])
				{
		    			$Calendar_class->dconvto = $dates[$column];
					$student[$column] = $Calendar_class->ConvertDate($student[$column]);
				}

				$letter_text = str_replace('<_field['.$column.'] />',charset_decode_utf8(str_replace("\n","<BR>",str_replace("\r\n","<BR>",$student[$column]))),$letter_text);
			}
		}


//			echo htmlspecialchars($letter_text);
		$letter_text = preg_replace('<div style="text-align?[:].>','div align="',$letter_text);
		$letter_text = preg_replace('<td style="text-align?[:].>','td align="',$letter_text);
		$letter_text = preg_replace('<h2 style="text-align?[:].>','h2 align="',$letter_text);
		$letter_text = preg_replace('<h3 style="text-align?[:].>','h3 align="',$letter_text);
		$letter_text = preg_replace('<h1 style="text-align?[:].>','h1 align="',$letter_text);

		$letter_text = str_replace('&nbsp;<u>',' <u>',$letter_text);
		$letter_text = str_replace('="center;','="center',$letter_text);
		$letter_text = str_replace('="left;','="left',$letter_text);
		$letter_text = str_replace('="right;','="right',$letter_text);
		$letter_text = str_replace('="justify;','="justify',$letter_text);
		$letter_text = "<TABLE class=right_both2><tr><td>&nbsp;</td></tr></TABLE>".$letter_text;
//		echo htmlspecialchars($letter_text);
	        return $letter_text;			
	}
	else
	{
		$student = $_SYSTEM['DrawTemplateHeaders_footer_array'][$studentid][1];
		$letter_text = $_SYSTEM['DrawTemplateHeaders_footer_text'];
		if(!$student) $student = array();
//		echo htmlspecialchars($letter_text);			
		$letter_text = preg_replace('<div style="text-align?[:].>','div align="',$letter_text);
		$letter_text = preg_replace('<td style="text-align?[:].>','td align="',$letter_text);
		$letter_text = preg_replace('<h2 style="text-align?[:].>','h2 align="',$letter_text);
		$letter_text = preg_replace('<h3 style="text-align?[:].>','h3 align="',$letter_text);
		$letter_text = preg_replace('<h1 style="text-align?[:].>','h1 align="',$letter_text);

		$letter_text = str_replace('&nbsp;<u>',' <u>',$letter_text);
		$letter_text = str_replace('="center;','="center',$letter_text);
		$letter_text = str_replace('="left;','="left',$letter_text);
		$letter_text = str_replace('="right;','="right',$letter_text);
		$letter_text = str_replace('="justify;','="justify',$letter_text);
		foreach($student as $column=>$true)
		{
			$log_fields = $lf_array[$studentid][substr($column,strpos($column,'_')+1,4)];
			if($log_fields)
			{
				$lc=1;
				unset($lf_stud);
				unset($lfields);
				foreach($log_fields as $count=>$field_data)
				{
					$i=0;
					foreach($field_data as $fieldname=>$field_info)
					{
						if(substr($fieldname,0,3) == 'LOG' && $logging_field_array[substr($column,strpos($column,'_')+1,4)][1][$fieldname.'_TITLE'])// && $field_info)
						{
						        $i++;
							$lf_stud[$lc][$fieldname] = $field_info;
    							$lfields[$i] = $fieldname;
					        }
					}
					$lc++;
				}
				$fic = count($lf_stud);
				$lfcnt = count($lfields);
				unset($lfd);
				$fc=1;
				foreach($lf_stud as $fld_name=>$info)
				{
					if($fc == 1)
					{
						$lfd[$column] = '<TABLE BORDER=1><TR>';
//						for($xx=1;$xx<=count($info);$xx++)
						foreach($lfields as $lcolumn)
							$lfd[$column] .= '<TD>'.$logging_field_array[substr($column,strpos($column,'_')+1,4)][1][$lcolumn.'_TITLE'].'</TD>';
						$lfd[$column] .= '</TR>';
					}
					$tt=1;
					foreach($info as $lcolumn=>$x)
					{
						if($tt == 1)
							$lfd[$column] .= '<TR>';
//							echo "==>".$lcolumn.($info[$lcolumn]?$info[$lcolumn]:'22')."<br>";
						$lffield_type = $logging_field_array[substr($column,strpos($column,'_')+1,4)][1][$lcolumn];
						if($lffield_type == 'date' && $_Config['DefaultDateFormat'])
						{
		    					$Calendar_class->dconvto = $_Config['DefaultDateFormat'];
							$info[$lcolumn] = $Calendar_class->ConvertDate($info[$lcolumn]);
						}
						$lfd[$column] .= '<TD>'.($info[$lcolumn]?$info[$lcolumn]:'&nbsp;').'</TD>';
						if($tt == count($info))
						{	$tds = $lfcnt - count($info);
							if($tds > 0)
								for($tdxx=1;$tdxx<=$tds;$tdxx++)
									$lfd[$column] .= '<TD>&nbsp;</TD>';
							$lfd[$column] .= '</TR>';
						}
						$tt++;
					}
					if($fic == $fc)
						$lfd[$column] .= '</TABLE>';
					$fc++;
				}
				$letter_text = str_replace('<_field['.$column.'] />',charset_decode_utf8(str_replace("\n","<BR>",str_replace("\r\n","<BR>",$lfd[$column]))),$letter_text);
			}

			if($log_fields)
			{
				$lc=1;
				unset($lf_stud);
				unset($lfields);
				foreach($log_fields as $count=>$field_data)
				{
					foreach($field_data as $fieldname=>$field_info)
					{
						if(substr($fieldname,0,3) == 'LOG' && $field_info)
						{
						        $lf_stud[$lc][$fieldname] = $field_info;
							$lfields[] = $fieldname;
						}
					}
					$lc++;
				}				
//				var_dump($lf_stud);
				$fic = count($lf_stud);
				unset($lfd);
				$fc=1;
				if($fic > 1)
					$lf_border = '1';
				else
					$lf_border = '0';
				
				foreach($lf_stud as $fld_name=>$info)
				{
					foreach($info as $lcolumn=>$x)
					{
						if($fc == 1)
//							$lfd[$lcolumn] = '<TABLE><TR><TD>'.$logging_field_array[substr($column,strpos($column,'_')+1,4)][1][$lcolumn.'_TITLE'].'</TD><TD><TABLE BORDER=1>';
							$lfd[$lcolumn] = '<TABLE BORDER='.$lf_border.'>';
						if(strpos($lfd[$lcolumn],'<TABLE') === false)
							$lfd[$lcolumn] = '<TABLE BORDER='.$lf_border.' WIDTH="100%">'.$lfd[$lcolumn];
						$lffield_type = $logging_field_array[substr($column,strpos($column,'_')+1,4)][1][$lcolumn];
						if($lffield_type == 'date' && $_Config['DefaultDateFormat'])
						{
		    					$Calendar_class->dconvto = $_Config['DefaultDateFormat'];
							$info[$lcolumn] = $Calendar_class->ConvertDate($info[$lcolumn]);
						}
						$lfd[$lcolumn] .= '<TR><TD>'.$info[$lcolumn].'</TD></TR>';
						$log_entrs[$column][$lcolumn][$fc] = $info[$lcolumn];
						if($fic == $fc)
							//$lfd[$lcolumn] .= '</TABLE></TD></TR></TABLE>';
							$lfd[$lcolumn] .= '</TABLE>';
					}
					$fc++;

				}
				foreach($lfields as $lcolumn)
					$letter_text = str_replace('<_field['.$lcolumn.'+'.$column.'] />',charset_decode_utf8(str_replace("\n","<BR>",str_replace("\r\n","<BR>",$lfd[$lcolumn]))),$letter_text);
				for($ivkey=1;$ivkey<=$log_fields_rec_count;$ivkey++)
				{
					foreach($lfields as $lcolumn)
					{
						$lffield_type = $logging_field_array[substr($column,strpos($column,'_')+1,4)][1][$lcolumn];
						if($lffield_type == 'date' && $_Config['DefaultDateFormat'])
						{
		    					$Calendar_class->dconvto = $_Config['DefaultDateFormat'];
							$log_entrs[$column][$lcolumn][$ivkey] = $Calendar_class->ConvertDate($log_entrs[$column][$lcolumn][$ivkey]);
						}

						$letter_text = str_replace('<_field['.$ivkey.'+'.$lcolumn.'+'.$column.'] />',charset_decode_utf8(str_replace("\n","<BR>",str_replace("\r\n","<BR>",$log_entrs[$column][$lcolumn][$ivkey]))),$letter_text);
					}
				}

			}
			elseif($logging_field_array[substr($column,strpos($column,'_')+1,4)][1]['ID'] <> '' && !$log_fields)
			{
				$fake_lfd = array('LOG_FIELD1','LOG_FIELD2','LOG_FIELD3','LOG_FIELD4','LOG_FIELD5','LOG_FIELD6','LOG_FIELD7','LOG_FIELD8','LOG_FIELD9','LOG_FIELD10','LOG_FIELD11','LOG_FIELD12','LOG_FIELD13','LOG_FIELD14','LOG_FIELD15','LOG_FIELD16','LOG_FIELD17');
				foreach($fake_lfd as $lcolumn)
					$letter_text = str_replace('<_field['.$lcolumn.'+'.$column.'] />',charset_decode_utf8(str_replace("\n","<BR>",str_replace("\r\n","<BR>",''))),$letter_text);
				//unset null records for "Value #x"
				for($ivkey=1;$ivkey<=$log_fields_rec_count;$ivkey++)
					foreach($fake_lfd as $lcolumn)
						$letter_text = str_replace('<_field['.$ivkey.'+'.$lcolumn.'+'.$column.'] />',charset_decode_utf8(str_replace("\n","<BR>",str_replace("\r\n","<BR>",''))),$letter_text);
				$letter_text = str_replace('<_field['.$column.'] />',charset_decode_utf8(str_replace("\n","<BR>",str_replace("\r\n","<BR>",''))),$letter_text);
			}
			elseif(substr($column,7,4) === '8881')
			{
				$_SYSTEM['DisplayHeaderCall'] = true;
				$letter_text = str_replace('<_field['.$column.'] />',charset_decode_utf8(str_replace("\n","<BR>",str_replace("\r\n","<BR>",$Student_class->getDataByField($column)))),$letter_text);
				$_SYSTEM['DisplayHeaderCall'] = false;
			}
			else
			{
				$cfield_type = $fields_array[substr($column,strpos($column,'_')+1)][1]['TYPE'];
				$f_id = substr($column,strpos($column,'_')+1);
				$f_id = intval($f_id);
				if($cfield_type == 'date' && $_Config['DefaultDateFormat'])
				{
					$Calendar_class->dconvto = $_Config['DefaultDateFormat'];
					$student[$column] = $Calendar_class->ConvertDate($student[$column]);
				}
				elseif($f_id < 20 && $dates[$column])
				{
		    			$Calendar_class->dconvto = $dates[$column];
					$student[$column] = $Calendar_class->ConvertDate($student[$column]);
				}				
				$letter_text = str_replace('<_field['.$column.'] />',charset_decode_utf8(str_replace("\n","<BR>",str_replace("\r\n","<BR>",$student[$column]))),$letter_text);
			}
//			$letter_text = str_replace('<_field['.$column.'] />',charset_decode_utf8(str_replace("\n","<BR>",str_replace("\r\n","<BR>",$student[$column]))),$letter_text);
//			$letter_text = ereg_replace('<div style="text-align?[:(center|left|right|justify)]','<div align=',$letter_text);

//
		}
//echo htmlspecialchars($letter_text);			
//die();
		unset($logging_field_array);
		unset($lf_array);
    		return $letter_text;
	}
}

function DrawTemplateHeaders($studentid='',$type='header', $return = false)
{
    if($return)
        return DrawTemplateHeaderBuffered($studentid, $type);
    elseif($studentid)
        echo DrawTemplateHeaderBuffered($studentid, $type);
}
//$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'=>_('Email'));

function makeLogHeader($student_id,$field)
{	global $_SYSTEM;

	$log_array = db_request(db_execute("SELECT ID,LOG_FIELD1,LOG_FIELD2,LOG_FIELD3,LOG_FIELD4,LOG_FIELD5,LOG_FIELD6,LOG_FIELD7,LOG_FIELD8,LOG_FIELD9,LOG_FIELD10,LOG_FIELD11,LOG_FIELD12,LOG_FIELD13,LOG_FIELD14,LOG_FIELD15,LOG_FIELD16,LOG_FIELD17,LOG_FIELD18,LOG_FIELD19,LOG_FIELD20 FROM STUDENT_LF_DATA WHERE STUDENT_ID='".$student_id."' AND STUDENT_FIELD_ID='".substr($field,7)."' ORDER BY ID ASC"));
	$field = $_SYSTEM['fields_array'][substr($field,7)][1];
	$table = '<TABLE border=1>';
	$table .= '<TR>';
	
	for($i=1;$i<=20;$i++)
	{
		if($field['LOG_FIELD'.$i])
		{
			$table .= '<TH>';
			$table .= $field['LOG_FIELD'.$i.'_TITLE'];
			$table .= '</TH>';
		}
	}
	
	/*
	if($field['LOG_CHECKBOX'])
	{
		$table .= '<TH>';
		$table .= $field['LOG_CHECKBOX_TITLE'];
		$table .= '</TH>';
	}
	if($field['LOG_SELECT'])
	{
		$table .= '<TH>';
		$table .= $field['LOG_SELECT_TITLE'];
		$table .= '</TH>';
	}
	if($field['LOG_SELECT2'])
	{
		$table .= '<TH>';
		$table .= $field['LOG_SELECT2_TITLE'];
		$table .= '</TH>';
	}
	if($field['LOG_DATE'])
	{
		$table .= '<TH>';
		$table .= $field['LOG_DATE_TITLE'];
		$table .= '</TH>';
	}
	if($field['LOG_DATE2'])
	{
		$table .= '<TH>';
		$table .= $field['LOG_DATE2_TITLE'];
		$table .= '</TH>';
	}
	if($field['LOG_NUMERIC'])
	{
		$table .= '<TH>';
		$table .= $field['LOG_NUMERIC_TITLE'];
		$table .= '</TH>';
	}
	for($i=1;$i<=5;$i++)
	{
		if($field['LOG_TEXT'.$i])
		{
			$table .= '<TH>';
			$table .= $field['LOG_TEXT'.$i.'_TITLE'];
			$table .= '</TH>';
		}
	}
	if($field['LOG_TEXTAREA'])
	{
		$table .= '<TH>';
		$table .= $field['LOG_TEXTAREA_TITLE'];
		$table .= '</TH>';
	}
	*/
	
	$table .= '</TR>';	
	
	
	foreach($log_array as $row)
	{
		$table .= '<TR>';
		
		for($i=1;$i<=20;$i++)
		{
			if($field['LOG_FIELD'.$i])
			{
    			$table .= '<TD>';
				$table .= ($row['LOG_FIELD'.$i]);
				$table .= '</TD>';	
			}	
		}

		/*	
		if($field['LOG_CHECKBOX'])
		{
			$table .= '<TD>';
			$table .= ($row['LOG_CHECKBOX']!='Y'?'N':'Y');
			$table .= '</TD>';
		}
		if($field['LOG_SELECT'])
		{
			$table .= '<TD>';
			$table .= $row['LOG_SELECT'];
			$table .= '</TD>';
		}
		if($field['LOG_SELECT2'])
		{
			$table .= '<TD>';
			$table .= $row['LOG_SELECT2'];
			$table .= '</TD>';
		}
		if($field['LOG_DATE'])
		{
			$table .= '<TD>';
			$table .= ProperDate($row['LOG_DATE']);
			$table .= '</TD>';
		}
		if($field['LOG_DATE2'])
		{
			$table .= '<TD>';
			$table .= ProperDate($row['LOG_DATE2']);
			$table .= '</TD>';
		}
		if($field['LOG_NUMERIC'])
		{
			$table .= '<TD>';
			$table .= $row['LOG_NUMERIC'];
			$table .= '</TD>';
		}
		for($i=1;$i<=5;$i++)
		{
			if($field['LOG_TEXT'.$i])
			{
				$table .= '<TD>';
				$table .= $row['LOG_TEXT'.$i];
				$table .= '</TD>';
			}
		}
		if($field['LOG_TEXTAREA'])
		{
			$table .= '<TD>';
			$table .= $row['LOG_TEXTAREA'];
			$table .= '</TD>';
		}
		*/
		
		$table .= '</TR>';
	}
	$table .= '</TABLE>';

	return $table;
}

function RoundGPA($gpa)
{
	if($gpa && strlen($gpa)==1)
		return $gpa.'.0';
	elseif($gpa)
		return round($gpa,SystemPreferences('ROUND_GPA_POINTS'));
}

function makeSchoolYear($school_year)
{
	return $school_year.((SystemPreferences('SCHOOL_YEAR_TITLE')=='YYYY-YYYY')?'-'.($school_year+1):'');
}

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

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

	if($record[$column[0]])
	{
		if($column[1]=='name')
			return $record[$column[0]][1]['NAME'];
		if($column[1]=='home')
			return $record[$column[0]][1]['PHONE'];
			
		foreach($record[$column[0]] as $info)
		{
			if(strpos($info['TITLE'],$column[1])===0)
				return $info['VALUE'];
		}
		// we should only reach here if the parent exists, but the contact info requested doesn't
		return;
	}
	// there isn't a contact called Father / Dad ... so, return any contact called parent instead
	if(($column[0]=='father' || $column[0]=='mother'))
	{
		foreach($record['parent'] as $i=>$info)
		{
			$return = false;
			if($column[1]=='name')
				$return = $record['parent'][$i]['NAME'];
			if($column[1]=='home')
				$return = $record['parent'][$i]['PHONE'];

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

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

		// the parent doesn't exist, or the contact info requested doesn't
		return;
	}
	// this is the 4th contact or there isn't a contact that starts with Emergency ... so, return any other contact instead
	if($column[0]=='emergency' || $column[0]=='contact')
	{
		foreach($record['other'] as $i=>$info)
		{
			$return = false;
			if($column[1]=='name')
				$return = $record['other'][$i]['NAME'];
			if($column[1]=='home')
				$return = $record['other'][$i]['PHONE'];

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

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

	// we should never reach this point
	return ;
}

function charset_decode_utf8($string) 
{
	/* Only do the slow convert if there are 8-bit characters */ 
	/* avoid using 0xA0 (\240) in ereg ranges. RH73 does not like that */ 
	if (! preg_match("[\200-\237]", $string) and ! preg_match("[\241-\377]", $string)) 
		return $string; 

	// decode three byte unicode characters 
	$string = preg_replace("/([\340-\357])([\200-\277])([\200-\277])/e","'&#'.((ord('\\1')-224)*4096 + (ord('\\2')-128)*64 + (ord('\\3')-128)).';'",$string); 

	// decode two byte unicode characters 
	$string = preg_replace("/([\300-\337])([\200-\277])/e","'&#'.((ord('\\1')-192)*64+(ord('\\2')-128)).';'",$string); 

	return $string; 
} 
function OutToVarStart()
{
    	ob_start();
}
function OutToVarEnd()
{
        $output = ob_get_contents();
	$flag = null;
        while (@ob_end_clean());
        return $output;
}
?>