<?php

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

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

function employees_insert() {
	global $Translation;

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

	$data = array();
	$data['TitleOfCourtesy'] = $_REQUEST['TitleOfCourtesy'];
		if($data['TitleOfCourtesy'] == empty_lookup_value) { $data['TitleOfCourtesy'] = ''; }
	$data['LastName'] = $_REQUEST['LastName'];
		if($data['LastName'] == empty_lookup_value) { $data['LastName'] = ''; }
	$data['FirstName'] = $_REQUEST['FirstName'];
		if($data['FirstName'] == empty_lookup_value) { $data['FirstName'] = ''; }
	$data['Title'] = $_REQUEST['Title'];
		if($data['Title'] == empty_lookup_value) { $data['Title'] = ''; }
	$data['BirthDate'] = intval($_REQUEST['BirthDateYear']) . '-' . intval($_REQUEST['BirthDateMonth']) . '-' . intval($_REQUEST['BirthDateDay']);
	$data['BirthDate'] = parseMySQLDate($data['BirthDate'], '');
	$data['HireDate'] = intval($_REQUEST['HireDateYear']) . '-' . intval($_REQUEST['HireDateMonth']) . '-' . intval($_REQUEST['HireDateDay']);
	$data['HireDate'] = parseMySQLDate($data['HireDate'], '1');
	$data['Address'] = br2nl($_REQUEST['Address']);
	$data['City'] = $_REQUEST['City'];
		if($data['City'] == empty_lookup_value) { $data['City'] = ''; }
	$data['Region'] = $_REQUEST['Region'];
		if($data['Region'] == empty_lookup_value) { $data['Region'] = ''; }
	$data['PostalCode'] = $_REQUEST['PostalCode'];
		if($data['PostalCode'] == empty_lookup_value) { $data['PostalCode'] = ''; }
	$data['Country'] = $_REQUEST['Country'];
		if($data['Country'] == empty_lookup_value) { $data['Country'] = ''; }
	$data['HomePhone'] = $_REQUEST['HomePhone'];
		if($data['HomePhone'] == empty_lookup_value) { $data['HomePhone'] = ''; }
	$data['Extension'] = $_REQUEST['Extension'];
		if($data['Extension'] == empty_lookup_value) { $data['Extension'] = ''; }
	$data['Notes'] = $_REQUEST['Notes'];
		if($data['Notes'] == empty_lookup_value) { $data['Notes'] = ''; }
	$data['ReportsTo'] = $_REQUEST['ReportsTo'];
		if($data['ReportsTo'] == empty_lookup_value) { $data['ReportsTo'] = ''; }
	$data['Photo'] = PrepareUploadedFile('Photo', 153600,'jpg|jpeg|gif|png', false, '');
	if($data['Photo']) createThumbnail($data['Photo'], getThumbnailSpecs('employees', 'Photo', 'tv'));

	/* for empty upload fields, when saving a copy of an existing record, copy the original upload field */
	if($_REQUEST['SelectedID']) {
		$res = sql("select * from employees where EmployeeID='" . makeSafe($_REQUEST['SelectedID']) . "'", $eo);
		if($row = db_fetch_assoc($res)) {
			if(!$data['Photo']) $data['Photo'] = $row['Photo'];
		}
	}

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

	$error = '';
	// set empty fields to NULL
	$data = array_map(function($v) { return ($v === '' ? NULL : $v); }, $data);
	insert('employees', backtick_keys_once($data), $error);
	if($error)
		die("{$error}<br><a href=\"#\" onclick=\"history.go(-1);\">{$Translation['< back']}</a>");

	$recID = db_insert_id(db_link());

	// hook: employees_after_insert
	if(function_exists('employees_after_insert')) {
		$res = sql("select * from `employees` where `EmployeeID`='" . makeSafe($recID, false) . "' limit 1", $eo);
		if($row = db_fetch_assoc($res)) {
			$data = array_map('makeSafe', $row);
		}
		$data['selectedID'] = makeSafe($recID, false);
		$args=array();
		if(!employees_after_insert($data, getMemberInfo(), $args)) { return $recID; }
	}

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

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

	return $recID;
}

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

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

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

	// mm: can member delete record?
	$arrPerm=getTablePermissions('employees');
	$ownerGroupID=sqlValue("select groupID from membership_userrecords where tableName='employees' and pkValue='$selected_id'");
	$ownerMemberID=sqlValue("select lcase(memberID) from membership_userrecords where tableName='employees' and pkValue='$selected_id'");
	if(($arrPerm[4]==1 && $ownerMemberID==getLoggedMemberID()) || ($arrPerm[4]==2 && $ownerGroupID==getLoggedGroupID()) || $arrPerm[4]==3) { // allow delete?
		// delete allowed, so continue ...
	}else{
		return $Translation['You don\'t have enough permissions to delete this record'];
	}

	// hook: employees_before_delete
	if(function_exists('employees_before_delete')) {
		$args=array();
		if(!employees_before_delete($selected_id, $skipChecks, getMemberInfo(), $args))
			return $Translation['Couldn\'t delete this record'];
	}

	// child table: employees
	$res = sql("select `EmployeeID` from `employees` where `EmployeeID`='$selected_id'", $eo);
	$EmployeeID = db_fetch_row($res);
	$rires = sql("select count(1) from `employees` where `ReportsTo`='".addslashes($EmployeeID[0])."'", $eo);
	$rirow = db_fetch_row($rires);
	if($rirow[0] && !$AllowDeleteOfParents && !$skipChecks) {
		$RetMsg = $Translation["couldn't delete"];
		$RetMsg = str_replace("<RelatedRecords>", $rirow[0], $RetMsg);
		$RetMsg = str_replace("<TableName>", "employees", $RetMsg);
		return $RetMsg;
	}elseif($rirow[0] && $AllowDeleteOfParents && !$skipChecks) {
		$RetMsg = $Translation["confirm delete"];
		$RetMsg = str_replace("<RelatedRecords>", $rirow[0], $RetMsg);
		$RetMsg = str_replace("<TableName>", "employees", $RetMsg);
		$RetMsg = str_replace("<Delete>", "<input type=\"button\" class=\"button\" value=\"".$Translation['yes']."\" onClick=\"window.location='employees_view.php?SelectedID=".urlencode($selected_id)."&delete_x=1&confirmed=1';\">", $RetMsg);
		$RetMsg = str_replace("<Cancel>", "<input type=\"button\" class=\"button\" value=\"".$Translation['no']."\" onClick=\"window.location='employees_view.php?SelectedID=".urlencode($selected_id)."';\">", $RetMsg);
		return $RetMsg;
	}

	// child table: orders
	$res = sql("select `EmployeeID` from `employees` where `EmployeeID`='$selected_id'", $eo);
	$EmployeeID = db_fetch_row($res);
	$rires = sql("select count(1) from `orders` where `EmployeeID`='".addslashes($EmployeeID[0])."'", $eo);
	$rirow = db_fetch_row($rires);
	if($rirow[0] && !$AllowDeleteOfParents && !$skipChecks) {
		$RetMsg = $Translation["couldn't delete"];
		$RetMsg = str_replace("<RelatedRecords>", $rirow[0], $RetMsg);
		$RetMsg = str_replace("<TableName>", "orders", $RetMsg);
		return $RetMsg;
	}elseif($rirow[0] && $AllowDeleteOfParents && !$skipChecks) {
		$RetMsg = $Translation["confirm delete"];
		$RetMsg = str_replace("<RelatedRecords>", $rirow[0], $RetMsg);
		$RetMsg = str_replace("<TableName>", "orders", $RetMsg);
		$RetMsg = str_replace("<Delete>", "<input type=\"button\" class=\"button\" value=\"".$Translation['yes']."\" onClick=\"window.location='employees_view.php?SelectedID=".urlencode($selected_id)."&delete_x=1&confirmed=1';\">", $RetMsg);
		$RetMsg = str_replace("<Cancel>", "<input type=\"button\" class=\"button\" value=\"".$Translation['no']."\" onClick=\"window.location='employees_view.php?SelectedID=".urlencode($selected_id)."';\">", $RetMsg);
		return $RetMsg;
	}

	// delete file stored in the 'Photo' field
	$res = sql("select `Photo` from `employees` where `EmployeeID`='$selected_id'", $eo);
	if($row=@db_fetch_row($res)) {
		if($row[0]!='') {
			@unlink(getUploadDir('').$row[0]);
			preg_match('/^[a-z0-9_]+\.(gif|png|jpg|jpeg|jpe)$/i', $row[0], $m);
			$thumbDV=str_replace(".$m[1]ffffgggg", "_dv.$m[1]", $row[0].'ffffgggg');
			$thumbTV=str_replace(".$m[1]ffffgggg", "_tv.$m[1]", $row[0].'ffffgggg');
			@unlink(getUploadDir('').$thumbTV);
			@unlink(getUploadDir('').$thumbDV);
		}
	}

	sql("delete from `employees` where `EmployeeID`='$selected_id'", $eo);

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

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

function employees_update($selected_id) {
	global $Translation;

	// mm: can member edit record?
	$arrPerm=getTablePermissions('employees');
	$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[3]==1 && $ownerMemberID==getLoggedMemberID()) || ($arrPerm[3]==2 && $ownerGroupID==getLoggedGroupID()) || $arrPerm[3]==3) { // allow update?
		// update allowed, so continue ...
	}else{
		return false;
	}

	$data['TitleOfCourtesy'] = makeSafe($_REQUEST['TitleOfCourtesy']);
		if($data['TitleOfCourtesy'] == empty_lookup_value) { $data['TitleOfCourtesy'] = ''; }
	$data['LastName'] = makeSafe($_REQUEST['LastName']);
		if($data['LastName'] == empty_lookup_value) { $data['LastName'] = ''; }
	$data['FirstName'] = makeSafe($_REQUEST['FirstName']);
		if($data['FirstName'] == empty_lookup_value) { $data['FirstName'] = ''; }
	$data['Title'] = makeSafe($_REQUEST['Title']);
		if($data['Title'] == empty_lookup_value) { $data['Title'] = ''; }
	$data['BirthDate'] = intval($_REQUEST['BirthDateYear']) . '-' . intval($_REQUEST['BirthDateMonth']) . '-' . intval($_REQUEST['BirthDateDay']);
	$data['BirthDate'] = parseMySQLDate($data['BirthDate'], '');
	$data['HireDate'] = intval($_REQUEST['HireDateYear']) . '-' . intval($_REQUEST['HireDateMonth']) . '-' . intval($_REQUEST['HireDateDay']);
	$data['HireDate'] = parseMySQLDate($data['HireDate'], '1');
	$data['Address'] = br2nl(makeSafe($_REQUEST['Address']));
	$data['City'] = makeSafe($_REQUEST['City']);
		if($data['City'] == empty_lookup_value) { $data['City'] = ''; }
	$data['Region'] = makeSafe($_REQUEST['Region']);
		if($data['Region'] == empty_lookup_value) { $data['Region'] = ''; }
	$data['PostalCode'] = makeSafe($_REQUEST['PostalCode']);
		if($data['PostalCode'] == empty_lookup_value) { $data['PostalCode'] = ''; }
	$data['Country'] = makeSafe($_REQUEST['Country']);
		if($data['Country'] == empty_lookup_value) { $data['Country'] = ''; }
	$data['HomePhone'] = makeSafe($_REQUEST['HomePhone']);
		if($data['HomePhone'] == empty_lookup_value) { $data['HomePhone'] = ''; }
	$data['Extension'] = makeSafe($_REQUEST['Extension']);
		if($data['Extension'] == empty_lookup_value) { $data['Extension'] = ''; }
	$data['Notes'] = makeSafe($_REQUEST['Notes']);
		if($data['Notes'] == empty_lookup_value) { $data['Notes'] = ''; }
	$data['ReportsTo'] = makeSafe($_REQUEST['ReportsTo']);
		if($data['ReportsTo'] == empty_lookup_value) { $data['ReportsTo'] = ''; }
	$data['selectedID'] = makeSafe($selected_id);
	if($_REQUEST['Photo_remove'] == 1) {
		$data['Photo'] = '';
		// delete file from server
		$res = sql("select `Photo` from `employees` where `EmployeeID`='".makeSafe($selected_id)."'", $eo);
		if($row = @db_fetch_row($res)) {
			if($row[0] != '') {
				@unlink(getUploadDir('') . $row[0]);
				preg_match('/^[a-z0-9_]+\.(gif|png|jpg|jpeg|jpe)$/i', $row[0], $m);
				$thumbDV = str_replace(".$m[1]ffffgggg", "_dv.$m[1]", $row[0] . 'ffffgggg');
				$thumbTV = str_replace(".$m[1]ffffgggg", "_tv.$m[1]", $row[0] . 'ffffgggg');
				@unlink(getUploadDir('') . $thumbTV);
				@unlink(getUploadDir('') . $thumbDV);
			}
		}
	} else {
		$data['Photo'] = PrepareUploadedFile('Photo', 153600, 'jpg|jpeg|gif|png', false, "");
		if($data['Photo']) createThumbnail($data['Photo'], getThumbnailSpecs('employees', 'Photo', 'tv'));
		// delete file from server
		if($data['Photo'] != '') {
			$res = sql("select `Photo` from `employees` where `EmployeeID`='" . makeSafe($selected_id) . "'", $eo);
			if($row = @db_fetch_row($res)) {
				if($row[0] != '') {
					@unlink(getUploadDir('') . $row[0]);
					preg_match('/^[a-z0-9_]+\.(gif|png|jpg|jpeg|jpe)$/i', $row[0], $m);
					$thumbDV = str_replace(".$m[1]ffffgggg", "_dv.$m[1]", $row[0] . 'ffffgggg');
					$thumbTV = str_replace(".$m[1]ffffgggg", "_tv.$m[1]", $row[0] . 'ffffgggg');
					@unlink(getUploadDir('') . $thumbTV);
					@unlink(getUploadDir('') . $thumbDV);
				}
			}
		}
	}

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

	$o = array('silentErrors' => true);
	sql('update `employees` set       `TitleOfCourtesy`=' . (($data['TitleOfCourtesy'] !== '' && $data['TitleOfCourtesy'] !== NULL) ? "'{$data['TitleOfCourtesy']}'" : 'NULL') . ', ' . ($data['Photo']!='' ? "`Photo`='{$data['Photo']}'" : ($_REQUEST['Photo_remove'] != 1 ? '`Photo`=`Photo`' : '`Photo`=NULL')) . ', `LastName`=' . (($data['LastName'] !== '' && $data['LastName'] !== NULL) ? "'{$data['LastName']}'" : 'NULL') . ', `FirstName`=' . (($data['FirstName'] !== '' && $data['FirstName'] !== NULL) ? "'{$data['FirstName']}'" : 'NULL') . ', `Title`=' . (($data['Title'] !== '' && $data['Title'] !== NULL) ? "'{$data['Title']}'" : 'NULL') . ', `BirthDate`=' . (($data['BirthDate'] !== '' && $data['BirthDate'] !== NULL) ? "'{$data['BirthDate']}'" : 'NULL') . ', `HireDate`=' . (($data['HireDate'] !== '' && $data['HireDate'] !== NULL) ? "'{$data['HireDate']}'" : 'NULL') . ', `Address`=' . (($data['Address'] !== '' && $data['Address'] !== NULL) ? "'{$data['Address']}'" : 'NULL') . ', `City`=' . (($data['City'] !== '' && $data['City'] !== NULL) ? "'{$data['City']}'" : 'NULL') . ', `Region`=' . (($data['Region'] !== '' && $data['Region'] !== NULL) ? "'{$data['Region']}'" : 'NULL') . ', `PostalCode`=' . (($data['PostalCode'] !== '' && $data['PostalCode'] !== NULL) ? "'{$data['PostalCode']}'" : 'NULL') . ', `Country`=' . (($data['Country'] !== '' && $data['Country'] !== NULL) ? "'{$data['Country']}'" : 'NULL') . ', `HomePhone`=' . (($data['HomePhone'] !== '' && $data['HomePhone'] !== NULL) ? "'{$data['HomePhone']}'" : 'NULL') . ', `Extension`=' . (($data['Extension'] !== '' && $data['Extension'] !== NULL) ? "'{$data['Extension']}'" : 'NULL') . ', `Notes`=' . (($data['Notes'] !== '' && $data['Notes'] !== NULL) ? "'{$data['Notes']}'" : 'NULL') . ', `ReportsTo`=' . (($data['ReportsTo'] !== '' && $data['ReportsTo'] !== NULL) ? "'{$data['ReportsTo']}'" : 'NULL') . " where `EmployeeID`='".makeSafe($selected_id)."'", $o);
	if($o['error']!='') {
		echo $o['error'];
		echo '<a href="employees_view.php?SelectedID='.urlencode($selected_id)."\">{$Translation['< back']}</a>";
		exit;
	}


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

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

}

function employees_form($selected_id = '', $AllowUpdate = 1, $AllowInsert = 1, $AllowDelete = 1, $ShowCancel = 0, $TemplateDV = '', $TemplateDVP = '') {
	// function to return an editable form for a table records
	// and fill it with data of record whose ID is $selected_id. If $selected_id
	// is empty, an empty form is shown, with only an 'Add New'
	// button displayed.

	global $Translation;

	// mm: get table permissions
	$arrPerm=getTablePermissions('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'], 'employees_view.php', false);
		}
		$combo_BirthDate->DefaultDate = $row['BirthDate'];
		$combo_HireDate->DefaultDate = $row['HireDate'];
		$combo_Country->SelectedData = $row['Country'];
		$combo_ReportsTo->SelectedData = $row['ReportsTo'];
		$urow = $row; /* unsanitized data */
		$hc = new CI_Input();
		$row = $hc->xss_clean($row); /* sanitize data */
	} else {
		$combo_Country->SelectedText = ( $_REQUEST['FilterField'][1]=='14' && $_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
		AppGini.current_ReportsTo__RAND__ = { text: "", value: "<?php echo addslashes($selected_id ? $urow['ReportsTo'] : $filterer_ReportsTo); ?>"};

		jQuery(function() {
			setTimeout(function() {
				if(typeof(ReportsTo_reload__RAND__) == 'function') ReportsTo_reload__RAND__();
			}, 10); /* we need to slightly delay client-side execution of the above code to allow AppGini.ajaxCache to work */
		});
		function ReportsTo_reload__RAND__() {
			new Ajax.Updater("ReportsTo-container__RAND__", "ajax_combo.php", {
				parameters: { t: "employees", f: "ReportsTo", id: AppGini.current_ReportsTo__RAND__.value, text: AppGini.current_ReportsTo__RAND__.text, o: <?php echo (($AllowUpdate || $AllowInsert) && !$dvprint ? '1' : '0'); ?> },
				method: "get",
				encoding: "<?php echo datalist_db_encoding; ?>",
				evalScripts: true,
				onComplete: function() { /* */ ReportsTo_changed__RAND__(); }
			});
		}
		function ReportsTo_changed__RAND__() {
			if($j("input[name=ReportsTo]").length) {
				if($j("input[name=ReportsTo]:checked").length) {
					AppGini.current_ReportsTo__RAND__.value = $j("input[name=ReportsTo]:checked").val();
					AppGini.current_ReportsTo__RAND__.text = "";
				}else{
					AppGini.current_ReportsTo__RAND__.value = "";
					AppGini.current_ReportsTo__RAND__.text = "";
				}
				AppGini.hideViewParentLinks();
			}

			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) {
		$template_file = is_file("./{$TemplateDVP}") ? "./{$TemplateDVP}" : './templates/employees_templateDVP.html';
		$templateCode = @file_get_contents($template_file);
	}else{
		$template_file = is_file("./{$TemplateDV}") ? "./{$TemplateDV}" : './templates/employees_templateDV.html';
		$templateCode = @file_get_contents($template_file);
	}

	// 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 = 'AppGini.closeParentModal(); return false;';
	}else{
		$backAction = '$j(\'form\').eq(0).attr(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;';
	}

	if($selected_id) {
		if(!$_REQUEST['Embedded']) $templateCode = str_replace('<%%DVPRINT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="dvprint" name="dvprint_x" value="1" onclick="$j(\'form\').eq(0).prop(\'novalidate\', true); document.myform.reset(); return true;" title="' . html_attr($Translation['Print Preview']) . '"><i class="glyphicon glyphicon-print"></i> ' . $Translation['Print Preview'] . '</button>', $templateCode);
		if($AllowUpdate) {
			$templateCode = str_replace('<%%UPDATE_BUTTON%%>', '<button type="submit" class="btn btn-success btn-lg" id="update" name="update_x" value="1" onclick="return employees_validateData();" title="' . html_attr($Translation['Save Changes']) . '"><i class="glyphicon glyphicon-ok"></i> ' . $Translation['Save Changes'] . '</button>', $templateCode);
		}else{
			$templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
		}
		if(($arrPerm[4]==1 && $ownerMemberID==getLoggedMemberID()) || ($arrPerm[4]==2 && $ownerGroupID==getLoggedGroupID()) || $arrPerm[4]==3) { // allow delete?
			$templateCode = str_replace('<%%DELETE_BUTTON%%>', '<button type="submit" class="btn btn-danger" id="delete" name="delete_x" value="1" onclick="return confirm(\'' . $Translation['are you sure?'] . '\');" title="' . html_attr($Translation['Delete']) . '"><i class="glyphicon glyphicon-trash"></i> ' . $Translation['Delete'] . '</button>', $templateCode);
		}else{
			$templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
		}
		$templateCode = str_replace('<%%DESELECT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '" title="' . html_attr($Translation['Back']) . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>', $templateCode);
	}else{
		$templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
		$templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
		$templateCode = str_replace('<%%DESELECT_BUTTON%%>', ($ShowCancel ? '<button type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '" title="' . html_attr($Translation['Back']) . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>' : ''), $templateCode);
	}

	// set records to read only if user can't insert new records and can't edit current record
	if(($selected_id && !$AllowUpdate) || (!$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', 'Reports To'), );
	foreach($lookup_fields as $luf => $ptfc) {
		$pt_perm = getTablePermissions($ptfc[0]);

		// process foreign key links
		if($pt_perm['view'] || $pt_perm['edit']) {
			$templateCode = str_replace("<%%PLINK({$luf})%%>", '<button type="button" class="btn btn-default view_parent hspacer-md" id="' . $ptfc[0] . '_view_parent" title="' . html_attr($Translation['View'] . ' ' . $ptfc[1]) . '"><i class="glyphicon glyphicon-eye-open"></i></button>', $templateCode);
		}

		// if user has insert permission to parent table of a lookup field, put an add new button
		if($pt_perm['insert'] && !$_REQUEST['Embedded']) {
			$templateCode = str_replace("<%%ADDNEW({$ptfc[0]})%%>", '<button type="button" class="btn btn-success add_new_parent hspacer-md" id="' . $ptfc[0] . '_add_new" title="' . html_attr($Translation['Add New'] . ' ' . $ptfc[1]) . '"><i class="glyphicon glyphicon-plus-sign"></i></button>', $templateCode);
		}
	}

	// process images
	$templateCode = str_replace('<%%UPLOADFILE(EmployeeID)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(TitleOfCourtesy)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(Photo)%%>', ($noUploads ? '' : "<div>{$Translation['upload image']}</div>" . '<i class="glyphicon glyphicon-remove text-danger clear-upload hidden"></i> <input type="file" name="Photo" id="Photo" data-filetypes="jpg|jpeg|gif|png" data-maxsize="153600">'), $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(Age)%%>', '', $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);
	$templateCode = str_replace('<%%UPLOADFILE(TotalSales)%%>', '', $templateCode);

	// process values
	if($selected_id) {
		if( $dvprint) $templateCode = str_replace('<%%VALUE(EmployeeID)%%>', safe_html($urow['EmployeeID']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(EmployeeID)%%>', html_attr($row['EmployeeID']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(EmployeeID)%%>', urlencode($urow['EmployeeID']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(TitleOfCourtesy)%%>', safe_html($urow['TitleOfCourtesy']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(TitleOfCourtesy)%%>', html_attr($row['TitleOfCourtesy']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(TitleOfCourtesy)%%>', urlencode($urow['TitleOfCourtesy']), $templateCode);
		$row['Photo'] = ($row['Photo'] != '' ? $row['Photo'] : 'blank.gif');
		if( $dvprint) $templateCode = str_replace('<%%VALUE(Photo)%%>', safe_html($urow['Photo']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(Photo)%%>', html_attr($row['Photo']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Photo)%%>', urlencode($urow['Photo']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(LastName)%%>', safe_html($urow['LastName']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(LastName)%%>', html_attr($row['LastName']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(LastName)%%>', urlencode($urow['LastName']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(FirstName)%%>', safe_html($urow['FirstName']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(FirstName)%%>', html_attr($row['FirstName']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(FirstName)%%>', urlencode($urow['FirstName']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(Title)%%>', safe_html($urow['Title']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(Title)%%>', html_attr($row['Title']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Title)%%>', urlencode($urow['Title']), $templateCode);
		$templateCode = str_replace('<%%VALUE(BirthDate)%%>', @date('m/d/Y', @strtotime(html_attr($row['BirthDate']))), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(BirthDate)%%>', urlencode(@date('m/d/Y', @strtotime(html_attr($urow['BirthDate'])))), $templateCode);
		$templateCode = str_replace('<%%VALUE(Age)%%>', safe_html($urow['Age']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Age)%%>', urlencode($urow['Age']), $templateCode);
		$templateCode = str_replace('<%%VALUE(HireDate)%%>', @date('m/d/Y', @strtotime(html_attr($row['HireDate']))), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(HireDate)%%>', urlencode(@date('m/d/Y', @strtotime(html_attr($urow['HireDate'])))), $templateCode);
		if($dvprint || (!$AllowUpdate && !$AllowInsert)) {
			$templateCode = str_replace('<%%VALUE(Address)%%>', safe_html($urow['Address']), $templateCode);
		}else{
			$templateCode = str_replace('<%%VALUE(Address)%%>', html_attr($row['Address']), $templateCode);
		}
		$templateCode = str_replace('<%%URLVALUE(Address)%%>', urlencode($urow['Address']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(City)%%>', safe_html($urow['City']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(City)%%>', html_attr($row['City']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(City)%%>', urlencode($urow['City']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(Region)%%>', safe_html($urow['Region']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(Region)%%>', html_attr($row['Region']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Region)%%>', urlencode($urow['Region']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(PostalCode)%%>', safe_html($urow['PostalCode']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(PostalCode)%%>', html_attr($row['PostalCode']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(PostalCode)%%>', urlencode($urow['PostalCode']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(Country)%%>', safe_html($urow['Country']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(Country)%%>', html_attr($row['Country']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Country)%%>', urlencode($urow['Country']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(HomePhone)%%>', safe_html($urow['HomePhone']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(HomePhone)%%>', html_attr($row['HomePhone']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(HomePhone)%%>', urlencode($urow['HomePhone']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(Extension)%%>', safe_html($urow['Extension']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(Extension)%%>', html_attr($row['Extension']), $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">' . html_attr($row['Notes']) . '</textarea>', $templateCode);
		}else{
			$templateCode = str_replace('<%%HTMLAREA(Notes)%%>', '<div id="Notes" class="form-control-static">' . $row['Notes'] . '</div>', $templateCode);
		}
		$templateCode = str_replace('<%%VALUE(Notes)%%>', nl2br($row['Notes']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Notes)%%>', urlencode($urow['Notes']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(ReportsTo)%%>', safe_html($urow['ReportsTo']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(ReportsTo)%%>', html_attr($row['ReportsTo']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(ReportsTo)%%>', urlencode($urow['ReportsTo']), $templateCode);
		$templateCode = str_replace('<%%VALUE(TotalSales)%%>', safe_html($urow['TotalSales']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(TotalSales)%%>', urlencode($urow['TotalSales']), $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(Age)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(Age)%%>', 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);
		$templateCode = str_replace('<%%VALUE(TotalSales)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(TotalSales)%%>', urlencode(''), $templateCode);
	}

	// process translations
	foreach($Translation as $symbol=>$trans) {
		$templateCode = str_replace("<%%TRANSLATION($symbol)%%>", $trans, $templateCode);
	}

	// clear scrap
	$templateCode = str_replace('<%%', '<!-- ', $templateCode);
	$templateCode = str_replace('%%>', ' -->', $templateCode);

	// hide links to inaccessible tables
	if($_REQUEST['dvprint_x'] == '') {
		$templateCode .= "\n\n<script>\$j(function() {\n";
		$arrTables = getTableList();
		foreach($arrTables as $name => $caption) {
			$templateCode .= "\t\$j('#{$name}_link').removeClass('hidden');\n";
			$templateCode .= "\t\$j('#xs_{$name}_link').removeClass('hidden');\n";
		}

		$templateCode .= $jsReadOnly;
		$templateCode .= $jsEditable;

		if(!$selected_id) {
		}

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

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


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

	// handle enforced parent values for read-only lookup fields

	// don't include blank images in lightbox gallery
	$templateCode = preg_replace('/blank.gif" data-lightbox=".*?"/', 'blank.gif"', $templateCode);

	// don't display empty email links
	$templateCode=preg_replace('/<a .*?href="mailto:".*?<\/a>/', '', $templateCode);

	/* default field values */
	$rdata = $jdata = get_defaults('employees');
	if($selected_id) {
		$jdata = get_joined_record('employees', $selected_id);
		if($jdata === false) $jdata = get_defaults('employees');
		$rdata = $row;
	}
	$templateCode .= loadView('employees-ajax-cache', array('rdata' => $rdata, 'jdata' => $jdata));

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

	return $templateCode;
}
?>