<?php

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


include("config.inc.php");
include("Functions_Sales.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");



//Read From Login Table
$querylog=" select ifNull(Unmodify_sellingprice,0) As Unmodify_SellingPrice, ifNull(FI_DeliverySalesPrice,0) As FI_DeliverySalesPrice, ".
          " ifNull(Login_ModifyDiscount,0) As Login_ModifyDiscount, ifNull(Login_ModifySellingPrice,0) As Login_ModifySellingPrice ".
          " 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);
}
//echo $querylog;
	
//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);
}

//Read From Module Table
$querymodule=" Select ifNull(Module_AdditionalTaxes,0) As Module_AdditionalTaxes, ifNull(Module_Pack,0) As Module_Pack, ifNull(Module_Delivery,0) As Module_Delivery, ".
			 " ifNull(module_DeliveryWithSorder,0) As Module_DeliveryWithSorder, ifNull(Module_NegativeQuantity,0) As Module_NegativeQuantity, ".
			 " ifNull(Module_SerialNo,0) As Module_SerialNo, ifNull(Module_DoubleUnit,0) As Module_DoubleUnit, ifNull(Module_Unit1Method,0) As Module_Unit1Method, ".
			 " ifNull(Module_ProjectDt,0) As Module_ProjectDt, ifNull(Module_CostCenterDt,0) As Module_CostCenterDt, ".
			 " ifNull(Module_ExpireDate,0) As Module_ExpireDate ".
			 " 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, Warehouse As SetupDftWareHouse From SalesSetup";
$resultSalesSetup=mysql_query($querySalesSetup,$connection) or die(mysql_error());
while($rowSalesSetup=mysql_fetch_array($resultSalesSetup)){
	extract($rowSalesSetup);
}



//Warehouse List
$querywarehouse=" select distinct warehouse.warehouse_code, warehouse_name ".
				" from warehouse where warehouse_code in (select warehouse_code from ".$HTTP_SESSION_VARS['dbLabel'].".loginstk where user_account='".$HTTP_SESSION_VARS['useraccount']."') ".
				" order by warehouse.warehouse_code";
$resultwh = mysql_query($querywarehouse,$connection) or die(mysql_error());
$whexist   = mysql_num_rows($resultwh);
if ($whexist == 0)
	$querywarehouse="select warehouse_code,warehouse_name from warehouse order by warehouse_code";
	
$resultwarehouse=mysql_query($querywarehouse,$connection) or die(mysql_error());


//Group List
$querygroup= " select distinct group_code, group_name ".
			 " from grouping where group_code in (select group_code from ".$HTTP_SESSION_VARS['dbLabel'].".loginstk where user_account='".$HTTP_SESSION_VARS['useraccount']."') ".
			 " order by group_code";
$resultgroup = mysql_query($querygroup,$connection) or die(mysql_error());
$groupexist   = mysql_num_rows($resultgroup);
if ($groupexist == 0)
	$querygroup="select group_code, group_name from grouping order by group_code";
	
$resultgroup=mysql_query($querygroup,$connection) or die(mysql_error());

$querydflwh="select warehouse_code as defaultwarehouse from ".$HTTP_SESSION_VARS['dbLabel'].".loginstk where user_account='".$HTTP_SESSION_VARS['useraccount']."' and ifNull(default_warehouse,0) = 1 ";
$resultdflwh=mysql_query($querydflwh,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultdflwh)){
  extract($rows);
}


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


function SubmitRecord(ItemExpire) {
	x = document.returnsalesdt;
	
	var result = CheckFields(ItemExpire);
	var vRSaId    = x.PRSaId.value;
	var vRSaDtId  = x.txtRSaDtId.value;
	var vMainMode = x.mainaction.value;
	var vMode= x.actionmode.value;
	
	if (vRSaDtId == '')
		vMode = 'submitrecord';	
	else
		vMode = 'editdt';	
	   
	if (result == 1) {
		x.action="Form_ReturnDelivery_Actions.php?mode="+vMode+"&mainmode="+vMainMode+"&SRSaId="+vRSaId+"&SRSaDtId="+vRSaDtId;
		x.submit();
		
	}	
}

function ChangeLocation() {
	x = document.returnsalesdt;
	var vMode = x.actionmode.value;
	
	if (vMode == 'submitrecord') {
		
		opener.document.returnsales.actionmode.value = x.actionmode.value;
		opener.document.returnsales.mainaction.value = x.mainaction.value;
		//opener.document.returnsales.message.value = x.message.value;
		opener.document.returnsales.txtRSaId.value = x.PRSaId.value;
		opener.document.returnsales.submit();
		
	} 
	else if (vMode == 'submitrecord' || vMode == 'editdt') {
		opener.document.returnsales.actionmode.value = x.actionmode.value;
		opener.document.returnsales.mainaction.value = x.mainaction.value;
		opener.document.returnsales.txtRSaId.value = x.PRSaId.value;
		opener.document.returnsales.submit();
		
		self.close();
	
	}
	
	//x.txtItemCode.focus();
}

function CheckFields(ItemExpire){
  
    x = document.returnsalesdt;
	
	var vmode = x.actionmode.value;
	
	var vRSaDtItem	 	= x.txtItemCode.value;
	var vRSaDtWarehouse = x.lstWarehouse.value;
	var vRSaDtQty       = x.txtRSaDtQty.value;
	var vRSaDtQty2	    = x.txtRSaDtQty2.value;
	var vRSaDtPrice     = x.txtRSaDtPrice.value;
	var vRSaDtDisc      = x.txtRSaDtDiscount.value;
	var vRemainQty      = x.txtRemainedQty.value;
	var vDirectReturn   = x.PRSaDirectReturn.value;
	
	var vRSaDtExpireDate = x.txtRSaDtExpireDate.value;
	var vRSaDtBatchNo    = x.txtRSaDtBatchNo.value;
	
	
	if (vRSaDtPrice == '')   vRSaDtPrice = 0;
	if (vRSaDtDisc == '')    vRSaDtDisc = 0;
	if (vRSaDtQty == '')     vRSaDtQty = 0;
	if (vRSaDtQty2 == '')    vRSaDtQty2 = 0;
	if (vRemainQty == '')  	 vRemainQty = 0;
	if (vDirectReturn == '') vDirectReturn = 0;
	
	vRSaDtQty  = parseInt(vRSaDtQty);	
	vRemainQty = parseInt(vRemainQty);
	
	if (vRSaDtWarehouse=='')
	{
		alert("Warehouse is mandatory!");
		x.lstWarehouse.focus();
		return 0;
	}
	else if (vRSaDtItem=='')
	{
		alert("Item is mandatory!");
		x.txtItemCode.focus();
		return 0;
	}
	else if ( vRSaDtQty*1 != vRSaDtQty/1 || vRSaDtQty < 0) {
		alert('Quantity ('+vRSaDtQty+') should be a NUMERIC and POSITIVE value. ');
		x.txtRSaDtQty.focus();
		return 0;
	}
	else if ( vRSaDtQty > vRemainQty && vDirectReturn == 0) {
		alert('Quantity ('+vRSaDtQty+') should be NOT MORE than [Remaining Invoice Qty ('+vRemainQty+')] ');
		x.txtRSaDtQty.focus();
		return 0;
	}
	else if ((vRSaDtPrice*1 != vRSaDtPrice/1 || vRSaDtPrice < 0) ) {
		alert('Price should be a NUMERIC and POSITIVE value.');
		x.txtRSaDtPrice.focus();
		return 0;
	}
	else if (vRSaDtDisc*1 != vRSaDtDisc/1 || vRSaDtDisc < 0) {
		alert('Discount should be a NUMERIC and POSITIVE value.');
		x.txtRSaDtDiscount.focus();
		return 0;
	}
	else if ((vRSaDtQty2 != '' && vRSaDtQty2*1 != vRSaDtQty2/1) ) {
		alert('Item Qty2 should be a NUMERIC value.');
		x.txtRSaDtQty2.focus();
		return 0;
	}
	else if (ItemExpire == 1 && vRSaDtExpireDate == '' ) {
		alert('Item Expire Date is mandatory.');
		x.txtRSaDtExpireDate.focus();
		return 0;
	}
	else if (ItemExpire == 1 && vRSaDtBatchNo == '' ) {
		alert('Item Batch No is mandatory.');
		x.txtRSaDtBatchNo.focus();
		return 0;
	}
		
	
	else
	return 1 ;	
}






//All= All form; D= Detail Part
function ClearForm(Option){
    x = document.returnsalesdt;
	var vmode = x.actionmode.value;
	
	if (Option == 'D')
	{
		x.txtRSaDtId.value='';
		x.txtItemCode.value='';
		x.txtItemDesc.value='';
		x.lstWarehouse.value='';
		x.txtWarehouseName.value='';
		x.lstGroup.value='';
		x.txtRSaDtRemark.value='';
		x.txtRSaDtQty.value='';
		x.txtRSaDtQty2.value='';
		x.txtDeliveryRef.value='';
		x.txtRemainedQty.value='';
		x.txtRSaDtPrice.value='';
		x.txtRSaDtDiscount.value='';
		x.txtRSaDtTotal.value='';
		x.txtRSaDtVat.value='';
		x.txtRSaDtExpireDate.value='';
		x.txtRSaDtBatchNo.value='';
		
		//x.message.value='';
		x.actionmode.value = '';
	
	}

}


function CalcRSaDtTotal(dec) {
	x = document.returnsalesdt;
	var vmode = x.actionmode.value;
	var Qty = x.txtRSaDtQty.value;
	var Price = x.txtRSaDtPrice.value;
	var Discount = x.txtRSaDtDiscount.value;
	if (Qty == '') Qty = 0;
	if (Price == '') Price = 0;
	if (Discount == '') Discount = 0;
	
	Qty = parseInt(Qty);
	Price = parseFloat(Price);
	Discount = parseFloat(Discount);
	
	if (Qty > 0 && Price >= 0)
	   x.txtRSaDtTotal.value = Math.round(((Qty*Price) - (Qty*Price*Discount/100))*Math.pow(10,dec))/Math.pow(10,dec);

}


function CalcQty2(ModuleUnit1Method,UnitCoef,Option) {
	x = document.returnsalesdt;
	var Qty  = x.txtRSaDtQty.value;
	var Qty2 = x.txtRSaDtQty2.value;
	
	if (Qty == '')  Qty = 0;
	if (Qty2 == '') Qty2 = 0;
	
	if(ModuleUnit1Method == 1) {
		if (Qty > 0 && Option == 1 && document.getElementById('txtRSaDtQty2').type == 'text') {
			x.txtRSaDtQty2.value = Qty*UnitCoef;
		}	
		else if (Qty == 0 && Option == 1 && document.getElementById('txtRSaDtQty2').type == 'text') {
			x.txtRSaDtQty2.value = '';
		}
	}
	//Case Modify Qty and Qty2 Should Be Empty
	else if(ModuleUnit1Method == 0 && Option == 1 && Qty2 == 0) {
		if (Qty > 0 && UnitCoef != 0 && document.getElementById('txtRSaDtQty2').type == 'text') {
			x.txtRSaDtQty2.value = Qty/UnitCoef;
		}	
		else if (Qty == 0 && document.getElementById('txtRSaDtQty2').type == 'text') {
			x.txtRSaDtQty2.value = '';
		}
	}
	//Case Modify Qty2 Get Qty
	else if(ModuleUnit1Method == 0 && Option == 2) {
		if (Qty2 > 0 && document.getElementById('txtRSaDtQty2').type == 'text') {
			x.txtRSaDtQty.value = Qty2*UnitCoef;
		}	
		else if (Qty2 == 0 && document.getElementById('txtRSaDtQty2').type == 'text') {
			x.txtRSaDtQty.value = '';
		}
	}
}

function SetItemVat(ModuleDelivery) {
	x = document.returnsalesdt;
	var vmode = x.actionmode.value;
	
	if (ModuleDelivery == 0 && document.getElementById('chkRSaDtVat')) {
		if (x.txtRSaDtVat.value == 1)
		   x.chkRSaDtVat.checked = true;
	}
	   
}


function showlistItems(str){
  var vdate, vid, vItemType, vItemSort,vItemCode;
  x = document.returnsalesdt;
  
  vdate		 = x.PRSaDate.value;
  vid   	 = x.PRSaId.value;
  vItemType  = x.lstItemType.value;
  vItemSort  = x.lstItemSort.value;
  vItemGroup = x.lstGroup.value;
  vItemWh    = x.lstWarehouse.value;
  vItemCode  = x.txtItemCode.value;
  
  vItemWh = vItemWh.replace('&','%26');
  
  window.open('List_SorItems.php?frm=6&PItem_Code='+vItemCode+'&ItemType='+vItemType+'&ItemSort='+vItemSort+'&ItemGroup='+vItemGroup+'&ItemWh='+vItemWh+'&TransDate='+vdate,'mywindow','width=850,height=400,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}

function showlistBatchNo(str) {
	x = document.returnsalesdt;
	vItemCode  = x.txtItemCode.value;
	
	window.open('List_BatchNo.php?frm=4&PItem_Code='+vItemCode,'List_BatchNo','width=580,height=400,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}

function showlistProject(str){

  window.open('List_SorProject.php?frm=22&item='+str,'mywindow','width=850,height=550,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}

function showlistCostcenter(str){

  window.open('List_SorCostcenter.php?frm=22&item='+str,'mywindow','width=850,height=550,,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}

function RefreshPage()
{
  document.returnsalesdt.submit();

}

function kd(e)
{
	x=document.returnsalesdt;
    var intKey = (window.Event) ? e.which : e.keyCode;
    if (intKey == 13) { //enter key
        //x.btnSubmitRecord.click();
		return false;
    }
    return true;
}

</script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Delivery Detail - Add Items</title>


<script type="text/javascript" src="dropdown.js"></script>
<link rel="stylesheet" href="default.css" type="text/css" />
<link rel="stylesheet" href="short.css" type="text/css" />
<link rel="stylesheet" href="dropdown.css" type="text/css" />
<style type="text/css">

body,td,th {
	font-family: Verdana, Arial, Helvetica, sans-serif;
	font-size: 11px;
}
body {
	margin-top: 2px;
	margin-left: 1px;
}
a:link {
	text-decoration: none;
	color: #0000FF;
}
a:visited {
	text-decoration: none;
	color: #0000FF;
}
a:hover {
	text-decoration: none;
	color: #0000FF;
}
a:active {
	text-decoration: none;
	color: #0000FF;
}
.style11 {color: #999999; font-weight: bold; }
.style12 {
	font-size: 9px;
	color: #999999;
	font-weight: bold;
}
.style15 {color: #5151FF; font-size: 10px;}
.style16 {
	font-size: 16px;
	color: #FF0000;
	font-weight: bold;
	font-family: "Times New Roman", Times, serif;
}
.style17 {font-size: 9px}
.style25 {color: #999999; font-weight: bold; font-size: 10px; }
.style26 {color: #FF0000}
.style27 {color: #999999 ;font-size: 10px;}
.style28 {color: #FFFFFF ;font-size: 10px;}

</style>

<link type="text/css" rel="stylesheet" href="dhtmlgoodies_calendar.css?random=20051112" media="screen"></LINK>
<SCRIPT type="text/javascript" src="dhtmlgoodies_calendar.js?random=20060118"></script>

</head>
<body onLoad='ChangeLocation();' >
<form name='returnsalesdt' method='post'>
<input type='hidden' name='mainaction' value='$mainaction'>
<input type='hidden' name='actionmode' value='$actionmode'>
<input type='hidden' name='PRSaDate' value='$PRSaDate'>
<input type='hidden' name='PRSaId' value='$PRSaId'>
<input type='hidden' name='PRSaDtId' value='$PRSaDtId'>
<input type='hidden' name='PRSaMaturityDate' value='$PRSaMaturityDate'>
<input type='hidden' name='PRSaClientCode' value='$PRSaClientCode'>
<input type='hidden' name='PRSaSalesmanCode' value='$PRSaSalesmanCode'>
<input type='hidden' name='PRSaProjectCode' value='$PRSaProjectCode'>
<input type='hidden' name='PRSaCostCentCode' value='$PRSaCostCentCode'>
<input type='hidden' name='PRSaCurr' value='$PRSaCurr'>
<input type='hidden' name='PRSaDiscount' value='$PRSaDiscount'>
<input type='hidden' name='PRSaDiscountAmt' value='$PRSaDiscountAmt'>
<input type='hidden' name='PRSaVatChkbx' value='$PRSaVatChkbx'>
<input type='hidden' name='PRSaDirectReturn' value='$PRSaDirectReturn'>

HERE;
	
echo "<input type='hidden' name='PRSaRemark' value='".htmlspecialchars($PRSaRemark, ENT_QUOTES)."' > 
	  <input type='hidden' name='PRSaDriverName' value='".htmlspecialchars($PRSaDriverName, ENT_QUOTES)."' >
	  <input type='hidden' name='PRSaVehicleNumber' value='".htmlspecialchars($PRSaVehicleNumber, ENT_QUOTES)."' >
	  <input type='hidden' name='PRSaDAddress' value='".htmlspecialchars($PRSaDAddress, ENT_QUOTES)."' > 
	  <input type='hidden' name='PRSaIAddress' value='".htmlspecialchars($PRSaIAddress, ENT_QUOTES)."' >";

	  
//Pack Item Module
$ModePackItem = '';
if ($Module_Pack == 0)	$ModePackItem = ' disabled ';
	

// User Has No Access To Modify The Price	
$ModeModifySellPrice = '';
$DiscountMode = '';
if ($Login_ModifySellingPrice == 0) $ModeModifySellPrice = ' readonly ';
if ($Login_ModifyDiscount == 0)	$DiscountMode = ' readonly ';

$PriceLabel = 'Price';	
if ($SalesTTC == 1) $PriceLabel = 'Price TTC';	

$lstWarehouse = $_POST["lstWarehouse"]; if ($lstWarehouse == ""){$lstWarehouse = $_GET["lstWarehouse"];}   

if (empty($lstWarehouse)) {
	if(!empty($defaultwarehouse))
		$lstWarehouse = $defaultwarehouse;
	else	
		$lstWarehouse = $SetupDftWareHouse;
}

$lstItemType = $_POST['lstItemType']; if ($lstItemType == ""){$lstItemType = $_GET["lstItemType"];} if ($lstItemType == ""){$lstItemType = "All";}
$lstItemSort = $_POST['lstItemSort']; if ($lstItemSort == ""){$lstItemSort = $_GET["lstItemSort"];} if ($lstItemSort == ""){$lstItemSort = "ItemCode";}	

if ($Module_ProjectDt == 1 && empty($txtProjectCodeDt))     $txtProjectCodeDt  = $PRSaProjectCode; 
if ($Module_CostCenterDt == 1 && empty($txtCostCentCodeDt)) $txtCostCentCodeDt = $PRSaCostCentCode; 

//Edit Delivery Detail Mode
if($PRSaDtId != ''){
	$querydt = " Select DeliveryDt.DeliveryDt_id, DeliveryDt.Item_code, Item_Description, DeliveryDt.Warehouse_Code, ".
	           " DeliveryDt_Remark, DeliveryDt_Quantity, Round(DeliveryDt_Price, ".$DecimalBase."), DeliveryDt_PriceBase1, DeliveryDt_PriceBase2, ".
			   " Round(DeliveryDt_DiscountPer, ".$DecimalBase."), if(Items.Item_Vat !='', 1, 0) As ItemVat, ".
			   " Round(((DeliveryDt_Quantity*DeliveryDt_Price)-((DeliveryDt_Quantity*DeliveryDt_Price*ifNull(DeliveryDt_DiscountPer,0))/100)), ".$DecimalBase.") As Total, ".
			   " Round(DeliveryDt_PriceTTC, ".$DecimalBase."), ".
			   " Round(((DeliveryDt_Quantity*DeliveryDt_PriceTTC)-((DeliveryDt_Quantity*DeliveryDt_PriceTTC*ifNull(DeliveryDt_DiscountPer,0))/100)), ".$DecimalBase.") As TotalTTC, ".
			   " DeliveryDt.Related_Ref, DeliveryDt.RelatedDt_Id, Warehouse.Warehouse_Name, DeliveryDt.Item_Unit2Qty, ".
			   " Date_Format(DeliveryDt.DeliveryDt_ExpireDate,'%d/%m/%Y') As DeliveryDt_ExpireDate, DeliveryDt.DeliveryDt_BatchNo, ".
			   " DeliveryDt.Project_code, DeliveryDt.CostCent_Code ".
			   " From Temp_DeliveryDt As DeliveryDt ".
			   " Inner Join Items on DeliveryDt.Item_code = Items.Item_code ".
			   " Inner Join Warehouse on DeliveryDt.Warehouse_Code = Warehouse.Warehouse_Code ".
	           " Where DeliveryDt.DeliveryDt_id = '".$PRSaDtId."'";
			   //" And Logged_Code = '".$HTTP_SESSION_VARS['useraccount']."' ";			   
	//echo $querydt;
	$resultdt=mysql_query($querydt,$connection) or die(mysql_error());
    $rowsdt=mysql_fetch_array($resultdt);
	
	$txtRSaDtId        = $rowsdt[0];
	$txtItemCode       = $rowsdt[1];
	$txtItemDesc       = $rowsdt[2];
	$lstWarehouse      = $rowsdt[3];
	$txtWarehouseName  = $rowsdt[16];
	$txtRSaDtRemark    = $rowsdt[4];
	$txtRSaDtQty       = $rowsdt[5];
	$txtRSaDtQty2      = $rowsdt[17];
	
	if ($SalesTTC == 1) 	
		$txtRSaDtPrice 	   = $rowsdt[12];
	else
		$txtRSaDtPrice 	   = $rowsdt[6];
		
	$txtRSaDtDiscount  = $rowsdt[9];
	
	if ($SalesTTC == 1) 	
		$txtRSaDtTotal     = $rowsdt[13];
	else
		$txtRSaDtTotal     = $rowsdt[11];
		
	$chkRSaDtVat  = $rowsdt[10];
	$txtRSaDtVat  = $rowsdt[10];
	
	$txtDeliveryRef  = $rowsdt[14];
	$txtRelatedDtID  = $rowsdt[15];
	
	$txtRSaDtExpireDate = $rowsdt[18];
	$txtRSaDtBatchNo    = $rowsdt[19];
	$txtProjectCodeDt	= $rowsdt[20]; 
	$txtCostCentCodeDt	= $rowsdt[21];
	
	$sub_query = " Select ifNull(DeliveryDt.DeliveryDt_Quantity,0) - ifNull(Sum(ifNull(ReturnDeliveryDt.DeliveryDt_Quantity,0)),0) ".
				 " From DeliveryDt As DeliveryDt, DeliveryDt As ReturnDeliveryDt ".
				 " Where DeliveryDt.DeliveryDt_Id = '".$txtRelatedDtID."' ".
				 " And DeliveryDt.Journal_Type = 'DI' ".
				 " And ReturnDeliveryDt.Journal_Type = 'DR' ".
				 " And ReturnDeliveryDt.DeliveryDt_Id != '".$txtRSaDtId."' ".
				 " And ReturnDeliveryDt.RelatedDt_Id = DeliveryDt.DeliveryDt_Id ";

	$sub_result = selectData($connection, $sub_query);
	$txtRemainedQty = $sub_result[0];
	if ($txtRemainedQty == '') $txtRemainedQty = 0;
		
	
}

$i_unitcoef = 1;
$i_expire   = 0;

if($txtItemCode != ''){
	
	if (empty($PRSaId)) $PRSaId = 0;
	if (empty($PRSaDtId)) $PRSaDtId = 0;
	
	
	//Get The Last Selling Price For The Item
	if ($lstItemType == 'Packed' || $lstItemType == 'PromoPacked'){
		if ($Module_Delivery == 0) {
			$query = " SELECT if($SalesTTC = 1, DeliveryDt_PriceTTC, DeliveryDt_Price) FROM DeliveryDt WHERE Client_Code = '".$PRSaClientCode."' And Item_CodePacked = '".$txtItemCode."' And ifNull(DeliveryDt_Price,0) > 0 ".
					 //" And (('".$lstWarehouse."' = '' And 1 = 1) Or ('".$lstWarehouse."' != '' And Warehouse_Code = '".$lstWarehouse."' )) ".
					 " Order By Delivery_Date Desc Limit 1 ";
		} else {
			$query = " SELECT if($SalesTTC = 1, SaleDt_PriceTTC, SaleDt_Price) FROM SalesDt WHERE Client_Code = '".$PRSaClientCode."' And Item_CodePacked = '".$txtItemCode."' And ifNull(SaleDt_Price,0) > 0 ".
					 //" And (('".$lstWarehouse."' = '' And 1 = 1) Or ('".$lstWarehouse."' != '' And Warehouse_Code = '".$lstWarehouse."' )) ".
					 " Order By Sale_Date Desc Limit 1 ";
		
		}
	} else {
		if ($Module_Delivery == 0) {
			$query = " SELECT if($SalesTTC = 1, DeliveryDt_PriceTTC, DeliveryDt_Price) FROM DeliveryDt WHERE Client_Code = '".$PRSaClientCode."' And Item_code = '".$txtItemCode."' And ifNull(DeliveryDt_Price,0) > 0 ".
					 //" And (('".$lstWarehouse."' = '' And 1 = 1) Or ('".$lstWarehouse."' != '' And Warehouse_Code = '".$lstWarehouse."' )) ".
					 " Order By Delivery_Date Desc Limit 1 ";
					 //echo $query ;
					 //exit;
		} else {
			$query = " SELECT if($SalesTTC = 1, SaleDt_PriceTTC, SaleDt_Price) FROM SalesDt WHERE Client_Code = '".$PRSaClientCode."' And Item_code = '".$txtItemCode."' And ifNull(SaleDt_Price,0) > 0 ".
					 //" And (('".$lstWarehouse."' = '' And 1 = 1) Or ('".$lstWarehouse."' != '' And Warehouse_Code = '".$lstWarehouse."' )) ".
					 " Order By Sale_Date Desc Limit 1 ";
		
		}
	}

	
	//echo $query;
	$result = selectData($connection, $query);
	$i_lsp = $result[0];
	//$i_lsp='123';
	//echo "<TR><TD>cccccccc</TD></TR>";
	if(!isset($i_lsp)) $i_lsp = 0;
	$txtItemLastSellPrice = number_format($i_lsp, $DecimalBase);
	//$txtItemLastSellPrice =999;
	$query = " SELECT Item_UnitSalesDesc, Item_UnitPurchaseDesc, ifNull(Item_Unit,1), ifNull(Item_Expire,1) ".
			 " FROM items WHERE Item_Code = '".$txtItemCode."'";
		
	//echo "<br><br>".$query;
	$result = selectData($connection, $query);
	$i_unit1  	  = $result[0];
	$i_unit2 	  = $result[1]; 
	$i_unitcoef	  = $result[2];
	$i_expire	  = $result[3];
	
	$txtItemUnit1 = $i_unit1;
	$txtItemUnit2 = $i_unit2;
		
}


$style= "style=' background-color:#4069A7; color:#FFFFFF;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px;'";

	  
echo"   <tr><td valign='top'>
        <table border='0' style='table-layout:fixed' align='center' valign='top' >
          <col width=75>
		  <col width=170>
		  <col width=80>
		  <col width=475>";

		  
		  
	echo"  <tr bgcolor='#F7F7F7' height='25'>
		     <th colspan='2'><span class='style3'>Add Items </span></th></tr>
		   <tr bgcolor='#F7F7F7' >	
			 <td colspan='2' align='center'><font size='1' color='#FF0000' face='Verdana'><b>".$message."<br>".$WarningMsg."</b></font></td></tr>			 
			 
		   <tr bgcolor='#F7F7F7' height='25'>
             <td valign='center' align='left' >
				<input type='hidden' name='txtRSaDtId' value='$txtRSaDtId' >
				<input type='hidden' name='txtWarehouseName' id='txtWarehouseName' value='$txtWarehouseName'>
				<span class='style12'>Warehouse&nbsp;<span class='style26'>*</span></span></td>";
		
		if ($PRSaDtId == '') {	 
		    echo"<td colspan='3'><select name='lstWarehouse' id='lstWarehouse' style='font-size:11px; width:250px; height:20px;' onchange='RefreshPage();' >";
			echo"<option></option>";
			while($wrhf=mysql_fetch_row($resultwarehouse)){
			echo"<option ";
				if (($lstWarehouse==$wrhf[0]) || ($DftWareHouse==$wrhf[0]))
					echo " selected ";
			echo" value='$wrhf[0]'>$wrhf[0] - $wrhf[1]</option>";
			}
			
			echo"</select></td>";
		} else 	{
			echo"<td colspan='3'><b>$lstWarehouse - $txtWarehouseName</b><input type='hidden' name='lstWarehouse' id='lstWarehouse' value='$lstWarehouse'></td>";
		
		}
		
		echo"
		  </tr>	 
		  <tr bgcolor='#F7F7F7' height='25'>
             <td valign='center' align='left' ><span class='style12'>Group</span></td>
		     <td colspan='3'><select name='lstGroup' id='lstGroup' style='font-size:11px; width:350px; height:20px;' >";
			echo"<option></option>";
			while($groupf=mysql_fetch_row($resultgroup)){
			echo"<option ";
				if ($lstGroup==$groupf[0] )
					echo " selected ";
			echo" value='$groupf[0]'>$groupf[0] - $groupf[1]</option>";
			}
			
			echo"</select></td>
			
		  </tr>	
		  <tr bgcolor='#F7F7F7' height='25'>
			<td align='left'><span class='style12'>Item Type</span></td>
			<td colspan='3'><select name='lstItemType' style='font-size:11px; width:200px; height:20px;'>";
			
			if ($lstItemType == "All"){
				echo "<option selected value='All'>All Items</option>";
			}else {
				echo "<option value='All'>All Items</option>";
			}
			if ($lstItemType == "Packed" && $Module_Pack == 1){
				echo "<option selected value='Packed'>Packed</option>";
			}else if ($Module_Pack == 1){
				echo "<option value='Packed'>Packed</option>";
			}
			if ($lstItemType == "PromoPacked" && $Module_Pack == 1){
				echo "<option selected value='PromoPacked'>Promo Packed</option>";
			}else{
				echo "<option value='PromoPacked'>Promo Packed</option>";
			}
			if ($lstItemType == "Trading"){
				echo "<option selected value='Trading'>Trading</option>";
			}else{
				echo "<option value='Trading'>Trading</option>";
			}
			if ($lstItemType == "PromoTrading"){
				echo "<option selected value='PromoTrading'>Promo Trading</option>";
			}else{
				echo "<option value='PromoTrading'>Promo Trading</option>";
			}
			if ($lstItemType == "Production"){
				echo "<option selected value='Production'>Production</option>";
			}else{
				echo "<option value='Production'>Production</option>";
			}
			if ($lstItemType == "NonStock"){
				echo "<option selected value='NonStock'>Non-Stock</option>";
			}else{
				echo "<option value='NonStock'>Non-Stock</option>";
			}
			echo "</select></td>
			
		  </tr>
		
		  <tr bgcolor='#F7F7F7' height='25'>
			<td align='left'><span class='style12'>Sort By</span></td>
			<td colspan='3'><select name='lstItemSort' style='font-size:11px; width:200px; height:20px;'>";
			if ($lstItemSort == "ItemCode"){
				echo "<option selected value='ItemCode'>Item Code</option>";
			}else{
				echo "<option value='ItemCode'>Item Code</option>";
			}
			if ($lstItemSort == "ItemDesc"){
				echo "<option selected value='ItemDesc'>Item Desc</option>";
			}else{
				echo "<option value='ItemDesc'>Item Desc</option>";
			}
			echo "</select></td>
		  </tr>
	
		  <tr bgcolor='#F7F7F7' height='25'>
             <td valign='center' align='left' ><span class='style12'>Item&nbsp;<span class='style26'>*</span></span></td>";
		
		if ($PRSaDtId == '') {
		    echo " <td colspan='3'><input type='text' name='txtItemCode' value='$txtItemCode' onBlur='SetItemVat($Module_Delivery);'   maxlength='20' style='font-size:12px; width:110px; height:20px;'>
						<input type='text' name='txtItemDesc' id='txtItemDesc' value='$txtItemDesc' style='font-size:12px; width:270px; height:20px;' />
						<label><span class='style12'><img src='img/btnopen.jpg' title=' Select Item '  width='15' height='17' border='0' onMouseOver=\"style.cursor='hand'\" onClick='showlistItems(1); ' /></span></label></td>";
		} else {
			echo " <td colspan='3'><input type='hidden' name='txtItemCode' value='$txtItemCode' ><input type='hidden' name='txtItemDesc' id='txtItemDesc' value='$txtItemDesc'  />
					<b>$txtItemCode&nbsp;-&nbsp;$txtItemDesc</b></td>";
		}
		
		echo "	
		  </tr>	 
		  <tr bgcolor='#F7F7F7' height='25'>
             <td valign='center' align='left' ><span class='style12'>Remark</span></td>
			 <td colspan='3'><input type='text' name='txtRSaDtRemark' value='".htmlspecialchars($txtRSaDtRemark, ENT_QUOTES)."'  maxlength='100' style='font-size:12px; width:400px; height:20px;'></td>
		  </tr>";

if ($Module_ProjectDt == 1 || $Module_CostCenterDt == 1) {
	echo"   <tr bgcolor='#F7F7F7'>";

	if ($Module_ProjectDt == 1) {
		echo" <td align='left'><span class='style12'>Project&nbsp;<span class='style12'>*</span></span></td>
			  <td align='left'> <span class='style12'>
				<input type='text' name='txtProjectCodeDt' id='txtProjectCodeDt' value='$txtProjectCodeDt' style='width:120px;' maxlength='15' readonly /></span>
				<label><span class='style12'><img src='img/btnopen.jpg' title=' Select Project ' width='15' height='20' border='0' onMouseOver=\"style.cursor='hand'\" onClick='showlistProject(1); '  /></span></label></td>";
	} else {
		echo" <td align='left'>&nbsp;</td>
			  <td align='left'><input type='hidden' name='txtProjectCodeDt' id='txtProjectCodeDt' value='' /></td>";
	}

	if ($Module_CostCenterDt == 1) {		  
		echo" <td align='left'><span class='style12'>Costcenter&nbsp;<span class='style12'>*</span></span></td>
			  <td align='left'><span class='style12'>
				<input type='text' name='txtCostCentCodeDt' id='txtCostCentCodeDt' value='$txtCostCentCodeDt' style='width:130px;' maxlength='15' readonly /></span>
				<label><span class='style12'><img src='img/btnopen.jpg' title=' Select Costcenter ' width='15' height='20' border='0' onMouseOver=\"style.cursor='hand'\"  onClick='showlistCostcenter(1); ' /></span></label></td>";
	} else {
		echo" <td align='left'>&nbsp;</td>
			  <td align='left'><input type='hidden' name='txtCostCentCodeDt' id='txtCostCentCodeDt' value='' /></td>";

	}
	echo"   </tr>";
}

if ($Module_ExpireDate == 1) {
	echo" <tr bgcolor='#F7F7F7' height='25'>
             <td valign='center' align='left' ><span class='style12'>Batch No</span></td>
			 <td><input type='text' name='txtRSaDtBatchNo' value='".htmlspecialchars($txtRSaDtBatchNo, ENT_QUOTES)."'  maxlength='40' style='font-size:12px; width:120px; height:20px;' readonly >
				<label><span class='style12'><img src='img/btnopen.jpg' title='Select Batch No'  width='15' height='17' border='0' onMouseOver=\"style.cursor='hand'\" onClick='showlistBatchNo(1); ' /></span></label></td>
			 <td align='left'><span class='style12'>Expire Date</span></td>
			 <td><input type='text' name='txtRSaDtExpireDate' value='$txtRSaDtExpireDate' maxlength='10' style='font-size:12px; width:90px; height:20px;'>
					<a HREF='#' onClick=\"displayCalendar(document.returnsalesdt.txtRSaDtExpireDate,'dd/mm/yyyy',this); return false;\" NAME='anchor1' ID='anchor1'><img src='./img/cal.gif' border=0 align=center></a>
			 </td>
		  </tr>	"; 	 
} else {
	echo" <input type='hidden' name='txtRSaDtExpireDate' value='$txtRSaDtExpireDate'>";
	echo" <input type='hidden' name='txtRSaDtBatchNo' value='$txtRSaDtBatchNo'>";
}

		  
echo"	  <tr bgcolor='#F7F7F7'><td valign='top' colspan='4'>
		    <table border='0' style='table-layout:fixed' align='left' valign='top' >
			<col width=75>";
			
			if ($Module_Delivery == 0 && $FI_DeliverySalesPrice == 1) {
				if ($Module_DoubleUnit == 1) {
					echo" <col width=75>
						  <col width=40>
						  <col width=75>
						  <col width=40>
						  <col width=75>
						  <col width=90>
						  <col width=100>
						  <col width=60>
						  <col width=100>
						  <col width=45>";
				} else {
					echo" <col width=75>
						  <col width=75>
						  <col width=90>
						  <col width=100>
						  <col width=60>
						  <col width=100>
						  <col width=70>";
				}
			} else {
				if ($Module_DoubleUnit == 1) {
					echo" <col width=100>
						  <col width=40>
						  <col width=100>
						  <col width=40>
						  <col width=100>
						  <col width=270>";
				} else {
					echo" <col width=100>
						  <col width=100>
						  <col width=370>";
				}

			}		  
		echo "<tr>";
		
		if ($Module_Delivery == 0 && $FI_DeliverySalesPrice == 1 ) { 
		    echo"<td valign='center' align='center' ><span class='style12'>Invoice Ref</span></td> 
				 <td valign='center' align='center' ><span class='style12'>Rem. Invoice Qty</span></td>";

			if ($Module_DoubleUnit == 1)
				echo"<td valign='center' align='center' ><span class='style12'>Unit1</span></td>";
						
			echo"<td valign='center' align='center' ><span class='style12'>Qty</span></td>";
					
			if ($Module_DoubleUnit == 1) {
				echo"<td valign='center' align='center' ><span class='style12'>Unit2</span></td>";
				echo"<td valign='center' align='center' ><span class='style12'>Unit2 Qty</span></td>";
			}
			echo"<td valign='center' align='center' ><span class='style12'>$PriceLabel&nbsp;<span class='style26'>*</span></span></td> 
				 <td valign='center' align='center' ><span class='style12'>Last Sell. Price</span></td> 
				 <td valign='center' align='center' ><span class='style12'>Disc(%)</span></td>
				 <td valign='center' align='center' ><span class='style12'>Total</span></td> 
			     <td valign='center' align='center' ><span class='style12'>VAT</span></td> ";
		} else {
			echo"<td valign='center' align='center' ><span class='style12'>Invoice Ref</span></td> 
				 <td valign='center' align='center' ><span class='style12'>Rem. Invoice Qty</span></td>";
				 
			if ($Module_DoubleUnit == 1)
				echo"<td valign='center' align='center' ><span class='style12'>Unit1</span></td>";
						
			echo"<td valign='center' align='center' ><span class='style12'>Qty</span></td>";
					
			if ($Module_DoubleUnit == 1) {
				echo"<td valign='center' align='center' ><span class='style12'>Unit2</span></td>";
				echo"<td valign='center' align='center' ><span class='style12'>Unit2 Qty</span></td>";
			}
			
			echo"<td valign='center' align='center'><span class='style12'>&nbsp;</span></td>";
		}	
			 
			
		echo"</tr>
		  <tr bgcolor='#F7F7F7' height='25'>";

		echo"<td align='center'><b>$txtDeliveryRef</b><input type='hidden' name='txtDeliveryRef' value='$txtDeliveryRef' ></td>
			 <td align='center'><b>$txtRemainedQty</b><input type='hidden' name='txtRemainedQty' value='$txtRemainedQty'></td>";
			 
		if ($Module_DoubleUnit == 1) echo"<td align='center'><b>$txtItemUnit1</b></td>";	 
		
		echo"<td align='center'><input type='text' name='txtRSaDtQty' value='$txtRSaDtQty' maxlength='20' onBlur='CalcRSaDtTotal($DecimalBase);'  onchange='CalcQty2($Module_Unit1Method,$i_unitcoef,1);' style='font-size:12px; width:60px; height:20px;'  ></td>";
		
		if ($Module_DoubleUnit == 1) {
			echo"<td align='center'><b>$txtItemUnit2</b></td>";
			echo "<td align='center'><input type='text' name='txtRSaDtQty2' id='txtRSaDtQty2' value='$txtRSaDtQty2' maxlength='20' onchange='CalcQty2($Module_Unit1Method,$i_unitcoef,2);' style='font-size:12px; width:60px; height:20px;' ></td>";
		} else {
			echo "<input type='hidden' name='txtRSaDtQty2' id='txtRSaDtQty2' value='$txtRSaDtQty2' >";
		}
			 
		if ($Module_Delivery == 0 && $FI_DeliverySalesPrice == 1) {   	 
			echo"<td align='center'><input type='text' name='txtRSaDtPrice' value='$txtRSaDtPrice' maxlength='20' onBlur='CalcRSaDtTotal($DecimalBase);' style='text-align:right; font-size:12px; width:80px; height:20px;' $ModeModifySellPrice></td>
				 <td align='center'><b>$txtItemLastSellPrice</b><input type='hidden' name='txtItemLastSellPrice' value='$txtItemLastSellPrice' maxlength='20' style='text-align:right; font-size:12px; width:90px; height:20px;' ></td>
				 <td align='center'><input type='text' name='txtRSaDtDiscount' value='$txtRSaDtDiscount' maxlength='20' onBlur='CalcRSaDtTotal($DecimalBase);'  style='text-align:right; font-size:12px; width:50px; height:20px;' ></td>
				 <td align='center'><input type='text' name='txtRSaDtTotal' value='$txtRSaDtTotal' maxlength='20' style='text-align:right; font-size:12px; width:90px; height:20px;' ></td>
				 <td align='center'><input type='hidden' name='txtRSaDtVat' value='$txtRSaDtVat'><input name='chkRSaDtVat' type='checkbox' id='chkRSaDtVat' value='1' disabled "; 
				  if($chkRSaDtVat==1 || $txtRSaDtVat == 1) echo "checked /></td>"; else echo " /></td>";   

		} else {				
			echo"<td align='center'><input type='hidden' name='txtRSaDtPrice' value='$txtRSaDtPrice'  >
									<input type='hidden' name='txtItemLastSellPrice' value='$txtItemLastSellPrice'  >
									<input type='hidden' name='txtRSaDtDiscount' value='$txtRSaDtDiscount' >
									<input type='hidden' name='txtRSaDtTotal' value='$txtRSaDtTotal' >
									<input type='hidden' name='txtRSaDtVat' value='$txtRSaDtVat'></td>";
												
		}	
		
echo"	  </tr>
		  </table></td></tr>
		  <tr bgcolor='#F7F7F7' height='30'>
		     <td colspan='4' align='center' bgcolor=#D8D8D8>
			    <input type='button' id='btnSubmitRecord' name='btnSubmitRecord'  value='Submit Record'  onclick='SubmitRecord($i_expire)' $style title='Submit Record'></td>
			 
		  </tr>
        </table>";

	

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

HERE;

?>