<?php
namespace PHPMaker2020\recetarios_2021;

/**
 * Page class
 */
class salidas_add extends salidas
{

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

	// Project ID
	public $ProjectID = "{2A7E3B79-A2EC-4C74-B4A2-FA2DA14712FE}";

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

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

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

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

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

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

	// 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 = TRUE;
		$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 fas 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 fas fa-exclamation"></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 fas 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 fas 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 = [];

		// 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(Config("TOKEN_NAME")) === NULL)
			return FALSE;
		$fn = Config("CHECK_TOKEN_FUNC");
		if (is_callable($fn))
			return $fn(Post(Config("TOKEN_NAME")), $this->TokenTimeout);
		return FALSE;
	}

	// Create Token
	public function createToken()
	{
		global $CurrentToken;
		$fn = Config("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, $DashboardReport;
		global $UserTable;

		// Check token
		$this->CheckToken = Config("CHECK_TOKEN");

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

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

		// Parent constuctor
		parent::__construct();

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

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

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

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

		// 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 (usuarios)
		$UserTable = $UserTable ?: new usuarios();
	}

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

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

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

		// Export
		global $salidas;
		if ($this->CustomExport && $this->CustomExport == $this->Export && array_key_exists($this->CustomExport, Config("EXPORT_CLASSES"))) {
				$content = ob_get_contents();
			if ($ExportFileName == "")
				$ExportFileName = $this->TableVar;
			$class = PROJECT_NAMESPACE . Config("EXPORT_CLASSES." . $this->CustomExport);
			if (class_exists($class)) {
				$doc = new $class($salidas);
				$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 (!Config("DEBUG") && ob_get_length())
				ob_end_clean();

			// Handle modal response
			if ($this->IsModal) { // Show as modal
				$row = ["url" => $url, "modal" => "1"];
				$pageName = GetPageName($url);
				if ($pageName != $this->getListUrl()) { // Not List page
					$row["caption"] = $this->getModalCaption($pageName);
					if ($pageName == "salidasview.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 = [];
		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 = [];
		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(GetApiUrl(Config("API_FILE_ACTION"),
									Config("API_OBJECT_NAME") . "=" . $fld->TableVar . "&" .
									Config("API_FIELD_NAME") . "=" . $fld->Param . "&" .
									Config("API_KEY_NAME") . "=" . rawurlencode($this->getRecordKeyValue($ar)))); //*** need to add this? API may not be in the same folder
								$row[$fldname] = ["type" => ContentType($val), "url" => $url, "name" => $fld->Param . ContentExtension($val)];
							} elseif (!$fld->UploadMultiple || !ContainsString($val, Config("MULTIPLE_UPLOAD_SEPARATOR"))) { // Single file
								$url = FullUrl(GetApiUrl(Config("API_FILE_ACTION"),
									Config("API_OBJECT_NAME") . "=" . $fld->TableVar . "&" .
									"fn=" . Encrypt($fld->physicalUploadPath() . $val)));
								$row[$fldname] = ["type" => MimeContentType($val), "url" => $url, "name" => $val];
							} else { // Multiple files
								$files = explode(Config("MULTIPLE_UPLOAD_SEPARATOR"), $val);
								$ar = [];
								foreach ($files as $file) {
									$url = FullUrl(GetApiUrl(Config("API_FILE_ACTION"),
										Config("API_OBJECT_NAME") . "=" . $fld->TableVar . "&" .
										"fn=" . Encrypt($fld->physicalUploadPath() . $file)));
									if (!EmptyValue($file))
										$ar[] = ["type" => MimeContentType($file), "url" => $url, "name" => $file];
								}
								$row[$fldname] = $ar;
							}
						}
					} else {
						$row[$fldname] = $val;
					}
				}
			}
		}
		return $row;
	}

	// Get record key value from array
	protected function getRecordKeyValue($ar)
	{
		$key = "";
		if (is_array($ar)) {
			$key .= @$ar['id'];
		}
		return $key;
	}

	/**
	 * Hide fields for add/edit
	 *
	 * @return void
	 */
	protected function hideFieldsForAddEdit()
	{
		if ($this->isAdd() || $this->isCopy() || $this->isGridAdd())
			$this->id->Visible = FALSE;
	}

	// Lookup data
	public function lookup()
	{
		global $Language, $Security;
		if (!isset($Language))
			$Language = new Language(Config("LANGUAGE_FOLDER"), Post("language", ""));

		// Set up API request
		if (!ValidApiRequest())
			return FALSE;
		$this->setupApiSecurity();

		// Get lookup object
		$fieldName = Post("field");
		if (!array_key_exists($fieldName, $this->fields))
			return FALSE;
		$lookupField = $this->fields[$fieldName];
		$lookup = $lookupField->Lookup;
		if ($lookup === NULL)
			return FALSE;
		$tbl = $lookup->getTable();
		if (!$Security->allowLookup(Config("PROJECT_ID") . $tbl->TableName)) // Lookup permission
			return FALSE;

		// Get lookup parameters
		$lookupType = Post("ajax", "unknown");
		$pageSize = -1;
		$offset = -1;
		$searchValue = "";
		if (SameText($lookupType, "modal")) {
			$searchValue = Post("sv", "");
			$pageSize = Post("recperpage", 10);
			$offset = Post("start", 0);
		} elseif (SameText($lookupType, "autosuggest")) {
			$searchValue = Param("q", "");
			$pageSize = Param("n", -1);
			$pageSize = is_numeric($pageSize) ? (int)$pageSize : -1;
			if ($pageSize <= 0)
				$pageSize = Config("AUTO_SUGGEST_MAX_ENTRIES");
			$start = Param("start", -1);
			$start = is_numeric($start) ? (int)$start : -1;
			$page = Param("page", -1);
			$page = is_numeric($page) ? (int)$page : -1;
			$offset = $start >= 0 ? $start : ($page > 0 && $pageSize > 0 ? ($page - 1) * $pageSize : 0);
		}
		$userSelect = Decrypt(Post("s", ""));
		$userFilter = Decrypt(Post("f", ""));
		$userOrderBy = Decrypt(Post("o", ""));
		$keys = Post("keys");
		$lookup->LookupType = $lookupType; // Lookup type
		if ($keys !== NULL) { // Selected records from modal
			if (is_array($keys))
				$keys = implode(Config("MULTIPLE_OPTION_SEPARATOR"), $keys);
			$lookup->FilterFields = []; // Skip parent fields if any
			$lookup->FilterValues[] = $keys; // Lookup values
			$pageSize = -1; // Show all records
		} else { // Lookup values
			$lookup->FilterValues[] = Post("v0", Post("lookupValue", ""));
		}
		$cnt = is_array($lookup->FilterFields) ? count($lookup->FilterFields) : 0;
		for ($i = 1; $i <= $cnt; $i++)
			$lookup->FilterValues[] = Post("v" . $i, "");
		$lookup->SearchValue = $searchValue;
		$lookup->PageSize = $pageSize;
		$lookup->Offset = $offset;
		if ($userSelect != "")
			$lookup->UserSelect = $userSelect;
		if ($userFilter != "")
			$lookup->UserFilter = $userFilter;
		if ($userOrderBy != "")
			$lookup->UserOrderBy = $userOrderBy;
		$lookup->toJson($this); // Use settings from current page
	}

	// Set up API security
	public function setupApiSecurity()
	{
		global $Security;

		// Setup security for API request
		if ($Security->isLoggedIn()) $Security->TablePermission_Loading();
		$Security->loadCurrentUserLevel(Config("PROJECT_ID") . $this->TableName);
		if ($Security->isLoggedIn()) $Security->TablePermission_Loaded();
		$Security->UserID_Loading();
		$Security->loadUserID();
		$Security->UserID_Loaded();
	}
	public $FormClassName = "ew-horizontal ew-form ew-add-form";
	public $IsModal = FALSE;
	public $IsMobileOrModal = FALSE;
	public $DbMasterFilter = "";
	public $DbDetailFilter = "";
	public $StartRecord;
	public $Priv = 0;
	public $OldRecordset;
	public $CopyRecord;

	//
	// Page run
	//

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

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

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

		// Security
		if (ValidApiRequest()) { // API request
			$this->setupApiSecurity(); // Set up API Security
			if (!$Security->canAdd()) {
				SetStatus(401); // Unauthorized
				return;
			}
		} else {
			$Security = new AdvancedSecurity();
			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("salidaslist.php"));
				else
					$this->terminate(GetUrl("login.php"));
				return;
			}
			if ($Security->isLoggedIn()) {
				$Security->UserID_Loading();
				$Security->loadUserID();
				$Security->UserID_Loaded();
			}
		}

		// Create form object
		$CurrentForm = new HttpForm();
		$this->CurrentAction = Param("action"); // Set up current action
		$this->id->Visible = FALSE;
		$this->Fecha_Hora->setVisibility();
		$this->Referencia->setVisibility();
		$this->id_remitente->setVisibility();
		$this->Nota->setVisibility();
		$this->id_Usuario->setVisibility();
		$this->Mes->setVisibility();
		$this->Anio->setVisibility();
		$this->Remitente->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
		// Check permission

		if (!$Security->canAdd()) {
			$this->setFailureMessage(DeniedMessage()); // No permission
			$this->terminate("salidaslist.php");
			return;
		}

		// 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("id") !== NULL) {
				$this->id->setQueryStringValue(Get("id"));
				$this->setKey("id", $this->id->CurrentValue); // Set up key
			} else {
				$this->setKey("id", ""); // Clear key
				$this->CopyRecord = FALSE;
			}
			if ($this->CopyRecord) {
				$this->CurrentAction = "copy"; // Copy record
			} else {
				$this->CurrentAction = "show"; // Display blank record
			}
		}

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

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

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

		// Perform current action
		switch ($this->CurrentAction) {
			case "copy": // Copy an existing record
				if (!$loaded) { // Record not loaded
					if ($this->getFailureMessage() == "")
						$this->setFailureMessage($Language->phrase("NoRecord")); // No record found
					$this->terminate("salidaslist.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) == "salidaslist.php")
						$returnUrl = $this->addMasterUrl($returnUrl); // List page, return to List page with correct master key if necessary
					elseif (GetPageName($returnUrl) == "salidasview.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->id->CurrentValue = NULL;
		$this->id->OldValue = $this->id->CurrentValue;
		$this->Fecha_Hora->CurrentValue = NULL;
		$this->Fecha_Hora->OldValue = $this->Fecha_Hora->CurrentValue;
		$this->Referencia->CurrentValue = NULL;
		$this->Referencia->OldValue = $this->Referencia->CurrentValue;
		$this->id_remitente->CurrentValue = NULL;
		$this->id_remitente->OldValue = $this->id_remitente->CurrentValue;
		$this->Nota->CurrentValue = NULL;
		$this->Nota->OldValue = $this->Nota->CurrentValue;
		$this->id_Usuario->CurrentValue = NULL;
		$this->id_Usuario->OldValue = $this->id_Usuario->CurrentValue;
		$this->Mes->CurrentValue = NULL;
		$this->Mes->OldValue = $this->Mes->CurrentValue;
		$this->Anio->CurrentValue = NULL;
		$this->Anio->OldValue = $this->Anio->CurrentValue;
		$this->Remitente->CurrentValue = NULL;
		$this->Remitente->OldValue = $this->Remitente->CurrentValue;
	}

	// Load form values
	protected function loadFormValues()
	{

		// Load from form
		global $CurrentForm;

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

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

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

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

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

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

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

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

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

	// Restore form values
	public function restoreFormValues()
	{
		global $CurrentForm;
		$this->Fecha_Hora->CurrentValue = $this->Fecha_Hora->FormValue;
		$this->Fecha_Hora->CurrentValue = UnFormatDateTime($this->Fecha_Hora->CurrentValue, 0);
		$this->Referencia->CurrentValue = $this->Referencia->FormValue;
		$this->id_remitente->CurrentValue = $this->id_remitente->FormValue;
		$this->Nota->CurrentValue = $this->Nota->FormValue;
		$this->id_Usuario->CurrentValue = $this->id_Usuario->FormValue;
		$this->Mes->CurrentValue = $this->Mes->FormValue;
		$this->Anio->CurrentValue = $this->Anio->FormValue;
		$this->Remitente->CurrentValue = $this->Remitente->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->id->setDbValue($row['id']);
		$this->Fecha_Hora->setDbValue($row['Fecha_Hora']);
		$this->Referencia->setDbValue($row['Referencia']);
		$this->id_remitente->setDbValue($row['id_remitente']);
		$this->Nota->setDbValue($row['Nota']);
		$this->id_Usuario->setDbValue($row['id_Usuario']);
		$this->Mes->setDbValue($row['Mes']);
		$this->Anio->setDbValue($row['Anio']);
		$this->Remitente->setDbValue($row['Remitente']);
	}

	// Return a row with default values
	protected function newRow()
	{
		$this->loadDefaultValues();
		$row = [];
		$row['id'] = $this->id->CurrentValue;
		$row['Fecha_Hora'] = $this->Fecha_Hora->CurrentValue;
		$row['Referencia'] = $this->Referencia->CurrentValue;
		$row['id_remitente'] = $this->id_remitente->CurrentValue;
		$row['Nota'] = $this->Nota->CurrentValue;
		$row['id_Usuario'] = $this->id_Usuario->CurrentValue;
		$row['Mes'] = $this->Mes->CurrentValue;
		$row['Anio'] = $this->Anio->CurrentValue;
		$row['Remitente'] = $this->Remitente->CurrentValue;
		return $row;
	}

	// Load old record
	protected function loadOldRecord()
	{

		// Load key values from Session
		$validKey = TRUE;
		if (strval($this->getKey("id")) != "")
			$this->id->OldValue = $this->getKey("id"); // id
		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
		// id
		// Fecha_Hora
		// Referencia
		// id_remitente
		// Nota
		// id_Usuario
		// Mes
		// Anio
		// Remitente

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

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

			// Fecha_Hora
			$this->Fecha_Hora->ViewValue = $this->Fecha_Hora->CurrentValue;
			$this->Fecha_Hora->ViewValue = FormatDateTime($this->Fecha_Hora->ViewValue, 0);
			$this->Fecha_Hora->ViewCustomAttributes = "";

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

			// Referencia
			$this->Referencia->EditAttrs["class"] = "form-control";
			$this->Referencia->EditCustomAttributes = "";
			if (!$this->Referencia->Raw)
				$this->Referencia->CurrentValue = HtmlDecode($this->Referencia->CurrentValue);
			$this->Referencia->EditValue = HtmlEncode($this->Referencia->CurrentValue);
			$this->Referencia->PlaceHolder = RemoveHtml($this->Referencia->caption());

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

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

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

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

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

			// Remitente
			$this->Remitente->EditAttrs["class"] = "form-control";
			$this->Remitente->EditCustomAttributes = "";
			if (!$this->Remitente->Raw)
				$this->Remitente->CurrentValue = HtmlDecode($this->Remitente->CurrentValue);
			$this->Remitente->EditValue = HtmlEncode($this->Remitente->CurrentValue);
			$this->Remitente->PlaceHolder = RemoveHtml($this->Remitente->caption());

			// Add refer script
			// Fecha_Hora

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

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

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

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

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

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

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

			// Remitente
			$this->Remitente->LinkCustomAttributes = "";
			$this->Remitente->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 (!Config("SERVER_VALIDATE"))
			return ($FormError == "");
		if ($this->Fecha_Hora->Required) {
			if (!$this->Fecha_Hora->IsDetailKey && $this->Fecha_Hora->FormValue != NULL && $this->Fecha_Hora->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->Fecha_Hora->caption(), $this->Fecha_Hora->RequiredErrorMessage));
			}
		}
		if (!CheckDate($this->Fecha_Hora->FormValue)) {
			AddMessage($FormError, $this->Fecha_Hora->errorMessage());
		}
		if ($this->Referencia->Required) {
			if (!$this->Referencia->IsDetailKey && $this->Referencia->FormValue != NULL && $this->Referencia->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->Referencia->caption(), $this->Referencia->RequiredErrorMessage));
			}
		}
		if ($this->id_remitente->Required) {
			if (!$this->id_remitente->IsDetailKey && $this->id_remitente->FormValue != NULL && $this->id_remitente->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->id_remitente->caption(), $this->id_remitente->RequiredErrorMessage));
			}
		}
		if (!CheckInteger($this->id_remitente->FormValue)) {
			AddMessage($FormError, $this->id_remitente->errorMessage());
		}
		if ($this->Nota->Required) {
			if (!$this->Nota->IsDetailKey && $this->Nota->FormValue != NULL && $this->Nota->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->Nota->caption(), $this->Nota->RequiredErrorMessage));
			}
		}
		if ($this->id_Usuario->Required) {
			if (!$this->id_Usuario->IsDetailKey && $this->id_Usuario->FormValue != NULL && $this->id_Usuario->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->id_Usuario->caption(), $this->id_Usuario->RequiredErrorMessage));
			}
		}
		if (!CheckInteger($this->id_Usuario->FormValue)) {
			AddMessage($FormError, $this->id_Usuario->errorMessage());
		}
		if ($this->Mes->Required) {
			if (!$this->Mes->IsDetailKey && $this->Mes->FormValue != NULL && $this->Mes->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->Mes->caption(), $this->Mes->RequiredErrorMessage));
			}
		}
		if (!CheckInteger($this->Mes->FormValue)) {
			AddMessage($FormError, $this->Mes->errorMessage());
		}
		if ($this->Anio->Required) {
			if (!$this->Anio->IsDetailKey && $this->Anio->FormValue != NULL && $this->Anio->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->Anio->caption(), $this->Anio->RequiredErrorMessage));
			}
		}
		if (!CheckInteger($this->Anio->FormValue)) {
			AddMessage($FormError, $this->Anio->errorMessage());
		}
		if ($this->Remitente->Required) {
			if (!$this->Remitente->IsDetailKey && $this->Remitente->FormValue != NULL && $this->Remitente->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->Remitente->caption(), $this->Remitente->RequiredErrorMessage));
			}
		}

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

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

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

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

		// Fecha_Hora
		$this->Fecha_Hora->setDbValueDef($rsnew, UnFormatDateTime($this->Fecha_Hora->CurrentValue, 0), CurrentDate(), FALSE);

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

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

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

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

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

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

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

		// Call Row Inserting event
		$rs = ($rsold) ? $rsold->fields : NULL;
		$insertRow = $this->Row_Inserting($rs, $rsnew);
		if ($insertRow) {
			$conn->raiseErrorFn = Config("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);
		}

		// Clean upload path if any
		if ($addRow) {
		}

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

	// Set up Breadcrumb
	protected function setupBreadcrumb()
	{
		global $Breadcrumb, $Language;
		$Breadcrumb = new Breadcrumb();
		$url = substr(CurrentUrl(), strrpos(CurrentUrl(), "/")+1);
		$Breadcrumb->add("list", $this->TableVar, $this->addMasterUrl("salidaslist.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) {

			// Get default connection and filter
			$conn = $this->getConnection();
			$lookupFilter = "";

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

			// Set up lookup SQL and connection
			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) {
				$totalCnt = $this->getRecordCount($sql, $conn);
				if ($totalCnt > $fld->LookupCacheCount) // Total count > cache count, do not cache
					return;
				$rs = $conn->execute($sql);
				$ar = [];
				while ($rs && !$rs->EOF) {
					$row = &$rs->fields;

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

	// Page Load event
	function Page_Load() {

		//echo "Page Load";
	}

	// Page Unload event
	function Page_Unload() {

		//echo "Page Unload";
	}

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

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

	}

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

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

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

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

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

	// Page Render event
	function Page_Render() {

		//echo "Page Render";
	}

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

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

	}

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

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

	}

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

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