<?php

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

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

function orders_insert() {
	global $Translation;

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

	$data = array();
	$data['CustomerID'] = $_REQUEST['CustomerID'];
		if($data['CustomerID'] == empty_lookup_value) { $data['CustomerID'] = ''; }
	$data['EmployeeID'] = $_REQUEST['EmployeeID'];
		if($data['EmployeeID'] == empty_lookup_value) { $data['EmployeeID'] = ''; }
	$data['OrderDate'] = intval($_REQUEST['OrderDateYear']) . '-' . intval($_REQUEST['OrderDateMonth']) . '-' . intval($_REQUEST['OrderDateDay']);
	$data['OrderDate'] = parseMySQLDate($data['OrderDate'], '1');
	$data['RequiredDate'] = intval($_REQUEST['RequiredDateYear']) . '-' . intval($_REQUEST['RequiredDateMonth']) . '-' . intval($_REQUEST['RequiredDateDay']);
	$data['RequiredDate'] = parseMySQLDate($data['RequiredDate'], '1');
	$data['ShippedDate'] = intval($_REQUEST['ShippedDateYear']) . '-' . intval($_REQUEST['ShippedDateMonth']) . '-' . intval($_REQUEST['ShippedDateDay']);
	$data['ShippedDate'] = parseMySQLDate($data['ShippedDate'], '');
	$data['ShipVia'] = $_REQUEST['ShipVia'];
		if($data['ShipVia'] == empty_lookup_value) { $data['ShipVia'] = ''; }
	$data['Freight'] = $_REQUEST['Freight'];
		if($data['Freight'] == empty_lookup_value) { $data['Freight'] = ''; }
	$data['ShipName'] = $_REQUEST['CustomerID'];
		if($data['ShipName'] == empty_lookup_value) { $data['ShipName'] = ''; }
	$data['ShipAddress'] = $_REQUEST['CustomerID'];
		if($data['ShipAddress'] == empty_lookup_value) { $data['ShipAddress'] = ''; }
	$data['ShipCity'] = $_REQUEST['CustomerID'];
		if($data['ShipCity'] == empty_lookup_value) { $data['ShipCity'] = ''; }
	$data['ShipRegion'] = $_REQUEST['CustomerID'];
		if($data['ShipRegion'] == empty_lookup_value) { $data['ShipRegion'] = ''; }
	$data['ShipPostalCode'] = $_REQUEST['CustomerID'];
		if($data['ShipPostalCode'] == empty_lookup_value) { $data['ShipPostalCode'] = ''; }
	$data['ShipCountry'] = $_REQUEST['CustomerID'];
		if($data['ShipCountry'] == empty_lookup_value) { $data['ShipCountry'] = ''; }
	if($data['Freight'] == '') $data['Freight'] = "0";

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

	$error = '';
	// set empty fields to NULL
	$data = array_map(function($v) { return ($v === '' ? NULL : $v); }, $data);
	insert('orders', backtick_keys_once($data), $error);
	if($error)
		die("{$error}<br><a href=\"#\" onclick=\"history.go(-1);\">{$Translation['< back']}</a>");

	$recID = db_insert_id(db_link());

	// hook: orders_after_insert
	if(function_exists('orders_after_insert')) {
		$res = sql("select * from `orders` where `OrderID`='" . makeSafe($recID, false) . "' limit 1", $eo);
		if($row = db_fetch_assoc($res)) {
			$data = array_map('makeSafe', $row);
		}
		$data['selectedID'] = makeSafe($recID, false);
		$args=array();
		if(!orders_after_insert($data, getMemberInfo(), $args)) { return $recID; }
	}

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

	// if this record is a copy of another record, copy children if applicable
	if(!empty($_REQUEST['SelectedID'])) orders_copy_children($recID, $_REQUEST['SelectedID']);

	return $recID;
}

function orders_copy_children($destination_id, $source_id) {
	global $Translation;
	$requests = array(); // array of curl handlers for launching insert requests
	$eo = array('silentErrors' => true);
	$uploads_dir = realpath(dirname(__FILE__) . '/../' . $Translation['ImageFolder']);
	$safe_sid = makeSafe($source_id);

	// copy order_details
	$res = sql("SELECT * FROM `order_details` WHERE `OrderID`='{$safe_sid}'", $eo);
	while($row = db_fetch_assoc($res)) {
		$data = array(
			'SelectedID' => $row['odID'],
			'OrderID' => $destination_id,
			'ProductID' => $row['ProductID'],
			'Category' => $row['Category'],
			'CatalogPrice' => $row['CatalogPrice'],
			'UnitsInStock' => $row['UnitsInStock'],
			'UnitPrice' => $row['UnitPrice'],
			'Quantity' => $row['Quantity'],
			'Discount' => $row['Discount'],
		);

		$ch = curl_insert_handler('order_details', $data);
		if($ch !== false) $requests[] = $ch;
	}

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

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

	// mm: can member delete record?
	$arrPerm=getTablePermissions('orders');
	$ownerGroupID=sqlValue("select groupID from membership_userrecords where tableName='orders' and pkValue='$selected_id'");
	$ownerMemberID=sqlValue("select lcase(memberID) from membership_userrecords where tableName='orders' and pkValue='$selected_id'");
	if(($arrPerm[4]==1 && $ownerMemberID==getLoggedMemberID()) || ($arrPerm[4]==2 && $ownerGroupID==getLoggedGroupID()) || $arrPerm[4]==3) { // allow delete?
		// delete allowed, so continue ...
	}else{
		return $Translation['You don\'t have enough permissions to delete this record'];
	}

	// hook: orders_before_delete
	if(function_exists('orders_before_delete')) {
		$args=array();
		if(!orders_before_delete($selected_id, $skipChecks, getMemberInfo(), $args))
			return $Translation['Couldn\'t delete this record'];
	}

	// child table: order_details
	$res = sql("select `OrderID` from `orders` where `OrderID`='$selected_id'", $eo);
	$OrderID = db_fetch_row($res);
	$rires = sql("select count(1) from `order_details` where `OrderID`='".addslashes($OrderID[0])."'", $eo);
	$rirow = db_fetch_row($rires);
	if($rirow[0] && !$AllowDeleteOfParents && !$skipChecks) {
		$RetMsg = $Translation["couldn't delete"];
		$RetMsg = str_replace("<RelatedRecords>", $rirow[0], $RetMsg);
		$RetMsg = str_replace("<TableName>", "order_details", $RetMsg);
		return $RetMsg;
	}elseif($rirow[0] && $AllowDeleteOfParents && !$skipChecks) {
		$RetMsg = $Translation["confirm delete"];
		$RetMsg = str_replace("<RelatedRecords>", $rirow[0], $RetMsg);
		$RetMsg = str_replace("<TableName>", "order_details", $RetMsg);
		$RetMsg = str_replace("<Delete>", "<input type=\"button\" class=\"button\" value=\"".$Translation['yes']."\" onClick=\"window.location='orders_view.php?SelectedID=".urlencode($selected_id)."&delete_x=1&confirmed=1';\">", $RetMsg);
		$RetMsg = str_replace("<Cancel>", "<input type=\"button\" class=\"button\" value=\"".$Translation['no']."\" onClick=\"window.location='orders_view.php?SelectedID=".urlencode($selected_id)."';\">", $RetMsg);
		return $RetMsg;
	}

	sql("delete from `orders` where `OrderID`='$selected_id'", $eo);

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

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

function orders_update($selected_id) {
	global $Translation;

	// mm: can member edit record?
	$arrPerm=getTablePermissions('orders');
	$ownerGroupID=sqlValue("select groupID from membership_userrecords where tableName='orders' and pkValue='".makeSafe($selected_id)."'");
	$ownerMemberID=sqlValue("select lcase(memberID) from membership_userrecords where tableName='orders' and pkValue='".makeSafe($selected_id)."'");
	if(($arrPerm[3]==1 && $ownerMemberID==getLoggedMemberID()) || ($arrPerm[3]==2 && $ownerGroupID==getLoggedGroupID()) || $arrPerm[3]==3) { // allow update?
		// update allowed, so continue ...
	}else{
		return false;
	}

	$data['CustomerID'] = makeSafe($_REQUEST['CustomerID']);
		if($data['CustomerID'] == empty_lookup_value) { $data['CustomerID'] = ''; }
	$data['EmployeeID'] = makeSafe($_REQUEST['EmployeeID']);
		if($data['EmployeeID'] == empty_lookup_value) { $data['EmployeeID'] = ''; }
	$data['OrderDate'] = intval($_REQUEST['OrderDateYear']) . '-' . intval($_REQUEST['OrderDateMonth']) . '-' . intval($_REQUEST['OrderDateDay']);
	$data['OrderDate'] = parseMySQLDate($data['OrderDate'], '1');
	$data['RequiredDate'] = intval($_REQUEST['RequiredDateYear']) . '-' . intval($_REQUEST['RequiredDateMonth']) . '-' . intval($_REQUEST['RequiredDateDay']);
	$data['RequiredDate'] = parseMySQLDate($data['RequiredDate'], '1');
	$data['ShippedDate'] = intval($_REQUEST['ShippedDateYear']) . '-' . intval($_REQUEST['ShippedDateMonth']) . '-' . intval($_REQUEST['ShippedDateDay']);
	$data['ShippedDate'] = parseMySQLDate($data['ShippedDate'], '');
	$data['ShipVia'] = makeSafe($_REQUEST['ShipVia']);
		if($data['ShipVia'] == empty_lookup_value) { $data['ShipVia'] = ''; }
	$data['Freight'] = makeSafe($_REQUEST['Freight']);
		if($data['Freight'] == empty_lookup_value) { $data['Freight'] = ''; }
	$data['ShipName'] = makeSafe($_REQUEST['CustomerID']);
		if($data['ShipName'] == empty_lookup_value) { $data['ShipName'] = ''; }
	$data['ShipAddress'] = makeSafe($_REQUEST['CustomerID']);
		if($data['ShipAddress'] == empty_lookup_value) { $data['ShipAddress'] = ''; }
	$data['ShipCity'] = makeSafe($_REQUEST['CustomerID']);
		if($data['ShipCity'] == empty_lookup_value) { $data['ShipCity'] = ''; }
	$data['ShipRegion'] = makeSafe($_REQUEST['CustomerID']);
		if($data['ShipRegion'] == empty_lookup_value) { $data['ShipRegion'] = ''; }
	$data['ShipPostalCode'] = makeSafe($_REQUEST['CustomerID']);
		if($data['ShipPostalCode'] == empty_lookup_value) { $data['ShipPostalCode'] = ''; }
	$data['ShipCountry'] = makeSafe($_REQUEST['CustomerID']);
		if($data['ShipCountry'] == empty_lookup_value) { $data['ShipCountry'] = ''; }
	$data['selectedID'] = makeSafe($selected_id);

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

	$o = array('silentErrors' => true);
	sql('update `orders` set       `CustomerID`=' . (($data['CustomerID'] !== '' && $data['CustomerID'] !== NULL) ? "'{$data['CustomerID']}'" : 'NULL') . ', `EmployeeID`=' . (($data['EmployeeID'] !== '' && $data['EmployeeID'] !== NULL) ? "'{$data['EmployeeID']}'" : 'NULL') . ', `OrderDate`=' . (($data['OrderDate'] !== '' && $data['OrderDate'] !== NULL) ? "'{$data['OrderDate']}'" : 'NULL') . ', `RequiredDate`=' . (($data['RequiredDate'] !== '' && $data['RequiredDate'] !== NULL) ? "'{$data['RequiredDate']}'" : 'NULL') . ', `ShippedDate`=' . (($data['ShippedDate'] !== '' && $data['ShippedDate'] !== NULL) ? "'{$data['ShippedDate']}'" : 'NULL') . ', `ShipVia`=' . (($data['ShipVia'] !== '' && $data['ShipVia'] !== NULL) ? "'{$data['ShipVia']}'" : 'NULL') . ', `Freight`=' . (($data['Freight'] !== '' && $data['Freight'] !== NULL) ? "'{$data['Freight']}'" : 'NULL') . ', `ShipName`=' . (($data['ShipName'] !== '' && $data['ShipName'] !== NULL) ? "'{$data['ShipName']}'" : 'NULL') . ', `ShipAddress`=' . (($data['ShipAddress'] !== '' && $data['ShipAddress'] !== NULL) ? "'{$data['ShipAddress']}'" : 'NULL') . ', `ShipCity`=' . (($data['ShipCity'] !== '' && $data['ShipCity'] !== NULL) ? "'{$data['ShipCity']}'" : 'NULL') . ', `ShipRegion`=' . (($data['ShipRegion'] !== '' && $data['ShipRegion'] !== NULL) ? "'{$data['ShipRegion']}'" : 'NULL') . ', `ShipPostalCode`=' . (($data['ShipPostalCode'] !== '' && $data['ShipPostalCode'] !== NULL) ? "'{$data['ShipPostalCode']}'" : 'NULL') . ', `ShipCountry`=' . (($data['ShipCountry'] !== '' && $data['ShipCountry'] !== NULL) ? "'{$data['ShipCountry']}'" : 'NULL') . " where `OrderID`='".makeSafe($selected_id)."'", $o);
	if($o['error']!='') {
		echo $o['error'];
		echo '<a href="orders_view.php?SelectedID='.urlencode($selected_id)."\">{$Translation['< back']}</a>";
		exit;
	}


	// hook: orders_after_update
	if(function_exists('orders_after_update')) {
		$res = sql("SELECT * FROM `orders` WHERE `OrderID`='{$data['selectedID']}' LIMIT 1", $eo);
		if($row = db_fetch_assoc($res)) {
			$data = array_map('makeSafe', $row);
		}
		$data['selectedID'] = $data['OrderID'];
		$args = array();
		if(!orders_after_update($data, getMemberInfo(), $args)) { return; }
	}

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

}

function orders_form($selected_id = '', $AllowUpdate = 1, $AllowInsert = 1, $AllowDelete = 1, $ShowCancel = 0, $TemplateDV = '', $TemplateDVP = '') {
	// function to return an editable form for a table records
	// and fill it with data of record whose ID is $selected_id. If $selected_id
	// is empty, an empty form is shown, with only an 'Add New'
	// button displayed.

	global $Translation;

	// mm: get table permissions
	$arrPerm=getTablePermissions('orders');
	if(!$arrPerm[1] && $selected_id=='') { return ''; }
	$AllowInsert = ($arrPerm[1] ? true : false);
	// print preview?
	$dvprint = false;
	if($selected_id && $_REQUEST['dvprint_x'] != '') {
		$dvprint = true;
	}

	$filterer_CustomerID = thisOr(undo_magic_quotes($_REQUEST['filterer_CustomerID']), '');
	$filterer_EmployeeID = thisOr(undo_magic_quotes($_REQUEST['filterer_EmployeeID']), '');
	$filterer_ShipVia = thisOr(undo_magic_quotes($_REQUEST['filterer_ShipVia']), '');

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

	// unique random identifier
	$rnd1 = ($dvprint ? rand(1000000, 9999999) : '');
	// combobox: CustomerID
	$combo_CustomerID = new DataCombo;
	// combobox: EmployeeID
	$combo_EmployeeID = new DataCombo;
	// combobox: OrderDate
	$combo_OrderDate = new DateCombo;
	$combo_OrderDate->DateFormat = "mdy";
	$combo_OrderDate->MinYear = 1900;
	$combo_OrderDate->MaxYear = 2100;
	$combo_OrderDate->DefaultDate = parseMySQLDate('1', '1');
	$combo_OrderDate->MonthNames = $Translation['month names'];
	$combo_OrderDate->NamePrefix = 'OrderDate';
	// combobox: RequiredDate
	$combo_RequiredDate = new DateCombo;
	$combo_RequiredDate->DateFormat = "mdy";
	$combo_RequiredDate->MinYear = 1900;
	$combo_RequiredDate->MaxYear = 2100;
	$combo_RequiredDate->DefaultDate = parseMySQLDate('1', '1');
	$combo_RequiredDate->MonthNames = $Translation['month names'];
	$combo_RequiredDate->NamePrefix = 'RequiredDate';
	// combobox: ShippedDate
	$combo_ShippedDate = new DateCombo;
	$combo_ShippedDate->DateFormat = "mdy";
	$combo_ShippedDate->MinYear = 1900;
	$combo_ShippedDate->MaxYear = 2100;
	$combo_ShippedDate->DefaultDate = parseMySQLDate('', '');
	$combo_ShippedDate->MonthNames = $Translation['month names'];
	$combo_ShippedDate->NamePrefix = 'ShippedDate';
	// combobox: ShipVia
	$combo_ShipVia = new DataCombo;

	if($selected_id) {
		// mm: check member permissions
		if(!$arrPerm[2]) {
			return "";
		}
		// mm: who is the owner?
		$ownerGroupID=sqlValue("select groupID from membership_userrecords where tableName='orders' and pkValue='".makeSafe($selected_id)."'");
		$ownerMemberID=sqlValue("select lcase(memberID) from membership_userrecords where tableName='orders' and pkValue='".makeSafe($selected_id)."'");
		if($arrPerm[2]==1 && getLoggedMemberID()!=$ownerMemberID) {
			return "";
		}
		if($arrPerm[2]==2 && getLoggedGroupID()!=$ownerGroupID) {
			return "";
		}

		// can edit?
		if(($arrPerm[3]==1 && $ownerMemberID==getLoggedMemberID()) || ($arrPerm[3]==2 && $ownerGroupID==getLoggedGroupID()) || $arrPerm[3]==3) {
			$AllowUpdate=1;
		}else{
			$AllowUpdate=0;
		}

		$res = sql("SELECT * FROM `orders` WHERE `OrderID`='" . makeSafe($selected_id) . "'", $eo);
		if(!($row = db_fetch_array($res))) {
			return error_message($Translation['No records found'], 'orders_view.php', false);
		}
		$combo_CustomerID->SelectedData = $row['CustomerID'];
		$combo_EmployeeID->SelectedData = $row['EmployeeID'];
		$combo_OrderDate->DefaultDate = $row['OrderDate'];
		$combo_RequiredDate->DefaultDate = $row['RequiredDate'];
		$combo_ShippedDate->DefaultDate = $row['ShippedDate'];
		$combo_ShipVia->SelectedData = $row['ShipVia'];
		$urow = $row; /* unsanitized data */
		$hc = new CI_Input();
		$row = $hc->xss_clean($row); /* sanitize data */
	} else {
		$combo_CustomerID->SelectedData = $filterer_CustomerID;
		$combo_EmployeeID->SelectedData = $filterer_EmployeeID;
		$combo_ShipVia->SelectedData = $filterer_ShipVia;
	}
	$combo_CustomerID->HTML = '<span id="CustomerID-container' . $rnd1 . '"></span><input type="hidden" name="CustomerID" id="CustomerID' . $rnd1 . '" value="' . html_attr($combo_CustomerID->SelectedData) . '">';
	$combo_CustomerID->MatchText = '<span id="CustomerID-container-readonly' . $rnd1 . '"></span><input type="hidden" name="CustomerID" id="CustomerID' . $rnd1 . '" value="' . html_attr($combo_CustomerID->SelectedData) . '">';
	$combo_EmployeeID->HTML = '<span id="EmployeeID-container' . $rnd1 . '"></span><input type="hidden" name="EmployeeID" id="EmployeeID' . $rnd1 . '" value="' . html_attr($combo_EmployeeID->SelectedData) . '">';
	$combo_EmployeeID->MatchText = '<span id="EmployeeID-container-readonly' . $rnd1 . '"></span><input type="hidden" name="EmployeeID" id="EmployeeID' . $rnd1 . '" value="' . html_attr($combo_EmployeeID->SelectedData) . '">';
	$combo_ShipVia->HTML = '<span id="ShipVia-container' . $rnd1 . '"></span><input type="hidden" name="ShipVia" id="ShipVia' . $rnd1 . '" value="' . html_attr($combo_ShipVia->SelectedData) . '">';
	$combo_ShipVia->MatchText = '<span id="ShipVia-container-readonly' . $rnd1 . '"></span><input type="hidden" name="ShipVia" id="ShipVia' . $rnd1 . '" value="' . html_attr($combo_ShipVia->SelectedData) . '">';

	ob_start();
	?>

	<script>
		// initial lookup values
		AppGini.current_CustomerID__RAND__ = { text: "", value: "<?php echo addslashes($selected_id ? $urow['CustomerID'] : $filterer_CustomerID); ?>"};
		AppGini.current_EmployeeID__RAND__ = { text: "", value: "<?php echo addslashes($selected_id ? $urow['EmployeeID'] : $filterer_EmployeeID); ?>"};
		AppGini.current_ShipVia__RAND__ = { text: "", value: "<?php echo addslashes($selected_id ? $urow['ShipVia'] : $filterer_ShipVia); ?>"};

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

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


							if(typeof(CustomerID_update_autofills__RAND__) == 'function') CustomerID_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: 'orders', f: 'CustomerID' }; },
					results: function(resp, page) { /* */ return resp; }
				},
				escapeMarkup: function(str) { /* */ return str; }
			}).on('change', function(e) {
				AppGini.current_CustomerID__RAND__.value = e.added.id;
				AppGini.current_CustomerID__RAND__.text = e.added.text;
				$j('[name="CustomerID"]').val(e.added.id);
				if(e.added.id == '<?php echo empty_lookup_value; ?>') { $j('.btn[id=customers_view_parent]').hide(); }else{ $j('.btn[id=customers_view_parent]').show(); }


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

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

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

		<?php }else{ ?>

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

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

		}
		function EmployeeID_reload__RAND__() {
		<?php if(($AllowUpdate || $AllowInsert) && !$dvprint) { ?>

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


							if(typeof(EmployeeID_update_autofills__RAND__) == 'function') EmployeeID_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: 'orders', f: 'EmployeeID' }; },
					results: function(resp, page) { /* */ return resp; }
				},
				escapeMarkup: function(str) { /* */ return str; }
			}).on('change', function(e) {
				AppGini.current_EmployeeID__RAND__.value = e.added.id;
				AppGini.current_EmployeeID__RAND__.text = e.added.text;
				$j('[name="EmployeeID"]').val(e.added.id);
				if(e.added.id == '<?php echo empty_lookup_value; ?>') { $j('.btn[id=employees_view_parent]').hide(); }else{ $j('.btn[id=employees_view_parent]').show(); }


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

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

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

		<?php }else{ ?>

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

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

		}
		function ShipVia_reload__RAND__() {
		<?php if(($AllowUpdate || $AllowInsert) && !$dvprint) { ?>

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


							if(typeof(ShipVia_update_autofills__RAND__) == 'function') ShipVia_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: 'orders', f: 'ShipVia' }; },
					results: function(resp, page) { /* */ return resp; }
				},
				escapeMarkup: function(str) { /* */ return str; }
			}).on('change', function(e) {
				AppGini.current_ShipVia__RAND__.value = e.added.id;
				AppGini.current_ShipVia__RAND__.text = e.added.text;
				$j('[name="ShipVia"]').val(e.added.id);
				if(e.added.id == '<?php echo empty_lookup_value; ?>') { $j('.btn[id=shippers_view_parent]').hide(); }else{ $j('.btn[id=shippers_view_parent]').show(); }


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

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

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

		<?php }else{ ?>

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

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

		}
	</script>
	<?php

	$lookups = str_replace('__RAND__', $rnd1, ob_get_contents());
	ob_end_clean();


	// code for template based detail view forms

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

	// process form title
	$templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Detail View', $templateCode);
	$templateCode = str_replace('<%%RND1%%>', $rnd1, $templateCode);
	$templateCode = str_replace('<%%EMBEDDED%%>', ($_REQUEST['Embedded'] ? 'Embedded=1' : ''), $templateCode);
	// process buttons
	if($AllowInsert) {
		if(!$selected_id) $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-success" id="insert" name="insert_x" value="1" onclick="return orders_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save New'] . '</button>', $templateCode);
		$templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="insert" name="insert_x" value="1" onclick="return orders_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save As Copy'] . '</button>', $templateCode);
	}else{
		$templateCode = str_replace('<%%INSERT_BUTTON%%>', '', $templateCode);
	}

	// 'Back' button action
	if($_REQUEST['Embedded']) {
		$backAction = 'AppGini.closeParentModal(); return false;';
	}else{
		$backAction = '$j(\'form\').eq(0).attr(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;';
	}

	if($selected_id) {
		if(!$_REQUEST['Embedded']) $templateCode = str_replace('<%%DVPRINT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="dvprint" name="dvprint_x" value="1" onclick="$j(\'form\').eq(0).prop(\'novalidate\', true); document.myform.reset(); return true;" title="' . html_attr($Translation['Print Preview']) . '"><i class="glyphicon glyphicon-print"></i> ' . $Translation['Print Preview'] . '</button>', $templateCode);
		if($AllowUpdate) {
			$templateCode = str_replace('<%%UPDATE_BUTTON%%>', '<button type="submit" class="btn btn-success btn-lg" id="update" name="update_x" value="1" onclick="return orders_validateData();" title="' . html_attr($Translation['Save Changes']) . '"><i class="glyphicon glyphicon-ok"></i> ' . $Translation['Save Changes'] . '</button>', $templateCode);
		}else{
			$templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
		}
		if(($arrPerm[4]==1 && $ownerMemberID==getLoggedMemberID()) || ($arrPerm[4]==2 && $ownerGroupID==getLoggedGroupID()) || $arrPerm[4]==3) { // allow delete?
			$templateCode = str_replace('<%%DELETE_BUTTON%%>', '<button type="submit" class="btn btn-danger" id="delete" name="delete_x" value="1" onclick="return confirm(\'' . $Translation['are you sure?'] . '\');" title="' . html_attr($Translation['Delete']) . '"><i class="glyphicon glyphicon-trash"></i> ' . $Translation['Delete'] . '</button>', $templateCode);
		}else{
			$templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
		}
		$templateCode = str_replace('<%%DESELECT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '" title="' . html_attr($Translation['Back']) . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>', $templateCode);
	}else{
		$templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
		$templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
		$templateCode = str_replace('<%%DESELECT_BUTTON%%>', ($ShowCancel ? '<button type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '" title="' . html_attr($Translation['Back']) . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>' : ''), $templateCode);
	}

	// set records to read only if user can't insert new records and can't edit current record
	if(($selected_id && !$AllowUpdate && !$AllowInsert) || (!$selected_id && !$AllowInsert)) {
		$jsReadOnly .= "\tjQuery('#CustomerID').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\tjQuery('#CustomerID_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
		$jsReadOnly .= "\tjQuery('#EmployeeID').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\tjQuery('#EmployeeID_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
		$jsReadOnly .= "\tjQuery('#OrderDate').prop('readonly', true);\n";
		$jsReadOnly .= "\tjQuery('#OrderDateDay, #OrderDateMonth, #OrderDateYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\tjQuery('#RequiredDate').prop('readonly', true);\n";
		$jsReadOnly .= "\tjQuery('#RequiredDateDay, #RequiredDateMonth, #RequiredDateYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\tjQuery('#ShippedDate').prop('readonly', true);\n";
		$jsReadOnly .= "\tjQuery('#ShippedDateDay, #ShippedDateMonth, #ShippedDateYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\tjQuery('#ShipVia').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\tjQuery('#ShipVia_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
		$jsReadOnly .= "\tjQuery('#Freight').replaceWith('<div class=\"form-control-static\" id=\"Freight\">' + (jQuery('#Freight').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('.select2-container').hide();\n";

		$noUploads = true;
	}elseif($AllowInsert) {
		$jsEditable .= "\tjQuery('form').eq(0).data('already_changed', true);"; // temporarily disable form change handler
			$jsEditable .= "\tjQuery('form').eq(0).data('already_changed', false);"; // re-enable form change handler
	}

	// process combos
	$templateCode = str_replace('<%%COMBO(CustomerID)%%>', $combo_CustomerID->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(CustomerID)%%>', $combo_CustomerID->MatchText, $templateCode);
	$templateCode = str_replace('<%%URLCOMBOTEXT(CustomerID)%%>', urlencode($combo_CustomerID->MatchText), $templateCode);
	$templateCode = str_replace('<%%COMBO(EmployeeID)%%>', $combo_EmployeeID->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(EmployeeID)%%>', $combo_EmployeeID->MatchText, $templateCode);
	$templateCode = str_replace('<%%URLCOMBOTEXT(EmployeeID)%%>', urlencode($combo_EmployeeID->MatchText), $templateCode);
	$templateCode = str_replace('<%%COMBO(OrderDate)%%>', ($selected_id && !$arrPerm[3] ? '<div class="form-control-static">' . $combo_OrderDate->GetHTML(true) . '</div>' : $combo_OrderDate->GetHTML()), $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(OrderDate)%%>', $combo_OrderDate->GetHTML(true), $templateCode);
	$templateCode = str_replace('<%%COMBO(RequiredDate)%%>', ($selected_id && !$arrPerm[3] ? '<div class="form-control-static">' . $combo_RequiredDate->GetHTML(true) . '</div>' : $combo_RequiredDate->GetHTML()), $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(RequiredDate)%%>', $combo_RequiredDate->GetHTML(true), $templateCode);
	$templateCode = str_replace('<%%COMBO(ShippedDate)%%>', ($selected_id && !$arrPerm[3] ? '<div class="form-control-static">' . $combo_ShippedDate->GetHTML(true) . '</div>' : $combo_ShippedDate->GetHTML()), $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(ShippedDate)%%>', $combo_ShippedDate->GetHTML(true), $templateCode);
	$templateCode = str_replace('<%%COMBO(ShipVia)%%>', $combo_ShipVia->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(ShipVia)%%>', $combo_ShipVia->MatchText, $templateCode);
	$templateCode = str_replace('<%%URLCOMBOTEXT(ShipVia)%%>', urlencode($combo_ShipVia->MatchText), $templateCode);

	/* lookup fields array: 'lookup field name' => array('parent table name', 'lookup field caption') */
	$lookup_fields = array('CustomerID' => array('customers', 'Customer'), 'EmployeeID' => array('employees', 'Employee'), 'ShipVia' => array('shippers', 'Ship Via'), );
	foreach($lookup_fields as $luf => $ptfc) {
		$pt_perm = getTablePermissions($ptfc[0]);

		// process foreign key links
		if($pt_perm['view'] || $pt_perm['edit']) {
			$templateCode = str_replace("<%%PLINK({$luf})%%>", '<button type="button" class="btn btn-default view_parent hspacer-md" id="' . $ptfc[0] . '_view_parent" title="' . html_attr($Translation['View'] . ' ' . $ptfc[1]) . '"><i class="glyphicon glyphicon-eye-open"></i></button>', $templateCode);
		}

		// if user has insert permission to parent table of a lookup field, put an add new button
		if($pt_perm['insert'] && !$_REQUEST['Embedded']) {
			$templateCode = str_replace("<%%ADDNEW({$ptfc[0]})%%>", '<button type="button" class="btn btn-success add_new_parent hspacer-md" id="' . $ptfc[0] . '_add_new" title="' . html_attr($Translation['Add New'] . ' ' . $ptfc[1]) . '"><i class="glyphicon glyphicon-plus-sign"></i></button>', $templateCode);
		}
	}

	// process images
	$templateCode = str_replace('<%%UPLOADFILE(OrderID)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(status)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(CustomerID)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(EmployeeID)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(OrderDate)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(RequiredDate)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(ShippedDate)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(ShipVia)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(Freight)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(total)%%>', '', $templateCode);

	// process values
	if($selected_id) {
		if( $dvprint) $templateCode = str_replace('<%%VALUE(OrderID)%%>', safe_html($urow['OrderID']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(OrderID)%%>', html_attr($row['OrderID']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(OrderID)%%>', urlencode($urow['OrderID']), $templateCode);
		$templateCode = str_replace('<%%VALUE(status)%%>', safe_html($urow['status']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(status)%%>', urlencode($urow['status']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(CustomerID)%%>', safe_html($urow['CustomerID']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(CustomerID)%%>', html_attr($row['CustomerID']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(CustomerID)%%>', urlencode($urow['CustomerID']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(EmployeeID)%%>', safe_html($urow['EmployeeID']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(EmployeeID)%%>', html_attr($row['EmployeeID']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(EmployeeID)%%>', urlencode($urow['EmployeeID']), $templateCode);
		$templateCode = str_replace('<%%VALUE(OrderDate)%%>', @date('m/d/Y', @strtotime(html_attr($row['OrderDate']))), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(OrderDate)%%>', urlencode(@date('m/d/Y', @strtotime(html_attr($urow['OrderDate'])))), $templateCode);
		$templateCode = str_replace('<%%VALUE(RequiredDate)%%>', @date('m/d/Y', @strtotime(html_attr($row['RequiredDate']))), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(RequiredDate)%%>', urlencode(@date('m/d/Y', @strtotime(html_attr($urow['RequiredDate'])))), $templateCode);
		$templateCode = str_replace('<%%VALUE(ShippedDate)%%>', @date('m/d/Y', @strtotime(html_attr($row['ShippedDate']))), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(ShippedDate)%%>', urlencode(@date('m/d/Y', @strtotime(html_attr($urow['ShippedDate'])))), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(ShipVia)%%>', safe_html($urow['ShipVia']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(ShipVia)%%>', html_attr($row['ShipVia']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(ShipVia)%%>', urlencode($urow['ShipVia']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(Freight)%%>', safe_html($urow['Freight']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(Freight)%%>', html_attr($row['Freight']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Freight)%%>', urlencode($urow['Freight']), $templateCode);
		$templateCode = str_replace('<%%VALUE(total)%%>', safe_html($urow['total']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(total)%%>', urlencode($urow['total']), $templateCode);
	}else{
		$templateCode = str_replace('<%%VALUE(OrderID)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(OrderID)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(status)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(status)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(CustomerID)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(CustomerID)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(EmployeeID)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(EmployeeID)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(OrderDate)%%>', '1', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(OrderDate)%%>', urlencode('1'), $templateCode);
		$templateCode = str_replace('<%%VALUE(RequiredDate)%%>', '1', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(RequiredDate)%%>', urlencode('1'), $templateCode);
		$templateCode = str_replace('<%%VALUE(ShippedDate)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(ShippedDate)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(ShipVia)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(ShipVia)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(Freight)%%>', '0', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Freight)%%>', urlencode('0'), $templateCode);
		$templateCode = str_replace('<%%VALUE(total)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(total)%%>', urlencode(''), $templateCode);
	}

	// process translations
	foreach($Translation as $symbol=>$trans) {
		$templateCode = str_replace("<%%TRANSLATION($symbol)%%>", $trans, $templateCode);
	}

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

	// hide links to inaccessible tables
	if($_REQUEST['dvprint_x'] == '') {
		$templateCode .= "\n\n<script>\$j(function() {\n";
		$arrTables = getTableList();
		foreach($arrTables as $name => $caption) {
			$templateCode .= "\t\$j('#{$name}_link').removeClass('hidden');\n";
			$templateCode .= "\t\$j('#xs_{$name}_link').removeClass('hidden');\n";
		}

		$templateCode .= $jsReadOnly;
		$templateCode .= $jsEditable;

		if(!$selected_id) {
		}

		$templateCode.="\n});</script>\n";
	}

	// ajaxed auto-fill fields
	$templateCode .= '<script>';
	$templateCode .= '$j(function() {';

	$templateCode .= "\tCustomerID_update_autofills$rnd1 = function() {\n";
	$templateCode .= "\t\t\$j.ajax({\n";
	if($dvprint) {
		$templateCode .= "\t\t\turl: 'orders_autofill.php?rnd1=$rnd1&mfk=CustomerID&id=' + encodeURIComponent('".addslashes($row['CustomerID'])."'),\n";
		$templateCode .= "\t\t\tcontentType: 'application/x-www-form-urlencoded; charset=" . datalist_db_encoding . "',\n";
		$templateCode .= "\t\t\ttype: 'GET'\n";
	} else {
		$templateCode .= "\t\t\turl: 'orders_autofill.php?rnd1=$rnd1&mfk=CustomerID&id=' + encodeURIComponent(AppGini.current_CustomerID{$rnd1}.value),\n";
		$templateCode .= "\t\t\tcontentType: 'application/x-www-form-urlencoded; charset=" . datalist_db_encoding . "',\n";
		$templateCode .= "\t\t\ttype: 'GET',\n";
		$templateCode .= "\t\t\tbeforeSend: function() { \$j('#CustomerID$rnd1').prop('disabled', true); \$j('#CustomerIDLoading').html('<img src=loading.gif align=top>'); },\n";
		$templateCode .= "\t\t\tcomplete: function() { " . (($arrPerm[1] || (($arrPerm[3] == 1 && $ownerMemberID == getLoggedMemberID()) || ($arrPerm[3] == 2 && $ownerGroupID == getLoggedGroupID()) || $arrPerm[3] == 3)) ? "\$j('#CustomerID$rnd1').prop('disabled', false); " : "\$j('#CustomerID$rnd1').prop('disabled', true); ")."\$j('#CustomerIDLoading').html(''); \$j(window).resize(); }\n";
	}
	$templateCode .= "\t\t});\n";
	$templateCode .= "\t};\n";
	if(!$dvprint) $templateCode .= "\tif(\$j('#CustomerID_caption').length) \$j('#CustomerID_caption').click(function() { /* */ CustomerID_update_autofills$rnd1(); });\n";


	$templateCode.="});";
	$templateCode.="</script>";
	$templateCode .= $lookups;

	// handle enforced parent values for read-only lookup fields

	// don't include blank images in lightbox gallery
	$templateCode = preg_replace('/blank.gif" data-lightbox=".*?"/', 'blank.gif"', $templateCode);

	// don't display empty email links
	$templateCode=preg_replace('/<a .*?href="mailto:".*?<\/a>/', '', $templateCode);

	/* default field values */
	$rdata = $jdata = get_defaults('orders');
	if($selected_id) {
		$jdata = get_joined_record('orders', $selected_id);
		if($jdata === false) $jdata = get_defaults('orders');
		$rdata = $row;
	}
	$templateCode .= loadView('orders-ajax-cache', array('rdata' => $rdata, 'jdata' => $jdata));

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

	return $templateCode;
}
?>