// JavaScript Document

// 1.0 Focused input decoration
sfFocus = function() {
	var sfEls = document.getElementsByTagName("input");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onfocus=function() {
			this.className+=" sffocus";
		}
		sfEls[i].onblur=function() {
			this.className=this.className.replace(new RegExp(" sffocus\\b"), "");
		}
	}

	var sfEls_new = document.getElementsByTagName("textarea");
	for (var i=0; i<sfEls_new.length; i++) {
		sfEls_new[i].onfocus=function() {
			this.className+=" sffocus";
		}
		sfEls_new[i].onblur=function() {
			this.className=this.className.replace(new RegExp(" sffocus\\b"), "");
		}
	}
}
if (window.attachEvent) window.attachEvent("onload", sfFocus);


// 2-0 form validation
function validateForm(){
	// Make quick references fields
	var name = document.getElementById('txtName');
	var email = document.getElementById('txtEmail');
	var message = document.getElementById('txtMessage');

	
	// Check each input in the order that it appears in the form!
	if(validateName(name, "Please check your input for this field:\n\n\t name \n\n (only apostrophes, letters, hyphens, and spaces are accepted)")) {
		if(validateEmail(email, "Please check your input for this field:\n\n\temail\n\n (only a valid email format is accepted)")){
			if (validateMessage(message, "Please check your input for this field:\n\n\tmessage\n\n (only plain text is accepted)")) {
				return true;
			}
		}
	}
	
	return false;	
}

// 2-1
function validateName(elem, helperMsg){
	var alphaExp = /^[a-zA-Z]+(([\ \'\,\.\-][a-zA-Z])?[a-zA-Z]*)*$/;
	if(elem.value.match(alphaExp)){
		return true;
	}else{
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

// 2-2
function validateMessage(elem, helperMsg){
	if(elem.value.length == 0){
		alert(helperMsg);
		elem.focus(); // set the focus to this input
		return false;
	}
	return true;
}

// 2-3
function validateEmail(elem, helperMsg){
	var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
	if(elem.value.match(emailExp)){
		return true;
	}else{
		alert(helperMsg);
		elem.focus();
		return false;
	}
}