// JavaScript Document
$(document).ready(function(){
	$("#submit").click(function(){					   				   
		$(".error").hide();
		var hasError = false;
		var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
		var phoneReg = /^[(2-9][0-9)]{2,4}[\s-][0-9]{2,3}[\s-][0-9]{4}$/;
		var testQuestionAnswer= "10";
		
		/*var emailToVal = $("#emailTo").val();
		if(emailToVal == '') {
			$("#emailTo").after('<span class="error">You forgot to enter the email address to send to.</span>');
			hasError = true;
		} else if(!emailReg.test(emailToVal)) {	
			$("#emailTo").after('<span class="error">Enter a valid email address to send to.</span>');
			hasError = true;
		}*/
		
		var fullNameVal = $("#fullName").val();
		if(fullNameVal == '') {
			$("#fullName").after('<span class="error">Please enter your name.</span>');
			hasError = true;
		}
		
		var emailFromVal = $("#emailFrom").val();
		if(emailFromVal == '') {
			$("#emailFrom").after('<span class="error">Please enter your email address.</span>');
			hasError = true;
		} else if(!emailReg.test(emailFromVal)) {	
			$("#emailFrom").after('<span class="error">Enter a valid email address.</span>');
			hasError = true;
		}
		
		var phoneVal = $("#phone").val();
		if(phoneVal == '') {
			$("#phone").after('<span class="error">Please provide your phone number with area code</span>');
			hasError = true;
		} else if(!phoneReg.test(phoneVal)) {	
			$("#phone").after('<span class="error">Phone number must be in the format xxx-xxx-xxxx</span>');
			hasError = true;
		}
		
		var subjectVal = $("#subject").val();
		if(subjectVal == '') {
			$("#subject").after('<span class="error">You forgot to enter the subject.</span>');
			hasError = true;
		}
		
		var testQuestionVal = $("#testQuestion").val();
		if(testQuestionVal == '') {
			$("#testQuestion").after('<span class="error">Answering this question helps us know you\'re a person and not a spammer.</span>');
			hasError = true;
		} else if(testQuestionVal !== testQuestionAnswer) {	
			$("#testQuestion").after('<span class="error">Oops! Your math is a bit off - Try again.</span>');
			hasError = true;
		}
		
		var messageVal = $("#message").val();
		if(messageVal == '') {
			$("#message").after('<span class="error">You forgot to enter the message.</span>');
			hasError = true;
		}
		
		
		if(hasError == false) {
			$(this).hide();
			$("#sendEmail li.buttons").append('<img src="http://www.mediajar.com/klim_test/klim_snow/contact/loading.gif" alt="Loading" id="loading" />');
			
			$.post("sendemail.php",
   				{ fullName: fullNameVal, emailFrom: emailFromVal, phone: phoneVal, subject: subjectVal, message: messageVal },
   					function(data){
						$("#sendEmail").slideUp("normal", function() {				   
							
							$("#sendEmail").before('<h1>Success</h1><p>Your email was sent.</p>');											
						});
   					}
				 );
		}
		
		return false;
	});						   
});
