
<?php

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


include("config.inc.php");
include("function.inc.php");
include("Functions_Trans.php");
//include("Functions_UserAccess.php");


$connection = mysql_connect($config['dbServer'],$config['dbUser'],$config['dbPass'],true,65536) 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);
}

set_time_limit(0);

//Read From Setup Table							
$querysetup= " select DecimalBase, DecimalBase1, DecimalBase2, base1, base2, Ledger_ValidateProject 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_ReferenceByCostcenter,0) As Module_ReferenceByCostcenter,".
			 " ifNull(Module_ReferenceByProject,0) As Module_ReferenceByProject, ifNull(Module_ProjectDt,0) As Module_ProjectDt, ifNull(Module_CostCenterDt,0) As Module_CostCenterDt, ".
			 " ifnull(Module_RestrictProjCost,0) as Module_RestrictProjCost, ifnull(Module_RestrictCost,0) as Module_RestrictCost, 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);
}

//User Access
$querylog=" select ifNull(login_belongstogrp,0) As FI_BelongsToGrp ".
		  " 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);
}

$mode 		 = $_GET['mode']; if ($mode == ""){$mode = $_POST["mode"];}
$mainmode    = $_GET['mainmode'];if ($mainmode == ""){$mainmode = $_POST["mainmode"];}
$SJourId     = $_GET['SJourId'];if ($SJourId == ""){$SJourId = $_POST["SJourId"];}
$SJourDtId   = $_GET['SJourDtId'];if ($SJourDtId == ""){$SJourDtId = $_POST["SJourDtId"];}
$SJourDivId  = $_GET['SJourDivId'];if ($SJourDivId == ""){$SJourDivId = $_POST["SJourDivId"];}
$SChkJourId  = $_GET['SChkJourId'];if ($SChkJourId == ""){$SChkJourId = $_POST["SChkJourId"];}
$SBillJourId = $_GET['SBillJourId'];if ($SBillJourId == ""){$SBillJourId = $_POST["SBillJourId"];}
$SCstJourId  = $_GET['SCstJourId'];if ($SCstJourId == ""){$SCstJourId = $_POST["SCstJourId"];}
$InTempJour	 = $_GET['InTempJour']; if ($InTempJour == ""){$InTempJour = $_POST["InTempJour"];}

$message='';
					
	
	
$PJourDate= $_POST["PJourDate"]; if ($PJourDate == ""){$PJourDate = $_GET["PJourDate"];}
$PJourId= $_POST["PJourId"]; if ($PJourId == ""){$PJourId = $_GET["PJourId"];}
$PJourDtId= $_POST["PJourDtId"]; if ($PJourDtId == ""){$PJourDtId = $_GET["PJourDtId"];}
$PJourType= $_POST["PJourType"]; if ($PJourType == ""){$PJourType = $_GET["PJourType"];}
$PRemark= $_POST["PRemark"]; if ($PRemark == ""){$PRemark = $_GET["PRemark"];}
$PManualNo= $_POST["PManualNo"]; if ($PManualNo == ""){$PManualNo = $_GET["PManualNo"];}
$PProjectCode= $_POST["PProjectCode"]; if ($PProjectCode == ""){$PProjectCode = $_GET["PProjectCode"];}
$PCostCentCode= $_POST["PCostCentCode"]; if ($PCostCentCode == ""){$PCostCentCode = $_GET["PCostCentCode"];}

$txtJourDate= $_POST["txtJourDate"]; if ($txtJourDate == ""){$txtJourDate = $_GET["txtJourDate"];}
$txtJourType= $_POST["txtJourType"]; if ($txtJourType == ""){$txtJourType = $_GET["txtJourType"];}
$txtRemark= $_POST["txtRemark"]; if ($txtRemark == ""){$txtRemark = $_GET["txtRemark"];}
$txtManualNo= $_POST["txtManualNo"]; if ($txtManualNo == ""){$txtManualNo = $_GET["txtManualNo"];}
$txtProjectCode= $_POST["txtProjectCode"]; if ($txtProjectCode == ""){$txtProjectCode = $_GET["txtProjectCode"];}
$txtCostCentCode= $_POST["txtCostCentCode"]; if ($txtCostCentCode == ""){$txtCostCentCode = $_GET["txtCostCentCode"];}

	
$txtLedgerId= $_POST["txtLedgerId"]; if ($txtLedgerId == ""){$txtLedgerId = $_GET["txtLedgerId"];}
$txtLedgerNo= $_POST["txtLedgerNo"]; if ($txtLedgerNo == ""){$txtLedgerNo = $_GET["txtLedgerNo"];}
$txtCurrencyCode= $_POST["txtCurrencyCode"]; if ($txtCurrencyCode == ""){$txtCurrencyCode = $_GET["txtCurrencyCode"];}
$txtJourDtdbcd= $_POST["txtJourDtdbcd"]; if ($txtJourDtdbcd == ""){$txtJourDtdbcd = $_GET["txtJourDtdbcd"];}
$txtJourDtDesc= $_POST["txtJourDtDesc"]; if ($txtJourDtDesc == ""){$txtJourDtDesc = $_GET["txtJourDtDesc"];}
$txtJourDtDesc1= $_POST["txtJourDtDesc1"]; if ($txtJourDtDesc1 == ""){$txtJourDtDesc1 = $_GET["txtJourDtDesc1"];}
$txtValueDate= $_POST["txtValueDate"]; if ($txtValueDate == ""){$txtValueDate = $_GET["txtValueDate"];}
$txtJourDtManualNo= $_POST["txtJourDtManualNo"]; if ($txtJourDtManualNo == ""){$txtJourDtManualNo = $_GET["txtJourDtManualNo"];}
$txtJourDtAmount= $_POST["txtJourDtAmount"]; if ($txtJourDtAmount == ""){$txtJourDtAmount = $_GET["txtJourDtAmount"];}
$txtJourDtAmount1= $_POST["txtJourDtAmount1"]; if ($txtJourDtAmount1 == ""){$txtJourDtAmount1 = $_GET["txtJourDtAmount1"];}
$txtJourDtAmount2= $_POST["txtJourDtAmount2"]; if ($txtJourDtAmount2 == ""){$txtJourDtAmount2 = $_GET["txtJourDtAmount2"];}

$txtChkJourLedgerNo= $_POST["txtChkJourLedgerNo"]; if ($txtChkJourLedgerNo == ""){$txtChkJourLedgerNo = $_GET["txtChkJourLedgerNo"];}
$txtChkJourCurrCode= $_POST["txtChkJourCurrCode"]; if ($txtChkJourCurrCode == ""){$txtChkJourCurrCode = $_GET["txtChkJourCurrCode"];}
$txtChkJourType= $_POST["txtChkJourType"]; if ($txtChkJourType == ""){$txtChkJourType = $_GET["txtChkJourType"];}
$txtChkJourNumber= $_POST["txtChkJourNumber"]; if ($txtChkJourNumber == ""){$txtChkJourNumber = $_GET["txtChkJourNumber"];}
$txtChkJourBank= $_POST["txtChkJourBank"]; if ($txtChkJourBank == ""){$txtChkJourBank = $_GET["txtChkJourBank"];}
$txtChkJourValueDate= $_POST["txtChkJourValueDate"]; if ($txtChkJourValueDate == ""){$txtChkJourValueDate = $_GET["txtChkJourValueDate"];}
$txtChkJourAmount= $_POST["txtChkJourAmount"]; if ($txtChkJourAmount == ""){$txtChkJourAmount = $_GET["txtChkJourAmount"];}
$txtChkJourAmount1= $_POST["txtChkJourAmount1"]; if ($txtChkJourAmount1 == ""){$txtChkJourAmount1 = $_GET["txtChkJourAmount1"];}
$txtChkJourAmount2= $_POST["txtChkJourAmount2"]; if ($txtChkJourAmount2 == ""){$txtChkJourAmount2 = $_GET["txtChkJourAmount2"];}

$txtBillJourLedgerNo= $_POST["txtBillJourLedgerNo"]; if ($txtBillJourLedgerNo == ""){$txtBillJourLedgerNo = $_GET["txtBillJourLedgerNo"];}
$txtBillJourCurrCode= $_POST["txtBillJourCurrCode"]; if ($txtBillJourCurrCode == ""){$txtBillJourCurrCode = $_GET["txtBillJourCurrCode"];}
$txtBillJourType= $_POST["txtBillJourType"]; if ($txtBillJourType == ""){$txtBillJourType = $_GET["txtBillJourType"];}
$txtBillJourNumber= $_POST["txtBillJourNumber"]; if ($txtBillJourNumber == ""){$txtBillJourNumber = $_GET["txtBillJourNumber"];}
$txtBillJourBank= $_POST["txtBillJourBank"]; if ($txtBillJourBank == ""){$txtBillJourBank = $_GET["txtBillJourBank"];}
$txtBillJourValueDate= $_POST["txtBillJourValueDate"]; if ($txtBillJourValueDate == ""){$txtBillJourValueDate = $_GET["txtBillJourValueDate"];}
$txtBillJourAmount= $_POST["txtBillJourAmount"]; if ($txtBillJourAmount == ""){$txtBillJourAmount = $_GET["txtBillJourAmount"];}
$txtBillJourAmount1= $_POST["txtBillJourAmount1"]; if ($txtBillJourAmount1 == ""){$txtBillJourAmount1 = $_GET["txtBillJourAmount1"];}
$txtBillJourAmount2= $_POST["txtBillJourAmount2"]; if ($txtBillJourAmount2 == ""){$txtBillJourAmount2 = $_GET["txtBillJourAmount2"];}

$txtProjectCodeDt= $_POST["txtProjectCodeDt"]; if ($txtProjectCodeDt == ""){$txtProjectCodeDt = $_GET["txtProjectCodeDt"];}
$txtCostCentCodeDt= $_POST["txtCostCentCodeDt"]; if ($txtCostCentCodeDt == ""){$txtCostCentCodeDt = $_GET["txtCostCentCodeDt"];}
$txtCstJourPerc= $_POST["txtCstJourPerc"]; if ($txtCstJourPerc == ""){$txtCstJourPerc = $_GET["txtCstJourPerc"];}
$txtCstJourAmount= $_POST["txtCstJourAmount"]; if ($txtCstJourAmount == ""){$txtCstJourAmount = $_GET["txtCstJourAmount"];}
$txtCstJourAmount1= $_POST["txtCstJourAmount1"]; if ($txtCstJourAmount1 == ""){$txtCstJourAmount1 = $_GET["txtCstJourAmount1"];}
$txtCstJourAmount2= $_POST["txtCstJourAmount2"]; if ($txtCstJourAmount2 == ""){$txtCstJourAmount2 = $_GET["txtCstJourAmount2"];}
$txtjournaldtrate= $_POST["txtjournaldtrate"]; if ($txtjournaldtrate == ""){$txtjournaldtrate = $_GET["txtjournaldtrate"];}
$txtjournaldtrate2= $_POST["txtjournaldtrate2"]; if ($txtjournaldtrate2 == ""){$txtjournaldtrate2 = $_GET["txtjournaldtrate2"];}
$PJourDesc= $_POST["PJourDesc"]; if ($PJourDesc == ""){$PJourDesc = $_GET["PJourDesc"];}
$vChecksNo= $_POST["vChecksNo"]; if ($vChecksNo == ""){$vChecksNo = $_GET["vChecksNo"];}

$vJourdtDistCode = $_GET['journaldtdistcode'];

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


if ($mode == "submitrecord"  || $mode == "submitrecord-ajax" || $mode == "importexcel"){
	
	$ErrorExists = 0;
	
	if ($PCostCentCode != '') {
		$sub_query = " Select Count(Costcent_code) From Costcent ".
					 " Where Costcent_code = '".$PCostCentCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Costcenter Code.';
		}
	}
	if ($PProjectCode != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$PProjectCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Project Code.';
		}	
	}
	
	if ($mode != "importexcel"){
		if (!empty($txtLedgerNo) && isset($txtLedgerNo)) {
			$sub_query = " Select Count(Ledger_Number) From Ledger ".
						 " Where Ledger_Number = '".$txtLedgerNo."' and ifNull(Ledger_grpdet,0) = 0 ";
			$sub_result = selectData($connection, $sub_query);
			if ($sub_result[0] == 0) {
				$ErrorExists = 1;
				$message = "Insert not allowed. Please check for Ledger Number.";
			}
		}
	}
	
	//Insert Master Table
	if ($SJourId == "" && $ErrorExists == 0){

		fbegin();	
		//$vJournalId = GetNextSequence($connection,'Null','Null','ID','JOURNAL','JV','Null',date('Y-m-d H:i:s'),0,0);
		$vJournalId = get_nextsequence('journal_id','',$connection);	
		fcommit();
		
		//$PRemark = iconv('utf-8','windows-1256', $PRemark);
		
		fbegin();
		$query = " INSERT INTO temp_journal (Journal_ID, Journal_RefGovernment, Journal_Date, Journal_SysDate, Journal_Folio, Journal_Type, Journal_TypeRef, ".
				 " Journal_Remark, Manual_No, Amnt1_db, Amnt2_db, Amnt1_cd, Amnt2_cd, Journal_Posted, Journal_Flag, Journal_Edit, ".
				 " Journal_BelongsToGroup, Journal_Confirmed, Journal_ConfirmedUser, Project_Code, Costcent_Code, User_Account, Logged_Code ) ".
				 " VALUES ( ".GetSQLValueString($vJournalId,'double').", Null, ".GetSQLValueString(insertMySQLDate($PJourDate),'date').", ".
				 "          ".GetSQLValueString(insertMySQLDate(displayToday()),'date').", Null, ".GetSQLValueString($PJourType,'text').", Null, ".
				 "          ".GetSQLValueString($PRemark,'text').", ".GetSQLValueString($PManualNo,'text').", 0, 0, 0, 0, 0, 'N', 0, ".
				 "          ".GetSQLValueString($FI_BelongsToGrp,'double').", 0, Null, ".GetSQLValueString($PProjectCode,'text').", ".
				 "          ".GetSQLValueString($PCostCentCode,'text').", ".GetSQLValueString($_SESSION['useraccount'],'text').", ".
				 "          ".GetSQLValueString($_SESSION['useraccount'],'text')." )";

		$result=mysql_query($query,$connection);
		//echo $query."<br>";exit;	
		
		if ($result){
			$SJourId = $vJournalId;
			fcommit();
			
			//Insert Divisions For Journal
			//if ($Module_Project == 1)	
				//$message  = AddDivisions($SJourId,'Null',$PTransDivID,$PDivType,$PDivisionID,$PDivisionCode,0,0,0,$connection);
		}else{
			$SJourId = "";
			$message  = mysql_error($connection); 
			frollback();
		}
	
	}

	//Insert Detail Tables
	if ($SJourId != "" && $SJourDtId == "" && $ErrorExists == 0 && ($mode == "submitrecord" || $mode == "submitrecord-ajax")){
	
		$ErrorExists = 0;
	
		if (empty($txtJourDtAmount))	$txtJourDtAmount = 0;
		if (empty($txtJourDtAmount1))	$txtJourDtAmount1 = 0;
		if (empty($txtJourDtAmount2))	$txtJourDtAmount2 = 0;
		if (empty($txtjournaldtrate))	$txtjournaldtrate = 0;	
		if (empty($txtjournaldtrate2))	$txtjournaldtrate2 = 0;	
			
		$vJourDtdbcd  = '';
		$vLedgerId    = '';
		$vJourDtDesc  = '';
		$vJourDtDesc1 = '';
		$vCurrencyCode   = '';
		$vJourDtAmount   = 0;
		$vJourDtAmount1  = 0;
		$vJourDtAmount2  = 0;
		$vValueDate      = '';
		$vJourDtManualNo = '';
		
		
		$vJourAmountDb1 = 0;
		$vJourAmountDb2 = 0;
		$vJourAmountcd1 = 0;
		$vJourAmountcd2 = 0;
			
			
		$vJourDtdbcd     = $txtJourDtdbcd;
		$vLedgerId       = $txtLedgerId;
		$vLedgerNo       = $txtLedgerNo;
		$vJourDtDesc     = $txtJourDtDesc;
		$vJourDtDesc1    = $txtJourDtDesc1;
		$vCurrencyCode   = $txtCurrencyCode;
		$vJourDtAmount   = $txtJourDtAmount;
		$vJourDtAmount1  = $txtJourDtAmount1;
		$vJourDtAmount2  = $txtJourDtAmount2;
		$vValueDate 	 = $txtValueDate;
		$vJourDtManualNo = $txtJourDtManualNo;
		
		//if($vJourDtdbcd == 'D') $vJourDtdbcdar = 'م';
		//else $vJourDtdbcdar = 'د';
		
		$vJourDtdbcdar = $vJourDtdbcd;
		
		
		if (!empty($vLedgerNo) && isset($vLedgerNo)) {
			$sub_query = " Select Count(Ledger_Number) From Ledger ".
						 " Where Ledger_Number = '$vLedgerNo' and ifNull(Ledger_grpdet,0) = 0 ";
			$sub_result = selectData($connection, $sub_query);
			if ($sub_result[0] == 0) {
				$ErrorExists = 1;
				$message = "Incorrect Ledger Number.";
			}
		}
		
		if ($ErrorExists == 0) {			
			//fbegin();
			//$vJourDtId = GetNextSequence($connection,'Null','Null','ID','JOURNALDT','JV','Null',date('Y-m-d H:i:s'),0,0);
			//fcommit();
			
			$query_dtincr="select Journal_dtincr from temp_journal where journal_id=".$SJourId;
			$result_dtincr=mysql_query($query_dtincr,$connection);
			$row_dtincr=mysql_fetch_row($result_dtincr);
			
			//by nadine
		 	$querydt = "select ifnull(max(journaldt_id),0) from temp_journaldt where Journal_Id = ".$SJourId;
			$resdt = mysql_query($querydt, $connection);
			$rowdt = mysql_fetch_row($resdt);
			$MaxJourDtId = $rowdt[0];
			if ($MaxJourDtId == 0){			
				$dtincr = 1;
				$dtincr_pad = str_pad($dtincr, 6, '0', STR_PAD_LEFT);
				$vJourDtId = $SJourId.''.$dtincr_pad;
			}  
			else {
				$vJourDtId = $MaxJourDtId + 1;
			} 	 	
			
		//	$vJourDtDesc  = iconv('utf-8','windows-1256', $vJourDtDesc);
		//	$vJourDtDesc1 = iconv('utf-8','windows-1256', $vJourDtDesc1);
			
			fbegin();
			$query = " INSERT INTO temp_journaldt (JournalDt_Id, Journal_Id, Ledger_Number, Currency_Code, Journaldt_desc, Journaldt_desc1, Journaldt_dbcd, Journaldt_dbcdAra, ". 
					 " Journaldt_amount, Journaldt_amount1, Journaldt_amount2, Journal_Date, Journaldt_ValueDate, Journaldt_posted, manual_no, Logged_Code,journaldt_rate,journaldt_rate2, journaldt_distributeCode )  ".
					 " VALUES ( ".GetSQLValueString($vJourDtId,'double').", ".GetSQLValueString($SJourId,'double').", ".GetSQLValueString($vLedgerNo,'text').", ".GetSQLValueString($vCurrencyCode,'text').", ".
					 "          ".GetSQLValueString($vJourDtDesc,'text').", ".GetSQLValueString($vJourDtDesc1,'text').", ".GetSQLValueString($vJourDtdbcd,'text').", ".
					 "          ".GetSQLValueString($vJourDtdbcdar,'text').", ".GetSQLValueString($vJourDtAmount,'double').", ".GetSQLValueString($vJourDtAmount1,'double').", ".
					 "          ".GetSQLValueString($vJourDtAmount2,'double').", ".GetSQLValueString(insertMySQLDate($PJourDate),'date').", ".GetSQLValueString(insertMySQLDate($vValueDate),'date').", ".
					 "          0, ".GetSQLValueString($vJourDtManualNo,'text').", ".GetSQLValueString($_SESSION['useraccount'],'text').",$txtjournaldtrate,$txtjournaldtrate2, ".GetSQLValueString($vJourdtDistCode,'text')."	) ";
				 
			//echo $query."<br>";exit;				
			$result=mysql_query($query,$connection);
			
			if ($result){
			
				//Insert Divisions For JournalDt
				//if ($Module_Project == 1 || $Module_ProjectDt == 1)	
					//$message  = AddDivisionsDt_Dflt($SJourId,$vJourDtId,$vLedgerId,$vJourDtAmount,$vJourDtAmount1,$vJourDtAmount2,$connection);
			
				
				//Case Header Project or Costcenter Is Not Empty Automatically Insert Into CstjourDt	
				if ($Module_Project == 1 || $Module_CostCenter == 1 || $Module_ProjectDt == 1 || $Module_CostCenterDt == 1) {
					$vCstJourDtPer   = 100;
					$vCstJourDtAmt   = $vJourDtAmount;
					$vCstJourDtAmt1  = $vJourDtAmount1;
					$vCstJourDtAmt2  = $vJourDtAmount2;
					
					if ($journal_distribution == '1' && $vJourdtDistCode != ''){
						$queryDist = "select distribution_code from project where project_code='$vJourdtDistCode' ";
						$resDist = mysql_query($queryDist, $connection);
						$rowDist = mysql_fetch_row($resDist);
						
						$costcentParent = $rowDist[0];
						if ($costcentParent != '') {
						
							$query = "select costcent_code, ifnull(CostCent_Percentage,0), ($vJourDtAmount*ifnull(CostCent_Percentage,0))/100 as amnt, ($vJourDtAmount1*ifnull(CostCent_Percentage,0))/100 as amnt1,
										($vJourDtAmount2*ifnull(CostCent_Percentage,0))/100  as amnt2 from costcent
										where costcent_code like '$costcentParent%' and costcent_code <> '$costcentParent' "; 
							$result = mysql_query($query,$connection);
							while($row = mysql_fetch_array($result)){
								 if ($row[1] > 0){
									$queryCst = " INSERT INTO temp_cstjour (JournalDt_Id, Project_code, Costcent_Code, Cstjour_Prcnt, CstJour_Amount, CstJour_Amount1, CstJour_Amount2, ".
										 " Synchronized, User_Account, Logged_Code ) ". 
										 " VALUES ( ".GetSQLValueString($vJourDtId,'double').", ".GetSQLValueString($vJourdtDistCode,'text').", ".
										 "          ".GetSQLValueString($row[0],'text').", ".GetSQLValueString($row[1],'double').", ".
										 "          ".GetSQLValueString($row[2],'double').", ".GetSQLValueString($row[3],'double').", ".
										 "          ".GetSQLValueString($row[4],'double').", 0, ".GetSQLValueString($_SESSION['useraccount'],'text').", ".
										 "          ".GetSQLValueString($_SESSION['useraccount'],'text')."	) "; 
									$resCst = mysql_query($queryCst,$connection);
								} 
							}						
						}
					}
					else {
						if ($Ledger_ValidateProject == 1) {
							$sub_query = " Select Project_Code, CostCenter_code From Ledger Where Ledger_Number = '".$vLedgerNo."'";
							$sub_result = selectData($connection, $sub_query);
							
							if ($sub_result[0] != '') $PProjectCode = $sub_result[0];
							if ($sub_result[1] != '') $PCostCentCode = $sub_result[1];
						} 
						
						$vProjectCodeDt	 = $PProjectCode;
						$vCostCentCodeDt = $PCostCentCode;
					
						if ($PProjectCode != '' || $PCostCentCode != '' ) {
						
							$query = " INSERT INTO temp_cstjour (JournalDt_Id, Project_code, Costcent_Code, Cstjour_Prcnt, CstJour_Amount, CstJour_Amount1, CstJour_Amount2, ".
									 " Synchronized, User_Account, Logged_Code ) ". 
									 " VALUES ( ".GetSQLValueString($vJourDtId,'double').", ".GetSQLValueString($vProjectCodeDt,'text').", ".
									 "          ".GetSQLValueString($vCostCentCodeDt,'text').", ".GetSQLValueString($vCstJourDtPer,'double').", ".
									 "          ".GetSQLValueString($vCstJourDtAmt,'double').", ".GetSQLValueString($vCstJourDtAmt1,'double').", ".
									 "          ".GetSQLValueString($vCstJourDtAmt2,'double').", 0, ".GetSQLValueString($_SESSION['useraccount'],'text').", ".
									 "          ".GetSQLValueString($_SESSION['useraccount'],'text')."	) ";
							//$message=$query;
							//echo $query."<br>";exit;				
							$result=mysql_query($query,$connection);
						}	
					}
				}

				if ($ChecksNo == '1' && $vJourDtId != '')	{
					fbegin();
		             $querychk = " INSERT INTO temp_chkjour (JournalDt_Id, Ledger_Number, Chk_Number, Chk_Bank, Chk_ValueDate, Chk_Type,         Currency_Code,  Chk_Amount, Chk_Amount1, Chk_Amount2 ) ". 
				          " VALUES ( ".GetSQLValueString($vJourDtId,'double').", ".GetSQLValueString($vLedgerNo,'text').",".GetSQLValueString($vChecksNo,'text').", ".
				       "          ".GetSQLValueString($vJourDtDesc,'text').", ".GetSQLValueString(insertMySQLDate($vValueDate),'date').", ".GetSQLValueString($vJourDtdbcd,'text').", ".GetSQLValueString($vCurrencyCode,'text').", ".
				      "          ".GetSQLValueString($vJourDtAmount,'double').", ".GetSQLValueString($vJourDtAmount1,'double').", ".GetSQLValueString($vJourDtAmount2,'double').") ";

		//echo $query."<br>";exit;				
		$resultchk=mysql_query($querychk,$connection);
			
		if ($resultchk){
			fcommit();
		} else{
			$message  .= mysql_error($connection); 
			frollback();
		}
				}
				
				/*if ($ChecksNo == '0')	{
					fbegin();
		             $querychk = " INSERT INTO temp_chkjour (JournalDt_Id, Ledger_Number, Chk_Number, Chk_Bank, Chk_ValueDate, Chk_Type,Currency_Code,  Chk_Amount, Chk_Amount1, Chk_Amount2 )  select ".GetSQLValueString($vJourDtId,'double').", Ledger_Number, Chk_Number, Chk_Bank, Chk_ValueDate, Chk_Type,Currency_Code,  Chk_Amount, Chk_Amount1, Chk_Amount2 from chkjour where Ledger_Number=".GetSQLValueString($vLedgerNo,'text');

					//$message = $query."<br>";//exit;				
					$resultchk=mysql_query($querychk,$connection);
						
					if ($resultchk){
						fcommit();
					} else{
						$message  .= mysql_error($connection); 
						frollback();
					}
				}*/
			
			
				$dtincr=$dtincr+1;
				$query_update_dtincr="update temp_journal set Journal_dtincr=$dtincr where journal_id=".$SJourId;
				$result_dtincr=mysql_query($query_update_dtincr,$connection);
				
				$sub_query = " Select Sum(if(Journaldt_dbcd='D', ifNull(Journaldt_amount1,0), 0)) As TotalDebitAmount1, Sum(if(Journaldt_dbcd='D', ifNull(Journaldt_amount2,0), 0)) As TotalDebitAmount2, ".
							 " Sum(if(Journaldt_dbcd='C', ifNull(Journaldt_amount1,0), 0)) As TotalCreditAmount1, Sum(if(Journaldt_dbcd='C', ifNull(Journaldt_amount2,0), 0)) As TotalCreditAmount2 ".
							 " From Temp_JournalDt ".
							 " Where Journal_Id = ".$SJourId;
				$sub_result = selectData($connection, $sub_query);
				
				$vJourAmountDb1 = $sub_result[0];
				$vJourAmountDb2 = $sub_result[1];
				$vJourAmountcd1 = $sub_result[2];
				$vJourAmountcd2 = $sub_result[3];
				
																																																					
				$sub_query1 = " UPDATE temp_journal SET ".
							  " Amnt1_db = $vJourAmountDb1, Amnt2_db = $vJourAmountDb2, ".
							  " Amnt1_cd = $vJourAmountcd1, Amnt2_cd = $vJourAmountcd2, ".
							  " Journal_Date = ".GetSQLValueString(insertMySQLDate($PJourDate),'date').", ".
							  " Journal_Remark = ".GetSQLValueString($PRemark,'text').", ".
							  " Journal_Type = ".GetSQLValueString($PJourType,'text').",  ".
							  " Manual_No = ".GetSQLValueString($PManualNo,'text')."  ".
							  " WHERE Journal_Id = ".$SJourId;
					 
				$sub_result1=mysql_query($sub_query1,$connection);
				//echo $sub_query1."<br>";exit;

					
							 
				fcommit();
			} else{
				$message  = mysql_error($connection); 
				frollback();
			}	
		}
		
	} // End Case Insert In Detail Tables
	
	else if ($SJourId != "" && $SJourDtId == "" && $ErrorExists == 0 && $mode == "importexcel"){
	
		$file = $_FILES['excelfile']['tmp_name'];
		
		if (isset($_FILES['excelfile']) && $_FILES['excelfile']['size'] > 0) { 

			$file_name = addslashes($_FILES['excelfile']['name']);
			$file_type =trim($_FILES['excelfile']['type']);
			
			//echo $file_type; exit;
			if (($file_type != 'application/vnd.ms-excel') && ($file_type != 'application/excel') && 
			    ($file_type != 'application/vnd.msexcel') )
			{
				$message = "Invalid file type. Please use only .xls files.";
			}
			else {
				
				$uploaddir = './uploadsexcel/'; //assigns upload directory 
				if (!is_dir($uploaddir)) mkdir($uploaddir, 0700);
				
				$uploadfile = $uploaddir . basename($_FILES['excelfile']['name']); //assigns upload directory and file name 
				if (move_uploaded_file($_FILES['excelfile']['tmp_name'], $uploadfile)) { 
				
					require_once('Spreadsheet/Excel/Reader.php');
					
					// ExcelFile($filename, $encoding);
					$data = new Spreadsheet_Excel_Reader();

					// Set output Encoding.
					$data->setUTFEncoder('iconv');
					$data->setOutputEncoding('CP1251');
					$data->read($uploadfile);
					
					if ($_FILES["excelfile"]["error"] == 0){
					
						$vExistsSerials = '';
						for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) {
							
							$vJourDtDesc1    = '';
							$vValueDate      = '';
							$vJourDtManualNo = '';
							
							$vJourAmountDb1 = 0;
							$vJourAmountDb2 = 0;
							$vJourAmountcd1 = 0;
							$vJourAmountcd2 = 0;
		
							$vLedgerNo 		= $data->sheets[0]['cells'][$i][1];
							$vJourDtDesc	= $data->sheets[0]['cells'][$i][3];
							$vCurrencyCode	= $data->sheets[0]['cells'][$i][4];
							$vJourDtdbcd	= $data->sheets[0]['cells'][$i][5];
							$vJourDtAmount	= $data->sheets[0]['cells'][$i][6];
							$vJourDtAmount1	= $data->sheets[0]['cells'][$i][7];
							$vJourDtAmount2	= $data->sheets[0]['cells'][$i][8];
							$vJourDtdbcdar  = $vJourDtdbcd;
							
							
							if (!empty($vLedgerNo) && isset($vLedgerNo)) {
								$sub_query = " Select Count(Ledger_Number) From Ledger ".
											 " Where Ledger_Number = $vLedgerNo and ifNull(Ledger_grpdet,0) = 0 ";
								$sub_result = selectData($connection, $sub_query);
								if ($sub_result[0] == 0) {
									$ErrorExists = 1;
									$message = "Incorrect Ledger Number.";
								}
							}
					
							
							if ($ErrorExists == 0){
							
								$query_dtincr="select Journal_dtincr from temp_journal where journal_id=".$SJourId;
								$result_dtincr=mysql_query($query_dtincr,$connection);
								$row_dtincr=mysql_fetch_row($result_dtincr);
								
								$dtincr = $row_dtincr[0];
								$dtincr_pad = str_pad($dtincr, 6, '0', STR_PAD_LEFT);
								$vJourDtId = $SJourId.''.$dtincr_pad;
									
								
								fbegin();
								$query = " INSERT INTO temp_journaldt (JournalDt_Id, Journal_Id, Ledger_Number, Currency_Code, Journaldt_desc, Journaldt_desc1, Journaldt_dbcd, Journaldt_dbcdAra, ". 
										 " Journaldt_amount, Journaldt_amount1, Journaldt_amount2, Journal_Date, Journaldt_ValueDate, Journaldt_posted, manual_no, Logged_Code )  ".
										 " VALUES ( ".GetSQLValueString($vJourDtId,'double').", ".GetSQLValueString($SJourId,'double').", ".GetSQLValueString($vLedgerNo,'text').", ".GetSQLValueString($vCurrencyCode,'text').", ".
										 "          ".GetSQLValueString($vJourDtDesc,'text').", ".GetSQLValueString($vJourDtDesc1,'text').", ".GetSQLValueString($vJourDtdbcd,'text').", ".
										 "          ".GetSQLValueString($vJourDtdbcdar,'text').", ".GetSQLValueString($vJourDtAmount,'double').", ".GetSQLValueString($vJourDtAmount1,'double').", ".
										 "          ".GetSQLValueString($vJourDtAmount2,'double').", ".GetSQLValueString(insertMySQLDate($PJourDate),'date').", ".GetSQLValueString(insertMySQLDate($PJourDate),'date').", ".
										 "          0, ".GetSQLValueString($vJourDtManualNo,'text').", ".GetSQLValueString($_SESSION['useraccount'],'text')."	) ";
									 
								//echo $query."<br>";exit;				
								$result=mysql_query($query,$connection);
								
								if ($result){
				
									//Case Header Project or Costcenter Is Not Empty Automatically Insert Into CstjourDt	
									if (($Module_Project == 1 || $Module_CostCenter == 1 || $Module_ProjectDt == 1 || $Module_CostCenterDt == 1) && ($PProjectCode != '' || $PCostCentCode != '' )) {
										$vCstJourDtPer   = 100;
										$vCstJourDtAmt   = $vJourDtAmount;
										$vCstJourDtAmt1  = $vJourDtAmount1;
										$vCstJourDtAmt2  = $vJourDtAmount2;
										$vProjectCodeDt	 = $PProjectCode;
										$vCostCentCodeDt = $PCostCentCode;
									
										$query = " INSERT INTO temp_cstjour (JournalDt_Id, Project_code, Costcent_Code, Cstjour_Prcnt, CstJour_Amount, CstJour_Amount1, CstJour_Amount2, ".
												 " Synchronized, User_Account, Logged_Code ) ". 
												 " VALUES ( ".GetSQLValueString($vJourDtId,'double').", ".GetSQLValueString($vProjectCodeDt,'text').", ".
												 "          ".GetSQLValueString($vCostCentCodeDt,'text').", ".GetSQLValueString($vCstJourDtPer,'double').", ".
												 "          ".GetSQLValueString($vCstJourDtAmt,'double').", ".GetSQLValueString($vCstJourDtAmt1,'double').", ".
												 "          ".GetSQLValueString($vCstJourDtAmt2,'double').", 0, ".GetSQLValueString($_SESSION['useraccount'],'text').", ".
												 "          ".GetSQLValueString($_SESSION['useraccount'],'text')."	) ";
									 
										//echo $query."<br>";exit;				
										$result=mysql_query($query,$connection);
									}

									
									$dtincr=$dtincr+1;
									$query_update_dtincr="update temp_journal set Journal_dtincr=$dtincr where journal_id=".$SJourId;
									$result_dtincr=mysql_query($query_update_dtincr,$connection);
									
									$sub_query = " Select Sum(if(Journaldt_dbcd='D', ifNull(Journaldt_amount1,0), 0)) As TotalDebitAmount1, Sum(if(Journaldt_dbcd='D', ifNull(Journaldt_amount2,0), 0)) As TotalDebitAmount2, ".
												 " Sum(if(Journaldt_dbcd='C', ifNull(Journaldt_amount1,0), 0)) As TotalCreditAmount1, Sum(if(Journaldt_dbcd='C', ifNull(Journaldt_amount2,0), 0)) As TotalCreditAmount2 ".
												 " From Temp_JournalDt ".
												 " Where Journal_Id = ".$SJourId;
									$sub_result = selectData($connection, $sub_query);
									
									$vJourAmountDb1 = $sub_result[0];
									$vJourAmountDb2 = $sub_result[1];
									$vJourAmountcd1 = $sub_result[2];
									$vJourAmountcd2 = $sub_result[3];
									
																																																										
									$sub_query1 = " UPDATE temp_journal SET ".
												  " Amnt1_db = $vJourAmountDb1, Amnt2_db = $vJourAmountDb2, ".
												  " Amnt1_cd = $vJourAmountcd1, Amnt2_cd = $vJourAmountcd2 ".
												  " WHERE Journal_Id = ".$SJourId;
										 
									$sub_result1=mysql_query($sub_query1,$connection);
									//echo $sub_query1."<br>";exit;

										
												 
									fcommit();
								} else{
									$message  = mysql_error($connection); 
									frollback();
								}
			
							}
						
						}
						
					}
					else {
						$message = $_FILES["excelfile"]["error"];
					}
				
				} else 
				{ 
					$message = "File upload failed."; 
				}
				
			}
			
		} else {
			$message = "File not found.";
		}
	
	}

} 
	
//Delete Detail Mode
else if ($mode == "deletedt" && $SJourDtId != ""){

	$AllowDelete = 1;
	$ErrorExists = 0;
	$message  = '';
	
	$vJourAmountDb1 = 0;
	$vJourAmountDb2 = 0;
	$vJourAmountcd1 = 0;
	$vJourAmountcd2 = 0;
	
	
	if ($AllowDelete == 1) {
		//Check Each JournalDt If Has Related Checks Used
		$query = " Select Count(*) ".
				 " From Checks Inner Join JournalDt on Checks.Journaldt_Id1 = JournalDt.JournalDt_Id ".
				 " Inner Join ChkJour on Checks.Chk_Number = ChkJour.Chk_Number and Checks.Ledger_Number = ChkJour.Ledger_Number  ".
				 " Where JournalDt.JournalDt_Id = '".$SJourDtId."' ".
				 " And ChkJour.JournalDt_Id = '".$SJourDtId."' ".
				 " And (ifNull(Checks.Journaldt_id2,0) != 0 and Checks.Journaldt_id2 != '' and Checks.Journaldt_id2 Is Not Null) ";

		$result = selectData($connection, $query);
		$ChecksExists = $result[0];
			
		if ($ChecksExists > 0 ){
			$message  = 'Delete not allowed. Checks Collected / Paid.';
			$AllowDelete = 0;
		}
	}	
	
	if ($AllowDelete == 1) {
		//Check Each JournalDt If Has Related Checks Used
		$query = " Select Count(*) ".
				 " From Bills Inner Join JournalDt on Bills.Journaldt_Id1 = JournalDt.JournalDt_Id ".
				 " Inner Join BillJour on Bills.Bill_Number = BillJourDt.Bill_Number and Bills.Ledger_Number = BillJourDt.Ledger_Number  ".
				 " Where JournalDt.JournalDt_Id = '".$SJourDtId."' ".
				 " And BillJour.JournalDt_Id = '".$SJourDtId."' ".
				 " And (ifNull(Bills.Journaldt_id2,0) != 0 and Bills.Journaldt_id2 != '' and Bills.Journaldt_id2 Is Not Null) ";

		$result = selectData($connection, $query);
		$BillsExists = $result[0];
			
		if ($BillsExists > 0 ){
			$message  = 'Delete not allowed. Bills Collected / Paid.';
			$AllowDelete = 0;
		}
	}

		
	//If No Constraints Exists On Delete
	if ($AllowDelete == 1) {

		
		fbegin();
		// Delete From Temp_CstJour For Selected Record
		$query = " DELETE FROM Temp_CstJour ".
				 " WHERE Temp_CstJour.JournalDt_Id = ".$SJourDtId;
		//echo $query;		 
		if (!updateData($connection, $query, true))
			$message  = mysql_error($connection);
		
		// Delete From Temp_Chkjour For Selected Record
		$query = " DELETE FROM Temp_Chkjour ".
				 " WHERE Temp_Chkjour.JournalDt_Id = ".$SJourDtId;
		//echo $query;				
		if (!updateData($connection, $query, true))		 
			$message  = mysql_error($connection); 	
				
		// Delete From Temp_Billjour For Selected Record
		$query = " DELETE FROM Temp_Billjour ".
				 " WHERE Temp_Billjour.JournalDt_Id = ".$SJourDtId;
					 
		if (!updateData($connection, $query, true))		 
			$message  = mysql_error($connection); 			 
				 
		// Delete From Temp_JournalDt For Selected Record
		$query = " DELETE FROM Temp_JournalDt ".
				 " WHERE JournalDt_Id = ".$SJourDtId;
					 
		if (!updateData($connection, $query, true)) {
			$message  = mysql_error($connection);
			$ErrorExists = 1;
			frollback();
		}  
		else {
			fcommit();
		}
			
			
	
			
		if ( $ErrorExists == 0 ){ 
			
			$sub_query = " Select Sum(if(Journaldt_dbcd='D', ifNull(Journaldt_amount1,0), 0)) As TotalDebitAmount1, Sum(if(Journaldt_dbcd='D', ifNull(Journaldt_amount2,0), 0)) As TotalDebitAmount2, ".
						 " Sum(if(Journaldt_dbcd='C', ifNull(Journaldt_amount1,0), 0)) As TotalCreditAmount1, Sum(if(Journaldt_dbcd='C', ifNull(Journaldt_amount2,0), 0)) As TotalCreditAmount2 ".
						 " From Temp_JournalDt ".
						 " Where Journal_Id = ".$SJourId;
			$sub_result = selectData($connection, $sub_query);
			
			$vJourAmountDb1 = $sub_result[0];
			$vJourAmountDb2 = $sub_result[1];
			$vJourAmountcd1 = $sub_result[2];
			$vJourAmountcd2 = $sub_result[3];
			
			if(empty($vJourAmountDb1)) $vJourAmountDb1 = 0;
			if(empty($vJourAmountDb2)) $vJourAmountDb2 = 0;
			if(empty($vJourAmountcd1)) $vJourAmountcd1 = 0;
			if(empty($vJourAmountcd2)) $vJourAmountcd2 = 0;
																																																							  
			fbegin();
			$sub_query1 = " UPDATE temp_journal SET ".
						  " Amnt1_db = $vJourAmountDb1, Amnt2_db = $vJourAmountDb2, ".
						  " Amnt1_cd = $vJourAmountcd1, Amnt2_cd = $vJourAmountcd2 ".
						  " WHERE Journal_Id = ".$SJourId;
			
			$sub_result1=mysql_query($sub_query1,$connection);
			//echo $sub_query1."<br>";exit;
				
			if ( $sub_result1 ){ 
				fcommit();
			} else
			{
			   $message  = mysql_error($connection); 
			   frollback();
			} 
		} // End If No Error Exists 
			
			
	
	} // End If No Constraints Found On Delete
	
	
}

//Edit Detail Tables
else if (($mode == "editdt" || $mode == "editdt-ajax") && $SJourId != "" && $SJourDtId != ""){

	$ErrorExists = 0;
	
	if (empty($txtJourDtAmount))	$txtJourDtAmount = 0;
	if (empty($txtJourDtAmount1))	$txtJourDtAmount1 = 0;
	if (empty($txtJourDtAmount2))	$txtJourDtAmount2 = 0;
	if (empty($txtjournaldtrate))	$txtjournaldtrate = 0;		
	if (empty($txtjournaldtrate2))	$txtjournaldtrate2 = 0;
	
	$vJourDtdbcd  = '';
	$vLedgerId    = '';
	$vJourDtDesc  = '';
	$vJourDtDesc1 = '';
	$vCurrencyCode   = '';
	$vJourDtAmount   = 0;
	$vJourDtAmount1  = 0;
	$vJourDtAmount2  = 0;
	$vValueDate      = '';
	$vJourDtManualNo = '';
		
	$vJourAmountDb1 = 0;
	$vJourAmountDb2 = 0;
	$vJourAmountcd1 = 0;
	$vJourAmountcd2 = 0;
			
			
	$vJourDtdbcd     = $txtJourDtdbcd;
	$vLedgerId       = $txtLedgerId;
	$vLedgerNo       = $txtLedgerNo;
	$vJourDtDesc     = $txtJourDtDesc;
	$vJourDtDesc1    = $txtJourDtDesc1;
	$vCurrencyCode   = $txtCurrencyCode;
	$vJourDtAmount   = $txtJourDtAmount;
	$vJourDtAmount1  = $txtJourDtAmount1;
	$vJourDtAmount2  = $txtJourDtAmount2;
	$vValueDate 	 = $txtValueDate;
	$vJourDtManualNo = $txtJourDtManualNo;
		
	//if($vJourDtdbcd == 'D') $vJourDtdbcdar = 'م';
	//else $vJourDtdbcdar = 'د';
	$vJourDtdbcdar = $vJourDtdbcd;

	
	if (!empty($vLedgerNo) && isset($vLedgerNo)) {
		$sub_query = " Select Count(Ledger_Number) From Ledger ".
					 " Where Ledger_Number = $vLedgerNo and ifNull(Ledger_grpdet,0) = 0";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = "Incorrect Ledger Number.";
		}
	}
	
	//$vJourDtDesc  = iconv('utf-8','windows-1256', $vJourDtDesc);
//	$vJourDtDesc1 = iconv('utf-8','windows-1256', $vJourDtDesc1);
		
	if ($ErrorExists == 0) {	
	
		fbegin();
		$query = " UPDATE temp_journaldt SET ".
				 " Currency_Code = ".GetSQLValueString($vCurrencyCode,'text').", Ledger_Number = ".GetSQLValueString($vLedgerNo,'text').
				 ",Journaldt_desc = ".GetSQLValueString($vJourDtDesc,'text').", Journaldt_desc1 = ".GetSQLValueString($vJourDtDesc1,'text').
				 ",Journaldt_dbcd = ".GetSQLValueString($vJourDtdbcd,'text').", Journaldt_dbcdAra = ".GetSQLValueString($vJourDtdbcdar,'text').
				 ",Journaldt_amount = ".GetSQLValueString($vJourDtAmount,'double').", Journaldt_amount1 = ".GetSQLValueString($vJourDtAmount1,'double').
				 ",Journaldt_amount2 = ".GetSQLValueString($vJourDtAmount2,'double').", Journaldt_ValueDate = ".GetSQLValueString(insertMySQLDate($vValueDate),'date').
				 ",manual_no = ".GetSQLValueString($vJourDtManualNo,'text').", journaldt_rate =  ".GetSQLValueString($txtjournaldtrate,'double').
				 ",journaldt_rate2 =  ".GetSQLValueString($txtjournaldtrate2,'double')." , journaldt_distributeCode = ".GetSQLValueString($vJourdtDistCode,'text')." ".
				 " WHERE JournalDt_Id = '".$SJourDtId."'";

		//echo $query."<br>";exit;				
		$result=mysql_query($query,$connection);
			
		if ($result){
			$sub_query = " Select Sum(if(Journaldt_dbcd='D', ifNull(Journaldt_amount1,0), 0)) As TotalDebitAmount1, Sum(if(Journaldt_dbcd='D', ifNull(Journaldt_amount2,0), 0)) As TotalDebitAmount2, ".
						 " Sum(if(Journaldt_dbcd='C', ifNull(Journaldt_amount1,0), 0)) As TotalCreditAmount1, Sum(if(Journaldt_dbcd='C', ifNull(Journaldt_amount2,0), 0)) As TotalCreditAmount2 ".
						 " From Temp_JournalDt ".
						 " Where Journal_Id = ".$SJourId;
			$sub_result = selectData($connection, $sub_query);
				
			$vJourAmountDb1 = $sub_result[0];
			$vJourAmountDb2 = $sub_result[1];
			$vJourAmountcd1 = $sub_result[2];
			$vJourAmountcd2 = $sub_result[3];
				
																																																								  
			$sub_query1 = " UPDATE temp_journal SET ".
						  " Amnt1_db = $vJourAmountDb1, Amnt2_db = $vJourAmountDb2, ".
						  " Amnt1_cd = $vJourAmountcd1, Amnt2_cd = $vJourAmountcd2 ".
						  " WHERE Journal_Id = ".$SJourId;
					 
			$sub_result1=mysql_query($sub_query1,$connection);
			//echo $sub_query1."<br>";exit;
			
			if ($Module_Project == 1 || $Module_CostCenter == 1 || $Module_ProjectDt == 1 || $Module_CostCenterDt == 1) {

				
				if ($journal_distribution == '1' && $vJourdtDistCode != ''){
					$querydt = "delete from temp_cstjour where JournalDt_Id = $SJourDtId ";
					$resdt = mysql_query($querydt, $connection);
					$queryDist = "select distribution_code from project where project_code='$vJourdtDistCode' ";
					$resDist = mysql_query($queryDist, $connection);
					$rowDist = mysql_fetch_row($resDist);
					
					$costcentParent = $rowDist[0];
					if ($costcentParent != '') {
					
						$query = "select costcent_code, ifnull(CostCent_Percentage,0), ($vJourDtAmount*ifnull(CostCent_Percentage,0))/100 as amnt, ($vJourDtAmount1*ifnull(CostCent_Percentage,0))/100 as amnt1,
									($vJourDtAmount2*ifnull(CostCent_Percentage,0))/100  as amnt2 from costcent
									where costcent_code like '$costcentParent%' and costcent_code <> '$costcentParent' "; 
						$result = mysql_query($query,$connection);
						while($row = mysql_fetch_array($result)){
							 if ($row[1] > 0){
								$queryCst = " INSERT INTO temp_cstjour (JournalDt_Id, Project_code, Costcent_Code, Cstjour_Prcnt, CstJour_Amount, CstJour_Amount1, CstJour_Amount2, ".
									 " Synchronized, User_Account, Logged_Code ) ". 
									 " VALUES ( ".GetSQLValueString($SJourDtId,'double').", ".GetSQLValueString($vJourdtDistCode,'text').", ".
									 "          ".GetSQLValueString($row[0],'text').", ".GetSQLValueString($row[1],'double').", ".
									 "          ".GetSQLValueString($row[2],'double').", ".GetSQLValueString($row[3],'double').", ".
									 "          ".GetSQLValueString($row[4],'double').", 0, ".GetSQLValueString($_SESSION['useraccount'],'text').", ".
									 "          ".GetSQLValueString($_SESSION['useraccount'],'text')."	) "; 
								$resCst = mysql_query($queryCst,$connection);
							} 
						}						
					}
				}
				else {
					$sub_query2 = " Select Cst_increment ".
								  " From Temp_CstJour As CstJour ".
								  " Where CstJour.JournalDt_Id = '".$SJourDtId."' ";	
					
					$sub_result2=mysql_query($sub_query2,$connection);			  
					while($sub_rows2=mysql_fetch_array($sub_result2)){			  
						
						$sub_query3 = " UPDATE Temp_CstJour SET ".
									  " CstJour_Amount  = ((ifNull(CstJour_Prcnt,0) * $vJourDtAmount)/100), ".
									  " CstJour_Amount1 = ((ifNull(CstJour_Prcnt,0) * $vJourDtAmount1)/100), ".
									  " CstJour_Amount2 = ((ifNull(CstJour_Prcnt,0) * $vJourDtAmount2)/100) ".
									  " WHERE Cst_increment = '".$sub_rows2[0]."'";
								 
						$sub_result3=mysql_query($sub_query3,$connection);
						//echo $sub_query3."<br>";exit;
					}	
				}
			}
					
			fcommit();
		} else{
			$message  = mysql_error($connection); 
			frollback();
		}

	}
} 

else if ($mode == "insertdivisiondt" && $SJourId != "" && $SJourDtId != ""){
	
	$ErrorExists = 0;
	
	if (empty($txtCstJourPerc))		$txtCstJourPerc = 0;
	if (empty($txtCstJourAmount))	$txtCstJourAmount = 0;
	if (empty($txtCstJourAmount1))	$txtCstJourAmount1 = 0;
	if (empty($txtCstJourAmount2))	$txtCstJourAmount2 = 0;
	
	if ($txtProjectCodeDt != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$txtProjectCodeDt."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Detail Project Code.';
		}
	}
	if ($txtCostCentCodeDt != '') {
		$sub_query = " Select Count(Costcent_code) From Costcent ".
					 " Where Costcent_code = '".$txtCostCentCodeDt."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Detail Costcenter Code.';
		}
	}
			
			
	if ($ErrorExists == 0) {
		
		/*fbegin();
		$vTransDivID = GetNextSequence($connection,'Null','Null','ID','TRANSACTIONDIVISIONS','JV','Null',date('Y-m-d H:i:s'),0,0);
		fcommit();*/
						
		fbegin();
		$query = " INSERT INTO temp_cstjour (JournalDt_Id, Project_code, Costcent_Code, Cstjour_Prcnt, CstJour_Amount, CstJour_Amount1, CstJour_Amount2, ".
							 " Synchronized, User_Account, Logged_Code ) ". 
							 " VALUES ( ".GetSQLValueString($SJourDtId,'double').", ".GetSQLValueString($txtProjectCodeDt,'text').", ".
							 "          ".GetSQLValueString($txtCostCentCodeDt,'text').", ".GetSQLValueString($txtCstJourPerc,'double').", ".
							 "          ".GetSQLValueString($txtCstJourAmount,'double').", ".GetSQLValueString($txtCstJourAmount1,'double').", ".
							 "          ".GetSQLValueString($txtCstJourAmount2,'double').", 0, ".GetSQLValueString($_SESSION['useraccount'],'text').", ".
							 "          ".GetSQLValueString($_SESSION['useraccount'],'text')."	) ";
				 
				 
		//echo $query."<br>";exit;				
		$result=mysql_query($query,$connection);
			
		if ($result){
			fcommit();
		} else{
			$message  = mysql_error($connection); 
			frollback();
		}	
	}	

} 


//Delete CstJourDt
else if ($mode == "deletedivisiondt" && $SCstJourId != ""){

	$AllowDelete = 1;
	$ErrorExists = 0;
	$message  = '';
	
	
		
	//If No Constraints Exists On Delete
	if ($AllowDelete == 1) {
		
		fbegin();
		
		// Delete From TempCstJourDt For Selected Record
		$query = " Delete From Temp_CstJour ".
				 " Where Cst_increment = '".$SCstJourId."'";
					 
		if (!updateData($connection, $query, true)) {
			$message  = mysql_error($connection);
			$ErrorExists = 1;
			frollback();
			$query = " DELETE FROM Temp_Chkjour ".
			 " WHERE Temp_Chkjour.JournalDt_Id In (Select JournalDt_Id From Temp_CstJour Where Cst_increment = '".$SCstJourId."') ";
				 
	if (!updateData($connection, $query, true))		 
		$message  = mysql_error($connection); 	
		}  
		else {
			fcommit();
		}
		
			
	
	} // End If No Constraints Found On Delete
	
	
}

//Edit CstJoutDt Table
else if ($mode == "editdivisiondt" && $SCstJourId != ""){

	$ErrorExists = 0;
	
	if (empty($txtCstJourPerc))		$txtCstJourPerc = 0;
	if (empty($txtCstJourAmount))	$txtCstJourAmount = 0;
	if (empty($txtCstJourAmount1))	$txtCstJourAmount1 = 0;
	if (empty($txtCstJourAmount2))	$txtCstJourAmount2 = 0;
		
	if ($txtProjectCodeDt != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$txtProjectCodeDt."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Detail Project Code.';
		}
	}
	if ($txtCostCentCodeDt != '') {
		$sub_query = " Select Count(Costcent_code) From Costcent ".
					 " Where Costcent_code = '".$txtCostCentCodeDt."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Detail Costcenter Code.';
		}
	}
	
	
	if ($ErrorExists == 0) {		
		fbegin();
		$query = " UPDATE Temp_CstJour SET ".
				 " Project_code = ".GetSQLValueString($txtProjectCodeDt,'text').", Costcent_Code = ".GetSQLValueString($txtCostCentCodeDt,'text').", ".
				 " Cstjour_Prcnt = ".GetSQLValueString($txtCstJourPerc,'double').", CstJour_Amount = ".GetSQLValueString($txtCstJourAmount,'double').", ". 
				 " CstJour_Amount1 = ".GetSQLValueString($txtCstJourAmount1,'double').", CstJour_Amount2 = ".GetSQLValueString($txtCstJourAmount2,'double').
				 " WHERE Cst_increment = '".$SCstJourId."'";

		//echo $query."<br>";exit;				
		$result=mysql_query($query,$connection);
			
		if ($result){
			
			fcommit();
		} else{
			$message  = mysql_error($connection); 
			frollback();
		}
	}
	
} 


// Insert ChkJourDt
else if ($mode == "insertchkjour" && $SJourId != "" && $SJourDtId != ""){
	
	$vChkJourId   = '';
	$vCheckNo     = '';
	$vBank        = '';
	$vChkJourValueDate = '';
	$vChkJourCurrCode  = '';
	$vChkJourLedgerNo  = '';
	$vChkJourType   = '';
	$vChkJourAmt    = 0;
	$vChkJourAmt1   = 0;
	$vChkJourAmt2   = 0;
	
	$vCheckExists = 0;
	
	if (empty($txtChkJourAmount))		$txtChkJourAmount = 0;
	if (empty($txtChkJourAmount1))		$txtChkJourAmount1 = 0;
	if (empty($txtChkJourAmount2))		$txtChkJourAmount2 = 0;
			
			

	$vCheckNo    	   = $txtChkJourNumber;
	$vBank       	   = $txtChkJourBank;
	$vChkJourValueDate = $txtChkJourValueDate;
	$vChkJourCurrCode  = $txtChkJourCurrCode;
	$vChkJourLedgerNo  = $txtChkJourLedgerNo;
	$vChkJourType      = $txtChkJourType;
	$vChkJourAmt       = $txtChkJourAmount;
	$vChkJourAmt1      = $txtChkJourAmount1;
	$vChkJourAmt2      = $txtChkJourAmount2;	
		
	
	if ($vChkJourType == 'A') {
		$sub_query=" select count(*) from checks ".
				   " where Ledger_Number = '".$vChkJourLedgerNo."' ". 
				   " and chk_number = '".$vCheckNo."' ";
				   
		//echo $sub_query;exit;
		$sub_result = selectData($connection, $sub_query);
		$vCheckExists = $sub_result[0];
	}
	
	if ($vChkJourType == 'A' && $vCheckExists == 0) {
		$sub_query= " select count(*) from temp_chkjour ".
		            " where Ledger_Number = '".$vChkJourLedgerNo."' ". 
					" and chk_number = '".$vCheckNo."'";
					
		//echo $sub_query;exit;
		$sub_result = selectData($connection, $sub_query);
		$vCheckExists = $sub_result[0];
	}
	
	
				 
	if ($vCheckExists == 0) {
		//fbegin();
		//$vChkJourId = GetNextSequence($connection,'Null','Null','ID','CHKJOUR','JV','Null',date('Y-m-d H:i:s'),0,0);
		//fcommit();
		
		fbegin();
		$query = " INSERT INTO temp_chkjour (JournalDt_Id, Ledger_Number, Chk_Number, Chk_Bank, Chk_ValueDate, Chk_Type, Currency_Code, Chk_Amount, Chk_Amount1, Chk_Amount2 ) ". 
				 " VALUES ( ".GetSQLValueString($SJourDtId,'double').", ".GetSQLValueString($vChkJourLedgerNo,'text').", ".GetSQLValueString($vCheckNo,'text').", ".
				 "          ".GetSQLValueString($vBank,'text').", ".GetSQLValueString(insertMySQLDate($vChkJourValueDate),'date').", ".GetSQLValueString($vChkJourType,'text').", ".GetSQLValueString($vChkJourCurrCode,'text').", ".
				 "          ".GetSQLValueString($vChkJourAmt,'double').", ".GetSQLValueString($vChkJourAmt1,'double').", ".GetSQLValueString($vChkJourAmt2,'double').") ";

		//echo $query."<br>";exit;				
		$result=mysql_query($query,$connection);
			
		if ($result){
			fcommit();
		} else{
			$message  .= mysql_error($connection); 
			frollback();
		}	
	} else {
		$message  .= 'Insert not allowed. Check No. already exists.'; 
	}

} 

//Edit ChkJoutDt Table
else if ($mode == "editchkjour" && $SChkJourId != ""){

	$vChkJourId   = '';
	$vCheckNo     = '';
	$vBank        = '';
	$vChkJourValueDate = '';
	$vChkJourCurrCode  = '';
	$vChkJourLedgerNo  = '';
	$vChkJourType   = '';
	$vChkJourAmt    = 0;
	$vChkJourAmt1   = 0;
	$vChkJourAmt2   = 0;
	
	
	if (empty($txtChkJourAmount))		$txtChkJourAmount = 0;
	if (empty($txtChkJourAmount1))		$txtChkJourAmount1 = 0;
	if (empty($txtChkJourAmount2))		$txtChkJourAmount2 = 0;
			
			

	$vCheckNo    	   = $txtChkJourNumber;
	$vBank       	   = $txtChkJourBank;
	$vChkJourValueDate = $txtChkJourValueDate;
	$vChkJourCurrCode  = $txtChkJourCurrCode;
	$vChkJourLedgerNo  = $txtChkJourLedgerNo;
	$vChkJourType      = $txtChkJourType;
	$vChkJourAmt       = $txtChkJourAmount;
	$vChkJourAmt1      = $txtChkJourAmount1;
	$vChkJourAmt2      = $txtChkJourAmount2;	
			

	fbegin();
	$query = " UPDATE temp_chkjour SET ".
			 " Chk_bank = ".GetSQLValueString($vBank,'text').", Chk_ValueDate = ".GetSQLValueString(insertMySQLDate($vChkJourValueDate),'date').", ". 
			 " Chk_Amount = ".GetSQLValueString($vChkJourAmt,'double').", Chk_Amount1 = ".GetSQLValueString($vChkJourAmt1,'double').", Chk_Amount2 = ".GetSQLValueString($vChkJourAmt2,'double').
			 " WHERE Chk_Increment = '".$SChkJourId."'";

	//echo $query."<br>";exit;				
	$result=mysql_query($query,$connection);
		
	if ($result){
		
		fcommit();
	} else{
		$message  = mysql_error($connection); 
		frollback();
	}

	
} 
//Delete ChkJour
else if ($mode == "deletechkjour" && $SChkJourId != ""){

	$AllowDelete = 1;
	$ErrorExists = 0;
	$message  = '';
	
	
		
	//If No Constraints Exists On Delete
	if ($AllowDelete == 1) {

		
		fbegin();
		
		// Delete From TempChkJour For Selected Record
		$query = " DELETE FROM Temp_ChkJour ".
				 " WHERE Chk_Increment = '".$SChkJourId."'";
					 
		if (!updateData($connection, $query, true)) {
			$message  = mysql_error($connection);
			$ErrorExists = 1;
			frollback();
		}  
		else {
			fcommit();
		}
			
	
	} // End If No Constraints Found On Delete
	
	
}


// Insert BillJourDt
else if ($mode == "insertbilljour" && $SJourId != "" && $SJourDtId != ""){
	
	$vBillJourId  = '';
	$vBillNo      = '';
	$vBank        = '';
	$vBillJourValueDate  = '';
	$vBillJourCurrCode   = '';
	$vBillJourLedgerCode = '';
	$vBillJourType   = '';
	$vBillJourAmt    = 0;
	$vBillJourAmt1   = 0;
	$vBillJourAmt2   = 0;
	
	$vBillExists = 0;
	
	if (empty($txtBillJourAmount))		$txtBillJourAmount = 0;
	if (empty($txtBillJourAmount1))		$txtBillJourAmount1 = 0;
	if (empty($txtBillJourAmount2))		$txtBillJourAmount2 = 0;
			
			

	$vBillNo    	     = $txtBillJourNumber;
	$vBank       	     = $txtBillJourBank;
	$vBillJourValueDate  = $txtBillJourValueDate;
	$vBillJourCurrCode   = $txtBillJourCurrCode;
	$vBillJourLedgerCode = $txtBillJourLedgerCode;
	$vBillJourType       = $txtBillJourType;
	$vBillJourAmt        = $txtBillJourAmount;
	$vBillJourAmt1       = $txtBillJourAmount1;
	$vBillJourAmt2       = $txtBillJourAmount2;	
		
	
	if ($vBillJourType == 'A') {
		$sub_query=" select count(*) from bills ".
				   " where Ledger_Number = '".$vBillJourLedgerCode."' ". 
				   " and bill_number = '".$vBillNo."' ";
				   
		//echo $sub_query;exit;
		$sub_result = selectData($connection, $sub_query);
		$vBillExists = $sub_result[0];
	}
	
	if ($vBillJourType == 'A' && $vBillExists == 0) {
		$sub_query= " select count(*) from temp_billjour ".
		            " where Ledger_Number = '".$vBillJourLedgerCode."' ". 
					" and bill_number = '".$vBillNo."'";
					
		//echo $sub_query;exit;
		$sub_result = selectData($connection, $sub_query);
		$vBillExists = $sub_result[0];
	}
	
	
				 
	if ($vBillExists == 0) {
		//fbegin();
		//$vBillJourId = GetNextSequence($connection,'Null','Null','ID','BILLJOUR','JV','Null',date('Y-m-d H:i:s'),0,0);
		//fcommit();
		
		fbegin();
		$query = " INSERT INTO temp_billjour (JournalDt_Id, Ledger_Number, Bill_Number, Bill_Bank, Bill_ValueDate, Bill_Type, Currency_Code, Bill_Amount, Bill_Amount1, Bill_Amount2 ) ". 
				 " VALUES ( ".GetSQLValueString($SJourDtId,'double').", ".GetSQLValueString($vBillJourLedgerCode,'text').", ".GetSQLValueString($vBillNo,'text').", ".
				 "          ".GetSQLValueString($vBank,'text').", ".GetSQLValueString(insertMySQLDate($vBillJourValueDate),'date').", ".GetSQLValueString($vBillJourType,'text').", ".GetSQLValueString($vBillJourCurrCode,'text').", ".
				 "          ".GetSQLValueString($vBillJourAmt,'double').", ".GetSQLValueString($vBillJourAmt1,'double').", ".GetSQLValueString($vBillJourAmt2,'double').") ";

		//echo $query."<br>";exit;				
		$result=mysql_query($query,$connection);
			
		if ($result){
			fcommit();
		} else{
			$message  .= mysql_error($connection); 
			frollback();
		}	
	} else {
		$message  .= 'Insert not allowed. Bill No. already exists.'; 
	}

} 

//Edit BillJoutDt Table
else if ($mode == "editbilljour" && $SBillJourId != ""){

	$vBillJourId  = '';
	$vBillNo      = '';
	$vBank        = '';
	$vBillJourValueDate   = '';
	$vBillJourCurrCode    = '';
	$vBillJourLedgerCode  = '';
	$vBillJourType   = '';
	$vBillJourAmt    = 0;
	$vBillJourAmt1   = 0;
	$vBillJourAmt2   = 0;
	
	$vBillExists = 0;
	
	if (empty($txtBillJourAmount))		$txtBillJourAmount = 0;
	if (empty($txtBillJourAmount1))		$txtBillJourAmount1 = 0;
	if (empty($txtBillJourAmount2))		$txtBillJourAmount2 = 0;
			
			

	$vBillNo    	     = $txtBillJourNumber;
	$vBank       	     = $txtBillJourBank;
	$vBillJourValueDate  = $txtBillJourValueDate;
	$vBillJourCurrCode   = $txtBillJourCurrCode;
	$vBillJourLedgerCode = $txtBillJourLedgerCode;
	$vBillJourType       = $txtBillJourType;
	$vBillJourAmt        = $txtBillJourAmount;
	$vBillJourAmt1       = $txtBillJourAmount1;
	$vBillJourAmt2       = $txtBillJourAmount2;	
			
			
	fbegin();
	$query = " UPDATE temp_billjour SET ".
			 " Bill_bank = ".GetSQLValueString($vBank,'text').", Bill_ValueDate = ".GetSQLValueString(insertMySQLDate($vBillJourValueDate),'date').", ". 
			 " Bill_Amount = ".GetSQLValueString($vBillJourAmt,'double').", Bill_Amount1 = ".GetSQLValueString($vBillJourAmt1,'double').", Bill_Amount2 = ".GetSQLValueString($vBillJourAmt2,'double').
			 " WHERE Bill_Increment = '".$SBillJourId."'";

	//echo $query."<br>";exit;				
	$result=mysql_query($query,$connection);
		
	if ($result){
		
		fcommit();
	} else{
		$message  = mysql_error($connection); 
		frollback();
	}

	
} 
//Delete BillJourDt
else if ($mode == "deletebilljour" && $SBillJourId != ""){

	$AllowDelete = 1;
	$ErrorExists = 0;
	$message  = '';
	
	
		
	//If No Constraints Exists On Delete
	if ($AllowDelete == 1) {

		
		fbegin();
		
		// Delete From TempBillJour For Selected Record
		$query = " DELETE FROM Temp_BillJour ".
				 " WHERE Bill_Increment = '".$SBillJourId."'";
					 
		if (!updateData($connection, $query, true)) {
			$message  = mysql_error($connection);
			$ErrorExists = 1;
			frollback();
		}  
		else {
			fcommit();
		}
			
	
	} // End If No Constraints Found On Delete
	
	
}

//Delete Record Mode From Main Tables
else if ($mode == "" && $mainmode == "delete" && $SJourId != ''){

	$AllowDelete = 1;
	$message  = '';
	
	//Check User Access For Date Modification/ Lock Period
	$MainCompanyName=explode('_',$_SESSION['dbName']);
	
	 $sub_query= " Select ifNull(AllowLockedPeriod,0) As AllowLockedPeriod, LockedPeriod As LockedPeriodDate, LockedPeriodDays As LockedPeriodDays ".
				" From ".$_SESSION['dbLabel'].".ListUserDir  ".
				" Where Usercode='".$_SESSION['useraccount']."' ".
				" And Upper(CompanyName) = Upper('".$MainCompanyName[0]."') ".
				" And Upper(Diryear) = Upper('".$MainCompanyName[1]."') ";
				  
	$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
	$rowsperiod = mysql_num_rows($sub_result);

	while($sub_rows=mysql_fetch_array($sub_result)){
		extract($sub_rows);
	}	
	if ($rowsperiod > 0 && $AllowLockedPeriod == 1) {
		$query = "SELECT date_format(Journal_Date,'%d/%m/%Y') FROM Journal WHERE Journal_id = ".$SJourId;
		$result = selectData($connection, $query);
		$txtDate  = $result[0];
 
		if (!(empty($LockedPeriodDate)) && $LockedPeriodDate != '' && date('Y-m-d',strtotime(insertMySQLDate($txtDate))) <= date('Y-m-d',strtotime($LockedPeriodDate))) $AllowDelete =0;
		if ($LockedPeriodDays != '' && dateDiff(insertMySQLDate(displayToday()),insertMySQLDate($txtDate)) > $LockedPeriodDays) $AllowDelete = 0;
		if($AllowDelete==0) $message  = 'Delete not allowed, Exceed Lock Period.';
	}
	
	
	 
	
	//Check If Journal Is Posted
	$query = "SELECT ifNull(Journal_Posted,0) As JournalPosted FROM Journal WHERE Journal_Id = '".$SJourId."'";
	$result = selectData($connection, $query);
	$JournalPosted = $result[0];
	
	if ($JournalPosted == 1 ){
		$message  = 'Delete not allowed, Transaction posted.';
		$AllowDelete = 0;
	}
	
	if ($AllowDelete == 1) {
		//Check Each JournalDt If Has Related Checks Used
		$query = " Select Count(*) ".
				 " From Checks Inner Join JournalDt on Checks.Journaldt_Id1 = JournalDt.JournalDt_Id ".
				 " Inner Join ChkJour on Checks.Chk_Number = ChkJour.Chk_Number and Checks.Ledger_Number = ChkJour.Ledger_Number  ".
				 " Where JournalDt.Journal_Id = '".$SJourId."' ".
				 " And ChkJour.JournalDt_Id In (Select JournalDt_Id From JournalDt where Journal_Id = '".$SJourId."') ".
				 " And (ifNull(Checks.Journaldt_id2,0) != 0 and Checks.Journaldt_id2 != '' and Checks.Journaldt_id2 Is Not Null) ";

		$result = selectData($connection, $query);
		$ChecksExists = $result[0];
			
		if ($ChecksExists > 0 ){
			$message  = 'Delete not allowed. Checks Collected / Paid.';
			$AllowDelete = 0;
		}
	}	
	
	if ($AllowDelete == 1) {
		//Check Each JournalDt If Has Related Checks Used
		$query = " Select Count(*) ".
				 " From Bills Inner Join JournalDt on Bills.Journaldt_Id1 = JournalDt.JournalDt_Id ".
				 " Inner Join BillJour on Bills.Bill_Number = BillJourDt.Bill_Number and Bills.Ledger_Number = BillJourDt.Ledger_Number  ".
				 " Where JournalDt.Journal_Id = '".$SJourId."' ".
				 " And BillJour.JournalDt_Id In (Select JournalDt_Id From JournalDt where Journal_Id = '".$SJourId."') ".
				 " And (ifNull(Bills.Journaldt_id2,0) != 0 and Bills.Journaldt_id2 != '' and Bills.Journaldt_id2 Is Not Null) ";

		$result = selectData($connection, $query);
		$BillsExists = $result[0];
			
		if ($BillsExists > 0 ){
			$message  = 'Delete not allowed. Bills Collected / Paid.';
			$AllowDelete = 0;
		}
	}
	
	
	//If No Constraints Exists On Delete
	if ($AllowDelete == 1) {
		
		// Manage Checks Before Delete
		$sub_query1 = " Select Chk_Increment, Chk_Number, Chk_Type, Ledger_Number ".
					  " From ChkJour ".
					  " WHERE Chkjour.JournalDt_Id In (Select JournalDt_Id From JournalDt Where Journal_Id = '".$SJourId."') ";
							  
		$sub_result1=mysql_query($sub_query1,$connection);
		while($sub_row1=mysql_fetch_row($sub_result1)){	
			$sub_query2  = " Select Count(*), ifNull(journaldt_id2,0) From Checks Where Chk_Number = '".$sub_row1[1]."' And Ledger_Number = '".$sub_row1[3]."' Group By journaldt_id2 ";
			$sub_result2 = selectData($connection, $sub_query2);
			$vChkCount     = $sub_result2[0];
			$vJournalDtId2  = $sub_result2[1];
					
			if (empty($vChkCount)) $vChkCount = 0;
			//$vChkCount = 0;
					
			if ($vChkCount > 0) {
				$message= "tessttt jhhjjhkhkhk kjhkjh kjh kh k<br>";
				if ($sub_row1[2] == 'C') {
					$sub_query3  = " UPDATE checks set journaldt_id2 = 'test' Where Chk_Number = '".$sub_row1[1]."' And Ledger_Number = '".$sub_row1[3]."' ";
				} else if ($vJournalDtId2 == 0) {
					$sub_query3  = " DELETE From Checks Where Chk_Number = '".$sub_row1[1]."' And Ledger_Number = '".$sub_row1[3]."' ";
				}
						
				if (!updateData($connection, $sub_query3, true))		 
					$message  = mysql_error($connection);
					
			}
		
		}
				
				
		// Manage Bills Before Delete
		$sub_query1 = " Select Bill_Increment, Bill_Number, Bill_Type, Ledger_Number ".
					  " From BillJour ".
					  " WHERE Billjour.JournalDt_Id In (Select JournalDt_Id From JournalDt Where Journal_Id = '".$SJourId."') ";
							  
		$sub_result1=mysql_query($sub_query1,$connection);
		while($sub_row1=mysql_fetch_row($sub_result1)){	
			$sub_query2  = " Select Count(*), ifNull(journaldt_id2,0) From Bills Where Bill_Number = '".$sub_row1[1]."' And Ledger_Number = '".$sub_row1[3]."' Group By journaldt_id2 ";
			$sub_result2 = selectData($connection, $sub_query2);
			$vBillCount     = $sub_result2[0];
			$vJournalDtId2  = $sub_result2[1];
					
			if (empty($vBillCount)) $vBillCount = 0;
					
			if ($vBillCount > 0) {
				if ($sub_row1[2] == 'C') {
					$sub_query3  = " UPDATE Bills set journaldt_id2 = Null Where Bill_Number = '".$sub_row1[1]."' And Ledger_Number = '".$sub_row1[3]."' ";
				} else if ($vJournalDtId2 == 0) {
					$sub_query3  = " DELETE From Bills Where Bill_Number = '".$sub_row1[1]."' And Ledger_Number = '".$sub_row1[3]."' ";
				}
						
				if (!updateData($connection, $sub_query3, true))		 
					$message  = mysql_error($connection);
					
			}
				
		}
		if($config['log_file'] == 1){
			$company = explode("_", $_SESSION['dbName']);
			$currCompany = strtoupper($company[0]);
						$transType = "D";
						$query_insertToHistory  = "call ".$config['dbName_history'].".InsertToHistory('$transType', '$SJourId', '".$_SESSION['useraccount']."', now(), '".$_SESSION['dbName']."', 'journal', '$currCompany')";
					//echo $query_insertToHistory;exit;
					$result_insertToHistory = mysql_query($query_insertToHistory, $connection);
						}		
	    // Delete From CstJour For Selected Record
		$query = " DELETE FROM CstJour ".
				 " WHERE CstJour.JournalDt_Id In (Select JournalDt_Id From JournalDt Where Journal_Id = '".$SJourId."') ";
		if (!updateData($connection, $query, true))
			$message  = mysql_error($connection);
				
				 
		// Delete From Chkjour For Selected Record
		$query = " DELETE FROM Chkjour ".
				 " WHERE Chkjour.JournalDt_Id In (Select JournalDt_Id From JournalDt Where Journal_Id = '".$SJourId."') ";
				 
		if (!updateData($connection, $query, true))		 
			$message  = mysql_error($connection); 	
			
		// Delete From Billjour For Selected Record
		$query = " DELETE FROM Billjour ".
				 " WHERE Billjour.JournalDt_Id In (Select JournalDt_Id From JournalDt Where Journal_Id = '".$SJourId."') ";
				 
		if (!updateData($connection, $query, true))		 
			$message  = mysql_error($connection); 	

				
		// Delete From JournalDt For Selected Record
		$query = " DELETE FROM JournalDt WHERE Journal_Id = ".$SJourId;
					 
		if (updateData($connection, $query, true)) {
			// Delete From Journal For Selected Record
			$query = " DELETE FROM Journal WHERE Journal_Id = ".$SJourId;
				
			if (!updateData($connection, $query, true))		 
				$message  = mysql_error($connection); 
				
		}
		else
			$message  = mysql_error($connection); 	
		
	}
	
	
}

//Delete Record Mode From Temp Tables
else if (($mode == "cancel" || $mainmode == "deletepending") && $SJourId != ''){

	// Delete From Temp_CstJour For Selected Record
	$query = " DELETE FROM Temp_CstJour ".
			 " WHERE Temp_CstJour.JournalDt_Id In (Select JournalDt_Id From Temp_JournalDt Where Journal_Id = '".$SJourId."') ";
	if (!updateData($connection, $query, true))
		$message  = mysql_error($connection);
		
	// Delete From Temp_Chkjour For Selected Record
	$query = " DELETE FROM Temp_Chkjour ".
			 " WHERE Temp_Chkjour.JournalDt_Id In (Select JournalDt_Id From Temp_JournalDt Where Journal_Id = '".$SJourId."') ";
				 
	if (!updateData($connection, $query, true))		 
		$message  = mysql_error($connection); 	
			
	// Delete From Temp_Billjour For Selected Record
	$query = " DELETE FROM Temp_Billjour ".
			 " WHERE Temp_Billjour.JournalDt_Id In (Select JournalDt_Id From Temp_JournalDt Where Journal_Id = '".$SJourId."') ";
				 
	if (!updateData($connection, $query, true))		 
		$message  = mysql_error($connection); 	

				
	// Delete From Temp_JournalDt For Selected Record
	$query = " DELETE FROM Temp_JournalDt WHERE Journal_Id = ".$SJourId;
			 
	if (updateData($connection, $query, true)) {
		// Delete From Temp_Journal For Selected Record
		$query = " DELETE FROM Temp_Journal WHERE Journal_Id = ".$SJourId;
				 
		if (!updateData($connection, $query, true))		 
			$message  = mysql_error($connection); 
	}
	else
		$message  = mysql_error($connection); 	
	

}

		
//Search Mode	
else if( ($mainmode == "search" || ($mainmode == "search2" && $InTempJour == -1) )  && $SJourId != ''){

	$ErrorExists = 0;
	//Copy Data From Main Tables To Temp Tables
	$query = " INSERT INTO temp_journal (Journal_ID, Journal_RefGovernment, Journal_Date, Journal_SysDate, Journal_Folio, Journal_Type, Journal_TypeRef, ".
	         " Journal_Remark, Manual_No, Amnt1_db, Amnt2_db, Amnt1_cd, Amnt2_cd, Journal_Posted, Journal_Flag, Journal_Edit, Journal_dtincr, ".
			 " Journal_BelongsToGroup, Journal_Confirmed, Journal_ConfirmedUser, Project_code, Costcent_Code, User_Account, Logged_Code ) ".
			 " SELECT Journal_ID, Journal_RefGovernment, Journal_Date, Journal_SysDate, Journal_Folio, Journal_Type, Journal_TypeRef, ".
	         " Journal_Remark, Manual_No, Amnt1_db, Amnt2_db, Amnt1_cd, Amnt2_cd, Journal_Posted, Journal_Flag, Journal_Edit, Journal_dtincr, ".
			 " Journal_BelongsToGroup, Journal_Confirmed, Journal_ConfirmedUser, Project_code, Costcent_Code, User_Account, '".$_SESSION['useraccount']."' ".
			 " FROM Journal ".
			 " WHERE Journal_ID = '".$SJourId."'";
	
	if (!updateData($connection, $query, true)) {
		$ErrorExists = 1;
		$message  = mysql_error($connection); 	
	}  

		
	if ($ErrorExists == 0) {
		//echo $message.$query; exit;				 
		$query = " INSERT INTO temp_journaldt (JournalDt_Id, Journal_Id, Ledger_Number, Currency_Code, Journaldt_desc, Journaldt_desc1, Journaldt_dbcd, Journaldt_dbcdAra, Journaldt_amount, Journaldt_amount1, ". 
				 " Journaldt_amount2, Journal_Date, Journaldt_ValueDate, Journaldt_posted, manual_no, Logged_Code, journaldt_rate,journaldt_rate2, journal_belongsToGroup, journaldt_distributeCode )  ".
				 " SELECT JournalDt_Id, Journal_Id, Ledger_Number, Currency_Code, Journaldt_desc, Journaldt_desc1, Journaldt_dbcd, Journaldt_dbcdAra, Journaldt_amount, Journaldt_amount1, ". 
				 " Journaldt_amount2, Journal_Date, Journaldt_ValueDate, Journaldt_posted, manual_no, '".$_SESSION['useraccount']."',journaldt_rate,journaldt_rate2 , journal_belongsToGroup, journaldt_distributeCode ".
				 " FROM JournalDt ".
				 " WHERE Journal_ID = '".$SJourId."'";
		
		if (!updateData($connection, $query, true))
		  $message  = mysql_error($connection); 			


		  
		  
		$query = " INSERT INTO temp_cstjour (JournalDt_Id, Project_Code, Costcent_code, Cstjour_prcnt, Cstjour_amount, Cstjour_amount1, Cstjour_amount2, user_account ) ".
				 " SELECT JournalDt_Id, Project_Code, Costcent_code, Cstjour_prcnt, Cstjour_amount, Cstjour_amount1, Cstjour_amount2, user_account ".
				 " FROM CstJour ".
				 " WHERE CstJour.JournalDt_Id  In (Select JournalDt_Id From Temp_JournalDt Where Journal_Id = '".$SJourId."') ";
					 
		if (!updateData($connection, $query, true))
			$message  = mysql_error($connection);  
		  
		$query = " INSERT INTO temp_chkjour (JournalDt_Id, Ledger_Number, Chk_Number, Chk_Bank, Chk_ValueDate, Chk_Type, Currency_Code, Chk_Amount, Chk_Amount1, Chk_Amount2 ) ".
				 " SELECT JournalDt_Id, Ledger_Number, Chk_Number, Chk_Bank, Chk_ValueDate, Chk_Type, Currency_Code, Chk_Amount, Chk_Amount1, Chk_Amount2 ".
				 " FROM ChkJour ".
				 " WHERE Chkjour.JournalDt_Id In (Select JournalDt_Id From Temp_JournalDt Where Journal_Id = '".$SJourId."') ";
				 
		if (!updateData($connection, $query, true))
		  $message  = mysql_error($connection); 

		  
		$query = " INSERT INTO temp_billjour (JournalDt_Id, Ledger_Number, Bill_Number, Bill_Bank, Bill_ValueDate, Bill_type, Currency_Code, Bill_Amount, Bill_Amount1, Bill_Amount2 ) ".
				 " SELECT JournalDt_Id, Ledger_Number, Bill_Number, Bill_Bank, Bill_ValueDate, Bill_type, Currency_Code, Bill_Amount, Bill_Amount1, Bill_Amount2 ".
				 " FROM BillJour ".
				 " WHERE Billjour.JournalDt_Id In (Select JournalDt_Id From Temp_JournalDt Where Journal_Id = '".$SJourId."') ";
				 
		if (!updateData($connection, $query, true))
		  $message  = mysql_error($connection);    

	    
	}
}		
//Search Mode	
else if($mainmode == "EditJournalFromReport" && $SJourId != ''){

	$ErrorExists = 0;
	//Copy Data From Main Tables To Temp Tables
	$query = " INSERT INTO temp_journal (Journal_ID, Journal_RefGovernment, Journal_Date, Journal_SysDate, Journal_Folio, Journal_Type, Journal_TypeRef, ".
	         " Journal_Remark, Manual_No, Amnt1_db, Amnt2_db, Amnt1_cd, Amnt2_cd, Journal_Posted, Journal_Flag, Journal_Edit, Journal_dtincr, ".
			 " Journal_BelongsToGroup, Journal_Confirmed, Journal_ConfirmedUser, Project_code, Costcent_Code, User_Account, Logged_Code ) ".
			 " SELECT Journal_ID, Journal_RefGovernment, Journal_Date, Journal_SysDate, Journal_Folio, Journal_Type, Journal_TypeRef, ".
	         " Journal_Remark, Manual_No, Amnt1_db, Amnt2_db, Amnt1_cd, Amnt2_cd, Journal_Posted, Journal_Flag, Journal_Edit, Journal_dtincr, ".
			 " Journal_BelongsToGroup, Journal_Confirmed, Journal_ConfirmedUser, Project_code, Costcent_Code, User_Account, '".$_SESSION['useraccount']."' ".
			 " FROM Journal ".
			 " WHERE Journal_ID = '".$SJourId."'";
	
	if (!updateData($connection, $query, true)) {
		$ErrorExists = 1;
		$message  = mysql_error($connection); 	
	}  

		
	if ($ErrorExists == 0) {
		//echo $message.$query; exit;				 
		$query = " INSERT INTO temp_journaldt (JournalDt_Id, Journal_Id, Ledger_Number, Currency_Code, Journaldt_desc, Journaldt_desc1, Journaldt_dbcd, Journaldt_dbcdAra, ". 
				 " Journaldt_amount, Journaldt_amount1, Journaldt_amount2, Journal_Date, Journaldt_ValueDate, Journaldt_posted, manual_no, Logged_Code,journaldt_rate )  ".
				 " SELECT JournalDt_Id, Journal_Id, Ledger_Number, Currency_Code, Journaldt_desc, Journaldt_desc1, Journaldt_dbcd, Journaldt_dbcdAra, ". 
				 " Journaldt_amount, Journaldt_amount1, Journaldt_amount2, Journal_Date, Journaldt_ValueDate, Journaldt_posted, manual_no, '".$_SESSION['useraccount']."',journaldt_rate  ".
				 " FROM JournalDt ".
				 " WHERE Journal_ID = '".$SJourId."'";
		
		if (!updateData($connection, $query, true))
		  $message  = mysql_error($connection); 			


		  
		  
		$query = " INSERT INTO temp_cstjour (JournalDt_Id, Project_Code, Costcent_code, Cstjour_prcnt, Cstjour_amount, Cstjour_amount1, Cstjour_amount2, user_account ) ".
				 " SELECT JournalDt_Id, Project_Code, Costcent_code, Cstjour_prcnt, Cstjour_amount, Cstjour_amount1, Cstjour_amount2, user_account ".
				 " FROM CstJour ".
				 " WHERE CstJour.JournalDt_Id  In (Select JournalDt_Id From Temp_JournalDt Where Journal_Id = '".$SJourId."') ";
					 
		if (!updateData($connection, $query, true))
			$message  = mysql_error($connection);  
		  
		$query = " INSERT INTO temp_chkjour (JournalDt_Id, Ledger_Number, Chk_Number, Chk_Bank, Chk_ValueDate, Chk_Type, Currency_Code, Chk_Amount, Chk_Amount1, Chk_Amount2 ) ".
				 " SELECT JournalDt_Id, Ledger_Number, Chk_Number, Chk_Bank, Chk_ValueDate, Chk_Type, Currency_Code, Chk_Amount, Chk_Amount1, Chk_Amount2 ".
				 " FROM ChkJour ".
				 " WHERE Chkjour.JournalDt_Id In (Select JournalDt_Id From Temp_JournalDt Where Journal_Id = '".$SJourId."') ";
				 
		if (!updateData($connection, $query, true))
		  $message  = mysql_error($connection); 

		  
		$query = " INSERT INTO temp_billjour (JournalDt_Id, Ledger_Number, Bill_Number, Bill_Bank, Bill_ValueDate, Bill_type, Currency_Code, Bill_Amount, Bill_Amount1, Bill_Amount2 ) ".
				 " SELECT JournalDt_Id, Ledger_Number, Bill_Number, Bill_Bank, Bill_ValueDate, Bill_type, Currency_Code, Bill_Amount, Bill_Amount1, Bill_Amount2 ".
				 " FROM BillJour ".
				 " WHERE Billjour.JournalDt_Id In (Select JournalDt_Id From Temp_JournalDt Where Journal_Id = '".$SJourId."') ";
				 
		if (!updateData($connection, $query, true))
		  $message  = mysql_error($connection);    

	    
	}
header ("Location: ./Form_Journal.php?actionmode=&mainaction=edit&txtJourId=".$SJourId."&message=".$message);
exit;	
}

else  if($mainmode == "loadfromstatmentproject" && $SJourId != ''){
	$ErrorExists = 0;
	//Copy Data From Main Tables To Temp Tables
	$query = " INSERT INTO $schemaname.temp_journal (Journal_ID, Journal_RefGovernment, Journal_Date, Journal_SysDate, Journal_Folio, Journal_Type, Journal_TypeRef, ".
	         " Journal_Remark, Manual_No, Amnt1_db, Amnt2_db, Amnt1_cd, Amnt2_cd, Journal_Posted, Journal_Flag, Journal_Edit, Journal_dtincr, ".
			 " Journal_BelongsToGroup, Journal_Confirmed, Journal_ConfirmedUser, Project_code, Costcent_Code, User_Account, Logged_Code ) ".
			 " SELECT Journal_ID, Journal_RefGovernment, Journal_Date, Journal_SysDate, Journal_Folio, Journal_Type, Journal_TypeRef, ".
	         " Journal_Remark, Manual_No, Amnt1_db, Amnt2_db, Amnt1_cd, Amnt2_cd, Journal_Posted, Journal_Flag, Journal_Edit, Journal_dtincr, ".
			 " Journal_BelongsToGroup, Journal_Confirmed, Journal_ConfirmedUser, Project_code, Costcent_Code, User_Account, '".$_SESSION['useraccount']."' ".
			 " FROM $schemaname.Journal ".
			 " WHERE Journal_ID = '".$SJourId."'";
	
	if (!updateData($connection, $query, true)) {
		$ErrorExists = 1;
		$message  = mysql_error($connection); 	
	}  

		
	if ($ErrorExists == 0) {
		//echo $message.$query; exit;				 
		$query = " INSERT INTO $schemaname.temp_journaldt (JournalDt_Id, Journal_Id, Ledger_Number, Currency_Code, Journaldt_desc, Journaldt_desc1, Journaldt_dbcd, Journaldt_dbcdAra, ". 
				 " Journaldt_amount, Journaldt_amount1, Journaldt_amount2, Journal_Date, Journaldt_ValueDate, Journaldt_posted, manual_no, Logged_Code, journaldt_rate,journaldt_rate2 )  ".
				 " SELECT JournalDt_Id, Journal_Id, Ledger_Number, Currency_Code, Journaldt_desc, Journaldt_desc1, Journaldt_dbcd, Journaldt_dbcdAra, ". 
				 " Journaldt_amount, Journaldt_amount1, Journaldt_amount2, Journal_Date, Journaldt_ValueDate, Journaldt_posted, manual_no, '".$_SESSION['useraccount']."',journaldt_rate,journaldt_rate2  ".
				 " FROM $schemaname.JournalDt ".
				 " WHERE Journal_ID = '".$SJourId."'";
		
		if (!updateData($connection, $query, true))
		  $message  = mysql_error($connection); 			


		  
		  
		$query = " INSERT INTO $schemaname.temp_cstjour (JournalDt_Id, Project_Code, Costcent_code, Cstjour_prcnt, Cstjour_amount, Cstjour_amount1, Cstjour_amount2, user_account ) ".
				 " SELECT JournalDt_Id, Project_Code, Costcent_code, Cstjour_prcnt, Cstjour_amount, Cstjour_amount1, Cstjour_amount2, user_account ".
				 " FROM $schemaname.CstJour as CstJour".
				 " WHERE CstJour.JournalDt_Id  In (Select JournalDt_Id From Temp_JournalDt Where Journal_Id = '".$SJourId."') ";
					 
		if (!updateData($connection, $query, true))
			$message  = mysql_error($connection);  
		  
		$query = " INSERT INTO $schemaname.temp_chkjour (JournalDt_Id, Ledger_Number, Chk_Number, Chk_Bank, Chk_ValueDate, Chk_Type, Currency_Code, Chk_Amount, Chk_Amount1, Chk_Amount2 ) ".
				 " SELECT JournalDt_Id, Ledger_Number, Chk_Number, Chk_Bank, Chk_ValueDate, Chk_Type, Currency_Code, Chk_Amount, Chk_Amount1, Chk_Amount2 ".
				 " FROM $schemaname.ChkJour as ChkJour ".
				 " WHERE $schemaname.Chkjour.JournalDt_Id In (Select JournalDt_Id From Temp_JournalDt Where Journal_Id = '".$SJourId."') ";
				 
		if (!updateData($connection, $query, true))
		  $message  = mysql_error($connection); 

		  
		$query = " INSERT INTO $schemaname.temp_billjour (JournalDt_Id, Ledger_Number, Bill_Number, Bill_Bank, Bill_ValueDate, Bill_type, Currency_Code, Bill_Amount, Bill_Amount1, Bill_Amount2 ) ".
				 " SELECT JournalDt_Id, Ledger_Number, Bill_Number, Bill_Bank, Bill_ValueDate, Bill_type, Currency_Code, Bill_Amount, Bill_Amount1, Bill_Amount2 ".
				 " FROM $schemaname.BillJour as BillJour ".
				 " WHERE Billjour.JournalDt_Id In (Select JournalDt_Id From Temp_JournalDt Where Journal_Id = '".$SJourId."') ";
				 
		if (!updateData($connection, $query, true))
		  $message  = mysql_error($connection);    

	    
	}
	
}
//Post Transactions
else if($mainmode == "posttrx"){

	$vSelectedRows = $_POST['SelectedRows']; 
	$query = " select journal_id from ( select journal_id from journal where journal_id in (".$vSelectedRows.") ".
			 " ) as Q where Q.journal_id not in (select journal_id from temp_journal )";
	$res = mysql_query($query,$connection);
	while ($rw = mysql_fetch_row($res)){
		$sub_query = " Update  Journal Set Journal_Confirmed = 1 ,Journal_ConfirmedUser = '".$_SESSION['useraccount']."' ".
					 " Where Journal.Journal_ID = $rw[0] ";
				        
		//echo $sub_query; exit;
		$sub_result=mysql_query($sub_query,$connection);
	}
	 
	header ("Location: ./Form_JournalSearchUnPosted.php?message=".$message."&alljv=n");
}
else if($mainmode == "copyjv" && $SJourId != ''){

	$ErrorExists = 0;
	
	fbegin();	
	$vJournalId = get_nextsequence('journal_id','',$connection);	
	fcommit();
	
	//fbegin();
	$query = " INSERT INTO temp_journal (Journal_ID, Journal_RefGovernment, Journal_Date, Journal_SysDate, Journal_Folio, Journal_Type, Journal_TypeRef, ".
	         " Journal_Remark, Manual_No, Amnt1_db, Amnt2_db, Amnt1_cd, Amnt2_cd, Journal_Posted, Journal_Flag, Journal_Edit, Journal_dtincr, ".
			 " Journal_BelongsToGroup, Journal_Confirmed, Journal_ConfirmedUser, Project_code, Costcent_Code, User_Account, Logged_Code ) ".
			 " SELECT ".GetSQLValueString($vJournalId,'double').", Null, ".GetSQLValueString(insertMySQLDate($PJourDate),'date').", Now(), Null, 'JV', Null, ".
	         " Journal_Remark, Manual_No, Amnt1_db, Amnt2_db, Amnt1_cd, Amnt2_cd, 0, Journal_Flag, 0, 1, ".
			 " Journal_BelongsToGroup, 0, Null, Project_code, Costcent_Code, '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."' ".
			 " FROM Journal ".
			 " WHERE Journal_ID = '".$SJourId."'";
	
	$result=mysql_query($query,$connection);
	if (!($result)){
		$ErrorExists = 1;
		$message  = mysql_error($connection); 	
	}  

		
	if ($ErrorExists == 0) {
		//echo $message.$query; exit;		

		$query = " SELECT JournalDt_Id, Journal_Id, Ledger_Number, Currency_Code, Journaldt_desc, Journaldt_desc1, Journaldt_dbcd, Journaldt_dbcdAra, ". 
				 " Journaldt_amount, Journaldt_amount1, Journaldt_amount2, Journal_Date, Journaldt_ValueDate, Journaldt_posted, manual_no, journaldt_rate  ".
				 " FROM JournalDt ".
				 " WHERE Journal_ID = '".$SJourId."'";
				 
		$result=mysql_query($query,$connection);
		while($rows=mysql_fetch_array($result)){			  
		
			$query_dtincr="select Journal_dtincr from temp_journal where journal_id=".$vJournalId;
			$result_dtincr=mysql_query($query_dtincr,$connection);
			$row_dtincr=mysql_fetch_row($result_dtincr);
				
			$dtincr = $row_dtincr[0];
			$dtincr_pad = str_pad($dtincr, 6, '0', STR_PAD_LEFT);
			$vJourDtId = $vJournalId.''.$dtincr_pad;
					
			if (empty($PJourDesc)) $vJourDesc = $rows[4]; else $vJourDesc = $PJourDesc;
			
			$sub_query = " INSERT INTO temp_journaldt (JournalDt_Id, Journal_Id, Ledger_Number, Currency_Code, Journaldt_desc, Journaldt_desc1, Journaldt_dbcd, Journaldt_dbcdAra, ". 
						 " Journaldt_amount, Journaldt_amount1, Journaldt_amount2, Journal_Date, Journaldt_ValueDate, Journaldt_posted, manual_no, Logged_Code, journaldt_rate, Journaldt_checkNo )  ".
						 " VALUES ( ".GetSQLValueString($vJourDtId,'double').", ".GetSQLValueString($vJournalId,'double').", ".GetSQLValueString($rows[2],'text').", ".GetSQLValueString($rows[3],'text').", ".
						 "          ".GetSQLValueString($vJourDesc,'text').", ".GetSQLValueString($rows[5],'text').", ".GetSQLValueString($rows[6],'text').", ".
						 "          ".GetSQLValueString($rows[7],'text').", ".GetSQLValueString($rows[8],'double').", ".GetSQLValueString($rows[9],'double').", ".
						 "          ".GetSQLValueString($rows[10],'double').", ".GetSQLValueString(insertMySQLDate($PJourDate),'date').", ".GetSQLValueString(insertMySQLDate($PJourDate),'date').", ".
						 "            0, Null, ".GetSQLValueString($_SESSION['useraccount'],'text').", ".GetSQLValueString($rows[15],'double').", ".GetSQLValueString($rows[15],'text')."	) ";
							 
			$sub_result=mysql_query($sub_query,$connection);
			//echo $sub_query."<br>";exit;
			
			if ($sub_result){
			
				if ($Module_Project == 1 || $Module_CostCenter == 1 || $Module_ProjectDt == 1 || $Module_CostCenterDt == 1) {
					
					$sub_query1 = " INSERT INTO temp_cstjour (JournalDt_Id, Project_Code, Costcent_code, Cstjour_prcnt, Cstjour_amount, Cstjour_amount1, Cstjour_amount2, user_account ) ".
								  " SELECT ".GetSQLValueString($vJourDtId,'double').", Project_Code, Costcent_code, Cstjour_prcnt, Cstjour_amount, Cstjour_amount1, Cstjour_amount2, ".GetSQLValueString($_SESSION['useraccount'],'text')." ".
								  " FROM CstJour ".
								  " WHERE CstJour.JournalDt_Id = '".$rows[0]."' ";
				 
					//echo $sub_query1."<br>";exit;				
					$sub_result1=mysql_query($sub_query1,$connection);
				}

					
			
			
				$dtincr=$dtincr+1;
				$query_update_dtincr="update temp_journal set Journal_dtincr=$dtincr where journal_id=".$vJournalId;
				$result_dtincr=mysql_query($query_update_dtincr,$connection);
				
			} else {
				$ErrorExists = 1;
				$message  = mysql_error($connection); 	
			}
		}

		/*if ($ErrorExists == 0) {
			fcommit();
		} else {
			frollback();
		}*/
    
	}
}


//Post Mode	
else if($mode == "post" && $SJourId != ''){  

	$AllowSave = 1;
	$ErrorExists = 0;
	
	$vCstJourBalPer   = 0;
	$vCstJourBalAmt   = 0;
	$vCstJourBalAmt1  = 0;
	$vCstJourBalAmt2  = 0;
	
	$vChkJourBalAmt   = 0;
	$vChkJourBalAmt1  = 0;
	$vChkJourBalAmt2  = 0;
	
	$vBillJourBalAmt   = 0;
	$vBillJourBalAmt1  = 0;
	$vBillJourBalAmt2  = 0;
	
	$vJourAmountDb1 = 0;
	$vJourAmountDb2 = 0;
	$vJourAmountcd1 = 0;
	$vJourAmountcd2 = 0;
	
	if ($Module_Project == 1 || $Module_CostCenter == 1 || $Module_ProjectDt == 1 || $Module_CostCenterDt == 1) {

	$sub_query1 = " Select JournalDt.JournalDt_ID, (100 - Round(Sum(ifNull(CstJour_Prcnt,0)),2)) As CstJourPer, ".
	              " Round((ifNull(JournalDt_Amount,0)  - Sum(ifNull(CstJour_Amount,0))), ".$DecimalBase.")  As CstJourAmount, ".
				  " Round((ifNull(JournalDt_Amount1,0) - Sum(ifNull(CstJour_Amount1,0))), ".$DecimalBase1.") As CstJourAmount1, ".
				  " Round((ifNull(JournalDt_Amount2,0) - Sum(ifNull(CstJour_Amount2,0))), ".$DecimalBase2.") As CstJourAmount2 ".
				  " From Temp_JournalDt As JournalDt ";
	if ($Module_ReferenceByCostcenter == 1 || $Module_RestrictProjCost == 1 || $Module_RestrictCost == 1)			  
		$sub_query1 .= " left Join Temp_CstJour As CstJour on JournalDt.JournalDt_ID = CstJour.JournalDt_ID ";
	else 	
		$sub_query1 .= " inner Join Temp_CstJour As CstJour on JournalDt.JournalDt_ID = CstJour.JournalDt_ID ";	
	$sub_query1 .=" Where JournalDt.Journal_ID = '".$SJourId."' ".
				  " Group By JournalDt.JournalDt_ID ";
				  
					      
	//echo $sub_query1; exit;
	$sub_result1=mysql_query($sub_query1,$connection);
	while($sub_row1=mysql_fetch_row($sub_result1)){
	
		$vJourDtId        = $sub_row1[0];
		$vCstJourBalPer   = $sub_row1[1];
		$vCstJourBalAmt   = $sub_row1[2];
		$vCstJourBalAmt1  = $sub_row1[3];
		$vCstJourBalAmt2  = $sub_row1[4];
		
		if($vCstJourBalPer != 0 || $vCstJourBalAmt1 != 0 || $vCstJourBalAmt2 != 0) {
			$AllowSave = 0;
			$ErrorRecId = $vJourDtId;
			$message='Save not allowed. Total of Project/Costcenter exceeds Total Amount.';
			break;
		}
	}	
	
	}  			
	
	$sub_query2 = " Select JournalDt.JournalDt_ID, ".
	              " Round((ifNull(JournalDt_Amount,0)  - Sum(ifNull(Chk_Amount,0))), ".$DecimalBase.")  As ChkAmount, ".
				  " Round((ifNull(JournalDt_Amount1,0) - Sum(ifNull(Chk_Amount1,0))), ".$DecimalBase1.") As ChkAmount1, ".
				  " Round((ifNull(JournalDt_Amount2,0) - Sum(ifNull(Chk_Amount2,0))), ".$DecimalBase2.") As ChkAmount2 ".
				  " From Temp_JournalDt As JournalDt Inner Join Temp_ChkJour on JournalDt.JournalDt_ID = Temp_ChkJour.JournalDt_ID ".
				  " Where JournalDt.Journal_ID = '".$SJourId."' ".
				  " Group By JournalDt.JournalDt_ID ";
				  
					      
	//echo $sub_query2; exit;
	$sub_result2=mysql_query($sub_query2,$connection);
	while($sub_row2=mysql_fetch_row($sub_result2)){
	
		$vJourDtId        = $sub_row2[0];
		$vChkJourBalAmt   = $sub_row2[1];
		$vChkJourBalAmt1  = $sub_row2[2];
		$vChkJourBalAmt2  = $sub_row2[3];
		
		if($vChkJourBalAmt != 0 || $vChkJourBalAmt1 != 0 || $vChkJourBalAmt2 != 0) {
			$AllowSave = 0;
			$ErrorRecId = $vJourDtId;
			$message='Save not allowed. Total of Cheques exceeds Total Amount.';
			break;
		}
	}
	
	$sub_query3 = " Select JournalDt.JournalDt_ID, ".
	              " Round((ifNull(JournalDt_Amount,0)  - Sum(ifNull(Bill_Amount,0))), ".$DecimalBase.")  As BillAmount, ".
				  " Round((ifNull(JournalDt_Amount1,0) - Sum(ifNull(Bill_Amount1,0))), ".$DecimalBase1.") As BillAmount1, ".
				  " Round((ifNull(JournalDt_Amount2,0) - Sum(ifNull(Bill_Amount2,0))), ".$DecimalBase2.") As BillAmount2 ".
				  " From Temp_JournalDt As JournalDt Inner Join Temp_BillJour on JournalDt.JournalDt_ID = Temp_BillJour.JournalDt_ID ".
				  " Where JournalDt.Journal_ID = '".$SJourId."' ".
				  " Group By JournalDt.JournalDt_ID ";
					      
	//echo $sub_query3; exit;
	$sub_result3=mysql_query($sub_query3,$connection);
	while($sub_row3=mysql_fetch_row($sub_result3)){
	
		$vJourDtId         = $sub_row3[0];
		$vBillJourBalAmt   = $sub_row3[1];
		$vBillJourBalAmt1  = $sub_row3[2];
		$vBillJourBalAmt2  = $sub_row3[3];
		
		if($vBillJourBalAmt != 0 || $vBillJourBalAmt1 != 0 || $vBillJourBalAmt2 != 0) {
			$AllowSave = 0;
			$ErrorRecId = $vJourDtId;
			$message='Save not allowed. Total of Bills exceeds Total Amount.';
			break;
		}
	}
	
	
	
	//if ($Module_Project == 1)	
		//$message1  = AddDivisions($SJourId,'Null',$txtTransDivID,$txtDivType,$txtDivisionID,$txtDivisionCode,0,0,0,$connection);
		
		
	/*$ArrayCondition=getEventConditions('beforesave',$_SESSION['dbLabel'],$_SESSION['accessschemaid'],$SSorId,'JournalForm','1',$_SESSION['logincompany'],$_SESSION['languageid'],$connection);
	//echo$ArrayCondition['status'];
	//echo$ArrayCondition['message'];
		
	$vCheckUserConditions = $ArrayCondition['status'];
		
	if($vCheckUserConditions == 0){
		$AllowSave = 0;
		$message = $ArrayCondition['message'];
	}				
	*/		

						
	//if ($AllowSave == 1 && $vCheckUserConditions == 1) {	
	
	
		$MainCompanyName=explode('_',$_SESSION['dbName']);

	$sub_query= " Select ifNull(AllowLockedPeriod,0) As AllowLockedPeriod, LockedPeriod As LockedPeriodDate, LockedPeriodDays As LockedPeriodDays ".
				" From ".$_SESSION['dbLabel'].".ListUserDir  ".
				" Where Usercode='".$_SESSION['useraccount']."' ".
				" And Upper(CompanyName) = Upper('".$MainCompanyName[0]."') ".
				" And Upper(Diryear) = Upper('".$MainCompanyName[1]."') ";
				  
	$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
	$rowsperiod = mysql_num_rows($sub_result);

	while($sub_rows=mysql_fetch_array($sub_result)){
		extract($sub_rows);
	}	
	
	$ExceedLockPeriod = 0;
	if ($rowsperiod > 0 && $AllowLockedPeriod == 1) {
		if (!(empty($LockedPeriodDate)) && $LockedPeriodDate != '' && date('Y-m-d',strtotime(insertMySQLDate($txtJourDate))) <= date('Y-m-d',strtotime($LockedPeriodDate))) $ExceedLockPeriod = 1;
		if ($LockedPeriodDays != '' && dateDiff(insertMySQLDate(displayToday()),insertMySQLDate($txtJourDate)) >= $LockedPeriodDays) $ExceedLockPeriod = 1;
	}
	 
	if ($AllowSave == 1  && $ExceedLockPeriod == 0) {	
		
		$sub_query4 = " Select Sum(if(Journaldt_dbcd='D', ifNull(Journaldt_amount1,0), 0)) As TotalDebitAmount1, Sum(if(Journaldt_dbcd='D', ifNull(Journaldt_amount2,0), 0)) As TotalDebitAmount2, ".
					  " Sum(if(Journaldt_dbcd='C', ifNull(Journaldt_amount1,0), 0)) As TotalCreditAmount1, Sum(if(Journaldt_dbcd='C', ifNull(Journaldt_amount2,0), 0)) As TotalCreditAmount2 ".
					  " From Temp_JournalDt ".
					  " Where Journal_Id = ".$SJourId;
		$sub_result4 = selectData($connection, $sub_query4);
				
		$vJourAmountDb1 = $sub_result4[0];
		$vJourAmountDb2 = $sub_result4[1];
		$vJourAmountcd1 = $sub_result4[2];
		$vJourAmountcd2 = $sub_result4[3];
				
																																									
		$sub_query5 = " UPDATE temp_journal SET ".
					  " Amnt1_db = $vJourAmountDb1, Amnt2_db = $vJourAmountDb2, ".
					  " Amnt1_cd = $vJourAmountcd1, Amnt2_cd = $vJourAmountcd2, ".
					  " Journal_Date = ".GetSQLValueString(insertMySQLDate($txtJourDate),'date').", ".
					  " Journal_Remark = ".GetSQLValueString($txtRemark,'text').", ".
					  " Journal_Type = ".GetSQLValueString($txtJourType,'text').",  ".
					  " Manual_No = ".GetSQLValueString($txtManualNo,'text').", ".
					  " Project_Code = ".GetSQLValueString($txtProjectCode,'text').", Costcent_code = ".GetSQLValueString($txtCostCentCode,'text')." ".
					  " WHERE Journal_Id = ".$SJourId;
				 
		$sub_result5=mysql_query($sub_query5,$connection);
		//echo $sub_query5."<br>"; exit;
	
		if ($sub_result5){
			
			$sub_query6 = " UPDATE temp_journaldt SET ".
						  " Journal_Date = ".GetSQLValueString(insertMySQLDate($txtJourDate),'date').
						  " WHERE Journal_Id = ".$SJourId;
			$sub_result6=mysql_query($sub_query6,$connection);
		
			
			$vOldProjCode  	= '';
			$vOldCostCentCode = '';
			
			$sub_query   = " SELECT date_format(Journal_Date,'%m'), Journal_Type, Project_Code, Costcent_code FROM Journal WHERE Journal_ID = $SJourId ";
			$sub_result  = selectData($connection, $sub_query);
			$vOldJourMonth    = $sub_result[0];
			$vOldJourType     = $sub_result[1];
			$vOldProjCode     = $sub_result[2];
			$vOldCostCentCode = $sub_result[3];
			
			
			// In Edit Case, Get The Old Values For SorderType, Project and Costcenter For References Issue
			//$vOldProjCode     = Get_CodeFromId(GetTransDivisionId($SJourId,'JV','PROJECT',$connection),'PROJECT',$connection);
			//$vOldCostCentCode = Get_CodeFromId(GetTransDivisionId($SJourId,'JV','COSTCENTER',$connection),'COSTCENTER',$connection);
				
			$query = "Select Count(*) From Temp_Journal where Journal_ID = '".$SJourId."'";
			//echo $query; exit;
			$result = selectData($connection, $query);
			$ExistInTemp = $result[0];	
			
			$query_checkDelivery  = "select count(*) as JournalExist from journal where journal_id = '$SJourId'";
					$result_checkDelivery = mysql_query($query_checkDelivery, $connection); 
					$row_checkDelivery    = mysql_fetch_array($result_checkDelivery);
					extract($row_checkDelivery);
					if($JournalExist > 0){
						$transType = "U";
					}
					else{
						$transType = "I";
					}
					$company = explode("_", $_SESSION['dbName']);
					$currCompany = strtoupper($company[0]);
			
			
			//Check If Record Exists In Temp Tables
			if ($ExistInTemp == 1) {
			
				fbegin();		
				$query = " SELECT CopyData_TempJournal('JV', ".$SJourId.", '".$_SESSION['useraccount']."') FROM Dual ";
				//echo $query; exit;
				$result = selectData($connection, $query);
				$result = $result[0];
				//echo $query; exit;
				//echo 'error='.$result; exit;
				if ($result != 0){ 
					fcommit();
					
					$sub_query   = " SELECT Journal_RefGovernment, Journal_Date, date_format(Journal_Date,'%m') as Journal_Month, Journal_Type, Journal_TypeRef, Project_Code, Costcent_code FROM Journal WHERE Journal_ID = $SJourId ";
					$sub_result  = selectData($connection, $sub_query);
					$vJourRef      = $sub_result[0];
					$vJourDate     = $sub_result[1];
					$vJourMonth    = $sub_result[2];
					$vJourType     = $sub_result[3];
					$vJourTypeRef  = $sub_result[4];
					$vProjectCode  = $sub_result[5];
					$vCostCentCode = $sub_result[6];
						
					//$vProjectCode  = Get_CodeFromId(GetTransDivisionId_Temp($SJourId,'JV','PROJECT',$connection),'PROJECT',$connection);
					//$vCostCentCode = Get_CodeFromId(GetTransDivisionId_Temp($SJourId,'JV','COSTCENTER',$connection),'COSTCENTER',$connection);
	
					if ($Module_ReferenceByCostcenter == 1)   $vProjCostCent = $vCostCentCode;
					else if ($Module_ReferenceByProject == 1) $vProjCostCent = $vProjectCode;
					else $vProjCostCent = '';
					
					$existCode = 0;
					if ($vOldCostCentCode != $vCostCentCode && $Module_ReferenceByCostcenter == 1 && $vJourRef != ''){
						$querychk = "select 1 from sequence where '$vOldCostCentCode' like Concat(Sequence.CostCenter,'%') and '$vCostCentCode' like Concat(Sequence.CostCenter,'%') ";
						$reschk = mysql_query($querychk, $connection);
						$rwchk = mysql_fetch_row($reschk);
						$existCode = $rwchk[0];
					}
					if ($vOldProjCode != $vProjectCode && $Module_ReferenceByProject == 1 && $vJourRef != ''){
						$querychk = "select 1 from sequence where '$vOldProjCode' like Concat(Sequence.Project,'%') and '$vProjectCode' like Concat(Sequence.Project,'%') ";
						$reschk = mysql_query($querychk, $connection);
						$rwchk = mysql_fetch_row($reschk);
						$existCode = $rwchk[0];
					}	
					
					if ($vJourRef == '' || ($vOldProjCode != $vProjectCode && $Module_ReferenceByProject == 1 && $existCode == 0) ||
						 ($vOldCostCentCode != $vCostCentCode && $Module_ReferenceByCostcenter == 1 && $existCode == 0)) {
							 
						fbegin();
						//$vJourRef = GetNextSequence($connection,$_SESSION['logincompanyname'],$vProjCostCent,'REF','JOURNAL','JV','Null',$vJourDate,$Module_ReferenceByProject,$Module_ReferenceByCostcenter);
						$vJourRef = get_nextsequence('Journal_RefGovernment',$vProjCostCent,$connection);
						fcommit();
								
						$query = " UPDATE Journal SET ".
								 " Journal_RefGovernment = $vJourRef ".
								 " WHERE Journal_ID = $SJourId ";
								
						if (!updateData($connection, $query, true)) 
							$message  = mysql_error($connection);
							
					}	
					
					if ($vJourTypeRef == '' || ($vJourType != $vOldJourType) || ($vOldProjCode != $vProjectCode && $Module_ReferenceByProject == 1) ||
						 ($vOldCostCentCode != $vCostCentCode && $Module_ReferenceByCostcenter == 1)) {
						 
						if($vJourType=='JV')
							$journal_typeref='JOURNAL_TYPEREF';
							
						else if($vJourType=='RV')
							$journal_typeref='Receipt_TypeRef';
							
						else if($vJourType=='PV')
							$journal_typeref='Payment_TypeRef';
							
						else if($vJourType=='DV')
							$journal_typeref='DbtNote_TypeRef';
							
						else if($vJourType=='CV')
							$journal_typeref='CrdNote_TypeRef';
							
						else if($vJourType=='AV')
							$journal_typeref='Amort_TypeRef';
							
						else if($vJourType=='GV')
							$journal_typeref='Charge_TypeRef';
							
						else if($vJourType=='SV')
							$journal_typeref='SaleJour_TypeRef';
						
						else if($vJourType=='JS')
							$journal_typeref='SalesJV_TypeRef';
							
						else if($vJourType=='JP')
							$journal_typeref='PurchasesJV_TypeRef';

						else if($vJourType=='SG')
							$journal_typeref='SaleJour_TypeRef';

						else if($vJourType=='RG')
							$journal_typeref='SaleJour_TypeRef';
						
						else if($vJourType=='FV')
							$journal_typeref='Assets_TypeRef';	
							
						else if($vJourType=='SO')
							$journal_typeref='Sorder_TypeRef';	
							
						else if($vJourType=='SI')
							$journal_typeref='Sales_TypeRef';	
							
						else if($vJourType=='SR')
							$journal_typeref='Sreturn_TypeRef';	
							
						else if($vJourType=='PI')
							$journal_typeref='Purchase_TypeRef';
						
						else if($vJourType=='PR')
							$journal_typeref='Preturn_TypeRef';
							
						else if($vJourType=='DI')
							$journal_typeref='Delivery_TypeRef';
						
						else if($vJourType=='DR')
							$journal_typeref='Dreturn_TypeRef';
							
						else if($vJourType=='TR')
							$journal_typeref='Transfer_TypeRef';
						
						else if($vJourType=='AD')
							$journal_typeref='Adjustment_TypeRef';	
							
						else if($vJourType=='PD')
							$journal_typeref='Production_TypeRef';		

						else if($vJourType=='SE')
							$journal_typeref='StockEval_TypeRef';	
							
						else if($vJourType=='TP')
							$journal_typeref='Transport_TypeRef';

						else if($vJourType=='RI')
							$journal_typeref='Retail_TypeRef';

						else if($vJourType=='CH')
							$journal_typeref='Check_TypeRef'; 
							
							
						fbegin();
						//$vJourTypeRef = GetNextSequence($connection,$_SESSION['logincompanyname'],$vProjCostCent,'TYPEREF','JOURNAL',$vJourType,'Null',$vJourDate,$Module_ReferenceByProject,$Module_ReferenceByCostcenter);
						$vJourTypeRef = get_nextsequence($journal_typeref,$vProjCostCent,$connection);
						fcommit();
						
						$vJourTypeRef = str_pad($vJourTypeRef, 8, '0', STR_PAD_LEFT);
						$vJourTypeRef = $vJourType.''.$vJourTypeRef;
								
						$query = " UPDATE Journal SET ".
								 " Journal_TypeRef = '".$vJourTypeRef."' ".
								 " WHERE Journal_ID = $SJourId ";
								
						if (!updateData($connection, $query, true)) 
							$message  = mysql_error($connection); 
						 
					}	

					if($vJourMonth != $vOldJourMonth) {
		
						fbegin();
						//$vJourFolio = GetNextSequence($connection,$_SESSION['logincompanyname'],$vProjCostCent,'FOLIO','JOURNAL',$vJourMonth,'Null',$vJourDate,$Module_ReferenceByProject,$Module_ReferenceByCostcenter);
						$vJourFolio = get_nextfolio ($vJourMonth,$connection);
						fcommit();
						
						$vJourFolio = str_pad($vJourFolio, 4, '0', STR_PAD_LEFT);
						$vJourFolio = $vJourMonth.''.$vJourFolio;
												
						$query = " UPDATE Journal SET ".
								 " Journal_Folio = $vJourFolio ".
								 " WHERE Journal_ID = $SJourId ";
								
						if (!updateData($connection, $query, true)) 
							$message  = mysql_error($connection); 
					}		
						
					 
				} else{
					$ErrorExists = 1;
					$message  .= mysql_error($connection); 
					$message  .= 'Error In CopyData_TempJournal Function.'; 
					frollback();
				}
			}
			
		} else{
			$ErrorExists = 1;
			$message  = mysql_error($connection); 
			frollback();
		}
		if($config['log_file'] == 1){
						$query_insertToHistory  = "call ".$config['dbName_history'].".InsertToHistory('$transType', '$SJourId', '".$_SESSION['useraccount']."', now(), '".$_SESSION['dbName']."', 'journal', '$currCompany')";
					//echo $query_insertToHistory;exit;
					$result_insertToHistory = mysql_query($query_insertToHistory, $connection);
						}
	}
	else {
	 if ($ExceedLockPeriod == 1)
			$message = 'Save not allowed. Exceed Lock Period.';
		
		frollback();
	}
}




$message   = ReplaceHtmlChars($message);
$PRemark   = ReplaceHtmlChars($PRemark);
$PManualNo = ReplaceHtmlChars($PManualNo);


//echo $mode.$message; exit;

if($mode == "post") {
	if ($AllowSave == 1 && $ErrorExists == 0)
		header ("Location: ./Form_Journal.php?actionmode=".$mode."&mainaction=".$mainmode."&PrJourId=".$SJourId."&PrJourRef=".$vJourRef."&message=".$message);
	else
		header ("Location: ./Form_Journal.php?actionmode=submitrecord&mainaction=".$mainmode."&ErrorRecId=".$ErrorRecId."&txtJourId=".$SJourId."&message=".$message);
}	
else if ($mode == "" && $mainmode == "delete" )	
	header ("Location: ./Form_JournalSearch.php?message=".$message);
else if ($mode == "" && $mainmode == "deletepending")	
	header ("Location: ./Form_JournalSearchPending.php?message=".$message);
else if ($mode == "" && $mainmode == "search" )		
	header ("Location: ./Form_JournalSearch.php?PMode=1&message=".$message);
else if ($mode == "" && $mainmode == "search2" )		
	header ("Location: ./Form_Journal.php?mainaction=edit&txtJourId=$SJourId&message=".$message);
else if ($mode == "" && $mainmode == "loadfromstatmentproject" && $message == '' )		
	header ("Location: ./Form_Journal.php?mainaction=edit&txtJourId=$SJourId");	
else if ($mode == "" && $mainmode == "loadfromstatmentproject" && $message != '' )		
	header ("Location: ./Form_Journal.php?message=".$message);
else if ($mode == "" && $mainmode == "copyjv" ) {
	if ($message != '')
		header ("Location: ./Form_JournalCopySearch.php?PMode=0&message=".$message);		
	else
		header ("Location: ./Form_JournalCopySearch.php?PMode=1&PJourId=".$vJournalId."&message=".$message);
}	
else if ($mode == "importexcel")	
	header ("Location: ./Form_Journal.php?actionmode=submitrecord&mainaction=".$mainmode."&txtJourId=".$SJourId."&message=".$message);
else if ($mode == "cancel" )		
	header ("Location: ./Form_Journal.php");
		
		

function AddDivisionsDt_Dflt($PId,$PDtId,$PLedgerId,$PAmount,$PAmount1,$PAmount2,$connection) {

	$sub_query = " Select Divisions_Id ".
				 " From Temp_TransactionDivisions As TransactionDivisions ".
				 " Where TransactionDivisions.Transaction_Id = '".$PId."' ".
				 " And TransactionDivisions.TransactionDt_Id Is Null ".
				 " And TransactionDivisions_Types = 'JV' ";
	
	$sub_result=mysql_query($sub_query,$connection);
	while($sub_rows=mysql_fetch_array($sub_result)){
	
		fbegin();
		$vTransDivID = GetNextSequence($connection,'Null','Null','ID','TRANSACTIONDIVISIONS','JV','Null',date('Y-m-d H:i:s'),0,0);
		fcommit();

		$vDivisionID = $sub_rows[0];
		
		$query = " INSERT INTO Temp_TransactionDivisions (TransactionDivisions_Id, Transaction_Id, TransactionDt_Id, Divisions_Id, TransactionDivisions_Types, ".
				 " TransactionDivisions_Perc, TransactionDivisions_Amount, TransactionDivisions_AmountB1, TransactionDivisions_AmountB2) ".
				 " VALUES ( ".$vTransDivID.", ".$PId.", ".$PDtId.", ".$vDivisionID.", 'JV', 100, $PAmount, $PAmount1, $PAmount2)";
				 
		$result=mysql_query($query,$connection);		 
	}

	$sub_query1  = " Select LedgerParty_Id From LedgerParty Where Ledger_Number = '".$PLedgerId."'";
	$sub_result1 = selectData($connection, $sub_query1);
	$vLedgerPartyId = $sub_result1[0];
	
	//Insert Defaults For Ledger
	$sub_query1=" Select DivisionTypes_Name From DivisionTypes ".
				" Inner Join DivisionTypesDt on DivisionTypesDt.DivisionTypes_Id = DivisionTypes.DivisionTypes_Id ".
				" Where Upper(DivisionTypesDt_Forms) Like '%JV%' ".
				" And ifNull(DivisionTypesDt_Master,0) = 0 ".
				" Order By DivisionTypes_Name";
	$sub_result1=mysql_query($sub_query1,$connection) or die(mysql_error($connection));	
	while($divtype=mysql_fetch_row($sub_result1)){
			
		$vDivisionType = strtoupper($divtype[0]);
				
		//Get Defaults From Ledger
		$sub_row=GetTransDivisionRow($vLedgerPartyId,'Null','LEDGER',$vDivisionType,$connection);
		$vDivisionID = $sub_row[1];
		
		fbegin();
		$vTransDivID = GetNextSequence($connection,'Null','Null','ID','TRANSACTIONDIVISIONS','JV','Null',date('Y-m-d H:i:s'),0,0);
		fcommit();
		
		
		$query = " INSERT INTO Temp_TransactionDivisions (TransactionDivisions_Id, Transaction_Id, TransactionDt_Id, Divisions_Id, TransactionDivisions_Types, ".
				 " TransactionDivisions_Perc, TransactionDivisions_Amount, TransactionDivisions_AmountB1, TransactionDivisions_AmountB2) ".
				 " VALUES ( ".$vTransDivID.", ".$PId.", ".$PDtId.", ".$vDivisionID.", 'JV', 100, $PAmount, $PAmount1, $PAmount2)";
				 
		$result=mysql_query($query,$connection);	
		
	}
}		
function AddDivisions($PId,$PDtId,$PTransDivID,$PDivType,$PDivisionID,$PDivisionCode,$PAmount,$PAmount1,$PAmount2,$connection) {
	$message  = '';

	$ErrorExists = 0;
	$InsertAllow = 1;
	

	
	if(!is_array($PTransDivID))   $PTransDivID = explode(',', $PTransDivID);
	if(!is_array($PDivType))      $PDivType = explode(',', $PDivType);
	if(!is_array($PDivisionID))   $PDivisionID = explode(',', $PDivisionID);
	if(!is_array($PDivisionCode)) $PDivisionCode = explode(',', $PDivisionCode);
	
	if(is_array($PTransDivID))   $TransDivID_Delete = implode(',', array_filter($PTransDivID));
	$TransDivID_Delete = trim($TransDivID_Delete,','); 
	
	$query = " Delete From Temp_TransactionDivisions ".
			 " Where Transaction_Id = '".$PId."' ".
			 " And TransactionDivisions_Types = 'JV' ".
			 " And TransactionDivisions_Id Not In (".$TransDivID_Delete.") ".
			 " And TransactionDt_Id Is Null ";
	//if($PDtId != '' && $PDtId != 'Null') $query .= " And TransactionDt_Id = '".$PDtId."' ";
	
	$result=mysql_query($query,$connection);
	
	for ($i=0; $i < count($PDivisionCode); $i++) {
	
		$vTransDivID      = $PTransDivID[$i];
		$vDivisionID      = $PDivisionID[$i];
		$vDivisionCode    = $PDivisionCode[$i];
		$vDivisionType    = $PDivType[$i];

		//Check For Division Code Before Insert
		if ($vDivisionCode != '') {
			$sub_query = " Select Count(Divisions_Code) ".
						 " From Divisions Inner Join DivisionTypes on Divisions.DivisionTypes_Id = DivisionTypes.DivisionTypes_Id ".
						 " Where Upper(Divisions_Code) = Upper('".$vDivisionCode."') ".
						 " And Upper(DivisionTypes_Name) = Upper('".$vDivisionType."') ";
			$sub_result = selectData($connection, $sub_query);
			if ($sub_result[0] == 0) {
				$ErrorExists = 1;
				$message = GetMsg('32',$_SESSION['languageid'],'error',$connection);
			}
			
			
		}

		//Check For Division Type If Exists More Than Once For Sorder
		if ($vDivisionCode != '' && $vTransDivID == '') {
			$sub_query = " Select Count(Divisions_Code) ".
						 " From Temp_TransactionDivisions As TransactionDivisions ".
						 " Inner Join Divisions on TransactionDivisions.Divisions_Id = Divisions.Divisions_Id ".
						 " Inner Join DivisionTypes on Divisions.DivisionTypes_Id = DivisionTypes.DivisionTypes_Id ".
						 " Where Upper(DivisionTypes_Name) = Upper('".$vDivisionType."') ".
						 " And TransactionDivisions.Transaction_Id = '".$PId."' ".
						 " And TransactionDivisions_Types = 'JV' ".
						 " And TransactionDt_Id Is Null ";
			//if($PDtId != '' && $PDtId != 'Null') $sub_query .= " And TransactionDivisions.TransactionDt_Id = '".$PDtId."' ";			 
			
			$sub_result = selectData($connection, $sub_query);

			if ($sub_result[0] > 0) {
				$ErrorExists = 1;
				$message = GetMsg('33',$_SESSION['languageid'],'error',$connection).'('.$vDivisionType.')';
			}
		}

		
		if ($ErrorExists == 0 && $vDivisionCode != ''){
		
			if ($vTransDivID != '') {
				$query = " UPDATE Temp_TransactionDivisions Set Divisions_Id = '".$vDivisionID."' ".
						 " WHERE TransactionDivisions_Id = '".$vTransDivID."'";
			} else {
			
				fbegin();
				$vTransDivID = GetNextSequence($connection,'Null','Null','ID','TRANSACTIONDIVISIONS','JV','Null',date('Y-m-d H:i:s'),0,0);
				fcommit();


				fbegin();
				$query = " INSERT INTO Temp_TransactionDivisions (TransactionDivisions_Id, Transaction_Id, TransactionDt_Id, Divisions_Id, TransactionDivisions_Types, ".
						 " TransactionDivisions_Perc, TransactionDivisions_Amount, TransactionDivisions_AmountB1, TransactionDivisions_AmountB2) ".
						 " VALUES ( ".$vTransDivID.", ".$PId.", ".$PDtId.", ".$vDivisionID.", 'JV', 100, $PAmount, $PAmount1, $PAmount2)";
			}
			
					 
			$result=mysql_query($query,$connection);
			//echo $query."<br>";

			if ($result){
				fcommit();

			}else{
				$message  = mysql_error($connection);
				frollback();
			}
		}
	}

	return $message;
}
/*
print <<<HERE
</form>
</body>

HERE;
*/


$return_arr = array();

$row_array['message'] = $message;
$row_array['transid'] = $SJourId;
		
array_push($return_arr,$row_array);
echo json_encode($return_arr);


?>