function check_input(f, x, d) {
  if (f[x] && f[x].value == "") {
    alert("Error: Please enter a value for " + d);
    if (f[x].focus) f[x].focus();
    return false;
  }
  return true;
}

function check_email(f, x) {
  if (!f[x]) return true;
  if (check_input(f, x, "Your E-mail Address")) {
    var email = f[x].value;
    var atpos = email.indexOf('@');
    var preat = email.substr(0, atpos);
    var postat = email.substr(atpos+1);
    if (preat.length < 1 || postat.length < 4 || postat.indexOf('.') <= 0 || postat.indexOf('.') + 2 >= postat.length) { 
      alert("Error: Please enter a valid E-mail Address");
    if (f[x].focus) f[x].focus();
      return false;
    }
    return true;
  }
  return false;
}

function check_phone(f, x, d, o) {
  if (o && f[x] && f[x].value == "") return true;
  if (!f[x]) return true;
  if (check_input(f, x, d)) {
    var phone = f[x].value.toLowerCase();
    var digits = "";
    var invalid = 0;
    for (var i = 0; i < phone.length; i++) {
      var c = phone.charAt(i);
      if (c >= '0' && c <= '9') digits += c;
      else if (c != '-' && c != '(' && c != ')' && c != ' ' && c != "\t" && c != 'e' && c != 'x' && c != 't' && c != 'n' && c != 's' && c != 'i' && c != 'o' && c != '#' && c != '.') {
        invalid = 1; break;
      }
    }
    if (invalid == 1 || digits.length < 10) {
      alert("Error: Please enter a valid " + d.replace("Your ", "") + "\n\nExamples:\n"+
            "  (123) 456-7890\n"+
            "  123-456-7890\n"+
            "  123-456-7890 ext. 2223\n"
      );
      if (f[x].focus) f[x].focus();
      return false;
    }
    return true;
  }
  return false;
}
        
function validate() {
  var f = document.forms[0];
  if (!check_input(f, "name", "Your Name")) return false;
  if (!check_input(f, "applicantname", "the Applicant's Name")) return false;
  if (!check_input(f, "dayphone", "Daytime phone")) return false;
  if (!check_email(f, "email")) return false;

  /* only required on Ask the Expert */
  var opt = (location.href.indexOf('AskTheExpert') < 0);
  if (!check_phone(f, "phone", "Your Phone Number", opt)) return false;

  if (!check_phone(f, "fax", "Your Fax Number", true)) return false;
  if (!check_phone(f, "dayphone", "Your Daytime Phone Number", true)) return false;
  if (!check_phone(f, "evephone", "Your Evening Phone Number", true)) return false;
  return true;
}
