<?php

session_start();

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

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

 

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

//Read From SalesSetup Table
   $querySalesSetup="Select TipsMaxBase1,ifnull(TipsMaxBase2,0), ifnull(salesjv_paymentmode,0) as salesjv_paymentmode ,cashcur , cashcur2 ,creditaccount,creditaccount2,
					cashaccount,cashaccount2,checkaccount,checkaccount2  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);
}

//User Access
$querylog=" select ifNull(login_belongstogrp,0) As FI_BelongsToGrp from ".$_SESSION['dbLabel'].".login where user_account='".$_SESSION['useraccount']."' and Upper(Login_Schema) = Upper('".$_SESSION['dbName']."')  ";
$resultlog=mysql_query($querylog,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultlog)){
	extract($rows);
}

//Read From Module Table
$querymodule=" Select ifNull(Module_ReferenceByCostcenter,0) As Module_ReferenceByCostcenter, ifNull(Module_ReferenceByProject,0) As Module_ReferenceByProject, ".
			 " ifNull(Module_ProjectDt,0) As Module_ProjectDt, ifNull(Module_CostCenterDt,0) As Module_CostCenterDt, ifNull(Module_UniqueManualNo,0) As Module_UniqueManualNo ".
			 " From Module";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}

$querycostcent=" select costcent_applyvat ".
               " from costcent left join ".$_SESSION['dbLabel'].".loginstk on costcent.costcent_code like concat(loginstk.costcent_code,'%') ".
 			   " where user_account='".$_SESSION['useraccount']."' ".
 			   "";

$costcentres = mysql_query($querycostcent,$connection) or die(mysql_error());
$rows=mysql_fetch_array($costcentres);
$costcent_applyvat = $rows[0];
if($costcent_applyvat=='')	$costcent_applyvat = 1;

if ($actionmode == 'addRemark'){
	$sorderJvId = $_GET['sorderJvId'];
	$query = "select setup_id, remark_description from sorderJv_RemarkSetup order by remark_description";
	$result = mysql_query($query,$connection);

	while($row = mysql_fetch_array($result)){
		$querychk = "select sorderJvRemarkdt_id from temp_sorderJvRemarkdt where sorderJv_id = $sorderJvId and Remarkdt_id = $row[0] ";
		$reschk = mysql_query($querychk,$connection);
		$rowchk = mysql_fetch_row($reschk);
		$sorderJvRemarkdt_id = $rowchk[0];
		
		$remarkchk = 'remarkchk'.$row[0];
		if($$remarkchk == '') $$remarkchk = 0;
		
		if($sorderJvRemarkdt_id == ''){
			fbegin();	
			$sorderJvRemarkdt_id = get_nextsequence('sorderJvRemarkdt_id','',$connection);	
			fcommit();
			$queryins = "insert into temp_sorderJvRemarkdt (sorderJvRemarkdt_id, sorderJv_id, Remarkdt_id, sorderJvRemarkdt_chk) values 
						($sorderJvRemarkdt_id, $sorderJvId, $row[0], ".$$remarkchk.") ";
			$resin =mysql_query($queryins, $connection);			
			
		} else {
			$queryup = "update temp_sorderJvRemarkdt set sorderJvRemarkdt_chk =  ".$$remarkchk." where sorderJvRemarkdt_id = $sorderJvRemarkdt_id ";
			$resup =mysql_query($queryup, $connection);			
		}
	}
	header("Location: ./Form_SorderJvRemark.php?jvId=$sorderJvId");
	exit;
}
if($actionmode == "searchcustomer"){
		$txtClientCode = $_GET['txtClientCode'];
		$query_checkcustomer  = "select ledger_number as CustomerCode, ledger_name as CustomerName  
		                         from clients
								 where ledger_number = '$txtClientCode'";
		$result_checkcustomer = mysql_query($query_checkcustomer, $connection);
		$num_checkcustomer    = mysql_num_rows($result_checkcustomer);
		if($num_checkcustomer > 0){
			$response = 1;
		}
		else{
			$response = 0;
		}
		$row_checkcustomer    = mysql_fetch_array($result_checkcustomer);
		extract($row_checkcustomer);
		echo $response;
		echo "[BRK]";
		echo $CustomerCode;
		echo "[BRK]";
		echo $CustomerName;
		echo "[BRK]";
		exit;
	}
else
    if($actionmode == "searchledger"){
		$txtLedgerNo = $_GET['txtLedgerNo'];
		$query_chkledger = "select ledger_number as LedgerNumber, ledger_name as LedgerName
		                    from ledger
							where ledger_number = '$txtLedgerNo' and Ledger_grpdet = 0";
		$result_chkledger = mysql_query($query_chkledger, $connection);
		$num_chkledger    = mysql_num_rows($result_chkledger);
		$row_chkledger    = mysql_fetch_array($result_chkledger);
		extract($row_chkledger);
		if($num_chkledger > 0){
			$response = 1;
		}
		else{
			$response = 0;
		}
		echo $response;
		echo "[BRK]";
		echo $LedgerNumber;
		echo "[BRK]";
		echo $LedgerName;
		echo "[BRK]";
		exit;
	}		

$message='';

if ($mode == "submitrecord" ){

	$ErrorExists = 0;

	$txtLedgerNo 		= $_GET["value1"];
	$txtDescription1 	= $_GET["value2"];
	$txtDescription2	= $_GET["value3"];
	$txtDtCurr 			= $_GET["value4"];
	$txtDtQty 			= $_GET["value5"];
	$txtDtPrice 		= $_GET["value6"];
	$txtDtDiscPer 		= $_GET["value7"];
	$txtDtTotal 		= $_GET["value8"];
	$txtDtVat 			= $_GET["value9"];
	$txtDtManualNo 		= $_GET["value10"];
	$txtProjectCodeDt 	= $_GET["value11"];
	$txtCostCentCodeDt 	= $_GET["value12"];
	$txtterms 			= $_GET["txtterms"];
	

	if (!isset($PCurr))   $PCurr = $base1;

	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$PCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$PCurr."' )";
	$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];

	//Check For Client, Salesman, Project and Costcenter Codes Before Insert
	if ($PCostCentCode != '') {
		$sub_query = " Select Count(Costcent_code) From Costcent ".
					 " Where Costcent_code = '".$PCostCentCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) $ErrorExists = 1;
	}
	if ($PProjectCode != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$PProjectCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) $ErrorExists = 1;
	}
	if ($PClientCode != '') {
		$sub_query = " Select Count(Ledger_Number) From Clients ".
					 " Where Ledger_Number = '".$PClientCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) $ErrorExists = 1;
	}
	if ($PSalesmanCode != '') {
		$sub_query = " Select Count(Ledger_Number) From Salesmen ".
					 " Where Ledger_Number = '".$PSalesmanCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) $ErrorExists = 1;
	}
	if ($txtLedgerNo != '') {
		$sub_query = " Select Count(Ledger_Number) From Ledger ".
					 " Where Ledger_Number = '".$txtLedgerNo."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) $ErrorExists = 1;
	}

	if ($txtProjectCodeDt != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$txtProjectCodeDt."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Detail Project Code.';
		}
	}
	if ($txtCostCentCodeDt != '') {
		$sub_query = " Select Count(Costcent_code) From Costcent ".
					 " Where Costcent_code = '".$txtCostCentCodeDt."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Detail Costcenter Code.';
		}
	}

	if ($ErrorExists == 1)
		$message = 'Insert not allowed. Please check for Client/Salesman/Project/Costcenter/Ledger Code.';

	//Insert Master Table
	if ($SId == "" && $ErrorExists == 0){

		if (empty($PDiscountAmt))	$PDiscountAmt = 0;
		if (empty($PDiscountPer))	$PDiscountPer = 0;
		if (empty($PVatChkbx))	    $PVatChkbx = 0;

		if (empty($cashcurrency1) ) $cashcurrency1 = 0;
		if (empty($bankcurrency1) ) $bankcurrency1 = 0;		
		if (empty($cardcurrency1) ) $cardcurrency1 = 0;		
		if (empty($cashcurrency2) ) $cashcurrency2 = 0;		
		if (empty($bankcurrency2) ) $bankcurrency2 = 0;
		if (empty($cardcurrency2) ) $cardcurrency2 = 0;

		$PCostCentCode = "".$PCostCentCode;
		if ($PCostCentCode == '')		$CostCentCode = "NULL";
		else							$CostCentCode = "'".$PCostCentCode."'";

		$PProjectCode = "".$PProjectCode;
		if ($PProjectCode == '')	$ProjectCode = "NULL";
		else						$ProjectCode = "'".$PProjectCode."'";

		if (empty($PSalesmanCode))	$SalesmanCode = "NULL";
		else						$SalesmanCode = "'".ereg_replace("'", "\'", trim($PSalesmanCode))."'";		

		fbegin();	
		$vSalesOrderJVId = get_nextsequence('SalesOrderJV_Id','',$connection);	
		fcommit();

		$Acc_Query = " SELECT VATAccountNonStock, DiscountAccount FROM salessetup ";
		$Acc_Result = selectData($connection, $Acc_Query);

		//$vVatAccount = $Acc_Result[0];
		if (empty($PVatPrefix)) $vVatAccount = $Acc_Result[0];
		else $vVatAccount = $PVatPrefix;

		$sub_queryVat = " SELECT GetVATAccount('".$PClientCode."','".$vVatAccount."') from dual ";
		$sub_resultVat = selectData($connection, $sub_queryVat);
		if ($sub_resultVat[0] != '') $vVatAccount = $sub_resultVat[0];

		if($costcent_applyvat==0) $PVatChkbx=0; 
		
		fbegin(); //    on begin  insert payment accounts from sales setup 
		$query = " INSERT INTO Temp_SalesOrderJV (SalesOrderJV_ID, SalesOrderJV_Reference, SalesOrderJV_Date, JournalDt_ValueDate, Client_Code, Salesman_Code, Sales_Remark, ".
				 " Currency_Code, Project_Code, Costcenter_Code, SalesOrderJV_Posted, SalesOrderJV_Edit, Sales_Mode, SalesOrderJV_BelongsToGroup, Journal_Type, Journal_Id, ".
				 " SalesOrderJV_Taxable, SalesOrderJV_TaxableBase1, SalesOrderJV_TaxableBase2, SalesOrderJV_NoneTaxable, SalesOrderJV_NoneTaxableBase1, SalesOrderJV_NoneTaxableBase2, ".
				 " SalesOrderJV_Total, SalesOrderJV_TotalBase1, SalesOrderJV_TotalBase2, SalesOrderJV_VAT, SalesOrderJV_VatBase1, SalesOrderJV_VatBase2, SalesOrderJV_VatCheck, SalesOrderJV_DiscountPer, ".
				 " SalesOrderJV_DiscountAmount, SalesOrderJV_DiscountAmount1, SalesOrderJV_DiscountAmount2, SalesOrderJV_VatAccount, SalesOrderJV_DiscountAccount, SalesOrderJv_ManualNo, ".
				 " SalesOrderJv_VatPrefix, User_Account, Logged_Code, salesOrderjv_PaymentTerms) ".
				 " VALUES ( ".$vSalesOrderJVId.", Null, '".insertMySQLDate($PDate)."', '".insertMySQLDate($PMaturityDate)."', '".ereg_replace("'", "\'", trim($PClientCode))."', ".
				 "          $SalesmanCode, '".ereg_replace("'", "\'", trim($PRemark))."', '".$PCurr."', $ProjectCode, $CostCentCode, ".
				 "          0, 0, 0, $FI_BelongsToGrp, 'JS', Null, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, $PVatChkbx, 0, 0, 0, 0, '".$vVatAccount."', '".$Acc_Result[1]."', ".
				 "          '".ereg_replace("'", "\'", trim($PManualNo))."', '".trim($PVatPrefix)."', '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."', ".GetSQLValueString($txtterms,'text')." );";
				 
		$result=mysql_query($query,$connection);
		//echo $query."<br>";exit;	

		if ($result){
			$SId = $vSalesOrderJVId;
			fcommit();
		}else{
			$SId = "";
			$ErrorExists = 1;
			$message  = mysql_error(); 
			frollback();
		}

	}

	//Insert Detail Tables
	if ($SId != "" && $SDtId == "" && $ErrorExists == 0){

		if (empty($PDiscountAmt))	$PDiscountAmt = 0;
		if (empty($PDiscountPer))	$PDiscountPer = 0;
		if (empty($PVatChkbx))	    $PVatChkbx = 0;

		if (empty($txtDtVat))	    $txtDtVat = 0;	
		if (empty($txtDtPrice))		$txtDtPrice = 0;
		if (empty($txtDtDiscPer))   $txtDtDiscPer = 0;
		if (empty($txtDtQty))  	    $txtSaDtQty = 0;      	
		if (empty($txtDtTotal))     $txtDtTotal = 0;  

		$PCostCentCode = "".$PCostCentCode;
		if ($PCostCentCode == '')	$CostCentCode = "NULL";
		else						$CostCentCode = "'".$PCostCentCode."'";
	
		$PProjectCode = "".$PProjectCode;
		if ($PProjectCode == '')	$ProjectCode = "NULL";
		else						$ProjectCode = "'".$PProjectCode."'";   

		$txtProjectCodeDt = "".$txtProjectCodeDt;
		if ($Module_ProjectDt == 1){
			if ($txtProjectCodeDt == '')	$ProjectCodeDt = "NULL";
			else							$ProjectCodeDt = "'".$txtProjectCodeDt."'";
		} else {
			$ProjectCodeDt = $ProjectCode;
		}
		
		$txtCostCentCodeDt = "".$txtCostCentCodeDt;
		if ($Module_CostCenterDt == 1) {
			if ($txtCostCentCodeDt == '')	$CostCentCodeDt = "NULL";
			else							$CostCentCodeDt = "'".$txtCostCentCodeDt."'";
		} else {
			$CostCentCodeDt = $CostCentCode;
		}

		if (empty($txtDtManualNo)) $vDtManualNo = "NULL";
		else	$vDtManualNo = "'".$txtDtManualNo."'";

		$vDtQty           = 0;
		$vDtDiscPer       = 0;
		$vDtTotal         = 0;
		$vDtPrice         = 0;
		$vDtPriceBase1    = 0;
		$vDtPriceBase2    = 0;
		$vDtDiscAmt       = 0;
		$vDtDiscAmtBase1  = 0;
		$vDtDiscAmtBase2  = 0;

		$vDtQty        = $txtDtQty;
		$vDtDiscPer    = $txtDtDiscPer;
		$vDtVat        = $txtDtVat;
		$vDtTotal      = $txtDtTotal;

		$vDtPrice      = $txtDtPrice;
		$vDtPriceBase1 = ($vDtPrice*$rate_dt)/$rate_dt1;
		$vDtPriceBase2 = ($vDtPrice*$rate_dt)/$rate_dt2;

		
		$vDtDiscAmt       = ((($vDtPrice*$vDtQty) - ($vDtPrice*$vDtQty*$vDtDiscPer/100))*$PDiscountPer)/100;
		$vDtDiscAmtBase1  = ($vDtDiscAmt*$rate_dt)/$rate_dt1;
		$vDtDiscAmtBase2  = ($vDtDiscAmt*$rate_dt)/$rate_dt2;				

		//Check For Manual No To Be Unique
		if ($Module_UniqueManualNo == 1 && $txtDtManualNo != "") {
			$sub_query = " Select Count(*) From ( Select SalesOrderJvDt_ID From SalesOrderJvDt ".
						 "                        Where SalesOrderJvDt.Journal_Type = 'JS' and upper(SalesOrderJvDt.SalesOrderJvDt_ManualNo) = '".$txtDtManualNo."' and SalesOrderJvDt.SalesOrderJvDt_ID != $SDtId ".
						 "                 Union  Select SalesOrderJvDt_ID From Temp_SalesOrderJvDt as SalesOrderJvDt ".
						 "                        Where SalesOrderJvDt.Journal_Type = 'JS' and upper(SalesOrderJvDt.SalesOrderJvDt_ManualNo) = '".$txtDtManualNo."' and SalesOrderJvDt.SalesOrderJvDt_ID != $SDtId) Q1 ";
			$sub_result = selectData($connection, $sub_query);
			if ($sub_result[0] > 1 ) {
				$ErrorExists = 1;
				$message = 'Manual No should be unique.';
			}	
		}

		if ($ErrorExists == 0){

			fbegin();
			$vSalesOrderJVDtId = get_nextsequence('SalesOrderJVDt_Id','',$connection);	
			fcommit();

			fbegin();

			// INsert  Income Account , Cost Account , SupplierAccount

			 $sub_query= " Select ifNull(AllowLockedPeriod,0) As AllowLockedPeriod, LockedPeriod As LockedPeriodDate, LockedPeriodDays As LockedPeriodDays ".
				" From ".$_SESSION['dbLabel'].".ListUserDir  ".
				" Where Usercode='".$_SESSION['useraccount']."' ".
				" And Upper(CompanyName) = Upper('".$MainCompanyName[0]."') ".
				" And Upper(Diryear) = Upper('".$MainCompanyName[1]."') ";

	        
      
			$query = " INSERT INTO Temp_SalesOrderJVDt (SalesOrderJVDt_Id, SalesOrderJV_Id, SalesOrderJV_Date, Currency_Code, Client_Code, Salesman_Code, Ledger_Number, SalesOrderJVDt_Description, SalesOrderJVDt_Description2, ". 
			 " Project_Code, Costcenter_Code, SalesOrderJVDt_Quantity, SalesOrderJVDt_Price, SalesOrderJVDt_PriceBase1, SalesOrderJVDt_PriceBase2, SalesOrderJVDt_DiscountPer, SalesOrderJVDt_DiscountAmount, ".
			 " SalesOrderJVDt_DiscountAmount1, SalesOrderJVDt_DiscountAmount2, SalesOrderJVDTCalcTotal, SalesOrderJVDt_VAT, Journal_Type, SalesOrderJVDt_ManualNo, Logged_Code )  ".
			 " VALUES ( ".$vSalesOrderJVDtId.", ".$SId.", '".insertMySQLDate($PDate)."', '".$PCurr."', '".ereg_replace("'", "\'", trim($PClientCode))."', ".
			 "          '".ereg_replace("'", "\'", trim($PSalesmanCode))."', '".ereg_replace("'", "\'", trim($txtLedgerNo))."', '".ereg_replace("'", "\'", trim($txtDescription1))."', ".
			 "          '".ereg_replace("'", "\'", trim($txtDescription2))."', $ProjectCodeDt, $CostCentCodeDt, $vDtQty, $vDtPrice, $vDtPriceBase1, $vDtPriceBase2, $vDtDiscPer, ".
			 "          $vDtDiscAmt, $vDtDiscAmtBase1, $vDtDiscAmtBase2, $vDtTotal, $vDtVat, 'JS', $vDtManualNo,  ".
			 " '".$_SESSION['useraccount']."'	) ";
	

			//echo $query."<br>";exit;				
			$result=mysql_query($query,$connection);

			if ($result){
				fcommit();
			} else{
				$txtDtId = "";
				$ErrorExists = 1;
				$message  = mysql_error(); 
				frollback();
			}	

			if ($ErrorExists == 0) {
				//Calculating Master Amounts
				$CalculateResult = Calculate_MasterAmounts($SId, $PDate, $PVatChkbx, $PDiscountPer, 0, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Setup_VatPercentage, 'I', $connection);
				$message  = $message . $CalculateResult;
			}
		}
	} // End Case Insert In Detail Tables

	
	echo "[BRK]";
	echo $SId;   // ID is data 1 ,  cz data 0 is document
	echo "[BRK]";
	echo $message;  //data 2 
	echo "[BRK]";

exit;
} 

else if( $mainmode == 'confirmorder'  && $SId != ''){
	$confirm_flag     = 1;
	$sorder_confirm   = 0;
	
	
	//echo $sorder_confirm;exit;
	
	
	$query = " SELECT ifNull(SorderJV_confirmed,0) FROM salesorderjv WHERE SalesOrderJV_Id = '".$SId."'";
	//echo "<br><br>".$query;exit;
	$result = selectData($connection, $query);
	$sorder_confirm   = $result[0];
	
	//echo $sorder_confirm;exit;
		
	
	if ($confirm_flag == 1 && $sorder_confirm == 0) {
		
		
		
		$query = "UPDATE salesorderjv SET SorderJV_confirmed = 1,approvedby='".$_SESSION['username']."' WHERE SalesOrderJV_Id = '".$SId."'";
		
		//echo $query;exit;

		if (updateData($connection, $query, true))
			$message = "Sales Order JV Confirmed";
		else
			$message  = mysql_error();
		
	} 
	header("Location:./Form_SalesOrderJVSearch.php?message=$message");
	exit;
}




else if ($actionmode=='checkaccountno'){

$codedesc 		= $_GET["codedesc"];
$vaccountno 	= $_GET["vaccountno"];
$vaccountname 	= $_GET["vaccountname"];

if ($codedesc==1)
	$query = "  select ledger_name from ledger where ledger_number = '".$vaccountno ."' and LEDGER_GRPDET=FALSE ";
	else
	$query = "  select ledger_number from ledger where ledger_name = '".$vaccountname ."' and LEDGER_GRPDET=FALSE ";

$result=mysql_query($query,$connection)  or die(mysql_error());
$row=mysql_fetch_row($result);
echo "[BRK]";
if ($row[0]!='')
	echo $row[0];
else	
	echo 0;
echo "[BRK]";
exit;
}	
//Delete Detail Mode
else if ($mode == "deletedt" ){

	$AllowDelete = 0;
	$ErrorExists = 0;
	$message  = '';

	if (!isset($txtCurr))   $txtCurr = $base1;

	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$txtCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$txtCurr."' )";
	$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 No Constraints Exists On Delete
	if ($AllowDelete == 0) {

		fbegin();

		// Delete From Temp_SalesJVDt For Selected Record
		$query = " DELETE FROM Temp_SalesOrderJVDt ".
				 " WHERE SalesOrderJVDt_Id = ".$SDtId;
				
		if (!updateData($connection, $query, true)) {
			$message  = mysql_error();
			$ErrorExists = 1;
			frollback();
		}  
		else {
			fcommit();
		}

		if ( $ErrorExists == 0 ){ 
			//Calculating Master Amounts
			$CalculateResult = Calculate_MasterAmounts($SId, $txtDate, $SVatChkbx, $txtDiscountPer, 0, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Setup_VatPercentage, 'D', $connection);
			$message  = $message . $CalculateResult;
		} // End If No Error Exists 

	} // End If No Constraints Found On Delete

}

//Edit Detail Tables
else if ($mode == "editdt" && $SId != "" && $SDtId != ""){

	$txtLedgerNo 		= $_GET["value1"];
	$txtDescription1	= $_GET["value2"];
	$txtDescription2 	= $_GET["value3"];
	$txtDtCurr 			= $_GET["value4"];
	$txtDtQty 			= $_GET["value5"];
	$txtDtPrice 		= $_GET["value6"];
	$txtDtDiscPer 		= $_GET["value7"];
	$txtDtTotal 		= $_GET["value8"];
	$txtDtVat 			= $_GET["value9"];
	$txtDtManualNo 		= $_GET["value10"];
	$txtProjectCodeDt 	= $_GET["value11"];
	$txtCostCentCodeDt 	= $_GET["value12"];
	$txtDtCost 			= $_GET["value13"];

	if (empty($PDiscountAmt))	$PDiscountAmt = 0;
	if (empty($PDiscountPer))	$PDiscountPer = 0;
	if (empty($PVatChkbx))	    $PVatChkbx = 0;

	if (empty($txtDtVat))	    $txtDtVat = 0;	
	if (empty($txtDtPrice))		$txtDtPrice = 0;
	if (empty($txtDtDiscPer))   $txtDtDiscPer = 0;
	if (empty($txtDtQty))  	    $txtSaDtQty = 0;      	
	if (empty($txtDtTotal))     $txtDtTotal = 0;  

	$ErrorExists = 0;

	$vDtQty           = 0;
	$vDtDiscPer       = 0;
	$vDtTotal         = 0;
	$vDtPrice         = 0;
	$vDtPriceBase1    = 0;
	$vDtPriceBase2    = 0;

	
	$vDtDiscAmt       = 0;
	$vDtDiscAmtBase1  = 0;
	$vDtDiscAmtBase2  = 0;

	$sub_query = " Select Currency_code, ifNull(SalesOrderJV_DiscountPer,0), date_format(SalesOrderJV_Date, '%d/%m/%Y'), ifNull(SalesOrderJV_VatCheck,0) ".
				 " From Temp_SalesOrderJV As SalesOrderJV ".
				 " Where SalesOrderJV_ID = ".$SId;
	$sub_result = selectData($connection, $sub_query);
	$vCurr         = $sub_result[0];
	$vDiscountPer  = $sub_result[1];
	$vDate         = $sub_result[2];
	$vVatChkbx     = $sub_result[3];

	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$vCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$vCurr."' )";
	$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 (empty($txtDtManualNo)) $vDtManualNo = 'Null';
	else	$vDtManualNo = "'".$txtDtManualNo."'";

	$vDtQty        = $txtDtQty;
	$vDtDiscPer    = $txtDtDiscPer;
	$vDtVat        = $txtDtVat;
	$vDtTotal      = $txtDtTotal;

	$vDtPrice      = $txtDtPrice;
	$vDtPriceBase1 = ($vDtPrice*$rate_dt)/$rate_dt1;
	$vDtPriceBase2 = ($vDtPrice*$rate_dt)/$rate_dt2;

 
	$vDtDiscAmt       = ((($vDtPrice*$vDtQty) - ($vDtPrice*$vDtQty*$vDtDiscPer/100))*$vDiscountPer)/100;
	$vDtDiscAmtBase1  = ($vDtDiscAmt*$rate_dt)/$rate_dt1;
	$vDtDiscAmtBase2  = ($vDtDiscAmt*$rate_dt)/$rate_dt2;

	//Check For Manual No To Be Unique
	if ($Module_UniqueManualNo == 1 && $txtDtManualNo != "") {
		$sub_query = " Select Count(*) From ( Select SalesOrderJvDt_ID From SalesOrderJvDt ".
					 "                        Where SalesOrderJvDt.Journal_Type = 'JS' and upper(SalesOrderJvDt.SalesOrderJvDt_ManualNo) = '".$txtDtManualNo."' and SalesOrderJvDt.SalesOrderJvDt_ID != $SDtId ".
					 "                 Union  Select SalesOrderJvDt_ID From Temp_SalesOrderJvDt as SalesOrderJvDt ".
					 "                        Where SalesOrderJvDt.Journal_Type = 'JS' and upper(SalesOrderJvDt.SalesOrderJvDt_ManualNo) = '".$txtDtManualNo."' and SalesOrderJvDt.SalesOrderJvDt_ID != $SDtId) Q1 ";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] > 1 ) {
			$ErrorExists = 1;
			$message = 'Manual No should be unique.';
		}	
	}

	$txtProjectCodeDt = "".$txtProjectCodeDt;
	if ($Module_ProjectDt == 1){
		if ($txtProjectCodeDt == '')	$ProjectCodeDt = "NULL";
		else							$ProjectCodeDt = "'".$txtProjectCodeDt."'";
	} 
	
	$CostCentCodeDt = "".$CostCentCodeDt;
	if ($Module_CostCenterDt == 1) {
		if ($txtCostCentCodeDt == '')	$CostCentCodeDt = "NULL";
		else							$CostCentCodeDt = "'".$txtCostCentCodeDt."'";
	}

	if ($ErrorExists == 0){
		

		fbegin();
		
		$query = " UPDATE Temp_SalesOrderJVDt SET ".
				 " SalesOrderJVDt_Description = '".ereg_replace("'", "\'", trim($txtDescription1))."', SalesOrderJVDt_Description2 = '".ereg_replace("'", "\'", trim($txtDescription2))."',  ". 
				 " SalesOrderJVDt_Quantity = $vDtQty, SalesOrderJVDt_Price = $vDtPrice, SalesOrderJVDt_PriceBase1 = $vDtPriceBase1, SalesOrderJVDt_PriceBase2 = $vDtPriceBase2,  ".
				 " SalesOrderJVDt_DiscountPer = $vDtDiscPer, SalesOrderJVDt_DiscountAmount = $vDtDiscAmt, SalesOrderJVDt_DiscountAmount1 = $vDtDiscAmtBase1, SalesOrderJVDt_DiscountAmount2 = $vDtDiscAmtBase2,  ".
				 " SalesOrderJVDTCalcTotal = $vDtTotal, SalesOrderJVDt_VAT = $vDtVat, SalesOrderJvDt_ManualNo = $vDtManualNo, ledger_number = '$value1' ";
	

		if ($Module_ProjectDt == 1)
			$query = $query.", Project_Code = $ProjectCodeDt ";
		if ($Module_CostCenterDt == 1)	
			$query = $query.", CostCenter_Code = $CostCentCodeDt ";	

		$query = $query." WHERE SalesOrderJVDt_Id = '".$SDtId."'";

		//echo $query."<br>";exit;				
		$result=mysql_query($query,$connection);

		if ($result){
			fcommit();

			//Calculating Master Amounts
			$CalculateResult = Calculate_MasterAmounts($SId, $vDate, $vVatChkbx, $vDiscountPer, 0, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Setup_VatPercentage, 'U', $connection);
			$message  = $message . $CalculateResult;

		} else{
			$message  = mysql_error(); 
			frollback();
		}
	}

	
exit;	
} 

//Delete Record Mode From Main Tables
else if ($mode == "" && $mainmode == "delete" && $SId != ''){

	$AllowDelete = 0;
	$message  = '';

	//Check User Access For Date Modification/ Lock Period
	$MainCompanyName=explode('_',$_SESSION['dbName']);

	 $sub_query= " Select ifNull(AllowLockedPeriod,0) As AllowLockedPeriod, LockedPeriod As LockedPeriodDate, LockedPeriodDays As LockedPeriodDays ".
				" From ".$_SESSION['dbLabel'].".ListUserDir  ".
				" Where Usercode='".$_SESSION['useraccount']."' ".
				" And Upper(CompanyName) = Upper('".$MainCompanyName[0]."') ".
				" And Upper(Diryear) = Upper('".$MainCompanyName[1]."') ";

	$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
	$rowsperiod = mysql_num_rows($sub_result);

	while($sub_rows=mysql_fetch_array($sub_result)){
		extract($sub_rows);
	}	
	if ($rowsperiod > 0 && $AllowLockedPeriod == 1) {
		$query = "SELECT date_format(SalesOrderJV_Date,'%d/%m/%Y') FROM SalesOrderJV WHERE SalesOrderJV_ID = ".$SId;
		$result = selectData($connection, $query);
		$txtDate  = $result[0];

		if (!(empty($LockedPeriodDate)) && $LockedPeriodDate != '' && date('Y-m-d',strtotime(insertMySQLDate($txtDate))) <= date('Y-m-d',strtotime($LockedPeriodDate))) $AllowDelete = 1;
		if ($LockedPeriodDays != '' && dateDiff(insertMySQLDate(displayToday()),insertMySQLDate($txtDate)) > $LockedPeriodDays) $AllowDelete = 1;
		if($AllowDelete==1) $message  = 'Delete not allowed, Exceed Lock Period.';
	}

	//Check If SalesJV Is Posted
	$query = "SELECT ifNull(SalesOrderJV_Posted,0) As SalesOrderJVPosted FROM SalesOrderJV WHERE SalesOrderJV_ID = ".$SId;
	$result = selectData($connection, $query);
	$SalesOrderJVPosted = $result[0];

	if ($SalesOrderJVPosted == 1 ){
		$message  = 'Delete not allowed, Transaction posted.';
		$AllowDelete = 1;
	}

	//If No Constraints Exists On Delete
	if ($AllowDelete == 0) {

		// Delete From SalesJVDt For Selected Record
		$query = " DELETE FROM SalesOrderJVDt ".
				 " WHERE SalesOrderJV_ID = ".$SId;

		if (updateData($connection, $query, true)) {
			
			$query = " DELETE FROM sorderJvRemarkdt ".
					 " WHERE sorderJv_id = ".$SId;

			if (!updateData($connection, $query, true))		 
				$message  = mysql_error(); 
			// Delete From SalesJV For Selected Record
			$query = " DELETE FROM SalesOrderJV ".
					 " WHERE SalesOrderJV_ID = ".$SId;

			if (!updateData($connection, $query, true))		 
				$message  = mysql_error(); 
		}
		else
			$message  = mysql_error(); 	

	}

}

//Delete Record Mode From Temp Tables
else if ($mode == "" && $mainmode == "deletepending" && $SId != ''){

	// Delete From Temp_SalesJVDt For Selected Record
	$query = " DELETE FROM Temp_SalesOrderJVDt ".
			 " WHERE SalesOrderJV_ID = ".$SId;

	if (updateData($connection, $query, true)) {
		$query = "DELETE FROM temp_sorderJvRemarkdt where sorderJv_id = $SId";
		if (!updateData($connection, $query, true))		 
			$message  = mysql_error(); 
		
		// Delete From Temp_SalesJV For Selected Record
		$query = " DELETE FROM Temp_SalesOrderJV ".
				 " WHERE SalesOrderJV_ID = ".$SId;
		
		if (!updateData($connection, $query, true))		 
			$message  = mysql_error(); 
	}
	else
		$message  = mysql_error(); 	

}

//Search Mode	
else if($mainmode == "search" && $SId != ''){

	$ErrorExists = 0;
	//Copy Data From Main Tables To Temp Tables
	$query = " INSERT INTO Temp_SalesOrderJV (SalesOrderJV_ID, SalesOrderJV_Reference, SalesOrderJV_Date, JournalDt_ValueDate, Client_Code, Salesman_Code, Sales_Remark, ".
			 " Currency_Code, Project_Code, Costcenter_Code, SalesOrderJV_Posted, SalesOrderJV_Edit, Sales_Mode, SalesOrderJV_BelongsToGroup, Journal_Type, Journal_Id, ".
			 " SalesOrderJV_Taxable, SalesOrderJV_TaxableBase1, SalesOrderJV_TaxableBase2, SalesOrderJV_NoneTaxable, SalesOrderJV_NoneTaxableBase1, SalesOrderJV_NoneTaxableBase2, ".
			 " SalesOrderJV_Total, SalesOrderJV_TotalBase1, SalesOrderJV_TotalBase2, SalesOrderJV_VAT, SalesOrderJV_VatBase1, SalesOrderJV_VatBase2, SalesOrderJV_VatCheck, SalesOrderJV_DiscountPer, ".
			 " SalesOrderJV_DiscountAmount, SalesOrderJV_DiscountAmount1, SalesOrderJV_DiscountAmount2, SalesOrderJV_VatAccount, SalesOrderJV_DiscountAccount, SalesOrderJv_ManualNo, ".
			 " SalesOrderJv_VatPrefix, salesOrderjv_PaymentTerms, User_Account, Logged_Code ) ".
			 " SELECT SalesOrderJV_ID, SalesOrderJV_Reference, SalesOrderJV_Date, JournalDt_ValueDate, Client_Code, Salesman_Code, Sales_Remark, ".
			 " Currency_Code, Project_Code, Costcenter_Code, SalesOrderJV_Posted, SalesOrderJV_Edit, Sales_Mode, SalesOrderJV_BelongsToGroup, Journal_Type, Journal_Id, ".
			 " SalesOrderJV_Taxable, SalesOrderJV_TaxableBase1, SalesOrderJV_TaxableBase2, SalesOrderJV_NoneTaxable, SalesOrderJV_NoneTaxableBase1, SalesOrderJV_NoneTaxableBase2, ".
			 " SalesOrderJV_Total, SalesOrderJV_TotalBase1, SalesOrderJV_TotalBase2, SalesOrderJV_VAT, SalesOrderJV_VatBase1, SalesOrderJV_VatBase2, SalesOrderJV_VatCheck, SalesOrderJV_DiscountPer, ".
			 " SalesOrderJV_DiscountAmount, SalesOrderJV_DiscountAmount1, SalesOrderJV_DiscountAmount2, SalesOrderJV_VatAccount, SalesOrderJV_DiscountAccount, SalesOrderJv_ManualNo, ".
			 " SalesOrderJv_VatPrefix, salesOrderjv_PaymentTerms, User_Account, '".$_SESSION['useraccount']."' ".
			 " FROM SalesOrderJV ".
			 " WHERE SalesOrderJV_ID = ".$SId;

	if (!updateData($connection, $query, true)) {
		$ErrorExists = 1;
		$message  = mysql_error(); 	
	}  

	if ($ErrorExists == 0) {
		//echo $message.$query; exit;

		$queryRemark = "insert into temp_sorderJvRemarkdt (sorderJvRemarkdt_id, sorderJv_id, Remarkdt_id, sorderJvRemarkdt_chk) 
						select sorderJvRemarkdt_id, sorderJv_id, Remarkdt_id, sorderJvRemarkdt_chk 
						from sorderJvRemarkdt
						where sorderJv_id = $SId";	
		if (!updateData($connection, $queryRemark, true))
			$message  = mysql_error(); 	
		
		$query = " INSERT INTO Temp_SalesOrderJVDt (SalesOrderJVDt_Id, SalesOrderJV_Id, SalesOrderJV_Date, Currency_Code, Client_Code, Salesman_Code, Ledger_Number, SalesOrderJVDt_Description, SalesOrderJVDt_Description2, ". 
				 " Project_Code, Costcenter_Code, SalesOrderJVDt_Quantity, SalesOrderJVDt_Price, SalesOrderJVDt_PriceBase1, SalesOrderJVDt_PriceBase2, SalesOrderJVDt_DiscountPer, SalesOrderJVDt_DiscountAmount, ".
				 " SalesOrderJVDt_DiscountAmount1, SalesOrderJVDt_DiscountAmount2, SalesOrderJVDTCalcTotal, SalesOrderJVDt_VAT, Journal_Type, SalesOrderJvDt_ManualNo, Logged_Code )  ".
				 " SELECT SalesOrderJVDt_Id, SalesOrderJV_Id, SalesOrderJV_Date, Currency_Code, Client_Code, Salesman_Code, Ledger_Number, SalesOrderJVDt_Description, SalesOrderJVDt_Description2, ". 
				 " Project_Code, Costcenter_Code, SalesOrderJVDt_Quantity, SalesOrderJVDt_Price, SalesOrderJVDt_PriceBase1, SalesOrderJVDt_PriceBase2, SalesOrderJVDt_DiscountPer, SalesOrderJVDt_DiscountAmount, ".
				 " SalesOrderJVDt_DiscountAmount1, SalesOrderJVDt_DiscountAmount2, SalesOrderJVDTCalcTotal, SalesOrderJVDt_VAT, Journal_Type, SalesOrderJvDt_ManualNo, '".$_SESSION['useraccount']."'   ".
				 " FROM SalesOrderJVDt ".
				 " WHERE SalesOrderJV_ID = ".$SId;

		if (!updateData($connection, $query, true))
			$message  = mysql_error(); 			

	}
}

//Post Mode	

else if($mode == "post" && $SId != ''){  

	if (!isset($txtCurr))   $txtCurr = $base1;

	if (empty($txtDiscountAmt))	$txtDiscountAmt = 0;
	if (empty($txtDiscountPer))	$txtDiscountPer = 0;
	if (empty($txtVatChkbx))	$txtVatChkbx = 0;

	$txtCostCentCode = "".$txtCostCentCode;
	if ($txtCostCentCode == '')	$CostCentCode = "NULL";
	else						$CostCentCode = "'".$txtCostCentCode."'";

	$ProjectCode = "".$ProjectCode;
	if ($txtProjectCode == '')	$ProjectCode = "NULL";
	else						$ProjectCode = "'".$txtProjectCode."'";      

	if (empty($txtSalesmanCode))	$SalesmanCode = "NULL";
	else							$SalesmanCode = "'".ereg_replace("'", "\'", trim($txtSalesmanCode))."'";		

	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$txtCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$txtCurr."' )";
	$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];

	$ExceedCreditLimit = 0;
	$SaveAllowed = 1;
	$ErrorExists = 0;

	$vDtQty           = 0;
	$vDtDiscPer       = 0;
	$vDtTotal         = 0;
	$vDtPrice         = 0;
	$vDtPriceBase1    = 0;
	$vDtPriceBase2    = 0;
	$vDtDiscAmt       = 0;
	$vDtDiscAmtBase1  = 0;
	$vDtDiscAmtBase2  = 0;

	//Check For Client, Salesman, Project and Costcenter Codes Before Insert
	if ($txtCostCentCode != '') {
		$sub_query = " Select Count(Costcent_code) From Costcent ".
					 " Where Costcent_code = '".$txtCostCentCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) $ErrorExists = 1;
	}
	if ($txtProjectCode != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$txtProjectCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) $ErrorExists = 1;
	}
	if ($txtClientCode != '') {
		$sub_query = " Select Count(Ledger_Number) From Clients ".
					 " Where Ledger_Number = '".$txtClientCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) $ErrorExists = 1;
	}
	if ($txtSalesmanCode != '') {
		$sub_query = " Select Count(Ledger_Number) From Salesmen ".
					 " Where Ledger_Number = '".$txtSalesmanCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) $ErrorExists = 1;
	}	

	//Check User Access For Date Modification/ Lock Period
	$MainCompanyName=explode('_',$_SESSION['dbName']);

	$sub_query= " Select ifNull(AllowLockedPeriod,0) As AllowLockedPeriod, LockedPeriod As LockedPeriodDate, LockedPeriodDays As LockedPeriodDays ".
				" From ".$_SESSION['dbLabel'].".ListUserDir  ".
				" Where Usercode='".$_SESSION['useraccount']."' ".
				" And Upper(CompanyName) = Upper('".$MainCompanyName[0]."') ".
				" And Upper(Diryear) = Upper('".$MainCompanyName[1]."') ";

	$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
	$rowsperiod = mysql_num_rows($sub_result);

	while($sub_rows=mysql_fetch_array($sub_result)){
		extract($sub_rows);
	}	

	if ($rowsperiod > 0 && $AllowLockedPeriod == 1) { 
		if (!(empty($LockedPeriodDate)) && $LockedPeriodDate != '' && insertMySQLDate($txtDate) < $LockedPeriodDate) $ExceedLockPeriod = 1;
		if ($LockedPeriodDays != '' && dateDiff(insertMySQLDate(displayToday()),insertMySQLDate($txtDate)) > $LockedPeriodDays) $ExceedLockPeriod = 1;
	}
		

	if ($SaveAllowed == 1 && $ErrorExists == 0 && $ExceedLockPeriod == 0) {

		$sub_query = " Select SalesOrderJVDt_Id, Currency_Code, ifNull(SalesOrderJVDt_Price,0), ifNull(SalesOrderJVDt_PriceBase1,0), ifNull(SalesOrderJVDt_PriceBase2,0), ".
					 " ifNull(SalesOrderJVDt_DiscountAmount,0), ifNull(SalesOrderJVDt_DiscountAmount1,0), ifNull(SalesOrderJVDt_DiscountAmount2,0), ifNull(SalesOrderJVDTCalcTotal,0) ".
					 " From Temp_SalesOrderJVDt ".
					 " Where SalesOrderJV_Id = ".$SId;	
		$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
		while($sub_row=mysql_fetch_array($sub_result)){

			$vDtPrice         = $sub_row[2];
			$vDtPriceBase1    = $sub_row[3];
			$vDtPriceBase2    = $sub_row[4];
			$vDtDiscAmt       = $sub_row[5];
			$vDtDiscAmtBase1  = $sub_row[6];
			$vDtDiscAmtBase2  = $sub_row[7];
			$vDtTotal		  = $sub_row[8];

			if ($sub_row[1] != $txtCurr) {
				$vDtPrice    = ConvertCurrency($sub_row[1], $txtCurr, insertMySQLDate($txtDate), $vDtPrice, $connection);
				$vDtDiscAmt  = ConvertCurrency($sub_row[1], $txtCurr, insertMySQLDate($txtDate), $vDtDiscAmt, $connection);
				$vDtTotal    = ConvertCurrency($sub_row[1], $txtCurr, insertMySQLDate($txtDate), $vDtTotal, $connection);

				$vDtPriceBase1    = ($vDtPrice*$rate_dt)/$rate_dt1;
				$vDtPriceBase2    = ($vDtPrice*$rate_dt)/$rate_dt2;
				$vDtDiscAmtBase1  = ($vDtDiscAmt*$rate_dt)/$rate_dt1;
				$vDtDiscAmtBase2  = ($vDtDiscAmt*$rate_dt)/$rate_dt2;

				$sub_query1 = " UPDATE Temp_SalesOrderJVDt SET  ".
							  " SalesOrderJVDt_Price = $vDtPrice, SalesOrderJVDt_PriceBase1 = $vDtPriceBase1, SalesOrderJVDt_PriceBase2 = $vDtPriceBase2, ".
							  " SalesOrderJVDt_DiscountAmount = $vDtDiscAmt, SalesOrderJVDt_DiscountAmount1 = $vDtDiscAmtBase1, SalesOrderJVDt_DiscountAmount2 = $vDtDiscAmtBase2, ".
							  " SalesOrderJVDTCalcTotal = $vDtTotal ".
							  " Where SalesOrderJVDt_Id = ".$sub_row[0];
				//echo $sub_query1; exit;	
				if (!updateData($connection, $sub_query1, true))		 
					$message  = mysql_error(); 

			}
		}

		$sub_query2 = " UPDATE Temp_SalesOrderJVDt SET ".
					  " Currency_Code = '".$txtCurr."', SalesOrderJV_Date = '".insertMySQLDate($txtDate)."', ".
					  " Client_Code = '".ereg_replace("'", "\'", trim($txtClientCode))."' ";

		if ($Module_ProjectDt != 1)
			$sub_query2 = $sub_query2.", Project_Code = $ProjectCode ";
		if ($Module_CostCenterDt != 1)	
			$sub_query2 = $sub_query2.", CostCenter_Code = $CostCentCode ";

		$sub_query2 = $sub_query2." WHERE SalesOrderJV_Id = $SId ";

		//echo $querydt."<br>";exit;		   
		if (!updateData($connection, $sub_query2, true))		 
			$message  = mysql_error(); 

		//Distribute The Total Discount On Detail Table
		$sub_query3 = " Select Sum((ifNull(SalesOrderJVDt_Quantity,0)*ifNull(SalesOrderJVDt_Price,0))-((ifNull(SalesOrderJVDt_Quantity,0)*ifNull(SalesOrderJVDt_Price,0)*ifNull(SalesOrderJVDt_DiscountPer,0))/100)) As Total ".
					  " From Temp_SalesOrderJVDt ".
					  " Where SalesOrderJV_Id = ".$SId;
		$sub_result3 = selectData($connection, $sub_query3);
		$vTotal   = $sub_result3[0];	
		$vDisAmt  = $txtDiscountAmt;

		$sub_query4 = " Select SalesOrderJVDt_Id,  ".
					  " ((ifNull(SalesOrderJVDt_Quantity,0)*ifNull(SalesOrderJVDt_Price,0))-((ifNull(SalesOrderJVDt_Quantity,0)*ifNull(SalesOrderJVDt_Price,0)*ifNull(SalesOrderJVDt_DiscountPer,0))/100)) As Total ".
					  " From Temp_SalesOrderJVDt As SalesOrderJVDt  ".
					  " Where SalesOrderJVDt.SalesOrderJV_Id = ".$SId;

		//echo $query; 
		$sub_result4=mysql_query($sub_query4,$connection) or die(mysql_error());
		while($sub_rows4=mysql_fetch_array($sub_result4)){

			$vDtId      = $sub_rows4[0];
			$vDtTotal   = $sub_rows4[1];

			$vDtDiscAmt	     = 0;
			$vDtDiscAmt 	 = ($vDtTotal/$vTotal)*$vDisAmt;
			$vDtDiscAmtBase1 = ($vDtDiscAmt*$rate_dt)/$rate_dt1;
			$vDtDiscAmtBase2 = ($vDtDiscAmt*$rate_dt)/$rate_dt2;


			$queryupd =  " UPDATE Temp_SalesOrderJVDt SET ".
						" SalesOrderJVDt_DiscountAmount = $vDtDiscAmt, SalesOrderJVDt_DiscountAmount1 = $vDtDiscAmtBase1, SalesOrderJVDt_DiscountAmount2 = $vDtDiscAmtBase2  ".
						" Where SalesOrderJVDt_Id = ".$vDtId;
			
			if (!updateData($connection, $queryupd, true))
				$error  = mysql_error(); 

		}

		//Calculating Master Amounts
		$CalculateResult = Calculate_MasterAmounts($SId, $txtDate, $SVatChkbx, $txtDiscountPer, $txtDiscountAmt, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Setup_VatPercentage, 'P', $connection);
		$message  = $message . $CalculateResult;

		$Acc_Query = " SELECT VATAccountNonStock, DiscountAccount FROM salessetup ";
		$Acc_Result = selectData($connection, $Acc_Query);

		//$vVatAccount = $Acc_Result[0];
		if (empty($txtVatPrefix)) $vVatAccount = $Acc_Result[0];
		else $vVatAccount = $txtVatPrefix;

		$sub_queryVat = " SELECT GetVATAccount('".$txtClientCode."','".$vVatAccount."') from dual ";
		$sub_resultVat = selectData($connection, $sub_queryVat);
		if ($sub_resultVat[0] != '') $vVatAccount = $sub_resultVat[0];

		/////update

		$sub_query5 = " UPDATE Temp_SalesOrderJV SET ".
					  " SalesOrderJV_Date = '".insertMySQLDate($txtDate)."' , SalesOrderJv_ManualNo = '".ereg_replace("'", "\'", trim($txtManualNo))."', ".
					  " JournalDt_ValueDate = '".insertMySQLDate($txtMaturityDate)."' , ".
					  " Sales_Remark = '".ereg_replace("'", "\'", trim($txtRemark))."', Client_Code = '".ereg_replace("'", "\'", trim($txtClientCode))."', ".
					  " Salesman_Code = $SalesmanCode, Currency_Code = '".$txtCurr."', Project_Code = $ProjectCode, Costcenter_code = $CostCentCode,  ".
					  " SalesOrderJv_VatPrefix = '".trim($txtVatPrefix)."', SalesOrderJV_VatAccount =  '".$vVatAccount."',  ".
					  " salesOrderjv_PaymentTerms = ".GetSQLValueString($txtterms,'text')." ".
					  " WHERE SalesOrderJV_ID = $SId ";
		$sub_result5=mysql_query($sub_query5,$connection);		 
		//echo $sub_query5; exit;		 
		if ($sub_result5){

			if ($mainmode == 'insert') $SMode = 'I';
			if ($mainmode == 'edit') $SMode = 'U';
			//echo $SMode;exit;

			$vOldProjCode  	  = '';
			$vOldCostCentCode = '';

			// In Edit Case, Get The Old Values Project and Costcenter For References Issue
			$query   = " SELECT Project_Code, Costcenter_code  FROM SalesOrderJV WHERE SalesOrderJV_ID = $SId ";
			$result  = selectData($connection, $query);
			$vOldProjCode  	  = $result[0];
			$vOldCostCentCode = $result[1];

			$query = "Select Count(*) From Temp_SalesOrderJV where SalesOrderJV_ID = '".$SId."'";
			//echo $query; exit;
			$result = selectData($connection, $query);
			$ExistInTemp = $result[0];	

			//Check If Record Exists In Temp Tables
			if ($ExistInTemp == 1) {

				fbegin();		
				$query_checkDelivery  = "select count(*) as SalesOrderJvExist from salesOrderjv where SalesOrderJv_Id = '$SId'";
					$result_checkDelivery = mysql_query($query_checkDelivery, $connection); 
					$row_checkDelivery    = mysql_fetch_array($result_checkDelivery);
					extract($row_checkDelivery);
					if($SalesJvExist > 0){
						$transType = "U";
					}
					else{
						$transType = "I";
					}
					$company = explode("_", $_SESSION['dbName']);
					$currCompany = strtoupper($company[0]);
					$query = " SELECT CopyData_TempSalesOrderJV('".$SMode."', ".$SId.", '".$_SESSION['useraccount']."') FROM Dual ";//echo $query; exit;
					$result = selectData($connection, $query);
					$result = $result[0];
				
				//echo 'error='.$result; exit;
				if ($result != 0){ 
					fcommit();

					$query   = " SELECT SalesOrderJV_Reference, Costcenter_code, Project_Code FROM SalesOrderJV WHERE SalesOrderJV_ID = '".$SId."'";
					$result  = selectData($connection, $query);
					$vRef  = $result[0];
					$vCostCentCode = $result[1];
					$vProjectCode  = $result[2];

					$existCode = 0;
					if ($vOldCostCentCode != $txtCostCentCode && $Module_ReferenceByCostcenter == 1 && $vRef != ''){
						$querychk = "select 1 from sequence where '$vOldCostCentCode' like Concat(Sequence.CostCenter,'%') and '$txtCostCentCode' like Concat(Sequence.CostCenter,'%') ";
						$reschk = mysql_query($querychk, $connection);
						$rwchk = mysql_fetch_row($reschk);
						$existCode = $rwchk[0];
					}
					if ($vOldProjCode != $txtProjectCode && $Module_ReferenceByProject == 1 && $vRef != ''){
						$querychk = "select 1 from sequence where '$vOldProjCode' like Concat(Sequence.Project,'%') and '$txtProjectCode' like Concat(Sequence.Project,'%') ";
						$reschk = mysql_query($querychk, $connection);
						$rwchk = mysql_fetch_row($reschk);
						$existCode = $rwchk[0];
					}
					$sendEmail = 0;
					if ($vRef == '' || ($vOldProjCode != $txtProjectCode && $Module_ReferenceByProject == 1 && $existCode == 0) ||
						 ($vOldCostCentCode != $txtCostCentCode && $Module_ReferenceByCostcenter == 1 && $existCode == 0)) {

						if ($Module_ReferenceByCostcenter == 1)   $vProjCostCent = $vCostCentCode;
						else if ($Module_ReferenceByProject == 1) $vProjCostCent = $vProjectCode;
						else $vProjCostCent = '';

						fbegin();
						$vRef = get_nextsequence('SalesOrderJV_Reference',$vProjCostCent,$connection);	
						fcommit();

						$query = " UPDATE SalesOrderJV SET ".
								 " SalesOrderJV_Reference = $vRef ".
								 " WHERE SalesOrderJV_ID = $SId ";

						if (!updateData($connection, $query, true)) 
							$message  = mysql_error();
						

					}	
				} else{
					$ErrorExists = 1;
					//$message  = mysql_error(); 
					$message  = 'Error In CopyData_TempSalesOrderJV Function.'; 
					frollback();
				}

			}

			if($config['log_file'] == 1){
						$query_insertToHistory  = "call ".$config['dbName_history'].".InsertToHistory('$transType', '$SId', '".$_SESSION['useraccount']."', now(), '".$_SESSION['dbName']."', 'salesOrderjv', '$currCompany')";
					//echo $query_insertToHistory;exit;
					$result_insertToHistory = mysql_query($query_insertToHistory, $connection);
						}

		} else{
			$message  = mysql_error(); 
			frollback();
		}

	}
	else {
		if ($ErrorExists == 1)	{/*	$message = 'Save not allowed. Please check for Client/Salesman/Project/Costcenter Code.';*/}

		else if ($ExceedLockPeriod == 1)
			$message = 'Save not allowed. Exceed Lock Period.';

	}
}

	if($mainmode == "editfromreport"){
		$ErrorExists = 0;
	//Copy Data From Main Tables To Temp Tables
	$query = " INSERT INTO Temp_SalesOrderJV (SalesOrderJV_ID, SalesOrderJV_Reference, SalesOrderJV_Date, JournalDt_ValueDate, Client_Code, Salesman_Code, Sales_Remark, ".
			 " Currency_Code, Project_Code, Costcenter_Code, SalesOrderJV_Posted, SalesOrderJV_Edit, Sales_Mode, SalesOrderJV_BelongsToGroup, Journal_Type, Journal_Id, ".
			 " SalesOrderJV_Taxable, SalesOrderJV_TaxableBase1, SalesOrderJV_TaxableBase2, SalesOrderJV_NoneTaxable, SalesOrderJV_NoneTaxableBase1, SalesOrderJV_NoneTaxableBase2, ".
			 " SalesOrderJV_Total, SalesOrderJV_TotalBase1, SalesOrderJV_TotalBase2, SalesOrderJV_VAT, SalesOrderJV_VatBase1, SalesOrderJV_VatBase2, SalesOrderJV_VatCheck, SalesOrderJV_DiscountPer, ".
			 " SalesOrderJV_DiscountAmount, SalesOrderJV_DiscountAmount1, SalesOrderJV_DiscountAmount2, SalesOrderJV_VatAccount, SalesOrderJV_DiscountAccount, SalesOrderJv_ManualNo, ".
			 " SalesOrderJv_VatPrefix, User_Account, Logged_Code ) ".
			 " SELECT SalesOrderJV_ID, SalesOrderJV_Reference, SalesOrderJV_Date, JournalDt_ValueDate, Client_Code, Salesman_Code, Sales_Remark, ".
			 " Currency_Code, Project_Code, Costcenter_Code, SalesOrderJV_Posted, SalesOrderJV_Edit, Sales_Mode, SalesOrderJV_BelongsToGroup, Journal_Type, Journal_Id, ".
			 " SalesOrderJV_Taxable, SalesOrderJV_TaxableBase1, SalesOrderJV_TaxableBase2, SalesOrderJV_NoneTaxable, SalesOrderJV_NoneTaxableBase1, SalesOrderJV_NoneTaxableBase2, ".
			 " SalesOrderJV_Total, SalesOrderJV_TotalBase1, SalesOrderJV_TotalBase2, SalesOrderJV_VAT, SalesOrderJV_VatBase1, SalesOrderJV_VatBase2, SalesOrderJV_VatCheck, SalesOrderJV_DiscountPer, ".
			 " SalesOrderJV_DiscountAmount, SalesOrderJV_DiscountAmount1, SalesOrderJV_DiscountAmount2, SalesOrderJV_VatAccount, SalesOrderJV_DiscountAccount, SalesOrderJv_ManualNo, ".
			 " SalesOrderJv_VatPrefix, User_Account, '".$_SESSION['useraccount']."'  ".
			 " FROM SalesOrderJV ".
			 " WHERE SalesOrderJV_ID = ".$SId;

	if (!updateData($connection, $query, true)) {
		$ErrorExists = 1;
		$message  = mysql_error(); 	
	}  

	if ($ErrorExists == 0) {
		//echo $message.$query; exit;				 
		$query = " INSERT INTO Temp_SalesOrderJVDt (SalesOrderJVDt_Id, SalesOrderJV_Id, SalesOrderJV_Date, Currency_Code, Client_Code, Salesman_Code, Ledger_Number, SalesOrderJVDt_Description, SalesOrderJVDt_Description2, ". 
				 " Project_Code, Costcenter_Code, SalesOrderJVDt_Quantity, SalesOrderJVDt_Price, SalesOrderJVDt_PriceBase1, SalesOrderJVDt_PriceBase2, SalesOrderJVDt_DiscountPer, SalesOrderJVDt_DiscountAmount, ".
				 " SalesOrderJVDt_DiscountAmount1, SalesOrderJVDt_DiscountAmount2, SalesOrderJVDTCalcTotal, SalesOrderJVDt_VAT, Journal_Type, SalesOrderJvDt_ManualNo, Logged_Code )  ".
				 " SELECT SalesOrderJVDt_Id, SalesOrderJV_Id, SalesOrderJV_Date, Currency_Code, Client_Code, Salesman_Code, Ledger_Number, SalesOrderJVDt_Description, SalesOrderJVDt_Description2, ". 
				 " Project_Code, Costcenter_Code, SalesOrderJVDt_Quantity, SalesOrderJVDt_Price, SalesOrderJVDt_PriceBase1, SalesOrderJVDt_PriceBase2, SalesOrderJVDt_DiscountPer, SalesOrderJVDt_DiscountAmount, ".
				 " SalesOrderJVDt_DiscountAmount1, SalesOrderJVDt_DiscountAmount2, SalesOrderJVDTCalcTotal, SalesOrderJVDt_VAT, Journal_Type, SalesOrderJvDt_ManualNo, '".$_SESSION['useraccount']."'   ".
				 " FROM SalesOrderJVDt ".
				 " WHERE SalesOrderJV_ID = ".$SId;

		if (!updateData($connection, $query, true))
			$message  = mysql_error(); 			

	}

	header ("Location: ./Form_SalesOrderJV.php?actionmode=&mainaction=edit&txtSalesOrderJVId=".$SId);
	}

$message = ereg_replace(' ','%20',$message);
$message = ereg_replace('#','%23',$message);
$message = ereg_replace('&','%26',$message);

$PRemark = ereg_replace(' ','%20',$PRemark);
$PRemark = ereg_replace('#','%23',$PRemark);
$PRemark = ereg_replace('&','%26',$PRemark);

$PManualNo = ereg_replace(' ','%20',$PManualNo);
$PManualNo = ereg_replace('#','%23',$PManualNo);
$PManualNo = ereg_replace('&','%26',$PManualNo);

//echo $mode.$message; exit;

if($mode == "post") {
	if ($SaveAllowed == 1)
		header ("Location: ./Form_SalesOrderJV.php?actionmode=".$mode."&mainaction=".$mainmode."&message=".$message."&PrId=".$SId."&PrRef=".$vRef);
	else
		header ("Location: ./Form_SalesOrderJV.php?actionmode=submitrecord&mainaction=".$mainmode."&message=".$message."&txtSalesOrderJVId=".$SId);
}	
else if ($mode == "" && $mainmode == "delete" )	
	header ("Location: ./Form_SalesOrderJVSearch.php?message=".$message);
else if ($mode == "" && $mainmode == "deletepending")	
	header ("Location: ./Form_SalesOrderJVSearchPending.php?message=".$message);
else if ($mode == "deletedt" )		
	header ("Location: ./Form_SalesOrderJV.php?actionmode=".$mode."&mainaction=".$mainmode."&message=".$message."&txtSalesOrderJVId=".$SId);	
else if ($mode == "editdt")		
	header ("Location: ./Form_SalesJVDetail.php?actionmode=".$mode."&mainaction=".$mainmode."&message=".$message."&PId=".$SId."&PDate=".$PDate."&PDtId=".$PDtId);
else if ($mode == "" && $mainmode == "search" )		
	header ("Location: ./Form_SalesOrderJVSearch.php?PMode=1&message=".$message);
else if ($mode == "submitrecord" ){
    header ("Location: ./Form_SalesJVDetail.php?actionmode=".$mode."&mainaction=".$mainmode."&PId=".$SId."&PDate=".$PDate."&PMaturityDate=".$PMaturityDate.	
			"&PClientCode=".$PClientCode."&PSalesmanCode=".$PSalesmanCode."&PCurr=".$PCurr."&PProjectCode=".$PProjectCode.
			"&PCostCentCode=".$PCostCentCode."&PDiscountPer=".$PDiscountPer."&PDiscountAmt=".$PDiscountAmt."&PVatChkbx=".$PVatChkbx.
			"&PManualNo=".$PManualNo."&PRemark=".$PRemark."&message=".$message);
}	

function Calculate_MasterAmounts($PId, $PDate, $PVatChk, $PDiscPer, $PDiscAmt, $PRate, $PRate1, $PRate2, $PSetupVatStartDate, $PSetupVatPercentage, $PMode, $connection) {

	$vDtTotal  = 0;
	$vDtVatChk = 0;

	$vTaxable        = 0;
	$vNoneTaxable    = 0;
	$vGrossTotal     = 0;
	$vDiscountAmt    = 0;
	$vDiscountPer    = 0;
	$vVatAmt      = 0;
	$vVatAmtBase1 = 0;
	$vVatAmtBase2 = 0;

	$vDiscountPer = $PDiscPer;

	// In Case Not Save, Then Get The Vat CheckBox From Table Sorder
	if ($PMode != 'P') {
		$sub_query = "Select ifNull(SalesOrderJV_VatCheck, 0) From Temp_SalesOrderJV Where SalesOrderJV_ID = '".$PId."'";
		//echo "<br><br>".$sub_query;
		$sub_result = selectData($connection, $sub_query);
		$PVatChk    = $sub_result[0];

	}

	//Calculating Master Amounts
	$sub_query = " Select Ledger_Number, ((ifNull(SalesOrderJVDt_Quantity,0)*ifNull(SalesOrderJVDt_Price,0))-((ifNull(SalesOrderJVDt_Quantity,0)*ifNull(SalesOrderJVDt_Price,0)*ifNull(SalesOrderJVDt_DiscountPer,0))/100)) As Total, ".
				 " ifNull(SalesOrderJVDt_VAT,0),  SalesOrderJVDt_Quantity, ifNull(SalesOrderJVDt_DiscountAmount,0) ".
				 " From Temp_SalesOrderJVDt ".
				 " Where SalesOrderJV_ID = ".$PId;

	//echo $sub_query;
	$sub_result=mysql_query($sub_query,$connection) or die(mysql_error());
	while($sub_rows=mysql_fetch_array($sub_result)){

		$vDtTotal   = $sub_rows[1];
		$vDtVatChk  = $sub_rows[2];

		$tax_flag = 0;
		$notax_flag = 1;
		if ($vDtVatChk > 0){
			$tax_flag = 1;
			$notax_flag = 0;
		}	

		$vTaxable     = $vTaxable     + ($vDtTotal*$tax_flag);
		$vNoneTaxable = $vNoneTaxable + ($vDtTotal*$notax_flag);

		// Calculation of Vat Amount
		if ((insertDate($PDate) > $PSetupVatStartDate && $PSetupVatPercentage > 0)  && $PVatChk == 1 && $vDtVatChk == 1 && $vDtTotal > 0)
			$vVatAmt = $vVatAmt + (($vDtTotal - $sub_rows[4])*$PSetupVatPercentage/100);

	}			

	$vGrossTotal = $vTaxable + $vNoneTaxable;

	// Calculation of Discount Amount	

	if ($PMode == 'P') {
		$vDiscountAmt      = $PDiscAmt;					
	} else {
		if ($vDiscountPer > 0) {
			$vDiscountAmt     = (($vGrossTotal * $vDiscountPer) / 100);
		}	
	}

	$vNetTotal         = $vGrossTotal + $vVatAmt - $vDiscountAmt;
	$vTaxableBase1     = ($vTaxable*$PRate)/$PRate1;
	$vTaxableBase2     = ($vTaxable*$PRate)/$PRate2;
	$vNoneTaxableBase1 = ($vNoneTaxable*$PRate)/$PRate1;
	$vNoneTaxableBase2 = ($vNoneTaxable*$PRate)/$PRate2;
	$vDiscountAmtBase1 = ($vDiscountAmt*$PRate)/$PRate1;
	$vDiscountAmtBase2 = ($vDiscountAmt*$PRate)/$PRate2;
	$vGrossTotalBase1  = ($vGrossTotal*$PRate)/$PRate1;
	$vGrossTotalBase2  = ($vGrossTotal*$PRate)/$PRate2;
	$vVatAmtBase1 	   = ($vVatAmt*$PRate)/$PRate1;
	$vVatAmtBase2 	   = ($vVatAmt*$PRate)/$PRate2;

	fbegin();

	$sub_query1 = " UPDATE Temp_SalesOrderJV SET ".
				  " SalesOrderJV_Taxable = $vTaxable, SalesOrderJV_TaxableBase1 = $vTaxableBase1, SalesOrderJV_TaxableBase2 = $vTaxableBase2, ".
				  " SalesOrderJV_NoneTaxable = $vNoneTaxable, SalesOrderJV_NoneTaxableBase1 = $vNoneTaxableBase1, SalesOrderJV_NoneTaxableBase2 = $vNoneTaxableBase2, ".
				  " SalesOrderJV_DiscountAmount = $vDiscountAmt, SalesOrderJV_DiscountAmount1 = $vDiscountAmtBase1, SalesOrderJV_DiscountAmount2 = $vDiscountAmtBase2, ".
				  " SalesOrderJV_DiscountPer = $vDiscountPer, SalesOrderJV_VAT = $vVatAmt, SalesOrderJV_VatBase1 = $vVatAmtBase1, SalesOrderJV_VatBase2 = $vVatAmtBase2, ".
				  " SalesOrderJV_VatCheck = $PVatChk, ".
				  " SalesOrderJV_Total = $vGrossTotal, SalesOrderJV_TotalBase1 = $vGrossTotalBase1, SalesOrderJV_TotalBase2 = $vGrossTotalBase2 ".
				  " WHERE SalesOrderJV_ID = ".$PId;

	$sub_result1=mysql_query($sub_query1,$connection);
	//echo $sub_query1."<br>";exit;
	if ($sub_result1){
		fcommit();

	}else{
		$message  = mysql_error(); 
		$error = 'Error In Function Calculate_MasterAmounts: '.$message;
		frollback();
	}

	Return $error;		

}



?>