<?php

session_start();
if($HTTP_SESSION_VARS['dbName']==""){
header("location:../index.php");
}


include("config.inc.php");
include("Functions_Sales.php");
include("function.inc.php");

$connection = mysql_connect($config['dbServer'],$config['dbUser'],$config['dbPass']) or die("Could not connect to DB");
mysql_select_db($HTTP_SESSION_VARS['dbName'],$connection) or die("Could not find DB");

//User Access
$querylog=" select ifNull(login_belongstogrp,0) As FI_BelongsToGrp from ".$HTTP_SESSION_VARS['dbLabel'].".login where user_account='".$HTTP_SESSION_VARS['useraccount']."' and Upper(Login_Schema) = Upper('".$HTTP_SESSION_VARS['dbName']."')  ";
$resultlog=mysql_query($querylog,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultlog)){
	extract($rows);
}
							
//Read From Module Table
$querymodule=" Select Module_AdditionalTaxes, ifNull(Module_NegativeQuantity,0) As Module_NegativeQuantity, ifNull(Module_rawmaterial,0) As Module_RawMaterial, ".
			 " ifNull(Module_DoubleUnit,0) As Module_DoubleUnit, ifNull(module_paymentterms,0) As Module_PaymentTerms, ".
             " ifNull(module_creditlimit,0) As Module_CreditLimit, ifNull(Module_Delivery,0) As Module_Delivery, ".
             " ifNull(module_DeliveryWithSorder,0) As Module_DeliveryWithSorder	 From Module ";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}

//Read From SalesSetup Table
$querySalesSetup="Select SalesTTC From SalesSetup";
$resultSalesSetup=mysql_query($querySalesSetup,$connection) or die(mysql_error());
while($rowSalesSetup=mysql_fetch_array($resultSalesSetup)){
	extract($rowSalesSetup);
}

//Read From Setup Table							
$querysetup= " select DecimalBase, DecimalBase1, DecimalBase2, base1, base2, grid_color1, grid_color2, ".
             " Date_Format(Setup_VatStartDate,'%Y%m%d') As Setup_VatStartDate, ifNull(Setup_VatPercentage,0) As Setup_VatPercentage from setup ";
$resultsetup=mysql_query($querysetup,$connection) or die(mysql_error());
while($rowsetup=mysql_fetch_array($resultsetup)){
	extract($rowsetup);
}


print <<<HERE
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" href="default.css" type="text/css" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

</head>
<body>
<form name='additemserials' method='post' action=''>
<input type='hidden' name='ItemSerialNo' id='ItemSerialNo' value='$ItemSerialNo' size='20' maxlength='40'/>
<input type='hidden' name='SerialId' id='SerialId' value='$SerialId' size='10' maxlength='40'/>
<input type='hidden' name='SaId' id='SaId' value='$SaId' size='10' maxlength='40'/>
<input type='hidden' name='PerPage' id='PerPage' value='$PerPage' size='10' maxlength='40'/>
<input type='hidden' name='Mode' id='Mode' value='$Mode' size='10' maxlength='40'/>		    
HERE;


if (!isset($PSaCurr)) $PSaCurr = $base1;
if (empty($PSaVatChkbx)) $PSaVatChkbx = 0;	

$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$PSaCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$PSaCurr."' )";
$result = selectData($connection, $query);
$rate_dt = $result[0];
		
$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base1."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base1."' )";
$result = selectData($connection, $query);
$rate_dt1 = $result[0];
		
$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base2."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base2."' )";
$result = selectData($connection, $query);
$rate_dt2 = $result[0];

if ($Mode == 'insert' && $ItemSerialNo != '') {

	
	$query= " Select Serial_ID, ifNull(SerialNo_Used,0), warehouse_code, ifNull(SerialNo_Quantity,1), ifNull(SerialNo_QuantitySold,0)  ".
	        " From purchasesserialno ".
			" where SerialNo_Code =  '".$ItemSerialNo."' ".
			" And Journal_Type in ('PI','DR','TR','AI','PD')";
			  
	$result = selectData($connection, $query);
	$SerialNoExists = $result[0];
	
	$IsAvailable = 1;
	$ErrorExists = 0;
	$SelectedSerialID = 0;
	$SelectedSerialQty     = 0;
	$SelectedSerialQtySold = 0;
	$SelectedItemCode      = '';
	
	if ($SerialNoExists != '') {
		if ($lstWarehouse != '' && isset($lstWarehouse)) {
		
			$sub_query= " Select SerialNo_Code  ".
						" From temp_purchasesserialno ".
						" where SerialNo_Code =  '".$ItemSerialNo."' ".
						" And Journal_Type in ('DI') ".
						" Union ".
						" Select SerialNo_Code  ".
						" From purchasesserialno ".
						" where SerialNo_Code =  '".$ItemSerialNo."' ".
						" And Journal_Type in ('DI') ";
			 //echo $sub_query; exit;	 
			$sub_result=mysql_query($sub_query,$connection)  or die(mysql_error());
			$RecCount=mysql_num_rows($sub_result);
		
			if ($RecCount == 0 || $RecCount == '') {
				$sub_query= " Select RelatedSerial_Id As Serial_ID, ifNull(SerialNo_Used,0), Purchasesserialno.warehouse_code, ifNull(SerialNo_Quantity,1), ifNull(SerialNo_QuantitySold,0) - 1 As SerialNo_QuantitySold, ".
							" purchasesserialno.Item_Code As Item_Code, 1 As OrderColumn ".
							" From purchasesserialno ".
							" Inner Join DeliveryDt on Purchasesserialno.PurchaseDt_id = DeliveryDt.DeliveryDt_ID ".
							" Where DeliveryDt.Delivery_id = '".$SaId."' ".
							" And Purchasesserialno.SerialNo_Code =  '".$ItemSerialNo."' ".
							" And Purchasesserialno.Warehouse_Code =  '".$lstWarehouse."' ".
							" And Purchasesserialno.Journal_Type = 'DI' ".
							" Union ".
							" Select Serial_ID, ifNull(SerialNo_Used,0), warehouse_code, ifNull(SerialNo_Quantity,1), ifNull(SerialNo_QuantitySold,0) As SerialNo_QuantitySold, Item_Code, 2 As OrderColumn  ".
							" From purchasesserialno ".
							" where SerialNo_Code =  '".$ItemSerialNo."' ".
							" And Warehouse_Code =  '".$lstWarehouse."' ".
							" And Journal_Type in ('PI','DR','TR','AI','PD') ".
							" Order by OrderColumn ";
							
							
				//echo $sub_query; exit;			
				$sub_result=mysql_query($sub_query,$connection)  or die(mysql_error());
				$sub_row=mysql_fetch_array($sub_result);
				$RecCount=mysql_num_rows($sub_result);
				
				if ($RecCount == 0) {
					$IsAvailable = 0;
					$message  = "Insert not allowed, Serial No (".$ItemSerialNo.") is not available in the warehouse (".$lstWarehouse.") . "; 
				}	
				else {
					
					if ($sub_row[1] == 1)
					{
						$sub_query= " Select Serial_ID, ifNull(SerialNo_Used,0), warehouse_code, ifNull(SerialNo_Quantity,1), ifNull(SerialNo_QuantitySold,0), Item_Code  ".
									" From purchasesserialno ".
									" where SerialNo_Code =  '".$ItemSerialNo."' ".
									" And Warehouse_Code =  '".$lstWarehouse."' ".
									" And ifNull(SerialNo_Used,0) = 0 ".
									" And Journal_Type in ('PI','DR','TR','AI','PD')";
						$sub_result=mysql_query($sub_query,$connection)  or die(mysql_error());
						$sub_row=mysql_fetch_array($sub_result);
						$RecCount=mysql_num_rows($sub_result);
						
						if ($RecCount == 0) {
							$IsAvailable = 0;
							$message  = "Insert not allowed, Serial No (".$ItemSerialNo.") is used in warehouse (".$lstWarehouse."). "; 
						}  else {
							$SelectedSerialID      = $sub_row[0];
							$SelectedSerialQty     = $sub_row[3];
							$SelectedSerialQtySold = $sub_row[4];
							$SelectedItemCode      = $sub_row[5];
							$IsAvailable = 1;
						}	
					
					} else {
						$SelectedSerialID      = $sub_row[0];
						$SelectedSerialQty     = $sub_row[3];
						$SelectedSerialQtySold = $sub_row[4];
						$SelectedItemCode      = $sub_row[5];
						$IsAvailable = 1;
					}	

				}	
			}
			else {
				$IsAvailable = 0;
				$message  = "Insert not allowed, serial no already invoiced. "; 
			}	
		}
		else {
			$IsAvailable = 0;
			$message  = "Insert not allowed, warehouse is empty. "; 
		}	
	}
	else {
		$IsAvailable = 0;
		$message  = "Insert not allowed, Serial No (".$ItemSerialNo.") is not available. "; 
	}
	
	
	if ($IsAvailable == 1 && $Module_DeliveryWithSorder == 1)
	{	$vSaDtItemCode = $SelectedItemCode;
				
		$query = "  Select Count(*) ".
				 "	From Temp_DeliveryDt As DeliveryDt  ".
				 "	Where DeliveryDt.Journal_Type = 'DI'  ".
				 "  And DeliveryDt.Item_Code = '".$vSaDtItemCode."' ".
				 "  And DeliveryDt.Warehouse_Code = '".$lstWarehouse."' ".
				 "  And DeliveryDt.Delivery_ID = '".$SaId."'";
		
		$result = selectData($connection, $query);
		$ItemExists = $result[0];
		
		if ($ItemExists == '') $ItemExists = 0;
		
		if ($ItemExists == 0 ){
			$message  = 'Insert not allowed, Item not available in current delivery.';
			$IsAvailable = 0;
		}	 
	}		 
	
	if ($IsAvailable == 1)
	{
		if (empty($PSaDiscountAmt))
			$PSaDiscountAmt = 0;
		if (empty($PSaDiscount))
			$PSaDiscount = 0;
				
		if (empty($PSaCostCentCode))
			$CostCentCode = 'Null';
		else
			$CostCentCode = "'".$PSaCostCentCode."'";
				
		if (empty($PSaProjectCode))
			$ProjectCode = 'Null';
		else
			$ProjectCode = "'".$PSaProjectCode."'";
			
			
		
		$vSaId   = '';
		$vSaDtId = '';
		$vSerId  = '';
		
		
		$vSaDtPriceTTC      = 0;
		$vSaDtPriceTTCBase1 = 0;
		$vSaDtPriceTTCBase2 = 0;					
		$vSaDtPrice      = 0;
		$vSaDtPriceBase1 = 0;
		$vSaDtPriceBase2 = 0;
		$vSaDtDiscAmt       = 0;
		$vSaDtDiscAmtBase1  = 0;
		$vSaDtDiscAmtBase2  = 0;
		$vSaDtDiscountPer   = 0;
		$vSaDtQty   = 0;
		$vSaDtItemCode = '';
		
		$vSaDtDirectStkDbt = '';
		$vSaDtDirectStkCrd = '';
		$vSaDtDirectStkCur = '';
		$vSaDtDiscAcc = '';
		$vSaDtItemAcc = '';
				
		$vCltTax1 = 0;
		$vCltTax2 = 0;
		$vCltTax3 = 0;
		$vCltTax4 = 0;
		$vCltTax5 = 0;
		$vSaDtTax1 = 0;
		$vSaDtTax2 = 0;
		$vSaDtTax3 = 0;
		$vSaDtTax4 = 0;
		$vSaDtTax5 = 0;	
		
		$ErrorExists = 0;
		
		//Check For Client, Salesman, Project and Costcenter Codes Before Insert
		if ($PSaCostCentCode != '') {
			$sub_query = " Select Count(Costcent_code) From Costcent ".
						 " Where Costcent_code = '".$PSaCostCentCode."'";
			$sub_result = selectData($connection, $sub_query);
			if ($sub_result[0] == 0) $ErrorExists = 1;
		}
		if ($PSaProjectCode != '') {
			$sub_query = " Select Count(Project_Code) From Project ".
						 " Where Project_Code = '".$PSaProjectCode."'";
			$sub_result = selectData($connection, $sub_query);
			if ($sub_result[0] == 0) $ErrorExists = 1;
		}
		if ($PSaClientCode != '') {
			$sub_query = " Select Count(Ledger_Number) From Clients ".
						 " Where Ledger_Number = '".$PSaClientCode."'";
			$sub_result = selectData($connection, $sub_query);
			if ($sub_result[0] == 0) $ErrorExists = 1;
		}
		if ($PSaSalesmanCode != '') {
			$sub_query = " Select Count(Ledger_Number) From Salesmen ".
						 " Where Ledger_Number = '".$PSaSalesmanCode."'";
			$sub_result = selectData($connection, $sub_query);
			if ($sub_result[0] == 0) $ErrorExists = 1;
		}
		
		if ($ErrorExists == 1) {
			$IsAvailable = 0;
			$message = 'Insert not allowed. Please check for Client/Salesman/Project/Costcenter Code.';
		}	
				
		//Insert Master Table
		if ($SaId == "" && $ErrorExists == 0){
		
			fbegin();	
			$vSaId = get_nextsequence('delivery_id','',$connection);	
			fcommit();
			
			$Acc_Query = " SELECT Sale_Acctax1, Sale_Acctax2, Sale_Acctax3, Sale_Acctax4, Sale_Acctax5, if( ifNull(CreditCurdefault,0)=1, CreditCur, '".$PSaCurr."') As CreditCur, ".
						 " CreditAccount, TipsAccount, VatAccount, CreditAccountVAT, PromotionAccount, TransportAccount ".
						 " FROM salessetup ";
					 
			$Acc_Result = selectData($connection, $Acc_Query);
			
			// Get Vat Checkbox From Client
			$query  = "SELECT ifNull(Client_VAT,0) FROM Clients WHERE Ledger_Number = '".$PSaClientCode."'";
			$result = selectData($connection, $query);
			$PSaVatChkbx = $result[0];
				 
			fbegin();
			$query = " INSERT INTO temp_deliveries (Delivery_ID, Delivery_Reference, Delivery_Date, JournalDt_ValueDate, Delivery_Remark, Client_code, Delivery_ShippedTo, Delivery_Marks, Delivery_ShippedVia, Salesman_Code, Currency_Code, ".
					 " Project_Code, Costcent_code, Delivery_Posted, Delivery_Edit, Delivery_Taxable, Delivery_TaxableBase1, Delivery_TaxableBase2, Delivery_NoneTaxable, Delivery_NoneTaxableBase1, Delivery_NoneTaxableBase2, Delivery_DiscountAmount, ".
					 " Delivery_DiscountBase1, Delivery_DiscountBase2, Delivery_DiscountPer, Delivery_VAT, Delivery_VATBase1, Delivery_VATBase2, Delivery_Total, Delivery_TotalBase1, Delivery_TotalBase2, Delivery_Confirmed, ".
					 " Delivery_Mode, Journal_Type, Journal_Id, Delivery_BelongsToGroup, Delivery_Acctax1, Delivery_Acctax2, Delivery_Acctax3, Delivery_Acctax4, Delivery_Acctax5, Delivery_CreditCur, Delivery_CreditAccount, Delivery_TipsAccount, ".
					 " Delivery_VatAccount, Delivery_CreditAccountVat, Delivery_PromotionAcc, Delivery_TransportAccount, Delivery_CREDITACCcur, Delivery_CREDITACC, Delivery_VatChkbx,Delivery_vehicleweight,Delivery_vehicleLoadweight, User_Account, Logged_Code) ".
					 " VALUES ( ".$vSaId.", Null, '".insertMySQLDate($PSaDate)."', '".insertMySQLDate($PSaMaturityDate)."', ".
					 "          '".ereg_replace("'", "\'", trim($PSaRemark))."', '".ereg_replace("'", "\'", trim($PSaClientCode))."', '".ereg_replace("'", "\'", trim($PSaDAddress))."', '".ereg_replace("'", "\'", trim($PSaVehicleNumber))."', ".
					 "          '".ereg_replace("'", "\'", trim($PSaDriverName))."', '".ereg_replace("'", "\'", trim($PSaSalesmanCode))."', '".$PSaCurr."', $ProjectCode, $CostCentCode, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ".
					 "          0, 'DI', Null, $FI_BelongsToGrp, '".$Acc_Result[0]."', '".$Acc_Result[1]."', '".$Acc_Result[2]."', '".$Acc_Result[3]."', '".$Acc_Result[4]."', '".$Acc_Result[5]."', '".$Acc_Result[6]."', '".$Acc_Result[7]."', ".
					 "          '".$Acc_Result[8]."', '".$Acc_Result[9]."', '".$Acc_Result[10]."', '".$Acc_Result[11]."', '".$Acc_Result[5]."', '".$Acc_Result[6]."', $PSaVatChkbx, '".ereg_replace("'", "\'", trim($PSaVehicleWeight))."', '".ereg_replace("'", "\'", trim($PSaVehicleLoadWeight))."', '".$HTTP_SESSION_VARS['useraccount']."', '".$HTTP_SESSION_VARS['useraccount']."' )";
						 
				 
			$result=mysql_query($query,$connection);
			//echo $query."<br>";exit;	
			
			if ($result){
				$SaId = $vSaId;
				fcommit();
			}else{
				$vSaId = "";
				$SaId  = "";
				$ErrorExists = 1;
				$message  = mysql_error(); 
				frollback();
			}
		
		}
		
		if ($SaId != ""  && $ErrorExists == 0)
		{
			$query = " UPDATE temp_deliveries SET ".
					 " Delivery_Remark =  '".ereg_replace("'", "\'", trim($PSaRemark))."', ".
					 " Delivery_Marks = '".ereg_replace("'", "\'", trim($PSaVehicleNumber))."', ".
					 " Delivery_ShippedVia = '".ereg_replace("'", "\'", trim($PSaDriverName))."', ".
					 " Project_Code = $ProjectCode, Costcent_code = $CostCentCode ".
					 " WHERE Delivery_Id = '".$SaId."' ";
			//echo $query."<br>";exit;				
			if (!updateData($connection, $query, true))		 
				$message  = mysql_error(); 	
				
				
			if ($Module_DeliveryWithSorder == 1) {
				$ordqty_query = "  Select Sum(ifNull(SorderDt.SorderDt_Quantity,0)) As QuantityOrdered ".
								"  From Temp_DeliveryDt As DeliveryDt  ".
								"  Inner Join SorderDt on SorderDt.SorderDt_ID = DeliveryDt.RelatedDt_Id  ".
								"  Where DeliveryDt.Journal_Type = 'DI'  ".
								"  And DeliveryDt.Item_Code = '".$SelectedItemCode."' ".
								"  And DeliveryDt.Warehouse_Code = '".$lstWarehouse."' ".
								"  And DeliveryDt.Delivery_ID = '".$SaId."' ".
								"  And (('".$lstItems."' != '' and  DeliveryDt.DeliveryDt_ID = '".$lstItems."') or ('".$lstItems."' = '' and 1 = 1)) ";
						  
				$delqty_query = "  Select Sum(ifNull(DeliveryDt.DeliveryDt_Quantity,0)) As QuantityDelivered ".
								"  From DeliveryDt  ".
								"  Inner Join Temp_DeliveryDt on DeliveryDt.RelatedDt_Id = Temp_DeliveryDt.RelatedDt_Id  ".
								"  Where Temp_DeliveryDt.Journal_Type = 'DI'  ".
								"  And Temp_DeliveryDt.Item_Code = '".$SelectedItemCode."' ".
								"  And Temp_DeliveryDt.Warehouse_Code = '".$lstWarehouse."' ".
								"  And Temp_DeliveryDt.Delivery_ID = '".$SaId."' ".
								"  And DeliveryDt.Journal_Type = 'DI'  ".
								"  And DeliveryDt.Delivery_ID != '".$SaId."' ".
								"  And (('".$lstItems."' != '' and  Temp_DeliveryDt.DeliveryDt_ID = '".$lstItems."') or ('".$lstItems."' = '' and 1 = 1)) ";				
							 
				$serial_query = "  Select Count(SerialNo_Code) As CountSerialNo ".
								"  From Temp_DeliveryDt As DeliveryDt  ".
								"  Left Join Temp_Purchasesserialno on DeliveryDt.DeliveryDt_ID = Temp_Purchasesserialno.PurchaseDt_ID ".
								"  And Temp_Purchasesserialno.Journal_Type = 'DI' ".
								"  Where DeliveryDt.Journal_Type = 'DI'  ".
								"  And DeliveryDt.Item_Code = '".$SelectedItemCode."' ".
								"  And DeliveryDt.Warehouse_Code = '".$lstWarehouse."' ".
								"  And DeliveryDt.Delivery_ID = '".$SaId."' ".
								"  And (('".$lstItems."' != '' and  DeliveryDt.DeliveryDt_ID = '".$lstItems."') or ('".$lstItems."' = '' and 1 = 1)) ";								
				
				//echo $ordqty_query; exit;			 
				$ordqty_result = selectData($connection, $ordqty_query);
				$delqty_result = selectData($connection, $delqty_query);
				$serial_result = selectData($connection, $serial_query);
				$ItemRemQty  = $ordqty_result[0] - $delqty_result[0];		
				$SerialCount = $serial_result[0];	

			}	
			
			if ($ItemRemQty == '') $ItemRemQty = 0;			 
			if ($SerialCount == '') $SerialCount = 0;	

			if ($Module_DeliveryWithSorder == 0 || ($Module_DeliveryWithSorder == 1 && $SerialCount < $ItemRemQty )) 
			{						 
				$sub_query = " Select DeliveryDt_ID, Item_Code, ifNull(DeliveryDt_Quantity,0) ".
							 " From Temp_DeliveryDt ".
							 " Where Item_Code = '".$SelectedItemCode."' ".
							 " And Delivery_ID = '".$SaId."'";
				$sub_result = selectData($connection, $sub_query);
				
				$vSaDtId = $sub_result[0];
				
				if ($vSaDtId == "" )
				{
					$vSaDtItemCode = $SelectedItemCode;
					$vSaDtQty      = $SelectedSerialQty;
					
					$query = " SELECT Item_Vat, ITEM_MAXQTY, Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), ifNull(Item_Unit, 0), ifNull(Item_Promotion, 0) ".
							 " FROM Items WHERE item_Code = '".$vSaDtItemCode."'";
					$result = selectData($connection, $query);
					$item_vat = $result[0];
					$Item_MaxQty = $result[1];
					$ItemGroupCode = $result[2];
					$ItemProd   = $result[3];
					$ItemTTCInc = $result[4];
					$ItemUnit   = $result[5];
					$ItemPromo  = $result[6];
					//$item_vat = $item_vat/100;
					$tax_flag = 0;
					$notax_flag = 1;
					if ($item_vat > 0){
						$tax_flag = 1;
						$notax_flag = 0;
					}	
					
					$vItemUnitCoef = 0;
					$vItemUnit2Qty = 0;
					if ($Module_DoubleUnit == 1) {
						$vItemUnitCoef = $ItemUnit;
						$vItemUnit2Qty = $vItemUnitCoef * $vSaDtQty;
					}
					
					

					if ($Module_Delivery == 0) {
						
						$query = "SELECT Client_SellingPrice FROM Clients WHERE Ledger_Number = '".$PSaClientCode."'";
						//echo "<br><br>".$query;
						$result = selectData($connection, $query);
						$c_sp = $result[0];
						
						
						
						$query = "SELECT Item_SellingPrice1, Item_SellingPrice2, Item_SellingPrice3, Item_SellingPrice4, Item_SellingPrice5, Item_SellingPrice6, ifNull(Item_Promotion, 0) FROM items WHERE Item_Code = '".$vSaDtItemCode."'";
							
						//echo "<br><br>".$query;
						$result = selectData($connection, $query);
						$i_sp = $result[0];
							
						switch ($c_sp){
							case "II":
								$i_sp = $result[1]; break;
							case "III":
								$i_sp = $result[2]; break;
							case "IV":
								$i_sp = $result[3]; break;
							case "V":
								$i_sp = $result[4]; break;
							case "VI":
								$i_sp = $result[5]; break;
						}
		
						//Setting Price For The Item
						$vSaDtPrice = $i_sp;
						
						//if item promotion the set price to zero
						if($ItemPromo == 1) $vSaDtPrice = 0;
						
						if ($SalesTTC == 1) {
							$vSaDtPriceTTC      = $vSaDtPrice;
							$vSaDtPriceTTCBase1 = ($vSaDtPriceTTC*$rate_dt)/$rate_dt1;
							$vSaDtPriceTTCBase2 = ($vSaDtPriceTTC*$rate_dt)/$rate_dt2;	

							//Added 2011/10/28
							if ($PSaVatChkbx == 1)	$vSaDtPrice = ($vSaDtPriceTTC / (1 + $item_vat/100));
							else $vSaDtPrice = $vSaDtPriceTTC;		
						
							//$vSaDtPrice      = ($vSaDtPriceTTC / (1 + $item_vat/100));
							$vSaDtPriceBase1 = ($vSaDtPrice*$rate_dt)/$rate_dt1;
							$vSaDtPriceBase2 = ($vSaDtPrice*$rate_dt)/$rate_dt2;
									
						} else	{
							$vSaDtPrice      = $vSaDtPrice;
							$vSaDtPriceBase1 = ($vSaDtPrice*$rate_dt)/$rate_dt1;
							$vSaDtPriceBase2 = ($vSaDtPrice*$rate_dt)/$rate_dt2;
							
							$vSaDtPriceTTC      = 0;
							$vSaDtPriceTTCBase1 = 0;
							$vSaDtPriceTTCBase2 = 0;
									
						}	
							
						
						// Calculation For Detail Discount Amount
						$vSaDtDiscAmt       = (($vSaDtPrice*$vSaDtQty) - ($vSaDtPrice*$vSaDtQty*$vSaDtDiscountPer/100))*$PSaDiscount;
						$vSaDtDiscAmtBase1  = ($vSaDtDiscAmt*$rate_dt)/$rate_dt1;
						$vSaDtDiscAmtBase2  = ($vSaDtDiscAmt*$rate_dt)/$rate_dt2;

						if ($Module_AdditionalTaxes == 1) {
						
							// Calculation of Item Tax Amounts
							$query = " SELECT ifNull(Client_Tax1,0), ifNull(Client_Tax2,0), ifNull(Client_Tax3,0), ifNull(Client_Tax4,0), ifNull(Client_Tax5,0) ".
									 " FROM Clients ".
									 " WHERE Ledger_number = '".$PSaClientCode."'";
												 
							$result = selectData($connection, $query);
							$vCltTax1 = $result[0];
							$vCltTax2 = $result[1];
							$vCltTax3 = $result[2];
							$vCltTax4 = $result[3];
							$vCltTax5 = $result[4];
										
							$query = " SELECT ifNull(Item_Tax1,0), ifNull(Item_Tax2,0), ifNull(Item_Tax3,0), ifNull(Item_Tax4,0), ifNull(Item_Tax5,0) ".
									 " FROM Items ".
									 " WHERE Item_Code = '".$vSaDtItemCode."'";
												 
							$result = selectData($connection, $query);

							
							if ($vCltTax1 != 0)	$vSaDtTax1 = $result[0];
							if ($vCltTax2 != 0)	$vSaDtTax2 = $result[1];
							if ($vCltTax3 != 0)	$vSaDtTax3 = $result[2];
							if ($vCltTax4 != 0)	$vSaDtTax4 = $result[3];
							if ($vCltTax5 != 0)	$vSaDtTax5 = $result[4];
								
						}
							
						
					
					} //End ($Module_Delivery == 0) 	
					
					
					// Get DirectStock Accounts
					$query = " SELECT Directstockdebit, Directstockcredit, Directstockcurrency_code, DiscountAccount, VatAccount, CreditAccountVAT, CreditAccount, PromotionAccount  ".
							 " FROM salessetup ";
									 
					$result = selectData($connection, $query);
							
					$vSaStpDirectStkDbt = $result[0];
					$vSaStpDirectStkCrd = $result[1];
					$vSaStpDirectStkCur = $result[2];	
					$vSaStpDiscAcc      = $result[3];	
					$vSaStpVatAcc       = $result[4];	
					$vSaStpCreditVatAcc = $result[5];	
					$vSaStpCreditAcc    = $result[6];	
					$vSaStpPromoAcc     = $result[7];	
							
						
					$query = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_VATAccount, Trans_NonRMVatAcc, ".
							 " Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc, Trans_discountacc, Trans_PromotionAcc  ".
							 " FROM transactionsetup ".
							 " WHERE Journal_type = 'SI' ".
							 " AND Group_code = '".$ItemGroupCode."'  ";
									 
					$result = selectData($connection, $query);
							
					$vTranStpDirectStkDbt = $result[0];
					$vTranStpDirectStkCrd = $result[1];
					$vTranStpDirectStkCur = $result[2];
					$vTranStpVatAcc       = $result[3];
					$vTranStpNonRmVatAcc  = $result[4];
					$vTranStpRmVatAcc     = $result[5];
					$vTranStpNonRmTTCIncAcc  = $result[6];
					$vTranStpRmTTCIncAcc     = $result[7];
					$vTranStpNonRmAcc        = $result[8];
					$vTranStpRmAcc           = $result[9];
					$vTranStpDiscAcc         = $result[10];
					$vTranStpPromoAcc        = $result[11]; 
							
					if ($Module_RawMaterial == 1) {
						$vSaDtDirectStkDbt = $vTranStpDirectStkDbt;
						$vSaDtDirectStkCrd = $vTranStpDirectStkCrd;
						$vSaDtDirectStkCur = $vTranStpDirectStkCur;
						$vSaDtVatAcc       = $vTranStpVatAcc;
						$vSaDtDiscAcc      = $vTranStpDiscAcc;
						$vSaDtPromoAcc     = $vTranStpPromoAcc;
								
						if ($item_vat > 0) {
							if ($ItemProd == 1)	$vSaDtItemAcc = $vTranStpNonRmVatAcc; else $vSaDtItemAcc = $vTranStpRmVatAcc;
						}
						else {
							if ($ItemProd == 1) {
								if ($ItemTTCInc == 1) $vSaDtItemAcc = $vTranStpNonRmTTCIncAcc; else $vSaDtItemAcc = $vTranStpNonRmAcc;
							}	
							else {
								if ($ItemTTCInc == 1) $vSaDtItemAcc = $vTranStpRmTTCIncAcc; else $vSaDtItemAcc = $vTranStpRmAcc;
							}
						}	
					} 
					else {
						$vSaDtDirectStkDbt = $vSaStpDirectStkDbt;
						$vSaDtDirectStkCrd = $vSaStpDirectStkCrd;
						$vSaDtDirectStkCur = $vSaStpDirectStkCur;		
						$vSaDtVatAcc       = $vSaStpVatAcc;
						$vSaDtDiscAcc      = $vSaStpDiscAcc;
						$vSaDtPromoAcc     = $vSaStpPromoAcc;
								
						if ($item_vat > 0)
							$vSaDtItemAcc = $vSaStpCreditVatAcc;
						else
							$vSaDtItemAcc = $vSaStpCreditAcc;	
							
					}
					
					
					fbegin();
					$vSaDtId = get_nextsequence('deliverydt_id','',$connection);	
					fcommit();
					
					fbegin();
					$vSerId = get_nextsequence('Serial_Id','',$connection);	
					fcommit();
					
					$vSaDtCostBase1  = 0;
					$vSaDtCostBase2  = 0;
					$query_cost = " select ifNull(MeanCostCur('".$vSaDtItemCode."', '".insertMySQLDate($PSaDate)."', 1, '', ''),0) MeanCostAmountB1 ,  ".
								  " ifNull(MeanCostCur('".$vSaDtItemCode."', '".insertMySQLDate($PSaDate)."', 2, '', ''),0) MeanCostAmountB2 from dual  ";
					$result_cost = selectData($connection, $query_cost);
					
					$vSaDtCostBase1  = $result_cost[0];
					$vSaDtCostBase2  = $result_cost[1];
					if (empty($vSaDtCostBase1)) $vSaDtCostBase1 = 0;
					if (empty($vSaDtCostBase2)) $vSaDtCostBase2 = 0;
					//echo $query_cost; exit;
					
					fbegin();
					$query = " INSERT INTO temp_deliverydt (DeliveryDt_id, Delivery_id, Currency_Code, Delivery_Date, Journal_Type, Client_Code, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, DeliveryDt_Quantity, ".
							 " DeliveryDt_Price, DeliveryDt_PriceBase1, DeliveryDt_PriceBase2, DeliveryDt_DiscountPer, DeliveryDt_DiscountAmount, DeliveryDt_DiscountBase1, DeliveryDt_DiscountBase2, Item_Vat, DeliveryDt_PriceTTC, ".
							 " Deliverydt_priceTTCBase1, Deliverydt_priceTTCBase2, Deliverydt_DirectStkDbt, Deliverydt_DirectStkCrd, Deliverydt_DirectStkCur, Deliverydt_discountacc, Deliverydt_ItemAccount, DeliveryDt_PromoAcc, ".
							 " Deliverydt_BelongsToGroup, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Deliverydt_posted, Deliverydt_OldData, Item_UnitCoef, Item_Unit2Qty, Deliverydt_promotion, Deliverydt_costbase1, Deliverydt_costbase2, ".
							 " User_Account, Logged_Code ) ".
							 " VALUES ( ".$vSaDtId.", ".$SaId.", '".$PSaCurr."', '".insertMySQLDate($PSaDate)."', 'DI', '".ereg_replace("'", "\'", trim($PSaClientCode))."',  ".
							 "          $ProjectCode, $CostCentCode, '".$lstWarehouse."', '".$vSaDtItemCode."', Null, $vSaDtQty, $vSaDtPrice, $vSaDtPriceBase1, $vSaDtPriceBase2, $vSaDtDiscountPer, 0, 0, 0, $item_vat, ".
							 "          $vSaDtPriceTTC, $vSaDtPriceTTCBase1, $vSaDtPriceTTCBase2, '".$vSaDtDirectStkDbt."', '".$vSaDtDirectStkCrd."', '".$vSaDtDirectStkCur."', '".$vSaDtDiscAcc."', '".$vSaDtItemAcc."', '".$vSaDtPromoAcc."', ".
							 "          $FI_BelongsToGrp,  $vSaDtTax1, $vSaDtTax2, $vSaDtTax3, $vSaDtTax4, $vSaDtTax5, 0, 0, $vItemUnitCoef, $vItemUnit2Qty, $ItemPromo, $vSaDtCostBase1, $vSaDtCostBase2, '".$HTTP_SESSION_VARS['useraccount']."', '".$HTTP_SESSION_VARS['useraccount']."' ) ";
					 
					//echo $query."<br>";exit;				
					$result=mysql_query($query,$connection);
					
					if ($result){
						$query = " INSERT INTO temp_purchasesserialno (Serial_ID, Journal_Type, DeliveryDt_ID, PurchaseDt_ID, Item_Code, SerialNo_Code, SerialNo_Used, RelatedSerial_Id, SerialNo_Quantity, SerialNo_QuantitySold, Warehouse_code, Logged_Code ) ".
								 " VALUES ( ".$vSerId.", 'DI', $vSaDtId, $vSaDtId, '".$vSaDtItemCode."', '".$ItemSerialNo."', 0, '".$SelectedSerialID."', '".$SelectedSerialQty."', $SelectedSerialQtySold + 1, '".$lstWarehouse."', '".$HTTP_SESSION_VARS['useraccount']."' ) ";
													 
						$result=mysql_query($query,$connection);
										
						if ($result){
							$message = "Serial no (".$ItemSerialNo.") inserted successfully.";
							fcommit();
						} else {
							$ErrorExists = 1;
							$message  = mysql_error(); 
							frollback();
						}
						
					} else {
						$ErrorExists = 1;
						$message  = mysql_error(); 
						frollback();
					}
					
					
				
				} 
				else {
					$vSaDtItemCode = $sub_result[1];
					$vSaDtQty      = $sub_result[2];
					$vSaDtQty      = $vSaDtQty + 1; 
				
					fbegin();
					$vSerId = get_nextsequence('Serial_Id','',$connection);	
					fcommit();
					
					$vMultiItemExists = 0;
					
					if ($Module_DeliveryWithSorder == 1) {
					    //Stopped 2011-08-18 due to dajcom request
						/*$sub_query = " Select DeliveryDt_ID, DeliveryDt.Item_code, Sum(ifNull(DeliveryDt_Quantity,0)), Sum(ifNull(SorderDt.SorderDt_Quantity,0)) ".
									 " From Temp_DeliveryDt As DeliveryDt ".
									 " Inner Join SorderDt on SorderDt.SorderDt_ID = DeliveryDt.RelatedDt_Id  ".
									 " Where DeliveryDt.Journal_Type = 'DI'  ".
									 " And DeliveryDt.Item_Code = '".$SelectedItemCode."' ".
									 " And DeliveryDt.Delivery_ID = '".$SaId."' ".
									 " Group By DeliveryDt_ID, DeliveryDt.Item_CodePacked, DeliveryDt.Item_code ".
									 " Having Sum(ifNull(DeliveryDt_Quantity,0)) < Sum(ifNull(SorderDt.SorderDt_Quantity,0)) ";*/
									 
						$sub_query = " Select DeliveryDt_ID, DeliveryDt.Item_code, ifNull(DeliveryDt_Quantity,0), ifNull(SorderDt.SorderDt_Quantity,0), ".
						             " ifNull(SorderDt.SorderDt_Quantity,0) - ifNull(DeliveryDt_Quantity,0) As RemainQty  ".
									 " From Temp_DeliveryDt As DeliveryDt ".
									 " Inner Join SorderDt on SorderDt.SorderDt_ID = DeliveryDt.RelatedDt_Id  ".
									 " Where DeliveryDt.Journal_Type = 'DI'  ".
									 " And DeliveryDt.Item_Code = '".$SelectedItemCode."' ".
									 " And DeliveryDt.Delivery_ID = '".$SaId."' ".
									 " Group By DeliveryDt_ID, DeliveryDt.Item_code ".
									 " Having RemainQty > 0 ".
									 " Order by RemainQty Asc Limit 1 ";
									 
						//echo $sub_query; exit;			 
						//$sub_result = selectData($connection, $sub_query);
						//$vSaDtId = $sub_result[0];
						
						$vMultiItemExists = 0;
						$sub_rowcount = 0;
						
						//Stopped 2011-08-18 due to dajcom request
						
						/*$sub_result=mysql_query($sub_query,$connection) or die(mysql_error());
						$sub_rowcount = mysql_num_rows($sub_result);
						
						if($sub_rowcount > 1) {
							$vMultiItemExists = 1;
							
							if ($lstItems != '') {
								$vMultiItemExists = 0;
								$vSaDtId = $lstItems;
							}
							//echo "item= ".$lstItems; exit;
						} else {
						    $sub_result = selectData($connection, $sub_query);
							$vSaDtId = $sub_result[0];
						}	*/
						
						$sub_result = selectData($connection, $sub_query);
						$vSaDtId = $sub_result[0];
							
					}		
					
					if ($vMultiItemExists == 0) {
						fbegin();
						$query = " UPDATE temp_deliverydt SET ".
								 " DeliveryDt_Quantity =  (ifNull(DeliveryDt_Quantity,0) + 1) ";
								 
						if ($Module_DoubleUnit == 1) {
							$query = $query.", Item_Unit2Qty = ifNull(Item_UnitCoef,0)*(ifNull(DeliveryDt_Quantity,0)) ";
						}		 
						$query = $query." WHERE DeliveryDt_id = '".$vSaDtId."' ";
								 
						 
						//echo $query."<br>";exit;				
						$result=mysql_query($query,$connection);
						
						if ($result){
							$query = " INSERT INTO temp_purchasesserialno (Serial_ID, Journal_Type, DeliveryDt_ID, PurchaseDt_ID, Item_Code, SerialNo_Code, SerialNo_Used, RelatedSerial_Id, SerialNo_Quantity, SerialNo_QuantitySold, Warehouse_code, Logged_Code ) ".
									 " VALUES ( ".$vSerId.", 'DI', $vSaDtId, $vSaDtId, '".$vSaDtItemCode."', '".$ItemSerialNo."', 0, '".$SelectedSerialID."', '".$SelectedSerialQty."', $SelectedSerialQtySold + 1, '".$lstWarehouse."', '".$HTTP_SESSION_VARS['useraccount']."' ) ";
														 
							$result=mysql_query($query,$connection);
											
							if ($result){
								$message = "Serial no (".$ItemSerialNo.") inserted successfully.";
								fcommit();
							} else {
								$ErrorExists = 1;
								$message  = mysql_error(); 
								frollback();
							}
							
						} else {
							$ErrorExists = 1;
							$message  = mysql_error(); 
							frollback();
						}
					}
					// In Case Item Exists More Than Once In The Current Delivery ==> Let User Select The Exact Item From The List
					else {
						$IsAvailable = 0;
						$message  = "Insert not allowed, Item ($SelectedItemCode) exists more than one time. Please select one Item from below list. "; 
					}
				}
			
			}
			else {
				$IsAvailable = 0;
				$message  = "Insert not allowed, Ordered Qty[$ItemRemQty] Exceeded for Item ($SelectedItemCode). "; 
			}

		
			
		} //End if ($SaId != "" )
		
		
	} //End Case IsAvailable = True
} //End Case Insert

if ($Mode == 'delete' && $SerialId != '') {
	
	$ErrorExists = 0;
	$IsAvailable = 1;
	
	$query = " SELECT ifNull(SerialNo_Used, 0) As SerialNo_Used, ifNull(PurchaseDt_ID, DeliveryDt_ID)  from temp_purchasesserialno ".
	         " WHERE Serial_ID = ".$SerialId;
			 //" AND Logged_Code = '".$HTTP_SESSION_VARS['useraccount']."' ";
	$result = selectData($connection, $query);
	$SerialNoUsed        = $result[0];
	$SerialDeliveryDt_Id = $result[1];
	
	if ($SerialNoUsed == 0) {
		fbegin();
		
		$query = " DELETE from temp_purchasesserialno ".
				 " WHERE Serial_ID = ".$SerialId.
				 //" AND Logged_Code = '".$HTTP_SESSION_VARS['useraccount']."' ".
				 " AND ifNull(SerialNo_Used, 0) = 0  ";
		
		$result=mysql_query($query,$connection);
			
		if ($result){
			$message = "Delete serial no (".$ItemSerialNo.") done successfully.";
			
			$query = " UPDATE temp_deliverydt SET ".
					 " DeliveryDt_Quantity =  (ifNull(DeliveryDt_Quantity,0) - 1) ";
					 
			if ($Module_DoubleUnit == 1) {
				$query = $query.", Item_Unit2Qty = ifNull(Item_UnitCoef,0)*(ifNull(DeliveryDt_Quantity,0)) ";
			}			 
			$query = $query." WHERE DeliveryDt_id = '".$SerialDeliveryDt_Id."' ";
			//echo $query."<br>";exit;				
			if (!updateData($connection, $query, true))		 
				$message  = mysql_error(); 	
			
			
			fcommit();
		}else{
			$ErrorExists = 1;
			$message  = mysql_error(); 
			frollback();
		}			
	} 
	else {	
		$ErrorExists = 1;
		$message  = "Delete not allowed, Serial No ".$ItemSerialNo." is used. "; 
	}	
}

// Update Amount Columns In Delivery Table
if ($Module_Delivery == 0 && $ErrorExists == 0 && $IsAvailable == 1 && $SaId != '') {

	if (empty($PSaVatChkbx)) $PSaVatChkbx = 0;
			
	$vSaDtTotal = 0;
	$vItemVat = 0;
				
	$vSaTaxable        = 0;
	$vSaTaxableTTC     = 0;
	$vSaNoneTaxable    = 0;
	$vSaGrossTotal     = 0;
	$vSaDiscountAmt    = 0;
	$vSaDiscountAmtTTC = 0;
	$vSaVat      = 0;
	$vSaVatBase1 = 0;
	$vSaVatBase2 = 0;
	
	$vSaTax1 = 0;
	$vSaTax2 = 0;
	$vSaTax3 = 0;
	$vSaTax4 = 0;
	$vSaTax5 = 0;
	$vSaTax1B1 = 0;
	$vSaTax2B1 = 0;
	$vSaTax3B1 = 0;
	$vSaTax4B1 = 0;
	$vSaTax5B1 = 0;
	$vSaTax1B2 = 0;
	$vSaTax2B2 = 0;
	$vSaTax3B2 = 0;
	$vSaTax4B2 = 0;
	$vSaTax5B2 = 0;
		
	$query = " Select Item_Code, ((ifNull(DeliveryDt_Quantity,0)*ifNull(DeliveryDt_Price,0))-((ifNull(DeliveryDt_Quantity,0)*ifNull(DeliveryDt_Price,0)*ifNull(DeliveryDt_DiscountPer,0))/100)) As Total, ifNull(Item_Vat,0),  ".
			 " DeliveryDt_Quantity, ifNull(DeliveryDt_DiscountAmount,0), ifNull(Item_Tax1,0), ifNull(Item_Tax2,0), ifNull(Item_Tax3,0), ifNull(Item_Tax4,0), ifNull(Item_Tax5,0) ".
			 " From Temp_DeliveryDt ".
			 " Where Delivery_ID = ".$SaId;
						 
									 
					 
	//echo $query;
	$result=mysql_query($query,$connection) or die(mysql_error());
	while($rows=mysql_fetch_array($result)){

		$vSaDtTotal  = $rows[1];
		$vItemVat    = $rows[2];
					
		$tax_flag = 0;
		$notax_flag = 1;
		if ($vItemVat > 0){
			$tax_flag = 1;
			$notax_flag = 0;
		}	
					
						
		$vSaTaxable     = $vSaTaxable     + ($vSaDtTotal*$tax_flag);
		$vSaNoneTaxable = $vSaNoneTaxable + ($vSaDtTotal*$notax_flag);
		

		
		// Calculation of Vat Amount
		if (((insertDate($PSaDate) > $Setup_VatStartDate && $vItemVat > 0) || ($Module_AdditionalTaxes == 1))  && $PSaVatChkbx == 1 && $vSaDtTotal > 0)
			$vSaVat = $vSaVat + (($vSaDtTotal - $rows[4])*$vItemVat/100);
			
		if ($Module_AdditionalTaxes == 1  && $vSaDtTotal > 0) {
			if ($vItemVat > 0 && $rows[5] != 0)
				$vSaTax1 = $vSaTax1 + (($vSaDtTotal - $rows[4])*$rows[5]/100);
			if ($vItemVat > 0 && $rows[6] != 0)
				$vSaTax2 = $vSaTax2 + (($vSaDtTotal - $rows[4])*$rows[6]/100);
			if ($vItemVat > 0 && $rows[7] != 0)
				$vSaTax3 = $vSaTax3 + (($vSaDtTotal - $rows[4])*$rows[7]/100);
			if ($vItemVat > 0 && $rows[8] != 0)
				$vSaTax4 = $vSaTax4 + (($vSaDtTotal - $rows[4])*$rows[8]/100);
			if ($vItemVat > 0 && $rows[9] != 0)
				$vSaTax5 = $vSaTax5 + (($vSaDtTotal - $rows[4])*$rows[9]/100);	
		}
					
	}			
				
				
	$vSaGrossTotal = $vSaTaxable + $vSaNoneTaxable;
				
			
	// Calculation of Discount Amount	
	if ($SalesTTC == 1) {
		if ($PSaDiscount > 0) {
			$vSaDiscountAmt     = (($vSaGrossTotal * $PSaDiscount) / 100);
			$vSaDiscountAmtTTC  = ($vSaDiscountAmt * (1 + $Setup_VatPercentage/100));
		}	
				
		if ($PSaVatChkbx == 1)	$vSaTaxableTTC = ($vSaTaxable * (1 + $Setup_VatPercentage/100));
		else $vSaTaxableTTC = $vSaTaxable;
	} else	{
		if ($PSaDiscount > 0) {
			$vSaDiscountAmt     = (($vSaGrossTotal * $PSaDiscount) / 100);
		}	
		
		$vSaTaxableTTC 		= 0;
		$vSaDiscountAmtTTC  = 0;
	}
				
	$vSaNetTotal         = $vSaGrossTotal + $vSaVat - $vSaDiscountAmt;
	$vSaTaxableBase1     = ($vSaTaxable*$rate_dt)/$rate_dt1;
	$vSaTaxableBase2     = ($vSaTaxable*$rate_dt)/$rate_dt2;
	$vSaNoneTaxableBase1 = ($vSaNoneTaxable*$rate_dt)/$rate_dt1;
	$vSaNoneTaxableBase2 = ($vSaNoneTaxable*$rate_dt)/$rate_dt2;
	$vSaDiscountAmtBase1 = ($vSaDiscountAmt*$rate_dt)/$rate_dt1;
	$vSaDiscountAmtBase2 = ($vSaDiscountAmt*$rate_dt)/$rate_dt2;
	$vSaGrossTotalBase1  = ($vSaGrossTotal*$rate_dt)/$rate_dt1;
	$vSaGrossTotalBase2  = ($vSaGrossTotal*$rate_dt)/$rate_dt2;
	$vSaVatBase1         = ($vSaVat*$rate_dt)/$rate_dt1;
	$vSaVatBase2         = ($vSaVat*$rate_dt)/$rate_dt2;
	
	$vSaTax1B1  = ($vSaTax1*$rate_dt)/$rate_dt1;
	$vSaTax1B2  = ($vSaTax1*$rate_dt)/$rate_dt2;		
	$vSaTax2B1  = ($vSaTax2*$rate_dt)/$rate_dt1;
	$vSaTax2B2  = ($vSaTax2*$rate_dt)/$rate_dt2;		
	$vSaTax3B1  = ($vSaTax3*$rate_dt)/$rate_dt1;
	$vSaTax3B2  = ($vSaTax3*$rate_dt)/$rate_dt2;		
	$vSaTax4B1  = ($vSaTax4*$rate_dt)/$rate_dt1;
	$vSaTax4B2  = ($vSaTax4*$rate_dt)/$rate_dt2;		
	$vSaTax5B1  = ($vSaTax5*$rate_dt)/$rate_dt1;
	$vSaTax5B2  = ($vSaTax5*$rate_dt)/$rate_dt2;	
				

				 
	$query = " UPDATE temp_deliveries SET ".
			 " Delivery_Taxable = $vSaTaxable, Delivery_TaxableBase1 = $vSaTaxableBase1, Delivery_TaxableBase2 = $vSaTaxableBase2, ".
			 " Delivery_NoneTaxable = $vSaNoneTaxable, Delivery_NoneTaxableBase1 = $vSaNoneTaxableBase1, Delivery_NoneTaxableBase2 = $vSaNoneTaxableBase2, ".
			 " Delivery_DiscountAmount = $vSaDiscountAmt, Delivery_DiscountBase1 = $vSaDiscountAmtBase1, Delivery_DiscountBase2 = $vSaDiscountAmtBase2, ".
			 " Delivery_DiscountPer = $PSaDiscount, Delivery_VAT = $vSaVat, Delivery_VATBase1 = $vSaVatBase1, Delivery_VATBase2 = $vSaVatBase2, ".
			 " Delivery_Total = $vSaGrossTotal, Delivery_TotalBase1 = $vSaGrossTotalBase1, Delivery_TotalBase2 = $vSaGrossTotalBase2, ".
			 " Delivery_DiscountTTC = $vSaDiscountAmtTTC, Delivery_TaxableTTC = $vSaTaxableTTC,  ".
			 " Delivery_Tax1 = $vSaTax1, Delivery_Tax1Base1 = $vSaTax1B1, Delivery_Tax1Base2 = $vSaTax1B2,  ".
			 " Delivery_Tax2 = $vSaTax2, Delivery_Tax2Base1 = $vSaTax2B1, Delivery_Tax2Base2 = $vSaTax2B2,  ".
			 " Delivery_Tax3 = $vSaTax3, Delivery_Tax3Base1 = $vSaTax3B1, Delivery_Tax3Base2 = $vSaTax3B2,  ".
			 " Delivery_Tax4 = $vSaTax4, Delivery_Tax4Base1 = $vSaTax4B1, Delivery_Tax4Base2 = $vSaTax4B2,  ".
			 " Delivery_Tax5 = $vSaTax5, Delivery_Tax5Base1 = $vSaTax5B1, Delivery_Tax5Base2 = $vSaTax5B2  ".
			 " WHERE Delivery_ID = ".$SaId;
			//" And Logged_Code = '".$HTTP_SESSION_VARS['useraccount']."' ";
						 
				 
	$result=mysql_query($query,$connection);
	//echo $query."<br>";exit;
				
}


$message          = ereg_replace(' ','%20',$message);
$PSaRemark        = ereg_replace(' ','%20',$PSaRemark);
$PSaIAddress      = ereg_replace(' ','%20',$PSaIAddress);
$PSaDAddress      = ereg_replace(' ','%20',$PSaDAddress);
$PSaDriverName    = ereg_replace(' ','%20',$PSaDriverName);
$PSaVehicleNumber = ereg_replace(' ','%20',$PSaVehicleNumber);

$lstWarehouse     = ereg_replace('#','%23',$lstWarehouse);
$PSaRemark        = ereg_replace('#','%23',$PSaRemark);
$PSaIAddress      = ereg_replace('#','%23',$PSaIAddress);
$PSaDAddress      = ereg_replace('#','%23',$PSaDAddress);
$PSaVehicleNumber = ereg_replace('#','%23',$PSaVehicleNumber);
$PSaDriverName    = ereg_replace('#','%23',$PSaDriverName);

$lstWarehouse     = ereg_replace('&','%26',$lstWarehouse);
$PSaRemark        = ereg_replace('&','%26',$PSaRemark);
$PSaIAddress      = ereg_replace('&','%26',$PSaIAddress);
$PSaDAddress      = ereg_replace('&','%26',$PSaDAddress);
$PSaVehicleNumber = ereg_replace('&','%26',$PSaVehicleNumber);
$PSaDriverName    = ereg_replace('&','%26',$PSaDriverName);


header ( "Location: ./Form_DeliveryAddSerial.php?lstWarehouse=".$lstWarehouse."&lstItems=".$lstItems."&PSaId=".$SaId."&perpage=".$PerPage.	
		 "&PSaDate=".$PSaDate."&PSaMaturityDate=".$PSaMaturityDate."&PSaClientCode=".$PSaClientCode."&PSaSalesmanCode=".$PSaSalesmanCode.
		 "&PSaCurr=".$PSaCurr."&PSaProjectCode=".$PSaProjectCode."&PSaCostCentCode=".$PSaCostCentCode."&PSaVatChkbx=".$PSaVatChkbx.
		 "&PSaDiscount=".$PSaDiscount."&PSaDiscountAmt=".$PSaDiscountAmt."&PSaDriverName=".$PSaDriverName."&PSaVehicleNumber=".$PSaVehicleNumber.
		 "&PSaRemark=".$PSaRemark."&PSaIAddress=".$PSaIAddress."&PSaDAddress=".$PSaDAddress."&message=".$message );

function fbegin()
{
	mysql_query("START TRANSACTION");
}
function fcommit(){
	mysql_query("COMMIT");
}
function frollback()
{
	mysql_query("ROLLBACK");
}

print <<<HERE
</form>
</body>

HERE;

?>