// JavaScript Document

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_showHideLayers() { //v6.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}

// patched to support sticky tabs - dave Tue Jun 22 16:07:21 MST 2004 @5 /Internet Time/
function MM_swapImgRestore(active) { //v3.0
  var i,x,a=document.MM_sr; 
  for(i=0; a && i < a.length && (x=a[i]) && x.oSrc; i++) {
      if(active != x.src) {
          // alert("active: " + active);
          // alert("x.src: " + x.src);
          x.src =   x.oSrc;
      }
  }
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function NewWindow(mypage, myname, w, h, scroll) {
var winl = (screen.width - w) / 2;
var wint = (screen.height - h) / 2;
winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',resizable'
win = window.open(mypage, myname, winprops)
if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
}



function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}



function YY_checkform() { //v4.71
//copyright (c)1998,2002 Yaromat.com
  var a=YY_checkform.arguments,oo=true,v='',s='',err=false,r,o,at,o1,t,i,j,ma,rx,cd,cm,cy,dte,at;
  for (i=1; i<a.length;i=i+4){
    if (a[i+1].charAt(0)=='#'){r=true; a[i+1]=a[i+1].substring(1);}else{r=false}
    o=MM_findObj(a[i].replace(/\[\d+\]/ig,""));
    o1=MM_findObj(a[i+1].replace(/\[\d+\]/ig,""));
    v=o.value;t=a[i+2];
    if (o.type=='text'||o.type=='password'||o.type=='hidden'){
      if (r&&v.length==0){err=true}
      if (v.length>0)
      if (t==1){ //fromto
        ma=a[i+1].split('_');if(isNaN(v)||v<ma[0]/1||v > ma[1]/1){err=true}
      } else if (t==2){
        rx=new RegExp("^[\\w\.=-]+@[\\w\\.-]+\\.[a-zA-Z]{2,4}$");if(!rx.test(v))err=true;
      } else if (t==3){ // date
        ma=a[i+1].split("#");at=v.match(ma[0]);
        if(at){
          cd=(at[ma[1]])?at[ma[1]]:1;cm=at[ma[2]]-1;cy=at[ma[3]];
          dte=new Date(cy,cm,cd);
          if(dte.getFullYear()!=cy||dte.getDate()!=cd||dte.getMonth()!=cm){err=true};
        }else{err=true}
      } else if (t==4){ // time
        ma=a[i+1].split("#");at=v.match(ma[0]);if(!at){err=true}
      } else if (t==5){ // check this 2
            if(o1.length)o1=o1[a[i+1].replace(/(.*\[)|(\].*)/ig,"")];
            if(!o1.checked){err=true}
      } else if (t==6){ // the same
            if(v!=MM_findObj(a[i+1]).value){err=true}
      }
    } else
    if (!o.type&&o.length>0&&o[0].type=='radio'){
          at = a[i].match(/(.*)\[(\d+)\].*/i);
          o2=(o.length>1)?o[at[2]]:o;
      if (t==1&&o2&&o2.checked&&o1&&o1.value.length/1==0){err=true}
      if (t==2){
        oo=false;
        for(j=0;j<o.length;j++){oo=oo||o[j].checked}
        if(!oo){s+='* '+a[i+3]+'\n'}
      }
    } else if (o.type=='checkbox'){
      if((t==1&&o.checked==false)||(t==2&&o.checked&&o1&&o1.value.length/1==0)){err=true}
    } else if (o.type=='select-one'||o.type=='select-multiple'){
      if(t==1&&o.selectedIndex/1==0){err=true}
    }else if (o.type=='textarea'){
      if(v.length<a[i+1]){err=true}
    }
    if (err){s+='* '+a[i+3]+'\n'; err=false}
  }
  if (s!=''){alert('The required information is incomplete or contains errors:\t\t\t\t\t\n\n'+s)}
  document.MM_returnValue = (s=='');
}


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 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 formatPercentpts(theNumber,decimalPlaces) {
  theNumber = getValue(theNumber);
  with (Math) theNumber = (round(theNumber * pow(10,decimalPlaces))) / pow(10,decimalPlaces);
  return(theNumber + "%");
}

function removeCents(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)
    }

    theNumber = getValue(workingNumber)

    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
    }

    if (isNegative == 1) {
      theString = "-$" + dollarAmt
      //theString = "($" + dollarAmt + "." + centsValue + ")"
    } else {
      theString = "$" + dollarAmt
    }

    dollarValue = "$" + dollarAmt
    return(theString)
  } else {
    return("$0")
  }
}

function calculate() {

    userdata    = document.forms[0];
    price       = getValue(userdata.price.value);
    percentdown = getValue(userdata.percentdown.value);
    rate        = getValue(userdata.rate.value);
    points      = getValue(userdata.points.value);
    taxes       = getValue(userdata.taxes.value);
    insurance   = getValue(userdata.insurance.value);
    term        = getValue(userdata.term.options[userdata.term.selectedIndex].text);

    var mortgage

    results = document.forms[0].results

    if (percentdown > 100) {
            results.value  = ('Your down payment should never exceed 100%.  ')
            results.value += ('You have entered a down payment of ' + percentdown + '%.')
    } else if ( (price == 0) || (rate == 0) ) {
            results.value  = ('Sorry...Some important information is missing from your form.  ')
            results.value += ('Please fill-in all necessary fields, and click "Calculate" again.');
    } else {


	    if (percentdown < 100) {
	        downpayment = (percentdown * price)/100
	    } else {
		downpayment = percentdown
	    }


	 //// MORTGAGE AND percentdown AMOUNTS

	  ratioDown = downpayment/price * 100

	  if (term >= 25) {
	    if (ratioDown >= 20) {
		MIfactor = 0
	    } else if (ratioDown >= 15) {
		MIfactor = .39
	    } else if (ratioDown >= 10) {
		MIfactor = .52
	    } else if (ratioDown >= 5) {
		MIfactor = .78
	    } else {
		MIfactor = 1.04
	    }

	  } else if (term == 20) {

	    if (ratioDown >= 20) {
		MIfactor = 0
	    } else if (ratioDown >= 15) {
		MIfactor = .21
	    } else if (ratioDown >= 10) {
		MIfactor = .41
	    } else if (ratioDown >= 5) {
		MIfactor = .67
	    } else {
		MIfactor = .79
	    }

	  } else {

	    if (ratioDown >= 20) {
		MIfactor = 0
	    } else if (ratioDown >= 15) {
		MIfactor = .21
	    } else if (ratioDown >= 10) {
		MIfactor = .41
	    } else if (ratioDown >= 5) {
		MIfactor = .67
	    } else {
		MIfactor = .79
	    }
	  }

	//// INSURANCE RATES - NOT BEING USED

	    ////propertyInsur = 17.5
	    ////if (taxes == 0) taxes = propertyInsur

	    ////homeownersInsur = 3
	    ////if (insurance == 0) insurance = homeownersInsur

	//// TAX BRACKET

	    if (term == 15) taxBracket = 15
	    if (term == 20) taxBracket = 17
	    if (term == 25) taxBracket = 28
	    if (term == 30) taxBracket = 33

	    mortgage       = price - downpayment
	    payment        = monthlyPayment(term, rate, mortgage)

	    //maxMortgage    = payment
	    monthlyTAX     = (taxes + insurance) / 12

	    monthlyMI 	   =  (MIfactor * mortgage) / 12 / 100

	    PITI 	   = payment + monthlyTAX + monthlyMI
	    PITI           = Math.round(PITI * 100) / 100;

	    payment        = Math.round(payment * 100) / 100;
	    monthlyTAX     = Math.round(monthlyTAX * 100) / 100;
	    monthlyMI      = Math.round(monthlyMI * 100) / 100;

	 //// POINTS

	    pointsPaid = mortgage * points / 100

	 //// LOAN AMOUNT & APR

	    monthly = payment + monthlyMI
	    amountFinanced = mortgage - (mortgage * .01) - 375 - (mortgage * rate / 100 / 365 * 30)

	    loanAmount = price - downpayment
	    APR = figureLoanAPR(term, rate, loanAmount, monthly)

	 /// CLOSING COSTS

	    closingCosts = (mortgage * .01) + 850 + (mortgage / 1000 * 2.1)

	 //// PREPAIDS

	    prePaids = (price * rate / 100 / 365 * 30) + ((taxes + insurance) / 12) + (monthlyMI * 2)

	 //// RESERVES

	    if (ratioDown >= 20) {
		reserves = PITI
	    } else {
		reserves = PITI * 2
	    }

	 //// TOTAL CASH

	    totalCash = downpayment + pointsPaid + closingCosts + prePaids + reserves

	 //// FORMAT RESULTS

	    downpayment    	= formatUSCurrency(downpayment)
	    mortgage     	= formatUSCurrency(mortgage)
	    payment           	= formatUSCurrency(payment)
	    monthlyTAX          = formatUSCurrency(monthlyTAX)
	    monthlyMI		= formatUSCurrency(monthlyMI)
	    PITI            	= formatUSCurrency(PITI)
	    price            	= formatUSCurrency(price)
	    APR                 = formatPercent(APR,3)
	    closingCosts    	= formatUSCurrency(closingCosts)
	    pointsPaid    	= formatUSCurrency(pointsPaid)
	    prePaids    	= formatUSCurrency(prePaids)
	    reserves    	= formatUSCurrency(reserves)
	    totalCash    	= formatUSCurrency(totalCash)


	 //// REMOVE CENTS

	    price 	 = removeCents(price)
	    downpayment  = removeCents(downpayment)
	    mortgage 	 = removeCents(mortgage)
	    closingCosts = removeCents(closingCosts)
	    pointsPaid   = removeCents(pointsPaid)
	    prePaids     = removeCents(prePaids)
	    reserves     = removeCents(reserves)
	    totalCash    = removeCents(totalCash)

	 //// DISPLAY RESULTS

	    if (percentdown >= 5) {
               results.value += ('\r\n');
	    }

            results.value = ('Based on the information you have provided, ');
            results.value += ('you will need the following amounts to  ');
            results.value += ('purchase a home of  ');
            results.value += ( price );
            results.value += (' with a mortgage amount of  ');
            results.value += ( mortgage );
            results.value += ('. ');

            results.value += ('\r\n\r\n');

            results.value += ('Downpayment:                       ' + downpayment  + '\r\n');
            results.value += ('Discount Points:                   ' + pointsPaid  + '\r\n');
            results.value += ('Closing Costs:                     ' + closingCosts  + '\r\n');
            results.value += ('Prepaids:                          ' + prePaids  + '\r\n');
            results.value += ('Reserves:                          ' + reserves  + '\r\n');
            results.value += ('Total Cash:                        ' + totalCash  + '\r\n');

            results.value += ('\r\n\r\n');
            results.value += ('Your total monthly payment would be: ');
	    results.value += ('\r\n');
            results.value += ('P&I Payment:                       ' + payment  + '\r\n');
            results.value += ('Monthly Tax/Ins. Escrows:          ' + monthlyTAX + '\r\n');
            results.value += ('Monthly MI:                        ' + monthlyMI  + '\r\n');
            results.value += ('Total PITI:                        ' + PITI       + '\r\n');
            results.value += ('Estimated Annual Percentage Rate:  ' + APR       + '\r\n');

    }


}


function monthlyPayment(term, rate, loanAmount) {
  if (rate > 1) { (rate = rate / 100); }
  rateMonthly = (rate / 12);

  totalPayments = (term * 12);
  if (rate == 0) {
      payment = (loanAmount / totalPayments)
  } else {
      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 + pointsPaid + (((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 menu_item (image_name,width,height) {
	if (document.images) {
		image_prefix = "images/resource_buttons/" + image_name;
		this.menu_image_off = new Image (width,height);
		this.menu_image_off.src = image_prefix + "-off.gif";
		this.menu_image_on = new Image (width,height);
		this.menu_image_on.src = image_prefix + "-on.gif";
		this.menu_image_over = new Image (width,height);
		this.menu_image_over.src = image_prefix + "-on.gif";
	}
}
function menu_active (itemID) {
	if (document.images) {
        if (itemID != whereami) {
			document[itemID].src = menu_item[itemID].menu_image_over.src;			
		}
	}
}
function menu_inactive (itemID) {
	if (document.images) {
		if (itemID != whereami) {
			document.images[itemID].src = menu_item[itemID].menu_image_off.src;
		}
	}
}
function new_menu_item (image_name,width,height) {
	 menu_item[image_name] = new menu_item (image_name,width,height);
}
function menu_click (itemID) {
	if (document.images) {
		document.images[itemID].src = menu_item[itemID].menu_image_on.src;
		whereami = itemID;
		for (var i in imageArray) {
			if (imageArray[i] == itemID) {}
			else {
				document.images[imageArray[i]].src = menu_item[imageArray[i]].menu_image_off.src;
			}
		}
	}
}

function loadImages () {
	if (document.images) {
		new_menu_item ("fitness_calcs",144,38);
        new_menu_item ("get_informed",141,38);
        new_menu_item ("inspired",141,38);
        new_menu_item ("know",144,38);
		imageArray = new Array("fitness_calcs","get_informed","inspired","know");
		whereami = 'fitness_calcs';
	}
}

loadImages();

function bookmarkPage() {
    if ( (navigator.appName == "Microsoft Internet Explorer") && (parseInt(navigator.appVersion) >= 4) && (navigator.userAgent.toLowerCase().indexOf("win") != -1) ) {
        window.external.AddFavorite(location.href, document.title);
    } else {
        alert("To bookmark this page, click \"OK\" below    \nand then press Control-D on your keyboard.\n(Macintosh users press Command-D.)");
    }
    return false;
}

