<?php

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

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

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

	// mm: can member insert record?
	$arrPerm = getTablePermissions('applications_leases');
	if(!$arrPerm['insert']) {
		$error_message = $Translation['no insert permission'];
		return false;
	}

	$data = [
		'tenants' => Request::lookup('tenants', ''),
		'status' => Request::val('status', 'Application'),
		'property' => Request::lookup('property', ''),
		'unit' => Request::lookup('unit', ''),
		'type' => Request::val('type', 'Fixed'),
		'total_number_of_occupants' => Request::val('total_number_of_occupants', ''),
		'start_date' => Request::dateComponents('start_date', '1'),
		'end_date' => Request::dateComponents('end_date', '1'),
		'recurring_charges_frequency' => Request::val('recurring_charges_frequency', 'Monthly'),
		'next_due_date' => Request::dateComponents('next_due_date', '1'),
		'rent' => Request::val('rent', ''),
		'security_deposit' => Request::val('security_deposit', ''),
		'security_deposit_date' => Request::dateComponents('security_deposit_date', ''),
		'emergency_contact' => br2nl(Request::val('emergency_contact', '')),
		'co_signer_details' => br2nl(Request::val('co_signer_details', '')),
		'notes' => Request::val('notes', ''),
		'agreement' => Request::checkBox('agreement', ''),
	];

	// record owner is current user
	$recordOwner = getLoggedMemberID();

	$recID = tableInsert('applications_leases', $data, $recordOwner, $error_message);

	// if this record is a copy of another record, copy children if applicable
	if(strlen(Request::val('SelectedID')) && $recID !== false)
		applications_leases_copy_children($recID, Request::val('SelectedID'));

	return $recID;
}

function applications_leases_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);
	$currentUsername = getLoggedMemberID();
	$errorMessage = '';

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

function applications_leases_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('applications_leases', $selected_id, 'delete')) {
		return $Translation['You don\'t have enough permissions to delete this record'];
	}

	// hook: applications_leases_before_delete
	if(function_exists('applications_leases_before_delete')) {
		$args = [];
		if(!applications_leases_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 `applications_leases` WHERE `id`='{$selected_id}'", $eo);

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

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

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

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

	$data = [
		'tenants' => Request::lookup('tenants', ''),
		'status' => Request::val('status', ''),
		'property' => Request::lookup('property', ''),
		'unit' => Request::lookup('unit', ''),
		'type' => Request::val('type', ''),
		'total_number_of_occupants' => Request::val('total_number_of_occupants', ''),
		'start_date' => Request::dateComponents('start_date', ''),
		'end_date' => Request::dateComponents('end_date', ''),
		'recurring_charges_frequency' => Request::val('recurring_charges_frequency', ''),
		'next_due_date' => Request::dateComponents('next_due_date', ''),
		'rent' => Request::val('rent', ''),
		'security_deposit' => Request::val('security_deposit', ''),
		'security_deposit_date' => Request::dateComponents('security_deposit_date', ''),
		'emergency_contact' => br2nl(Request::val('emergency_contact', '')),
		'co_signer_details' => br2nl(Request::val('co_signer_details', '')),
		'notes' => Request::val('notes', ''),
		'agreement' => Request::checkBox('agreement', ''),
	];

	if($data['status'] === '') {
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">{$Translation['error:']} 'Application status': {$Translation['field not null']}<br><br>";
		echo '<a href="" onclick="history.go(-1); return false;">' . $Translation['< back'] . '</a></div>';
		exit;
	}
	if($data['type'] === '') {
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">{$Translation['error:']} 'Lease type': {$Translation['field not null']}<br><br>";
		echo '<a href="" onclick="history.go(-1); return false;">' . $Translation['< back'] . '</a></div>';
		exit;
	}
	if($data['recurring_charges_frequency'] === '') {
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">{$Translation['error:']} 'Recurring charges frequency': {$Translation['field not null']}<br><br>";
		echo '<a href="" onclick="history.go(-1); return false;">' . $Translation['< back'] . '</a></div>';
		exit;
	}
	// get existing values
	$old_data = getRecord('applications_leases', $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: applications_leases_before_update
	if(function_exists('applications_leases_before_update')) {
		$args = ['old_data' => $old_data];
		if(!applications_leases_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(
		'applications_leases',
		backtick_keys_once($set),
		['`id`' => $selected_id],
		$error_message
	)) {
		echo $error_message;
		echo '<a href="applications_leases_view.php?SelectedID=' . urlencode($selected_id) . "\">{$Translation['< back']}</a>";
		exit;
	}


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

	// hook: applications_leases_after_update
	if(function_exists('applications_leases_after_update')) {
		if($row = getRecord('applications_leases', $data['selectedID'])) $data = array_map('makeSafe', $row);

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

	// mm: update record update timestamp
	set_record_owner('applications_leases', $selected_id);
}

function applications_leases_form($selectedId = '', $allowUpdate = true, $allowInsert = true, $allowDelete = true, $separateDV = true, $templateDV = '', $templateDVP = '') {
	// function to return an editable form for a table records
	// and fill it with data of record whose ID is $selectedId. If $selectedId
	// is empty, an empty form is shown, with only an 'Add New'
	// button displayed.

	global $Translation;
	$eo = ['silentErrors' => true];
	$noUploads = $row = $urow = $jsReadOnly = $jsEditable = $lookups = null;
	$noSaveAsCopy = false;
	$hasSelectedId = strlen($selectedId) > 0;

	// mm: get table permissions
	$arrPerm = getTablePermissions('applications_leases');
	$allowInsert = ($arrPerm['insert'] ? true : false);
	$allowUpdate = $hasSelectedId && check_record_permission('applications_leases', $selectedId, 'edit');
	$allowDelete = $hasSelectedId && check_record_permission('applications_leases', $selectedId, 'delete');

	if(!$allowInsert && !$hasSelectedId)
		// no insert permission and no record selected
		// so show access denied error -- except if TVDV: just hide DV
		return $separateDV ? $Translation['tableAccessDenied'] : '';

	if($hasSelectedId && !check_record_permission('applications_leases', $selectedId, 'view'))
		return $Translation['tableAccessDenied'];

	// print preview?
	$dvprint = $hasSelectedId && Request::val('dvprint_x') != '';

	$showSaveNew = !$dvprint && ($allowInsert && !$hasSelectedId);
	$showSaveChanges = !$dvprint && $allowUpdate && $hasSelectedId;
	$showDelete = !$dvprint && $allowDelete && $hasSelectedId;
	$showSaveAsCopy = !$dvprint && ($allowInsert && $hasSelectedId && !$noSaveAsCopy);
	$fieldsAreEditable = !$dvprint && (($allowInsert && !$hasSelectedId) || ($allowUpdate && $hasSelectedId) || $showSaveAsCopy);

	$filterer_tenants = Request::val('filterer_tenants');
	$filterer_property = Request::val('filterer_property');
	$filterer_unit = Request::val('filterer_unit');

	// populate filterers, starting from children to grand-parents
	if($filterer_unit && !$filterer_property) $filterer_property = sqlValue("select property from units where id='" . makeSafe($filterer_unit) . "'");

	// unique random identifier
	$rnd1 = ($dvprint ? rand(1000000, 9999999) : '');
	// combobox: tenants
	$combo_tenants = new DataCombo;
	// combobox: status
	$combo_status = new Combo;
	$combo_status->ListType = 2;
	$combo_status->MultipleSeparator = ', ';
	$combo_status->ListBoxHeight = 10;
	$combo_status->RadiosPerLine = 1;
	if(is_file(__DIR__ . '/hooks/applications_leases.status.csv')) {
		$status_data = addslashes(implode('', @file(__DIR__ . '/hooks/applications_leases.status.csv')));
		$combo_status->ListItem = array_trim(explode('||', entitiesToUTF8(convertLegacyOptions($status_data))));
		$combo_status->ListData = $combo_status->ListItem;
	} else {
		$combo_status->ListItem = array_trim(explode('||', entitiesToUTF8(convertLegacyOptions("Application;;Lease;;Historical lease"))));
		$combo_status->ListData = $combo_status->ListItem;
	}
	$combo_status->SelectName = 'status';
	$combo_status->AllowNull = false;
	// combobox: property
	$combo_property = new DataCombo;
	// combobox: unit, filterable by: property
	$combo_unit = new DataCombo;
	// combobox: type
	$combo_type = new Combo;
	$combo_type->ListType = 2;
	$combo_type->MultipleSeparator = ', ';
	$combo_type->ListBoxHeight = 10;
	$combo_type->RadiosPerLine = 1;
	if(is_file(__DIR__ . '/hooks/applications_leases.type.csv')) {
		$type_data = addslashes(implode('', @file(__DIR__ . '/hooks/applications_leases.type.csv')));
		$combo_type->ListItem = array_trim(explode('||', entitiesToUTF8(convertLegacyOptions($type_data))));
		$combo_type->ListData = $combo_type->ListItem;
	} else {
		$combo_type->ListItem = array_trim(explode('||', entitiesToUTF8(convertLegacyOptions("Fixed;;Fixed with rollover;;At-will"))));
		$combo_type->ListData = $combo_type->ListItem;
	}
	$combo_type->SelectName = 'type';
	$combo_type->AllowNull = false;
	// combobox: start_date
	$combo_start_date = new DateCombo;
	$combo_start_date->DateFormat = "mdy";
	$combo_start_date->MinYear = defined('applications_leases.start_date.MinYear') ? constant('applications_leases.start_date.MinYear') : 1900;
	$combo_start_date->MaxYear = defined('applications_leases.start_date.MaxYear') ? constant('applications_leases.start_date.MaxYear') : 2100;
	$combo_start_date->DefaultDate = parseMySQLDate('1', '1');
	$combo_start_date->MonthNames = $Translation['month names'];
	$combo_start_date->NamePrefix = 'start_date';
	// combobox: end_date
	$combo_end_date = new DateCombo;
	$combo_end_date->DateFormat = "mdy";
	$combo_end_date->MinYear = defined('applications_leases.end_date.MinYear') ? constant('applications_leases.end_date.MinYear') : 1900;
	$combo_end_date->MaxYear = defined('applications_leases.end_date.MaxYear') ? constant('applications_leases.end_date.MaxYear') : 2100;
	$combo_end_date->DefaultDate = parseMySQLDate('1', '1');
	$combo_end_date->MonthNames = $Translation['month names'];
	$combo_end_date->NamePrefix = 'end_date';
	// combobox: recurring_charges_frequency
	$combo_recurring_charges_frequency = new Combo;
	$combo_recurring_charges_frequency->ListType = 0;
	$combo_recurring_charges_frequency->MultipleSeparator = ', ';
	$combo_recurring_charges_frequency->ListBoxHeight = 10;
	$combo_recurring_charges_frequency->RadiosPerLine = 1;
	if(is_file(__DIR__ . '/hooks/applications_leases.recurring_charges_frequency.csv')) {
		$recurring_charges_frequency_data = addslashes(implode('', @file(__DIR__ . '/hooks/applications_leases.recurring_charges_frequency.csv')));
		$combo_recurring_charges_frequency->ListItem = array_trim(explode('||', entitiesToUTF8(convertLegacyOptions($recurring_charges_frequency_data))));
		$combo_recurring_charges_frequency->ListData = $combo_recurring_charges_frequency->ListItem;
	} else {
		$combo_recurring_charges_frequency->ListItem = array_trim(explode('||', entitiesToUTF8(convertLegacyOptions("Daily;;Weekly;;Every two weeks;;Monthly;;Every two months;;Quarterly;;Every six months;;Yearly;;One time"))));
		$combo_recurring_charges_frequency->ListData = $combo_recurring_charges_frequency->ListItem;
	}
	$combo_recurring_charges_frequency->SelectName = 'recurring_charges_frequency';
	$combo_recurring_charges_frequency->AllowNull = false;
	// combobox: next_due_date
	$combo_next_due_date = new DateCombo;
	$combo_next_due_date->DateFormat = "mdy";
	$combo_next_due_date->MinYear = defined('applications_leases.next_due_date.MinYear') ? constant('applications_leases.next_due_date.MinYear') : 1900;
	$combo_next_due_date->MaxYear = defined('applications_leases.next_due_date.MaxYear') ? constant('applications_leases.next_due_date.MaxYear') : 2100;
	$combo_next_due_date->DefaultDate = parseMySQLDate('1', '1');
	$combo_next_due_date->MonthNames = $Translation['month names'];
	$combo_next_due_date->NamePrefix = 'next_due_date';
	// combobox: security_deposit_date
	$combo_security_deposit_date = new DateCombo;
	$combo_security_deposit_date->DateFormat = "mdy";
	$combo_security_deposit_date->MinYear = defined('applications_leases.security_deposit_date.MinYear') ? constant('applications_leases.security_deposit_date.MinYear') : 1900;
	$combo_security_deposit_date->MaxYear = defined('applications_leases.security_deposit_date.MaxYear') ? constant('applications_leases.security_deposit_date.MaxYear') : 2100;
	$combo_security_deposit_date->DefaultDate = parseMySQLDate('', '');
	$combo_security_deposit_date->MonthNames = $Translation['month names'];
	$combo_security_deposit_date->NamePrefix = 'security_deposit_date';

	if($hasSelectedId) {
		if(!($row = getRecord('applications_leases', $selectedId))) {
			return error_message($Translation['No records found'], 'applications_leases_view.php', false);
		}
		$combo_tenants->SelectedData = $row['tenants'];
		$combo_status->SelectedData = $row['status'];
		$combo_property->SelectedData = $row['property'];
		$combo_unit->SelectedData = $row['unit'];
		$combo_type->SelectedData = $row['type'];
		$combo_start_date->DefaultDate = $row['start_date'];
		$combo_end_date->DefaultDate = $row['end_date'];
		$combo_recurring_charges_frequency->SelectedData = $row['recurring_charges_frequency'];
		$combo_next_due_date->DefaultDate = $row['next_due_date'];
		$combo_security_deposit_date->DefaultDate = $row['security_deposit_date'];
		$urow = $row; /* unsanitized data */
		$row = array_map('safe_html', $row);
	} else {
		$filterField = Request::val('FilterField');
		$filterOperator = Request::val('FilterOperator');
		$filterValue = Request::val('FilterValue');
		$combo_tenants->SelectedData = $filterer_tenants;
		$combo_status->SelectedText = (isset($filterField[1]) && $filterField[1] == '3' && $filterOperator[1] == '<=>' ? $filterValue[1] : entitiesToUTF8('Application'));
		$combo_property->SelectedData = $filterer_property;
		$combo_unit->SelectedData = $filterer_unit;
		$combo_type->SelectedText = (isset($filterField[1]) && $filterField[1] == '6' && $filterOperator[1] == '<=>' ? $filterValue[1] : entitiesToUTF8('Fixed'));
		$combo_recurring_charges_frequency->SelectedText = (isset($filterField[1]) && $filterField[1] == '10' && $filterOperator[1] == '<=>' ? $filterValue[1] : entitiesToUTF8('Monthly'));
	}
	$combo_tenants->HTML = '<span id="tenants-container' . $rnd1 . '"></span><input type="hidden" name="tenants" id="tenants' . $rnd1 . '" value="' . html_attr($combo_tenants->SelectedData) . '">';
	$combo_tenants->MatchText = '<span id="tenants-container-readonly' . $rnd1 . '"></span><input type="hidden" name="tenants" id="tenants' . $rnd1 . '" value="' . html_attr($combo_tenants->SelectedData) . '">';
	$combo_status->Render();
	$combo_property->HTML = '<span id="property-container' . $rnd1 . '"></span><input type="hidden" name="property" id="property' . $rnd1 . '" value="' . html_attr($combo_property->SelectedData) . '">';
	$combo_property->MatchText = '<span id="property-container-readonly' . $rnd1 . '"></span><input type="hidden" name="property" id="property' . $rnd1 . '" value="' . html_attr($combo_property->SelectedData) . '">';
	$combo_unit->HTML = '<span id="unit-container' . $rnd1 . '"></span><input type="hidden" name="unit" id="unit' . $rnd1 . '" value="' . html_attr($combo_unit->SelectedData) . '">';
	$combo_unit->MatchText = '<span id="unit-container-readonly' . $rnd1 . '"></span><input type="hidden" name="unit" id="unit' . $rnd1 . '" value="' . html_attr($combo_unit->SelectedData) . '">';
	$combo_type->Render();
	$combo_recurring_charges_frequency->Render();

	ob_start();
	?>

	<script>
		// initial lookup values
		AppGini.current_tenants__RAND__ = { text: "", value: "<?php echo addslashes($hasSelectedId ? $urow['tenants'] : htmlspecialchars($filterer_tenants, ENT_QUOTES)); ?>"};
		AppGini.current_property__RAND__ = { text: "", value: "<?php echo addslashes($hasSelectedId ? $urow['property'] : htmlspecialchars($filterer_property, ENT_QUOTES)); ?>"};
		AppGini.current_unit__RAND__ = { text: "", value: "<?php echo addslashes($hasSelectedId ? $urow['unit'] : htmlspecialchars($filterer_unit, ENT_QUOTES)); ?>"};

		$j(function() {
			setTimeout(function() {
				if(typeof(tenants_reload__RAND__) == 'function') tenants_reload__RAND__();
				if(typeof(property_reload__RAND__) == 'function') property_reload__RAND__();
				<?php echo (!$allowUpdate || $dvprint ? 'if(typeof(unit_reload__RAND__) == \'function\') unit_reload__RAND__(AppGini.current_property__RAND__.value);' : ''); ?>
			}, 50); /* we need to slightly delay client-side execution of the above code to allow AppGini.ajaxCache to work */
		});
		function tenants_reload__RAND__() {
		<?php if($fieldsAreEditable) { ?>

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


							if(typeof(tenants_update_autofills__RAND__) == 'function') tenants_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: 'applications_leases', f: 'tenants' }; },
					results: function(resp, page) { return resp; }
				},
				escapeMarkup: function(str) { return str; }
			}).on('change', function(e) {
				AppGini.current_tenants__RAND__.value = e.added.id;
				AppGini.current_tenants__RAND__.text = e.added.text;
				$j('[name="tenants"]').val(e.added.id);
				if(e.added.id == '<?php echo empty_lookup_value; ?>') { $j('.btn[id=applicants_and_tenants_view_parent]').hide(); } else { $j('.btn[id=applicants_and_tenants_view_parent]').show(); }


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

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

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

		<?php } else { ?>

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

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

		}
		function property_reload__RAND__() {
		<?php if($fieldsAreEditable) { ?>

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

						if(typeof(unit_reload__RAND__) == 'function') unit_reload__RAND__(AppGini.current_property__RAND__.value);

							if(typeof(property_update_autofills__RAND__) == 'function') property_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: 'applications_leases', f: 'property' }; },
					results: function(resp, page) { return resp; }
				},
				escapeMarkup: function(str) { return str; }
			}).on('change', function(e) {
				AppGini.current_property__RAND__.value = e.added.id;
				AppGini.current_property__RAND__.text = e.added.text;
				$j('[name="property"]').val(e.added.id);
				if(e.added.id == '<?php echo empty_lookup_value; ?>') { $j('.btn[id=properties_view_parent]').hide(); } else { $j('.btn[id=properties_view_parent]').show(); }

						if(typeof(unit_reload__RAND__) == 'function') unit_reload__RAND__(AppGini.current_property__RAND__.value);

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

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

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

		<?php } else { ?>

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

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

		}
		function unit_reload__RAND__(filterer_property) {
		<?php if($fieldsAreEditable) { ?>

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


							if(typeof(unit_update_autofills__RAND__) == 'function') unit_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 { filterer_property: filterer_property, s: term, p: page, t: 'applications_leases', f: 'unit' }; },
					results: function(resp, page) { return resp; }
				},
				escapeMarkup: function(str) { return str; }
			}).on('change', function(e) {
				AppGini.current_unit__RAND__.value = e.added.id;
				AppGini.current_unit__RAND__.text = e.added.text;
				$j('[name="unit"]').val(e.added.id);
				if(e.added.id == '<?php echo empty_lookup_value; ?>') { $j('.btn[id=units_view_parent]').hide(); } else { $j('.btn[id=units_view_parent]').show(); }


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

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

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

		<?php } else { ?>

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

					if(typeof(unit_update_autofills__RAND__) == 'function') unit_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/applications_leases_templateDVP.html';
		$templateCode = @file_get_contents($template_file);
	} else {
		$template_file = is_file("./{$templateDV}") ? "./{$templateDV}" : './templates/applications_leases_templateDV.html';
		$templateCode = @file_get_contents($template_file);
	}

	// process form title
	$templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Application/Lease Info', $templateCode);
	$templateCode = str_replace('<%%RND1%%>', $rnd1, $templateCode);
	$templateCode = str_replace('<%%EMBEDDED%%>', (Request::val('Embedded') ? 'Embedded=1' : ''), $templateCode);
	// process buttons
	if($showSaveNew) {
		$templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-success" id="insert" name="insert_x" value="1"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save New'] . '</button>', $templateCode);
	} elseif($showSaveAsCopy) {
		$templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="insert" name="insert_x" value="1"><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 = 'return true;';
	}

	if($hasSelectedId) {
		if(!Request::val('Embedded')) $templateCode = str_replace('<%%DVPRINT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="dvprint" name="dvprint_x" value="1" 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" 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(
			$allowInsert
			&& !$allowUpdate && !$allowDelete && !$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(!$fieldsAreEditable) {
		$jsReadOnly = '';
		$jsReadOnly .= "\t\$j('#tenants').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\t\$j('#tenants_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
		$jsReadOnly .= "\t\$j('input[name=status]').parent().html('<div class=\"form-control-static\">' + \$j('input[name=status]:checked').next().text() + '</div>')\n";
		$jsReadOnly .= "\t\$j('#property').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\t\$j('#property_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
		$jsReadOnly .= "\t\$j('#unit').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\t\$j('#unit_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
		$jsReadOnly .= "\t\$j('input[name=type]').parent().html('<div class=\"form-control-static\">' + \$j('input[name=type]:checked').next().text() + '</div>')\n";
		$jsReadOnly .= "\t\$j('#total_number_of_occupants').replaceWith('<div class=\"form-control-static\" id=\"total_number_of_occupants\">' + (\$j('#total_number_of_occupants').val() || '') + '</div>');\n";
		$jsReadOnly .= "\t\$j('#start_date').prop('readonly', true);\n";
		$jsReadOnly .= "\t\$j('#start_dateDay, #start_dateMonth, #start_dateYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\t\$j('#end_date').prop('readonly', true);\n";
		$jsReadOnly .= "\t\$j('#end_dateDay, #end_dateMonth, #end_dateYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\t\$j('#recurring_charges_frequency').replaceWith('<div class=\"form-control-static\" id=\"recurring_charges_frequency\">' + (\$j('#recurring_charges_frequency').val() || '') + '</div>'); \$j('#recurring_charges_frequency-multi-selection-help').hide();\n";
		$jsReadOnly .= "\t\$j('#next_due_date').prop('readonly', true);\n";
		$jsReadOnly .= "\t\$j('#next_due_dateDay, #next_due_dateMonth, #next_due_dateYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\t\$j('#rent').replaceWith('<div class=\"form-control-static\" id=\"rent\">' + (\$j('#rent').val() || '') + '</div>');\n";
		$jsReadOnly .= "\t\$j('#security_deposit').replaceWith('<div class=\"form-control-static\" id=\"security_deposit\">' + (\$j('#security_deposit').val() || '') + '</div>');\n";
		$jsReadOnly .= "\t\$j('#security_deposit_date').prop('readonly', true);\n";
		$jsReadOnly .= "\t\$j('#security_deposit_dateDay, #security_deposit_dateMonth, #security_deposit_dateYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\t\$j('#emergency_contact').replaceWith('<div class=\"form-control-static\" id=\"emergency_contact\">' + (\$j('#emergency_contact').val() || '') + '</div>');\n";
		$jsReadOnly .= "\t\$j('#co_signer_details').replaceWith('<div class=\"form-control-static\" id=\"co_signer_details\">' + (\$j('#co_signer_details').val() || '') + '</div>');\n";
		$jsReadOnly .= "\t\$j('#agreement').prop('disabled', true);\n";
		$jsReadOnly .= "\t\$j('.select2-container').hide();\n";

		$noUploads = true;
	} else {
		// temporarily disable form change handler till time and datetime pickers are enabled
		$jsEditable = "\t\$j('form').eq(0).data('already_changed', true);";
		$jsEditable .= "\t\$j('form').eq(0).data('already_changed', false);"; // re-enable form change handler
	}

	// process combos
	$templateCode = str_replace('<%%COMBO(tenants)%%>', $combo_tenants->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(tenants)%%>', $combo_tenants->MatchText, $templateCode);
	$templateCode = str_replace('<%%URLCOMBOTEXT(tenants)%%>', urlencode($combo_tenants->MatchText), $templateCode);
	$templateCode = str_replace('<%%COMBO(status)%%>', $combo_status->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(status)%%>', $combo_status->SelectedData, $templateCode);
	$templateCode = str_replace('<%%COMBO(property)%%>', $combo_property->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(property)%%>', $combo_property->MatchText, $templateCode);
	$templateCode = str_replace('<%%URLCOMBOTEXT(property)%%>', urlencode($combo_property->MatchText), $templateCode);
	$templateCode = str_replace('<%%COMBO(unit)%%>', $combo_unit->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(unit)%%>', $combo_unit->MatchText, $templateCode);
	$templateCode = str_replace('<%%URLCOMBOTEXT(unit)%%>', urlencode($combo_unit->MatchText), $templateCode);
	$templateCode = str_replace('<%%COMBO(type)%%>', $combo_type->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(type)%%>', $combo_type->SelectedData, $templateCode);
	$templateCode = str_replace(
		'<%%COMBO(start_date)%%>',
		(!$fieldsAreEditable ?
			'<div class="form-control-static">' . $combo_start_date->GetHTML(true) . '</div>' :
			$combo_start_date->GetHTML()
		), $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(start_date)%%>', $combo_start_date->GetHTML(true), $templateCode);
	$templateCode = str_replace(
		'<%%COMBO(end_date)%%>',
		(!$fieldsAreEditable ?
			'<div class="form-control-static">' . $combo_end_date->GetHTML(true) . '</div>' :
			$combo_end_date->GetHTML()
		), $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(end_date)%%>', $combo_end_date->GetHTML(true), $templateCode);
	$templateCode = str_replace('<%%COMBO(recurring_charges_frequency)%%>', $combo_recurring_charges_frequency->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(recurring_charges_frequency)%%>', $combo_recurring_charges_frequency->SelectedData, $templateCode);
	$templateCode = str_replace(
		'<%%COMBO(next_due_date)%%>',
		(!$fieldsAreEditable ?
			'<div class="form-control-static">' . $combo_next_due_date->GetHTML(true) . '</div>' :
			$combo_next_due_date->GetHTML()
		), $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(next_due_date)%%>', $combo_next_due_date->GetHTML(true), $templateCode);
	$templateCode = str_replace(
		'<%%COMBO(security_deposit_date)%%>',
		(!$fieldsAreEditable ?
			'<div class="form-control-static">' . $combo_security_deposit_date->GetHTML(true) . '</div>' :
			$combo_security_deposit_date->GetHTML()
		), $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(security_deposit_date)%%>', $combo_security_deposit_date->GetHTML(true), $templateCode);

	/* lookup fields array: 'lookup field name' => ['parent table name', 'lookup field caption'] */
	$lookup_fields = ['tenants' => ['applicants_and_tenants', 'Applicant/ Tenant'], 'property' => ['properties', 'Property'], 'unit' => ['units', 'Unit applied for'], ];
	foreach($lookup_fields as $luf => $ptfc) {
		$pt_perm = getTablePermissions($ptfc[0]);

		// process foreign key links
		if(($pt_perm['view'] && isDetailViewEnabled($ptfc[0])) || $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(tenants)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(status)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(property)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(unit)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(type)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(total_number_of_occupants)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(start_date)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(end_date)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(recurring_charges_frequency)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(next_due_date)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(rent)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(security_deposit)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(security_deposit_date)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(emergency_contact)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(co_signer_details)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(notes)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(agreement)%%>', '', $templateCode);

	// process values
	if($hasSelectedId) {
		if( $dvprint) $templateCode = str_replace('<%%VALUE(id)%%>', safe_html($urow['id']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(id)%%>', html_attr($row['id']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(id)%%>', urlencode($urow['id']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(tenants)%%>', safe_html($urow['tenants']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(tenants)%%>', html_attr($row['tenants']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(tenants)%%>', urlencode($urow['tenants']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(status)%%>', safe_html($urow['status']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(status)%%>', html_attr($row['status']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(status)%%>', urlencode($urow['status']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(property)%%>', safe_html($urow['property']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(property)%%>', html_attr($row['property']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(property)%%>', urlencode($urow['property']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(unit)%%>', safe_html($urow['unit']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(unit)%%>', html_attr($row['unit']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(unit)%%>', urlencode($urow['unit']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(type)%%>', safe_html($urow['type']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(type)%%>', html_attr($row['type']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(type)%%>', urlencode($urow['type']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(total_number_of_occupants)%%>', safe_html($urow['total_number_of_occupants']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(total_number_of_occupants)%%>', html_attr($row['total_number_of_occupants']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(total_number_of_occupants)%%>', urlencode($urow['total_number_of_occupants']), $templateCode);
		$templateCode = str_replace('<%%VALUE(start_date)%%>', app_datetime($row['start_date']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(start_date)%%>', urlencode(app_datetime($urow['start_date'])), $templateCode);
		$templateCode = str_replace('<%%VALUE(end_date)%%>', app_datetime($row['end_date']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(end_date)%%>', urlencode(app_datetime($urow['end_date'])), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(recurring_charges_frequency)%%>', safe_html($urow['recurring_charges_frequency']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(recurring_charges_frequency)%%>', html_attr($row['recurring_charges_frequency']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(recurring_charges_frequency)%%>', urlencode($urow['recurring_charges_frequency']), $templateCode);
		$templateCode = str_replace('<%%VALUE(next_due_date)%%>', app_datetime($row['next_due_date']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(next_due_date)%%>', urlencode(app_datetime($urow['next_due_date'])), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(rent)%%>', safe_html($urow['rent']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(rent)%%>', html_attr($row['rent']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(rent)%%>', urlencode($urow['rent']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(security_deposit)%%>', safe_html($urow['security_deposit']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(security_deposit)%%>', html_attr($row['security_deposit']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(security_deposit)%%>', urlencode($urow['security_deposit']), $templateCode);
		$templateCode = str_replace('<%%VALUE(security_deposit_date)%%>', app_datetime($row['security_deposit_date']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(security_deposit_date)%%>', urlencode(app_datetime($urow['security_deposit_date'])), $templateCode);
		$templateCode = str_replace('<%%VALUE(emergency_contact)%%>', safe_html($urow['emergency_contact'], $fieldsAreEditable), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(emergency_contact)%%>', urlencode($urow['emergency_contact']), $templateCode);
		$templateCode = str_replace('<%%VALUE(co_signer_details)%%>', safe_html($urow['co_signer_details'], $fieldsAreEditable), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(co_signer_details)%%>', urlencode($urow['co_signer_details']), $templateCode);
		if($fieldsAreEditable) {
			$templateCode = str_replace('<%%HTMLAREA(notes)%%>', '<textarea maxlength="65500" name="notes" id="notes" rows="5">' . safe_html(htmlspecialchars_decode($row['notes'])) . '</textarea>', $templateCode);
		} else {
			$templateCode = str_replace('<%%HTMLAREA(notes)%%>', '<div id="notes" class="form-control-static">' . $row['notes'] . '</div>', $templateCode);
		}
		$templateCode = str_replace('<%%VALUE(notes)%%>', nl2br($row['notes']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(notes)%%>', urlencode($urow['notes']), $templateCode);
		$templateCode = str_replace('<%%CHECKED(agreement)%%>', ($row['agreement'] ? "checked" : ""), $templateCode);
	} else {
		$templateCode = str_replace('<%%VALUE(id)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(id)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(tenants)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(tenants)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(status)%%>', 'Application', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(status)%%>', urlencode('Application'), $templateCode);
		$templateCode = str_replace('<%%VALUE(property)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(property)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(unit)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(unit)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(type)%%>', 'Fixed', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(type)%%>', urlencode('Fixed'), $templateCode);
		$templateCode = str_replace('<%%VALUE(total_number_of_occupants)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(total_number_of_occupants)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(start_date)%%>', '1', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(start_date)%%>', urlencode('1'), $templateCode);
		$templateCode = str_replace('<%%VALUE(end_date)%%>', '1', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(end_date)%%>', urlencode('1'), $templateCode);
		$templateCode = str_replace('<%%VALUE(recurring_charges_frequency)%%>', 'Monthly', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(recurring_charges_frequency)%%>', urlencode('Monthly'), $templateCode);
		$templateCode = str_replace('<%%VALUE(next_due_date)%%>', '1', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(next_due_date)%%>', urlencode('1'), $templateCode);
		$templateCode = str_replace('<%%VALUE(rent)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(rent)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(security_deposit)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(security_deposit)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(security_deposit_date)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(security_deposit_date)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(emergency_contact)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(emergency_contact)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(co_signer_details)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(co_signer_details)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%HTMLAREA(notes)%%>', '<textarea maxlength="65500" name="notes" id="notes" rows="5"></textarea>', $templateCode);
		$templateCode = str_replace('<%%CHECKED(agreement)%%>', '', $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(!$hasSelectedId) {
		}

		$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');

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

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

	return $templateCode;
}