<?php
namespace PHPMaker2019\project_germanos;

/**
 * Table class for clients
 */
class clients extends DbTable
{
	protected $SqlFrom = "";
	protected $SqlSelect = "";
	protected $SqlSelectList = "";
	protected $SqlWhere = "";
	protected $SqlGroupBy = "";
	protected $SqlHaving = "";
	protected $SqlOrderBy = "";
	public $UseSessionForListSql = TRUE;

	// Column CSS classes
	public $LeftColumnClass = "col-sm-2 col-form-label ew-label";
	public $RightColumnClass = "col-sm-10";
	public $OffsetColumnClass = "col-sm-10 offset-sm-2";
	public $TableLeftColumnClass = "w-col-2";

	// Audit trail
	public $AuditTrailOnAdd = TRUE;
	public $AuditTrailOnEdit = TRUE;
	public $AuditTrailOnDelete = TRUE;
	public $AuditTrailOnView = FALSE;
	public $AuditTrailOnViewData = FALSE;
	public $AuditTrailOnSearch = FALSE;

	// Export
	public $ExportDoc;

	// Fields
	public $ClientID;
	public $ClientTypeID;
	public $ClientGroupID;
	public $TitleID;
	public $FirstName;
	public $MiddleName;
	public $LastName;
	public $PartnersName;
	public $CompanyName;
	public $ContactPerson;
	public $WorkNature;
	public $JobTitle;
	public $Photo;
	public $BirthDate;
	public $Title;
	public $TitleEn;
	public $FirstNameEn;
	public $MiddleNameEn;
	public $LastNameEn;
	public $PartnersNameEn;
	public $CompanyNameEn;
	public $AddressID;
	public $ContactID;
	public $Gender;
	public $Notes;
	public $Activated;
	public $Profile;
	public $_UserID;
	public $CreatedBy;
	public $CreatedDate;
	public $UpdatedBy;
	public $UpdatedDate;
	public $FileNumber;
	public $NotesConv;

	// Constructor
	public function __construct()
	{
		global $Language, $CurrentLanguage;

		// Language object
		if (!isset($Language))
			$Language = new Language();
		$this->TableVar = 'clients';
		$this->TableName = 'clients';
		$this->TableType = 'TABLE';

		// Update Table
		$this->UpdateTable = "`clients`";
		$this->Dbid = 'DB';
		$this->ExportAll = TRUE;
		$this->ExportPageBreakCount = 0; // Page break per every n record (PDF only)
		$this->ExportPageOrientation = "portrait"; // Page orientation (PDF only)
		$this->ExportPageSize = "a4"; // Page size (PDF only)
		$this->ExportExcelPageOrientation = \PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::ORIENTATION_DEFAULT; // Page orientation (PhpSpreadsheet only)
		$this->ExportExcelPageSize = \PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_A4; // Page size (PhpSpreadsheet only)
		$this->ExportWordPageOrientation = "portrait"; // Page orientation (PHPWord only)
		$this->ExportWordColumnWidth = NULL; // Cell width (PHPWord only)
		$this->DetailAdd = TRUE; // Allow detail add
		$this->DetailEdit = TRUE; // Allow detail edit
		$this->DetailView = TRUE; // Allow detail view
		$this->ShowMultipleDetails = TRUE; // Show multiple details
		$this->GridAddRowCount = 5;
		$this->AllowAddDeleteRow = TRUE; // Allow add/delete row
		$this->UserIDAllowSecurity = 0; // User ID Allow
		$this->BasicSearch = new BasicSearch($this->TableVar);
		$this->BasicSearch->TypeDefault = "AND";

		// ClientID
		$this->ClientID = new DbField('clients', 'clients', 'x_ClientID', 'ClientID', '`ClientID`', '`ClientID`', 3, -1, FALSE, '`ClientID`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'HIDDEN');
		$this->ClientID->IsAutoIncrement = TRUE; // Autoincrement field
		$this->ClientID->IsPrimaryKey = TRUE; // Primary key field
		$this->ClientID->IsForeignKey = TRUE; // Foreign key field
		$this->ClientID->Sortable = TRUE; // Allow sort
		$this->ClientID->DefaultErrorMessage = $Language->phrase("IncorrectInteger");
		$this->fields['ClientID'] = &$this->ClientID;

		// ClientTypeID
		$this->ClientTypeID = new DbField('clients', 'clients', 'x_ClientTypeID', 'ClientTypeID', '`ClientTypeID`', '`ClientTypeID`', 3, -1, FALSE, '`ClientTypeID`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'SELECT');
		$this->ClientTypeID->Nullable = FALSE; // NOT NULL field
		$this->ClientTypeID->Required = TRUE; // Required field
		$this->ClientTypeID->Sortable = TRUE; // Allow sort
		$this->ClientTypeID->UsePleaseSelect = TRUE; // Use PleaseSelect by default
		$this->ClientTypeID->PleaseSelectText = $Language->phrase("PleaseSelect"); // PleaseSelect text
		switch ($CurrentLanguage) {
			case "ar":
				$this->ClientTypeID->Lookup = new Lookup('ClientTypeID', 'partiestype', FALSE, 'PartiesTypeID', ["PartiesType",null,null,""], [], [], [], [], [], [], '', '');
				break;
			case "en":
				$this->ClientTypeID->Lookup = new Lookup('ClientTypeID', 'partiestype', FALSE, 'PartiesTypeID', ["PartiesTypeEn",null,null,""], [], [], [], [], [], [], '', '');
				break;
			case "fr":
				$this->ClientTypeID->Lookup = new Lookup('ClientTypeID', 'partiestype', FALSE, 'PartiesTypeID', ["PartiesTypeEn",null,null,""], [], [], [], [], [], [], '', '');
				break;
			default:
				$this->ClientTypeID->Lookup = new Lookup('ClientTypeID', 'partiestype', FALSE, 'PartiesTypeID', ["PartiesType","","",""], [], [], [], [], [], [], '', '');
				break;
		}
		$this->ClientTypeID->DefaultErrorMessage = $Language->phrase("IncorrectInteger");
		$this->fields['ClientTypeID'] = &$this->ClientTypeID;

		// ClientGroupID
		$this->ClientGroupID = new DbField('clients', 'clients', 'x_ClientGroupID', 'ClientGroupID', '`ClientGroupID`', '`ClientGroupID`', 3, -1, FALSE, '`EV__ClientGroupID`', TRUE, TRUE, TRUE, 'FORMATTED TEXT', 'TEXT');
		$this->ClientGroupID->Sortable = TRUE; // Allow sort
		switch ($CurrentLanguage) {
			case "ar":
				$this->ClientGroupID->Lookup = new Lookup('ClientGroupID', 'clients', FALSE, 'ClientID', ["FirstName","MiddleName","LastName",""], [], [], [], [], [], [], '', '');
				break;
			case "en":
				$this->ClientGroupID->Lookup = new Lookup('ClientGroupID', 'clients', FALSE, 'ClientID', ["FirstNameEn","MiddleNameEn","LastNameEn",""], [], [], [], [], [], [], '', '');
				break;
			case "fr":
				$this->ClientGroupID->Lookup = new Lookup('ClientGroupID', 'clients', FALSE, 'ClientID', ["FirstNameEn","MiddleNameEn","LastNameEn",""], [], [], [], [], [], [], '', '');
				break;
			default:
				$this->ClientGroupID->Lookup = new Lookup('ClientGroupID', 'clients', FALSE, 'ClientID', ["FirstName","MiddleName","LastName",""], [], [], [], [], [], [], '', '');
				break;
		}
		$this->ClientGroupID->DefaultErrorMessage = $Language->phrase("IncorrectInteger");
		$this->fields['ClientGroupID'] = &$this->ClientGroupID;

		// TitleID
		$this->TitleID = new DbField('clients', 'clients', 'x_TitleID', 'TitleID', '`TitleID`', '`TitleID`', 3, -1, FALSE, '`TitleID`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'SELECT');
		$this->TitleID->Sortable = TRUE; // Allow sort
		$this->TitleID->UsePleaseSelect = TRUE; // Use PleaseSelect by default
		$this->TitleID->PleaseSelectText = $Language->phrase("PleaseSelect"); // PleaseSelect text
		switch ($CurrentLanguage) {
			case "ar":
				$this->TitleID->Lookup = new Lookup('TitleID', 'titles', FALSE, 'TitleID', ["Title",null,null,""], [], [], [], [], [], [], '', '');
				break;
			case "en":
				$this->TitleID->Lookup = new Lookup('TitleID', 'titles', FALSE, 'TitleID', ["TitleEn",null,null,""], [], [], [], [], [], [], '', '');
				break;
			case "fr":
				$this->TitleID->Lookup = new Lookup('TitleID', 'titles', FALSE, 'TitleID', ["TitleEn",null,null,""], [], [], [], [], [], [], '', '');
				break;
			default:
				$this->TitleID->Lookup = new Lookup('TitleID', 'titles', FALSE, 'TitleID', ["Title","","",""], [], [], [], [], [], [], '', '');
				break;
		}
		$this->TitleID->DefaultErrorMessage = $Language->phrase("IncorrectInteger");
		$this->fields['TitleID'] = &$this->TitleID;

		// FirstName
		$this->FirstName = new DbField('clients', 'clients', 'x_FirstName', 'FirstName', '`FirstName`', '`FirstName`', 200, -1, FALSE, '`FirstName`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->FirstName->Sortable = TRUE; // Allow sort
		$this->fields['FirstName'] = &$this->FirstName;

		// MiddleName
		$this->MiddleName = new DbField('clients', 'clients', 'x_MiddleName', 'MiddleName', '`MiddleName`', '`MiddleName`', 200, -1, FALSE, '`MiddleName`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->MiddleName->Sortable = TRUE; // Allow sort
		$this->fields['MiddleName'] = &$this->MiddleName;

		// LastName
		$this->LastName = new DbField('clients', 'clients', 'x_LastName', 'LastName', '`LastName`', '`LastName`', 200, -1, FALSE, '`LastName`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->LastName->Sortable = TRUE; // Allow sort
		$this->fields['LastName'] = &$this->LastName;

		// PartnersName
		$this->PartnersName = new DbField('clients', 'clients', 'x_PartnersName', 'PartnersName', '`PartnersName`', '`PartnersName`', 200, -1, FALSE, '`PartnersName`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->PartnersName->Sortable = TRUE; // Allow sort
		$this->fields['PartnersName'] = &$this->PartnersName;

		// CompanyName
		$this->CompanyName = new DbField('clients', 'clients', 'x_CompanyName', 'CompanyName', '`CompanyName`', '`CompanyName`', 200, -1, FALSE, '`CompanyName`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->CompanyName->Sortable = TRUE; // Allow sort
		$this->fields['CompanyName'] = &$this->CompanyName;

		// ContactPerson
		$this->ContactPerson = new DbField('clients', 'clients', 'x_ContactPerson', 'ContactPerson', '`ContactPerson`', '`ContactPerson`', 200, -1, FALSE, '`ContactPerson`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->ContactPerson->Sortable = TRUE; // Allow sort
		$this->fields['ContactPerson'] = &$this->ContactPerson;

		// WorkNature
		$this->WorkNature = new DbField('clients', 'clients', 'x_WorkNature', 'WorkNature', '`WorkNature`', '`WorkNature`', 200, -1, FALSE, '`WorkNature`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->WorkNature->Sortable = TRUE; // Allow sort
		$this->fields['WorkNature'] = &$this->WorkNature;

		// JobTitle
		$this->JobTitle = new DbField('clients', 'clients', 'x_JobTitle', 'JobTitle', '`JobTitle`', '`JobTitle`', 200, -1, FALSE, '`JobTitle`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->JobTitle->Sortable = TRUE; // Allow sort
		$this->fields['JobTitle'] = &$this->JobTitle;

		// Photo
		$this->Photo = new DbField('clients', 'clients', 'x_Photo', 'Photo', '`Photo`', '`Photo`', 200, -1, TRUE, '`Photo`', FALSE, FALSE, FALSE, 'IMAGE', 'FILE');
		$this->Photo->Sortable = TRUE; // Allow sort
		$this->fields['Photo'] = &$this->Photo;

		// BirthDate
		$this->BirthDate = new DbField('clients', 'clients', 'x_BirthDate', 'BirthDate', '`BirthDate`', CastDateFieldForLike('`BirthDate`', 0, "DB"), 135, 0, FALSE, '`BirthDate`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->BirthDate->Sortable = TRUE; // Allow sort
		$this->BirthDate->DefaultErrorMessage = str_replace("%s", $GLOBALS["DATE_FORMAT"], $Language->phrase("IncorrectDate"));
		$this->fields['BirthDate'] = &$this->BirthDate;

		// Title
		$this->Title = new DbField('clients', 'clients', 'x_Title', 'Title', '`Title`', '`Title`', 200, -1, FALSE, '`Title`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->Title->Sortable = FALSE; // Allow sort
		$this->fields['Title'] = &$this->Title;

		// TitleEn
		$this->TitleEn = new DbField('clients', 'clients', 'x_TitleEn', 'TitleEn', '`TitleEn`', '`TitleEn`', 200, -1, FALSE, '`TitleEn`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->TitleEn->Sortable = FALSE; // Allow sort
		$this->fields['TitleEn'] = &$this->TitleEn;

		// FirstNameEn
		$this->FirstNameEn = new DbField('clients', 'clients', 'x_FirstNameEn', 'FirstNameEn', '`FirstNameEn`', '`FirstNameEn`', 200, -1, FALSE, '`FirstNameEn`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->FirstNameEn->Sortable = FALSE; // Allow sort
		$this->fields['FirstNameEn'] = &$this->FirstNameEn;

		// MiddleNameEn
		$this->MiddleNameEn = new DbField('clients', 'clients', 'x_MiddleNameEn', 'MiddleNameEn', '`MiddleNameEn`', '`MiddleNameEn`', 200, -1, FALSE, '`MiddleNameEn`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->MiddleNameEn->Sortable = FALSE; // Allow sort
		$this->fields['MiddleNameEn'] = &$this->MiddleNameEn;

		// LastNameEn
		$this->LastNameEn = new DbField('clients', 'clients', 'x_LastNameEn', 'LastNameEn', '`LastNameEn`', '`LastNameEn`', 200, -1, FALSE, '`LastNameEn`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->LastNameEn->Sortable = FALSE; // Allow sort
		$this->fields['LastNameEn'] = &$this->LastNameEn;

		// PartnersNameEn
		$this->PartnersNameEn = new DbField('clients', 'clients', 'x_PartnersNameEn', 'PartnersNameEn', '`PartnersNameEn`', '`PartnersNameEn`', 200, -1, FALSE, '`PartnersNameEn`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->PartnersNameEn->Sortable = FALSE; // Allow sort
		$this->fields['PartnersNameEn'] = &$this->PartnersNameEn;

		// CompanyNameEn
		$this->CompanyNameEn = new DbField('clients', 'clients', 'x_CompanyNameEn', 'CompanyNameEn', '`CompanyNameEn`', '`CompanyNameEn`', 200, -1, FALSE, '`CompanyNameEn`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->CompanyNameEn->Sortable = FALSE; // Allow sort
		$this->fields['CompanyNameEn'] = &$this->CompanyNameEn;

		// AddressID
		$this->AddressID = new DbField('clients', 'clients', 'x_AddressID', 'AddressID', '`AddressID`', '`AddressID`', 3, -1, FALSE, '`AddressID`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->AddressID->Sortable = FALSE; // Allow sort
		$this->AddressID->DefaultErrorMessage = $Language->phrase("IncorrectInteger");
		$this->fields['AddressID'] = &$this->AddressID;

		// ContactID
		$this->ContactID = new DbField('clients', 'clients', 'x_ContactID', 'ContactID', '`ContactID`', '`ContactID`', 3, -1, FALSE, '`ContactID`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->ContactID->Sortable = FALSE; // Allow sort
		$this->ContactID->DefaultErrorMessage = $Language->phrase("IncorrectInteger");
		$this->fields['ContactID'] = &$this->ContactID;

		// Gender
		$this->Gender = new DbField('clients', 'clients', 'x_Gender', 'Gender', '`Gender`', '`Gender`', 202, -1, FALSE, '`Gender`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'RADIO');
		$this->Gender->Sortable = TRUE; // Allow sort
		switch ($CurrentLanguage) {
			case "ar":
				$this->Gender->Lookup = new Lookup('Gender', 'clients', FALSE, '', [null,null,null,""], [], [], [], [], [], [], '', '');
				break;
			case "en":
				$this->Gender->Lookup = new Lookup('Gender', 'clients', FALSE, '', [null,null,null,""], [], [], [], [], [], [], '', '');
				break;
			case "fr":
				$this->Gender->Lookup = new Lookup('Gender', 'clients', FALSE, '', [null,null,null,""], [], [], [], [], [], [], '', '');
				break;
			default:
				$this->Gender->Lookup = new Lookup('Gender', 'clients', FALSE, '', ["","","",""], [], [], [], [], [], [], '', '');
				break;
		}
		$this->Gender->OptionCount = 2;
		$this->fields['Gender'] = &$this->Gender;

		// Notes
		$this->Notes = new DbField('clients', 'clients', 'x_Notes', 'Notes', '`Notes`', '`Notes`', 201, -1, FALSE, '`Notes`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXTAREA');
		$this->Notes->Sortable = TRUE; // Allow sort
		$this->fields['Notes'] = &$this->Notes;

		// Activated
		$this->Activated = new DbField('clients', 'clients', 'x_Activated', 'Activated', '`Activated`', '`Activated`', 202, -1, FALSE, '`Activated`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'CHECKBOX');
		$this->Activated->Nullable = FALSE; // NOT NULL field
		$this->Activated->Sortable = FALSE; // Allow sort
		$this->Activated->DataType = DATATYPE_BOOLEAN;
		$this->Activated->TrueValue = 'Y';
		$this->Activated->FalseValue = 'N';
		switch ($CurrentLanguage) {
			case "ar":
				$this->Activated->Lookup = new Lookup('Activated', 'clients', FALSE, '', [null,null,null,""], [], [], [], [], [], [], '', '');
				break;
			case "en":
				$this->Activated->Lookup = new Lookup('Activated', 'clients', FALSE, '', [null,null,null,""], [], [], [], [], [], [], '', '');
				break;
			case "fr":
				$this->Activated->Lookup = new Lookup('Activated', 'clients', FALSE, '', [null,null,null,""], [], [], [], [], [], [], '', '');
				break;
			default:
				$this->Activated->Lookup = new Lookup('Activated', 'clients', FALSE, '', ["","","",""], [], [], [], [], [], [], '', '');
				break;
		}
		$this->Activated->OptionCount = 2;
		$this->fields['Activated'] = &$this->Activated;

		// Profile
		$this->Profile = new DbField('clients', 'clients', 'x_Profile', 'Profile', '`Profile`', '`Profile`', 201, -1, FALSE, '`Profile`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXTAREA');
		$this->Profile->Sortable = FALSE; // Allow sort
		$this->fields['Profile'] = &$this->Profile;

		// UserID
		$this->_UserID = new DbField('clients', 'clients', 'x__UserID', 'UserID', '`UserID`', '`UserID`', 3, -1, FALSE, '`UserID`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->_UserID->Sortable = FALSE; // Allow sort
		$this->_UserID->DefaultErrorMessage = $Language->phrase("IncorrectInteger");
		$this->fields['UserID'] = &$this->_UserID;

		// CreatedBy
		$this->CreatedBy = new DbField('clients', 'clients', 'x_CreatedBy', 'CreatedBy', '`CreatedBy`', '`CreatedBy`', 200, -1, FALSE, '`CreatedBy`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->CreatedBy->Sortable = FALSE; // Allow sort
		$this->fields['CreatedBy'] = &$this->CreatedBy;

		// CreatedDate
		$this->CreatedDate = new DbField('clients', 'clients', 'x_CreatedDate', 'CreatedDate', '`CreatedDate`', CastDateFieldForLike('`CreatedDate`', 0, "DB"), 135, 0, FALSE, '`CreatedDate`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->CreatedDate->Sortable = FALSE; // Allow sort
		$this->CreatedDate->DefaultErrorMessage = str_replace("%s", $GLOBALS["DATE_FORMAT"], $Language->phrase("IncorrectDate"));
		$this->fields['CreatedDate'] = &$this->CreatedDate;

		// UpdatedBy
		$this->UpdatedBy = new DbField('clients', 'clients', 'x_UpdatedBy', 'UpdatedBy', '`UpdatedBy`', '`UpdatedBy`', 200, -1, FALSE, '`UpdatedBy`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->UpdatedBy->Sortable = FALSE; // Allow sort
		$this->fields['UpdatedBy'] = &$this->UpdatedBy;

		// UpdatedDate
		$this->UpdatedDate = new DbField('clients', 'clients', 'x_UpdatedDate', 'UpdatedDate', '`UpdatedDate`', CastDateFieldForLike('`UpdatedDate`', 0, "DB"), 135, 0, FALSE, '`UpdatedDate`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->UpdatedDate->Sortable = FALSE; // Allow sort
		$this->UpdatedDate->DefaultErrorMessage = str_replace("%s", $GLOBALS["DATE_FORMAT"], $Language->phrase("IncorrectDate"));
		$this->fields['UpdatedDate'] = &$this->UpdatedDate;

		// FileNumber
		$this->FileNumber = new DbField('clients', 'clients', 'x_FileNumber', 'FileNumber', '`FileNumber`', '`FileNumber`', 200, -1, FALSE, '`FileNumber`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->FileNumber->Sortable = FALSE; // Allow sort
		$this->fields['FileNumber'] = &$this->FileNumber;

		// NotesConv
		$this->NotesConv = new DbField('clients', 'clients', 'x_NotesConv', 'NotesConv', '`NotesConv`', '`NotesConv`', 200, -1, FALSE, '`NotesConv`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->NotesConv->Sortable = FALSE; // Allow sort
		$this->fields['NotesConv'] = &$this->NotesConv;
	}

	// Field Visibility
	public function getFieldVisibility($fldParm)
	{
		global $Security;
		return $this->$fldParm->Visible; // Returns original value
	}

	// Set left column class (must be predefined col-*-* classes of Bootstrap grid system)
	function setLeftColumnClass($class)
	{
		if (preg_match('/^col\-(\w+)\-(\d+)$/', $class, $match)) {
			$this->LeftColumnClass = $class . " col-form-label ew-label";
			$this->RightColumnClass = "col-" . $match[1] . "-" . strval(12 - (int)$match[2]);
			$this->OffsetColumnClass = $this->RightColumnClass . " " . str_replace("col-", "offset-", $class);
			$this->TableLeftColumnClass = preg_replace('/^col-\w+-(\d+)$/', "w-col-$1", $class); // Change to w-col-*
		}
	}

	// Multiple column sort
	public function updateSort(&$fld, $ctrl)
	{
		if ($this->CurrentOrder == $fld->Name) {
			$sortField = $fld->Expression;
			$lastSort = $fld->getSort();
			if ($this->CurrentOrderType == "ASC" || $this->CurrentOrderType == "DESC") {
				$thisSort = $this->CurrentOrderType;
			} else {
				$thisSort = ($lastSort == "ASC") ? "DESC" : "ASC";
			}
			$fld->setSort($thisSort);
			if ($ctrl) {
				$orderBy = $this->getSessionOrderBy();
				if (ContainsString($orderBy, $sortField . " " . $lastSort)) {
					$orderBy = str_replace($sortField . " " . $lastSort, $sortField . " " . $thisSort, $orderBy);
				} else {
					if ($orderBy <> "")
						$orderBy .= ", ";
					$orderBy .= $sortField . " " . $thisSort;
				}
				$this->setSessionOrderBy($orderBy); // Save to Session
			} else {
				$this->setSessionOrderBy($sortField . " " . $thisSort); // Save to Session
			}
			$sortFieldList = ($fld->VirtualExpression <> "") ? $fld->VirtualExpression : $sortField;
			if ($ctrl) {
				$orderByList = $this->getSessionOrderByList();
				if (ContainsString($orderByList, $sortFieldList . " " . $lastSort)) {
					$orderByList = str_replace($sortFieldList . " " . $lastSort, $sortFieldList . " " . $thisSort, $orderByList);
				} else {
					if ($orderByList <> "") $orderByList .= ", ";
					$orderByList .= $sortFieldList . " " . $thisSort;
				}
				$this->setSessionOrderByList($orderByList); // Save to Session
			} else {
				$this->setSessionOrderByList($sortFieldList . " " . $thisSort); // Save to Session
			}
		} else {
			if (!$ctrl)
				$fld->setSort("");
		}
	}

	// Session ORDER BY for List page
	public function getSessionOrderByList()
	{
		return @$_SESSION[PROJECT_NAME . "_" . $this->TableVar . "_" . TABLE_ORDER_BY_LIST];
	}
	public function setSessionOrderByList($v)
	{
		$_SESSION[PROJECT_NAME . "_" . $this->TableVar . "_" . TABLE_ORDER_BY_LIST] = $v;
	}

	// Current detail table name
	public function getCurrentDetailTable()
	{
		return @$_SESSION[PROJECT_NAME . "_" . $this->TableVar . "_" . TABLE_DETAIL_TABLE];
	}
	public function setCurrentDetailTable($v)
	{
		$_SESSION[PROJECT_NAME . "_" . $this->TableVar . "_" . TABLE_DETAIL_TABLE] = $v;
	}

	// Get detail url
	public function getDetailUrl()
	{

		// Detail url
		$detailUrl = "";
		if ($this->getCurrentDetailTable() == "cases") {
			$detailUrl = $GLOBALS["cases"]->getListUrl() . "?" . TABLE_SHOW_MASTER . "=" . $this->TableVar;
			$detailUrl .= "&fk_ClientID=" . urlencode($this->ClientID->CurrentValue);
		}
		if ($this->getCurrentDetailTable() == "clientadditinalinfo") {
			$detailUrl = $GLOBALS["clientadditinalinfo"]->getListUrl() . "?" . TABLE_SHOW_MASTER . "=" . $this->TableVar;
			$detailUrl .= "&fk_ClientID=" . urlencode($this->ClientID->CurrentValue);
		}
		if ($this->getCurrentDetailTable() == "clientaddress") {
			$detailUrl = $GLOBALS["clientaddress"]->getListUrl() . "?" . TABLE_SHOW_MASTER . "=" . $this->TableVar;
			$detailUrl .= "&fk_ClientID=" . urlencode($this->ClientID->CurrentValue);
		}
		if ($this->getCurrentDetailTable() == "clientcontact") {
			$detailUrl = $GLOBALS["clientcontact"]->getListUrl() . "?" . TABLE_SHOW_MASTER . "=" . $this->TableVar;
			$detailUrl .= "&fk_ClientID=" . urlencode($this->ClientID->CurrentValue);
		}
		if ($this->getCurrentDetailTable() == "clientpartners") {
			$detailUrl = $GLOBALS["clientpartners"]->getListUrl() . "?" . TABLE_SHOW_MASTER . "=" . $this->TableVar;
			$detailUrl .= "&fk_ClientID=" . urlencode($this->ClientID->CurrentValue);
		}
		if ($detailUrl == "")
			$detailUrl = "clientslist.php";
		return $detailUrl;
	}

	// Table level SQL
	public function getSqlFrom() // From
	{
		return ($this->SqlFrom <> "") ? $this->SqlFrom : "`clients`";
	}
	public function sqlFrom() // For backward compatibility
	{
		return $this->getSqlFrom();
	}
	public function setSqlFrom($v)
	{
		$this->SqlFrom = $v;
	}
	public function getSqlSelect() // Select
	{
		return ($this->SqlSelect <> "") ? $this->SqlSelect : "SELECT * FROM " . $this->getSqlFrom();
	}
	public function sqlSelect() // For backward compatibility
	{
		return $this->getSqlSelect();
	}
	public function setSqlSelect($v)
	{
		$this->SqlSelect = $v;
	}
	public function getSqlSelectList() // Select for List page
	{
		$select = "";
		global $CurrentLanguage;
		switch ($CurrentLanguage) {
			case "ar":
				$select = "SELECT * FROM (" .
					"SELECT *, (SELECT CONCAT(COALESCE(`FirstName`, ''),'" . ValueSeparator(1, $this->ClientGroupID) . "',COALESCE(`MiddleName`,''),'" . ValueSeparator(2, $this->ClientGroupID) . "',COALESCE(`LastName`,'')) FROM `clients` `TMP_LOOKUPTABLE` WHERE `TMP_LOOKUPTABLE`.`ClientID` = `clients`.`ClientGroupID` LIMIT 1) AS `EV__ClientGroupID` FROM `clients`" .
					") `TMP_TABLE`";
				break;
			case "en":
				$select = "SELECT * FROM (" .
					"SELECT *, (SELECT CONCAT(COALESCE(`FirstNameEn`, ''),'" . ValueSeparator(1, $this->ClientGroupID) . "',COALESCE(`MiddleNameEn`,''),'" . ValueSeparator(2, $this->ClientGroupID) . "',COALESCE(`LastNameEn`,'')) FROM `clients` `TMP_LOOKUPTABLE` WHERE `TMP_LOOKUPTABLE`.`ClientID` = `clients`.`ClientGroupID` LIMIT 1) AS `EV__ClientGroupID` FROM `clients`" .
					") `TMP_TABLE`";
				break;
			case "fr":
				$select = "SELECT * FROM (" .
					"SELECT *, (SELECT CONCAT(COALESCE(`FirstNameEn`, ''),'" . ValueSeparator(1, $this->ClientGroupID) . "',COALESCE(`MiddleNameEn`,''),'" . ValueSeparator(2, $this->ClientGroupID) . "',COALESCE(`LastNameEn`,'')) FROM `clients` `TMP_LOOKUPTABLE` WHERE `TMP_LOOKUPTABLE`.`ClientID` = `clients`.`ClientGroupID` LIMIT 1) AS `EV__ClientGroupID` FROM `clients`" .
					") `TMP_TABLE`";
				break;
			default:
				$select = "SELECT * FROM (" .
					"SELECT *, (SELECT CONCAT(COALESCE(`FirstName`, ''),'" . ValueSeparator(1, $this->ClientGroupID) . "',COALESCE(`MiddleName`,''),'" . ValueSeparator(2, $this->ClientGroupID) . "',COALESCE(`LastName`,'')) FROM `clients` `TMP_LOOKUPTABLE` WHERE `TMP_LOOKUPTABLE`.`ClientID` = `clients`.`ClientGroupID` LIMIT 1) AS `EV__ClientGroupID` FROM `clients`" .
					") `TMP_TABLE`";
				break;
		}
		return ($this->SqlSelectList <> "") ? $this->SqlSelectList : $select;
	}
	public function sqlSelectList() // For backward compatibility
	{
		return $this->getSqlSelectList();
	}
	public function setSqlSelectList($v)
	{
		$this->SqlSelectList = $v;
	}
	public function getSqlWhere() // Where
	{
		$where = ($this->SqlWhere <> "") ? $this->SqlWhere : "";
		$this->TableFilter = "";
		AddFilter($where, $this->TableFilter);
		return $where;
	}
	public function sqlWhere() // For backward compatibility
	{
		return $this->getSqlWhere();
	}
	public function setSqlWhere($v)
	{
		$this->SqlWhere = $v;
	}
	public function getSqlGroupBy() // Group By
	{
		return ($this->SqlGroupBy <> "") ? $this->SqlGroupBy : "";
	}
	public function sqlGroupBy() // For backward compatibility
	{
		return $this->getSqlGroupBy();
	}
	public function setSqlGroupBy($v)
	{
		$this->SqlGroupBy = $v;
	}
	public function getSqlHaving() // Having
	{
		return ($this->SqlHaving <> "") ? $this->SqlHaving : "";
	}
	public function sqlHaving() // For backward compatibility
	{
		return $this->getSqlHaving();
	}
	public function setSqlHaving($v)
	{
		$this->SqlHaving = $v;
	}
	public function getSqlOrderBy() // Order By
	{
		return ($this->SqlOrderBy <> "") ? $this->SqlOrderBy : "";
	}
	public function sqlOrderBy() // For backward compatibility
	{
		return $this->getSqlOrderBy();
	}
	public function setSqlOrderBy($v)
	{
		$this->SqlOrderBy = $v;
	}

	// Apply User ID filters
	public function applyUserIDFilters($filter)
	{
		return $filter;
	}

	// Check if User ID security allows view all
	public function userIDAllow($id = "")
	{
		$allow = USER_ID_ALLOW;
		switch ($id) {
			case "add":
			case "copy":
			case "gridadd":
			case "register":
			case "addopt":
				return (($allow & 1) == 1);
			case "edit":
			case "gridedit":
			case "update":
			case "changepwd":
			case "forgotpwd":
				return (($allow & 4) == 4);
			case "delete":
				return (($allow & 2) == 2);
			case "view":
				return (($allow & 32) == 32);
			case "search":
				return (($allow & 64) == 64);
			default:
				return (($allow & 8) == 8);
		}
	}

	// Get SQL
	public function getSql($where, $orderBy = "")
	{
		return BuildSelectSql($this->getSqlSelect(), $this->getSqlWhere(),
			$this->getSqlGroupBy(), $this->getSqlHaving(), $this->getSqlOrderBy(),
			$where, $orderBy);
	}

	// Table SQL
	public function getCurrentSql()
	{
		$filter = $this->CurrentFilter;
		$filter = $this->applyUserIDFilters($filter);
		$sort = $this->getSessionOrderBy();
		return $this->getSql($filter, $sort);
	}

	// Table SQL with List page filter
	public function getListSql()
	{
		$filter = $this->UseSessionForListSql ? $this->getSessionWhere() : "";
		AddFilter($filter, $this->CurrentFilter);
		$filter = $this->applyUserIDFilters($filter);
		$this->Recordset_Selecting($filter);
		if ($this->useVirtualFields()) {
			$select = $this->getSqlSelectList();
			$sort = $this->UseSessionForListSql ? $this->getSessionOrderByList() : "";
		} else {
			$select = $this->getSqlSelect();
			$sort = $this->UseSessionForListSql ? $this->getSessionOrderBy() : "";
		}
		return BuildSelectSql($select, $this->getSqlWhere(), $this->getSqlGroupBy(),
			$this->getSqlHaving(), $this->getSqlOrderBy(), $filter, $sort);
	}

	// Get ORDER BY clause
	public function getOrderBy()
	{
		$sort = ($this->useVirtualFields()) ? $this->getSessionOrderByList() : $this->getSessionOrderBy();
		return BuildSelectSql("", "", "", "", $this->getSqlOrderBy(), "", $sort);
	}

	// Check if virtual fields is used in SQL
	protected function useVirtualFields()
	{
		$where = $this->UseSessionForListSql ? $this->getSessionWhere() : $this->CurrentFilter;
		$orderBy = $this->UseSessionForListSql ? $this->getSessionOrderByList() : "";
		if ($where <> "")
			$where = " " . str_replace(array("(",")"), array("",""), $where) . " ";
		if ($orderBy <> "")
			$orderBy = " " . str_replace(array("(",")"), array("",""), $orderBy) . " ";
		if ($this->ClientGroupID->AdvancedSearch->SearchValue <> "" ||
			$this->ClientGroupID->AdvancedSearch->SearchValue2 <> "" ||
			ContainsString($where, " " . $this->ClientGroupID->VirtualExpression . " "))
			return TRUE;
		if (ContainsString($orderBy, " " . $this->ClientGroupID->VirtualExpression . " "))
			return TRUE;
		return FALSE;
	}

	// Get record count
	public function getRecordCount($sql)
	{
		$cnt = -1;
		$rs = NULL;
		$sql = preg_replace('/\/\*BeginOrderBy\*\/[\s\S]+\/\*EndOrderBy\*\//', "", $sql); // Remove ORDER BY clause (MSSQL)
		$pattern = '/^SELECT\s([\s\S]+)\sFROM\s/i';

		// Skip Custom View / SubQuery and SELECT DISTINCT
		if (($this->TableType == 'TABLE' || $this->TableType == 'VIEW' || $this->TableType == 'LINKTABLE') &&
			preg_match($pattern, $sql) && !preg_match('/\(\s*(SELECT[^)]+)\)/i', $sql) && !preg_match('/^\s*select\s+distinct\s+/i', $sql)) {
			$sqlwrk = "SELECT COUNT(*) FROM " . preg_replace($pattern, "", $sql);
		} else {
			$sqlwrk = "SELECT COUNT(*) FROM (" . $sql . ") COUNT_TABLE";
		}
		$conn = &$this->getConnection();
		if ($rs = $conn->execute($sqlwrk)) {
			if (!$rs->EOF && $rs->FieldCount() > 0) {
				$cnt = $rs->fields[0];
				$rs->close();
			}
			return (int)$cnt;
		}

		// Unable to get count, get record count directly
		if ($rs = $conn->execute($sql)) {
			$cnt = $rs->RecordCount();
			$rs->close();
			return (int)$cnt;
		}
		return $cnt;
	}

	// Get record count based on filter (for detail record count in master table pages)
	public function loadRecordCount($filter)
	{
		$origFilter = $this->CurrentFilter;
		$this->CurrentFilter = $filter;
		$this->Recordset_Selecting($this->CurrentFilter);
		$select = $this->TableType == 'CUSTOMVIEW' ? $this->getSqlSelect() : "SELECT * FROM " . $this->getSqlFrom();
		$groupBy = $this->TableType == 'CUSTOMVIEW' ? $this->getSqlGroupBy() : "";
		$having = $this->TableType == 'CUSTOMVIEW' ? $this->getSqlHaving() : "";
		$sql = BuildSelectSql($select, $this->getSqlWhere(), $groupBy, $having, "", $this->CurrentFilter, "");
		$cnt = $this->getRecordCount($sql);
		$this->CurrentFilter = $origFilter;
		return $cnt;
	}

	// Get record count (for current List page)
	public function listRecordCount()
	{
		$filter = $this->getSessionWhere();
		AddFilter($filter, $this->CurrentFilter);
		$filter = $this->applyUserIDFilters($filter);
		$this->Recordset_Selecting($filter);
		$select = $this->TableType == 'CUSTOMVIEW' ? $this->getSqlSelect() : "SELECT * FROM " . $this->getSqlFrom();
		$groupBy = $this->TableType == 'CUSTOMVIEW' ? $this->getSqlGroupBy() : "";
		$having = $this->TableType == 'CUSTOMVIEW' ? $this->getSqlHaving() : "";
		if ($this->useVirtualFields())
			$sql = BuildSelectSql($this->getSqlSelectList(), $this->getSqlWhere(), $groupBy, $having, "", $filter, "");
		else
			$sql = BuildSelectSql($select, $this->getSqlWhere(), $groupBy, $having, "", $filter, "");
		$cnt = $this->getRecordCount($sql);
		return $cnt;
	}

	// INSERT statement
	protected function insertSql(&$rs)
	{
		$names = "";
		$values = "";
		foreach ($rs as $name => $value) {
			if (!isset($this->fields[$name]) || $this->fields[$name]->IsCustom)
				continue;
			$names .= $this->fields[$name]->Expression . ",";
			$values .= QuotedValue($value, $this->fields[$name]->DataType, $this->Dbid) . ",";
		}
		$names = preg_replace('/,+$/', "", $names);
		$values = preg_replace('/,+$/', "", $values);
		return "INSERT INTO " . $this->UpdateTable . " ($names) VALUES ($values)";
	}

	// Insert
	public function insert(&$rs)
	{
		$conn = &$this->getConnection();
		$success = $conn->execute($this->insertSql($rs));
		if ($success) {

			// Get insert id if necessary
			$this->ClientID->setDbValue($conn->insert_ID());
			$rs['ClientID'] = $this->ClientID->DbValue;
			if ($this->AuditTrailOnAdd)
				$this->writeAuditTrailOnAdd($rs);
		}
		return $success;
	}

	// UPDATE statement
	protected function updateSql(&$rs, $where = "", $curfilter = TRUE)
	{
		$sql = "UPDATE " . $this->UpdateTable . " SET ";
		foreach ($rs as $name => $value) {
			if (!isset($this->fields[$name]) || $this->fields[$name]->IsCustom || $this->fields[$name]->IsPrimaryKey)
				continue;
			$sql .= $this->fields[$name]->Expression . "=";
			$sql .= QuotedValue($value, $this->fields[$name]->DataType, $this->Dbid) . ",";
		}
		$sql = preg_replace('/,+$/', "", $sql);
		$filter = ($curfilter) ? $this->CurrentFilter : "";
		if (is_array($where))
			$where = $this->arrayToFilter($where);
		AddFilter($filter, $where);
		if ($filter <> "")
			$sql .= " WHERE " . $filter;
		return $sql;
	}

	// Update
	public function update(&$rs, $where = "", $rsold = NULL, $curfilter = TRUE)
	{
		$conn = &$this->getConnection();
		$success = $conn->execute($this->updateSql($rs, $where, $curfilter));
		if ($success && $this->AuditTrailOnEdit && $rsold) {
			$rsaudit = $rs;
			$fldname = 'ClientID';
			if (!array_key_exists($fldname, $rsaudit))
				$rsaudit[$fldname] = $rsold[$fldname];
			$this->writeAuditTrailOnEdit($rsold, $rsaudit);
		}
		return $success;
	}

	// DELETE statement
	protected function deleteSql(&$rs, $where = "", $curfilter = TRUE)
	{
		$sql = "DELETE FROM " . $this->UpdateTable . " WHERE ";
		if (is_array($where))
			$where = $this->arrayToFilter($where);
		if ($rs) {
			if (array_key_exists('ClientID', $rs))
				AddFilter($where, QuotedName('ClientID', $this->Dbid) . '=' . QuotedValue($rs['ClientID'], $this->ClientID->DataType, $this->Dbid));
		}
		$filter = ($curfilter) ? $this->CurrentFilter : "";
		AddFilter($filter, $where);
		if ($filter <> "")
			$sql .= $filter;
		else
			$sql .= "0=1"; // Avoid delete
		return $sql;
	}

	// Delete
	public function delete(&$rs, $where = "", $curfilter = FALSE)
	{
		$success = TRUE;
		$conn = &$this->getConnection();

		// Cascade delete detail table 'cases'
		if (!isset($GLOBALS["cases"]))
			$GLOBALS["cases"] = new cases();
		$rscascade = $GLOBALS["cases"]->loadRs("`ClientID` = " . QuotedValue($rs['ClientID'], DATATYPE_NUMBER, "DB")); 
		$dtlrows = ($rscascade) ? $rscascade->getRows() : array();

		// Call Row Deleting event
		foreach ($dtlrows as $dtlrow) {
			$success = $GLOBALS["cases"]->Row_Deleting($dtlrow);
			if (!$success)
				break;
		}
		if ($success) {
			foreach ($dtlrows as $dtlrow) {
				$success = $GLOBALS["cases"]->delete($dtlrow); // Delete
				if (!$success)
					break;
			}
		}

		// Call Row Deleted event
		if ($success) {
			foreach ($dtlrows as $dtlrow)
				$GLOBALS["cases"]->Row_Deleted($dtlrow);
		}
		if ($success)
			$success = $conn->execute($this->deleteSql($rs, $where, $curfilter));
		if ($success && $this->AuditTrailOnDelete)
			$this->writeAuditTrailOnDelete($rs);
		return $success;
	}

	// Load DbValue from recordset or array
	protected function loadDbValues(&$rs)
	{
		if (!$rs || !is_array($rs) && $rs->EOF)
			return;
		$row = is_array($rs) ? $rs : $rs->fields;
		$this->ClientID->DbValue = $row['ClientID'];
		$this->ClientTypeID->DbValue = $row['ClientTypeID'];
		$this->ClientGroupID->DbValue = $row['ClientGroupID'];
		$this->TitleID->DbValue = $row['TitleID'];
		$this->FirstName->DbValue = $row['FirstName'];
		$this->MiddleName->DbValue = $row['MiddleName'];
		$this->LastName->DbValue = $row['LastName'];
		$this->PartnersName->DbValue = $row['PartnersName'];
		$this->CompanyName->DbValue = $row['CompanyName'];
		$this->ContactPerson->DbValue = $row['ContactPerson'];
		$this->WorkNature->DbValue = $row['WorkNature'];
		$this->JobTitle->DbValue = $row['JobTitle'];
		$this->Photo->Upload->DbValue = $row['Photo'];
		$this->BirthDate->DbValue = $row['BirthDate'];
		$this->Title->DbValue = $row['Title'];
		$this->TitleEn->DbValue = $row['TitleEn'];
		$this->FirstNameEn->DbValue = $row['FirstNameEn'];
		$this->MiddleNameEn->DbValue = $row['MiddleNameEn'];
		$this->LastNameEn->DbValue = $row['LastNameEn'];
		$this->PartnersNameEn->DbValue = $row['PartnersNameEn'];
		$this->CompanyNameEn->DbValue = $row['CompanyNameEn'];
		$this->AddressID->DbValue = $row['AddressID'];
		$this->ContactID->DbValue = $row['ContactID'];
		$this->Gender->DbValue = $row['Gender'];
		$this->Notes->DbValue = $row['Notes'];
		$this->Activated->DbValue = $row['Activated'];
		$this->Profile->DbValue = $row['Profile'];
		$this->_UserID->DbValue = $row['UserID'];
		$this->CreatedBy->DbValue = $row['CreatedBy'];
		$this->CreatedDate->DbValue = $row['CreatedDate'];
		$this->UpdatedBy->DbValue = $row['UpdatedBy'];
		$this->UpdatedDate->DbValue = $row['UpdatedDate'];
		$this->FileNumber->DbValue = $row['FileNumber'];
		$this->NotesConv->DbValue = $row['NotesConv'];
	}

	// Delete uploaded files
	public function deleteUploadedFiles($row)
	{
		$this->loadDbValues($row);
		$oldFiles = EmptyValue($row['Photo']) ? [] : [$row['Photo']];
		foreach ($oldFiles as $oldFile) {
			if (file_exists($this->Photo->oldPhysicalUploadPath() . $oldFile))
				@unlink($this->Photo->oldPhysicalUploadPath() . $oldFile);
		}
	}

	// Record filter WHERE clause
	protected function sqlKeyFilter()
	{
		return "`ClientID` = @ClientID@";
	}

	// Get record filter
	public function getRecordFilter($row = NULL)
	{
		$keyFilter = $this->sqlKeyFilter();
		$val = is_array($row) ? (array_key_exists('ClientID', $row) ? $row['ClientID'] : NULL) : $this->ClientID->CurrentValue;
		if (!is_numeric($val))
			return "0=1"; // Invalid key
		if ($val == NULL)
			return "0=1"; // Invalid key
		else
			$keyFilter = str_replace("@ClientID@", AdjustSql($val, $this->Dbid), $keyFilter); // Replace key value
		return $keyFilter;
	}

	// Return page URL
	public function getReturnUrl()
	{
		$name = PROJECT_NAME . "_" . $this->TableVar . "_" . TABLE_RETURN_URL;

		// Get referer URL automatically
		if (ServerVar("HTTP_REFERER") <> "" && ReferPageName() <> CurrentPageName() && ReferPageName() <> "login.php") // Referer not same page or login page
			$_SESSION[$name] = ServerVar("HTTP_REFERER"); // Save to Session
		if (@$_SESSION[$name] <> "") {
			return $_SESSION[$name];
		} else {
			return "clientslist.php";
		}
	}
	public function setReturnUrl($v)
	{
		$_SESSION[PROJECT_NAME . "_" . $this->TableVar . "_" . TABLE_RETURN_URL] = $v;
	}

	// Get modal caption
	public function getModalCaption($pageName)
	{
		global $Language;
		if ($pageName == "clientsview.php")
			return $Language->phrase("View");
		elseif ($pageName == "clientsedit.php")
			return $Language->phrase("Edit");
		elseif ($pageName == "clientsadd.php")
			return $Language->phrase("Add");
		else
			return "";
	}

	// List URL
	public function getListUrl()
	{
		return "clientslist.php";
	}

	// View URL
	public function getViewUrl($parm = "")
	{
		if ($parm <> "")
			$url = $this->keyUrl("clientsview.php", $this->getUrlParm($parm));
		else
			$url = $this->keyUrl("clientsview.php", $this->getUrlParm(TABLE_SHOW_DETAIL . "="));
		return $this->addMasterUrl($url);
	}

	// Add URL
	public function getAddUrl($parm = "")
	{
		if ($parm <> "")
			$url = "clientsadd.php?" . $this->getUrlParm($parm);
		else
			$url = "clientsadd.php";
		return $this->addMasterUrl($url);
	}

	// Edit URL
	public function getEditUrl($parm = "")
	{
		if ($parm <> "")
			$url = $this->keyUrl("clientsedit.php", $this->getUrlParm($parm));
		else
			$url = $this->keyUrl("clientsedit.php", $this->getUrlParm(TABLE_SHOW_DETAIL . "="));
		return $this->addMasterUrl($url);
	}

	// Inline edit URL
	public function getInlineEditUrl()
	{
		$url = $this->keyUrl(CurrentPageName(), $this->getUrlParm("action=edit"));
		return $this->addMasterUrl($url);
	}

	// Copy URL
	public function getCopyUrl($parm = "")
	{
		if ($parm <> "")
			$url = $this->keyUrl("clientsadd.php", $this->getUrlParm($parm));
		else
			$url = $this->keyUrl("clientsadd.php", $this->getUrlParm(TABLE_SHOW_DETAIL . "="));
		return $this->addMasterUrl($url);
	}

	// Inline copy URL
	public function getInlineCopyUrl()
	{
		$url = $this->keyUrl(CurrentPageName(), $this->getUrlParm("action=copy"));
		return $this->addMasterUrl($url);
	}

	// Delete URL
	public function getDeleteUrl()
	{
		return $this->keyUrl("clientsdelete.php", $this->getUrlParm());
	}

	// Add master url
	public function addMasterUrl($url)
	{
		return $url;
	}
	public function keyToJson($htmlEncode = FALSE)
	{
		$json = "";
		$json .= "ClientID:" . JsonEncode($this->ClientID->CurrentValue, "number");
		$json = "{" . $json . "}";
		if ($htmlEncode)
			$json = HtmlEncode($json);
		return $json;
	}

	// Add key value to URL
	public function keyUrl($url, $parm = "")
	{
		$url = $url . "?";
		if ($parm <> "")
			$url .= $parm . "&";
		if ($this->ClientID->CurrentValue != NULL) {
			$url .= "ClientID=" . urlencode($this->ClientID->CurrentValue);
		} else {
			return "javascript:ew.alert(ew.language.phrase('InvalidRecord'));";
		}
		return $url;
	}

	// Sort URL
	public function sortUrl(&$fld)
	{
		if ($this->CurrentAction || $this->isExport() ||
			in_array($fld->Type, array(128, 204, 205))) { // Unsortable data type
				return "";
		} elseif ($fld->Sortable) {
			$urlParm = $this->getUrlParm("order=" . urlencode($fld->Name) . "&amp;ordertype=" . $fld->reverseSort());
			return $this->addMasterUrl(CurrentPageName() . "?" . $urlParm);
		} else {
			return "";
		}
	}

	// Get record keys from Post/Get/Session
	public function getRecordKeys()
	{
		global $COMPOSITE_KEY_SEPARATOR;
		$arKeys = array();
		$arKey = array();
		if (Param("key_m") !== NULL) {
			$arKeys = Param("key_m");
			$cnt = count($arKeys);
		} else {
			if (Param("ClientID") !== NULL)
				$arKeys[] = Param("ClientID");
			elseif (IsApi() && Key(0) !== NULL)
				$arKeys[] = Key(0);
			elseif (IsApi() && Route(2) !== NULL)
				$arKeys[] = Route(2);
			else
				$arKeys = NULL; // Do not setup

			//return $arKeys; // Do not return yet, so the values will also be checked by the following code
		}

		// Check keys
		$ar = array();
		if (is_array($arKeys)) {
			foreach ($arKeys as $key) {
				if (!is_numeric($key))
					continue;
				$ar[] = $key;
			}
		}
		return $ar;
	}

	// Get filter from record keys
	public function getFilterFromRecordKeys()
	{
		$arKeys = $this->getRecordKeys();
		$keyFilter = "";
		foreach ($arKeys as $key) {
			if ($keyFilter <> "") $keyFilter .= " OR ";
			$this->ClientID->CurrentValue = $key;
			$keyFilter .= "(" . $this->getRecordFilter() . ")";
		}
		return $keyFilter;
	}

	// Load rows based on filter
	public function &loadRs($filter)
	{

		// Set up filter (WHERE Clause)
		$sql = $this->getSql($filter);
		$conn = &$this->getConnection();
		$rs = $conn->execute($sql);
		return $rs;
	}

	// Load row values from recordset
	public function loadListRowValues(&$rs)
	{
		$this->ClientID->setDbValue($rs->fields('ClientID'));
		$this->ClientTypeID->setDbValue($rs->fields('ClientTypeID'));
		$this->ClientGroupID->setDbValue($rs->fields('ClientGroupID'));
		$this->TitleID->setDbValue($rs->fields('TitleID'));
		$this->FirstName->setDbValue($rs->fields('FirstName'));
		$this->MiddleName->setDbValue($rs->fields('MiddleName'));
		$this->LastName->setDbValue($rs->fields('LastName'));
		$this->PartnersName->setDbValue($rs->fields('PartnersName'));
		$this->CompanyName->setDbValue($rs->fields('CompanyName'));
		$this->ContactPerson->setDbValue($rs->fields('ContactPerson'));
		$this->WorkNature->setDbValue($rs->fields('WorkNature'));
		$this->JobTitle->setDbValue($rs->fields('JobTitle'));
		$this->Photo->Upload->DbValue = $rs->fields('Photo');
		$this->BirthDate->setDbValue($rs->fields('BirthDate'));
		$this->Title->setDbValue($rs->fields('Title'));
		$this->TitleEn->setDbValue($rs->fields('TitleEn'));
		$this->FirstNameEn->setDbValue($rs->fields('FirstNameEn'));
		$this->MiddleNameEn->setDbValue($rs->fields('MiddleNameEn'));
		$this->LastNameEn->setDbValue($rs->fields('LastNameEn'));
		$this->PartnersNameEn->setDbValue($rs->fields('PartnersNameEn'));
		$this->CompanyNameEn->setDbValue($rs->fields('CompanyNameEn'));
		$this->AddressID->setDbValue($rs->fields('AddressID'));
		$this->ContactID->setDbValue($rs->fields('ContactID'));
		$this->Gender->setDbValue($rs->fields('Gender'));
		$this->Notes->setDbValue($rs->fields('Notes'));
		$this->Activated->setDbValue($rs->fields('Activated'));
		$this->Profile->setDbValue($rs->fields('Profile'));
		$this->_UserID->setDbValue($rs->fields('UserID'));
		$this->CreatedBy->setDbValue($rs->fields('CreatedBy'));
		$this->CreatedDate->setDbValue($rs->fields('CreatedDate'));
		$this->UpdatedBy->setDbValue($rs->fields('UpdatedBy'));
		$this->UpdatedDate->setDbValue($rs->fields('UpdatedDate'));
		$this->FileNumber->setDbValue($rs->fields('FileNumber'));
		$this->NotesConv->setDbValue($rs->fields('NotesConv'));
	}

	// Render list row values
	public function renderListRow()
	{
		global $Security, $CurrentLanguage, $Language;

		// Call Row Rendering event
		$this->Row_Rendering();

		// Common render codes
		// ClientID
		// ClientTypeID
		// ClientGroupID
		// TitleID
		// FirstName

		$this->FirstName->CellCssStyle = "min-width: 150px;";

		// MiddleName
		// LastName
		// PartnersName
		// CompanyName

		$this->CompanyName->CellCssStyle = "min-width: 150px;";

		// ContactPerson
		// WorkNature
		// JobTitle
		// Photo
		// BirthDate
		// Title

		$this->Title->CellCssStyle = "white-space: nowrap;";

		// TitleEn
		$this->TitleEn->CellCssStyle = "white-space: nowrap;";

		// FirstNameEn
		$this->FirstNameEn->CellCssStyle = "width: 500px;";

		// MiddleNameEn
		$this->MiddleNameEn->CellCssStyle = "width: 100px;";

		// LastNameEn
		$this->LastNameEn->CellCssStyle = "width: 500px;";

		// PartnersNameEn
		// CompanyNameEn
		// AddressID

		$this->AddressID->CellCssStyle = "white-space: nowrap;";

		// ContactID
		$this->ContactID->CellCssStyle = "white-space: nowrap;";

		// Gender
		// Notes

		$this->Notes->CellCssStyle = "white-space: nowrap;";

		// Activated
		$this->Activated->CellCssStyle = "white-space: nowrap;";

		// Profile
		$this->Profile->CellCssStyle = "white-space: nowrap;";

		// UserID
		$this->_UserID->CellCssStyle = "white-space: nowrap;";

		// CreatedBy
		$this->CreatedBy->CellCssStyle = "white-space: nowrap;";

		// CreatedDate
		$this->CreatedDate->CellCssStyle = "white-space: nowrap;";

		// UpdatedBy
		$this->UpdatedBy->CellCssStyle = "white-space: nowrap;";

		// UpdatedDate
		$this->UpdatedDate->CellCssStyle = "white-space: nowrap;";

		// FileNumber
		$this->FileNumber->CellCssStyle = "white-space: nowrap;";

		// NotesConv
		$this->NotesConv->CellCssStyle = "white-space: nowrap;";

		// ClientID
		$this->ClientID->ViewValue = $this->ClientID->CurrentValue;
		$this->ClientID->ViewCustomAttributes = "";

		// ClientTypeID
		$curVal = strval($this->ClientTypeID->CurrentValue);
		if ($curVal <> "") {
			$this->ClientTypeID->ViewValue = $this->ClientTypeID->lookupCacheOption($curVal);
			if ($this->ClientTypeID->ViewValue === NULL) { // Lookup from database
				$filterWrk = "`PartiesTypeID`" . SearchString("=", $curVal, DATATYPE_NUMBER, "");
				$sqlWrk = $this->ClientTypeID->Lookup->getSql(FALSE, $filterWrk, '', $this);
				$rswrk = Conn()->execute($sqlWrk);
				if ($rswrk && !$rswrk->EOF) { // Lookup values found
					$arwrk = array();
					$arwrk[1] = $rswrk->fields('df');
					$this->ClientTypeID->ViewValue = $this->ClientTypeID->displayValue($arwrk);
					$rswrk->Close();
				} else {
					$this->ClientTypeID->ViewValue = $this->ClientTypeID->CurrentValue;
				}
			}
		} else {
			$this->ClientTypeID->ViewValue = NULL;
		}
		$this->ClientTypeID->ViewCustomAttributes = "";

		// ClientGroupID
		if ($this->ClientGroupID->VirtualValue <> "") {
			$this->ClientGroupID->ViewValue = $this->ClientGroupID->VirtualValue;
		} else {
			$this->ClientGroupID->ViewValue = $this->ClientGroupID->CurrentValue;
		$curVal = strval($this->ClientGroupID->CurrentValue);
		if ($curVal <> "") {
			$this->ClientGroupID->ViewValue = $this->ClientGroupID->lookupCacheOption($curVal);
			if ($this->ClientGroupID->ViewValue === NULL) { // Lookup from database
				$filterWrk = "`ClientID`" . SearchString("=", $curVal, DATATYPE_NUMBER, "");
				$sqlWrk = $this->ClientGroupID->Lookup->getSql(FALSE, $filterWrk, '', $this);
				$rswrk = Conn()->execute($sqlWrk);
				if ($rswrk && !$rswrk->EOF) { // Lookup values found
					$arwrk = array();
					$arwrk[1] = $rswrk->fields('df');
					$arwrk[2] = $rswrk->fields('df2');
					$arwrk[3] = $rswrk->fields('df3');
					$this->ClientGroupID->ViewValue = $this->ClientGroupID->displayValue($arwrk);
					$rswrk->Close();
				} else {
					$this->ClientGroupID->ViewValue = $this->ClientGroupID->CurrentValue;
				}
			}
		} else {
			$this->ClientGroupID->ViewValue = NULL;
		}
		}
		$this->ClientGroupID->ViewCustomAttributes = "";

		// TitleID
		$curVal = strval($this->TitleID->CurrentValue);
		if ($curVal <> "") {
			$this->TitleID->ViewValue = $this->TitleID->lookupCacheOption($curVal);
			if ($this->TitleID->ViewValue === NULL) { // Lookup from database
				$filterWrk = "`TitleID`" . SearchString("=", $curVal, DATATYPE_NUMBER, "");
				$sqlWrk = $this->TitleID->Lookup->getSql(FALSE, $filterWrk, '', $this);
				$rswrk = Conn()->execute($sqlWrk);
				if ($rswrk && !$rswrk->EOF) { // Lookup values found
					$arwrk = array();
					$arwrk[1] = $rswrk->fields('df');
					$this->TitleID->ViewValue = $this->TitleID->displayValue($arwrk);
					$rswrk->Close();
				} else {
					$this->TitleID->ViewValue = $this->TitleID->CurrentValue;
				}
			}
		} else {
			$this->TitleID->ViewValue = NULL;
		}
		$this->TitleID->ViewCustomAttributes = "";

		// FirstName
		$this->FirstName->ViewValue = $this->FirstName->CurrentValue;
		$this->FirstName->ViewCustomAttributes = "";

		// MiddleName
		$this->MiddleName->ViewValue = $this->MiddleName->CurrentValue;
		$this->MiddleName->ViewCustomAttributes = "";

		// LastName
		$this->LastName->ViewValue = $this->LastName->CurrentValue;
		$this->LastName->ViewCustomAttributes = "";

		// PartnersName
		$this->PartnersName->ViewValue = $this->PartnersName->CurrentValue;
		$this->PartnersName->ViewCustomAttributes = "";

		// CompanyName
		$this->CompanyName->ViewValue = $this->CompanyName->CurrentValue;
		$this->CompanyName->ViewCustomAttributes = "";

		// ContactPerson
		$this->ContactPerson->ViewValue = $this->ContactPerson->CurrentValue;
		$this->ContactPerson->ViewCustomAttributes = "";

		// WorkNature
		$this->WorkNature->ViewValue = $this->WorkNature->CurrentValue;
		$this->WorkNature->ViewCustomAttributes = "";

		// JobTitle
		$this->JobTitle->ViewValue = $this->JobTitle->CurrentValue;
		$this->JobTitle->ViewCustomAttributes = "";

		// Photo
		if (!EmptyValue($this->Photo->Upload->DbValue)) {
			$this->Photo->ImageAlt = $this->Photo->alt();
			$this->Photo->ViewValue = $this->Photo->Upload->DbValue;
		} else {
			$this->Photo->ViewValue = "";
		}
		$this->Photo->ViewCustomAttributes = "";

		// BirthDate
		$this->BirthDate->ViewValue = $this->BirthDate->CurrentValue;
		$this->BirthDate->ViewValue = FormatDateTime($this->BirthDate->ViewValue, 0);
		$this->BirthDate->ViewCustomAttributes = "";

		// Title
		$this->Title->ViewValue = $this->Title->CurrentValue;
		$this->Title->ViewCustomAttributes = "";

		// TitleEn
		$this->TitleEn->ViewValue = $this->TitleEn->CurrentValue;
		$this->TitleEn->ViewCustomAttributes = "";

		// FirstNameEn
		$this->FirstNameEn->ViewValue = $this->FirstNameEn->CurrentValue;
		$this->FirstNameEn->ViewCustomAttributes = "";

		// MiddleNameEn
		$this->MiddleNameEn->ViewValue = $this->MiddleNameEn->CurrentValue;
		$this->MiddleNameEn->ViewCustomAttributes = "";

		// LastNameEn
		$this->LastNameEn->ViewValue = $this->LastNameEn->CurrentValue;
		$this->LastNameEn->ViewCustomAttributes = "";

		// PartnersNameEn
		$this->PartnersNameEn->ViewValue = $this->PartnersNameEn->CurrentValue;
		$this->PartnersNameEn->ViewCustomAttributes = "";

		// CompanyNameEn
		$this->CompanyNameEn->ViewValue = $this->CompanyNameEn->CurrentValue;
		$this->CompanyNameEn->ViewCustomAttributes = "";

		// AddressID
		$this->AddressID->ViewValue = $this->AddressID->CurrentValue;
		$this->AddressID->ViewValue = FormatNumber($this->AddressID->ViewValue, 0, -2, -2, -2);
		$this->AddressID->ViewCustomAttributes = "";

		// ContactID
		$this->ContactID->ViewValue = $this->ContactID->CurrentValue;
		$this->ContactID->ViewValue = FormatNumber($this->ContactID->ViewValue, 0, -2, -2, -2);
		$this->ContactID->ViewCustomAttributes = "";

		// Gender
		if (strval($this->Gender->CurrentValue) <> "") {
			$this->Gender->ViewValue = $this->Gender->optionCaption($this->Gender->CurrentValue);
		} else {
			$this->Gender->ViewValue = NULL;
		}
		$this->Gender->ViewCustomAttributes = "";

		// Notes
		$this->Notes->ViewValue = $this->Notes->CurrentValue;
		$this->Notes->ViewCustomAttributes = "";

		// Activated
		if (ConvertToBool($this->Activated->CurrentValue)) {
			$this->Activated->ViewValue = $this->Activated->tagCaption(1) <> "" ? $this->Activated->tagCaption(1) : "Y";
		} else {
			$this->Activated->ViewValue = $this->Activated->tagCaption(2) <> "" ? $this->Activated->tagCaption(2) : "N";
		}
		$this->Activated->ViewCustomAttributes = "";

		// Profile
		$this->Profile->ViewValue = $this->Profile->CurrentValue;
		$this->Profile->ViewCustomAttributes = "";

		// UserID
		$this->_UserID->ViewValue = $this->_UserID->CurrentValue;
		$this->_UserID->ViewValue = FormatNumber($this->_UserID->ViewValue, 0, -2, -2, -2);
		$this->_UserID->ViewCustomAttributes = "";

		// CreatedBy
		$this->CreatedBy->ViewValue = $this->CreatedBy->CurrentValue;
		$this->CreatedBy->ViewCustomAttributes = "";

		// CreatedDate
		$this->CreatedDate->ViewValue = $this->CreatedDate->CurrentValue;
		$this->CreatedDate->ViewValue = FormatDateTime($this->CreatedDate->ViewValue, 0);
		$this->CreatedDate->ViewCustomAttributes = "";

		// UpdatedBy
		$this->UpdatedBy->ViewValue = $this->UpdatedBy->CurrentValue;
		$this->UpdatedBy->ViewCustomAttributes = "";

		// UpdatedDate
		$this->UpdatedDate->ViewValue = $this->UpdatedDate->CurrentValue;
		$this->UpdatedDate->ViewValue = FormatDateTime($this->UpdatedDate->ViewValue, 0);
		$this->UpdatedDate->ViewCustomAttributes = "";

		// FileNumber
		$this->FileNumber->ViewValue = $this->FileNumber->CurrentValue;
		$this->FileNumber->ViewCustomAttributes = "";

		// NotesConv
		$this->NotesConv->ViewValue = $this->NotesConv->CurrentValue;
		$this->NotesConv->ViewCustomAttributes = "";

		// ClientID
		$this->ClientID->LinkCustomAttributes = "";
		$this->ClientID->HrefValue = "";
		$this->ClientID->TooltipValue = "";

		// ClientTypeID
		$this->ClientTypeID->LinkCustomAttributes = "";
		$this->ClientTypeID->HrefValue = "";
		$this->ClientTypeID->TooltipValue = "";

		// ClientGroupID
		$this->ClientGroupID->LinkCustomAttributes = "";
		$this->ClientGroupID->HrefValue = "";
		$this->ClientGroupID->TooltipValue = "";

		// TitleID
		$this->TitleID->LinkCustomAttributes = "";
		$this->TitleID->HrefValue = "";
		$this->TitleID->TooltipValue = "";

		// FirstName
		$this->FirstName->LinkCustomAttributes = "";
		$this->FirstName->HrefValue = "";
		$this->FirstName->TooltipValue = "";

		// MiddleName
		$this->MiddleName->LinkCustomAttributes = "";
		$this->MiddleName->HrefValue = "";
		$this->MiddleName->TooltipValue = "";

		// LastName
		$this->LastName->LinkCustomAttributes = "";
		$this->LastName->HrefValue = "";
		$this->LastName->TooltipValue = "";

		// PartnersName
		$this->PartnersName->LinkCustomAttributes = "";
		$this->PartnersName->HrefValue = "";
		$this->PartnersName->TooltipValue = "";

		// CompanyName
		$this->CompanyName->LinkCustomAttributes = "";
		$this->CompanyName->HrefValue = "";
		$this->CompanyName->TooltipValue = "";

		// ContactPerson
		$this->ContactPerson->LinkCustomAttributes = "";
		$this->ContactPerson->HrefValue = "";
		$this->ContactPerson->TooltipValue = "";

		// WorkNature
		$this->WorkNature->LinkCustomAttributes = "";
		$this->WorkNature->HrefValue = "";
		$this->WorkNature->TooltipValue = "";

		// JobTitle
		$this->JobTitle->LinkCustomAttributes = "";
		$this->JobTitle->HrefValue = "";
		$this->JobTitle->TooltipValue = "";

		// Photo
		$this->Photo->LinkCustomAttributes = "";
		if (!EmptyValue($this->Photo->Upload->DbValue)) {
			$this->Photo->HrefValue = GetFileUploadUrl($this->Photo, $this->Photo->Upload->DbValue); // Add prefix/suffix
			$this->Photo->LinkAttrs["target"] = ""; // Add target
			if ($this->isExport()) $this->Photo->HrefValue = FullUrl($this->Photo->HrefValue, "href");
		} else {
			$this->Photo->HrefValue = "";
		}
		$this->Photo->ExportHrefValue = $this->Photo->UploadPath . $this->Photo->Upload->DbValue;
		$this->Photo->TooltipValue = "";
		if ($this->Photo->UseColorbox) {
			if (EmptyValue($this->Photo->TooltipValue))
				$this->Photo->LinkAttrs["title"] = $Language->phrase("ViewImageGallery");
			$this->Photo->LinkAttrs["data-rel"] = "clients_x_Photo";
			AppendClass($this->Photo->LinkAttrs["class"], "ew-lightbox");
		}

		// BirthDate
		$this->BirthDate->LinkCustomAttributes = "";
		$this->BirthDate->HrefValue = "";
		$this->BirthDate->TooltipValue = "";

		// Title
		$this->Title->LinkCustomAttributes = "";
		$this->Title->HrefValue = "";
		$this->Title->TooltipValue = "";

		// TitleEn
		$this->TitleEn->LinkCustomAttributes = "";
		$this->TitleEn->HrefValue = "";
		$this->TitleEn->TooltipValue = "";

		// FirstNameEn
		$this->FirstNameEn->LinkCustomAttributes = "";
		$this->FirstNameEn->HrefValue = "";
		$this->FirstNameEn->TooltipValue = "";

		// MiddleNameEn
		$this->MiddleNameEn->LinkCustomAttributes = "";
		$this->MiddleNameEn->HrefValue = "";
		$this->MiddleNameEn->TooltipValue = "";

		// LastNameEn
		$this->LastNameEn->LinkCustomAttributes = "";
		$this->LastNameEn->HrefValue = "";
		$this->LastNameEn->TooltipValue = "";

		// PartnersNameEn
		$this->PartnersNameEn->LinkCustomAttributes = "";
		$this->PartnersNameEn->HrefValue = "";
		$this->PartnersNameEn->TooltipValue = "";

		// CompanyNameEn
		$this->CompanyNameEn->LinkCustomAttributes = "";
		$this->CompanyNameEn->HrefValue = "";
		$this->CompanyNameEn->TooltipValue = "";

		// AddressID
		$this->AddressID->LinkCustomAttributes = "";
		$this->AddressID->HrefValue = "";
		$this->AddressID->TooltipValue = "";

		// ContactID
		$this->ContactID->LinkCustomAttributes = "";
		$this->ContactID->HrefValue = "";
		$this->ContactID->TooltipValue = "";

		// Gender
		$this->Gender->LinkCustomAttributes = "";
		$this->Gender->HrefValue = "";
		$this->Gender->TooltipValue = "";

		// Notes
		$this->Notes->LinkCustomAttributes = "";
		$this->Notes->HrefValue = "";
		$this->Notes->TooltipValue = "";

		// Activated
		$this->Activated->LinkCustomAttributes = "";
		$this->Activated->HrefValue = "";
		$this->Activated->TooltipValue = "";

		// Profile
		$this->Profile->LinkCustomAttributes = "";
		$this->Profile->HrefValue = "";
		$this->Profile->TooltipValue = "";

		// UserID
		$this->_UserID->LinkCustomAttributes = "";
		$this->_UserID->HrefValue = "";
		$this->_UserID->TooltipValue = "";

		// CreatedBy
		$this->CreatedBy->LinkCustomAttributes = "";
		$this->CreatedBy->HrefValue = "";
		$this->CreatedBy->TooltipValue = "";

		// CreatedDate
		$this->CreatedDate->LinkCustomAttributes = "";
		$this->CreatedDate->HrefValue = "";
		$this->CreatedDate->TooltipValue = "";

		// UpdatedBy
		$this->UpdatedBy->LinkCustomAttributes = "";
		$this->UpdatedBy->HrefValue = "";
		$this->UpdatedBy->TooltipValue = "";

		// UpdatedDate
		$this->UpdatedDate->LinkCustomAttributes = "";
		$this->UpdatedDate->HrefValue = "";
		$this->UpdatedDate->TooltipValue = "";

		// FileNumber
		$this->FileNumber->LinkCustomAttributes = "";
		$this->FileNumber->HrefValue = "";
		$this->FileNumber->TooltipValue = "";

		// NotesConv
		$this->NotesConv->LinkCustomAttributes = "";
		$this->NotesConv->HrefValue = "";
		$this->NotesConv->TooltipValue = "";

		// Call Row Rendered event
		$this->Row_Rendered();

		// Save data for Custom Template
		$this->Rows[] = $this->customTemplateFieldValues();
	}

	// Render edit row values
	public function renderEditRow()
	{
		global $Security, $CurrentLanguage, $Language;

		// Call Row Rendering event
		$this->Row_Rendering();

		// ClientID
		$this->ClientID->EditAttrs["class"] = "form-control";
		$this->ClientID->EditCustomAttributes = "";

		// ClientTypeID
		$this->ClientTypeID->EditAttrs["class"] = "form-control";
		$this->ClientTypeID->EditCustomAttributes = "";

		// ClientGroupID
		$this->ClientGroupID->EditAttrs["class"] = "form-control";
		$this->ClientGroupID->EditCustomAttributes = "";
		$this->ClientGroupID->EditValue = $this->ClientGroupID->CurrentValue;
		$this->ClientGroupID->PlaceHolder = RemoveHtml($this->ClientGroupID->caption());

		// TitleID
		$this->TitleID->EditAttrs["class"] = "form-control";
		$this->TitleID->EditCustomAttributes = "";

		// FirstName
		$this->FirstName->EditAttrs["class"] = "form-control";
		$this->FirstName->EditCustomAttributes = "";
		$this->FirstName->EditValue = $this->FirstName->CurrentValue;
		$this->FirstName->PlaceHolder = RemoveHtml($this->FirstName->caption());

		// MiddleName
		$this->MiddleName->EditAttrs["class"] = "form-control";
		$this->MiddleName->EditCustomAttributes = "";
		$this->MiddleName->EditValue = $this->MiddleName->CurrentValue;
		$this->MiddleName->PlaceHolder = RemoveHtml($this->MiddleName->caption());

		// LastName
		$this->LastName->EditAttrs["class"] = "form-control";
		$this->LastName->EditCustomAttributes = "";
		$this->LastName->EditValue = $this->LastName->CurrentValue;
		$this->LastName->PlaceHolder = RemoveHtml($this->LastName->caption());

		// PartnersName
		$this->PartnersName->EditAttrs["class"] = "form-control";
		$this->PartnersName->EditCustomAttributes = "";
		$this->PartnersName->EditValue = $this->PartnersName->CurrentValue;
		$this->PartnersName->PlaceHolder = RemoveHtml($this->PartnersName->caption());

		// CompanyName
		$this->CompanyName->EditAttrs["class"] = "form-control";
		$this->CompanyName->EditCustomAttributes = "";
		$this->CompanyName->EditValue = $this->CompanyName->CurrentValue;
		$this->CompanyName->PlaceHolder = RemoveHtml($this->CompanyName->caption());

		// ContactPerson
		$this->ContactPerson->EditAttrs["class"] = "form-control";
		$this->ContactPerson->EditCustomAttributes = "";
		$this->ContactPerson->EditValue = $this->ContactPerson->CurrentValue;
		$this->ContactPerson->PlaceHolder = RemoveHtml($this->ContactPerson->caption());

		// WorkNature
		$this->WorkNature->EditAttrs["class"] = "form-control";
		$this->WorkNature->EditCustomAttributes = "";
		$this->WorkNature->EditValue = $this->WorkNature->CurrentValue;
		$this->WorkNature->PlaceHolder = RemoveHtml($this->WorkNature->caption());

		// JobTitle
		$this->JobTitle->EditAttrs["class"] = "form-control";
		$this->JobTitle->EditCustomAttributes = "";
		$this->JobTitle->EditValue = $this->JobTitle->CurrentValue;
		$this->JobTitle->PlaceHolder = RemoveHtml($this->JobTitle->caption());

		// Photo
		$this->Photo->EditAttrs["class"] = "form-control";
		$this->Photo->EditCustomAttributes = "";
		if (!EmptyValue($this->Photo->Upload->DbValue)) {
			$this->Photo->ImageAlt = $this->Photo->alt();
			$this->Photo->EditValue = $this->Photo->Upload->DbValue;
		} else {
			$this->Photo->EditValue = "";
		}
		if (!EmptyValue($this->Photo->CurrentValue))
				$this->Photo->Upload->FileName = $this->Photo->CurrentValue;

		// BirthDate
		$this->BirthDate->EditAttrs["class"] = "form-control";
		$this->BirthDate->EditCustomAttributes = "";
		$this->BirthDate->EditValue = FormatDateTime($this->BirthDate->CurrentValue, 8);
		$this->BirthDate->PlaceHolder = RemoveHtml($this->BirthDate->caption());

		// Title
		$this->Title->EditAttrs["class"] = "form-control";
		$this->Title->EditCustomAttributes = "";
		$this->Title->EditValue = $this->Title->CurrentValue;
		$this->Title->PlaceHolder = RemoveHtml($this->Title->caption());

		// TitleEn
		$this->TitleEn->EditAttrs["class"] = "form-control";
		$this->TitleEn->EditCustomAttributes = "";
		$this->TitleEn->EditValue = $this->TitleEn->CurrentValue;
		$this->TitleEn->PlaceHolder = RemoveHtml($this->TitleEn->caption());

		// FirstNameEn
		$this->FirstNameEn->EditAttrs["class"] = "form-control";
		$this->FirstNameEn->EditCustomAttributes = "";
		$this->FirstNameEn->EditValue = $this->FirstNameEn->CurrentValue;
		$this->FirstNameEn->PlaceHolder = RemoveHtml($this->FirstNameEn->caption());

		// MiddleNameEn
		$this->MiddleNameEn->EditAttrs["class"] = "form-control";
		$this->MiddleNameEn->EditCustomAttributes = "";
		$this->MiddleNameEn->EditValue = $this->MiddleNameEn->CurrentValue;
		$this->MiddleNameEn->PlaceHolder = RemoveHtml($this->MiddleNameEn->caption());

		// LastNameEn
		$this->LastNameEn->EditAttrs["class"] = "form-control";
		$this->LastNameEn->EditCustomAttributes = "";
		$this->LastNameEn->EditValue = $this->LastNameEn->CurrentValue;
		$this->LastNameEn->PlaceHolder = RemoveHtml($this->LastNameEn->caption());

		// PartnersNameEn
		$this->PartnersNameEn->EditAttrs["class"] = "form-control";
		$this->PartnersNameEn->EditCustomAttributes = "";
		$this->PartnersNameEn->EditValue = $this->PartnersNameEn->CurrentValue;
		$this->PartnersNameEn->PlaceHolder = RemoveHtml($this->PartnersNameEn->caption());

		// CompanyNameEn
		$this->CompanyNameEn->EditAttrs["class"] = "form-control";
		$this->CompanyNameEn->EditCustomAttributes = "";
		$this->CompanyNameEn->EditValue = $this->CompanyNameEn->CurrentValue;
		$this->CompanyNameEn->PlaceHolder = RemoveHtml($this->CompanyNameEn->caption());

		// AddressID
		$this->AddressID->EditAttrs["class"] = "form-control";
		$this->AddressID->EditCustomAttributes = "";
		$this->AddressID->EditValue = $this->AddressID->CurrentValue;
		$this->AddressID->PlaceHolder = RemoveHtml($this->AddressID->caption());

		// ContactID
		$this->ContactID->EditAttrs["class"] = "form-control";
		$this->ContactID->EditCustomAttributes = "";
		$this->ContactID->EditValue = $this->ContactID->CurrentValue;
		$this->ContactID->PlaceHolder = RemoveHtml($this->ContactID->caption());

		// Gender
		$this->Gender->EditCustomAttributes = "";
		$this->Gender->EditValue = $this->Gender->options(FALSE);

		// Notes
		$this->Notes->EditAttrs["class"] = "form-control";
		$this->Notes->EditCustomAttributes = "";
		$this->Notes->EditValue = $this->Notes->CurrentValue;
		$this->Notes->PlaceHolder = RemoveHtml($this->Notes->caption());

		// Activated
		$this->Activated->EditCustomAttributes = "";
		$this->Activated->EditValue = $this->Activated->options(FALSE);

		// Profile
		$this->Profile->EditAttrs["class"] = "form-control";
		$this->Profile->EditCustomAttributes = "";
		$this->Profile->EditValue = $this->Profile->CurrentValue;
		$this->Profile->PlaceHolder = RemoveHtml($this->Profile->caption());

		// UserID
		$this->_UserID->EditAttrs["class"] = "form-control";
		$this->_UserID->EditCustomAttributes = "";
		$this->_UserID->EditValue = $this->_UserID->CurrentValue;
		$this->_UserID->PlaceHolder = RemoveHtml($this->_UserID->caption());

		// CreatedBy
		$this->CreatedBy->EditAttrs["class"] = "form-control";
		$this->CreatedBy->EditCustomAttributes = "";
		$this->CreatedBy->EditValue = $this->CreatedBy->CurrentValue;
		$this->CreatedBy->PlaceHolder = RemoveHtml($this->CreatedBy->caption());

		// CreatedDate
		$this->CreatedDate->EditAttrs["class"] = "form-control";
		$this->CreatedDate->EditCustomAttributes = "";
		$this->CreatedDate->EditValue = FormatDateTime($this->CreatedDate->CurrentValue, 8);
		$this->CreatedDate->PlaceHolder = RemoveHtml($this->CreatedDate->caption());

		// UpdatedBy
		$this->UpdatedBy->EditAttrs["class"] = "form-control";
		$this->UpdatedBy->EditCustomAttributes = "";
		$this->UpdatedBy->EditValue = $this->UpdatedBy->CurrentValue;
		$this->UpdatedBy->PlaceHolder = RemoveHtml($this->UpdatedBy->caption());

		// UpdatedDate
		$this->UpdatedDate->EditAttrs["class"] = "form-control";
		$this->UpdatedDate->EditCustomAttributes = "";
		$this->UpdatedDate->EditValue = FormatDateTime($this->UpdatedDate->CurrentValue, 8);
		$this->UpdatedDate->PlaceHolder = RemoveHtml($this->UpdatedDate->caption());

		// FileNumber
		$this->FileNumber->EditAttrs["class"] = "form-control";
		$this->FileNumber->EditCustomAttributes = "";
		$this->FileNumber->EditValue = $this->FileNumber->CurrentValue;
		$this->FileNumber->PlaceHolder = RemoveHtml($this->FileNumber->caption());

		// NotesConv
		$this->NotesConv->EditAttrs["class"] = "form-control";
		$this->NotesConv->EditCustomAttributes = "";
		$this->NotesConv->EditValue = $this->NotesConv->CurrentValue;
		$this->NotesConv->PlaceHolder = RemoveHtml($this->NotesConv->caption());

		// Call Row Rendered event
		$this->Row_Rendered();
	}

	// Aggregate list row values
	public function aggregateListRowValues()
	{
	}

	// Aggregate list row (for rendering)
	public function aggregateListRow()
	{

		// Call Row Rendered event
		$this->Row_Rendered();
	}

	// Export data in HTML/CSV/Word/Excel/Email/PDF format
	public function exportDocument($doc, $recordset, $startRec = 1, $stopRec = 1, $exportPageType = "")
	{
		if (!$recordset || !$doc)
			return;
		if (!$doc->ExportCustom) {

			// Write header
			$doc->exportTableHeader();
			if ($doc->Horizontal) { // Horizontal format, write header
				$doc->beginExportRow();
				if ($exportPageType == "view") {
					$doc->exportCaption($this->ClientID);
					$doc->exportCaption($this->ClientTypeID);
					$doc->exportCaption($this->ClientGroupID);
					$doc->exportCaption($this->TitleID);
					$doc->exportCaption($this->FirstName);
					$doc->exportCaption($this->MiddleName);
					$doc->exportCaption($this->LastName);
					$doc->exportCaption($this->PartnersName);
					$doc->exportCaption($this->CompanyName);
					$doc->exportCaption($this->ContactPerson);
					$doc->exportCaption($this->WorkNature);
					$doc->exportCaption($this->JobTitle);
					$doc->exportCaption($this->Photo);
					$doc->exportCaption($this->BirthDate);
					$doc->exportCaption($this->Gender);
					$doc->exportCaption($this->Notes);
				} else {
					$doc->exportCaption($this->ClientID);
					$doc->exportCaption($this->ClientTypeID);
					$doc->exportCaption($this->ClientGroupID);
					$doc->exportCaption($this->TitleID);
					$doc->exportCaption($this->FirstName);
					$doc->exportCaption($this->MiddleName);
					$doc->exportCaption($this->LastName);
					$doc->exportCaption($this->PartnersName);
					$doc->exportCaption($this->CompanyName);
					$doc->exportCaption($this->ContactPerson);
					$doc->exportCaption($this->WorkNature);
					$doc->exportCaption($this->JobTitle);
					$doc->exportCaption($this->Photo);
					$doc->exportCaption($this->BirthDate);
					$doc->exportCaption($this->Gender);
					$doc->exportCaption($this->Notes);
				}
				$doc->endExportRow();
			}
		}

		// Move to first record
		$recCnt = $startRec - 1;
		if (!$recordset->EOF) {
			$recordset->moveFirst();
			if ($startRec > 1)
				$recordset->move($startRec - 1);
		}
		while (!$recordset->EOF && $recCnt < $stopRec) {
			$recCnt++;
			if ($recCnt >= $startRec) {
				$rowCnt = $recCnt - $startRec + 1;

				// Page break
				if ($this->ExportPageBreakCount > 0) {
					if ($rowCnt > 1 && ($rowCnt - 1) % $this->ExportPageBreakCount == 0)
						$doc->exportPageBreak();
				}
				$this->loadListRowValues($recordset);

				// Render row
				$this->RowType = ROWTYPE_VIEW; // Render view
				$this->resetAttributes();
				$this->renderListRow();
				if (!$doc->ExportCustom) {
					$doc->beginExportRow($rowCnt); // Allow CSS styles if enabled
					if ($exportPageType == "view") {
						$doc->exportField($this->ClientID);
						$doc->exportField($this->ClientTypeID);
						$doc->exportField($this->ClientGroupID);
						$doc->exportField($this->TitleID);
						$doc->exportField($this->FirstName);
						$doc->exportField($this->MiddleName);
						$doc->exportField($this->LastName);
						$doc->exportField($this->PartnersName);
						$doc->exportField($this->CompanyName);
						$doc->exportField($this->ContactPerson);
						$doc->exportField($this->WorkNature);
						$doc->exportField($this->JobTitle);
						$doc->exportField($this->Photo);
						$doc->exportField($this->BirthDate);
						$doc->exportField($this->Gender);
						$doc->exportField($this->Notes);
					} else {
						$doc->exportField($this->ClientID);
						$doc->exportField($this->ClientTypeID);
						$doc->exportField($this->ClientGroupID);
						$doc->exportField($this->TitleID);
						$doc->exportField($this->FirstName);
						$doc->exportField($this->MiddleName);
						$doc->exportField($this->LastName);
						$doc->exportField($this->PartnersName);
						$doc->exportField($this->CompanyName);
						$doc->exportField($this->ContactPerson);
						$doc->exportField($this->WorkNature);
						$doc->exportField($this->JobTitle);
						$doc->exportField($this->Photo);
						$doc->exportField($this->BirthDate);
						$doc->exportField($this->Gender);
						$doc->exportField($this->Notes);
					}
					$doc->endExportRow($rowCnt);
				}
			}

			// Call Row Export server event
			if ($doc->ExportCustom)
				$this->Row_Export($recordset->fields);
			$recordset->moveNext();
		}
		if (!$doc->ExportCustom) {
			$doc->exportTableFooter();
		}
	}

	// Lookup data from table
	public function lookup()
	{
		global $Language, $LANGUAGE_FOLDER, $PROJECT_ID;
		if (!isset($Language))
			$Language = new Language($LANGUAGE_FOLDER, Post("language", ""));
		global $Security, $RequestSecurity;

		// Check token first
		$func = PROJECT_NAMESPACE . "CheckToken";
		$validRequest = FALSE;
		if (is_callable($func) && Post(TOKEN_NAME) !== NULL) {
			$validRequest = $func(Post(TOKEN_NAME), SessionTimeoutTime());
			if ($validRequest) {
				if (!isset($Security)) {
					if (session_status() !== PHP_SESSION_ACTIVE)
						session_start(); // Init session data
					$Security = new AdvancedSecurity();
					if ($Security->isLoggedIn()) $Security->TablePermission_Loading();
					$Security->loadCurrentUserLevel($PROJECT_ID . $this->TableName);
					if ($Security->isLoggedIn()) $Security->TablePermission_Loaded();
					$validRequest = $Security->canList(); // List permission
					if ($validRequest) {
						$Security->UserID_Loading();
						$Security->loadUserID();
						$Security->UserID_Loaded();
					}
				}
			}
		} else {

			// User profile
			$UserProfile = new UserProfile();

			// Security
			$Security = new AdvancedSecurity();
			if (is_array($RequestSecurity)) // Login user for API request
				$Security->loginUser(@$RequestSecurity["username"], @$RequestSecurity["userid"], @$RequestSecurity["parentuserid"], @$RequestSecurity["userlevelid"]);
			$Security->TablePermission_Loading();
			$Security->loadCurrentUserLevel(CurrentProjectID() . $this->TableName);
			$Security->TablePermission_Loaded();
			$validRequest = $Security->canList(); // List permission
		}

		// Reject invalid request
		if (!$validRequest)
			return FALSE;

		// Load lookup parameters
		$distinct = ConvertToBool(Post("distinct"));
		$linkField = Post("linkField");
		$displayFields = Post("displayFields");
		$parentFields = Post("parentFields");
		if (!is_array($parentFields))
			$parentFields = [];
		$childFields = Post("childFields");
		if (!is_array($childFields))
			$childFields = [];
		$filterFields = Post("filterFields");
		if (!is_array($filterFields))
			$filterFields = [];
		$filterFieldVars = Post("filterFieldVars");
		if (!is_array($filterFieldVars))
			$filterFieldVars = [];
		$filterOperators = Post("filterOperators");
		if (!is_array($filterOperators))
			$filterOperators = [];
		$autoFillSourceFields = Post("autoFillSourceFields");
		if (!is_array($autoFillSourceFields))
			$autoFillSourceFields = [];
		$formatAutoFill = FALSE;
		$lookupType = Post("ajax", "unknown");
		$pageSize = -1;
		$offset = -1;
		$searchValue = "";
		if (SameText($lookupType, "modal")) {
			$searchValue = Post("sv", "");
			$pageSize = Post("recperpage", 10);
			$offset = Post("start", 0);
		} elseif (SameText($lookupType, "autosuggest")) {
			$searchValue = Get("q", "");
			$pageSize = Param("n", -1);
			$pageSize = is_numeric($pageSize) ? (int)$pageSize : -1;
			if ($pageSize <= 0)
				$pageSize = AUTO_SUGGEST_MAX_ENTRIES;
			$start = Param("start", -1);
			$start = is_numeric($start) ? (int)$start : -1;
			$page = Param("page", -1);
			$page = is_numeric($page) ? (int)$page : -1;
			$offset = $start >= 0 ? $start : ($page > 0 && $pageSize > 0 ? ($page - 1) * $pageSize : 0);
		}
		$userSelect = Decrypt(Post("s", ""));
		$userFilter = Decrypt(Post("f", ""));
		$userOrderBy = Decrypt(Post("o", ""));
		$keys = Post("keys");

		// Selected records from modal, skip parent/filter fields and show all records
		if ($keys !== NULL) {
			$parentFields = [];
			$filterFields = [];
			$filterFieldVars = [];
			$offset = 0;
			$pageSize = 0;
		}

		// Create lookup object and output JSON
		$lookup = new Lookup($linkField, $this->TableVar, $distinct, $linkField, $displayFields, $parentFields, $childFields, $filterFields, $filterFieldVars, $autoFillSourceFields);
		foreach ($filterFields as $i => $filterField) { // Set up filter operators
			if (@$filterOperators[$i] <> "")
				$lookup->setFilterOperator($filterField, $filterOperators[$i]);
		}
		$lookup->LookupType = $lookupType; // Lookup type
		if ($keys !== NULL) { // Selected records from modal
			if (is_array($keys))
				$keys = implode(LOOKUP_FILTER_VALUE_SEPARATOR, $keys);
			$lookup->FilterValues[] = $keys; // Lookup values
		} else { // Lookup values
			$lookup->FilterValues[] = Post("v0", Post("lookupValue", ""));
		}
		$cnt = is_array($filterFields) ? count($filterFields) : 0;
		for ($i = 1; $i <= $cnt; $i++)
			$lookup->FilterValues[] = Post("v" . $i, "");
		$lookup->SearchValue = $searchValue;
		$lookup->PageSize = $pageSize;
		$lookup->Offset = $offset;
		if ($userSelect <> "")
			$lookup->UserSelect = $userSelect;
		if ($userFilter <> "")
			$lookup->UserFilter = $userFilter;
		if ($userOrderBy <> "")
			$lookup->UserOrderBy = $userOrderBy;
		$lookup->toJson();
	}

	// Get file data
	public function getFileData($fldparm, $key, $resize, $width = THUMBNAIL_DEFAULT_WIDTH, $height = THUMBNAIL_DEFAULT_HEIGHT)
	{
		global $COMPOSITE_KEY_SEPARATOR;

		// Set up field name / file name field / file type field
		$fldName = "";
		$fileNameFld = "";
		$fileTypeFld = "";
		if ($fldparm == 'Photo') {
			$fldName = "Photo";
			$fileNameFld = "Photo";
		} else {
			return FALSE; // Incorrect field
		}

		// Set up key values
		$ar = explode($COMPOSITE_KEY_SEPARATOR, $key);
		if (count($ar) == 1) {
			$this->ClientID->CurrentValue = $ar[0];
		} else {
			return FALSE; // Incorrect key
		}

		// Set up filter (WHERE Clause)
		$filter = $this->getRecordFilter();
		$this->CurrentFilter = $filter;
		$sql = $this->getCurrentSql();
		$conn = &$this->getConnection();
		$dbtype = GetConnectionType($this->Dbid);
		if (($rs = $conn->execute($sql)) && !$rs->EOF) {
			$val = $rs->fields($fldName);
			if (!EmptyValue($val)) {
				$fld = $this->fields[$fldName];

				// Binary data
				if ($fld->DataType == DATATYPE_BLOB) {
					if ($dbtype <> "MYSQL") {
						if (is_array($val) || is_object($val)) // Byte array
							$val = BytesToString($val);
					}
					if ($resize)
						ResizeBinary($val, $width, $height);

					// Write file type
					if ($fileTypeFld <> "" && !EmptyValue($rs->fields($fileTypeFld))) {
						AddHeader("Content-type", $rs->fields($fileTypeFld));
					} else {
						AddHeader("Content-type", ContentType($val));
					}

					// Write file name
					if ($fileNameFld <> "" && !EmptyValue($rs->fields($fileNameFld)))
						AddHeader("Content-Disposition", "attachment; filename=\"" . $rs->fields($fileNameFld) . "\"");

					// Write file data
					if (StartsString("PK", $val) && ContainsString($val, "[Content_Types].xml") &&
						ContainsString($val, "_rels") && ContainsString($val, "docProps")) { // Fix Office 2007 documents
						if (!EndsString("\0\0\0", $val)) // Not ends with 3 or 4 \0
							$val .= "\0\0\0\0";
					}

					// Clear any debug message
					if (ob_get_length())
						ob_end_clean();

					// Write binary data
					Write($val);

				// Upload to folder
				} else {
					if ($fld->UploadMultiple)
						$files = explode(MULTIPLE_UPLOAD_SEPARATOR, $val);
					else
						$files = [$val];
					$data = [];
					$ar = [];
					foreach ($files as $file) {
						if (!EmptyValue($file))
							$ar[$file] = FullUrl($fld->hrefPath() . $file);
					}
					$data[$fld->Param] = $ar;
					WriteJson($data);
				}
			}
			$rs->close();
			return TRUE;
		}
		return FALSE;
	}

	// Write Audit Trail start/end for grid update
	public function writeAuditTrailDummy($typ)
	{
		$table = 'clients';
		$usr = CurrentUserID();
		WriteAuditTrail("log", DbCurrentDateTime(), ScriptName(), $usr, $typ, $table, "", "", "", "");
	}

	// Write Audit Trail (add page)
	public function writeAuditTrailOnAdd(&$rs)
	{
		global $Language;
		if (!$this->AuditTrailOnAdd)
			return;
		$table = 'clients';

		// Get key value
		$key = "";
		if ($key <> "")
			$key .= $GLOBALS["COMPOSITE_KEY_SEPARATOR"];
		$key .= $rs['ClientID'];

		// Write Audit Trail
		$dt = DbCurrentDateTime();
		$id = ScriptName();
		$usr = CurrentUserID();
		foreach (array_keys($rs) as $fldname) {
			if (array_key_exists($fldname, $this->fields) && $this->fields[$fldname]->DataType <> DATATYPE_BLOB) { // Ignore BLOB fields
				if ($this->fields[$fldname]->HtmlTag == "PASSWORD") {
					$newvalue = $Language->phrase("PasswordMask"); // Password Field
				} elseif ($this->fields[$fldname]->DataType == DATATYPE_MEMO) {
					if (AUDIT_TRAIL_TO_DATABASE)
						$newvalue = $rs[$fldname];
					else
						$newvalue = "[MEMO]"; // Memo Field
				} elseif ($this->fields[$fldname]->DataType == DATATYPE_XML) {
					$newvalue = "[XML]"; // XML Field
				} else {
					$newvalue = $rs[$fldname];
				}
				WriteAuditTrail("log", $dt, $id, $usr, "A", $table, $fldname, $key, "", $newvalue);
			}
		}
	}

	// Write Audit Trail (edit page)
	public function writeAuditTrailOnEdit(&$rsold, &$rsnew)
	{
		global $Language;
		if (!$this->AuditTrailOnEdit)
			return;
		$table = 'clients';

		// Get key value
		$key = "";
		if ($key <> "")
			$key .= $GLOBALS["COMPOSITE_KEY_SEPARATOR"];
		$key .= $rsold['ClientID'];

		// Write Audit Trail
		$dt = DbCurrentDateTime();
		$id = ScriptName();
		$usr = CurrentUserID();
		foreach (array_keys($rsnew) as $fldname) {
			if (array_key_exists($fldname, $this->fields) && array_key_exists($fldname, $rsold) && $this->fields[$fldname]->DataType <> DATATYPE_BLOB) { // Ignore BLOB fields
				if ($this->fields[$fldname]->DataType == DATATYPE_DATE) { // DateTime field
					$modified = (FormatDateTime($rsold[$fldname], 0) <> FormatDateTime($rsnew[$fldname], 0));
				} else {
					$modified = !CompareValue($rsold[$fldname], $rsnew[$fldname]);
				}
				if ($modified) {
					if ($this->fields[$fldname]->HtmlTag == "PASSWORD") { // Password Field
						$oldvalue = $Language->phrase("PasswordMask");
						$newvalue = $Language->phrase("PasswordMask");
					} elseif ($this->fields[$fldname]->DataType == DATATYPE_MEMO) { // Memo field
						if (AUDIT_TRAIL_TO_DATABASE) {
							$oldvalue = $rsold[$fldname];
							$newvalue = $rsnew[$fldname];
						} else {
							$oldvalue = "[MEMO]";
							$newvalue = "[MEMO]";
						}
					} elseif ($this->fields[$fldname]->DataType == DATATYPE_XML) { // XML field
						$oldvalue = "[XML]";
						$newvalue = "[XML]";
					} else {
						$oldvalue = $rsold[$fldname];
						$newvalue = $rsnew[$fldname];
					}
					WriteAuditTrail("log", $dt, $id, $usr, "U", $table, $fldname, $key, $oldvalue, $newvalue);
				}
			}
		}
	}

	// Write Audit Trail (delete page)
	public function writeAuditTrailOnDelete(&$rs)
	{
		global $Language;
		if (!$this->AuditTrailOnDelete)
			return;
		$table = 'clients';

		// Get key value
		$key = "";
		if ($key <> "")
			$key .= $GLOBALS["COMPOSITE_KEY_SEPARATOR"];
		$key .= $rs['ClientID'];

		// Write Audit Trail
		$dt = DbCurrentDateTime();
		$id = ScriptName();
		$curUser = CurrentUserID();
		foreach (array_keys($rs) as $fldname) {
			if (array_key_exists($fldname, $this->fields) && $this->fields[$fldname]->DataType <> DATATYPE_BLOB) { // Ignore BLOB fields
				if ($this->fields[$fldname]->HtmlTag == "PASSWORD") {
					$oldvalue = $Language->phrase("PasswordMask"); // Password Field
				} elseif ($this->fields[$fldname]->DataType == DATATYPE_MEMO) {
					if (AUDIT_TRAIL_TO_DATABASE)
						$oldvalue = $rs[$fldname];
					else
						$oldvalue = "[MEMO]"; // Memo field
				} elseif ($this->fields[$fldname]->DataType == DATATYPE_XML) {
					$oldvalue = "[XML]"; // XML field
				} else {
					$oldvalue = $rs[$fldname];
				}
				WriteAuditTrail("log", $dt, $id, $curUser, "D", $table, $fldname, $key, $oldvalue, "");
			}
		}
	}

	// Table level events
	// Recordset Selecting event
	function Recordset_Selecting(&$filter) {

		// Enter your code here
	}

	// Recordset Selected event
	function Recordset_Selected(&$rs) {

		//echo "Recordset Selected";
	}

	// Recordset Search Validated event
	function Recordset_SearchValidated() {

		// Example:
		//$this->MyField1->AdvancedSearch->SearchValue = "your search criteria"; // Search value

	}

	// Recordset Searching event
	function Recordset_Searching(&$filter) {

		// Enter your code here
	}

	// Row_Selecting event
	function Row_Selecting(&$filter) {

		// Enter your code here
	}

	// Row Selected event
	function Row_Selected(&$rs) {

		//echo "Row Selected";
	}

	// Row Inserting event
	function Row_Inserting($rsold, &$rsnew) {

		// Enter your code here
		// To cancel, set return value to FALSE

		return TRUE;
	}

	// Row Inserted event
	function Row_Inserted($rsold, &$rsnew) {

		//echo "Row Inserted"
	}

	// Row Updating event
	function Row_Updating($rsold, &$rsnew) {

		// Enter your code here
		// To cancel, set return value to FALSE

		return TRUE;
	}

	// Row Updated event
	function Row_Updated($rsold, &$rsnew) {

		//echo "Row Updated";
	}

	// Row Update Conflict event
	function Row_UpdateConflict($rsold, &$rsnew) {

		// Enter your code here
		// To ignore conflict, set return value to FALSE

		return TRUE;
	}

	// Grid Inserting event
	function Grid_Inserting() {

		// Enter your code here
		// To reject grid insert, set return value to FALSE

		return TRUE;
	}

	// Grid Inserted event
	function Grid_Inserted($rsnew) {

		//echo "Grid Inserted";
	}

	// Grid Updating event
	function Grid_Updating($rsold) {

		// Enter your code here
		// To reject grid update, set return value to FALSE

		return TRUE;
	}

	// Grid Updated event
	function Grid_Updated($rsold, $rsnew) {

		//echo "Grid Updated";
	}

	// Row Deleting event
	function Row_Deleting(&$rs) {

		// Enter your code here
		// To cancel, set return value to False

		return TRUE;
	}

	// Row Deleted event
	function Row_Deleted(&$rs) {

		//echo "Row Deleted";
	}

	// Email Sending event
	function Email_Sending($email, &$args) {

		//var_dump($email); var_dump($args); exit();
		return TRUE;
	}

	// Lookup Selecting event
	function Lookup_Selecting($fld, &$filter) {

		//var_dump($fld->Name, $fld->Lookup, $filter); // Uncomment to view the filter
		// Enter your code here

	}

	// Row Rendering event
	function Row_Rendering() {

		// Enter your code here
	}

	// Row Rendered event
	function Row_Rendered() {

		// To view properties of field class, use:
		//var_dump($this-><FieldName>);

	}

	// User ID Filtering event
	function UserID_Filtering(&$filter) {

		// Enter your code here
	}
}
?>
