<?php
namespace PHPMaker2019\project_germanos;

/**
 * Page class
 */
class notices_add extends notices
{

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

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

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

	// Page object name
	public $PageObjName = "notices_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 (notices)
		if (!isset($GLOBALS["notices"]) || get_class($GLOBALS["notices"]) == PROJECT_NAMESPACE . "notices") {
			$GLOBALS["notices"] = &$this;
			$GLOBALS["Table"] = &$GLOBALS["notices"];
		}

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

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

		// 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, $notices;
		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($notices);
				$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 == "noticesview.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['NoticeID'];
		}
		return $key;
	}

	/**
	 * Hide fields for add/edit
	 *
	 * @return void
	 */
	protected function hideFieldsForAddEdit()
	{
		if ($this->isAdd() || $this->isCopy() || $this->isGridAdd())
			$this->NoticeID->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("noticeslist.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->NoticeID->Visible = FALSE;
		$this->CaseID->setVisibility();
		$this->Notice->setVisibility();
		$this->NoticeEn->Visible = FALSE;
		$this->NoticeDate->setVisibility();
		$this->NoticeTime->setVisibility();
		$this->Notes->setVisibility();
		$this->PostMan->setVisibility();
		$this->LawyerID->setVisibility();
		$this->_UserID->Visible = FALSE;
		$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
		$this->setupLookupOptions($this->CaseID);
		$this->setupLookupOptions($this->LawyerID);

		// 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("NoticeID") !== NULL) {
				$this->NoticeID->setQueryStringValue(Get("NoticeID"));
				$this->setKey("NoticeID", $this->NoticeID->CurrentValue); // Set up key
			} else {
				$this->setKey("NoticeID", ""); // 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();

		// Set up master/detail parameters
		// NOTE: must be after loadOldRecord to prevent master key values overwritten

		$this->setupMasterParms();

		// 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("noticeslist.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) == "noticeslist.php")
						$returnUrl = $this->addMasterUrl($returnUrl); // List page, return to List page with correct master key if necessary
					elseif (GetPageName($returnUrl) == "noticesview.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->NoticeID->CurrentValue = NULL;
		$this->NoticeID->OldValue = $this->NoticeID->CurrentValue;
		$this->CaseID->CurrentValue = NULL;
		$this->CaseID->OldValue = $this->CaseID->CurrentValue;
		$this->Notice->CurrentValue = NULL;
		$this->Notice->OldValue = $this->Notice->CurrentValue;
		$this->NoticeEn->CurrentValue = NULL;
		$this->NoticeEn->OldValue = $this->NoticeEn->CurrentValue;
		$this->NoticeDate->CurrentValue = date("d/m/Y");
		$this->NoticeTime->CurrentValue = date("h:i A");
		$this->Notes->CurrentValue = NULL;
		$this->Notes->OldValue = $this->Notes->CurrentValue;
		$this->PostMan->CurrentValue = NULL;
		$this->PostMan->OldValue = $this->PostMan->CurrentValue;
		$this->LawyerID->CurrentValue = NULL;
		$this->LawyerID->OldValue = $this->LawyerID->CurrentValue;
		$this->_UserID->CurrentValue = NULL;
		$this->_UserID->OldValue = $this->_UserID->CurrentValue;
		$this->CreatedBy->CurrentValue = NULL;
		$this->CreatedBy->OldValue = $this->CreatedBy->CurrentValue;
		$this->CreatedDate->CurrentValue = NULL;
		$this->CreatedDate->OldValue = $this->CreatedDate->CurrentValue;
		$this->UpdatedBy->CurrentValue = NULL;
		$this->UpdatedBy->OldValue = $this->UpdatedBy->CurrentValue;
		$this->UpdatedDate->CurrentValue = NULL;
		$this->UpdatedDate->OldValue = $this->UpdatedDate->CurrentValue;
	}

	// Load form values
	protected function loadFormValues()
	{

		// Load from form
		global $CurrentForm;

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

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

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

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

		// 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 'PostMan' first before field var 'x_PostMan'
		$val = $CurrentForm->hasValue("PostMan") ? $CurrentForm->getValue("PostMan") : $CurrentForm->getValue("x_PostMan");
		if (!$this->PostMan->IsDetailKey) {
			if (IsApi() && $val == NULL)
				$this->PostMan->Visible = FALSE; // Disable update for API request
			else
				$this->PostMan->setFormValue($val);
		}

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

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

	// Restore form values
	public function restoreFormValues()
	{
		global $CurrentForm;
		$this->CaseID->CurrentValue = $this->CaseID->FormValue;
		$this->Notice->CurrentValue = $this->Notice->FormValue;
		$this->NoticeDate->CurrentValue = $this->NoticeDate->FormValue;
		$this->NoticeDate->CurrentValue = UnFormatDateTime($this->NoticeDate->CurrentValue, 7);
		$this->NoticeTime->CurrentValue = $this->NoticeTime->FormValue;
		$this->NoticeTime->CurrentValue = UnFormatDateTime($this->NoticeTime->CurrentValue, 4);
		$this->Notes->CurrentValue = $this->Notes->FormValue;
		$this->PostMan->CurrentValue = $this->PostMan->FormValue;
		$this->LawyerID->CurrentValue = $this->LawyerID->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->NoticeID->setDbValue($row['NoticeID']);
		$this->CaseID->setDbValue($row['CaseID']);
		if (array_key_exists('EV__CaseID', $rs->fields)) {
			$this->CaseID->VirtualValue = $rs->fields('EV__CaseID'); // Set up virtual field value
		} else {
			$this->CaseID->VirtualValue = ""; // Clear value
		}
		$this->Notice->setDbValue($row['Notice']);
		$this->NoticeEn->setDbValue($row['NoticeEn']);
		$this->NoticeDate->setDbValue($row['NoticeDate']);
		$this->NoticeTime->setDbValue($row['NoticeTime']);
		$this->Notes->setDbValue($row['Notes']);
		$this->PostMan->setDbValue($row['PostMan']);
		$this->LawyerID->setDbValue($row['LawyerID']);
		$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']);
	}

	// Return a row with default values
	protected function newRow()
	{
		$this->loadDefaultValues();
		$row = [];
		$row['NoticeID'] = $this->NoticeID->CurrentValue;
		$row['CaseID'] = $this->CaseID->CurrentValue;
		$row['Notice'] = $this->Notice->CurrentValue;
		$row['NoticeEn'] = $this->NoticeEn->CurrentValue;
		$row['NoticeDate'] = $this->NoticeDate->CurrentValue;
		$row['NoticeTime'] = $this->NoticeTime->CurrentValue;
		$row['Notes'] = $this->Notes->CurrentValue;
		$row['PostMan'] = $this->PostMan->CurrentValue;
		$row['LawyerID'] = $this->LawyerID->CurrentValue;
		$row['UserID'] = $this->_UserID->CurrentValue;
		$row['CreatedBy'] = $this->CreatedBy->CurrentValue;
		$row['CreatedDate'] = $this->CreatedDate->CurrentValue;
		$row['UpdatedBy'] = $this->UpdatedBy->CurrentValue;
		$row['UpdatedDate'] = $this->UpdatedDate->CurrentValue;
		return $row;
	}

	// Load old record
	protected function loadOldRecord()
	{

		// Load key values from Session
		$validKey = TRUE;
		if (strval($this->getKey("NoticeID")) <> "")
			$this->NoticeID->CurrentValue = $this->getKey("NoticeID"); // NoticeID
		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
		// NoticeID
		// CaseID
		// Notice
		// NoticeEn
		// NoticeDate
		// NoticeTime
		// Notes
		// PostMan
		// LawyerID
		// UserID
		// CreatedBy
		// CreatedDate
		// UpdatedBy
		// UpdatedDate

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

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

			// CaseID
			if ($this->CaseID->VirtualValue <> "") {
				$this->CaseID->ViewValue = $this->CaseID->VirtualValue;
			} else {
				$this->CaseID->ViewValue = $this->CaseID->CurrentValue;
			$curVal = strval($this->CaseID->CurrentValue);
			if ($curVal <> "") {
				$this->CaseID->ViewValue = $this->CaseID->lookupCacheOption($curVal);
				if ($this->CaseID->ViewValue === NULL) { // Lookup from database
					$filterWrk = "`CaseID`" . SearchString("=", $curVal, DATATYPE_NUMBER, "");
					$sqlWrk = $this->CaseID->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');
						$this->CaseID->ViewValue = $this->CaseID->displayValue($arwrk);
						$rswrk->Close();
					} else {
						$this->CaseID->ViewValue = $this->CaseID->CurrentValue;
					}
				}
			} else {
				$this->CaseID->ViewValue = NULL;
			}
			}
			$this->CaseID->ViewCustomAttributes = "";

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

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

			// NoticeTime
			$this->NoticeTime->ViewValue = $this->NoticeTime->CurrentValue;
			$this->NoticeTime->ViewValue = FormatDateTime($this->NoticeTime->ViewValue, 4);
			$this->NoticeTime->ViewCustomAttributes = "";

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

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

			// LawyerID
			$curVal = strval($this->LawyerID->CurrentValue);
			if ($curVal <> "") {
				$this->LawyerID->ViewValue = $this->LawyerID->lookupCacheOption($curVal);
				if ($this->LawyerID->ViewValue === NULL) { // Lookup from database
					$filterWrk = "`LawyerID`" . SearchString("=", $curVal, DATATYPE_NUMBER, "");
					$sqlWrk = $this->LawyerID->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->LawyerID->ViewValue = $this->LawyerID->displayValue($arwrk);
						$rswrk->Close();
					} else {
						$this->LawyerID->ViewValue = $this->LawyerID->CurrentValue;
					}
				}
			} else {
				$this->LawyerID->ViewValue = NULL;
			}
			$this->LawyerID->ViewCustomAttributes = "";

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

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

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

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

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

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

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

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

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

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

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

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

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

			// Add refer script
			// CaseID

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

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

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

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

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

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

			// LawyerID
			$this->LawyerID->LinkCustomAttributes = "";
			$this->LawyerID->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->NoticeID->Required) {
			if (!$this->NoticeID->IsDetailKey && $this->NoticeID->FormValue != NULL && $this->NoticeID->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->NoticeID->caption(), $this->NoticeID->RequiredErrorMessage));
			}
		}
		if ($this->CaseID->Required) {
			if (!$this->CaseID->IsDetailKey && $this->CaseID->FormValue != NULL && $this->CaseID->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->CaseID->caption(), $this->CaseID->RequiredErrorMessage));
			}
		}
		if ($this->Notice->Required) {
			if (!$this->Notice->IsDetailKey && $this->Notice->FormValue != NULL && $this->Notice->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->Notice->caption(), $this->Notice->RequiredErrorMessage));
			}
		}
		if ($this->NoticeEn->Required) {
			if (!$this->NoticeEn->IsDetailKey && $this->NoticeEn->FormValue != NULL && $this->NoticeEn->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->NoticeEn->caption(), $this->NoticeEn->RequiredErrorMessage));
			}
		}
		if ($this->NoticeDate->Required) {
			if (!$this->NoticeDate->IsDetailKey && $this->NoticeDate->FormValue != NULL && $this->NoticeDate->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->NoticeDate->caption(), $this->NoticeDate->RequiredErrorMessage));
			}
		}
		if (!CheckEuroDate($this->NoticeDate->FormValue)) {
			AddMessage($FormError, $this->NoticeDate->errorMessage());
		}
		if ($this->NoticeTime->Required) {
			if (!$this->NoticeTime->IsDetailKey && $this->NoticeTime->FormValue != NULL && $this->NoticeTime->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->NoticeTime->caption(), $this->NoticeTime->RequiredErrorMessage));
			}
		}
		if (!CheckTime($this->NoticeTime->FormValue)) {
			AddMessage($FormError, $this->NoticeTime->errorMessage());
		}
		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->PostMan->Required) {
			if (!$this->PostMan->IsDetailKey && $this->PostMan->FormValue != NULL && $this->PostMan->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->PostMan->caption(), $this->PostMan->RequiredErrorMessage));
			}
		}
		if ($this->LawyerID->Required) {
			if (!$this->LawyerID->IsDetailKey && $this->LawyerID->FormValue != NULL && $this->LawyerID->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->LawyerID->caption(), $this->LawyerID->RequiredErrorMessage));
			}
		}
		if ($this->_UserID->Required) {
			if (!$this->_UserID->IsDetailKey && $this->_UserID->FormValue != NULL && $this->_UserID->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->_UserID->caption(), $this->_UserID->RequiredErrorMessage));
			}
		}
		if ($this->CreatedBy->Required) {
			if (!$this->CreatedBy->IsDetailKey && $this->CreatedBy->FormValue != NULL && $this->CreatedBy->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->CreatedBy->caption(), $this->CreatedBy->RequiredErrorMessage));
			}
		}
		if ($this->CreatedDate->Required) {
			if (!$this->CreatedDate->IsDetailKey && $this->CreatedDate->FormValue != NULL && $this->CreatedDate->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->CreatedDate->caption(), $this->CreatedDate->RequiredErrorMessage));
			}
		}
		if ($this->UpdatedBy->Required) {
			if (!$this->UpdatedBy->IsDetailKey && $this->UpdatedBy->FormValue != NULL && $this->UpdatedBy->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->UpdatedBy->caption(), $this->UpdatedBy->RequiredErrorMessage));
			}
		}
		if ($this->UpdatedDate->Required) {
			if (!$this->UpdatedDate->IsDetailKey && $this->UpdatedDate->FormValue != NULL && $this->UpdatedDate->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->UpdatedDate->caption(), $this->UpdatedDate->RequiredErrorMessage));
			}
		}

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

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

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

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

		// Notice
		$this->Notice->setDbValueDef($rsnew, $this->Notice->CurrentValue, "", FALSE);

		// NoticeDate
		$this->NoticeDate->setDbValueDef($rsnew, UnFormatDateTime($this->NoticeDate->CurrentValue, 7), NULL, FALSE);

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

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

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

		// LawyerID
		$this->LawyerID->setDbValueDef($rsnew, $this->LawyerID->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);
		}

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

	// Set up master/detail based on QueryString
	protected function setupMasterParms()
	{
		$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 == "cases") {
				$validMaster = TRUE;
				if (Get("fk_CaseID") !== NULL) {
					$GLOBALS["cases"]->CaseID->setQueryStringValue(Get("fk_CaseID"));
					$this->CaseID->setQueryStringValue($GLOBALS["cases"]->CaseID->QueryStringValue);
					$this->CaseID->setSessionValue($this->CaseID->QueryStringValue);
					if (!is_numeric($GLOBALS["cases"]->CaseID->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 == "cases") {
				$validMaster = TRUE;
				if (Post("fk_CaseID") !== NULL) {
					$GLOBALS["cases"]->CaseID->setFormValue(Post("fk_CaseID"));
					$this->CaseID->setFormValue($GLOBALS["cases"]->CaseID->FormValue);
					$this->CaseID->setSessionValue($this->CaseID->FormValue);
					if (!is_numeric($GLOBALS["cases"]->CaseID->FormValue))
						$validMaster = FALSE;
				} else {
					$validMaster = FALSE;
				}
			}
		}
		if ($validMaster) {

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

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

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

	// Set up Breadcrumb
	protected function setupBreadcrumb()
	{
		global $Breadcrumb, $Language;
		$Breadcrumb = new Breadcrumb();
		$url = substr(CurrentUrl(), strrpos(CurrentUrl(), "/")+1);
		$Breadcrumb->add("list", $this->TableVar, $this->addMasterUrl("noticeslist.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) {
						case "x_CaseID":
							break;
						case "x_LawyerID":
							break;
					}
					$ar[strval($row[0])] = $row;
					$rs->moveNext();
				}
				if ($rs)
					$rs->close();
				$fld->Lookup->Options = $ar;
			}
		}
	}

	// Page Load event
	function Page_Load() {

		//echo "Page Load";
	}

	// Page Unload event
	function Page_Unload() {

		//echo "Page Unload";
	}

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

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

	}

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

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

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

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

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

	// Page Render event
	function Page_Render() {

		//echo "Page Render";
	}

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

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

	}

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

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

	}

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

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