function getValue(theString){
    var noJunk = "";
    var withDollar = "";
    var foundDecimal = 0;
    var foundAlphaChar = 0;

    theString += "";
    for (i=0; i <= theString.length; i++) {
        var thisChar = theString.substring(i, i+1);

        if (thisChar == ".") {
          foundDecimal = 1;
          noJunk = noJunk + thisChar;
        }

        if ((thisChar < "0") || (thisChar > "9")) {
          if ((thisChar != "$") && (thisChar !=".") && (thisChar != ",") && (thisChar != " ") && (thisChar !="")) foundAlphaChar = 1;
        } else {
           withDollar = withDollar + thisChar
           noJunk = noJunk + thisChar
        }

        if ((thisChar == "$") || (thisChar == ".") || (thisChar == ",")) {
          withDollar = withDollar + thisChar
        }
     }

     if (foundDecimal) { return parseFloat(noJunk); }
     else if (noJunk.length > 0) { return parseInt(noJunk); }
     else return 0;
}

function formatUSCurrency(theNumber) {
  var isNegative = 0
  if (theNumber != "") {

    var workingNumber = theNumber + "" // Evaluate to a string

    if (workingNumber.charAt(0) == "-") { 
      isNegative = 1;
      workingNumber = workingNumber.substring(1, workingNumber.length)
    }

    var withoutChars = ""
    for (x=0; x<=((workingNumber.length)-1); x++) {
      thisChar = workingNumber.charAt(x)
      charAsNum = parseInt(thisChar)
      if ( ((thisChar >= "0") & (thisChar <= "9")) || (thisChar == ".")  ) { 
        withoutChars += workingNumber.charAt(x) 
      }
    }
    workingNumber = withoutChars
    decimalPoint = workingNumber.indexOf(".")

    if (decimalPoint == -1) {
      dollarValue = workingNumber
      centsValue = "00"
      } else if (decimalPoint == 0) {
      dollarValue = "0"
      centsValue = workingNumber.substring(decimalPoint + 1, workingNumber.length)
    } else {
        dollarValue = workingNumber.substring(0, decimalPoint)
        if (decimalPoint == (workingNumber.length - 1)) {
          centsValue = "00";
        } else {
          centsValue = getValue(workingNumber.substring(decimalPoint + 1, workingNumber.length));
          centsValue += "0";
          centsValue = centsValue.charAt(0) + centsValue.charAt(1)
        }
    }

    var theString = dollarValue;
    var totalCommas = Math.floor((theString.length - 1) / 3)

    var dollarAmt = ""
    x=dollarValue.length
    position = 0
    while (x > 0) {
        x = x - 1
        thisChar = dollarValue.charAt(x)
        rounded = Math.round(position/3)
        if ( (position/3 == rounded ) & (position != 0) ) {
           dollarAmt = "," + dollarAmt
        }
        dollarAmt = thisChar +  dollarAmt
        position = position + 1
    }

    if (isNegative) {
      theString = "-$" + dollarAmt + "." + centsValue
      //theString = "($" + dollarAmt + "." + centsValue + ")"
    } else { 
      theString = "$" + dollarAmt + "." + centsValue
    }
    return (theString);
  } else {
    return("$0.00");
  }
}

function formatPercent(theNumber,decimalPlaces) {
  theNumber = getValue(theNumber);
  if (theNumber < 1) { theNumber = theNumber * 100; }
  with (Math) theNumber = (round(theNumber * pow(10,decimalPlaces))) / pow(10,decimalPlaces); 
  return(theNumber + "%");
}

function removeCents(theNumber) {

  theNumber = getValue(theNumber)
  theNumber = Math.round(theNumber * 100) / 100;
  theNumber = theNumber + ""
  decimalPoint = theNumber.indexOf(".")

    if (decimalPoint == -1) {
      dollarValue = theNumber
    } else if (decimalPoint == 0) {
      dollarValue = 0
    } else {
      dollarValue = theNumber.substring(0, decimalPoint)
    }

    var dollarAmt = ""
    x=dollarValue.length
    position = 0
    while (x > 0) {
        x = x - 1
        thisChar = dollarValue.charAt(x)
        rounded = Math.round(position/3)
        if ( (position/3 == rounded ) & (position != 0) ) {
           dollarAmt = "," + dollarAmt
        }
        dollarAmt = thisChar +  dollarAmt
        position = position + 1
    }

  dollarValue = "$" + dollarAmt
  return(dollarValue)
}

function calculate(formobj) {

    userdata            = formobj;
    monthIncome1        = getValue(userdata.monthIncome1.value);
    monthIncome2        = getValue(userdata.monthIncome2.value);
    monthInt            = getValue(userdata.monthInt.value);
    monthDiv            = getValue(userdata.monthDiv.value);
    monthPart           = getValue(userdata.monthPart.value);
    monthOther          = getValue(userdata.monthOther.value);
    monthMorg           = getValue(userdata.monthMorg.value);
    monthHousing        = getValue(userdata.monthHousing.value);
    monthLoan1          = getValue(userdata.monthLoan1.value);
    monthLoan2          = getValue(userdata.monthLoan2.value);
    monthFees           = getValue(userdata.monthFees.value);
    monthInsurance      = getValue(userdata.monthInsurance.value);
    monthTaxes          = getValue(userdata.monthTaxes.value);
    monthSavings        = getValue(userdata.monthSavings.value);
    monthEmpRet         = getValue(userdata.monthEmpRet.value);
    monthIndRet         = getValue(userdata.monthIndRet.value);
    monthOExp           = getValue(userdata.monthOExp.value);
    monthFood1          = getValue(userdata.monthFood1.value);
    monthFood2          = getValue(userdata.monthFood2.value);
    monthAuto           = getValue(userdata.monthAuto.value);
    monthCharity        = getValue(userdata.monthCharity.value);
    monthCc             = getValue(userdata.monthCc.value);
    monthCloth          = getValue(userdata.monthCloth.value);
    monthEdu            = getValue(userdata.monthEdu.value);
    monthEnt            = getValue(userdata.monthEnt.value);
    monthGifts          = getValue(userdata.monthGifts.value);
    monthFurn           = getValue(userdata.monthFurn.value);
    monthMed            = getValue(userdata.monthMed.value);
    monthNews           = getValue(userdata.monthNews.value);
    monthCare           = getValue(userdata.monthCare.value);
    monthPets           = getValue(userdata.monthPets.value);
    monthTrans          = getValue(userdata.monthTrans.value);
    monthUtil1          = getValue(userdata.monthUtil1.value);
    monthCable          = getValue(userdata.monthCable.value);
    monthVac            = getValue(userdata.monthVac.value);
    monthOther5         = getValue(userdata.monthOther5.value);
    monthCreditCards    = getValue(userdata.monthCreditCards.value);
    
  var totalIncome = 0;
  var totalIncomeyr = 0;
  var totFixExp = 0;
  var totFixExpyr = 0;
  var totVarExp = 0;
  var totVarExpyr = 0;
  var totExp = 0;
  var totExpyr = 0;
  var totDif = 0;
  var totDifyr = 0;
  var absoluteValTotDifyr = 0;
 
  totalIncome = monthIncome1 + monthIncome2 + monthInt + monthDiv + monthPart + monthOther;
  totalIncomeyr = totalIncome * 12;
  totFixExp = monthMorg + monthHousing + monthLoan1 + monthLoan2 + monthFees + monthInsurance;
  totFixExp = totFixExp + monthTaxes + monthCreditCards + monthSavings;
  totFixExp = totFixExp + monthEmpRet + monthIndRet + monthOExp;
  totFixExpyr = totFixExp * 12;
  totVarExp = monthFood1 + monthFood2 + monthAuto + monthCharity + monthCc + monthCloth + monthEdu;
  totVarExp = totVarExp + monthEnt + monthGifts + monthFurn + monthMed + monthNews + monthCare + monthPets + monthTrans;
  totVarExp = totVarExp + monthUtil1 + monthCable + monthVac + monthOther5;  
  totVarExpyr = totVarExp * 12;
  totExp = totVarExp + totFixExp;
  totExpyr = totVarExpyr + totFixExpyr;
  totDif = totalIncome - totExp;
  totDifyr = totalIncomeyr - totExpyr;
  absoluteValTotDifyr = Math.abs(totDifyr);

  totalIncome = formatUSCurrency(totalIncome);
  totalIncomeyr = formatUSCurrency(totalIncomeyr); 
  totFixExp = formatUSCurrency(totFixExp);
  totFixExpyr = formatUSCurrency(totFixExpyr);
  totVarExp = formatUSCurrency(totVarExp);
  totVarExpyr = formatUSCurrency(totVarExpyr);
  totExp = formatUSCurrency(totExp);
  totExpyr = formatUSCurrency(totExpyr); 
  totDif = formatUSCurrency(totDif);
  totDifyr = formatUSCurrency(totDifyr); 
  absoluteValTotDifyr = formatUSCurrency(absoluteValTotDifyr);

  results = ('Based on the information provided, after one year your total income will be ');
  results += (totalIncomeyr);
  results += (' and your total expenses will be ');
  results += (totExpyr);
  results += ('.');
  results += (' This results in a')
                    if (totExpyr < totalIncomeyr) {
                    results.value += (' surplus of ')
                    results.value += ( totDifyr )
                    results.value += ('.' + '\r\n\r\n');
                    } else {
                    results.value += (' shortage of ')
                    results.value += ( absoluteValTotDifyr )
                                        results.value += ('.' + '\r\n\r\n');
            }
  
  results +=  ('Total Income' + '\r\n');
  results += ('         Monthly:' + '                    ' + totalIncome + '\r\n');
  results += ('         Yearly: ' + '                     ' + totalIncomeyr + '\r\n\r\n');
  results += ('Total Fixed Expenses' + '\r\n');
  results += ('         Monthly:' + '                    ' + totFixExp + '\r\n');
  results += ('         Yearly: ' + '                     ' + totFixExpyr + '\r\n\r\n');
  results += ('Total Variable Expenses' + '\r\n');
  results += ('         Monthly:' + '                    ' + totVarExp + '\r\n'); 
  results += ('         Yearly: ' + '                     ' + totVarExpyr + '\r\n\r\n'); 
  results += ('Total Expenses' + '\r\n');
  results += ('         Monthly:' + '                    ' + totExp + '\r\n'); 
  results += ('         Yearly: ' + '                     ' + totExpyr + '\r\n\r\n');
  results += ('Net Income' + '\r\n');
  results += ('         Monthly:' + '                    ' + totDif + '\r\n');
  results += ('         Yearly: ' + '                     ' + totDifyr + '\n');
 
 alert(results);

}

function monthlyPayment(term, rate, loanAmount) {
  if (rate > 1) { (rate = rate / 100); }
  rateMonthly = (rate / 12);

  totalPayments = (term * 12);
  payment = (loanAmount * rateMonthly) / (1 - Math.pow((1+rateMonthly), (-1*totalPayments)) )
  return(payment)
}

function figureLoanAPR (loanYears, iRateAnnual, loanAmount, monthly) {
  loanMonths = loanYears * 12;
  if (iRateAnnual > 1) { (iRateAnnual = iRateAnnual / 100); }
  iRateMonthly = iRateAnnual / 12;

  prepaidFinanceCharges = Math.round(((.01 * loanAmount) + 375 + (((loanAmount * iRateAnnual) / 365) * 30)) * 100) / 100;

  aprPrinciple = Math.round((loanAmount - prepaidFinanceCharges) * 100) / 100;
  compoundX = Math.pow( (1 + iRateMonthly) , (-1 * loanMonths) );

  loanAPR = ((monthly * (1 - (compoundX) )) / aprPrinciple) * 12 * 100;
  loanAPR = Math.round(loanAPR * 1000) / 1000;
  return(loanAPR);
}

function getFieldValue(theString)
{
    var noJunk = ""
    var withDollar = ""
    var foundDecimal = 0
    var foundAlphaChar = 0

    if (theString.value.length == 0) 
    {
		theString.value = 0;
	return 0
    }

    for (i=0; i <= theString.value.length; i++)
    {
        var thisChar = theString.value.substring(i, i+1);

        if (thisChar == ".")
        {
          foundDecimal = 1;
          noJunk = noJunk + thisChar;
        }

        if ((thisChar < "0") || (thisChar > "9"))
        {
          if ((thisChar != "$") && (thisChar !=".") && (thisChar != ",") && (thisChar != " ") && (thisChar !="")) foundAlphaChar = 1;
        }
        else 
	{
	   withDollar = withDollar + thisChar
	   noJunk = noJunk + thisChar
	}

	if ((thisChar == "$") || (thisChar == ".") || (thisChar == ","))
	{
	  withDollar = withDollar + thisChar
	}
     }

     if (foundAlphaChar)
     {
		theString.value = "withDollar";
     }

     if (foundDecimal) { return parseFloat(noJunk); }
     else if (noJunk.length > 0) { return parseInt(noJunk); }
     else return 0;
}

function getFieldValue1(theString,theField)
{
    var noJunk = ""
    var foundDecimal = 0
    var foundAlphaChar = 0

    for (i=0; i <= theString.length; i++)
    {
        var thisChar = theString.substring(i, i+1);

        if (thisChar == ".")
        {
          foundDecimal = 1;
          noJunk = noJunk + thisChar;
        }

        if ((thisChar < "0") || (thisChar > "9"))
        {
          if ((thisChar != "$") && (thisChar !=".") && (thisChar != ",") && (thisChar != " ") && (thisChar !="")) foundAlphaChar = 1;
        }
        else 
	{
	   noJunk = noJunk + thisChar
	}
     }

     if (foundAlphaChar)
     {
	//document.forms[0].theField.value = noJunk;
	eval ("document.forms[0]." + theField + ".value = noJunk")
     }

     if (foundDecimal) { return parseFloat(noJunk); }
     else if (noJunk.length > 0) { return parseInt(noJunk); }
     else return 0;

}

function compute(form)
{   
	var i;
        var totalCost;

	yearsUntil=getFieldValue(form.yearsUntil);
	collegeStay=getFieldValue(form.collegeStay);
	current=getFieldValue(form.current);


        totalCost = 0;

        if ((yearsUntil != -1) && (current != -1)) 
        {
	  with (Math) 
	  {
		var wholeYears = 0
		for (i=0; i <= (collegeStay - 1); i++) 
		{
                        yearsOut = yearsUntil + i;
			yearsCost = (current * (pow (1.05, yearsOut)));
			totalCost = totalCost + yearsCost;
			wholeYears++
		}

		// Calculate for partial years

		partialYear = collegeStay - wholeYears
		if (partialYear > 0)
		{
			yearsOut = yearsUntil + wholeYears;
			yearsCost = (current * (pow (1.05, yearsOut)));
			totalCost = totalCost + (yearsCost * partialYear);
		}

		
		fouryear = formatUSCurrency(totalCost);
		averageAnnual = formatUSCurrency(totalCost / collegeStay);
	  }
        }
        else
        {
		form.fouryear.value = "(incomplete)";
		form.averageAnnual.value = "(incomplete)";
        }

		var mothly_cost = 0; 
		monthly_cost = formatUSCurrency( (totalCost / yearsUntil) / 12 );
		
  results =  ('Based on the information provided, the projected total cost for your child\'s education will be ');
  results +=  ( fouryear + '\r\n\r\n');
  results +=  ('This averages out to ');
  results +=  ( averageAnnual );
  results +=  (' each year. For which you\'d need to save: ' + monthly_cost + '* per month.\r\n\r\n*This does not take into account accrued interest.');

	alert(results);
		
}

function totalGroup(formName, groupName) {

  var elementNumber;
  var total;
  var i;

  total = 0;
  for (i = 1; i <=30; i++) {
    elementNumber = '' + i;
    total +=  getValue(formName.elements[groupName + elementNumber].value);
  }
  formName.elements[groupName + 'Total'].value = formatUSCurrency(total); 
}

function savings(formobj) {

    userdata    = formobj;
    rate        = getValue(userdata.rate.value);
    time        = getValue(userdata.time.value);
    currentbal  = getValue(userdata.currentbal.value);
    amount      = getValue(userdata.amount.value);
  
  var monthSav = 0;
  var nomRate = 0;
  var ret = 1;  
  var saveGap = 0;
  var valofSav = 0;
  var i = 0;
  var m = 0;
  var q = 0;
  var noSaveGap = 0;

  //Value of Savings
  rate = rate * .01; 
  for (index=1; index <= time; index++) {
        ret = ret + ret * rate;
  }
  ret = ret * 100;
  ret = Math.round(ret);
  ret = ret/100;
     
  valofSav = currentbal * ret;
  saveGap = amount - valofSav;
  if (saveGap <= 0) {
        noSaveGap = 1;
  }
    
  //Monthly savings requirement
  nomRate=(Math.pow((1+rate),(1/12)))-1;
  i = 1 + nomRate;
  m = time * 12;
  for (index=1; index <= m; index++) {
        q = q + (Math.pow(i,index))
  }
  
  monthSav = saveGap/q;              
  monthSav = monthSav * 100;
  monthSav = Math.round(monthSav);
  monthSav = monthSav/100;  

  valofSav = formatUSCurrency(valofSav)
  saveGap  = formatUSCurrency(saveGap)
  monthSav = formatUSCurrency(monthSav)
  valofSav = removeCents(valofSav)
  saveGap  = removeCents(saveGap)  

        //// DISPLAY RESULTS
        
        if (noSaveGap == 0) {
            results = ('The value of your current savings when the purchase is made will be ' + valofSav + '.');
            results += ('  This leaves a savings gap of ' + saveGap + '.');
            results += (' To obtain your goal you must save ' + monthSav + ' a month over the next ' + time + ' years.  ');
            results += ('Savings growth based on annual interest compounding.');
        } else {
            results = ('Based on the information provided you currently have sufficient funds for your anticipated purchase.  Your savings balance will be ');
            results += ( valofSav );
            results += (' at the time of the purchase.  ');
            results += ('Savings growth based on annual interest compounding.'); 
        }

		alert(results);

}
