//////////////////////////////////////////////////////////////////////////////
//
//		This file does the error checking for our form.  The error checks aren't
// 	too in depth simply because we aren't "storing" any of this data in a
//	database.  We simply want to make sure that the data is presentable i.e.
//  not have a1/4r/w343 for a date.
//
//	Coded by Jeff Speed
//	
//	Some functions (validations) were pulled from various websites with the 
//	belief that they are in the public domain.
//
//////////////////////////////////////////////////////////////////////////////

// These are the global variables to handle our error message
var errored_fields = new Array();
var error_msg = "";
var error_ind = false;
var error_count = 0;


//////////////////////////////////////////////////////////////////////////////
//
//	This is the main function of the javascript file.  It calls all of the 
//  support functions in proper order.  It then will call the function to
//  print any error messages if necessary otherwise it returns a value of 
//  true.  A value of true means that all the data in the form is as we 
//  expected.
//
//////////////////////////////////////////////////////////////////////////////
function validate_content(){
	
	Errored_fields = getElementbyClass(' error');
	if (errored_fields.length > 0){remove_error_class(' error');}
	
	validate_donor();			
	validate_funding(); 
	validate_scholarship();	
	validate_mechanics(); 
	validate_modifications();	 
	if (error_ind == false) {validate_verify();}
	
	if (error_ind) { print_error('errormsg',error_msg); return false; }
	else return true;
}


//////////////////////////////////////////////////////////////////////////////
//
//	This is function will validate all the required fields in the Donor 
//  Identification section of the form.
//
//////////////////////////////////////////////////////////////////////////////
function validate_donor(){
	
	var first_val = '', last_val = '', dayphone_val = '', addr_val = '', city_val = '', state_val = '', zip_val = '';
	
	// get the values of the fields
	first_val = document.getElementById('sFirstname').value;
	last_val = document.getElementById('sLastname').value;
	dayphone_val = document.getElementById('sDayphone1').value + "-" + document.getElementById('sDayphone2').value + "-" + document.getElementById('sDayphone3').value;
	addr_val = document.getElementById('sAddress1').value;
	city_val = document.getElementById('sCity').value;
	state_val = document.getElementById('sState').value;
	zip_val = document.getElementById('sPostcode').value;
	
	// error check the fields
		if (first_val.length == 0){
			errored_fields[error_count] = 'sFirstnamediv';
			error_count++;
			error_msg += "Please tell us your first name.\n<br>\n";
			error_ind = true;
		}
		if (last_val.length == 0){
			errored_fields[error_count] = 'sLastnamediv';
			error_count++;
			error_msg += "Please tell us your last name.\n<br>\n";
			error_ind = true;
		}
		if (validate_phone(dayphone_val) == null){
			errored_fields[error_count] = 'sDayphonediv';
			error_count++;
			error_msg += "Invalid phone number. Please enter the phone number where you can be reached during the day.\n<br>\n";
			error_ind = true;
		}		
		if (addr_val.length == 0){
			errored_fields[error_count] = 'sAddress1div';
			error_count++;
			error_msg += "Please tell us your address.\n<br>\n";
			error_ind = true;
		}
		if (city_val.length == 0){
			errored_fields[error_count] = 'sCitydiv';
			error_count++;
			error_msg += "Please tell us the city where you are located.\n<br>\n";
			error_ind = true;
		}
		if (validate_state(state_val) == null){
			errored_fields[error_count] = 'sStatediv';
			error_count++;
			error_msg += "Invalid State. Please enter the state abbreviation for the state where you live.\n<br>\n";
			error_ind = true;
		}			
	  var tempzipmsg = validateZIP(zip_val);
		if (tempzipmsg != ""){
				errored_fields[error_count] = 'sPostcodediv';
				error_count++;
				error_msg += "Donor Identification. " + tempzipmsg + "\n<br>\n";
				error_ind = true;
			}
}



//////////////////////////////////////////////////////////////////////////////
//
//	This is function will validate all the required fields in the Funding
//  Details section of the form.
//
//////////////////////////////////////////////////////////////////////////////
function validate_funding(){
	
	var fundtype_val = '', fundamt_val = '';
	
	// get values
	fundamt_val = document.getElementById('sFundAmount').value;
	for (i=0;i<document.forms['devfou'].bFund.length;i++)
	{
		if (document.forms['devfou'].bFund[i].checked) {	fundtype_val = document.forms['devfou'].bFund[i].value; }
	}
	
	// error check

	if (fundtype_val == ''){
			errored_fields[error_count] = 'bFunddiv';
			error_count++;
			error_msg += "Please tell us how you intend to fund the scholarship.\n<br>\n";
			error_ind = true;
	}
	if (fundamt_val.length == 0){
			errored_fields[error_count] = 'sFundAmountdiv';
			error_count++;
			error_msg += "Please tell us the dollar amount used to fund the scholarship.\n<br>\n";
			error_ind = true;
	}
}


//////////////////////////////////////////////////////////////////////////////
//
//	This is function will validate all the required fields in the Scholarship
//	Details section.
//
//////////////////////////////////////////////////////////////////////////////
function validate_scholarship(){
	
	var title_val = '', amount_val = '', method_val = '';
	
	// get values
	title_val = document.getElementById('sScholarname').value;
	amount_val = document.getElementById('sAmount').value;
	for (i=0;i<document.forms['devfou'].bPay.length;i++)
	{
		if (document.forms['devfou'].bPay[i].checked) {	method_val = document.forms['devfou'].bPay[i].value; }
	}
	
	
	// error check
	if (title_val.length == 0){
			errored_fields[error_count] = 'sScholarnamediv';
			error_count++;
			error_msg += "Please tell us the name of the scholarship.\n<br>\n";
			error_ind = true;
		}
	if (amount_val.length == 0){
			errored_fields[error_count] = 'sAmountdiv';
			error_count++;
			error_msg += "Please tell us the amount of money the scholarship will award.\n<br>\n";
			error_ind = true;
		}		
	if (method_val == ''){
			errored_fields[error_count] = 'bPaydiv';
			error_count++;
			error_msg += "Please tell us the method of payment the scholarship will use.\n<br>\n";
			error_ind = true;
	}

}


//////////////////////////////////////////////////////////////////////////////
//
//	This is function will validate all the required fields in the Mechanics
//	section.
//
//////////////////////////////////////////////////////////////////////////////
function validate_mechanics(){
	
	var criteria_val = '', retain_val = '', balance_val = '';
	
	
	// get values
	criteria_val = document.getElementById('scriteria').value;
	retain_val = document.getElementById('sretain').value;
	
	for (i=0;i<document.forms['devfou'].bRemain.length;i++)
	{
		if (document.forms['devfou'].bRemain[i].checked) {	balance_val = document.forms['devfou'].bRemain[i].value; }
	}
	
	
	// error check
	if (criteria_val.length == 0){
			errored_fields[error_count] = 'scriteriadiv';
			error_count++;
			error_msg += "Please tell us the criteria for the scholarship.\n<br>\n";
			error_ind = true;
		}
	if (retain_val.length == 0){
			errored_fields[error_count] = 'sretaindiv';
			error_count++;
			error_msg += "Please tell us the retaining conditions for the scholarship.\n<br>\n";
			error_ind = true;
		}
	if (balance_val.length == 0){
			errored_fields[error_count] = 'bRemaindiv';
			error_count++;
			error_msg += "Please tell us how you would like any remaining balance handled.\n<br>\n";
			error_ind = true;
		}		

}


//////////////////////////////////////////////////////////////////////////////
//
//	This is function will validate all the required field in the Modifications
//	section.
//
//////////////////////////////////////////////////////////////////////////////
function validate_modifications(){
	
	var checked_val;
	
	//get values
	checked_val = document.getElementById('bMod').checked;

	
	// error check
			if (!checked_val){
						errored_fields[error_count] = 'bModdiv';
						error_count++;
						error_msg += "Please tell us if you have read and agree with our modification policy.\n<br>\n";
						error_ind = true;
					}	
					

}



//////////////////////////////////////////////////////////////////////////////
//
//	This is function will validate all the required fields in the Donor 
//	Verification section.
//
//////////////////////////////////////////////////////////////////////////////
function validate_verify(){
	
	var initial_val = '', vdob_val = '';
	var first_val = document.getElementById('sFirstname').value;
	var last_val = document.getElementById('sLastname').value;
	var middle_val = document.getElementById('smiddlename').value;
	
	// get form values
	initial_val = document.getElementById('sVerifyInitials').value;
	for (i=0;i<document.forms['devfou'].nVDobmonth.length;i++)
	{
		if (document.forms['devfou'].nVDobmonth[i].selected) {	vdob_val = document.forms['devfou'].nVDobmonth[i].value; }
	}
	vdob_val += "/" + document.getElementById('nVDobday').value + "/" + document.getElementById('nVDobyear').value;
	
	// error check
	if (initial_val.length == 0){
						errored_fields[error_count] = 'sVerifyInitialsdiv';
						error_count++;
						error_msg += "Please enter your initials as a form of signature.\n<br>\n";
						error_ind = true;
					}
	else switch (initial_val.length){
					case 2 :
									if (initial_val.toUpperCase() != (first_val.charAt(0).toUpperCase() + last_val.charAt(0).toUpperCase())){
									errored_fields[error_count] = 'sVerifyInitialsdiv';
									error_count++;
									error_msg += "Your verification initials did not match up with the first and last name given in the Person Details section.\n<br>\n";
									error_ind = true;	
									}
									break;
					case 3 :
									if (initial_val.toUpperCase() != (first_val.charAt(0).toUpperCase() + middle_val.charAt(0).toUpperCase() + last_val.charAt(0).toUpperCase())){
									errored_fields[error_count] = 'sVerifyInitialsdiv';
									error_count++;
									error_msg += "Your verification initials did not match up with the first, middle, and last name given in the Person Details section.\n<br>\n";
									error_ind = true;	
									}
									break;
					default : 	
									errored_fields[error_count] = 'sVerifyInitialsdiv';
									error_count++;
									error_msg += "Only 2 or 3 letters are allowed for initials.\n<br>\n";
									error_ind = true;
					}
									
	var tempdobmsg = isValidDate(vdob_val);
		if (tempdobmsg != ""){
				errored_fields[error_count] = 'sVerifyDOBdiv';
				error_count++;
				error_msg += "Verification. " + tempdobmsg + "\n<br>\n";
				error_ind = true;
			}
					
					
}

//***********************************************************
//
//				SUPPORT FUNCTIONS
//
//***********************************************************


/////////////////////////////////////////////////////
//
//		This function will calculate a person's age
//		based on a given date.
//
/////////////////////////////////////////////////////
function age(bDay){
 now = new Date();
 bD = new Array(); 
 bD = bDay.split('/');
 if(bD.length==3){
   born = new Date(bD[2], bD[0]*1-1, bD[1]);
   years = Math.floor((now.getTime() - born.getTime()) / (365.25 * 24 * 60 * 60 * 1000));
   return years;
 }
}



/////////////////////////////////////////////////////
//
//		This function will print out the error message
//		as well as assign the errored fields the error
//		class.  This will allow the fields to stand out
//		on the form.
//
/////////////////////////////////////////////////////
function print_error(id,text)
{	
	x = document.getElementById(id);
	x.innerHTML = '';
	x.innerHTML = text;
	
	for(i=0;i<errored_fields.length;i++)
			{
				//alert(errored_fields[i]);
			y = document.getElementById(errored_fields[i]);
			y.className += " error";
			}
	
	document.getElementById('errormsganchor').focus(); 

}


/////////////////////////////////////////////////////
//
//		This function allows us to get all the HTML
//		elements that are associated with a particular
//		class.
//
/////////////////////////////////////////////////////
function getElementbyClass(classname){
 
 var inc=0;
 var alltags=document.all? document.all : document.getElementsByTagName('*');
 var customcollection = new Array();
 var tempstring;
 
 for (i=0; i<alltags.length; i++){
 	 tempstring = alltags[i].className;
   if (tempstring.indexOf(classname) > -1){
     customcollection[inc] = alltags[i].id;
     inc++;
    }
 	}
 return customcollection;
}  


/////////////////////////////////////////////////////
//
//	This function will clear the the errorclass from
//	each HTML element.  This is used as a way to 
//	initialize the error checking procedure.
//
/////////////////////////////////////////////////////
function remove_error_class(errorclass){
	
	error_count = 0;
	error_msg = "";
	error_ind = false;
	
	for (i=0; i<errored_fields.length; i++){
			var x = document.getElementById(errored_fields[i]).className
			x = x.replace(errorclass, '');
			document.getElementById(errored_fields[i]).className = x;		
	}
	
	errored_fields.length = 0;
	
}


/////////////////////////////////////////////////////
//
//	This function validates a user input to make sure
//	it matches a valid state abbreviation.
//
/////////////////////////////////////////////////////
function validate_state(userinput){
	
	var state_regex = /^(AK|AL|AR|AZ|CA|CO|CT|DC|DE|FL|GA|HI|IA|ID|IL|IN|KS|KY|LA|MA|MD|ME|MI|MN|MO|MS|MT|NB|NC|ND|NH|NJ|NM|NV|NY|OH|OK|OR|PA|RI|SC|SD|TN|TX|UT|VA|VT|WA|WI|WV|WY)$/i;
	
	return userinput.match(state_regex);
	
}


/////////////////////////////////////////////////////
//
//		This function validates a phone number to make
//		sure it is in a 123-456-7890 format.
//
/////////////////////////////////////////////////////
function validate_phone(userinput){
	
	var phone_regex = /^\(?\d{3}\)?\s|-\d{3}-\d{4}$/;
	
	return userinput.match(phone_regex);
	
}


/////////////////////////////////////////////////////
//
//		This function makes sure a value is a valid zip
//		code.  A valid zip code is either 12345 or 
//		12345-6789.
//
/////////////////////////////////////////////////////
function validateZIP(field) {
	var valid = "0123456789-";
	var hyphencount = 0;
	var emsg = "";
	
	if (field.length!=5 && field.length!=10) {
	emsg = "Please enter your 5 digit or 5 digit+4 zip code.";
	return emsg;
	}
	for (var i=0; i < field.length; i++) {
	temp = "" + field.substring(i, i+1);
	if (temp == "-") hyphencount++;
	if (valid.indexOf(temp) == "-1") {
	emsg = "Invalid characters in your zip code.";
	return emsg;
	}
	if ((hyphencount > 1) || ((field.length==10) && ""+field.charAt(5)!="-")) {
	emsg = "The hyphen character should be used with a properly formatted 5 digit+four zip code, like '12345-6789'.";
	return emsg;
	   }
	}
	return emsg;
}


/////////////////////////////////////////////////////
//
//		This function makes sure that a passed value is
// 		a valid SSN.
//
/////////////////////////////////////////////////////
function SSNValidation(ssn) {
	var msg = "";
	var matchArr = ssn.match(/^(\d{3})-?\d{2}-?\d{4}$/);
	var numDashes = ssn.split('-').length - 1;
	
	if (matchArr == null || numDashes == 1) {
				msg = "Invalid SSN. Must be 9 digits or in the form NNN-NN-NNNN.";
				return msg;
		}
	else 
				if (parseInt(matchArr[1],10)==0) {
						msg = "Invalid SSN: SSN's can't start with 000.";
						return msg;
					}
				else {
							return msg;
	   			}
}


/////////////////////////////////////////////////////
//
//	This function checks to make sure a date is valid.
//  See comments within code for more detail.
//
/////////////////////////////////////////////////////
function isValidDate(dateStr) {
	// Checks for the following valid date formats:
	// MM/DD/YY   MM/DD/YYYY   MM-DD-YY   MM-DD-YYYY
	// Also separates date into month, day, and year variables
	
	// This regex is for an optional 4 digit year
	//var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/;
	
	// To require a 4 digit year entry, use this line instead:
	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;
	var msg = "";
	var matchArray = dateStr.match(datePat); // is the format ok?
	
	if (matchArray == null) {
			msg = "Date is not in a valid format.";
			return msg;
		}
	
	month = matchArray[1]; // parse date into variables
	day = matchArray[3];
	year = matchArray[4];
	
	if (month < 1 || month > 12) { // check month range
			msg = "Month must be between 1 and 12.";
			return msg;
		}
	
	if (day < 1 || day > 31) {
			msg = "Day must be between 1 and 31.";
			return msg;
		}
	
	if ((month==4 || month==6 || month==9 || month==11) && day==31) {
			msg = "Month "+month+" doesn't have 31 days."
			return msg
		}
	
	if (month == 2) { // check for february 29th
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		if (day>29 || (day==29 && !isleap)) {
				msg = "February " + year + " doesn't have " + day + " days.";
				return msg;
	   	}
		}
	
	return msg;  // date is valid
}


/////////////////////////////////////////////////////
//
//		This function checks to make sure a value is in 
//    a format that is equal to abcd@abcd.efg
//
/////////////////////////////////////////////////////
function validate_email(userinput){
	
	var email_regex = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/;
	
	return userinput.match(email_regex);
	
}

