<?php
 //.*\$txtProjectCode.*=.*; test remove
 
session_start();
header("Content-type: text/html; charset=".$_SESSION['encodingmode']);
if($_SESSION['dbName']==""){
header("location:../index.php");
}

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

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

if(	$_SESSION['encodingmode'] == 'utf8' || $_SESSION['encodingmode'] == 'utf-8'){
	mysql_query("SET NAMES 'utf8'"); 
	mysql_query('SET CHARACTER SET utf8'); 
	mysql_set_charset('utf8', $connection);
}

$querylog="SELECT FI_Delivery as loginaccess, FI_SalesVAT 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);
}

if ($loginaccess=='' or $loginaccess==0)
	header("location:menu.php");


//$querylog="select * from ".$HTTP_SESSION_VARS['dbLabel'].".login where user_account='".$HTTP_SESSION_VARS['useraccount']."' and Upper(Login_Schema) = Upper('".$HTTP_SESSION_VARS['dbName']."')  ";
$querylog=" select ifNull(FI_DeliveryDel,0) As FI_DeliveryDel, ifNull(FI_DeliveryMod,0) As FI_DeliveryMod, ifNull(FI_DeliveryApp,0) As FI_DeliveryApp, ifNull(FI_DeliveryConfirmed,0) As FI_DeliveryConfirm, ".
          "	ifNull(FI_DeliverySalesPrice,0) As FI_DeliverySalesPrice, ifNull(ModifyVAT,0) As ModifyVAT, ifNull(Login_ModifyDiscount,0) As Login_ModifyDiscount, ifNull(FI_SalesCheckSalesman,0) As FI_SalesCheckSalesman, ".
		  " ifNull(Login_FastPrint,0) As Login_FastPrint, ifNull(FA_LedgerAccess,0) As FA_LedgerAccess, ifNull(login_disapprovesorder,0) As Login_DisapproveSorder, ifNull(Login_NegativeQty,0) As Login_NegativeQty, ".
		  " ifNull(Login_ModifySellingPrice,0) As Login_ModifySellingPrice, ifNull(login_maturitydate,0) as login_maturitydate,  ".
		  " ifNull(Login_MinAllowCostPer,0) As Login_MinAllowCostPer, ifNull(Login_MaxAllowCostPer,0) As Login_MaxAllowCostPer ".
		  " 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 Setup Table							
$querysetup= " select DecimalBase, DecimalBase1, DecimalBase2, base1, base2, grid_color1, grid_color2, ifNull(Client_ValidateProject,0) as Client_ValidateProject, ".
             " Date_Format(Setup_VatStartDate,'%Y%m%d') As Setup_VatStartDate, ifNull(Setup_VatPercentage,0) As Setup_VatPercentage,  ifnull(costcentminimum,0) as costcentminimum
			 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_Delivery,0) As Module_Delivery, ifNull(Module_Project,0) As Module_Project, ifNull(Module_Costcenter,0) As Module_CostCenter, ".
			 " ifNull(Module_RestrictProjCost,0) As Module_RestrictProjCost, ifNull(Module_RestrictCost,0) As Module_RestrictCost, ifNull(module_DeliveryWithSorder,0) As Module_DeliveryWithSorder,".
             " ifNull(Module_DirectStock,0) As Module_DirectStock, ifNull(Module_PrintWaybill,0) As Module_PrintWaybill, ifNull(Module_ShowBalance,0) As Module_ShowBalance,	".
			 " ifNull(Module_SerialNo,0) As Module_SerialNo, ifNull(Module_PostToJournal,0) As Module_PostToJournal, ifNull(Module_ReferenceByProject,0) As Module_ReferenceByProject,".
			 " ifNull(Module_CreditLimitByProj,0) As Module_CreditLimitByProj, ifNull(Module_ProjectDt,0) As Module_ProjectDt, ifNull(Module_CostCenterDt,0) As Module_CostCenterDt, ".
			 " ifNull(Module_DoubleUnit,0) As Module_DoubleUnit, ifNull(Module_ExpireDate,0) As Module_ExpireDate, ifNull(Module_Pack,0) As Module_Pack, ifNull(Module_Unit1Method,0) As Module_Unit1Method,  ".
			 " ifNull(Module_DeliveryClosingQty,0) As Module_DeliveryClosingQty, ifNull(Module_ChangeInvoiceItems,0) As Module_ChangeInvoiceItems, ifNull(Module_NegativeQuantity,0) As Module_NegativeQuantity,".
			 " ifNull(Module_VehicleWeight,0) As Module_VehicleWeight, ifNull(Module_LoadSoldItems,0) as Module_LoadSoldItems,ifNull(Module_ImportExcell,0) As Module_ImportExcell, ".
			 " ifNull(Module_Heatno,0) As Module_Heatno, ifNull(Module_BatchNo,0) As Module_BatchNo,ifNull(module_autodiscount,0) As Module_AutoDiscount, ".
			 " ifNull(Module_Sorderproduction,0) As Module_Sorderproduction,ifNull(module_SalesAutoReceipt,0) as module_SalesAutoReceipt, ifnull(Module_Weight,0) as Module_Weight,  ".
			 " ifnull(module_chargesInTransfer,0) as module_chargesInTransfer ".
             " 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, ClientCur, Warehouse As SetupDftWareHouse, ifNull(ExportTransportToJV,0) As ExportTransportToJV, ifNull(ExportBonusToJV,0) As ExportBonusToJV,".
				 " ifNull(Sale_MaxExceedQty,0) As Sale_MaxExceedQty, ifNull(ShowCostCentLayout,0) As ShowCostCentLayout, ifNull(packingXNbrOfUnit,0) As packingXNbrOfUnit, 
				   ifNull(showBatch,0) As showBatch, ifnull(showDestinatin,0) as showDestinatin FROM SalesSetup";
$resultSalesSetup=mysql_query($querySalesSetup,$connection) or die(mysql_error()); 
while($rowSalesSetup=mysql_fetch_array($resultSalesSetup)){
	extract($rowSalesSetup);
}

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

//Projects List
$queryproject=" select distinct project.project_code, project_name ".
              " from project left join ".$_SESSION['dbLabel'].".loginstk on project.project_code like concat(ifnull(loginstk.project_code,project.project_code),'%') ".
			  " where user_account='".$_SESSION['useraccount']."' ".
			  " order by project.project_code"; 
$projectresult = mysql_query($queryproject,$connection) or die(mysql_error());
$projectrows   = mysql_num_rows($projectresult);
if ($projectrows == 0)
    $queryproject=" select distinct project_code, project_name from project order by project_code ";
			  
			  
			  
		   
//$resultfromproject=mysql_query($queryproject,$connection) or die(mysql_error());

$query=$query." select deliverypreview_lang from ".$_SESSION['dbLabel'].".users where user_account='".$_SESSION['useraccount']."'";
	//echo$query;
	$result=mysql_query($query, $connection);
	$row=mysql_fetch_row($result);
	$defaultlang = $row[0];
//Costcenter List
$querycostcent=" select distinct costcent.costcent_code, costcent_name ".
               " from costcent left join ".$_SESSION['dbLabel'].".loginstk on costcent.costcent_code like concat(loginstk.costcent_code,'%') ".
 			   " where user_account='".$_SESSION['useraccount']."' ".
 			   " order by costcent.costcent_code";
			  
$costcentresult = mysql_query($querycostcent,$connection) or die(mysql_error());
$costcentrows   = mysql_num_rows($costcentresult);
if ($costcentrows == 0)
    $querycostcent=" select distinct costcent_code, costcent_name from costcent order by costcent_code ";			  
//$resultcostcent=mysql_query($querycostcent,$connection) or die(mysql_error());


$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;

$querycurrency="select Currency_code from currency order by currency_code";
$resultcurrency=mysql_query($querycurrency,$connection) or die(mysql_error());



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

//Access Mode On Insert/Edit/Delete
$InsertMode = '';
$ConfirmMode = '';
$DiscountMode = '';
if ($FI_DeliveryApp == 0) $InsertMode = ' disabled ';
if ($FI_DeliveryConfirm == 0) $ConfirmMode = ' disabled ';
if ($Login_ModifyDiscount == 0)	$DiscountMode = ' readonly ';


if (empty($mainaction))	$mainaction = 'insert';

$message = ereg_replace("'"," ",$message);

print <<<HERE
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1256" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> 
<meta name="viewport" content="width=device-width, initial-scale=1.0"> 
<link rel="stylesheet" type="text/css" media="all" href="css-v2/style.css">

<link rel="stylesheet" type="text/css" media="all" href="js/grid/UI_DataGrid_V1.css">
<script type="text/javascript" src="js/grid/UI_DataGrid.js"></script>
<script type="text/javascript" src="js/grid/jquery-1.9.1.js"></script>


<link type="text/css" href="js/calendar/jquery.datepick.css" rel="stylesheet">
<script type="text/javascript" src="js/calendar/jquery.datepick.js"></script>

<link type="text/css" href="js/grid/scripts/jquery-ui.css" rel="stylesheet">
<script type="text/javascript" src="js/grid/scripts/jquery-ui.min.js"></script>

<script type="text/javascript" language="javascript">
	$(document).ready(function() { 
		
		$(document).on('focus', '.date', function() {
			$('.date').datepick({showTrigger: '#calImg'});
		});
		
		$(document).on('focusin', '.table-focus-g1', function() {
			AutoSaveRecordGrid(this.id,'SelectedRec','ModRec_G1','imgSubmit');
			selRecordColor(this,'SelectedRec','SelectedRecColor');
		});
		
		//Set Scroll Positions on Page Load
		scrollToPage();
		
		$(window).scroll(function(){
			scrollPage();
		});
		
		//Set Cursor Position After Page Reload
		var NextElement = readCookie('dl-nextcell');
		MoveNextRecord(NextElement);
		eraseCookie('dl-nextcell');
		
		
		
	});
	
	
</script>

<script type="text/javascript" language="javascript">

function Showimage(vitemcode){

	win = window.open('List_Items_Picture.php?item_code='+vitemcode, 'History', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=990,height=600,top=60,left=100');		
	win.creator = self;
	win.focus();	

}


function getItemLocation(index){

	var item_code = document.getElementById('itemcode['+index+']').value;
	if(item_code != ''){
		
		if (window.XMLHttpRequest)
			{// code for IE7+, Firefox, Chrome, Opera, Safari
				xmlhttp=new XMLHttpRequest();
			}
		else
			{// code for IE6, IE5
				xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
			}
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
					var data = xmlhttp.responseText.split("[BRK]");
				if(document.getElementById('item_location['+index+']'))	{
					if(data[1] != ''){
						document.getElementById('item_location['+index+']').value =  data[1] ;
					}
				}
				data  = '';		
				
			}
		}
		 
		
		xmlhttp.open("GET","Form_Purchase_Actions.php?actionmode=getItemLocation"+"&item_code="+item_code,true);
		xmlhttp.send();
	}
}


function UpdateDiscount(PIndex,amt,decimalbase){



var SaDtDiscount   = document.getElementById('sadtdiscount['+PIndex+']').value;
var clientdiscount   = document.getElementById('deliverydt_clientdiscount['+PIndex+']').value;
var itemdiscount   = document.getElementById('deliverydt_itemdiscount['+PIndex+']').value;

if(SaDtDiscount=='') SaDtDiscount = 0;
SaDtDiscount = parseFloat(SaDtDiscount);


if(clientdiscount=='') clientdiscount = 0;
clientdiscount = parseFloat(clientdiscount);

if(itemdiscount=='') itemdiscount = 0;
itemdiscount = parseFloat(itemdiscount);


if(SaDtDiscount<clientdiscount){
alert('Discount must not be less than '+document.getElementById('deliverydt_clientdiscount['+PIndex+']').value);
// document.getElementById('sadtdiscount['+PIndex+']').focus();
 window.setTimeout(function ()
    {
        document.getElementById('sadtdiscount['+PIndex+']').focus();
    }, 100);
return false();
}
SaDtDiscount =  itemdiscount+ clientdiscount ;
/*
if(SaDtDiscount==clientdiscount){
	clientdiscount = SaDtDiscount;
	itemdiscount = 0;
	}
else {
 SaDtDiscount =  itemdiscount+ clientdiscount ;
}*/

 document.getElementById('sadtdiscount['+PIndex+']').value = SaDtDiscount;
 //document.getElementById('deliverydt_clientdiscount['+PIndex+']').value = clientdiscount;
 //document.getElementById('deliverydt_itemdiscount['+PIndex+']').value = itemdiscount;
CalcSaDtTotal(decimalbase,PIndex);
}

function UpdateDiscount1(PIndex,amt){

 

var SaDtDiscount   = document.getElementById('sadtdiscount['+PIndex+']').value;
var clientdiscount   = document.getElementById('deliverydt_clientdiscount['+PIndex+']').value;
var itemdiscount   = document.getElementById('deliverydt_itemdiscount['+PIndex+']').value;

if(SaDtDiscount=='') SaDtDiscount = 0;
SaDtDiscount = parseFloat(SaDtDiscount);


if(clientdiscount=='') clientdiscount = 0;
clientdiscount = parseFloat(clientdiscount);

if(itemdiscount=='') itemdiscount = 0;
itemdiscount = parseFloat(itemdiscount);


if(SaDtDiscount<clientdiscount){
alert('Discount must not be less than '+document.getElementById('deliverydt_clientdiscount['+PIndex+']').value);
 document.getElementById('sadtdiscount['+PIndex+']').focus();
 window.setTimeout(function ()
    {
        document.getElementById('sadtdiscount['+PIndex+']').focus();
    }, 100);
return false();
}
if(SaDtDiscount==clientdiscount){
	clientdiscount = SaDtDiscount;
	itemdiscount = 0;
	}
else {
 itemdiscount = SaDtDiscount - clientdiscount ;
}

 document.getElementById('sadtdiscount['+PIndex+']').value = SaDtDiscount;
 document.getElementById('deliverydt_clientdiscount['+PIndex+']').value = clientdiscount;
 document.getElementById('deliverydt_itemdiscount['+PIndex+']').value = itemdiscount;

}


function kdClient(choice,e)
{   
	 x = document.sales;
	
	 if(choice==0)
		var clientcode = x.txtClientCode.value;
		else
		var clientcode = x.txtClientName.value;
		
    var intKey = (window.Event) ? e.which : e.keyCode;
	
		
    if (intKey == 13) { //enter key
	
	
		var xmlhttp = getXMLHttpRequest();	
		
		
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{ 
				var data = xmlhttp.responseText.split("[BRK]");
				  
					if(data[1]!=''){
							 
							if(choice==0)
								x.txtClientName.value = data[2];
							else
							x.txtClientCode.value = data[1];
								
							x.txtSalesmanCode.value='';
							x.txtSalesmanName.value='';
							x.txtDAddress.value='';
							x.txtSaDiscount_Temp.value = data[3];
							SetMaturityDate($Module_Delivery);
						
						if(x.txtClientName.value!='')
							{
								x.submit();	
							} 
							
						
						
					}else {
					 
					document.getElementById('lstClientCodeH').click();
				}
			}
		}
	    
		xmlhttp.open("GET","Form_Delivery_Actions.php?mode=getclientname&clientcode="+clientcode+"&choice="+choice);
		xmlhttp.send();
	
      
			
			
    }
	
	
  


}

function checkduplicate(PIndex,PItem) {


x = document.sales; 
	
		var xmlhttp = getXMLHttpRequest();	
		var SaId  = x.txtSaId.value;
		var vSaClient = x.txtClientCode.value;
		
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				var data = xmlhttp.responseText.split("[BRK]");
					
					var Module_AutoDiscount  = x.Module_AutoDiscount.value;
					
						if(data[0]==1 && document.getElementById('sadtid['+PIndex+']').value=='')
							alert('Duplicate Item');
					
					//if(Module_AutoDiscount==1){
						//if(data[1]!='')
							//document.getElementById('sadtdiscount['+PIndex+']').value = data[1];
							
							document.getElementById('deliverydt_itemdiscount['+PIndex+']').value = data[1];
							document.getElementById('deliverydt_clientdiscount['+PIndex+']').value = data[2];
							document.getElementById('sadtdiscount['+PIndex+']').value = parseFloat(data[1]) + parseFloat(data[2]);
							
						//}
			}
		}
	    
		xmlhttp.open("GET","Form_Delivery_Actions.php?mode=checkduplicate&PItem="+PItem+"&SSaId="+SaId+"&vSaClient="+vSaClient);
		xmlhttp.send();


}

function showlistHeatNo(PIndex) {
	XPos = (screen.availHeight - 550) / 2;
	YPos = (screen.availWidth - 850) / 2;
	
	var vHeatNoCode = encodeURIComponent(document.getElementById('deliverydt_heatno['+PIndex+']').value);
	
	window.open('List_HeatNo.php?frm=7&index='+PIndex+'&PHeatNoCode='+vHeatNoCode+'&PHeatNo_Type=','List_HeatNo','width=850,height=550,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=no,left='+YPos+',top='+XPos);
}

function openhistory(vitemcode){
var vSaClient = x.txtClientCode.value;
win = window.open('Form_ItemHistoryDelivery.php?PItem_Code='+vitemcode+'&vSaClient='+vSaClient, 'History', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=990,height=600,top=60,left=100');		
	win.creator = self;
	win.focus();	

}


function LoadFromExcel(ModuleRestProj, ModuleRestCost, ModuleProj, ModuleCost, CheckSalesman){
x = document.sales;
	var vSaClient = x.txtClientCode.value;
	
	if (vSaClient != '') {
		var result = CheckFields(ModuleRestProj, ModuleRestCost, ModuleProj, ModuleCost, CheckSalesman);

		var vSaId = x.txtSaId.value;
		var vSaDate = x.txtDate.value;
		var vSaMaturityDate = x.txtMaturityDate.value;
		var vSaClient = x.txtClientCode.value;
		var vSaSalesman = x.txtSalesmanCode.value;
		var vSaRemark = x.txtRemark.value;
		var vSaCurr = x.txtCurr.value;
		var vSaProjectCode = x.txtProjectCode.value;
		var vSaCostCentCode = x.txtCostCentCode.value;
		var vSaDiscount = x.txtSaDiscount.value;
		var vSaDiscountAmt = x.txtSaDiscountAmt.value;
		var vSaIAddress = x.txtIAddress.value;
		var vSaDAddress = x.txtDAddress.value;
		var vSaVehicleNumber = x.txtVehicleNumber.value;
		var vSaDriverName = x.txtDriverName.value;
		var vVatChkbx = x.txtSaVatChk.value;
		
		vSaRemark   = vSaRemark.replace('&','%26');
		vSaIAddress = vSaIAddress.replace('&','%26');
		vSaDAddress = vSaDAddress.replace('&','%26');
		vSaVehicleNumber = vSaVehicleNumber.replace('&','%26');
		vSaDriverName    = vSaDriverName.replace('&','%26');
		
		vSaRemark   = vSaRemark.replace('#','%23');
		vSaIAddress = vSaIAddress.replace('#','%23');
		vSaDAddress = vSaDAddress.replace('#','%23');
		vSaVehicleNumber = vSaVehicleNumber.replace('#','%23');
		vSaDriverName    = vSaDriverName.replace('#','%23');
		
		
		var vMainMode = x.mainaction.value;
		
		if (result == 1) {
		
			var str = '?mainaction='+vMainMode+'&mode=importfromexcel&PSaId='+vSaId+'&PSaDate='+vSaDate+'&PSaMaturityDate='+vSaMaturityDate+
							  '&PSaClientCode='+vSaClient+'&PSaSalesmanCode='+vSaSalesman+'&PSaCurr='+vSaCurr+'&PSaProjectCode='+vSaProjectCode+
							  '&PSaCostCentCode='+vSaCostCentCode+'&PSaDiscount='+vSaDiscount+'&PSaDiscountAmt='+vSaDiscountAmt+'&PSaVatChkbx='+vVatChkbx+
							  '&PSaVehicleNumber='+vSaVehicleNumber+'&PSaDriverName='+vSaDriverName+'&PSaRemark='+vSaRemark+'&PSaIAddress='+vSaIAddress+'&PSaDAddress='+vSaDAddress	;		
			
			
			 
			x.action="Form_Delivery_Actions.php?"+str;
			x.submit();
					
					
		
			
			
			
		}
	}  
}

function CheckFields(ModuleRestProj, ModuleRestCost, ModuleProj, ModuleCost, CheckSalesman){
  
    x = document.sales;
	
	var SaDate = x.txtDate.value;
	var SaMaturityDate = x.txtMaturityDate.value;
	var SaClient = x.txtClientCode.value;
	var SaSalesman = x.txtSalesmanCode.value;
	var SaProject = x.txtProjectCode.value;
	var SaCostCenter = x.txtCostCentCode.value;
	var SaCurr = x.txtCurr.value;
	
	var vmode  = x.mainaction.value;
	var vmode1 = x.actionmode.value;
	
	if (SaDate=='' )
	{
		alert("Date is mandatory!");
		x.txtDate.focus();
		return 0;
	}
	else if (SaMaturityDate=='')
	{
		alert("MaturityDate is mandatory!");
		x.txtMaturityDate.focus();
		return 0;
	}
	else if (SaClient=='' )
	{
		alert("Client is mandatory!");
		x.txtClientCode.focus();
		return 0;
	}
	else if (SaSalesman=='' && CheckSalesman==1)
	{
		alert("Salesman is mandatory!");
		x.txtSalesmanCode.focus();
		return 0;
	}
	else if (SaProject=='' && ModuleRestProj==1 && ModuleProj==1)
	{
		alert("Project is mandatory!");
		x.txtProjectCode.focus();
		return 0;
	}
	else if (SaCostCenter=='' && ModuleRestCost==1 && ModuleCost==1 && document.getElementById('txtCostCentCode').type == 'text')
	{
		alert("CostCenter is mandatory!");
		x.txtCostCentCode.focus();
		return 0;
	}
	else if (SaCurr=='' )
	{
		alert("Currency is mandatory!");
		x.txtCurr.focus();
		return 0;
	}
	
			
	
	else
	return 1 ;	
}


function CheckFieldsDt(PIndex,ModuleNegativeQuantity,LoginNegativeQty,ItemNonStock,ItemExpire,ModuleExpireDate,ItemWithSerial,ModuleSerialNo,ModuleDeliveryWithSorder,MaxExceedQty,MinAllowCostPer,MaxAllowCostPer,ModuleDelivery){
  
    x = document.sales;
	
	var SaDtItem 	   = document.getElementById('itemcode['+PIndex+']').value;
	var SaDtWarehouse = document.getElementById('warehousecode['+PIndex+']').value;
	var SaDtQty       = document.getElementById('sadtquantity['+PIndex+']').value;
	var SaDtQty2	   = document.getElementById('unit2qty['+PIndex+']').value;
	var SaDtPrice     = document.getElementById('price['+PIndex+']').value;
	var SaDtDisc      = document.getElementById('sadtdiscount['+PIndex+']').value;
	var AvailableQty   = document.getElementById('availableqty['+PIndex+']').value;
	var costcentminimum = x.costcentminimum.value;
	var OrderQty  = document.getElementById('sorderqty['+PIndex+']').value;
	var ReturnQty = document.getElementById('returnqty['+PIndex+']').value;
	var SoldQty   = document.getElementById('soldqty['+PIndex+']').value;
	
	var SaDtExpireDate = document.getElementById('expiredate['+PIndex+']').value;
	var SaDtBatchNo    = document.getElementById('batchno['+PIndex+']').value;
	
	var ItemCost 	   = document.getElementById('costprice['+PIndex+']').value;
	//var ItemPrice 	   = document.getElementById('sellprice['+PIndex+']').value;
	
	
	var vmode = x.actionmode.value;
	
	if (SaDtPrice == '')  SaDtPrice = 0;
	if (SaDtQty2 == '')   SaDtQty2 = 0;
	if (SaDtQty == '')    SaDtQty = 0;
	if (OrderQty == '')   OrderQty = 0;
	if (ReturnQty == '')  ReturnQty = 0;
	if (SoldQty == '')    SoldQty = 0;
	if (ItemCost == '')   ItemCost = 0;
	//if (ItemPrice == '')  ItemPrice = 0;
	
	SaDtQty   = parseFloat(SaDtQty);	
	OrderQty  = parseFloat(OrderQty);
	ReturnQty = parseFloat(ReturnQty);
	SoldQty   = parseFloat(SoldQty);
	//AvailableQty = parseFloat(Math.abs(AvailableQty));
	AvailableQty = parseFloat(AvailableQty);
	//alert(ItemCost);
	var vAllowedQty = (MaxExceedQty*OrderQty/100);
	var vAllowedPrice  = roundNumber((ItemCost*(1 + parseFloat(MinAllowCostPer/100))),3);
	var vAllowedPrice1 = roundNumber((ItemCost*(1 + parseFloat(MaxAllowCostPer/100))),3);
	//alert(ItemCost+' '+vAllowedPrice+' '+SaDtPrice);
	if (SaDtItem=='')
	{
		alert("Item is mandatory!");
		document.getElementById('itemcode['+PIndex+']').focus();
		return 0;
	}	
	else if (SaDtWarehouse=='')
	{
		alert("Warehouse is mandatory!");
		document.getElementById('warehousecode['+PIndex+']').focus();
		return 0;
	}
	else if (SaDtQty*1 != SaDtQty/1 || SaDtQty <= 0  ) {
		alert('Quantity ('+SaDtQty+') should be NUMERIC and POSITIVE and GREATER Than Zero. ');
		document.getElementById('sadtquantity['+PIndex+']').focus();
		return 0;
	}
	 
	else if ((SaDtQty - OrderQty) > vAllowedQty && OrderQty > 0 && ModuleDeliveryWithSorder == 1) { 
		alert('Quantity entered not allowed. Qty must be <= Ordered Qty ['+OrderQty+'].');
		document.getElementById('sadtquantity['+PIndex+']').focus();	
		return 0;		
	} 
	else if (SaDtQty < ReturnQty && ReturnQty > 0) {
		alert('Quantity entered not allowed. Qty must be >= Returned Qty ['+ReturnQty+'].');
		document.getElementById('sadtquantity['+PIndex+']').focus();	
		return 0;
	}
	else if (SaDtQty < SoldQty && SoldQty > 0) {
		alert('Quantity entered not allowed. Qty must be >= Sold Qty ['+SoldQty+'].');
		document.getElementById('sadtquantity['+PIndex+']').focus();	
		return 0;
	}
	else if ( ((SaDtPrice*1 != SaDtPrice/1 || SaDtPrice < 0) ) && ModuleDelivery == 0 ) {
		alert('Price should be a NUMERIC and POSITIVE value');
		document.getElementById('price['+PIndex+']').focus();
		return 0;
	}
	else if ((((SaDtPrice - (SaDtDisc*SaDtPrice/100)) < vAllowedPrice) && (SaDtDisc != 100) ) && ModuleDelivery == 0 ) { 
		alert('Price entered not allowed.');
		//alert(vAllowedPrice);
		document.getElementById('price['+PIndex+']').focus();
		return 1;		
	} 
	else if (((SaDtPrice - (SaDtDisc*SaDtPrice/100)) > vAllowedPrice1 && MaxAllowCostPer > 0 && vAllowedPrice1 > 0 && (SaDtDisc != 100))  && ModuleDelivery == 0 )  { 
		alert('Price entered not allowed.');
		document.getElementById('price['+PIndex+']').focus();
		return 0;		
	} 
	else if ( ((SaDtDisc != '' && SaDtDisc*1 != SaDtDisc/1) )  && ModuleDelivery == 0 ) {
		alert('Discount should be a NUMERIC value');
		document.getElementById('sadtdiscount['+PIndex+']').focus();
		return 0;
	}
	else if ((SaDtQty2 != '' && SaDtQty2*1 != SaDtQty2/1) ) {
		alert('Item Qty2 should be a NUMERIC value.');
		document.getElementById('unit2qty['+PIndex+']').focus();
		return 0;
	}
	else if (ItemExpire == 1 && ModuleExpireDate==1 && SaDtExpireDate == '' ) {
		alert('Item Expire Date is mandatory.');
		document.getElementById('expiredate['+PIndex+']').focus();
		return 0;
	}
	else if (ItemExpire == 1 && ModuleExpireDate==1 && SaDtBatchNo == '' ) {
		alert('Item Batch No is mandatory.');
		document.getElementById('batchno['+PIndex+']').focus();
		return 0;
	}
	
		
	
	else
	return 1 ;	
}


function ClearPage(){
	if (window.confirm ( "Are you sure you want to Clear Page?"))
	{
		ClearForm('All');
		x = document.sales;
		x.mainaction.value='insert';
		x.actionmode.value='';
		x.action='Form_Delivery.php';
		x.submit();
	}	
}

function ClearPage1(){
	x = document.sales;
	var msg = x.message.value;
	
	ClearForm('All');
	
	x.mainaction.value='insert';
	x.actionmode.value='';
	x.message.value=msg;
	x.action='Form_Delivery.php?message='+x.message.value;
	x.submit();
}


function CancelRecord(){
	x = document.sales;
	var vmode   = x.mainaction.value;
	var vmode1  = x.actionmode.value;
	var SaId = x.txtSaId.value;
		
	if (confirm ( "Are you sure you want to Delete current pending Delivery permenantly?"))
	{
		x.action="Form_Delivery_Actions.php?mode=cancel&mainmode=&SSaId="+SaId;
		x.submit();
	}
    
}



function PostChanges(ModuleRestProj, ModuleRestCost, ModuleProj, ModuleCost, ModuleDelivery, CheckSalesman) { 
	var x = document.sales;
	var SaId      = x.txtSaId.value;
	var vMainMode = x.mainaction.value;
	 
	
	for (var i=0; i < document.sales.langr1.length; i++)
		{
			if (document.sales.langr1[i].checked)
			{
				var PLang = document.sales.langr1[i].value;
			}
		}
		
		
	var vVatChkbx = x.txtSaVatChk.value;
	var result = CheckFields(ModuleRestProj, ModuleRestCost, ModuleProj, ModuleCost, CheckSalesman);
	 
	
	if (x.QtySerNo.value == 1){
		alert('Please check Item(s) Qty.');
	}
	else if (x.txtSaCountDetail.value == 0 || x.txtSaCountDetail.value == '') {
		alert('Save not allowed. Please add items.');
	}
	else {
	
		if (result == 1) {
			if (confirm ( "Are you sure you want to Save current Delivery?"))
			{
				//Save Grid Before Posting	
				var vModRec  = document.getElementById('ModRec_G1').value;
				if (vModRec != "") {
					var Obj = document.getElementById('CurRec'+vModRec);
					Obj.style.backgroundColor='#F13A3A';
					alert("Please Submit changes before.");
					
				} else {
					if (document.getElementById('btnPost'))
						x.btnPost.disabled = true;
					if (document.getElementById('btnCancel'))
						x.btnCancel.disabled = true;	
					if (document.getElementById('btnClear'))
						x.btnClear.disabled = true;
					if (document.getElementById('btnAddItem'))
						x.btnAddItem.disabled = true;
					if (document.getElementById('btnAddSerial'))
						x.btnAddSerial.disabled = true;	
					if (document.getElementById('btnStatement'))
						x.btnStatement.disabled = true;	
					if (document.getElementById('btnLoadItems'))
						x.btnLoadItems.disabled = true;		
					if (document.getElementById('btnSearchSorder'))
						x.btnSearchSorder.disabled = true;
						
					if(document.getElementById('autoReceipt')){
						if(document.getElementById('autoReceipt').checked)
							var txtautoReceipt = 1;
						else  var txtautoReceipt = 0;
					}
					x.actionmode.value='post';
					x.action="Form_Delivery_Actions.php?mode=post&mainmode="+vMainMode+"&SSaId="+SaId+"&SSaVatChkbx="+vVatChkbx+"&PLang="+PLang+'&PSaDate='+x.txtDate.value+'&txtautoReceipt='+txtautoReceipt;
					x.submit(); 
				}	
			}
		}
	}	
}

function ConfirmSales(SaId) {
	x = document.sales;
	var vMainMode = x.mainaction.value;
	for (var i=0; i < document.sales.langr1.length; i++)
		{
			if (document.sales.langr1[i].checked)
			{
				var PLang = document.sales.langr1[i].value;
			}
		}
	
	
	if (confirm ( "Do you want to Confirm saved delivery?"))
	{
		x.actionmode.value='confirmsales';
		x.action="Form_Delivery_Actions.php?mode=confirmsales&mainmode="+vMainMode+"&SSaId="+SaId;
		x.submit();
	} else {
		x.actionmode.value='confirmsales';
		x.submit();
	}
	

}

	
function DeleteSaDt(SaDtId, ItemPackCode, ItemCode, ModuleDelivery) {
	x = document.sales;
	var SaId  = x.txtSaId.value;
	var vMainMode = x.mainaction.value;
	var vVatChkbx = x.txtSaVatChk.value;
	var vDelMsg = '';
	
	
	if (ItemPackCode != '')
	   vDelMsg = "Are you sure you want to Delete Pack Item "+ItemPackCode+" ?";
	else  
	   vDelMsg = "Are you sure you want to Delete Item "+ItemCode+" ?";
	   
	if (confirm ( vDelMsg ))
	{
		x.action="Form_Delivery_Actions.php?mode=deletedt&mainmode="+vMainMode+"&SSaId="+SaId+"&SSaDtId="+SaDtId+"&SSaVatChkbx="+vVatChkbx;
		x.submit();
	}

}

function UpdateSaDt(SaDtId,ModuleDelivery) {
    x = document.sales; 
	var vSaId     = x.txtSaId.value;
	var vSaDate   = x.txtDate.value;
	var vVatChkbx = x.txtSaVatChk.value;
	
	var vMainMode = x.mainaction.value;
	
	win = window.open('Form_DeliveryDetail.php?mainaction='+vMainMode+'&actionmode=&PSaId='+vSaId+'&PSaDate='+vSaDate+'&PSaDtId='+SaDtId+'&PSaVatChkbx='+vVatChkbx, 'Form_DeliveryDetail', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=830,height=340,top=100');		
	win.creator = self;
	win.focus();		

}




//All= All form; D= Detail Part
function ClearForm(Option){
    x = document.sales;
	var vmode = x.actionmode.value;
	
	if (Option == 'All') {
		
		x.txtSaId.value='';
		x.txtRef.value='';
		x.txtSorderRef.value='';
		x.txtJvRef.value='';
		x.txtJvFolio.value='';
		x.txtDate.value='';
		x.txtMaturityDate.value='';
		x.txtClientCode.value='';
		x.txtClientName.value='';
		x.txtClientVat.value='';
		x.txtPaymentTerms.value='';
		x.txtCurrentBalance.value='';
		x.txtCreditLimit.value='';
		x.txtSalesmanCode.value='';
		x.txtSalesmanName.value='';
		x.txtRemark.value='';
		x.txtManualNo.value='';
		x.txtCurr.value='';
		x.txtProjectCode.value='';
		x.txtCostCentCode.value='';
		x.txtIAddress.value='';
		x.txtDAddress.value='';
		x.txtVehicleNumber.value='';
		x.txtDriverName.value='';
		x.txtVehicleWeight.value='';
		x.txtVehicleLoadWeight.value='';
		
		
		x.txtSaTaxable.value='';
		x.txtSaNoneTaxable.value='';
		x.txtSaGrossTotal.value='';
		x.txtSaDiscount.value='';
		x.txtSaDiscountAmt.value='';
		x.txtSaVat.value='';
		x.txtSaVatChk.value='';
		x.txtSaNetTotal.value='';
		x.txtSaTotalTaxes.value='';
		x.txtSaTransportAmt.value='';
		x.txtSaBonusAmt.value='';
		
		x.txtSaCountDetail.value='';
				
		x.message.value		= '';
		x.QtySerNo.value	= '';
		x.delivery_cashType.value = '';
		
		x.txtdestfrom.value	= '';
		x.txtdestto.value	= '';
		x.txtdestdate.value	= '';
		
		x.actionmode.value = '';
		x.mainaction.value = '';
	} 
}

function AddItems(ModuleRestProj, ModuleRestCost, ModuleProj, ModuleCost, ModuleDelivery, CheckSalesman) {
	x = document.sales;
	//x.actionmode.value = '';
	var result = CheckFields(ModuleRestProj, ModuleRestCost, ModuleProj, ModuleCost, CheckSalesman);

	var vSaId = x.txtSaId.value;
	var vSaDate = x.txtDate.value;
	var vSaMaturityDate = x.txtMaturityDate.value;
	var vSaClient = x.txtClientCode.value;
	var vSaSalesman = x.txtSalesmanCode.value;
	var vSaRemark = x.txtRemark.value;
	var vSaManualNo = x.txtManualNo.value;
	var vSaCurr = x.txtCurr.value;
	var vSaProjectCode = x.txtProjectCode.value;
	var vSaCostCentCode = x.txtCostCentCode.value;
	var vSaDiscount = x.txtSaDiscount.value;
	var vSaDiscountAmt = x.txtSaDiscountAmt.value;
	var vSaIAddress = x.txtIAddress.value;
	var vSaDAddress = x.txtDAddress.value;
	var vSaVehicleNumber = x.txtVehicleNumber.value;
	var vSaDriverName = x.txtDriverName.value;
	var vVatChkbx = x.txtSaVatChk.value;
	var vSaVehicleWeight = x.txtVehicleWeight.value;
	var vSaVehicleLoadWeight = x.txtVehicleLoadWeight.value;
	
	vSaRemark   = vSaRemark.replace('&','%26');
	vSaIAddress = vSaIAddress.replace('&','%26');
	vSaDAddress = vSaDAddress.replace('&','%26');
	vSaVehicleNumber = vSaVehicleNumber.replace('&','%26');
	vSaDriverName    = vSaDriverName.replace('&','%26');
	
	vSaRemark   = vSaRemark.replace('#','%23');
	vSaIAddress = vSaIAddress.replace('#','%23');
	vSaDAddress = vSaDAddress.replace('#','%23');
	vSaVehicleNumber = vSaVehicleNumber.replace('#','%23');
	vSaDriverName    = vSaDriverName.replace('#','%23');
	
	vSaManualNo = vSaManualNo.replace('&','%26');
	vSaManualNo = vSaManualNo.replace('#','%23');
	
	
	var vMainMode = x.mainaction.value;
	
	if (result == 1) {
		win = window.open('Form_DeliveryDetail.php?mainaction='+vMainMode+'&actionmode=&PSaId='+vSaId+'&PSaDate='+vSaDate+'&PSaMaturityDate='+vSaMaturityDate+
		                  '&PSaClientCode='+vSaClient+'&PSaSalesmanCode='+vSaSalesman+'&PSaCurr='+vSaCurr+'&PSaProjectCode='+vSaProjectCode+
						  '&PSaCostCentCode='+vSaCostCentCode+'&PSaDiscount='+vSaDiscount+'&PSaDiscountAmt='+vSaDiscountAmt+'&PSaVatChkbx='+vVatChkbx+
						  '&PSaVehicleNumber='+vSaVehicleNumber+'&PSaDriverName='+vSaDriverName+'&PSaManualNo='+vSaManualNo+'&PSaRemark='+vSaRemark+
						  '&PSaIAddress='+vSaIAddress+'&PSaDAddress='+vSaDAddress+
						  '&PSaVehicleWeight='+vSaVehicleWeight+'&PSaVehicleLoadWeight='+vSaVehicleLoadWeight	, 
						  'Form_DeliveryDetail', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=830,height=340,top=100');		
		win.creator = self;
		win.focus();		
	}	
	
    
}

function AddSerials(ModuleRestProj, ModuleRestCost, ModuleDelivery, ModuleProj, ModuleCost, CheckSalesman) {
	x = document.sales;
	//x.actionmode.value = '';
	var result = CheckFields(ModuleRestProj, ModuleRestCost, ModuleProj, ModuleCost, CheckSalesman);

	var vSaId = x.txtSaId.value;
	var vSaDate = x.txtDate.value;
	var vSaMaturityDate = x.txtMaturityDate.value;
	var vSaClient = x.txtClientCode.value;
	var vSaSalesman = x.txtSalesmanCode.value;
	var vSaRemark = x.txtRemark.value;
	var vSaCurr = x.txtCurr.value;
	var vSaProjectCode = x.txtProjectCode.value;
	var vSaCostCentCode = x.txtCostCentCode.value;
	var vSaDiscount = x.txtSaDiscount.value;
	var vSaDiscountAmt = x.txtSaDiscountAmt.value;
	var vSaIAddress = x.txtIAddress.value;
	var vSaDAddress = x.txtDAddress.value;
	var vSaVehicleNumber = x.txtVehicleNumber.value;
	var vSaDriverName = x.txtDriverName.value;
	var vVatChkbx = x.txtSaVatChk.value;
	var vSaVehicleWeight = x.txtVehicleWeight.value;
	var vSaVehicleLoadWeight = x.txtVehicleLoadWeight.value;

	
	vSaRemark   = vSaRemark.replace('&','%26');
	vSaIAddress = vSaIAddress.replace('&','%26');
	vSaDAddress = vSaDAddress.replace('&','%26');
	vSaVehicleNumber = vSaVehicleNumber.replace('&','%26');
	vSaDriverName    = vSaDriverName.replace('&','%26');
	
	
	vSaRemark   = vSaRemark.replace('#','%23');
	vSaIAddress = vSaIAddress.replace('#','%23');
	vSaDAddress = vSaDAddress.replace('#','%23');
	vSaVehicleNumber = vSaVehicleNumber.replace('#','%23');
	vSaDriverName    = vSaDriverName.replace('#','%23');
	
	
	var vMainMode = x.mainaction.value;
	
	if (result == 1) {
		win = window.open('Form_DeliveryAddSerial.php?mainaction='+vMainMode+'&actionmode=&PSaId='+vSaId+'&PSaDate='+vSaDate+'&PSaMaturityDate='+vSaMaturityDate+
		                  '&PSaClientCode='+vSaClient+'&PSaSalesmanCode='+vSaSalesman+'&PSaCurr='+vSaCurr+'&PSaProjectCode='+vSaProjectCode+
						  '&PSaCostCentCode='+vSaCostCentCode+'&PSaDiscount='+vSaDiscount+'&PSaDiscountAmt='+vSaDiscountAmt+'&PSaVatChkbx='+vVatChkbx+
						  '&PSaVehicleNumber='+vSaVehicleNumber+'&PSaDriverName='+vSaDriverName+'&PSaRemark='+vSaRemark+'&PSaIAddress='+vSaIAddress+'&PSaDAddress='+vSaDAddress+
						  '&PSaVehicleWeight='+vSaVehicleWeight+'&PSaVehicleLoadWeight='+vSaVehicleLoadWeight	, 
						  'Form_DeliveryAddSerial', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=780,height=400,top=100');		
		win.creator = self;
		win.focus();		
	}	
	
    
}


function DeleteRecordGrid(filepath,formname,transid,SaDtId,index,dftorderby,orderby,morelines,startrange,perpage,direction,ModuleDelivery) {
	x = document.sales;
	var vSaId    = x.txtSaId.value;
	var vSaCurr  = x.txtCurr.value;
	var vSaDate  = x.txtDate.value;
	var vSaDiscount = x.txtSaDiscount.value;
	var vMainMode = x.mainaction.value;
	var vVatChkbx = x.txtSaVatChk.value;
	var vDelMsg = 'Are you sure you want to delete this record?';

	
	if (confirm ( vDelMsg ))
	{
		var xmlhttp = getXMLHttpRequest();	
		$("#Loader").addClass("ajaxsaving");
		
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				var data = $.parseJSON(xmlhttp.responseText);
					
				var msg = data[0].message;
					
				if (msg != "") {
					$("#Loader").removeClass("ajaxsaving");
					alert(decodeURIComponent(msg));
				} else { 
					$("#Loader").removeClass("ajaxsaving");
					ReloadGrid(filepath,formname,transid,'datagrid',index,dftorderby,'DEL',orderby,morelines,startrange,perpage,0,direction);			
					
					if (ModuleDelivery == 0) ReloadGridDt(filepath,'DI-TOT','TOTALS','totals',transid,-1);
				}
			}
		}
	    
		xmlhttp.open("GET","Form_Delivery_Actions.php?mode=deletedt&mainmode="+vMainMode+"&SSaId="+vSaId+"&SSaDtId="+SaDtId+"&SSaVatChkbx="+vVatChkbx+"&txtCurr="+vSaCurr+"&txtDate="+vSaDate+"&txtSaDiscount="+vSaDiscount);
		xmlhttp.send();
	}	

}


function SubmitRecordGrid(PIndex,filepath,formname,transid,dftorderby,orderby,morelines,startrange,perpage,direction,ModuleNegativeSorder,LoginNegativeQty,ModuleRestProj,ModuleRestCost,ModuleProj,ModuleCost,ModuleExpireDate,ModuleSerialNo,ModuleDeliveryWithSorder,MaxExceedQty,CheckSalesman,ModuleDelivery,MinAllowCostPer,MaxAllowCostPer)

 {
 
	var SubBtnID = 'imgSubmit['+PIndex+']';
	if (document.getElementById(SubBtnID))	document.getElementById(SubBtnID).disabled = true;
	var x = document.sales;
	
	
	var x = document.sales;
	
	//alert('invalid item code ');exit;
	//txtItemCode
	var itemcode  = document.getElementById('itemcode['+PIndex+']').value;
	var notallowedtoadditemduetocostcenter = false;
	 
	
	$.get( "Get_AutocompleteQuery.php?tablename=items&term="+itemcode, function( data ) {
		//  used to restrice user to add an item that belong to another cost center  , nb: will only fire  in case user have access to only specific cost center in loginstk NB cost center filtered in Get_AutocompleteQuery tablename:items
       
 if (parseInt(data.length) == parseInt(0) )
 {
	 alert('not allowed to add this item!');
		document.getElementById('itemcode['+PIndex+']').focus();
 }
 
	else{
			
	 
	var ItemNonStock   = document.getElementById('itemnonstock['+PIndex+']').value;
	var ItemExpire     = document.getElementById('itemexpire['+PIndex+']').value;
	var ItemWithSerial = document.getElementById('itemwithserial['+PIndex+']').value;
	var txthscode 		= document.getElementById('txthscode').value;
	var txtnumber_boxes = document.getElementById('txtnumber_boxes').value;
	var txtgrossweight 	= document.getElementById('txtgrossweight').value;
	var txtnetweight 	= document.getElementById('txtnetweight').value;
	var vdelivery_export  = x.delivery_export.value;
	var txtdestfrom		= encodeURIComponent(x.txtdestfrom.value);
	var txtdestto		= encodeURIComponent(x.txtdestto.value);
	var txtdestdate		= x.txtdestdate.value;
	
	if (document.getElementById('sadtid['+PIndex+']').value == '' && ModuleDeliveryWithSorder==1) {
		alert('load from sales order');	
		return;	
	} 
	var ItemPromo = 0;
	if (document.getElementById('chkpromo['+PIndex+']').checked) ItemPromo = 1;
	
	var result = 1;
	result = CheckFields(ModuleRestProj, ModuleRestCost, ModuleProj, ModuleCost, CheckSalesman);
	
	if (result == 1) {
		result = CheckFieldsDt(PIndex,ModuleNegativeSorder,LoginNegativeQty,ItemNonStock,ItemExpire,ModuleExpireDate,ItemWithSerial,ModuleSerialNo,ModuleDeliveryWithSorder,MaxExceedQty,MinAllowCostPer,MaxAllowCostPer,ModuleDelivery);
	}

	var SaDtId   = document.getElementById('sadtid['+PIndex+']').value;
	if (SaDtId == '') vMode = 'submitrecord-ajax';	
	else vMode = 'editdt-ajax';	
	
	if(document.getElementById('deliverydt_quantitybox['+PIndex+']'))
	var deliverydt_quantitybox  = document.getElementById('deliverydt_quantitybox['+PIndex+']').value;
	else var deliverydt_quantitybox  = '';
	if(document.getElementById('deliverydt_itemunit['+PIndex+']'))
	var deliverydt_itemunit  = document.getElementById('deliverydt_itemunit['+PIndex+']').value;
	else var deliverydt_itemunit  = '';
	
	if(document.getElementById('deliverydt_itempackage['+PIndex+']'))
	var deliverydt_itempackage  = document.getElementById('deliverydt_itempackage['+PIndex+']').value;
	else var deliverydt_itempackage  = '';
	
	 if(document.getElementById('sadtpacking['+PIndex+']'))
	var SaDtPacking = document.getElementById('sadtpacking['+PIndex+']').value;
	else SaDtPacking = 0;
	if(document.getElementById('sadtnbrunit['+PIndex+']'))
	var SaDtnbrUnit = document.getElementById('sadtnbrunit['+PIndex+']').value;
	else var SaDtnbrUnit = 0; 
	
	if(document.getElementById('sadtnbrunit['+PIndex+']'))
	var SaDtnbrUnit = document.getElementById('sadtnbrunit['+PIndex+']').value;
	else SaDtnbrUnit = 0;
	
	if(document.getElementById('sadtcloseqty['+PIndex+']'))
	var vSaDtCloseQty = document.getElementById('sadtcloseqty['+PIndex+']').value;
	else var vSaDtCloseQty = 0;
	
	if(document.getElementById('sadtquantity['+PIndex+']'))
	var vSaDtQty = document.getElementById('sadtquantity['+PIndex+']').value;
	else var vSaDtQty = 0;
	
	if(document.getElementById('unit2qty['+PIndex+']'))
	var vSaDtQty2 = document.getElementById('unit2qty['+PIndex+']').value;
	else var vSaDtQty2 = 0;
	
	if(document.getElementById('price['+PIndex+']'))
	var vSaDtPrice = document.getElementById('price['+PIndex+']').value;
	else var  vSSaDtPrice = 0; 
	
	if(document.getElementById('sadtdiscount['+PIndex+']'))
	var vSaDtDiscount = document.getElementById('sadtdiscount['+PIndex+']').value;
	else var vSaDtDiscount = 0; 
	
	if(document.getElementById('deliverydt_clientdiscount['+PIndex+']'))
	var vdeliverydt_clientdiscount = document.getElementById('deliverydt_clientdiscount['+PIndex+']').value;
	else var vdeliverydt_clientdiscount = 0;
	
	if(document.getElementById('sadtid['+PIndex+']'))
	var vSSaDtId = document.getElementById('sadtid['+PIndex+']').value;
	else var vSSaDtId = 0; 
	
	if(document.getElementById('deliverydt_itemdiscount['+PIndex+']'))
	var vdeliverydt_itemdiscount = document.getElementById('deliverydt_itemdiscount['+PIndex+']').value;
	else var vdeliverydt_itemdiscount = 0; 
	
	if(document.getElementById('deliverydt_heatno['+PIndex+']'))
	var vdeliverydt_heatno = document.getElementById('deliverydt_heatno['+PIndex+']').value;
	else var vdeliverydt_heatno = 0; 
	
	if(document.getElementById('batchno['+PIndex+']'))
	var vSaDtBatchNo = document.getElementById('batchno['+PIndex+']').value;
	else var vSaDtBatchNo = 0; 
	
	if(document.getElementById('expiredate['+PIndex+']'))
	var vSaDtExpireDate = document.getElementById('expiredate['+PIndex+']').value;
	else var vSaDtExpireDate = 0;
	
	if(document.getElementById('projectcodedt['+PIndex+']'))
	var vProjectCodeDt = document.getElementById('projectcodedt['+PIndex+']').value;
	else var vProjectCodeDt = 0;
	
	if(document.getElementById('costcentcodedt['+PIndex+']'))
	var vCostCentCodeDt = document.getElementById('costcentcodedt['+PIndex+']').value;
	else var vCostCentCodeDt = 0;
	
	var deliverydt_netweight = 0;
	if(document.getElementById('deliverydt_netweight['+PIndex+']'))
	  deliverydt_netweight = document.getElementById('deliverydt_netweight['+PIndex+']').value;
	else deliverydt_netweight = 0;
	
	var destfrom = encodeURIComponent(document.getElementById('destfrom['+PIndex+']').value);
	var destto	 = encodeURIComponent(document.getElementById('destto['+PIndex+']').value);
	var destdate = document.getElementById('destdate['+PIndex+']').value;
	 
	var delivery_cashType = '';
	if(x.delivery_cashType)
		var delivery_cashType = x.delivery_cashType.value;
	
	var  the_data = 'mode='+vMode+
					'&mainmode='+x.mainaction.value+
					'&SSaId='+x.txtSaId.value+
					'&PSaId='+x.txtSaId.value+
					'&PSaDate='+x.txtDate.value+
					'&PSaCurr='+x.txtCurr.value+
					'&PSaMaturityDate='+x.txtMaturityDate.value+
					'&PSaClientCode='+x.txtClientCode.value+
					'&PSaSalesmanCode='+x.txtSalesmanCode.value+
					'&PSaDiscount='+x.txtSaDiscount.value+
					'&PSaDiscountAmt='+x.txtSaDiscountAmt.value+
					'&PSaVatChkbx='+x.txtSaVatChk.value+
					'&PSaProjectCode='+x.txtProjectCode.value+
					'&PSaCostCentCode='+x.txtCostCentCode.value+'&delivery_cashType='+delivery_cashType+
					'&PSaDriverName='+encodeURIComponent(x.txtDriverName.value)+
					'&PSaVehicleNumber='+encodeURIComponent(x.txtVehicleNumber.value)+
					'&PSaVehicleWeight='+x.txtVehicleWeight.value+
					'&PSaVehicleLoadWeight='+x.txtVehicleLoadWeight.value+
					'&PSaManualNo='+encodeURIComponent(x.txtManualNo.value)+
					'&PSaRemark='+encodeURIComponent(x.txtRemark.value)+
					'&delivery_export='+vdelivery_export+'&PSaIAddress='+encodeURIComponent(x.txtIAddress.value)+'&PSaDAddress='+encodeURIComponent(x.txtDAddress.value)+
					'&txtdestfrom='+txtdestfrom+'&txtdestto='+txtdestto+'&txtdestdate='+txtdestdate+
					'&SSaDtId='+vSSaDtId+
					'&lstWarehouse='+document.getElementById('warehousecode['+PIndex+']').value+
					'&txtItemCode='+encodeURIComponent(document.getElementById('itemcode['+PIndex+']').value)+
					'&txtSaDtRemark='+encodeURIComponent(document.getElementById('remarkdt['+PIndex+']').value)+
					'&txtSaDtCloseQty='+vSaDtCloseQty+'&txtSaDtQty='+vSaDtQty+'&txtSaDtQty2='+vSaDtQty2+
					'&txtSaDtPrice='+vSaDtPrice+'&txtSaDtDiscount='+vSaDtDiscount+'&deliverydt_clientdiscount='+vdeliverydt_clientdiscount+
					'&deliverydt_itemdiscount='+vdeliverydt_itemdiscount+'&chkSaDtPromo='+ItemPromo+'&deliverydt_heatno='+vdeliverydt_heatno+
					'&txtSaDtBatchNo='+vSaDtBatchNo+'&txtSaDtExpireDate='+vSaDtExpireDate+'&txtProjectCodeDt='+vProjectCodeDt+
					'&deliverydt_quantitybox='+deliverydt_quantitybox+'&deliverydt_itemunit='+deliverydt_itemunit+
					'&deliverydt_itempackage='+deliverydt_itempackage+'&txtSaDtnetweight='+deliverydt_netweight+
					'&txtCostCentCodeDt='+document.getElementById('costcentcodedt['+PIndex+']').value+
					'&txtSaDtnbrUnit='+SaDtnbrUnit+'&txtSaDtPacking='+SaDtPacking+'&delivery_date='+x.delivery_date.value+'&delivery_card_msg='+x.delivery_card_msg.value+
					'&delivery_contact='+x.delivery_contact.value+'&delivery_contactphone='+x.delivery_contactphone.value+
					'&txthscode='+txthscode+'&txtnumber_boxes='+txtnumber_boxes+'&txtgrossweight='+txtgrossweight+'&txtnetweight='+txtnetweight+
					'&destfrom='+destfrom+'&destto='+destto+'&destdate='+destdate;
		
	//alert(the_data);
	if (result == 1) {
		var xmlhttp = getXMLHttpRequest();	
		var getdate = new Date();  //Used to prevent caching during ajax call
  
		$("#Loader").addClass("ajaxsaving");
		//$('#datagrid :input').attr('disabled', true);
		
		var SubBtnID = 'imgSubmit['+PIndex+']';
		if (document.getElementById(SubBtnID))	document.getElementById(SubBtnID).disabled = true;		
		
		if(xmlhttp) {
			//xmlhttp.open("POST", "Form_Delivery_Actions.php", true);
		
			xmlhttp.onreadystatechange=function()
			{
				if (xmlhttp.readyState==4 && xmlhttp.status==200)
				{
					var data = $.parseJSON(xmlhttp.responseText);
					//var data2 = xmlhttp.responseText;
					var msg = data[0].message;
					//var msg = data2;
					//alert(decodeURIComponent(msg));
					if (msg != "") {
						$("#Loader").removeClass("ajaxsaving");
						if (document.getElementById(SubBtnID))	document.getElementById(SubBtnID).disabled = false;
						alert(decodeURIComponent(msg));
					} else {	
						if (transid == ""){
							transid = data[0].transid;
							
							x.txtSaId.value = transid;
							x.submit();
						} 
							
						var index = parseInt(PIndex) + 1;
						var nextcell = 'itemcode['+index+']';
						
						createCookie('dl-nextcell',nextcell);
						
						ReloadGrid(filepath,formname,transid,'datagrid',PIndex,dftorderby,'ADD',orderby,morelines,startrange,perpage,0,direction,function() {
							MoveNextRecord(nextcell);
							
							if (ModuleDelivery == 0) ReloadGridDt(filepath,'DI-TOT','TOTALS','totals',transid,-1);
							document.getElementById('ModRec_G1').value = "";
						});
						
						
					}
				}
			}
			
			// adds  a header to tell the PHP script to recognize the data as is sent via POST
			//xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			//xmlhttp.send(the_data);
			
			xmlhttp.open("GET","Form_Delivery_Actions.php?"+the_data);
			xmlhttp.send();
			
		}
	}
	}
	});

}


function AddSerialNo(SaDtId, ItemCode, SaDtQty, WhCode) {
	x = document.sales;
	var SaId = x.txtSaId.value;
	WhCode = WhCode.replace('&','%26');
	
	XPos = (screen.availHeight - 450) / 2;
	YPos = (screen.availWidth - 550) / 2;
    win = window.open('Form_DeliverySerialNo.php?SRItemCode='+ItemCode+'&SRItemQty='+SaDtQty+'&SRWhCode='+WhCode+'&SRSaDtId='+SaDtId+'&SRSaId='+SaId, 'Form_DeliverySerialNo', 'titlebar=no,toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=no,directories=no, width=580,height=450,left='+YPos+',top='+XPos);		
	//win.creator = self;
	//win.focus();		
	
}

function SearchForRef(){
    
	//ClearForm('All');
    x = document.sales;
    win = window.open('Form_DeliverySearch.php', 'Form_DeliverySearch', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=1000,height=550,top=100');		
	win.creator = self;
	win.focus();		
			
}

function SearchForPending(){
    //ClearForm('All');
    x = document.sales;
    win = window.open('Form_DeliverySearchPending.php', 'Form_DeliverySearchPending', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=950,height=560,top=100');		
	win.creator = self;
	win.focus();		
			
}

function PayCash() {
	x = document.sales;
	var vSaId = x.txtSaId.value;
	
	var XPos = (screen.availHeight - 220) / 2;
	var YPos = (screen.availWidth - 350) / 2;
		
	
	window.open('Form_Delivery_PayCash.php?PSaId='+vSaId,'Form_Delivery_PayCash','width=400,height=260,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes,left='+YPos+',top='+XPos);

}

function PayCredit() {
	x = document.sales;
	var vSaId = x.txtSaId.value;
	
	x.action="Form_Delivery_Actions.php?mode=CreditPayment&SSaId="+vSaId;
	x.submit();
}

function SearchConfirmedSorder(ModuleRestProj, ModuleRestCost, ModuleProj, ModuleCost, ModuleDelivery, CheckSalesman){
	x = document.sales;
	var vSaClient = x.txtClientCode.value;
	
	if (vSaClient != '') {
		var result = CheckFields(ModuleRestProj, ModuleRestCost, ModuleProj, ModuleCost, CheckSalesman);

		var vSaId = x.txtSaId.value;
		var vSaDate = x.txtDate.value;
		var vSaMaturityDate = x.txtMaturityDate.value;
		var vSaClient = x.txtClientCode.value;
		var vSaSalesman = x.txtSalesmanCode.value;
		var vSaRemark = x.txtRemark.value;
		var vSaCurr = x.txtCurr.value;
		var vSaProjectCode = x.txtProjectCode.value;
		var vSaCostCentCode = x.txtCostCentCode.value;
		var vSaDiscount = x.txtSaDiscount.value;
		var vSaDiscountAmt = x.txtSaDiscountAmt.value;
		var vSaIAddress = x.txtIAddress.value;
		var vSaDAddress = x.txtDAddress.value;
		var vSaVehicleNumber = x.txtVehicleNumber.value;
		var vSaDriverName = x.txtDriverName.value;
		var vVatChkbx = x.txtSaVatChk.value;
		
		vSaRemark   = vSaRemark.replace('&','%26');
		vSaIAddress = vSaIAddress.replace('&','%26');
		vSaDAddress = vSaDAddress.replace('&','%26');
		vSaVehicleNumber = vSaVehicleNumber.replace('&','%26');
		vSaDriverName    = vSaDriverName.replace('&','%26');
		
		vSaRemark   = vSaRemark.replace('#','%23');
		vSaIAddress = vSaIAddress.replace('#','%23');
		vSaDAddress = vSaDAddress.replace('#','%23');
		vSaVehicleNumber = vSaVehicleNumber.replace('#','%23');
		vSaDriverName    = vSaDriverName.replace('#','%23');
		
		
		var vMainMode = x.mainaction.value;
		
		if (result == 1) {
			win = window.open('Form_Delivery_LoadSorder.php?mainaction='+vMainMode+'&actionmode=&PSaId='+vSaId+'&PSaDate='+vSaDate+'&PSaMaturityDate='+vSaMaturityDate+
							  '&PSaClientCode='+vSaClient+'&PSaSalesmanCode='+vSaSalesman+'&PSaCurr='+vSaCurr+'&PSaProjectCode='+vSaProjectCode+
							  '&PSaCostCentCode='+vSaCostCentCode+'&PSaDiscount='+vSaDiscount+'&PSaDiscountAmt='+vSaDiscountAmt+'&PSaVatChkbx='+vVatChkbx+
							  '&PSaVehicleNumber='+vSaVehicleNumber+'&PSaDriverName='+vSaDriverName+'&PSaRemark='+vSaRemark+'&PSaIAddress='+vSaIAddress+'&PSaDAddress='+vSaDAddress	, 
							  'Form_Delivery_LoadSorder', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=1180,height=580,top=100,left=20');		
			win.creator = self;
			win.focus();		
		}
	} else {
		win = window.open('Form_Delivery_LoadSorder.php?PSaClientCode='+vSaClient, 'Form_Delivery_LoadSorder', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=1180,height=580,top=100,left=20');		
		win.creator = self;
		win.focus();		
	}
}

function LoadSoldItems(ModuleRestProj, ModuleRestCost, ModuleProj, ModuleCost, CheckSalesman){
	x = document.sales;
	var vMainMode = x.mainaction.value;
	var vSaId = x.txtSaId.value;
	
	if (vSaId == '') {
		var result = CheckFields(ModuleRestProj, ModuleRestCost, ModuleProj, ModuleCost, CheckSalesman);

		
		var vSaDate = x.txtDate.value;
		var vSaMaturityDate = x.txtMaturityDate.value;
		var vSaClient = x.txtClientCode.value;
		var vSaSalesman = x.txtSalesmanCode.value;
		var vSaRemark = x.txtRemark.value;
		var vSaCurr = x.txtCurr.value;
		var vSaProjectCode = x.txtProjectCode.value;
		var vSaCostCentCode = x.txtCostCentCode.value;
		var vSaDiscount = x.txtSaDiscount.value;
		var vSaDiscountAmt = x.txtSaDiscountAmt.value;
		var vSaIAddress = x.txtIAddress.value;
		var vSaDAddress = x.txtDAddress.value;
		var vSaVehicleNumber = x.txtVehicleNumber.value;
		var vSaDriverName = x.txtDriverName.value;
		var vVatChkbx = x.txtSaVatChk.value;
		var vSaVehicleWeight = x.txtVehicleWeight.value;
		var vSaVehicleLoadWeight = x.txtVehicleLoadWeight.value;

	
		vSaRemark   = vSaRemark.replace('&','%26');
		vSaIAddress = vSaIAddress.replace('&','%26');
		vSaDAddress = vSaDAddress.replace('&','%26');
		vSaVehicleNumber = vSaVehicleNumber.replace('&','%26');
		vSaDriverName    = vSaDriverName.replace('&','%26');
		
		
		vSaRemark   = vSaRemark.replace('#','%23');
		vSaIAddress = vSaIAddress.replace('#','%23');
		vSaDAddress = vSaDAddress.replace('#','%23');
		vSaVehicleNumber = vSaVehicleNumber.replace('#','%23');
		vSaDriverName    = vSaDriverName.replace('#','%23');
		
		if (result == 1) {
			win = window.open('Form_DeliveryLoadItems.php?mainaction='+vMainMode+'&actionmode=&PSaId='+vSaId+'&PSaDate='+vSaDate+'&PSaMaturityDate='+vSaMaturityDate+
							  '&PSaClientCode='+vSaClient+'&PSaSalesmanCode='+vSaSalesman+'&PSaCurr='+vSaCurr+'&PSaProjectCode='+vSaProjectCode+
							  '&PSaCostCentCode='+vSaCostCentCode+'&PSaVatChkbx='+vVatChkbx+'&PSaVehicleNumber='+vSaVehicleNumber+'&PSaDriverName='+vSaDriverName+
							  '&PSaRemark='+vSaRemark+'&PSaIAddress='+vSaIAddress+'&PSaDAddress='+vSaDAddress+ 
							  '&PSaVehicleWeight='+vSaVehicleWeight+'&PSaVehicleLoadWeight='+vSaVehicleLoadWeight	, 
							  'Form_DeliveryLoadItems', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=no,width=480,height=170,top=200,left=200');		
			win.creator = self;
			win.focus();		
		}
		
		
	} 
}

function DisapproveOrder(SorRef){

	x = document.sales;
	var SaId  = x.txtSaId.value;
	
	if (SorRef != '') {
		if (confirm ( "Are you sure you want to Disapprove order with reference = "+SorRef+" ?") )
		{
			x.action="Form_Delivery_Actions.php?mainmode=disapproveorder1&SSaId="+SaId+"&SSorRef="+SorRef;
			x.submit();
		}
	}
	
}

function SetMaturityDate(ModuleDelivery) {

	x = document.sales;
	var vmode = x.mainaction.value;
	
	//if(x.txtClientVat.value == 1 && ModuleDelivery == 0 && document.getElementById('chkSaVat'))
	    //x.chkSaVat.checked = true;
    
	//if (vmode == 'insert' || vmode == 'edit') {
	    var str   = document.getElementById('txtPaymentTerms').value;
		var str1 = '';
		
		if (str == '') str = 0;
		var sdays = parseInt(str);	
		var sdate = document.getElementById('txtDate').value;
		sdate = ChangeDate(sdate);
		var d = new Date(sdate); 
		
		d.setDate(d.getDate() + sdays); 
		
		str = d.getDate();
		str1 = str.toString();
		
		if (str1.length == 1)
     		str1 = "0"+str1;
			
		str = d.getMonth()+1;
		str2 = str.toString();
		
		if (str2.length == 1)
     		str2 = "0"+str2;	
		
		
		x.txtMaturityDate.value=(str1 + "/" + str2 + "/" + d.getFullYear()); 
		
	//}  
	
	    
		
}

function ChangeDate(sdate){
	var idate = new String;
	idate = sdate;
      
    dt_array = idate.split("/");
      
    if ((dt_array[0] < 10) && (dt_array[0].length == 1))
		dt_array[0] = "0" + dt_array[0];
        
	if ((dt_array[1] < 10) && (dt_array[1].length == 1))
		dt_array[1] = "0" + dt_array[1];
   	
	//fdate = dt_array[1] + "-" + dt_array[0] + "-" + dt_array[2];
	//fdate = dt_array[2] + "-" + dt_array[1] + "-" + dt_array[0];
	// "mm/dd/yyyy"
	fdate = dt_array[1] + "/" + dt_array[0] + "/" + dt_array[2];
	
	return fdate;
}



function CalcSaDiscount(option, dec, vatapplied, vatperc, SalesTTC) {
	x = document.sales;
	var vmode  = x.mainaction.value;
	x.txtSaDiscount_Temp.value='';
	var vmode1 = x.actionmode.value;
	
	var TaxAmt		 = x.txtSaTaxable.value;
	var GrossTotal	 = x.txtSaGrossTotal.value;
	var DisPer		 = x.txtSaDiscount.value;
	var DisAmt		 = x.txtSaDiscountAmt.value;
	var VatAmt		 = x.txtSaVat.value;
	var TaxesAmt   	 = x.txtSaTotalTaxes.value;
	var TransportAmt = x.txtSaTransportAmt.value;
	var BonusAmt	 = x.txtSaBonusAmt.value;
	
	if ((DisAmt*1 != DisAmt/1 || DisAmt < 0) ) {
		alert('Discount Amount should be a NUMERIC value');
		x.txtSaDiscountAmt.focus();
		return 0;
	}
	else if ((DisPer*1 != DisPer/1 || DisPer < 0) ) {
		alert('Discount Percentage should be a NUMERIC value');
		x.txtSaDiscount.focus();
		return 0;
	}
	
	
	if (TaxAmt == '') 		TaxAmt = 0;
	if (GrossTotal == '') 	GrossTotal = 0;
	if (DisPer == '') 		DisPer = 0;
	if (DisAmt == '') 		DisAmt = 0;
	if (TaxesAmt == '') 	TaxesAmt = 0;
	if (TransportAmt == '') TransportAmt = 0;
	if (BonusAmt == '') 	BonusAmt = 0;
	
	TaxAmt		 = parseFloat(TaxAmt);
	GrossTotal	 = parseFloat(GrossTotal);
	DisPer		 = parseFloat(DisPer);
	DisAmt		 = parseFloat(DisAmt);
	VatAmt		 = parseFloat(VatAmt);
	TaxesAmt	 = parseFloat(TaxesAmt);
	TransportAmt = parseFloat(TransportAmt);
	BonusAmt	 = parseFloat(BonusAmt);
	
	if (GrossTotal > 0 && (DisPer > 0 || DisAmt > 0)) {
		if (option == 1 )  //Option by Percentage Get The Amount
			x.txtSaDiscountAmt.value = roundNumber((GrossTotal*DisPer/100),dec);
		else if (option == 2 ){  //Option by Amount Get The Per
		    x.txtSaDiscount.value = roundNumber(((DisAmt/GrossTotal)*100),dec);
				
			if (DisAmt > 0)	x.txtSaDiscount.readOnly = true; 
			else  x.txtSaDiscount.readOnly = false;
					
		}

		// Calculation of Vat Amount and Net Total
		DisAmt = x.txtSaDiscountAmt.value;
		if (DisAmt == '') DisAmt = 0;
		DisAmt = parseFloat(DisAmt);
		
		VatAmt = 0;
		if (SalesTTC == 1) {		
			if (vatapplied == 1 && TaxAmt > 0) {
				VatAmt = roundNumber((((TaxAmt - DisAmt + TransportAmt + BonusAmt) / (1 + vatperc/100)) * (vatperc/100)),dec);
			}
			
			NetTotal = 	roundNumber((GrossTotal + TaxesAmt + TransportAmt + BonusAmt - DisAmt),dec);
			
		}
		else {
			if (vatapplied == 1 && TaxAmt > 0) {
				VatAmt = roundNumber(((TaxAmt - ((DisAmt - TransportAmt - BonusAmt)*TaxAmt/GrossTotal))*vatperc/100),dec);
			} 
			
			NetTotal = 	roundNumber((GrossTotal + VatAmt + TaxesAmt + TransportAmt + BonusAmt - DisAmt),dec);
		}
		
		VatAmt 	 = parseFloat(VatAmt);
		NetTotal = parseFloat(NetTotal);
		x.txtSaVat.value      = formatNumber(VatAmt,dec);
		x.txtSaNetTotal.value = formatNumber(NetTotal,dec);
		
	}   
	
}

function CalcNetTotal(dec, vatapplied, vatperc, SalesTTC) {
	x = document.sales;
	
	var TaxAmt       = x.txtSaTaxable.value;
	var GrossTotal   = x.txtSaGrossTotal.value;
	var VatAmt       = x.txtSaVat.value;
	var DisAmt       = x.txtSaDiscountAmt.value;
	var NetTotal     = x.txtSaNetTotal.value;
	var TaxesAmt     = x.txtSaTotalTaxes.value;
	var TransportAmt = x.txtSaTransportAmt.value;
	var BonusAmt 	 = x.txtSaBonusAmt.value;
	
	if (TaxAmt == '')       TaxAmt = 0;
	if (GrossTotal == '')   GrossTotal = 0;
	if (VatAmt == '')       VatAmt = 0;
	if (DisAmt == '')       DisAmt = 0;
	if (NetTotal == '')     NetTotal = 0;
	if (TaxesAmt == '')     TaxesAmt = 0;
	if (TransportAmt == '') TransportAmt = 0;
	if (BonusAmt == '') 	BonusAmt = 0;
	
	TaxAmt 		 = parseFloat(TaxAmt);
	VatAmt 	 	 = parseFloat(VatAmt);
	NetTotal     = parseFloat(NetTotal);
	DisAmt       = parseFloat(DisAmt);
	GrossTotal   = parseFloat(GrossTotal);
	TaxesAmt     = parseFloat(TaxesAmt);
	TransportAmt = parseFloat(TransportAmt);
	BonusAmt 	 = parseFloat(BonusAmt);
	
	VatAmt = 0;
	
	if (SalesTTC == 1) {
		if (vatapplied == 1 && TaxAmt > 0) {
			VatAmt = roundNumber((((TaxAmt - DisAmt + TransportAmt + BonusAmt) / (1 + vatperc/100)) * (vatperc/100)),dec);
		}
			
		NetTotal = GrossTotal + TaxesAmt + TransportAmt + BonusAmt - DisAmt;
	} else {
		if (vatapplied == 1 && TaxAmt > 0) {
			VatAmt = roundNumber(((TaxAmt - ((DisAmt - TransportAmt - BonusAmt)*TaxAmt/GrossTotal))*vatperc/100),dec);
		}
			
		NetTotal = GrossTotal + VatAmt + TaxesAmt + TransportAmt + BonusAmt - DisAmt;
	}
	
	VatAmt 	   = parseFloat(VatAmt);
	NetTotal   = parseFloat(NetTotal);
	x.txtSaVat.value      = formatNumber(VatAmt,dec);	
	x.txtSaNetTotal.value = formatNumber(roundNumber(NetTotal,dec),dec);
	
	

}

function SetSaVat(dec, vatapplied, vatperc, ModuleDelivery, SalesTTC) {
	x = document.sales;
	var vmode  = x.mainaction.value;
	var vmode1 = x.actionmode.value;
	
	var TaxAmt       = x.txtSaTaxable.value;
	var GrossTotal   = x.txtSaGrossTotal.value;
	var VatAmt       = x.txtSaVat.value;
	var DisAmt       = x.txtSaDiscountAmt.value;
	var NetTotal     = x.txtSaNetTotal.value;
	var TaxesAmt     = x.txtSaTotalTaxes.value;
	var TransportAmt = x.txtSaTransportAmt.value;
	var BonusAmt     = x.txtSaBonusAmt.value;
	
	if (TaxAmt == '') 		TaxAmt = 0;
	if (GrossTotal == '') 	GrossTotal = 0;
	if (VatAmt == '') 		VatAmt = 0;
	if (DisAmt == '') 		DisAmt = 0;
	if (NetTotal == '') 	NetTotal = 0;
	if (TaxesAmt == '') 	TaxesAmt = 0;
	if (TransportAmt == '') TransportAmt = 0;
	if (BonusAmt == '') 	BonusAmt = 0;
	
	VatAmt		 = parseFloat(VatAmt);
	NetTotal	 = parseFloat(NetTotal);
	DisAmt		 = parseFloat(DisAmt);
	TaxAmt 		 = parseFloat(TaxAmt);
	GrossTotal 	 = parseFloat(GrossTotal);
	TaxesAmt 	 = parseFloat(TaxesAmt);
	TransportAmt = parseFloat(TransportAmt);
	BonusAmt	 = parseFloat(BonusAmt);
	
	if (x.chkSaVat.checked && ModuleDelivery == 0) {
	
		x.txtSaVatChk.value = 1;
		
		// Calculation of Vat Amount and Net Total
		
		VatAmt = 0;
		if (SalesTTC == 1) {		
			if (vatapplied == 1 && TaxAmt > 0) {
				VatAmt = roundNumber((((TaxAmt - DisAmt + TransportAmt + BonusAmt) / (1 + vatperc/100)) * (vatperc/100)),dec);
			}
			
		}
		else {
			if (vatapplied == 1 && TaxAmt > 0) {
				VatAmt = roundNumber(((TaxAmt - ((DisAmt - TransportAmt - BonusAmt)*TaxAmt/GrossTotal))*vatperc/100),dec);
			} 
			
			NetTotal = 	roundNumber((GrossTotal + VatAmt + TaxesAmt + TransportAmt + BonusAmt - DisAmt),dec);
		}
		
		VatAmt	   = parseFloat(VatAmt);
		TaxAmt 	   = parseFloat(TaxAmt);
		GrossTotal = parseFloat(GrossTotal);
		NetTotal   = parseFloat(NetTotal);
		
		x.txtSaTaxable.value    = formatNumber(TaxAmt,dec);
		x.txtSaGrossTotal.value = formatNumber(GrossTotal,dec);
		x.txtSaVat.value        = formatNumber(VatAmt,dec);
		x.txtSaNetTotal.value   = formatNumber(NetTotal,dec);
			
		
	}
	else
	{
		x.txtSaVatChk.value = 0;
		
		if (SalesTTC == 1) {
			x.txtSaVat.value      = formatNumber(0,dec);
		}
		else {
			x.txtSaVat.value      = formatNumber(0,dec);
			x.txtSaNetTotal.value = formatNumber(roundNumber((NetTotal - VatAmt),dec),dec);
		}
		
	}  
	

}


function ChangeCurrency() {
	x = document.sales;
	var SaId = x.txtSaId.value;
	var vVatChkbx = x.txtSaVatChk.value;
	
	if (SaId != '') {
		x.action="Form_Delivery_Actions.php?mode=changecurrency&SSaId="+SaId+"&SSaVatChkbx="+vVatChkbx;
		x.submit();
	} else {
		x.submit();
	}
}

function ChangeInvoiceDiscount() {
	x = document.sales;
	var vSaId 	  = x.txtSaId.value;
	var vDisPer	  = x.txtSaDiscount.value;
	var vDisAmt	  = x.txtSaDiscountAmt.value;
	var vVatChkbx = x.txtSaVatChk.value;
	
	if (vSaId != '') {
		x.action="Form_Delivery_Actions.php?mode=changediscount&SSaId="+vSaId+"&SSaVatChkbx="+vVatChkbx+"&txtSaDiscountAmt="+vDisAmt+"&txtSaDiscount="+vDisPer;
		x.submit();
	} 
}

function roundNumber(num, dec) { // Arguments: number to round, number of decimal places
  var newnumber = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
  newnumber = parseFloat(newnumber); 
  
  return newnumber;
}

function formatNumber(num, dec) { // Arguments: number to format, number of decimal places
	return num.toFixed(dec);
}


function PrintSales(SaId, SaRef, JvRef) {
	let str = '';
	let x = document.sales;
	let i;
	let vMsg = "Do you want to Print current Invoice with reference "+SaRef+" ?";
	for (i=0; i < document.sales.langr1.length; i++)
		{
			if (document.sales.langr1[i].checked)
			{
				var PLang = document.sales.langr1[i].value;
			}
		}
 
	if (JvRef != "") vMsg = "Do you want to Print current Invoice with Ref: "+SaRef+" and JV Ref: "+JvRef+" ?";
	
	if (confirm (vMsg))
	{

		str = 'Form_DeliveryPreview.php?SalesId='+SaId+'&printlogo=0&PLang='+PLang;
		window.open(str);
		self.focus();
	}	

}

function PrintSalesWaybill(SaId, SaRef) {
	let x = document.sales;
	let str = '';
	let i;
	for (i=0; i < document.sales.langr1.length; i++)
		{
			if (document.sales.langr1[i].checked)
			{
				var PLang = document.sales.langr1[i].value;
			}
		}
	if (confirm ( "Do you want to Print current Waybill with reference "+SaRef+" ?"))
	{
		str = 'Form_DeliveryWaybillPreview.php?SalesId='+SaId+'&PLang='+PLang;
		window.open(str);
	}	
	
	
}

function PrintStatement(Base1Curr,ModuleReferenceByProject) {
	x = document.sales;
	var vCurrDate = new Date();
	var m = vCurrDate.getMonth()+1;
	var d = vCurrDate.getDate();
	var vMonth = (m < 10) ? '0' + m : m;
	var vDays  = (d < 10) ? '0' + d : d; 
	var vYear  = vCurrDate.getYear();
	
	if (x.txtClientCode.value == '') {
		alert('Please choose a client.');
		return;
	}	
		
	varfromledger = x.txtClientCode.value;
	vartoledger   = x.txtClientCode.value;
	varfromproject = x.txtProjectCode.value;
	vartoproject   = x.txtProjectCode.value;
	varfromcst     = x.txtCostCentCode.value;
	vartocostcent  = x.txtCostCentCode.value;
	varfromdate    = "01/01/" + vYear;
	vartodate 	   = vDays + "/" + vMonth + "/" + vYear;
	
	if (ModuleReferenceByProject == 1) {
		str =   'Rep_StatementProjCost.php?option=1&fromdate='+varfromdate+'&todate='+vartodate+'&fromledger='+varfromledger+'&toledger='+vartoledger
			   +'&fromproject='+varfromproject+'&toproject='+vartoproject+'&fromcst='+varfromcst+'&tocostcent='+vartocostcent
			   +'&currency='+Base1Curr+'&groupby=1&balance=1&prtvaluedate=1&prtjvtype=1&prtprevbal=1&showdetail=1&alltypes=1'
			   +'&exclude=0&jvtype=&parentprjcost=0';
	} else {
		str =   'rep_statementofaccount.php?fromdate=&todate=&fromledger='+varfromledger+'&toledger='+vartoledger
			   +'&dateoption=1&transaction=3&ledgeroption=1&curr=1&currbase1=0&currbase2=0&cum=0'
			   +'&alltypes=1&exclude=0&jvtype=&showunposted=0&prtfolio=1&prtref=1&prtdesc=1&prtvaluedate=1'
			   +'&prtjvtype=0&prtcostcent=0&prtproject=0&prevbal=1&dtjv=0&dtdate=1&checks=1';
	}
   
	window.open(str);
}


function showlistClient(str){
	var vdate, vcode;
	vdate=document.sales.txtDate.value;
	vcode=encodeURIComponent(document.sales.txtClientCode.value);
	vname=encodeURIComponent(document.sales.txtClientName.value);
  
	window.open('List_SorClient.php?frm=2&item='+str+'&PLedger_name='+vname+'&PLedger_number='+vcode+'&TransDate='+vdate,'mywindow','width=850,height=550,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}
function showlistClientName(str) {
	var vdate, vcode;
	vdate=document.sales.txtDate.value;
	vname=encodeURIComponent(document.sales.txtClientName.value);
  
	window.open('List_SorClient.php?frm=2&item='+str+'&PLedger_name='+vname+'&TransDate='+vdate,'mywindow','width=850,height=550,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}


function showlistSalesman(str){
  var vdate, vcode;
  vdate=document.sales.txtDate.value;
  vcode=encodeURIComponent(document.sales.txtSalesmanCode.value);
  
  window.open('List_SorSalesman.php?frm=2&item='+str+'&PLedger_number='+vcode+'&TransDate='+vdate,'mywindow','width=850,height=550,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}

function showlistProject(str){

	vProjectCode = encodeURIComponent(document.getElementById('txtProjectCode').value);
	window.open('List_SorProject.php?frm=2&item='+str+'&PProject_Code='+vProjectCode,'mywindow','width=850,height=550,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}

function showlistCostcenter(str){

	vCostcentCode = encodeURIComponent(document.getElementById('txtCostCentCode').value);
	window.open('List_SorCostcenter.php?frm=2&item='+str+'&PCostcent_Code='+vCostcentCode,'mywindow','width=850,height=550,,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}

function showlistProjectDt(str,PIndex){
	XPos = (screen.availHeight - 550) / 2;
	YPos = (screen.availWidth - 850) / 2;
	
	vProjectCode = encodeURIComponent(document.getElementById('projectcodedt['+PIndex+']').value);
	
	window.open('List_SorProject.php?frm=25&index='+PIndex+'&item='+str+'&PProject_Code='+vProjectCode,'List_SorProject','width=850,height=550,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes,left='+YPos+',top='+XPos);
}

function showlistCostcenterDt(str,PIndex){
	XPos = (screen.availHeight - 550) / 2;
	YPos = (screen.availWidth - 850) / 2;
	
	vCostcentCode = encodeURIComponent(document.getElementById('costcentcodedt['+PIndex+']').value);
	
	window.open('List_SorCostcenter.php?frm=25&index='+PIndex+'&item='+str+'&PCostcent_Code='+vCostcentCode,'List_SorCostcenter','width=850,height=550,,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes,left='+YPos+',top='+XPos);
}

function showlistBatchNo(str,PIndex) {
	x = document.sales;
	
	XPos = (screen.availHeight - 400) / 2;
	YPos = (screen.availWidth - 580) / 2;
	
	vItemCode = encodeURIComponent(document.getElementById('itemcode['+PIndex+']').value);
	vWarehouseCode = encodeURIComponent(document.getElementById('warehousecode['+PIndex+']').value);
	
	window.open('List_BatchNo.php?frm=10&index='+PIndex+'&PItem_Code='+vItemCode+'&PWarehouseCode='+vWarehouseCode,'List_BatchNo','width=580,height=400,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes,left='+YPos+',top='+XPos);
}

function showlistItems(str,PIndex){
	var vDate, vItemCode;
	x = document.sales;
	
	XPos = (screen.availHeight - 400) / 2;
	YPos = (screen.availWidth - 850) / 2;
  
	vDate 	   = x.txtDate.value;
	vItemCode  = encodeURIComponent(document.getElementById('itemcode['+PIndex+']').value);
	var txtClientCode = x.txtClientCode.value;
	window.open('List_SorItems.php?frm=7&index='+PIndex+'&ClientCode='+txtClientCode+'&PItem_Code='+vItemCode+'&ItemType=All&TransDate='+vDate,'List_SorItems','width=850,height=400,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=no,left='+YPos+',top='+XPos);
}

function showlistItemsDesc(str,PIndex){
	var vDate, vItemCode;
	x = document.sales;
	
	XPos = (screen.availHeight - 400) / 2;
	YPos = (screen.availWidth - 850) / 2;
  
	vDate 	   = x.txtDate.value;
	vItemDesc  = encodeURIComponent(document.getElementById('itemdescription['+PIndex+']').value);
	
	window.open('List_SorItems.php?frm=7&index='+PIndex+'&PItem_Description='+vItemDesc+'&ItemType=All&TransDate='+vDate,'List_SorItems','width=850,height=400,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=no,left='+YPos+',top='+XPos);
}

function showlistWarehouse(PIndex) {
	XPos = (screen.availHeight - 550) / 2;
	YPos = (screen.availWidth - 850) / 2;
	
	var vWarehouseCode = encodeURIComponent(document.getElementById('warehousecode['+PIndex+']').value);
	
	window.open('List_SorWarehouse.php?frm=2&index='+PIndex+'&PWarehouse_Code='+vWarehouseCode,'List_SorWarehouse','width=850,height=550,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=no,left='+YPos+',top='+XPos);
}


function CalcSaDtTotal(dec,PIndex) { 
	var x = document.sales;
	var vmode = x.actionmode.value;
	var Qty      = document.getElementById('sadtquantity['+PIndex+']').value;
	var Price    = document.getElementById('price['+PIndex+']').value;
	var Discount = document.getElementById('sadtdiscount['+PIndex+']').value;
	
	if (Qty == '') 		Qty = 0;
	if (Price == '') 	Price = 0;
	if (Discount == '') Discount = 0;
	
	Qty      = parseFloat(Qty);
	Price    = parseFloat(Price);
	Discount = parseFloat(Discount);
	
	if (Qty > 0 && Price >= 0) {
	   document.getElementById('sadttotal['+PIndex+']').value = roundNumber(((Qty*Price) - (Qty*Price*Discount/100)),dec);
	}  
	
}

function caclQtyByPack (dec,PIndex){
	var x = document.sales;
	
	var QtyPack      = document.getElementById('sadtpacking['+PIndex+']').value;
	var QtyUnitNbr      = document.getElementById('sadtnbrunit['+PIndex+']').value;
	if( QtyPack >=0 && QtyUnitNbr >=0){
	   document.getElementById('sadtquantity['+PIndex+']').value = roundNumber(QtyPack*QtyUnitNbr,dec);
	}
}


function CalcQty2(ModuleUnit1Method,Option,PIndex) {
	x = document.sales;
	var Qty  = document.getElementById('sadtquantity['+PIndex+']').value; 
	var Qty2 = document.getElementById('unit2qty['+PIndex+']').value;
	var UnitCoef = document.getElementById('itemunitcoef['+PIndex+']').value;
	
	if (Qty == '')  Qty = 0;
	if (Qty2 == '') Qty2 = 0;
	
	if(ModuleUnit1Method == 1) {
		if (Qty > 0 && Option == 1 && document.getElementById('unit2qty['+PIndex+']').type == 'text') {
			document.getElementById('unit2qty['+PIndex+']').value = Qty*UnitCoef;
		}	
		else if (Qty == 0 && Option == 1 && document.getElementById('unit2qty['+PIndex+']').type == 'text') {
			document.getElementById('unit2qty['+PIndex+']').value = '';
		}
	}
	//Case Modify Qty and Qty2 Should Be Empty
	else if(ModuleUnit1Method == 0 && Option == 1 && Qty2 == 0) {
		if (Qty > 0 && UnitCoef != 0 && document.getElementById('unit2qty['+PIndex+']').type == 'text') {
			document.getElementById('unit2qty['+PIndex+']').value = Qty/UnitCoef;
		}	
		else if (Qty == 0 && document.getElementById('unit2qty['+PIndex+']').type == 'text') {
			document.getElementById('unit2qty['+PIndex+']').value = '';
		}
	}
	//Case Modify Qty2 Get Qty
	else if(ModuleUnit1Method == 0 && Option == 2) {
		if (Qty2 > 0 && document.getElementById('unit2qty['+PIndex+']').type == 'text') {
			document.getElementById('sadtquantity['+PIndex+']').value = Qty2*UnitCoef;
		}	
		else if (Qty2 == 0 && document.getElementById('unit2qty['+PIndex+']').type == 'text') {
			document.getElementById('sadtquantity['+PIndex+']').value = '';
		}
	}
}

function CalcFinalQty(PIndex) {
	x = document.sales;
	var ClosingQty   = document.getElementById('sadtcloseqty['+PIndex+']').value;
	var AvailableQty = document.getElementById('availableqty['+PIndex+']').value;
	var FinalQty = AvailableQty - ClosingQty;
	
	var el=document.getElementById('sadtquantity['+PIndex+']');

	document.getElementById('sadtquantity['+PIndex+']').value = FinalQty;
	
	$('#'.el).trigger("change");
	//fire(el,'change');
}

function ShowSlidingDiv(PDivID) {
	$(PDivID).slideToggle();
}


function kd(e)
{ 

	x=document.sales;
    var intKey = (window.Event) ? e.which : e.keyCode;
    if (intKey == 13) { //enter key
        
		if(document.activeElement.id == 'sadiscount' || document.activeElement.id == 'sadiscountamt') {
			ChangeInvoiceDiscount();
		}
		
		return false;
    }
    return true;
}

function LoadSorder() {
	var x = document.production;
	
	win = window.open('Form_Delivery_LoadProduction.php', 'Form_Delivery_LoadProduction', 
					  'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=no,width=960,height=600,top=100,left=10');
	win.creator = self;
	win.focus();		
	
}

function changeQty2(vuniteQty,index){
	var vUnit2 = document.getElementById("itemunit2["+index+"]").value;
	
	if(vUnit2 == '') vUnit2 =0;
	if(vuniteQty == '') vuniteQty=0;
	document.getElementById("sadtquantity["+index+"]").value = vuniteQty/vUnit2;
	var newqty = document.getElementById("sadtquantity["+index+"]").value;
	if(document.getElementById("sadttotal["+index+"]"))
	 document.getElementById("sadttotal["+index+"]").value = parseFloat(newqty)*parseFloat(document.getElementById("price["+index+"]").value);
	
	
}
function openAddressInfo(txtSaId)
{
	var x = document.sales;
	XPos = (screen.availHeight - 550) / 2;
	YPos = (screen.availWidth - 850) / 2;
	if(txtSaId == null)
	{
		txtSaId = "";
	}
	var delivery_date = x.delivery_date.value;
	var delivery_card_msg = x.delivery_card_msg.value;
	var delivery_contact = x.delivery_contact.value;
	var txtDAddress = x.txtDAddress.value;
	var delivery_contactphone = x.delivery_contactphone.value;
	
	window.open('updateAddressInfo.php?SaId='+txtSaId+'&delivery_date='+delivery_date+'&delivery_card_msg='+delivery_card_msg+'&delivery_contact='+delivery_contact+'&txtDAddress='+txtDAddress+'&delivery_contactphone='+delivery_contactphone,'updateAddressInfo','width=520,height=250,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=no,left='+YPos+',top='+XPos);
}
function showInfo(){
	$('#exportInfo').slideToggle();
}

function closeMatWin(){
	document.getElementById('exportInfo').style.display = "none";
}

function getCostCharges(index){
	var item_code 		= document.getElementById('itemcode['+index+']').value;
	var deliverydate 	= document.sales.txtDate.value;
	var curr			= document.sales.txtCurr.value;
	var warehouse_code  = document.getElementById('warehousecode['+index+']').value; 
	
	if (warehouse_code == ''){
		alert('Warehouse is Empty!');
		return 0;
	} else {
		if (window.XMLHttpRequest)
		{// code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp1=new XMLHttpRequest();
		}
		else
		{// code for IE6, IE5
			xmlhttp1=new ActiveXObject("Microsoft.XMLHTTP");
		}
		  

		xmlhttp1.onreadystatechange=function()
		{  
			if (xmlhttp1.readyState==4 && xmlhttp1.status==200)
			{
				var data = xmlhttp1.responseText.split("[BRK]");
				var msg = data[1];
				if (msg != '') {
					alert(msg);
				} else {
					document.getElementById('costprice['+index+']').value = data[2];		
				}
			}
		}
				

		xmlhttp1.open("GET","Form_Delivery_Actions.php?mode=getCostCharge&item_code="+item_code+"&deliverydate="+deliverydate+"&curr="+curr+"&warehouse_code="+warehouse_code,true);
		xmlhttp1.send(); 
	}
}

function getDestination(index){
	document.getElementById('destfrom['+index+']').value = document.sales.txtdestfrom.value;
	document.getElementById('destto['+index+']').value = document.sales.txtdestto.value;
	document.getElementById('destdate['+index+']').value = document.sales.txtdestdate.value;
}

function getItemInfo(index){
	var item_code = encodeURIComponent(document.getElementById('itemcode['+index+']').value);
	if (window.XMLHttpRequest)
		{// code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp=new XMLHttpRequest();
		}
		else
		{// code for IE6, IE5
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
		  

		xmlhttp.onreadystatechange=function()
		{  
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				var data = xmlhttp.responseText.split("[BRK]");
				document.getElementById('deliverydt_netweight['+index+']').value = data[1];				
				
			}
		}
				

		xmlhttp.open("GET","Form_Delivery_Actions.php?mode=getItemInfo&item_code="+item_code,true);
		xmlhttp.send(); 
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Delivery</title>

<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>
<style>
#exportInfo {
	width: 600px;
    height: 150px;
    z-index: 99999999;
    position: absolute;
    background-color: rgb(220, 213, 213);
    right: 50%;
    left: 30%;
    top: 30%;
    display: none;
	border: 2px solid darkgray;
}
</style>
</head>
<body >
<form name='sales' method='post' action=''   enctype='multipart/form-data'>
<input type='hidden' name='actionmode' value='$actionmode'>
<input type='hidden' name='mainaction' value='$mainaction'>
<input type='hidden' name='message' value='$message' size='200'>
<input type='hidden' name='QtySerNo' value='$QtySerNo'>
<input type='hidden' name='Module_AutoDiscount' value='$Module_AutoDiscount'>
<input type='hidden' name='costcentminimum' id='costcentminimum' value='$costcentminimum'>		

HERE;

//$message='';

	
//Initializations

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

//Get Default Project from salessetup
$querydflproject="select project as defaultprojectsalessetup from salessetup ";
$resultdflproject=mysql_query($querydflproject,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultdflproject)){
	extract($rows);
}
 
	
//Get Default Project
$querydflproject="select project_code as defaultproject from ".$_SESSION['dbLabel'].".loginstk where user_account='".$_SESSION['useraccount']."' and default_project=1 ";
$resultdflproject=mysql_query($querydflproject,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultdflproject)){
	extract($rows);
}
 
 if (empty($defaultproject))
 {
	 $defaultproject =  $defaultprojectsalessetup;
 }
//echo $querydflproject;exit;
	
//Get Default Coscenter
$querydflcostcent="select costcent_code as defaultcostcent from ".$_SESSION['dbLabel'].".loginstk where user_account='".$_SESSION['useraccount']."' and default_costcenter=1 ";
$resultdflcostcent=mysql_query($querydflcostcent,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultdflcostcent)){
	extract($rows);
}

/// if client changed then update all related to client
UpdateTransaction($txtSaId,$txtClientCode,$txtProjectCode,$txtCostCentCode,$txtMaturityDate,$connection);



if ((empty($txtProjectCode)) && $Module_Project == 1)
	$txtProjectCode = $defaultproject;
if ((empty($txtCostCentCode)) && $Module_CostCenter == 1)
	$txtCostCentCode = $defaultcostcent;	

if (empty($txtCurr) )
{	
	if ($ClientCur != '')
		$txtCurr = $ClientCur;
	else
		$txtCurr = $base1;
} 
if (empty($txtDate))	
	$txtDate = displayToday();
 

	
if (empty($txtMaturityDate))	
	$txtMaturityDate = displayToday();



if ($actionmode != "cancel" && $txtSaId != '') {
	// Read From Temp Tables For Selected Record				 
	$query = " Select Delivery_ID, Delivery_Reference, Date_Format(Delivery_Date,'%d/%m/%Y') As Delivery_Date, ".
	         " Date_Format(JournalDt_ValueDate,'%d/%m/%Y') As MaturityDate, ".
			 " Deliveries.Client_code As ClientCode, Clients.Ledger_name As ClientName, Client_VAT,   ".
			 " Deliveries.Salesman_code As SalesmanCode, Salesmen.Ledger_name As SalesmanName, ".
			 " Deliveries.Currency_code, Client_Address, Delivery_ShippedTo, Delivery_Marks, Delivery_ShippedVia, ".
			 " Delivery_Remark, Deliveries.Project_Code, Deliveries.Costcent_code,  ".
			 " Round(ifNull(Delivery_Taxable,0), ".$DecimalBase."), Round(ifNull(Delivery_NoneTaxable,0), ".$DecimalBase."), ".
			 " Round(ifNull(Delivery_Total,0), ".$DecimalBase.") As GrossTotal, ".
			 " Round(ifNull(Delivery_DiscountPer,0), ".$DecimalBase."), Round(ifNull(Delivery_DiscountAmount,0), ".$DecimalBase."),  ".
			 " Round(ifNull(Delivery_VAT,0), ".$DecimalBase.") As Delivery_VAT, ".
			 " Round((ifNull(Delivery_Total,0) + IfNull(Delivery_VAT,0) + ifNull(Delivery_TransportAmount,0) + IfNull(Delivery_BonusAmount,0) - IfNull(Delivery_DiscountAmount,0) + (ifNull(Delivery_Tax1,0) + ifNull(Delivery_Tax2,0) + ifNull(Delivery_Tax3,0) + ifNull(Delivery_Tax4,0) + ifNull(Delivery_Tax5,0))), ".$DecimalBase.") As Delivery_NetTotal,  ".
			 " ifNull(Delivery_VatChkbx,0) As Delivery_VatChkbx, Sorder_reference, ".
			 " Round((ifNull(Delivery_Tax1,0) + ifNull(Delivery_Tax2,0) + ifNull(Delivery_Tax3,0) + ifNull(Delivery_Tax4,0) + ifNull(Delivery_Tax5,0)), ".$DecimalBase.") As TotalTaxes,  ".
			 " Round(ifNull(Delivery_TransportAmount,0), ".$DecimalBase.") As TransportAmt, Journal.Journal_folio, Journal.Journal_refgovernment, Round(ifNull(Delivery_DiscountTTC,0), ".$DecimalBase."),   ".
			 " Round((ifNull(Delivery_TaxableTTC,0) + ifNull(Delivery_NoneTaxable,0) + ifNull(Delivery_TransportTTC,0) + IfNull(Delivery_BonusTTC,0) - IfNull(Delivery_DiscountTTC,0) + (ifNull(Delivery_Tax1,0) + ifNull(Delivery_Tax2,0) + ifNull(Delivery_Tax3,0) + ifNull(Delivery_Tax4,0) + ifNull(Delivery_Tax5,0))), ".$DecimalBase.") As Delivery_NetTotalTTC,  ".
			 " ClientsDetail.Detail_Code, ClientsDetail.Detail_Name, Round(ifNull(Delivery_TaxableTTC,0), ".$DecimalBase."), Round(ifNull(Delivery_TaxableTTC,0) + ifNull(Delivery_NoneTaxable,0), ".$DecimalBase.") As GrossTotalTTC, ".
			 " Round(ifNull(Delivery_TransportTTC,0), ".$DecimalBase.") As TransportAmtTTC, ".
			 " Round(ifNull(Delivery_BonusAmount,0), ".$DecimalBase.") As BonusAmt, Round(ifNull(Delivery_BonusTTC,0), ".$DecimalBase.") As BonusAmtTTC,  ".
			 " Deliveries.Delivery_ManualNo  ,Deliveries.Delivery_vehicleweight ,Deliveries.Delivery_vehicleLoadweight,Delivery_export, trans_id, date_format(Deliveries.Delivery_ClientDeliveryDate, '%d/%m/%Y') as delivery_date, Deliveries.Delivery_ShippingWay as delivery_card_msg, Deliveries.Delivery_ShipName as delivery_contact, ".
			 " Deliveries.Delivery_ClientPhone as delivery_contactphone, delivery_cashType, delivery_HScode, Delivery_NoCarton, Delivery_CartonGrossWt, Delivery_CartonNetWeight, ".
			 " deliveries_destinationFrom, deliveries_destinationTo, date_format(deliveries_destinationDate,'%d/%m/%Y') ".
			 " From Temp_Deliveries As Deliveries ".
			 " Left Join Clients on Deliveries.Client_code = Clients.Ledger_Number ".
			 " Left Join ClientsDetail on Deliveries.Detail_Code = ClientsDetail.Detail_Code ".
			 " Left Join Salesmen on Deliveries.Salesman_code = Salesmen.Ledger_Number ".
			 " Left Join Journal on Deliveries.Journal_ID = Journal.Journal_ID ".
	         " Where Delivery_ID = ".$txtSaId;
			 //" And Logged_Code = '".$HTTP_SESSION_VARS['useraccount']."' ";
			 
			 
			 
	//echo $query; exit;
	$result=mysql_query($query,$connection) or die(mysql_error());
    $rows=mysql_fetch_array($result);
	extract($rows);
	$txtSaId  				= $rows[0];
	$txtRef   				= $rows[1];
	$txtDate  				= $rows[2];
	
	if($txtMaturityDate=="")
		$txtMaturityDate 	= $rows[3];
	
	if ($txtClientCode == "") {
		$txtClientCode   	= $rows[4];
		$txtClientName   	= $rows[5];
		$txtClientVat    	= $rows[6];
	} 
	if ($txtSalesmanCode == "") {
		$txtSalesmanCode 	= $rows[7];
		$txtSalesmanName 	= $rows[8];
	}	
	$txtCurr        	 	= $rows[9];
	$txtIAddress     		= $rows[10];
	$txtDAddress     		= $rows[11];
	$txtVehicleNumber  		= $rows[12];
	$txtDriverName     		= $rows[13];
	$txtRemark         		= $rows[14];
	$txtProjectCode    		= $rows[15];
	$txtCostCentCode   		= $rows[16];
	$txtManualNo 	   		= $rows[39];
	$txtVehicleWeight  		= $rows[40];
	$txtVehicleLoadWeight  	= $rows[41];
	$delivery_export 		= $rows[42];
	$vtrans_id 				= $rows[43];
	/*
	//$txtSaTaxable      = $rows[17];
	if ($SalesTTC == 1) $txtSaTaxable      = $rows[34]; else $txtSaTaxable      = $rows[17];
	$txtSaNoneTaxable  = $rows[18];
	//$txtSaGrossTotal   = $rows[19];
	if ($SalesTTC == 1) $txtSaGrossTotal   = $rows[35]; else $txtSaGrossTotal   = $rows[19];
	$txtSaDiscount     = $rows[20];
	//$txtSaDiscountAmt  = $rows[21];
	if ($SalesTTC == 1) $txtSaDiscountAmt  = $rows[30]; else $txtSaDiscountAmt  = $rows[21];
	$txtSaVat          = $rows[22];
	if ($SalesTTC == 1) $txtSaNetTotal     = $rows[31]; else $txtSaNetTotal     = $rows[23];
	//$txtSaNetTotal     = $rows[23];
	$txtSaVatChk       = $rows[24];
	$txtSaTotalTaxes   = $rows[26];
	//$txtSaTransportAmt = $rows[27];
	if ($SalesTTC == 1) $txtSaTransportAmt = $rows[36]; else $txtSaTransportAmt = $rows[27];
	if ($SalesTTC == 1) $txtSaBonusAmt = $rows[38]; else $txtSaBonusAmt = $rows[37];
	*/
	$txtSorderRef     	= $rows[25];
	$txtJvFolio	      	= $rows[28];
	$txtJvRef 	      	= $rows[29];
	
	$txtClientDtCode   	= $rows[32];
	$txtClientDtName   	= $rows[33];
	$delivery_cashType 	= $rows[48];
		
	$txthscode   		= $rows[49];
	$txtnumber_boxes  	= $rows[50];
	$txtgrossweight   	= $rows[51];
	$txtnetweight   	= $rows[52];
	
	$txtdestfrom   		= $rows[53];
	$txtdestto   		= $rows[54];
	$txtdestdate   		= $rows[55];

	$query = " Select Count(*) FROM Temp_DeliveryDt ".
			 " WHERE Delivery_id = ".$txtSaId;
	$result = selectData($connection, $query);
	$txtSaCountDetail = $result[0];
	if($txtSaCountDetail == '') $txtSaCountDetail = 0;
	
}




//$style= "style=' background-color:#4069A7; color:#FFFFFF;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px;'";
$FormTitle = 'DELIVERY';
if ($Module_Delivery == 0) $FormTitle = 'SALES';

echo"<table cellpadding='0' cellspacing='0' border='0'  align='center' class='layout-width'>";
include_once("header.php");
echo" <tr><td  valign='top'>";

include_once("sidemenu.php");
echo"  </td></tr>";


echo" <tr style='height:26px;'>
		<td  valign='top' id='content-top'><input type='hidden' id='txtSaDiscount_Temp'  name='txtSaDiscount_Temp' value='$txtSaDiscount_Temp'>
			<table border='0' cellpadding='0' cellspacing='0' style='table-layout:fixed; height:26px;' class='layout-width'>
			<tr style='height:26px;'>
				<td style='width:38px; height:26px;'>&nbsp;</td>
				<td valign='middle' style='width:300px; height:26px;'><span class='title'>$FormTitle</span></td>
				<td class='message' valign='middle' style='height:26px;'>".htmlspecialchars($message, ENT_QUOTES)."</td>
			</tr></table>
		</td>
	  </tr>";

echo"<tr>
		<td  height='34'  valign='top' id='content-top2'>
			<table border='0' cellpadding='0' cellspacing='0' class='layout-width'>
			<tr>
				<td width='30'  height='34'>&nbsp;</td>
				<td valign='middle' height='34' width='720px' align='left'>";

	//	if ($Module_DeliveryWithSorder == 0)
	//echo"	<input type='button' id='btnAddItem' name='btnAddItem' value='Add Item'  onclick='AddItems($Module_RestrictProjCost, $Module_RestrictCost, $Module_Project, $Module_CostCenter, $FI_SalesCheckSalesman)' $style title='Add Item' >";

if ($Module_SerialNo == 1)
	echo"	<button type='button' id='btnAddSerial' name='btnAddSerial' onclick='AddSerials($Module_RestrictProjCost, $Module_RestrictCost, $Module_Project, $Module_CostCenter, $FI_SalesCheckSalesman)' title='Add Item' ><span><span>Add Serials</span></span></button>";

echo" <button type='button' id='btnClear' name='btnClear' onclick='ClearPage();return false;' title='Clear Page'><span><span>Clear Page</span></span></button>";
	

				
if ($txtSaId != '' || $txtClientCode != '')
	echo" <button type='button' id='btnCancel' name='btnCancel' onclick='CancelRecord();return false;' title='Cancel Changes'><span><span>Cancel</span></span></button>";

	
if ($txtSaId != '')
	echo" <button type='button' id='btnPost' name='btnPost' onclick='PostChanges($Module_RestrictProjCost, $Module_RestrictCost, $Module_Project, $Module_CostCenter, $FI_SalesCheckSalesman);return false;' title='Save Changes'><span><span>Save</span></span></button>";


if ($txtSaId == '' && $txtClientCode == '')
	echo" <button type='button' id='btnSearch' name='btnSearch' onclick='SearchForRef();return false;' title='Search By Reference'><span><span>Search</span></span></button>";


if ($txtSaId == '')
		echo" <button type='button' id='btnPending' name='btnPending' onclick='SearchForPending();return false;' title='Pending Preparation Order'><span><span>Pending</span></span></button>";

echo" <button type='button' id='btnSearchSorder' name='btnSearchSorder' onclick='SearchConfirmedSorder($Module_RestrictProjCost, $Module_RestrictCost, $Module_Project, $Module_CostCenter, $FI_SalesCheckSalesman);return false;' title='Search Confirmed Preparation Order'><span>
<span>Load Sales Order</span></span></button>";
if($Module_Sorderproduction == 1 && $txtSaId == "")
echo" <button type='button' id='btnLoadSorder' name='btnLoadSorder' onclick='LoadSorder();return false;' title='Load Sales Order'><span><span>Load Production</span></span></button>";
	
if($langr1==''){
if( $defaultlang=='a') $chk1=' checked ';
if( $defaultlang=='e') $chk2=' checked ';
if( $defaultlang=='f') $chk3=' checked ';
}



if(strtoupper($langr1)=='AR') $chk1=' checked ';
if(strtoupper($langr1)=='EN') $chk2=' checked ';
if(strtoupper($langr1)=='FR') $chk3=' checked ';
 echo"<input type='radio' name='langr1' $chk1 id='langr1' value='AR'><span class='style1'>Arabic</span>";
echo" <input type='radio' name='langr1'  $chk2 id='langr1' value='En'><span class='style1'>English";
echo" <input type='radio' name='langr1'  $chk3 id='langr1' value='Fr'><span class='style1'>French";
//echo"<input type='file' name='userfile1' id='userfile1' style='width:200px;' accept='file'>";
//echo" <button type='button' id='btnLoadExcel' name='btnLoadExcel' onclick='LoadFromExcel($Module_RestrictProjCost, $Module_RestrictCost, $Module_Project, $Module_CostCenter, $FI_SalesCheckSalesman);return false;'  title='Load From Excell'><span><span>Load From Excell</span></span></button>";



if($Module_ImportExcell==1)

echo"&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<button type='button' id='btnImp' name='btnImp' onclick='LoadFromExcel($Module_RestrictProjCost, $Module_RestrictCost, $Module_Project, $Module_CostCenter, $FI_SalesCheckSalesman);return false;' title='Import From Excel'><span><span>Import from Excell</span></span></button>
<input type='file'  name='image'    id='image' style='width:200px;' accept='file/xls'>
";


if ($Module_LoadSoldItems == 1) {
	echo" <button type='button' id='btnLoadItems' name='btnLoadItems' onclick='LoadSoldItems($Module_RestrictProjCost, $Module_RestrictCost, $Module_Project, $Module_CostCenter, $FI_SalesCheckSalesman);return false;' title='Load Sold Items'><span><span>Load Sold Items</span></span></button>";
}
		
		
//if ($Login_DisapproveSorder == 1 && $txtRef == "")
	//echo" <button type='button' id='btnDisapproveOrder' name='btnDisapproveOrder' onclick=\"DisapproveOrder('".$txtSorderRef."');\" title='Disapprove Order'><span><span>Disapprove Order</span></span></button>";


if ($FA_LedgerAccess == 1 && $txtClientCode != '')
	echo" <button type='button' id='btnStatement' name='btnStatement' onclick=\"PrintStatement('".$base1."',$Module_ReferenceByProject);\" title='Print Client Statement'><span><span>Client Statement</span></span></button>";
	
if ($txtSaId != '' && $Module_Delivery == 0) {
	echo" <button type='button' id='btnCash' name='btnCash' onclick='PayCash();return false;' title='Pay Cash'><span><span>Cash</span></span></button>";
	echo" <button type='button' id='btnCredit' name='btnCredit' onclick='PayCredit();return false;' title='Pay Credit'><span><span>Credit</span></span></button>";
}
if($module_SalesAutoReceipt == 1){
echo"<span class='style1'><input type='checkbox' id='autoReceipt' name='autoReceipt' ";
if($vtrans_id!='')  echo " checked ";
echo " >Auto Receipt</span>";
}
echo"	</td></tr></table>";
echo"</td></tr>";				

		
echo"<tr><td id='content-body'>
<table border='0'  align='center' valign='top' width=100% class='tablecontent'>
   <tr bgcolor='#F7F7F7'><td valign='top' align='left' colspan='10'>";	

echo"<input type='hidden' name='delivery_export' value='$delivery_export' size='10'>";
   
print <<<HERE

		<table border="0" style='table-layout:fixed'>
		  <col width=90>
		  <col width=70>
		  <col width=80>
		  <col width=90>
		  <col width=60>
		  <col width=70>
		  <col width=70>
		  <col width=80>
		  <col width=80>
		  <col width=120>
		  <col width=270>
		<tr bgcolor="#F7F7F7" height='25'> 
          <td valign="center" align='left' ><span class="style1">Reference&nbsp;<span class="style16">*</span></span></td>
		  <td><font face='Verdana' size='2'><b>&nbsp;$txtRef</b></font><input type='hidden' name='txtSaCountDetail' value='$txtSaCountDetail' >
		  <input type='hidden' name='txtSaId' value='$txtSaId' size='10'><input type="hidden" name="txtRef" value="$txtRef" size='10' readonly>
		  </td>
		  <td align="left"><span class="style1">Preparation Order Ref</span></td>	
		  <td><font face='Verdana' size='2'><b>&nbsp;$txtSorderRef</b></font>
			  <input type="hidden" name="txtSorderRef" value="$txtSorderRef" size='10' readonly>
			  <input type='hidden' name='txtJvFolio' value='$txtJvFolio' >
			  <input type='hidden' name='txtJvRef' value='$txtJvRef' >
		  </td>

HERE;
	if ($Module_PostToJournal == 1) {
		echo " <td align='left'><span class='style1'>Folio</span></td>	
			   <td><font face='Verdana' size='2'><b>&nbsp;$txtJvFolio</b></font></td>
			   <td align='left'><span class='style1'>JV Ref.</span></td>	
			   <td><font face='Verdana' size='2'><b>&nbsp;$txtJvRef</b></font></td>";

	} else {
		echo" <td colspan='4'>&nbsp;</td>";
	}	

$strt = $_SESSION['StartFinancial_Date'];
$end = $_SESSION['EndFinancial_Date'];
	
print <<<HERE
		  <td align="left"><span class="style1">Date&nbsp;<span class="style16">*</span></span></td>
		  <td><input type='text' name='txtDate' id='txtDate' value='$txtDate'  onBlur=checkDateFormat(this,$strt,$end)   onchange='SetMaturityDate($Module_Delivery);' maxlength='10'  style='width:90px;'>
		                   <A HREF="#" onClick="displayCalendar(document.sales.txtDate,'dd/mm/yyyy',this);  return false; " NAME="anchor1" ID="anchor1"><img src='./img/cal.gif' border=0 align=center></A></td>

HERE;


// Check If Vat Applied
$VatApplied = 0;
$txtModeVat = "";
//echo insertDate($txtDate).' > '.$Setup_VatStartDate.' && '.$Setup_VatPercentage.' || '.$Module_AdditionalTaxes;
if ((insertDate($txtDate) > $Setup_VatStartDate && $Setup_VatPercentage != 0) || ($Module_AdditionalTaxes == 1)) {		  
  $txtModeVat = " disabled ";
  $VatApplied = 1;
}

if ($txtClientCode != "" ){				
	$query = " SELECT Client_CreditLimit, Client_Address, ifNull(Client_PaymentTerms,0), Clients.Salesmen_Code, Salesmen.Ledger_name As Salesmen_Name, ".
			 " Clients.Project_Code, Clients.CostCenter_Code, Clients.Currency_Code, Salesmen.Salesman_WarehouseCode ".
	         " FROM Clients Left Outer Join Salesmen on Clients.Salesmen_Code = Salesmen.Ledger_number WHERE Clients.Ledger_Number = '".$txtClientCode."'"; 
			 
			 
			// 411100454
	$result = selectData($connection, $query);

	$txtCreditLimit = $result[0];
	$txtIAddress = $result[1];
	$txtPaymentTerms = $result[2];
	
	$txtMaturityDate =  date('d/m/Y', strtotime(insertDate($txtDate). ' + '.$txtPaymentTerms.' days'));



//$txtDAddress = $txtIAddress;
	//if ($txtDAddress == ""){$txtDAddress = $txtIAddress;}
	
	if ($txtSalesmanCode == "") {
		$txtSalesmanCode = $result[3];
		$txtSalesmanName = $result[4];
	}
		
	if ($Module_Project == 1 && $Client_ValidateProject == 1)
		$txtProjectCode = $result[5]; //Client_ValidateProject
	if ($Module_CostCenter == 1 && $Client_ValidateProject == 1)	
		$txtCostCentCode = $result[6];	
			
	if ($txtSaId == "") {
		//if ($txtCurr != $result[7]) $txtCurr = $result[7];	
		if ($txtCurr == '') $txtCurr = $result[7];	
		if ($result[8] != '') $SetupDftWareHouse = $result[8];
	} 
	//echo $SetupDftWareHouse;
	if ($txtSaId == "") $vCltProjectCode = $result[5];
	else	$vCltProjectCode = $txtProjectCode;
	
	if ($Module_CreditLimitByProj == 1 && $vCltProjectCode != '') {
		$query = "SELECT ifNull(Client_CreditLimit,0) FROM ClientsCreditLimit WHERE Client_Code = '".$txtClientCode."' and '".$vCltProjectCode."' like concat(Project_Code,'%') limit 1 ";
		//echo "<br><br>".$query;
		$result = selectData($connection, $query);
		$txtCreditLimit = $result[0];
	}
			
	//Get Current Balance
	if ($Module_CreditLimitByProj == 1 && $vCltProjectCode != '') {
		$querybalance = " SELECT Round(IFNULL(SUM(if(journaldt_dbcd = 'D', if(CstJour.Cst_increment is null,Journaldt_amount1,Cstjour_amount1), (-1)*if(CstJour.Cst_increment is null,Journaldt_amount1,Cstjour_amount1))), 0)) As Balance FROM journaldt ".
						" Left outer Join CstJour As CstJour on Journaldt.JournalDt_ID = Cstjour.JournalDt_ID ".
						" where journaldt.ledger_number = '".$txtClientCode."' ".
						" and date_format(journaldt.journal_date,'%Y%m%d') <= date_format('".insertMySQLDate($txtDate)."','%Y%m%d') ".
						" and CstJour.Project_Code like concat('".$vCltProjectCode."', '%') ";
	} else {
		$querybalance = "SELECT IFNULL(SUM(if(journaldt_dbcd = 'D', journaldt_amount1, (-1)*journaldt_amount1)), 0) As Balance FROM journaldt where ledger_number = '".$txtClientCode."' and date_format(journaldt.journal_date,'%Y%m%d') <= date_format('".insertMySQLDate($txtDate)."','%Y%m%d')";
	}	
	//echo "<br><br>".$querybalance;
	$result = selectData($connection, $querybalance);
	$q1 = $result[0];
	if (is_numeric($q1)){
		//Do Nothing
	}else{
		$q1 = 0;
	}
	
	$txtCurrentBalance = $q1;

	$sub_query = "select InvoiceDays('".$txtClientCode."', '".insertMySQLDate(displayToday())."', 0)";
	//echo "<br><br>".$query;
	$sub_result = selectData($connection, $sub_query);
	$txtLastInvoiceDay = $sub_result[0];
	//echo "<br><br>".$result[0];				
	
}

if ($txtSalesmanCode != "" ){
	$query = " SELECT Salesmen.Salesman_WarehouseCode ".
	         " FROM Salesmen ".
			 " WHERE Salesmen.Ledger_Number = '".$txtSalesmanCode."'";
	$result = selectData($connection, $query);
	if ($result[0] != '') $SetupDftWareHouse = $result[0];
}

$Parameters = array();
$Parameters['FI_SalesCheckSalesman'] 		= $FI_SalesCheckSalesman;
$Parameters['FI_DeliverySalesPrice'] 		= $FI_DeliverySalesPrice;
$Parameters['Login_NegativeQty'] 			= $Login_NegativeQty;
$Parameters['Login_ModifySellingPrice'] 	= $Login_ModifySellingPrice;
$Parameters['Login_ModifyDiscount'] 		= $Login_ModifyDiscount;
$Parameters['Login_MinAllowCostPer'] 		= $Login_MinAllowCostPer;
$Parameters['Login_MaxAllowCostPer'] 		= $Login_MaxAllowCostPer;
$Parameters['Module_Delivery'] 				= $Module_Delivery;
$Parameters['Module_NegativeQuantity'] 		= $Module_NegativeQuantity;
$Parameters['Module_Unit1Method'] 			= $Module_Unit1Method;
$Parameters['Module_Pack'] 					= $Module_Pack;
$Parameters['Module_DoubleUnit'] 			= $Module_DoubleUnit;
$Parameters['Module_Project'] 				= $Module_Project;
$Parameters['Module_CostCenter'] 			= $Module_CostCenter;
$Parameters['Module_ProjectDt'] 			= $Module_ProjectDt;
$Parameters['Module_CostCenterDt'] 			= $Module_CostCenterDt;
$Parameters['Module_RestrictProjCost'] 		= $Module_RestrictProjCost;
$Parameters['Module_RestrictCost'] 			= $Module_RestrictCost;
$Parameters['ShowCostCentLayout'] 			= $ShowCostCentLayout;
$Parameters['Module_SerialNo'] 				= $Module_SerialNo;
$Parameters['Module_ExpireDate'] 			= $Module_ExpireDate;
$Parameters['Module_DeliveryClosingQty'] 	= $Module_DeliveryClosingQty;
$Parameters['Module_DeliveryWithSorder'] 	= $Module_DeliveryWithSorder;
$Parameters['Sale_MaxExceedQty'] 			= $Sale_MaxExceedQty;
$Parameters['SalesTTC']	 					= $SalesTTC;
$Parameters['DecimalBase'] 					= $DecimalBase;
$Parameters['Setup_VatPercentage'] 			= $Setup_VatPercentage;
$Parameters['Module_AdditionalTaxes'] 		= $Module_AdditionalTaxes;
$Parameters['ExportTransportToJV'] 			= $ExportTransportToJV;
$Parameters['ExportBonusToJV'] 				= $ExportBonusToJV;
$Parameters['VatApplied'] 					= $VatApplied;
$Parameters['AllowModifyVAT'] 				= $AllowModifyVAT;
$Parameters['SetupDftWareHouse'] 			= $SetupDftWareHouse;
$Parameters['defaultwarehouse']  			= $defaultwarehouse;

$Parameters['txtDate'] 		   				= $txtDate;
$Parameters['txtClientCode']   				= $txtClientCode;
$Parameters['txtClientDetail'] 				= $txtClientDetail;
$Parameters['txtCurrCode']     				= $txtCurr;
$Parameters['Base1']    	   				= $base1;
$Parameters['Base2']    	   				= $base2;
$Parameters['Module_Heatno'] 				= $Module_Heatno;
$Parameters['costcent_applyvat'] 			= $costcent_applyvat;
$Parameters['FI_SalesVAT'] 					= $FI_SalesVAT;
$Parameters['delivery_export']   			= $delivery_export;
$Parameters['txtSaDiscount_Temp']   		= $txtSaDiscount_Temp;
$Parameters['packingXNbrOfUnit'] 			= $packingXNbrOfUnit;
$Parameters['Module_Sorderproduction'] 		= $Module_Sorderproduction;
$Parameters['showBatch'] 					= $showBatch; 
$Parameters['Module_BatchNo'] 				= $Module_BatchNo;
$Parameters['Module_Weight'] 				= $Module_Weight;
$Parameters['module_chargesInTransfer']		= $module_chargesInTransfer;
$Parameters['showDestinatin'] 				= $showDestinatin;
$_SESSION['gdl_parameters'] 		 		= $Parameters;

if ($Module_Delivery == 0 && $FI_DeliverySalesPrice == 1) {
/*
	echo"<td rowspan='7' valign='top'><table border='0' style='table-layout:fixed'>
			<col width=100>
			<col width=110>
			
			<tr bgcolor='#D8D8D8' height='20'>
			 <td valign='center' align='right' ><span class='style1'>Taxable</span></td> 
			 <td align='left'><input type='text' name='txtSaTaxable' value='$txtSaTaxable' maxlength='20' readonly style='text-align:right; width:100px; height=18px;'></td>
		  </tr>
		  <tr bgcolor='#D8D8D8' height='25'>
			 <td valign='center' align='right' ><span class='style1'>None Taxable</span></td> 
 			 <td align='left'><input type='text' name='txtSaNoneTaxable' value='$txtSaNoneTaxable' maxlength='20' readonly style='text-align:right; width:100px; height=18px;'></td>

		  </tr>
		  <tr bgcolor='#D8D8D8' height='20'>
			 <td valign='center' align='right' ><span class='style1'>Gross Total</span></td> 
			 <td align='left'><input type='text' name='txtSaGrossTotal' value='$txtSaGrossTotal' maxlength='20' readonly style='text-align:right; width:100px; height=18px;'></td>
		  </tr>
		  <tr bgcolor='#D8D8D8' height='20'>
			 <td valign='center' align='right' ><span class='style1'>Discount</span></td> 
			 <td align='left'><input type='text' name='txtSaDiscount' value='$txtSaDiscount' maxlength='5'  style='text-align:right; width:40px; height=18px;' onKeyup='CalcSaDiscount(1, $DecimalBase,$VatApplied,$Setup_VatPercentage,$SalesTTC);' $DiscountMode >%
			                  <input type='text' name='txtSaDiscountAmt' value='$txtSaDiscountAmt' maxlength='20' style='text-align:right; width:44px; height=18px;' onKeyup='CalcSaDiscount(2, $DecimalBase,$VatApplied,$Setup_VatPercentage,$SalesTTC);' $DiscountMode ></td>
		  </tr>";
		  
	if ($ExportTransportToJV == 1) {
		echo"<tr bgcolor='#D8D8D8' height='20'>
			   <td valign='center' align='right' ><span class='style1'>Transport</span></td> 
			   <td align='left'><input type='text' name='txtSaTransportAmt' value='$txtSaTransportAmt' maxlength='20'  style='text-align:right; width:100px; height=18px;' onKeyup='CalcNetTotal($DecimalBase,$VatApplied,$Setup_VatPercentage,$SalesTTC);'></td>
		     </tr>";
	} else {
		echo "<input type='hidden' name='txtSaTransportAmt' value='$txtSaTransportAmt'>";
	}	

	if ($ExportBonusToJV == 1) {
		echo"<tr bgcolor='#D8D8D8' height='20'>
			   <td valign='center' align='right' ><span class='style1'>Bonus</span></td> 
			   <td align='left'><input type='text' name='txtSaBonusAmt' value='$txtSaBonusAmt' maxlength='20'  style='text-align:right; width:100px; height=18px;' onKeyup='CalcNetTotal($DecimalBase,$VatApplied,$Setup_VatPercentage,$SalesTTC);'></td>
		     </tr>";
	} else {
		echo "<input type='hidden' name='txtSaBonusAmt' value='$txtSaBonusAmt'>";
	}		
		  

$AllowModifyVAT = '';
if ($ModifyVAT == 0)
	$AllowModifyVAT = ' disabled ';


echo "    <tr bgcolor='#D8D8D8' height='20'>
			 <td valign='center' align='right' >
				<input type='hidden' name='txtSaVatChk' id='txtSaVatChk' value='$txtSaVatChk' size='1'/>
				<input name='chkSaVat' type='checkbox' id='chkSaVat' value='1' onClick='SetSaVat($DecimalBase,$VatApplied,$Setup_VatPercentage,$Module_Delivery,$SalesTTC);'   "; 
			  if ($txtSaVatChk==1 ) echo " checked $AllowModifyVAT />";  else echo " $AllowModifyVAT />";   
			  
	          
echo "   	 <span class='style1'>VAT $Setup_VatPercentage%</span></td> 
			 <td align='left'>
				<input type='text' name='txtSaVat' value='$txtSaVat' maxlength='20' style='text-align:right; width:100px; height=18px;' >
			 </td>
		  </tr>";

	if ($Module_AdditionalTaxes == 1) {
		echo"<tr bgcolor='#D8D8D8' height='20'>
			   <td valign='center' align='right' ><span class='style1'>Taxes</span></td> 
			   <td align='left'><input type='text' name='txtSaTotalTaxes' value='$txtSaTotalTaxes' maxlength='20' readonly style='text-align:right; width:100px; height=18px;' ></td>
		     </tr>";
	} else {
		echo "<input type='hidden' name='txtSaTotalTaxes' value='$txtSaTotalTaxes'>";
	}
	
	

	
	
echo"      <tr bgcolor='#D8D8D8' height='20'>
			 <td valign='center' align='right' ><span class='style1'>Net Total</span></td> 
			 <td align='left'><input type='text' name='txtSaNetTotal' value='$txtSaNetTotal' maxlength='20' readonly style='text-align:right; width:100px; height=18px;'></td>
		  </tr>
		  
		  </table></td></tr>";*/
		  
echo"	  <td rowspan='6' valign='top' >";

echo"	<div id='totals' style='width:240px; margin-top:3px; float:right;'>";
	ShowDeliveryTotals($connection,$txtSaId,$_SESSION['gdl_parameters'],$_SESSION['gdl_arrayaccess']);
echo"	</div>"; 

echo"	  </td>
		</tr>";
		
} else {
	echo"<td rowspan='7' >&nbsp;
			<input type='hidden' name='txtSaTaxable' value='$txtSaTaxable' >
			<input type='hidden' name='txtSaNoneTaxable' value='$txtSaNoneTaxable' >
			<input type='hidden' name='txtSaGrossTotal' value='$txtSaGrossTotal' >
			<input type='hidden' name='txtSaDiscount' value='$txtSaDiscount'  >
            <input type='hidden' name='txtSaDiscountAmt' value='$txtSaDiscountAmt' >
			<input type='hidden' name='txtSaVat' value='$txtSaVat' >
			<input type='hidden' name='txtSaVatChk' id='txtSaVatChk' value='$txtSaVatChk'/>
			<input type='hidden' name='txtSaTotalTaxes' value='$txtSaTotalTaxes' >
			<input type='hidden' name='txtSaTransportAmt' value='$txtSaTransportAmt' >
			<input type='hidden' name='txtSaBonusAmt' value='$txtSaBonusAmt' >
			<input type='hidden' name='txtSaNetTotal' value='$txtSaNetTotal' ></td></tr>";

}




echo"   <tr bgcolor='#F7F7F7'>
		  <td align='left' ><span class='style1'>Client&nbsp;<span class='style16'>*</span></span></td>";
echo"     <td colspan='7' ><span class='style1'>";
echo"     <label>

           <input type='text'   name='txtClientCode' id='txtClientCode' value='$txtClientCode' onblur='SetMaturityDate($Module_Delivery);'  style='width:95px;' maxlength='10'  onkeydown='return kdClient(0,event);'    />           
		   <input type='text'   name='txtClientName' id='txtClientName' value='$txtClientName' style='width:285px;'   onkeydown='return kdClient(1,event);'   />
		   <label><span class='style1'><img src='img/btnopen.jpg' title=' Select Client ' id='lstClientCodeH' width='15' height='20' border='0' onMouseOver=\"style.cursor='hand'\"  onClick='showlistClient(1); ' /> </span></label>
		   <label><img src='img/btnopen.jpg' title='Select Client' id='lstClientNameH' width='15' height='20' border='0' onMouseOver=\"style.cursor='hand'\"  onClick='showlistClientName(1);' style='display:none;' /></label>
		   <input type='hidden' name='txtClientVat' id='txtClientVat' value='$txtClientVat' />
          </label>
          </span>
          </td>";

if ($Module_ShowBalance == 1) {		  
	echo" <td align='left'><span class='style1'>Credit Limit</span></td>
		  <td align='left' ><font face='Verdana' size='2'><b>".addComma($txtCreditLimit)."</b></td>";
} else {
	echo" <td align='left' colspan='2'>&nbsp;</td>";
}		

echo"   <input type='hidden' name='txtPaymentTerms' id='txtPaymentTerms' value='$txtPaymentTerms' />
		<input type='hidden' name='txtCurrentBalance' value='$txtCurrentBalance'>
		<input type='hidden' name='txtCreditLimit' value='$txtCreditLimit' />";

echo"   </tr>";


if ($txtClientDtCode != '') {

	echo"   <tr bgcolor='#F7F7F7' height='25'>
			  <td align='left' ><span class='style1'>Detail</span></td>";
	echo"     <td colspan='7'><font face='Verdana' size='2'><b>&nbsp;$txtClientDtCode&nbsp;-&nbsp;$txtClientDtName</b></font></td>";
	echo"     <td colspan='2'>&nbsp;</td>";
	echo"   </tr>";

	
}	


echo"   <tr bgcolor='#F7F7F7'  height='25'>
		  <td align='left' ><span class='style1'>Salesman</span></td>";
echo"     <td colspan='7' ><span class='style1'>";
echo"     <label>
           <input type='text'   name='txtSalesmanCode' id='txtSalesmanCode' value='$txtSalesmanCode' style='width:95px;' maxlength='10' readonly />
           <input type='text'   name='txtSalesmanName' id='txtSalesmanName' value='$txtSalesmanName' style='width:285px;' readonly />
          </label>
          </span>
          <label><span class='style1'><img src='img/btnopen.jpg' title=' Select Salesman ' width='15' height='20' border='0' onMouseOver=\"style.cursor='hand'\"  onClick='showlistSalesman(1); ' /> </span></label></td>";

if ($Module_Delivery == 0 && $FI_DeliverySalesPrice == 1) {
	echo"     <td align='left' ><span class='style1'>Currency&nbsp;<span class='style16'>*</span></span></td>";
	echo"     <td ><span class='style1'><select name='txtCurr' id='txtCurr' style='width:60px;' onchange='ChangeCurrency();'>";
			echo"<option></option>";
			while($curf=mysql_fetch_row($resultcurrency)){
			echo"<option ";
				if ($txtCurr==$curf[0])
					echo " selected ";
				echo" value='$curf[0]'>$curf[0] </option>";
			}
			echo"</select></span></td>";	
} else {
	echo"<td colspan='2' ><input type='hidden'  name='txtCurr' id='txtCurr' value='$txtCurr' /></td>";
}			
          
echo"   </tr>";


echo"   <tr bgcolor='#F7F7F7'  height='25'>
		  <td align='left' valign='center'><span class='style1'>Remark</span></td><td colspan='7' > <span class='style1'>
		  <textarea name='txtRemark' rows=2 cols=46 >".$txtRemark."  </textarea></span></td>";

echo"     <td align='left' ><span class='style1'>Maturity&nbsp;<span class='style16'>*</span></span></td>
          <td ><input type='text' name='txtMaturityDate' value='$txtMaturityDate' maxlength='10'  style='width:90px;' ";if($login_maturitydate==0) echo ' readonly';echo">";
		  
		  if($login_maturitydate==1){
				echo"&nbsp;<A HREF='#' onClick=\"displayCalendar(document.sales.txtMaturityDate,'dd/mm/yyyy',this); return false;\" NAME=\"anchor1\" ID=\"anchor1\"><img src='./img/cal.gif' border=0 align=center></A>";
			}	
				
				echo"</td>";
echo"   </tr>";		  


echo"   <tr bgcolor='#F7F7F7'  height='30'>
		  <td align='left' valign='center'><span class='style1'>Driver's Name</span></td><td colspan='7' > <span class='style1'>
		  <input type='text' name='txtDriverName' value='".htmlspecialchars($txtDriverName, ENT_QUOTES)."'  style='width:385px;' maxlength='30' ></span></td>";
		  
echo"     <td align='left' valign='center'><span class='style1'>Vehicle No</span></td>
		  <td><input type='text' name='txtVehicleNumber' value='".htmlspecialchars($txtVehicleNumber, ENT_QUOTES)."'  style='width:90px;' maxlength='30' ></span></td>";
echo"   </tr>";		  

echo"   </tr>";


if($Module_VehicleWeight==1) {

echo"   <tr bgcolor='#F7F7F7'>";
echo"     <td align='left' valign='center'><span class='style1' >Vehicle Weight</span></td>
		  <td  colspan='2'><input type='text' name='txtVehicleWeight' readonly value='".htmlspecialchars($txtVehicleWeight, ENT_QUOTES)."'  style='width:120px;' maxlength='30' ></span></td>";
echo"     <td colspan='5' align='left' valign='center'><span class='style1'>Vehicle Loaded Weight</span>
		  <input type='text' name='txtVehicleLoadWeight' value='".htmlspecialchars($txtVehicleLoadWeight, ENT_QUOTES)."'  style='width:80px;' maxlength='30' ></span></td>";
echo"     <td align='left' valign='center'><span class='style1'>Total Weight</span></td>
		  <td><input type='text' name='txtRealQty' value='".htmlspecialchars($txtRealQty, ENT_QUOTES)."'  style='width:90px;' maxlength='30' ></span></td>";	  
echo"   </tr>";		  
}
else {
echo"
	  <input type='hidden' name='txtVehicleWeight' readonly value='".htmlspecialchars($txtVehicleWeight, ENT_QUOTES)."'  style='width:120px;' maxlength='30' ></span>
	  <input type='hidden' name='txtVehicleLoadWeight' value='".htmlspecialchars($txtVehicleLoadWeight, ENT_QUOTES)."'  style='width:80px;' maxlength='30' ></span>
	  <input type='hidden' name='txtRealQty' value='".htmlspecialchars($txtRealQty, ENT_QUOTES)."'  style='width:90px;' maxlength='30' ></span> 
	";		  
}

echo"   <tr bgcolor='#F7F7F7' >";

if ($Module_Project	== 1) { 
	echo "<td align='left' ><span class='style1'>Project&nbsp;<span class='style16'>*</span></span></td>
	      <td align='left' colspan='2'> <span class='style1'>
		    <input type='text' name='txtProjectCode' id='txtProjectCode' value='$txtProjectCode' style='width:120px;' maxlength='20' onchange=\"CheckLookup('chkcodeexists','project','project_code',this.value,'lstProjectCodeH');\" /></span>
		    <label><span class='style1'><img src='img/btnopen.jpg' title=' Select Project ' id='lstProjectCodeH' width='15' height='20' border='0' onMouseOver=\"style.cursor='hand'\" onClick='showlistProject(1); '  /></span></label></td>";
} else	{
	echo "<td align='left' colspan='3'><input type='hidden' name='txtProjectCode' id='txtProjectCode' value='' /></td>";
}		

if ($Module_CostCenter == 1 && $ShowCostCentLayout == 1) {		  
	echo" <td align='left' ><span class='style1'>Costcenter&nbsp;<span class='style16'>*</span></span></td>";		
	echo" <td align='left' colspan='4'><span class='style1'>
		    <input type='text' name='txtCostCentCode' id='txtCostCentCode' value='$txtCostCentCode' style='width:139px;' maxlength='20' onchange=\"CheckLookup('chkcodeexists','costcent','costcent_code',this.value,'lstCostCentCodeH');\" /></span>
		    <label><span class='style1'><img src='img/btnopen.jpg' title=' Select Costcenter ' id='lstCostCentCodeH' width='15' height='20' border='0' onMouseOver=\"style.cursor='hand'\"  onClick='showlistCostcenter(1); ' /></span></label></td>";
} else {
	echo "<td align='left' colspan='5'><input type='hidden' name='txtCostCentCode' id='txtCostCentCode' value='' /></td>";
}			


echo"   <td align='left' valign='center'><span class='style1'>Manual No</span></td>
		<td><input type='text' name='txtManualNo' value='".htmlspecialchars($txtManualNo, ENT_QUOTES)."'  style='width:90px;' maxlength='20' ></td>";
		
/*if ($txtClientDtCode != '') 
	echo"<td align='left' colspan='3'>&nbsp;</td>";
else
	echo"<td align='left' colspan='2'>&nbsp;</td>";*/
	
$querycashtype=" select CashType_Code, CashType_Description, CostCent_Code from cashtype where Journal_Type = 'DI'".
               " order by CashType_Description"; 
$resultcashtype=mysql_query($querycashtype,$connection) or die(mysql_error());
$numrow = mysql_num_rows($resultcashtype);
if($numrow >0){
	echo"   <tr height='25px' bgcolor='#F7F7F7'>
		   <td align='left'><span class='style1'>Cash Type</span></td>
		   <td align='left' colspan='7'><select name='delivery_cashType' id='delivery_cashType' value='$delivery_cashType' style='width:120px;'>";
		echo "<option value='' ".($delivery_cashType==''?'selected':'')."></option>";
		while($row = mysql_fetch_row($resultcashtype)){
			echo "<option value='$row[0]' ".($delivery_cashType==$row[0]?'selected':'').">$row[1]</option>";
		}		
		   echo "</select></td>
		   <td align='left'><span class='style1'></span></td>
		   <td align='left' colspan='2'></td></tr>";
} else echo "<input type='hidden' name='delivery_cashType' id='delivery_cashType' value='$delivery_cashType'>";

echo"   <tr bgcolor='#F7F7F7'>
		   <td align='left'><span class='style1'>Invoice Address</span></td>
		   <td align='left' colspan='7'><input type='hidden' name='txtIAddress' value='$txtIAddress'><font size='2' face='Verdana'><b>&nbsp;&nbsp;".str_replace("'", "", $txtIAddress)."</b></font></td>
		   <td align='left'><span class='style1'>Delivery Address</span></td>
		   <td align='left' colspan='2'><textarea name='txtDAddress' rows='3' cols='39'>".htmlspecialchars($txtDAddress, ENT_QUOTES)."</textarea>";
		   echo "<input type='hidden' name='delivery_date' value='".$delivery_date."'>";
		   echo "<input type='hidden' name='delivery_card_msg' value='".$delivery_card_msg."'>";
		   echo "<input type='hidden' name='delivery_contact' value='".$delivery_contact."'>";
		   echo "<input type='hidden' name='delivery_contactphone' value='".$delivery_contactphone."'>";
		   echo "&nbsp;<img src='img/openlist.png' style='cursor: pointer' onclick='openAddressInfo(".$txtSaId.")'>";
		echo "</td></tr>";



if ($showDestinatin == 1){
	echo "<tr bgcolor='#F7F7F7' height='30px'><td colspan='11'><fieldset style='border: 1px solid lightgray;'><legend><span class='style1'>Destination</span></legend>
		<table cellspacing=0 cellpadding=0 border=0><col width='90px'><col width='250px'><col width='90px'><col width='250px'><col width='90px'><col width='120px'><tr>
				<td><span class='style1'>From</span></td><td><input type='text' name='txtdestfrom' id='txtdestfrom' value='".htmlspecialchars($txtdestfrom,ENT_QUOTES)."' maxlength='45' style='width:230px;'></td>
				<td><span class='style1'>To</span></td><td><input type='text' name='txtdestto' id='txtdestto' value='".htmlspecialchars($txtdestto,ENT_QUOTES)."' maxlength='45' style='width:230px;'></td>
				<td><span class='style1'>Date</span></td><td><input type='text' name='txtdestdate' id='txtdestdate' value='$txtdestdate' style='width:90px;'>
				<a href='#' onclick=\"displayCalendar(document.sales.txtdestdate,'dd/mm/yyyy',this);  return false; \" name='anchor1' id='anchor1'>
				<img src='./img/cal.gif' border=0 align='center'></a>
				</td>
			</tr></table>
		</fieldset></td></tr>";
} else {
	echo "<input type='hidden' name='txtdestfrom' id='txtdestfrom' value='".htmlspecialchars($txtdestfrom,ENT_QUOTES)."'  maxlength='45'>
		<input type='hidden' name='txtdestto' id='txtdestto' value='".htmlspecialchars($txtdestto,ENT_QUOTES)."' maxlength='45'>
		<input type='hidden' name='txtdestdate' id='txtdestdate' value='$txtdestdate'>";
}
echo"   <tr bgcolor='#D8D8D8' height='30'>
			<td colspan='11' align='center'>";
echo"  <button type='button' id='btnXtraInfo' name='btnXtraInfo' onclick='showInfo(); return false;' title='More Information'><span><span>Export Information</span></span></button>";
echo"       </td>";
echo"<td bgcolor='#F7F7F7' align='left' colspan='2'>&nbsp;</td>
		</tr>";
		


echo "<tr><td colspan='10'><div id='exportInfo'>";
echo "<table width='600px' cellpadding='0' cellspacing='0'><col width='100px'><col width='150px'><col width='100px'><col width='150px'>";
echo "<tr><td colspan='4' align='right' valign='top'><img src='img/close-button.png' height='20px' width='20px' onclick=\"closeMatWin();\" onmouseover=\"style.cursor='hand'\"></td></tr>";

if($txtSaId == '' && $txthscode == '') $txthscode = '62044900';
echo "<tr height='30px'>
		<td  style='padding-left: 10px;'><span class='style1'>HS Code</span></td>
		<td><input type='text' name='txthscode' id='txthscode' value='$txthscode' style='width:150px;'>
		<td  style='padding-left: 10px;'><span class='style1'>Number Of Boxes</span></td>
		<td><input type='text' name='txtnumber_boxes' id='txtnumber_boxes' value='$txtnumber_boxes' style='width:150px;'>
		</td>
	 </tr>";

echo "<tr height='30px'>
		<td  style='padding-left: 10px;'><span class='style1'>Gross Weight</span></td>
		<td><input type='text' name='txtgrossweight' id='txtgrossweight' value='$txtgrossweight' style='width:150px;'>
		<td  style='padding-left: 10px;'><span class='style1'>Net Weight</span></td>
		<td><input type='text' name='txtnetweight' id='txtnetweight' value='$txtnetweight' style='width:150px;'>
		</td>
	 </tr>";	 

echo "</table>";
echo "</div></tr>";			

	
		  
/*		  
		  

echo"   <tr><td colspan='11' valign='top'>";
echo"	<div style='overflow:scroll; height:180px; width:980px;' >";
echo"     <table border='0' style='table-layout:fixed'>
		  <col width=20>
		  <col width=20>
		  <col width=20>";
		  
if ($Module_Delivery == 0 && $FI_DeliverySalesPrice == 1) {
	if ($Module_DoubleUnit == 1) {
		echo" <col width=120>
			  <col width=120>
			  <col width=200>
			  <col width=70>
			  <col width=60>
			  <col width=60>
			  <col width=60>
			  <col width=60>
			  <col width=60>
			  <col width=60>
			  <col width=50>
			  <col width=90>
			  <col width=50>
			  <col width=100>";
	} else {
		echo" <col width=120>
			  <col width=120>
			  <col width=200>
			  <col width=70>
			  <col width=60>
			  <col width=60>
			  <col width=60>
			  <col width=70>
			  <col width=50>
			  <col width=90>
			  <col width=50>
			  <col width=100>";
	}

	if ($Module_ProjectDt == 1)	
		echo"<col width=100>";
	if ($Module_CostCenterDt == 1)
		echo"<col width=100>";
	if ($Module_ExpireDate == 1) {
		echo"<col width=80>";
		echo"<col width=80>";
	}	  	
} else {
	if ($Module_DoubleUnit == 1) {
		echo" <col width=120>
			  <col width=120>
			  <col width=210>
			  <col width=60>
			  <col width=65>
			  <col width=65>
			  <col width=40>
			  <col width=80>
			  <col width=40>
			  <col width=60>
			  <col width=50>";
	} else {
		echo" <col width=120>
			  <col width=120>
			  <col width=250>
			  <col width=95>
			  <col width=62>
			  <col width=80>
			  <col width=60>
			  <col width=80>
			  <col width=50>";
	}

	if ($Module_ProjectDt == 1)	
		echo"<col width=100>";
	if ($Module_CostCenterDt == 1)
		echo"<col width=100>";
	if ($Module_ExpireDate == 1) {
		echo"<col width=80>";
		echo"<col width=80>";
	}
}		  
		  
		  echo"<tr height='25'>";
		  echo"  <td bgcolor='#F7F7F7' align='left'><span class='style27'>&nbsp;</span></td>";
		  echo"  <td bgcolor='#F7F7F7' align='left'><span class='style27'>&nbsp;</span></td>";
		  echo"  <td bgcolor='#F7F7F7' align='left'><span class='style27'>&nbsp;</span></td>";
          echo"  <td bgcolor='#F7F7F7' align='left'><span class='style27'>Item Code Packed</span></td>";
		  echo"  <td bgcolor='#F7F7F7' align='left'><span class='style27'>Item Code</span></td>";
		  echo"  <td bgcolor='#F7F7F7' align='left'><span class='style27'>Description</span></td>";
		  echo"  <td bgcolor='#F7F7F7' align='left'><span class='style27'>Warehouse</span></td>";
		  echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Order Ref</span></td>";
		  echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Rem. Order Qty</span></td>";
		  
		  //if ($Module_DoubleUnit == 1)
			echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Unit1</span></td>";
			
		  echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Delivery Qty</span></td>";
		  
		  if ($Module_DoubleUnit == 1) {
			echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Unit2</span></td>";
			echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Unit2 Qty</span></td>";
		  }
		  echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>S/N Bal</span></td>";
			
		  if ($Module_Delivery == 0 && $FI_DeliverySalesPrice == 1) {
			echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>$PriceLabel</span></td>";
			echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Disc(%)</span></td>";
			echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Total</span></td>";
		  }	
		  
		  if ($Module_ProjectDt == 1)	
			echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Project</span></td>";
		  if ($Module_CostCenterDt == 1)
			echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>CostCenter</span></td>";
		  if ($Module_ExpireDate == 1) {
			echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Batch No</span></td>";
			echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Expire Date</span></td>";
		  }
          echo"</tr>";
		  
		  if ($txtSaId != '' ) {
		     
			//Checking For Difference Btw Qty and Count SerialNo
		    $QtySerNoCheck = 0;
			echo '<script type="text/javascript" language="javascript">';
			echo ' x = document.sales; ';
  			echo ' x.QtySerNo.value=0; ';
			echo '</script>';
			  
			$totdtqty = 0;
			 
			$querydt = " Select DeliveryDt.DeliveryDt_id, DeliveryDt.Item_CodePacked, DeliveryDt.Item_code, Item_Description, DeliveryDt.Warehouse_Code, ".
					   " DeliveryDt_Remark, DeliveryDt_Quantity, Round(DeliveryDt_Price, ".$DecimalBase."), DeliveryDt_PriceBase1, DeliveryDt_PriceBase2, ".
					   " Round(DeliveryDt_DiscountPer, ".$DecimalBase."),  ".
					   " 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, ".
					   " SorderDt.SorderDt_Quantity, ifNull(item_withserialno,0) As ItemWithSerialNo, Sorder.Sorder_reference, Count(SerialNo_Code) As CountSerialNo,  ".
					   " DeliveryDt.Item_Unit2Qty, Item_UnitPurchaseDesc, Item_UnitSalesDesc, ".
					   " Date_Format(DeliveryDt_ExpireDate,'%d/%m/%Y') As DeliveryDt_ExpireDate, DeliveryDt_BatchNo, DeliveryDt.Project_code, DeliveryDt.CostCent_Code ".
					   " From Temp_DeliveryDt As DeliveryDt Left Join Items on DeliveryDt.Item_code = Items.Item_code ".
					   " Left Join Temp_Purchasesserialno on DeliveryDt.DeliveryDt_ID = Temp_Purchasesserialno.PurchaseDt_ID ".
					   " And Temp_Purchasesserialno.Journal_Type = 'DI' ".
					   " And Temp_Purchasesserialno.DeliveryDt_ID Is Not Null ".
					   " Left Join SorderDt on SorderDt.SorderDt_ID = DeliveryDt.RelatedDt_Id  ".
					   " Left Join Sorder on Sorder.Sorder_ID = SorderDt.Sorder_ID  ".
					   " Where DeliveryDt.Delivery_ID = ".$txtSaId.
					   //" And DeliveryDt.Logged_Code = '".$HTTP_SESSION_VARS['useraccount']."' ".
					   " Group By  DeliveryDt.DeliveryDt_ID ".
					   " Order By DeliveryDt.DeliveryDt_ID Desc ";
			//echo $querydt;
			$resultdt=mysql_query($querydt,$connection) or die(mysql_error());
			while($rowsdt=mysql_fetch_array($resultdt)){
			    
				$ct+=1;

				if($ct%2==0)
					$Color="style='background-color:".$grid_color1."'";
				else			
					$Color="style='background-color:".$grid_color2."'";	
						
				$sub_query = " Select ifNull(Sum(ifNull(DeliveryDt1.DeliveryDt_Quantity,0)),0) ".
							 " From Temp_DeliveryDt As DeliveryDt, DeliveryDt As DeliveryDt1 ".
							 " Where DeliveryDt.DeliveryDt_id = '".$rowsdt[0]."' ".
							 " And DeliveryDt.Journal_Type = 'DI' ".
							 " And (ifNull(DeliveryDt.RelatedDt_Id,0) != 0 and DeliveryDt.RelatedDt_Id != '') ".
							 " And DeliveryDt1.Journal_Type = 'DI' ".
							 " And DeliveryDt1.Delivery_ID != '".$txtSaId."' ".
							 " And DeliveryDt1.RelatedDt_Id = DeliveryDt.RelatedDt_Id ";

				$sub_result = selectData($connection, $sub_query);
				$DeliveredQty = $sub_result[0];
				if ($DeliveredQty == '') $DeliveredQty = 0;
				$OrderedQty = $rowsdt[14];
				$RemainedQty = $OrderedQty - $DeliveredQty;
				
				echo "<tr ".$Color." >";

				// If ItemWithSerialNo True And ModuleSerialNo True	
				if ($rowsdt[15] == 1 && $Module_SerialNo == 1) 
					echo "	<td align='center' valign='center'><span class='style15'><img src='img/button_addserial.png' onMouseOver=\"style.cursor='hand'\" onclick=\"AddSerialNo('".$rowsdt[0]."','".htmlentities($rowsdt[2])."','".$RemainedQty."','".$rowsdt[4]."')\" title='Add Serial Nos'  ></span></td>";
				else
					echo "	<td align='center' valign='center'>&nbsp;</td>";
					
				echo "	<td align='center' valign='center'><span class='style15'><img src='img/button_edit.png'  onMouseOver=\"style.cursor='hand'\" onclick=UpdateSaDt('".$rowsdt[0]."',$Module_Delivery) title='Edit Record'  ></span></td>";
				echo "	<td align='center' valign='center'><span class='style15'><img src='img/c_delete.png'  onMouseOver=\"style.cursor='hand'\" onclick=\"DeleteSaDt('".$rowsdt[0]."','".htmlentities($rowsdt[1])."','".htmlentities($rowsdt[2])."',$Module_Delivery)\" title='Delete Record'  ></span></td>";
				echo "	<td align='left'><span class='style15'>".$rowsdt[1]."</span></td>";
				echo "	<td align='left'><span class='style15'>".$rowsdt[2]."</span></td>";
				echo "	<td align='left'><span class='style15'>".$rowsdt[3]."</span></td>";
				echo "	<td align='left'><span class='style15'>".$rowsdt[4]."</span></td>";
				echo "	<td align='left'><span class='style15'>".$rowsdt[16]."</span></td>";
				//echo "	<td align='right'><span class='style15'>".$rowsdt[14]."</span></td>";
				echo "	<td align='right'><span class='style15'>".$RemainedQty."</span></td>";
				//echo "	<td align='right'><span class='style15'>".$rowsdt[6]."</span></td>";
				
				//if ($Module_DoubleUnit == 1)
					echo "	<td align='left'><span class='style15'>".$rowsdt[20]."</span></td>";
					
				// if Total Quantity Differs From Total SerialNos And
				// If ItemWithSerialNo True And ModuleSerialNo True	
				//Stopped 20120612 due to dajcom request
				//if (($rowsdt[6] != $rowsdt[17] && $rowsdt[15] != 0 && $Module_SerialNo == 1) || ($rowsdt[6] == 0 && $rowsdt[15] != 0 && $Module_SerialNo == 1)) {
				if (($rowsdt[6] != $rowsdt[17] && $rowsdt[17] != 0 && $Module_SerialNo == 1) ) {
				    if ($QtySerNoCheck == 0) {
						$QtySerNoCheck = 1;
						
						echo '<script type="text/javascript" language="javascript">';
						echo ' x = document.sales; ';
						echo ' x.QtySerNo.value=1; ';
						echo '</script>';
					}					
						
					echo "	<td align='right' style='background-color:#FF0000' ><span class='style28' style='text-decoration:underline;'>".$rowsdt[6]."</span></td>";
				} else	
					echo "	<td align='right'><span class='style15'>".$rowsdt[6]."</span></td>";
					
				if ($Module_DoubleUnit == 1) { 
					echo "	<td align='left'><span class='style15'>".$rowsdt[19]."</span></td>";	
					echo "	<td align='right'><span class='style15'>".number_format($rowsdt[18],2)."</span></td>";	
				}	
					
				echo "	<td align='right'><span class='style15'>".$rowsdt[17]."</span></td>";	
				
				if ($Module_Delivery == 0 && $FI_DeliverySalesPrice == 1) {
					if ($SalesTTC == 1) 
						echo "	<td align='right'><span class='style15'>".number_format($rowsdt[12], $DecimalBase)."</span></td>";
					else
						echo "	<td align='right'><span class='style15'>".number_format($rowsdt[7], $DecimalBase)."</span></td>";
						
					echo "	<td align='right'><span class='style15'>".$rowsdt[10]."</span></td>";
					
					if ($SalesTTC == 1) 
						echo "	<td align='right'><span class='style15'>".number_format($rowsdt[13], $DecimalBase)."</span></td>";
					else
						echo "	<td align='right'><span class='style15'>".number_format($rowsdt[11], $DecimalBase)."</span></td>";
				}
				
				if ($Module_ProjectDt == 1)	
					echo "	<td align='left'><span class='style15'>".$rowsdt[23]."</span></td>";
				if ($Module_CostCenterDt == 1)
					echo "	<td align='left'><span class='style15'>".$rowsdt[24]."</span></td>";
				if ($Module_ExpireDate == 1) {
					echo "	<td align='left'><span class='style15'>".$rowsdt[22]."</span></td>";
					echo "	<td align='left'><span class='style15'>".$rowsdt[21]."</span></td>";
				}
				
				echo "</tr>";
						
					
			$totdtqty = $totdtqty + $rowsdt[6];
			}
			
			if ($totdtqty!=''){
			echo '<script type="text/javascript" language="javascript">';
						echo ' x = document.sales; ';
						echo ' x.txtRealQty.value='.$totdtqty.'; ';
						echo '</script>';
						}
		 }
		
		echo "</table></div>"; 

echo"   </td></tr>";
*/
/*
echo"   <tr bgcolor='#D8D8D8' height='30'><td colspan='11' align='center'>";

if ($Module_DeliveryWithSorder == 0)
	echo"	<input type='button' id='btnAddItem' name='btnAddItem' value='Add Item'  onclick='AddItems($Module_RestrictProjCost, $Module_RestrictCost, $Module_Project, $Module_CostCenter, $FI_SalesCheckSalesman)' $style title='Add Item' >";

if ($Module_SerialNo == 0)
	echo"	<input type='button' id='btnAddSerial' name='btnAddSerial' value='Add Serials'  onclick='AddSerials($Module_RestrictProjCost, $Module_RestrictCost, $Module_Project, $Module_CostCenter, $FI_SalesCheckSalesman)' $style title='Add Item' >";
	
echo"       <input type='button' id='btnClear' name='btnClear' value='Clear Page'   onclick='ClearPage();' $style title='Clear Page'>";
				
if ($txtSaId != '')
	echo"   <input type='button' name='btnCancel' id='btnCancel' value='Cancel' onclick='CancelRecord();' $style title='Cancel Changes'>";
	
if ($txtSaId != '')
	echo"   <input type='button' name='btnPost' id='btnPost' value='Save' onclick='PostChanges($Module_RestrictProjCost, $Module_RestrictCost, $Module_Project, $Module_CostCenter, $FI_SalesCheckSalesman);' $style	title='Save Changes' />";

if ($txtSaId == '')
	echo"   <input name='btnSearch' type='button' id='btnSearch' value='Search' onclick='SearchForRef();' $style title='Search By Reference' />";

if ($txtSaId == '')
	echo"   <input name='btnPending' type='button' id='btnPending' value='Pending' onclick='SearchForPending();' $style title='Pending Preparation Order'  />";

echo"   <input name='btnSearchSorder' type='button' id='btnSearchSorder' value='Load Preparation Order' onclick='SearchConfirmedSorder($Module_RestrictProjCost, $Module_RestrictCost, $Module_Project, $Module_CostCenter, $FI_SalesCheckSalesman);' $style title='Search Confirmed Preparation Order'  />";
echo"   <input name='btnLoadItems' type='button' id='btnLoadItems' value='Load Sold Items' onclick='LoadSoldItems($Module_RestrictProjCost, $Module_RestrictCost, $Module_Project, $Module_CostCenter, $FI_SalesCheckSalesman);' $style title=''Load Sold Items'  />";
		
		
if ($Login_DisapproveSorder == 1 && $txtRef == "")
	echo"  <input name='btnDisapproveOrder' type='button' id='btnDisapproveOrder' value='Disapprove Order' onclick=\"DisapproveOrder('".$txtSorderRef."');\" $style title='Disapprove Order' />";

if ($FA_LedgerAccess == 1 && $txtClientCode != '')
	echo"  <input name='btnStatement' type='button' id='btnStatement' value='Client Statement' onclick=\"PrintStatement('".$base1."',$Module_ReferenceByProject);\" $style title='Print Client Statement' />";		
				

echo"   </td></tr>";	
*/

echo"   <tr bgcolor='#ffffff'><td colspan='11' valign='top'>";
echo"	<div id='datagrid' class='grid' style='width:1090px;' >";




//Show Items Grid
ShowDeliveryDtGrid($connection,'DI',$txtSaId,$_SESSION['gdl_parameters'],$_SESSION['gdl_arrayaccess'],'DeliveryDt.DeliveryDt_ID');

echo"	  </div>"; 
echo"   </td></tr>"; 
echo"   </table></td></tr>"; 
 echo"   </table></td></tr><tr height='30'><td align='center' id='content-bottom' ></td></tr>";  
echo"   </table></td></tr>"; 

echo" </table>  ";//end of last table menu
	

if ($actionmode == "post"  && $PrSaId != '') {
	$sub_query = " SELECT Delivery_Reference, Journal_Refgovernment ".
			     " FROM Deliveries Left Join Journal on Deliveries.Journal_Id = Journal.Journal_Id ".
                 " WHERE Delivery_Id = $PrSaId ";
	$sub_result   = selectData($connection, $sub_query);
	$PrSaRef = $sub_result[0];
	$PrJvRef = $sub_result[1];
	
	
	echo '<script type="text/javascript" language="javascript">';
	
	if ($Login_FastPrint == 1) {
		//if ($FI_DeliverySalesPrice == 1)
			echo ' PrintSales(\''.$PrSaId.'\', \''.$PrSaRef.'\', \''.$PrJvRef.'\'); ';
		
		if ($Module_Delivery == 0 && $Module_PrintWaybill == 1)		
			echo ' PrintSalesWaybill(\''.$PrSaId.'\', \''.$PrSaRef.'\'); ';
	}		
	echo ' ClearPage1(); ';
	echo '</script>';

}

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

HERE;

?>