// Client-side validation of the signup page!

var VALIDATE = []; // map of validation values

var default_msg = "Invalid Characters";
var alphanumeric = /^([a-zA-Z0-9]+ *)+$/;

// fields to validate
VALIDATE["username_regex"] = alphanumeric;
VALIDATE["username_msg"] = default_msg;

VALIDATE["password_regex"] = /^([a-zA-Z0-9#$&@]+ *){4,12}$/;
VALIDATE["password_msg"] = default_msg;

// I don't think this is ever called b/c pass0 is just compared to pass
VALIDATE["password2_regex"] = /^([a-zA-Z0-9#$&@]+ *){4,12}$/;
VALIDATE["password2_msg"] = default_msg;

VALIDATE["fname_regex"] = alphanumeric;
VALIDATE["fname_msg"] = default_msg;

VALIDATE["lname_regex"] = alphanumeric;
VALIDATE["lname_msg"] = default_msg;

VALIDATE["email_regex"] = /^[\w\.%\-]+@[\w.\-]+\.[a-zA-Z]{2,4}$/;
VALIDATE["email_msg"] = "E-mail must be in the form: user@domain.com.";

VALIDATE["recruiter_regex"] = alphanumeric;
VALIDATE["recruiter_msg"] = default_msg;


document.observe("dom:loaded", function() {

	// watches for a submission, then validates
	$("signup").observe("submit", validate);
	
	// individual input validation as the users fills out the form
	$$("#signup input").invoke("observe", "change", checkThisField);
});

// Validates each of the input fields in the form
function validate(event) {

	var valid = true;

/*	// there are not bad input notices or if there is one it's the one sitting on the submit button from a previous failed attempt
	var valid = $$("#signup input.inputBad").size() == 0 || ($$("#signup input.inputBad").size() == 1 && $("submit").hasClassName("inputBad"));
	
	// empty out password boxes if they fail on submit
	if (!valid && $$("#signup input[type='password']")[0].value != $$("#signup input[type='password2']")[0].value) {
		$$("#signup input[type='password']")[0].value = "";
		$$("#signup input[type='password2']")[0].value = "";
	}
*/	
	// go through all the input fields and check them, except the username because it's slow due to ajax
	$$("#signup input").each(
		function(piece) {
			if(piece.name != "username" && piece.value != "" && piece.name != "recruiter") {
				if(!checkField(piece)) {
					valid = false;
				}
										     // recruiter is not a required field
			} else if (piece.value == "" && piece.name != "recruiter") { // field is empty, but needs to be filled
				showError(piece, "Missing information");
				valid = false;
			}			
		});
	
	// if all is good, submit!
	
	var form = $("signup");
	if(valid) {
		clearError($("submit"));
		// let the form submit		
	} else {
		// stop submission
		Event.stop(event);	
		showError($("submit"),
			"There are some problems with your registration. Please look over your form  and try again.");
	}	
}

function checkThisField(event) {
	checkField(this);
}

// validates each input field after it is filled in
// immediately shows error if the input value is bad
// returns true if valid, false if invalid
// can pass an optional submitting parameter which by default is false
function checkField(field, submitting) {

	var value = field.value;
	//var asynch = submitting ? false : true;
	
	// check all non submit/reset/checkbox input values
	if(field.type != "submit" && field.type != "reset" && field.type != "checkbox") {
		if (field.name == "password2") {
			// passwords must match
			if($$("input[name='password']")[0].value != value) {
				showError(field, "Passwords do not match");
				return false;
			} else {
				clearError(field);
				return true;
			}
		} else if (!value.match(VALIDATE[field.name + "_regex"]) && value != "") {
			// show error only if it hasn't been shown before
			var msg = VALIDATE[field.name + "_msg"];
			showError(field, msg);
			return false;
		} else if (field.name == "username") {
			// make an AJAX request to check if the username exists
			new Ajax.Request("checkUsername.php?username=" + value,	{	
			
				method: "post",	
				//asynchronous: asynch,
				onSuccess: function () { 
					clearError(field);
					return true;
				},
				onFailure: function() {
					showError(field, "Username already exists.");
					return false;
				}
			});
		} else if (value != "" && field.name == "recruiter") {
			// make an AJAX request to check if the username exists
			new Ajax.Request("checkUsername.php?username=" + value,	{	
			
				method: "post",	
				//asynchronous: asynch,
				onSuccess: function () { 
					showError(field, "Recruiter's username does not exist.");
					return false;
				},
				onFailure: function() {
					clearError(field);
					return true;
				}
			});
		} else {
			clearError(field);
			return true;
		}
	} else {
		return true;
	}
}

// shows that the given field has an error and the associated message
function showError(field, message) {
	if(!field.hasClassName("inputBad")) {
		field.addClassName("inputBad");
		var errorMsg = document.createElement("span");
		errorMsg.textContent = message;
		errorMsg.addClassName("errorMsg");
		field.parentNode.appendChild(errorMsg);
	// when missing info has been filled in but does not validate, just change the message
	} else if (field.hasClassName("inputBad") && field.next().textContent == "Missing information") {
		field.next().textContent = message;
	}
}

// the field has been fixed and should no longer show an error
function clearError(field) {
	if(field.hasClassName("inputBad")) {
		field.removeClassName("inputBad");
		var last = field.parentNode.lastChild;
		if(last.hasClassName("errorMsg")) {
			field.parentNode.removeChild(last);
		}
	}
}

