var badchars = /([a-z])\1{2,}/gi;
var avatarScriptBase = 'forms';
function flagError(errorlabel,message)
{
	if (errorlabel == '') return;
	if (!document.getElementById(errorlabel)) return;
	document.getElementById(errorlabel).style.display = 'inline';
	document.getElementById(errorlabel).innerHTML = message + '<br>';
	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 = "";
}


/**
 * DHTML phone number validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
var phoneError = 0;

// Declaring required variables
var digits = "0123456789";
// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()- ";
// characters which are allowed in international phone numbers
// (a leading + is OK)
var validWorldPhoneChars = phoneNumberDelimiters + "+";
// Minimum no of digits in an international phone no.
var minDigitsInIPhoneNumber = 10;

function isInteger(s)
{   
	var i;
	for (i = 0; i < s.length; i++) {   
	// Check that current character is number.
		var c = s.charAt(i);
		if (((c < "0") || (c > "9"))) return false;
	}
	// All characters are numbers.
	return true;
}

function stripCharsInBag(s, bag)
{   
	var i;
	var returnString = "";
	// Search through string's characters one by one.
	// If character is not in bag, append to returnString.
	for (i = 0; i < s.length; i++) {   
		// Check that current character isn't whitespace.
		var c = s.charAt(i);
		if (bag.indexOf(c) == -1) returnString += c;
	}
	return returnString;
}

function checkInternationalPhone(strPhone)
{
	s=stripCharsInBag(strPhone,validWorldPhoneChars);
	return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
}

function validateAreaCode(Phone,PhoneLabel,Country,NoUnflag)
{
	if (!NoUnflag) { unflagError(PhoneLabel); }
	$.getJSON("/" + avatarScriptBase + "/forms/checkphone.php?validate=areacode&phone=" + Phone.value + "&phonelabel=" + PhoneLabel + "&country=" + Country, getCall);
}

function validatePrefix(Phone,PhoneLabel,Country,NoUnflag)
{
	if (!NoUnflag) { unflagError(PhoneLabel); }
	$.getJSON("/" + avatarScriptBase + "/forms/checkphone.php?validate=prefix&phone=" + Phone.value + "&phonelabel=" + PhoneLabel + "&country=" + Country, getCall);
}

function validateFullPhone(Phone,PhoneLabel,Country,NoUnflag)
{
	if (!NoUnflag) { unflagError(PhoneLabel); }
	$.getJSON("/" + avatarScriptBase + "/forms/checkphone.php?validate=full&phone=" + Phone.value + "&phonelabel=" + PhoneLabel + "&country=" + Country, getCall);
}

function getCall(data)
{
	for (var key in data) {
		if (data[key] == '') {
			//unflagError(key);
		} else {
			flagError(key,data[key]);
			phoneError = 1;
		}
	}
}

function buildPhone(FieldName)
{
	areacode = document.getElementById(FieldName + '_areacode').value;
	if (areacode == '') areacode = '000';
	prefix = document.getElementById(FieldName + '_prefix').value;
	if (prefix == '') prefix = '000';
	suffix = document.getElementById(FieldName + '_suffix').value;
	if (suffix == '') suffix = '0000';
	document.getElementById(FieldName).value = areacode + '-' + prefix + '-' + suffix;
	if (document.getElementById(FieldName).value == '000-000-0000') document.getElementById(FieldName).value = '';
}

function validatePhone(Phone,PhoneLabel,Country)
{
	unflagError(PhoneLabel);
	phoneError = 0;
	if (checkInternationalPhone(Phone.value)==false){
		flagError(PhoneLabel,'Required');
		return false;
	}
	
	validateAreaCode(Phone,PhoneLabel,Country,1); //Area code validation to be run synchronously
	if (phoneError == 1) return false;
	
	validatePrefix(Phone,PhoneLabel,Country,1); //Prefix validation to be run synchronously
	if (phoneError == 1) return false;

	validateFullPhone(Phone,PhoneLabel,Country,1); //Full phone number validation to be run synchronously
	if (phoneError == 1) return false;

	return true;
}
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;
	
}
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;
	}
}
function noNumbers(fieldvalue,label)
{
	var invalidName = /[0-9]/;
	if (invalidName.test(fieldvalue)) {
		flagError(label,"Invalid");
		return false;
	}
	return true;
}

var vulgarityFlag = 0;

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

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;
	}
}
