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

   include("config.inc.php");
   include("Functions_Trans.php");
   include("Forms_DataGridSalesOrderJV.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 FA_SalesOrderJv as loginaccess, FA_SalesJvVAT, ifNull(FA_SalesOrderJVDel,0) As FA_SalesOrderJVDel, ifNull(FA_SalesOrderJVMod,0) As FA_SalesOrderJVMod, ".
			" ifNull(FA_SalesOrderJVApp,0) As FA_SalesOrderJVApp, ifNull(ModifyVAT,0) As ModifyVAT, ifNull(Login_ModifyDiscount,0) As Login_ModifyDiscount, ifNull(FI_SalesCheckSalesman,0) As FI_SalesCheckSalesman, ".
			" ifNull(Login_FastPrint,0) As Login_FastPrint, ifNull(Login_ModifySellingPrice,0) As Login_ModifySellingPrice ".
			" from ".$_SESSION['dbLabel'].".login where user_account='".$_SESSION['useraccount']."' and Upper(Login_Schema) = Upper('".$_SESSION['dbName']."')  ";

   $resultlog=mysql_query($querylog,$connection) or die(mysql_error());

   while($rows=mysql_fetch_array($resultlog)){
   	extract($rows);
   }
   
   if ($loginaccess=='' or $loginaccess==0)
   	header("location:menu.php");

   $querycostcent=" select costcent_applyvat ".
                  " from costcent left join ".$_SESSION['dbLabel'].".loginstk on costcent.costcent_code like concat(loginstk.costcent_code,'%') ".
    			   " where user_account='".$_SESSION['useraccount']."' ".
    			   "";

   $costcentres = mysql_query($querycostcent,$connection) or die(mysql_error());
   $rows=mysql_fetch_array($costcentres);
   $costcent_applyvat = $rows[0];
   if($costcent_applyvat=='')	$costcent_applyvat = 1;

   //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_Project,0) As Module_Project, ifNull(Module_Costcenter,0) As Module_CostCenter, ".
   			 " ifNull(Module_ProjectDt,0) As Module_ProjectDt, ifNull(Module_CostCenterDt,0) As Module_CostCenterDt, ".
   			 " ifNull(Module_RestrictProjCost,0) As Module_RestrictProjCost, ifNull(Module_RestrictCost,0) As Module_RestrictCost ".
                " 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 ClientCur, VATAccountNonStock,CashCur,CashCur2 ,ifnull(salesjv_paymentmode,0) as salesjv_paymentmode From SalesSetup";
   $resultSalesSetup=mysql_query($querySalesSetup,$connection) or die(mysql_error());
   while($rowSalesSetup=mysql_fetch_array($resultSalesSetup)){
   	extract($rowSalesSetup);
   }

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

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

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

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

   $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/tabs.css">

   <link rel="stylesheet" type="text/css" media="all" href="css-v2/style.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" src="dropdown.js"></script>
  		
HERE;
 
Print <<<HERE


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

   function clearsalesjvdt(vrec){

   var txtLedgerNo = 'txtLedgerNo['+vrec+']';
   var txtLedgerName = 'txtLedgerName['+vrec+']';
   var txtDescription1 = 'txtDescription1['+vrec+']';
   var txtDescription2 = 'txtDescription2['+vrec+']';
   var txtDtCurr = 'txtDtCurr['+vrec+']';
   var txtDtQty = 'txtDtQty['+vrec+']';
   var txtDtPrice = 'txtDtPrice['+vrec+']';
   var txtDtDiscPer = 'txtDtDiscPer['+vrec+']';
   var txtDtTotal = 'txtDtTotal['+vrec+']';
   var txtDtVat = 'txtDtVat['+vrec+']';
   var txtDtManualNo = 'txtDtManualNo['+vrec+']';

    document.getElementById(txtLedgerNo).value = '';
    document.getElementById(txtLedgerName).value = '';
    document.getElementById(txtDescription1).value = '';
    document.getElementById(txtDescription2).value = '';
    document.getElementById(txtDtCurr).value = '';
    document.getElementById(txtDtQty).value = '';
    document.getElementById(txtDtPrice).value = '';
    document.getElementById(txtDtDiscPer).value = '';
    document.getElementById(txtDtTotal).value = '';
    document.getElementById(txtDtVat).value = '';
    document.getElementById(txtDtManualNo).value = '';

   }

   function showsearchpage(vtype,vtext1,vtext2,vtext3,vtext4,vwidth,vheight){
   	var text1value = document.getElementById(vtext1).value;

   	win = window.open('List_AccountNo.php?PLedger_Number='+text1value+'&item=2&vtype='+vtype+'&vtext1='+vtext1+'&vtext2='+vtext2+'&vtext3='+vtext3+'&vtext4='+vtext4+'&text1value='+text1value, 'Search', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width='+vwidth+',height='+vheight+',top=100,left=100');		
   	win.creator = self;
   	win.focus();	
   	}

   function showsearchpage1(vtype,vtext1,vtext2,vtext3,vtext4,vtext5,vtext6,vwidth,vheight){

   		var text2value = document.getElementById(vtext2).value;

   	win = window.open('List_AccountNo.php?PLedger_Name='+text2value+'&item=2&vtype='+vtype+'&vtext1='+vtext1+'&vtext2='+vtext2+'&text1value='+text2value, 'Search', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width='+vwidth+',height='+vheight+',top=100,left=100');		
   	win.creator = self;
   	win.focus();
   	}

   function setaccountno(val,vfield1,vfield2,vgridname,btnname,btnname1,codedesc){

   if (window.XMLHttpRequest)
     {// code for IE7+, Firefox, Chrome, Opera, Safari
     xmlhttp=new XMLHttpRequest();
     }
   else
     {// code for IE6, IE5
     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
     }
   xmlhttp.onreadystatechange=function()
     {
     if (xmlhttp.readyState==4 && xmlhttp.status==200)
       {
   				{ 	
   					var data = xmlhttp.responseText.split("[BRK]");
   					var resp = data[1];
   					if (resp==0)
   						{
   							if (codedesc==1)
   								document.getElementById(btnname).click();
   							else	
   								document.getElementById(btnname1).click();
   						}
   						else	{							
   								if (codedesc==1)
   									document.getElementById(vfield2).value = resp;
   								else	
   									document.getElementById(vfield1).value = resp;
   								}
   				}
   		}
     }

     if (codedesc==1)
   	xmlhttp.open("GET","Form_SalesOrderJV_Actions.php?vaccountno="+val+"&codedesc="+codedesc+"&actionmode=checkaccountno",true);
   else	
     if (codedesc==2)
   	xmlhttp.open("GET","Form_SalesOrderJV_Actions.php?vaccountname="+val+"&codedesc="+codedesc+"&actionmode=checkaccountno",true);  

   xmlhttp.send();

   }	

   function showlistManualNo(str,indx) {
   	x = document.salesjvdt;

   	var txtLedgerNo = 'txtLedgerNo[' + indx + ']';
   	var vTransType = 'JS';
   	var vLedgerNo  = document.getElementById(txtLedgerNo).value;

   	window.open('Form_Trans_ListManualNo.php?index='+indx+'&str='+str+'&PTransType='+vTransType+'&PLedgerNo='+vLedgerNo,'Form_Trans_ListManualNo','width=740,height=550,,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
   }

   function CalcDtTotal(option, dec ,indx) {
   	x = document.salesjvdt;

   	if (!e) { var e = window.event;}
       var intKey = (window.Event) ? e.which : e.keyCode;

   	var txtDtQty = 'txtDtQty[' + indx + ']';
   	var txtDtPrice = 'txtDtPrice[' + indx + ']';
   	var txtDtDiscPer = 'txtDtDiscPer[' + indx + ']';
   	var txtDtTotal = 'txtDtTotal[' + indx + ']';

   	var vDtQty     = document.getElementById(txtDtQty).value;
   	var vDtPrice   = document.getElementById(txtDtPrice).value;
   	var vDtDiscPer = document.getElementById(txtDtDiscPer).value;
   	var vDtTotal   = document.getElementById(txtDtTotal).value;

   	if (vDtPrice == '')   vDtPrice = 0;
   	if (vDtQty == '')     vDtQty = 0;
   	if (vDtDiscPer == '') vDtDiscPer = 0;
   	if (vDtTotal == '')   vDtTotal = 0;

   	vDtQty     = parseFloat(vDtQty);	
   	vDtPrice   = parseFloat(vDtPrice);	
   	vDtDiscPer = parseFloat(vDtDiscPer);	
   	vDtTotal   = parseFloat(vDtTotal);	

   	if (option == 1 && vDtQty > 0 && vDtPrice >= 0)
   		document.getElementById(txtDtTotal).value = Math.round(((vDtQty*vDtPrice) - (vDtQty*vDtPrice*vDtDiscPer/100))*Math.pow(10,dec))/Math.pow(10,dec);
   	else if (option == 2 && intKey != 9 && vDtQty > 0 && vDtTotal >= 0)
   		document.getElementById(txtDtPrice).value = Math.round((vDtTotal/vDtQty)*Math.pow(10,dec))/Math.pow(10,dec);

   }

   function dokeysalesjvdt(e,obj,rowindx,columnslist,vbutname){

   	//if (e.ctrlKey == false)
   	//return;
   	var vindx = rowindx;
   	if (!e) { var e = window.Events;}
       var intKey = (window.Events) ? e.which : e.keyCode;

   	var columnsarray=new Array();
   	columnsarray = columnslist.split(",");
   	var firstcell = columnsarray[0];
   	var lastcell  = columnsarray[columnsarray.length-1];
   	var arrayname = obj.id.split("[");

   	if (( ((intKey == 37) || (intKey == 39)) && e.ctrlKey )  ||  (intKey == 13))
   	{
   		var cindx = columnsarray.indexOf(arrayname[0]);

   		if (intKey == 37) { //left key
   			var nextindx = Number(cindx) - 1;
   		}
   		if (intKey == 13 || intKey == 39) { //right key
   			var nextindx = Number(cindx) + 1;
   		}

   		var nextitem = columnsarray[nextindx] + '[' + rowindx + ']' ;

   		if (document.getElementById(nextitem)) {
   			var nextobj = document.getElementById(nextitem);
   			nextobj.focus();
   			if(nextobj.type!='select-one')
   			nextobj.select();
   		}

   		else { 
   			var nextrow  = rowindx + 1;
   			var nextcell = firstcell + '[' +  nextrow + ']';

   			var imgname = 'imgSubmit' + vbutname + '[' +  rowindx + ']';

   			document.getElementById(imgname).click();

   			if (document.getElementById(nextcell) ) {
   				document.getElementById(nextcell).focus();
   				if(document.getElementById(nextcell).type!='select-one')
   				document.getElementById(nextcell).select();
   			}	

   		}	
   	}
   	else if ( ((intKey == 38) || (intKey == 40)) && e.ctrlKey) {

   		if (intKey == 38) 
   			rowindx = rowindx - 1;
   		if (intKey == 40) 
   			rowindx = rowindx + 1;

   		var nextitem =  arrayname[0] + '[' + rowindx + ']';
   		if (document.getElementById(nextitem)) {
   			var nextobj = document.getElementById(nextitem);
   			nextobj.focus();
   			if(nextobj.type!='select-one')
   			nextobj.select();
   		}	
   	}

   }

   function CheckFields(ModuleRestProj, ModuleRestCost, CheckSalesman){

       x = document.salesorderjv;

   	var vDate = x.txtDate.value;
   	var vMaturityDate = x.txtMaturityDate.value;
   	var vClient = x.txtClientCode.value;
   	var vSalesman = x.txtSalesmanCode.value;
   	var vProject = x.txtProjectCode.value;
   	var vCostCenter = x.txtCostCentCode.value;
   	var vCurr = x.txtCurr.value;

   	var vmode  = x.mainaction.value;
   	var vmode1 = x.actionmode.value;

   	if (vDate=='' )
   	{
   		alert("Date is mandatory!");
   		x.txtDate.focus();
   		return 0;
   	}
   	else if (vMaturityDate=='')
   	{
   		alert("MaturityDate is mandatory!");
   		x.txtMaturityDate.focus();
   		return 0;
   	}
   	else if (vClient=='' )
   	{
   		alert("Client is mandatory!");
   		x.txtClientCode.focus();
   		return 0;
   	}
   	else if (vSalesman=='' && CheckSalesman==1)
   	{
   		alert("Salesman is mandatory!");
   		x.txtSalesmanCode.focus();
   		return 0;
   	}
   	else if (vProject=='' && ModuleRestProj==1)
   	{
   		alert("Project is mandatory!");
   		x.txtProjectCode.focus();
   		return 0;
   	}
   	else if (vCostCenter=='' && ModuleRestCost==1)
   	{
   		alert("CostCenter is mandatory!");
   		x.txtCostCentCode.focus();
   		return 0;
   	}
   	else if (vCurr=='' )
   	{
   		alert("Currency is mandatory!");
   		x.txtCurr.focus();
   		return 0;
   	}

   	else
   	return 1 ;	
   }

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

   function ClearPage1(){
   	x = document.salesorderjv;
   	var msg = x.message.value;

   	ClearForm('All');

   	x.mainaction.value='insert';
   	x.actionmode.value='';
   	x.message.value=msg;
   	x.action='Form_SalesOrderJV.php?message='+x.message.value;
   	x.submit();
   }

   function CancelRecord(){
   	x = document.salesorderjv;
   	var vmode  = x.mainaction.value;
   	var vmode1 = x.actionmode.value;
   	var vId    = x.txtSalesOrderJVId.value;

   	if (confirm ( "Are you sure you want to Delete current pending SalesJV permenantly?"))
   	{
   		ClearForm('All');
   		x.txtSalesOrderJVId.value = vId;
   		x.mainaction.value='insert';
   		x.actionmode.value='cancel';
   		x.action='Form_SalesOrderJV.php';
   		x.submit();
   	}

   }
	function addRemark(){
		let x = document.salesorderjv;
		let jvId = x.txtSalesOrderJVId.value;
		window.open('Form_SorderJvRemark.php?jvId='+jvId,'Remark','width=600,height=500');
		
	}
	
   function PostChanges(ModuleRestProj, ModuleRestCost, CheckSalesman) {
   	x = document.salesorderjv;
   	var vId       = x.txtSalesOrderJVId.value;
   	var vMainMode = x.mainaction.value;
   	var vVatChkbx = x.txtVatChk.value;
   	var result = CheckFields(ModuleRestProj, ModuleRestCost, CheckSalesman);

   	if (x.txtCountDetail.value == 0 || x.txtCountDetail.value == '') {
   		alert('Save not allowed. Please add detail(s).');
   	}
   	else {

   		if (result == 1) {
   			if (confirm ( "Are you sure you want to Save current Sales Order JV?"))
   			{
   				x.btnPost.disabled = true;
   				x.btnCancel.disabled = true;
   				x.btnClear.disabled = true;

   				x.actionmode.value='post';
   				x.action="Form_SalesOrderJV_Actions.php?mode=post&mainmode="+vMainMode+"&SId="+vId+"&SVatChkbx="+vVatChkbx;
   				x.submit();
   			}
   		}
   	}	
   }

   function DeleteDetail(PDtId) {
   	x = document.salesorderjv;
   	var vId       = x.txtSalesOrderJVId.value;
   	var vMainMode = x.mainaction.value;
   	var vVatChkbx = x.txtVatChk.value;

   	var vDelMsg = '';
   	vDelMsg = "Are you sure you want to Delete this record ?";

   	if (confirm ( vDelMsg ))
   	{
   		x.action="Form_SalesOrderJV_Actions.php?mode=deletedt&mainmode="+vMainMode+"&SId="+vId+"&SDtId="+PDtId+"&SVatChkbx="+vVatChkbx;
   		x.submit();
   	}

   }

  
   //All= All form; D= Detail Part
   function ClearForm(Option){
       x = document.salesorderjv;
   	var vmode = x.actionmode.value;

   	if (Option == 'All') {

   		x.txtSalesOrderJVId.value='';
   		x.txtRef.value='';
   		x.txtDate.value='';
   		x.txtMaturityDate.value='';
   		x.txtClientCode.value='';
   		x.txtClientName.value='';
   		x.txtClientVat.value='';
   		x.txtSalesmanCode.value='';
   		x.txtSalesmanName.value='';
   		x.txtRemark.value='';
   		x.txtManualNo.value='';
   		x.txtVatPrefix.value='';
   		x.txtCurr.value='';
   		x.txtProjectCode.value='';
   		x.txtCostCentCode.value='';

   		x.txtTaxable.value='';
   		x.txtNoneTaxable.value='';
   		x.txtGrossTotal.value='';
   		x.txtDiscountPer.value='';
   		x.txtDiscountAmt.value='';
   		x.txtVatAmt.value='';
   		x.txtVatChk.value='';
   		x.txtNetTotal.value='';

   		x.txtCountDetail.value='';
   		x.txtterms.value='';

   		x.message.value='';

   		x.actionmode.value = '';
   		x.mainaction.value = '';

	
   	} 
   }

  

   function SearchForRef(){

   	//ClearForm('All');
       x = document.salesorderjv;
       win = window.open('Form_SalesOrderJVSearch.php', 'Form_SalesOrderJVSearch', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=850,height=500,top=100');		
   	win.creator = self;
   	win.focus();		

   }

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

   }

  
   function ChangeDate(sdate){
   	var idate = new String;
   	idate = sdate;

       dt_array = idate.split("/");

       if ((dt_array[0] < 10) && (dt_array[0].length == 1))
   		dt_array[0] = "0" + dt_array[0];

   	if ((dt_array[1] < 10) && (dt_array[1].length == 1))
   		dt_array[1] = "0" + dt_array[1];

   	fdate = dt_array[1] + "-" + dt_array[0] + "-" + dt_array[2];

   	return fdate;
   }

   function CalcDiscount(option, dec, vatapplied, vatperc) {
   	x = document.salesjvorder;
   	var vmode  = x.mainaction.value;
   	var vmode1 = x.actionmode.value;

   	var TaxAmt		 = x.txtTaxable.value;
   	var GrossTotal	 = x.txtGrossTotal.value;
   	var DisPer		 = x.txtDiscountPer.value;
   	var DisAmt		 = x.txtDiscountAmt.value;
   	var VatAmt		 = x.txtVatAmt.value;

   	if ((DisAmt*1 != DisAmt/1 || DisAmt < 0) ) {
   		alert('Discount Amount should be a NUMERIC value');
   		x.txtDiscountAmt.focus();
   		return 0;
   	}
   	else if ((DisPer*1 != DisPer/1 || DisPer < 0) ) {
   		alert('Discount Percentage should be a NUMERIC value');
   		x.txtDiscountPer.focus();
   		return 0;
   	}

   	if (TaxAmt == '') 		TaxAmt = 0;
   	if (GrossTotal == '') 	GrossTotal = 0;
   	if (DisPer == '') 		DisPer = 0;
   	if (DisAmt == '') 		DisAmt = 0;
   	if (VatAmt == '') 		VatAmt = 0;

   	TaxAmt		 = parseFloat(TaxAmt);
   	GrossTotal	 = parseFloat(GrossTotal);
   	DisPer		 = parseFloat(DisPer);
   	DisAmt		 = parseFloat(DisAmt);
   	VatAmt		 = parseFloat(VatAmt);

   	if (GrossTotal > 0 && (DisPer > 0 || DisAmt > 0)) {
   		if (option == 1 )  //Option by Percentage Get The Amount
   			x.txtDiscountAmt.value = roundNumber((GrossTotal*DisPer/100),dec);
   		else if (option == 2 ){  //Option by Amount Get The Per
   		    x.txtDiscountPer.value = roundNumber(((DisAmt/GrossTotal)*100),dec);

   			if (DisAmt > 0)	x.txtDiscountPer.readOnly = true; 
   			else  x.txtDiscountPer.readOnly = false;

   		}

   		// Calculation of Vat Amount and Net Total
   		DisAmt = x.txtDiscountAmt.value;
   		if (DisAmt == '') DisAmt = 0;
   		DisAmt = parseFloat(DisAmt);

   		VatAmt = 0;
   		if (vatapplied == 1 && TaxAmt > 0) {
   			VatAmt = roundNumber(((TaxAmt - (DisAmt*TaxAmt/GrossTotal))*vatperc/100),dec);
   		} 

   		NetTotal = 	roundNumber((GrossTotal + VatAmt - DisAmt),dec);

   		VatAmt 	 = parseFloat(VatAmt);
   		NetTotal = parseFloat(NetTotal);
   		x.txtVatAmt.value   = formatNumber(VatAmt,dec);
   		x.txtNetTotal.value = formatNumber(NetTotal,dec);

   	}   

   }

   function SetVatDt(indx) {
   	x = document.salesorderjv;
   	var vmode = x.actionmode.value;
   	var txtDtVat = 'txtDtVat[' + indx + ']';
   	var chkDtVat = 'chkDtVat[' + indx + ']';

   	document.getElementById(txtDtVat).value = 0;

   	if (document.getElementById(chkDtVat).checked) document.getElementById(txtDtVat).value = 1;

   }

   function SetVat(dec, vatapplied, vatperc) {
   	x = document.salesorderjv;
   	var vmode  = x.mainaction.value;
   	var vmode1 = x.actionmode.value;

   	var TaxAmt       = x.txtTaxable.value;
   	var GrossTotal   = x.txtGrossTotal.value;
   	var VatAmt       = x.txtVatAmt.value;
   	var DisAmt       = x.txtDiscountAmt.value;
   	var NetTotal     = x.txtNetTotal.value;

   	if (TaxAmt == '') 		TaxAmt = 0;
   	if (GrossTotal == '') 	GrossTotal = 0;
   	if (VatAmt == '') 		VatAmt = 0;
   	if (DisAmt == '') 		DisAmt = 0;
   	if (NetTotal == '') 	NetTotal = 0;

   	VatAmt		 = parseFloat(VatAmt);
   	NetTotal	 = parseFloat(NetTotal);
   	DisAmt		 = parseFloat(DisAmt);
   	TaxAmt 		 = parseFloat(TaxAmt);
   	GrossTotal 	 = parseFloat(GrossTotal);

   	if (x.chkVat.checked) {

   		x.txtVatChk.value = 1;

   		// Calculation of Vat Amount and Net Total

   		VatAmt = 0;
   		if (vatapplied == 1 && TaxAmt > 0) {
   			VatAmt = roundNumber(((TaxAmt - (DisAmt*TaxAmt/GrossTotal))*vatperc/100),dec);
   		} 

   		NetTotal = 	roundNumber((GrossTotal + VatAmt - DisAmt),dec);

   		VatAmt	   = parseFloat(VatAmt);
   		TaxAmt 	   = parseFloat(TaxAmt);
   		GrossTotal = parseFloat(GrossTotal);
   		NetTotal   = parseFloat(NetTotal);

   		x.txtTaxable.value    = formatNumber(TaxAmt,dec);
   		x.txtGrossTotal.value = formatNumber(GrossTotal,dec);
   		x.txtVatAmt.value     = formatNumber(VatAmt,dec);
   		x.txtNetTotal.value   = formatNumber(NetTotal,dec);

   	}
   	else
   	{
   		x.txtVatChk.value = 0;

   		x.txtVatAmt.value   = formatNumber(0,dec);
   		x.txtNetTotal.value = formatNumber(roundNumber((NetTotal - VatAmt),dec),dec);

   	}  

   }

   function submitSalesOrderJvDt(TrDtId,TrId,vrec,vmode,ModuleRestProj, ModuleRestCost, CheckSalesman,filepath){

   var vDTId = TrDtId; 

   	if (vmode=='i')
   	{		 
		var vactionmode = 'submitdt';
		vmode = 'submitrecord';
   	}	
   	else 	{
		var vactionmode = 'editdt';	
		vmode = 'editdt';
   	}

   var txtLedgerNo 			= 'txtLedgerNo['+vrec+']';
   var txtDescription1 		= 'txtDescription1['+vrec+']';
   var txtDescription2 		= 'txtDescription2['+vrec+']';
   var txtDtCurr 			= 'txtDtCurr['+vrec+']';
   var txtDtQty 			= 'txtDtQty['+vrec+']';
   var txtDtPrice 			= 'txtDtPrice['+vrec+']';
   var txtDtDiscPer 		= 'txtDtDiscPer['+vrec+']';
   var txtDtTotal 			= 'txtDtTotal['+vrec+']';
   var txtDtVat 			= 'txtDtVat['+vrec+']';
   var txtDtManualNo 		= 'txtDtManualNo['+vrec+']';
   var txtProjectCodeDt 	= 'projectcodedt['+vrec+']';
   var txtCostCentCodeDt 	= 'costcentcodedt['+vrec+']';

   var value1 	= document.getElementById(txtLedgerNo).value;
   var value2 	= encodeURIComponent(document.getElementById(txtDescription1).value);
   var value3 	= encodeURIComponent(document.getElementById(txtDescription2).value);
   var value4 	= document.getElementById(txtDtCurr).value;
   var value5 	= document.getElementById(txtDtQty).value;
   var value6 	= document.getElementById(txtDtPrice).value;
   var value7 	= document.getElementById(txtDtDiscPer).value;;
   var value8 	= document.getElementById(txtDtTotal).value;;
   var value9 	= document.getElementById(txtDtVat).value;;
   var value10 	= document.getElementById(txtDtManualNo).value;;
   var value11 	= encodeURIComponent(document.getElementById(txtProjectCodeDt).value);
   var value12 	= encodeURIComponent(document.getElementById(txtCostCentCodeDt).value);
   

   var x =  document.salesorderjv;
   var result = CheckFields(ModuleRestProj, ModuleRestCost, CheckSalesman);
   if (result != 1) 
   return;		
   	var vId           = x.txtSalesOrderJVId.value;
   	var vDate         = x.txtDate.value;
   	var vMaturityDate = x.txtMaturityDate.value;
   	var vClient       = x.txtClientCode.value;
   	var vSalesman     = x.txtSalesmanCode.value;
   	var vRemark       = encodeURIComponent(x.txtRemark.value);
   	var vManualNo     = encodeURIComponent(x.txtManualNo.value);
   	var vVatPrefix    = x.txtVatPrefix.value;
   	var vCurr         = x.txtCurr.value;
   	var vProjectCode  = encodeURIComponent(x.txtProjectCode.value);
   	var vCostCentCode = encodeURIComponent(x.txtCostCentCode.value);
   	var vDiscountPer  = x.txtDiscountPer.value;
   	var vDiscountAmt  = x.txtDiscountAmt.value;
   	var vVatChkbx     = x.txtVatChk.value;
   	var txtterms      = encodeURIComponent(x.txtterms.value);

   	var vMainMode = x.mainaction.value;

   	var SubBtnID = 'imgSubmitSalesOrderJvDt['+vrec+']';
   	var SubBtnObj = document.getElementById(SubBtnID);
   	$(SubBtnObj).unbind('click');
   	$(SubBtnObj).removeAttr("onclick");	

   if (window.XMLHttpRequest)
     {// code for IE7+, Firefox, Chrome, Opera, Safari
       xmlhttp=new XMLHttpRequest();
     }
   else
     {// code for IE6, IE5

     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
     }

   var trid = document.getElementById('txtSalesOrderJVId').value;

   $("#Loader").addClass("ajaxsaving");  
   xmlhttp.onreadystatechange=function()
     {  

     if (xmlhttp.readyState==4 && xmlhttp.status==200)
       {
   				{ 		
   					if (vmode=='submitrecord')
   					{  

						var data = xmlhttp.responseText.split("[BRK]");

						document.getElementById('txtSalesOrderJVId').value = data[1];
						document.salesorderjv.actionmode.value='edit';

   						if (trid==''){				
							document.salesorderjv.action='Form_SalesOrderJV.php';				
							document.salesorderjv.submit();

						}
						else {

							ReloadGrid(filepath,'JSO',trid,'datagrid','','','ADD','','','','',0,'',function() {
								var focusedvrec = parseInt(vrec) + 1;
								var focused = 'txtLedgerNo['+focusedvrec+']';
								document.getElementById(focused).focus();
							});
							ReloadGridDt(filepath,'SalesOrderJv-TOT','TOTALS','totals',trid,-1);

						}
   					}	
   					else {
   							var data = xmlhttp.responseText.split("[BRK]");

							ReloadGrid(filepath,'JSO',trid,'datagrid','','','ADD','','','','',0,'',function() {
   											var focusedvrec = parseInt(vrec) + 1;
   											var focused = 'txtLedgerNo['+focusedvrec+']';
   											document.getElementById(focused).focus();
   										});
   							ReloadGridDt(filepath,'SalesOrderJv-TOT','TOTALS','totals',trid,-1);
					}
						
						
   				}
   		}

     }

   	xmlhttp.open("GET","Form_SalesOrderJV_Actions.php?mainaction="+vMainMode+"&actionmode=&SId="+vId+"&SDtId="+vDTId+"&PDate="+vDate+"&PMaturityDate="+vMaturityDate+
   								"&PClientCode="+vClient+"&PSalesmanCode="+vSalesman+"&PCurr="+vCurr+"&PProjectCode="+vProjectCode+
   								"&PCostCentCode="+vCostCentCode+"&PDiscountPer="+vDiscountPer+"&PDiscountAmt="+vDiscountAmt+
   								"&PVatChkbx="+vVatChkbx+"&PManualNo="+vManualNo+"&PVatPrefix="+vVatPrefix+"&PRemark="+vRemark+"&mode="+vmode+
   								"&value1="+value1+"&value2="+value2+"&value3="+value3+"&value4="+value4+"&value5="+value5+
   								"&value6="+value6+"&value7="+value7+"&value8="+value8+"&value9="+value9+"&value10="+value10+
   								"&value11="+value11+"&value12="+value12+"&txtterms="+txtterms 
   								,true);
   xmlhttp.send();   
   }

   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 PrintSalesOrderJV(PId, PRef) {
   	var str = '';

   	if (confirm ( "Do you want to Print current Invoice with reference "+PRef+" ?"))
   	{
   		str = 'Form_SalesOrderJVPreview.php?SalesOrderJVId='+PId;
   		window.open(str);
   	}	

   }

   function showlistClient(str){
     var vdate, vcode;
     vdate=document.salesorderjv.txtDate.value;
     vcode=document.salesorderjv.txtClientCode.value;

     window.open('List_SorClient.php?frm=21&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 showlistSalesman(str){
     var vdate, vcode;
     vdate=document.salesorderjv.txtDate.value;
     vcode=document.salesorderjv.txtSalesmanCode.value;

     window.open('List_SorSalesman.php?frm=11&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){

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

   function showlistCostcenter(str){

     window.open('List_SorCostcenter.php?frm=11&item='+str,'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 SetRecordGridDefaults(PIndex) {
   	x = document.salesorderjv;

   	if (document.getElementById('projectcodedt['+PIndex+']')){
   		if (document.getElementById('projectcodedt['+PIndex+']').value == "")
   			document.getElementById('projectcodedt['+PIndex+']').value = x.txtProjectCode.value;
   	}	

   	if (document.getElementById('costcentcodedt['+PIndex+']')){
   		if (document.getElementById('costcentcodedt['+PIndex+']').value == "")
   			document.getElementById('costcentcodedt['+PIndex+']').value = x.txtCostCentCode.value;
   	}
   }

   function kd(e)
   { 

   	x=document.salesorderjv;
       var intKey = (window.Event) ? e.which : e.keyCode;
       if (intKey == 13) { //enter key
           //x.btnSubmitRecord.click();

   		return false;
       }
       return true;
   }
   function searchCustomer(e){
   	if(e.keyCode == 13){

   	var txtClientCode = document.getElementById('txtClientCode').value;
   	var str = "Form_SalesOrderJV_Actions.php?actionmode=searchcustomer&txtClientCode="+txtClientCode;
   	var xhttp = new XMLHttpRequest();
   	//alert(str);exit;
     xhttp.onreadystatechange = function() {
       if (xhttp.readyState == 4 && xhttp.status == 200) { 
   		var data = xhttp.responseText.split('[BRK]');
   		//document.write(data[0]);
   		if(data[0] == 1){
   			document.getElementById('txtClientCode').value = data[1];
   			document.getElementById('txtClientName').value = data[2];
           }
   		else{
   			var str2 = "List_SorClient.php?frm=7&item=1&PLedger_number="+document.getElementById('txtClientCode').value+"&TransDate="+document.getElementById('txtDate').value;
   			window.open(str2, 'List_SorProject','width=850,height=550,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes,left=150,top=150');
   		}
   		}
     };
     xhttp.open("GET", str, true);
     xhttp.send();
   	}
   }
   function searchLedger(e){
   	if(e.keyCode == 13){
   		var txtLedgerNo = document.getElementById('txtLedgerNo[0]').value;
   		var str = "Form_SalesOrderJV_Actions.php=actionmode=searchledger&txtLedgerNo="+txtLedgerNo;
   		var xhttp = new XMLHttpRequest();
   	//alert(str);exit;
     xhttp.onreadystatechange = function() {
       if (xhttp.readyState == 4 && xhttp.status == 200) { 
   		var data = xhttp.responseText.split('[BRK]');
   		if(data[0] == 1){
   			document.getElementById('txtLedgerNo[0]').value = data[1];
   			document.getElementById('txtLedgerName[0]').value = data[2];
   		}
   		else{
   			var str2 = "List_AccountNo.php?PLedger_Number="+document.getElementById('txtLedgerNo[0]').value+"&item=2&vtype=txtLedgerNo&vtext1=txtLedgerNo[0]&vtext2=txtLedgerName[0]&vtext3=projectcodedt[0]&vtext4=costcentcodedt[0]&text1value=";
   			window.open(str2, 'List_SorProject','width=850,height=550,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes,left=150,top=150');
   		}
   		}
     };
     xhttp.open("GET", str, true);
     xhttp.send();
   	}
   }

   function moveToNextField(fieldName, e){
   	if(e.keyCode == 13){
   	document.getElementById(fieldName).focus();
   	}
   }

   </script>
   <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
   <title>Sales Order JV</title>

   <link rel="stylesheet" type="text/css" media="all" href="js/grid/UI_DataGrid_V1.css">

   <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='salesorderjv' method='post' action=''>
     $toecho  
   <input type='hidden' name='actionmode' value='$actionmode'>
   <input type='hidden' name='mainaction' value='$mainaction'>
   <input type='hidden' name='message' value='$message' size='200'>
HERE;

   //$message='';

   //Initializations

   //Get Default Project
   $querydflproject="select project_code as defaultproject from ".$_SESSION['dbLabel'].".loginstk where user_account='".$_SESSION['useraccount']."' and default_project=1 ";
   $resultdflproject=mysql_query($querydflproject,$connection) or die(mysql_error());
   while($rows=mysql_fetch_array($resultdflproject)){
   	extract($rows);
   }

   //Get Default Coscenter
   $querydflcostcent="select costcent_code as defaultcostcent from ".$_SESSION['dbLabel'].".loginstk where user_account='".$_SESSION['useraccount']."' and default_costcenter=1 ";
   $resultdflcostcent=mysql_query($querydflcostcent,$connection) or die(mysql_error());
   while($rows=mysql_fetch_array($resultdflcostcent)){
   	extract($rows);
   }

   if ((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"  && $txtSalesOrderJVId != '') {
   	// Read From Temp Tables For Selected Record				 
   	$query = " Select SalesOrderJV_ID, SalesOrderJV_Reference, Date_Format(SalesOrderJV_Date,'%d/%m/%Y') As SalesOrderJV_Date, ".
   	         " Date_Format(JournalDt_ValueDate,'%d/%m/%Y') As MaturityDate, ".
   			 " SalesOrderJV.Client_Code As ClientCode, Clients.Ledger_name As ClientName, Client_VAT,   ".
   			 " SalesOrderJV.Salesman_Code As SalesmanCode, Salesmen.Ledger_name As SalesmanName, ".
   			 " SalesOrderJV.Currency_Code, Sales_Remark, SalesOrderJV.Project_Code, SalesOrderJV.Costcenter_Code,  ".
   			 " Round(ifNull(SalesOrderJV_Taxable,0), ".$DecimalBase."), Round(ifNull(SalesOrderJV_NoneTaxable,0), ".$DecimalBase."), ".
   			 " Round(ifNull(SalesOrderJV_Total,0), ".$DecimalBase.") As GrossTotal, ".
   			 " Round(ifNull(SalesOrderJV_DiscountPer,0), ".$DecimalBase."), Round(ifNull(SalesOrderJV_DiscountAmount,0), ".$DecimalBase."),  ".
   			 " Round(ifNull(SalesOrderJV_VAT,0), ".$DecimalBase.") As SalesOrderJV_VAT, ".
   			 " Round((ifNull(SalesOrderJV_Total,0) + IfNull(SalesOrderJV_VAT,0) - IfNull(SalesOrderJV_DiscountAmount,0)), ".$DecimalBase.") As SalesOrderJV_NetTotal,  ".
   			 " ifNull(SalesOrderJV_VatCheck,0) As SalesOrderJV_VatCheck, SalesOrderJV.SalesOrderJv_ManualNo, SalesOrderJV.SalesOrderJv_VatPrefix, salesOrderjv_PaymentTerms ".
   			 " From Temp_SalesOrderJV As SalesOrderJV ".
   			 " Left Join Clients on SalesOrderJV.Client_Code = Clients.Ledger_Number ".
   			 " Left Join Salesmen on SalesOrderJV.Salesman_Code = Salesmen.Ledger_Number ".
   	         " Where SalesOrderJV_ID = ".$txtSalesOrderJVId;
    //echo $query;
   	$result=mysql_query($query,$connection) or die(mysql_error());
       $rows=mysql_fetch_array($result);

   	$txtSalesOrderJVId   = $rows[0];
   	$txtRef          	 = $rows[1];
   	$txtDate         	 = $rows[2];
   	$txtMaturityDate 	 = $rows[3];

   	if (empty($txtClientCode)) { 
   	$txtClientCode   	= $rows[4];
   	$txtClientName    	= $rows[5];
   	$txtClientVat    	= $rows[6];
   	}

   	$txtSalesmanCode 	= $rows[7];
   	$txtSalesmanName 	= $rows[8];
   	$txtCurr         	= $rows[9];
   	$txtRemark        	= $rows[10];
   	$txtProjectCode    	= $rows[11];
   	$txtCostCentCode   	= $rows[12];
   	$txtManualNo 	   	= $rows[21];
   	$txtVatPrefix 	   	= $rows[22];

   	$txtTaxable      = $rows[13];
   	$txtNoneTaxable  = $rows[14];
   	$txtGrossTotal   = $rows[15];
   	$txtDiscountPer  = $rows[16];
   	$txtDiscountAmt  = $rows[17];
   	$txtVatAmt       = $rows[18];
   	$txtNetTotal     = $rows[19];
   	$txtVatChk       = $rows[20];
   	$txtterms		 = $rows[23];

   	$query = " Select Count(*) FROM Temp_SalesOrderJVDt ".
   			 " WHERE SalesOrderJV_ID = ".$txtSalesOrderJVId;
   	$result = selectData($connection, $query);
   	$txtCountDetail = $result[0];
   	if($txtCountDetail == '') $txtCountDetail = 0;

   }

   //Search/Cancel Mode	
   if ($actionmode == "cancel" && $txtSalesOrderJVId != '') {

   	// Delete From Temp Tables Already Filled By Search
   	$query = " DELETE FROM Temp_SalesOrderJVDt ".
   			 " WHERE SalesOrderJV_ID = ".$txtSalesOrderJVId;
   	if (!updateData($connection, $query, true))
         $message  = mysql_error(); 
	
	$query = "DELETE FROM temp_sorderJvRemarkdt ".
   			 " WHERE sorderJv_id = ".$txtSalesOrderJVId;
   			
   	if (!updateData($connection, $query, true))
         $message  = mysql_error();   
	 
   	$query = " DELETE FROM Temp_SalesOrderJV ".
   			 " WHERE SalesOrderJV_ID = ".$txtSalesOrderJVId;
   			
   	if (!updateData($connection, $query, true))
         $message  = mysql_error();   

   	$txtSalesOrderJVId = '';
   }

   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 Order JV</span></td>
   				<td class='message' valign='middle' style='height:26px;'>".htmlspecialchars($message, ENT_QUOTES)."</td>
   			</tr></table>
   		</td>
   	  </tr>";

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

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

   echo"<button type='button' id='btnCancel' name='btnCancel' ";
   if ($actionmode=='cancel' || ($actionmode=='' && $mainaction!='edit'))
   			echo " disabled ";

   echo" onclick='CancelRecord();return false;' title='Cancel Changes'><span><span>Cancel</span></span></button>";	

   if($txtSalesOrderJVId != '')
    echo"<button type='button' id='btnRemark' name='btnRemark' onclick='addRemark();return false;' title='add Remark'><span><span>Add Remark</span></span></button>";		
	
   echo"<button type='button' id='btnPost' name='btnPost' ";
   	if (($actionmode=='' || $actionmode=='cancel') && $mainaction!='edit')
   			echo " disabled ";
   	echo" onclick='PostChanges($Module_RestrictProjCost,$Module_RestrictCost,$FI_SalesCheckSalesman);return false;' title='Save Changes'><span><span>Save</span></span></button>";		

   echo"<button type='button' id='btnSearch' name='btnSearch' ";
   	if (($actionmode!='' && $actionmode!='cancel') || $mainaction=='edit') 
   		    echo " disabled ";
   	echo" onclick='SearchForRef();return false;' title='Search By Reference'><span><span>Search</span></span></button>";

   echo"<button type='button' id='btnPending' name='btnPending' ";	

           if (($actionmode!='' && $actionmode!='cancel') || $mainaction=='edit')
   	   echo " disabled ";
   	   echo" onclick='SearchForPending();return false;' title='Search Pending'><span><span>Pending</span></span></button>";	

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

   echo"<tr><td id='content-body'>";

  

   echo "<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=100>
   		  <col width=60>
   		  <col width=90>
   		  <col width=60>
   		  <col width=100>
   		  <col width=80>
   		  <col width=170>
   		  <col width=250>
   		<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='txtCountDetail' value='$txtCountDetail' >
   			<input type='hidden' name='txtSalesOrderJVId'  id='txtSalesOrderJVId' value='$txtSalesOrderJVId' size='10'>
   			<input type="hidden" name="txtRef" value="$txtRef" size='10' >
   		  </td>

HERE;
 	echo" <td colspan='4'>&nbsp;</td>";
   
   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' maxlength='10' style='width:90px;' readonly >
   		                   <A HREF="#" onClick="displayCalendar(document.salesorderjv.txtDate,'dd/mm/yyyy',this);  return false; " NAME="anchor1" ID="anchor1"><img src='./img/cal.gif' border=0 align=center></A></td>

HERE;

   if ($txtClientCode != "" ){				
   	$query = " SELECT Clients.Salesmen_Code, Salesmen.Ledger_name As Salesmen_Name, Clients.Project_Code ".
   	         " FROM Clients Left Outer Join Salesmen on Clients.Salesmen_Code = Salesmen.Ledger_number WHERE Clients.Ledger_Number = '".$txtClientCode."'";
   	$result = selectData($connection, $query);

   	if ($txtSalesOrderJVId == "") {
   		$txtSalesmanCode = $result[0];
   		$txtSalesmanName = $result[1];

   		if ($Client_ValidateProject == 1) $txtProjectCode = $result[2];
   	}

   }

   // Check If Vat Applied
   $VatApplied = 0;

   if (insertDate($txtDate) > $Setup_VatStartDate && $Setup_VatPercentage != 0) {		  
     $VatApplied = 1;
   }
   $AllowModifyVAT = '';
   if ($ModifyVAT == 0) $AllowModifyVAT = ' disabled ';

   $Parameters = array();
   $Parameters['Login_AllowPrice'] 			= $Login_AllowPrice;
   $Parameters['Login_NegativeQty'] 		= $Login_NegativeQty;
   $Parameters['Login_ModifySellingPrice'] 	= $Login_ModifySellingPrice;
   $Parameters['Login_ModifyDiscount'] 		= $Login_ModifyDiscount;
   $Parameters['Allow_MinimumPrice'] 		= $Allow_MinimumPrice;
   $Parameters['Module_Unit1Method'] 		= $Module_Unit1Method;
   $Parameters['Module_Pack'] 				= $Module_Pack;
   $Parameters['Module_DoubleUnit'] 		= $Module_DoubleUnit;
   $Parameters['Module_ProjectDt'] 			= $Module_ProjectDt;
   $Parameters['Module_CostCenterDt'] 		= $Module_CostCenterDt;
   $Parameters['Module_RestrictProjCost'] 	= $Module_RestrictProjCost;
   $Parameters['Module_RestrictCost'] 		= $Module_RestrictCost;
   $Parameters['ShowCostCentLayout'] 		= $ShowCostCentLayout;
   $Parameters['DecimalBase'] 				= $DecimalBase;
   $Parameters['Setup_VatPercentage'] 		= $Setup_VatPercentage;
   $Parameters['Module_AdditionalTaxes'] 	= $Module_AdditionalTaxes;
   $Parameters['VatApplied'] 				= $VatApplied;
   $Parameters['AllowModifyVAT'] 			= $AllowModifyVAT;
   $Parameters['txtClientCode']  			= $txtClientCode;
   $Parameters['FA_SalesJvVAT'] 			= $FA_SalesJvVAT;
   $Parameters['costcent_applyvat'] 		= $costcent_applyvat;
   $Parameters['FI_SalesCheckSalesman'] 	= $FI_SalesCheckSalesman;
   $Parameters['salesjv_paymentmode'] 		= $salesjv_paymentmode;
   $_SESSION['SalesOrderJv_parameters']  	= $Parameters;

   echo"<td rowspan='5' valign='top'>";


   echo"	<div id='totals' style='width:240px; margin-top:2px; float:right;border:0px solid #000000;'>";
	ShowSalesOrderJvTotals($connection,$txtSalesOrderJVId,$_SESSION['SalesOrderJv_parameters'],$_SESSION['gSalesJv_arrayaccess']);
   echo"	</div>"; 

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

   echo"   <tr bgcolor='#F7F7F7' height='25'>
   		  <td align='left' ><span class='style1'>Client&nbsp;<span class='style16'>*</span></span></td>";
   echo"     <td colspan='5' ><span class='style1'>";
   echo"     <label>
              <input type='text'   name='txtClientCode' id='txtClientCode' value='$txtClientCode' style='width:95px;' maxlength='10' onkeyup=\"searchCustomer(event); moveToNextField('txtClientName', event)\"  />
              <input type='text'   name='txtClientName' id='txtClientName' value='$txtClientName' style='width:285px;' onkeyup=\"moveToNextField('txtSalesmanCode', event)\" />
   		   <label><span class='style1'><img src='img/btnopen.jpg' title=' Select Client ' width='15' height='20' border='0' onMouseOver=\"style.cursor='hand'\"  onClick='showlistClient(1); '  /> </span></label>
   		   <input type='hidden' name='txtClientVat' id='txtClientVat' value='$txtClientVat' />
             </label>
             </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;' readonly >
   						  <A HREF='#' onClick=\"displayCalendar(document.salesorderjv.txtMaturityDate,'dd/mm/yyyy',this); return false;\" NAME=\"anchor1\" ID=\"anchor1\"><img src='./img/cal.gif' border=0 align=center></A></td>";		  
   echo"   </tr>";

   echo"   <tr bgcolor='#F7F7F7'  height='25'>
   		  <td align='left' ><span class='style1'>Salesman</span></td>";
   echo"     <td colspan='5' ><span class='style1'>";
   echo"     <label>
              <input type='text'   name='txtSalesmanCode' id='txtSalesmanCode' onkeyup=\"moveToNextField('txtSalesmanName', event)\" value='$txtSalesmanCode' style='width:95px;' maxlength='10'  />
              <input type='text'   name='txtSalesmanName' id='txtSalesmanName' onkeyup=\"moveToNextField('txtRemark', event)\" 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>";

   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:90px;'>";
   			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><span class='style1'>Payment Terms</span></td>
			<td colspan='5'><textarea name='txtterms' id='txtterms' cols='52' rows='3'>".htmlspecialchars($txtterms, ENT_QUOTES)."</textarea></td>
			<td></td>
		</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' id='txtRemark' value='".htmlspecialchars($txtRemark, ENT_QUOTES)."' onkeyup=\"moveToNextField('txtManualNo', event)\"  style='width:385px;' maxlength='200' ></span></td>";

   //echo" 	  <td align='left' colspan='2'>&nbsp;</td>";
   echo"   <td align='left' valign='center'><span class='style1'>Manual No</span></td>
   		<td><input type='text' name='txtManualNo' id='txtManualNo' value='".htmlspecialchars($txtManualNo, ENT_QUOTES)."' onkeyup=\"moveToNextField('txtVatPrefix', event)\"  style='width:90px;' maxlength='20' ></td>";
   echo"   </tr>";		  

   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' readonly /></span>
   		    <label><span class='style1'><img src='img/btnopen.jpg' title=' Select Project ' width='15' height='20' border='0' onMouseOver=\"style.cursor='hand'\" onClick='showlistProject(1); '  /></span></label></td>";
   } else	{
   	echo "<td align='left' colspan='3'><input type='hidden' name='txtProjectCode' id='txtProjectCode' value='$txtProjectCode' /></td>";
   }		

   if ($Module_CostCenter == 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:130px;' maxlength='15' readonly /></span>
   		    <label><span class='style1'><img src='img/btnopen.jpg' title=' Select Costcenter ' width='15' height='20' border='0' onMouseOver=\"style.cursor='hand'\"  onClick='showlistCostcenter(1); ' /></span></label></td>";
   } else {
   	echo "<td align='left' colspan='3'><input type='hidden' name='txtCostCentCode' id='txtCostCentCode' value='$txtCostCentCode' /></td>";
   }			

   //echo"	  <td align='left' colspan='2'>&nbsp;</td>";
   echo"   <td align='left' valign='center'><span class='style1'>Vat Prefix</span></td>
   		<td><input type='text' name='txtVatPrefix' id='txtVatPrefix' onkeyup=\"moveToNextField('txtLedgerNo[0]', event)\"  value='".htmlspecialchars($txtVatPrefix, ENT_QUOTES)."'  style='width:90px;' maxlength='10' ></td>";

   echo"   </tr>";

   echo"   </table>";

   echo "</td>";

   echo "</tr>"; 

   echo"   <tr >";

   echo "<td colspan='10' valign='top' bgcolor='#ffffff'>";

   echo"	<div id='datagrid' class='' style='width:1200px;' >";

   //Show Items Grid
   ShowSalesOrderJvDtGrid($connection,'JS',$txtSalesOrderJVId,$_SESSION['SalesOrderJv_parameters'],$_SESSION['gSalesJv_arrayaccess']);

   echo"	  </div>"; 

   echo"   </td>";

   echo "</tr>"; 

   	echo"   <tr><td colspan='9' valign='top'>";

   echo"	<div id='testdatagrid' class='' style='width:1090px;' >";

   echo"	  </div>"; 

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

   echo"   </table>";

   echo "</td>";

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

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

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

   if ($actionmode == "post"  && $PrId != '') {
   	echo '<script type="text/javascript" language="javascript">';

   	if ($Login_FastPrint == 1) {
   		echo ' PrintSalesOrderJV(\''.$PrId.'\', \''.$PrRef.'\'); ';

   	}		
   	echo ' ClearPage1(); ';
   	echo '</script>';

   }


   // table
   print <<<HERE

   </form>

   </body>

HERE;

   ?>