// JavaScript Document
$(document).ready(function() {
	
	$("form").submit(function() {
		var form_id = $(this).attr('id');
		if (form_id != 'ignore_validation'){
		
			var return_validation = 'The following are REQUIRED:<br/><br/>';
			form_valid = true;
			
			form_name = $('input[type=submit]').closest("form").attr('name');
			
			// Check all the required fields to ensure they are not empty
			$('.required').each(function(){
				
				if ($(this).is(":visible")){ // ensure we dont check hidden inputs as they are obviously not required
				
					$(this).removeClass('error_input');	// lets reset the highlighting if its the second time around								 
					if(($(this).val() == '') || ($(this).val() == '0')){
				   
						return_validation = return_validation + '* "' + $(this).attr('title') + '"<br />';
						$(this).addClass('error_input');
						form_valid = false;
						
					}
	
				}
				
			 });
			 
			 
			 // if the field is empty there is no need to further validate the fields 
			 if (form_valid != false){
			 
				 // Check and see if the postal code is legit
				 /*
				 zip = $('#postalcode').val();
				 zip = zip.toUpperCase();
				 
				 if (!zip.match(/^[A-Z][0-9][A-Z][0-9][A-Z][0-9]$/)) {
					return_validation = return_validation + '* Your postal code is invalid. <br />'; 
					$('#postalcode').addClass('error_input');
					form_valid = false; 
				 }
				 */
		
				 
				 // Check if the name field has no special characters
				 name = $('#author').val();
				 if (!name.match(/[a-zA-Z0-9-_]+/)) {
					return_validation = return_validation + '* Your name contains invalid characters. <br />'; 
					$('#author').addClass('error_input');
					form_valid = false; 
				 }
				 
				 
				 // Check if the email address is legit
				 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);
				 
				 // for WORDPRESS lets check if the user is logged in. If so we dont need to test this field
				 if (!$('form p:first').hasClass('logged-in-as')){
					 if (!pattern.test($('#email').val())){
						return_validation = return_validation + '* Your email address is invalid. <br />'; 
						$('#email').addClass('error_input');
						form_valid = false; 
					 }
				 }
			 }
				 
			 
			 // If we have any failures on the validation above then lets stop things right now and return the error
			 if (form_valid == false){
				 $("#validation_return").html(return_validation).show();
	
				var target_offset = $("#validation_return").offset();
				var target_top = target_offset.top - 50;
	
				$('html, body').animate({scrollTop:target_top}, 500);
	
				 
				 return false;
				
			 }
			 
		}
							  
	});
	
});
