<?php
define("EW_PAGE_ID", "add", TRUE); // Page ID
define("EW_TABLE_NAME", 'osj-categories', TRUE);
?>
<?php 
session_start(); // Initialize session data
ob_start(); // Turn on output buffering
?>
<?php include "osj-ewcfg50.php" ?>
<?php include "osj-ewmysql50.php" ?>
<?php include "osj-phpfn50.php" ?>
<?php include "osj-osj2dcategoriesinfo.php" ?>
<?php include "osj-userfn50.php" ?>
<?php include "osj-osj2dusersinfo.php" ?>
<?php
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // Always modified
header("Cache-Control: private, no-store, no-cache, must-revalidate"); // HTTP/1.1 
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache"); // HTTP/1.0
?>
<?php

// Open connection to the database
$conn = ew_Connect();
?>
<?php
$Security = new cAdvancedSecurity();
?>
<?php
if (!$Security->IsLoggedIn()) $Security->AutoLogin();
$Security->LoadCurrentUserLevel('osj-categories');
if (!$Security->IsLoggedIn()) {
	$Security->SaveLastUrl();
	Page_Terminate("osj-login.php");
}
if (!$Security->CanAdd()) {
	$Security->SaveLastUrl();
	Page_Terminate("osj-osj2dcategorieslist.php");
}
?>
<?php

// Common page loading event (in userfn*.php)
Page_Loading();
?>
<?php

// Page load event, used in current page
Page_Load();
?>
<?php
$osj2Dcategories->Export = @$_GET["export"]; // Get export parameter
$sExport = $osj2Dcategories->Export; // Get export parameter, used in header
$sExportFile = $osj2Dcategories->TableVar; // Get export file, used in header
?>
<?php

// Load key values from QueryString
$bCopy = TRUE;
if (@$_GET["category_id"] != "") {
  $osj2Dcategories->category_id->setQueryStringValue($_GET["category_id"]);
} else {
  $bCopy = FALSE;
}

// Create form object
$objForm = new cFormObj();

// Process form if post back
if (@$_POST["a_add"] <> "") {
  $osj2Dcategories->CurrentAction = $_POST["a_add"]; // Get form action
  LoadFormValues(); // Load form values
} else { // Not post back
  if ($bCopy) {
    $osj2Dcategories->CurrentAction = "C"; // Copy Record
  } else {
    $osj2Dcategories->CurrentAction = "I"; // Display Blank Record
    LoadDefaultValues(); // Load default values
  }
}

// Perform action based on action code
switch ($osj2Dcategories->CurrentAction) {
  case "I": // Blank record, no action required
		break;
  case "C": // Copy an existing record
   if (!LoadRow()) { // Load record based on key
      $_SESSION[EW_SESSION_MESSAGE] = "No records found"; // No record found
      Page_Terminate($osj2Dcategories->getReturnUrl()); // Clean up and return
    }
		break;
  case "A": // ' Add new record
		$osj2Dcategories->SendEmail = TRUE; // Send email on add success
    if (AddRow()) { // Add successful
      $_SESSION[EW_SESSION_MESSAGE] = "Add New Record Successful"; // Set up success message
      Page_Terminate($osj2Dcategories->KeyUrl($osj2Dcategories->getReturnUrl())); // Clean up and return
    } else {
      RestoreFormValues(); // Add failed, restore form values
    }
}

// Render row based on row type
$osj2Dcategories->RowType = EW_ROWTYPE_ADD;  // Render add type
RenderRow();
?>
<?php include "osj-header.php" ?>
<script type="text/javascript">
<!--
var EW_PAGE_ID = "add"; // Page id
var EW_SHOW_HIGHLIGHT = "Show highlight"; 
var EW_HIDE_HIGHLIGHT = "Hide highlight";

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

function ew_ValidateForm(fobj) {
	if (fobj.a_confirm && fobj.a_confirm.value == "F")
		return true;
	var i, elm, aelm, infix;
	var rowcnt = (fobj.key_count) ? Number(fobj.key_count.value) : 1;
	for (i=0; i<rowcnt; i++) {
		infix = (fobj.key_count) ? String(i+1) : "";
		elm = fobj.elements["x" + infix + "_category_id"];
		if (elm && !ew_HasValue(elm)) {
			if (!ew_OnError(elm, "Please enter required field - category id"))
				return false;
		}
		elm = fobj.elements["x" + infix + "_category_id"];
		if (elm && !ew_CheckInteger(elm.value)) {
			if (!ew_OnError(elm, "Incorrect integer - category id"))
				return false; 
		}
		elm = fobj.elements["x" + infix + "_category_name"];
		if (elm && !ew_HasValue(elm)) {
			if (!ew_OnError(elm, "Please enter required field - Category Name"))
				return false;
		}
	}
	return true;
}

//-->
</script>
<script type="text/javascript">
<!--
var ew_DHTMLEditors = [];

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

// js for Popup Calendar
//-->

</script>
<script type="text/javascript">
<!--
var ew_MultiPagePage = "Page"; // multi-page Page Text
var ew_MultiPageOf = "of"; // multi-page Of Text
var ew_MultiPagePrev = "Prev"; // multi-page Prev Text
var ew_MultiPageNext = "Next"; // multi-page Next Text

//-->
</script>
<script language="JavaScript" type="text/javascript">
<!--

// Write your client script here, no need to add script tags.
// To include another .js script, use:
// ew_ClientScriptInclude("my_javascript.js"); 
//-->

</script>
<p><span class="phpmaker">Add to TABLE: Categories<br><br><a href="<?php echo $osj2Dcategories->getReturnUrl() ?>">Go Back</a></span></p>
<?php
if (@$_SESSION[EW_SESSION_MESSAGE] <> "") { // Mesasge in Session, display
?>
<p><span class="ewmsg"><?php echo $_SESSION[EW_SESSION_MESSAGE] ?></span></p>
<?php
  $_SESSION[EW_SESSION_MESSAGE] = ""; // Clear message in Session
}
?>
<form name="fosj2Dcategoriesadd" id="fosj2Dcategoriesadd" action="osj-osj2dcategoriesadd.php" method="post" onSubmit="return ew_ValidateForm(this);">
<p>
<input type="hidden" name="a_add" id="a_add" value="A">
<table class="ewTable">
  <tr class="ewTableRow">
    <td class="ewTableHeader">category id<span class='ewmsg'>&nbsp;*</span></td>
    <td<?php echo $osj2Dcategories->category_id->CellAttributes() ?>><span id="cb_x_category_id"></span></td>
  </tr>
  <tr class="ewTableAltRow">
    <td class="ewTableHeader">parent id<span class='ewmsg'>&nbsp;*</span></td>
    <td<?php echo $osj2Dcategories->parent_id->CellAttributes() ?>><span id="cb_x_parent_id">
<select id="x_parent_id" name="x_parent_id"<?php echo $osj2Dcategories->parent_id->EditAttributes() ?>>
<!--option value="">Please Select</option-->
<?php
if (is_array($osj2Dcategories->parent_id->EditValue)) {
	$arwrk = $osj2Dcategories->parent_id->EditValue;
	$rowswrk = count($arwrk);
	for ($rowcntwrk = 0; $rowcntwrk < $rowswrk; $rowcntwrk++) {
		$selwrk = (strval($osj2Dcategories->parent_id->CurrentValue) == strval($arwrk[$rowcntwrk][0])) ? " selected" : "";	
?>
<option value="<?php echo ew_HtmlEncode($arwrk[$rowcntwrk][0]) ?>"<?php echo $selwrk ?>>
<?php echo $arwrk[$rowcntwrk][1] ?>
</option>
<?php
			}
}
?>
</select>
</span></td>
  </tr>
  <tr class="ewTableRow">
    <td class="ewTableHeader">Category Name<span class='ewmsg'>&nbsp;*</span></td>
    <td<?php echo $osj2Dcategories->category_name->CellAttributes() ?>><span id="cb_x_category_name">
<input type="text" name="x_category_name" id="x_category_name" title="Category Name"  size="30" maxlength="255" value="<?php echo $osj2Dcategories->category_name->EditValue ?>"<?php echo $osj2Dcategories->category_name->EditAttributes() ?>>
</span></td>
  </tr>
</table>
<p>
<input type="submit" name="btnAction" id="btnAction" value="    Add    ">
</form>
<script language="JavaScript" type="text/javascript">
<!--

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

</script>
<?php include "osj-footer.php" ?>
<?php

// If control is passed here, simply terminate the page without redirect
Page_Terminate();

// -----------------------------------------------------------------
//  Subroutine Page_Terminate
//  - called when exit page
//  - clean up connection and objects
//  - if url specified, redirect to url, otherwise end response
function Page_Terminate($url = "") {
	global $conn;

	// Page unload event, used in current page
	Page_Unload();

	// Global page unloaded event (in userfn*.php)
	Page_Unloaded();

	 // Close Connection
	$conn->Close();

	// Go to url if specified
	if ($url <> "") {
		ob_end_clean();
		header("Location: $url");
	}
	exit();
}
?>
<?php

// Load default values
function LoadDefaultValues() {
	global $osj2Dcategories;
	$osj2Dcategories->parent_id->CurrentValue = 0;
}
?>
<?php

// Load form values
function LoadFormValues() {

	// Load from form
	global $objForm, $osj2Dcategories;
	$osj2Dcategories->category_id->setFormValue($objForm->GetValue("x_category_id"));
	$osj2Dcategories->parent_id->setFormValue($objForm->GetValue("x_parent_id"));
	$osj2Dcategories->category_name->setFormValue($objForm->GetValue("x_category_name"));
}

// Restore form values
function RestoreFormValues() {
	global $osj2Dcategories;
	$osj2Dcategories->category_id->CurrentValue = $osj2Dcategories->category_id->FormValue;
	$osj2Dcategories->parent_id->CurrentValue = $osj2Dcategories->parent_id->FormValue;
	$osj2Dcategories->category_name->CurrentValue = $osj2Dcategories->category_name->FormValue;
}
?>
<?php

// Load row based on key values
function LoadRow() {
	global $conn, $Security, $osj2Dcategories;
	$sFilter = $osj2Dcategories->SqlKeyFilter();
	if (!is_numeric($osj2Dcategories->category_id->CurrentValue)) {
		return FALSE; // Invalid key, exit
	}
	$sFilter = str_replace("@category_id@", ew_AdjustSql($osj2Dcategories->category_id->CurrentValue), $sFilter); // Replace key value

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

	// Load sql based on filter
	$osj2Dcategories->CurrentFilter = $sFilter;
	$sSql = $osj2Dcategories->SQL();
	if ($rs = $conn->Execute($sSql)) {
		if ($rs->EOF) {
			$LoadRow = FALSE;
		} else {
			$LoadRow = TRUE;
			$rs->MoveFirst();
			LoadRowValues($rs); // Load row values

			// Call Row Selected event
			$osj2Dcategories->Row_Selected($rs);
		}
		$rs->Close();
	} else {
		$LoadRow = FALSE;
	}
	return $LoadRow;
}

// Load row values from recordset
function LoadRowValues(&$rs) {
	global $osj2Dcategories;
	$osj2Dcategories->category_id->setDbValue($rs->fields('category_id'));
	$osj2Dcategories->parent_id->setDbValue($rs->fields('parent_id'));
	$osj2Dcategories->category_name->setDbValue($rs->fields('category_name'));
}
?>
<?php

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

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

	// Common render codes for all row types
	// category_id

	$osj2Dcategories->category_id->CellCssStyle = "";
	$osj2Dcategories->category_id->CellCssClass = "";

	// parent_id
	$osj2Dcategories->parent_id->CellCssStyle = "";
	$osj2Dcategories->parent_id->CellCssClass = "";

	// category_name
	$osj2Dcategories->category_name->CellCssStyle = "";
	$osj2Dcategories->category_name->CellCssClass = "";
	if ($osj2Dcategories->RowType == EW_ROWTYPE_VIEW) { // View row
	} elseif ($osj2Dcategories->RowType == EW_ROWTYPE_ADD) { // Add row

		// category_id
		$osj2Dcategories->category_id->EditCustomAttributes = "";
		$osj2Dcategories->category_id->EditValue = ew_HtmlEncode($osj2Dcategories->category_id->CurrentValue);

		// parent_id
		$osj2Dcategories->parent_id->EditCustomAttributes = "";
		$sSqlWrk = "SELECT `category_id`, `category_name` FROM `osj-categories`";
		$sSqlWrk .= " WHERE (" . "`parent_id` = 0 OR `parent_id` = -1" . ")";
		$sSqlWrk .= " ORDER BY `category_name` ";
		$rswrk = $conn->Execute($sSqlWrk);
		$arwrk = ($rswrk) ? $rswrk->GetRows() : array();
		if ($rswrk) $rswrk->Close();
		array_unshift($arwrk, array("", "Please Select"));
		$osj2Dcategories->parent_id->EditValue = $arwrk;

		// category_name
		$osj2Dcategories->category_name->EditCustomAttributes = "";
		$osj2Dcategories->category_name->EditValue = ew_HtmlEncode($osj2Dcategories->category_name->CurrentValue);
	} elseif ($osj2Dcategories->RowType == EW_ROWTYPE_EDIT) { // Edit row
	} elseif ($osj2Dcategories->RowType == EW_ROWTYPE_SEARCH) { // Search row
	}

	// Call Row Rendered event
	$osj2Dcategories->Row_Rendered();
}
?>
<?php

// Add record
function AddRow() {
	global $conn, $Security, $osj2Dcategories;

	// Check for duplicate key
	$bCheckKey = TRUE;
	$sFilter = $osj2Dcategories->SqlKeyFilter();
	if (trim(strval($osj2Dcategories->category_id->CurrentValue)) == "") {
		$bCheckKey = FALSE;
	} else {
		$sFilter = str_replace("@category_id@", ew_AdjustSql($osj2Dcategories->category_id->CurrentValue), $sFilter); // Replace key value
	}
	if (!is_numeric($osj2Dcategories->category_id->CurrentValue)) {
		$bCheckKey = FALSE;
	}
	if ($bCheckKey) {
		$rsChk = $osj2Dcategories->LoadRs($sFilter);
		if ($rsChk && !$rsChk->EOF) {
			$_SESSION[EW_SESSION_MESSAGE] = "Duplicate value for primary key";
			$rsChk->Close();
			return FALSE;
		}
	}
	$rsnew = array();

	// Field category_id
	// Field parent_id

	$osj2Dcategories->parent_id->SetDbValueDef($osj2Dcategories->parent_id->CurrentValue, 0);
	$rsnew['parent_id'] =& $osj2Dcategories->parent_id->DbValue;

	// Field category_name
	$osj2Dcategories->category_name->SetDbValueDef($osj2Dcategories->category_name->CurrentValue, "");
	$rsnew['category_name'] =& $osj2Dcategories->category_name->DbValue;

	// Call Row Inserting event
	$bInsertRow = $osj2Dcategories->Row_Inserting($rsnew);
	if ($bInsertRow) {
		$conn->raiseErrorFn = 'ew_ErrorFn';
		$AddRow = $conn->Execute($osj2Dcategories->InsertSQL($rsnew));
		$conn->raiseErrorFn = '';
	} else {
		if ($osj2Dcategories->CancelMessage <> "") {
			$_SESSION[EW_SESSION_MESSAGE] = $osj2Dcategories->CancelMessage;
			$osj2Dcategories->CancelMessage = "";
		} else {
			$_SESSION[EW_SESSION_MESSAGE] = "Insert cancelled";
		}
		$AddRow = FALSE;
	}
	if ($AddRow) {
		$osj2Dcategories->category_id->setDbValue($conn->Insert_ID());
		$rsnew['category_id'] =& $osj2Dcategories->category_id->DbValue;

		// Call Row Inserted event
		$osj2Dcategories->Row_Inserted($rsnew);
		WriteAuditTrailOnAdd($rsnew);
	}
	return $AddRow;
}
?>
<?php

// Write Audit Trail start/end for grid update
function WriteAuditTrailDummy($typ) {
	$table = 'osj-categories';

	// Write Audit Trail
	$filePfx = "log";
	$curDate = date("Y/m/d");
	$curTime = date("H:i:s");
	$id = ew_ScriptName();
	$user = CurrentUserID();
	$action = $typ;
	ew_WriteAuditTrail($filePfx, $curDate, $curTime, $id, $user, $action, $table, "", "", "", "");
}
?>
<?php

// Write Audit Trail (add page)
function WriteAuditTrailOnAdd(&$rs) {
	global $osj2Dcategories;
	$table = 'osj-categories';

	// Get key value
	$key = "";
	if ($key <> "") $key .= EW_COMPOSITE_KEY_SEPARATOR;
	$key .= $rs['category_id'];

	// Write Audit Trail
	$filePfx = "log";
	$curDate = date("Y/m/d");
	$curTime = date("H:i:s");
	$id = ew_ScriptName();
	$user = CurrentUserID();
	$action = "A";
	$oldvalue = "";
	foreach (array_keys($rs) as $fldname) {
		if ($osj2Dcategories->fields[$fldname]->FldDataType <> EW_DATATYPE_BLOB) { // Ignore Blob Field
			$newvalue = ($osj2Dcategories->fields[$fldname]->FldDataType == EW_DATATYPE_MEMO) ? "<MEMO>" : $rs[$fldname]; // Memo Field
			ew_WriteAuditTrail($filePfx, $curDate, $curTime, $id, $user, $action, $table, $fldname, $key, $oldvalue, $newvalue);
		}
	}
}
?>
<?php

// Page Load event
function Page_Load() {

	//echo "Page Load";
}

// Page Unload event
function Page_Unload() {

	//echo "Page Unload";
}
?>