<?php
session_start();
//header("Content-type: text/html; charset=windows-1256");


if($_SESSION['dbName']==""){
header("location:../index.php");
}
$FormName = $_POST["FormName"]; if ($FormName == ""){$FormName = $_GET["FormName"];}	
$FormName = 'Form_Receipt';
include("config.inc.php");
include("Functions_UserAccess.php");
include("function.inc.php");

$connection = mysql_connect($config['dbServer'],$config['dbUser'],$config['dbPass']);
		mysql_select_db($_SESSION['dbName'],$connection);
		
mysql_query("SET NAMES 'utf8'"); 
mysql_query('SET CHARACTER SET utf8'); 

//Grid Colors
$grid_color1=getSmodulevalue('grid_color1','string',$_SESSION['logincompany'],$_SESSION['dbLabel'],$connection);
$grid_color2=getSmodulevalue('grid_color2','string',$_SESSION['logincompany'],$_SESSION['dbLabel'],$connection);

$dist_receiptdt=getSmodulevalue('dist_receiptdt','string',$_SESSION['logincompany'],$_SESSION['dbLabel'],$connection);

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


if($mainmode=='')	$mainmode='insert';

if($mainmode=='edit' && $dist_receiptdt==1) {
	$readonlyactive = 'readonly';
	$disactive = '';
}
else {$readonlyactive = '';$disactive = '';}




if($mainmode=='edit' && $dist_receiptdt==1) $disablebutton = 'disabled';
else $disablebutton=''; 

if($dist_receiptdt==0) $disabledistr = 'disabled';
else $disabledistr='';

$sub_result=getformdetails($FormName,$_SESSION['accessschemaid'],$_SESSION['dbLabel']);

$sub_row=mysql_fetch_row($sub_result);
$Form_Insert=$sub_row[1];
$Form_Edit=$sub_row[2];
$Form_Print=$sub_row[4];
$Form_Preview=$sub_row[5];
$Form_View=$sub_row[7];
$Form_Delete=$sub_row[3];


$base1=getSmodulevalue('base1','string',$_SESSION['logincompany'],$_SESSION['dbLabel'],$connection);
$base2=getSmodulevalue('base2','string',$_SESSION['logincompany'],$_SESSION['dbLabel'],$connection);

$query_schema = "SELECT accounting_schema,receipt_cashdebit,receipt_checkdebit, receipt_cashdebit2,AdditionalAmount_Account,
				receipt_checkdebit2,receipt_bankdebit,receipt_bankdebit2 from setup";
		//echo$query_schema;
		$result_schema=mysql_query($query_schema, $connection);		
		$row=mysql_fetch_row($result_schema);
		$schema=$row[0];
		$receipt_cashdebit=$row[1];
		$receipt_checkdebit=$row[2];
		$receipt_cashdebit2=$row[3];
		$AdditionalAmount_Account = $row[4];
		$receipt_checkdebit2 = $row[5];
		$receipt_bankdebit = $row[6];
		$receipt_bankdebit2 = $row[7];


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

$sub_result=get_labelbuttons($_SESSION['dbLabel'],$_SESSION['accessid'],$connection);

while($sub_row=mysql_fetch_row($sub_result)){

	$ButtonArray[$sub_row[0]]['ButtonLabel']= $sub_row[1];
	$ButtonArray[$sub_row[0]]['ButtonTitle']= $sub_row[2];
}	
print <<< HERE
<!DOCTYLE HTML PUBLIC
"-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR?html4/loose.dtd">

<html>
<head><title>Receipts</title>
<link rel="stylesheet" type="text/css" href="jquery.autocomplete.css" />
<style>
		    table.mt {border-width: 0px;border-spacing:0px ;border-style: solid;border-color: #cfcfcf;border-collapse: collapse;background-color: transparent;}
            table.mt th {border-width: 0px;padding: 0px;border-style: solid;border-color: #cfcfcf;white-space: nowrap; background-color: #F6F6F6;font-size:9px}
            table.mt td {border-width: 1px;padding: 0px;border-style: solid;border-color: #cfcfcf;vertical-align:middle;font-size:9px}


			
input:focus {border:1px solid #1e87a5;background-color:#f2f2f2;}
select:focus {border:1px solid #1e87a5;}

input:hover {border:1px solid #1e87a5;background-color:#f2f2f2;}
select:hover {border:1px solid #1e87a5;}

</style>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.autocomplete.js"></script>

	<script language="JavaScript" src="dhtmlgoodies_calendar.js"></script>
	<link rel="stylesheet" href="dhtmlgoodies_calendar.css">
	<link rel="stylesheet" type="text/css" media="all" href="css/style.css">
<LINK REL=StyleSheet HREF="css/style.css" TYPE="text/css" MEDIA=screen>
<link rel="stylesheet" type="text/css" media="all" href="css/style.css">

	<script language="JavaScript" src="dhtmlgoodies_calendar.js"></script>
	<link rel="stylesheet" href="dhtmlgoodies_calendar.css">

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


    function toggle_visibility(id) {
       var e = document.getElementById(id);
       if(e.style.display == 'block')
          e.style.display = 'none';
       else
          e.style.display = 'block';
    }




function changevalue(obj,indx){

if(obj.checked)
	document.getElementById(indx).value = 1;
	else
	document.getElementById(indx).value = 0;
}


function set_family(){
document.feesreport.action="search_family.php";
document.feesreport.submit();
}

function showlistledgers(num){

	window.open('List_ReceiptLedgers.php?number='+num,'mywindow','width=600,height=350,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}

function change_action4(){

if(document.feesreport.regreceiptheader_amount.value=='' || document.feesreport.regreceiptheader_amount.value==0 ){
document.feesreport.regreceiptheader_amountbase1.focus();
return;
}
document.feesreport.submit();
}

function change_actiondist(){ 
var regrecptheader = document.feesreport.regreceiptheader_amount.value;	
if(parseInt(regrecptheader)=='' || parseInt(regrecptheader)==0 ){
document.feesreport.regreceiptheader_amountbase1.focus();
return;
} 

document.feesreport.submit();	
}

function getstatement(familyid){
var period=document.feesreport.period_id.value;
window.open("Rep_StatementofAccount.php?family_id="+familyid+"&class_id=&toclass_id=&period_id="+period+"&export=0");
}

function change_action3()
{
var srch=document.feesreport.search.value;
var period=document.feesreport.period_id.value;
window.open("search_family.php?search="+srch+"&period_id="+period,'_blank',"left=400,top=150 ,scrollbars=1,width=750,height=650");
}


function openlist()
{

var regreceiptheader_prestudid=document.feesreport.regreceiptheader_prestudid.value;
var familydt_id=document.feesreport.familydt_id.value;

window.open("Form_Receiptlists.php?regreceiptheader_prestudid="+regreceiptheader_prestudid+"&familydt_id="+familydt_id,'_blank',"left=400,top=150 ,scrollbars=1,width=800,height=650");
}



function submitenter(myfield,e){

var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;

if (keycode == 13)
   {
   	var period = document.feesreport.period_id.value;
	var srch=document.feesreport.search.value;
    window.open("search_family.php?search="+srch+"&period_id="+period,'_blank',"left=400,top=150 ,scrollbars=1,width=750,height=650");
  
   return false;
   }
else
   return true;
}


function settotal(student_id,obj,i,start){

var vname = 'amount'+i;
var j='j'+i;
var maxrows = document.getElementById(j).value;

document.getElementById(vname).value=0;
var xx = document.getElementById(vname).value;
var yy;

if(xx=='')
	xx=0;
	
for (x = start; x < maxrows; x++) { 
	y='fees'+student_id+'-'+x;
	//alert(y);
	y = document.getElementById(y).value;
	
	if(y=='')
		y=0;
    xx = parseFloat(xx) + parseFloat(y);
}
document.getElementById(vname).value=xx;

calculateTotal(document.getElementById('i').value);
}




function calculateall(){

var curr1 = document.getElementById('currency_code').value;
var amount1 = document.getElementById('regreceiptheader_amountbase1').value;

var curr2 = document.getElementById('currency_code2').value;
var amount2 = document.getElementById('regreceiptheader_amount2').value;


var curr3 = document.getElementById('check_currency_code').value;
var amount3 = document.getElementById('check_amount').value;


if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
				{ 
					document.getElementById('regreceiptheader_amount').value=parseInt(xmlhttp.responseText);
				}
		}
  }

xmlhttp.open("GET","Form_Receipt_Action.php?mainmode=calculateall&curr1="+curr1+"&amount1="+amount1+"&curr2="+curr2+"&amount2="+amount2+"&curr3="+curr3+"&amount3="+amount3,true);
xmlhttp.send();

}

function calculateall1(){

var curr1 = document.getElementById('currency_code').value;
var amount1 = document.getElementById('regreceiptheader_amountbase1').value;

var curr2 = document.getElementById('currency_code2').value;
var amount2 = document.getElementById('regreceiptheader_amount2').value;


var curr3 = document.getElementById('check_currency_code').value;
var amount3 = document.getElementById('check_amount').value;

var curr4 = document.getElementById('check_currency_code2').value;
var amount4 = document.getElementById('check_amount2').value;

if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
				{ 
					document.getElementById('regreceiptheader_amount').value=parseInt(xmlhttp.responseText);
				}
		}
  }

xmlhttp.open("GET","Form_Receipt_Action.php?mainmode=calculateall1&curr1="+curr1+"&amount1="+amount1+"&curr2="+curr2+"&amount2="+amount2+"&curr3="+curr3+"&amount3="+amount3+"&curr4="+curr4+"&amount4="+amount4,true);
xmlhttp.send();

}

function calculateTotal(limit){
	var x;
	var sum=0;
	//alert('hello');
	
	for(var i=0;i<limit;i++){
		x='amount'+i;
		if(document.getElementById(x).value=='')
			document.getElementById(x).value=0;
		sum=sum+parseFloat(document.getElementById(x).value);
	}
	//alert('sum:'+sum);
	document.feesreport.totalAmount.value=sum;
}
function set_period(){
	
    var per_id = document.feesreport.per_id.value;
	//alert (per_id);
	
    document.feesreport.period_id.value= per_id;
	//alert (document.feesreport.period_id.value);
	document.feesreport.submit();

}
function set_period1(){
	
    var per_id = document.feesreport.per_id.value;
	//alert (per_id);
	
    document.feesreport.period_id.value= per_id;
	//alert (document.feesreport.period_id.value);
	//document.feesreport.submit();

}
function set_type_fees(){
	
var type_id = document.feesreport.typ_fee.options[feesreport.typ_fee.selectedIndex].value;

document.feesreport.type_fees.value= type_id;
//alert('fees type'+document.feesreport.type_fees.value);
document.feesreport.submit();
}

function SubmitRecord(vactionmode,dist_receiptdt){
	var x=document.feesreport;
	var search= x.search.value;
	if(search=='' ){
		alert("No Parent Was Selected!");
		return;
	}
	
	
	if(dist_receiptdt == 1){ 
var familyid = document.feesreport.familyid.value; 
var ammtinput = document.feesreport.regreceiptheader_amount.value; 
var totamounttopay = document.feesreport.totalAmounttobepaid.value; 
	
	if(familyid == '' )
{
	alert("No Family Was Chosen!");
	return;
}
	if(parseInt(ammtinput) <= 0 || ammtinput == '' )
{
	alert("Amount is Empty!");
	document.feesreport.regreceiptheader_amountbase1.focus();
	return;
}
if( vactionmode == 'insert')
if(parseInt(totamounttopay) <= 0 || totamounttopay == '' ) {
		alert("Please Distribute The Amount First!");
	document.feesreport.regreceiptheader_amountbase1.focus();
	return;
	}
}

//var vtotalAmount = x.totalAmount.value;
if(dist_receiptdt == 2){
var pnumber=x.payment_number.value;

//var pnumber=document.getElementById("payment_number").value;
//alert('payment number'+paymentnumber);

 var pvalue='totalpayment'+pnumber;
 //alert('p:'+pvalue);
var payment=document.getElementById(pvalue).value;


 
//vtotalAmount = parseFloat(vtotalAmount.replace(/,/g,"") );
payment=parseFloat(payment.replace(/,/g,"") );
//alert('payment 1: '+payment);
var vregreceiptheader_amount = x.regreceiptheader_amount.value;

vregreceiptheader_amount = parseFloat(vregreceiptheader_amount.replace(",",""));
//alert('payment2: '+vregreceiptheader_amount);
if(payment!=vregreceiptheader_amount){
	alert('Amounts Differs.');
	return;
}
} 
/*else if( vregreceiptheader_amount - vtotalAmount  > 10 && dist_receiptdt == 1)	{

	alert('Amounts Differs.');
	return;
}*/


		
		if(document.getElementById('btnClear'))
			document.getElementById('btnClear').disabled=true;
	
		if(document.getElementById('btnSearch'))
			document.getElementById('btnSearch').disabled=true;
	
		if(document.getElementById('btnPrint'))
			document.getElementById('btnPrint').disabled=true;	
		
		x.mainmode.value=vactionmode;
		//alert('description'+x.description.value);
		
		x.action='Form_Receipt_Action.php';
		x.submit();

}
 function PrintReceipt(vid,perid){
	if(vid == '') {
		alert('Please Save the Receipt First!');
		return 0;
	} else window.open("Printable_Receipt.php?regreceiptheader_id="+vid+"&period_id="+perid);
} 


function ClearPage(str){
	var x=document.feesreport;
	
	if (confirm ( "Are you sure you want to Clear Page?"))
	{
		x.mainmode.value='';
		if(x.totalAmount)
			x.totalAmount.value='';
		x.familyid.value='';
		x.firstname.value='';
		x.familydt_id.value='';
		x.familyname.value='';
		x.regreceiptheader_id.value='';
		x.regreceiptheader_prestudid.value='';
		x.period_id.value='';
		x.currency_code2.value='';
		x.regreceiptheader_amount2.value='';
		x.check_date.value='';
		x.check_currency_code.value='';
		x.check_amount.value='';
		x.bank_name.value='';
		x.bank_branch.value='';
		x.check_no.value='';
		x.currency_code.value='';
		x.regreceiptheader_amount.value='';
		x.regreceiptheader_reference.value='';
		x.regreceiptheader_amountbase1.value='';
		if(str == 1){
			x.check_amount2.value='';
			x.checktype.value='1';
		}
		if(x.ledger_number) x.ledger_number.value='';
		if(x.ledger_number2) x.ledger_number2.value='';
		x.familycode1.value = '';
		x.regreceiptheader_date.value='';
		x.description.value='';
		x.action='Form_Receipt.php';
		x.submit();
	}	
}
function changevaluepaid(obj,indx){

if(obj.checked)
 //alert('pa:'+indx);
	document.getElementById(indx).value = 1;
else
	document.getElementById(indx).value = 0;
	document.feesreport.submit();
	
}

 function changedefered(obj,number){
		
		var old='oldvalue'+number;
		
		var payment=document.getElementById(old).value;
		
		payment=payment.replace(/\,/g,'');
		
		var newpayment=obj.value;
		newpayment=newpayment.replace(/\,/g,'');
		
		document.getElementById('amountremoved').value=parseFloat(payment)-parseFloat(newpayment);
		var oldv;
		var i;
		for(i=1;i<=9;i++){
		     oldv='oldvalue'+i;	
			 document.getElementById(oldv).value='';
			
	    }
		//alert('payment'+payment);
		document.getElementById('number').value=number;
		document.feesreport.mainmode.value='regenerate';
		//alert('amunt removed'+document.getElementById('amountremoved').value);
		document.feesreport.submit();

 }
 function setoldvalue(obj,number){
 var old='oldvalue'+number;
 
 //alert('old value'+document.getElementById(old).value);
 if(document.getElementById(old).value==''){
	document.getElementById(old).value=obj.value;
	//alert('old value'+document.getElementById(old).value);
 }
}
 function setchecktype(){
	 var x=document.feesreport;
	 var amount1 = document.getElementById("check_amount").value;
	 var amount2 = document.getElementById("check_amount2").value;
	 if(document.getElementById("checktype").value==1){  
		 if(amount1 != '' || amount2 == '' ){
			document.getElementById("bank_name").value = document.getElementById("receipt_checkdebit").value; 
		 }
		  if( amount2 != '' && amount1 == ''){
			 document.getElementById("bank_name").value = document.getElementById("receipt_checkdebit2").value; 
		 }
	 } else  if(document.getElementById("checktype").value==2){
		 if(amount1 != '' || amount2 == '' ){
			document.getElementById("bank_name").value = document.getElementById("receipt_bankdebit").value;  
		 }
		  if( amount2 != '' && amount1 == ''){
			 document.getElementById("bank_name").value = document.getElementById("receipt_bankdebit2").value; 
		 }
	 }
	// document.feesreport.submit();
 }
 
 function setAccount1(){
	 var amount1 = document.getElementById("check_amount").value; 
	  if(amount1 != ''){
		 if(document.getElementById("checktype").value == 1)
			document.getElementById("bank_name").value = document.getElementById("receipt_checkdebit").value;
		else if(document.getElementById("checktype").value == 2)
			document.getElementById("bank_name").value = document.getElementById("receipt_bankdebit").value;
		document.getElementById("check_amount2").value = '';
	 } 
	
 }
 
 function setAccount2(){
	 var amount2 = document.getElementById("check_amount2").value; 
	 
	 if(amount2 != ''){ 
		  if(document.getElementById("checktype").value == 1)
			document.getElementById("bank_name").value = document.getElementById("receipt_checkdebit2").value;
		else if(document.getElementById("checktype").value == 2)
			document.getElementById("bank_name").value = document.getElementById("receipt_bankdebit2").value;
		document.getElementById("check_amount").value = '';
	 }
 }
</script>


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

$(document).ready(function(){
  $("#search").autocomplete("autocomplete.php?period_id=$period_id", {
        selectFirst: true
  });
 
 });

</script>
</head>
<body >
<form name='feesreport' method='post'>

HERE;
echo'<table cellpadding="0" cellspacing="0" border="0"  align="center" class = "layout-width" >';

include_once("header.php");
print <<<HERE

<tr>
  <td  height="26"  valign="top" id='content-top'>
	<table class = 'layout-width' border="0" cellpadding="0" cellspacing="0">
	<tr  height='26'>
      <td width="38" height="26">&nbsp;</td>
      <td width="300" valign="middle" height="26"><span class="title">Receipt 

HERE;

print <<<HERE
	  
	  </span></td><td class='message' valign="middle">&nbsp; $message</td>
	</tr></table></td></tr>
HERE;
print <<<HERE

<tr>
  <td  height="25"  valign="top" id='content-top2'>
	<table class = 'layout-width' border="0" cellpadding="0" cellspacing="0">
	<tr >
      <td width="38"  height="25">&nbsp;</td>
	<td valign='middle' height="25">
HERE;
echo"   </td></tr>";
echo"	</table></td></tr>";


echo"<input type='hidden' name='type_fees' id='type_fees'  value='$type_fees' >";
echo"<input type='hidden' name='mainmode' id='mainmode'  value='$mainmode' >";
echo"<input type='hidden' name='regreceiptheader_id' id='regreceiptheader_id'  value='$regreceiptheader_id' >";
echo"<input type='hidden' name='oldvalue1' id='oldvalue1'  value='$oldvalue1' >";
echo"<input type='hidden' name='oldvalue2' id='oldvalue2'  value='$oldvalue2' >";
echo"<input type='hidden' name='oldvalue3' id='oldvalue3'  value='$oldvalue3' >";
echo"<input type='hidden' name='oldvalue4' id='oldvalue4'  value='$oldvalue4' >";
echo"<input type='hidden' name='oldvalue5' id='oldvalue5'  value='$oldvalue5' >";
echo"<input type='hidden' name='oldvalue6' id='oldvalue6'  value='$oldvalue6' >";
echo"<input type='hidden' name='oldvalue7' id='oldvalue7'  value='$oldvalue7' >";
echo"<input type='hidden' name='oldvalue8' id='oldvalue8'  value='$oldvalue8' >";
echo"<input type='hidden' name='oldvalue9' id='oldvalue9'  value='$oldvalue9' >";
echo"<input type='hidden' name='amountremoved' id='amountremoved'  value='$amountremoved' >";
echo"<input type='hidden' name='number' id='number'  value='$number' >";
echo"<input type='hidden' name='familycode1' id='familycode1'  value=".trim($familycode1)." >";
echo"<input type='hidden' name='AdditionalAmount_Account' id='AdditionalAmount_Account' value='$AdditionalAmount_Account'>";
echo"<input type='hidden' name='receipt_checkdebit' id='receipt_checkdebit'  value='$receipt_checkdebit' >";
echo"<input type='hidden' name='receipt_checkdebit2' id='receipt_checkdebit2'  value='$receipt_checkdebit2' >";
echo"<input type='hidden' name='receipt_bankdebit' id='receipt_bankdebit'  value='$receipt_bankdebit' >";
echo"<input type='hidden' name='receipt_bankdebit2' id='receipt_bankdebit2'  value='$receipt_bankdebit2' >";

echo"<input type='hidden' name='familydt_id' id='familydt_id'  value='$familydt_id' >";


if($mainmode!='regenerate'){
$oldvalue1=$oldvalue2=$oldvalue3=$oldvalue4=$oldvalue5=$oldvalue6=$oldvalue7=$oldvalue8=$oldvalue9='';
$amountremoved='';
//echo "mode now:".$mainmode;
}

$totalAmount =0;

if($mainmode=='edit' and $regreceiptheader_id!=''){


$query="SELECT regreceiptheader_id, period_id, familydt_id, regreceiptheader_amount, currency_code,regreceiptheader_prestudid,date_format(regreceiptheader_date,'%d/%m/%Y') 
,currency_code2, regreceiptheader_amount2, date_format(check_date,'%d/%m/%Y') , check_currency_code, check_amount, bank_name, bank_branch, check_no, regreceiptheader_reference,
regreceiptheader_description,ledger_number,ledger_number2,bank_reference,payment_number, check_amount2, check_currency_code2,
checktype, receipttotal_amount, journal_id
FROM regreceiptheader where regreceiptheader_id = $regreceiptheader_id"; 
 

//echo $query;

$result=mysql_query($query,$connection) or die(mysql_error());
$row=mysql_fetch_row($result);
 $period_id=$row[1];
if($familydt_id == '') $familydt_id=$row[2]; 
$totalAmount=$row[3];
if($regreceiptheader_amountbase1=='')
	$regreceiptheader_amountbase1=$row[3];
$currency_code=$row[4];
$regreceiptheader_prestudid=$row[5];
$regreceiptheader_date=$row[6];

$currency_code2=$row[7];
if($regreceiptheader_amount2=='')
$regreceiptheader_amount2=$row[8];
$check_date=$row[9];
$check_currency_code=$row[10];
$check_amount=$row[11];
$bank_name=$row[12];
$bank_branch=$row[13];
$check_no=$row[14];
$per_id=$row[1];
$regreceiptheader_reference=$row[15];
$description=$row[16];
$ledger_number=$row[17];
$ledger_number2=$row[18];
$bank_reference=$row[19];
$payment_number=$row[20];
$vamount1 = 0;
$vamount2 = 0;
$vamount3 = 0;

$check_amount2 = $row[21]; 
$check_currency_code2 = $row[22];
$checktype = $row[23];
$journalid=$row[25];

if($journalid != '' && $dist_receiptdt==1) $disablesave = 'disabled';
else $disablesave = '';
$today=date('Y-m-d'); 
if($dist_receiptdt == 1)
$regreceiptheader_amount = $row[24];
else {
if($currency_code!='' && $regreceiptheader_amountbase1!='')
		$vamount1 = ConvertCurrency($currency_code, $base1, $today, $regreceiptheader_amountbase1, $connection,$schema);
	
	
	if($currency_code2!='' && $regreceiptheader_amount2!='')
		$vamount2 = ConvertCurrency($currency_code2, $base1, $today, $regreceiptheader_amount2, $connection,$schema);

	if($check_currency_code!='' && $check_amount!='')
		$vamount3 = ConvertCurrency($check_currency_code, $base1, $today, $check_amount, $connection,$schema);

	
//echo $check_currency_code;
$regreceiptheader_amount= $vamount1 + $vamount2 + $vamount3;
//echo $regreceiptheader_amount;
}
}
if($period_id=='')
	$period_id=get_defaultperiod($connection);

if($familycode1 != '')
$query="SELECT distinct familydt_id,family_id,familydt_FirstName,familydt_LastName FROM familiesdt group by family_id"; 
else 
$query="SELECT distinct prestud_familyid,prestud_fathername, prestud_familyname FROM prestudent group by prestud_familyid"; 	
$result=mysql_query($query,$connection) or die(mysql_error());
//echo $query;

if($period_id=='')
	$period_id=get_defaultperiod($connection);
	//$period_id=get_nextperiod($connection);

$result_period = get_allperiod($connection);




if($dist_receiptdt == 1){ 
	
$totalamountleft = 0;	 
 $querypay = "select sum(FeeDeferredPayment_amount)
			- sum(if(ifnull(FeeDeferredPayment_discountamount,0) = 0,FeeDeferredPayment_amount*
			ifnull(FeeDeferredPayment_discountper,0)/100 ,FeeDeferredPayment_discountamount))
			- sum(if(ifnull(FeeDeferredPayment_finanaidamount,0) = 0,FeeDeferredPayment_amount*
			ifnull(FeeDeferredPayment_finanaidper,0)/100 ,FeeDeferredPayment_finanaidamount))
			from feesdeferredpayments
			left join fees on fees.fee_id = feesdeferredpayments.fee_id
			where fees.period_id=$period_id
			and if('$familycode1' != '',family_id = (select family_id from familiesdt where familydt_id = $familydt_id), family_id=$familydt_id )";
 $respay = mysql_query($querypay,$connection);			
 $rwpay = mysql_fetch_row($respay);
 //echo $querypay;
 $querypaid = "select sum(regreceiptdt_amount) from regreceiptdt
				left join regreceipt on regreceipt.regreceipt_id = regreceiptdt.regreceipt_id
				left join regreceiptheader on regreceiptheader.regreceiptheader_id = regreceipt.regreceiptheader_id
				where regreceiptheader.period_id=$period_id and familydt_id = $familydt_id";
 $respaid = mysql_query($querypaid,$connection);
 $rwpaid = mysql_fetch_row($respaid);
 $totalamountleft = $rwpay[0] - $rwpaid[0]; 
 echo "<input type='hidden' name='totalamountleft' value='$totalamountleft'>";
 if($bank_name == '' )$bank_name=$receipt_checkdebit;

 }

echo"<tr ><input type='hidden' name='regreceiptheader_prestudid' id='regreceiptheader_prestudid'  value='$regreceiptheader_prestudid' ><td id='content-body'>
	<table border='0' 	align='center'   class='tablecontent' cellpadding='0' cellspacing='0' >
	<col width=60><col width=120><col width=60><col width=120><col width=300>
	<tr><td colspan=4><table width=950 border=0 class='mt'>
	<tr height=30>
	  <td ><font size=1><b>Search:&nbsp&nbsp&nbsp&nbsp</b></td>
	  <td align=left>";
 
 
 if($regreceiptheader_prestudid==''){
		if($familycode1 != '')
		$query="SELECT distinct family_id,familydt_FirstName,familydt_LastName FROM familiesdt where familydt_id='".$familydt_id."'"; 
		else if($familycode1 == '')
		$query="SELECT distinct prestud_familyid,prestud_fathername,prestud_familyname FROM prestudent where prestud_familyid='".$familydt_id."'"; 	
 }else
		$query="SELECT distinct prestud_id,prestud_firstname,prestud_familyname FROM prestudent where prestud_id='".$regreceiptheader_prestudid."'"; 
		//	echo $query;
			$result=mysql_query($query,$connection) or die(mysql_error());
			 $res = mysql_fetch_row($result);
			 $familyid=$res[0];
			 $firstname=$res[1];
			 $familyname=$res[2];
		
		if($familycode1 != '')
		$query="SELECT family_code, family_description FROM families where family_id='".$familyid."'"; 
		else 
		$query="SELECT distinct null, prestud_familyname FROM prestudent where prestud_familyid='".$familyid."'"; 	
			//echo $query;
			$result=mysql_query($query,$connection) or die(mysql_error());
			 $res = mysql_fetch_row($result);
			 $familycode = $res[0];
			 $family_description = $res[1];
			 
		//echo $query;
		//if($regreceiptheader_reference=='')
		echo"<input type='text' name='search' id='search' style='border-radius:4px;width:212px;font-size:12px' value='$familydt_id' onKeyPress='return submitenter(this,event)' $disablebutton>";
		
		echo"</td><td>";
		if($regreceiptheader_reference=='' || $dist_receiptdt == 0)
		echo"<button type='button'  id='btnSearch' name='btnSearch' onclick='change_action3()'  title='".$ButtonArray[4]['ButtonTitle']."'><span><span>".$ButtonArray[4]['ButtonLabel']."</span></span></button>";
		
        echo"</td>";
		
		echo"<td style='border-top' colspan=2>";
		echo"<button type='button'  id='btnRec' name='btnRec' onclick='openlist()'  title='".$ButtonArray[4]['ButtonTitle']."'><span><span>Receipts</span></span></button>";
		
		
		
		
	

echo"<button type='button' id='btnClear' name='btnClear' onclick='ClearPage($dist_receiptdt); return false;' title='".$ButtonArray[3]['ButtonTitle']."'><span><span>".$ButtonArray[3]['ButtonLabel']."</span></span></button>";

//echo "current mode".$mainmode;
if (($Form_Insert == 1 && $mainmode=='insert') ||($dist_receiptdt==2)){
		print<<<HERE
		<button type='button' id='btnPost' name='btnPost' onclick="SubmitRecord('$mainmode','$dist_receiptdt'); return false;" 
HERE;

echo"
		title='".$ButtonArray[1]['ButtonTitle']."'><span><span>".$ButtonArray[1]['ButtonLabel']."</span></span></button>";
}
if ( ($Form_Edit == 1 && $mainmode=='edit')||($dist_receiptdt==2)){
		print<<<HERE
		<button type='button' id='btnPost' name='btnPost' onclick="SubmitRecord('$mainmode','$dist_receiptdt'); return false;" 
HERE;

echo"
		title='".$ButtonArray[1]['ButtonTitle']."'><span><span>".$ButtonArray[1]['ButtonLabel']."</span></span></button>";
}
if($dist_receiptdt!=2)
echo"<button type='button'  id='btnPrint' name='btnPrint' onclick=\"PrintReceipt('$regreceiptheader_id','$period_id')\"  ><span><span>Print</span></span></button>";	
if($dist_receiptdt == 1 && $regreceiptheader_prestudid == '')
echo"<button type='button'  id='btnGenerate' name='btnGenerate' onclick='change_actiondist()'  ><span><span>Distribute Fees</span></span></button>";		
else  if($dist_receiptdt == 2)
echo"<button type='button'  id='btnGenerate' name='btnGenerate' onclick='change_action4($ii)'  $disabledistr><span><span>Distribute Fees</span></span></button>";		
echo"<button type='button'  id='btnGenerate' name='btnGenerate' onclick='getstatement($familyid)'  ><span><span>Statement</span></span></button>";		
echo"<br><font color=red size=1><b><i>&nbsp;&nbsp;&nbsp;$firstname $familyname ($familycode) $family_description</b><i></font></td>";
		echo"</tr>";
		
		echo"<input type='text' hidden name='familyid' id='familyid' style='width:200px;font-size:12px' value='$familyid' >";	
		echo"<input type='text'  hidden name='firstname' value='$firstname' style='width:200px;font-size:12px'>";
	    echo"<input type='text'  hidden name='familyname' value='$familyname' style='width:200px;font-size:12px'>";
$today=date('d/m/Y');		
if($regreceiptheader_date=='')
	$regreceiptheader_date = $today;
if($check_date=='')
	$check_date = $today;
													
 echo"<tr height=30><td><b><font size=1>Reference</b></td><td colspan=1>
 <input type='text' name='regreceiptheader_reference' id='regreceiptheader_reference' value='$regreceiptheader_reference' style='border-radius:4px;width:212px;font-size:12px' $readonlyactive></td>
 <td><b><font size=1>Date</b></td>
 <td><input type='text' name='regreceiptheader_date' id='regreceiptheader_date' value='$regreceiptheader_date' style='border-radius:4px;width:162px;font-size:12px'>";
 
 echo"<a href='#' onClick=\"displayCalendar(document.feesreport.regreceiptheader_date,'dd/mm/yyyy',this); return false; \" name='anchor1' id='anchor1'><image src='./img/cal.gif' border=0 align=bottom></image></a>";
 // adjusted by tony $disactive
 if($mainmode=='edit' and $regreceiptheader_id!='')
	 echo"</td>
 	<td><font color=#000000><b><font size=1>Period:</b>&nbsp;<select name='per_id' onchange='set_period1()' style='border-radius:4px; '$disactive >";
else	 
 echo"</td>
 	<td><font color=#000000><b><font size=1>Period:</b>&nbsp;<select name='per_id' onchange='set_period()' style='border-radius:4px; '$disactive >";
		//echo"<option value=''></option>";
		while ($rowwp=mysql_fetch_row($result_period))
			{
			if ($period_id==$rowwp[0])
			echo "<option value='$rowwp[0]' selected>$rowwp[1]</option>";
			else
			echo "<option value='$rowwp[0]'>$rowwp[1]</option>";
			}
			echo"</select>";
 echo"</td>
 </tr>";

	echo"<input type='hidden' name='period_id' id='period_id'  value='$period_id' >";
	
	    //echo"<input type='button'  id='btnSearch' name='btnSearch' onclick='change_action3() title=title='".$ButtonArray[4]['ButtonTitle']."'><span><span>".$ButtonArray[4]['ButtonLabel']."</span></span>";
       if($dist_receiptdt == 1) $calfunction = 'calculateall1()';
		else $calfunction = 'calculateall()';
		

			$result_cur=get_currency($connection);
			
			echo"<tr height=30><td><b>";
			if($dist_receiptdt==2)
				echo"<font size=1>Amounts&nbsp;</td><td><select name='currency_code'  id='currency_code' onchange='$calfunction' style='border-radius:4px;font-size:11px'>";
			else
				echo"<font size=1>Cash Amounts&nbsp;</td><td><select name='currency_code'  id='currency_code' onchange='$calfunction' style='border-radius:4px;font-size:11px' $disactive>";
			echo"<option value=''></option>";
				while ($rows=mysql_fetch_row($result_cur))
				{
				if ($currency_code==$rows[0] or ($rows[0]==$base1))
					echo "<option value='$rows[0]' selected>$rows[0] </option>";
				else
					echo "<option value='$rows[0]'>$rows[0] </option>";
				}
			echo"</select>&nbsp;<input type='text' name='regreceiptheader_amountbase1' id='regreceiptheader_amountbase1' style='border-radius:4px;' value='$regreceiptheader_amountbase1'  onblur='$calfunction' $readonlyactive>";		
		echo"</td>";
		
	if($ledger_number=='')	
	$ledger_number = $receipt_cashdebit;
	if($ledger_number2=='')
		$ledger_number2 = $receipt_cashdebit2;
	/// adjust by tony line 922 $readonlyactive
	
	if($dist_receiptdt==2)	{
		echo"<td><b><font size=1>Bank ref.</b></td>	<td ><input type='text' name='bank_reference' value='$bank_reference' maxlength='10' size='7'></td>";
		echo"<td><b><font size=1>Payment number</b>&nbsp;&nbsp;&nbsp;<input type='text' name='payment_number' value='$payment_number' maxlength='10' size='1'></td>";
	}
	else	
		echo"<td><b><font size=1>Ledger No</b></td>	<td ><input type='text' name='ledger_number' value='$ledger_number' maxlength='10' size='7' >&nbsp;
			<input type='text' name='ledger_name' value='".htmlspecialchars($ledger_name, ENT_QUOTES)."' readonly size='20'>

			<input type='button' name='ledgerbut' onMouseOver=\"style.cursor='hand'\"   value='...' onclick='showlistledgers(1);' $disactive></td>";
	echo"</tr>";
echo"<tr>";
       /*if($dist_receiptdt==2)
				echo"<td>&nbsp;</td><td>&nbsp;</td>";
	else{*/
		$result_cur=get_currency($connection);
			
			
			echo"<td></td><td colspan=1><select name='currency_code2' id='currency_code2'   onchange='calculateall()'  style='border-radius:4px;font-size:11px' $disactive>";
			echo"<option value=''></option>";
				while ($rows=mysql_fetch_row($result_cur))
				{
				if ($currency_code2==$rows[0] or ($rows[0]==$base2))
					echo "<option value='$rows[0]' selected>$rows[0] </option>";
				else
					echo "<option value='$rows[0]'>$rows[0] </option>";
				}
			echo"</select>&nbsp;<input type='text' name='regreceiptheader_amount2' id='regreceiptheader_amount2' value='$regreceiptheader_amount2' style='border-radius:4px;'  onblur='$calfunction' $readonlyactive>
			
			</td>";	
		//}
			//echo $dist_receiptdt;
			
	//// adjust by tony line 953   $readonlyactive
	if($dist_receiptdt==2)
			echo"<td>&nbsp;</td><td>&nbsp;</td>";
	else
			echo"<td><b><font size=1>Ledger No</b></td>	<td ><input type='text' name='ledger_number2' value='$ledger_number2' maxlength='10' size='7'>&nbsp;
			<input type='text' name='ledger_name2' value='".htmlspecialchars($ledger_name2, ENT_QUOTES)."' readonly size='20'>
					<input type='button' name='ledgerbut2' onMouseOver=\"style.cursor='hand'\"   value='...' onclick='showlistledgers(2);' $disactive></td>
		";
		
			
		echo"<td> <b><i><font size=1>Total Amount $base1 </i><input type='text' name='regreceiptheader_amount' id='regreceiptheader_amount' value='".$regreceiptheader_amount."' style='border-radius:4px;font-size:13px;font-weight:bold;font-style:italic;border:0px;text-align:right;width:90' readonly></td>";
		echo"</tr>";
		
		// adjusted by tony $disactive
		echo"<tr><td  height=30><font size=1><b>Descritpion</b></td><td colspan='4'><input type='text' style='border-radius:4px;width:830px;font-size:12px'  name='description' value='$description' ></td></tr>";
		if($dist_receiptdt!=2){
			if($dist_receiptdt == 1) $chkname = "Advance";
			else $chkname = "Cheque";
			echo"<tr><td colspan=5>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href='#' onclick='toggle_visibility(\"foo\");'><font size=1><b>$chkname</a><b></font></td></tr>";
		}
		echo"</table></td></tr>";
		
		
		$result_cur=get_currency($connection);
			if($dist_receiptdt==1) { $chckfuntion1 = 'setAccount1()'; $chckfuntion2 = 'setAccount2()'; }
			else { $chckfuntion1 = ''; $chckfuntion2 = ''; }
			if($check_amount!='' and $check_date!='')
				$hidd = '';
				else
				$hidd = ' hidden ';
				
			echo"<tr height=10><td colspan=5>
			
			<div id='foo' $hidd>
			<table><tr><td>";			
			

			echo"<font  size=1 >Amount</td><td><select name='check_currency_code' id='check_currency_code'   onchange='calculateall()'  style='font-size:11px' $disactive>";
			echo"<option value=''></option>";
				while ($rows=mysql_fetch_row($result_cur))
				{
				if ($check_currency_code==$rows[0]  or ($rows[0]==$base1 and $check_currency_code==''))
					echo "<option value='$rows[0]' selected>$rows[0] </option>";
				else
					echo "<option value='$rows[0]'>$rows[0] </option>";
				}
			echo"</select>&nbsp;<input type='text' name='check_amount' id='check_amount' value='$check_amount' style='font-size:11px;'  onblur='$calfunction;$chckfuntion1;' $readonlyactive></td>";		
		
		
		echo"<td align='center'><font  size=1 color='#000000'>Date</td><td align=left><input type=text name='check_date' style='font-size:11px;width:110'  value='$check_date' readonly>";
		echo"      <a href='#' onClick=\"displayCalendar(document.feesreport.check_date,'dd/mm/yyyy',this); return false; \" name='anchor1' id='anchor1'><image src='./img/cal.gif' border=0 align=bottom></image></a>";
		echo"</td></tr>";
		if($dist_receiptdt == 1){
			$result_cur=get_currency($connection);
		echo "<tr><td>";
		echo"<font  size=1 ></td><td><select name='check_currency_code2' id='check_currency_code2'   onchange='calculateall()'  style='font-size:11px' $disactive>";
			echo"<option value=''></option>";
				while ($rows=mysql_fetch_row($result_cur))
				{
				if ($check_currency_code2==$rows[0]  or ($rows[0]==$base2 and $check_currency_code2==''))
					echo "<option value='$rows[0]' selected>$rows[0] </option>";
				else
					echo "<option value='$rows[0]'>$rows[0] </option>";
				}
			echo"</select>&nbsp;<input type='text' name='check_amount2' id='check_amount2' value='$check_amount2' style='font-size:11px;'  onblur='$calfunction;$chckfuntion2;' $readonlyactive></td>";		
		echo "</tr>";
		}
		echo"<tr><td align='left'><font size=1 color='#000000'>Check No</td><td colspan=1 align=left><input type=text name='check_no' style='font-size:11px;width:310'  value='$check_no' ></td>";
		
		//tony  $disactive
		if($dist_receiptdt==1){
			echo "<td></td><td><select name='checktype' id='checktype' onchange='setchecktype();' style='font-size:11px;width:90' >";
			echo "<option value='1' ";
			if($checktype == 1) echo " selected ";
			echo " >Check</option>";
			echo "<option value='2' "; 
			if($checktype == 2) echo " selected ";
			echo " >Bank</option>";
			echo "</select></td>";
		}
		echo "</tr>";
		
		if($dist_receiptdt==1)
		echo"<tr><td align='right'><font  size=1 color='#000000'>Bank Name</td><td colspan=1 align=left><input type=text name='bank_branch' style='font-size:11px;width:310'  value='$bank_branch' ></td></tr>";
		// adjust by tony line 1032 $readonlyactive
		
		if($dist_receiptdt!=2){	
			echo"<tr height=25><td><b><font size=1>Ledger No</b></td>	<td ><input type='text' name='bank_name' id='bank_name' value='$bank_name' maxlength='10' size='7' >&nbsp;
			<input type=text name='ledger_name' style='font-size:11px;width:310'  value='$ledger_name' readonly>
			<input type='button' name='ledgerbut' onMouseOver=\"style.cursor='hand'\"   value='...' onclick='showlistledgers(3);' $disactive></td></tr>";
		}
		if($dist_receiptdt!=1)
		echo"<tr><td align='right'><font  size=1 color='#000000'>Bank Branch</td><td colspan=1 align=left><input type=text name='bank_branch' style='font-size:11px;width:310'  value='$bank_branch' ></td></tr>";
	
		
		echo"</table></div></td></tr>";
		
		if($dist_receiptdt == 1){ 
		echo"<tr><td>";
		$query_defaultper = "select period_id from periods where period_default=1;";
		$res_defaultper = mysql_query($query_defaultper,$connection);
		$rw_defaultper = mysql_fetch_row($res_defaultper);
		if($period_id != $rw_defaultper[0]){
			$regOnly = 1;
			$now_period = $rw_defaultper[0];
		} else $regOnly = 0; 
		echo"<table border=0 class='mt'	align='center'   style='width:1100;font-size:10px'  cellpadding='0' cellspacing='0' >";
		echo"<col width=100>";
		echo"<col width=100>";
		echo"<col width=100>";
		echo"<col width=100>";
		echo"<col width=100>";
		echo"<col width=100>";
		echo"<col width=100>";
		echo"<col width=300>";
		echo"<tr><td colspan=6><table>";
		$perd_default = get_defaultperiod($connection);
		 if($regOnly ==0){
		if($familycode1 != '')
		$query="select Upper(Student_FirstName),Class_code,student_code,student_id,null,null,students.class_id 
						from students inner join classes on students.class_id=classes.class_id 
				where (familyDt_idfather='".$familydt_id."' or familyDt_idmother='".$familydt_id."' )
				 and if($period_id = $perd_default, 1=1,studentstatus_id=4) and 
				 ((period_id = $period_id or nextperiod_id=$period_id ) 
				  )
				and if($period_id = $perd_default, 1=1,class_last != 1)";
		 else $query="select Upper(prestud_firstname),Class_code,null,prestud_id,null,null,prestud_class 
						from prestudent inner join classes on prestud_class=classes.class_id 
				where prestud_familyid='".$familydt_id."' 
				 and prestud_decision='a' and prestud_period = $period_id ";
		 }
		else if($regOnly ==1)	{  
		if($familycode1 != '')		
		$query="select Upper(Student_FirstName),Class_code,student_code,student_id,null,null,students.class_id 
						from students inner join classes on students.class_id=classes.class_id 
				where (familyDt_idfather='".$familydt_id."' or familyDt_idmother='".$familydt_id."' )
				 and if($period_id = $perd_default, 1=1,studentstatus_id=4) 
				and ((period_id = $now_period or nextperiod_id=$now_period)or if($period_id = $perd_default, 1=1,nextperiod_id=$period_id))
				and if($period_id = $perd_default, 1=1,class_last != 1)	 ";
		 else $query="select Upper(prestud_firstname),Class_code,null,prestud_id,null,null,prestud_class 
						from prestudent inner join classes on prestud_class=classes.class_id 
				where prestud_familyid='".$familydt_id."' 
				 and prestud_decision='a' and prestud_period = $period_id ";
		}			
			//echo $query;
 

				$result=mysql_query($query,$connection);
				$numstudent=mysql_num_rows($result);
				
		
		$ii=0;	
		$k=0;	
		$feesname='-1';
		$allfeesselected='-1';
		while ($res=mysql_fetch_row($result))	{
					echo"<tr>"; 
					echo"<td  style='border-top:0px;border-left:0px;border-right:0px;border-bottom:0px'> <table border=0><tr><td colspan=2 style='border-top:0px;border-left:0px;border-right:0px;border-bottom:0px'><i><u><font color=red>$res[0]</font></i></u></td></tr>";
					if($familycode1 != ''){
					if($regOnly ==1)
					$query="SELECT FeesTemplatename_id,FeesTemplatename_name,null,null,FeesTemplatename_name,transportation_included 
									from feestemplatenames 
									where transportation_included = 1 or  transportation_included = 6 or  transportation_included = 3
									order by FeesTemplatename_name";
					else $query="SELECT FeesTemplatename_id,FeesTemplatename_name,null,null,FeesTemplatename_name,transportation_included 
									from feestemplatenames 
									where transportation_included <> 2 and transportation_included <> 1
									order by FeesTemplatename_name";				
					} else 
					$query="SELECT FeesTemplatename_id,FeesTemplatename_name,null,null,FeesTemplatename_name,transportation_included 
								from feestemplatenames 
								where feestemplatename_prestud
								order by FeesTemplatename_name";
					 //echo $query;
					$resultfees=mysql_query($query,$connection) or die(mysql_error());
					$numstudent1=mysql_num_rows($resultfees);
					
					$feesname='feesname'.$k;
					$$feesname='-1';
					echo"<tr>";
					$kk=0;
					while( $resfees = mysql_fetch_row($resultfees))
						{
							
							$hasDue = 0;		
							
							if($kk%2==0)
								$bgcolor='#C8C8C8';
								else
								$bgcolor='#E8E8E8';
								
							
							$xx='name'.$ii;
							if($$xx=='1')
								$chk=' checked ';
								else $chk='';
								
							if($hasDue>0){	
								$chk=' checked ';
								$stat=' disabled ';
								$$xx=1;
								} else $stat = ''; 
							if($resfees[5] == 3){
							if($familycode1 != '')
							$querynewstd = "select * from students where student_id=$res[3] and nextperiod_id = period_id
							and period_id=$period_id and if($period_id = $perd_default, 1=1,studentstatus_id=4) "; 
							else 
							$querynewstd = "select * from prestudent 
								where prestud_id =$res[3] and prestud_period=$period_id and prestud_decision='a'";
							//echo $querynewstd;
							$resnewstd = mysql_query($querynewstd,$connection); 
							$rwnewstd = mysql_fetch_row($resnewstd);
							if($rwnewstd[0] == '') {$stat = ' disabled ';$chk='';$$xx=0;}
							else $stat = '';
							}
							
							if($resfees[5] == 6 ){
							$querybus = "select 1 from feestemplatenames
										where transportation_included=6
										and exists (select student_transportation from students where student_id=$res[3])
										and 1 not in (select 1 from regreceiptdt
										left join regreceipt on regreceipt.regreceipt_id=regreceiptdt.regreceipt_id
										left join regreceiptheader on regreceipt.regreceiptheader_id=regreceiptheader.regreceiptheader_id
										where student_id = $res[3]	and familydt_id = $familydt_id
										and regreceiptheader.period_id= $period_id And tuitionfees_id =$resfees[0])"; 
							$resbus = mysql_query($querybus,$connection);	
							$rwbus = mysql_fetch_row($resbus);
								if($rwbus == ''){
								$stat=' disabled ';
									$chk=' ';
									$$xx=0;
								}	
							}			
							$remainingamounts =  calculate_remaining($resfees[0],$res[6],$res[3],$period_id,$connection);
							//echo $remainingamounts;
							$perd_default = get_defaultperiod($connection);
							if($perd_default == $period_id )	
							if($remainingamounts<=0)	{	
									$stat=' disabled ';
									$chk=' ';
									$$xx=0;
								} 
							if($perd_default != $period_id){		
							$recheaderdates = explode('/', $regreceiptheader_date);
							$recheaderdate = $recheaderdates[2]."-".$recheaderdates[1]."-".$recheaderdates[0];		
							$querydt=" select FeeTemplate_amount, feespreamount
										from feestemplatestudentdt,feestemplate
										where class_id= ".$res[6]."
										and feestemplatestudentdt.FeeTemplate_id = feestemplate.FeesTemplate_id
										and (FeesTemplate_startdate <= '$recheaderdate'	and ifnull(FeesTemplate_enddate,'$recheaderdate') >= '$recheaderdate')
										and FeeTemplateDt_name = $resfees[0]";
							//echo $querydt."<br>";			
							$resultdt=mysql_query($querydt,$connection) or die(mysql_error());
							$resamount = mysql_fetch_row($resultdt);
							 if(($resamount[0] == 0 && $resamount[0] == '') && ($resamount[1] == 0 && $resamount[1] == '') )	{	
									$stat=' disabled ';
									$chk=' ';
									$$xx=0;
									}
							if($resamount[0] != 0 && $resamount[0] != '')	{
								$remainingamounts =  calculate_remaining($resfees[0],$res[6],$res[3],$period_id,$connection);
							if($remainingamounts<=0)	{	
									$stat=' disabled ';
									$chk=' ';
									$$xx=0;
									} 
							}	
							if($resamount[1] != 0 && $resamount[1] != '')	{							
							$querybus = "select 1 from feestemplatenames
										where transportation_included=6
										and exists (select student_transportation from students where student_id=$res[3])
										and 1 not in (select 1 from regreceiptdt
										left join regreceipt on regreceipt.regreceipt_id=regreceiptdt.regreceipt_id
										left join regreceiptheader on regreceipt.regreceiptheader_id=regreceiptheader.regreceiptheader_id
										where student_id = $res[3]	and familydt_id = $familydt_id
										and regreceiptheader.period_id= $period_id And tuitionfees_id in (
											select t.feestemplatename_id from feestemplatenames as t 
											where t.transportation_included=6 ))";
							$resbus = mysql_query($querybus,$connection);	
							$rwbus = mysql_fetch_row($resbus);
							if($rwbus == ''){
								$stat=' disabled ';
									$chk=' ';
									$$xx=0;
							}							

							}
							}
							echo"<td bgcolor=$bgcolor align=left><input type='checkbox'  onMouseOver=\"style.cursor='hand'\"  name='chk".$xx."' id='chk".$xx."' 
									$stat  $chk onclick=\"changevalue(this,'".$xx."')\">
							<input type='hidden' name='".$xx."' id='".$xx."' value='".$$xx."' >
							</td>";
							echo"<td  bgcolor=$bgcolor width=130 align=left>".$resfees[1]."</td>";
							
							
						if($$xx=='1')	{
						$$feesname=$$feesname.','.$resfees[0];	
										}
						$ii=$ii+1;
						$kk+=1;
						}
					echo"</tr>";
					echo "</table></td></tr>";	
					echo"<input type='hidden' name='feesname$k' id='feesname$k' value='".$$feesname."'>";
									$querydt="select (select sum(feedeferredpayment_amount
												- if(ifnull(FeeDeferredPayment_discountamount,0)=0,feedeferredpayment_amount*ifnull(FeeDeferredPayment_discountper,0)/100,FeeDeferredPayment_discountamount)
												- if(ifnull(FeeDeferredPayment_finanaidamount,0)=0,feedeferredpayment_amount*ifnull(FeeDeferredPayment_finanaidper,0)/100,FeeDeferredPayment_finanaidamount)
											)
												from feesdeferredpayments,fees
												where  student_id = $res[3]
												and fees.fee_id=feesdeferredpayments.fee_id
												and period_id = $period_id
												And FeeTemplateDt_name in (".$$feesname.")
												group by family_id)"; 
							//	echo $querydt."<br>";
									$resdt=mysql_query($querydt,$connection) or die(mysql_error());
									$rowdt = mysql_fetch_row($resdt);
									
									
									if($rowdt[0]>0)
										$amountperfamily = $amountperfamily + $rowdt[0];
									 else {
												$today=date('Y-m-d');
												if($regreceiptheader_date=='')
													$regreceiptheader_date = $today;
												 $querydt=" select sum(FeeTemplate_amount)
													from feestemplatestudentdt,feestemplate
													where class_id= ".$res[6]."
													and feestemplatestudentdt.FeeTemplate_id = feestemplate.FeesTemplate_id
													and (FeesTemplate_startdate <= '$regreceiptheader_date'	and ifnull(FeesTemplate_enddate,'$regreceiptheader_date') >= '$regreceiptheader_date')
													and FeeTemplateDt_name in (".$$feesname.") ";
													
													//echo $querydt;
									$resdt=mysql_query($querydt,$connection) or die(mysql_error());	
									$rowdt = mysql_fetch_row($resdt);	
									$amountperfamily = $amountperfamily + $rowdt[0];									
									  
									 
									 }
									 
								
						
					$k+=1;
					}
				echo"</tr>";
				
				 	
		 		//echo $feesname;
		
		
		echo"</table></td></tr>";
		
	
	
		
		//echo"<tr><th>Student Code</th><th>First Name</th><th>Class</th><th>Amount</th></tr>";
		
		
		
		
		if($regreceiptheader_prestudid==''){
			if($mainmode=='insert'){
			if($familycode1 != '')		
			$query="select Upper(Student_FirstName),Class_name,student_code,student_id,null,null,students.class_id from students inner join classes on students.class_id=classes.class_id 
				where (familyDt_idfather=".$familydt_id." or familyDt_idmother=".$familydt_id." ) 
				and (if($regOnly=1,period_id ='$now_period',period_id ='$period_id') 
					or if($regOnly=1,nextperiod_id='$now_period',nextperiod_id='$period_id') 
					or if($regOnly=1,nextperiod_id='$period_id',nextperiod_id='$period_id'))
				and if($period_id = $perd_default, 1=1,studentstatus_id=4) 
				and if($period_id = $perd_default, 1=1,class_last != 1)	
				order by student_id ";
			else
			$query="select Upper(prestud_firstname),Class_name,null,prestud_id,null,null,prestud_class from prestudent inner join classes on prestud_class=classes.class_id 
				where prestud_familyid=".$familydt_id." 
				and prestud_decision='a' and prestud_period=$period_id
				order by prestud_id ";	
				
			}else{
			if($familycode1 != '')
			$query="select Upper(Student_FirstName),Class_name,student_code,students.student_id ,regreceipt_id ,regreceipt_amount,students.class_id
					from regreceipt,students inner join classes on students.class_id=classes.class_id 
					where (familyDt_idfather=".$familydt_id." or familyDt_idmother=".$familydt_id.") 
				and regreceipt.student_id=students.student_id and regreceiptheader_id= $regreceiptheader_id	 
				and (if($regOnly=1,period_id ='$now_period',period_id ='$period_id') 
					or if($regOnly=1,nextperiod_id='$now_period',nextperiod_id='$period_id')
					or if($regOnly=1,nextperiod_id='$period_id',nextperiod_id='$period_id')	)
				and if($period_id = $perd_default, 1=1,studentstatus_id=4) 
				and if($period_id = $perd_default, 1=1,class_last != 1)
				order by student_id"	;
			else
			$query="select Upper(prestud_firstname),Class_name,null,prestud_id,regreceipt_id ,regreceipt_amount,prestud_class
					from regreceipt,prestudent inner join classes on prestud_class=classes.class_id 
					where prestud_familyid=".$familydt_id." 
				and regreceipt.student_id=prestud_id and regreceiptheader_id= $regreceiptheader_id	 
				and prestud_decision='a' and prestud_period=$period_id
				order by prestud_id"	;	
			}	
		} else {

			if($mainmode=='insert')
				$query="select 
						prestud_firstname,null,prestud_familyname,prestud_id ,null,null,prestud_class
						from prestudent where prestud_id=".$regreceiptheader_prestudid;
			else
				$query="select prestud_firstname,prestud_familyname,prestudent.prestud_id,prestudent.prestud_id ,regreceipt_id ,regreceipt_amount,prestud_class
					from regreceipt,prestudent ,regreceiptheader 
					where prestudent.prestud_id=".$regreceiptheader_prestudid."
					and regreceiptheader.regreceiptheader_prestudid=prestudent.prestud_id 
					and regreceipt.regreceiptheader_id=regreceiptheader.regreceiptheader_id 
					and regreceiptheader.regreceiptheader_id= $regreceiptheader_id"
					;
		}		//echo $query;
			if($mainmode == 'insert' && $dist_receiptdt == 1){ 
			$result=mysql_query($query,$connection); $ii=0;
			while($rw = mysql_fetch_row($result)){
				
				$feesname='feesname'.$ii; //echo $$feesname; echo "<br>";
		if($familycode1 != '')		
		$querytotalamt = "select sum(feedeferredpayment_amount
							- if(ifnull(FeeDeferredPayment_discountamount,0)=0,feedeferredpayment_amount*ifnull(FeeDeferredPayment_discountper,0)/100,FeeDeferredPayment_discountamount)
							- if(ifnull(FeeDeferredPayment_finanaidamount,0)=0,feedeferredpayment_amount*ifnull(FeeDeferredPayment_finanaidper,0)/100,FeeDeferredPayment_finanaidamount)
							 ), FeeDeferredPayment_number, if($period_id != $perd_default,sum(feedeferredpayment_amount), 0) from feesdeferredpayments,fees
							where fees.Family_id in (select distinct family_id from familiesdt where familydt_id=$familydt_id)
							and fees.fee_id=feesdeferredpayments.fee_id
							and period_id = $period_id
							And FeeTemplateDt_name in (".$$feesname.")
							and student_id = $rw[3]			
							group by FeeDeferredPayment_number";
		else $querytotalamt = "select sum(feedeferredpayment_amount
							- if(ifnull(FeeDeferredPayment_discountamount,0)=0,feedeferredpayment_amount*ifnull(FeeDeferredPayment_discountper,0)/100,FeeDeferredPayment_discountamount)
							- if(ifnull(FeeDeferredPayment_finanaidamount,0)=0,feedeferredpayment_amount*ifnull(FeeDeferredPayment_finanaidper,0)/100,FeeDeferredPayment_finanaidamount)
							 ), FeeDeferredPayment_number, sum(feedeferredpayment_amount) from feesdeferredpayments,fees
							where fees.Family_id =$familydt_id
							and fees.fee_id=feesdeferredpayments.fee_id
							and period_id = $period_id
							And FeeTemplateDt_name in (".$$feesname.")
							and student_id = $rw[3]			
							group by FeeDeferredPayment_number";					
			//echo $querytotalamt;	echo "<br>";					
			$restotalamt = mysql_query($querytotalamt,$connection);
			$t=0;$jk=0;	
			$totaldeffNoDisc = 0;	
			while($rwtotalamt = mysql_fetch_row($restotalamt)){
				$totalamtstd[$rwtotalamt[1]][$t] = $totalamtstd[$rwtotalamt[1]][$t] + $rwtotalamt[0];
				$totaldeffNoDisc = $rwtotalamt[2]; //echo $t; echo "<br>hjh";
				$t++;
				
			} 
			if($period_id != $perd_default)	{
				$recheaderdates = explode('/', $regreceiptheader_date);
				$recheaderdate = $recheaderdates[2]."-".$recheaderdates[1]."-".$recheaderdates[0];
				$querydt=" select sum(if(ifnull(FeeTemplate_amount,0)=0,ifnull(feespreamount,0),FeeTemplate_amount ))
							from feestemplatestudentdt,feestemplate
							where class_id= $rw[6]
							and feestemplatestudentdt.FeeTemplate_id = feestemplate.FeesTemplate_id
							and (FeesTemplate_startdate <= '$recheaderdate'	and ifnull(FeesTemplate_enddate,'$recheaderdate') >= '$recheaderdate')
							and FeeTemplateDt_name in (".$$feesname.")";
				//ECHO $querydt;
				//echo $totalamtstd[1][$t-1];			
				$resdt = mysql_query($querydt,$connection);
				$rwdt = mysql_fetch_row($resdt);
				$totalamtstd[1][$jk] = $totalamtstd[1][$jk] + $rwdt[0] - $totaldeffNoDisc;
					
			}
			
			
			$ii++;
				
			
			} 
			$result=mysql_query($query,$connection); $ii=0;
			$countstd=0; $stdid = '';
			$numstd = mysql_num_rows($result);
			while($rw = mysql_fetch_row($result)){
				$feesname='feesname'.$ii; 
				$feenameids = explode(',',$$feesname);
				foreach($feenameids as $feenameid){
					
			if(	$feenameid != '-1'){	
			if($stdid != $rw[3]) $countstd=$countstd+1;
			//echo $feenameid;echo "<br>";
			if($familycode1 != '')	
			$querytotRemainAmt = "select sum(regreceiptdt_amount) from regreceiptdt
						left join regreceipt on regreceipt.regreceipt_id=regreceiptdt.regreceipt_id
						left join regreceiptheader on regreceipt.regreceiptheader_id=regreceiptheader.regreceiptheader_id
						where student_id = $rw[3]	and familydt_id = $familydt_id
						and regreceiptheader.period_id= $period_id And tuitionfees_id =$feenameid;";
		else $querytotRemainAmt = "select sum(regreceiptdt_amount) from regreceiptdt
						left join regreceipt on regreceipt.regreceipt_id=regreceiptdt.regreceipt_id
						left join regreceiptheader on regreceipt.regreceiptheader_id=regreceiptheader.regreceiptheader_id
						where student_id = $rw[3]	and familydt_id = $familydt_id
						and regreceiptheader.period_id= $period_id And tuitionfees_id =$feenameid";	//echo $querytotRemainAmt."<br><br>";
			$tt=0;$ctr=2;$def=1;	
			$restotRemainAmt = mysql_query($querytotRemainAmt,$connection);
			$rwtotcount = mysql_num_rows($restotRemainAmt);
			while($rwtotRemainAmt = mysql_fetch_row($restotRemainAmt) ){ 
				if($rwtotRemainAmt[0] == '') $rwtotRemainAmt[0]=0;
				
				if($period_id != $perd_default){
					$totalamtstd[$def][$tt] = $totalamtstd[$def][$tt] - $rwtotRemainAmt[0];
					$def++;$tt++;
				}else{	
					if($familycode1 != '')		
		$querytotalamt1 = "select sum(feedeferredpayment_amount
							- if(ifnull(FeeDeferredPayment_discountamount,0)=0,feedeferredpayment_amount*ifnull(FeeDeferredPayment_discountper,0)/100,FeeDeferredPayment_discountamount)
							- if(ifnull(FeeDeferredPayment_finanaidamount,0)=0,feedeferredpayment_amount*ifnull(FeeDeferredPayment_finanaidper,0)/100,FeeDeferredPayment_finanaidamount)
							 ), FeeDeferredPayment_number, if($period_id != $perd_default,sum(feedeferredpayment_amount), 0) from feesdeferredpayments,fees
							where fees.Family_id in (select distinct family_id from familiesdt where familydt_id=$familydt_id)
							and fees.fee_id=feesdeferredpayments.fee_id
							and period_id = $period_id
							And FeeTemplateDt_name = $feenameid
							and student_id = $rw[3]			
							group by FeeDeferredPayment_number";
		else $querytotalamt1 = "select sum(feedeferredpayment_amount
							- if(ifnull(FeeDeferredPayment_discountamount,0)=0,feedeferredpayment_amount*ifnull(FeeDeferredPayment_discountper,0)/100,FeeDeferredPayment_discountamount)
							- if(ifnull(FeeDeferredPayment_finanaidamount,0)=0,feedeferredpayment_amount*ifnull(FeeDeferredPayment_finanaidper,0)/100,FeeDeferredPayment_finanaidamount)
							 ), FeeDeferredPayment_number, sum(feedeferredpayment_amount) from feesdeferredpayments,fees
							where fees.Family_id =$familydt_id
							and fees.fee_id=feesdeferredpayments.fee_id
							and period_id = $period_id
							And FeeTemplateDt_name = $feenameid
							and student_id = $rw[3]			
							group by FeeDeferredPayment_number";	
		$res1 = mysql_query($querytotalamt1,$connection);					
		while($rw1 = mysql_fetch_row($res1)){
			if($rw1[0] - $rwtotRemainAmt[0]>=0){
				$totalamtstd[$def][$tt] = $totalamtstd[$def][$tt] - $rwtotRemainAmt[0];//echo $totalamtstd[$def][$tt] - $rw1[0];echo "<br>";
				$def++;$tt++;
				break;
			}else if($rw1[0] - $rwtotRemainAmt[0]<0) { 
				$totalamtstd[$def][$tt] = $totalamtstd[$def][$tt] - $rw1[0];
				$def++;$tt++;
				
				$totalamtstd[$def][$tt] = $totalamtstd[$def][$tt] - ($rwtotRemainAmt[0]-$rw1[0]);
				break;
			}
		}
				}
				
				
				
			} $stdid = $rw[3];
				} 
			}$ii++;
			}
			
	}	
		//echo $query;
		$result=mysql_query($query,$connection);
		$i=0;
		$j=0;
		$remaining_to_next_deferred=0;	
		$totalAmount=0;
		//if(count($result)==0)
			//"<tr><td> </td><td></td><td></td></tr>";
		
		while ($res=mysql_fetch_row($result)){
			$class_id=$res[6];
			$feesname='feesname'.$i;
			$regreceiptheadertext='regreceiptheader_id'.$i;
			$$regreceiptheadertext=$res[4];
			
			$stdid = 'Studentid'.$i;
			$$stdid = $res[3];
			echo "<input type='hidden' name='$stdid' value='".$$stdid."'>";
			if($$feesname=='')
				$$feesname='-1';
		 
			echo"<input type='hidden' name='$regreceiptheadertext' value='".$$regreceiptheadertext."'>";
			//$amount$i=0;
			
			
			
			
			
			echo"<tr><td style='border-top:0px;border-left:0px;border-right:0px;border-bottom:0px' colspan=8><hr></td></tr>";
			
			echo"<tr><td colspan=4><div style='background-color:#D8D8D8'><i><b>Student:</b> <b><font color=#1e87a5>$res[2]<i> - &nbsp;$res[0]&nbsp;$firstname $familyname (Class $res[1])&nbsp;</td>
			<td  align=center><b>Deferred Amounts</td>
							<td align=center><b>Receipt Amounts</td>
							<td align=center><b>Remaining</td>
							<td  style='border-top:0px;border-left:0px;border-right:0px;border-bottom:0px' align=center></td>
			</tr>";
			$regreceipt_id =$res[4];
			$student_id=$res[3];
			
			
		//regreceiptdt_id, tuitionfees_id, regreceiptdt_amount, regreceipt_id	
			if($mainmode=='insert' || $mainmode=='edit'){
				
				if($regreceiptheader_prestudid==''){
					if($familycode1 != '')
						$query = "  select distinct FeeTemplateDt_name,FeeTemplateDt_name,null,null,FeesTemplatename_name,
									if($period_id = $perd_default,feedeferredpayment_date,null),student_id,
									if($period_id != $perd_default and (Transportation_included = 6 or Transportation_included = 3) , 0,feedeferredpayment_amount 
									- if(ifnull(FeeDeferredPayment_discountamount,0)=0,feedeferredpayment_amount*ifnull(FeeDeferredPayment_discountper,0)/100,FeeDeferredPayment_discountamount)
									- if(ifnull(FeeDeferredPayment_finanaidamount,0)=0,feedeferredpayment_amount*ifnull(FeeDeferredPayment_finanaidper,0)/100,FeeDeferredPayment_finanaidamount)
									 )
									,feesdeferredpayments.Ledger_number2, FeeTemplateDt_name,
									if($period_id = $perd_default,FeeDeferredPayment_date, null),if($period_id = $perd_default,FeeDeferredPayment_number,null)
									from feesdeferredpayments
									left join fees on fees.fee_id=feesdeferredpayments.fee_id
									left join feestemplatenames on feestemplatenames.FeesTemplatename_id=feesdeferredpayments.FeeTemplateDt_name
									where student_id = $student_id
									And FeeTemplateDt_name in (".$$feesname.")
									and if($period_id = $perd_default,period_id = $period_id,(period_id = $period_id or period_id=$perd_default) 	)
									order by feedeferredpayment_date,FeesTemplatename_name ";
					else $query = "  select distinct FeeTemplateDt_name,FeeTemplateDt_name,null,null,FeesTemplatename_name,
									feedeferredpayment_date,student_id,
									feedeferredpayment_amount 
									- if(ifnull(FeeDeferredPayment_discountamount,0)=0,feedeferredpayment_amount*ifnull(FeeDeferredPayment_discountper,0)/100,FeeDeferredPayment_discountamount)
									- if(ifnull(FeeDeferredPayment_finanaidamount,0)=0,feedeferredpayment_amount*ifnull(FeeDeferredPayment_finanaidper,0)/100,FeeDeferredPayment_finanaidamount)
									 
									,feesdeferredpayments.Ledger_number2, FeeTemplateDt_name,
									FeeDeferredPayment_date,FeeDeferredPayment_number
									from feesdeferredpayments
									left join fees on fees.fee_id=feesdeferredpayments.fee_id
									left join feestemplatenames on feestemplatenames.FeesTemplatename_id=feesdeferredpayments.FeeTemplateDt_name
									where student_id = $student_id
									And FeeTemplateDt_name in (".$$feesname.")
									and period_id = $period_id
									order by feedeferredpayment_date,FeesTemplatename_name ";			
				//	echo $query;	
					//group by feesdeferredpayments.FeeTemplateDt_name
						$resultcheck=mysql_query($query,$connection) or die(mysql_error());
						$numcheck=mysql_num_rows($resultcheck);
						if($numcheck==0){
						//else{	
								$query = " 
								SELECT  FeesTemplatename_id,FeesTemplatename_name,null,null,FeesTemplatename_name 
										FROM feestemplatenames							
										where FeesTemplatename_id in(".$$feesname.")
								order by FeesTemplatename_name		";				
						}
						
						
					}
					else{					
					$query="SELECT FeesTemplatename_id,FeesTemplatename_name,null,null,FeesTemplatename_name FROM feestemplatenames ";
					
					if($respre==1)
					$query=$query." where transportation_included=1 or transportation_included=1";
					else
					$query=$query." where transportation_included=2 or transportation_included=2";
				//echo $query;
				}
				
				//exit;
				}
			else {
					if($regreceiptheader_prestudid=='')
						$query="SELECT regreceiptdt_id, tuitionfees_id, regreceiptdt_amount, regreceipt_id	 ,FeesTemplatename_name, FeesTemplatename_id,regreceiptdt.ledger_number
						from regreceiptdt ,feestemplatenames
						where regreceipt_id=$regreceipt_id
						and feestemplatenames.FeesTemplatename_id=regreceiptdt.tuitionfees_id";
						
					else $query="SELECT regreceiptdt_id, tuitionfees_id, regreceiptdt_amount, regreceipt_id	 ,FeesTemplatename_name, FeesTemplatename_id,regreceiptdt.ledger_number
						from regreceiptdt ,feestemplatenames
						where regreceipt_id=$regreceipt_id
						and feestemplatenames.FeesTemplatename_id=regreceiptdt.tuitionfees_id";
				}
			//echo $query."<br><br>";
			$resultfees=mysql_query($query,$connection) or die(mysql_error());
			
			
			$j=0;
				$jname='startj'.$i;
				$$jname=$j; 
				echo"<input type='hidden' name='$jname' id='$jname' value='".$$jname."'>";
				$k=0;		
				$total_regreceipt=0;	$t=0; $defferednumbr = 1;
				$totaldeffamount = 0; $remainingamnt =0; $sameDeffer = 1; $xamount=0;
				$lastfees = 0; $$fees = 0; $totpaid=0;
				$totalfees = mysql_num_rows($resultfees); 
				while( $resfees = mysql_fetch_row($resultfees))
				{ 	if($totalreceiptamt[$resfees[11]] == '') $totalreceiptamt[$resfees[11]]=0;
					$lastfees++;
					if($mainmode=='insert') 
						$feestemplateid = $resfees[0];
					else 
						$feestemplateid = $resfees[1];
					//echo $resfees[11]."ff"; echo "<br>";
					if($mainmode=='insert') 
						$ledgernumber = $resfees[8];
					else 
						$ledgernumber = $resfees[6];
					$feesnamedeffer = $resfees[9];
					if($oldfeestempname !=$resfees[1] )	{	
					$qdt = " SELECT feetemplate_amount FROM feestemplatenames
								inner join feestemplatestudentdt on feestemplatestudentdt.feetemplatedt_name = feestemplatenames.feestemplatename_id
								inner join feestemplate on feestemplate.feestemplate_id= feestemplatestudentdt.feetemplate_id 
								and if('$regreceiptheader_date'='',now(),'$regreceiptheader_date') between FeesTemplate_startdate and FeesTemplate_enddate
								and class_id=$class_id and feetemplatedt_name = '$feestemplateid'";
						//echo $qdt."<br>";
						$resultfeesdt=mysql_query($qdt,$connection) or die(mysql_error());
						$resfeesdt = mysql_fetch_row($resultfeesdt);
					}
						if(($regreceiptheader_amount!='' or $regreceiptheader_amount2!='') and $regreceiptheader_prestudid==''){
						if($oldfeestempname !=$resfees[1] )	{
						$querydt="select (select sum(feedeferredpayment_amount
									- if(ifnull(FeeDeferredPayment_discountamount,0)=0,feedeferredpayment_amount*ifnull(FeeDeferredPayment_discountper,0)/100,FeeDeferredPayment_discountamount)
									- if(ifnull(FeeDeferredPayment_finanaidamount,0)=0,feedeferredpayment_amount*ifnull(FeeDeferredPayment_finanaidper,0)/100,FeeDeferredPayment_finanaidamount)
									) from feesdeferredpayments,fees
									where student_id = $student_id
									and fees.fee_id=feesdeferredpayments.fee_id
									and period_id = $period_id
									And if('".$$feesname."' <> '-1',FeeTemplateDt_name in (".$$feesname."),1=1) 
									group by student_id)"; 
								//echo  $querydt."<br>";					
						$resdt=mysql_query($querydt,$connection) or die(mysql_error());
						$rowdt = mysql_fetch_row($resdt);
						$amountperstudent = $rowdt[0]; 
						
								//echo $querydt."<br>";
							if($amountperstudent=='' or $amountperstudent==0){
								$querydt="select sum(FeeTemplate_amount)
										from feestemplatestudentdt,feestemplate
										where class_id= ".$res[6]."
										and feestemplatestudentdt.FeeTemplate_id = feestemplate.FeesTemplate_id
										and (FeesTemplate_startdate <= '$regreceiptheader_date'	and ifnull(FeesTemplate_enddate,'$regreceiptheader_date') >= '$regreceiptheader_date')
										and FeeTemplateDt_name in (".$$feesname.") ";
													
													
							//	echo  $querydt."<br>";					
									$resdt=mysql_query($querydt,$connection) or die(mysql_error());
									$rowdt = mysql_fetch_row($resdt);
									$amountperstudent = $rowdt[0];
							
							}
						//echo $amountperstudent;
						}
							
											
						$amount  = $regreceiptheader_amount *  (($amountperstudent / $amountperfamily) * 100) / 100 ; 
						$amount2  = $regreceiptheader_amount2 *  ($amountperstudent / $amountperfamily * 100) / 100 ;
						
						
												
						if($oldfeestempname !=$resfees[1] ){
						$getamount = GetAmount($student_id,$resfees[0],$familydt_id,$$feesname,$amount,$amount2,$period_id,$remaining_to_next_deferred,$connection,$numcheck,$regreceiptheader_date,$class_id);
						//echo $getamount;
						$amountrec  = split(":",$getamount); 
						$resfeesdt[0] = $amountrec[0];
						//echo $resfeesdt[0];
						$remaining_to_next_deferred =  $amountrec[1];
						}
						
						}
						$queryreceipt1 = " select sum(regreceiptdt_amount) as AmounttillNow
									from regreceiptheader,regreceipt,regreceiptdt
									where regreceipt.period_id = $period_id 
									and regreceiptheader.familydt_id = $familydt_id
									and regreceiptheader.regreceiptheader_id = regreceipt.regreceiptheader_id
									and regreceipt.regreceipt_id = regreceiptdt.regreceipt_id
									and regreceiptdt.tuitionfees_id in (".$$feesname.")";
						//echo $queryreceipt1; echo "<br><br>";
						$resultreceipt1=mysql_query($queryreceipt1,$connection) or die(mysql_error());
						$rwreceipt1 = mysql_fetch_row($resultreceipt1);
						$totalreceiptAmount = $rwreceipt1[0];
						if($totalreceiptAmount=='') $totalreceiptAmount=0;
					//if($oldfeestempname !=$resfees[1] ){
					$fees = $resfees[0];
					$fees = 'fees'.$student_id."-".$j;
					//echo $fees; echo "<br>";
					if($mainmode=='edit')
						$$fees=$resfees[2];
					
					//echo $$fees;
					//if($mainmode!='edit' and $$fees=='')
					//if($mainmode!='edit')
							//$$fees = $resfeesdt[0];
					if($numcheck==0)
							$stat = ' ';
						else
						$stat = ' readonly';
				//	}	
						
						$query="select sum(feedeferredpayment_amount
									- if(ifnull(FeeDeferredPayment_discountamount,0)=0,feedeferredpayment_amount*ifnull(FeeDeferredPayment_discountper,0)/100,FeeDeferredPayment_discountamount)
									- if(ifnull(FeeDeferredPayment_finanaidamount,0)=0,feedeferredpayment_amount*ifnull(FeeDeferredPayment_finanaidper,0)/100,FeeDeferredPayment_finanaidamount)
									), count(feedeferredpayment_amount) from feesdeferredpayments,fees
									where student_id = $student_id
									and fees.fee_id=feesdeferredpayments.fee_id
									and period_id = $period_id
									And FeeTemplateDt_name = $feestemplateid 
									group by student_id"; 
									//echo $query;
							$resultamount=mysql_query($query,$connection) or die(mysql_error());
							$resamount = mysql_fetch_row($resultamount);
							$deferredamounts = $resamount[0];
						if($period_id != $perd_default && $resfees[7] == 0)	{
							$recheaderdates = explode('/', $regreceiptheader_date);
							$recheaderdate = $recheaderdates[2]."-".$recheaderdates[1]."-".$recheaderdates[0];
							$querydt=" select ifnull(FeeTemplate_amount,0), ifnull(feespreamount,0)
										from feestemplatestudentdt,feestemplate
										where class_id= ".$res[6]."
										and feestemplatestudentdt.FeeTemplate_id = feestemplate.FeesTemplate_id
										and (FeesTemplate_startdate <= '$recheaderdate'	and ifnull(FeesTemplate_enddate,'$recheaderdate') >= '$recheaderdate')
										and FeeTemplateDt_name = $feestemplateid";
							//echo $querydt;			
							$resultdt=mysql_query($querydt,$connection) or die(mysql_error());
							$resamount = mysql_fetch_row($resultdt);
							$resfees[7] = $resamount[0];
							$deferredamounts = $resamount[0];
							if($resfees[7] == 0) $resfees[7] = $resamount[1];
							if($deferredamounts == 0) $deferredamounts = $resamount[1];							
						}
							if($deferredamounts=='') $deferredamounts=0;
						$queryreceipt = " select sum(regreceiptdt_amount) as AmounttillNow
									from regreceipt,regreceiptdt
									where regreceipt.period_id = $period_id 
									and regreceipt.student_id = $student_id
									and regreceipt.regreceipt_id = regreceiptdt.regreceipt_id
									and regreceiptdt.tuitionfees_id = $feestemplateid";
						//echo $queryreceipt; echo "<br><br>";
						$resultreceipt=mysql_query($queryreceipt,$connection) or die(mysql_error());
						$rwreceipt = mysql_fetch_row($resultreceipt);
						$totreceiptamounts = $rwreceipt[0];
						if($totreceiptamounts=='') $totreceiptamounts=0;
						//echo $totreceiptamounts;
						if($period_id != $perd_default) {
							$resfees[11] = 1;		
							$resamount[1] = 1;
						} 
						if($defferednumbr == $resfees[11] ){ 
						$sameDeffer = 1;
						 
						//	echo $totreceiptamounts ."<br> ". $resfees[7];
						//} else { 
							if($totreceiptamounts != 0) {
								if($totreceiptamounts >=  $resfees[7])
								$receiptamounts = $resfees[7];
								else $receiptamounts = $totreceiptamounts;
								
							}
							else $receiptamounts = 0;
						if($period_id != $perd_default){
						$amountperdeff = $totalamtstd[$defferednumbr][$t];// - $receiptamounts; 
						}
						else 
						$amountperdeff = $totalamtstd[$defferednumbr][$t];// - $receiptamounts; 
						} else {
							$sameDeffer = 0;
							if($totreceiptamounts == 0) $receiptamounts = 0;
							else {
								$receiptamounts = 0;
								$totreceiptamounts_temp = $totreceiptamounts;
								$stillamount = 1;
								while($stillamount == 1 && ($totreceiptamounts - $resfees[7])>0 && $receiptamounts >=0){
									$receiptamounts = $receiptamounts + ($totreceiptamounts - $resfees[7]);
									$totreceiptamounts_temp = $totreceiptamounts_temp - $resfees[7];
									//echo $totreceiptamounts - $resfees[7]; echo "gh<br>";
									//echo $receiptamounts; echo "gh<br>";
									if($receiptamounts <= $resfees[7] ) $stillamount=0;
								}
							}
							$defferednumbr = $defferednumbr + 1;
							$t = $t +1;
							$amountperdeff = $totalamtstd[$defferednumbr][$t];// - $receiptamounts;
						}
						
						
						
						if($sameDeffer == 0){ 
						//echo $remainingamnt2; echo "<br>";//
						 //|| $remainingamnt2 >$amountperdeff&& ($countstd<$numstd || $countstd == 1)
						if($lastfees == $totalfees && (($remainingamnt2) > ($deferredamounts)) || $remainingamnt2 >$amountperdeff ) 
							$xamount =  $resfees[7] - $receiptamounts; 
						 else if($remainingamnt2 > 0)
							$xamount = $remainingamnt2*(($deferredamounts/$resamount[1])-$receiptamounts)/($amountperdeff);
						
						// if( $remainingamnt2 >$resfees[7] && $lastfees == $totalfees)	
						//$xamount = $resfees[7]*(($deferredamounts/$resamount[1])-$receiptamounts)/($amountperdeff- $totalreceiptamt[$resfees[11]]);
						 else $xamount = 0; 
						//	echo $lastfees .'=='. $totalfees; echo "<br>";
						//echo $totpaid; echo "<br>";
					//	echo $remainingamnt2.'*'.(($deferredamounts/$resamount[1])-$receiptamounts).
					//	'/'.($amountperdeff);
					//		echo "<br>";
						 }
						
						if($sameDeffer == 1){ 
						// if($period_id != $perd_default){
							//echo  $totalreceiptAmount  ; echo "<br><br>";
							$totalreceiptamt[$resfees[11]] = $receiptamounts;
						// }
						//$xamount = $regreceiptheader_amount*(($deferredamounts/$resamount[1])-$receiptamounts)/($amountperdeff -  ($totalreceiptAmount - $totalreceiptamt[$resfees[11]] ));
						$xamount = $regreceiptheader_amount*(($deferredamounts/$resamount[1])-$receiptamounts)/($amountperdeff );
						//	echo $xamount; echo "<br>";
						//} else { 
					//	$xamount = $regreceiptheader_amount*(($deferredamounts/$resamount[1])-$receiptamounts)/($amountperdeff -  $totalreceiptamt[$defferednumbr]);
					//echo $totalreceiptamt[$resfees[11]]; echo "<br>";
					//	}
					//echo $regreceiptheader_amount."*".((($deferredamounts/$resamount[1])-$receiptamounts)/$resamount[1])."/".($amountperdeff  ); echo "<br>";
						//echo ((($deferredamounts."/".$resamount[1])."-".$receiptamounts)."/".$resamount[1])."/".($amountperdeff ." -". $totalreceiptamt[$resfees[11]] ); echo "<br>";
						
						//echo $regreceiptheader_amount."*".((($deferredamounts/$resamount[1])-$receiptamounts)/$resamount[1])."/".($amountperdeff -  ($totalreceiptAmount - $totalreceiptamt[$resfees[11]] )); echo "<br>";
						//echo ((($deferredamounts."/".$resamount[1])."-".$receiptamounts)."/".$resamount[1])."/".($amountperdeff ."-".  ($totalreceiptAmount." -". $totalreceiptamt[$resfees[11]] )); echo "<br>";
						//echo $xamount; 
						//echo "<br>";
						if($xamount != 0)
						$xamount = $xamount+$remainingamnt;	
						$amountdeffered2 =  $xamount - $resfees[7];
						$amountperdeff = $totalamtstd[$defferednumbr][$t];// -$receiptamounts;
					//	$totalreceiptamt[$resfees[11]] = $receiptamounts;
						$totalreceiptamt[$resfees[11]] =  $totalreceiptamt[$resfees[11]]+ $receiptamounts;
						
						$sameDeffer = 1; 
						} else {
							$sameDeffer = 0;
							$amountdeffered2 =  $xamount - $resfees[7];
							$defferednumbr = $defferednumbr + 1;
							$t = $t +1;
							$amountperdeff = $totalamtstd[$defferednumbr][$t];// -$receiptamounts;
							$totalreceiptamt[$resfees[11]] =  $totalreceiptamt[$resfees[11]]+ $receiptamounts;
							
						}
						
						
						
											
						echo "<tr><td>$resfees[10]</td><td colspan='2'>$resfees[4]</td>";
						if($regreceiptheader_prestudid != '') echo "<td>$regreceiptheader_amount</td>";
						else{
						if($amountdeffered2 > 0 && $sameDeffer == 1 )
						{
							echo "<td>".round($resfees[7]-$receiptamounts)."";
							if($oldfeestempname ==$resfees[1] && $oldstd == $student_id){
							$$fees = ($resfees[7]-$receiptamounts) ; //$$fees
							} else {
							$$fees = 0;
							$$fees = ($resfees[7]-$receiptamounts);//$$fees
							
						}
							$totpaid = $totpaid + $$fees;
						}						
						else {
							echo "<td>".round($xamount)."";
						
						if($oldfeestempname ==$resfees[1] && $oldstd == $student_id ){
							$$fees = $xamount;  //$$fees
						} else {
							$$fees = 0; 
							$$fees =$xamount; //$$fees
							
						}
						$totpaid = $totpaid + $$fees;
						} 
						}
						//echo "<br>";echo $$fees; echo "<br>";
						echo "<td align='center'>$resfees[7] </td>";
						//if($receiptamounts <0) $receiptamounts=0;
						echo "<td>".number_format(round($receiptamounts),$DecimalBase1)."</td>";
						
							//	echo $$fees; echo "<br>";			
						if($amountdeffered2 > 0 )
						{
							$remainingamnt = $amountdeffered2;
							$remainingamnt2=$regreceiptheader_amount - ($totalamtstd[$defferednumbr][$t]);// - $totalreceiptamt[$resfees[11]] ); 
							
						}else $remainingamnt =0;
						
						if($amountdeffered2 < 0 && $sameDeffer == 1 && $xamount == 0){
							$remainingamnt2=$regreceiptheader_amount - ($totalamtstd[$defferednumbr][$t]);// - $totalreceiptamt[$resfees[11]] ); 
							//echo "id".$student_id; echo "<br>";
							//echo $regreceiptheader_amount."-(".$totalamtstd[$defferednumbr][$t] ."-". $totalreceiptamt[$resfees[11]] ."-". $receiptamounts.")"; echo "<br>";
							
						}  
						// echo $remainingamnt2;echo "<br>";
						
						if($oldfeestempname != $resfees[1] ){
							$total_regreceipt+=$$fees;
							
							} 
						if($oldfeestempname == $resfees[1] && $oldstd != $student_id){
							$total_regreceipt+=$$fees;
						}						
						if($oldfeestempname == $resfees[1] && $oldstd == $student_id){
								$total_regreceipt+=$xamount;
							
							} 
						if($regreceiptheader_prestudid != '') $total_regreceipt = $regreceiptheader_amount;	
						echo "<input type='hidden' name='$resfees[0]' id='$resfees[0]' value='".$resfees[0]."'>";
						echo "<input type='hidden' name='$fees' id='$fees'    
								style='border-top:0px;border-left:0px;border-right:0px;border-bottom:0px;text-align:right;width:114px;font-size:11px' 
								value='".$$fees."'>
						<input type='hidden' name='hidden$j' id='hidden$j' style='text-align:right;width:114px;font-size:12px' value='".$fees."'>";
							
							//echo $total_regreceipt; echo "<br>";
							
							if($oldfeestempname != $resfees[1] ){
							if($xamount != 0) $totalAmount+=$$fees;
							} if($oldfeestempname == $resfees[1] && $oldstd == $student_id ){
								if($xamount != 0) $totalAmount+=$xamount;
							}
							if($oldfeestempname == $resfees[1] && $oldstd != $student_id){
							$totalAmount+=$$fees;
						}
						if($regreceiptheader_prestudid != '') $totalAmount = $regreceiptheader_amount;	
						
							$rem = $resfees[7] - $receiptamounts;
							echo"<td><input type='text' readonly name='rem$j' id='rem$j' value='".round($rem)." ' style='width:75px;text-align:right;border-width:0px;font-size:10px'>
							<input type='hidden' readonly name='hiddenrem$j' id='hiddenrem$j' value='rem$j' style='width:75px;text-align:right;border-width:0px'>";
							echo "</td></tr>";
					//	}
					$j+=1;
					$oldfeestempname = $resfees[1];
					$oldstd = $student_id;
					
				}
			 
				
			echo"</td></tr>";
			
			

			
			
			
			$jname='j'.$i;
			$$jname=$j;
			echo"<input type='hidden' name='$jname' id='$jname' value='".$$jname."'>";	
			$amt = 'amount'.$i;
			
			if($res[5]!='')
				$$amt=$res[5];
			else	$$amt = $total_regreceipt;
			
			echo"<tr height=30><td colspan='2'></td><td align=right><b><i>Total&nbsp; </b></tD><td colspan=1>
					<input type='text' name='amount$i'  id='amount$i'   value='".number_format(round($$amt),$DecimalBase1)."'  style='text-align:right;font-style:italic;font-weight:bold;width:114px;font-size:12px;border:0px' readonly onchange='calculateTotal($i)'>
					</div>
					</td></tr>";
			
			
			
			
			$gg==1;
			$i++;
		
		}
		
		
 
 
		
		//echo"<tr><td>$res[0] </td><td>$res[1]</td><td></td></tr>";
		echo"<input type='hidden' name='i' id='i' value='$i'>";
		
		echo"</table>";
	
		echo"</td></tr>";
	}

//if($gg==1)

      echo"<td></td><td align=right colspan=2 ><b><font color=red>Total</b></font>&nbsp; 
		   <input type='text' id='totalAmount'  name='totalAmount' value='".number_format(round($totalAmount),$DecimalBase1)."' style='text-align:right;border:0px;font-color:red;width:150px;font-size:14px' readonly>
		   <input type='hidden' id='totalAmounttobepaid'  name='totalAmounttobepaid' value='".round($totalAmount)."'>
		   </td></tr>";
		   if($totalAmount < $regreceiptheader_amount)
				$additional_amount = $regreceiptheader_amount - $totalAmount;
			else $additional_amount = 0;
			echo "<input type='hidden' id='additional_amount'  name='additional_amount' value='".round($additional_amount)."'>";
//else
 //     echo"<td  colspan=2 ><b><font color=red></b></font>&nbsp;<input type='hidden' id='totalAmount'  name='totalAmount' value='$totalAmount' style='text-align:right;border:0px;font-color:red;width:150px;font-size:14px' readonly></td>";
	  
	echo'<tr><td>';



	
if($remaining_to_next_deferred=='')		 $remaining_to_next_deferred=0;
//echo "remaining".$remaining_to_next_deferred;
 
/* print <<<HERE
<script language="JavaScript" type="text/javascript">

if('$remaining_to_next_deferred' > 0){
	 var name;
	 var remainingamount = $remaining_to_next_deferred;
	 var differ;
	 var total=0;
	for (i = 0; i < remainingamount; i++) {
     name 	  = 'hidden'+i;
	 textname = document.getElementById(name).value; 
	 textname1 = document.getElementById(textname).value; 
	 
	 
	 namerem     = 'hiddenrem'+i;
	 textnamerem = document.getElementById(namerem).value;
	 textnamerem1 = document.getElementById(textnamerem).value;
	 
	differ =  parseFloat(textnamerem1) - parseFloat(textname1);
	
	 //alert(textname1+' '+textnamerem1+' '+differ);
	
	if(remainingamount>differ && remainingamount > 0 && differ > 0){
		
		remainingamount=remainingamount-differ;
		document.getElementById(textname).value = parseFloat(textname1)	+ parseFloat(differ); 
	}
	else
	if(remainingamount<differ && remainingamount > 0 && differ > 0){
	
		document.getElementById(textname).value = parseFloat(textname1)	+ parseFloat(remainingamount); 
		remainingamount=0;
	}
	else
	if(remainingamount==differ && remainingamount > 0 && differ > 0){
	 
		document.getElementById(textname).value = parseFloat(textname1)	+ parseFloat(remainingamount); 
		remainingamount=0;	
	}
	total = total + parseFloat(document.getElementById(textname).value);
	document.getElementById('totalAmount').value = Math.round(total);
	
}

	}
</script>
HERE; */

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




if( $dist_receiptdt == 2 ){
				$queryfee="SELECT fee_id FROM fees where family_id=".$familyid." and period_id=".$period_id;
				$resultfee=mysql_query($queryfee, $connection);
				$fee=mysql_fetch_array($resultfee);
				$fee_id=$fee[0];
			
				if($mainmode=='regenerate'){
				
				
				
				$querys="select  FeedeferredPayment_amount,student_id from feesdeferredpayments where  fee_id=".$fee_id." and FeeTemplateDt_name=13 and FeeDeferredPayment_number=".$number;
				
				
				$results=mysql_query($querys, $connection);
				$count=mysql_num_rows($results);
				
				$amntremstd=$amountremoved/$count;
				
				$flag=1;
				while($fee=mysql_fetch_array($results))
				  if($fee[0]-$amntremstd<0)
				     $flag=0;
				 
				if($flag!=0){
					$results=mysql_query($querys, $connection);
					while($fee=mysql_fetch_array($results)){
						$newamount=$fee[0]-$amntremstd;
						$queryupdate1="update feesdeferredpayments set FeeDeferredPayment_amount=".$newamount." where FeeTemplateDt_name=13 and fee_id=".$fee_id." and FeeDeferredPayment_number=".$number." and student_id=".$fee[1];
						$resultupdate=mysql_query($queryupdate1, $connection);
					
						
						$number1=$number+1;
						$queryr="Select FeeDeferredPayment_id,FeedeferredPayment_amount from feesdeferredpayments where fee_id=".$fee_id."
						and FeeDeferredPayment_number between ".($number1)." and (SELECT count(FeeDeferredPayment_id) FROM feesdeferredpayments where fee_id=".$fee_id." and FeeTemplateDt_name=13) ";
						
						$resultr=mysql_query($queryr, $connection);
						$countr=mysql_num_rows($resultr);
						
						$amounttoadd=$amountremoved/($countr*$count);
						
						while($rows=mysql_fetch_array($resultr)){
							$amountnew=$rows[1]+$amounttoadd;
							
							$queryupdate2="update feesdeferredpayments set FeeDeferredPayment_amount=".$amountnew." where FeeDeferredPayment_id=".$rows[0];
							
							$resultupdate2=mysql_query($queryupdate2, $connection);
						}
					}




			}
              
				for($i=1;$i<=9;$i++){
					
					$oldvalue1='';
					
					$$oldval='';
					
				}
				$amountremoved='';
				$mainmode='insert';
				

				}

				
				
				
				
				
				
					$query_deferredpayment="select FeeDeferredPayment_id,feesdeferredpayments.Fee_id,date_format(FeeDeferredPayment_date,'%d-%m-%Y'),FeeDeferredPayment_number,date_format(FeeDeferredvalue_date,'%d-%m-%Y'),FeeDeferredPayment_amount,
											FeeTemplateDt_name,student_firstname,FeesTemplatename_name,feesdeferredpayments.student_id,feesdeferredpayments.ledger_number,FeeDeferredPayment_amountBase1,FeeDeferredPayment_amountBase2,FeeDeferredPayment_discountper,
											FeeDeferredPayment_amount-((FeeDeferredPayment_amount*ifnull(FeeDeferredPayment_discountper,0))/100)
											,if(FeeDeferredPayment_discountamount=0,FeeDeferredPayment_amount*ifnull(FeeDeferredPayment_discountper,0)/100	,FeeDeferredPayment_discountamount),FeeDeferredPayment_number
											from feesdeferredpayments
											left join feestemplatenames on feestemplatenames.FeesTemplatename_id=feesdeferredpayments.FeeTemplateDt_name
											left join students on students.student_id=feesdeferredpayments.student_id
											left join fees on fees.fee_id=feesdeferredpayments.fee_id	
											where feesdeferredpayments.Fee_id='".$fee_id."'  
											order by FeeDeferredPayment_number,FeesTemplatename_name,student_firstname,FeeDeferredPayment_date";
					//echo$query_deferredpayment;exit;
					//echo "fee_id:".$fee_id;
					$result_deferred=mysql_query($query_deferredpayment, $connection);
					$deferrednum=mysql_num_rows($result_deferred);
					echo"<input type='hidden' name='deferrednum' value='$deferrednum'>";
					
					$p=1;
					$t=0;
					$v=1;
					$total=0;
					echo"<tr><td colspan='10' align='left'><div style='overflow-y:scroll;height:1010px;width:1020px;'><table style='font-size: 11px;
						color: #000000;' border='0' width=900>
						<col width=100>
						<col width=150>
						<col width=150>
						<col width=50>
						<col width=150>
						<col width=100>
						<col width=100>
						
						";
					
					echo"<tr bgcolor='#1e87a5' height='25px'><td ><font color=#FFFFFF>Payment number</td><td ><font color=#FFFFFF>Due Date</td><td  ><font color=#FFFFFF>Total </td><td><font color=#FFFFFF>Paid</td><td> <font color=#FFFFFF>Bank reference no</td>
									<td ><font color=#FFFFFF>Payment date</td></tr>";
					//$k=0;
					$last_date='value_date1';
					$sumpayment=0;
					while($row_deferred=mysql_fetch_array($result_deferred)){
					    
						$nameissue_date='issue_date'.$v;
						$issue_date='issue_date'.$v;
						$$issue_date=$row_deferred[2];
						
						$namevalue_date='value_date'.$v;
						$last_date=$value_date;
						$value_date='value_date'.$v;
						
						//$$last_date=$$value_date;
						$$value_date=$row_deferred[4];
						
						
						$nameamountdeferred='amountdeferred'.$v;
						$amountdeferred='amountdeferred'.$v;
						$$amountdeferred=$row_deferred[5];
						
						$nameamountdeferred1='amount1deferred'.$v;
						$amount1deferred='amount1deferred'.$v;
						$$amount1deferred=$row_deferred[11];
						
						$nameamountdeferred2='amount2deferred'.$v;
						$amount2deferred='amount2deferred'.$v;
						$$amount2deferred=$row_deferred[12];
						
						$namepaymentnumber='paymentnumber'.$v;
						$paymentnumber='paymentnumber'.$v;
						$$paymentnumber=$row_deferred[3];
						
						$nametemplatename='templatename'.$v;
						$templatename='templatename'.$v;
						$$templatename=$row_deferred[6];
						
						$namestudentdeferred='studentdeferred'.$v;
						$studentdeferred='studentdeferred'.$v;
						$$studentdeferred=$row_deferred[9];
						
						$nameledgerdeferred='ledger_number'.$v;
						$ledger_number='ledger_number'.$v;
						$$ledger_number=$row_deferred[10];
						
							
						
						echo"<input type='hidden' name='$nametemplatename' value='".$$templatename."'>";
						echo"<input type='hidden' name='$namestudentdeferred' value='".$$studentdeferred."'>";
						echo"<input type='hidden' name='$nameledgerdeferred' value='".$$ledger_number."'>";
						
						
						
							//echo $totalpayment.":".$$totalpayment."<br>";;
						
						
						if($defnum==''){
							$defnum=$row_deferred[16];
							$k++;
							$totalpayment='totalpayment'.$k;
							$$totalpayment='';
						}
						
						if($defnum!=$row_deferred[16]){
								$defnum=$row_deferred[16];
								$k++;
								$previoustot=$$totalpayment;
								//$$totalpayment='';
								//$previoustot=round($previoustot);
								$previoustotname=$totalpayment;
								$totalpayment='totalpayment'.$k;
								$$totalpayment='';
						}
						    
							//echo "previous:".$previoustot;
						if($number!=$row_deferred[3] && $number!=''&&$previoustot!=''){
						
							$t=$t+1;
							
							$paid='paid'.$t;
							$bank='bank'.$t;
							$pdate='pdate'.$t;
									
							   
							//echo "total:".$totalpayment;exit;
							//$previoustot=round($previoustot,0,PHP_ROUND_HALF_DOWN);
							//1.55, 1, PHP_ROUND_HALF_DOWN
							//echo "previous:".$previoustot;
							$previoustot=number_format($previoustot, $DecimalBase1, '.', '');
							$queryr="select bank_reference,date_format(regreceiptheader_date,'%d-%m-%Y')  from regreceiptheader
							inner join familiesdt on familiesdt.familydt_id=regreceiptheader.familydt_id
							where familiesdt.family_id=".$familyid." and regreceiptheader_amount=".$previoustot." and period_id=".$period_id." and payment_number =".$t;
							//echo $queryr;
							$resultr=mysql_query($queryr, $connection);
							$numr=mysql_num_rows($resultr);
							//echo "num:".$numr;
							if($numr==1){	
								$$paid=1;
								$rowb=mysql_fetch_array($resultr);
								$$bank=$rowb[0];
								$$pdate=$rowb[1];
							}
							
							$previoustot=number_format($previoustot, $DecimalBase1, '.', ',');
							
							//$previoustot=round($previoustot);
							$sumpayment+=$previoustot;
							//echo "previous:".$previoustot;
							//echo "total paid:".$total_paid;
							if($$paid==1){
							   $ck='checked';
							   $dis='';
							    $change='disabled';
							   
							}							   
							else{
							   $ck='';
							   $dis='disabled';
							    $change='';
							}
							
							echo"<tr class='row_colorgrey'><td>Payment $t<td align='left'><input type='hidden' name='$namevalue_date' value='".$$last_date."' size='10'>".$$last_date."</td><td ><input type='text' name='".$previoustotname."' id='".$previoustotname."' value='".$previoustot."' style='border-radius:4px;width:80px;font-size:12px' $change onchange=\"changedefered(this,$t)\" onclick=\"setoldvalue(this,$t)\"> $base1</td><td><input type='checkbox'  onMouseOver=\"style.cursor='hand'\" disabled  $stat  $ck onclick=\"changevaluepaid(this,'".$paid."')\">
							
							<input type='hidden' name='".$paid."' id='".$paid."' value='".$$paid."' ></td><td align='left' ><input type='text' name='".$bank."' id='".$bank."' value='".$$bank."' disabled ></td>
									<td><input type='text' name='".$pdate."' id='".$pdate."' value='".$$pdate."' style='border-radius:4px;width:80px;font-size:12px' disabled>";
							echo"<a href='#'";
							if( $dis=='')
							   echo" onClick=\"displayCalendar(document.feesreport.".$pdate.",'dd/mm/yyyy',this); return false; \" name='".$pdate."' id='".$pdate."' $dis>";// <image src='./img/cal.gif' border=0 align=bottom></image></a>";
							//else echo"><image src='./img/cal.gif' border=0 align=bottom></image></a>";
 
						echo"</td></tr>";
							
							//echo"paid:".$$paid;
							echo"<tr height='30px'  bgcolor='#ffffff'><td colspan='8'><hr></td></tr>";
							//$$totalpayment=0;
						}	
						
					
						
						$p=$p+1;
						$number=$row_deferred[3]; 
						$valuedate=$row_deferred[4];
						//$$totalpayment=number_unformat($$totalpayment,true,'.',',');
						//echo "total payment:".$$totalpayment."<br>";
						//echo "defferred:".$row_deferred[14]."<br>";
						$$totalpayment=$$totalpayment+$row_deferred[14];
						
						//$$totalpayment=round($$totalpayment);
						//echo $totalpayment.":".$$totalpayment."<br>";exit;
						$total=$total+$row_deferred[14];
						
						//echo$v;
						$v=$v+1;
						$tuitionname = $row_deferred[8];
												
					}
					
					$t=$t+1;
					
					$paid='paid'.$t;
							$bank='bank'.$t;
							$pdate='pdate'.$t;
							$previoustot=$$totalpayment;
							$previoustotname=$totalpayment;			
							   
							//echo "total:".$totalpayment;exit;
							$previoustot=number_format($previoustot, $DecimalBase1, '.', '');
							$queryr="select bank_reference,date_format(regreceiptheader_date,'%d-%m-%Y')  from regreceiptheader
							inner join familiesdt on familiesdt.familydt_id=regreceiptheader.familydt_id
							where familiesdt.family_id=".$familyid." and regreceiptheader_amount=".$previoustot." and period_id=".$period_id." and payment_number =".$t;
							//echo $queryr;
							$resultr=mysql_query($queryr, $connection);
							$numr=mysql_num_rows($resultr);
							//echo "num:".$numr;
							//echo "total paid:".$totalpaid;
							
							if($numr==1){	
								$$paid=1;
								$rowb=mysql_fetch_array($resultr);
								$$bank=$rowb[0];
								$$pdate=$rowb[1];
								$sumpayment=$sumpayment+$previoustot;
								 
							}
							
							//$previoustot=number_format($previoustot, $DecimalBase1, '.', ',');
							
							
							
							if($$paid==1){
							   $ck='checked';
							   $dis='';
							  
							}							   
							else{
							   $ck='';
							   $dis='disabled';
							   
							}
					
					
					
					
					$previoustot=number_format($previoustot, $DecimalBase1, '.', ',');
					
					
					echo"<tr class='row_colorgrey'><td>Payment $t<td align='left'><input type='hidden' name='$namevalue_date' value='".$$value_date."' size='10'>".$$value_date."</td><td ><input type='text' name='".$previoustotname."' id='".$previoustotname."' value='".$previoustot."' style='border-radius:4px;width:80px;font-size:12px' disabled > $base1</td><td><input type='checkbox'  onMouseOver=\"style.cursor='hand'\" disabled  $stat  $ck onclick=\"changevaluepaid(this,'".$paid."')\">
							
							<input type='hidden' name='".$paid."' id='".$paid."' value='".$$paid."' ></td><td align='left' ><input type='text' name='".$bank."' id='".$bank."' value='".$$bank."' disabled ></td>
									<td><input type='text' name='".$pdate."' id='".$pdate."' value='".$$pdate."' style='border-radius:4px;width:80px;font-size:12px' disabled>";
							echo"<a href='#'";
							if( $dis=='')
							   echo" onClick=\"displayCalendar(document.feesreport.".$pdate.",'dd/mm/yyyy',this); return false; \" name='".$pdate."' id='".$pdate."' $dis>";// <image src='./img/cal.gif' border=0 align=bottom></image></a>";
							//else echo"><image src='./img/cal.gif' border=0 align=bottom></image></a>";
 
						echo"</td></tr>";
					
					//echo "bank:".$bank;
					
				//echo"<tr  class='row_colorgrey'><td >&nbsp;</td><td align='right' colspan='6'><font color=#000000><b><i>Payment $t </font>&nbsp;&nbsp;&nbsp;<font color=#000000>".$$totalpayment." $base1</font></td></tr>";
                $queryremaining="select sum(regreceiptheader_amount)from regreceiptheader where period_id=".$period_id." and familydt_id=".$familydt_id;
				$resultremaining=mysql_query($queryremaining, $connection);
				$rowr=mysql_fetch_array($resultremaining);
				$remainingbalance=($total-$rowr[0]);
				$remainingbalance=number_format($remainingbalance, $DecimalBase1, '.', ',');
				$total=number_format($total, $DecimalBase, '.', ',');
				//$remainingbalance=($total-$sumpayment);

				
				echo"<tr height='20px'><td colspan='7'><hr></td></tr>";
				//echo $total." ".$rowr[0];
				
				echo"<tr><td align='right'  colspan='4'><b><i><font color=red>Total : &nbsp;   <input type='hidden' name='total' value='$total' readonly>$total $base1</td><td align='center'><b>&nbsp;&nbsp;&nbsp;Remaining:</b></td><td ><b>$remainingbalance $base1</b></td></tr>";

				echo"</table></div></td></tr>";
					echo"</table></td><td id='search-content3' style='height:34px; width:31px;'>&nbsp;</td></tr>";
				echo"<tr><td id='search-bottom1' style='height:34px; width:31px;'>&nbsp;</td>
						<td id='search-bottom2' style='height:34px; width:31px;'>&nbsp;</td>
						<td id='search-bottom3' style='height:34px; width:31px;'>&nbsp;</td></tr>";
				echo"</table></td></tr>";

					echo"<br><br></table>";

//echo"<br><br></table>";


















//}
	
}		
		echo"</table></td></tr>";
		
	
	  echo"   <tr height='30'><td colspan='1' align='center' id='content-bottom' ></td></tr>";  
	  echo"</table>";
	  
	  echo"</form></body></html>";

	  
	  
function HasDuesTillNow($studentid,$fesstemplatename,$familydt_id,$connection){

//echo $fesstemplatename." ".$familydt_id."<br>";
//$q1 = " select sum(ifnull(feedeferredpayment_amount,0)) from feesdeferredpayments where student_id in ( select student_id from students where familyDt_idfather = $familydt_id) 
if($dist_receiptdt == 1)
	$q1 = " select sum(ifnull(feedeferredpayment_amount,0)
		- if(ifnull(FeeDeferredPayment_discountamount,0)=0,feedeferredpayment_amount*ifnull(FeeDeferredPayment_discountper,0)/100,FeeDeferredPayment_discountamount)
		- if(ifnull(FeeDeferredPayment_finanaidamount,0)=0,feedeferredpayment_amount*ifnull(FeeDeferredPayment_finanaidper,0)/100,FeeDeferredPayment_finanaidamount)
		) from feesdeferredpayments where student_id = $studentid 
		and FeeTemplateDt_name = $fesstemplatename
		and FeeDeferredvalue_date <= now()";
$q1 = " select sum(ifnull(feedeferredpayment_amount,0)) from feesdeferredpayments where student_id = $studentid 
		and FeeTemplateDt_name = $fesstemplatename
		and FeeDeferredvalue_date <= now()";

$result1=mysql_query($q1,$connection) or die(mysql_error());
$row1 = mysql_fetch_row($result1);
if($row1[0]=='')
	$row1[0]=0;
					
/*$q2= "select sum(ifnull(regreceiptdt_amount,0))
		from  regreceiptdt,regreceipt 
		where regreceiptdt.regreceipt_id = regreceipt.regreceipt_id 
		and regreceipt.student_id in ( select student_id from students where familyDt_idfather = $familydt_id)
		and tuitionfees_id = $fesstemplatename ";*/
$q2= "select sum(ifnull(regreceiptdt_amount,0))
		from  regreceiptdt,regreceipt 
		where regreceiptdt.regreceipt_id = regreceipt.regreceipt_id 
		and regreceipt.student_id = $studentid
		and tuitionfees_id = $fesstemplatename ";
$result2=mysql_query($q2,$connection) or die(mysql_error());
$row2 = mysql_fetch_row($result2);
if($row2[0]=='')
	$row2[0]=0;
   
  //echo $q1.":".$row1[0].":".$row2[0]."<br>";
  
return $row1[0]-$row2[0];


}

function GetAmount($student_id,$fesstemplatename,$familydt_id,$feesname,$amount1,$amount2,$period_id,$remaining_from_prev_deferred,$connection,$numcheck,$regreceiptheader_date,$class_id){
$today=date('Y-m-d');
if($regreceiptheader_date=='')
	$regreceiptheader_date = $today;
$query = "  select  tuitionfees_id,sum(ifnull(regreceiptdt_amount,0)) regreceiptdt_amount
								from  regreceiptdt,regreceipt 
								where regreceiptdt.regreceipt_id = regreceipt.regreceipt_id 
								and regreceipt.student_id = $student_id
								and period_id = $period_id
								and tuitionfees_id =  $fesstemplatename
								group by tuitionfees_id";	

//echo $query;
$result3=mysql_query($query,$connection) or die(mysql_error());
$row3 = mysql_fetch_row($result3);
$amountpaid = $row3[1];
if($amountpaid=='')		 $amountpaid = 0;

						if($numcheck>0)
							$query = " 	select sum(feedeferredpayment_amount 
								- if(ifnull(FeeDeferredPayment_discountamount,0)=0,feedeferredpayment_amount*ifnull(FeeDeferredPayment_discountper,0)/100,FeeDeferredPayment_discountamount)
								- if(ifnull(FeeDeferredPayment_finanaidamount,0)=0,feedeferredpayment_amount*ifnull(FeeDeferredPayment_finanaidper,0)/100,FeeDeferredPayment_finanaidamount)
							)
								from feesdeferredpayments
								where student_id = $student_id
								and feesdeferredpayments.FeeTemplateDt_name = $fesstemplatename
								group by feesdeferredpayments.FeeTemplateDt_name";	
							else	
							$query=" select sum(FeeTemplate_amount)
													from feestemplatestudentdt,feestemplate
													where class_id= ".$class_id."
													and feestemplatestudentdt.FeeTemplate_id = feestemplate.FeesTemplate_id
													and (FeesTemplate_startdate <= '$regreceiptheader_date'	and ifnull(FeesTemplate_enddate,'$regreceiptheader_date') >= '$regreceiptheader_date')
													and FeeTemplateDt_name = $fesstemplatename ";
								//echo $query;
								//exit;
$result3=mysql_query($query,$connection) or die(mysql_error());
$row3 = mysql_fetch_row($result3);
$totalamount = $row3[0] ;
if($totalamount=='')		 $totalamount = 0;
								
$remainingamount = $totalamount - $amountpaid ;
//echo $remainingamount; echo "<br>";
//echo $query."<br>";				
							if($numcheck>0)
								$query = "select sum(feedeferredpayment_amount
									- if(ifnull(FeeDeferredPayment_discountamount,0)=0,feedeferredpayment_amount*ifnull(FeeDeferredPayment_discountper,0)/100,FeeDeferredPayment_discountamount)
									- if(ifnull(FeeDeferredPayment_finanaidamount,0)=0,feedeferredpayment_amount*ifnull(FeeDeferredPayment_finanaidper,0)/100,FeeDeferredPayment_finanaidamount)
								)/(select sum(feedeferredpayment_amount
									- if(ifnull(FeeDeferredPayment_discountamount,0)=0,feedeferredpayment_amount*ifnull(FeeDeferredPayment_discountper,0)/100,FeeDeferredPayment_discountamount)
									- if(ifnull(FeeDeferredPayment_finanaidamount,0)=0,feedeferredpayment_amount*ifnull(FeeDeferredPayment_finanaidper,0)/100,FeeDeferredPayment_finanaidamount)
							)
								from feesdeferredpayments,fees
								where student_id = $student_id
								and fees.fee_id=feesdeferredpayments.fee_id
								and period_id = $period_id
								And FeeTemplateDt_name in ($feesname) 
								group by student_id) * 100 AS percentage
								from feesdeferredpayments,fees
								where student_id = $student_id
								and fees.fee_id=feesdeferredpayments.fee_id
								and period_id = $period_id
								and feesdeferredpayments.FeeTemplateDt_name = $fesstemplatename
								group by feesdeferredpayments.FeeTemplateDt_name";	
								else $query=" select sum(FeeTemplate_amount) / ( Select sum(FeeTemplate_amount)
										from feestemplatestudentdt,feestemplate
										where class_id= ".$class_id."
										and feestemplatestudentdt.FeeTemplate_id = feestemplate.FeesTemplate_id
										and (FeesTemplate_startdate <= '$regreceiptheader_date'	and ifnull(FeesTemplate_enddate,'$regreceiptheader_date') >= '$regreceiptheader_date')
										and FeeTemplateDt_name in ($feesname) 
										) * 100  AS percentage	
										from feestemplatestudentdt,feestemplate
										where class_id= ".$class_id."
										and feestemplatestudentdt.FeeTemplate_id = feestemplate.FeesTemplate_id
										and (FeesTemplate_startdate <= '$regreceiptheader_date'	and ifnull(FeesTemplate_enddate,'$regreceiptheader_date') >= '$regreceiptheader_date')
										and FeeTemplateDt_name = $fesstemplatename	";	
										
								//echo $query."<br>";
$result3=mysql_query($query,$connection) or die(mysql_error());
$row3 = mysql_fetch_row($result3);
$percentage = $row3[0];

if($percentage=='')		 $percentage = 0; 

$percentage_amount =  ($amount1 * $percentage / 100) + $remaining_from_prev_deferred;

//echo $percentage_amount."<br>";
if ($remainingamount < $percentage_amount)	{
	
	
	$aditionalamount = $percentage_amount - $remainingamount;
	$remaining_from_prev_deferred = $aditionalamount;
	//echo $percentage_amount."__".$percentage_amount."<br>";
	return $remainingamount.":".$aditionalamount;
	
	}
else { 
//	echo $percentage_amount."<br>";
	return $percentage_amount.":"."0";
	
	}
	
}

function GetAmount2($student_id,$fesstemplatename,$familydt_id,$feesname,$defferednumbr,$feesnamedeffer,$headeramount,$amount1,$amount2,$period_id,$remaining_from_prev_deferred,$connection,$numcheck,$regreceiptheader_date,$class_id){
$today=date('Y-m-d'); 
if($regreceiptheader_date=='')
	$regreceiptheader_date = $today;
$query = "  select  tuitionfees_id,sum(ifnull(regreceiptdt_amount,0)) regreceiptdt_amount
								from  regreceiptdt,regreceipt 
								where regreceiptdt.regreceipt_id = regreceipt.regreceipt_id 
								and regreceipt.student_id = $student_id
								and period_id = $period_id
								and tuitionfees_id =  $fesstemplatename
								group by tuitionfees_id";	

//echo $query;
$result3=mysql_query($query,$connection) or die(mysql_error());
$row3 = mysql_fetch_row($result3);
$amountpaid = $row3[1];
if($amountpaid=='')		 $amountpaid = 0;
							
						/* if($numcheck>0){
							if($feesnamedeffer == $defferednumbr)
							$query = "select feedeferredpayment_amount 
								- if(ifnull(FeeDeferredPayment_discountamount,0)=0,feedeferredpayment_amount*ifnull(FeeDeferredPayment_discountper,0)/100,FeeDeferredPayment_discountamount)
								- if(ifnull(FeeDeferredPayment_finanaidamount,0)=0,feedeferredpayment_amount*ifnull(FeeDeferredPayment_finanaidper,0)/100,FeeDeferredPayment_finanaidamount)
							
								from feesdeferredpayments
								where student_id = $student_id
								and feesdeferredpayments.FeeTemplateDt_name = $fesstemplatename
								group by feesdeferredpayments.FeeTemplateDt_name";	
						}else	
							$query=" select sum(FeeTemplate_amount)
									from feestemplatestudentdt,feestemplate
									where class_id= ".$class_id."
									and feestemplatestudentdt.FeeTemplate_id = feestemplate.FeesTemplate_id
									and (FeesTemplate_startdate <= '$regreceiptheader_date'	and ifnull(FeesTemplate_enddate,'$regreceiptheader_date') >= '$regreceiptheader_date')
									and FeeTemplateDt_name = $fesstemplatename "; */
if($feesnamedeffer == $defferednumbr){
							$query = "select feedeferredpayment_amount 
								- if(ifnull(FeeDeferredPayment_discountamount,0)=0,feedeferredpayment_amount*ifnull(FeeDeferredPayment_discountper,0)/100,FeeDeferredPayment_discountamount)
								- if(ifnull(FeeDeferredPayment_finanaidamount,0)=0,feedeferredpayment_amount*ifnull(FeeDeferredPayment_finanaidper,0)/100,FeeDeferredPayment_finanaidamount)
								from feesdeferredpayments
								where student_id = $student_id
								and feesdeferredpayments.FeeTemplateDt_name = $fesstemplatename
								group by feesdeferredpayments.FeeTemplateDt_name";								

							//echo $query;
								//exit;
$result3=mysql_query($query,$connection) or die(mysql_error());
$row3 = mysql_fetch_row($result3);
$totalamount = $row3[0] ;}
if($totalamount=='')		 $totalamount = 0;
								
$remainingamount = $totalamount - $amountpaid ;
$remainingamount2 = $totalamount - $amountpaid ;
//echo $remainingamount; echo "<br>";
//echo $query."<br>";				
							if($numcheck>0)
								$query = "select sum(feedeferredpayment_amount
									- if(ifnull(FeeDeferredPayment_discountamount,0)=0,feedeferredpayment_amount*ifnull(FeeDeferredPayment_discountper,0)/100,FeeDeferredPayment_discountamount)
									- if(ifnull(FeeDeferredPayment_finanaidamount,0)=0,feedeferredpayment_amount*ifnull(FeeDeferredPayment_finanaidper,0)/100,FeeDeferredPayment_finanaidamount)
								)/(select sum(feedeferredpayment_amount
									- if(ifnull(FeeDeferredPayment_discountamount,0)=0,feedeferredpayment_amount*ifnull(FeeDeferredPayment_discountper,0)/100,FeeDeferredPayment_discountamount)
									- if(ifnull(FeeDeferredPayment_finanaidamount,0)=0,feedeferredpayment_amount*ifnull(FeeDeferredPayment_finanaidper,0)/100,FeeDeferredPayment_finanaidamount)
							)
								from feesdeferredpayments,fees
								where student_id = $student_id
								and fees.fee_id=feesdeferredpayments.fee_id
								and period_id = $period_id
								And FeeTemplateDt_name in ($feesname) 
								group by student_id) * 100 AS percentage
								from feesdeferredpayments,fees
								where student_id = $student_id
								and fees.fee_id=feesdeferredpayments.fee_id
								and period_id = $period_id
								and feesdeferredpayments.FeeTemplateDt_name = $fesstemplatename
								group by feesdeferredpayments.FeeTemplateDt_name";	
								else $query="select sum(FeeTemplate_amount) / ( Select sum(FeeTemplate_amount)
										from feestemplatestudentdt,feestemplate
										where class_id= ".$class_id."
										and feestemplatestudentdt.FeeTemplate_id = feestemplate.FeesTemplate_id
										and (FeesTemplate_startdate <= '$regreceiptheader_date'	and ifnull(FeesTemplate_enddate,'$regreceiptheader_date') >= '$regreceiptheader_date')
										and FeeTemplateDt_name in ($feesname) 
										) * 100  AS percentage	
										from feestemplatestudentdt,feestemplate
										where class_id= ".$class_id."
										and feestemplatestudentdt.FeeTemplate_id = feestemplate.FeesTemplate_id
										and (FeesTemplate_startdate <= '$regreceiptheader_date'	and ifnull(FeesTemplate_enddate,'$regreceiptheader_date') >= '$regreceiptheader_date')
										and FeeTemplateDt_name = $fesstemplatename	";	
										
										
													
													
								//echo $query."<br>";
$result3=mysql_query($query,$connection) or die(mysql_error());
$row3 = mysql_fetch_row($result3);
$percentage = $row3[0];

if($percentage=='')		 $percentage = 0; 
if($totalamount == 0) $percentage_amount = 0;
else $percentage_amount =  ( $headeramount * $totalamount) / $amount1; 
//+ $remaining_from_prev_deferred;
//$percentage_amount = 600000+ $remaining_from_prev_deferred;
//	echo $headeramount."*".$totalamount."/".$amount1; echo "<br>";

//echo $amount1."<br>";

if ($remainingamount < $percentage_amount)	{
	

	$aditionalamount = $percentage_amount - $remainingamount;
	$remaining_from_prev_deferred = $aditionalamount;
	 $carryover = (( $headeramount * $remainingamount) / $amount1) - $remainingamount ; //echo $headeramount."*".$remainingamount."/".$amount1; echo "<br>";
	 //$carryover = $carryover;
	//echo $remainingamount."__".$percentage_amount."<br>";
	if($percentage_amount != 0)
	return $remainingamount.":".$aditionalamount.":".$carryover;
	else return $percentage_amount.":".$aditionalamount.":".$carryover;
	}
else { 
//	echo $percentage_amount."<br>";
	return $percentage_amount.":"."0";
	
	}
	
}


function calculate_remaining($FeesTemplatename_id,$class_id,$student_id,$period_id,$connection){

$query = " select sum(FeeTemplateDeferredPayment_amount) as AmounttillNow
										from feestemplatedeferredpayments
										inner join feestemplate on feestemplate.feestemplate_id=feestemplatedeferredpayments.FeeTemplate_id
										inner join feestemplatenames on feestemplatenames.FeesTemplatename_id=feestemplatedeferredpayments.FeeTemplateDt_name
										inner join classes on classes.class_id=feestemplate.class_id
										where feestemplate.class_id= $class_id
										and feestemplatenames.FeesTemplatename_id = $FeesTemplatename_id
										and now() between FeesTemplate_startdate and FeesTemplate_enddate
										";
				//echo $query; echo "<br>";						
							$resultamount=mysql_query($query,$connection) or die(mysql_error());
							$resamount = mysql_fetch_row($resultamount);
							$numtempdeferred=mysql_num_rows($resultamount);
							$deferredamounts = $resamount[0];
							if($deferredamounts=='') $return = 1;
							if($deferredamounts=='') $deferredamounts=0;
							
							
							$query = " select sum(regreceiptdt_amount) as AmounttillNow
										from regreceipt,regreceiptdt
										where regreceipt.period_id = $period_id 
										and regreceipt.student_id = $student_id
										and regreceipt.regreceipt_id = regreceiptdt.regreceipt_id
										and regreceiptdt.tuitionfees_id = $FeesTemplatename_id";
							//echo $query;
							$resultamount=mysql_query($query,$connection) or die(mysql_error());
							$resamount = mysql_fetch_row($resultamount);
							$receiptamounts = $resamount[0];
							if($receiptamounts=='') $receiptamounts=0;
							//echo $deferredamounts - $receiptamounts; echo "<br>";
							if($return==1)
							return 1;
							else
							return $deferredamounts - $receiptamounts;

}	


function number_unformat($number, $force_number, $dec_point, $thousands_sep) {
	if ($force_number) {
		$number = preg_replace('/^[^\d]+/', '', $number);
	} else if (preg_match('/^[^\d]+/', $number)) {
		return false;
	}
	$type = (strpos($number, $dec_point) === false) ? 'int' : 'float';
	$number = str_replace(array($dec_point, $thousands_sep), array('.', ''), $number);
	settype($number, $type);
	return $number;
}						
	
?>