<?php
namespace PHPMaker2019\project_germanos;

/**
 * Page class
 */
class attachments_grid extends attachments
{

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

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

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

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

	// Grid form hidden field names
	public $FormName = "fattachmentsgrid";
	public $FormActionName = "k_action";
	public $FormKeyName = "k_key";
	public $FormOldKeyName = "k_oldkey";
	public $FormBlankRowName = "k_blankrow";
	public $FormKeyCountName = "key_count";

	// Page URLs
	public $AddUrl;
	public $EditUrl;
	public $CopyUrl;
	public $DeleteUrl;
	public $ViewUrl;
	public $ListUrl;

	// 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
		$this->FormActionName .= "_" . $this->FormName;
		$this->FormKeyName .= "_" . $this->FormName;
		$this->FormOldKeyName .= "_" . $this->FormName;
		$this->FormBlankRowName .= "_" . $this->FormName;
		$this->FormKeyCountName .= "_" . $this->FormName;
		$GLOBALS["Grid"] = &$this;
		$this->TokenTimeout = SessionTimeoutTime();

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

		// Parent constuctor
		parent::__construct();

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

			// $GLOBALS["MasterTable"] = &$GLOBALS["Table"];
			// if (!isset($GLOBALS["Table"]))
			// 	$GLOBALS["Table"] = &$GLOBALS["attachments"];

		}
		$this->AddUrl = "attachmentsadd.php";

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

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

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

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

		// List options
		$this->ListOptions = new ListOptions();
		$this->ListOptions->TableVar = $this->TableVar;

		// Other options
		if (!$this->OtherOptions)
			$this->OtherOptions = new ListOptionsArray();
		$this->OtherOptions["addedit"] = new ListOptions();
		$this->OtherOptions["addedit"]->Tag = "div";
		$this->OtherOptions["addedit"]->TagClassName = "ew-add-edit-option";
	}

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

		// Export
		global $EXPORT, $attachments;
		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($attachments);
				$doc->Text = @$content;
				if ($this->isExport("email"))
					echo $this->exportEmail($doc->Text);
				else
					$doc->export();
				DeleteTempImages(); // Delete temp images
				exit();
			}
		}

//		$GLOBALS["Table"] = &$GLOBALS["MasterTable"];
		unset($GLOBALS["Grid"]);
		if ($url === "")
			return;
		if (!IsApi())
			$this->Page_Redirecting($url);

		// 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();
			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['AttachmentID'];
		}
		return $key;
	}

	/**
	 * Hide fields for add/edit
	 *
	 * @return void
	 */
	protected function hideFieldsForAddEdit()
	{
		if ($this->isAdd() || $this->isCopy() || $this->isGridAdd())
			$this->AttachmentID->Visible = FALSE;
	}

	// Class variables
	public $ListOptions; // List options
	public $ExportOptions; // Export options
	public $SearchOptions; // Search options
	public $OtherOptions; // Other options
	public $FilterOptions; // Filter options
	public $ImportOptions; // Import options
	public $ListActions; // List actions
	public $SelectedCount = 0;
	public $SelectedIndex = 0;
	public $ShowOtherOptions = FALSE;
	public $DisplayRecs = 10;
	public $StartRec;
	public $StopRec;
	public $TotalRecs = 0;
	public $RecRange = 10;
	public $Pager;
	public $AutoHidePager = AUTO_HIDE_PAGER;
	public $AutoHidePageSizeSelector = AUTO_HIDE_PAGE_SIZE_SELECTOR;
	public $DefaultSearchWhere = ""; // Default search WHERE clause
	public $SearchWhere = ""; // Search WHERE clause
	public $RecCnt = 0; // Record count
	public $EditRowCnt;
	public $StartRowCnt = 1;
	public $RowCnt = 0;
	public $Attrs = array(); // Row attributes and cell attributes
	public $RowIndex = 0; // Row index
	public $KeyCount = 0; // Key count
	public $RowAction = ""; // Row action
	public $RowOldKey = ""; // Row old key (for copy)
	public $MultiColumnClass = "col-sm";
	public $MultiColumnEditClass = "w-100";
	public $DbMasterFilter = ""; // Master filter
	public $DbDetailFilter = ""; // Detail filter
	public $MasterRecordExists;
	public $MultiSelectKey;
	public $Command;
	public $RestoreSearch = FALSE;
	public $DetailPages;
	public $OldRecordset;

	//
	// Page run
	//

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

		// 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();
		}

		// 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->canList()) {
				$Security->saveLastUrl();
				$this->setFailureMessage(DeniedMessage()); // Set no permission
				$this->terminate(GetUrl("index.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();
		}

		// Get grid add count
		$gridaddcnt = Get(TABLE_GRID_ADD_ROW_COUNT, "");
		if (is_numeric($gridaddcnt) && $gridaddcnt > 0)
			$this->GridAddRowCount = $gridaddcnt;

		// Set up list options
		$this->setupListOptions();
		$this->AttachmentID->setVisibility();
		$this->AttachmentSource_ID->setVisibility();
		$this->CaseID->setVisibility();
		$this->EmployeeID->setVisibility();
		$this->AttachID->setVisibility();
		$this->AttachFilename->setVisibility();
		$this->AttachFilenameInitial->setVisibility();
		$this->AttachExtension->setVisibility();
		$this->AttachDescription->setVisibility();
		$this->AttachNotes->Visible = FALSE;
		$this->AttachFilepath->setVisibility();
		$this->AttachPath->setVisibility();
		$this->Notes->Visible = FALSE;
		$this->_UserID->Visible = FALSE;
		$this->CreatedBy->Visible = FALSE;
		$this->CreatedDate->Visible = FALSE;
		$this->UpdatedBy->Visible = FALSE;
		$this->UpdatedDate->Visible = FALSE;
		$this->AddedBy->Visible = FALSE;
		$this->AddedDate->Visible = FALSE;
		$this->_Case->setVisibility();
		$this->hideFieldsForAddEdit();

		// 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 master detail parameters
		$this->setupMasterParms();

		// Setup other options
		$this->setupOtherOptions();

		// Set up lookup cache
		$this->setupLookupOptions($this->AttachmentSource_ID);

		// Search filters
		$srchAdvanced = ""; // Advanced search filter
		$srchBasic = ""; // Basic search filter
		$filter = "";

		// Get command
		$this->Command = strtolower(Get("cmd"));
		if ($this->isPageRequest()) { // Validate request

			// Set up records per page
			$this->setupDisplayRecs();

			// Handle reset command
			$this->resetCmd();

			// Hide list options
			if ($this->isExport()) {
				$this->ListOptions->hideAllOptions(array("sequence"));
				$this->ListOptions->UseDropDownButton = FALSE; // Disable drop down button
				$this->ListOptions->UseButtonGroup = FALSE; // Disable button group
			} elseif ($this->isGridAdd() || $this->isGridEdit()) {
				$this->ListOptions->hideAllOptions();
				$this->ListOptions->UseDropDownButton = FALSE; // Disable drop down button
				$this->ListOptions->UseButtonGroup = FALSE; // Disable button group
			}

			// Show grid delete link for grid add / grid edit
			if ($this->AllowAddDeleteRow) {
				if ($this->isGridAdd() || $this->isGridEdit()) {
					$item = &$this->ListOptions->getItem("griddelete");
					if ($item)
						$item->Visible = TRUE;
				}
			}

			// Set up sorting order
			$this->setupSortOrder();
		}

		// Restore display records
		if ($this->Command <> "json" && $this->getRecordsPerPage() <> "") {
			$this->DisplayRecs = $this->getRecordsPerPage(); // Restore from Session
		} else {
			$this->DisplayRecs = 10; // Load default
		}

		// Load Sorting Order
		if ($this->Command <> "json")
			$this->loadSortOrder();

		// Build filter
		$filter = "";
		if (!$Security->canList())
			$filter = "(0=1)"; // Filter all records

		// Restore master/detail filter
		$this->DbMasterFilter = $this->getMasterFilter(); // Restore master filter
		$this->DbDetailFilter = $this->getDetailFilter(); // Restore detail filter
		AddFilter($filter, $this->DbDetailFilter);
		AddFilter($filter, $this->SearchWhere);

		// Load master record
		if ($this->CurrentMode <> "add" && $this->getMasterFilter() <> "" && $this->getCurrentMasterTable() == "cases") {
			global $cases;
			$rsmaster = $cases->loadRs($this->DbMasterFilter);
			$this->MasterRecordExists = ($rsmaster && !$rsmaster->EOF);
			if (!$this->MasterRecordExists) {
				$this->setFailureMessage($Language->phrase("NoRecord")); // Set no record found
				$this->terminate("caseslist.php"); // Return to master page
			} else {
				$cases->loadListRowValues($rsmaster);
				$cases->RowType = ROWTYPE_MASTER; // Master row
				$cases->renderListRow();
				$rsmaster->close();
			}
		}

		// Set up filter
		if ($this->Command == "json") {
			$this->UseSessionForListSql = FALSE; // Do not use session for ListSQL
			$this->CurrentFilter = $filter;
		} else {
			$this->setSessionWhere($filter);
			$this->CurrentFilter = "";
		}
		if ($this->isGridAdd()) {
			if ($this->CurrentMode == "copy") {
				$selectLimit = $this->UseSelectLimit;
				if ($selectLimit) {
					$this->TotalRecs = $this->listRecordCount();
					$this->Recordset = $this->loadRecordset($this->StartRec - 1, $this->DisplayRecs);
				} else {
					if ($this->Recordset = $this->loadRecordset())
						$this->TotalRecs = $this->Recordset->RecordCount();
				}
				$this->StartRec = 1;
				$this->DisplayRecs = $this->TotalRecs;
			} else {
				$this->CurrentFilter = "0=1";
				$this->StartRec = 1;
				$this->DisplayRecs = $this->GridAddRowCount;
			}
			$this->TotalRecs = $this->DisplayRecs;
			$this->StopRec = $this->DisplayRecs;
		} else {
			$selectLimit = $this->UseSelectLimit;
			if ($selectLimit) {
				$this->TotalRecs = $this->listRecordCount();
			} else {
				if ($this->Recordset = $this->loadRecordset())
					$this->TotalRecs = $this->Recordset->RecordCount();
			}
			$this->StartRec = 1;
			$this->DisplayRecs = $this->TotalRecs; // Display all records
			if ($selectLimit)
				$this->Recordset = $this->loadRecordset($this->StartRec - 1, $this->DisplayRecs);

			// Set no record found message
			if (!$this->CurrentAction && $this->TotalRecs == 0) {
				if (!$Security->canList())
					$this->setWarningMessage(DeniedMessage());
				if ($this->SearchWhere == "0=101")
					$this->setWarningMessage($Language->phrase("EnterSearchCriteria"));
				else
					$this->setWarningMessage($Language->phrase("NoRecord"));
			}
		}

		// Normal return
		if (IsApi()) {
			$rows = $this->getRecordsFromRecordset($this->Recordset);
			$this->Recordset->close();
			WriteJson(["success" => TRUE, $this->TableVar => $rows, "totalRecordCount" => $this->TotalRecs]);
			$this->terminate(TRUE);
		}
	}

	// Set up number of records displayed per page
	protected function setupDisplayRecs()
	{
		$wrk = Get(TABLE_REC_PER_PAGE, "");
		if ($wrk <> "") {
			if (is_numeric($wrk)) {
				$this->DisplayRecs = (int)$wrk;
			} else {
				if (SameText($wrk, "all")) { // Display all records
					$this->DisplayRecs = -1;
				} else {
					$this->DisplayRecs = 10; // Non-numeric, load default
				}
			}
			$this->setRecordsPerPage($this->DisplayRecs); // Save to Session

			// Reset start position
			$this->StartRec = 1;
			$this->setStartRecordNumber($this->StartRec);
		}
	}

	// Exit inline mode
	protected function clearInlineMode()
	{
		$this->LastAction = $this->CurrentAction; // Save last action
		$this->CurrentAction = ""; // Clear action
		$_SESSION[SESSION_INLINE_MODE] = ""; // Clear inline mode
	}

	// Switch to Grid Add mode
	protected function gridAddMode()
	{
		$this->CurrentAction = "gridadd";
		$_SESSION[SESSION_INLINE_MODE] = "gridadd";
		$this->hideFieldsForAddEdit();
	}

	// Switch to Grid Edit mode
	protected function gridEditMode()
	{
		$this->CurrentAction = "gridedit";
		$_SESSION[SESSION_INLINE_MODE] = "gridedit";
		$this->hideFieldsForAddEdit();
	}

	// Perform update to grid
	public function gridUpdate()
	{
		global $Language, $CurrentForm, $FormError;
		$gridUpdate = TRUE;

		// Get old recordset
		$this->CurrentFilter = $this->buildKeyFilter();
		if ($this->CurrentFilter == "")
			$this->CurrentFilter = "0=1";
		$sql = $this->getCurrentSql();
		$conn = &$this->getConnection();
		if ($rs = $conn->execute($sql)) {
			$rsold = $rs->getRows();
			$rs->close();
		}

		// Call Grid Updating event
		if (!$this->Grid_Updating($rsold)) {
			if ($this->getFailureMessage() == "")
				$this->setFailureMessage($Language->phrase("GridEditCancelled")); // Set grid edit cancelled message
			return FALSE;
		}
		if ($this->AuditTrailOnEdit)
			$this->writeAuditTrailDummy($Language->phrase("BatchUpdateBegin")); // Batch update begin
		$key = "";

		// Update row index and get row key
		$CurrentForm->Index = -1;
		$rowcnt = strval($CurrentForm->getValue($this->FormKeyCountName));
		if ($rowcnt == "" || !is_numeric($rowcnt))
			$rowcnt = 0;

		// Update all rows based on key
		for ($rowindex = 1; $rowindex <= $rowcnt; $rowindex++) {
			$CurrentForm->Index = $rowindex;
			$rowkey = strval($CurrentForm->getValue($this->FormKeyName));
			$rowaction = strval($CurrentForm->getValue($this->FormActionName));

			// Load all values and keys
			if ($rowaction <> "insertdelete") { // Skip insert then deleted rows
				$this->loadFormValues(); // Get form values
				if ($rowaction == "" || $rowaction == "edit" || $rowaction == "delete") {
					$gridUpdate = $this->setupKeyValues($rowkey); // Set up key values
				} else {
					$gridUpdate = TRUE;
				}

				// Skip empty row
				if ($rowaction == "insert" && $this->emptyRow()) {

					// No action required
				// Validate form and insert/update/delete record

				} elseif ($gridUpdate) {
					if ($rowaction == "delete") {
						$this->CurrentFilter = $this->getRecordFilter();
						$gridUpdate = $this->deleteRows(); // Delete this row
					} else if (!$this->validateForm()) {
						$gridUpdate = FALSE; // Form error, reset action
						$this->setFailureMessage($FormError);
					} else {
						if ($rowaction == "insert") {
							$gridUpdate = $this->addRow(); // Insert this row
						} else {
							if ($rowkey <> "") {
								$this->SendEmail = FALSE; // Do not send email on update success
								$gridUpdate = $this->editRow(); // Update this row
							}
						} // End update
					}
				}
				if ($gridUpdate) {
					if ($key <> "")
						$key .= ", ";
					$key .= $rowkey;
				} else {
					break;
				}
			}
		}
		if ($gridUpdate) {

			// Get new recordset
			if ($rs = $conn->execute($sql)) {
				$rsnew = $rs->getRows();
				$rs->close();
			}

			// Call Grid_Updated event
			$this->Grid_Updated($rsold, $rsnew);
			if ($this->AuditTrailOnEdit)
				$this->writeAuditTrailDummy($Language->phrase("BatchUpdateSuccess")); // Batch update success
			$this->clearInlineMode(); // Clear inline edit mode
		} else {
			if ($this->AuditTrailOnEdit)
				$this->writeAuditTrailDummy($Language->phrase("BatchUpdateRollback")); // Batch update rollback
			if ($this->getFailureMessage() == "")
				$this->setFailureMessage($Language->phrase("UpdateFailed")); // Set update failed message
		}
		return $gridUpdate;
	}

	// Build filter for all keys
	protected function buildKeyFilter()
	{
		global $CurrentForm;
		$wrkFilter = "";

		// Update row index and get row key
		$rowindex = 1;
		$CurrentForm->Index = $rowindex;
		$thisKey = strval($CurrentForm->getValue($this->FormKeyName));
		while ($thisKey <> "") {
			if ($this->setupKeyValues($thisKey)) {
				$filter = $this->getRecordFilter();
				if ($wrkFilter <> "")
					$wrkFilter .= " OR ";
				$wrkFilter .= $filter;
			} else {
				$wrkFilter = "0=1";
				break;
			}

			// Update row index and get row key
			$rowindex++; // Next row
			$CurrentForm->Index = $rowindex;
			$thisKey = strval($CurrentForm->getValue($this->FormKeyName));
		}
		return $wrkFilter;
	}

	// Set up key values
	protected function setupKeyValues($key)
	{
		$arKeyFlds = explode($GLOBALS["COMPOSITE_KEY_SEPARATOR"], $key);
		if (count($arKeyFlds) >= 1) {
			$this->AttachmentID->setFormValue($arKeyFlds[0]);
			if (!is_numeric($this->AttachmentID->FormValue))
				return FALSE;
		}
		return TRUE;
	}

	// Perform Grid Add
	public function gridInsert()
	{
		global $Language, $CurrentForm, $FormError;
		$rowindex = 1;
		$gridInsert = FALSE;
		$conn = &$this->getConnection();

		// Call Grid Inserting event
		if (!$this->Grid_Inserting()) {
			if ($this->getFailureMessage() == "")
				$this->setFailureMessage($Language->phrase("GridAddCancelled")); // Set grid add cancelled message
			return FALSE;
		}

		// Init key filter
		$wrkfilter = "";
		$addcnt = 0;
		if ($this->AuditTrailOnAdd)
			$this->writeAuditTrailDummy($Language->phrase("BatchInsertBegin")); // Batch insert begin
		$key = "";

		// Get row count
		$CurrentForm->Index = -1;
		$rowcnt = strval($CurrentForm->getValue($this->FormKeyCountName));
		if ($rowcnt == "" || !is_numeric($rowcnt))
			$rowcnt = 0;

		// Insert all rows
		for ($rowindex = 1; $rowindex <= $rowcnt; $rowindex++) {

			// Load current row values
			$CurrentForm->Index = $rowindex;
			$rowaction = strval($CurrentForm->getValue($this->FormActionName));
			if ($rowaction <> "" && $rowaction <> "insert")
				continue; // Skip
			if ($rowaction == "insert") {
				$this->RowOldKey = strval($CurrentForm->getValue($this->FormOldKeyName));
				$this->loadOldRecord(); // Load old record
			}
			$this->loadFormValues(); // Get form values
			if (!$this->emptyRow()) {
				$addcnt++;
				$this->SendEmail = FALSE; // Do not send email on insert success

				// Validate form
				if (!$this->validateForm()) {
					$gridInsert = FALSE; // Form error, reset action
					$this->setFailureMessage($FormError);
				} else {
					$gridInsert = $this->addRow($this->OldRecordset); // Insert this row
				}
				if ($gridInsert) {
					if ($key <> "")
						$key .= $GLOBALS["COMPOSITE_KEY_SEPARATOR"];
					$key .= $this->AttachmentID->CurrentValue;

					// Add filter for this record
					$filter = $this->getRecordFilter();
					if ($wrkfilter <> "")
						$wrkfilter .= " OR ";
					$wrkfilter .= $filter;
				} else {
					break;
				}
			}
		}
		if ($addcnt == 0) { // No record inserted
			$this->clearInlineMode(); // Clear grid add mode and return
			return TRUE;
		}
		if ($gridInsert) {

			// Get new recordset
			$this->CurrentFilter = $wrkfilter;
			$sql = $this->getCurrentSql();
			if ($rs = $conn->execute($sql)) {
				$rsnew = $rs->getRows();
				$rs->close();
			}

			// Call Grid_Inserted event
			$this->Grid_Inserted($rsnew);
			if ($this->AuditTrailOnAdd)
				$this->writeAuditTrailDummy($Language->phrase("BatchInsertSuccess")); // Batch insert success
			$this->clearInlineMode(); // Clear grid add mode
		} else {
			if ($this->AuditTrailOnAdd)
				$this->writeAuditTrailDummy($Language->phrase("BatchInsertRollback")); // Batch insert rollback
			if ($this->getFailureMessage() == "")
				$this->setFailureMessage($Language->phrase("InsertFailed")); // Set insert failed message
		}
		return $gridInsert;
	}

	// Check if empty row
	public function emptyRow()
	{
		global $CurrentForm;
		if ($CurrentForm->hasValue("x_AttachmentSource_ID") && $CurrentForm->hasValue("o_AttachmentSource_ID") && $this->AttachmentSource_ID->CurrentValue <> $this->AttachmentSource_ID->OldValue)
			return FALSE;
		if ($CurrentForm->hasValue("x_CaseID") && $CurrentForm->hasValue("o_CaseID") && $this->CaseID->CurrentValue <> $this->CaseID->OldValue)
			return FALSE;
		if ($CurrentForm->hasValue("x_EmployeeID") && $CurrentForm->hasValue("o_EmployeeID") && $this->EmployeeID->CurrentValue <> $this->EmployeeID->OldValue)
			return FALSE;
		if ($CurrentForm->hasValue("x_AttachID") && $CurrentForm->hasValue("o_AttachID") && $this->AttachID->CurrentValue <> $this->AttachID->OldValue)
			return FALSE;
		if (!EmptyValue($this->AttachFilename->Upload->Value))
			return FALSE;
		if ($CurrentForm->hasValue("x_AttachFilenameInitial") && $CurrentForm->hasValue("o_AttachFilenameInitial") && $this->AttachFilenameInitial->CurrentValue <> $this->AttachFilenameInitial->OldValue)
			return FALSE;
		if ($CurrentForm->hasValue("x_AttachExtension") && $CurrentForm->hasValue("o_AttachExtension") && $this->AttachExtension->CurrentValue <> $this->AttachExtension->OldValue)
			return FALSE;
		if ($CurrentForm->hasValue("x_AttachDescription") && $CurrentForm->hasValue("o_AttachDescription") && $this->AttachDescription->CurrentValue <> $this->AttachDescription->OldValue)
			return FALSE;
		if ($CurrentForm->hasValue("x_AttachFilepath") && $CurrentForm->hasValue("o_AttachFilepath") && $this->AttachFilepath->CurrentValue <> $this->AttachFilepath->OldValue)
			return FALSE;
		if ($CurrentForm->hasValue("x_AttachPath") && $CurrentForm->hasValue("o_AttachPath") && $this->AttachPath->CurrentValue <> $this->AttachPath->OldValue)
			return FALSE;
		if ($CurrentForm->hasValue("x__Case") && $CurrentForm->hasValue("o__Case") && $this->_Case->CurrentValue <> $this->_Case->OldValue)
			return FALSE;
		return TRUE;
	}

	// Validate grid form
	public function validateGridForm()
	{
		global $CurrentForm;

		// Get row count
		$CurrentForm->Index = -1;
		$rowcnt = strval($CurrentForm->getValue($this->FormKeyCountName));
		if ($rowcnt == "" || !is_numeric($rowcnt))
			$rowcnt = 0;

		// Validate all records
		for ($rowindex = 1; $rowindex <= $rowcnt; $rowindex++) {

			// Load current row values
			$CurrentForm->Index = $rowindex;
			$rowaction = strval($CurrentForm->getValue($this->FormActionName));
			if ($rowaction <> "delete" && $rowaction <> "insertdelete") {
				$this->loadFormValues(); // Get form values
				if ($rowaction == "insert" && $this->emptyRow()) {

					// Ignore
				} else if (!$this->validateForm()) {
					return FALSE;
				}
			}
		}
		return TRUE;
	}

	// Get all form values of the grid
	public function getGridFormValues()
	{
		global $CurrentForm;

		// Get row count
		$CurrentForm->Index = -1;
		$rowcnt = strval($CurrentForm->getValue($this->FormKeyCountName));
		if ($rowcnt == "" || !is_numeric($rowcnt))
			$rowcnt = 0;
		$rows = array();

		// Loop through all records
		for ($rowindex = 1; $rowindex <= $rowcnt; $rowindex++) {

			// Load current row values
			$CurrentForm->Index = $rowindex;
			$rowaction = strval($CurrentForm->getValue($this->FormActionName));
			if ($rowaction <> "delete" && $rowaction <> "insertdelete") {
				$this->loadFormValues(); // Get form values
				if ($rowaction == "insert" && $this->emptyRow()) {

					// Ignore
				} else {
					$rows[] = $this->getFieldValues("FormValue"); // Return row as array
				}
			}
		}
		return $rows; // Return as array of array
	}

	// Restore form values for current row
	public function restoreCurrentRowFormValues($idx)
	{
		global $CurrentForm;

		// Get row based on current index
		$CurrentForm->Index = $idx;
		$this->loadFormValues(); // Load form values
	}

	// Set up sort parameters
	protected function setupSortOrder()
	{

		// Check for "order" parameter
		if (Get("order") !== NULL) {
			$this->CurrentOrder = Get("order");
			$this->CurrentOrderType = Get("ordertype", "");
			$this->setStartRecordNumber(1); // Reset start position
		}
	}

	// Load sort order parameters
	protected function loadSortOrder()
	{
		$orderBy = $this->getSessionOrderBy(); // Get ORDER BY from Session
		if ($orderBy == "") {
			if ($this->getSqlOrderBy() <> "") {
				$orderBy = $this->getSqlOrderBy();
				$this->setSessionOrderBy($orderBy);
			}
		}
	}

	// Reset command
	// - cmd=reset (Reset search parameters)
	// - cmd=resetall (Reset search and master/detail parameters)
	// - cmd=resetsort (Reset sort parameters)

	protected function resetCmd()
	{

		// Check if reset command
		if (substr($this->Command,0,5) == "reset") {

			// Reset master/detail keys
			if ($this->Command == "resetall") {
				$this->setCurrentMasterTable(""); // Clear master table
				$this->DbMasterFilter = "";
				$this->DbDetailFilter = "";
				$this->CaseID->setSessionValue("");
			}

			// Reset sorting order
			if ($this->Command == "resetsort") {
				$orderBy = "";
				$this->setSessionOrderBy($orderBy);
			}

			// Reset start position
			$this->StartRec = 1;
			$this->setStartRecordNumber($this->StartRec);
		}
	}

	// Set up list options
	protected function setupListOptions()
	{
		global $Security, $Language;

		// "griddelete"
		if ($this->AllowAddDeleteRow) {
			$item = &$this->ListOptions->add("griddelete");
			$item->CssClass = "text-nowrap";
			$item->OnLeft = TRUE;
			$item->Visible = FALSE; // Default hidden
		}

		// Add group option item
		$item = &$this->ListOptions->add($this->ListOptions->GroupOptionName);
		$item->Body = "";
		$item->OnLeft = TRUE;
		$item->Visible = FALSE;

		// "view"
		$item = &$this->ListOptions->add("view");
		$item->CssClass = "text-nowrap";
		$item->Visible = $Security->canView();
		$item->OnLeft = TRUE;

		// "edit"
		$item = &$this->ListOptions->add("edit");
		$item->CssClass = "text-nowrap";
		$item->Visible = $Security->canEdit();
		$item->OnLeft = TRUE;

		// "copy"
		$item = &$this->ListOptions->add("copy");
		$item->CssClass = "text-nowrap";
		$item->Visible = $Security->canAdd();
		$item->OnLeft = TRUE;

		// "delete"
		$item = &$this->ListOptions->add("delete");
		$item->CssClass = "text-nowrap";
		$item->Visible = $Security->canDelete();
		$item->OnLeft = TRUE;

		// Drop down button for ListOptions
		$this->ListOptions->UseDropDownButton = FALSE;
		$this->ListOptions->DropDownButtonPhrase = $Language->phrase("ButtonListOptions");
		$this->ListOptions->UseButtonGroup = FALSE;
		if ($this->ListOptions->UseButtonGroup && IsMobile())
			$this->ListOptions->UseDropDownButton = TRUE;

		//$this->ListOptions->ButtonClass = ""; // Class for button group
		// Call ListOptions_Load event

		$this->ListOptions_Load();
		$item = &$this->ListOptions->getItem($this->ListOptions->GroupOptionName);
		$item->Visible = $this->ListOptions->groupOptionVisible();
	}

	// Render list options
	public function renderListOptions()
	{
		global $Security, $Language, $CurrentForm;
		$this->ListOptions->loadDefault();

		// Call ListOptions_Rendering event
		$this->ListOptions_Rendering();

		// Set up row action and key
		if (is_numeric($this->RowIndex) && $this->CurrentMode <> "view") {
			$CurrentForm->Index = $this->RowIndex;
			$actionName = str_replace("k_", "k" . $this->RowIndex . "_", $this->FormActionName);
			$oldKeyName = str_replace("k_", "k" . $this->RowIndex . "_", $this->FormOldKeyName);
			$keyName = str_replace("k_", "k" . $this->RowIndex . "_", $this->FormKeyName);
			$blankRowName = str_replace("k_", "k" . $this->RowIndex . "_", $this->FormBlankRowName);
			if ($this->RowAction <> "")
				$this->MultiSelectKey .= "<input type=\"hidden\" name=\"" . $actionName . "\" id=\"" . $actionName . "\" value=\"" . $this->RowAction . "\">";
			if ($CurrentForm->hasValue($this->FormOldKeyName))
				$this->RowOldKey = strval($CurrentForm->getValue($this->FormOldKeyName));
			if ($this->RowOldKey <> "")
				$this->MultiSelectKey .= "<input type=\"hidden\" name=\"" . $oldKeyName . "\" id=\"" . $oldKeyName . "\" value=\"" . HtmlEncode($this->RowOldKey) . "\">";
			if ($this->RowAction == "delete") {
				$rowkey = $CurrentForm->getValue($this->FormKeyName);
				$this->setupKeyValues($rowkey);
			}
			if ($this->RowAction == "insert" && $this->isConfirm() && $this->emptyRow())
				$this->MultiSelectKey .= "<input type=\"hidden\" name=\"" . $blankRowName . "\" id=\"" . $blankRowName . "\" value=\"1\">";
		}

		// "delete"
		if ($this->AllowAddDeleteRow) {
			if ($this->CurrentMode == "add" || $this->CurrentMode == "copy" || $this->CurrentMode == "edit") {
				$options = &$this->ListOptions;
				$options->UseButtonGroup = TRUE; // Use button group for grid delete button
				$opt = &$options->Items["griddelete"];
				if (!$Security->canDelete() && is_numeric($this->RowIndex) && ($this->RowAction == "" || $this->RowAction == "edit")) { // Do not allow delete existing record
					$opt->Body = "&nbsp;";
				} else {
					$opt->Body = "<a class=\"ew-grid-link ew-grid-delete\" title=\"" . HtmlTitle($Language->phrase("DeleteLink")) . "\" data-caption=\"" . HtmlTitle($Language->phrase("DeleteLink")) . "\" onclick=\"return ew.deleteGridRow(this, " . $this->RowIndex . ");\">" . $Language->phrase("DeleteLink") . "</a>";
				}
			}
		}
		if ($this->CurrentMode == "view") { // View mode

		// "view"
		$opt = &$this->ListOptions->Items["view"];
		$viewcaption = HtmlTitle($Language->phrase("ViewLink"));
		if ($Security->canView()) {
			$opt->Body = "<a class=\"ew-row-link ew-view\" title=\"" . $viewcaption . "\" data-caption=\"" . $viewcaption . "\" href=\"" . HtmlEncode($this->ViewUrl) . "\">" . $Language->phrase("ViewLink") . "</a>";
		} else {
			$opt->Body = "";
		}

		// "edit"
		$opt = &$this->ListOptions->Items["edit"];
		$editcaption = HtmlTitle($Language->phrase("EditLink"));
		if ($Security->canEdit()) {
			$opt->Body = "<a class=\"ew-row-link ew-edit\" title=\"" . HtmlTitle($Language->phrase("EditLink")) . "\" data-caption=\"" . HtmlTitle($Language->phrase("EditLink")) . "\" href=\"" . HtmlEncode($this->EditUrl) . "\">" . $Language->phrase("EditLink") . "</a>";
		} else {
			$opt->Body = "";
		}

		// "copy"
		$opt = &$this->ListOptions->Items["copy"];
		$copycaption = HtmlTitle($Language->phrase("CopyLink"));
		if ($Security->canAdd()) {
			$opt->Body = "<a class=\"ew-row-link ew-copy\" title=\"" . $copycaption . "\" data-caption=\"" . $copycaption . "\" href=\"" . HtmlEncode($this->CopyUrl) . "\">" . $Language->phrase("CopyLink") . "</a>";
		} else {
			$opt->Body = "";
		}

		// "delete"
		$opt = &$this->ListOptions->Items["delete"];
		if ($Security->canDelete())
			$opt->Body = "<a class=\"ew-row-link ew-delete\"" . "" . " title=\"" . HtmlTitle($Language->phrase("DeleteLink")) . "\" data-caption=\"" . HtmlTitle($Language->phrase("DeleteLink")) . "\" href=\"" . HtmlEncode($this->DeleteUrl) . "\">" . $Language->phrase("DeleteLink") . "</a>";
		else
			$opt->Body = "";
		} // End View mode
		if ($this->CurrentMode == "edit" && is_numeric($this->RowIndex)) {
			$this->MultiSelectKey .= "<input type=\"hidden\" name=\"" . $keyName . "\" id=\"" . $keyName . "\" value=\"" . $this->AttachmentID->CurrentValue . "\">";
		}
		$this->renderListOptionsExt();

		// Call ListOptions_Rendered event
		$this->ListOptions_Rendered();
	}

	// Set record key
	public function setRecordKey(&$key, $rs)
	{
		$key = "";
		if ($key <> "")
			$key .= $GLOBALS["COMPOSITE_KEY_SEPARATOR"];
		$key .= $rs->fields('AttachmentID');
	}

	// Set up other options
	protected function setupOtherOptions()
	{
		global $Language, $Security;
		$option = &$this->OtherOptions["addedit"];
		$option->UseDropDownButton = FALSE;
		$option->DropDownButtonPhrase = $Language->phrase("ButtonAddEdit");
		$option->UseButtonGroup = TRUE;

		//$option->ButtonClass = ""; // Class for button group
		$item = &$option->add($option->GroupOptionName);
		$item->Body = "";
		$item->Visible = FALSE;

		// Add
		if ($this->CurrentMode == "view") { // Check view mode
			$item = &$option->add("add");
			$addcaption = HtmlTitle($Language->phrase("AddLink"));
			$this->AddUrl = $this->getAddUrl();
			$item->Body = "<a class=\"ew-add-edit ew-add\" title=\"" . $addcaption . "\" data-caption=\"" . $addcaption . "\" href=\"" . HtmlEncode($this->AddUrl) . "\">" . $Language->phrase("AddLink") . "</a>";
			$item->Visible = ($this->AddUrl <> "" && $Security->canAdd());
		}
	}

	// Render other options
	public function renderOtherOptions()
	{
		global $Language, $Security;
		$options = &$this->OtherOptions;
		if (($this->CurrentMode == "add" || $this->CurrentMode == "copy" || $this->CurrentMode == "edit") && !$this->isConfirm()) { // Check add/copy/edit mode
			if ($this->AllowAddDeleteRow) {
				$option = &$options["addedit"];
				$option->UseDropDownButton = FALSE;
				$item = &$option->add("addblankrow");
				$item->Body = "<a class=\"ew-add-edit ew-add-blank-row\" title=\"" . HtmlTitle($Language->phrase("AddBlankRow")) . "\" data-caption=\"" . HtmlTitle($Language->phrase("AddBlankRow")) . "\" href=\"javascript:void(0);\" onclick=\"ew.addGridRow(this);\">" . $Language->phrase("AddBlankRow") . "</a>";
				$item->Visible = $Security->canAdd();
				$this->ShowOtherOptions = $item->Visible;
			}
		}
		if ($this->CurrentMode == "view") { // Check view mode
			$option = &$options["addedit"];
			$item = &$option->getItem("add");
			$this->ShowOtherOptions = $item && $item->Visible;
		}
	}
	protected function renderListOptionsExt()
	{
		global $Security, $Language;
	}

	// 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->AttachFilename->Upload->Index = $CurrentForm->Index;
		$this->AttachFilename->Upload->uploadFile();
		$this->AttachFilename->CurrentValue = $this->AttachFilename->Upload->FileName;
	}

	// Load default values
	protected function loadDefaultValues()
	{
		$this->AttachmentID->CurrentValue = NULL;
		$this->AttachmentID->OldValue = $this->AttachmentID->CurrentValue;
		$this->AttachmentSource_ID->CurrentValue = 1;
		$this->AttachmentSource_ID->OldValue = $this->AttachmentSource_ID->CurrentValue;
		$this->CaseID->CurrentValue = NULL;
		$this->CaseID->OldValue = $this->CaseID->CurrentValue;
		$this->EmployeeID->CurrentValue = NULL;
		$this->EmployeeID->OldValue = $this->EmployeeID->CurrentValue;
		$this->AttachID->CurrentValue = NULL;
		$this->AttachID->OldValue = $this->AttachID->CurrentValue;
		$this->AttachFilename->Upload->DbValue = NULL;
		$this->AttachFilename->OldValue = $this->AttachFilename->Upload->DbValue;
		$this->AttachFilename->Upload->Index = $this->RowIndex;
		$this->AttachFilenameInitial->CurrentValue = NULL;
		$this->AttachFilenameInitial->OldValue = $this->AttachFilenameInitial->CurrentValue;
		$this->AttachExtension->CurrentValue = NULL;
		$this->AttachExtension->OldValue = $this->AttachExtension->CurrentValue;
		$this->AttachDescription->CurrentValue = NULL;
		$this->AttachDescription->OldValue = $this->AttachDescription->CurrentValue;
		$this->AttachNotes->CurrentValue = NULL;
		$this->AttachNotes->OldValue = $this->AttachNotes->CurrentValue;
		$this->AttachFilepath->CurrentValue = NULL;
		$this->AttachFilepath->OldValue = $this->AttachFilepath->CurrentValue;
		$this->AttachPath->CurrentValue = NULL;
		$this->AttachPath->OldValue = $this->AttachPath->CurrentValue;
		$this->Notes->CurrentValue = NULL;
		$this->Notes->OldValue = $this->Notes->CurrentValue;
		$this->_UserID->CurrentValue = NULL;
		$this->_UserID->OldValue = $this->_UserID->CurrentValue;
		$this->CreatedBy->CurrentValue = NULL;
		$this->CreatedBy->OldValue = $this->CreatedBy->CurrentValue;
		$this->CreatedDate->CurrentValue = NULL;
		$this->CreatedDate->OldValue = $this->CreatedDate->CurrentValue;
		$this->UpdatedBy->CurrentValue = NULL;
		$this->UpdatedBy->OldValue = $this->UpdatedBy->CurrentValue;
		$this->UpdatedDate->CurrentValue = NULL;
		$this->UpdatedDate->OldValue = $this->UpdatedDate->CurrentValue;
		$this->AddedBy->CurrentValue = NULL;
		$this->AddedBy->OldValue = $this->AddedBy->CurrentValue;
		$this->AddedDate->CurrentValue = NULL;
		$this->AddedDate->OldValue = $this->AddedDate->CurrentValue;
		$this->_Case->CurrentValue = NULL;
		$this->_Case->OldValue = $this->_Case->CurrentValue;
	}

	// Load form values
	protected function loadFormValues()
	{

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

		// Check field name 'AttachmentID' first before field var 'x_AttachmentID'
		$val = $CurrentForm->hasValue("AttachmentID") ? $CurrentForm->getValue("AttachmentID") : $CurrentForm->getValue("x_AttachmentID");
		if (!$this->AttachmentID->IsDetailKey && !$this->isGridAdd() && !$this->isAdd())
			$this->AttachmentID->setFormValue($val);

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

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

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

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

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

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

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

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

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

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

	// Restore form values
	public function restoreFormValues()
	{
		global $CurrentForm;
		if (!$this->isGridAdd() && !$this->isAdd())
			$this->AttachmentID->CurrentValue = $this->AttachmentID->FormValue;
		$this->AttachmentSource_ID->CurrentValue = $this->AttachmentSource_ID->FormValue;
		$this->CaseID->CurrentValue = $this->CaseID->FormValue;
		$this->EmployeeID->CurrentValue = $this->EmployeeID->FormValue;
		$this->AttachID->CurrentValue = $this->AttachID->FormValue;
		$this->AttachFilenameInitial->CurrentValue = $this->AttachFilenameInitial->FormValue;
		$this->AttachExtension->CurrentValue = $this->AttachExtension->FormValue;
		$this->AttachDescription->CurrentValue = $this->AttachDescription->FormValue;
		$this->AttachFilepath->CurrentValue = $this->AttachFilepath->FormValue;
		$this->AttachPath->CurrentValue = $this->AttachPath->FormValue;
		$this->_Case->CurrentValue = $this->_Case->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->getSessionOrderBy())]);
			} 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->AttachmentID->setDbValue($row['AttachmentID']);
		$this->AttachmentSource_ID->setDbValue($row['AttachmentSource_ID']);
		$this->CaseID->setDbValue($row['CaseID']);
		$this->EmployeeID->setDbValue($row['EmployeeID']);
		$this->AttachID->setDbValue($row['AttachID']);
		$this->AttachFilename->Upload->DbValue = $row['AttachFilename'];
		$this->AttachFilename->setDbValue($this->AttachFilename->Upload->DbValue);
		$this->AttachFilename->Upload->Index = $this->RowIndex;
		$this->AttachFilenameInitial->setDbValue($row['AttachFilenameInitial']);
		$this->AttachExtension->setDbValue($row['AttachExtension']);
		$this->AttachDescription->setDbValue($row['AttachDescription']);
		$this->AttachNotes->setDbValue($row['AttachNotes']);
		$this->AttachFilepath->setDbValue($row['AttachFilepath']);
		$this->AttachPath->setDbValue($row['AttachPath']);
		$this->Notes->setDbValue($row['Notes']);
		$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->AddedBy->setDbValue($row['AddedBy']);
		$this->AddedDate->setDbValue($row['AddedDate']);
		$this->_Case->setDbValue($row['Case']);
	}

	// Return a row with default values
	protected function newRow()
	{
		$this->loadDefaultValues();
		$row = [];
		$row['AttachmentID'] = $this->AttachmentID->CurrentValue;
		$row['AttachmentSource_ID'] = $this->AttachmentSource_ID->CurrentValue;
		$row['CaseID'] = $this->CaseID->CurrentValue;
		$row['EmployeeID'] = $this->EmployeeID->CurrentValue;
		$row['AttachID'] = $this->AttachID->CurrentValue;
		$row['AttachFilename'] = $this->AttachFilename->Upload->DbValue;
		$row['AttachFilenameInitial'] = $this->AttachFilenameInitial->CurrentValue;
		$row['AttachExtension'] = $this->AttachExtension->CurrentValue;
		$row['AttachDescription'] = $this->AttachDescription->CurrentValue;
		$row['AttachNotes'] = $this->AttachNotes->CurrentValue;
		$row['AttachFilepath'] = $this->AttachFilepath->CurrentValue;
		$row['AttachPath'] = $this->AttachPath->CurrentValue;
		$row['Notes'] = $this->Notes->CurrentValue;
		$row['UserID'] = $this->_UserID->CurrentValue;
		$row['CreatedBy'] = $this->CreatedBy->CurrentValue;
		$row['CreatedDate'] = $this->CreatedDate->CurrentValue;
		$row['UpdatedBy'] = $this->UpdatedBy->CurrentValue;
		$row['UpdatedDate'] = $this->UpdatedDate->CurrentValue;
		$row['AddedBy'] = $this->AddedBy->CurrentValue;
		$row['AddedDate'] = $this->AddedDate->CurrentValue;
		$row['Case'] = $this->_Case->CurrentValue;
		return $row;
	}

	// Load old record
	protected function loadOldRecord()
	{

		// Load key values from Session
		$validKey = TRUE;
		$arKeys[] = $this->RowOldKey;
		$cnt = count($arKeys);
		if ($cnt >= 1) {
			if (strval($arKeys[0]) <> "")
				$this->AttachmentID->CurrentValue = strval($arKeys[0]); // AttachmentID
			else
				$validKey = FALSE;
		} 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
		$this->ViewUrl = $this->getViewUrl();
		$this->EditUrl = $this->getEditUrl();
		$this->CopyUrl = $this->getCopyUrl();
		$this->DeleteUrl = $this->getDeleteUrl();

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

		// Common render codes for all row types
		// AttachmentID
		// AttachmentSource_ID
		// CaseID
		// EmployeeID
		// AttachID
		// AttachFilename
		// AttachFilenameInitial
		// AttachExtension
		// AttachDescription
		// AttachNotes
		// AttachFilepath
		// AttachPath
		// Notes
		// 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;";

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

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

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

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

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

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

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

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

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

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

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

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

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

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

			// Case
			$this->_Case->ViewValue = $this->_Case->CurrentValue;
			$this->_Case->ViewCustomAttributes = "";

			// AttachmentID
			$this->AttachmentID->LinkCustomAttributes = "";
			$this->AttachmentID->HrefValue = "";
			$this->AttachmentID->TooltipValue = "";
			if (!$this->isExport())
				$this->AttachmentID->ViewValue = $this->highlightValue($this->AttachmentID);

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

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

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

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

			// AttachFilename
			$this->AttachFilename->LinkCustomAttributes = "";
			$this->AttachFilename->HrefValue = "";
			$this->AttachFilename->ExportHrefValue = $this->AttachFilename->UploadPath . $this->AttachFilename->Upload->DbValue;
			$this->AttachFilename->TooltipValue = "";

			// AttachFilenameInitial
			$this->AttachFilenameInitial->LinkCustomAttributes = "";
			$this->AttachFilenameInitial->HrefValue = "";
			$this->AttachFilenameInitial->TooltipValue = "";
			if (!$this->isExport())
				$this->AttachFilenameInitial->ViewValue = $this->highlightValue($this->AttachFilenameInitial);

			// AttachExtension
			$this->AttachExtension->LinkCustomAttributes = "";
			$this->AttachExtension->HrefValue = "";
			$this->AttachExtension->TooltipValue = "";
			if (!$this->isExport())
				$this->AttachExtension->ViewValue = $this->highlightValue($this->AttachExtension);

			// AttachDescription
			$this->AttachDescription->LinkCustomAttributes = "";
			$this->AttachDescription->HrefValue = "";
			$this->AttachDescription->TooltipValue = "";
			if (!$this->isExport())
				$this->AttachDescription->ViewValue = $this->highlightValue($this->AttachDescription);

			// AttachFilepath
			$this->AttachFilepath->LinkCustomAttributes = "";
			$this->AttachFilepath->HrefValue = "";
			$this->AttachFilepath->TooltipValue = "";
			if (!$this->isExport())
				$this->AttachFilepath->ViewValue = $this->highlightValue($this->AttachFilepath);

			// AttachPath
			$this->AttachPath->LinkCustomAttributes = "";
			$this->AttachPath->HrefValue = "";
			$this->AttachPath->TooltipValue = "";
			if (!$this->isExport())
				$this->AttachPath->ViewValue = $this->highlightValue($this->AttachPath);

			// Case
			$this->_Case->LinkCustomAttributes = "";
			$this->_Case->HrefValue = "";
			$this->_Case->TooltipValue = "";
			if (!$this->isExport())
				$this->_Case->ViewValue = $this->highlightValue($this->_Case);
		} elseif ($this->RowType == ROWTYPE_ADD) { // Add row

			// AttachmentID
			// AttachmentSource_ID

			$this->AttachmentSource_ID->EditAttrs["class"] = "form-control";
			$this->AttachmentSource_ID->EditCustomAttributes = "";
			$this->AttachmentSource_ID->EditValue = HtmlEncode($this->AttachmentSource_ID->CurrentValue);
			$curVal = strval($this->AttachmentSource_ID->CurrentValue);
			if ($curVal <> "") {
				$this->AttachmentSource_ID->EditValue = $this->AttachmentSource_ID->lookupCacheOption($curVal);
				if ($this->AttachmentSource_ID->EditValue === NULL) { // Lookup from database
					$filterWrk = "`AttachmentSource_ID`" . SearchString("=", $curVal, DATATYPE_NUMBER, "");
					$sqlWrk = $this->AttachmentSource_ID->Lookup->getSql(FALSE, $filterWrk, '', $this);
					$rswrk = Conn()->execute($sqlWrk);
					if ($rswrk && !$rswrk->EOF) { // Lookup values found
						$arwrk = array();
						$arwrk[1] = HtmlEncode($rswrk->fields('df'));
						$this->AttachmentSource_ID->EditValue = $this->AttachmentSource_ID->displayValue($arwrk);
						$rswrk->Close();
					} else {
						$this->AttachmentSource_ID->EditValue = HtmlEncode($this->AttachmentSource_ID->CurrentValue);
					}
				}
			} else {
				$this->AttachmentSource_ID->EditValue = NULL;
			}
			$this->AttachmentSource_ID->PlaceHolder = RemoveHtml($this->AttachmentSource_ID->caption());

			// CaseID
			$this->CaseID->EditAttrs["class"] = "form-control";
			$this->CaseID->EditCustomAttributes = "";
			if ($this->CaseID->getSessionValue() <> "") {
				$this->CaseID->CurrentValue = $this->CaseID->getSessionValue();
				$this->CaseID->OldValue = $this->CaseID->CurrentValue;
			$this->CaseID->ViewValue = $this->CaseID->CurrentValue;
			$this->CaseID->ViewValue = FormatNumber($this->CaseID->ViewValue, 0, -2, -2, -2);
			$this->CaseID->ViewCustomAttributes = "";
			} else {
			$this->CaseID->EditValue = HtmlEncode($this->CaseID->CurrentValue);
			$this->CaseID->PlaceHolder = RemoveHtml($this->CaseID->caption());
			}

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

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

			// AttachFilename
			$this->AttachFilename->EditAttrs["class"] = "form-control";
			$this->AttachFilename->EditCustomAttributes = "";
			if (!EmptyValue($this->AttachFilename->Upload->DbValue)) {
				$this->AttachFilename->EditValue = $this->AttachFilename->Upload->DbValue;
			} else {
				$this->AttachFilename->EditValue = "";
			}
			if (!EmptyValue($this->AttachFilename->CurrentValue))
					$this->AttachFilename->Upload->FileName = $this->AttachFilename->CurrentValue;
			if (is_numeric($this->RowIndex) && !$this->EventCancelled)
				RenderUploadField($this->AttachFilename, $this->RowIndex);

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

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

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

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

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

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

			// Add refer script
			// AttachmentID

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

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

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

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

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

			// AttachFilename
			$this->AttachFilename->LinkCustomAttributes = "";
			$this->AttachFilename->HrefValue = "";
			$this->AttachFilename->ExportHrefValue = $this->AttachFilename->UploadPath . $this->AttachFilename->Upload->DbValue;

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

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

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

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

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

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

			// AttachmentID
			$this->AttachmentID->EditAttrs["class"] = "form-control";
			$this->AttachmentID->EditCustomAttributes = "";
			$this->AttachmentID->EditValue = $this->AttachmentID->CurrentValue;
			$this->AttachmentID->ViewCustomAttributes = "";

			// AttachmentSource_ID
			$this->AttachmentSource_ID->EditAttrs["class"] = "form-control";
			$this->AttachmentSource_ID->EditCustomAttributes = "";
			$this->AttachmentSource_ID->EditValue = HtmlEncode($this->AttachmentSource_ID->CurrentValue);
			$curVal = strval($this->AttachmentSource_ID->CurrentValue);
			if ($curVal <> "") {
				$this->AttachmentSource_ID->EditValue = $this->AttachmentSource_ID->lookupCacheOption($curVal);
				if ($this->AttachmentSource_ID->EditValue === NULL) { // Lookup from database
					$filterWrk = "`AttachmentSource_ID`" . SearchString("=", $curVal, DATATYPE_NUMBER, "");
					$sqlWrk = $this->AttachmentSource_ID->Lookup->getSql(FALSE, $filterWrk, '', $this);
					$rswrk = Conn()->execute($sqlWrk);
					if ($rswrk && !$rswrk->EOF) { // Lookup values found
						$arwrk = array();
						$arwrk[1] = HtmlEncode($rswrk->fields('df'));
						$this->AttachmentSource_ID->EditValue = $this->AttachmentSource_ID->displayValue($arwrk);
						$rswrk->Close();
					} else {
						$this->AttachmentSource_ID->EditValue = HtmlEncode($this->AttachmentSource_ID->CurrentValue);
					}
				}
			} else {
				$this->AttachmentSource_ID->EditValue = NULL;
			}
			$this->AttachmentSource_ID->PlaceHolder = RemoveHtml($this->AttachmentSource_ID->caption());

			// CaseID
			$this->CaseID->EditAttrs["class"] = "form-control";
			$this->CaseID->EditCustomAttributes = "";
			if ($this->CaseID->getSessionValue() <> "") {
				$this->CaseID->CurrentValue = $this->CaseID->getSessionValue();
				$this->CaseID->OldValue = $this->CaseID->CurrentValue;
			$this->CaseID->ViewValue = $this->CaseID->CurrentValue;
			$this->CaseID->ViewValue = FormatNumber($this->CaseID->ViewValue, 0, -2, -2, -2);
			$this->CaseID->ViewCustomAttributes = "";
			} else {
			$this->CaseID->EditValue = HtmlEncode($this->CaseID->CurrentValue);
			$this->CaseID->PlaceHolder = RemoveHtml($this->CaseID->caption());
			}

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

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

			// AttachFilename
			$this->AttachFilename->EditAttrs["class"] = "form-control";
			$this->AttachFilename->EditCustomAttributes = "";
			if (!EmptyValue($this->AttachFilename->Upload->DbValue)) {
				$this->AttachFilename->EditValue = $this->AttachFilename->Upload->DbValue;
			} else {
				$this->AttachFilename->EditValue = "";
			}
			if (!EmptyValue($this->AttachFilename->CurrentValue))
					$this->AttachFilename->Upload->FileName = $this->AttachFilename->CurrentValue;
			if (is_numeric($this->RowIndex) && !$this->EventCancelled)
				RenderUploadField($this->AttachFilename, $this->RowIndex);

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

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

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

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

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

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

			// Edit refer script
			// AttachmentID

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

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

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

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

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

			// AttachFilename
			$this->AttachFilename->LinkCustomAttributes = "";
			$this->AttachFilename->HrefValue = "";
			$this->AttachFilename->ExportHrefValue = $this->AttachFilename->UploadPath . $this->AttachFilename->Upload->DbValue;

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

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

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

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

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

			// Case
			$this->_Case->LinkCustomAttributes = "";
			$this->_Case->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;

		// Check if validation required
		if (!SERVER_VALIDATE)
			return ($FormError == "");
		if ($this->AttachmentID->Required) {
			if (!$this->AttachmentID->IsDetailKey && $this->AttachmentID->FormValue != NULL && $this->AttachmentID->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->AttachmentID->caption(), $this->AttachmentID->RequiredErrorMessage));
			}
		}
		if ($this->AttachmentSource_ID->Required) {
			if (!$this->AttachmentSource_ID->IsDetailKey && $this->AttachmentSource_ID->FormValue != NULL && $this->AttachmentSource_ID->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->AttachmentSource_ID->caption(), $this->AttachmentSource_ID->RequiredErrorMessage));
			}
		}
		if (!CheckInteger($this->AttachmentSource_ID->FormValue)) {
			AddMessage($FormError, $this->AttachmentSource_ID->errorMessage());
		}
		if ($this->CaseID->Required) {
			if (!$this->CaseID->IsDetailKey && $this->CaseID->FormValue != NULL && $this->CaseID->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->CaseID->caption(), $this->CaseID->RequiredErrorMessage));
			}
		}
		if (!CheckInteger($this->CaseID->FormValue)) {
			AddMessage($FormError, $this->CaseID->errorMessage());
		}
		if ($this->EmployeeID->Required) {
			if (!$this->EmployeeID->IsDetailKey && $this->EmployeeID->FormValue != NULL && $this->EmployeeID->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->EmployeeID->caption(), $this->EmployeeID->RequiredErrorMessage));
			}
		}
		if (!CheckInteger($this->EmployeeID->FormValue)) {
			AddMessage($FormError, $this->EmployeeID->errorMessage());
		}
		if ($this->AttachID->Required) {
			if (!$this->AttachID->IsDetailKey && $this->AttachID->FormValue != NULL && $this->AttachID->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->AttachID->caption(), $this->AttachID->RequiredErrorMessage));
			}
		}
		if (!CheckInteger($this->AttachID->FormValue)) {
			AddMessage($FormError, $this->AttachID->errorMessage());
		}
		if ($this->AttachFilename->Required) {
			if ($this->AttachFilename->Upload->FileName == "" && !$this->AttachFilename->Upload->KeepFile) {
				AddMessage($FormError, str_replace("%s", $this->AttachFilename->caption(), $this->AttachFilename->RequiredErrorMessage));
			}
		}
		if ($this->AttachFilenameInitial->Required) {
			if (!$this->AttachFilenameInitial->IsDetailKey && $this->AttachFilenameInitial->FormValue != NULL && $this->AttachFilenameInitial->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->AttachFilenameInitial->caption(), $this->AttachFilenameInitial->RequiredErrorMessage));
			}
		}
		if ($this->AttachExtension->Required) {
			if (!$this->AttachExtension->IsDetailKey && $this->AttachExtension->FormValue != NULL && $this->AttachExtension->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->AttachExtension->caption(), $this->AttachExtension->RequiredErrorMessage));
			}
		}
		if ($this->AttachDescription->Required) {
			if (!$this->AttachDescription->IsDetailKey && $this->AttachDescription->FormValue != NULL && $this->AttachDescription->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->AttachDescription->caption(), $this->AttachDescription->RequiredErrorMessage));
			}
		}
		if ($this->AttachNotes->Required) {
			if (!$this->AttachNotes->IsDetailKey && $this->AttachNotes->FormValue != NULL && $this->AttachNotes->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->AttachNotes->caption(), $this->AttachNotes->RequiredErrorMessage));
			}
		}
		if ($this->AttachFilepath->Required) {
			if (!$this->AttachFilepath->IsDetailKey && $this->AttachFilepath->FormValue != NULL && $this->AttachFilepath->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->AttachFilepath->caption(), $this->AttachFilepath->RequiredErrorMessage));
			}
		}
		if ($this->AttachPath->Required) {
			if (!$this->AttachPath->IsDetailKey && $this->AttachPath->FormValue != NULL && $this->AttachPath->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->AttachPath->caption(), $this->AttachPath->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->_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->AddedBy->Required) {
			if (!$this->AddedBy->IsDetailKey && $this->AddedBy->FormValue != NULL && $this->AddedBy->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->AddedBy->caption(), $this->AddedBy->RequiredErrorMessage));
			}
		}
		if ($this->AddedDate->Required) {
			if (!$this->AddedDate->IsDetailKey && $this->AddedDate->FormValue != NULL && $this->AddedDate->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->AddedDate->caption(), $this->AddedDate->RequiredErrorMessage));
			}
		}
		if ($this->_Case->Required) {
			if (!$this->_Case->IsDetailKey && $this->_Case->FormValue != NULL && $this->_Case->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->_Case->caption(), $this->_Case->RequiredErrorMessage));
			}
		}

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

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

	// Delete records based on current filter
	protected function deleteRows()
	{
		global $Language, $Security;
		if (!$Security->canDelete()) {
			$this->setFailureMessage($Language->phrase("NoDeletePermission")); // No delete permission
			return FALSE;
		}
		$deleteRows = TRUE;
		$sql = $this->getCurrentSql();
		$conn = &$this->getConnection();
		$conn->raiseErrorFn = $GLOBALS["ERROR_FUNC"];
		$rs = $conn->execute($sql);
		$conn->raiseErrorFn = '';
		if ($rs === FALSE) {
			return FALSE;
		} elseif ($rs->EOF) {
			$this->setFailureMessage($Language->phrase("NoRecord")); // No record found
			$rs->close();
			return FALSE;
		}
		$rows = ($rs) ? $rs->getRows() : [];
		if ($this->AuditTrailOnDelete)
			$this->writeAuditTrailDummy($Language->phrase("BatchDeleteBegin")); // Batch delete begin

		// Clone old rows
		$rsold = $rows;
		if ($rs)
			$rs->close();

		// Call row deleting event
		if ($deleteRows) {
			foreach ($rsold as $row) {
				$deleteRows = $this->Row_Deleting($row);
				if (!$deleteRows)
					break;
			}
		}
		if ($deleteRows) {
			$key = "";
			foreach ($rsold as $row) {
				$thisKey = "";
				if ($thisKey <> "")
					$thisKey .= $GLOBALS["COMPOSITE_KEY_SEPARATOR"];
				$thisKey .= $row['AttachmentID'];
				if (DELETE_UPLOADED_FILES) // Delete old files
					$this->deleteUploadedFiles($row);
				$conn->raiseErrorFn = $GLOBALS["ERROR_FUNC"];
				$deleteRows = $this->delete($row); // Delete
				$conn->raiseErrorFn = '';
				if ($deleteRows === FALSE)
					break;
				if ($key <> "")
					$key .= ", ";
				$key .= $thisKey;
			}
		}
		if (!$deleteRows) {

			// Set up error message
			if ($this->getSuccessMessage() <> "" || $this->getFailureMessage() <> "") {

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

		// Call Row Deleted event
		if ($deleteRows) {
			foreach ($rsold as $row) {
				$this->Row_Deleted($row);
			}
		}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

			// Check referential integrity for master table 'cases'
			$validMasterRecord = TRUE;
			$masterFilter = $this->sqlMasterFilter_cases();
			$keyValue = isset($rsnew['CaseID']) ? $rsnew['CaseID'] : $rsold['CaseID'];
			if (strval($keyValue) <> "") {
				$masterFilter = str_replace("@CaseID@", AdjustSql($keyValue), $masterFilter);
			} else {
				$validMasterRecord = FALSE;
			}
			if ($validMasterRecord) {
				if (!isset($GLOBALS["cases"]))
					$GLOBALS["cases"] = new cases();
				$rsmaster = $GLOBALS["cases"]->loadRs($masterFilter);
				$validMasterRecord = ($rsmaster && !$rsmaster->EOF);
				$rsmaster->close();
			}
			if (!$validMasterRecord) {
				$relatedRecordMsg = str_replace("%t", "cases", $Language->phrase("RelatedRecordRequired"));
				$this->setFailureMessage($relatedRecordMsg);
				$rs->close();
				return FALSE;
			}
			if ($this->AttachFilename->Visible && !$this->AttachFilename->Upload->KeepFile) {
				$oldFiles = EmptyValue($this->AttachFilename->Upload->DbValue) ? array() : explode(MULTIPLE_UPLOAD_SEPARATOR, strval($this->AttachFilename->Upload->DbValue));
				if (!EmptyValue($this->AttachFilename->Upload->FileName)) {
					$newFiles = explode(MULTIPLE_UPLOAD_SEPARATOR, strval($this->AttachFilename->Upload->FileName));
					$NewFileCount = count($newFiles);
					for ($i = 0; $i < $NewFileCount; $i++) {
						if ($newFiles[$i] <> "") {
							$file = $newFiles[$i];
							if (file_exists(UploadTempPath($this->AttachFilename, $this->AttachFilename->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->AttachFilename->physicalUploadPath(), $file); // Get new file name
								if ($file1 <> $file) { // Rename temp file
									while (file_exists(UploadTempPath($this->AttachFilename, $this->AttachFilename->Upload->Index) . $file1) || file_exists($this->AttachFilename->physicalUploadPath() . $file1)) // Make sure no file name clash
										$file1 = UniqueFilename($this->AttachFilename->physicalUploadPath(), $file1, TRUE); // Use indexed name
									rename(UploadTempPath($this->AttachFilename, $this->AttachFilename->Upload->Index) . $file, UploadTempPath($this->AttachFilename, $this->AttachFilename->Upload->Index) . $file1);
									$newFiles[$i] = $file1;
								}
							}
						}
					}
					$this->AttachFilename->Upload->DbValue = empty($oldFiles) ? "" : implode(MULTIPLE_UPLOAD_SEPARATOR, $oldFiles);
					$this->AttachFilename->Upload->FileName = implode(MULTIPLE_UPLOAD_SEPARATOR, $newFiles);
					$this->AttachFilename->setDbValueDef($rsnew, $this->AttachFilename->Upload->FileName, NULL, $this->AttachFilename->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->AttachFilename->Visible && !$this->AttachFilename->Upload->KeepFile) {
						$oldFiles = EmptyValue($this->AttachFilename->Upload->DbValue) ? array() : explode(MULTIPLE_UPLOAD_SEPARATOR, strval($this->AttachFilename->Upload->DbValue));
						if (!EmptyValue($this->AttachFilename->Upload->FileName)) {
							$newFiles = explode(MULTIPLE_UPLOAD_SEPARATOR, $this->AttachFilename->Upload->FileName);
							$newFiles2 = explode(MULTIPLE_UPLOAD_SEPARATOR, $rsnew['AttachFilename']);
							$newFileCount = count($newFiles);
							for ($i = 0; $i < $newFileCount; $i++) {
								if ($newFiles[$i] <> "") {
									$file = UploadTempPath($this->AttachFilename, $this->AttachFilename->Upload->Index) . $newFiles[$i];
									if (file_exists($file)) {
										if (@$newFiles2[$i] <> "") // Use correct file name
											$newFiles[$i] = $newFiles2[$i];
										if (!$this->AttachFilename->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->AttachFilename->oldPhysicalUploadPath() . $oldFile);
							}
						}
					}
				}
			} 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();

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

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

	// Add record
	protected function addRow($rsold = NULL)
	{
		global $Language, $Security;

		// Set up foreign key field value from Session
			if ($this->getCurrentMasterTable() == "cases") {
				$this->CaseID->CurrentValue = $this->CaseID->getSessionValue();
			}

		// Check referential integrity for master table 'cases'
		$validMasterRecord = TRUE;
		$masterFilter = $this->sqlMasterFilter_cases();
		if (strval($this->CaseID->CurrentValue) <> "") {
			$masterFilter = str_replace("@CaseID@", AdjustSql($this->CaseID->CurrentValue, "DB"), $masterFilter);
		} else {
			$validMasterRecord = FALSE;
		}
		if ($validMasterRecord) {
			if (!isset($GLOBALS["cases"]))
				$GLOBALS["cases"] = new cases();
			$rsmaster = $GLOBALS["cases"]->loadRs($masterFilter);
			$validMasterRecord = ($rsmaster && !$rsmaster->EOF);
			$rsmaster->close();
		}
		if (!$validMasterRecord) {
			$relatedRecordMsg = str_replace("%t", "cases", $Language->phrase("RelatedRecordRequired"));
			$this->setFailureMessage($relatedRecordMsg);
			return FALSE;
		}
		$conn = &$this->getConnection();

		// Load db values from rsold
		$this->loadDbValues($rsold);
		if ($rsold) {
		}
		$rsnew = [];

		// AttachmentSource_ID
		$this->AttachmentSource_ID->setDbValueDef($rsnew, $this->AttachmentSource_ID->CurrentValue, 0, strval($this->AttachmentSource_ID->CurrentValue) == "");

		// CaseID
		$this->CaseID->setDbValueDef($rsnew, $this->CaseID->CurrentValue, NULL, FALSE);

		// EmployeeID
		$this->EmployeeID->setDbValueDef($rsnew, $this->EmployeeID->CurrentValue, NULL, FALSE);

		// AttachID
		$this->AttachID->setDbValueDef($rsnew, $this->AttachID->CurrentValue, NULL, FALSE);

		// AttachFilename
		if ($this->AttachFilename->Visible && !$this->AttachFilename->Upload->KeepFile) {
			$this->AttachFilename->Upload->DbValue = ""; // No need to delete old file
			if ($this->AttachFilename->Upload->FileName == "") {
				$rsnew['AttachFilename'] = NULL;
			} else {
				$rsnew['AttachFilename'] = $this->AttachFilename->Upload->FileName;
			}
		}

		// AttachFilenameInitial
		$this->AttachFilenameInitial->setDbValueDef($rsnew, $this->AttachFilenameInitial->CurrentValue, NULL, FALSE);

		// AttachExtension
		$this->AttachExtension->setDbValueDef($rsnew, $this->AttachExtension->CurrentValue, NULL, FALSE);

		// AttachDescription
		$this->AttachDescription->setDbValueDef($rsnew, $this->AttachDescription->CurrentValue, NULL, FALSE);

		// AttachFilepath
		$this->AttachFilepath->setDbValueDef($rsnew, $this->AttachFilepath->CurrentValue, NULL, FALSE);

		// AttachPath
		$this->AttachPath->setDbValueDef($rsnew, $this->AttachPath->CurrentValue, NULL, FALSE);

		// Case
		$this->_Case->setDbValueDef($rsnew, $this->_Case->CurrentValue, NULL, FALSE);
		if ($this->AttachFilename->Visible && !$this->AttachFilename->Upload->KeepFile) {
			$oldFiles = EmptyValue($this->AttachFilename->Upload->DbValue) ? array() : explode(MULTIPLE_UPLOAD_SEPARATOR, strval($this->AttachFilename->Upload->DbValue));
			if (!EmptyValue($this->AttachFilename->Upload->FileName)) {
				$newFiles = explode(MULTIPLE_UPLOAD_SEPARATOR, strval($this->AttachFilename->Upload->FileName));
				$NewFileCount = count($newFiles);
				for ($i = 0; $i < $NewFileCount; $i++) {
					if ($newFiles[$i] <> "") {
						$file = $newFiles[$i];
						if (file_exists(UploadTempPath($this->AttachFilename, $this->AttachFilename->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->AttachFilename->physicalUploadPath(), $file); // Get new file name
							if ($file1 <> $file) { // Rename temp file
								while (file_exists(UploadTempPath($this->AttachFilename, $this->AttachFilename->Upload->Index) . $file1) || file_exists($this->AttachFilename->physicalUploadPath() . $file1)) // Make sure no file name clash
									$file1 = UniqueFilename($this->AttachFilename->physicalUploadPath(), $file1, TRUE); // Use indexed name
								rename(UploadTempPath($this->AttachFilename, $this->AttachFilename->Upload->Index) . $file, UploadTempPath($this->AttachFilename, $this->AttachFilename->Upload->Index) . $file1);
								$newFiles[$i] = $file1;
							}
						}
					}
				}
				$this->AttachFilename->Upload->DbValue = empty($oldFiles) ? "" : implode(MULTIPLE_UPLOAD_SEPARATOR, $oldFiles);
				$this->AttachFilename->Upload->FileName = implode(MULTIPLE_UPLOAD_SEPARATOR, $newFiles);
				$this->AttachFilename->setDbValueDef($rsnew, $this->AttachFilename->Upload->FileName, NULL, FALSE);
			}
		}

		// Call Row Inserting event
		$rs = ($rsold) ? $rsold->fields : NULL;
		$insertRow = $this->Row_Inserting($rs, $rsnew);
		if ($insertRow) {
			$conn->raiseErrorFn = $GLOBALS["ERROR_FUNC"];
			$addRow = $this->insert($rsnew);
			$conn->raiseErrorFn = '';
			if ($addRow) {
				if ($this->AttachFilename->Visible && !$this->AttachFilename->Upload->KeepFile) {
					$oldFiles = EmptyValue($this->AttachFilename->Upload->DbValue) ? array() : explode(MULTIPLE_UPLOAD_SEPARATOR, strval($this->AttachFilename->Upload->DbValue));
					if (!EmptyValue($this->AttachFilename->Upload->FileName)) {
						$newFiles = explode(MULTIPLE_UPLOAD_SEPARATOR, $this->AttachFilename->Upload->FileName);
						$newFiles2 = explode(MULTIPLE_UPLOAD_SEPARATOR, $rsnew['AttachFilename']);
						$newFileCount = count($newFiles);
						for ($i = 0; $i < $newFileCount; $i++) {
							if ($newFiles[$i] <> "") {
								$file = UploadTempPath($this->AttachFilename, $this->AttachFilename->Upload->Index) . $newFiles[$i];
								if (file_exists($file)) {
									if (@$newFiles2[$i] <> "") // Use correct file name
										$newFiles[$i] = $newFiles2[$i];
									if (!$this->AttachFilename->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->AttachFilename->oldPhysicalUploadPath() . $oldFile);
						}
					}
				}
			}
		} 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("InsertCancelled"));
			}
			$addRow = FALSE;
		}
		if ($addRow) {

			// Call Row Inserted event
			$rs = ($rsold) ? $rsold->fields : NULL;
			$this->Row_Inserted($rs, $rsnew);
		}

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

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

	// Set up master/detail based on QueryString
	protected function setupMasterParms()
	{

		// Hide foreign keys
		$masterTblVar = $this->getCurrentMasterTable();
		if ($masterTblVar == "cases") {
			$this->CaseID->Visible = FALSE;
			if ($GLOBALS["cases"]->EventCancelled)
				$this->EventCancelled = TRUE;
		}
		$this->DbMasterFilter = $this->getMasterFilter(); // Get master filter
		$this->DbDetailFilter = $this->getDetailFilter(); // Get detail filter
	}

	// 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_AttachmentSource_ID":
							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;
	}

	// ListOptions Load event
	function ListOptions_Load() {

		// Example:
		//$opt = &$this->ListOptions->Add("new");
		//$opt->Header = "xxx";
		//$opt->OnLeft = TRUE; // Link on left
		//$opt->MoveTo(0); // Move to first column

	}

	// ListOptions Rendering event
	function ListOptions_Rendering() {

		//$GLOBALS["xxx_grid"]->DetailAdd = (...condition...); // Set to TRUE or FALSE conditionally
		//$GLOBALS["xxx_grid"]->DetailEdit = (...condition...); // Set to TRUE or FALSE conditionally
		//$GLOBALS["xxx_grid"]->DetailView = (...condition...); // Set to TRUE or FALSE conditionally

	}

	// ListOptions Rendered event
	function ListOptions_Rendered() {

		// Example:
		//$this->ListOptions->Items["new"]->Body = "xxx";

	}
}
?>
