var cancelVerify = false;

// This example is from JavaScript: The Definitive Guide, 3rd Edition.
// That book and this example were Written by David Flanagan.
// They are Copyright (c) 1996, 1997, 1998 O'Reilly & Associates.
// This example is provided WITHOUT WARRANTY either expressed or implied.
// You may study, use, modify, and distribute it for any purpose,
// as long as this notice is retained.
// Code has been additionally modified by Jay Willis, PMZ Real Estate
// last modified 2/24/99

// A utility function that returns true if a string contains only
// whitespace characters.
function isblank(s)
{
    for(var i = 0; i < s.length; i++) {
        var c = s.charAt(i);
        if ((c != ' ') && (c != '\n') && (c != '\t')) return false;
    }
    return true;
}

// A utility function that checks a string for valid numeric characters
function checknumber(n) {
  var tempnumber = "";
  var dots = 0;
  var len = n.value.length;
  for (i = 0 ; i < len ; i++) {
    var c = n.value.charAt(i);
    if ((c == "-" && i == 0) ||
      (c <= "9" && c >= "0") ||
      (c == "." && dots == 0)) {
      tempnumber = tempnumber + c;
      if (c == ".") {
        dots++;
      }
    }
  }
  if (tempnumber.length == len) {
    n.value = tempnumber;
    return n.value;
  } else {
    return false;
  }
}

// A utility function that removes spaces, commas and dollar signs
// from a string.

function clearspaces(s) {
  var newstring = "";
  var len = s.value.length;
  for (i = 0 ; i < len ; i++) {
    var c = s.value.charAt(i);
    if ((c != " ") && (c !=  ",") && (c != "$")) {
      newstring = newstring + c;
    }
  }
  s.value = newstring;
  return s.value
}

// A utility function that checks and formats a string for a valid
// zip or zip+4

function formatzip(z) {
  var tempnumber = "";
  var len = z.value.length;
  for (i = 0 ; i < len ; i++) {
    var c = z.value.charAt(i);
    if ( c <= "9" && c >=  "0") {
      tempnumber = tempnumber + c;
    }
  }
  if ( tempnumber.length == 5 || tempnumber.length == 9) {
    zip = tempnumber.substring(0,5);
    plus4 = tempnumber.substring(5,9);
    if (tempnumber.length == 9) {
      z.value = zip + "-" + plus4;
    } else {
      z.value = zip;
    }
    return z.value;
  } else {
        return false;
  }
}

// A utility function that checks and formats a string for a valid
// phone number

function formatphone(p) {
  var tempnumber = "";
  var len = p.value.length;
  for (i = 0 ; i < len ; i++) {
    var c = p.value.charAt(i);
    if ( c <= "9" && c >=  "0") {
      tempnumber = tempnumber + c;
    }
  }
  if ( tempnumber.length == 7) {
    tempnumber = "209" + tempnumber;
  }
  if ( tempnumber.length == 10) {
    areacode = tempnumber.substring(0,3);
    prefix = tempnumber.substring(3,6);
    digits = tempnumber.substring(6,10);
    p.value = "(" + areacode + ") " + prefix + "-" + digits;
    return p.value;
  } else {
    p.value = tempnumber;
    return false;
  }
}

// A utility function that checks a string for a valid phone number
function checkphone(p) {
  var tempnumber = "";
  var len = p.value.length;
  for (i = 0 ; i < len ; i++) {
    var c = p.value.charAt(i);
    if ( c <= "9" && c >=  "0") {
      tempnumber = tempnumber + c;
    }
  }
  if ( tempnumber.length == 10 || tempnumber.length == 7 || tempnumber.length == 0) {
    return true;
  } else {
    return false;
  }
}

// A utility function that checks and formats a string for a valid
// Email address

function checkemail(e) {
  var at = 0;
  var dot = 0;
  var countat = 0;
  e.value = clearspaces(e);
  var len = e.value.length;
  for (var i = 0; i < len; i++ ) {
    var c = e.value.charAt(i);
        if (c == '@') at = i, countat ++;
        if (c == '.') dot = i;
  }
  if ((at == 0) || (dot == 0) || (at > dot) || (dot - at < 2) || ( len - dot < 3) || (countat > 1)){
    return (false);
  } else {
    return e.value;
  }
}

// This is the function that performs form verification. It will be invoked
// from the onSubmit() event handler. The handler should return whatever
// value this function returns.
function verify(f)
{
  var msg;
  var empty_fields = "";
  var errors = "";
  var fieldName = "";
  var radioArr = "";

  if (cancelVerify)
    return true;

  // Loop through the elements of the form, looking for all
  // text and textarea elements that don't have an "optional" property
  // defined. Then, check for fields that are empty and make a list of them.
  // Also, if any of these elements have a "min" or a "max" property defined,
  // then verify that they are mef_mlnList and that they are in the right range.
  // Put together error messages for fields that are wrong.
  for(var i = 0; i < f.elements.length; i++) {
    var e = f.elements[i];

    if ((e.label != '') && (e.label != null)){
      fieldName = e.label;
    } else {
      fieldName = e.name;
    }

    if (e.mandatory && (
      e.type == "text" ||
      e.type == "textarea" ||
      e.type == "password" ||
      e.type == "select-one" ||
      e.type == "select-multiple"
      )) {
      // first check if the field is empty
      if ((e.value == null) || (e.value == "") || isblank(e.value)) {
        empty_fields += "\n          " + fieldName;
        continue;
      }
    }

    if (e.type == "checkbox" && e.mandatory ) {
      if (!e.checked) {
        empty_fields += "\n          " + fieldName;
        continue;
      }
    }

    // Check for absolute field length requirement
    if (e.value && (e.reqlength != null) && (e.value.length != e.reqlength)) {
      errors += "- The field " + fieldName + " must contain " + e.reqlength + " characters\n";
    }

    // Check for minimum field length requirement
    if (e.value && (e.minlength != null) && (e.value.length < e.minlength)) {
      errors += "- The field " + fieldName + " must be a minimum of " + e.minlength + " characters\n";
    }

    // Check for maximum field length requirement
    if (e.value && (e.maxlength != null) && (e.value.length > e.maxlength)) {
      errors += "- The field " + fieldName + " cannot exceed a maximum of " + e.maxlength + " characters\n";
    }

    // Now check for fields that are supposed to be numeric.
    if ((e.numeric || (e.min != null && e.min != '') || (e.max != null && e.max != '')) && e.value) {
      if (!checknumber(e)) {
        errors += "- The field " + fieldName + " must contain only numeric characters\n";
      } else {
//    }

//    if ((e.numeric || (e.min != null) || (e.max != null)) && e.value) {
        var v = parseFloat(e.value);
        if (isNaN(v) || (e.min != null && e.min != '' && v < e.min) || (e.max != null && e.max != '' && v > e.max)) {
          errors += "- The field " + fieldName + " must be a number";
          if (e.min != null && e.min != '')
            errors += " that is at least " + e.min;

          if (e.min != null && e.min != '' && e.max != null && e.max != '')
            errors += " and no greater than " + e.max;
          else if (e.max != null && e.max != '')
            errors += " that is no greater than " + e.max;
          errors += ".\n";
        }
      }
    }

    // Check for valid zip codes.
    if ((e.zip || e.zip5) && e.value) {
      if (!formatzip(e)) {
        if (e.zip)
          errors += "- The field " + fieldName + " must be a valid ZIP code. i.e. 95350 or 95350-1234\n";
        else
          errors += "- The field " + fieldName + " must be a valid ZIP code. i.e. 95350\n";
      } else {
        e.value = formatzip(e);
      }
    }

    // Check for valid phone number.
    if (e.phone && e.value) {
      if (!checkphone(e)) {
        errors += "- The field " + fieldName + " must be a valid phone number. i.e. (209) 555-1212\n";
      } else {
        e.value = formatphone(e);
      }
    }

    // Check for valid email addresses.
    if (e.email && e.value) {
      if (!checkemail(e)) {
        errors += "- The field " + fieldName + " must be a valid Email address. i.e. househunter@pmz.com\n";
      } else {
        e.value = checkemail(e);
      }
    }
  }

  // Now, if there were any errors, display the messages, and
  // return false to prevent the form from being submitted.
  // Otherwise return true.
  if (!empty_fields && !errors) return true;

  msg  = "______________________________________________________\n\n"
  msg += "The form was not submitted because of the following reason(s).\n";
  msg += "Please correct these issue(s) and re-submit.\n";
  msg += "______________________________________________________\n\n"

  if (empty_fields) {
    msg += "- The following required field(s) are empty:"
    + empty_fields + "\n";
    if (errors) msg += "\n";
  }
  msg += errors;
  alert(msg);
  return false;
}

// Return Year +/- tolerance
function currYear(amt){
  var dt = new Date();
  var fullYear = dt.getFullYear();
  if (amt != null)
    fullYear += amt;
  var year = new String(fullYear);
  return year;
}

// Date validation routine
//-----------------------------------------------------------------------------

// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1950;
var maxYear=2100;

function inputDateCk(dt,min,max){
  dtval = clearspaces(dt)
  if (min != null)
    minYear=min;
  if (max != null)
    maxYear=max;
  if (dtval != ""){
    if (isDate(dtval)==false){
      dt.focus()
// ***  Highlight entry following format error
//    dt.select()
      return false
    }
  }
  return true
}

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 false
  }
  if (strMonth.length<1 || month<1 || month>12){
    alert("Please enter a valid month")
    return false
  }
  if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
    alert("Please enter a valid day")
    return false
  }
  if (strYear.length == 2){
    if (year<50)
      strYear="20"+strYear
    else
      strYear="19"+strYear
  year=parseInt(strYear)
  }
  if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
    if (minYear != maxYear)
    alert("Please enter a valid 4 digit year from \'"+minYear+"\' through \'"+maxYear+"\'")
    else
      alert("Please enter the year as \'"+minYear+ "\' ONLY!")
    return false
  }
  if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
    alert("Please enter a valid date")
    return false
  }
return true
}
