// create the trim prototype on the String object
String.prototype.trim = function() {
 // skip leading and trailing whitespace
 // and return everything in between
  return this.replace(/^\s*(\b.*\b|)\s*$/, "$1");
}

function BodyOnLoad() {
  //ShowFieldHelp('','');
  //writeMenus();
  var tagname = new String();
  var inputtype = new String();
  //next 3 lines pertain to ipahelpbox.js
  if (!HelpBoxOffset) {
    var HelpBoxOffset = 10;
  }
  if (ie4) {
    this.topMargin = document.all.floatLayer.offsetTop - HelpBoxOffset;
  }
  window.setInterval("main()", 10) 
  element = MM_findObj("Action");
  if (element) {
  element.value = '';
  }
  if (document.forms[0]) {
    for (x = 0; x < document.forms[0].elements.length; x++) {
      tagname = document.forms[0].elements[x].tagName;
      tagname = tagname.toUpperCase();
      if (tagname == 'INPUT') {
        inputtype = document.forms[0].elements[x].type;
        inputtype = inputtype.toUpperCase();
        if (inputtype != 'HIDDEN') {
          if (inputtype != 'RADIO') 
          document.forms[0].elements[x].focus();

          break;
        }
      } else {
        document.forms[0].elements[x].focus();
        break;
      }
    }
  }
  //alert(s);

  return true;
}
// Object constructor 
function ValidationRecord(ElementName, FriendlyName, Required, Rule) { 
   this.ElementName = ElementName;
   this.FriendlyName = FriendlyName;
   this.Required = Required;
   this.Rule = Rule;
}

function ConditionalValidationRecord(ElementName, FriendlyName, Required, Rule, ConditionalElementName, Operator, MatchValues) {
   this.ElementName = ElementName;
   this.FriendlyName = FriendlyName;
   this.Required = Required;
   this.Rule = Rule;
   this.ConditionalElementName = ConditionalElementName;
   this.MatchValuesString = MatchValues;
   this.MatchValues = MatchValues.split(",");

   for (x = 0; x < this.MatchValues.length; x++) {
    this.MatchValues[x] = this.MatchValues[x].trim();
   }
   this.Operator = Operator; //valid values are "==" and "!="
}

function GetSelectedValue(sel) {
  var s = new String();
  s = sel.options[sel.selectedIndex].value;
  if (s == '') {
    s = sel.options[sel.selectedIndex].text;
  }
  return s;
}

function ToggleVisibility(elm) {
  if (elm.style.display != 'none') {
    elm.style.display = 'none';
  } else {
    elm.style.display = 'inline';
    elements = document.all;
    if (elements != null) {
      tables = elements.tags("TABLE");
    
      /*for (x = 0; x < tables.length; x++) {
     if ((tables[x].className == 'collapseform') && (tables[x] != elm)) {
      tables[x].style.display = 'none';
     }
     }*/
    }
  }
  return true;
}

function ConditionalVisibility(source, operator, testvalue, target) {
  //alert("conditional visibility");
  var sourcevalue = new String();
  bshow = false;
  if (source.options) {
    sourcevalue = GetSelectedValue(source);
  } else {
    sourcevalue = source.value;
  }
  
  if (isNaN(sourcevalue)) { //testvalue
    if (sourcevalue == '')
      return true;
    bshow = eval('\"' + sourcevalue + '\"' + operator + '\"' + testvalue + '\"');
  } else {
    if (sourcevalue == '')
      sourcevalue = 0;
    bshow = eval(sourcevalue + operator + testvalue);
  }
  
  if (bshow == true) {
    //alert(target);
    target.style.display = 'inline';
    //alert("done");
  } else {
    target.style.display = 'none';
  }
  //alert(target.id + ' ' + bshow + ' ' + sourcevalue);

  return true;

}



function ConditionalVisibilityEx(source, operator, testvalue, secondtestvalue, target) {
  var sourcevalue = new String();
  bshow = false;
  secondbshow = false;
  if (source.options) {
    sourcevalue = GetSelectedValue(source);
  } else {
    sourcevalue = source.value;
  }
  
  if (isNaN(testvalue)) {
    if (sourcevalue == '')
      return true;
    bshow = eval('\"' + sourcevalue + '\"' + operator + '\"' + testvalue + '\"');
  } else {
    if (sourcevalue == '')
      sourcevalue = 0;
    bshow = eval(sourcevalue + operator + testvalue);
  }

  if (isNaN(secondtestvalue)) {
    if (sourcevalue == '')
      return true;
    secondbshow = eval('\"' + sourcevalue + '\"' + operator + '\"' + secondtestvalue + '\"');
  } else {
    if (sourcevalue == '')
      sourcevalue = 0;
    secondbshow = eval(sourcevalue + operator + secondtestvalue);
  }
  
  if ((bshow == true) || (secondbshow == true)) {
    target.style.display = 'inline';
  } else {
    target.style.display = 'none';
  }
  //alert(target.id + ' ' + bshow + ' ' + sourcevalue);

  return true;

}

function ZeroPropertiesOwned(value, propertiesowned) {
  //if they rent and it is a refinance transaction, then they must own at least one property.
  //this function is only called if it is a refinance transaction, controlled by server side scripting.
  propertiesownedelement = MM_findObj(propertiesowned);
  foundzero = false;
  if (propertiesownedelement) {
    if (value == 'rent') {
      for (x = 0; x < propertiesownedelement.length; x++) {
        if (propertiesownedelement.options(x).value == '0') {
          propertiesownedelement.options.remove(x);
          propertiesownedelement.selectedIndex = 0;
          break;
        }
      }
    } else if (value == 'own') {
      for (x = 0; x < propertiesownedelement.length; x++) {
        if (propertiesownedelement.options(x).value == '0') {
          foundzero = true;
          break;
        }
      }
      if (!foundzero) {
        var oOption = document.createElement("OPTION");
        propertiesownedelement.options.add(oOption, 0);
        oOption.innerText = "0";
        oOption.value = "0";
      }
    }
  }
}

function DisclosureContacts(selectname) {
  element = MM_findObj(selectname);
  if (element) {
    selectedvalue = new String('');
    selectedvalue = GetSelectedValue(element);
    selectedvaluearray = selectedvalue.split("|");
    disclosureemail = MM_findObj("disclosure_email");
    disclosurephone = MM_findObj("disclosure_phone");
    if (disclosureemail) {
      disclosureemail.innerHTML = selectedvaluearray[3];
      disclosureemail.href = 'MAILTO:' + selectedvaluearray[3];
    }
    if (disclosurephone) {
      disclosurephone.innerHTML = selectedvaluearray[2];
    }
  }
  return true;
}

function formatCurrency(num) {
  num = num.toString().replace(/\$|\,/g,'');
  if(isNaN(num))
    num = "0";
  sign = (num == (num = Math.abs(num)));
  num = Math.floor(num*100+0.50000000001);
  cents = num%100;
  num = Math.floor(num/100).toString();
  if(cents<10)
    cents = "0" + cents;
  for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
    num = num.substring(0,num.length-(4*i+3))+','+
  num.substring(num.length-(4*i+3));
  return (((sign)?'':'-') + '$' + num + '.' + cents);
}

function FormatNumber(num, places) {
  if (isNaN(num)) {
    return num;
  } else {
    num = Math.round(num * Math.pow(10,places)) / Math.pow(10,places);
    var snum = new String(num);
    var dec = new String();
    if (places > 0) {
      if (snum.indexOf('.') == -1) {
        snum = snum + '.';
      }
      dec = snum.substring(snum.indexOf('.')+1, snum.length);
      if (dec.length < places) {
        for (x = dec.length; x < places; x++) {
          dec += '0';
        }
      }
      return snum.substring(0, snum.indexOf('.')) + '.' + dec;
    } else {
      return snum;
    }
  }
}

function MM_findObj(n, d) { //v4.0
  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 && document.getElementById) 
    x=document.getElementById(n); 
  return x;
}

function FillMortgageForm(name, elm) {
  institution = MM_findObj("mortgage_holder_" + name);
  //accountnum = MM_findObj("account_number_" + name);
  balance = MM_findObj("mortgage_balance_" + name);
  payment = MM_findObj("mortgage_payment_" + name);
  if ((institution) && (balance) && (payment)) {
    value = GetSelectedValue(elm);

    valuearray = value.split("|");
    if (valuearray.length == 4) {
      institution.value = valuearray[0];
      //accountnum.value = valuearray[1];
      balance.value = valuearray[2];
      payment.value = valuearray[3];
    } else {
      institution.value = '';
      //accountnum.value = '';
      balance.value = '';
      payment.value = '';
    }
  }
}

function ConditionalText(source, operator, testvalue, targetname, truetext, falsetext) {
  var sourcevalue = new String();
  var target = MM_findObj(targetname);

  bshow = false;
  if (source.options) {
    sourcevalue = GetSelectedValue(source);
  } else {
    sourcevalue = source.value;
  }
  if (sourcevalue == '')
    return true;
  
  if (isNaN(testvalue)) {
    bshow = eval('\"' + sourcevalue + '\"' + operator + '\"' + testvalue + '\"');
  } else {
    bshow = eval(sourcevalue + operator + testvalue);
  }
  
  if ((bshow == true) && (target)) {
    target.innerText = truetext;
  } else {
    target.innerText = falsetext;
  }
  //alert(source.name + ' ' + sourcevalue + ' ' + targetname);
  return true;
}

function AddSpouse(primaryborrower, selectlist) {
  //primaryborrower should be the borrower number of the borrower adding this
  var OptionValue = new String('');
  //first check if we already have another borrower to use as the spouse.  this relies on existing spouse linking by marital status selection
  for (var x = 0; x < selectlist.options.length; x++) {
    OptionValue = selectlist.options[x].value;
    if (OptionValue.indexOf('borrower_') > -1) {
      selectlist.selectedIndex = x;
      return 1;
    }
  }
  //if we've got here we need to add another borrower, then set their marital status to married to the next borrower.
  SkipValidationSubmit(selectlist.form, 'AddSpouse:' + primaryborrower);
  selectlist.form.submit();
}


function FindMatchingSpouse(source) {
  var sourcevalue = new String();
  var sourcename = new String();
  sourcename = source.name;
  sourceborrower = sourcename.charAt(sourcename.length - 1);
  selectedspouse = eval("source.form.selected_spouse_borrower_" + sourceborrower);

  sourcevalue = GetSelectedValue(source);
  //re-enable a previously selected-as-spouse borrowers drop down
  //and hide the same as spouse checkbox.
  if ((selectedspouse) && (selectedspouse.value != '')) {
    selectedvalue = selectedspouse.value;
    target = MM_findObj(selectedspouse.value);
    if (target) {
      target.disabled = false;
      target.selectedIndex = 0;
      for (x = 0; x < target.options.length; x++) {
        if (target.options[x].className == 'removeme') {
          target.options.remove(x);
        }
      }
    }
    
    targetborrower = selectedvalue.charAt(selectedvalue.length - 1);

    checkbox = MM_findObj("current_same_as_spouse_borrower_" + targetborrower);
    if (checkbox) {
      if (checkbox.checked) {
        checkbox.checked = false;
        ImportResidence(checkbox, 'borrower_' + targetborrower, 'current');
      }
    }
    element = MM_findObj("hidden_current_same_as_spouse_borrower_" + targetborrower);
    if (element) {
      element.value = "";
    }
    checkbox = MM_findObj("previous_same_as_spouse_borrower_" + targetborrower);
    if (checkbox) {
      if (checkbox.checked) {
        checkbox.checked = false;
        ImportResidence(checkbox, 'borrower_' + targetborrower, 'previous');
      }
    }
    element = MM_findObj("hidden_previous_same_as_spouse_borrower_" + targetborrower);
    if (element) {
      element.value = "";
    }
    checkrow = MM_findObj("check_same_as_spouse_borrower_" + targetborrower);
    if (checkrow) {
      checkrow.style.display = "none";
    }
    checkrow = MM_findObj("check_previous_same_as_spouse_borrower_" + targetborrower);
    if (checkrow) {
      checkrow.style.display = "none";
    }
    element = MM_findObj("joint_liquid_accounts_label_borrower_" + targetborrower);
    if (element) {
      element.innerText = "";
    }
    element = MM_findObj("joint_properties_owned_label_borrower_" + targetborrower);
    if (element) {
      element.innerText = "";
    }
    element = MM_findObj("joint_ccd_accounts_label_borrower_" + targetborrower);
    if (element) {
      element.innerText = "";
    }
  }
  //only if the drop down selection is one of the options that includes the word "borrower" in the value
  //then we search for that borrower and manipulate its form.
  if (sourcevalue.indexOf("borrower") > 0) {    
    targetborrower = sourcevalue.charAt(sourcevalue.length - 1);  

    
    //link the spouse to this borrower
    target = MM_findObj("marital_status_borrower_" + targetborrower);
    if (target) {
      foundoption = false;
      for (x = 0; x < target.options.length; x++) {
        if (target.options[x].value == 'married_to_borrower_' + sourceborrower) {
          target.selectedIndex = x;
          target.disabled = true;
          selectedspouse.value = target.name;
          //alert(selectedspouse.value);
          foundoption = true;
          break;
        }
      }
      if (foundoption == false) {
        var oOption = document.createElement("OPTION");
        target.options.add(oOption);
        oOption.innerText = "Married to Borrower #" + sourceborrower;
        oOption.value = "married_to_borrower_" + sourceborrower;
        oOption.className = "removeme";
        target.selectedIndex = oOption.index;
        target.disabled = true;
        selectedspouse.value = target.name;
        //alert(selectedspouse.value);
      }
      checkrow = MM_findObj("check_same_as_spouse_borrower_" + targetborrower);
      if (checkrow) {
        checkrow.style.display = "inline";
      }
      checkrow = MM_findObj("check_previous_same_as_spouse_borrower_" + targetborrower);
      if (checkrow) {
        checkrow.style.display = "inline";
      }
      checkbox = MM_findObj("current_same_as_spouse_borrower_" + targetborrower);
      if (checkbox) {
        checkbox.checked = true;
        ImportResidence(checkbox, "borrower_" + targetborrower, 'current');
      }
      checkbox = MM_findObj("previous_same_as_spouse_borrower_" + targetborrower);
      if (checkbox) {
        checkbox.checked = true;
        ImportResidence(checkbox, "borrower_" + targetborrower, 'previous');
      }
      element = MM_findObj("joint_liquid_accounts_label_borrower_" + targetborrower);
      if (element) {
        element.innerText = "other than joint assets reported by spouse";
      }
      element = MM_findObj("joint_properties_owned_label_borrower_" + targetborrower);
      if (element) {
        element.innerText = "other than joint properties reported by spouse";
      }
      element = MM_findObj("joint_ccd_accounts_label_borrower_" + targetborrower);
      if (element) {
        element.innerText = "other than joint accounts reported by spouse";
      }
      element = MM_findObj("last_name_borrower_" + targetborrower);
      sourceelement = MM_findObj("last_name_borrower_" + sourceborrower);
      if ((element) && (sourceelement)) {
        element.value = sourceelement.value;
      }
    }

    //unmark any other borrowers that were previously marked as married to the spouse.
    x = 0;
    while (x < 10) {
      x++;
      if ((x == sourceborrower) || (x == targetborrower)) {
        continue;
      }
      target = MM_findObj('marital_status_borrower_' + x);
      if (target) {
        targetvalue = GetSelectedValue(target);
        thisborrower = targetvalue.charAt(targetvalue.length - 1);
        if (thisborrower == targetborrower) {
          target.selectedIndex = 0;
          target.disabled = false;
          target = eval("source.form.selected_spouse_borrower_" + x);
          if (target) {
            target.value = '';
          }
          alert('Borrower #' + x + ' was previously selected as married to Borrower #' + 
            targetborrower + '\rPlease select a new marital status for Borrower #' + x);
        }
      } else {
        break;
      }
    }  
  } else if (sourcevalue == "married") {
    //window.open("include_spouse.htm","","width=350,height=100");
    //if (confirm("Do you want to include your spouse to this application?")) {
      if (AddSpouse(sourceborrower, source) == 1) {
        FindMatchingSpouse(source);
      }

    //}
  }
}

function CharacterCountInRange(text, asciilow, asciihigh) {
  var count = 0;
  var code = 0;
  var s = new String(text);
  for (var x = 0; x < s.length; x++) {
    code = s.charCodeAt(x);
    if ((code >= asciilow) && (code <= asciihigh)) {
      count++;
    }
  }
  return count;
}

function ImportCurrentResidence(elm, borrower) {
  hiddenfield = MM_findObj("hidden_current_same_as_spouse_" + borrower);
  if (elm.checked) {
    if (hiddenfield) {
      hiddenfield.value = 'yes';
    }
    //figure out who their spouse is.
    spouselist = MM_findObj("marital_status_" + borrower);
    if (spouselist) {
      selectedspouse = GetSelectedValue(spouselist);
      selectedspouse = selectedspouse.charAt(selectedspouse.length - 1);
      spouserecord = MM_findObj("current_street_borrower_" + selectedspouse);
      thisrecord = MM_findObj("current_street_" + borrower);
      if ((spouserecord) && (thisrecord)) {
        thisrecord.value = spouserecord.value;
        thisrecord.disabled = true;
      }
      spouserecord = MM_findObj("current_city_borrower_" + selectedspouse);
      thisrecord = MM_findObj("current_city_" + borrower);
      if ((spouserecord) && (thisrecord)) {
        thisrecord.value = spouserecord.value;
        thisrecord.disabled = true;
      }
      spouserecord = MM_findObj("current_state_borrower_" + selectedspouse);
      thisrecord = MM_findObj("current_state_" + borrower);
      if ((spouserecord) && (thisrecord)) {
        thisrecord.value = spouserecord.value;
        thisrecord.disabled = true;
      }
      spouserecord = MM_findObj("current_zip_borrower_" + selectedspouse);
      thisrecord = MM_findObj("current_zip_" + borrower);
      if ((spouserecord) && (thisrecord)) {
        thisrecord.value = spouserecord.value;
        thisrecord.disabled = true;
      }
      spouserecord = MM_findObj("current_residence_length_borrower_" + selectedspouse);
      thisrecord = MM_findObj("current_residence_length_" + borrower);
      if ((spouserecord) && (thisrecord)) {
        thisrecord.value = spouserecord.value;
        thisrecord.disabled = true;
        ConditionalVisibility(thisrecord, '<', 2, eval('previous_address_' + borrower));
      }
      spouserecord = MM_findObj("own_rent_borrower_" + selectedspouse);
      thisrecord = MM_findObj("own_rent_" + borrower);
      if ((spouserecord) && (thisrecord)) {
        thisrecord.selectedIndex = spouserecord.selectedIndex;
        thisrecord.disabled = true;
        ConditionalText(thisrecord, '==', 'rent', 'properties_owned_label_' + borrower, 'Number of properties owned by this borrower', 'Number of properties owned by this borrower other than their current residence');
      }
    }
  } else {
     if (hiddenfield) {
      hiddenfield.value = 'no';
    }
    thisrecord = MM_findObj("current_street_" + borrower);
    if (thisrecord) {
      thisrecord.value = '';
      thisrecord.disabled = false;
    }
    thisrecord = MM_findObj("current_city_" + borrower);
    if (thisrecord) {
      thisrecord.value = '';
      thisrecord.disabled = false;
    }
    thisrecord = MM_findObj("current_state_" + borrower);
    if (thisrecord) {
      thisrecord.value = '';
      thisrecord.disabled = false;
    }
    thisrecord = MM_findObj("current_zip_" + borrower);
    if (thisrecord) {
      thisrecord.value = '';
      thisrecord.disabled = false;
    }
    thisrecord = MM_findObj("current_residence_length_" + borrower);
    if (thisrecord) {
      thisrecord.value = '';
      thisrecord.disabled = false;
      ConditionalVisibility(thisrecord, '<', 2, eval('previous_address_' + borrower));
    }
    thisrecord = MM_findObj("own_rent_" + borrower);
    if (thisrecord) {
      thisrecord.selectedIndex = 0;
      thisrecord.disabled = false;
      ConditionalText(thisrecord, '==', 'rent', 'properties_owned_label_' + borrower, 'Number of properties owned by this borrower', 'Number of properties owned by this borrower other than their current residence');
    }
  }
  return true;
}

function ImportResidence(elm, borrower, whichresidence) {
  hiddenfield = MM_findObj("hidden_" + whichresidence + "_same_as_spouse_" + borrower);
  if (elm.checked) {
    if (hiddenfield) {
      hiddenfield.value = 'yes';
    }
  //figure out who their spouse is.
  spouselist = MM_findObj("marital_status_" + borrower);
  if (spouselist) {
    selectedspouse = GetSelectedValue(spouselist);
    selectedspouse = selectedspouse.charAt(selectedspouse.length - 1);
    spouserecord = MM_findObj(whichresidence + "_street_borrower_" + selectedspouse);
    thisrecord = MM_findObj(whichresidence + "_street_" + borrower);
    if ((spouserecord) && (thisrecord)) {
      thisrecord.value = spouserecord.value;
      thisrecord.disabled = true;
    }
    spouserecord = MM_findObj(whichresidence + "_city_borrower_" + selectedspouse);
    thisrecord = MM_findObj(whichresidence + "_city_" + borrower);
    if ((spouserecord) && (thisrecord)) {
      thisrecord.value = spouserecord.value;
      thisrecord.disabled = true;
    }
    spouserecord = MM_findObj(whichresidence + "_state_borrower_" + selectedspouse);
    thisrecord = MM_findObj(whichresidence + "_state_" + borrower);
    if ((spouserecord) && (thisrecord)) {
      thisrecord.value = spouserecord.value;
      thisrecord.disabled = true;
    }
    spouserecord = MM_findObj(whichresidence + "_zip_borrower_" + selectedspouse);
    thisrecord = MM_findObj(whichresidence + "_zip_" + borrower);
    if ((spouserecord) && (thisrecord)) {
      thisrecord.value = spouserecord.value;
      thisrecord.disabled = true;
    }
    spouserecord = MM_findObj(whichresidence + "_residence_length_borrower_" + selectedspouse);
    thisrecord = MM_findObj(whichresidence + "_residence_length_" + borrower);
    if ((spouserecord) && (thisrecord)) {
      thisrecord.value = spouserecord.value;
      thisrecord.disabled = true;
      //alert(whichresidence.indexOf("current"));
      if (whichresidence.indexOf("current") >= 0) {
        ConditionalVisibility(thisrecord, '<', 2, eval('previous_address_' + borrower));
      }
    }
    if (whichresidence.indexOf("current") >= 0) {
      spouserecord = MM_findObj("own_rent_borrower_" + selectedspouse);
      thisrecord = MM_findObj("own_rent_" + borrower);
      if ((spouserecord) && (thisrecord)) {
        thisrecord.selectedIndex = spouserecord.selectedIndex;
        thisrecord.disabled = true;
        ConditionalText(thisrecord, '==', 'rent', 'properties_owned_label_' + borrower, 'Number of properties owned by this borrower', 'Number of properties owned by this borrower other than their current residence');
      }
      spouserecord = MM_findObj("home_phone1_borrower_" + selectedspouse);
      thisrecord = MM_findObj("home_phone1_" + borrower);
      if ((spouserecord) && (thisrecord)) {
        thisrecord.value = spouserecord.value;
        thisrecord.disabled = true;
      }
      spouserecord = MM_findObj("home_phone2_borrower_" + selectedspouse);
      thisrecord = MM_findObj("home_phone2_" + borrower);
      if ((spouserecord) && (thisrecord)) {
        thisrecord.value = spouserecord.value;
        thisrecord.disabled = true;
      }
      spouserecord = MM_findObj("home_phone3_borrower_" + selectedspouse);
      thisrecord = MM_findObj("home_phone3_" + borrower);
      if ((spouserecord) && (thisrecord)) {
        thisrecord.value = spouserecord.value;
        thisrecord.disabled = true;
      }

    }
  }
  } else {
     if (hiddenfield) {
      hiddenfield.value = 'no';
    }
    thisrecord = MM_findObj(whichresidence + "_street_" + borrower);
    if (thisrecord) {
      thisrecord.value = '';
      thisrecord.disabled = false;
    }
    thisrecord = MM_findObj(whichresidence + "_city_" + borrower);
    if (thisrecord) {
      thisrecord.value = '';
      thisrecord.disabled = false;
    }
    thisrecord = MM_findObj(whichresidence + "_state_" + borrower);
    if (thisrecord) {
      thisrecord.value = '';
      thisrecord.disabled = false;
    }
    thisrecord = MM_findObj(whichresidence + "_zip_" + borrower);
    if (thisrecord) {
      thisrecord.value = '';
      thisrecord.disabled = false;
    }
    thisrecord = MM_findObj(whichresidence + "_residence_length_" + borrower);
    if (thisrecord) {
      thisrecord.value = '';
      thisrecord.disabled = false;
      if (whichresidence.indexOf("current") >= 0) {
        ConditionalVisibility(thisrecord, '<', 2, eval('previous_address_' + borrower));
      }
    }
    if (whichresidence.indexOf("current") >= 0) {
      thisrecord = MM_findObj("own_rent_" + borrower);
      if (thisrecord) {
        thisrecord.selectedIndex = 0;
        thisrecord.disabled = false;
        ConditionalText(thisrecord, '==', 'rent', 'properties_owned_label_' + borrower, 'Number of properties owned by this borrower', 'Number of properties owned by this borrower other than their current residence');
      }
      thisrecord = MM_findObj("home_phone1_" + borrower);
      if (thisrecord) {
        thisrecord.disabled = false;
      }
      thisrecord = MM_findObj("home_phone2_" + borrower);
      if (thisrecord) {
        thisrecord.disabled = false;
      }
      thisrecord = MM_findObj("home_phone3_" + borrower);
      if (thisrecord) {
        thisrecord.disabled = false;
      }
    }
  }
  return true;
}

function SyncAddress(borrower, whichaddress) {
  selectedspouse = MM_findObj("selected_spouse_" + borrower);
  //alert(selectedspouse.value + ' ' + whichaddress);
  if (selectedspouse) {
    spousevalue = selectedspouse.value;
    spousevalue = spousevalue.charAt(spousevalue.length - 1);
    spousecheck = MM_findObj(whichaddress + "_same_as_spouse_borrower_" + spousevalue);
    if (spousecheck) {
      if (spousecheck.checked) {
        ImportResidence(spousecheck, 'borrower_' + spousevalue, whichaddress);
      }
    }
  }
  return true;
}


/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;
var digits = "0123456789";
// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()-. ";
var zipCodeDelimiters = "- ";
// characters which are allowed in international phone numbers
// (a leading + is OK)
var validWorldPhoneChars = phoneNumberDelimiters + "+";
// Minimum no of digits in an international phone no.
var minDigitsInIPhoneNumber = 10;

function isInteger(s){
  var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
  var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
  // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
  for (var i = 1; i <= n; i++) {
    this[i] = 31
    if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
    if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
  var daysInMonth = DaysArray(12)
  var pos1=dtStr.indexOf(dtCh)
  var pos2=dtStr.indexOf(dtCh,pos1+1)
  var strMonth=dtStr.substring(0,pos1)
  var strDay=dtStr.substring(pos1+1,pos2)
  var strYear=dtStr.substring(pos2+1)
  strYr=strYear
  if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
  if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
  for (var i = 1; i <= 3; i++) {
    if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
  }
  month=parseInt(strMonth)
  day=parseInt(strDay)
  year=parseInt(strYr)
  if (pos1==-1 || pos2==-1){
    //alert("The date format should be : mm/dd/yyyy")
    return 1;//false
  }
  if (month<1 || month>12){
    //alert("Please enter a valid month")
    return 2;//false
  }
  if (day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
    //alert("Please enter a valid day")
    return 3;//false
  }
  if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
    //alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
    return 4;//false
  }
  if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
    //alert("Please enter a valid date")
    return 5;//false
  }
return 0;
}

function checkInternationalPhone(strPhone){
  s=stripCharsInBag(strPhone,validWorldPhoneChars);
  return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
}

function isZipCode(strZip) {
  s = stripCharsInBag(strZip, zipCodeDelimiters);
  return (isInteger(s) && ((s.length == 5) || (s.length == 9)));
}

function FormatPhone(elm) {
  s = stripCharsInBag(elm.value, '()-. ');
  
  if (s.length == 10) {
    s = s.substr(0,3) + '-' + s.substr(3,3) + '-' + s.substr(6,4);
    elm.value = s;
    elm.style.backgroundColor = '#FFFFFF';
  } else if (s.length > 0) {
    elm.style.backgroundColor = '#FFFFCC';
  } else if (s.length == 0) {
    elm.style.backgroundColor = '#FFFFFF';
  }
  return true;
   //else if ((s.length > 10) && (s.substr(10,1) == 'x')) {
    //s = s.substr(0,3) + '-' + s.substr(3,3) + '-' + s.substr(6,4) + ' ' + s.substr(10, s.length);
   // elm.value = s;
  //}
}



function MoveToField(elm, length, target) {
  s = new String(elm.value);
  if (s.length == length) {
    if ((target) && (!target.disabled))
      target.focus();
  }
  return true;

}

function SkipValidationSubmit(frm, action) {
  element = MM_findObj("Action");
  //alert(element);
  var actionstr = new String(action);
  if (element) {
    element.value = action;
    if (actionstr.indexOf("Remove:") == 0) {
      if (!confirm("Delete this item?")) {
        element.value = 'cancelaction';
      }
    }
    //frm.submit();  not needed for input type image.
  }
}

function ValidateForm() {
  //leave this at the top or we'll loose disabled field's values.
  elements = document.forms[0].all;
  for (x = 0; x < elements.length; x++) {
      if (elements[x].disabled) {
      elements[x].disabled = false;
    }
  }
  
  element = MM_findObj("Action");
  if (element) {
    //alert(element.value);
    if ((element.value) && (element.value != '')) {
      if (element.value == 'cancelaction') {
        return false;
      } else {
        return true;
      }
    }
  }

  var elements = new Array();
  var msg = new String();
  for (x = 0; x < ValidationObjects.length; x++) 
  {
    ValidationObject = ValidationObjects[x];
    element = MM_findObj(ValidationObject.ElementName);
    if (element) 
    {
      //if (!element.length) {
      if ((element.length != null) && (!element.options))
      {
      //skip radio groups.
      }
      else
      {
        element.style.backgroundColor = '';
      }
      /* handle ConditionalValidationRecords.
        if Operator == "==" then  
          skip to next validation object if ConditionalElementName's value does not match any of the values in the MatchValues array  
       else if Operator == "!=" then
        skip to next validation object if ConditionalElementName's value matches any of the values in the MatchValues array
      end

      */
      if (ValidationObject.ConditionalElementName) 
      {
        //preserve original, replace local variable with a copy of the original.
        
        conditionalelement = MM_findObj(ValidationObject.ConditionalElementName);
        conditionalvalue = new String("");
        if (conditionalelement) 
        {
          if (conditionalelement.options) { //SELECT element
            conditionalvalue = GetSelectedValue(conditionalelement);
          } else if (conditionalelement.length) { //RADIO group
            for (y = 0; y < conditionalelement.length; y++) {
              if (conditionalelement[y].checked) {
                conditionalvalue = conditionalelement[y].value;
                break;
              }
            }      
          } else if (conditionalelement.value) {
            //Radio group with only one element, or textboxes.
            
            if (conditionalelement.tagName == 'INPUT') {
              inputtype = new String(conditionalelement.type);
              inputtype = inputtype.toUpperCase();
              
              if (inputtype == 'RADIO') {
                if (conditionalelement.checked) {
                  conditionalvalue = conditionalelement.value;
                } else {
                  conditionalvalue = '';
                }
              } else {
                conditionalvalue = conditionalelement.value;
              }
            } else {
              conditionalvalue = conditionalelement.value;
            }
          }
        }
        //alert("conditionalvalue: " + conditionalvalue);
        FoundMatch = false;
        for (y = 0; y < ValidationObject.MatchValues.length; y++) {
          //alert(conditionalvalue + ' . ' + ValidationObject.MatchValues[y]);
          if (conditionalvalue == ValidationObject.MatchValues[y]) {
            FoundMatch = true;
            break;  
          }
        }
        
        if (((!FoundMatch) && (ValidationObject.Operator == "==")) ||
           ((FoundMatch) && (ValidationObject.Operator == "!=")))  {
          //ValidationObject.Required = false;
          //ValidationObject.Rule = "";
          continue;
        }
        //} else {
        //  continue; //skip this ValidationObject if we can't find the ConditionalElement.
        //}

      }
       
      if (ValidationObject.Required) 
      {
        if ((element.value != null) && (element.value == '') && (!element.options))
        {
          //textbox, password, or textarea.
          msg += 'Please enter a value for "' + ValidationObject.FriendlyName + '".\n';
          element.style.backgroundColor = '#FFFFCC';
          elements[elements.length] = element;  
        }
      //just don't validate single checkboxes and don't use single radio buttons.
          /*else if ((!element.value) && (element.checked != null) && (!element.checked))
          {
          //single radio button or check box
            msg += 'Please check an item for "' + ValidationObject.FriendlyName + '".\n';
        element.style.backgroundColor = '#FFFFCC';  
          }*/
        else if ((element.options != null)) //&& (element.selectedIndex < 0))
        {
          //select list, a.k.a. combo box
          s = new String(element.options[element.selectedIndex].value.toLowerCase());
          if (s == "") 
          {
          s = element.options[element.selectedIndex].text;
          s = s.toLowerCase();
          }
          p = s.indexOf('please select');
          if ((p > -1) || (element.selectedIndex < 0))
          {
                msg += 'Please select an item for "' + ValidationObject.FriendlyName + '".\n';
            element.style.backgroundColor = '#FFFFCC';
            elements[elements.length] = element; 
          }
        }
        else if ((element.length != null) && (!element.options))
        {
          //radio boxes or check boxes
          FoundChecked = false;
          for (y = 0; y < element.length; y++) 
          {
            if (element[y].checked) 
            {
              FoundChecked = true;
              break;
            }
          }
          if (!FoundChecked)
            msg += 'Please select an option for "' + ValidationObject.FriendlyName + '".\n';
        } 
      } //done ValidationObject.Required
      if (ValidationObject.Rule != '')
      {
        if ((element) && (element.length) && (element.length > 0)) {
        //do nothing.
        } else if ((!element.value) || (element.value.length == 0) || (element.value == ''))
          continue;
        if (ValidationObject.Rule.indexOf('isEmail') != -1) 
        {
          a=element.value.indexOf('@');
          p=element.value.indexOf('.');
          if (a<1 || a==(element.value.length-1) || p<1)
          { 
            msg += ' - "' + ValidationObject.FriendlyName + '" must contain an e-mail address.\n';
            element.style.backgroundColor = '#FFFFCC';
            elements[elements.length] = element; 
          }
        }
        //dont use else if, may be multiple
        if (ValidationObject.Rule.indexOf('isConfirmMatch') != -1)
        {
          //alert(element.name);
          matchelement = MM_findObj(element.name + '_confirm');
          //alert(element.name.length);
          //alert('_confirm'.length);
          
          //var s = element.name.substring(0, element.name.length - '_confirm'.length);
          //alert(s);
          //matchelement = MM_findObj(s);
          if (matchelement) 
          {
            if (matchelement.value != element.value)
            {
              msg += ' - "' + ValidationObject.FriendlyName + '" must match the confirmation box.\n';
              element.style.backgroundColor = '#FFFFCC';
              matchelement.style.backgroundColor = '#FFFFCC';
              elements[elements.length] = element; 
            }
          }
        }
        //may be multiple with isConfirmMatch.
        if (ValidationObject.Rule.indexOf('isPassword') != -1)
        {        
          if (element.value.length < PasswordMinimumLength) {
            msg += ' - "' + ValidationObject.FriendlyName + '" must be at least ' + PasswordMinimumLength + ' characters long.\n';
            element.style.backgroundColor = '#FFFFCC';
            elements[elements.length] = element; 
          }
          if ((PasswordNoSpaces) && (CharacterCountInRange(element.value, 32, 32) > 0)) {
            msg += ' - "' + ValidationObject.FriendlyName + '" cannot contain spaces.\n';
            element.style.backgroundColor = '#FFFFCC';
            elements[elements.length] = element;
          }
          if (CharacterCountInRange(element.value, 48, 57) < PasswordMinimumNumbers) {
            msg += ' - "' + ValidationObject.FriendlyName + '" must contain at least ' + PasswordMinimumNumbers + ' numeric character(s).\n';
            element.style.backgroundColor = '#FFFFCC';
            elements[elements.length] = element;
          }
          if (CharacterCountInRange(element.value, 65, 90) < PasswordMinimumUpperCase) {
            msg += ' - "' + ValidationObject.FriendlyName + '" must contain at least ' + PasswordMinimumUpperCase + ' upper case character(s).\n';
            element.style.backgroundColor = '#FFFFCC';
            elements[elements.length] = element;
          }
          if (CharacterCountInRange(element.value, 97, 122) < PasswordMinimumLowerCase) {
            msg += ' - "' + ValidationObject.FriendlyName + '" must contain at least ' + PasswordMinimumLowerCase + ' lower case character(s).\n';
            element.style.backgroundColor = '#FFFFCC';
            elements[elements.length] = element;
          }
        }
		else if (ValidationObject.Rule.indexOf('isValidCreditReportAuth') != -1)
        {
		  if (element.value == 1) {  //if user selected 'yes' for credit report, make sure they've agreed to authorization
          	creditauth = MM_findObj(element.name + '_authorized');
				if (creditauth.value != 'yes') {
			  	msg += ' - "' + ValidationObject.FriendlyName + '" must agree to give authorization to run credit report.\n';
          element.style.backgroundColor = '#FFFFCC';
          element.selectedIndex = 2;
          element.fireEvent("onchange");
          elements[elements.length] = element;
				}
		  }
        }
        else if (ValidationObject.Rule.indexOf('isPhone') != -1)
        {
          if (checkInternationalPhone(element.value) == false) 
          {
            msg += ' - "' + ValidationObject.FriendlyName + '" must contain a valid 10 digit phone number.\n';
            element.style.backgroundColor = '#FFFFCC';
            elements[elements.length] = element; 
          }

        }
        else if (ValidationObject.Rule.indexOf('isZip') != -1)
        {
          if (isZipCode(element.value) == false) 
          {
            msg += ' - "' + ValidationObject.FriendlyName + '" must contain a valid 5 or 9 digit zip code.\n';
            element.style.backgroundColor = '#FFFFCC';
            elements[elements.length] = element; 
          }

        }
        else if (ValidationObject.Rule.indexOf('isNumber') != -1)
        {
          if (element.value) {
            element.value = stripCharsInBag(element.value, "$,");
          }
          if (ValidationObject.Rule.length > 8) {
            requiredlength = ValidationObject.Rule.substring(8); //get position 8 and on.
            if (!isNaN(requiredlength)) {
              value = element.value;
              if (value.length != requiredlength) {
                msg += ' - "' + ValidationObject.FriendlyName + '" must contain a number ' + requiredlength + ' characters long.\n';
                element.style.backgroundColor = '#FFFFCC';//'#FFD2D2';
                elements[elements.length] = element; 
              }
            }
          }
          if (isNaN(element.value))
          {
            msg += ' - "' + ValidationObject.FriendlyName + '" must contain a number.\n';
            element.style.backgroundColor = '#FFFFCC';//'#FFD2D2';
            elements[elements.length] = element; 
          }
        }
        else if (ValidationObject.Rule.indexOf('isYes') != -1)
        {
          //alert('in yes');
          var FoundValue = false;
          if (element.length) {
            for (y = 0; y < element.length; y++) {
              if (element[y].checked) {
                //alert(element[x].value);
                FoundValue = true;
                if ((element[y].value != '1') && (element[y].value != 'yes')) {
                  msg += ' - "' + ValidationObject.FriendlyName + '" must be marked Yes to continue.\n';
                  //element.style.backgroundColor = '#FFFFCC';//'#FFD2D2';
                  //elements[elements.length] = element; 
                }
              }
            }
          }

          if (!FoundValue) {
            msg += ' - "' + ValidationObject.FriendlyName + '" must be marked Yes to continue.\n';
            //element.style.backgroundColor = '#FFFFCC';//'#FFD2D2';
            //elements[elements.length] = element;
          }
          /*alert(element);
          if (element.value) {
            if (element.value != '1') {
              msg += ' - "' + ValidationObject.FriendlyName + '" must be marked Yes to continue.\n';
              element.style.backgroundColor = '#FFFFCC';//'#FFD2D2';
              elements[elements.length] = element; 
            }
          } else {
            msg += ' - "' + ValidationObject.FriendlyName + '" must be marked Yes to continue.\n';
            element.style.backgroundColor = '#FFFFCC';//'#FFD2D2';
            elements[elements.length] = element; 
          } */
        }
        else if (ValidationObject.Rule.indexOf('isDate') != -1)
        {
          r=isDate(element.value); //value is okay because only text boxes can be date fields for this validation.
          if (r > 0) {
            if (r == 1)
              msg += ' - ' + 'The date format for "' + ValidationObject.FriendlyName + '" should be : mm/dd/yyyy\n';
            else if (r == 2)
              msg += ' - ' + 'Please enter a valid month for "' + ValidationObject.FriendlyName + '"\n';
            else if (r == 3)
              msg += ' - ' + 'Please enter a valid day for "' + ValidationObject.FriendlyName + '"\n';
            else if (r == 4)
              msg += ' - ' + 'Please enter a valid 4 digit year between '+minYear+" and "+maxYear + ' for "' + ValidationObject.FriendlyName + '"\n';
            else if (r == 5)
              msg += ' - ' + 'Please enter a valid date for "' + ValidationObject.FriendlyName + '"\n';
            element.style.backgroundColor = '#FFFFCC';
            elements[elements.length] = element; 
          }
        }
      } //done with ValidationObject.Rule != ''
    } //done with if (element)
  } //done with for loop of ValidationObjects
  if (msg != '')
  {
    msg = 'Please address the following issue(s):\n' + msg;
  
    //alert(elements.length);
    if (elements.length > 0) {
      elements[0].focus; //this doesn't work, probably because function returns false.
    }
    alert(msg);
    return false;
  }
  else
    return true;
}

function IncomeExpert(elm) {
  elm.form.source.value = elm.name;
  var win = window.open('incomeexpert.htm', 'incomeexpert', 'width=430,height=225,toolbar=no,menubar=no,location=no');
  win.focus();
}

function EnterToTab(evt) {
  if (ie4) {
    if (window.event.keyCode == 13) {
    window.event.keyCode = 9;
    }  
  }
}

function PopupHelp(url) {
  var win = window.open(url, 'popupHelp', 'width=525,height=400,toolbar=no,menubar=no,location=no,resizable=yes,scrollbars=yes');
  win.focus();
  return false;
}

//Opens up a confirmation popup with 'prompt' as the message.  Redirects to 'url' if
//user clicks OK
function go_to_url_with_prompt(url, prompt) {
	if (confirm(prompt)) {
		self.location = url;
		return true;
	}
		return false;
}

// Opens up a new window with 'content' as the body content. Used to open up a printer friendly page.
function openPrinterFriendlyPage(content, title) {
  sHTML = '<HTML>\n';
	sHTML += '<HEAD>\n';
	sHTML += '<TITLE>' + title + '</TITLE>\n';
	sHTML += '</HEAD>\n';
	sHTML += '<BODY BGCOLOR="white" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">\n';
	sHTML += content;
	sHTML += '</BODY>\n';
	sHTML += '</HTML>\n';
	var popUp = window.open("blank.htm", "", "width=525,height=365,scrollbars=yes,status=yes");
	popUp.document.write(sHTML);
	popUp.document.close();
}