<?php
namespace PHPMaker2019\project_germanos;

/**
 * Page class
 */
class clients_edit extends clients
{

	// Page ID
	public $PageID = "edit";

	// Project ID
	public $ProjectID = "{8D47CED4-FEF0-4756-8F48-9FC38A15AA2A}";

	// Table name
	public $TableName = 'clients';

	// Page object name
	public $PageObjName = "clients_edit";

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

	// Page headings
	public $Heading = "";
	public $Subheading = "";
	public $PageHeader;
	public $PageFooter;

	// Token
	public $Token = "";
	public $TokenTimeout = 0;
	public $CheckToken = CHECK_TOKEN;

	// Messages
	private $_message = "";
	private $_failureMessage = "";
	private $_successMessage = "";
	private $_warningMessage = "";

	// Page heading
	public function pageHeading()
	{
		global $Language;
		if ($this->Heading <> "")
			return $this->Heading;
		if (method_exists($this, "tableCaption"))
			return $this->tableCaption();
		return "";
	}

	// Page subheading
	public function pageSubheading()
	{
		global $Language;
		if ($this->Subheading <> "")
			return $this->Subheading;
		if ($this->TableName)
			return $Language->phrase($this->PageID);
		return "";
	}

	// Page name
	public function pageName()
	{
		return CurrentPageName();
	}

	// Page URL
	public function pageUrl()
	{
		$url = CurrentPageName() . "?";
		if ($this->UseTokenInUrl)
			$url .= "t=" . $this->TableVar . "&"; // Add page token
		return $url;
	}

	// Get message
	public function getMessage()
	{
		return isset($_SESSION[SESSION_MESSAGE]) ? $_SESSION[SESSION_MESSAGE] : $this->_message;
	}

	// Set message
	public function setMessage($v)
	{
		AddMessage($this->_message, $v);
		$_SESSION[SESSION_MESSAGE] = $this->_message;
	}

	// Get failure message
	public function getFailureMessage()
	{
		return isset($_SESSION[SESSION_FAILURE_MESSAGE]) ? $_SESSION[SESSION_FAILURE_MESSAGE] : $this->_failureMessage;
	}

	// Set failure message
	public function setFailureMessage($v)
	{
		AddMessage($this->_failureMessage, $v);
		$_SESSION[SESSION_FAILURE_MESSAGE] = $this->_failureMessage;
	}

	// Get success message
	public function getSuccessMessage()
	{
		return isset($_SESSION[SESSION_SUCCESS_MESSAGE]) ? $_SESSION[SESSION_SUCCESS_MESSAGE] : $this->_successMessage;
	}

	// Set success message
	public function setSuccessMessage($v)
	{
		AddMessage($this->_successMessage, $v);
		$_SESSION[SESSION_SUCCESS_MESSAGE] = $this->_successMessage;
	}

	// Get warning message
	public function getWarningMessage()
	{
		return isset($_SESSION[SESSION_WARNING_MESSAGE]) ? $_SESSION[SESSION_WARNING_MESSAGE] : $this->_warningMessage;
	}

	// Set warning message
	public function setWarningMessage($v)
	{
		AddMessage($this->_warningMessage, $v);
		$_SESSION[SESSION_WARNING_MESSAGE] = $this->_warningMessage;
	}

	// Clear message
	public function clearMessage()
	{
		$this->_message = "";
		$_SESSION[SESSION_MESSAGE] = "";
	}

	// Clear failure message
	public function clearFailureMessage()
	{
		$this->_failureMessage = "";
		$_SESSION[SESSION_FAILURE_MESSAGE] = "";
	}

	// Clear success message
	public function clearSuccessMessage()
	{
		$this->_successMessage = "";
		$_SESSION[SESSION_SUCCESS_MESSAGE] = "";
	}

	// Clear warning message
	public function clearWarningMessage()
	{
		$this->_warningMessage = "";
		$_SESSION[SESSION_WARNING_MESSAGE] = "";
	}

	// Clear messages
	public function clearMessages()
	{
		$this->clearMessage();
		$this->clearFailureMessage();
		$this->clearSuccessMessage();
		$this->clearWarningMessage();
	}

	// Show message
	public function showMessage()
	{
		$hidden = FALSE;
		$html = "";

		// Message
		$message = $this->getMessage();
		if (method_exists($this, "Message_Showing"))
			$this->Message_Showing($message, "");
		if ($message <> "") { // Message in Session, display
			if (!$hidden)
				$message = '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>' . $message;
			$html .= '<div class="alert alert-info alert-dismissible ew-info"><i class="icon fa fa-info"></i>' . $message . '</div>';
			$_SESSION[SESSION_MESSAGE] = ""; // Clear message in Session
		}

		// Warning message
		$warningMessage = $this->getWarningMessage();
		if (method_exists($this, "Message_Showing"))
			$this->Message_Showing($warningMessage, "warning");
		if ($warningMessage <> "") { // Message in Session, display
			if (!$hidden)
				$warningMessage = '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>' . $warningMessage;
			$html .= '<div class="alert alert-warning alert-dismissible ew-warning"><i class="icon fa fa-warning"></i>' . $warningMessage . '</div>';
			$_SESSION[SESSION_WARNING_MESSAGE] = ""; // Clear message in Session
		}

		// Success message
		$successMessage = $this->getSuccessMessage();
		if (method_exists($this, "Message_Showing"))
			$this->Message_Showing($successMessage, "success");
		if ($successMessage <> "") { // Message in Session, display
			if (!$hidden)
				$successMessage = '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>' . $successMessage;
			$html .= '<div class="alert alert-success alert-dismissible ew-success"><i class="icon fa fa-check"></i>' . $successMessage . '</div>';
			$_SESSION[SESSION_SUCCESS_MESSAGE] = ""; // Clear message in Session
		}

		// Failure message
		$errorMessage = $this->getFailureMessage();
		if (method_exists($this, "Message_Showing"))
			$this->Message_Showing($errorMessage, "failure");
		if ($errorMessage <> "") { // Message in Session, display
			if (!$hidden)
				$errorMessage = '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>' . $errorMessage;
			$html .= '<div class="alert alert-danger alert-dismissible ew-error"><i class="icon fa fa-ban"></i>' . $errorMessage . '</div>';
			$_SESSION[SESSION_FAILURE_MESSAGE] = ""; // Clear message in Session
		}
		echo '<div class="ew-message-dialog' . (($hidden) ? ' d-none' : "") . '">' . $html . '</div>';
	}

	// Get message as array
	public function getMessages()
	{
		$ar = array();

		// Message
		$message = $this->getMessage();

		//if (method_exists($this, "Message_Showing"))
		//	$this->Message_Showing($message, "");

		if ($message <> "") { // Message in Session, display
			$ar["message"] = $message;
			$_SESSION[SESSION_MESSAGE] = ""; // Clear message in Session
		}

		// Warning message
		$warningMessage = $this->getWarningMessage();

		//if (method_exists($this, "Message_Showing"))
		//	$this->Message_Showing($warningMessage, "warning");

		if ($warningMessage <> "") { // Message in Session, display
			$ar["warningMessage"] = $warningMessage;
			$_SESSION[SESSION_WARNING_MESSAGE] = ""; // Clear message in Session
		}

		// Success message
		$successMessage = $this->getSuccessMessage();

		//if (method_exists($this, "Message_Showing"))
		//	$this->Message_Showing($successMessage, "success");

		if ($successMessage <> "") { // Message in Session, display
			$ar["successMessage"] = $successMessage;
			$_SESSION[SESSION_SUCCESS_MESSAGE] = ""; // Clear message in Session
		}

		// Failure message
		$failureMessage = $this->getFailureMessage();

		//if (method_exists($this, "Message_Showing"))
		//	$this->Message_Showing($failureMessage, "failure");

		if ($failureMessage <> "") { // Message in Session, display
			$ar["failureMessage"] = $failureMessage;
			$_SESSION[SESSION_FAILURE_MESSAGE] = ""; // Clear message in Session
		}
		return $ar;
	}

	// Show Page Header
	public function showPageHeader()
	{
		$header = $this->PageHeader;
		$this->Page_DataRendering($header);
		if ($header <> "") { // Header exists, display
			echo '<p id="ew-page-header">' . $header . '</p>';
		}
	}

	// Show Page Footer
	public function showPageFooter()
	{
		$footer = $this->PageFooter;
		$this->Page_DataRendered($footer);
		if ($footer <> "") { // Footer exists, display
			echo '<p id="ew-page-footer">' . $footer . '</p>';
		}
	}

	// Validate page request
	protected function isPageRequest()
	{
		global $CurrentForm;
		if ($this->UseTokenInUrl) {
			if ($CurrentForm)
				return ($this->TableVar == $CurrentForm->getValue("t"));
			if (Get("t") !== NULL)
				return ($this->TableVar == Get("t"));
		}
		return TRUE;
	}

	// Valid Post
	protected function validPost()
	{
		if (!$this->CheckToken || !IsPost() || IsApi())
			return TRUE;
		if (Post(TOKEN_NAME) === NULL)
			return FALSE;
		$fn = PROJECT_NAMESPACE . CHECK_TOKEN_FUNC;
		if (is_callable($fn))
			return $fn(Post(TOKEN_NAME), $this->TokenTimeout);
		return FALSE;
	}

	// Create Token
	public function createToken()
	{
		global $CurrentToken;
		$fn = PROJECT_NAMESPACE . CREATE_TOKEN_FUNC; // Always create token, required by API file/lookup request
		if ($this->Token == "" && is_callable($fn)) // Create token
			$this->Token = $fn();
		$CurrentToken = $this->Token; // Save to global variable
	}

	// Constructor
	public function __construct()
	{
		global $Language, $COMPOSITE_KEY_SEPARATOR;
		global $UserTable, $UserTableConn;

		// Initialize
		$GLOBALS["Page"] = &$this;
		$this->TokenTimeout = SessionTimeoutTime();

		// Language object
		if (!isset($Language))
			$Language = new Language();

		// Parent constuctor
		parent::__construct();

		// Table object (clients)
		if (!isset($GLOBALS["clients"]) || get_class($GLOBALS["clients"]) == PROJECT_NAMESPACE . "clients") {
			$GLOBALS["clients"] = &$this;
			$GLOBALS["Table"] = &$GLOBALS["clients"];
		}

		// Table object (employees)
		if (!isset($GLOBALS['employees']))
			$GLOBALS['employees'] = new employees();

		// Page ID
		if (!defined(PROJECT_NAMESPACE . "PAGE_ID"))
			define(PROJECT_NAMESPACE . "PAGE_ID", 'edit');

		// Table name (for backward compatibility)
		if (!defined(PROJECT_NAMESPACE . "TABLE_NAME"))
			define(PROJECT_NAMESPACE . "TABLE_NAME", 'clients');

		// Start timer
		if (!isset($GLOBALS["DebugTimer"]))
			$GLOBALS["DebugTimer"] = new Timer();

		// Debug message
		LoadDebugMessage();

		// Open connection
		if (!isset($GLOBALS["Conn"]))
			$GLOBALS["Conn"] = &$this->getConnection();

		// User table object (employees)
		if (!isset($UserTable)) {
			$UserTable = new employees();
			$UserTableConn = Conn($UserTable->Dbid);
		}
	}

	// Terminate page
	public function terminate($url = "")
	{
		global $ExportFileName, $TempImages;

		// Page Unload event
		$this->Page_Unload();

		// Global Page Unloaded event (in userfn*.php)
		Page_Unloaded();

		// Export
		global $EXPORT, $clients;
		if ($this->CustomExport && $this->CustomExport == $this->Export && array_key_exists($this->CustomExport, $EXPORT)) {
				$content = ob_get_contents();
			if ($ExportFileName == "")
				$ExportFileName = $this->TableVar;
			$class = PROJECT_NAMESPACE . $EXPORT[$this->CustomExport];
			if (class_exists($class)) {
				$doc = new $class($clients);
				$doc->Text = @$content;
				if ($this->isExport("email"))
					echo $this->exportEmail($doc->Text);
				else
					$doc->export();
				DeleteTempImages(); // Delete temp images
				exit();
			}
		}
		if (!IsApi())
			$this->Page_Redirecting($url);

		// Close connection
		CloseConnections();

		// Return for API
		if (IsApi()) {
			$res = $url === TRUE;
			if (!$res) // Show error
				WriteJson(array_merge(["success" => FALSE], $this->getMessages()));
			return;
		}

		// Go to URL if specified
		if ($url <> "") {
			if (!DEBUG_ENABLED && ob_get_length())
				ob_end_clean();

			// Handle modal response
			if ($this->IsModal) { // Show as modal
				$row = array("url" => $url, "modal" => "1");
				$pageName = GetPageName($url);
				if ($pageName != $this->getListUrl()) { // Not List page
					$row["caption"] = $this->getModalCaption($pageName);
					if ($pageName == "clientsview.php")
						$row["view"] = "1";
				} else { // List page should not be shown as modal => error
					$row["error"] = $this->getFailureMessage();
					$this->clearFailureMessage();
				}
				WriteJson($row);
			} else {
				SaveDebugMessage();
				AddHeader("Location", $url);
			}
		}
		exit();
	}

	// Get records from recordset
	protected function getRecordsFromRecordset($rs, $current = FALSE)
	{
		$rows = array();
		if (is_object($rs)) { // Recordset
			while ($rs && !$rs->EOF) {
				$this->loadRowValues($rs); // Set up DbValue/CurrentValue
				$row = $this->getRecordFromArray($rs->fields);
				if ($current)
					return $row;
				else
					$rows[] = $row;
				$rs->moveNext();
			}
		} elseif (is_array($rs)) {
			foreach ($rs as $ar) {
				$row = $this->getRecordFromArray($ar);
				if ($current)
					return $row;
				else
					$rows[] = $row;
			}
		}
		return $rows;
	}

	// Get record from array
	protected function getRecordFromArray($ar)
	{
		$row = array();
		if (is_array($ar)) {
			foreach ($ar as $fldname => $val) {
				if (array_key_exists($fldname, $this->fields) && ($this->fields[$fldname]->Visible || $this->fields[$fldname]->IsPrimaryKey)) { // Primary key or Visible
					$fld = &$this->fields[$fldname];
					if ($fld->HtmlTag == "FILE") { // Upload field
						if (EmptyValue($val)) {
							$row[$fldname] = NULL;
						} else {
							if ($fld->DataType == DATATYPE_BLOB) {

								//$url = FullUrl($fld->TableVar . "/" . API_FILE_ACTION . "/" . $fld->Param . "/" . rawurlencode($this->getRecordKeyValue($ar))); // URL rewrite format
								$url = FullUrl(GetPageName(API_URL) . "?" . API_OBJECT_NAME . "=" . $fld->TableVar . "&" . API_ACTION_NAME . "=" . API_FILE_ACTION . "&" . API_FIELD_NAME . "=" . $fld->Param . "&" . API_KEY_NAME . "=" . rawurlencode($this->getRecordKeyValue($ar))); // Query string format
								$row[$fldname] = ["mimeType" => ContentType($val), "url" => $url];
							} elseif (!$fld->UploadMultiple || !ContainsString($val, MULTIPLE_UPLOAD_SEPARATOR)) { // Single file
								$row[$fldname] = ["mimeType" => MimeContentType($val), "url" => FullUrl($fld->hrefPath() . $val)];
							} else { // Multiple files
								$files = explode(MULTIPLE_UPLOAD_SEPARATOR, $val);
								$ar = [];
								foreach ($files as $file) {
									if (!EmptyValue($file))
										$ar[] = ["type" => MimeContentType($file), "url" => FullUrl($fld->hrefPath() . $file)];
								}
								$row[$fldname] = $ar;
							}
						}
					} else {
						$row[$fldname] = $val;
					}
				}
			}
		}
		return $row;
	}

	// Get record key value from array
	protected function getRecordKeyValue($ar)
	{
		global $COMPOSITE_KEY_SEPARATOR;
		$key = "";
		if (is_array($ar)) {
			$key .= @$ar['ClientID'];
		}
		return $key;
	}

	/**
	 * Hide fields for add/edit
	 *
	 * @return void
	 */
	protected function hideFieldsForAddEdit()
	{
		if ($this->isAdd() || $this->isCopy() || $this->isGridAdd())
			$this->ClientID->Visible = FALSE;
	}
	public $FormClassName = "ew-horizontal ew-form ew-edit-form";
	public $IsModal = FALSE;
	public $IsMobileOrModal = FALSE;
	public $DbMasterFilter;
	public $DbDetailFilter;
	public $DisplayRecs = 1;
	public $StartRec;
	public $StopRec;
	public $TotalRecs = 0;
	public $RecRange = 10;
	public $Pager;
	public $AutoHidePager = AUTO_HIDE_PAGER;
	public $RecCnt;
	public $DetailPages; // Detail pages object

	//
	// Page run
	//

	public function run()
	{
		global $ExportType, $CustomExportType, $ExportFileName, $UserProfile, $Language, $Security, $RequestSecurity, $CurrentForm,
			$FormError, $SkipHeaderFooter;

		// Init Session data for API request if token found
		if (IsApi() && session_status() !== PHP_SESSION_ACTIVE) {
			$func = PROJECT_NAMESPACE . CHECK_TOKEN_FUNC;
			if (is_callable($func) && Param(TOKEN_NAME) !== NULL && $func(Param(TOKEN_NAME), SessionTimeoutTime()))
				session_start();
		}

		// Is modal
		$this->IsModal = (Param("modal") == "1");

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

		// Security
		$Security = new AdvancedSecurity();
		$validRequest = FALSE;

		// Check security for API request
		If (IsApi()) {

			// Check token first
			$func = PROJECT_NAMESPACE . CHECK_TOKEN_FUNC;
			if (is_callable($func) && Post(TOKEN_NAME) !== NULL)
				$validRequest = $func(Post(TOKEN_NAME), SessionTimeoutTime());
			elseif (is_array($RequestSecurity) && @$RequestSecurity["username"] <> "") // Login user for API request
				$Security->loginUser(@$RequestSecurity["username"], @$RequestSecurity["userid"], @$RequestSecurity["parentuserid"], @$RequestSecurity["userlevelid"]);
		}
		if (!$validRequest) {
			if (IsPasswordExpired())
				$this->terminate(GetUrl("changepwd.php"));
			if (!$Security->isLoggedIn())
				$Security->autoLogin();
			if ($Security->isLoggedIn())
				$Security->TablePermission_Loading();
			$Security->loadCurrentUserLevel($this->ProjectID . $this->TableName);
			if ($Security->isLoggedIn())
				$Security->TablePermission_Loaded();
			if (!$Security->canEdit()) {
				$Security->saveLastUrl();
				$this->setFailureMessage(DeniedMessage()); // Set no permission
				if ($Security->canList())
					$this->terminate(GetUrl("clientslist.php"));
				else
					$this->terminate(GetUrl("login.php"));
				return;
			}
			if ($Security->isLoggedIn()) {
				$Security->UserID_Loading();
				$Security->loadUserID();
				$Security->UserID_Loaded();
			}
		}

		// Update last accessed time
		if ($UserProfile->isValidUser(CurrentUserName(), session_id())) {
		} else {
			Write($Language->phrase("UserProfileCorrupted"));
			$this->terminate();
		}

		// Create form object
		$CurrentForm = new HttpForm();
		$this->CurrentAction = Param("action"); // Set up current action
		$this->ClientID->setVisibility();
		$this->ClientTypeID->setVisibility();
		$this->ClientGroupID->setVisibility();
		$this->TitleID->setVisibility();
		$this->FirstName->setVisibility();
		$this->MiddleName->setVisibility();
		$this->LastName->setVisibility();
		$this->PartnersName->setVisibility();
		$this->CompanyName->setVisibility();
		$this->ContactPerson->setVisibility();
		$this->WorkNature->setVisibility();
		$this->JobTitle->setVisibility();
		$this->Photo->setVisibility();
		$this->BirthDate->setVisibility();
		$this->Title->Visible = FALSE;
		$this->TitleEn->Visible = FALSE;
		$this->FirstNameEn->Visible = FALSE;
		$this->MiddleNameEn->Visible = FALSE;
		$this->LastNameEn->Visible = FALSE;
		$this->PartnersNameEn->Visible = FALSE;
		$this->CompanyNameEn->Visible = FALSE;
		$this->AddressID->Visible = FALSE;
		$this->ContactID->Visible = FALSE;
		$this->Gender->setVisibility();
		$this->Notes->setVisibility();
		$this->Activated->Visible = FALSE;
		$this->Profile->Visible = FALSE;
		$this->_UserID->Visible = FALSE;
		$this->CreatedBy->Visible = FALSE;
		$this->CreatedDate->Visible = FALSE;
		$this->UpdatedBy->Visible = FALSE;
		$this->UpdatedDate->Visible = FALSE;
		$this->FileNumber->Visible = FALSE;
		$this->NotesConv->setVisibility();
		$this->hideFieldsForAddEdit();

		// Do not use lookup cache
		$this->setUseLookupCache(FALSE);

		// Set up detail page object
		$this->setupDetailPages();

		// Global Page Loading event (in userfn*.php)
		Page_Loading();

		// Page Load event
		$this->Page_Load();

		// Check token
		if (!$this->validPost()) {
			Write($Language->phrase("InvalidPostRequest"));
			$this->terminate();
		}

		// Create Token
		$this->createToken();

		// Set up lookup cache
		$this->setupLookupOptions($this->ClientTypeID);
		$this->setupLookupOptions($this->ClientGroupID);
		$this->setupLookupOptions($this->TitleID);

		// Check modal
		if ($this->IsModal)
			$SkipHeaderFooter = TRUE;
		$this->IsMobileOrModal = IsMobile() || $this->IsModal;
		$this->FormClassName = "ew-form ew-edit-form ew-horizontal";

		// Load record by position
		$loadByPosition = FALSE;
		$loaded = FALSE;
		$postBack = FALSE;

		// Set up current action and primary key
		if (IsApi()) {
			$this->CurrentAction = "update"; // Update record directly
			$postBack = TRUE;
		} elseif (Post("action") !== NULL) {
			$this->CurrentAction = Post("action"); // Get action code
			if (!$this->isShow()) // Not reload record, handle as postback
				$postBack = TRUE;

			// Load key from Form
			if ($CurrentForm->hasValue("x_ClientID")) {
				$this->ClientID->setFormValue($CurrentForm->getValue("x_ClientID"));
			}
		} else {
			$this->CurrentAction = "show"; // Default action is display

			// Load key from QueryString
			$loadByQuery = FALSE;
			if (Get("ClientID") !== NULL) {
				$this->ClientID->setQueryStringValue(Get("ClientID"));
				$loadByQuery = TRUE;
			} else {
				$this->ClientID->CurrentValue = NULL;
			}
			if (!$loadByQuery)
				$loadByPosition = TRUE;
		}

		// Load recordset
		$this->StartRec = 1; // Initialize start position
		if ($rs = $this->loadRecordset()) // Load records
			$this->TotalRecs = $rs->RecordCount(); // Get record count
		if ($this->TotalRecs <= 0) { // No record found
			if ($this->getSuccessMessage() == "" && $this->getFailureMessage() == "")
				$this->setFailureMessage($Language->phrase("NoRecord")); // Set no record message
			$this->terminate("clientslist.php"); // Return to list page
		} elseif ($loadByPosition) { // Load record by position
			$this->setupStartRec(); // Set up start record position

			// Point to current record
			if ($this->StartRec <= $this->TotalRecs) {
				$rs->move($this->StartRec - 1);
				$loaded = TRUE;
			}
		} else { // Match key values
			if ($this->ClientID->CurrentValue != NULL) {
				while (!$rs->EOF) {
					if (SameString($this->ClientID->CurrentValue, $rs->fields('ClientID'))) {
						$this->setStartRecordNumber($this->StartRec); // Save record position
						$loaded = TRUE;
						break;
					} else {
						$this->StartRec++;
						$rs->moveNext();
					}
				}
			}
		}

		// Load current row values
		if ($loaded)
			$this->loadRowValues($rs);

		// Process form if post back
		if ($postBack) {
			$this->loadFormValues(); // Get form values

			// Set up detail parameters
			$this->setupDetailParms();
		}

		// Validate form if post back
		if ($postBack) {
			if (!$this->validateForm()) {
				$this->setFailureMessage($FormError);
				$this->EventCancelled = TRUE; // Event cancelled
				$this->restoreFormValues();
				if (IsApi()) {
					$this->terminate();
					return;
				} else {
					$this->CurrentAction = ""; // Form error, reset action
				}
			}
		}

		// Perform current action
		switch ($this->CurrentAction) {
			case "show": // Get a record to display
				if (!$loaded) {
					if ($this->getSuccessMessage() == "" && $this->getFailureMessage() == "")
						$this->setFailureMessage($Language->phrase("NoRecord")); // Set no record message
					$this->terminate("clientslist.php"); // Return to list page
				} else {
				}

				// Set up detail parameters
				$this->setupDetailParms();
				break;
			case "update": // Update
				if ($this->getCurrentDetailTable() <> "") // Master/detail edit
					$returnUrl = $this->getViewUrl(TABLE_SHOW_DETAIL . "=" . $this->getCurrentDetailTable()); // Master/Detail view page
				else
					$returnUrl = $this->getReturnUrl();
				if (GetPageName($returnUrl) == "clientslist.php")
					$returnUrl = $this->addMasterUrl($returnUrl); // List page, return to List page with correct master key if necessary
				$this->SendEmail = TRUE; // Send email on update success
				if ($this->editRow()) { // Update record based on key
					if ($this->getSuccessMessage() == "")
						$this->setSuccessMessage($Language->phrase("UpdateSuccess")); // Update success
					if (IsApi()) {
						$this->terminate(TRUE);
						return;
					} else {
						$this->terminate($returnUrl); // Return to caller
					}
				} elseif (IsApi()) { // API request, return
					$this->terminate();
					return;
				} elseif ($this->getFailureMessage() == $Language->phrase("NoRecord")) {
					$this->terminate($returnUrl); // Return to caller
				} else {
					$this->EventCancelled = TRUE; // Event cancelled
					$this->restoreFormValues(); // Restore form values if update failed

					// Set up detail parameters
					$this->setupDetailParms();
				}
		}

		// Set up Breadcrumb
		$this->setupBreadcrumb();

		// Render the record
		$this->RowType = ROWTYPE_EDIT; // Render as Edit
		$this->resetAttributes();
		$this->renderRow();
	}

	// Set up starting record parameters
	public function setupStartRec()
	{
		if ($this->DisplayRecs == 0)
			return;
		if ($this->isPageRequest()) { // Validate request
			if (Get(TABLE_START_REC) !== NULL) { // Check for "start" parameter
				$this->StartRec = Get(TABLE_START_REC);
				$this->setStartRecordNumber($this->StartRec);
			} elseif (Get(TABLE_PAGE_NO) !== NULL) {
				$pageNo = Get(TABLE_PAGE_NO);
				if (is_numeric($pageNo)) {
					$this->StartRec = ($pageNo - 1) * $this->DisplayRecs + 1;
					if ($this->StartRec <= 0) {
						$this->StartRec = 1;
					} elseif ($this->StartRec >= (int)(($this->TotalRecs - 1)/$this->DisplayRecs) * $this->DisplayRecs + 1) {
						$this->StartRec = (int)(($this->TotalRecs - 1)/$this->DisplayRecs) * $this->DisplayRecs + 1;
					}
					$this->setStartRecordNumber($this->StartRec);
				}
			}
		}
		$this->StartRec = $this->getStartRecordNumber();

		// Check if correct start record counter
		if (!is_numeric($this->StartRec) || $this->StartRec == "") { // Avoid invalid start record counter
			$this->StartRec = 1; // Reset start record counter
			$this->setStartRecordNumber($this->StartRec);
		} elseif ($this->StartRec > $this->TotalRecs) { // Avoid starting record > total records
			$this->StartRec = (int)(($this->TotalRecs - 1)/$this->DisplayRecs) * $this->DisplayRecs + 1; // Point to last page first record
			$this->setStartRecordNumber($this->StartRec);
		} elseif (($this->StartRec - 1) % $this->DisplayRecs <> 0) {
			$this->StartRec = (int)(($this->StartRec - 1)/$this->DisplayRecs) * $this->DisplayRecs + 1; // Point to page boundary
			$this->setStartRecordNumber($this->StartRec);
		}
	}

	// Get upload files
	protected function getUploadFiles()
	{
		global $CurrentForm, $Language;
		$this->Photo->Upload->Index = $CurrentForm->Index;
		$this->Photo->Upload->uploadFile();
		$this->Photo->CurrentValue = $this->Photo->Upload->FileName;
	}

	// Load form values
	protected function loadFormValues()
	{

		// Load from form
		global $CurrentForm;
		$this->getUploadFiles(); // Get upload files

		// Check field name 'ClientID' first before field var 'x_ClientID'
		$val = $CurrentForm->hasValue("ClientID") ? $CurrentForm->getValue("ClientID") : $CurrentForm->getValue("x_ClientID");
		if (!$this->ClientID->IsDetailKey)
			$this->ClientID->setFormValue($val);

		// Check field name 'ClientTypeID' first before field var 'x_ClientTypeID'
		$val = $CurrentForm->hasValue("ClientTypeID") ? $CurrentForm->getValue("ClientTypeID") : $CurrentForm->getValue("x_ClientTypeID");
		if (!$this->ClientTypeID->IsDetailKey) {
			if (IsApi() && $val == NULL)
				$this->ClientTypeID->Visible = FALSE; // Disable update for API request
			else
				$this->ClientTypeID->setFormValue($val);
		}

		// Check field name 'ClientGroupID' first before field var 'x_ClientGroupID'
		$val = $CurrentForm->hasValue("ClientGroupID") ? $CurrentForm->getValue("ClientGroupID") : $CurrentForm->getValue("x_ClientGroupID");
		if (!$this->ClientGroupID->IsDetailKey) {
			if (IsApi() && $val == NULL)
				$this->ClientGroupID->Visible = FALSE; // Disable update for API request
			else
				$this->ClientGroupID->setFormValue($val);
		}

		// Check field name 'TitleID' first before field var 'x_TitleID'
		$val = $CurrentForm->hasValue("TitleID") ? $CurrentForm->getValue("TitleID") : $CurrentForm->getValue("x_TitleID");
		if (!$this->TitleID->IsDetailKey) {
			if (IsApi() && $val == NULL)
				$this->TitleID->Visible = FALSE; // Disable update for API request
			else
				$this->TitleID->setFormValue($val);
		}

		// Check field name 'FirstName' first before field var 'x_FirstName'
		$val = $CurrentForm->hasValue("FirstName") ? $CurrentForm->getValue("FirstName") : $CurrentForm->getValue("x_FirstName");
		if (!$this->FirstName->IsDetailKey) {
			if (IsApi() && $val == NULL)
				$this->FirstName->Visible = FALSE; // Disable update for API request
			else
				$this->FirstName->setFormValue($val);
		}

		// Check field name 'MiddleName' first before field var 'x_MiddleName'
		$val = $CurrentForm->hasValue("MiddleName") ? $CurrentForm->getValue("MiddleName") : $CurrentForm->getValue("x_MiddleName");
		if (!$this->MiddleName->IsDetailKey) {
			if (IsApi() && $val == NULL)
				$this->MiddleName->Visible = FALSE; // Disable update for API request
			else
				$this->MiddleName->setFormValue($val);
		}

		// Check field name 'LastName' first before field var 'x_LastName'
		$val = $CurrentForm->hasValue("LastName") ? $CurrentForm->getValue("LastName") : $CurrentForm->getValue("x_LastName");
		if (!$this->LastName->IsDetailKey) {
			if (IsApi() && $val == NULL)
				$this->LastName->Visible = FALSE; // Disable update for API request
			else
				$this->LastName->setFormValue($val);
		}

		// Check field name 'PartnersName' first before field var 'x_PartnersName'
		$val = $CurrentForm->hasValue("PartnersName") ? $CurrentForm->getValue("PartnersName") : $CurrentForm->getValue("x_PartnersName");
		if (!$this->PartnersName->IsDetailKey) {
			if (IsApi() && $val == NULL)
				$this->PartnersName->Visible = FALSE; // Disable update for API request
			else
				$this->PartnersName->setFormValue($val);
		}

		// Check field name 'CompanyName' first before field var 'x_CompanyName'
		$val = $CurrentForm->hasValue("CompanyName") ? $CurrentForm->getValue("CompanyName") : $CurrentForm->getValue("x_CompanyName");
		if (!$this->CompanyName->IsDetailKey) {
			if (IsApi() && $val == NULL)
				$this->CompanyName->Visible = FALSE; // Disable update for API request
			else
				$this->CompanyName->setFormValue($val);
		}

		// Check field name 'ContactPerson' first before field var 'x_ContactPerson'
		$val = $CurrentForm->hasValue("ContactPerson") ? $CurrentForm->getValue("ContactPerson") : $CurrentForm->getValue("x_ContactPerson");
		if (!$this->ContactPerson->IsDetailKey) {
			if (IsApi() && $val == NULL)
				$this->ContactPerson->Visible = FALSE; // Disable update for API request
			else
				$this->ContactPerson->setFormValue($val);
		}

		// Check field name 'WorkNature' first before field var 'x_WorkNature'
		$val = $CurrentForm->hasValue("WorkNature") ? $CurrentForm->getValue("WorkNature") : $CurrentForm->getValue("x_WorkNature");
		if (!$this->WorkNature->IsDetailKey) {
			if (IsApi() && $val == NULL)
				$this->WorkNature->Visible = FALSE; // Disable update for API request
			else
				$this->WorkNature->setFormValue($val);
		}

		// Check field name 'JobTitle' first before field var 'x_JobTitle'
		$val = $CurrentForm->hasValue("JobTitle") ? $CurrentForm->getValue("JobTitle") : $CurrentForm->getValue("x_JobTitle");
		if (!$this->JobTitle->IsDetailKey) {
			if (IsApi() && $val == NULL)
				$this->JobTitle->Visible = FALSE; // Disable update for API request
			else
				$this->JobTitle->setFormValue($val);
		}

		// Check field name 'BirthDate' first before field var 'x_BirthDate'
		$val = $CurrentForm->hasValue("BirthDate") ? $CurrentForm->getValue("BirthDate") : $CurrentForm->getValue("x_BirthDate");
		if (!$this->BirthDate->IsDetailKey) {
			if (IsApi() && $val == NULL)
				$this->BirthDate->Visible = FALSE; // Disable update for API request
			else
				$this->BirthDate->setFormValue($val);
			$this->BirthDate->CurrentValue = UnFormatDateTime($this->BirthDate->CurrentValue, 0);
		}

		// Check field name 'Gender' first before field var 'x_Gender'
		$val = $CurrentForm->hasValue("Gender") ? $CurrentForm->getValue("Gender") : $CurrentForm->getValue("x_Gender");
		if (!$this->Gender->IsDetailKey) {
			if (IsApi() && $val == NULL)
				$this->Gender->Visible = FALSE; // Disable update for API request
			else
				$this->Gender->setFormValue($val);
		}

		// Check field name 'Notes' first before field var 'x_Notes'
		$val = $CurrentForm->hasValue("Notes") ? $CurrentForm->getValue("Notes") : $CurrentForm->getValue("x_Notes");
		if (!$this->Notes->IsDetailKey) {
			if (IsApi() && $val == NULL)
				$this->Notes->Visible = FALSE; // Disable update for API request
			else
				$this->Notes->setFormValue($val);
		}

		// Check field name 'NotesConv' first before field var 'x_NotesConv'
		$val = $CurrentForm->hasValue("NotesConv") ? $CurrentForm->getValue("NotesConv") : $CurrentForm->getValue("x_NotesConv");
		if (!$this->NotesConv->IsDetailKey) {
			if (IsApi() && $val == NULL)
				$this->NotesConv->Visible = FALSE; // Disable update for API request
			else
				$this->NotesConv->setFormValue($val);
		}
	}

	// Restore form values
	public function restoreFormValues()
	{
		global $CurrentForm;
		$this->ClientID->CurrentValue = $this->ClientID->FormValue;
		$this->ClientTypeID->CurrentValue = $this->ClientTypeID->FormValue;
		$this->ClientGroupID->CurrentValue = $this->ClientGroupID->FormValue;
		$this->TitleID->CurrentValue = $this->TitleID->FormValue;
		$this->FirstName->CurrentValue = $this->FirstName->FormValue;
		$this->MiddleName->CurrentValue = $this->MiddleName->FormValue;
		$this->LastName->CurrentValue = $this->LastName->FormValue;
		$this->PartnersName->CurrentValue = $this->PartnersName->FormValue;
		$this->CompanyName->CurrentValue = $this->CompanyName->FormValue;
		$this->ContactPerson->CurrentValue = $this->ContactPerson->FormValue;
		$this->WorkNature->CurrentValue = $this->WorkNature->FormValue;
		$this->JobTitle->CurrentValue = $this->JobTitle->FormValue;
		$this->BirthDate->CurrentValue = $this->BirthDate->FormValue;
		$this->BirthDate->CurrentValue = UnFormatDateTime($this->BirthDate->CurrentValue, 0);
		$this->Gender->CurrentValue = $this->Gender->FormValue;
		$this->Notes->CurrentValue = $this->Notes->FormValue;
		$this->NotesConv->CurrentValue = $this->NotesConv->FormValue;
	}

	// Load recordset
	public function loadRecordset($offset = -1, $rowcnt = -1)
	{

		// Load List page SQL
		$sql = $this->getListSql();
		$conn = &$this->getConnection();

		// Load recordset
		$dbtype = GetConnectionType($this->Dbid);
		if ($this->UseSelectLimit) {
			$conn->raiseErrorFn = $GLOBALS["ERROR_FUNC"];
			if ($dbtype == "MSSQL") {
				$rs = $conn->selectLimit($sql, $rowcnt, $offset, ["_hasOrderBy" => trim($this->getOrderBy()) || trim($this->getSessionOrderByList())]);
			} else {
				$rs = $conn->selectLimit($sql, $rowcnt, $offset);
			}
			$conn->raiseErrorFn = '';
		} else {
			$rs = LoadRecordset($sql, $conn);
		}

		// Call Recordset Selected event
		$this->Recordset_Selected($rs);
		return $rs;
	}

	// Load row based on key values
	public function loadRow()
	{
		global $Security, $Language;
		$filter = $this->getRecordFilter();

		// Call Row Selecting event
		$this->Row_Selecting($filter);

		// Load SQL based on filter
		$this->CurrentFilter = $filter;
		$sql = $this->getCurrentSql();
		$conn = &$this->getConnection();
		$res = FALSE;
		$rs = LoadRecordset($sql, $conn);
		if ($rs && !$rs->EOF) {
			$res = TRUE;
			$this->loadRowValues($rs); // Load row values
			$rs->close();
		}
		return $res;
	}

	// Load row values from recordset
	public function loadRowValues($rs = NULL)
	{
		if ($rs && !$rs->EOF)
			$row = $rs->fields;
		else
			$row = $this->newRow();

		// Call Row Selected event
		$this->Row_Selected($row);
		if (!$rs || $rs->EOF)
			return;
		$this->ClientID->setDbValue($row['ClientID']);
		$this->ClientTypeID->setDbValue($row['ClientTypeID']);
		$this->ClientGroupID->setDbValue($row['ClientGroupID']);
		if (array_key_exists('EV__ClientGroupID', $rs->fields)) {
			$this->ClientGroupID->VirtualValue = $rs->fields('EV__ClientGroupID'); // Set up virtual field value
		} else {
			$this->ClientGroupID->VirtualValue = ""; // Clear value
		}
		$this->TitleID->setDbValue($row['TitleID']);
		$this->FirstName->setDbValue($row['FirstName']);
		$this->MiddleName->setDbValue($row['MiddleName']);
		$this->LastName->setDbValue($row['LastName']);
		$this->PartnersName->setDbValue($row['PartnersName']);
		$this->CompanyName->setDbValue($row['CompanyName']);
		$this->ContactPerson->setDbValue($row['ContactPerson']);
		$this->WorkNature->setDbValue($row['WorkNature']);
		$this->JobTitle->setDbValue($row['JobTitle']);
		$this->Photo->Upload->DbValue = $row['Photo'];
		$this->Photo->setDbValue($this->Photo->Upload->DbValue);
		$this->BirthDate->setDbValue($row['BirthDate']);
		$this->Title->setDbValue($row['Title']);
		$this->TitleEn->setDbValue($row['TitleEn']);
		$this->FirstNameEn->setDbValue($row['FirstNameEn']);
		$this->MiddleNameEn->setDbValue($row['MiddleNameEn']);
		$this->LastNameEn->setDbValue($row['LastNameEn']);
		$this->PartnersNameEn->setDbValue($row['PartnersNameEn']);
		$this->CompanyNameEn->setDbValue($row['CompanyNameEn']);
		$this->AddressID->setDbValue($row['AddressID']);
		$this->ContactID->setDbValue($row['ContactID']);
		$this->Gender->setDbValue($row['Gender']);
		$this->Notes->setDbValue($row['Notes']);
		$this->Activated->setDbValue($row['Activated']);
		$this->Profile->setDbValue($row['Profile']);
		$this->_UserID->setDbValue($row['UserID']);
		$this->CreatedBy->setDbValue($row['CreatedBy']);
		$this->CreatedDate->setDbValue($row['CreatedDate']);
		$this->UpdatedBy->setDbValue($row['UpdatedBy']);
		$this->UpdatedDate->setDbValue($row['UpdatedDate']);
		$this->FileNumber->setDbValue($row['FileNumber']);
		$this->NotesConv->setDbValue($row['NotesConv']);
	}

	// Return a row with default values
	protected function newRow()
	{
		$row = [];
		$row['ClientID'] = NULL;
		$row['ClientTypeID'] = NULL;
		$row['ClientGroupID'] = NULL;
		$row['TitleID'] = NULL;
		$row['FirstName'] = NULL;
		$row['MiddleName'] = NULL;
		$row['LastName'] = NULL;
		$row['PartnersName'] = NULL;
		$row['CompanyName'] = NULL;
		$row['ContactPerson'] = NULL;
		$row['WorkNature'] = NULL;
		$row['JobTitle'] = NULL;
		$row['Photo'] = NULL;
		$row['BirthDate'] = NULL;
		$row['Title'] = NULL;
		$row['TitleEn'] = NULL;
		$row['FirstNameEn'] = NULL;
		$row['MiddleNameEn'] = NULL;
		$row['LastNameEn'] = NULL;
		$row['PartnersNameEn'] = NULL;
		$row['CompanyNameEn'] = NULL;
		$row['AddressID'] = NULL;
		$row['ContactID'] = NULL;
		$row['Gender'] = NULL;
		$row['Notes'] = NULL;
		$row['Activated'] = NULL;
		$row['Profile'] = NULL;
		$row['UserID'] = NULL;
		$row['CreatedBy'] = NULL;
		$row['CreatedDate'] = NULL;
		$row['UpdatedBy'] = NULL;
		$row['UpdatedDate'] = NULL;
		$row['FileNumber'] = NULL;
		$row['NotesConv'] = NULL;
		return $row;
	}

	// Load old record
	protected function loadOldRecord()
	{

		// Load key values from Session
		$validKey = TRUE;
		if (strval($this->getKey("ClientID")) <> "")
			$this->ClientID->CurrentValue = $this->getKey("ClientID"); // ClientID
		else
			$validKey = FALSE;

		// Load old record
		$this->OldRecordset = NULL;
		if ($validKey) {
			$this->CurrentFilter = $this->getRecordFilter();
			$sql = $this->getCurrentSql();
			$conn = &$this->getConnection();
			$this->OldRecordset = LoadRecordset($sql, $conn);
		}
		$this->loadRowValues($this->OldRecordset); // Load row values
		return $validKey;
	}

	// Render row values based on field settings
	public function renderRow()
	{
		global $Security, $Language, $CurrentLanguage;

		// Initialize URLs
		// Call Row_Rendering event

		$this->Row_Rendering();

		// Common render codes for all row types
		// ClientID
		// ClientTypeID
		// ClientGroupID
		// TitleID
		// FirstName
		// MiddleName
		// LastName
		// PartnersName
		// CompanyName
		// ContactPerson
		// WorkNature
		// JobTitle
		// Photo
		// BirthDate
		// Title
		// TitleEn
		// FirstNameEn
		// MiddleNameEn
		// LastNameEn
		// PartnersNameEn
		// CompanyNameEn
		// AddressID
		// ContactID
		// Gender
		// Notes
		// Activated
		// Profile
		// UserID
		// CreatedBy
		// CreatedDate
		// UpdatedBy
		// UpdatedDate
		// FileNumber
		// NotesConv

		if ($this->RowType == ROWTYPE_VIEW) { // View row

			// 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 = "";

			// 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 = "";

			// 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 = "";

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

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

			// NotesConv
			$this->NotesConv->LinkCustomAttributes = "";
			$this->NotesConv->HrefValue = "";
			$this->NotesConv->TooltipValue = "";
		} elseif ($this->RowType == ROWTYPE_EDIT) { // Edit row

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

			// ClientTypeID
			$this->ClientTypeID->EditAttrs["class"] = "form-control";
			$this->ClientTypeID->EditCustomAttributes = "";
			$curVal = trim(strval($this->ClientTypeID->CurrentValue));
			if ($curVal <> "")
				$this->ClientTypeID->ViewValue = $this->ClientTypeID->lookupCacheOption($curVal);
			else
				$this->ClientTypeID->ViewValue = $this->ClientTypeID->Lookup !== NULL && is_array($this->ClientTypeID->Lookup->Options) ? $curVal : NULL;
			if ($this->ClientTypeID->ViewValue !== NULL) { // Load from cache
				$this->ClientTypeID->EditValue = array_values($this->ClientTypeID->Lookup->Options);
			} else { // Lookup from database
				if ($curVal == "") {
					$filterWrk = "0=1";
				} else {
					$filterWrk = "`PartiesTypeID`" . SearchString("=", $this->ClientTypeID->CurrentValue, DATATYPE_NUMBER, "");
				}
				$sqlWrk = $this->ClientTypeID->Lookup->getSql(TRUE, $filterWrk, '', $this);
				$rswrk = Conn()->execute($sqlWrk);
				$arwrk = ($rswrk) ? $rswrk->GetRows() : array();
				if ($rswrk) $rswrk->Close();
				$this->ClientTypeID->EditValue = $arwrk;
			}

			// ClientGroupID
			$this->ClientGroupID->EditAttrs["class"] = "form-control";
			$this->ClientGroupID->EditCustomAttributes = "";
			$this->ClientGroupID->EditValue = HtmlEncode($this->ClientGroupID->CurrentValue);
			$curVal = strval($this->ClientGroupID->CurrentValue);
			if ($curVal <> "") {
				$this->ClientGroupID->EditValue = $this->ClientGroupID->lookupCacheOption($curVal);
				if ($this->ClientGroupID->EditValue === 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] = HtmlEncode($rswrk->fields('df'));
						$arwrk[2] = HtmlEncode($rswrk->fields('df2'));
						$arwrk[3] = HtmlEncode($rswrk->fields('df3'));
						$this->ClientGroupID->EditValue = $this->ClientGroupID->displayValue($arwrk);
						$rswrk->Close();
					} else {
						$this->ClientGroupID->EditValue = HtmlEncode($this->ClientGroupID->CurrentValue);
					}
				}
			} else {
				$this->ClientGroupID->EditValue = NULL;
			}
			$this->ClientGroupID->PlaceHolder = RemoveHtml($this->ClientGroupID->caption());

			// TitleID
			$this->TitleID->EditAttrs["class"] = "form-control";
			$this->TitleID->EditCustomAttributes = "";
			$curVal = trim(strval($this->TitleID->CurrentValue));
			if ($curVal <> "")
				$this->TitleID->ViewValue = $this->TitleID->lookupCacheOption($curVal);
			else
				$this->TitleID->ViewValue = $this->TitleID->Lookup !== NULL && is_array($this->TitleID->Lookup->Options) ? $curVal : NULL;
			if ($this->TitleID->ViewValue !== NULL) { // Load from cache
				$this->TitleID->EditValue = array_values($this->TitleID->Lookup->Options);
			} else { // Lookup from database
				if ($curVal == "") {
					$filterWrk = "0=1";
				} else {
					$filterWrk = "`TitleID`" . SearchString("=", $this->TitleID->CurrentValue, DATATYPE_NUMBER, "");
				}
				$sqlWrk = $this->TitleID->Lookup->getSql(TRUE, $filterWrk, '', $this);
				$rswrk = Conn()->execute($sqlWrk);
				$arwrk = ($rswrk) ? $rswrk->GetRows() : array();
				if ($rswrk) $rswrk->Close();
				$this->TitleID->EditValue = $arwrk;
			}

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

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

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

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

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

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

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

			// JobTitle
			$this->JobTitle->EditAttrs["class"] = "form-control";
			$this->JobTitle->EditCustomAttributes = "";
			$this->JobTitle->EditValue = HtmlEncode($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;
			if ($this->isShow() && !$this->EventCancelled)
				RenderUploadField($this->Photo);

			// BirthDate
			$this->BirthDate->EditAttrs["class"] = "form-control";
			$this->BirthDate->EditCustomAttributes = "";
			$this->BirthDate->EditValue = HtmlEncode(FormatDateTime($this->BirthDate->CurrentValue, 8));
			$this->BirthDate->PlaceHolder = RemoveHtml($this->BirthDate->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 = HtmlEncode($this->Notes->CurrentValue);
			$this->Notes->PlaceHolder = RemoveHtml($this->Notes->caption());

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

			// Edit refer script
			// ClientID

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

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

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

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

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

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

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

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

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

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

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

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

			// 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;

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

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

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

			// NotesConv
			$this->NotesConv->LinkCustomAttributes = "";
			$this->NotesConv->HrefValue = "";
		}
		if ($this->RowType == ROWTYPE_ADD || $this->RowType == ROWTYPE_EDIT || $this->RowType == ROWTYPE_SEARCH) // Add/Edit/Search row
			$this->setupFieldTitles();

		// Call Row Rendered event
		if ($this->RowType <> ROWTYPE_AGGREGATEINIT)
			$this->Row_Rendered();
	}

	// Validate form
	protected function validateForm()
	{
		global $Language, $FormError;

		// Initialize form error message
		$FormError = "";

		// Check if validation required
		if (!SERVER_VALIDATE)
			return ($FormError == "");
		if ($this->ClientID->Required) {
			if (!$this->ClientID->IsDetailKey && $this->ClientID->FormValue != NULL && $this->ClientID->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->ClientID->caption(), $this->ClientID->RequiredErrorMessage));
			}
		}
		if ($this->ClientTypeID->Required) {
			if (!$this->ClientTypeID->IsDetailKey && $this->ClientTypeID->FormValue != NULL && $this->ClientTypeID->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->ClientTypeID->caption(), $this->ClientTypeID->RequiredErrorMessage));
			}
		}
		if ($this->ClientGroupID->Required) {
			if (!$this->ClientGroupID->IsDetailKey && $this->ClientGroupID->FormValue != NULL && $this->ClientGroupID->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->ClientGroupID->caption(), $this->ClientGroupID->RequiredErrorMessage));
			}
		}
		if ($this->TitleID->Required) {
			if (!$this->TitleID->IsDetailKey && $this->TitleID->FormValue != NULL && $this->TitleID->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->TitleID->caption(), $this->TitleID->RequiredErrorMessage));
			}
		}
		if ($this->FirstName->Required) {
			if (!$this->FirstName->IsDetailKey && $this->FirstName->FormValue != NULL && $this->FirstName->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->FirstName->caption(), $this->FirstName->RequiredErrorMessage));
			}
		}
		if ($this->MiddleName->Required) {
			if (!$this->MiddleName->IsDetailKey && $this->MiddleName->FormValue != NULL && $this->MiddleName->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->MiddleName->caption(), $this->MiddleName->RequiredErrorMessage));
			}
		}
		if ($this->LastName->Required) {
			if (!$this->LastName->IsDetailKey && $this->LastName->FormValue != NULL && $this->LastName->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->LastName->caption(), $this->LastName->RequiredErrorMessage));
			}
		}
		if ($this->PartnersName->Required) {
			if (!$this->PartnersName->IsDetailKey && $this->PartnersName->FormValue != NULL && $this->PartnersName->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->PartnersName->caption(), $this->PartnersName->RequiredErrorMessage));
			}
		}
		if ($this->CompanyName->Required) {
			if (!$this->CompanyName->IsDetailKey && $this->CompanyName->FormValue != NULL && $this->CompanyName->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->CompanyName->caption(), $this->CompanyName->RequiredErrorMessage));
			}
		}
		if ($this->ContactPerson->Required) {
			if (!$this->ContactPerson->IsDetailKey && $this->ContactPerson->FormValue != NULL && $this->ContactPerson->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->ContactPerson->caption(), $this->ContactPerson->RequiredErrorMessage));
			}
		}
		if ($this->WorkNature->Required) {
			if (!$this->WorkNature->IsDetailKey && $this->WorkNature->FormValue != NULL && $this->WorkNature->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->WorkNature->caption(), $this->WorkNature->RequiredErrorMessage));
			}
		}
		if ($this->JobTitle->Required) {
			if (!$this->JobTitle->IsDetailKey && $this->JobTitle->FormValue != NULL && $this->JobTitle->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->JobTitle->caption(), $this->JobTitle->RequiredErrorMessage));
			}
		}
		if ($this->Photo->Required) {
			if ($this->Photo->Upload->FileName == "" && !$this->Photo->Upload->KeepFile) {
				AddMessage($FormError, str_replace("%s", $this->Photo->caption(), $this->Photo->RequiredErrorMessage));
			}
		}
		if ($this->BirthDate->Required) {
			if (!$this->BirthDate->IsDetailKey && $this->BirthDate->FormValue != NULL && $this->BirthDate->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->BirthDate->caption(), $this->BirthDate->RequiredErrorMessage));
			}
		}
		if (!CheckDate($this->BirthDate->FormValue)) {
			AddMessage($FormError, $this->BirthDate->errorMessage());
		}
		if ($this->Title->Required) {
			if (!$this->Title->IsDetailKey && $this->Title->FormValue != NULL && $this->Title->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->Title->caption(), $this->Title->RequiredErrorMessage));
			}
		}
		if ($this->TitleEn->Required) {
			if (!$this->TitleEn->IsDetailKey && $this->TitleEn->FormValue != NULL && $this->TitleEn->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->TitleEn->caption(), $this->TitleEn->RequiredErrorMessage));
			}
		}
		if ($this->FirstNameEn->Required) {
			if (!$this->FirstNameEn->IsDetailKey && $this->FirstNameEn->FormValue != NULL && $this->FirstNameEn->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->FirstNameEn->caption(), $this->FirstNameEn->RequiredErrorMessage));
			}
		}
		if ($this->MiddleNameEn->Required) {
			if (!$this->MiddleNameEn->IsDetailKey && $this->MiddleNameEn->FormValue != NULL && $this->MiddleNameEn->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->MiddleNameEn->caption(), $this->MiddleNameEn->RequiredErrorMessage));
			}
		}
		if ($this->LastNameEn->Required) {
			if (!$this->LastNameEn->IsDetailKey && $this->LastNameEn->FormValue != NULL && $this->LastNameEn->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->LastNameEn->caption(), $this->LastNameEn->RequiredErrorMessage));
			}
		}
		if ($this->PartnersNameEn->Required) {
			if (!$this->PartnersNameEn->IsDetailKey && $this->PartnersNameEn->FormValue != NULL && $this->PartnersNameEn->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->PartnersNameEn->caption(), $this->PartnersNameEn->RequiredErrorMessage));
			}
		}
		if ($this->CompanyNameEn->Required) {
			if (!$this->CompanyNameEn->IsDetailKey && $this->CompanyNameEn->FormValue != NULL && $this->CompanyNameEn->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->CompanyNameEn->caption(), $this->CompanyNameEn->RequiredErrorMessage));
			}
		}
		if ($this->AddressID->Required) {
			if (!$this->AddressID->IsDetailKey && $this->AddressID->FormValue != NULL && $this->AddressID->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->AddressID->caption(), $this->AddressID->RequiredErrorMessage));
			}
		}
		if ($this->ContactID->Required) {
			if (!$this->ContactID->IsDetailKey && $this->ContactID->FormValue != NULL && $this->ContactID->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->ContactID->caption(), $this->ContactID->RequiredErrorMessage));
			}
		}
		if ($this->Gender->Required) {
			if ($this->Gender->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->Gender->caption(), $this->Gender->RequiredErrorMessage));
			}
		}
		if ($this->Notes->Required) {
			if (!$this->Notes->IsDetailKey && $this->Notes->FormValue != NULL && $this->Notes->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->Notes->caption(), $this->Notes->RequiredErrorMessage));
			}
		}
		if ($this->Activated->Required) {
			if ($this->Activated->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->Activated->caption(), $this->Activated->RequiredErrorMessage));
			}
		}
		if ($this->Profile->Required) {
			if (!$this->Profile->IsDetailKey && $this->Profile->FormValue != NULL && $this->Profile->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->Profile->caption(), $this->Profile->RequiredErrorMessage));
			}
		}
		if ($this->_UserID->Required) {
			if (!$this->_UserID->IsDetailKey && $this->_UserID->FormValue != NULL && $this->_UserID->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->_UserID->caption(), $this->_UserID->RequiredErrorMessage));
			}
		}
		if ($this->CreatedBy->Required) {
			if (!$this->CreatedBy->IsDetailKey && $this->CreatedBy->FormValue != NULL && $this->CreatedBy->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->CreatedBy->caption(), $this->CreatedBy->RequiredErrorMessage));
			}
		}
		if ($this->CreatedDate->Required) {
			if (!$this->CreatedDate->IsDetailKey && $this->CreatedDate->FormValue != NULL && $this->CreatedDate->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->CreatedDate->caption(), $this->CreatedDate->RequiredErrorMessage));
			}
		}
		if ($this->UpdatedBy->Required) {
			if (!$this->UpdatedBy->IsDetailKey && $this->UpdatedBy->FormValue != NULL && $this->UpdatedBy->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->UpdatedBy->caption(), $this->UpdatedBy->RequiredErrorMessage));
			}
		}
		if ($this->UpdatedDate->Required) {
			if (!$this->UpdatedDate->IsDetailKey && $this->UpdatedDate->FormValue != NULL && $this->UpdatedDate->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->UpdatedDate->caption(), $this->UpdatedDate->RequiredErrorMessage));
			}
		}
		if ($this->FileNumber->Required) {
			if (!$this->FileNumber->IsDetailKey && $this->FileNumber->FormValue != NULL && $this->FileNumber->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->FileNumber->caption(), $this->FileNumber->RequiredErrorMessage));
			}
		}
		if ($this->NotesConv->Required) {
			if (!$this->NotesConv->IsDetailKey && $this->NotesConv->FormValue != NULL && $this->NotesConv->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->NotesConv->caption(), $this->NotesConv->RequiredErrorMessage));
			}
		}

		// Validate detail grid
		$detailTblVar = explode(",", $this->getCurrentDetailTable());
		if (in_array("cases", $detailTblVar) && $GLOBALS["cases"]->DetailEdit) {
			if (!isset($GLOBALS["cases_grid"]))
				$GLOBALS["cases_grid"] = new cases_grid(); // Get detail page object
			$GLOBALS["cases_grid"]->validateGridForm();
		}
		if (in_array("clientadditinalinfo", $detailTblVar) && $GLOBALS["clientadditinalinfo"]->DetailEdit) {
			if (!isset($GLOBALS["clientadditinalinfo_grid"]))
				$GLOBALS["clientadditinalinfo_grid"] = new clientadditinalinfo_grid(); // Get detail page object
			$GLOBALS["clientadditinalinfo_grid"]->validateGridForm();
		}
		if (in_array("clientaddress", $detailTblVar) && $GLOBALS["clientaddress"]->DetailEdit) {
			if (!isset($GLOBALS["clientaddress_grid"]))
				$GLOBALS["clientaddress_grid"] = new clientaddress_grid(); // Get detail page object
			$GLOBALS["clientaddress_grid"]->validateGridForm();
		}
		if (in_array("clientcontact", $detailTblVar) && $GLOBALS["clientcontact"]->DetailEdit) {
			if (!isset($GLOBALS["clientcontact_grid"]))
				$GLOBALS["clientcontact_grid"] = new clientcontact_grid(); // Get detail page object
			$GLOBALS["clientcontact_grid"]->validateGridForm();
		}
		if (in_array("clientpartners", $detailTblVar) && $GLOBALS["clientpartners"]->DetailEdit) {
			if (!isset($GLOBALS["clientpartners_grid"]))
				$GLOBALS["clientpartners_grid"] = new clientpartners_grid(); // Get detail page object
			$GLOBALS["clientpartners_grid"]->validateGridForm();
		}

		// Return validate result
		$validateForm = ($FormError == "");

		// Call Form_CustomValidate event
		$formCustomError = "";
		$validateForm = $validateForm && $this->Form_CustomValidate($formCustomError);
		if ($formCustomError <> "") {
			AddMessage($FormError, $formCustomError);
		}
		return $validateForm;
	}

	// Update record based on key values
	protected function editRow()
	{
		global $Security, $Language;
		$filter = $this->getRecordFilter();
		$filter = $this->applyUserIDFilters($filter);
		$conn = &$this->getConnection();
		$this->CurrentFilter = $filter;
		$sql = $this->getCurrentSql();
		$conn->raiseErrorFn = $GLOBALS["ERROR_FUNC"];
		$rs = $conn->execute($sql);
		$conn->raiseErrorFn = '';
		if ($rs === FALSE)
			return FALSE;
		if ($rs->EOF) {
			$this->setFailureMessage($Language->phrase("NoRecord")); // Set no record message
			$editRow = FALSE; // Update Failed
		} else {

			// Begin transaction
			if ($this->getCurrentDetailTable() <> "")
				$conn->beginTrans();

			// Save old values
			$rsold = &$rs->fields;
			$this->loadDbValues($rsold);
			$rsnew = [];

			// ClientTypeID
			$this->ClientTypeID->setDbValueDef($rsnew, $this->ClientTypeID->CurrentValue, 0, $this->ClientTypeID->ReadOnly);

			// ClientGroupID
			$this->ClientGroupID->setDbValueDef($rsnew, $this->ClientGroupID->CurrentValue, NULL, $this->ClientGroupID->ReadOnly);

			// TitleID
			$this->TitleID->setDbValueDef($rsnew, $this->TitleID->CurrentValue, NULL, $this->TitleID->ReadOnly);

			// FirstName
			$this->FirstName->setDbValueDef($rsnew, $this->FirstName->CurrentValue, NULL, $this->FirstName->ReadOnly);

			// MiddleName
			$this->MiddleName->setDbValueDef($rsnew, $this->MiddleName->CurrentValue, NULL, $this->MiddleName->ReadOnly);

			// LastName
			$this->LastName->setDbValueDef($rsnew, $this->LastName->CurrentValue, NULL, $this->LastName->ReadOnly);

			// PartnersName
			$this->PartnersName->setDbValueDef($rsnew, $this->PartnersName->CurrentValue, NULL, $this->PartnersName->ReadOnly);

			// CompanyName
			$this->CompanyName->setDbValueDef($rsnew, $this->CompanyName->CurrentValue, NULL, $this->CompanyName->ReadOnly);

			// ContactPerson
			$this->ContactPerson->setDbValueDef($rsnew, $this->ContactPerson->CurrentValue, NULL, $this->ContactPerson->ReadOnly);

			// WorkNature
			$this->WorkNature->setDbValueDef($rsnew, $this->WorkNature->CurrentValue, NULL, $this->WorkNature->ReadOnly);

			// JobTitle
			$this->JobTitle->setDbValueDef($rsnew, $this->JobTitle->CurrentValue, NULL, $this->JobTitle->ReadOnly);

			// Photo
			if ($this->Photo->Visible && !$this->Photo->ReadOnly && !$this->Photo->Upload->KeepFile) {
				$this->Photo->Upload->DbValue = $rsold['Photo']; // Get original value
				if ($this->Photo->Upload->FileName == "") {
					$rsnew['Photo'] = NULL;
				} else {
					$rsnew['Photo'] = $this->Photo->Upload->FileName;
				}
			}

			// BirthDate
			$this->BirthDate->setDbValueDef($rsnew, UnFormatDateTime($this->BirthDate->CurrentValue, 0), NULL, $this->BirthDate->ReadOnly);

			// Gender
			$this->Gender->setDbValueDef($rsnew, $this->Gender->CurrentValue, NULL, $this->Gender->ReadOnly);

			// Notes
			$this->Notes->setDbValueDef($rsnew, $this->Notes->CurrentValue, NULL, $this->Notes->ReadOnly);

			// NotesConv
			$this->NotesConv->setDbValueDef($rsnew, $this->NotesConv->CurrentValue, NULL, $this->NotesConv->ReadOnly);
			if ($this->Photo->Visible && !$this->Photo->Upload->KeepFile) {
				$oldFiles = EmptyValue($this->Photo->Upload->DbValue) ? array() : array($this->Photo->Upload->DbValue);
				if (!EmptyValue($this->Photo->Upload->FileName)) {
					$newFiles = array($this->Photo->Upload->FileName);
					$NewFileCount = count($newFiles);
					for ($i = 0; $i < $NewFileCount; $i++) {
						if ($newFiles[$i] <> "") {
							$file = $newFiles[$i];
							if (file_exists(UploadTempPath($this->Photo, $this->Photo->Upload->Index) . $file)) {
								if (DELETE_UPLOADED_FILES) {
									$oldFileFound = FALSE;
									$oldFileCount = count($oldFiles);
									for ($j = 0; $j < $oldFileCount; $j++) {
										$oldFile = $oldFiles[$j];
										if ($oldFile == $file) { // Old file found, no need to delete anymore
											unset($oldFiles[$j]);
											$oldFileFound = TRUE;
											break;
										}
									}
									if ($oldFileFound) // No need to check if file exists further
										continue;
								}
								$file1 = UniqueFilename($this->Photo->physicalUploadPath(), $file); // Get new file name
								if ($file1 <> $file) { // Rename temp file
									while (file_exists(UploadTempPath($this->Photo, $this->Photo->Upload->Index) . $file1) || file_exists($this->Photo->physicalUploadPath() . $file1)) // Make sure no file name clash
										$file1 = UniqueFilename($this->Photo->physicalUploadPath(), $file1, TRUE); // Use indexed name
									rename(UploadTempPath($this->Photo, $this->Photo->Upload->Index) . $file, UploadTempPath($this->Photo, $this->Photo->Upload->Index) . $file1);
									$newFiles[$i] = $file1;
								}
							}
						}
					}
					$this->Photo->Upload->DbValue = empty($oldFiles) ? "" : implode(MULTIPLE_UPLOAD_SEPARATOR, $oldFiles);
					$this->Photo->Upload->FileName = implode(MULTIPLE_UPLOAD_SEPARATOR, $newFiles);
					$this->Photo->setDbValueDef($rsnew, $this->Photo->Upload->FileName, NULL, $this->Photo->ReadOnly);
				}
			}

			// Call Row Updating event
			$updateRow = $this->Row_Updating($rsold, $rsnew);
			if ($updateRow) {
				$conn->raiseErrorFn = $GLOBALS["ERROR_FUNC"];
				if (count($rsnew) > 0)
					$editRow = $this->update($rsnew, "", $rsold);
				else
					$editRow = TRUE; // No field to update
				$conn->raiseErrorFn = '';
				if ($editRow) {
					if ($this->Photo->Visible && !$this->Photo->Upload->KeepFile) {
						$oldFiles = EmptyValue($this->Photo->Upload->DbValue) ? array() : array($this->Photo->Upload->DbValue);
						if (!EmptyValue($this->Photo->Upload->FileName)) {
							$newFiles = array($this->Photo->Upload->FileName);
							$newFiles2 = array($rsnew['Photo']);
							$newFileCount = count($newFiles);
							for ($i = 0; $i < $newFileCount; $i++) {
								if ($newFiles[$i] <> "") {
									$file = UploadTempPath($this->Photo, $this->Photo->Upload->Index) . $newFiles[$i];
									if (file_exists($file)) {
										if (@$newFiles2[$i] <> "") // Use correct file name
											$newFiles[$i] = $newFiles2[$i];
										if (!$this->Photo->Upload->saveToFile($newFiles[$i], TRUE, $i)) { // Just replace
											$this->setFailureMessage($Language->phrase("UploadErrMsg7"));
											return FALSE;
										}
									}
								}
							}
						} else {
							$newFiles = array();
						}
						if (DELETE_UPLOADED_FILES) {
							foreach ($oldFiles as $oldFile) {
								if ($oldFile <> "" && !in_array($oldFile, $newFiles))
									@unlink($this->Photo->oldPhysicalUploadPath() . $oldFile);
							}
						}
					}
				}

				// Update detail records
				$detailTblVar = explode(",", $this->getCurrentDetailTable());
				if ($editRow) {
					if (in_array("cases", $detailTblVar) && $GLOBALS["cases"]->DetailEdit) {
						if (!isset($GLOBALS["cases_grid"]))
							$GLOBALS["cases_grid"] = new cases_grid(); // Get detail page object
						$Security->loadCurrentUserLevel($this->ProjectID . "cases"); // Load user level of detail table
						$editRow = $GLOBALS["cases_grid"]->gridUpdate();
						$Security->loadCurrentUserLevel($this->ProjectID . $this->TableName); // Restore user level of master table
					}
				}
				if ($editRow) {
					if (in_array("clientadditinalinfo", $detailTblVar) && $GLOBALS["clientadditinalinfo"]->DetailEdit) {
						if (!isset($GLOBALS["clientadditinalinfo_grid"]))
							$GLOBALS["clientadditinalinfo_grid"] = new clientadditinalinfo_grid(); // Get detail page object
						$Security->loadCurrentUserLevel($this->ProjectID . "clientadditinalinfo"); // Load user level of detail table
						$editRow = $GLOBALS["clientadditinalinfo_grid"]->gridUpdate();
						$Security->loadCurrentUserLevel($this->ProjectID . $this->TableName); // Restore user level of master table
					}
				}
				if ($editRow) {
					if (in_array("clientaddress", $detailTblVar) && $GLOBALS["clientaddress"]->DetailEdit) {
						if (!isset($GLOBALS["clientaddress_grid"]))
							$GLOBALS["clientaddress_grid"] = new clientaddress_grid(); // Get detail page object
						$Security->loadCurrentUserLevel($this->ProjectID . "clientaddress"); // Load user level of detail table
						$editRow = $GLOBALS["clientaddress_grid"]->gridUpdate();
						$Security->loadCurrentUserLevel($this->ProjectID . $this->TableName); // Restore user level of master table
					}
				}
				if ($editRow) {
					if (in_array("clientcontact", $detailTblVar) && $GLOBALS["clientcontact"]->DetailEdit) {
						if (!isset($GLOBALS["clientcontact_grid"]))
							$GLOBALS["clientcontact_grid"] = new clientcontact_grid(); // Get detail page object
						$Security->loadCurrentUserLevel($this->ProjectID . "clientcontact"); // Load user level of detail table
						$editRow = $GLOBALS["clientcontact_grid"]->gridUpdate();
						$Security->loadCurrentUserLevel($this->ProjectID . $this->TableName); // Restore user level of master table
					}
				}
				if ($editRow) {
					if (in_array("clientpartners", $detailTblVar) && $GLOBALS["clientpartners"]->DetailEdit) {
						if (!isset($GLOBALS["clientpartners_grid"]))
							$GLOBALS["clientpartners_grid"] = new clientpartners_grid(); // Get detail page object
						$Security->loadCurrentUserLevel($this->ProjectID . "clientpartners"); // Load user level of detail table
						$editRow = $GLOBALS["clientpartners_grid"]->gridUpdate();
						$Security->loadCurrentUserLevel($this->ProjectID . $this->TableName); // Restore user level of master table
					}
				}

				// Commit/Rollback transaction
				if ($this->getCurrentDetailTable() <> "") {
					if ($editRow) {
						$conn->commitTrans(); // Commit transaction
					} else {
						$conn->rollbackTrans(); // Rollback transaction
					}
				}
			} else {
				if ($this->getSuccessMessage() <> "" || $this->getFailureMessage() <> "") {

					// Use the message, do nothing
				} elseif ($this->CancelMessage <> "") {
					$this->setFailureMessage($this->CancelMessage);
					$this->CancelMessage = "";
				} else {
					$this->setFailureMessage($Language->phrase("UpdateCancelled"));
				}
				$editRow = FALSE;
			}
		}

		// Call Row_Updated event
		if ($editRow)
			$this->Row_Updated($rsold, $rsnew);
		$rs->close();

		// Photo
		if ($this->Photo->Upload->FileToken <> "")
			CleanUploadTempPath($this->Photo->Upload->FileToken, $this->Photo->Upload->Index);
		else
			CleanUploadTempPath($this->Photo, $this->Photo->Upload->Index);

		// Write JSON for API request
		if (IsApi() && $editRow) {
			$row = $this->getRecordsFromRecordset([$rsnew], TRUE);
			WriteJson(["success" => TRUE, $this->TableVar => $row]);
		}
		return $editRow;
	}

	// Set up detail parms based on QueryString
	protected function setupDetailParms()
	{

		// Get the keys for master table
		if (Get(TABLE_SHOW_DETAIL) !== NULL) {
			$detailTblVar = Get(TABLE_SHOW_DETAIL);
			$this->setCurrentDetailTable($detailTblVar);
		} else {
			$detailTblVar = $this->getCurrentDetailTable();
		}
		if ($detailTblVar <> "") {
			$detailTblVar = explode(",", $detailTblVar);
			if (in_array("cases", $detailTblVar)) {
				if (!isset($GLOBALS["cases_grid"]))
					$GLOBALS["cases_grid"] = new cases_grid();
				if ($GLOBALS["cases_grid"]->DetailEdit) {
					$GLOBALS["cases_grid"]->CurrentMode = "edit";
					$GLOBALS["cases_grid"]->CurrentAction = "gridedit";

					// Save current master table to detail table
					$GLOBALS["cases_grid"]->setCurrentMasterTable($this->TableVar);
					$GLOBALS["cases_grid"]->setStartRecordNumber(1);
					$GLOBALS["cases_grid"]->ClientID->IsDetailKey = TRUE;
					$GLOBALS["cases_grid"]->ClientID->CurrentValue = $this->ClientID->CurrentValue;
					$GLOBALS["cases_grid"]->ClientID->setSessionValue($GLOBALS["cases_grid"]->ClientID->CurrentValue);
					$GLOBALS["cases_grid"]->LitigantID->setSessionValue(""); // Clear session key
				}
			}
			if (in_array("clientadditinalinfo", $detailTblVar)) {
				if (!isset($GLOBALS["clientadditinalinfo_grid"]))
					$GLOBALS["clientadditinalinfo_grid"] = new clientadditinalinfo_grid();
				if ($GLOBALS["clientadditinalinfo_grid"]->DetailEdit) {
					$GLOBALS["clientadditinalinfo_grid"]->CurrentMode = "edit";
					$GLOBALS["clientadditinalinfo_grid"]->CurrentAction = "gridedit";

					// Save current master table to detail table
					$GLOBALS["clientadditinalinfo_grid"]->setCurrentMasterTable($this->TableVar);
					$GLOBALS["clientadditinalinfo_grid"]->setStartRecordNumber(1);
					$GLOBALS["clientadditinalinfo_grid"]->ClientID->IsDetailKey = TRUE;
					$GLOBALS["clientadditinalinfo_grid"]->ClientID->CurrentValue = $this->ClientID->CurrentValue;
					$GLOBALS["clientadditinalinfo_grid"]->ClientID->setSessionValue($GLOBALS["clientadditinalinfo_grid"]->ClientID->CurrentValue);
				}
			}
			if (in_array("clientaddress", $detailTblVar)) {
				if (!isset($GLOBALS["clientaddress_grid"]))
					$GLOBALS["clientaddress_grid"] = new clientaddress_grid();
				if ($GLOBALS["clientaddress_grid"]->DetailEdit) {
					$GLOBALS["clientaddress_grid"]->CurrentMode = "edit";
					$GLOBALS["clientaddress_grid"]->CurrentAction = "gridedit";

					// Save current master table to detail table
					$GLOBALS["clientaddress_grid"]->setCurrentMasterTable($this->TableVar);
					$GLOBALS["clientaddress_grid"]->setStartRecordNumber(1);
					$GLOBALS["clientaddress_grid"]->ClientID->IsDetailKey = TRUE;
					$GLOBALS["clientaddress_grid"]->ClientID->CurrentValue = $this->ClientID->CurrentValue;
					$GLOBALS["clientaddress_grid"]->ClientID->setSessionValue($GLOBALS["clientaddress_grid"]->ClientID->CurrentValue);
				}
			}
			if (in_array("clientcontact", $detailTblVar)) {
				if (!isset($GLOBALS["clientcontact_grid"]))
					$GLOBALS["clientcontact_grid"] = new clientcontact_grid();
				if ($GLOBALS["clientcontact_grid"]->DetailEdit) {
					$GLOBALS["clientcontact_grid"]->CurrentMode = "edit";
					$GLOBALS["clientcontact_grid"]->CurrentAction = "gridedit";

					// Save current master table to detail table
					$GLOBALS["clientcontact_grid"]->setCurrentMasterTable($this->TableVar);
					$GLOBALS["clientcontact_grid"]->setStartRecordNumber(1);
					$GLOBALS["clientcontact_grid"]->ClientID->IsDetailKey = TRUE;
					$GLOBALS["clientcontact_grid"]->ClientID->CurrentValue = $this->ClientID->CurrentValue;
					$GLOBALS["clientcontact_grid"]->ClientID->setSessionValue($GLOBALS["clientcontact_grid"]->ClientID->CurrentValue);
				}
			}
			if (in_array("clientpartners", $detailTblVar)) {
				if (!isset($GLOBALS["clientpartners_grid"]))
					$GLOBALS["clientpartners_grid"] = new clientpartners_grid();
				if ($GLOBALS["clientpartners_grid"]->DetailEdit) {
					$GLOBALS["clientpartners_grid"]->CurrentMode = "edit";
					$GLOBALS["clientpartners_grid"]->CurrentAction = "gridedit";

					// Save current master table to detail table
					$GLOBALS["clientpartners_grid"]->setCurrentMasterTable($this->TableVar);
					$GLOBALS["clientpartners_grid"]->setStartRecordNumber(1);
					$GLOBALS["clientpartners_grid"]->ClientID->IsDetailKey = TRUE;
					$GLOBALS["clientpartners_grid"]->ClientID->CurrentValue = $this->ClientID->CurrentValue;
					$GLOBALS["clientpartners_grid"]->ClientID->setSessionValue($GLOBALS["clientpartners_grid"]->ClientID->CurrentValue);
				}
			}
		}
	}

	// Set up Breadcrumb
	protected function setupBreadcrumb()
	{
		global $Breadcrumb, $Language;
		$Breadcrumb = new Breadcrumb();
		$url = substr(CurrentUrl(), strrpos(CurrentUrl(), "/")+1);
		$Breadcrumb->add("list", $this->TableVar, $this->addMasterUrl("clientslist.php"), "", $this->TableVar, TRUE);
		$pageId = "edit";
		$Breadcrumb->add("edit", $pageId, $url);
	}

	// Set up detail pages
	protected function setupDetailPages()
	{
		$pages = new SubPages();
		$pages->Style = "tabs";
		$pages->add('cases');
		$pages->add('clientadditinalinfo');
		$pages->add('clientaddress');
		$pages->add('clientcontact');
		$pages->add('clientpartners');
		$this->DetailPages = $pages;
	}

	// Setup lookup options
	public function setupLookupOptions($fld)
	{
		if ($fld->Lookup !== NULL && $fld->Lookup->Options === NULL) {

			// No need to check any more
			$fld->Lookup->Options = [];

			// Set up lookup SQL
			switch ($fld->FieldVar) {
				default:
					$lookupFilter = "";
					break;
			}

			// Always call to Lookup->getSql so that user can setup Lookup->Options in Lookup_Selecting server event
			$sql = $fld->Lookup->getSql(FALSE, "", $lookupFilter, $this);

			// Set up lookup cache
			if ($fld->UseLookupCache && $sql <> "" && count($fld->Lookup->Options) == 0) {
				$conn = &$this->getConnection();
				$totalCnt = $this->getRecordCount($sql);
				if ($totalCnt > $fld->LookupCacheCount) // Total count > cache count, do not cache
					return;
				$rs = $conn->execute($sql);
				$ar = [];
				while ($rs && !$rs->EOF) {
					$row = &$rs->fields;

					// Format the field values
					switch ($fld->FieldVar) {
						case "x_ClientTypeID":
							break;
						case "x_ClientGroupID":
							break;
						case "x_TitleID":
							break;
					}
					$ar[strval($row[0])] = $row;
					$rs->moveNext();
				}
				if ($rs)
					$rs->close();
				$fld->Lookup->Options = $ar;
			}
		}
	}

	// Page Load event
	function Page_Load() {

		//echo "Page Load";
	}

	// Page Unload event
	function Page_Unload() {

		//echo "Page Unload";
	}

	// Page Redirecting event
	function Page_Redirecting(&$url) {

		// Example:
		//$url = "your URL";

	}

	// Message Showing event
	// $type = ''|'success'|'failure'|'warning'
	function Message_Showing(&$msg, $type) {
		if ($type == 'success') {

			//$msg = "your success message";
		} elseif ($type == 'failure') {

			//$msg = "your failure message";
		} elseif ($type == 'warning') {

			//$msg = "your warning message";
		} else {

			//$msg = "your message";
		}
	}

	// Page Render event
	function Page_Render() {

		//echo "Page Render";
	}

	// Page Data Rendering event
	function Page_DataRendering(&$header) {

		// Example:
		//$header = "your header";

	}

	// Page Data Rendered event
	function Page_DataRendered(&$footer) {

		// Example:
		//$footer = "your footer";

	}

	// Form Custom Validate event
	function Form_CustomValidate(&$customError) {

		// Return error message in CustomError
		return TRUE;
	}
}
?>
