$(document).ready(function(){

	function validateEmail(email) {

		var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
		if(reg.test(email) == false) {
			return false;
		} else {
			return true;
		}

	}

	function submitForm() {

		var fCheck = true;
		var thisRel = "";
		var thisName = "";
		var thisVal = "";

		$("div[name$='Error']").fadeOut(500);

		// first check the selected courses
        var $fields = $("input[name='course[]']:checked");
        if (!$fields.length) {
            alert('You must select at least 1 course');
			fCheck = false;
            return false;
		}


		if ( fCheck ) {
			// check each required field
			$("[name^='item']").each( function() {
				thisRel = $(this).attr("rel");
				thisName = $(this).attr("name");
				thisVal = $(this).attr("validate");
				if ( thisRel == "1" ) {
					if ( $(this).val() == "" ) {
						$("[name='e" + thisName + "Error']").html("required");
						$("[name='e" + thisName + "Error']").fadeIn(500);
						$(this).focus();
						fCheck = false;
						return false;
					} else {
						if ( thisVal == "email" ) {
							if ( !validateEmail($(this).val()) ) {
								$("[name='e" + thisName + "Error']").html("not a valid email address");
								$("[name='e" + thisName + "Error']").fadeIn(500);
								$(this).focus();
								fCheck = false;
								return false;
							}
						}
					}
				}
			});
		}

		if ( fCheck ) {
			return true;
		}

	}

	$("#submitBtn").click(function() {
		if ( submitForm() ) {
			return true;
		} else {
			return false;
		}
	});

});
