function validateEmail(email) {
	var pattern = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/g;
	return pattern.test(email);
}

function displayError(message, timeout) {
	if(message) {
/*
		$('.msgBox').addClass('error').text(message);
		$('.msgBox').show(0, function() {
			if(timeout && !isNaN(timeout) && timeout > 0) {
				window.setTimeout(function() {
					$('.msgBox').fadeOut('normal');
				}, timeout);
			}
		});
		window.scrollTo(0, $('.msgBox').position().top);
*/
		alert(message);	
	}
/*
	else {
		$('.msgBox').hide();
	}
*/
}

function displayMessage(message, timeout) {
	if(message) {
		$('.msgBox').removeClass('error').text(message);
		$('.msgBox').show(0, function() {
			if(timeout && !isNaN(timeout) && timeout > 0) {
				window.setTimeout(function() {
					$('.msgBox').fadeOut('normal');
				}, timeout);
			}
		});
		window.scrollTo(0, $('.msgBox').position().top);
	}
	else {
		$('.msgBox').hide();
	}
}

function validateForm(form) {
	var valid = true;
	$('.error:input').removeClass('error');
	
	// validate any input elements that have a name attribute
	form.find(':input').each(function(i) {
		if($(this).hasClass('required') && !$(this).val()) {
			$(this).addClass('error');
			valid = false;
		}
		else if($(this).hasClass('email') && $(this).val() && !validateEmail($(this).val())) {
			displayError("Please enter a valid email address.");
			$(this).addClass('error');
			valid = false;
		}
	});
	
	$(':input.error:first').focus();
	
	return valid;
}

$(document).ready(function() {
	$('#contact-form').submit(function(event) {
		event.preventDefault();
		try {
			var form = $(this);
			
			if(validateForm(form)) {
				var safetyCheck = 
					$('<input>')
						.attr('type','hidden')
						.attr('name','safety_check');
				safetyCheck.val('true');
				form.append(safetyCheck);
				
				var request = form.serialize();
				
				$.post('contact.php', request, function(response) {
					if(response.success) {
						window.location = 'newsletter-submit.php';
					}
					else {
						if(typeof console == 'object' && typeof console.error == 'function') {
							console.error(response.error_msg);
						}
					}
				}, 'json');
			}
		}
		catch(e) {
			if(typeof console == 'object' && typeof console.error == 'function') {
				console.error(e);
			}
		}
		
		return false;
	});
});
