// Functions for Enrollment Form Functionality and Validation

// function for trimming white space from beginning or end of strings.
function trim(passedText){ 
	strText = new String(passedText);
	// this will get rid of leading spaces 
    while (strText.substring(0,1) == ' ') 
        strText = strText.substring(1, strText.length);

    // this will get rid of trailing spaces 
    while (strText.substring(strText.length-1,strText.length) == ' ')
        strText = strText.substring(0, strText.length-1);

   return strText;
} 


function jumpToNxtField(currentField,fieldLabel,maxLength,nextField){
	// currentField needs to be the name/id of the field you're in when calling this function.
	// fieldLabel is the text to display identifying the field where the issue is...if there's an issue.
	// maxLength is the maximum number or characters allowed before you jump to the next section of the phone number.
	// nextField needs to be the section you want to jump to if this section is at number capacity and a valid number.

	// if they have entered all numbers, and they are at the max length for this section of the phone number...
	if (currentField.value.length == maxLength){ 
		if(isNaN(currentField.value)){
			alert('Please only enter numbers into the ' + fieldLabel + ' field.');
		} else {
		nextField.focus();
		return false;
		}
	}
}

function validPhone(num){
	if (isNaN(num)){ // If they enter something that is not a number...
		var sectnMsg = ""; 
		if (frmSectn.length > 2) { sectnMsg = " in the " + frmSectn + " section" }
		alert('Please enter a number for section ' + phnNumSectn +' of the phone number' + frmSectn + '.');
		currentField.focus();		
		result = false;
	}
}


function isEmailAddr(email)
{
  var result = false;
  var theStr = new String(email);
  var index = theStr.indexOf("@");
  if (index > 0){
    var pindex = theStr.indexOf(".",index);
    if ((pindex > index+1) && (theStr.length > pindex+1))
	result = true;
  }
  return result;
}

function validRequired(formField,fieldLabel){
	var result = true;
	if (formField.value == ""){
		var sectnMsg = ""; 
		alert(fieldLabel + ' is a required field.  Please enter a value for  "' + fieldLabel + '".');
		formField.focus();
		result = false;
	}
	return result;
}

function allDigits(str){
	return inValidCharSet(str,"0123456789");
}

function inValidCharSet(str,charset){
	var result = true;

	// Note: doesn't use regular expressions to avoid early Mac browser bugs	
	for (var i=0;i<str.length;i++){
		if (charset.indexOf(str.substr(i,1))<0){
			result = false;
			break;
		}
	}
	return result;
}

function validEmail(formField,fieldLabel,required){
	var result = true;
	
	if (required && !validRequired(formField,fieldLabel)) { result = false }

	if (result && ((formField.value.length < 3) || !isEmailAddr(formField.value)) ) {
		alert("Please enter a complete email address in the form: yourname@yourdomain.com for " + fieldLabel + ".");
		formField.focus();
		result = false;
	}
  return result;
}

function validNum(formField,fieldLabel,required){
	var result = true;

	if (required && !validRequired(formField,fieldLabel)) { result = false }
  
 	if (result)	{
 		if (!allDigits(formField.value)) {
//			var sectnMsg = ""; 
//			if (frmSectn.length > 2) { sectnMsg = " in the " + frmSectn + " section" }
 			alert('The ' + fieldLabel + ' can only contain numeric characters; no letters, punctuation, or other special characters. Please correct the ' + fieldLabel + '.');
			formField.focus();		
			result = false;
		}
	} 
	return result;
}

function validInt(formField,fieldLabel,required){
	var result = true;
	var sectnMsg = ""; 
	
	if (required && !validRequired(formField,fieldLabel)) { result = false }
  
 	if (result){
 		var num = parseInt(formField.value,10);
 		if (isNaN(num)){
 			alert('Please enter a number for "' + fieldLabel + '.  All characters in this field must be numbers.');
			formField.focus();		
			result = false;
		}
	} 
	return result;
}


function validDate(formField,fieldLabel,required){
	var result = true;
	var sectnMsg = ""; 
	if (required){
		if(!validRequired(formField,fieldLabel)) { result = false }
	}
	if (result)	{
 		var elems = formField.value.split("/");
 		
 		result = (elems.length == 3); // should be three components
 		
 		if (result)	{
 			var month = parseInt(elems[0],10);
  			var day = parseInt(elems[1],10);
 			var year = parseInt(elems[2],10);
			result = allDigits(elems[0]) && (month > 0) && (month < 13) &&
					 allDigits(elems[1]) && (day > 0) && (day < 32) &&
					 allDigits(elems[2]) && ((elems[2].length == 2) || (elems[2].length == 4));
 		}
 		
  		if (!result) {
 			alert('Please enter a date in the format MM/DD/YYYY for the "' + fieldLabel +'" field.');
			formField.focus();
			result = false;
		}
	} 
	return result;
}

function validAge(formField, fieldLabel, validationType, ageLimit, chkStudent, maxStudentAge, studentChkBxFld)
 {	// Function assumes field already validated for date
	// variable validationType must be "under" for validation of "no older than x years old", or "over" to validate that the age is "at least age x"
	// variable chkStudent must be set to true or false (or 1 or 0 respectively) to indicate whether to also check if this person is a student, and to prompt if the student checkbox (studentChkBxFld) is not checked.
  var ageOK = true;
  // Create date object using birth date str
  var birthDate = new Date(formField.value);
  // Create todays dateE
  var today = new Date();
  // getTime returns date in milliseconds, so need
  // to divide by number of milliseconds in year
  var age = (today.getTime() - birthDate.getTime())  /(365*24*60*60*1000)
  if(validationType == "over"){
	   if (age < ageLimit)
	    {
			cropAgeAt = age.toString().indexOf( ".") + 3;
			displayAge = age.toString().substr(0, cropAgeAt);
			alert(fieldLabel + ' must indicate they are over age' + ageLimit + '.\n Your entry indicates they are ' + displayAge + ' years old.  Please correct.');
			ageOK = false;
			formField.focus();
	    }
		if (age > 100){
			cropAgeAt = age.toString().indexOf( ".") + 3;
			displayAge = age.toString().substr(0, cropAgeAt);
		 	alert(fieldLabel + " indicates they are " + displayAge + " years old.  \n\nFirst of all, we find this rather unlikely, and secondly, if this is true....at that age we highly doubt they still have teeth or would want a dentist poking around in their mouth with pointy instruments.\n We suspect you've made a mistake entering the birth date....please correct.");
		 	ageOK = false;
		 	formField.focus();
		}
		
	} else if (validationType == "under") {
		if (age > ageLimit)
		{
		cropAgeAt = age.toString().indexOf( ".") + 3;
  	    displayAge = age.toString().substr(0, cropAgeAt);
	   	msg = fieldLabel + " must be under age" + ageLimit + ".\n Your entry indicates they are " + displayAge + " years old.  Please correct.";
	   
	   	if((studentChkBxFld.value == "false") && (age < maxStudentAge) && (chkStudent == true)) { 	   
	   	msg += "\n PLEASE NOTE:  If this person is over " + ageLimit + " but a valid dependent due to the fact that they are a full time student, please make sure the checkbox indicating student status is checked.";
	    alert(msg);
		ageOK = false;
	   	formField.focus();
	   }
	   if(age > maxStudentAge){
	   	msg += "\n PLEASE NOTE:  This person is too old to qualify as a dependent, even if a student.  If the age you've entered is accurate, this person cannot qualify as a dependent for this plan.  Please clear this persons information before continuing with your enrollment application";
	    alert(msg);
		ageOK = false;
	   	formField.focus();
	   }	
	  }
	}

  return ageOK;
 }
 

function validSocial(formField, fieldLabel, required){
	var result = true;
	var sectnMsg = ""; 
	if (validInt(formField,fieldLabel,required)){
		if (formField.value.length != 9 ){
		  alert ('There is an error in ' + fieldLabel + '.  \n Social Security Numbers must be exactly 9 digits long and contain only numbers. \n No dashes, dots, or other non-numeric characters are allowed.');
		  formField.focus();
		  result = false;
		}
	} else { result = false }
	return result;
}

function validBnkRouting(formField, fieldLabel, required){
  var i, n, t;

  // First, remove any non-numeric characters.
  t = "";
  for (i = 0; i < formField.value.length; i++) {
    c = parseInt(formField.value.charAt(i), 10);
    if (c >= 0 && c <= 9){
      t = t + c;
     } else { 
	 	alert(fieldLabel + " can only contain numbers.  Please correct."); 
		formField.focus(); 
		return false; 
	 }
  }

  // Check the length, it should be nine digits.
  if (t.length != 9){
    alert (fieldLabel + " must be exactly nine (9) numbers long.  Please correct.");
	formField.focus();
    return false;
   }

  // Now run through each digit and calculate the total.
  n = 0;
  for (i = 0; i < t.length; i += 3) {
    n += parseInt(t.charAt(i),     10) * 3
      +  parseInt(t.charAt(i + 1), 10) * 7
      +  parseInt(t.charAt(i + 2), 10);
  }

  // If the resulting sum is an even multiple of ten (but not zero),
  // the aba routing number is good.
  if (n != 0 && n % 10 == 0){
    return true;
  } else {
	alert("According to our records, the value entered in " + fieldLabel + " is not a valid Bank Routing number.  Please correct.");
	formField.focus();
    return false;
  }
}

function validNumLen(formField, fieldLabel, required, numLen){
	var result = true;
	if (validInt(formField,fieldLabel,required)){
		if (formField.value.length != numLen ){
		  alert ('There is an error in ' + fieldLabel + '.  \n ' + fieldLabel + ' must be exactly ' + numLen + ' digits long and contain only numbers. \n No dashes, dots, or other non-numeric characters are allowed.');
		  formField.focus();
		  result = false;
		}
	} else { result = false }
	return result;
}

