/*
	File:		validate.js
	Author:		Dan Soppelsa, Lucid Media
	Date:		August 11, 2011

	Description:	provides client side validation for the login form
*/
window.onload = pageloaded;
var userEmailBox = "";		// the user name (e-mail address) input field
var userPassBox = "";		// the password input field
var errMessage = "";		// the error message to be displayed if there are login difficulties

var userEmail = "";			// the text of the user name input field
var userPass = "";			// the text of the password input field


var comment = "";		// the comment text
var form = "";		// the document's form


// Executes when the page is loaded, initializes variables
function pageloaded() {

	// Get the user name and password boxes
	userEmailBox = document.getElementById("user");
	userPassBox = document.getElementById("password");
	errMessage = document.getElementById("login_err_message");
			
	// get the form to be validated		
	form = document.getElementById("login_form");
	
	// when the form is submitted, validate it (client side)
	form.onsubmit = validate_form;

	if(window.location.search.length != 0) {
		errMessage.style.display = "block";	
	}
} // end function pageloaded


// Validates the form on submission
function validate_form() {
	userEmail = userEmailBox.value;
	userPass = userPassBox.value;
		
	var message = "There are errors on the form:\n\n";		// the message to be output to the user if there are errors on the form
	var formIsValid = true;
	
	// check to ensure a proper email address submitted
	
	// check to see that the user name is a proper e-mail address
	// in the form [YOURNAME]@[DOMAIN].[EXTENSION]
	if(!validEmail(userEmail))
	{	
		userEmailBox.style.backgroundColor = "yellow";
		message += "- Please enter a proper user name (email address) in the form:\n\t\tyourname@domain.com\n";
		userEmailBox.focus();
		formIsValid = false;	
	} // end if
	
	
	// check to see that a password in the proper format(6-20 characters) has been entered.
	// this does not necessarily mean that the password is valid.
	
	// password fails on: contains space, outside of range 6-20 characters
	if((userPass.indexOf(" ") >= 0) || (userPass.length < 6) || (userPass.length > 20)) {
		
		userPassBox.value = "";
		userPassBox.style.backgroundColor = "yellow";
		message += "- Please enter a password in the proper format (6-20 characters, no spaces)\n";
		
		if(formIsValid)
			userPassBox.focus();
			
		formIsValid = false;
	}
	
	
	if(formIsValid) {
		return true;
	}
	else
	{
		document.getElementById("login_err_message").style.display = "block";
		alert(message);
		return false;			
	} // end else
	
} // end function validate_form

function validEmail(email) {
	var regEx = /^\w[-._\w]*\w@\w[-._\w]*\w\.\w{2,8}$/;
	return regEx.test(email);
}




