<?php
namespace PHPMaker2019\project_germanos;

/**
 * Table class for files
 */
class files extends DbTable
{
	protected $SqlFrom = "";
	protected $SqlSelect = "";
	protected $SqlSelectList = "";
	protected $SqlWhere = "";
	protected $SqlGroupBy = "";
	protected $SqlHaving = "";
	protected $SqlOrderBy = "";
	public $UseSessionForListSql = TRUE;

	// Column CSS classes
	public $LeftColumnClass = "col-sm-2 col-form-label ew-label";
	public $RightColumnClass = "col-sm-10";
	public $OffsetColumnClass = "col-sm-10 offset-sm-2";
	public $TableLeftColumnClass = "w-col-2";

	// Audit trail
	public $AuditTrailOnAdd = TRUE;
	public $AuditTrailOnEdit = TRUE;
	public $AuditTrailOnDelete = TRUE;
	public $AuditTrailOnView = TRUE;
	public $AuditTrailOnViewData = FALSE;
	public $AuditTrailOnSearch = FALSE;

	// Export
	public $ExportDoc;

	// Fields
	public $FileID;
	public $CaseNumber;
	public $FileNumber;
	public $EnvelopeNumber;
	public $FileLocation;
	public $_Case;
	public $CaseEn;
	public $CaseType;
	public $ClientName;
	public $LitigantName;
	public $CourtName;
	public $CourtTypeName;
	public $CourtGenderName;
	public $JudgeName;
	public $Notes;
	public $CreatedBy;
	public $CreatedDate;
	public $UpdatedBy;
	public $UpdatedDate;
	public $CourtID;
	public $ClientID;
	public $LitigantID;

	// Constructor
	public function __construct()
	{
		global $Language, $CurrentLanguage;

		// Language object
		if (!isset($Language))
			$Language = new Language();
		$this->TableVar = 'files';
		$this->TableName = 'files';
		$this->TableType = 'TABLE';

		// Update Table
		$this->UpdateTable = "`files`";
		$this->Dbid = 'DB';
		$this->ExportAll = TRUE;
		$this->ExportPageBreakCount = 0; // Page break per every n record (PDF only)
		$this->ExportPageOrientation = "portrait"; // Page orientation (PDF only)
		$this->ExportPageSize = "a4"; // Page size (PDF only)
		$this->ExportExcelPageOrientation = \PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::ORIENTATION_DEFAULT; // Page orientation (PhpSpreadsheet only)
		$this->ExportExcelPageSize = \PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_A4; // Page size (PhpSpreadsheet only)
		$this->ExportWordPageOrientation = "portrait"; // Page orientation (PHPWord only)
		$this->ExportWordColumnWidth = NULL; // Cell width (PHPWord only)
		$this->DetailAdd = FALSE; // Allow detail add
		$this->DetailEdit = FALSE; // Allow detail edit
		$this->DetailView = FALSE; // Allow detail view
		$this->ShowMultipleDetails = FALSE; // Show multiple details
		$this->GridAddRowCount = 5;
		$this->AllowAddDeleteRow = TRUE; // Allow add/delete row
		$this->UserIDAllowSecurity = 0; // User ID Allow
		$this->BasicSearch = new BasicSearch($this->TableVar);
		$this->BasicSearch->TypeDefault = "AND";

		// FileID
		$this->FileID = new DbField('files', 'files', 'x_FileID', 'FileID', '`FileID`', '`FileID`', 3, -1, FALSE, '`FileID`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'NO');
		$this->FileID->IsAutoIncrement = TRUE; // Autoincrement field
		$this->FileID->IsPrimaryKey = TRUE; // Primary key field
		$this->FileID->Sortable = TRUE; // Allow sort
		$this->FileID->DefaultErrorMessage = $Language->phrase("IncorrectInteger");
		$this->fields['FileID'] = &$this->FileID;

		// CaseNumber
		$this->CaseNumber = new DbField('files', 'files', 'x_CaseNumber', 'CaseNumber', '`CaseNumber`', '`CaseNumber`', 200, -1, FALSE, '`CaseNumber`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->CaseNumber->Sortable = TRUE; // Allow sort
		$this->fields['CaseNumber'] = &$this->CaseNumber;

		// FileNumber
		$this->FileNumber = new DbField('files', 'files', 'x_FileNumber', 'FileNumber', '`FileNumber`', '`FileNumber`', 200, -1, FALSE, '`FileNumber`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->FileNumber->Sortable = TRUE; // Allow sort
		$this->fields['FileNumber'] = &$this->FileNumber;

		// EnvelopeNumber
		$this->EnvelopeNumber = new DbField('files', 'files', 'x_EnvelopeNumber', 'EnvelopeNumber', '`EnvelopeNumber`', '`EnvelopeNumber`', 200, -1, FALSE, '`EnvelopeNumber`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->EnvelopeNumber->Sortable = TRUE; // Allow sort
		$this->fields['EnvelopeNumber'] = &$this->EnvelopeNumber;

		// FileLocation
		$this->FileLocation = new DbField('files', 'files', 'x_FileLocation', 'FileLocation', '`FileLocation`', '`FileLocation`', 200, -1, FALSE, '`FileLocation`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->FileLocation->Sortable = TRUE; // Allow sort
		$this->fields['FileLocation'] = &$this->FileLocation;

		// Case
		$this->_Case = new DbField('files', 'files', 'x__Case', 'Case', '`Case`', '`Case`', 200, -1, FALSE, '`Case`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->_Case->Sortable = TRUE; // Allow sort
		$this->fields['Case'] = &$this->_Case;

		// CaseEn
		$this->CaseEn = new DbField('files', 'files', 'x_CaseEn', 'CaseEn', '`CaseEn`', '`CaseEn`', 200, -1, FALSE, '`CaseEn`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->CaseEn->Sortable = FALSE; // Allow sort
		$this->fields['CaseEn'] = &$this->CaseEn;

		// CaseType
		$this->CaseType = new DbField('files', 'files', 'x_CaseType', 'CaseType', '`CaseType`', '`CaseType`', 200, -1, FALSE, '`CaseType`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->CaseType->Sortable = TRUE; // Allow sort
		$this->fields['CaseType'] = &$this->CaseType;

		// ClientName
		$this->ClientName = new DbField('files', 'files', 'x_ClientName', 'ClientName', '`ClientName`', '`ClientName`', 200, -1, FALSE, '`ClientName`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->ClientName->Sortable = TRUE; // Allow sort
		$this->fields['ClientName'] = &$this->ClientName;

		// LitigantName
		$this->LitigantName = new DbField('files', 'files', 'x_LitigantName', 'LitigantName', '`LitigantName`', '`LitigantName`', 200, -1, FALSE, '`LitigantName`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->LitigantName->Sortable = TRUE; // Allow sort
		$this->fields['LitigantName'] = &$this->LitigantName;

		// CourtName
		$this->CourtName = new DbField('files', 'files', 'x_CourtName', 'CourtName', '`CourtName`', '`CourtName`', 200, -1, FALSE, '`CourtName`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->CourtName->Sortable = TRUE; // Allow sort
		$this->fields['CourtName'] = &$this->CourtName;

		// CourtTypeName
		$this->CourtTypeName = new DbField('files', 'files', 'x_CourtTypeName', 'CourtTypeName', '`CourtTypeName`', '`CourtTypeName`', 200, -1, FALSE, '`CourtTypeName`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->CourtTypeName->Sortable = FALSE; // Allow sort
		$this->fields['CourtTypeName'] = &$this->CourtTypeName;

		// CourtGenderName
		$this->CourtGenderName = new DbField('files', 'files', 'x_CourtGenderName', 'CourtGenderName', '`CourtGenderName`', '`CourtGenderName`', 200, -1, FALSE, '`CourtGenderName`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->CourtGenderName->Sortable = FALSE; // Allow sort
		$this->fields['CourtGenderName'] = &$this->CourtGenderName;

		// JudgeName
		$this->JudgeName = new DbField('files', 'files', 'x_JudgeName', 'JudgeName', '`JudgeName`', '`JudgeName`', 200, -1, FALSE, '`JudgeName`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->JudgeName->Sortable = TRUE; // Allow sort
		$this->fields['JudgeName'] = &$this->JudgeName;

		// Notes
		$this->Notes = new DbField('files', 'files', 'x_Notes', 'Notes', '`Notes`', '`Notes`', 201, -1, FALSE, '`Notes`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXTAREA');
		$this->Notes->Sortable = TRUE; // Allow sort
		$this->fields['Notes'] = &$this->Notes;

		// CreatedBy
		$this->CreatedBy = new DbField('files', 'files', 'x_CreatedBy', 'CreatedBy', '`CreatedBy`', '`CreatedBy`', 200, -1, FALSE, '`CreatedBy`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->CreatedBy->Sortable = FALSE; // Allow sort
		$this->fields['CreatedBy'] = &$this->CreatedBy;

		// CreatedDate
		$this->CreatedDate = new DbField('files', 'files', 'x_CreatedDate', 'CreatedDate', '`CreatedDate`', CastDateFieldForLike('`CreatedDate`', 0, "DB"), 135, 0, FALSE, '`CreatedDate`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->CreatedDate->Sortable = FALSE; // Allow sort
		$this->CreatedDate->DefaultErrorMessage = str_replace("%s", $GLOBALS["DATE_FORMAT"], $Language->phrase("IncorrectDate"));
		$this->fields['CreatedDate'] = &$this->CreatedDate;

		// UpdatedBy
		$this->UpdatedBy = new DbField('files', 'files', 'x_UpdatedBy', 'UpdatedBy', '`UpdatedBy`', '`UpdatedBy`', 200, -1, FALSE, '`UpdatedBy`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->UpdatedBy->Sortable = FALSE; // Allow sort
		$this->fields['UpdatedBy'] = &$this->UpdatedBy;

		// UpdatedDate
		$this->UpdatedDate = new DbField('files', 'files', 'x_UpdatedDate', 'UpdatedDate', '`UpdatedDate`', CastDateFieldForLike('`UpdatedDate`', 0, "DB"), 135, 0, FALSE, '`UpdatedDate`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->UpdatedDate->Sortable = FALSE; // Allow sort
		$this->UpdatedDate->DefaultErrorMessage = str_replace("%s", $GLOBALS["DATE_FORMAT"], $Language->phrase("IncorrectDate"));
		$this->fields['UpdatedDate'] = &$this->UpdatedDate;

		// CourtID
		$this->CourtID = new DbField('files', 'files', 'x_CourtID', 'CourtID', '`CourtID`', '`CourtID`', 3, -1, FALSE, '`CourtID`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->CourtID->Sortable = FALSE; // Allow sort
		$this->CourtID->DefaultErrorMessage = $Language->phrase("IncorrectInteger");
		$this->fields['CourtID'] = &$this->CourtID;

		// ClientID
		$this->ClientID = new DbField('files', 'files', 'x_ClientID', 'ClientID', '`ClientID`', '`ClientID`', 3, -1, FALSE, '`ClientID`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->ClientID->Sortable = FALSE; // Allow sort
		$this->ClientID->DefaultErrorMessage = $Language->phrase("IncorrectInteger");
		$this->fields['ClientID'] = &$this->ClientID;

		// LitigantID
		$this->LitigantID = new DbField('files', 'files', 'x_LitigantID', 'LitigantID', '`LitigantID`', '`LitigantID`', 3, -1, FALSE, '`LitigantID`', FALSE, FALSE, FALSE, 'FORMATTED TEXT', 'TEXT');
		$this->LitigantID->Sortable = FALSE; // Allow sort
		$this->LitigantID->DefaultErrorMessage = $Language->phrase("IncorrectInteger");
		$this->fields['LitigantID'] = &$this->LitigantID;
	}

	// Field Visibility
	public function getFieldVisibility($fldParm)
	{
		global $Security;
		return $this->$fldParm->Visible; // Returns original value
	}

	// Set left column class (must be predefined col-*-* classes of Bootstrap grid system)
	function setLeftColumnClass($class)
	{
		if (preg_match('/^col\-(\w+)\-(\d+)$/', $class, $match)) {
			$this->LeftColumnClass = $class . " col-form-label ew-label";
			$this->RightColumnClass = "col-" . $match[1] . "-" . strval(12 - (int)$match[2]);
			$this->OffsetColumnClass = $this->RightColumnClass . " " . str_replace("col-", "offset-", $class);
			$this->TableLeftColumnClass = preg_replace('/^col-\w+-(\d+)$/', "w-col-$1", $class); // Change to w-col-*
		}
	}

	// Multiple column sort
	public function updateSort(&$fld, $ctrl)
	{
		if ($this->CurrentOrder == $fld->Name) {
			$sortField = $fld->Expression;
			$lastSort = $fld->getSort();
			if ($this->CurrentOrderType == "ASC" || $this->CurrentOrderType == "DESC") {
				$thisSort = $this->CurrentOrderType;
			} else {
				$thisSort = ($lastSort == "ASC") ? "DESC" : "ASC";
			}
			$fld->setSort($thisSort);
			if ($ctrl) {
				$orderBy = $this->getSessionOrderBy();
				if (ContainsString($orderBy, $sortField . " " . $lastSort)) {
					$orderBy = str_replace($sortField . " " . $lastSort, $sortField . " " . $thisSort, $orderBy);
				} else {
					if ($orderBy <> "")
						$orderBy .= ", ";
					$orderBy .= $sortField . " " . $thisSort;
				}
				$this->setSessionOrderBy($orderBy); // Save to Session
			} else {
				$this->setSessionOrderBy($sortField . " " . $thisSort); // Save to Session
			}
		} else {
			if (!$ctrl)
				$fld->setSort("");
		}
	}

	// Table level SQL
	public function getSqlFrom() // From
	{
		return ($this->SqlFrom <> "") ? $this->SqlFrom : "`files`";
	}
	public function sqlFrom() // For backward compatibility
	{
		return $this->getSqlFrom();
	}
	public function setSqlFrom($v)
	{
		$this->SqlFrom = $v;
	}
	public function getSqlSelect() // Select
	{
		return ($this->SqlSelect <> "") ? $this->SqlSelect : "SELECT * FROM " . $this->getSqlFrom();
	}
	public function sqlSelect() // For backward compatibility
	{
		return $this->getSqlSelect();
	}
	public function setSqlSelect($v)
	{
		$this->SqlSelect = $v;
	}
	public function getSqlWhere() // Where
	{
		$where = ($this->SqlWhere <> "") ? $this->SqlWhere : "";
		$this->TableFilter = "";
		AddFilter($where, $this->TableFilter);
		return $where;
	}
	public function sqlWhere() // For backward compatibility
	{
		return $this->getSqlWhere();
	}
	public function setSqlWhere($v)
	{
		$this->SqlWhere = $v;
	}
	public function getSqlGroupBy() // Group By
	{
		return ($this->SqlGroupBy <> "") ? $this->SqlGroupBy : "";
	}
	public function sqlGroupBy() // For backward compatibility
	{
		return $this->getSqlGroupBy();
	}
	public function setSqlGroupBy($v)
	{
		$this->SqlGroupBy = $v;
	}
	public function getSqlHaving() // Having
	{
		return ($this->SqlHaving <> "") ? $this->SqlHaving : "";
	}
	public function sqlHaving() // For backward compatibility
	{
		return $this->getSqlHaving();
	}
	public function setSqlHaving($v)
	{
		$this->SqlHaving = $v;
	}
	public function getSqlOrderBy() // Order By
	{
		return ($this->SqlOrderBy <> "") ? $this->SqlOrderBy : "";
	}
	public function sqlOrderBy() // For backward compatibility
	{
		return $this->getSqlOrderBy();
	}
	public function setSqlOrderBy($v)
	{
		$this->SqlOrderBy = $v;
	}

	// Apply User ID filters
	public function applyUserIDFilters($filter)
	{
		return $filter;
	}

	// Check if User ID security allows view all
	public function userIDAllow($id = "")
	{
		$allow = USER_ID_ALLOW;
		switch ($id) {
			case "add":
			case "copy":
			case "gridadd":
			case "register":
			case "addopt":
				return (($allow & 1) == 1);
			case "edit":
			case "gridedit":
			case "update":
			case "changepwd":
			case "forgotpwd":
				return (($allow & 4) == 4);
			case "delete":
				return (($allow & 2) == 2);
			case "view":
				return (($allow & 32) == 32);
			case "search":
				return (($allow & 64) == 64);
			default:
				return (($allow & 8) == 8);
		}
	}

	// Get SQL
	public function getSql($where, $orderBy = "")
	{
		return BuildSelectSql($this->getSqlSelect(), $this->getSqlWhere(),
			$this->getSqlGroupBy(), $this->getSqlHaving(), $this->getSqlOrderBy(),
			$where, $orderBy);
	}

	// Table SQL
	public function getCurrentSql()
	{
		$filter = $this->CurrentFilter;
		$filter = $this->applyUserIDFilters($filter);
		$sort = $this->getSessionOrderBy();
		return $this->getSql($filter, $sort);
	}

	// Table SQL with List page filter
	public function getListSql()
	{
		$filter = $this->UseSessionForListSql ? $this->getSessionWhere() : "";
		AddFilter($filter, $this->CurrentFilter);
		$filter = $this->applyUserIDFilters($filter);
		$this->Recordset_Selecting($filter);
		$select = $this->getSqlSelect();
		$sort = $this->UseSessionForListSql ? $this->getSessionOrderBy() : "";
		return BuildSelectSql($select, $this->getSqlWhere(), $this->getSqlGroupBy(),
			$this->getSqlHaving(), $this->getSqlOrderBy(), $filter, $sort);
	}

	// Get ORDER BY clause
	public function getOrderBy()
	{
		$sort = $this->getSessionOrderBy();
		return BuildSelectSql("", "", "", "", $this->getSqlOrderBy(), "", $sort);
	}

	// Get record count
	public function getRecordCount($sql)
	{
		$cnt = -1;
		$rs = NULL;
		$sql = preg_replace('/\/\*BeginOrderBy\*\/[\s\S]+\/\*EndOrderBy\*\//', "", $sql); // Remove ORDER BY clause (MSSQL)
		$pattern = '/^SELECT\s([\s\S]+)\sFROM\s/i';

		// Skip Custom View / SubQuery and SELECT DISTINCT
		if (($this->TableType == 'TABLE' || $this->TableType == 'VIEW' || $this->TableType == 'LINKTABLE') &&
			preg_match($pattern, $sql) && !preg_match('/\(\s*(SELECT[^)]+)\)/i', $sql) && !preg_match('/^\s*select\s+distinct\s+/i', $sql)) {
			$sqlwrk = "SELECT COUNT(*) FROM " . preg_replace($pattern, "", $sql);
		} else {
			$sqlwrk = "SELECT COUNT(*) FROM (" . $sql . ") COUNT_TABLE";
		}
		$conn = &$this->getConnection();
		if ($rs = $conn->execute($sqlwrk)) {
			if (!$rs->EOF && $rs->FieldCount() > 0) {
				$cnt = $rs->fields[0];
				$rs->close();
			}
			return (int)$cnt;
		}

		// Unable to get count, get record count directly
		if ($rs = $conn->execute($sql)) {
			$cnt = $rs->RecordCount();
			$rs->close();
			return (int)$cnt;
		}
		return $cnt;
	}

	// Get record count based on filter (for detail record count in master table pages)
	public function loadRecordCount($filter)
	{
		$origFilter = $this->CurrentFilter;
		$this->CurrentFilter = $filter;
		$this->Recordset_Selecting($this->CurrentFilter);
		$select = $this->TableType == 'CUSTOMVIEW' ? $this->getSqlSelect() : "SELECT * FROM " . $this->getSqlFrom();
		$groupBy = $this->TableType == 'CUSTOMVIEW' ? $this->getSqlGroupBy() : "";
		$having = $this->TableType == 'CUSTOMVIEW' ? $this->getSqlHaving() : "";
		$sql = BuildSelectSql($select, $this->getSqlWhere(), $groupBy, $having, "", $this->CurrentFilter, "");
		$cnt = $this->getRecordCount($sql);
		$this->CurrentFilter = $origFilter;
		return $cnt;
	}

	// Get record count (for current List page)
	public function listRecordCount()
	{
		$filter = $this->getSessionWhere();
		AddFilter($filter, $this->CurrentFilter);
		$filter = $this->applyUserIDFilters($filter);
		$this->Recordset_Selecting($filter);
		$select = $this->TableType == 'CUSTOMVIEW' ? $this->getSqlSelect() : "SELECT * FROM " . $this->getSqlFrom();
		$groupBy = $this->TableType == 'CUSTOMVIEW' ? $this->getSqlGroupBy() : "";
		$having = $this->TableType == 'CUSTOMVIEW' ? $this->getSqlHaving() : "";
		$sql = BuildSelectSql($select, $this->getSqlWhere(), $groupBy, $having, "", $filter, "");
		$cnt = $this->getRecordCount($sql);
		return $cnt;
	}

	// INSERT statement
	protected function insertSql(&$rs)
	{
		$names = "";
		$values = "";
		foreach ($rs as $name => $value) {
			if (!isset($this->fields[$name]) || $this->fields[$name]->IsCustom)
				continue;
			$names .= $this->fields[$name]->Expression . ",";
			$values .= QuotedValue($value, $this->fields[$name]->DataType, $this->Dbid) . ",";
		}
		$names = preg_replace('/,+$/', "", $names);
		$values = preg_replace('/,+$/', "", $values);
		return "INSERT INTO " . $this->UpdateTable . " ($names) VALUES ($values)";
	}

	// Insert
	public function insert(&$rs)
	{
		$conn = &$this->getConnection();
		$success = $conn->execute($this->insertSql($rs));
		if ($success) {

			// Get insert id if necessary
			$this->FileID->setDbValue($conn->insert_ID());
			$rs['FileID'] = $this->FileID->DbValue;
			if ($this->AuditTrailOnAdd)
				$this->writeAuditTrailOnAdd($rs);
		}
		return $success;
	}

	// UPDATE statement
	protected function updateSql(&$rs, $where = "", $curfilter = TRUE)
	{
		$sql = "UPDATE " . $this->UpdateTable . " SET ";
		foreach ($rs as $name => $value) {
			if (!isset($this->fields[$name]) || $this->fields[$name]->IsCustom || $this->fields[$name]->IsPrimaryKey)
				continue;
			$sql .= $this->fields[$name]->Expression . "=";
			$sql .= QuotedValue($value, $this->fields[$name]->DataType, $this->Dbid) . ",";
		}
		$sql = preg_replace('/,+$/', "", $sql);
		$filter = ($curfilter) ? $this->CurrentFilter : "";
		if (is_array($where))
			$where = $this->arrayToFilter($where);
		AddFilter($filter, $where);
		if ($filter <> "")
			$sql .= " WHERE " . $filter;
		return $sql;
	}

	// Update
	public function update(&$rs, $where = "", $rsold = NULL, $curfilter = TRUE)
	{
		$conn = &$this->getConnection();
		$success = $conn->execute($this->updateSql($rs, $where, $curfilter));
		if ($success && $this->AuditTrailOnEdit && $rsold) {
			$rsaudit = $rs;
			$fldname = 'FileID';
			if (!array_key_exists($fldname, $rsaudit))
				$rsaudit[$fldname] = $rsold[$fldname];
			$this->writeAuditTrailOnEdit($rsold, $rsaudit);
		}
		return $success;
	}

	// DELETE statement
	protected function deleteSql(&$rs, $where = "", $curfilter = TRUE)
	{
		$sql = "DELETE FROM " . $this->UpdateTable . " WHERE ";
		if (is_array($where))
			$where = $this->arrayToFilter($where);
		if ($rs) {
			if (array_key_exists('FileID', $rs))
				AddFilter($where, QuotedName('FileID', $this->Dbid) . '=' . QuotedValue($rs['FileID'], $this->FileID->DataType, $this->Dbid));
		}
		$filter = ($curfilter) ? $this->CurrentFilter : "";
		AddFilter($filter, $where);
		if ($filter <> "")
			$sql .= $filter;
		else
			$sql .= "0=1"; // Avoid delete
		return $sql;
	}

	// Delete
	public function delete(&$rs, $where = "", $curfilter = FALSE)
	{
		$success = TRUE;
		$conn = &$this->getConnection();
		if ($success)
			$success = $conn->execute($this->deleteSql($rs, $where, $curfilter));
		if ($success && $this->AuditTrailOnDelete)
			$this->writeAuditTrailOnDelete($rs);
		return $success;
	}

	// Load DbValue from recordset or array
	protected function loadDbValues(&$rs)
	{
		if (!$rs || !is_array($rs) && $rs->EOF)
			return;
		$row = is_array($rs) ? $rs : $rs->fields;
		$this->FileID->DbValue = $row['FileID'];
		$this->CaseNumber->DbValue = $row['CaseNumber'];
		$this->FileNumber->DbValue = $row['FileNumber'];
		$this->EnvelopeNumber->DbValue = $row['EnvelopeNumber'];
		$this->FileLocation->DbValue = $row['FileLocation'];
		$this->_Case->DbValue = $row['Case'];
		$this->CaseEn->DbValue = $row['CaseEn'];
		$this->CaseType->DbValue = $row['CaseType'];
		$this->ClientName->DbValue = $row['ClientName'];
		$this->LitigantName->DbValue = $row['LitigantName'];
		$this->CourtName->DbValue = $row['CourtName'];
		$this->CourtTypeName->DbValue = $row['CourtTypeName'];
		$this->CourtGenderName->DbValue = $row['CourtGenderName'];
		$this->JudgeName->DbValue = $row['JudgeName'];
		$this->Notes->DbValue = $row['Notes'];
		$this->CreatedBy->DbValue = $row['CreatedBy'];
		$this->CreatedDate->DbValue = $row['CreatedDate'];
		$this->UpdatedBy->DbValue = $row['UpdatedBy'];
		$this->UpdatedDate->DbValue = $row['UpdatedDate'];
		$this->CourtID->DbValue = $row['CourtID'];
		$this->ClientID->DbValue = $row['ClientID'];
		$this->LitigantID->DbValue = $row['LitigantID'];
	}

	// Delete uploaded files
	public function deleteUploadedFiles($row)
	{
		$this->loadDbValues($row);
	}

	// Record filter WHERE clause
	protected function sqlKeyFilter()
	{
		return "`FileID` = @FileID@";
	}

	// Get record filter
	public function getRecordFilter($row = NULL)
	{
		$keyFilter = $this->sqlKeyFilter();
		$val = is_array($row) ? (array_key_exists('FileID', $row) ? $row['FileID'] : NULL) : $this->FileID->CurrentValue;
		if (!is_numeric($val))
			return "0=1"; // Invalid key
		if ($val == NULL)
			return "0=1"; // Invalid key
		else
			$keyFilter = str_replace("@FileID@", AdjustSql($val, $this->Dbid), $keyFilter); // Replace key value
		return $keyFilter;
	}

	// Return page URL
	public function getReturnUrl()
	{
		$name = PROJECT_NAME . "_" . $this->TableVar . "_" . TABLE_RETURN_URL;

		// Get referer URL automatically
		if (ServerVar("HTTP_REFERER") <> "" && ReferPageName() <> CurrentPageName() && ReferPageName() <> "login.php") // Referer not same page or login page
			$_SESSION[$name] = ServerVar("HTTP_REFERER"); // Save to Session
		if (@$_SESSION[$name] <> "") {
			return $_SESSION[$name];
		} else {
			return "fileslist.php";
		}
	}
	public function setReturnUrl($v)
	{
		$_SESSION[PROJECT_NAME . "_" . $this->TableVar . "_" . TABLE_RETURN_URL] = $v;
	}

	// Get modal caption
	public function getModalCaption($pageName)
	{
		global $Language;
		if ($pageName == "filesview.php")
			return $Language->phrase("View");
		elseif ($pageName == "filesedit.php")
			return $Language->phrase("Edit");
		elseif ($pageName == "filesadd.php")
			return $Language->phrase("Add");
		else
			return "";
	}

	// List URL
	public function getListUrl()
	{
		return "fileslist.php";
	}

	// View URL
	public function getViewUrl($parm = "")
	{
		if ($parm <> "")
			$url = $this->keyUrl("filesview.php", $this->getUrlParm($parm));
		else
			$url = $this->keyUrl("filesview.php", $this->getUrlParm(TABLE_SHOW_DETAIL . "="));
		return $this->addMasterUrl($url);
	}

	// Add URL
	public function getAddUrl($parm = "")
	{
		if ($parm <> "")
			$url = "filesadd.php?" . $this->getUrlParm($parm);
		else
			$url = "filesadd.php";
		return $this->addMasterUrl($url);
	}

	// Edit URL
	public function getEditUrl($parm = "")
	{
		$url = $this->keyUrl("filesedit.php", $this->getUrlParm($parm));
		return $this->addMasterUrl($url);
	}

	// Inline edit URL
	public function getInlineEditUrl()
	{
		$url = $this->keyUrl(CurrentPageName(), $this->getUrlParm("action=edit"));
		return $this->addMasterUrl($url);
	}

	// Copy URL
	public function getCopyUrl($parm = "")
	{
		$url = $this->keyUrl("filesadd.php", $this->getUrlParm($parm));
		return $this->addMasterUrl($url);
	}

	// Inline copy URL
	public function getInlineCopyUrl()
	{
		$url = $this->keyUrl(CurrentPageName(), $this->getUrlParm("action=copy"));
		return $this->addMasterUrl($url);
	}

	// Delete URL
	public function getDeleteUrl()
	{
		return $this->keyUrl("filesdelete.php", $this->getUrlParm());
	}

	// Add master url
	public function addMasterUrl($url)
	{
		return $url;
	}
	public function keyToJson($htmlEncode = FALSE)
	{
		$json = "";
		$json .= "FileID:" . JsonEncode($this->FileID->CurrentValue, "number");
		$json = "{" . $json . "}";
		if ($htmlEncode)
			$json = HtmlEncode($json);
		return $json;
	}

	// Add key value to URL
	public function keyUrl($url, $parm = "")
	{
		$url = $url . "?";
		if ($parm <> "")
			$url .= $parm . "&";
		if ($this->FileID->CurrentValue != NULL) {
			$url .= "FileID=" . urlencode($this->FileID->CurrentValue);
		} else {
			return "javascript:ew.alert(ew.language.phrase('InvalidRecord'));";
		}
		return $url;
	}

	// Sort URL
	public function sortUrl(&$fld)
	{
		if ($this->CurrentAction || $this->isExport() ||
			in_array($fld->Type, array(128, 204, 205))) { // Unsortable data type
				return "";
		} elseif ($fld->Sortable) {
			$urlParm = $this->getUrlParm("order=" . urlencode($fld->Name) . "&amp;ordertype=" . $fld->reverseSort());
			return $this->addMasterUrl(CurrentPageName() . "?" . $urlParm);
		} else {
			return "";
		}
	}

	// Get record keys from Post/Get/Session
	public function getRecordKeys()
	{
		global $COMPOSITE_KEY_SEPARATOR;
		$arKeys = array();
		$arKey = array();
		if (Param("key_m") !== NULL) {
			$arKeys = Param("key_m");
			$cnt = count($arKeys);
		} else {
			if (Param("FileID") !== NULL)
				$arKeys[] = Param("FileID");
			elseif (IsApi() && Key(0) !== NULL)
				$arKeys[] = Key(0);
			elseif (IsApi() && Route(2) !== NULL)
				$arKeys[] = Route(2);
			else
				$arKeys = NULL; // Do not setup

			//return $arKeys; // Do not return yet, so the values will also be checked by the following code
		}

		// Check keys
		$ar = array();
		if (is_array($arKeys)) {
			foreach ($arKeys as $key) {
				if (!is_numeric($key))
					continue;
				$ar[] = $key;
			}
		}
		return $ar;
	}

	// Get filter from record keys
	public function getFilterFromRecordKeys()
	{
		$arKeys = $this->getRecordKeys();
		$keyFilter = "";
		foreach ($arKeys as $key) {
			if ($keyFilter <> "") $keyFilter .= " OR ";
			$this->FileID->CurrentValue = $key;
			$keyFilter .= "(" . $this->getRecordFilter() . ")";
		}
		return $keyFilter;
	}

	// Load rows based on filter
	public function &loadRs($filter)
	{

		// Set up filter (WHERE Clause)
		$sql = $this->getSql($filter);
		$conn = &$this->getConnection();
		$rs = $conn->execute($sql);
		return $rs;
	}

	// Load row values from recordset
	public function loadListRowValues(&$rs)
	{
		$this->FileID->setDbValue($rs->fields('FileID'));
		$this->CaseNumber->setDbValue($rs->fields('CaseNumber'));
		$this->FileNumber->setDbValue($rs->fields('FileNumber'));
		$this->EnvelopeNumber->setDbValue($rs->fields('EnvelopeNumber'));
		$this->FileLocation->setDbValue($rs->fields('FileLocation'));
		$this->_Case->setDbValue($rs->fields('Case'));
		$this->CaseEn->setDbValue($rs->fields('CaseEn'));
		$this->CaseType->setDbValue($rs->fields('CaseType'));
		$this->ClientName->setDbValue($rs->fields('ClientName'));
		$this->LitigantName->setDbValue($rs->fields('LitigantName'));
		$this->CourtName->setDbValue($rs->fields('CourtName'));
		$this->CourtTypeName->setDbValue($rs->fields('CourtTypeName'));
		$this->CourtGenderName->setDbValue($rs->fields('CourtGenderName'));
		$this->JudgeName->setDbValue($rs->fields('JudgeName'));
		$this->Notes->setDbValue($rs->fields('Notes'));
		$this->CreatedBy->setDbValue($rs->fields('CreatedBy'));
		$this->CreatedDate->setDbValue($rs->fields('CreatedDate'));
		$this->UpdatedBy->setDbValue($rs->fields('UpdatedBy'));
		$this->UpdatedDate->setDbValue($rs->fields('UpdatedDate'));
		$this->CourtID->setDbValue($rs->fields('CourtID'));
		$this->ClientID->setDbValue($rs->fields('ClientID'));
		$this->LitigantID->setDbValue($rs->fields('LitigantID'));
	}

	// Render list row values
	public function renderListRow()
	{
		global $Security, $CurrentLanguage, $Language;

		// Call Row Rendering event
		$this->Row_Rendering();

		// Common render codes
		// FileID
		// CaseNumber
		// FileNumber
		// EnvelopeNumber
		// FileLocation
		// Case
		// CaseEn

		$this->CaseEn->CellCssStyle = "white-space: nowrap;";

		// CaseType
		$this->CaseType->CellCssStyle = "min-width: 150px;";

		// ClientName
		$this->ClientName->CellCssStyle = "min-width: 150px;";

		// LitigantName
		$this->LitigantName->CellCssStyle = "min-width: 300px;";

		// CourtName
		$this->CourtName->CellCssStyle = "min-width: 150px;";

		// CourtTypeName
		$this->CourtTypeName->CellCssStyle = "white-space: nowrap;";

		// CourtGenderName
		$this->CourtGenderName->CellCssStyle = "white-space: nowrap;";

		// JudgeName
		$this->JudgeName->CellCssStyle = "min-width: 150px;";

		// Notes
		$this->Notes->CellCssStyle = "min-width: 150px;";

		// CreatedBy
		$this->CreatedBy->CellCssStyle = "white-space: nowrap;";

		// CreatedDate
		$this->CreatedDate->CellCssStyle = "white-space: nowrap;";

		// UpdatedBy
		$this->UpdatedBy->CellCssStyle = "white-space: nowrap;";

		// UpdatedDate
		$this->UpdatedDate->CellCssStyle = "white-space: nowrap;";

		// CourtID
		$this->CourtID->CellCssStyle = "white-space: nowrap;";

		// ClientID
		$this->ClientID->CellCssStyle = "white-space: nowrap;";

		// LitigantID
		$this->LitigantID->CellCssStyle = "white-space: nowrap;";

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		// Call Row Rendered event
		$this->Row_Rendered();

		// Save data for Custom Template
		$this->Rows[] = $this->customTemplateFieldValues();
	}

	// Render edit row values
	public function renderEditRow()
	{
		global $Security, $CurrentLanguage, $Language;

		// Call Row Rendering event
		$this->Row_Rendering();

		// FileID
		$this->FileID->EditAttrs["class"] = "form-control";
		$this->FileID->EditCustomAttributes = "";
		$this->FileID->EditValue = $this->FileID->CurrentValue;
		$this->FileID->ViewCustomAttributes = "";

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		// Call Row Rendered event
		$this->Row_Rendered();
	}

	// Aggregate list row values
	public function aggregateListRowValues()
	{
	}

	// Aggregate list row (for rendering)
	public function aggregateListRow()
	{

		// Call Row Rendered event
		$this->Row_Rendered();
	}

	// Export data in HTML/CSV/Word/Excel/Email/PDF format
	public function exportDocument($doc, $recordset, $startRec = 1, $stopRec = 1, $exportPageType = "")
	{
		if (!$recordset || !$doc)
			return;
		if (!$doc->ExportCustom) {

			// Write header
			$doc->exportTableHeader();
			if ($doc->Horizontal) { // Horizontal format, write header
				$doc->beginExportRow();
				if ($exportPageType == "view") {
					$doc->exportCaption($this->FileID);
					$doc->exportCaption($this->CaseNumber);
					$doc->exportCaption($this->FileNumber);
					$doc->exportCaption($this->EnvelopeNumber);
					$doc->exportCaption($this->FileLocation);
					$doc->exportCaption($this->_Case);
					$doc->exportCaption($this->CaseType);
					$doc->exportCaption($this->ClientName);
					$doc->exportCaption($this->LitigantName);
					$doc->exportCaption($this->CourtName);
					$doc->exportCaption($this->JudgeName);
					$doc->exportCaption($this->Notes);
				} else {
					$doc->exportCaption($this->FileID);
					$doc->exportCaption($this->CaseNumber);
					$doc->exportCaption($this->FileNumber);
					$doc->exportCaption($this->EnvelopeNumber);
					$doc->exportCaption($this->FileLocation);
					$doc->exportCaption($this->_Case);
					$doc->exportCaption($this->CaseType);
					$doc->exportCaption($this->ClientName);
					$doc->exportCaption($this->LitigantName);
					$doc->exportCaption($this->CourtName);
					$doc->exportCaption($this->JudgeName);
				}
				$doc->endExportRow();
			}
		}

		// Move to first record
		$recCnt = $startRec - 1;
		if (!$recordset->EOF) {
			$recordset->moveFirst();
			if ($startRec > 1)
				$recordset->move($startRec - 1);
		}
		while (!$recordset->EOF && $recCnt < $stopRec) {
			$recCnt++;
			if ($recCnt >= $startRec) {
				$rowCnt = $recCnt - $startRec + 1;

				// Page break
				if ($this->ExportPageBreakCount > 0) {
					if ($rowCnt > 1 && ($rowCnt - 1) % $this->ExportPageBreakCount == 0)
						$doc->exportPageBreak();
				}
				$this->loadListRowValues($recordset);

				// Render row
				$this->RowType = ROWTYPE_VIEW; // Render view
				$this->resetAttributes();
				$this->renderListRow();
				if (!$doc->ExportCustom) {
					$doc->beginExportRow($rowCnt); // Allow CSS styles if enabled
					if ($exportPageType == "view") {
						$doc->exportField($this->FileID);
						$doc->exportField($this->CaseNumber);
						$doc->exportField($this->FileNumber);
						$doc->exportField($this->EnvelopeNumber);
						$doc->exportField($this->FileLocation);
						$doc->exportField($this->_Case);
						$doc->exportField($this->CaseType);
						$doc->exportField($this->ClientName);
						$doc->exportField($this->LitigantName);
						$doc->exportField($this->CourtName);
						$doc->exportField($this->JudgeName);
						$doc->exportField($this->Notes);
					} else {
						$doc->exportField($this->FileID);
						$doc->exportField($this->CaseNumber);
						$doc->exportField($this->FileNumber);
						$doc->exportField($this->EnvelopeNumber);
						$doc->exportField($this->FileLocation);
						$doc->exportField($this->_Case);
						$doc->exportField($this->CaseType);
						$doc->exportField($this->ClientName);
						$doc->exportField($this->LitigantName);
						$doc->exportField($this->CourtName);
						$doc->exportField($this->JudgeName);
					}
					$doc->endExportRow($rowCnt);
				}
			}

			// Call Row Export server event
			if ($doc->ExportCustom)
				$this->Row_Export($recordset->fields);
			$recordset->moveNext();
		}
		if (!$doc->ExportCustom) {
			$doc->exportTableFooter();
		}
	}

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

		// Check token first
		$func = PROJECT_NAMESPACE . "CheckToken";
		$validRequest = FALSE;
		if (is_callable($func) && Post(TOKEN_NAME) !== NULL) {
			$validRequest = $func(Post(TOKEN_NAME), SessionTimeoutTime());
			if ($validRequest) {
				if (!isset($Security)) {
					if (session_status() !== PHP_SESSION_ACTIVE)
						session_start(); // Init session data
					$Security = new AdvancedSecurity();
					if ($Security->isLoggedIn()) $Security->TablePermission_Loading();
					$Security->loadCurrentUserLevel($PROJECT_ID . $this->TableName);
					if ($Security->isLoggedIn()) $Security->TablePermission_Loaded();
					$validRequest = $Security->canList(); // List permission
					if ($validRequest) {
						$Security->UserID_Loading();
						$Security->loadUserID();
						$Security->UserID_Loaded();
					}
				}
			}
		} else {

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

			// Security
			$Security = new AdvancedSecurity();
			if (is_array($RequestSecurity)) // Login user for API request
				$Security->loginUser(@$RequestSecurity["username"], @$RequestSecurity["userid"], @$RequestSecurity["parentuserid"], @$RequestSecurity["userlevelid"]);
			$Security->TablePermission_Loading();
			$Security->loadCurrentUserLevel(CurrentProjectID() . $this->TableName);
			$Security->TablePermission_Loaded();
			$validRequest = $Security->canList(); // List permission
		}

		// Reject invalid request
		if (!$validRequest)
			return FALSE;

		// Load lookup parameters
		$distinct = ConvertToBool(Post("distinct"));
		$linkField = Post("linkField");
		$displayFields = Post("displayFields");
		$parentFields = Post("parentFields");
		if (!is_array($parentFields))
			$parentFields = [];
		$childFields = Post("childFields");
		if (!is_array($childFields))
			$childFields = [];
		$filterFields = Post("filterFields");
		if (!is_array($filterFields))
			$filterFields = [];
		$filterFieldVars = Post("filterFieldVars");
		if (!is_array($filterFieldVars))
			$filterFieldVars = [];
		$filterOperators = Post("filterOperators");
		if (!is_array($filterOperators))
			$filterOperators = [];
		$autoFillSourceFields = Post("autoFillSourceFields");
		if (!is_array($autoFillSourceFields))
			$autoFillSourceFields = [];
		$formatAutoFill = FALSE;
		$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 = Get("q", "");
			$pageSize = Param("n", -1);
			$pageSize = is_numeric($pageSize) ? (int)$pageSize : -1;
			if ($pageSize <= 0)
				$pageSize = 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");

		// Selected records from modal, skip parent/filter fields and show all records
		if ($keys !== NULL) {
			$parentFields = [];
			$filterFields = [];
			$filterFieldVars = [];
			$offset = 0;
			$pageSize = 0;
		}

		// Create lookup object and output JSON
		$lookup = new Lookup($linkField, $this->TableVar, $distinct, $linkField, $displayFields, $parentFields, $childFields, $filterFields, $filterFieldVars, $autoFillSourceFields);
		foreach ($filterFields as $i => $filterField) { // Set up filter operators
			if (@$filterOperators[$i] <> "")
				$lookup->setFilterOperator($filterField, $filterOperators[$i]);
		}
		$lookup->LookupType = $lookupType; // Lookup type
		if ($keys !== NULL) { // Selected records from modal
			if (is_array($keys))
				$keys = implode(LOOKUP_FILTER_VALUE_SEPARATOR, $keys);
			$lookup->FilterValues[] = $keys; // Lookup values
		} else { // Lookup values
			$lookup->FilterValues[] = Post("v0", Post("lookupValue", ""));
		}
		$cnt = is_array($filterFields) ? count($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();
	}

	// Get file data
	public function getFileData($fldparm, $key, $resize, $width = THUMBNAIL_DEFAULT_WIDTH, $height = THUMBNAIL_DEFAULT_HEIGHT)
	{

		// No binary fields
		return FALSE;
	}

	// Write Audit Trail start/end for grid update
	public function writeAuditTrailDummy($typ)
	{
		$table = 'files';
		$usr = CurrentUserID();
		WriteAuditTrail("log", DbCurrentDateTime(), ScriptName(), $usr, $typ, $table, "", "", "", "");
	}

	// Write Audit Trail (add page)
	public function writeAuditTrailOnAdd(&$rs)
	{
		global $Language;
		if (!$this->AuditTrailOnAdd)
			return;
		$table = 'files';

		// Get key value
		$key = "";
		if ($key <> "")
			$key .= $GLOBALS["COMPOSITE_KEY_SEPARATOR"];
		$key .= $rs['FileID'];

		// Write Audit Trail
		$dt = DbCurrentDateTime();
		$id = ScriptName();
		$usr = CurrentUserID();
		foreach (array_keys($rs) as $fldname) {
			if (array_key_exists($fldname, $this->fields) && $this->fields[$fldname]->DataType <> DATATYPE_BLOB) { // Ignore BLOB fields
				if ($this->fields[$fldname]->HtmlTag == "PASSWORD") {
					$newvalue = $Language->phrase("PasswordMask"); // Password Field
				} elseif ($this->fields[$fldname]->DataType == DATATYPE_MEMO) {
					if (AUDIT_TRAIL_TO_DATABASE)
						$newvalue = $rs[$fldname];
					else
						$newvalue = "[MEMO]"; // Memo Field
				} elseif ($this->fields[$fldname]->DataType == DATATYPE_XML) {
					$newvalue = "[XML]"; // XML Field
				} else {
					$newvalue = $rs[$fldname];
				}
				WriteAuditTrail("log", $dt, $id, $usr, "A", $table, $fldname, $key, "", $newvalue);
			}
		}
	}

	// Write Audit Trail (edit page)
	public function writeAuditTrailOnEdit(&$rsold, &$rsnew)
	{
		global $Language;
		if (!$this->AuditTrailOnEdit)
			return;
		$table = 'files';

		// Get key value
		$key = "";
		if ($key <> "")
			$key .= $GLOBALS["COMPOSITE_KEY_SEPARATOR"];
		$key .= $rsold['FileID'];

		// Write Audit Trail
		$dt = DbCurrentDateTime();
		$id = ScriptName();
		$usr = CurrentUserID();
		foreach (array_keys($rsnew) as $fldname) {
			if (array_key_exists($fldname, $this->fields) && array_key_exists($fldname, $rsold) && $this->fields[$fldname]->DataType <> DATATYPE_BLOB) { // Ignore BLOB fields
				if ($this->fields[$fldname]->DataType == DATATYPE_DATE) { // DateTime field
					$modified = (FormatDateTime($rsold[$fldname], 0) <> FormatDateTime($rsnew[$fldname], 0));
				} else {
					$modified = !CompareValue($rsold[$fldname], $rsnew[$fldname]);
				}
				if ($modified) {
					if ($this->fields[$fldname]->HtmlTag == "PASSWORD") { // Password Field
						$oldvalue = $Language->phrase("PasswordMask");
						$newvalue = $Language->phrase("PasswordMask");
					} elseif ($this->fields[$fldname]->DataType == DATATYPE_MEMO) { // Memo field
						if (AUDIT_TRAIL_TO_DATABASE) {
							$oldvalue = $rsold[$fldname];
							$newvalue = $rsnew[$fldname];
						} else {
							$oldvalue = "[MEMO]";
							$newvalue = "[MEMO]";
						}
					} elseif ($this->fields[$fldname]->DataType == DATATYPE_XML) { // XML field
						$oldvalue = "[XML]";
						$newvalue = "[XML]";
					} else {
						$oldvalue = $rsold[$fldname];
						$newvalue = $rsnew[$fldname];
					}
					WriteAuditTrail("log", $dt, $id, $usr, "U", $table, $fldname, $key, $oldvalue, $newvalue);
				}
			}
		}
	}

	// Write Audit Trail (delete page)
	public function writeAuditTrailOnDelete(&$rs)
	{
		global $Language;
		if (!$this->AuditTrailOnDelete)
			return;
		$table = 'files';

		// Get key value
		$key = "";
		if ($key <> "")
			$key .= $GLOBALS["COMPOSITE_KEY_SEPARATOR"];
		$key .= $rs['FileID'];

		// Write Audit Trail
		$dt = DbCurrentDateTime();
		$id = ScriptName();
		$curUser = CurrentUserID();
		foreach (array_keys($rs) as $fldname) {
			if (array_key_exists($fldname, $this->fields) && $this->fields[$fldname]->DataType <> DATATYPE_BLOB) { // Ignore BLOB fields
				if ($this->fields[$fldname]->HtmlTag == "PASSWORD") {
					$oldvalue = $Language->phrase("PasswordMask"); // Password Field
				} elseif ($this->fields[$fldname]->DataType == DATATYPE_MEMO) {
					if (AUDIT_TRAIL_TO_DATABASE)
						$oldvalue = $rs[$fldname];
					else
						$oldvalue = "[MEMO]"; // Memo field
				} elseif ($this->fields[$fldname]->DataType == DATATYPE_XML) {
					$oldvalue = "[XML]"; // XML field
				} else {
					$oldvalue = $rs[$fldname];
				}
				WriteAuditTrail("log", $dt, $id, $curUser, "D", $table, $fldname, $key, $oldvalue, "");
			}
		}
	}

	// Write Audit Trail (view page)
	public function writeAuditTrailOnView(&$rs)
	{
		global $Language;
		if (!$this->AuditTrailOnView)
			return;
		$table = 'files';

		// Get key value
		$key = "";
		if ($key <> "")
			$key .= $GLOBALS["COMPOSITE_KEY_SEPARATOR"];
		$key .= $rs['FileID'];

		// Write Audit Trail
		$dt = DbCurrentDateTime();
		$id = ScriptName();
		$usr = CurrentUserID();
		if ($this->AuditTrailOnViewData) { // Write all data
			foreach (array_keys($rs) as $fldname) {
				if (array_key_exists($fldname, $this->fields) && $this->fields[$fldname]->DataType <> DATATYPE_BLOB) { // Ignore BLOB fields
					if ($this->fields[$fldname]->HtmlTag == "PASSWORD") {
						$oldvalue = $Language->phrase("PasswordMask"); // Password Field
					} elseif ($this->fields[$fldname]->DataType == DATATYPE_MEMO) {
						if (AUDIT_TRAIL_TO_DATABASE)
							$oldvalue = $rs[$fldname];
						else
							$oldvalue = "[MEMO]"; // Memo Field
					} elseif ($this->fields[$fldname]->DataType == DATATYPE_XML) {
						$oldvalue = "[XML]"; // XML Field
					} else {
						$oldvalue = $rs[$fldname];
					}
					WriteAuditTrail("log", $dt, $id, $usr, "V", $table, $fldname, $key, $oldvalue, "");
				}
			}
		} else { // Write record id only
			WriteAuditTrail("log", $dt, $id, $usr, "V", $table, "", $key, "", "");
		}
	}

	// Table level events
	// Recordset Selecting event
	function Recordset_Selecting(&$filter) {

		// Enter your code here
	}

	// Recordset Selected event
	function Recordset_Selected(&$rs) {

		//echo "Recordset Selected";
	}

	// Recordset Search Validated event
	function Recordset_SearchValidated() {

		// Example:
		//$this->MyField1->AdvancedSearch->SearchValue = "your search criteria"; // Search value

	}

	// Recordset Searching event
	function Recordset_Searching(&$filter) {

		// Enter your code here
	}

	// Row_Selecting event
	function Row_Selecting(&$filter) {

		// Enter your code here
	}

	// Row Selected event
	function Row_Selected(&$rs) {

		//echo "Row Selected";
	}

	// Row Inserting event
	function Row_Inserting($rsold, &$rsnew) {

		// Enter your code here
		// To cancel, set return value to FALSE

		return TRUE;
	}

	// Row Inserted event
	function Row_Inserted($rsold, &$rsnew) {

		//echo "Row Inserted"
	}

	// Row Updating event
	function Row_Updating($rsold, &$rsnew) {

		// Enter your code here
		// To cancel, set return value to FALSE

		return TRUE;
	}

	// Row Updated event
	function Row_Updated($rsold, &$rsnew) {

		//echo "Row Updated";
	}

	// Row Update Conflict event
	function Row_UpdateConflict($rsold, &$rsnew) {

		// Enter your code here
		// To ignore conflict, set return value to FALSE

		return TRUE;
	}

	// Grid Inserting event
	function Grid_Inserting() {

		// Enter your code here
		// To reject grid insert, set return value to FALSE

		return TRUE;
	}

	// Grid Inserted event
	function Grid_Inserted($rsnew) {

		//echo "Grid Inserted";
	}

	// Grid Updating event
	function Grid_Updating($rsold) {

		// Enter your code here
		// To reject grid update, set return value to FALSE

		return TRUE;
	}

	// Grid Updated event
	function Grid_Updated($rsold, $rsnew) {

		//echo "Grid Updated";
	}

	// Row Deleting event
	function Row_Deleting(&$rs) {

		// Enter your code here
		// To cancel, set return value to False

		return TRUE;
	}

	// Row Deleted event
	function Row_Deleted(&$rs) {

		//echo "Row Deleted";
	}

	// Email Sending event
	function Email_Sending($email, &$args) {

		//var_dump($email); var_dump($args); exit();
		return TRUE;
	}

	// Lookup Selecting event
	function Lookup_Selecting($fld, &$filter) {

		//var_dump($fld->Name, $fld->Lookup, $filter); // Uncomment to view the filter
		// Enter your code here

	}

	// Row Rendering event
	function Row_Rendering() {

		// Enter your code here
	}

	// Row Rendered event
	function Row_Rendered() {

		// To view properties of field class, use:
		//var_dump($this-><FieldName>);

	}

	// User ID Filtering event
	function UserID_Filtering(&$filter) {

		// Enter your code here
	}
}
?>
