jQuery(document).ready(function() {
	jQuery("#verzenden").click(function() {		
		// Call validation script located at given url and retrieve json object through AJAX.
		$.getJSON('contact/validate', {naam: $("#naam").val(), email: $("#email").val(), vraag: $("#vraag").val()}, function(json) {			
			// remove old messages
			$('#naam-errors').remove();
			$('#email-errors').remove();
			$('#vraag-errors').remove();
			
			// if the response object contains only the boolean true, the form is valid and can be processed
			if(json == true) {
				$('#contact_form').submit();
			} else {
				// loop through the json response object
				$.each(json, function(field, errors) {
					$('#' + field).after('<div id="'+ field +'-errors"></div>');
					
					var count = 0;
					// loop through all errors
					$.each(errors, function(validator, message) {
						// only show the first error
						if (count < 1) {
							// put the error messages next to the corresponding form fields
							$('#'+ field +'-errors').append(message + "<br />");
						} else {
							return false;
						}
						count++;
					});
				});
			}
		});
		
		return false;
	});
});
