formCancel = false;

function cardval(s) {
// remove non-numerics
var v = "0123456789";
var w = "";
for (i=0; i < s.length; i++) {
x = s.charAt(i);
if (v.indexOf(x,0) != -1)
w += x;
}
// validate number
j = w.length / 2;
if (j < 6.5 || j > 8 || j == 7) return false;
k = Math.floor(j);
m = Math.ceil(j) - k;
c = 0;
for (i=0; i<k; i++) {
a = w.charAt(i*2+m) * 2;
c += a > 9 ? Math.floor(a/10 + a%10) : a;
}
for (i=0; i<k+m; i++) c += w.charAt(i*2+1-m) * 1;
return (c%10 == 0);
}

function trimText(checkField,limit) {
	// if too long...trim it!
	if (!checkTextTooLong(checkField,limit)) 
	{
		checkField.value = checkField.value.substring(0, limit);
	}
}

// check if we're looking at a valid URL
function isURL(checkStr)
{
  if (checkStr.match(/^(\s)*((h|H)(t|T)(t|T)(p|P):\/\/)?([A-Za-z0-9_-]+\.)+[A-Za-z]+[A-Za-z]+(\/(.*))?(\s)*$/g) != null) {  
    return true;
  }
  return false;
}
function checkURL(checkField)
{
  if (checkField.value && !isURL(checkField.value))
  {
    alert("The '"+getFieldName(checkField)+"' field is invalid, please try again. \nIt must be a valid web address (example: www.domain.com).\n");
    checkField.focus();
    return false;
  }

  return true;
}

// check to see the given year is leap year or not
// Input: Year, 2 or 4 digit
// Output: if is a leap year, then true. Otherwise false
function isLeapYear(year)
{
	if (year < 100)
		if (year < 50)
			year = year + 2000;
		else
			year = year + 1900;
	if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0))
		return true;
	else
		return false;
}

function isAlpha(checkStr)
{
  // allow ONLY alphanumeric keys, no symbols or punctuation
  // this can be altered for any "checkOK" string you desire
  var checkOK = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ";
  for (i = 0;  i < checkStr.length;  i++)
  {
    ch = checkStr.charAt(i);
    for (j = 0;  j < checkOK.length;  j++)
	{
      if (ch == checkOK.charAt(j))
	  {
        break;
	  }
    }
    if (j == checkOK.length)
    {
      return false;
    }
  }
  return true;
}

function isNumber(checkStr)
{
  // allow ONLY alphanumeric keys, no symbols or punctuation
  // this can be altered for any "checkOK" string you desire
  var checkOK = "0123456789";
  for (i = 0;  i < checkStr.length;  i++)
  {
    ch = checkStr.charAt(i);
    for (j = 0;  j < checkOK.length;  j++)
	{
      if (ch == checkOK.charAt(j))
	  {
        break;
	  }
    }
    if (j == checkOK.length)
    {
      return false;
    }
  }
  return true;
}

function isEmail(checkStr)
{
//  if (checkStr.match(/[^@ ]+@[A-Za-z0-9_-]+.(com|org|net|biz|cc|tv|gov|mil|us)/g) != null) {
  if (checkStr.match(/[A-Za-z0-9_-]+(.[A-Za-z0-9_-])*@([A-Za-z0-9_-]+.)+[A-Za-z]+[A-Za-z]+/g) != null) {  
	
    return true
  }
  return false;
}


function isAlphanum(checkStr)
{
  // allow ONLY alphanumeric keys, no symbols or punctuation
  // this can be altered for any "checkOK" string you desire
  var checkOK = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 ";
  for (i = 0;  i < checkStr.length;  i++)
 {
    ch = checkStr.charAt(i);
    for (j = 0;  j < checkOK.length;  j++)
      if (ch == checkOK.charAt(j))
        break;
    if (j == checkOK.length)
    {
      return false;
    }
  }
  return true;
}


function isRadioButtonBlank(radioButton)
{
  // require at least one radio button be selected
  for (i = 0;  i < radioButton.length;  i++)
  {
    if (radioButton[i].checked)
        return true;
  }  
  return false;
}


function isPhone(checkStr)
{
  // remove all extraneous characters and any leading ones... then count, there should be 10 digits.
  // allow ONLY alphanumeric keys, no symbols or punctuation
  // this can be altered for any "checkOK" string you desire

  var checkOK = "0123456789";
  var checkResult = "";
  var ch = "";
  for (i = 0;  i < checkStr.length;  i++)
  {
    ch = checkStr.charAt(i);
    //eliminate leading 1 (we don't want 1-800; instead we want 800)
	if((ch == '1') && (i == 0))
	{
	  ch = '';
	}
    for (j = 0;  j < checkOK.length;  j++)
    {
      if (ch == checkOK.charAt(j))
      {
		break;
	  }
      // if we've reached the end of the acceptable strings and there is no match, then this char is invalid.
      if(j == (checkOK.length-1)){ch = '';}
    }
	checkResult += ch;
  }

  if(checkResult.length == 10)
  {
    return true;
  }
  return false;
}


function getFieldName(checkField)
{
  var fieldName = '';
  fieldName = checkField.alias;
  if(!fieldName)
  {
    fieldName = checkField.name;
  }
  return fieldName;
}

function checkAlphanum(checkField)
{
  if (checkField.value && !isAlphanum(checkField.value))
  {
    alert("Please enter only letter and numeric characters in the '"+getFieldName(checkField)+"' field.");
    checkField.focus();
    return (false);
  }
  return true;
}

function checkAge(checkField)
{
 	if(checkField.value < 13)
	{
		alert("You must be at least 13 years old to register!");
		checkField.focus();
		return false;
	}
  return true;
}


function checkBlank(checkField)
{
  // check to see if a field is blank
  if (checkField.value == "")
  {
    alert("You must enter a value for the '"+getFieldName(checkField)+"' field, please try again.");
    checkField.focus();
    return (false);
  }
  return false;
}

function checkAlpha(checkField)
{
  if (checkField.value && !isAlpha(checkField.value))
  {
    alert("Please enter only alphabetic characters for the '"+getFieldName(checkField)+"' field, please try again.");
    checkField.focus();
    return (false);
  }
  return true;
}

function checkNum(checkField)
{
  if (checkField.value && !isNumber(checkField.value))
  {
    alert("Please enter only numbers in the '"+getFieldName(checkField)+"' field.");
    checkField.focus();
    return (false);
  }
  return true;
}

function checkEmail(checkField)
{
  if (checkField.value && !isEmail(checkField.value))
  {
    alert("The '"+getFieldName(checkField)+"' field is invalid, please try again. \nIt must contain an '@' and a '.' following the '@'.");
    checkField.focus();
    return false;
  }

  return true;
}

function checkTextTooLong(checkField, n)
{
  // allow only 'n' characters maximum in the field
  if (checkField.value.length > n)
  {
    alert("Please enter at most "+n.toString()+" characters in the " + getFieldName(checkField) + " field.");
    checkField.focus();
    return (false);
  }
  return true;
}

function checkTextTooShort(checkField, n)
{
  // allow only 'n' characters maximum in the field
  if (checkField.value.length < n)
  {
    alert("Please enter at least "+n.toString()+" characters in the '"+getFieldName(checkField)+"' field.");
    checkField.focus();
    return (false);
  }
  return true;
}

function checkPhone(checkField)
{
  if (checkField.value && !isPhone(checkField.value))
  {
    alert("The '"+getFieldName(checkField)+"' field is invalid, please try again. \nIt must be in the format ###-###-####.");
    checkField.focus();
    return (false);
  }
  return true;
}

function checkSelectBox(selectBox)
{
  // check if the first drop down is selected, if so, invalid selection
  var i = selectBox.selectedIndex;
  if (selectBox.options[i].value == '')
  {
    alert("The first '"+getFieldName(selectBox)+"' option is not a valid selection.\nPlease choose one of the other options.");
    selectBox.focus();
    return (false);
  }
  return true;
}

function checkRadioButton(radioButton)
{
  if (!isRadioButtonBlank(radioButton))
  {
    alert("Please select one of the '"+getFieldName(radioButton)+"' options.");
    return (false);
  }
  return true;
}

// requires there be a theForm.required object to contain the bit flags to determine which fields are required.
function checkRequired(theForm)
{

  if (formCancel == true) {return true;}

  for (i = 0;  i < theForm.elements.length;  i++)
  {
    var formElement = theForm.elements[i];
    // this code does more work than it needs to, but its readable and simple so I chose it instead.
	// (in cases where n instances for a given name exist it can perform up to the square of n checks for that name.)
    if(theForm.required[formElement.name]){
	  if(formElement.type == "checkbox"){
        var isChecked = false;
        if(formElement.checked && formElement.value != ""){isChecked = true;}
		if(!isChecked)
		{
          alert("'"+getFieldName(formElement)+"' is a required field.\nPlease check continue.");
          formElement.focus();
          return (false);
		}
	  }else if(formElement.type == "password" && !formElement.value){
        alert("The '"+getFieldName(formElement)+"' field is a required password.\nPlease fill it out to continue.");
        formElement.focus();
        return (false);
	  }else if(formElement.type == "radio"){
        var isChecked = false;

		// if there is only one radio button lets see if its checked.
		if (theForm[formElement.name].length == undefined && formElement.checked){
          isChecked = true; break;
		}
        for (j = 0;  j < theForm[formElement.name].length;  j++)
		{
          var formRadio = theForm[formElement.name][j];
          if(formRadio.checked){isChecked = true; break;}
		}
		if(!isChecked)
		{
          alert("'"+getFieldName(formElement)+"' is a required field.\nPlease select one to continue.");
          formElement.focus();
          return (false);
		}
	  }else if(formElement.type == "select-one"){
	    var j = formElement.selectedIndex;
        if (formElement.options[j].value == '')
        {
          alert("The '"+getFieldName(formElement)+"' select-box is a required field.\nPlease choose a valid selection to continue.");
          formElement.focus();
          return (false);
        }
	  }else if(formElement.type == "select-multiple"){
	    var j = formElement.selectedIndex;
        var isChecked = false;
        if (formElement.selectedIndex == -1)
        {
          alert("The '"+getFieldName(formElement)+"' select-box is a required field.\nPlease choose a valid selection to continue.");
          formElement.focus();
          return (false);
        } else {
          for (var k = 0;  k <= formElement.length;  k++)
          {
            if(formElement.options[k].selected && formElement.options[k].value != ""){isChecked = true; break;} 
          }
          if(!isChecked)
          {
	        alert("The '"+getFieldName(formElement)+"' field is a required field.\nPlease select one or more valid selections to continue.");
	        formElement.focus();
	        return (false);
          }
		}
	  }else if(formElement.type == "text"  && !formElement.value){
        alert("The '"+getFieldName(formElement)+"' field is a required field.\nPlease fill it out to continue.");
        formElement.focus();
        return (false);
	  }else if(formElement.type == "textarea" && !formElement.value){
        alert("The '"+getFieldName(formElement)+"' field is a required field.\nPlease fill it out to continue.");
        formElement.focus();
        return (false);
	  }
	}
  }
  return true;
}

// requires there be a theForm.alias object to contain the relationships between variables and their aliases.
function setFieldAlias (theForm)
{
  for (i = 0;  i < theForm.elements.length;  i++)
  {
    var formElement = theForm.elements[i];
	if(formElement.name)
	{
      formElement.alias = theForm.alias[formElement.name];
	}
  }

  return true;
}

function checkValidChar (theForm)
{

  if (formCancel == true) {return true;}
  
  for (i = 0;  i < theForm.elements.length;  i++)
  {
    var formElement = theForm.elements[i];

    // this code does more work than it needs to, but its readable and simple so I chose it instead.
    if(((formElement.type == "password") || (formElement.type == "text") || (formElement.type == "textarea"))
      && formElement.value)
	{
	  // allow ONLY valid characters, no double quotes (or any other chars we deem bad later on)
	  // (see: checkValidChar)
	  // this can be altered for any "checkInvalid" string you desire
	  var checkInvalid = '"{}';
      formElement.invalidChar = '';
      var checkStr = formElement.value;
      var ch = '';
	  for (j = 0;  j < checkStr.length;  j++)
	  {
        ch = checkStr.charAt(j);
	    for (k = 0;  k < checkInvalid.length;  k++)
	    {
		  // double quotes are acceptable in textarea field types.
	      if (ch == '"' && formElement.type == "textarea") {continue;}

	      if (ch == checkInvalid.charAt(k))
	      {
	        formElement.invalidChar = ch;
	        break;
		  }
		}
	  }

      if(formElement.invalidChar != '')
	  {
	    alert("The '"+getFieldName(formElement)+"' field contains a "+formElement.invalidChar+", which is an invalid character.\nPlease remove it to continue.");
        formElement.focus();
        return (false);
	  }
    }
  }
  return true;
}

function checkBirthdate(checkField, limit)
{
	today = new Date();
	difference = getAgeFromDates(getDateFromField(checkField), today);
	if(difference < limit)
	{
		alert("You must be at least "+limit+" years old to register!");
		return false;
	}
	return true;
}

// this converts the birthdate to an age (in years, rounded down)
// it is not precise and errs on the side of safety, sometimes
// requiring the DOB to be a month or more before the necessary date for an age.
function getAgeFromDates(then, now)
{
	var msPerYear = (1000 * 60 * 60 * 24 * 365);
	var difference = now.getTime() - then.getTime();
	return parseInt(difference / msPerYear);
}

// alternative form of getAge -- thanks to Matt Levy for his help with this function
function getAgeFromDates2(then, now)
{
	var age = now.getYear() - then.getYear();     // Upper bound on age
	if (now.getMonth() < then.getMonth()) {       // birthday hasn't happened yet
		age--;
	} else {
		if ( (now.getMonth() == then.getMonth()) && (now.getDay() < then.getDay()) ) { // birthday is this month
			age--;
		} 
	}
	return age+1;  //punting, trying to get this to work
}


function getAgeFromDates3(dob, nowx) 
{
	// http://developer.irt.org/script/29.htm
    var now = new Date();
    var today = new Date(now.getYear(),now.getMonth(),now.getDate());

    var yearNow = now.getYear();
    var monthNow = now.getMonth();
    var dateNow = now.getDate();

    var yearDob = dob.getYear();
    var monthDob = dob.getMonth();
    var dateDob = dob.getDate();

    yearAge = yearNow - yearDob;

    if (monthNow >= monthDob)
        var monthAge = monthNow - monthDob;
    else {
        yearAge--;
        var monthAge = 12 + monthNow - monthDob;
    }

    if (dateNow >= dateDob)
        var dateAge = dateNow - dateDob;
    else {
        monthAge--;
        var dateAge = 31 + dateNow - dateDob;

        if (monthAge < 0) {
            monthAge = 11;
            yearAge--; 
        }
    }

    return yearAge + ' years ' + monthAge + ' months ' + dateAge + ' days' + '(' + today + ')';
	//return yearAge;
}

function getDateFromField(checkField){
	var date = checkField.value;
	var month = date.substring(0,2);
	var day = date.substring(3,5);
	var year = date.substring(6,10);
	return new Date(year, month, day);
}
 

// this is a stub for a function previously found in a deprecated library.
function checkBday(checkField)
{
	if (!checkBirthdate(checkField, 13)){
		window.top.close();
	}
}

// check to see if an entered date is valid
// Must contain 0 in front of single digit months and days
// Must be 4 digit year
// Input: a string
// Output: if it is a valid date, then true. Otherwise, an error message
function checkDate(checkField)
{
	if(!checkField.value)
	{
		return true;
	}
	date = checkField.value;
	var length = date.length;
	var DayoftheMonth = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
	var day, month, year;

	// check date's format
	if (!isNumber(date) && (date.charAt(2) != '/' || date.charAt(5) != '/' || length != 10))
	{
	    alert("The '"+getFieldName(checkField)+"' field format must be MM/DD/YYYY.\nPlease fix it to continue.");
        checkField.focus();
        return (false);
	}
	else if (isNumber(date) && length != 8)
	{
	    alert("The '"+getFieldName(checkField)+"' field format must be MM/DD/YYYY.\nPlease fix it to continue.");
        checkField.focus();
        return (false);
	}

	if (!isNumber(date))
	{
		month = date.substring(0,2);
		day = date.substring(3,5);
		year = date.substring(6,10);
	}
	else
	{
		month = date.substring(0,2);
		day = date.substring(2,4);
		year = date.substring(4,8);
	}

	if (!isNumber(month) || !isNumber(day) || !isNumber(year))
	{
	    alert("The '"+getFieldName(checkField)+"' field format must be MM/DD/YYYY or MMDDYYYY.\nPlease fix it to continue.");
        checkField.focus();
        return (false);
	}
	else if (month < 0 || month > 12)
	{
	    alert("The '"+getFieldName(checkField)+"' field contains an Invalid Month.\n Please fix it to continue.");
        checkField.focus();
        return (false);
	}
	else if (month == "02" && ((isLeapYear(year) && day > 29) || (!isLeapYear(year) && day > 28)))
	{
	    alert("The '"+getFieldName(checkField)+"' field contains an Invalid day for the given Month.\n Please fix it to continue.");
        checkField.focus();
        return (false);
	}
	else if (month != 2 && day > DayoftheMonth[month-1])
	{
	    alert("The '"+getFieldName(checkField)+"' field contains an Invalid Month.\n Please fix it to continue.");
        checkField.focus();
        return (false);
	}
	return true;
}