<?php

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

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

function oumrah_insert() {
	global $Translation;

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

	$data = array();
	$data['Pelerinage'] = $_REQUEST['Pelerinage'];
		if($data['Pelerinage'] == empty_lookup_value) { $data['Pelerinage'] = ''; }
	$data['Prenom'] = $_REQUEST['Prenom'];
		if($data['Prenom'] == empty_lookup_value) { $data['Prenom'] = ''; }
	$data['Nom'] = $_REQUEST['Nom'];
		if($data['Nom'] == empty_lookup_value) { $data['Nom'] = ''; }
	$data['Datedenaissance'] = intval($_REQUEST['DatedenaissanceYear']) . '-' . intval($_REQUEST['DatedenaissanceMonth']) . '-' . intval($_REQUEST['DatedenaissanceDay']);
	$data['Datedenaissance'] = parseMySQLDate($data['Datedenaissance'], '');
	$data['Lieudenaissance'] = $_REQUEST['Lieudenaissance'];
		if($data['Lieudenaissance'] == empty_lookup_value) { $data['Lieudenaissance'] = ''; }
	$data['Adresse'] = $_REQUEST['Adresse'];
		if($data['Adresse'] == empty_lookup_value) { $data['Adresse'] = ''; }
	$data['Sexe'] = $_REQUEST['Sexe'];
		if($data['Sexe'] == empty_lookup_value) { $data['Sexe'] = ''; }
	$data['Numropasseport'] = $_REQUEST['Numropasseport'];
		if($data['Numropasseport'] == empty_lookup_value) { $data['Numropasseport'] = ''; }
	$data['Remarque'] = $_REQUEST['Remarque'];
		if($data['Remarque'] == empty_lookup_value) { $data['Remarque'] = ''; }
	$data['Tlphoneplerin'] = $_REQUEST['Tlphoneplerin'];
		if($data['Tlphoneplerin'] == empty_lookup_value) { $data['Tlphoneplerin'] = ''; }
	$data['Tlphonefamille'] = $_REQUEST['Tlphonefamille'];
		if($data['Tlphonefamille'] == empty_lookup_value) { $data['Tlphonefamille'] = ''; }
	$data['Personnecontacter'] = $_REQUEST['Personnecontacter'];
		if($data['Personnecontacter'] == empty_lookup_value) { $data['Personnecontacter'] = ''; }
	$data['Squence'] = $_REQUEST['Squence'];
		if($data['Squence'] == empty_lookup_value) { $data['Squence'] = ''; }
	$data['Profession'] = $_REQUEST['Profession'];
		if($data['Profession'] == empty_lookup_value) { $data['Profession'] = ''; }
	$data['Ethnie'] = $_REQUEST['Ethnie'];
		if($data['Ethnie'] == empty_lookup_value) { $data['Ethnie'] = ''; }
	$data['Region'] = $_REQUEST['Region'];
		if($data['Region'] == empty_lookup_value) { $data['Region'] = ''; }
	$data['groupe'] = parseCode('<%%creatorGroup%%>', true);
	$data['agent'] = parseCode('<%%creatorUsername%%>', true);
	if($data['total_entree'] == '') $data['total_entree'] = "0";
	if($data['total_sortie'] == '') $data['total_sortie'] = "0";
	if($data['solde'] == '') $data['solde'] = "0";

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

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

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

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

	return $recID;
}

function oumrah_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 entrees
	$res = sql("SELECT * FROM `entrees` WHERE `oumrah`='{$safe_sid}'", $eo);
	while($row = db_fetch_assoc($res)) {
		$data = array(
			'SelectedID' => $row['identrees'],
			'date_entreeDay' => ($row['date_entree'] ? substr($row['date_entree'], 8, 2) : ''),
			'date_entreeMonth' => ($row['date_entree'] ? substr($row['date_entree'], 5, 2) : ''),
			'date_entreeYear' => ($row['date_entree'] ? substr($row['date_entree'], 0, 4) : ''),
			'client' => $row['client'],
			'oumrah' => $destination_id,
			'description' => $row['description'],
			'montant' => $row['montant'],
			'observations' => $row['observations'],
		);

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

	// copy sorties
	$res = sql("SELECT * FROM `sorties` WHERE `oumrah`='{$safe_sid}'", $eo);
	while($row = db_fetch_assoc($res)) {
		$data = array(
			'SelectedID' => $row['idsorties'],
			'date_sortieDay' => ($row['date_sortie'] ? substr($row['date_sortie'], 8, 2) : ''),
			'date_sortieMonth' => ($row['date_sortie'] ? substr($row['date_sortie'], 5, 2) : ''),
			'date_sortieYear' => ($row['date_sortie'] ? substr($row['date_sortie'], 0, 4) : ''),
			'client' => $row['client'],
			'oumrah' => $destination_id,
			'montant' => $row['montant'],
			'observations' => $row['observations'],
		);

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

	// copy souscriptions
	$res = sql("SELECT * FROM `souscriptions` WHERE `oumrah`='{$safe_sid}'", $eo);
	while($row = db_fetch_assoc($res)) {
		$data = array(
			'SelectedID' => $row['idsouscription'],
			'pelerin' => $row['pelerin'],
			'oumrah' => $destination_id,
			'package' => $row['package'],
			'prix' => $row['prix'],
			'remise' => $row['remise'],
			'net_a_payer' => $row['net_a_payer'],
			'observations' => $row['observations'],
		);

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

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

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

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

	// child table: souscriptions
	$res = sql("select `idoumrah` from `oumrah` where `idoumrah`='$selected_id'", $eo);
	$idoumrah = db_fetch_row($res);
	$rires = sql("select count(1) from `souscriptions` where `oumrah`='".addslashes($idoumrah[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>", "souscriptions", $RetMsg);
		return $RetMsg;
	}elseif($rirow[0] && $AllowDeleteOfParents && !$skipChecks) {
		$RetMsg = $Translation["confirm delete"];
		$RetMsg = str_replace("<RelatedRecords>", $rirow[0], $RetMsg);
		$RetMsg = str_replace("<TableName>", "souscriptions", $RetMsg);
		$RetMsg = str_replace("<Delete>", "<input type=\"button\" class=\"button\" value=\"".$Translation['yes']."\" onClick=\"window.location='oumrah_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='oumrah_view.php?SelectedID=".urlencode($selected_id)."';\">", $RetMsg);
		return $RetMsg;
	}

	// child table: entrees
	$res = sql("select `idoumrah` from `oumrah` where `idoumrah`='$selected_id'", $eo);
	$idoumrah = db_fetch_row($res);
	$rires = sql("select count(1) from `entrees` where `oumrah`='".addslashes($idoumrah[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>", "entrees", $RetMsg);
		return $RetMsg;
	}elseif($rirow[0] && $AllowDeleteOfParents && !$skipChecks) {
		$RetMsg = $Translation["confirm delete"];
		$RetMsg = str_replace("<RelatedRecords>", $rirow[0], $RetMsg);
		$RetMsg = str_replace("<TableName>", "entrees", $RetMsg);
		$RetMsg = str_replace("<Delete>", "<input type=\"button\" class=\"button\" value=\"".$Translation['yes']."\" onClick=\"window.location='oumrah_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='oumrah_view.php?SelectedID=".urlencode($selected_id)."';\">", $RetMsg);
		return $RetMsg;
	}

	// child table: sorties
	$res = sql("select `idoumrah` from `oumrah` where `idoumrah`='$selected_id'", $eo);
	$idoumrah = db_fetch_row($res);
	$rires = sql("select count(1) from `sorties` where `oumrah`='".addslashes($idoumrah[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>", "sorties", $RetMsg);
		return $RetMsg;
	}elseif($rirow[0] && $AllowDeleteOfParents && !$skipChecks) {
		$RetMsg = $Translation["confirm delete"];
		$RetMsg = str_replace("<RelatedRecords>", $rirow[0], $RetMsg);
		$RetMsg = str_replace("<TableName>", "sorties", $RetMsg);
		$RetMsg = str_replace("<Delete>", "<input type=\"button\" class=\"button\" value=\"".$Translation['yes']."\" onClick=\"window.location='oumrah_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='oumrah_view.php?SelectedID=".urlencode($selected_id)."';\">", $RetMsg);
		return $RetMsg;
	}

	sql("delete from `oumrah` where `idoumrah`='$selected_id'", $eo);

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

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

function oumrah_update($selected_id) {
	global $Translation;

	// mm: can member edit record?
	$arrPerm=getTablePermissions('oumrah');
	$ownerGroupID=sqlValue("select groupID from membership_userrecords where tableName='oumrah' and pkValue='".makeSafe($selected_id)."'");
	$ownerMemberID=sqlValue("select lcase(memberID) from membership_userrecords where tableName='oumrah' 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['Pelerinage'] = makeSafe($_REQUEST['Pelerinage']);
		if($data['Pelerinage'] == empty_lookup_value) { $data['Pelerinage'] = ''; }
	$data['Prenom'] = makeSafe($_REQUEST['Prenom']);
		if($data['Prenom'] == empty_lookup_value) { $data['Prenom'] = ''; }
	$data['Nom'] = makeSafe($_REQUEST['Nom']);
		if($data['Nom'] == empty_lookup_value) { $data['Nom'] = ''; }
	$data['Datedenaissance'] = intval($_REQUEST['DatedenaissanceYear']) . '-' . intval($_REQUEST['DatedenaissanceMonth']) . '-' . intval($_REQUEST['DatedenaissanceDay']);
	$data['Datedenaissance'] = parseMySQLDate($data['Datedenaissance'], '');
	$data['Lieudenaissance'] = makeSafe($_REQUEST['Lieudenaissance']);
		if($data['Lieudenaissance'] == empty_lookup_value) { $data['Lieudenaissance'] = ''; }
	$data['Adresse'] = makeSafe($_REQUEST['Adresse']);
		if($data['Adresse'] == empty_lookup_value) { $data['Adresse'] = ''; }
	$data['Sexe'] = makeSafe($_REQUEST['Sexe']);
		if($data['Sexe'] == empty_lookup_value) { $data['Sexe'] = ''; }
	$data['Numropasseport'] = makeSafe($_REQUEST['Numropasseport']);
		if($data['Numropasseport'] == empty_lookup_value) { $data['Numropasseport'] = ''; }
	$data['Remarque'] = makeSafe($_REQUEST['Remarque']);
		if($data['Remarque'] == empty_lookup_value) { $data['Remarque'] = ''; }
	$data['Tlphoneplerin'] = makeSafe($_REQUEST['Tlphoneplerin']);
		if($data['Tlphoneplerin'] == empty_lookup_value) { $data['Tlphoneplerin'] = ''; }
	$data['Tlphonefamille'] = makeSafe($_REQUEST['Tlphonefamille']);
		if($data['Tlphonefamille'] == empty_lookup_value) { $data['Tlphonefamille'] = ''; }
	$data['Personnecontacter'] = makeSafe($_REQUEST['Personnecontacter']);
		if($data['Personnecontacter'] == empty_lookup_value) { $data['Personnecontacter'] = ''; }
	$data['Squence'] = makeSafe($_REQUEST['Squence']);
		if($data['Squence'] == empty_lookup_value) { $data['Squence'] = ''; }
	$data['Profession'] = makeSafe($_REQUEST['Profession']);
		if($data['Profession'] == empty_lookup_value) { $data['Profession'] = ''; }
	$data['Ethnie'] = makeSafe($_REQUEST['Ethnie']);
		if($data['Ethnie'] == empty_lookup_value) { $data['Ethnie'] = ''; }
	$data['Region'] = makeSafe($_REQUEST['Region']);
		if($data['Region'] == empty_lookup_value) { $data['Region'] = ''; }
	$data['selectedID'] = makeSafe($selected_id);

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

	$o = array('silentErrors' => true);
	sql('update `oumrah` set       `Pelerinage`=' . (($data['Pelerinage'] !== '' && $data['Pelerinage'] !== NULL) ? "'{$data['Pelerinage']}'" : 'NULL') . ', `Prenom`=' . (($data['Prenom'] !== '' && $data['Prenom'] !== NULL) ? "'{$data['Prenom']}'" : 'NULL') . ', `Nom`=' . (($data['Nom'] !== '' && $data['Nom'] !== NULL) ? "'{$data['Nom']}'" : 'NULL') . ', `Datedenaissance`=' . (($data['Datedenaissance'] !== '' && $data['Datedenaissance'] !== NULL) ? "'{$data['Datedenaissance']}'" : 'NULL') . ', `Lieudenaissance`=' . (($data['Lieudenaissance'] !== '' && $data['Lieudenaissance'] !== NULL) ? "'{$data['Lieudenaissance']}'" : 'NULL') . ', `Adresse`=' . (($data['Adresse'] !== '' && $data['Adresse'] !== NULL) ? "'{$data['Adresse']}'" : 'NULL') . ', `Sexe`=' . (($data['Sexe'] !== '' && $data['Sexe'] !== NULL) ? "'{$data['Sexe']}'" : 'NULL') . ', `Numropasseport`=' . (($data['Numropasseport'] !== '' && $data['Numropasseport'] !== NULL) ? "'{$data['Numropasseport']}'" : 'NULL') . ', `Remarque`=' . (($data['Remarque'] !== '' && $data['Remarque'] !== NULL) ? "'{$data['Remarque']}'" : 'NULL') . ', `Tlphoneplerin`=' . (($data['Tlphoneplerin'] !== '' && $data['Tlphoneplerin'] !== NULL) ? "'{$data['Tlphoneplerin']}'" : 'NULL') . ', `Tlphonefamille`=' . (($data['Tlphonefamille'] !== '' && $data['Tlphonefamille'] !== NULL) ? "'{$data['Tlphonefamille']}'" : 'NULL') . ', `Personnecontacter`=' . (($data['Personnecontacter'] !== '' && $data['Personnecontacter'] !== NULL) ? "'{$data['Personnecontacter']}'" : 'NULL') . ', `Squence`=' . (($data['Squence'] !== '' && $data['Squence'] !== NULL) ? "'{$data['Squence']}'" : 'NULL') . ', `Profession`=' . (($data['Profession'] !== '' && $data['Profession'] !== NULL) ? "'{$data['Profession']}'" : 'NULL') . ', `Ethnie`=' . (($data['Ethnie'] !== '' && $data['Ethnie'] !== NULL) ? "'{$data['Ethnie']}'" : 'NULL') . ', `Region`=' . (($data['Region'] !== '' && $data['Region'] !== NULL) ? "'{$data['Region']}'" : 'NULL') . " where `idoumrah`='".makeSafe($selected_id)."'", $o);
	if($o['error']!='') {
		echo $o['error'];
		echo '<a href="oumrah_view.php?SelectedID='.urlencode($selected_id)."\">{$Translation['< back']}</a>";
		exit;
	}


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

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

}

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

	$filterer_Pelerinage = thisOr(undo_magic_quotes($_REQUEST['filterer_Pelerinage']), '');

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

	// unique random identifier
	$rnd1 = ($dvprint ? rand(1000000, 9999999) : '');
	// combobox: Pelerinage
	$combo_Pelerinage = new DataCombo;
	// combobox: Datedenaissance
	$combo_Datedenaissance = new DateCombo;
	$combo_Datedenaissance->DateFormat = "dmy";
	$combo_Datedenaissance->MinYear = 1900;
	$combo_Datedenaissance->MaxYear = 2100;
	$combo_Datedenaissance->DefaultDate = parseMySQLDate('', '');
	$combo_Datedenaissance->MonthNames = $Translation['month names'];
	$combo_Datedenaissance->NamePrefix = 'Datedenaissance';

	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='oumrah' and pkValue='".makeSafe($selected_id)."'");
		$ownerMemberID=sqlValue("select lcase(memberID) from membership_userrecords where tableName='oumrah' 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 `oumrah` WHERE `idoumrah`='" . makeSafe($selected_id) . "'", $eo);
		if(!($row = db_fetch_array($res))) {
			return error_message($Translation['No records found'], 'oumrah_view.php', false);
		}
		$combo_Pelerinage->SelectedData = $row['Pelerinage'];
		$combo_Datedenaissance->DefaultDate = $row['Datedenaissance'];
		$row['total_entree'] = sqlValue("SELECT REPLACE(FORMAT(`total_entree`, 0), ',', ' ') FROM `oumrah` WHERE `idoumrah`='" . makeSafe($selected_id) . "'");
		$row['total_sortie'] = sqlValue("SELECT REPLACE(FORMAT(`total_sortie`, 0), ',', ' ') FROM `oumrah` WHERE `idoumrah`='" . makeSafe($selected_id) . "'");
		$row['solde'] = sqlValue("SELECT REPLACE(FORMAT(`solde`, 0), ',', ' ') FROM `oumrah` WHERE `idoumrah`='" . makeSafe($selected_id) . "'");
		$urow = $row; /* unsanitized data */
		$hc = new CI_Input();
		$row = $hc->xss_clean($row); /* sanitize data */
	} else {
		$combo_Pelerinage->SelectedData = $filterer_Pelerinage;
	}
	$combo_Pelerinage->HTML = '<span id="Pelerinage-container' . $rnd1 . '"></span><input type="hidden" name="Pelerinage" id="Pelerinage' . $rnd1 . '" value="' . html_attr($combo_Pelerinage->SelectedData) . '">';
	$combo_Pelerinage->MatchText = '<span id="Pelerinage-container-readonly' . $rnd1 . '"></span><input type="hidden" name="Pelerinage" id="Pelerinage' . $rnd1 . '" value="' . html_attr($combo_Pelerinage->SelectedData) . '">';

	ob_start();
	?>

	<script>
		// initial lookup values
		AppGini.current_Pelerinage__RAND__ = { text: "", value: "<?php echo addslashes($selected_id ? $urow['Pelerinage'] : $filterer_Pelerinage); ?>"};

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

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


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


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

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

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

		<?php }else{ ?>

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

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

	// process form title
	$templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Oumrah', $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 oumrah_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 oumrah_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 oumrah_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('#Pelerinage').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\tjQuery('#Pelerinage_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
		$jsReadOnly .= "\tjQuery('#Prenom').replaceWith('<div class=\"form-control-static\" id=\"Prenom\">' + (jQuery('#Prenom').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#Nom').replaceWith('<div class=\"form-control-static\" id=\"Nom\">' + (jQuery('#Nom').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#Datedenaissance').prop('readonly', true);\n";
		$jsReadOnly .= "\tjQuery('#DatedenaissanceDay, #DatedenaissanceMonth, #DatedenaissanceYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\tjQuery('#Lieudenaissance').replaceWith('<div class=\"form-control-static\" id=\"Lieudenaissance\">' + (jQuery('#Lieudenaissance').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#Adresse').replaceWith('<div class=\"form-control-static\" id=\"Adresse\">' + (jQuery('#Adresse').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#Sexe').replaceWith('<div class=\"form-control-static\" id=\"Sexe\">' + (jQuery('#Sexe').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#Numropasseport').replaceWith('<div class=\"form-control-static\" id=\"Numropasseport\">' + (jQuery('#Numropasseport').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#Remarque').replaceWith('<div class=\"form-control-static\" id=\"Remarque\">' + (jQuery('#Remarque').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#Tlphoneplerin').replaceWith('<div class=\"form-control-static\" id=\"Tlphoneplerin\">' + (jQuery('#Tlphoneplerin').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#Tlphonefamille').replaceWith('<div class=\"form-control-static\" id=\"Tlphonefamille\">' + (jQuery('#Tlphonefamille').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#Personnecontacter').replaceWith('<div class=\"form-control-static\" id=\"Personnecontacter\">' + (jQuery('#Personnecontacter').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#Squence').replaceWith('<div class=\"form-control-static\" id=\"Squence\">' + (jQuery('#Squence').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#Profession').replaceWith('<div class=\"form-control-static\" id=\"Profession\">' + (jQuery('#Profession').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#Ethnie').replaceWith('<div class=\"form-control-static\" id=\"Ethnie\">' + (jQuery('#Ethnie').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#Region').replaceWith('<div class=\"form-control-static\" id=\"Region\">' + (jQuery('#Region').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(Pelerinage)%%>', $combo_Pelerinage->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(Pelerinage)%%>', $combo_Pelerinage->MatchText, $templateCode);
	$templateCode = str_replace('<%%URLCOMBOTEXT(Pelerinage)%%>', urlencode($combo_Pelerinage->MatchText), $templateCode);
	$templateCode = str_replace('<%%COMBO(Datedenaissance)%%>', ($selected_id && !$arrPerm[3] ? '<div class="form-control-static">' . $combo_Datedenaissance->GetHTML(true) . '</div>' : $combo_Datedenaissance->GetHTML()), $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(Datedenaissance)%%>', $combo_Datedenaissance->GetHTML(true), $templateCode);

	/* lookup fields array: 'lookup field name' => array('parent table name', 'lookup field caption') */
	$lookup_fields = array('Pelerinage' => array('annees', 'Ann&#233;e'), );
	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(idoumrah)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(Pelerinage)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(Prenom)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(Nom)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(Datedenaissance)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(Lieudenaissance)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(Adresse)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(Sexe)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(Numropasseport)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(Remarque)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(Tlphoneplerin)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(Tlphonefamille)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(Personnecontacter)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(Squence)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(Profession)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(Ethnie)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(Region)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(total_entree)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(total_sortie)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(solde)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(groupe)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(agent)%%>', '', $templateCode);

	// process values
	if($selected_id) {
		if( $dvprint) $templateCode = str_replace('<%%VALUE(idoumrah)%%>', safe_html($urow['idoumrah']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(idoumrah)%%>', html_attr($row['idoumrah']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(idoumrah)%%>', urlencode($urow['idoumrah']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(Pelerinage)%%>', safe_html($urow['Pelerinage']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(Pelerinage)%%>', html_attr($row['Pelerinage']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Pelerinage)%%>', urlencode($urow['Pelerinage']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(Prenom)%%>', safe_html($urow['Prenom']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(Prenom)%%>', html_attr($row['Prenom']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Prenom)%%>', urlencode($urow['Prenom']), $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);
		$templateCode = str_replace('<%%VALUE(Datedenaissance)%%>', @date('d/m/Y', @strtotime(html_attr($row['Datedenaissance']))), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Datedenaissance)%%>', urlencode(@date('d/m/Y', @strtotime(html_attr($urow['Datedenaissance'])))), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(Lieudenaissance)%%>', safe_html($urow['Lieudenaissance']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(Lieudenaissance)%%>', html_attr($row['Lieudenaissance']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Lieudenaissance)%%>', urlencode($urow['Lieudenaissance']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(Adresse)%%>', safe_html($urow['Adresse']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(Adresse)%%>', html_attr($row['Adresse']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Adresse)%%>', urlencode($urow['Adresse']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(Sexe)%%>', safe_html($urow['Sexe']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(Sexe)%%>', html_attr($row['Sexe']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Sexe)%%>', urlencode($urow['Sexe']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(Numropasseport)%%>', safe_html($urow['Numropasseport']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(Numropasseport)%%>', html_attr($row['Numropasseport']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Numropasseport)%%>', urlencode($urow['Numropasseport']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(Remarque)%%>', safe_html($urow['Remarque']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(Remarque)%%>', html_attr($row['Remarque']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Remarque)%%>', urlencode($urow['Remarque']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(Tlphoneplerin)%%>', safe_html($urow['Tlphoneplerin']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(Tlphoneplerin)%%>', html_attr($row['Tlphoneplerin']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Tlphoneplerin)%%>', urlencode($urow['Tlphoneplerin']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(Tlphonefamille)%%>', safe_html($urow['Tlphonefamille']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(Tlphonefamille)%%>', html_attr($row['Tlphonefamille']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Tlphonefamille)%%>', urlencode($urow['Tlphonefamille']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(Personnecontacter)%%>', safe_html($urow['Personnecontacter']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(Personnecontacter)%%>', html_attr($row['Personnecontacter']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Personnecontacter)%%>', urlencode($urow['Personnecontacter']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(Squence)%%>', safe_html($urow['Squence']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(Squence)%%>', html_attr($row['Squence']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Squence)%%>', urlencode($urow['Squence']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(Profession)%%>', safe_html($urow['Profession']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(Profession)%%>', html_attr($row['Profession']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Profession)%%>', urlencode($urow['Profession']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(Ethnie)%%>', safe_html($urow['Ethnie']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(Ethnie)%%>', html_attr($row['Ethnie']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Ethnie)%%>', urlencode($urow['Ethnie']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(Region)%%>', safe_html($urow['Region']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(Region)%%>', html_attr($row['Region']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Region)%%>', urlencode($urow['Region']), $templateCode);
		$templateCode = str_replace('<%%VALUE(total_entree)%%>', safe_html($urow['total_entree']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(total_entree)%%>', urlencode($urow['total_entree']), $templateCode);
		$templateCode = str_replace('<%%VALUE(total_sortie)%%>', safe_html($urow['total_sortie']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(total_sortie)%%>', urlencode($urow['total_sortie']), $templateCode);
		$templateCode = str_replace('<%%VALUE(solde)%%>', safe_html($urow['solde']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(solde)%%>', urlencode($urow['solde']), $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(idoumrah)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(idoumrah)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(Pelerinage)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Pelerinage)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(Prenom)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Prenom)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(Nom)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Nom)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(Datedenaissance)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Datedenaissance)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(Lieudenaissance)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Lieudenaissance)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(Adresse)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Adresse)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(Sexe)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Sexe)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(Numropasseport)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Numropasseport)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(Remarque)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Remarque)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(Tlphoneplerin)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Tlphoneplerin)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(Tlphonefamille)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Tlphonefamille)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(Personnecontacter)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Personnecontacter)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(Squence)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Squence)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(Profession)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Profession)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(Ethnie)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Ethnie)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(Region)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Region)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(total_entree)%%>', '0', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(total_entree)%%>', urlencode('0'), $templateCode);
		$templateCode = str_replace('<%%VALUE(total_sortie)%%>', '0', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(total_sortie)%%>', urlencode('0'), $templateCode);
		$templateCode = str_replace('<%%VALUE(solde)%%>', '0', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(solde)%%>', urlencode('0'), $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});</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('oumrah');
	if($selected_id) {
		$jdata = get_joined_record('oumrah', $selected_id);
		if($jdata === false) $jdata = get_defaults('oumrah');
		$rdata = $row;
	}
	$templateCode .= loadView('oumrah-ajax-cache', array('rdata' => $rdata, 'jdata' => $jdata));

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

	return $templateCode;
}
?>