//	jQuery-Actions for Contact Form
//	Version 1.0
/*
	-- CHANGELOG --
	2010-03-11: Added extra comments for readability.
	-- --------- --
*/

// WAIT FOR PAGE TO LOAD
$(document).ready(function() {
	
	// CHECK EMAIL FUNCTION
	function validateEmail(e) {
		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(e);
	}
	
	// Set validEmail
	var validEmail=1;
	
	// WHEN USER SELECTS ANOTHER FIELD
	$('#contactForm :input').blur(function() {
										   
		// Check if field is email
		if ($(this).attr('name')=='email')
		{
			// If field is email, check for valid address
			var e=validateEmail($(this).val());
			if (e==0)
			{
				// If not valid, show red border
				$(this).css('borderBottom', '1px solid red');
				
				// Update validEmail
				validEmail=2;
			}
			else
			{
				// If valid, show green border
				$(this).css('borderBottom', '1px solid green');
				
				// Update validEmail
				validEmail=1;
				
				// Remove error message
				$(this).next().remove();
			}
		}
		
		// Check other fields
		else if ($(this).attr('class')=='required' && $(this).val()==0)
		{
			// If empty, show red border
			$(this).css('borderBottom', '1px solid red');
		}
		else if ($(this).attr('class')=='required')
		{
			// If not empty, show green border
			$(this).css('borderBottom', '1px solid green');
			
			// Remove error message
			$(this).next().remove();
		}
		
		// If previous field is not required, do nothing
	});
	
	// WHEN USER SUBMITS FORM
	$('#contactForm #submit').click(function() {
											 
		// Define result true, then change to false if error is found
		var result=true;
		
		// Remove existing errors
		$('.error').remove();
		
		// Get field inputs
		var inputs=$('#contactForm :input');
		
		// Empty field container
		var empty={};
		
		var i=0;
		
		// For each input ...
		inputs.each(function() {
			
			// If field is required
			if ($(this).attr('class')=='required')
			{
				// If field is email, check validation
				if ($(this).attr('name')=='email' && validEmail==2) {
					empty[i]='email';
					$(this).css('borderBottom', '1px solid red');
					
					// Flag result as false
					result=false;
					i++;
				}
				
				// If field is not email ...
				else if ($(this).val()==0)
				{
					empty[i]=$(this).attr('name');
					$(this).css('borderBottom', '1px solid red');
					
					// Flag result as false
					result=false;
					i++;
				}
			}
		});
		
		// Return result
		return result;
	});
	
});