<?php

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

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

function details_decompte_insert(){
	global $Translation;

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

	$data['tranches'] = makeSafe($_REQUEST['tranches']);
		if($data['tranches'] == empty_lookup_value){ $data['tranches'] = ''; }
	$data['periodes'] = makeSafe($_REQUEST['periodes']);
		if($data['periodes'] == empty_lookup_value){ $data['periodes'] = ''; }
	$data['pourcentage'] = makeSafe($_REQUEST['pourcentage']);
		if($data['pourcentage'] == empty_lookup_value){ $data['pourcentage'] = ''; }
	$data['coef'] = makeSafe($_REQUEST['coef']);
		if($data['coef'] == empty_lookup_value){ $data['coef'] = ''; }
	$data['salaire_moyen'] = makeSafe($_REQUEST['salaire_moyen']);
		if($data['salaire_moyen'] == empty_lookup_value){ $data['salaire_moyen'] = ''; }
	$data['montant'] = makeSafe($_REQUEST['montant']);
		if($data['montant'] == empty_lookup_value){ $data['montant'] = ''; }
	$data['mois_preavis'] = makeSafe($_REQUEST['mois_preavis']);
		if($data['mois_preavis'] == empty_lookup_value){ $data['mois_preavis'] = ''; }
	$data['mois_conge'] = makeSafe($_REQUEST['mois_conge']);
		if($data['mois_conge'] == empty_lookup_value){ $data['mois_conge'] = ''; }
	$data['to_decomptes'] = makeSafe($_REQUEST['to_decomptes']);
		if($data['to_decomptes'] == empty_lookup_value){ $data['to_decomptes'] = ''; }

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

	$o = array('silentErrors' => true);
	sql('insert into `details_decompte` set       `tranches`=' . (($data['tranches'] !== '' && $data['tranches'] !== NULL) ? "'{$data['tranches']}'" : 'NULL') . ', `periodes`=' . (($data['periodes'] !== '' && $data['periodes'] !== NULL) ? "'{$data['periodes']}'" : 'NULL') . ', `pourcentage`=' . (($data['pourcentage'] !== '' && $data['pourcentage'] !== NULL) ? "'{$data['pourcentage']}'" : 'NULL') . ', `coef`=' . (($data['coef'] !== '' && $data['coef'] !== NULL) ? "'{$data['coef']}'" : 'NULL') . ', `salaire_moyen`=' . (($data['salaire_moyen'] !== '' && $data['salaire_moyen'] !== NULL) ? "'{$data['salaire_moyen']}'" : 'NULL') . ', `montant`=' . (($data['montant'] !== '' && $data['montant'] !== NULL) ? "'{$data['montant']}'" : 'NULL') . ', `mois_preavis`=' . (($data['mois_preavis'] !== '' && $data['mois_preavis'] !== NULL) ? "'{$data['mois_preavis']}'" : 'NULL') . ', `mois_conge`=' . (($data['mois_conge'] !== '' && $data['mois_conge'] !== NULL) ? "'{$data['mois_conge']}'" : 'NULL'), $o);
	if($o['error']!=''){
		echo $o['error'];
		echo "<a href=\"details_decompte_view.php?addNew_x=1\">{$Translation['< back']}</a>";
		exit;
	}

	$recID = db_insert_id(db_link());
	// enforce pk zerofill
	$recID = str_pad($recID, sqlValue("select length(`iddetail_decompte`) from `details_decompte` limit 1"), '0', STR_PAD_LEFT);

	// automatic to_decomptes
	if($_REQUEST['filterer_to_decomptes']){
		sql("update `details_decompte` set `to_decomptes`='" . makeSafe($_REQUEST['filterer_to_decomptes']) . "' where `iddetail_decompte`='" . makeSafe($recID, false) . "'", $eo);
	}

	// hook: details_decompte_after_insert
	if(function_exists('details_decompte_after_insert')){
		$res = sql("select * from `details_decompte` where `iddetail_decompte`='" . 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(!details_decompte_after_insert($data, getMemberInfo(), $args)){ return $recID; }
	}

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

	return $recID;
}

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

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

	sql("delete from `details_decompte` where `iddetail_decompte`='$selected_id'", $eo);

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

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

function details_decompte_update($selected_id){
	global $Translation;

	// mm: can member edit record?
	$arrPerm=getTablePermissions('details_decompte');
	$ownerGroupID=sqlValue("select groupID from membership_userrecords where tableName='details_decompte' and pkValue='".makeSafe($selected_id)."'");
	$ownerMemberID=sqlValue("select lcase(memberID) from membership_userrecords where tableName='details_decompte' 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['tranches'] = makeSafe($_REQUEST['tranches']);
		if($data['tranches'] == empty_lookup_value){ $data['tranches'] = ''; }
	$data['periodes'] = makeSafe($_REQUEST['periodes']);
		if($data['periodes'] == empty_lookup_value){ $data['periodes'] = ''; }
	$data['pourcentage'] = makeSafe($_REQUEST['pourcentage']);
		if($data['pourcentage'] == empty_lookup_value){ $data['pourcentage'] = ''; }
	$data['coef'] = makeSafe($_REQUEST['coef']);
		if($data['coef'] == empty_lookup_value){ $data['coef'] = ''; }
	$data['salaire_moyen'] = makeSafe($_REQUEST['salaire_moyen']);
		if($data['salaire_moyen'] == empty_lookup_value){ $data['salaire_moyen'] = ''; }
	$data['montant'] = makeSafe($_REQUEST['montant']);
		if($data['montant'] == empty_lookup_value){ $data['montant'] = ''; }
	$data['mois_preavis'] = makeSafe($_REQUEST['mois_preavis']);
		if($data['mois_preavis'] == empty_lookup_value){ $data['mois_preavis'] = ''; }
	$data['mois_conge'] = makeSafe($_REQUEST['mois_conge']);
		if($data['mois_conge'] == empty_lookup_value){ $data['mois_conge'] = ''; }
	$data['to_decomptes'] = makeSafe($_REQUEST['to_decomptes']);
		if($data['to_decomptes'] == empty_lookup_value){ $data['to_decomptes'] = ''; }
	$data['selectedID']=makeSafe($selected_id);

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

	$o=array('silentErrors' => true);
	sql('update `details_decompte` set       `tranches`=' . (($data['tranches'] !== '' && $data['tranches'] !== NULL) ? "'{$data['tranches']}'" : 'NULL') . ', `periodes`=' . (($data['periodes'] !== '' && $data['periodes'] !== NULL) ? "'{$data['periodes']}'" : 'NULL') . ', `pourcentage`=' . (($data['pourcentage'] !== '' && $data['pourcentage'] !== NULL) ? "'{$data['pourcentage']}'" : 'NULL') . ', `coef`=' . (($data['coef'] !== '' && $data['coef'] !== NULL) ? "'{$data['coef']}'" : 'NULL') . ', `salaire_moyen`=' . (($data['salaire_moyen'] !== '' && $data['salaire_moyen'] !== NULL) ? "'{$data['salaire_moyen']}'" : 'NULL') . ', `montant`=' . (($data['montant'] !== '' && $data['montant'] !== NULL) ? "'{$data['montant']}'" : 'NULL') . ', `mois_preavis`=' . (($data['mois_preavis'] !== '' && $data['mois_preavis'] !== NULL) ? "'{$data['mois_preavis']}'" : 'NULL') . ', `mois_conge`=' . (($data['mois_conge'] !== '' && $data['mois_conge'] !== NULL) ? "'{$data['mois_conge']}'" : 'NULL') . " where `iddetail_decompte`='".makeSafe($selected_id)."'", $o);
	if($o['error']!=''){
		echo $o['error'];
		echo '<a href="details_decompte_view.php?SelectedID='.urlencode($selected_id)."\">{$Translation['< back']}</a>";
		exit;
	}


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

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

}

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

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

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

	// unique random identifier
	$rnd1 = ($dvprint ? rand(1000000, 9999999) : '');
	// combobox: tranches
	$combo_tranches = new Combo;
	$combo_tranches->ListType = 0;
	$combo_tranches->MultipleSeparator = ', ';
	$combo_tranches->ListBoxHeight = 10;
	$combo_tranches->RadiosPerLine = 1;
	if(is_file(dirname(__FILE__).'/hooks/details_decompte.tranches.csv')){
		$tranches_data = addslashes(implode('', @file(dirname(__FILE__).'/hooks/details_decompte.tranches.csv')));
		$combo_tranches->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($tranches_data)));
		$combo_tranches->ListData = $combo_tranches->ListItem;
	}else{
		$combo_tranches->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("1&#232;re tranche;;2&#232;me tranche;;3&#232;me tranche;;4&#232;me tranche")));
		$combo_tranches->ListData = $combo_tranches->ListItem;
	}
	$combo_tranches->SelectName = 'tranches';
	// combobox: periodes
	$combo_periodes = new Combo;
	$combo_periodes->ListType = 0;
	$combo_periodes->MultipleSeparator = ', ';
	$combo_periodes->ListBoxHeight = 10;
	$combo_periodes->RadiosPerLine = 1;
	if(is_file(dirname(__FILE__).'/hooks/details_decompte.periodes.csv')){
		$periodes_data = addslashes(implode('', @file(dirname(__FILE__).'/hooks/details_decompte.periodes.csv')));
		$combo_periodes->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($periodes_data)));
		$combo_periodes->ListData = $combo_periodes->ListItem;
	}else{
		$combo_periodes->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("5 premi&#232;res ann&#233;es;;entre 6 et 10 ans;;au-del&#224; de 10 ans et moins de 20 ans;;au-del&#224; de 20ans")));
		$combo_periodes->ListData = $combo_periodes->ListItem;
	}
	$combo_periodes->SelectName = 'periodes';
	// combobox: to_decomptes
	$combo_to_decomptes = 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='details_decompte' and pkValue='".makeSafe($selected_id)."'");
		$ownerMemberID=sqlValue("select lcase(memberID) from membership_userrecords where tableName='details_decompte' 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 `details_decompte` where `iddetail_decompte`='".makeSafe($selected_id)."'", $eo);
		if(!($row = db_fetch_array($res))){
			return error_message($Translation['No records found'], 'details_decompte_view.php', false);
		}
		$urow = $row; /* unsanitized data */
		$hc = new CI_Input();
		$row = $hc->xss_clean($row); /* sanitize data */
		$combo_tranches->SelectedData = $row['tranches'];
		$combo_periodes->SelectedData = $row['periodes'];
		$combo_to_decomptes->SelectedData = $row['to_decomptes'];
	}else{
		$combo_tranches->SelectedText = ( $_REQUEST['FilterField'][1]=='2' && $_REQUEST['FilterOperator'][1]=='<=>' ? (get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1]) : "");
		$combo_periodes->SelectedText = ( $_REQUEST['FilterField'][1]=='3' && $_REQUEST['FilterOperator'][1]=='<=>' ? (get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1]) : "");
		$combo_to_decomptes->SelectedData = $filterer_to_decomptes;
	}
	$combo_tranches->Render();
	$combo_periodes->Render();
	$combo_to_decomptes->HTML = '<span id="to_decomptes-container' . $rnd1 . '"></span><input type="hidden" name="to_decomptes" id="to_decomptes' . $rnd1 . '" value="' . html_attr($combo_to_decomptes->SelectedData) . '">';
	$combo_to_decomptes->MatchText = '<span id="to_decomptes-container-readonly' . $rnd1 . '"></span><input type="hidden" name="to_decomptes" id="to_decomptes' . $rnd1 . '" value="' . html_attr($combo_to_decomptes->SelectedData) . '">';

	ob_start();
	?>

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

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

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


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


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

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

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

		<?php }else{ ?>

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

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

	// process form title
	$templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Informations', $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 details_decompte_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 details_decompte_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 details_decompte_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('#tranches').replaceWith('<div class=\"form-control-static\" id=\"tranches\">' + (jQuery('#tranches').val() || '') + '</div>'); jQuery('#tranches-multi-selection-help').hide();\n";
		$jsReadOnly .= "\tjQuery('#periodes').replaceWith('<div class=\"form-control-static\" id=\"periodes\">' + (jQuery('#periodes').val() || '') + '</div>'); jQuery('#periodes-multi-selection-help').hide();\n";
		$jsReadOnly .= "\tjQuery('#pourcentage').replaceWith('<div class=\"form-control-static\" id=\"pourcentage\">' + (jQuery('#pourcentage').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#coef').replaceWith('<div class=\"form-control-static\" id=\"coef\">' + (jQuery('#coef').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#salaire_moyen').replaceWith('<div class=\"form-control-static\" id=\"salaire_moyen\">' + (jQuery('#salaire_moyen').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#montant').replaceWith('<div class=\"form-control-static\" id=\"montant\">' + (jQuery('#montant').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#mois_preavis').replaceWith('<div class=\"form-control-static\" id=\"mois_preavis\">' + (jQuery('#mois_preavis').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#mois_conge').replaceWith('<div class=\"form-control-static\" id=\"mois_conge\">' + (jQuery('#mois_conge').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(tranches)%%>', $combo_tranches->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(tranches)%%>', $combo_tranches->SelectedData, $templateCode);
	$templateCode = str_replace('<%%COMBO(periodes)%%>', $combo_periodes->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(periodes)%%>', $combo_periodes->SelectedData, $templateCode);
	$templateCode = str_replace('<%%COMBO(to_decomptes)%%>', $combo_to_decomptes->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(to_decomptes)%%>', $combo_to_decomptes->MatchText, $templateCode);
	$templateCode = str_replace('<%%URLCOMBOTEXT(to_decomptes)%%>', urlencode($combo_to_decomptes->MatchText), $templateCode);

	/* lookup fields array: 'lookup field name' => array('parent table name', 'lookup field caption') */
	$lookup_fields = array(  'to_decomptes' => array('decomptes', 'To decomptes'));
	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(iddetail_decompte)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(tranches)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(periodes)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(pourcentage)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(coef)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(salaire_moyen)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(montant)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(mois_preavis)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(mois_conge)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(to_decomptes)%%>', '', $templateCode);

	// process values
	if($selected_id){
		if( $dvprint) $templateCode = str_replace('<%%VALUE(iddetail_decompte)%%>', safe_html($urow['iddetail_decompte']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(iddetail_decompte)%%>', html_attr($row['iddetail_decompte']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(iddetail_decompte)%%>', urlencode($urow['iddetail_decompte']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(tranches)%%>', safe_html($urow['tranches']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(tranches)%%>', html_attr($row['tranches']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(tranches)%%>', urlencode($urow['tranches']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(periodes)%%>', safe_html($urow['periodes']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(periodes)%%>', html_attr($row['periodes']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(periodes)%%>', urlencode($urow['periodes']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(pourcentage)%%>', safe_html($urow['pourcentage']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(pourcentage)%%>', html_attr($row['pourcentage']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(pourcentage)%%>', urlencode($urow['pourcentage']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(coef)%%>', safe_html($urow['coef']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(coef)%%>', html_attr($row['coef']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(coef)%%>', urlencode($urow['coef']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(salaire_moyen)%%>', safe_html($urow['salaire_moyen']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(salaire_moyen)%%>', html_attr($row['salaire_moyen']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(salaire_moyen)%%>', urlencode($urow['salaire_moyen']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(montant)%%>', safe_html($urow['montant']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(montant)%%>', html_attr($row['montant']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(montant)%%>', urlencode($urow['montant']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(mois_preavis)%%>', safe_html($urow['mois_preavis']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(mois_preavis)%%>', html_attr($row['mois_preavis']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(mois_preavis)%%>', urlencode($urow['mois_preavis']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(mois_conge)%%>', safe_html($urow['mois_conge']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(mois_conge)%%>', html_attr($row['mois_conge']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(mois_conge)%%>', urlencode($urow['mois_conge']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(to_decomptes)%%>', safe_html($urow['to_decomptes']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(to_decomptes)%%>', html_attr($row['to_decomptes']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(to_decomptes)%%>', urlencode($urow['to_decomptes']), $templateCode);
	}else{
		$templateCode = str_replace('<%%VALUE(iddetail_decompte)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(iddetail_decompte)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(tranches)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(tranches)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(periodes)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(periodes)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(pourcentage)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(pourcentage)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(coef)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(coef)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(salaire_moyen)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(salaire_moyen)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(montant)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(montant)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(mois_preavis)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(mois_preavis)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(mois_conge)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(mois_conge)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(to_decomptes)%%>', ( $_REQUEST['FilterField'][1]=='10' && $_REQUEST['FilterOperator'][1]=='<=>' ? $combo_to_decomptes->SelectedData : ''), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(to_decomptes)%%>', urlencode( $_REQUEST['FilterField'][1]=='10' && $_REQUEST['FilterOperator'][1]=='<=>' ? $combo_to_decomptes->SelectedData : ''), $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('details_decompte');
	if($selected_id){
		$jdata = get_joined_record('details_decompte', $selected_id);
		if($jdata === false) $jdata = get_defaults('details_decompte');
		$rdata = $row;
	}
	$templateCode .= loadView('details_decompte-ajax-cache', array('rdata' => $rdata, 'jdata' => $jdata));

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

	return $templateCode;
}
?>