// --------------------------------------------------------------------
//	forms.js
//	Javscript functions used to validate html form inputs
//
//	Version	Date		Reason
//	0.1		2-Nov-2007	First draft
//	0.2		5-Nov-2007	Includes checkIfDefaultText
//	2.0		19-Mar-2009 Rewrite as object libraries and remove all onevent handlers from html
// --------------------------------------------------------------------

var formValidations = {
	emptyString : /^\s*$/, 	//	var emptyString = /^\s*$/;

	checkIfDefaultText : function (inputfield, defaulttext) {
		if (inputfield.value === defaulttext) {
			return true;
		} else {
			return false;
		}
	}, 

	setFocus : function (inputfield) {
		// return focus to the input field with a 100ms delay to accomodate IE timing bug
		// pass the function to be executed after a timeout as a function rather than a string, to avoid an unnecessary implicit eval;
		// TBD: if IE4, pass a string (doesn't work as a function in IE4...), else pass a function
		setTimeout( function () { inputfield.focus(); }, 100 ); 
	},

	updateInfoField : function (infofield, messagetype,	message) {
		// infofield = id of html element to display information, warning or error message
		// messagetype = class to give infofield element, information, warning or error
		// message = message string to display in infofield
		// Display "message" of "messagetype", informational, warning or error message, in "infofield"
		// Some browsers have a problem with empty elements, so place a non-breaking space here, if empty 
		var nbsp = 160; // non-breaking space character
		var element;
		
		if (formValidations.emptyString.test(message)) {
			message = String.fromCharCode(nbsp);
		}
		element = Base.byId(infofield);
		if (typeof element.firstChild !== "undefined") {
			element.firstChild.nodeValue = message;
		} else {
			element.value = message;
		}
		element.className = messagetype;   // set the CSS class to adjust appearance of message
	},

	validateIsNotEmpty : function (inputfield, infofield, fieldname, inputrequired) {
	// inputfield = id of html form field element to be validated
	// infofield = id of html element to display information, warning or error message
	// fieldname = text string giving name of the field for display in error message
	// inputrequired = flag to indicate whether field is required input - true if required
	// validateisNotEmpty validates that something has been entered into the field
	// returns true if field is not empty
	// returns false if the field is empty
	if (formValidations.emptyString.test(inputfield.value)) {
			if (inputrequired) {
				formValidations.updateInfoField(infofield, "error", " Error: " + fieldname + " is required.");  
				formValidations.setFocus(inputfield);
				return false;
			} else {
				formValidations.updateInfoField(infofield, "information", "");   // OK
				return false;  
			}
		}
		formValidations.updateInfoField (infofield, "information", "");  
		return true;
	},

	validateEmail : function (inputfield, infofield, fieldname, inputrequired) {
	// inputfield = id of html form field element to be validated
	// infofield = id of html element to display information, warning or error message
	// fieldname = text string giving name of the field for display in error message
	// inputrequired = flag to indicate whether field is required input - true if required
	// validateEmail validates that a plausible email address has been entered
	// returns true if field is a plausible email address
	// returns false if the field is not
		var tfld = inputfield.value.trim();  // value of field with whitespace trimmed off
		var validemail = /^[^@]+@[^@.]+\.[^@]*\w\w$/  ;
		if (!formValidations.validateIsNotEmpty(inputfield, infofield, fieldname, inputrequired)) { 
			return !inputrequired;
		}
		if (!validemail.test(tfld)) {
			formValidations.updateInfoField(infofield, "error", " Error: not a valid e-mail address");
			formValidations.setFocus(inputfield);
			return false;
		}
		validemail = /^[A-Za-z][\w.-]+@\w[\w.-]+\.[\w.-]*[A-Za-z][A-Za-z]$/  ;
		if (!validemail.test(tfld)) {
			formValidations.updateInfoField(infofield, "warning", " Unusual e-mail address - check if correct");
		} else {
			formValidations.updateInfoField(infofield, "information", "");
		}
		return true;
	},

	validateTelephoneNumber : function (inputfield, infofield, fieldname, inputrequired) {
	// inputfield = id of html form field element to be validated
	// infofield = id of html element to display information, warning or error message
	// fieldname = text string giving name of the field for display in error message
	// inputrequired = flag to indicate whether field is required input - true if required
	// validateTelephoneNumber validates that a plausible telephone number has been entered
	// Returns true if field is a plausible telephone number
	// Permits spaces, hyphens, brackets and leading +
	// Returns false if the field is not
		var tfld = inputfield.value.trim();  // value of field with whitespace trimmed off
		var telnr = /^\+?[0-9 ()-]+[0-9]$/;
		var numdigits = 0;
		var j; 
		if (!formValidations.validateIsNotEmpty(inputfield, infofield, fieldname, inputrequired)) { 
			return !inputrequired;
		}
		if (!telnr.test(tfld)) {
			formValidations.updateInfoField (infofield, "error", " Error: Use digits, space, ( ) - and leading + only.");
			formValidations.setFocus(inputfield);
			return false;
		}
		for (j=0; j<tfld.length; j++) {
			if (tfld.charAt(j)>='0' && tfld.charAt(j)<='9') numdigits++;
		}
		if (numdigits<10) {
			formValidations.updateInfoField (infofield, "error", " Error: Only " + numdigits + " digits - please include area code");
			formValidations.setFocus(inputfield);
			return false;
		}
		if (numdigits>14) {
			formValidations.updateInfoField (infofield, "warning", " " + numdigits + " digits - check if correct");
		} else {
			formValidations.updateInfoField (infofield, "information", "");
		}
		return true;
	}
};

var contactForm = {
	init: function () {
		Base.addEventListener(Base.byId('contact_form'), 'submit', contactForm.validateOnSubmit);
		Base.addEventListener( Base.byId('subject'), 'change', function () { formValidations.validateIsNotEmpty(this, 'info_field_subject', 'subject', true); } );
		Base.addEventListener( Base.byId('subject'), 'focus', function () { if(formValidations.checkIfDefaultText(this, 'The West London Irish Society')) { this.select(); } } );
		Base.addEventListener( Base.byId('realname'), 'change', function () { formValidations.validateIsNotEmpty(this, 'info_field_realname', 'your name', true); } );
		Base.addEventListener( Base.byId('email'), 'change', function () { formValidations.validateEmail(this, 'info_field_email', 'your email address', true); } );
		Base.addEventListener( Base.byId('phone'), 'change', function () { formValidations.validateTelephoneNumber(this, 'info_field_telnr', 'your telephone number', false); } );
		Base.addEventListener( Base.byId('message'), 'change', function () { formValidations.validateIsNotEmpty(this, 'info_field_message', 'message', true); } );
		Base.addEventListener( Base.byId('message'), 'focus', function () { if(formValidations.checkIfDefaultText(this, '[your message...]')) { this.select(); } } );
		document.forms['contact_form'].subject.focus();
	},
	validateOnSubmit: function (event) {
		var errors=0;
		// execute all element validations in reverse order, so focus gets set to the first one in error.
		// validate message
		if (!formValidations.validateIsNotEmpty(document.forms['contact_form'].message, 'info_field_message', 'message', true)) {
			errors++;
		}
		if (formValidations.checkIfDefaultText(document.forms['contact_form'].message, '[your message...]')) {
			formValidations.updateInfoField('info_field_message', "error", " Error: message is required.");  
			errors++;
		} 
		// address - no validation
		// validate telephone number
		if (!formValidations.validateTelephoneNumber(document.forms['contact_form'].phone, 'info_field_telnr', 'your telephone number', false)) {
			errors++;
		}
		// validate email address
		if (!formValidations.validateEmail(document.forms['contact_form'].email, 'info_field_email', 'your email address', true)) {
			errors++;
		}
		// validate name
		if (!formValidations.validateIsNotEmpty(document.forms['contact_form'].realname, 'info_field_realname', 'your name', true)) {
			errors++;
		}
		// recipient - no validation necessary as uses radio buttons 
		// validate subject
		if (!formValidations.validateIsNotEmpty(document.forms['contact_form'].subject, 'info_field_subject', 'subject', true)) {
			errors++; 
		}
		if (errors > 1) {
			alert('There are fields which need correction before sending');
		} else if (errors==1) {
			alert('There is a field which needs correction before sending');
		}
		if (errors > 0) {
			Base.preventDefault(event);			
		}
		return (errors==0);
	}
};
Base.start(contactForm);