<?php
namespace PHPMaker2019\project_germanos;

/**
 * Page class
 */
class cases_delete extends cases
{

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		// Parent constuctor
		parent::__construct();

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

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

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

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

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

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

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

		// Debug message
		LoadDebugMessage();

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

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

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

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

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

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

		// Close connection
		CloseConnections();

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

		// Go to URL if specified
		if ($url <> "") {
			if (!DEBUG_ENABLED && ob_get_length())
				ob_end_clean();
			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['CaseID'];
		}
		return $key;
	}

	/**
	 * Hide fields for add/edit
	 *
	 * @return void
	 */
	protected function hideFieldsForAddEdit()
	{
		if ($this->isAdd() || $this->isCopy() || $this->isGridAdd())
			$this->CaseID->Visible = FALSE;
	}
	public $DbMasterFilter = "";
	public $DbDetailFilter = "";
	public $StartRec;
	public $TotalRecs = 0;
	public $RecCnt;
	public $RecKeys = array();
	public $StartRowCnt = 1;
	public $RowCnt = 0;

	//
	// Page run
	//

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

		// 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->canDelete()) {
				$Security->saveLastUrl();
				$this->setFailureMessage(DeniedMessage()); // Set no permission
				if ($Security->canList())
					$this->terminate(GetUrl("caseslist.php"));
				else
					$this->terminate(GetUrl("login.php"));
				return;
			}
			if ($Security->isLoggedIn()) {
				$Security->UserID_Loading();
				$Security->loadUserID();
				$Security->UserID_Loaded();
			}
		}

		// Update last accessed time
		if ($UserProfile->isValidUser(CurrentUserName(), session_id())) {
		} else {
			Write($Language->phrase("UserProfileCorrupted"));
			$this->terminate();
		}
		$this->CurrentAction = Param("action"); // Set up current action
		$this->CaseID->Visible = FALSE;
		$this->ClientID->setVisibility();
		$this->LitigantID->setVisibility();
		$this->CaseTypeID->setVisibility();
		$this->CourtID->setVisibility();
		$this->CaseNumber->setVisibility();
		$this->FileNumber->setVisibility();
		$this->EnvelopeNumber->Visible = FALSE;
		$this->ClientStatusID->setVisibility();
		$this->LitigantStatusID->setVisibility();
		$this->CourtTypeID->Visible = FALSE;
		$this->CourtGenderID->Visible = FALSE;
		$this->JudgeID->Visible = FALSE;
		$this->Notes->setVisibility();
		$this->FileLocation->Visible = FALSE;
		$this->_Case->Visible = FALSE;
		$this->CaseEn->Visible = FALSE;
		$this->CaseSortID->Visible = FALSE;
		$this->CaseRegisteredDate->Visible = FALSE;
		$this->CaseStatusID->Visible = FALSE;
		$this->ParentCaseID->setVisibility();
		$this->FileNumber2->setVisibility();
		$this->_UserID->Visible = FALSE;
		$this->CreatedBy->Visible = FALSE;
		$this->CreatedDate->Visible = FALSE;
		$this->UpdatedBy->Visible = FALSE;
		$this->UpdatedDate->Visible = FALSE;
		$this->CaseTypeConv->Visible = FALSE;
		$this->CaseConv->Visible = FALSE;
		$this->ClientStatusConv->Visible = FALSE;
		$this->LitigantStatusConv->Visible = FALSE;
		$this->ClientNameConv->Visible = FALSE;
		$this->LitigantNameConv->Visible = FALSE;
		$this->ClientNameConvFiles->setVisibility();
		$this->LitigantNameConvFiles->setVisibility();
		$this->CaseTypeConvFiles->setVisibility();
		$this->CourtConvFiles->Visible = FALSE;
		$this->FileNumberConvFiles->Visible = FALSE;
		$this->CaseNumberConvFiles->Visible = FALSE;
		$this->NotesConvFiles->Visible = FALSE;
		$this->hideFieldsForAddEdit();

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

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

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

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

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

		// Set up lookup cache
		$this->setupLookupOptions($this->ClientID);
		$this->setupLookupOptions($this->LitigantID);
		$this->setupLookupOptions($this->CaseTypeID);
		$this->setupLookupOptions($this->CourtID);
		$this->setupLookupOptions($this->ClientStatusID);
		$this->setupLookupOptions($this->LitigantStatusID);
		$this->setupLookupOptions($this->CourtTypeID);
		$this->setupLookupOptions($this->CourtGenderID);
		$this->setupLookupOptions($this->JudgeID);
		$this->setupLookupOptions($this->CaseSortID);
		$this->setupLookupOptions($this->CaseStatusID);

		// Set up master/detail parameters
		$this->setupMasterParms();

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

		// Load key parameters
		$this->RecKeys = $this->getRecordKeys(); // Load record keys
		$filter = $this->getFilterFromRecordKeys();
		if ($filter == "") {
			$this->terminate("caseslist.php"); // Prevent SQL injection, return to list
			return;
		}

		// Set up filter (WHERE Clause)
		$this->CurrentFilter = $filter;

		// Get action
		if (IsApi()) {
			$this->CurrentAction = "delete"; // Delete record directly
		} elseif (Post("action") !== NULL) {
			$this->CurrentAction = Post("action");
		} elseif (Get("action") == "1") {
			$this->CurrentAction = "delete"; // Delete record directly
		} else {
			$this->CurrentAction = "show"; // Display record
		}
		if ($this->isDelete()) {
			$this->SendEmail = TRUE; // Send email on delete success
			if ($this->deleteRows()) { // Delete rows
				if ($this->getSuccessMessage() == "")
					$this->setSuccessMessage($Language->phrase("DeleteSuccess")); // Set up success message
				if (IsApi()) {
					$this->terminate(TRUE);
					return;
				} else {
					$this->terminate($this->getReturnUrl()); // Return to caller
				}
			} else { // Delete failed
				if (IsApi()) {
					$this->terminate();
					return;
				}
				$this->CurrentAction = "show"; // Display record
			}
		}
		if ($this->isShow()) { // Load records for display
			if ($this->Recordset = $this->loadRecordset())
				$this->TotalRecs = $this->Recordset->RecordCount(); // Get record count
			if ($this->TotalRecs <= 0) { // No record found, exit
				if ($this->Recordset)
					$this->Recordset->close();
				$this->terminate("caseslist.php"); // Return to list
			}
		}
	}

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

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

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

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

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

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

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

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

		// Call Row Selected event
		$this->Row_Selected($row);
		if (!$rs || $rs->EOF)
			return;
		$this->CaseID->setDbValue($row['CaseID']);
		$this->ClientID->setDbValue($row['ClientID']);
		if (array_key_exists('EV__ClientID', $rs->fields)) {
			$this->ClientID->VirtualValue = $rs->fields('EV__ClientID'); // Set up virtual field value
		} else {
			$this->ClientID->VirtualValue = ""; // Clear value
		}
		$this->LitigantID->setDbValue($row['LitigantID']);
		if (array_key_exists('EV__LitigantID', $rs->fields)) {
			$this->LitigantID->VirtualValue = $rs->fields('EV__LitigantID'); // Set up virtual field value
		} else {
			$this->LitigantID->VirtualValue = ""; // Clear value
		}
		$this->CaseTypeID->setDbValue($row['CaseTypeID']);
		if (array_key_exists('EV__CaseTypeID', $rs->fields)) {
			$this->CaseTypeID->VirtualValue = $rs->fields('EV__CaseTypeID'); // Set up virtual field value
		} else {
			$this->CaseTypeID->VirtualValue = ""; // Clear value
		}
		$this->CourtID->setDbValue($row['CourtID']);
		if (array_key_exists('EV__CourtID', $rs->fields)) {
			$this->CourtID->VirtualValue = $rs->fields('EV__CourtID'); // Set up virtual field value
		} else {
			$this->CourtID->VirtualValue = ""; // Clear value
		}
		$this->CaseNumber->setDbValue($row['CaseNumber']);
		$this->FileNumber->setDbValue($row['FileNumber']);
		$this->EnvelopeNumber->setDbValue($row['EnvelopeNumber']);
		$this->ClientStatusID->setDbValue($row['ClientStatusID']);
		if (array_key_exists('EV__ClientStatusID', $rs->fields)) {
			$this->ClientStatusID->VirtualValue = $rs->fields('EV__ClientStatusID'); // Set up virtual field value
		} else {
			$this->ClientStatusID->VirtualValue = ""; // Clear value
		}
		$this->LitigantStatusID->setDbValue($row['LitigantStatusID']);
		if (array_key_exists('EV__LitigantStatusID', $rs->fields)) {
			$this->LitigantStatusID->VirtualValue = $rs->fields('EV__LitigantStatusID'); // Set up virtual field value
		} else {
			$this->LitigantStatusID->VirtualValue = ""; // Clear value
		}
		$this->CourtTypeID->setDbValue($row['CourtTypeID']);
		if (array_key_exists('EV__CourtTypeID', $rs->fields)) {
			$this->CourtTypeID->VirtualValue = $rs->fields('EV__CourtTypeID'); // Set up virtual field value
		} else {
			$this->CourtTypeID->VirtualValue = ""; // Clear value
		}
		$this->CourtGenderID->setDbValue($row['CourtGenderID']);
		if (array_key_exists('EV__CourtGenderID', $rs->fields)) {
			$this->CourtGenderID->VirtualValue = $rs->fields('EV__CourtGenderID'); // Set up virtual field value
		} else {
			$this->CourtGenderID->VirtualValue = ""; // Clear value
		}
		$this->JudgeID->setDbValue($row['JudgeID']);
		if (array_key_exists('EV__JudgeID', $rs->fields)) {
			$this->JudgeID->VirtualValue = $rs->fields('EV__JudgeID'); // Set up virtual field value
		} else {
			$this->JudgeID->VirtualValue = ""; // Clear value
		}
		$this->Notes->setDbValue($row['Notes']);
		$this->FileLocation->setDbValue($row['FileLocation']);
		$this->_Case->setDbValue($row['Case']);
		$this->CaseEn->setDbValue($row['CaseEn']);
		$this->CaseSortID->setDbValue($row['CaseSortID']);
		if (array_key_exists('EV__CaseSortID', $rs->fields)) {
			$this->CaseSortID->VirtualValue = $rs->fields('EV__CaseSortID'); // Set up virtual field value
		} else {
			$this->CaseSortID->VirtualValue = ""; // Clear value
		}
		$this->CaseRegisteredDate->setDbValue($row['CaseRegisteredDate']);
		$this->CaseStatusID->setDbValue($row['CaseStatusID']);
		if (array_key_exists('EV__CaseStatusID', $rs->fields)) {
			$this->CaseStatusID->VirtualValue = $rs->fields('EV__CaseStatusID'); // Set up virtual field value
		} else {
			$this->CaseStatusID->VirtualValue = ""; // Clear value
		}
		$this->ParentCaseID->setDbValue($row['ParentCaseID']);
		$this->FileNumber2->setDbValue($row['FileNumber2']);
		$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->CaseTypeConv->setDbValue($row['CaseTypeConv']);
		$this->CaseConv->setDbValue($row['CaseConv']);
		$this->ClientStatusConv->setDbValue($row['ClientStatusConv']);
		$this->LitigantStatusConv->setDbValue($row['LitigantStatusConv']);
		$this->ClientNameConv->setDbValue($row['ClientNameConv']);
		$this->LitigantNameConv->setDbValue($row['LitigantNameConv']);
		$this->ClientNameConvFiles->setDbValue($row['ClientNameConvFiles']);
		$this->LitigantNameConvFiles->setDbValue($row['LitigantNameConvFiles']);
		$this->CaseTypeConvFiles->setDbValue($row['CaseTypeConvFiles']);
		$this->CourtConvFiles->setDbValue($row['CourtConvFiles']);
		$this->FileNumberConvFiles->setDbValue($row['FileNumberConvFiles']);
		$this->CaseNumberConvFiles->setDbValue($row['CaseNumberConvFiles']);
		$this->NotesConvFiles->setDbValue($row['NotesConvFiles']);
	}

	// Return a row with default values
	protected function newRow()
	{
		$row = [];
		$row['CaseID'] = NULL;
		$row['ClientID'] = NULL;
		$row['LitigantID'] = NULL;
		$row['CaseTypeID'] = NULL;
		$row['CourtID'] = NULL;
		$row['CaseNumber'] = NULL;
		$row['FileNumber'] = NULL;
		$row['EnvelopeNumber'] = NULL;
		$row['ClientStatusID'] = NULL;
		$row['LitigantStatusID'] = NULL;
		$row['CourtTypeID'] = NULL;
		$row['CourtGenderID'] = NULL;
		$row['JudgeID'] = NULL;
		$row['Notes'] = NULL;
		$row['FileLocation'] = NULL;
		$row['Case'] = NULL;
		$row['CaseEn'] = NULL;
		$row['CaseSortID'] = NULL;
		$row['CaseRegisteredDate'] = NULL;
		$row['CaseStatusID'] = NULL;
		$row['ParentCaseID'] = NULL;
		$row['FileNumber2'] = NULL;
		$row['UserID'] = NULL;
		$row['CreatedBy'] = NULL;
		$row['CreatedDate'] = NULL;
		$row['UpdatedBy'] = NULL;
		$row['UpdatedDate'] = NULL;
		$row['CaseTypeConv'] = NULL;
		$row['CaseConv'] = NULL;
		$row['ClientStatusConv'] = NULL;
		$row['LitigantStatusConv'] = NULL;
		$row['ClientNameConv'] = NULL;
		$row['LitigantNameConv'] = NULL;
		$row['ClientNameConvFiles'] = NULL;
		$row['LitigantNameConvFiles'] = NULL;
		$row['CaseTypeConvFiles'] = NULL;
		$row['CourtConvFiles'] = NULL;
		$row['FileNumberConvFiles'] = NULL;
		$row['CaseNumberConvFiles'] = NULL;
		$row['NotesConvFiles'] = NULL;
		return $row;
	}

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

		// Initialize URLs
		// Call Row_Rendering event

		$this->Row_Rendering();

		// Common render codes for all row types
		// CaseID
		// ClientID

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

		// LitigantID
		$this->LitigantID->CellCssStyle = "width: 250px; white-space: nowrap;";

		// CaseTypeID
		$this->CaseTypeID->CellCssStyle = "min-width: 120px;";

		// CourtID
		$this->CourtID->CellCssStyle = "width: 200px; white-space: nowrap;";

		// CaseNumber
		// FileNumber
		// EnvelopeNumber
		// ClientStatusID
		// LitigantStatusID
		// CourtTypeID

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

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

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

		// Notes
		$this->Notes->CellCssStyle = "min-width: 450px;";

		// FileLocation
		// Case

		$this->_Case->CellCssStyle = "min-width: 180px;";

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

		// CaseSortID
		// CaseRegisteredDate
		// CaseStatusID
		// ParentCaseID
		// FileNumber2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		// NotesConvFiles
		$this->NotesConvFiles->CellCssStyle = "white-space: nowrap;";
		if ($this->RowType == ROWTYPE_VIEW) { // View row

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

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

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

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

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

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

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

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

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

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

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

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

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

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

			// CaseRegisteredDate
			$this->CaseRegisteredDate->ViewValue = $this->CaseRegisteredDate->CurrentValue;
			$this->CaseRegisteredDate->ViewValue = FormatDateTime($this->CaseRegisteredDate->ViewValue, 7);
			$this->CaseRegisteredDate->ViewCustomAttributes = "";

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

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

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

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

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

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

			// ClientID
			$this->ClientID->LinkCustomAttributes = "";
			if (!EmptyValue($this->ClientID->CurrentValue)) {
				$this->ClientID->HrefValue = "/home/clientsview.php?showdetail=clientaddress,clientcontact,cases&ClientID=" . $this->ClientID->CurrentValue; // Add prefix/suffix
				$this->ClientID->LinkAttrs["target"] = "_self"; // Add target
				if ($this->isExport()) $this->ClientID->HrefValue = FullUrl($this->ClientID->HrefValue, "href");
			} else {
				$this->ClientID->HrefValue = "";
			}
			$this->ClientID->TooltipValue = "";

			// LitigantID
			$this->LitigantID->LinkCustomAttributes = "";
			if (!EmptyValue($this->LitigantID->CurrentValue)) {
				$this->LitigantID->HrefValue = "/home/litigantsview.php?showdetail=litigantaddress,litigantcontact,cases&LitigantID=" . $this->LitigantID->CurrentValue; // Add prefix/suffix
				$this->LitigantID->LinkAttrs["target"] = "_self"; // Add target
				if ($this->isExport()) $this->LitigantID->HrefValue = FullUrl($this->LitigantID->HrefValue, "href");
			} else {
				$this->LitigantID->HrefValue = "";
			}
			$this->LitigantID->TooltipValue = "";

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

			// CourtID
			$this->CourtID->LinkCustomAttributes = "";
			if (!EmptyValue($this->CourtID->CurrentValue)) {
				$this->CourtID->HrefValue = "/home/courtsview.php?showdetail=courtaddress,courtcontact&CourtID=" . $this->CourtID->CurrentValue; // Add prefix/suffix
				$this->CourtID->LinkAttrs["target"] = "_self"; // Add target
				if ($this->isExport()) $this->CourtID->HrefValue = FullUrl($this->CourtID->HrefValue, "href");
			} else {
				$this->CourtID->HrefValue = "";
			}
			$this->CourtID->TooltipValue = "";

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

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

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

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

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

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

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

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

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

			// CaseTypeConvFiles
			$this->CaseTypeConvFiles->LinkCustomAttributes = "";
			$this->CaseTypeConvFiles->HrefValue = "";
			$this->CaseTypeConvFiles->TooltipValue = "";
		}

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

	// 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() : [];
		$conn->beginTrans();
		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['CaseID'];
				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"));
			}
		}
		if ($deleteRows) {
			$conn->commitTrans(); // Commit the changes
			if ($this->AuditTrailOnDelete)
				$this->writeAuditTrailDummy($Language->phrase("BatchDeleteSuccess")); // Batch delete success
			$table = 'cases';
			$subject = $table . " " . $Language->phrase("RecordDeleted");
			$action = $Language->phrase("ActionDeleted");
			$email = new Email();
			$email->load(EMAIL_NOTIFY_TEMPLATE);
			$email->replaceSender(SENDER_EMAIL); // Replace Sender
			$email->replaceRecipient(RECIPIENT_EMAIL); // Replace Recipient
			$email->replaceSubject($subject); // Replace Subject
			$email->replaceContent("<!--table-->", $table);
			$email->replaceContent("<!--key-->", $key);
			$email->replaceContent("<!--action-->", $action);
			$args = [];
			$args["rs"] = &$rsold;
			$emailSent = FALSE;
			if ($this->Email_Sending($email, $args))
				$emailSent = $email->send();
			if (!$emailSent)
				$this->setFailureMessage($email->SendErrDescription);
		} else {
			$conn->rollbackTrans(); // Rollback changes
			if ($this->AuditTrailOnDelete)
				$this->writeAuditTrailDummy($Language->phrase("BatchDeleteRollback")); // Batch delete rollback
		}

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

	// Set up master/detail based on QueryString
	protected function setupMasterParms()
	{
		$validMaster = FALSE;

		// Get the keys for master table
		if (Get(TABLE_SHOW_MASTER) !== NULL) {
			$masterTblVar = Get(TABLE_SHOW_MASTER);
			if ($masterTblVar == "") {
				$validMaster = TRUE;
				$this->DbMasterFilter = "";
				$this->DbDetailFilter = "";
			}
			if ($masterTblVar == "clients") {
				$validMaster = TRUE;
				if (Get("fk_ClientID") !== NULL) {
					$GLOBALS["clients"]->ClientID->setQueryStringValue(Get("fk_ClientID"));
					$this->ClientID->setQueryStringValue($GLOBALS["clients"]->ClientID->QueryStringValue);
					$this->ClientID->setSessionValue($this->ClientID->QueryStringValue);
					if (!is_numeric($GLOBALS["clients"]->ClientID->QueryStringValue))
						$validMaster = FALSE;
				} else {
					$validMaster = FALSE;
				}
			}
			if ($masterTblVar == "litigants") {
				$validMaster = TRUE;
				if (Get("fk_LitigantID") !== NULL) {
					$GLOBALS["litigants"]->LitigantID->setQueryStringValue(Get("fk_LitigantID"));
					$this->LitigantID->setQueryStringValue($GLOBALS["litigants"]->LitigantID->QueryStringValue);
					$this->LitigantID->setSessionValue($this->LitigantID->QueryStringValue);
					if (!is_numeric($GLOBALS["litigants"]->LitigantID->QueryStringValue))
						$validMaster = FALSE;
				} else {
					$validMaster = FALSE;
				}
			}
		} elseif (Post(TABLE_SHOW_MASTER) !== NULL) {
			$masterTblVar = Post(TABLE_SHOW_MASTER);
			if ($masterTblVar == "") {
				$validMaster = TRUE;
				$this->DbMasterFilter = "";
				$this->DbDetailFilter = "";
			}
			if ($masterTblVar == "clients") {
				$validMaster = TRUE;
				if (Post("fk_ClientID") !== NULL) {
					$GLOBALS["clients"]->ClientID->setFormValue(Post("fk_ClientID"));
					$this->ClientID->setFormValue($GLOBALS["clients"]->ClientID->FormValue);
					$this->ClientID->setSessionValue($this->ClientID->FormValue);
					if (!is_numeric($GLOBALS["clients"]->ClientID->FormValue))
						$validMaster = FALSE;
				} else {
					$validMaster = FALSE;
				}
			}
			if ($masterTblVar == "litigants") {
				$validMaster = TRUE;
				if (Post("fk_LitigantID") !== NULL) {
					$GLOBALS["litigants"]->LitigantID->setFormValue(Post("fk_LitigantID"));
					$this->LitigantID->setFormValue($GLOBALS["litigants"]->LitigantID->FormValue);
					$this->LitigantID->setSessionValue($this->LitigantID->FormValue);
					if (!is_numeric($GLOBALS["litigants"]->LitigantID->FormValue))
						$validMaster = FALSE;
				} else {
					$validMaster = FALSE;
				}
			}
		}
		if ($validMaster) {

			// Save current master table
			$this->setCurrentMasterTable($masterTblVar);

			// Reset start record counter (new master key)
			if (!$this->isAddOrEdit()) {
				$this->StartRec = 1;
				$this->setStartRecordNumber($this->StartRec);
			}

			// Clear previous master key from Session
			if ($masterTblVar <> "clients") {
				if ($this->ClientID->CurrentValue == "")
					$this->ClientID->setSessionValue("");
			}
			if ($masterTblVar <> "litigants") {
				if ($this->LitigantID->CurrentValue == "")
					$this->LitigantID->setSessionValue("");
			}
		}
		$this->DbMasterFilter = $this->getMasterFilter(); // Get master filter
		$this->DbDetailFilter = $this->getDetailFilter(); // Get detail filter
	}

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

	// 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_ClientID":
							break;
						case "x_LitigantID":
							break;
						case "x_CaseTypeID":
							break;
						case "x_CourtID":
							break;
						case "x_ClientStatusID":
							break;
						case "x_LitigantStatusID":
							break;
						case "x_CourtTypeID":
							break;
						case "x_CourtGenderID":
							break;
						case "x_JudgeID":
							break;
						case "x_CaseSortID":
							break;
						case "x_CaseStatusID":
							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";

	}
}
?>
