<?php

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


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


$querylog="SELECT FI_Sales as loginaccess 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_SalesDel,0) As FI_SalesDel, ifNull(FI_SalesMod,0) As FI_SalesMod, ".
          " ifNull(FI_SalesApp,0) As FI_SalesApp, ifNull(ModifyVAT,0) As ModifyVAT, ifNull(Login_ModifyDiscount,0) As Login_ModifyDiscount, ".
		  " ifNull(Login_FastPrint,0) As Login_FastPrint,ifNull(FI_SalesWithPrice,0) As FI_SalesWithPrice, ifNull(FI_ChangeInvoiceClient,0) As FI_ChangeInvoiceClient, ".
		  " ifNull(Login_ModifySellingPrice,0) As Login_ModifySellingPrice, ifNull(Allow_MinimumPrice,0) As Allow_MinimumPrice,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 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_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_ProjectDt,0) As Module_ProjectDt, ifNull(Module_CostCenterDt,0) As Module_CostCenterDt, ".
			 " ifNull(Module_DoubleUnit,0) As Module_DoubleUnit, ifNull(Module_ChangeInvoiceClient,0) As Module_ChangeInvoiceClient, ".
			 " ifNull(Module_ExpireDate,0) As Module_ExpireDate, ifNull(Module_Pack,0) As Module_Pack, ifNull(Module_Unit1Method,0) As Module_Unit1Method, ".
			 " ifNull(Module_VehicleWeight,0) As Module_VehicleWeight, ifNull(module_DeliveryWithSorder,0) As Module_DeliveryWithSorder ".			 
             " From Module ";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}

//Read From SalesSetup Table
$querySalesSetup=" Select SalesTTC, ClientCur, Warehouse As SetupDftWareHouse, ifNull(ExportTransportToJV,0) As ExportTransportToJV, ".
				 " ifNull(ExportBonusToJV,0) As ExportBonusToJV, ifNull(PriceDecimalBase,0) As PriceDecimalBase, 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());

//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());




$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"];}   

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


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


$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('sa-nextcell');
		MoveNextRecord(NextElement);
		eraseCookie('sa-nextcell');
		
		
		
	});
	
	
</script>

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

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

}


function openhistory(vitemcode){

win = window.open('Form_ItemHistorySales.php?PItem_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 CheckFields(ModuleRestProj, ModuleRestCost, ModuleProj, ModuleCost){
  
    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=='' )
	{
		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,ItemExpire,ModuleExpireDate,AllowMinPrice,ItemMinPrice,MinAllowCostPer,MaxAllowCostPer){
  
    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('deliveryqty['+PIndex+']').value;
	
	
	var SaDtExpireDate = document.getElementById('expiredate['+PIndex+']').value;
	var SaDtBatchNo    = document.getElementById('batchno['+PIndex+']').value;
	
	if(document.getElementById('costprice['+PIndex+']'))
	var ItemCost 	   = document.getElementById('costprice['+PIndex+']').value;
	else ItemCost = '';
	//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 (AvailableQty == '') AvailableQty = 0;
	if (ItemCost == '')     ItemCost = 0;
	//if (ItemPrice == '')    ItemPrice = 0;
	
	SaDtQty      = parseFloat(SaDtQty);	
	AvailableQty = parseFloat(AvailableQty);
	
	var vAllowedPrice  = roundNumber((ItemCost*(1 - parseFloat(MinAllowCostPer/100))),3);
	var vAllowedPrice1 = roundNumber((ItemCost*(1 + parseFloat(MaxAllowCostPer/100))),3);
	
	
	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 > AvailableQty && AvailableQty >= 0) {
		alert('Quantity entered not allowed. Qty must be <= Available Qty ['+AvailableQty+'].');
		document.getElementById('sadtquantity['+PIndex+']').focus();	
		return 0;
	}*/
	else if ((SaDtPrice*1 != SaDtPrice/1 || SaDtPrice < 0) ) {
		alert('Price should be a NUMERIC and POSITIVE value');
		document.getElementById('price['+PIndex+']').focus();
		return 0;
	}
	else if ((SaDtPrice < ItemMinPrice && AllowMinPrice == 0 && ItemMinPrice != 0) ) {
		alert('Price not allowed, minimum price '+ItemMinPrice);
		document.getElementById('price['+PIndex+']').focus();
		return 0;
	}
	else if (SaDtPrice < vAllowedPrice) { 
		alert('Price entered not allowed. Price must not be less than min allowed price  ['+vAllowedPrice+'].');
		document.getElementById('price['+PIndex+']').focus();
		return 0;		
	} 
	else if (SaDtPrice > vAllowedPrice1 && MaxAllowCostPer > 0 && vAllowedPrice1 > 0) { 
		alert('Price entered not allowed. Price must be less than max allowed price  ['+vAllowedPrice1+'].');
		document.getElementById('price['+PIndex+']').focus();
		return 0;		
	} 
	else if ((SaDtDisc != '' && SaDtDisc*1 != SaDtDisc/1) ) {
		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 (confirm ( "Are you sure you want to Clear Page?"))
	{
		ClearForm('All');
		x = document.sales;
		x.mainaction.value='insert';
		x.actionmode.value='';
		x.action='Form_Sales.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_Sales.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 Invoice permenantly?"))
	{
		x.action="Form_Sales_Actions.php?mode=cancel&mainmode=&SSaId="+SaId;
		x.submit();
	}
    
}


function PostChanges(ModuleRestProj, ModuleRestCost, ModuleProj, ModuleCost ) {
	x = document.sales;
	var SaId  = x.txtSaId.value;
	var vMainMode = x.mainaction.value;
	var result = CheckFields(ModuleRestProj, ModuleRestCost, ModuleProj, ModuleCost);
	
	var vSaVatChkbx = 0;
	if (x.chkSaVat.checked)
		vSaVatChkbx = 1;	
	
	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 Invoice?"))
			{
				//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('btnSearchDelivery'))
						x.btnSearchDelivery.disabled = true;	
						
					x.actionmode.value='post';
					x.action="Form_Sales_Actions.php?mode=post&mainmode="+vMainMode+"&SSaId="+SaId+"&SSaVatChkbx="+vSaVatChkbx;
					x.submit();
				}	
			}
		}
	}
	
}


	
function DeleteSaDt(SaDtId, ItemPackCode, ItemCode) {
	x = document.sales;
	var SaId  = x.txtSaId.value;
	var vMainMode = x.mainaction.value;
	var vDelMsg = '';
	
	var vSaVatChkbx = 0;
	if (x.chkSaVat.checked)
		vSaVatChkbx = 1;	
	
	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_Sales_Actions.php?mode=deletedt&mainmode="+vMainMode+"&SSaId="+SaId+"&SSaDtId="+SaDtId+"&SSaVatChkbx="+vSaVatChkbx;
		x.submit();
	}

}

function UpdateSaDt(SaDtId) {
    x = document.sales; 
	var vSaId = x.txtSaId.value;
	var vSaDate = x.txtDate.value;
	var vSaCurr = x.txtCurr.value;
	var vSaClientCode = x.txtClientCode.value;
	var vSaVatChkbx = 0;
	
	if (x.chkSaVat.checked)
		vSaVatChkbx = 1;	
	
	
	var vMainMode = x.mainaction.value;
	
	win = window.open('Form_SalesDetail.php?mainaction='+vMainMode+'&actionmode=&PSaId='+vSaId+'&PSaDate='+vSaDate+'&PSaCurr='+vSaCurr+'&PSaDtId='+SaDtId+'&PSaVatChkbx='+vSaVatChkbx+'&PSaClientCode='+vSaClientCode, 'Form_SalesDetail', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=830,height=320,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.txtVehicleNumber.value='';
		x.txtDriverName.value='';
		
		x.txtVehicleWeight.value='';
		x.txtVehicleLoadWeight.value='';
		x.txtVehicleRealWeight.value='';
		
		
		x.txtSaTaxable.value='';
		x.txtSaNoneTaxable.value='';
		x.txtSaGrossTotal.value='';
		x.txtSaDiscount.value='';
		x.txtSaDiscountAmt.value='';
		x.txtSaVat.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 DeleteRecordGrid(filepath,formname,transid,SaDtId,index,dftorderby,orderby,morelines,startrange,perpage,direction) {
	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);			
					ReloadGridDt(filepath,'SI-TOT','TOTALS','totals',transid,-1);
				}
			}
		}
	   
		xmlhttp.open("GET","Form_Sales_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,ModuleRestProj,ModuleRestCost,ModuleProj,ModuleCost,ModuleExpireDate,AllowMinPrice,MinAllowCostPer,MaxAllowCostPer) {
	
	x = document.sales;
	
	var ItemMinPrice   = document.getElementById('itemminprice['+PIndex+']').value;
	var ItemExpire     = document.getElementById('itemexpire['+PIndex+']').value;
	
	var ItemPromo = 0;
	if (document.getElementById('chkpromo['+PIndex+']'))
	if (document.getElementById('chkpromo['+PIndex+']').checked) ItemPromo = 1;
	
	
	var result = 1;
	result = CheckFields(ModuleRestProj, ModuleRestCost, ModuleProj, ModuleCost);
	
	if (result == 1) {
		result = CheckFieldsDt(PIndex,ItemExpire,ModuleExpireDate,AllowMinPrice,ItemMinPrice,MinAllowCostPer,MaxAllowCostPer);
	}
	
	var SaDtId   = document.getElementById('sadtid['+PIndex+']').value;
	if (SaDtId == '') vMode = 'submitrecord-ajax';	
	else vMode = 'editdt-ajax';	
	
	if(document.getElementById('unit2qty['+PIndex+']'))
		var unit2qty = document.getElementById('unit2qty['+PIndex+']').value;
	else var unit2qty = 0;
	
	if(document.getElementById('sadtdiscount['+PIndex+']'))
		var discountdt = document.getElementById('sadtdiscount['+PIndex+']').value;
	else var discountdt = 0;
	
	if(document.getElementById('batchno['+PIndex+']'))
		var bacthno = document.getElementById('batchno['+PIndex+']').value;
	else var batchno = '';
	
	if(document.getElementById('expiredate['+PIndex+']'))
		var expdate = document.getElementById('expiredate['+PIndex+']').value;
	else var expdate = '';
	
	if(document.getElementById('projectcodedt['+PIndex+']'))
		var proj = document.getElementById('projectcodedt['+PIndex+']').value;
	else var proj = '';
	
	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+
					'&PSaRemark='+encodeURIComponent(x.txtRemark.value)+
					'&PSaIAddress='+encodeURIComponent(x.txtIAddress.value)+
					'&SSaDtId='+document.getElementById('sadtid['+PIndex+']').value+
					'&lstWarehouse='+document.getElementById('warehousecode['+PIndex+']').value+
					'&txtItemCode='+document.getElementById('itemcode['+PIndex+']').value+
					'&txtSaDtRemark='+document.getElementById('remarkdt['+PIndex+']').value+
					'&txtSaDtQty='+document.getElementById('sadtquantity['+PIndex+']').value+
					'&txtSaDtQty2='+unit2qty+
					'&txtSaDtPrice='+document.getElementById('price['+PIndex+']').value+
					'&txtSaDtDiscount='+discountdt+
					'&chkSaDtPromo='+ItemPromo+
					'&txtSaDtBatchNo='+batchno+
					'&txtSaDtExpireDate='+expdate+
					'&txtProjectCodeDt='+proj+
					'&txtCostCentCodeDt='+document.getElementById('costcentcodedt['+PIndex+']').value;
					
			//'&PSaDriverName='+encodeURIComponent(x.txtDriverName.value)+
					//'&PSaVehicleNumber='+encodeURIComponent(x.txtVehicleNumber.value)+
					//'&PSaVehicleWeight='+x.txtVehicleWeight.value+
					//'&PSaVehicleLoadWeight='+x.txtVehicleLoadWeight.value+
					//'&PSaVehicleRealWeight='+x.txtVehicleRealWeight.value+
					//'&PSaManualNo='+encodeURIComponent(x.txtManualNo.value)+
					
	
	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_Sales_Actions.php", true);
		
			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");
						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('sa-nextcell',nextcell);
						
						ReloadGrid(filepath,formname,transid,'datagrid',PIndex,dftorderby,'ADD',orderby,morelines,startrange,perpage,0,direction,function() {
							MoveNextRecord(nextcell);
							ReloadGridDt(filepath,'SI-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_Sales_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_SalesSerialNo.php?SRItemCode='+ItemCode+'&SRItemQty='+SaDtQty+'&SRWhCode='+WhCode+'&SRSaDtId='+SaDtId+'&SRSaId='+SaId, 'Form_SalesSerialNo', 'titlebar=no,toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=no,directories=no, width=550,height=450,left='+YPos+',top='+XPos);		
	//win.creator = self;
	//win.focus();		
	
}

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

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

function SearchConfirmedDelivery(){
	x = document.sales;
	var vSaClient = x.txtClientCode.value;
	var vSaId = x.txtSaId.value;
	
	win = window.open('Form_Sales_LoadDelivery.php?PSaId='+vSaId+'&PSaClientCode='+vSaClient, 'Form_Sales_LoadDelivery', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=970,height=600,top=50,left=50');		
	win.creator = self;
	win.focus();		
	
}

function SetMaturityDate() {

	x = document.sales;
	var vmode = x.mainaction.value;
	
	if(x.txtClientVat.value == 1)
	    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[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;
	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 (VatAmt == '') 		VatAmt = 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);
		
		
		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, 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);
	
	// Calculation of Vat Amount and Net Total
	if (x.chkSaVat.checked) {
		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
	{
		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 vSaVatChkbx = 0;
	if (x.chkSaVat.checked) vSaVatChkbx = 1;
	
	if (SaId != '') {
		x.action="Form_Sales_Actions.php?mode=changecurrency&SSaId="+SaId+"&SSaVatChkbx="+vSaVatChkbx;
		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 = 0;
	if (x.chkSaVat.checked) vVatChkbx = 1;
	
	if (vSaId != '') {
		x.action="Form_Sales_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) {
	var str = '';
	var vLetterHead = 0;
	
	if (confirm ( "Do you want to Print current Invoice with reference "+SaRef+" ?"))
	{
		if (confirm ( "Do you want to print with Letter Head?") )
		{
			vLetterHead = 1;
		}
		
		str = 'Form_SalesPreview.php?SalesId='+SaId+'&LetterHead='+vLetterHead;
		window.open(str);
	}	
	
	
}

function PrintSalesReceipt(SaId, SaRef) {
	var str = '';
	
	if (confirm ( "Do you want to Print Invoice Receipt ?"))
	{
		str = 'Form_SalesReceiptPreview.php?SalesId='+SaId;
		window.open(str);
	}	
	
	
}

function PrintSalesWaybill(SaId, SaRef) {
	var str = '';
	
	if (confirm ( "Do you want to Print current Invoice with reference "+SaRef+" ?"))
	{
		str = 'Form_SalesWaybillPreview.php?SalesId='+SaId;
		window.open(str);
	}	
	
	
}

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_Sales_PayCash.php?PSaId='+vSaId,'Form_Sales_PayCash','width=400,height=280,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_Sales_Actions.php?mode=CreditPayment&SSaId="+vSaId;
	x.submit();
}

function showlistClient(str){
	var vdate, vcode;
	vdate=document.sales.txtDate.value;
	vcode=encodeURIComponent(document.sales.txtClientCode.value);
  
	window.open('List_SorClient.php?frm=3&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 showlistClientName(str) {
	var vdate, vcode;
	vdate=document.sales.txtDate.value;
	vname=encodeURIComponent(document.sales.txtClientName.value);
  
	window.open('List_SorClient.php?frm=3&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=3&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=3&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=3&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);
  
	window.open('List_SorItems.php?frm=7&index='+PIndex+'&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 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;
}


</script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Invoice</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='sales' method='post' action=''>
<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'>
HERE;

//$message='';

	
//Initializations

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


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 Sale_ID, Sale_Reference, Date_Format(Sale_Date,'%d/%m/%Y') As Sale_Date, ".
	         " Date_Format(JournalDt_ValueDate,'%d/%m/%Y') As MaturityDate, ".
			 " Sales.Client_code As ClientCode, Clients.Ledger_name As ClientName, Client_VAT,   ".
			 " Sales.Salesman_code As SalesmanCode, Salesmen.Ledger_name As SalesmanName, ".
			 " Sales.Currency_code, Client_Address, Sale_ShippedTo, Sale_Marks, Sale_ShippedVia, ".
			 " Sale_Remark, Sales.Project_Code, Sales.Costcenter_code,  ".
			 " Round(ifNull(Sale_Taxable,0), ".$DecimalBase."), Round(ifNull(Sale_NoneTaxable,0), ".$DecimalBase."), ".
			 " Round(ifNull(Sale_Total,0), ".$DecimalBase.") As GrossTotal, ".
			 " Round(ifNull(Sale_DiscountPer,0), ".$DecimalBase."), Round(ifNull(Sale_DiscountAmount,0), ".$DecimalBase."),  ".
			 " Round(ifNull(Sale_VAT,0), ".$DecimalBase.") As Sale_VAT, ".
			 " Round((ifNull(Sale_Total,0) + IfNull(Sale_VAT,0) + IfNull(Sale_TransportAmount,0) + IfNull(Sale_BonusAmount,0) - IfNull(Sale_DiscountAmount,0) + (ifNull(Sale_Tax1,0) + ifNull(Sale_Tax2,0) + ifNull(Sale_Tax3,0) + ifNull(Sale_Tax4,0) + ifNull(Sale_Tax5,0))), ".$DecimalBase.") As Sale_NetTotal,  ".
			 " ifNull(sale_chkvat,0) As Sale_VatChckbx, Sorder_reference, ".
			 " Round((ifNull(Sale_Tax1,0) + ifNull(Sale_Tax2,0) + ifNull(Sale_Tax3,0) + ifNull(Sale_Tax4,0) + ifNull(Sale_Tax5,0)), ".$DecimalBase.") As TotalTaxes,  ".
			 " Journal.Journal_folio, Journal.Journal_refgovernment, Round(ifNull(Sale_DiscountTTC,0), ".$DecimalBase."),  ".
			 " Round((ifNull(Sale_TaxableTTC,0) + IfNull(Sale_NoneTaxable,0) + IfNull(Sale_TransportTTC,0) + IfNull(Sale_BonusTTC,0) - IfNull(Sale_DiscountTTC,0) + (ifNull(Sale_Tax1,0) + ifNull(Sale_Tax2,0) + ifNull(Sale_Tax3,0) + ifNull(Sale_Tax4,0) + ifNull(Sale_Tax5,0))), ".$DecimalBase.") As Sale_NetTotalTTC,  ".
			 " Round(ifNull(Sale_TransportAmount,0), ".$DecimalBase.") As TransportAmt, Round(ifNull(Sale_TransportTTC,0), ".$DecimalBase.") As TransportAmtTTC,  ".
			 " Round(ifNull(Sale_BonusAmount,0), ".$DecimalBase.") As BonusAmt, Round(ifNull(Sale_BonusTTC,0), ".$DecimalBase.") As BonusAmtTTC,  ".
			 " Round(ifNull(Sale_TaxableTTC,0), ".$DecimalBase."), Round(ifNull(Sale_TaxableTTC,0) + ifNull(Sale_NoneTaxable,0), ".$DecimalBase.") As GrossTotalTTC, ".
			 " Sale_ManualNo , ifNull(Sale_vehicleweight,0), ifNull(Sale_vehicleLoadweight,0), ifNull(Sale_vehicleRealweight,0), ifNull(Sale_Mode,0) ".
			 " From Temp_Sales As Sales ".
			 " Left Join Clients on Sales.Client_code = Clients.Ledger_Number ".
			 " Left Join Salesmen on Sales.Salesman_code = Salesmen.Ledger_Number ".
			 " Left Join Journal on Sales.Journal_ID = Journal.Journal_ID ".
	         " Where Sale_ID = ".$txtSaId;
			 //" And Logged_Code = '".$HTTP_SESSION_VARS['useraccount']."' ";
			 
			 
	//echo $query;
	$result=mysql_query($query,$connection) or die(mysql_error());
    $rows=mysql_fetch_array($result);
	
	$txtSaId  = $rows[0];
	$txtRef   = $rows[1];
	$txtDate  = $rows[2];
	$txtMaturityDate = $rows[3];
	
	if (empty($txtClientCode)) {
		$txtClientCode   = $rows[4];
		$txtClientName   = $rows[5];
		$txtClientVat    = $rows[6];
	}
	if (empty($txtSalesmanCode)) {
		$txtSalesmanCode = $rows[7];
		$txtSalesmanName = $rows[8];
	}	
	$txtCurr         = $rows[9];
	$txtIAddress     = $rows[11];
	$txtVehicleNumber  = $rows[12];
	$txtDriverName     = $rows[13];
	$txtRemark         = $rows[14];
	$txtProjectCode    = $rows[15];
	$txtCostCentCode   = $rows[16];
	$txtManualNo 	   = $rows[37];
	
	$txtVehicleWeight 	   = $rows[38];
	$txtVehicleLoadWeight  = $rows[39];
	$txtVehicleRealWeight  = $rows[40];
	
	
	//$txtSaTaxable     = $rows[17];
	
	if ($SalesTTC == 1) $txtSaTaxable = $rows[35]; else $txtSaTaxable = $rows[17];
	$txtSaNoneTaxable = $rows[18];
	//$txtSaGrossTotal  = $rows[19];
	if ($SalesTTC == 1) $txtSaGrossTotal = $rows[36]; else $txtSaGrossTotal = $rows[19];
	$txtSaDiscount    = $rows[20];
	if ($SalesTTC == 1) $txtSaDiscountAmt = $rows[29]; else $txtSaDiscountAmt = $rows[21];
	$txtSaVat         = $rows[22];
	if ($SalesTTC == 1) $txtSaNetTotal    = $rows[30]; else $txtSaNetTotal    = $rows[23];
	$chkSaVat         = $rows[24];
	if ($SalesTTC == 1) $txtSaTransportAmt = $rows[32]; else $txtSaTransportAmt = $rows[31];
	if ($SalesTTC == 1) $txtSaBonusAmt = $rows[34]; else $txtSaBonusAmt = $rows[33];
	$txtSaTotalTaxes  = $rows[26];
	
	
	$txtSorderRef     = $rows[25];
	$txtJvFolio	      = $rows[27];
	$txtJvRef 	      = $rows[28];
	
	$txtSaleMode	  = $rows[41];
	
	
	$query = " Select Count(*) FROM Temp_SalesDt ".
			 " WHERE Sale_id = ".$txtSaId;
	$result = selectData($connection, $query);
	$txtSaCountDetail = $result[0];
	if($txtSaCountDetail == '') $txtSaCountDetail = 0;
	
	//echo $txtSaCountDetail;
}






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

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'>
			<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'>SALES</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='420px' align='left'>";

echo" <button type='button' id='btnClear' name='btnClear' onclick='ClearPage();return false;' title='Clear Page'><span><span>Clear Page</span></span></button>";
	
if ($txtSaId != '')
	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);return false;' title='Save Changes'><span><span>Save</span></span></button>";

if ($txtSaId == '')
	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 Productions'><span><span>Pending</span></span></button>";

echo" 		<button type='button' id='btnSearchDelivery' name='btnSearchDelivery' onclick='SearchConfirmedDelivery();return false;' title='Search Confirmed Delivery'><span><span>Load Delivery</span></span></button>";

echo"	</td>";
echo"	<td valign='middle' height='34' width='300px' align='left'>";

if ($txtSaId != '') {
	echo" <button type='button' id='btnCash' name='btnCash' onclick='PayCash();return false;' title='Pay Cash'><span><span>Cash</span></span></button>";
	
	if (($Module_DeliveryWithSorder == 0) || ($Module_DeliveryWithSorder == 1 && $txtSaleMode != 1)){
		echo" <button type='button' id='btnCredit' name='btnCredit' onclick='PayCredit();return false;' title='Pay Credit'><span><span>Credit</span></span></button>";
	}	
}	
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'>";	

   
print <<<HERE
		
		<table border="0" style='table-layout:fixed'>
		  <col width=90>
		  <col width=80>
		  <col width=80>
		  <col width=90>
		  <col width=100>
		  <col width=150>
		  <col width=100>
		  <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>
			<input type='hidden' name='txtJvFolio' value='$txtJvFolio' >
			<input type='hidden' name='txtJvRef' value='$txtJvRef' >
			<input type='hidden' name='txtSorderRef' value='$txtSorderRef' >
		  </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 align='left' 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();' 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, Client_PaymentTerms, Clients.Salesmen_Code, Salesmen.Ledger_name As Salesmen_Name, Clients.Currency_Code, ".
			 " Clients.Project_Code, Clients.CostCenter_Code, Salesmen.Salesman_WarehouseCode ".
	         " FROM Clients Left Outer Join Salesmen on Clients.Salesmen_Code = Salesmen.Ledger_number WHERE Clients.Ledger_Number = '".$txtClientCode."'";
	$result = selectData($connection, $query);

	$txtCreditLimit = $result[0];
	$txtCltCurrCode = $result[5];
	$txtPaymentTerms = $result[2];
	
	if ($txtSalesmanCode == "") {
		$txtSalesmanCode = $result[3];
		$txtSalesmanName = $result[4];
	}
	
	if ($Module_Project == 1 && $Client_ValidateProject == 1)
		$txtProjectCode = $result[6];
	if ($Module_CostCenter == 1 && $Client_ValidateProject == 1)	
		$txtCostCentCode = $result[7];	
			
	if ($txtSaId == "") {
		if ($txtCurr != $txtCltCurrCode) $txtCurr = $result[5];	
		if ($result[8] != '') $SetupDftWareHouse = $result[8];
	}
	
	$query = "SELECT ifNull(convertcurfunc('".$txtCltCurrCode."', '".$txtCurr."', '".insertMySQLDate($txtDate)."', 0, 0, '', '', ifNull($txtCreditLimit,0)),0) From Dual ";
	$result = selectData($connection, $query);
	$txtCreditLimit = $result[0];

	//Get Current Balance
	$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>".$sub_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_SalesWithPrice']     = $FI_SalesWithPrice;
$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['Allow_MinimumPrice'] = $Allow_MinimumPrice;
$Parameters['SalesTTC'] = $SalesTTC;
$Parameters['DecimalBase'] = $DecimalBase;
$Parameters['PriceDecimalBase'] = $PriceDecimalBase;
$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;

$_SESSION['gsa_parameters']  = $Parameters;

/*
	echo"<td rowspan='8' valign='top' ><table border='0' style='table-layout:fixed'>
			<col width=110>
			<col width=150>
			
			<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 name='chkSaVat' type='checkbox' id='chkSaVat' value='1' onClick='SetSaVat($DecimalBase,$VatApplied,$Setup_VatPercentage,$SalesTTC);'   "; 
			  if($txtSaId != "" && $chkSaVat==1 ) echo "checked $AllowModifyVAT />"; 
			  else if($txtSaId == "" && $txtClientVat==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='25'>
			 <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>";

*/

$TotalStyle = '';
//$FI_SalesWithPrice=1;
if ($FI_SalesWithPrice != 1) $TotalStyle = 'display:none;';

echo"	  <td rowspan='8' valign='top'>";
echo"		<div id='totals' style='width:270px; margin-top:3px; float:right; $TotalStyle' >";
		ShowSalesTotals($connection,$txtSaId,$_SESSION['gsa_parameters'],$_SESSION['gsa_arrayaccess']);
echo"		</div>"; 
echo"	  </td>
		</tr>";


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

	if (($txtSaId == "") || ($Module_ChangeInvoiceClient == 1 && $FI_ChangeInvoiceClient == 1)) {
	    echo"<label>
			  <input type='text'   name='txtClientCode' id='txtClientCode' value='$txtClientCode' onBlur='SetMaturityDate();'  style='width:95px;' maxlength='10' onchange=\"CheckLookup('chkcodeexists','clients','ledger_number',this.value,'lstClientCodeH'); \" />
			  <input type='text'   name='txtClientName' id='txtClientName' value='$txtClientName' style='width:285px;' onchange=\"CheckLookup('chkcodeexists','clients','ledger_name',this.value,'lstClientNameH');\" />
			  <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>";	  
	} else {
		echo"<label>
			  <input type='text'   name='txtClientCode' id='txtClientCode' value='$txtClientCode' style='width:95px;' maxlength='10'  readonly/>
			  <input type='text'   name='txtClientName' id='txtClientName' value='$txtClientName' style='width:285px;' readonly />
			  <input type='hidden' name='txtClientVat' id='txtClientVat' value='$txtClientVat' />
			</label>
           </span> ";
	}	


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



echo"   <tr bgcolor='#F7F7F7'  height='25'>
		  <td align='left' ><span class='style1'>Salesman</span></td>";
echo"     <td colspan='5' ><span class='style1'>";

	//if ($txtSaId == "") {
		echo"<label>
				<input type='text'   name='txtSalesmanCode' id='txtSalesmanCode' value='$txtSalesmanCode' style='width:95px;' maxlength='10'  />
				<input type='text'   name='txtSalesmanName' id='txtSalesmanName' value='$txtSalesmanName' style='width:285px;'  />
			</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>";
	/*} else {
		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>";
	}*/

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>";	
		
          
echo"   </tr>";


echo"   <tr bgcolor='#F7F7F7'  height='25'>
		  <td align='left' valign='center'><span class='style1'>Remark</span></td><td colspan='5' > <span class='style1'>
		  <input type='text' name='txtRemark' value='".htmlspecialchars($txtRemark, ENT_QUOTES)."'  style='width:385px;' maxlength='200' ></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='5' > <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>";		  

if($Module_VehicleWeight==1) {
echo"   <tr bgcolor='#F7F7F7'  height='25'>";
 
echo"     <td align='left' valign='center'><span class='style1'>Vehicle Weight</span></td>
		  <td  colspan='5'><input type='text' name='txtVehicleWeight' readonly value='".htmlspecialchars($txtVehicleWeight, ENT_QUOTES)."'  style='width:60px;' maxlength='30' ></span>";

		  
echo"     <span class='style1'>&nbsp;Total Weight</span>
		  <input type='text' name='txtRealQty' value='".htmlspecialchars($txtRealQty, ENT_QUOTES)."'  style='width:60px;' maxlength='30' ></span>";

echo"     <span class='style1'>&nbsp;Loaded Weight</span>";
echo"     &nbsp;<input type='text' name='txtVehicleLoadWeight' value='".htmlspecialchars($txtVehicleLoadWeight, ENT_QUOTES)."'  style='width:60px;' maxlength='30' ></span></td>";
echo "    <td><span class='style1'>Real Weight</span></td>";
echo"<td>";
echo"     <input type='text' name='txtVehicleRealWeight' value='".htmlspecialchars($txtVehicleRealWeight, ENT_QUOTES)."'  style='width:90px;' maxlength='30' ></span></td>";
echo"</td>";
echo"   </tr>";	
}
else {
echo"	<input type='hidden' name='txtVehicleWeight' readonly value='".htmlspecialchars($txtVehicleWeight, ENT_QUOTES)."'  style='width:60px;' maxlength='30' ></span>
		<input type='hidden' name='txtRealQty' value='".htmlspecialchars($txtRealQty, ENT_QUOTES)."'  style='width:60px;' maxlength='30' >
		<input type='hidden' name='txtVehicleLoadWeight' value='".htmlspecialchars($txtVehicleLoadWeight, ENT_QUOTES)."'  style='width:60px;' maxlength='30' >
		<input type='hidden' name='txtVehicleRealWeight' value='".htmlspecialchars($txtVehicleRealWeight, ENT_QUOTES)."'  style='width:90px;' maxlength='30' >
		";
}


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

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='15' 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='2'><span class='style1'>
		    <input type='text' name='txtCostCentCode' id='txtCostCentCode' value='$txtCostCentCode' style='width:129px;' maxlength='15' 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='3'><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>";
echo"   </tr>";
echo"   <tr bgcolor='#F7F7F7'>
		   <td align='left'><span class='style1'>Invoice Address</span></td>
		   <td align='left' colspan='7'><textarea name='txtIAddress' rows='4' cols='45' style='width:385px;'>".htmlspecialchars($txtIAddress, ENT_QUOTES)."</textarea></td>
		</td></tr>";

		  
/*
echo"   <tr><td colspan='9' 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_DoubleUnit == 1) {		  
	echo" <col width=120>
		  <col width=120>
		  <col width=200>
		  <col width=70>
		  <col width=60>
		  <col width=70>
		  <col width=60>
		  <col width=70>
		  <col width=60>
		  <col width=70>
		  <col width=50>
		  <col width=90>
		  <col width=60>
		  <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 {
	echo" <col width=120>
		  <col width=120>
		  <col width=200>
		  <col width=70>
		  <col width=60>
		  <col width=70>
		  <col width=60>
		  <col width=70>
		  <col width=50>
		  <col width=90>
		  <col width=60>
		  <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>";
	}	
}
		  
		  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'>Delivery Ref</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'>Unit1</span></td>";
			
		  echo"  <td bgcolor='#F7F7F7' align='center'><span class='style27'>Invoice 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>";
  		  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>';
			
			$querydt = " Select SalesDt.SaleDt_id, SalesDt.Item_CodePacked, SalesDt.Item_code, Item_Description, SalesDt.Warehouse_Code, ".
					   " SalesDt_Remark, SaleDt_Quantity, Round(SalesDt.SaleDt_Price, ".$DecimalBase."), SalesDt.SaleDt_PriceBase1, SalesDt.SaleDt_PriceBase2, ".
					   " Round(SaleDt_DiscountPer, ".$DecimalBase."),  ".
					   " Round(((SaleDt_Quantity*SalesDt.SaleDt_Price)-((SaleDt_Quantity*SalesDt.SaleDt_Price*ifNull(SaleDt_DiscountPer,0))/100)), ".$DecimalBase.") As Total, ".
					   " Round(SaleDt_PriceTTC, ".$DecimalBase."), ".
					   " Round(((SaleDt_Quantity*SaleDt_PriceTTC)-((SaleDt_Quantity*SaleDt_PriceTTC*ifNull(SaleDt_DiscountPer,0))/100)), ".$DecimalBase.") As TotalTTC, ".
					   " DeliveryDt.DeliveryDt_Quantity, ifNull(item_withserialno,0) As ItemWithSerialNo, Deliveries.Delivery_reference, Count(SerialNo_Code) As CountSerialNo,  ".
					   " DeliveryDt.DeliveryDt_ID, SalesDt.Item_Unit2Qty, Item_UnitPurchaseDesc, Item_UnitSalesDesc, ".
					   " Date_Format(SaleDt_ExpireDate,'%d/%m/%Y') As SaleDt_ExpireDate, SaleDt_BatchNo, SalesDt.Project_code, SalesDt.CostCenter_Code ".
					   " From Temp_SalesDt As SalesDt Left Join Items on SalesDt.Item_code = Items.Item_code ".
					   " Left Join Temp_Purchasesserialno on SalesDt.SaleDt_ID = Temp_Purchasesserialno.PurchaseDt_ID ".
					   " And Temp_Purchasesserialno.Journal_Type = 'SI' ".
					   " Left Join DeliveryDt on DeliveryDt.DeliveryDt_ID = SalesDt.RelatedDt_Id  ".
					   " Left Join Deliveries on Deliveries.Delivery_ID = DeliveryDt.Delivery_ID  ".
					   " Where SalesDt.Sale_ID = ".$txtSaId.
					   " Group By  SalesDt.SaleDt_id ".
					   " Order By SalesDt.SaleDt_id Desc ";
			//echo $querydt;
			$resultdt=mysql_query($querydt,$connection) or die(mysql_error());
			while($rowsdt=mysql_fetch_array($resultdt)){
			
				$sub_query = " Select Sum(Q1.QtySold) As QtySold From ".
							 " ( Select ifNull(Sum(ifNull(SaleDt_Quantity,0)), 0) As QtySold ".
							 "   From SalesDt ".
							 "   Where SalesDt.RelatedDt_Id = '".$rowsdt[18]."' ".
							 "   And SalesDt.SaleDt_id != '".$rowsdt[0]."' ".
							 "   Union ".
							 "   Select ifNull(Sum(ifNull(SaleDt_Quantity,0)), 0) As QtySold ".
							 "   From Temp_SalesDt ".
							 "   Where Temp_SalesDt.RelatedDt_Id = '".$rowsdt[18]."' ".
							 "   And Temp_SalesDt.SaleDt_id != '".$rowsdt[0]."' ".
							 " ) As Q1 ";
	
				$sub_result = selectData($connection, $sub_query);	
				if ($sub_result[0] == '') $sub_result[0] = 0;

				$vDeliveryRemainQty = $rowsdt[14] - $sub_result[0];
			    
				$ct+=1;

				if($ct%2==0)
					$Color="style='background-color:".$grid_color1."'";
				else			
					$Color="style='background-color:".$grid_color2."'";	
						
				
				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])."',$rowsdt[14],'".$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]."') 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])."')\" 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'>".$vDeliveryRemainQty."</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[21]."</span></td>";
					
				// if Total Quantity Differs From Total SerialNos And
				// If ItemWithSerialNo True And ModuleSerialNo True	
				if (($rowsdt[6] != $rowsdt[17] && $rowsdt[15] != 0 && $Module_SerialNo == 1) || ($rowsdt[6] == 0 && $rowsdt[15] != 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[20]."</span></td>";	
					echo "	<td align='right'><span class='style15'>".$rowsdt[19]."</span></td>";	
				}
				
				echo "	<td align='right'><span class='style15'>".$rowsdt[17]."</span></td>";	
				
				//echo "	<td align='right'><span class='style15'>".$rowsdt[17]."</span></td>";	
				
				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[24]."</span></td>";
				if ($Module_CostCenterDt == 1)
					echo "	<td align='left'><span class='style15'>".$rowsdt[25]."</span></td>";
				if ($Module_ExpireDate == 1) {
					echo "	<td align='left'><span class='style15'>".$rowsdt[23]."</span></td>";
					echo "	<td align='left'><span class='style15'>".$rowsdt[22]."</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><td colspan='9' valign='top'>";
echo"	<div id='datagrid' class='grid' style='width:1090px;' >";

//Show Items Grid
ShowSalesDtGrid($connection,'SI',$txtSaId,$_SESSION['gsa_parameters'],$_SESSION['gsa_arrayaccess'],'SalesDt.SaleDt_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>  ";//end of last table menu
	
if ($actionmode == "post"  && $PrSaId != '') {
	echo '<script type="text/javascript" language="javascript">';
	
	if ($Login_FastPrint == 1) {
		$sub_query = " Select ifNull(Sale_PrintReceipt,0) From Sales Where Sale_Id = '".$PrSaId."'";
		$sub_result = selectData($connection, $sub_query);
		$PrintReceipt = $sub_result[0];
		
	   //if ($FI_SalesWithPrice == 1)
		echo ' PrintSales(\''.$PrSaId.'\', \''.$PrSaRef.'\'); ';
		
		if ($Module_PrintWaybill == 1) {
			echo ' PrintSalesWaybill(\''.$PrSaId.'\', \''.$PrSaRef.'\'); ';
		}

		if ($PrintReceipt == 1) {
			echo ' PrintSalesReceipt(\''.$PrSaId.'\', \''.$PrSaRef.'\'); ';
		}
	}
	
	echo ' ClearPage1(); ';
	echo '</script>';

}

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

HERE;

?>