<?php
namespace PHPMaker2020\recetarios_2021;

/**
 * Page class
 */
class usuarios_add extends usuarios
{

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

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

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

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

		// 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 $usuarios;
		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($usuarios);
				$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 == "usuariosview.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("usuarioslist.php"));
				else
					$this->terminate(GetUrl("login.php"));
				return;
			}
			if ($Security->isLoggedIn()) {
				$Security->UserID_Loading();
				$Security->loadUserID();
				$Security->UserID_Loaded();
				if (strval($Security->currentUserID()) == "") {
					$this->setFailureMessage(DeniedMessage()); // Set no permission
					$this->terminate(GetUrl("usuarioslist.php"));
					return;
				}
			}
		}

		// Create form object
		$CurrentForm = new HttpForm();
		$this->CurrentAction = Param("action"); // Set up current action
		$this->id->Visible = FALSE;
		$this->Apellido->setVisibility();
		$this->Nombre->setVisibility();
		$this->Usuario->setVisibility();
		$this->Contrasena->setVisibility();
		$this->ReportarA->setVisibility();
		$this->UsuarioNivel->setVisibility();
		$this->Activado->setVisibility();
		$this->Fecha_Nacimiento->setVisibility();
		$this->Direccion->setVisibility();
		$this->Localidad->setVisibility();
		$this->Provincia->setVisibility();
		$this->CodigoPostal->setVisibility();
		$this->Telefono->setVisibility();
		$this->Extension->setVisibility();
		$this->_Email->setVisibility();
		$this->Foto->setVisibility();
		$this->Notas->setVisibility();
		$this->Perfil->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->UsuarioNivel);

		// Check permission
		if (!$Security->canAdd()) {
			$this->setFailureMessage(DeniedMessage()); // No permission
			$this->terminate("usuarioslist.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("usuarioslist.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) == "usuarioslist.php")
						$returnUrl = $this->addMasterUrl($returnUrl); // List page, return to List page with correct master key if necessary
					elseif (GetPageName($returnUrl) == "usuariosview.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->Apellido->CurrentValue = NULL;
		$this->Apellido->OldValue = $this->Apellido->CurrentValue;
		$this->Nombre->CurrentValue = NULL;
		$this->Nombre->OldValue = $this->Nombre->CurrentValue;
		$this->Usuario->CurrentValue = NULL;
		$this->Usuario->OldValue = $this->Usuario->CurrentValue;
		$this->Contrasena->CurrentValue = NULL;
		$this->Contrasena->OldValue = $this->Contrasena->CurrentValue;
		$this->ReportarA->CurrentValue = NULL;
		$this->ReportarA->OldValue = $this->ReportarA->CurrentValue;
		$this->UsuarioNivel->CurrentValue = NULL;
		$this->UsuarioNivel->OldValue = $this->UsuarioNivel->CurrentValue;
		$this->Activado->CurrentValue = "N";
		$this->Fecha_Nacimiento->CurrentValue = NULL;
		$this->Fecha_Nacimiento->OldValue = $this->Fecha_Nacimiento->CurrentValue;
		$this->Direccion->CurrentValue = NULL;
		$this->Direccion->OldValue = $this->Direccion->CurrentValue;
		$this->Localidad->CurrentValue = NULL;
		$this->Localidad->OldValue = $this->Localidad->CurrentValue;
		$this->Provincia->CurrentValue = NULL;
		$this->Provincia->OldValue = $this->Provincia->CurrentValue;
		$this->CodigoPostal->CurrentValue = NULL;
		$this->CodigoPostal->OldValue = $this->CodigoPostal->CurrentValue;
		$this->Telefono->CurrentValue = NULL;
		$this->Telefono->OldValue = $this->Telefono->CurrentValue;
		$this->Extension->CurrentValue = NULL;
		$this->Extension->OldValue = $this->Extension->CurrentValue;
		$this->_Email->CurrentValue = NULL;
		$this->_Email->OldValue = $this->_Email->CurrentValue;
		$this->Foto->CurrentValue = NULL;
		$this->Foto->OldValue = $this->Foto->CurrentValue;
		$this->Notas->CurrentValue = NULL;
		$this->Notas->OldValue = $this->Notas->CurrentValue;
		$this->Perfil->CurrentValue = NULL;
		$this->Perfil->OldValue = $this->Perfil->CurrentValue;
	}

	// Load form values
	protected function loadFormValues()
	{

		// Load from form
		global $CurrentForm;

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

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

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

		// Check field name 'Contrasena' first before field var 'x_Contrasena'
		$val = $CurrentForm->hasValue("Contrasena") ? $CurrentForm->getValue("Contrasena") : $CurrentForm->getValue("x_Contrasena");
		if (!$this->Contrasena->IsDetailKey) {
			if (IsApi() && $val == NULL)
				$this->Contrasena->Visible = FALSE; // Disable update for API request
			else
				if (Config("ENCRYPTED_PASSWORD")) // Encrypted password, use raw value
					$this->Contrasena->setRawFormValue($val);
				else
					$this->Contrasena->setFormValue($val);
		}

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

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

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

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

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

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

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

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

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

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

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

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

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

		// Check field name 'Perfil' first before field var 'x_Perfil'
		$val = $CurrentForm->hasValue("Perfil") ? $CurrentForm->getValue("Perfil") : $CurrentForm->getValue("x_Perfil");
		if (!$this->Perfil->IsDetailKey) {
			if (IsApi() && $val == NULL)
				$this->Perfil->Visible = FALSE; // Disable update for API request
			else
				$this->Perfil->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->Apellido->CurrentValue = $this->Apellido->FormValue;
		$this->Nombre->CurrentValue = $this->Nombre->FormValue;
		$this->Usuario->CurrentValue = $this->Usuario->FormValue;
		$this->Contrasena->CurrentValue = $this->Contrasena->FormValue;
		$this->ReportarA->CurrentValue = $this->ReportarA->FormValue;
		$this->UsuarioNivel->CurrentValue = $this->UsuarioNivel->FormValue;
		$this->Activado->CurrentValue = $this->Activado->FormValue;
		$this->Fecha_Nacimiento->CurrentValue = $this->Fecha_Nacimiento->FormValue;
		$this->Fecha_Nacimiento->CurrentValue = UnFormatDateTime($this->Fecha_Nacimiento->CurrentValue, 0);
		$this->Direccion->CurrentValue = $this->Direccion->FormValue;
		$this->Localidad->CurrentValue = $this->Localidad->FormValue;
		$this->Provincia->CurrentValue = $this->Provincia->FormValue;
		$this->CodigoPostal->CurrentValue = $this->CodigoPostal->FormValue;
		$this->Telefono->CurrentValue = $this->Telefono->FormValue;
		$this->Extension->CurrentValue = $this->Extension->FormValue;
		$this->_Email->CurrentValue = $this->_Email->FormValue;
		$this->Foto->CurrentValue = $this->Foto->FormValue;
		$this->Notas->CurrentValue = $this->Notas->FormValue;
		$this->Perfil->CurrentValue = $this->Perfil->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();
		}

		// Check if valid User ID
		if ($res) {
			$res = $this->showOptionLink('add');
			if (!$res) {
				$userIdMsg = DeniedMessage();
				$this->setFailureMessage($userIdMsg);
			}
		}
		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->Apellido->setDbValue($row['Apellido']);
		$this->Nombre->setDbValue($row['Nombre']);
		$this->Usuario->setDbValue($row['Usuario']);
		$this->Contrasena->setDbValue($row['Contrasena']);
		$this->ReportarA->setDbValue($row['ReportarA']);
		$this->UsuarioNivel->setDbValue($row['UsuarioNivel']);
		$this->Activado->setDbValue($row['Activado']);
		$this->Fecha_Nacimiento->setDbValue($row['Fecha_Nacimiento']);
		$this->Direccion->setDbValue($row['Direccion']);
		$this->Localidad->setDbValue($row['Localidad']);
		$this->Provincia->setDbValue($row['Provincia']);
		$this->CodigoPostal->setDbValue($row['CodigoPostal']);
		$this->Telefono->setDbValue($row['Telefono']);
		$this->Extension->setDbValue($row['Extension']);
		$this->_Email->setDbValue($row['Email']);
		$this->Foto->setDbValue($row['Foto']);
		$this->Notas->setDbValue($row['Notas']);
		$this->Perfil->setDbValue($row['Perfil']);
	}

	// Return a row with default values
	protected function newRow()
	{
		$this->loadDefaultValues();
		$row = [];
		$row['id'] = $this->id->CurrentValue;
		$row['Apellido'] = $this->Apellido->CurrentValue;
		$row['Nombre'] = $this->Nombre->CurrentValue;
		$row['Usuario'] = $this->Usuario->CurrentValue;
		$row['Contrasena'] = $this->Contrasena->CurrentValue;
		$row['ReportarA'] = $this->ReportarA->CurrentValue;
		$row['UsuarioNivel'] = $this->UsuarioNivel->CurrentValue;
		$row['Activado'] = $this->Activado->CurrentValue;
		$row['Fecha_Nacimiento'] = $this->Fecha_Nacimiento->CurrentValue;
		$row['Direccion'] = $this->Direccion->CurrentValue;
		$row['Localidad'] = $this->Localidad->CurrentValue;
		$row['Provincia'] = $this->Provincia->CurrentValue;
		$row['CodigoPostal'] = $this->CodigoPostal->CurrentValue;
		$row['Telefono'] = $this->Telefono->CurrentValue;
		$row['Extension'] = $this->Extension->CurrentValue;
		$row['Email'] = $this->_Email->CurrentValue;
		$row['Foto'] = $this->Foto->CurrentValue;
		$row['Notas'] = $this->Notas->CurrentValue;
		$row['Perfil'] = $this->Perfil->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
		// Apellido
		// Nombre
		// Usuario
		// Contrasena
		// ReportarA
		// UsuarioNivel
		// Activado
		// Fecha_Nacimiento
		// Direccion
		// Localidad
		// Provincia
		// CodigoPostal
		// Telefono
		// Extension
		// Email
		// Foto
		// Notas
		// Perfil

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

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

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

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

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

			// Contrasena
			$this->Contrasena->ViewValue = $Language->phrase("PasswordMask");
			$this->Contrasena->ViewCustomAttributes = "";

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

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

			// Activado
			if (ConvertToBool($this->Activado->CurrentValue)) {
				$this->Activado->ViewValue = $this->Activado->tagCaption(1) != "" ? $this->Activado->tagCaption(1) : "Y";
			} else {
				$this->Activado->ViewValue = $this->Activado->tagCaption(2) != "" ? $this->Activado->tagCaption(2) : "N";
			}
			$this->Activado->ViewCustomAttributes = "";

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

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

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

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

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

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

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

			// Email
			$this->_Email->ViewValue = $this->_Email->CurrentValue;
			$this->_Email->ViewCustomAttributes = "";

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

			// Email
			$this->_Email->LinkCustomAttributes = "";
			$this->_Email->HrefValue = "";
			$this->_Email->TooltipValue = "";

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

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

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

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

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

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

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

			// ReportarA
			$this->ReportarA->EditAttrs["class"] = "form-control";
			$this->ReportarA->EditCustomAttributes = "";
			if (!$Security->isAdmin() && $Security->isLoggedIn()) { // Non system admin
			} else {
				$this->ReportarA->EditValue = HtmlEncode($this->ReportarA->CurrentValue);
				$this->ReportarA->PlaceHolder = RemoveHtml($this->ReportarA->caption());
			}

			// UsuarioNivel
			$this->UsuarioNivel->EditAttrs["class"] = "form-control";
			$this->UsuarioNivel->EditCustomAttributes = "";
			if (!$Security->canAdmin()) { // System admin
				$this->UsuarioNivel->EditValue = $Language->phrase("PasswordMask");
			} else {
				$curVal = trim(strval($this->UsuarioNivel->CurrentValue));
				if ($curVal != "")
					$this->UsuarioNivel->ViewValue = $this->UsuarioNivel->lookupCacheOption($curVal);
				else
					$this->UsuarioNivel->ViewValue = $this->UsuarioNivel->Lookup !== NULL && is_array($this->UsuarioNivel->Lookup->Options) ? $curVal : NULL;
				if ($this->UsuarioNivel->ViewValue !== NULL) { // Load from cache
					$this->UsuarioNivel->EditValue = array_values($this->UsuarioNivel->Lookup->Options);
				} else { // Lookup from database
					if ($curVal == "") {
						$filterWrk = "0=1";
					} else {
						$filterWrk = "`userlevelid`" . SearchString("=", $this->UsuarioNivel->CurrentValue, DATATYPE_NUMBER, "");
					}
					$sqlWrk = $this->UsuarioNivel->Lookup->getSql(TRUE, $filterWrk, '', $this);
					$rswrk = Conn()->execute($sqlWrk);
					$arwrk = $rswrk ? $rswrk->getRows() : [];
					if ($rswrk)
						$rswrk->close();
					$this->UsuarioNivel->EditValue = $arwrk;
				}
			}

			// Activado
			$this->Activado->EditCustomAttributes = "";
			$this->Activado->EditValue = $this->Activado->options(FALSE);

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

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

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

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

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

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

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

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

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

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

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

			// Add refer script
			// Apellido

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

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

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

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

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

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

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

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

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

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

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

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

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

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

			// Email
			$this->_Email->LinkCustomAttributes = "";
			$this->_Email->HrefValue = "";

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

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

			// Perfil
			$this->Perfil->LinkCustomAttributes = "";
			$this->Perfil->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->Apellido->Required) {
			if (!$this->Apellido->IsDetailKey && $this->Apellido->FormValue != NULL && $this->Apellido->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->Apellido->caption(), $this->Apellido->RequiredErrorMessage));
			}
		}
		if ($this->Nombre->Required) {
			if (!$this->Nombre->IsDetailKey && $this->Nombre->FormValue != NULL && $this->Nombre->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->Nombre->caption(), $this->Nombre->RequiredErrorMessage));
			}
		}
		if ($this->Usuario->Required) {
			if (!$this->Usuario->IsDetailKey && $this->Usuario->FormValue != NULL && $this->Usuario->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->Usuario->caption(), $this->Usuario->RequiredErrorMessage));
			}
		}
		if ($this->Contrasena->Required) {
			if (!$this->Contrasena->IsDetailKey && $this->Contrasena->FormValue != NULL && $this->Contrasena->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->Contrasena->caption(), $this->Contrasena->RequiredErrorMessage));
			}
		}
		if ($this->ReportarA->Required) {
			if (!$this->ReportarA->IsDetailKey && $this->ReportarA->FormValue != NULL && $this->ReportarA->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->ReportarA->caption(), $this->ReportarA->RequiredErrorMessage));
			}
		}
		if (!CheckInteger($this->ReportarA->FormValue)) {
			AddMessage($FormError, $this->ReportarA->errorMessage());
		}
		if ($this->UsuarioNivel->Required) {
			if (!$this->UsuarioNivel->IsDetailKey && $this->UsuarioNivel->FormValue != NULL && $this->UsuarioNivel->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->UsuarioNivel->caption(), $this->UsuarioNivel->RequiredErrorMessage));
			}
		}
		if ($this->Activado->Required) {
			if ($this->Activado->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->Activado->caption(), $this->Activado->RequiredErrorMessage));
			}
		}
		if ($this->Fecha_Nacimiento->Required) {
			if (!$this->Fecha_Nacimiento->IsDetailKey && $this->Fecha_Nacimiento->FormValue != NULL && $this->Fecha_Nacimiento->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->Fecha_Nacimiento->caption(), $this->Fecha_Nacimiento->RequiredErrorMessage));
			}
		}
		if (!CheckDate($this->Fecha_Nacimiento->FormValue)) {
			AddMessage($FormError, $this->Fecha_Nacimiento->errorMessage());
		}
		if ($this->Direccion->Required) {
			if (!$this->Direccion->IsDetailKey && $this->Direccion->FormValue != NULL && $this->Direccion->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->Direccion->caption(), $this->Direccion->RequiredErrorMessage));
			}
		}
		if ($this->Localidad->Required) {
			if (!$this->Localidad->IsDetailKey && $this->Localidad->FormValue != NULL && $this->Localidad->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->Localidad->caption(), $this->Localidad->RequiredErrorMessage));
			}
		}
		if ($this->Provincia->Required) {
			if (!$this->Provincia->IsDetailKey && $this->Provincia->FormValue != NULL && $this->Provincia->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->Provincia->caption(), $this->Provincia->RequiredErrorMessage));
			}
		}
		if ($this->CodigoPostal->Required) {
			if (!$this->CodigoPostal->IsDetailKey && $this->CodigoPostal->FormValue != NULL && $this->CodigoPostal->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->CodigoPostal->caption(), $this->CodigoPostal->RequiredErrorMessage));
			}
		}
		if ($this->Telefono->Required) {
			if (!$this->Telefono->IsDetailKey && $this->Telefono->FormValue != NULL && $this->Telefono->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->Telefono->caption(), $this->Telefono->RequiredErrorMessage));
			}
		}
		if ($this->Extension->Required) {
			if (!$this->Extension->IsDetailKey && $this->Extension->FormValue != NULL && $this->Extension->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->Extension->caption(), $this->Extension->RequiredErrorMessage));
			}
		}
		if ($this->_Email->Required) {
			if (!$this->_Email->IsDetailKey && $this->_Email->FormValue != NULL && $this->_Email->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->_Email->caption(), $this->_Email->RequiredErrorMessage));
			}
		}
		if ($this->Foto->Required) {
			if (!$this->Foto->IsDetailKey && $this->Foto->FormValue != NULL && $this->Foto->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->Foto->caption(), $this->Foto->RequiredErrorMessage));
			}
		}
		if ($this->Notas->Required) {
			if (!$this->Notas->IsDetailKey && $this->Notas->FormValue != NULL && $this->Notas->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->Notas->caption(), $this->Notas->RequiredErrorMessage));
			}
		}
		if ($this->Perfil->Required) {
			if (!$this->Perfil->IsDetailKey && $this->Perfil->FormValue != NULL && $this->Perfil->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->Perfil->caption(), $this->Perfil->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 if valid User ID
		$validUser = FALSE;
		if ($Security->currentUserID() != "" && !EmptyValue($this->id->CurrentValue) && !$Security->isAdmin()) { // Non system admin
			$validUser = $Security->isValidUserID($this->id->CurrentValue);
			if (!$validUser) {
				$userIdMsg = str_replace("%c", CurrentUserID(), $Language->phrase("UnAuthorizedUserID"));
				$userIdMsg = str_replace("%u", $this->id->CurrentValue, $userIdMsg);
				$this->setFailureMessage($userIdMsg);
				return FALSE;
			}
		}

		// Check if valid Parent User ID
		$validParentUser = FALSE;
		if ($Security->currentUserID() != "" && !EmptyValue($this->ReportarA->CurrentValue) && !$Security->isAdmin()) { // Non system admin
			$validParentUser = $Security->isValidUserID($this->ReportarA->CurrentValue);
			if (!$validParentUser) {
				$parentUserIdMsg = str_replace("%c", CurrentUserID(), $Language->phrase("UnAuthorizedParentUserID"));
				$parentUserIdMsg = str_replace("%p", $this->ReportarA->CurrentValue, $parentUserIdMsg);
				$this->setFailureMessage($parentUserIdMsg);
				return FALSE;
			}
		}
		$conn = $this->getConnection();

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

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

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

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

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

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

		// UsuarioNivel
		
		if ($Security->canAdmin()) { // System admin
			
			$this->UsuarioNivel->setDbValueDef($rsnew, $this->UsuarioNivel->CurrentValue, NULL, FALSE);
			
		}
		

		// Activado
		$tmpBool = $this->Activado->CurrentValue;
		if ($tmpBool != "Y" && $tmpBool != "N")
			$tmpBool = !empty($tmpBool) ? "Y" : "N";
		$this->Activado->setDbValueDef($rsnew, $tmpBool, "N", strval($this->Activado->CurrentValue) == "");

		// Fecha_Nacimiento
		$this->Fecha_Nacimiento->setDbValueDef($rsnew, UnFormatDateTime($this->Fecha_Nacimiento->CurrentValue, 0), NULL, FALSE);

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

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

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

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

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

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

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

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

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

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

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

	// Show link optionally based on User ID
	protected function showOptionLink($id = "")
	{
		global $Security;
		if ($Security->isLoggedIn() && !$Security->isAdmin() && !$this->userIDAllow($id))
			return $Security->isValidUserID($this->id->CurrentValue);
		return TRUE;
	}

	// 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("usuarioslist.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) {
				case "x_UsuarioNivel":
					break;
				case "x_Activado":
					break;
				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) {
						case "x_UsuarioNivel":
							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;
	}
} // End class
?>