<?php

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

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

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

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

	$data = [
		'datum' => Request::dateComponents('datum', '1'),
		'beginn' => Request::val('beginn', ''),
		'ende' => Request::val('ende', ''),
		'pilot' => parseCode('<%%creatorUsername%%>', true),
		'anzahl_fluege' => Request::val('anzahl_fluege', ''),
		'max_flughoehe' => Request::val('max_flughoehe', ''),
		'flugplatz' => Request::lookup('flugplatz', ''),
		'modell' => Request::val('modell', ''),
		'besonderheiten' => br2nl(Request::val('besonderheiten', '')),
		'gastpilot' => Request::checkBox('gastpilot', ''),
		'name_gastpilot' => Request::val('name_gastpilot', ''),
		'mfbo' => Request::lookup('mfbo', ''),
		'reg_nr' => Request::val('reg_nr', ''),
		'fluege' => Request::val('fluege', ''),
		'hoehe' => Request::val('hoehe', ''),
		'datei' => Request::fileUpload('datei', [
			'maxSize' => 2560000,
			'types' => 'jpg|jpeg|gif|png|webp',
			'noRename' => false,
			'dir' => '',
			'success' => function($name, $selected_id) {
			},
			'failure' => function($selected_id, $fileRemoved) {
				if(!strlen(Request::val('SelectedID'))) return '';

				/* for empty upload fields, when saving a copy of an existing record, copy the original upload field */
				return existing_value('flugbuch_verein', 'datei', Request::val('SelectedID'));
			},
		]),
		'datei_1' => Request::fileUpload('datei_1', [
			'maxSize' => 2560000,
			'types' => 'doc|docx|docm|odt|pdf|xls|xlsx|zip|jpg|jpeg|gif|png',
			'noRename' => false,
			'dir' => '',
			'success' => function($name, $selected_id) {
			},
			'failure' => function($selected_id, $fileRemoved) {
				if(!strlen(Request::val('SelectedID'))) return '';

				/* for empty upload fields, when saving a copy of an existing record, copy the original upload field */
				return existing_value('flugbuch_verein', 'datei_1', Request::val('SelectedID'));
			},
		]),
		'erfasser' => parseCode('<%%creatorUsername%%>', true),
		'erfasst' => parseCode('<%%creationDateTime%%>', true, true),
	];

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

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

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

	return $recID;
}

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

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

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

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

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

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

	$data = [
		'datum' => Request::dateComponents('datum', ''),
		'beginn' => Request::val('beginn', ''),
		'ende' => Request::val('ende', ''),
		'anzahl_fluege' => Request::val('anzahl_fluege', ''),
		'max_flughoehe' => Request::val('max_flughoehe', ''),
		'flugplatz' => Request::lookup('flugplatz', ''),
		'modell' => Request::val('modell', ''),
		'besonderheiten' => br2nl(Request::val('besonderheiten', '')),
		'gastpilot' => Request::checkBox('gastpilot', ''),
		'name_gastpilot' => Request::val('name_gastpilot', ''),
		'mfbo' => Request::lookup('mfbo', ''),
		'reg_nr' => Request::val('reg_nr', ''),
		'fluege' => Request::val('fluege', ''),
		'hoehe' => Request::val('hoehe', ''),
		'datei' => Request::fileUpload('datei', [
			'maxSize' => 2560000,
			'types' => 'jpg|jpeg|gif|png|webp',
			'noRename' => false,
			'dir' => '',
			'id' => $selected_id,
			'success' => function($name, $selected_id) {
			},
			'removeOnRequest' => true,
			'remove' => function($selected_id) {
				// do nothing: preserve removed files on server.
			},
			'failure' => function($selected_id, $fileRemoved) {
				if($fileRemoved) return '';
				return existing_value('flugbuch_verein', 'datei', $selected_id);
			},
		]),
		'datei_1' => Request::fileUpload('datei_1', [
			'maxSize' => 2560000,
			'types' => 'doc|docx|docm|odt|pdf|xls|xlsx|zip|jpg|jpeg|gif|png',
			'noRename' => false,
			'dir' => '',
			'id' => $selected_id,
			'success' => function($name, $selected_id) {
			},
			'removeOnRequest' => true,
			'remove' => function($selected_id) {
				// do nothing: preserve removed files on server.
			},
			'failure' => function($selected_id, $fileRemoved) {
				if($fileRemoved) return '';
				return existing_value('flugbuch_verein', 'datei_1', $selected_id);
			},
		]),
		'geaendert_von' => parseCode('<%%editorUsername%%>', false),
		'geaendert' => parseCode('<%%editingDateTime%%>', false, true),
	];

	if($data['datum'] === '') {
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">{$Translation['error:']} 'Datum': {$Translation['field not null']}<br><br>";
		echo '<a href="" onclick="history.go(-1); return false;">' . $Translation['< back'] . '</a></div>';
		exit;
	}
	if($data['beginn'] === '') {
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">{$Translation['error:']} 'Beginn': {$Translation['field not null']}<br><br>";
		echo '<a href="" onclick="history.go(-1); return false;">' . $Translation['< back'] . '</a></div>';
		exit;
	}
	if($data['ende'] === '') {
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">{$Translation['error:']} 'Ende': {$Translation['field not null']}<br><br>";
		echo '<a href="" onclick="history.go(-1); return false;">' . $Translation['< back'] . '</a></div>';
		exit;
	}
	if($data['anzahl_fluege'] === '') {
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">{$Translation['error:']} 'Anzahl der Fl&#252;ge': {$Translation['field not null']}<br><br>";
		echo '<a href="" onclick="history.go(-1); return false;">' . $Translation['< back'] . '</a></div>';
		exit;
	}
	if($data['max_flughoehe'] === '') {
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">{$Translation['error:']} 'maximale Flugh&#246;he': {$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('flugbuch_verein', $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: flugbuch_verein_before_update
	if(function_exists('flugbuch_verein_before_update')) {
		$args = ['old_data' => $old_data];
		if(!flugbuch_verein_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(
		'flugbuch_verein',
		backtick_keys_once($set),
		['`id`' => $selected_id],
		$error_message
	)) {
		echo $error_message;
		echo '<a href="flugbuch_verein_view.php?SelectedID=' . urlencode($selected_id) . "\">{$Translation['< back']}</a>";
		exit;
	}


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

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

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

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

function flugbuch_verein_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 = true;
	$hasSelectedId = strlen($selectedId) > 0;

	// mm: get table permissions
	$arrPerm = getTablePermissions('flugbuch_verein');
	$allowInsert = ($arrPerm['insert'] ? true : false);
	$allowUpdate = $hasSelectedId && check_record_permission('flugbuch_verein', $selectedId, 'edit');
	$allowDelete = $hasSelectedId && check_record_permission('flugbuch_verein', $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('flugbuch_verein', $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_flugplatz = Request::val('filterer_flugplatz');
	$filterer_mfbo = Request::val('filterer_mfbo');

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

	// unique random identifier
	$rnd1 = ($dvprint ? rand(1000000, 9999999) : '');
	// combobox: datum
	$combo_datum = new DateCombo;
	$combo_datum->DateFormat = "dmy";
	$combo_datum->MinYear = defined('flugbuch_verein.datum.MinYear') ? constant('flugbuch_verein.datum.MinYear') : 1900;
	$combo_datum->MaxYear = defined('flugbuch_verein.datum.MaxYear') ? constant('flugbuch_verein.datum.MaxYear') : 2100;
	$combo_datum->DefaultDate = parseMySQLDate('1', '1');
	$combo_datum->MonthNames = $Translation['month names'];
	$combo_datum->NamePrefix = 'datum';
	// combobox: flugplatz
	$combo_flugplatz = new DataCombo;
	// combobox: mfbo
	$combo_mfbo = new DataCombo;

	if($hasSelectedId) {
		if(!($row = getRecord('flugbuch_verein', $selectedId))) {
			return error_message($Translation['No records found'], 'flugbuch_verein_view.php', false);
		}
		$combo_datum->DefaultDate = $row['datum'];
		$combo_flugplatz->SelectedData = $row['flugplatz'];
		$combo_mfbo->SelectedData = $row['mfbo'];
		$urow = $row; /* unsanitized data */
		$row = array_map('safe_html', $row);
	} else {
		$filterField = Request::val('FilterField');
		$filterOperator = Request::val('FilterOperator');
		$filterValue = Request::val('FilterValue');
		$combo_flugplatz->SelectedData = $filterer_flugplatz;
		$combo_mfbo->SelectedData = $filterer_mfbo;
	}
	$combo_flugplatz->HTML = '<span id="flugplatz-container' . $rnd1 . '"></span><input type="hidden" name="flugplatz" id="flugplatz' . $rnd1 . '" value="' . html_attr($combo_flugplatz->SelectedData) . '">';
	$combo_flugplatz->MatchText = '<span id="flugplatz-container-readonly' . $rnd1 . '"></span><input type="hidden" name="flugplatz" id="flugplatz' . $rnd1 . '" value="' . html_attr($combo_flugplatz->SelectedData) . '">';
	$combo_mfbo->HTML = '<span id="mfbo-container' . $rnd1 . '"></span><input type="hidden" name="mfbo" id="mfbo' . $rnd1 . '" value="' . html_attr($combo_mfbo->SelectedData) . '">';
	$combo_mfbo->MatchText = '<span id="mfbo-container-readonly' . $rnd1 . '"></span><input type="hidden" name="mfbo" id="mfbo' . $rnd1 . '" value="' . html_attr($combo_mfbo->SelectedData) . '">';

	ob_start();
	?>

	<script>
		// initial lookup values
		AppGini.current_flugplatz__RAND__ = { text: "", value: "<?php echo addslashes($hasSelectedId ? $urow['flugplatz'] : htmlspecialchars($filterer_flugplatz, ENT_QUOTES)); ?>"};
		AppGini.current_mfbo__RAND__ = { text: "", value: "<?php echo addslashes($hasSelectedId ? $urow['mfbo'] : htmlspecialchars($filterer_mfbo, ENT_QUOTES)); ?>"};

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

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


							if(typeof(flugplatz_update_autofills__RAND__) == 'function') flugplatz_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: 'flugbuch_verein', f: 'flugplatz' }; },
					results: function(resp, page) { return resp; }
				},
				escapeMarkup: function(str) { return str; }
			}).on('change', function(e) {
				AppGini.current_flugplatz__RAND__.value = e.added.id;
				AppGini.current_flugplatz__RAND__.text = e.added.text;
				$j('[name="flugplatz"]').val(e.added.id);
				$j(this).parents('.form-group')
					.find('.btn[id=flugplaetze_oe_view_parent]')
					.toggleClass('hidden', e.added.id == '<?php echo empty_lookup_value; ?>');


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

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

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

		<?php } else { ?>

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

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

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

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


							if(typeof(mfbo_update_autofills__RAND__) == 'function') mfbo_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: 'flugbuch_verein', f: 'mfbo' }; },
					results: function(resp, page) { return resp; }
				},
				escapeMarkup: function(str) { return str; }
			}).on('change', function(e) {
				AppGini.current_mfbo__RAND__.value = e.added.id;
				AppGini.current_mfbo__RAND__.text = e.added.text;
				$j('[name="mfbo"]').val(e.added.id);
				$j(this).parents('.form-group')
					.find('.btn[id=mfbo_view_parent]')
					.toggleClass('hidden', e.added.id == '<?php echo empty_lookup_value; ?>');


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

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

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

		<?php } else { ?>

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

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

	// process form title
	$templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Flugbucheintrag', $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 ltr" 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 ltr"
					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('#datum').prop('readonly', true);\n";
		$jsReadOnly .= "\t\$j('#datumDay, #datumMonth, #datumYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\t\$j('#beginn').replaceWith('<div class=\"form-control-static\" id=\"beginn\">' + (\$j('#beginn').val() || '') + '</div>');\n";
		$jsReadOnly .= "\t\$j('#ende').replaceWith('<div class=\"form-control-static\" id=\"ende\">' + (\$j('#ende').val() || '') + '</div>');\n";
		$jsReadOnly .= "\t\$j('#anzahl_fluege').replaceWith('<div class=\"form-control-static\" id=\"anzahl_fluege\">' + (\$j('#anzahl_fluege').val() || '') + '</div>');\n";
		$jsReadOnly .= "\t\$j('#max_flughoehe').replaceWith('<div class=\"form-control-static\" id=\"max_flughoehe\">' + (\$j('#max_flughoehe').val() || '') + '</div>');\n";
		$jsReadOnly .= "\t\$j('#flugplatz').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\t\$j('#flugplatz_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
		$jsReadOnly .= "\t\$j('#modell').replaceWith('<div class=\"form-control-static\" id=\"modell\">' + (\$j('#modell').val() || '') + '</div>');\n";
		$jsReadOnly .= "\t\$j('#besonderheiten').replaceWith('<div class=\"form-control-static\" id=\"besonderheiten\">' + (\$j('#besonderheiten').val() || '') + '</div>');\n";
		$jsReadOnly .= "\t\$j('#gastpilot').prop('disabled', true);\n";
		$jsReadOnly .= "\t\$j('#name_gastpilot').replaceWith('<div class=\"form-control-static\" id=\"name_gastpilot\">' + (\$j('#name_gastpilot').val() || '') + '</div>');\n";
		$jsReadOnly .= "\t\$j('#mfbo').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\t\$j('#mfbo_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
		$jsReadOnly .= "\t\$j('#reg_nr').replaceWith('<div class=\"form-control-static\" id=\"reg_nr\">' + (\$j('#reg_nr').val() || '') + '</div>');\n";
		$jsReadOnly .= "\t\$j('#fluege').replaceWith('<div class=\"form-control-static\" id=\"fluege\">' + (\$j('#fluege').val() || '') + '</div>');\n";
		$jsReadOnly .= "\t\$j('#hoehe').replaceWith('<div class=\"form-control-static\" id=\"hoehe\">' + (\$j('#hoehe').val() || '') + '</div>');\n";
		$jsReadOnly .= "\t\$j('#datei').parent().replaceWith(`<div class=\"form-control-static\" id=\"datei\">\${\$j('#datei').val() || ''}\${\$j('#datei').val() ? '<a target=\"_blank\" class=\"hspacer-lg\" href=\"' + \$j('#datei').val() + '\" target=\"_blank\"><i class=\"glyphicon glyphicon-globe\"></i></a>' : ''}</div>`);\n";
		$jsReadOnly .= "\t\$j('#datei_1').parent().replaceWith(`<div class=\"form-control-static\" id=\"datei_1\">\${\$j('#datei_1').val() || ''}\${\$j('#datei_1').val() ? '<a target=\"_blank\" class=\"hspacer-lg\" href=\"' + \$j('#datei_1').val() + '\" target=\"_blank\"><i class=\"glyphicon glyphicon-globe\"></i></a>' : ''}</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('#beginn').addClass('always_shown').timepicker({ defaultTime: false, showSeconds: false, showMeridian: false, showInputs: false, disableFocus: true, minuteStep: AppGini.config.timeFieldMinutesStep || 5 });";
		$jsEditable .= "\t\$j('#ende').addClass('always_shown').timepicker({ defaultTime: false, showSeconds: false, showMeridian: false, showInputs: false, disableFocus: true, minuteStep: AppGini.config.timeFieldMinutesStep || 5 });";
		$jsEditable .= "\t\$j('form').eq(0).data('already_changed', false);"; // re-enable form change handler
	}

	// process combos
	$templateCode = str_replace(
		'<%%COMBO(datum)%%>',
		(!$fieldsAreEditable ?
			'<div class="form-control-static">' . $combo_datum->GetHTML(true) . '</div>' :
			$combo_datum->GetHTML()
		), $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(datum)%%>', $combo_datum->GetHTML(true), $templateCode);
	$templateCode = str_replace('<%%COMBO(flugplatz)%%>', $combo_flugplatz->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(flugplatz)%%>', $combo_flugplatz->MatchText, $templateCode);
	$templateCode = str_replace('<%%URLCOMBOTEXT(flugplatz)%%>', urlencode($combo_flugplatz->MatchText), $templateCode);
	$templateCode = str_replace('<%%COMBO(mfbo)%%>', $combo_mfbo->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(mfbo)%%>', $combo_mfbo->MatchText, $templateCode);
	$templateCode = str_replace('<%%URLCOMBOTEXT(mfbo)%%>', urlencode($combo_mfbo->MatchText), $templateCode);

	/* lookup fields array: 'lookup field name' => ['parent table name', 'lookup field caption'] */
	$lookup_fields = ['flugplatz' => ['flugplaetze_oe', 'Flugplatz'], 'mfbo' => ['mfbo', 'MFBO gelesen JA/NEIN'], ];
	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(datum)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(beginn)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(ende)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(pilot)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(anzahl_fluege)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(max_flughoehe)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(flugplatz)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(luftraumbeobachter_anwesend)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(modell)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(besonderheiten)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(gastpilot)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(name_gastpilot)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(mfbo)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(reg_nr)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(fluege)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(lrb)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(hoehe)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(datei)%%>', ($noUploads ? '' : "<div>{$Translation['upload image']}</div>" . '<input type="file" name="datei" id="datei" data-filetypes="jpg|jpeg|gif|png|webp" data-maxsize="2560000" style="max-width: calc(100% - 1.5rem);" accept=".jpg,.jpeg,.gif,.png,.webp">' . '<i class="text-danger clear-upload hidden pull-right" style="margin-top: -.1em; font-size: large;">&times;</i>'), $templateCode);
	if($allowUpdate && $row['datei'] != '') {
		$templateCode = str_replace('<%%REMOVEFILE(datei)%%>', '<input type="checkbox" name="datei_remove" id="datei_remove" value="1"> <label for="datei_remove" style="color: red; font-weight: bold;">'.$Translation['remove image'].'</label>', $templateCode);
	} else {
		$templateCode = str_replace('<%%REMOVEFILE(datei)%%>', '', $templateCode);
	}
	$templateCode = str_replace('<%%UPLOADFILE(datei_1)%%>', ($noUploads ? '' : "<div>{$Translation['upload image']}</div>" . '<input type="file" name="datei_1" id="datei_1" data-filetypes="doc|docx|docm|odt|pdf|xls|xlsx|zip|jpg|jpeg|gif|png" data-maxsize="2560000" style="max-width: calc(100% - 1.5rem);" accept=".doc,.docx,.docm,.odt,.pdf,.xls,.xlsx,.zip,.jpg,.jpeg,.gif,.png">' . '<i class="text-danger clear-upload hidden pull-right" style="margin-top: -.1em; font-size: large;">&times;</i>'), $templateCode);
	if($allowUpdate && $row['datei_1'] != '') {
		$templateCode = str_replace('<%%REMOVEFILE(datei_1)%%>', '<input type="checkbox" name="datei_1_remove" id="datei_1_remove" value="1"> <label for="datei_1_remove" style="color: red; font-weight: bold;">'.$Translation['remove image'].'</label>', $templateCode);
	} else {
		$templateCode = str_replace('<%%REMOVEFILE(datei_1)%%>', '', $templateCode);
	}
	$templateCode = str_replace('<%%UPLOADFILE(erfasser)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(erfasst)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(geaendert_von)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(geaendert)%%>', '', $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);
		$templateCode = str_replace('<%%VALUE(datum)%%>', app_datetime($row['datum']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(datum)%%>', urlencode(app_datetime($urow['datum'])), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(beginn)%%>', safe_html($urow['beginn']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(beginn)%%>', html_attr($row['beginn']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(beginn)%%>', urlencode($urow['beginn']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(ende)%%>', safe_html($urow['ende']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(ende)%%>', html_attr($row['ende']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(ende)%%>', urlencode($urow['ende']), $templateCode);
		$templateCode = str_replace('<%%VALUE(pilot)%%>', safe_html($urow['pilot']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(pilot)%%>', urlencode($urow['pilot']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(anzahl_fluege)%%>', safe_html($urow['anzahl_fluege']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(anzahl_fluege)%%>', html_attr($row['anzahl_fluege']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(anzahl_fluege)%%>', urlencode($urow['anzahl_fluege']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(max_flughoehe)%%>', safe_html($urow['max_flughoehe']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(max_flughoehe)%%>', html_attr($row['max_flughoehe']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(max_flughoehe)%%>', urlencode($urow['max_flughoehe']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(flugplatz)%%>', safe_html($urow['flugplatz']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(flugplatz)%%>', html_attr($row['flugplatz']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(flugplatz)%%>', urlencode($urow['flugplatz']), $templateCode);
		$templateCode = str_replace('<%%VALUE(luftraumbeobachter_anwesend)%%>', safe_html($urow['luftraumbeobachter_anwesend']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(luftraumbeobachter_anwesend)%%>', urlencode($urow['luftraumbeobachter_anwesend']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(modell)%%>', safe_html($urow['modell']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(modell)%%>', html_attr($row['modell']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(modell)%%>', urlencode($urow['modell']), $templateCode);
		$templateCode = str_replace('<%%VALUE(besonderheiten)%%>', safe_html($urow['besonderheiten'], $fieldsAreEditable), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(besonderheiten)%%>', urlencode($urow['besonderheiten']), $templateCode);
		$templateCode = str_replace('<%%CHECKED(gastpilot)%%>', ($row['gastpilot'] ? "checked" : ""), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(name_gastpilot)%%>', safe_html($urow['name_gastpilot']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(name_gastpilot)%%>', html_attr($row['name_gastpilot']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(name_gastpilot)%%>', urlencode($urow['name_gastpilot']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(mfbo)%%>', safe_html($urow['mfbo']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(mfbo)%%>', html_attr($row['mfbo']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(mfbo)%%>', urlencode($urow['mfbo']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(reg_nr)%%>', safe_html($urow['reg_nr']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(reg_nr)%%>', html_attr($row['reg_nr']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(reg_nr)%%>', urlencode($urow['reg_nr']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(fluege)%%>', safe_html($urow['fluege']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(fluege)%%>', html_attr($row['fluege']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(fluege)%%>', urlencode($urow['fluege']), $templateCode);
		$templateCode = str_replace('<%%VALUE(lrb)%%>', safe_html($urow['lrb']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(lrb)%%>', urlencode($urow['lrb']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(hoehe)%%>', safe_html($urow['hoehe']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(hoehe)%%>', html_attr($row['hoehe']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(hoehe)%%>', urlencode($urow['hoehe']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(datei)%%>', safe_html($urow['datei']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(datei)%%>', html_attr($row['datei']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(datei)%%>', urlencode($urow['datei']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(datei_1)%%>', safe_html($urow['datei_1']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(datei_1)%%>', html_attr($row['datei_1']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(datei_1)%%>', urlencode($urow['datei_1']), $templateCode);
		$templateCode = str_replace('<%%VALUE(erfasser)%%>', safe_html($urow['erfasser']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(erfasser)%%>', urlencode($urow['erfasser']), $templateCode);
		$templateCode = str_replace('<%%VALUE(erfasst)%%>', app_datetime($row['erfasst'], 'dt'), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(erfasst)%%>', urlencode(app_datetime($urow['erfasst'], 'dt')), $templateCode);
		$templateCode = str_replace('<%%VALUE(geaendert_von)%%>', safe_html($urow['geaendert_von']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(geaendert_von)%%>', urlencode($urow['geaendert_von']), $templateCode);
		$templateCode = str_replace('<%%VALUE(geaendert)%%>', app_datetime($row['geaendert'], 'dt'), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(geaendert)%%>', urlencode(app_datetime($urow['geaendert'], 'dt')), $templateCode);
	} else {
		$templateCode = str_replace('<%%VALUE(id)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(id)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(datum)%%>', '1', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(datum)%%>', urlencode('1'), $templateCode);
		$templateCode = str_replace('<%%VALUE(beginn)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(beginn)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(ende)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(ende)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(pilot)%%>', '<%%creatorUsername%%>', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(pilot)%%>', urlencode('<%%creatorUsername%%>'), $templateCode);
		$templateCode = str_replace('<%%VALUE(anzahl_fluege)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(anzahl_fluege)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(max_flughoehe)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(max_flughoehe)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(flugplatz)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(flugplatz)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(luftraumbeobachter_anwesend)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(luftraumbeobachter_anwesend)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(modell)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(modell)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(besonderheiten)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(besonderheiten)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%CHECKED(gastpilot)%%>', '', $templateCode);
		$templateCode = str_replace('<%%VALUE(name_gastpilot)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(name_gastpilot)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(mfbo)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(mfbo)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(reg_nr)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(reg_nr)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(fluege)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(fluege)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(lrb)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(lrb)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(hoehe)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(hoehe)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(datei)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(datei)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(datei_1)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(datei_1)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(erfasser)%%>', '<%%creatorUsername%%>', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(erfasser)%%>', urlencode('<%%creatorUsername%%>'), $templateCode);
		$templateCode = str_replace('<%%VALUE(erfasst)%%>', '<%%creationDateTime%%>', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(erfasst)%%>', urlencode('<%%creationDateTime%%>'), $templateCode);
		$templateCode = str_replace('<%%VALUE(geaendert_von)%%>', '<%%editorUsername%%>', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(geaendert_von)%%>', urlencode('<%%editorUsername%%>'), $templateCode);
		$templateCode = str_replace('<%%VALUE(geaendert)%%>', '<%%editingDateTime%%>', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(geaendert)%%>', urlencode('<%%editingDateTime%%>'), $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\tif(document.getElementById('dateiEdit')) { document.getElementById('dateiEdit').style.display='inline'; }";
			$templateCode.="\n\tif(document.getElementById('dateiEditLink')) { document.getElementById('dateiEditLink').style.display='none'; }";
			$templateCode.="\n\tif(document.getElementById('datei_1Edit')) { document.getElementById('datei_1Edit').style.display='inline'; }";
			$templateCode.="\n\tif(document.getElementById('datei_1EditLink')) { document.getElementById('datei_1EditLink').style.display='none'; }";
		}

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

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

	return $templateCode;
}