
var formValidation = function(targetForm){
	
	var $myForm = $(targetForm);
	var $allRequiredFields = $(targetForm + ' .required')
	var errorMessage = '';
	var errorVisible = false;
	var allErrorFields = new Array;
	
	// *** Private methods *** //	
	$myForm.submit(function(){

		if(validateFields()){			
			return true;
			
		} else {
			return false;
		}
		
	});
	
	function validateFields(){

		var valid = true;
		
		
		
		$allRequiredFields.each(function(){
			var $thisField = $(this);
			
			resetCSS($thisField);
			
			if($thisField.is('#email')){
				
				if(this.value != '' && !/.+@.+\.[a-zA-Z]{2,4}$/.test(this.value)){					
				
					valid = false;
					errorMessage = 'Your email is invalid.';
					displayError($thisField);
				}			
			}
			
			if ($thisField.val() ==''){
				
				allErrorFields.push($thisField.attr('name'));
				errorMessage = 'This field is required. Please enter a value.';
				displayError($thisField);
				valid = false;
			}
		});
		
		return valid;
	}
	
	function displayError($targetObj){
		
		var $thisObj = $targetObj;
		
		$thisObj.parent().css('background', '#ffdfdf');
		$thisObj.parent().css('margin-top', '6px');
		$thisObj.parent().find('label').css('color', 'red');
		
		var myError = errorMessage;
		
		$thisObj.parent().find('p.error-message').empty();
		$thisObj.parent().find('p.error-message').text(myError);
		
		if(errorVisible != true){
			
			$thisObj.parent().find('p.error-message').show();
			
			errorVisible = true;
		}		
	}
	
	function resetCSS($targetObj){
		
		var $thisObj = $targetObj;
		
		$thisObj.parent().css('background', 'none');
		$thisObj.parent().css('margin-top', '0px');
		$thisObj.parent().find('label').css('color', '#798CB8');
		$thisObj.parent().find('p.error-message').hide()
		
		errorVisible = false;
	}

};

$(document).ready( function(){
	var contactForm = new formValidation("#contact-form");
});





