<?php

// Data functions (insert, update, delete, form) for table students

// This script and data application were generated by AppGini 5.70
// Download AppGini for free from https://bigprof.com/appgini/download/

function students_insert(){
	global $Translation;

	// mm: can member insert record?
	$arrPerm=getTablePermissions('students');
	if(!$arrPerm[1]){
		return false;
	}

	$data['FullName'] = makeSafe($_REQUEST['FullName']);
		if($data['FullName'] == empty_lookup_value){ $data['FullName'] = ''; }
	$data['Gender'] = makeSafe($_REQUEST['Gender']);
		if($data['Gender'] == empty_lookup_value){ $data['Gender'] = ''; }
	$data['DOB'] = intval($_REQUEST['DOBYear']) . '-' . intval($_REQUEST['DOBMonth']) . '-' . intval($_REQUEST['DOBDay']);
	$data['DOB'] = parseMySQLDate($data['DOB'], '');
	$data['RegNo'] = makeSafe($_REQUEST['RegNo']);
		if($data['RegNo'] == empty_lookup_value){ $data['RegNo'] = ''; }
	$data['Class'] = makeSafe($_REQUEST['Class']);
		if($data['Class'] == empty_lookup_value){ $data['Class'] = ''; }
	$data['Stream'] = makeSafe($_REQUEST['Stream']);
		if($data['Stream'] == empty_lookup_value){ $data['Stream'] = ''; }
	$data['Hostel'] = makeSafe($_REQUEST['Hostel']);
		if($data['Hostel'] == empty_lookup_value){ $data['Hostel'] = ''; }
	$data['DOJ'] = intval($_REQUEST['DOJYear']) . '-' . intval($_REQUEST['DOJMonth']) . '-' . intval($_REQUEST['DOJDay']);
	$data['DOJ'] = parseMySQLDate($data['DOJ'], '1');
	$data['Category'] = makeSafe($_REQUEST['Category']);
		if($data['Category'] == empty_lookup_value){ $data['Category'] = ''; }
	$data['AcademicYear'] = makeSafe($_REQUEST['AcademicYear']);
		if($data['AcademicYear'] == empty_lookup_value){ $data['AcademicYear'] = ''; }
	$data['TotalFees'] = makeSafe($_REQUEST['TotalFees']);
		if($data['TotalFees'] == empty_lookup_value){ $data['TotalFees'] = ''; }
	$data['AdvanceFees'] = makeSafe($_REQUEST['AdvanceFees']);
		if($data['AdvanceFees'] == empty_lookup_value){ $data['AdvanceFees'] = ''; }
	$data['Balance'] = makeSafe($_REQUEST['Balance']);
		if($data['Balance'] == empty_lookup_value){ $data['Balance'] = ''; }
	$data['Parent'] = makeSafe($_REQUEST['Parent']);
		if($data['Parent'] == empty_lookup_value){ $data['Parent'] = ''; }
	$data['Photo'] = PrepareUploadedFile('Photo', 5120000,'jpg|jpeg|gif|png', false, '');
	if($data['Photo']) createThumbnail($data['Photo'], getThumbnailSpecs('students', 'Photo', 'tv'));
	if($data['Photo']) createThumbnail($data['Photo'], getThumbnailSpecs('students', 'Photo', 'dv'));
	if($data['FullName']== ''){
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">" . $Translation['error:'] . " 'FullName': " . $Translation['field not null'] . '<br><br>';
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}
	if($data['Gender']== ''){
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">" . $Translation['error:'] . " 'Gender': " . $Translation['field not null'] . '<br><br>';
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}
	if($data['DOB']== ''){
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">" . $Translation['error:'] . " 'Death Of Birth': " . $Translation['field not null'] . '<br><br>';
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}
	if($data['RegNo']== ''){
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">" . $Translation['error:'] . " 'RegNo': " . $Translation['field not null'] . '<br><br>';
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}
	if($data['Class']== ''){
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">" . $Translation['error:'] . " 'Class': " . $Translation['field not null'] . '<br><br>';
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}
	if($data['DOJ']== ''){
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">" . $Translation['error:'] . " 'DOJ': " . $Translation['field not null'] . '<br><br>';
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}
	if($data['AcademicYear']== ''){
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">" . $Translation['error:'] . " 'AcademicYear': " . $Translation['field not null'] . '<br><br>';
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}
	if($data['TotalFees']== ''){
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">" . $Translation['error:'] . " 'TotalFees': " . $Translation['field not null'] . '<br><br>';
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}
	if($data['AdvanceFees']== ''){
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">" . $Translation['error:'] . " 'AdvanceFees': " . $Translation['field not null'] . '<br><br>';
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}

	/* for empty upload fields, when saving a copy of an existing record, copy the original upload field */
	if($_REQUEST['SelectedID']){
		$res = sql("select * from students where id='" . makeSafe($_REQUEST['SelectedID']) . "'", $eo);
		if($row = db_fetch_assoc($res)){
			if(!$data['Photo']) $data['Photo'] = makeSafe($row['Photo']);
		}
	}

	// hook: students_before_insert
	if(function_exists('students_before_insert')){
		$args=array();
		if(!students_before_insert($data, getMemberInfo(), $args)){ return false; }
	}

	$o = array('silentErrors' => true);
	sql('insert into `students` set       `FullName`=' . (($data['FullName'] !== '' && $data['FullName'] !== NULL) ? "'{$data['FullName']}'" : 'NULL') . ', `Gender`=' . (($data['Gender'] !== '' && $data['Gender'] !== NULL) ? "'{$data['Gender']}'" : 'NULL') . ', `DOB`=' . (($data['DOB'] !== '' && $data['DOB'] !== NULL) ? "'{$data['DOB']}'" : 'NULL') . ', ' . ($data['Photo'] != '' ? "`Photo`='{$data['Photo']}'" : '`Photo`=NULL') . ', `RegNo`=' . (($data['RegNo'] !== '' && $data['RegNo'] !== NULL) ? "'{$data['RegNo']}'" : 'NULL') . ', `Class`=' . (($data['Class'] !== '' && $data['Class'] !== NULL) ? "'{$data['Class']}'" : 'NULL') . ', `Stream`=' . (($data['Stream'] !== '' && $data['Stream'] !== NULL) ? "'{$data['Stream']}'" : 'NULL') . ', `Hostel`=' . (($data['Hostel'] !== '' && $data['Hostel'] !== NULL) ? "'{$data['Hostel']}'" : 'NULL') . ', `DOJ`=' . (($data['DOJ'] !== '' && $data['DOJ'] !== NULL) ? "'{$data['DOJ']}'" : 'NULL') . ', `Category`=' . (($data['Category'] !== '' && $data['Category'] !== NULL) ? "'{$data['Category']}'" : 'NULL') . ', `AcademicYear`=' . (($data['AcademicYear'] !== '' && $data['AcademicYear'] !== NULL) ? "'{$data['AcademicYear']}'" : 'NULL') . ', `TotalFees`=' . (($data['TotalFees'] !== '' && $data['TotalFees'] !== NULL) ? "'{$data['TotalFees']}'" : 'NULL') . ', `AdvanceFees`=' . (($data['AdvanceFees'] !== '' && $data['AdvanceFees'] !== NULL) ? "'{$data['AdvanceFees']}'" : 'NULL') . ', `Balance`=' . (($data['Balance'] !== '' && $data['Balance'] !== NULL) ? "'{$data['Balance']}'" : 'NULL') . ', `Parent`=' . (($data['Parent'] !== '' && $data['Parent'] !== NULL) ? "'{$data['Parent']}'" : 'NULL'), $o);
	if($o['error']!=''){
		echo $o['error'];
		echo "<a href=\"students_view.php?addNew_x=1\">{$Translation['< back']}</a>";
		exit;
	}

	$recID = db_insert_id(db_link());

	// hook: students_after_insert
	if(function_exists('students_after_insert')){
		$res = sql("select * from `students` where `id`='" . makeSafe($recID, false) . "' limit 1", $eo);
		if($row = db_fetch_assoc($res)){
			$data = array_map('makeSafe', $row);
		}
		$data['selectedID'] = makeSafe($recID, false);
		$args=array();
		if(!students_after_insert($data, getMemberInfo(), $args)){ return $recID; }
	}

	// mm: save ownership data
	set_record_owner('students', $recID, getLoggedMemberID());

	return $recID;
}

function students_delete($selected_id, $AllowDeleteOfParents=false, $skipChecks=false){
	// insure referential integrity ...
	global $Translation;
	$selected_id=makeSafe($selected_id);

	// mm: can member delete record?
	$arrPerm=getTablePermissions('students');
	$ownerGroupID=sqlValue("select groupID from membership_userrecords where tableName='students' and pkValue='$selected_id'");
	$ownerMemberID=sqlValue("select lcase(memberID) from membership_userrecords where tableName='students' and pkValue='$selected_id'");
	if(($arrPerm[4]==1 && $ownerMemberID==getLoggedMemberID()) || ($arrPerm[4]==2 && $ownerGroupID==getLoggedGroupID()) || $arrPerm[4]==3){ // allow delete?
		// delete allowed, so continue ...
	}else{
		return $Translation['You don\'t have enough permissions to delete this record'];
	}

	// hook: students_before_delete
	if(function_exists('students_before_delete')){
		$args=array();
		if(!students_before_delete($selected_id, $skipChecks, getMemberInfo(), $args))
			return $Translation['Couldn\'t delete this record'];
	}

	// child table: feescollection
	$res = sql("select `id` from `students` where `id`='$selected_id'", $eo);
	$id = db_fetch_row($res);
	$rires = sql("select count(1) from `feescollection` where `Student`='".addslashes($id[0])."'", $eo);
	$rirow = db_fetch_row($rires);
	if($rirow[0] && !$AllowDeleteOfParents && !$skipChecks){
		$RetMsg = $Translation["couldn't delete"];
		$RetMsg = str_replace("<RelatedRecords>", $rirow[0], $RetMsg);
		$RetMsg = str_replace("<TableName>", "feescollection", $RetMsg);
		return $RetMsg;
	}elseif($rirow[0] && $AllowDeleteOfParents && !$skipChecks){
		$RetMsg = $Translation["confirm delete"];
		$RetMsg = str_replace("<RelatedRecords>", $rirow[0], $RetMsg);
		$RetMsg = str_replace("<TableName>", "feescollection", $RetMsg);
		$RetMsg = str_replace("<Delete>", "<input type=\"button\" class=\"button\" value=\"".$Translation['yes']."\" onClick=\"window.location='students_view.php?SelectedID=".urlencode($selected_id)."&delete_x=1&confirmed=1';\">", $RetMsg);
		$RetMsg = str_replace("<Cancel>", "<input type=\"button\" class=\"button\" value=\"".$Translation['no']."\" onClick=\"window.location='students_view.php?SelectedID=".urlencode($selected_id)."';\">", $RetMsg);
		return $RetMsg;
	}

	// child table: examresults
	$res = sql("select `id` from `students` where `id`='$selected_id'", $eo);
	$id = db_fetch_row($res);
	$rires = sql("select count(1) from `examresults` where `student`='".addslashes($id[0])."'", $eo);
	$rirow = db_fetch_row($rires);
	if($rirow[0] && !$AllowDeleteOfParents && !$skipChecks){
		$RetMsg = $Translation["couldn't delete"];
		$RetMsg = str_replace("<RelatedRecords>", $rirow[0], $RetMsg);
		$RetMsg = str_replace("<TableName>", "examresults", $RetMsg);
		return $RetMsg;
	}elseif($rirow[0] && $AllowDeleteOfParents && !$skipChecks){
		$RetMsg = $Translation["confirm delete"];
		$RetMsg = str_replace("<RelatedRecords>", $rirow[0], $RetMsg);
		$RetMsg = str_replace("<TableName>", "examresults", $RetMsg);
		$RetMsg = str_replace("<Delete>", "<input type=\"button\" class=\"button\" value=\"".$Translation['yes']."\" onClick=\"window.location='students_view.php?SelectedID=".urlencode($selected_id)."&delete_x=1&confirmed=1';\">", $RetMsg);
		$RetMsg = str_replace("<Cancel>", "<input type=\"button\" class=\"button\" value=\"".$Translation['no']."\" onClick=\"window.location='students_view.php?SelectedID=".urlencode($selected_id)."';\">", $RetMsg);
		return $RetMsg;
	}

	// child table: classattendance
	$res = sql("select `id` from `students` where `id`='$selected_id'", $eo);
	$id = db_fetch_row($res);
	$rires = sql("select count(1) from `classattendance` where `Student`='".addslashes($id[0])."'", $eo);
	$rirow = db_fetch_row($rires);
	if($rirow[0] && !$AllowDeleteOfParents && !$skipChecks){
		$RetMsg = $Translation["couldn't delete"];
		$RetMsg = str_replace("<RelatedRecords>", $rirow[0], $RetMsg);
		$RetMsg = str_replace("<TableName>", "classattendance", $RetMsg);
		return $RetMsg;
	}elseif($rirow[0] && $AllowDeleteOfParents && !$skipChecks){
		$RetMsg = $Translation["confirm delete"];
		$RetMsg = str_replace("<RelatedRecords>", $rirow[0], $RetMsg);
		$RetMsg = str_replace("<TableName>", "classattendance", $RetMsg);
		$RetMsg = str_replace("<Delete>", "<input type=\"button\" class=\"button\" value=\"".$Translation['yes']."\" onClick=\"window.location='students_view.php?SelectedID=".urlencode($selected_id)."&delete_x=1&confirmed=1';\">", $RetMsg);
		$RetMsg = str_replace("<Cancel>", "<input type=\"button\" class=\"button\" value=\"".$Translation['no']."\" onClick=\"window.location='students_view.php?SelectedID=".urlencode($selected_id)."';\">", $RetMsg);
		return $RetMsg;
	}

	// delete file stored in the 'Photo' field
	$res = sql("select `Photo` from `students` where `id`='$selected_id'", $eo);
	if($row=@db_fetch_row($res)){
		if($row[0]!=''){
			@unlink(getUploadDir('').$row[0]);
			preg_match('/^[a-z0-9_]+\.(gif|png|jpg|jpeg|jpe)$/i', $row[0], $m);
			$thumbDV=str_replace(".$m[1]ffffgggg", "_dv.$m[1]", $row[0].'ffffgggg');
			$thumbTV=str_replace(".$m[1]ffffgggg", "_tv.$m[1]", $row[0].'ffffgggg');
			@unlink(getUploadDir('').$thumbTV);
			@unlink(getUploadDir('').$thumbDV);
		}
	}

	sql("delete from `students` where `id`='$selected_id'", $eo);

	// hook: students_after_delete
	if(function_exists('students_after_delete')){
		$args=array();
		students_after_delete($selected_id, getMemberInfo(), $args);
	}

	// mm: delete ownership data
	sql("delete from membership_userrecords where tableName='students' and pkValue='$selected_id'", $eo);
}

function students_update($selected_id){
	global $Translation;

	// mm: can member edit record?
	$arrPerm=getTablePermissions('students');
	$ownerGroupID=sqlValue("select groupID from membership_userrecords where tableName='students' and pkValue='".makeSafe($selected_id)."'");
	$ownerMemberID=sqlValue("select lcase(memberID) from membership_userrecords where tableName='students' and pkValue='".makeSafe($selected_id)."'");
	if(($arrPerm[3]==1 && $ownerMemberID==getLoggedMemberID()) || ($arrPerm[3]==2 && $ownerGroupID==getLoggedGroupID()) || $arrPerm[3]==3){ // allow update?
		// update allowed, so continue ...
	}else{
		return false;
	}

	$data['FullName'] = makeSafe($_REQUEST['FullName']);
		if($data['FullName'] == empty_lookup_value){ $data['FullName'] = ''; }
	if($data['FullName']==''){
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">{$Translation['error:']} 'FullName': {$Translation['field not null']}<br><br>";
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}
	$data['Gender'] = makeSafe($_REQUEST['Gender']);
		if($data['Gender'] == empty_lookup_value){ $data['Gender'] = ''; }
	if($data['Gender']==''){
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">{$Translation['error:']} 'Gender': {$Translation['field not null']}<br><br>";
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}
	$data['DOB'] = intval($_REQUEST['DOBYear']) . '-' . intval($_REQUEST['DOBMonth']) . '-' . intval($_REQUEST['DOBDay']);
	$data['DOB'] = parseMySQLDate($data['DOB'], '');
	if($data['DOB']==''){
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">{$Translation['error:']} 'Death Of Birth': {$Translation['field not null']}<br><br>";
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}
	$data['RegNo'] = makeSafe($_REQUEST['RegNo']);
		if($data['RegNo'] == empty_lookup_value){ $data['RegNo'] = ''; }
	if($data['RegNo']==''){
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">{$Translation['error:']} 'RegNo': {$Translation['field not null']}<br><br>";
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}
	$data['Class'] = makeSafe($_REQUEST['Class']);
		if($data['Class'] == empty_lookup_value){ $data['Class'] = ''; }
	if($data['Class']==''){
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">{$Translation['error:']} 'Class': {$Translation['field not null']}<br><br>";
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}
	$data['Stream'] = makeSafe($_REQUEST['Stream']);
		if($data['Stream'] == empty_lookup_value){ $data['Stream'] = ''; }
	$data['Hostel'] = makeSafe($_REQUEST['Hostel']);
		if($data['Hostel'] == empty_lookup_value){ $data['Hostel'] = ''; }
	$data['DOJ'] = intval($_REQUEST['DOJYear']) . '-' . intval($_REQUEST['DOJMonth']) . '-' . intval($_REQUEST['DOJDay']);
	$data['DOJ'] = parseMySQLDate($data['DOJ'], '1');
	if($data['DOJ']==''){
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">{$Translation['error:']} 'DOJ': {$Translation['field not null']}<br><br>";
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}
	$data['Category'] = makeSafe($_REQUEST['Category']);
		if($data['Category'] == empty_lookup_value){ $data['Category'] = ''; }
	$data['AcademicYear'] = makeSafe($_REQUEST['AcademicYear']);
		if($data['AcademicYear'] == empty_lookup_value){ $data['AcademicYear'] = ''; }
	if($data['AcademicYear']==''){
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">{$Translation['error:']} 'AcademicYear': {$Translation['field not null']}<br><br>";
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}
	$data['TotalFees'] = makeSafe($_REQUEST['TotalFees']);
		if($data['TotalFees'] == empty_lookup_value){ $data['TotalFees'] = ''; }
	if($data['TotalFees']==''){
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">{$Translation['error:']} 'TotalFees': {$Translation['field not null']}<br><br>";
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}
	$data['AdvanceFees'] = makeSafe($_REQUEST['AdvanceFees']);
		if($data['AdvanceFees'] == empty_lookup_value){ $data['AdvanceFees'] = ''; }
	if($data['AdvanceFees']==''){
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">{$Translation['error:']} 'AdvanceFees': {$Translation['field not null']}<br><br>";
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}
	$data['Balance'] = makeSafe($_REQUEST['Balance']);
		if($data['Balance'] == empty_lookup_value){ $data['Balance'] = ''; }
	$data['Parent'] = makeSafe($_REQUEST['Parent']);
		if($data['Parent'] == empty_lookup_value){ $data['Parent'] = ''; }
	$data['selectedID']=makeSafe($selected_id);
	if($_REQUEST['Photo_remove'] == 1){
		$data['Photo'] = '';
		// delete file from server
		$res = sql("select `Photo` from `students` where `id`='".makeSafe($selected_id)."'", $eo);
		if($row=@db_fetch_row($res)){
			if($row[0]!=''){
				@unlink(getUploadDir('').$row[0]);
				preg_match('/^[a-z0-9_]+\.(gif|png|jpg|jpeg|jpe)$/i', $row[0], $m);
				$thumbDV=str_replace(".$m[1]ffffgggg", "_dv.$m[1]", $row[0].'ffffgggg');
				$thumbTV=str_replace(".$m[1]ffffgggg", "_tv.$m[1]", $row[0].'ffffgggg');
				@unlink(getUploadDir('').$thumbTV);
				@unlink(getUploadDir('').$thumbDV);
			}
		}
	}else{
		$data['Photo'] = PrepareUploadedFile('Photo', 5120000, 'jpg|jpeg|gif|png', false, "");
		if($data['Photo']) createThumbnail($data['Photo'], getThumbnailSpecs('students', 'Photo', 'tv'));
		if($data['Photo']) createThumbnail($data['Photo'], getThumbnailSpecs('students', 'Photo', 'dv'));
		// delete file from server
		if($data['Photo'] != ''){
			$res = sql("select `Photo` from `students` where `id`='".makeSafe($selected_id)."'", $eo);
			if($row=@db_fetch_row($res)){
				if($row[0]!=''){
					@unlink(getUploadDir('').$row[0]);
					preg_match('/^[a-z0-9_]+\.(gif|png|jpg|jpeg|jpe)$/i', $row[0], $m);
					$thumbDV=str_replace(".$m[1]ffffgggg", "_dv.$m[1]", $row[0].'ffffgggg');
					$thumbTV=str_replace(".$m[1]ffffgggg", "_tv.$m[1]", $row[0].'ffffgggg');
					@unlink(getUploadDir('').$thumbTV);
					@unlink(getUploadDir('').$thumbDV);
				}
			}
		}
	}

	// hook: students_before_update
	if(function_exists('students_before_update')){
		$args=array();
		if(!students_before_update($data, getMemberInfo(), $args)){ return false; }
	}

	$o=array('silentErrors' => true);
	sql('update `students` set       `FullName`=' . (($data['FullName'] !== '' && $data['FullName'] !== NULL) ? "'{$data['FullName']}'" : 'NULL') . ', `Gender`=' . (($data['Gender'] !== '' && $data['Gender'] !== NULL) ? "'{$data['Gender']}'" : 'NULL') . ', `DOB`=' . (($data['DOB'] !== '' && $data['DOB'] !== NULL) ? "'{$data['DOB']}'" : 'NULL') . ', ' . ($data['Photo']!='' ? "`Photo`='{$data['Photo']}'" : ($_REQUEST['Photo_remove'] != 1 ? '`Photo`=`Photo`' : '`Photo`=NULL')) . ', `RegNo`=' . (($data['RegNo'] !== '' && $data['RegNo'] !== NULL) ? "'{$data['RegNo']}'" : 'NULL') . ', `Class`=' . (($data['Class'] !== '' && $data['Class'] !== NULL) ? "'{$data['Class']}'" : 'NULL') . ', `Stream`=' . (($data['Stream'] !== '' && $data['Stream'] !== NULL) ? "'{$data['Stream']}'" : 'NULL') . ', `Hostel`=' . (($data['Hostel'] !== '' && $data['Hostel'] !== NULL) ? "'{$data['Hostel']}'" : 'NULL') . ', `DOJ`=' . (($data['DOJ'] !== '' && $data['DOJ'] !== NULL) ? "'{$data['DOJ']}'" : 'NULL') . ', `Category`=' . (($data['Category'] !== '' && $data['Category'] !== NULL) ? "'{$data['Category']}'" : 'NULL') . ', `AcademicYear`=' . (($data['AcademicYear'] !== '' && $data['AcademicYear'] !== NULL) ? "'{$data['AcademicYear']}'" : 'NULL') . ', `TotalFees`=' . (($data['TotalFees'] !== '' && $data['TotalFees'] !== NULL) ? "'{$data['TotalFees']}'" : 'NULL') . ', `AdvanceFees`=' . (($data['AdvanceFees'] !== '' && $data['AdvanceFees'] !== NULL) ? "'{$data['AdvanceFees']}'" : 'NULL') . ', `Balance`=' . (($data['Balance'] !== '' && $data['Balance'] !== NULL) ? "'{$data['Balance']}'" : 'NULL') . ', `Parent`=' . (($data['Parent'] !== '' && $data['Parent'] !== NULL) ? "'{$data['Parent']}'" : 'NULL') . " where `id`='".makeSafe($selected_id)."'", $o);
	if($o['error']!=''){
		echo $o['error'];
		echo '<a href="students_view.php?SelectedID='.urlencode($selected_id)."\">{$Translation['< back']}</a>";
		exit;
	}


	// hook: students_after_update
	if(function_exists('students_after_update')){
		$res = sql("SELECT * FROM `students` WHERE `id`='{$data['selectedID']}' LIMIT 1", $eo);
		if($row = db_fetch_assoc($res)){
			$data = array_map('makeSafe', $row);
		}
		$data['selectedID'] = $data['id'];
		$args = array();
		if(!students_after_update($data, getMemberInfo(), $args)){ return; }
	}

	// mm: update ownership data
	sql("update membership_userrecords set dateUpdated='".time()."' where tableName='students' and pkValue='".makeSafe($selected_id)."'", $eo);

}

function students_form($selected_id = '', $AllowUpdate = 1, $AllowInsert = 1, $AllowDelete = 1, $ShowCancel = 0, $TemplateDV = '', $TemplateDVP = ''){
	// function to return an editable form for a table records
	// and fill it with data of record whose ID is $selected_id. If $selected_id
	// is empty, an empty form is shown, with only an 'Add New'
	// button displayed.

	global $Translation;

	// mm: get table permissions
	$arrPerm=getTablePermissions('students');
	if(!$arrPerm[1] && $selected_id==''){ return ''; }
	$AllowInsert = ($arrPerm[1] ? true : false);
	// print preview?
	$dvprint = false;
	if($selected_id && $_REQUEST['dvprint_x'] != ''){
		$dvprint = true;
	}

	$filterer_Class = thisOr(undo_magic_quotes($_REQUEST['filterer_Class']), '');
	$filterer_Stream = thisOr(undo_magic_quotes($_REQUEST['filterer_Stream']), '');
	$filterer_Hostel = thisOr(undo_magic_quotes($_REQUEST['filterer_Hostel']), '');
	$filterer_Category = thisOr(undo_magic_quotes($_REQUEST['filterer_Category']), '');
	$filterer_AcademicYear = thisOr(undo_magic_quotes($_REQUEST['filterer_AcademicYear']), '');
	$filterer_TotalFees = thisOr(undo_magic_quotes($_REQUEST['filterer_TotalFees']), '');
	$filterer_Parent = thisOr(undo_magic_quotes($_REQUEST['filterer_Parent']), '');

	// populate filterers, starting from children to grand-parents
	if($filterer_TotalFees && !$filterer_Class) $filterer_Class = sqlValue("select Class from schoolmoney where id='" . makeSafe($filterer_TotalFees) . "'");

	// unique random identifier
	$rnd1 = ($dvprint ? rand(1000000, 9999999) : '');
	// combobox: Gender
	$combo_Gender = new Combo;
	$combo_Gender->ListType = 0;
	$combo_Gender->MultipleSeparator = ', ';
	$combo_Gender->ListBoxHeight = 10;
	$combo_Gender->RadiosPerLine = 1;
	if(is_file(dirname(__FILE__).'/hooks/students.Gender.csv')){
		$Gender_data = addslashes(implode('', @file(dirname(__FILE__).'/hooks/students.Gender.csv')));
		$combo_Gender->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($Gender_data)));
		$combo_Gender->ListData = $combo_Gender->ListItem;
	}else{
		$combo_Gender->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Male;;Female")));
		$combo_Gender->ListData = $combo_Gender->ListItem;
	}
	$combo_Gender->SelectName = 'Gender';
	$combo_Gender->AllowNull = false;
	// combobox: DOB
	$combo_DOB = new DateCombo;
	$combo_DOB->DateFormat = "mdy";
	$combo_DOB->MinYear = 1900;
	$combo_DOB->MaxYear = 2100;
	$combo_DOB->DefaultDate = parseMySQLDate('', '');
	$combo_DOB->MonthNames = $Translation['month names'];
	$combo_DOB->NamePrefix = 'DOB';
	// combobox: Class
	$combo_Class = new DataCombo;
	// combobox: Stream
	$combo_Stream = new DataCombo;
	// combobox: Hostel
	$combo_Hostel = new DataCombo;
	// combobox: DOJ
	$combo_DOJ = new DateCombo;
	$combo_DOJ->DateFormat = "mdy";
	$combo_DOJ->MinYear = 1900;
	$combo_DOJ->MaxYear = 2100;
	$combo_DOJ->DefaultDate = parseMySQLDate('1', '1');
	$combo_DOJ->MonthNames = $Translation['month names'];
	$combo_DOJ->NamePrefix = 'DOJ';
	// combobox: Category
	$combo_Category = new DataCombo;
	// combobox: AcademicYear
	$combo_AcademicYear = new DataCombo;
	// combobox: TotalFees, filterable by: Class
	$combo_TotalFees = new DataCombo;
	// combobox: Parent
	$combo_Parent = new DataCombo;

	if($selected_id){
		// mm: check member permissions
		if(!$arrPerm[2]){
			return "";
		}
		// mm: who is the owner?
		$ownerGroupID=sqlValue("select groupID from membership_userrecords where tableName='students' and pkValue='".makeSafe($selected_id)."'");
		$ownerMemberID=sqlValue("select lcase(memberID) from membership_userrecords where tableName='students' and pkValue='".makeSafe($selected_id)."'");
		if($arrPerm[2]==1 && getLoggedMemberID()!=$ownerMemberID){
			return "";
		}
		if($arrPerm[2]==2 && getLoggedGroupID()!=$ownerGroupID){
			return "";
		}

		// can edit?
		if(($arrPerm[3]==1 && $ownerMemberID==getLoggedMemberID()) || ($arrPerm[3]==2 && $ownerGroupID==getLoggedGroupID()) || $arrPerm[3]==3){
			$AllowUpdate=1;
		}else{
			$AllowUpdate=0;
		}

		$res = sql("select * from `students` where `id`='".makeSafe($selected_id)."'", $eo);
		if(!($row = db_fetch_array($res))){
			return error_message($Translation['No records found'], 'students_view.php', false);
		}
		$urow = $row; /* unsanitized data */
		$hc = new CI_Input();
		$row = $hc->xss_clean($row); /* sanitize data */
		$combo_Gender->SelectedData = $row['Gender'];
		$combo_DOB->DefaultDate = $row['DOB'];
		$combo_Class->SelectedData = $row['Class'];
		$combo_Stream->SelectedData = $row['Stream'];
		$combo_Hostel->SelectedData = $row['Hostel'];
		$combo_DOJ->DefaultDate = $row['DOJ'];
		$combo_Category->SelectedData = $row['Category'];
		$combo_AcademicYear->SelectedData = $row['AcademicYear'];
		$combo_TotalFees->SelectedData = $row['TotalFees'];
		$combo_Parent->SelectedData = $row['Parent'];
	}else{
		$combo_Gender->SelectedText = ( $_REQUEST['FilterField'][1]=='3' && $_REQUEST['FilterOperator'][1]=='<=>' ? (get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1]) : "");
		$combo_Class->SelectedData = $filterer_Class;
		$combo_Stream->SelectedData = $filterer_Stream;
		$combo_Hostel->SelectedData = $filterer_Hostel;
		$combo_Category->SelectedData = $filterer_Category;
		$combo_AcademicYear->SelectedData = $filterer_AcademicYear;
		$combo_TotalFees->SelectedData = $filterer_TotalFees;
		$combo_Parent->SelectedData = $filterer_Parent;
	}
	$combo_Gender->Render();
	$combo_Class->HTML = '<span id="Class-container' . $rnd1 . '"></span><input type="hidden" name="Class" id="Class' . $rnd1 . '" value="' . html_attr($combo_Class->SelectedData) . '">';
	$combo_Class->MatchText = '<span id="Class-container-readonly' . $rnd1 . '"></span><input type="hidden" name="Class" id="Class' . $rnd1 . '" value="' . html_attr($combo_Class->SelectedData) . '">';
	$combo_Stream->HTML = '<span id="Stream-container' . $rnd1 . '"></span><input type="hidden" name="Stream" id="Stream' . $rnd1 . '" value="' . html_attr($combo_Stream->SelectedData) . '">';
	$combo_Stream->MatchText = '<span id="Stream-container-readonly' . $rnd1 . '"></span><input type="hidden" name="Stream" id="Stream' . $rnd1 . '" value="' . html_attr($combo_Stream->SelectedData) . '">';
	$combo_Hostel->HTML = '<span id="Hostel-container' . $rnd1 . '"></span><input type="hidden" name="Hostel" id="Hostel' . $rnd1 . '" value="' . html_attr($combo_Hostel->SelectedData) . '">';
	$combo_Hostel->MatchText = '<span id="Hostel-container-readonly' . $rnd1 . '"></span><input type="hidden" name="Hostel" id="Hostel' . $rnd1 . '" value="' . html_attr($combo_Hostel->SelectedData) . '">';
	$combo_Category->HTML = '<span id="Category-container' . $rnd1 . '"></span><input type="hidden" name="Category" id="Category' . $rnd1 . '" value="' . html_attr($combo_Category->SelectedData) . '">';
	$combo_Category->MatchText = '<span id="Category-container-readonly' . $rnd1 . '"></span><input type="hidden" name="Category" id="Category' . $rnd1 . '" value="' . html_attr($combo_Category->SelectedData) . '">';
	$combo_AcademicYear->HTML = '<span id="AcademicYear-container' . $rnd1 . '"></span><input type="hidden" name="AcademicYear" id="AcademicYear' . $rnd1 . '" value="' . html_attr($combo_AcademicYear->SelectedData) . '">';
	$combo_AcademicYear->MatchText = '<span id="AcademicYear-container-readonly' . $rnd1 . '"></span><input type="hidden" name="AcademicYear" id="AcademicYear' . $rnd1 . '" value="' . html_attr($combo_AcademicYear->SelectedData) . '">';
	$combo_TotalFees->HTML = '<span id="TotalFees-container' . $rnd1 . '"></span><input type="hidden" name="TotalFees" id="TotalFees' . $rnd1 . '" value="' . html_attr($combo_TotalFees->SelectedData) . '">';
	$combo_TotalFees->MatchText = '<span id="TotalFees-container-readonly' . $rnd1 . '"></span><input type="hidden" name="TotalFees" id="TotalFees' . $rnd1 . '" value="' . html_attr($combo_TotalFees->SelectedData) . '">';
	$combo_Parent->HTML = '<span id="Parent-container' . $rnd1 . '"></span><input type="hidden" name="Parent" id="Parent' . $rnd1 . '" value="' . html_attr($combo_Parent->SelectedData) . '">';
	$combo_Parent->MatchText = '<span id="Parent-container-readonly' . $rnd1 . '"></span><input type="hidden" name="Parent" id="Parent' . $rnd1 . '" value="' . html_attr($combo_Parent->SelectedData) . '">';

	ob_start();
	?>

	<script>
		// initial lookup values
		AppGini.current_Class__RAND__ = { text: "", value: "<?php echo addslashes($selected_id ? $urow['Class'] : $filterer_Class); ?>"};
		AppGini.current_Stream__RAND__ = { text: "", value: "<?php echo addslashes($selected_id ? $urow['Stream'] : $filterer_Stream); ?>"};
		AppGini.current_Hostel__RAND__ = { text: "", value: "<?php echo addslashes($selected_id ? $urow['Hostel'] : $filterer_Hostel); ?>"};
		AppGini.current_Category__RAND__ = { text: "", value: "<?php echo addslashes($selected_id ? $urow['Category'] : $filterer_Category); ?>"};
		AppGini.current_AcademicYear__RAND__ = { text: "", value: "<?php echo addslashes($selected_id ? $urow['AcademicYear'] : $filterer_AcademicYear); ?>"};
		AppGini.current_TotalFees__RAND__ = { text: "", value: "<?php echo addslashes($selected_id ? $urow['TotalFees'] : $filterer_TotalFees); ?>"};
		AppGini.current_Parent__RAND__ = { text: "", value: "<?php echo addslashes($selected_id ? $urow['Parent'] : $filterer_Parent); ?>"};

		jQuery(function() {
			setTimeout(function(){
				if(typeof(Class_reload__RAND__) == 'function') Class_reload__RAND__();
				if(typeof(Stream_reload__RAND__) == 'function') Stream_reload__RAND__();
				if(typeof(Hostel_reload__RAND__) == 'function') Hostel_reload__RAND__();
				if(typeof(Category_reload__RAND__) == 'function') Category_reload__RAND__();
				if(typeof(AcademicYear_reload__RAND__) == 'function') AcademicYear_reload__RAND__();
				<?php echo (!$AllowUpdate || $dvprint ? 'if(typeof(TotalFees_reload__RAND__) == \'function\') TotalFees_reload__RAND__(AppGini.current_Class__RAND__.value);' : ''); ?>
				if(typeof(Parent_reload__RAND__) == 'function') Parent_reload__RAND__();
			}, 10); /* we need to slightly delay client-side execution of the above code to allow AppGini.ajaxCache to work */
		});
		function Class_reload__RAND__(){
		<?php if(($AllowUpdate || $AllowInsert) && !$dvprint){ ?>

			$j("#Class-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					$j.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: AppGini.current_Class__RAND__.value, t: 'students', f: 'Class' },
						success: function(resp){
							c({
								id: resp.results[0].id,
								text: resp.results[0].text
							});
							$j('[name="Class"]').val(resp.results[0].id);
							$j('[id=Class-container-readonly__RAND__]').html('<span id="Class-match-text">' + resp.results[0].text + '</span>');
							if(resp.results[0].id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=classes_view_parent]').hide(); }else{ $j('.btn[id=classes_view_parent]').show(); }

						if(typeof(TotalFees_reload__RAND__) == 'function') TotalFees_reload__RAND__(AppGini.current_Class__RAND__.value);

							if(typeof(Class_update_autofills__RAND__) == 'function') Class_update_autofills__RAND__();
						}
					});
				},
				width: '100%',
				formatNoMatches: function(term){ return '<?php echo addslashes($Translation['No matches found!']); ?>'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { s: term, p: page, t: 'students', f: 'Class' }; },
					results: function(resp, page){ return resp; }
				},
				escapeMarkup: function(str){ return str; }
			}).on('change', function(e){
				AppGini.current_Class__RAND__.value = e.added.id;
				AppGini.current_Class__RAND__.text = e.added.text;
				$j('[name="Class"]').val(e.added.id);
				if(e.added.id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=classes_view_parent]').hide(); }else{ $j('.btn[id=classes_view_parent]').show(); }

						if(typeof(TotalFees_reload__RAND__) == 'function') TotalFees_reload__RAND__(AppGini.current_Class__RAND__.value);

				if(typeof(Class_update_autofills__RAND__) == 'function') Class_update_autofills__RAND__();
			});

			if(!$j("#Class-container__RAND__").length){
				$j.ajax({
					url: 'ajax_combo.php',
					dataType: 'json',
					data: { id: AppGini.current_Class__RAND__.value, t: 'students', f: 'Class' },
					success: function(resp){
						$j('[name="Class"]').val(resp.results[0].id);
						$j('[id=Class-container-readonly__RAND__]').html('<span id="Class-match-text">' + resp.results[0].text + '</span>');
						if(resp.results[0].id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=classes_view_parent]').hide(); }else{ $j('.btn[id=classes_view_parent]').show(); }

						if(typeof(Class_update_autofills__RAND__) == 'function') Class_update_autofills__RAND__();
					}
				});
			}

		<?php }else{ ?>

			$j.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: AppGini.current_Class__RAND__.value, t: 'students', f: 'Class' },
				success: function(resp){
					$j('[id=Class-container__RAND__], [id=Class-container-readonly__RAND__]').html('<span id="Class-match-text">' + resp.results[0].text + '</span>');
					if(resp.results[0].id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=classes_view_parent]').hide(); }else{ $j('.btn[id=classes_view_parent]').show(); }

					if(typeof(Class_update_autofills__RAND__) == 'function') Class_update_autofills__RAND__();
				}
			});
		<?php } ?>

		}
		function Stream_reload__RAND__(){
		<?php if(($AllowUpdate || $AllowInsert) && !$dvprint){ ?>

			$j("#Stream-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					$j.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: AppGini.current_Stream__RAND__.value, t: 'students', f: 'Stream' },
						success: function(resp){
							c({
								id: resp.results[0].id,
								text: resp.results[0].text
							});
							$j('[name="Stream"]').val(resp.results[0].id);
							$j('[id=Stream-container-readonly__RAND__]').html('<span id="Stream-match-text">' + resp.results[0].text + '</span>');
							if(resp.results[0].id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=streams_view_parent]').hide(); }else{ $j('.btn[id=streams_view_parent]').show(); }


							if(typeof(Stream_update_autofills__RAND__) == 'function') Stream_update_autofills__RAND__();
						}
					});
				},
				width: '100%',
				formatNoMatches: function(term){ return '<?php echo addslashes($Translation['No matches found!']); ?>'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { s: term, p: page, t: 'students', f: 'Stream' }; },
					results: function(resp, page){ return resp; }
				},
				escapeMarkup: function(str){ return str; }
			}).on('change', function(e){
				AppGini.current_Stream__RAND__.value = e.added.id;
				AppGini.current_Stream__RAND__.text = e.added.text;
				$j('[name="Stream"]').val(e.added.id);
				if(e.added.id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=streams_view_parent]').hide(); }else{ $j('.btn[id=streams_view_parent]').show(); }


				if(typeof(Stream_update_autofills__RAND__) == 'function') Stream_update_autofills__RAND__();
			});

			if(!$j("#Stream-container__RAND__").length){
				$j.ajax({
					url: 'ajax_combo.php',
					dataType: 'json',
					data: { id: AppGini.current_Stream__RAND__.value, t: 'students', f: 'Stream' },
					success: function(resp){
						$j('[name="Stream"]').val(resp.results[0].id);
						$j('[id=Stream-container-readonly__RAND__]').html('<span id="Stream-match-text">' + resp.results[0].text + '</span>');
						if(resp.results[0].id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=streams_view_parent]').hide(); }else{ $j('.btn[id=streams_view_parent]').show(); }

						if(typeof(Stream_update_autofills__RAND__) == 'function') Stream_update_autofills__RAND__();
					}
				});
			}

		<?php }else{ ?>

			$j.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: AppGini.current_Stream__RAND__.value, t: 'students', f: 'Stream' },
				success: function(resp){
					$j('[id=Stream-container__RAND__], [id=Stream-container-readonly__RAND__]').html('<span id="Stream-match-text">' + resp.results[0].text + '</span>');
					if(resp.results[0].id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=streams_view_parent]').hide(); }else{ $j('.btn[id=streams_view_parent]').show(); }

					if(typeof(Stream_update_autofills__RAND__) == 'function') Stream_update_autofills__RAND__();
				}
			});
		<?php } ?>

		}
		function Hostel_reload__RAND__(){
		<?php if(($AllowUpdate || $AllowInsert) && !$dvprint){ ?>

			$j("#Hostel-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					$j.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: AppGini.current_Hostel__RAND__.value, t: 'students', f: 'Hostel' },
						success: function(resp){
							c({
								id: resp.results[0].id,
								text: resp.results[0].text
							});
							$j('[name="Hostel"]').val(resp.results[0].id);
							$j('[id=Hostel-container-readonly__RAND__]').html('<span id="Hostel-match-text">' + resp.results[0].text + '</span>');
							if(resp.results[0].id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=hostels_view_parent]').hide(); }else{ $j('.btn[id=hostels_view_parent]').show(); }


							if(typeof(Hostel_update_autofills__RAND__) == 'function') Hostel_update_autofills__RAND__();
						}
					});
				},
				width: '100%',
				formatNoMatches: function(term){ return '<?php echo addslashes($Translation['No matches found!']); ?>'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { s: term, p: page, t: 'students', f: 'Hostel' }; },
					results: function(resp, page){ return resp; }
				},
				escapeMarkup: function(str){ return str; }
			}).on('change', function(e){
				AppGini.current_Hostel__RAND__.value = e.added.id;
				AppGini.current_Hostel__RAND__.text = e.added.text;
				$j('[name="Hostel"]').val(e.added.id);
				if(e.added.id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=hostels_view_parent]').hide(); }else{ $j('.btn[id=hostels_view_parent]').show(); }


				if(typeof(Hostel_update_autofills__RAND__) == 'function') Hostel_update_autofills__RAND__();
			});

			if(!$j("#Hostel-container__RAND__").length){
				$j.ajax({
					url: 'ajax_combo.php',
					dataType: 'json',
					data: { id: AppGini.current_Hostel__RAND__.value, t: 'students', f: 'Hostel' },
					success: function(resp){
						$j('[name="Hostel"]').val(resp.results[0].id);
						$j('[id=Hostel-container-readonly__RAND__]').html('<span id="Hostel-match-text">' + resp.results[0].text + '</span>');
						if(resp.results[0].id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=hostels_view_parent]').hide(); }else{ $j('.btn[id=hostels_view_parent]').show(); }

						if(typeof(Hostel_update_autofills__RAND__) == 'function') Hostel_update_autofills__RAND__();
					}
				});
			}

		<?php }else{ ?>

			$j.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: AppGini.current_Hostel__RAND__.value, t: 'students', f: 'Hostel' },
				success: function(resp){
					$j('[id=Hostel-container__RAND__], [id=Hostel-container-readonly__RAND__]').html('<span id="Hostel-match-text">' + resp.results[0].text + '</span>');
					if(resp.results[0].id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=hostels_view_parent]').hide(); }else{ $j('.btn[id=hostels_view_parent]').show(); }

					if(typeof(Hostel_update_autofills__RAND__) == 'function') Hostel_update_autofills__RAND__();
				}
			});
		<?php } ?>

		}
		function Category_reload__RAND__(){
		<?php if(($AllowUpdate || $AllowInsert) && !$dvprint){ ?>

			$j("#Category-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					$j.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: AppGini.current_Category__RAND__.value, t: 'students', f: 'Category' },
						success: function(resp){
							c({
								id: resp.results[0].id,
								text: resp.results[0].text
							});
							$j('[name="Category"]').val(resp.results[0].id);
							$j('[id=Category-container-readonly__RAND__]').html('<span id="Category-match-text">' + resp.results[0].text + '</span>');
							if(resp.results[0].id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=studentcategories_view_parent]').hide(); }else{ $j('.btn[id=studentcategories_view_parent]').show(); }


							if(typeof(Category_update_autofills__RAND__) == 'function') Category_update_autofills__RAND__();
						}
					});
				},
				width: '100%',
				formatNoMatches: function(term){ return '<?php echo addslashes($Translation['No matches found!']); ?>'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { s: term, p: page, t: 'students', f: 'Category' }; },
					results: function(resp, page){ return resp; }
				},
				escapeMarkup: function(str){ return str; }
			}).on('change', function(e){
				AppGini.current_Category__RAND__.value = e.added.id;
				AppGini.current_Category__RAND__.text = e.added.text;
				$j('[name="Category"]').val(e.added.id);
				if(e.added.id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=studentcategories_view_parent]').hide(); }else{ $j('.btn[id=studentcategories_view_parent]').show(); }


				if(typeof(Category_update_autofills__RAND__) == 'function') Category_update_autofills__RAND__();
			});

			if(!$j("#Category-container__RAND__").length){
				$j.ajax({
					url: 'ajax_combo.php',
					dataType: 'json',
					data: { id: AppGini.current_Category__RAND__.value, t: 'students', f: 'Category' },
					success: function(resp){
						$j('[name="Category"]').val(resp.results[0].id);
						$j('[id=Category-container-readonly__RAND__]').html('<span id="Category-match-text">' + resp.results[0].text + '</span>');
						if(resp.results[0].id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=studentcategories_view_parent]').hide(); }else{ $j('.btn[id=studentcategories_view_parent]').show(); }

						if(typeof(Category_update_autofills__RAND__) == 'function') Category_update_autofills__RAND__();
					}
				});
			}

		<?php }else{ ?>

			$j.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: AppGini.current_Category__RAND__.value, t: 'students', f: 'Category' },
				success: function(resp){
					$j('[id=Category-container__RAND__], [id=Category-container-readonly__RAND__]').html('<span id="Category-match-text">' + resp.results[0].text + '</span>');
					if(resp.results[0].id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=studentcategories_view_parent]').hide(); }else{ $j('.btn[id=studentcategories_view_parent]').show(); }

					if(typeof(Category_update_autofills__RAND__) == 'function') Category_update_autofills__RAND__();
				}
			});
		<?php } ?>

		}
		function AcademicYear_reload__RAND__(){
		<?php if(($AllowUpdate || $AllowInsert) && !$dvprint){ ?>

			$j("#AcademicYear-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					$j.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: AppGini.current_AcademicYear__RAND__.value, t: 'students', f: 'AcademicYear' },
						success: function(resp){
							c({
								id: resp.results[0].id,
								text: resp.results[0].text
							});
							$j('[name="AcademicYear"]').val(resp.results[0].id);
							$j('[id=AcademicYear-container-readonly__RAND__]').html('<span id="AcademicYear-match-text">' + resp.results[0].text + '</span>');
							if(resp.results[0].id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=sessions_view_parent]').hide(); }else{ $j('.btn[id=sessions_view_parent]').show(); }


							if(typeof(AcademicYear_update_autofills__RAND__) == 'function') AcademicYear_update_autofills__RAND__();
						}
					});
				},
				width: '100%',
				formatNoMatches: function(term){ return '<?php echo addslashes($Translation['No matches found!']); ?>'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { s: term, p: page, t: 'students', f: 'AcademicYear' }; },
					results: function(resp, page){ return resp; }
				},
				escapeMarkup: function(str){ return str; }
			}).on('change', function(e){
				AppGini.current_AcademicYear__RAND__.value = e.added.id;
				AppGini.current_AcademicYear__RAND__.text = e.added.text;
				$j('[name="AcademicYear"]').val(e.added.id);
				if(e.added.id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=sessions_view_parent]').hide(); }else{ $j('.btn[id=sessions_view_parent]').show(); }


				if(typeof(AcademicYear_update_autofills__RAND__) == 'function') AcademicYear_update_autofills__RAND__();
			});

			if(!$j("#AcademicYear-container__RAND__").length){
				$j.ajax({
					url: 'ajax_combo.php',
					dataType: 'json',
					data: { id: AppGini.current_AcademicYear__RAND__.value, t: 'students', f: 'AcademicYear' },
					success: function(resp){
						$j('[name="AcademicYear"]').val(resp.results[0].id);
						$j('[id=AcademicYear-container-readonly__RAND__]').html('<span id="AcademicYear-match-text">' + resp.results[0].text + '</span>');
						if(resp.results[0].id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=sessions_view_parent]').hide(); }else{ $j('.btn[id=sessions_view_parent]').show(); }

						if(typeof(AcademicYear_update_autofills__RAND__) == 'function') AcademicYear_update_autofills__RAND__();
					}
				});
			}

		<?php }else{ ?>

			$j.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: AppGini.current_AcademicYear__RAND__.value, t: 'students', f: 'AcademicYear' },
				success: function(resp){
					$j('[id=AcademicYear-container__RAND__], [id=AcademicYear-container-readonly__RAND__]').html('<span id="AcademicYear-match-text">' + resp.results[0].text + '</span>');
					if(resp.results[0].id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=sessions_view_parent]').hide(); }else{ $j('.btn[id=sessions_view_parent]').show(); }

					if(typeof(AcademicYear_update_autofills__RAND__) == 'function') AcademicYear_update_autofills__RAND__();
				}
			});
		<?php } ?>

		}
		function TotalFees_reload__RAND__(filterer_Class){
		<?php if(($AllowUpdate || $AllowInsert) && !$dvprint){ ?>

			$j("#TotalFees-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					$j.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { filterer_Class: filterer_Class, id: AppGini.current_TotalFees__RAND__.value, t: 'students', f: 'TotalFees' },
						success: function(resp){
							c({
								id: resp.results[0].id,
								text: resp.results[0].text
							});
							$j('[name="TotalFees"]').val(resp.results[0].id);
							$j('[id=TotalFees-container-readonly__RAND__]').html('<span id="TotalFees-match-text">' + resp.results[0].text + '</span>');
							if(resp.results[0].id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=schoolmoney_view_parent]').hide(); }else{ $j('.btn[id=schoolmoney_view_parent]').show(); }


							if(typeof(TotalFees_update_autofills__RAND__) == 'function') TotalFees_update_autofills__RAND__();
						}
					});
				},
				width: '100%',
				formatNoMatches: function(term){ return '<?php echo addslashes($Translation['No matches found!']); ?>'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { filterer_Class: filterer_Class, s: term, p: page, t: 'students', f: 'TotalFees' }; },
					results: function(resp, page){ return resp; }
				},
				escapeMarkup: function(str){ return str; }
			}).on('change', function(e){
				AppGini.current_TotalFees__RAND__.value = e.added.id;
				AppGini.current_TotalFees__RAND__.text = e.added.text;
				$j('[name="TotalFees"]').val(e.added.id);
				if(e.added.id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=schoolmoney_view_parent]').hide(); }else{ $j('.btn[id=schoolmoney_view_parent]').show(); }


				if(typeof(TotalFees_update_autofills__RAND__) == 'function') TotalFees_update_autofills__RAND__();
			});

			if(!$j("#TotalFees-container__RAND__").length){
				$j.ajax({
					url: 'ajax_combo.php',
					dataType: 'json',
					data: { id: AppGini.current_TotalFees__RAND__.value, t: 'students', f: 'TotalFees' },
					success: function(resp){
						$j('[name="TotalFees"]').val(resp.results[0].id);
						$j('[id=TotalFees-container-readonly__RAND__]').html('<span id="TotalFees-match-text">' + resp.results[0].text + '</span>');
						if(resp.results[0].id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=schoolmoney_view_parent]').hide(); }else{ $j('.btn[id=schoolmoney_view_parent]').show(); }

						if(typeof(TotalFees_update_autofills__RAND__) == 'function') TotalFees_update_autofills__RAND__();
					}
				});
			}

		<?php }else{ ?>

			$j.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: AppGini.current_TotalFees__RAND__.value, t: 'students', f: 'TotalFees' },
				success: function(resp){
					$j('[id=TotalFees-container__RAND__], [id=TotalFees-container-readonly__RAND__]').html('<span id="TotalFees-match-text">' + resp.results[0].text + '</span>');
					if(resp.results[0].id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=schoolmoney_view_parent]').hide(); }else{ $j('.btn[id=schoolmoney_view_parent]').show(); }

					if(typeof(TotalFees_update_autofills__RAND__) == 'function') TotalFees_update_autofills__RAND__();
				}
			});
		<?php } ?>

		}
		function Parent_reload__RAND__(){
		<?php if(($AllowUpdate || $AllowInsert) && !$dvprint){ ?>

			$j("#Parent-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					$j.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: AppGini.current_Parent__RAND__.value, t: 'students', f: 'Parent' },
						success: function(resp){
							c({
								id: resp.results[0].id,
								text: resp.results[0].text
							});
							$j('[name="Parent"]').val(resp.results[0].id);
							$j('[id=Parent-container-readonly__RAND__]').html('<span id="Parent-match-text">' + resp.results[0].text + '</span>');
							if(resp.results[0].id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=parents_view_parent]').hide(); }else{ $j('.btn[id=parents_view_parent]').show(); }


							if(typeof(Parent_update_autofills__RAND__) == 'function') Parent_update_autofills__RAND__();
						}
					});
				},
				width: '100%',
				formatNoMatches: function(term){ return '<?php echo addslashes($Translation['No matches found!']); ?>'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { s: term, p: page, t: 'students', f: 'Parent' }; },
					results: function(resp, page){ return resp; }
				},
				escapeMarkup: function(str){ return str; }
			}).on('change', function(e){
				AppGini.current_Parent__RAND__.value = e.added.id;
				AppGini.current_Parent__RAND__.text = e.added.text;
				$j('[name="Parent"]').val(e.added.id);
				if(e.added.id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=parents_view_parent]').hide(); }else{ $j('.btn[id=parents_view_parent]').show(); }


				if(typeof(Parent_update_autofills__RAND__) == 'function') Parent_update_autofills__RAND__();
			});

			if(!$j("#Parent-container__RAND__").length){
				$j.ajax({
					url: 'ajax_combo.php',
					dataType: 'json',
					data: { id: AppGini.current_Parent__RAND__.value, t: 'students', f: 'Parent' },
					success: function(resp){
						$j('[name="Parent"]').val(resp.results[0].id);
						$j('[id=Parent-container-readonly__RAND__]').html('<span id="Parent-match-text">' + resp.results[0].text + '</span>');
						if(resp.results[0].id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=parents_view_parent]').hide(); }else{ $j('.btn[id=parents_view_parent]').show(); }

						if(typeof(Parent_update_autofills__RAND__) == 'function') Parent_update_autofills__RAND__();
					}
				});
			}

		<?php }else{ ?>

			$j.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: AppGini.current_Parent__RAND__.value, t: 'students', f: 'Parent' },
				success: function(resp){
					$j('[id=Parent-container__RAND__], [id=Parent-container-readonly__RAND__]').html('<span id="Parent-match-text">' + resp.results[0].text + '</span>');
					if(resp.results[0].id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=parents_view_parent]').hide(); }else{ $j('.btn[id=parents_view_parent]').show(); }

					if(typeof(Parent_update_autofills__RAND__) == 'function') Parent_update_autofills__RAND__();
				}
			});
		<?php } ?>

		}
	</script>
	<?php

	$lookups = str_replace('__RAND__', $rnd1, ob_get_contents());
	ob_end_clean();


	// code for template based detail view forms

	// open the detail view template
	if($dvprint){
		$template_file = is_file("./{$TemplateDVP}") ? "./{$TemplateDVP}" : './templates/students_templateDVP.html';
		$templateCode = @file_get_contents($template_file);
	}else{
		$template_file = is_file("./{$TemplateDV}") ? "./{$TemplateDV}" : './templates/students_templateDV.html';
		$templateCode = @file_get_contents($template_file);
	}

	// process form title
	$templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Student details', $templateCode);
	$templateCode = str_replace('<%%RND1%%>', $rnd1, $templateCode);
	$templateCode = str_replace('<%%EMBEDDED%%>', ($_REQUEST['Embedded'] ? 'Embedded=1' : ''), $templateCode);
	// process buttons
	if($arrPerm[1] && !$selected_id){ // allow insert and no record selected?
		if(!$selected_id) $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-success" id="insert" name="insert_x" value="1" onclick="return students_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save New'] . '</button>', $templateCode);
		$templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="insert" name="insert_x" value="1" onclick="return students_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save As Copy'] . '</button>', $templateCode);
	}else{
		$templateCode = str_replace('<%%INSERT_BUTTON%%>', '', $templateCode);
	}

	// 'Back' button action
	if($_REQUEST['Embedded']){
		$backAction = 'AppGini.closeParentModal(); return false;';
	}else{
		$backAction = '$j(\'form\').eq(0).attr(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;';
	}

	if($selected_id){
		if(!$_REQUEST['Embedded']) $templateCode = str_replace('<%%DVPRINT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="dvprint" name="dvprint_x" value="1" onclick="$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;" title="' . html_attr($Translation['Print Preview']) . '"><i class="glyphicon glyphicon-print"></i> ' . $Translation['Print Preview'] . '</button>', $templateCode);
		if($AllowUpdate){
			$templateCode = str_replace('<%%UPDATE_BUTTON%%>', '<button type="submit" class="btn btn-success btn-lg" id="update" name="update_x" value="1" onclick="return students_validateData();" title="' . html_attr($Translation['Save Changes']) . '"><i class="glyphicon glyphicon-ok"></i> ' . $Translation['Save Changes'] . '</button>', $templateCode);
		}else{
			$templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
		}
		if(($arrPerm[4]==1 && $ownerMemberID==getLoggedMemberID()) || ($arrPerm[4]==2 && $ownerGroupID==getLoggedGroupID()) || $arrPerm[4]==3){ // allow delete?
			$templateCode = str_replace('<%%DELETE_BUTTON%%>', '<button type="submit" class="btn btn-danger" id="delete" name="delete_x" value="1" onclick="return confirm(\'' . $Translation['are you sure?'] . '\');" title="' . html_attr($Translation['Delete']) . '"><i class="glyphicon glyphicon-trash"></i> ' . $Translation['Delete'] . '</button>', $templateCode);
		}else{
			$templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
		}
		$templateCode = str_replace('<%%DESELECT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '" title="' . html_attr($Translation['Back']) . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>', $templateCode);
	}else{
		$templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
		$templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
		$templateCode = str_replace('<%%DESELECT_BUTTON%%>', ($ShowCancel ? '<button type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '" title="' . html_attr($Translation['Back']) . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>' : ''), $templateCode);
	}

	// set records to read only if user can't insert new records and can't edit current record
	if(($selected_id && !$AllowUpdate) || (!$selected_id && !$AllowInsert)){
		$jsReadOnly .= "\tjQuery('#FullName').replaceWith('<div class=\"form-control-static\" id=\"FullName\">' + (jQuery('#FullName').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#Gender').replaceWith('<div class=\"form-control-static\" id=\"Gender\">' + (jQuery('#Gender').val() || '') + '</div>'); jQuery('#Gender-multi-selection-help').hide();\n";
		$jsReadOnly .= "\tjQuery('#DOB').prop('readonly', true);\n";
		$jsReadOnly .= "\tjQuery('#DOBDay, #DOBMonth, #DOBYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\tjQuery('#Photo').replaceWith('<div class=\"form-control-static\" id=\"Photo\">' + (jQuery('#Photo').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#RegNo').replaceWith('<div class=\"form-control-static\" id=\"RegNo\">' + (jQuery('#RegNo').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#Class').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\tjQuery('#Class_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
		$jsReadOnly .= "\tjQuery('#Stream').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\tjQuery('#Stream_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
		$jsReadOnly .= "\tjQuery('#Hostel').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\tjQuery('#Hostel_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
		$jsReadOnly .= "\tjQuery('#DOJ').prop('readonly', true);\n";
		$jsReadOnly .= "\tjQuery('#DOJDay, #DOJMonth, #DOJYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\tjQuery('#Category').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\tjQuery('#Category_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
		$jsReadOnly .= "\tjQuery('#AcademicYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\tjQuery('#AcademicYear_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
		$jsReadOnly .= "\tjQuery('#TotalFees').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\tjQuery('#TotalFees_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
		$jsReadOnly .= "\tjQuery('#AdvanceFees').replaceWith('<div class=\"form-control-static\" id=\"AdvanceFees\">' + (jQuery('#AdvanceFees').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#Balance').replaceWith('<div class=\"form-control-static\" id=\"Balance\">' + (jQuery('#Balance').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#Parent').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\tjQuery('#Parent_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
		$jsReadOnly .= "\tjQuery('.select2-container').hide();\n";

		$noUploads = true;
	}elseif(($AllowInsert && !$selected_id) || ($AllowUpdate && $selected_id)){
		$jsEditable .= "\tjQuery('form').eq(0).data('already_changed', true);"; // temporarily disable form change handler
			$jsEditable .= "\tjQuery('form').eq(0).data('already_changed', false);"; // re-enable form change handler
	}

	// process combos
	$templateCode = str_replace('<%%COMBO(Gender)%%>', $combo_Gender->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(Gender)%%>', $combo_Gender->SelectedData, $templateCode);
	$templateCode = str_replace('<%%COMBO(DOB)%%>', ($selected_id && !$arrPerm[3] ? '<div class="form-control-static">' . $combo_DOB->GetHTML(true) . '</div>' : $combo_DOB->GetHTML()), $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(DOB)%%>', $combo_DOB->GetHTML(true), $templateCode);
	$templateCode = str_replace('<%%COMBO(Class)%%>', $combo_Class->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(Class)%%>', $combo_Class->MatchText, $templateCode);
	$templateCode = str_replace('<%%URLCOMBOTEXT(Class)%%>', urlencode($combo_Class->MatchText), $templateCode);
	$templateCode = str_replace('<%%COMBO(Stream)%%>', $combo_Stream->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(Stream)%%>', $combo_Stream->MatchText, $templateCode);
	$templateCode = str_replace('<%%URLCOMBOTEXT(Stream)%%>', urlencode($combo_Stream->MatchText), $templateCode);
	$templateCode = str_replace('<%%COMBO(Hostel)%%>', $combo_Hostel->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(Hostel)%%>', $combo_Hostel->MatchText, $templateCode);
	$templateCode = str_replace('<%%URLCOMBOTEXT(Hostel)%%>', urlencode($combo_Hostel->MatchText), $templateCode);
	$templateCode = str_replace('<%%COMBO(DOJ)%%>', ($selected_id && !$arrPerm[3] ? '<div class="form-control-static">' . $combo_DOJ->GetHTML(true) . '</div>' : $combo_DOJ->GetHTML()), $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(DOJ)%%>', $combo_DOJ->GetHTML(true), $templateCode);
	$templateCode = str_replace('<%%COMBO(Category)%%>', $combo_Category->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(Category)%%>', $combo_Category->MatchText, $templateCode);
	$templateCode = str_replace('<%%URLCOMBOTEXT(Category)%%>', urlencode($combo_Category->MatchText), $templateCode);
	$templateCode = str_replace('<%%COMBO(AcademicYear)%%>', $combo_AcademicYear->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(AcademicYear)%%>', $combo_AcademicYear->MatchText, $templateCode);
	$templateCode = str_replace('<%%URLCOMBOTEXT(AcademicYear)%%>', urlencode($combo_AcademicYear->MatchText), $templateCode);
	$templateCode = str_replace('<%%COMBO(TotalFees)%%>', $combo_TotalFees->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(TotalFees)%%>', $combo_TotalFees->MatchText, $templateCode);
	$templateCode = str_replace('<%%URLCOMBOTEXT(TotalFees)%%>', urlencode($combo_TotalFees->MatchText), $templateCode);
	$templateCode = str_replace('<%%COMBO(Parent)%%>', $combo_Parent->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(Parent)%%>', $combo_Parent->MatchText, $templateCode);
	$templateCode = str_replace('<%%URLCOMBOTEXT(Parent)%%>', urlencode($combo_Parent->MatchText), $templateCode);

	/* lookup fields array: 'lookup field name' => array('parent table name', 'lookup field caption') */
	$lookup_fields = array(  'Class' => array('classes', 'Class'), 'Stream' => array('streams', 'Stream'), 'Hostel' => array('hostels', 'Hostel'), 'Category' => array('studentcategories', 'Category'), 'AcademicYear' => array('sessions', 'AcademicYear'), 'TotalFees' => array('schoolmoney', 'TotalFees'), 'Parent' => array('parents', 'Parent'));
	foreach($lookup_fields as $luf => $ptfc){
		$pt_perm = getTablePermissions($ptfc[0]);

		// process foreign key links
		if($pt_perm['view'] || $pt_perm['edit']){
			$templateCode = str_replace("<%%PLINK({$luf})%%>", '<button type="button" class="btn btn-default view_parent hspacer-md" id="' . $ptfc[0] . '_view_parent" title="' . html_attr($Translation['View'] . ' ' . $ptfc[1]) . '"><i class="glyphicon glyphicon-eye-open"></i></button>', $templateCode);
		}

		// if user has insert permission to parent table of a lookup field, put an add new button
		if($pt_perm['insert'] && !$_REQUEST['Embedded']){
			$templateCode = str_replace("<%%ADDNEW({$ptfc[0]})%%>", '<button type="button" class="btn btn-success add_new_parent hspacer-md" id="' . $ptfc[0] . '_add_new" title="' . html_attr($Translation['Add New'] . ' ' . $ptfc[1]) . '"><i class="glyphicon glyphicon-plus-sign"></i></button>', $templateCode);
		}
	}

	// process images
	$templateCode = str_replace('<%%UPLOADFILE(id)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(FullName)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(Gender)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(DOB)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(Photo)%%>', ($noUploads ? '' : '<input type=hidden name=MAX_FILE_SIZE value=5120000>'.$Translation['upload image'].' <input type="file" name="Photo" id="Photo">'), $templateCode);
	if($AllowUpdate && $row['Photo'] != ''){
		$templateCode = str_replace('<%%REMOVEFILE(Photo)%%>', '<br><input type="checkbox" name="Photo_remove" id="Photo_remove" value="1"> <label for="Photo_remove" style="color: red; font-weight: bold;">'.$Translation['remove image'].'</label>', $templateCode);
	}else{
		$templateCode = str_replace('<%%REMOVEFILE(Photo)%%>', '', $templateCode);
	}
	$templateCode = str_replace('<%%UPLOADFILE(RegNo)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(Class)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(Stream)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(Hostel)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(DOJ)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(Category)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(AcademicYear)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(TotalFees)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(AdvanceFees)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(Balance)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(Parent)%%>', '', $templateCode);

	// process values
	if($selected_id){
		if( $dvprint) $templateCode = str_replace('<%%VALUE(id)%%>', safe_html($urow['id']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(id)%%>', html_attr($row['id']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(id)%%>', urlencode($urow['id']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(FullName)%%>', safe_html($urow['FullName']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(FullName)%%>', html_attr($row['FullName']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(FullName)%%>', urlencode($urow['FullName']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(Gender)%%>', safe_html($urow['Gender']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(Gender)%%>', html_attr($row['Gender']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Gender)%%>', urlencode($urow['Gender']), $templateCode);
		$templateCode = str_replace('<%%VALUE(DOB)%%>', @date('m/d/Y', @strtotime(html_attr($row['DOB']))), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(DOB)%%>', urlencode(@date('m/d/Y', @strtotime(html_attr($urow['DOB'])))), $templateCode);
		$row['Photo'] = ($row['Photo'] != '' ? $row['Photo'] : 'blank.gif');
		if( $dvprint) $templateCode = str_replace('<%%VALUE(Photo)%%>', safe_html($urow['Photo']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(Photo)%%>', html_attr($row['Photo']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Photo)%%>', urlencode($urow['Photo']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(RegNo)%%>', safe_html($urow['RegNo']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(RegNo)%%>', html_attr($row['RegNo']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(RegNo)%%>', urlencode($urow['RegNo']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(Class)%%>', safe_html($urow['Class']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(Class)%%>', html_attr($row['Class']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Class)%%>', urlencode($urow['Class']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(Stream)%%>', safe_html($urow['Stream']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(Stream)%%>', html_attr($row['Stream']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Stream)%%>', urlencode($urow['Stream']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(Hostel)%%>', safe_html($urow['Hostel']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(Hostel)%%>', html_attr($row['Hostel']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Hostel)%%>', urlencode($urow['Hostel']), $templateCode);
		$templateCode = str_replace('<%%VALUE(DOJ)%%>', @date('m/d/Y', @strtotime(html_attr($row['DOJ']))), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(DOJ)%%>', urlencode(@date('m/d/Y', @strtotime(html_attr($urow['DOJ'])))), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(Category)%%>', safe_html($urow['Category']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(Category)%%>', html_attr($row['Category']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Category)%%>', urlencode($urow['Category']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(AcademicYear)%%>', safe_html($urow['AcademicYear']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(AcademicYear)%%>', html_attr($row['AcademicYear']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(AcademicYear)%%>', urlencode($urow['AcademicYear']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(TotalFees)%%>', safe_html($urow['TotalFees']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(TotalFees)%%>', html_attr($row['TotalFees']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(TotalFees)%%>', urlencode($urow['TotalFees']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(AdvanceFees)%%>', safe_html($urow['AdvanceFees']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(AdvanceFees)%%>', html_attr($row['AdvanceFees']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(AdvanceFees)%%>', urlencode($urow['AdvanceFees']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(Balance)%%>', safe_html($urow['Balance']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(Balance)%%>', html_attr($row['Balance']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Balance)%%>', urlencode($urow['Balance']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(Parent)%%>', safe_html($urow['Parent']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(Parent)%%>', html_attr($row['Parent']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Parent)%%>', urlencode($urow['Parent']), $templateCode);
	}else{
		$templateCode = str_replace('<%%VALUE(id)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(id)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(FullName)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(FullName)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(Gender)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Gender)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(DOB)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(DOB)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(Photo)%%>', 'blank.gif', $templateCode);
		$templateCode = str_replace('<%%VALUE(RegNo)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(RegNo)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(Class)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Class)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(Stream)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Stream)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(Hostel)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Hostel)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(DOJ)%%>', '1', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(DOJ)%%>', urlencode('1'), $templateCode);
		$templateCode = str_replace('<%%VALUE(Category)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Category)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(AcademicYear)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(AcademicYear)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(TotalFees)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(TotalFees)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(AdvanceFees)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(AdvanceFees)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(Balance)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Balance)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(Parent)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Parent)%%>', urlencode(''), $templateCode);
	}

	// process translations
	foreach($Translation as $symbol=>$trans){
		$templateCode = str_replace("<%%TRANSLATION($symbol)%%>", $trans, $templateCode);
	}

	// clear scrap
	$templateCode = str_replace('<%%', '<!-- ', $templateCode);
	$templateCode = str_replace('%%>', ' -->', $templateCode);

	// hide links to inaccessible tables
	if($_REQUEST['dvprint_x'] == ''){
		$templateCode .= "\n\n<script>\$j(function(){\n";
		$arrTables = getTableList();
		foreach($arrTables as $name => $caption){
			$templateCode .= "\t\$j('#{$name}_link').removeClass('hidden');\n";
			$templateCode .= "\t\$j('#xs_{$name}_link').removeClass('hidden');\n";
		}

		$templateCode .= $jsReadOnly;
		$templateCode .= $jsEditable;

		if(!$selected_id){
		}

		$templateCode.="\n});</script>\n";
	}

	// ajaxed auto-fill fields
	$templateCode .= '<script>';
	$templateCode .= '$j(function() {';


	$templateCode.="});";
	$templateCode.="</script>";
	$templateCode .= $lookups;

	// handle enforced parent values for read-only lookup fields

	// don't include blank images in lightbox gallery
	$templateCode = preg_replace('/blank.gif" data-lightbox=".*?"/', 'blank.gif"', $templateCode);

	// don't display empty email links
	$templateCode=preg_replace('/<a .*?href="mailto:".*?<\/a>/', '', $templateCode);

	/* default field values */
	$rdata = $jdata = get_defaults('students');
	if($selected_id){
		$jdata = get_joined_record('students', $selected_id);
		if($jdata === false) $jdata = get_defaults('students');
		$rdata = $row;
	}
	$cache_data = array(
		'rdata' => array_map('nl2br', array_map('addslashes', $rdata)),
		'jdata' => array_map('nl2br', array_map('addslashes', $jdata))
	);
	$templateCode .= loadView('students-ajax-cache', $cache_data);

	// hook: students_dv
	if(function_exists('students_dv')){
		$args=array();
		students_dv(($selected_id ? $selected_id : FALSE), getMemberInfo(), $templateCode, $args);
	}

	return $templateCode;
}
?>