//create global array for outputting all errors at once
var arrErrors = new Array();
var frm = document.forms[0];

/* :::::: FORM VALIDATION :::::: */

// Validator Object code
//___________________________________________
function AreaZipMismatch(str)
{
	if(confirm(str))
	{
		document.forms[0].areazipoverride.value='yes';
		document.forms[0].submit();
	}
}

function Validator()
{
	this.isValid = true;
	this.fullMatchProfanity = new Array('shit','piss','cunt','tits','ass');
	this.partialMatchProfanity = new Array('fuck','cocksucker','motherfucker','asshole');
	this.validNumbers = '0123456789';
	this.validPhoneCharacters = '0123456789';
	this.validZipCharacters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789- ';
	this.validTextCharacters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ';
}

new Validator();

function V_raiseError(message)
{
	if (this.isValid) 
		//alert(message);
		arrErrors[arrErrors.length] = message;
	//this.isValid = false;
}

function V_containsProfanity(field)
{
	for (var i=0; i<this.fullMatchProfanity.length; i++)
	{
		if (field.toLowerCase() == this.fullMatchProfanity[i]) return true;
	}
	for (var i=0; i<this.partialMatchProfanity.length; i++)
	{
		if (field.toLowerCase().indexOf(this.partialMatchProfanity[i]) > -1) return true;
	}
	return false;
}

function V_validateText(text, label)
{
	if (!this.isValid) return;
	if (text.value == '' || text.value.replace(/ /gi,'')=='')
	{
		this.raiseError('Please enter your ' + label + '.');
		text.value='';
	}
	else if (this.containsProfanity(text.value))
	{
		this.raiseError(label + ' must not contain profane content.');
	}
}
// for text only like first and last name
function V_validateTextChars(text, label)
{
	//if (!this.isValid) return;
	if (text.value == '' || text.value.replace(/ /gi,'')=='' || text.value.length < 2)
	{
		addErrorClass(text);
		this.raiseError('Please enter your ' + label + '.');
		text.value='';
		
	}
	else if (this.containsProfanity(text.value))
	{
		addErrorClass(text);
		this.raiseError(label + ' must not contain profane content.');
	}
	else if (!this.isTextValid(text.value))
	{
		addErrorClass(text);
		this.raiseError(label + ' contains invalid characters.');
	}
	else
	{
		removeErrorClass(text);
	}
}

function V_validatePhone(phone, label)
{
	if (!this.isValid) return;
	
	if (phone.value == '')
	{
		if(phone.parentNode.parentNode.childNodes[0].className.indexOf("errorField") < 0)
			phone.parentNode.parentNode.childNodes[0].className += " errorField";
		this.raiseError(label + ' phone number must not be blank.');
	}
	else if (phone.value.length < 7)
	{
		if(phone.parentNode.parentNode.childNodes[0].className.indexOf("errorField") < 0)
			phone.parentNode.parentNode.childNodes[0].className += " errorField";
		this.raiseError(label + ' phone number should have at least seven numbers.');
	}
	else if (!this.isPhoneNumeric(phone.value))
	{
		if(phone.parentNode.parentNode.childNodes[0].className.indexOf("errorField") < 0)
			phone.parentNode.parentNode.childNodes[0].className += " errorField";
		this.raiseError(label + ' phone number should have only numbers.');
	}
	else
		phone.parentNode.parentNode.childNodes[0].className = phone.parentNode.parentNode.childNodes[0].className.replace("errorField", "");
}

function V_validateZip(zip, label)
{
	var blnIsZipValid = true;
	if (zip.value == '')
	{
		blnIsZipValid = false;
		this.raiseError(label + ' must not be blank.');
	}
	else if (zip.value.length < 5)
	{
		blnIsZipValid = false;
		this.raiseError(label + ' must be at least five characters.');
	}
	else if (!this.isZipValid(zip.value.toLowerCase()))
	{
		blnIsZipValid = false;
		this.raiseError(label + ' contains invalid characters.');
	}
	if(blnIsZipValid == false)
	    addErrorClass(zip);
	else
		removeErrorClass(zip);
}

function V_validateZipCanada(zip, label)
{
	var blnIsZipValid = true;
	if (zip.value == '')
	{
		blnIsZipValid = false;
		this.raiseError(label + ' must not be blank.');
	}
	else if (zip.value.length < 6)
	{
		blnIsZipValid = false;
		this.raiseError(label + ' must be at least six characters.');
	}
	else if (!this.isZipValid(zip.value.toLowerCase()))
	{
		blnIsZipValid = false;
		this.raiseError(label + ' contains invalid characters.');
	}
	if(blnIsZipValid == false)
	    addErrorClass(zip);
	else
		removeErrorClass(zip);
}

function V_validateNumericOnly(myField, label)
{
	if (!this.isValid) return;
	if (myField.value == '')
	{
		if(myField.parentNode.parentNode.childNodes[0].className.indexOf("errorField") < 0)
			myField.parentNode.parentNode.childNodes[0].className += " errorField";
		this.raiseError(label + ' must not be blank.');
	}
	else if (myField.value.length < 4)
	{
		if(myField.parentNode.parentNode.childNodes[0].className.indexOf("errorField") < 0)
			myField.parentNode.parentNode.childNodes[0].className += " errorField";
		this.raiseError(label + ' must be four characters long.');
	}
	else
		myField.parentNode.parentNode.childNodes[0].className = myField.parentNode.parentNode.childNodes[0].className.replace("errorField", "");
}

function V_validateEmail(email, label)
{
	var blnIsEmailValid = true;
	if (!this.isValid) return;
	if (email.value == '')
	{
		blnIsEmailValid = false;
		this.raiseError(label + ' must not be blank.');
	}
	// Email validation
	else if (email.value != '')
	{
		var str = email.value;
		var instancecounter = 0;

		str += '';
		intAt = str.indexOf( '@', 1 );		// the "@"
		intDot = str.lastIndexOf( '.' );		// the last "."
		namestr = str.substring( 0, intAt );		// everything before the "@"
		domainstr = str.substring( intAt +1, str.length );		// everything after the "@"
		toplevelstr = str.substring( intDot +1, str.length);		// everything after the last "."
		
		if ((str.indexOf('test@') > -1) || (str.indexOf('@test.') > -1))
		{
			blnIsEmailValid = false;
			this.raiseError(label + ' appears to be invalid.');
		}
		
		if ((str.indexOf(" ")!=-1) || (intAt == -1) || (intDot == -1 ) || (namestr.length == 0) || (domainstr.length == 0) || (intAt > intDot) || (domainstr.indexOf(".") <= 0) || (toplevelstr.length <= 1))
		{
			blnIsEmailValid = false;
			this.raiseError(label + ' appears to be invalid.');
		} 
		else
		{
			// iterate through email address checking for
			// more than 1 @ sysmbol, or none at all
			for ( i = 0; i < str.length; i++ )
			{
				if ((str.substring(i,i+1)) == "@" )
				{
					instancecounter = instancecounter + 1;
				}
			}
			// Check to see if we have none, or more than one @ symbol
			if ((instancecounter > 1) || (instancecounter == 0 ))
			{
				blnIsEmailValid = false;
				this.raiseError(label + ' appears to be invalid.');
			}
		}
	}
	if(blnIsEmailValid == false)
		addErrorClass(email);
	else
	    removeErrorClass(email);
}	

function V_isNumeric(field)
{
	for (var i=0; i<field.length; i++)
	{
		if (this.validNumbers.indexOf(field.charAt(i),0) == -1)
			return false;
	}
	return true;
}

function V_isPhoneNumeric(field)
{
	for (var i=0; i<field.length; i++)
	{
		if (this.validPhoneCharacters.indexOf(field.charAt(i),0) == -1) return false;
	}
	return true;
}

function V_isZipValid(field)
{
	for (var i=0; i<field.length; i++)
	{
		if (this.validZipCharacters.indexOf(field.charAt(i),0) == -1) return false;
	}
	return true;
}

function V_isTextValid(field)
{
	for (var i=0; i<field.length; i++)
	{
		if (this.validTextCharacters.indexOf(field.charAt(i),0) == -1) return false;
	}
	return true;
}

Validator.prototype.raiseError = V_raiseError;
Validator.prototype.validateText = V_validateText;
Validator.prototype.validateTextChars = V_validateTextChars;
Validator.prototype.validatePhone = V_validatePhone;
Validator.prototype.validateZip = V_validateZip;
Validator.prototype.validateZipCanada = V_validateZipCanada;
Validator.prototype.validateNumericOnly = V_validateNumericOnly;
Validator.prototype.isNumeric = V_isNumeric;
Validator.prototype.isZipValid = V_isZipValid;
Validator.prototype.isTextValid = V_isTextValid;
Validator.prototype.isPhoneNumeric = V_isPhoneNumeric;
Validator.prototype.validateEmail = V_validateEmail;
Validator.prototype.containsProfanity = V_containsProfanity;

//---------- custom functions ----------

function addErrorClass(fieldId)
{
    blnRetVal = false;
    
    if(fieldId.parentNode.parentNode.childNodes[0].className.indexOf("errorField") < 0)				
	{
	    fieldId.parentNode.parentNode.childNodes[0].className += " errorField";
	    blnRetVal = true;
	}
	if(fieldId.className != "inputError")
	{
		fieldId.className = "inputError";
		blnRetVal = true;
	}
	
	return blnRetVal;
}

function removeErrorClass(fieldId)
{
    fieldId.parentNode.parentNode.childNodes[0].className = fieldId.parentNode.parentNode.childNodes[0].className.replace("errorField", "");
	fieldId.className = fieldId.className.replace("inputError", "");
}

function checkDegree()
{
	/*
	switch(frm.program_code[frm.program_code.selectedIndex].value)
	{
		case '368':
		case '370':
		case '373':
		case '622':
			alert('Thank you for your interest in Capella University.  The specialization you have selected is for current K-12 professionals interested in extending their education with a graduate degree.  Please be aware that this specialization does not lead to initial teacher licensure.');
			break;
		default:
			break;
	}
	*/
}

function checkCountry()
{
	if (frm.country_code[frm.country_code.selectedIndex].value != '' && frm.country_code[frm.country_code.selectedIndex].value != 'USA' && frm.country_code[frm.country_code.selectedIndex].value != 'CAN')
	{
		document.getElementById("state_code")[0].selected = true;
		document.getElementById("stateRow").className = 'hidden';
		document.getElementById("phoneCountryCodeRow").className = 'visible';
	}
	else
	{
		document.getElementById("stateRow").className = 'visible';
		document.getElementById("phoneCountryCodeRow").className = 'hidden';
		frm.phone_country_code.value = '1';
	}
}

function detectCountry()
{//hide country code row on page load if value is usa or can
	if(frm.country_code[frm.country_code.selectedIndex].value == "USA" || frm.country_code[frm.country_code.selectedIndex].value == "CAN")
	{//hide phone country code and make sure state field is visible for USA/CAN
		document.getElementById("phoneCountryCodeRow").className = "hidden";
		document.getElementById("stateRow").className = "visible";
	}
	else if(frm.country_code[frm.country_code.selectedIndex].value != "") //if a country value exists, and it's not USA or CAN, hide the state field
		document.getElementById("stateRow").className = "hidden";
	else //else make sure phone country code is visible for non-USA/CAN countries
		document.getElementById("phoneCountryCodeRow").className = "visible";
}

function shiftFocus(this_field, next_field, length)
{
	var currentField = document.getElementById(this_field);
	var acode = currentField.value; 
	currentField.value = acode.replace(/\D/g, ''); //strip non numeric keys before checking count
	if(currentField.value.length ==  length)
	{
		document.getElementById(next_field).focus();
	}
}

function CkEduMisMatch()
{
	var progD = document.getElementById('program').options[document.getElementById('program').selectedIndex].value;
	var highEdVal = frm.education_level.options[frm.education_level.selectedIndex].value;
	var msg = "Your highest level of education may not meet entrance requirements\nfor the degree you are seeking.\n\nPlease verify your selection before submitting this form.";

	if (progD != "BS" && progD != "Certificate" && highEdVal != ""){
		var limitLevel1 = "1::2::3::4::5::6::7::8::9::";
		var limitLevel2 = limitLevel1 + "10::";

		if ((progD == "Online MS" || progD == "MBA") && limitLevel1.indexOf(highEdVal + "::") > -1){
			alert(msg);
			FlagAlert(frm.program);
			FlagAlert(frm.education_level);
		}
		else if ((progD == "PhD" || progD == "PsyD") && limitLevel2.indexOf(highEdVal + "::") > -1){
			alert(msg);
			FlagAlert(frm.program);
			FlagAlert(frm.education_level);
		}
	}
}

//---------- form validation function ----------
function VerifyAndSubmitStep1(strGoToStep2){
	var degID = 0;
	var v = new Validator();
	var errorUl = document.getElementById("errorUl");
	
	//empty the errors array and remove any list items in errorUl first
	arrErrors.length = 0;
	errorUl.innerHTML = "";

	// verify first name is not blank
	v.validateTextChars(frm.first_name, 'First Name');
	
	// verify last name is not blank
	v.validateTextChars(frm.last_name, 'Last Name');

	if(frm.zip.value == "")
	{
		addErrorClass(frm.zip);				
		v.raiseError('Please enter your zip/postal code.');
	}
	else
	{
		removeErrorClass(frm.zip)
	}
		
	//double check zip field and phone country code in case the user used a form autocomplete tool
	if(frm.phone_country_code.value == '' || frm.country_code.value == '')
	    checkZip(frm.zip.value);   

	//verify country
	if (frm.country_code[frm.country_code.selectedIndex].value == '' && document.getElementById('countryRow').className == 'visible')
	{
		addErrorClass(frm.state_code);
		addErrorClass(frm.country_code);
		v.raiseError('Please select your country.');
	}
	else if (frm.country_code[frm.country_code.selectedIndex].value != 'USA' && frm.country_code[frm.country_code.selectedIndex].value != 'CAN')
	{
		checkCountry();
		removeErrorClass(frm.country_code);
	}
	
	// verify state is not blank
	switch(frm.country_code[frm.country_code.selectedIndex].value)
	{
	    case 'USA':
	    case 'CAN':
	        if (frm.state_code[frm.state_code.selectedIndex].value == '' && document.getElementById('stateRow').className == 'visible')
            {
	            addErrorClass(frm.state_code);
	            v.raiseError('Please select your state.');
            }
            else
	            removeErrorClass(frm.state_code);
	        break;
	    default:
	        break;
	}
	
	// verify zip code
	switch(frm.country_code.value)
	{
		case 'USA':
			v.validateZip(frm.zip, 'ZIP');
			break;
		case 'CAN':
			v.validateZipCanada(frm.zip, 'ZIP');
			break;
	}
	
	// verify phone fields
	//verify phone_country_code
	var blnIsPhoneValid = true;
	var phone = frm.phone_combined.value;
	
	//setup array of characters to remove from phone
	var charArray = new Array();
	charArray[0] = "(";
	charArray[1] = ")";
	charArray[2] = " ";
	charArray[3] = "-";
	
	//loop through charArray to see if any illegal characters are in phone
	//if so, call removeCharacter function to remove them
	for(var i = 0; i < charArray.length; i++)
	{
		if(phone.indexOf(charArray[i]) > -1)
			removeCharacter(charArray[i]);
	}
	
	function removeCharacter(character)
	{
		var intIndexOfMatch = phone.indexOf(character);
		while(intIndexOfMatch != -1)
		{
			//remove character
			phone = phone.replace(character, "");
			//find next match
			intIndexOfMatch = phone.indexOf(character);
		}
	}
	var areaCode = phone.substring(0, 3);
	var phoneNumber = phone.substring(3, 10);
	frm.h_area_code.value = areaCode;
	frm.h_phone.value = phoneNumber;
	if (frm.phone_country_code.value == '' && document.getElementById('phoneCountryCodeRow').className == 'visible')
	{
		addErrorClass(frm.phone_country_code);
		v.raiseError('Please enter your phone country code');
	}
	else
		removeErrorClass(frm.phone_country_code);
	
	// verify home area code
	if (phone == '')
	{
		blnIsPhoneValid = false;
		v.raiseError('Please enter your phone number');
	}
	//remove special characters from phone
	else if (frm.phone_country_code.value == "1" && phone.length != 10)
	{
		blnIsPhoneValid = false;
		v.raiseError('Phone number must have 10 digits');
	}
	if (!v.isPhoneNumeric(phone))
	{
		blnIsPhoneValid = false;
		v.raiseError('Phone number should contain only numbers.');
	}
	else if (areaCode == '111' || areaCode == '123' || areaCode == '222' || areaCode == '333' || areaCode == '444' || areaCode == '555' || areaCode == '666' || areaCode == '777' || areaCode == '888' || areaCode == '999' || areaCode == '911' || areaCode == '000' || areaCode == '098')
	{
		blnIsPhoneValid = false;
		v.raiseError('Home area code apears to be invalid.');
	}
	
	if (phoneNumber.replace(/-/gi,'')=='1111111' || phoneNumber.replace(/-/gi,'')=='1234567' || phoneNumber.replace(/-/gi,'')=='4567890' || phoneNumber.replace(/-/gi,'')=='0000000' || phoneNumber.replace(/-/gi,'')=='2222222' || phoneNumber.replace(/-/gi,'')=='3333333' || phoneNumber.replace(/-/gi,'')=='4444444' || phoneNumber.replace(/-/gi,'')=='5555555' || phoneNumber.replace(/-/gi,'')=='6666666' || phoneNumber.replace(/-/gi,'')=='7777777' || phoneNumber.replace(/-/gi,'')=='8888888' || phoneNumber.replace(/-/gi,'')=='9999999' || phoneNumber.replace(/-/gi,'')=='00000000' || phoneNumber.replace(/-/gi,'')=='000000')
	{
		blnIsPhoneValid = false;
		v.raiseError('Home phone number appears to be invalid.');
	}
	else if (phoneNumber.indexOf('000') == 0 || phoneNumber.indexOf('911') == 0 || phoneNumber.indexOf('555') == 0 || phoneNumber.indexOf('1234') == 0 || phoneNumber.indexOf('0123') == 0)
	{
		blnIsPhoneValid = false;
		v.raiseError('Home phone number appears to be invalid.');
	}
	if(blnIsPhoneValid == false)
	{
		addErrorClass(frm.phone_combined);
	}
	else
		removeErrorClass(frm.phone_combined);

    //validate best_time_to_call field
    if (frm.best_time_to_call[frm.best_time_to_call.selectedIndex].value == '') {
        addErrorClass(frm.best_time_to_call);
        v.raiseError('Please select the best time to call.');
    }
    else {
        removeErrorClass(frm.best_time_to_call);
    }
	
	// verify e-mail address is not blank and verify valid format
	v.validateEmail(frm.email, 'Email Address');
	
	// verify program
	if(frm.program)
	{
	    if (frm.program[frm.program.selectedIndex].value == '')
	    {
		    v.raiseError('Please indicate your degree level.');
		    addErrorClass(frm.program);
	    }
	    else
	        removeErrorClass(frm.program);
    }

	// verify school
	if(frm.school)
	{
	    if (frm.school[frm.school.selectedIndex].value == '')
	    {
		    v.raiseError('Please indicate your area of study.');
		    addErrorClass(frm.school);
	    }
	    else
	        removeErrorClass(frm.school);
	}
	
	// verify specialization
	if(frm.specialization && frm.specialization.options)
	{
	    if (frm.specialization[frm.specialization.selectedIndex].value == '')
	    {
		    v.raiseError('Please indicate your specialization.');
		    addErrorClass(frm.specialization);
	    }
	    else
		    removeErrorClass(frm.specialization);
	}
	
	    
	//verify start date
	if (frm.month_completion_date[frm.month_completion_date.selectedIndex].value == '' || frm.year_completion_date[frm.year_completion_date.selectedIndex].value == '')
	{
		v.raiseError('Please indicate your projected start date.');
		addErrorClass(frm.month_completion_date);
	}
	else
	{
	    //verify that start date is in the future
	    var date = new Date();
	    var currentMonth = (date.getMonth() +1);
	    var currentYear = date.getFullYear();
	    if(frm.year_completion_date[frm.year_completion_date.selectedIndex].value == currentYear && frm.month_completion_date[frm.month_completion_date.selectedIndex].value <= currentMonth)
	    {
		    v.raiseError('Please select a future date.');
		    addErrorClass(frm.year_completion_date);
	    }
	    else
	        removeErrorClass(frm.year_completion_date);
	}
	
	// verify education_level
	if (frm.education_level[frm.education_level.selectedIndex].value == '')
	{
			v.raiseError('Please indicate your highest level of education.');
			addErrorClass(frm.education_level);
	}
	else
	    removeErrorClass(frm.education_level);
	
	//if persona questions are present, validate them
	if(document.getElementById("persona1q"))
	{
		// verify persona1q
		if (frm.persona1q[frm.persona1q.selectedIndex].value == '')
		{
			v.raiseError('Please indicate your primary motivation for going back to school.');
			addErrorClass(frm.persona1q);
		}
		else
			removeErrorClass(frm.persona1q);
	}
	
	if(document.getElementById("persona2q"))
	{
		// verify persona2q
		if (frm.persona2q[frm.persona2q.selectedIndex].value == '')
		{
			v.raiseError('Please indicate your approach to making a major decision.');
			addErrorClass(frm.persona2q);
		}
		else
			removeErrorClass(frm.persona2q);
	}
	
	//double check zip field and phone country code in case the user used a form autocomplete tool
	if(frm.phone_country_code.value == '' || frm.country_code.value == '')
	    checkZip(frm.zip.value);	
	
	var errorDiv = document.getElementById("errorDiv");
	if(arrErrors.length > 0)
	{		
		//prevent form submission by setting isValid to false
		v.isValid = false;
		//make errors div visible
		errorDiv.className = "visible";
		//generate a new list item for each form error in the errorUl <ul> tag	
		for(var i = 0; i < arrErrors.length; i++)
		{
			errorUl.innerHTML += "<li>" + arrErrors[i] + "</li>";
		}
	}
	else
		errorDiv.className = "hidden";
	
	if (v.isValid) 
	{
		for (var i=0; i<document.links.length; i++)
		{
			if (document.links[i].href.toLowerCase() == 'javascript:validateform();')
			{
				document.links[i].href = '#';
				break;
			}
		}
		frm.submit();
	}
}

function VerifyAndSubmitStep2(){
	var errorUl = document.getElementById("errorUl");
	var v = new Validator();
	//empty the errors array and remove any list items in errorUl first
	arrErrors.length = 0;
	errorUl.innerHTML = "";
	//if one of the address fields is filled in, validate the others
	if(frm.address)//first check to see if field exists (only visible if user selects USA/CAN in step 1)
	{
		if(frm.address.value == '')
		{
			addErrorClass(frm.address);
			v.raiseError('Please enter your address.');
		}
		else
		    removeErrorClass(frm.address);
			
		if(frm.city.value == '')
		{
			addErrorClass(frm.city);
			v.raiseError('Please enter your city.');
		}
		else
			removeErrorClass(frm.city);
	}
	
	var errorDiv = document.getElementById("errorDiv");
	if(arrErrors.length > 0)
	{		
		//prevent form submission by setting isValid to false
		v.isValid = false;
		//make errors div visible
		errorDiv.className = "visible";
		//generate a new list item for each form error in the errorUl <ul> tag	
		for(var i = 0; i < arrErrors.length; i++)
		{
			errorUl.innerHTML += "<li>" + arrErrors[i] + "</li>";
		}
	}
	
	if(v.isValid == true)
	{
		for (var i=0; i<document.links.length; i++)
		{
			if (document.links[i].href.toLowerCase() == 'javascript:validateform();')
			{
				document.links[i].href = '#';
				break;
			}
		}
		
		frm.submit();
	}
}