<?php
namespace PHPMaker2019\project_germanos;

/**
 * Page class
 */
class cases_view extends cases
{

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

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

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

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

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

	// Export URLs
	public $ExportPrintUrl;
	public $ExportHtmlUrl;
	public $ExportExcelUrl;
	public $ExportWordUrl;
	public $ExportXmlUrl;
	public $ExportCsvUrl;
	public $ExportPdfUrl;

	// Custom export
	public $ExportExcelCustom = FALSE;
	public $ExportWordCustom = FALSE;
	public $ExportPdfCustom = FALSE;
	public $ExportEmailCustom = FALSE;

	// Update URLs
	public $InlineAddUrl;
	public $InlineCopyUrl;
	public $InlineEditUrl;
	public $GridAddUrl;
	public $GridEditUrl;
	public $MultiDeleteUrl;
	public $MultiUpdateUrl;

	// 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"];
		}
		$keyUrl = "";
		if (Get("CaseID") !== NULL) {
			$this->RecKey["CaseID"] = Get("CaseID");
			$keyUrl .= "&amp;CaseID=" . urlencode($this->RecKey["CaseID"]);
		}
		$this->ExportPrintUrl = $this->pageUrl() . "export=print" . $keyUrl;
		$this->ExportHtmlUrl = $this->pageUrl() . "export=html" . $keyUrl;
		$this->ExportExcelUrl = $this->pageUrl() . "export=excel" . $keyUrl;
		$this->ExportWordUrl = $this->pageUrl() . "export=word" . $keyUrl;
		$this->ExportXmlUrl = $this->pageUrl() . "export=xml" . $keyUrl;
		$this->ExportCsvUrl = $this->pageUrl() . "export=csv" . $keyUrl;
		$this->ExportPdfUrl = $this->pageUrl() . "export=pdf" . $keyUrl;

		// 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", 'view');

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

		// Export options
		$this->ExportOptions = new ListOptions();
		$this->ExportOptions->Tag = "div";
		$this->ExportOptions->TagClassName = "ew-export-option";

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

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

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

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

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

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

	// Get record key value from array
	protected function getRecordKeyValue($ar)
	{
		global $COMPOSITE_KEY_SEPARATOR;
		$key = "";
		if (is_array($ar)) {
			$key .= @$ar['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 $ExportOptions; // Export options
	public $OtherOptions; // Other options
	public $DisplayRecs = 1;
	public $DbMasterFilter;
	public $DbDetailFilter;
	public $StartRec;
	public $StopRec;
	public $TotalRecs = 0;
	public $RecRange = 10;
	public $Pager;
	public $AutoHidePager = AUTO_HIDE_PAGER;
	public $RecCnt;
	public $RecKey = array();
	public $IsModal = FALSE;
	public $hearings_Count;
	public $notices_Count;
	public $complaints_Count;
	public $notifications_Count;
	public $attachments_Count;
	public $DetailPages; // Detail pages object

	//
	// Page run
	//

	public function run()
	{
		global $ExportType, $CustomExportType, $ExportFileName, $UserProfile, $Language, $Security, $RequestSecurity, $CurrentForm,
			$SkipHeaderFooter, $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();
		}

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

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

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

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

			// Check token first
			$func = PROJECT_NAMESPACE . CHECK_TOKEN_FUNC;
			if (is_callable($func) && Post(TOKEN_NAME) !== NULL)
				$validRequest = $func(Post(TOKEN_NAME), SessionTimeoutTime());
			elseif (is_array($RequestSecurity) && @$RequestSecurity["username"] <> "") // Login user for API request
				$Security->loginUser(@$RequestSecurity["username"], @$RequestSecurity["userid"], @$RequestSecurity["parentuserid"], @$RequestSecurity["userlevelid"]);
		}
		if (!$validRequest) {
			if (IsPasswordExpired())
				$this->terminate(GetUrl("changepwd.php"));
			if (!$Security->isLoggedIn())
				$Security->autoLogin();
			if ($Security->isLoggedIn())
				$Security->TablePermission_Loading();
			$Security->loadCurrentUserLevel($this->ProjectID . $this->TableName);
			if ($Security->isLoggedIn())
				$Security->TablePermission_Loaded();
			if (!$Security->canView()) {
				$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();
		}

		// Get export parameters
		$custom = "";
		if (Param("export") !== NULL) {
			$this->Export = Param("export");
			$custom = Param("custom", "");
		} elseif (IsPost()) {
			if (Post("exporttype") !== NULL)
				$this->Export = Post("exporttype");
			$custom = Post("custom", "");
		} elseif (Get("cmd") == "json") {
			$this->Export = Get("cmd");
		} else {
			$this->setExportReturnUrl(CurrentUrl());
		}
		$ExportFileName = $this->TableVar; // Get export file, used in header
		if (Get("CaseID") !== NULL) {
			if ($ExportFileName <> "")
				$ExportFileName .= "_";
			$ExportFileName .= Get("CaseID");
		}

		// Get custom export parameters
		if ($this->isExport() && $custom <> "") {
			$this->CustomExport = $this->Export;
			$this->Export = "print";
		}
		$CustomExportType = $this->CustomExport;
		$ExportType = $this->Export; // Get export parameter, used in header

		// Update Export URLs
		if (defined(PROJECT_NAMESPACE . "USE_PHPEXCEL"))
			$this->ExportExcelCustom = FALSE;
		if ($this->ExportExcelCustom)
			$this->ExportExcelUrl .= "&amp;custom=1";
		if (defined(PROJECT_NAMESPACE . "USE_PHPWORD"))
			$this->ExportWordCustom = FALSE;
		if ($this->ExportWordCustom)
			$this->ExportWordUrl .= "&amp;custom=1";
		if ($this->ExportPdfCustom)
			$this->ExportPdfUrl .= "&amp;custom=1";
		$this->CurrentAction = Param("action"); // Set up current action

		// Setup export options
		$this->setupExportOptions();
		$this->CaseID->setVisibility();
		$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->setVisibility();
		$this->Notes->setVisibility();
		$this->FileLocation->setVisibility();
		$this->_Case->setVisibility();
		$this->CaseEn->Visible = FALSE;
		$this->CaseSortID->setVisibility();
		$this->CaseRegisteredDate->setVisibility();
		$this->CaseStatusID->setVisibility();
		$this->ParentCaseID->setVisibility();
		$this->FileNumber2->Visible = FALSE;
		$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);

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

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

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

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

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

		// Set up lookup cache
		$this->setupLookupOptions($this->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);

		// Check modal
		if ($this->IsModal)
			$SkipHeaderFooter = TRUE;

		// Load current record
		$loadCurrentRecord = FALSE;
		$returnUrl = "";
		$matchRecord = FALSE;

		// Set up master/detail parameters
		$this->setupMasterParms();
		if ($this->isPageRequest()) { // Validate request
			if (Get("CaseID") !== NULL) {
				$this->CaseID->setQueryStringValue(Get("CaseID"));
				$this->RecKey["CaseID"] = $this->CaseID->QueryStringValue;
			} elseif (IsApi() && Key(0) != NULL) {
				$this->CaseID->setQueryStringValue(Key(0));
				$this->RecKey["CaseID"] = $this->CaseID->QueryStringValue;
			} elseif (Post("CaseID") !== NULL) {
				$this->CaseID->setFormValue(Post("CaseID"));
				$this->RecKey["CaseID"] = $this->CaseID->FormValue;
			} elseif (IsApi() && Route(2) != NULL) {
				$this->CaseID->setFormValue(Route(2));
				$this->RecKey["CaseID"] = $this->CaseID->FormValue;
			} else {
				$loadCurrentRecord = TRUE;
			}

			// Get action
			$this->CurrentAction = "show"; // Display
			switch ($this->CurrentAction) {
				case "show": // Get a record to display
					$this->StartRec = 1; // Initialize start position
					if ($this->Recordset = $this->loadRecordset()) // Load records
						$this->TotalRecs = $this->Recordset->RecordCount(); // Get record count
					if ($this->TotalRecs <= 0) { // No record found
						if ($this->getSuccessMessage() == "" && $this->getFailureMessage() == "")
							$this->setFailureMessage($Language->phrase("NoRecord")); // Set no record message
						$this->terminate("caseslist.php"); // Return to list page
					} elseif ($loadCurrentRecord) { // Load current record position
						$this->setupStartRec(); // Set up start record position

						// Point to current record
						if ($this->StartRec <= $this->TotalRecs) {
							$matchRecord = TRUE;
							$this->Recordset->move($this->StartRec - 1);
						}
					} else { // Match key values
						while (!$this->Recordset->EOF) {
							if (SameString($this->CaseID->CurrentValue, $this->Recordset->fields('CaseID'))) {
								$this->setStartRecordNumber($this->StartRec); // Save record position
								$matchRecord = TRUE;
								break;
							} else {
								$this->StartRec++;
								$this->Recordset->moveNext();
							}
						}
					}
					if (!$matchRecord) {
						if ($this->getSuccessMessage() == "" && $this->getFailureMessage() == "")
							$this->setFailureMessage($Language->phrase("NoRecord")); // Set no record message
						$returnUrl = "caseslist.php"; // No matching record, return to list
					} else {
						$this->loadRowValues($this->Recordset); // Load row values
					}
			}

			// Export data only
			if (!$this->CustomExport && in_array($this->Export, array_keys($EXPORT))) {
				$this->exportData();
				$this->terminate();
			}
		} else {
			$returnUrl = "caseslist.php"; // Not page request, return to list
		}
		if ($returnUrl <> "") {
			$this->terminate($returnUrl);
			return;
		}

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

		// Render row
		$this->RowType = ROWTYPE_VIEW;
		$this->resetAttributes();
		$this->renderRow();

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

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

	// Set up other options
	protected function setupOtherOptions()
	{
		global $Language, $Security;
		$options = &$this->OtherOptions;
		$option = &$options["action"];

		// Add
		$item = &$option->add("add");
		$addcaption = HtmlTitle($Language->phrase("ViewPageAddLink"));
		if ($this->IsModal) // Modal
			$item->Body = "<a class=\"ew-action ew-add\" title=\"" . $addcaption . "\" data-caption=\"" . $addcaption . "\" href=\"javascript:void(0);\" onclick=\"ew.modalDialogShow({lnk:this,url:'" . HtmlEncode($this->AddUrl) . "'});\">" . $Language->phrase("ViewPageAddLink") . "</a>";
		else
			$item->Body = "<a class=\"ew-action ew-add\" title=\"" . $addcaption . "\" data-caption=\"" . $addcaption . "\" href=\"" . HtmlEncode($this->AddUrl) . "\">" . $Language->phrase("ViewPageAddLink") . "</a>";
		$item->Visible = ($this->AddUrl <> "" && $Security->canAdd());

		// Edit
		$item = &$option->add("edit");
		$editcaption = HtmlTitle($Language->phrase("ViewPageEditLink"));
		if ($this->IsModal) // Modal
			$item->Body = "<a class=\"ew-action ew-edit\" title=\"" . $editcaption . "\" data-caption=\"" . $editcaption . "\" href=\"javascript:void(0);\" onclick=\"ew.modalDialogShow({lnk:this,url:'" . HtmlEncode($this->EditUrl) . "'});\">" . $Language->phrase("ViewPageEditLink") . "</a>";
		else
			$item->Body = "<a class=\"ew-action ew-edit\" title=\"" . $editcaption . "\" data-caption=\"" . $editcaption . "\" href=\"" . HtmlEncode($this->EditUrl) . "\">" . $Language->phrase("ViewPageEditLink") . "</a>";
		$item->Visible = ($this->EditUrl <> "" && $Security->canEdit());

		// Copy
		$item = &$option->add("copy");
		$copycaption = HtmlTitle($Language->phrase("ViewPageCopyLink"));
		if ($this->IsModal) // Modal
			$item->Body = "<a class=\"ew-action ew-copy\" title=\"" . $copycaption . "\" data-caption=\"" . $copycaption . "\" href=\"javascript:void(0);\" onclick=\"ew.modalDialogShow({lnk:this,btn:'AddBtn',url:'" . HtmlEncode($this->CopyUrl) . "'});\">" . $Language->phrase("ViewPageCopyLink") . "</a>";
		else
			$item->Body = "<a class=\"ew-action ew-copy\" title=\"" . $copycaption . "\" data-caption=\"" . $copycaption . "\" href=\"" . HtmlEncode($this->CopyUrl) . "\">" . $Language->phrase("ViewPageCopyLink") . "</a>";
		$item->Visible = ($this->CopyUrl <> "" && $Security->canAdd());

		// Delete
		$item = &$option->add("delete");
		if ($this->IsModal) // Handle as inline delete
			$item->Body = "<a onclick=\"return ew.confirmDelete(this);\" class=\"ew-action ew-delete\" title=\"" . HtmlTitle($Language->phrase("ViewPageDeleteLink")) . "\" data-caption=\"" . HtmlTitle($Language->phrase("ViewPageDeleteLink")) . "\" href=\"" . HtmlEncode(UrlAddQuery($this->DeleteUrl, "action=1")) . "\">" . $Language->phrase("ViewPageDeleteLink") . "</a>";
		else
			$item->Body = "<a class=\"ew-action ew-delete\" title=\"" . HtmlTitle($Language->phrase("ViewPageDeleteLink")) . "\" data-caption=\"" . HtmlTitle($Language->phrase("ViewPageDeleteLink")) . "\" href=\"" . HtmlEncode($this->DeleteUrl) . "\">" . $Language->phrase("ViewPageDeleteLink") . "</a>";
		$item->Visible = ($this->DeleteUrl <> "" && $Security->canDelete());
		$option = &$options["detail"];
		$detailTableLink = "";
		$detailViewTblVar = "";
		$detailCopyTblVar = "";
		$detailEditTblVar = "";

		// "detail_hearings"
		$item = &$option->add("detail_hearings");
		$body = $Language->phrase("ViewPageDetailLink") . $Language->TablePhrase("hearings", "TblCaption");
		$body .= str_replace("%c", $this->hearings_Count, $Language->phrase("DetailCount"));
		$body = "<a class=\"btn btn-default ew-row-link ew-detail\" data-action=\"list\" href=\"" . HtmlEncode("hearingslist.php?" . TABLE_SHOW_MASTER . "=cases&fk_CaseID=" . urlencode(strval($this->CaseID->CurrentValue)) . "") . "\">" . $body . "</a>";
		$links = "";
		if (!isset($GLOBALS["hearings_grid"]))
			$GLOBALS["hearings_grid"] = new hearings_grid();
		if ($GLOBALS["hearings_grid"]->DetailView && $Security->canView() && $Security->allowView(CurrentProjectID() . 'hearings')) {
			$links .= "<li><a class=\"ew-row-link ew-detail-view\" data-action=\"view\" data-caption=\"" . HtmlTitle($Language->phrase("MasterDetailViewLink")) . "\" href=\"" . HtmlEncode($this->getViewUrl(TABLE_SHOW_DETAIL . "=hearings")) . "\">" . HtmlImageAndText($Language->phrase("MasterDetailViewLink")) . "</a></li>";
			if ($detailViewTblVar <> "")
				$detailViewTblVar .= ",";
			$detailViewTblVar .= "hearings";
		}
		if ($GLOBALS["hearings_grid"]->DetailEdit && $Security->canEdit() && $Security->allowEdit(CurrentProjectID() . 'hearings')) {
			$links .= "<li><a class=\"ew-row-link ew-detail-edit\" data-action=\"edit\" data-caption=\"" . HtmlTitle($Language->phrase("MasterDetailEditLink")) . "\" href=\"" . HtmlEncode($this->getEditUrl(TABLE_SHOW_DETAIL . "=hearings")) . "\">" . HtmlImageAndText($Language->phrase("MasterDetailEditLink")) . "</a></li>";
			if ($detailEditTblVar <> "")
				$detailEditTblVar .= ",";
			$detailEditTblVar .= "hearings";
		}
		if ($GLOBALS["hearings_grid"]->DetailAdd && $Security->canAdd() && $Security->allowAdd(CurrentProjectID() . 'hearings')) {
			$links .= "<li><a class=\"ew-row-link ew-detail-copy\" data-action=\"add\" data-caption=\"" . HtmlTitle($Language->phrase("MasterDetailCopyLink")) . "\" href=\"" . HtmlEncode($this->getCopyUrl(TABLE_SHOW_DETAIL . "=hearings")) . "\">" . HtmlImageAndText($Language->phrase("MasterDetailCopyLink")) . "</a></li>";
			if ($detailCopyTblVar <> "")
				$detailCopyTblVar .= ",";
			$detailCopyTblVar .= "hearings";
		}
		if ($links <> "") {
			$body .= "<button class=\"dropdown-toggle btn btn-default ew-detail\" data-toggle=\"dropdown\"></button>";
			$body .= "<ul class=\"dropdown-menu\">". $links . "</ul>";
		}
		$body = "<div class=\"btn-group btn-group-sm ew-btn-group\">" . $body . "</div>";
		$item->Body = $body;
		$item->Visible = $Security->allowList(CurrentProjectID() . 'hearings');
		if ($item->Visible) {
			if ($detailTableLink <> "")
				$detailTableLink .= ",";
			$detailTableLink .= "hearings";
		}
		if ($this->ShowMultipleDetails)
			$item->Visible = FALSE;

		// "detail_notices"
		$item = &$option->add("detail_notices");
		$body = $Language->phrase("ViewPageDetailLink") . $Language->TablePhrase("notices", "TblCaption");
		$body .= str_replace("%c", $this->notices_Count, $Language->phrase("DetailCount"));
		$body = "<a class=\"btn btn-default ew-row-link ew-detail\" data-action=\"list\" href=\"" . HtmlEncode("noticeslist.php?" . TABLE_SHOW_MASTER . "=cases&fk_CaseID=" . urlencode(strval($this->CaseID->CurrentValue)) . "") . "\">" . $body . "</a>";
		$links = "";
		if (!isset($GLOBALS["notices_grid"]))
			$GLOBALS["notices_grid"] = new notices_grid();
		if ($GLOBALS["notices_grid"]->DetailView && $Security->canView() && $Security->allowView(CurrentProjectID() . 'notices')) {
			$links .= "<li><a class=\"ew-row-link ew-detail-view\" data-action=\"view\" data-caption=\"" . HtmlTitle($Language->phrase("MasterDetailViewLink")) . "\" href=\"" . HtmlEncode($this->getViewUrl(TABLE_SHOW_DETAIL . "=notices")) . "\">" . HtmlImageAndText($Language->phrase("MasterDetailViewLink")) . "</a></li>";
			if ($detailViewTblVar <> "")
				$detailViewTblVar .= ",";
			$detailViewTblVar .= "notices";
		}
		if ($GLOBALS["notices_grid"]->DetailEdit && $Security->canEdit() && $Security->allowEdit(CurrentProjectID() . 'notices')) {
			$links .= "<li><a class=\"ew-row-link ew-detail-edit\" data-action=\"edit\" data-caption=\"" . HtmlTitle($Language->phrase("MasterDetailEditLink")) . "\" href=\"" . HtmlEncode($this->getEditUrl(TABLE_SHOW_DETAIL . "=notices")) . "\">" . HtmlImageAndText($Language->phrase("MasterDetailEditLink")) . "</a></li>";
			if ($detailEditTblVar <> "")
				$detailEditTblVar .= ",";
			$detailEditTblVar .= "notices";
		}
		if ($GLOBALS["notices_grid"]->DetailAdd && $Security->canAdd() && $Security->allowAdd(CurrentProjectID() . 'notices')) {
			$links .= "<li><a class=\"ew-row-link ew-detail-copy\" data-action=\"add\" data-caption=\"" . HtmlTitle($Language->phrase("MasterDetailCopyLink")) . "\" href=\"" . HtmlEncode($this->getCopyUrl(TABLE_SHOW_DETAIL . "=notices")) . "\">" . HtmlImageAndText($Language->phrase("MasterDetailCopyLink")) . "</a></li>";
			if ($detailCopyTblVar <> "")
				$detailCopyTblVar .= ",";
			$detailCopyTblVar .= "notices";
		}
		if ($links <> "") {
			$body .= "<button class=\"dropdown-toggle btn btn-default ew-detail\" data-toggle=\"dropdown\"></button>";
			$body .= "<ul class=\"dropdown-menu\">". $links . "</ul>";
		}
		$body = "<div class=\"btn-group btn-group-sm ew-btn-group\">" . $body . "</div>";
		$item->Body = $body;
		$item->Visible = $Security->allowList(CurrentProjectID() . 'notices');
		if ($item->Visible) {
			if ($detailTableLink <> "")
				$detailTableLink .= ",";
			$detailTableLink .= "notices";
		}
		if ($this->ShowMultipleDetails)
			$item->Visible = FALSE;

		// "detail_complaints"
		$item = &$option->add("detail_complaints");
		$body = $Language->phrase("ViewPageDetailLink") . $Language->TablePhrase("complaints", "TblCaption");
		$body .= str_replace("%c", $this->complaints_Count, $Language->phrase("DetailCount"));
		$body = "<a class=\"btn btn-default ew-row-link ew-detail\" data-action=\"list\" href=\"" . HtmlEncode("complaintslist.php?" . TABLE_SHOW_MASTER . "=cases&fk_CaseID=" . urlencode(strval($this->CaseID->CurrentValue)) . "") . "\">" . $body . "</a>";
		$links = "";
		if (!isset($GLOBALS["complaints_grid"]))
			$GLOBALS["complaints_grid"] = new complaints_grid();
		if ($GLOBALS["complaints_grid"]->DetailView && $Security->canView() && $Security->allowView(CurrentProjectID() . 'complaints')) {
			$links .= "<li><a class=\"ew-row-link ew-detail-view\" data-action=\"view\" data-caption=\"" . HtmlTitle($Language->phrase("MasterDetailViewLink")) . "\" href=\"" . HtmlEncode($this->getViewUrl(TABLE_SHOW_DETAIL . "=complaints")) . "\">" . HtmlImageAndText($Language->phrase("MasterDetailViewLink")) . "</a></li>";
			if ($detailViewTblVar <> "")
				$detailViewTblVar .= ",";
			$detailViewTblVar .= "complaints";
		}
		if ($GLOBALS["complaints_grid"]->DetailEdit && $Security->canEdit() && $Security->allowEdit(CurrentProjectID() . 'complaints')) {
			$links .= "<li><a class=\"ew-row-link ew-detail-edit\" data-action=\"edit\" data-caption=\"" . HtmlTitle($Language->phrase("MasterDetailEditLink")) . "\" href=\"" . HtmlEncode($this->getEditUrl(TABLE_SHOW_DETAIL . "=complaints")) . "\">" . HtmlImageAndText($Language->phrase("MasterDetailEditLink")) . "</a></li>";
			if ($detailEditTblVar <> "")
				$detailEditTblVar .= ",";
			$detailEditTblVar .= "complaints";
		}
		if ($GLOBALS["complaints_grid"]->DetailAdd && $Security->canAdd() && $Security->allowAdd(CurrentProjectID() . 'complaints')) {
			$links .= "<li><a class=\"ew-row-link ew-detail-copy\" data-action=\"add\" data-caption=\"" . HtmlTitle($Language->phrase("MasterDetailCopyLink")) . "\" href=\"" . HtmlEncode($this->getCopyUrl(TABLE_SHOW_DETAIL . "=complaints")) . "\">" . HtmlImageAndText($Language->phrase("MasterDetailCopyLink")) . "</a></li>";
			if ($detailCopyTblVar <> "")
				$detailCopyTblVar .= ",";
			$detailCopyTblVar .= "complaints";
		}
		if ($links <> "") {
			$body .= "<button class=\"dropdown-toggle btn btn-default ew-detail\" data-toggle=\"dropdown\"></button>";
			$body .= "<ul class=\"dropdown-menu\">". $links . "</ul>";
		}
		$body = "<div class=\"btn-group btn-group-sm ew-btn-group\">" . $body . "</div>";
		$item->Body = $body;
		$item->Visible = $Security->allowList(CurrentProjectID() . 'complaints');
		if ($item->Visible) {
			if ($detailTableLink <> "")
				$detailTableLink .= ",";
			$detailTableLink .= "complaints";
		}
		if ($this->ShowMultipleDetails)
			$item->Visible = FALSE;

		// "detail_notifications"
		$item = &$option->add("detail_notifications");
		$body = $Language->phrase("ViewPageDetailLink") . $Language->TablePhrase("notifications", "TblCaption");
		$body .= str_replace("%c", $this->notifications_Count, $Language->phrase("DetailCount"));
		$body = "<a class=\"btn btn-default ew-row-link ew-detail\" data-action=\"list\" href=\"" . HtmlEncode("notificationslist.php?" . TABLE_SHOW_MASTER . "=cases&fk_CaseID=" . urlencode(strval($this->CaseID->CurrentValue)) . "") . "\">" . $body . "</a>";
		$links = "";
		if (!isset($GLOBALS["notifications_grid"]))
			$GLOBALS["notifications_grid"] = new notifications_grid();
		if ($GLOBALS["notifications_grid"]->DetailView && $Security->canView() && $Security->allowView(CurrentProjectID() . 'notifications')) {
			$links .= "<li><a class=\"ew-row-link ew-detail-view\" data-action=\"view\" data-caption=\"" . HtmlTitle($Language->phrase("MasterDetailViewLink")) . "\" href=\"" . HtmlEncode($this->getViewUrl(TABLE_SHOW_DETAIL . "=notifications")) . "\">" . HtmlImageAndText($Language->phrase("MasterDetailViewLink")) . "</a></li>";
			if ($detailViewTblVar <> "")
				$detailViewTblVar .= ",";
			$detailViewTblVar .= "notifications";
		}
		if ($GLOBALS["notifications_grid"]->DetailEdit && $Security->canEdit() && $Security->allowEdit(CurrentProjectID() . 'notifications')) {
			$links .= "<li><a class=\"ew-row-link ew-detail-edit\" data-action=\"edit\" data-caption=\"" . HtmlTitle($Language->phrase("MasterDetailEditLink")) . "\" href=\"" . HtmlEncode($this->getEditUrl(TABLE_SHOW_DETAIL . "=notifications")) . "\">" . HtmlImageAndText($Language->phrase("MasterDetailEditLink")) . "</a></li>";
			if ($detailEditTblVar <> "")
				$detailEditTblVar .= ",";
			$detailEditTblVar .= "notifications";
		}
		if ($GLOBALS["notifications_grid"]->DetailAdd && $Security->canAdd() && $Security->allowAdd(CurrentProjectID() . 'notifications')) {
			$links .= "<li><a class=\"ew-row-link ew-detail-copy\" data-action=\"add\" data-caption=\"" . HtmlTitle($Language->phrase("MasterDetailCopyLink")) . "\" href=\"" . HtmlEncode($this->getCopyUrl(TABLE_SHOW_DETAIL . "=notifications")) . "\">" . HtmlImageAndText($Language->phrase("MasterDetailCopyLink")) . "</a></li>";
			if ($detailCopyTblVar <> "")
				$detailCopyTblVar .= ",";
			$detailCopyTblVar .= "notifications";
		}
		if ($links <> "") {
			$body .= "<button class=\"dropdown-toggle btn btn-default ew-detail\" data-toggle=\"dropdown\"></button>";
			$body .= "<ul class=\"dropdown-menu\">". $links . "</ul>";
		}
		$body = "<div class=\"btn-group btn-group-sm ew-btn-group\">" . $body . "</div>";
		$item->Body = $body;
		$item->Visible = $Security->allowList(CurrentProjectID() . 'notifications');
		if ($item->Visible) {
			if ($detailTableLink <> "")
				$detailTableLink .= ",";
			$detailTableLink .= "notifications";
		}
		if ($this->ShowMultipleDetails)
			$item->Visible = FALSE;

		// "detail_attachments"
		$item = &$option->add("detail_attachments");
		$body = $Language->phrase("ViewPageDetailLink") . $Language->TablePhrase("attachments", "TblCaption");
		$body .= str_replace("%c", $this->attachments_Count, $Language->phrase("DetailCount"));
		$body = "<a class=\"btn btn-default ew-row-link ew-detail\" data-action=\"list\" href=\"" . HtmlEncode("attachmentslist.php?" . TABLE_SHOW_MASTER . "=cases&fk_CaseID=" . urlencode(strval($this->CaseID->CurrentValue)) . "") . "\">" . $body . "</a>";
		$links = "";
		if (!isset($GLOBALS["attachments_grid"]))
			$GLOBALS["attachments_grid"] = new attachments_grid();
		if ($GLOBALS["attachments_grid"]->DetailView && $Security->canView() && $Security->allowView(CurrentProjectID() . 'attachments')) {
			$links .= "<li><a class=\"ew-row-link ew-detail-view\" data-action=\"view\" data-caption=\"" . HtmlTitle($Language->phrase("MasterDetailViewLink")) . "\" href=\"" . HtmlEncode($this->getViewUrl(TABLE_SHOW_DETAIL . "=attachments")) . "\">" . HtmlImageAndText($Language->phrase("MasterDetailViewLink")) . "</a></li>";
			if ($detailViewTblVar <> "")
				$detailViewTblVar .= ",";
			$detailViewTblVar .= "attachments";
		}
		if ($GLOBALS["attachments_grid"]->DetailEdit && $Security->canEdit() && $Security->allowEdit(CurrentProjectID() . 'attachments')) {
			$links .= "<li><a class=\"ew-row-link ew-detail-edit\" data-action=\"edit\" data-caption=\"" . HtmlTitle($Language->phrase("MasterDetailEditLink")) . "\" href=\"" . HtmlEncode($this->getEditUrl(TABLE_SHOW_DETAIL . "=attachments")) . "\">" . HtmlImageAndText($Language->phrase("MasterDetailEditLink")) . "</a></li>";
			if ($detailEditTblVar <> "")
				$detailEditTblVar .= ",";
			$detailEditTblVar .= "attachments";
		}
		if ($GLOBALS["attachments_grid"]->DetailAdd && $Security->canAdd() && $Security->allowAdd(CurrentProjectID() . 'attachments')) {
			$links .= "<li><a class=\"ew-row-link ew-detail-copy\" data-action=\"add\" data-caption=\"" . HtmlTitle($Language->phrase("MasterDetailCopyLink")) . "\" href=\"" . HtmlEncode($this->getCopyUrl(TABLE_SHOW_DETAIL . "=attachments")) . "\">" . HtmlImageAndText($Language->phrase("MasterDetailCopyLink")) . "</a></li>";
			if ($detailCopyTblVar <> "")
				$detailCopyTblVar .= ",";
			$detailCopyTblVar .= "attachments";
		}
		if ($links <> "") {
			$body .= "<button class=\"dropdown-toggle btn btn-default ew-detail\" data-toggle=\"dropdown\"></button>";
			$body .= "<ul class=\"dropdown-menu\">". $links . "</ul>";
		}
		$body = "<div class=\"btn-group btn-group-sm ew-btn-group\">" . $body . "</div>";
		$item->Body = $body;
		$item->Visible = $Security->allowList(CurrentProjectID() . 'attachments');
		if ($item->Visible) {
			if ($detailTableLink <> "")
				$detailTableLink .= ",";
			$detailTableLink .= "attachments";
		}
		if ($this->ShowMultipleDetails)
			$item->Visible = FALSE;

		// Multiple details
		if ($this->ShowMultipleDetails) {
			$body = "<div class=\"btn-group btn-group-sm ew-btn-group\">";
			$links = "";
			if ($detailViewTblVar <> "") {
				$links .= "<li><a class=\"ew-row-link ew-detail-view\" data-action=\"view\" data-caption=\"" . HtmlTitle($Language->phrase("MasterDetailViewLink")) . "\" href=\"" . HtmlEncode($this->getViewUrl(TABLE_SHOW_DETAIL . "=" . $detailViewTblVar)) . "\">" . HtmlImageAndText($Language->phrase("MasterDetailViewLink")) . "</a></li>";
			}
			if ($detailEditTblVar <> "") {
				$links .= "<li><a class=\"ew-row-link ew-detail-edit\" data-action=\"edit\" data-caption=\"" . HtmlTitle($Language->phrase("MasterDetailEditLink")) . "\" href=\"" . HtmlEncode($this->getEditUrl(TABLE_SHOW_DETAIL . "=" . $detailEditTblVar)) . "\">" . HtmlImageAndText($Language->phrase("MasterDetailEditLink")) . "</a></li>";
			}
			if ($detailCopyTblVar <> "") {
				$links .= "<li><a class=\"ew-row-link ew-detail-copy\" data-action=\"add\" data-caption=\"" . HtmlTitle($Language->phrase("MasterDetailCopyLink")) . "\" href=\"" . HtmlEncode($this->getCopyUrl(TABLE_SHOW_DETAIL . "=" . $detailCopyTblVar)) . "\">" . HtmlImageAndText($Language->phrase("MasterDetailCopyLink")) . "</a></li>";
			}
			if ($links <> "") {
				$body .= "<button class=\"dropdown-toggle btn btn-default ew-master-detail\" title=\"" . HtmlTitle($Language->phrase("MultipleMasterDetails")) . "\" data-toggle=\"dropdown\">" . $Language->phrase("MultipleMasterDetails") . "</button>";
				$body .= "<ul class=\"dropdown-menu ew-menu\">". $links . "</ul>";
			}
			$body .= "</div>";

			// Multiple details
			$opt = &$option->add("details");
			$opt->Body = $body;
		}

		// Set up detail default
		$option = &$options["detail"];
		$options["detail"]->DropDownButtonPhrase = $Language->phrase("ButtonDetails");
		$ar = explode(",", $detailTableLink);
		$cnt = count($ar);
		$option->UseDropDownButton = ($cnt > 1);
		$option->UseButtonGroup = TRUE;
		$item = &$option->add($option->GroupOptionName);
		$item->Body = "";
		$item->Visible = FALSE;

		// Set up action default
		$option = &$options["action"];
		$option->DropDownButtonPhrase = $Language->phrase("ButtonActions");
		$option->UseDropDownButton = FALSE;
		$option->UseButtonGroup = TRUE;
		$item = &$option->add($option->GroupOptionName);
		$item->Body = "";
		$item->Visible = FALSE;
	}

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

	// 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;
		if ($this->AuditTrailOnView)
			$this->writeAuditTrailOnView($row);
		$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']);
		if (!isset($GLOBALS["hearings_grid"]))
			$GLOBALS["hearings_grid"] = new hearings_grid();
		$detailFilter = $GLOBALS["hearings"]->sqlDetailFilter_cases();
		$detailFilter = str_replace("@CaseID@", AdjustSql($this->CaseID->DbValue, "DB"), $detailFilter);
		$GLOBALS["hearings"]->setCurrentMasterTable("cases");
		$detailFilter = $GLOBALS["hearings"]->applyUserIDFilters($detailFilter);
		$this->hearings_Count = $GLOBALS["hearings"]->loadRecordCount($detailFilter);
		if (!isset($GLOBALS["notices_grid"]))
			$GLOBALS["notices_grid"] = new notices_grid();
		$detailFilter = $GLOBALS["notices"]->sqlDetailFilter_cases();
		$detailFilter = str_replace("@CaseID@", AdjustSql($this->CaseID->DbValue, "DB"), $detailFilter);
		$GLOBALS["notices"]->setCurrentMasterTable("cases");
		$detailFilter = $GLOBALS["notices"]->applyUserIDFilters($detailFilter);
		$this->notices_Count = $GLOBALS["notices"]->loadRecordCount($detailFilter);
		if (!isset($GLOBALS["complaints_grid"]))
			$GLOBALS["complaints_grid"] = new complaints_grid();
		$detailFilter = $GLOBALS["complaints"]->sqlDetailFilter_cases();
		$detailFilter = str_replace("@CaseID@", AdjustSql($this->CaseID->DbValue, "DB"), $detailFilter);
		$GLOBALS["complaints"]->setCurrentMasterTable("cases");
		$detailFilter = $GLOBALS["complaints"]->applyUserIDFilters($detailFilter);
		$this->complaints_Count = $GLOBALS["complaints"]->loadRecordCount($detailFilter);
		if (!isset($GLOBALS["notifications_grid"]))
			$GLOBALS["notifications_grid"] = new notifications_grid();
		$detailFilter = $GLOBALS["notifications"]->sqlDetailFilter_cases();
		$detailFilter = str_replace("@CaseID@", AdjustSql($this->CaseID->DbValue, "DB"), $detailFilter);
		$GLOBALS["notifications"]->setCurrentMasterTable("cases");
		$detailFilter = $GLOBALS["notifications"]->applyUserIDFilters($detailFilter);
		$this->notifications_Count = $GLOBALS["notifications"]->loadRecordCount($detailFilter);
		if (!isset($GLOBALS["attachments_grid"]))
			$GLOBALS["attachments_grid"] = new attachments_grid();
		$detailFilter = $GLOBALS["attachments"]->sqlDetailFilter_cases();
		$detailFilter = str_replace("@CaseID@", AdjustSql($this->CaseID->DbValue, "DB"), $detailFilter);
		$GLOBALS["attachments"]->setCurrentMasterTable("cases");
		$detailFilter = $GLOBALS["attachments"]->applyUserIDFilters($detailFilter);
		$this->attachments_Count = $GLOBALS["attachments"]->loadRecordCount($detailFilter);
	}

	// 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
		$this->AddUrl = $this->getAddUrl();
		$this->EditUrl = $this->getEditUrl();
		$this->CopyUrl = $this->getCopyUrl();
		$this->DeleteUrl = $this->getDeleteUrl();
		$this->ListUrl = $this->getListUrl();
		$this->setupOtherOptions();

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

		// Common render codes for all row types
		// CaseID
		// ClientID
		// LitigantID
		// CaseTypeID
		// CourtID
		// CaseNumber
		// FileNumber
		// EnvelopeNumber
		// ClientStatusID
		// LitigantStatusID
		// CourtTypeID
		// CourtGenderID
		// JudgeID
		// Notes
		// FileLocation
		// Case
		// CaseEn
		// CaseSortID
		// CaseRegisteredDate
		// CaseStatusID
		// ParentCaseID
		// FileNumber2
		// UserID
		// CreatedBy
		// CreatedDate
		// UpdatedBy
		// UpdatedDate
		// CaseTypeConv
		// CaseConv
		// ClientStatusConv
		// LitigantStatusConv
		// ClientNameConv
		// LitigantNameConv
		// ClientNameConvFiles
		// LitigantNameConvFiles
		// CaseTypeConvFiles
		// CourtConvFiles
		// FileNumberConvFiles
		// CaseNumberConvFiles
		// NotesConvFiles

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

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

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

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

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

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

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

			// Case
			$this->_Case->LinkCustomAttributes = "";
			$this->_Case->HrefValue = "";
			$this->_Case->TooltipValue = "";

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

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

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

			// ParentCaseID
			$this->ParentCaseID->LinkCustomAttributes = "";
			$this->ParentCaseID->HrefValue = "";
			$this->ParentCaseID->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();
	}

	// Get export HTML tag
	protected function getExportTag($type, $custom = FALSE)
	{
		global $Language;
		if (SameText($type, "excel")) {
			if ($custom)
				return "<a href=\"javascript:void(0);\" class=\"ew-export-link ew-excel\" title=\"" . HtmlEncode($Language->phrase("ExportToExcelText")) . "\" data-caption=\"" . HtmlEncode($Language->phrase("ExportToExcelText")) . "\" onclick=\"ew.export(document.fcasesview,'" . $this->ExportExcelUrl . "','excel',true);\">" . $Language->phrase("ExportToExcel") . "</a>";
			else
				return "<a href=\"" . $this->ExportExcelUrl . "\" class=\"ew-export-link ew-excel\" title=\"" . HtmlEncode($Language->phrase("ExportToExcelText")) . "\" data-caption=\"" . HtmlEncode($Language->phrase("ExportToExcelText")) . "\">" . $Language->phrase("ExportToExcel") . "</a>";
		} elseif (SameText($type, "word")) {
			if ($custom)
				return "<a href=\"javascript:void(0);\" class=\"ew-export-link ew-word\" title=\"" . HtmlEncode($Language->phrase("ExportToWordText")) . "\" data-caption=\"" . HtmlEncode($Language->phrase("ExportToWordText")) . "\" onclick=\"ew.export(document.fcasesview,'" . $this->ExportWordUrl . "','word',true);\">" . $Language->phrase("ExportToWord") . "</a>";
			else
				return "<a href=\"" . $this->ExportWordUrl . "\" class=\"ew-export-link ew-word\" title=\"" . HtmlEncode($Language->phrase("ExportToWordText")) . "\" data-caption=\"" . HtmlEncode($Language->phrase("ExportToWordText")) . "\">" . $Language->phrase("ExportToWord") . "</a>";
		} elseif (SameText($type, "pdf")) {
			if ($custom)
				return "<a href=\"javascript:void(0);\" class=\"ew-export-link ew-pdf\" title=\"" . HtmlEncode($Language->phrase("ExportToPDFText")) . "\" data-caption=\"" . HtmlEncode($Language->phrase("ExportToPDFText")) . "\" onclick=\"ew.export(document.fcasesview,'" . $this->ExportPdfUrl . "','pdf',true);\">" . $Language->phrase("ExportToPDF") . "</a>";
			else
				return "<a href=\"" . $this->ExportPdfUrl . "\" class=\"ew-export-link ew-pdf\" title=\"" . HtmlEncode($Language->phrase("ExportToPDFText")) . "\" data-caption=\"" . HtmlEncode($Language->phrase("ExportToPDFText")) . "\">" . $Language->phrase("ExportToPDF") . "</a>";
		} elseif (SameText($type, "html")) {
			return "<a href=\"" . $this->ExportHtmlUrl . "\" class=\"ew-export-link ew-html\" title=\"" . HtmlEncode($Language->phrase("ExportToHtmlText")) . "\" data-caption=\"" . HtmlEncode($Language->phrase("ExportToHtmlText")) . "\">" . $Language->phrase("ExportToHtml") . "</a>";
		} elseif (SameText($type, "xml")) {
			return "<a href=\"" . $this->ExportXmlUrl . "\" class=\"ew-export-link ew-xml\" title=\"" . HtmlEncode($Language->phrase("ExportToXmlText")) . "\" data-caption=\"" . HtmlEncode($Language->phrase("ExportToXmlText")) . "\">" . $Language->phrase("ExportToXml") . "</a>";
		} elseif (SameText($type, "csv")) {
			return "<a href=\"" . $this->ExportCsvUrl . "\" class=\"ew-export-link ew-csv\" title=\"" . HtmlEncode($Language->phrase("ExportToCsvText")) . "\" data-caption=\"" . HtmlEncode($Language->phrase("ExportToCsvText")) . "\">" . $Language->phrase("ExportToCsv") . "</a>";
		} elseif (SameText($type, "print")) {
			return "<a href=\"" . $this->ExportPrintUrl . "\" class=\"ew-export-link ew-print\" title=\"" . HtmlEncode($Language->phrase("PrinterFriendlyText")) . "\" data-caption=\"" . HtmlEncode($Language->phrase("PrinterFriendlyText")) . "\">" . $Language->phrase("PrinterFriendly") . "</a>";
		}
	}

	// Set up export options
	protected function setupExportOptions()
	{
		global $Language;

		// Printer friendly
		$item = &$this->ExportOptions->add("print");
		$item->Body = $this->getExportTag("print");
		$item->Visible = TRUE;

		// Export to Excel
		$item = &$this->ExportOptions->add("excel");
		$item->Body = $this->getExportTag("excel");
		$item->Visible = TRUE;

		// Export to Word
		$item = &$this->ExportOptions->add("word");
		$item->Body = $this->getExportTag("word");
		$item->Visible = TRUE;

		// Export to Html
		$item = &$this->ExportOptions->add("html");
		$item->Body = $this->getExportTag("html");
		$item->Visible = TRUE;

		// Export to Xml
		$item = &$this->ExportOptions->add("xml");
		$item->Body = $this->getExportTag("xml");
		$item->Visible = FALSE;

		// Export to Csv
		$item = &$this->ExportOptions->add("csv");
		$item->Body = $this->getExportTag("csv");
		$item->Visible = TRUE;

		// Export to Pdf
		$item = &$this->ExportOptions->add("pdf");
		$item->Body = $this->getExportTag("pdf");
		$item->Visible = TRUE;

		// Export to Email
		$item = &$this->ExportOptions->add("email");
		$url = "";
		$item->Body = "<button id=\"emf_cases\" class=\"ew-export-link ew-email\" title=\"" . $Language->phrase("ExportToEmailText") . "\" data-caption=\"" . $Language->phrase("ExportToEmailText") . "\" onclick=\"ew.emailDialogShow({lnk:'emf_cases',hdr:ew.language.phrase('ExportToEmailText'),f:document.fcasesview,key:" . ArrayToJsonAttribute($this->RecKey) . ",sel:false" . $url . "});\">" . $Language->phrase("ExportToEmail") . "</button>";
		$item->Visible = TRUE;

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

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

		// Hide options for export
		if ($this->isExport())
			$this->ExportOptions->hideAllOptions();
	}

	/**
	 * Export data in HTML/CSV/Word/Excel/XML/Email/PDF format
	 *
	 * @param boolean $return Return the data rather than output it
	 * @return mixed 
	 */
	public function exportData($return = FALSE)
	{
		global $Language;
		$utf8 = SameText(PROJECT_CHARSET, "utf-8");
		$selectLimit = FALSE;

		// Load recordset
		if ($selectLimit) {
			$this->TotalRecs = $this->listRecordCount();
		} else {
			if (!$this->Recordset)
				$this->Recordset = $this->loadRecordset();
			$rs = &$this->Recordset;
			if ($rs)
				$this->TotalRecs = $rs->RecordCount();
		}
		$this->StartRec = 1;
		$this->setupStartRec(); // Set up start record position

		// Set the last record to display
		if ($this->DisplayRecs <= 0) {
			$this->StopRec = $this->TotalRecs;
		} else {
			$this->StopRec = $this->StartRec + $this->DisplayRecs - 1;
		}
		$this->ExportDoc = GetExportDocument($this, "v");
		$doc = &$this->ExportDoc;
		if (!$doc)
			$this->setFailureMessage($Language->phrase("ExportClassNotFound")); // Export class not found
		if (!$rs || !$doc) {
			RemoveHeader("Content-Type"); // Remove header
			RemoveHeader("Content-Disposition");
			$this->showMessage();
			return;
		}
		if ($selectLimit) {
			$this->StartRec = 1;
			$this->StopRec = $this->DisplayRecs <= 0 ? $this->TotalRecs : $this->DisplayRecs;
		}

		// Call Page Exporting server event
		$this->ExportDoc->ExportCustom = !$this->Page_Exporting();
		$header = $this->PageHeader;
		$this->Page_DataRendering($header);
		$doc->Text .= $header;
		$this->exportDocument($doc, $rs, $this->StartRec, $this->StopRec, "view");

		// Export detail records (hearings)
		if (EXPORT_DETAIL_RECORDS && in_array("hearings", explode(",", $this->getCurrentDetailTable()))) {
			global $hearings;
			if (!isset($hearings))
				$hearings = new hearings();
			$rsdetail = $hearings->loadRs($hearings->getDetailFilter()); // Load detail records
			if ($rsdetail && !$rsdetail->EOF) {
				$exportStyle = $doc->Style;
				$doc->setStyle("h"); // Change to horizontal
				if (!$this->isExport("csv") || EXPORT_DETAIL_RECORDS_FOR_CSV) {
					$doc->exportEmptyRow();
					$detailcnt = $rsdetail->RecordCount();
					$oldtbl = $doc->Table;
					$doc->Table = $hearings;
					$hearings->exportDocument($doc, $rsdetail, 1, $detailcnt);
					$doc->Table = $oldtbl;
				}
				$doc->setStyle($exportStyle); // Restore
				$rsdetail->close();
			}
		}

		// Export detail records (notices)
		if (EXPORT_DETAIL_RECORDS && in_array("notices", explode(",", $this->getCurrentDetailTable()))) {
			global $notices;
			if (!isset($notices))
				$notices = new notices();
			$rsdetail = $notices->loadRs($notices->getDetailFilter()); // Load detail records
			if ($rsdetail && !$rsdetail->EOF) {
				$exportStyle = $doc->Style;
				$doc->setStyle("h"); // Change to horizontal
				if (!$this->isExport("csv") || EXPORT_DETAIL_RECORDS_FOR_CSV) {
					$doc->exportEmptyRow();
					$detailcnt = $rsdetail->RecordCount();
					$oldtbl = $doc->Table;
					$doc->Table = $notices;
					$notices->exportDocument($doc, $rsdetail, 1, $detailcnt);
					$doc->Table = $oldtbl;
				}
				$doc->setStyle($exportStyle); // Restore
				$rsdetail->close();
			}
		}

		// Export detail records (complaints)
		if (EXPORT_DETAIL_RECORDS && in_array("complaints", explode(",", $this->getCurrentDetailTable()))) {
			global $complaints;
			if (!isset($complaints))
				$complaints = new complaints();
			$rsdetail = $complaints->loadRs($complaints->getDetailFilter()); // Load detail records
			if ($rsdetail && !$rsdetail->EOF) {
				$exportStyle = $doc->Style;
				$doc->setStyle("h"); // Change to horizontal
				if (!$this->isExport("csv") || EXPORT_DETAIL_RECORDS_FOR_CSV) {
					$doc->exportEmptyRow();
					$detailcnt = $rsdetail->RecordCount();
					$oldtbl = $doc->Table;
					$doc->Table = $complaints;
					$complaints->exportDocument($doc, $rsdetail, 1, $detailcnt);
					$doc->Table = $oldtbl;
				}
				$doc->setStyle($exportStyle); // Restore
				$rsdetail->close();
			}
		}

		// Export detail records (notifications)
		if (EXPORT_DETAIL_RECORDS && in_array("notifications", explode(",", $this->getCurrentDetailTable()))) {
			global $notifications;
			if (!isset($notifications))
				$notifications = new notifications();
			$rsdetail = $notifications->loadRs($notifications->getDetailFilter()); // Load detail records
			if ($rsdetail && !$rsdetail->EOF) {
				$exportStyle = $doc->Style;
				$doc->setStyle("h"); // Change to horizontal
				if (!$this->isExport("csv") || EXPORT_DETAIL_RECORDS_FOR_CSV) {
					$doc->exportEmptyRow();
					$detailcnt = $rsdetail->RecordCount();
					$oldtbl = $doc->Table;
					$doc->Table = $notifications;
					$notifications->exportDocument($doc, $rsdetail, 1, $detailcnt);
					$doc->Table = $oldtbl;
				}
				$doc->setStyle($exportStyle); // Restore
				$rsdetail->close();
			}
		}

		// Export detail records (attachments)
		if (EXPORT_DETAIL_RECORDS && in_array("attachments", explode(",", $this->getCurrentDetailTable()))) {
			global $attachments;
			if (!isset($attachments))
				$attachments = new attachments();
			$rsdetail = $attachments->loadRs($attachments->getDetailFilter()); // Load detail records
			if ($rsdetail && !$rsdetail->EOF) {
				$exportStyle = $doc->Style;
				$doc->setStyle("h"); // Change to horizontal
				if (!$this->isExport("csv") || EXPORT_DETAIL_RECORDS_FOR_CSV) {
					$doc->exportEmptyRow();
					$detailcnt = $rsdetail->RecordCount();
					$oldtbl = $doc->Table;
					$doc->Table = $attachments;
					$attachments->exportDocument($doc, $rsdetail, 1, $detailcnt);
					$doc->Table = $oldtbl;
				}
				$doc->setStyle($exportStyle); // Restore
				$rsdetail->close();
			}
		}
		$footer = $this->PageFooter;
		$this->Page_DataRendered($footer);
		$doc->Text .= $footer;

		// Close recordset
		$rs->close();

		// Call Page Exported server event
		$this->Page_Exported();

		// Export header and footer
		$doc->exportHeaderAndFooter();

		// Clean output buffer (without destroying output buffer)
		$buffer = ob_get_contents(); // Save the output buffer
		if (!DEBUG_ENABLED && $buffer)
			ob_clean();

		// Write debug message if enabled
		if (DEBUG_ENABLED && !$this->isExport("pdf"))
			echo GetDebugMessage();

		// Output data
		if ($this->isExport("email")) {
			if ($return)
				return $doc->Text; // Return email content
			else
				echo $this->exportEmail($doc->Text); // Send email
		} else {
			$doc->export();
			if ($return) {
				RemoveHeader("Content-Type"); // Remove header
				RemoveHeader("Content-Disposition");
				$content = ob_get_contents();
				if ($content)
					ob_clean();
				if ($buffer)
					echo $buffer; // Resume the output buffer
				return $content;
			}
		}
	}

	// Export email
	protected function exportEmail($emailContent)
	{
		global $TempImages, $Language;
		$sender = Post("sender", "");
		$recipient = Post("recipient", "");
		$cc = Post("cc", "");
		$bcc = Post("bcc", "");

		// Subject
		$subject = Post("subject", "");
		$emailSubject = $subject;

		// Message
		$content = Post("message", "");
		$emailMessage = $content;

		// Check sender
		if ($sender == "") {
			return "<p class=\"text-danger\">" . $Language->phrase("EnterSenderEmail") . "</p>";
		}
		if (!CheckEmail($sender)) {
			return "<p class=\"text-danger\">" . $Language->phrase("EnterProperSenderEmail") . "</p>";
		}

		// Check recipient
		if (!CheckEmailList($recipient, MAX_EMAIL_RECIPIENT)) {
			return "<p class=\"text-danger\">" . $Language->phrase("EnterProperRecipientEmail") . "</p>";
		}

		// Check cc
		if (!CheckEmailList($cc, MAX_EMAIL_RECIPIENT)) {
			return "<p class=\"text-danger\">" . $Language->phrase("EnterProperCcEmail") . "</p>";
		}

		// Check bcc
		if (!CheckEmailList($bcc, MAX_EMAIL_RECIPIENT)) {
			return "<p class=\"text-danger\">" . $Language->phrase("EnterProperBccEmail") . "</p>";
		}

		// Check email sent count
		if (!isset($_SESSION[EXPORT_EMAIL_COUNTER]))
			$_SESSION[EXPORT_EMAIL_COUNTER] = 0;
		if ((int)$_SESSION[EXPORT_EMAIL_COUNTER] > MAX_EMAIL_SENT_COUNT) {
			return "<p class=\"text-danger\">" . $Language->phrase("ExceedMaxEmailExport") . "</p>";
		}

		// Send email
		$email = new Email();
		$email->Sender = $sender; // Sender
		$email->Recipient = $recipient; // Recipient
		$email->Cc = $cc; // Cc
		$email->Bcc = $bcc; // Bcc
		$email->Subject = $emailSubject; // Subject
		$email->Format = "html";
		if ($emailMessage <> "")
			$emailMessage = RemoveXss($emailMessage) . "<br><br>";
		foreach ($TempImages as $tmpImage)
			$email->addEmbeddedImage($tmpImage);
		$email->Content = $emailMessage . CleanEmailContent($emailContent); // Content
		$eventArgs = [];
		if ($this->Recordset) {
			$this->RecCnt = $this->StartRec - 1;
			$this->Recordset->moveFirst();
			if ($this->StartRec > 1)
				$this->Recordset->move($this->StartRec - 1);
			$eventArgs["rs"] = &$this->Recordset;
		}
		$emailSent = FALSE;
		if ($this->Email_Sending($email, $eventArgs))
			$emailSent = $email->send();

		// Check email sent status
		if ($emailSent) {

			// Update email sent count
			$_SESSION[EXPORT_EMAIL_COUNTER]++;

			// Sent email success
			return "<p class=\"text-success\">" . $Language->phrase("SendEmailSuccess") . "</p>"; // Set up success message
		} else {

			// Sent email failure
			return "<p class=\"text-danger\">" . $email->SendErrDescription . "</p>";
		}
	}

	// 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);
			$this->setSessionWhere($this->getDetailFilter());

			// 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 detail parms based on QueryString
	protected function setupDetailParms()
	{

		// Get the keys for master table
		if (Get(TABLE_SHOW_DETAIL) !== NULL) {
			$detailTblVar = Get(TABLE_SHOW_DETAIL);
			$this->setCurrentDetailTable($detailTblVar);
		} else {
			$detailTblVar = $this->getCurrentDetailTable();
		}
		if ($detailTblVar <> "") {
			$detailTblVar = explode(",", $detailTblVar);
			if (in_array("hearings", $detailTblVar)) {
				if (!isset($GLOBALS["hearings_grid"]))
					$GLOBALS["hearings_grid"] = new hearings_grid();
				if ($GLOBALS["hearings_grid"]->DetailView) {
					$GLOBALS["hearings_grid"]->CurrentMode = "view";

					// Save current master table to detail table
					$GLOBALS["hearings_grid"]->setCurrentMasterTable($this->TableVar);
					$GLOBALS["hearings_grid"]->setStartRecordNumber(1);
					$GLOBALS["hearings_grid"]->CaseID->IsDetailKey = TRUE;
					$GLOBALS["hearings_grid"]->CaseID->CurrentValue = $this->CaseID->CurrentValue;
					$GLOBALS["hearings_grid"]->CaseID->setSessionValue($GLOBALS["hearings_grid"]->CaseID->CurrentValue);
				}
			}
			if (in_array("notices", $detailTblVar)) {
				if (!isset($GLOBALS["notices_grid"]))
					$GLOBALS["notices_grid"] = new notices_grid();
				if ($GLOBALS["notices_grid"]->DetailView) {
					$GLOBALS["notices_grid"]->CurrentMode = "view";

					// Save current master table to detail table
					$GLOBALS["notices_grid"]->setCurrentMasterTable($this->TableVar);
					$GLOBALS["notices_grid"]->setStartRecordNumber(1);
					$GLOBALS["notices_grid"]->CaseID->IsDetailKey = TRUE;
					$GLOBALS["notices_grid"]->CaseID->CurrentValue = $this->CaseID->CurrentValue;
					$GLOBALS["notices_grid"]->CaseID->setSessionValue($GLOBALS["notices_grid"]->CaseID->CurrentValue);
				}
			}
			if (in_array("complaints", $detailTblVar)) {
				if (!isset($GLOBALS["complaints_grid"]))
					$GLOBALS["complaints_grid"] = new complaints_grid();
				if ($GLOBALS["complaints_grid"]->DetailView) {
					$GLOBALS["complaints_grid"]->CurrentMode = "view";

					// Save current master table to detail table
					$GLOBALS["complaints_grid"]->setCurrentMasterTable($this->TableVar);
					$GLOBALS["complaints_grid"]->setStartRecordNumber(1);
					$GLOBALS["complaints_grid"]->CaseID->IsDetailKey = TRUE;
					$GLOBALS["complaints_grid"]->CaseID->CurrentValue = $this->CaseID->CurrentValue;
					$GLOBALS["complaints_grid"]->CaseID->setSessionValue($GLOBALS["complaints_grid"]->CaseID->CurrentValue);
				}
			}
			if (in_array("notifications", $detailTblVar)) {
				if (!isset($GLOBALS["notifications_grid"]))
					$GLOBALS["notifications_grid"] = new notifications_grid();
				if ($GLOBALS["notifications_grid"]->DetailView) {
					$GLOBALS["notifications_grid"]->CurrentMode = "view";

					// Save current master table to detail table
					$GLOBALS["notifications_grid"]->setCurrentMasterTable($this->TableVar);
					$GLOBALS["notifications_grid"]->setStartRecordNumber(1);
					$GLOBALS["notifications_grid"]->CaseID->IsDetailKey = TRUE;
					$GLOBALS["notifications_grid"]->CaseID->CurrentValue = $this->CaseID->CurrentValue;
					$GLOBALS["notifications_grid"]->CaseID->setSessionValue($GLOBALS["notifications_grid"]->CaseID->CurrentValue);
				}
			}
			if (in_array("attachments", $detailTblVar)) {
				if (!isset($GLOBALS["attachments_grid"]))
					$GLOBALS["attachments_grid"] = new attachments_grid();
				if ($GLOBALS["attachments_grid"]->DetailView) {
					$GLOBALS["attachments_grid"]->CurrentMode = "view";

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

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

	// Set up detail pages
	protected function setupDetailPages()
	{
		$pages = new SubPages();
		$pages->Style = "tabs";
		$pages->add('hearings');
		$pages->add('notices');
		$pages->add('complaints');
		$pages->add('notifications');
		$pages->add('attachments');
		$this->DetailPages = $pages;
	}

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

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

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

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

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

					// Format the field values
					switch ($fld->FieldVar) {
						case "x_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";

	}

	// Page Exporting event
	// $this->ExportDoc = export document object
	function Page_Exporting() {

		//$this->ExportDoc->Text = "my header"; // Export header
		//return FALSE; // Return FALSE to skip default export and use Row_Export event

		return TRUE; // Return TRUE to use default export and skip Row_Export event
	}

	// Row Export event
	// $this->ExportDoc = export document object
	function Row_Export($rs) {

		//$this->ExportDoc->Text .= "my content"; // Build HTML with field value: $rs["MyField"] or $this->MyField->ViewValue
	}

	// Page Exported event
	// $this->ExportDoc = export document object
	function Page_Exported() {

		//$this->ExportDoc->Text .= "my footer"; // Export footer
		//echo $this->ExportDoc->Text;

	}
}
?>
