<?php

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

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

function medical_records_insert(&$error_message = '') {
	global $Translation;

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

	$data = [
		'image_1' => Request::fileUpload('image_1', [
			'maxSize' => 1024000,
			'types' => 'jpg|jpeg|gif|png|webp',
			'noRename' => false,
			'dir' => '',
			'success' => function($name, $selected_id) {
				createThumbnail($name, getThumbnailSpecs('medical_records', 'image_1', 'tv'));
				createThumbnail($name, getThumbnailSpecs('medical_records', 'image_1', 'dv'));
			},
			'failure' => function($selected_id, $fileRemoved) {
				if(!strlen(Request::val('SelectedID'))) return '';

				/* for empty upload fields, when saving a copy of an existing record, copy the original upload field */
				return existing_value('medical_records', 'image_1', Request::val('SelectedID'));
			},
		]),
		'image_2' => Request::fileUpload('image_2', [
			'maxSize' => 1024000,
			'types' => 'jpg|jpeg|gif|png|webp',
			'noRename' => false,
			'dir' => '',
			'success' => function($name, $selected_id) {
				createThumbnail($name, getThumbnailSpecs('medical_records', 'image_2', 'tv'));
				createThumbnail($name, getThumbnailSpecs('medical_records', 'image_2', 'dv'));
			},
			'failure' => function($selected_id, $fileRemoved) {
				if(!strlen(Request::val('SelectedID'))) return '';

				/* for empty upload fields, when saving a copy of an existing record, copy the original upload field */
				return existing_value('medical_records', 'image_2', Request::val('SelectedID'));
			},
		]),
		'image_3' => Request::fileUpload('image_3', [
			'maxSize' => 1024000,
			'types' => 'jpg|jpeg|gif|png|webp',
			'noRename' => false,
			'dir' => '',
			'success' => function($name, $selected_id) {
				createThumbnail($name, getThumbnailSpecs('medical_records', 'image_3', 'tv'));
				createThumbnail($name, getThumbnailSpecs('medical_records', 'image_3', 'dv'));
			},
			'failure' => function($selected_id, $fileRemoved) {
				if(!strlen(Request::val('SelectedID'))) return '';

				/* for empty upload fields, when saving a copy of an existing record, copy the original upload field */
				return existing_value('medical_records', 'image_3', Request::val('SelectedID'));
			},
		]),
		'image_4' => Request::fileUpload('image_4', [
			'maxSize' => 1024000,
			'types' => 'jpg|jpeg|gif|png|webp',
			'noRename' => false,
			'dir' => '',
			'success' => function($name, $selected_id) {
				createThumbnail($name, getThumbnailSpecs('medical_records', 'image_4', 'tv'));
				createThumbnail($name, getThumbnailSpecs('medical_records', 'image_4', 'dv'));
			},
			'failure' => function($selected_id, $fileRemoved) {
				if(!strlen(Request::val('SelectedID'))) return '';

				/* for empty upload fields, when saving a copy of an existing record, copy the original upload field */
				return existing_value('medical_records', 'image_4', Request::val('SelectedID'));
			},
		]),
		'image_5' => Request::fileUpload('image_5', [
			'maxSize' => 1024000,
			'types' => 'jpg|jpeg|gif|png|webp',
			'noRename' => false,
			'dir' => '',
			'success' => function($name, $selected_id) {
				createThumbnail($name, getThumbnailSpecs('medical_records', 'image_5', 'tv'));
				createThumbnail($name, getThumbnailSpecs('medical_records', 'image_5', 'dv'));
			},
			'failure' => function($selected_id, $fileRemoved) {
				if(!strlen(Request::val('SelectedID'))) return '';

				/* for empty upload fields, when saving a copy of an existing record, copy the original upload field */
				return existing_value('medical_records', 'image_5', Request::val('SelectedID'));
			},
		]),
		'document_1' => Request::fileUpload('document_1', [
			'maxSize' => 5120000,
			'types' => 'txt|doc|docx|docm|odt|pdf|rtf',
			'noRename' => false,
			'dir' => '',
			'success' => function($name, $selected_id) {
			},
			'failure' => function($selected_id, $fileRemoved) {
				if(!strlen(Request::val('SelectedID'))) return '';

				/* for empty upload fields, when saving a copy of an existing record, copy the original upload field */
				return existing_value('medical_records', 'document_1', Request::val('SelectedID'));
			},
		]),
		'document_2' => Request::fileUpload('document_2', [
			'maxSize' => 5120000,
			'types' => 'txt|doc|docx|docm|odt|pdf|rtf',
			'noRename' => false,
			'dir' => '',
			'success' => function($name, $selected_id) {
			},
			'failure' => function($selected_id, $fileRemoved) {
				if(!strlen(Request::val('SelectedID'))) return '';

				/* for empty upload fields, when saving a copy of an existing record, copy the original upload field */
				return existing_value('medical_records', 'document_2', Request::val('SelectedID'));
			},
		]),
		'document_3' => Request::fileUpload('document_3', [
			'maxSize' => 5120000,
			'types' => 'txt|doc|docx|docm|odt|pdf|rtf',
			'noRename' => false,
			'dir' => '',
			'success' => function($name, $selected_id) {
			},
			'failure' => function($selected_id, $fileRemoved) {
				if(!strlen(Request::val('SelectedID'))) return '';

				/* for empty upload fields, when saving a copy of an existing record, copy the original upload field */
				return existing_value('medical_records', 'document_3', Request::val('SelectedID'));
			},
		]),
		'document_4' => Request::fileUpload('document_4', [
			'maxSize' => 5120000,
			'types' => 'txt|doc|docx|docm|odt|pdf|rtf',
			'noRename' => false,
			'dir' => '',
			'success' => function($name, $selected_id) {
			},
			'failure' => function($selected_id, $fileRemoved) {
				if(!strlen(Request::val('SelectedID'))) return '';

				/* for empty upload fields, when saving a copy of an existing record, copy the original upload field */
				return existing_value('medical_records', 'document_4', Request::val('SelectedID'));
			},
		]),
		'document_5' => Request::fileUpload('document_5', [
			'maxSize' => 5120000,
			'types' => 'txt|doc|docx|docm|odt|pdf|rtf',
			'noRename' => false,
			'dir' => '',
			'success' => function($name, $selected_id) {
			},
			'failure' => function($selected_id, $fileRemoved) {
				if(!strlen(Request::val('SelectedID'))) return '';

				/* for empty upload fields, when saving a copy of an existing record, copy the original upload field */
				return existing_value('medical_records', 'document_5', Request::val('SelectedID'));
			},
		]),
		'description' => br2nl(Request::val('description', '')),
	];


	// hook: medical_records_before_insert
	if(function_exists('medical_records_before_insert')) {
		$args = [];
		if(!medical_records_before_insert($data, getMemberInfo(), $args)) {
			if(isset($args['error_message'])) $error_message = $args['error_message'];
			return false;
		}
	}

	$error = '';
	// set empty fields to NULL
	$data = array_map(function($v) { return ($v === '' ? NULL : $v); }, $data);
	insert('medical_records', backtick_keys_once($data), $error);
	if($error) {
		$error_message = $error;
		return false;
	}

	$recID = db_insert_id(db_link());

	// automatic patient if passed as filterer
	if(Request::val('filterer_patient')) {
		sql("UPDATE `medical_records` SET `patient`='" . makeSafe(Request::val('filterer_patient')) . "' WHERE `id`='" . makeSafe($recID, false) . "'", $eo);
	}

	update_calc_fields('medical_records', $recID, calculated_fields()['medical_records']);

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

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

	// if this record is a copy of another record, copy children if applicable
	if(strlen(Request::val('SelectedID'))) medical_records_copy_children($recID, Request::val('SelectedID'));

	return $recID;
}

function medical_records_copy_children($destination_id, $source_id) {
	global $Translation;
	$requests = []; // array of curl handlers for launching insert requests
	$eo = ['silentErrors' => true];
	$safe_sid = makeSafe($source_id);

	// launch requests, asynchronously
	curl_batch($requests);
}

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

	// mm: can member delete record?
	if(!check_record_permission('medical_records', $selected_id, 'delete')) {
		return $Translation['You don\'t have enough permissions to delete this record'];
	}

	// hook: medical_records_before_delete
	if(function_exists('medical_records_before_delete')) {
		$args = [];
		if(!medical_records_before_delete($selected_id, $skipChecks, getMemberInfo(), $args))
			return $Translation['Couldn\'t delete this record'] . (
				!empty($args['error_message']) ?
					'<div class="text-bold">' . strip_tags($args['error_message']) . '</div>'
					: '' 
			);
	}

	sql("DELETE FROM `medical_records` WHERE `id`='{$selected_id}'", $eo);

	// hook: medical_records_after_delete
	if(function_exists('medical_records_after_delete')) {
		$args = [];
		medical_records_after_delete($selected_id, getMemberInfo(), $args);
	}

	// mm: delete ownership data
	sql("DELETE FROM `membership_userrecords` WHERE `tableName`='medical_records' AND `pkValue`='{$selected_id}'", $eo);
}

function medical_records_update(&$selected_id, &$error_message = '') {
	global $Translation;

	// mm: can member edit record?
	if(!check_record_permission('medical_records', $selected_id, 'edit')) return false;

	$data = [
		'image_1' => Request::fileUpload('image_1', [
			'maxSize' => 1024000,
			'types' => 'jpg|jpeg|gif|png|webp',
			'noRename' => false,
			'dir' => '',
			'id' => $selected_id,
			'success' => function($name, $selected_id) {
				createThumbnail($name, getThumbnailSpecs('medical_records', 'image_1', 'tv'));
				createThumbnail($name, getThumbnailSpecs('medical_records', 'image_1', 'dv'));
			},
			'removeOnRequest' => true,
			'remove' => function($selected_id) {
				// do nothing: preserve removed files on server.
			},
			'failure' => function($selected_id, $fileRemoved) {
				if($fileRemoved) return '';
				return existing_value('medical_records', 'image_1', $selected_id);
			},
		]),
		'image_2' => Request::fileUpload('image_2', [
			'maxSize' => 1024000,
			'types' => 'jpg|jpeg|gif|png|webp',
			'noRename' => false,
			'dir' => '',
			'id' => $selected_id,
			'success' => function($name, $selected_id) {
				createThumbnail($name, getThumbnailSpecs('medical_records', 'image_2', 'tv'));
				createThumbnail($name, getThumbnailSpecs('medical_records', 'image_2', 'dv'));
			},
			'removeOnRequest' => true,
			'remove' => function($selected_id) {
				// do nothing: preserve removed files on server.
			},
			'failure' => function($selected_id, $fileRemoved) {
				if($fileRemoved) return '';
				return existing_value('medical_records', 'image_2', $selected_id);
			},
		]),
		'image_3' => Request::fileUpload('image_3', [
			'maxSize' => 1024000,
			'types' => 'jpg|jpeg|gif|png|webp',
			'noRename' => false,
			'dir' => '',
			'id' => $selected_id,
			'success' => function($name, $selected_id) {
				createThumbnail($name, getThumbnailSpecs('medical_records', 'image_3', 'tv'));
				createThumbnail($name, getThumbnailSpecs('medical_records', 'image_3', 'dv'));
			},
			'removeOnRequest' => true,
			'remove' => function($selected_id) {
				// do nothing: preserve removed files on server.
			},
			'failure' => function($selected_id, $fileRemoved) {
				if($fileRemoved) return '';
				return existing_value('medical_records', 'image_3', $selected_id);
			},
		]),
		'image_4' => Request::fileUpload('image_4', [
			'maxSize' => 1024000,
			'types' => 'jpg|jpeg|gif|png|webp',
			'noRename' => false,
			'dir' => '',
			'id' => $selected_id,
			'success' => function($name, $selected_id) {
				createThumbnail($name, getThumbnailSpecs('medical_records', 'image_4', 'tv'));
				createThumbnail($name, getThumbnailSpecs('medical_records', 'image_4', 'dv'));
			},
			'removeOnRequest' => true,
			'remove' => function($selected_id) {
				// do nothing: preserve removed files on server.
			},
			'failure' => function($selected_id, $fileRemoved) {
				if($fileRemoved) return '';
				return existing_value('medical_records', 'image_4', $selected_id);
			},
		]),
		'image_5' => Request::fileUpload('image_5', [
			'maxSize' => 1024000,
			'types' => 'jpg|jpeg|gif|png|webp',
			'noRename' => false,
			'dir' => '',
			'id' => $selected_id,
			'success' => function($name, $selected_id) {
				createThumbnail($name, getThumbnailSpecs('medical_records', 'image_5', 'tv'));
				createThumbnail($name, getThumbnailSpecs('medical_records', 'image_5', 'dv'));
			},
			'removeOnRequest' => true,
			'remove' => function($selected_id) {
				// do nothing: preserve removed files on server.
			},
			'failure' => function($selected_id, $fileRemoved) {
				if($fileRemoved) return '';
				return existing_value('medical_records', 'image_5', $selected_id);
			},
		]),
		'document_1' => Request::fileUpload('document_1', [
			'maxSize' => 5120000,
			'types' => 'txt|doc|docx|docm|odt|pdf|rtf',
			'noRename' => false,
			'dir' => '',
			'id' => $selected_id,
			'success' => function($name, $selected_id) {
			},
			'removeOnRequest' => true,
			'remove' => function($selected_id) {
				// do nothing: preserve removed files on server.
			},
			'failure' => function($selected_id, $fileRemoved) {
				if($fileRemoved) return '';
				return existing_value('medical_records', 'document_1', $selected_id);
			},
		]),
		'document_2' => Request::fileUpload('document_2', [
			'maxSize' => 5120000,
			'types' => 'txt|doc|docx|docm|odt|pdf|rtf',
			'noRename' => false,
			'dir' => '',
			'id' => $selected_id,
			'success' => function($name, $selected_id) {
			},
			'removeOnRequest' => true,
			'remove' => function($selected_id) {
				// do nothing: preserve removed files on server.
			},
			'failure' => function($selected_id, $fileRemoved) {
				if($fileRemoved) return '';
				return existing_value('medical_records', 'document_2', $selected_id);
			},
		]),
		'document_3' => Request::fileUpload('document_3', [
			'maxSize' => 5120000,
			'types' => 'txt|doc|docx|docm|odt|pdf|rtf',
			'noRename' => false,
			'dir' => '',
			'id' => $selected_id,
			'success' => function($name, $selected_id) {
			},
			'removeOnRequest' => true,
			'remove' => function($selected_id) {
				// do nothing: preserve removed files on server.
			},
			'failure' => function($selected_id, $fileRemoved) {
				if($fileRemoved) return '';
				return existing_value('medical_records', 'document_3', $selected_id);
			},
		]),
		'document_4' => Request::fileUpload('document_4', [
			'maxSize' => 5120000,
			'types' => 'txt|doc|docx|docm|odt|pdf|rtf',
			'noRename' => false,
			'dir' => '',
			'id' => $selected_id,
			'success' => function($name, $selected_id) {
			},
			'removeOnRequest' => true,
			'remove' => function($selected_id) {
				// do nothing: preserve removed files on server.
			},
			'failure' => function($selected_id, $fileRemoved) {
				if($fileRemoved) return '';
				return existing_value('medical_records', 'document_4', $selected_id);
			},
		]),
		'document_5' => Request::fileUpload('document_5', [
			'maxSize' => 5120000,
			'types' => 'txt|doc|docx|docm|odt|pdf|rtf',
			'noRename' => false,
			'dir' => '',
			'id' => $selected_id,
			'success' => function($name, $selected_id) {
			},
			'removeOnRequest' => true,
			'remove' => function($selected_id) {
				// do nothing: preserve removed files on server.
			},
			'failure' => function($selected_id, $fileRemoved) {
				if($fileRemoved) return '';
				return existing_value('medical_records', 'document_5', $selected_id);
			},
		]),
		'description' => br2nl(Request::val('description', '')),
	];

	// get existing values
	$old_data = getRecord('medical_records', $selected_id);
	if(is_array($old_data)) {
		$old_data = array_map('makeSafe', $old_data);
		$old_data['selectedID'] = makeSafe($selected_id);
	}

	$data['selectedID'] = makeSafe($selected_id);

	// hook: medical_records_before_update
	if(function_exists('medical_records_before_update')) {
		$args = ['old_data' => $old_data];
		if(!medical_records_before_update($data, getMemberInfo(), $args)) {
			if(isset($args['error_message'])) $error_message = $args['error_message'];
			return false;
		}
	}

	$set = $data; unset($set['selectedID']);
	foreach ($set as $field => $value) {
		$set[$field] = ($value !== '' && $value !== NULL) ? $value : NULL;
	}

	if(!update(
		'medical_records', 
		backtick_keys_once($set), 
		['`id`' => $selected_id], 
		$error_message
	)) {
		echo $error_message;
		echo '<a href="medical_records_view.php?SelectedID=' . urlencode($selected_id) . "\">{$Translation['< back']}</a>";
		exit;
	}


	$eo = ['silentErrors' => true];

	update_calc_fields('medical_records', $data['selectedID'], calculated_fields()['medical_records']);

	// hook: medical_records_after_update
	if(function_exists('medical_records_after_update')) {
		$res = sql("SELECT * FROM `medical_records` WHERE `id`='{$data['selectedID']}' LIMIT 1", $eo);
		if($row = db_fetch_assoc($res)) $data = array_map('makeSafe', $row);

		$data['selectedID'] = $data['id'];
		$args = ['old_data' => $old_data];
		if(!medical_records_after_update($data, getMemberInfo(), $args)) return;
	}

	// mm: update ownership data
	sql("UPDATE `membership_userrecords` SET `dateUpdated`='" . time() . "' WHERE `tableName`='medical_records' AND `pkValue`='" . makeSafe($selected_id) . "'", $eo);
}

function medical_records_form($selected_id = '', $AllowUpdate = 1, $AllowInsert = 1, $AllowDelete = 1, $separateDV = 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;
	$eo = ['silentErrors' => true];
	$noUploads = null;
	$row = $urow = $jsReadOnly = $jsEditable = $lookups = null;

	$noSaveAsCopy = false;

	// mm: get table permissions
	$arrPerm = getTablePermissions('medical_records');
	if(!$arrPerm['insert'] && $selected_id == '')
		// no insert permission and no record selected
		// so show access denied error unless TVDV
		return $separateDV ? $Translation['tableAccessDenied'] : '';
	$AllowInsert = ($arrPerm['insert'] ? true : false);
	// print preview?
	$dvprint = false;
	if(strlen($selected_id) && Request::val('dvprint_x') != '') {
		$dvprint = true;
	}

	$filterer_patient = Request::val('filterer_patient');

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

	// unique random identifier
	$rnd1 = ($dvprint ? rand(1000000, 9999999) : '');
	// combobox: patient
	$combo_patient = new DataCombo;

	if($selected_id) {
		if(!check_record_permission('medical_records', $selected_id, 'view'))
			return $Translation['tableAccessDenied'];

		// can edit?
		$AllowUpdate = check_record_permission('medical_records', $selected_id, 'edit');

		// can delete?
		$AllowDelete = check_record_permission('medical_records', $selected_id, 'delete');

		$res = sql("SELECT * FROM `medical_records` WHERE `id`='" . makeSafe($selected_id) . "'", $eo);
		if(!($row = db_fetch_array($res))) {
			return error_message($Translation['No records found'], 'medical_records_view.php', false);
		}
		$combo_patient->SelectedData = $row['patient'];
		$urow = $row; /* unsanitized data */
		$row = array_map('safe_html', $row);
	} else {
		$filterField = Request::val('FilterField');
		$filterOperator = Request::val('FilterOperator');
		$filterValue = Request::val('FilterValue');
		$combo_patient->SelectedData = $filterer_patient;
	}
	$combo_patient->HTML = '<span id="patient-container' . $rnd1 . '"></span><input type="hidden" name="patient" id="patient' . $rnd1 . '" value="' . html_attr($combo_patient->SelectedData) . '">';
	$combo_patient->MatchText = '<span id="patient-container-readonly' . $rnd1 . '"></span><input type="hidden" name="patient" id="patient' . $rnd1 . '" value="' . html_attr($combo_patient->SelectedData) . '">';

	ob_start();
	?>

	<script>
		// initial lookup values
		AppGini.current_patient__RAND__ = { text: "", value: "<?php echo addslashes($selected_id ? $urow['patient'] : htmlspecialchars($filterer_patient, ENT_QUOTES)); ?>"};

		jQuery(function() {
			setTimeout(function() {
				if(typeof(patient_reload__RAND__) == 'function') patient_reload__RAND__();
			}, 50); /* we need to slightly delay client-side execution of the above code to allow AppGini.ajaxCache to work */
		});
		function patient_reload__RAND__() {
		<?php if(($AllowUpdate || $AllowInsert) && !$dvprint) { ?>

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


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


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

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

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

		<?php } else { ?>

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

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

		}
	</script>
	<?php

	$lookups = str_replace('__RAND__', $rnd1, ob_get_clean());


	// code for template based detail view forms

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

	// process form title
	$templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Patient document details', $templateCode);
	$templateCode = str_replace('<%%RND1%%>', $rnd1, $templateCode);
	$templateCode = str_replace('<%%EMBEDDED%%>', (Request::val('Embedded') ? 'Embedded=1' : ''), $templateCode);
	// process buttons
	if($AllowInsert) {
		if(!$selected_id) $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-success" id="insert" name="insert_x" value="1" onclick="return medical_records_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 medical_records_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::val('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::val('Embedded')) $templateCode = str_replace('<%%DVPRINT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="dvprint" name="dvprint_x" value="1" onclick="$j(\'form\').eq(0).prop(\'novalidate\', true); 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 medical_records_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($AllowDelete)
			$templateCode = str_replace('<%%DELETE_BUTTON%%>', '<button type="submit" class="btn btn-danger" id="delete" name="delete_x" value="1" 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);

		// if not in embedded mode and user has insert only but no view/update/delete,
		// remove 'back' button
		if(
			$arrPerm['insert']
			&& !$arrPerm['update'] && !$arrPerm['delete'] && !$arrPerm['view']
			&& !Request::val('Embedded')
		)
			$templateCode = str_replace('<%%DESELECT_BUTTON%%>', '', $templateCode);
		elseif($separateDV)
			$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('<%%DESELECT_BUTTON%%>', '', $templateCode);
	}

	// set records to read only if user can't insert new records and can't edit current record
	if(($selected_id && !$AllowUpdate && !$AllowInsert) || (!$selected_id && !$AllowInsert)) {
		$jsReadOnly = '';
		$jsReadOnly .= "\tjQuery('#image_1').replaceWith('<div class=\"form-control-static\" id=\"image_1\">' + (jQuery('#image_1').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#image_2').replaceWith('<div class=\"form-control-static\" id=\"image_2\">' + (jQuery('#image_2').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#image_3').replaceWith('<div class=\"form-control-static\" id=\"image_3\">' + (jQuery('#image_3').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#image_4').replaceWith('<div class=\"form-control-static\" id=\"image_4\">' + (jQuery('#image_4').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#image_5').replaceWith('<div class=\"form-control-static\" id=\"image_5\">' + (jQuery('#image_5').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#document_1').replaceWith('<div class=\"form-control-static\" id=\"document_1\">' + (jQuery('#document_1').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#document_2').replaceWith('<div class=\"form-control-static\" id=\"document_2\">' + (jQuery('#document_2').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#document_3').replaceWith('<div class=\"form-control-static\" id=\"document_3\">' + (jQuery('#document_3').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#document_4').replaceWith('<div class=\"form-control-static\" id=\"document_4\">' + (jQuery('#document_4').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#document_5').replaceWith('<div class=\"form-control-static\" id=\"document_5\">' + (jQuery('#document_5').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#description').replaceWith('<div class=\"form-control-static\" id=\"description\">' + (jQuery('#description').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('.select2-container').hide();\n";

		$noUploads = true;
	} elseif($AllowInsert) {
		$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(patient)%%>', $combo_patient->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(patient)%%>', $combo_patient->MatchText, $templateCode);
	$templateCode = str_replace('<%%URLCOMBOTEXT(patient)%%>', urlencode($combo_patient->MatchText), $templateCode);

	/* lookup fields array: 'lookup field name' => ['parent table name', 'lookup field caption'] */
	$lookup_fields = ['patient' => ['patients', 'Patient'], ];
	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" 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::val('Embedded')*/) {
			$templateCode = str_replace("<%%ADDNEW({$ptfc[0]})%%>", '<button type="button" class="btn btn-default add_new_parent" id="' . $ptfc[0] . '_add_new" title="' . html_attr($Translation['Add New'] . ' ' . $ptfc[1]) . '"><i class="glyphicon glyphicon-plus text-success"></i></button>', $templateCode);
		}
	}

	// process images
	$templateCode = str_replace('<%%UPLOADFILE(id)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(patient)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(image_1)%%>', ($noUploads ? '' : "<div>{$Translation['upload image']}</div>" . '<input type="file" name="image_1" id="image_1" data-filetypes="jpg|jpeg|gif|png|webp" data-maxsize="1024000" style="max-width: calc(100% - 1.5rem);" accept="capture=camera,image/*">' . '<i class="text-danger clear-upload hidden pull-right" style="margin-top: -.1em; font-size: large;">&times;</i>'), $templateCode);
	if($AllowUpdate && $row['image_1'] != '') {
		$templateCode = str_replace('<%%REMOVEFILE(image_1)%%>', '<input type="checkbox" name="image_1_remove" id="image_1_remove" value="1"> <label for="image_1_remove" style="color: red; font-weight: bold;">'.$Translation['remove image'].'</label>', $templateCode);
	} else {
		$templateCode = str_replace('<%%REMOVEFILE(image_1)%%>', '', $templateCode);
	}
	$templateCode = str_replace('<%%UPLOADFILE(image_2)%%>', ($noUploads ? '' : "<div>{$Translation['upload image']}</div>" . '<input type="file" name="image_2" id="image_2" data-filetypes="jpg|jpeg|gif|png|webp" data-maxsize="1024000" style="max-width: calc(100% - 1.5rem);" accept="capture=camera,image/*">' . '<i class="text-danger clear-upload hidden pull-right" style="margin-top: -.1em; font-size: large;">&times;</i>'), $templateCode);
	if($AllowUpdate && $row['image_2'] != '') {
		$templateCode = str_replace('<%%REMOVEFILE(image_2)%%>', '<input type="checkbox" name="image_2_remove" id="image_2_remove" value="1"> <label for="image_2_remove" style="color: red; font-weight: bold;">'.$Translation['remove image'].'</label>', $templateCode);
	} else {
		$templateCode = str_replace('<%%REMOVEFILE(image_2)%%>', '', $templateCode);
	}
	$templateCode = str_replace('<%%UPLOADFILE(image_3)%%>', ($noUploads ? '' : "<div>{$Translation['upload image']}</div>" . '<input type="file" name="image_3" id="image_3" data-filetypes="jpg|jpeg|gif|png|webp" data-maxsize="1024000" style="max-width: calc(100% - 1.5rem);" accept="capture=camera,image/*">' . '<i class="text-danger clear-upload hidden pull-right" style="margin-top: -.1em; font-size: large;">&times;</i>'), $templateCode);
	if($AllowUpdate && $row['image_3'] != '') {
		$templateCode = str_replace('<%%REMOVEFILE(image_3)%%>', '<input type="checkbox" name="image_3_remove" id="image_3_remove" value="1"> <label for="image_3_remove" style="color: red; font-weight: bold;">'.$Translation['remove image'].'</label>', $templateCode);
	} else {
		$templateCode = str_replace('<%%REMOVEFILE(image_3)%%>', '', $templateCode);
	}
	$templateCode = str_replace('<%%UPLOADFILE(image_4)%%>', ($noUploads ? '' : "<div>{$Translation['upload image']}</div>" . '<input type="file" name="image_4" id="image_4" data-filetypes="jpg|jpeg|gif|png|webp" data-maxsize="1024000" style="max-width: calc(100% - 1.5rem);" accept="capture=camera,image/*">' . '<i class="text-danger clear-upload hidden pull-right" style="margin-top: -.1em; font-size: large;">&times;</i>'), $templateCode);
	if($AllowUpdate && $row['image_4'] != '') {
		$templateCode = str_replace('<%%REMOVEFILE(image_4)%%>', '<input type="checkbox" name="image_4_remove" id="image_4_remove" value="1"> <label for="image_4_remove" style="color: red; font-weight: bold;">'.$Translation['remove image'].'</label>', $templateCode);
	} else {
		$templateCode = str_replace('<%%REMOVEFILE(image_4)%%>', '', $templateCode);
	}
	$templateCode = str_replace('<%%UPLOADFILE(image_5)%%>', ($noUploads ? '' : "<div>{$Translation['upload image']}</div>" . '<input type="file" name="image_5" id="image_5" data-filetypes="jpg|jpeg|gif|png|webp" data-maxsize="1024000" style="max-width: calc(100% - 1.5rem);" accept="capture=camera,image/*">' . '<i class="text-danger clear-upload hidden pull-right" style="margin-top: -.1em; font-size: large;">&times;</i>'), $templateCode);
	if($AllowUpdate && $row['image_5'] != '') {
		$templateCode = str_replace('<%%REMOVEFILE(image_5)%%>', '<input type="checkbox" name="image_5_remove" id="image_5_remove" value="1"> <label for="image_5_remove" style="color: red; font-weight: bold;">'.$Translation['remove image'].'</label>', $templateCode);
	} else {
		$templateCode = str_replace('<%%REMOVEFILE(image_5)%%>', '', $templateCode);
	}
	$templateCode = str_replace('<%%UPLOADFILE(document_1)%%>', ($noUploads ? '' : "<div>{$Translation['upload image']}</div>" . '<input type="file" name="document_1" id="document_1" data-filetypes="txt|doc|docx|docm|odt|pdf|rtf" data-maxsize="5120000" style="max-width: calc(100% - 1.5rem);" accept=".txt,.doc,.docx,.docm,.odt,.pdf,.rtf">' . '<i class="text-danger clear-upload hidden pull-right" style="margin-top: -.1em; font-size: large;">&times;</i>'), $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(document_2)%%>', ($noUploads ? '' : "<div>{$Translation['upload image']}</div>" . '<input type="file" name="document_2" id="document_2" data-filetypes="txt|doc|docx|docm|odt|pdf|rtf" data-maxsize="5120000" style="max-width: calc(100% - 1.5rem);" accept=".txt,.doc,.docx,.docm,.odt,.pdf,.rtf">' . '<i class="text-danger clear-upload hidden pull-right" style="margin-top: -.1em; font-size: large;">&times;</i>'), $templateCode);
	if($AllowUpdate && $row['document_2'] != '') {
		$templateCode = str_replace('<%%REMOVEFILE(document_2)%%>', '<input type="checkbox" name="document_2_remove" id="document_2_remove" value="1"> <label for="document_2_remove" style="color: red; font-weight: bold;">'.$Translation['remove image'].'</label>', $templateCode);
	} else {
		$templateCode = str_replace('<%%REMOVEFILE(document_2)%%>', '', $templateCode);
	}
	$templateCode = str_replace('<%%UPLOADFILE(document_3)%%>', ($noUploads ? '' : "<div>{$Translation['upload image']}</div>" . '<input type="file" name="document_3" id="document_3" data-filetypes="txt|doc|docx|docm|odt|pdf|rtf" data-maxsize="5120000" style="max-width: calc(100% - 1.5rem);" accept=".txt,.doc,.docx,.docm,.odt,.pdf,.rtf">' . '<i class="text-danger clear-upload hidden pull-right" style="margin-top: -.1em; font-size: large;">&times;</i>'), $templateCode);
	if($AllowUpdate && $row['document_3'] != '') {
		$templateCode = str_replace('<%%REMOVEFILE(document_3)%%>', '<input type="checkbox" name="document_3_remove" id="document_3_remove" value="1"> <label for="document_3_remove" style="color: red; font-weight: bold;">'.$Translation['remove image'].'</label>', $templateCode);
	} else {
		$templateCode = str_replace('<%%REMOVEFILE(document_3)%%>', '', $templateCode);
	}
	$templateCode = str_replace('<%%UPLOADFILE(document_4)%%>', ($noUploads ? '' : "<div>{$Translation['upload image']}</div>" . '<input type="file" name="document_4" id="document_4" data-filetypes="txt|doc|docx|docm|odt|pdf|rtf" data-maxsize="5120000" style="max-width: calc(100% - 1.5rem);" accept=".txt,.doc,.docx,.docm,.odt,.pdf,.rtf">' . '<i class="text-danger clear-upload hidden pull-right" style="margin-top: -.1em; font-size: large;">&times;</i>'), $templateCode);
	if($AllowUpdate && $row['document_4'] != '') {
		$templateCode = str_replace('<%%REMOVEFILE(document_4)%%>', '<input type="checkbox" name="document_4_remove" id="document_4_remove" value="1"> <label for="document_4_remove" style="color: red; font-weight: bold;">'.$Translation['remove image'].'</label>', $templateCode);
	} else {
		$templateCode = str_replace('<%%REMOVEFILE(document_4)%%>', '', $templateCode);
	}
	$templateCode = str_replace('<%%UPLOADFILE(document_5)%%>', ($noUploads ? '' : "<div>{$Translation['upload image']}</div>" . '<input type="file" name="document_5" id="document_5" data-filetypes="txt|doc|docx|docm|odt|pdf|rtf" data-maxsize="5120000" style="max-width: calc(100% - 1.5rem);" accept=".txt,.doc,.docx,.docm,.odt,.pdf,.rtf">' . '<i class="text-danger clear-upload hidden pull-right" style="margin-top: -.1em; font-size: large;">&times;</i>'), $templateCode);
	if($AllowUpdate && $row['document_5'] != '') {
		$templateCode = str_replace('<%%REMOVEFILE(document_5)%%>', '<input type="checkbox" name="document_5_remove" id="document_5_remove" value="1"> <label for="document_5_remove" style="color: red; font-weight: bold;">'.$Translation['remove image'].'</label>', $templateCode);
	} else {
		$templateCode = str_replace('<%%REMOVEFILE(document_5)%%>', '', $templateCode);
	}
	$templateCode = str_replace('<%%UPLOADFILE(description)%%>', '', $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);
		$templateCode = str_replace('<%%VALUE(patient)%%>', safe_html($urow['patient']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(patient)%%>', urlencode($urow['patient']), $templateCode);
		$row['image_1'] = ($row['image_1'] != '' ? $row['image_1'] : 'blank.gif');
		if( $dvprint) $templateCode = str_replace('<%%VALUE(image_1)%%>', safe_html($urow['image_1']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(image_1)%%>', html_attr($row['image_1']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(image_1)%%>', urlencode($urow['image_1']), $templateCode);
		$row['image_2'] = ($row['image_2'] != '' ? $row['image_2'] : 'blank.gif');
		if( $dvprint) $templateCode = str_replace('<%%VALUE(image_2)%%>', safe_html($urow['image_2']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(image_2)%%>', html_attr($row['image_2']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(image_2)%%>', urlencode($urow['image_2']), $templateCode);
		$row['image_3'] = ($row['image_3'] != '' ? $row['image_3'] : 'blank.gif');
		if( $dvprint) $templateCode = str_replace('<%%VALUE(image_3)%%>', safe_html($urow['image_3']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(image_3)%%>', html_attr($row['image_3']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(image_3)%%>', urlencode($urow['image_3']), $templateCode);
		$row['image_4'] = ($row['image_4'] != '' ? $row['image_4'] : 'blank.gif');
		if( $dvprint) $templateCode = str_replace('<%%VALUE(image_4)%%>', safe_html($urow['image_4']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(image_4)%%>', html_attr($row['image_4']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(image_4)%%>', urlencode($urow['image_4']), $templateCode);
		$row['image_5'] = ($row['image_5'] != '' ? $row['image_5'] : 'blank.gif');
		if( $dvprint) $templateCode = str_replace('<%%VALUE(image_5)%%>', safe_html($urow['image_5']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(image_5)%%>', html_attr($row['image_5']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(image_5)%%>', urlencode($urow['image_5']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(document_1)%%>', safe_html($urow['document_1']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(document_1)%%>', html_attr($row['document_1']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(document_1)%%>', urlencode($urow['document_1']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(document_2)%%>', safe_html($urow['document_2']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(document_2)%%>', html_attr($row['document_2']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(document_2)%%>', urlencode($urow['document_2']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(document_3)%%>', safe_html($urow['document_3']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(document_3)%%>', html_attr($row['document_3']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(document_3)%%>', urlencode($urow['document_3']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(document_4)%%>', safe_html($urow['document_4']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(document_4)%%>', html_attr($row['document_4']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(document_4)%%>', urlencode($urow['document_4']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(document_5)%%>', safe_html($urow['document_5']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(document_5)%%>', html_attr($row['document_5']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(document_5)%%>', urlencode($urow['document_5']), $templateCode);
		if($dvprint || (!$AllowUpdate && !$AllowInsert)) {
			$templateCode = str_replace('<%%VALUE(description)%%>', safe_html($urow['description']), $templateCode);
		} else {
			$templateCode = str_replace('<%%VALUE(description)%%>', safe_html($urow['description'], true), $templateCode);
		}
		$templateCode = str_replace('<%%URLVALUE(description)%%>', urlencode($urow['description']), $templateCode);
	} else {
		$templateCode = str_replace('<%%VALUE(id)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(id)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(patient)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(patient)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(image_1)%%>', 'blank.gif', $templateCode);
		$templateCode = str_replace('<%%VALUE(image_2)%%>', 'blank.gif', $templateCode);
		$templateCode = str_replace('<%%VALUE(image_3)%%>', 'blank.gif', $templateCode);
		$templateCode = str_replace('<%%VALUE(image_4)%%>', 'blank.gif', $templateCode);
		$templateCode = str_replace('<%%VALUE(image_5)%%>', 'blank.gif', $templateCode);
		$templateCode = str_replace('<%%VALUE(document_1)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(document_1)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(document_2)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(document_2)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(document_3)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(document_3)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(document_4)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(document_4)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(document_5)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(document_5)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(description)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(description)%%>', urlencode(''), $templateCode);
	}

	// process translations
	$templateCode = parseTemplate($templateCode);

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

	// hide links to inaccessible tables
	if(Request::val('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
	$filterField = Request::val('FilterField');
	$filterOperator = Request::val('FilterOperator');
	$filterValue = Request::val('FilterValue');
	if(isset($filterField[1]) && $filterField[1] == '2' && $filterOperator[1] == '<=>')
		$templateCode.="\n<input type=hidden name=patient value=\"" . html_attr($filterValue[1]) . "\">\n";

	// 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('medical_records');
	if($selected_id) {
		$jdata = get_joined_record('medical_records', $selected_id);
		if($jdata === false) $jdata = get_defaults('medical_records');
		$rdata = $row;
	}
	$templateCode .= loadView('medical_records-ajax-cache', ['rdata' => $rdata, 'jdata' => $jdata]);

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

	return $templateCode;
}