// ------------------------------------------
// Rutting Reds Venison
// validation.js
//
// jQuery Document
// Contains functions and events for form
// validation on the contact us page.
//
// Copyright (c) Brave Creative
// bravecreative.co.uk
// ------------------------------------------

/* Valid Email Address RegExp */
function checkEmail(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
};

$(function() {

/* Hide Errors */
$('.error').hide();

/* For xbrowser */
$('input, textarea').focus(function(){$(this).css({backgroundColor:"#FFF", border:"#000 1px solid"});});
$('input, textarea').blur(function(){$(this).css({backgroundColor:"#FBFBFB", border:"#999 1px solid"}).removeClass('contact-input-error'); $('.error').hide();});

/* Begin */

	$('.send-contact').live('click', function(){

		$('.error').hide();
		$('input').removeClass('contact-input-error');
		
		/* Values */
		var name = $('#name').val();
		var email = $('#email').val();
		var msg = $('#msg').val();		

		/* Validate Fields */
	
		if(name == '') {  
			$('#name-error').show();
			$('#name').focus().addClass('contact-input-error');
			return false;
		}
		
		if(email == '') {  
			$('#email-error').show();
			$('#email').focus().addClass('contact-input-error');
			return false;
		}	
		
		if(!checkEmail(email)) {
			$('#email-error-valid').show();
			$('#email').focus().addClass('contact-input-error');
			return false;		
		}	
		
		if(msg == '') {
			$('#msg-error').show();
			$('#msg').focus().addClass('contact-input-error');
			return false;		
		}
		
		// If all goes well send off ajax! 
		// PHP will do the server side validation and return the results
		
		var dataString = 'name='+ name + '&email=' + email + '&msg=' + msg;
		
		$.ajax({
      		type: "POST",
      		url: "http://www.stonehouseaccountants.com/ajax/send-email.php",
      		beforeSend: function() {$('#contact-form div').stop().animate({opacity: 0.25}, 300); $('#loader').show();},
      		data: dataString,
      		success: function(data) {
      			$('#loader').hide();
      			$('#contact-form div').hide().animate({opacity: 1}, 300).empty().append(data).slideDown(500);
			},
			error: function() {alert('An unexpected error has occurred! Please try again.'); location.reload();}
     	});
     	
     	return false;
     		
	});

});
