<?php
/* $Revision: 1.39 $ */
$PageSecurity = 4;
include('includes/DefineSuppTransClass.php');
include('includes/DefinePOClass.php');
include('includes/SQL_CommonFunctions.inc');
/* Session started in header.inc for password checking 
 * and authorisation level check 
 */
include('includes/session.inc');
$title = _('Purchase Order Items');

$identifier=$_GET['identifier'];
$supplier = $_GET['suppid'];
$final_qtation = $_GET['final_quat'];
$ModifyOrderNumber = $_GET['ModifyOrderNumbe'];

/* If a purchase order header doesn't exist, then go to
 * PO_Header.php to create one
 */
if (!isset($_SESSION['PO'.$identifier])){
	header('Location:' . $rootpath . '/PO_Header.php?' . SID);
	exit;
} //end if (!isset($_SESSION['PO'.$identifier]))

include('includes/header.inc');

$Maximum_Number_Of_Parts_To_Show=50;
 	echo '<a href="'. $rootpath . '/index.php?' . SID . "identifier=".$identifier.'">'. _('Purchases'). '</a>>>';
	echo '<a href="'.$rootpath.'/PO_SelectOSPurchOrder.php?' . SID . "identifier=".$identifier. '">' ._('Purchase Order') . '</a><br>';

// add new request here 08-09-26
if (isset($_POST['StockID2']) && $_GET['Edit']=='') {
/* If a stock item is selected and a purchdata record
 * exists for it then find that record.
 */
	$sql = "SELECT
			stockmaster.description,
			purchdata.suppliers_partno,
			stockmaster.pkg_type,
			stockmaster.units,
			stockmaster.netweight,		
			stockmaster.kgs,
			stockmaster.volume
			FROM purchdata INNER JOIN stockmaster
			ON purchdata.stockid=stockmaster.stockid
			WHERE purchdata.stockid='" . $_POST['StockID2'] . "' AND
			purchdata.supplierno='".$_SESSION['PO'.$identifier]->SupplierID."'";

	$ErrMsg = _('The stock record of the stock selected') . ': ' . $_POST['Stock'] . ' ' . 
		_('cannot be retrieved because');
	$DbgMsg = _('The SQL used to retrieve the supplier details and failed was');
	$result =DB_query($sql,$db,$ErrMsg,$DbgMsg);
	$myrow = DB_fetch_row($result);
	
	$_POST['ItemDescription'] = $myrow[0];
	$_POST['suppliers_partno'] = $myrow[1];
	$_POST['package'] = $myrow[2];
	$_POST['uom'] = $myrow[3];
	$_POST['nw'] = $myrow[4];
	$_POST['gw'] = $myrow[5];
	$_POST['cuft'] = $myrow[6];
} // end if (isset($_POST['StockID2']) && $_GET['Edit']=='')

if (isset($_POST['UpdateLines']) OR isset($_POST['Commit'])) 
{
	foreach ($_SESSION['PO'.$identifier]->LineItems as $POLine) 
	{
		if ($POLine->Deleted==False) {
			$_SESSION['PO'.$identifier]->LineItems[$POLine->LineNo]->Quantity=$_POST['Qty'.$POLine->LineNo];
			$_SESSION['PO'.$identifier]->LineItems[$POLine->LineNo]->Price=$_POST['Price'.$POLine->LineNo];
			$_SESSION['PO'.$identifier]->LineItems[$POLine->LineNo]->nw=$_POST['nw'.$POLine->LineNo];
			$_SESSION['PO'.$identifier]->LineItems[$POLine->LineNo]->ReqDelDate=$_POST['ReqDelDate'.$POLine->LineNo];
		}
	}
}

if (isset($_POST['Commit'])){ /*User wishes to commit the order to the database */
 /* NewItem is set from the part selection list as the part code selected */
/* take the form entries and enter the data from the form into the PurchOrder class variable */
$ModifyOrderNumber = $_POST['ModifyOrderNumber'];
$cti=1;
//print_r($_POST['ProductID']);

	foreach ($_POST['ProductID'] as $key => $value) {
	if ($_POST['ProductID']=='$key') {
			$ItemCode= $value;
			$Quantity=$value;
			$AlreadyOnThisOrder =0;
			if ($_SESSION['PO_AllowSameItemMultipleTimes'] ==false){
				if (count($_SESSION['PO'.$identifier]->LineItems)!=0){
					foreach ($_SESSION['PO'.$identifier]->LineItems AS $OrderItem) {
					/* do a loop round the items on the order to see that the item
					is not already on this order */
						if (($OrderItem->StockID == $ItemCode) and ($OrderItem->Deleted==false)) {
							$AlreadyOnThisOrder = 1;
							prnMsg( _('The item') . ' ' . $ItemCode . ' ' . _('is already on this order') . '. ' . _('The system will not allow the same item on the order more than once') . '. ' . _('However you can change the quantity ordered of the existing line if necessary'),'error');
						}
					} /* end of the foreach loop to look for preexisting items of the same code */
				}
			}
			if ($AlreadyOnThisOrder!=1 and $Quantity>0){
				 $purchdatasql='SELECT COUNT(supplierno)
								FROM purchdata
								WHERE purchdata.supplierno = "' . $_SESSION['PO'.$identifier]->SupplierID . '"
								AND purchdata.stockid="'. $ItemCode . '"';
				$purchdataresult=DB_query($purchdatasql, $db);
				$myrow=DB_fetch_row($purchdataresult);
				
				if ($myrow[0]>0) {
				 	 $sql = "SELECT stockmaster.description,
						stockmaster.stockid,
						stockmaster.units,
						stockmaster.decimalplaces,
						stockmaster.kgs,
						stockmaster.netweight,
						stockcategory.stockact,
						chartmaster.accountname,
						purchdata.price,
						purchdata.conversionfactor,				
						purchdata.supplierdescription,
						purchdata.suppliersuom,
						purchdata.suppliers_partno,
						purchdata.leadtime
					    FROM stockcategory,
						chartmaster,
						stockmaster LEFT JOIN purchdata
					    ON stockmaster.stockid = purchdata.stockid
					    AND purchdata.supplierno = '" . $_SESSION['PO'.$identifier]->SupplierID . "'
					    WHERE chartmaster.accountcode = stockcategory.stockact
						AND stockcategory.categoryid = stockmaster.categoryid
						AND stockmaster.stockid = '". $ItemCode . "'
						AND purchdata.effectivefrom = 
						(SELECT max(effectivefrom) 
						 FROM purchdata 
						 WHERE purchdata.stockid='". $ItemCode . "'
						 AND purchdata.supplierno='" . $_SESSION['PO'.$identifier]->SupplierID . "')";
				} else {
				 $sql='SELECT stockmaster.description,
						stockmaster.stockid,
						stockmaster.units,
						stockmaster.decimalplaces,
						stockmaster.kgs,
						stockmaster.netweight,
						stockcategory.stockact,
						chartmaster.accountname
					FROM stockcategory,
						chartmaster,
						stockmaster
					WHERE chartmaster.accountcode = stockcategory.stockact
						AND stockcategory.categoryid = stockmaster.categoryid
						AND stockmaster.stockid = "'. Amit . '"';
				}

				$ErrMsg = _('The supplier pricing details for') . ' ' . $ItemCode . ' ' . _('could not be retrieved because');
				$DbgMsg = _('The SQL used to retrieve the pricing details but failed was');
				$result1 = DB_query($sql,$db,$ErrMsg,$DbgMsg);

				if ($myrow = DB_fetch_array($result1)){
				//print_r($_POST['Rate']);die;
				foreach($_POST['Rate'] as $key=>$val)
				{
						if (is_numeric($_POST['Rate'][$key]))
						{
	
							  $_SESSION['PO'.$identifier]->add_to_order ($_SESSION['PO'.$identifier]->LinesOnOrder+1,
								$_POST['ProductID'][$key],
								0, /*Serialised */
								0, /*Controlled */
								$_POST['quantity'][$key], /* Qty */
								$_POST['ProductDes'][$key],
								$_POST['Rate'][$key],
								'',
								'',
								$_SESSION['PO'.$identifier]->deliverydate,
								$_POST['Discount'][$key],
								$_POST['NetRate'][$key],
								'',
								$_POST['LeadTime'][$key],
								$_POST['PreIns'][$key],
								$_POST['Specification'][$key],
								$_POST['Quantum'][$key],
								'',
								'',
								'',
								'',
								'',
								'',
								'',
								'',
								'',
								$Quantity*$myrow['price'],
								'',
								$_POST['Discount'][$key],
								$_POST['NetRate'][$key],
								$_POST['LeadTime'][$key],								
								$_POST['PreIns'][$key],
								$_POST['Specification'][$key],
								$_POST['Quantum'][$key]);
								
						} else { /*There was no supplier purchasing data for the item selected so enter a purchase order line with zero price */
	
							$_SESSION['PO'.$identifier]->add_to_order ($_SESSION['PO'.$identifier]->LinesOnOrder+1,
								$_POST['ProductID'][$key],
								0, /*Serialised */
								0, /*Controlled */
								$_POST['quantity'][$key], /* Qty */
								$_POST['ProductDes'][$key],
								$_POST['Rate'][$key],
								'',
								'',
								$_SESSION['PO'.$identifier]->deliverydate,
								$_POST['Discount'][$key],
								$_POST['NetRate'][$key],
								'',
								$_POST['LeadTime'][$key],
								$_POST['PreIns'][$key],
								$_POST['Specification'][$key],
								$_POST['Quantum'][$key],
								'',
								'',
								'',
								'',
								'',
								'',
								'',
								'',
								'',
								$Quantity*$myrow['price'],
								'',
								$_POST['Discount'][$key],
								$_POST['NetRate'][$key],
								$_POST['LeadTime'][$key],								
								$_POST['PreIns'][$key],
								$_POST['Specification'][$key],
								$_POST['Quantum'][$key]);
						}
					}
			/*Make sure the line is also available for editing by default without additional clicks */
			//$_GET['Edit'] = $_SESSION['PO'.$identifier]->LinesOnOrder; /* this is a bit confusing but it was incremented by the add_to_order function */
			    } else {
					prnMsg (_('The item code') . ' ' . $ItemCode . ' ' . _('does not exist in the database and therefore cannot be added to the order'),'error');
					if ($debug==1){
						echo "<br>".$sql;
					}
					include('includes/footer.inc');
					exit;
				}
			} /* end of if not already on the order */
		}
		$cti++;
	}




//////First do some validation
 /////Is the delivery information all entered
 
	    $InputError=0; /*Start off assuming the best */
	   if ($_SESSION['PO'.$identifier]->DelAdd1=='' or strlen($_SESSION['PO'.$identifier]->DelAdd1)<3){
		prnMsg( _('The purchase order can not be committed to the database because there is no delivery steet address specified'),'error');
		$InputError=1;
	   } elseif ($_SESSION['PO'.$identifier]->Location=='' or ! isset($_SESSION['PO'.$identifier]->Location)){
		prnMsg( _('The purchase order can not be committed to the database because there is no location specified to book any stock items into'),'error');
		$InputError=1;
	}
	/* elseif ($_SESSION['PO'.$identifier]->LinesOnOrder <=0){
		prnMsg( _('The purchase order can not be committed to the database because there are no lines entered on this order'),'error');
		$InputError=1;
	}*/

     //////////////////If all clear then proceed to update the database////////////
	if ($InputError!=1){
		 $emailsql='SELECT email FROM www_users WHERE userid="'.$_SESSION['PO'.$identifier]->Initiator.'"';
		$emailresult=DB_query($emailsql, $db);
		$emailrow=DB_fetch_array($emailresult);
		$sql = 'BEGIN';
		$result = DB_query($sql,$db);
    
		/*its an existing order need to update the old order info */
	//	 		$_SESSION['PO'.$identifier]->version += 0.01;
			$date = date($_SESSION['DefaultDateFormat']);
		     /*Update the purchase order header with any changes */
			
                   $ModifyOrderNumber = $_REQUEST['ModifyOrderNumber']; 
	        	   $sql = "UPDATE purchorders SET
			                   supplierno ='" . $supplier . "' ,
					           comments= '" . $_SESSION['PO'.$identifier]->Comments . "',
					           initiator='" . $_SESSION['PO'.$identifier]->Initiator . "',
					           requisitionno='" . $_SESSION['PO'.$identifier]->RequisitionNo . "',
					           intostocklocation='" . $_SESSION['PO'.$identifier]->Location . "',
					           deladd1='" . $_SESSION['PO'.$identifier]->DelAdd1 . "',
					           deladd2='" . $_SESSION['PO'.$identifier]->DelAdd2 . "',
					           deladd3='" . $_SESSION['PO'.$identifier]->DelAdd3 . "',
					           deladd4='" . $_SESSION['PO'.$identifier]->DelAdd4 . "',
					           deladd5='" . $_SESSION['PO'.$identifier]->DelAdd5 . "',
					           deladd6='" . $_SESSION['PO'.$identifier]->DelAdd6 . "',
					           version='" .  $_SESSION['PO'.$identifier]->version . "',
					           realorderno='" . $_SESSION['PO'.$identifier]->OrderNo2 . "',
					           revised='" . FormatDateForSQL($date) . "',
					           deliveryby='" . $_SESSION['PO'.$identifier]->deliveryby . "',
					           deliverydate='" . FormatDateForSQL($_SESSION['PO'.$identifier]->deliverydate) . "'
		     		           WHERE orderno = '" . $ModifyOrderNumber ."'";
			$ErrMsg =  _('The purchase order could not be updated because');
			$DbgMsg = _('The SQL statement used to update the purchase order header record, that failed was');
			//$result =DB_query($sql,$db,$ErrMsg,$DbgMsg,true);		
			/*Now Update the purchase order detail records */
			
			if($result ==true)
			{
			 $del_sql="DELETE FROM purchorderdetails WHERE orderno='" . $ModifyOrderNumber . "'";
			 $del_result = DB_query($del_sql,$db);
			 if($del_sql ==true)
			 {		
		    		  
			 foreach ($_POST['Rate'] as $key => $value) {
		   $Update_sql = "INSERT INTO purchorderdetails (
							 orderno,
							 itemcode,
							 deliverydate,
							 itemdescription,
							 quatity1,
							 Rate1,
							 Rate,
							 quatity,
							 Discount,
							 Sub_total,
							 Lead_Time,
							 Pre_Delevery_Ins,
							 Specification,
							 Quantum,
							 Product_Cost_Without_Taxes,
							 Total_Charges_Cost,
							 grand_total_amount,
							 subtotal_amount)
					VALUES (
							' " .$ModifyOrderNumber . "',
							'" .  $_POST['ProductID'][$key] . "',
							'" .  $_POST['deliverydate'][$key] . "',
							'" .  $_POST['ProductDes'][$key] . "',
							'" .  $POLine->nw. "',
							'" .  $POLine->nw. "',
							'" .  $_POST['Rate'][$key] . "',
							'" .  $_POST['quantity'][$key] . "',
							'" .  $_POST['Discount'][$key] . "',
							'" .  $_POST['NetRate'][$key] . "',
							'" .  $_POST['LeadTime'][$key] . "',
							'" .  $_POST['Specification'][$key] . "',
							'" .  $_POST['Quantum'][$key] . "',
							'" .  $_POST['Quantum'][$key] . "',
							'',
							'',
							'',
							'')";
					$ErrMsg =_('One of the purchase order detail records could not be inserted into the database because');
					$DbgMsg =_('The SQL statement used to insert the purchase order detail record and failed was');
					$Update_result =DB_query($Update_sql,$db,$ErrMsg,$DbgMsg);
					//echo "<pre>";print_r($db);
					/*$sql = "update purchorderdetails SET grand_total_amount = '" . $_POST['TWT']. "' where orderno = '" . $_SESSION['PO'.$identifier]->OrderNo ."'";							
					$result =DB_query($sql,$db,$ErrMsg,$DbgMsg,true);*/
					}
					
			}
			
			}

			 echo '<br><br>';
		     prnMsg(_('Purchase order') . ' ' . $ModifyOrderNumber . ' ' . _('has been updated'),'success');
		     if ($_SESSION['PO'.$identifier]->AllowPrintPO==1){
			 //    echo '<br><a target="_blank" href="'.$rootpath.'/PO_PDFPurchOrder.php?' . SID . '&OrderNo=' . $_SESSION['PO'.$identifier]->OrderNo . '">' . _('Print Purchase Order') . '</a>';
		     }
		/*end of if its a new order or an existing one */

		$sql = 'COMMIT';
		$Result = DB_query($sql,$db);
		
		// Updating purchase orders taxes 
			           
				       $Tax_sql="DELETE FROM purchordertax WHERE orderno='" . $ModifyOrderNumber . "'";
						$ErrMsg =  _('The purchase order could not be deleted because');
						$DbgMsg = _('The SQL statement used to delete the purchase order header record, that failed was');
						$Tax_result = DB_query($Tax_sql,$db,$ErrMsg,$DbgMsg);
										
				foreach ($_POST['taxDescName_'] as $k => $v) {
				
			 	 $chkSql = "select count(*) as `totCount` from purchordertax 
						   where orderno = '". $ModifyOrderNumber ."' and taxgroupid = ".$v;
				$chkresult =DB_query($chkSql,$db,$ErrMsg,$DbgMsg,true);		
				$chkrow=DB_fetch_array($chkresult);
				if($chkrow['totCount']>0){	
				  $sql = "UPDATE purchordertax SET
							tax = '" . $_POST['tax_qty'][$k]. "' ,
							amount='" . $_POST['tax_percentage_'][$k] . "',
							taxgroupid=" . $_POST['taxDescName_'][$k] . ",
							Product_Cost_With_Taxes='".$_POST['TWT']."'
							WHERE orderno = '" . $ModifyOrderNumber ."' and taxgroupid = ".$_POST['taxDescName_'][$k]; 
				}else{
				 $sql = "insert into purchordertax SET
							tax = '" . $_POST['tax_qty'][$k]. "' ,
							amount='" . $_POST['tax_percentage_'][$k] . "',
							taxgroupid=" . $_POST['taxDescName_'][$k] . ",
							Product_Cost_With_Taxes='".$_POST['TWT']."',
							orderno = '". $ModifyOrderNumber ."'";
				}
					$result =DB_query($sql,$db,$ErrMsg,$DbgMsg,true);	
					
					
					 $ordersql = "update purchorderdetails SET
							Product_Cost_Without_Taxes = '" . $_POST['TWT']. "',
							subtotal_amount='".$_POST['Total']."'									
							where orderno = '". $ModifyOrderNumber ."'";					
					$result =DB_query($ordersql,$db,$ErrMsg,$DbgMsg,true);
				
			}
			
			$PO_chargesql="DELETE FROM po_charge WHERE orderno='" . $ModifyOrderNumber . "'";
			$ErrMsg =  _('The purchase order could not be deleted because');
			$DbgMsg = _('The SQL statement used to delete the purchase order header record, that failed was');
			$PO_result = DB_query($PO_chargesql,$db,$ErrMsg,$DbgMsg);
				 		
		
		  $pocount = $_POST['countcharges'];
		
		for($chg=1;$chg<$pocount; $chg++)
		{
		  $chkswasql = "insert into po_charge (id, 
											ch_name, 
											Inclusive, 
											As_Per_Actual, 
											charges, 
											charges_Amount, 
											Orderno 
											) 
											Values(NULL,
											'" . $_POST['desc_'.$chg.'']."',
											'" . $_POST['Charge_'.$chg.'']."',
											'" . $_POST['AsPerActual_'.$chg.'']."',
											'" . $_POST[''.$chg.'']."',
											'".  $_POST['actual_'.$chg.'']."', 
											'" . $ModifyOrderNumber ."')";
		$chkswaresult =DB_query($chkswasql,$db,$ErrMsg,$DbgMsg,true);
		}
		
		 $prodsql = "update purchorderdetails SET
							Total_Charges_Cost = '" . $_POST['TotalCharge']. "',
							grand_total_amount = '" . $_POST['GrandTotal']. "' 									
							where orderno = '" . $ModifyOrderNumber ."'";					
					$prodresult =DB_query($prodsql,$db,$ErrMsg,$DbgMsg,true);
			
		unset($_SESSION['PO'.$identifier]); /*Clear the PO data to allow a newy to be input*/
		
		include('includes/footer.inc');
		exit;
	} /*end if there were no input errors trapped */
} /* end of the code to do transfer the PO object to the database  - user hit the place PO*/


//////////////////////////////Show Dispaly quatation Charge whit tax Item By Amit Kumar ///////////////////////////////////

/*if (isset($_POST['Search'])){/*  /*ie seach for stock items */

/*	If ($_POST['Keywords'] AND $_POST['StockCode']) {
		$msg=_('Stock description keywords have been used in preference to the Stock code extract entered');
	}
	If ($_POST['Keywords']) {
		//insert wildcard characters in spaces

		$i=0;
		$SearchString = '%';
		while (strpos($_POST['Keywords'], ' ', $i)) {
			$wrdlen=strpos($_POST['Keywords'],' ',$i) - $i;
			$SearchString=$SearchString . substr($_POST['Keywords'],$i,$wrdlen) . '%';
			$i=strpos($_POST['Keywords'],' ',$i) +1;
		}
		$SearchString = $SearchString. substr($_POST['Keywords'],$i).'%';

		if ($_POST['StockCat']=='All'){
			$sql = "SELECT stockmaster.stockid,
					stockmaster.description,
					stockmaster.units
				FROM stockmaster INNER JOIN stockcategory
				ON stockmaster.categoryid=stockcategory.categoryid
				WHERE stockmaster.mbflag!='D'
				AND stockmaster.mbflag!='A'
				AND stockmaster.mbflag!='K'
				and stockmaster.discontinued!=1
				AND stockmaster.description " . LIKE . " '$SearchString'
				ORDER BY stockmaster.stockid";
		} else {
			$sql = "SELECT stockmaster.stockid,
					stockmaster.description,
					stockmaster.units
				FROM stockmaster INNER JOIN stockcategory
				ON stockmaster.categoryid=stockcategory.categoryid
				WHERE stockmaster.mbflag!='D'
				AND stockmaster.mbflag!='A'
				AND stockmaster.mbflag!='K'
				and stockmaster.discontinued!=1
				AND stockmaster.description " . LIKE . " '$SearchString'
				AND stockmaster.categoryid='" . $_POST['StockCat'] . "'
				ORDER BY stockmaster.stockid";
		}

	} elseif ($_POST['StockCode']){

		$_POST['StockCode'] = '%' . $_POST['StockCode'] . '%';

		if ($_POST['StockCat']=='All'){
			$sql = "SELECT stockmaster.stockid,
					stockmaster.description,
					stockmaster.units
				FROM stockmaster INNER JOIN stockcategory
				ON stockmaster.categoryid=stockcategory.categoryid
				WHERE stockmaster.mbflag!='D'
				AND stockmaster.mbflag!='A'
				AND stockmaster.mbflag!='K'
				and stockmaster.discontinued!=1
				AND stockmaster.stockid " . LIKE . " '" . $_POST['StockCode'] . "'
				ORDER BY stockmaster.stockid";
		} else {
			$sql = "SELECT stockmaster.stockid,
					stockmaster.description,
					stockmaster.units
				FROM stockmaster INNER JOIN stockcategory
				ON stockmaster.categoryid=stockcategory.categoryid
				WHERE stockmaster.mbflag!='D'
				AND stockmaster.mbflag!='A'
				AND stockmaster.mbflag!='K'
				and stockmaster.discontinued!=1
				AND stockmaster.stockid " . LIKE . " '" . $_POST['StockCode'] . "'
				AND stockmaster.categoryid='" . $_POST['StockCat'] . "'
				ORDER BY stockmaster.stockid";
		}

	} else {
		if ($_POST['StockCat']=='All'){
			$sql = "SELECT stockmaster.stockid,
					stockmaster.description,
					stockmaster.units
				FROM stockmaster INNER JOIN stockcategory
				ON stockmaster.categoryid=stockcategory.categoryid
				WHERE stockmaster.mbflag!='D'
				AND stockmaster.mbflag!='A'
				AND stockmaster.mbflag!='K'
				and stockmaster.discontinued!=1
				ORDER BY stockmaster.stockid";
		} else {
			$sql = "SELECT stockmaster.stockid,
					stockmaster.description,
					stockmaster.units
				FROM stockmaster INNER JOIN stockcategory
				ON stockmaster.categoryid=stockcategory.categoryid
				WHERE stockmaster.mbflag!='D'
				AND stockmaster.mbflag!='A'
				AND stockmaster.mbflag!='K'
				and stockmaster.discontinued!=1
				AND stockmaster.categoryid='" . $_POST['StockCat'] . "'
				ORDER BY stockmaster.stockid";
		}
	}

	$ErrMsg = _('There is a problem selecting the part records to display because');
	$DbgMsg = _('The SQL statement that failed was');
	$SearchResult = DB_query($sql,$db,$ErrMsg,$DbgMsg);

	if (DB_num_rows($SearchResult)==0 && $debug==1){
		prnMsg( _('There are no products to display matching the criteria provided'),'warn');
	}
	if (DB_num_rows($SearchResult)==1){

		$myrow=DB_fetch_array($SearchResult);
		$_GET['NewItem'] = $myrow['stockid'];
		DB_data_seek($SearchResult,0);*/
	//}

//} //end of if search

/* Always do the stuff below if not looking for a supplierid */

if(isset($_GET['Delete'])){
	if($_SESSION['PO'.$identifier]->Some_Already_Received($_POST['LineNo'])==0){
		$_SESSION['PO'.$identifier]->LineItems[$_GET['Delete']]->Deleted=True;
		include ('includes/PO_UnsetFormVbls.php');
	} else {
		prnMsg( _('This item cannot be deleted because some of it has already been received'),'warn');
	}
}


if (isset($_POST['LookupPrice']) and isset($_POST['StockID2'])){
	$sql = "SELECT purchdata.price,
			purchdata.conversionfactor,
			purchdata.supplierdescription
		FROM purchdata
		WHERE  purchdata.supplierno = '" . $_SESSION['PO'.$identifier]->SupplierID . "'
		AND purchdata.stockid = '". strtoupper($_POST['StockID2']) . "'";

	$ErrMsg = _('The supplier pricing details for') . ' ' . strtoupper($_POST['StockID']) . ' ' . _('could not be retrieved because');
	$DbgMsg = _('The SQL used to retrieve the pricing details but failed was');
	$LookupResult = DB_query($sql,$db,$ErrMsg,$DbgMsg);

	if (DB_num_rows($LookupResult)==1){
		$myrow = DB_fetch_array($LookupResult);
		$_POST['Price'] = $myrow['price']/$myrow['conversionfactor'];
	} else {
		prnMsg(_('Sorry') . ' ... ' . _('there is no purchasing data set up for this supplier') . '  - ' . $_SESSION['PO'.$identifier]->SupplierID . ' ' . _('and item') . ' ' . strtoupper($_POST['StockID']),'warn');
	}
}

if (isset($_POST['UpdateLine'])){
	$AllowUpdate=true; /*Start assuming the best ... now look for the worst*/

	if ($_POST['Qty']==0 OR $_POST['Price'] < 0){
		$AllowUpdate = false;
		prnMsg( _('The Update Could Not Be Processed') . '<br>' . _('You are attempting to set the quantity ordered to zero, or the price is set to an amount less than 0'),'error');
	}

	if ($_SESSION['PO'.$identifier]->LineItems[$_POST['LineNo']]->QtyInv > $_POST['Qty'] OR $_SESSION['PO'.$identifier]->LineItems[$_POST['LineNo']]->QtyReceived > $_POST['Qty']){
		$AllowUpdate = false;
		prnMsg( _('The Update Could Not Be Processed') . '<br>' . _('You are attempting to make the quantity ordered a quantity less than has already been invoiced or received this is of course prohibited') . '. ' . _('The quantity received can only be modified by entering a negative receipt and the quantity invoiced can only be reduced by entering a credit note against this item'),'error');
	}

	if ($_SESSION['PO'.$identifier]->GLLink==1) {
	/*Check for existance of GL Code selected */
		$sql = 'SELECT accountname 
				FROM chartmaster 
				WHERE accountcode =' .  $_SESSION['PO'.$identifier]->LineItems[$_POST['LineNo']]->GLCode;
		$ErrMsg = _('The account name for') . ' ' . $_POST['GLCode'] . ' ' . _('could not be retrieved because');
		$DbgMsg = _('The SQL used to retrieve the account details but failed was');
		$GLActResult = DB_query($sql,$db,$ErrMsg,$DbgMsg);
		if (DB_error_no($db)!=0 OR DB_num_rows($GLActResult)==0){
			$AllowUpdate = false;
			prnMsg( _('The Update Could Not Be Processed') . '<br>' . _('The GL account code selected does not exist in the database see the listing of GL Account Codes to ensure a valid account is selected'),'error');
		} else {
			$GLActRow = DB_fetch_row($GLActResult);
			$GLAccountName = $GLActRow[0];
		}
	}

	include ('PO_Chk_ShiptRef_JobRef.php');

	if (!isset($_POST['JobRef'])) {
		$_POST['JobRef']='';
	}

	if ($AllowUpdate == true) {

		$_SESSION['PO'.$identifier]->update_order_item(
					$_POST['LineNo'],
					$_POST['Qty'],
					$_POST['Price'],
					$_POST['ItemDescription'],
					$_POST['GLCode'],
					$GLAccountName,
					$_POST['ReqDelDate'],
					$_POST['ShiptRef'],
					$_POST['JobRef'],
					$_POST['itemno'],
					$_SESSION['PO'.$identifier]->LineItems[$_POST['LineNo']]->uom,
					$_POST['suppliers_partno'],
					$_POST['Qty']*$_POST['Price'],
					$_POST['package'],
					$_POST['pcunit'],
					$_POST['nw'],
					$_POST['gw'],
					$_POST['cuft'],
					$_POST['Qty'],
					$_POST['Qty']*$_POST['Price']
					);

		include ('includes/PO_UnsetFormVbls.php');
	}
}

if (isset($_POST['EnterLine'])){ /*Inputs from the form directly without selecting a stock item from the search */

	$AllowUpdate = true; /*always assume the best */

	if (!is_numeric($_POST['Qty'])){
		$AllowUpdate = false;
		prnMsg( _('Cannot Enter this order line') . '<br>' . _('The quantity of the order item must be numeric'),'error');
	}
	if ($_POST['Qty']<0){
		$AllowUpdate = false;
		prnMsg( _('Cannot Enter this order line') . '<br>' . _('The quantity of the ordered item entered must be a positive amount'),'error');
	}
	if (!is_numeric($_POST['Price'])){
		$AllowUpdate = false;
		prnMsg( _('Cannot Enter this order line') . '<br>' . _('The price entered must be numeric'),'error');
	}
	if (!is_date($_POST['ReqDelDate'])){
// mark on 081013
		$AllowUpdate = False;
		prnMsg( _('Cannot Enter this order line') . '</b><br>' . _('The date entered must be in the format') . ' ' . $_SESSION['DefaultDateFormat'], 'error');
	}

//	include ('PO_Chk_ShiptRef_JobRef.php');

 /*Then its not a stock item */

		/*need to check GL Code is valid if GLLink is active */
		if ($_SESSION['PO'.$identifier]->GLLink==1){

			$sql = 'SELECT accountname 
					FROM chartmaster 
					WHERE accountcode =' . (int) $_POST['GLCode'];
			$ErrMsg =  _('The account details for') . ' ' . $_POST['GLCode'] . ' ' . _('could not be retrieved because');
			$DbgMsg =  _('The SQL used to retrieve the details of the account, but failed was');
			$GLValidResult = DB_query($sql,$db,$ErrMsg,$DbgMsg,false,false);
			if (DB_error_no($db) !=0) {
				$AllowUpdate = false;
				prnMsg( _('The validation process for the GL Code entered could not be executed because') . ' ' . DB_error_msg($db), 'error');
				if ($debug==1){
					prnMsg (_('The SQL used to validate the code entered was') . ' ' . $sql,'error');
				}
				include('includes/footer.inc');
				exit;
			}
			if (DB_num_rows($GLValidResult) == 0) { /*The GLCode entered does not exist */
				$AllowUpdate = false;
				prnMsg( _('Cannot enter this order line') . ':<br>' . _('The general ledger code') . ' - ' . $_POST['GLCode'] . ' ' . _('is not a general ledger code that is defined in the chart of accounts') . ' . ' . _('Please use a code that is already defined') . '. ' . _('See the Chart list from the link below'),'error');
			} else {
				$myrow = DB_fetch_row($GLValidResult);
				$GLAccountName = $myrow[0];
			}
		} /* dont bother checking the GL Code if there is no GL code to check ie not linked to GL */
		else {
			$_POST['GLCode']=0;
		}
		if (strlen($_POST['ItemDescription'])<=3){
			$AllowUpdate = false;
			prnMsg(_('Cannot enter this order line') . ':<br>' . _('The description of the item being purchase is required where a non-stock item is being ordered'),'warn');
		}

		if ($AllowUpdate == true){
		  $_SESSION['PO'.$identifier]->add_to_order ($_SESSION['PO'.$identifier]->LinesOnOrder+1,
						'',
						0, /*Serialised */
						0, /*Controlled */
						$_POST['Qty'],
						$_POST['ItemDescription'],
						$_POST['Price'],
						_('each'),
						$_POST['GLCode'],
						$_POST['ReqDelDate'],
						$_POST['ShiptRef'],
						$_POST['JobRef'],
						0,
						0,
						$GLAccountName,
						2,
						$_POST['itemno'],						
						$_POST['uom'],
						$_POST['suppliers_partno'],
						$_POST['subtotal_amount'],
						$_POST['package'],
						$_POST['pcunit'],
						$_POST['nw'],
						$_POST['gw'],
						$_POST['cuft'],
						$_POST['total_quantity'],
						$_POST['total_amount']
						);
		   include ('includes/PO_UnsetFormVbls.php');
		}
	}
 /*end if Enter line button was hit */

/*if (isset($_POST['NewItem'])){}*/ /* end of if its a new item */

/* This is where the order as selected should be displayed  reflecting any deletions or insertions*/

echo "<form name=form1 action='" . $_SERVER['PHP_SELF'] . "?" . SID . "identifier=".$identifier. "&suppid=".$supplier. "&final_quat=".$final_qtation. "&ModifyOrderNumber=".$ModifyOrderNumber."' method=post>";


if (isset($_POST['NonStockOrder'])) {
	echo '<br><table><tr><td>'._('Description of Item').'</td>';
	echo '<td><input type=text name=ItemDescription size=40></td></tr>';
	echo '<tr><td>'._('General Ledger Code').'</td>';
	echo '<td><select name="GLCode">';
	$sql='SELECT 
			accountcode, 
			accountname 
		  FROM chartmaster 
		  ORDER BY accountcode ASC';
	$result=DB_query($sql, $db);
	while ($myrow=DB_fetch_array($result)) {
		echo '<option value="'.$myrow['accountcode'].'">'.$myrow['accountcode'].' - '.$myrow['accountname'].'</option>';
	}
	echo '</td></tr>';
	echo '<tr><td>'._('Quantity to purchase').'</td>';
	echo '<td><input type=text class=number name=Qty size=10></td></tr>';
	echo '<tr><td>'._('Price per item').'</td>';
	echo '<td><input type=text class=number name=Price size=10></td></tr>';
	echo '<tr><td>'._('Delivery Date').'</td>';
	echo '<td><input type=text class=date alt="'.$_SESSION['DefaultDateFormat'].'" name=ReqDelDate size=11
			value="'.$_SESSION['PO'.$identifier]->deliverydate .'"></td></tr>';
	echo '</table>';
	echo '<input type=submit name="EnterLine" value="Enter Item">';
}

echo '<hr>';

if(!isset($_GET['Edit']) || !isset($_GET['suppid']) && (!isset($_GET['final_quat'])))
{
echo '<br><div align="center"><b>'._('Update  Order Summary') . '</b></div><br/><br/>';

function getTaxInformation($supplier, $final_qtation, $ModifyOrderNumber){
   global $db;

  $sql="select taxauthorities.taxid, taxauthorities.description, taxgrouptaxes.*,suppliers.vendor_code from suppliers
INNER JOIN taxgroups on taxgroups.taxgroupid = suppliers.tax_group
INNER JOIN taxgrouptaxes on taxgrouptaxes.taxgroupid = taxgroups.taxgroupid
INNER JOIN taxauthorities on taxauthorities.taxid = taxgrouptaxes.taxauthid
where suppliers.vendor_code='".$supplier."' ";
	  $result =DB_query($sql,$db);
	  $i=0;
	while($myrow = DB_fetch_row($result))
	{
	
	
	    $TaxID[$i] = $myrow[0];
		$TaxDesc[$i] = $myrow[1];
		$TaxGroupId[$i] = $myrow[2];
		$CalculationOrder[$i] = $myrow[4];
     $SSql = "select * from purchordertax Where orderno ='".$ModifyOrderNumber."' AND taxgroupid='".$TaxID[$i]."'";
		 $Seleresult =DB_query($SSql,$db);
		 $myselectrow = DB_fetch_row($Seleresult);
		
		echo '<tr><td align="right" style="text-align:right;"  colspan="5">'.$TaxDesc[$i].'</td><td>
		<input type="text" name="tax_qty['.$i.']" id="'.$TaxDesc[$i].'" size="6" onblur="TaxAmount(this.value,\''.$TaxDesc[$i].'\')" 
		value="'.$myselectrow[2].'">
		<input type="hidden" name="taxDescName_['.$i.']" value="'.$TaxID[$i].'"> %=
		 
		 <input type="text" name="tax_percentage_['.$i.']" size="5"  id="tax_'.$TaxDesc[$i].'"  
		 value="'.$myselectrow[3].'" readonly>
		 <input type="hidden" name="counttax" size="5" value="'.$i.'" >';
		echo '</td><td colspan="6">&nbsp;</td></tr>';
		$i++;
	}
	return $suplierData;
}

	 echo "<br/>";
           $sql="SELECT *FROM purchorderdetails WHERE purchorderdetails.orderno='". $ModifyOrderNumber ."'";
				 $result=DB_query($sql, $db);
				 $myrow=DB_fetch_array($result);
				 $requisition=$myrow['pr_no'];
				 echo'<table width="80%" border="1">
				 <tr>
				<th>'."Qty".'</th>
				<th>'."Prod. Desc.".'</th>
				<th>'."Prod. ID".'</th>
				<th>'."Rate".'</th>
				 <th>'."Discount".'</th>
				<th>'."SubTotal".'</th>
				<th>'."Lead Time".'</th>
				<th>'."Pre Delevery Ins.".'</th>
				<th>'."Specification".'</th>
				<th>'."Quantum".'</th></tr>';
  
            $vend_sql="SELECT venderquotations.id, 
	                   venderquotations.total_amt, 
					   venderquotations.amtwithtax, 
					   venderquotations.totalcharge, 
					   venderquotations.grand_total 
					   FROM venderquotations 
					   WHERE id='".$final_qtation."'";
					  $result_vend=DB_query($vend_sql,$db);
					  $myrowvender=DB_fetch_array($result_vend);
					  $totalcharges = $myrowvender['totalcharge'];
				      $grandtotal = $myrowvender['grand_total']; 
				      $totalamount = $myrowvender['total_amt'];
					  
				      $sql="Select * FROM  purchorderdetails  WHERE orderno='".$ModifyOrderNumber."'";
					  $result=DB_query($sql,$db);
					  
					   $i=1;
  while($myrow=DB_fetch_array($result))
     {
	                  $Product_Cost_Without_Taxes = $myrow['Product_Cost_Without_Taxes'];
	                  $totalcharges = $myrow['Total_Charges_Cost'];
				      $grandtot = $myrow['grand_total_amount']; 
				      $totalamount = $myrow['subtotal_amount'];
					  
	   echo '<tr><td><input type="text" name="quantity['.$i.']" size="5" value="'.$myrow['quatity'].'" id="Quantity_'.$i.'" >
	   <input type="text" name="Qty'.$myrow['prod_id'].'" size="5" value="'.$myrow['quatity'].'" id="Qty_'.$i.'" ></td>';
	   echo '<td><input type="text" name="ProductDes['.$i.']" size="20" value="'.$myrow['itemdescription'].'" readonly></td>';
	   echo '<td><input type="text" name="ProductID['.$i.']" size="10" value="'.$myrow['itemcode'].'" readonly>
	   <input type="hidden" name="deliverydate['.$i.']" size="10" value="'.$myrow['deliverydate'].'"></td>';
	   echo '<td><input type="text" name="Rate['.$i.']" id="Rate_'.$i.'"  value="'.$myrow['Rate'].'" size="6" /></td>';
	   if($myrow['discount_type']=="PercentAmt")
	     {echo '<td><input type="text" name="Discount['.$i.']" id="Discount_'.$i.'" value="'.$myrow['Discount'].'" onblur="DiscountAmount(this.value,'.$i.')" size="6" /></td>';}
	   else {echo '<td><input type="text" name="Discount['.$i.']" id="Discount_'.$i.'" value="'.$myrow['Discount'].'" onblur="DiscountAmount(this.value,'.$i.')" size="6" /></td>';}	 
	   echo '<td><input type="text" id="NetRate_'.$i.'" name="NetRate['.$i.']" value="'.$myrow['Sub_total'].'" size="8" readonly/></td>';
	   echo '<td><input type="text" name="LeadTime['.$i.']" value="'.$myrow['Lead_Time'].'" size="8" /></td>';
	   echo '<td><input type="text" name="PreIns['.$i.']" value="'.$myrow['Pre_Delevery_Ins'].'" size="20" /></td>';
	   echo '<td><input type="text" name="Specification['.$i.']" value="'.$myrow['Specification'].'" size="15" /></td>';
	   echo '<td><input type="text" name="Quantum['.$i.']" value="'.$myrow['Quantum'].'" size="10" /></td>';
	   $i++;
	 }
	echo "<input type='hidden' name='PO_count' value='".$i."'>";
echo  '<tr><td align="right" style="text-align:right;" colspan=6><B>'."Product Cost Without Taxes".'</B></td><td><input type="text" value="'.$totalamount.'" name="Total" id="Total" size="8" readonly></td>';

getTaxInformation($supplier, $final_qtation, $ModifyOrderNumber);
echo  '<tr><td align="right" style="text-align:right;" colspan=5><B>'."Product Cost With Taxes".'</B></td><td><input type="text" name="TWT" id="TWT"  value="'.$Product_Cost_Without_Taxes.'" size="8" readonly></td><td align="right" style="text-align:right;" colspan=5>&nbsp;</td><td>&nbsp;</td></tr>';  
echo '</table>';
echo ' <table width="80%" border="1">
					<tr>
					  <th>'."Description".'</th>
					  <th>'."Inclusive".'</th>
					  <th>'."As Per Actual".'</th>
					 <th>'."Amount".'</th>
					</tr>';
				$result=DB_query('SELECT Chargesid, Chargesdescription FROM inclusivecharge',$db);
				$CR=1;
				while($myrow=DB_fetch_array($result))
				  {
				      $chargename = $myrow['Chargesdescription'];
				      $sqlprt = 'select * from po_charge Where ch_name="'.$chargename.'" AND Orderno="'.$ModifyOrderNumber.'"';
					  $sqlprt_result=DB_query($sqlprt,$db);
					  $mycols=DB_fetch_array($sqlprt_result);
					/* while($mycols=DB_fetch_array($sqlprt_result))
					  {*/
				  
					  echo '<tr><th>'.$myrow['Chargesdescription'].'</th><input type="hidden" name="desc_'.$myrow['Chargesid'].'" value="'.$myrow['Chargesdescription'].'">
								<td width="10%">
								<select name="Charge_'.$myrow['Chargesid'].'" id="Charge_'.$myrow['Chargesid'].'" onchange="ChargeAmount(this.value,\''.$myrow['Chargesid'].'\')">
										<option value="YES">'."YES".'</option>
										<option value="NO">'."NO".'</option>
									</select>
								</td>
								<td width="10%">
									<select name="AsPerActual_'.$myrow['Chargesid'].'" id="AsPerActual_'.$myrow['Chargesid'].'">
										<option value="Amount">'."Amount".'</option>
										<option value="PercentAmt">'."PercentAmt".'</option>
									</select>
								 </td>
								 <td>
									<input name="'.$myrow['Chargesid'].'" value="'.$mycols['charges'].'" id="'.$myrow['Chargesid'].'" type="text" size="8" onblur="ChargeCalculater(this.value,\''.$myrow['Chargesid'].'\')">'."=".'
									<input name="actual_'.$myrow['Chargesid'].'" value="'.$mycols['charges_Amount'].'" id="actual_'.$myrow['Chargesid'].'" type="text" size="8" readonly></td>
							</tr>';
							
						//}
						 $CR++;
				  }	 
				  
			echo '<input type="hidden" name="countcharges" value="'.$CR.'"></td></tr>';
			echo  '<tr><td align="right" style="text-align:right;"><B>'."Total Charges Cost".'</B></td><td><input type="text" name="TotalCharge" value="'.$totalcharges.'"  id="TotalCharge" size="8" onblur="FinalGrandTotal(this.value)" readonly></td>
			<td align="right" style="text-align:right;" colspan=2></td>
			</tr>'; 
			echo  '<tr><td align="right" style="text-align:right;"><B>'."Grand Total".'</B></td><td><input type="text" value="'.$grandtot.'"  name="GrandTotal" id="GrandTotal" size="8" readonly></td>
			<td align="right" style="text-align:right;" colspan=2></td>
			</tr></table>';
	echo '<br><div class="centre">';
	echo '<br><input type="submit" name="Commit" value="Process Order">
	<input type="hidden" name="ModifyOrderNumber" value="'. $ModifyOrderNumber .'">';
}


if (isset($SearchResult)) {


	echo "<table cellpadding=1 colspan=7 border=1>";

	$tableheader = "<tr>
			<th>" . _('Code')  . "</th>
			<th>" . _('Description') . "</th>
			<th>" . _('Units') . "</th>
			<th><a href='#end'>"._('Go to end of list')."</a></th>
			</tr>";
	echo $tableheader;

	$j = 1;
	$k=0; //row colour counter

	while ($myrow=DB_fetch_array($SearchResult)) {

		if ($k==1){
			echo '<tr class="EvenTableRows">';
			$k=0;
		} else {
			echo '<tr class="OddTableRows">';
			$k=1;
		}

		$filename = $myrow['stockid'] . '.jpg';
		if (file_exists( $_SESSION['part_pics_dir'] . '/' . $filename) ) {

			$ImageSource = '<img src="'.$rootpath . '/' . $_SESSION['part_pics_dir'] . '/' . $myrow['stockid'] . 
				'.jpg" width="50" height="50">';

		} else {
			$ImageSource = '<i>'._('No Image').'</i>';
		}

			$uomsql='SELECT conversionfactor, suppliersuom
					FROM purchdata
					WHERE supplierno="'.$_SESSION['PO'.$identifier]->SupplierID.'"
					AND stockid="'.$myrow['stockid'].'"';

			$uomresult=DB_query($uomsql, $db);
			if (DB_num_rows($uomresult)>0) {
				$uomrow=DB_fetch_array($uomresult);
				if (strlen($uomrow['suppliersuom'])>0) {
					$uom=$uomrow['suppliersuom'];
				} else {
					$uom=$myrow['units'];
				}
			} else {
				$uom=$myrow['units'];
			}
			printf("<td>%s</td>
			<td>%s</td>
			<td>%s</td>
			<td>%s</td>
			<td><input class='number' type='text' size=6 value=0 name='qty%s'></td>
			</tr>",
			$myrow['stockid'],
			$myrow['description'],
			$uom,
			$ImageSource,
			$myrow['stockid']);

		$PartsDisplayed++;
		if ($PartsDisplayed == $Maximum_Number_Of_Parts_To_Show){
			break;
		}
#end of page full new headings if
	}
#end of while loop
	echo '</table>';
	if ($PartsDisplayed == $Maximum_Number_Of_Parts_To_Show){

	/*$Maximum_Number_Of_Parts_To_Show defined in config.php */

		prnMsg( _('Only the first') . ' ' . $Maximum_Number_Of_Parts_To_Show . ' ' . _('can be displayed') . '. ' . 
			_('Please restrict your search to only the parts required'),'info');
	}
	echo '<a name="end"></a><br><div class="centre"><input type="submit" name="NewItem" value="Order some"></div>';
}#end if SearchResults to show

echo '<hr>';

echo '</form>';
include('includes/footer.inc');
?>
<script type="text/javascript">
var TotalPercent=0;
var TotalAmount=0;
var finalAmount=0;
function ChargeCalculater(Amt,Amtid)
  {
     var AsPerActual=document.getElementById(Amtid).value;
	 var ActualType=document.getElementById("AsPerActual_"+Amtid).value;
	 if(document.getElementById(Amtid).value !='')
	 {
	 if(ActualType=='PercentAmt')
	   {
	     var Total= document.getElementById("Total").value;
		 var charge= parseFloat(Total) * parseFloat(AsPerActual)/100;
		 TotalPercent= parseFloat(TotalPercent) + parseFloat(charge);
		 document.getElementById("actual_"+Amtid).value= charge;
	   }
	 else
	   {
	     document.getElementById("actual_"+Amtid).value=AsPerActual; 
		 TotalAmount=parseFloat(TotalAmount) + parseFloat(AsPerActual);
	   }
	    finalAmount= parseFloat(TotalAmount) + parseFloat(TotalPercent);
		//alert(finalAmount);
		//document.getElementById("TotalCharge").value=parseFloat(finalAmount);
		
		if(isNaN(finalAmount))
		{
			 var TotalCharge =document.getElementById("TotalCharge").value;
			 var AsPerActual=document.getElementById(Amtid).value;
			
			if(AsPerActual !='')
			{	
			 var finalAmountTotal2= parseFloat(AsPerActual) + parseFloat(TotalCharge);
			  document.getElementById("TotalCharge").value=finalAmountTotal2;
			}
			else
			{
			   document.getElementById("TotalCharge").value=TotalCharge;
			}
		}
		else
		{
		  document.getElementById("TotalCharge").value=parseFloat(finalAmount);
		}
		
	}
		
	return true;
  }

function FinalGrandTotal(A)
   {
      var GTWC=document.getElementById("TWT").value;
	  var FinalGT= parseFloat(GTWC) + parseFloat(A);
		if(isNaN(FinalGT))
		{
		  document.getElementById("GrandTotal").value=parseFloat(0);
		}
		else
		{
		  document.getElementById("GrandTotal").value=parseFloat(FinalGT);
		 }
		  
   }
function ChargeAmount(CA,ID)
 {
   if (CA=='NO')
     {
	   //alert(CA);
	   document.getElementById(ID).readOnly=true;
	   document.getElementById("actual_"+ID).disabled=true;
	   document.getElementById("AsPerActual_"+ID).disabled=true;
	 }
	else if (CA!='NO')
	 {
	    document.getElementById(ID).readOnly=false;
	    document.getElementById("AsPerActual_"+ID).disabled=false; 
		document.getElementById("actual_"+ID).disabled=false;
	 }    
  // alert(ID);
 }
var Total=0;
function DiscountAmount(DA,i)
{
	
	var discount_percent = document.getElementById("PerAmo_"+i).value;
	var rate = document.getElementById("Rate_"+i).value;
	var discount = document.getElementById("Discount_"+i).value;
	var quantity = document.getElementById("Quantity_"+i).value;
	var totalPrice = quantity*rate;
	if(discount_percent=='PercentAmt')
	{
		var percent = totalPrice * discount/100;
		var subTotal = totalPrice - percent;
	}
	else if(discount_percent=='Amount')
	{
		var percent = discount;
		var subTotal = totalPrice-percent;
	}
	document.getElementById("NetRate_"+i).value = subTotal;
	Total=parseFloat(Total) + parseFloat(subTotal);
	document.getElementById("Total").value=Total;
	return true;
}	

//alert(Total);
var GrandTax=0;
var GrandTotal=0;	
function TaxAmount(Tax,Name)
  {
    
	var Total=document.getElementById("Total").value;
	document.getElementById("tax_"+Name).value = Total*Tax/100;
	GrandTax=GrandTax + Total*Tax/100;
    GrandTotal = parseFloat(Total) + parseFloat(GrandTax);
	document.getElementById("TWT").value=GrandTotal;
	//alert(GrandTotal);
  }

function fillUpValueFromVendor(v){
var v = v;
return true;
//var url = "<--?php echo $rootpath;?>/VenderQutations.php?RequisitionNo=<--?php echo $_REQUEST['RequisitionNo']; ?>&vendorresult=1&vendor="+v;
// alert(url);
//location.replace(url);

}
</script>