<?php

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

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

function suivi_client_insert() {
	global $Translation;

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

	$data = array();
	$data['num_dossier'] = $_REQUEST['num_dossier'];
		if($data['num_dossier'] == empty_lookup_value) { $data['num_dossier'] = ''; }
	$data['nom'] = $_REQUEST['nom'];
		if($data['nom'] == empty_lookup_value) { $data['nom'] = ''; }
	$data['prenom'] = $_REQUEST['nom'];
		if($data['prenom'] == empty_lookup_value) { $data['prenom'] = ''; }
	$data['raison_sociale'] = $_REQUEST['nom'];
		if($data['raison_sociale'] == empty_lookup_value) { $data['raison_sociale'] = ''; }
	$data['telephone'] = $_REQUEST['nom'];
		if($data['telephone'] == empty_lookup_value) { $data['telephone'] = ''; }
	$data['email'] = $_REQUEST['nom'];
		if($data['email'] == empty_lookup_value) { $data['email'] = ''; }
	$data['whatsapp'] = $_REQUEST['nom'];
		if($data['whatsapp'] == empty_lookup_value) { $data['whatsapp'] = ''; }
	$data['service_demande'] = $_REQUEST['service_demande'];
		if($data['service_demande'] == empty_lookup_value) { $data['service_demande'] = ''; }
	$data['date_demande'] = intval($_REQUEST['date_demandeYear']) . '-' . intval($_REQUEST['date_demandeMonth']) . '-' . intval($_REQUEST['date_demandeDay']);
	$data['date_demande'] = parseMySQLDate($data['date_demande'], '1');
	$data['statut_service'] = $_REQUEST['statut_service'];
		if($data['statut_service'] == empty_lookup_value) { $data['statut_service'] = ''; }
	$data['num_visa'] = $_REQUEST['num_visa'];
		if($data['num_visa'] == empty_lookup_value) { $data['num_visa'] = ''; }
	$data['date_debut_visa'] = intval($_REQUEST['date_debut_visaYear']) . '-' . intval($_REQUEST['date_debut_visaMonth']) . '-' . intval($_REQUEST['date_debut_visaDay']);
	$data['date_debut_visa'] = parseMySQLDate($data['date_debut_visa'], '');
	$data['date_fin_visa'] = intval($_REQUEST['date_fin_visaYear']) . '-' . intval($_REQUEST['date_fin_visaMonth']) . '-' . intval($_REQUEST['date_fin_visaDay']);
	$data['date_fin_visa'] = parseMySQLDate($data['date_fin_visa'], '');
	$data['type_de_visa'] = $_REQUEST['type_de_visa'];
		if($data['type_de_visa'] == empty_lookup_value) { $data['type_de_visa'] = ''; }
	$data['observations'] = $_REQUEST['observations'];
		if($data['observations'] == empty_lookup_value) { $data['observations'] = ''; }
	$data['groupe'] = parseCode('<%%creatorGroup%%>', true);
	$data['agent'] = parseCode('<%%creatorUsername%%>', true);
	if($data['nom']== '') {
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">" . $Translation['error:'] . " 'Nom': " . $Translation['field not null'] . '<br><br>';
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}
	if($data['service_demande']== '') {
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">" . $Translation['error:'] . " 'Service demande': " . $Translation['field not null'] . '<br><br>';
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}
	if($data['statut_service']== '') {
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">" . $Translation['error:'] . " 'Statut du service': " . $Translation['field not null'] . '<br><br>';
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}

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

	$error = '';
	// set empty fields to NULL
	$data = array_map(function($v) { return ($v === '' ? NULL : $v); }, $data);
	insert('suivi_client', 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: suivi_client_after_insert
	if(function_exists('suivi_client_after_insert')) {
		$res = sql("select * from `suivi_client` where `idsuivi_client`='" . 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(!suivi_client_after_insert($data, getMemberInfo(), $args)) { return $recID; }
	}

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

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

	return $recID;
}

function suivi_client_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);

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

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

	// mm: can member delete record?
	$arrPerm=getTablePermissions('suivi_client');
	$ownerGroupID=sqlValue("select groupID from membership_userrecords where tableName='suivi_client' and pkValue='$selected_id'");
	$ownerMemberID=sqlValue("select lcase(memberID) from membership_userrecords where tableName='suivi_client' 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: suivi_client_before_delete
	if(function_exists('suivi_client_before_delete')) {
		$args=array();
		if(!suivi_client_before_delete($selected_id, $skipChecks, getMemberInfo(), $args))
			return $Translation['Couldn\'t delete this record'];
	}

	sql("delete from `suivi_client` where `idsuivi_client`='$selected_id'", $eo);

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

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

function suivi_client_update($selected_id) {
	global $Translation;

	// mm: can member edit record?
	$arrPerm=getTablePermissions('suivi_client');
	$ownerGroupID=sqlValue("select groupID from membership_userrecords where tableName='suivi_client' and pkValue='".makeSafe($selected_id)."'");
	$ownerMemberID=sqlValue("select lcase(memberID) from membership_userrecords where tableName='suivi_client' 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['num_dossier'] = makeSafe($_REQUEST['num_dossier']);
		if($data['num_dossier'] == empty_lookup_value) { $data['num_dossier'] = ''; }
	$data['nom'] = makeSafe($_REQUEST['nom']);
		if($data['nom'] == empty_lookup_value) { $data['nom'] = ''; }
	if($data['nom']=='') {
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">{$Translation['error:']} 'Nom': {$Translation['field not null']}<br><br>";
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}
	$data['prenom'] = makeSafe($_REQUEST['nom']);
		if($data['prenom'] == empty_lookup_value) { $data['prenom'] = ''; }
	$data['raison_sociale'] = makeSafe($_REQUEST['nom']);
		if($data['raison_sociale'] == empty_lookup_value) { $data['raison_sociale'] = ''; }
	$data['telephone'] = makeSafe($_REQUEST['nom']);
		if($data['telephone'] == empty_lookup_value) { $data['telephone'] = ''; }
	$data['email'] = makeSafe($_REQUEST['nom']);
		if($data['email'] == empty_lookup_value) { $data['email'] = ''; }
	$data['whatsapp'] = makeSafe($_REQUEST['nom']);
		if($data['whatsapp'] == empty_lookup_value) { $data['whatsapp'] = ''; }
	$data['service_demande'] = makeSafe($_REQUEST['service_demande']);
		if($data['service_demande'] == empty_lookup_value) { $data['service_demande'] = ''; }
	if($data['service_demande']=='') {
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">{$Translation['error:']} 'Service demande': {$Translation['field not null']}<br><br>";
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}
	$data['date_demande'] = intval($_REQUEST['date_demandeYear']) . '-' . intval($_REQUEST['date_demandeMonth']) . '-' . intval($_REQUEST['date_demandeDay']);
	$data['date_demande'] = parseMySQLDate($data['date_demande'], '1');
	$data['statut_service'] = makeSafe($_REQUEST['statut_service']);
		if($data['statut_service'] == empty_lookup_value) { $data['statut_service'] = ''; }
	if($data['statut_service']=='') {
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">{$Translation['error:']} 'Statut du service': {$Translation['field not null']}<br><br>";
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}
	$data['num_visa'] = makeSafe($_REQUEST['num_visa']);
		if($data['num_visa'] == empty_lookup_value) { $data['num_visa'] = ''; }
	$data['date_debut_visa'] = intval($_REQUEST['date_debut_visaYear']) . '-' . intval($_REQUEST['date_debut_visaMonth']) . '-' . intval($_REQUEST['date_debut_visaDay']);
	$data['date_debut_visa'] = parseMySQLDate($data['date_debut_visa'], '');
	$data['date_fin_visa'] = intval($_REQUEST['date_fin_visaYear']) . '-' . intval($_REQUEST['date_fin_visaMonth']) . '-' . intval($_REQUEST['date_fin_visaDay']);
	$data['date_fin_visa'] = parseMySQLDate($data['date_fin_visa'], '');
	$data['type_de_visa'] = makeSafe($_REQUEST['type_de_visa']);
		if($data['type_de_visa'] == empty_lookup_value) { $data['type_de_visa'] = ''; }
	$data['observations'] = makeSafe($_REQUEST['observations']);
		if($data['observations'] == empty_lookup_value) { $data['observations'] = ''; }
	$data['selectedID'] = makeSafe($selected_id);

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

	$o = array('silentErrors' => true);
	sql('update `suivi_client` set       `num_dossier`=' . (($data['num_dossier'] !== '' && $data['num_dossier'] !== NULL) ? "'{$data['num_dossier']}'" : 'NULL') . ', `nom`=' . (($data['nom'] !== '' && $data['nom'] !== NULL) ? "'{$data['nom']}'" : 'NULL') . ', `prenom`=' . (($data['prenom'] !== '' && $data['prenom'] !== NULL) ? "'{$data['prenom']}'" : 'NULL') . ', `raison_sociale`=' . (($data['raison_sociale'] !== '' && $data['raison_sociale'] !== NULL) ? "'{$data['raison_sociale']}'" : 'NULL') . ', `telephone`=' . (($data['telephone'] !== '' && $data['telephone'] !== NULL) ? "'{$data['telephone']}'" : 'NULL') . ', `email`=' . (($data['email'] !== '' && $data['email'] !== NULL) ? "'{$data['email']}'" : 'NULL') . ', `whatsapp`=' . (($data['whatsapp'] !== '' && $data['whatsapp'] !== NULL) ? "'{$data['whatsapp']}'" : 'NULL') . ', `service_demande`=' . (($data['service_demande'] !== '' && $data['service_demande'] !== NULL) ? "'{$data['service_demande']}'" : 'NULL') . ', `date_demande`=' . (($data['date_demande'] !== '' && $data['date_demande'] !== NULL) ? "'{$data['date_demande']}'" : 'NULL') . ', `statut_service`=' . (($data['statut_service'] !== '' && $data['statut_service'] !== NULL) ? "'{$data['statut_service']}'" : 'NULL') . ', `num_visa`=' . (($data['num_visa'] !== '' && $data['num_visa'] !== NULL) ? "'{$data['num_visa']}'" : 'NULL') . ', `date_debut_visa`=' . (($data['date_debut_visa'] !== '' && $data['date_debut_visa'] !== NULL) ? "'{$data['date_debut_visa']}'" : 'NULL') . ', `date_fin_visa`=' . (($data['date_fin_visa'] !== '' && $data['date_fin_visa'] !== NULL) ? "'{$data['date_fin_visa']}'" : 'NULL') . ', `type_de_visa`=' . (($data['type_de_visa'] !== '' && $data['type_de_visa'] !== NULL) ? "'{$data['type_de_visa']}'" : 'NULL') . ', `observations`=' . (($data['observations'] !== '' && $data['observations'] !== NULL) ? "'{$data['observations']}'" : 'NULL') . " where `idsuivi_client`='".makeSafe($selected_id)."'", $o);
	if($o['error']!='') {
		echo $o['error'];
		echo '<a href="suivi_client_view.php?SelectedID='.urlencode($selected_id)."\">{$Translation['< back']}</a>";
		exit;
	}


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

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

}

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

	$filterer_nom = thisOr(undo_magic_quotes($_REQUEST['filterer_nom']), '');
	$filterer_service_demande = thisOr(undo_magic_quotes($_REQUEST['filterer_service_demande']), '');
	$filterer_type_de_visa = thisOr(undo_magic_quotes($_REQUEST['filterer_type_de_visa']), '');

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

	// unique random identifier
	$rnd1 = ($dvprint ? rand(1000000, 9999999) : '');
	// combobox: nom
	$combo_nom = new DataCombo;
	// combobox: service_demande
	$combo_service_demande = new DataCombo;
	// combobox: date_demande
	$combo_date_demande = new DateCombo;
	$combo_date_demande->DateFormat = "dmy";
	$combo_date_demande->MinYear = 1900;
	$combo_date_demande->MaxYear = 2100;
	$combo_date_demande->DefaultDate = parseMySQLDate('1', '1');
	$combo_date_demande->MonthNames = $Translation['month names'];
	$combo_date_demande->NamePrefix = 'date_demande';
	// combobox: statut_service
	$combo_statut_service = new Combo;
	$combo_statut_service->ListType = 0;
	$combo_statut_service->MultipleSeparator = ', ';
	$combo_statut_service->ListBoxHeight = 10;
	$combo_statut_service->RadiosPerLine = 1;
	if(is_file(dirname(__FILE__).'/hooks/suivi_client.statut_service.csv')) {
		$statut_service_data = addslashes(implode('', @file(dirname(__FILE__).'/hooks/suivi_client.statut_service.csv')));
		$combo_statut_service->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($statut_service_data)));
		$combo_statut_service->ListData = $combo_statut_service->ListItem;
	}else{
		$combo_statut_service->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("En cours;;Valid&#233;;;Annul&#233;e;;Rejet&#233;;;Impay&#233;;;Pay&#233;;;Supprim&#233;")));
		$combo_statut_service->ListData = $combo_statut_service->ListItem;
	}
	$combo_statut_service->SelectName = 'statut_service';
	$combo_statut_service->AllowNull = false;
	// combobox: date_debut_visa
	$combo_date_debut_visa = new DateCombo;
	$combo_date_debut_visa->DateFormat = "dmy";
	$combo_date_debut_visa->MinYear = 1900;
	$combo_date_debut_visa->MaxYear = 2100;
	$combo_date_debut_visa->DefaultDate = parseMySQLDate('', '');
	$combo_date_debut_visa->MonthNames = $Translation['month names'];
	$combo_date_debut_visa->NamePrefix = 'date_debut_visa';
	// combobox: date_fin_visa
	$combo_date_fin_visa = new DateCombo;
	$combo_date_fin_visa->DateFormat = "dmy";
	$combo_date_fin_visa->MinYear = 1900;
	$combo_date_fin_visa->MaxYear = 2100;
	$combo_date_fin_visa->DefaultDate = parseMySQLDate('', '');
	$combo_date_fin_visa->MonthNames = $Translation['month names'];
	$combo_date_fin_visa->NamePrefix = 'date_fin_visa';
	// combobox: type_de_visa
	$combo_type_de_visa = 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='suivi_client' and pkValue='".makeSafe($selected_id)."'");
		$ownerMemberID=sqlValue("select lcase(memberID) from membership_userrecords where tableName='suivi_client' 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 `suivi_client` WHERE `idsuivi_client`='" . makeSafe($selected_id) . "'", $eo);
		if(!($row = db_fetch_array($res))) {
			return error_message($Translation['No records found'], 'suivi_client_view.php', false);
		}
		$combo_nom->SelectedData = $row['nom'];
		$combo_service_demande->SelectedData = $row['service_demande'];
		$combo_date_demande->DefaultDate = $row['date_demande'];
		$combo_statut_service->SelectedData = $row['statut_service'];
		$combo_date_debut_visa->DefaultDate = $row['date_debut_visa'];
		$combo_date_fin_visa->DefaultDate = $row['date_fin_visa'];
		$combo_type_de_visa->SelectedData = $row['type_de_visa'];
		$urow = $row; /* unsanitized data */
		$hc = new CI_Input();
		$row = $hc->xss_clean($row); /* sanitize data */
	} else {
		$combo_nom->SelectedData = $filterer_nom;
		$combo_service_demande->SelectedData = $filterer_service_demande;
		$combo_statut_service->SelectedText = ( $_REQUEST['FilterField'][1]=='11' && $_REQUEST['FilterOperator'][1]=='<=>' ? (get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1]) : "");
		$combo_type_de_visa->SelectedData = $filterer_type_de_visa;
	}
	$combo_nom->HTML = '<span id="nom-container' . $rnd1 . '"></span><input type="hidden" name="nom" id="nom' . $rnd1 . '" value="' . html_attr($combo_nom->SelectedData) . '">';
	$combo_nom->MatchText = '<span id="nom-container-readonly' . $rnd1 . '"></span><input type="hidden" name="nom" id="nom' . $rnd1 . '" value="' . html_attr($combo_nom->SelectedData) . '">';
	$combo_service_demande->HTML = '<span id="service_demande-container' . $rnd1 . '"></span><input type="hidden" name="service_demande" id="service_demande' . $rnd1 . '" value="' . html_attr($combo_service_demande->SelectedData) . '">';
	$combo_service_demande->MatchText = '<span id="service_demande-container-readonly' . $rnd1 . '"></span><input type="hidden" name="service_demande" id="service_demande' . $rnd1 . '" value="' . html_attr($combo_service_demande->SelectedData) . '">';
	$combo_statut_service->Render();
	$combo_type_de_visa->HTML = '<span id="type_de_visa-container' . $rnd1 . '"></span><input type="hidden" name="type_de_visa" id="type_de_visa' . $rnd1 . '" value="' . html_attr($combo_type_de_visa->SelectedData) . '">';
	$combo_type_de_visa->MatchText = '<span id="type_de_visa-container-readonly' . $rnd1 . '"></span><input type="hidden" name="type_de_visa" id="type_de_visa' . $rnd1 . '" value="' . html_attr($combo_type_de_visa->SelectedData) . '">';

	ob_start();
	?>

	<script>
		// initial lookup values
		AppGini.current_nom__RAND__ = { text: "", value: "<?php echo addslashes($selected_id ? $urow['nom'] : $filterer_nom); ?>"};
		AppGini.current_service_demande__RAND__ = { text: "", value: "<?php echo addslashes($selected_id ? $urow['service_demande'] : $filterer_service_demande); ?>"};
		AppGini.current_type_de_visa__RAND__ = { text: "", value: "<?php echo addslashes($selected_id ? $urow['type_de_visa'] : $filterer_type_de_visa); ?>"};

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

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


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


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

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

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

		<?php }else{ ?>

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

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

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

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


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


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

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

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

		<?php }else{ ?>

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

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

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

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


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


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

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

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

		<?php }else{ ?>

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

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

	// process form title
	$templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Suivi client', $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 suivi_client_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 suivi_client_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 suivi_client_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('#num_dossier').replaceWith('<div class=\"form-control-static\" id=\"num_dossier\">' + (jQuery('#num_dossier').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#nom').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\tjQuery('#nom_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
		$jsReadOnly .= "\tjQuery('#email, #email-edit-link').hide();\n";
		$jsReadOnly .= "\tjQuery('#service_demande').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\tjQuery('#service_demande_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
		$jsReadOnly .= "\tjQuery('#date_demande').prop('readonly', true);\n";
		$jsReadOnly .= "\tjQuery('#date_demandeDay, #date_demandeMonth, #date_demandeYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\tjQuery('#statut_service').replaceWith('<div class=\"form-control-static\" id=\"statut_service\">' + (jQuery('#statut_service').val() || '') + '</div>'); jQuery('#statut_service-multi-selection-help').hide();\n";
		$jsReadOnly .= "\tjQuery('#num_visa').replaceWith('<div class=\"form-control-static\" id=\"num_visa\">' + (jQuery('#num_visa').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#date_debut_visa').prop('readonly', true);\n";
		$jsReadOnly .= "\tjQuery('#date_debut_visaDay, #date_debut_visaMonth, #date_debut_visaYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\tjQuery('#date_fin_visa').prop('readonly', true);\n";
		$jsReadOnly .= "\tjQuery('#date_fin_visaDay, #date_fin_visaMonth, #date_fin_visaYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\tjQuery('#type_de_visa').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\tjQuery('#type_de_visa_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(nom)%%>', $combo_nom->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(nom)%%>', $combo_nom->MatchText, $templateCode);
	$templateCode = str_replace('<%%URLCOMBOTEXT(nom)%%>', urlencode($combo_nom->MatchText), $templateCode);
	$templateCode = str_replace('<%%COMBO(service_demande)%%>', $combo_service_demande->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(service_demande)%%>', $combo_service_demande->MatchText, $templateCode);
	$templateCode = str_replace('<%%URLCOMBOTEXT(service_demande)%%>', urlencode($combo_service_demande->MatchText), $templateCode);
	$templateCode = str_replace('<%%COMBO(date_demande)%%>', ($selected_id && !$arrPerm[3] ? '<div class="form-control-static">' . $combo_date_demande->GetHTML(true) . '</div>' : $combo_date_demande->GetHTML()), $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(date_demande)%%>', $combo_date_demande->GetHTML(true), $templateCode);
	$templateCode = str_replace('<%%COMBO(statut_service)%%>', $combo_statut_service->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(statut_service)%%>', $combo_statut_service->SelectedData, $templateCode);
	$templateCode = str_replace('<%%COMBO(date_debut_visa)%%>', ($selected_id && !$arrPerm[3] ? '<div class="form-control-static">' . $combo_date_debut_visa->GetHTML(true) . '</div>' : $combo_date_debut_visa->GetHTML()), $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(date_debut_visa)%%>', $combo_date_debut_visa->GetHTML(true), $templateCode);
	$templateCode = str_replace('<%%COMBO(date_fin_visa)%%>', ($selected_id && !$arrPerm[3] ? '<div class="form-control-static">' . $combo_date_fin_visa->GetHTML(true) . '</div>' : $combo_date_fin_visa->GetHTML()), $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(date_fin_visa)%%>', $combo_date_fin_visa->GetHTML(true), $templateCode);
	$templateCode = str_replace('<%%COMBO(type_de_visa)%%>', $combo_type_de_visa->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(type_de_visa)%%>', $combo_type_de_visa->MatchText, $templateCode);
	$templateCode = str_replace('<%%URLCOMBOTEXT(type_de_visa)%%>', urlencode($combo_type_de_visa->MatchText), $templateCode);

	/* lookup fields array: 'lookup field name' => array('parent table name', 'lookup field caption') */
	$lookup_fields = array('nom' => array('clients', 'Nom'), 'service_demande' => array('produits_services', 'Service demande'), 'type_de_visa' => array('type_visa', 'Type de visa'), );
	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(idsuivi_client)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(num_dossier)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(nom)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(service_demande)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(date_demande)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(statut_service)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(num_visa)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(date_debut_visa)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(date_fin_visa)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(type_de_visa)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(observations)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(groupe)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(agent)%%>', '', $templateCode);

	// process values
	if($selected_id) {
		if( $dvprint) $templateCode = str_replace('<%%VALUE(idsuivi_client)%%>', safe_html($urow['idsuivi_client']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(idsuivi_client)%%>', html_attr($row['idsuivi_client']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(idsuivi_client)%%>', urlencode($urow['idsuivi_client']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(num_dossier)%%>', safe_html($urow['num_dossier']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(num_dossier)%%>', html_attr($row['num_dossier']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(num_dossier)%%>', urlencode($urow['num_dossier']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(nom)%%>', safe_html($urow['nom']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(nom)%%>', html_attr($row['nom']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(nom)%%>', urlencode($urow['nom']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(service_demande)%%>', safe_html($urow['service_demande']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(service_demande)%%>', html_attr($row['service_demande']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(service_demande)%%>', urlencode($urow['service_demande']), $templateCode);
		$templateCode = str_replace('<%%VALUE(date_demande)%%>', @date('d/m/Y', @strtotime(html_attr($row['date_demande']))), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(date_demande)%%>', urlencode(@date('d/m/Y', @strtotime(html_attr($urow['date_demande'])))), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(statut_service)%%>', safe_html($urow['statut_service']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(statut_service)%%>', html_attr($row['statut_service']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(statut_service)%%>', urlencode($urow['statut_service']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(num_visa)%%>', safe_html($urow['num_visa']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(num_visa)%%>', html_attr($row['num_visa']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(num_visa)%%>', urlencode($urow['num_visa']), $templateCode);
		$templateCode = str_replace('<%%VALUE(date_debut_visa)%%>', @date('d/m/Y', @strtotime(html_attr($row['date_debut_visa']))), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(date_debut_visa)%%>', urlencode(@date('d/m/Y', @strtotime(html_attr($urow['date_debut_visa'])))), $templateCode);
		$templateCode = str_replace('<%%VALUE(date_fin_visa)%%>', @date('d/m/Y', @strtotime(html_attr($row['date_fin_visa']))), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(date_fin_visa)%%>', urlencode(@date('d/m/Y', @strtotime(html_attr($urow['date_fin_visa'])))), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(type_de_visa)%%>', safe_html($urow['type_de_visa']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(type_de_visa)%%>', html_attr($row['type_de_visa']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(type_de_visa)%%>', urlencode($urow['type_de_visa']), $templateCode);
		if($AllowUpdate || $AllowInsert) {
			$templateCode = str_replace('<%%HTMLAREA(observations)%%>', '<textarea name="observations" id="observations" rows="5">' . html_attr($row['observations']) . '</textarea>', $templateCode);
		}else{
			$templateCode = str_replace('<%%HTMLAREA(observations)%%>', '<div id="observations" class="form-control-static">' . $row['observations'] . '</div>', $templateCode);
		}
		$templateCode = str_replace('<%%VALUE(observations)%%>', nl2br($row['observations']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(observations)%%>', urlencode($urow['observations']), $templateCode);
		$templateCode = str_replace('<%%VALUE(groupe)%%>', safe_html($urow['groupe']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(groupe)%%>', urlencode($urow['groupe']), $templateCode);
		$templateCode = str_replace('<%%VALUE(agent)%%>', safe_html($urow['agent']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(agent)%%>', urlencode($urow['agent']), $templateCode);
	}else{
		$templateCode = str_replace('<%%VALUE(idsuivi_client)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(idsuivi_client)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(num_dossier)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(num_dossier)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(nom)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(nom)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(service_demande)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(service_demande)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(date_demande)%%>', '1', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(date_demande)%%>', urlencode('1'), $templateCode);
		$templateCode = str_replace('<%%VALUE(statut_service)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(statut_service)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(num_visa)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(num_visa)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(date_debut_visa)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(date_debut_visa)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(date_fin_visa)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(date_fin_visa)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(type_de_visa)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(type_de_visa)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%HTMLAREA(observations)%%>', '<textarea name="observations" id="observations" rows="5"></textarea>', $templateCode);
		$templateCode = str_replace('<%%VALUE(groupe)%%>', '<%%creatorGroup%%>', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(groupe)%%>', urlencode('<%%creatorGroup%%>'), $templateCode);
		$templateCode = str_replace('<%%VALUE(agent)%%>', '<%%creatorUsername%%>', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(agent)%%>', urlencode('<%%creatorUsername%%>'), $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\tif(document.getElementById('emailEdit')) { document.getElementById('emailEdit').style.display='inline'; }";
			$templateCode.="\n\tif(document.getElementById('emailEditLink')) { document.getElementById('emailEditLink').style.display='none'; }";
		}

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

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

	$templateCode .= "\tnom_update_autofills$rnd1 = function() {\n";
	$templateCode .= "\t\t\$j.ajax({\n";
	if($dvprint) {
		$templateCode .= "\t\t\turl: 'suivi_client_autofill.php?rnd1=$rnd1&mfk=nom&id=' + encodeURIComponent('".addslashes($row['nom'])."'),\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: 'suivi_client_autofill.php?rnd1=$rnd1&mfk=nom&id=' + encodeURIComponent(AppGini.current_nom{$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('#nom$rnd1').prop('disabled', true); \$j('#nomLoading').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('#nom$rnd1').prop('disabled', false); " : "\$j('#nom$rnd1').prop('disabled', true); ")."\$j('#nomLoading').html(''); \$j(window).resize(); }\n";
	}
	$templateCode .= "\t\t});\n";
	$templateCode .= "\t};\n";
	if(!$dvprint) $templateCode .= "\tif(\$j('#nom_caption').length) \$j('#nom_caption').click(function() { /* */ nom_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('suivi_client');
	if($selected_id) {
		$jdata = get_joined_record('suivi_client', $selected_id);
		if($jdata === false) $jdata = get_defaults('suivi_client');
		$rdata = $row;
	}
	$templateCode .= loadView('suivi_client-ajax-cache', array('rdata' => $rdata, 'jdata' => $jdata));

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

	return $templateCode;
}
?>