
var doalert = true;
var noalert = false;
var invalidfields = "";
var digits = "0123456789";
var lowercaseLetters = "abcdefghijklmnopqrstuvwxyz";
var uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var whitespace = " \t\n\r";
var decimalPointDelimiter = ".";
var phoneNumberDelimiters = "()-. ";
var validUSPhoneChars = digits + phoneNumberDelimiters;
var validWorldPhoneChars = digits + phoneNumberDelimiters + "+" + "/";
var SSNDelimiters = "- ";
var AccountNumberDelimiters = "- ";
var validSSNChars = digits + SSNDelimiters;
var digitsInSocialSecurityNumber = 9;
var digitsInAccountNumber = 8;
var digitsInUSPhoneNumber = 10;
var ZIPCodeDelimiters = "-";
var ZIPCodeDelimeter = "-";
var validZIPCodeChars = digits + ZIPCodeDelimiters;
var digitsInZIPCode1 = 5;
var digitsInZIPCode2 = 9;
var creditCardDelimiters = " ";
var mPrefix = "You did not enter a value into the ";
var mSuffix = " field. This is a required field. Please enter it now.";
var USStateCodeDelimiter = "|";
var USStateCodes = "AL|AK|AS|AZ|AR|CA|CO|CT|DE|DC|FM|FL|GA|GU|HI|ID|IL|IN|IA|KS|KY|LA|ME|MH|MD|MA|MI|MN|MS|MO|MT|NE|NV|NH|NJ|NM|NY|NC|ND|MP|OH|OK|OR|PW|PA|PR|RI|SC|SD|TN|TX|UT|VT|VI|VA|WA|WV|WI|WY|AE|AA|AE|AE|AP";
var validNameChars = "'-., ";

var sLastName = "Last Name";
var sFirstName = "First Name";
var sWorldLastName = "Family Name";
var sWorldFirstName = "Given Name";
var sTitle = "Title";
var sCompanyName = "Company Name";
var sUSAddress = "Street Address";
var sWorldAddress = "Address";
var sCity = "City";
var sState = "State Code";
var sWorldState = "State, Province, or Prefecture";
var sCountry = "Country";
var sZIPCode = "ZIP Code";
var sWorldPostalCode = "Postal Code";
var sPhone = "Phone Number";
var sFax = "Fax Number";
var sEmail = "Email";
var sSSN = "Social Security Number";
var sAccountNumber = "Account Number";

var iState = "This field must be a valid two character U.S. state abbreviation (like CA for California). Please re-enter it now.";
var iZIPCode = "This field must be a 5 or 9 digit U.S. ZIP Code (like 94043). Please re-enter it now.";
var iUSPhone = "Your telephone number needs to be in the correct format, including an area code, such as 8605554496.";
var iWorldPhone = "Your telephone number needs to be in the correct format, including an area code, such as 8605554496, or a country code, such as 85225390000.";
var iUSFax = "Your fax number needs to be in the correct format, including an area code, such as 8605554496.";
var iWorldFax = "Your fax number needs to be in the correct format, including an area code, such as 8605554496, or a country code, such as 85225390000.";
var iSSN = "This field must be a 9 digit numeric social security number (like 123456789). Please re-enter it now.";
var iAccountNumber = "This field must be an 8 digit numeric account number (like 12345678). Please re-enter it now."
var iEmail = "To submit your e-mail, you must provide a valid e-mail address in the correct format, such as name@domain.com.";
var iDay = "This field must be a day number between 1 and 31.  Please re-enter it now.";
var iMonth = "This field must be a month number between 1 and 12.  Please re-enter it now.";
var iYear = "This field must be  4 digit year number.  Please re-enter it now.";
var iString = "This field must be text of some kind.  Please re-enter it now.";
var iNumber = "This field must be a number (like 9, 1.234 or 0.1234 if it's a decimal).  Please re-enter it now.";

var pEntryPrompt = "Please enter a "; 
var pState = "2 character code (like CA).";
var pZIPCode = "5 or 9 digit U.S. ZIP Code (like 94043).";
var pUSPhone = "10 digit U.S. phone number (like 415 555 1212).";
var pWorldPhone = "international phone number.";
var pSSN = "9 digit U.S. social security number (like 123 45 6789).";
var pEmail = "valid email address (like foo@bar.com).";
var pNumber = "number (like 9, 1.234 or 0.1234 if it's a decimal).";
var defaultEmptyOK = false;

// Make a blank array of size n (1..n), populated with zeroes
function makeArray(n) {
   for (var i = 1; i <= n; i++) {
      this[i] = 0;
   } 
   return this;
}

// Make an array called daysInMonth
var daysInMonth = makeArray(12);
daysInMonth[1] = 31;
daysInMonth[2] = 29;
daysInMonth[3] = 31;
daysInMonth[4] = 30;
daysInMonth[5] = 31;
daysInMonth[6] = 30;
daysInMonth[7] = 31;
daysInMonth[8] = 31;
daysInMonth[9] = 30;
daysInMonth[10] = 31;
daysInMonth[11] = 30;
daysInMonth[12] = 31;

// *******************************************************
// String and number functions ***************************
// *******************************************************
// Is the string non-existent (null) or is it's length equal to zero?
function isEmpty(s)
{   return ((s == null) || (s.length == 0))
}

// *******************************************************
// Is the string empty (see above) or is it full of whitespace characters (tabs, returns etc)
function isWhitespace (s)
{   var i;
        if (isEmpty(s)) return true;
            
    for (i = 0; i < s.length; i++)
    {   
                var c = s.charAt(i);
        if (whitespace.indexOf(c) == -1) return false;
    }
        return true;
}
// *******************************************************
// Convert all the underscores in a string to spaces
function underscoreToSpace (s)
{   var i;
    var returnString = "";
        
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (c=="_") {returnString += " "} else {returnString += c};
    }
    return returnString;
}
// *******************************************************
// Convert all the spaces in a string to dots
function spaceToDot (s)
{   var i;
    var returnString = "";
        
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (c==" ") {returnString += "."} else {returnString += c};
    }
    return returnString;
}
// *******************************************************
// Are all the characters in the string in the bag (a set of characters)?
function allCharsInBag (s, bag)
{   
	flag=true;
	for (i = 0; i < s.length; i++)
	{
		flag=flag&&(bag.indexOf(s.charAt(i)) != -1);
	}
    return (flag);
}
// *******************************************************
// Strip out all the characters in the string that are in the bag
function stripCharsInBag (s, bag)
{   var i;
    var returnString = "";
        
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}
// *******************************************************
// Strip out all the characters in the string that are NOT in the bag
function stripCharsNotInBag (s, bag)
{   var i;
    var returnString = "";
        
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (bag.indexOf(c) != -1) returnString += c;
    }
    return returnString;
}
// *******************************************************
function stripWhitespace (s)
// Strip out all the characters in the string that are whitespace
{   
	return stripCharsInBag (s, whitespace)
}
// *******************************************************
// Is the character in the string?
function charInString (c, s)
{   for (i = 0; i < s.length; i++)
    {   if (s.charAt(i) == c) return true;
    }
    return false
}

// *******************************************************
// Strip any leading whitespace characters from the string
function stripInitialWhitespace (s)
{   var i = 0;
    while ((i < s.length) && charInString (s.charAt(i), whitespace))
       i++;
    return s.substring (i, s.length);
}
// *******************************************************
// Is the character a letter?
function isLetter (c)
{   return ( ((c >= "a") && (c <= "z")) || ((c >= "A") && (c <= "Z")) )
}
// *******************************************************
// Is the character a number?
function isDigit (c)
{   return ((c >= "0") && (c <= "9"))
}
// *******************************************************
// Is the character a letter or number?
function isLetterOrDigit (c)
{   return (isLetter(c) || isDigit(c))
}
// *******************************************************
// Does the string represent a valid integer (7, 111, 0)?
function isInteger (s)
{   var i;
    if (isEmpty(s)) 
       if (isInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isInteger.arguments[1] == true);
            
    for (i = 0; i < s.length; i++)
    {   
                var c = s.charAt(i);
        if (!isDigit(c)) return false;
    }
        return true;
}
// *******************************************************
// Does the string represent a valid signed integer (+7, -111)?
function isSignedInteger (s)
{   if (isEmpty(s)) 
       if (isSignedInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isSignedInteger.arguments[1] == true);
    else {
        var startPos = 0;
        var secondArg = defaultEmptyOK;
        if (isSignedInteger.arguments.length > 1)
            secondArg = isSignedInteger.arguments[1];
                if ( (s.charAt(0) == "-") || (s.charAt(0) == "+") )
           startPos = 1;    
        return (isInteger(s.substring(startPos, s.length), secondArg))
    }
}
// *******************************************************
// Does the string represent a positive integer (7, 111, +9)?
function isPositiveInteger (s)
{   var secondArg = defaultEmptyOK;
    if (isPositiveInteger.arguments.length > 1)
        secondArg = isPositiveInteger.arguments[1];
                        
    return (isSignedInteger(s, secondArg)
         && ( (isEmpty(s) && secondArg)  || (parseInt (s, 10) > 0) ) );
}
// *******************************************************
// Does the string represent a non-negative integer (7, 111, +9, 0)?
function isNonnegativeInteger (s)
{   var secondArg = defaultEmptyOK;
    if (isNonnegativeInteger.arguments.length > 1)
        secondArg = isNonnegativeInteger.arguments[1];
                        
    return (isSignedInteger(s, secondArg)
         && ( (isEmpty(s) && secondArg)  || (parseInt (s, 10) >= 0) ) );
}
// *******************************************************
// Does the string represent a negative integer (-9)?
function isNegativeInteger (s)
{   var secondArg = defaultEmptyOK;
    if (isNegativeInteger.arguments.length > 1)
        secondArg = isNegativeInteger.arguments[1];
                        
    return (isSignedInteger(s, secondArg)
         && ( (isEmpty(s) && secondArg)  || (parseInt (s, 10) < 0) ) );
}
// *******************************************************
// Does the string represent a non-positive integer (-9, 0)?
function isNonpositiveInteger (s)
{   var secondArg = defaultEmptyOK;
    if (isNonpositiveInteger.arguments.length > 1)
        secondArg = isNonpositiveInteger.arguments[1];
                        
    return (isSignedInteger(s, secondArg)
         && ( (isEmpty(s) && secondArg)  || (parseInt (s, 10) <= 0) ) );
}
// *******************************************************
// Does the string represent a floating-point number (9.1, 0.5)?
function isFloat (s)
{   var i;
    var seenDecimalPoint = false;
    if (isEmpty(s)) 
       if (isFloat.arguments.length == 1) return defaultEmptyOK;
       else return (isFloat.arguments[1] == true);
    if (s == decimalPointDelimiter) return false;
            
    for (i = 0; i < s.length; i++)
    {   
                var c = s.charAt(i);
        if ((c == decimalPointDelimiter) && !seenDecimalPoint) seenDecimalPoint = true;
        else if (!isDigit(c)) return false;
    }
        return true;
}
// *******************************************************
// Does the string represent a signed floating-point number (-9.1, +0.5)?
function isSignedFloat (s)
{   if (isEmpty(s)) 
       if (isSignedFloat.arguments.length == 1) return defaultEmptyOK;
       else return (isSignedFloat.arguments[1] == true);
    else {
        var startPos = 0;
        var secondArg = defaultEmptyOK;
        if (isSignedFloat.arguments.length > 1)
            secondArg = isSignedFloat.arguments[1];
                if ( (s.charAt(0) == "-") || (s.charAt(0) == "+") )
           startPos = 1;    
        return (isFloat(s.substring(startPos, s.length), secondArg))
    }
}
// *******************************************************
function isAlphabetic (s)
// Is the string composed exclusively of letters?
{   var i;
    if (isEmpty(s)) 
       if (isAlphabetic.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphabetic.arguments[1] == true);
            
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (!isLetter(c))
        return false;
    }
        return true;
}
// *******************************************************
function isAlphanumeric (s)
// Is the string composed exclusively of letters and digits?
{   var i;
    if (isEmpty(s)) 
       if (isAlphanumeric.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphanumeric.arguments[1] == true);
            
    for (i = 0; i < s.length; i++)
    {   
                var c = s.charAt(i);
        if (! (isLetter(c) || isDigit(c) ) )
        return false;
    }
        return true;
}
// *******************************************************
function isValidName (s)
// Is the string composed exclusively of valid name characters?
// i.e. alphabetic and may contain "validNameChars"
{   var i;
    var containsLetter = false;
    if (isEmpty(s)) 
       if (isAlphabetic.arguments.length == 1) return defaultEmptyOK;
       else return (isAlphabetic.arguments[1] == true);
            
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (!isLetter(c)) {
		  if (!allCharsInBag(c,validNameChars))
            return false;
		}
		else
		  containsLetter = true;
    }
	
	if (containsLetter == true)
	  return true;
	else
	  return false;
}

// *******************************************************
// Format checking functions******************************
// *******************************************************
// Given a string and a series of characters/length values, return a formatted string
// SSN = 012345678
// reformat (SSN, "", 3, "-", 2, "-", 4)
// SSS becomes 012-34-5678
function reformat (s)
{   var arg;
    var sPos = 0;
    var resultString = "";
    for (var i = 1; i < reformat.arguments.length; i++) {
       arg = reformat.arguments[i];
       if (i % 2 == 1) resultString += arg;
       else {
           resultString += s.substring(sPos, sPos + arg);
           sPos += arg;
       }
    }
    return resultString;
}
// *******************************************************
// Is the string a valid social security number, excluding symbols (111223333)?
function isSSN (s)
{   if (isEmpty(s)) 
       if (isSSN.arguments.length == 1) return defaultEmptyOK;
       else return (isSSN.arguments[1] == true);
    return (isInteger(s) && s.length == digitsInSocialSecurityNumber)
}
// *******************************************************
// Is the string a valid account number?
function isAccountNumber (s)
{  if (isEmpty(s)) 
       if (isAccountNumber.arguments.length == 1) return defaultEmptyOK;
       else return (isAccountNumber.arguments[1] == true);
    return (isInteger(s) && s.length == digitsInAccountNumber)
}
// *******************************************************
// Is the string a valid US phone number, excluding symbols (8885551212)?
function isUSPhone (s)
{   
    return (isInteger(s) && s.length == digitsInUSPhoneNumber)
}
// *******************************************************
function isInternationalPhone (s)
// Do all the characters in the string fit in the bag of valid world phone number characters?
{   
    return (allCharsInBag(s, validWorldPhoneChars));
}
// *******************************************************
function isZIPCode (s)
// Is the string a valid zipcode, minus the symbols (12345, 123412345)?
{  
   return (isInteger(s) && 
            ((s.length == digitsInZIPCode1) ||
             (s.length == digitsInZIPCode2)))
}
// *******************************************************
function isState (s)
// Is the string a US state abbreviation(CT, VT, az)?
{       
    upState = s.toUpperCase();
    return ( (USStateCodes.indexOf(upState) != -1) &&
             (upState.indexOf(USStateCodeDelimiter) == -1) )
}
// *******************************************************
function isEmail (s)
// Is the string in a valid email address format (x@y.z)?
{   
    if (isWhitespace(s)) return false;
    var i = 1;
    var sLength = s.length;
        while ((i < sLength) && (s.charAt(i) != "@"))
    { i++
    }
    if ((i >= sLength) || (s.charAt(i) != "@")) return false;
    else i += 2;
        while ((i < sLength) && (s.charAt(i) != "."))
    { i++
    }
        if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
    else return true;
}
// *******************************************************
function isURL (s)
// Is the string in a valid url (http(s)://)?
{ var site = s.substring(0, 8);
	if ((site.substring(0,7) != "http://") && (site != "https://") ) {
	return false;
	} else {
	return true;
	}
}
// *******************************************************
function isYear (s)
// Is the string a valid positive year (43, 1911, 2011)?
{   if (isEmpty(s)) 
       if (isYear.arguments.length == 1) return defaultEmptyOK;
       else return (isYear.arguments[1] == true);
    if (!isNonnegativeInteger(s)) return false;
    return (s.length == 4);
}
// *******************************************************
// Is the integer in the range a to b?
function isIntegerInRange (s, a, b)
{   if (isEmpty(s)) 
       if (isIntegerInRange.arguments.length == 1) return defaultEmptyOK;
       else return (isIntegerInRange.arguments[1] == true);
            if (!isInteger(s, false)) return false;
                    var num = parseInt (s, 10);
    return ((num >= a) && (num <= b));
}
// *******************************************************
// Is the float in the range a to b?
function isFloatInRange (s, a, b)
{   if (isEmpty(s)) 
       if (isFloatInRange.arguments.length == 1) return defaultEmptyOK;
       else return (isFloatInRange.arguments[1] == true);
            if (!isFloat(s, false)) return false;
                    var num = parseFloat (s);
    return ((num >= a) && (num <= b));
}
// *******************************************************
function isMonth (s)
// Is the string a month value (1..12)?
{   
    return isIntegerInRange (s, 1, 12);
}
// *******************************************************
// Is the string a day of the month (1..31)?
function isDay (s)
{    
    return isIntegerInRange (s, 1, 31);
}
// *******************************************************
// Given a year, return the number of days February will have.
function daysInFebruary (year)
{           return (  ((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0) ) ) ? 29 : 28 );
}
// *******************************************************
// Given year, month and day strings (1917, 11, 4) are they valid dates?
function isDate (year, month, day)
{       if (! (isYear(year, false) && isMonth(month, false) && isDay(day, false))) return false;
            var intYear = parseInt(year);
    var intMonth = parseInt(month);
    var intDay = parseInt(day);
        if (intDay > daysInMonth[intMonth]) return false; 
    if ((intMonth == 2) && (intDay > daysInFebruary(intYear))) return false;
    return true;
}

// *******************************************************
// Alert functions ***************************************
// *******************************************************
// Given a string field, remove all characters after the asterisk and convert all the underscores to spaces
function cleanupName (theField)
{
    s = theField.name;
    s = s.substring(0,s.indexOf("*"));
    s = underscoreToSpace (s);
    return(s);
}
// *******************************************************
// Load the window status bar with a string
function prompt (s)
{   window.status = s;
}
// *******************************************************
// Load the window status bar with the pEntryPrompt message and a string
function promptEntry (s)
{   window.status = pEntryPrompt + s;
}
// *******************************************************
// Send up an alert window notifying a user that a field is empty
function warnEmpty (theField)
{   theField.focus();
    s=cleanupName(theField);
    alert(mPrefix + s + mSuffix);
    return false;
}
// *******************************************************
// Send up an alert window notifying a user that a field is invalid based on a given string
function warnInvalid (theField, s)
{   
	//theField.focus();
    //theField.select();
    alert(s);
    return false;
}
// *******************************************************
// Functions To Interactively Check Various Fields *******
// *******************************************************
// Format a number to be a social security number (111223333 become 111-22-3333)
function reformatSSN (SSN)
{   
	return (reformat (SSN, "", 3, "-", 2, "-", 4))
}

// Is the given field a SSN? If so, reformat it. If it's empty and that's OK then return true.
function checkSSN (theField, emptyOK)
{   if (checkSSN.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    else
    {  var normalizedSSN = stripCharsInBag(theField.value, SSNDelimiters)
       if (!isSSN(normalizedSSN, false)) 
          return warnInvalid (theField, iSSN);
       else 
       {            
          //CIGNA requested format change for SSN on 3/12/01 -- bblake     
          //theField.value = reformatSSN(normalizedSSN);
		  theField.value = normalizedSSN;
          return true;
       }
    }
}

// Is the given field a valid Account Number? If it's empty and that's OK then return true.
function checkAccountNumber (theField, emptyOK)
{   if (checkAccountNumber.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    else
    {  var normalizedAccNum = stripCharsInBag(theField.value, AccountNumberDelimiters)
       if (!isAccountNumber(normalizedAccNum, false)) 
          return warnInvalid (theField, iAccountNumber);
       else 
       {            
		  theField.value = normalizedAccNum;
          return true;
       }
    }
}

// Is the given field a year? If it's empty and that's OK then return true.
function checkYear (theField, emptyOK)
{   if (checkYear.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    if (!isYear(theField.value, false)) 
       return warnInvalid (theField, iYear);
    else return true;
}


// Is the given field a month? If it's empty and that's OK then return true.
function checkMonth (theField, emptyOK)
{   if (checkMonth.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    if (!isMonth(theField.value, false)) 
       return warnInvalid (theField, iMonth);
    else return true;
}


// Is the given field a day? If it's empty and that's OK then return true.
function checkDay (theField, emptyOK)
{   if (checkDay.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    if (!isDay(theField.value, false)) 
       return warnInvalid (theField, iDay);
    else return true;
}

// Is the given field a date? If it's empty and that's OK then return true.
function checkDate (yearField, monthField, dayField, labelString, OKtoOmitDay)
{           if (checkDate.arguments.length == 4) OKtoOmitDay = false;
    if (!isYear(yearField.value)) return warnInvalid (yearField, iYear);
    if (!isMonth(monthField.value)) return warnInvalid (monthField, iMonth);
    if ( (OKtoOmitDay == true) && isEmpty(dayField.value) ) return true;
    else if (!isDay(dayField.value)) 
       return warnInvalid (dayField, iDay);
    if (isDate (yearField.value, monthField.value, dayField.value))
       return true;
    alert (iDatePrefix + labelString + iDateSuffix)
    return false
}

// Is the given field a number? 
// If an alert is requested and the field is invalid then put up an alert.
function checkNumber (theField, isAlert)
{           
    if (isEmpty(theField.value))
    {
      if (isAlert) warnEmpty(theField);
      return false;
    }
    else
    {
    	if (isInteger(theField) || isSignedInteger(theField) || isFloat (theField) || isSignedFloat (theField))
    	{
	    	return true;
	    }
	    else
	    {
		    if (isAlert) warnInvalid (theField, iNumber);
	    	return false;
	    }
    }
}

// Is the given field a string? 
// If an alert is requested and the field is invalid then put up an alert.
function checkString (theField, isAlert)
{           
    if (isEmpty(theField.value))
    {
      if (isAlert) warnEmpty(theField);
      return false;
    }
    else
    {
      return true;
    }
}

// Shift the field to all uppercase characters.
// Is the given field a state? 
// If an alert is requested and the field is invalid then put up an alert.
function checkState (theField, isAlert)
{   
  theField.value = theField.value.toUpperCase();
  if (!isState(theField.value))
  {
    if (isAlert) warnInvalid (theField, iState);
    return false;
  }
  else
  {
    return true;
  }
}

// Convert a string to zip code format (12345 stays the same, 123456789 becomes 12345-6789)
function reformatZIPCode (ZIPString)
{   if (ZIPString.length == 5) return ZIPString;
    else return (reformat (ZIPString, "", 5, "-", 4));
}

// Is a given field a valid zipcode format?
// Reformat it if it's OK.
// If an alert is requested and the field is invalid then put up an alert.
function checkZIPCode (theField, isAlert)
{
  var normalizedZIP = stripCharsInBag(theField.value, ZIPCodeDelimiters);
  if (!isZIPCode(normalizedZIP)) 
  {
    if (isAlert) warnInvalid (theField, iZIPCode);
    return false;
    
  }
  else
  {
    theField.value = reformatZIPCode(normalizedZIP)
    return true;
  }
}

// Convert a string to US phone number formatting (1112223333 becomes 111.222.3333)
function reformatUSPhone (USPhone)
{  
	 return (reformat (USPhone, "",3, ".", 3, ".", 4));
}

// Is a given field a valid US phone number format?
// Reformat it if it's OK.
// If an alert is requested and the field is invalid then put up an alert.
function checkUSPhone (theField, isAlert)
{   
  var normalizedPhone = stripCharsInBag(theField.value, phoneNumberDelimiters);
  if (!isUSPhone(normalizedPhone)) 
  {
    if (isAlert)
	{ 
	  if (theField.name.indexOf('Fax') == -1)
	  	warnInvalid (theField, iUSPhone);
	  else
	    warnInvalid (theField, iUSFax);
      return false;
	}
  }
  else
  {
    theField.value = reformatUSPhone(normalizedPhone)
    return true;
  }
}

// Is a given field a valid international phone number format?
// If an alert is requested and the field is invalid then put up an alert.
function checkInternationalPhone (theField, isAlert)
{   
  if (!isInternationalPhone(theField.value))
  {
    if (isAlert)
	{ 
	  if (theField.name.indexOf('Fax') == -1)
	    warnInvalid (theField, iWorldPhone);
	  else
	    warnInvalid (theField, iWorldFax);
      return false;
	}
  }
  else
  {
    return true;
  }
}

// Is a given field a valid phone number format of any kind?
// If an alert is requested and the field is invalid then put up an alert.
function checkAnyPhone (theField, isAlert)
{
	f=theField.value;
	f=stripCharsInBag(f, phoneNumberDelimiters);
	if (f.length <= 10)
	{
		return (checkUSPhone(theField, isAlert));
	}
	else
	{
		return (checkInternationalPhone(theField, isAlert));
	}
}

// Is a given field a valid email format?
// If an alert is requested and the field is invalid then put up an alert.
function checkEmail (theField, isAlert)
{   
    if (!isEmail(theField.value)) 
    {
      if (isAlert) warnInvalid (theField, iEmail);
      return false;
    }
    else
    {
      return true;
    }
}

// Given a form and a string which is the name of a field in that form, return the form elementobject with that name
// If the field is unfound alert the user
function getnamedelement(theform,thename)
{
	for (i=0;i<theform.elements.length;i++)
	{
		if (theform.elements[i].name==thename)
		{
			return(theform.elements[i]);
		}
	}
	alert("The form element named "+thename+" was not found in the form named "+theform.name+".");
	return(false);
}

// Are either or both of the fields in the form valid e-mails?
function eitherormail (theform,e1,e2)
{
	email1=getnamedelement(theform,e1);
	email2=getnamedelement(theform,e2);
	if (!isWhitespace(email1.value))
	{	
		checkEmail(email1,noalert);
	}
	if (!isWhitespace(email2.value))
	{	
		checkEmail(email2,noalert);
	}
	return(isEmail(email1.value) || isEmail(email2.value));
}

var invalidfields;

// *****************************************************************************************
// This function checks to see if all the required fields are entered and whether they are
// a valid format, if so then it returns true otherwise it returns false
function valid(theform, boolAlert)
{   
	invalidfields = "";
	allarevalid=true;
	
	for (i = 0; ((i < theform.elements.length)); i++) //go through every element...
	{
		thisonesvalid=true;
		elementname=theform.elements[i].name;
		wheresthestar=elementname.indexOf('*');
		
		cleanfieldname=underscoreToSpace(elementname.substring(0, wheresthestar));
		if (wheresthestar > 0) //if there is a star in the field name then it's required...
		{		
			if (isEmpty(theform.elements[i].value))
      		{
      			// if its empty then throw up a warning (if requested). Store the field name as invalid and send back false
        		
				if (boolAlert==true) warnEmpty(cleanfieldname);
				invalidfields = invalidfields + cleanfieldname + " is empty.\n";
				allarevalid = false;
     		}
      		else
     		{
				// if it isnt empty then...
	  			// perform check to see what the type of required field is and whether its valid
	  			wheresthecolon=elementname.indexOf(':');
	  			if (wheresthecolon > 0)
	  			{
	  				endofrequiredtype=wheresthecolon;
	  			}
	  			else
	  			{
	  				endofrequiredtype=elementname.length;
	  			}
	  			requiredtype=elementname.substring(wheresthestar+1,endofrequiredtype);
	  			if (requiredtype == "number") 
				thisonesvalid = checkNumber(theform.elements[i], noalert)
				
				if (requiredtype == "string") 
				thisonesvalid = checkString(theform.elements[i], noalert)
				
	  			if (requiredtype == "state") 
				thisonesvalid = checkState(theform.elements[i], noalert)
				
	  			if (requiredtype == "zip") 
				thisonesvalid = checkZIPCode(theform.elements[i], noalert)
				
	  			if (requiredtype == "phone") 
				thisonesvalid = checkUSPhone(theform.elements[i], noalert)
				
	  			if (requiredtype == "email") 
				thisonesvalid = checkEmail(theform.elements[i], noalert)
				
				if (thisonesvalid == false) invalidfields = invalidfields + cleanfieldname + " is misformatted.\n";
				allarevalid = allarevalid && thisonesvalid;
			} 
		} 
	} //end for
	return (allarevalid);
}


// *****************************************************************************************
// This function checks to see if the form is valid and then submits it, otherwise it alerts
// the user
function validSend (theform, boolAlert)
{
	invalidfields="";
	if (valid(theform, boolAlert))
	{
		theform.submit();
		return (true);
	}
	else
	{
		if (invalidfields != "") alert("The following fields were either left empty or improperly formatted:\n"+invalidfields);
		return (false);
	}
}

