<?php

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

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

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

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

	$data = [
		'property_name' => Request::val('property_name', ''),
		'photo' => Request::fileUpload('photo', [
			'maxSize' => 2048000,
			'types' => 'jpg|jpeg|gif|png|webp',
			'noRename' => false,
			'dir' => '',
			'success' => function($name, $selected_id) {
				Thumbnail::create($name, getThumbnailSpecs('properties', 'photo', 'tv'));
				Thumbnail::create($name, getThumbnailSpecs('properties', 'photo', '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('properties', 'photo', Request::val('SelectedID'));
			},
		]),
		'type' => Request::val('type', ''),
		'number_of_units' => Request::val('number_of_units', ''),
		'owner' => Request::lookup('owner', ''),
		'country' => Request::val('country', ''),
		'street' => Request::val('street', ''),
		'City' => Request::val('City', ''),
		'State' => Request::val('State', ''),
		'ZIP' => Request::val('ZIP', ''),
	];

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

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

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

	return $recID;
}

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

	// hook: properties_before_delete
	if(function_exists('properties_before_delete')) {
		$args = [];
		if(!properties_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>'
					: '' 
			);
	}

	// child table: applications_leases
	$res = sql("SELECT `id` FROM `properties` WHERE `id`='{$selected_id}'", $eo);
	$id = db_fetch_row($res);
	$rires = sql("SELECT COUNT(1) FROM `applications_leases` WHERE `property`='" . makeSafe($id[0]) . "'", $eo);
	$rirow = db_fetch_row($rires);
	$childrenATag = '<a class="alert-link" href="applications_leases_view.php?filterer_property=' . urlencode($id[0]) . '">%s</a>';
	if($rirow[0] && !$AllowDeleteOfParents && !$skipChecks) {
		$RetMsg = $Translation["couldn't delete"];
		$RetMsg = str_replace('<RelatedRecords>', sprintf($childrenATag, $rirow[0]), $RetMsg);
		$RetMsg = str_replace(['[<TableName>]', '<TableName>'], sprintf($childrenATag, 'applications_leases'), $RetMsg);
		return $RetMsg;
	} elseif($rirow[0] && $AllowDeleteOfParents && !$skipChecks) {
		$RetMsg = $Translation['confirm delete'];
		$RetMsg = str_replace('<RelatedRecords>', sprintf($childrenATag, $rirow[0]), $RetMsg);
		$RetMsg = str_replace(['[<TableName>]', '<TableName>'], sprintf($childrenATag, 'applications_leases'), $RetMsg);
		$RetMsg = str_replace('<Delete>', '<input type="button" class="btn btn-danger" value="' . html_attr($Translation['yes']) . '" onClick="window.location = `properties_view.php?SelectedID=' . urlencode($selected_id) . '&delete_x=1&confirmed=1&csrf_token=' . urlencode(csrf_token(false, true)) . (Request::val('Embedded') ? '&Embedded=1' : '') . '`;">', $RetMsg);
		$RetMsg = str_replace('<Cancel>', '<input type="button" class="btn btn-success" value="' . html_attr($Translation[ 'no']) . '" onClick="window.location = `properties_view.php?SelectedID=' . urlencode($selected_id) . (Request::val('Embedded') ? '&Embedded=1' : '') . '`;">', $RetMsg);
		return $RetMsg;
	}

	// child table: property_photos
	$res = sql("SELECT `id` FROM `properties` WHERE `id`='{$selected_id}'", $eo);
	$id = db_fetch_row($res);
	$rires = sql("SELECT COUNT(1) FROM `property_photos` WHERE `property`='" . makeSafe($id[0]) . "'", $eo);
	$rirow = db_fetch_row($rires);
	$childrenATag = '<a class="alert-link" href="property_photos_view.php?filterer_property=' . urlencode($id[0]) . '">%s</a>';
	if($rirow[0] && !$AllowDeleteOfParents && !$skipChecks) {
		$RetMsg = $Translation["couldn't delete"];
		$RetMsg = str_replace('<RelatedRecords>', sprintf($childrenATag, $rirow[0]), $RetMsg);
		$RetMsg = str_replace(['[<TableName>]', '<TableName>'], sprintf($childrenATag, 'property_photos'), $RetMsg);
		return $RetMsg;
	} elseif($rirow[0] && $AllowDeleteOfParents && !$skipChecks) {
		$RetMsg = $Translation['confirm delete'];
		$RetMsg = str_replace('<RelatedRecords>', sprintf($childrenATag, $rirow[0]), $RetMsg);
		$RetMsg = str_replace(['[<TableName>]', '<TableName>'], sprintf($childrenATag, 'property_photos'), $RetMsg);
		$RetMsg = str_replace('<Delete>', '<input type="button" class="btn btn-danger" value="' . html_attr($Translation['yes']) . '" onClick="window.location = `properties_view.php?SelectedID=' . urlencode($selected_id) . '&delete_x=1&confirmed=1&csrf_token=' . urlencode(csrf_token(false, true)) . (Request::val('Embedded') ? '&Embedded=1' : '') . '`;">', $RetMsg);
		$RetMsg = str_replace('<Cancel>', '<input type="button" class="btn btn-success" value="' . html_attr($Translation[ 'no']) . '" onClick="window.location = `properties_view.php?SelectedID=' . urlencode($selected_id) . (Request::val('Embedded') ? '&Embedded=1' : '') . '`;">', $RetMsg);
		return $RetMsg;
	}

	// child table: units
	$res = sql("SELECT `id` FROM `properties` WHERE `id`='{$selected_id}'", $eo);
	$id = db_fetch_row($res);
	$rires = sql("SELECT COUNT(1) FROM `units` WHERE `property`='" . makeSafe($id[0]) . "'", $eo);
	$rirow = db_fetch_row($rires);
	$childrenATag = '<a class="alert-link" href="units_view.php?filterer_property=' . urlencode($id[0]) . '">%s</a>';
	if($rirow[0] && !$AllowDeleteOfParents && !$skipChecks) {
		$RetMsg = $Translation["couldn't delete"];
		$RetMsg = str_replace('<RelatedRecords>', sprintf($childrenATag, $rirow[0]), $RetMsg);
		$RetMsg = str_replace(['[<TableName>]', '<TableName>'], sprintf($childrenATag, 'units'), $RetMsg);
		return $RetMsg;
	} elseif($rirow[0] && $AllowDeleteOfParents && !$skipChecks) {
		$RetMsg = $Translation['confirm delete'];
		$RetMsg = str_replace('<RelatedRecords>', sprintf($childrenATag, $rirow[0]), $RetMsg);
		$RetMsg = str_replace(['[<TableName>]', '<TableName>'], sprintf($childrenATag, 'units'), $RetMsg);
		$RetMsg = str_replace('<Delete>', '<input type="button" class="btn btn-danger" value="' . html_attr($Translation['yes']) . '" onClick="window.location = `properties_view.php?SelectedID=' . urlencode($selected_id) . '&delete_x=1&confirmed=1&csrf_token=' . urlencode(csrf_token(false, true)) . (Request::val('Embedded') ? '&Embedded=1' : '') . '`;">', $RetMsg);
		$RetMsg = str_replace('<Cancel>', '<input type="button" class="btn btn-success" value="' . html_attr($Translation[ 'no']) . '" onClick="window.location = `properties_view.php?SelectedID=' . urlencode($selected_id) . (Request::val('Embedded') ? '&Embedded=1' : '') . '`;">', $RetMsg);
		return $RetMsg;
	}

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

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

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

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

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

	$data = [
		'property_name' => Request::val('property_name', ''),
		'photo' => Request::fileUpload('photo', [
			'maxSize' => 2048000,
			'types' => 'jpg|jpeg|gif|png|webp',
			'noRename' => false,
			'dir' => '',
			'id' => $selected_id,
			'success' => function($name, $selected_id) {
				Thumbnail::create($name, getThumbnailSpecs('properties', 'photo', 'tv'));
				Thumbnail::create($name, getThumbnailSpecs('properties', 'photo', '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('properties', 'photo', $selected_id);
			},
		]),
		'type' => Request::val('type', ''),
		'number_of_units' => Request::val('number_of_units', ''),
		'owner' => Request::lookup('owner', ''),
		'country' => Request::val('country', ''),
		'street' => Request::val('street', ''),
		'City' => Request::val('City', ''),
		'State' => Request::val('State', ''),
		'ZIP' => Request::val('ZIP', ''),
	];

	if($data['property_name'] === '') {
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">{$Translation['error:']} 'Property Name': {$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:']} 'Type': {$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('properties', $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: properties_before_update
	if(function_exists('properties_before_update')) {
		$args = ['old_data' => $old_data];
		if(!properties_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(
		'properties', 
		backtick_keys_once($set), 
		['`id`' => $selected_id], 
		$error_message
	)) {
		echo $error_message;
		echo '<a href="properties_view.php?SelectedID=' . urlencode($selected_id) . "\">{$Translation['< back']}</a>";
		exit;
	}


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

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

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

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

function properties_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('properties');
	$allowInsert = ($arrPerm['insert'] ? true : false);
	$allowUpdate = $hasSelectedId && check_record_permission('properties', $selectedId, 'edit');
	$allowDelete = $hasSelectedId && check_record_permission('properties', $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('properties', $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_owner = Request::val('filterer_owner');

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

	// unique random identifier
	$rnd1 = ($dvprint ? rand(1000000, 9999999) : '');
	// 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/properties.type.csv')) {
		$type_data = addslashes(implode('', @file(__DIR__ . '/hooks/properties.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("Residential;;Commercial;;Condo/Townhome;;Multi-Family;;Single-Family;;stores;;office;;shops"))));
		$combo_type->ListData = $combo_type->ListItem;
	}
	$combo_type->SelectName = 'type';
	$combo_type->AllowNull = false;
	// combobox: owner
	$combo_owner = new DataCombo;
	// combobox: operating_account
	$combo_operating_account = new Combo;
	$combo_operating_account->ListType = 0;
	$combo_operating_account->MultipleSeparator = ', ';
	$combo_operating_account->ListBoxHeight = 10;
	$combo_operating_account->RadiosPerLine = 1;
	if(is_file(__DIR__ . '/hooks/properties.operating_account.csv')) {
		$operating_account_data = addslashes(implode('', @file(__DIR__ . '/hooks/properties.operating_account.csv')));
		$combo_operating_account->ListItem = array_trim(explode('||', entitiesToUTF8(convertLegacyOptions($operating_account_data))));
		$combo_operating_account->ListData = $combo_operating_account->ListItem;
	} else {
		$combo_operating_account->ListItem = array_trim(explode('||', entitiesToUTF8(convertLegacyOptions("Operating bank account;;Security deposit bank account"))));
		$combo_operating_account->ListData = $combo_operating_account->ListItem;
	}
	$combo_operating_account->SelectName = 'operating_account';
	// combobox: country
	$combo_country = new Combo;
	$combo_country->ListType = 0;
	$combo_country->MultipleSeparator = ', ';
	$combo_country->ListBoxHeight = 10;
	$combo_country->RadiosPerLine = 1;
	if(is_file(__DIR__ . '/hooks/properties.country.csv')) {
		$country_data = addslashes(implode('', @file(__DIR__ . '/hooks/properties.country.csv')));
		$combo_country->ListItem = array_trim(explode('||', entitiesToUTF8(convertLegacyOptions($country_data))));
		$combo_country->ListData = $combo_country->ListItem;
	} else {
		$combo_country->ListItem = array_trim(explode('||', entitiesToUTF8(convertLegacyOptions("Afghanistan;;Albania;;Algeria;;American Samoa;;Andorra;;Angola;;Anguilla;;Antarctica;;Antigua, Barbuda;;Argentina;;Armenia;;Aruba;;Australia;;Austria;;Azerbaijan;;Bahamas;;Bahrain;;Bangladesh;;Barbados;;Belarus;;Belgium;;Belize;;Benin;;Bermuda;;Bhutan;;Bolivia;;Bosnia, Herzegovina;;Botswana;;Bouvet Is.;;Brazil;;Brunei Darussalam;;Bulgaria;;Burkina Faso;;Burundi;;Cambodia;;Cameroon;;Canada;;Canary Is.;;Cape Verde;;Cayman Is.;;Central African Rep.;;Chad;;Channel Islands;;Chile;;China;;Christmas Is.;;Cocos Is.;;Colombia;;Comoros;;Congo, D.R. Of;;Congo;;Cook Is.;;Costa Rica;;Croatia;;Cuba;;Cyprus;;Czech Republic;;Denmark;;Djibouti;;Dominica;;Dominican Republic;;Ecuador;;Egypt;;El Salvador;;Equatorial Guinea;;Eritrea;;Estonia;;Ethiopia;;Falkland Is.;;Faroe Is.;;Fiji;;Finland;;France;;French Guiana;;French Polynesia;;French Territories;;Gabon;;Gambia;;Georgia;;Germany;;Ghana;;Gibraltar;;Greece;;Greenland;;Grenada;;Guadeloupe;;Guam;;Guatemala;;Guernsey;;Guinea-bissau;;Guinea;;Guyana;;Haiti;;Heard, Mcdonald Is.;;Honduras;;Hong Kong;;Hungary;;Iceland;;India;;Indonesia;;Iran;;Iraq;;Ireland;;Israel;;Italy;;Ivory Coast;;Jamaica;;Japan;;Jersey;;Jordan;;Kazakhstan;;Kenya;;Kiribati;;Korea, D.P.R Of;;Korea, Rep. Of;;Kuwait;;Kyrgyzstan;;Lao Peoples D.R.;;Latvia;;Lebanon;;Lesotho;;Liberia;;Libyan Arab Jamahiriya;;Liechtenstein;;Lithuania;;Luxembourg;;Macao;;Macedonia, F.Y.R Of;;Madagascar;;Malawi;;Malaysia;;Maldives;;Mali;;Malta;;Mariana Islands;;Marshall Islands;;Martinique;;Mauritania;;Mauritius;;Mayotte;;Mexico;;Micronesia;;Moldova;;Monaco;;Mongolia;;Montserrat;;Morocco;;Mozambique;;Myanmar;;Namibia;;Nauru;;Nepal;;Netherlands Antilles;;Netherlands;;New Caledonia;;New Zealand;;Nicaragua;;Niger;;Nigeria;;Niue;;Norfolk Island;;Norway;;Oman;;Pakistan;;Palau;;Palestinian Terr.;;Panama;;Papua New Guinea;;Paraguay;;Peru;;Philippines;;Pitcairn;;Poland;;Portugal;;Puerto Rico;;Qatar;;Reunion;;Romania;;Russian Federation;;Rwanda;;Samoa;;San Marino;;Sao Tome, Principe;;Saudi Arabia;;Senegal;;Seychelles;;Sierra Leone;;Singapore;;Slovakia;;Slovenia;;Solomon Is.;;Somalia;;South Africa;;South Georgia;;South Sandwich Is.;;Spain;;Sri Lanka;;St. Helena;;St. Kitts, Nevis;;St. Lucia;;St. Pierre, Miquelon;;St. Vincent, Grenadines;;Sudan;;Suriname;;Svalbard, Jan Mayen;;Swaziland;;Sweden;;Switzerland;;Syrian Arab Republic;;Taiwan;;Tajikistan;;Tanzania;;Thailand;;Timor-leste;;Togo;;Tokelau;;Tonga;;Trinidad, Tobago;;Tunisia;;Turkey;;Turkmenistan;;Turks, Caicoss;;Tuvalu;;Uganda;;Ukraine;;United Arab Emirates;;United Kingdom;;United States;;Uruguay;;Uzbekistan;;Vanuatu;;Vatican City;;Venezuela;;Viet Nam;;Virgin Is. British;;Virgin Is. U.S.;;Wallis, Futuna;;Western Sahara;;Yemen;;Yugoslavia;;Zambia;;Zimbabwe"))));
		$combo_country->ListData = $combo_country->ListItem;
	}
	$combo_country->SelectName = 'country';
	// combobox: State
	$combo_State = new Combo;
	$combo_State->ListType = 0;
	$combo_State->MultipleSeparator = ', ';
	$combo_State->ListBoxHeight = 10;
	$combo_State->RadiosPerLine = 1;
	if(is_file(__DIR__ . '/hooks/properties.State.csv')) {
		$State_data = addslashes(implode('', @file(__DIR__ . '/hooks/properties.State.csv')));
		$combo_State->ListItem = array_trim(explode('||', entitiesToUTF8(convertLegacyOptions($State_data))));
		$combo_State->ListData = $combo_State->ListItem;
	} else {
		$combo_State->ListItem = array_trim(explode('||', entitiesToUTF8(convertLegacyOptions("AL;;AK;;AS;;AZ;;AR;;CA;;CO;;CT;;DE;;DC;;FM;;FL;;GA;;GU;;HI;;ID;;IL;;IN;;IA;;KS;;KY;;LA;;ME;;MH;;MD;;MA;;MI;;MN;;MS;;MO;;MT;;NE;;NV;;NH;;NJ;;NM;;NY;;NC;;ND;;MP;;OH;;OK;;OR;;PW;;PA;;PR;;RI;;SC;;SD;;TN;;TX;;UT;;VT;;VI;;VA;;WA;;WV;;WI;;WY"))));
		$combo_State->ListData = $combo_State->ListItem;
	}
	$combo_State->SelectName = 'State';

	if($hasSelectedId) {
		if(!($row = getRecord('properties', $selectedId))) {
			return error_message($Translation['No records found'], 'properties_view.php', false);
		}
		$combo_type->SelectedData = $row['type'];
		$combo_owner->SelectedData = $row['owner'];
		$combo_operating_account->SelectedData = $row['operating_account'];
		$combo_country->SelectedData = $row['country'];
		$combo_State->SelectedData = $row['State'];
		$urow = $row; /* unsanitized data */
		$row = array_map('safe_html', $row);
	} else {
		$filterField = Request::val('FilterField');
		$filterOperator = Request::val('FilterOperator');
		$filterValue = Request::val('FilterValue');
		$combo_type->SelectedText = (isset($filterField[1]) && $filterField[1] == '4' && $filterOperator[1] == '<=>' ? $filterValue[1] : entitiesToUTF8(''));
		$combo_owner->SelectedData = $filterer_owner;
		$combo_operating_account->SelectedText = (isset($filterField[1]) && $filterField[1] == '7' && $filterOperator[1] == '<=>' ? $filterValue[1] : entitiesToUTF8(''));
		$combo_country->SelectedText = (isset($filterField[1]) && $filterField[1] == '10' && $filterOperator[1] == '<=>' ? $filterValue[1] : entitiesToUTF8(''));
		$combo_State->SelectedText = (isset($filterField[1]) && $filterField[1] == '13' && $filterOperator[1] == '<=>' ? $filterValue[1] : entitiesToUTF8(''));
	}
	$combo_type->Render();
	$combo_owner->HTML = '<span id="owner-container' . $rnd1 . '"></span><input type="hidden" name="owner" id="owner' . $rnd1 . '" value="' . html_attr($combo_owner->SelectedData) . '">';
	$combo_owner->MatchText = '<span id="owner-container-readonly' . $rnd1 . '"></span><input type="hidden" name="owner" id="owner' . $rnd1 . '" value="' . html_attr($combo_owner->SelectedData) . '">';
	$combo_operating_account->Render();
	$combo_country->Render();
	$combo_State->Render();

	ob_start();
	?>

	<script>
		// initial lookup values
		AppGini.current_owner__RAND__ = { text: "", value: "<?php echo addslashes($hasSelectedId ? $urow['owner'] : htmlspecialchars($filterer_owner, ENT_QUOTES)); ?>"};

		$j(function() {
			setTimeout(function() {
				if(typeof(owner_reload__RAND__) == 'function') owner_reload__RAND__();
			}, 50); /* we need to slightly delay client-side execution of the above code to allow AppGini.ajaxCache to work */
		});
		function owner_reload__RAND__() {
		<?php if($fieldsAreEditable) { ?>

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


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


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

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

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

		<?php } else { ?>

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

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

	// process form title
	$templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Property details', $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('#property_name').replaceWith('<div class=\"form-control-static\" id=\"property_name\">' + (\$j('#property_name').val() || '') + '</div>');\n";
		$jsReadOnly .= "\t\$j('#photo').replaceWith('<div class=\"form-control-static\" id=\"photo\">' + (\$j('#photo').val() || '') + '</div>');\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('#number_of_units').replaceWith('<div class=\"form-control-static\" id=\"number_of_units\">' + (\$j('#number_of_units').val() || '') + '</div>');\n";
		$jsReadOnly .= "\t\$j('#owner').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\t\$j('#owner_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
		$jsReadOnly .= "\t\$j('#country').replaceWith('<div class=\"form-control-static\" id=\"country\">' + (\$j('#country').val() || '') + '</div>'); \$j('#country-multi-selection-help').hide();\n";
		$jsReadOnly .= "\t\$j('#street').replaceWith('<div class=\"form-control-static\" id=\"street\">' + (\$j('#street').val() || '') + '</div>');\n";
		$jsReadOnly .= "\t\$j('#City').replaceWith('<div class=\"form-control-static\" id=\"City\">' + (\$j('#City').val() || '') + '</div>');\n";
		$jsReadOnly .= "\t\$j('#State').replaceWith('<div class=\"form-control-static\" id=\"State\">' + (\$j('#State').val() || '') + '</div>'); \$j('#State-multi-selection-help').hide();\n";
		$jsReadOnly .= "\t\$j('#ZIP').replaceWith('<div class=\"form-control-static\" id=\"ZIP\">' + (\$j('#ZIP').val() || '') + '</div>');\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(type)%%>', $combo_type->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(type)%%>', $combo_type->SelectedData, $templateCode);
	$templateCode = str_replace('<%%COMBO(owner)%%>', $combo_owner->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(owner)%%>', $combo_owner->MatchText, $templateCode);
	$templateCode = str_replace('<%%URLCOMBOTEXT(owner)%%>', urlencode($combo_owner->MatchText), $templateCode);
	$templateCode = str_replace('<%%COMBO(operating_account)%%>', $combo_operating_account->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(operating_account)%%>', $combo_operating_account->SelectedData, $templateCode);
	$templateCode = str_replace('<%%COMBO(country)%%>', $combo_country->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(country)%%>', $combo_country->SelectedData, $templateCode);
	$templateCode = str_replace('<%%COMBO(State)%%>', $combo_State->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(State)%%>', $combo_State->SelectedData, $templateCode);

	/* lookup fields array: 'lookup field name' => ['parent table name', 'lookup field caption'] */
	$lookup_fields = ['owner' => ['rental_owners', 'Owner'], ];
	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(property_name)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(photo)%%>', ($noUploads ? '' : "<div>{$Translation['upload image']}</div>" . '<input type="file" name="photo" id="photo" data-filetypes="jpg|jpeg|gif|png|webp" data-maxsize="2048000" 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['photo'] != '') {
		$templateCode = str_replace('<%%REMOVEFILE(photo)%%>', '<input type="checkbox" name="photo_remove" id="photo_remove" value="1"> <label for="photo_remove" style="color: red; font-weight: bold;">'.$Translation['remove image'].'</label>', $templateCode);
	} else {
		$templateCode = str_replace('<%%REMOVEFILE(photo)%%>', '', $templateCode);
	}
	$templateCode = str_replace('<%%UPLOADFILE(type)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(number_of_units)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(owner)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(operating_account)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(property_reserve)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(lease_term)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(country)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(street)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(City)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(State)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(ZIP)%%>', '', $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(property_name)%%>', safe_html($urow['property_name']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(property_name)%%>', html_attr($row['property_name']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(property_name)%%>', urlencode($urow['property_name']), $templateCode);
		$row['photo'] = ($row['photo'] != '' ? $row['photo'] : 'blank.gif');
		if( $dvprint) $templateCode = str_replace('<%%VALUE(photo)%%>', safe_html($urow['photo']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(photo)%%>', html_attr($row['photo']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(photo)%%>', urlencode($urow['photo']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(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(number_of_units)%%>', safe_html($urow['number_of_units']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(number_of_units)%%>', html_attr($row['number_of_units']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(number_of_units)%%>', urlencode($urow['number_of_units']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(owner)%%>', safe_html($urow['owner']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(owner)%%>', html_attr($row['owner']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(owner)%%>', urlencode($urow['owner']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(operating_account)%%>', safe_html($urow['operating_account']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(operating_account)%%>', html_attr($row['operating_account']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(operating_account)%%>', urlencode($urow['operating_account']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(property_reserve)%%>', safe_html($urow['property_reserve']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(property_reserve)%%>', html_attr($row['property_reserve']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(property_reserve)%%>', urlencode($urow['property_reserve']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(lease_term)%%>', safe_html($urow['lease_term']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(lease_term)%%>', html_attr($row['lease_term']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(lease_term)%%>', urlencode($urow['lease_term']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(country)%%>', safe_html($urow['country']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(country)%%>', html_attr($row['country']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(country)%%>', urlencode($urow['country']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(street)%%>', safe_html($urow['street']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(street)%%>', html_attr($row['street']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(street)%%>', urlencode($urow['street']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(City)%%>', safe_html($urow['City']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(City)%%>', html_attr($row['City']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(City)%%>', urlencode($urow['City']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(State)%%>', safe_html($urow['State']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(State)%%>', html_attr($row['State']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(State)%%>', urlencode($urow['State']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(ZIP)%%>', safe_html($urow['ZIP']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(ZIP)%%>', html_attr($row['ZIP']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(ZIP)%%>', urlencode($urow['ZIP']), $templateCode);
	} else {
		$templateCode = str_replace('<%%VALUE(id)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(id)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(property_name)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(property_name)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(photo)%%>', 'blank.gif', $templateCode);
		$templateCode = str_replace('<%%VALUE(type)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(type)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(number_of_units)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(number_of_units)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(owner)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(owner)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(operating_account)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(operating_account)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(property_reserve)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(property_reserve)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(lease_term)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(lease_term)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(country)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(country)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(street)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(street)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(City)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(City)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(State)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(State)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(ZIP)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(ZIP)%%>', urlencode(''), $templateCode);
	}

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

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

	return $templateCode;
}