$(document).ready(function(){
	$("#submit").click(function(){					   				   
		$(".error").hide();
		var hasError = "false";
		var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
		
		var emailFromVal = $("#emailFrom").val();
		if(emailFromVal == '') {
			$("#emailFrom").after('<span class="error">We really need an email address to be able to contact you.</span>');
			hasError = "true";
		} else if(!emailReg.test(emailFromVal)) {	
			$("#emailFrom").after('<span class="error">This email address does not seem valid.</span>');
			hasError = "true";
		}
		
		var telVal = $("#telNo").val();
				
		var nameVal = $("#name").val();
		if(nameVal == '') {
			$("#name").after('<span class="error">We really need your name to be able to contact you.</span>');
			hasError = "true";
		}
		
		var messageVal = $("#message").val();
		if(messageVal == '') {
			$("#message").after('<span class="error">There is no message.</span>');
			hasError = "true";
		}
		
		var captchaVal = $("#captcha_code").val();
		if(captchaVal == ''){
		    $("#captcha_code").after('<span class="errorCaptcha">Please enter the characters from image.</span>');
		    hasError="true";
		} else {
		    $.ajax({
				type:'GET',
				url:'email/captcha.php',
				data:'code='+captchaVal,
				async: false,
				success: function(data){
		        	if(data!=="1"){
		            	$("#captcha_code").after('<span class="errorCaptcha">The characters you entered don\'t match the image.</span>');
		        		hasError="true";
		            }
				}
			});
		}
		
		if(hasError == "false") {
			$(this).hide();
			$("#sendEmail li.buttons").append('loading...loading...loading');

			$.post("email/sendEmail.php",
   				{ emailFrom: emailFromVal, name: nameVal, telNo:telVal, message: messageVal },
   					function(data){
						$("#sendEmail").slideUp("normal", function() {				   
							
							$("#sendEmail").before('<h2>Thanks</h2><br class="cB" /><p>Your message has been sent and Ian will get in touch shortly.</p>');											
						});
   					}
				 );
		} else {
		    document.getElementById('captcha').src = 'securimage/securimage_show.php?' + Math.random();
		    $("#captcha_code").value="";
		}
		
		return false;
	});						   
});
