$(document).ready(function(){
	$("#contact").submit(function(){
		var hasError = false;
		var emailReg = /^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$/;
		
		var nomVal = $("#nom").val();
		if(nomVal == ""){
			if(!$("#nom").next().is(".error")){
				$('<span class="error">Please enter your name.</span>').insertAfter("#nom").css("display", "none").fadeIn(300);
			}
			hasError = true;
		} else if($("#nom").next().is(".error") && nomVal != ""){
			$("#nom").next().remove();
		}
		
		var emailVal = $("#email").val();
		if(emailVal == "") {
			if($("#email").next().is(".error")){
				$("#email").next().replaceWith($('<span class="error">Please enter your email.</span>'));
			} else {
				$('<span class="error">Please enter your email.</span>').insertAfter("#email").css("display", "none").fadeIn(300);
			}
			hasError = true;
		} else if(!emailReg.test(emailVal)) {
			if($("#email").next().is(".error")){
				$("#email").next().replaceWith($('<span class="error">Please enter a valid email.</span>'));
			} else {
				$('<span class="error">Please enter a valid email.</span>').insertAfter("#email").css("display", "none").fadeIn(300);
			}
			hasError = true;
		}
		
		var questionsVal = $("#questions").val();
		if(questionsVal == ""){
			if(!$("#questions").next().is(".error")){
				$('<span class="error">Please enter your question!</span>').insertAfter("#questions").css("display", "none").fadeIn(300);
			}
			hasError = true;
		} else if($("#questions").next().is(".error") && questionsVal != ""){
			$("#questions").next().remove();
		}
		
		if(hasError == false) {
			$("#bottomRightBottom").empty().append('<br /><img src="../static/loading.gif" alt="Loading..." id="loading" />');
			
			$.post("sendemail.php", {nom: nomVal, email: emailVal, questions: questionsVal}, function(data){
					$("#bottomRightBottom").fadeOut(300, function(){
						$(this).empty().append("<p>Your message was successfully sent.</p>").fadeIn(300);
					});
				}
			);
		}

		return false;
	});
});
