// $Id: profile_base.js 2737 2009-03-04 12:00:14Z dmf $
// Functions to support validation of join, join_access & profile_base

// Variables to be populated in the HTML: 
// none, but valStrings should come from requiredFields.js

// Username validation
function checkUsername (formElement) {
	valStrings["username"] = formElement.value;
	if (!formElement.value.match(/^\w{3,20}$/) && formElement.value) {
		alert(valStrings["usernameLength"]); 
		formElement.value = formElement.value.replace(/\W/g, '');
		if (formElement.value.length < 3) {
			formElement.value = '';
		}
		formElement.focus();
		return false;
	} else if (formElement.value.match(/\d/g) && formElement.value.match(/\d/g).length > 4) {
		alert(valStrings["usernameDigits"]); 
		formElement.value = formElement.value.replace(/\d/g, '');
		if (formElement.value.length < 3) {
			formElement.value = '';
		}
		formElement.focus();
		return false;
	} else {
		return true;
	}
}

// checkEmail by DMF, based on emailCheck v1.1.2 from http://javascript.internet.com 
function checkEmail (formElement, relaxed) {
	var emailStr = formElement.value;
	var emailPat = /^(.+)@(.+)$/;
	var specialChars = "\\!\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
	var validChars = "\[^\\s" + specialChars + "\]";
	var quotedUser = "(\"[^\"]*\")";
	var ipDomainPat = /^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
	var atom = validChars + '+';
	var domAtom = '[a-zA-Z0-9\-]+';
	var word = "(" + atom + "|" + quotedUser + ")";
	var userPat = new RegExp("^" + word + "(\\." + word + ")*$");
	var domainPat = new RegExp("^" + domAtom + "(\\." + domAtom +")*$");
	var domAtomPat = new RegExp(domAtom,"g");
	

	// Don't bother if there's no emailStr
	if (!emailStr) {
		return true;
	}

	// Begin with the coarse pattern to simply break up user@domain into different pieces that are easy to analyze.
	var matchArray = emailStr.match(emailPat);
	if (matchArray == null) {
		alert (valStrings["emailUserAtDomain"]);
		formElement.focus();
		return false;
	}
	var user = matchArray[1];
	var domain = matchArray[2];

	// See if "user" is valid 
	if (user.match(userPat) == null) {
		alert (valStrings["emailUserPart"]);
		formElement.focus();
		return false;
	}

	// See if "user" matches username
	if (!relaxed && formElement.form.username && formElement.form.username.value && user.toLowerCase() == formElement.form.username.value.toLowerCase()) {
		alert (valStrings["emailUsername"]);
		formElement.form.username.value = "";
		formElement.form.username.focus();
		return false;
	}

	// See if address starts www.
	if (user.substr(0,4).toLowerCase() == "www.") {
		if (confirm(valStrings["emailWWW"])) {
			formElement.value = formElement.value.substr(4);
			formElement.focus();
			return false;
		}
	}

	// if the e-mail address is at an IP address (as opposed to a symbolic host name) make sure the IP address is valid.
	var IPArray = domain.match(ipDomainPat);
	if (IPArray != null) {
		for (var i=1;i<=4;i++) {
			if (IPArray[i]>255) {
				alert (valStrings["emailIPBad"]);
				formElement.focus();
				return false;
			}
		}
		return true;
	}

	// Domain is symbolic name
	if (domain.match(domainPat) == null) {
		alert (valStrings["emailDomainPart"]);
		formElement.focus();
		return false;
	}

	// Domain name seems valid, but now make sure that it ends in a valid TLD and that there's a hostname preceding the TLD
	var domArr = domain.match(domAtomPat);
	var len = domArr.length;
	if (!domArr[len-1].match(/^(com|net|org|edu|gov|mil|int|arpa|biz|info|name|pro|museum|aero|coop|travel|jobs|eu)$/i) // .travel, .jobs and .eu added on 2005-04-08
	 && !domArr[len-1].match(/^(ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bl|bm|bn|bo|br|bs|bt|bv|bw|by|bz)$/i)
	 && !domArr[len-1].match(/^(ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|fi|fj|fk|fm|fo|fr|ga|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy)$/i)
	 && !domArr[len-1].match(/^(hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mf|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz)$/i)
	 && !domArr[len-1].match(/^(na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|sv|sy|sz)$/i)
	 && !domArr[len-1].match(/^(tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$/i)
	   ) {
		alert (valStrings["emailBadTLD"]);
		formElement.focus();
		return false;
	}

	// Make sure there's a host name preceding the domain.
	if (len < 2) {
		alert (valStrings["emailNoSLD"]);
		formElement.focus();
		return false;
	}

	// If we've gotten this far, everything's valid!
	return true;
}

// Checks that two email address fields match
function checkEmails (checkForm) {
	if (checkForm.email.value == checkForm.email2.value) {
		return true;
	} else {
		alert (valStrings["emailMismatch"]);
		checkForm.email.value = checkForm.email2.value = '';
		checkForm.email.focus();
		return false;
	}
}

// Activation code validation
function checkActivationCode (formElement) {
	if (!formElement.value.match(/^[a-zA-Z]{3}[1-9]{3}$/) && formElement.value) {
		alert(valStrings["badActivationFormat"]); 
		formElement.value = '';
		formElement.focus();
		return false;
	} else {
		return true;
	}
}

// Checks length bounds on a single password
function checkPassword (formElement) {
	if (!formElement.value.match(/^.{4,15}$/) && formElement.value) {
		alert(valStrings["passwordLength"]); 
		if (formElement.value.length < 4) {
			formElement.value = '';
		}
		formElement.focus();
		return false;
	}
	if (formElement.value && formElement.value.match(/^[0-9]+$/)) {
		alert(valStrings["passwordAllNumeric"]); 
		formElement.focus();
		return false;
	}
	
	if (formElement.form.username.length && formElement.value.toLowerCase() == formElement.form.username.value.toLowerCase()) {
		alert(valStrings["passwordUsername"]); 
		formElement.value = '';
		formElement.focus();
		return false;
	}
	
	// Verify that the password field does NOT contain any part of the username
	if (formElement.value.length && formElement.form.username.value.toLowerCase().match(formElement.value.toLowerCase())) {
		alert(valStrings["passwordUsernameStrMatch"]);
		formElement.value = '';
		formElement.focus();
		return false;
	}
	return true;
}

// Checks that two password fields match
function checkPasswords (checkForm) {
	if (checkForm.password.value == checkForm.password2.value) {
		return true;
	} else {
		alert (valStrings["passwordMismatch"]);
		checkForm.password.value = checkForm.password2.value = '';
		checkForm.password.focus();
		return false;
	}
}

// Checks for default firstName
function checkFirstName (formElement) {
	if (formElement.value == valStrings["defaultFirstName"]) {
		alert ('"' + formElement.value + '" ' + valStrings["err_badFirstName"]);
		formElement.focus();
		return false;
	} else {
		return true;
	}
}

// Verify that the password does NOT contain any part of the first name
function comparePasswordName (formElement, password) {
	if (formElement.value.toLowerCase().match(password.value.toLowerCase()) && formElement.value) {
		alert(valStrings["passwordUsernameStrMatch"]);
		password.value = password.form.password2.value = '';
		password.focus();
		return false;
	}
	
	return true;
}

// Checks for default surname
function checkSurname (formElement) {
	if (formElement.value == valStrings["defaultSurname"]) {
		alert ('"' + formElement.value + '" ' + valStrings["err_badSurname"]);
		formElement.focus();
		return false;
	} else {
		return true;
	}
}

// Check for underage users.
function checkBirthDate (formElement) {
	var year = formElement.form.birthDateYear.options[formElement.form.birthDateYear.selectedIndex].text;
	var month = formElement.form.birthDateMonth.options[formElement.form.birthDateMonth.selectedIndex].value;
	var day = formElement.form.birthDateDay.options[formElement.form.birthDateDay.selectedIndex].text;
	var birth18 = new Date (serverDate.substr(0,4) - 18, serverDate.substr(5,2) - 1, serverDate.substr(8,2));
	var birthDate = new Date (year, (month - 1), day);
	if (birthDate.getTime() > birth18.getTime()) {
		alert (valStrings["tooYoung"]); 
		formElement.focus();
		return false;
	}
	return true;
}

// Check that min & max are the right way round and importance is correct
function checkAgeRange (formElement) {
	var mAgeMin = formElement.form.mAgeMin.selectedIndex;
	var mAgeMax = formElement.form.mAgeMax.selectedIndex;
	if (mAgeMax < mAgeMin) {
		formElement.form.mAgeMin.options[mAgeMin].selected = false;
		formElement.form.mAgeMax.options[mAgeMax].selected = false;
		formElement.form.mAgeMin.options[mAgeMax].selected = true;
		formElement.form.mAgeMax.options[mAgeMin].selected = true;
	}
	return true;
}

// Conditions for form submission
function submitJoin (checkForm, relaxed) {
	return (checkRequiredFields(checkForm) 
	     && checkUsername (checkForm.username)
	     && checkEmails (checkForm)
	     && checkEmail (checkForm.email, relaxed)
	     && checkEmail (checkForm.email2, relaxed));
}

function submitAffiliatesJoin (checkForm) {
	return (checkRequiredFields(checkForm) 
	     && checkUsername (checkForm.username)
	     && checkEmail (checkForm.email));
}

function submitJoin_v2 (checkForm, relaxed) {
	var interimResult = checkRequiredFields(checkForm);
	interimResult = interimResult && checkUsername (checkForm.username);
	interimResult = interimResult && checkPassword (checkForm.password);
	interimResult = interimResult && checkPasswords (checkForm);
	
	interimResult = interimResult && comparePasswordName (checkForm.firstName, checkForm.password);
	interimResult = interimResult && comparePasswordName (checkForm.surname, checkForm.password);
	
	if (typeof valStrings["defaultFirstName"] != "undefined") {
		interimResult = interimResult && checkFirstName (checkForm.firstName);
		interimResult = interimResult && checkSurname (checkForm.surname);
	}
	if (checkForm.email2.value == "[suppressed]") {
		interimResult = interimResult && checkEmail (checkForm.email, relaxed);
	} else {
		interimResult = interimResult && checkEmails (checkForm);
		interimResult = interimResult && checkEmail (checkForm.email, relaxed);
		interimResult = interimResult && checkEmail (checkForm.email2, relaxed);
	}
	if (typeof checkForm.birthDateDay != "undefined") {
		interimResult = interimResult && checkBirthDate (checkForm.birthDateDay);
	}
	if (typeof valStrings["invalidPostCodeFormat"] != "undefined" && checkForm.countryID.options[checkForm.countryID.selectedIndex].value == "uk") {
		interimResult = interimResult && validatePostCodeUK(checkForm.postCode, false, true);
	}
	
	return interimResult;
}

function submitJoin_access (checkForm) {
	return (checkRequiredFields(checkForm) 
		 && checkActivationCode (checkForm.activationCode)
	     && checkPassword (checkForm.password)
	     && checkPasswords (checkForm)
		 && comparePasswordName (checkForm.firstName, checkForm.password)
		 && comparePasswordName (checkForm.surname, checkForm.password));
}

function submitProfile_base (checkForm, relaxed) {
	return (checkRequiredFields(checkForm) 
	     && checkUsername (checkForm.username)
	     && checkEmail (checkForm.email, relaxed)
	     && checkPassword (checkForm.password)
	     && checkPasswords (checkForm)
		 && comparePasswordName (checkForm.firstName, checkForm.password)
		 && comparePasswordName (checkForm.surname, checkForm.password));
}


