
var digits = "0123456789";

var lowercaseLetters = "abcdefghijklmnopqrstuvwxyz"

var uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

var alphanums = lowercaseLetters + uppercaseLetters + digits

var mPrefix = "You did not enter a value into the "
var mSuffix = " field. This is a required field. Please enter it now."
var mZeroPlayers = "You need to add at least one online or one offline player in order to create a team."

var whitespace = " \t\n\r";

var digitsInZIPCode1 = 5
var digitsInZIPCode2 = 9

var iZIPCode = "This field must be a 5 or 9 digit U.S. ZIP Code (like 94043). Please re-enter it now."
var iEmail = "This field must be a valid email address (like myname@myhost.com). Please re-enter it now."

var defaultEmptyOK = false

function makeArray(n) {
  //*** BUG: If I put this line in, I get two error messages:
  //(1) Window.length can't be set by assignment
  //(2) daysInMonth has no property indexed by 4
  //If I leave it out, the code works fine.
  //   this.length = 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;

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 isMonth (s)
{   s = stripLeadZero(s); 
 if (isEmpty(s)) 
   if (isMonth.arguments.length == 1) return defaultEmptyOK;
   else return (isMonth.arguments[1] == true);
 return ((s>0)&&(s<13));
}
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 isDay (s)
{   s = stripLeadZero(s);
 if (isEmpty(s)) 
   if (isDay.arguments.length == 1) return defaultEmptyOK;
   else return (isDay.arguments[1] == true);   
 return isIntegerInRange (s, 1, 31);
}
function isIntegerInRange (s, a, b)
{   if (isEmpty(s)) 
  if (isIntegerInRange.arguments.length == 1) return defaultEmptyOK;
  else return (isIntegerInRange.arguments[1] == true);

// Catch non-integer strings to avoid creating a NaN below,
// which isn't available on JavaScript 1.0 for Windows.
 if (!isInteger(s, false)) return false;

 // Now, explicitly change the type to integer via parseInt
 // so that the comparison code below will work both on 
 // JavaScript 1.2 (which typechecks in equality comparisons)
 // and JavaScript 1.1 and before (which doesn't).
 var num = parseInt (s);
 return ((num >= a) && (num <= b));
}
// Check whether string s is empty.

function isEmpty(s)
{   return ((s == null) || (s.length == 0))
      }
// Returns true if string s is empty or 
// whitespace characters only.

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 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 whitespace characters from s.
// Global variable whitespace (see above)
// defines which characters are considered whitespace.

function stripWhitespace (s)

{   return stripCharsInBag (s, whitespace)
      }

// Returns true if character c is an English letter 
// (A .. Z, a..z).
//
// NOTE: Need i18n version to support European characters.
// This could be tricky due to different character
// sets and orderings for various languages and platforms.

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



// Returns true if character c is a digit 
// (0 .. 9).

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



// Returns true if character c is a letter or digit.

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

 // 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 isPositiveInteger (s)
{   var secondArg = defaultEmptyOK;

 if (isPositiveInteger.arguments.length > 1)
   secondArg = isPositiveInteger.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 positive, not negative, number

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

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

// isAlphabetic (STRING s [, BOOLEAN emptyOK])
// 
// Returns true if string s is English letters 
// (A .. Z, a..z) only.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.
//
// NOTE: Need i18n version to support European characters.
// This could be tricky due to different character
// sets and orderings for various languages and platforms.

function isAlphabetic (s)

{   var i;

 if (isEmpty(s)) 
   if (isAlphabetic.arguments.length == 1) return defaultEmptyOK;
   else return (isAlphabetic.arguments[1] == true);

 // Search through string's characters one by one
 // until we find a non-alphabetic character.
 // When we do, return false; if we don't, return 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;
}




// isAlphanumeric (STRING s [, BOOLEAN emptyOK])
// 
// Returns true if string s is English letters 
// (A .. Z, a..z) and numbers only.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.
//
// NOTE: Need i18n version to support European characters.
// This could be tricky due to different character
// sets and orderings for various languages and platforms.

function isAlphanumeric (s)

{   var i;

 if (isEmpty(s)) 
   if (isAlphanumeric.arguments.length == 1) return defaultEmptyOK;
   else return (isAlphanumeric.arguments[1] == true);

 // Search through string's characters one by one
 // until we find a non-alphanumeric 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 or letter.
     var c = s.charAt(i);

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

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

// isEmail (STRING s [, BOOLEAN emptyOK])
// 
// Email address must be of form a@b.c -- in other words:
// * there must be at least one character before the @
// * there must be at least one character before and after the .
// * the characters @ and . are both required
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isEmail (s)
{   if (isEmpty(s)) 
  if (isEmail.arguments.length == 1) return defaultEmptyOK;
  else return (isEmail.arguments[1] == true);
   
// is s whitespace?
 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;

 // look for @
 while ((i < sLength) && (s.charAt(i) != "@"))
   { i++
       }

 if ((i >= sLength) || (s.charAt(i) != "@")) return false;
 else i += 2;

 // look for .
 while ((i < sLength) && (s.charAt(i) != "."))
   { i++
       }

 // there must be at least one character after the .
 if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
 else return true;
}
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));
}

// Notify user that required field theField is empty.
// String s describes expected contents of theField.value.
// Put focus in theField and return false.

function warnEmpty (theField, s)
{   theField.focus()
      alert(mPrefix + s + mSuffix)
      return false
}
function warnEmptyA (theField, s)
{   theField.focus()
      alert(mZeroPlayers)
      return false
}
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))
     }
}
// 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) && isMonth(month) && isDay(day))) 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;
}

// Notify user that contents of field theField are invalid.
// String s describes expected contents of theField.value.
// Put select theField, pu focus in it, and return false.

function warnInvalid (theField, s)
{   theField.focus()
      theField.select()
      alert(s)
      return false
      }
function getRadioButtonValue (radio)
{   for (var i = 0; i < radio.length; i++)
  {   if (radio[i].checked) { break }
  }
 return radio[i].value
   }
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 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 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 checkStringA (theField, s, emptyOK)
{   // Next line is needed on NN3 to avoid "undefined is not a number" error
    // in equality comparison below.
  if (checkStringA.arguments.length == 2) emptyOK = defaultEmptyOK;
  if ((emptyOK == true) && (isEmpty(theField.value))) return true;
  if (isWhitespace(theField.value)) 
    return warnEmptyA (theField, s);
  else return true;
}
function checkUserid(theField, s)
{
  theField.value = stripWhitespace(theField.value);

  if(isWhitespace(theField.value)){
    return warnEmpty(theField,s);
  } else if (!isAlphanumeric(theField.value) || (theField.value.length < 5) || (theField.value.length > 16)){
    return warnInvalid(theField, "Username must be between 5 and 16 alphanumeric characters long");
  } else return true;
}
function checkTeamName(theField,s){

  if(isWhitespace(theField.value)){
    return warnEmpty(theField,s);
  } else if (theField.value.length > 16){
    return warnInvalid(theField, "Please change your team name.  Your team name is limited to 16 characters or spaces.");
  } else return true;
}

function checkLeagueName(theField,s){

  if(isWhitespace(theField.value)){
    return warnEmpty(theField,s);
  } else if (theField.value.length > 16){
    return warnInvalid(theField, "Please change your league name.  Your league name is limited to 16 characters or spaces.");
  } else return true;
}
function checkLeaderName(theField,s){

  if(isWhitespace(theField.value)){
    return warnEmpty(theField,s);
  } else if (theField.value.length > 16){
    return warnInvalid(theField, "Please change your leader name.  Your leader name is limited to 16 characters or spaces.");
  } else return true;
}
function checkOrganization(theField,s){

  if(isWhitespace(theField.value)){
    return warnEmpty(theField,s);
  } else if (theField.value.length > 64){
    return warnInvalid(theField, "Please change your organization name.  Your organization name is limited to 64 characters or spaces.");
  } else return true;
}
function checkCaptainName(theField,s){

  if(isWhitespace(theField.value)){
    return warnEmpty(theField,s);
  } else if (theField.value.length > 16){
    return warnInvalid(theField, "Please change your captain name.  Your captain name is limited to 16 characters or spaces.");
  } else return true;
}

function checkPassword(field1, field2, s1, s2){
  field1.value = stripWhitespace(field1.value);
  field2.value = stripWhitespace(field2.value);
   
  if(isWhitespace(field1.value)){
    return warnEmpty(field1,s1);
  } else if((field1.value.length < 6 ) || (field1.value.length > 32)){
    return warnInvalid(field1, "Your password must be between 6 and 32 characters long");
  } else if(isWhitespace(field2.value)){
    return warnEmpty(field2,s2);
  } else if((field1.value!=field2.value)) {
    field2.value = "";
    return warnInvalid(field1, "Passwords do not match");
  }
  else return true;
}

function checkTwoEmails(field1, field2){
  if(!isValidEmail(field1.value)){
    return warnInvalid(field1, iEmail);
  } else if(field1.value!=field2.value){
    return warnInvalid(field2, "E-mail addresses do not match");
  } else return true;
}
function checkSelection(field1, initVal, s){
  if(field1.value == initVal){
    field1.focus()
      alert("You must select a(n) " + s)
      return false;
  }
  return true;
}

function checkIntegerInRange(theField, min, max, s, emptyOK){
  if (checkIntegerInRange.arguments.length == 4) emptyOK = defaultEmptyOK;
  if ((emptyOK == true) && (isEmpty(theField.value))) return true;
  if((!isInteger(theField.value))||(theField.value < min) || (theField.value > max)){
    return warnInvalid(theField, "You must enter a whole number between " + min + " and " + max + " for the " + s + " field.");
  }
  else return true;
}
function checkRadioSelected(theField, s){
  var hasValue = false;
  for(var i=0;i<theField.length;i++){
    if (theField[i].checked) {
      hasValue = true;
      break;
    }
  } 
  if(hasValue) return true;
  else alert(s);
  return false;
}

function validateEmail(strEmail){
  var arrEmail = strEmail.split(/\,|\n/);
  for(i=0;i<arrEmail.length;i++){
    if(!isEmpty(arrEmail[i]) && !isValidEmail(arrEmail[i])) {
      alert(arrEmail[i] + " is not a valid email address. Please correct and resubmit!");
      return false;
    }
  }
  return true;
}

function checkTeamDate(theField, s) {
  var dateArr = theField.value.split('/');

  if(dateArr.length!=3){
    return warnInvalid(theField, "Invalid date entered, dates must be entered as (mm/dd/yy)");
  }
  if(!isDate("20" + dateArr[2],dateArr[0],dateArr[1])){
    return warnInvalid(theField, "Invalid date entered, please correct and resubmit");
  }
  var millisInDay = 24*60*60*1000;
	
  var today = new Date();
  var submittedDate = new Date("20"+dateArr[2],dateArr[0]-1,dateArr[1]);
  submittedDate.setHours(22);
  subMillis = today.getTime();
  var minDate = new Date(subMillis + millisInDay);
  minDate.setHours(0);
  minDate.setMinutes(0);
  minDate.setSeconds(0);
  if(submittedDate.getTime()<minDate.getTime()){
    return warnInvalid(theField, "Invalid date entered - date has to be tomorrow or later");
  }
	
  return true;
}
function isValidEmail(str){
  var regex = /^([a-zA-Z0-9_\-\'])+(\.([a-zA-Z0-9_\-\'])+)*@((\[(((([0-1])?([0-9])?[0-9])|(2[0-4][0-9])|(2[0-5][0-5])))\.(((([0-1])?([0-9])?[0-9])|(2[0-4][0-9])|(2[0-5][0-5])))\.(((([0-1])?([0-9])?[0-9])|(2[0-4][0-9])|(2[0-5][0-5])))\.(((([0-1])?([0-9])?[0-9])|(2[0-4][0-9])|(2[0-5][0-5]))\]))|((([a-zA-Z0-9])+(([\-])+([a-zA-Z0-9])+)*\.)+([a-zA-Z])+(([\-])+([a-zA-Z0-9])+)*))$/;
  trim(str).search(regex)
    return ((trim(str).search(regex)) == 0);

}
function checkZIPCode (theField, emptyOK)
{   var z = trim(theField.value);
	var regex = /^(\d\d\d\d\d)(-\d\d\d\d)?$/;
 if(z.match(regex)){
   return true;
 } 
 return warnInvalid (theField, "Invalid zip code entered - please enter a valid 5 digit zip code");
}
function checkBMI(feet, inches, newWeight){
  var height = (parseInt(feet) * 12) + parseInt(inches);
  var newBMI = (parseInt(newWeight) * 704.5)/(parseInt(height)*parseInt(height));
  if(newBMI < 19){
    return false;
  } 
  return true;
}
function checkGender(theField){
  var genderSelected = false;
  for(var i=0;i<theField.length;i++){
    if(theField[i].checked){
      genderSelected = true;
    }
  }
  if(!genderSelected){
    alert("Please select your gender");
  }
  return genderSelected;
}
function trim(str)
{
  return str.replace(/^\s*|\s*$/g,"");
}
function stripLeadZero(s){
  return s.replace(/^0/g,"");
}
	

