function confirm_message(message, postUrl) {
  if (confirm(message)) {
    window.location=postUrl;
  }
}

function getNumber(input) {
  var number = 0;
  cleanText(input, ",$ ");
  var v = parseFloat(input.value);
  if (!isNaN(v)) {
    number = v;
  }
  return number;
}

function isValidFormat(inStr,format) {

  var str;

  str = inStr;
  str.toUpperCase();

  if (str.length != format.length) {
    return false;
  }

  for (i = 0; i < format.length; i++) {
     if (format.charAt(i) == '9') {
       if (str.charAt(i) < '0' || str.charAt(i) > '9') {
         return false;
       }
     } else if (format.charAt(i) == 'A') {
       if (!((str.charAt(i) >= '0' && str.charAt(i) <= '9') || (str.charAt(i) >= 'A' && str.charAt(i) <= 'Z'))) {
         return false;
       }
     } else if (format.charAt(i) == 'L') {
       if (!(str.charAt(i) >= 'A' && str.charAt(i) <= 'Z')) {
         return false;
       }
     } else if (format.charAt(i) != str.charAt(i)) {
       return false;
     } 
  }

  return true;

}

function isValidEmail(str) {
  // are regular expressions supported?
  var supported = 0;
  if (window.RegExp) {
    var tempStr = "a";
    var tempReg = new RegExp(tempStr);
    if (tempReg.test(tempStr)) supported = 1;
  }

  if (!supported) 
    return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);

  var r1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)");
  var r2 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$");
  return (!r1.test(str) && r2.test(str));
}


function confirm_delete(postUrl) {
  message = "Are you sure you want to delete this record?";
  confirm_message(message, postUrl);
}

function cleanText(input,filteredValues) {
  s = input.value;
  var i;
  var returnString = "";
  for (i = 0; i < s.length; i++) {  // Search through string and append to unfiltered values to returnString.
    var c = s.charAt(i);
    if (filteredValues.indexOf(c) == -1) returnString += c;
  }
  input.value = returnString;
}

function isblank(s) {
    if (s) {
    } else {
      return true;
    }
    for(var i = 0; i < s.length; i++) {
        var c = s.charAt(i);
        if ((c != ' ') && (c != '\n') && (c != '\t')) return false;
    }
    return true;
}

function formatZip(zip) {

  if (zip.length == 5) {
     return zip;
  }

  var returnZip = "";
  
  returnZip = zip.substr(0,5);
  returnZip += "-";
  returnZip += zip.substr(5);
  return returnZip;

}

function isValidZip(input) {
  cleanText(input, "-()/ ");
  var z = input.value;
  var r1 = new RegExp("^[0-9]*$");
  if (!r1.test(z)) {
    return false;
  }
  if ((z.length != 5) && (z.length != 9)) {
     return false;
  }

  return true;
}

function formatSsn(ssn) {
  var returnSsn = "";

  returnSsn = ssn.substr(0,3);
  returnSsn += "-";
  returnSsn += ssn.substr(3,2);
  returnSsn += "-";
  returnSsn += ssn.substr(5,4);

  return returnSsn;
}

function isValidSsn(input) {
  cleanText(input, "- ");
  
  var v = input.value;
  var r1 = new RegExp("^[0-9]*$");
  if (!r1.test(v)) {
    return false;
  }
  if (v.length != 9) {
    return false;
  }
  return true;
}


function formatPhone(phoneNumber) {
  var returnPhone = "(";
  var idx = 0;
  
  returnPhone += phoneNumber.substr(0,3);
  returnPhone += ") ";
  returnPhone += phoneNumber.substr(3,3);
  returnPhone += "-";
  returnPhone += phoneNumber.substr(6,4);
  return returnPhone;
  
}


function isValidPhone(input) {
  cleanText(input, "()-/ ");
  
  var v = input.value;
  var r1 = new RegExp("^[0-9]*$");
  if (!r1.test(v)) {
    return false;
  }
  if (v.length != 10) {
    return false;
  }
  return true;
}

function check_date(objName) {
  var strDatestyle = "US"; //United States date style
  //var strDatestyle = "EU";  //European date style
  var strDate;
  var strDateArray;
  var strDay;
  var strMonth;
  var strYear;
  var intday;
  var intMonth;
  var intYear;
  var booFound = false;
  var datefield = objName;
  var strSeparatorArray = new Array("-"," ","/",".");
  var intElementNr;
  var err = 0;
  var strMonthArray = new Array(12);
  strMonthArray[0] = "Jan";
  strMonthArray[1] = "Feb";
  strMonthArray[2] = "Mar";
  strMonthArray[3] = "Apr";
  strMonthArray[4] = "May";
  strMonthArray[5] = "Jun";
  strMonthArray[6] = "Jul";
  strMonthArray[7] = "Aug";
  strMonthArray[8] = "Sep";
  strMonthArray[9] = "Oct";
  strMonthArray[10] = "Nov";
  strMonthArray[11] = "Dec";
  strDate = datefield.value;
  if (strDate.length < 1) {
    return true;
  }
  for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {
    if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) {
      strDateArray = strDate.split(strSeparatorArray[intElementNr]);
      if (strDateArray.length != 3) {
        err = 1;
        return false;
      } else {
        strDay = strDateArray[0];
        strMonth = strDateArray[1];
        strYear = strDateArray[2];
      }
      booFound = true;
    }
  }
  if (booFound == false) {
    if (strDate.length == 5) {
      strDate = '0' + strDate;
    }
    if (strDate.length>5) {
      strDay = strDate.substr(0, 2);
      strMonth = strDate.substr(2, 2);
      strYear = strDate.substr(4);
    } else {
      err = 9;
      return false;
    }
  }
  if (strYear.length == 2) {
    var intTwoYear = parseInt(strYear);
    if (intTwoYear < 20) {
      strYear = '20' + strYear;
    } else {
      strYear = '19' + strYear;
    }
  }
  // US style
  if (strDatestyle == "US") {
    strTemp = strDay;
    strDay = strMonth;
    strMonth = strTemp;
  }
  intday = parseInt(strDay, 10);
  if (isNaN(intday)) {
    err = 2;
    return false;
  }
  intMonth = parseInt(strMonth, 10);
  if (isNaN(intMonth)) {
    for (i = 0;i<12;i++) {
      if (strMonth.toUpperCase() == strMonthArray[i].toUpperCase()) {
        intMonth = i+1;
        strMonth = strMonthArray[i];
        i = 12;
       }
    }
    if (isNaN(intMonth)) {
      err = 3;
      return false;
     }
  }
  intYear = parseInt(strYear, 10);
  if (isNaN(intYear)) {
    err = 4;
    return false;
  }
  if (intMonth>12 || intMonth<1) {
    err = 5;
    return false;
  }
  if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1)) {
    err = 6;
    return false;
  }
  if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1)) {
    err = 7;
    return false;
  }
  if (intMonth == 2) {
    if (intday < 1) {
      err = 8;
      return false;
    }
    if (LeapYear(intYear) == true) {
      if (intday > 29) {
        err = 9;
        return false;
      }
    }
    else {
      if (intday > 28) {
        err = 10;
        return false;
      }
    }
  }
  if (strDatestyle == "US") {
    datefield.value = intMonth + "/" + intday+"/" + strYear;
  }
  else {
    datefield.value = intday + " " + strMonthArray[intMonth-1] + " " + strYear;
  }
  return true;
}
function LeapYear(intYear) {
    if (intYear % 100 == 0) {
      if (intYear % 400 == 0) { return true; }
    }
    else {
      if ((intYear % 4) == 0) { return true; }
    }
    return false;
}

function doDateCheck(from, to) {
  var errors = ""
  if (Date.parse(from.value) > Date.parse(to.value)) {
    if (from.value == "" || to.value == "") 
      errors = "Both dates must be entered.";
    else 
      errors = "To date must occur after the from date.";
  }
  return errors;
}


function checkMinMax(e, v) {
   var errors = "";
   if (((e.min != null) && (v < e.min)) || 
      ((e.max != null) && (v > e.max))) {
      errors += e.label + " must be a number";
      if (e.min != null) 
        errors += " that is greater than or equal to " + e.min;

      if (e.max != null && e.min != null) 
        errors += " and less than or equal to " + e.max;
      else if (e.max != null)
        errors += " that is less than or equal to " + e.max;

      errors += ".\n";
   }

   return errors;
}

function makeFieldNormal(e) {
  if (e.optional) {
    e.style.backgroundColor="";
  } else {
    e.style.backgroundColor="#FFFF66";
  }
}

function makeFieldInError(e) {
  e.style.backgroundColor="#FF3333";
}

// This is the function that performs form verification. It is invoked
// from the onsubmit event handler. The handler should return whatever
// value this function returns.
function validate(f) {
    var msg;
    var empty_fields = "";
    var errors = "";

    // 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,
    // verify that they are numbers and in the right range.
    // If the element has a "numeric" property defined, verify that
    // it is a number, but don't check its range.
    // Put together error messages for fields that are wrong.
    for(var i = 0; i < f.length; i++) {
        var e = f.elements[i];
        var errorMsg = null;
        if ((e.type == "text") || (e.type == "textarea") || e.type=="select-one" || e.type == "password" ) {

            if (e.type == "select-one" && e.selectedIndex == 0) {
               if (!e.optional && e.validate) {
                  makeFieldNormal(e);
                  if (e.label == null) {
                     e.label = e.name;
                  }
                  empty_fields += "\n          " + e.label;
                  makeFieldInError(e);
               }
               continue;
            }

            makeFieldNormal(e);
            cleanText(e, '"'); // don't allow double quote character

            // first check if the field is empty
            if ((e.value == null) || (e.value == "") || isblank(e.value)) {
               if (!e.optional) {
                  if (e.label == null) {
                     e.label = e.name;
                  }
                  empty_fields += "\n          " + e.label;
                  makeFieldInError(e);
               }
               continue;
            }

            if (e.text) {
            }
 
            if (e.email && !isValidEmail(e.value)) {
               errors += e.label + " is an invalid email address. \n";
               makeFieldInError(e);
            }

            if (e.phone) {
              if (isValidPhone(e)) {
                 e.value = formatPhone(e.value);
              } else {
                errors += e.label + " is an invalid phone number.  Phone numbers must be 10 digits.\n";
                makeFieldInError(e);
              }
            }

            if (e.zip) {
              if (isValidZip(e)) {
                 e.value = formatZip(e.value);
              } else {
                errors += e.label + " is an invalid zip code.  Zip Codes must be either 5 or 9 digits.\n";
                makeFieldInError(e);
              }
            }

            if (e.date) {
              if (!check_date(e)) {
                errors += e.label + " is an invalid date.  Please use MM/DD/YYYY format.\n";
                makeFieldInError(e);
              }
            }

            if (e.ssn) {
              if (isValidSsn(e)) {
                 e.value = formatSsn(e.value);
              } else {
                errors += e.label + " is invalid.  Please enter in 999-99-9999 format.\n";
                makeFieldInError(e);
              }
            }

            if (e.correctformat) {
              if (!isValidFormat(e.value, e.format)) {
                errors += e.label + " is invalid.  Please enter in " + e.format + " format.\n";
                makeFieldInError(e);
              }
            }
              
            if (e.year) {
               e.integer=true;
               if (e.min) {
               } else {
                 e.min=1900;
               }
               if (e.max) {
               } else {
                 e.max=2050;
               }
            }

            if (e.number) {
                cleanText(e, ",$ ");
                var v = parseFloat(e.value);
                if (isNaN(v)) {
                    errors += "- The field " + e.label + " must be a number.\n";
                    makeFieldInError(e);
                } else {
                  e.value = v;
                  errorMsg = checkMinMax(e, v);
                  if (errorMsg) {
                     errors+=errorMsg;
                     makeFieldInError(e);
                  }
                }
            }

            if (e.integer) {
                cleanText(e, ", ");
                var v = parseInt(e.value);
                if (isNaN(v)) {
                    errors += "- The field " + e.label + " must be an integer.\n";
                    makeFieldInError(e);
                } else {
                  e.value = v;
                  errorMsg = checkMinMax(e, v);
                  if (errorMsg) {
                     errors+=errorMsg;
                     makeFieldInError(e);
                  }
                }
            }

        }
        if (e.validator) {
           errorMsg = e.validator(e,errors);
           if (errorMsg) {
              errors+=errorMsg;
              makeFieldInError(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 error(s).\n";
    msg += "Please correct these error(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;
}
