/* Feedback form script */

var maxChars = 3000, cc, msg;

function updateCharCount() {
	if (cc && msg) {
		cc.innerHTML = "(" + (maxChars - msg.value.length) + " characters remaining)";
	}
}

function initFeedback() {
	cc = document.getElementById("charCount");
	msg = document.getElementById("msg");
	updateCharCount();	
}
initFeedback();

function isBlank(str) {
	return (!str || str=="");
}

function isValidEmail(str) {
	str = str.replace(/^\s+|\s+$/g, ''); //trim whitespace
	var filter  = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})$/;
	return (filter.test(str));
}

function markLabel(field, isError) {
	var labelB = field.parentNode.getElementsByTagName("b")[0];
	labelB.className = isError ? "error" : "";
}

function validateForm(f) {
	var error = new Array(0);
	var from_email = f.from_email.value;
	var subj = f.subj.value;
	var msg = f.msg.value;
	
	if (isBlank(from_email)) {
		error.push("<b>Email Address:</b> Your e-mail address is required");
		markLabel(f.from_email, true);
	}
	else if (!isValidEmail(from_email)) {
		error.push("<b>Email Address:</b> Invalid email.  Your address must be in the format 'name@domain.com'");
		markLabel(f.from_email, true);
	}
	else {
		markLabel(f.from_email, false);
	}
	
	if (isBlank(subj)) {
		error.push("<b>Subject:</b> Please select a subject");
		markLabel(f.subj, true);
	}
	else {
		markLabel(f.subj, false);
	}
	
	if (msg.length > 3000) {
		error.push("<b>Message:</b> Your message must be 3000 characters or less.");
		markLabel(f.msg, true);
	}
	else {
		markLabel(f.msg, false);
	}
	
	if (error.length > 0) {
		var errorPrint = "";
		for (var i = 0; i < error.length; i++) {
			errorPrint += error[i];
		}
		
		var errorBox = document.getElementById("errorBox");
		if (errorBox) {
			var errorHTML = '<div class="errorMsgs"><ul>';
			for (var i = 0; i < error.length; i++) {
				errorHTML += '<li>' + error[i] + '</li>';
			}
			errorHTML += '</ul></div>';
		}
		errorBox.innerHTML = errorHTML;
		
		return false;
	}
	return true;
}