// VARIABLE DECLARATIONS
var digits = "0123456789";
var whitespace = " \t\n\r";
var digitsInSocialSecurityNumber = 9;
var mPrefix = "You did not enter a value into the "
var mSuffix = " field. This is a required field. Please enter it now."
var sSSN = "Social Security Number"
var sDateOfBirth = "Date of Birth"
var digitsInUSPhoneNumber = 10;
var phoneNumberDelimiters = "()- ";
var sEmail = "Email"

// i is an abbreviation for "invalid"

var iSSN = "This field must be a 9 digit U.S. social security number (no spaces or dashes). Please reenter it now."
var iEmail = "This field must be a valid email address (like foo@bar.com). Please reenter it now."
var iDay = "This field must be a day number between 1 and 31.  Please reenter it now."
var iMonth = "This field must be a month number between 1 and 12.  Please reenter it now."
var iYear = "This field must be a 4 digit year number.  Please reenter it now."
var iDatePrefix = "The Month, Day, and Year for "
var iDateSuffix = " do not form a valid date.  Please reenter them now."
var iStateCode = "This field must be a valid two character U.S. state abbreviation (like CA for California). Please reenter it now."
var iZIPCode = "This field must be a 5 or 9 digit U.S. ZIP Code (like 94043). Please reenter it now."
var iUSPhone = "This field must be a 10 digit U.S. phone number (like 415 555 1212). Please reenter it now."
var iWorldPhone = "This field must be a valid international phone number. Please reenter it now."

// Global variable defaultEmptyOK defines default return value 
// for many functions when they are passed the empty string. 

var defaultEmptyOK = false

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;

function formatNumber(numToFormat)
{
    var num = parseFloat(numToFormat);
    num = Math.round(num*100)/(100);
    var floatVal = (num == "") ? floatVal = 0.00 : parseFloat(num);
    if(( floatVal * 10) % 10)
    {
       if((floatVal * 1000) % 100) // means 2 or more digits after decimal
       {
        // do nothing
       }
       else             // means only 1 digit right of decimal so add second 0
       {
          num = floatVal + "0";
       }
    }
     else              // means no digits to right of decimal add .00
     {
        num = floatVal + ".00";
     }
     return num;
}


// does not depend on defaultEmptyOK
function checkRadio(e,stringToWarn)
{   
    var flag = false;
    radionumButton = e.length;
    for(var i = 0; i < radionumButton; i++)
    {
       if(e[i].checked)
       {
          flag = true;
          break;
       }
    }
    if(flag == false)
    {  alert("\nYou must select one of the options for:\n\n" + stringToWarn + "\n");
       // ie 3 doesn't support focus();    
       if(!((navigator.appName == "Microsoft Internet Explorer") &&
             (parseInt(navigator.appVersion) <=2)))
       e[0].focus();
    }   
    return flag;   
}

// Get checked value from radio button.
function getRadioButtonValue (radio)
{   for (var i = 0; i < radio.length; i++)
    {   if (radio[i].checked) { break }
    }
    if(radio[i] != null)
    {
        return radio[i].value;
    }
    else
    {
        return;
    }
}


// note this does not make use of emptyOK global.  If empty is OK don't call this
function isSelectChosen(theField, theWarningString )
{
    // change next line to just <0  if using selects where 0 element
    // is considered a valid answer
    
    if(theField.selectedIndex <= 0)
    {
        alert("\nYou must select a value for " + theWarningString + "\n");
        if(!((navigator.appName == "Microsoft Internet Explorer") && 
             (parseInt(navigator.appVersion) <=2)))
             theField.focus();  // ie 4 doesn't support select() 
                                // ie 3 doesn't support focus();
        return false;
    }
    return true;
}

// isUSPhoneNumber (STRING s [, BOOLEAN emptyOK])
// 
// isUSPhoneNumber returns true if string s is a valid U.S. Phone
// Number.  Must be 10 digits.
//
// NOTE: Strip out any delimiters (spaces, hyphens, parentheses, etc.)
// from string s before calling this function.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

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)

}

// takes USPhone, a string of 10 digits
// and reformats as (123) 456-789

function reformatUSPhone (USPhone)
{   return (reformat (USPhone, "(", 3, ") ", 3, "-", 4))
}

// checkUSPhone (TEXTFIELD theField [, BOOLEAN emptyOK==false])
//
// Check that string theField.value is a valid US Phone.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

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-789, comment next line out
          theField.value = reformatUSPhone(normalizedPhone)
          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++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }

    return returnString;
}

// Removes all characters which do NOT appear in string bag 
// from string s.

function stripCharsNotInBag (s, bag)

{   var i;
    var returnString = "";

    // Search through string's characters one by one.
    // If character is in bag, append to returnString.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) != -1) returnString += c;
    }

    return returnString;
}


// isInteger (STRING s [, BOOLEAN emptyOK])
// 
// Returns true if all characters in string s are numbers.
//
// Accepts non-signed integers only. Does not accept floating 
// point, exponential notation, etc.
//
// We don't use parseInt because that would accept a string
// with trailing non-numeric characters.
//
// By default, returns defaultEmptyOK if s is empty.
// There is an optional second argument called emptyOK.
// emptyOK is used to override for a single function call
//      the default behavior which is specified globally by
//      defaultEmptyOK.
// If emptyOK is false (or any value other than true), 
//      the function will return false if s is empty.
// If emptyOK is true, the function will return true if s is empty.
//
// EXAMPLE FUNCTION CALL:     RESULT:
// isInteger ("5")            true 
// isInteger ("")             defaultEmptyOK
// isInteger ("-5")           false
// isInteger ("", true)       true
// isInteger ("", false)      false
// isInteger ("5", false)     true

function isInteger (s)

{   var i;

    if (isEmpty(s)) 
       if (isInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isInteger.arguments[1] == true);

    // Search through string's characters one by one
    // until we find a non-numeric character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);

        if (!isDigit(c)) return false;
    }

    // All characters are numbers.
    return true;
}

function isDigit (c)
{   return ((c >= "0") && (c <= "9"))
}

// reformat (TARGETSTRING, STRING, INTEGER, STRING, INTEGER ... )       
//
// Handy function for arbitrarily inserting formatting characters
// or delimiters of various kinds within TARGETSTRING.
//
// reformat takes one named argument, a string s, and any number
// of other arguments.  The other arguments must be integers or
// strings.  These other arguments specify how string s is to be
// reformatted and how and where other strings are to be inserted
// into it.
//
// reformat processes the other arguments in order one by one.
// * If the argument is an integer, reformat appends that number 
//   of sequential characters from s to the resultString.
// * If the argument is a string, reformat appends the string
//   to the resultString.
//
// NOTE: The first argument after TARGETSTRING must be a string.
// (It can be empty.)  The second argument must be an integer.
// Thereafter, integers and strings must alternate.  This is to
// provide backward compatibility to Navigator 2.0.2 JavaScript
// by avoiding use of the typeof operator.
//
// It is the caller's responsibility to make sure that we do not
// try to copy more characters from s than s.length.
//
// EXAMPLES:
//
// * To reformat a 10-digit U.S. phone number from "1234567890"
//   to "(123) 456-7890" make this function call:
//   reformat("1234567890", "(", 3, ") ", 3, "-", 4)
//
// * To reformat a 9-digit U.S. Social Security number from
//   "123456789" to "123-45-6789" make this function call:
//   reformat("123456789", "", 3, "-", 2, "-", 4)
//
// HINT:
//
// If you have a string which is already delimited in one way
// (example: a phone number delimited with spaces as "123 456 7890")
// and you want to delimit it in another way using function reformat,
// call function stripCharsNotInBag to remove the unwanted 
// characters, THEN call function reformat to delimit as desired.
//
// EXAMPLE:
//
// reformat (stripCharsNotInBag ("123 456 7890", digits),
//           "(", 3, ") ", 3, "-", 4)

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;
}


// checkEmail (TEXTFIELD theField [, BOOLEAN emptyOK==false])
//
// Check that string theField.value is a valid Email.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function checkEmail (theField, emptyOK)
{   
	if (checkEmail.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    else if (!isEmail(theField.value, false)) 
       return warnInvalid (theField, iEmail);
    else return true;
}

function isEmail (s)
{   if (isEmpty(s)) 
       if (isEmail.arguments.length == 1) return defaultEmptyOK;
       else return (isEmail.arguments[1] == true);
   
    if (isWhitespace(s)) return false;
    
    // there must be >= 1 character before @, so we
    // start looking at character position 1 
    // (i.e. second character)
    var i = 1;
    var sLength = s.length;
    
    // do some preliminary checks for @. or ..  .@ or ending on .
    if(s.indexOf("@.") >= 0  || s.indexOf("..") >= 0  ||  s.charAt(sLength - 1) == "." )
        return false;
    
    // look for @
    while ((i < sLength) && (s.charAt(i) != "@"))
    { i++
    }

    if ((i >= sLength) || (s.charAt(i) != "@")) return false;
         else i += 2;
    
    // look for .'s
    while ((i < sLength) && (s.charAt(i) != "."))
    { i++
    }  
    // there must be at least one character after the .
    if (i >= sLength - 1) return false;
    else return true;
}

// isSSN (STRING s [, BOOLEAN emptyOK])
// NOTE: Strip out any delimiters (spaces, hyphens, etc.)
// from string s before calling this function.

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)
}

// isYear (STRING s [, BOOLEAN emptyOK])
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 == 4);
}

// isMonth (STRING s [, BOOLEAN emptyOK])

function isMonth (s)
{   var tempStr;   
    if (isEmpty(s)) 
       if (isMonth.arguments.length == 1) return defaultEmptyOK;
       else return (isMonth.arguments[1] == true);
    // LAW added next if/else so could allow leading zeros and still use isIntegerinRange call    
    if(s.length == 2 && s.substring(0,1) == '0')
       tempStr = s.substring(1,2);
    else 
       tempStr = s;   
    return isIntegerInRange (tempStr, 1, 12);
}

// isDay (STRING s [, BOOLEAN emptyOK])
// 
// isDay returns true if string s is a valid 
// day number between 1 and 31.

function isDay (s)
{   var tempStr;
    if (isEmpty(s)) 
       if (isDay.arguments.length == 1) return defaultEmptyOK;
       else return (isDay.arguments[1] == true);   
    if(s.length == 2 && s.substring(0,1) == '0')  
       tempStr = s.substring(1,2);  
    else
       tempStr = s;   
    return isIntegerInRange (tempStr, 1, 31);
}

function daysInFebruary (year)
{   return (  ((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0) ) ) ? 29 : 28 );
}

// isDate (STRING year, STRING month, STRING day)
//
// isDate returns true if string arguments year, month, and day 
// form a valid date.

function isDate (year, month, day)
{   // catch invalid years (not 2- or 4-digit) and invalid months and days.
    if (! (isYear(year, false) && isMonth(month, false) && isDay(day, false))) return false;

    // Explicitly change type to integer to make code work in both
    // JavaScript 1.1 and JavaScript 1.2.
    var intYear = parseInt(year);
    var intMonth = parseInt(month);
    var intDay = parseInt(day);

    // catch invalid days, except for February
    if (intDay > daysInMonth[intMonth]) return false; 

    if ((intMonth == 2) && (intDay > daysInFebruary(intYear))) return false;

    return true;
}

/* FUNCTIONS TO NOTIFY USER OF INPUT REQUIREMENTS OR MISTAKES. */

// Notify user that required field theField is empty.
// String s describes expected contents of theField.value.

function warnEmpty (theField, s)
{   theField.focus()
    alert(mPrefix + s + mSuffix)
    return false
}

// Notify user that contents of field theField are invalid.
// String s describes expected contents of theField.value.

function warnInvalid (theField, s)
{   theField.focus()
    //theField.select()
    alert(s)
    return false
}

/* FUNCTIONS TO INTERACTIVELY CHECK VARIOUS FIELDS. */

// Check that string theField.value is a valid SSN.

function checkSSN (theField, emptyOK)
{   if (checkSSN.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    else
    {  
       if (!isSSN(theField.value, false)) 
          return warnInvalid (theField, iSSN);
       else 
          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;
}


// isNonnegativeInteger (STRING s [, BOOLEAN emptyOK])
// 
// Returns true if string s is an integer >= 0.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isNonnegativeInteger (s)
{   var secondArg = defaultEmptyOK;

    if (isNonnegativeInteger.arguments.length > 1)
        secondArg = isNonnegativeInteger.arguments[1];

    // The next line is a bit byzantine.  What it means is:
    // a) s must be a signed integer, AND
    // b) one of the following must be true:
    //    i)  s is empty and we are supposed to return true for
    //        empty strings
    //    ii) this is a number >= 0

    return (isSignedInteger(s, secondArg)
         && ( (isEmpty(s) && secondArg)  || (parseInt (s) >= 0) ) );
}


// isSignedInteger (STRING s [, BOOLEAN emptyOK])

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 isWhitespace (s)
{   var i;
    // Is s empty?
    if (isEmpty(s)) return true;
    // Search through string's characters one by one
    // until we find a non-whitespace character.
    // When we do, return false; if we don't, return true.
    for (i = 0; i < s.length; i++)
    {
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (whitespace.indexOf(c) == -1) return false;
    }
    // All characters are whitespace.
    return true;
}

function isBlank(s)
{
        for(var i = 0; i < s.length; i++)
        {
                var c = s.charAt(i);
                if (c!= ' ')
                        return false;
        }
        return true;
}

function isEmpty(s)
{   return ((s == null) || (s.length == 0))
}

function toggleDiv() 
{
	var val;
	var f = document.inquiryForm;
	for (var i = 0; i < f.degree.length; i++) {
		//alert("value = "+f.degree[i].value);
		if( f.degree[i].checked ) {
			//alert(f.degree[i].value+" checked");
			var action = '';
			if(document.all)
				action = 'block';
			else action = 'table-row';
			document.getElementById(f.degree[i].value).style.display=action;
		}
		else {
			document.getElementById(f.degree[i].value).style.display='none';
		}
	}
}
function requiredText(text_array){
	regex = / /g;

	for (var i=0; i < text_array.length; i++){
		var textObj = text_array[i][0];
		var textText = text_array[i][1];
		
		if (textObj.value.replace(regex,'') == ''){
			window.alert("Please fill in the field '" + textText + "'");
			textObj.focus();
			return false;
		} 
	} //end for
	
	return true;

} //end requireText()

function grad_app_verify(f)
{
  
   if(!checkString(f.firstName, "First Name")) 
      return false;
   
   if(!checkString(f.lastName, "Last Name")) 
      return false;

   if(!checkString(f.address, "Street Address")) 
      return false;

   if(!checkString(f.city, "City")) 
      return false;

   if(!isSelectChosen(f.state, "State")) 
      return false;

   if(!checkString(f.zip, "Zip")) 
      return false;

   if(!checkSSN(f.ssn))
      return false;

   if(!checkEmail(f.email)) 
      return false;

   if(!checkString(f.base, "Military base")) 
      return false;

   if(!isSelectChosen(f.gradMonth, "Month you plan to graduate"))
      return false;
      
   if(!isSelectChosen(f.gradYear, "Year you plan to graduate"))
      return false;

   if(!isSelectChosen(f.degree, "Degree"))
      return false;

   if(!isSelectChosen(f.majorPrimary, "Major"))
      return false;
      
   if (!checkRadio(f.attendCommencement,"Do you plan to attend Franklin University's commencement?"))
      return false;

   if(getRadioButtonValue(f.attendCommencement) == "Yes")
   {   

       if(!isSelectChosen(f.heightFeet, "Height - feet"))
          return false;
      
       if(!isSelectChosen(f.heightInches, "Height - inches"))
          return false;

       if(!checkString(f.weight, "Weight")) 
          return false;
   }

  return true;
  
}  // end of grad_app_verify
		
function inquiry_verify(f) 
{

   if(!checkString(f.firstName, "First Name")) 
      return false;

   if(!checkString(f.lastName, "Last Name")) 
      return false;

   if(!checkEmail(f.email)) 
      return false;

   if(!checkString(f.address, "Address")) 
      return false;

   if(!checkString(f.city, "City")) 
      return false;

   if(!isSelectChosen(f.state, "State")) 
      return false;

   if(!checkString(f.zip, "Zip")) 
      return false;

   if(isWhitespace(f.phone.value))
   {
   		alert("Please enter a phone number.");
   		f.phone.focus();
		return false;
   } 
   if(!checkUSPhone(f.phone, true))
      return false;
      
	return true;
} // end of inquiry_verify

function lit_req_verify(f) 
{

   if(!checkString(f.center, "Installation/Education Center")) 
      return false;

   if(!checkString(f.firstName, "First Name")) 
      return false;

   if(!checkString(f.lastName, "Last Name")) 
      return false;

   if(!checkString(f.address, "Address")) 
      return false;

   if(!checkString(f.city, "City")) 
      return false;

   if(!isSelectChosen(f.state, "State")) 
      return false;

   if(!checkString(f.zip, "Zip")) 
      return false;

   if(isWhitespace(f.phone.value))
   {
   		alert("Please enter a phone number.");
   		f.phone.focus();
		return false;
   } 
   if(!checkUSPhone(f.phone, true))
      return false;
      
   if(!checkEmail(f.email)) 
      return false;

	return true;
}
