<?php

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


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

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


$querylog="SELECT FA_InvoicesAllocation as loginaccess, ifNull(FI_RepRestrictProject,0) As FI_RepRestrictProject, ifNull(FI_RepRestrictCostcenter,0) As FI_RepRestrictCostcenter ".
		  " from ".$_SESSION['dbLabel'].".login where user_account='".$_SESSION['useraccount']."' 	and Upper(Login_Schema) = Upper('".$_SESSION['dbName']."')	";
$resultlog=mysql_query($querylog,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultlog)){
	extract($rows);
}

if ($loginaccess=='' or $loginaccess==0)
	header("location:menu.php");


ini_set('max_execution_time', 0);

//Read From Setup Table							
$querysetup= " select DecimalBase, Decimalbase1, Decimalbase2, base1, base2, grid_color1, grid_color2, ifNull(Client_ValidateProject,0) As Client_ValidateProject, ".
             " Date_Format(Setup_VatStartDate,'%Y%m%d') As Setup_VatStartDate, ifNull(Setup_VatPercentage,0) As Setup_VatPercentage from setup ";
$resultsetup=mysql_query($querysetup,$connection) or die(mysql_error());
while($rowsetup=mysql_fetch_array($resultsetup)){
	extract($rowsetup);
} 

//Read From Module Table
$querymodule=" Select ifNull(Module_Project,0) As Module_Project, ifNull(Module_Costcenter,0) As Module_CostCenter, ".
			 " ifNull(Module_RestrictProjCost,0) As Module_RestrictProjCost, ifNull(Module_RestrictCost,0) As Module_RestrictCost, ".
			 " ifNull(Module_ProjectParent,0) As Module_ProjectParent, ifNull(Module_CostCenterParent,0) As Module_CostCenterParent, ".
			 " ifNull(Module_Delivery,0) As Module_Delivery, ifNull(Module_AcctrxPostRV,0) As Module_AcctrxPostRV, ".
			 " ifNull(Module_AcctrxPostCV,0) As Module_AcctrxPostCV ". 
             " From Module ";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}

$queryproject=" select distinct project.project_code, project_name ".
              " from project left join ".$_SESSION['dbLabel'].".loginstk on (($Module_ProjectParent=1 and project.project_code like concat(ifnull(loginstk.project_code,project.project_code),'%')) or ($Module_ProjectParent=0 and project.project_code = loginstk.project_code )) ".
			  " where user_account='".$_SESSION['useraccount']."' ".
			  " and (loginstk.project_code is not null and loginstk.project_code != '')  and Upper(loginstk.company_name) = Upper('".$_SESSION['dbName']."') ".
			  " order by project.project_code";
$projectresult = mysql_query($queryproject,$connection) or die(mysql_error());
$projectexist  = mysql_num_rows($projectresult);		  

$querycostcent=" select distinct costcent.costcent_code, costcent_name ".
               " from costcent left join ".$_SESSION['dbLabel'].".loginstk on (($Module_CostCenterParent=1 and costcent.costcent_code like concat(ifnull(loginstk.costcent_code,costcent.costcent_code),'%')) or ($Module_CostCenterParent=0 and costcent.costcent_code = loginstk.costcent_code )) ".
			   " where user_account='".$_SESSION['useraccount']."' ".
			   " and (loginstk.costcent_code is not null and loginstk.costcent_code != '') and Upper(loginstk.company_name) = Upper('".$_SESSION['dbName']."')  ".
			   " order by costcent.costcent_code";
$costcentresult = mysql_query($querycostcent,$connection) or die(mysql_error());
$costcentexist  = mysql_num_rows($costcentresult);	



$querylog="select ifNull(Login_negativeQty,0) As Login_negativeQty, 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);
}
 

// Setting Initial Values For Parameters
$querydate=" Select Date_Format(Min(Journal_date),'%d/%m/%Y') As DefaultFromDate, ".
           " Date_Format(Max(Journal_date),'%d/%m/%Y') As DefaultToDate, Date_Format(NOW(),'%d/%m/%Y') As DefaultAgingDate ".
		   " From JournalDt ";
$resultdate=mysql_query($querydate,$connection) or die(mysql_error());
$rowdate=mysql_fetch_row($resultdate);



if (!isset($fromdate))  $fromdate = $rowdate[0];
if (!isset($todate))    $todate   = $rowdate[1];

if (!isset($dispfromdate))  $dispfromdate = $fromdate;
if (!isset($disptodate))    $disptodate   = $todate;

if (!empty($fromdate))  $fromdate = explodeword($fromdate);
if (!empty($todate))    $todate   = explodeword($todate);  
if(substr($fromledger,0,2) == '41' ) $ledger_type = 2;
else if(substr($fromledger,0,2) == '40' ) $ledger_type = 1;
if($ledger_type == '') $ledger_type = 1;
if($ledgertype[0] == '') $ledgertype[0] = $ledger_type;
  
 
//echo $fromdate;
$sub_query = "Select Ledger_Name,currency_code From Ledger Where Ledger_Number ='$fromledger'";
$sub_result = selectData($connection, $sub_query);
$fromledgername = $sub_result[0];
$fromledgercurr = $sub_result[1];
 
$dispfromledger 	= $fromledger;
$dispfromledgername = $fromledgername;  

$fromledger    = GetSQLValueString($fromledger, 'text');  
$dispfromledgercurr    =  $fromledgercurr ;  

print <<< HERE
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1256" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> 
<meta name="viewport" content="width=device-width, initial-scale=1.0"> 

<link rel="stylesheet" type="text/css" media="all" href="js/grid/UI_DataGrid_V1.css">
<script type="text/javascript" src="js/grid/UI_DataGrid.js"></script>
<script type="text/javascript" src="js/grid/jquery-1.9.1.js"></script>

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

<link type="text/css" href="js/calendar/jquery.datepick.css" rel="stylesheet">
<script type="text/javascript" src="js/calendar/jquery.datepick.js"></script>

<link type="text/css" href="js/grid/scripts/jquery-ui.css" rel="stylesheet">
<script type="text/javascript" src="js/grid/scripts/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" media="all" href="css-v2/style.css">
<link rel="stylesheet" type="text/css" media="all" href="js/grid/UI_DataGrid_V1.css">
<script type="text/javascript" language="javascript">

function SearchForm() {
	var x=document.invoices;
	if(x.fromledger.value != ''){
		x.actionmode.value = 'Search';
		x.submit();
	}else{
		alert('Please start By choosing a Ledger');
	}
}

function AutoAllocate() {
	var x=document.invoices;
	if(x.fromledger.value != ''){
		let vledger = x.fromledger.value;
		let vfromdate = x.fromdate.value; 
		let vtodate = x.todate.value; 
		
		x.action = 'Form_autoallocateFifo.php?SendLedger_number='+vledger+'&vfromdate='+vfromdate+'&vtodate='+vtodate;
		x.submit();
	}else{
		let vfromdate = x.fromdate.value; 
		let vtodate = x.todate.value; 

		x.action = 'Form_autoallocateFifo_bulk.php?vfromdate='+vfromdate+'&vtodate='+vtodate;
		x.submit();
	}
}


function SubmitAlloc(){
	if(confirm("Are you Sure you want to Submit these Allocations?")){
		var vcurr = document.getElementById('ledger_curr').value;
		var vcurrLedger = document.getElementById('fromledger').value;
		var AllAllocs = document.getElementById('Results').innerHTML.split('<br>');
		const allocX = [];
		for(var i = 1; i < AllAllocs.length; i++){
			var CurrAlloc = AllAllocs[i].split('=&gt;');
			var debit = CurrAlloc[0].split('<b>Debit</b> : ')[1].split(':');
			var debitJvId = debit[0];
			var debitJvAmount = cleanAmount(debit[1]);
			

			var credits = CurrAlloc[1].split(' <b>Credit(s)</b> : ');
			var mycredits = credits[1];
			allocX[i]  = []
			allocX[i].push('--');
			allocX[i].push(debitJvId);
			allocX[i].push(debitJvAmount);
			allocX[i].push(mycredits);

			
		}
		document.invoices.action = 'form_livealloc.php?action=LiveAlloc&curr='+vcurr+'&ledger='+vcurrLedger+'&links='+allocX;
		document.invoices.submit();
	}
 }

function liveAlloc() {


	var vCurrColor = getRandomColor();
	var Debits = '';
	var Credits = '';


	var DebitsforLabels = '';
	var CreditsforLabels = '';

	var inputs = document.getElementsByTagName('input');
		for(var i=0; i<inputs.length; i++){
			if(inputs[i].getAttribute('type') == 'checkbox'){
				if(inputs[i].id.includes("chk_D_"))
				{
					if(inputs[i].checked && inputs[i].disabled == false ){
						Debits = Debits + "|"+inputs[i].id.substr(6,inputs[i].id.length)+':'+document.getElementById("amount_D_"+inputs[i].id.substr(6,inputs[i].id.length)).value;
						DebitsforLabels = DebitsforLabels + "|"+inputs[i].id.substr(6,inputs[i].id.length);
					}
					 
				}
			}
		} 

		for(var i=0; i<inputs.length; i++){
			if(inputs[i].getAttribute('type') == 'checkbox'){
				if(inputs[i].id.includes("chk_C_"))
				{
					if(inputs[i].checked && inputs[i].disabled == false ){
						Credits = Credits + "|"+inputs[i].id.substr(6,inputs[i].id.length)+':'+document.getElementById("amount_C_"+inputs[i].id.substr(6,inputs[i].id.length)).value;
						CreditsforLabels = CreditsforLabels + "|"+inputs[i].id.substr(6,inputs[i].id.length);
					} 
				}
			}
		}


		if(Debits =='' && Credits == '') return false;
		// add to Legend
		document.getElementById('Results').innerHTML = document.getElementById('Results').innerHTML +'<BR><span id="allocColor" style="background-color:'+vCurrColor+';" >&nbsp;</span> <b>Debit</b> : ' + Debits.replace('|','') +'  => <b>Credit(s)</b> : '+ Credits.replace(/[|]/g,'__ __');
		
		
		
		// disabling Fields && coloring
		var AllDebits = DebitsforLabels.split('|');

		for(var j =1; j<=AllDebits.length;j++){
			for(var i=0; i<inputs.length; i++){
				if(inputs[i].getAttribute('type') == 'checkbox'){
					if(inputs[i].id == "chk_D_"+AllDebits[j] )
					{
						if(inputs[i].checked){
							inputs[i].disabled = true;
							document.getElementById("amount_D_"+AllDebits[j]).disabled = true;
							document.getElementById("row_D_"+AllDebits[j]).style.backgroundColor  = vCurrColor;

						}
						 
					}
				}
			} 
		} // end for loop Debits



		var AllCredits = CreditsforLabels.split('|');

		for(var j =1; j<=AllCredits.length;j++){
			for(var i=0; i<inputs.length; i++){
				if(inputs[i].getAttribute('type') == 'checkbox'){
					if(inputs[i].id == "chk_C_"+AllCredits[j] )
					{
						if(inputs[i].checked){
							inputs[i].disabled = true;
							document.getElementById("amount_C_"+AllCredits[j]).disabled = true;
							document.getElementById("row_C_"+AllCredits[j]).style.backgroundColor  = vCurrColor;
						}
						 
					}
				}
			} 
		} // end for loop Credits


		// emptying Fields C & D 
		document.getElementById("field_D").innerHTML = '';
		document.getElementById("field_C").innerHTML = '';
		document.getElementById("field_Bal").innerHTML = '';


		// freeing Debits 
		// to release all checkboxes 
			
		var inputs = document.getElementsByTagName('input');
		for(var i=0; i<inputs.length; i++){
			if(inputs[i].getAttribute('type') == 'checkbox'){
				if(inputs[i].id.includes("chk_D_") ){
 					if(document.getElementById("row_D_"+inputs[i].id.substr(6,inputs[i].id.length)).style.backgroundColor  == '#F7F7F7' || document.getElementById("row_D_"+inputs[i].id.substr(6,inputs[i].id.length)).style.backgroundColor  == 'rgb(230, 230, 230)' ||document.getElementById("row_D_"+inputs[i].id.substr(6,inputs[i].id.length)).style.backgroundColor  == 'rgb(247, 247, 247)' ||  document.getElementById("row_D_"+inputs[i].id.substr(6,inputs[i].id.length)).style.backgroundColor  == '#E6E6E6'){
						inputs[i].disabled  = false;
						inputs[i].checked  = false;
					}
				}
			}
		}


		
}
function SubmitForm() {
	var x=document.invoices;
	
	var vAmountSI = 0;
	var vAmountRV = 0;
	var vTotalPaidAmount = 0;
	var vClosedCounter = 0;
	
	var vSchemaSI = '';
	var vSchemaRV = '';
		
		
	var vInvoicesID    = new Array();
	var vReceiptsID    = new Array();
	
	
	for (var i=0; i< document.getElementsByName('ChkSI[]').length; i++) {
		if (document.getElementsByName('ChkSI[]')[i].checked) {
			var vChkSI = document.getElementsByName('ChkSI[]')[i].value; 
			vNameSI = 'AmountSI'+vChkSI; 
			vAmountSI	= document.getElementById(vNameSI).value;
			vTotalPaidAmount = vTotalPaidAmount + parseFloat(vAmountSI);
			vInvoicesID.push(vChkSI);
		}	
	}
	
	for (var i=0; i<document.getElementsByName('ChkRV[]').length; i++) {
		if (document.getElementsByName('ChkRV[]')[i].checked) {
			var vChkRV = document.getElementsByName('ChkRV[]')[i].value;
			vNameRV = 'AmountRV'+vChkRV;
			vAmountRV	= parseFloat(document.getElementById(vNameRV).value);
			vReceiptsID.push(vChkRV);
		}	
	}
		
	let ledger_type = 0;	
	for (var i=0; i<document.getElementsByName('ledgertype[]').length; i++) {
		if (document.getElementsByName('ledgertype[]')[i].checked) {
			ledger_type = document.getElementsByName('ledgertype[]')[i].value;
		}	
	}
	
	if(Math.round(vAmountRV,2) != Math.round(vTotalPaidAmount,2))
		vClosedCounter = 1;
	else vClosedCounter  = 0;
	
	
	if (vInvoicesID.length == 0 ) {
		alert("Please select at least one invoice.");
	} 
	else if (vReceiptsID.length == 0 ) {
		alert("Please select a Receipt.");
	}	
	else if (vClosedCounter == 1) {
		alert("Please check for total amount paid.");
		x.dAmount.focus();
	}
	else {
		x.action = "Form_AdvPaymentAllocation_Actions.php?mode=AllocateInvoices&PInvoicesID="+vInvoicesID+"&PReceiptsID="+vReceiptsID+"&ledger_type="+ledger_type;
		x.submit();
	}	 
}

function cleanAmount(Amount){
	var AmountX = 0;
	AmountStr = Amount.toString();
	if(AmountStr.includes(",")){
		AmountX = AmountStr.replaceAll(',','');
	}else if(AmountStr == ''){
		AmountX = 0;
	}else{
		AmountX = Amount;
	}
	AmountX = Math.round(AmountX * 10000 ) / 10000;
	return parseFloat(AmountX.toFixed(2));
}

function SelectCredit(TagValue,frmField){
	if(cleanAmount(document.getElementById('field_D').innerHTML) > 0)
	{	
		if(frmField == 1){
			if(document.getElementById("chk_C_"+TagValue).checked == false)
				document.getElementById("chk_C_"+TagValue).checked = true;
			else
				return false;
		}
		var AmountSelected = 0;
		if(document.getElementById("chk_C_"+TagValue).checked == true){
			var Amount = cleanAmount(document.getElementById('amount_C_'+TagValue).value);
			
			if(cleanAmount(document.getElementById('amount_C_'+TagValue).value) <= cleanAmount(document.getElementById('amountH_C_'+TagValue).value)){
				if( cleanAmount(document.getElementById('field_C').innerHTML) + Amount > cleanAmount(document.getElementById('field_D').innerHTML) ){
					
					document.getElementById('amount_C_'+TagValue).value = cleanAmount(cleanAmount(document.getElementById('field_D').innerHTML) - cleanAmount(document.getElementById('field_C').innerHTML));
					document.getElementById('amountB_C_'+TagValue).value = cleanAmount(cleanAmount(document.getElementById('amountH_C_'+TagValue).value) - cleanAmount(document.getElementById('amount_C_'+TagValue).value));
					document.getElementById('field_C').innerHTML = cleanAmount(document.getElementById('field_D').innerHTML);
					document.getElementById('amountlstVal_C_'+TagValue).value = document.getElementById('amount_C_'+TagValue).value ;
				}else{
					document.getElementById('field_C').innerHTML = cleanAmount(cleanAmount(document.getElementById('field_C').innerHTML) + Amount);
					document.getElementById('amountB_C_'+TagValue).value = cleanAmount(cleanAmount(document.getElementById('amountH_C_'+TagValue).value) - cleanAmount(document.getElementById('amount_C_'+TagValue).value));
					document.getElementById('amountlstVal_C_'+TagValue).value = cleanAmount(document.getElementById('amount_C_'+TagValue).value) ; 
				}
			}else{
				alert('Invalid Amount');
			}
		}else{

			document.getElementById('amount_C_'+TagValue).value =  cleanAmount(cleanAmount(document.getElementById('amountH_C_'+TagValue).value) - cleanAmount(document.getElementById('amountU_C_'+TagValue).value)) ;
			document.getElementById('amountB_C_'+TagValue).value = '';
			// document.getElementById('amount_C_'+TagValue).value =  cleanAmount(document.getElementById('amountlstVal_C_'+TagValue).value);
			var Amount = 0;

			var inputs = document.getElementsByTagName('input'); 
			for(var i=0; i<inputs.length; i++){
				if(inputs[i].getAttribute('type') == 'checkbox'){
					if(inputs[i].id.includes("chk_C_") && inputs[i].checked == true && inputs[i].disabled == false)
					{
						Amount = Amount + cleanAmount(document.getElementById("amount_C_"+inputs[i].id.substr(6,inputs[i].id.length)).value);
					}
				}
			}
			document.getElementById('field_C').innerHTML =  cleanAmount(Amount); 
		} 

		document.getElementById('field_Bal').innerHTML =  cleanAmount( cleanAmount(document.getElementById('field_D').innerHTML) - cleanAmount(document.getElementById('field_C').innerHTML) );

	}else{
		alert('please a Transaction');
	}
}


function getRandomColor() {
	var letters = '0123456789ABCDEF';
	var color = '#';
	for (var i = 0; i < 6; i++) {
	  color += letters[Math.floor(Math.random() * 16)];
	}
	return color;
  }

  

function SelectDebit(TagValue) {
	if(document.getElementById("chk_D_"+TagValue).checked == true){
		document.getElementById('field_D').innerHTML = cleanAmount(document.getElementById("amount_D_"+TagValue).value); 
		// to disable all checkboxes 
		var inputs = document.getElementsByTagName('input'); 
		for(var i=0; i<inputs.length; i++){ 
			if(inputs[i].getAttribute('type') == 'checkbox'){ 
				if(inputs[i].id.includes("chk_D_")) 
				{ 
					if(!inputs[i].checked) { 
						inputs[i].disabled  = true; 
					} 
				} 
			} 
		} 
	}else{
		document.getElementById('field_D').innerHTML = "";
		document.getElementById('field_C').innerHTML = "";
		// to release all checkboxes 
		var inputs = document.getElementsByTagName('input');
		for(var i=0; i<inputs.length; i++){
			if(inputs[i].getAttribute('type') == 'checkbox'){
				if(inputs[i].id.includes("chk_D_") && (document.getElementById("row_D_"+inputs[i].id.substr(6,inputs[i].id.length)).style.backgroundColor  == '#F7F7F7' || document.getElementById("row_D_"+inputs[i].id.substr(6,inputs[i].id.length)).style.backgroundColor  == '#E6E6E6'))
				{
					 
						inputs[i].disabled  = false; 
						inputs[i].checked  = false; 
					 
				}
			}
		} 

		for(var i=0; i<inputs.length; i++){
			if(inputs[i].getAttribute('type') == 'checkbox'){
				if(inputs[i].id.includes("chk_C_") && inputs[i].disabled == false)
				{
					 
						inputs[i].disabled  = false; 
						inputs[i].checked  = false; 
					 
				}
			}
		}



	}
	 

}

function showlistledger(str){
	let accountoption;
	
	for(i=0;i<document.getElementsByName('ledgertype[]').length;i++){
		if(document.getElementsByName('ledgertype[]')[i].checked)
		accountoption = document.getElementsByName('ledgertype[]')[i].value;
	}
	window.open('select_accountno.php?item='+str+'&accountoption='+accountoption,'mywindow','width=710,height=550,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}

function ClearForm(){ 
	document.invoices.fromledger.value = '';
	document.invoices.fromledgername.value = '';    
	document.invoices.action = "Form_AdvancedPaymentAllocation1.php";
	document.invoices.submit();
} 

function DeleteDetailLink(LinkID) {
 
	var vDelMsg   = 'Are you sure you want to delete this Link ?';

	
	if (confirm ( vDelMsg ))
	{
		var xmlhttp = getXMLHttpRequest();	
		
		var accountoption = 0;
		for(i=0;i<document.getElementsByName('ledgertype[]').length;i++){
			if(document.getElementsByName('ledgertype[]')[i].checked)
			accountoption = document.getElementsByName('ledgertype[]')[i].value;
		}

		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				{ 
					//var data = $.parseJSON(xmlhttp.responseText);
					//var msg = data[0].message; alert(msg);
					//ReloadGridDt(filepath,formname,action,gridid,transid,LinkID);	
					SearchForm();
				}
			}
		}

		xmlhttp.open("GET","Form_Trans_Actions.php?mode=deleteinvoice2Direct&AllocLink="+LinkID);

		xmlhttp.send();
	}	

}

function UNAllocateSup() {
	var vDelMsg   = 'Are you sure you want to Fully Unllocate this Supplier ?';
	if (confirm ( vDelMsg ))
	{
		var x=document.invoices;
		if(x.fromledger.value != ''){
			x.action = 'Form_trans_Actions.php?mode=unallocateSup&SendLedger_number='+x.fromledger.value;
			x.submit();
		}else{
			alert('Please start By choosing a Ledger');
		}
	}
	
}


</script>
<title>Advanced Payments Allocation</title>
<style type="text/css">

/* Hide HTML5 Up and Down arrows. */
input[type="number"]::-webkit-outer-spin-button, input[type="number"]::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
input[type="number"] {
-moz-appearance: textfield;
}

body,td,th {
	font-family: Verdana, Arial, Helvetica, sans-serif;
	font-size: 11px;
}
body {
	margin-top: 2px;
	margin-left: 1px;
}
a:link {
	text-decoration: none;
	color: #0000FF;
}
a:visited {
	text-decoration: none;
	color: #0000FF;
}
a:hover {
	text-decoration: none;
	color: #0000FF;
}
a:active {
	text-decoration: none;
	color: #0000FF;
}

.style12 {
	font-size: 9px;
	color: #999999;
	font-weight: bold;
}
.style15 {color: #5151FF; font-size: 10px;}
.style16 {
	font-size: 16px;
	color: #FF0000;
	font-weight: bold;
	font-family: "Times New Roman", Times, serif;
}
.style17 {font-size: 9px}
.style25 {color: #999999; font-weight: bold; font-size: 10px; }
.style26 {color: #FF0000}
.style27 {color: #999999 ;font-size: 10px;}
.style28 {color: #FFFFFF ;font-size: 10px;}

</style>

<link type="text/css" rel="stylesheet" href="dhtmlgoodies_calendar.css?random=20051112" media="screen"></LINK>
<SCRIPT type="text/javascript" src="dhtmlgoodies_calendar.js?random=20060118"></script>
<script type="text/javascript" src="js/grid/jquery-1.9.1.js"></script>
</head>
<body>
<form name='invoices' method='post' action=''>
<input type='hidden' name='actionmode' value='$actionmode'>
<input type='hidden' name='mainaction' value='$mainaction'>
<input type='hidden' name='ledger_type' value='$ledger_type'>
<input type='hidden' name='message' value='$message' size='200'>
HERE;

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

$MainCompanyName=explode('_',$_SESSION['dbName']);  
$CompName = $MainCompanyName[0];
// $QueryDir = " Select Concat(CompanyName, '_', DirYear) As DirSchema, Date_Format(StartFinancialDate,'%Y-%m-%d') As StartFinancialDate, Date_Format(EndFinancialDate,'%Y-%m-%d') As EndFinancialDate, CompanyName, DirYear ".
			// " From ".$_SESSION['dbLabel'].".Directories ". 
			// " Where Upper(CompanyName) = Upper('".$CompName."') ".
			// " And ( (ifNull(Date_Format('".$fromdate."','%Y%m'),Date_Format(StartFinancialDate,'%Y%m')) >= Date_Format(StartFinancialDate,'%Y%m') and ifNull(Date_Format('".$todate."','%Y%m'),Date_Format(EndFinancialDate,'%Y%m')) <= Date_Format(EndFinancialDate,'%Y%m')) or   ".
			// //"  		(ifNull(Date_Format(". $fromdate.",'%Y%m'),Date_Format(StartFinancialDate,'%Y%m')) <= Date_Format(StartFinancialDate,'%Y%m') and ifNull(Date_Format(". $todate.",'%Y%m'),Date_Format(EndFinancialDate,'%Y%m')) >= Date_Format(EndFinancialDate,'%Y%m')) or ".
			// "       (Date_Format(StartFinancialDate,'%Y%m') >= ifNull(Date_Format('".$fromdate."','%Y%m'),Date_Format(StartFinancialDate,'%Y%m')) and Date_Format(StartFinancialDate,'%Y%m') <= ifNull(Date_Format('".$todate."','%Y%m'),Date_Format(EndFinancialDate,'%Y%m')) ) or ".
            // "       (Date_Format(EndFinancialDate,'%Y%m') >= ifNull(Date_Format('".$fromdate."','%Y%m'),Date_Format(StartFinancialDate,'%Y%m')) and Date_Format(EndFinancialDate,'%Y%m') <= ifNull(Date_Format('".$todate."','%Y%m'),Date_Format(EndFinancialDate,'%Y%m')) ) ".
			// "      )  ".
			// " Order By DirYear ";
			
// // echo $QueryDir; exit;
// $ResultDir=mysql_query($QueryDir,$connection) or die(mysql_error());
// $ResultDir1=mysql_query($QueryDir,$connection) or die(mysql_error());
// $ResultDir2=mysql_query($QueryDir,$connection) or die(mysql_error());
// $ResultDir3=mysql_query($QueryDir,$connection) or die(mysql_error());
// $ResultDir4=mysql_query($QueryDir,$connection) or die(mysql_error());
// $ResultDir5=mysql_query($QueryDir,$connection) or die(mysql_error());
// $RowsDirCount = mysql_num_rows($ResultDir);
// $ResultDir = mysql_fetch_array($ResultDir);
// extract($ResultDir);
  
$QueryRV = '';

$QueryRV =  "
SELECT
	J.journal_id AS JVID,
	J.journal_type,
	Jdt.Currency_code,
	if(j.journal_type = 'JV' , ifnull( j.Journal_refgovernment , '' ),
    concat (
 		ifnull( cd_transQuery.trans_reference, '' ),
		ifnull( cd_purQuery.purchase_reference, '' ),
		ifnull( cd_delQuery.delivery_reference,  '' )
    ) ) AS ref,
		if(j.journal_type = 'JV' , ifnull( j.Journal_Remark , ' ' ),
    concat(
		ifnull( cd_transQuery.trans_remark, '' ),
		ifnull( cd_purQuery.purchase_remark, '' ),
		ifnull( cd_delQuery.delivery_remark,  '' )
	) )AS description,
	if('$fromledgercurr' = '$base1',
			ifnull( jdt.Journaldt_amount1, 0 ),
			if('$fromledgercurr' = '$base2',
					ifnull( jdt.Journaldt_amount2, 0 ),
					ifnull( convertcurFunc ( Jdt.Currency_code, '$fromledgercurr', now(), 0, 0, '$base1', '$base2', jdt.journaldt_Amount1 ) ,0)
				)
		),
	if('$fromledgercurr' = '$base1',
		ifnull( allALlocatedCredits.AllocatedAmount1, 0 ),
		if('$fromledgercurr' = '$base2',
				ifnull( allALlocatedCredits.AllocatedAmount2, 0 ),
				ifnull( convertcurFunc ( allALlocatedCredits.Currency_code, '$fromledgercurr', now(), 0, 0, '$base1', '$base2', allALlocatedCredits.AllocatedAmount1 ) ,0)
			)
	),
	ifnull(
		round(
				if('$fromledgercurr' = '$base1',
					ifnull( jdt.Journaldt_amount1, 0 ),
					if('$fromledgercurr' = '$base2',
							ifnull( jdt.Journaldt_amount2, 0 ),
							ifnull( convertcurFunc ( Jdt.Currency_code, '$fromledgercurr', now(), 0, 0, '$base1', '$base2', jdt.journaldt_Amount1 ) ,0)
						)
				)
				-  
				if('$fromledgercurr' = '$base1',
					ifnull( allALlocatedCredits.AllocatedAmount1, 0 ),
					if('$fromledgercurr' = '$base2',
							ifnull( allALlocatedCredits.AllocatedAmount2, 0 ),
							ifnull( convertcurFunc ( allALlocatedCredits.Currency_code, '$fromledgercurr', now(), 0, 0, '$base1', '$base2', allALlocatedCredits.AllocatedAmount1 ) ,0)
						)
				) 
			,2),
		0
	) remainingAmount,
	date_format(J.journal_date , '%d/%m/%Y')
FROM
	journal J
	INNER JOIN journaldt JDT ON J.journal_id = JDT.journal_id
	LEFT JOIN (
		SELECT
			journal_idD,
			sum( amount ) AllocatedAmount,
			sum( amountbase1 ) AllocatedAmount1,
			sum( amountbase2 ) AllocatedAmount2,
			currency_code
		FROM
			".$_SESSION['dbLabel'].".alloclink
		where upper( AllocComp ) = upper( '$CompName' )  and ledger_number = $fromledger
		GROUP BY
			journal_idD,ledger_number
	) allALlocatedCredits ON J.journal_id = allALlocatedCredits.journal_idD
	LEFT JOIN ( SELECT purchase_id, purchase_reference, purchase_remark, purchase_InvoiceNo, journal_type,journal_id FROM ".$_SESSION['dbName'].".purchases  where Supplier_code = $fromledger ) AS cd_purQuery ON J.journal_type = cd_purQuery.journal_type
	AND J.journal_id = cd_purQuery.journal_id
	LEFT JOIN ( SELECT delivery_id, delivery_reference, delivery_remark, Delivery_ManualNo, Journal_Type, journal_id FROM ".$_SESSION['dbName'].".deliveries where client_code = $fromledger) AS cd_delQuery ON J.journal_id = cd_delQuery.journal_id
	LEFT JOIN ( SELECT Sale_id, Sale_Reference, Sale_Remark, Sale_ManualNo, journal_type,journal_id FROM ".$_SESSION['dbName'].".sales where client_code = $fromledger ) AS cd_salQuery ON J.journal_type = cd_salQuery.journal_type
	AND J.journal_id = cd_salQuery.journal_id
	LEFT JOIN ( SELECT trans.trans_id, trans.trans_reference, trans_remark, trans_manualno, trans_type, journal_id FROM ".$_SESSION['dbName'].".trans, transdt where trans.trans_id = transdt.trans_id and transdt.ledger_number = $fromledger ) AS cd_transQuery ON  J.journal_id = cd_transQuery.journal_id
WHERE
    JDT.journaldt_dbcd = 'D'
    AND JDT.Ledger_number = $fromledger
	AND J.Journal_BelongsToGroup >= ifnull( $FI_BelongsToGrp , 5 )
	AND J.journal_date between '$fromdate' and '$todate'
	HAVING remainingAmount > 0
	order by j.journal_date";
    //  echo '<br>'.$QueryRV;
//  echo '<br>'.$fromledgercurr;
//exit;


echo"<table cellpadding='0' cellspacing='0' border='0'  align='center' class='layout-width'>";
include_once("header.php");
echo" <tr><td  valign='top'>";

include_once("sidemenu.php");
echo"  </td></tr>";


echo" <tr style='height:26px;'>
		<td  valign='top' id='content-top'>
			<table border='0' cellpadding='0' cellspacing='0' style='table-layout:fixed; height:26px;' class='layout-width'>
			<tr style='height:26px;'>
				<td style='width:38px; height:26px;'>&nbsp;</td>
				<td valign='middle' style='width:300px; height:26px;'><span class='title'>ADVANCED PAYMENTS ALLOCATION</span></td>
				<td class='message' valign='middle' style='height:26px;'>".htmlspecialchars($message, ENT_QUOTES)."</td>
			</tr></table>
		</td>
	  </tr>";

echo"<tr>
		<td  height='34'  valign='top' id='content-top2'>
			<table border='0' cellpadding='0' cellspacing='0' class='layout-width'>
			<tr>
				<td width='30'  height='34'>&nbsp;</td>
				<td valign='middle' height='34' width='720px' align='left'>";
	
	echo"<button type='button' id='btnClear' name='btnClear' onclick='ClearForm(); return false;' title='Clear'><span><span>Clear</span></span></button>";
	echo"<button type='button' id='btnSearch' name='btnSearch' onclick='SearchForm(); return false;' title='Search'><span><span>Search</span></span></button>";
	echo"<button type='button' id='btnSubmit' name='btnSubmit' onclick='AutoAllocate(); return false;' title='Auto Allocate FIFO'><span><span>Auto Allocate FIFO</span></span></button>";
	echo"<button type='button' id='btnSubmit' name='btnSubmit' onclick='UNAllocateSup(); return false;' title='Auto Un - Allocate FIFO'><span><span>UN-Allocate Supplier Invoices</span></span></button>";
	echo"<button type='button' id='btnSubmit' name='btnSubmit' onclick='liveAlloc(); return false;' title='Live Alloc'><span><span>Live Alloc</span></span></button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
	echo"<button type='button' id='btnSubmit' name='btnSubmit' onclick='SubmitAlloc(); return false;' title='Submit Allocations'><span><span>Submit Allocations</span></span></button>";

	

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

echo"<tr><td id='content-body'>
<table border='0'  align='center' valign='top' width=100% class='tablecontent'>
   <tr bgcolor='#F7F7F7'><td valign='top' align='left'>";	 

print <<<HERE
		
		
		<table border="0" style='table-layout:fixed'>
		  <col width=80>
		  <col width=250>
		  <col width=80>
		  <col width=700>

HERE;


echo" <tr>";	  
echo"   <td height='19' colspan='4' align='center' bgcolor='#F5F5F5'>";


echo "<span class='style1' style='padding-left: 20px;'><input type='radio' name='ledgertype[]' id='ledgertype' value='2' ".($ledgertype[0]=='2'?'checked':'')." > Client</span> &nbsp;
<span class='style1' style='padding-left: 38px;'><input type='radio' name='ledgertype[]' id='ledgertype' value='1' ".($ledgertype[0]=='1'?'checked':'')." > Supplier</span>";

echo "</td>";


echo" <tr>";	  
echo"   <td height='19' colspan='2' align='left' bgcolor='#F5F5F5'><span class='style1'>Date</span></td>";
echo"   <td height='19' colspan='2' align='left' bgcolor='#F5F5F5'><span class='style1'>Ledger No. / Name</span></td>";
echo" </tr>";

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

echo" <tr height='25'>";	  
echo"   <td valign='middle' bgcolor='#F5F5F5' ><span class='style1'>From</span></td>";
echo"   <td valign='middle' bgcolor='#F5F5F5' ><span class='style1'>";
echo"      <input type='text' name='fromdate' value='$dispfromdate'  onBlur='checkDateFormat(this)'  maxlength='10' size='10'>";
echo"      <A HREF=\"#\" onClick=\"displayCalendar(document.invoices.fromdate,'dd/mm/yyyy',this); return false;\" NAME=\"anchor1\" ID=\"anchor1\"><image src='./img/cal.gif' border=0 align=center></image></A></span></td>";
echo"   <td align='left' bgcolor='#F5F5F5' ><span class='style1'>From</span></td>";
echo"   <td valign='middle' bgcolor='#F5F5F5' ><span class='style1'>";
echo"   <input name='fromledger' type='text' id='fromledger' size='10' value='".$dispfromledger."' readonly />
        <input name='fromledgername' type='text' id='fromledgername' size='35' value='".$dispfromledgername."' readonly />
		</span>
		<label><span class='style1'><a href='javascript:void(0);' NAME='My Window Name' title=' Select Ledger From ' 
             onClick='showlistledger(3); '><img src='img/btnopen.jpg' width='15' height='20' border='0' /></a> </span></label>";			 
echo"	</td>";
				
echo" </tr>";

echo" <tr height='25'>";
echo"   <td valign='top' bgcolor='#F5F5F5'><span class='style1'>To</span></td>";
echo"   <td valign='top' bgcolor='#F5F5F5'><span class='style1'>";
echo"      <input type='text' name='todate' value='$disptodate'  onBlur='checkDateFormat(this)'   maxlength='10' size='10'>";
echo"      <A HREF=\"#\" onClick=\"displayCalendar(document.invoices.todate,'dd/mm/yyyy',this); return false;\" NAME=\"anchor1\" ID=\"anchor1\"><image src='./img/cal.gif' border=0 align=center></image></A></span></td>";
  
echo" </tr>";



echo" <tr height='25'>";
echo"   <td valign='top' bgcolor='#F5F5F5'><span class='style1'>ViewMode</span></td>";
echo"   <td valign='top' bgcolor='#F5F5F5'>
	<select id= 'isAllocated' name= 'isAllocated'>
		<option value ='0' ";  if($isAllocated == 0) {echo 'Selected';} else { echo '' ; } echo ">Not Alocated</option>";
echo	"<option value ='1' ";  if($isAllocated == 1) {echo 'Selected';} else {echo '' ;} echo ">Preview </option>";"
	</select>

	</td>";
echo"   <td align='left' bgcolor='#F5F5F5'></td>";
echo"   <td valign='middle' bgcolor='#F5F5F5'></td>"; 
echo" </tr>";


//Display Receipts
echo" <tr>";
echo"   <td colspan='4' valign='top' bgcolor='#F5F5F5'>";

if($isAllocated ==0){
	
	echo"   <div style='position:relative; float:left; overflow:none; border:1px solid #B5B5B5;' >
		<div style='overflow:none; height:20px; width:100%; margin-top:5px; text-align:center; font-weight:bold; Font-Size:15px;' >Unallocated Transanctions </div>
		<div style='overflow:none; height:20px; width:100%; margin-top:5px; text-align:center; font-weight:bold;' ><input type='text' id='ledger_curr' name='ledger_curr' value = '".$dispfromledgercurr."' readonly ></div>
		<div style='overflow:auto; height:35px; width:49%; margin-top:5px;display:inline-block;text-align: center;' ><span Style='font-weight:bold;' id='field_D'></span></div>
		<div style='overflow:auto; height:35px; width:49%; margin-top:5px;display:inline-block;text-align: center;' ><span Style='font-weight:bold;' id='field_C'></span></div>
		<div style='overflow:auto; height:35px; width:100%; margin-top:5px;display:inline-block;text-align: center;' ><span Style='font-weight:bold;' id='field_Bal'></span></div>
		<div style='overflow:auto; height:350px; width:40%; margin-top:5px;display:inline-block;' >
		<table border='0' style='table-layout:fixed; width:100%;' id='grid_datatable' class='grid_data'>".
		'<colgroup>
			<col width="5%">
			<col width="7%">
			<col width="15%">
			<col width="12%">
			<col width="32%"> 
			<col width="22%"> 
		</colgroup>';
			
	echo"	<tr height='30'>"; 
	echo"		<th align='center'><span class='style1'>&nbsp;</span></th>";
	echo"		<th align='center'><span class='style1'>REF</span></th>"; 
	echo"		<th align='center'><span class='style1'>Date</span></th>";
	echo"		<th align='center'><span class='style1'>Type</span></th>";
	echo"		<th align='center'><span class='style1'>Description</span></th>";
	echo"		<th align='center'><span class='style1'>Amount</span></th>"; 
	echo"	</tr>";		

	if ($actionmode == 'Search' && $isAllocated == 0) {
	      
		$resultRV=mysql_query($QueryRV,$connection) or die(mysql_error());
		while($rowsRV=mysql_fetch_array($resultRV)){
			extract($rowsRV);
			// echo "<pre>";
			//  print_r($rowsRV);
			// echo "</pre>";
			$ct+=1;
		
			if($ct%2==0)
				$Color="style='background-color:".$grid_color1."'";
			else			
				$Color="style='background-color:".$grid_color2."'";	
			
			echo "<tr ".$Color." id='row_D_$rowsRV[0]'>";
			echo "	<td align='left'><span class='style15'><input type='checkbox' onclick='SelectDebit($rowsRV[0]);' id='chk_D_$rowsRV[0]'></span></td>";
			echo "	<td align='left'><span class='style15'>&nbsp;".$rowsRV[3]."</span></td>";
			echo "	<td align='left'><span class='style15'>&nbsp;".$rowsRV[8]."</span></td>";
			echo "	<td align='center'><span class='style15'>".$rowsRV[1]."</span></td>";
			echo "	<td align='left'><span class='style15'>&nbsp;". $rowsRV[4] ."</span></td>";
			echo "	<td align='right'><input type='text' id='amount_D_$rowsRV[0]' value='".number_format($rowsRV[7] ,$Decimalbase2)."' readOnly style='width: -webkit-fill-available;'></td>";
			echo "</tr>";	
			
		}
		
	}		
			
	echo "	</table></div>";


// >------- End Debit Side


// >----- Start Credit Side

echo"<div style='overflow:auto; height:350px; width:60%; margin-top:5px;display:inline-block;' >
<table border='0' style='table-layout:fixed; width:100%;' id='grid_datatable' class='grid_data'>".
'<colgroup>
	<col width="4%">
	<col width="5%">
	<col width="10%">
	<col width="5%">
	<col width="32%">
	<col width="15%">
	<col width="15%"> 
	<col width="15%"> 
</colgroup>';
    
echo"	<tr height='30'>"; 
echo"		<th align='center'><span class='style1'>&nbsp;</span></th>";
echo"		<th align='center'><span class='style1'>REF</span></th>"; 
echo"		<th align='center'><span class='style1'>Date</span></th>";
echo"		<th align='center'><span class='style1'>Type</span></th>";
echo"		<th align='center'><span class='style1'>Description</span></th>";
echo"		<th align='center'><span class='style1'>Org. Amount</span></th>";
echo"		<th align='center'><span class='style1'>Rem. Amount</span></th>";
echo"		<th align='center'><span class='style1'>Balance</span></th>"; 
echo"	</tr>";		

if ($actionmode == 'Search' && $isAllocated == 0) {
    
    


    $QuerySIX = "
                SELECT distinct
                    J.journal_id as JVID,
                    J.journal_type,
                    Jdt.Currency_code,
                    date_format(Jdt.journal_date, '%d-%m-%Y') as jdtdate,
                    ifnull( tempAllocatedC.AllocatedAmount, 0 ) as existsintemp,
                    ifnull( tempAllocatedC.allocRemark, '' ) as existsintempRem,
                    ifnull( J.Journal_refgovernment, '' ) cd_jvRef,
                    concat ( ifnull( cd_transQuery.trans_reference, '' )   , ifnull( cd_purQuery.purchase_reference, '' )   , ifnull( cd_delQuery.delivery_reference, '' )  ) as REF,
                    concat ( ifnull( J.manual_no, '' ) , ifnull( cd_transQuery.trans_manualno, '' ) ,  ifnull( cd_purQuery.purchase_InvoiceNo, '' ) ,ifnull( cd_delQuery.Delivery_ManualNo, '' ) ) as manual_no,
                    concat ( ifnull( J.Journal_Remark, ''), ifnull( cd_transQuery.trans_reference, '' ), ifnull( cd_transQuery.trans_remark, '' ), ifnull( cd_purQuery.purchase_remark, '' ), ifnull( cd_delQuery.delivery_remark, '' ) ) as description ,
                    
                    round(if('$fromledgercurr' = '$base1', ifNull( journaldt_Amount1, 0 ),
                        if('$fromledgercurr' = '$base2',
                            ifNull( journaldt_Amount2, 0 ) ,
                            ifNull(convertcurFunc(Jdt.Currency_code , '$fromledgercurr', now(), 0,0, '$base1','$base2',journaldt_Amount) , 0 )
                        ) 
                    ),2) as  initialamnt1, 
                    round(ifnull( allALlocatedCredits.AllocatedAmount, 0 ) + ifnull( tempAllocatedC.AllocatedAmount, 0 ),2) AllocatedAmount,

                

                    round(if('$fromledgercurr' = '$base1', ifNull( round( ifnull( jdt.Journaldt_amount1, 0 ) - ifnull( allALlocatedCredits.AllocatedAmount1, 0 ), 2 ) - ifnull( tempAllocatedC.AllocatedAmount1, 0 ), 0 ),
                            if('$fromledgercurr' = '$base2',
                                ifNull( round( ifnull( jdt.Journaldt_amount2, 0 ) - ifnull( allALlocatedCredits.AllocatedAmount2, 0 ), 2 ) - ifnull( tempAllocatedC.AllocatedAmount2, 0 ), 0 ) , 
                                ifNull(convertcurFunc(Jdt.Currency_code , '$fromledgercurr', now(), 0,0, '$base1','$base2',
                                                        (
                                                            round( ifnull( jdt.Journaldt_amount, 0 ) - ifnull( allALlocatedCredits.AllocatedAmount, 0 ), 2 ) - ifnull( tempAllocatedC.AllocatedAmount, 0 )
                                                        )
                                                    )
                                        ,0 )
                            )
                    ),2),

                    round(
                    if('$fromledgercurr' = '$base1', ifNull( round( ifnull( jdt.Journaldt_amount1, 0 ) - ifnull( allALlocatedCredits.AllocatedAmount1, 0 ), 2 ) - ifnull( tempAllocatedC.AllocatedAmount1, 0 ), 0 ),
                            if('$fromledgercurr' = '$base2',
                                ifNull( round( ifnull( jdt.Journaldt_amount2, 0 ) - ifnull( allALlocatedCredits.AllocatedAmount2, 0 ), 2 ) - ifnull( tempAllocatedC.AllocatedAmount2, 0 ), 0 ) , 
                                ifNull(convertcurFunc(Jdt.Currency_code , '$fromledgercurr', now(), 0,0, '$base1','$base2',
                                                        (
                                                            round( ifnull( jdt.Journaldt_amount, 0 ) - ifnull( allALlocatedCredits.AllocatedAmount, 0 ), 2 ) - ifnull( tempAllocatedC.AllocatedAmount, 0 )
                                                        )
                                                    )
                                        ,0 )
                            )
                    ),2) remainingAmount,

                    tempTransAllocated.AllocatedAmount as currTransAllocEIT,
                    tempTransAllocated.allocRemark as currTransAllocEITrem 
                FROM
                    journal J
                    Inner JOIN journaldt JDT ON J.journal_id = JDT.journal_id 
                    LEFT JOIN (
                        SELECT
                            journal_idC,
                            sum( amount ) AllocatedAmount,
                            sum( amountbase1 ) AllocatedAmount1,
                            sum( amountbase2 ) AllocatedAmount2,
                            ifnull(allocRemark, '') as allocRemark
                        FROM
                            ".$_SESSION['dbLabel'].".temp_alloclink 
                    WHERE
                        upper( AllocComp ) = upper( '".$CompName."' ) and ledger_number = $fromledger  
                        GROUP BY
                            journal_idC,ledger_number
                        ) tempAllocatedC ON J.journal_id = tempAllocatedC.journal_idC ";
                
                    $QuerySIX.=" LEFT JOIN (select journal_idC, sum(amount) AllocatedAmount ,sum(amountbase1) AllocatedAmount1 ,sum(amountbase2) AllocatedAmount2 from  ".$_SESSION['dbLabel'].".alloclink  WHERE upper( AllocComp ) = upper( '".$CompName."' ) and ledger_number = $fromledger  group by journal_idC,ledger_number ) allALlocatedCredits on J.journal_id = allALlocatedCredits.journal_idC ";
                
                $QuerySIX.=" LEFT JOIN (select journal_idD, sum(amount) AllocatedAmount ,sum(amountbase1) AllocatedAmount1 ,sum(amountbase2) AllocatedAmount2 , transtype from  ".$_SESSION['dbLabel'].".temp_alloclink group by journal_idD ) tempAllocated on J.journal_id = tempAllocated.journal_idD 
                    left join (
                        SELECT
                        journal_idD,
                        sum( amount ) AllocatedAmount,
                        sum( amountbase1 ) AllocatedAmount1,
                        sum( amountbase2 ) AllocatedAmount2,
                        ifnull(trans_id , '')  as trans_id,
                        ifnull(transtype , '')  as transtype,
                        ifnull(allocRemark, '') as allocRemark,ledger_number
                    FROM
                        ".$_SESSION['dbLabel'].".alloclink 
                    WHERE
                        upper( AllocComp ) = upper( '".$CompName."' )
						and ledger_number = $fromledger 
                    GROUP BY
                        journal_idD, alloclink.trans_id, alloclink.transtype,ledger_number
                    ) tempTransAllocated ON J.journal_id = tempTransAllocated.journal_idD and tempTransAllocated.transtype = '$PTransType'  
                    LEFT JOIN (select purchase_id, purchase_reference,purchase_remark,purchase_InvoiceNo,journal_type , journal_id from ".$_SESSION['dbName'].".purchases where Supplier_code = $fromledger) as cd_purQuery on J.journal_type = cd_purQuery.journal_type  and J.journal_id = cd_purQuery.journal_id
                    LEFT JOIN (select delivery_id, delivery_reference,delivery_remark,Delivery_ManualNo,Journal_Type , journal_id from ".$_SESSION['dbName'].".deliveries where client_code = $fromledger) as cd_delQuery on J.journal_type = cd_delQuery.journal_type  and J.journal_id = cd_delQuery.journal_id
                    LEFT JOIN (select Sale_id, Sale_Reference,Sale_Remark,Sale_ManualNo,journal_type , journal_id from ".$_SESSION['dbName'].".sales where client_code = $fromledger) as cd_salQuery on J.journal_type = cd_salQuery.journal_type  and J.journal_id = cd_salQuery.journal_id 
					LEFT JOIN ( SELECT trans.trans_id, trans.trans_reference, trans_remark, trans_manualno, trans_type, journal_id FROM ".$_SESSION['dbName'].".trans, transdt where trans.trans_id = transdt.trans_id and transdt.ledger_number = $fromledger ) AS cd_transQuery ON  J.journal_id = cd_transQuery.journal_id
                WHERE
                    jdt.Ledger_Number = $fromledger 
                    and JDT.journaldt_dbcd = 'C' 
                    and J.Journal_BelongsToGroup >= ifnull($FI_BelongsToGrp,5)
                    having remainingAmount > 0.001";



                    //echo "<br>$QuerySIX";

                $resultXSI=mysql_query($QuerySIX,$connection)  ;
                while($rowsSIX=mysql_fetch_array($resultXSI)){
                    extract($rowsSIX); 
                    $ct+=1;

                    if($ct%2==0)
                        $Color="style='background-color:".$grid_color1."'";
                    else			
                        $Color="style='background-color:".$grid_color2."'";	
                    
                    echo "<tr ".$Color." id='row_C_$rowsSIX[0]' >";
                    echo "	<td align='left'><span class='style15'><input type='checkbox' onclick='SelectCredit(".$rowsSIX[0].",0);' id='chk_C_$rowsSIX[0]'></span></td>";
                    echo "	<td align='left'><span class='style15'>&nbsp;".$rowsSIX[7]."</span></td>";
                    echo "	<td align='left'><span class='style15'>&nbsp;".$rowsSIX[3]."</span></td>";
                    echo "	<td align='center'><span class='style15'>".$rowsSIX[1]."</span></td>";
                    echo "	<td align='left'><span class='style15'>&nbsp;". $rowsSIX[9] . " - <b> " . $rowsSIX[8] ."</b></span></td>"; 
                    echo "	<td align='left'><span class='style15'>". number_format($rowsSIX[10], 2)."</span></td>"; 
                    echo "	<td align='right'>
								<input type='text' id='amount_C_$rowsSIX[0]' value='".number_format($rowsSIX[13] ,$Decimalbase2)."' onblur='SelectCredit(".$rowsSIX[0].",1);' style='width: -webkit-fill-available;'>
								<input type='hidden' id='amountH_C_$rowsSIX[0]' value='".number_format($rowsSIX[13] ,$Decimalbase2)."'>
								<input type='hidden' id='amountU_C_$rowsSIX[0]' value=''>
								<input type='hidden' id='amountlstVal_C_$rowsSIX[0]' value=''>
							 </td>";
					echo "	<td align='right'>
						<input type='text' id='amountB_C_$rowsSIX[0]'  style='width: -webkit-fill-available;'   value='".number_format($rowsSIX[13] ,$Decimalbase2)."' readOnly>
					</td>";
                    echo "</tr>";	
                    
                    }

    }		
    
echo "	</table>";
echo "</div>";
// >-----End creditSide
// >-----Start Results
echo"<div id='Results'>
	<h1>Live Allocations</h1>
</div>";	
// >-----End Results

    
echo "</div>"; 

 

}else{
	$FR = 0;
	//date_format(Detaillink_date , '%d-%m-%Y') as Detaillink_date,
	$QueryAllocsSup = "
					
				SELECT
				suppliers.LEDGER_NUMBER,
				suppliers.Ledger_name,

				IF( journaldt.journaldt_dbcd = 'D', journaldt.journal_id, '-' ) AS journalID_D,
				IF( journaldt.journaldt_dbcd = 'C', journaldt.journal_id, '-' ) AS journalID_C,
				IF( journaldt.journaldt_dbcd = 'D', journaldt.journaldt_desc, '-' ) AS journaldesc_D,
				IF( journaldt.journaldt_dbcd = 'C', journaldt.journaldt_desc, '-' ) AS journalIdesc_C,
				IF( journaldt.journaldt_dbcd = 'D', journal.JOURNAL_TYPE, '-' ) AS journalType_D,
				IF( journaldt.journaldt_dbcd = 'C', journal.JOURNAL_TYPE, '-' ) AS journalType_C,
				IF( journaldt.journaldt_dbcd = 'D', date_format(journaldt.Journal_Date , '%d/%m/%Y'), '-' ) AS journalDate_D,
				IF( journaldt.journaldt_dbcd = 'C', date_format(journaldt.Journal_Date , '%d/%m/%Y'), '-' ) AS journalDate_C,
				IF( journaldt.journaldt_dbcd = 'D', date_format(journaldt.Journaldt_ValueDate , '%d/%m/%Y'), '-' ) AS journalValueDate_D,
				IF( journaldt.journaldt_dbcd = 'C', date_format(journaldt.Journaldt_ValueDate , '%d/%m/%Y'), '-' ) AS journalValueDate_C,
				IF( journaldt.journaldt_dbcd = 'D', journaldt.Currency_code, '-' ) AS journalCurr_D,
				IF( journaldt.journaldt_dbcd = 'C', journaldt.Currency_code, '-' ) AS journalCurr_C,
				IF(journaldt.journaldt_dbcd = 'D',
					IF(
							suppliers.Currency_Code = 'GHC',
							journaldt.Journaldt_amount1,
						IF
							(
								suppliers.Currency_Code = 'USD',
								journaldt.Journaldt_amount2,
								convertcurFunc ( journaldt.Currency_code, suppliers.Currency_Code, now( ), 0, 0, 'GHC', 'USD', journaldt.Journaldt_amount ) 
							) 
						),
						'-' 
					) AS journalOriginalAmount_D,
				IF(
						journaldt.journaldt_dbcd = 'C',
					IF
						(
							suppliers.Currency_Code = 'GHC',
							journaldt.Journaldt_amount1,
						IF
							(
								suppliers.Currency_Code = 'USD',
								journaldt.Journaldt_amount2,
								convertcurFunc ( journaldt.Currency_code, suppliers.Currency_Code, now( ), 0, 0, 'GHC', 'USD', journaldt.Journaldt_amount ) 
							) 
						),
						'-' 
					) AS journalOriginalAmount_C,
				IF(
						journaldt.journaldt_dbcd = 'C',
					IF
						(
							suppliers.Currency_Code = 'GHC',
							ifnull(ALLCOnC.AllocatedAmount1,0),
						IF
							(
								suppliers.Currency_Code = 'USD',
								ifnull(ALLCOnC.AllocatedAmount2,0),
								convertcurFunc ( ALLCOnC.currency_code, suppliers.Currency_Code, now( ), 0, 0, 'GHC', 'USD', ifnull(ALLCOnC.AllocatedAmount,0) ) 
							) 
						),
						'-' 
					) AS journalAllocatedAmount_C,
					IF(
						journaldt.journaldt_dbcd = 'D',
					IF
						(
							suppliers.Currency_Code = 'GHC',
							ifnull(ALLCOnD.AllocatedAmount1,0),
						IF
							(
								suppliers.Currency_Code = 'USD',
								ifnull(ALLCOnD.AllocatedAmount2,0),
								convertcurFunc ( ALLCOnD.currency_code, suppliers.Currency_Code, now( ), 0, 0, 'GHC', 'USD', ifnull(ALLCOnD.AllocatedAmount,0) ) 
							) 
						),
						'-' 
					) AS journalAllocatedAmount_D,
					IF(
						journaldt.journaldt_dbcd = 'D', ALLC.journal_idC , '-') as AllocatedJournal_id,
				IF(
						journaldt.journaldt_dbcd = 'D',
						concat(
						ifnull( trans1.trans_reference, '' ),
						ifnull( Delivery1.Delivery_Reference, '' ),
						ifnull( Sale1.Sale_Reference, '' ),
						ifnull( purchase1.purchase_Reference, '' ),
						if(journal.JOURNAL_TYPE in ('JV','EX' , 'OP') , ifnull( journal.Journal_refgovernment, '' )  , '')
					) , '-') AS Debit_Ref,
					IF(
						journaldt.journaldt_dbcd = 'C',
						concat(
						ifnull( trans1.trans_reference, '' ),
						ifnull( Delivery1.Delivery_Reference, '' ),
						ifnull( Sale1.Sale_Reference, '' ),
						ifnull( purchase1.purchase_Reference, '' ),
						if(journal.JOURNAL_TYPE in ('JV','EX' , 'OP') , ifnull( journal.Journal_refgovernment, '' )  , '')
					) , '-') AS Credit_Ref,
					
					IF(
						journaldt.journaldt_dbcd = 'D',
						concat(
						ifnull( trans2.trans_reference, '' ),
						ifnull( Delivery2.Delivery_Reference, '' ),
						ifnull( Sale2.Sale_Reference, '' ),
						ifnull( purchase2.purchase_Reference, '' ),
						if(ALLCateJV.JOURNAL_TYPE in ('JV','EX' , 'OP') , ifnull( ALLCateJV.Journal_refgovernment, '' )  , '')
					) , '-') AS Alloc_Ref,
					
					IF(
						journaldt.journaldt_dbcd = 'D',
						concat(
						ifnull( date_format(trans2.trans_date,'%d/%m/%Y'), '' ),
						ifnull( date_format(Delivery2.Delivery_date,'%d/%m/%Y'), '' ),
						ifnull( date_format(Sale2.Sale_date,'%d/%m/%Y'), '' ),
						ifnull( date_format(purchase2.purchase_date,'%d/%m/%Y'), '' ),
						if(ALLCateJV.JOURNAL_TYPE in ('JV','EX' , 'OP') , ifnull( date_format(ALLCateJV.Journal_date,'%d/%m/%Y'), '' )  , '')
					) , '-') AS AllocatedJounal_Date,
					IF(
						journaldt.journaldt_dbcd = 'D',
						concat(
						ifnull( trans2.trans_Type, '' ),
						ifnull( Delivery2.journal_Type, '' ),
						ifnull( Sale2.journal_Type, '' ),
						ifnull( purchase2.journal_Type, '' ),
						if(ALLCateJV.JOURNAL_TYPE in ('JV','EX' , 'OP') , ifnull( ALLCateJV.Journal_Type, '' )  , '')
					) , '-') AS AllocatedJounal_Type,
					
					IF (	journaldt.journaldt_dbcd = 'D',	concat( ifnull( ALLC.allocRemark, '' ) ), '-') AS AllocatedJournal_Remark,

					IF( journaldt.journaldt_dbcd = 'D', ALLC.AllocLink_id , '') as LinkID,
					IF
					(
						suppliers.Currency_Code = 'GHC',
						ALLC.amountbase1,
					IF
						(
							suppliers.Currency_Code = 'USD',
							ALLC.amountbase2,
							convertcurFunc ( ALLC.Currency_code, suppliers.Currency_Code, now( ), 0, 0, 'GHC', 'USD', ALLC.amount ) 
						) 
					) AS allocatedOnDAmount
				FROM
					journaldt
					INNER JOIN journal ON journaldt.journal_id = journal.journal_id
					INNER JOIN suppliers ON journaldt.Ledger_number = suppliers.Ledger_number 
					LEFT JOIN ".$_SESSION['dbLabel'].".alloclink ALLC ON journaldt.journal_id = ALLC.journal_idD  AND ALLC.Ledger_number = $fromledger
					LEFT JOIN journaldt ALLCatedDT ON ALLC.journal_idC = ALLCatedDT.journal_id AND ALLCatedDT.Ledger_number = $fromledger
					LEFT JOIN journal ALLCateJV ON ALLC.journal_idC = ALLCateJV.journal_id
				
				LEFT JOIN trans trans1 ON journal.journal_id = trans1.journal_id 						and journal.JOURNAL_TYPE = trans1.trans_type
					LEFT JOIN deliveries Delivery1 ON journal.journal_id = Delivery1.journal_id 	and journal.JOURNAL_TYPE = Delivery1.JOURNAL_TYPE
					LEFT JOIN sales Sale1 ON journal.journal_id = Sale1.journal_id 						and journal.JOURNAL_TYPE = Sale1.JOURNAL_TYPE
					LEFT JOIN purchases purchase1 ON journal.journal_id = purchase1.journal_id 		and journal.JOURNAL_TYPE = purchase1.JOURNAL_TYPE
					
					LEFT JOIN trans trans2 ON ALLCateJV.journal_id = trans2.journal_id 				and   ALLCateJV.JOURNAL_TYPE = trans2.trans_type
					LEFT JOIN deliveries Delivery2 ON ALLCateJV.journal_id = Delivery2.journal_id 	and journal.JOURNAL_TYPE = Delivery2.JOURNAL_TYPE
					LEFT JOIN sales Sale2 ON ALLCateJV.journal_id = Sale2.journal_id 					and ALLCateJV.JOURNAL_TYPE = Sale2.JOURNAL_TYPE
					LEFT JOIN purchases purchase2 ON ALLCateJV.journal_id = purchase2.journal_id 	and ALLCateJV.JOURNAL_TYPE = purchase2.JOURNAL_TYPE
					
					LEFT JOIN (
					SELECT
						journal_idC,
						ledger_number,
						currency_code,
						ifnull( sum( amount ), 0 ) AllocatedAmount,
						ifnull( sum( amountbase1 ), 0 ) AllocatedAmount1,
						ifnull( sum( amountbase2 ), 0 ) AllocatedAmount2 
					FROM
						".$_SESSION['dbLabel'].".alloclink 
					WHERE
						journal_idC IS NOT NULL 
						and upper(AllocComp) = upper('$CompName')
						and Ledger_number =  $fromledger
					GROUP BY
						journal_idC, ledger_number
					) ALLCOnC ON journaldt.journal_id = ALLCOnC.journal_idC and journaldt.ledger_number = ALLCOnC.ledger_number 
					LEFT JOIN (
						SELECT
							journal_idD,
							ledger_number,
							currency_code,
							ifnull( sum( amount ), 0 ) AllocatedAmount,
							ifnull( sum( amountbase1 ), 0 ) AllocatedAmount1,
							ifnull( sum( amountbase2 ), 0 ) AllocatedAmount2 
						FROM
							".$_SESSION['dbLabel'].".alloclink 
						WHERE
							journal_idD IS NOT NULL
							and upper(AllocComp) = upper('$CompName')
							and Ledger_number =  $fromledger
						GROUP BY
							journal_idD, ledger_number
							) ALLCOnD ON journaldt.journal_id = ALLCOnD.journal_idD and journaldt.ledger_number = ALLCOnD.ledger_number 
					
				WHERE
					journaldt.Ledger_number = $fromledger      

				Having 
				if(journalOriginalAmount_D = '-' , journalOriginalAmount_C - journalAllocatedAmount_C >= 0.001 , 1=1)
				AND if(journalOriginalAmount_D != '-' , journalOriginalAmount_D  >= 0.001 , 1=1)


				ORDER BY
					journaldt.journal_date ASC

	";
	$QueryAllocsClt = "		
	SELECT
	clients.LEDGER_NUMBER,
	clients.Ledger_name,

	IF( journaldt.journaldt_dbcd = 'D', journaldt.journal_id, '-' ) AS journalID_D,
	IF( journaldt.journaldt_dbcd = 'C', journaldt.journal_id, '-' ) AS journalID_C,
	IF( journaldt.journaldt_dbcd = 'D', journaldt.journaldt_desc, '-' ) AS journaldesc_D,
	IF( journaldt.journaldt_dbcd = 'C', journaldt.journaldt_desc, '-' ) AS journalIdesc_C,
	IF( journaldt.journaldt_dbcd = 'D', journal.JOURNAL_TYPE, '-' ) AS journalType_D,
	IF( journaldt.journaldt_dbcd = 'C', journal.JOURNAL_TYPE, '-' ) AS journalType_C,
	IF( journaldt.journaldt_dbcd = 'D', date_format(journaldt.Journal_Date , '%d/%m/%Y'), '-' ) AS journalDate_D,
	IF( journaldt.journaldt_dbcd = 'C', date_format(journaldt.Journal_Date , '%d/%m/%Y'), '-' ) AS journalDate_C,
	IF( journaldt.journaldt_dbcd = 'D', date_format(journaldt.Journaldt_ValueDate , '%d/%m/%Y'), '-' ) AS journalValueDate_D,
	IF( journaldt.journaldt_dbcd = 'C', date_format(journaldt.Journaldt_ValueDate , '%d/%m/%Y'), '-' ) AS journalValueDate_C,
	IF( journaldt.journaldt_dbcd = 'D', journaldt.Currency_code, '-' ) AS journalCurr_D,
	IF( journaldt.journaldt_dbcd = 'C', journaldt.Currency_code, '-' ) AS journalCurr_C,
	IF(journaldt.journaldt_dbcd = 'D',
		IF(
				clients.Currency_Code = 'GHC',
				journaldt.Journaldt_amount1,
			IF
				(
					clients.Currency_Code = 'USD',
					journaldt.Journaldt_amount2,
					convertcurFunc ( journaldt.Currency_code, clients.Currency_Code, now( ), 0, 0, 'GHC', 'USD', journaldt.Journaldt_amount ) 
				) 
			),
			'-' 
		) AS journalOriginalAmount_D,
	IF(
			journaldt.journaldt_dbcd = 'C',
		IF
			(
				clients.Currency_Code = 'GHC',
				journaldt.Journaldt_amount1,
			IF
				(
					clients.Currency_Code = 'USD',
					journaldt.Journaldt_amount2,
					convertcurFunc ( journaldt.Currency_code, clients.Currency_Code, now( ), 0, 0, 'GHC', 'USD', journaldt.Journaldt_amount ) 
				) 
			),
			'-' 
		) AS journalOriginalAmount_C,
	IF(
			journaldt.journaldt_dbcd = 'C',
		IF
			(
				clients.Currency_Code = 'GHC',
				ifnull(ALLCOnC.AllocatedAmount1,0),
			IF
				(
					clients.Currency_Code = 'USD',
					ifnull(ALLCOnC.AllocatedAmount2,0),
					convertcurFunc ( ALLCOnC.currency_code, clients.Currency_Code, now( ), 0, 0, 'GHC', 'USD', ifnull(ALLCOnC.AllocatedAmount,0) ) 
				) 
			),
			'-' 
		) AS journalAllocatedAmount_C,
		IF(
			journaldt.journaldt_dbcd = 'D',
		IF
			(
				clients.Currency_Code = 'GHC',
				ifnull(ALLCOnD.AllocatedAmount1,0),
			IF
				(
					clients.Currency_Code = 'USD',
					ifnull(ALLCOnD.AllocatedAmount2,0),
					convertcurFunc ( ALLCOnD.currency_code, clients.Currency_Code, now( ), 0, 0, 'GHC', 'USD', ifnull(ALLCOnD.AllocatedAmount,0) ) 
				) 
			),
			'-' 
		) AS journalAllocatedAmount_D,
		IF(
			journaldt.journaldt_dbcd = 'D', ALLC.journal_idC , '-') as AllocatedJournal_id,
	IF(
			journaldt.journaldt_dbcd = 'D',
			concat(
			ifnull( trans1.trans_reference, '' ),
			ifnull( Delivery1.Delivery_Reference, '' ),
			ifnull( Sale1.Sale_Reference, '' ),
			ifnull( purchase1.purchase_Reference, '' ),
			if(journal.JOURNAL_TYPE in ('JV','EX' , 'OP') , ifnull( journal.Journal_refgovernment, '' )  , '')
		) , '-') AS Debit_Ref,
		IF(
			journaldt.journaldt_dbcd = 'C',
			concat(
			ifnull( trans1.trans_reference, '' ),
			ifnull( Delivery1.Delivery_Reference, '' ),
			ifnull( Sale1.Sale_Reference, '' ),
			ifnull( purchase1.purchase_Reference, '' ),
			if(journal.JOURNAL_TYPE in ('JV','EX' , 'OP') , ifnull( journal.Journal_refgovernment, '' )  , '')
		) , '-') AS Credit_Ref,
		
		IF(
			journaldt.journaldt_dbcd = 'D',
			concat(
			ifnull( trans2.trans_reference, '' ),
			ifnull( Delivery2.Delivery_Reference, '' ),
			ifnull( Sale2.Sale_Reference, '' ),
			ifnull( purchase2.purchase_Reference, '' ),
			if(ALLCateJV.JOURNAL_TYPE in ('JV','EX' , 'OP') , ifnull( ALLCateJV.Journal_refgovernment, '' )  , '')
		) , '-') AS Alloc_Ref,
		
		IF(
			journaldt.journaldt_dbcd = 'D',
			concat(
			ifnull( date_format(trans2.trans_date,'%d/%m/%Y'), '' ),
			ifnull( date_format(Delivery2.Delivery_date,'%d/%m/%Y'), '' ),
			ifnull( date_format(Sale2.Sale_date,'%d/%m/%Y'), '' ),
			ifnull( date_format(purchase2.purchase_date,'%d/%m/%Y'), '' ),
			if(ALLCateJV.JOURNAL_TYPE in ('JV','EX' , 'OP') , ifnull( date_format(ALLCateJV.Journal_date,'%d/%m/%Y'), '' )  , '')
		) , '-') AS AllocatedJounal_Date,
		IF(
			journaldt.journaldt_dbcd = 'D',
			concat(
			ifnull( trans2.trans_Type, '' ),
			ifnull( Delivery2.journal_Type, '' ),
			ifnull( Sale2.journal_Type, '' ),
			ifnull( purchase2.journal_Type, '' ),
			if(ALLCateJV.JOURNAL_TYPE in ('JV','EX' , 'OP') , ifnull( ALLCateJV.Journal_Type, '' )  , '')
		) , '-') AS AllocatedJounal_Type,
		
		IF (	journaldt.journaldt_dbcd = 'D',	concat( ifnull( ALLC.allocRemark, '' ) ), '-') AS AllocatedJournal_Remark,

		IF( journaldt.journaldt_dbcd = 'D', ALLC.AllocLink_id , '') as LinkID,
		IF
		(
			clients.Currency_Code = 'GHC',
			ALLC.amountbase1,
		IF
			(
				clients.Currency_Code = 'USD',
				ALLC.amountbase2,
				convertcurFunc ( ALLC.Currency_code, clients.Currency_Code, now( ), 0, 0, 'GHC', 'USD', ALLC.amount ) 
			) 
		) AS allocatedOnDAmount
	FROM
		journaldt
		INNER JOIN journal ON journaldt.journal_id = journal.journal_id
		INNER JOIN clients ON journaldt.Ledger_number = clients.Ledger_number
		LEFT JOIN ".$_SESSION['dbLabel'].".alloclink ALLC ON journaldt.journal_id = ALLC.journal_idD  AND ALLC.Ledger_number = $fromledger
		LEFT JOIN journaldt ALLCatedDT ON ALLC.journal_idC = ALLCatedDT.journal_id  
		AND ALLCatedDT.Ledger_number = journaldt.Ledger_number
		LEFT JOIN journal ALLCateJV ON ALLC.journal_idC = ALLCateJV.journal_id
	
		LEFT JOIN trans trans1 ON journal.journal_id = trans1.journal_id 						
		LEFT JOIN deliveries Delivery1 ON journal.journal_id = Delivery1.journal_id 	
		LEFT JOIN sales Sale1 ON journal.journal_id = Sale1.journal_id 						
		LEFT JOIN purchases purchase1 ON journal.journal_id = purchase1.journal_id 		
		
		LEFT JOIN trans trans2 ON ALLCateJV.journal_id = trans2.journal_id 				and   ALLCateJV.JOURNAL_TYPE = trans2.trans_type
		LEFT JOIN deliveries Delivery2 ON ALLCateJV.journal_id = Delivery2.journal_id 	and ALLCateJV.JOURNAL_TYPE = Delivery2.JOURNAL_TYPE
		LEFT JOIN sales Sale2 ON ALLCateJV.journal_id = Sale2.journal_id 					and ALLCateJV.JOURNAL_TYPE = Sale2.JOURNAL_TYPE
		LEFT JOIN purchases purchase2 ON ALLCateJV.journal_id = purchase2.journal_id 	and ALLCateJV.JOURNAL_TYPE = purchase2.JOURNAL_TYPE
		
		LEFT JOIN (
		SELECT
			journal_idC,
			ledger_number,
			currency_code,
			ifnull( sum( amount ), 0 ) AllocatedAmount,
			ifnull( sum( amountbase1 ), 0 ) AllocatedAmount1,
			ifnull( sum( amountbase2 ), 0 ) AllocatedAmount2 
		FROM
			".$_SESSION['dbLabel'].".alloclink 
		WHERE
			journal_idC IS NOT NULL 
			and upper(AllocComp) = upper('$CompName')
			AND Ledger_number = $fromledger 
		GROUP BY
			journal_idC, ledger_number
		) ALLCOnC ON journaldt.journal_id = ALLCOnC.journal_idC and journaldt.ledger_number = ALLCOnC.ledger_number 
		LEFT JOIN (
			SELECT
				journal_idD,
				ledger_number,
				currency_code,
				ifnull( sum( amount ), 0 ) AllocatedAmount,
				ifnull( sum( amountbase1 ), 0 ) AllocatedAmount1,
				ifnull( sum( amountbase2 ), 0 ) AllocatedAmount2 
			FROM
				".$_SESSION['dbLabel'].".alloclink 
			WHERE
				journal_idD IS NOT NULL
				and upper(AllocComp) = upper('$CompName')
				AND Ledger_number = $fromledger 

			GROUP BY
				journal_idD, ledger_number
				) ALLCOnD ON journaldt.journal_id = ALLCOnD.journal_idD and journaldt.ledger_number = ALLCOnD.ledger_number 
		
	WHERE
		journaldt.Ledger_number = $fromledger 
		

	Having 
	if(journalOriginalAmount_D = '-' , journalOriginalAmount_C - journalAllocatedAmount_C >= 0.001 , 1=1)
	AND if(journalOriginalAmount_D != '-' , journalOriginalAmount_D  >= 0.001 , 1=1)



	ORDER BY
		journaldt.journal_date ASC

	"; 
 	 
	$ref = '';
	$color1 = "style='Height: 20px;background-color: #FFFFFF'";	
	$color2 = "style='Height: 20px;background-color: #d3d3d3'";

	echo '<table width="100%" cellpadding=0 cellspacing=0>';
	
	echo"	<tr height='30'>";
	echo"	</tr>";
	echo"	<tr height='30'>"; 
	echo"		<th align='left'><span class='style13'>REF</span></th>"; 
	echo"		<th align='left'><span class='style13'>Date</span></th>";
	echo"		<th align='left'><span class='style13'>Type</span></th>"; 
	echo"		<th align='right'><span class='style13'>Amount $fromledgercurr</span></th>"; 
	echo"		<th align='center'><span> &nbsp;</span></th>";
	echo"		<th align='center'><span> &nbsp;</span></th>";
	echo"		<th align='left'><span class='style13'>REF</span></th>"; 
	echo"		<th align='left'><span class='style13'>Date</span></th>";
	echo"		<th align='left'><span class='style13'>Type</span></th>"; 
	echo"		<th align='right'><span class='style13'>Amount $fromledgercurr</span></th>";
	echo"		<th align='right'><span class='style13'>Rem. Amount $fromledgercurr</span></th>";   
	echo"	</tr>";		
	 
	if($_POST['ledgertype'][0] == 1){
		 // echo "1-<br>".$QueryAllocsSup;
		$resultAlloc=mysql_query($QueryAllocsSup,$connection) or die(mysql_error());    
	 }else if($_POST['ledgertype'][0] == 2){
		 // echo "1-<br>". $QueryAllocsClt;
		$resultAlloc=mysql_query($QueryAllocsClt,$connection) or die(mysql_error());
	 }
	$SuppTotal = 0;  
    while ($rowsAlloc=mysql_fetch_array($resultAlloc)) {
 				$FR++;
				extract($rowsAlloc); 
				if ($ref != $journalID_D || $jourtype != $journalType_D || $ref == '-')  {
					if ($FR > 1) {
						$colorSwitcherIndex++;
					} 
					$remainingAmount     = $journalOriginalAmount_D;
					// $ref = $Debit_Ref;
				}
				
				// calculate Sup Overall Balance
				if($ref != $journalID_D && $journalID_D != '-' ){
					$SuppTotal  += $journalOriginalAmount_D - $allocatedOnDAmount  ;
					// ECHO "<HR>";
					// ECHO "<BR>->   (+) " . $journalOriginalAmount_D - $allocatedOnDAmount  ;
				}elseif($ref == $journalID_D && $journalID_D != '-'){
					$SuppTotal -= $allocatedOnDAmount ;
					// ECHO "<BR>->   (+) " . $allocatedOnDAmount ;
				}else{
					$SuppTotal -= ($journalOriginalAmount_C - $journalAllocatedAmount_C) ;
					// ECHO "<BR>->   (-) " . round(($journalOriginalAmount_C - $journalAllocatedAmount_C) ;
				} 



				($colorSwitcherIndex % 2 == 0) ? $color = $color2 : $color = $color1;
				
				$PaidAmount    = round($allocatedOnDAmount,2); 
				$remainingAmount = round($remainingAmount,2) - round($allocatedOnDAmount,2);

				
				// -- end jp color switcher
				echo"<tr $color >";	
				// echo "<BR> $ref ---  $Debit_Ref";
				if($ref != $journalID_D && $journalID_D != '-' ){
					
						echo "	<td align='left'><span>$Debit_Ref</span></td>";
						echo " <td align='left'>$journalDate_D</td>"; 
						echo "	<td align='left'><span>$journalType_D</span></td>"; 
						echo "	<td align='right'><span>".number_format(round($journalOriginalAmount_D ,2),$Decimalbase1)."</span></td>"; 
					
				} else {
					echo " <td align='left'>&nbsp;</td>";
					echo "	<td align='left'><span>&nbsp;</span></td>";
					echo "	<td align='left'><span>&nbsp;</span></td>"; 
					echo "	<td align='right'><span>&nbsp;</span></td>"; 
				}

					//spacer
					echo " <td align='left'> &nbsp;</td>";

					//delete detaillink
					if($LinkID != '' ){
						echo '<td ><span class="style5"><img src="img/delete.png" onmouseover="style.cursor=\'hand\'" onclick="DeleteDetailLink('.$LinkID.');" title="Delete Relation" style="width: 20px; height: 20px; cursor: pointer;"></span></td>';
					}else{
						echo " <td align='left'> &nbsp;</td>";
					}
					//start of Credit Part  
					if($journalID_D != '-'){
						echo "	<td align='left'><span>$Alloc_Ref</span></td>";
						echo " <td align='left'>$AllocatedJounal_Date</td>"; 
						echo "	<td align='left'><span> $AllocatedJounal_Type   </span></td>";
						echo "	<td align='right'><span>".number_format(round($allocatedOnDAmount,2),$Decimalbase1)." </span></td>";
						echo "	<td align='right'><span>".number_format(round($remainingAmount,2),$Decimalbase2) ." </span></td>";

					}else{ // Case if allocated
						echo "	<td align='left'><span> $Credit_Ref </span></td>";
						echo "	<td align='left'><span> $journalDate_C </span></td>";
						echo "	<td align='left'><span> $journalType_C</span></td>";
						echo "	<td align='right'><span>".number_format(round($journalOriginalAmount_C - $journalAllocatedAmount_C,2),$Decimalbase1)."  </span></td>";
						echo "	<td align='right'><span>".number_format(round($journalOriginalAmount_C - $journalAllocatedAmount_C,2),$Decimalbase1)."  </span></td>";
					}
					// $SuppTotal += round($remainingAmount,2) - round($journalOriginalAmount_C - $journalAllocatedAmount_C,2);
					//  echo "<BR>----(".$SuppTotal.")----";
					$ref = $journalID_D;
					$jourtype = $journalType_D; 
					echo"</tr>";


		 
	}
	echo"<TR height='32px'><td colspan='11'align = 'center'>
	<b>Supplier Total : </b> " . number_format(round($SuppTotal,2),$Decimalbase1) . "
	</td></TR>";
	echo '</table>';
}

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


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

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

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


function GetSQLValueString($theValue, $theType) 
{
  $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "Null";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "Null";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "Null";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "Null";
      break;
  }
  return $theValue;
}

function explodeword($date)
{

	$trim = explode('/',$date);
	$trim = "$trim[2]"."-"."$trim[1]"."-"."$trim[0]";
	return $trim;
}
echo"  
</form>
 
</body>
</html>";

?>