/**
 * 
 * Validate Registration Form
 * 
 */

var validate = function() {
	
	/**
	 * Private Methods
	 */
	
	// go though each validation element
	function doValidation(e) {
		
		$("p.invalid").removeClass("invalid");
		
		var form = $(e.target);
		var valid = true;
		
		// required
		$("p.required").each(function() {
			var value = $("input:first,textarea:first", this).val();
			if (value == "") {
				valid = false;
				doInvalid($(this));
			};
		});
		
		$("p.email").each(function() {
			var value = $("input:first,textarea:first", this).val();
			if (!/^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(value)) {
				valid = false;
				doInvalid($(this),"* Please enter a valid Email");
			}; 
		});
		 
		if (!valid) {
			$("p.invalid input:first").focus()
		} else {
			// populate message
			var str = "";
			$("p",form).each(function() {
				if ($("label:first strong",this).length > 0) {
					str += $("label:first strong:first",this).text();
				} else {
					str += $("label:first",this).text();
				}
				str += ":\n";
				if ($("input:first",this).attr("type") == "checkbox") {
					str += $("input:first",this).is(":checked") ? "Yes" : "No";
				} else {
					str += $("input:first",this).val() ? $("input:first",this).val() : "";
				}
				str += $("textarea:first",this).val() ? $("textarea:first",this).val() : "";
				str += "\n\n";
			});
			$("#message").val(str);
		}
		
		return valid;
	}
	
	// make elm invalid
	function doInvalid(elm,msg) {
		elm.addClass("invalid");
		if (msg) {
			$("label:first",elm).text(msg);
		}
	}
	
	/**
	 * Public Methods
	 */
	
	return {
		init: function() {
			$("#regform").submit(doValidation);
		}
	}
}();

$(document).ready(validate.init);