$(document).ready(function(){
	$("#register").submit(function(){
		return validate(); // The form will only submit if validate returns true
	});
});

function validate(){
	// Validate the form here
	
	$('.fieldRequired').each(function(i){
		$(this).removeClass('fieldRequired');
	});
	
	var errorText = '';

	// This will cycle through DOM looking for lables, from there it will cycle through their inputs checking for if they are required or validEmail
	// If something doesn't validate it will display an alert using the label and add a class that can be styled to represent it needs atention
	$('label').each(function(i){
		var field = $(this).text();
		$('#'+$(this).attr('for')+'.required').each(function(i){
			if( $(this).val() == '' ){
				errorText = errorText + " \n\r" + field + " is required";
				$(this).addClass('fieldRequired');
			}
		});
		$('#'+$(this).attr('for')+'.validEmail').each(function(i){
			if( !isEmailValid($(this).val()) ){
				errorText = errorText + " \n\r" + field + " must be valid";
				$(this).addClass('fieldRequired');
			}
		});
	});
	
	if (errorText != ''){
		alert("Sorry there are the following issues with your details: \n\r"+errorText);
		return false;
	}else{
		return true;
	}
}

function isEmailValid(str)
{
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	return reg.test(str);
}
