// VARIABLE DECLARATIONS

var digits = "0123456789";
var lowercaseLetters = "abcdefghijklmnopqrstuvwxyz"
var uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var whitespace = " \t\n\r\f\v";
var decimalPointDelimiter = "."
var phoneNumberDelimiters = "()- ";
var validUSPhoneChars = digits + phoneNumberDelimiters;
var validWorldPhoneChars = digits + phoneNumberDelimiters + "+";
var SSNDelimiters = "- ";
var validSSNChars = digits + SSNDelimiters;
var digitsInSocialSecurityNumber = 9;
var digitsInUSPhoneNumber = 10;
var ZIPCodeDelimiters = "-";
var ZIPCodeDelimeter = "-";
var validZIPCodeChars = digits + ZIPCodeDelimiters;
var digitsInZIPCode1 = 5;
var digitsInZIPCode2 = 9;
var defaultEmptyOK = false;

function makeArray(n) {

   for (var i = 1; i <= n; i++) {
      this[i] = 0
   } 
   return this
}


var daysInMonth = makeArray(12);
daysInMonth[1] = 31;
daysInMonth[2] = 29;   // must programmatically check this
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;

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"

function isEmpty(s)
{   return ((s == null) || (s.length == 0))
}

function isWhitespace (s)

{   var i;

    // Is s empty?
    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;
}

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;
}

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)

{   return stripCharsInBag (s, whitespace)
}


function charInString (c, s)
{   for (i = 0; i < s.length; i++)
    {   if (s.charAt(i) == c) return true;
    }
    return false
}

function stripInitialWhitespace (s)

{   var i = 0;

    while ((i < s.length) && charInString (s.charAt(i), whitespace))
       i++;
    
    return s.substring (i, s.length);
}


function isLetter (c)
{   return ( ((c >= "a") && (c <= "z")) || ((c >= "A") && (c <= "Z")) )
}


function isDigit (c)
{   return ((c >= "0") && (c <= "9"))
}


function isLetterOrDigit (c)
{   return (isLetter(c) || isDigit(c))
}


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;
}


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];

        // skip leading + or -
        if ( (s.charAt(0) == "-") || (s.charAt(0) == "+") )
           startPos = 1;    
        return (isInteger(s.substring(startPos, s.length), secondArg))
    }
}


function isPositiveInteger (s)
{   var secondArg = defaultEmptyOK;

    if (isPositiveInteger.arguments.length > 1)
        secondArg = isPositiveInteger.arguments[1];

    return (isSignedInteger(s, secondArg)
         && ( (isEmpty(s) && secondArg)  || (parseInt (s) > 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) >= 0) ) );
}


function isNegativeInteger (s)
{   var secondArg = defaultEmptyOK;

    if (isNegativeInteger.arguments.length > 1)
        secondArg = isNegativeInteger.arguments[1];


    return (isSignedInteger(s, secondArg)
         && ( (isEmpty(s) && secondArg)  || (parseInt (s) < 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) <= 0) ) );
}

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;
}

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];

        // skip leading + or -
        if ( (s.charAt(0) == "-") || (s.charAt(0) == "+") )
           startPos = 1;    
        return (isFloat(s.substring(startPos, s.length), secondArg))
    }
}


function isAlphabetic (s)

{   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++)
    {   
        // Check that current character is letter.
        var c = s.charAt(i);

        if (!isLetter(c))
        return false;
    }

    // All characters are letters.
    return true;
}

function isAlphanumeric (s)

{   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++)
    {   
        // Check that current character is number or letter.
        var c = s.charAt(i);

        if (! (isLetter(c) || isDigit(c) ) )
        return false;
    }

    // All characters are numbers or letters.
    return true;
}

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;
}

function isUSPhoneNumber (s)
{   if (isEmpty(s)) 
       if (isUSPhoneNumber.arguments.length == 1) return defaultEmptyOK;
       else return (isUSPhoneNumber.arguments[1] == true);
    return (isInteger(s) && s.length == digitsInUSPhoneNumber)
}

function isZIPCode (s)
{  if (isEmpty(s)) 
       if (isZIPCode.arguments.length == 1) return defaultEmptyOK;
       else return (isZIPCode.arguments[1] == true);
   return (isInteger(s) && 
            ((s.length == digitsInZIPCode1) ||
             (s.length == digitsInZIPCode2)))
}

function isStateCode(s)
{   if (isEmpty(s)) 
       if (isStateCode.arguments.length == 1) return defaultEmptyOK;
       else return (isStateCode.arguments[1] == true);
    return ( (USStateCodes.indexOf(s) != -1) &&
             (s.indexOf(USStateCodeDelimiter) == -1) )
}

function isYear (s)
{   if (isEmpty(s)) 
       if (isYear.arguments.length == 1) return defaultEmptyOK;
       else return (isYear.arguments[1] == true);
    if (!isNonnegativeInteger(s)) return false;
    return ((s.length == 2) || (s.length == 4));
}



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);

   return ((num >= a) && (num <= b));
	
}

function isMonth (s){   


	if (isEmpty(s)) {
	      if (isMonth.arguments.length == 1){

			 	return defaultEmptyOK;
	      } else {
		
				return (isMonth.arguments[1] == true);
			}
	}

   return isIntegerInRange (s, 1, 12);
}


function isDay (s)
{   if (isEmpty(s)) 
       if (isDay.arguments.length == 1) return defaultEmptyOK;
       else return (isDay.arguments[1] == true);   
    return isIntegerInRange (s, 1, 31);
}


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 isDate (year, month, day)
{   // catch invalid years (not 2- or 4-digit) and invalid months and days.

//alert("isMonth: " + isMonth(month, false));

    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;
}

function isDateMDY (dateEntry) {
  
  var datevalues=dateEntry.split("/");
  
  if(datevalues.length != 3)return false;
  
  //if there is a leading 0 before day or month, strip it.
  if(datevalues[0].charAt(0)=="0")datevalues[0]=datevalues[0].charAt(1);
  if(datevalues[1].charAt(0)=="0")datevalues[1]=datevalues[1].charAt(1);
  
  if ( !isDate(datevalues[2],datevalues[0],datevalues[1]) ){
    return false;
  }
  return true;

}

function checkString (theField, s, emptyOK)
{   // Next line is needed on NN3 to avoid "undefined is not a number" error
    // in equality comparison below.
    if (checkString.arguments.length == 2) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    if (isWhitespace(theField.value)) 
       return warnEmpty (theField, s);
    else return true;
}


function checkStateCode (theField, emptyOK)
{   if (checkStateCode.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    else
    {  theField.value = theField.value.toUpperCase();
       if (!isStateCode(theField.value, false)) 
          return warnInvalid (theField, iStateCode);
       else return true;
    }
}

function reformatZIPCode (ZIPString)
{   if (ZIPString.length == 5) return ZIPString;
    else return (reformat (ZIPString, "", 5, "-", 4));
}


function checkZIPCode (theField, emptyOK)
{   if (checkZIPCode.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    else
    { var normalizedZIP = stripCharsInBag(theField.value, ZIPCodeDelimiters)
      if (!isZIPCode(normalizedZIP, false)) 
         return warnInvalid (theField, iZIPCode);
      else 
      {  // if you don't want to insert a hyphen, comment next line out
         theField.value = reformatZIPCode(normalizedZIP)
         return true;
      }
    }
}


function reformatUSPhone (USPhone)
{   return (reformat (USPhone, "", 3, "-", 3, "-", 4))
}


function checkUSPhone (theField, emptyOK)
{   if (checkUSPhone.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    else
    {  var normalizedPhone = stripCharsInBag(theField.value, phoneNumberDelimiters)
       if (!isUSPhoneNumber(normalizedPhone, false)) 
          return warnInvalid (theField, iUSPhone);
       else 
       {  // if you don't want to reformat as 123-456-7890, comment next line out
          theField.value = reformatUSPhone(normalizedPhone)
          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;
}


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;
}



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;
}

function checkDate (yearField, monthField, dayField, labelString, OKtoOmitDay)
{   // Next line is needed on NN3 to avoid "undefined is not a number" error
    // in equality comparison below.
    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
}


function getRadioButtonValue (radio)
{   for (var i = 0; i < radio.length; i++)
    {   if (radio[i].checked) { break }
    }
    return radio[i].value
}

/*--------------------------------------------------------------------------------*/

/* Function requiredOk(required, form)
 * Use this function to check the required fields on a form
 * @param required - a comma sepearated list of required fields
 */

var foundRequiredErrors = new Array();  // array to store the found errors
var requiredErrorCount = 0; // error counter
var requiredErrors = "" // String to hold the error message

function requiredOk(required, form){
   // take the required fields from the form and split in to an array
   var requiredFields = stripWhitespace(required).split(",");
   //clean out any old errors in the found errors array
   foundRequiredErrors.length = 0;
   //ensure the error count is 0 to start
   requiredErrorCount = 0;
   //ensure the required errors field is blank
   requiredErrors = "";
   // loop through the required fields array and determine if any fields are blank
   for(var i=0; i < requiredFields.length; i++) {
      field = form[requiredFields[i]];
		
      if(!field.length){
         if(field.type == "text" || field.type == "textarea" || field.type == "password" || field.type == "hidden") {
            fieldval = field.value;

            if(fieldval == "" || fieldval == null || isWhitespace(fieldval)){
               errorFound(requiredFields[i], form);
            }				
   		}
         
      }
      else {
         if(field.type == "select-one" || field.type == "select-multiple") {
            for(var j=0; j < field.options.length; j++){
               if(field.options[j].selected){
                  if(field.options[j].value == "") {
                     errorFound(requiredFields[i], form);
                  }
               }
            } 
         }
         if(field.type == "checkbox" || field.type == "radio") {
            var countNotChecked = 0;
            for(var k=0; k < field.length; k++){  
               if(field[k].checked != true) {
   			   countNotChecked += 1;
   			   }
   		   }
   		   if(countNotChecked == field.length){
               errorFound(requiredFields[i], form);
               countNotChecked = 0;
            }
         }
      }
   }
	
	
	
   if(foundRequiredErrors.length > 0) {     
      requiredErrors = "<p><b>" + required_error_header + " </b><p>"; 
      for(err = 0; err < foundRequiredErrors.length; err++) {

         requiredErrors += "<li>" + error[foundRequiredErrors[err] + ",label"] + "</li>";
      }

      return false;
   }
   return true;
}

/* errorFound(field, form)
 * puts the field name in the error array and sets the container to error
 * then increments the error counter
 * @param field - the name of the field with the error
 *        form - the name of the form to see the error class
 */
function errorFound(field, form){
   foundRequiredErrors[requiredErrorCount] = field;

   document.getElementById(form.name + field+"Container").className="error";	
   requiredErrorCount += 1;
}

/* clearErrorStyles(tagName) function
 * removes the style="error" from all tags of a given type
 * @param tagName - the type of tag to remove the error style from
 */
 
function clearErrorStyles(tagName) {
   for(i=0; i < document.getElementsByTagName(tagName).length; i++){      
      if(document.getElementsByTagName(tagName)[i].className == 'error' || document.getElementsByTagName(tagName)[i].className == 'fieldError'){
         document.getElementsByTagName(tagName)[i].className = "";
      }
   }
}

var emailErrorCode = "";
function isValidEmail(emailToValidate) {
var errorNotFound = true;
// something found in e-mail. validate.
   if (emailToValidate != "")	{
      var emailRegEx = /^([\-\w_\.]+)@{1}([\-\w_]+)(\.\w+)+(\w$)/i;
      var result = emailToValidate.match(emailRegEx);
      if(result != null){
         if(emailToValidate.match(/(www\.)/i)!=null){
            emailErrorCode = "www_found";
            errorNotFound = false;
         }
         else {
            var illegalEmailArray = new Array ('a@a.com','b@b.com','c@c.com','d@d.com','e@e.com','f@f.com','g@g.com','h@h.com','i@i.com','j@j.com','k@k.com','l@l.com','m@m.com','n@n.com','o@o.com','p@p.com','q@q.com','r@r.com','s@s.com','t@t.com','u@u.com','v@v.com','w@w.com','x@x.com','y@y.com','z@z.com','1@1.com','2@2.com','3@3.com','4@4.com','5@5.com','6@6.com','7@7.com','8@8.com','9@9.com','0@0.com','mickey@mouse.com','mickeymouse@mickeymouse.com','me@me.com');
   			for (i=0; i < illegalEmailArray.length; i++)	{
      			if (emailToValidate == illegalEmailArray[i])	{
      				emailErrorCode = "invalid_email_address"
      				errorNotFound = false;
      			}
      		}
         }
      }
      else {
         emailErrorCode = "invalid_email_address";
         errorNotFound = false;
      }    
   }
   else {
      emailErrorCode = "invalid_email_address";
      errorNotFound = false;
   }
   return errorNotFound;
}      

