<?php

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



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

//echo $HTTP_SESSION_VARS['dbName']." ".$HTTP_SESSION_VARS['dbLabel'];
 

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


$querylog="SELECT FI_Delivery as loginaccess, FI_SalesVAT from ".$_SESSION['dbLabel'].".login where user_account='".$_SESSION['useraccount']."' 	and Upper(Login_Schema) = Upper('".$HTTP_SESSION_VARS['dbName']."')	";
$resultlog=mysql_query($querylog,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultlog)){
	extract($rows);
}

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 ".$HTTP_SESSION_VARS['dbLabel'].".login where user_account='".$HTTP_SESSION_VARS['useraccount']."' and Upper(Login_Schema) = Upper('".$HTTP_SESSION_VARS['dbName']."')  ";
$resultlog=mysql_query($querylog,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultlog)){
	extract($rows);
}

	
//Read From 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 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_autodiscount,0) As Module_AutoDiscount ".
             " 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 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 ".$HTTP_SESSION_VARS['dbLabel'].".loginstk where user_account='".$HTTP_SESSION_VARS['useraccount']."' and ifNull(default_warehouse,0) = 1 ";
$resultdflwh=mysql_query($querydflwh,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultdflwh)){
  extract($rows);
}

//Projects List
$queryproject=" select distinct project.project_code, project_name ".
              " from project left join ".$HTTP_SESSION_VARS['dbLabel'].".loginstk on project.project_code like concat(ifnull(loginstk.project_code,project.project_code),'%') ".
			  " where user_account='".$HTTP_SESSION_VARS['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='".$HTTP_SESSION_VARS['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 ".$HTTP_SESSION_VARS['dbLabel'].".loginstk on costcent.costcent_code like concat(loginstk.costcent_code,'%') ".
 			   " where user_account='".$HTTP_SESSION_VARS['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 ".$HTTP_SESSION_VARS['dbLabel'].".loginstk on costcent.costcent_code like concat(loginstk.costcent_code,'%') ".
 			   " where user_account='".$HTTP_SESSION_VARS['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 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=BatchNo','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;
	//alert(msgw);
	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 sadtquantity     = document.getElementById('sadtquantity['+PIndex+']').value;
	var SaDtDisc      = document.getElementById('sadtdiscount['+PIndex+']').value;
	var AvailableQty   = document.getElementById('availableqty['+PIndex+']').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);
	
	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 < vAllowedPrice)  && ModuleDelivery == 0 ) { 
		alert('Price entered not allowed.');
		document.getElementById('price['+PIndex+']').focus();
		return 2;		
	} 
	
	else if ((SaDtPrice > vAllowedPrice1 && MaxAllowCostPer > 0 && vAllowedPrice1 > 0)  && 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
		if(sadtquantity == 1)
		{
			document.getElementById('sadtquantity['+PIndex+']').focus();
		}

		
		
	
	else
	return 1 ;	
}


function ClearPage(){
	if (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) {
	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;
						
					
					x.actionmode.value='post';
					x.action="Form_Delivery_Actions.php?mode=post&mainmode="+vMainMode+"&SSaId="+SaId+"&SSaVatChkbx="+vVatChkbx+"&PLang="+PLang+'&PSaDate='+x.txtDate.value;
					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.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) {
	
	x = document.sales;
	 
	var ItemNonStock   = document.getElementById('itemnonstock['+PIndex+']').value;
	var ItemExpire     = document.getElementById('itemexpire['+PIndex+']').value;
	var ItemWithSerial = document.getElementById('itemwithserial['+PIndex+']').value;
var vdelivery_export  = x.delivery_export.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 == 2) {
		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  = '';
	
	
	
	var delivery_date     = x.delivery_date.value;
	var delivery_card_msg = x.delivery_card_msg.value;
	var delivery_contact  = x.delivery_contact.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+
					'&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)+
					'&SSaDtId='+document.getElementById('sadtid['+PIndex+']').value+
					'&lstWarehouse='+document.getElementById('warehousecode['+PIndex+']').value+
					'&txtItemCode='+encodeURIComponent(document.getElementById('itemcode['+PIndex+']').value)+
					'&txtSaDtRemark='+document.getElementById('remarkdt['+PIndex+']').value+
					'&txtSaDtCloseQty='+document.getElementById('sadtcloseqty['+PIndex+']').value+
					'&txtSaDtQty='+document.getElementById('sadtquantity['+PIndex+']').value+
					'&txtSaDtQty2='+document.getElementById('unit2qty['+PIndex+']').value+
					'&txtSaDtPrice='+document.getElementById('price['+PIndex+']').value+
					'&txtSaDtDiscount='+document.getElementById('sadtdiscount['+PIndex+']').value+
					'&deliverydt_clientdiscount='+document.getElementById('deliverydt_clientdiscount['+PIndex+']').value+
					'&deliverydt_itemdiscount='+document.getElementById('deliverydt_itemdiscount['+PIndex+']').value+
					'&chkSaDtPromo='+ItemPromo+
					'&deliverydt_heatno='+document.getElementById('deliverydt_heatno['+PIndex+']').value+
					'&txtSaDtBatchNo='+document.getElementById('batchno['+PIndex+']').value+
					'&txtSaDtExpireDate='+document.getElementById('expiredate['+PIndex+']').value+
					'&txtProjectCodeDt='+document.getElementById('projectcodedt['+PIndex+']').value+
					'&deliverydt_quantitybox='+deliverydt_quantitybox+
					'&deliverydt_itemunit='+deliverydt_itemunit+
					'&deliverydt_itempackage='+deliverydt_itempackage+
					'&txtCostCentCodeDt='+document.getElementById('costcentcodedt['+PIndex+']').value+'&Pdelivery_date='+delivery_date+'&Pdelivery_card_msg='+delivery_card_msg+'&Pdelivery_contact='+delivery_contact;
		
	
	if (result == 1 || result == 2) {
		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 msg = data[0].message;				
					var msgw = data[0].messagew;
					if ((msgw!="") && (msg == "") &&(msgw!="")) {
						alert(decodeURIComponent(msgw));
						//alert("test");
						document.getElementById('txtClientCode').focus();
						document.getElementById('txtClientCode').scrollIntoView();
						
					}
					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+']';
						if (result == 2)
							 nextcell = 'price[' + parseInt(PIndex) + ']';
						
						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=1230,height=600,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) {
	var str = '';
	x = document.sales;
	var vMsg = "Do you want to Print current Invoice with reference "+SaRef+" ?";
	for (var 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);
	}	
	
	
}

function PrintSalesWaybill(SaId, SaRef) {
x = document.sales;
	var str = '';
	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 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);
	
	window.open('List_BatchNo.php?frm=10&index='+PIndex+'&PItem_Code='+vItemCode,'List_BatchNo','width=580,height=400,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes,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) {
	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 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 openAddressInfo(txtSaId)
{
	XPos = (screen.availHeight - 550) / 2;
	YPos = (screen.availWidth - 850) / 2;
	if(txtSaId == null)
	{
		txtSaId = "";
	}
	window.open('updateAddressInfo.php?SaId='+txtSaId,'updateAddressInfo','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 saveAddress()
{
	opener.document.salesorder.sorder_date.value = document.salesorder_address.sorder_date.value;
	opener.document.salesorder.sorder_card_msg.value = document.salesorder_address.sorder_card_msg.value;
	opener.document.salesorder.sorder_contact.value = document.salesorder_address.sorder_contact.value;
	opener.document.salesorder.txtDAddress.value = document.salesorder_address.txtDAddress.value;
	opener.document.salesorder.sorder_contactphone.value = document.salesorder_address.sorder_contactphone.value;
	window.close();
	
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Sales Order</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>

</head>
<body onkeydown='return kd(event);'>
<form name='salesorder_address' id='salesorder_address' method='post' action=''   enctype='multipart/form-data'>


HERE;


//echo "<input type='text' name='date'><A HREF=\"#\" onClick=\"displayCalendar(document.sales_address.date,'dd/mm/yyyy',this);  return false; \" NAME=\"anchor1\" ID=\"anchor1\"><img src='./img/cal.gif' border=0 align=center></A>";
$SorId = $_GET['SorId'];
if($SorId != "")
{
	$query_salesorder_address  = "select date_format(Sorder_ClientSorderDate, '%d/%m/%Y') as sorder_date1, Sorder_ShippingWay as sorder_card_msg1, Sorder_ShipName as sorder_contact1, Sorder_DeliveryPlace as txtDAddress1, Sorder_ClientPhone as sorder_contactphone1
	                         from temp_sorder
							 where Sorder_id = '".$SorId."'";
							 //echo $query_salesorder_address;
	$result_salesorder_address = mysql_query($query_salesorder_address, $connection);
	$row_salesorder_address    = mysql_fetch_array($result_salesorder_address);
	extract($row_salesorder_address);
}
if($sorder_date == "")
{
	$query_delivery_date  = "select date_format(now(), '%d/%m/%Y') as delivery_date2";
	$result_delivery_date = mysql_query($query_delivery_date, $connection);
	$row_delivery_date    = mysql_fetch_array($result_delivery_date);
	extract($row_delivery_date);
	$sorder_date = $delivery_date2;
}
echo "<div style='width: 500px; margin: auto'>
<table width=500>
<tr>
<td style='width: 150px; font-size: 12px; font-weight: bold; vertical-align: top'>Delivery Date &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<A HREF=\"#\" onClick=\"displayCalendar(document.salesorder_address.sorder_date,'dd/mm/yyyy',this);  return false; \" NAME=\"anchor1\" ID=\"anchor1\"><img src='./img/cal.gif' border=0 align=center></A>&nbsp;</td>
<td style='width: 350px'><input type='text' name='sorder_date' style='width: 320px; vertical-align: top' value='";
if($sorder_date1 != "")
{
	echo $sorder_date1;
}
else
{
echo $sorder_date;
}
echo "'>&nbsp;</td>
</tr>
<tr>
<td style='width: 150px; font-size: 12px; font-weight: bold; vertical-align: top'>Contact Person</td>
<td style='width: 350px; vertical-align: top'><input type='text' style='width: 320px;' name='sorder_contact' value='";
if($sorder_contact1 != "")
{
	echo $sorder_contact1;
}
else{
echo $sorder_contact;
}
echo "'></td>
</tr>
<tr>
<td style='width: 150px; font-size: 12px; font-weight: bold; vertical-align: top'>Contact Phone</td>
<td style='width: 350px; vertical-align: top'><input type='text' style='width: 320px;' name='sorder_contactphone' value='";
if($sorder_contactphone1 != "")
{
	echo $sorder_contactphone1;
}
else{
echo $sorder_contactphone;
}
echo "'></td>
</tr>
<tr>
<td style='width: 150px; font-size: 12px; font-weight: bold; vertical-align: top'>Card Message</td>
<td style='width: 350px; vertical-align: top'><textarea name='sorder_card_msg' style='width: 320px; height: 50px'>";
if($sorder_card_msg1 != "")
{
	echo $sorder_card_msg1;
}
else
{
echo $sorder_card_msg;
}
echo "</textarea></td>
</tr>
<tr>
<td style='width: 150px; font-size: 12px; font-weight: bold; vertical-align: top'>Delivery Address</td>
<td style='width: 350px; vertical-align: top'><textarea name='txtDAddress' style='width: 320px; height: 80px'>";
if($txtDAddress1 != "")
{
	echo $txtDAddress1;
}
else
{
echo $txtDAddress;
}
echo "</textarea></td>
</tr>
<tr>
<td></td>
<td style='text-align: center'><button type='button' id='btnCash' name='btnCash' onclick='saveAddress();return false;' title='Save'><span><span>Save</span></span></button></td>
</tr>
</table>
</div>";


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

HERE;

?>