var badchars = /([a-z])\1{2,}/gi;
var avatarScriptBase = 'schooldegrees';
function flagError(errorlabel,message)
{
	if (errorlabel == '') return;
	if (!document.getElementById(errorlabel)) return;
	document.getElementById(errorlabel).style.display = '';
	document.getElementById(errorlabel).innerHTML = message + '<br>';
	document.getElementById('parentDivOf' + errorlabel).style.display = ''
	document.getElementById('parentDivOf' + errorlabel).style.backgroundColor = "#E7A6A6";
	document.getElementById('parentDivOf' + errorlabel).style.border = "1px solid #BB0000";
}

function unflagError(errorlabel)
{
	if (errorlabel == '') return;
	if (!document.getElementById(errorlabel)) return;
	document.getElementById(errorlabel).innerHTML = '<br>';
	document.getElementById(errorlabel).style.display = 'none';
	document.getElementById('parentDivOf' + errorlabel).style.backgroundColor = "";
	document.getElementById('parentDivOf' + errorlabel).style.border = "";
}


var emailError = 0;

function validateEmail(emailAddress)
{
	var invalidEmail = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/; // not valid
	var validEmail = /^[a-zA-Z0-9\-\.\+\%\_]+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,}|[0-9]{1,3})$/; // valid

	if (!invalidEmail.test(emailAddress) && validEmail.test(emailAddress))  // if syntax is valid
	{
		return true;
	}
	return false;
}

function pingMX(emailAddr,label)
{
	document.body.style.cursor = 'wait';
	
	getJSON("/" + avatarScriptBase + "/forms/pingmx.php?&email=" + emailAddr + "&emaillabel=" + label, getPingMXCall);
}

function getPingMXCall(data)
{
	document.body.style.cursor = 'default';
	
	for (var key in data) {
		if (data[key] == '') {
		} else {
			flagError(key,data[key]);
			emailError = 1;
		}
	}
}

function alertOnInvalidEmail(email_obj,label)
{
	emailError = 0;
	
	if (!validateEmail(email_obj.value)) {
        if (0 == email_obj.value.length) {
            flagError(label,'Required');
        } else {
            flagError(label,"'" + email_obj.value + "' is invalid.");
        }
        return false;
	}
	
	pingMX(email_obj.value,label);
	if (emailError == 1) return false;
	
	return true;
}
function getCheckedRadioValue(id)
{
	for (var i=0; i<100; i++){ //Max 100 radio buttons to prevent infinite loop
		rb = document.getElementById(id + '_' + i);
		if (rb == null) return false;
		if (rb.checked) return rb.value;
	}
	return false;
}

function hasChecked(id)
{
	for (var i=0; i<100; i++){ //Max 100 radio buttons to prevent infinite loop
		rb = document.getElementById(id + '_' + i);
		if (rb == null) return false;
		if (rb.checked) return true;
	}
	return false;
}
var postalCodeValidationFlag = 0;

function checkPostalCode(pc,campusID,label,state)
{
	if (validateUSPostalCode(pc.value) || validateCanadianPostalCode(pc.value)) {
	} else {
		flagError(label,"Invalid");
		return false;
	}
	
	if (campusID == 0)  return true;
	
	postalCodeValidationFlag = 0;
	checkPostalCodeAgainstCampus(pc.value,campusID,label,state);
	
	if (postalCodeValidationFlag == 1) return false;
	
	return true;
}

function validateUSPostalCode(postalCode)
{
	validPostalCode = /^[0-9]{5}(\-[0-9]{4}){0,1}$/;
	if (validPostalCode.test(postalCode))
		return true;
	else
		return false;
}

function validateCanadianPostalCode(postalCode)
{
	validPostalCode = /^([a-ceghj-npr-tv-z]){1}[0-9]{1}[a-ceghj-npr-tv-z]{1}\s?[0-9]{1}[a-ceghj-npr-tv-z]{1}[0-9]{1}$/i;
	if (validPostalCode.test(postalCode))
		return true;
	else
		return false;
}

function checkPostalCodeAgainstCampus(postalCode,campusID,label,state)
{
	getJSON("/" + avatarScriptBase + "/forms/checkpostalcode.php?pc=" + postalCode + "&campusID=" + campusID + "&label=" + label + "&state=" + state, getPostalCodeData);
	//Might want to pass in the SchoolID as well in order to return a campus of that school which WOULD be valid
}

function getPostalCodeData(data)
{
	switch (data['response']) {
		case 'Y':
			break;
		case 'N':
			flagError(data['label'],'Invalid');
			postalCodeValidationFlag = 1;
			break;
		case 'M':
			flagError(data['label'],'Mismatch with State');
			postalCodeValidationFlag = 1;
			break;
		case 'C': //This postal code does not work for this school
			flagError(data['label'],'Invalid for this campus');
			postalCodeValidationFlag = 1;
			break;
	}
}
var vulgarityFlag = 0;

function isVulgar(label,value)
{
	vulgarityFlag = 0;
	checkVulgarity(label,value);
	
	if (vulgarityFlag == 1) return true;
	
	return false;
}

function checkVulgarity(label,value)
{
	getJSON("/" + avatarScriptBase + "/forms/checkvulgarity.php?label=" + label + "&value=" + escape(value), getVulgarityData);
}


function getVulgarityData(data)
{
	switch (data['response']) {
		case 'Y':
			flagError(data['label'],'Invalid');
			vulgarityFlag = 1;
			break;
		case 'N':
			break;
	}
}
function modifyAreaOfStudy(gaos,campusID,areaOfStudySelect)
{
	getJSON("/" + avatarScriptBase + "/modifyareaofstudy.php?gaos=" + gaos + "&campusID=" + campusID + "&aname=" + areaOfStudySelect, getAreaOfStudyData);
}

function getAreaOfStudyData(data)
{
	for (var key in data) {
		var throwerror = 0;

		sel = document.getElementById(key);

		var current = null;
		//Grab the current selected value and keep it (if it remains in the list)
		if (sel.selectedIndex > 0) {
			current = sel.options[sel.selectedIndex].value;
			throwerror = 1;
		}

		//If the first value is a default beginning value, keep it
		default_value = '';
		if (sel.options[0].value == '') default_value = sel.options[0].text;

		sel.options.length = 0; //Zero out array

		var i = 0;

		//Replace default beginning value (if exists)
		if (default_value != '') {
			sel.options[i] = new Option(default_value,'');
			i++;
		}

		//Add in programs from Ajax response
		optionarr = data[key];
		for (var optionkey in optionarr) {
			var node = optionarr[optionkey];
			sel.options[i] = new Option(node['desc'],node['value']);
			if (node['value'] == current) {
				sel.selectedIndex = i; //Current was the value that was selected before.  Reselect it if it remains in the list.
				throwerror = 0;
			}
			i++;
		}

		if (throwerror == 1) {
			flagError('error' + sel.id,'You must select another area of study.');
			sel.focus();
		}
	}
}
