var Loans = new LoansList();
var STDERR = ""; 
var RightRateRate = 5.625; //rih-rayh

function addLoan(principal, interest, consolidate, type) { //add a loan to the Loan list

  var timestamp = new Date(); //think "UID" for loans
  var myLoan = new Loan(principal, interest, consolidate, type, timestamp.getTime());
  if (document.loanAdder && myLoan.isValid()) {document.loanAdder.principal.value = "";}
  if (document.loanAdder && myLoan.isValid()) {document.loanAdder.interest.value = "";}
  return Loans.add(myLoan);
}
 
function setScale(myFloat,scale){  //sets the precision of floating point number 'myFloat' to the value defined by 'scale' 
	FloatVal = parseFloat(Math.round(myFloat * parseInt(Math.pow(10,scale)))/parseInt(Math.pow(10,scale)));
	return FloatVal;
}

function formatNumber(num, type, locale) { //turn a number into currency. 
  //for now we throw away type... we assume 'currency',
  //for now we throw away 'locale'... we assume US for locale
  
  if(isNaN(num))
    num = "0";
  sign = (num == (num = Math.abs(num)));
  num = Math.floor(num*100+0.50000000001);
  cents = num%100;
  num = Math.floor(num/100).toString();
  if(cents<10)
    cents = "0" + cents;
  for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
    num = num.substring(0,num.length-(4*i+3))+','+
      num.substring(num.length-(4*i+3));
  return (((sign)?'':'-') + '$' + num + '.' + cents);
}

function getAggregateCostTotal(term) { //get the original total cost to repay all loans over the timespan 'term'

  if (Loans.getLength() > 0 ) {
    var totalLoanDebt = 0;
    for (var i = 0 ; i < Loans.getLength() ; i++ ) {
      if (Loans.getElementAt(i).isConsolidate()) {
	var myLoan = Loans.getElementAt(i);
	var Amortizer = new amortizer(myLoan.getPrincipal(), myLoan.getInterest(),term);
	totalLoanDebt += Amortizer.getBalance();
      }
    }
    return totalLoanDebt;
  } else {
    return 0;
  }

}
function getAggregateMonthlyPayment(term) { //get the aggregate monthly payment of each original loan for the timespan 'term'

  if (Loans.getLength() > 0 ) {
    var totalLoanDebt = 0;
    for (var i = 0 ; i < Loans.getLength() ; i++ ) {
      if (Loans.getElementAt(i).isConsolidate()) {
	var myLoan = Loans.getElementAt(i);
	var Amortizer = new amortizer(myLoan.getPrincipal(), myLoan.getInterest(),term);
	totalLoanDebt += Amortizer.getMonthlyPayment();
      }
    }
    return totalLoanDebt;
  } else {
    return 0;
  }

}
	      
function getLoanType(myElement) { //tell me what type of loan is selected in the radio-box group specified by 'myElement'
  for ( var i = 0 ; i < myElement.length; i++) {
    if (myElement[i].checked == true) {
      return myElement[i].value
	}
  }
}

function removeLoan(loanID) { //remove a loan from the Loan List in the document tree, and from the Loans collection in the script
  //   alert("Removing Loan" );
  var toRemove = document.getElementById("loanID" + loanID) ;
  oldNode = document.getElementById("loanListBody").removeChild(toRemove);						       
  Loans.remove(loanID);
  summarize();
	
}

function removeAllLoans() {
  var theLoans = new Array();  
  for (var i = 0 ; i < Loans.getLength(); i++ ) {
    theLoans[i] = Loans.getElementAt(i).getTimestamp();
  }
  for (var i = 0; i < theLoans.length; i++ ) {
    removeLoan(theLoans[i])
      }
}

function summarize() { //show the loan summary info based on the loans the user added.
  document.debtSummary.totalBalance.value = formatNumber(Loans.getTotal());
  document.debtSummary.consolidationBalance.value = formatNumber(Loans.getConsolidationTotal());
  if (Loans.isRightRate()) {
    document.debtSummary.consolidationRate.value = RightRateRate;
    //document.debtSummary.useDiscount.checked = false;
    //document.debtSummary.useDiscount.disabled = true;
    //document.debtSummary.useAutoDebit.checked = false;
    //document.debtSummary.useAutoDebit.disabled = true;
  } else {
    document.debtSummary.consolidationRate.value = Loans.getRate();
    //document.debtSummary.useDiscount.disabled = false;
    //document.debtSummary.useAutoDebit.disabled = false;
  }
  document.debtSummary.consolidationTerm.value = Loans.getTermYears(); 

}

function updateList(option) { //uses DOM to create new nodes in the document tree for each loan you add.
  if (Loans.getLength() > 0 ) { //don't write no loans [literally]
    if (option != "rateonly") {
      var List = document.getElementById("loanListBody");
      var LoanRow = document.createElement("tr");
      var paymentCell = document.createElement("td");
      var paymentData = document.createTextNode(formatNumber(Loans.getLoan(Loans.getLength() - 1).getPrincipal()));
      paymentCell.appendChild(paymentData);
      var interestCell = document.createElement("td");
      var interestData = document.createTextNode( setScale(Loans.getLoan(Loans.getLength() - 1).getInterest(),4) + "%");
      interestCell.appendChild(interestData);
      var typeCell = document.createElement("td");
      var typeData = document.createTextNode(Loans.getLoan(Loans.getLength() - 1).getType());
      typeCell.appendChild(typeData);
      var consolidateCell = document.createElement("td");
      var consolidateData = document.createTextNode(Loans.getLoan(Loans.getLength() - 1).isConsolidateYesNo());
      var removeImg = document.createElement("img");
      removeImg.setAttribute("src","http://edfed.com/calculator/images/buttons/remove.gif")
	removeImg.setAttribute("onClick","removeLoan(" + Loans.getLoan(Loans.getLength() - 1).getTimestamp() + ")");
      removeImg.style.pointer = "pointer,arrow,hand";
      removeImg.style.verticalAlign = "text-top";
      removeImg.style.paddingLeft = "10px";
      consolidateCell.appendChild(consolidateData);
      consolidateCell.appendChild(removeImg);
      if (removeImg.outerHTML) { //hack for Internet Explorer. Otherwise DOM properties never get 'activated' in the render-tree
        removeImg.outerHTML = removeImg.outerHTML;
      }      
      consolidateCell.setAttribute("valign","middle");

      LoanRow.appendChild(paymentCell);
      LoanRow.appendChild(interestCell);
      LoanRow.appendChild(typeCell);
      LoanRow.appendChild(consolidateCell);
      LoanRow.setAttribute("id", "loanID" + Loans.getLoan(Loans.getLength() - 1).getTimestamp());
	       
      List.appendChild(LoanRow);

    }
    summarize();
  }
}



function Amortize(principal, rate, years,discount,ach) { //show the loan information. This probably should not be called 'Amortize'
 var DEBUG = false;
 if (document.debug) DEBUG = true; 
 if(DEBUG) document.debug.out.value = " ";

  if (parseFloat(principal.toString().replace(/\$|\,/g,'')) > 0) {
    
  	var myPrincipalValue =  parseFloat(principal.toString().replace(/\$|\,/g,''));
  	var OnePercentOffMonths = 36;
  	if (myPrincipalValue >= 20000) { 
      OnePercentOffMonths = 48;
    } else {
        OnePercentOffMonths = 36; //MPRates have their own matrix, so use that
    }
  	
    /*if (parseFloat(principal.toString().replace(/\$|\,/g,'')) < 20000) {
      document.getElementById("OnePercentIneligible").style.display="block";
    } else {
      document.getElementById("OnePercentIneligible").style.display="none";
    }*/
	
    var Amortization = new amortizer(principal, rate, years) ;
    Amortization.setOnePercentOff(discount);
    Amortization.setOnePercentOffStart(OnePercentOffMonths);
    Amortization.setACH(ach);
    Amortization.setSchedule();
    //var LevDiscount =  Amortization.getEarlyPayoffSavings(36,discount,ach);
  	
    var prevBal = setScale(getAggregateCostTotal(years),2);
    var prevPmt = setScale(getAggregateMonthlyPayment(10),2); //10 year term (getAgMoPay(10) for FFELP. 
  
    if (prevBal == parseFloat("0.0")) {alert("You either have no loans to consolidate or your Loan List is empty.\n" +
					     "You may still use the 'Consolidation Loan Summary' fields to calculate " +
					     "repayment, but we cannot list how much you may save with our loan.");
    }
  
    

    /*var levIntBal = document.createTextNode(formatNumber(setScale(Amortization.getInterestBalance(),2)));
    oldLevIntBal = document.getElementById("levelInterestBal").childNodes[0];
    document.getElementById("levelInterestBal").replaceChild(levIntBal,oldLevIntBal);*/
	
    var levOldPmt = document.createTextNode(formatNumber(setScale(prevPmt,2)));
    oldLevOldPmt = document.getElementById("levelOldPayment").childNodes[0];
    document.getElementById("levelOldPayment").replaceChild(levOldPmt,oldLevOldPmt);
  
    var levPmt = document.createTextNode(formatNumber(setScale(Amortization.getMonthlyPayment(),2)));
    oldLevPmt = document.getElementById("levelPayment").childNodes[0];
    document.getElementById("levelPayment").replaceChild(levPmt,oldLevPmt);
    
    var levelMonthlySaving = document.createTextNode(formatNumber(setScale(prevPmt-Amortization.getMonthlyPayment(),2)));
   	if((prevPmt-Amortization.getMonthlyPayment()) < 0)
    {
    	document.getElementById("levelMonthlySaving").parentNode.parentNode.style.display = "none";
    }
    else
    {
    	oldlevelMonthlySaving = document.getElementById("levelMonthlySaving").childNodes[0];
    	document.getElementById("levelMonthlySaving").replaceChild(levelMonthlySaving,oldlevelMonthlySaving);
    	document.getElementById("levelMonthlySaving").parentNode.parentNode.style.display = "block";
    }
    
    /*
    var ltot = setScale(Amortization.getInterestBalance() + Amortization.getPrincipal(),2)
    var levelTotal = document.createTextNode(formatNumber(ltot ));
    oldLevelTotal = document.getElementById("levelTotalBal").childNodes[0];
    document.getElementById("levelTotalBal").replaceChild(levelTotal,oldLevelTotal);

    var levelOldTotal = document.createTextNode(formatNumber(prevBal ));
    oldLevelOldTotal = document.getElementById("levelOldTotalBal").childNodes[0];
    document.getElementById("levelOldTotalBal").replaceChild(levelOldTotal,oldLevelOldTotal);
    if (prevBal > 0 ) {
      var lSavings = prevBal - ltot;
      if (lSavings > 0 ) {
	var levelSavings = document.createTextNode(formatNumber(lSavings ));
	oldLevelSavings = document.getElementById("levelSavings").childNodes[0];
	document.getElementById("levelSavings").replaceChild(levelSavings,oldLevelSavings);
	document.getElementById("levelSavings").parentNode.parentNode.style.display = "block";
	document.getElementById("levelOldTotalBal").parentNode.parentNode.style.display ="block";
      }else {
	document.getElementById("levelSavings").parentNode.parentNode.style.display = "none";
	document.getElementById("levelOldTotalBal").parentNode.parentNode.style.display = "none";
      }
    
    }*/
    if (years > 2) { //don't do this if for some reason someone wants to repay in less than 2 years
      /* select2 */

      var Amortization2 = new amortizer(Amortization.getPrincipal(),Amortization.getInterest(),(Amortization.getTermYears() - 2));
      Amortization2.setOnePercentOff(discount);
      Amortization2.setOnePercentOffStart(12);
      Amortization2.setACH(ach);
      Amortization2.setSchedule();
 
      var select2aOldPmt = document.createTextNode(formatNumber(setScale(prevPmt,2)));
      oldSelect2aOldPmt = document.getElementById("select2aOld").childNodes[0];
      document.getElementById("select2aOld").replaceChild(select2aOldPmt,oldSelect2aOldPmt);
    
      var select2aPmt = document.createTextNode(formatNumber(setScale(Amortization.getInterestOnlyMonthlyPayment(),2)));
      oldSelect2aPmt = document.getElementById("select2a").childNodes[0];
      document.getElementById("select2a").replaceChild(select2aPmt,oldSelect2aPmt);

      var select2bPmt = document.createTextNode(formatNumber(setScale(Amortization2.getMonthlyPayment(),2)));
      oldSelect2bPmt = document.getElementById("select2b").childNodes[0];
      document.getElementById("select2b").replaceChild(select2bPmt,oldSelect2bPmt);
      
      var select2MonthlySaving = document.createTextNode(formatNumber(setScale(prevPmt-Amortization2.getMonthlyPayment(),2)));
      
		if((prevPmt-Amortization2.getMonthlyPayment()) < 0)
		{
			document.getElementById("select2MonthlySaving").parentNode.parentNode.style.display = "none";
		}
		else
		{
			oldselect2MonthlySaving = document.getElementById("select2MonthlySaving").childNodes[0];
			document.getElementById("select2MonthlySaving").replaceChild(select2MonthlySaving,oldselect2MonthlySaving);
			document.getElementById("select2MonthlySaving").parentNode.parentNode.style.display = "block";
		}
      
      /*var select2Interest = document.createTextNode(formatNumber(setScale(Amortization2.getInterestBalance() + (Amortization.getInterestOnlyMonthlyPayment() * 24),2) ));
      oldSelect2Interest = document.getElementById("select2InterestBal").childNodes[0];
      document.getElementById("select2InterestBal").replaceChild(select2Interest,oldSelect2Interest);

      var s2tot = setScale(Amortization2.getInterestBalance() +  (Amortization.getInterestOnlyMonthlyPayment() * 24) + Amortization.getPrincipal(),2);
      var select2Total = document.createTextNode(formatNumber(s2tot ));
      oldSelect2Total = document.getElementById("select2TotalBal").childNodes[0];
      document.getElementById("select2TotalBal").replaceChild(select2Total,oldSelect2Total);

      var select2OldTotal = document.createTextNode(formatNumber(prevBal ));
      oldSelect2OldTotal = document.getElementById("select2OldTotalBal").childNodes[0];
      document.getElementById("select2OldTotalBal").replaceChild(select2OldTotal,oldSelect2OldTotal);
      if (prevBal > 0 ) {
		var s2savings = prevBal - s2tot  ;
	if (s2savings > 0) {
	  var select2Savings = document.createTextNode(formatNumber(s2savings ));
	  oldSelect2Savings = document.getElementById("select2Savings").childNodes[0];
	  document.getElementById("select2Savings").replaceChild(select2Savings,oldSelect2Savings);
	  document.getElementById("select2Savings").parentNode.parentNode.style.display = "block";
	  document.getElementById("select2OldTotalBal").parentNode.parentNode.style.display ="block";
	}else {
	  document.getElementById("select2Savings").parentNode.parentNode.style.display = "none";
	  document.getElementById("select2OldTotalBal").parentNode.parentNode.style.display = "none";
	}

      }*/
      /*  select5 */

      var select5aOldPmt = document.createTextNode(formatNumber(setScale(prevPmt,2)));
      oldSelect5aOldPmt = document.getElementById("select5aOld").childNodes[0];
      document.getElementById("select5aOld").replaceChild(select5aOldPmt,oldSelect5aOldPmt);

      var select5aPmt = document.createTextNode(formatNumber(setScale(Amortization.getInterestOnlyMonthlyPayment(),2)));
      oldSelect5aPmt = document.getElementById("select5a").childNodes[0];
      document.getElementById("select5a").replaceChild(select5aPmt,oldSelect5aPmt);
   
      var Select5Plan = new select5(Amortization2);
      var Select5bPrincPmt = Select5Plan.getYearsThreeToFivePrincipalPayment(Amortization2.getSchedule());
      var select5bPmt = document.createTextNode( formatNumber(setScale((Amortization.getInterestOnlyMonthlyPayment() + Select5bPrincPmt ),2)) );
      oldSelect5bPmt = document.getElementById("select5b").childNodes[0];
      document.getElementById("select5b").replaceChild(select5bPmt,oldSelect5bPmt);
      var Amortization5c = Select5Plan.getRemainingAmortizer();
      Amortization5c.setOnePercentOff(discount);
      Amortization5c.setOnePercentOffStart(1);
      Amortization5c.setACH(ach);
      Amortization5c.getSchedule();
   
 
      var select5cPmt = document.createTextNode(formatNumber(setScale(Amortization5c.getMonthlyPayment(),2)));
      oldSelect5cPmt = document.getElementById("select5c").childNodes[0];
      document.getElementById("select5c").replaceChild(select5cPmt,oldSelect5cPmt);
      
      /**************** Newly added field*****************************/
      var select5MonthlySaving = document.createTextNode(formatNumber(setScale(prevPmt - Amortization5c.getMonthlyPayment(),2)));
      if((prevPmt - Amortization5c.getMonthlyPayment()) < 0)
		{
			document.getElementById("select5MonthlySaving").parentNode.parentNode.style.display = "none";
		}
		else
		{
			oldselect5MonthlySaving = document.getElementById("select5MonthlySaving").childNodes[0];
      		document.getElementById("select5MonthlySaving").replaceChild(select5MonthlySaving,oldselect5MonthlySaving);
			document.getElementById("select5MonthlySaving").parentNode.parentNode.style.display = "block";
		}
      /**************** Newly added field*****************************/
      
      /*var select5IntNumeric = Amortization5c.getInterestBalance() + (Amortization.getInterestOnlyMonthlyPayment() * 24) + Select5Plan.getYearsThreeToFiveInterestPaid();
      var select5Interest = document.createTextNode(formatNumber(setScale(select5IntNumeric,2) ));
      oldSelect5Interest = document.getElementById("select5InterestBal").childNodes[0];
      document.getElementById("select5InterestBal").replaceChild(select5Interest,oldSelect5Interest);
      var s5tot = setScale( ( Amortization.getPrincipal() + select5IntNumeric),2);
      var select5Total = document.createTextNode(formatNumber(s5tot ));
      oldSelect5Total = document.getElementById("select5TotalBal").childNodes[0];
      document.getElementById("select5TotalBal").replaceChild(select5Total,oldSelect5Total);
      var select5OldTotal = document.createTextNode(formatNumber(prevBal ));
      oldSelect5OldTotal = document.getElementById("select5OldTotalBal").childNodes[0];
      document.getElementById("select5OldTotalBal").replaceChild(select5OldTotal,oldSelect5OldTotal);

      if (prevBal > 0 ) {
	var s5savings = prevBal - s5tot;
	if (s5savings > 0) {
	  var select5Savings = document.createTextNode(formatNumber(s5savings ));
	  oldSelect5Savings = document.getElementById("select5Savings").childNodes[0];
	  document.getElementById("select5Savings").replaceChild(select5Savings,oldSelect5Savings);
	  document.getElementById("select5Savings").parentNode.parentNode.style.display = "block";
	  document.getElementById("select5OldTotalBal").parentNode.parentNode.style.display ="block";
	}else {
	  document.getElementById("select5Savings").parentNode.parentNode.style.display = "none";
	  document.getElementById("select5OldTotalBal").parentNode.parentNode.style.display = "none";
	}
      }*/
 
    }
    return true;
  } else {

    return false;

  }
  



}

