var inputfieldErrorBGColor = '#ffe0e0';
var inputfieldErrorLabelColor = 'red';

function trim (str) {
	return str.replace(/(^[\n\s]+)|([\n\s]+$)/g, ""); 
}

function isFieldInvalid(fieldId, labelId) {
	var x = document.getElementById(fieldId);
	var y = document.getElementById(labelId);
	if (!x || trim(x.value) == "") {
		if (x)
			x.style.backgroundColor = inputfieldErrorBGColor;
	
		if (y)
			y.style.color = inputfieldErrorLabelColor;
		
		return 1; 
	} else {
		if (x)
			x.style.backgroundColor = '';
		
		if (y)
			y.style.color = '';
	}
	
	return 0;
}

function checkFields() {
	var emptyFields = 0;

	emptyFields += isFieldInvalid('username', 'usernameLabel');
	emptyFields += isFieldInvalid('useremail', 'useremailLabel');
	emptyFields += isFieldInvalid('usermessage', 'usermessageLabel');
	
	x = document.getElementById('errorText');
	if (emptyFields > 0) {
		if (x) {
			x.innerHTML = 'Please fill in the field' +
				((emptyFields > 1)?'s':'') + ' marked in red!';
		}
		
		return false;
	} else if (x)
		x.innerHTML = '';
	
	// ok, all fields are filled out, now check wether the email
	// address has the correct form...
	
	var y = document.getElementById('useremail');
	var z = document.getElementById('useremailLabel');
	if (y && !(/^[^\@]+\@[^\@\.]+\.[^\.].+$/).test(y.value)) {
		if (y)
			y.style.backgroundColor = inputfieldErrorBGColor;
		
		if (z)
			z.style.color = inputfieldErrorLabelColor;
			
		if (x)
			x.innerHTML = 'Please check that you didn\'t mistype your email address!';
		
		return false;
	} else {
		if (x)
			x.innerHTML = '';
		
		if (y)
			y.style.backgroundColor = '';
		
		if (z)
			z.style.color = '';
	}
	
	return true;
}
