<?php
if (session_id() == "") session_start(); // Init session data
ob_start(); // Turn on output buffering
?>
<?php include_once "ewcfg14.php" ?>
<?php include_once ((EW_USE_ADODB) ? "adodb5/adodb.inc.php" : "ewmysql14.php") ?>
<?php include_once "phpfn14.php" ?>
<?php include_once "coinfo.php" ?>
<?php include_once "employeesinfo.php" ?>
<?php include_once "userfn14.php" ?>
<?php

//
// Page class
//

$co_addopt = NULL; // Initialize page object first

class cco_addopt extends cco {

	// Page ID
	var $PageID = 'addopt';

	// Project ID
	var $ProjectID = '{CC60B42B-604B-412A-B014-2315920AF6AA}';

	// Table name
	var $TableName = 'co';

	// Page object name
	var $PageObjName = 'co_addopt';

	// Page headings
	var $Heading = '';
	var $Subheading = '';

	// Page heading
	function PageHeading() {
		global $Language;
		if ($this->Heading <> "")
			return $this->Heading;
		if (method_exists($this, "TableCaption"))
			return $this->TableCaption();
		return "";
	}

	// Page subheading
	function PageSubheading() {
		global $Language;
		if ($this->Subheading <> "")
			return $this->Subheading;
		if ($this->TableName)
			return $Language->Phrase($this->PageID);
		return "";
	}

	// Page name
	function PageName() {
		return ew_CurrentPage();
	}

	// Page URL
	function PageUrl() {
		$PageUrl = ew_CurrentPage() . "?";
		if ($this->UseTokenInUrl) $PageUrl .= "t=" . $this->TableVar . "&"; // Add page token
		return $PageUrl;
	}

	// Message
	function getMessage() {
		return @$_SESSION[EW_SESSION_MESSAGE];
	}

	function setMessage($v) {
		ew_AddMessage($_SESSION[EW_SESSION_MESSAGE], $v);
	}

	function getFailureMessage() {
		return @$_SESSION[EW_SESSION_FAILURE_MESSAGE];
	}

	function setFailureMessage($v) {
		ew_AddMessage($_SESSION[EW_SESSION_FAILURE_MESSAGE], $v);
	}

	function getSuccessMessage() {
		return @$_SESSION[EW_SESSION_SUCCESS_MESSAGE];
	}

	function setSuccessMessage($v) {
		ew_AddMessage($_SESSION[EW_SESSION_SUCCESS_MESSAGE], $v);
	}

	function getWarningMessage() {
		return @$_SESSION[EW_SESSION_WARNING_MESSAGE];
	}

	function setWarningMessage($v) {
		ew_AddMessage($_SESSION[EW_SESSION_WARNING_MESSAGE], $v);
	}

	// Methods to clear message
	function ClearMessage() {
		$_SESSION[EW_SESSION_MESSAGE] = "";
	}

	function ClearFailureMessage() {
		$_SESSION[EW_SESSION_FAILURE_MESSAGE] = "";
	}

	function ClearSuccessMessage() {
		$_SESSION[EW_SESSION_SUCCESS_MESSAGE] = "";
	}

	function ClearWarningMessage() {
		$_SESSION[EW_SESSION_WARNING_MESSAGE] = "";
	}

	function ClearMessages() {
		$_SESSION[EW_SESSION_MESSAGE] = "";
		$_SESSION[EW_SESSION_FAILURE_MESSAGE] = "";
		$_SESSION[EW_SESSION_SUCCESS_MESSAGE] = "";
		$_SESSION[EW_SESSION_WARNING_MESSAGE] = "";
	}

	// Show message
	function ShowMessage() {
		$hidden = FALSE;
		$html = "";

		// Message
		$sMessage = $this->getMessage();
		if (method_exists($this, "Message_Showing"))
			$this->Message_Showing($sMessage, "");
		if ($sMessage <> "") { // Message in Session, display
			if (!$hidden)
				$sMessage = "<button type=\"button\" class=\"close\" data-dismiss=\"alert\">&times;</button>" . $sMessage;
			$html .= "<div class=\"alert alert-info ewInfo\">" . $sMessage . "</div>";
			$_SESSION[EW_SESSION_MESSAGE] = ""; // Clear message in Session
		}

		// Warning message
		$sWarningMessage = $this->getWarningMessage();
		if (method_exists($this, "Message_Showing"))
			$this->Message_Showing($sWarningMessage, "warning");
		if ($sWarningMessage <> "") { // Message in Session, display
			if (!$hidden)
				$sWarningMessage = "<button type=\"button\" class=\"close\" data-dismiss=\"alert\">&times;</button>" . $sWarningMessage;
			$html .= "<div class=\"alert alert-warning ewWarning\">" . $sWarningMessage . "</div>";
			$_SESSION[EW_SESSION_WARNING_MESSAGE] = ""; // Clear message in Session
		}

		// Success message
		$sSuccessMessage = $this->getSuccessMessage();
		if (method_exists($this, "Message_Showing"))
			$this->Message_Showing($sSuccessMessage, "success");
		if ($sSuccessMessage <> "") { // Message in Session, display
			if (!$hidden)
				$sSuccessMessage = "<button type=\"button\" class=\"close\" data-dismiss=\"alert\">&times;</button>" . $sSuccessMessage;
			$html .= "<div class=\"alert alert-success ewSuccess\">" . $sSuccessMessage . "</div>";
			$_SESSION[EW_SESSION_SUCCESS_MESSAGE] = ""; // Clear message in Session
		}

		// Failure message
		$sErrorMessage = $this->getFailureMessage();
		if (method_exists($this, "Message_Showing"))
			$this->Message_Showing($sErrorMessage, "failure");
		if ($sErrorMessage <> "") { // Message in Session, display
			if (!$hidden)
				$sErrorMessage = "<button type=\"button\" class=\"close\" data-dismiss=\"alert\">&times;</button>" . $sErrorMessage;
			$html .= "<div class=\"alert alert-danger ewError\">" . $sErrorMessage . "</div>";
			$_SESSION[EW_SESSION_FAILURE_MESSAGE] = ""; // Clear message in Session
		}
		echo "<div class=\"ewMessageDialog\"" . (($hidden) ? " style=\"display: none;\"" : "") . ">" . $html . "</div>";
	}
	var $PageHeader;
	var $PageFooter;

	// Show Page Header
	function ShowPageHeader() {
		$sHeader = $this->PageHeader;
		$this->Page_DataRendering($sHeader);
		if ($sHeader <> "") { // Header exists, display
			echo "<p>" . $sHeader . "</p>";
		}
	}

	// Show Page Footer
	function ShowPageFooter() {
		$sFooter = $this->PageFooter;
		$this->Page_DataRendered($sFooter);
		if ($sFooter <> "") { // Footer exists, display
			echo "<p>" . $sFooter . "</p>";
		}
	}

	// Validate page request
	function IsPageRequest() {
		global $objForm;
		if ($this->UseTokenInUrl) {
			if ($objForm)
				return ($this->TableVar == $objForm->GetValue("t"));
			if (@$_GET["t"] <> "")
				return ($this->TableVar == $_GET["t"]);
		} else {
			return TRUE;
		}
	}
	var $Token = "";
	var $TokenTimeout = 0;
	var $CheckToken = EW_CHECK_TOKEN;
	var $CheckTokenFn = "ew_CheckToken";
	var $CreateTokenFn = "ew_CreateToken";

	// Valid Post
	function ValidPost() {
		if (!$this->CheckToken || !ew_IsPost())
			return TRUE;
		if (!isset($_POST[EW_TOKEN_NAME]))
			return FALSE;
		$fn = $this->CheckTokenFn;
		if (is_callable($fn))
			return $fn($_POST[EW_TOKEN_NAME], $this->TokenTimeout);
		return FALSE;
	}

	// Create Token
	function CreateToken() {
		global $gsToken;
		if ($this->CheckToken) {
			$fn = $this->CreateTokenFn;
			if ($this->Token == "" && is_callable($fn)) // Create token
				$this->Token = $fn();
			$gsToken = $this->Token; // Save to global variable
		}
	}

	//
	// Page class constructor
	//
	function __construct() {
		global $conn, $Language;
		global $UserTable, $UserTableConn;
		$GLOBALS["Page"] = &$this;
		$this->TokenTimeout = ew_SessionTimeoutTime();

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

		// Parent constuctor
		parent::__construct();

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

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

		// Page ID
		if (!defined("EW_PAGE_ID"))
			define("EW_PAGE_ID", 'addopt', TRUE);

		// Table name (for backward compatibility)
		if (!defined("EW_TABLE_NAME"))
			define("EW_TABLE_NAME", 'co', TRUE);

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

		// Debug message
		ew_LoadDebugMsg();

		// Open connection
		if (!isset($conn))
			$conn = ew_Connect($this->DBID);

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

	//
	//  Page_Init
	//
	function Page_Init() {
		global $gsExport, $gsCustomExport, $gsExportFile, $UserProfile, $Language, $Security, $objForm;

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

		// Security
		$Security = new cAdvancedSecurity();
		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(ew_DeniedMsg()); // Set no permission
			if ($Security->CanList())
				$this->Page_Terminate(ew_GetUrl("colist.php"));
			else
				$this->Page_Terminate(ew_GetUrl("login.php"));
		}

		// NOTE: Security object may be needed in other part of the script, skip set to Nothing
		// 
		// Security = null;
		// 
		// Create form object

		$objForm = new cFormObj();
		$this->CurrentAction = (@$_GET["a"] <> "") ? $_GET["a"] : @$_POST["a_list"]; // Set up current action
		$this->co_id->SetVisibility();
		if ($this->IsAdd() || $this->IsCopy() || $this->IsGridAdd())
			$this->co_id->Visible = FALSE;
		$this->co_nama->SetVisibility();
		$this->co_telp->SetVisibility();
		$this->co_foto->SetVisibility();

		// Global Page Loading event (in userfn*.php)
		Page_Loading();

		// Page Load event
		$this->Page_Load();

		// Check token
		if (!$this->ValidPost()) {
			echo $Language->Phrase("InvalidPostRequest");
			$this->Page_Terminate();
			exit();
		}

		// Process auto fill
		if (@$_POST["ajax"] == "autofill") {
			$results = $this->GetAutoFill(@$_POST["name"], @$_POST["q"]);
			if ($results) {

				// Clean output buffer
				if (!EW_DEBUG_ENABLED && ob_get_length())
					ob_end_clean();
				echo $results;
				$this->Page_Terminate();
				exit();
			}
		}

		// Create Token
		$this->CreateToken();
	}

	//
	// Page_Terminate
	//
	function Page_Terminate($url = "") {
		global $gsExportFile, $gTmpImages;

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

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

		// Export
		global $EW_EXPORT, $co;
		if ($this->CustomExport <> "" && $this->CustomExport == $this->Export && array_key_exists($this->CustomExport, $EW_EXPORT)) {
				$sContent = ob_get_contents();
			if ($gsExportFile == "") $gsExportFile = $this->TableVar;
			$class = $EW_EXPORT[$this->CustomExport];
			if (class_exists($class)) {
				$doc = new $class($co);
				$doc->Text = $sContent;
				if ($this->Export == "email")
					echo $this->ExportEmail($doc->Text);
				else
					$doc->Export();
				ew_DeleteTmpImages(); // Delete temp images
				exit();
			}
		}
		$this->Page_Redirecting($url);

		// Close connection
		ew_CloseConn();

		// Go to URL if specified
		if ($url <> "") {
			if (!EW_DEBUG_ENABLED && ob_get_length())
				ob_end_clean();
			ew_SaveDebugMsg();
			header("Location: " . $url);
		}
		exit();
	}

	//
	// Page main
	//
	function Page_Main() {
		global $objForm, $Language, $gsFormError;
		set_error_handler("ew_ErrorHandler");

		// Set up Breadcrumb
		//$this->SetupBreadcrumb(); // Not used

		$this->LoadRowValues(); // Load default values

		// Process form if post back
		if ($objForm->GetValue("a_addopt") <> "") {
			$this->CurrentAction = $objForm->GetValue("a_addopt"); // Get form action
			$this->LoadFormValues(); // Load form values

			// Validate form
			if (!$this->ValidateForm()) {
				$this->CurrentAction = "I"; // Form error, reset action
				$this->setFailureMessage($gsFormError);
			}
		} else { // Not post back
			$this->CurrentAction = "I"; // Display blank record
		}

		// Perform action based on action code
		switch ($this->CurrentAction) {
			case "I": // Blank record, no action required
				break;
			case "A": // Add new record
				$this->SendEmail = TRUE; // Send email on add success
				if ($this->AddRow()) { // Add successful
					$row = array();
					$row["x_co_id"] = $this->co_id->DbValue;
					$row["x_co_nama"] = ew_ConvertToUtf8($this->co_nama->DbValue);
					$row["x_co_telp"] = ew_ConvertToUtf8($this->co_telp->DbValue);
					$row["x_co_foto"] = ew_ConvertToUtf8($this->co_foto->DbValue);
					if (!EW_DEBUG_ENABLED && ob_get_length())
						ob_end_clean();
					ew_Header(FALSE, "utf-8", TRUE);
					echo ew_ArrayToJson(array($row));
				} else {
					$this->ShowMessage();
				}
				$this->Page_Terminate();
				exit();
		}

		// Render row
		$this->RowType = EW_ROWTYPE_ADD; // Render add type
		$this->ResetAttrs();
		$this->RenderRow();
	}

	// Get upload files
	function GetUploadFiles() {
		global $objForm, $Language;

		// Get upload data
		$this->co_foto->Upload->Index = $objForm->Index;
		$this->co_foto->Upload->UploadFile();
		$this->co_foto->CurrentValue = $this->co_foto->Upload->FileName;
	}

	// Load default values
	function LoadDefaultValues() {
		$this->co_id->CurrentValue = NULL;
		$this->co_id->OldValue = $this->co_id->CurrentValue;
		$this->co_nama->CurrentValue = NULL;
		$this->co_nama->OldValue = $this->co_nama->CurrentValue;
		$this->co_telp->CurrentValue = NULL;
		$this->co_telp->OldValue = $this->co_telp->CurrentValue;
		$this->co_foto->Upload->DbValue = NULL;
		$this->co_foto->OldValue = $this->co_foto->Upload->DbValue;
		$this->co_foto->CurrentValue = NULL; // Clear file related field
	}

	// Load form values
	function LoadFormValues() {

		// Load from form
		global $objForm;
		$this->GetUploadFiles(); // Get upload files
		if (!$this->co_nama->FldIsDetailKey) {
			$this->co_nama->setFormValue(ew_ConvertFromUtf8($objForm->GetValue("x_co_nama")));
		}
		if (!$this->co_telp->FldIsDetailKey) {
			$this->co_telp->setFormValue(ew_ConvertFromUtf8($objForm->GetValue("x_co_telp")));
		}
	}

	// Restore form values
	function RestoreFormValues() {
		global $objForm;
		$this->co_nama->CurrentValue = ew_ConvertToUtf8($this->co_nama->FormValue);
		$this->co_telp->CurrentValue = ew_ConvertToUtf8($this->co_telp->FormValue);
	}

	// Load row based on key values
	function LoadRow() {
		global $Security, $Language;
		$sFilter = $this->KeyFilter();

		// Call Row Selecting event
		$this->Row_Selecting($sFilter);

		// Load SQL based on filter
		$this->CurrentFilter = $sFilter;
		$sSql = $this->SQL();
		$conn = &$this->Connection();
		$res = FALSE;
		$rs = ew_LoadRecordset($sSql, $conn);
		if ($rs && !$rs->EOF) {
			$res = TRUE;
			$this->LoadRowValues($rs); // Load row values
			$rs->Close();
		}
		return $res;
	}

	// Load row values from recordset
	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->co_id->setDbValue($row['co_id']);
		$this->co_nama->setDbValue($row['co_nama']);
		$this->co_telp->setDbValue($row['co_telp']);
		$this->co_foto->Upload->DbValue = $row['co_foto'];
		$this->co_foto->setDbValue($this->co_foto->Upload->DbValue);
	}

	// Return a row with default values
	function NewRow() {
		$this->LoadDefaultValues();
		$row = array();
		$row['co_id'] = $this->co_id->CurrentValue;
		$row['co_nama'] = $this->co_nama->CurrentValue;
		$row['co_telp'] = $this->co_telp->CurrentValue;
		$row['co_foto'] = $this->co_foto->Upload->DbValue;
		return $row;
	}

	// Load DbValue from recordset
	function LoadDbValues(&$rs) {
		if (!$rs || !is_array($rs) && $rs->EOF)
			return;
		$row = is_array($rs) ? $rs : $rs->fields;
		$this->co_id->DbValue = $row['co_id'];
		$this->co_nama->DbValue = $row['co_nama'];
		$this->co_telp->DbValue = $row['co_telp'];
		$this->co_foto->Upload->DbValue = $row['co_foto'];
	}

	// Render row values based on field settings
	function RenderRow() {
		global $Security, $Language, $gsLanguage;

		// Initialize URLs
		// Call Row_Rendering event

		$this->Row_Rendering();

		// Common render codes for all row types
		// co_id
		// co_nama
		// co_telp
		// co_foto

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

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

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

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

		// co_foto
		$this->co_foto->UploadPath = "foto_co";
		if (!ew_Empty($this->co_foto->Upload->DbValue)) {
			$this->co_foto->ImageWidth = 30;
			$this->co_foto->ImageHeight = 40;
			$this->co_foto->ImageAlt = $this->co_foto->FldAlt();
			$this->co_foto->ViewValue = $this->co_foto->Upload->DbValue;
		} else {
			$this->co_foto->ViewValue = "";
		}
		$this->co_foto->ViewCustomAttributes = "";

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

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

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

			// co_foto
			$this->co_foto->LinkCustomAttributes = "";
			$this->co_foto->UploadPath = "foto_co";
			if (!ew_Empty($this->co_foto->Upload->DbValue)) {
				$this->co_foto->HrefValue = ew_GetFileUploadUrl($this->co_foto, $this->co_foto->Upload->DbValue); // Add prefix/suffix
				$this->co_foto->LinkAttrs["target"] = "_blank"; // Add target
				if ($this->Export <> "") $this->co_foto->HrefValue = ew_FullUrl($this->co_foto->HrefValue, "href");
			} else {
				$this->co_foto->HrefValue = "";
			}
			$this->co_foto->HrefValue2 = $this->co_foto->UploadPath . $this->co_foto->Upload->DbValue;
			$this->co_foto->TooltipValue = "";
			if ($this->co_foto->UseColorbox) {
				if (ew_Empty($this->co_foto->TooltipValue))
					$this->co_foto->LinkAttrs["title"] = $Language->Phrase("ViewImageGallery");
				$this->co_foto->LinkAttrs["data-rel"] = "co_x_co_foto";
				ew_AppendClass($this->co_foto->LinkAttrs["class"], "ewLightbox");
			}
		} elseif ($this->RowType == EW_ROWTYPE_ADD) { // Add row

			// co_id
			// co_nama

			$this->co_nama->EditAttrs["class"] = "form-control";
			$this->co_nama->EditCustomAttributes = "";
			$this->co_nama->EditValue = ew_HtmlEncode($this->co_nama->CurrentValue);
			$this->co_nama->PlaceHolder = ew_RemoveHtml($this->co_nama->FldCaption());

			// co_telp
			$this->co_telp->EditAttrs["class"] = "form-control";
			$this->co_telp->EditCustomAttributes = "";
			$this->co_telp->EditValue = ew_HtmlEncode($this->co_telp->CurrentValue);
			$this->co_telp->PlaceHolder = ew_RemoveHtml($this->co_telp->FldCaption());

			// co_foto
			$this->co_foto->EditAttrs["class"] = "form-control";
			$this->co_foto->EditCustomAttributes = "";
			$this->co_foto->UploadPath = "foto_co";
			if (!ew_Empty($this->co_foto->Upload->DbValue)) {
				$this->co_foto->ImageWidth = 30;
				$this->co_foto->ImageHeight = 40;
				$this->co_foto->ImageAlt = $this->co_foto->FldAlt();
				$this->co_foto->EditValue = $this->co_foto->Upload->DbValue;
			} else {
				$this->co_foto->EditValue = "";
			}
			if (!ew_Empty($this->co_foto->CurrentValue))
					$this->co_foto->Upload->FileName = $this->co_foto->CurrentValue;
			if ($this->CurrentAction == "I" && !$this->EventCancelled) ew_RenderUploadField($this->co_foto);

			// Add refer script
			// co_id

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

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

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

			// co_foto
			$this->co_foto->LinkCustomAttributes = "";
			$this->co_foto->UploadPath = "foto_co";
			if (!ew_Empty($this->co_foto->Upload->DbValue)) {
				$this->co_foto->HrefValue = ew_GetFileUploadUrl($this->co_foto, $this->co_foto->Upload->DbValue); // Add prefix/suffix
				$this->co_foto->LinkAttrs["target"] = "_blank"; // Add target
				if ($this->Export <> "") $this->co_foto->HrefValue = ew_FullUrl($this->co_foto->HrefValue, "href");
			} else {
				$this->co_foto->HrefValue = "";
			}
			$this->co_foto->HrefValue2 = $this->co_foto->UploadPath . $this->co_foto->Upload->DbValue;
		}
		if ($this->RowType == EW_ROWTYPE_ADD || $this->RowType == EW_ROWTYPE_EDIT || $this->RowType == EW_ROWTYPE_SEARCH) // Add/Edit/Search row
			$this->SetupFieldTitles();

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

	// Validate form
	function ValidateForm() {
		global $Language, $gsFormError;

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

		// Check if validation required
		if (!EW_SERVER_VALIDATE)
			return ($gsFormError == "");
		if (!ew_CheckInteger($this->co_id->FormValue)) {
			ew_AddMessage($gsFormError, $this->co_id->FldErrMsg());
		}
		if (!ew_CheckInteger($this->co_telp->FormValue)) {
			ew_AddMessage($gsFormError, $this->co_telp->FldErrMsg());
		}

		// Return validate result
		$ValidateForm = ($gsFormError == "");

		// Call Form_CustomValidate event
		$sFormCustomError = "";
		$ValidateForm = $ValidateForm && $this->Form_CustomValidate($sFormCustomError);
		if ($sFormCustomError <> "") {
			ew_AddMessage($gsFormError, $sFormCustomError);
		}
		return $ValidateForm;
	}

	// Add record
	function AddRow($rsold = NULL) {
		global $Language, $Security;
		$conn = &$this->Connection();

		// Load db values from rsold
		$this->LoadDbValues($rsold);
		if ($rsold) {
			$this->co_foto->OldUploadPath = "foto_co";
			$this->co_foto->UploadPath = $this->co_foto->OldUploadPath;
		}
		$rsnew = array();

		// co_nama
		$this->co_nama->SetDbValueDef($rsnew, $this->co_nama->CurrentValue, NULL, FALSE);

		// co_telp
		$this->co_telp->SetDbValueDef($rsnew, $this->co_telp->CurrentValue, NULL, FALSE);

		// co_foto
		if ($this->co_foto->Visible && !$this->co_foto->Upload->KeepFile) {
			$this->co_foto->Upload->DbValue = ""; // No need to delete old file
			if ($this->co_foto->Upload->FileName == "") {
				$rsnew['co_foto'] = NULL;
			} else {
				$rsnew['co_foto'] = $this->co_foto->Upload->FileName;
			}
			$this->co_foto->ImageWidth = 300; // Resize width
			$this->co_foto->ImageHeight = 400; // Resize height
		}
		if ($this->co_foto->Visible && !$this->co_foto->Upload->KeepFile) {
			$this->co_foto->UploadPath = "foto_co";
			$OldFiles = ew_Empty($this->co_foto->Upload->DbValue) ? array() : array($this->co_foto->Upload->DbValue);
			if (!ew_Empty($this->co_foto->Upload->FileName)) {
				$NewFiles = array($this->co_foto->Upload->FileName);
				$NewFileCount = count($NewFiles);
				for ($i = 0; $i < $NewFileCount; $i++) {
					$fldvar = ($this->co_foto->Upload->Index < 0) ? $this->co_foto->FldVar : substr($this->co_foto->FldVar, 0, 1) . $this->co_foto->Upload->Index . substr($this->co_foto->FldVar, 1);
					if ($NewFiles[$i] <> "") {
						$file = $NewFiles[$i];
						if (file_exists(ew_UploadTempPath($fldvar, $this->co_foto->TblVar) . $file)) {
							$OldFileFound = FALSE;
							$OldFileCount = count($OldFiles);
							for ($j = 0; $j < $OldFileCount; $j++) {
								$file1 = $OldFiles[$j];
								if ($file1 == $file) { // Old file found, no need to delete anymore
									unset($OldFiles[$j]);
									$OldFileFound = TRUE;
									break;
								}
							}
							if ($OldFileFound) // No need to check if file exists further
								continue;
							$file1 = ew_UploadFileNameEx($this->co_foto->PhysicalUploadPath(), $file); // Get new file name
							if ($file1 <> $file) { // Rename temp file
								while (file_exists(ew_UploadTempPath($fldvar, $this->co_foto->TblVar) . $file1) || file_exists($this->co_foto->PhysicalUploadPath() . $file1)) // Make sure no file name clash
									$file1 = ew_UniqueFilename($this->co_foto->PhysicalUploadPath(), $file1, TRUE); // Use indexed name
								rename(ew_UploadTempPath($fldvar, $this->co_foto->TblVar) . $file, ew_UploadTempPath($fldvar, $this->co_foto->TblVar) . $file1);
								$NewFiles[$i] = $file1;
							}
						}
					}
				}
				$this->co_foto->Upload->DbValue = empty($OldFiles) ? "" : implode(EW_MULTIPLE_UPLOAD_SEPARATOR, $OldFiles);
				$this->co_foto->Upload->FileName = implode(EW_MULTIPLE_UPLOAD_SEPARATOR, $NewFiles);
				$this->co_foto->SetDbValueDef($rsnew, $this->co_foto->Upload->FileName, NULL, FALSE);
			}
		}

		// Call Row Inserting event
		$rs = ($rsold == NULL) ? NULL : $rsold->fields;
		$bInsertRow = $this->Row_Inserting($rs, $rsnew);
		if ($bInsertRow) {
			$conn->raiseErrorFn = $GLOBALS["EW_ERROR_FN"];
			$AddRow = $this->Insert($rsnew);
			$conn->raiseErrorFn = '';
			if ($AddRow) {
				if ($this->co_foto->Visible && !$this->co_foto->Upload->KeepFile) {
					$OldFiles = ew_Empty($this->co_foto->Upload->DbValue) ? array() : array($this->co_foto->Upload->DbValue);
					if (!ew_Empty($this->co_foto->Upload->FileName)) {
						$NewFiles = array($this->co_foto->Upload->FileName);
						$NewFiles2 = array($rsnew['co_foto']);
						$NewFileCount = count($NewFiles);
						for ($i = 0; $i < $NewFileCount; $i++) {
							$fldvar = ($this->co_foto->Upload->Index < 0) ? $this->co_foto->FldVar : substr($this->co_foto->FldVar, 0, 1) . $this->co_foto->Upload->Index . substr($this->co_foto->FldVar, 1);
							if ($NewFiles[$i] <> "") {
								$file = ew_UploadTempPath($fldvar, $this->co_foto->TblVar) . $NewFiles[$i];
								if (file_exists($file)) {
									if (@$NewFiles2[$i] <> "") // Use correct file name
										$NewFiles[$i] = $NewFiles2[$i];
									if (!$this->co_foto->Upload->ResizeAndSaveToFile($this->co_foto->ImageWidth, $this->co_foto->ImageHeight, EW_THUMBNAIL_DEFAULT_QUALITY, $NewFiles[$i], TRUE, $i)) {
										$this->setFailureMessage($Language->Phrase("UploadErrMsg7"));
										return FALSE;
									}
								}
							}
						}
					} else {
						$NewFiles = array();
					}
					$OldFileCount = count($OldFiles);
					for ($i = 0; $i < $OldFileCount; $i++) {
						if ($OldFiles[$i] <> "" && !in_array($OldFiles[$i], $NewFiles))
							@unlink($this->co_foto->OldPhysicalUploadPath() . $OldFiles[$i]);
					}
				}
			}
		} 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 == NULL) ? NULL : $rsold->fields;
			$this->Row_Inserted($rs, $rsnew);
		}

		// co_foto
		ew_CleanUploadTempPath($this->co_foto, $this->co_foto->Upload->Index);
		return $AddRow;
	}

	// Set up Breadcrumb
	function SetupBreadcrumb() {
		global $Breadcrumb, $Language;
		$Breadcrumb = new cBreadcrumb();
		$url = substr(ew_CurrentUrl(), strrpos(ew_CurrentUrl(), "/")+1);
		$Breadcrumb->Add("list", $this->TableVar, $this->AddMasterUrl("colist.php"), "", $this->TableVar, TRUE);
		$PageId = "addopt";
		$Breadcrumb->Add("addopt", $PageId, $url);
	}

	// Setup lookup filters of a field
	function SetupLookupFilters($fld, $pageId = null) {
		global $gsLanguage;
		$pageId = $pageId ?: $this->PageID;
		switch ($fld->FldVar) {
		}
	}

	// Setup AutoSuggest filters of a field
	function SetupAutoSuggestFilters($fld, $pageId = null) {
		global $gsLanguage;
		$pageId = $pageId ?: $this->PageID;
		switch ($fld->FldVar) {
		}
	}

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

	}

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

		// Return error message in CustomError
		return TRUE;
	}
}
?>
<?php ew_Header(FALSE) ?>
<?php

// Create page object
if (!isset($co_addopt)) $co_addopt = new cco_addopt();

// Page init
$co_addopt->Page_Init();

// Page main
$co_addopt->Page_Main();

// Global Page Rendering event (in userfn*.php)
Page_Rendering();

// Page Rendering event
$co_addopt->Page_Render();
?>
<script type="text/javascript">

// Form object
var CurrentPageID = EW_PAGE_ID = "addopt";
var CurrentForm = fcoaddopt = new ew_Form("fcoaddopt", "addopt");

// Validate form
fcoaddopt.Validate = function() {
	if (!this.ValidateRequired)
		return true; // Ignore validation
	var $ = jQuery, fobj = this.GetForm(), $fobj = $(fobj);
	if ($fobj.find("#a_confirm").val() == "F")
		return true;
	var elm, felm, uelm, addcnt = 0;
	var $k = $fobj.find("#" + this.FormKeyCountName); // Get key_count
	var rowcnt = ($k[0]) ? parseInt($k.val(), 10) : 1;
	var startcnt = (rowcnt == 0) ? 0 : 1; // Check rowcnt == 0 => Inline-Add
	var gridinsert = $fobj.find("#a_list").val() == "gridinsert";
	for (var i = startcnt; i <= rowcnt; i++) {
		var infix = ($k[0]) ? String(i) : "";
		$fobj.data("rowindex", infix);
			elm = this.GetElements("x" + infix + "_co_id");
			if (elm && !ew_CheckInteger(elm.value))
				return this.OnError(elm, "<?php echo ew_JsEncode2($co->co_id->FldErrMsg()) ?>");
			elm = this.GetElements("x" + infix + "_co_telp");
			if (elm && !ew_CheckInteger(elm.value))
				return this.OnError(elm, "<?php echo ew_JsEncode2($co->co_telp->FldErrMsg()) ?>");

			// Fire Form_CustomValidate event
			if (!this.Form_CustomValidate(fobj))
				return false;
	}
	return true;
}

// Form_CustomValidate event
fcoaddopt.Form_CustomValidate = 
 function(fobj) { // DO NOT CHANGE THIS LINE!

 	// Your custom validation code here, return false if invalid.
 	return true;
 }

// Use JavaScript validation or not
fcoaddopt.ValidateRequired = <?php echo json_encode(EW_CLIENT_VALIDATE) ?>;

// Dynamic selection lists
// Form object for search

</script>
<script type="text/javascript">

// Write your client script here, no need to add script tags.
</script>
<?php
$co_addopt->ShowMessage();
?>
<form name="fcoaddopt" id="fcoaddopt" class="ewForm form-horizontal" action="coaddopt.php" method="post">
<?php if ($co_addopt->CheckToken) { ?>
<input type="hidden" name="<?php echo EW_TOKEN_NAME ?>" value="<?php echo $co_addopt->Token ?>">
<?php } ?>
<input type="hidden" name="t" value="co">
<input type="hidden" name="a_addopt" id="a_addopt" value="A">
<?php if ($co->co_id->Visible) { // co_id ?>
<?php } ?>
<?php if ($co->co_nama->Visible) { // co_nama ?>
	<div class="form-group">
		<label class="col-sm-2 control-label ewLabel" for="x_co_nama"><?php echo $co->co_nama->FldCaption() ?></label>
		<div class="col-sm-10">
<input type="text" data-table="co" data-field="x_co_nama" name="x_co_nama" id="x_co_nama" size="30" maxlength="50" placeholder="<?php echo ew_HtmlEncode($co->co_nama->getPlaceHolder()) ?>" value="<?php echo $co->co_nama->EditValue ?>"<?php echo $co->co_nama->EditAttributes() ?>>
</div>
	</div>
<?php } ?>
<?php if ($co->co_telp->Visible) { // co_telp ?>
	<div class="form-group">
		<label class="col-sm-2 control-label ewLabel" for="x_co_telp"><?php echo $co->co_telp->FldCaption() ?></label>
		<div class="col-sm-10">
<input type="text" data-table="co" data-field="x_co_telp" name="x_co_telp" id="x_co_telp" size="30" placeholder="<?php echo ew_HtmlEncode($co->co_telp->getPlaceHolder()) ?>" value="<?php echo $co->co_telp->EditValue ?>"<?php echo $co->co_telp->EditAttributes() ?>>
</div>
	</div>
<?php } ?>
<?php if ($co->co_foto->Visible) { // co_foto ?>
	<div class="form-group">
		<label class="col-sm-2 control-label ewLabel"><?php echo $co->co_foto->FldCaption() ?></label>
		<div class="col-sm-10">
<div id="fd_x_co_foto">
<span title="<?php echo $co->co_foto->FldTitle() ? $co->co_foto->FldTitle() : $Language->Phrase("ChooseFile") ?>" class="btn btn-default btn-sm fileinput-button ewTooltip<?php if ($co->co_foto->ReadOnly || $co->co_foto->Disabled) echo " hide"; ?>" data-trigger="hover">
	<span><?php echo $Language->Phrase("ChooseFileBtn") ?></span>
	<input type="file" title=" " data-table="co" data-field="x_co_foto" name="x_co_foto" id="x_co_foto"<?php echo $co->co_foto->EditAttributes() ?>>
</span>
<input type="hidden" name="fn_x_co_foto" id= "fn_x_co_foto" value="<?php echo $co->co_foto->Upload->FileName ?>">
<input type="hidden" name="fa_x_co_foto" id= "fa_x_co_foto" value="0">
<input type="hidden" name="fs_x_co_foto" id= "fs_x_co_foto" value="50">
<input type="hidden" name="fx_x_co_foto" id= "fx_x_co_foto" value="<?php echo $co->co_foto->UploadAllowedFileExt ?>">
<input type="hidden" name="fm_x_co_foto" id= "fm_x_co_foto" value="<?php echo $co->co_foto->UploadMaxFileSize ?>">
</div>
<table id="ft_x_co_foto" class="table table-condensed pull-left ewUploadTable"><tbody class="files"></tbody></table>
</div>
	</div>
<?php } ?>
</form>
<script type="text/javascript">
fcoaddopt.Init();
</script>
<script type="text/javascript">

// Write your table-specific startup script here
// document.write("page loaded");

</script>
<?php
$co_addopt->Page_Terminate();
?>
