// Consolidation JS File
   

//----------BEGIN GENERIC FUNCTIONS----------------------------------------------------------

function fnGetObj(name)
{ //Generic function to get object reference for most browsers

  if (document.getElementById)
  {
  	this.obj = document.getElementById(name);
	this.style = document.getElementById(name).style;
  }
  else if (document.all)
  {
	this.obj = document.all[name];
	this.style = document.all[name].style;
  }
  else if (document.layers)
  {
   	this.obj = document.layers[name];
   	this.style = document.layers[name];
  }
}

function fnValidateNumeric(fieldname)
{ //Validate a Field contains only valid numbers.

  var strValue = fieldname;

  var objRegExp  =  /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/;
  return objRegExp.test(strValue);
}

function fnTrimAll(strValue) 
{ //Remove leading and trailing spaces plus commas and dollar signs from provided string

  strValue = fnRemoveCommas(strValue);
  strValue = fnRemoveDollarSigns(strValue);
  var objRegExp = /^(\s*)$/;

  //check for all spaces
  if(objRegExp.test(strValue))
  {
    strValue = strValue.replace(objRegExp, '');
    if( strValue.length == 0)
    return strValue;
  }

  //check for leading & trailing spaces
  objRegExp = /^(\s*)([\W\w]*)(\b\s*$)/;
  if(objRegExp.test(strValue))
  {
    //remove leading and trailing whitespace characters
    strValue = strValue.replace(objRegExp, '$2');
  }

  return strValue;
}

function fnValidateInteger(fieldname)
{ //Validate a Field contains a valid integer number.

  var fieldObj = new fnGetObj(fieldname);
  var strValue = fieldObj.obj.value;
  strValue = fnTrimAll(strValue);

  var objRegExp  = /(^-?\d\d*$)/;
  return objRegExp.test(strValue);
}

function fnCheckField(fieldname)
{ //Check a Field (cannot be null, empty string, zero length, or string of blanks)
  
  var fieldObj = new fnGetObj(fieldname);
  var teststring = fieldObj.obj.value;

  teststring = fnTrimAll(teststring);
  if ((teststring == '') || (teststring == null) || (teststring.length == 0))
  {
    return false;
  }

  return true;
}

function fnValidatePosNum(fieldname)
{ //Validate a Number is Positive (including 0)

  var fieldObj = new fnGetObj(fieldname);
  var strValue = fieldObj.obj.value;
  strValue = fnTrimAll(strValue);

  return (parseInt(strValue,10)>=0); 
}


function fnRemoveCommas(strValue)
{  //Remove commas from string

  var objRegExp = /,/g; //search for commas globally
  
  //replace all matches with empty strings 
  return strValue.replace(objRegExp, '');
  
}

function fnRemoveDollarSigns(strValue)
{  //Remove dollar sign from string

  if(strValue.indexOf('$') >= 0)
  {
    strValue = strValue.substring(1, strValue.length);
  }
   return strValue;
}

function fnAddCommas(srcNumber)
{  //Add commas to number string

   var txtNumber = '' + srcNumber;
   if (isNaN(txtNumber) || txtNumber == "") {
      return srcNumber;
   }
   else 
   {
      var rxSplit = new RegExp('([0-9])([0-9][0-9][0-9][,.])');
      var arrNumber = txtNumber.split('.');
      arrNumber[0] += '.';
      do
      {
         arrNumber[0] = arrNumber[0].replace(rxSplit, '$1,$2');
      } 
      while (rxSplit.test(arrNumber[0]));
      if (arrNumber.length > 1)
      {
         return arrNumber.join('');
      }
      else
      {
      return arrNumber[0].split('.')[0];
      }
   }
}

function fnShowHide(fieldname, desiredaction)
{  //Function to Show or Hide a Field
   
   var fieldObj = new fnGetObj(fieldname);

   if (desiredaction == "Hide")
   {
      if (fieldObj.style.display != "none")
      {
         fieldObj.style.display = "none";
      }
   }
   
   if (desiredaction == "Show")
   {
      if (fieldObj.style.display == "none")
      {
         fieldObj.style.display = "";
      }
   }
}


function findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

function findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}

function fnShowNote(InfoText,obj,NoteHeight)
{
  var ToolTip = new fnGetObj("largenote");
  
  if (ToolTip.style.visibility=="visible") {
	ToolTip.style.visibility = "hidden";
  } 
  else {
	  
	  ToolTip.style.left = findPosX(obj);
	  ToolTip.style.top = findPosY(obj)-NoteHeight;
	
	  var ToolTipText = new fnGetObj("largenotetext");
	  ToolTipText.obj.innerHTML = "<font size=1 color='#000000' style='font-family:Verdana, Arial, Helvetica, sans-serif'>" + InfoText + "</font>";
	
	  ToolTip.style.visibility = "visible";
	  //window.status="visible";  
  }
  
}


function fnHideNote() {
   var ToolTip = new fnGetObj("largenote");
   ToolTip.style.visibility = "hidden"; 
   //window.status="hidden";  
}


function fnAddDollarSign(number, numdecimals)
{
	var output;
	var num = parseFloat(number);
	num = num.toFixed(numdecimals);
	
	var commas = fnAddCommas(num);
	
	if(number < 0)
	{
		//alert(commas);
		output = "-$" + commas.substring(1, commas.length);	
	}
	else
	{
		output = "$" + commas;	
	}
	
	return output;
}



function fnFormatInput(ref)
{
	//alert(ref.id);
	var ref = new fnGetObj(ref.id);
	var value = fnTrimAll(ref.obj.value);

	//Remove non-numeric characters; This is to prevent users from pasting a string.
	value = fnRemoveNonNumeric(value);

	//Remove unnecesary 0's from the input.
	value = fnRemoveLeadingZeros(value);

	//Add commas
	value = fnAddCommas(value);

	//Display the value on the textbox
	ref.obj.value = value;
	
	
}


function fnCheckInput(e, ref, count) //Check user's input | DO NOT ALLOW COMMAS
{
	
	/*
	Function will do the following:
		-Function checks every keystroke (onKeyPress event) for the set parameters below.
		-If the user presses a key that is not defined, the function will return false.
		-The function has a counter to limit the amount of characters the user can enter. 
		 This is useful when you want to format the text inside the textbox after the user enters data. Example: textbox maxlength='8', 
		 function limits user to 6 chartacters, so we have 2 characters available for commas, periods, etc. (need to do this for Safari and NS)
		-Function limits the user to only one period per textbox.
		
	List of ASCII codes:
	
		Symbol		Code
		------		----
		,		44
		.		46
		$		36
		<		60
		>		62
		0 - 9		48 - 57
		a - z		97 - 122
		A - Z		65 - 90
		backspace	8
		delete		127
		del (Mac)	63272
		tab		9
		Arrows		0
		
	For more symbols: http://www.ascii.cl/htmlcodes.htm
	*/
	
	var key = window.event ? e.keyCode : e.which; //Determine which key the user pressed
	//alert("key: " + key);
	//var keychar = String.fromCharCode(key);
	
	//If key pressed is one of the following, return true: 'delete', 'backspace', 'tab' 
	//This is a workaround for the MAC not allowing users to delete input once the limit (counter) reached 6.
	
	// delete (win)  backspace   --tab--    delete (Mac)  left arrow (Mac) right arrow (Mac)
	if(key == 127 || key == 8 || key ==9 || key == 63272 || key == 63234 || key == 63235) 
	{
		
		return true;
		fnCalculateCostofLoans(1);
	}
	else
	{
		var id = ref.id;
		//alert(ref.id);
		var element = new fnGetObj(id);
		var counter;
		counter = element.obj.value.length; //Count the number of characters in the text box
		//alert(counter);
		
		if (counter >= count) //If user enteres more than 6 characters return false and prevent user from entering more data
		{	
			if(key == 0) return true; //Allow Arrow Keys when the limit is reached
			else return false;				
		}
		else
		{

			// ------------------ Numbers-----------------------   --comma--      --period--    ---delete---  Backspace
			if ((key > 47 && key < 58) || (key == 0 || key == 8 || /*(key == 44) ||*/ (key == 46)) || key == 127 || key == 8) //Valid Input (numbers, commas, periods, backspace, delete
			{
				var elContent = element.obj.value; //Get textbox content
				//alert("elContent: " + elContent);
				
				if((key == 46) && elContent.indexOf(".") != -1) //If there is already a period on the input field, return false
				{
					return false;	
				}
				if(key == 0) return true; //Do not run the function if user presses the arrow keys
				else 
                                {
                                    timedelay = 500;

                                    setTimeout("fnCalculateCostofLoans(2);", timedelay); 
				    //delay: allows function to capture the entire value inputted; 
                                    //otherwise, last value entered is lost.
                                }
			}
			else //Invalid input, return false
			{
				return false;
			}
		}
	}
}

function fnCheckInput2(e, ref, count) //Check user's input | DO NOT allow periods or commas
{
	var key = window.event ? e.keyCode : e.which; //Determine which key the user pressed
	//alert("key: " + key);
	//var keychar = String.fromCharCode(key);
	
	//If key pressed is one of the following, return true: 'delete', 'backspace', 'tab' 
	//This is a workaround for the MAC not allowing users to delete input once the limit (counter) reached 6.
	
	// delete (win)  backspace   --tab--    delete (Mac)  left arrow (Mac) right arrow (Mac)
	if(key == 127 || key == 8 || key ==9 || key == 63272 || key == 63234 || key == 63235) 
	{
		return true;
		fnCalculateCostofLoans(3);
	}
	else
	{
		var id = ref.id;
		//alert(ref.id);
		var element = new fnGetObj(id);
		var counter;
		counter = element.obj.value.length; //Count the number of characters in the text box
		//alert(counter);
		
		if (counter >= count) //If user enteres more than 6 characters return false and prevent user from entering more data
		{	
			if(key == 0) return true; //Allow Arrow Keys when the limit is reached
			else return false;			
		}
		else
		{

			// ------------------ Numbers-----------------------   --comma--      --period--    ---delete---  Backspace
			if ((key > 47 && key < 58) || (key == 0 || key == 8 || (key == 44) /*|| (key == 46)*/) || key == 127 || key == 8) //Valid Input (numbers, commas, periods, backspace, delete
			{
				var elContent = element.obj.value; //Get textbox content
				//alert("elContent: " + elContent);
				
				/*
				if((key == 46) && elContent.indexOf(".") != -1) //If there is already a period on the input field, return false
				{
					return false;	
				}
				*/
				if(key == 0) return true; //Do not run the function if user presses the arrow keys
				else 
                                {

                                    timedelay = 500;

                                    setTimeout("fnCalculateCostofLoans(4);", timedelay); 
				    //delay: allows function to capture the entire value inputted; 
                                    //otherwise, last value entered is lost.
                                }
			}
			else //Invalid input, return false
			{
				return false;
			}
		}
	}

//clearTimeout(globalTimeout);
//globalTimeout = setTimeout("fnShowHide('loaderDiv', 'Show');", 100);
//globalTimeout = setTimeout("fnShowHide('loaderDiv2', 'Show');", 100);
}


function fnRemoveLeadingZeros(value)
{
	/*
	Function will do the following:
		-If there are zeros to the left of a number, it will remove all of them. Example: '00150' -> '150'
		-If there is a period and there are more than one zero to the left of it, it will remove all but one zero. Example: '00.50' - > '0.50'
		-If the value starts with a period, it will add a zero to the left of the period. Example: '.50' - > '0.50'
		-If the user entered one or more zeros in the input box, the value will default to one zero. Example: '000' -> '0'
		-If the last character is a period, the function will remove the period. Example: '5000.' - > '5000'
		
	Assumptions:
		-The user will only be allowed to enter ONE period in the text box. (fnCheckInput)
	*/
	
	
	val = value;
	
	var newVal = val;
	var nextVal;
	var prevVal;
	var currCharacter;
	
	if(val.indexOf(".") == 0) newVal = "0" + newVal; //If the value starts with a period, add a zero. Example: ".5" -> "0.5"
	//if(val.indexOf(".") == (val.length - 1)) newVal = newVal + "00";
	
	if(val.indexOf("0") != -1)
	{
		
		for(i = 0; i <= val.length - 1; i++)
		{
					
			if(val.charAt(i) == "0") //If current character is zero, start validation
			{
							
				prevVal = i-1;
				nextVal = i+1;
				
				if(prevVal < 0) prevVal = 0; //If previous value does not exist, make prevVal the current value
				
				if(val.charAt(prevVal) == "0")
				{
						
					if(i < val.indexOf(".")) //If the current character comes BEFORE the period
					{
						var curr = parseInt(i);
						var period = parseInt(val.indexOf("."));
					
						if((period - curr) <= 1)
						{
							break;	
						}
						else if((period - curr) > 1)
						{
							newVal = val.substring(nextVal);
						}
							
					}
					else
					{
						//alert(val.charAt(nextVal));
						if(val.charAt(nextVal) == "0")
						{
							newVal = val.substring(nextVal);
						}
						else if(val.charAt(nextVal) != "0")
						{
							newVal = val.substring(nextVal);
							break;
						}
			
					}
				
				}
				
			}
			else if(val.charAt(i) != "0")  //If current character is NOT zero, break loop
			{
				break;	
			}
			
		}
	}
	
	if(newVal.indexOf(".") == (newVal.length - 1)) newVal = newVal.substring(0, newVal.length - 1); //If the last character is a period, remove the period.
	if(newVal == "") newVal = 0; //If the user entered 1 or more zeros in the input field, default it to 1 zero
	
	return newVal;
}


function fnAddSpaces(value, spaces)
{
	var sOutput = "";
	var iCounter = 0;
	
	for(iChar = 0; iChar <= value.length - 1; iChar++)
	{
		sOutput += value.charAt(iChar);
		if (value.charAt(iChar) != " ") 
		{
			iCounter++;
			if (iCounter == spaces) 
			{
				iCounter = 0;
				sOutput += " ";
			}	
		} 
		else 
		{
			iCounter = 0;	
		}
		
	}	
	
	return sOutput;
}

function fnRemoveNonNumeric(value)
{
	var sOutput = "";
	
	for(l = 0; l <= value.length - 1; l++)
	{
			
		if (fnValidateNumeric(value.charAt(l)) == true || value.charAt(l) == ".") //If the character is numeric OR a period, add to output string
		{
			sOutput += value.charAt(l);
							
		} 
	
	}	
	//alert(sOutput);
	return sOutput;
}

function fnHideShowText(id, value, action)
{
	/*
	Insert the following parameters in the input element (textbox):
	
	onfocus=\"fnHideShowText(this.id, this.value, 'Hide')\" 
	onBlur=\"fnHideShowText(this.id, this.value, 'Show')\"
	
	*/
	
	var ref = new fnGetObj(id);
	var val = value;

	
	if(action == 'Hide') //User clicks on textbox (onFocus)
	{
		//alert("Hide");	
		ref.obj.className = 'txtbox';	
		if(value == pop19) //If textbox value = defaul value
		{
			val='';	
			ref.obj.value = val;
		}
	
	}
	else if (action == 'Show') //User clicks out of textbox (onBlur)
	{
		//alert("Show");
		if(value == '') 
		{
			val= pop19;
			ref.obj.className = 'txtboxGrey';
			ref.obj.value = val;
		}
		
	}
	
}


//----------END GENERIC FUNCTIONS----------------------------------------------------


//Global Variables

var numExistLoansDefault = 4;
var numExistAcctsDefault = 2;

var numExistLoans = numExistLoansDefault;
var numExistAccts = numExistAcctsDefault;

var ExistLoansArr = new Array();
var ExistAcctsArr = new Array();

var globalTimeout;
var labelArr = new Array();

var maxMonths;
var ConsLoanInfo;
var CurrLoanBalArr = new Array();
var ConsLoanBalArr = new Array();
var NetSavingsArr = new Array();
var NetLossArr_PosVals = new Array();
var resCurr = new Array();
var resNew = new Array();
var totalCurrPayment;
var totalCurrCost; 
var totalNewCost;
var SvngsRate;
var FedStateTaxRate;

//Use this variable to enable/disable print button and to "adjust" chart arrays
var totalAmtOwed = 0;

//Chart Type - this is used to modify the step in chart.js file
var chartType; 


//Graph variables
var graphDecimalsFlag; 
var label;
var ValScaler=1;
var graphDecimalsFlag2; 
var label2;
var ValScaler2=1;
var threshold=0;
var AbsMaxVal;


function fnAttachEvents()
{
	var formElements = new Array();
	formElements = document.getElementsByTagName('input');
	
	for(var i = 0; i < formElements.length; i++)
	{
		//if (id.search("c") > 0 || id.search("d") > 0)
	
		if(formElements[i].getAttribute("filter") == 'savings')
		{
			var id = formElements[i].id;
			//alert(id);
			id = id.toString();
			var el = new fnGetObj(id); 
			
			//Apply the onBlur events
			el.obj.onblur = function() 
			{
				fnFormatInput(this);
				//fnCalculateCostofLoans(5);
			} 
			/*
			//Apply the onKeyUp events
			el.obj.onKeyUp = function() 
			{
				fnCheckKeyUp(event, id);
			} 
			//Added this event to the input tags to fix Firefox issue on the Mac - event was not being added properly through this method
			/*
			//Apply onKeyPress events
			el.obj.onkeypress = function() 
			{
				return fnCheckInput(event, this);
			} 
			*/
			//alert("browser: " + BrowserDetect.browser + "\n" + "version: " + BrowserDetect.version + "\n" + "OS: " + BrowserDetect.OS);
		}
		
		if(formElements[i].getAttribute("filter") == 'debt')
		{
			var id = formElements[i].id;
			//alert(id);
			id = id.toString();
			var el = new fnGetObj(id); 
			
			//Apply the onBlur events
			el.obj.onblur = function() 
			{
				fnFormatInput(this);
				//fnCalculateCostofLoans(7);
			} 
			/*
			//Apply the onKeyUp events
			el.obj.onKeyUp = function() 
			{
				fnCheckKeyUp(event, id);
			} 
			//Added this event to the input tags to fix Firefox issue on the Mac - event was not being added properly through this method
			/*
			//Apply onKeyPress events
			el.obj.onkeypress = function() 
			{
				return fnCheckInput(event, this);
			} 
			*/
		}
	}


        //After page loads and events are added, reset the Consolidation Loan Type fields
	fnConsLoanEvents(false);


	//After page loads and events are added, perform calculations to populate table and graph
	fnCalculateCostofLoans(8);
}

function fnCheckKeyUp(e, id)
{
	var key = window.event ? e.keyCode : e.which; //Determine which key the user pressed
	//alert("key: " + key);
	//var keychar = String.fromCharCode(key);
	
	//If key pressed is one of the following, return true: 'delete', 'backspace', 'tab' 
	//This is a workaround for the MAC not allowing users to delete input once the limit (counter) reached 6.
	
	if(key == 37 || key == 39) return true;
	// delete (win)  backspace   backspace    Left Arrow   Right arrow
	else if(key == 127 || key == 8 || key == 46 /*|| key == 37 || key == 39*/) 
	{
		var element = new fnGetObj(id);
		var counter;
		counter = element.obj.value.length; //Count the number of characters in the text box


                timedelay = 500;

                setTimeout("fnCalculateCostofLoans(9);", timedelay); 
		//delay: allows function to capture the entire value inputted; 
               //otherwise, last value entered is lost.

	}
	
}


function fnChangeStyle(id, color, fweight)
{
	var ref = new fnGetObj(id);
	ref.style.color = color;
	ref.style.fontWeight = fweight;
	
	var ref2 = new fnGetObj('print' + id);
	ref2.style.color = color;
	ref2.style.fontWeight = fweight;
}

function fnCheckLimits(element, value, limit, dir)
{
   if (dir == ">"){
	if(value > limit){ 
	   value = limit;
	   document.getElementById(element).value = limit;
	}
   }	else if (dir == "<"){
        if (value < limit){
           value = limit;
	   	   document.getElementById(element).value = limit;      
        }
   }
   return value;
}

function fnCalculateCostofLoans(callnum)
{  //  Calculate Cost of Loans and Break Even Point
   //  numExistLoans - Total Number of Existing Loans
   //  numExistAccts - Total Number of Existing Accounts

   //alert("CalculateCostofLoans Call " + callnum);
   ExistLoansArr = new Array();
   ExistAcctsArr = new Array();
   var idName;
   var inAmtOwed;
   var inMthsLeft;
   var inIntRate;

   
   var inConsLoanIntRate;
   var inConsLoanMthsToPayoff;
   var inConsLoanClosingCosts;
   var inConsLoanDiscPts;


   //Read in the Existing Loans
   for (count=0; count < numExistLoans; count++)
   {
      idName = "L" + (count+1);

      ExistLoansArr[count] = new Object();

      var refLoanType = new fnGetObj(idName + "Choice");
      ExistLoansArr[count].LoanType = refLoanType.obj.value;
      if (ExistLoansArr[count].LoanType == "E")
      {  //Education Loans are tax-deductible
         ExistLoansArr[count].deductible = true;
      }
      else
      {
         ExistLoansArr[count].deductible = false;
      }

      var refAmtOwed = new fnGetObj(idName + "a");
      inAmtOwed = refAmtOwed.obj.value;
      inAmtOwed = inAmtOwed.toString();
      inAmtOwed = fnRemoveCommas(inAmtOwed);
      inAmtOwed = parseFloat(inAmtOwed);
	  if(isNaN(inAmtOwed) || inAmtOwed == "") inAmtOwed = 0; //Prevents the NaN output in the results table
      ExistLoansArr[count].AmtOwed = inAmtOwed;

      var refIntRate = new fnGetObj(idName + "b");
      inIntRate = refIntRate.obj.value;
      inIntRate= fnCheckLimits(idName + "b", inIntRate, 25, ">");
	  if(isNaN(inIntRate) || inIntRate == "") inIntRate = 0;
      ExistLoansArr[count].IntRate = inIntRate;
	  //alert("ExistLoansArr["+count+"].IntRate: " + ExistLoansArr[count].IntRate);

      var refMthsLeft = new fnGetObj(idName + "c");
      inMthsLeft = refMthsLeft.obj.value; 
      inMthsLeft = fnCheckLimits(idName + "c", inMthsLeft , 360, ">");
	  inMthsLeft = fnCheckLimits(idName + "c", inMthsLeft , 1, "<");
      ExistLoansArr[count].MthsLeft = parseInt(inMthsLeft);
	  
	  totalAmtOwed += inAmtOwed;
   }
	
   //Read in the Existing Accounts
   for (count=0; count < numExistAccts; count++)
   {
      idName = "A" + (count+1);

      ExistAcctsArr[count] = new Object();

      var refAcctType = new fnGetObj(idName + "Choice");
      ExistAcctsArr[count].AcctType = refAcctType .obj.value;
      ExistAcctsArr[count].deductible = false;

      var refAmtOwed = new fnGetObj(idName + "a");
      inAmtOwed = refAmtOwed.obj.value;
      inAmtOwed = inAmtOwed.toString();
      inAmtOwed = fnRemoveCommas(inAmtOwed);
      inAmtOwed = parseFloat(inAmtOwed);
	  if(isNaN(inAmtOwed) || inAmtOwed == "") inAmtOwed = 0; //Prevents the NaN output in the results table
      ExistAcctsArr[count].AmtOwed = inAmtOwed;

      var refIntRate = new fnGetObj(idName + "b");
      inIntRate= refIntRate.obj.value; 
      inIntRate= fnCheckLimits(idName + "b", inIntRate, 25, ">");
	  if(isNaN(inIntRate) || inIntRate == "") inIntRate = 0;
      ExistAcctsArr[count].IntRate = inIntRate;
	  
	  totalAmtOwed += inAmtOwed;
   }
	
	
   //Read in the Consolidation Loan Info
    ConsLoanInfo = new Object();

   //get the radio button choice  - HEL, HELC, PL, PLC 
   ConsLoanInfo.LoanType= fnGetConsLoanType();

   var refConsLoanIntRate = new fnGetObj("CL1a");
   inConsLoanIntRate = refConsLoanIntRate.obj.value; 
   inConsLoanIntRate = fnCheckLimits("CL1a", inConsLoanIntRate, 25, ">");
   if(isNaN(inConsLoanIntRate) || inConsLoanIntRate == "" || inConsLoanIntRate == 0) inConsLoanIntRate = 0.0001; //Prevents the NaN output in the results table
   ConsLoanInfo.IntRate = inConsLoanIntRate;
   //alert(inConsLoanIntRate);


   var refConsLoanMthsToPayoff = new fnGetObj("CL2a");
   inConsLoanMthsToPayoff= refConsLoanMthsToPayoff.obj.value;
   inConsLoanMthsToPayoff= fnCheckLimits("CL2a", inConsLoanMthsToPayoff, 1, "<");
   inConsLoanMthsToPayoff= fnCheckLimits("CL2a", inConsLoanMthsToPayoff, 360, ">");
   ConsLoanInfo.MthsToPayoff = inConsLoanMthsToPayoff;

   if (ConsLoanInfo.LoanType == "HEL" || ConsLoanInfo.LoanType == "HELC")
   {  //For home equity loan and home equity line of credit, also need the closing costs & discount points
      var refConsLoanClosingCosts = new fnGetObj("CL3a");
      inConsLoanClosingCosts= refConsLoanClosingCosts.obj.value;
      inConsLoanClosingCosts= inConsLoanClosingCosts.toString();
      inConsLoanClosingCosts = fnRemoveCommas(inConsLoanClosingCosts);
      inConsLoanClosingCosts = parseFloat(inConsLoanClosingCosts);
	  if(isNaN(inConsLoanClosingCosts) || inConsLoanClosingCosts == "") inConsLoanClosingCosts = 0; //Prevents the NaN output in the results table
      ConsLoanInfo.ClosingCosts = inConsLoanClosingCosts;

      var refConsLoanDiscPts = new fnGetObj("CL4a");
      inConsLoanDiscPts= refConsLoanDiscPts.obj.value; 
      inConsLoanDiscPts= fnCheckLimits("CL4a", inConsLoanDiscPts, 10, ">");
      ConsLoanInfo.DiscPts = inConsLoanDiscPts;
      ConsLoanInfo.deductible = true;
   }
   else
   {
      ConsLoanInfo.ClosingCosts = 0;
      ConsLoanInfo.DiscPts = 0;
      ConsLoanInfo.deductible = false;
   }

   //Read Remaining Information
   //var refSavingsRate = new fnGetObj("saverate");
  // SvngsRate = refSavingsRate.obj.value; 
  // SvngsRate = fnCheckLimits("saverate", SvngsRate, 15, ">");
  //JRB.... Don't use SvngsRate for now
     SvngsRate = 0;

      var refTax = new fnGetObj("taxrate");
      FedStateTaxRate = refTax .obj.value;
      FedStateTaxRate = fnCheckLimits("taxrate", FedStateTaxRate, 50, ">");

//*************************************************//
//Now that we have the data - calculate the results//
//*************************************************//
	//maximum number of months to model - prime with consolidation loan term
	maxMonths = ConsLoanInfo.MthsToPayoff;  
	var totalCurrInterest = 0;
	var totalCurrDeduction = 0;
	var totalCurrSavings = 0;
	resCurr = new Array();
	resNew = new Array();
	var resRateCost = new Array();
	totalCurrPayment = 0;

	ConsLoanInfo.AmtOwed = 0;
	
	//calculate monthly payments for loans and accounts
	for (count=0; count < numExistLoans; count++)
	{
		ExistLoansArr[count].mRate = ExistLoansArr[count].IntRate/1200;
		ExistLoansArr[count].MthPymt = (ExistLoansArr[count].AmtOwed*ExistLoansArr[count].mRate)/(1-Math.pow(1+ExistLoansArr[count].mRate,-ExistLoansArr[count].MthsLeft));
		if (ExistLoansArr[count].MthsLeft > maxMonths) maxMonths = ExistLoansArr[count].MthsLeft;
		ExistLoansArr[count].tBal = ExistLoansArr[count].AmtOwed; //add entry for modeling balance
		ConsLoanInfo.AmtOwed += ExistLoansArr[count].tBal;
		if (isNaN(ExistLoansArr[count].MthPymt)) ExistLoansArr[count].MthPymt = 0;
		totalCurrPayment += ExistLoansArr[count].MthPymt;
	}
	for (count=0; count < numExistAccts; count++)
	{
		//use length of consolidation loan period for payoff period for accounts
		ExistAcctsArr[count].mRate = ExistAcctsArr[count].IntRate/1200;
      		ExistAcctsArr[count].MthPymt = (ExistAcctsArr[count].AmtOwed*ExistAcctsArr[count].mRate)/(1-Math.pow(1+ExistAcctsArr[count].mRate,-36)); //previous period was ConsLoanInfo.MthsToPayoff
		ExistAcctsArr[count].tBal = ExistAcctsArr[count].AmtOwed; //add entry for modeling balance
		ConsLoanInfo.AmtOwed += ExistAcctsArr[count].tBal;
		ExistAcctsArr[count].deductible = false;
		if (isNaN(ExistAcctsArr[count].MthPymt)) ExistAcctsArr[count].MthPymt = 0;
		totalCurrPayment += ExistAcctsArr[count].MthPymt;
   	}

	ConsLoanInfo.mRate = ConsLoanInfo.IntRate/1200;  //monthly rate
	ConsLoanInfo.MthPymt = (ConsLoanInfo.AmtOwed*ConsLoanInfo.mRate)/(1-Math.pow(1+ConsLoanInfo.mRate,-ConsLoanInfo.MthsToPayoff)); //new monthly payment
	ConsLoanInfo.totalInterest = ConsLoanInfo.ClosingCosts + ((ConsLoanInfo.DiscPts/100) * ConsLoanInfo.AmtOwed); //add fees and points to interest
	ConsLoanInfo.tDeduction = 0;

	if (ConsLoanInfo.deductible) {//prepopulate with tax savings from points
		ConsLoanInfo.tDeduction = ((ConsLoanInfo.DiscPts/100) * ConsLoanInfo.AmtOwed)* FedStateTaxRate/100; 
	}

	ConsLoanInfo.totalSavings = 0;
	ConsLoanInfo.tBal = ConsLoanInfo.AmtOwed;

	//calculate and store account and loan monthly interest, tax deduction 
	for (var m=0; m<maxMonths;m++) {
		resCurr[m] = new Object();
		resNew[m] = new Object();
		
		resCurr[m].balance = 0;
		resNew[m].balance = 0;
		//Current Loans
		for (count=0; count < numExistLoans; count++)
		{
			if (ExistLoansArr[count].tBal > 0) {
				resCurr[m].balance += ExistLoansArr[count].tBal; 
				var tInterest = ExistLoansArr[count].tBal * ExistLoansArr[count].mRate;
				totalCurrInterest += tInterest; 
				ExistLoansArr[count].tBal += tInterest - ExistLoansArr[count].MthPymt;
				if (ExistLoansArr[count].deductible) totalCurrDeduction += tInterest * FedStateTaxRate/100;			
			}
		}

		for (count=0; count < numExistAccts; count++)
		{
			if (ExistAcctsArr[count].tBal > 0) {
				resCurr[m].balance += ExistAcctsArr[count].tBal;
		      		var tInterest = ExistAcctsArr[count].tBal * ExistAcctsArr[count].mRate;
				totalCurrInterest += tInterest; 
				ExistAcctsArr[count].tBal += tInterest - ExistAcctsArr[count].MthPymt;
				if (ExistAcctsArr[count].deductible) totalCurrDeduction += tInterest * FedStateTaxRate/100;				
			}
	   	}

		resCurr[m].interest = totalCurrInterest;

		
		if ((m+1)%12==0) { //add deductions to savings every 12 months
			totalCurrSavings += totalCurrDeduction;
			totalCurrDeduction = 0;
		}
		totalCurrSavings *= (1 + ((1-(FedStateTaxRate/100)) * (SvngsRate/100)))
		resCurr[m].savings = totalCurrSavings;

		
		//New Consolidation Loan
		if (ConsLoanInfo.tBal > 0) {
			resNew[m].balance = ConsLoanInfo.tBal;
	      		var tInterest = ConsLoanInfo.tBal * ConsLoanInfo.mRate;
			ConsLoanInfo.totalInterest += tInterest; 
			ConsLoanInfo.tBal += tInterest - ConsLoanInfo.MthPymt;
			if (ConsLoanInfo.deductible) ConsLoanInfo.tDeduction += tInterest * FedStateTaxRate/100;
	   	} else {
			resNew[m].balance = 0;
		}

		
		resNew[m].interest = ConsLoanInfo.totalInterest;

	
		if ((m+1)%12==0) { //add deductions to savings every 12 months
			ConsLoanInfo.totalSavings += ConsLoanInfo.tDeduction;
			ConsLoanInfo.tDeduction = 0;
		}
		ConsLoanInfo.totalSavings *= (1 + ((1-(FedStateTaxRate/100)) * (SvngsRate/100)))

		resNew[m].savings = ConsLoanInfo.totalSavings;
	}
	
	totalCurrSavings += totalCurrDeduction;
	totalCurrDeduction = 0;
	
	ConsLoanInfo.totalSavings += ConsLoanInfo.tDeduction;
	ConsLoanInfo.tDeduction = 0;

	for (var r = 5; r<21;r++) {
		resRateCost[r-5] = fnCalcCostofLoan(ConsLoanInfo.AmtOwed,r,ConsLoanInfo.deductible,SvngsRate,FedStateTaxRate,ConsLoanInfo.DiscPts,ConsLoanInfo.MthsToPayoff,ConsLoanInfo.ClosingCosts);
	}	

	totalCurrCost = ConsLoanInfo.AmtOwed + resCurr[maxMonths-1].interest - resCurr[maxMonths-1].savings;
	totalNewCost = ConsLoanInfo.AmtOwed + resNew[maxMonths-1].interest - resNew[maxMonths-1].savings;

//*************************************************//
//      Begin updates of results output        	   //
//*************************************************//

	fnShowHide('loaderDiv', 'Show');
        fnShowHide('loaderDiv2', 'Show');

//*************************************************//
//    Update results table               	   //
//*************************************************//

        fnUpdateResultsTable();

//*************************************************//
//    Update Loan Balances graph              	   //
//*************************************************//
        CurrLoanBalArr = new Array();
        ConsLoanBalArr = new Array();
        CurrLoanBalArr[0] = 0;
        ConsLoanBalArr[0] = 0;

        for(var mq=1; mq<=maxMonths; mq++)
        {
           CurrLoanBalArr[mq] = Math.round(parseFloat(resCurr[mq-1].balance));
           ConsLoanBalArr[mq] = Math.round(parseFloat(resNew[mq-1].balance));
           if (CurrLoanBalArr[mq] < 0) CurrLoanBalArr[mq]=0;
           if (ConsLoanBalArr[mq] < 0) ConsLoanBalArr[mq]=0;
        }
    
	globalTimeout = setTimeout("fnDrawGraph_LoanBal('loanbalchart')",300);



        //Update Time Frame below graph (either 'months' or 'years')
	var t, tOut;
		
	//if(maxMonths <= 72) tOut = "Months";
	//else tOut = "Years";
	tOut = "Months";
	
	t = new fnGetObj('timeFrame');
	t.obj.innerHTML = tOut;
	
	//t = new fnGetObj('printtimeFrame');
	//t.obj.innerHTML = tOut;

//*************************************************//
//    Update Break-even graph            	   //
//*************************************************//

        for(r=5; r<21; r++)
        {         
		    NetSavingsArr[r-5] = totalCurrCost - ConsLoanInfo.AmtOwed ;
            NetLossArr_PosVals[r-5] = resRateCost[r-5] - ConsLoanInfo.AmtOwed ;
        }
  		
	globalTimeout = setTimeout("fnDrawGraph_NetSvngs('netsvngschart')",600);


//*************************************************//
// JRB- MO   Write results out to table for testing//
//*************************************************//
    jrbdebug = false;
    if (jrbdebug)
    {
	var sOutput = "";
	
	sOutput += "<table border=1 cellpadding=2><tr><th> </th><th>Current</th><th>Consolidation</th></tr>";
	sOutput += "<tr align=right><td>Monthly Payment</td><td>" + totalCurrPayment.toFixed(2) + "</td><td>" + ConsLoanInfo.MthPymt.toFixed(2) + "</td></tr>";
	sOutput += "<tr align=right><td>Interest</td><td>" + resCurr[maxMonths-1].interest.toFixed(2) + "</td><td>" + resNew[maxMonths-1].interest.toFixed(2) + "</td></tr>";
	sOutput += "<tr align=right><td>Tax Savings</td><td>" + resCurr[maxMonths-1].savings.toFixed(2) + "</td><td>" + resNew[maxMonths-1].savings.toFixed(2) + "</td></tr>";
	sOutput += "<tr align=right><td>Total Cost</td><td>" + totalCurrCost.toFixed(2) + "</td><td>" + totalNewCost.toFixed(2) + "</td></tr></table><br>";
	
	sOutput += "<table border=1 cellpadding=2><tr><th>Month</th><th>Curr Balance</th><th>Curr Interest</th><th>Curr Savings</th><th>New Balance</th><th>New Interest<br>& Fees</th><th>New Savings</th></tr>";
	for (var m=0; m<maxMonths;m++) {
		sOutput += "<tr align=right><td>" + (m+1) + "</td>";
		sOutput += "<td>" + resCurr[m].balance.toFixed(2) + "</td><td>" + resCurr[m].interest.toFixed(2) + "</td><td>" + resCurr[m].savings.toFixed(2) + "</td>";
		sOutput += "<td>" + resNew[m].balance.toFixed(2) + "</td><td>" + resNew[m].interest.toFixed(2) + "</td><td>" + resNew[m].savings.toFixed(2) + "</td>";
		sOutput += "</tr>";
	}

	sOutput += "</table><br><table border=1 cellpadding=2><tr><th>Rate</th><th>Current Cost</th><th>Consolidation Cost</th><th>Net Savings</th></tr>";
	for (var r = 5; r<21;r++) {
		var netSavings = totalCurrCost - resRateCost[r-5];
		sOutput += "<tr align=right><td>" + r + "%</td><td>" + totalCurrCost.toFixed(2) + "</td><td>" + resRateCost[r-5].toFixed(2) + "</td><td>" + netSavings.toFixed(2) + "</td></tr>";
	}

	var outputdiv = new fnGetObj("MOtestresults");
	outputdiv.obj.innerHTML = sOutput + "</table>";
        fnShowHide('MOtestresults', 'Show');
    }
    else
    {
        fnShowHide('MOtestresults', 'Hide');
    }


	//Disable Printer-=Friendly Results button if total amount owed is 0.
	var printbtn = new fnGetObj('printBtn');
	
	if(totalAmtOwed <=0){ if(printbtn.obj.disabled != true) printbtn.obj.disabled = true;}
	else{ if(printbtn.obj.disabled != false) printbtn.obj.disabled = false;	}

}

function fnCalcCostofLoan(Balance,Rate,Deductible,SvngsRate,FedStateTaxRate,DiscPts,numMonths,tClosingCosts) {
	var totalInterest = 0; tClosingCosts;
	var totalSavings = 0; 
	var tDeduction = 0;
	var tBal = Balance;
	var mRate = Rate/1200;
	var MthPymt = (Balance*mRate)/(1-Math.pow(1+mRate,-numMonths));
		

	totalInterest = tClosingCosts + ((DiscPts/100) * Balance);

	if (Deductible) {//prepopulate with tax savings from points
		tDeduction = ((DiscPts/100) * Balance)* FedStateTaxRate/100; 
	}


	for (var m=0; m<maxMonths;m++) {

		if (tBal > 0) {
			var tInterest = tBal * mRate;
			totalInterest += tInterest; 
			tBal += tInterest - MthPymt;
			if (Deductible) tDeduction += tInterest * FedStateTaxRate/100;
	   	} 	

		if ((m+1)%12==0) { //add deductions to savings every 12 months
			totalSavings += tDeduction;
			tDeduction = 0;
		}
		totalSavings *= (1 + ((1-(FedStateTaxRate/100)) * (SvngsRate/100)));
	}

	var result = Balance + totalInterest - totalSavings - tDeduction;
	return result;
}

function fnUpdateResultsTable()
{
       var resultstext = "";

	var LoanTypCd = ConsLoanInfo.LoanType;

        switch(LoanTypCd)
        {
           case "HEL":
              LoanType = "Home Equity Loan / Line of Credit";
              break;
           case "HELC":
              LoanType = "Home Equity Loan / Line of Credit";
              break;
	   case "PL":
              LoanType = "Personal Loan / Line of Credit";
              break;
	   case "PLC":
              LoanType = "Personal Loan / Line of Credit";
              break;
           default:
              LoanType = "";
        }


	//Difference in cost between Current Loan and Consol. loan at end of Consol. Loan
	var diff = Math.round(totalCurrCost - totalNewCost);
	var diffFormatted = fnAddDollarSign(Math.abs(diff),0);	
        
        var strmonths = " months";
        if (maxMonths == 1)
        {
           var strmonths = " month";
        }
	
	if (diff > 0.01)
	{
		resultstext = "<br>Consolidating with a " + LoanType + " will save you <nobr><b>" + diffFormatted + "</b></nobr> over the " + maxMonths + strmonths + ".<br><br>";
	}
	else if (diff < -0.01)
	{
		resultstext = "<br>Consolidating with a " + LoanType + " will cost you <nobr><b>" + diffFormatted + "</b></nobr> over the " + maxMonths + strmonths + ".<br><br>";	
	}
	else
	{
		resultstext = "<br>Consolidating with a " + LoanType + " will not make any difference over the " + maxMonths + strmonths + ".<br><br>";
	}

	ref = new fnGetObj('finalresults');
	ref.obj.innerHTML = resultstext;

	ref = new fnGetObj('currMthPymt');
	ref.obj.innerHTML = fnAddDollarSign(Math.round(totalCurrPayment),0);
	ref = new fnGetObj('consMthPymt');
	ref.obj.innerHTML = fnAddDollarSign(Math.round(ConsLoanInfo.MthPymt),0);

	ref = new fnGetObj('currTotInt');
	ref.obj.innerHTML = fnAddDollarSign(Math.round(resCurr[maxMonths-1].interest),0);
	ref = new fnGetObj('consTotInt');
	ref.obj.innerHTML = fnAddDollarSign(Math.round(resNew[maxMonths-1].interest),0);

	ref = new fnGetObj('currTotSavings');
	ref.obj.innerHTML = fnAddDollarSign(Math.round(resCurr[maxMonths-1].savings),0);
	ref = new fnGetObj('consTotSavings');
	ref.obj.innerHTML = fnAddDollarSign(Math.round(resNew[maxMonths-1].savings),0);

	ref = new fnGetObj('currTotCost');
	ref.obj.innerHTML = fnAddDollarSign(Math.round(totalCurrCost),0);
	ref = new fnGetObj('consTotCost');
	ref.obj.innerHTML = fnAddDollarSign(Math.round(totalNewCost),0);
}



function fnClearAll()
{  //Set fields to 0 or their required minimum values
   
   //Hide Popups
   fnHideNote();
   
   totalAmtOwed = 0;

   var ref;
   var count;

   //Clear all textboxes for Existing Loans
   //Note: For any added loans, leave the drop down box selection they made
   for (count=0; count < numExistLoans; count++)
   {
      idName = "L" + (count+1); 
      ref = new fnGetObj(idName + "a")
      ref.obj.value = "0";

      ref = new fnGetObj(idName + "b")
      ref.obj.value = "0";

      ref = new fnGetObj(idName + "c")
      ref.obj.value = "0";
   }	

   //Clear all textboxes for Existing Accounts
   //Note: For any added accounts, leave the drop down box selection they made
   for (count=0; count < numExistAccts; count++)
   {
      idName = "A" + (count+1); 
      ref = new fnGetObj(idName + "a")
      ref.obj.value = "0";

      ref = new fnGetObj(idName + "b")
      ref.obj.value = "0";
   }

   //Clear all textboxes for Consolidation Loan
   //Note: Leave the currently selected Loan Type
   ref = new fnGetObj("CL1a");
   ref.obj.value = "5";

   ref = new fnGetObj("CL2a");
   ref.obj.value = "1";

   ref = new fnGetObj("CL3a");
   ref.obj.value = "0";

   ref = new fnGetObj("CL4a");
   ref.obj.value = "0";

   //clear all textboxes for Remaining Information
   ref = new fnGetObj("saverate");
   ref.obj.value = "0";

   ref = new fnGetObj("taxrate");
   ref.obj.value = "0";
	
   fnCalculateCostofLoans(10);
   
}

function fnReset()
{  //Re-establish default values
   //fnClearAll();
	
   var ref;
   var count;

   //Hide Popups
   fnHideNote();
	

   //Remove any Added Loans
   if (numExistLoans > numExistLoansDefault)
   { //Row 0 is a header row
      var tableElem =  new fnGetObj("LoanTable");
      count = tableElem.obj.rows.length - 1;
      while (count > numExistLoansDefault)
      {
         tableElem.obj.deleteRow(count);
         count--;
      }

      numExistLoans = numExistLoansDefault
   }


   //Reset Existing Loans
   ref = new fnGetObj("L1a")
   ref.obj.value = val1;
   ref = new fnGetObj("L1b")
   ref.obj.value = val2;
   ref = new fnGetObj("L1c")
   ref.obj.value = val3;

   ref = new fnGetObj("L2a")
   ref.obj.value = val4;
   ref = new fnGetObj("L2b")
   ref.obj.value = val5;
   ref = new fnGetObj("L2c")
   ref.obj.value = val6;

   ref = new fnGetObj("L3a")
   ref.obj.value = val7;
   ref = new fnGetObj("L3b")
   ref.obj.value = val8;
   ref = new fnGetObj("L3c")
   ref.obj.value = val9;

   ref = new fnGetObj("L4a")
   ref.obj.value = val10;
   ref = new fnGetObj("L4b")
   ref.obj.value = val11;
   ref = new fnGetObj("L4c")
   ref.obj.value = val12;

   //Remove any Added Accounts
   if (numExistAccts > numExistAcctsDefault)
   { //Row 0 is a header row
      var tableElem =  new fnGetObj("AcctTable");
      count = tableElem.obj.rows.length - 1;
      while (count > numExistAcctsDefault)
      {
         tableElem.obj.deleteRow(count);
         count--;
      }

      numExistAccts = numExistAcctsDefault
   }

   //Reset Existing Accounts
   ref = new fnGetObj("A1a")
   ref.obj.value = val13;
   ref = new fnGetObj("A1b")
   ref.obj.value = val14;

   ref = new fnGetObj("A2a")
   ref.obj.value = val15;
   ref = new fnGetObj("A2b")
   ref.obj.value = val16;

   //Reset Consolidation Loan
   //  NOTE:  Reset Loan Choice to Default
   var radioID = window.document.forms['calcform'].rdoCLType;
   for (counter=0; counter < radioID.length; counter++)
   {
      if (radioID[counter].value == CLDefType)
      {
         radioID[counter].checked = true;
         break;
      }
   }
   fnSetConsLoanTypeFields(CLDefType);

   ref = new fnGetObj("CL1a");
   ref.obj.value = val17;

   ref = new fnGetObj("CL2a");
   ref.obj.value = val18;

   ref = new fnGetObj("CL3a");
   ref.obj.value = val19;

   ref = new fnGetObj("CL4a");
   ref.obj.value = val20;

   //clear all textboxes for Remaining Information
   ref = new fnGetObj("saverate");
   ref.obj.value = val21;

   ref = new fnGetObj("taxrate");
   ref.obj.value = val22;

   fnCalculateCostofLoans(11);
   scroll(0,0); //Bump the page to the top.
	
}


function fnGeneratePrintPage()
{
	var ref, ref2, val;
	
	//Hide Help pop-up bubble
	fnHideNote();
	
	//Hide Normal DIVs
	var div = new fnGetObj('normalDIV');
	div.style.display = 'none';
	
	//Show Print DIV
	var div = new fnGetObj('printDIV');
	div.style.display = '';
	
	//Generate Printable charts
	fnDrawGraph_LoanBal('printloanbalchart');
	fnDrawGraph_NetSvngs('printnetsvngschart');


	//Get data for Results Table
	ref = new fnGetObj('finalresults');
	resultstext = ref.obj.innerHTML;
	
	ref = new fnGetObj('printResults');
	ref.obj.innerHTML = resultstext;
	
	ref = new fnGetObj('printcurrMthPymt');
	ref.obj.innerHTML = fnAddDollarSign(Math.round(totalCurrPayment),0);
	ref = new fnGetObj('printconsMthPymt');
	ref.obj.innerHTML =  fnAddDollarSign(Math.round(ConsLoanInfo.MthPymt),0);
	
	ref = new fnGetObj('printcurrTotInt');
	ref.obj.innerHTML = fnAddDollarSign(Math.round(resCurr[maxMonths-1].interest),0);
	ref = new fnGetObj('printconsTotInt');
	ref.obj.innerHTML =  fnAddDollarSign(Math.round(resNew[maxMonths-1].interest),0);

	ref = new fnGetObj('printcurrTotSavings');
	ref.obj.innerHTML = fnAddDollarSign(Math.round(resCurr[maxMonths-1].savings),0);
	ref = new fnGetObj('printconsTotSavings');
	ref.obj.innerHTML =  fnAddDollarSign(Math.round(resNew[maxMonths-1].savings),0);	

	ref = new fnGetObj('printcurrTotCost');
	ref.obj.innerHTML = "<b>" + fnAddDollarSign(Math.round(totalCurrCost),0) + "</b>";
	ref = new fnGetObj('printconsTotCost');
	ref.obj.innerHTML = "<b>" + fnAddDollarSign(Math.round(totalNewCost),0) + "</b>";

	//Get data for Inputs table
        //Note:  dynamically generate rows for Existing Loans and Existing Accounts
        var tableElem;
        var row;
        var LoanTypeText;

        //Note:  dynamically generate rows for Existing Loans & Existing Accounts.
        //       delete any existing rows first (except for header row)
        tableElem = new fnGetObj("printLoanTable");
        var count = tableElem.obj.rows.length - 1;
        while (count > 0)
        {
           tableElem.obj.deleteRow(count);
           count--;
        }

 	for (count=0; count < numExistLoans; count++)
        {

           switch(ExistLoansArr[count].LoanType)
           {
              case "A":
                 LoanTypeText= "Auto:";
                 break;
              case "B":
                 LoanTypeText= "Boat/RV:";
                 break;
              case "E":
                 LoanTypeText= "Education:";
                 break;
              case "O":
                 LoanTypeText= "Other:";
                 break;           
              default:
                 LoanTypeText= "Other:";
           }

           var row = tableElem.obj.insertRow(tableElem.obj.rows.length);
           row.className = "row";

           cell0 = row.insertCell(0);
           cell0.innerHTML = "&nbsp;";
           cell0.width = "10px";

           cell1 = row.insertCell(1);
           cell1.innerHTML =  LoanTypeText;   
           cell1.width = "80px";
           cell1.className = "indent";


           cell2 = row.insertCell(2);
           cell2.innerHTML = "&nbsp;";
           cell2.width = "10px";

           cell3 = row.insertCell(3);
           cell3.innerHTML = fnAddDollarSign(ExistLoansArr[count].AmtOwed);
           cell3.width = "60px";

           cell4 = row.insertCell(4);
           cell4.innerHTML = "&nbsp;";
           cell4.width = "20px";

           cell5 = row.insertCell(5);
           cell5.innerHTML = ExistLoansArr[count].IntRate + "%";
           cell5.width = "60px";

           cell6 = row.insertCell(6);
           cell6.innerHTML = "&nbsp;";
           cell6.width = "20px";

           cell7 = row.insertCell(7);
           cell7.innerHTML = ExistLoansArr[count].MthsLeft
           cell7.width = "60px";

           cell8 = row.insertCell(8);
           cell8.innerHTML = "&nbsp;";
           cell8.width = "15px";
        }

        var AcctTypeText;

        tableElem = new fnGetObj("printAcctTable");
        var count = tableElem.obj.rows.length - 1;
        while (count > 0)
        {
           tableElem.obj.deleteRow(count);
           count--;
        }

   	for (count=0; count < numExistAccts; count++)
        {
           switch(ExistAcctsArr[count].AcctType)
           {
              case "C":
                 AcctTypeText = "Credit Card:";
                 break;
              case "O":
                 AcctTypeText = "Other:";
                 break;           
              default:
                 AcctTypeText = "Other:";
           }

           var row = tableElem.obj.insertRow(tableElem.obj.rows.length);
           row.className = "row";

           cell0 = row.insertCell(0);
           cell0.innerHTML = "&nbsp;";
           cell0.width = "10px";

           cell1 = row.insertCell(1);
           cell1.innerHTML =  AcctTypeText;
           cell1.width = "80px";
           cell1.className = "indent";

           cell2 = row.insertCell(2);
           cell2.innerHTML = "&nbsp;";
           cell2.width = "10px";

           cell3 = row.insertCell(3);
           cell3.innerHTML = "&nbsp;";
           cell3.width = "60px";

           cell4 = row.insertCell(4);
           cell4.innerHTML = "&nbsp;";
           cell4.width = "20px";

           cell5 = row.insertCell(5);
           cell5.innerHTML =  fnAddDollarSign(ExistAcctsArr[count].AmtOwed);
           cell5.width = "60px";

           cell6 = row.insertCell(6);
           cell6.innerHTML = "&nbsp;";
           cell6.width = "20px";

           cell7 = row.insertCell(7);
		   cell7.innerHTML = ExistAcctsArr[count].IntRate + "%";
           cell7.width = "60px";

           cell8 = row.insertCell(8);
           cell8.innerHTML = "&nbsp;";
           cell8.width = "15px";
        }

	var LoanTypCd = ConsLoanInfo.LoanType;
        switch(LoanTypCd)
        {
           case "HEL":
              LoanType = "Home Equity Loan / <br>Line of Credit";
              break;
           case "HELC":
              LoanType = "Home Equity Loan / <br>Line of Credit";
              break;
	   case "PL":
              LoanType = "Personal Loan / <br>Line of Credit";
              break;
	   case "PLC":
              LoanType = "Personal Loan / <br>Line of Credit";
              break;
           default:
              LoanType = "";
        }
	ref = new fnGetObj('printconloantype');
	ref.obj.innerHTML = LoanType;

	ref = new fnGetObj('printCL1a');
	//ref.obj.innerHTML = ConsLoanInfo.IntRate + "%";
	ref.obj.innerHTML = document.getElementById('CL1a').value + "%";

	ref = new fnGetObj('printCL2a');
	ref.obj.innerHTML = ConsLoanInfo.MthsToPayoff;

        if (ConsLoanInfo.LoanType  == "HEL" || ConsLoanInfo.LoanType  == "HELC")
        {  //Only Show Closing Costs & discount Points for Home Equity
           fnShowHide("printclcosts", "Show");
           fnShowHide("printdiscpts", "Show");

	   ref = new fnGetObj('printCL3a');
           ref.obj.innerHTML = fnAddDollarSign(ConsLoanInfo.ClosingCosts);

	   ref = new fnGetObj('printCL4a');
	   ref.obj.innerHTML = ConsLoanInfo.DiscPts;
        }
        else
        {
           fnShowHide("printclcosts", "Hide");
           fnShowHide("printdiscpts", "Hide");
        }


	//ref = new fnGetObj('printsaverate');
	//ref.obj.innerHTML = SvngsRate + "%";

	ref = new fnGetObj('printtaxrate');
	ref.obj.innerHTML = FedStateTaxRate  + "%";

	scroll(0,0); //Bump the page to the top.

}




function fnBackToNormal()
{
	//Hide Print DIV
	var div = new fnGetObj('printDIV');
	div.style.display = 'none';
	
	//Show Normal DIV
	var div = new fnGetObj('normalDIV');
	div.style.display = '';
	
	//Enable Print button
	var printbtn = new fnGetObj('printBtn');
	printbtn.obj.disabled = false;
	
	scroll(0,0); //Bump the page to the top.
	
	//Draw graphs
	fnDrawGraph_LoanBal('loanbalchart');
	fnDrawGraph_NetSvngs('netsvngschart');
}

var vals = "<br>";
function formatbignums(inputval)
{
	var decimalPlaces = 0;
	//alert("inputval: " + inputval + "\n" + "threshold: " + threshold);
 
	if(inputval > 0) //If value is positive, do normal scaling
	{
	   if(inputval < threshold) //Add decimal place
	   {
			if(graphDecimalsFlag2)  decimalPlaces = 1;   
			outputstring = fnAddCommas((inputval*ValScaler2*100)/100);
			outputstring = parseFloat(outputstring).toFixed(decimalPlaces) + label2;
			
			//if(inputval == 1000) outputstring = "1,000" + label2;
			//outputstring = "+" + outputstring;
	   }
	   else
	   {
		   if(graphDecimalsFlag)  decimalPlaces = 1;
			outputstring = fnAddCommas((inputval*ValScaler*100)/100);
			outputstring = parseFloat(outputstring).toFixed(decimalPlaces) + label;
			
			if(outputstring == 1) outputstring = "1,000";
			//outputstring = "+" + outputstring;
	   }
	}
	else if(inputval < 0) //If value is negative, reverse scaling
	{
	   if(inputval > -threshold) //Add decimal place
	   {
			if(graphDecimalsFlag2)  decimalPlaces = 1;   
			outputstring = fnAddCommas((inputval*ValScaler2*100)/100);
			outputstring = parseFloat(outputstring).toFixed(decimalPlaces) + label2;
			
			//if(inputval == -1000) alert("inputval==1000");//outputstring = "-1,000" + label2;
	   }
	   else
	   {
		   if(graphDecimalsFlag)  decimalPlaces = 1;
			outputstring = fnAddCommas((inputval*ValScaler*100)/100);
			outputstring = parseFloat(outputstring).toFixed(decimalPlaces) + label;
			
			//if(inputval == -1000) alert("inputval==1000");//outputstring = "-1,000" + label;
	   }
	}
	else outputstring = 0;
   
   //if(outputstring == "+1") outputstring = "+1,000";
   //if(outputstring == "-1") outputstring = "-1,000";

   return outputstring;
}

function fnAddLoan(tableID)
{  //Add a Loan Row to the Existing Loans table

    numExistLoans = numExistLoans + 1;

    var tableElem =  new fnGetObj(tableID);
    var row = tableElem.obj.insertRow(tableElem.obj.rows.length);
    
    if (numExistLoans % 2 == 1)
    {
       row.className = "row";
       row.bgColor = "#EEEEEE";
    }
    else
    {
       row.className = "row";
    }     
	row.width = "100%";

    var cell0 = row.insertCell(0);
    cell0.innerHTML = "&nbsp;";
    cell0.width = "5px";
    cell0.align = "right";

    var cell1 = row.insertCell(1);
    cell1.innerHTML = "<select id='L" + numExistLoans + "Choice' class='inputbox' onChange='fnCalculateCostofLoans(16);'><option value='A'>Auto</option><option value='B'>Boat/RV</option><option value='E'>Education</option><option value='O'>Other</option></select>";
    cell1.width = "110px";
    cell1.vAlign= "middle";
    cell1.className = "indent";

    var cell2 = row.insertCell(2);
    cell2.innerHTML = "$";
    cell2.width = "10px";

    var cell3 = row.insertCell(3);
    cell3.innerHTML = "<input id='L" + numExistLoans + "a' class='inputbox' filter='debt' maxlength='9' type='text' size='6' value='0' onkeypress='return fnCheckInput2(event, this, 6);' onKeyUp='return fnCheckKeyUp(event, this.id);' >";
    cell3.width="65px";
	cell3.align="right";
    fnSpecialAttachEvents("L" + numExistLoans + "a");

    var cell4 = row.insertCell(4);
    cell4.innerHTML = "&nbsp;";
    cell4.width = "5px";

    var cell5 = row.insertCell(5);
    cell5.innerHTML = "<input id='L" + numExistLoans + "b' class='inputbox' filter='debt' maxlength='5' type='text' size='6' value='0' onkeypress='return fnCheckInput(event, this, 5);' onKeyUp='return fnCheckKeyUp(event, this.id);'>";
    cell5.width="65px";
	cell5.align="right";
    fnSpecialAttachEvents("L" + numExistLoans + "b");

    var cell6 = row.insertCell(6);
    cell6.innerHTML = "%";
    cell6.width = "10px";
    cell6.align = "left";

    var cell7 = row.insertCell(7);
    cell7.innerHTML = "<input id='L" + numExistLoans + "c' class='inputbox' filter='debt' maxlength='3' type='text' size='6' value='0' onkeypress='return fnCheckInput(event, this, 5);' onKeyUp='return fnCheckKeyUp(event, this.id);'>";
    cell7.width = "65px";
	cell7.align="right";
    fnSpecialAttachEvents("L" + numExistLoans + "c");

    var cell8 = row.insertCell(8);
    cell8.innerHTML = "&nbsp;";
    cell8.width = "5px";
    cell8.align = "left";

    //Since we added a whole new existing loan, recalculate
    fnCalculateCostofLoans(12);
}

function fnAddAccount(tableID)
{  //Add an Account Row to the Existing Accounts table

   numExistAccts = numExistAccts + 1;

    var tableElem =  new fnGetObj(tableID);
    var row = tableElem.obj.insertRow(tableElem.obj.rows.length);
    
    if (numExistAccts % 2 == 1)
    {
       row.className = "row";
       row.bgColor = "#EEEEEE";
    }
    else
    {
       row.className = "row";
    }     

    var cell0 = row.insertCell(0);
    cell0.innerHTML = "&nbsp;";
    cell0.width = "5px";
    cell0.align = "right";

    var cell1 = row.insertCell(1);
    cell1.innerHTML = "<select id='A" + numExistAccts + "Choice' class='inputbox' onChange='fnCalculateCostofLoans(13);' style='width:95px'><option value='C'>Credit Card</option><option value='O'>Other</option></select>";
    cell1.width = "110px";
    cell1.vAlign= "middle";
    cell1.className = "indent";

    var cell2 = row.insertCell(2);
    cell2.innerHTML = "$";
    cell2.width = "10px";
	
	var cell3 = row.insertCell(3);
    cell3.innerHTML = "<input id='A" + numExistAccts + "a' class='inputbox' filter='debt' maxlength='9' type='text' size='6' value='0' onkeypress='return fnCheckInput2(event, this, 6);' onKeyUp='return fnCheckKeyUp(event, this.id);' >";
    cell3.width="65px";
    fnSpecialAttachEvents("A" + numExistAccts+ "a");

    var cell4 = row.insertCell(4);
    cell4.innerHTML = "&nbsp;";
    cell4.width = "10px";

	 var cell5 = row.insertCell(5);
    cell5.innerHTML = "<input id='A" + numExistAccts + "b' class='inputbox' filter='debt' maxlength='5' type='text' size='6' value='0' onkeypress='return fnCheckInput(event, this, 5);' onKeyUp='return fnCheckKeyUp(event, this.id);'>";
    cell5.width = "65px";
    fnSpecialAttachEvents("A" + numExistAccts+ "b");


    var cell6 = row.insertCell(6);
    cell6.innerHTML = "%";
    cell6.width = "10px";
	cell6.align = "left";

    var cell7 = row.insertCell(7);
    cell7.innerHTML = "&nbsp;";
    cell7.width = "65px";
    cell7.align = "left";

    var cell8 = row.insertCell(8);
    cell8.innerHTML = "&nbsp;";
    cell8.width = "5px";
    cell8.align = "left";

    //Since we added a whole new existing account, recalculate
    fnCalculateCostofLoans(14);
}


function fnSpecialAttachEvents(cellID)
{  //Use to attach events to dynamically added cells of filter type "debt"
	var id = cellID;
	//alert(id);
	id = id.toString();
	var el = new fnGetObj(id); 
			
	//Apply the onBlur events
	el.obj.onblur = function() 
	{
		fnFormatInput(this);
	} 
	/*
	//Apply the onKeyUp events
	el.obj.onKeyUp = function() 
	{
		fnCheckKeyUp(event, id);
	} 
	//Added this event to the input tags to fix Firefox issue on the Mac - event was not being added properly through this method
	/*
	//Apply onKeyPress events
	el.obj.onkeypress = function() 
	{
		return fnCheckInput(event, this);
	} 
	*/
}

function fnConsLoanEvents(bRedoCalcs)
{  //Handle the Change of Consolidation Loan Type.  Hide Closing Costs & Discount Points if NOT HEL/HELC

   var CLType = fnGetConsLoanType();
   fnSetConsLoanTypeFields(CLType);


   //Redo the Calculations
   if (bRedoCalcs) fnCalculateCostofLoans(15);
}

function fnGetConsLoanType()
{
   var CLType;

   //get the radio button choice  - HEL, HELC, PL, PLC 
   var radioID = window.document.forms['calcform'].rdoCLType;
   for (counter=0; counter < radioID.length; counter++)
   {
      if (radioID[counter].checked)
      {
         CLType = radioID[counter].value;
         break;
      }
   }
   return CLType;
}

function fnSetConsLoanTypeFields(CLType)
{  //Hide or Show The Closing Costs and Discount Points rows
   if (CLType  == "HEL" || CLType  == "HELC")
   {
      fnShowHide("clcosts", "Show");
      fnShowHide("discpts", "Show");
   }
   else
   {
      fnShowHide("clcosts", "Hide");
      fnShowHide("discpts", "Hide");
   }
}

var step = 0;
var divider = 0;
function fnScaleLabels(range)
{
	step = 0;
	divider = 0;
	if(range == 'months'){//Monthly	
		step = 1; divider = 1;
	}
	else if(range == '2months'){//2-month
		step = 2; divider = 1;
	}
	else if(range == '6months'){//Yearly
		step = 6; divider = 6;
	}
	else if(range == 'yearly'){//Yearly
		step = 12; divider = 6;
	}
	else if(range == '2years'){//2 years
		step = 24; divider = 12;
	}
	else if(range == '5years'){//5 years
		step = 60; divider = 12;
	}
	else{ //10 years	
		step = 120; divider = 12;
	}
}


function fnDrawGraph_LoanBal(divID) 
{  //graph of Current Loan Balance versus Consolidation Loan Balance over time
	var c = new Chart(document.getElementById(divID));
	
	var labelArr = new Array();
	
	var q, density;
	var d = 1;
	maxMonths = parseInt(maxMonths);	

	if(maxMonths <= 12) fnScaleLabels('months');
	else if (maxMonths <= 24) fnScaleLabels('2months');
	else if (maxMonths <= 48) fnScaleLabels('6months');
        else if (maxMonths <= 72 ) fnScaleLabels('yearly');
	else if (maxMonths <= 120 ) fnScaleLabels('2years');
	else fnScaleLabels('5years');
	
		
	CurrLoanBalArr[maxMonths+1] = 0;
	ConsLoanBalArr[maxMonths+1] = 0;

	
	for(q=1; q <= maxMonths+1; q++) 
	{
		if(maxMonths <= 12) // If 12 months or less, display all labels
		{
			labelArr[q] = q;
			density = maxMonths+1; //Show month 1 - 12	
		}
		else // Else, scale labels
		{
			if((q+1)%step == 1) labelArr[q] = q;
			else labelArr[q] = "";
			density = maxMonths+1; //Add 1 to start labels at zero and display the years properly	
		}
	}
	
	
	labelArr[0] = "";
	labelArr[maxMonths+1] = "";

	c.setDefaultType(CHART_BAR);
	chartType = "bar";
	c.setGridDensity(density, 9);
	c.setHorizontalLabels(labelArr);
	c.setShowLegend(false);
				
	if(maxMonths < 24){ c.setBarWidth(10); c.setBarDistance(0);}
	else if(maxMonths < 48){ c.setBarWidth(6); c.setBarDistance(0);}
	else if(maxMonths < 60){ c.setBarWidth(3); c.setBarDistance(0);}
	else if(maxMonths < 72){ c.setBarWidth(2); c.setBarDistance(0);}
	else if(maxMonths < 120){ c.setBarWidth(1); c.setBarDistance(0);}
	else{ c.setBarWidth(1); c.setBarDistance(0)};

        if (CurrLoanBalArr[1]>0)
        {  //if there is no loan balance, don't graph it
	   c.add('Cons Loan Balance', '#009933', ConsLoanBalArr);
	   c.add('Curr Loan Balance', '#FF6600', CurrLoanBalArr);
        }
		
	c.draw();
	globalTimeout = setTimeout("fnShowHide('loaderDiv', 'Hide')", 50);

	
}

function fnDrawGraph_NetSvngs(divID) 
{  //graph of Current Loan Balance versus Consolidation Loan Balance over time
	var c = new Chart(document.getElementById(divID));
	 
        var GoodVals = false;
        labelArr = new Array();
	
	var q, density;
	var d = 1;
        var step=1;
        var divider=1;
        density=16;
	
	for(q=0; q < 16; q++) 
	{
	   labelArr[q] = q + 5;
           if (NetLossArr_PosVals[q]>0) GoodVals = true;
           if (NetSavingsArr[q]>0) GoodVals = true;
		   
		   if(totalAmtOwed <= 0) density = 15;
	}

	c.setDefaultType(CHART_LINE);
	chartType = "line";
	c.setGridDensity(density, 9);
	c.setHorizontalLabels(labelArr);
	c.setShowLegend(false);			
       // c.setBarWidth(10); 
        //c.setBarDistance(-5);

       if (GoodVals)
       {  // don't draw if there are no Non-zero values
           c.add('Net Loss Pos Val', '#33CC33', NetLossArr_PosVals); //Consolidation Loan
		   c.add('Net Savings', '#FF0000', NetSavingsArr); //Current Loan
       }

	c.draw();
	globalTimeout = setTimeout("fnShowHide('loaderDiv2', 'Hide')", 50);
}
