<?php

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

include("config.inc.php");
include("Functions_Trans.php");
include("Forms_DataGrid.php");

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

if(	$_SESSION['encodingmode'] == 'utf8' || $_SESSION['encodingmode'] == 'utf-8'){
	mysql_query("SET NAMES 'utf8'"); 
	mysql_query('SET CHARACTER SET utf8'); 
	mysql_set_charset('utf8', $connection);
}
$query_language  = "select user_account, Language from ".$_SESSION['dbLabel'].".login  where user_account = '".$_SESSION['useraccount']."'";
$result_language = mysql_query($query_language, $connection); 
$row_language    = mysql_fetch_array($result_language);
extract($row_language);

$query_journal_labels  = "select Language, label0 as Ref1, TypeRef as TypeRef1, label3 as Folio1, label2 as Date1, label1 as Type1, Project as Project1, Disp_2_1 as Costcenter2, Remark as Remark1, ManualNo as ManualNo1, Disp_1 as LedgerNo1, LedgerName as LedgerName1, Disp_4_1 as DescX, Disp_3 as Curr1, D_C as DC1, Disp_5 as Amount1, Disp_1_3 as ValueDate1, ManualNo as ManualNo1, Desc1 as Desc1,
                          NoRecords, Perpage, Page, Disp_2_2 as Perce, Disp_1_1 as CheckNo, Disp_1_2 as Bankk, Label4 as Debitt, Label5 as Creditt, Disp_4 as Balancee
                          from ".$_SESSION['dbLabel'].".journal_label
                          where Language = '".$Language."'";
$result_journal_labels = mysql_query($query_journal_labels, $connection);
$row_journal_labels    = mysql_fetch_array($result_journal_labels);
extract($row_journal_labels);

$_SESSION['query_journal_labels'] = $query_journal_labels;

$query_navigator = "SELECT LANGUAGE,
       ClearPage,
       Excel,
       Save,
       Print,
       Addd,
       Search,
       Pending,
       CopyJV,
       PaymentRequests,
       ExportExcel,
	   cancell
FROM ".$_SESSION['dbLabel'].".mainform_label
WHERE LANGUAGE = '".$Language."'";
$result_navigator = mysql_query($query_navigator, $connection);
$row_navigator    = mysql_fetch_array($result_navigator);
extract($row_navigator);

//echo $Costcenter1; exit;
$query_project  = "select Journal as Journal1, ResultsPage as ResultsPage1
                   from ".$_SESSION['dbLabel'].".mainform_label
				   where Language = '".$Language."'";
$result_project = mysql_query($query_project, $connection);
$row_project    = mysql_fetch_array($result_project);
extract($row_project);

$querylog="SELECT ifNull(FA_Journal, 0) as loginaccess, ifNull(FA_JournalPrintingAsk, 0) as FA_JournalPrintingAsk from ".$_SESSION['dbLabel'].".login where user_account='".$_SESSION['useraccount']."' 	and Upper(Login_Schema) = Upper('".$_SESSION['dbName']."')	";
$resultlog=mysql_query($querylog,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultlog)){
	extract($rows);
}
if ($loginaccess=='' or $loginaccess==0)
	header("location:menu.php");
	
$querylog=" select ifNull(FA_JournalApp,0) As FA_JournalApp, ifNull(Login_FastPrint,0) As Login_FastPrint, ifNull(FA_LedgerAccess,0) As FA_LedgerAccess ".
		  " 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, Journal_DefaultCur ".
             " 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_RestrictProjCost,0) As Module_RestrictProjCost, ifNull(Module_RestrictCost,0) As Module_RestrictCost, ".
			 " ifNull(Module_ProjectDt,0) As Module_ProjectDt, ifNull(Module_CostCenterDt,0) As Module_CostCenterDt, ".
			 " ifNull(module_referencebycostcenter,0) As Module_ReferenceByCostCenter, ifNull(module_checks,0) As Module_checks, ".
			 " ifNull(Module_ShowBalance,0) As Module_ShowBalance, ifNull(Module_ImportExcell,0) As Module_ImportExcell, ifNull(Module_bill,0) As Module_bill, ".
			 " ifNull(module_journalRate,0) As module_journalRate,ifNull(module_ledgerrestrictcur,0) As module_ledgerrestrictcur, ifnull(journal_distribution,0) as journal_distribution  ".	
			 " From Module";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}



/// Journal Type
$queryjourtype="select type_name,  if(type_desc is null or type_desc = '',type_name, concat(type_name, '-',type_desc)) from jourtype where ifnull(type_visible,0) = 1 ";
$resultjourtype=mysql_query($queryjourtype,$connection)	or die( mysql_error($connection));





/* //Read From TransSetup Table							
$querytranssetup= " select DefaultCur, DefaultProject as StpDefaultProject, DefaultCostcenter as StpDefaultCostcenter, ifnull(Hide_ValueDate,0) Hide_ValueDate,  ifnull(Hide_Base2,0) Hide_Base2,
					ifnull(showJournalRate,0) as showJournalRate, showCheckNo_RV 
					from transsetup where JournalType = 'JV'";
					
 
$resulttranssetup=mysql_query($querytranssetup,$connection) or die(mysql_error());
while($rowtranssetup=mysql_fetch_array($resulttranssetup)){
	extract($rowtranssetup);
} */   // no journal type jv in transsetup 

//Get Default Project from setup
$querytranssetup= " select jv_defaultproject as defaultprojectsetup from setup ";
					
 
$resulttranssetup=mysql_query($querytranssetup,$connection) or die(mysql_error());
while($rowtranssetup=mysql_fetch_array($resulttranssetup)){
	extract($rowtranssetup);
}





//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);
}
//echo $querydflproject;exit;


 if (empty($defaultproject))
 {
	 $defaultproject =  $defaultprojectsetup;
 }
 

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


//Get Excluded Project for user
$queryExProject 		= "select project_codeExcluded from ".$_SESSION['dbLabel'].".loginstk where user_account = '".$_SESSION['useraccount']."' ";
$resExProject 			= mysql_query($queryExProject, $connection);
$rowExProject 			= mysql_fetch_row($resExProject);
$project_codeExcluded   = $rowExProject[0];


$vMainCompanyName=explode('_',$_SESSION['dbName']);  
$DirCompany  = $vMainCompanyName[0];
preg_match_all('!\d+!', $vMainCompanyName[1] ,$DirYears );
$fromdate =  '01/01/'.$DirYears[0][0];
$todate = date('d/m/Y'); 


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


<meta http-equiv="Content-Type" content="text/html; charset=windows-1256" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />


<link rel="stylesheet" type="text/css" media="all" href="css-v2/style.css">
<link type="text/css" rel="stylesheet" href="js/calendar/dhtmlgoodies_calendar.css?random=20051112" media="screen"></LINK>
<SCRIPT type="text/javascript" src="js/calendar/dhtmlgoodies_calendar.js?random=20060118"></script>

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

<script type="text/javascript" src="js/tabsClass/tabber.js"></script>
<link rel="stylesheet" href="js/tabsClass/tabber.css" type="text/css" />

<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');
		}); 
		$(document).on('focusin', '.table-focus-g2', function() { 
			AutoSaveRecordGrid(this.id,'SelectedRec_G2','ModRec_G2','imgSubmit_D');
			selRecordColor(this,'SelectedRec_G2','SelectedRecColor_G2');
		});
		$(document).on('focusin', '.table-focus-g3', function() {
			AutoSaveRecordGrid(this.id,'SelectedRec_G3','ModRec_G3','imgSubmit_C');
			selRecordColor(this,'SelectedRec_G3','SelectedRecColor_G3');
		});
		$(document).on('focusin', '.table-focus-g4', function() {
			AutoSaveRecordGrid(this.id,'SelectedRec_G4','ModRec_G4','imgSubmit_B');
			selRecordColor(this,'SelectedRec_G4','SelectedRecColor_G4');
		});
		 
		//Set Scroll Positions on Page Load
		scrollToPage();
		
		$(window).scroll(function(){
			scrollPage();
		});
		
		//document.getElementById('CurRec0').click();
		
		
		//Set Cursor Position After Page Reload
		var NextElement = readCookie('jv-nextcell');
		
		//stopped by maruon
		NextElement = 'ledgernumber[0]';
		document.journal.RecIndex_G1.value=0;
		MoveNextRecord(NextElement);
		
		if(document.getElementById('projectcodedt[0]'))
			document.getElementById('projectcodedt[0]').focus();
		else 	
		if(document.getElementById('costcentcodedt[0]'))
			document.getElementById('costcentcodedt[0]').focus();
		//else if(document.getElementById('chkjournumber[0]'))
		//		document.getElementById('chkjournumber[0]').focus();
				
		
		
		
		
		eraseCookie('jv-nextcell');
		
		
		//Disable Sub Detail Grids
		/*
		$('#datagrid-d :input').attr('disabled', true);
		$('#datagrid-c :input').attr('disabled', true);
		$('#datagrid-b :input').attr('disabled', true);
		*/
	});
	
	function ShowSlidingDiv(PDivID) {
	$(PDivID).slideToggle();
}
	function OpenStatementOfAccount(indx){
	var ledgernbr = document.getElementById("ledgernumber["+indx+"]").value;
	var fromdate = document.getElementById("fromdate").value;
	var todate = document.getElementById("todate").value;
	
	win = window.open('rep_statementofaccount.php?fromdate='+fromdate+'&todate='+todate+'&fromledger='+ledgernbr+'&toledger='+ledgernbr+'&fromproject=&fromcst=&fromcur=&dateoption=1&transaction=3&ledgeroption=1&curr=1&currbase1=0&currbase2=0&cum=0&alltypes=0&exclude=0&jvtype=&showunposted=0&prtfolio=1&prtref=1&prtdesc=1&prtvaluedate=1&prtjvtype=0&prtcostcent=0&prtproject=0&prevbal=1&dtjv=0&dtdate=1&checks=1&cltcst=&cltprj=&parentprj=0&prtaging=0&prtheader=1&prtcstjour=0&prtwording=0&salesman=&prtwnac=0&varprtbreak=1');
	win.creator = self;
	win.focus();
}
	
	
</script>

<script type="text/javascript">
//var indx = document.journal.lastinputrow.value;
var tabberOptions = {
  'manualStartup':true,
  'onClick': function(argsObj) {

    var t = argsObj.tabber; /* Tabber object */
    var id = t.id; /* ID of the main tabber DIV */
    var i = argsObj.index; /* Which tab was clicked (0 is the first tab) */
    var e = argsObj.event; /* Event object */
	
	if (id == 'tab1') document.getElementById('PTabIndex').value = i;
  },

  /* Optional: set an ID for each tab navigation link */
  'addLinkId': true
};

</script>
<script type="text/javascript" language="javascript">
//var indx = document.journal.lastinputrow.value;

function CheckFields(ModuleRestProj, ModuleRestCost, ModuleProj, ModuleCost){
  
    x = document.journal;
	
	var vJourDate = x.txtJourDate.value;
	var vJourType = x.txtJourType.value;
	var vJourProject    = x.txtProjectCode.value;
	var vJourCostCenter = x.txtCostCentCode.value;
	
	if (vJourDate=='' )
	{
		alert("Date is mandatory!");
		x.txtJourDate.focus();
		return 0;
	}
	else if (vJourType=='')
	{
		alert("Journal Type is mandatory!");
		x.txtJourType.focus();
		return 0;
	}
	else if (vJourProject=='' && ModuleRestProj==1 && ModuleProj==1)
	{
		alert("Project is mandatory!");
		x.txtProjectCode.focus();
		return 0;
	}
	else if (vJourCostCenter=='' && ModuleRestCost==1 && ModuleCost==1)
	{
		alert("CostCenter is mandatory!");
		x.txtCostCentCode.focus();
		return 0;
	}
		
	
	
	return 1 ;	
}

function UploadDocuments(vform){

var TransId = document.journal.txtJourId.value;

win = window.open('UploadDocuments.php?vform='+vform+'&prqstid='+TransId, 'Upload', '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 CheckFieldsDt(PIndex){
  
    x = document.journal;
	
	var vAmount, vAmount1, vAmount1;
	
	vLedgerNo = document.getElementById('ledgernumber['+PIndex+']').value;
	vCurrCode = document.getElementById('currencycode['+PIndex+']').value;
	vAmount   = document.getElementById('journaldtamount['+PIndex+']').value;
	vAmount	  = vAmount.split(",").join("");
	//vAmount   = document.getElementById('journaldtamount['+PIndex+']').value;
	vAmount1  = document.getElementById('journaldtamount1['+PIndex+']').value;
	vAmount1	  = vAmount1.split(",").join("");
	vAmount2  = document.getElementById('journaldtamount2['+PIndex+']').value;
	vAmount2	  = vAmount2.split(",").join("");
	vJournaldt_desc  = document.getElementById('journaldtdesc['+PIndex+']').value;
	
	if (vAmount == '')  vAmount  = 0;
	if (vAmount1 == '') vAmount1 = 0;
	if (vAmount2 == '') vAmount2 = 0;
	

	if (vLedgerNo=='' )
	{
		alert("Ledger Number is mandatory!");
		document.getElementById('ledgernumber['+PIndex+']').focus();
		return 0;
	}
	else if (vJournaldt_desc=='' )
	{
		alert("Description is mandatory!");
		document.getElementById('journaldtdesc['+PIndex+']').focus();
		return 0;
	}
	else if (vCurrCode=='')
	{
		alert("Currency is mandatory!");
		document.getElementById('currencycode['+PIndex+']').focus();
		return 0;
	}
	// else if (vAmount*1 != vAmount/1 || vAmount < 0) {
	// 	alert('Amount should be a Numeric and Positive value.');
	// 	document.getElementById('journaldtamount['+PIndex+']').focus();
	// 	return 0;
	// }
	// else if (vAmount1*1 != vAmount1/1 || vAmount1 < 0) {
	// 	alert('Amount1 should be a Numeric and Positive value.');
	// 	document.getElementById('journaldtamount1['+PIndex+']').focus();
	// 	return 0;
	// }
	// else if (vAmount2*1 != vAmount2/1 || vAmount2 < 0) {
	// 	alert('Amount2 should be a Numeric and Positive value.');
	// 	document.getElementById('journaldtamount2['+PIndex+']').focus();
	// 	return 0;
	// }
	else if (vAmount==0 && vAmount1==0 && vAmount2==0)
	{
		alert("Amount is mandatory!");
		document.getElementById('journaldtamount['+PIndex+']').focus();
		return 0;
	}
	else	
		return 1 ;	
}


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

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

function CancelRecord(){
	x = document.journal;
	var vmode  = x.mainaction.value;
	var vmode1 = x.actionmode.value;
	var JourId = x.txtJourId.value;
		
	if (confirm ( "Are you sure you want to Delete current pending Transaction permenantly?"))
	{
		x.action="Form_Journal_Actions.php?mode=cancel&mainmode="+vmode+"&SJourId="+JourId;
		x.submit();
	}
    
}



function PostChanges(ModuleRestProj, ModuleRestCost, ModuleProj, ModuleCost) {
	x = document.journal;
	var vJourId     = x.txtJourId.value;
	var vMainMode   = x.mainaction.value;
	var result = CheckFields(ModuleRestProj, ModuleRestCost, ModuleProj, ModuleCost);
	
	var vJourAmtBal1 = roundNumber(x.txtJourBalance1.value,0);
	var vJourAmtBal2 = roundNumber(x.txtJourBalance2.value,0);
	
	
	if (x.txtCountDetail.value == 0 || x.txtCountDetail.value == '') {
		alert('Save not allowed. Please add Details.');
	}
	else if (vJourAmtBal1 != 0 || vJourAmtBal2 != 0) {
		alert('Save not allowed. Please check for Balances.');
	}
	else {
	
		if (result == 1) {
			if (confirm ( "Are you sure you want to Save current Transaction?"))
			{
				//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 {
					x.btnPost.disabled = true;
					x.btnCancel.disabled = true;
					x.btnClear.disabled = true;
					
					
					x.actionmode.value='post';
					x.action="Form_Journal_Actions.php?mode=post&mainmode="+vMainMode+"&SJourId="+vJourId;
					x.submit();
				}	
			}
		}
	}	
}

function ImportExcel(ModuleRestProj, ModuleRestCost, ModuleProj, ModuleCost) {
	
	x = document.journal;
	var vJourId     = x.txtJourId.value;
	var vMainMode   = x.mainaction.value;
	
	var result = CheckFields(ModuleRestProj, ModuleRestCost, ModuleProj, ModuleCost);
	
		
	var vMode = 'importexcel';
	var  the_data = 'mode='+vMode+
					'&mainmode='+x.mainaction.value+
					'&SJourId='+x.txtJourId.value+
					'&PJourId='+x.txtJourId.value+
					'&PJourDate='+x.txtJourDate.value+
					'&PJourType='+x.txtJourType.value+
					'&PRemark='+encodeURIComponent(x.txtRemark.value)+
					'&PManualNo='+encodeURIComponent(x.txtManualNo.value)+
					'&PProjectCode='+x.txtProjectCode.value+
					'&PCostCentCode='+x.txtCostCentCode.value;
					
						
	if (result == 1) {
		x.action="Form_Journal_Actions.php?"+the_data;
		x.submit();		
	}
	
}

function DeleteRecordGrid(filepath,formname,transid,JourDtId,index,dftorderby,orderby,morelines,startrange,perpage,direction) {
	x = document.journal;
	var vJourId   = x.txtJourId.value;
	var vMainMode = x.mainaction.value;
	var vDelMsg   = 'Are you sure you want to delete this record?';

	
	if (confirm ( vDelMsg ))
	{
		var xmlhttp = getXMLHttpRequest();	
		$("#Loader").addClass("ajaxsaving");
		
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				var data = $.parseJSON(xmlhttp.responseText);
					
				var msg = data[0].message;
					
				if (msg != "") {
					$("#Loader").removeClass("ajaxsaving");
					alert(decodeURIComponent(msg));
				} else {
					ReloadGrid(filepath,formname,transid,'datagrid',index,dftorderby,'DEL',orderby,morelines,startrange,perpage,0,direction);			
					ReloadGridDt(filepath,'JV-TOT','TOTALS','totals',transid,-1);
				}
			}
		}
	
		xmlhttp.open("GET","Form_Journal_Actions.php?mode=deletedt&mainmode="+vMainMode+"&SJourId="+vJourId+"&SJourDtId="+JourDtId);
		xmlhttp.send();
	}	

}

function SubmitRecordGrid(PIndex,filepath,formname,transid,dftorderby,orderby,morelines,startrange,perpage,direction,ModuleRestProj,ModuleRestCost, ModuleProj, ModuleCost,NextField,Motion,TabIndex) {
	
	x = document.journal;
	
	var JourDtId   = document.getElementById('jourdtid['+PIndex+']').value;
	if (JourDtId == '') vMode = 'submitrecord-ajax';	
	else vMode = 'editdt-ajax';	
	
	var result = 1;
	result = CheckFields(ModuleRestProj, ModuleRestCost, ModuleProj, ModuleCost);
	
	if (result == 1) {
		var result = CheckFieldsDt(PIndex);
	}
	
	var activity = document.getElementById('journaldtactivity['+PIndex+']').value;
	
	if(document.getElementById('journaldtrate['+PIndex+']'))
	var journaldtrate = document.getElementById('journaldtrate['+PIndex+']').value;	
	else var journaldtrate=0;
	
	if(document.getElementById('journaldtrate2['+PIndex+']'))
	var journaldtrate2 = document.getElementById('journaldtrate2['+PIndex+']').value;
	else var journaldtrate2=0;
	
	var ChecksNo = 0;
	if (x.ChecksNo)
		ChecksNo = x.ChecksNo.value;
	
	var vChecksNo=0;
	if (x.vChecksNo)
		vChecksNo = x.vChecksNo.value; 
	
	vAmount	  = document.getElementById('journaldtamount['+PIndex+']').value;
	vAmount	  = vAmount.split(",").join("");
	vAmount1	  = document.getElementById('journaldtamount1['+PIndex+']').value;
	vAmount1	  = vAmount1.split(",").join("");
	vAmount2	  = document.getElementById('journaldtamount2['+PIndex+']').value;
	vAmount2	  = vAmount2.split(",").join("");
	//alert(vAmount);
	//alert(vAmount1);
	//alert(vAmount2);
	
	var  the_data = 'mode='+vMode+
					'&mainmode='+x.mainaction.value+
					'&SJourId='+x.txtJourId.value+
					'&PJourId='+x.txtJourId.value+
					'&PJourDate='+x.txtJourDate.value+
					'&PJourType='+x.txtJourType.value+
					'&PRemark='+encodeURIComponent(x.txtRemark.value)+
					'&PManualNo='+encodeURIComponent(x.txtManualNo.value)+
					'&PProjectCode='+x.txtProjectCode.value+
					'&PCostCentCode='+x.txtCostCentCode.value+
					'&SJourDtId='+document.getElementById('jourdtid['+PIndex+']').value+
					'&txtLedgerNo='+document.getElementById('ledgernumber['+PIndex+']').value+
					'&txtCurrencyCode='+document.getElementById('currencycode['+PIndex+']').value+
					'&txtJourDtdbcd='+document.getElementById('journaldtdbcd['+PIndex+']').value+
					'&txtJourDtDesc='+encodeURIComponent(document.getElementById('journaldtdesc['+PIndex+']').value)+
					'&txtJourDtDesc1='+encodeURIComponent(document.getElementById('journaldtdesc1['+PIndex+']').value)+
					'&txtValueDate='+document.getElementById('journaldtvaluedate['+PIndex+']').value+
					'&txtJourDtManualNo='+encodeURIComponent(document.getElementById('journaldtmanualno['+PIndex+']').value)+
					'&txtJourDtAmount='+vAmount+
					'&txtJourDtAmount1='+vAmount1+
					'&txtJourDtAmount2='+vAmount2+"&txtjournaldtrate="+journaldtrate
					+"&txtjournaldtrate2="+journaldtrate2+'&ChecksNo='+ChecksNo+'&vChecksNo='+vChecksNo+'&journaldtdistcode='+document.getElementById('journaldtdistcode['+PIndex+']').value;
					
	
	if (result == 1) {
		var xmlhttp = getXMLHttpRequest();	
		var getdate = new Date();  //Used to prevent caching during ajax call
  
		$("#Loader").addClass("ajaxsaving");
		
		
		var SubBtnID = 'imgSubmit['+PIndex+']';
		if (document.getElementById(SubBtnID))	document.getElementById(SubBtnID).disabled = true;
		
		if(xmlhttp) {
			//xmlhttp.open("POST", "Form_Journal_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;
							if(x.ChecksNo) 
							x.ChecksNo.value = 0;
						
							if(x.vChecksNo) 
								x.vChecksNo.value = 0;
														
							x.txtJourId.value = transid;
							x.submit();
						} 
						
                        if(x.ChecksNo) 
							x.ChecksNo.value = 0;
						
						if(x.vChecksNo) 
							x.vChecksNo.value = 0;
						
						
						var index = parseInt(PIndex) + 1;
						var nextcell = 'ledgernumber['+index+']';
						
						createCookie('jv-nextcell',nextcell);
						createCookie('trs-index',index);
						
						ReloadGrid(filepath,formname,transid,'datagrid',PIndex,dftorderby,'ADD',orderby,morelines,startrange,perpage,0,direction,function() {
						

						if(Motion==1 && JourDtId == ''){ //case on insert to move back to the inserted row and then go to next grid
								var lastindex = index - 1;
								
								
								var lastcell = 'ledgernumber['+lastindex+']';
								MoveNextRecord(lastcell);
							
								if (document.getElementById('CurRec'+lastindex))
									document.getElementById('CurRec'+lastindex).click();
									
							}
							
							if(Motion==0){ //case motion is false
								MoveNextRecord(nextcell);
								if (document.getElementById('CurRec'+index))
									document.getElementById('CurRec'+index).click();
							}
							
							if(Motion==1){ ////maroun grid motion case motion is true
									var done = false;
									//alert (NextField);
									while (!done){
										if(document.getElementById(NextField)) {
											document.getElementById('tab1').tabber.tabShow(TabIndex);//opn the tab
											document.getElementById(NextField).focus();
											done= true;
										}
									}
							}
							
							//document.getElementById('CurRec'+index).click();
							if (activity == '') activity = 1;
							if (NextField != 'projectcodedt[0]' && NextField != 'costcentcodedt[0]' && (activity == '1' || activity == '2')){
								if (activity == 1) NextField = 'projectcodedt[0]';
								else NextField = 'chkjournumber[0]'; 
								document.getElementById('tab1').tabber.tabShow(1);//opn the tab
									
									if(document.getElementById(nextcell)) {
										document.getElementById(nextcell).focus();
									}
									/*if(document.getElementById(NextField)) {
										document.getElementById(NextField).focus();
								}*/
							}
							else if (NextField != 'projectcodedt[0]' && NextField != 'costcentcodedt[0]' && (activity == 3 || activity == 4)){
								NextField = 'billjournumber[0]';
								document.getElementById('tab1').tabber.tabShow(TabIndex);//opn the tab
								
								if(document.getElementById(nextcell)) {
										document.getElementById(nextcell).focus();
								}
								/*	if(document.getElementById(NextField)) {
										document.getElementById(NextField).focus();
								}*/
							}
							if (document.getElementById('RecIndex_G1')) 
									document.getElementById('RecIndex_G1').value = parseInt(index) - 1;
									
							MoveNextRecord(nextcell);
							//MoveNextRecord(NextField); 
							
							ReloadGridDt(filepath,'JV-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);
			//alert(the_data);
			xmlhttp.open("GET","Form_Journal_Actions.php?"+the_data);
			xmlhttp.send();
			
		}
	}	
}



function SetRecordGridDefaults(PIndex) {
	x = document.journal;
	
	document.getElementById('journaldtmanualno['+PIndex+']').value = x.txtManualNo.value;

}

function LoadDetails(filepath,formname,action,gridid,transid,transdtid,Pindex) {

	 var vFormName, vGridId;
		if (document.getElementById('RecIndex_G1')) 
			document.getElementById('RecIndex_G1').value = Pindex;
			

	vGridId = gridid + '-d';
	if (document.getElementById(vGridId)) {
		ReloadGridDt(filepath,'JV-D',action,vGridId,transid,transdtid,function() {
			if (transdtid == -1) {	
				//Disable Sub Detail Grids
				$('#tab1 :input').attr('disabled', true);
			}
		});
	}
	
	vGridId = gridid + '-b';
	if (document.getElementById(vGridId)) {
		ReloadGridDt(filepath,'JV-B',action,vGridId,transid,transdtid);
	}	
	
	vGridId = gridid + '-c';
	if (document.getElementById(vGridId)) {
		ReloadGridDt(filepath,'JV-C',action,vGridId,transid,transdtid);
	}	
	 
	
}


function DeleteChkJour(filepath,formname,action,gridid,transid,transdtid,ChkJourId) {
	x = document.journal;
	var vJourId   = x.txtJourId.value;
	var vMainMode = x.mainaction.value;
	var vDelMsg   = 'Are you sure you want to delete this record?';

	
	if (confirm ( vDelMsg ))
	{
		var xmlhttp = getXMLHttpRequest();	
		$("#Loader_G3").addClass("ajaxsaving");
		
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				{ 
					ReloadGridDt(filepath,formname,action,gridid,transid,transdtid);			
				}
			}
		}
	
		xmlhttp.open("GET","Form_Journal_Actions.php?mode=deletechkjour&mainmode="+vMainMode+"&SJourId="+vJourId+"&SJourDtId="+transdtid+"&SChkJourId="+ChkJourId);
		xmlhttp.send();
	}	

}

function SubmitChkJour(PIndex,filepath,formname,action,gridid,transid,transdtid) {
	
	x = document.journal;
	
	//var result = CheckFieldsDt(PIndex);
	var result = 1;
	
	var ChkJourId   = document.getElementById('chkjourid['+PIndex+']').value;
	if (ChkJourId == '') vMode = 'insertchkjour';	
	else vMode = 'editchkjour';	

	var vCheckNo       = document.getElementById('chkjournumber['+PIndex+']').value;
	var vBankName      = document.getElementById('chkjourbank['+PIndex+']').value;
	var vChkJourAmt    = document.getElementById('chkjouramount['+PIndex+']').value;
	var vChkJourAmt1   = document.getElementById('chkjouramount1['+PIndex+']').value;
	var vChkJourAmt2   = document.getElementById('chkjouramount2['+PIndex+']').value;
	var vChkJourBalAmt = document.getElementById('chkjourbalamt['+PIndex+']').value;
	var vChkJourAmtH   = document.getElementById('chkjouramount_h['+PIndex+']').value;
	
	if (vChkJourAmt == '')    vChkJourAmt = 0;
	if (vChkJourAmt1 == '')   vChkJourAmt1 = 0;
	if (vChkJourAmt2 == '')   vChkJourAmt2 = 0;
	if (vChkJourBalAmt == '') vChkJourBalAmt = 0;
	if (vChkJourAmtH == '')   vChkJourAmtH = 0;
	
	vChkJourAmt    = parseFloat(vChkJourAmt);
	vChkJourAmt1   = parseFloat(vChkJourAmt1);
	vChkJourAmt2   = parseFloat(vChkJourAmt2);
	vChkJourBalAmt = parseFloat(vChkJourBalAmt);
	vChkJourAmtH   = parseFloat(vChkJourAmtH);
	
	var vMandatoryFields=x.mandatoryfields_d2.value;
	var vFieldsArray = vMandatoryFields.split(",");

	
	if (vCheckNo=='' )
	{
		alert("Check Number is mandatory!");
		document.getElementById('chkjournumber['+PIndex+']').focus();
		return 0;
	}
	else if (vBankName=='')
	{
		alert("Bank is mandatory!");
		document.getElementById('chkjourbank['+PIndex+']').focus();
		return 0;
	}	
	else if (vChkJourBalAmt == 0) {
		alert('Invalid Amount, Balance is zero. ');
		document.getElementById('chkjouramount['+PIndex+']').focus();
		return false;
	}
	if (vChkJourAmtH > vChkJourBalAmt && vChkJourBalAmt != 0) {
		alert('Amount must be less than or equal to Balance: '+vChkJourBalAmt);
		document.getElementById('chkjouramount['+PIndex+']').focus();
		return false;
	}
	else if (vChkJourAmt==0 && vChkJourAmt1==0 && vChkJourAmt2==0) {
		alert('Amount/Amount1/Amoun2 must be Greater than Zero.');
		document.getElementById('chkjouramount['+PIndex+']').focus();
		return false;
	}


	var  the_data = 'mode='+vMode+
					'&mainmode='+x.mainaction.value+
					'&SJourId='+x.txtJourId.value+
					'&SJourDtId='+transdtid+
					'&SChkJourId='+document.getElementById('chkjourid['+PIndex+']').value+
					'&txtChkJourCurrCode='+document.getElementById('chkjourcurrcode['+PIndex+']').value+
					'&txtChkJourLedgerNo='+document.getElementById('chkjourledgerno['+PIndex+']').value+
					'&txtChkJourType='+document.getElementById('chkjourtype['+PIndex+']').value+
					'&txtChkJourNumber='+encodeURIComponent(document.getElementById('chkjournumber['+PIndex+']').value)+
					'&txtChkJourBank='+encodeURIComponent(document.getElementById('chkjourbank['+PIndex+']').value)+
					'&txtChkJourValueDate='+document.getElementById('chkjourvaluedate['+PIndex+']').value+
					'&txtChkJourAmount='+document.getElementById('chkjouramount_h['+PIndex+']').value+
					'&txtChkJourAmount1='+document.getElementById('chkjouramount1_h['+PIndex+']').value+
					'&txtChkJourAmount2='+document.getElementById('chkjouramount2_h['+PIndex+']').value;
					
	
	if (result == 1) {
		var xmlhttp = getXMLHttpRequest();	
		var getdate = new Date();  //Used to prevent caching during ajax call
  
		$("#Loader_G3").addClass("ajaxsaving");
		var SubBtnID = 'imgSubmit_C['+PIndex+']';
			if (document.getElementById(SubBtnID)) document.getElementById(SubBtnID).disabled=true;
		
		if(xmlhttp) { 
			xmlhttp.open("POST", "Form_Journal_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_G3").removeClass("ajaxsaving");
						if (document.getElementById(SubBtnID)) document.getElementById(SubBtnID).disabled=false;
						alert(decodeURIComponent(msg));
					} else {	
							
						var index = parseInt(PIndex) + 1;
						var nextcell = 'chkjournumber['+index+']';
						ReloadGridDt(filepath,formname,action,gridid,transid,transdtid,function() {
							MoveNextRecord(nextcell);
						});
						
						document.getElementById('ModRec_G3').value = "";
					}
				}
			}
			
			// adds  a header to tell the PHP script to recognize the data as is sent via POST
			//alert(the_data);
			xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			xmlhttp.send(the_data);
			
		}
	}
}

function DeleteBillJour(filepath,formname,action,gridid,transid,transdtid,BillJourId) {
	x = document.journal;
	var vJourId   = x.txtJourId.value;
	var vMainMode = x.mainaction.value;
	var vDelMsg   = 'Are you sure you want to delete this record?';

	
	if (confirm ( vDelMsg ))
	{
		var xmlhttp = getXMLHttpRequest();	
		$("#Loader_G4").addClass("ajaxsaving");
		
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				{ 
					ReloadGridDt(filepath,formname,action,gridid,transid,transdtid);			
				}
			}
		}
	
		xmlhttp.open("GET","Form_Journal_Actions.php?mode=deletebilljour&mainmode="+vMainMode+"&SJourId="+vJourId+"&SJourDtId="+transdtid+"&SBillJourId="+BillJourId);
		xmlhttp.send();
	}	

}

function SubmitBillJour(PIndex,filepath,formname,action,gridid,transid,transdtid) {
	
	x = document.journal;
	
	//var result = CheckFieldsDt(PIndex);
	var result = 1;
	
	var BillJourId   = document.getElementById('billjourid['+PIndex+']').value;
	if (BillJourId == '') vMode = 'insertbilljour';	
	else vMode = 'editbilljour';	

	var vBillNo         = document.getElementById('billjournumber['+PIndex+']').value;
	var vBankName       = document.getElementById('billjourbank['+PIndex+']').value;
	var vBillJourAmt    = document.getElementById('billjouramount['+PIndex+']').value;
	var vBillJourAmt1   = document.getElementById('billjouramount1['+PIndex+']').value;
	var vBillJourAmt2   = document.getElementById('billjouramount2['+PIndex+']').value;
	var vBillJourBalAmt = document.getElementById('billjourbalamt['+PIndex+']').value;
	var vBillJourAmtH    = document.getElementById('billjouramount_h['+PIndex+']').value;
	
	if (vBillJourAmt == '')    vBillJourAmt = 0;
	if (vBillJourAmt1 == '')   vBillJourAmt1 = 0;
	if (vBillJourAmt2 == '')   vBillJourAmt2 = 0;
	if (vBillJourBalAmt == '') vBillJourBalAmt = 0;
	if (vBillJourAmtH == '')   vBillJourAmtH = 0;
	
	vBillJourAmt    = parseFloat(vBillJourAmt);
	vBillJourAmt1   = parseFloat(vBillJourAmt1);
	vBillJourAmt2   = parseFloat(vBillJourAmt2);
	vBillJourBalAmt = parseFloat(vBillJourBalAmt);
	vBillJourAmtH   = parseFloat(vBillJourAmtH);
	
	var vMandatoryFields=x.mandatoryfields_d3.value;
	var vFieldsArray = vMandatoryFields.split(",");

	
	if (vBillNo=='' )
	{
		alert("Check Number is mandatory!");
		document.getElementById('billjournumber['+PIndex+']').focus();
		return 0;
	}
	else if (vBankName=='')
	{
		alert("Bank is mandatory!");
		document.getElementById('billjourbank['+PIndex+']').focus();
		return 0;
	}	
	else if (vBillJourBalAmt == 0) {
		alert('Invalid Amount, Balance is zero. ');
		document.getElementById('billjouramount['+PIndex+']').focus();
		return false;
	}
	if (vBillJourAmtH > vBillJourBalAmt && vBillJourBalAmt != 0) {
		alert('Amount must be less than or equal to Balance: '+vBillJourBalAmt);
		document.getElementById('billjouramount['+PIndex+']').focus();
		return false;
	}
	else if (vBillJourAmt==0 && vBillJourAmt1==0 && vBillJourAmt2==0) {
		alert('Amount/Amount1/Amoun2 must be Greater than Zero.');
		document.getElementById('billjouramount['+PIndex+']').focus();
		return false;
	}


	var  the_data = 'mode='+vMode+
					'&mainmode='+x.mainaction.value+
					'&SJourId='+x.txtJourId.value+
					'&SJourDtId='+transdtid+
					'&SBillJourId='+document.getElementById('billjourid['+PIndex+']').value+
					'&txtBillJourCurrCode='+document.getElementById('billjourcurrcode['+PIndex+']').value+
					'&txtBillJourLedgerNo='+document.getElementById('billjourledgerno['+PIndex+']').value+
					'&txtBillJourType='+document.getElementById('billjourtype['+PIndex+']').value+
					'&txtBillJourNumber='+encodeURIComponent(document.getElementById('billjournumber['+PIndex+']').value)+
					'&txtBillJourBank='+encodeURIComponent(document.getElementById('billjourbank['+PIndex+']').value)+
					'&txtBillJourValueDate='+document.getElementById('billjourvaluedate['+PIndex+']').value+
					'&txtBillJourAmount='+document.getElementById('billjouramount_h['+PIndex+']').value+
					'&txtBillJourAmount1='+document.getElementById('billjouramount1_h['+PIndex+']').value+
					'&txtBillJourAmount2='+document.getElementById('billjouramount2_h['+PIndex+']').value;
					
	
	if (result == 1) {
		var xmlhttp = getXMLHttpRequest();	
		var getdate = new Date();  //Used to prevent caching during ajax call
  
		$("#Loader_G4").addClass("ajaxsaving");
		var SubBtnID = 'imgSubmit_B['+PIndex+']';
			if (document.getElementById(SubBtnID)) document.getElementById(SubBtnID).disabled=true;
		
		if(xmlhttp) { 
			xmlhttp.open("POST", "Form_Journal_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_G4").removeClass("ajaxsaving");
						if (document.getElementById(SubBtnID)) document.getElementById(SubBtnID).disabled=false;
						alert(decodeURIComponent(msg));
					} else {	
							
						var index = parseInt(PIndex) + 1;
						var nextcell = 'billjournumber['+index+']';
						ReloadGridDt(filepath,formname,action,gridid,transid,transdtid,function() {
							MoveNextRecord(nextcell);
						});
						
						document.getElementById('ModRec_G4').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);
			
		}
	}
}

function DeleteDivisionDt(filepath,formname,action,gridid,transid,transdtid,cstjourId) {
	x = document.journal;
	var vJourId   = x.txtJourId.value;
	var vMainMode = x.mainaction.value;
	var vDelMsg   = 'Are you sure you want to delete this record?';

	
	if (confirm ( vDelMsg ))
	{
		var xmlhttp = getXMLHttpRequest();	
		$("#Loader_G2").addClass("ajaxsaving");
		
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				{ 
					ReloadGridDt(filepath,formname,action,gridid,transid,transdtid);
				}
			}
		}
	
		xmlhttp.open("GET","Form_Journal_Actions.php?mode=deletedivisiondt&mainmode="+vMainMode+"&SJourId="+vJourId+"&SJourDtId="+transdtid+"&SCstJourId="+cstjourId);
		xmlhttp.send();
	}	

}

function SubmitDivisionDt(PIndex,filepath,formname,action,gridid,transid,transdtid,NextField,Motion,TabIndex,down) {
	
	x = document.journal;
	
	//var result = CheckFieldsDt(PIndex);
	var result = 1;
	
	var CstJourId   = document.getElementById('cstjourid['+PIndex+']').value;
	if (CstJourId == '') vMode = 'insertdivisiondt';	
	else vMode = 'editdivisiondt';	

	var vProjectCode  = document.getElementById('projectcodedt['+PIndex+']').value;
	var vCostCentCode = document.getElementById('costcentcodedt['+PIndex+']').value;
	var vAmount       = document.getElementById('cstjouramount['+PIndex+']').value;
	var vAmount1      = document.getElementById('cstjouramount1['+PIndex+']').value;
	var vAmount2      = document.getElementById('cstjouramount2['+PIndex+']').value;
	var vBalanceAmt   = document.getElementById('cstjourbalamt['+PIndex+']').value;
	var vPerc	      = document.getElementById('cstjourperc['+PIndex+']').value;
	var vAmountH      = document.getElementById('cstjouramount_h['+PIndex+']').value;
	
	
	if (vAmount == '')     vAmount = 0;
	if (vAmount1 == '')    vAmount1 = 0;
	if (vAmount2 == '')    vAmount2 = 0;
	if (vBalanceAmt == '') vBalanceAmt = 0;
	if (vAmountH == '')    vAmountH = 0;
	
	vAmount     = parseFloat(vAmount);
	vAmount1    = parseFloat(vAmount1);
	vAmount2    = parseFloat(vAmount2);
	vBalanceAmt = parseFloat(vBalanceAmt);
	vAmountH    = parseFloat(vAmountH);
	
	if (vProjectCode=='' && document.getElementById('projectcodedt['+PIndex+']').type != 'hidden')
	{
		alert("Project Code is mandatory!");
		document.getElementById('projectcodedt['+PIndex+']').focus();
		return 0;
	}
	else if (vCostCentCode=='' && document.getElementById('costcentcodedt['+PIndex+']').type != 'hidden')
	{
		alert("CostCenter Code is mandatory!");
		document.getElementById('costcentcodedt['+PIndex+']').focus();
		return 0;
	}	
	else if (vBalanceAmt == 0) {
		alert('Invalid Amount, Balance is zero. ');
		document.getElementById('cstjouramount['+PIndex+']').focus();
		return false;
	}
	else if (vAmountH > vBalanceAmt && vBalanceAmt != 0) {
		alert('Amount must be less than or equal to Balance: '+vBalanceAmt);
		document.getElementById('cstjouramount['+PIndex+']').focus();
		return false;
	}
	else if (vAmount==0 && vAmount1==0 && vAmount2==0) {
		alert('Amount/Amount1/Amoun2 must be Greater than Zero.');
		document.getElementById('cstjouramount['+PIndex+']').focus();
		return false;
	}
	else if ( vPerc <= 0 || vPerc > 100 ) {
		alert('Percentage ('+vPerc+') should be a NUMERIC and BETWEEN 1 and 100 . ');
		document.getElementById('cstjourperc['+PIndex+']').focus();
		return false;
	}
	var per = true;
	var totalpercentage = 0;
	for (var i = 0; per; i++){
		if (document.getElementById('cstjourperc['+i+']')){
			totalpercentage += parseFloat(document.getElementById('cstjourperc['+i+']').value);
		}
		else {
			per = false;
		}
	}

	var  the_data = 'mode='+vMode+
					'&mainmode='+x.mainaction.value+
					'&SJourId='+x.txtJourId.value+
					'&SJourDtId='+transdtid+
					'&SCstJourId='+document.getElementById('cstjourid['+PIndex+']').value+
					'&txtProjectCodeDt='+document.getElementById('projectcodedt['+PIndex+']').value+
					'&txtCostCentCodeDt='+document.getElementById('costcentcodedt['+PIndex+']').value+
					'&txtCstJourPerc='+document.getElementById('cstjourperc['+PIndex+']').value+
					'&txtCstJourAmount='+document.getElementById('cstjouramount_h['+PIndex+']').value+
					'&txtCstJourAmount1='+document.getElementById('cstjouramount1_h['+PIndex+']').value+
					'&txtCstJourAmount2='+document.getElementById('cstjouramount2_h['+PIndex+']').value;
	
	
	if (result == 1) {
		var xmlhttp = getXMLHttpRequest();	
		var getdate = new Date();  //Used to prevent caching during ajax call
  
		$("#Loader_G2").addClass("ajaxsaving");
		var SubBtnID = 'imgSubmit_D['+PIndex+']';
		if (document.getElementById(SubBtnID)) document.getElementById(SubBtnID).disabled=true;
		
		if(xmlhttp) { 
			xmlhttp.open("POST", "Form_Journal_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_G2").removeClass("ajaxsaving");
						if (document.getElementById(SubBtnID)) document.getElementById(SubBtnID).disabled=false;
						
						alert(decodeURIComponent(msg));
					} else {	
							
						var index = parseInt(PIndex) + 1;
						
						if (document.getElementById('projectcodedt['+PIndex+']').type != 'hidden')
							var nextcell = 'projectcodedt['+index+']';
						else var nextcell = 'costcentcodedt['+index+']';	
						
						if (totalpercentage == 100){
							var i = 0;
							for (i = 0; document.getElementById('ledgernumber['+i+']'); i++){}
							i--;
							nextcell = 'ledgernumber['+i+']';
						}
							
						
						 ReloadGridDt(filepath,formname,action,gridid,transid,transdtid,function() {
							//MoveNextRecord(nextcell);
							
							 if(Motion==1 && transdtid == '' && down==0){ //case on insert to move back to the inserted row and then go to next grid
								var lastindex = index - 1;
								var lastcell = 'ledgernumber['+lastindex+']';
								MoveNextRecord(lastcell);
								
								if (document.getElementById('CurRec_G1'+lastindex))
									document.getElementById('CurRec_G1'+lastindex).click();
									
							} 
							
							 //stopped by nadine
							  if(Motion==0 || down==1){ //case motion is false
								 MoveNextRecord(nextcell);
							 } 
							
							 if(Motion==1  && down==0){ ////maroun grid motion case motion is true
							
							
								document.getElementById('tab1').tabber.tabShow(TabIndex);//opn the tab
									if(document.getElementById(NextField)) {
										
										document.getElementById(NextField).focus();
								}		
							} 
							
							
						}); 
						
						document.getElementById('ModRec_G2').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);
			
		}
	}
}

function ClearDivision(Option,PIndex,PIndex1) {
	x = document.journal;
	
	if (Option == 'H') {
		document.getElementById('cstjourid['+PIndex+']').value = '';
		document.getElementById('projectcode['+PIndex+']').value = '';
		document.getElementById('costcentcode['+PIndex+']').value = '';
	}
	else if (Option == 'D') {
		document.getElementById('cstjourid['+PIndex+']['+PIndex1+']').value = '';
		document.getElementById('projectcodedt['+PIndex+']['+PIndex1+']').value = '';
		document.getElementById('costcentcodedt['+PIndex+']['+PIndex1+']').value = '';
	}	
	
	//x.submit();

}

function CheckPercentage(PercID, BalID) {
	x=document.journal;
	var vPer=0, vPerBal=0;
	
	if (document.getElementById(PercID).value != "")
		vPer = parseFloat(document.getElementById(PercID).value);
		
	if (document.getElementById(BalID).value != "")
		vPerBal = parseFloat(document.getElementById(BalID).value);	

	
	if ( vPer < 0) {
		alert('Percentage should be a Numeric and Positive value.');
		document.getElementById(PercID).focus();
		return (false);
	}
	else if (vPer > vPerBal) {
		alert('Percentage must be less than or equal to '+vPerBal);
		document.getElementById(PercID).focus();
		return (false);
	}
	
	return (true);
}

// function CheckAmount(tagID) {
// 	x=document.journal;
// 	var vAmount = 0;
	
// 	if (document.getElementById(tagID).value != "")
// 		vAmount = document.getElementById(tagID).value;
		
	
// 	if ( vAmount < 0) {
// 		document.getElementById(tagID).value='';
// 		document.getElementById(tagID).focus();
// 		alert('Amount should be a Numeric and Positive value.');
		
// 	} 
// }
function CheckAmount(tagID) {
	x=document.journal;
	var vAmount = 0;
	
	if (document.getElementById(tagID).value != "")
		vAmount = document.getElementById(tagID).value;
	
    vAmount = vAmount.split(",").join("");	
	// here you should change
	if (vAmount*1 != vAmount/1 || vAmount < 0) {
		document.getElementById(tagID).value='';
		document.getElementById(tagID).value='';
		document.getElementById(tagID).focus();
		alert('Amount should be a Numeric and Positive value.');
		
	} 
}

function SetAmount(option, dec1, dec2, curr, currbase1, currbase2, pdate, index) {

	var x=document.journal;
	var vAmount, vAmount1, vAmount2, vChkAmount, vChkAmount1, vChkAmount2, vBillAmount, vBillAmount1, vBillAmount2;
	pdate = document.getElementById("journaldate").value;
	dec1  = parseInt(dec1);
	dec2  = parseInt(dec2);
	
	var JourDtId  = document.getElementById('jourdtid['+index+']').value;
	
	console.log("did enter set amount");
	if (option == 1 || option == 2 || option == 3 || option == 4) {
		
		vAmount  = document.getElementById('journaldtamount['+index+']').value;
		vAmount	  = vAmount.split(",").join("");
		// here you should change
		vAmount1 = document.getElementById('journaldtamount1['+index+']').value;
		vAmount1	  = vAmount1.split(",").join("");

		vAmount2 = document.getElementById('journaldtamount2['+index+']').value;
		vAmount2	  = vAmount2.split(",").join("");
		if(document.getElementById("journaldtrate2["+index+"]"))
			vRate2 = 1;
		else vRate2 = 0;
		if(vRate2 == 0)
		vRate 	  = document.getElementById("journaldtrate["+index+"]").value;
		else vRate = 0;
		
		if (curr == '') curr = document.getElementById('currencycode['+index+']').value;
	
		if (vAmount == '')  vAmount = 0;
		if (vAmount1 == '') vAmount1 = 0;
		if (vAmount2 == '') vAmount2 = 0;
		
		vAmount  = parseFloat(vAmount);
		vAmount1 = parseFloat(vAmount1);
		vAmount2 = parseFloat(vAmount2);
	
		var vParamAmt  = vAmount;
		var vParamAmt1 = vAmount1;
	}
	else if (option == 5 || option == 6 || option == 7) {
	
		vChkAmount  = document.getElementById('chkjouramount['+index+']').value;
		vChkAmount	  = vChkAmount.split(",").join("");
		vChkAmount1 = document.getElementById('chkjouramount1['+index+']').value;
		vChkAmount1	  = vChkAmount1.split(",").join("");

		vChkAmount2 = document.getElementById('chkjouramount2['+index+']').value;
		vChkAmount2	  = vChkAmount2.split(",").join("");
		
		if (vChkAmount == '')  vChkAmount  = 0;
		if (vChkAmount1 == '') vChkAmount1 = 0;
		if (vChkAmount2 == '') vChkAmount2 = 0;
					
		
		
		vChkAmount  = parseFloat(vChkAmount);
		vChkAmount1 = parseFloat(vChkAmount1);
		vChkAmount2 = parseFloat(vChkAmount2);
	
		var vParamAmt = vChkAmount;
	}
	else if (option == 8 || option == 9 || option == 10) {
	
		vBillAmount  = document.getElementById('billjouramount['+index+']').value;
		vBillAmount	  = vBillAmount.split(",").join("");
		vBillAmount1 = document.getElementById('billjouramount1['+index+']').value;
		vBillAmount1	  = vBillAmount1.split(",").join("");
		vBillAmount2 = document.getElementById('billjouramount2['+index+']').value;
		vBillAmount2	  = vBillAmount2.split(",").join("");
		
		if (vBillAmount == '')  vBillAmount  = 0;
		if (vBillAmount1 == '') vBillAmount1 = 0;
		if (vBillAmount2 == '') vBillAmount2 = 0;
					
		
		
		vBillAmount  = parseFloat(vBillAmount);
		vBillAmount1 = parseFloat(vBillAmount1);
		vBillAmount2 = parseFloat(vBillAmount2);
	
		var vParamAmt = vBillAmount;
	}
	
	if(document.getElementById('journaldtrate['+index+']'))
	var vjourDtRate = document.getElementById('journaldtrate['+index+']').value;
	if(document.getElementById('journaldtrate2['+index+']'))
	var vjourDtRate2 = document.getElementById('journaldtrate2['+index+']').value;
	
	
	var xmlhttp = getXMLHttpRequest();
	
	xmlhttp.onreadystatechange=function()
	{
		if (xmlhttp.readyState==4 && xmlhttp.status==200)
		{
			{ 
				var data = $.parseJSON(xmlhttp.responseText);
				
				if (option == 1) {
		
					if (document.getElementById('journaldtamount_h[' + index + ']')) document.getElementById('journaldtamount_h[' + index + ']').value = vAmount;
					//alert('test');
					if (vAmount >= 0) { 
						vAmount1 = roundNumber(data[0].amount1, dec1);
						vAmount2 = roundNumber(data[0].amount2, dec2);
						
						//vAmount1 = data[0].amount1;
						//vAmount2 = data[0].amount2;
						//vAmount = data[0].amount;
						
						if (document.getElementById('journaldtamount[' + index + ']')) {
							document.getElementById('journaldtamount[' + index + ']').value = vAmount;
							formatFieldDigits(document.getElementById('journaldtamount[' + index + ']'));
						}
						// here you should call
						if (document.getElementById('journaldtamount_h[' + index + ']')){
							document.getElementById('journaldtamount_h[' + index + ']').value = data[0].amount;
							formatFieldDigits(document.getElementById('journaldtamount_h[' + index + ']'));

						}
						if (document.getElementById('journaldtamount1[' + index + ']')){
							document.getElementById('journaldtamount1[' + index + ']').value = vAmount1;
							formatFieldDigits(document.getElementById('journaldtamount1[' + index + ']'));

						}
						if (document.getElementById('journaldtamount1_h[' + index + ']')){
							document.getElementById('journaldtamount1_h[' + index + ']').value = data[0].amount1;
							formatFieldDigits(document.getElementById('journaldtamount1_h[' + index + ']'));

						}
						
						if (document.getElementById('journaldtamount2[' + index + ']')){
							document.getElementById('journaldtamount2[' + index + ']').value = vAmount2;
							formatFieldDigits(document.getElementById('journaldtamount2[' + index + ']'));

						}
						if (document.getElementById('journaldtamount2_h[' + index + ']')){
							document.getElementById('journaldtamount2_h[' + index + ']').value = data[0].amount2;
							formatFieldDigits(document.getElementById('journaldtamount2_h[' + index + ']'));

						}
							
					}	
				}	
				else if (option == 2) {
					//vAmount1 = vAmount1.split(",").join("");
					if (curr == currbase1 && vAmount1 >= 0) {
						if (document.getElementById('journaldtamount[' + index + ']')) document.getElementById('journaldtamount[' + index + ']').value = vAmount1; 
						if (document.getElementById('journaldtamount_h[' + index + ']')) document.getElementById('journaldtamount_h[' + index + ']').value = vAmount1;
						if (document.getElementById('journaldtamount1_h[' + index + ']')) document.getElementById('journaldtamount1_h[' + index + ']').value = vAmount1;
					}	
					else if (curr == currbase2 && vAmount1 >= 0) {
						if (document.getElementById('journaldtamount1_h[' + index + ']')) document.getElementById('journaldtamount1_h[' + index + ']').value = vAmount1;
					}
					else if (vAmount1 >= 0) {
						if (document.getElementById('journaldtamount1_h[' + index + ']')) document.getElementById('journaldtamount1_h[' + index + ']').value = vAmount1;
					}
				
				}
				else if (option == 3) {
					
					if (curr == currbase2 && vAmount2 >= 0) {
						if (document.getElementById('journaldtamount[' + index + ']')) document.getElementById('journaldtamount[' + index + ']').value = vAmount2;
						if (document.getElementById('journaldtamount_h[' + index + ']')) document.getElementById('journaldtamount_h[' + index + ']').value = vAmount2;
						if (document.getElementById('journaldtamount2_h[' + index + ']')) document.getElementById('journaldtamount2_h[' + index + ']').value = vAmount2;
					}	
					else if (curr == currbase1 && vAmount2 >= 0) {
						if (document.getElementById('journaldtamount2_h[' + index + ']')) document.getElementById('journaldtamount2_h[' + index + ']').value = vAmount2;
					}
					else if (vAmount1 >= 0) {
						if (document.getElementById('journaldtamount2_h[' + index + ']')) document.getElementById('journaldtamount2_h[' + index + ']').value = vAmount2;
					}

				}
				else if (option == 4) { //Case Change Currency
				    
					//alert('test');
					//vAmount1 = data[0].amount1;
					//vAmount2 = data[0].amount2;
					//vAmount = data[0].amount.split(",").join("");
					//alert(vAmount);
					if (curr == currbase1) {
						if (JourDtId != '') {
							vAmount2 = roundNumber(data[0].amount2, dec2);
						    //vAmount2 = data[0].amount2.split(",").join("");
							//vAmount = data[0].amount.split(",").join("");
							if (document.getElementById('journaldtamount1[' + index + ']')) document.getElementById('journaldtamount1[' + index + ']').value = vAmount;
							if (document.getElementById('journaldtamount1_h[' + index + ']')) document.getElementById('journaldtamount1_h[' + index + ']').value = vAmount;
						
							if (document.getElementById('journaldtamount2[' + index + ']')) document.getElementById('journaldtamount2[' + index + ']').value = vAmount2;
							if (document.getElementById('journaldtamount2_h[' + index + ']')) document.getElementById('journaldtamount2_h[' + index + ']').value = data[0].amount2;
						} else {
							if (document.getElementById('journaldtamount[' + index + ']')) document.getElementById('journaldtamount[' + index + ']').value = vAmount1;
							if (document.getElementById('journaldtamount_h[' + index + ']')) document.getElementById('journaldtamount_h[' + index + ']').value = document.getElementById('journaldtamount1_h[' + index + ']').value;
						}	
					}
					else if (curr == currbase2) {
						if (JourDtId != '') {
							vAmount1 = roundNumber(data[0].amount1, dec1);
						   //vAmount1 = data[0].amount1.split(",").join("");
						   //vAmount = data[0].amount.split(",").join("");
							if (document.getElementById('journaldtamount1[' + index + ']')) document.getElementById('journaldtamount1[' + index + ']').value = vAmount1;
							if (document.getElementById('journaldtamount1_h[' + index + ']')) document.getElementById('journaldtamount1_h[' + index + ']').value = data[0].amount1;
						
							if (document.getElementById('journaldtamount2[' + index + ']')) document.getElementById('journaldtamount2[' + index + ']').value = vAmount;
							if (document.getElementById('journaldtamount2_h[' + index + ']')) document.getElementById('journaldtamount2_h[' + index + ']').value = vAmount;
						} else {
							if (document.getElementById('journaldtamount[' + index + ']')) document.getElementById('journaldtamount[' + index + ']').value = vAmount2;
							if (document.getElementById('journaldtamount_h[' + index + ']')) document.getElementById('journaldtamount_h[' + index + ']').value = document.getElementById('journaldtamount2_h[' + index + ']').value;
						}	
					}
					else {
						if (JourDtId != '') {
							vAmount1 = roundNumber(data[0].amount1, dec1);
							vAmount2 = roundNumber(data[0].amount2, dec2);
							//vAmount1 = data[0].amount1.split(",").join("");
							//vAmount2 = data[0].amount1.split(",").join("");
							if (document.getElementById('journaldtamount1[' + index + ']')) document.getElementById('journaldtamount1[' + index + ']').value = vAmount1;
							if (document.getElementById('journaldtamount1_h[' + index + ']')) document.getElementById('journaldtamount1_h[' + index + ']').value = data[0].amount1;
							
							if (document.getElementById('journaldtamount2[' + index + ']')) document.getElementById('journaldtamount2[' + index + ']').value = vAmount2;
							if (document.getElementById('journaldtamount2_h[' + index + ']')) document.getElementById('journaldtamount2_h[' + index + ']').value = data[0].amount2;
						} else {
							//vAmount = roundNumber(data[0].amount, dec1);
						
							if (document.getElementById('journaldtamount[' + index + ']')) document.getElementById('journaldtamount[' + index + ']').value = vAmount;
							if (document.getElementById('journaldtamount_h[' + index + ']')) document.getElementById('journaldtamount_h[' + index + ']').value = data[0].amount;
						}	
					}
				}
				else if (option == 5) {
		
					if (document.getElementById('chkjouramount_h[' + index + ']')){
						document.getElementById('chkjouramount_h[' + index + ']').value = vChkAmount;
						formatFieldDigits(document.getElementById('chkjouramount_h[' + index + ']'));
					}
					if (vChkAmount >= 0) { 
						vChkAmount1 = roundNumber(data[0].amount1, dec1);
						vChkAmount2 = roundNumber(data[0].amount2, dec2);
						
						if (document.getElementById('chkjouramount1[' + index + ']')){
							document.getElementById('chkjouramount1[' + index + ']').value = vChkAmount1;
							formatFieldDigits(document.getElementById('chkjouramount1[' + index + ']'));
						}
						if (document.getElementById('chkjouramount1_h[' + index + ']')){
							document.getElementById('chkjouramount1_h[' + index + ']').value = parseFloat(data[0].amount1);
							formatFieldDigits(document.getElementById('chkjouramount1_h[' + index + ']'));
						}
						
						if (document.getElementById('chkjouramount2[' + index + ']')){
							document.getElementById('chkjouramount2[' + index + ']').value = vChkAmount2;
							formatFieldDigits(document.getElementById('chkjouramount2[' + index + ']'));
						}
						if (document.getElementById('chkjouramount2_h[' + index + ']')){
							document.getElementById('chkjouramount2_h[' + index + ']').value = parseFloat(data[0].amount2);
							formatFieldDigits(document.getElementById('chkjouramount2_h[' + index + ']'));
						}
							
					}	
				}
				else if (option ==6) {
					
					if (curr == currbase1 && vChkAmount1 >= 0) {
						if (document.getElementById('chkjouramount[' + index + ']')) document.getElementById('chkjouramount[' + index + ']').value = vChkAmount1;
						if (document.getElementById('chkjouramount_h[' + index + ']')) document.getElementById('chkjouramount_h[' + index + ']').value = vChkAmount1;
						if (document.getElementById('chkjouramount1_h[' + index + ']')) document.getElementById('chkjouramount1_h[' + index + ']').value = vChkAmount1;
					}	
					else if (curr == currbase2 && vChkAmount1 >= 0) {
						if (document.getElementById('chkjouramount1_h[' + index + ']')) document.getElementById('chkjouramount1_h[' + index + ']').value = vChkAmount1;
					}
				
				}
				else if (option == 7) {
					
					if (curr == currbase2 && vChkAmount2 >= 0) {
						if (document.getElementById('chkjouramount[' + index + ']')) document.getElementById('chkjouramount[' + index + ']').value = vChkAmount2;
						if (document.getElementById('chkjouramount_h[' + index + ']')) document.getElementById('chkjouramount_h[' + index + ']').value = vChkAmount2;
						if (document.getElementById('chkjouramount2_h[' + index + ']')) document.getElementById('chkjouramount2_h[' + index + ']').value = vChkAmount2;
					}	
					else if (curr == currbase1 && vChkAmount2 >= 0) {
						if (document.getElementById('chkjouramount2_h[' + index + ']')) document.getElementById('chkjouramount2_h[' + index + ']').value = vChkAmount2;
					}

				}
				else if (option == 8) {
		
					if (document.getElementById('billjouramount_h[' + index + ']')){
						document.getElementById('billjouramount_h[' + index + ']').value = vBillAmount;
						formatFieldDigits(document.getElementById('billjouramount_h[' + index + ']'));
					}
					
					if (vBillAmount >= 0) { 
						vBillAmount1 = roundNumber(data[0].amount1, dec1);
						vBillAmount2 = roundNumber(data[0].amount2, dec2);
						
						if (document.getElementById('billjouramount1[' + index + ']')){
							document.getElementById('billjouramount1[' + index + ']').value = vBillAmount1;
							formatFieldDigits(document.getElementById('billjouramount1[' + index + ']'));
						}
						if (document.getElementById('billjouramount1_h[' + index + ']')){
							document.getElementById('billjouramount1_h[' + index + ']').value = parseFloat(data[0].amount1);
							formatFieldDigits(document.getElementById('billjouramount1_h[' + index + ']'));
						}
						
						if (document.getElementById('billjouramount2[' + index + ']')){
							document.getElementById('billjouramount2[' + index + ']').value = vBillAmount2;
							formatFieldDigits(document.getElementById('billjouramount2[' + index + ']'));
						}
						if (document.getElementById('billjouramount2_h[' + index + ']')){
							document.getElementById('billjouramount2_h[' + index + ']').value = parseFloat(data[0].amount2);
							formatFieldDigits(document.getElementById('billjouramount2_h[' + index + ']'));
						}
							
					}	
				}
				else if (option == 9) {
					
					if (curr == currbase1 && vBillAmount1 >= 0) {
						if (document.getElementById('billjouramount[' + index + ']')) document.getElementById('billjouramount[' + index + ']').value = vBillAmount1;
						if (document.getElementById('billjouramount_h[' + index + ']')) document.getElementById('billjouramount_h[' + index + ']').value = vBillAmount1;
						if (document.getElementById('billjouramount1_h[' + index + ']')) document.getElementById('billjouramount1_h[' + index + ']').value = vBillAmount1;
					}	
					else if (curr == currbase2 && vBillAmount1 >= 0) {
						if (document.getElementById('billjouramount1_h[' + index + ']')) document.getElementById('billjouramount1_h[' + index + ']').value = vBillAmount1;
					}
				
				}
				else if (option == 10) {
					
					if (curr == currbase2 && vBillAmount2 >= 0) {
						if (document.getElementById('billjouramount[' + index + ']')) document.getElementById('billjouramount[' + index + ']').value = vBillAmount2;
						if (document.getElementById('billjouramount_h[' + index + ']')) document.getElementById('billjouramount_h[' + index + ']').value = vBillAmount2;
						if (document.getElementById('billjouramount2_h[' + index + ']')) document.getElementById('billjouramount2_h[' + index + ']').value = vBillAmount2;
					}	
					else if (curr == currbase1 && vBillAmount2 >= 0) {
						if (document.getElementById('billjouramount2_h[' + index + ']')) document.getElementById('billjouramount2_h[' + index + ']').value = vBillAmount2;
					}

				}
				
			}
		}
	}
	
	if((option == 1 || option == 2 || option == 3 || option == 4) && vRate != '' && vRate != 0 && curr != currbase1 && vRate2 == 0 )
		xmlhttp.open("GET","Get_AutocompleteQuery.php?tablename=convertamtrate&pcurrency="+curr+"&pdate="+pdate+"&pcurrbase1="+currbase1+"&pcurrbase2="+currbase2+"&pamount="+vParamAmt+"&prate="+vRate,true);
	else if (option == 4 && JourDtId == '') {
		//alert('test');
		xmlhttp.open("GET","Get_AutocompleteQuery.php?tablename=convertamt1&pcurrency="+curr+"&pdate="+pdate+"&pcurrbase1="+currbase1+"&pcurrbase2="+currbase2+"&pamount="+vParamAmt1+"&jourDtRate="+vjourDtRate+"&jourDtRate2="+vjourDtRate2,true);
	} else {
		xmlhttp.open("GET","Get_AutocompleteQuery.php?tablename=convertamt&pcurrency="+curr+"&pdate="+pdate+"&pcurrbase1="+currbase1+"&pcurrbase2="+currbase2+"&pamount="+vParamAmt+"&jourDtRate="+vjourDtRate+"&jourDtRate2="+vjourDtRate2,true);
	}
	
	xmlhttp.send();

}

function formatFieldDigits(obj,event){
 
	var val = obj.value;
	 val = val.replace(/[^0-9\.]/g,'');
	 
	 if(val != "") {
	   valArr = val.split('.');
	   valArr[0] = (parseInt(valArr[0],10)).toLocaleString();
	   val = valArr.join('.');
	 }
	 
	 obj.value = val;
	 console.log(obj.value);
	 //console.log(obj.value);
	   //console.log(event);
	   //var valueArray = obj.value.split(".");
	   //console.log(valueArray);
	   //if(valueArray.length>1 && valueArray[0]!= ""){
		   //console.log("is Array");
		   //var n = parseInt(valueArray[0].replace(/\D/g,''),10);
		   //n = n+"."+valueArray[1];
		   //obj.value = n.toLocaleString();
	   //}else{
	   //	console.log("not Array");
	   //	var n = parseInt(obj.value.replace(/\D/g,''),10);
	   //	obj.value = n.toLocaleString();
	   //}
   } 


function SetPercentageDivision(tagid, dec1, dec2, divtype, index) {
	x=document.journal;
	var vPer, vAmount, vAmount1, vAmount2, vAmountTot, vAmountTot1, vAmountTot2;
	
	vAmountTot  = document.getElementById('cstjourtotamt['+index+']').value;
	vAmountTot1 = document.getElementById('cstjourtotamt1['+index+']').value;
	vAmountTot2 = document.getElementById('cstjourtotamt2['+index+']').value;
	
	if (vAmountTot == '')  vAmountTot  = 0;
	if (vAmountTot1 == '') vAmountTot1 = 0;
	if (vAmountTot2 == '') vAmountTot2 = 0;
		
	vAmountTot  = parseFloat(vAmountTot);
	vAmountTot1 = parseFloat(vAmountTot1);
	vAmountTot2 = parseFloat(vAmountTot2);
	
	
	vPer = document.getElementById(tagid).value;
	if (vPer == '') vPer = 0;
	vPer=parseFloat(vPer);
	
	
	if (vAmountTot > 0) { 
		vAmount = roundNumber(((vAmountTot*vPer)/100), dec1)
		document.getElementById('cstjouramount['+index+']').value = vAmount;
		document.getElementById('cstjouramount_h['+index+']').value = parseFloat((vAmountTot*vPer)/100);
		
		vAmount1 = roundNumber(((vAmountTot1*vPer)/100), dec1)
		document.getElementById('cstjouramount1['+index+']').value = vAmount1;
		document.getElementById('cstjouramount1_h['+index+']').value = parseFloat((vAmountTot1*vPer)/100);
				
		vAmount2 = roundNumber(((vAmountTot2*vPer)/100), dec2)
		document.getElementById('cstjouramount2['+index+']').value = vAmount2;
		document.getElementById('cstjouramount2_h['+index+']').value = parseFloat((vAmountTot2*vPer)/100);
	}
}

function SetAmountDivision(option, dec1, dec2, curr, currbase1, currbase2, pdate, divtype, index) {

	x=document.journal;
	var vPer, vAmount, vAmount1, vAmount2, vAmountTot, vAmountTot1, vAmountTot2;
	
	dec1  = parseInt(dec1);
	dec2  = parseInt(dec2);
	
	
	vAmountTot  = document.getElementById('cstjourtotamt['+index+']').value;
	vAmountTot1 = document.getElementById('cstjourtotamt1['+index+']').value;
	vAmountTot2 = document.getElementById('cstjourtotamt2['+index+']').value;
	
	if (vAmountTot == '')  vAmountTot  = 0;
	if (vAmountTot1 == '') vAmountTot1 = 0;
	if (vAmountTot2 == '') vAmountTot2 = 0;
		
	vAmountTot  = parseFloat(vAmountTot);
	vAmountTot1 = parseFloat(vAmountTot1);
	vAmountTot2 = parseFloat(vAmountTot2);
	
	
	vAmount  = document.getElementById('cstjouramount['+index+']').value;
	vAmount	  = vAmount.split(",").join("");
	vAmount1 = document.getElementById('cstjouramount1['+index+']').value;
	vAmount1	  = vAmount1.split(",").join("");
	vAmount2 = document.getElementById('cstjouramount2['+index+']').value;
	vAmount2	  = vAmount2.split(",").join("");
	
	if (vAmount == '')  vAmount = 0;
	if (vAmount1 == '') vAmount1 = 0;
	if (vAmount2 == '') vAmount2 = 0;
		
	vAmount  = parseFloat(vAmount);
	vAmount1 = parseFloat(vAmount1);
	vAmount2 = parseFloat(vAmount2);
	
	
	
	
	

	var xmlhttp = getXMLHttpRequest();
	
	xmlhttp.onreadystatechange=function()
	{
		if (xmlhttp.readyState==4 && xmlhttp.status==200)
		{
			{ 
				var data = $.parseJSON(xmlhttp.responseText);
				console.table(data);
				if (option == 1) {
		
					if (document.getElementById('cstjouramount_h['+index + ']')){
						document.getElementById('cstjouramount_h['+index+']').value = vAmount;
						formatFieldDigits(document.getElementById('cstjouramount_h[' + index + ']'));
					}
					
					if (vAmount >= 0) { 
						vAmount1 = roundNumber(data[0].amount1, dec1);
						vAmount2 = roundNumber(data[0].amount2, dec2);
						
						if (document.getElementById('cstjouramount1['+index+']')){ 
							document.getElementById('cstjouramount1['+index+']').value = vAmount1;
							formatFieldDigits(document.getElementById('cstjouramount1[' + index + ']'));

						}
						if (document.getElementById('cstjouramount1_h['+index+']')){
							document.getElementById('cstjouramount1_h['+index+']').value = parseFloat(data[0].amount1);
							formatFieldDigits(document.getElementById('cstjouramount1_h[' + index + ']'));

						}
						
						if (document.getElementById('cstjouramount2['+index+']')){
							document.getElementById('cstjouramount2['+index+']').value = vAmount2;
							formatFieldDigits(document.getElementById('cstjouramount2[' + index + ']'));
						}
						if (document.getElementById('cstjouramount2_h['+index+']')){
							document.getElementById('cstjouramount2_h['+index+']').value = parseFloat(data[0].amount2);
							formatFieldDigits(document.getElementById('cstjouramount2_h[' + index + ']'));
						}
							
					}	
				}	
				else if (option == 2) {
					
					if (curr == currbase1 && vAmount1 >= 0) {
						if (document.getElementById('cstjouramount['+index+']')) document.getElementById('cstjouramount['+index+']').value = vAmount1;
						if (document.getElementById('cstjouramount_h['+index+']')) document.getElementById('cstjouramount_h['+index+']').value = vAmount1;
						if (document.getElementById('cstjouramount1_h['+index+']')) document.getElementById('cstjouramount1_h['+index+']').value = vAmount1;
					}	
					else if (curr == currbase2 && vAmount1 >= 0) {
						if (document.getElementById('cstjouramount1_h['+index+']')) document.getElementById('cstjouramount1_h['+index+']').value = vAmount1;
					}
				
				}
				else if (option == 3) {
					
					if (curr == currbase2 && vAmount2 >= 0) {
						if (document.getElementById('cstjouramount['+index+']')) document.getElementById('cstjouramount['+index+']').value = vAmount2;
						if (document.getElementById('cstjouramount_h['+index+']')) document.getElementById('cstjouramount_h['+index+']').value = vAmount2;
						if (document.getElementById('cstjouramount2_h['+index+']')) document.getElementById('cstjouramount2_h['+index+']').value = vAmount2;
					}	
					else if (curr == currbase1 && vAmount2 >= 0) {
						if (document.getElementById('cstjouramount2_h['+index+']')) document.getElementById('cstjouramount2_h['+index+']').value = vAmount2;
					}

				}
		
				vPer = roundNumber((vAmount/vAmountTot)*100,dec1);
				vPer = parseFloat(vPer);
				if (document.getElementById('cstjourperc['+index+']')) document.getElementById('cstjourperc['+index+']').value = vPer;

			}
		}
	}

	
	xmlhttp.open("GET","Get_AutocompleteQuery.php?tablename=convertamt&pcurrency="+curr+"&pdate="+pdate+"&pcurrbase1="+currbase1+"&pcurrbase2="+currbase2+"&pamount="+vAmount,true);
	xmlhttp.send();

}

//All= All form; D= Detail Part
function ClearForm(Option){
    x = document.journal;
	var vmode = x.actionmode.value;
	
	if (Option == 'All') {
		
		x.txtJourId.value='';
		x.txtJourRef.value='';
		x.txtJourType.value='';
		x.txtTypeRef.value='';
		x.txtFolio.value='';
		x.txtJourDate.value='';
		x.txtRemark.value='';
		x.txtManualNo.value='';
		
		x.txtJourAmountDb1.value='';
		x.txtJourAmountDb2.value='';
		x.txtJourAmountCd1.value='';
		x.txtJourAmountCd2.value='';
		x.txtJourBalance1.value='';
		x.txtJourBalance2.value='';
			
		x.txtCountDetail.value='';
		x.mandatoryfields_d.value='';
		x.mandatoryfields_d1.value='';
		x.mandatoryfields_d2.value='';
		x.mandatoryfields_d3.value='';
		x.ErrorRecId.value='';
		x.message.value='';
		
		x.txtProjectCode.value='';
		x.txtCostCentCode.value='';
		
		x.actionmode.value = '';
		x.mainaction.value = '';
		x.mainaction.value = '';
	} 
}



function SearchForRef(){
    XPos = (screen.availHeight - 560) / 2;
	YPos = (screen.availWidth - 970) / 2;
	
	x = document.journal;
	
    win = window.open('Form_JournalSearch.php', 'Form_JournalSearch', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=no,width=785,height=475,left='+YPos+',top='+XPos);		
	win.creator = self;
	win.focus();		
			
}

function SearchForPending(){
	XPos = (screen.availHeight - 560) / 2;
	YPos = (screen.availWidth - 970) / 2;
	
    x = document.journal;
	
    win = window.open('Form_JournalSearchPending.php', 'Form_JournalSearchPending', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=no,width=990,height=580,left='+YPos+',top='+XPos);		
	win.creator = self;
	win.focus();		
			
}

function SearchCopyJV(){
	XPos = (screen.availHeight - 560) / 2;
	YPos = (screen.availWidth - 970) / 2;
	
    x = document.journal;
	
	var vJourDate = x.txtJourDate.value;
	
    win = window.open('Form_JournalCopySearch.php?PJourDate='+vJourDate, 'Form_JournalCopySearch', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=no,width=990,height=580,left='+YPos+',top='+XPos);		
	win.creator = self;
	win.focus();		
			
}

function PrintJournal(JourId, JourRef,JourRefFolio) {
	var str = '';
	x = document.journal;
	var FA_JournalPrintingAsk = document.getElementById('FA_JournalPrintingAsk').value;
	//alert(FA_JournalPrintingAsk);
	if(FA_JournalPrintingAsk == 1){
	if (confirm ( "Do you want to Print current Transaction with reference "+JourRef+" Folio "+JourRefFolio+"?"))
	{
		str = 'Form_JournalPreview.php?journal_id='+JourId;
		window.open(str);
	}	
	}
	
}


function showlistLedger(frm,str,ledgertype,showdetails,PIndex){
	x = document.journal;
	
	XPos = (screen.availHeight - 500) / 2;
	YPos = (screen.availWidth - 780) / 2;
	
	var keyword = encodeURIComponent(document.getElementById('ledgernumber['+PIndex+']').value);
	window.open('List_Agents_orderbycode1.php?str=22&index='+PIndex+'&PRef='+keyword+'&ShowDetails='+showdetails,'mywindow','width=780,height=500,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=no,left='+YPos+',top='+XPos);
}

function showlistChecks(check){
	var x=document;
	
	if(check=="1"){	
		if(x.getElementById('txtCostCentCode').value!="" && x.getElementById('txtProjectCode').value!=""){
			
			var indx = document.journal.lastinputrow.value;
	
			showlistChecks2(indx);
		}else
			alert("Fill Mandatory Fields (*)");
	}else{
		var indx = document.journal.lastinputrow.value;
	
		showlistChecks2(indx);
		
	}
			
}
function showlistChecks2(PIndex){
	x = document.journal;
	
	XPos = (screen.availHeight - 500) / 2;
	YPos = (screen.availWidth - 780) / 2;
	
	
	window.open('List_Checkss.php?index='+PIndex,'mywindow','width=780,height=500,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=no,left='+YPos+',top='+XPos);
}


function showlistLedgerName(frm,str,ledgertype,showdetails,PIndex){
	x = document.journal;
	
	XPos = (screen.availHeight - 500) / 2;
	YPos = (screen.availWidth - 780) / 2;
	
	var keyword = encodeURIComponent(document.getElementById('ledgername['+PIndex+']').value);
	window.open('List_Agents_orderbycode.php?str=22&index='+PIndex+'&PRef='+keyword+'&ShowDetails='+showdetails,'mywindow','width=780,height=500,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=no,left='+YPos+',top='+XPos);
}



function showlistProject(str){

	vProjectCode = encodeURIComponent(document.getElementById('txtProjectCode').value);
	window.open('List_SorProject.php?frm=26&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=26&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;
	
	if (str == '3')
		vProjectCode = '';
	else
		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 showlistCheck(str,PIndex,PJourDtId,PChkJourId){
	x = document.journal;
	
	XPos = (screen.availHeight - 450) / 2;
	YPos = (screen.availWidth - 700) / 2;

	if (PJourDtId != -1) {
		window.open('List_FrmChecks.php?frm=1&item='+str+'&index='+PIndex+'&PJourDtId='+PJourDtId+'&PChkJourId='+PChkJourId,'Checks','toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=no,width=700,height=450,left='+YPos+',top='+XPos);
	} else {
		alert('Please select a ledger first.');
	}
}

function showlistBill(str,PIndex,PJourDtId,PBillJourId){
	x = document.journal;
	
	XPos = (screen.availHeight - 450) / 2;
	YPos = (screen.availWidth - 700) / 2;

	if (PJourDtId != -1) {
		window.open('List_FrmBills.php?frm=1&item='+str+'&index='+PIndex+'&PJourDtId='+PJourDtId+'&PBillJourId='+PBillJourId,'Bills','toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=no,width=700,height=450,left='+YPos+',top='+XPos);
	} else {
		alert('Please select a ledger first.');
	}
}

function ShowTooltip(e,text,option) {
	var x = e.pageX + 'px';
    var y = e.pageY + 'px';
    	
	if (option == 'S') {
		var div = $('<div id="hintDiv">').css({
					"position": "absolute",  
					"width": "100px",
					"height": "150px",
					"border": "1px solid #21B1FF",
					"background-color": "#00D9FF",
					"z-index":"999999",
					"left": x,
					"top": y
				});
        $(div).append(text);
        $(document.body).append(div);    
		
	} else { 
		$('#hintDiv').remove();
	}
}
function kd(e)
{ 

	x=document.trans;
    var intKey = (window.Event) ? e.which : e.keyCode;
    if (intKey == 13) { //enter key
        //x.btnSubmitRecord.click();
		
		/*el = x.elements;
		var w = '';
		for(var i=0;i<el.length;i++){
		
			el[i].getfocus=function(){
				w=this.name;
				alert(w);
			}
		}*/
		

		return false;
    }
    return true;
}

function setRate(rtype,index) {
	if(document.getElementById('journaldtrate['+index+']'))
	var vjourDtRate = document.getElementById('journaldtrate['+index+']').value;
	else var vjourDtRate=0;
	if(document.getElementById('journaldtrate2['+index+']'))
	var vjourDtRate2 = document.getElementById('journaldtrate2['+index+']').value;
	else var vjourDtRate2 = 0;
	if(rtype==2){
		if(vjourDtRate2 != '' || vjourDtRate2 != 0) 
	{
		vjourDtRate=0;
		if(document.getElementById('journaldtrate['+index+']'))
		document.getElementById('journaldtrate['+index+']').value=vjourDtRate;
	}
	}
	if(rtype==1){
	if(vjourDtRate != '' || vjourDtRate != 0){
		vjourDtRate2=0;
		if(document.getElementById('journaldtrate2['+index+']'))
		document.getElementById('journaldtrate2['+index+']').value=vjourDtRate2;
	}
	}
}

function SetAmountRate(opt,dec1, dec2, curr, currbase1, currbase2, pdate, index){
	var vRate, vAmount, vAmount1, vAmount2, vCurr;
	
	pdate = document.getElementById("journaldate").value;
	dec1  = parseInt(dec1);
	dec2  = parseInt(dec2);
	

	vRate 	  = document.getElementById("journaldtrate["+index+"]").value;
	vAmount   = document.getElementById("journaldtamount["+index+"]").value;
	vAmount1  = document.getElementById("journaldtamount1["+index+"]").value; 
	vAmount2  = document.getElementById("journaldtamount2["+index+"]").value;
	vCurr	  = document.getElementById("currencycode["+index+"]").value;
	
	
	if(vRate == '') 	vRate    = 0;
	else 				vRate    = parseFloat(vRate);
	
	if(vAmount == '') 	vAmount  = 0;
	else 				vAmount  = parseFloat(vAmount);
	
	if(vAmount1 == '') 	vAmount1 = 0;
	else 				vAmount1 = parseFloat(vAmount1);
	
	if(vAmount2 == '')	vAmount2 = 0;
	else 				vAmount2 = parseFloat(vAmount2);
	
	if(vCurr != currbase1 && vRate != '' && vRate != 0 ){	
	var xmlhttp = getXMLHttpRequest();
	
	xmlhttp.onreadystatechange=function()
	{
		if (xmlhttp.readyState==4 && xmlhttp.status==200)
		{
			{ 
				var data = $.parseJSON(xmlhttp.responseText);
				vAmount1 = roundNumber(data[0].amount1, dec1); 
				vAmount2 = roundNumber(data[0].amount2, dec2); 
					
				if (document.getElementById('journaldtamount1[' + index + ']')) document.getElementById('journaldtamount1[' + index + ']').value = vAmount1;
				if (document.getElementById('journaldtamount1_h[' + index + ']')) document.getElementById('journaldtamount1_h[' + index + ']').value = parseFloat(data[0].amount1);
				
				if (document.getElementById('journaldtamount2[' + index + ']')) document.getElementById('journaldtamount2[' + index + ']').value = vAmount2;
				if (document.getElementById('journaldtamount2_h[' + index + ']')) document.getElementById('journaldtamount2_h[' + index + ']').value = parseFloat(data[0].amount2);
				
			}
		}
	}
	
	
		xmlhttp.open("GET","Get_AutocompleteQuery.php?tablename=convertamtrate&pcurrency="+vCurr+"&pdate="+pdate+"&pcurrbase1="+currbase1+"&pcurrbase2="+currbase2+"&pamount="+vAmount+"&prate="+vRate,true);
		xmlhttp.send();
	} else { 
		
		SetAmount(opt, dec1, dec2, '', currbase1, currbase2, pdate, index); 
	}
	
}
function changeDate(Hide_ValueDate){
	if( Hide_ValueDate == 0 ){
	var indx = document.journal.lastinputrow.value;
	var headerdate = document.journal.txtJourDate.value;
	var valuedate;
	for(i=0;i<=indx;i++){
		valuedate = 'journaldtvaluedate['+i+']'; 
		document.getElementById(valuedate).value=headerdate;
	}
	}
}

function checkCurrency(opt, dec1, dec2, currbase1, currbase2, pdate, indx){
	var curname 	= 'currencycode['+indx+']';
	var ledgername  = 'ledgernumber['+indx+']';
	var vCheckCur;
	var vCurr 		= document.getElementById(curname).value;
	var vLedgercode  = document.getElementById(ledgername).value;

		
		var xmlhttp = getXMLHttpRequest();
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				{ 
					var data = $.parseJSON(xmlhttp.responseText);
					vCheckCur = data[0].checkCur; 
					if(vCheckCur == 0){
						document.getElementById(curname).value = data[0].cur; 
						alert("Changing Currency is Not Allowed!");
					} else {
						SetAmount(opt, dec1, dec2, data[0].cur, currbase1, currbase2, pdate, indx); 
					}
				}
			}
		}
	
	
		xmlhttp.open("GET","Get_AutocompleteQuery.php?tablename=checkLedgerCurrency&pcurrency="+vCurr+"&pLedgercode="+vLedgercode,true);
		xmlhttp.send();
		
		
	
}

function checkLedger(e,indx){ 
	var ledgercode  = 'ledgernumber['+indx+']';
	var ledgername  = 'ledgername['+indx+']';
	var inactiveLedger;
	
	var journaldate  = document.getElementById("journaldate").value; 
	var vLedgercode  = document.getElementById(ledgercode).value;

		
		var xmlhttp = getXMLHttpRequest();
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				{ 
					var data = $.parseJSON(xmlhttp.responseText);
					inactiveLedger = data[0].Ledger_inactive; 
					if(inactiveLedger == 1){
						document.getElementById(ledgercode).value = ''; 
						document.getElementById(ledgername).value = '';
						showlistLedger(17,1,'all',0,indx);
					} 
				}
			}
		}
	
	
		xmlhttp.open("GET","Get_AutocompleteQuery.php?tablename=checkinactiveledger&pdate="+journaldate+"&pledger="+vLedgercode,true);
		xmlhttp.send();
	
}

function moveUpDown(e, field, index){

 	if (e.keyCode == '38'){ //up
		if (index != 0){
			var newIndex = parseInt(index)-1;
			var newField = field+'['+newIndex+']';
			if (document.getElementById(newField))
				document.getElementById(newField).focus();
			
		}
	}
	if (e.keyCode == '40'){ //down
		var newIndex = parseInt(index)+1;
		var newField = field+'['+newIndex+']';
		if (document.getElementById(newField))
			document.getElementById(newField).focus();
	
	}
	 
	
}

function setDistCode(){
	var lrow = document.getElementById('lastinputrow').value;
	if (lrow != 0) lrow = parseInt(lrow+1);
	if (document.getElementById('txtProjectCode').value != '')
		document.getElementById('journaldtdistcode['+lrow+']').value = document.getElementById('txtProjectCode').value;
}
</script>
<title>Journal</title>
</head>
<body>
<form name='journal' id='journal' method='post' enctype='multipart/form-data'>
<input type='hidden' name='actionmode' value='$actionmode'>
<input type='hidden' name='mainaction' value='$mainaction'>
<input type='hidden' name='message' value='$message' size='200'>
<input type='hidden' name='mandatoryfields_d' value='$vMandatoryFields_D'>
<input type='hidden' name='mandatoryfields_d1' value='$vMandatoryFields_D1'>
<input type='hidden' name='mandatoryfields_d2' value='$vMandatoryFields_D2'>
<input type='hidden' name='mandatoryfields_d3' value='$vMandatoryFields_D3'>
<input type='hidden' name='ErrorRecId' value='$ErrorRecId' >
<input type='hidden' name='PTabIndex' id='PTabIndex' value='$PTabIndex'>
<input type='hidden' name='fromdate' id='fromdate' value='$fromdate'>
<input type='hidden' name='todate' id='todate' value='$todate'>

HERE;

//Initializations
if (empty($mainaction))		 $mainaction = 'insert';
if (empty($txtJourDate))	 $txtJourDate = displayToday();
if (empty($txtJourType))  	 $txtJourType='JV';

if ((empty($txtProjectCode)) && $Module_Project == 1 ) //&& $StpDefaultProject != '')
	$txtProjectCode = $defaultproject;

/* if ((empty($txtProjectCode)) && $Module_Project == 1)
	$txtProjectCode = $defaultproject; */


if ((empty($txtCostCentCode)) && $Module_CostCenter == 1 && $StpDefaultCostcenter != '')
	$txtCostCentCode = $StpDefaultCostcenter;

if ((empty($txtCostCentCode)) && $Module_CostCenter == 1)	
	$txtCostCentCode = $defaultcostcent;
		
if ($txtJourId != '' && $actionmode != 'cancel') {
	// Read From Temp Tables For Selected Record				 
	$query = " Select Journal_ID, Journal_RefGovernment, Journal_Folio, Journal_Type, Journal_TypeRef, ".
			 " Date_Format(Journal_Date,'%d/%m/%Y') As Journal_Date, Journal_Remark, Manual_No, ".
			 " ifNull(Amnt1_db,0), ifNull(Amnt2_db,0), ifNull(Amnt1_cd,0), ifNull(Amnt2_cd,0),  ".
			 " Project_code, Costcent_Code ".
			 " From Temp_Journal As Journal ".
			 " Where Journal_ID = ".$txtJourId;
			 
	//echo $query;
	$result=mysql_query($query,$connection) or die(mysql_error());
    $rows=mysql_fetch_array($result);
	
	$txtJourId     = $rows[0];
	$txtJourRef    = $rows[1];
	$txtFolio      = $rows[2];
	$txtJourType   = $rows[3];
	$txtTypeRef    = $rows[4];
	$txtJourDate   = $rows[5];
	$txtRemark     = $rows[6];
	$txtManualNo   = $rows[7];
	
	$txtJourAmountDb1   = $rows[8];
	$txtJourAmountDb2   = $rows[9];
	$txtJourAmountCd1   = $rows[10];
	$txtJourAmountCd2   = $rows[11];
	$txtJourBalance1  = $txtJourAmountDb1 - $txtJourAmountCd1;
	$txtJourBalance2  = $txtJourAmountDb2 - $txtJourAmountCd2;
	
	$txtProjectCode  = $rows[12];
	$txtCostCentCode = $rows[13];
	
	
	
	$query = " Select Count(*) FROM Temp_JournalDt ".
			 " WHERE Journal_ID = ".$txtJourId;
	$result = selectData($connection, $query);
	$txtCountDetail = $result[0];
	if($txtCountDetail == '') $txtCountDetail = 0;
	
	
}
//echo $txtJourDate;
echo "<input type='hidden' name='FA_JournalPrintingAsk' id='FA_JournalPrintingAsk' value='$FA_JournalPrintingAsk' />";
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'>JOURNAL</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='38'  height='34'>&nbsp;</td>
				<td valign='middle' height='34'>";

echo"		<button type='button' id='btnClear' name='btnClear' onclick='ClearPage(); return false;' title='Clear Page'><span><span>$ClearPage</span></span></button>";
				
if ($txtJourId != '')				
	echo"   <button type='button' name='btnCancel' id='btnCancel' onclick='CancelRecord(); return false;' title='Cancel Changes'><span><span>$cancell</span></span></button>";
	
if ($txtJourId != '' && $FA_JournalApp == 1)				
	echo"   <button type='button' name='btnPost' id='btnPost' onclick='PostChanges($Module_RestrictProjCost, $Module_RestrictCost, $Module_Project, $Module_CostCenter);return false;' title='Save Changes'><span><span>$Save</span></span></button>";
	
if ($txtJourId == '')
	echo"   <button type='button' name='btnSearch' id='btnSearch' onclick='SearchForRef();return false;' title='Search'><span><span>$Search</span></span></button>";

if ($txtJourId == '')
	echo"   <button type='button' name='btnPending' id='btnPending' onclick='SearchForPending();return false;' title='Search Pending'><span><span>$Pending</span></span></button>";	
	
if ($txtJourId == '')
	echo"   <button type='button' name='btnCopyJV' id='btnCopyJV' onclick='SearchCopyJV();return false;' title='Copy JV'><span><span>$CopyJV</span></span></button>";	
	
	
	if ($txtJourId !='')	
	echo"<button type='button' id='btnUpload' name='btnUpload' 
			onclick=\"UploadDocuments('Journal');return false;\" title='Upload Documents'><span><span>Upload Documents</span></span></button>";
			

			
			
if ($Module_ImportExcell == 1) {
	$HintText = '1-LedgerNo<br>2-LedgerName<br>3-Description<br>4-Currency<br>5-D/C<br>6-Amount<br>7-AmountB1<br>8-AmountB2';
	
	echo"</td><td>";
	echo"<table border=0><tr>
			<td>
				<button type='button' id='btnImport' name='btnImport' onclick=\"ImportExcel($Module_RestrictProjCost, $Module_RestrictCost, $Module_Project, $Module_CostCenter);return false;\" onmouseover=\"ShowTooltip(event,'$HintText','S');\" onmouseout=\"ShowTooltip(event,'','H');\" ><span><span>Import Excel</span></span></button>
				<input type='file' name='excelfile' id='excelfile' style='width:200px;' accept='file/xls'>
			</td>
		</tr></table>";	
}

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

$strt = $_SESSION['StartFinancial_Date'];
$end = $_SESSION['EndFinancial_Date'];
echo"<tr><td id='content-body'>
		<table border='0' align='center'  class='tablecontent' cellpadding='0' cellspacing='0' >
		  <col width=80>
		  <col width=120>
		  <col width=70>
		  <col width=150>
		  <col width=70>
		  <col width=100>
		  <col width=100>
		  <col width=410>
		
		<tr style='height:25px;'>
          <td valign='center' align='left' ><span class='style1'>$Ref1</span></td>
		  <td align='left'><b>$txtJourRef</b>
		      <input type='hidden' name='txtCountDetail' value='$txtCountDetail' >
			  <input type='hidden' name='txtJourId' id='txtJourId' value='$txtJourId' >
			  <input type='hidden' name='txtJourRef' value='$txtJourRef' >
			  <input type='hidden' name='txtTypeRef' value='$txtTypeRef' >
			  <input type='hidden' name='txtFolio' value='$txtFolio' >
			  <input type='hidden' name='ChecksNo' id='ChecksNo' value='$ChecksNo' >
			  <input type='hidden' name='vChecksNo' id='vChecksNo' value='$vChecksNo' >
			  
		  </td>
		  <td valign='center' align='left' ><span class='style1'>$TypeRef1</span></td>
		  <td align='left'><b>$txtTypeRef</b></td>
		  <td valign='center' align='left' ><span class='style1'>$Folio1</span></td>
		  <td align='left'><b>$txtFolio</b></td>
		  <td align='left'><span class='style1'>$Date1</span><span class='style2'>*</span></td>
		  <td align='left'><input type='text' id='journaldate' name='txtJourDate' value='$txtJourDate' onBlur=checkDateFormat(this,$strt,$end); onchange=\"changeDate('$Hide_ValueDate');\"   maxlength='10' style='width:80px;'  >
		        <a HREF='#' onClick=\"displayCalendar(document.journal.txtJourDate,'dd/mm/yyyy',this);  return false;\" NAME='anchor1' ID='anchor1'><img src='./img/calendar.png' width='20' height='20' border=0 align=center></a></td>";

echo"	</tr>"; 
		  
echo"   <tr style='height:25px;'>
		  <td align='left' valign='center'><span class='style1'>$Remark1</span></td>
		  <td align='left' colspan='3' ><span class='style1'>
		  <input type='text' id='journalremark' name='txtRemark' value='".htmlspecialchars($txtRemark, ENT_QUOTES)."'   style='width:310px;' maxlength='150' ></span></td>";
		  
echo"     <td align='left' ><span class='style1'>$Type1</span><span class='style2'>*</span></td>";
echo"     <td align='left'><span class='style1'><select name='txtJourType' id='journaltype' style='width:90px;'>";
		  echo"<option></option>";
		  while($row=mysql_fetch_row($resultjourtype)){
			echo"<option ";
			if ($txtJourType==$row[0]) echo " selected ";
		    echo" value='$row[0]'>$row[1]</option>";
		  }
		  echo"</select></span></td>";	
		  
echo"     <td align='left' ><span class='style1'>$ManualNo1</span></td>";
echo"     <td align='left'><span class='style1'><input type='text' id='journalmanualno' name='txtManualNo' value='".htmlspecialchars($txtManualNo, ENT_QUOTES)."'  style='width:80px;' maxlength='45'  ></span></td>"; 
		  
echo"   </tr>";	

$Boolean_Project = 0;
if ($Module_Project == 1 || $Module_CostCenter == 1) {
	$Boolean_Project = 1;
	echo"   <tr style='height:25px;'>";
	if ($Module_Project == 1) {
		echo" <td align='left' ><span class='style1'>$Project1&nbsp;<span class='style2'>*</span></span></td>
			  <td align='left' colspan='2' > <span class='style1'>
				<input type='text' name='txtProjectCode' id='txtProjectCode' value='$txtProjectCode' style='width:155px;'  maxlength='20' onchange=\"CheckLookup('chkcodeexists','project','project_code',this.value,'lstProjectCodeH');";
			if ($journal_distribution == '1')
				echo "setDistCode();";		
				echo "\" /></span>
				<label><span><img src='img/openlist.png' title='Select Project' id='lstProjectCodeH' width='20' height='20' border='0' onMouseOver=\"style.cursor='pointer'\" onClick='showlistProject(1); ' style='vertical-align:bottom;'/></span></label>
			  </td>";
	} else {
		echo" <td align='left' colspan='2'><input type='hidden' name='txtProjectCode' id='txtProjectCode' value='$txtProjectCode' /></td>";

	}	
	echo"   </tr>";			
	echo"   <tr style='height:25px;'>";
	if ($Module_CostCenter == 1) {		  
		echo" <td align='left' ><span class='style1'>$Costcenter2<span class='style2'>*</span></span></td>		
			  <td align='left' colspan='2' ><span class='style1'>
				<input type='text' name='txtCostCentCode' id='txtCostCentCode' value='$txtCostCentCode' style='width:155px;' maxlength='20' onchange=\"CheckLookup('chkcodeexists','costcent','costcent_code',this.value,'lstCostCentCodeH');\" /></span>
				<label><span><img src='img/openlist.png' title='Select Costcenter' id='lstCostCentCodeH' width='20' height='20' border='0' onMouseOver=\"style.cursor='pointer'\" onClick='showlistCostcenter(1); ' style='vertical-align:bottom;'/></span></label>
			  </td>";
			  
	} else {
		echo" <td align='left' colspan='2'><input type='hidden' name='txtCostCentCode' id='txtCostCentCode' value='$txtCostCentCode' /></td>";

	}
	
	echo"	<td colspan='4'>&nbsp;</td>";
	echo"  </tr>";	
} else {
	echo" <input type='hidden' name='txtProjectCode' id='txtProjectCode' value='$txtProjectCode' />";
	echo" <input type='hidden' name='txtCostCentCode' id='txtCostCentCode' value='$txtCostCentCode' />";
}
echo "	<span><td></td></span><span><td></td></span><span><td></td></span><span><td></td></span>";
echo "	<td colspan=3 align='right'>&nbsp;</td><td  align='left'><button type='button' id='btnImport' name='btnImport' onclick=\"showlistChecks('".$Boolean_Project."');\" ><span><span>Select Check</span></span></button></td>";
echo"   <tr><td colspan='8' valign='top'>";
echo"	<div id='datagrid' class='grid' style='width:1090px;'>";


//Show Items Grid

$Parameters = array();
$Parameters['Module_Project'] 				= $Module_Project;
$Parameters['Module_CostCenter'] 			= $Module_CostCenter;
$Parameters['Module_ProjectDt'] 			= $Module_ProjectDt;
$Parameters['Module_CostCenterDt'] 			= $Module_CostCenterDt;
$Parameters['Module_ReferenceByCostCenter'] = $Module_ReferenceByCostCenter;
$Parameters['Module_checks'] 				= $Module_checks;
$Parameters['Module_RestrictProjCost'] 		= $Module_RestrictProjCost;
$Parameters['Module_RestrictCost'] 			= $Module_RestrictCost;
$Parameters['DecimalBase'] 					= $DecimalBase;
$Parameters['DecimalBase1'] 				= $DecimalBase1;
$Parameters['DecimalBase2'] 				= $DecimalBase2;
$Parameters['Journal_DefaultCur'] 			= $Journal_DefaultCur;
$Parameters['module_journalRate'] 			= $module_journalRate;
$Parameters['Base1'] 						= $base1;
$Parameters['Base2'] 						= $base2;
$Parameters['Hide_ValueDate'] 				= $Hide_ValueDate;
$Parameters['Hide_Base2'] 					= $Hide_Base2;

$Parameters['txtJourDate'] 					= $txtJourDate;
$Parameters['ErrorRecId']  					= $ErrorRecId;
$Parameters['module_ledgerrestrictcur']  	= $module_ledgerrestrictcur;
$Parameters['showJournalRate'] 				= $showJournalRate;
$Parameters['journal_distribution'] 		= $journal_distribution;

$_SESSION['gjv_parameters']  = $Parameters;

$_SESSION['query_journal_labels'] = $query_journal_labels;

ShowJournalDtGrid($connection,'JV',$txtJourId,$_SESSION['gjv_parameters'],$_SESSION['gjv_arrayaccess'],'JournalDt.JournalDt_ID', '','','','','', '', '',$query_journal_labels);

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

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

echo"	<div class='tabber' id='tab1' style='width:800px; margin-top:10px; float:left; text-align:left;'>";

if ($Module_Project == 1 || $Module_CostCenter == 1 || $Module_ProjectDt == 1 || $Module_CostCenterDt == 1) {
	echo"	<div class='tabbertab'>
				<h2 title='CstJour'>CstJour</h2>";	
	echo"		<div id='datagrid-d' style='width:780px; height:150px; margin-top:5px; border:1px solid gray;'>";

	ShowJournalDtGridDivisions($connection,'JV-D',$txtJourId,-1,'',$_SESSION['gjv_parameters'],$_SESSION['gjv_arrayaccess'], $query_journal_labels);

	echo"		</div>"; 	
	echo"	</div>";

}
if($Module_checks==1){
echo"		<div class='tabbertab'>
				<h2 title='Checks'>Checks</h2>";
echo"			<div id='datagrid-c' style='width:780px; height:150px; margin-top:5px; border:1px solid gray;'>";				
				
	ShowJournalDtGridChecks($connection,'JV-C',$txtJourId,-1,$_SESSION['gjv_parameters'],$_SESSION['gjv_arrayaccess'], $query_journal_labels);
	
echo"			</div>";
echo"		</div>";
}

if($Module_bill==1){
echo"		<div class='tabbertab'>
				<h2 title='Bills'>Bills</h2>";
echo"			<div id='datagrid-b' style='width:780px; height:150px; margin-top:5px; border:1px solid gray;'>";				
				
	ShowJournalDtGridBills($connection,'JV-B',$txtJourId,-1,$_SESSION['gjv_parameters'],$_SESSION['gjv_arrayaccess']);
	
echo"			</div>";
echo"		</div>";
} else {
echo"	<div id='datagrid-b' style='width:780px; height:150px; margin-top:5px; border:1px solid gray;display:none'>";				
	ShowJournalDtGridBills($connection,'JV-B',$txtJourId,-1,$_SESSION['gjv_parameters'],$_SESSION['gjv_arrayaccess']);
echo "</div>";	
}
	
	
echo"	</div>";


echo"	<div id='totals' style='width:240px; height:190px; margin-top:10px; float:right;'>";
	ShowJournalTotals($connection,$txtJourId,$_SESSION['gjv_parameters'],$_SESSION['gjv_arrayaccess'], $query_journal_labels);
echo"	</div>"; 
echo"   </td></tr>"; 		  
		  
echo" </table></td></tr>";

echo" <tr height='30'><td align='center' id='content-bottom' ></td></tr>";
include("footer.php");	
echo" </table>  ";//end of last table menu


echo"<script type=\"text/javascript\" language=\"javascript\">";
echo"	tabberAutomatic(tabberOptions);";
echo"   vTabIndex = document.getElementById('PTabIndex').value; ";
echo"	if (document.getElementById('tab1')) document.getElementById('tab1').tabber.tabShow(vTabIndex); ";
echo"</script>";

if ($actionmode == "post" && $PrJourId != '' and $message=='') {

	$query    = " SELECT Journal_RefGovernment,Journal_folio ".
			    " FROM Journal ".
                " WHERE Journal_Id = $PrJourId ";
	$result     = selectData($connection, $query);
	$PrJourRef  = $result[0];
	$PrJourRefFolio  = $result[1];
		
	
	echo '<script type="text/javascript" language="javascript">';
	
	if ($Login_FastPrint == 1) 
		echo ' PrintJournal(\''.$PrJourId.'\', \''.$PrJourRef.'\', \''.$PrJourRefFolio.'\'); ';
		
	echo ' ClearPage1(); ';
	echo '</script>';

}


print <<<HERE

</form>
</body>
<html>

HERE;

?>