<?php

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

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

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

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

	$data = [
		'producto' => Request::val('producto', ''),
		'precio' => Request::val('precio', ''),
		'image' => Request::fileUpload('image', [
			'maxSize' => 2048000,
			'types' => 'jpg|jpeg|gif|png',
			'noRename' => false,
			'dir' => '',
			'success' => function($name, $selected_id) {
				createThumbnail($name, getThumbnailSpecs('producto', 'image', 'tv'));
				createThumbnail($name, getThumbnailSpecs('producto', 'image', 'dv'));
			},
			'failure' => function($selected_id, $fileRemoved) {
				if(!isset($_REQUEST['SelectedID'])) return '';

				/* for empty upload fields, when saving a copy of an existing record, copy the original upload field */
				return existing_value('producto', 'image', $_REQUEST['SelectedID']);
			},
		]),
		'categoriaId' => Request::val('categoriaId', ''),
		'localId' => Request::val('localId', ''),
	];


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

	$error = '';
	// set empty fields to NULL
	$data = array_map(function($v) { return ($v === '' ? NULL : $v); }, $data);
	insert('producto', 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());

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

	// hook: producto_after_insert
	if(function_exists('producto_after_insert')) {
		$res = sql("SELECT * FROM `producto` WHERE `id`='" . makeSafe($recID, false) . "' LIMIT 1", $eo);
		if($row = db_fetch_assoc($res)) {
			$data = array_map('makeSafe', $row);
		}
		$data['selectedID'] = makeSafe($recID, false);
		$args=[];
		if(!producto_after_insert($data, getMemberInfo(), $args)) { return $recID; }
	}

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

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

	return $recID;
}

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

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

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

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

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

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

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

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

	$data = [
		'producto' => Request::val('producto', ''),
		'precio' => Request::val('precio', ''),
		'image' => Request::fileUpload('image', [
			'maxSize' => 2048000,
			'types' => 'jpg|jpeg|gif|png',
			'noRename' => false,
			'dir' => '',
			'id' => $selected_id,
			'success' => function($name, $selected_id) {
				createThumbnail($name, getThumbnailSpecs('producto', 'image', 'tv'));
				createThumbnail($name, getThumbnailSpecs('producto', 'image', 'dv'));
			},
			'failure' => function($selected_id, $fileRemoved) {
				if($fileRemoved) return '';
				return existing_value('producto', 'image', $selected_id);
			},
		]),
		'categoriaId' => Request::val('categoriaId', ''),
		'localId' => Request::val('localId', ''),
	];

	// get existing values
	$old_data = getRecord('producto', $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: producto_before_update
	if(function_exists('producto_before_update')) {
		$args = ['old_data' => $old_data];
		if(!producto_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(
		'producto', 
		backtick_keys_once($set), 
		['`id`' => $selected_id], 
		$error_message
	)) {
		echo $error_message;
		echo '<a href="producto_view.php?SelectedID=' . urlencode($selected_id) . "\">{$Translation['< back']}</a>";
		exit;
	}


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

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

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

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

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

function producto_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('producto');
	if(!$arrPerm[1] && $selected_id=='') { return ''; }
	$AllowInsert = ($arrPerm[1] ? true : false);
	// print preview?
	$dvprint = false;
	if($selected_id && $_REQUEST['dvprint_x'] != '') {
		$dvprint = true;
	}

	$filterer_categoriaId = thisOr($_REQUEST['filterer_categoriaId'], '');
	$filterer_localId = thisOr($_REQUEST['filterer_localId'], '');

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

	// unique random identifier
	$rnd1 = ($dvprint ? rand(1000000, 9999999) : '');
	// combobox: categoriaId
	$combo_categoriaId = new DataCombo;
	// combobox: localId
	$combo_localId = 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='producto' and pkValue='".makeSafe($selected_id)."'");
		$ownerMemberID=sqlValue("select lcase(memberID) from membership_userrecords where tableName='producto' 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 `producto` WHERE `id`='" . makeSafe($selected_id) . "'", $eo);
		if(!($row = db_fetch_array($res))) {
			return error_message($Translation['No records found'], 'producto_view.php', false);
		}
		$combo_categoriaId->SelectedData = $row['categoriaId'];
		$combo_localId->SelectedData = $row['localId'];
		$urow = $row; /* unsanitized data */
		$hc = new CI_Input();
		$row = $hc->xss_clean($row); /* sanitize data */
	} else {
		$combo_categoriaId->SelectedData = $filterer_categoriaId;
		$combo_localId->SelectedData = $filterer_localId;
	}
	$combo_categoriaId->HTML = '<span id="categoriaId-container' . $rnd1 . '"></span><input type="hidden" name="categoriaId" id="categoriaId' . $rnd1 . '" value="' . html_attr($combo_categoriaId->SelectedData) . '">';
	$combo_categoriaId->MatchText = '<span id="categoriaId-container-readonly' . $rnd1 . '"></span><input type="hidden" name="categoriaId" id="categoriaId' . $rnd1 . '" value="' . html_attr($combo_categoriaId->SelectedData) . '">';
	$combo_localId->HTML = '<span id="localId-container' . $rnd1 . '"></span><input type="hidden" name="localId" id="localId' . $rnd1 . '" value="' . html_attr($combo_localId->SelectedData) . '">';
	$combo_localId->MatchText = '<span id="localId-container-readonly' . $rnd1 . '"></span><input type="hidden" name="localId" id="localId' . $rnd1 . '" value="' . html_attr($combo_localId->SelectedData) . '">';

	ob_start();
	?>

	<script>
		// initial lookup values
		AppGini.current_categoriaId__RAND__ = { text: "", value: "<?php echo addslashes($selected_id ? $urow['categoriaId'] : $filterer_categoriaId); ?>"};
		AppGini.current_localId__RAND__ = { text: "", value: "<?php echo addslashes($selected_id ? $urow['localId'] : $filterer_localId); ?>"};

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

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


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


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

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

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

		<?php } else { ?>

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

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

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

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


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


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

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

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

		<?php } else { ?>

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

					if(typeof(localId_update_autofills__RAND__) == 'function') localId_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/producto_templateDVP.html';
		$templateCode = @file_get_contents($template_file);
	} else {
		$template_file = is_file("./{$TemplateDV}") ? "./{$TemplateDV}" : './templates/producto_templateDV.html';
		$templateCode = @file_get_contents($template_file);
	}

	// process form title
	$templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Producto details', $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 producto_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 producto_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 producto_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('#producto').replaceWith('<div class=\"form-control-static\" id=\"producto\">' + (jQuery('#producto').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#precio').replaceWith('<div class=\"form-control-static\" id=\"precio\">' + (jQuery('#precio').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#image').replaceWith('<div class=\"form-control-static\" id=\"image\">' + (jQuery('#image').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#categoriaId').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\tjQuery('#categoriaId_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
		$jsReadOnly .= "\tjQuery('#localId').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\tjQuery('#localId_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\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(categoriaId)%%>', $combo_categoriaId->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(categoriaId)%%>', $combo_categoriaId->MatchText, $templateCode);
	$templateCode = str_replace('<%%URLCOMBOTEXT(categoriaId)%%>', urlencode($combo_categoriaId->MatchText), $templateCode);
	$templateCode = str_replace('<%%COMBO(localId)%%>', $combo_localId->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(localId)%%>', $combo_localId->MatchText, $templateCode);
	$templateCode = str_replace('<%%URLCOMBOTEXT(localId)%%>', urlencode($combo_localId->MatchText), $templateCode);

	/* lookup fields array: 'lookup field name' => array('parent table name', 'lookup field caption') */
	$lookup_fields = array('categoriaId' => array('Categoria', 'CategoriaId'), 'localId' => array('locales', 'LocalId'), );
	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(id)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(producto)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(precio)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(image)%%>', ($noUploads ? '' : "<div>{$Translation['upload image']}</div>" . '<i class="glyphicon glyphicon-remove text-danger clear-upload hidden"></i> <input type="file" name="image" id="image" data-filetypes="jpg|jpeg|gif|png" data-maxsize="2048000" accept=".jpg,.jpeg,.gif,.png">'), $templateCode);
	if($AllowUpdate && $row['image'] != '') {
		$templateCode = str_replace('<%%REMOVEFILE(image)%%>', '<br><input type="checkbox" name="image_remove" id="image_remove" value="1"> <label for="image_remove" style="color: red; font-weight: bold;">'.$Translation['remove image'].'</label>', $templateCode);
	} else {
		$templateCode = str_replace('<%%REMOVEFILE(image)%%>', '', $templateCode);
	}
	$templateCode = str_replace('<%%UPLOADFILE(categoriaId)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(localId)%%>', '', $templateCode);

	// process values
	if($selected_id) {
		if( $dvprint) $templateCode = str_replace('<%%VALUE(id)%%>', safe_html($urow['id']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(id)%%>', html_attr($row['id']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(id)%%>', urlencode($urow['id']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(producto)%%>', safe_html($urow['producto']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(producto)%%>', html_attr($row['producto']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(producto)%%>', urlencode($urow['producto']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(precio)%%>', safe_html($urow['precio']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(precio)%%>', html_attr($row['precio']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(precio)%%>', urlencode($urow['precio']), $templateCode);
		$row['image'] = ($row['image'] != '' ? $row['image'] : 'blank.gif');
		if( $dvprint) $templateCode = str_replace('<%%VALUE(image)%%>', safe_html($urow['image']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(image)%%>', html_attr($row['image']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(image)%%>', urlencode($urow['image']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(categoriaId)%%>', safe_html($urow['categoriaId']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(categoriaId)%%>', html_attr($row['categoriaId']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(categoriaId)%%>', urlencode($urow['categoriaId']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(localId)%%>', safe_html($urow['localId']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(localId)%%>', html_attr($row['localId']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(localId)%%>', urlencode($urow['localId']), $templateCode);
	} else {
		$templateCode = str_replace('<%%VALUE(id)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(id)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(producto)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(producto)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(precio)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(precio)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(image)%%>', 'blank.gif', $templateCode);
		$templateCode = str_replace('<%%VALUE(categoriaId)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(categoriaId)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(localId)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(localId)%%>', 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.="});";
	$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('producto');
	if($selected_id) {
		$jdata = get_joined_record('producto', $selected_id);
		if($jdata === false) $jdata = get_defaults('producto');
		$rdata = $row;
	}
	$templateCode .= loadView('producto-ajax-cache', array('rdata' => $rdata, 'jdata' => $jdata));

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

	return $templateCode;
}