<?php

function MailingLabel($address_id)
{	global $THIS_array,$_SYSTEM;

	//выгребает данные по адресам: если для родителей или опекунов то через PEOPLE, если для учащихся то через STUDENT_IN_ADDRESS
	$student_id = $THIS_array['STUDENT_ID'];
	if($address_id && !$_SYSTEM['MailingLabel'][$address_id][$student_id])
	{
		if($_REQUEST['to_address'] != 'student')
		{
			$people_array = db_request(db_execute("SELECT a.ADDRESS_ID,p.PERSON_ID,
				COALESCE(a.MAIL_ADDRESS,a.ADDRESS) AS ADDRESS,COALESCE(a.MAIL_CITY,a.CITY) AS CITY,COALESCE(a.MAIL_STATE,a.STATE) AS STATE,COALESCE(a.MAIL_ZIPCODE,a.ZIPCODE) AS ZIPCODE,a.PHONE,
					p.LAST_NAME,p.FIRST_NAME,p.MIDDLE_NAME
				FROM ADDRESS a,STUDENT_RELATIONS p,STUDENTS_IN_SR sjp
				WHERE a.ADDRESS_ID='$address_id' AND a.ADDRESS_ID=sjp.ADDRESS_ID AND p.PERSON_ID=sjp.PERSON_ID 
					AND sjp.CUSTODY='Y' AND sjp.STUDENT_ID='".$student_id."'"),array(),array('LAST_NAME'));
			if(count($people_array))
			{
				foreach($people_array as $last_name=>$people)
				{
					for($i=1;$i<count($people);$i++)
						$return .= $people[$i]['FIRST_NAME'].' &amp; ';
					$return .= $people[$i]['FIRST_NAME'].' '.$people[$i]['LAST_NAME'].'<BR>';
				}
				$return .= '<!-- ENDPARENTS -->'.$people[$i]['ADDRESS'].'<BR>'.$people[$i]['CITY'].', '.$people[$i]['STATE'].' '.$people[$i]['ZIPCODE'];
			}
		}
		else
		{
			$stu_addr_array = db_request(db_execute("SELECT a.ADDRESS_ID, COALESCE(a.MAIL_ADDRESS,a.ADDRESS) AS ADDRESS,COALESCE(a.MAIL_CITY,a.CITY) AS CITY,COALESCE(a.MAIL_STATE,a.STATE) AS STATE,COALESCE(a.MAIL_ZIPCODE,a.ZIPCODE) AS ZIPCODE,a.PHONE
				FROM ADDRESS a,STUDENTS_IN_ADDRESS sa WHERE a.ADDRESS_ID='$address_id' AND a.ADDRESS_ID=sa.ADDRESS_ID AND sa.STUDENT_ID='".$student_id."'"),array(),array());
			if(count($stu_addr_array))
			{
				$return .= '<!-- ENDPARENTS -->'.$stu_addr_array[1]['ADDRESS'].'<BR>'.$stu_addr_array[1]['CITY'].', '.$stu_addr_array[1]['STATE'].' '.$stu_addr_array[1]['ZIPCODE'];
			}				
		}
		$_SYSTEM['MailingLabel'][$address_id][$student_id] = $return;
	}

	return $_SYSTEM['MailingLabel'][$address_id][$student_id];
}

// Takes no args.  ADDRESS_ID and STUDENT_ID are pulled from $THIS_array
function MailToLabel()
{	global $THIS_array,$_SYSTEM;

	if($THIS_array['STUDENT_ID'] && $THIS_array['ADDRESS_ID'])
	{
		$people_array = db_request(db_execute("SELECT p.LAST_NAME,p.FIRST_NAME,p.MIDDLE_NAME
			FROM STUDENT_RELATIONS p,STUDENTS_IN_SR sjp
			WHERE sjp.ADDRESS_ID='".$THIS_array['ADDRESS_ID']."' AND p.PERSON_ID=sjp.PERSON_ID 
				AND sjp.CUSTODY='Y' AND sjp.STUDENT_ID='".$THIS_array['STUDENT_ID']."'"),array(),array('LAST_NAME'));
		
		if(count($people_array))
		{
			foreach($people_array as $last_name=>$people)
			{
				for($i=1;$i<count($people);$i++)
					$return .= $people[$i]['FIRST_NAME'].' &amp; ';
				$return .= $people[$i]['FIRST_NAME'].' '.$people[$i]['LAST_NAME'].', ';
			}
		}
		return substr($return,0,-2);
	}
}

?>