<?php
ob_start();
/* $Revision: 1.73 $ */
$PageSecurity = 11;

include('includes/session.inc');
$title = _('Item Maintenance');
include('includes/header.inc');
include('includes/function_lib.php');
include('includes/SQL_CommonFunctions.inc');
$date=date('d/m/Y');
?>

<script type="text/javascript">
function MinVal()
	{
		var x=document.getElementById("minlevel").value;
		if(x<3){alert("Min Value Must Be Greater than or Equal to Three.");}
	}

function MaxVal()
	{
		var x=document.getElementById("maxlevel").value;
		if(x>10){alert("Max Value Must Be Less than or Equal to Ten.");}
	}
</script>
<script type="text/javascript" src="js/dynamicRow.js"></script>
<?php
 /*If this form is called with the StockID then it is assumed that the stock item is to be modified */

if (isset($_GET['StockID']))
{
	$StockID =trim(strtoupper($_GET['StockID'])); 
} 
elseif (isset($_POST['StockID']))
{
	$StockID =trim(strtoupper($_POST['StockID']));
	
} else 
{
	$StockID = '';
}

if (isset($StockID))
 {
	 $sql = "SELECT COUNT(stockid) FROM stockmaster WHERE stockid='".$StockID."'";
	$result = DB_query($sql,$db);
	$myrow = DB_fetch_row($result);
	if ($myrow[0]==0) {
		$New=1;
	}
}

?>

<?php
echo '<a href="' . $rootpath . '/SelectProduct.php?' . SID . '">' . _('Back to Items') . '</a><br>' . "\n";

if($_REQUEST['action']=='insert'){
echo "<div class='success'>Record Inserted Successfully</div>";
}
if (isset($_FILES['ItemPicture']) AND $_FILES['ItemPicture']['name'] !='') {

	$result    = $_FILES['ItemPicture']['error'];
 	$UploadTheFile = 'Yes'; //Assume all is well to start off with
	$filename = $_SESSION['part_pics_dir'] . '/' . $StockID . '.jpg';

	 //But check for the worst
	if (strtoupper(substr(trim($_FILES['ItemPicture']['name']),strlen($_FILES['ItemPicture']['name'])-3))!='JPG'){
		prnMsg(_('Only jpg files are supported - a file extension of .jpg is expected'),'warn');
		$UploadTheFile ='No';
	} elseif ( $_FILES['ItemPicture']['size'] > ($_SESSION['MaxImageSize']*1024)) { //File Size Check
		prnMsg(_('The file size is over the maximum allowed. The maximum size allowed in KB is') . ' ' . $_SESSION['MaxImageSize'],'warn');
		$UploadTheFile ='No';
	} elseif ( $_FILES['ItemPicture']['type'] == "text/plain" ) {  //File Type Check
		prnMsg( _('Only graphics files can be uploaded'),'warn');
         	$UploadTheFile ='No';
	} elseif (file_exists($filename)){
		prnMsg(_('Attempting to overwrite an existing item image'),'warn');
		$result = unlink($filename);
		if (!$result){
			prnMsg(_('The existing image could not be removed'),'error');
			$UploadTheFile ='No';
		}
	}

	if ($UploadTheFile=='Yes'){
		$result  =  move_uploaded_file($_FILES['ItemPicture']['tmp_name'], $filename);
		$message = ($result)?_('File url') ."<a href='". $filename ."'>" .  $filename . '</a>' : _('Something is wrong with uploading a file');
	}
 /* EOR Add Image upload for New Item  - by Ori */
}

if (isset($Errors))
 {
	unset($Errors);
}
$Errors = array();
$InputError = 0;

if(isset($_POST['UpdateStockItem']))
{ 
     $countval= count($_REQUEST['user_shipping']); 
 	
	$data['maincategoryid']=$_REQUEST['CategoryID'];  
	$data['categoryid']=$_REQUEST['itemcodeval']; 
	$data['shade_name'] = $_POST['shade_name'];
	$data['item_serial_code'] = $_POST['item_serial_code'];
	$data['client_code'] = $_POST['client_code'];
	$data['stockid   '] =$_REQUEST['StockID'];
	$data['description'] =$_REQUEST['description'];
	$data['stockid   '] =$_REQUEST['StockID'];
	$data['description'] =$_REQUEST['description'];
	$data['longdescription'] =$_REQUEST['longdescription'];
	 $data['ItemPDF'] =$_REQUEST['ItemPDF'];
	$data['materialtype'] =$_REQUEST['materialtype'];
	$data['size'] =$_REQUEST['size'];
	 $data['IapF'] =$_REQUEST['IapF'];
	$data['abcclass'] =$_REQUEST['abcclass'];
	$data['minlevel'] =$_REQUEST['minlevel'];
	$data['maxlevel'] =$_REQUEST['maxlevel'];
	$data['eoq'] =$_REQUEST['eoq'];
	$data['postdelqcreg'] =$_REQUEST['postdelqcreg'];
	$data['qctestdays'] =$_REQUEST['qctestdays'];
	$data['qctesthours'] =$_REQUEST['qctesthours'];
 	$data['predeliveryqc'] =$_REQUEST['predeliveryqc'];
	$data['volume'] =$_REQUEST['volume'];
	$data['kgs'] =$_REQUEST['kgs'];
	$data['units'] =$_REQUEST['units'];
	$data['mbflag'] =$_REQUEST['mbflag'];
	$data['discontinued'] =$_REQUEST['discontinued'];
	$data['decimalplaces'] =$_REQUEST['decimalplaces'];
	$data['discountcategory'] =$_REQUEST['discountcategory'];
	$data['taxcatid'] =$_REQUEST['taxcatid'];
	$data['discontinued'] =$_REQUEST['discontinued'];
	$data['pansize'] =$_REQUEST['pansize'];
	$data['shrinkfactor'] =$_REQUEST['shrinkfactor'];
	//$data['qc'] =$_REQUEST['qc'];
	$data['length'] =$_REQUEST['length'];
	$data['breadth'] =$_REQUEST['breadth'];
	$data['shape'] =$_REQUEST['shape'];
	$data['make'] =$_REQUEST['make'];
	$data['color'] =$_REQUEST['color'];
	$data['grade'] =$_REQUEST['grade'];
	//$data['countval'] =$_REQUEST['countval'];
     $data['reguestby'] =$_REQUEST['reguestby'];
 	 $data['reguestdate'] =FormatDateForSQL($_REQUEST['reguestdate']);
	$data['approvedby'] =$_REQUEST['approvedby'];
	$data['approveddate'] =FormatDateForSQL($_REQUEST['approveddate']);
	
	$cond="stockid ='".$_REQUEST['StockID']."'";	
 $sql =$s->EditRecord('stockmaster', $data, $cond);
 
 				$ErrMsg = _('The stock item could not be updated because');
				$DbgMsg = _('The SQL that was used to update the stock item and failed was');
				$result = DB_query($sql,$db,$ErrMsg,$DbgMsg);
				//delete any properties for the item no longer relevant with the change of category
				$delete_query = "DELETE FROM item_specification WHERE proc_id ='" . $StockID . "'"; 
				$Deleteresult = DB_query($delete_query, $db);
			
				   
				    	 $sql="INSERT INTO item_specification(proc_id, manufacture, color, grade)
								  VALUE('" . $_POST['StockID'] . "',
								  '" . $_POST['make'] . "',
								  '" . $_POST['color'] . "',
								  '" . $_POST['grade'] . "')";
						$ErrMsg =  _('The item specification could not be added because');
						$DbgMsg = _('The SQL that was used to add the item failed was');		  
						$result = DB_query($sql,$db,$ErrMsg,$DbgMsg);		  
				//now insert any item properties
				for ($i=0;$i<$_POST['PropertyCounter'];$i++)
				{

					if ($_POST['PropType' . $i] ==2){
						if ($_POST['PropValue' . $i]=='on'){
							$_POST['PropValue' . $i]=1;
						} else {
							$_POST['PropValue' . $i]=0;
						}
					}
					   $result = DB_query("INSERT INTO stockitemproperties (stockid,
																			stkcatpropid,
																			value)
														VALUES ('" . $StockID . "',
																" . $_POST['PropID' . $i] . ",
																'" . $_POST['PropValue' . $i] . "')",
										$db);
				} //end of loop around properties defined for the category
				prnMsg( _('Stock Item') . ' ' . $StockID . ' ' . _('has been updated'), 'success');

		}
if (isset($_POST['submit']))
{

	//initialise no input errors assumed initially before we test

	/* actions to take once the user has clicked the submit button
	ie the page has called itself with some user input */

	//first off validate inputs sensible
	$i=1;


	if (!isset($_POST['description']) or strlen($_POST['description']) > 50 OR strlen($_POST['description'])==0) {
		$InputError = 1;
		prnMsg (_('The stock item description must be entered and be fifty characters or less long') . '. ' . _('It cannot be a zero length string either') . ' - ' . _('a description is required'),'error');
		$Errors[$i] = 'description';
		$i++;
	}
	 
	if (strlen($StockID) ==0) 
	{
		$InputError = 1;
		prnMsg (_('The Stock Item code cannot be empty'),'error');
		$Errors[$i] = 'StockID';
		$i++;
	}
	if (strstr($StockID,' ') OR strstr($StockID,"'") OR strstr($StockID,'+') OR strstr($StockID,"\\") OR strstr($StockID,"\"") OR strstr($StockID,'&') OR strstr($StockID,'.') OR strstr($StockID,'"')) {
		$InputError = 1;
		prnMsg(_('The stock item code cannot contain any of the following characters') . " - ' & + \" \\ " . _('or a space'),'error');
		$Errors[$i] = 'StockID';
		$i++;
		$StockID='';
	}
	if (strlen($_POST['units']) >20) {
		$InputError = 1;
		prnMsg(_('The unit of measure must be 20 characters or less long'),'error');
		$Errors[$i] = 'units';
		$i++;
	}
	if (strlen($_POST['barCode']) >20) {
		$InputError = 1;
		prnMsg(_('The barCode must be 20 characters or less long'),'error');
		$Errors[$i] = 'barCode';
		$i++;
	}
	if (!is_numeric($_POST['volume'])) {
		$InputError = 1;
		prnMsg (_('The volume of the packaged item in cubic metres must be numeric') ,'error');
		$Errors[$i] = 'volume';
		$i++;
	}
	if ($_POST['volume'] <0) {
		$InputError = 1;
		prnMsg(_('The volume of the packaged item must be a positive number'),'error');
		$Errors[$i] = 'volume';
		$i++;
	}
	if (!is_numeric($_POST['kgs'])) {
		$InputError = 1;
		prnMsg(_('The weight of the packaged item in kgs must be numeric'),'error');
		$Errors[$i] = 'kgs';
		$i++;
	}
	if ($_POST['kgs']<0) {
		$InputError = 1;
		prnMsg(_('The weight of the packaged item must be a positive number'),'error');
		$Errors[$i] = 'kgs';
		$i++;
	}
	if (!is_numeric($_POST['eoq'])) {
		$InputError = 1;
		prnMsg(_('The economic order quantity must be numeric'),'error');
		$Errors[$i] = 'eoq';
		$i++;
	}
	if ($_POST['eoq'] <0) {
		$InputError = 1;
		prnMsg (_('The economic order quantity must be a positive number'),'error');
		$Errors[$i] = 'eoq';
		$i++;
	}
	if ($_POST['Controlled']==0 AND $_POST['Serialised']==1){
		$InputError = 1;
		prnMsg(_('The item can only be serialised if there is lot control enabled already') . '. ' . _('Batch control') . ' - ' . _('with any number of items in a lot/bundle/roll is enabled when controlled is enabled') . '. ' . _('Serialised control requires that only one item is in the batch') . '. ' . _('For serialised control') . ', ' . _('both controlled and serialised must be enabled'),'error');
		$Errors[$i] = 'Serialised';
		$i++;
	}
	if ($_POST['NextSerialNo']!=0 AND $_POST['Serialised']==0){
		$InputError = 1;
		prnMsg(_('The item can only have automatically generated serial numbers if it is a serialised item'),'error');
		$Errors[$i] = 'NextSerialNo';
		$i++;
	}
	if ($_POST['NextSerialNo']!=0 AND $_POST['mbflag']!='M'){
		$InputError = 1;
		prnMsg(_('The item can only have automatically generated serial numbers if it is a manufactured item'),'error');
		$Errors[$i] = 'NextSerialNo';
		$i++;
	}
	if (($_POST['mbflag']=='A' OR $_POST['mbflag']=='K' OR $_POST['mbflag']=='D' OR $_POST['mbflag']=='G') AND $_POST['Controlled']==1){
		$InputError = 1;
		prnMsg(_('Assembly/Kitset/Phantom/Service/Labour items cannot also be controlled items') . '. ' . _('Assemblies/Dummies/Phantom and Kitsets are not physical items and batch/serial control is therefore not appropriate'),'error');
		$Errors[$i] = 'Controlled';
		$i++;
	}
	if (trim($_POST['CategoryID'])=='')
	{
		$InputError = 1;
		prnMsg(_('There are no inventory categories defined. All inventory items must belong to a valid inventory category,'),'error');
		$Errors[$i] = 'CategoryID';
		$i++;
	}
	if (!is_numeric($_POST['pansize']))
	 {
		$InputError = 1;
		prnMsg(_('pansize quantity must be numeric'),'error');
		$Errors[$i] = 'pansize';
		$i++;
	}
	if (!is_numeric($_POST['shrinkfactor'])) {
		$InputError = 1;
		prnMsg(_('Shrinkage factor quantity must be numeric'),'error');
		$Errors[$i] = 'shrinkfactor';
		$i++;
	}
	if ($InputError !=1)
	{
		if ($_POST['Serialised']==1){ /*Not appropriate to have several dp on serial items */
			$_POST['decimalplaces']=0;
		}
		if (!isset($_POST['New']) and !isset($New)) { /*so its an existing one */

			/*first check on the changes being made we must disallow:
			- changes from manufactured or purchased to Service, Assembly or Kitset if there is stock-changes from manufactured, kitset or assembly where a BOM exists
			*/
			$sql = "SELECT mbflag,
							controlled,
							serialised
					FROM stockmaster WHERE stockid = '".$StockID."'";
			$mbflagResult = DB_query($sql,$db);
			$myrow = DB_fetch_row($mbflagResult);
			$Oldmbflag = $myrow[0];
			$OldControlled = $myrow[1];
			$OldSerialised = $myrow[2];

			$sql = "SELECT SUM(locstock.quantity) FROM locstock WHERE stockid='".$StockID."'";
			$result = DB_query($sql,$db);
			$stkqtychk = DB_fetch_row($result);

			if ($Oldmbflag != $_POST['mbflag']){
				if (($Oldmbflag == 'M' OR $Oldmbflag=='B') AND ($_POST['mbflag']=='A' OR $_POST['mbflag']=='K' OR $_POST['mbflag']=='D' OR $_POST['mbflag']=='G')){ /*then need to check that there is no stock holding first */
					/* stock holding OK for phantom (ghost) items */
					if ($stkqtychk[0]!=0 AND $Oldmbflag!='G'){
						$InputError=1;
						prnMsg( _('The make or buy flag cannot be changed from') . ' ' . $Oldmbflag . ' ' . _('to') . ' ' . $_POST['mbflag'] . ' ' . _('where there is a quantity of stock on hand at any location') . '. ' . _('Currently there are') . ' ' . $stkqtychk[0] .  ' ' . _('on hand') , 'errror');
					}
					/* don't allow controlled/serialized  */
					if ($_POST['Controlled']==1){
						$InputError=1;
						prnMsg( _('The make or buy flag cannot be changed from') . ' ' . $Oldmbflag . ' ' . _('to') . ' ' . $_POST['mbflag'] . ' ' . _('where the item is to be lot controlled') . '. ' . _('Kitset, phantom, dummy and assembly items cannot be lot controlled'), 'error');
					}
				}
				/*now check that if the item is being changed to a kitset, there are no items on sales orders or purchase orders*/
				if ($_POST['mbflag']=='K') {
					$sql = "SELECT quantity-qtyinvoiced
						FROM salesorderdetails
						WHERE stkcode = '$StockID'
						AND completed=0";

					$result = DB_query($sql,$db);
					$ChkSalesOrds = DB_fetch_row($result);
					if ($ChkSalesOrds[0]!=0){
						$InputError = 1;
						prnMsg( _('The make or buy flag cannot be changed to a kitset where there is a quantity outstanding to be delivered on sales orders') . '. ' . _('Currently there are') .' ' . $ChkSalesOrds[0] . ' '. _('outstanding'), 'error');
					}
				}
				/*now check that if it is to be a kitset or assembly or dummy there is no quantity on purchase orders outstanding*/
				if ($_POST['mbflag']=='K' OR $_POST['mbflag']=='A' OR $_POST['mbflag']=='D') {

					$sql = "SELECT quantityord-quantityrecd
						FROM purchorderdetails
						WHERE itemcode = '".$StockID."'
						AND completed=0";

					$result = DB_query($sql,$db);
					$ChkPurchOrds = DB_fetch_row($result);
					if ($ChkPurchOrds[0]!=0){
						$InputError = 1;
						prnMsg( _('The make or buy flag cannot be changed to'). ' ' . $_POST['mbflag'] . ' '. _('where there is a quantity outstanding to be received on purchase orders') . '. ' . _('Currently there are'). ' ' . $ChkPurchOrds[0] . ' '. _('yet to be received'). 'error');
					}
				}

				/*now check that if it was a Manufactured, Kitset, Phantom or Assembly and is being changed to a purchased or dummy - that no BOM exists */
				if (($Oldmbflag=='M' OR $Oldmbflag =='K' OR $Oldmbflag=='A' OR $Oldmbflag=='G') AND ($_POST['mbflag']=='B' OR $_POST['mbflag']=='D')) {
					$sql = "SELECT COUNT(*) FROM bom WHERE parent = '".$StockID."'";
					$result = DB_query($sql,$db);
					$ChkBOM = DB_fetch_row($result);
					if ($ChkBOM[0]!=0){
						$InputError = 1;
						prnMsg( _('The make or buy flag cannot be changed from manufactured, kitset or assembly to'). ' ' . $_POST['mbflag'] . ' '. _('where there is a bill of material set up for the item') . '. ' . _('Bills of material are not appropriate for purchased or dummy items'), 'error');
					}
				}

				/*now check that if it was Manufac, Phantom or Purchased and is being changed to assembly or kitset, it is not a component on an existing BOM */
				if (($Oldmbflag=='M' OR $Oldmbflag =='B' OR $Oldmbflag=='D' OR $Oldmbflag=='G') AND ($_POST['mbflag']=='A' OR $_POST['mbflag']=='K')) {
					$sql = "SELECT COUNT(*) FROM bom WHERE component = '$StockID'";
					$result = DB_query($sql,$db);
					$ChkBOM = DB_fetch_row($result);
					if ($ChkBOM[0]!=0){
						$InputError = 1;
						prnMsg( _('The make or buy flag cannot be changed from manufactured, purchased or dummy to a kitset or assembly where the item is a component in a bill of material') . '. ' . _('Assembly and kitset items are not appropriate as components in a bill of materials'), 'error');
					}
				}
			}

			/* Do some checks for changes in the Serial & Controlled setups */
			if ($OldControlled != $_POST['Controlled'] AND $stkqtychk[0]!=0){
				$InputError=1;
				prnMsg( _('You can not change a Non-Controlled Item to Controlled (or back from Controlled to non-controlled when there is currently stock on hand for the item') , 'error');

			}
			if ($OldSerialised != $_POST['Serialised'] AND $stkqtychk[0]!=0){
				$InputError=1;
				prnMsg( _('You can not change a Serialised Item to Non-Serialised (or vice-versa) when there is a quantity on hand for the item') , 'error');
			}
			
           if ($InputError == 0)
			{
				         $sql = "UPDATE stockmaster
						SET maincategoryid='" . $_POST['CategoryID'] . "',
						stockid='" . $_POST['StockID'] . "',
						categoryid='" . $_POST['itemcode'] . "',
						longdescription='" . $_POST['longdescription'] . "',
						description='" . $_POST['description'] . "',
						discontinued=" . $_POST['discontinued'] . ",
						controlled=" . $_POST['Controlled'] . ",
						serialised=" . $_POST['Serialised'].",
						perishable=" . $_POST['Perishable'].",
						categoryid='" . $_POST['CategoryID'] . "',
						units='" . $_POST['units'] . "',
						mbflag='" . $_POST['mbflag'] . "',
						eoq=" . $_POST['eoq'] . ",
						volume=" . $_POST['volume'] . ",
						kgs=" . $_POST['kgs'] . ",
						barCode='" . $_POST['barCode'] . "',
						discountcategory='" . $_POST['discountcategory'] . "',
						taxcatid=" . $_POST['taxcatid'] . ",
						decimalplaces=" . $_POST['decimalplaces'] . ",
						appendfile='" . $_POST['ItemPDF'] . "',
						shrinkfactor=" . $_POST['shrinkfactor'] . ",
						pansize=" . $_POST['pansize'] . ",
						nextserialno=" . $_POST['NextSerialNo'] . ",
						QC=" . $_POST['qc'] . ",
						reguestdate='" . FormatDateForSQL($_POST['reguestdate']) . "',
						approveddate='" . FormatDateForSQL($_POST['approveddate']) . "',
						make='".$_POST['make']."',
						color='".$_POST['color']."',
						grade='".$_POST['grade']."'
						WHERE stockid='$StockID'";

				//echo $sql;die;
				$ErrMsg = _('The stock item could not be updated because');
				$DbgMsg = _('The SQL that was used to update the stock item and failed was');
				//$result = DB_query($sql,$db,$ErrMsg,$DbgMsg);

				//delete any properties for the item no longer relevant with the change of category
				$result = DB_query("DELETE FROM stockitemproperties
										WHERE stockid ='" . $StockID . "'",
									$db);

				//now insert any item properties
				for ($i=0;$i<$_POST['PropertyCounter'];$i++)
				{

					if ($_POST['PropType' . $i] ==2){
						if ($_POST['PropValue' . $i]=='on'){
							$_POST['PropValue' . $i]=1;
						} else {
							$_POST['PropValue' . $i]=0;
						}
					}
					$result = DB_query("INSERT INTO stockitemproperties (stockid,
																			stkcatpropid,
																			value)
														VALUES ('" . $StockID . "',
																" . $_POST['PropID' . $i] . ",
																'" . $_POST['PropValue' . $i] . "')",
										$db);
				} //end of loop around properties defined for the category
				prnMsg( _('Stock Item') . ' ' . $StockID . ' ' . _('has been updated'), 'success');

			 }
			
		} else { //it is a NEW part
			//but lets be really sure here
			
			
			$result = DB_query("SELECT stockid FROM stockmaster WHERE stockid='" . $StockID ."'",$db);
			if (DB_num_rows($result)==1)
			{
			
			
			
				prnMsg(_('The stock code entered is actually already in the database - duplicate stock codes are prohibited by the system. Try choosing an alternative stock code'),'error');
				//exit;
			} 
			else
			 {  
			 
			 
			 
			$_POST['itemcode']= $_POST['itemcodeval'];
//echo "<br>*************************stockmaster*************************************</br>";	

	$data_insert['stockid   '] =$_REQUEST['StockID'];
	$data_insert['maincategoryid'] = $_POST['CategoryID'];
	$data_insert['categoryid'] = $_POST['itemcode'];
	$data_insert['shade_name'] = $_POST['shade_name'];
	$data_insert['item_serial_code'] = $_POST['item_serial_code'];
	$data_insert['client_code'] = $_POST['client_code'];
	$data_insert['description'] =$_REQUEST['description'];
	$data['ItemPDF'] =$_REQUEST['ItemPDF'];
	$data_insert['materialtype'] =$_REQUEST['materialtype'];
	$data_insert['size'] =$_REQUEST['size'];
	$data['IapF'] =$_REQUEST['IapF'];
	$data_insert['abcclass'] =$_REQUEST['abcclass'];
	$data_insert['minlevel'] =$_REQUEST['minlevel'];
	$data_insert['maxlevel'] =$_REQUEST['maxlevel'];
	$data_insert['eoq'] =$_REQUEST['eoq'];
	$data_insert['postdelqcreg'] =$_REQUEST['postdelqcreg'];
	$data_insert['qctestdays'] =$_REQUEST['qctestdays'];
	$data_insert['qctesthours'] =$_REQUEST['qctesthours'];
	$data_insert['predeliveryqc'] =$_REQUEST['predeliveryqc'];
	$data_insert['volume'] =$_REQUEST['volume'];
	$data_insert['kgs'] =$_REQUEST['kgs'];
	$data_insert['units'] =$_REQUEST['units'];
	$data_insert['mbflag'] =$_REQUEST['mbflag'];
	$data_insert['discontinued'] =$_REQUEST['discontinued'];
	$data_insert['decimalplaces'] =$_REQUEST['decimalplaces'];
	$data_insert['discountcategory'] =$_REQUEST['discountcategory'];
	$data_insert['taxcatid'] =$_REQUEST['taxcatid'];
	$data_insert['discontinued'] =$_REQUEST['discontinued'];
	$data_insert['pansize'] =$_REQUEST['pansize'];
	$data_insert['shrinkfactor'] =$_REQUEST['shrinkfactor'];
	//$data_insert['qc'] =$_REQUEST['qc'];
	$data_insert['length'] =$_REQUEST['length'];
	$data_insert['breadth'] =$_REQUEST['breadth'];
	$data_insert['shape'] =$_REQUEST['shape'];
	$data_insert['make'] =$_REQUEST['make'];
	$data_insert['color'] =$_REQUEST['color'];
	$data_insert['grade'] =$_REQUEST['grade'];
	//$data_insert['countval'] =$_REQUEST['countval'];
	$data_insert['reguestby'] =$_REQUEST['reguestby'];
 	 $data_insert['reguestdate'] =FormatDateForSQL($_REQUEST['reguestdate']);
	$data_insert['approvedby'] =$_REQUEST['approvedby'];
	$data_insert['approveddate'] =FormatDateForSQL($_REQUEST['approveddate']);
  	$sql=	$s->insertRecord('stockmaster', $data_insert);

 				$ErrMsg =  _('The item could not be added because');
				$DbgMsg = _('The SQL that was used to add the item failed was');
				$result = DB_query($sql,$db, $ErrMsg, $DbgMsg);
				
				/*$sql="SELECT stockid FROM stockmaster ORDER BY stockid DESC LIMIT 0,5";	
				$result = DB_query($sql,$db);	
				$myrow = DB_fetch_row($result);*/
				
				 // for($i=0;$i<$countval;$i++)
					// {
					//echo "<br>*************************item_specification*************************************</br>";			 

						    $sql="INSERT INTO item_specification(proc_id, manufacture, color, grade)
								  VALUE('" . $_POST['StockID'] . "',
								  '" . $_POST['make'] . "',
								  '" . $_POST['color'] . "',
								  '" . $_POST['grade'] . "')";
						$ErrMsg =  _('The item specification could not be added because');
						$DbgMsg = _('The SQL that was used to add the item failed was');		  
						$result = DB_query($sql,$db,$ErrMsg,$DbgMsg);		  
				//  }
				
				if (DB_error_no($db) ==0) {
					//echo "<br>*************************lockstock*************************************</br>";			 


/////////to check locstock table//////2011-09-15/////
 $sql_lock = "select * from locstock where stockid = '" . $StockID ."' ";
$result_loc = DB_query($sql_lock,$db);
if($my_sql_row = DB_num_rows($result_loc) == '0'){

			 $sql = "INSERT INTO locstock (loccode,	stockid) SELECT locations.loccode, '" . $StockID . "' FROM locations";

					$ErrMsg =  _('The locations for the item') . ' ' . $StockID .  ' ' . _('could not be added because');
					$DbgMsg = _('NB Locations records can be added by opening the utility page') . ' <i>Z_makeStockLocns.php</i> ' . _('The SQL that was used to add the location records that failed was');
					$InsResult = DB_query($sql,$db,$ErrMsg,$DbgMsg);
exit;
					if (DB_error_no($db) ==0) 
					{
						prnMsg( _('New Item') .' ' . "<a href='SelectProduct.php?StockID=$StockID'>$StockID</a>" . ' '. _('has been added to the database'),'success');					
						
						unset($_POST['longdescription']);
						unset($_POST['description']);
			// Leave Category ID set for ease of batch entry
					    unset($_POST['CategoryID']);
						unset($_POST['units']);
						unset($_POST['mbflag']);
						unset($_POST['discontinued']);
						unset($_POST['Controlled']);
						unset($_POST['Serialised']);
						unset($_POST['Perishable']);
						unset($_POST['volume']);
						unset($_POST['kgs']);
						unset($_POST['barCode']);
						unset($_POST['ReorderLevel']);
						unset($_POST['discountcategory']);
						unset($_POST['decimalplaces']);
						unset($_POST['ItemPDF']);
						unset($_POST['shrinkfactor']);
						unset($_POST['pansize']);
						unset($_POST['reguestdate']);
						unset($_POST['approveddate']);
						unset($StockID);
					}//ALL WORKED SO RESET THE FORM VARIABLES
}					
				}//THE INSERT OF THE NEW CODE WORKED SO BANG IN THE STOCK LOCATION RECORDS TOO
			
			
			$s->pageLocation('Stocks.php?action=insert');
			
			}//END CHECK FOR ALREADY EXISTING ITEM OF THE SAME CODE
		}

	} else {
		echo '<br>'. "\n";
		//prnMsg( _('Validation failed, no updates or deletes took place'), 'error');
	}
} 
elseif(isset($_POST['delete']) AND strlen($_POST['delete']) >1 )
{
//the button to delete a selected record was clicked instead of the submit button

	$CancelDelete = 0;

// PREVENT DELETES IF DEPENDENT RECORDS IN 'StockMoves'

	$sql= "SELECT COUNT(*) FROM stockmoves WHERE stockid='$StockID'";
	$result = DB_query($sql,$db);
	$myrow = DB_fetch_row($result);
	if ($myrow[0]>0) {
		$CancelDelete = 1;
		prnMsg( _('Cannot delete this stock item because there are stock movements that refer to this item'),'warn');
		echo '<br>' . _('There are') . ' ' . $myrow[0] . ' ' . _('stock movements that refer to this item');

	} else {
		$sql= "SELECT COUNT(*) FROM bom WHERE component='$StockID'";
		$result = DB_query($sql,$db);
		$myrow = DB_fetch_row($result);
		if ($myrow[0]>0) {
			$CancelDelete = 1;
			prnMsg( _('Cannot delete this item record because there are bills of material that require this part as a component'),'warn');
			echo '<br>' . _('There are') . ' ' . $myrow[0] . ' ' . _('bills of material that require this part as a component');
		} else {
			$sql= "SELECT COUNT(*) FROM salesorderdetails WHERE stkcode='$StockID'";
			$result = DB_query($sql,$db);
			$myrow = DB_fetch_row($result);
			if ($myrow[0]>0) {
				$CancelDelete = 1;
				prnMsg( _('Cannot delete this item record because there are existing sales orders for this part'),'warn');
				echo '<br>' . _('There are') . ' ' . $myrow[0] . ' ' . _('sales order items against this part');
			} else {
				$sql= "SELECT COUNT(*) FROM salesanalysis WHERE stockid='$StockID'";
				$result = DB_query($sql,$db);
				$myrow = DB_fetch_row($result);
				if ($myrow[0]>0) {
					$CancelDelete = 1;
					prnMsg(_('Cannot delete this item because sales analysis records exist for it'),'warn');
					echo '<br>' . _('There are') . ' ' . $myrow[0] . ' ' . _('sales analysis records against this part');
				} else {
					$sql= "SELECT COUNT(*) FROM purchorderdetails WHERE itemcode='$StockID'";
					$result = DB_query($sql,$db);
					$myrow = DB_fetch_row($result);
					if ($myrow[0]>0) {
						$CancelDelete = 1;
						prnMsg(_('Cannot delete this item because there are existing purchase order items for it'),'warn');
						echo '<br>' . _('There are') . ' ' . $myrow[0] . ' ' . _('purchase order item record relating to this part');
					} else {
						$sql = "SELECT SUM(quantity) AS qoh FROM locstock WHERE stockid='$StockID'";
						$result = DB_query($sql,$db);
						$myrow = DB_fetch_row($result);
						if ($myrow[0]!=0) {
							$CancelDelete = 1;
							prnMsg( _('Cannot delete this item because there is currently some stock on hand'),'warn');
							echo '<br>' . _('There are') . ' ' . $myrow[0] . ' ' . _('on hand for this part');
						}
					}
				}
			}
		}

	}
	if ($CancelDelete==0) {
		$result = DB_Txn_Begin($db);

			/*Deletes LocStock records*/
			$sql ="DELETE FROM locstock WHERE stockid='$StockID'";
			$result=DB_query($sql,$db,_('Could not delete the location stock records because'),'',true);
			/*Deletes Price records*/
			$sql ="DELETE FROM prices WHERE stockid='$StockID'";
			$result=DB_query($sql,$db,_('Could not delete the prices for this stock record because'),'',true);
			/*and cascade deletes in PurchData */
			$sql ="DELETE FROM purchdata WHERE stockid='$StockID'";
			$result=DB_query($sql,$db,_('Could not delete the purchasing data because'),'',true);
			/*and cascade delete the bill of material if any */
			$sql = "DELETE FROM bom WHERE parent='$StockID'";
			$result=DB_query($sql,$db,_('Could not delete the bill of material because'),'',true);
			$sql="DELETE FROM stockmaster WHERE stockid='$StockID'";
			$result=DB_query($sql,$db, _('Could not delete the item record'),'',true);
            $result = DB_Txn_Commit($db);

		prnMsg(_('Deleted the stock master record for') . ' ' . $StockID . '....' .
		'<br>. . ' . _('and all the location stock records set up for the part') .
		'<br>. . .' . _('and any bill of material that may have been set up for the part') .
		'<br> . . . .' . _('and any purchasing data that may have been set up for the part') .
		'<br> . . . . .' . _('and any prices that may have been set up for the part'),'success');
		unset($_POST['longdescription']);
		unset($_POST['description']);
		unset($_POST['eoq']);
		unset($_POST['CategoryID']);
		unset($_POST['units']);
		unset($_POST['mbflag']);
		unset($_POST['discontinued']);
		unset($_POST['Controlled']);
		unset($_POST['Serialised']);
		unset($_POST['Perishable']);
		unset($_POST['volume']);
		unset($_POST['kgs']);
		unset($_POST['barCode']);
		unset($_POST['ReorderLevel']);
		unset($_POST['discountcategory']);
		unset($_POST['taxcatid']);
		unset($_POST['decimalplaces']);
		unset($_POST['ItemPDF']);
		unset($StockID);
		unset($_SESSION['SelectedStockItem']);
		//echo "<meta http-equiv='Refresh' content='0; url=" . $rootpath . '/SelectProduct.php?' . SID  ."'>";


	} //end if Delete Part
}

echo '<form  enctype="multipart/form-data" method="post" action="' . $_SERVER['PHP_SELF'] . '?' .SID .'">
	<table border="0" cellpadding="5" cellspacing="1" class="inborder" style="background:#dce6f2;">'. "\n"; // Nested table

//echo '<form name="ItemForm" enctype="multipart/form-data" method="post" action="' . $_SERVER['PHP_SELF'] . '?' .SID .'"><table border="2">
//	<tr><td><table>'. "\n"; // Nested table
if (!isset($StockID) or $StockID=='')
{
/*If the page was called without $StockID passed to page then assume a new stock item is to be entered show a form with a part Code field other wise the form showing the fields with the existing entries against the part will show for editing with only a hidden StockID field. New is set to flag that the page may have called itself and still be entering a new part, in which case the page needs to know not to go looking up details for an existing part*/
$New = true;
echo '<input type="hidden" name="New" value="1">'. "\n";
echo '<tr><td style="text-align:center; padding:5px 0px 5px 0px;" colspan="2" class="headingtable" ><strong>ITEM MASTER </strong></td>
</tr>';
echo '<tr class="OddTableRows"><td>' . _('Item Main Category') . ':</td><td><select name="CategoryID" onChange="putnumber1(this.value)">';
 //echo '<tr><td>' . _('Item Main Category') . ':</td><td><select name="CategoryID" onChange="putnumber1(this.value)" onChange="getnumber(this.value)">';
    
	 $sql = 'SELECT stockmaincategoryid,stockmaincategoryname FROM stockmaincategory';
	 $ErrMsg = _('The stock categories could not be retrieved because');
	 $DbgMsg = _('The SQL used to retrieve stock categories and failed was');
	 $result = DB_query($sql,$db,$ErrMsg,$DbgMsg);
     
		while ($myrow=DB_fetch_array($result))
		{
			if (!isset($_POST['CategoryID']) or $myrow['stockmaincategoryname']==$_POST['stockmaincategoryname'])
			{
			 	echo '<option selected VALUE="'. $myrow['stockmaincategoryid'] . '">'.$myrow['stockmaincategoryname'].'</option>';
			} 
		}
		
	echo '</select><a target="_blank" href="'. $rootpath . '/stockmaincategory.php?' . SID . '">' . _('Add or Modify Main Category') . '</a></td></tr>';



    echo '<tr class="EvenTableRows"><td>' . _('Item Sub Category') . ':</td><td><div id="change">';


echo '</div><a target="_blank" href="'. $rootpath . '/StockCategories.php?' . SID . '">' . _('Add or Modify Sub Category') . '</a></td></tr>';}
elseif(!isset($_POST['UpdateCategories']) and $InputError!=1) 
{ 
// Must be modifying an existing item and no changes made yet/////////////
 
	  $sql = "SELECT *
			FROM stockmaster
		WHERE stockid = '$StockID'";
	  $result = DB_query($sql, $db);
	  $myrow = DB_fetch_array($result);
		
		$_POST['CategoryID']  =  $myrow['maincategoryid'];
		$_POST['client_code']  =  $myrow['client_code'];
		$_POST['StockID']  =  $myrow['stockid'];
		$_POST['item_serial_code']  =  $myrow['item_serial_code'];
	  	$_POST['shade_name']  =  $myrow['shade_name'];
		$_POST['abcclass']  =  $myrow['abcclass'];
		
		$_POST['itemcode'] = $myrow['categoryid'];
		$_POST['CategoryID']  =  $myrow['maincategoryid'];
		$_POST['StockID']  =  $myrow['stockid'];
		$_POST['itemcode'] = $myrow['categoryid'];
    	$_POST['description'] = $myrow['description'];
 		$_POST['size'] = $myrow['size'];
 		$_POST['units']  =  $myrow['units'];
		$_POST['mbflag']  =  $myrow['mbflag'];
		$_POST['lastcurcostdate']  =  $myrow['lastcurcostdate'];
 		$_POST['actualcost']  =  $myrow['actualcost'];
		$_POST['lastcost']  =  $myrow['lastcost'];
		$_POST['materialcost']  =  $myrow['materialcost'];
		$_POST['labourcost']  =  $myrow['labourcost'];
		$_POST['overheadcost']  =  $myrow['overheadcost'];
		$_POST['lowestlevel']  =  $myrow['lowestlevel'];
 		$_POST['discontinued']  =  $myrow['discontinued'];
		$_POST['controlled']  =  $myrow['controlled'];
		$_POST['eoq']  =  $myrow['eoq'];
		$_POST['volume']  =  $myrow['volume'];
		$_POST['kgs']  =  $myrow['kgs'];
		$_POST['barCode']  =  $myrow['barCode'];
 		$_POST['discountcategory']  =  $myrow['discountcategory'];
		$_POST['taxcatid']  =  $myrow['taxcatid'];
		$_POST['serialised']  =  $myrow['serialised'];
		$_POST['appendfile']  =  $myrow['appendfile'];
		$_POST['perishable']  =  $myrow['perishable'];
		$_POST['decimalplaces']  =  $myrow['decimalplaces'];
		$_POST['nextserialno']  =  $myrow['nextserialno'];
	  	$_POST['pansize']  =  $myrow['pansize'];
 		$_POST['shrinkfactor']  =  $myrow['shrinkfactor'];
		$_POST['netweight']  =  $myrow['netweight'];
		$_POST['length']  =  $myrow['length'];
		$_POST['breadth']  =  $myrow['breadth'];
 		$_POST['shape']  =  $myrow['shape'];
 		$_POST['materialtype']  =  $myrow['materialtype'];
		 
		$_POST['discountcategory']  =  $myrow['discountcategory'];
		$_POST['abcclass']  =  $myrow['abcclass'];
		$_POST['excisableitem']  =  $myrow['excisableitem'];
		$_POST['excise']  =  $myrow['excise'];
		$_POST['minlevel']  =  $myrow['minlevel'];
		$_POST['maxlevel']  =  $myrow['maxlevel'];
		$_POST['reorderlevel']  =  $myrow['reorderlevel'];
		$_POST['postdelqcreg']  =  $myrow['postdelqcreg'];
		$_POST['qctestdays']  =  $myrow['qctestdays'];
		$_POST['qctesthours']  =  $myrow['qctesthours'];
		$_POST['size']  =  $myrow['size'];
		$_POST['make']  =  $myrow['make'];
		$_POST['color']  =  $myrow['color'];
		$_POST['grade']  =  $myrow['grade'];
		$_POST['created_date']  =  $myrow['created_date'];


$_POST['reguestby']  =  $myrow['reguestby'];
$_POST['approvedby']  =  $myrow['approvedby'];
		  $_POST['barCode']  = $myrow['barCode'];
		  $_POST['ItemPDF']  = $myrow['appendfile'];
		  $_POST['NextSerialNo'] = $myrow['nextserialno'];
          $_POST['reguestdate'] = ConvertSQLDate($myrow['reguestdate']);
	      $_POST['approveddate']= ConvertSQLDate($myrow['approveddate']);
		
	echo '<tr><td style="text-align:center; padding:5px 0px 5px 0px;" colspan="2" class="headingtable" ><strong>UPDATE ITEM MASTER </strong></td>
</tr>';
	echo '<tr class="EvenTableRows">
			<td>' . _('Item Main Category') . ':</td>';
			?>
			<td>
			<select name="CategoryID" onChange="putnumber1(this.value)">
			<option value="000">---Select Main Category---</option>
			<?php 
			$item_sql=DB_query("Select stockmaincategoryid,stockmaincategoryname from stockmaincategory",$db);
			while($item_row=DB_fetch_array($item_sql))
			{
			?>
			<option value="<?php echo $item_row['stockmaincategoryid'];?>"<?php echo($_POST['CategoryID']==$item_row['stockmaincategoryid']?'selected':'') ?>><?php echo $item_row['stockmaincategoryname'];?></option>
			<?php } ?>
			</select>
			</td>
			
	<?php echo'</tr>'. "\n";
	 echo '<tr class="EvenTableRows"><td>' . _('Item Sub Category') . ':</td>';
	echo ' <td><div id="change">';
		   
		   
	$sql1='select categoryid,categorydescription from stockcategory where stockmaincategory ="'.$_POST['CategoryID'].'"';
	 	$result1 = DB_query($sql1,$db);?>
		<select id="itemcodeval" name="itemcodeval" onChange="putnumber(this.value)">
		<option value="000">Select Sub Category</option>
		<?php 
		while($myrow1=DB_Fetch_array($result1))
		{?>
			<option value="<?php echo $myrow1['categoryid'];?>"<?php echo($_POST['itemcode']==$myrow1['categoryid']?'selected':'');?>><?php echo $myrow1['categorydescription'];?></option>
<?php 	} ?>
		</select>
		   
		   
		   
		   
<?php 		   
	echo'</div></td></tr>';
} //$_POST['CategoryID']
else { // some changes were made to the data so don't re-set form variables to DB ie the code above
	
	echo '<tr><td>' . _('Item Code') . ':</td><td>'.$StockID.'</td></tr>';
	
	// edit by below
	echo '<tr><td>' . _('Item Sub Category') . ':</td><td>'.$StockID.'</td></tr>';
	echo "<input type='text' name='StockID' value='$StockID'>";}
 
echo'<tr class="OddTableRows"><td>'._('Item xxxCode').':</td><td><input type="text" id="StockID" name="StockID" value="'.$StockID.'" readonly="readonly" size="60"> </td></tr>';

if (isset($_POST['description'])) 
{
	$description = $_POST['description'];
} else {
	$description ='';
}



echo '<tr class="EvenTableRows"><td>' . _('Item description')  .':</td><td><input ' . (in_array('description',$Errors) ?  'class="inputerror"' : '' ) .' type="Text" name="description" size=40 maxlength=50 value="'.$_POST['description']. '"></td></tr>'."\n";

  
echo '<tr class="OddTableRows"><td>' . _('Client Code'). ':</td><td><input ' . (in_array('description',$Errors) ?  'class="inputerror"' : '' ) .' type="Text" name="client_code" size=40 maxlength=50 value="' . htmlentities($_POST['client_code'],ENT_QUOTES,_('ISO-8859-1')) . '"></td></tr>'."\n";



echo '<tr class="EvenTableRows"><td>' . _('Grade'). ':</td><td><input ' . (in_array('shade_name',$Errors) ?  'class="inputerror"' : '' ) .' type="Text" name="shade_name" size=40 maxlength=50 value="' . htmlentities($_POST['shade_name'],ENT_QUOTES,_('ISO-8859-1')) . '"></td></tr>'."\n";


echo '<tr class="OddTableRows"><td>' . _('Item Serial No.'). ':</td><td><input ' . (in_array('item_serial_code',$Errors) ?  'class="inputerror"' : '' ) .' type="Text" name="item_serial_code" size=40 maxlength=50 value="' . htmlentities($_POST['item_serial_code'],ENT_QUOTES,_('ISO-8859-1')) . '"></td></tr>'."\n";


// Generate selection drop down from pdf_append directory - by emdx,
// developed with examples from http://au2.php.net/manual/en/function.opendir.php
function select_files($dir, $label = '', $select_name = 'ItemPDF', $curr_val = '', $char_length = 60) 
{
	$teller = 0;
	if (!file_exists($dir)) 
	{
		mkdir($dir);
		chmod($dir, 0777);
	}
	if ($handle = opendir($dir)) {
		$mydir = "<select name=".$select_name.">\n";
		$mydir .= '<option VALUE=0>none';
		if (isset($_POST['ItemPDF'])) {
			$curr_val = $_POST['ItemPDF'];
		} else {
			$curr_val .=  'none';
		}
		while (false !== ($file = readdir($handle)))
		{
			$files[] = $file;
		}
		closedir($handle);
		sort($files);
		foreach ($files as $val) {
			if (is_file($dir.$val)) {
				$mydir .= '<option VALUE='.$val;
				$mydir .= ($val == $curr_val) ? ' selected>' : '>';
				$mydir .= $val."\n";
				$teller++;
			}
		}
		$mydir .= "";
	}
	return $mydir;
}


if (!isset($_POST['ItemPDF']))
 {
	$_POST['ItemPDF'] = '';
}
//echo '<tr class="EvenTableRows"><td>' . _('PDF attachment (.pdf)') . ':' . "\n</td><td>" . select_files('companies/' . $_SESSION['DatabaseName'] .'/pdf_append//','' , 'ItemPDF', $_POST['ItemPDF'], '60') . '</td></tr>'. "\n";

// Add image upload for New Item  - by Ori
echo '<tr class="OddTableRows"><td>'. _('Image File (.jpg)') . ':</td><td><input type="file" id="ItemPicture" name="ItemPicture"></td></tr>';
// EOR Add Image upload for New Item  - by Ori

echo '<tr class="EvenTableRows"><td>' . _('Material Type').':</td><td><input ' . (in_array('materialtype',$Errors) ?  'class="inputerror"' : '' ) .' type="Text" name="materialtype" size=15 maxlength=50 value="' . htmlentities($_POST['materialtype'],ENT_QUOTES,_('ISO-8859-1')) . '"></td></tr>'."\n";

echo '<tr class="OddTableRows">
<td>' . _('Size') . ':</td>';
?>
<td>
<select name="size" id="size">
<option value="000">---Select Size---</option>
<?php
$size_sql=DB_query("Select * from size_master",$db);
while($size_row=DB_fetch_array($size_sql))
{
?>
<option value="<?php echo $size_row['id'];?>"<?php echo($_REQUEST['size']==$size_row['id']?'selected':'')?>><?php echo $size_row['name'];?></option>
<?php } ?>
</select>
</td>
</tr>
<?php 
if (!isset($_POST['eoq']) or $_POST['eoq']=='')
{
    $_POST['eoq']=0;
}

if (!isset($_POST['volume']) or $_POST['volume']=='')
{
    $_POST['volume']=0;
}
if (!isset($_POST['kgs']) or $_POST['kgs']=='')
{
    $_POST['kgs']=0;
}
if (!isset($_POST['Controlled']) or $_POST['Controlled']=='')
{
    $_POST['Controlled']=0;
}
if (!isset($_POST['Serialised']) or $_POST['Serialised']=='' || $_POST['Controlled']==0)
{
    $_POST['Serialised']=0;
}
if (!isset($_POST['decimalplaces']) or $_POST['decimalplaces']=='')
{
	$_POST['decimalplaces']=0;
}
if (!isset($_POST['discontinued']) or $_POST['discontinued']=='')
{
    $_POST['discontinued']=0;
}
if (!isset($_POST['pansize'])) 
{
	$_POST['pansize']=0;
}
if (!isset($_POST['shrinkfactor'])) 
{
	$_POST['shrinkfactor']=0;
}
if (!isset($_POST['NextSerialNo'])) 
{
	$_POST['NextSerialNo']=0;
}

echo '<tr class="EvenTableRows"><td>' . _('Issue as per FIFO') . ':</td><td><select name="IapF">';
if ($_POST['IapF']==0){
	echo '<option selected value=0>' . _('Yes') . '</option>';
} else {
	echo '<option value=0>' . _('Yes') . '</option>';
}
if ($_POST['IapF']==1){
	echo '<option selected value=1>' . _('No') . '</option>';
} else {
	echo '<option value=1>' . _('No') . '</option>';
}
echo '</select></td></tr>';


echo '<tr class="OddTableRows"><td>' . _('GSM') . ':</td><td><input ' . (in_array('eoq',$Errors) ?  'class="inputerror"' : '' ) .'   type="Text"  name="abcclass" size=12 maxlength=10 value="' . $_POST['abcclass'] . '"></td></tr>';

 
echo '<tr class="EvenTableRows"><td>' . _('Min Level') . ':</td><td><input ' . (in_array('minlevel',$Errors) ?  'class=""' : '' ) .'   type="Text"  name="minlevel" id="minlevel" size=12 onblur="MinVal()" maxlength=10 value="' . $_POST['minlevel'] . '"></td></tr>';

echo '<tr class="OddTableRows"><td>' . _('Max Level') . ':</td><td><input ' . (in_array('maxlevel',$Errors) ?  'class=""' : '' ) .'   type="Text"  name="maxlevel" id="maxlevel" size=12 onblur="MaxVal()" maxlength=10 value="' . $_POST['maxlevel'] . '"></td></tr>';

 
echo '<input ' . (in_array('eoq',$Errors) ?  'class="inputerror"' : '' ) .'   type="hidden" class="number" name="eoq" size="10" maxlength=10 value="' . $_POST['eoq'] . '">';
/*echo '<tr class="EvenTableRows"><td>' . _('Economic Order Quantity') . ':</td><td><input ' . (in_array('eoq',$Errors) ?  'class="inputerror"' : '' ) .'   type="hidden" class="number" name="eoq" size="10" maxlength=10 value="' . $_POST['eoq'] . '"></td></tr>';*/
// edit


/*echo '<tr class="OddTableRows"><td>' . _('Post Del Qc Reg') . ':</td><td><select name="postdelqcreg">';
if ($_POST['postdelqcreg']==0)
{
	echo '<option selected value="0">' . _('Yes') . '</option>';
} 
else {
	echo '<option value="0">' . _('Yes') . '</option>';
}

if ($_POST['postdelqcreg']==1){
	echo '<option selected value="1">' . _('No') . '</option>';
} else {
	echo '<option value="1">' . _('No') . '</option>';
}
echo '</select></td></tr>';*/

/*echo '<tr class="EvenTableRows"><td>' . _('Pre Delivery Qc') . ':</td><td>
<select name="predeliveryqc" >';
if ($_POST['predeliveryqc']==0){
	echo '<option selected value=0>' . _('Yes') . '</option>';
} else {
	echo '<option value=0>' . _('Yes') . '</option>';
}
if ($_POST['predeliveryqc']==1){
	echo '<option selected value=1>' . _('No') . '</option>';
} else {
	echo '<option value=1>' . _('No') . '</option>';
}
echo '</select></td></tr>';*/

//
echo '<tr class="OddTableRows"><td>' . _('Packaged volume (metres cubed)') . ':</td><td><input ' . (in_array('volume',$Errors) ?  'class="inputerror"' : '' ) .'   type="Text" class="number" name="volume" size=12 maxlength=10 value="' . $_POST['volume'] . '"></td></tr>';

echo '<tr class="EvenTableRows"><td>' . _('Packaged Weight (kgs)') . ':</td><td>
<input ' . (in_array('kgs',$Errors) ?  'class="inputerror"' : '' ) .'   type="Text" class="number" name="kgs" size=12 maxlength=10 value="' . $_POST['kgs'] . '">
</td></tr>';

##========Changed by moha end

echo '<tr class="OddTableRows"><td>' . _('units of Measure') . ':</td><td>
<select ' . (in_array('description',$Errors) ?  'class="selecterror"' : '' ) .'  name="units">';
$sql = 'SELECT  unitid,unitname FROM unitsofmeasure ORDER by unitname';
$UOMResult = DB_query($sql,$db);

if (!isset($_POST['units'])) 
{
	$UOMrow['unitname']=_('each');
}
while( $UOMrow = DB_fetch_array($UOMResult) ) 
{
     if (isset($_POST['units']) and $_POST['units']==$UOMrow['unitname'])
	 {
	    echo '<option selected value="' . $UOMrow['unitid'] . '">' . $UOMrow['unitname'] . '</option>';
     } 
	 else 
	 {
	    echo '<option value="' . $UOMrow['unitid'] . '">' . $UOMrow['unitname']  . '</option>';
     }
}
echo '</select></td></tr>';
/*echo '<tr class="EvenTableRows"><td>' . _('Assembly, Kit, Manufactured or Service/Labour') . ':</td><td>
<select name="mbflag">';
if ($_POST['mbflag']=='A')
{
	echo '<option selected value="A">' . _('Assembly') . '</option>';
} 
else {
	echo '<option value="A">' . _('Assembly') . '</option>';
}
if (!isset($_POST['mbflag']) or $_POST['mbflag']=='K')
{
	echo '<option selected value="K">' . _('Kit') . '</option>';
} 
else {
	echo '<option value="K">' . _('Kit') . '</option>';
}
if (!isset($_POST['mbflag']) or $_POST['mbflag']=='M'){
	echo '<option selected value="M">' . _('Manufactured') . '</option>';
} else {
	echo '<option value="M">' . _('Manufactured') . '</option>';
}
if (!isset($_POST['mbflag']) or $_POST['mbflag']=='G' OR !isset($_POST['mbflag']) OR $_POST['mbflag']==''){
	echo '<option selected value="G">' . _('Phantom') . '</option>';
} else {
	echo '<option value="G">' . _('Phantom') . '</option>';
}
if (!isset($_POST['mbflag']) or $_POST['mbflag']=='B' OR !isset($_POST['mbflag']) OR $_POST['mbflag']==''){
	echo '<option selected value="B">' . _('Purchased') . '</option>';
} else {
	echo '<option value="B">' . _('Purchased') . '</option>';
}

if (isset($_POST['mbflag']) and $_POST['mbflag']=='D'){
	echo '<option selected value="D">' . _('Service/Labour') . '</option>';
} else {
echo '<option value="D">' . _('Service/Labour') . '</option>';
}

echo '</select></td></tr>';*/

echo '<tr class="OddTableRows"><td>' . _('Current or Obsolete') . ':</td><td>
<select name="discontinued">';
if ($_POST['discontinued']==0){
	echo '<option selected value=0>' . _('Current') . '</option>';
} else {
	echo '<option value=0>' . _('Current') . '</option>';
}
if ($_POST['discontinued']==1){
	echo '<option selected value=1>' . _('Obsolete') . '</option>';
} else {
	echo '<option value=1>' . _('Obsolete') . '</option>';
}
echo '</select></td></tr>';

 

echo '<tr class="EvenTableRows"><td>' . _('Decimal Places for display Quantity') . ':</td><td><input type="text" class="number" name="decimalplaces" size=1 maxlength="1" value="' . $_POST['decimalplaces'] . '"></td></tr>';
 
 
/*echo '<tr class="OddTableRows"><td>' . _('Discount Category') . ':</td><td><input type="Text" name="discountcategory" size=2 maxlength=2 value="' . $_POST['discountcategory'] . '"></td></tr>';

echo '<tr class="EvenTableRows"><td>' . _('Tax Category') . ':</td><td>';
  $sql = 'SELECT taxcatid  , taxcatname          FROM taxcategories ORDER BY taxcatname';

echo '<select name="taxcatid">';
$result = DB_query($sql, $db);

if (!isset($_POST['taxcatid']))
{
	$_POST['taxcatid'] = $_SESSION['Defaulttaxcatidegory'];
}

while ($myrow = DB_fetch_array($result)) {
	if ($_POST['taxcatid'] == $myrow['taxcatid']){
		echo '<option selected value=' . $myrow['taxcatid'] . '>' . $myrow['taxcatname'] . '</option>';
	} else {
		echo '<option value=' . $myrow['taxcatid'] . '>' . $myrow['taxcatname'] . '</option>';
	}
} //end while loop

echo '</select></td></tr>';*/

     /*echo '<tr class="OddTableRows">
        <td>' . _('Pan Size') . ':</td>
	    <td><input type="Text" class="number" name="pansize" size="6" maxlength="6" value=' . $_POST['pansize'] . '></td>
	</tr>';*/
	
	 echo '<input type="hidden" class="number" name="pansize" size="6" maxlength="6" value=' . $_POST['pansize'] . '>';	
	echo '<input type="hidden" class="number" name="shrinkfactor" size="6" maxlength="6" value=' . $_POST['shrinkfactor'] . '>';
    /*echo '<tr class="EvenTableRows">
        <td>' . _('Shrinkage Factor') . ':</td>
	    <td><input type="Text" class="number" name="shrinkfactor" size="6" maxlength="6" value=' . $_POST['shrinkfactor'] . '></td>
	</tr>';*/


echo '<tr class="OddTableRows"><td style="text-align:center; padding:5px 0px 5px 0px;" colspan="2"  class="headingtable"><strong>Item Specifications :</strong></td>
	  </tr>'; ?>
<tr>
<td colspan="2">
<table width="100%" border="0">
<tr>
<td>Make</td>
<td>
<select name="make" id="make">
<option value="000">---Select Make---</option>
<?php
$make_sql="Select * from product_manufacture";
$make_result = DB_query($make_sql, $db);
while($make_row=DB_fetch_array($make_result))
{
?>
<option value="<?php echo $make_row['id'];?>"<?php echo($_POST['make']==$make_row['id']?'selected':'')?>><?php echo $make_row['manufacturer']?></option>
<?php } ?>
</select>
</td>
<td>Grade</td>
<td><select name="grade" id="grade">
<option value="000">---Select Grade---</option>
<?php
$grade_sql="Select * from product_grade";
$grade_result = DB_query($grade_sql, $db);
while($grade_row=DB_fetch_array($grade_result))
{
?>
<option value="<?php echo $grade_row['id'];?>"<?php echo($_POST['grade']==$grade_row['id']?'selected':'');?>><?php echo $grade_row['grade']?></option>
<?php } ?>
</select></td>
<td>Color</td>
<td><select name="color" id="color">
<option value="000">---Select Color---</option>
<?php
$color_sql="Select * from product_color";
$color_result = DB_query($color_sql, $db);
while($color_row=DB_fetch_array($color_result))
{
?>
<option value="<?php echo $color_row['id'];?>"<?php echo ($_POST['color']==$color_row['id']?'selected':'');?>><?php echo $color_row['color']?></option>
<?php } ?>
</select></td>
</tr>
</table>	
</td>
</tr>	
	
	
<?php 	  
   echo'<tr class="OddTableRows">
        <td>' . _('length') . ':</td>
	    <td><input type="Text" name="length" size="12" maxlength="6" value=' . $_POST['length'] . '></td>
	</tr>';	
	echo'<tr class="EvenTableRows">
        <td>' . _('breadth') . ':</td>
	    <td><input type="Text" name="breadth" size="12" maxlength="6" value=' . $_POST['breadth'] . '></td>
	</tr>';	
  
  echo'<tr class="OddTableRows">
        <td>' . _('Reel Width') . ':</td>
	    <td><input type="Text" name="shape" size="12" maxlength="6" value=' . $_POST['shape'] . '></td>
	</tr>';	
   
		?>

	  <?php 
	  
	  echo '<tr><td style="text-align:center; padding:5px 0px 5px 0px;" colspan="2"  class="headingtable"><strong>Requester :</strong></td>
	  </tr>';
	    
  echo'<tr class="OddTableRows">
        <td>' . _('Request By') . ':</td>
	    <td><input type="Text" name="reguestby" size="12" maxlength="6" value=' . $_POST['reguestby'] . '></td>
	</tr>';	

 echo'<tr class="EvenTableRows">
        <td>' . _('Request Date') . ':</td>
	    <td><input type="Text" name="reguestdate" size="12" maxlength="6" value="'.$date.'" class="datepicker"></td></tr>';

 echo '<tr><td style="text-align:center; padding:5px 0px 5px 0px;" colspan="2" class="headingtable"><strong>Approvals : </strong></td>
	  </tr>';
echo'<tr class="OddTableRows">
        <td>' . _('Approved By') . ':</td>
	    <td><input type="Text" name="approvedby" size="12" maxlength="6" value=' . $_POST['approvedby'] . '></td>
	</tr>';	
	echo'<tr class="EvenTableRows">
        <td>' . _('Approved Date') . ':</td>
	    <td><input type="Text" name="approveddate" size="12" class="datepicker" value="'.$date.'"></td></tr>';
	
	if($_REQUEST['StockID'] == '')
	{
	
	echo '<tr>
        <td colspan="2"><center><input type="submit" name="submit" value="Save"></center></td>
	    </tr>';
		
	}
	else
	{
	echo '<tr class="OddTableRows">
        <td colspan="2"><center><input type="submit" name="UpdateStockItem" value="Edit"></center></td>
	    </tr>';
	
	}

 if (function_exists('imagecreatefrompng'))
 {
	$StockImgLink = '<img src="GetStockImage.php?SID&automake=1&textcolor=FFFFFF&bgcolor=CCCCCC'.
		'&StockID='.urlencode($StockID).
		'&text='.
		'&width=64'.
		'&height=64'.
		'" >';
} else {
	if( isset($StockID) and file_exists($_SESSION['part_pics_dir'] . '/' .$StockID.'.jpg') ) {
		$StockImgLink = '<img src="' . $_SESSION['part_pics_dir'] . '/' .$StockID.'.jpg" >';
	} else {
		$StockImgLink = _('No Image');
	}
}

echo '</table></td></tr></table><div class="centre">';

if (!isset($_POST['CategoryID'])) {
	$_POST['CategoryID'] = '';
}
//echo '<table><tr><th colspan="2">' . _('') . '</th></tr>';

//echo '<table><tr><th colspan="2">' . _('Item Category Properties') . '</th></tr>';
$sql = "SELECT stkcatpropid,
				label,
				controltype,
				defaultvalue
		FROM stockcatproperties
		WHERE categoryid ='" . $_POST['CategoryID'] . "'
		AND reqatsalesorder =0
		ORDER BY stkcatpropid";

$PropertiesResult = DB_query($sql,$db);
$PropertyCounter = 0;
$PropertyWidth = array();

while ($PropertyRow=DB_fetch_array($PropertiesResult))
{

	$PropValResult = DB_query("SELECT value FROM
									stockitemproperties
									WHERE stockid='" . $StockID . "'
									AND stkcatpropid =" . $PropertyRow['stkcatpropid'],
								$db);
	$PropValRow = DB_fetch_row($PropValResult);
	$PropertyValue = $PropValRow[0];

	echo '<input type="hidden" name="PropID' . $PropertyCounter . '" value=' .$PropertyRow['stkcatpropid'] .'>';

	echo '<tr><td>' . $PropertyRow['label'] . '</td>
				<td>';
	switch ($PropertyRow['controltype']) {
	 	case 0; //textbox
	 		echo '<input type="textbox" name="PropValue' . $PropertyCounter . '" size="20" maxlength="100" value="' . $PropertyValue . '">';
	 		break;
	 	case 1; //select box
	 		$OptionValues = explode(',',$PropertyRow['defaultvalue']);
			echo '<select name="PropValue' . $PropertyCounter . '">';
			foreach ($OptionValues as $PropertyOptionValue){
				if ($PropertyOptionValue == $PropertyValue){
					echo '<option selected value="' . $PropertyOptionValue . '">' . $PropertyOptionValue . '</option>';
				} else {
					echo '<option value="' . $PropertyOptionValue . '">' . $PropertyOptionValue . '</option>';
				}
			}
			echo '</select>';
			break;
		case 2; //checkbox
			echo '<input type="checkbox" name="PropValue' . $PropertyCounter . '"';
			if ($PropertyValue==1){
				echo '"checked"';
			}
			echo '>';
			break;
	} //end switch

	echo '<input type="hidden" name="PropType' . $PropertyCounter .'" value=' . $PropertyRow['controltype'] . '>';
	echo '</td></tr>';
	$PropertyCounter++;
} //end loop round properties for the item category
echo '</table>';
//echo '</form></div>';

echo '<input type="hidden" name="PropertyCounter" value=' . $PropertyCounter . '>';
echo '</form></div>';

?>

<script language="javascript">
 var xmlHttp
 var rowcount=1;
function Manufacture()
{
	var str1 = document.getElementById("make").value;
	var str2 = document.getElementById("color").value;
	var str3 = document.getElementById("grade").value;
    xmlHttp=GetXmlHttpObject();
	 
	if(str1!="" && str2!="" && str3!="")
	{	  
		if (xmlHttp==null)
		{
		    alert ("Your browser does not support AJAX!");
		    return;
		} 
		var url="manufacture.php";
		url=url+"?makeId="+str1+"&colorId="+str2+"&gradeId="+str3+"&Rowcount="+rowcount;
		//alert(url);
		xmlHttp.onreadystatechange=AddRow;
		xmlHttp.open("GET",url,true);
		xmlHttp.send(null);
	}
}

function AddRow() 
{ 
	if (xmlHttp.readyState==4)
	{ 
   		var old_add_value = document.getElementById("Add").innerHTML;
		var new_value = xmlHttp.responseText;
	    var final_value = old_add_value + new_value;
	    document.getElementById("Add").innerHTML=final_value;
		rowcount++;
	}
}

 
function putnumber1(str)
{ 
   
   xmlHttp=GetXmlHttpObject();
		if (xmlHttp==null)
		  {
		    alert ("Your browser does not support AJAX!");
		    return;
		  } 
	var url="randomnumber.php";
	url=url+"?Category1="+str;
	//alert(url);
	//url=url+"&sid="+Math.random();
	xmlHttp.onreadystatechange=NumberChanged1;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}

function NumberChanged1() 
{ 
	if (xmlHttp.readyState==4)
	{ 
	   document.getElementById("change").innerHTML=xmlHttp.responseText;
	}
}

function putnumber(str)
{ 
 	xmlHttp=GetXmlHttpObject();
		if (xmlHttp==null)
		  {
		    alert ("Your browser does not support AJAX!");
		    return;
		  } 
	var url="stockNumber.php";
	url=url+"?itemcode="+str;
	//alert(url);
	//url=url+"&sid="+Math.random();
	xmlHttp.onreadystatechange=NumberChanged2;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}

function NumberChanged2() 
{ 
	if (xmlHttp.readyState==4)
	{ 
	    document.getElementById("StockID").value=xmlHttp.responseText;
	}
}


function GetXmlHttpObject()
{
	var xmlHttp=null;
	try
	  {
	  // Firefox, Opera 8.0+, Safari
	  xmlHttp=new XMLHttpRequest();
	  }
	catch (e)
	  {
	  // Internet Explorer
	  try
		{
		xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
	  catch (e)
		{
		xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
	  }
	return xmlHttp;
}
</script>


<?php
include('includes/footer.inc');
?>
