// Define the global config variables
var thisFormSelector = '.dineto-form';

// Default the global hasSubmit variable to false
var hasSubmit = false;

// On document ready, attach form events
$(document).ready(function(){
 
	// Define the context variable for the form
	var thisForm = $(thisFormSelector);	 
 
  // Ensure Dine.TO forms exist on the page
	if (thisForm.length){
		
		// Generate a change validation event for the form
		$('input,textarea', thisForm).bind('change blur keyup', function(){
			job_form_validate(thisForm);
			return true;
			});
	 
		// Generate a submit validation event for the form
		thisForm.submit(function(e){
			hasSubmit = true;
			// Update the form action and return true
			if (job_form_validate(thisForm)){ 
				return true; 
			}
			// Prevent submission and return false
			else { 
				e.preventDefault(); 
				return false; 
				}
			});		
		
	  }
		
});	
	
// Define a function for validating field inputs
function job_form_validate(thisContext){
	
	// Default the verified flag to true
	var isVerified = true;
	
	// Loop through each required field
	$('*[data-required]', thisContext).each(function(){
		
		// Collect the required type from the data
		var requireType = $(this).attr('data-required');
		
		// Collect this field's name, object, and value
		var thisVerified = true;
		var fieldName = $(this).attr('for');
		var fieldTitle = $(this).html();
		var thisField = $('*[name='+fieldName+']', thisContext);
		var thisValue = thisField.val();
		
		// Validate based on require type
		if (requireType == 'default'){
			// Ensure the field is not empty
			if (!thisValue.length){
				// Set the verified flag to false
				isVerified = false;	
				thisVerified = false;
				}					
			} else if (requireType == 'email_address'){
			// Ensure the field is is a valid email address
			if (!thisValue.length || !thisValue.match(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}$/i)){
				// Set the verified flag to false
				isVerified = false;
				thisVerified = false;
				}
			} else if (requireType == 'postal_code'){
			// Ensure the field is is a valid postal code
			if (!thisValue.length || !thisValue.match(/^[a-z][0-9][a-z](\s|-){0,}[0-9][a-z][0-9]$/i)){
				// Set the verified flag to false
				isVerified = false;
				thisVerified = false;
				}
			}
			
		// Check if the field is not verified
		if (!thisVerified && hasSubmit){
			// Only show visual errors if submit
			thisField.parent().addClass('error_field');
			} else if (thisVerified) {
			// Remove any visual errors on the field
			thisField.parent().removeClass('error_field');		
			}									
			
		});
	
	// Return the global verified flag
	return isVerified;
	}
	
