<?php
namespace PHPMaker2019\project_germanos;

/**
 * Page class
 */
class envelopes_add extends envelopes
{

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

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

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

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

	// 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 (envelopes)
		if (!isset($GLOBALS["envelopes"]) || get_class($GLOBALS["envelopes"]) == PROJECT_NAMESPACE . "envelopes") {
			$GLOBALS["envelopes"] = &$this;
			$GLOBALS["Table"] = &$GLOBALS["envelopes"];
		}

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

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

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

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

		// Debug message
		LoadDebugMessage();

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

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

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

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

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

		// Export
		global $EXPORT, $envelopes;
		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($envelopes);
				$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 == "envelopesview.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['EnvelopeID'];
		}
		return $key;
	}

	/**
	 * Hide fields for add/edit
	 *
	 * @return void
	 */
	protected function hideFieldsForAddEdit()
	{
		if ($this->isAdd() || $this->isCopy() || $this->isGridAdd())
			$this->EnvelopeID->Visible = FALSE;
	}
	public $FormClassName = "ew-horizontal ew-form ew-add-form";
	public $IsModal = FALSE;
	public $IsMobileOrModal = FALSE;
	public $DbMasterFilter = "";
	public $DbDetailFilter = "";
	public $StartRec;
	public $Priv = 0;
	public $OldRecordset;
	public $CopyRecord;

	//
	// Page run
	//

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

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

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

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

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

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

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

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

		// Create form object
		$CurrentForm = new HttpForm();
		$this->CurrentAction = Param("action"); // Set up current action
		$this->EnvelopeID->Visible = FALSE;
		$this->CaseNumber->setVisibility();
		$this->FileNumber->setVisibility();
		$this->EnvelopeNumber->setVisibility();
		$this->FileLocation->setVisibility();
		$this->_Case->setVisibility();
		$this->CaseEn->setVisibility();
		$this->CaseType->setVisibility();
		$this->ClientName->setVisibility();
		$this->LitigantName->setVisibility();
		$this->CourtName->setVisibility();
		$this->CourtID->setVisibility();
		$this->CourtTypeName->setVisibility();
		$this->CourtGenderName->setVisibility();
		$this->JudgeName->setVisibility();
		$this->Notes->setVisibility();
		$this->ClientID->setVisibility();
		$this->LitigantID->setVisibility();
		$this->CreatedBy->Visible = FALSE;
		$this->CreatedDate->Visible = FALSE;
		$this->UpdatedBy->Visible = FALSE;
		$this->UpdatedDate->Visible = FALSE;
		$this->hideFieldsForAddEdit();

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

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

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

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

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

		// Set up lookup cache
		// Check modal

		if ($this->IsModal)
			$SkipHeaderFooter = TRUE;
		$this->IsMobileOrModal = IsMobile() || $this->IsModal;
		$this->FormClassName = "ew-form ew-add-form ew-horizontal";
		$postBack = FALSE;

		// Set up current action
		if (IsApi()) {
			$this->CurrentAction = "insert"; // Add record directly
			$postBack = TRUE;
		} elseif (Post("action") !== NULL) {
			$this->CurrentAction = Post("action"); // Get form action
			$postBack = TRUE;
		} else { // Not post back

			// Load key values from QueryString
			$this->CopyRecord = TRUE;
			if (Get("EnvelopeID") !== NULL) {
				$this->EnvelopeID->setQueryStringValue(Get("EnvelopeID"));
				$this->setKey("EnvelopeID", $this->EnvelopeID->CurrentValue); // Set up key
			} else {
				$this->setKey("EnvelopeID", ""); // Clear key
				$this->CopyRecord = FALSE;
			}
			if ($this->CopyRecord) {
				$this->CurrentAction = "copy"; // Copy record
			} else {
				$this->CurrentAction = "show"; // Display blank record
			}
		}

		// Load old record / default values
		$loaded = $this->loadOldRecord();

		// Load form values
		if ($postBack) {
			$this->loadFormValues(); // Load form values
		}

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

		// Perform current action
		switch ($this->CurrentAction) {
			case "copy": // Copy an existing record
				if (!$loaded) { // Record not loaded
					if ($this->getFailureMessage() == "")
						$this->setFailureMessage($Language->phrase("NoRecord")); // No record found
					$this->terminate("envelopeslist.php"); // No matching record, return to list
				}
				break;
			case "insert": // Add new record
				$this->SendEmail = TRUE; // Send email on add success
				if ($this->addRow($this->OldRecordset)) { // Add successful
					if ($this->getSuccessMessage() == "")
						$this->setSuccessMessage($Language->phrase("AddSuccess")); // Set up success message
					$returnUrl = $this->getReturnUrl();
					if (GetPageName($returnUrl) == "envelopeslist.php")
						$returnUrl = $this->addMasterUrl($returnUrl); // List page, return to List page with correct master key if necessary
					elseif (GetPageName($returnUrl) == "envelopesview.php")
						$returnUrl = $this->getViewUrl(); // View page, return to View page with keyurl directly
					if (IsApi()) { // Return to caller
						$this->terminate(TRUE);
						return;
					} else {
						$this->terminate($returnUrl);
					}
				} elseif (IsApi()) { // API request, return
					$this->terminate();
					return;
				} else {
					$this->EventCancelled = TRUE; // Event cancelled
					$this->restoreFormValues(); // Add failed, restore form values
				}
		}

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

		// Render row based on row type
		$this->RowType = ROWTYPE_ADD; // Render add type

		// Render row
		$this->resetAttributes();
		$this->renderRow();
	}

	// Get upload files
	protected function getUploadFiles()
	{
		global $CurrentForm, $Language;
	}

	// Load default values
	protected function loadDefaultValues()
	{
		$this->EnvelopeID->CurrentValue = NULL;
		$this->EnvelopeID->OldValue = $this->EnvelopeID->CurrentValue;
		$this->CaseNumber->CurrentValue = NULL;
		$this->CaseNumber->OldValue = $this->CaseNumber->CurrentValue;
		$this->FileNumber->CurrentValue = NULL;
		$this->FileNumber->OldValue = $this->FileNumber->CurrentValue;
		$this->EnvelopeNumber->CurrentValue = NULL;
		$this->EnvelopeNumber->OldValue = $this->EnvelopeNumber->CurrentValue;
		$this->FileLocation->CurrentValue = NULL;
		$this->FileLocation->OldValue = $this->FileLocation->CurrentValue;
		$this->_Case->CurrentValue = NULL;
		$this->_Case->OldValue = $this->_Case->CurrentValue;
		$this->CaseEn->CurrentValue = NULL;
		$this->CaseEn->OldValue = $this->CaseEn->CurrentValue;
		$this->CaseType->CurrentValue = NULL;
		$this->CaseType->OldValue = $this->CaseType->CurrentValue;
		$this->ClientName->CurrentValue = NULL;
		$this->ClientName->OldValue = $this->ClientName->CurrentValue;
		$this->LitigantName->CurrentValue = NULL;
		$this->LitigantName->OldValue = $this->LitigantName->CurrentValue;
		$this->CourtName->CurrentValue = NULL;
		$this->CourtName->OldValue = $this->CourtName->CurrentValue;
		$this->CourtID->CurrentValue = NULL;
		$this->CourtID->OldValue = $this->CourtID->CurrentValue;
		$this->CourtTypeName->CurrentValue = NULL;
		$this->CourtTypeName->OldValue = $this->CourtTypeName->CurrentValue;
		$this->CourtGenderName->CurrentValue = NULL;
		$this->CourtGenderName->OldValue = $this->CourtGenderName->CurrentValue;
		$this->JudgeName->CurrentValue = NULL;
		$this->JudgeName->OldValue = $this->JudgeName->CurrentValue;
		$this->Notes->CurrentValue = NULL;
		$this->Notes->OldValue = $this->Notes->CurrentValue;
		$this->ClientID->CurrentValue = NULL;
		$this->ClientID->OldValue = $this->ClientID->CurrentValue;
		$this->LitigantID->CurrentValue = NULL;
		$this->LitigantID->OldValue = $this->LitigantID->CurrentValue;
		$this->CreatedBy->CurrentValue = NULL;
		$this->CreatedBy->OldValue = $this->CreatedBy->CurrentValue;
		$this->CreatedDate->CurrentValue = NULL;
		$this->CreatedDate->OldValue = $this->CreatedDate->CurrentValue;
		$this->UpdatedBy->CurrentValue = NULL;
		$this->UpdatedBy->OldValue = $this->UpdatedBy->CurrentValue;
		$this->UpdatedDate->CurrentValue = NULL;
		$this->UpdatedDate->OldValue = $this->UpdatedDate->CurrentValue;
	}

	// Load form values
	protected function loadFormValues()
	{

		// Load from form
		global $CurrentForm;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		// Check field name 'EnvelopeID' first before field var 'x_EnvelopeID'
		$val = $CurrentForm->hasValue("EnvelopeID") ? $CurrentForm->getValue("EnvelopeID") : $CurrentForm->getValue("x_EnvelopeID");
	}

	// Restore form values
	public function restoreFormValues()
	{
		global $CurrentForm;
		$this->CaseNumber->CurrentValue = $this->CaseNumber->FormValue;
		$this->FileNumber->CurrentValue = $this->FileNumber->FormValue;
		$this->EnvelopeNumber->CurrentValue = $this->EnvelopeNumber->FormValue;
		$this->FileLocation->CurrentValue = $this->FileLocation->FormValue;
		$this->_Case->CurrentValue = $this->_Case->FormValue;
		$this->CaseEn->CurrentValue = $this->CaseEn->FormValue;
		$this->CaseType->CurrentValue = $this->CaseType->FormValue;
		$this->ClientName->CurrentValue = $this->ClientName->FormValue;
		$this->LitigantName->CurrentValue = $this->LitigantName->FormValue;
		$this->CourtName->CurrentValue = $this->CourtName->FormValue;
		$this->CourtID->CurrentValue = $this->CourtID->FormValue;
		$this->CourtTypeName->CurrentValue = $this->CourtTypeName->FormValue;
		$this->CourtGenderName->CurrentValue = $this->CourtGenderName->FormValue;
		$this->JudgeName->CurrentValue = $this->JudgeName->FormValue;
		$this->Notes->CurrentValue = $this->Notes->FormValue;
		$this->ClientID->CurrentValue = $this->ClientID->FormValue;
		$this->LitigantID->CurrentValue = $this->LitigantID->FormValue;
	}

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

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

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

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

		// Call Row Selected event
		$this->Row_Selected($row);
		if (!$rs || $rs->EOF)
			return;
		$this->EnvelopeID->setDbValue($row['EnvelopeID']);
		$this->CaseNumber->setDbValue($row['CaseNumber']);
		$this->FileNumber->setDbValue($row['FileNumber']);
		$this->EnvelopeNumber->setDbValue($row['EnvelopeNumber']);
		$this->FileLocation->setDbValue($row['FileLocation']);
		$this->_Case->setDbValue($row['Case']);
		$this->CaseEn->setDbValue($row['CaseEn']);
		$this->CaseType->setDbValue($row['CaseType']);
		$this->ClientName->setDbValue($row['ClientName']);
		$this->LitigantName->setDbValue($row['LitigantName']);
		$this->CourtName->setDbValue($row['CourtName']);
		$this->CourtID->setDbValue($row['CourtID']);
		$this->CourtTypeName->setDbValue($row['CourtTypeName']);
		$this->CourtGenderName->setDbValue($row['CourtGenderName']);
		$this->JudgeName->setDbValue($row['JudgeName']);
		$this->Notes->setDbValue($row['Notes']);
		$this->ClientID->setDbValue($row['ClientID']);
		$this->LitigantID->setDbValue($row['LitigantID']);
		$this->CreatedBy->setDbValue($row['CreatedBy']);
		$this->CreatedDate->setDbValue($row['CreatedDate']);
		$this->UpdatedBy->setDbValue($row['UpdatedBy']);
		$this->UpdatedDate->setDbValue($row['UpdatedDate']);
	}

	// Return a row with default values
	protected function newRow()
	{
		$this->loadDefaultValues();
		$row = [];
		$row['EnvelopeID'] = $this->EnvelopeID->CurrentValue;
		$row['CaseNumber'] = $this->CaseNumber->CurrentValue;
		$row['FileNumber'] = $this->FileNumber->CurrentValue;
		$row['EnvelopeNumber'] = $this->EnvelopeNumber->CurrentValue;
		$row['FileLocation'] = $this->FileLocation->CurrentValue;
		$row['Case'] = $this->_Case->CurrentValue;
		$row['CaseEn'] = $this->CaseEn->CurrentValue;
		$row['CaseType'] = $this->CaseType->CurrentValue;
		$row['ClientName'] = $this->ClientName->CurrentValue;
		$row['LitigantName'] = $this->LitigantName->CurrentValue;
		$row['CourtName'] = $this->CourtName->CurrentValue;
		$row['CourtID'] = $this->CourtID->CurrentValue;
		$row['CourtTypeName'] = $this->CourtTypeName->CurrentValue;
		$row['CourtGenderName'] = $this->CourtGenderName->CurrentValue;
		$row['JudgeName'] = $this->JudgeName->CurrentValue;
		$row['Notes'] = $this->Notes->CurrentValue;
		$row['ClientID'] = $this->ClientID->CurrentValue;
		$row['LitigantID'] = $this->LitigantID->CurrentValue;
		$row['CreatedBy'] = $this->CreatedBy->CurrentValue;
		$row['CreatedDate'] = $this->CreatedDate->CurrentValue;
		$row['UpdatedBy'] = $this->UpdatedBy->CurrentValue;
		$row['UpdatedDate'] = $this->UpdatedDate->CurrentValue;
		return $row;
	}

	// Load old record
	protected function loadOldRecord()
	{

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

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

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

		// Initialize URLs
		// Call Row_Rendering event

		$this->Row_Rendering();

		// Common render codes for all row types
		// EnvelopeID
		// CaseNumber
		// FileNumber
		// EnvelopeNumber
		// FileLocation
		// Case
		// CaseEn
		// CaseType
		// ClientName
		// LitigantName
		// CourtName
		// CourtID
		// CourtTypeName
		// CourtGenderName
		// JudgeName
		// Notes
		// ClientID
		// LitigantID
		// CreatedBy
		// CreatedDate
		// UpdatedBy
		// UpdatedDate

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

			// LitigantID
			$this->LitigantID->LinkCustomAttributes = "";
			$this->LitigantID->HrefValue = "";
			$this->LitigantID->TooltipValue = "";
		} elseif ($this->RowType == ROWTYPE_ADD) { // Add row

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

			// Add refer script
			// CaseNumber

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		// Check if validation required
		if (!SERVER_VALIDATE)
			return ($FormError == "");
		if ($this->EnvelopeID->Required) {
			if (!$this->EnvelopeID->IsDetailKey && $this->EnvelopeID->FormValue != NULL && $this->EnvelopeID->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->EnvelopeID->caption(), $this->EnvelopeID->RequiredErrorMessage));
			}
		}
		if ($this->CaseNumber->Required) {
			if (!$this->CaseNumber->IsDetailKey && $this->CaseNumber->FormValue != NULL && $this->CaseNumber->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->CaseNumber->caption(), $this->CaseNumber->RequiredErrorMessage));
			}
		}
		if ($this->FileNumber->Required) {
			if (!$this->FileNumber->IsDetailKey && $this->FileNumber->FormValue != NULL && $this->FileNumber->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->FileNumber->caption(), $this->FileNumber->RequiredErrorMessage));
			}
		}
		if ($this->EnvelopeNumber->Required) {
			if (!$this->EnvelopeNumber->IsDetailKey && $this->EnvelopeNumber->FormValue != NULL && $this->EnvelopeNumber->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->EnvelopeNumber->caption(), $this->EnvelopeNumber->RequiredErrorMessage));
			}
		}
		if ($this->FileLocation->Required) {
			if (!$this->FileLocation->IsDetailKey && $this->FileLocation->FormValue != NULL && $this->FileLocation->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->FileLocation->caption(), $this->FileLocation->RequiredErrorMessage));
			}
		}
		if ($this->_Case->Required) {
			if (!$this->_Case->IsDetailKey && $this->_Case->FormValue != NULL && $this->_Case->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->_Case->caption(), $this->_Case->RequiredErrorMessage));
			}
		}
		if ($this->CaseEn->Required) {
			if (!$this->CaseEn->IsDetailKey && $this->CaseEn->FormValue != NULL && $this->CaseEn->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->CaseEn->caption(), $this->CaseEn->RequiredErrorMessage));
			}
		}
		if ($this->CaseType->Required) {
			if (!$this->CaseType->IsDetailKey && $this->CaseType->FormValue != NULL && $this->CaseType->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->CaseType->caption(), $this->CaseType->RequiredErrorMessage));
			}
		}
		if ($this->ClientName->Required) {
			if (!$this->ClientName->IsDetailKey && $this->ClientName->FormValue != NULL && $this->ClientName->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->ClientName->caption(), $this->ClientName->RequiredErrorMessage));
			}
		}
		if ($this->LitigantName->Required) {
			if (!$this->LitigantName->IsDetailKey && $this->LitigantName->FormValue != NULL && $this->LitigantName->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->LitigantName->caption(), $this->LitigantName->RequiredErrorMessage));
			}
		}
		if ($this->CourtName->Required) {
			if (!$this->CourtName->IsDetailKey && $this->CourtName->FormValue != NULL && $this->CourtName->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->CourtName->caption(), $this->CourtName->RequiredErrorMessage));
			}
		}
		if ($this->CourtID->Required) {
			if (!$this->CourtID->IsDetailKey && $this->CourtID->FormValue != NULL && $this->CourtID->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->CourtID->caption(), $this->CourtID->RequiredErrorMessage));
			}
		}
		if (!CheckInteger($this->CourtID->FormValue)) {
			AddMessage($FormError, $this->CourtID->errorMessage());
		}
		if ($this->CourtTypeName->Required) {
			if (!$this->CourtTypeName->IsDetailKey && $this->CourtTypeName->FormValue != NULL && $this->CourtTypeName->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->CourtTypeName->caption(), $this->CourtTypeName->RequiredErrorMessage));
			}
		}
		if ($this->CourtGenderName->Required) {
			if (!$this->CourtGenderName->IsDetailKey && $this->CourtGenderName->FormValue != NULL && $this->CourtGenderName->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->CourtGenderName->caption(), $this->CourtGenderName->RequiredErrorMessage));
			}
		}
		if ($this->JudgeName->Required) {
			if (!$this->JudgeName->IsDetailKey && $this->JudgeName->FormValue != NULL && $this->JudgeName->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->JudgeName->caption(), $this->JudgeName->RequiredErrorMessage));
			}
		}
		if ($this->Notes->Required) {
			if (!$this->Notes->IsDetailKey && $this->Notes->FormValue != NULL && $this->Notes->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->Notes->caption(), $this->Notes->RequiredErrorMessage));
			}
		}
		if ($this->ClientID->Required) {
			if (!$this->ClientID->IsDetailKey && $this->ClientID->FormValue != NULL && $this->ClientID->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->ClientID->caption(), $this->ClientID->RequiredErrorMessage));
			}
		}
		if (!CheckInteger($this->ClientID->FormValue)) {
			AddMessage($FormError, $this->ClientID->errorMessage());
		}
		if ($this->LitigantID->Required) {
			if (!$this->LitigantID->IsDetailKey && $this->LitigantID->FormValue != NULL && $this->LitigantID->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->LitigantID->caption(), $this->LitigantID->RequiredErrorMessage));
			}
		}
		if (!CheckInteger($this->LitigantID->FormValue)) {
			AddMessage($FormError, $this->LitigantID->errorMessage());
		}
		if ($this->CreatedBy->Required) {
			if (!$this->CreatedBy->IsDetailKey && $this->CreatedBy->FormValue != NULL && $this->CreatedBy->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->CreatedBy->caption(), $this->CreatedBy->RequiredErrorMessage));
			}
		}
		if ($this->CreatedDate->Required) {
			if (!$this->CreatedDate->IsDetailKey && $this->CreatedDate->FormValue != NULL && $this->CreatedDate->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->CreatedDate->caption(), $this->CreatedDate->RequiredErrorMessage));
			}
		}
		if ($this->UpdatedBy->Required) {
			if (!$this->UpdatedBy->IsDetailKey && $this->UpdatedBy->FormValue != NULL && $this->UpdatedBy->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->UpdatedBy->caption(), $this->UpdatedBy->RequiredErrorMessage));
			}
		}
		if ($this->UpdatedDate->Required) {
			if (!$this->UpdatedDate->IsDetailKey && $this->UpdatedDate->FormValue != NULL && $this->UpdatedDate->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->UpdatedDate->caption(), $this->UpdatedDate->RequiredErrorMessage));
			}
		}

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

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

	// Add record
	protected function addRow($rsold = NULL)
	{
		global $Language, $Security;
		$conn = &$this->getConnection();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		// Call Row Inserting event
		$rs = ($rsold) ? $rsold->fields : NULL;
		$insertRow = $this->Row_Inserting($rs, $rsnew);
		if ($insertRow) {
			$conn->raiseErrorFn = $GLOBALS["ERROR_FUNC"];
			$addRow = $this->insert($rsnew);
			$conn->raiseErrorFn = '';
			if ($addRow) {
			}
		} else {
			if ($this->getSuccessMessage() <> "" || $this->getFailureMessage() <> "") {

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

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

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

	// 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("envelopeslist.php"), "", $this->TableVar, TRUE);
		$pageId = ($this->isCopy()) ? "Copy" : "Add";
		$Breadcrumb->add("add", $pageId, $url);
	}

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

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

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

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

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

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

	// Page Load event
	function Page_Load() {

		//echo "Page Load";
	}

	// Page Unload event
	function Page_Unload() {

		//echo "Page Unload";
	}

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

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

	}

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

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

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

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

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

	// Page Render event
	function Page_Render() {

		//echo "Page Render";
	}

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

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

	}

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

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

	}

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

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