//Title:      Pre-Qualification calculator
//Version:    1.02
//Copyright:  Copyright (c) 2001
//Author:     REVIE
//Company:    Rhino Internet


/**
 * Does the calculations for the Pre-Qualification calculator
 *
 * <p>
 * <b>Changelog:</b><pre>
 *   1.00  REVIE 1999/12/17  created
 *   1.01  REVIE 2001/02/12  added loan types
 *   1.02  REVIE 2001/03/02  selects conforming or non-conforming
 *                           automatically for conventional loans
 * </pre>
 *
 * @version 1.02
 * @author  REVIE
 * @since   JDK1.1
 */


// -----------------------------------------------
//
//  variables
//


var visible  = 'show';
var hidden   = 'hide';

if(document.all) {
   visibile = 'visible';
   hidden   = 'hidden';
}

var states      = new Array();
var stateMenu   = new Array();
var typeMenu    = new Array();
var changed     = false;

//my version of jscript "constants"

function FHA()    {return 1;}
function VA()     {return 2;}
function CONV()   {return 3;}
function CONF()   {return 4;}
function NONCONF(){return 5;}

// -----------------------------------------------
//
//  constructors
//


function rateClass(desc,term,progid,upper,lower,minltv,maxltv,taxperc,insperc,
                   fees, feeperc, eTax, eMI, type)
{
   this.rate     = 0;
   this.points   = 0;
   this.apr      = 0;
   this.desc     = desc;
   this.term     = term;
   this.progid   = progid;
   this.upper    = upper;
   this.lower    = lower;
   this.minltv   = minltv;
   this.maxltv   = maxltv;
   this.taxperc  = taxperc;
   this.insperc  = insperc;
   this.fees     = fees;
   this.feeperc  = feeperc;
   this.est_taxes= eTax;
   this.est_mi   = eMI;
   this.type     = type;

   this.mi       = new Array();
   this.miminltv = new Array();
   this.mimaxltv = new Array();

   this.frontratio = new Array();
   this.backratio  = new Array();
   this.ratminltv  = new Array();
   this.ratmaxltv  = new Array();
} // rateCLass



// -----------------------------------------------
//
//  data load methods
//


function newRate(state,stateName,desc,term,progid,upper,lower,minltv,maxltv,
                 taxperc,insperc,fees,feeperc,eTax,eMI,loanType)
{

   if(states[state]==null) {
      states[state] = new State();
      states[state].state = state;
      states[state].name  = stateName;
   }

   if (states[state].type[loanType]==null) {
     //if (loanType > CONV()) loanType = CONV();
      states[state].type[loanType] = new LoanType();
      states[state].type[loanType].id = loanType;

      var found = 0;
      for (var i=0; !found && i<typeMenu.length; i++) {
         if (typeMenu[i].id == loanType) {
            states[state].type[loanType].name = typeMenu[i].name;
            found = 1;
         }
      }

      if (!found) {
         states[state].type[loanType].name = loanType;
      }
   }

   var progdes = states[state].type[loanType].rates.length;

   if(progdes<0) {
      progdes=0;
   }

   if(states[state].type[loanType].rates[progdes]==null) {
      states[state].type[loanType].rates[progdes]=
         new rateClass(desc, term, progid, upper, lower, 
                       minltv, maxltv, taxperc, insperc, 
                       fees, feeperc, eTax, eMI, loanType);
   } else {
      states[state].type[loanType].rates[progdes].desc      = desc;
      states[state].type[loanType].rates[progdes].term      = term;
      states[state].type[loanType].rates[progdes].progid    = progid;
      states[state].type[loanType].rates[progdes].upper     = upper;
      states[state].type[loanType].rates[progdes].lower     = lower;
      states[state].type[loanType].rates[progdes].minltv    = minltv;
      states[state].type[loanType].rates[progdes].maxltv    = maxltv;
      states[state].type[loanType].rates[progdes].taxperc   = taxperc;
      states[state].type[loanType].rates[progdes].insperc   = insperc;
      states[state].type[loanType].rates[progdes].fees      = fees;
      states[state].type[loanType].rates[progdes].feeperc   = feeperc;
      states[state].type[loanType].rates[progdes].est_taxes = eTax;
      states[state].type[loanType].rates[progdes].est_mi    = eMI;
      states[state].type[loanType].rates[progdes].type      = loanType;
   }
} // newRate


function addRate(state, desc, rate, points, apr, loanType)
{
   if(states[state]==null) {
      states[state] = new State();
      states[state].state = state;
      states[state].name  = state;
   } 

   if (states[state].type[loanType]==null) {
      states[state].type[loanType] = new LoanType();
      states[state].type[loanType].id = loanType;

      for (i in typeMenu) {
         if (i.id == loanType) {
            states[state].type[loanType].name = i.name;
         }
      }
   }

   var progdes = states[state].type[loanType].rates.length-1;
   if(progdes<0) {
      progdes=0;
   }

   if(states[state].type[loanType].rates[progdes]==null) {
      states[state].type[loanType].rates[progdes]= 
         new rateClass(desc, "30", "", confLimitMax, "10000", 
                       "0", "97", ".80", ".33", "0", "0", 
                       "11.3", "5.4", "1", "4");
   }

   states[state].type[loanType].rates[progdes].rate   = rate;
   states[state].type[loanType].rates[progdes].points = points;
   states[state].type[loanType].rates[progdes].apr    = apr;
} // addRate


function addMI(state,desc,miperc,minltv,maxltv, loanType)
{
   if(states[state]==null) {
      states[state] = new State();
      states[state].state = state;
      states[state].name  = state;
   } 

   if (states[state].type[loanType]==null) {
      states[state].type[loanType] = new LoanType();
      states[state].type[loanType].id = loanType;

      for (i in typeMenu) {
         if (i.id == loanType) {
            states[state].type[loanType].name = i.name;
         }
      }
   }

   var progdes = states[state].type[loanType].rates.length-1;
   if(progdes<0) {
      progdes=0;
   }

   if(states[state].type[loanType].rates[progdes]==null) {
      states[state].type[loanType].rates[progdes]=
         new rateClass(desc,"30","",confLimitMax,"10000",
                       "0","97",".80",".33","0","0",
                       "11.3","5.4","4");
   }

   var indx = states[state].type[loanType].rates[progdes].mi.length;
   states[state].type[loanType].rates[progdes].mi[indx]       = miperc;
   states[state].type[loanType].rates[progdes].miminltv[indx] = minltv;
   states[state].type[loanType].rates[progdes].mimaxltv[indx] = maxltv;
   //alert(state+" "+loanType+" "+progdes+" "+indx+ " = " + miperc);   
} // addMI


function addRatio(state,desc,frontratio,backratio,minltv,maxltv,loanType)
{
   if(states[state]==null) {
      states[state] = new State();
      states[state].state = state;
      states[state].name  = state;
   } 

   if (states[state].type[loanType]==null) {
      states[state].type[loanType] = new LoanType();
      states[state].type[loanType].id = loanType;

      for (i in typeMenu) {
         if (i.id == loanType) {
            states[state].type[loanType].name = i.name;
         }
      }
   }

   var progdes = states[state].type[loanType].rates.length-1;
   if(progdes<0) {
      progdes=0;
   }

   if(states[state].type[loanType].rates[progdes]==null) {
      states[state].type[loanType].rates[progdes]= 
         new rateClass(desc,"30","",confLimitMax,"10000",
                       "0","97",".80",".33","0","0",
                       "11.3","5.4","4");
   }

   var indx = states[state].type[loanType].rates[progdes].frontratio.length;
   states[state].type[loanType].rates[progdes].frontratio[indx] = frontratio;
   states[state].type[loanType].rates[progdes].backratio[indx]  = backratio;
   states[state].type[loanType].rates[progdes].ratminltv[indx]  = minltv;
   states[state].type[loanType].rates[progdes].ratmaxltv[indx]  = maxltv;
} // addRatio



// -----------------------------------------------
//
//  form display methods
//

function buildRateMenu(rate)
{
   document.prequal.ProgName1.options.length = 1;
   document.prequal.ProgName1.options.selectedIndex = 0;
   var state   = document.prequal.state.selectedIndex-1;

   var rateName = (rate?'':selectedRateName==null?'':selectedRateName);
   var type = getLoanType();

   if(state>=0 && state<stateMenu.length && hasRates(state, type)) {
      state = getState();

      var i=0;
      for( aMenuIdx in states[state].type[type].rates ) {
         var aMenu = states[state].type[type].rates[aMenuIdx];
         document.prequal.ProgName1.options[i] = 
            new Option(aMenu.desc, aMenu.progid);

         if((rate && aMenuIdx==rate) || 
            (rateName && 
             rateName==states[state].type[type].rates[aMenuIdx].desc)) {
            document.prequal.ProgName1.options.selectedIndex = i;
         }
         i++;
      }

      changed=false;
   } else {
      resetRateMenu();
   }
} // buildRateMenu


function resetLoanTypeMenu(text) {
   var typeTxt = "- Select -";
   document.prequal.loanType.options.length = 1;

   document.prequal.loanType.options[0] = new Option(typeTxt,"");
   document.prequal.loanType.options.selectedIndex = 0;
   resetRateMenu(text);
} // resetLoanTypeMenu


function resetRateMenu(text) {
   if(!text) { 
      text = "- Select -";
   }

   document.prequal.ProgName1.options.length = 1;

   document.prequal.ProgName1.options[0] = new Option(text,"");
   document.prequal.ProgName1.options.selectedIndex = 0;

   calc_it("ProgName1", getLoanType());
} // resetRateMenu


function addState(state,name) {
   var idx = stateMenu.length;

   if(stateMenu[idx]==null) {
      stateMenu[idx] = new State();
   }

   stateMenu[idx].state = state;
   stateMenu[idx].name  = name;
} // addState


function getState() {
   var idx = document.prequal.state.selectedIndex;
   if (idx>0) {
      return document.prequal.state.options[idx].value;
   } else {
      return '';
   }
} // getState


function State() {
   this.state = "";
   this.name  = "";
   this.type = new Array();
} // State


function addLoanType(id, name) {
   var idx = typeMenu.length;

   if(typeMenu[idx]==null) {
      typeMenu[idx] = new LoanType();
   }

   typeMenu[idx].id = id;
   typeMenu[idx].name  = name;
} // addLoanType


function getLoanType()
{
   var type = document.prequal.loanType.selectedIndex;
   if (type<=0) {
      return -1;
   } else {
      type = document.prequal.loanType.options[type].value;
   }

   if (type==CONV()) { // conforming
      if (document.prequal.maxloan0.value > 275000) {
         type = NONCONF();
      } else {
         type = CONF();
      }
   }

   return type;
} // getLoanType


function LoanType() {
   this.id = "";
   this.name  = "";
   this.rates = new Array();
} // State


// -----------------------------------------------
//
//  miscellaneous methods
//


function isValidState(idx) {
   var state = getState();
   if(!state) {
      return(0);
   }

   var valid = false;
   for(var i=0; i<validStates.length; i++) {
      //alert (state + " ?= " + validStates[i]);

      if(state == validStates[i]) { 
         return(1);
      }
   }

   return(0);
} // isValidState


function hasRates(idx, loanType) {
   state = getState();

   if(state && isValidState(state) && states[state]!=null && 
      states[state].type[loanType]!=null) { 
      return(1);
   } else { 
      return(0);
   }
} // hasRates


function buildStateMenu(state) {
   document.prequal.state.options.length = 1;

   var i=1;
   document.prequal.state.options[0] = new Option("- Select -","");
   document.prequal.state.options.selectedIndex = 0;

   for( aMenuIdx in stateMenu ) {
      var aMenu = stateMenu[aMenuIdx];

      if (includeState(aMenu)) {
         document.prequal.state.options[i] = 
            new Option(aMenu.name, aMenu.state);

         if(aMenu.state==state) {
            document.prequal.state.options.selectedIndex = i;
         }
         i++;
      }
   }

   buildLoanTypeMenu(selectedLoanType);
} // buildStateMenu


function buildLoanTypeMenu(loanType) {
   document.prequal.loanType.options.length = 1;
   var state = document.prequal.state.selectedIndex-1;

   var i=1;
   var opt = 0;
   document.prequal.loanType.options[0] = 
      new Option("- Select -","");
   document.prequal.loanType.options.selectedIndex = 0;

  if(state>=0 && state<stateMenu.length) {
      state = getState();

      for( j in states[state].type ) {
         var aMenu = states[state].type[j];
         if (!aMenu.name) {
            continue;
         }
         //sort in order of conv, fha, va
         //1 = fha
         if (aMenu.name == "FHA") opt = 2;
         //2 = va
         else if (aMenu.name == "VA") opt = 3;
         //3 =  set conf or nonconf to conv
         else {
            aMenu.name = "Conventional";  opt = 1;
            aMenu.id = CONV();   
         }
         
         
         if (opt > 0) {
            document.prequal.loanType.options[opt] = 
               new Option(aMenu.name, aMenu.id);
            opt = 0;
         }
         if(aMenu.id==loanType) {
            document.prequal.loanType.options.selectedIndex = i;
         }
         i++;
      }
   }

   buildRateMenu(selectedRate);
} // buildLoanTypeMenu


//for now we can statically allocate states
function includeState(aMenu) {
 
   if (aMenu.state == "AZ") {
      return true;
   }

   return false;  
   
} // includeState


function RateChange() {
   var i;
   var progdes = document.prequal.ProgName1.selectedIndex;
   var state   = document.prequal.state.selectedIndex-1;
   var type    = getLoanType();

   if(progdes>=0 && state>=0 && state<stateMenu.length &&
      hasRates(state,type)) {

      state = getState();

      document.prequal.desc.value = 
         states[state].type[type].rates[progdes].desc;
      document.prequal.term.value =
         states[state].type[type].rates[progdes].term;
      document.prequal.upper.value =
         states[state].type[type].rates[progdes].upper;
      document.prequal.lower.value =
         states[state].type[type].rates[progdes].lower;
      document.prequal.minltv.value =
         states[state].type[type].rates[progdes].minltv;
      document.prequal.maxltv.value =
         states[state].type[type].rates[progdes].maxltv;
      document.prequal.taxperc.value =
         states[state].type[type].rates[progdes].taxperc;
      document.prequal.fees.value =
         states[state].type[type].rates[progdes].fees;

      document.prequal.ratesheet1.value  = 
         fmt_pct(states[state].type[type].rates[progdes].rate);
      //document.prequal.pointsheet1.value =
      //   states[state].type[type].rates[progdes].points;
      //document.prequal.aprsheet1.value   =
      //   fmt_pct(states[state].type[type].rates[progdes].apr);

      document.prequal.downalert.value = "";
   } else { 
      progdes = -1; 

      document.prequal.desc.value    = "";
      document.prequal.term.value    = "30";
      document.prequal.upper.value   = confLimitMax;
      document.prequal.lower.value   = "10000";
      document.prequal.minltv.value  = "0";
      document.prequal.maxltv.value  = "95";
      document.prequal.taxperc.value = "0.000%";
      document.prequal.fees.value    = "0";

      document.prequal.ratesheet1.value  = "0.000%";
      //document.prequal.pointsheet1.value = "0";
      //document.prequal.aprsheet1.value   = "0.000%";
   }

   document.prequal.progalert.value = "";
   changed=false;

   calc_it("ProgName1", type);
} // RateChange


function getStateNumber(stateval) {
   
   for (var i=0;i<stateMenu.length;i++) {
      if (stateval == stateMenu[i].state) {
         return i;
      }
   }

   return -1;
} // getStateNumber


function StateChange() {
   //var state = document.prequal.state.selectedIndex-1;
   
   var state = 
      getStateNumber(document.prequal.state.options
                     [document.prequal.state.selectedIndex].value);

   if(state>=0 && state<stateMenu.length && !isValidState(state)) {
      resetLoanTypeMenu();
      document.prequal.progalert.value = "";
      saveInfo();
      document.prequal.submit();
      return(true);
   } else if(state>=0 && state<stateMenu.length) {
      buildLoanTypeMenu(selectedLoanType);
      LoanTypeChange();
   } else if(state>=0 && state<stateMenu.length && isValidState(state)) {
      resetLoanTypeMenu("- No rates for "+stateMenu[state].name+" -");
      
   } else {
      resetLoanTypeMenu();
   }
} // StateChange


function LoanTypeChange() {
   //var state = document.prequal.state.selectedIndex-1;

   var state = 
      getStateNumber(document.prequal.state.options
                     [document.prequal.state.selectedIndex].value);
   var type = getLoanType();

   if(state>=0 && state<stateMenu.length && hasRates(state,type)) {
      buildRateMenu(selectedRate);
   } else if(state>=0 && state<stateMenu.length && !isValidState(state)) {
      resetRateMenu();
      document.prequal.progalert.value = "";
      saveInfo();
      document.prequal.submit(); 
      return(true);
   } else if(state>=0 && state<stateMenu.length && isValidState(state)) {
      resetRateMenu("- No rates for "+stateMenu[state].name+" -");
      
   } else {
      resetRateMenu();
   }

   RateChange();
} // LoanTypeChange


function st_pct(rate) {
   var newnum, ch;
   newnum = "";

   for (var i=0; i<rate.length; i++) {
      ch = rate.charAt(i);
      if((ch >= "0" && ch <= "9") || (ch==".")) {
         newnum += ch;
      }
   }

   if(newnum.length>0) {
      return parseFloat(newnum);
   } else { 
      return(0);
   }
} // st_pct


function fmt_pct(input) {
   var res, len;
   input = st_pct(input)+"";
   len = input.indexOf(".");

   if (len == -1) {
      len = input.length;
      res = ".000";
   } else {
      res = input.substring(len, input.length);
      if(res.length>4) {
         res = res.substring(0,4);
      } else {
         for(var i=res.length; i<4; i++) {
            res += "0";
         }
      } 
   }

   res = input.substring(0, len) + res + "%";
   return res;
} // fmt_pct


function fmt_pmt(input) {
   var res, len;
   input += "";
   len = input.indexOf(".");

   if (len == -1) {
      len = input.length;
      res = "";
   } else {
      input = ""+(parseFloat(input)+0.005);
      len = input.indexOf(".");
      res = input.substring(len, input.length);

      if(res.length>3) {
         res = res.substring(0,3);
      } else {
         for(var i=res.length; i<3; i++) {
            res += "0";
         }
      } 
   }

   while(len > 4) {
      res = input.substring(len-3, len) + res;
      res = "," + res;
      len -= 3;
   }

   res = input.substring(0, len) + res;
   return res;
} // fmt_pmt


function fixfield(fldnm) {
   if((fldnm != "userterm") && (fldnm != "option")) {

      var formfld = "document.prequal." + fldnm;
      var price=eval(formfld + ".value");
      var newnum, ch;
      var intval = 99;

      newnum = "";

      for (var i=0; i<price.length; i++) {
         ch = price.charAt(i);
         if((ch >= "0") && (ch <= "9") || (ch==".") || (ch=="-")) {
            newnum += ch;
         }
      }

      if(newnum.length == 0) {
         newnum = 0;
      }

      //alert("new num = " + newnum);
      if(fldnm=='ratesheet1' || fldnm=='downPerc') {
         eval(formfld + ".value = '" + newnum + "%'");
         document.prequal.downalert.value = "";
      } else {
         eval(formfld + ".value = " + newnum);
      }
   }
   document.prequal.progalert.value = "";

   calc_it(fldnm, getLoanType());
} // fixfield


function fixtext(element,fldnm,head,foot) {
   var fldval  = eval("document.prequal." + element + ".value");

   if(document.all) {
      document.all[fldnm].innerHTML = head+fldval+foot;
   } else if(document.layers) {
      // don't know how to do it in Netscape.  Should be able to change with:
      //   document.layers[fldnm].document.open();
      //   document.layers[fldnm].document.write(head+fldval+foot);
      //   document.layers[fldnm].document.close();
      // but it doesn't work.  Grrr...
   }
} // fixtext


function calc_mopay(state,progdes,loanType,inc,debt,ratio) {
   var minpay,maxpay,m_pmt,frontratio,backratio;

   // first, let's get some ratios!  Woohoo!
   var ratioLength = 
      states[state].type[loanType].rates[progdes].frontratio.length;

   var found = -1;
   if (getLoanType() >= CONV()) {
      frontratio = 30; backratio = 40;
   }

   //grab from database
   for(var i=0; found<0 && i<ratioLength; i++) {
      if(ratio >= 
         parseFloat(states[state].type[loanType].rates[progdes].ratminltv[i]) 
       && ratio <= 
         parseFloat(states[state].type[loanType].rates[progdes].ratmaxltv[i])
        )
      { 
        frontratio =
            states[state].type[loanType].rates[progdes].frontratio[i];
         backratio = 
            states[state].type[loanType].rates[progdes].backratio[i];
         found=i;
      }
   }
   //override calculated rates for VA and FHA
   if (getLoanType() == VA()) {
      frontratio = backratio = 45; found=-1;
   }
   else if (getLoanType() == FHA()) {
      frontratio = 35; backratio = 45; found=-1;
   }
   
   if(!isNaN(frontratio) && parseFloat(frontratio)>0) {
      minpay = (parseFloat(frontratio)/100) * inc;
   } else { 
      minpay = 0;
   }

   if(!isNaN(backratio) && parseFloat(backratio)>0) {
      maxpay = ((parseFloat(backratio)/100) * inc) - debt;
   } else { 
      maxpay = 0;
   }

   if(minpay>0 && minpay<maxpay) { 
      m_pmt = minpay;
   } else if(maxpay>0) { 
      m_pmt = maxpay;
   } else { 
      m_pmt = 0;
   }

   return(m_pmt);
} // calc_mopay


function calc_it(whchanged, loanType) {

   if (loanType == CONV()) {
      loanType++;
   }
   
   var b_inc, c_inc, i_inc, r_inc, o_inc, t_inc;
   var c_deb, a_deb, i_deb, s_deb, o_deb, t_deb;

   b_inc = document.prequal.inc_emp.value;
   b_inc != "" ? b_inc = b_inc : b_inc = "0";
   c_inc = document.prequal.inc_com.value;
   c_inc != "" ? c_inc = c_inc : c_inc = "0";
   i_inc = document.prequal.inc_inv.value;
   i_inc != "" ? i_inc = i_inc : i_inc = 0;
   r_inc = document.prequal.inc_rnt.value;
   r_inc != "" ? r_inc = r_inc : r_inc = 0;
   o_inc = document.prequal.inc_oth.value;
   o_inc != "" ? o_inc = o_inc : o_inc = 0;
   t_inc = parseInt(b_inc) + parseInt(c_inc) + parseInt(i_inc) + 
      parseInt(r_inc) + parseInt(o_inc);
   document.prequal.inc_tot.value = fmt_pmt(t_inc);
   c_deb = document.prequal.deb_ccr.value;
   c_deb != "" ? c_deb = c_deb : c_deb = "0";
   a_deb = document.prequal.deb_car.value;
   a_deb != "" ? a_deb = a_deb : a_deb = "0";
   i_deb = document.prequal.deb_ins.value;
   i_deb != "" ? i_deb = i_deb : i_deb = 0;
   s_deb = document.prequal.deb_cld.value;
   s_deb != "" ? s_deb = s_deb : s_deb = 0;
   o_deb = document.prequal.deb_oth.value;
   o_deb != "" ? o_deb = o_deb : o_deb = 0;
   t_deb = parseInt(c_deb) + parseInt(a_deb) + parseInt(i_deb) +
      parseInt(s_deb) + parseInt(o_deb);
   document.prequal.deb_tot.value = fmt_pmt(t_deb);

   var inctest = document.prequal.incalert.value;
   var debtest = document.prequal.debalert.value;

   inctest = "1"; // don't need to show these, but leave them around 
   debtest = "1"; // just in case.

   if((t_inc > 20000) && (inctest != "1")) {
      alert("Are you sure the income you stated is your MONTHLY income, "+
            "not annual?");
      document.prequal.incalert.value = "1"; // only show this message once
   }

   if((t_deb > 3000) && (debtest != "1")) {
      alert("Are you sure the debt payments you stated are MONTHLY "+
            "payments, not balances?");
      document.prequal.debalert.value = "1"; // only show this message once
   }


   var state   = document.prequal.state.selectedIndex-1;
   var progdes = document.prequal.ProgName1.selectedIndex;
   var type    = loanType;
 
   if(progdes>=0 && state>=0 && 
      state<stateMenu.length && hasRates(state, type)) {
      state = getState();
   } else { 
      progdes=-1;
   }
   //alert(type);

   var mopay,term,rate,points,apr,tax,ins,mi,fees,feeperc,est_tax,est_mi,
      upper,lower,minltv,maxltv,d_perc;
   var l_amt,ol_amt,m_pri,p_pri,d_pmt,h_pmt,p_tax,m_tax,a_tax,mi_term,m_mi;
   var testratio,x,t_rate;

   d_perc= st_pct(document.prequal.downPerc.value);
   d_pmt = 0;
   if(progdes >= 0 && type>=0) {

      mopay   = calc_mopay(state,progdes,type,t_inc,t_deb,(100-d_perc));
      term    = states[state].type[type].rates[progdes].term;
      rate    = states[state].type[type].rates[progdes].rate;
      points  = states[state].type[type].rates[progdes].points;
      apr     = states[state].type[type].rates[progdes].apr;
      tax     = states[state].type[type].rates[progdes].taxperc;
      ins     = states[state].type[type].rates[progdes].insperc;
      fees    = states[state].type[type].rates[progdes].fees;
      feeperc = states[state].type[type].rates[progdes].feeperc;
      est_tax = states[state].type[type].rates[progdes].est_taxes;
      est_mi  = states[state].type[type].rates[progdes].est_mi;
      upper   = states[state].type[type].rates[progdes].upper;
      lower   = states[state].type[type].rates[progdes].lower;
      minltv  = states[state].type[type].rates[progdes].minltv;
      maxltv  = states[state].type[type].rates[progdes].maxltv;
      if(changed) {
         rate   = document.prequal.ratesheet1.value;
         apr    = rate;
         points = 0;
      }
   } else {
      mopay   = 0;
      term    = 30;
      rate    = 0;
      points  = 0;
      apr     = 0;
      tax     = 0.80;
      ins     = 0.33;
      fees    = 0;
      feeperc = 0;
      est_tax = 11.3;
      est_mi  = 5.4;
      upper   = 247000;
      lower   = 10000;
      minltv  = 0;
      maxltv  = 100;
   }
   term = parseFloat(term);
   mi_term = (term>0 ? term*12 : 1);
   term = (term>0 ? term : 1);
   document.prequal.payment.value = mopay;
   h_pmt = mopay;
   
   t_rate= (1-(1/Math.pow((1+(parseFloat(rate)/1200)),mi_term)))/
      (parseFloat(rate)/1200);

   var debug = "";
   var ltv = 100-d_perc;
   
   if (mopay>0 
      && (d_perc>0 || (getLoanType() == VA() && d_perc>=0)) 
      && ltv>=parseFloat(minltv) && 
      ltv<=parseFloat(maxltv) && !isNaN(t_rate)) {

      //alert ("Loan Rate: " + fmt_pmt(rate) + "%\n" +
      //       "Monthly Insurance Term: " + mi_term + "\n" +
      //       "T Rate: " + fmt_pmt(t_rate) + "%\n" +
      //       "Maximum Monthly Payment: $" + fmt_pmt(mopay) + "\n" +
      //       "Down Payment Percentage: " + fmt_pmt(d_perc) + "%\n" +
      //       "Estimated Tax: $" + fmt_pmt(est_tax) + "\n" +
      //       "Estimated Mortgage Insurance: $" + fmt_pmt(est_mi) + "\n" +
      //       "Loan-To-Value: " + fmt_pmt(ltv) + "\n" +
      //       "Min/Max LTVs: " + fmt_pmt(minltv) + " to " + fmt_pmt(maxltv));

      // Calculation stuff.  Hopefully it's somewhat accurate.
      if(d_perc <= 20) {
         m_tax = h_pmt * (parseFloat(est_tax)/100);
         m_mi  = h_pmt * (parseFloat(est_mi)/100);
      } else {  
         m_tax = h_pmt * (parseFloat(est_tax)/100);
         m_mi  = 0;
      }
      
      m_pri = h_pmt - (m_tax + m_mi);
      p_pri = m_pri * t_rate;
      l_amt = p_pri*(100/(100-d_perc));
      d_pmt = l_amt-p_pri;
      
      //alert(state+" "+progdes+" "+type+" "+(100-d_perc));
      mi     = getMIrate(state,progdes,type,(100-d_perc));
      
      a_tax  = l_amt*(parseFloat(tax)/100) + l_amt*(parseFloat(ins)/100);
      m_tax  = a_tax/12;
      
      //alert("formula = ("+p_pri+"*("+mi+"/100))/12)");
      m_mi   = (p_pri*(mi/100))/12;
      //alert(" = "+m_mi);
      
      m_pri  = h_pmt - (m_tax + m_mi);
      testratio=100;
      x=1;
      while(l_amt>0 && testratio>0.5 && x<30) {
         ol_amt = l_amt;
         p_pri = m_pri * t_rate;
         l_amt = p_pri*(100/(100-d_perc));
         d_pmt = l_amt-p_pri;

         mi = getMIrate(state,progdes,type,(100-d_perc));
         a_tax  = l_amt*(parseFloat(tax)/100) + l_amt*(parseFloat(ins)/100);
      
         m_mi   = (p_pri*(mi/100))/12;
      
         m_tax  = a_tax/12;
         m_pri  = h_pmt - (m_tax + m_mi);

         testratio = (Math.abs(ol_amt-l_amt)/Math.abs(l_amt))*100;
         x++;

         //if (!confirm("Old loan amount:\t$" + fmt_pmt(ol_amt) + "\n" +
         //             "New loan amount:\t$" + fmt_pmt(l_amt) + "\n" +
         //             "Primary Amount :\t$" + fmt_pmt(p_pri) + "\n" +
         //             "Down Payment   :\t$" + fmt_pmt(d_pmt) + "\n" +
         //             "Mortgage Insur.:\t$" + fmt_pmt(mi) + "\n" +
         //             "Max Monthly Pmt:\t$" + fmt_pmt(h_pmt) + "\n" +
         //             "Approx. Ratio  :\t" + fmt_pmt(testratio) + "%\n" +
         //             "\nContinue?")) {
         //   return;
         //}
      }

      //alert("Found a primary loan amount at $" + fmt_pmt(p_pri) +
      //      ", taking " + x + " tries (and ended with a ratio at "+
      //      fmt_pmt(testratio) + "% too).  Phew!");

      // Supposedly, the below stuff adds on closing costs, but it just
      // makes the output look funny, so it's dropped for now.
      //d_pmt = d_pmt + parseFloat(fees) + l_amt*(parseFloat(feeperc)/100);
      l_amt = Math.round(l_amt);
      p_pri = Math.round(p_pri);
      m_pri = Math.round(m_pri);
      m_tax = Math.round(m_tax);
      m_mi  = Math.round(m_mi);
      d_pmt = Math.round(d_pmt);

      // Phew.  We're done.  Let's clean up and display the results.
      if(isNaN(l_amt)) { l_amt = 0; }
      if(isNaN(p_pri)) { p_pri = 0; }
      if(isNaN(m_pri)) { m_pri = 0; }
      if(isNaN(m_tax)) { m_tax = 0; }
      if(isNaN(m_mi))  { m_mi  = 0; }
      if(isNaN(d_pmt)) { d_pmt = 0; }
         
      if(l_amt<0 || p_pri<0 || m_pri<0 || m_tax<0 ||
         d_pmt<0 || m_mi<0 || p_pri<parseFloat(lower)) {
         document.prequal.maxloan0.value = "$0";
         document.prequal.price0.value   = "$0";
         document.prequal.pmt0.value     = "$0";
         document.prequal.mi0.value      = "$0";
         document.prequal.ti0.value      = "$0";
         document.prequal.amt_dwn.value  = "$0";

         var progtest = document.prequal.progalert.value;
         /* DLR - when all else fails comment out shit */
         /*if(progtest!="1" && p_pri<parseFloat(lower)) {*/
            alert("We are unable to pre-qualify you because your loan amount "+
                  "does not meet our minimum loan requirement.");
            document.prequal.progalert.value = "1";
         /*}*/
      } else {
         var toobig = false;
         //alert("test "+p_pri+">"+upper);
         
         if(p_pri>parseFloat(upper)) {
            p_pri = parseInt(upper);
            l_amt = p_pri*(100/(100-d_perc));
            d_pmt = l_amt - p_pri;

            mi = getMIrate(state,progdes,type,(100-d_perc));
            m_mi  = (p_pri*(mi/100))/12;
            a_tax = l_amt*(parseFloat(tax)/100)+l_amt*(parseFloat(ins)/100);
            m_tax = a_tax/12;
            m_pri = p_pri/t_rate;
            h_pmt = m_pri + (m_tax + m_mi);
            toobig = true;

            l_amt = Math.round(l_amt);
            p_pri = Math.round(p_pri);
            m_pri = Math.round(m_pri);
            m_tax = Math.round(m_tax);
            m_mi  = Math.round(m_mi);
            d_pmt = Math.round(d_pmt);
            if(isNaN(l_amt)) { l_amt = 0; }
            if(isNaN(p_pri)) { p_pri = 0; }
            if(isNaN(m_pri)) { m_pri = 0; }
            if(isNaN(m_tax)) { m_tax = 0; }
            if(isNaN(m_mi))  { m_mi  = 0; }
            if(isNaN(d_pmt)) { d_pmt = 0; }
         }

         document.prequal.maxloan0.value = "$"+fmt_pmt(p_pri);
         //redo the calculation now that we know the total amount
         //- redo it with the correct loan type -tsm
         //alert("testing = "+type+" "+l_amt+">"+confLimitMax);
           
         if (type==CONF() && l_amt >= confLimitMax) {
           // alert("recalc= "+NONCONF());
            calc_it(whchanged,NONCONF());
            return; 
         }
         document.prequal.price0.value   = "$"+fmt_pmt(l_amt);
         document.prequal.pmt0.value     = "$"+fmt_pmt(m_pri);
         document.prequal.mi0.value      = "$"+fmt_pmt(m_mi);
         document.prequal.ti0.value      = "$"+fmt_pmt(m_tax);
         document.prequal.amt_dwn.value  = "$"+fmt_pmt(d_pmt);

         var progtest = document.prequal.progalert.value;
         if(progtest!="1" && toobig) {
            alert("Your qualification has been limited by the maximum loan "+
                  "amount available under this program.  If you would like "+
                  "to pre-qualify for a greater loan amount, please try "+
                  "selecting another program.");
            document.prequal.progalert.value = "1";
         }
      }
   } else {
      // set defaults
      document.prequal.maxloan0.value = "$0";
      document.prequal.price0.value   = "$0";
      document.prequal.pmt0.value     = "$0";
      document.prequal.mi0.value      = "$0";
      document.prequal.ti0.value      = "$0";
      document.prequal.amt_dwn.value  = "$0";
      
      //alert (mopay + "&&"+d_perc+"&&"+t_rate);
      if(mopay>0 && d_perc>0 && !isNaN(t_rate) &&
         !(ltv>=parseFloat(minltv) && ltv<=parseFloat(maxltv))) {

         var downtest = document.prequal.downalert.value;
         if(downtest!="1") {
            alert("Your qualification has been limited by the amount of your "+
                  "down payment.  If you would like to pre-qualify for a "+
                  "different loan amount, please try again by choosing a "+
                  (ltv>parseFloat(maxltv)?"larger":"smaller")+
                  " down payment percentage.");
            document.prequal.downalert.value = "1";
         }
      } else if((d_perc>0) && (t_inc>0 || t_deb>0)) {
         var progtest = document.prequal.progalert.value;
         //DLR - comment comment
         /*if(progtest!="1" && p_pri<parseFloat(lower)) {*/
            alert("We are unable to pre-qualify you because your loan amount "+
                  "does not meet our minimum loan requirement.");
            document.prequal.progalert.value = "1";
         /*}*/
      }
   }
} // calc_it


function getMIrate(state,progdes,type,ratio) {
   var miLength = states[state].type[type].rates[progdes].mi.length;
   
   var mi = "0";
   var found = false;
   if (getLoanType() == VA()) {
      mi = 0.005;  
      return mi;  
   }
   else {
      for(var i=0; !found && i<miLength; i++) {
         var minltv = 
            st_pct(states[state].type[type].rates[progdes].miminltv[i]);
         var maxltv = 
            st_pct(states[state].type[type].rates[progdes].mimaxltv[i]);
         if(minltv<=ratio && maxltv>=ratio) {
            mi = states[state].type[type].rates[progdes].mi[i];
            found = true;
            //alert("mi = "+mi);
         }
         
      }
   }
   document.prequal.miperc.value = mi;
   return(st_pct(mi));
} // getMIrate


function ChangeNotAllowed() {
   alert("This field is calculated.");
} // ChangeNotAllowed


function setfocus() {
   document.prequal.inc_emp.select();
   document.prequal.inc_emp.focus();
} // setfocus


function saveInfo() {
   var state   = document.prequal.state.selectedIndex-1;
   var progdes = document.prequal.ProgName1.selectedIndex;
   var expires = new Date((new Date()).getTime() + 1*60000); // 1 minute exp.
   var type    = document.prequal.loanType.selectedIndex;

   if (type>0) {
      type = document.prequal.loanType.options[type].value;
   } else {
      type = -1;
   }

   if(state>=0 && state<stateMenu.length && isValidState(state)){
      state = getState();
      document.cookie = "selectedState=" + state;// + "; expires=" + expires;
      // expires tag didn't work well with IE (though perfect in Netscape).
   } else { 
      state = "";
   }

   if(state && type && type>0 && states[state].type[type]!=null) {
      document.cookie = "selectedLoanType=" + type;// + "; expires=" + expires;
      if(progdes>0 && states[state].type[type].rates[progdes]!=null) {
         document.cookie = "selectedRate=" + 
            progdes;// + "; expires=" + expires;
      }
   }

   //alert("Cookie for this session:"+document.cookie);
   return(true);
} // prequal.submit()


function selectedValue(aSelectObj) {
   var selectIdx = aSelectObj.selectedIndex;
   var selectStr;
   if (selectIdx < 0) {
      selectStr = "";
   } else {
      selectStr = (aSelectObj.options[selectIdx]).value;
   }
   return selectStr;
}


function selectedText(aSelectObj) {
   var selectIdx = aSelectObj.selectedIndex;
   var selectStr;
   if (selectIdx < 0) {
      selectStr = "";
   } else {
      selectStr = (aSelectObj.options[selectIdx]).text;
   }
   return selectStr;
} // selectedText


function changeRate() {
   changed = true;

   //document.prequal.pointsheet1.value = '0.000';
   //document.prequal.aprsheet1.value   = document.prequal.ratesheet1.value;

   calc_it("ProgName1", getLoanType());
} // changeRate


function getCookieVal(name) {
   var allcookies = document.cookie;
   if(allcookies==null || allcookies.length<=0) { 
      return null;
   }

   var pos = allcookies.indexOf(name+"=");
   if(pos>=0) {
      var start = pos + name.length + 1;
      var end = allcookies.indexOf(";", start);
      return allcookies.substring(start, end);
   } else {
      return null;
   }
} // getCookieVal


function initDocument() {
   fixfield('downPerc');

   if(selectedRate!=null && selectedState!=null) {
      initRates();

      var state = getCookieVal("selectedState");
      if(state!=null) {
         selectedState = state;
      }

      var type = getCookieVal("selectedLoanType");
      if(type!=null) { 
         selectedLoanType = type;
      }

      var rate = getCookieVal("selectedRate");
      if(rate!=null) { 
         selectedRate = rate;
      }

      buildStateMenu(selectedState);
      RateChange();
   }

   setfocus();
} // document initializer

