<?php

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

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

function patients_insert(){
	global $Translation;

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

	$data['last_name'] = makeSafe($_REQUEST['last_name']);
		if($data['last_name'] == empty_lookup_value){ $data['last_name'] = ''; }
	$data['first_name'] = makeSafe($_REQUEST['first_name']);
		if($data['first_name'] == empty_lookup_value){ $data['first_name'] = ''; }
	$data['gender'] = makeSafe($_REQUEST['gender']);
		if($data['gender'] == empty_lookup_value){ $data['gender'] = ''; }
	$data['sexual_orientation'] = makeSafe($_REQUEST['sexual_orientation']);
		if($data['sexual_orientation'] == empty_lookup_value){ $data['sexual_orientation'] = ''; }
	$data['birth_date'] = intval($_REQUEST['birth_dateYear']) . '-' . intval($_REQUEST['birth_dateMonth']) . '-' . intval($_REQUEST['birth_dateDay']);
	$data['birth_date'] = parseMySQLDate($data['birth_date'], '');
	$data['address'] = br2nl(makeSafe($_REQUEST['address']));
	$data['city'] = makeSafe($_REQUEST['city']);
		if($data['city'] == empty_lookup_value){ $data['city'] = ''; }
	$data['state'] = makeSafe($_REQUEST['state']);
		if($data['state'] == empty_lookup_value){ $data['state'] = ''; }
	$data['zip'] = makeSafe($_REQUEST['zip']);
		if($data['zip'] == empty_lookup_value){ $data['zip'] = ''; }
	$data['home_phone'] = makeSafe($_REQUEST['home_phone']);
		if($data['home_phone'] == empty_lookup_value){ $data['home_phone'] = ''; }
	$data['work_phone'] = makeSafe($_REQUEST['work_phone']);
		if($data['work_phone'] == empty_lookup_value){ $data['work_phone'] = ''; }
	$data['mobile'] = makeSafe($_REQUEST['mobile']);
		if($data['mobile'] == empty_lookup_value){ $data['mobile'] = ''; }
	$data['tobacco_usage'] = makeSafe($_REQUEST['tobacco_usage']);
		if($data['tobacco_usage'] == empty_lookup_value){ $data['tobacco_usage'] = ''; }
	$data['alcohol_intake'] = makeSafe($_REQUEST['alcohol_intake']);
		if($data['alcohol_intake'] == empty_lookup_value){ $data['alcohol_intake'] = ''; }
	$data['history'] = makeSafe($_REQUEST['history']);
		if($data['history'] == empty_lookup_value){ $data['history'] = ''; }
	$data['surgical_history'] = br2nl(makeSafe($_REQUEST['surgical_history']));
	$data['obstetric_history'] = br2nl(makeSafe($_REQUEST['obstetric_history']));
	$data['genetic_diseases'] = br2nl(makeSafe($_REQUEST['genetic_diseases']));
	$data['contact_person'] = makeSafe($_REQUEST['contact_person']);
		if($data['contact_person'] == empty_lookup_value){ $data['contact_person'] = ''; }
	$data['other_details'] = br2nl(makeSafe($_REQUEST['other_details']));
	$data['comments'] = makeSafe($_REQUEST['comments']);
		if($data['comments'] == empty_lookup_value){ $data['comments'] = ''; }
	$data['filed'] = parseCode('<%%creationDateTime%%>', true, true);
	$data['image'] = PrepareUploadedFile('image', 1024000,'jpg|jpeg|gif|png', false, '');
	if($data['image']) createThumbnail($data['image'], getThumbnailSpecs('patients', 'image', 'tv'));
	if($data['image']) createThumbnail($data['image'], getThumbnailSpecs('patients', 'image', 'dv'));
	if($data['last_name']== ''){
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">" . $Translation['error:'] . " 'Last name': " . $Translation['field not null'] . '<br><br>';
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}
	if($data['first_name']== ''){
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">" . $Translation['error:'] . " 'First name': " . $Translation['field not null'] . '<br><br>';
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}
	if($data['gender'] == '') $data['gender'] = "Unknown";
	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['sexual_orientation'] == '') $data['sexual_orientation'] = "Unknown";
	if($data['sexual_orientation']== ''){
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">" . $Translation['error:'] . " 'Sexual orientation': " . $Translation['field not null'] . '<br><br>';
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}
	if($data['tobacco_usage'] == '') $data['tobacco_usage'] = "Unknown";
	if($data['tobacco_usage']== ''){
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">" . $Translation['error:'] . " 'Tobacco usage': " . $Translation['field not null'] . '<br><br>';
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}
	if($data['alcohol_intake'] == '') $data['alcohol_intake'] = "Unknown";
	if($data['alcohol_intake']== ''){
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">" . $Translation['error:'] . " 'Alcohol Intake': " . $Translation['field not null'] . '<br><br>';
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}
	if($data['history'] == '') $data['history'] = "Unknown";
	if($data['history']== ''){
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">" . $Translation['error:'] . " 'History': " . $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 patients where id='" . makeSafe($_REQUEST['SelectedID']) . "'", $eo);
		if($row = db_fetch_assoc($res)){
			if(!$data['image']) $data['image'] = makeSafe($row['image']);
		}
	}

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

	$o = array('silentErrors' => true);
	sql('insert into `patients` set       `last_name`=' . (($data['last_name'] !== '' && $data['last_name'] !== NULL) ? "'{$data['last_name']}'" : 'NULL') . ', `first_name`=' . (($data['first_name'] !== '' && $data['first_name'] !== NULL) ? "'{$data['first_name']}'" : 'NULL') . ', `gender`=' . (($data['gender'] !== '' && $data['gender'] !== NULL) ? "'{$data['gender']}'" : 'NULL') . ', `sexual_orientation`=' . (($data['sexual_orientation'] !== '' && $data['sexual_orientation'] !== NULL) ? "'{$data['sexual_orientation']}'" : 'NULL') . ', `birth_date`=' . (($data['birth_date'] !== '' && $data['birth_date'] !== NULL) ? "'{$data['birth_date']}'" : 'NULL') . ', ' . ($data['image'] != '' ? "`image`='{$data['image']}'" : '`image`=NULL') . ', `state`=' . (($data['state'] !== '' && $data['state'] !== NULL) ? "'{$data['state']}'" : 'NULL') . ', `mobile`=' . (($data['mobile'] !== '' && $data['mobile'] !== NULL) ? "'{$data['mobile']}'" : 'NULL') . ', `tobacco_usage`=' . (($data['tobacco_usage'] !== '' && $data['tobacco_usage'] !== NULL) ? "'{$data['tobacco_usage']}'" : 'NULL') . ', `alcohol_intake`=' . (($data['alcohol_intake'] !== '' && $data['alcohol_intake'] !== NULL) ? "'{$data['alcohol_intake']}'" : 'NULL') . ', `history`=' . (($data['history'] !== '' && $data['history'] !== NULL) ? "'{$data['history']}'" : 'NULL') . ', `surgical_history`=' . (($data['surgical_history'] !== '' && $data['surgical_history'] !== NULL) ? "'{$data['surgical_history']}'" : 'NULL') . ', `obstetric_history`=' . (($data['obstetric_history'] !== '' && $data['obstetric_history'] !== NULL) ? "'{$data['obstetric_history']}'" : 'NULL') . ', `genetic_diseases`=' . (($data['genetic_diseases'] !== '' && $data['genetic_diseases'] !== NULL) ? "'{$data['genetic_diseases']}'" : 'NULL') . ', `contact_person`=' . (($data['contact_person'] !== '' && $data['contact_person'] !== NULL) ? "'{$data['contact_person']}'" : 'NULL') . ', `other_details`=' . (($data['other_details'] !== '' && $data['other_details'] !== NULL) ? "'{$data['other_details']}'" : 'NULL') . ', `comments`=' . (($data['comments'] !== '' && $data['comments'] !== NULL) ? "'{$data['comments']}'" : 'NULL') . ', `filed`=' . "'{$data['filed']}'", $o);
	if($o['error']!=''){
		echo $o['error'];
		echo "<a href=\"patients_view.php?addNew_x=1\">{$Translation['< back']}</a>";
		exit;
	}

	$recID = db_insert_id(db_link());

	// hook: patients_after_insert
	if(function_exists('patients_after_insert')){
		$res = sql("select * from `patients` 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(!patients_after_insert($data, getMemberInfo(), $args)){ return $recID; }
	}

	// mm: save ownership data
	sql("insert ignore into membership_userrecords set tableName='patients', pkValue='" . makeSafe($recID, false) . "', memberID='" . makeSafe(getLoggedMemberID(), false) . "', dateAdded='" . time() . "', dateUpdated='" . time() . "', groupID='" . getLoggedGroupID() . "'", $eo);

	return $recID;
}

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

	// mm: can member delete record?
	$arrPerm=getTablePermissions('patients');
	$ownerGroupID=sqlValue("select groupID from membership_userrecords where tableName='patients' and pkValue='$selected_id'");
	$ownerMemberID=sqlValue("select lcase(memberID) from membership_userrecords where tableName='patients' 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: patients_before_delete
	if(function_exists('patients_before_delete')){
		$args=array();
		if(!patients_before_delete($selected_id, $skipChecks, getMemberInfo(), $args))
			return $Translation['Couldn\'t delete this record'];
	}

	// child table: medical_records
	$res = sql("select `id` from `patients` where `id`='$selected_id'", $eo);
	$id = db_fetch_row($res);
	$rires = sql("select count(1) from `medical_records` where `patient`='".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>", "medical_records", $RetMsg);
		return $RetMsg;
	}elseif($rirow[0] && $AllowDeleteOfParents && !$skipChecks){
		$RetMsg = $Translation["confirm delete"];
		$RetMsg = str_replace("<RelatedRecords>", $rirow[0], $RetMsg);
		$RetMsg = str_replace("<TableName>", "medical_records", $RetMsg);
		$RetMsg = str_replace("<Delete>", "<input type=\"button\" class=\"button\" value=\"".$Translation['yes']."\" onClick=\"window.location='patients_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='patients_view.php?SelectedID=".urlencode($selected_id)."';\">", $RetMsg);
		return $RetMsg;
	}

	// child table: events
	$res = sql("select `id` from `patients` where `id`='$selected_id'", $eo);
	$id = db_fetch_row($res);
	$rires = sql("select count(1) from `events` where `name_patient`='".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>", "events", $RetMsg);
		return $RetMsg;
	}elseif($rirow[0] && $AllowDeleteOfParents && !$skipChecks){
		$RetMsg = $Translation["confirm delete"];
		$RetMsg = str_replace("<RelatedRecords>", $rirow[0], $RetMsg);
		$RetMsg = str_replace("<TableName>", "events", $RetMsg);
		$RetMsg = str_replace("<Delete>", "<input type=\"button\" class=\"button\" value=\"".$Translation['yes']."\" onClick=\"window.location='patients_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='patients_view.php?SelectedID=".urlencode($selected_id)."';\">", $RetMsg);
		return $RetMsg;
	}

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

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

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

function patients_update($selected_id){
	global $Translation;

	// mm: can member edit record?
	$arrPerm=getTablePermissions('patients');
	$ownerGroupID=sqlValue("select groupID from membership_userrecords where tableName='patients' and pkValue='".makeSafe($selected_id)."'");
	$ownerMemberID=sqlValue("select lcase(memberID) from membership_userrecords where tableName='patients' 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['last_name'] = makeSafe($_REQUEST['last_name']);
		if($data['last_name'] == empty_lookup_value){ $data['last_name'] = ''; }
	if($data['last_name']==''){
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">{$Translation['error:']} 'Last name': {$Translation['field not null']}<br><br>";
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}
	$data['first_name'] = makeSafe($_REQUEST['first_name']);
		if($data['first_name'] == empty_lookup_value){ $data['first_name'] = ''; }
	if($data['first_name']==''){
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">{$Translation['error:']} 'First name': {$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['sexual_orientation'] = makeSafe($_REQUEST['sexual_orientation']);
		if($data['sexual_orientation'] == empty_lookup_value){ $data['sexual_orientation'] = ''; }
	if($data['sexual_orientation']==''){
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">{$Translation['error:']} 'Sexual orientation': {$Translation['field not null']}<br><br>";
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}
	$data['birth_date'] = intval($_REQUEST['birth_dateYear']) . '-' . intval($_REQUEST['birth_dateMonth']) . '-' . intval($_REQUEST['birth_dateDay']);
	$data['birth_date'] = parseMySQLDate($data['birth_date'], '');
	$data['address'] = br2nl(makeSafe($_REQUEST['address']));
	$data['city'] = makeSafe($_REQUEST['city']);
		if($data['city'] == empty_lookup_value){ $data['city'] = ''; }
	$data['state'] = makeSafe($_REQUEST['state']);
		if($data['state'] == empty_lookup_value){ $data['state'] = ''; }
	$data['zip'] = makeSafe($_REQUEST['zip']);
		if($data['zip'] == empty_lookup_value){ $data['zip'] = ''; }
	$data['home_phone'] = makeSafe($_REQUEST['home_phone']);
		if($data['home_phone'] == empty_lookup_value){ $data['home_phone'] = ''; }
	$data['work_phone'] = makeSafe($_REQUEST['work_phone']);
		if($data['work_phone'] == empty_lookup_value){ $data['work_phone'] = ''; }
	$data['mobile'] = makeSafe($_REQUEST['mobile']);
		if($data['mobile'] == empty_lookup_value){ $data['mobile'] = ''; }
	$data['tobacco_usage'] = makeSafe($_REQUEST['tobacco_usage']);
		if($data['tobacco_usage'] == empty_lookup_value){ $data['tobacco_usage'] = ''; }
	if($data['tobacco_usage']==''){
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">{$Translation['error:']} 'Tobacco usage': {$Translation['field not null']}<br><br>";
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}
	$data['alcohol_intake'] = makeSafe($_REQUEST['alcohol_intake']);
		if($data['alcohol_intake'] == empty_lookup_value){ $data['alcohol_intake'] = ''; }
	if($data['alcohol_intake']==''){
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">{$Translation['error:']} 'Alcohol Intake': {$Translation['field not null']}<br><br>";
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}
	$data['history'] = makeSafe($_REQUEST['history']);
		if($data['history'] == empty_lookup_value){ $data['history'] = ''; }
	if($data['history']==''){
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">{$Translation['error:']} 'History': {$Translation['field not null']}<br><br>";
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}
	$data['surgical_history'] = br2nl(makeSafe($_REQUEST['surgical_history']));
	$data['obstetric_history'] = br2nl(makeSafe($_REQUEST['obstetric_history']));
	$data['genetic_diseases'] = br2nl(makeSafe($_REQUEST['genetic_diseases']));
	$data['contact_person'] = makeSafe($_REQUEST['contact_person']);
		if($data['contact_person'] == empty_lookup_value){ $data['contact_person'] = ''; }
	$data['other_details'] = br2nl(makeSafe($_REQUEST['other_details']));
	$data['comments'] = makeSafe($_REQUEST['comments']);
		if($data['comments'] == empty_lookup_value){ $data['comments'] = ''; }
	$data['last_modified'] = parseCode('<%%editingDateTime%%>', false, true);
	$data['selectedID']=makeSafe($selected_id);
	if($_REQUEST['image_remove'] == 1){
		$data['image'] = '';
	}else{
		$data['image'] = PrepareUploadedFile('image', 1024000, 'jpg|jpeg|gif|png', false, "");
		if($data['image']) createThumbnail($data['image'], getThumbnailSpecs('patients', 'image', 'tv'));
		if($data['image']) createThumbnail($data['image'], getThumbnailSpecs('patients', 'image', 'dv'));
	}

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

	$o=array('silentErrors' => true);
	sql('update `patients` set       `last_name`=' . (($data['last_name'] !== '' && $data['last_name'] !== NULL) ? "'{$data['last_name']}'" : 'NULL') . ', `first_name`=' . (($data['first_name'] !== '' && $data['first_name'] !== NULL) ? "'{$data['first_name']}'" : 'NULL') . ', `gender`=' . (($data['gender'] !== '' && $data['gender'] !== NULL) ? "'{$data['gender']}'" : 'NULL') . ', `sexual_orientation`=' . (($data['sexual_orientation'] !== '' && $data['sexual_orientation'] !== NULL) ? "'{$data['sexual_orientation']}'" : 'NULL') . ', `birth_date`=' . (($data['birth_date'] !== '' && $data['birth_date'] !== NULL) ? "'{$data['birth_date']}'" : 'NULL') . ', ' . ($data['image']!='' ? "`image`='{$data['image']}'" : ($_REQUEST['image_remove'] != 1 ? '`image`=`image`' : '`image`=NULL')) . ', `state`=' . (($data['state'] !== '' && $data['state'] !== NULL) ? "'{$data['state']}'" : 'NULL') . ', `mobile`=' . (($data['mobile'] !== '' && $data['mobile'] !== NULL) ? "'{$data['mobile']}'" : 'NULL') . ', `tobacco_usage`=' . (($data['tobacco_usage'] !== '' && $data['tobacco_usage'] !== NULL) ? "'{$data['tobacco_usage']}'" : 'NULL') . ', `alcohol_intake`=' . (($data['alcohol_intake'] !== '' && $data['alcohol_intake'] !== NULL) ? "'{$data['alcohol_intake']}'" : 'NULL') . ', `history`=' . (($data['history'] !== '' && $data['history'] !== NULL) ? "'{$data['history']}'" : 'NULL') . ', `surgical_history`=' . (($data['surgical_history'] !== '' && $data['surgical_history'] !== NULL) ? "'{$data['surgical_history']}'" : 'NULL') . ', `obstetric_history`=' . (($data['obstetric_history'] !== '' && $data['obstetric_history'] !== NULL) ? "'{$data['obstetric_history']}'" : 'NULL') . ', `genetic_diseases`=' . (($data['genetic_diseases'] !== '' && $data['genetic_diseases'] !== NULL) ? "'{$data['genetic_diseases']}'" : 'NULL') . ', `contact_person`=' . (($data['contact_person'] !== '' && $data['contact_person'] !== NULL) ? "'{$data['contact_person']}'" : 'NULL') . ', `other_details`=' . (($data['other_details'] !== '' && $data['other_details'] !== NULL) ? "'{$data['other_details']}'" : 'NULL') . ', `comments`=' . (($data['comments'] !== '' && $data['comments'] !== NULL) ? "'{$data['comments']}'" : 'NULL') . ', `filed`=`filed`' . ', `last_modified`=' . "'{$data['last_modified']}'" . " where `id`='".makeSafe($selected_id)."'", $o);
	if($o['error']!=''){
		echo $o['error'];
		echo '<a href="patients_view.php?SelectedID='.urlencode($selected_id)."\">{$Translation['< back']}</a>";
		exit;
	}


	// hook: patients_after_update
	if(function_exists('patients_after_update')){
		$res = sql("SELECT * FROM `patients` 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(!patients_after_update($data, getMemberInfo(), $args)){ return; }
	}

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

}

function patients_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('patients');
	if(!$arrPerm[1] && $selected_id==''){ return ''; }
	$AllowInsert = ($arrPerm[1] ? true : false);
	// print preview?
	$dvprint = false;
	if($selected_id && $_REQUEST['dvprint_x'] != ''){
		$dvprint = true;
	}


	// populate filterers, starting from children to grand-parents

	// 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/patients.gender.csv')){
		$gender_data = addslashes(implode('', @file(dirname(__FILE__).'/hooks/patients.gender.csv')));
		$combo_gender->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($gender_data)));
		$combo_gender->ListData = $combo_gender->ListItem;
	}else{
		$combo_gender->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Unknown;;Male;;Female;;Other")));
		$combo_gender->ListData = $combo_gender->ListItem;
	}
	$combo_gender->SelectName = 'gender';
	$combo_gender->AllowNull = false;
	// combobox: sexual_orientation
	$combo_sexual_orientation = new Combo;
	$combo_sexual_orientation->ListType = 0;
	$combo_sexual_orientation->MultipleSeparator = ', ';
	$combo_sexual_orientation->ListBoxHeight = 10;
	$combo_sexual_orientation->RadiosPerLine = 1;
	if(is_file(dirname(__FILE__).'/hooks/patients.sexual_orientation.csv')){
		$sexual_orientation_data = addslashes(implode('', @file(dirname(__FILE__).'/hooks/patients.sexual_orientation.csv')));
		$combo_sexual_orientation->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($sexual_orientation_data)));
		$combo_sexual_orientation->ListData = $combo_sexual_orientation->ListItem;
	}else{
		$combo_sexual_orientation->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Unknown;;Opposite gender;;Same gender;;Asexuality;;Bisexuality")));
		$combo_sexual_orientation->ListData = $combo_sexual_orientation->ListItem;
	}
	$combo_sexual_orientation->SelectName = 'sexual_orientation';
	$combo_sexual_orientation->AllowNull = false;
	// combobox: birth_date
	$combo_birth_date = new DateCombo;
	$combo_birth_date->DateFormat = "mdy";
	$combo_birth_date->MinYear = 1900;
	$combo_birth_date->MaxYear = 2100;
	$combo_birth_date->DefaultDate = parseMySQLDate('', '');
	$combo_birth_date->MonthNames = $Translation['month names'];
	$combo_birth_date->NamePrefix = 'birth_date';
	// combobox: state
	$combo_state = new Combo;
	$combo_state->ListType = 0;
	$combo_state->MultipleSeparator = ', ';
	$combo_state->ListBoxHeight = 10;
	$combo_state->RadiosPerLine = 1;
	if(is_file(dirname(__FILE__).'/hooks/patients.state.csv')){
		$state_data = addslashes(implode('', @file(dirname(__FILE__).'/hooks/patients.state.csv')));
		$combo_state->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($state_data)));
		$combo_state->ListData = $combo_state->ListItem;
	}else{
		$combo_state->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("AL;;AK;;AS;;AZ;;AR;;CA;;CO;;CT;;DE;;DC;;FM;;FL;;GA;;GU;;HI;;ID;;IL;;IN;;IA;;KS;;KY;;LA;;ME;;MH;;MD;;MA;;MI;;MN;;MS;;MO;;MT;;NE;;NV;;NH;;NJ;;NM;;NY;;NC;;ND;;MP;;OH;;OK;;OR;;PW;;PA;;PR;;RI;;SC;;SD;;TN;;TX;;UT;;VT;;VI;;VA;;WA;;WV;;WI;;WY")));
		$combo_state->ListData = $combo_state->ListItem;
	}
	$combo_state->SelectName = 'state';
	// combobox: tobacco_usage
	$combo_tobacco_usage = new Combo;
	$combo_tobacco_usage->ListType = 0;
	$combo_tobacco_usage->MultipleSeparator = ', ';
	$combo_tobacco_usage->ListBoxHeight = 10;
	$combo_tobacco_usage->RadiosPerLine = 1;
	if(is_file(dirname(__FILE__).'/hooks/patients.tobacco_usage.csv')){
		$tobacco_usage_data = addslashes(implode('', @file(dirname(__FILE__).'/hooks/patients.tobacco_usage.csv')));
		$combo_tobacco_usage->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($tobacco_usage_data)));
		$combo_tobacco_usage->ListData = $combo_tobacco_usage->ListItem;
	}else{
		$combo_tobacco_usage->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Unknown;;Non-smoker;;Light smoker;;Average smoker;;Social smoker;;Heavy smoker;;Serial quitter;;Quitter")));
		$combo_tobacco_usage->ListData = $combo_tobacco_usage->ListItem;
	}
	$combo_tobacco_usage->SelectName = 'tobacco_usage';
	$combo_tobacco_usage->AllowNull = false;
	// combobox: alcohol_intake
	$combo_alcohol_intake = new Combo;
	$combo_alcohol_intake->ListType = 0;
	$combo_alcohol_intake->MultipleSeparator = ', ';
	$combo_alcohol_intake->ListBoxHeight = 10;
	$combo_alcohol_intake->RadiosPerLine = 1;
	if(is_file(dirname(__FILE__).'/hooks/patients.alcohol_intake.csv')){
		$alcohol_intake_data = addslashes(implode('', @file(dirname(__FILE__).'/hooks/patients.alcohol_intake.csv')));
		$combo_alcohol_intake->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($alcohol_intake_data)));
		$combo_alcohol_intake->ListData = $combo_alcohol_intake->ListItem;
	}else{
		$combo_alcohol_intake->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Unknown;;Non-drinker;;Light drinker;;Social drinker;;Pressured drinker;;Daily drinker;;Binge drinker;;Compulsive drinker;;Addicted drinker;;Serial quitter;;Quitter")));
		$combo_alcohol_intake->ListData = $combo_alcohol_intake->ListItem;
	}
	$combo_alcohol_intake->SelectName = 'alcohol_intake';
	$combo_alcohol_intake->AllowNull = false;
	// combobox: history
	$combo_history = new Combo;
	$combo_history->ListType = 0;
	$combo_history->MultipleSeparator = ', ';
	$combo_history->ListBoxHeight = 10;
	$combo_history->RadiosPerLine = 1;
	if(is_file(dirname(__FILE__).'/hooks/patients.history.csv')){
		$history_data = addslashes(implode('', @file(dirname(__FILE__).'/hooks/patients.history.csv')));
		$combo_history->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($history_data)));
		$combo_history->ListData = $combo_history->ListItem;
	}else{
		$combo_history->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Unkown;;Asthma;;Diabetes;;Blood pressure;;Medication allergies;;Food allergies;;None")));
		$combo_history->ListData = $combo_history->ListItem;
	}
	$combo_history->SelectName = 'history';
	$combo_history->AllowNull = false;

	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='patients' and pkValue='".makeSafe($selected_id)."'");
		$ownerMemberID=sqlValue("select lcase(memberID) from membership_userrecords where tableName='patients' 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 `patients` where `id`='".makeSafe($selected_id)."'", $eo);
		if(!($row = db_fetch_array($res))){
			return error_message($Translation['No records found'], 'patients_view.php', false);
		}
		$urow = $row; /* unsanitized data */
		$hc = new CI_Input();
		$row = $hc->xss_clean($row); /* sanitize data */
		$combo_gender->SelectedData = $row['gender'];
		$combo_sexual_orientation->SelectedData = $row['sexual_orientation'];
		$combo_birth_date->DefaultDate = $row['birth_date'];
		$combo_state->SelectedData = $row['state'];
		$combo_tobacco_usage->SelectedData = $row['tobacco_usage'];
		$combo_alcohol_intake->SelectedData = $row['alcohol_intake'];
		$combo_history->SelectedData = $row['history'];
		$row['filed'] = sqlValue("select DATE_FORMAT(`filed`, '%c/%e/%Y %l:%i%p') from `patients` where `id`='".makeSafe($selected_id)."'");
		$row['last_modified'] = sqlValue("select DATE_FORMAT(`last_modified`, '%c/%e/%Y %l:%i%p') from `patients` where `id`='".makeSafe($selected_id)."'");
	}else{
		$combo_gender->SelectedText = ( $_REQUEST['FilterField'][1]=='4' && $_REQUEST['FilterOperator'][1]=='<=>' ? (get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1]) : "Unknown");
		$combo_sexual_orientation->SelectedText = ( $_REQUEST['FilterField'][1]=='5' && $_REQUEST['FilterOperator'][1]=='<=>' ? (get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1]) : "Unknown");
		$combo_state->SelectedText = ( $_REQUEST['FilterField'][1]=='11' && $_REQUEST['FilterOperator'][1]=='<=>' ? (get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1]) : "");
		$combo_tobacco_usage->SelectedText = ( $_REQUEST['FilterField'][1]=='16' && $_REQUEST['FilterOperator'][1]=='<=>' ? (get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1]) : "Unknown");
		$combo_alcohol_intake->SelectedText = ( $_REQUEST['FilterField'][1]=='17' && $_REQUEST['FilterOperator'][1]=='<=>' ? (get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1]) : "Unknown");
		$combo_history->SelectedText = ( $_REQUEST['FilterField'][1]=='18' && $_REQUEST['FilterOperator'][1]=='<=>' ? (get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1]) : "Unknown");
	}
	$combo_gender->Render();
	$combo_sexual_orientation->Render();
	$combo_state->Render();
	$combo_tobacco_usage->Render();
	$combo_alcohol_intake->Render();
	$combo_history->Render();

	// code for template based detail view forms

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

	// process form title
	$templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Patient 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 patients_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 patients_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 = 'window.parent.jQuery(\'.modal\').modal(\'hide\'); return false;';
	}else{
		$backAction = '$$(\'form\')[0].writeAttribute(\'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 patients_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('#last_name').replaceWith('<div class=\"form-control-static\" id=\"last_name\">' + (jQuery('#last_name').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#first_name').replaceWith('<div class=\"form-control-static\" id=\"first_name\">' + (jQuery('#first_name').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('#sexual_orientation').replaceWith('<div class=\"form-control-static\" id=\"sexual_orientation\">' + (jQuery('#sexual_orientation').val() || '') + '</div>'); jQuery('#sexual_orientation-multi-selection-help').hide();\n";
		$jsReadOnly .= "\tjQuery('#birth_date').prop('readonly', true);\n";
		$jsReadOnly .= "\tjQuery('#birth_dateDay, #birth_dateMonth, #birth_dateYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\tjQuery('#image').replaceWith('<div class=\"form-control-static\" id=\"image\">' + (jQuery('#image').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#state').replaceWith('<div class=\"form-control-static\" id=\"state\">' + (jQuery('#state').val() || '') + '</div>'); jQuery('#state-multi-selection-help').hide();\n";
		$jsReadOnly .= "\tjQuery('#mobile').replaceWith('<div class=\"form-control-static\" id=\"mobile\">' + (jQuery('#mobile').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#tobacco_usage').replaceWith('<div class=\"form-control-static\" id=\"tobacco_usage\">' + (jQuery('#tobacco_usage').val() || '') + '</div>'); jQuery('#tobacco_usage-multi-selection-help').hide();\n";
		$jsReadOnly .= "\tjQuery('#alcohol_intake').replaceWith('<div class=\"form-control-static\" id=\"alcohol_intake\">' + (jQuery('#alcohol_intake').val() || '') + '</div>'); jQuery('#alcohol_intake-multi-selection-help').hide();\n";
		$jsReadOnly .= "\tjQuery('#history').replaceWith('<div class=\"form-control-static\" id=\"history\">' + (jQuery('#history').val() || '') + '</div>'); jQuery('#history-multi-selection-help').hide();\n";
		$jsReadOnly .= "\tjQuery('#surgical_history').replaceWith('<div class=\"form-control-static\" id=\"surgical_history\">' + (jQuery('#surgical_history').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#obstetric_history').replaceWith('<div class=\"form-control-static\" id=\"obstetric_history\">' + (jQuery('#obstetric_history').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#genetic_diseases').replaceWith('<div class=\"form-control-static\" id=\"genetic_diseases\">' + (jQuery('#genetic_diseases').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#contact_person').replaceWith('<div class=\"form-control-static\" id=\"contact_person\">' + (jQuery('#contact_person').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#other_details').replaceWith('<div class=\"form-control-static\" id=\"other_details\">' + (jQuery('#other_details').val() || '') + '</div>');\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(sexual_orientation)%%>', $combo_sexual_orientation->HTML, $templateCode);
	$templateCode=str_replace('<%%COMBOTEXT(sexual_orientation)%%>', $combo_sexual_orientation->SelectedData, $templateCode);
	$templateCode=str_replace('<%%COMBO(birth_date)%%>', ($selected_id && !$arrPerm[3] ? '<div class="form-control-static">' . $combo_birth_date->GetHTML(true) . '</div>' : $combo_birth_date->GetHTML()), $templateCode);
	$templateCode=str_replace('<%%COMBOTEXT(birth_date)%%>', $combo_birth_date->GetHTML(true), $templateCode);
	$templateCode=str_replace('<%%COMBO(state)%%>', $combo_state->HTML, $templateCode);
	$templateCode=str_replace('<%%COMBOTEXT(state)%%>', $combo_state->SelectedData, $templateCode);
	$templateCode=str_replace('<%%COMBO(tobacco_usage)%%>', $combo_tobacco_usage->HTML, $templateCode);
	$templateCode=str_replace('<%%COMBOTEXT(tobacco_usage)%%>', $combo_tobacco_usage->SelectedData, $templateCode);
	$templateCode=str_replace('<%%COMBO(alcohol_intake)%%>', $combo_alcohol_intake->HTML, $templateCode);
	$templateCode=str_replace('<%%COMBOTEXT(alcohol_intake)%%>', $combo_alcohol_intake->SelectedData, $templateCode);
	$templateCode=str_replace('<%%COMBO(history)%%>', $combo_history->HTML, $templateCode);
	$templateCode=str_replace('<%%COMBOTEXT(history)%%>', $combo_history->SelectedData, $templateCode);

	/* lookup fields array: 'lookup field name' => array('parent table name', 'lookup field caption') */
	$lookup_fields = array();
	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(last_name)%%>', '', $templateCode);
	$templateCode=str_replace('<%%UPLOADFILE(first_name)%%>', '', $templateCode);
	$templateCode=str_replace('<%%UPLOADFILE(gender)%%>', '', $templateCode);
	$templateCode=str_replace('<%%UPLOADFILE(sexual_orientation)%%>', '', $templateCode);
	$templateCode=str_replace('<%%UPLOADFILE(birth_date)%%>', '', $templateCode);
	$templateCode=str_replace('<%%UPLOADFILE(age)%%>', '', $templateCode);
	$templateCode=str_replace('<%%UPLOADFILE(image)%%>', ($noUploads ? '' : '<input type=hidden name=MAX_FILE_SIZE value=1024000>'.$Translation['upload image'].' <input type="file" name="image" id="image">'), $templateCode);
	if($AllowUpdate && $row['image']!=''){
		$templateCode=str_replace('<%%REMOVEFILE(image)%%>', '<br><input type="checkbox" name="image_remove" id="image_remove" value="1"> <label for="image_remove" style="color: red; font-weight: bold;">'.$Translation['remove image'].'</label>', $templateCode);
	}else{
		$templateCode=str_replace('<%%REMOVEFILE(image)%%>', '', $templateCode);
	}
	$templateCode=str_replace('<%%UPLOADFILE(address)%%>', '', $templateCode);
	$templateCode=str_replace('<%%UPLOADFILE(city)%%>', '', $templateCode);
	$templateCode=str_replace('<%%UPLOADFILE(state)%%>', '', $templateCode);
	$templateCode=str_replace('<%%UPLOADFILE(zip)%%>', '', $templateCode);
	$templateCode=str_replace('<%%UPLOADFILE(home_phone)%%>', '', $templateCode);
	$templateCode=str_replace('<%%UPLOADFILE(work_phone)%%>', '', $templateCode);
	$templateCode=str_replace('<%%UPLOADFILE(mobile)%%>', '', $templateCode);
	$templateCode=str_replace('<%%UPLOADFILE(tobacco_usage)%%>', '', $templateCode);
	$templateCode=str_replace('<%%UPLOADFILE(alcohol_intake)%%>', '', $templateCode);
	$templateCode=str_replace('<%%UPLOADFILE(history)%%>', '', $templateCode);
	$templateCode=str_replace('<%%UPLOADFILE(surgical_history)%%>', '', $templateCode);
	$templateCode=str_replace('<%%UPLOADFILE(obstetric_history)%%>', '', $templateCode);
	$templateCode=str_replace('<%%UPLOADFILE(genetic_diseases)%%>', '', $templateCode);
	$templateCode=str_replace('<%%UPLOADFILE(contact_person)%%>', '', $templateCode);
	$templateCode=str_replace('<%%UPLOADFILE(other_details)%%>', '', $templateCode);
	$templateCode=str_replace('<%%UPLOADFILE(comments)%%>', '', $templateCode);
	$templateCode=str_replace('<%%UPLOADFILE(filed)%%>', '', $templateCode);
	$templateCode=str_replace('<%%UPLOADFILE(last_modified)%%>', '', $templateCode);

	// process values
	if($selected_id){
		$templateCode=str_replace('<%%VALUE(id)%%>', html_attr($row['id']), $templateCode);
		$templateCode=str_replace('<%%URLVALUE(id)%%>', urlencode($urow['id']), $templateCode);
		$templateCode=str_replace('<%%VALUE(last_name)%%>', html_attr($row['last_name']), $templateCode);
		$templateCode=str_replace('<%%URLVALUE(last_name)%%>', urlencode($urow['last_name']), $templateCode);
		$templateCode=str_replace('<%%VALUE(first_name)%%>', html_attr($row['first_name']), $templateCode);
		$templateCode=str_replace('<%%URLVALUE(first_name)%%>', urlencode($urow['first_name']), $templateCode);
		$templateCode=str_replace('<%%VALUE(gender)%%>', html_attr($row['gender']), $templateCode);
		$templateCode=str_replace('<%%URLVALUE(gender)%%>', urlencode($urow['gender']), $templateCode);
		$templateCode=str_replace('<%%VALUE(sexual_orientation)%%>', html_attr($row['sexual_orientation']), $templateCode);
		$templateCode=str_replace('<%%URLVALUE(sexual_orientation)%%>', urlencode($urow['sexual_orientation']), $templateCode);
		$templateCode=str_replace('<%%VALUE(birth_date)%%>', @date('m/d/Y', @strtotime(html_attr($row['birth_date']))), $templateCode);
		$templateCode=str_replace('<%%URLVALUE(birth_date)%%>', urlencode(@date('m/d/Y', @strtotime(html_attr($urow['birth_date'])))), $templateCode);
		$templateCode=str_replace('<%%VALUE(age)%%>', html_attr($row['age']), $templateCode);
		$templateCode=str_replace('<%%URLVALUE(age)%%>', urlencode($urow['age']), $templateCode);
		$row['image']=($row['image']!=''?$row['image']:'blank.gif');
		$templateCode=str_replace('<%%VALUE(image)%%>', html_attr($row['image']), $templateCode);
		$templateCode=str_replace('<%%URLVALUE(image)%%>', urlencode($urow['image']), $templateCode);
		if($dvprint){
			$templateCode = str_replace('<%%VALUE(address)%%>', nl2br(html_attr($row['address'])), $templateCode);
		}else{
			$templateCode = str_replace('<%%VALUE(address)%%>', html_attr($row['address']), $templateCode);
		}
		$templateCode=str_replace('<%%URLVALUE(address)%%>', urlencode($urow['address']), $templateCode);
		$templateCode=str_replace('<%%VALUE(city)%%>', html_attr($row['city']), $templateCode);
		$templateCode=str_replace('<%%URLVALUE(city)%%>', urlencode($urow['city']), $templateCode);
		$templateCode=str_replace('<%%VALUE(state)%%>', html_attr($row['state']), $templateCode);
		$templateCode=str_replace('<%%URLVALUE(state)%%>', urlencode($urow['state']), $templateCode);
		$templateCode=str_replace('<%%VALUE(zip)%%>', html_attr($row['zip']), $templateCode);
		$templateCode=str_replace('<%%URLVALUE(zip)%%>', urlencode($urow['zip']), $templateCode);
		$templateCode=str_replace('<%%VALUE(home_phone)%%>', html_attr($row['home_phone']), $templateCode);
		$templateCode=str_replace('<%%URLVALUE(home_phone)%%>', urlencode($urow['home_phone']), $templateCode);
		$templateCode=str_replace('<%%VALUE(work_phone)%%>', html_attr($row['work_phone']), $templateCode);
		$templateCode=str_replace('<%%URLVALUE(work_phone)%%>', urlencode($urow['work_phone']), $templateCode);
		$templateCode=str_replace('<%%VALUE(mobile)%%>', html_attr($row['mobile']), $templateCode);
		$templateCode=str_replace('<%%URLVALUE(mobile)%%>', urlencode($urow['mobile']), $templateCode);
		$templateCode=str_replace('<%%VALUE(tobacco_usage)%%>', html_attr($row['tobacco_usage']), $templateCode);
		$templateCode=str_replace('<%%URLVALUE(tobacco_usage)%%>', urlencode($urow['tobacco_usage']), $templateCode);
		$templateCode=str_replace('<%%VALUE(alcohol_intake)%%>', html_attr($row['alcohol_intake']), $templateCode);
		$templateCode=str_replace('<%%URLVALUE(alcohol_intake)%%>', urlencode($urow['alcohol_intake']), $templateCode);
		$templateCode=str_replace('<%%VALUE(history)%%>', html_attr($row['history']), $templateCode);
		$templateCode=str_replace('<%%URLVALUE(history)%%>', urlencode($urow['history']), $templateCode);
		if($dvprint){
			$templateCode = str_replace('<%%VALUE(surgical_history)%%>', nl2br(html_attr($row['surgical_history'])), $templateCode);
		}else{
			$templateCode = str_replace('<%%VALUE(surgical_history)%%>', html_attr($row['surgical_history']), $templateCode);
		}
		$templateCode=str_replace('<%%URLVALUE(surgical_history)%%>', urlencode($urow['surgical_history']), $templateCode);
		if($dvprint){
			$templateCode = str_replace('<%%VALUE(obstetric_history)%%>', nl2br(html_attr($row['obstetric_history'])), $templateCode);
		}else{
			$templateCode = str_replace('<%%VALUE(obstetric_history)%%>', html_attr($row['obstetric_history']), $templateCode);
		}
		$templateCode=str_replace('<%%URLVALUE(obstetric_history)%%>', urlencode($urow['obstetric_history']), $templateCode);
		if($dvprint){
			$templateCode = str_replace('<%%VALUE(genetic_diseases)%%>', nl2br(html_attr($row['genetic_diseases'])), $templateCode);
		}else{
			$templateCode = str_replace('<%%VALUE(genetic_diseases)%%>', html_attr($row['genetic_diseases']), $templateCode);
		}
		$templateCode=str_replace('<%%URLVALUE(genetic_diseases)%%>', urlencode($urow['genetic_diseases']), $templateCode);
		$templateCode=str_replace('<%%VALUE(contact_person)%%>', html_attr($row['contact_person']), $templateCode);
		$templateCode=str_replace('<%%URLVALUE(contact_person)%%>', urlencode($urow['contact_person']), $templateCode);
		if($dvprint){
			$templateCode = str_replace('<%%VALUE(other_details)%%>', nl2br(html_attr($row['other_details'])), $templateCode);
		}else{
			$templateCode = str_replace('<%%VALUE(other_details)%%>', html_attr($row['other_details']), $templateCode);
		}
		$templateCode=str_replace('<%%URLVALUE(other_details)%%>', urlencode($urow['other_details']), $templateCode);
		if($AllowUpdate || $AllowInsert){
			$templateCode = str_replace('<%%HTMLAREA(comments)%%>', '<textarea name="comments" id="comments" rows="5">' . html_attr($row['comments']) . '</textarea>', $templateCode);
		}else{
			$templateCode = str_replace('<%%HTMLAREA(comments)%%>', '<div id="comments" class="form-control-static">' . $row['comments'] . '</div>', $templateCode);
		}
		$templateCode=str_replace('<%%VALUE(comments)%%>', nl2br($row['comments']), $templateCode);
		$templateCode=str_replace('<%%URLVALUE(comments)%%>', urlencode($urow['comments']), $templateCode);
		$templateCode=str_replace('<%%VALUE(filed)%%>', html_attr($row['filed']), $templateCode);
		$templateCode=str_replace('<%%URLVALUE(filed)%%>', urlencode($urow['filed']), $templateCode);
		$templateCode=str_replace('<%%VALUE(last_modified)%%>', html_attr($row['last_modified']), $templateCode);
		$templateCode=str_replace('<%%URLVALUE(last_modified)%%>', urlencode($urow['last_modified']), $templateCode);
	}else{
		$templateCode=str_replace('<%%VALUE(id)%%>', '', $templateCode);
		$templateCode=str_replace('<%%URLVALUE(id)%%>', urlencode(''), $templateCode);
		$templateCode=str_replace('<%%VALUE(last_name)%%>', '', $templateCode);
		$templateCode=str_replace('<%%URLVALUE(last_name)%%>', urlencode(''), $templateCode);
		$templateCode=str_replace('<%%VALUE(first_name)%%>', '', $templateCode);
		$templateCode=str_replace('<%%URLVALUE(first_name)%%>', urlencode(''), $templateCode);
		$templateCode=str_replace('<%%VALUE(gender)%%>', 'Unknown', $templateCode);
		$templateCode=str_replace('<%%URLVALUE(gender)%%>', urlencode('Unknown'), $templateCode);
		$templateCode=str_replace('<%%VALUE(sexual_orientation)%%>', 'Unknown', $templateCode);
		$templateCode=str_replace('<%%URLVALUE(sexual_orientation)%%>', urlencode('Unknown'), $templateCode);
		$templateCode=str_replace('<%%VALUE(birth_date)%%>', '', $templateCode);
		$templateCode=str_replace('<%%URLVALUE(birth_date)%%>', urlencode(''), $templateCode);
		$templateCode=str_replace('<%%VALUE(age)%%>', '', $templateCode);
		$templateCode=str_replace('<%%URLVALUE(age)%%>', urlencode(''), $templateCode);
		$templateCode=str_replace('<%%VALUE(image)%%>', 'blank.gif', $templateCode);
		$templateCode=str_replace('<%%VALUE(address)%%>', '', $templateCode);
		$templateCode=str_replace('<%%URLVALUE(address)%%>', urlencode(''), $templateCode);
		$templateCode=str_replace('<%%VALUE(city)%%>', '', $templateCode);
		$templateCode=str_replace('<%%URLVALUE(city)%%>', urlencode(''), $templateCode);
		$templateCode=str_replace('<%%VALUE(state)%%>', '', $templateCode);
		$templateCode=str_replace('<%%URLVALUE(state)%%>', urlencode(''), $templateCode);
		$templateCode=str_replace('<%%VALUE(zip)%%>', '', $templateCode);
		$templateCode=str_replace('<%%URLVALUE(zip)%%>', urlencode(''), $templateCode);
		$templateCode=str_replace('<%%VALUE(home_phone)%%>', '', $templateCode);
		$templateCode=str_replace('<%%URLVALUE(home_phone)%%>', urlencode(''), $templateCode);
		$templateCode=str_replace('<%%VALUE(work_phone)%%>', '', $templateCode);
		$templateCode=str_replace('<%%URLVALUE(work_phone)%%>', urlencode(''), $templateCode);
		$templateCode=str_replace('<%%VALUE(mobile)%%>', '', $templateCode);
		$templateCode=str_replace('<%%URLVALUE(mobile)%%>', urlencode(''), $templateCode);
		$templateCode=str_replace('<%%VALUE(tobacco_usage)%%>', 'Unknown', $templateCode);
		$templateCode=str_replace('<%%URLVALUE(tobacco_usage)%%>', urlencode('Unknown'), $templateCode);
		$templateCode=str_replace('<%%VALUE(alcohol_intake)%%>', 'Unknown', $templateCode);
		$templateCode=str_replace('<%%URLVALUE(alcohol_intake)%%>', urlencode('Unknown'), $templateCode);
		$templateCode=str_replace('<%%VALUE(history)%%>', 'Unknown', $templateCode);
		$templateCode=str_replace('<%%URLVALUE(history)%%>', urlencode('Unknown'), $templateCode);
		$templateCode=str_replace('<%%VALUE(surgical_history)%%>', '', $templateCode);
		$templateCode=str_replace('<%%URLVALUE(surgical_history)%%>', urlencode(''), $templateCode);
		$templateCode=str_replace('<%%VALUE(obstetric_history)%%>', '', $templateCode);
		$templateCode=str_replace('<%%URLVALUE(obstetric_history)%%>', urlencode(''), $templateCode);
		$templateCode=str_replace('<%%VALUE(genetic_diseases)%%>', '', $templateCode);
		$templateCode=str_replace('<%%URLVALUE(genetic_diseases)%%>', urlencode(''), $templateCode);
		$templateCode=str_replace('<%%VALUE(contact_person)%%>', '', $templateCode);
		$templateCode=str_replace('<%%URLVALUE(contact_person)%%>', urlencode(''), $templateCode);
		$templateCode=str_replace('<%%VALUE(other_details)%%>', '', $templateCode);
		$templateCode=str_replace('<%%URLVALUE(other_details)%%>', urlencode(''), $templateCode);
		$templateCode=str_replace('<%%HTMLAREA(comments)%%>', '<textarea name="comments" id="comments" rows="5"></textarea>', $templateCode);
		$templateCode=str_replace('<%%VALUE(filed)%%>', '<%%creationDateTime%%>', $templateCode);
		$templateCode=str_replace('<%%URLVALUE(filed)%%>', urlencode('<%%creationDateTime%%>'), $templateCode);
		$templateCode=str_replace('<%%VALUE(last_modified)%%>', '<%%editingDateTime%%>', $templateCode);
		$templateCode=str_replace('<%%URLVALUE(last_modified)%%>', urlencode('<%%editingDateTime%%>'), $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('patients');
	if($selected_id){
		$jdata = get_joined_record('patients', $selected_id);
		$rdata = $row;
	}
	$cache_data = array(
		'rdata' => array_map('nl2br', array_map('addslashes', $rdata)),
		'jdata' => array_map('nl2br', array_map('addslashes', $jdata)),
	);
	$templateCode .= loadView('patients-ajax-cache', $cache_data);

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

	return $templateCode;
}
?>