<?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, ".	
			 " ifNull(module_saleswht,0) As module_saleswht ".	
             " 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,showGRNNo  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;
	
	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 (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 - (SaDtDisc*SaDtPrice/100))< ItemMinPrice && AllowMinPrice == 0 && ItemMinPrice != 0) ) {
		alert('Price not allowed, minimum price '+ItemMinPrice);
		document.getElementById('price['+PIndex+']').focus();
		return 0;
	}
	else if ((SaDtPrice - (SaDtDisc*SaDtPrice/100)) < 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 - (SaDtDisc*SaDtPrice/100)) > 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;	
	
	var vSaWHTChkbx = 0;
	if (x.chkSaWHT)
		if (x.chkSaWHT.checked)
		vSaWHTChkbx = 1;	
	
	var vSaWHTPer;
	vSaWHTPer = x.txtSaWHTPer.value;
	
	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+"&SaWHTChkbx="+vSaWHTChkbx+"&SaWHTPer="+vSaWHTPer;
					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;	
	
	var txtSaWHTChk = x.txtSaWHTChk.value;
	var txtSaWHTPer = x.txtSaWHTPer.value;
	
	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+'&SaWHTChk='+txtSaWHTChk+'&SaWHTPer='+txtSaWHTPer;
		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?';
	
	var txtSaWHTChk = x.txtSaWHTChk.value;
	var txtSaWHTPer = x.txtSaWHTPer.value;
	
	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
					+"&SaWHTChk="+txtSaWHTChk+"&SaWHTPer="+txtSaWHTPer);
		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+']').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';	
	
	var txtSaWHTChk = x.txtSaWHTChk.value;
	var txtSaWHT = x.txtSaWHT.value;
	var txtSaWHTPer = x.txtSaWHTPer.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+
					'&PSaVehicleRealWeight='+x.txtVehicleRealWeight.value+
					'&PSaManualNo='+encodeURIComponent(x.txtManualNo.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='+document.getElementById('unit2qty['+PIndex+']').value+
					'&txtSaDtPrice='+document.getElementById('price['+PIndex+']').value+
					'&txtSaDtDiscount='+document.getElementById('sadtdiscount['+PIndex+']').value+
					'&chkSaDtPromo='+ItemPromo+'&SaWHTChk='+txtSaWHTChk+'&SaWHT='+txtSaWHT+'&SaWHTPer='+txtSaWHTPer+
					'&txtSaDtBatchNo='+document.getElementById('batchno['+PIndex+']').value+
					'&txtSaDtExpireDate='+document.getElementById('expiredate['+PIndex+']').value+
					'&txtProjectCodeDt='+document.getElementById('projectcodedt['+PIndex+']').value+
					'&txtCostCentCodeDt='+document.getElementById('costcentcodedt['+PIndex+']').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,Module_Delivery, 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;
	var vSaWHTChkbx  = 0;
	var vSaWHTPer  = 0;
	
	if (x.chkSaVat.checked) vSaVatChkbx = 1;
	if (x.chkSaWHT.checked) vSaWHTChkbx = 1;
	var vSaWHTPer = x.txtSaWHTPer.value;
	
	if (SaId != '') {
		x.action="Form_Sales_Actions.php?mode=changecurrency&SSaId="+SaId+"&SSaVatChkbx="+vSaVatChkbx+"&SaWHTChkbx="+vSaWHTChkbx+"&SaWHTPer="+vSaWHTPer;
		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 vSaWHTChkbx = 0;
	vSaWHTPer = 0;
	var vVatChkbx = 0;
	
	if (x.chkSaVat.checked) vVatChkbx = 1;
	
	if (x.chkSaWHT.checked) vSaWHTChkbx = 1;
	var vSaWHTPer = x.txtSaWHTPer.value;
	
	if (vSaId != '') {
		x.action="Form_Sales_Actions.php?mode=changediscount&SSaId="+vSaId+"&SSaVatChkbx="+vVatChkbx+"&txtSaDiscountAmt="+vDisAmt+"&txtSaDiscount="+vDisPer+"&SaWHTChkbx="+vSaWHTChkbx+"&SaWHTPer="+vSaWHTPer;
		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_SalesPreview.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);
	vWarehouseCode = encodeURIComponent(document.getElementById('warehousecode['+PIndex+']').value);
	
	window.open('List_BatchNo.php?frm=10&index='+PIndex+'&PItem_Code='+vItemCode+'&PWarehouseCode='+vWarehouseCode,'List_BatchNo','width=580,height=400,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes,left='+YPos+',top='+XPos);
}
function showlistItems(str,PIndex){
	var vDate, vItemCode;
	x = document.sales;
	
	XPos = (screen.availHeight - 400) / 2;
	YPos = (screen.availWidth - 850) / 2;
  
	vDate 	   = x.txtDate.value;
	vItemCode  = encodeURIComponent(document.getElementById('itemcode['+PIndex+']').value);
  
	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;
}

function SetSaWHT(DecimalBase,SaWHTPer){
	var x = document.sales;
	var vat;
	var grosstot = x.txtSaGrossTotal.value;
	if(x.chkSaVat.checked)
	vat = x.txtSaVat.value;
	else vat = 0;
	
	if(document.getElementById("chkSaWHT").checked){
		x.txtSaWHTChk.value=1;
		x.txtSaWHT.value = roundNumber(SaWHTPer*(grosstot-vat)/100,DecimalBase);
	} else {
		x.txtSaWHTChk.value=0;
		x.txtSaWHT.value = 0;
	}
	
}
</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 >

<form name='dfs' >
<input type='text'  tabindex='1'>
<input type='text'  tabindex='2'>

</form>
HERE;


?>


<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>
$(document).on('keypress', 'input,select', function (e) {
    if (e.which == 13) {
        e.preventDefault();
        var $next = $('[tabIndex=' + (+this.tabIndex + 1) + ']');
        console.log($next.length);
        if (!$next.length) {
            $next = $('[tabIndex=1]');
        }
        $next.focus();
    }
    });
</script>