/**
 * JavaScript Form Validation Library
 *
 * <p>
 * <b>Changelog:</b> <pre>
 *   1.00  author 2000/02/21 created
 *   1.01  REVIE  2000/09/29 added a checkAll() to check to see if all
 *                           form fields had been at least filled in
 * </pre>
 *
 *     NOTE: Save this file as validate.js
 * HOMEPAGE: http://sites.netscape.net/michaelanino/kitten
 *
 * @author Michael Nino (mnino@insight.com)
 * @version 1.01
 */

/**
 * FUNCTION: Match( field, value, equals)
 *  PURPOSE: Returns true if field's value matches/equals the 
 *           value argument otherwise returns false. Setting the
 *           the equal argument to true indicates you wish the
 *           the value argument to equal the field's value. 
 *
 */




function Match( field, value, equals ) {
   var pattern;
   var r;
   var checked = 0;
   var blank = new RegExp("^[ ]*$");


   if ( equals ) {
      pattern = new RegExp("^"+value+"$");
   } else {
      pattern = new RegExp(value);
   } // if else

   /* Text Fields/Areas/Hidden */
   /* 
      NOTE: DOES NOT SUPPORT MULTIPLE HIDDEN FIELDS 
      WITH THE SAME NAME NOR DOES IT SUPPORT FIELDS
      WITH DIFFERENT TYPES AND USING THE SAME NAME.
      THIS IS A FEATURE TO BE IMPLEMENTED IN THE
      NEXT RELEASE OF THIS LIBRARY!
   */
  
   if ( (field.type == "text") || 
        (field.type == "password") || 
        (field.type == "textarea") || 
        (field.type == "hidden") ) {
      return field.value.match(pattern);
   } // if

   /* Select Fields */
   if ( (field.type == "select-one") || ( field.type == "select" ) ) {
      if (field.selectedIndex == -1) {
         return false;
      } // if
      return field.options[field.selectedIndex].value.match(pattern);
   } // if

   /* Radio Button Groups */
   if ( field[0] && field[0].type == "radio" ) {
      for (r=0; r<field.length; r++) {
         if ( field[r].checked ) {
            checked++;
         } // if 
         if ( (field[r].checked) && (field[r].value.match(pattern)) ) {
            return true;
         } // if
      } // for 
      return false;
   } // if


} // Match


/**
 * FUNCTION: Equal( field, value )
 *  PURPOSE: Returns true if field's value is equals 
 *           the value argument otherwise returns false.
 *           This function is a wrapper to a Match function
 *           call with the equal argument specified. 
 *
 */
function Equal( field, value ) {
   return Match(field,value,true);
} // Equal


/**
 * FUNCTION: Number( field )
 *  PURPOSE: Returns true if field's value is a integer 
 *           the value argument otherwise returns false.
 *           This function is a wrapper to a Match function
 *           call with the equal argument specified.
 *
 */
function isNumber( field ) {
   return Match(field,'[0-9]+',true);
} // Number


/**
 * FUNCTION: DateValue( field )
 *  PURPOSE: Returns true if field's value is a valid date string
 *           the value argument otherwise returns false.
 *           This function is a wrapper to a Match function
 *           call with the equal argument specified.
 *
 */
function DateValue( field ) {
   if (Match(field,'(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|30|31)-[1-9][0-9][0-9][0-9]',true) ||
       Match(field,'(0[1-9]|1[0-2])\\/(0[1-9]|[1-2][0-9]|30|31)\\/[1-9][0-9][0-9][0-9]',true) ) { 
      return true; 
   } else { 
      return false; 
   }
} // DateValue


/**
 * FUNCTION: DateValue( field )
 *  PURPOSE: Returns true if field's value is a valid date string
 *           the value argument otherwise returns false.
 *           This function is a wrapper to a Match function
 *           call with the equal argument specified.
 *
 */
function TimeValue( field ) {
   return Match(field,'(0[0-9]|1[0-2]):[0-5][0-9](:[0-5][0-9]){0,1}',true);
} // TimeValue



/**
 * FUNCTION: Currency( field )
 *  PURPOSE: Returns true if field's value is a currency value 
 *           the value argument otherwise returns false.
 *           This function is a wrapper to a Match function
 *           call with the equal argument specified.
 *
 */
function Currency( field ) {
   return Match(field,'[$]*([0-9]{1,3}[,])*[0-9]{0,3}\.[0-9]{2}',true);
} // Currency


/**
 * FUNCTION: SSN( field )
 *  PURPOSE: Returns true if field's value is a social security number
 *           the value argument otherwise returns false.
 *           This function is a wrapper to a Match function
 *           call with the equal argument specified.
 *
 */
function SSN( field ) {
   return Match(field,'[0-9]{3}-[0-9]{2}-[0-9]{4}',true);
} // SSN

//This function is already in the Re-architected /_files/formfunctions.js
function isValidSSN(sSSN, bFourDigitOnly){

	/* 
	This function checks that the user has entered a properly formatted SSN.
	It will validate that the passed in string (sSSN) was entered as
	999-99-9999, 999999999, or 9999 (for last four digit check only).
	It also checks various SSN formatting rules.
	Parameters:
		sSSN = string to test
		bFourDigitOnly = true or false.  Check for last four digits only.
	Returns:
		true or false
	*/

	// Check for spaces and periods
	// We don't have to check for other special characters
	// because the isNaN check will catch any other characters.
	if(sSSN.indexOf(" ")>-1 || sSSN.indexOf(".")>-1){
		return (false);
	}

	if(sSSN.length == 11){
		if(sSSN.charAt(3)!="-" || sSSN.charAt(6)!="-"){
			return (false);	// SSN not 999-99-9999
		}		
	}

	// Strip out any hyphens
	var i = sSSN.indexOf("-");
	while(sSSN.indexOf("-") > -1){
		sSSN = sSSN.substring(0,i) + sSSN.substring(i+1);
		i = sSSN.indexOf("-");
	}

	if(sSSN.length!=4 && sSSN.length!=9){
		return (false);	// At this point, SSN should be either 4 or 9 characters
	}

	if(isNaN(sSSN)){
		return (false);	// SSN is not numeric
	}

	if(bFourDigitOnly){
		if(sSSN=="0000" || sSSN.length!=4){
			return (false);	// Last 4 digits cannot be all zeros
		}
	}else{
		if(sSSN.length != 9){
			return (false);	// SSN is not 9 digits
		}
		if(sSSN.substring(0,3)=="000" || sSSN.substring(0,3)>"772" || sSSN.substring(0,3)=="666" || sSSN.substring(3,5)=="00" || sSSN.substring(5,8)=="0000"){
			// All zeros are not allowed in any of the groups
			// Highest area (first 3 digits) currently assigned is 772. See http://www.ssa.gov/history/ssn/geocard.html
			// 666 is not assigned by the SSA
			return (false);
		}
		if(sSSN>="987654320" && sSSN<="987654329"){
			// This check is redundant since the 772 check above will catch this first
			return (false); // This block of SSNs reserved by SSA for advertising use
		}
	}

	return (true);	
}


/**
 * FUNCTION: Phone( field )
 *  PURPOSE: Returns true if field's value is a phone number
 *           the value argument otherwise returns false.
 *           This function is a wrapper to a Match function
 *           call with the equal argument specified.
 *
 */
function Phone( field ) {
   if (Match(field,'(1-|1 ){0,1}[0-9]{3}-[0-9]{3}-[0-9]{4}',true) ||
       Match(field,'(1-|1 ){0,1}\\([0-9]{3}\\) [0-9]{3}-[0-9]{4}',true) ) {
     return true; 
   } else { 
      return false;
   } 
} // Phone


/**
 * FUNCTION: Email( field )
 *  PURPOSE: Returns true if field's value is an email address
 *           the value argument otherwise returns false.
 *           This function is a wrapper to a Match function
 *           call with the equal argument specified.
 *
 */
function Email( field ) {
   return Match(field,'[0-9a-zA-Z_]+[@][0-9a-zA-Z_]+(\\.[0-9a-zA-Z_]+)+',true);
} // Email



//////This Validates e-mail Addresses (D.Walgren, D.Luko, 11/15/02):
function IsValidEmail(emailfield) {
	var iAt;
	var iAt2;
	var iPeriod;
	var iSpace;
	var iLength;
	var sFirstChar;
	var sLastChar;
	var pattern;
	var res;
	var field = new String(emailfield);

	iAt = field.indexOf("@", 1);
	iLength = field.length;
	sFirstChar = field.substring(0,1);
	sLastChar = field.substring(iLength-1, iLength);

	if(field.indexOf("..") > 0) {
		alert("Please correct the e-mail address. Two periods together are not allowed.");
 		return false;
	}
	if(field.indexOf(".@") > 0) {
		alert("Please correct the e-mail address. A period cannot preceed the @ symbol.");
 		return false;
	}
	if(iAt == -1) {
		alert("Please correct the e-mail address. An @ symbol is required.");
		return false;
	}
	iAt2 = field.indexOf("@", iAt + 1);
	if(iAt2 != -1) {
		alert("Please correct the e-mail address. Only one @ symbol is valid.");
 		return false;	
	}
	iPeriod = (field.indexOf(".", iAt + 1));
	if(iPeriod == -1) {
		alert("Please correct the e-mail address. A period is required.");
 		return false;
	}
	if(iPeriod == (iAt+1)) {
		alert("Please correct the e-mail address. A period cannot follow the @ symbol.");
 		return false;
	}
	if(iPeriod == (iAt-1)) {
		alert("Please correct the e-mail address.  A period cannot preceed the @ symbol.");
 		return false;
	}
  	iSpace = (field.indexOf(" ", 1));
  	if(iSpace > 0) {
    		alert("Please correct the e-mail address. Spaces are not valid.");
    		return false;
  	}
	pattern = new RegExp("[0-9a-zA-Z]");
	if (!sFirstChar.match(pattern)) {
		alert("Please correct the e-mail address. The first character must be a letter or number.");
		return false;
	}
	if (!sLastChar.match(pattern)) {
		alert("Please correct the e-mail address. The last character must be a letter or number.");
		return false;
	}
	if (iLength < 5) {
		alert("Please correct the e-mail address. The proper e-mail format is name@aaa.bbb");
		return false;
	}
	var validchars = new String("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-_@");
	for (i=0; i<field.length; i++) {
		j = validchars.indexOf(field.charAt(i), 0);
		if (j < 0) {
			alert("Please correct the e-mail address. Special characters are not allowed. Use only letters, numbers, @, period, underscore and hyphen characters.");
			return false;
		}
	}
	return true;
}//IsValidEmail

/**
 * FUNCTION: Blank( field )
 *  PURPOSE: Returns true if field's value is blank or 
 *           contains spaces otherwise returns false.
 *           This function is a wrapper to a Match function
 *           call with the value argument specified.
 *
 */
function Blank( field ) {
   var r;

   if ( typeof(field.type) == "undefined" ) { // radio button group
      for (r=0; r<field.length; r++) {
         if (field[r].checked) {
            return false;
         } // if
      } // for
      return true;
   } else {
      return Match(field,"[ ]*",true);
   } // if else

} // Blank

/**
 * FUNCTION: checklength( form )
 *  PURPOSE: Given the minimum length that an input
 *           field should be, this returns true, otherwise 
 *           returns false, and displays an error prompt.
 */
function checkLength( field, min_length ) {
   if(Match( field, '[0-9a-zA-Z_]{'+min_length+'}',false )) {
      return true;
   } else {
      alert("The input field isn't long enough.  Must be at least "+
            min_length + " characters in length.");
      return false;
   }
} // checkLength

/**
 * FUNCTION: checkAll( form )
 *  PURPOSE: Returns true if all form fields filled in, otherwise 
 *           returns false, and displays an error prompt.
 */
function checkAll( form ) {
   var empty_fields = new Array();

   if (form.required && form.required.value) {
      var required = form.required.value;
      var fields = required.split(/\s*,\s*/);
      
      for(var i=0; i < fields.length; i++) {
         var e = eval('form.'+fields[i]);
         if (e && Blank(e)) {
            empty_fields[i] = fields[i];
         }
      }
   } else {
      for(var i=0; i < form.length; i++) {
         var e = form.elements[i];
         if (Blank(e)) {
            empty_fields[i] = e.name;
         }
      }
   }

   if (empty_fields.length<=0) { return true; }

   var msg = 
      "We are unable to process your request.\n" +
      "Please correct and re-submit.\n\n" +
      " - The following required field(s) are empty:\n        " + 
      empty_fields.join("\n        ") + "\n";
   alert(msg);
   return false;
} // checkAll
