?>
</td>
			<td class="tdCell" align="left"><?php 
    echo thisOr($row[3]);
    ?>
</td>
			<td class="tdCell" align="left"><?php 
    echo thisOr($row[4]);
    ?>
</td>
			<td class="tdCell" align="left"><?php 
    echo thisOr($row[5]);
    ?>
</td>
			<td class="tdCell" align="left"><?php 
    echo thisOr($row[6]);
    ?>
</td>
			<td class="tdCell" align="left">
				<?php 
    echo $row[7] && $row[8] ? "Banned" : ($row[8] ? "Active" : "Waiting approval");
    ?>
				</td>
			<td class="tdCaptionCell" align="left">
				<?php 
    if (!$row[8]) {
        // if member is not approved, display approve link
        ?>
<a href="pageChangeMemberStatus.php?memberID=<?php 
        echo $row[0];
        ?>
Пример #2
0
"></i></a>
						<?php 
    } else {
        echo "&nbsp; &nbsp;";
    }
    ?>
				</td>
			<td class="tdCell" align="left"><a href="pageEditGroup.php?groupID=<?php 
    echo $row[0];
    ?>
"><?php 
    echo $row[1];
    ?>
</a></td>
			<td class="tdCell" align="left"><?php 
    echo thisOr($row[2]);
    ?>
</td>
			<td align="right" class="tdCell">
				<?php 
    echo $groupMembersCount;
    ?>
				</td>
			<td class="tdCaptionCell" align="left">
				<a href="pageEditMember.php?groupID=<?php 
    echo $row[0];
    ?>
"><i class="glyphicon glyphicon-plus-sign" title="<?php 
    echo $Translation["add new member"];
    ?>
"></i></a>
				<td><?php 
        echo $fn;
        ?>
</td>
				<td class="<?php 
        echo $diff ? 'bold text-success' : '';
        ?>
"><?php 
        echo $fd['appgini'];
        ?>
</td>
				<td class="<?php 
        echo $diff ? 'bold text-danger' : '';
        ?>
"><?php 
        echo thisOr($fd['db'], "Doesn't exist!");
        ?>
</td>
				<td>
					<?php 
        if ($diff && $no_db) {
            ?>
						<a href="pageRebuildFields.php?t=<?php 
            echo $tn;
            ?>
&f=<?php 
            echo $fn;
            ?>
" class="btn btn-success btn-xs btn_create" data-toggle="tooltip" data-placement="top" title="Create the field by running an ADD COLUMN query."><i class="glyphicon glyphicon-plus"></i> Create it</a>
					<?php 
        } elseif ($diff) {
Пример #4
0
function orders_form($selected_id = '', $AllowUpdate = 1, $AllowInsert = 1, $AllowDelete = 1, $ShowCancel = 0)
{
    // function to return an editable form for a table records
    // and fill it with data of record whose ID is $selected_id. If $selected_id
    // is empty, an empty form is shown, with only an 'Add New'
    // button displayed.
    global $Translation;
    // mm: get table permissions
    $arrPerm = getTablePermissions('orders');
    if (!$arrPerm[1] && $selected_id == '') {
        return '';
    }
    $AllowInsert = $arrPerm[1] ? true : false;
    // print preview?
    $dvprint = false;
    if ($selected_id && $_REQUEST['dvprint_x'] != '') {
        $dvprint = true;
    }
    $filterer_CustomerID = thisOr(undo_magic_quotes($_REQUEST['filterer_CustomerID']), '');
    $filterer_EmployeeID = thisOr(undo_magic_quotes($_REQUEST['filterer_EmployeeID']), '');
    $filterer_ShipVia = thisOr(undo_magic_quotes($_REQUEST['filterer_ShipVia']), '');
    // populate filterers, starting from children to grand-parents
    // unique random identifier
    $rnd1 = $dvprint ? rand(1000000, 9999999) : '';
    // combobox: CustomerID
    $combo_CustomerID = new DataCombo();
    // combobox: EmployeeID
    $combo_EmployeeID = new DataCombo();
    // combobox: OrderDate
    $combo_OrderDate = new DateCombo();
    $combo_OrderDate->DateFormat = "mdy";
    $combo_OrderDate->MinYear = 1900;
    $combo_OrderDate->MaxYear = 2100;
    $combo_OrderDate->DefaultDate = parseMySQLDate('1', '1');
    $combo_OrderDate->MonthNames = $Translation['month names'];
    $combo_OrderDate->NamePrefix = 'OrderDate';
    // combobox: RequiredDate
    $combo_RequiredDate = new DateCombo();
    $combo_RequiredDate->DateFormat = "mdy";
    $combo_RequiredDate->MinYear = 1900;
    $combo_RequiredDate->MaxYear = 2100;
    $combo_RequiredDate->DefaultDate = parseMySQLDate('1', '1');
    $combo_RequiredDate->MonthNames = $Translation['month names'];
    $combo_RequiredDate->NamePrefix = 'RequiredDate';
    // combobox: ShippedDate
    $combo_ShippedDate = new DateCombo();
    $combo_ShippedDate->DateFormat = "mdy";
    $combo_ShippedDate->MinYear = 1900;
    $combo_ShippedDate->MaxYear = 2100;
    $combo_ShippedDate->DefaultDate = parseMySQLDate('', '');
    $combo_ShippedDate->MonthNames = $Translation['month names'];
    $combo_ShippedDate->NamePrefix = 'ShippedDate';
    // combobox: ShipVia
    $combo_ShipVia = new DataCombo();
    if ($selected_id) {
        // mm: check member permissions
        if (!$arrPerm[2]) {
            return "";
        }
        // mm: who is the owner?
        $ownerGroupID = sqlValue("select groupID from membership_userrecords where tableName='orders' and pkValue='" . makeSafe($selected_id) . "'");
        $ownerMemberID = sqlValue("select lcase(memberID) from membership_userrecords where tableName='orders' and pkValue='" . makeSafe($selected_id) . "'");
        if ($arrPerm[2] == 1 && getLoggedMemberID() != $ownerMemberID) {
            return "";
        }
        if ($arrPerm[2] == 2 && getLoggedGroupID() != $ownerGroupID) {
            return "";
        }
        // can edit?
        if ($arrPerm[3] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[3] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[3] == 3) {
            $AllowUpdate = 1;
        } else {
            $AllowUpdate = 0;
        }
        $res = sql("select * from `orders` where `OrderID`='" . makeSafe($selected_id) . "'", $eo);
        if (!($row = db_fetch_array($res))) {
            return error_message($Translation['No records found']);
        }
        $urow = $row;
        /* unsanitized data */
        $hc = new CI_Input();
        $row = $hc->xss_clean($row);
        /* sanitize data */
        $combo_CustomerID->SelectedData = $row['CustomerID'];
        $combo_EmployeeID->SelectedData = $row['EmployeeID'];
        $combo_OrderDate->DefaultDate = $row['OrderDate'];
        $combo_RequiredDate->DefaultDate = $row['RequiredDate'];
        $combo_ShippedDate->DefaultDate = $row['ShippedDate'];
        $combo_ShipVia->SelectedData = $row['ShipVia'];
    } else {
        $combo_CustomerID->SelectedData = $filterer_CustomerID;
        $combo_EmployeeID->SelectedData = $filterer_EmployeeID;
        $combo_ShipVia->SelectedData = $filterer_ShipVia;
    }
    $combo_CustomerID->HTML = '<span id="CustomerID-container' . $rnd1 . '"></span><input type="hidden" name="CustomerID" id="CustomerID' . $rnd1 . '" value="' . htmlspecialchars($combo_CustomerID->SelectedData, ENT_QUOTES, 'iso-8859-1') . '">';
    $combo_CustomerID->MatchText = '<span id="CustomerID-container-readonly' . $rnd1 . '"></span><input type="hidden" name="CustomerID" id="CustomerID' . $rnd1 . '" value="' . htmlspecialchars($combo_CustomerID->SelectedData, ENT_QUOTES, 'iso-8859-1') . '">';
    $combo_EmployeeID->HTML = '<span id="EmployeeID-container' . $rnd1 . '"></span><input type="hidden" name="EmployeeID" id="EmployeeID' . $rnd1 . '" value="' . htmlspecialchars($combo_EmployeeID->SelectedData, ENT_QUOTES, 'iso-8859-1') . '">';
    $combo_EmployeeID->MatchText = '<span id="EmployeeID-container-readonly' . $rnd1 . '"></span><input type="hidden" name="EmployeeID" id="EmployeeID' . $rnd1 . '" value="' . htmlspecialchars($combo_EmployeeID->SelectedData, ENT_QUOTES, 'iso-8859-1') . '">';
    $combo_ShipVia->HTML = '<span id="ShipVia-container' . $rnd1 . '"></span><input type="hidden" name="ShipVia" id="ShipVia' . $rnd1 . '" value="' . htmlspecialchars($combo_ShipVia->SelectedData, ENT_QUOTES, 'iso-8859-1') . '">';
    $combo_ShipVia->MatchText = '<span id="ShipVia-container-readonly' . $rnd1 . '"></span><input type="hidden" name="ShipVia" id="ShipVia' . $rnd1 . '" value="' . htmlspecialchars($combo_ShipVia->SelectedData, ENT_QUOTES, 'iso-8859-1') . '">';
    ob_start();
    ?>

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

		jQuery(function() {
			if(typeof(CustomerID_reload__RAND__) == 'function') CustomerID_reload__RAND__();
			if(typeof(EmployeeID_reload__RAND__) == 'function') EmployeeID_reload__RAND__();
			if(typeof(ShipVia_reload__RAND__) == 'function') ShipVia_reload__RAND__();
		});
		function CustomerID_reload__RAND__(){
		<?php 
    if (($AllowUpdate || $AllowInsert) && !$dvprint) {
        ?>

			jQuery("#CustomerID-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					jQuery.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: current_CustomerID__RAND__.value, t: 'orders', f: 'CustomerID' }
					}).done(function(resp){
						c({
							id: resp.results[0].id,
							text: resp.results[0].text
						});
						jQuery('[name="CustomerID"]').val(resp.results[0].id);
						jQuery('[id=CustomerID-container-readonly__RAND__]').html('<span id="CustomerID-match-text">' + resp.results[0].text + '</span>');


						if(typeof(CustomerID_update_autofills__RAND__) == 'function') CustomerID_update_autofills__RAND__();
					});
				},
				width: ($j('fieldset .col-xs-11').width() - 99) + 'px',
				formatNoMatches: function(term){ return '<?php 
        echo addslashes($Translation['No matches found!']);
        ?>
'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { s: term, p: page, t: 'orders', f: 'CustomerID' }; },
					results: function(resp, page){ return resp; }
				}
			}).on('change', function(e){
				current_CustomerID__RAND__.value = e.added.id;
				current_CustomerID__RAND__.text = e.added.text;
				jQuery('[name="CustomerID"]').val(e.added.id);


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

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

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

		<?php 
    } else {
        ?>

			jQuery.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: current_CustomerID__RAND__.value, t: 'orders', f: 'CustomerID' }
			}).done(function(resp){
				jQuery('[id=CustomerID-container__RAND__], [id=CustomerID-container-readonly__RAND__]').html('<span id="CustomerID-match-text">' + resp.results[0].text + '</span>');

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

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

			jQuery("#EmployeeID-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					jQuery.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: current_EmployeeID__RAND__.value, t: 'orders', f: 'EmployeeID' }
					}).done(function(resp){
						c({
							id: resp.results[0].id,
							text: resp.results[0].text
						});
						jQuery('[name="EmployeeID"]').val(resp.results[0].id);
						jQuery('[id=EmployeeID-container-readonly__RAND__]').html('<span id="EmployeeID-match-text">' + resp.results[0].text + '</span>');


						if(typeof(EmployeeID_update_autofills__RAND__) == 'function') EmployeeID_update_autofills__RAND__();
					});
				},
				width: ($j('fieldset .col-xs-11').width() - 99) + 'px',
				formatNoMatches: function(term){ return '<?php 
        echo addslashes($Translation['No matches found!']);
        ?>
'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { s: term, p: page, t: 'orders', f: 'EmployeeID' }; },
					results: function(resp, page){ return resp; }
				}
			}).on('change', function(e){
				current_EmployeeID__RAND__.value = e.added.id;
				current_EmployeeID__RAND__.text = e.added.text;
				jQuery('[name="EmployeeID"]').val(e.added.id);


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

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

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

		<?php 
    } else {
        ?>

			jQuery.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: current_EmployeeID__RAND__.value, t: 'orders', f: 'EmployeeID' }
			}).done(function(resp){
				jQuery('[id=EmployeeID-container__RAND__], [id=EmployeeID-container-readonly__RAND__]').html('<span id="EmployeeID-match-text">' + resp.results[0].text + '</span>');

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

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

			jQuery("#ShipVia-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					jQuery.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: current_ShipVia__RAND__.value, t: 'orders', f: 'ShipVia' }
					}).done(function(resp){
						c({
							id: resp.results[0].id,
							text: resp.results[0].text
						});
						jQuery('[name="ShipVia"]').val(resp.results[0].id);
						jQuery('[id=ShipVia-container-readonly__RAND__]').html('<span id="ShipVia-match-text">' + resp.results[0].text + '</span>');


						if(typeof(ShipVia_update_autofills__RAND__) == 'function') ShipVia_update_autofills__RAND__();
					});
				},
				width: ($j('fieldset .col-xs-11').width() - 99) + 'px',
				formatNoMatches: function(term){ return '<?php 
        echo addslashes($Translation['No matches found!']);
        ?>
'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { s: term, p: page, t: 'orders', f: 'ShipVia' }; },
					results: function(resp, page){ return resp; }
				}
			}).on('change', function(e){
				current_ShipVia__RAND__.value = e.added.id;
				current_ShipVia__RAND__.text = e.added.text;
				jQuery('[name="ShipVia"]').val(e.added.id);


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

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

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

		<?php 
    } else {
        ?>

			jQuery.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: current_ShipVia__RAND__.value, t: 'orders', f: 'ShipVia' }
			}).done(function(resp){
				jQuery('[id=ShipVia-container__RAND__], [id=ShipVia-container-readonly__RAND__]').html('<span id="ShipVia-match-text">' + resp.results[0].text + '</span>');

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

		}
	</script>
	<?php 
    $lookups = str_replace('__RAND__', $rnd1, ob_get_contents());
    ob_end_clean();
    // code for template based detail view forms
    // open the detail view template
    if ($dvprint) {
        $templateCode = @file_get_contents('./templates/orders_templateDVP.html');
    } else {
        $templateCode = @file_get_contents('./templates/orders_templateDV.html');
    }
    // process form title
    $templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Detail View', $templateCode);
    $templateCode = str_replace('<%%RND1%%>', $rnd1, $templateCode);
    $templateCode = str_replace('<%%EMBEDDED%%>', $_REQUEST['Embedded'] ? 'Embedded=1' : '', $templateCode);
    // process buttons
    if ($arrPerm[1] && !$selected_id) {
        // allow insert and no record selected?
        if (!$selected_id) {
            $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-success" id="insert" name="insert_x" value="1" onclick="return orders_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save New'] . '</button>', $templateCode);
        }
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="insert" name="insert_x" value="1" onclick="return orders_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save As Copy'] . '</button>', $templateCode);
    } else {
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '', $templateCode);
    }
    // 'Back' button action
    if ($_REQUEST['Embedded']) {
        $backAction = 'window.parent.jQuery(\'.modal\').modal(\'hide\'); return false;';
    } else {
        $backAction = '$$(\'form\')[0].writeAttribute(\'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="$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;"><i class="glyphicon glyphicon-print"></i> ' . $Translation['Print Preview'] . '</button>', $templateCode);
        }
        if ($AllowUpdate) {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '<button type="submit" class="btn btn-success btn-lg" id="update" name="update_x" value="1" onclick="return orders_validateData();"><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?'] . '\');"><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 . '"><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 . '"><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 || !$selected_id && !$AllowInsert) {
        $jsReadOnly .= "\tjQuery('#CustomerID').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#CustomerID_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
        $jsReadOnly .= "\tjQuery('#EmployeeID').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#EmployeeID_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
        $jsReadOnly .= "\tjQuery('#OrderDate').prop('readonly', true);\n";
        $jsReadOnly .= "\tjQuery('#OrderDateDay, #OrderDateMonth, #OrderDateYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#RequiredDate').prop('readonly', true);\n";
        $jsReadOnly .= "\tjQuery('#RequiredDateDay, #RequiredDateMonth, #RequiredDateYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#ShippedDate').prop('readonly', true);\n";
        $jsReadOnly .= "\tjQuery('#ShippedDateDay, #ShippedDateMonth, #ShippedDateYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#ShipVia').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#ShipVia_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
        $jsReadOnly .= "\tjQuery('#Freight').replaceWith('<div class=\"form-control-static\" id=\"Freight\">' + (jQuery('#Freight').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('.select2-container').hide();\n";
        $noUploads = true;
    } elseif ($AllowInsert && !$selected_id || $AllowUpdate && $selected_id) {
        $jsEditable .= "\tjQuery('form').eq(0).data('already_changed', true);";
        // temporarily disable form change handler
        $jsEditable .= "\tjQuery('form').eq(0).data('already_changed', false);";
        // re-enable form change handler
    }
    // process combos
    $templateCode = str_replace('<%%COMBO(CustomerID)%%>', $combo_CustomerID->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(CustomerID)%%>', $combo_CustomerID->MatchText, $templateCode);
    $templateCode = str_replace('<%%URLCOMBOTEXT(CustomerID)%%>', urlencode($combo_CustomerID->MatchText), $templateCode);
    $templateCode = str_replace('<%%COMBO(EmployeeID)%%>', $combo_EmployeeID->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(EmployeeID)%%>', $combo_EmployeeID->MatchText, $templateCode);
    $templateCode = str_replace('<%%URLCOMBOTEXT(EmployeeID)%%>', urlencode($combo_EmployeeID->MatchText), $templateCode);
    $templateCode = str_replace('<%%COMBO(OrderDate)%%>', $selected_id && !$arrPerm[3] ? '<div class="form-control-static">' . $combo_OrderDate->GetHTML(true) . '</div>' : $combo_OrderDate->GetHTML(), $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(OrderDate)%%>', $combo_OrderDate->GetHTML(true), $templateCode);
    $templateCode = str_replace('<%%COMBO(RequiredDate)%%>', $selected_id && !$arrPerm[3] ? '<div class="form-control-static">' . $combo_RequiredDate->GetHTML(true) . '</div>' : $combo_RequiredDate->GetHTML(), $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(RequiredDate)%%>', $combo_RequiredDate->GetHTML(true), $templateCode);
    $templateCode = str_replace('<%%COMBO(ShippedDate)%%>', $selected_id && !$arrPerm[3] ? '<div class="form-control-static">' . $combo_ShippedDate->GetHTML(true) . '</div>' : $combo_ShippedDate->GetHTML(), $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(ShippedDate)%%>', $combo_ShippedDate->GetHTML(true), $templateCode);
    $templateCode = str_replace('<%%COMBO(ShipVia)%%>', $combo_ShipVia->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(ShipVia)%%>', $combo_ShipVia->MatchText, $templateCode);
    $templateCode = str_replace('<%%URLCOMBOTEXT(ShipVia)%%>', urlencode($combo_ShipVia->MatchText), $templateCode);
    /* lookup fields array: 'lookup field name' => array('parent table name', 'lookup field caption') */
    $lookup_fields = array('CustomerID' => array('customers', 'Customer'), 'EmployeeID' => array('employees', 'Employee'), 'ShipVia' => array('shippers', 'Ship Via'));
    foreach ($lookup_fields as $luf => $ptfc) {
        $pt_perm = getTablePermissions($ptfc[0]);
        // process foreign key links
        if ($pt_perm['view'] || $pt_perm['edit']) {
            $templateCode = str_replace("<%%PLINK({$luf})%%>", '<button type="button" class="btn btn-default view_parent hspacer-lg" id="' . $ptfc[0] . '_view_parent" title="' . htmlspecialchars($Translation['View'] . ' ' . $ptfc[1], ENT_QUOTES, 'iso-8859-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" id="' . $ptfc[0] . '_add_new" title="' . htmlspecialchars($Translation['Add New'] . ' ' . $ptfc[1], ENT_QUOTES, 'iso-8859-1') . '"><i class="glyphicon glyphicon-plus-sign"></i></button>', $templateCode);
        }
    }
    // process images
    $templateCode = str_replace('<%%UPLOADFILE(OrderID)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(CustomerID)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(EmployeeID)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(OrderDate)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(RequiredDate)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(ShippedDate)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(ShipVia)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(Freight)%%>', '', $templateCode);
    // process values
    if ($selected_id) {
        $templateCode = str_replace('<%%VALUE(OrderID)%%>', htmlspecialchars($row['OrderID'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(OrderID)%%>', urlencode($urow['OrderID']), $templateCode);
        $templateCode = str_replace('<%%VALUE(CustomerID)%%>', htmlspecialchars($row['CustomerID'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(CustomerID)%%>', urlencode($urow['CustomerID']), $templateCode);
        $templateCode = str_replace('<%%VALUE(EmployeeID)%%>', htmlspecialchars($row['EmployeeID'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(EmployeeID)%%>', urlencode($urow['EmployeeID']), $templateCode);
        $templateCode = str_replace('<%%VALUE(OrderDate)%%>', @date('m/d/Y', @strtotime(htmlspecialchars($row['OrderDate'], ENT_QUOTES, 'iso-8859-1'))), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(OrderDate)%%>', urlencode(@date('m/d/Y', @strtotime(htmlspecialchars($urow['OrderDate'], ENT_QUOTES, 'iso-8859-1')))), $templateCode);
        $templateCode = str_replace('<%%VALUE(RequiredDate)%%>', @date('m/d/Y', @strtotime(htmlspecialchars($row['RequiredDate'], ENT_QUOTES, 'iso-8859-1'))), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(RequiredDate)%%>', urlencode(@date('m/d/Y', @strtotime(htmlspecialchars($urow['RequiredDate'], ENT_QUOTES, 'iso-8859-1')))), $templateCode);
        $templateCode = str_replace('<%%VALUE(ShippedDate)%%>', @date('m/d/Y', @strtotime(htmlspecialchars($row['ShippedDate'], ENT_QUOTES, 'iso-8859-1'))), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(ShippedDate)%%>', urlencode(@date('m/d/Y', @strtotime(htmlspecialchars($urow['ShippedDate'], ENT_QUOTES, 'iso-8859-1')))), $templateCode);
        $templateCode = str_replace('<%%VALUE(ShipVia)%%>', htmlspecialchars($row['ShipVia'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(ShipVia)%%>', urlencode($urow['ShipVia']), $templateCode);
        $templateCode = str_replace('<%%VALUE(Freight)%%>', htmlspecialchars($row['Freight'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(Freight)%%>', urlencode($urow['Freight']), $templateCode);
    } else {
        $templateCode = str_replace('<%%VALUE(OrderID)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(OrderID)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(CustomerID)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(CustomerID)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(EmployeeID)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(EmployeeID)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(OrderDate)%%>', '1', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(OrderDate)%%>', urlencode('1'), $templateCode);
        $templateCode = str_replace('<%%VALUE(RequiredDate)%%>', '1', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(RequiredDate)%%>', urlencode('1'), $templateCode);
        $templateCode = str_replace('<%%VALUE(ShippedDate)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(ShippedDate)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(ShipVia)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(ShipVia)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(Freight)%%>', '0', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(Freight)%%>', urlencode('0'), $templateCode);
    }
    // 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 ($_POST['dvprint_x'] == '') {
        $templateCode .= "\n\n<script>\$j(function(){\n";
        $arrTables = getTableList();
        foreach ($arrTables as $name => $caption) {
            $templateCode .= "\t\$j('#{$name}_link').removeClass('hidden');\n";
            $templateCode .= "\t\$j('#xs_{$name}_link').removeClass('hidden');\n";
        }
        $templateCode .= $jsReadOnly;
        $templateCode .= $jsEditable;
        if (!$selected_id) {
        }
        $templateCode .= "\n});</script>\n";
    }
    // ajaxed auto-fill fields
    $templateCode .= '<script>';
    $templateCode .= '$j(function() {';
    $templateCode .= "\tCustomerID_update_autofills{$rnd1} = function(){\n";
    $templateCode .= "\t\tnew Ajax.Request(\n";
    if ($dvprint) {
        $templateCode .= "\t\t\t'orders_autofill.php?rnd1={$rnd1}&mfk=CustomerID&id='+encodeURIComponent('" . addslashes($row['CustomerID']) . "'),\n";
        $templateCode .= "\t\t\t{encoding: 'iso-8859-1', method: 'get'}\n";
    } else {
        $templateCode .= "\t\t\t'orders_autofill.php?rnd1={$rnd1}&mfk=CustomerID&id=' + encodeURIComponent(current_CustomerID{$rnd1}.value),\n";
        $templateCode .= "\t\t\t{encoding: 'iso-8859-1', method: 'get', onCreate: function(){ \$('CustomerID{$rnd1}').disable(); \$('CustomerIDLoading').innerHTML='<img src=loading.gif align=top>'; }, onComplete: function(){" . ($arrPerm[1] || ($arrPerm[3] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[3] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[3] == 3) ? "\$('CustomerID{$rnd1}').enable(); " : "\$('CustomerID{$rnd1}').disable(); ") . "\$('CustomerIDLoading').innerHTML='';}}\n";
    }
    $templateCode .= "\t\t);\n";
    $templateCode .= "\t};\n";
    if (!$dvprint) {
        $templateCode .= "\tif(\$('CustomerID_caption') != undefined) \$('CustomerID_caption').onchange=CustomerID_update_autofills{$rnd1};\n";
    }
    $templateCode .= "});";
    $templateCode .= "</script>";
    $templateCode .= $lookups;
    // handle enforced parent values for read-only lookup fields
    // don't include blank images in lightbox gallery
    $templateCode = preg_replace('/blank.gif" rel="lightbox\\[.*?\\]"/', 'blank.gif"', $templateCode);
    // don't display empty email links
    $templateCode = preg_replace('/<a .*?href="mailto:".*?<\\/a>/', '', $templateCode);
    // hook: orders_dv
    if (function_exists('orders_dv')) {
        $args = array();
        orders_dv($selected_id ? $selected_id : FALSE, getMemberInfo(), $templateCode, $args);
    }
    return $templateCode;
}
Пример #5
0
				<td><?php 
        echo $fn;
        ?>
</td>
				<td class="<?php 
        echo $diff ? 'bold text-success' : '';
        ?>
"><?php 
        echo $fd['appgini'];
        ?>
</td>
				<td class="<?php 
        echo $diff ? 'bold text-danger' : '';
        ?>
"><?php 
        echo thisOr($fd['db'], $Translation['does not exist']);
        ?>
</td>
				<td>
					<?php 
        if ($diff && $no_db) {
            ?>
						<a href="pageRebuildFields.php?t=<?php 
            echo $tn;
            ?>
&f=<?php 
            echo $fn;
            ?>
" class="btn btn-success btn-xs btn_create" data-toggle="tooltip" data-placement="top" title="<?php 
            echo $Translation['create field'];
            ?>
Пример #6
0
function employees_form($selected_id = '', $AllowUpdate = 1, $AllowInsert = 1, $AllowDelete = 1, $ShowCancel = 0)
{
    // 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('employees');
    if (!$arrPerm[1] && $selected_id == '') {
        return '';
    }
    $AllowInsert = $arrPerm[1] ? true : false;
    // print preview?
    $dvprint = false;
    if ($selected_id && $_REQUEST['dvprint_x'] != '') {
        $dvprint = true;
    }
    $filterer_ReportsTo = thisOr(undo_magic_quotes($_REQUEST['filterer_ReportsTo']), '');
    // populate filterers, starting from children to grand-parents
    // unique random identifier
    $rnd1 = $dvprint ? rand(1000000, 9999999) : '';
    // combobox: BirthDate
    $combo_BirthDate = new DateCombo();
    $combo_BirthDate->DateFormat = "mdy";
    $combo_BirthDate->MinYear = 1900;
    $combo_BirthDate->MaxYear = 2100;
    $combo_BirthDate->DefaultDate = parseMySQLDate('', '');
    $combo_BirthDate->MonthNames = $Translation['month names'];
    $combo_BirthDate->NamePrefix = 'BirthDate';
    // combobox: HireDate
    $combo_HireDate = new DateCombo();
    $combo_HireDate->DateFormat = "mdy";
    $combo_HireDate->MinYear = 1900;
    $combo_HireDate->MaxYear = 2100;
    $combo_HireDate->DefaultDate = parseMySQLDate('1', '1');
    $combo_HireDate->MonthNames = $Translation['month names'];
    $combo_HireDate->NamePrefix = 'HireDate';
    // combobox: Country
    $combo_Country = new Combo();
    $combo_Country->ListType = 0;
    $combo_Country->MultipleSeparator = ', ';
    $combo_Country->ListBoxHeight = 10;
    $combo_Country->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/employees.Country.csv')) {
        $Country_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/employees.Country.csv')));
        $combo_Country->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($Country_data)));
        $combo_Country->ListData = $combo_Country->ListItem;
    } else {
        $combo_Country->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Afghanistan;;Albania;;Algeria;;American Samoa;;Andorra;;Angola;;Anguilla;;Antarctica;;Antigua, Barbuda;;Argentina;;Armenia;;Aruba;;Australia;;Austria;;Azerbaijan;;Bahamas;;Bahrain;;Bangladesh;;Barbados;;Belarus;;Belgium;;Belize;;Benin;;Bermuda;;Bhutan;;Bolivia;;Bosnia, Herzegovina;;Botswana;;Bouvet Is.;;Brazil;;Brunei Darussalam;;Bulgaria;;Burkina Faso;;Burundi;;Cambodia;;Cameroon;;Canada;;Canary Is.;;Cape Verde;;Cayman Is.;;Central African Rep.;;Chad;;Channel Islands;;Chile;;China;;Christmas Is.;;Cocos Is.;;Colombia;;Comoros;;Congo, D.R. Of;;Congo;;Cook Is.;;Costa Rica;;Croatia;;Cuba;;Cyprus;;Czech Republic;;Denmark;;Djibouti;;Dominica;;Dominican Republic;;Ecuador;;Egypt;;El Salvador;;Equatorial Guinea;;Eritrea;;Estonia;;Ethiopia;;Falkland Is.;;Faroe Is.;;Fiji;;Finland;;France;;French Guiana;;French Polynesia;;French Territories;;Gabon;;Gambia;;Georgia;;Germany;;Ghana;;Gibraltar;;Greece;;Greenland;;Grenada;;Guadeloupe;;Guam;;Guatemala;;Guernsey;;Guinea-bissau;;Guinea;;Guyana;;Haiti;;Heard, Mcdonald Is.;;Honduras;;Hong Kong;;Hungary;;Iceland;;India;;Indonesia;;Iran;;Iraq;;Ireland;;Israel;;Italy;;Ivory Coast;;Jamaica;;Japan;;Jersey;;Jordan;;Kazakhstan;;Kenya;;Kiribati;;Korea, D.P.R Of;;Korea, Rep. Of;;Kuwait;;Kyrgyzstan;;Lao Peoples D.R.;;Latvia;;Lebanon;;Lesotho;;Liberia;;Libyan Arab Jamahiriya;;Liechtenstein;;Lithuania;;Luxembourg;;Macao;;Macedonia, F.Y.R Of;;Madagascar;;Malawi;;Malaysia;;Maldives;;Mali;;Malta;;Mariana Islands;;Marshall Islands;;Martinique;;Mauritania;;Mauritius;;Mayotte;;Mexico;;Micronesia;;Moldova;;Monaco;;Mongolia;;Montserrat;;Morocco;;Mozambique;;Myanmar;;Namibia;;Nauru;;Nepal;;Netherlands Antilles;;Netherlands;;New Caledonia;;New Zealand;;Nicaragua;;Niger;;Nigeria;;Niue;;Norfolk Island;;Norway;;Oman;;Pakistan;;Palau;;Palestinian Terr.;;Panama;;Papua New Guinea;;Paraguay;;Peru;;Philippines;;Pitcairn;;Poland;;Portugal;;Puerto Rico;;Qatar;;Reunion;;Romania;;Russian Federation;;Rwanda;;Samoa;;San Marino;;Sao Tome, Principe;;Saudi Arabia;;Senegal;;Seychelles;;Sierra Leone;;Singapore;;Slovakia;;Slovenia;;Solomon Is.;;Somalia;;South Africa;;South Georgia;;South Sandwich Is.;;Spain;;Sri Lanka;;St. Helena;;St. Kitts, Nevis;;St. Lucia;;St. Pierre, Miquelon;;St. Vincent, Grenadines;;Sudan;;Suriname;;Svalbard, Jan Mayen;;Swaziland;;Sweden;;Switzerland;;Syrian Arab Republic;;Taiwan;;Tajikistan;;Tanzania;;Thailand;;Timor-leste;;Togo;;Tokelau;;Tonga;;Trinidad, Tobago;;Tunisia;;Turkey;;Turkmenistan;;Turks, Caicoss;;Tuvalu;;Uganda;;Ukraine;;United Arab Emirates;;United Kingdom;;United States;;Uruguay;;Uzbekistan;;Vanuatu;;Vatican City;;Venezuela;;Viet Nam;;Virgin Is. British;;Virgin Is. U.S.;;Wallis, Futuna;;Western Sahara;;Yemen;;Yugoslavia;;Zambia;;Zimbabwe")));
        $combo_Country->ListData = $combo_Country->ListItem;
    }
    $combo_Country->SelectName = 'Country';
    // combobox: ReportsTo
    $combo_ReportsTo = 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='employees' and pkValue='" . makeSafe($selected_id) . "'");
        $ownerMemberID = sqlValue("select lcase(memberID) from membership_userrecords where tableName='employees' 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 `employees` where `EmployeeID`='" . makeSafe($selected_id) . "'", $eo);
        if (!($row = db_fetch_array($res))) {
            return error_message($Translation['No records found']);
        }
        $urow = $row;
        /* unsanitized data */
        $hc = new CI_Input();
        $row = $hc->xss_clean($row);
        /* sanitize data */
        $combo_BirthDate->DefaultDate = $row['BirthDate'];
        $combo_HireDate->DefaultDate = $row['HireDate'];
        $combo_Country->SelectedData = $row['Country'];
        $combo_ReportsTo->SelectedData = $row['ReportsTo'];
    } else {
        $combo_Country->SelectedText = $_REQUEST['FilterField'][1] == '13' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "";
        $combo_ReportsTo->SelectedData = $filterer_ReportsTo;
    }
    $combo_Country->Render();
    $combo_ReportsTo->HTML = $combo_ReportsTo->MatchText = '<span id="ReportsTo-container' . $rnd1 . '"></span>';
    ob_start();
    ?>

	<script>
		// initial lookup values
		var current_ReportsTo__RAND__ = { text: "", value: "<?php 
    echo addslashes($selected_id ? $urow['ReportsTo'] : $filterer_ReportsTo);
    ?>
"};

		jQuery(function() {
			if(typeof(ReportsTo_reload__RAND__) == 'function') ReportsTo_reload__RAND__();
		});
		function ReportsTo_reload__RAND__(){
			new Ajax.Updater("ReportsTo-container__RAND__", "ajax_combo.php", {
				parameters: { t: "employees", f: "ReportsTo", id: current_ReportsTo__RAND__.value, text: current_ReportsTo__RAND__.text, o: <?php 
    echo ($AllowUpdate || $AllowInsert) && !$dvprint ? '1' : '0';
    ?>
 },
				method: "get",
				encoding: "iso-8859-1",
				evalScripts: true,
				onComplete: function(){ ReportsTo_changed__RAND__(); }
			});
		}
		function ReportsTo_changed__RAND__(){
			if($$("input[name=ReportsTo]").length){
				if($$("input[name=ReportsTo]:checked")[0] != undefined){
					current_ReportsTo__RAND__.value = $$("input[name=ReportsTo]:checked")[0].value;
					current_ReportsTo__RAND__.text = "";
				}else{
					current_ReportsTo__RAND__.value = "";
					current_ReportsTo__RAND__.text = "";
				}
			}

			if(typeof(ReportsTo_update_autofills__RAND__) == 'function') ReportsTo_update_autofills__RAND__();
		}
	</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) {
        $templateCode = @file_get_contents('./templates/employees_templateDVP.html');
    } else {
        $templateCode = @file_get_contents('./templates/employees_templateDV.html');
    }
    // process form title
    $templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Detail View', $templateCode);
    $templateCode = str_replace('<%%RND1%%>', $rnd1, $templateCode);
    $templateCode = str_replace('<%%EMBEDDED%%>', $_REQUEST['Embedded'] ? 'Embedded=1' : '', $templateCode);
    // process buttons
    if ($arrPerm[1] && !$selected_id) {
        // allow insert and no record selected?
        if (!$selected_id) {
            $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-success" id="insert" name="insert_x" value="1" onclick="return employees_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 employees_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 = 'window.parent.jQuery(\'.modal\').modal(\'hide\'); return false;';
    } else {
        $backAction = '$$(\'form\')[0].writeAttribute(\'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="$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;"><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 employees_validateData();"><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?'] . '\');"><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 . '"><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 . '"><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 || !$selected_id && !$AllowInsert) {
        $jsReadOnly .= "\tjQuery('#TitleOfCourtesy').replaceWith('<div class=\"form-control-static\" id=\"TitleOfCourtesy\">' + (jQuery('#TitleOfCourtesy').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#Photo').replaceWith('<div class=\"form-control-static\" id=\"Photo\">' + (jQuery('#Photo').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#LastName').replaceWith('<div class=\"form-control-static\" id=\"LastName\">' + (jQuery('#LastName').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#FirstName').replaceWith('<div class=\"form-control-static\" id=\"FirstName\">' + (jQuery('#FirstName').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#Title').replaceWith('<div class=\"form-control-static\" id=\"Title\">' + (jQuery('#Title').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#BirthDate').prop('readonly', true);\n";
        $jsReadOnly .= "\tjQuery('#BirthDateDay, #BirthDateMonth, #BirthDateYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#HireDate').prop('readonly', true);\n";
        $jsReadOnly .= "\tjQuery('#HireDateDay, #HireDateMonth, #HireDateYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#Address').replaceWith('<div class=\"form-control-static\" id=\"Address\">' + (jQuery('#Address').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#City').replaceWith('<div class=\"form-control-static\" id=\"City\">' + (jQuery('#City').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#Region').replaceWith('<div class=\"form-control-static\" id=\"Region\">' + (jQuery('#Region').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#PostalCode').replaceWith('<div class=\"form-control-static\" id=\"PostalCode\">' + (jQuery('#PostalCode').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#Country').replaceWith('<div class=\"form-control-static\" id=\"Country\">' + (jQuery('#Country').val() || '') + '</div>'); jQuery('#Country-multi-selection-help').hide();\n";
        $jsReadOnly .= "\tjQuery('#HomePhone').replaceWith('<div class=\"form-control-static\" id=\"HomePhone\">' + (jQuery('#HomePhone').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#Extension').replaceWith('<div class=\"form-control-static\" id=\"Extension\">' + (jQuery('#Extension').val() || '') + '</div>');\n";
        $jsReadOnly .= "\tjQuery('#ReportsTo').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#ReportsTo_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
        $jsReadOnly .= "\tjQuery('.select2-container').hide();\n";
        $noUploads = true;
    } elseif ($AllowInsert && !$selected_id || $AllowUpdate && $selected_id) {
        $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(BirthDate)%%>', $selected_id && !$arrPerm[3] ? '<div class="form-control-static">' . $combo_BirthDate->GetHTML(true) . '</div>' : $combo_BirthDate->GetHTML(), $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(BirthDate)%%>', $combo_BirthDate->GetHTML(true), $templateCode);
    $templateCode = str_replace('<%%COMBO(HireDate)%%>', $selected_id && !$arrPerm[3] ? '<div class="form-control-static">' . $combo_HireDate->GetHTML(true) . '</div>' : $combo_HireDate->GetHTML(), $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(HireDate)%%>', $combo_HireDate->GetHTML(true), $templateCode);
    $templateCode = str_replace('<%%COMBO(Country)%%>', $combo_Country->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(Country)%%>', $combo_Country->SelectedData, $templateCode);
    $templateCode = str_replace('<%%COMBO(ReportsTo)%%>', $combo_ReportsTo->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(ReportsTo)%%>', $combo_ReportsTo->MatchText, $templateCode);
    $templateCode = str_replace('<%%URLCOMBOTEXT(ReportsTo)%%>', urlencode($combo_ReportsTo->MatchText), $templateCode);
    /* lookup fields array: 'lookup field name' => array('parent table name', 'lookup field caption') */
    $lookup_fields = array('ReportsTo' => array('employees', 'ReportsTo'));
    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-lg" id="' . $ptfc[0] . '_view_parent" title="' . htmlspecialchars($Translation['View'] . ' ' . $ptfc[1], ENT_QUOTES, 'iso-8859-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" id="' . $ptfc[0] . '_add_new" title="' . htmlspecialchars($Translation['Add New'] . ' ' . $ptfc[1], ENT_QUOTES, 'iso-8859-1') . '"><i class="glyphicon glyphicon-plus-sign"></i></button>', $templateCode);
        }
    }
    // process images
    $templateCode = str_replace('<%%UPLOADFILE(EmployeeID)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(TitleOfCourtesy)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(Photo)%%>', $noUploads ? '' : '<input type=hidden name=MAX_FILE_SIZE value=153600>' . $Translation['upload image'] . ' <input type="file" name="Photo" id="Photo">', $templateCode);
    if ($AllowUpdate && $row['Photo'] != '') {
        $templateCode = str_replace('<%%REMOVEFILE(Photo)%%>', '<br><input type="checkbox" name="Photo_remove" id="Photo_remove" value="1"> <label for="Photo_remove" style="color: red; font-weight: bold;">' . $Translation['remove image'] . '</label>', $templateCode);
    } else {
        $templateCode = str_replace('<%%REMOVEFILE(Photo)%%>', '', $templateCode);
    }
    $templateCode = str_replace('<%%UPLOADFILE(LastName)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(FirstName)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(Title)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(BirthDate)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(HireDate)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(Address)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(City)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(Region)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(PostalCode)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(Country)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(HomePhone)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(Extension)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(Notes)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(ReportsTo)%%>', '', $templateCode);
    // process values
    if ($selected_id) {
        $templateCode = str_replace('<%%VALUE(EmployeeID)%%>', htmlspecialchars($row['EmployeeID'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(EmployeeID)%%>', urlencode($urow['EmployeeID']), $templateCode);
        $templateCode = str_replace('<%%VALUE(TitleOfCourtesy)%%>', htmlspecialchars($row['TitleOfCourtesy'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(TitleOfCourtesy)%%>', urlencode($urow['TitleOfCourtesy']), $templateCode);
        $row['Photo'] = $row['Photo'] != '' ? $row['Photo'] : 'blank.gif';
        $templateCode = str_replace('<%%VALUE(Photo)%%>', htmlspecialchars($row['Photo'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(Photo)%%>', urlencode($urow['Photo']), $templateCode);
        $templateCode = str_replace('<%%VALUE(LastName)%%>', htmlspecialchars($row['LastName'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(LastName)%%>', urlencode($urow['LastName']), $templateCode);
        $templateCode = str_replace('<%%VALUE(FirstName)%%>', htmlspecialchars($row['FirstName'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(FirstName)%%>', urlencode($urow['FirstName']), $templateCode);
        $templateCode = str_replace('<%%VALUE(Title)%%>', htmlspecialchars($row['Title'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(Title)%%>', urlencode($urow['Title']), $templateCode);
        $templateCode = str_replace('<%%VALUE(BirthDate)%%>', @date('m/d/Y', @strtotime(htmlspecialchars($row['BirthDate'], ENT_QUOTES, 'iso-8859-1'))), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(BirthDate)%%>', urlencode(@date('m/d/Y', @strtotime(htmlspecialchars($urow['BirthDate'], ENT_QUOTES, 'iso-8859-1')))), $templateCode);
        $templateCode = str_replace('<%%VALUE(HireDate)%%>', @date('m/d/Y', @strtotime(htmlspecialchars($row['HireDate'], ENT_QUOTES, 'iso-8859-1'))), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(HireDate)%%>', urlencode(@date('m/d/Y', @strtotime(htmlspecialchars($urow['HireDate'], ENT_QUOTES, 'iso-8859-1')))), $templateCode);
        if ($dvprint) {
            $templateCode = str_replace('<%%VALUE(Address)%%>', nl2br(htmlspecialchars($row['Address'], ENT_QUOTES, 'iso-8859-1')), $templateCode);
        } else {
            $templateCode = str_replace('<%%VALUE(Address)%%>', htmlspecialchars($row['Address'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        }
        $templateCode = str_replace('<%%URLVALUE(Address)%%>', urlencode($urow['Address']), $templateCode);
        $templateCode = str_replace('<%%VALUE(City)%%>', htmlspecialchars($row['City'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(City)%%>', urlencode($urow['City']), $templateCode);
        $templateCode = str_replace('<%%VALUE(Region)%%>', htmlspecialchars($row['Region'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(Region)%%>', urlencode($urow['Region']), $templateCode);
        $templateCode = str_replace('<%%VALUE(PostalCode)%%>', htmlspecialchars($row['PostalCode'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(PostalCode)%%>', urlencode($urow['PostalCode']), $templateCode);
        $templateCode = str_replace('<%%VALUE(Country)%%>', htmlspecialchars($row['Country'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(Country)%%>', urlencode($urow['Country']), $templateCode);
        $templateCode = str_replace('<%%VALUE(HomePhone)%%>', htmlspecialchars($row['HomePhone'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(HomePhone)%%>', urlencode($urow['HomePhone']), $templateCode);
        $templateCode = str_replace('<%%VALUE(Extension)%%>', htmlspecialchars($row['Extension'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(Extension)%%>', urlencode($urow['Extension']), $templateCode);
        if ($AllowUpdate || $AllowInsert) {
            $templateCode = str_replace('<%%HTMLAREA(Notes)%%>', '<textarea name="Notes" id="Notes" rows="5">' . htmlspecialchars($row['Notes'], ENT_QUOTES, 'iso-8859-1') . '</textarea>', $templateCode);
        } else {
            $templateCode = str_replace('<%%HTMLAREA(Notes)%%>', $row['Notes'], $templateCode);
        }
        $templateCode = str_replace('<%%VALUE(Notes)%%>', nl2br($row['Notes']), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(Notes)%%>', urlencode($urow['Notes']), $templateCode);
        $templateCode = str_replace('<%%VALUE(ReportsTo)%%>', htmlspecialchars($row['ReportsTo'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(ReportsTo)%%>', urlencode($urow['ReportsTo']), $templateCode);
    } else {
        $templateCode = str_replace('<%%VALUE(EmployeeID)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(EmployeeID)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(TitleOfCourtesy)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(TitleOfCourtesy)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(Photo)%%>', 'blank.gif', $templateCode);
        $templateCode = str_replace('<%%VALUE(LastName)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(LastName)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(FirstName)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(FirstName)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(Title)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(Title)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(BirthDate)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(BirthDate)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(HireDate)%%>', '1', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(HireDate)%%>', urlencode('1'), $templateCode);
        $templateCode = str_replace('<%%VALUE(Address)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(Address)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(City)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(City)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(Region)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(Region)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(PostalCode)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(PostalCode)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(Country)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(Country)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(HomePhone)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(HomePhone)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(Extension)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(Extension)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%HTMLAREA(Notes)%%>', '<textarea name="Notes" id="Notes" rows="5"></textarea>', $templateCode);
        $templateCode = str_replace('<%%VALUE(ReportsTo)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(ReportsTo)%%>', urlencode(''), $templateCode);
    }
    // process translations
    foreach ($Translation as $symbol => $trans) {
        $templateCode = str_replace("<%%TRANSLATION({$symbol})%%>", $trans, $templateCode);
    }
    // clear scrap
    $templateCode = str_replace('<%%', '<!-- ', $templateCode);
    $templateCode = str_replace('%%>', ' -->', $templateCode);
    // hide links to inaccessible tables
    if ($_POST['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" rel="lightbox\\[.*?\\]"/', 'blank.gif"', $templateCode);
    // don't display empty email links
    $templateCode = preg_replace('/<a .*?href="mailto:".*?<\\/a>/', '', $templateCode);
    // hook: employees_dv
    if (function_exists('employees_dv')) {
        $args = array();
        employees_dv($selected_id ? $selected_id : FALSE, getMemberInfo(), $templateCode, $args);
    }
    return $templateCode;
}
Пример #7
0
 function Render()
 {
     // get post and get variables
     global $Translation;
     $adminConfig = config('adminConfig');
     $FiltersPerGroup = 4;
     $buttonWholeWidth = 136;
     $current_view = '';
     /* TV, DV, TVDV, TVP, DVP, Filters */
     $Embedded = intval($_REQUEST['Embedded']);
     if ($_SERVER['REQUEST_METHOD'] == 'GET') {
         $SortField = $_GET["SortField"];
         $SortDirection = $_GET["SortDirection"];
         $FirstRecord = $_GET["FirstRecord"];
         $ScrollUp_y = $_GET["ScrollUp_y"];
         $ScrollDn_y = $_GET["ScrollDn_y"];
         $Previous_x = $_GET["Previous_x"];
         $Next_x = $_GET["Next_x"];
         $Filter_x = $_GET["Filter_x"];
         $SaveFilter_x = $_GET["SaveFilter_x"];
         $NoFilter_x = $_GET["NoFilter_x"];
         $CancelFilter = $_GET["CancelFilter"];
         $ApplyFilter = $_GET["ApplyFilter"];
         $Search_x = $_GET["Search_x"];
         $SearchString = get_magic_quotes_gpc() ? stripslashes($_GET['SearchString']) : $_GET['SearchString'];
         $CSV_x = $_GET["CSV_x"];
         $FilterAnd = $_GET["FilterAnd"];
         $FilterField = $_GET["FilterField"];
         $FilterOperator = $_GET["FilterOperator"];
         if (is_array($_GET['FilterValue'])) {
             foreach ($_GET['FilterValue'] as $fvi => $fv) {
                 $FilterValue[$fvi] = get_magic_quotes_gpc() ? stripslashes($fv) : $fv;
             }
         }
         $Print_x = $_GET['Print_x'];
         $PrintTV = $_GET['PrintTV'];
         $PrintDV = $_GET['PrintDV'];
         $SelectedID = get_magic_quotes_gpc() ? stripslashes($_GET['SelectedID']) : $_GET['SelectedID'];
         $insert_x = $_GET['insert_x'];
         $update_x = $_GET['update_x'];
         $delete_x = $_GET['delete_x'];
         $SkipChecks = $_GET['confirmed'];
         $deselect_x = $_GET['deselect_x'];
         $addNew_x = $_GET['addNew_x'];
         $dvprint_x = $_GET['dvprint_x'];
         $DisplayRecords = in_array($_GET['DisplayRecords'], array('user', 'group')) ? $_GET['DisplayRecords'] : 'all';
     } else {
         $SortField = $_POST['SortField'];
         $SortDirection = $_POST['SortDirection'];
         $FirstRecord = $_POST['FirstRecord'];
         $ScrollUp_y = $_POST['ScrollUp_y'];
         $ScrollDn_y = $_POST['ScrollDn_y'];
         $Previous_x = $_POST['Previous_x'];
         $Next_x = $_POST['Next_x'];
         $Filter_x = $_POST['Filter_x'];
         $SaveFilter_x = $_POST['SaveFilter_x'];
         $NoFilter_x = $_POST['NoFilter_x'];
         $CancelFilter = $_POST['CancelFilter'];
         $ApplyFilter = $_POST['ApplyFilter'];
         $Search_x = $_POST['Search_x'];
         $SearchString = get_magic_quotes_gpc() ? stripslashes($_POST['SearchString']) : $_POST['SearchString'];
         $CSV_x = $_POST['CSV_x'];
         $FilterAnd = $_POST['FilterAnd'];
         $FilterField = $_POST['FilterField'];
         $FilterOperator = $_POST['FilterOperator'];
         if (is_array($_POST['FilterValue'])) {
             foreach ($_POST['FilterValue'] as $fvi => $fv) {
                 $FilterValue[$fvi] = get_magic_quotes_gpc() ? stripslashes($fv) : $fv;
             }
         }
         $Print_x = $_POST['Print_x'];
         $PrintTV = $_POST['PrintTV'];
         $PrintDV = $_POST['PrintDV'];
         $SelectedID = get_magic_quotes_gpc() ? stripslashes($_POST['SelectedID']) : $_POST['SelectedID'];
         $insert_x = $_POST['insert_x'];
         $update_x = $_POST['update_x'];
         $delete_x = $_POST['delete_x'];
         $SkipChecks = $_POST['confirmed'];
         $deselect_x = $_POST['deselect_x'];
         $addNew_x = $_POST['addNew_x'];
         $dvprint_x = $_POST['dvprint_x'];
         $DisplayRecords = in_array($_POST['DisplayRecords'], array('user', 'group')) ? $_POST['DisplayRecords'] : 'all';
     }
     $mi = getMemberInfo();
     // insure authenticity of user inputs:
     if (is_array($FilterAnd)) {
         foreach ($FilterAnd as $i => $f) {
             if ($f && !preg_match('/^(and|or)$/i', trim($f))) {
                 $FilterAnd[$i] = 'and';
             }
         }
     }
     if (is_array($FilterOperator)) {
         foreach ($FilterOperator as $i => $f) {
             if ($f && !in_array(trim($f), array_keys($GLOBALS['filter_operators']))) {
                 $FilterOperator[$i] = '';
             }
         }
     }
     if (!preg_match('/^\\s*[1-9][0-9]*\\s*(asc|desc)?(\\s*,\\s*[1-9][0-9]*\\s*(asc|desc)?)*$/i', $SortField)) {
         $SortField = '';
     }
     if (!preg_match('/^(asc|desc)$/i', $SortDirection)) {
         $SortDirection = '';
     }
     if (!$this->AllowDelete) {
         $delete_x = '';
     }
     if (!$this->AllowDeleteOfParents) {
         $SkipChecks = '';
     }
     if (!$this->AllowInsert) {
         $insert_x = '';
         $addNew_x = '';
     }
     if (!$this->AllowUpdate) {
         $update_x = '';
     }
     if (!$this->AllowFilters) {
         $Filter_x = '';
     }
     if (!$this->AllowPrinting) {
         $Print_x = '';
         $PrintTV = '';
     }
     if (!$this->QuickSearch) {
         $SearchString = '';
     }
     if (!$this->AllowCSV) {
         $CSV_x = '';
     }
     // enforce record selection if user has edit/delete permissions on the current table
     $AllowPrintDV = 1;
     $this->Permissions = getTablePermissions($this->TableName);
     if ($this->Permissions[3] || $this->Permissions[4]) {
         // current user can edit or delete?
         $this->AllowSelection = 1;
     } elseif (!$this->AllowSelection) {
         $SelectedID = '';
         $AllowPrintDV = 0;
         $PrintDV = '';
     }
     if (!$this->AllowSelection || !$SelectedID) {
         $dvprint_x = '';
     }
     $this->QueryFieldsIndexed = reIndex($this->QueryFieldsFilters);
     // determine type of current view: TV, DV, TVDV, TVP, DVP or Filters?
     if ($this->SeparateDV) {
         $current_view = 'TV';
         if ($Print_x != '' || $PrintTV != '') {
             $current_view = 'TVP';
         } elseif ($dvprint_x != '' || $PrintDV != '') {
             $current_view = 'DVP';
         } elseif ($Filter_x != '') {
             $current_view = 'Filters';
         } elseif ($SelectedID && !$deselect_x && !$delete_x || $addNew_x != '') {
             $current_view = 'DV';
         }
     } else {
         $current_view = 'TVDV';
         if ($Print_x != '' || $PrintTV != '') {
             $current_view = 'TVP';
         } elseif ($dvprint_x != '' || $PrintDV != '') {
             $current_view = 'DVP';
         } elseif ($Filter_x != '') {
             $current_view = 'Filters';
         }
     }
     $this->HTML .= '<div class="row"><div class="col-xs-11 col-md-12">';
     $this->HTML .= '<form ' . (datalist_image_uploads_exist ? 'enctype="multipart/form-data" ' : '') . 'method="post" name="myform" action="' . $this->ScriptFileName . '">';
     if ($Embedded) {
         $this->HTML .= '<input name="Embedded" value="1" type="hidden" />';
     }
     $this->HTML .= '<script>';
     $this->HTML .= 'function enterAction(){';
     $this->HTML .= '   if($$("input[name=SearchString]:focus")[0] != undefined){ $("Search").click(); }';
     $this->HTML .= '   return false;';
     $this->HTML .= '}';
     $this->HTML .= '</script>';
     $this->HTML .= '<input id="EnterAction" type="submit" style="position: absolute; left: 0px; top: -250px;" onclick="return enterAction();">';
     $this->ContentType = 'tableview';
     // default content type
     if ($PrintTV != '') {
         $Print_x = 1;
         $_POST['Print_x'] = 1;
     }
     // handle user commands ...
     if ($deselect_x != '') {
         $SelectedID = '';
         $this->showTV();
     } elseif ($insert_x != '') {
         $SelectedID = call_user_func($this->TableName . '_insert');
         // redirect to a safe url to avoid refreshing and thus
         // insertion of duplicate records.
         $url = $this->RedirectAfterInsert;
         $insert_status = 'record-added-ok=' . rand();
         if (!$SelectedID) {
             $insert_status = 'record-added-error=' . rand();
         }
         // compose filters and sorting
         foreach ($this->filterers as $filterer => $caption) {
             if ($_REQUEST['filterer_' . $filterer] != '') {
                 $filtersGET .= '&filterer_' . $filterer . '=' . urlencode($_REQUEST['filterer_' . $filterer]);
             }
         }
         for ($i = 1; $i <= 20 * $FiltersPerGroup; $i++) {
             // Number of filters allowed
             if ($FilterField[$i] != '' && $FilterOperator[$i] != '' && ($FilterValue[$i] != '' || strpos($FilterOperator[$i], 'empty'))) {
                 $filtersGET .= "&FilterAnd[{$i}]={$FilterAnd[$i]}&FilterField[{$i}]={$FilterField[$i]}&FilterOperator[{$i}]={$FilterOperator[$i]}&FilterValue[{$i}]=" . urlencode($FilterValue[$i]);
             }
         }
         if ($Embedded) {
             $filtersGET .= '&Embedded=1&SelectedID=' . urlencode($SelectedID);
         }
         $filtersGET .= "&SortField={$SortField}&SortDirection={$SortDirection}&FirstRecord={$FirstRecord}";
         $filtersGET .= "&DisplayRecords={$DisplayRecords}";
         $filtersGET .= '&SearchString=' . urlencode($SearchString);
         $filtersGET = substr($filtersGET, 1);
         // remove initial &
         if ($url) {
             /* if designer specified a redirect-after-insert url */
             $url .= (strpos($url, '?') !== false ? '&' : '?') . $insert_status;
             $url .= strpos($url, $this->ScriptFileName) !== false ? "&{$filtersGET}" : '';
             $url = str_replace("#ID#", urlencode($SelectedID), $url);
         } else {
             /* if no redirect-after-insert url, use default */
             $url = "{$this->ScriptFileName}?{$insert_status}&{$filtersGET}";
             /* if DV and TV in same page, select new record */
             if (!$this->SeparateDV) {
                 $url .= '&SelectedID=' . urlencode($SelectedID);
             }
         }
         @header('Location: ' . $url);
         $this->HTML .= "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"0;url=" . $url . "\">";
         return;
     } elseif ($delete_x != '') {
         $d = call_user_func($this->TableName . '_delete', $SelectedID, $this->AllowDeleteOfParents, $SkipChecks);
         // handle ajax delete requests
         if (is_ajax()) {
             die($d ? $d : 'OK');
         }
         if ($d) {
             //$_REQUEST['record-deleted-error'] = 1;
             $this->HTML .= error_message($d);
         } else {
             $_REQUEST['record-deleted-ok'] = 1;
             $SelectedID = '';
             $this->showTV();
         }
     } elseif ($update_x != '') {
         $updated = call_user_func($this->TableName . '_update', $SelectedID);
         $update_status = 'record-updated-ok=' . rand();
         if ($updated === false) {
             $update_status = 'record-updated-error=' . rand();
         }
         // compose filters and sorting
         foreach ($this->filterers as $filterer => $caption) {
             if ($_REQUEST['filterer_' . $filterer] != '') {
                 $filtersGET .= '&filterer_' . $filterer . '=' . urlencode($_REQUEST['filterer_' . $filterer]);
             }
         }
         for ($i = 1; $i <= 20 * $FiltersPerGroup; $i++) {
             // Number of filters allowed
             if ($FilterField[$i] != '' && $FilterOperator[$i] != '' && ($FilterValue[$i] != '' || strpos($FilterOperator[$i], 'empty'))) {
                 $filtersGET .= "&FilterAnd[{$i}]={$FilterAnd[$i]}&FilterField[{$i}]={$FilterField[$i]}&FilterOperator[{$i}]={$FilterOperator[$i]}&FilterValue[{$i}]=" . urlencode($FilterValue[$i]);
             }
         }
         $filtersGET .= "&SortField={$SortField}&SortDirection={$SortDirection}&FirstRecord={$FirstRecord}&Embedded={$Embedded}";
         $filtersGET .= "&DisplayRecords={$DisplayRecords}";
         $filtersGET .= '&SearchString=' . urlencode($SearchString);
         $filtersGET = substr($filtersGET, 1);
         // remove initial &
         $redirectUrl = $this->ScriptFileName . '?SelectedID=' . urlencode($SelectedID) . '&' . $filtersGET . '&' . $update_status;
         @header("Location: {$redirectUrl}");
         $this->HTML .= '<META HTTP-EQUIV="Refresh" CONTENT="0;url=' . $redirectUrl . '">';
         return;
     } elseif ($addNew_x != '') {
         $SelectedID = '';
         $this->hideTV();
     } elseif ($Print_x != '') {
         // print code here ....
         $this->AllowNavigation = 0;
         $this->AllowSelection = 0;
     } elseif ($SaveFilter_x != '' && $this->AllowSavingFilters) {
         $filter_link = $_SERVER['HTTP_REFERER'] . '?SortField=' . urlencode($SortField) . '&SortDirection=' . $SortDirection . '&';
         for ($i = 1; $i <= 20 * $FiltersPerGroup; $i++) {
             // Number of filters allowed
             if (($FilterField[$i] != '' || $i == 1) && $FilterOperator[$i] != '' && ($FilterValue[$i] != '' || strpos($FilterOperator[$i], 'empty'))) {
                 $filter_link .= urlencode("FilterAnd[{$i}]") . '=' . urlencode($FilterAnd[$i]) . '&';
                 $filter_link .= urlencode("FilterField[{$i}]") . '=' . urlencode($FilterField[$i]) . '&';
                 $filter_link .= urlencode("FilterOperator[{$i}]") . '=' . urlencode($FilterOperator[$i]) . '&';
                 $filter_link .= urlencode("FilterValue[{$i}]") . '=' . urlencode($FilterValue[$i]) . '&';
             }
         }
         $filter_link = substr($filter_link, 0, -1);
         /* trim last '&' */
         $this->HTML .= '<div id="saved_filter_source_code" class="row"><div class="col-md-6 col-md-offset-3">';
         $this->HTML .= '<div class="panel panel-info">';
         $this->HTML .= '<div class="panel-heading"><h3 class="panel-title">' . $Translation["saved filters title"] . "</h3></div>";
         $this->HTML .= '<div class="panel-body">';
         $this->HTML .= $Translation["saved filters instructions"];
         $this->HTML .= '<textarea rows="4" class="form-control vspacer-lg" style="width: 100%;" onfocus="$j(this).select();">' . "&lt;a href=\"{$filter_link}\"&gt;Saved filter link&lt;a&gt;" . '</textarea>';
         $this->HTML .= "<div><a href=\"{$filter_link}\" title=\"" . htmlspecialchars($filter_link) . "\">{$Translation['permalink']}</a></div>";
         $this->HTML .= '<button type="button" class="btn btn-default btn-block vspacer-lg" onclick="$j(\'#saved_filter_source_code\').remove();"><i class="glyphicon glyphicon-remove"></i> ' . $Translation['hide code'] . '</button>';
         $this->HTML .= '</div>';
         $this->HTML .= '</div>';
         $this->HTML .= '</div></div>';
     } elseif ($Filter_x != '') {
         $orderBy = array();
         if ($SortField) {
             $sortFields = explode(',', $SortField);
             $i = 0;
             foreach ($sortFields as $sf) {
                 $tob = preg_split('/\\s+/', $sf, 2);
                 $orderBy[] = array(trim($tob[0]) => strtolower(trim($tob[1])) == 'desc' ? 'desc' : 'asc');
                 $i++;
             }
             $orderBy[$i - 1][$tob[0]] = strtolower(trim($SortDirection)) == 'desc' ? 'desc' : 'asc';
         }
         $currDir = dirname(__FILE__) . '/hooks';
         // path to hooks folder
         $uff = "{$currDir}/{$this->TableName}.filters.{$mi['username']}.php";
         // user-specific filter file
         $gff = "{$currDir}/{$this->TableName}.filters.{$mi['group']}.php";
         // group-specific filter file
         $tff = "{$currDir}/{$this->TableName}.filters.php";
         // table-specific filter file
         /*
         	if no explicit filter file exists, look for filter files in the hooks folder in this order:
         		1. tablename.filters.username.php ($uff)
         		2. tablename.filters.groupname.php ($gff)
         		3. tablename.filters.php ($tff)
         */
         if (!is_file($this->FilterPage)) {
             $this->FilterPage = 'defaultFilters.php';
             if (is_file($uff)) {
                 $this->FilterPage = $uff;
             } elseif (is_file($gff)) {
                 $this->FilterPage = $gff;
             } elseif (is_file($tff)) {
                 $this->FilterPage = $tff;
             }
         }
         if ($this->FilterPage != '') {
             ob_start();
             @(include $this->FilterPage);
             $out = ob_get_contents();
             ob_end_clean();
             $this->HTML .= $out;
         }
         // hidden variables ....
         $this->HTML .= '<input name="SortField" value="' . $SortField . '" type="hidden" />';
         $this->HTML .= '<input name="SortDirection" type="hidden" value="' . $SortDirection . '" />';
         $this->HTML .= '<input name="FirstRecord" type="hidden" value="1" />';
         $this->ContentType = 'filters';
         return;
     } elseif ($NoFilter_x != '') {
         // clear all filters ...
         for ($i = 1; $i <= datalist_filters_count * $FiltersPerGroup; $i++) {
             // Number of filters allowed
             $FilterField[$i] = '';
             $FilterOperator[$i] = '';
             $FilterValue[$i] = '';
         }
         $DisplayRecords = 'all';
         $SearchString = '';
         $FirstRecord = 1;
         // clear filterers
         foreach ($this->filterers as $filterer => $caption) {
             $_REQUEST['filterer_' . $filterer] = '';
         }
     } elseif ($SelectedID) {
         $this->hideTV();
     }
     // apply lookup filterers to the query
     foreach ($this->filterers as $filterer => $caption) {
         if ($_REQUEST['filterer_' . $filterer] != '') {
             if ($this->QueryWhere == '') {
                 $this->QueryWhere = "where ";
             } else {
                 $this->QueryWhere .= " and ";
             }
             $this->QueryWhere .= "`{$this->TableName}`.`{$filterer}`='" . makeSafe($_REQUEST['filterer_' . $filterer]) . "' ";
             break;
             // currently, only one filterer can be applied at a time
         }
     }
     // apply quick search to the query
     if ($SearchString != '') {
         if ($Search_x != '') {
             $FirstRecord = 1;
         }
         if ($this->QueryWhere == '') {
             $this->QueryWhere = "where ";
         } else {
             $this->QueryWhere .= " and ";
         }
         foreach ($this->QueryFieldsQS as $fName => $fCaption) {
             if (strpos($fName, '<img') === False) {
                 $this->QuerySearchableFields[$fName] = $fCaption;
             }
         }
         $this->QueryWhere .= '(' . implode(" LIKE '%" . makeSafe($SearchString) . "%' or ", array_keys($this->QuerySearchableFields)) . " LIKE '%" . makeSafe($SearchString) . "%')";
     }
     // set query filters
     $QueryHasWhere = 0;
     if (strpos($this->QueryWhere, 'where ') !== FALSE) {
         $QueryHasWhere = 1;
     }
     $WhereNeedsClosing = 0;
     for ($i = 1; $i <= datalist_filters_count * $FiltersPerGroup; $i += $FiltersPerGroup) {
         // Number of filters allowed
         // test current filter group
         $GroupHasFilters = 0;
         for ($j = 0; $j < $FiltersPerGroup; $j++) {
             if ($FilterField[$i + $j] != '' && $this->QueryFieldsIndexed[$FilterField[$i + $j]] != '' && $FilterOperator[$i + $j] != '' && ($FilterValue[$i + $j] != '' || strpos($FilterOperator[$i + $j], 'empty'))) {
                 $GroupHasFilters = 1;
                 break;
             }
         }
         if ($GroupHasFilters) {
             if (!stristr($this->QueryWhere, "where ")) {
                 $this->QueryWhere = "where (";
             } elseif ($QueryHasWhere) {
                 $this->QueryWhere .= " and (";
                 $QueryHasWhere = 0;
             }
             $this->QueryWhere .= " <FilterGroup> " . $FilterAnd[$i] . " (";
             for ($j = 0; $j < $FiltersPerGroup; $j++) {
                 if ($FilterField[$i + $j] != '' && $this->QueryFieldsIndexed[$FilterField[$i + $j]] != '' && $FilterOperator[$i + $j] != '' && ($FilterValue[$i + $j] != '' || strpos($FilterOperator[$i + $j], 'empty'))) {
                     if ($FilterAnd[$i + $j] == '') {
                         $FilterAnd[$i + $j] = 'and';
                     }
                     // test for date/time fields
                     $tries = 0;
                     $isDateTime = FALSE;
                     $isDate = FALSE;
                     $fieldName = str_replace('`', '', $this->QueryFieldsIndexed[$FilterField[$i + $j]]);
                     list($tn, $fn) = explode('.', $fieldName);
                     while (!($res = sql("show columns from `{$tn}` like '{$fn}'", $eo)) && $tries < 2) {
                         $tn = substr($tn, 0, -1);
                         $tries++;
                     }
                     if ($row = @db_fetch_array($res)) {
                         if ($row['Type'] == 'date' || $row['Type'] == 'time') {
                             $isDateTime = TRUE;
                             if ($row['Type'] == 'date') {
                                 $isDate = True;
                             }
                         }
                     }
                     // end of test
                     if ($FilterOperator[$i + $j] == 'is-empty' && !$isDateTime) {
                         $this->QueryWhere .= " <FilterItem> " . $FilterAnd[$i + $j] . " (" . $this->QueryFieldsIndexed[$FilterField[$i + $j]] . "='' or " . $this->QueryFieldsIndexed[$FilterField[$i + $j]] . " is NULL) </FilterItem>";
                     } elseif ($FilterOperator[$i + $j] == 'is-not-empty' && !$isDateTime) {
                         $this->QueryWhere .= " <FilterItem> " . $FilterAnd[$i + $j] . " " . $this->QueryFieldsIndexed[$FilterField[$i + $j]] . "!='' </FilterItem>";
                     } elseif ($FilterOperator[$i + $j] == 'is-empty' && $isDateTime) {
                         $this->QueryWhere .= " <FilterItem> " . $FilterAnd[$i + $j] . " (" . $this->QueryFieldsIndexed[$FilterField[$i + $j]] . "=0 or " . $this->QueryFieldsIndexed[$FilterField[$i + $j]] . " is NULL) </FilterItem>";
                     } elseif ($FilterOperator[$i + $j] == 'is-not-empty' && $isDateTime) {
                         $this->QueryWhere .= " <FilterItem> " . $FilterAnd[$i + $j] . " " . $this->QueryFieldsIndexed[$FilterField[$i + $j]] . "!=0 </FilterItem>";
                     } elseif ($FilterOperator[$i + $j] == 'like' && !strstr($FilterValue[$i + $j], "%") && !strstr($FilterValue[$i + $j], "_")) {
                         $this->QueryWhere .= " <FilterItem> " . $FilterAnd[$i + $j] . " " . $this->QueryFieldsIndexed[$FilterField[$i + $j]] . " like '%" . makeSafe($FilterValue[$i + $j]) . "%' </FilterItem>";
                     } elseif ($FilterOperator[$i + $j] == 'not-like' && !strstr($FilterValue[$i + $j], "%") && !strstr($FilterValue[$i + $j], "_")) {
                         $this->QueryWhere .= " <FilterItem> " . $FilterAnd[$i + $j] . " " . $this->QueryFieldsIndexed[$FilterField[$i + $j]] . " not like '%" . makeSafe($FilterValue[$i + $j]) . "%' </FilterItem>";
                     } elseif ($isDate) {
                         $dateValue = toMySQLDate($FilterValue[$i + $j]);
                         $this->QueryWhere .= " <FilterItem> " . $FilterAnd[$i + $j] . " " . $this->QueryFieldsIndexed[$FilterField[$i + $j]] . " " . $GLOBALS['filter_operators'][$FilterOperator[$i + $j]] . " '{$dateValue}' </FilterItem>";
                     } else {
                         $this->QueryWhere .= " <FilterItem> " . $FilterAnd[$i + $j] . " " . $this->QueryFieldsIndexed[$FilterField[$i + $j]] . " " . $GLOBALS['filter_operators'][$FilterOperator[$i + $j]] . " '" . makeSafe($FilterValue[$i + $j]) . "' </FilterItem>";
                     }
                 }
             }
             $this->QueryWhere .= ") </FilterGroup>";
             $WhereNeedsClosing = 1;
         }
     }
     if ($WhereNeedsClosing) {
         $this->QueryWhere .= ")";
     }
     // set query sort
     if (!stristr($this->QueryOrder, "order by ") && $SortField != '' && $this->AllowSorting) {
         $actualSortField = $SortField;
         foreach ($this->SortFields as $fieldNum => $fieldSort) {
             $actualSortField = str_replace(" {$fieldNum} ", " {$fieldSort} ", " {$actualSortField} ");
             $actualSortField = str_replace(",{$fieldNum} ", ",{$fieldSort} ", " {$actualSortField} ");
         }
         $this->QueryOrder = "order by {$actualSortField} {$SortDirection}";
     }
     // clean up query
     $this->QueryWhere = str_replace('( <FilterGroup> and ', '( ', $this->QueryWhere);
     $this->QueryWhere = str_replace('( <FilterGroup> or ', '( ', $this->QueryWhere);
     $this->QueryWhere = str_replace('( <FilterItem> and ', '( ', $this->QueryWhere);
     $this->QueryWhere = str_replace('( <FilterItem> or ', '( ', $this->QueryWhere);
     $this->QueryWhere = str_replace('<FilterGroup>', '', $this->QueryWhere);
     $this->QueryWhere = str_replace('</FilterGroup>', '', $this->QueryWhere);
     $this->QueryWhere = str_replace('<FilterItem>', '', $this->QueryWhere);
     $this->QueryWhere = str_replace('</FilterItem>', '', $this->QueryWhere);
     // if no 'order by' clause found, apply default sorting if specified
     if ($this->DefaultSortField != '' && $this->QueryOrder == '') {
         $this->QueryOrder = "order by " . $this->DefaultSortField . " " . $this->DefaultSortDirection;
     }
     // get count of matching records ...
     $TempQuery = 'SELECT count(1) from ' . $this->QueryFrom . ' ' . $this->QueryWhere;
     $RecordCount = sqlValue($TempQuery);
     $FieldCountTV = count($this->QueryFieldsTV);
     $FieldCountCSV = count($this->QueryFieldsCSV);
     $FieldCountFilters = count($this->QueryFieldsFilters);
     if (!$RecordCount) {
         $FirstRecord = 1;
     }
     // Output CSV on request
     if ($CSV_x != '') {
         $this->HTML = '';
         if (datalist_db_encoding == 'UTF-8') {
             $this->HTML = "";
         }
         // BOM characters for UTF-8 output
         // execute query for CSV output
         $fieldList = '';
         foreach ($this->QueryFieldsCSV as $fn => $fc) {
             $fieldList .= "{$fn} as `{$fc}`, ";
         }
         $fieldList = substr($fieldList, 0, -2);
         $csvQuery = 'SELECT ' . $fieldList . ' from ' . $this->QueryFrom . ' ' . $this->QueryWhere . ' ' . $this->QueryOrder;
         // hook: table_csv
         if (function_exists($this->TableName . '_csv')) {
             $args = array();
             $mq = call_user_func_array($this->TableName . '_csv', array($csvQuery, $mi, &$args));
             $csvQuery = $mq ? $mq : $csvQuery;
         }
         $result = sql($csvQuery, $eo);
         // output CSV field names
         for ($i = 0; $i < $FieldCountCSV; $i++) {
             $this->HTML .= "\"" . db_field_name($result, $i) . "\"" . $this->CSVSeparator;
         }
         $this->HTML .= "\n\n";
         // output CSV data
         while ($row = db_fetch_row($result)) {
             for ($i = 0; $i < $FieldCountCSV; $i++) {
                 $this->HTML .= "\"" . str_replace(array("\r\n", "\r", "\n", '"'), array(' ', ' ', ' ', '""'), strip_tags($row[$i])) . "\"" . $this->CSVSeparator;
             }
             $this->HTML .= "\n\n";
         }
         $this->HTML = str_replace($this->CSVSeparator . "\n\n", "\n", $this->HTML);
         $this->HTML = substr($this->HTML, 0, -1);
         // clean any output buffers
         while (@ob_end_clean()) {
         }
         // output CSV HTTP headers ...
         header('HTTP/1.1 200 OK');
         header('Date: ' . @date("D M j G:i:s T Y"));
         header('Last-Modified: ' . @date("D M j G:i:s T Y"));
         header("Content-Type: application/force-download");
         header("Content-Length: " . (string) strlen($this->HTML));
         header("Content-Transfer-Encoding: Binary");
         header("Content-Disposition: attachment; filename={$this->TableName}.csv");
         // send output and quit script
         echo $this->HTML;
         exit;
     }
     $t = time();
     // just a random number for any purpose ...
     // should SelectedID be reset on clicking TV buttons?
     $resetSelection = $this->SeparateDV ? "document.myform.SelectedID.value = '';" : "document.myform.writeAttribute('novalidate', 'novalidate');";
     if ($current_view == 'DV' && !$Embedded) {
         $this->HTML .= '<div class="page-header">';
         $this->HTML .= '<h1>';
         $this->HTML .= '<a style="text-decoration: none; color: inherit;" href="' . $this->TableName . '_view.php"><img src="' . $this->TableIcon . '"> ' . $this->TableTitle . '</a>';
         $this->HTML .= '</h1>';
         $this->HTML .= '</div>';
     }
     // quick search and TV action buttons
     if (!$this->HideTableView && !($dvprint_x && $this->AllowSelection && $SelectedID) && !$PrintDV) {
         $buttons_all = $quick_search_html = '';
         if ($Print_x == '') {
             // display 'Add New' icon
             if ($this->Permissions[1] && $this->SeparateDV) {
                 $buttons_all .= '<button type="submit" id="addNew" name="addNew_x" value="1" class="btn btn-success"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Add New'] . '</button>';
                 $buttonsCount++;
             }
             // display Print icon
             if ($this->AllowPrinting) {
                 $buttons_all .= '<button onClick="document.myform.NoDV.value=1; ' . $resetSelection . ' return true;" type="submit" name="Print_x" id="Print" value="1" class="btn btn-default"><i class="glyphicon glyphicon-print"></i> ' . $Translation['Print Preview'] . '</button>';
                 $buttonsCount++;
             }
             // display CSV icon
             if ($this->AllowCSV) {
                 $buttons_all .= '<button onClick="document.myform.NoDV.value=1; ' . $resetSelection . ' return true;" type="submit" name="CSV_x" id="CSV" value="1" class="btn btn-default"><i class="glyphicon glyphicon-download-alt"></i> ' . $Translation['CSV'] . '</button>';
                 $buttonsCount++;
             }
             // display Filter icon
             if ($this->AllowFilters) {
                 $buttons_all .= '<button onClick="document.myform.NoDV.value=1; ' . $resetSelection . ' return true;" type="submit" name="Filter_x" id="Filter" value="1" class="btn btn-default"><i class="glyphicon glyphicon-filter"></i> ' . $Translation['filter'] . '</button>';
                 $buttonsCount++;
             }
             // display Show All icon
             if ($this->AllowFilters) {
                 $buttons_all .= '<button onClick="document.myform.NoDV.value=1; ' . $resetSelection . ' return true;" type="submit" name="NoFilter_x" id="NoFilter" value="1" class="btn btn-default"><i class="glyphicon glyphicon-remove-circle"></i> ' . $Translation['Reset Filters'] . '</button>';
                 $buttonsCount++;
             }
             $quick_search_html .= '<div class="input-group" id="quick-search">';
             $quick_search_html .= '<input type="text" name="SearchString" value="' . htmlspecialchars($SearchString, ENT_QUOTES, 'iso-8859-1') . '" class="form-control" placeholder="' . htmlspecialchars($this->QuickSearchText) . '">';
             $quick_search_html .= '<span class="input-group-btn">';
             $quick_search_html .= '<button name="Search_x" value="1" id="Search" type="submit" onClick="' . $resetSelection . ' document.myform.NoDV.value=1; return true;"  class="btn btn-default" title="' . htmlspecialchars($this->QuickSearchText) . '"><i class="glyphicon glyphicon-search"></i></button>';
             $quick_search_html .= '<button name="NoFilter_x" value="1" id="NoFilter_x" type="submit" onClick="' . $resetSelection . ' document.myform.NoDV.value=1; return true;"  class="btn btn-default" title="' . htmlspecialchars($Translation['Reset Filters']) . '"><i class="glyphicon glyphicon-remove-circle"></i></button>';
             $quick_search_html .= '</span>';
             $quick_search_html .= '</div>';
         } else {
             $buttons_all .= '<button class="btn btn-primary" type="button" id="sendToPrinter" onClick="window.print();"><i class="glyphicon glyphicon-print"></i> ' . $Translation['Print'] . '</button>';
             $buttons_all .= '<button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-remove-circle"></i> ' . $Translation['Cancel Printing'] . '</button>';
         }
         /* if user can print DV, add action to 'More' menu */
         $selected_records_more = array();
         if ($AllowPrintDV) {
             $selected_records_more[] = array('function' => $this->SeparateDV ? 'print_multiple_dv_sdv' : 'print_multiple_dv_tvdv', 'title' => $Translation['Print Preview Detail View'], 'icon' => 'print');
         }
         /* if user can mass-delete selected records, add action to 'More' menu */
         if ($this->AllowMassDelete && $this->AllowDelete) {
             $selected_records_more[] = array('function' => 'mass_delete', 'title' => $Translation['Delete'], 'icon' => 'trash', 'class' => 'text-danger');
         }
         /* if user is admin, add 'Change owner' action to 'More' menu */
         /* also, add help link for adding more actions */
         if ($mi['admin']) {
             $selected_records_more[] = array('function' => 'mass_change_owner', 'title' => $Translation['Change owner'], 'icon' => 'user');
             $selected_records_more[] = array('function' => 'add_more_actions_link', 'title' => $Translation['Add more actions'], 'icon' => 'question-sign', 'class' => 'text-info');
         }
         /* user-defined actions ... should be set in the {tablename}_batch_actions() function in hooks/{tablename}.php */
         $user_actions = array();
         if (function_exists($this->TableName . '_batch_actions')) {
             $args = array();
             $user_actions = call_user_func_array($this->TableName . '_batch_actions', array(&$args));
             if (is_array($user_actions) && count($user_actions)) {
                 $selected_records_more = array_merge($selected_records_more, $user_actions);
             }
         }
         $actual_more_count = 0;
         $more_menu = $more_menu_js = '';
         if (count($selected_records_more)) {
             $more_menu .= '<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" id="selected_records_more"><i class="glyphicon glyphicon-check"></i> ' . $Translation['More'] . ' <span class="caret"></span></button>';
             $more_menu .= '<ul class="dropdown-menu" role="menu">';
             foreach ($selected_records_more as $action) {
                 if (!$action['function'] || !$action['title']) {
                     continue;
                 }
                 $action['class'] = !isset($action['class']) ? '' : $action['class'];
                 $action['icon'] = !isset($action['icon']) ? '' : $action['icon'];
                 $actual_more_count++;
                 $more_menu .= '<li>' . '<a href="#" id="selected_records_' . $action['function'] . '">' . '<span class="' . $action['class'] . '">' . ($action['icon'] ? '<i class="glyphicon glyphicon-' . $action['icon'] . '"></i> ' : '') . $action['title'] . '</span>' . '</a>' . '</li>';
                 // on clicking an action, call its js handler function, passing the current table name and an array of selected IDs to it
                 $more_menu_js .= "jQuery('[id=selected_records_{$action['function']}]').click(function(){ {$action['function']}('{$this->TableName}', get_selected_records_ids()); return false; });";
             }
             $more_menu .= '</ul>';
         }
         if ($Embedded) {
             $this->HTML .= '<script>$j(function(){ $j(\'[id^=notification-]\').parent().css({\'margin-top\': \'15px\', \'margin-bottom\': \'0\'}); })</script>';
         } else {
             $this->HTML .= '<div class="page-header">';
             $this->HTML .= '<h1>';
             $this->HTML .= '<div class="row">';
             $this->HTML .= '<div class="col-sm-8">';
             $this->HTML .= '<a style="text-decoration: none; color: inherit;" href="' . $this->TableName . '_view.php"><img src="' . $this->TableIcon . '"> ' . $this->TableTitle . '</a>';
             $this->HTML .= '</div>';
             if ($this->QuickSearch) {
                 $this->HTML .= '<div class="col-sm-4">';
                 $this->HTML .= $quick_search_html;
                 $this->HTML .= '</div>';
             }
             $this->HTML .= '</div>';
             $this->HTML .= '</h1>';
             $this->HTML .= '</div>';
             $this->HTML .= '<div id="top_buttons" class="hidden-print">';
             /* .all_records: container for buttons that don't need a selection */
             /* .selected_records: container for buttons that need a selection */
             $this->HTML .= '<div class="btn-group btn-group-lg visible-md visible-lg all_records pull-left">' . $buttons_all . '</div>';
             $this->HTML .= '<div class="btn-group btn-group-lg visible-md visible-lg selected_records hidden pull-left hspacer-lg">' . $buttons_selected . ($actual_more_count ? $more_menu : '') . '</div>';
             $this->HTML .= '<div class="btn-group-vertical btn-group-lg visible-xs visible-sm all_records">' . $buttons_all . '</div>';
             $this->HTML .= '<div class="btn-group-vertical btn-group-lg visible-xs visible-sm selected_records hidden vspacer-lg">' . $buttons_selected . ($actual_more_count ? $more_menu : '') . '</div>';
             $this->HTML .= '<div class="clearfix"></div><p></p>';
             $this->HTML .= '</div>';
         }
         if ($Print_x != '') {
             /* fix top margin for print-preview */
             $this->HTML .= '<style>body{ padding-top: 0 !important; }</style>';
             /* disable links inside table body to prevent printing their href */
             $this->HTML .= '<script>jQuery(function(){ jQuery("tbody a").removeAttr("href").removeAttr("rel"); });</script>';
         }
         // script for focusing into the search box on loading the page
         // and for declaring record action handlers
         $this->HTML .= '<script>jQuery(function(){ jQuery("input[name=SearchString]").focus();  ' . $more_menu_js . ' });</script>';
     }
     // begin table and display table title
     if (!$this->HideTableView && !($dvprint_x && $this->AllowSelection && $SelectedID) && !$PrintDV && !$Embedded) {
         $this->HTML .= '<div class="table-responsive"><table class="table table-striped table-bordered table-hover">';
         $this->HTML .= '<thead><tr>';
         if (!$Print_x) {
             $this->HTML .= '<th style="width: 18px;" class="text-center"><input class="hidden-print" type="checkbox" title="' . htmlspecialchars($Translation['Select all records']) . '" id="select_all_records"></th>';
         }
         // Templates
         if ($this->Template != '') {
             $rowTemplate = @implode('', @file('./' . $this->Template));
             if (!$rowTemplate) {
                 $rowTemplate = '';
                 $selrowTemplate = '';
             } else {
                 if ($this->SelectedTemplate != '') {
                     $selrowTemplate = @implode('', @file('./' . $this->SelectedTemplate));
                     if (!$selrowTemplate) {
                         $selrowTemplate = '';
                     }
                 } else {
                     $selrowTemplate = '';
                 }
             }
         } else {
             $rowTemplate = '';
             $selrowTemplate = '';
         }
         // process translations
         if ($rowTemplate) {
             foreach ($Translation as $symbol => $trans) {
                 $rowTemplate = str_replace("<%%TRANSLATION({$symbol})%%>", $trans, $rowTemplate);
             }
         }
         if ($selrowTemplate) {
             foreach ($Translation as $symbol => $trans) {
                 $selrowTemplate = str_replace("<%%TRANSLATION({$symbol})%%>", $trans, $selrowTemplate);
             }
         }
         // End of templates
         // $this->ccffv: map $FilterField values to field captions as stored in ColCaption
         $this->ccffv = array();
         foreach ($this->ColCaption as $captionIndex => $caption) {
             $ffv = 1;
             foreach ($this->QueryFieldsFilters as $uselessKey => $filterCaption) {
                 if ($caption == $filterCaption) {
                     $this->ccffv[$captionIndex] = $ffv;
                 }
                 $ffv++;
             }
         }
         // display table headers
         $totalColWidth = array_sum($this->ColWidth);
         $forceHeaderWidth = false;
         if ($rowTemplate == '' || $this->ShowTableHeader) {
             for ($i = 0; $i < count($this->ColCaption); $i++) {
                 /* Sorting icon and link */
                 $sort1 = $sort2 = $filterHint = '';
                 if ($this->AllowSorting == 1) {
                     if ($current_view != 'TVP') {
                         $sort1 = "<a href=\"{$this->ScriptFileName}?SortDirection=asc&SortField=" . $this->ColNumber[$i] . "\" onClick=\"{$resetSelection} document.myform.NoDV.value=1; document.myform.SortDirection.value='asc'; document.myform.SortField.value = '" . $this->ColNumber[$i] . "'; document.myform.submit(); return false;\" class=\"TableHeader\">";
                         $sort2 = "</a>";
                     }
                     if ($this->ColNumber[$i] == $SortField) {
                         $SortDirection = $SortDirection == "asc" ? "desc" : "asc";
                         if ($current_view != 'TVP') {
                             $sort1 = "<a href=\"{$this->ScriptFileName}?SortDirection={$SortDirection}&SortField=" . $this->ColNumber[$i] . "\" onClick=\"{$resetSelection} document.myform.NoDV.value=1; document.myform.SortDirection.value='{$SortDirection}'; document.myform.SortField.value = " . $this->ColNumber[$i] . "; document.myform.submit(); return false;\" class=\"TableHeader\">";
                         }
                         $sort2 = " <i class=\"text-warning glyphicon glyphicon-sort-by-attributes" . ($SortDirection == 'desc' ? '' : '-alt') . "\"></i>{$sort2}";
                         $SortDirection = $SortDirection == "asc" ? "desc" : "asc";
                     }
                 } else {
                     $sort1 = '';
                     $sort2 = '';
                 }
                 /* Filtering icon and hint */
                 if ($this->AllowFilters && is_array($FilterField)) {
                     // check to see if there is any filter applied on the current field
                     if (isset($this->ccffv[$i]) && in_array($this->ccffv[$i], $FilterField)) {
                         // render filter icon
                         $filterHint = '&nbsp;<button type="submit" class="btn btn-default btn-xs' . ($current_view == 'TVP' ? ' disabled' : '') . '" name="Filter_x" value="1" title="' . htmlspecialchars($Translation['filtered field']) . '"><i class="glyphicon glyphicon-filter"></i></button>';
                     }
                 }
                 $this->HTML .= "\t<th class=\"{$this->TableName}-{$this->ColFieldName[$i]}\" " . ($forceHeaderWidth ? ' style="width: ' . ($this->ColWidth[$i] ? $this->ColWidth[$i] : 100) . 'px;"' : '') . ">{$sort1}{$this->ColCaption[$i]}{$sort2}{$filterHint}</th>\n";
             }
         } else {
             // Display a Sort by drop down
             $this->HTML .= "\t<th><td colspan=" . (count($this->ColCaption) + 1) . ">";
             if ($this->AllowSorting == 1) {
                 $sortCombo = new Combo();
                 for ($i = 0; $i < count($this->ColCaption); $i++) {
                     $sortCombo->ListItem[] = $this->ColCaption[$i];
                     $sortCombo->ListData[] = $this->ColNumber[$i];
                 }
                 $sortCombo->SelectName = "FieldsList";
                 $sortCombo->SelectedData = $SortField;
                 $sortCombo->Class = 'TableBody';
                 $sortCombo->SelectedClass = 'TableBodySelected';
                 $sortCombo->Render();
                 $d = $sortCombo->HTML;
                 $d = str_replace('<select ', "<select onChange=\"document.myform.SortDirection.value='{$SortDirection}'; document.myform.SortField.value=document.myform.FieldsList.value; document.myform.NoDV.value=1; document.myform.submit();\" ", $d);
                 if ($SortField) {
                     $SortDirection = $SortDirection == "desc" ? "asc" : "desc";
                     $sort = "<a href=\"javascript: document.myform.NoDV.value=1; document.myform.SortDirection.value='{$SortDirection}'; document.myform.SortField.value='{$SortField}'; document.myform.submit();\" class=TableHeader><img src={$SortDirection}.gif border=0 width=11 height=11 hspace=3></a>";
                     $SortDirection = $SortDirection == "desc" ? "asc" : "desc";
                 } else {
                     $sort = '';
                 }
                 $this->HTML .= $Translation['order by'] . " {$d} {$sort}";
             }
             $this->HTML .= "</td></th>\n";
         }
         // table view navigation code ...
         if ($RecordCount && $this->AllowNavigation && $RecordCount > $this->RecordsPerPage) {
             while ($FirstRecord > $RecordCount) {
                 $FirstRecord -= $this->RecordsPerPage;
             }
             if ($FirstRecord == '' || $FirstRecord < 1) {
                 $FirstRecord = 1;
             }
             if ($Previous_x != '') {
                 $FirstRecord -= $this->RecordsPerPage;
                 if ($FirstRecord <= 0) {
                     $FirstRecord = 1;
                 }
             } elseif ($Next_x != '') {
                 $FirstRecord += $this->RecordsPerPage;
                 if ($FirstRecord > $RecordCount) {
                     $FirstRecord = $RecordCount - $RecordCount % $this->RecordsPerPage + 1;
                 }
                 if ($FirstRecord > $RecordCount) {
                     $FirstRecord = $RecordCount - $this->RecordsPerPage + 1;
                 }
                 if ($FirstRecord <= 0) {
                     $FirstRecord = 1;
                 }
             }
         } elseif ($RecordCount) {
             $FirstRecord = 1;
             $this->RecordsPerPage = 2000;
             // a limit on max records in print preview to avoid performance drops
         }
         // end of table view navigation code
         $this->HTML .= "\n\t</tr>\n\n</thead>\n\n<tbody><!-- tv data below -->\n";
         $i = 0;
         $hc = new CI_Input();
         $hc->charset = datalist_db_encoding;
         if ($RecordCount) {
             $i = $FirstRecord;
             // execute query for table view
             $fieldList = '';
             foreach ($this->QueryFieldsTV as $fn => $fc) {
                 $fieldList .= "{$fn} as `{$fc}`, ";
             }
             $fieldList = substr($fieldList, 0, -2);
             if ($this->PrimaryKey) {
                 $fieldList .= ", {$this->PrimaryKey} as '" . str_replace('`', '', $this->PrimaryKey) . "'";
             }
             $tvQuery = 'SELECT ' . $fieldList . ' from ' . $this->QueryFrom . ' ' . $this->QueryWhere . ' ' . $this->QueryOrder;
             $result = sql($tvQuery . " limit " . ($i - 1) . ",{$this->RecordsPerPage}", $eo);
             while (($row = db_fetch_array($result)) && $i < $FirstRecord + $this->RecordsPerPage) {
                 $attr_id = htmlspecialchars($row[$FieldCountTV], ENT_QUOTES, 'iso-8859-1');
                 /* pk value suitable for inserting into html tag attributes */
                 $js_id = addslashes($row[$FieldCountTV]);
                 /* pk value suitable for inserting into js strings */
                 $alt = ($i - $FirstRecord) % 2;
                 if (($PrintTV || $Print_x) && count($_POST['record_selector']) && !in_array($row[$FieldCountTV], $_POST['record_selector'])) {
                     continue;
                 }
                 $class = "TableBody" . ($alt ? 'Selected' : '') . ($fNumeric ? 'Numeric' : '');
                 if ($Print_x != '') {
                     $this->HTML .= '<tr>';
                 }
                 if (!$Print_x) {
                     $this->HTML .= $SelectedID == $row[$FieldCountTV] ? '<tr class="active">' : '<tr>';
                     $checked = is_array($_POST['record_selector']) && in_array($row[$FieldCountTV], $_POST['record_selector']) ? ' checked' : '';
                     $this->HTML .= "<td class=\"text-center\"><input class=\"hidden-print record_selector\" type=\"checkbox\" id=\"record_selector_{$attr_id}\" name=\"record_selector[]\" value=\"{$attr_id}\"{$checked}></td>";
                 }
                 // templates
                 if ($rowTemplate != '') {
                     if ($this->AllowSelection == 1 && $SelectedID == $row[$FieldCountTV] && $selrowTemplate != '') {
                         $rowTemp = $selrowTemplate;
                     } else {
                         $rowTemp = $rowTemplate;
                     }
                     if ($this->AllowSelection == 1 && $SelectedID != $row[$FieldCountTV]) {
                         $rowTemp = str_replace('<%%SELECT%%>', "<a onclick=\"document.myform.SelectedField.value=this.parentNode.cellIndex; document.myform.SelectedID.value='" . addslashes($row[$FieldCountTV]) . "'; document.myform.submit(); return false;\" href=\"{$this->ScriptFileName}?SelectedID=" . htmlspecialchars($row[$FieldCountTV], ENT_QUOTES) . "\" class=\"{$class}\" style=\"display: block; padding:0px;\">", $rowTemp);
                         $rowTemp = str_replace('<%%ENDSELECT%%>', '</a>', $rowTemp);
                     } else {
                         $rowTemp = str_replace('<%%SELECT%%>', '', $rowTemp);
                         $rowTemp = str_replace('<%%ENDSELECT%%>', '', $rowTemp);
                     }
                     for ($j = 0; $j < $FieldCountTV; $j++) {
                         $fieldTVCaption = current(array_slice($this->QueryFieldsTV, $j, 1));
                         $fd = $hc->xss_clean(nl2br($row[$j]));
                         /* Sanitize output against XSS attacks */
                         /*
                         	the TV template could contain field placeholders in the format 
                         	<%%FIELD_n%%> or <%%VALUE(Field name)%%> 
                         */
                         $rowTemp = str_replace("<%%FIELD_{$j}%%>", thisOr($fd), $rowTemp);
                         $rowTemp = str_replace("<%%VALUE({$fieldTVCaption})%%>", thisOr($fd), $rowTemp);
                         if (strpos($rowTemp, "<%%YOUTUBETHUMB({$fieldTVCaption})%%>") !== false) {
                             $rowTemp = str_replace("<%%YOUTUBETHUMB({$fieldTVCaption})%%>", thisOr(get_embed('youtube', $fd, '', '', 'thumbnail_url'), 'blank.gif'), $rowTemp);
                         }
                         if (strpos($rowTemp, "<%%GOOGLEMAPTHUMB({$fieldTVCaption})%%>") !== false) {
                             $rowTemp = str_replace("<%%GOOGLEMAPTHUMB({$fieldTVCaption})%%>", thisOr(get_embed('googlemap', $fd, '', '', 'thumbnail_url'), 'blank.gif'), $rowTemp);
                         }
                         if (thisOr($fd) == '&nbsp;' && preg_match('/<a href=".*?&nbsp;.*?<\\/a>/i', $rowTemp, $m)) {
                             $rowTemp = str_replace($m[0], '', $rowTemp);
                         }
                     }
                     if ($alt && $SelectedID != $row[$FieldCountTV]) {
                         $rowTemp = str_replace("TableBody", "TableBodySelected", $rowTemp);
                         $rowTemp = str_replace("TableBodyNumeric", "TableBodySelectedNumeric", $rowTemp);
                         $rowTemp = str_replace("SelectedSelected", "Selected", $rowTemp);
                     }
                     if ($SearchString != '') {
                         $rowTemp = highlight($SearchString, $rowTemp);
                     }
                     $this->HTML .= $rowTemp;
                     $rowTemp = '';
                 } else {
                     // end of templates
                     for ($j = 0; $j < $FieldCountTV; $j++) {
                         $fType = db_field_type($result, $j);
                         $fNumeric = stristr($fType, 'int') || stristr($fType, 'float') || stristr($fType, 'decimal') || stristr($fType, 'numeric') || stristr($fType, 'real') || stristr($fType, 'double') ? true : false;
                         if ($this->AllowSelection == 1) {
                             $sel1 = "<a href=\"{$this->ScriptFileName}?SelectedID=" . htmlspecialchars($row[$FieldCountTV], ENT_QUOTES) . "\" onclick=\"document.myform.SelectedID.value='" . addslashes($row[$FieldCountTV]) . "'; document.myform.submit(); return false;\" class=\"{$class}\" style=\"padding:0px;\">";
                             $sel2 = "</a>";
                         } else {
                             $sel1 = '';
                             $sel2 = '';
                         }
                         $this->HTML .= "<td valign=top class={$class}><div class={$class}>&nbsp;{$sel1}" . $row[$j] . "{$sel2}&nbsp;</div></td>";
                     }
                 }
                 $this->HTML .= "</tr>\n";
                 $i++;
             }
             $i--;
         }
         $this->HTML = preg_replace("/<a href=\"(mailto:)?&nbsp;[^\n]*title=\"&nbsp;\"><\\/a>/", '&nbsp;', $this->HTML);
         $this->HTML = preg_replace("/<a [^>]*>(&nbsp;)*<\\/a>/", '&nbsp;', $this->HTML);
         $this->HTML = preg_replace("/<%%.*%%>/U", '&nbsp;', $this->HTML);
         // end of data
         $this->HTML .= '<!-- tv data above -->';
         $this->HTML .= "\n</tbody>";
         if ($Print_x == '') {
             // TV
             $pagesMenu = '';
             if ($RecordCount > $this->RecordsPerPage) {
                 $pagesMenuId = "{$this->TableName}_pagesMenu";
                 $pagesMenu = $Translation['go to page'] . ' <select class="input-sm" id="' . $pagesMenuId . '" onChange="document.myform.writeAttribute(\'novalidate\', \'novalidate\'); document.myform.NoDV.value=1; document.myform.FirstRecord.value=(this.value * ' . $this->RecordsPerPage . '+1); document.myform.submit();">';
                 $pagesMenu .= '</select>';
                 $pagesMenu .= '<script>';
                 $pagesMenu .= 'var lastPage = ' . (ceil($RecordCount / $this->RecordsPerPage) - 1) . ';';
                 $pagesMenu .= 'var currentPage = ' . ($FirstRecord - 1) / $this->RecordsPerPage . ';';
                 $pagesMenu .= 'var pagesMenu = document.getElementById("' . $pagesMenuId . '");';
                 $pagesMenu .= 'var lump = ' . datalist_max_page_lump . ';';
                 $pagesMenu .= 'if(lastPage <= lump * 3){';
                 $pagesMenu .= '  addPageNumbers(0, lastPage);';
                 $pagesMenu .= '}else{';
                 $pagesMenu .= '  addPageNumbers(0, lump - 1);';
                 $pagesMenu .= '  if(currentPage < lump) addPageNumbers(lump, currentPage + lump / 2);';
                 $pagesMenu .= '  if(currentPage >= lump && currentPage < (lastPage - lump)){';
                 $pagesMenu .= '    addPageNumbers(';
                 $pagesMenu .= '      Math.max(currentPage - lump / 2, lump),';
                 $pagesMenu .= '      Math.min(currentPage + lump / 2, lastPage - lump - 1)';
                 $pagesMenu .= '    );';
                 $pagesMenu .= '  }';
                 $pagesMenu .= '  if(currentPage >= (lastPage - lump)) addPageNumbers(currentPage - lump / 2, lastPage - lump - 1);';
                 $pagesMenu .= '  addPageNumbers(lastPage - lump, lastPage);';
                 $pagesMenu .= '}';
                 $pagesMenu .= 'function addPageNumbers(fromPage, toPage){';
                 $pagesMenu .= '  var ellipsesIndex = 0;';
                 $pagesMenu .= '  if(fromPage > toPage) return;';
                 $pagesMenu .= '  if(fromPage > 0){';
                 $pagesMenu .= '    if(pagesMenu.options[pagesMenu.options.length - 1].text != fromPage){';
                 $pagesMenu .= '      ellipsesIndex = pagesMenu.options.length;';
                 $pagesMenu .= '      fromPage--;';
                 $pagesMenu .= '    }';
                 $pagesMenu .= '  }';
                 $pagesMenu .= '  for(i = fromPage; i <= toPage; i++){';
                 $pagesMenu .= '    var option = document.createElement("option");';
                 $pagesMenu .= '    option.text = (i + 1);';
                 $pagesMenu .= '    option.value = i;';
                 $pagesMenu .= '    if(i == currentPage){ option.selected = "selected"; }';
                 $pagesMenu .= '    try{';
                 $pagesMenu .= '      /* for IE earlier than version 8 */';
                 $pagesMenu .= '      pagesMenu.add(option, pagesMenu.options[null]);';
                 $pagesMenu .= '    }catch(e){';
                 $pagesMenu .= '      pagesMenu.add(option, null);';
                 $pagesMenu .= '    }';
                 $pagesMenu .= '  }';
                 $pagesMenu .= '  if(ellipsesIndex > 0){';
                 $pagesMenu .= '    pagesMenu.options[ellipsesIndex].text = " ... ";';
                 $pagesMenu .= '  }';
                 $pagesMenu .= '}';
                 $pagesMenu .= '</script>';
             }
             $this->HTML .= "\n\t";
             if ($i) {
                 // 1 or more records found
                 $this->HTML .= "<tfoot><tr><td colspan=" . (count($this->ColCaption) + 1) . '>';
                 $this->HTML .= $Translation['records x to y of z'];
                 $this->HTML .= '</td></tr></tfoot>';
             }
             if (!$i) {
                 // no records found
                 $this->HTML .= "<tfoot><tr><td colspan=" . (count($this->ColCaption) + 1) . '>';
                 $this->HTML .= '<div class="alert alert-warning">';
                 $this->HTML .= '<i class="glyphicon glyphicon-warning-sign"></i> ';
                 $this->HTML .= $Translation['No matches found!'];
                 $this->HTML .= '</div>';
                 $this->HTML .= '</td></tr></tfoot>';
             }
         } else {
             // TVP
             if ($i) {
                 $this->HTML .= "\n\t<tfoot><tr><td colspan=" . (count($this->ColCaption) + 1) . '>' . $Translation['records x to y of z'] . '</td></tr></tfoot>';
             }
             if (!$i) {
                 $this->HTML .= "\n\t<tfoot><tr><td colspan=" . (count($this->ColCaption) + 1) . '>' . $Translation['No matches found!'] . '</td></tr></tfoot>';
             }
         }
         $this->HTML = str_replace("<FirstRecord>", number_format($FirstRecord), $this->HTML);
         $this->HTML = str_replace("<LastRecord>", number_format($i), $this->HTML);
         $this->HTML = str_replace("<RecordCount>", number_format($RecordCount), $this->HTML);
         $tvShown = true;
         $this->HTML .= "</table></div>\n";
         if ($Print_x == '' && $i) {
             // TV
             $this->HTML .= '<div class="row">';
             $this->HTML .= '<div class="col-sm-4 col-md-3 col-lg-2 vspacer-lg">';
             $this->HTML .= '<button onClick="' . $resetSelection . ' document.myform.NoDV.value = 1; return true;" type="submit" name="Previous_x" id="Previous" value="1" class="btn btn-default btn-block"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Previous'] . '</button>';
             $this->HTML .= '</div>';
             $this->HTML .= '<div class="col-sm-4 col-md-4 col-lg-2 col-md-offset-1 col-lg-offset-3 text-center vspacer-lg">';
             $this->HTML .= $pagesMenu;
             $this->HTML .= '</div>';
             $this->HTML .= '<div class="col-sm-4 col-md-3 col-lg-2 col-md-offset-1 col-lg-offset-3 text-right vspacer-lg">';
             $this->HTML .= '<button onClick="' . $resetSelection . ' document.myform.NoDV.value=1; return true;" type="submit" name="Next_x" id="Next" value="1" class="btn btn-default btn-block">' . $Translation['Next'] . ' <i class="glyphicon glyphicon-chevron-right"></i></button>';
             $this->HTML .= '</div>';
             $this->HTML .= '</div>';
         }
     }
     /* that marks the end of the TV table */
     // hidden variables ....
     foreach ($this->filterers as $filterer => $caption) {
         if ($_REQUEST['filterer_' . $filterer] != '') {
             $this->HTML .= "<input name=\"filterer_{$filterer}\" value=\"" . htmlspecialchars($_REQUEST['filterer_' . $filterer], ENT_QUOTES, 'iso-8859-1') . "\" type=\"hidden\" />";
             break;
             // currently, only one filterer can be applied at a time
         }
     }
     $this->HTML .= '<input name="SortField" value="' . $SortField . '" type="hidden">';
     $this->HTML .= '<input name="SelectedID" value="' . htmlspecialchars($SelectedID, ENT_QUOTES, 'iso-8859-1') . '" type="hidden">';
     $this->HTML .= '<input name="SelectedField" value="" type="hidden">';
     $this->HTML .= '<input name="SortDirection" type="hidden" value="' . $SortDirection . '">';
     $this->HTML .= '<input name="FirstRecord" type="hidden" value="' . $FirstRecord . '">';
     $this->HTML .= '<input name="NoDV" type="hidden" value="">';
     $this->HTML .= '<input name="PrintDV" type="hidden" value="">';
     if ($this->QuickSearch && !strpos($this->HTML, 'SearchString')) {
         $this->HTML .= '<input name="SearchString" type="hidden" value="' . htmlspecialchars($SearchString, ENT_QUOTES, 'iso-8859-1') . '">';
     }
     // hidden variables: filters ...
     $FiltersCode = '';
     for ($i = 1; $i <= datalist_filters_count * $FiltersPerGroup; $i++) {
         // Number of filters allowed
         if ($i % $FiltersPerGroup == 1 && $i != 1 && $FilterAnd[$i] != '') {
             $FiltersCode .= "<input name=\"FilterAnd[{$i}]\" value=\"{$FilterAnd[$i]}\" type=\"hidden\">\n";
         }
         if ($FilterField[$i] != '' && $FilterOperator[$i] != '' && ($FilterValue[$i] != '' || strpos($FilterOperator[$i], 'empty'))) {
             if (!strstr($FiltersCode, "<input name=\"FilterAnd[{$i}]\" value=")) {
                 $FiltersCode .= "<input name=\"FilterAnd[{$i}]\" value=\"{$FilterAnd[$i]}\" type=\"hidden\">\n";
             }
             $FiltersCode .= "<input name=\"FilterField[{$i}]\" value=\"{$FilterField[$i]}\" type=\"hidden\">\n";
             $FiltersCode .= "<input name=\"FilterOperator[{$i}]\" value=\"{$FilterOperator[$i]}\" type=\"hidden\">\n";
             $FiltersCode .= "<input name=\"FilterValue[{$i}]\" value=\"" . htmlspecialchars($FilterValue[$i], ENT_QUOTES, 'iso-8859-1') . "\" type=\"hidden\">\n";
         }
     }
     $FiltersCode .= "<input name=\"DisplayRecords\" value=\"{$DisplayRecords}\" type=\"hidden\" />";
     $this->HTML .= $FiltersCode;
     // display details form ...
     if (($this->AllowSelection || $this->AllowInsert || $this->AllowUpdate || $this->AllowDelete) && $Print_x == '' && !$PrintDV) {
         if ($this->SeparateDV && $this->HideTableView || !$this->SeparateDV) {
             $dvCode = call_user_func("{$this->TableName}_form", $SelectedID, $this->AllowUpdate, $this->HideTableView && $SelectedID ? 0 : $this->AllowInsert, $this->AllowDelete, $this->SeparateDV);
             $this->HTML .= "\n\t<div class=\"panel panel-default detail_view\">{$dvCode}</div>";
             $this->HTML .= $this->SeparateDV ? '<input name="SearchString" value="' . htmlspecialchars($SearchString, ENT_QUOTES, 'iso-8859-1') . '" type="hidden">' : '';
             if ($dvCode) {
                 $this->ContentType = 'detailview';
                 $dvShown = true;
             }
         }
     }
     // display multiple printable detail views
     if ($PrintDV) {
         $dvCode = '';
         $_POST['dvprint_x'] = $_GET['dvprint_x'] = $_REQUEST['dvprint_x'] = 1;
         // hidden vars
         foreach ($this->filterers as $filterer => $caption) {
             if ($_REQUEST['filterer_' . $filterer] != '') {
                 $this->HTML .= "<input name=\"filterer_{$filterer}\" value=\"" . htmlspecialchars($_REQUEST['filterer_' . $filterer], ENT_QUOTES, 'iso-8859-1') . "\" type=\"hidden\" />";
                 break;
                 // currently, only one filterer can be applied at a time
             }
         }
         // count selected records
         $selectedRecords = 0;
         if (is_array($_POST['record_selector'])) {
             foreach ($_POST['record_selector'] as $id) {
                 $selectedRecords++;
                 $this->HTML .= '<input type="hidden" name="record_selector[]" value="' . htmlspecialchars($id, ENT_QUOTES, 'iso-8859-1') . '">' . "\n";
             }
         }
         if ($selectedRecords && $selectedRecords <= datalist_max_records_dv_print) {
             // if records selected > {datalist_max_records_dv_print} don't show DV preview to avoid db performance issues.
             foreach ($_POST['record_selector'] as $id) {
                 $dvCode .= call_user_func($this->TableName . '_form', $id, 0, 0, 0, 1);
             }
             if ($dvCode != '') {
                 $dvCode = preg_replace('/<input .*?type="?image"?.*?>/', '', $dvCode);
                 $this->HTML .= $dvCode;
             }
         } else {
             $this->HTML .= error_message($Translation['Maximum records allowed to enable this feature is'] . ' ' . datalist_max_records_dv_print);
             $this->HTML .= '<input type="submit" class="print-button" value="' . $Translation['Print Preview Table View'] . '">';
         }
     }
     $this->HTML .= "</form>";
     $this->HTML .= '</div><div class="col-xs-1 md-hidden lg-hidden"></div></div>';
     // $this->HTML .= '<font face="garamond">'.htmlspecialchars($tvQuery).'</font>';  // uncomment this line for debugging the table view query
     if ($dvShown && $tvShown) {
         $this->ContentType = 'tableview+detailview';
     }
     if ($dvprint_x != '') {
         $this->ContentType = 'print-detailview';
     }
     if ($Print_x != '') {
         $this->ContentType = 'print-tableview';
     }
     if ($PrintDV != '') {
         $this->ContentType = 'print-detailview';
     }
     // call detail view javascript hook file if found
     $dvJSHooksFile = dirname(__FILE__) . '/hooks/' . $this->TableName . '-dv.js';
     if (is_file($dvJSHooksFile) && ($this->ContentType == 'detailview' || $this->ContentType == 'tableview+detailview')) {
         $this->HTML .= "\n<script src=\"hooks/{$this->TableName}-dv.js\"></script>\n";
     }
 }
Пример #8
0
function outcomes_form($selected_id = '', $AllowUpdate = 1, $AllowInsert = 1, $AllowDelete = 1, $ShowCancel = 0)
{
    // 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('outcomes');
    if (!$arrPerm[1] && $selected_id == '') {
        return '';
    }
    // print preview?
    $dvprint = false;
    if ($selected_id && $_REQUEST['dvprint_x'] != '') {
        $dvprint = true;
    }
    $filterer_outcome_area = thisOr(undo_magic_quotes($_REQUEST['filterer_outcome_area']), '');
    // populate filterers, starting from children to grand-parents
    // unique random identifier
    $rnd1 = $dvprint ? rand(1000000, 9999999) : '';
    // combobox: outcome_area
    $combo_outcome_area = new DataCombo();
    // combobox: strata
    $combo_strata = new Combo();
    $combo_strata->ListType = 0;
    $combo_strata->MultipleSeparator = ', ';
    $combo_strata->ListBoxHeight = 10;
    $combo_strata->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/outcomes.strata.csv')) {
        $strata_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/outcomes.strata.csv')));
        $combo_strata->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($strata_data)));
        $combo_strata->ListData = $combo_strata->ListItem;
    } else {
        $combo_strata->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Individuals;;Community, Sector & Society")));
        $combo_strata->ListData = $combo_strata->ListItem;
    }
    $combo_strata->SelectName = 'strata';
    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='outcomes' and pkValue='" . makeSafe($selected_id) . "'");
        $ownerMemberID = sqlValue("select lcase(memberID) from membership_userrecords where tableName='outcomes' 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 `outcomes` where `outcome_id`='" . makeSafe($selected_id) . "'", $eo);
        $row = mysql_fetch_array($res);
        $urow = $row;
        /* unsanitized data */
        $hc = new CI_Input();
        $row = $hc->xss_clean($row);
        /* sanitize data */
        $combo_outcome_area->SelectedData = $row['outcome_area'];
        $combo_strata->SelectedData = $row['strata'];
    } else {
        $combo_outcome_area->SelectedData = $filterer_outcome_area;
        $combo_strata->SelectedText = $_REQUEST['FilterField'][1] == '4' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "";
    }
    $combo_outcome_area->HTML = $combo_outcome_area->MatchText = '<span id="outcome_area-container' . $rnd1 . '"></span><input type="hidden" name="outcome_area" id="outcome_area' . $rnd1 . '">';
    $combo_strata->Render();
    ob_start();
    ?>

	<script>
		// initial lookup values
		var current_outcome_area__RAND__ = { text: "", value: "<?php 
    echo addslashes($selected_id ? $urow['outcome_area'] : $filterer_outcome_area);
    ?>
"};
		
		jQuery(function() {
			outcome_area_reload__RAND__();
		});
		function outcome_area_reload__RAND__(){
		<?php 
    if (($AllowUpdate || $AllowInsert) && !$dvprint) {
        ?>

			jQuery("#outcome_area-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					jQuery.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: current_outcome_area__RAND__.value, t: 'outcomes', f: 'outcome_area' }
					}).done(function(resp){
						c({
							id: resp.results[0].id,
							text: resp.results[0].text
						});
						jQuery('[name="outcome_area"]').val(resp.results[0].id);


						if(typeof(outcome_area_update_autofills__RAND__) == 'function') outcome_area_update_autofills__RAND__();
					});
				},
				width: '100%',
				formatNoMatches: function(term){ return '<?php 
        echo addslashes($Translation['No matches found!']);
        ?>
'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { s: term, p: page, t: 'outcomes', f: 'outcome_area' }; },
					results: function(resp, page){ return resp; }
				}
			}).on('change', function(e){
				current_outcome_area__RAND__.value = e.added.id;
				current_outcome_area__RAND__.text = e.added.text;
				jQuery('[name="outcome_area"]').val(e.added.id);


				if(typeof(outcome_area_update_autofills__RAND__) == 'function') outcome_area_update_autofills__RAND__();
			});
		<?php 
    } else {
        ?>

			jQuery.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: current_outcome_area__RAND__.value, t: 'outcomes', f: 'outcome_area' }
			}).done(function(resp){
				jQuery('#outcome_area-container__RAND__').html('<span id="outcome_area-match-text">' + resp.results[0].text + '</span>');

				if(typeof(outcome_area_update_autofills__RAND__) == 'function') outcome_area_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) {
        $templateCode = @file_get_contents('./templates/outcomes_templateDVP.html');
    } else {
        $templateCode = @file_get_contents('./templates/outcomes_templateDV.html');
    }
    // process form title
    $templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Outcome details', $templateCode);
    $templateCode = str_replace('<%%RND1%%>', $rnd1, $templateCode);
    // process buttons
    if ($arrPerm[1]) {
        // allow insert?
        if (!$selected_id) {
            $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-success" id="insert" name="insert_x" value="1" onclick="return outcomes_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save New'] . '</button>', $templateCode);
        }
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-default" id="insert" name="insert_x" value="1" onclick="return outcomes_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 = 'window.parent.jQuery(\'.modal\').modal(\'hide\'); return false;';
    } else {
        $backAction = '$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;';
    }
    if ($selected_id) {
        if (!$_REQUEST['Embedded']) {
            $templateCode = str_replace('<%%DVPRINT_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-default" id="dvprint" name="dvprint_x" value="1" onclick="$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;"><i class="glyphicon glyphicon-print"></i> ' . $Translation['Print Preview'] . '</button>', $templateCode);
        }
        if ($AllowUpdate) {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-success btn-lg" id="update" name="update_x" value="1" onclick="return outcomes_validateData();"><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 tabindex="2" type="submit" class="btn btn-danger" id="delete" name="delete_x" value="1" onclick="return confirm(\'' . $Translation['are you sure?'] . '\');"><i class="glyphicon glyphicon-trash"></i> ' . $Translation['Delete'] . '</button>', $templateCode);
        } else {
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        }
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><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 tabindex="2" type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><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 && !$arrPerm[1] || !$selected_id && !$arrPerm[1]) {
        $jsReadOnly .= "\tjQuery('#outcome_area').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#outcome_area_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
        $jsReadOnly .= "\tjQuery('#description').replaceWith('<p class=\"form-control-static\" id=\"description\">' + (jQuery('#description').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#strata').replaceWith('<p class=\"form-control-static\" id=\"strata\">' + (jQuery('#strata').val() || '') + '</p>'); jQuery('#strata-multi-selection-help').hide();\n";
        $noUploads = true;
    }
    // process combos
    $templateCode = str_replace('<%%COMBO(outcome_area)%%>', $combo_outcome_area->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(outcome_area)%%>', $combo_outcome_area->MatchText, $templateCode);
    $templateCode = str_replace('<%%URLCOMBOTEXT(outcome_area)%%>', urlencode($combo_outcome_area->MatchText), $templateCode);
    $templateCode = str_replace('<%%COMBO(strata)%%>', $combo_strata->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(strata)%%>', $combo_strata->SelectedData, $templateCode);
    // process foreign key links
    if ($selected_id) {
        $templateCode = str_replace('<%%PLINK(outcome_area)%%>', $combo_outcome_area->SelectedData ? "<span id=\"outcome_areas_plink1\" class=\"hidden\"><a class=\"btn btn-default\" href=\"outcome_areas_view.php?SelectedID=" . urlencode($combo_outcome_area->SelectedData) . "\"><i class=\"glyphicon glyphicon-search\"></i></a></span>" : '', $templateCode);
    }
    // process images
    $templateCode = str_replace('<%%UPLOADFILE(outcome_id)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(outcome_area)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(description)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(strata)%%>', '', $templateCode);
    // process values
    if ($selected_id) {
        $templateCode = str_replace('<%%VALUE(outcome_id)%%>', htmlspecialchars($row['outcome_id'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(outcome_id)%%>', urlencode($urow['outcome_id']), $templateCode);
        $templateCode = str_replace('<%%VALUE(outcome_area)%%>', htmlspecialchars($row['outcome_area'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(outcome_area)%%>', urlencode($urow['outcome_area']), $templateCode);
        if ($dvprint) {
            $templateCode = str_replace('<%%VALUE(description)%%>', nl2br(htmlspecialchars($row['description'], ENT_QUOTES)), $templateCode);
        } else {
            $templateCode = str_replace('<%%VALUE(description)%%>', htmlspecialchars($row['description'], ENT_QUOTES), $templateCode);
        }
        $templateCode = str_replace('<%%URLVALUE(description)%%>', urlencode($urow['description']), $templateCode);
        $templateCode = str_replace('<%%VALUE(strata)%%>', htmlspecialchars($row['strata'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(strata)%%>', urlencode($urow['strata']), $templateCode);
    } else {
        $templateCode = str_replace('<%%VALUE(outcome_id)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(outcome_id)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(outcome_area)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(outcome_area)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(description)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(description)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(strata)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(strata)%%>', urlencode(''), $templateCode);
    }
    // process translations
    foreach ($Translation as $symbol => $trans) {
        $templateCode = str_replace("<%%TRANSLATION({$symbol})%%>", $trans, $templateCode);
    }
    // clear scrap
    $templateCode = str_replace('<%%', '<!-- ', $templateCode);
    $templateCode = str_replace('%%>', ' -->', $templateCode);
    // hide links to inaccessible tables
    if ($_POST['dvprint_x'] == '') {
        $templateCode .= "\n\n<script>jQuery(function(){\n";
        $arrTables = getTableList();
        foreach ($arrTables as $name => $caption) {
            $templateCode .= "\tjQuery('#{$name}_link').removeClass('hidden');\n";
            $templateCode .= "\tjQuery('#xs_{$name}_link').removeClass('hidden');\n";
            $templateCode .= "\tjQuery('[id^=\"{$name}_plink\"]').removeClass('hidden');\n";
        }
        $templateCode .= $jsReadOnly;
        if (!$selected_id) {
        }
        $templateCode .= "\n});</script>\n";
    }
    // ajaxed auto-fill fields
    $templateCode .= "<script>";
    $templateCode .= "document.observe('dom:loaded', 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" rel="lightbox\\[.*?\\]"/', 'blank.gif"', $templateCode);
    // don't display empty email links
    $templateCode = preg_replace('/<a .*?href="mailto:".*?<\\/a>/', '', $templateCode);
    // hook: outcomes_dv
    if (function_exists('outcomes_dv')) {
        $args = array();
        outcomes_dv($selected_id ? $selected_id : FALSE, getMemberInfo(), $templateCode, $args);
    }
    return $templateCode;
}
function residence_and_rental_history_form($selected_id = '', $AllowUpdate = 1, $AllowInsert = 1, $AllowDelete = 1, $ShowCancel = 0)
{
    // 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('residence_and_rental_history');
    if (!$arrPerm[1] && $selected_id == '') {
        return '';
    }
    $AllowInsert = $arrPerm[1] ? true : false;
    // print preview?
    $dvprint = false;
    if ($selected_id && $_REQUEST['dvprint_x'] != '') {
        $dvprint = true;
    }
    $filterer_tenant = thisOr(undo_magic_quotes($_REQUEST['filterer_tenant']), '');
    // populate filterers, starting from children to grand-parents
    // unique random identifier
    $rnd1 = $dvprint ? rand(1000000, 9999999) : '';
    // combobox: tenant
    $combo_tenant = new DataCombo();
    // combobox: duration_of_residency_from
    $combo_duration_of_residency_from = new DateCombo();
    $combo_duration_of_residency_from->DateFormat = "mdy";
    $combo_duration_of_residency_from->MinYear = 1900;
    $combo_duration_of_residency_from->MaxYear = 2100;
    $combo_duration_of_residency_from->DefaultDate = parseMySQLDate('', '');
    $combo_duration_of_residency_from->MonthNames = $Translation['month names'];
    $combo_duration_of_residency_from->NamePrefix = 'duration_of_residency_from';
    // combobox: to
    $combo_to = new DateCombo();
    $combo_to->DateFormat = "mdy";
    $combo_to->MinYear = 1900;
    $combo_to->MaxYear = 2100;
    $combo_to->DefaultDate = parseMySQLDate('', '');
    $combo_to->MonthNames = $Translation['month names'];
    $combo_to->NamePrefix = 'to';
    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='residence_and_rental_history' and pkValue='" . makeSafe($selected_id) . "'");
        $ownerMemberID = sqlValue("select lcase(memberID) from membership_userrecords where tableName='residence_and_rental_history' 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 `residence_and_rental_history` where `id`='" . makeSafe($selected_id) . "'", $eo);
        if (!($row = db_fetch_array($res))) {
            return error_message($Translation['No records found']);
        }
        $urow = $row;
        /* unsanitized data */
        $hc = new CI_Input();
        $row = $hc->xss_clean($row);
        /* sanitize data */
        $combo_tenant->SelectedData = $row['tenant'];
        $combo_duration_of_residency_from->DefaultDate = $row['duration_of_residency_from'];
        $combo_to->DefaultDate = $row['to'];
    } else {
        $combo_tenant->SelectedData = $filterer_tenant;
    }
    $combo_tenant->HTML = '<span id="tenant-container' . $rnd1 . '"></span><input type="hidden" name="tenant" id="tenant' . $rnd1 . '">';
    $combo_tenant->MatchText = '<span id="tenant-container-readonly' . $rnd1 . '"></span><input type="hidden" name="tenant" id="tenant' . $rnd1 . '">';
    ob_start();
    ?>

	<script>
		// initial lookup values
		var current_tenant__RAND__ = { text: "", value: "<?php 
    echo addslashes($selected_id ? $urow['tenant'] : $filterer_tenant);
    ?>
"};

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

			jQuery("#tenant-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					jQuery.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: current_tenant__RAND__.value, t: 'residence_and_rental_history', f: 'tenant' }
					}).done(function(resp){
						c({
							id: resp.results[0].id,
							text: resp.results[0].text
						});
						jQuery('[name="tenant"]').val(resp.results[0].id);
						jQuery('[id=tenant-container-readonly__RAND__]').html('<span id="tenant-match-text">' + resp.results[0].text + '</span>');


						if(typeof(tenant_update_autofills__RAND__) == 'function') tenant_update_autofills__RAND__();
					});
				},
				width: '100%',
				formatNoMatches: function(term){ return '<?php 
        echo addslashes($Translation['No matches found!']);
        ?>
'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { s: term, p: page, t: 'residence_and_rental_history', f: 'tenant' }; },
					results: function(resp, page){ return resp; }
				}
			}).on('change', function(e){
				current_tenant__RAND__.value = e.added.id;
				current_tenant__RAND__.text = e.added.text;
				jQuery('[name="tenant"]').val(e.added.id);


				if(typeof(tenant_update_autofills__RAND__) == 'function') tenant_update_autofills__RAND__();
			});
		<?php 
    } else {
        ?>

			jQuery.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: current_tenant__RAND__.value, t: 'residence_and_rental_history', f: 'tenant' }
			}).done(function(resp){
				jQuery('[id=tenant-container__RAND__], [id=tenant-container-readonly__RAND__]').html('<span id="tenant-match-text">' + resp.results[0].text + '</span>');

				if(typeof(tenant_update_autofills__RAND__) == 'function') tenant_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) {
        $templateCode = @file_get_contents('./templates/residence_and_rental_history_templateDVP.html');
    } else {
        $templateCode = @file_get_contents('./templates/residence_and_rental_history_templateDV.html');
    }
    // process form title
    $templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Residence and rental history details', $templateCode);
    $templateCode = str_replace('<%%RND1%%>', $rnd1, $templateCode);
    $templateCode = str_replace('<%%EMBEDDED%%>', $_REQUEST['Embedded'] ? 'Embedded=1' : '', $templateCode);
    // process buttons
    if ($AllowInsert) {
        if (!$selected_id) {
            $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-success" id="insert" name="insert_x" value="1" onclick="return residence_and_rental_history_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 residence_and_rental_history_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 = 'window.parent.jQuery(\'.modal\').modal(\'hide\'); return false;';
    } else {
        $backAction = '$$(\'form\')[0].writeAttribute(\'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="$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;"><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 residence_and_rental_history_validateData();"><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?'] . '\');"><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 . '"><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 . '"><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('#tenant').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#tenant_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
        $jsReadOnly .= "\tjQuery('#address').replaceWith('<p class=\"form-control-static\" id=\"address\">' + (jQuery('#address').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#landlord_or_manager_name').replaceWith('<p class=\"form-control-static\" id=\"landlord_or_manager_name\">' + (jQuery('#landlord_or_manager_name').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#landlord_or_manager_phone').replaceWith('<p class=\"form-control-static\" id=\"landlord_or_manager_phone\">' + (jQuery('#landlord_or_manager_phone').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#monthly_rent').replaceWith('<p class=\"form-control-static\" id=\"monthly_rent\">' + (jQuery('#monthly_rent').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#duration_of_residency_from').prop('readonly', true);\n";
        $jsReadOnly .= "\tjQuery('#duration_of_residency_fromDay, #duration_of_residency_fromMonth, #duration_of_residency_fromYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#to').prop('readonly', true);\n";
        $jsReadOnly .= "\tjQuery('#toDay, #toMonth, #toYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#reason_for_leaving').replaceWith('<p class=\"form-control-static\" id=\"reason_for_leaving\">' + (jQuery('#reason_for_leaving').val() || '') + '</p>');\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(tenant)%%>', $combo_tenant->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(tenant)%%>', $combo_tenant->MatchText, $templateCode);
    $templateCode = str_replace('<%%URLCOMBOTEXT(tenant)%%>', urlencode($combo_tenant->MatchText), $templateCode);
    $templateCode = str_replace('<%%COMBO(duration_of_residency_from)%%>', $selected_id && !$arrPerm[3] ? '<p class="form-control-static">' . $combo_duration_of_residency_from->GetHTML(true) . '</p>' : $combo_duration_of_residency_from->GetHTML(), $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(duration_of_residency_from)%%>', $combo_duration_of_residency_from->GetHTML(true), $templateCode);
    $templateCode = str_replace('<%%COMBO(to)%%>', $selected_id && !$arrPerm[3] ? '<p class="form-control-static">' . $combo_to->GetHTML(true) . '</p>' : $combo_to->GetHTML(), $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(to)%%>', $combo_to->GetHTML(true), $templateCode);
    // process foreign key links
    if ($selected_id) {
        $templateCode = str_replace('<%%PLINK(tenant)%%>', $combo_tenant->SelectedData ? "<span id=\"applicants_and_tenants_plink1\" class=\"hidden\"><a class=\"btn btn-default\" href=\"applicants_and_tenants_view.php?SelectedID=" . urlencode($combo_tenant->SelectedData) . "\"><i class=\"glyphicon glyphicon-search\"></i></a></span>" : '', $templateCode);
    }
    // process images
    $templateCode = str_replace('<%%UPLOADFILE(id)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(tenant)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(address)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(landlord_or_manager_name)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(landlord_or_manager_phone)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(monthly_rent)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(duration_of_residency_from)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(to)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(reason_for_leaving)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(notes)%%>', '', $templateCode);
    // process values
    if ($selected_id) {
        $templateCode = str_replace('<%%VALUE(id)%%>', htmlspecialchars($row['id'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(id)%%>', urlencode($urow['id']), $templateCode);
        $templateCode = str_replace('<%%VALUE(tenant)%%>', htmlspecialchars($row['tenant'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(tenant)%%>', urlencode($urow['tenant']), $templateCode);
        $templateCode = str_replace('<%%VALUE(address)%%>', htmlspecialchars($row['address'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(address)%%>', urlencode($urow['address']), $templateCode);
        $templateCode = str_replace('<%%VALUE(landlord_or_manager_name)%%>', htmlspecialchars($row['landlord_or_manager_name'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(landlord_or_manager_name)%%>', urlencode($urow['landlord_or_manager_name']), $templateCode);
        $templateCode = str_replace('<%%VALUE(landlord_or_manager_phone)%%>', htmlspecialchars($row['landlord_or_manager_phone'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(landlord_or_manager_phone)%%>', urlencode($urow['landlord_or_manager_phone']), $templateCode);
        $templateCode = str_replace('<%%VALUE(monthly_rent)%%>', htmlspecialchars($row['monthly_rent'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(monthly_rent)%%>', urlencode($urow['monthly_rent']), $templateCode);
        $templateCode = str_replace('<%%VALUE(duration_of_residency_from)%%>', @date('m/d/Y', @strtotime(htmlspecialchars($row['duration_of_residency_from'], ENT_QUOTES))), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(duration_of_residency_from)%%>', urlencode(@date('m/d/Y', @strtotime(htmlspecialchars($urow['duration_of_residency_from'], ENT_QUOTES)))), $templateCode);
        $templateCode = str_replace('<%%VALUE(to)%%>', @date('m/d/Y', @strtotime(htmlspecialchars($row['to'], ENT_QUOTES))), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(to)%%>', urlencode(@date('m/d/Y', @strtotime(htmlspecialchars($urow['to'], ENT_QUOTES)))), $templateCode);
        $templateCode = str_replace('<%%VALUE(reason_for_leaving)%%>', htmlspecialchars($row['reason_for_leaving'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(reason_for_leaving)%%>', urlencode($urow['reason_for_leaving']), $templateCode);
        if ($AllowUpdate || $AllowInsert) {
            $templateCode = str_replace('<%%HTMLAREA(notes)%%>', '<textarea name="notes" id="notes" rows="5">' . htmlspecialchars($row['notes'], ENT_QUOTES) . '</textarea>', $templateCode);
        } else {
            $templateCode = str_replace('<%%HTMLAREA(notes)%%>', $row['notes'], $templateCode);
        }
        $templateCode = str_replace('<%%VALUE(notes)%%>', nl2br($row['notes']), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(notes)%%>', urlencode($urow['notes']), $templateCode);
    } else {
        $templateCode = str_replace('<%%VALUE(id)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(id)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(tenant)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(tenant)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(address)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(address)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(landlord_or_manager_name)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(landlord_or_manager_name)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(landlord_or_manager_phone)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(landlord_or_manager_phone)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(monthly_rent)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(monthly_rent)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(duration_of_residency_from)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(duration_of_residency_from)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(to)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(to)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(reason_for_leaving)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(reason_for_leaving)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%HTMLAREA(notes)%%>', '<textarea name="notes" id="notes" rows="5"></textarea>', $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 ($_POST['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 .= "\t\$j('[id^=\"{$name}_plink\"]').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" rel="lightbox\\[.*?\\]"/', 'blank.gif"', $templateCode);
    // don't display empty email links
    $templateCode = preg_replace('/<a .*?href="mailto:".*?<\\/a>/', '', $templateCode);
    // hook: residence_and_rental_history_dv
    if (function_exists('residence_and_rental_history_dv')) {
        $args = array();
        residence_and_rental_history_dv($selected_id ? $selected_id : FALSE, getMemberInfo(), $templateCode, $args);
    }
    return $templateCode;
}
function properties_form($selected_id = '', $AllowUpdate = 1, $AllowInsert = 1, $AllowDelete = 1, $ShowCancel = 0)
{
    // 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('properties');
    if (!$arrPerm[1] && $selected_id == '') {
        return '';
    }
    $AllowInsert = $arrPerm[1] ? true : false;
    // print preview?
    $dvprint = false;
    if ($selected_id && $_REQUEST['dvprint_x'] != '') {
        $dvprint = true;
    }
    $filterer_owner = thisOr(undo_magic_quotes($_REQUEST['filterer_owner']), '');
    // populate filterers, starting from children to grand-parents
    // unique random identifier
    $rnd1 = $dvprint ? rand(1000000, 9999999) : '';
    // combobox: type
    $combo_type = new Combo();
    $combo_type->ListType = 2;
    $combo_type->MultipleSeparator = ', ';
    $combo_type->ListBoxHeight = 10;
    $combo_type->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/properties.type.csv')) {
        $type_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/properties.type.csv')));
        $combo_type->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($type_data)));
        $combo_type->ListData = $combo_type->ListItem;
    } else {
        $combo_type->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Residential;;Commercial;;Condo/Townhome;;Multi-Family;;Single-Family;;stores;;office;;shops")));
        $combo_type->ListData = $combo_type->ListItem;
    }
    $combo_type->SelectName = 'type';
    $combo_type->AllowNull = false;
    // combobox: owner
    $combo_owner = new DataCombo();
    // combobox: operating_account
    $combo_operating_account = new Combo();
    $combo_operating_account->ListType = 0;
    $combo_operating_account->MultipleSeparator = ', ';
    $combo_operating_account->ListBoxHeight = 10;
    $combo_operating_account->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/properties.operating_account.csv')) {
        $operating_account_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/properties.operating_account.csv')));
        $combo_operating_account->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($operating_account_data)));
        $combo_operating_account->ListData = $combo_operating_account->ListItem;
    } else {
        $combo_operating_account->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Operating bank account;;Security deposit bank account")));
        $combo_operating_account->ListData = $combo_operating_account->ListItem;
    }
    $combo_operating_account->SelectName = 'operating_account';
    // combobox: country
    $combo_country = new Combo();
    $combo_country->ListType = 0;
    $combo_country->MultipleSeparator = ', ';
    $combo_country->ListBoxHeight = 10;
    $combo_country->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/properties.country.csv')) {
        $country_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/properties.country.csv')));
        $combo_country->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($country_data)));
        $combo_country->ListData = $combo_country->ListItem;
    } else {
        $combo_country->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Afghanistan;;Albania;;Algeria;;American Samoa;;Andorra;;Angola;;Anguilla;;Antarctica;;Antigua, Barbuda;;Argentina;;Armenia;;Aruba;;Australia;;Austria;;Azerbaijan;;Bahamas;;Bahrain;;Bangladesh;;Barbados;;Belarus;;Belgium;;Belize;;Benin;;Bermuda;;Bhutan;;Bolivia;;Bosnia, Herzegovina;;Botswana;;Bouvet Is.;;Brazil;;Brunei Darussalam;;Bulgaria;;Burkina Faso;;Burundi;;Cambodia;;Cameroon;;Canada;;Canary Is.;;Cape Verde;;Cayman Is.;;Central African Rep.;;Chad;;Channel Islands;;Chile;;China;;Christmas Is.;;Cocos Is.;;Colombia;;Comoros;;Congo, D.R. Of;;Congo;;Cook Is.;;Costa Rica;;Croatia;;Cuba;;Cyprus;;Czech Republic;;Denmark;;Djibouti;;Dominica;;Dominican Republic;;Ecuador;;Egypt;;El Salvador;;Equatorial Guinea;;Eritrea;;Estonia;;Ethiopia;;Falkland Is.;;Faroe Is.;;Fiji;;Finland;;France;;French Guiana;;French Polynesia;;French Territories;;Gabon;;Gambia;;Georgia;;Germany;;Ghana;;Gibraltar;;Greece;;Greenland;;Grenada;;Guadeloupe;;Guam;;Guatemala;;Guernsey;;Guinea-bissau;;Guinea;;Guyana;;Haiti;;Heard, Mcdonald Is.;;Honduras;;Hong Kong;;Hungary;;Iceland;;India;;Indonesia;;Iran;;Iraq;;Ireland;;Israel;;Italy;;Ivory Coast;;Jamaica;;Japan;;Jersey;;Jordan;;Kazakhstan;;Kenya;;Kiribati;;Korea, D.P.R Of;;Korea, Rep. Of;;Kuwait;;Kyrgyzstan;;Lao Peoples D.R.;;Latvia;;Lebanon;;Lesotho;;Liberia;;Libyan Arab Jamahiriya;;Liechtenstein;;Lithuania;;Luxembourg;;Macao;;Macedonia, F.Y.R Of;;Madagascar;;Malawi;;Malaysia;;Maldives;;Mali;;Malta;;Mariana Islands;;Marshall Islands;;Martinique;;Mauritania;;Mauritius;;Mayotte;;Mexico;;Micronesia;;Moldova;;Monaco;;Mongolia;;Montserrat;;Morocco;;Mozambique;;Myanmar;;Namibia;;Nauru;;Nepal;;Netherlands Antilles;;Netherlands;;New Caledonia;;New Zealand;;Nicaragua;;Niger;;Nigeria;;Niue;;Norfolk Island;;Norway;;Oman;;Pakistan;;Palau;;Palestinian Terr.;;Panama;;Papua New Guinea;;Paraguay;;Peru;;Philippines;;Pitcairn;;Poland;;Portugal;;Puerto Rico;;Qatar;;Reunion;;Romania;;Russian Federation;;Rwanda;;Samoa;;San Marino;;Sao Tome, Principe;;Saudi Arabia;;Senegal;;Seychelles;;Sierra Leone;;Singapore;;Slovakia;;Slovenia;;Solomon Is.;;Somalia;;South Africa;;South Georgia;;South Sandwich Is.;;Spain;;Sri Lanka;;St. Helena;;St. Kitts, Nevis;;St. Lucia;;St. Pierre, Miquelon;;St. Vincent, Grenadines;;Sudan;;Suriname;;Svalbard, Jan Mayen;;Swaziland;;Sweden;;Switzerland;;Syrian Arab Republic;;Taiwan;;Tajikistan;;Tanzania;;Thailand;;Timor-leste;;Togo;;Tokelau;;Tonga;;Trinidad, Tobago;;Tunisia;;Turkey;;Turkmenistan;;Turks, Caicoss;;Tuvalu;;Uganda;;Ukraine;;United Arab Emirates;;United Kingdom;;United States;;Uruguay;;Uzbekistan;;Vanuatu;;Vatican City;;Venezuela;;Viet Nam;;Virgin Is. British;;Virgin Is. U.S.;;Wallis, Futuna;;Western Sahara;;Yemen;;Yugoslavia;;Zambia;;Zimbabwe")));
        $combo_country->ListData = $combo_country->ListItem;
    }
    $combo_country->SelectName = 'country';
    // combobox: State
    $combo_State = new Combo();
    $combo_State->ListType = 0;
    $combo_State->MultipleSeparator = ', ';
    $combo_State->ListBoxHeight = 10;
    $combo_State->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/properties.State.csv')) {
        $State_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/properties.State.csv')));
        $combo_State->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($State_data)));
        $combo_State->ListData = $combo_State->ListItem;
    } else {
        $combo_State->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("AL;;AK;;AS;;AZ;;AR;;CA;;CO;;CT;;DE;;DC;;FM;;FL;;GA;;GU;;HI;;ID;;IL;;IN;;IA;;KS;;KY;;LA;;ME;;MH;;MD;;MA;;MI;;MN;;MS;;MO;;MT;;NE;;NV;;NH;;NJ;;NM;;NY;;NC;;ND;;MP;;OH;;OK;;OR;;PW;;PA;;PR;;RI;;SC;;SD;;TN;;TX;;UT;;VT;;VI;;VA;;WA;;WV;;WI;;WY")));
        $combo_State->ListData = $combo_State->ListItem;
    }
    $combo_State->SelectName = 'State';
    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='properties' and pkValue='" . makeSafe($selected_id) . "'");
        $ownerMemberID = sqlValue("select lcase(memberID) from membership_userrecords where tableName='properties' 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 `properties` where `id`='" . makeSafe($selected_id) . "'", $eo);
        if (!($row = db_fetch_array($res))) {
            return error_message($Translation['No records found']);
        }
        $urow = $row;
        /* unsanitized data */
        $hc = new CI_Input();
        $row = $hc->xss_clean($row);
        /* sanitize data */
        $combo_type->SelectedData = $row['type'];
        $combo_owner->SelectedData = $row['owner'];
        $combo_operating_account->SelectedData = $row['operating_account'];
        $combo_country->SelectedData = $row['country'];
        $combo_State->SelectedData = $row['State'];
    } else {
        $combo_type->SelectedText = $_REQUEST['FilterField'][1] == '3' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "";
        $combo_owner->SelectedData = $filterer_owner;
        $combo_operating_account->SelectedText = $_REQUEST['FilterField'][1] == '7' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "";
        $combo_country->SelectedText = $_REQUEST['FilterField'][1] == '10' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "";
        $combo_State->SelectedText = $_REQUEST['FilterField'][1] == '13' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "";
    }
    $combo_type->Render();
    $combo_owner->HTML = '<span id="owner-container' . $rnd1 . '"></span><input type="hidden" name="owner" id="owner' . $rnd1 . '">';
    $combo_owner->MatchText = '<span id="owner-container-readonly' . $rnd1 . '"></span><input type="hidden" name="owner" id="owner' . $rnd1 . '">';
    $combo_operating_account->Render();
    $combo_country->Render();
    $combo_State->Render();
    ob_start();
    ?>

	<script>
		// initial lookup values
		var current_owner__RAND__ = { text: "", value: "<?php 
    echo addslashes($selected_id ? $urow['owner'] : $filterer_owner);
    ?>
"};

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

			jQuery("#owner-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					jQuery.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: current_owner__RAND__.value, t: 'properties', f: 'owner' }
					}).done(function(resp){
						c({
							id: resp.results[0].id,
							text: resp.results[0].text
						});
						jQuery('[name="owner"]').val(resp.results[0].id);
						jQuery('[id=owner-container-readonly__RAND__]').html('<span id="owner-match-text">' + resp.results[0].text + '</span>');


						if(typeof(owner_update_autofills__RAND__) == 'function') owner_update_autofills__RAND__();
					});
				},
				width: '100%',
				formatNoMatches: function(term){ return '<?php 
        echo addslashes($Translation['No matches found!']);
        ?>
'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { s: term, p: page, t: 'properties', f: 'owner' }; },
					results: function(resp, page){ return resp; }
				}
			}).on('change', function(e){
				current_owner__RAND__.value = e.added.id;
				current_owner__RAND__.text = e.added.text;
				jQuery('[name="owner"]').val(e.added.id);


				if(typeof(owner_update_autofills__RAND__) == 'function') owner_update_autofills__RAND__();
			});
		<?php 
    } else {
        ?>

			jQuery.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: current_owner__RAND__.value, t: 'properties', f: 'owner' }
			}).done(function(resp){
				jQuery('[id=owner-container__RAND__], [id=owner-container-readonly__RAND__]').html('<span id="owner-match-text">' + resp.results[0].text + '</span>');

				if(typeof(owner_update_autofills__RAND__) == 'function') owner_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) {
        $templateCode = @file_get_contents('./templates/properties_templateDVP.html');
    } else {
        $templateCode = @file_get_contents('./templates/properties_templateDV.html');
    }
    // process form title
    $templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Property details', $templateCode);
    $templateCode = str_replace('<%%RND1%%>', $rnd1, $templateCode);
    $templateCode = str_replace('<%%EMBEDDED%%>', $_REQUEST['Embedded'] ? 'Embedded=1' : '', $templateCode);
    // process buttons
    if ($AllowInsert) {
        if (!$selected_id) {
            $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-success" id="insert" name="insert_x" value="1" onclick="return properties_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 properties_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 = 'window.parent.jQuery(\'.modal\').modal(\'hide\'); return false;';
    } else {
        $backAction = '$$(\'form\')[0].writeAttribute(\'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="$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;"><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 properties_validateData();"><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?'] . '\');"><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 . '"><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 . '"><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('#property_name').replaceWith('<p class=\"form-control-static\" id=\"property_name\">' + (jQuery('#property_name').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('input[name=type]').parent().html('<p class=\"form-control-static\">' + jQuery('input[name=type]:checked').next().text() + '</p>')\n";
        $jsReadOnly .= "\tjQuery('#number_of_units').replaceWith('<p class=\"form-control-static\" id=\"number_of_units\">' + (jQuery('#number_of_units').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#photo').replaceWith('<p class=\"form-control-static\" id=\"photo\">' + (jQuery('#photo').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#owner').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#owner_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
        $jsReadOnly .= "\tjQuery('#country').replaceWith('<p class=\"form-control-static\" id=\"country\">' + (jQuery('#country').val() || '') + '</p>'); jQuery('#country-multi-selection-help').hide();\n";
        $jsReadOnly .= "\tjQuery('#street').replaceWith('<p class=\"form-control-static\" id=\"street\">' + (jQuery('#street').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#City').replaceWith('<p class=\"form-control-static\" id=\"City\">' + (jQuery('#City').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#State').replaceWith('<p class=\"form-control-static\" id=\"State\">' + (jQuery('#State').val() || '') + '</p>'); jQuery('#State-multi-selection-help').hide();\n";
        $jsReadOnly .= "\tjQuery('#ZIP').replaceWith('<p class=\"form-control-static\" id=\"ZIP\">' + (jQuery('#ZIP').val() || '') + '</p>');\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(type)%%>', $combo_type->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(type)%%>', $combo_type->SelectedData, $templateCode);
    $templateCode = str_replace('<%%COMBO(owner)%%>', $combo_owner->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(owner)%%>', $combo_owner->MatchText, $templateCode);
    $templateCode = str_replace('<%%URLCOMBOTEXT(owner)%%>', urlencode($combo_owner->MatchText), $templateCode);
    $templateCode = str_replace('<%%COMBO(operating_account)%%>', $combo_operating_account->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(operating_account)%%>', $combo_operating_account->SelectedData, $templateCode);
    $templateCode = str_replace('<%%COMBO(country)%%>', $combo_country->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(country)%%>', $combo_country->SelectedData, $templateCode);
    $templateCode = str_replace('<%%COMBO(State)%%>', $combo_State->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(State)%%>', $combo_State->SelectedData, $templateCode);
    // process foreign key links
    if ($selected_id) {
        $templateCode = str_replace('<%%PLINK(owner)%%>', $combo_owner->SelectedData ? "<span id=\"rental_owners_plink1\" class=\"hidden\"><a class=\"btn btn-default\" href=\"rental_owners_view.php?SelectedID=" . urlencode($combo_owner->SelectedData) . "\"><i class=\"glyphicon glyphicon-search\"></i></a></span>" : '', $templateCode);
    }
    // process images
    $templateCode = str_replace('<%%UPLOADFILE(id)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(property_name)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(type)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(number_of_units)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(photo)%%>', $noUploads ? '' : '<br><input type=hidden name=MAX_FILE_SIZE value=1024000>' . $Translation['upload image'] . ' <input type="file" name="photo">', $templateCode);
    if ($AllowUpdate && $row['photo'] != '') {
        $templateCode = str_replace('<%%REMOVEFILE(photo)%%>', '<br><input type="checkbox" name="photo_remove" id="photo_remove" value="1"> <label for="photo_remove" style="color: red; font-weight: bold;">' . $Translation['remove image'] . '</label>', $templateCode);
    } else {
        $templateCode = str_replace('<%%REMOVEFILE(photo)%%>', '', $templateCode);
    }
    $templateCode = str_replace('<%%UPLOADFILE(owner)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(operating_account)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(property_reserve)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(lease_term)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(country)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(street)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(City)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(State)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(ZIP)%%>', '', $templateCode);
    // process values
    if ($selected_id) {
        $templateCode = str_replace('<%%VALUE(id)%%>', htmlspecialchars($row['id'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(id)%%>', urlencode($urow['id']), $templateCode);
        $templateCode = str_replace('<%%VALUE(property_name)%%>', htmlspecialchars($row['property_name'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(property_name)%%>', urlencode($urow['property_name']), $templateCode);
        $templateCode = str_replace('<%%VALUE(type)%%>', htmlspecialchars($row['type'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(type)%%>', urlencode($urow['type']), $templateCode);
        $templateCode = str_replace('<%%VALUE(number_of_units)%%>', htmlspecialchars($row['number_of_units'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(number_of_units)%%>', urlencode($urow['number_of_units']), $templateCode);
        $row['photo'] = $row['photo'] != '' ? $row['photo'] : 'blank.gif';
        $templateCode = str_replace('<%%VALUE(photo)%%>', htmlspecialchars($row['photo'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(photo)%%>', urlencode($urow['photo']), $templateCode);
        $templateCode = str_replace('<%%VALUE(owner)%%>', htmlspecialchars($row['owner'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(owner)%%>', urlencode($urow['owner']), $templateCode);
        $templateCode = str_replace('<%%VALUE(operating_account)%%>', htmlspecialchars($row['operating_account'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(operating_account)%%>', urlencode($urow['operating_account']), $templateCode);
        $templateCode = str_replace('<%%VALUE(property_reserve)%%>', htmlspecialchars($row['property_reserve'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(property_reserve)%%>', urlencode($urow['property_reserve']), $templateCode);
        $templateCode = str_replace('<%%VALUE(lease_term)%%>', htmlspecialchars($row['lease_term'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(lease_term)%%>', urlencode($urow['lease_term']), $templateCode);
        $templateCode = str_replace('<%%VALUE(country)%%>', htmlspecialchars($row['country'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(country)%%>', urlencode($urow['country']), $templateCode);
        $templateCode = str_replace('<%%VALUE(street)%%>', htmlspecialchars($row['street'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(street)%%>', urlencode($urow['street']), $templateCode);
        $templateCode = str_replace('<%%VALUE(City)%%>', htmlspecialchars($row['City'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(City)%%>', urlencode($urow['City']), $templateCode);
        $templateCode = str_replace('<%%VALUE(State)%%>', htmlspecialchars($row['State'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(State)%%>', urlencode($urow['State']), $templateCode);
        $templateCode = str_replace('<%%VALUE(ZIP)%%>', htmlspecialchars($row['ZIP'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(ZIP)%%>', urlencode($urow['ZIP']), $templateCode);
    } else {
        $templateCode = str_replace('<%%VALUE(id)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(id)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(property_name)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(property_name)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(type)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(type)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(number_of_units)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(number_of_units)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(photo)%%>', 'blank.gif', $templateCode);
        $templateCode = str_replace('<%%VALUE(owner)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(owner)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(operating_account)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(operating_account)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(property_reserve)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(property_reserve)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(lease_term)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(lease_term)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(country)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(country)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(street)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(street)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(City)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(City)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(State)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(State)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(ZIP)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(ZIP)%%>', urlencode(''), $templateCode);
    }
    // process translations
    foreach ($Translation as $symbol => $trans) {
        $templateCode = str_replace("<%%TRANSLATION({$symbol})%%>", $trans, $templateCode);
    }
    // clear scrap
    $templateCode = str_replace('<%%', '<!-- ', $templateCode);
    $templateCode = str_replace('%%>', ' -->', $templateCode);
    // hide links to inaccessible tables
    if ($_POST['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 .= "\t\$j('[id^=\"{$name}_plink\"]').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" rel="lightbox\\[.*?\\]"/', 'blank.gif"', $templateCode);
    // don't display empty email links
    $templateCode = preg_replace('/<a .*?href="mailto:".*?<\\/a>/', '', $templateCode);
    // hook: properties_dv
    if (function_exists('properties_dv')) {
        $args = array();
        properties_dv($selected_id ? $selected_id : FALSE, getMemberInfo(), $templateCode, $args);
    }
    return $templateCode;
}
 function Render()
 {
     // get post and get variables
     global $Translation;
     $FiltersPerGroup = 4;
     if ($_SERVER['REQUEST_METHOD'] == 'GET') {
         $SortField = $_GET["SortField"];
         $SortDirection = $_GET["SortDirection"];
         $FirstRecord = $_GET["FirstRecord"];
         $ScrollUp_y = $_GET["ScrollUp_y"];
         $ScrollDn_y = $_GET["ScrollDn_y"];
         $Previous_x = $_GET["Previous_x"];
         $Next_x = $_GET["Next_x"];
         $Filter_x = $_GET["Filter_x"];
         $SaveFilter_x = $_GET["SaveFilter_x"];
         $NoFilter_x = $_GET["NoFilter_x"];
         $CancelFilter = $_GET["CancelFilter"];
         $ApplyFilter = $_GET["ApplyFilter"];
         $Search_x = $_GET["Search_x"];
         $SearchString = get_magic_quotes_gpc() ? stripslashes($_GET['SearchString']) : $_GET['SearchString'];
         $CSV_x = $_GET["CSV_x"];
         $FilterAnd = $_GET["FilterAnd"];
         $FilterField = $_GET["FilterField"];
         $FilterOperator = $_GET["FilterOperator"];
         if (is_array($_GET['FilterValue'])) {
             foreach ($_GET['FilterValue'] as $fvi => $fv) {
                 $FilterValue[$fvi] = get_magic_quotes_gpc() ? stripslashes($fv) : $fv;
             }
         }
         $Print_x = $_GET["Print_x"];
         $SelectedID = get_magic_quotes_gpc() ? stripslashes($_GET['SelectedID']) : $_GET['SelectedID'];
         $insert_x = $_GET["insert_x"];
         $update_x = $_GET["update_x"];
         $delete_x = $_GET["delete_x"];
         $SkipChecks = $_GET['confirmed'];
         $deselect_x = $_GET["deselect_x"];
         $addNew_x = $_GET["addNew_x"];
         $dvprint_x = $_GET['dvprint_x'];
     } else {
         $SortField = $_POST["SortField"];
         $SortDirection = $_POST["SortDirection"];
         $FirstRecord = $_POST["FirstRecord"];
         $ScrollUp_y = $_POST["ScrollUp_y"];
         $ScrollDn_y = $_POST["ScrollDn_y"];
         $Previous_x = $_POST["Previous_x"];
         $Next_x = $_POST["Next_x"];
         $Filter_x = $_POST["Filter_x"];
         $SaveFilter_x = $_POST["SaveFilter_x"];
         $NoFilter_x = $_POST["NoFilter_x"];
         $CancelFilter = $_POST["CancelFilter"];
         $ApplyFilter = $_POST["ApplyFilter"];
         $Search_x = $_POST["Search_x"];
         $SearchString = get_magic_quotes_gpc() ? stripslashes($_POST['SearchString']) : $_POST['SearchString'];
         $CSV_x = $_POST["CSV_x"];
         $FilterAnd = $_POST['FilterAnd'];
         $FilterField = $_POST['FilterField'];
         $FilterOperator = $_POST['FilterOperator'];
         if (is_array($_POST['FilterValue'])) {
             foreach ($_POST['FilterValue'] as $fvi => $fv) {
                 $FilterValue[$fvi] = get_magic_quotes_gpc() ? stripslashes($fv) : $fv;
             }
         }
         $Print_x = $_POST['Print_x'];
         $PrintTV = $_POST['PrintTV'];
         $PrintDV = $_POST['PrintDV'];
         $SelectedID = get_magic_quotes_gpc() ? stripslashes($_POST['SelectedID']) : $_POST['SelectedID'];
         $insert_x = $_POST['insert_x'];
         $update_x = $_POST['update_x'];
         $delete_x = $_POST['delete_x'];
         $SkipChecks = $_POST['confirmed'];
         $deselect_x = $_POST['deselect_x'];
         $addNew_x = $_POST['addNew_x'];
         $dvprint_x = $_POST['dvprint_x'];
     }
     // insure authenticity of user inputs:
     if (!$this->AllowDelete) {
         $delete_x = "";
     }
     if (!$this->AllowDeleteOfParents) {
         $SkipChecks = "";
     }
     if (!$this->AllowInsert) {
         $insert_x = "";
         $addNew_x = "";
     }
     if (!$this->AllowUpdate) {
         $update_x = "";
     }
     if (!$this->AllowFilters) {
         $Filter_x = "";
     }
     if (!$this->AllowPrinting) {
         $Print_x = '';
         $PrintDV = '';
         $PrintTV = '';
     }
     if (!$this->AllowPrintingMultiSelection) {
         $PrintDV = '';
         $PrintTV = '';
     }
     if (!$this->QuickSearch) {
         $SearchString = "";
     }
     if (!$this->AllowCSV) {
         $CSV_x = "";
     }
     // enforce record selection if user has edit/delete permissions on the current table
     $AllowPrintDV = 1;
     $this->Permissions = getTablePermissions($this->TableName);
     if ($this->Permissions[3] || $this->Permissions[4]) {
         // current user can edit or delete?
         $this->AllowSelection = 1;
     } elseif (!$this->AllowSelection) {
         $SelectedID = '';
         $AllowPrintDV = 0;
         $PrintDV = '';
     }
     if (!$this->AllowSelection || !$SelectedID) {
         $dvprint_x = '';
     }
     $this->QueryFieldsIndexed = reIndex($this->QueryFieldsFilters);
     $this->HTML .= '<form method="post" name="myform" action="' . $this->ScriptFileName . '">';
     $this->HTML .= '<input type="submit" style="position: absolute; left: 0px; top: -100px;" onclick="return false;">';
     $this->ContentType = 'tableview';
     // default content type
     // handle user commands ...
     if ($PrintTV != '') {
         $Print_x = 1;
         $_POST['Print_x'] = 1;
     }
     if ($deselect_x != '') {
         $SelectedID = '';
         $this->showTV();
     } elseif ($insert_x != '') {
         $SelectedID = call_user_func($this->TableName . '_insert');
         // redirect to a safe url to avoid refreshing and thus
         // insertion of duplicate records.
         // compose filters and sorting
         for ($i = 1; $i <= 20 * $FiltersPerGroup; $i++) {
             // Number of filters allowed
             if ($FilterField[$i] != "" && $FilterOperator[$i] != "" && ($FilterValue[$i] != "" || strstr($FilterOperator[$i], 'Empty'))) {
                 $filtersGET .= "&FilterAnd[{$i}]={$FilterAnd[$i]}&FilterField[{$i}]={$FilterField[$i]}&FilterOperator[{$i}]={$FilterOperator[$i]}&FilterValue[{$i}]=" . urlencode($FilterValue[$i]);
             }
         }
         $filtersGET .= "&SortField={$SortField}&SortDirection={$SortDirection}&FirstRecord={$FirstRecord}";
         $filtersGET = substr($filtersGET, 1);
         // remove initial &
         if ($this->RedirectAfterInsert != "") {
             if (strpos($this->RedirectAfterInsert, '?')) {
                 $this->RedirectAfterInsert .= '&record-added-ok=' . rand();
             } else {
                 $this->RedirectAfterInsert .= '?record-added-ok=' . rand();
             }
             if (strpos($this->RedirectAfterInsert, $this->ScriptFileName) !== false) {
                 $this->RedirectAfterInsert .= '&' . $filtersGET;
             }
             $this->HTML .= "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"0;url=" . str_replace("#ID#", urlencode($SelectedID), $this->RedirectAfterInsert) . "\">";
             return;
         } else {
             $this->HTML .= '<META HTTP-EQUIV="Refresh" CONTENT="0;url=' . $this->ScriptFileName . '?SelectedID=' . urlencode($SelectedID) . '&' . $filtersGET . '">';
             return;
         }
     } elseif ($delete_x != "") {
         $d = call_user_func($this->TableName . '_delete', $SelectedID, $this->AllowDeleteOfParents, $SkipChecks);
         if ($d) {
             $this->HTML .= "<div class=Error>" . $Translation['error:'] . " {$d}</div>";
         } else {
             $SelectedID = "";
             $this->showTV();
         }
     } elseif ($update_x != "") {
         call_user_func($this->TableName . '_update', $SelectedID);
         // compose filters and sorting
         for ($i = 1; $i <= 20 * $FiltersPerGroup; $i++) {
             // Number of filters allowed
             if ($FilterField[$i] != "" && $FilterOperator[$i] != "" && ($FilterValue[$i] != "" || strstr($FilterOperator[$i], 'Empty'))) {
                 $filtersGET .= "&FilterAnd[{$i}]={$FilterAnd[$i]}&FilterField[{$i}]={$FilterField[$i]}&FilterOperator[{$i}]={$FilterOperator[$i]}&FilterValue[{$i}]=" . urlencode($FilterValue[$i]);
             }
         }
         $filtersGET .= "&SortField={$SortField}&SortDirection={$SortDirection}&FirstRecord={$FirstRecord}";
         $filtersGET = substr($filtersGET, 1);
         // remove initial &
         $this->HTML .= '<META HTTP-EQUIV="Refresh" CONTENT="0;url=' . $this->ScriptFileName . '?SelectedID=' . urlencode($SelectedID) . '&' . $filtersGET . '&record-updated-ok=' . rand() . '">';
         return;
     } elseif ($addNew_x != "") {
         $SelectedID = '';
         $this->hideTV();
     } elseif ($Print_x != "") {
         // print code here ....
         $this->AllowNavigation = 0;
         $this->AllowSelection = 0;
     } elseif ($SaveFilter_x != "" && $this->AllowSavingFilters) {
         $this->HTML .= "<table width=550 border=0 align=center><tr><td class=TableTitle>" . $Translation["saved filters title"] . "</td></tr>";
         $this->HTML .= "\n\t<tr><td class=TableHeader>" . $Translation["saved filters instructions"] . "</td></tr>";
         $this->HTML .= "\n\t<tr><td class=TableHeader><textarea cols=60 rows=12 wrap=off>";
         $SourceCode = "<html><body>\n";
         $SourceCode .= '<form method="post" action="' . $_SERVER['HTTP_REFERER'] . '">' . "\n";
         for ($i = 1; $i <= 20 * $FiltersPerGroup; $i++) {
             // Number of filters allowed
             if ($i % $FiltersPerGroup == 1 && $i != 1 && $FilterAnd[$i] != "") {
                 $SourceCode .= "\t<input name=FilterAnd[{$i}] value='{$FilterAnd[$i]}' type=hidden>\n";
             }
             if ($FilterField[$i] != "" && $FilterOperator[$i] != "" && ($FilterValue[$i] != "" || strstr($FilterOperator[$i], 'Empty'))) {
                 if (!strstr($SourceCode, "\t<input name=FilterAnd[{$i}] value=")) {
                     $SourceCode .= "\t<input name=FilterAnd[{$i}] value='{$FilterAnd[$i]}' type=hidden>\n";
                 }
                 $SourceCode .= "\t<input name=FilterField[{$i}] value='{$FilterField[$i]}' type=hidden>\n";
                 $SourceCode .= "\t<input name=FilterOperator[{$i}] value='{$FilterOperator[$i]}' type=hidden>\n";
                 $SourceCode .= "\t<input name=FilterValue[{$i}] value='" . htmlspecialchars($FilterValue[$i], ENT_QUOTES) . "' type=hidden>\n\n";
             }
         }
         $SourceCode .= "\n\t<input type=submit value=\"Show Filtered Data\">\n";
         $SourceCode .= "</form>\n</body></html>";
         $this->HTML .= $SourceCode;
         $this->HTML .= "</textarea>";
         $this->HTML .= "<br /><input type=submit value=\"" . $Translation["hide code"] . "\">";
         $this->HTML .= "\n\t</table>\n\n";
     } elseif ($Filter_x != "") {
         if ($this->FilterPage != "") {
             ob_start();
             @(include $this->FilterPage);
             $out = ob_get_contents();
             ob_end_clean();
             $this->HTML .= $out;
         } else {
             // filter page code here .....
             $this->HTML .= '<table border="0" align="center"><tr><td colspan="4" class="TableTitle">' . $this->TableTitle . " " . $Translation['filters'] . "</td></tr>";
             $this->HTML .= "\n\t<tr><td class=\"TableHeader\"></td><td class=\"TableHeader\">" . $Translation['filtered field'] . '</td><td class="TableHeader">' . $Translation['comparison operator'] . '</td><td class="TableHeader">' . $Translation['comparison value'] . '</td></tr>';
             $this->HTML .= "\n\t<tr><td colspan=\"4\" class=\"TableHeader\"></td></tr>";
             for ($i = 1; $i <= 3 * $FiltersPerGroup; $i++) {
                 // Number of filters allowed
                 $fields = "";
                 $operators = "";
                 if ($i % $FiltersPerGroup == 1 && $i != 1) {
                     $this->HTML .= "\n\t<tr><td colspan=4 class=TableHeader></td></tr>";
                     $this->HTML .= "\n\t<tr><td colspan=4 align=center>";
                     $seland = new Combo();
                     $seland->ListItem = array($Translation["or"], $Translation["and"]);
                     $seland->ListData = array("or", "and");
                     $seland->SelectName = "FilterAnd[{$i}]";
                     $seland->SelectedData = $FilterAnd[$i];
                     $seland->Render();
                     $this->HTML .= $seland->HTML . "</td></tr>";
                     $this->HTML .= "\n\t<tr><td colspan=4 class=TableHeader></td></tr>";
                 }
                 $this->HTML .= "\n\t<tr><td class=TableHeader style='text-align:left;'>&nbsp;" . $Translation["filter"] . sprintf("%02d", $i) . " ";
                 // And, Or select
                 if ($i % $FiltersPerGroup != 1) {
                     $seland = new Combo();
                     $seland->ListItem = array($Translation["and"], $Translation["or"]);
                     $seland->ListData = array("and", "or");
                     $seland->SelectName = "FilterAnd[{$i}]";
                     $seland->SelectedData = $FilterAnd[$i];
                     $seland->Render();
                     $this->HTML .= $seland->HTML . "</td>";
                 } else {
                     $this->HTML .= "</td>";
                 }
                 // Fields list
                 $selfields = new Combo();
                 $selfields->SelectName = "FilterField[{$i}]";
                 $selfields->SelectedData = $FilterField[$i];
                 $selfields->ListItem = array_values($this->QueryFieldsFilters);
                 $selfields->ListData = array_keys($this->QueryFieldsIndexed);
                 $selfields->Render();
                 $this->HTML .= "\n\t\t<td>{$selfields->HTML}</td>";
                 // Operators list
                 $selop = new Combo();
                 $selop->ListItem = array($Translation["equal to"], $Translation["not equal to"], $Translation["greater than"], $Translation["greater than or equal to"], $Translation["less than"], $Translation["less than or equal to"], $Translation["like"], $Translation["not like"], $Translation["is empty"], $Translation["is not empty"]);
                 $selop->ListData = array("<=>", "!=", ">", ">=", "<", "<=", "like", "not like", "isEmpty", "isNotEmpty");
                 $selop->SelectName = "FilterOperator[{$i}]";
                 $selop->SelectedData = $FilterOperator[$i];
                 $selop->Render();
                 $this->HTML .= "\n\t\t<td>{$selop->HTML}</td>";
                 // Comparison expression
                 $this->HTML .= "\n\t\t<td><input size=25 type=text name=FilterValue[{$i}] value=\"" . htmlspecialchars($FilterValue[$i], ENT_QUOTES) . "\" class=TextBox></td></tr>";
                 if (!$i % $FiltersPerGroup) {
                     $this->HTML .= "\n\t<tr><td colspan=4 class=TableHeader></td></tr>";
                 }
             }
             $this->HTML .= "\n\t<tr><td colspan=4 class=TableHeader></td></tr>";
             $this->HTML .= "\n\t<tr><td colspan=4 align=right><input type=image src=applyFilters.gif alt='" . $Translation["apply filters"] . "'>" . ($this->AllowSavingFilters ? " &nbsp; <input type=image src=save_search.gif alt='" . $Translation["save filters"] . "' name=SaveFilter>" : "") . "</td></tr>";
             $this->HTML .= "\n</table>";
         }
         // hidden variables ....
         $this->HTML .= "<input name=SortField value='" . (is_numeric($SortField) ? $SortField : $SortFieldNumeric) . "' type=hidden>";
         $this->HTML .= "<input name=SortDirection type=hidden value='{$SortDirection}'>";
         $this->HTML .= "<input name=FirstRecord type=hidden value='1'>";
         $this->ContentType = 'filters';
         return;
     } elseif ($NoFilter_x != "") {
         // clear all filters ...
         for ($i = 1; $i <= 20 * $FiltersPerGroup; $i++) {
             // Number of filters allowed
             $FilterField[$i] = "";
             $FilterOperator[$i] = "";
             $FilterValue[$i] = "";
         }
         $SearchString = "";
     } elseif ($SelectedID) {
         $this->hideTV();
     }
     if ($SearchString != '') {
         if ($Search_x != '') {
             $FirstRecord = 1;
         }
         if ($this->QueryWhere == '') {
             $this->QueryWhere = "where ";
         } else {
             $this->QueryWhere .= " and ";
         }
         foreach ($this->QueryFieldsQS as $fName => $fCaption) {
             if (strpos($fName, '<img') === False) {
                 $this->QuerySearchableFields[$fName] = $fCaption;
             }
         }
         $this->QueryWhere .= '(' . implode(" LIKE '%" . makeSafe($SearchString) . "%' or ", array_keys($this->QuerySearchableFields)) . " LIKE '%" . makeSafe($SearchString) . "%')";
     }
     // set query filters
     $QueryHasWhere = 0;
     if (strpos($this->QueryWhere, 'where ') !== FALSE) {
         $QueryHasWhere = 1;
     }
     $WhereNeedsClosing = 0;
     for ($i = 1; $i <= 20 * $FiltersPerGroup; $i += $FiltersPerGroup) {
         // Number of filters allowed
         // test current filter group
         $GroupHasFilters = 0;
         for ($j = 0; $j < $FiltersPerGroup; $j++) {
             if ($FilterField[$i + $j] != "" && $FilterOperator[$i + $j] != "" && ($FilterValue[$i + $j] != "" || strstr($FilterOperator[$i + $j], 'Empty'))) {
                 $GroupHasFilters = 1;
                 break;
             }
         }
         if ($GroupHasFilters) {
             if (!stristr($this->QueryWhere, "where ")) {
                 $this->QueryWhere = "where (";
             } elseif ($QueryHasWhere) {
                 $this->QueryWhere .= " and (";
                 $QueryHasWhere = 0;
             }
             $this->QueryWhere .= " <FilterGroup> " . $FilterAnd[$i] . " (";
             for ($j = 0; $j < $FiltersPerGroup; $j++) {
                 if ($FilterField[$i + $j] != "" && $FilterOperator[$i + $j] != "" && ($FilterValue[$i + $j] != "" || strstr($FilterOperator[$i + $j], 'Empty'))) {
                     if ($FilterAnd[$i + $j] == '') {
                         $FilterAnd[$i + $j] = 'and';
                     }
                     // test for date/time fields
                     $tries = 0;
                     $isDateTime = FALSE;
                     $isDate = FALSE;
                     $fieldName = str_replace('`', '', $this->QueryFieldsIndexed[$FilterField[$i + $j]]);
                     list($tn, $fn) = explode('.', $fieldName);
                     while (!($res = sql("show columns from `{$tn}` like '{$fn}'")) && $tries < 2) {
                         $tn = substr($tn, 0, -1);
                         $tries++;
                     }
                     if ($row = @mysql_fetch_array($res)) {
                         if ($row['Type'] == 'date' || $row['Type'] == 'time') {
                             $isDateTime = TRUE;
                             if ($row['Type'] == 'date') {
                                 $isDate = True;
                             }
                         }
                     }
                     // end of test
                     if ($FilterOperator[$i + $j] == 'isEmpty' && !$isDateTime) {
                         $this->QueryWhere .= " <FilterItem> " . $FilterAnd[$i + $j] . " (" . $this->QueryFieldsIndexed[$FilterField[$i + $j]] . "='' or " . $this->QueryFieldsIndexed[$FilterField[$i + $j]] . " is NULL) </FilterItem>";
                     } elseif ($FilterOperator[$i + $j] == 'isNotEmpty' && !$isDateTime) {
                         $this->QueryWhere .= " <FilterItem> " . $FilterAnd[$i + $j] . " " . $this->QueryFieldsIndexed[$FilterField[$i + $j]] . "!='' </FilterItem>";
                     } elseif ($FilterOperator[$i + $j] == 'isEmpty' && $isDateTime) {
                         $this->QueryWhere .= " <FilterItem> " . $FilterAnd[$i + $j] . " (" . $this->QueryFieldsIndexed[$FilterField[$i + $j]] . "=0 or " . $this->QueryFieldsIndexed[$FilterField[$i + $j]] . " is NULL) </FilterItem>";
                     } elseif ($FilterOperator[$i + $j] == 'isNotEmpty' && $isDateTime) {
                         $this->QueryWhere .= " <FilterItem> " . $FilterAnd[$i + $j] . " " . $this->QueryFieldsIndexed[$FilterField[$i + $j]] . "!=0 </FilterItem>";
                     } elseif ($FilterOperator[$i + $j] == 'like' && !strstr($FilterValue[$i + $j], "%") && !strstr($FilterValue[$i + $j], "_")) {
                         $this->QueryWhere .= " <FilterItem> " . $FilterAnd[$i + $j] . " " . $this->QueryFieldsIndexed[$FilterField[$i + $j]] . " " . $FilterOperator[$i + $j] . " '%" . makeSafe($FilterValue[$i + $j]) . "%' </FilterItem>";
                     } elseif ($FilterOperator[$i + $j] == 'not like' && !strstr($FilterValue[$i + $j], "%") && !strstr($FilterValue[$i + $j], "_")) {
                         $this->QueryWhere .= " <FilterItem> " . $FilterAnd[$i + $j] . " " . $this->QueryFieldsIndexed[$FilterField[$i + $j]] . " " . $FilterOperator[$i + $j] . " '%" . makeSafe($FilterValue[$i + $j]) . "%' </FilterItem>";
                     } elseif ($isDate) {
                         $dateValue = toMySQLDate($FilterValue[$i + $j]);
                         $this->QueryWhere .= " <FilterItem> " . $FilterAnd[$i + $j] . " " . $this->QueryFieldsIndexed[$FilterField[$i + $j]] . " " . $FilterOperator[$i + $j] . " '{$dateValue}' </FilterItem>";
                     } else {
                         $this->QueryWhere .= " <FilterItem> " . $FilterAnd[$i + $j] . " " . $this->QueryFieldsIndexed[$FilterField[$i + $j]] . " " . $FilterOperator[$i + $j] . " '" . makeSafe($FilterValue[$i + $j]) . "' </FilterItem>";
                     }
                 }
             }
             $this->QueryWhere .= ") </FilterGroup>";
             $WhereNeedsClosing = 1;
         }
     }
     if ($WhereNeedsClosing) {
         $this->QueryWhere .= ")";
     }
     // set query sort
     if (!stristr($this->QueryOrder, "order by ") && $SortField != "" && $this->AllowSorting) {
         $this->QueryOrder = "order by {$SortField} {$SortDirection}";
     }
     // clean up query
     $this->QueryWhere = str_replace("( <FilterGroup> and ", "( ", $this->QueryWhere);
     $this->QueryWhere = str_replace("( <FilterGroup> or ", "( ", $this->QueryWhere);
     $this->QueryWhere = str_replace("( <FilterItem> and ", "( ", $this->QueryWhere);
     $this->QueryWhere = str_replace("( <FilterItem> or ", "( ", $this->QueryWhere);
     $this->QueryWhere = str_replace("<FilterGroup>", "", $this->QueryWhere);
     $this->QueryWhere = str_replace("</FilterGroup>", "", $this->QueryWhere);
     $this->QueryWhere = str_replace("<FilterItem>", "", $this->QueryWhere);
     $this->QueryWhere = str_replace("</FilterItem>", "", $this->QueryWhere);
     // if no 'order by' clause found, apply default sorting if specified
     if ($this->DefaultSortField != "" && $this->QueryOrder == '') {
         $this->QueryOrder = "order by " . $this->DefaultSortField . " " . $this->DefaultSortDirection;
     }
     // get count of matching records ...
     $TempQuery = 'SELECT count(1) from ' . $this->QueryFrom . ' ' . $this->QueryWhere;
     $RecordCount = sqlValue($TempQuery);
     $FieldCountTV = count($this->QueryFieldsTV);
     $FieldCountCSV = count($this->QueryFieldsCSV);
     $FieldCountFilters = count($this->QueryFieldsFilters);
     if (!$RecordCount) {
         $FirstRecord = 1;
     }
     // disable multi-selection if too many records to avoid browser performance issues
     if ($RecordCount > 1000) {
         $this->AllowPrintingMultiSelection = 0;
     }
     // Output CSV on request
     if ($CSV_x != '') {
         $this->HTML = '';
         // execute query for CSV output
         $fieldList = '';
         foreach ($this->QueryFieldsCSV as $fn => $fc) {
             $fieldList .= "{$fn} as `{$fc}`, ";
         }
         $fieldList = substr($fieldList, 0, -2);
         $csvQuery = 'SELECT ' . $fieldList . ' from ' . $this->QueryFrom . ' ' . $this->QueryWhere . ' ' . $this->QueryOrder;
         // hook: table_csv
         if (function_exists($this->TableName . '_csv')) {
             $args = array();
             $mq = call_user_func($this->TableName . '_csv', $csvQuery, getMemberInfo(), $args);
             $csvQuery = $mq ? $mq : $csvQuery;
         }
         $result = sql($csvQuery);
         // output CSV field names
         for ($i = 0; $i < $FieldCountCSV; $i++) {
             $this->HTML .= "\"" . mysql_field_name($result, $i) . "\"" . $this->CSVSeparator;
         }
         $this->HTML .= "\n\n";
         // output CSV data
         while ($row = mysql_fetch_row($result)) {
             for ($i = 0; $i < $FieldCountCSV; $i++) {
                 $this->HTML .= "\"" . str_replace(array("\r\n", "\r", "\n", '"'), array(' ', ' ', ' ', '""'), $row[$i]) . "\"" . $this->CSVSeparator;
             }
             $this->HTML .= "\n\n";
         }
         $this->HTML = str_replace($this->CSVSeparator . "\n\n", "\n", $this->HTML);
         $this->HTML = substr($this->HTML, 0, strlen($this->HTML) - 1);
         // clean any output buffers
         while (@ob_end_clean()) {
         }
         // output CSV HTTP headers ...
         header('HTTP/1.1 200 OK');
         header('Date: ' . @date("D M j G:i:s T Y"));
         header('Last-Modified: ' . @date("D M j G:i:s T Y"));
         header("Content-Type: application/force-download");
         header("Content-Lenght: " . (string) strlen($this->HTML));
         header("Content-Transfer-Encoding: Binary");
         header("Content-Disposition: attachment; filename={$this->TableName}.csv");
         // send output and quit script
         echo $this->HTML;
         exit;
     }
     $t = time();
     // just a random number for any purpose ...
     //$this->HTML .= "<font face=garamond>".$this->Query."</font>";  // uncomment this line for debugging
     // should SelectedID be reset on clicking TV buttons?
     $resetSelection = $this->SeparateDV ? "document.myform.SelectedID.value=''; " : '';
     // begin table and display table title
     $this->HTML .= "<table align=center cellspacing=1 cellpadding=0 border=0><tr>\n";
     $this->HTML .= "<td colspan=" . ($FieldCountTV + 2) . ">";
     $sum_width = 0;
     for ($i = 0; $i < count($this->ColWidth); $i++) {
         $sum_width += $this->ColWidth[$i];
     }
     $this->HTML .= "<table" . ($this->HideTableView ? "" : " width=100%") . " cellspacing=0 cellpadding=0 border=0>" . ($dvprint_x && $this->AllowSelection && $SelectedID ? '' : "<tr><td align=left colspan=2><div class=TableTitle>{$this->TableTitle}</div><br /></td></tr>");
     if (!$this->HideTableView && !($dvprint_x && $this->AllowSelection && $SelectedID) && !$PrintDV) {
         $this->HTML .= "<tr>";
         // display tables navigator menu
         if ($Print_x == '') {
             $this->HTML .= "<td align=left>" . NavMenus() . "</td>";
         } else {
             $this->HTML .= "\n<style type=\"text/css\">@media print{.displayOnly {display: none;}}</style>\n";
             if ($this->AllowPrintingMultiSelection) {
                 $withSelected = '' . '<input class="print-button" type="button" id="selectAll" value="' . $Translation['Select all records'] . '" onClick="$(\'toggleAll\').checked=!$(\'toggleAll\').checked; toggleAllRecords();">' . '<span id="withSelected">' . '<input class="print-button" type="submit" name="PrintTV" value="' . $Translation['Print Preview Table View'] . '">' . ($AllowPrintDV ? '<input id="PrintDV" class="print-button" type="submit" name="PrintDV" value="' . $Translation['Print Preview Detail View'] . '">' : '') . '<input class="print-button" type="submit" name="Print_x" value="' . $Translation['Cancel Selection'] . '">' . ' &nbsp;</span>' . '<script>' . 'var countSelected=0; ' . 'document.observe(\'dom:loaded\', function(){ ' . 'setInterval("' . '$(\'withSelected\').style.display=(countSelected ? \'inline\' : \'none\');' . '", 500); ' . '});' . '</script>';
             }
             $this->HTML .= "\n" . '<td colspan="2" class="displayOnly" style="min-width: 65em;"><div>' . '<input class="print-button" type="submit" value="' . $Translation['Cancel Printing'] . '">' . '<input class="print-button" type="button" id="sendToPrinter" value="' . $Translation['Print'] . '" onClick="window.print();">' . $withSelected . '</div></td>' . "\n";
         }
         // display quick search box
         if ($this->QuickSearch > 0 && $this->QuickSearch < 4 && $Print_x == '') {
             if ($this->QuickSearch == 1 || $this->QuickSearch == 2) {
                 $this->HTML .= '</tr><tr>';
             }
             $this->HTML .= "<td><div class=TableBodySelected style='text-align:" . ($this->QuickSearch == 1 ? "left" : ($this->QuickSearch == 2 ? "center" : "right")) . ";'>";
             $this->HTML .= "<nobr><b>" . $this->QuickSearchText . "</b> <input type=text name=SearchString value='" . htmlspecialchars($SearchString, ENT_QUOTES) . "' size=15 class=TextBox>";
             $this->HTML .= "<input onClick=\"{$resetSelection} document.myform.NoDV.value=1;\" align=top border=0 name=Search type=image vspace=2 hspace=2 src=qsearch.gif alt='" . $this->QuickSearchText . "'>";
             $this->HTML .= "</nobr></div></td>";
         }
         $this->HTML .= "</tr>";
         $this->HTML .= "<tr><td colspan=2><div class=\"TableBody\" style=\"text-align:center;\"><nobr>";
         // display 'Add New' icon
         if ($this->Permissions[1] && $this->SeparateDV && $Print_x == '') {
             $this->HTML .= " <input type=image src=addNew.gif name=addNew alt='" . $Translation['add new record'] . "'>";
         }
         // display Print icon
         if ($this->AllowPrinting && $Print_x == '') {
             $this->HTML .= " <input onClick=\"document.myform.NoDV.value=1;\" type=image src=print.gif name=Print alt='" . $Translation["printer friendly view"] . "'>";
         }
         // display CSV icon
         if ($this->AllowCSV && $Print_x == '') {
             $this->HTML .= " <input onClick=\"document.myform.NoDV.value=1;\" type=image src=csv.gif name=CSV alt='" . $Translation["save as csv"] . "'>";
         }
         // display Filter icons
         if ($this->AllowFilters && $Print_x == '') {
             $this->HTML .= " <input onClick=\"document.myform.NoDV.value=1;\" type=image src=search.gif name=Filter alt='" . $Translation["edit filters"] . "'> <input onClick=\"{$resetSelection} document.myform.NoDV.value=1;\" type=image src=cancel_search.gif name=NoFilter alt='" . $Translation["clear filters"] . "'> ";
         }
         $this->HTML .= "</nobr></div></td></tr>";
         $this->HTML .= "<!--</td></tr>--></table></td></tr>";
         $this->HTML .= "<tr><td class=TableHeader>" . ($this->AllowSelection ? "&nbsp;&nbsp;" : "") . "</td>";
         if ($this->AllowPrintingMultiSelection && $Print_x != '') {
             $this->HTML .= '<td class="TableHeader displayOnly" align="left"><input type="checkbox" title="' . $Translation['Select all records'] . '" id="toggleAll" onclick="toggleAllRecords();"></td>';
         }
         // Templates
         if ($this->Template != '') {
             $rowTemplate = @implode('', @file('./' . $this->Template));
             if (!$rowTemplate) {
                 $rowTemplate = '';
                 $selrowTemplate = '';
             } else {
                 if ($this->SelectedTemplate != '') {
                     $selrowTemplate = @implode('', @file('./' . $this->SelectedTemplate));
                     if (!$selrowTemplate) {
                         $selrowTemplate = '';
                     }
                 } else {
                     $selrowTemplate = '';
                 }
             }
         } else {
             $rowTemplate = '';
             $selrowTemplate = '';
         }
         // process translations
         if ($rowTemplate) {
             foreach ($Translation as $symbol => $trans) {
                 $rowTemplate = str_replace("<%%TRANSLATION({$symbol})%%>", $trans, $rowTemplate);
             }
         }
         if ($selrowTemplate) {
             foreach ($Translation as $symbol => $trans) {
                 $selrowTemplate = str_replace("<%%TRANSLATION({$symbol})%%>", $trans, $selrowTemplate);
             }
         }
         // End of templates
         // display table headers
         global $SortFieldNumeric;
         if ($rowTemplate == '' || $this->ShowTableHeader == 1) {
             for ($i = 0; $i < count($this->ColCaption); $i++) {
                 if ($this->AllowSorting == 1) {
                     $sort1 = "<a href=\"{$this->ScriptFileName}?SortDirection=asc&SortField=" . $this->ColNumber[$i] . "\" onClick=\"{$resetSelection} document.myform.NoDV.value=1; document.myform.SortDirection.value='asc'; document.myform.SortField.value = '" . $this->ColNumber[$i] . "'; document.myform.submit(); return false;\" class=\"TableHeader\">";
                     $sort2 = "</a>";
                     if ($this->ColNumber[$i] == $SortField || $this->ColNumber[$i] == $SortFieldNumeric) {
                         $SortDirection = $SortDirection == "asc" ? "desc" : "asc";
                         $sort1 = "<a href=\"{$this->ScriptFileName}?SortDirection={$SortDirection}&SortField=" . $this->ColNumber[$i] . "\" onClick=\"{$resetSelection} document.myform.NoDV.value=1; document.myform.SortDirection.value='{$SortDirection}'; document.myform.SortField.value = " . $this->ColNumber[$i] . "; document.myform.submit(); return false;\" class=\"TableHeader\"><img src=\"{$SortDirection}.gif\" border=\"0\" hspace=\"3\">";
                         $SortDirection = $SortDirection == "asc" ? "desc" : "asc";
                     }
                 } else {
                     $sort1 = '';
                     $sort2 = '';
                 }
                 $this->HTML .= "\t<td valign=top nowrap width='" . ($this->ColWidth[$i] ? $this->ColWidth[$i] : 100) . "' class=TableHeader><div class=TableHeader>{$sort1}" . $this->ColCaption[$i] . "{$sort2}</div></td>\n";
             }
         } else {
             // Display a Sort by drop down
             $this->HTML .= "\t<td valign=top class=TableHeader colspan=" . ($FieldCountTV + 1) . "><div class=TableHeader>";
             if ($this->AllowSorting == 1) {
                 $sortCombo = new Combo();
                 //$sortCombo->ListItem[] = "";
                 //$sortCombo->ListData[] = "";
                 for ($i = 0; $i < count($this->ColCaption); $i++) {
                     $sortCombo->ListItem[] = $this->ColCaption[$i];
                     $sortCombo->ListData[] = $this->ColNumber[$i];
                 }
                 $sortCombo->SelectName = "FieldsList";
                 $sortCombo->SelectedData = is_numeric($SortField) ? $SortField : $SortFieldNumeric;
                 $sortCombo->Class = 'TableBody';
                 $sortCombo->SelectedClass = 'TableBodySelected';
                 $sortCombo->Render();
                 $d = $sortCombo->HTML;
                 $d = str_replace('<select ', "<select onChange=\"document.myform.SortDirection.value='{$SortDirection}'; document.myform.SortField.value=document.myform.FieldsList.value; document.myform.NoDV.value=1; document.myform.submit();\" ", $d);
                 if ($SortField) {
                     $SortDirection = $SortDirection == "desc" ? "asc" : "desc";
                     $sort = "<a href=\"javascript: document.myform.NoDV.value=1; document.myform.SortDirection.value='{$SortDirection}'; document.myform.SortField.value='{$SortField}'; document.myform.submit();\" class=TableHeader><img src={$SortDirection}.gif border=0 width=11 height=11 hspace=3></a>";
                     $SortDirection = $SortDirection == "desc" ? "asc" : "desc";
                 } else {
                     $sort = '';
                 }
                 $this->HTML .= $Translation['order by'] . " {$d} {$sort}";
             }
             $this->HTML .= "</div></td>\n";
         }
         // table view navigation code ...
         if ($RecordCount && $this->AllowNavigation && $RecordCount > $this->RecordsPerPage) {
             while ($FirstRecord > $RecordCount) {
                 $FirstRecord -= $this->RecordsPerPage;
             }
             if ($FirstRecord == "" || $FirstRecord < 1) {
                 $FirstRecord = 1;
             }
             if ($Previous_x != "") {
                 $FirstRecord -= $this->RecordsPerPage;
                 if ($FirstRecord <= 0) {
                     $FirstRecord = 1;
                 }
             } elseif ($Next_x != "") {
                 $FirstRecord += $this->RecordsPerPage;
                 if ($FirstRecord > $RecordCount) {
                     $FirstRecord = $RecordCount - $RecordCount % $this->RecordsPerPage + 1;
                 }
                 if ($FirstRecord > $RecordCount) {
                     $FirstRecord = $RecordCount - $this->RecordsPerPage + 1;
                 }
                 if ($FirstRecord <= 0) {
                     $FirstRecord = 1;
                 }
             } else {
                 // no scrolling action took place :)
             }
         } elseif ($RecordCount) {
             $FirstRecord = 1;
             $this->RecordsPerPage = $RecordCount;
         }
         // end of table view navigation code
         $this->HTML .= "\n\t</tr>\n";
         $this->HTML = "<script>\n\t\t\t\t\tfunction colorize(item, color){\n\t\t\t\t\t\tvar n=item.childNodes.length;\n\t\t\t\t\t\tfor(var i=0; i<n; i++){\n\t\t\t\t\t\t\tif(item.childNodes[i].nodeName=='TD'){\n\t\t\t\t\t\t\t\titem.childNodes[i].style.backgroundColor=color;\n\t\t\t\t\t\t\t\tif(item.childNodes[i].childNodes.length>0){\n\t\t\t\t\t\t\t\t\tif(item.childNodes[i].childNodes[0].nodeName=='A'){\n\t\t\t\t\t\t\t\t\t\titem.childNodes[i].childNodes[0].style.backgroundColor=color;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t</script>" . $this->HTML . '<!-- tv data below -->';
         $i = 0;
         $hc = new HtmlFilter();
         $hc->encoding = 'iso-8859-1';
         $hc->defaultProtocol = '';
         if ($RecordCount) {
             $i = $FirstRecord;
             // execute query for table view
             $fieldList = '';
             foreach ($this->QueryFieldsTV as $fn => $fc) {
                 $fieldList .= "{$fn} as `{$fc}`, ";
             }
             $fieldList = substr($fieldList, 0, -2);
             if ($this->PrimaryKey) {
                 $fieldList .= ", {$this->PrimaryKey} as '" . str_replace('`', '', $this->PrimaryKey) . "'";
             }
             $tvQuery = 'SELECT ' . $fieldList . ' from ' . $this->QueryFrom . ' ' . $this->QueryWhere . ' ' . $this->QueryOrder;
             $result = sql($tvQuery . " limit " . ($i - 1) . ",{$this->RecordsPerPage}");
             while (($row = mysql_fetch_array($result)) && $i < $FirstRecord + $this->RecordsPerPage) {
                 $alt = ($i - $FirstRecord) % 2;
                 if ($PrintTV && $_POST["select_{$row[$FieldCountTV]}"] != 1) {
                     continue;
                 }
                 $class = "TableBody" . ($alt ? "Selected" : "") . ($fNumeric ? "Numeric" : "");
                 $this->HTML .= "\t<tr onMouseOver=\"colorize(this, '" . $this->HighlightColor . "');\" onMouseOut=\"colorize(this, '');\">";
                 $this->HTML .= "<td class={$class} valign=top align=right width=12>" . ($SelectedID == $row[$FieldCountTV] ? "<font color=red>&rArr;</font>" : "&nbsp;") . "</td>";
                 if ($this->AllowPrintingMultiSelection && $Print_x != '') {
                     $this->HTML .= "<td class=\"{$class} displayOnly\" valign=\"top\" align=\"left\" width=\"12\"><input type=\"checkbox\" id=\"select_{$row[$FieldCountTV]}\" name=\"select_{$row[$FieldCountTV]}\" value=\"1\" onclick=\"if(\$('select_{$row[$FieldCountTV]}').checked) countSelected++; else countSelected--;\"></td>";
                     $toggleAllScript .= "\$('select_{$row[$FieldCountTV]}').checked=s;";
                 }
                 // templates
                 if ($rowTemplate != '') {
                     if ($this->AllowSelection == 1 && $SelectedID == $row[$FieldCountTV] && $selrowTemplate != "") {
                         $rowTemp = $selrowTemplate;
                     } else {
                         $rowTemp = $rowTemplate;
                     }
                     if ($this->AllowSelection == 1 && $SelectedID != $row[$FieldCountTV]) {
                         $rowTemp = str_replace('<%%SELECT%%>', "<a onclick=\"document.myform.SelectedField.value=this.parentNode.cellIndex; document.myform.SelectedID.value='" . addslashes($row[$FieldCountTV]) . "'; document.myform.submit(); return false;\" href=\"{$this->ScriptFileName}?SelectedID=" . htmlspecialchars($row[$FieldCountTV], ENT_QUOTES) . "\" class=\"{$class}\" style=\"display: block; padding:0px;\">", $rowTemp);
                         $rowTemp = str_replace('<%%ENDSELECT%%>', '</a>', $rowTemp);
                     } else {
                         $rowTemp = str_replace('<%%SELECT%%>', "", $rowTemp);
                         $rowTemp = str_replace('<%%ENDSELECT%%>', '', $rowTemp);
                     }
                     for ($j = 0; $j < $FieldCountTV; $j++) {
                         $fieldTVCaption = current(array_slice($this->QueryFieldsTV, $j, 1));
                         $fd = $hc->clean($row[$j]);
                         /*
                         	the TV template could contain field placeholders in the format 
                         	<%%FIELD_n%%> or <%%VALUE(Field Caption)%%> 
                         */
                         $rowTemp = str_replace("<%%FIELD_{$j}%%>", thisOr($fd), $rowTemp);
                         $rowTemp = str_replace("<%%VALUE({$fieldTVCaption})%%>", thisOr($fd), $rowTemp);
                         if (thisOr($fd) == '&nbsp;' && preg_match('/<a href=".*?&nbsp;.*?<\\/a>/i', $rowTemp, $m)) {
                             $rowTemp = str_replace($m[0], '', $rowTemp);
                         }
                     }
                     if ($alt && $SelectedID != $row[$FieldCountTV]) {
                         $rowTemp = str_replace("TableBody", "TableBodySelected", $rowTemp);
                         $rowTemp = str_replace("TableBodyNumeric", "TableBodySelectedNumeric", $rowTemp);
                         $rowTemp = str_replace("SelectedSelected", "Selected", $rowTemp);
                     }
                     if ($SearchString != '') {
                         $rowTemp = highlight($SearchString, $rowTemp);
                     }
                     $this->HTML .= $rowTemp;
                     $rowTemp = '';
                 } else {
                     // end of templates
                     for ($j = 0; $j < $FieldCountTV; $j++) {
                         $fType = mysql_field_type($result, $j);
                         $fNumeric = stristr($fType, 'int') || stristr($fType, 'float') || stristr($fType, 'decimal') || stristr($fType, 'numeric') || stristr($fType, 'real') || stristr($fType, 'double') ? true : false;
                         if ($this->AllowSelection == 1) {
                             $sel1 = "<a href=\"{$this->ScriptFileName}?SelectedID=" . htmlspecialchars($row[$FieldCountTV], ENT_QUOTES) . "\" onclick=\"document.myform.SelectedID.value='" . addslashes($row[$FieldCountTV]) . "'; document.myform.submit(); return false;\" class=\"{$class}\" style=\"padding:0px;\">";
                             $sel2 = "</a>";
                         } else {
                             $sel1 = "";
                             $sel2 = "";
                         }
                         $this->HTML .= "<td valign=top class={$class}><div class={$class}>&nbsp;{$sel1}" . $row[$j] . "{$sel2}&nbsp;</div></td>";
                     }
                 }
                 $this->HTML .= "</tr>\n";
                 $i++;
             }
             $i--;
         }
         $this->HTML = preg_replace("/<a href=\"(mailto:)?&nbsp;[^\n]*title=\"&nbsp;\"><\\/a>/", '&nbsp;', $this->HTML);
         $this->HTML = preg_replace("/<a [^>]*>(&nbsp;)*<\\/a>/", '&nbsp;', $this->HTML);
         $this->HTML = preg_replace("/<%%.*%%>/U", '&nbsp;', $this->HTML);
         if ($this->ShowRecordSlots) {
             for ($j = $i + 1; $j < $FirstRecord + $this->RecordsPerPage; $j++) {
                 $this->HTML .= "\n\t<tr><td colspan=" . ($FieldCountTV + 1) . "><div class=TableBody>&nbsp;</div></td></tr>";
             }
         }
         // end of data
         $this->HTML .= '<!-- tv data above -->';
         if ($Print_x == "") {
             $pagesMenu = '';
             if ($RecordCount > $this->RecordsPerPage) {
                 $pagesMenu = "<td align=center><div class=TableFooter>" . $Translation['go to page'] . " <select onChange=\"{$resetSelection} document.myform.NoDV.value=1; document.myform.FirstRecord.value=(this.value*" . $this->RecordsPerPage . "+1); document.myform.submit();\">";
                 for ($page = 0; $page < ceil($RecordCount / $this->RecordsPerPage); $page++) {
                     $pagesMenu .= "<option value=\"{$page}\" " . ($FirstRecord == $page * $this->RecordsPerPage + 1 ? 'selected' : '') . ">" . ($page + 1) . "</option>";
                 }
                 $pagesMenu .= '</select></div></td>';
             }
             $totalWidth = array_sum($this->ColWidth);
             $totalWidth = $totalWidth > 750 ? 750 : '100%';
             $this->HTML .= "\n\t<tr><td colspan=" . ($FieldCountTV + 1) . "><table width=100%><tr class=TableFooter><td align=left><input onClick=\"{$resetSelection} document.myform.NoDV.value=1;\" type=image name=Previous src=previousPage.gif></td><td align=center><div class=TableFooter>" . $Translation["records x to y of z"] . "</div></td>{$pagesMenu}<td align=right><input onClick=\"{$resetSelection} document.myform.NoDV.value=1;\" type=image name=Next src=nextPage.gif></td></tr></table></td></tr>";
         } else {
             $this->HTML .= "\n\t<tr><td colspan=" . ($FieldCountTV + 1) . "><nobr><div class=TableFooter>" . $Translation["records x to y of z"] . "</div></nobr></td></tr>";
         }
         $this->HTML = str_replace("<FirstRecord>", $FirstRecord, $this->HTML);
         $this->HTML = str_replace("<LastRecord>", $i, $this->HTML);
         $this->HTML = str_replace("<RecordCount>", $RecordCount, $this->HTML);
         $tvShown = true;
     }
     // hidden variables ....
     $this->HTML .= "<input name=SortField value='{$SortField}' type=hidden>";
     $this->HTML .= "<input name=SelectedID value=\"{$SelectedID}\" type=hidden>";
     $this->HTML .= "<input name=SelectedField value=\"\" type=hidden>";
     $this->HTML .= "<input name=SortDirection type=hidden value='{$SortDirection}'>";
     $this->HTML .= "<input name=FirstRecord type=hidden value='{$FirstRecord}'>";
     $this->HTML .= "<input name=NoDV type=hidden value=''>";
     if ($this->QuickSearch && !strpos($this->HTML, 'SearchString')) {
         $this->HTML .= '<input name="SearchString" type="hidden" value="' . htmlspecialchars($SearchString, ENT_QUOTES) . '">';
     }
     // hidden variables: filters ...
     $FiltersCode = '';
     for ($i = 1; $i <= 20 * $FiltersPerGroup; $i++) {
         // Number of filters allowed
         if ($i % $FiltersPerGroup == 1 && $i != 1 && $FilterAnd[$i] != "") {
             $FiltersCode .= "<input name=\"FilterAnd[{$i}]\" value=\"{$FilterAnd[$i]}\" type=\"hidden\">\n";
         }
         if ($FilterField[$i] != '' && $FilterOperator[$i] != '' && ($FilterValue[$i] != '' || strstr($FilterOperator[$i], 'Empty'))) {
             if (!strstr($FiltersCode, "<input name=\"FilterAnd[{$i}]\" value=")) {
                 $FiltersCode .= "<input name=\"FilterAnd[{$i}]\" value=\"{$FilterAnd[$i]}\" type=\"hidden\">\n";
             }
             $FiltersCode .= "<input name=\"FilterField[{$i}]\" value=\"{$FilterField[$i]}\" type=\"hidden\">\n";
             $FiltersCode .= "<input name=\"FilterOperator[{$i}]\" value=\"{$FilterOperator[$i]}\" type=\"hidden\">\n";
             $FiltersCode .= "<input name=\"FilterValue[{$i}]\" value=\"" . htmlspecialchars($FilterValue[$i], ENT_QUOTES) . "\" type=\"hidden\">\n";
         }
     }
     $this->HTML .= $FiltersCode;
     // display details form ...
     if (($this->AllowSelection || $this->AllowInsert || $this->AllowUpdate || $this->AllowDelete) && $Print_x == '' && !$PrintDV) {
         if ($this->SeparateDV && $this->HideTableView || !$this->SeparateDV) {
             $dvCode = call_user_func($this->TableName . '_form', $SelectedID, $this->AllowUpdate, $this->HideTableView && $SelectedID ? 0 : $this->AllowInsert, $this->AllowDelete, $this->SeparateDV);
             $this->HTML .= "\n\t<tr><td colspan=" . ($FieldCountTV + 2) . ">{$dvCode}</td></tr>";
             $this->HTML .= $this->SeparateDV ? "<input name=SearchString value='" . htmlspecialchars($SearchString, ENT_QUOTES) . "' type=hidden>" : "";
             if ($dvCode) {
                 $this->ContentType = 'detailview';
                 $dvShown = true;
             }
         }
     }
     // display multiple printable detail views
     if ($PrintDV) {
         $dvCode = '';
         $_POST['dvprint_x'] = 1;
         // hidden vars
         $this->HTML .= '<input type="hidden" name="Print_x" value="1">' . "\n";
         $this->HTML .= '<input type="hidden" name="PrintTV" value="1">' . "\n";
         // count selected records
         $selectedRecords = 0;
         foreach ($_POST as $n => $v) {
             if (strpos($n, 'select_') === 0) {
                 $id = str_replace('select_', '', $n);
                 $selectedRecords++;
                 $this->HTML .= '<input type="hidden" name="select_' . $id . '" value="1">' . "\n";
             }
         }
         if ($selectedRecords <= 100) {
             // if records selected > 100 don't show DV preview to avoid db performance issues.
             foreach ($_POST as $n => $v) {
                 if (strpos($n, 'select_') === 0) {
                     $id = str_replace('select_', '', $n);
                     $dvCode .= call_user_func($this->TableName . '_form', $id, 0, 0, 0, 1);
                 }
             }
             if ($dvCode != '') {
                 $dvCode = preg_replace('/<input .*?type="?image"?.*?>/', '', $dvCode);
                 $this->HTML .= "\n" . '<div class="TableBodySelected displayOnly">' . '<input class="print-button" type="submit" value="' . $Translation['Cancel Printing'] . '">' . '<input class="print-button" type="button" id="sendToPrinter" value="' . $Translation['Print'] . '" onClick="window.print();">' . '</div>' . "\n";
                 $this->HTML .= $dvCode;
             }
         } else {
             $this->HTML .= '<div class="Error">' . $Translation['Maximum records allowed to enable this feature is'] . ' 100.</div>';
             $this->HTML .= '<input type="submit" class="print-button" value="' . $Translation['Print Preview Table View'] . '">';
         }
     }
     $this->HTML .= "</table>\n";
     if ($this->AllowPrintingMultiSelection && $Print_x != '') {
         $this->HTML .= "<script>function toggleAllRecords(){ var s=\$('toggleAll').checked; {$toggleAllScript} if(s) countSelected={$RecordCount}; else countSelected=0; }</script>\n";
     }
     $this->HTML .= "</form></center>";
     if ($dvShown && $tvShown) {
         $this->ContentType = 'tableview+detailview';
     }
     if ($dvprint_x != '') {
         $this->ContentType = 'print-detailview';
     }
     if ($Print_x != '') {
         $this->ContentType = 'print-tableview';
     }
     //mysql_close();
     // Das ist Alles!
 }
Пример #12
0
function entries_form($selected_id = '', $AllowUpdate = 1, $AllowInsert = 1, $AllowDelete = 1, $ShowCancel = 0)
{
    // 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('entries');
    if (!$arrPerm[1] && $selected_id == '') {
        return '';
    }
    // print preview?
    $dvprint = false;
    if ($selected_id && $_REQUEST['dvprint_x'] != '') {
        $dvprint = true;
    }
    $filterer_report = thisOr(undo_magic_quotes($_REQUEST['filterer_report']), '');
    $filterer_outcome = thisOr(undo_magic_quotes($_REQUEST['filterer_outcome']), '');
    $filterer_indicator = thisOr(undo_magic_quotes($_REQUEST['filterer_indicator']), '');
    $filterer_beneficiary_group = thisOr(undo_magic_quotes($_REQUEST['filterer_beneficiary_group']), '');
    // populate filterers, starting from children to grand-parents
    if ($filterer_indicator && !$filterer_outcome) {
        $filterer_outcome = sqlValue("select outcome from indicators where indicator_id='" . makeSafe($filterer_indicator) . "'");
    }
    // unique random identifier
    $rnd1 = $dvprint ? rand(1000000, 9999999) : '';
    // combobox: created
    $combo_created = new DateCombo();
    $combo_created->DateFormat = "dmy";
    $combo_created->MinYear = 1900;
    $combo_created->MaxYear = 2100;
    $combo_created->DefaultDate = parseMySQLDate('<%%creationDate%%>', '<%%creationDate%%>');
    $combo_created->MonthNames = $Translation['month names'];
    $combo_created->NamePrefix = 'created';
    // combobox: report
    $combo_report = new DataCombo();
    // combobox: outcome
    $combo_outcome = new DataCombo();
    // combobox: indicator, filterable by: outcome
    $combo_indicator = new DataCombo();
    // combobox: beneficiary_group
    $combo_beneficiary_group = new DataCombo();
    // combobox: beneficiary_group_relevance
    $combo_beneficiary_group_relevance = new Combo();
    $combo_beneficiary_group_relevance->ListType = 0;
    $combo_beneficiary_group_relevance->MultipleSeparator = ', ';
    $combo_beneficiary_group_relevance->ListBoxHeight = 10;
    $combo_beneficiary_group_relevance->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/entries.beneficiary_group_relevance.csv')) {
        $beneficiary_group_relevance_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/entries.beneficiary_group_relevance.csv')));
        $combo_beneficiary_group_relevance->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($beneficiary_group_relevance_data)));
        $combo_beneficiary_group_relevance->ListData = $combo_beneficiary_group_relevance->ListItem;
    } else {
        $combo_beneficiary_group_relevance->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("1;;2;;3;;4;;5")));
        $combo_beneficiary_group_relevance->ListData = $combo_beneficiary_group_relevance->ListItem;
    }
    $combo_beneficiary_group_relevance->SelectName = 'beneficiary_group_relevance';
    // combobox: reliability
    $combo_reliability = new Combo();
    $combo_reliability->ListType = 0;
    $combo_reliability->MultipleSeparator = ', ';
    $combo_reliability->ListBoxHeight = 10;
    $combo_reliability->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/entries.reliability.csv')) {
        $reliability_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/entries.reliability.csv')));
        $combo_reliability->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($reliability_data)));
        $combo_reliability->ListData = $combo_reliability->ListItem;
    } else {
        $combo_reliability->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("1;;2;;3;;4;;5")));
        $combo_reliability->ListData = $combo_reliability->ListItem;
    }
    $combo_reliability->SelectName = 'reliability';
    // combobox: intentionality
    $combo_intentionality = new Combo();
    $combo_intentionality->ListType = 0;
    $combo_intentionality->MultipleSeparator = ', ';
    $combo_intentionality->ListBoxHeight = 10;
    $combo_intentionality->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/entries.intentionality.csv')) {
        $intentionality_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/entries.intentionality.csv')));
        $combo_intentionality->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($intentionality_data)));
        $combo_intentionality->ListData = $combo_intentionality->ListItem;
    } else {
        $combo_intentionality->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("1;;2;;3;;4;;5")));
        $combo_intentionality->ListData = $combo_intentionality->ListItem;
    }
    $combo_intentionality->SelectName = 'intentionality';
    // combobox: equivalence
    $combo_equivalence = new Combo();
    $combo_equivalence->ListType = 0;
    $combo_equivalence->MultipleSeparator = ', ';
    $combo_equivalence->ListBoxHeight = 10;
    $combo_equivalence->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/entries.equivalence.csv')) {
        $equivalence_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/entries.equivalence.csv')));
        $combo_equivalence->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($equivalence_data)));
        $combo_equivalence->ListData = $combo_equivalence->ListItem;
    } else {
        $combo_equivalence->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("1;;2;;3;;4;;5")));
        $combo_equivalence->ListData = $combo_equivalence->ListItem;
    }
    $combo_equivalence->SelectName = 'equivalence';
    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='entries' and pkValue='" . makeSafe($selected_id) . "'");
        $ownerMemberID = sqlValue("select lcase(memberID) from membership_userrecords where tableName='entries' 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 `entries` where `entry_id`='" . makeSafe($selected_id) . "'", $eo);
        $row = mysql_fetch_array($res);
        $urow = $row;
        /* unsanitized data */
        $hc = new CI_Input();
        $row = $hc->xss_clean($row);
        /* sanitize data */
        $combo_created->DefaultDate = $row['created'];
        $combo_report->SelectedData = $row['report'];
        $combo_outcome->SelectedData = $row['outcome'];
        $combo_indicator->SelectedData = $row['indicator'];
        $combo_beneficiary_group->SelectedData = $row['beneficiary_group'];
        $combo_beneficiary_group_relevance->SelectedData = $row['beneficiary_group_relevance'];
        $combo_reliability->SelectedData = $row['reliability'];
        $combo_intentionality->SelectedData = $row['intentionality'];
        $combo_equivalence->SelectedData = $row['equivalence'];
    } else {
        $combo_report->SelectedData = $filterer_report;
        $combo_outcome->SelectedData = $filterer_outcome;
        $combo_indicator->SelectedData = $filterer_indicator;
        $combo_beneficiary_group->SelectedData = $filterer_beneficiary_group;
        $combo_beneficiary_group_relevance->SelectedText = $_REQUEST['FilterField'][1] == '10' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "";
        $combo_reliability->SelectedText = $_REQUEST['FilterField'][1] == '13' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "";
        $combo_intentionality->SelectedText = $_REQUEST['FilterField'][1] == '14' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "";
        $combo_equivalence->SelectedText = $_REQUEST['FilterField'][1] == '15' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "";
    }
    $combo_report->HTML = $combo_report->MatchText = '<span id="report-container' . $rnd1 . '"></span><input type="hidden" name="report" id="report' . $rnd1 . '">';
    $combo_outcome->HTML = $combo_outcome->MatchText = '<span id="outcome-container' . $rnd1 . '"></span><input type="hidden" name="outcome" id="outcome' . $rnd1 . '">';
    $combo_indicator->HTML = $combo_indicator->MatchText = '<span id="indicator-container' . $rnd1 . '"></span><input type="hidden" name="indicator" id="indicator' . $rnd1 . '">';
    $combo_beneficiary_group->HTML = $combo_beneficiary_group->MatchText = '<span id="beneficiary_group-container' . $rnd1 . '"></span><input type="hidden" name="beneficiary_group" id="beneficiary_group' . $rnd1 . '">';
    $combo_beneficiary_group_relevance->Render();
    $combo_reliability->Render();
    $combo_intentionality->Render();
    $combo_equivalence->Render();
    ob_start();
    ?>

	<script>
		// initial lookup values
		var current_report__RAND__ = { text: "", value: "<?php 
    echo addslashes($selected_id ? $urow['report'] : $filterer_report);
    ?>
"};
		var current_outcome__RAND__ = { text: "", value: "<?php 
    echo addslashes($selected_id ? $urow['outcome'] : $filterer_outcome);
    ?>
"};
		var current_indicator__RAND__ = { text: "", value: "<?php 
    echo addslashes($selected_id ? $urow['indicator'] : $filterer_indicator);
    ?>
"};
		var current_beneficiary_group__RAND__ = { text: "", value: "<?php 
    echo addslashes($selected_id ? $urow['beneficiary_group'] : $filterer_beneficiary_group);
    ?>
"};
		
		jQuery(function() {
			report_reload__RAND__();
			outcome_reload__RAND__();
			<?php 
    echo !$AllowUpdate || $dvprint ? 'indicator_reload__RAND__(current_outcome__RAND__.value);' : '';
    ?>
			beneficiary_group_reload__RAND__();
		});
		function report_reload__RAND__(){
		<?php 
    if (($AllowUpdate || $AllowInsert) && !$dvprint) {
        ?>

			jQuery("#report-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					jQuery.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: current_report__RAND__.value, t: 'entries', f: 'report' }
					}).done(function(resp){
						c({
							id: resp.results[0].id,
							text: resp.results[0].text
						});
						jQuery('[name="report"]').val(resp.results[0].id);


						if(typeof(report_update_autofills__RAND__) == 'function') report_update_autofills__RAND__();
					});
				},
				width: '100%',
				formatNoMatches: function(term){ return '<?php 
        echo addslashes($Translation['No matches found!']);
        ?>
'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { s: term, p: page, t: 'entries', f: 'report' }; },
					results: function(resp, page){ return resp; }
				}
			}).on('change', function(e){
				current_report__RAND__.value = e.added.id;
				current_report__RAND__.text = e.added.text;
				jQuery('[name="report"]').val(e.added.id);


				if(typeof(report_update_autofills__RAND__) == 'function') report_update_autofills__RAND__();
			});
		<?php 
    } else {
        ?>

			jQuery.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: current_report__RAND__.value, t: 'entries', f: 'report' }
			}).done(function(resp){
				jQuery('#report-container__RAND__').html('<span id="report-match-text">' + resp.results[0].text + '</span>');

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

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

			jQuery("#outcome-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					jQuery.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: current_outcome__RAND__.value, t: 'entries', f: 'outcome' }
					}).done(function(resp){
						c({
							id: resp.results[0].id,
							text: resp.results[0].text
						});
						jQuery('[name="outcome"]').val(resp.results[0].id);

						indicator_reload__RAND__(current_outcome__RAND__.value);

						if(typeof(outcome_update_autofills__RAND__) == 'function') outcome_update_autofills__RAND__();
					});
				},
				width: '100%',
				formatNoMatches: function(term){ return '<?php 
        echo addslashes($Translation['No matches found!']);
        ?>
'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { s: term, p: page, t: 'entries', f: 'outcome' }; },
					results: function(resp, page){ return resp; }
				}
			}).on('change', function(e){
				current_outcome__RAND__.value = e.added.id;
				current_outcome__RAND__.text = e.added.text;
				jQuery('[name="outcome"]').val(e.added.id);

						indicator_reload__RAND__(current_outcome__RAND__.value);

				if(typeof(outcome_update_autofills__RAND__) == 'function') outcome_update_autofills__RAND__();
			});
		<?php 
    } else {
        ?>

			jQuery.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: current_outcome__RAND__.value, t: 'entries', f: 'outcome' }
			}).done(function(resp){
				jQuery('#outcome-container__RAND__').html('<span id="outcome-match-text">' + resp.results[0].text + '</span>');

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

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

			jQuery("#indicator-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					jQuery.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { filterer_outcome: filterer_outcome, id: current_indicator__RAND__.value, t: 'entries', f: 'indicator' }
					}).done(function(resp){
						c({
							id: resp.results[0].id,
							text: resp.results[0].text
						});
						jQuery('[name="indicator"]').val(resp.results[0].id);


						if(typeof(indicator_update_autofills__RAND__) == 'function') indicator_update_autofills__RAND__();
					});
				},
				width: '100%',
				formatNoMatches: function(term){ return '<?php 
        echo addslashes($Translation['No matches found!']);
        ?>
'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { filterer_outcome: filterer_outcome, s: term, p: page, t: 'entries', f: 'indicator' }; },
					results: function(resp, page){ return resp; }
				}
			}).on('change', function(e){
				current_indicator__RAND__.value = e.added.id;
				current_indicator__RAND__.text = e.added.text;
				jQuery('[name="indicator"]').val(e.added.id);


				if(typeof(indicator_update_autofills__RAND__) == 'function') indicator_update_autofills__RAND__();
			});
		<?php 
    } else {
        ?>

			jQuery.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: current_indicator__RAND__.value, t: 'entries', f: 'indicator' }
			}).done(function(resp){
				jQuery('#indicator-container__RAND__').html('<span id="indicator-match-text">' + resp.results[0].text + '</span>');

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

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

			jQuery("#beneficiary_group-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					jQuery.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: current_beneficiary_group__RAND__.value, t: 'entries', f: 'beneficiary_group' }
					}).done(function(resp){
						c({
							id: resp.results[0].id,
							text: resp.results[0].text
						});
						jQuery('[name="beneficiary_group"]').val(resp.results[0].id);


						if(typeof(beneficiary_group_update_autofills__RAND__) == 'function') beneficiary_group_update_autofills__RAND__();
					});
				},
				width: '100%',
				formatNoMatches: function(term){ return '<?php 
        echo addslashes($Translation['No matches found!']);
        ?>
'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { s: term, p: page, t: 'entries', f: 'beneficiary_group' }; },
					results: function(resp, page){ return resp; }
				}
			}).on('change', function(e){
				current_beneficiary_group__RAND__.value = e.added.id;
				current_beneficiary_group__RAND__.text = e.added.text;
				jQuery('[name="beneficiary_group"]').val(e.added.id);


				if(typeof(beneficiary_group_update_autofills__RAND__) == 'function') beneficiary_group_update_autofills__RAND__();
			});
		<?php 
    } else {
        ?>

			jQuery.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: current_beneficiary_group__RAND__.value, t: 'entries', f: 'beneficiary_group' }
			}).done(function(resp){
				jQuery('#beneficiary_group-container__RAND__').html('<span id="beneficiary_group-match-text">' + resp.results[0].text + '</span>');

				if(typeof(beneficiary_group_update_autofills__RAND__) == 'function') beneficiary_group_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) {
        $templateCode = @file_get_contents('./templates/entries_templateDVP.html');
    } else {
        $templateCode = @file_get_contents('./templates/entries_templateDV.html');
    }
    // process form title
    $templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Entry details', $templateCode);
    $templateCode = str_replace('<%%RND1%%>', $rnd1, $templateCode);
    // process buttons
    if ($arrPerm[1]) {
        // allow insert?
        if (!$selected_id) {
            $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-success" id="insert" name="insert_x" value="1" onclick="return entries_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save New'] . '</button>', $templateCode);
        }
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-default" id="insert" name="insert_x" value="1" onclick="return entries_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 = 'window.parent.jQuery(\'.modal\').modal(\'hide\'); return false;';
    } else {
        $backAction = '$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;';
    }
    if ($selected_id) {
        if (!$_REQUEST['Embedded']) {
            $templateCode = str_replace('<%%DVPRINT_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-default" id="dvprint" name="dvprint_x" value="1" onclick="$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;"><i class="glyphicon glyphicon-print"></i> ' . $Translation['Print Preview'] . '</button>', $templateCode);
        }
        if ($AllowUpdate) {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-success btn-lg" id="update" name="update_x" value="1" onclick="return entries_validateData();"><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 tabindex="2" type="submit" class="btn btn-danger" id="delete" name="delete_x" value="1" onclick="return confirm(\'' . $Translation['are you sure?'] . '\');"><i class="glyphicon glyphicon-trash"></i> ' . $Translation['Delete'] . '</button>', $templateCode);
        } else {
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        }
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><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 tabindex="2" type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><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 && !$arrPerm[1] || !$selected_id && !$arrPerm[1]) {
        $jsReadOnly .= "\tjQuery('#report').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#report_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
        $jsReadOnly .= "\tjQuery('#outcome').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#outcome_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
        $jsReadOnly .= "\tjQuery('#indicator').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#indicator_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
        $jsReadOnly .= "\tjQuery('#score').replaceWith('<p class=\"form-control-static\" id=\"score\">' + (jQuery('#score').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#beneficiary_group').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#beneficiary_group_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
        $jsReadOnly .= "\tjQuery('#beneficiary_group_relevance').replaceWith('<p class=\"form-control-static\" id=\"beneficiary_group_relevance\">' + (jQuery('#beneficiary_group_relevance').val() || '') + '</p>'); jQuery('#beneficiary_group_relevance-multi-selection-help').hide();\n";
        $jsReadOnly .= "\tjQuery('#comment').replaceWith('<p class=\"form-control-static\" id=\"comment\">' + (jQuery('#comment').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#reference').replaceWith('<p class=\"form-control-static\" id=\"reference\">' + (jQuery('#reference').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#reliability').replaceWith('<p class=\"form-control-static\" id=\"reliability\">' + (jQuery('#reliability').val() || '') + '</p>'); jQuery('#reliability-multi-selection-help').hide();\n";
        $jsReadOnly .= "\tjQuery('#intentionality').replaceWith('<p class=\"form-control-static\" id=\"intentionality\">' + (jQuery('#intentionality').val() || '') + '</p>'); jQuery('#intentionality-multi-selection-help').hide();\n";
        $jsReadOnly .= "\tjQuery('#equivalence').replaceWith('<p class=\"form-control-static\" id=\"equivalence\">' + (jQuery('#equivalence').val() || '') + '</p>'); jQuery('#equivalence-multi-selection-help').hide();\n";
        $noUploads = true;
    }
    // process combos
    $templateCode = str_replace('<%%COMBO(created)%%>', $selected_id && !$arrPerm[3] ? '<p class="form-control-static">' . $combo_created->GetHTML(true) . '</p>' : $combo_created->GetHTML(), $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(created)%%>', $combo_created->GetHTML(true), $templateCode);
    $templateCode = str_replace('<%%COMBO(report)%%>', $combo_report->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(report)%%>', $combo_report->MatchText, $templateCode);
    $templateCode = str_replace('<%%URLCOMBOTEXT(report)%%>', urlencode($combo_report->MatchText), $templateCode);
    $templateCode = str_replace('<%%COMBO(outcome)%%>', $combo_outcome->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(outcome)%%>', $combo_outcome->MatchText, $templateCode);
    $templateCode = str_replace('<%%URLCOMBOTEXT(outcome)%%>', urlencode($combo_outcome->MatchText), $templateCode);
    $templateCode = str_replace('<%%COMBO(indicator)%%>', $combo_indicator->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(indicator)%%>', $combo_indicator->MatchText, $templateCode);
    $templateCode = str_replace('<%%URLCOMBOTEXT(indicator)%%>', urlencode($combo_indicator->MatchText), $templateCode);
    $templateCode = str_replace('<%%COMBO(beneficiary_group)%%>', $combo_beneficiary_group->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(beneficiary_group)%%>', $combo_beneficiary_group->MatchText, $templateCode);
    $templateCode = str_replace('<%%URLCOMBOTEXT(beneficiary_group)%%>', urlencode($combo_beneficiary_group->MatchText), $templateCode);
    $templateCode = str_replace('<%%COMBO(beneficiary_group_relevance)%%>', $combo_beneficiary_group_relevance->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(beneficiary_group_relevance)%%>', $combo_beneficiary_group_relevance->SelectedData, $templateCode);
    $templateCode = str_replace('<%%COMBO(reliability)%%>', $combo_reliability->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(reliability)%%>', $combo_reliability->SelectedData, $templateCode);
    $templateCode = str_replace('<%%COMBO(intentionality)%%>', $combo_intentionality->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(intentionality)%%>', $combo_intentionality->SelectedData, $templateCode);
    $templateCode = str_replace('<%%COMBO(equivalence)%%>', $combo_equivalence->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(equivalence)%%>', $combo_equivalence->SelectedData, $templateCode);
    // process foreign key links
    if ($selected_id) {
        $templateCode = str_replace('<%%PLINK(report)%%>', $combo_report->SelectedData ? "<span id=\"reports_plink1\" class=\"hidden\"><a class=\"btn btn-default\" href=\"reports_view.php?SelectedID=" . urlencode($combo_report->SelectedData) . "\"><i class=\"glyphicon glyphicon-search\"></i></a></span>" : '', $templateCode);
        $templateCode = str_replace('<%%PLINK(outcome)%%>', $combo_outcome->SelectedData ? "<span id=\"outcomes_plink2\" class=\"hidden\"><a class=\"btn btn-default\" href=\"outcomes_view.php?SelectedID=" . urlencode($combo_outcome->SelectedData) . "\"><i class=\"glyphicon glyphicon-search\"></i></a></span>" : '', $templateCode);
        $templateCode = str_replace('<%%PLINK(indicator)%%>', $combo_indicator->SelectedData ? "<span id=\"indicators_plink3\" class=\"hidden\"><a class=\"btn btn-default\" href=\"indicators_view.php?SelectedID=" . urlencode($combo_indicator->SelectedData) . "\"><i class=\"glyphicon glyphicon-search\"></i></a></span>" : '', $templateCode);
        $templateCode = str_replace('<%%PLINK(beneficiary_group)%%>', $combo_beneficiary_group->SelectedData ? "<span id=\"beneficiary_groups_plink4\" class=\"hidden\"><a class=\"btn btn-default\" href=\"beneficiary_groups_view.php?SelectedID=" . urlencode($combo_beneficiary_group->SelectedData) . "\"><i class=\"glyphicon glyphicon-search\"></i></a></span>" : '', $templateCode);
    }
    // process images
    $templateCode = str_replace('<%%UPLOADFILE(entry_id)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(created)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(created_by)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(report)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(outcome)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(indicator)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(score)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(beneficiary_group)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(beneficiary_group_relevance)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(comment)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(reference)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(reliability)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(intentionality)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(equivalence)%%>', '', $templateCode);
    // process values
    if ($selected_id) {
        $templateCode = str_replace('<%%VALUE(entry_id)%%>', htmlspecialchars($row['entry_id'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(entry_id)%%>', urlencode($urow['entry_id']), $templateCode);
        $templateCode = str_replace('<%%VALUE(created)%%>', @date('d/m/Y', @strtotime(htmlspecialchars($row['created'], ENT_QUOTES))), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(created)%%>', urlencode(@date('d/m/Y', @strtotime(htmlspecialchars($urow['created'], ENT_QUOTES)))), $templateCode);
        $templateCode = str_replace('<%%VALUE(created_by)%%>', htmlspecialchars($row['created_by'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(created_by)%%>', urlencode($urow['created_by']), $templateCode);
        $templateCode = str_replace('<%%VALUE(report)%%>', htmlspecialchars($row['report'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(report)%%>', urlencode($urow['report']), $templateCode);
        $templateCode = str_replace('<%%VALUE(outcome)%%>', htmlspecialchars($row['outcome'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(outcome)%%>', urlencode($urow['outcome']), $templateCode);
        $templateCode = str_replace('<%%VALUE(indicator)%%>', htmlspecialchars($row['indicator'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(indicator)%%>', urlencode($urow['indicator']), $templateCode);
        $templateCode = str_replace('<%%VALUE(score)%%>', htmlspecialchars($row['score'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(score)%%>', urlencode($urow['score']), $templateCode);
        $templateCode = str_replace('<%%VALUE(beneficiary_group)%%>', htmlspecialchars($row['beneficiary_group'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(beneficiary_group)%%>', urlencode($urow['beneficiary_group']), $templateCode);
        $templateCode = str_replace('<%%VALUE(beneficiary_group_relevance)%%>', htmlspecialchars($row['beneficiary_group_relevance'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(beneficiary_group_relevance)%%>', urlencode($urow['beneficiary_group_relevance']), $templateCode);
        if ($dvprint) {
            $templateCode = str_replace('<%%VALUE(comment)%%>', nl2br(htmlspecialchars($row['comment'], ENT_QUOTES)), $templateCode);
        } else {
            $templateCode = str_replace('<%%VALUE(comment)%%>', htmlspecialchars($row['comment'], ENT_QUOTES), $templateCode);
        }
        $templateCode = str_replace('<%%URLVALUE(comment)%%>', urlencode($urow['comment']), $templateCode);
        $templateCode = str_replace('<%%VALUE(reference)%%>', htmlspecialchars($row['reference'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(reference)%%>', urlencode($urow['reference']), $templateCode);
        $templateCode = str_replace('<%%VALUE(reliability)%%>', htmlspecialchars($row['reliability'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(reliability)%%>', urlencode($urow['reliability']), $templateCode);
        $templateCode = str_replace('<%%VALUE(intentionality)%%>', htmlspecialchars($row['intentionality'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(intentionality)%%>', urlencode($urow['intentionality']), $templateCode);
        $templateCode = str_replace('<%%VALUE(equivalence)%%>', htmlspecialchars($row['equivalence'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(equivalence)%%>', urlencode($urow['equivalence']), $templateCode);
    } else {
        $templateCode = str_replace('<%%VALUE(entry_id)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(entry_id)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(created)%%>', '<%%creationDate%%>', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(created)%%>', urlencode('<%%creationDate%%>'), $templateCode);
        $templateCode = str_replace('<%%VALUE(created_by)%%>', '<%%creatorUsername%%>', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(created_by)%%>', urlencode('<%%creatorUsername%%>'), $templateCode);
        $templateCode = str_replace('<%%VALUE(report)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(report)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(outcome)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(outcome)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(indicator)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(indicator)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(score)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(score)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(beneficiary_group)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(beneficiary_group)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(beneficiary_group_relevance)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(beneficiary_group_relevance)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(comment)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(comment)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(reference)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(reference)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(reliability)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(reliability)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(intentionality)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(intentionality)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(equivalence)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(equivalence)%%>', urlencode(''), $templateCode);
    }
    // process translations
    foreach ($Translation as $symbol => $trans) {
        $templateCode = str_replace("<%%TRANSLATION({$symbol})%%>", $trans, $templateCode);
    }
    // clear scrap
    $templateCode = str_replace('<%%', '<!-- ', $templateCode);
    $templateCode = str_replace('%%>', ' -->', $templateCode);
    // hide links to inaccessible tables
    if ($_POST['dvprint_x'] == '') {
        $templateCode .= "\n\n<script>jQuery(function(){\n";
        $arrTables = getTableList();
        foreach ($arrTables as $name => $caption) {
            $templateCode .= "\tjQuery('#{$name}_link').removeClass('hidden');\n";
            $templateCode .= "\tjQuery('#xs_{$name}_link').removeClass('hidden');\n";
            $templateCode .= "\tjQuery('[id^=\"{$name}_plink\"]').removeClass('hidden');\n";
        }
        $templateCode .= $jsReadOnly;
        if (!$selected_id) {
        }
        $templateCode .= "\n});</script>\n";
    }
    // ajaxed auto-fill fields
    $templateCode .= "<script>";
    $templateCode .= "document.observe('dom:loaded', function() {";
    $templateCode .= "\toutcome_update_autofills{$rnd1} = function(){\n";
    $templateCode .= "\t\tnew Ajax.Request(\n";
    if ($dvprint) {
        $templateCode .= "\t\t\t'entries_autofill.php?rnd1={$rnd1}&mfk=outcome&id='+encodeURIComponent('" . addslashes($row['outcome']) . "'),\n";
        $templateCode .= "\t\t\t{encoding: 'UTF-8', method: 'get'}\n";
    } else {
        $templateCode .= "\t\t\t'entries_autofill.php?rnd1={$rnd1}&mfk=outcome&id=' + encodeURIComponent(current_outcome{$rnd1}.value),\n";
        $templateCode .= "\t\t\t{encoding: 'UTF-8', method: 'get', onCreate: function(){ \$('outcome{$rnd1}').disable(); \$('outcomeLoading').innerHTML='<img src=loading.gif align=top>'; }, onComplete: function(){" . ($arrPerm[1] || ($arrPerm[3] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[3] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[3] == 3) ? "\$('outcome{$rnd1}').enable(); " : "\$('outcome{$rnd1}').disable(); ") . "\$('outcomeLoading').innerHTML='';}}\n";
    }
    $templateCode .= "\t\t);\n";
    $templateCode .= "\t};\n";
    if (!$dvprint) {
        $templateCode .= "\tif(\$('outcome_caption') != undefined) \$('outcome_caption').onchange=outcome_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" rel="lightbox\\[.*?\\]"/', 'blank.gif"', $templateCode);
    // don't display empty email links
    $templateCode = preg_replace('/<a .*?href="mailto:".*?<\\/a>/', '', $templateCode);
    // hook: entries_dv
    if (function_exists('entries_dv')) {
        $args = array();
        entries_dv($selected_id ? $selected_id : FALSE, getMemberInfo(), $templateCode, $args);
    }
    return $templateCode;
}
Пример #13
0
function units_form($selected_id = '', $AllowUpdate = 1, $AllowInsert = 1, $AllowDelete = 1, $ShowCancel = 0)
{
    // 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('units');
    if (!$arrPerm[1] && $selected_id == '') {
        return '';
    }
    $AllowInsert = $arrPerm[1] ? true : false;
    // print preview?
    $dvprint = false;
    if ($selected_id && $_REQUEST['dvprint_x'] != '') {
        $dvprint = true;
    }
    $filterer_property = thisOr(undo_magic_quotes($_REQUEST['filterer_property']), '');
    // populate filterers, starting from children to grand-parents
    // unique random identifier
    $rnd1 = $dvprint ? rand(1000000, 9999999) : '';
    // combobox: property
    $combo_property = new DataCombo();
    // combobox: status
    $combo_status = new Combo();
    $combo_status->ListType = 2;
    $combo_status->MultipleSeparator = ', ';
    $combo_status->ListBoxHeight = 10;
    $combo_status->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/units.status.csv')) {
        $status_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/units.status.csv')));
        $combo_status->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($status_data)));
        $combo_status->ListData = $combo_status->ListItem;
    } else {
        $combo_status->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Occupied;;Listed;;Unlisted")));
        $combo_status->ListData = $combo_status->ListItem;
    }
    $combo_status->SelectName = 'status';
    $combo_status->AllowNull = false;
    // combobox: features
    $combo_features = new Combo();
    $combo_features->ListType = 3;
    $combo_features->MultipleSeparator = ', ';
    $combo_features->ListBoxHeight = 10;
    $combo_features->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/units.features.csv')) {
        $features_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/units.features.csv')));
        $combo_features->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($features_data)));
        $combo_features->ListData = $combo_features->ListItem;
    } else {
        $combo_features->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Cable ready;; Micorwave;;Hardwood floors;; High speed internet;;Air conditioning;;Refrigerator;;Dishwasher;;Walk-in closets;;Balcony;;Deck;;Patio;;Garage parking;;Carport;;Fenced yard;;Laundry room / hookups;; Fireplace;;Oven / range;;Heat - electric;; Heat - gas;; Heat - oil")));
        $combo_features->ListData = $combo_features->ListItem;
    }
    $combo_features->SelectName = 'features';
    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='units' and pkValue='" . makeSafe($selected_id) . "'");
        $ownerMemberID = sqlValue("select lcase(memberID) from membership_userrecords where tableName='units' 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 `units` where `id`='" . makeSafe($selected_id) . "'", $eo);
        if (!($row = db_fetch_array($res))) {
            return error_message($Translation['No records found']);
        }
        $urow = $row;
        /* unsanitized data */
        $hc = new CI_Input();
        $row = $hc->xss_clean($row);
        /* sanitize data */
        $combo_property->SelectedData = $row['property'];
        $combo_status->SelectedData = $row['status'];
        $combo_features->SelectedData = $row['features'];
    } else {
        $combo_property->SelectedData = $filterer_property;
        $combo_status->SelectedText = $_REQUEST['FilterField'][1] == '5' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "";
    }
    $combo_property->HTML = '<span id="property-container' . $rnd1 . '"></span><input type="hidden" name="property" id="property' . $rnd1 . '">';
    $combo_property->MatchText = '<span id="property-container-readonly' . $rnd1 . '"></span><input type="hidden" name="property" id="property' . $rnd1 . '">';
    $combo_status->Render();
    $combo_features->Render();
    ob_start();
    ?>

	<script>
		// initial lookup values
		var current_property__RAND__ = { text: "", value: "<?php 
    echo addslashes($selected_id ? $urow['property'] : $filterer_property);
    ?>
"};

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

			jQuery("#property-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					jQuery.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: current_property__RAND__.value, t: 'units', f: 'property' }
					}).done(function(resp){
						c({
							id: resp.results[0].id,
							text: resp.results[0].text
						});
						jQuery('[name="property"]').val(resp.results[0].id);
						jQuery('[id=property-container-readonly__RAND__]').html('<span id="property-match-text">' + resp.results[0].text + '</span>');


						if(typeof(property_update_autofills__RAND__) == 'function') property_update_autofills__RAND__();
					});
				},
				width: '100%',
				formatNoMatches: function(term){ return '<?php 
        echo addslashes($Translation['No matches found!']);
        ?>
'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { s: term, p: page, t: 'units', f: 'property' }; },
					results: function(resp, page){ return resp; }
				}
			}).on('change', function(e){
				current_property__RAND__.value = e.added.id;
				current_property__RAND__.text = e.added.text;
				jQuery('[name="property"]').val(e.added.id);


				if(typeof(property_update_autofills__RAND__) == 'function') property_update_autofills__RAND__();
			});
		<?php 
    } else {
        ?>

			jQuery.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: current_property__RAND__.value, t: 'units', f: 'property' }
			}).done(function(resp){
				jQuery('[id=property-container__RAND__], [id=property-container-readonly__RAND__]').html('<span id="property-match-text">' + resp.results[0].text + '</span>');

				if(typeof(property_update_autofills__RAND__) == 'function') property_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) {
        $templateCode = @file_get_contents('./templates/units_templateDVP.html');
    } else {
        $templateCode = @file_get_contents('./templates/units_templateDV.html');
    }
    // process form title
    $templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Unit details', $templateCode);
    $templateCode = str_replace('<%%RND1%%>', $rnd1, $templateCode);
    $templateCode = str_replace('<%%EMBEDDED%%>', $_REQUEST['Embedded'] ? 'Embedded=1' : '', $templateCode);
    // process buttons
    if ($AllowInsert) {
        if (!$selected_id) {
            $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-success" id="insert" name="insert_x" value="1" onclick="return units_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 units_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 = 'window.parent.jQuery(\'.modal\').modal(\'hide\'); return false;';
    } else {
        $backAction = '$$(\'form\')[0].writeAttribute(\'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="$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;"><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 units_validateData();"><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?'] . '\');"><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 . '"><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 . '"><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('#property').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#property_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
        $jsReadOnly .= "\tjQuery('#unit_number').replaceWith('<p class=\"form-control-static\" id=\"unit_number\">' + (jQuery('#unit_number').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#photo').replaceWith('<p class=\"form-control-static\" id=\"photo\">' + (jQuery('#photo').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('input[name=status]').parent().html('<p class=\"form-control-static\">' + jQuery('input[name=status]:checked').next().text() + '</p>')\n";
        $jsReadOnly .= "\tjQuery('#size').replaceWith('<p class=\"form-control-static\" id=\"size\">' + (jQuery('#size').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#rooms').replaceWith('<p class=\"form-control-static\" id=\"rooms\">' + (jQuery('#rooms').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#bathroom').replaceWith('<p class=\"form-control-static\" id=\"bathroom\">' + (jQuery('#bathroom').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#features').replaceWith('<p class=\"form-control-static\" id=\"features\">' + (jQuery('#features').val() || '') + '</p>'); jQuery('#features-multi-selection-help').hide();\n";
        $jsReadOnly .= "\tjQuery('#s2id_features').remove();\n";
        $jsReadOnly .= "\tjQuery('#rental_amount').replaceWith('<p class=\"form-control-static\" id=\"rental_amount\">' + (jQuery('#rental_amount').val() || '') + '</p>');\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(property)%%>', $combo_property->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(property)%%>', $combo_property->MatchText, $templateCode);
    $templateCode = str_replace('<%%URLCOMBOTEXT(property)%%>', urlencode($combo_property->MatchText), $templateCode);
    $templateCode = str_replace('<%%COMBO(status)%%>', $combo_status->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(status)%%>', $combo_status->SelectedData, $templateCode);
    $templateCode = str_replace('<%%COMBO(features)%%>', $combo_features->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(features)%%>', $combo_features->SelectedData, $templateCode);
    // process foreign key links
    if ($selected_id) {
        $templateCode = str_replace('<%%PLINK(property)%%>', $combo_property->SelectedData ? "<span id=\"properties_plink1\" class=\"hidden\"><a class=\"btn btn-default\" href=\"properties_view.php?SelectedID=" . urlencode($combo_property->SelectedData) . "\"><i class=\"glyphicon glyphicon-search\"></i></a></span>" : '', $templateCode);
    }
    // process images
    $templateCode = str_replace('<%%UPLOADFILE(id)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(property)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(unit_number)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(photo)%%>', $noUploads ? '' : '<br><input type=hidden name=MAX_FILE_SIZE value=1024000>' . $Translation['upload image'] . ' <input type="file" name="photo">', $templateCode);
    if ($AllowUpdate && $row['photo'] != '') {
        $templateCode = str_replace('<%%REMOVEFILE(photo)%%>', '<br><input type="checkbox" name="photo_remove" id="photo_remove" value="1"> <label for="photo_remove" style="color: red; font-weight: bold;">' . $Translation['remove image'] . '</label>', $templateCode);
    } else {
        $templateCode = str_replace('<%%REMOVEFILE(photo)%%>', '', $templateCode);
    }
    $templateCode = str_replace('<%%UPLOADFILE(status)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(size)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(rooms)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(bathroom)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(features)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(market_rent)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(rental_amount)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(deposit_amount)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(description)%%>', '', $templateCode);
    // process values
    if ($selected_id) {
        $templateCode = str_replace('<%%VALUE(id)%%>', htmlspecialchars($row['id'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(id)%%>', urlencode($urow['id']), $templateCode);
        $templateCode = str_replace('<%%VALUE(property)%%>', htmlspecialchars($row['property'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(property)%%>', urlencode($urow['property']), $templateCode);
        $templateCode = str_replace('<%%VALUE(unit_number)%%>', htmlspecialchars($row['unit_number'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(unit_number)%%>', urlencode($urow['unit_number']), $templateCode);
        $row['photo'] = $row['photo'] != '' ? $row['photo'] : 'blank.gif';
        $templateCode = str_replace('<%%VALUE(photo)%%>', htmlspecialchars($row['photo'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(photo)%%>', urlencode($urow['photo']), $templateCode);
        $templateCode = str_replace('<%%VALUE(status)%%>', htmlspecialchars($row['status'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(status)%%>', urlencode($urow['status']), $templateCode);
        $templateCode = str_replace('<%%VALUE(size)%%>', htmlspecialchars($row['size'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(size)%%>', urlencode($urow['size']), $templateCode);
        $templateCode = str_replace('<%%VALUE(rooms)%%>', htmlspecialchars($row['rooms'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(rooms)%%>', urlencode($urow['rooms']), $templateCode);
        $templateCode = str_replace('<%%VALUE(bathroom)%%>', htmlspecialchars($row['bathroom'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(bathroom)%%>', urlencode($urow['bathroom']), $templateCode);
        $templateCode = str_replace('<%%VALUE(features)%%>', htmlspecialchars($row['features'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(features)%%>', urlencode($urow['features']), $templateCode);
        $templateCode = str_replace('<%%VALUE(market_rent)%%>', htmlspecialchars($row['market_rent'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(market_rent)%%>', urlencode($urow['market_rent']), $templateCode);
        $templateCode = str_replace('<%%VALUE(rental_amount)%%>', htmlspecialchars($row['rental_amount'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(rental_amount)%%>', urlencode($urow['rental_amount']), $templateCode);
        $templateCode = str_replace('<%%VALUE(deposit_amount)%%>', htmlspecialchars($row['deposit_amount'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(deposit_amount)%%>', urlencode($urow['deposit_amount']), $templateCode);
        if ($AllowUpdate || $AllowInsert) {
            $templateCode = str_replace('<%%HTMLAREA(description)%%>', '<textarea name="description" id="description" rows="5">' . htmlspecialchars($row['description'], ENT_QUOTES) . '</textarea>', $templateCode);
        } else {
            $templateCode = str_replace('<%%HTMLAREA(description)%%>', $row['description'], $templateCode);
        }
        $templateCode = str_replace('<%%VALUE(description)%%>', nl2br($row['description']), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(description)%%>', urlencode($urow['description']), $templateCode);
    } else {
        $templateCode = str_replace('<%%VALUE(id)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(id)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(property)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(property)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(unit_number)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(unit_number)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(photo)%%>', 'blank.gif', $templateCode);
        $templateCode = str_replace('<%%VALUE(status)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(status)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(size)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(size)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(rooms)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(rooms)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(bathroom)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(bathroom)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(features)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(features)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(market_rent)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(market_rent)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(rental_amount)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(rental_amount)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(deposit_amount)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(deposit_amount)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%HTMLAREA(description)%%>', '<textarea name="description" id="description" rows="5"></textarea>', $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 ($_POST['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 .= "\t\$j('[id^=\"{$name}_plink\"]').removeClass('hidden');\n";
        }
        $templateCode .= $jsReadOnly;
        $templateCode .= $jsEditable;
        if (!$selected_id) {
        }
        $templateCode .= "\n});</script>\n";
    }
    // ajaxed auto-fill fields
    $templateCode .= '<script>';
    $templateCode .= '$j(function() {';
    $templateCode .= "\tproperty_update_autofills{$rnd1} = function(){\n";
    $templateCode .= "\t\tnew Ajax.Request(\n";
    if ($dvprint) {
        $templateCode .= "\t\t\t'units_autofill.php?rnd1={$rnd1}&mfk=property&id='+encodeURIComponent('" . addslashes($row['property']) . "'),\n";
        $templateCode .= "\t\t\t{encoding: 'UTF-8', method: 'get'}\n";
    } else {
        $templateCode .= "\t\t\t'units_autofill.php?rnd1={$rnd1}&mfk=property&id=' + encodeURIComponent(current_property{$rnd1}.value),\n";
        $templateCode .= "\t\t\t{encoding: 'UTF-8', method: 'get', onCreate: function(){ \$('property{$rnd1}').disable(); \$('propertyLoading').innerHTML='<img src=loading.gif align=top>'; }, onComplete: function(){" . ($arrPerm[1] || ($arrPerm[3] == 1 && $ownerMemberID == getLoggedMemberID() || $arrPerm[3] == 2 && $ownerGroupID == getLoggedGroupID() || $arrPerm[3] == 3) ? "\$('property{$rnd1}').enable(); " : "\$('property{$rnd1}').disable(); ") . "\$('propertyLoading').innerHTML='';}}\n";
    }
    $templateCode .= "\t\t);\n";
    $templateCode .= "\t};\n";
    if (!$dvprint) {
        $templateCode .= "\tif(\$('property_caption') != undefined) \$('property_caption').onchange=property_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" rel="lightbox\\[.*?\\]"/', 'blank.gif"', $templateCode);
    // don't display empty email links
    $templateCode = preg_replace('/<a .*?href="mailto:".*?<\\/a>/', '', $templateCode);
    // hook: units_dv
    if (function_exists('units_dv')) {
        $args = array();
        units_dv($selected_id ? $selected_id : FALSE, getMemberInfo(), $templateCode, $args);
    }
    return $templateCode;
}
Пример #14
0
function duck_mrs2016_form($selected_id = '', $AllowUpdate = 1, $AllowInsert = 1, $AllowDelete = 1, $ShowCancel = 0)
{
    // 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('duck_mrs2016');
    if (!$arrPerm[1] && $selected_id == '') {
        return '';
    }
    $AllowInsert = $arrPerm[1] ? true : false;
    // print preview?
    $dvprint = false;
    if ($selected_id && $_REQUEST['dvprint_x'] != '') {
        $dvprint = true;
    }
    $filterer_transaction_id = thisOr(undo_magic_quotes($_REQUEST['filterer_transaction_id']), '');
    // populate filterers, starting from children to grand-parents
    // unique random identifier
    $rnd1 = $dvprint ? rand(1000000, 9999999) : '';
    // combobox: transaction_id
    $combo_transaction_id = 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='duck_mrs2016' and pkValue='" . makeSafe($selected_id) . "'");
        $ownerMemberID = sqlValue("select lcase(memberID) from membership_userrecords where tableName='duck_mrs2016' 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 `duck_mrs2016` where `duck_id`='" . makeSafe($selected_id) . "'", $eo);
        if (!($row = db_fetch_array($res))) {
            return error_message($Translation['No records found']);
        }
        $urow = $row;
        /* unsanitized data */
        $hc = new CI_Input();
        $row = $hc->xss_clean($row);
        /* sanitize data */
        $combo_transaction_id->SelectedData = $row['transaction_id'];
    } else {
        $combo_transaction_id->SelectedData = $filterer_transaction_id;
    }
    $combo_transaction_id->HTML = '<span id="transaction_id-container' . $rnd1 . '"></span><input type="hidden" name="transaction_id" id="transaction_id' . $rnd1 . '" value="' . htmlspecialchars($combo_transaction_id->SelectedData, ENT_QUOTES, 'iso-8859-1') . '">';
    $combo_transaction_id->MatchText = '<span id="transaction_id-container-readonly' . $rnd1 . '"></span><input type="hidden" name="transaction_id" id="transaction_id' . $rnd1 . '" value="' . htmlspecialchars($combo_transaction_id->SelectedData, ENT_QUOTES, 'iso-8859-1') . '">';
    ob_start();
    ?>

	<script>
		// initial lookup values
		var current_transaction_id__RAND__ = { text: "", value: "<?php 
    echo addslashes($selected_id ? $urow['transaction_id'] : $filterer_transaction_id);
    ?>
"};

		jQuery(function() {
			if(typeof(transaction_id_reload__RAND__) == 'function') transaction_id_reload__RAND__();
		});
		function transaction_id_reload__RAND__(){
		<?php 
    if (($AllowUpdate || $AllowInsert) && !$dvprint) {
        ?>

			jQuery("#transaction_id-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					jQuery.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: current_transaction_id__RAND__.value, t: 'duck_mrs2016', f: 'transaction_id' }
					}).done(function(resp){
						c({
							id: resp.results[0].id,
							text: resp.results[0].text
						});
						jQuery('[name="transaction_id"]').val(resp.results[0].id);
						jQuery('[id=transaction_id-container-readonly__RAND__]').html('<span id="transaction_id-match-text">' + resp.results[0].text + '</span>');


						if(typeof(transaction_id_update_autofills__RAND__) == 'function') transaction_id_update_autofills__RAND__();
					});
				},
				width: ($j('fieldset .col-xs-11').width() - 99) + 'px',
				formatNoMatches: function(term){ return '<?php 
        echo addslashes($Translation['No matches found!']);
        ?>
'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { s: term, p: page, t: 'duck_mrs2016', f: 'transaction_id' }; },
					results: function(resp, page){ return resp; }
				}
			}).on('change', function(e){
				current_transaction_id__RAND__.value = e.added.id;
				current_transaction_id__RAND__.text = e.added.text;
				jQuery('[name="transaction_id"]').val(e.added.id);


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

			if(!$j("#transaction_id-container__RAND__").length){
				$j.ajax({
					url: 'ajax_combo.php',
					dataType: 'json',
					data: { id: current_transaction_id__RAND__.value, t: 'duck_mrs2016', f: 'transaction_id' }
				}).done(function(resp){
					$j('[name="transaction_id"]').val(resp.results[0].id);
					$j('[id=transaction_id-container-readonly__RAND__]').html('<span id="transaction_id-match-text">' + resp.results[0].text + '</span>');

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

		<?php 
    } else {
        ?>

			jQuery.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: current_transaction_id__RAND__.value, t: 'duck_mrs2016', f: 'transaction_id' }
			}).done(function(resp){
				jQuery('[id=transaction_id-container__RAND__], [id=transaction_id-container-readonly__RAND__]').html('<span id="transaction_id-match-text">' + resp.results[0].text + '</span>');

				if(typeof(transaction_id_update_autofills__RAND__) == 'function') transaction_id_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) {
        $templateCode = @file_get_contents('./templates/duck_mrs2016_templateDVP.html');
    } else {
        $templateCode = @file_get_contents('./templates/duck_mrs2016_templateDV.html');
    }
    // process form title
    $templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Duck mrs2016 details', $templateCode);
    $templateCode = str_replace('<%%RND1%%>', $rnd1, $templateCode);
    $templateCode = str_replace('<%%EMBEDDED%%>', $_REQUEST['Embedded'] ? 'Embedded=1' : '', $templateCode);
    // process buttons
    if ($AllowInsert) {
        if (!$selected_id) {
            $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-success" id="insert" name="insert_x" value="1" onclick="return duck_mrs2016_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 duck_mrs2016_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 = 'window.parent.jQuery(\'.modal\').modal(\'hide\'); return false;';
    } else {
        $backAction = '$$(\'form\')[0].writeAttribute(\'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="$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;"><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 duck_mrs2016_validateData();"><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?'] . '\');"><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 . '"><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 . '"><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('#transaction_id').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#transaction_id_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(transaction_id)%%>', $combo_transaction_id->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(transaction_id)%%>', $combo_transaction_id->MatchText, $templateCode);
    $templateCode = str_replace('<%%URLCOMBOTEXT(transaction_id)%%>', urlencode($combo_transaction_id->MatchText), $templateCode);
    /* lookup fields array: 'lookup field name' => array('parent table name', 'lookup field caption') */
    $lookup_fields = array('transaction_id' => array('trans_mrs2016', 'Transactie nr'));
    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-lg" id="' . $ptfc[0] . '_view_parent" title="' . htmlspecialchars($Translation['View'] . ' ' . $ptfc[1], ENT_QUOTES, 'iso-8859-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" id="' . $ptfc[0] . '_add_new" title="' . htmlspecialchars($Translation['Add New'] . ' ' . $ptfc[1], ENT_QUOTES, 'iso-8859-1') . '"><i class="glyphicon glyphicon-plus-sign"></i></button>', $templateCode);
        }
    }
    // process images
    $templateCode = str_replace('<%%UPLOADFILE(duck_id)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(transaction_id)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(creationdate)%%>', '', $templateCode);
    // process values
    if ($selected_id) {
        $templateCode = str_replace('<%%VALUE(duck_id)%%>', htmlspecialchars($row['duck_id'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(duck_id)%%>', urlencode($urow['duck_id']), $templateCode);
        $templateCode = str_replace('<%%VALUE(transaction_id)%%>', htmlspecialchars($row['transaction_id'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(transaction_id)%%>', urlencode($urow['transaction_id']), $templateCode);
        $templateCode = str_replace('<%%VALUE(creationdate)%%>', htmlspecialchars($row['creationdate'], ENT_QUOTES, 'iso-8859-1'), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(creationdate)%%>', urlencode($urow['creationdate']), $templateCode);
    } else {
        $templateCode = str_replace('<%%VALUE(duck_id)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(duck_id)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(transaction_id)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(transaction_id)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(creationdate)%%>', '<%%creationDate%%>', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(creationdate)%%>', urlencode('<%%creationDate%%>'), $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);
    // hook: duck_mrs2016_dv
    if (function_exists('duck_mrs2016_dv')) {
        $args = array();
        duck_mrs2016_dv($selected_id ? $selected_id : FALSE, getMemberInfo(), $templateCode, $args);
    }
    return $templateCode;
}
Пример #15
0
function companies_form($selected_id = '', $AllowUpdate = 1, $AllowInsert = 1, $AllowDelete = 1, $ShowCancel = 0)
{
    // 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('companies');
    if (!$arrPerm[1] && $selected_id == '') {
        return '';
    }
    // print preview?
    $dvprint = false;
    if ($selected_id && $_REQUEST['dvprint_x'] != '') {
        $dvprint = true;
    }
    $filterer_client = thisOr(undo_magic_quotes($_REQUEST['filterer_client']), '');
    $filterer_sic_code = thisOr(undo_magic_quotes($_REQUEST['filterer_sic_code']), '');
    // populate filterers, starting from children to grand-parents
    // unique random identifier
    $rnd1 = $dvprint ? rand(1000000, 9999999) : '';
    // combobox: client
    $combo_client = new DataCombo();
    // combobox: industry
    $combo_industry = new Combo();
    $combo_industry->ListType = 0;
    $combo_industry->MultipleSeparator = ', ';
    $combo_industry->ListBoxHeight = 10;
    $combo_industry->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/companies.industry.csv')) {
        $industry_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/companies.industry.csv')));
        $combo_industry->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($industry_data)));
        $combo_industry->ListData = $combo_industry->ListItem;
    } else {
        $combo_industry->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Automobiles and parts;;Business services;;Carbon offsetting and trading;;Charitable services and fundraising;;Chemicals;;Clothing retail;;Construction;;Consulting;;Consumer electronics;;Consumer goods and services (other);;Eating and drinking places;;Education;;Energy and Water;;Financial services;;Food and beverages retail;;Food producers;;Forestry and paper;;Health;;Household goods;;Internet platforms;;Leisure goods;;Media;;Other;;Personal goods;;Recycling and waste management;;Residential and commercial property;;Retail (general);;Telecoms;;Training and employment;;Transport;;Travel, tourism and leisure")));
        $combo_industry->ListData = $combo_industry->ListItem;
    }
    $combo_industry->SelectName = 'industry';
    // combobox: country_hq
    $combo_country_hq = new Combo();
    $combo_country_hq->ListType = 0;
    $combo_country_hq->MultipleSeparator = ', ';
    $combo_country_hq->ListBoxHeight = 10;
    $combo_country_hq->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/companies.country_hq.csv')) {
        $country_hq_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/companies.country_hq.csv')));
        $combo_country_hq->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($country_hq_data)));
        $combo_country_hq->ListData = $combo_country_hq->ListItem;
    } else {
        $combo_country_hq->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Afghanistan;;Albania;;Algeria;;American Samoa;;Andorra;;Angola;;Anguilla;;Antarctica;;Antigua, Barbuda;;Argentina;;Armenia;;Aruba;;Australia;;Austria;;Azerbaijan;;Bahamas;;Bahrain;;Bangladesh;;Barbados;;Belarus;;Belgium;;Belize;;Benin;;Bermuda;;Bhutan;;Bolivia;;Bosnia, Herzegovina;;Botswana;;Bouvet Is.;;Brazil;;Brunei Darussalam;;Bulgaria;;Burkina Faso;;Burundi;;Cambodia;;Cameroon;;Canada;;Canary Is.;;Cape Verde;;Cayman Is.;;Central African Rep.;;Chad;;Channel Islands;;Chile;;China;;Christmas Is.;;Cocos Is.;;Colombia;;Comoros;;Congo, D.R. Of;;Congo;;Cook Is.;;Costa Rica;;Croatia;;Cuba;;Cyprus;;Czech Republic;;Denmark;;Djibouti;;Dominica;;Dominican Republic;;Ecuador;;Egypt;;El Salvador;;Equatorial Guinea;;Eritrea;;Estonia;;Ethiopia;;Falkland Is.;;Faroe Is.;;Fiji;;Finland;;France;;French Guiana;;French Polynesia;;French Territories;;Gabon;;Gambia;;Georgia;;Germany;;Ghana;;Gibraltar;;Greece;;Greenland;;Grenada;;Guadeloupe;;Guam;;Guatemala;;Guernsey;;Guinea-bissau;;Guinea;;Guyana;;Haiti;;Heard, Mcdonald Is.;;Honduras;;Hong Kong;;Hungary;;Iceland;;India;;Indonesia;;Iran;;Iraq;;Ireland;;Israel;;Italy;;Ivory Coast;;Jamaica;;Japan;;Jersey;;Jordan;;Kazakhstan;;Kenya;;Kiribati;;Korea, D.P.R Of;;Korea, Rep. Of;;Kuwait;;Kyrgyzstan;;Lao Peoples D.R.;;Latvia;;Lebanon;;Lesotho;;Liberia;;Libyan Arab Jamahiriya;;Liechtenstein;;Lithuania;;Luxembourg;;Macao;;Macedonia, F.Y.R Of;;Madagascar;;Malawi;;Malaysia;;Maldives;;Mali;;Malta;;Mariana Islands;;Marshall Islands;;Martinique;;Mauritania;;Mauritius;;Mayotte;;Mexico;;Micronesia;;Moldova;;Monaco;;Mongolia;;Montserrat;;Morocco;;Mozambique;;Myanmar;;Namibia;;Nauru;;Nepal;;Netherlands Antilles;;Netherlands;;New Caledonia;;New Zealand;;Nicaragua;;Niger;;Nigeria;;Niue;;Norfolk Island;;Norway;;Oman;;Pakistan;;Palau;;Palestinian Terr.;;Panama;;Papua New Guinea;;Paraguay;;Peru;;Philippines;;Pitcairn;;Poland;;Portugal;;Puerto Rico;;Qatar;;Reunion;;Romania;;Russian Federation;;Rwanda;;Samoa;;San Marino;;Sao Tome, Principe;;Saudi Arabia;;Senegal;;Seychelles;;Sierra Leone;;Singapore;;Slovakia;;Slovenia;;Solomon Is.;;Somalia;;South Africa;;South Georgia;;South Sandwich Is.;;Spain;;Sri Lanka;;St. Helena;;St. Kitts, Nevis;;St. Lucia;;St. Pierre, Miquelon;;St. Vincent, Grenadines;;Sudan;;Suriname;;Svalbard, Jan Mayen;;Swaziland;;Sweden;;Switzerland;;Syrian Arab Republic;;Taiwan;;Tajikistan;;Tanzania;;Thailand;;Timor-leste;;Togo;;Tokelau;;Tonga;;Trinidad, Tobago;;Tunisia;;Turkey;;Turkmenistan;;Turks, Caicoss;;Tuvalu;;Uganda;;Ukraine;;United Arab Emirates;;United Kingdom;;United States;;Uruguay;;Uzbekistan;;Vanuatu;;Vatican City;;Venezuela;;Viet Nam;;Virgin Is. British;;Virgin Is. U.S.;;Wallis, Futuna;;Western Sahara;;Yemen;;Yugoslavia;;Zambia;;Zimbabwe")));
        $combo_country_hq->ListData = $combo_country_hq->ListItem;
    }
    $combo_country_hq->SelectName = 'country_hq';
    // combobox: country_operations
    $combo_country_operations = new Combo();
    $combo_country_operations->ListType = 3;
    $combo_country_operations->MultipleSeparator = ', ';
    $combo_country_operations->ListBoxHeight = 10;
    $combo_country_operations->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/companies.country_operations.csv')) {
        $country_operations_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/companies.country_operations.csv')));
        $combo_country_operations->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($country_operations_data)));
        $combo_country_operations->ListData = $combo_country_operations->ListItem;
    } else {
        $combo_country_operations->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Afghanistan;;Albania;;Algeria;;American Samoa;;Andorra;;Angola;;Anguilla;;Antarctica;;Antigua, Barbuda;;Argentina;;Armenia;;Aruba;;Australia;;Austria;;Azerbaijan;;Bahamas;;Bahrain;;Bangladesh;;Barbados;;Belarus;;Belgium;;Belize;;Benin;;Bermuda;;Bhutan;;Bolivia;;Bosnia, Herzegovina;;Botswana;;Bouvet Is.;;Brazil;;Brunei Darussalam;;Bulgaria;;Burkina Faso;;Burundi;;Cambodia;;Cameroon;;Canada;;Canary Is.;;Cape Verde;;Cayman Is.;;Central African Rep.;;Chad;;Channel Islands;;Chile;;China;;Christmas Is.;;Cocos Is.;;Colombia;;Comoros;;Congo, D.R. Of;;Congo;;Cook Is.;;Costa Rica;;Croatia;;Cuba;;Cyprus;;Czech Republic;;Denmark;;Djibouti;;Dominica;;Dominican Republic;;Ecuador;;Egypt;;El Salvador;;Equatorial Guinea;;Eritrea;;Estonia;;Ethiopia;;Falkland Is.;;Faroe Is.;;Fiji;;Finland;;France;;French Guiana;;French Polynesia;;French Territories;;Gabon;;Gambia;;Georgia;;Germany;;Ghana;;Gibraltar;;Greece;;Greenland;;Grenada;;Guadeloupe;;Guam;;Guatemala;;Guernsey;;Guinea-bissau;;Guinea;;Guyana;;Haiti;;Heard, Mcdonald Is.;;Honduras;;Hong Kong;;Hungary;;Iceland;;India;;Indonesia;;Iran;;Iraq;;Ireland;;Israel;;Italy;;Ivory Coast;;Jamaica;;Japan;;Jersey;;Jordan;;Kazakhstan;;Kenya;;Kiribati;;Korea, D.P.R Of;;Korea, Rep. Of;;Kuwait;;Kyrgyzstan;;Lao Peoples D.R.;;Latvia;;Lebanon;;Lesotho;;Liberia;;Libyan Arab Jamahiriya;;Liechtenstein;;Lithuania;;Luxembourg;;Macao;;Macedonia, F.Y.R Of;;Madagascar;;Malawi;;Malaysia;;Maldives;;Mali;;Malta;;Mariana Islands;;Marshall Islands;;Martinique;;Mauritania;;Mauritius;;Mayotte;;Mexico;;Micronesia;;Moldova;;Monaco;;Mongolia;;Montserrat;;Morocco;;Mozambique;;Myanmar;;Namibia;;Nauru;;Nepal;;Netherlands Antilles;;Netherlands;;New Caledonia;;New Zealand;;Nicaragua;;Niger;;Nigeria;;Niue;;Norfolk Island;;Norway;;Oman;;Pakistan;;Palau;;Palestinian Terr.;;Panama;;Papua New Guinea;;Paraguay;;Peru;;Philippines;;Pitcairn;;Poland;;Portugal;;Puerto Rico;;Qatar;;Reunion;;Romania;;Russian Federation;;Rwanda;;Samoa;;San Marino;;Sao Tome, Principe;;Saudi Arabia;;Senegal;;Seychelles;;Sierra Leone;;Singapore;;Slovakia;;Slovenia;;Solomon Is.;;Somalia;;South Africa;;South Georgia;;South Sandwich Is.;;Spain;;Sri Lanka;;St. Helena;;St. Kitts, Nevis;;St. Lucia;;St. Pierre, Miquelon;;St. Vincent, Grenadines;;Sudan;;Suriname;;Svalbard, Jan Mayen;;Swaziland;;Sweden;;Switzerland;;Syrian Arab Republic;;Taiwan;;Tajikistan;;Tanzania;;Thailand;;Timor-leste;;Togo;;Tokelau;;Tonga;;Trinidad, Tobago;;Tunisia;;Turkey;;Turkmenistan;;Turks, Caicoss;;Tuvalu;;Uganda;;Ukraine;;United Arab Emirates;;United Kingdom;;United States;;Uruguay;;Uzbekistan;;Vanuatu;;Vatican City;;Venezuela;;Viet Nam;;Virgin Is. British;;Virgin Is. U.S.;;Wallis, Futuna;;Western Sahara;;Yemen;;Yugoslavia;;Zambia;;Zimbabwe")));
        $combo_country_operations->ListData = $combo_country_operations->ListItem;
    }
    $combo_country_operations->SelectName = 'country_operations';
    // combobox: company_type
    $combo_company_type = new Combo();
    $combo_company_type->ListType = 0;
    $combo_company_type->MultipleSeparator = ', ';
    $combo_company_type->ListBoxHeight = 10;
    $combo_company_type->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/companies.company_type.csv')) {
        $company_type_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/companies.company_type.csv')));
        $combo_company_type->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($company_type_data)));
        $combo_company_type->ListData = $combo_company_type->ListItem;
    } else {
        $combo_company_type->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("501(c);;AG;;BV;;CIC;;Company limited by guarantee;;Cooperative;;GmbH;;Inc;;IPS;;L3C;;LLP;;LP;;Ltd;;Ltda;;Non-incorporated partnership;;Not stated;;NV;;PLC;;Private company limited by shares;;Royal Charter;;SA;;SARL;;Societas Europaea;;Sole trader;;Subsidiary;;Unincorporated;;Unlimited")));
        $combo_company_type->ListData = $combo_company_type->ListItem;
    }
    $combo_company_type->SelectName = 'company_type';
    // combobox: sic_code
    $combo_sic_code = new DataCombo();
    // combobox: created
    $combo_created = new DateCombo();
    $combo_created->DateFormat = "dmy";
    $combo_created->MinYear = 1900;
    $combo_created->MaxYear = 2100;
    $combo_created->DefaultDate = parseMySQLDate('<%%creationDate%%>', '<%%creationDate%%>');
    $combo_created->MonthNames = $Translation['month names'];
    $combo_created->NamePrefix = 'created';
    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='companies' and pkValue='" . makeSafe($selected_id) . "'");
        $ownerMemberID = sqlValue("select lcase(memberID) from membership_userrecords where tableName='companies' 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 `companies` where `company_id`='" . makeSafe($selected_id) . "'", $eo);
        $row = mysql_fetch_array($res);
        $urow = $row;
        /* unsanitized data */
        $hc = new CI_Input();
        $row = $hc->xss_clean($row);
        /* sanitize data */
        $combo_client->SelectedData = $row['client'];
        $combo_industry->SelectedData = $row['industry'];
        $combo_country_hq->SelectedData = $row['country_hq'];
        $combo_country_operations->SelectedData = $row['country_operations'];
        $combo_company_type->SelectedData = $row['company_type'];
        $combo_sic_code->SelectedData = $row['sic_code'];
        $combo_created->DefaultDate = $row['created'];
    } else {
        $combo_client->SelectedData = $filterer_client;
        $combo_industry->SelectedText = $_REQUEST['FilterField'][1] == '7' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "";
        $combo_country_hq->SelectedText = $_REQUEST['FilterField'][1] == '9' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "United Kingdom";
        $combo_company_type->SelectedText = $_REQUEST['FilterField'][1] == '12' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "";
        $combo_sic_code->SelectedData = $filterer_sic_code;
    }
    $combo_client->HTML = $combo_client->MatchText = '<span id="client-container' . $rnd1 . '"></span><input type="hidden" name="client" id="client' . $rnd1 . '">';
    $combo_industry->Render();
    $combo_country_hq->Render();
    $combo_country_operations->Render();
    $combo_company_type->Render();
    $combo_sic_code->HTML = $combo_sic_code->MatchText = '<span id="sic_code-container' . $rnd1 . '"></span><input type="hidden" name="sic_code" id="sic_code' . $rnd1 . '">';
    ob_start();
    ?>

	<script>
		// initial lookup values
		var current_client__RAND__ = { text: "", value: "<?php 
    echo addslashes($selected_id ? $urow['client'] : $filterer_client);
    ?>
"};
		var current_sic_code__RAND__ = { text: "", value: "<?php 
    echo addslashes($selected_id ? $urow['sic_code'] : $filterer_sic_code);
    ?>
"};
		
		jQuery(function() {
			client_reload__RAND__();
			sic_code_reload__RAND__();
		});
		function client_reload__RAND__(){
		<?php 
    if (($AllowUpdate || $AllowInsert) && !$dvprint) {
        ?>

			jQuery("#client-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					jQuery.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: current_client__RAND__.value, t: 'companies', f: 'client' }
					}).done(function(resp){
						c({
							id: resp.results[0].id,
							text: resp.results[0].text
						});
						jQuery('[name="client"]').val(resp.results[0].id);


						if(typeof(client_update_autofills__RAND__) == 'function') client_update_autofills__RAND__();
					});
				},
				width: '100%',
				formatNoMatches: function(term){ return '<?php 
        echo addslashes($Translation['No matches found!']);
        ?>
'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { s: term, p: page, t: 'companies', f: 'client' }; },
					results: function(resp, page){ return resp; }
				}
			}).on('change', function(e){
				current_client__RAND__.value = e.added.id;
				current_client__RAND__.text = e.added.text;
				jQuery('[name="client"]').val(e.added.id);


				if(typeof(client_update_autofills__RAND__) == 'function') client_update_autofills__RAND__();
			});
		<?php 
    } else {
        ?>

			jQuery.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: current_client__RAND__.value, t: 'companies', f: 'client' }
			}).done(function(resp){
				jQuery('#client-container__RAND__').html('<span id="client-match-text">' + resp.results[0].text + '</span>');

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

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

			jQuery("#sic_code-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					jQuery.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: current_sic_code__RAND__.value, t: 'companies', f: 'sic_code' }
					}).done(function(resp){
						c({
							id: resp.results[0].id,
							text: resp.results[0].text
						});
						jQuery('[name="sic_code"]').val(resp.results[0].id);


						if(typeof(sic_code_update_autofills__RAND__) == 'function') sic_code_update_autofills__RAND__();
					});
				},
				width: '100%',
				formatNoMatches: function(term){ return '<?php 
        echo addslashes($Translation['No matches found!']);
        ?>
'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { s: term, p: page, t: 'companies', f: 'sic_code' }; },
					results: function(resp, page){ return resp; }
				}
			}).on('change', function(e){
				current_sic_code__RAND__.value = e.added.id;
				current_sic_code__RAND__.text = e.added.text;
				jQuery('[name="sic_code"]').val(e.added.id);


				if(typeof(sic_code_update_autofills__RAND__) == 'function') sic_code_update_autofills__RAND__();
			});
		<?php 
    } else {
        ?>

			jQuery.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: current_sic_code__RAND__.value, t: 'companies', f: 'sic_code' }
			}).done(function(resp){
				jQuery('#sic_code-container__RAND__').html('<span id="sic_code-match-text">' + resp.results[0].text + '</span>');

				if(typeof(sic_code_update_autofills__RAND__) == 'function') sic_code_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) {
        $templateCode = @file_get_contents('./templates/companies_templateDVP.html');
    } else {
        $templateCode = @file_get_contents('./templates/companies_templateDV.html');
    }
    // process form title
    $templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Company details', $templateCode);
    $templateCode = str_replace('<%%RND1%%>', $rnd1, $templateCode);
    // process buttons
    if ($arrPerm[1]) {
        // allow insert?
        if (!$selected_id) {
            $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-success" id="insert" name="insert_x" value="1" onclick="return companies_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save New'] . '</button>', $templateCode);
        }
        $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-default" id="insert" name="insert_x" value="1" onclick="return companies_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 = 'window.parent.jQuery(\'.modal\').modal(\'hide\'); return false;';
    } else {
        $backAction = '$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;';
    }
    if ($selected_id) {
        if (!$_REQUEST['Embedded']) {
            $templateCode = str_replace('<%%DVPRINT_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-default" id="dvprint" name="dvprint_x" value="1" onclick="$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;"><i class="glyphicon glyphicon-print"></i> ' . $Translation['Print Preview'] . '</button>', $templateCode);
        }
        if ($AllowUpdate) {
            $templateCode = str_replace('<%%UPDATE_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-success btn-lg" id="update" name="update_x" value="1" onclick="return companies_validateData();"><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 tabindex="2" type="submit" class="btn btn-danger" id="delete" name="delete_x" value="1" onclick="return confirm(\'' . $Translation['are you sure?'] . '\');"><i class="glyphicon glyphicon-trash"></i> ' . $Translation['Delete'] . '</button>', $templateCode);
        } else {
            $templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
        }
        $templateCode = str_replace('<%%DESELECT_BUTTON%%>', '<button tabindex="2" type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><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 tabindex="2" type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '"><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 && !$arrPerm[1] || !$selected_id && !$arrPerm[1]) {
        $jsReadOnly .= "\tjQuery('#name').replaceWith('<p class=\"form-control-static\" id=\"name\">' + (jQuery('#name').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#client').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#client_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
        $jsReadOnly .= "\tjQuery('#website').replaceWith('<p class=\"form-control-static\" id=\"website\">' + (jQuery('#website').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#website, #website-edit-link').hide();\n";
        $jsReadOnly .= "\tjQuery('#description').replaceWith('<p class=\"form-control-static\" id=\"description\">' + (jQuery('#description').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#founded').replaceWith('<p class=\"form-control-static\" id=\"founded\">' + (jQuery('#founded').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#industry').replaceWith('<p class=\"form-control-static\" id=\"industry\">' + (jQuery('#industry').val() || '') + '</p>'); jQuery('#industry-multi-selection-help').hide();\n";
        $jsReadOnly .= "\tjQuery('#company_number').replaceWith('<p class=\"form-control-static\" id=\"company_number\">' + (jQuery('#company_number').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#country_hq').replaceWith('<p class=\"form-control-static\" id=\"country_hq\">' + (jQuery('#country_hq').val() || '') + '</p>'); jQuery('#country_hq-multi-selection-help').hide();\n";
        $jsReadOnly .= "\tjQuery('#country_operations').replaceWith('<p class=\"form-control-static\" id=\"country_operations\">' + (jQuery('#country_operations').val() || '') + '</p>'); jQuery('#country_operations-multi-selection-help').hide();\n";
        $jsReadOnly .= "\tjQuery('#s2id_country_operations').remove();\n";
        $jsReadOnly .= "\tjQuery('#num_employees').replaceWith('<p class=\"form-control-static\" id=\"num_employees\">' + (jQuery('#num_employees').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#company_type').replaceWith('<p class=\"form-control-static\" id=\"company_type\">' + (jQuery('#company_type').val() || '') + '</p>'); jQuery('#company_type-multi-selection-help').hide();\n";
        $jsReadOnly .= "\tjQuery('#sic_code').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#sic_code_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
        $noUploads = true;
    }
    // process combos
    $templateCode = str_replace('<%%COMBO(client)%%>', $combo_client->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(client)%%>', $combo_client->MatchText, $templateCode);
    $templateCode = str_replace('<%%URLCOMBOTEXT(client)%%>', urlencode($combo_client->MatchText), $templateCode);
    $templateCode = str_replace('<%%COMBO(industry)%%>', $combo_industry->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(industry)%%>', $combo_industry->SelectedData, $templateCode);
    $templateCode = str_replace('<%%COMBO(country_hq)%%>', $combo_country_hq->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(country_hq)%%>', $combo_country_hq->SelectedData, $templateCode);
    $templateCode = str_replace('<%%COMBO(country_operations)%%>', $combo_country_operations->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(country_operations)%%>', $combo_country_operations->SelectedData, $templateCode);
    $templateCode = str_replace('<%%COMBO(company_type)%%>', $combo_company_type->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(company_type)%%>', $combo_company_type->SelectedData, $templateCode);
    $templateCode = str_replace('<%%COMBO(sic_code)%%>', $combo_sic_code->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(sic_code)%%>', $combo_sic_code->MatchText, $templateCode);
    $templateCode = str_replace('<%%URLCOMBOTEXT(sic_code)%%>', urlencode($combo_sic_code->MatchText), $templateCode);
    $templateCode = str_replace('<%%COMBO(created)%%>', $selected_id && !$arrPerm[3] ? '<p class="form-control-static">' . $combo_created->GetHTML(true) . '</p>' : $combo_created->GetHTML(), $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(created)%%>', $combo_created->GetHTML(true), $templateCode);
    // process foreign key links
    if ($selected_id) {
        $templateCode = str_replace('<%%PLINK(client)%%>', $combo_client->SelectedData ? "<span id=\"clients_plink1\" class=\"hidden\"><a class=\"btn btn-default\" href=\"clients_view.php?SelectedID=" . urlencode($combo_client->SelectedData) . "\"><i class=\"glyphicon glyphicon-search\"></i></a></span>" : '', $templateCode);
        $templateCode = str_replace('<%%PLINK(sic_code)%%>', $combo_sic_code->SelectedData ? "<span id=\"sic_plink2\" class=\"hidden\"><a class=\"btn btn-default\" href=\"sic_view.php?SelectedID=" . urlencode($combo_sic_code->SelectedData) . "\"><i class=\"glyphicon glyphicon-search\"></i></a></span>" : '', $templateCode);
    }
    // process images
    $templateCode = str_replace('<%%UPLOADFILE(company_id)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(name)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(client)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(website)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(description)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(founded)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(industry)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(company_number)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(country_hq)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(country_operations)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(num_employees)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(company_type)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(sic_code)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(created)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(created_by)%%>', '', $templateCode);
    // process values
    if ($selected_id) {
        $templateCode = str_replace('<%%VALUE(company_id)%%>', htmlspecialchars($row['company_id'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(company_id)%%>', urlencode($urow['company_id']), $templateCode);
        $templateCode = str_replace('<%%VALUE(name)%%>', htmlspecialchars($row['name'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(name)%%>', urlencode($urow['name']), $templateCode);
        $templateCode = str_replace('<%%VALUE(client)%%>', htmlspecialchars($row['client'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(client)%%>', urlencode($urow['client']), $templateCode);
        $templateCode = str_replace('<%%VALUE(website)%%>', htmlspecialchars($row['website'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(website)%%>', urlencode($urow['website']), $templateCode);
        $templateCode = str_replace('<%%VALUE(description)%%>', htmlspecialchars($row['description'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(description)%%>', urlencode($urow['description']), $templateCode);
        $templateCode = str_replace('<%%VALUE(founded)%%>', htmlspecialchars($row['founded'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(founded)%%>', urlencode($urow['founded']), $templateCode);
        $templateCode = str_replace('<%%VALUE(industry)%%>', htmlspecialchars($row['industry'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(industry)%%>', urlencode($urow['industry']), $templateCode);
        $templateCode = str_replace('<%%VALUE(company_number)%%>', htmlspecialchars($row['company_number'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(company_number)%%>', urlencode($urow['company_number']), $templateCode);
        $templateCode = str_replace('<%%VALUE(country_hq)%%>', htmlspecialchars($row['country_hq'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(country_hq)%%>', urlencode($urow['country_hq']), $templateCode);
        $templateCode = str_replace('<%%VALUE(country_operations)%%>', htmlspecialchars($row['country_operations'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(country_operations)%%>', urlencode($urow['country_operations']), $templateCode);
        $templateCode = str_replace('<%%VALUE(num_employees)%%>', htmlspecialchars($row['num_employees'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(num_employees)%%>', urlencode($urow['num_employees']), $templateCode);
        $templateCode = str_replace('<%%VALUE(company_type)%%>', htmlspecialchars($row['company_type'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(company_type)%%>', urlencode($urow['company_type']), $templateCode);
        $templateCode = str_replace('<%%VALUE(sic_code)%%>', htmlspecialchars($row['sic_code'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(sic_code)%%>', urlencode($urow['sic_code']), $templateCode);
        $templateCode = str_replace('<%%VALUE(created)%%>', @date('d/m/Y', @strtotime(htmlspecialchars($row['created'], ENT_QUOTES))), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(created)%%>', urlencode(@date('d/m/Y', @strtotime(htmlspecialchars($urow['created'], ENT_QUOTES)))), $templateCode);
        $templateCode = str_replace('<%%VALUE(created_by)%%>', htmlspecialchars($row['created_by'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(created_by)%%>', urlencode($urow['created_by']), $templateCode);
    } else {
        $templateCode = str_replace('<%%VALUE(company_id)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(company_id)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(name)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(name)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(client)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(client)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(website)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(website)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(description)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(description)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(founded)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(founded)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(industry)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(industry)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(company_number)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(company_number)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(country_hq)%%>', 'United Kingdom', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(country_hq)%%>', urlencode('United Kingdom'), $templateCode);
        $templateCode = str_replace('<%%VALUE(country_operations)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(country_operations)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(num_employees)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(num_employees)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(company_type)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(company_type)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(sic_code)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(sic_code)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(created)%%>', '<%%creationDate%%>', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(created)%%>', urlencode('<%%creationDate%%>'), $templateCode);
        $templateCode = str_replace('<%%VALUE(created_by)%%>', '<%%creatorUsername%%>', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(created_by)%%>', 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 ($_POST['dvprint_x'] == '') {
        $templateCode .= "\n\n<script>jQuery(function(){\n";
        $arrTables = getTableList();
        foreach ($arrTables as $name => $caption) {
            $templateCode .= "\tjQuery('#{$name}_link').removeClass('hidden');\n";
            $templateCode .= "\tjQuery('#xs_{$name}_link').removeClass('hidden');\n";
            $templateCode .= "\tjQuery('[id^=\"{$name}_plink\"]').removeClass('hidden');\n";
        }
        $templateCode .= $jsReadOnly;
        if (!$selected_id) {
            $templateCode .= "\n\tif(document.getElementById('websiteEdit')){ document.getElementById('websiteEdit').style.display='inline'; }";
            $templateCode .= "\n\tif(document.getElementById('websiteEditLink')){ document.getElementById('websiteEditLink').style.display='none'; }";
        }
        $templateCode .= "\n});</script>\n";
    }
    // ajaxed auto-fill fields
    $templateCode .= "<script>";
    $templateCode .= "document.observe('dom:loaded', 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" rel="lightbox\\[.*?\\]"/', 'blank.gif"', $templateCode);
    // don't display empty email links
    $templateCode = preg_replace('/<a .*?href="mailto:".*?<\\/a>/', '', $templateCode);
    // hook: companies_dv
    if (function_exists('companies_dv')) {
        $args = array();
        companies_dv($selected_id ? $selected_id : FALSE, getMemberInfo(), $templateCode, $args);
    }
    return $templateCode;
}
function applications_leases_form($selected_id = '', $AllowUpdate = 1, $AllowInsert = 1, $AllowDelete = 1, $ShowCancel = 0)
{
    // 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('applications_leases');
    if (!$arrPerm[1] && $selected_id == '') {
        return '';
    }
    $AllowInsert = $arrPerm[1] ? true : false;
    // print preview?
    $dvprint = false;
    if ($selected_id && $_REQUEST['dvprint_x'] != '') {
        $dvprint = true;
    }
    $filterer_tenants = thisOr(undo_magic_quotes($_REQUEST['filterer_tenants']), '');
    $filterer_property = thisOr(undo_magic_quotes($_REQUEST['filterer_property']), '');
    $filterer_unit = thisOr(undo_magic_quotes($_REQUEST['filterer_unit']), '');
    // populate filterers, starting from children to grand-parents
    if ($filterer_unit && !$filterer_property) {
        $filterer_property = sqlValue("select property from units where id='" . makeSafe($filterer_unit) . "'");
    }
    // unique random identifier
    $rnd1 = $dvprint ? rand(1000000, 9999999) : '';
    // combobox: tenants
    $combo_tenants = new DataCombo();
    // combobox: status
    $combo_status = new Combo();
    $combo_status->ListType = 2;
    $combo_status->MultipleSeparator = ', ';
    $combo_status->ListBoxHeight = 10;
    $combo_status->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/applications_leases.status.csv')) {
        $status_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/applications_leases.status.csv')));
        $combo_status->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($status_data)));
        $combo_status->ListData = $combo_status->ListItem;
    } else {
        $combo_status->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Application;;Lease;;Historical lease")));
        $combo_status->ListData = $combo_status->ListItem;
    }
    $combo_status->SelectName = 'status';
    $combo_status->AllowNull = false;
    // combobox: property
    $combo_property = new DataCombo();
    // combobox: unit, filterable by: property
    $combo_unit = new DataCombo();
    // combobox: type
    $combo_type = new Combo();
    $combo_type->ListType = 2;
    $combo_type->MultipleSeparator = ', ';
    $combo_type->ListBoxHeight = 10;
    $combo_type->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/applications_leases.type.csv')) {
        $type_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/applications_leases.type.csv')));
        $combo_type->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($type_data)));
        $combo_type->ListData = $combo_type->ListItem;
    } else {
        $combo_type->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Fixed;;Fixed with rollover;;At-will")));
        $combo_type->ListData = $combo_type->ListItem;
    }
    $combo_type->SelectName = 'type';
    $combo_type->AllowNull = false;
    // combobox: start_date
    $combo_start_date = new DateCombo();
    $combo_start_date->DateFormat = "mdy";
    $combo_start_date->MinYear = 1900;
    $combo_start_date->MaxYear = 2100;
    $combo_start_date->DefaultDate = parseMySQLDate('1', '1');
    $combo_start_date->MonthNames = $Translation['month names'];
    $combo_start_date->NamePrefix = 'start_date';
    // combobox: end_date
    $combo_end_date = new DateCombo();
    $combo_end_date->DateFormat = "mdy";
    $combo_end_date->MinYear = 1900;
    $combo_end_date->MaxYear = 2100;
    $combo_end_date->DefaultDate = parseMySQLDate('1', '1');
    $combo_end_date->MonthNames = $Translation['month names'];
    $combo_end_date->NamePrefix = 'end_date';
    // combobox: recurring_charges_frequency
    $combo_recurring_charges_frequency = new Combo();
    $combo_recurring_charges_frequency->ListType = 0;
    $combo_recurring_charges_frequency->MultipleSeparator = ', ';
    $combo_recurring_charges_frequency->ListBoxHeight = 10;
    $combo_recurring_charges_frequency->RadiosPerLine = 1;
    if (is_file(dirname(__FILE__) . '/hooks/applications_leases.recurring_charges_frequency.csv')) {
        $recurring_charges_frequency_data = addslashes(implode('', @file(dirname(__FILE__) . '/hooks/applications_leases.recurring_charges_frequency.csv')));
        $combo_recurring_charges_frequency->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($recurring_charges_frequency_data)));
        $combo_recurring_charges_frequency->ListData = $combo_recurring_charges_frequency->ListItem;
    } else {
        $combo_recurring_charges_frequency->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Daily;;Weekly;;Every two weeks;;Monthly;;Every two months;;Quarterly;;Every six months;;Yearly;;One time")));
        $combo_recurring_charges_frequency->ListData = $combo_recurring_charges_frequency->ListItem;
    }
    $combo_recurring_charges_frequency->SelectName = 'recurring_charges_frequency';
    $combo_recurring_charges_frequency->AllowNull = false;
    // combobox: next_due_date
    $combo_next_due_date = new DateCombo();
    $combo_next_due_date->DateFormat = "mdy";
    $combo_next_due_date->MinYear = 1900;
    $combo_next_due_date->MaxYear = 2100;
    $combo_next_due_date->DefaultDate = parseMySQLDate('1', '1');
    $combo_next_due_date->MonthNames = $Translation['month names'];
    $combo_next_due_date->NamePrefix = 'next_due_date';
    // combobox: security_deposit_date
    $combo_security_deposit_date = new DateCombo();
    $combo_security_deposit_date->DateFormat = "mdy";
    $combo_security_deposit_date->MinYear = 1900;
    $combo_security_deposit_date->MaxYear = 2100;
    $combo_security_deposit_date->DefaultDate = parseMySQLDate('', '');
    $combo_security_deposit_date->MonthNames = $Translation['month names'];
    $combo_security_deposit_date->NamePrefix = 'security_deposit_date';
    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='applications_leases' and pkValue='" . makeSafe($selected_id) . "'");
        $ownerMemberID = sqlValue("select lcase(memberID) from membership_userrecords where tableName='applications_leases' 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 `applications_leases` where `id`='" . makeSafe($selected_id) . "'", $eo);
        if (!($row = db_fetch_array($res))) {
            return error_message($Translation['No records found']);
        }
        $urow = $row;
        /* unsanitized data */
        $hc = new CI_Input();
        $row = $hc->xss_clean($row);
        /* sanitize data */
        $combo_tenants->SelectedData = $row['tenants'];
        $combo_status->SelectedData = $row['status'];
        $combo_property->SelectedData = $row['property'];
        $combo_unit->SelectedData = $row['unit'];
        $combo_type->SelectedData = $row['type'];
        $combo_start_date->DefaultDate = $row['start_date'];
        $combo_end_date->DefaultDate = $row['end_date'];
        $combo_recurring_charges_frequency->SelectedData = $row['recurring_charges_frequency'];
        $combo_next_due_date->DefaultDate = $row['next_due_date'];
        $combo_security_deposit_date->DefaultDate = $row['security_deposit_date'];
    } else {
        $combo_tenants->SelectedData = $filterer_tenants;
        $combo_status->SelectedText = $_REQUEST['FilterField'][1] == '3' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "Application";
        $combo_property->SelectedData = $filterer_property;
        $combo_unit->SelectedData = $filterer_unit;
        $combo_type->SelectedText = $_REQUEST['FilterField'][1] == '6' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "Fixed";
        $combo_recurring_charges_frequency->SelectedText = $_REQUEST['FilterField'][1] == '10' && $_REQUEST['FilterOperator'][1] == '<=>' ? get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1] : "Monthly";
    }
    $combo_tenants->HTML = '<span id="tenants-container' . $rnd1 . '"></span><input type="hidden" name="tenants" id="tenants' . $rnd1 . '">';
    $combo_tenants->MatchText = '<span id="tenants-container-readonly' . $rnd1 . '"></span><input type="hidden" name="tenants" id="tenants' . $rnd1 . '">';
    $combo_status->Render();
    $combo_property->HTML = '<span id="property-container' . $rnd1 . '"></span><input type="hidden" name="property" id="property' . $rnd1 . '">';
    $combo_property->MatchText = '<span id="property-container-readonly' . $rnd1 . '"></span><input type="hidden" name="property" id="property' . $rnd1 . '">';
    $combo_unit->HTML = '<span id="unit-container' . $rnd1 . '"></span><input type="hidden" name="unit" id="unit' . $rnd1 . '">';
    $combo_unit->MatchText = '<span id="unit-container-readonly' . $rnd1 . '"></span><input type="hidden" name="unit" id="unit' . $rnd1 . '">';
    $combo_type->Render();
    $combo_recurring_charges_frequency->Render();
    ob_start();
    ?>

	<script>
		// initial lookup values
		var current_tenants__RAND__ = { text: "", value: "<?php 
    echo addslashes($selected_id ? $urow['tenants'] : $filterer_tenants);
    ?>
"};
		var current_property__RAND__ = { text: "", value: "<?php 
    echo addslashes($selected_id ? $urow['property'] : $filterer_property);
    ?>
"};
		var current_unit__RAND__ = { text: "", value: "<?php 
    echo addslashes($selected_id ? $urow['unit'] : $filterer_unit);
    ?>
"};

		jQuery(function() {
			tenants_reload__RAND__();
			property_reload__RAND__();
			<?php 
    echo !$AllowUpdate || $dvprint ? 'unit_reload__RAND__(current_property__RAND__.value);' : '';
    ?>
		});
		function tenants_reload__RAND__(){
		<?php 
    if (($AllowUpdate || $AllowInsert) && !$dvprint) {
        ?>

			jQuery("#tenants-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					jQuery.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: current_tenants__RAND__.value, t: 'applications_leases', f: 'tenants' }
					}).done(function(resp){
						c({
							id: resp.results[0].id,
							text: resp.results[0].text
						});
						jQuery('[name="tenants"]').val(resp.results[0].id);
						jQuery('[id=tenants-container-readonly__RAND__]').html('<span id="tenants-match-text">' + resp.results[0].text + '</span>');


						if(typeof(tenants_update_autofills__RAND__) == 'function') tenants_update_autofills__RAND__();
					});
				},
				width: '100%',
				formatNoMatches: function(term){ return '<?php 
        echo addslashes($Translation['No matches found!']);
        ?>
'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { s: term, p: page, t: 'applications_leases', f: 'tenants' }; },
					results: function(resp, page){ return resp; }
				}
			}).on('change', function(e){
				current_tenants__RAND__.value = e.added.id;
				current_tenants__RAND__.text = e.added.text;
				jQuery('[name="tenants"]').val(e.added.id);


				if(typeof(tenants_update_autofills__RAND__) == 'function') tenants_update_autofills__RAND__();
			});
		<?php 
    } else {
        ?>

			jQuery.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: current_tenants__RAND__.value, t: 'applications_leases', f: 'tenants' }
			}).done(function(resp){
				jQuery('[id=tenants-container__RAND__], [id=tenants-container-readonly__RAND__]').html('<span id="tenants-match-text">' + resp.results[0].text + '</span>');

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

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

			jQuery("#property-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					jQuery.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: current_property__RAND__.value, t: 'applications_leases', f: 'property' }
					}).done(function(resp){
						c({
							id: resp.results[0].id,
							text: resp.results[0].text
						});
						jQuery('[name="property"]').val(resp.results[0].id);
						jQuery('[id=property-container-readonly__RAND__]').html('<span id="property-match-text">' + resp.results[0].text + '</span>');

						unit_reload__RAND__(current_property__RAND__.value);

						if(typeof(property_update_autofills__RAND__) == 'function') property_update_autofills__RAND__();
					});
				},
				width: '100%',
				formatNoMatches: function(term){ return '<?php 
        echo addslashes($Translation['No matches found!']);
        ?>
'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { s: term, p: page, t: 'applications_leases', f: 'property' }; },
					results: function(resp, page){ return resp; }
				}
			}).on('change', function(e){
				current_property__RAND__.value = e.added.id;
				current_property__RAND__.text = e.added.text;
				jQuery('[name="property"]').val(e.added.id);

						unit_reload__RAND__(current_property__RAND__.value);

				if(typeof(property_update_autofills__RAND__) == 'function') property_update_autofills__RAND__();
			});
		<?php 
    } else {
        ?>

			jQuery.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: current_property__RAND__.value, t: 'applications_leases', f: 'property' }
			}).done(function(resp){
				jQuery('[id=property-container__RAND__], [id=property-container-readonly__RAND__]').html('<span id="property-match-text">' + resp.results[0].text + '</span>');

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

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

			jQuery("#unit-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					jQuery.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { filterer_property: filterer_property, id: current_unit__RAND__.value, t: 'applications_leases', f: 'unit' }
					}).done(function(resp){
						c({
							id: resp.results[0].id,
							text: resp.results[0].text
						});
						jQuery('[name="unit"]').val(resp.results[0].id);
						jQuery('[id=unit-container-readonly__RAND__]').html('<span id="unit-match-text">' + resp.results[0].text + '</span>');


						if(typeof(unit_update_autofills__RAND__) == 'function') unit_update_autofills__RAND__();
					});
				},
				width: '100%',
				formatNoMatches: function(term){ return '<?php 
        echo addslashes($Translation['No matches found!']);
        ?>
'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { filterer_property: filterer_property, s: term, p: page, t: 'applications_leases', f: 'unit' }; },
					results: function(resp, page){ return resp; }
				}
			}).on('change', function(e){
				current_unit__RAND__.value = e.added.id;
				current_unit__RAND__.text = e.added.text;
				jQuery('[name="unit"]').val(e.added.id);


				if(typeof(unit_update_autofills__RAND__) == 'function') unit_update_autofills__RAND__();
			});
		<?php 
    } else {
        ?>

			jQuery.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: current_unit__RAND__.value, t: 'applications_leases', f: 'unit' }
			}).done(function(resp){
				jQuery('[id=unit-container__RAND__], [id=unit-container-readonly__RAND__]').html('<span id="unit-match-text">' + resp.results[0].text + '</span>');

				if(typeof(unit_update_autofills__RAND__) == 'function') unit_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) {
        $templateCode = @file_get_contents('./templates/applications_leases_templateDVP.html');
    } else {
        $templateCode = @file_get_contents('./templates/applications_leases_templateDV.html');
    }
    // process form title
    $templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Lease details', $templateCode);
    $templateCode = str_replace('<%%RND1%%>', $rnd1, $templateCode);
    $templateCode = str_replace('<%%EMBEDDED%%>', $_REQUEST['Embedded'] ? 'Embedded=1' : '', $templateCode);
    // process buttons
    if ($AllowInsert) {
        if (!$selected_id) {
            $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-success" id="insert" name="insert_x" value="1" onclick="return applications_leases_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 applications_leases_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 = 'window.parent.jQuery(\'.modal\').modal(\'hide\'); return false;';
    } else {
        $backAction = '$$(\'form\')[0].writeAttribute(\'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="$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;"><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 applications_leases_validateData();"><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?'] . '\');"><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 . '"><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 . '"><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('#tenants').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#tenants_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
        $jsReadOnly .= "\tjQuery('input[name=status]').parent().html('<p class=\"form-control-static\">' + jQuery('input[name=status]:checked').next().text() + '</p>')\n";
        $jsReadOnly .= "\tjQuery('#property').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#property_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
        $jsReadOnly .= "\tjQuery('#unit').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#unit_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
        $jsReadOnly .= "\tjQuery('input[name=type]').parent().html('<p class=\"form-control-static\">' + jQuery('input[name=type]:checked').next().text() + '</p>')\n";
        $jsReadOnly .= "\tjQuery('#total_number_of_occupants').replaceWith('<p class=\"form-control-static\" id=\"total_number_of_occupants\">' + (jQuery('#total_number_of_occupants').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#start_date').prop('readonly', true);\n";
        $jsReadOnly .= "\tjQuery('#start_dateDay, #start_dateMonth, #start_dateYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#end_date').prop('readonly', true);\n";
        $jsReadOnly .= "\tjQuery('#end_dateDay, #end_dateMonth, #end_dateYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#recurring_charges_frequency').replaceWith('<p class=\"form-control-static\" id=\"recurring_charges_frequency\">' + (jQuery('#recurring_charges_frequency').val() || '') + '</p>'); jQuery('#recurring_charges_frequency-multi-selection-help').hide();\n";
        $jsReadOnly .= "\tjQuery('#next_due_date').prop('readonly', true);\n";
        $jsReadOnly .= "\tjQuery('#next_due_dateDay, #next_due_dateMonth, #next_due_dateYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#rent').replaceWith('<p class=\"form-control-static\" id=\"rent\">' + (jQuery('#rent').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#security_deposit').replaceWith('<p class=\"form-control-static\" id=\"security_deposit\">' + (jQuery('#security_deposit').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#security_deposit_date').prop('readonly', true);\n";
        $jsReadOnly .= "\tjQuery('#security_deposit_dateDay, #security_deposit_dateMonth, #security_deposit_dateYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
        $jsReadOnly .= "\tjQuery('#emergency_contact').replaceWith('<p class=\"form-control-static\" id=\"emergency_contact\">' + (jQuery('#emergency_contact').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#co_signer_details').replaceWith('<p class=\"form-control-static\" id=\"co_signer_details\">' + (jQuery('#co_signer_details').val() || '') + '</p>');\n";
        $jsReadOnly .= "\tjQuery('#agreement').prop('disabled', true);\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(tenants)%%>', $combo_tenants->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(tenants)%%>', $combo_tenants->MatchText, $templateCode);
    $templateCode = str_replace('<%%URLCOMBOTEXT(tenants)%%>', urlencode($combo_tenants->MatchText), $templateCode);
    $templateCode = str_replace('<%%COMBO(status)%%>', $combo_status->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(status)%%>', $combo_status->SelectedData, $templateCode);
    $templateCode = str_replace('<%%COMBO(property)%%>', $combo_property->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(property)%%>', $combo_property->MatchText, $templateCode);
    $templateCode = str_replace('<%%URLCOMBOTEXT(property)%%>', urlencode($combo_property->MatchText), $templateCode);
    $templateCode = str_replace('<%%COMBO(unit)%%>', $combo_unit->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(unit)%%>', $combo_unit->MatchText, $templateCode);
    $templateCode = str_replace('<%%URLCOMBOTEXT(unit)%%>', urlencode($combo_unit->MatchText), $templateCode);
    $templateCode = str_replace('<%%COMBO(type)%%>', $combo_type->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(type)%%>', $combo_type->SelectedData, $templateCode);
    $templateCode = str_replace('<%%COMBO(start_date)%%>', $selected_id && !$arrPerm[3] ? '<p class="form-control-static">' . $combo_start_date->GetHTML(true) . '</p>' : $combo_start_date->GetHTML(), $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(start_date)%%>', $combo_start_date->GetHTML(true), $templateCode);
    $templateCode = str_replace('<%%COMBO(end_date)%%>', $selected_id && !$arrPerm[3] ? '<p class="form-control-static">' . $combo_end_date->GetHTML(true) . '</p>' : $combo_end_date->GetHTML(), $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(end_date)%%>', $combo_end_date->GetHTML(true), $templateCode);
    $templateCode = str_replace('<%%COMBO(recurring_charges_frequency)%%>', $combo_recurring_charges_frequency->HTML, $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(recurring_charges_frequency)%%>', $combo_recurring_charges_frequency->SelectedData, $templateCode);
    $templateCode = str_replace('<%%COMBO(next_due_date)%%>', $selected_id && !$arrPerm[3] ? '<p class="form-control-static">' . $combo_next_due_date->GetHTML(true) . '</p>' : $combo_next_due_date->GetHTML(), $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(next_due_date)%%>', $combo_next_due_date->GetHTML(true), $templateCode);
    $templateCode = str_replace('<%%COMBO(security_deposit_date)%%>', $selected_id && !$arrPerm[3] ? '<p class="form-control-static">' . $combo_security_deposit_date->GetHTML(true) . '</p>' : $combo_security_deposit_date->GetHTML(), $templateCode);
    $templateCode = str_replace('<%%COMBOTEXT(security_deposit_date)%%>', $combo_security_deposit_date->GetHTML(true), $templateCode);
    // process foreign key links
    if ($selected_id) {
        $templateCode = str_replace('<%%PLINK(tenants)%%>', $combo_tenants->SelectedData ? "<span id=\"applicants_and_tenants_plink1\" class=\"hidden\"><a class=\"btn btn-default\" href=\"applicants_and_tenants_view.php?SelectedID=" . urlencode($combo_tenants->SelectedData) . "\"><i class=\"glyphicon glyphicon-search\"></i></a></span>" : '', $templateCode);
        $templateCode = str_replace('<%%PLINK(property)%%>', $combo_property->SelectedData ? "<span id=\"properties_plink2\" class=\"hidden\"><a class=\"btn btn-default\" href=\"properties_view.php?SelectedID=" . urlencode($combo_property->SelectedData) . "\"><i class=\"glyphicon glyphicon-search\"></i></a></span>" : '', $templateCode);
        $templateCode = str_replace('<%%PLINK(unit)%%>', $combo_unit->SelectedData ? "<span id=\"units_plink3\" class=\"hidden\"><a class=\"btn btn-default\" href=\"units_view.php?SelectedID=" . urlencode($combo_unit->SelectedData) . "\"><i class=\"glyphicon glyphicon-search\"></i></a></span>" : '', $templateCode);
    }
    // process images
    $templateCode = str_replace('<%%UPLOADFILE(id)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(tenants)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(status)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(property)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(unit)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(type)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(total_number_of_occupants)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(start_date)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(end_date)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(recurring_charges_frequency)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(next_due_date)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(rent)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(security_deposit)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(security_deposit_date)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(emergency_contact)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(co_signer_details)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(notes)%%>', '', $templateCode);
    $templateCode = str_replace('<%%UPLOADFILE(agreement)%%>', '', $templateCode);
    // process values
    if ($selected_id) {
        $templateCode = str_replace('<%%VALUE(id)%%>', htmlspecialchars($row['id'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(id)%%>', urlencode($urow['id']), $templateCode);
        $templateCode = str_replace('<%%VALUE(tenants)%%>', htmlspecialchars($row['tenants'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(tenants)%%>', urlencode($urow['tenants']), $templateCode);
        $templateCode = str_replace('<%%VALUE(status)%%>', htmlspecialchars($row['status'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(status)%%>', urlencode($urow['status']), $templateCode);
        $templateCode = str_replace('<%%VALUE(property)%%>', htmlspecialchars($row['property'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(property)%%>', urlencode($urow['property']), $templateCode);
        $templateCode = str_replace('<%%VALUE(unit)%%>', htmlspecialchars($row['unit'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(unit)%%>', urlencode($urow['unit']), $templateCode);
        $templateCode = str_replace('<%%VALUE(type)%%>', htmlspecialchars($row['type'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(type)%%>', urlencode($urow['type']), $templateCode);
        $templateCode = str_replace('<%%VALUE(total_number_of_occupants)%%>', htmlspecialchars($row['total_number_of_occupants'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(total_number_of_occupants)%%>', urlencode($urow['total_number_of_occupants']), $templateCode);
        $templateCode = str_replace('<%%VALUE(start_date)%%>', @date('m/d/Y', @strtotime(htmlspecialchars($row['start_date'], ENT_QUOTES))), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(start_date)%%>', urlencode(@date('m/d/Y', @strtotime(htmlspecialchars($urow['start_date'], ENT_QUOTES)))), $templateCode);
        $templateCode = str_replace('<%%VALUE(end_date)%%>', @date('m/d/Y', @strtotime(htmlspecialchars($row['end_date'], ENT_QUOTES))), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(end_date)%%>', urlencode(@date('m/d/Y', @strtotime(htmlspecialchars($urow['end_date'], ENT_QUOTES)))), $templateCode);
        $templateCode = str_replace('<%%VALUE(recurring_charges_frequency)%%>', htmlspecialchars($row['recurring_charges_frequency'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(recurring_charges_frequency)%%>', urlencode($urow['recurring_charges_frequency']), $templateCode);
        $templateCode = str_replace('<%%VALUE(next_due_date)%%>', @date('m/d/Y', @strtotime(htmlspecialchars($row['next_due_date'], ENT_QUOTES))), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(next_due_date)%%>', urlencode(@date('m/d/Y', @strtotime(htmlspecialchars($urow['next_due_date'], ENT_QUOTES)))), $templateCode);
        $templateCode = str_replace('<%%VALUE(rent)%%>', htmlspecialchars($row['rent'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(rent)%%>', urlencode($urow['rent']), $templateCode);
        $templateCode = str_replace('<%%VALUE(security_deposit)%%>', htmlspecialchars($row['security_deposit'], ENT_QUOTES), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(security_deposit)%%>', urlencode($urow['security_deposit']), $templateCode);
        $templateCode = str_replace('<%%VALUE(security_deposit_date)%%>', @date('m/d/Y', @strtotime(htmlspecialchars($row['security_deposit_date'], ENT_QUOTES))), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(security_deposit_date)%%>', urlencode(@date('m/d/Y', @strtotime(htmlspecialchars($urow['security_deposit_date'], ENT_QUOTES)))), $templateCode);
        if ($dvprint) {
            $templateCode = str_replace('<%%VALUE(emergency_contact)%%>', nl2br(htmlspecialchars($row['emergency_contact'], ENT_QUOTES)), $templateCode);
        } else {
            $templateCode = str_replace('<%%VALUE(emergency_contact)%%>', htmlspecialchars($row['emergency_contact'], ENT_QUOTES), $templateCode);
        }
        $templateCode = str_replace('<%%URLVALUE(emergency_contact)%%>', urlencode($urow['emergency_contact']), $templateCode);
        if ($dvprint) {
            $templateCode = str_replace('<%%VALUE(co_signer_details)%%>', nl2br(htmlspecialchars($row['co_signer_details'], ENT_QUOTES)), $templateCode);
        } else {
            $templateCode = str_replace('<%%VALUE(co_signer_details)%%>', htmlspecialchars($row['co_signer_details'], ENT_QUOTES), $templateCode);
        }
        $templateCode = str_replace('<%%URLVALUE(co_signer_details)%%>', urlencode($urow['co_signer_details']), $templateCode);
        if ($AllowUpdate || $AllowInsert) {
            $templateCode = str_replace('<%%HTMLAREA(notes)%%>', '<textarea name="notes" id="notes" rows="5">' . htmlspecialchars($row['notes'], ENT_QUOTES) . '</textarea>', $templateCode);
        } else {
            $templateCode = str_replace('<%%HTMLAREA(notes)%%>', $row['notes'], $templateCode);
        }
        $templateCode = str_replace('<%%VALUE(notes)%%>', nl2br($row['notes']), $templateCode);
        $templateCode = str_replace('<%%URLVALUE(notes)%%>', urlencode($urow['notes']), $templateCode);
        $templateCode = str_replace('<%%CHECKED(agreement)%%>', $row['agreement'] ? "checked" : "", $templateCode);
    } else {
        $templateCode = str_replace('<%%VALUE(id)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(id)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(tenants)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(tenants)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(status)%%>', 'Application', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(status)%%>', urlencode('Application'), $templateCode);
        $templateCode = str_replace('<%%VALUE(property)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(property)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(unit)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(unit)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(type)%%>', 'Fixed', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(type)%%>', urlencode('Fixed'), $templateCode);
        $templateCode = str_replace('<%%VALUE(total_number_of_occupants)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(total_number_of_occupants)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(start_date)%%>', '1', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(start_date)%%>', urlencode('1'), $templateCode);
        $templateCode = str_replace('<%%VALUE(end_date)%%>', '1', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(end_date)%%>', urlencode('1'), $templateCode);
        $templateCode = str_replace('<%%VALUE(recurring_charges_frequency)%%>', 'Monthly', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(recurring_charges_frequency)%%>', urlencode('Monthly'), $templateCode);
        $templateCode = str_replace('<%%VALUE(next_due_date)%%>', '1', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(next_due_date)%%>', urlencode('1'), $templateCode);
        $templateCode = str_replace('<%%VALUE(rent)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(rent)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(security_deposit)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(security_deposit)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(security_deposit_date)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(security_deposit_date)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(emergency_contact)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(emergency_contact)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%VALUE(co_signer_details)%%>', '', $templateCode);
        $templateCode = str_replace('<%%URLVALUE(co_signer_details)%%>', urlencode(''), $templateCode);
        $templateCode = str_replace('<%%HTMLAREA(notes)%%>', '<textarea name="notes" id="notes" rows="5"></textarea>', $templateCode);
        $templateCode = str_replace('<%%CHECKED(agreement)%%>', '', $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 ($_POST['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 .= "\t\$j('[id^=\"{$name}_plink\"]').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" rel="lightbox\\[.*?\\]"/', 'blank.gif"', $templateCode);
    // don't display empty email links
    $templateCode = preg_replace('/<a .*?href="mailto:".*?<\\/a>/', '', $templateCode);
    // hook: applications_leases_dv
    if (function_exists('applications_leases_dv')) {
        $args = array();
        applications_leases_dv($selected_id ? $selected_id : FALSE, getMemberInfo(), $templateCode, $args);
    }
    return $templateCode;
}