<?php
namespace PHPMaker2019\project_germanos;

/**
 * Page class
 */
class attachments_add extends attachments
{

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

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

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

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

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

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

		// Debug message
		LoadDebugMessage();

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

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

	// 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, $attachments;
		if ($this->CustomExport && $this->CustomExport == $this->Export && array_key_exists($this->CustomExport, $EXPORT)) {
				$content = ob_get_contents();
			if ($ExportFileName == "")
				$ExportFileName = $this->TableVar;
			$class = PROJECT_NAMESPACE . $EXPORT[$this->CustomExport];
			if (class_exists($class)) {
				$doc = new $class($attachments);
				$doc->Text = @$content;
				if ($this->isExport("email"))
					echo $this->exportEmail($doc->Text);
				else
					$doc->export();
				DeleteTempImages(); // Delete temp images
				exit();
			}
		}
		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 == "attachmentsview.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['AttachmentID'];
		}
		return $key;
	}

	/**
	 * Hide fields for add/edit
	 *
	 * @return void
	 */
	protected function hideFieldsForAddEdit()
	{
		if ($this->isAdd() || $this->isCopy() || $this->isGridAdd())
			$this->AttachmentID->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("attachmentslist.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->AttachmentID->Visible = FALSE;
		$this->AttachmentSource_ID->setVisibility();
		$this->CaseID->setVisibility();
		$this->EmployeeID->setVisibility();
		$this->AttachID->setVisibility();
		$this->AttachFilename->setVisibility();
		$this->AttachFilenameInitial->setVisibility();
		$this->AttachExtension->setVisibility();
		$this->AttachDescription->setVisibility();
		$this->AttachNotes->setVisibility();
		$this->AttachFilepath->setVisibility();
		$this->AttachPath->setVisibility();
		$this->Notes->setVisibility();
		$this->_UserID->Visible = FALSE;
		$this->CreatedBy->Visible = FALSE;
		$this->CreatedDate->Visible = FALSE;
		$this->UpdatedBy->Visible = FALSE;
		$this->UpdatedDate->Visible = FALSE;
		$this->AddedBy->Visible = FALSE;
		$this->AddedDate->Visible = FALSE;
		$this->_Case->setVisibility();
		$this->hideFieldsForAddEdit();

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

		// 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("AttachmentID") !== NULL) {
				$this->AttachmentID->setQueryStringValue(Get("AttachmentID"));
				$this->setKey("AttachmentID", $this->AttachmentID->CurrentValue); // Set up key
			} else {
				$this->setKey("AttachmentID", ""); // 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("attachmentslist.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) == "attachmentslist.php")
						$returnUrl = $this->addMasterUrl($returnUrl); // List page, return to List page with correct master key if necessary
					elseif (GetPageName($returnUrl) == "attachmentsview.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;
		$this->AttachFilename->Upload->Index = $CurrentForm->Index;
		$this->AttachFilename->Upload->uploadFile();
		$this->AttachFilename->CurrentValue = $this->AttachFilename->Upload->FileName;
	}

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

	// Load form values
	protected function loadFormValues()
	{

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

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

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

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

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

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

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

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

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

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

		// 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 '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 'AttachmentID' first before field var 'x_AttachmentID'
		$val = $CurrentForm->hasValue("AttachmentID") ? $CurrentForm->getValue("AttachmentID") : $CurrentForm->getValue("x_AttachmentID");
	}

	// Restore form values
	public function restoreFormValues()
	{
		global $CurrentForm;
		$this->AttachmentSource_ID->CurrentValue = $this->AttachmentSource_ID->FormValue;
		$this->CaseID->CurrentValue = $this->CaseID->FormValue;
		$this->EmployeeID->CurrentValue = $this->EmployeeID->FormValue;
		$this->AttachID->CurrentValue = $this->AttachID->FormValue;
		$this->AttachFilenameInitial->CurrentValue = $this->AttachFilenameInitial->FormValue;
		$this->AttachExtension->CurrentValue = $this->AttachExtension->FormValue;
		$this->AttachDescription->CurrentValue = $this->AttachDescription->FormValue;
		$this->AttachNotes->CurrentValue = $this->AttachNotes->FormValue;
		$this->AttachFilepath->CurrentValue = $this->AttachFilepath->FormValue;
		$this->AttachPath->CurrentValue = $this->AttachPath->FormValue;
		$this->Notes->CurrentValue = $this->Notes->FormValue;
		$this->_Case->CurrentValue = $this->_Case->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->AttachmentID->setDbValue($row['AttachmentID']);
		$this->AttachmentSource_ID->setDbValue($row['AttachmentSource_ID']);
		$this->CaseID->setDbValue($row['CaseID']);
		$this->EmployeeID->setDbValue($row['EmployeeID']);
		$this->AttachID->setDbValue($row['AttachID']);
		$this->AttachFilename->Upload->DbValue = $row['AttachFilename'];
		$this->AttachFilename->setDbValue($this->AttachFilename->Upload->DbValue);
		$this->AttachFilenameInitial->setDbValue($row['AttachFilenameInitial']);
		$this->AttachExtension->setDbValue($row['AttachExtension']);
		$this->AttachDescription->setDbValue($row['AttachDescription']);
		$this->AttachNotes->setDbValue($row['AttachNotes']);
		$this->AttachFilepath->setDbValue($row['AttachFilepath']);
		$this->AttachPath->setDbValue($row['AttachPath']);
		$this->Notes->setDbValue($row['Notes']);
		$this->_UserID->setDbValue($row['UserID']);
		$this->CreatedBy->setDbValue($row['CreatedBy']);
		$this->CreatedDate->setDbValue($row['CreatedDate']);
		$this->UpdatedBy->setDbValue($row['UpdatedBy']);
		$this->UpdatedDate->setDbValue($row['UpdatedDate']);
		$this->AddedBy->setDbValue($row['AddedBy']);
		$this->AddedDate->setDbValue($row['AddedDate']);
		$this->_Case->setDbValue($row['Case']);
	}

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

	// Load old record
	protected function loadOldRecord()
	{

		// Load key values from Session
		$validKey = TRUE;
		if (strval($this->getKey("AttachmentID")) <> "")
			$this->AttachmentID->CurrentValue = $this->getKey("AttachmentID"); // AttachmentID
		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
		// AttachmentID
		// AttachmentSource_ID
		// CaseID
		// EmployeeID
		// AttachID
		// AttachFilename
		// AttachFilenameInitial
		// AttachExtension
		// AttachDescription
		// AttachNotes
		// AttachFilepath
		// AttachPath
		// Notes
		// UserID
		// CreatedBy
		// CreatedDate
		// UpdatedBy
		// UpdatedDate
		// AddedBy
		// AddedDate
		// Case

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

			// Add refer script
			// AttachmentSource_ID

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	// 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 = [];

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

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

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

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

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

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

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

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

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

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

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

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

		// Case
		$this->_Case->setDbValueDef($rsnew, $this->_Case->CurrentValue, NULL, FALSE);
		if ($this->AttachFilename->Visible && !$this->AttachFilename->Upload->KeepFile) {
			$oldFiles = EmptyValue($this->AttachFilename->Upload->DbValue) ? array() : explode(MULTIPLE_UPLOAD_SEPARATOR, strval($this->AttachFilename->Upload->DbValue));
			if (!EmptyValue($this->AttachFilename->Upload->FileName)) {
				$newFiles = explode(MULTIPLE_UPLOAD_SEPARATOR, strval($this->AttachFilename->Upload->FileName));
				$NewFileCount = count($newFiles);
				for ($i = 0; $i < $NewFileCount; $i++) {
					if ($newFiles[$i] <> "") {
						$file = $newFiles[$i];
						if (file_exists(UploadTempPath($this->AttachFilename, $this->AttachFilename->Upload->Index) . $file)) {
							if (DELETE_UPLOADED_FILES) {
								$oldFileFound = FALSE;
								$oldFileCount = count($oldFiles);
								for ($j = 0; $j < $oldFileCount; $j++) {
									$oldFile = $oldFiles[$j];
									if ($oldFile == $file) { // Old file found, no need to delete anymore
										unset($oldFiles[$j]);
										$oldFileFound = TRUE;
										break;
									}
								}
								if ($oldFileFound) // No need to check if file exists further
									continue;
							}
							$file1 = UniqueFilename($this->AttachFilename->physicalUploadPath(), $file); // Get new file name
							if ($file1 <> $file) { // Rename temp file
								while (file_exists(UploadTempPath($this->AttachFilename, $this->AttachFilename->Upload->Index) . $file1) || file_exists($this->AttachFilename->physicalUploadPath() . $file1)) // Make sure no file name clash
									$file1 = UniqueFilename($this->AttachFilename->physicalUploadPath(), $file1, TRUE); // Use indexed name
								rename(UploadTempPath($this->AttachFilename, $this->AttachFilename->Upload->Index) . $file, UploadTempPath($this->AttachFilename, $this->AttachFilename->Upload->Index) . $file1);
								$newFiles[$i] = $file1;
							}
						}
					}
				}
				$this->AttachFilename->Upload->DbValue = empty($oldFiles) ? "" : implode(MULTIPLE_UPLOAD_SEPARATOR, $oldFiles);
				$this->AttachFilename->Upload->FileName = implode(MULTIPLE_UPLOAD_SEPARATOR, $newFiles);
				$this->AttachFilename->setDbValueDef($rsnew, $this->AttachFilename->Upload->FileName, NULL, FALSE);
			}
		}

		// Call Row Inserting event
		$rs = ($rsold) ? $rsold->fields : NULL;
		$insertRow = $this->Row_Inserting($rs, $rsnew);
		if ($insertRow) {
			$conn->raiseErrorFn = $GLOBALS["ERROR_FUNC"];
			$addRow = $this->insert($rsnew);
			$conn->raiseErrorFn = '';
			if ($addRow) {
				if ($this->AttachFilename->Visible && !$this->AttachFilename->Upload->KeepFile) {
					$oldFiles = EmptyValue($this->AttachFilename->Upload->DbValue) ? array() : explode(MULTIPLE_UPLOAD_SEPARATOR, strval($this->AttachFilename->Upload->DbValue));
					if (!EmptyValue($this->AttachFilename->Upload->FileName)) {
						$newFiles = explode(MULTIPLE_UPLOAD_SEPARATOR, $this->AttachFilename->Upload->FileName);
						$newFiles2 = explode(MULTIPLE_UPLOAD_SEPARATOR, $rsnew['AttachFilename']);
						$newFileCount = count($newFiles);
						for ($i = 0; $i < $newFileCount; $i++) {
							if ($newFiles[$i] <> "") {
								$file = UploadTempPath($this->AttachFilename, $this->AttachFilename->Upload->Index) . $newFiles[$i];
								if (file_exists($file)) {
									if (@$newFiles2[$i] <> "") // Use correct file name
										$newFiles[$i] = $newFiles2[$i];
									if (!$this->AttachFilename->Upload->saveToFile($newFiles[$i], TRUE, $i)) { // Just replace
										$this->setFailureMessage($Language->phrase("UploadErrMsg7"));
										return FALSE;
									}
								}
							}
						}
					} else {
						$newFiles = array();
					}
					if (DELETE_UPLOADED_FILES) {
						foreach ($oldFiles as $oldFile) {
							if ($oldFile <> "" && !in_array($oldFile, $newFiles))
								@unlink($this->AttachFilename->oldPhysicalUploadPath() . $oldFile);
						}
					}
				}
			}
		} else {
			if ($this->getSuccessMessage() <> "" || $this->getFailureMessage() <> "") {

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

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

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

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

	// Set up master/detail based on QueryString
	protected function setupMasterParms()
	{
		$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("attachmentslist.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_AttachmentSource_ID":
							break;
					}
					$ar[strval($row[0])] = $row;
					$rs->moveNext();
				}
				if ($rs)
					$rs->close();
				$fld->Lookup->Options = $ar;
			}
		}
	}

	// Page Load event
	function Page_Load() {

		//echo "Page Load";
	}

	// Page Unload event
	function Page_Unload() {

		//echo "Page Unload";
	}

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

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

	}

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

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

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

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

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

	// Page Render event
	function Page_Render() {

		//echo "Page Render";
	}

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

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

	}

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

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

	}

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

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