/********************************************************************************************

Title: Jquery Ajax Validation Script
Author: Alex Garcia
Version: 1.0
Created: 10/21/2009
Requires: jquery 1.3.2
Description: This script allows us to validate any form and post the data ansynchronously
using jQuery.Ajax. It works with jquery 1.3.2 and has been tested to function with CodeIgniter.

Todo: It would be nice to create an array of required elements and then using jquery .each loop
through all of the ids in the array doing the necessary checks dynamically. I have not been able 
to get that to work without the form doing a traditional postback, which defeats the purpose
of the script. As I get more agile with jQuery I will revisit this addition as it will
ease the use of this script for developers with very little javascript experience. Right now
a developer will have to dig into the code to create the validation code manually for each form
element, which is not ideal but acceptable,

********************************************************************************************
01. Configuration
********************************************************************************************/

//The page the form should post to.
var post_page = 'https://www.tombensonchevy.com/finance.php';

//The page/content we want to load on success (this gets done asynchronously via javascript)
var result_page = 'https://www.tombensonchevy.com/assets/forms/process_finance_form.php';

//The id of the element where we want to load the result page content. Usually a div on the page.
var result_target_id = '#message';

//The message to display on successful submission. This gets wrapped in a div with the class "sucess_message".
var status_success_message = 'Thank you. Your information has been recieved.';

//The message to display on successful submission. This gets wrapped in a div with the class "sucess_message".
var status_error_message = 'There are problems with the form. Please hover over the alerts for more details.';

//The id of the form
var form_id = '#form';

//The id of the loading animation image.
var loading_id = '#loading';

//The name of the class for all error messages. Errors should be in this format "<span class="error" id=""></span>"
//There is no need to add the message since we will customize it for each type of validation.
var error_class = '.error';

//The id of our submit button
var submit_id = '#submit';

/********************************************************************************************
02. Start the processing - No need to touch
********************************************************************************************/

$(document).ready(function() {
  
  //Lets hide our errors and loading image
  $(error_class).hide();
  $(loading_id).hide();
 

//When the submit button is clicked lets start the checking.  
$(submit_id).click(function(){
  
  //Hide the submit button and errors then show the loading 
  //animation to indicate that a postback has occured.  
  
  $(submit_id).hide();
  $(loading_id).show();
  $(error_class).hide();
  
  var hasErrors = new Array(); 

/********************************************************************************************
03. Check Required Inputs and set our regular expressions
********************************************************************************************/  

//Used to validate email addresses to this format "email@isp.com"
var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

//Used to validate phone numbers to this format "555-555-5555"
var phoneReg = /^(?:\([2-9]\d{2}\)\ ?|[2-9]\d{2}(?:\-?|\ ?))[2-9]\d{2}[- ]?\d{4}$/;

//Lets check the required input, send an error message and then display errors there are any
//@param string id (is the id of the form input we are validating)
//@param string message (is the error message we want to insert into our error spans)
//@param string data_type (is the field type for validating certain types of data such as email and phone)
//@param string message2 (is a secondary error message when doing regular expression checks)

function check_input(id, message, data_type, message2){
   
   //Let's define the id from our form that we are checking for a value;
   var check_id =  $('#'+id).val();
    
 
if(data_type=='email')
{   
       if(check_id=='')
       {
           var hasErrors = 'true';
           $('#error_'+id).show();
           $('#error_'+id).html(message);
           return hasErrors;
            
       }else if(!emailReg.test(check_id)){
       
           var hasErrors = 'true';
           $('#error_'+id).show();
           $('#error_'+id).html(message2);
           return hasErrors; 
       }

}else if(data_type=='phone'){
        
        if(check_id=='')
        {
           var hasErrors = 'true';
           $('#error_'+id).show();
           $('#error_'+id).html(message);
           return hasErrors; 
        
        }else if(!phoneReg.test(check_id)){
           var hasErrors = 'true';
           $('#error_'+id).show();
           $('#error_'+id).html(message2);
           return hasErrors; 
        }
        
}else{   
        
        if(check_id=='')
            {
               var hasErrors = 'true';
               $('#error_'+id).show();
               $('#error_'+id).html(message);
               return hasErrors;
            }
    }    
}
  

/********************************************************************************************
04. Configure the fields and errors
********************************************************************************************/

   //For each field lets do some validation. 
   //If there is an error lets set the hasErrors variable to true
   //and show the corresponding error message.
   
    //Function signature
  //check_input(id of the field, error message, optional type(email or phone), optional error msg);
  //Each form input that is required should also have as span tag with this signature <span class="error" id="error_ID OF INPUT"></span>
  //Next to the input.
   
  	hasErrors[0] = check_input('requiredFirstName','Please enter your first name');
  	hasErrors[1] = check_input('bday','Please enter your birthday.');
	hasErrors[2] = check_input('requiredLastName','Please enter your last name');
	hasErrors[3] = check_input('requiredCity','Please enter your city.');
	hasErrors[4] = check_input('requiredState','Please enter your state.');
	hasErrors[5] = check_input('requiredZip','Please enter your zip code.');
	hasErrors[6] = check_input('requiredYears','Please enter your years.');
	hasErrors[7] = check_input('requiredMonths','Please enter your months.');
    hasErrors[8] = check_input('Email','Please enter your email.','email','Please enter a valid email address.');
	hasErrors[9] = check_input('fullname','Please enter your full name');
	hasErrors[10] = check_input('date','Please enter the date.');
	hasErrors[11] = check_input('requiredAddress','Please enter address.');
	hasErrors[12] = check_input('phone','Please enter your phone.','phone','Please enter a valid phone number format like: 210-555-5555.');
 
    
    //Add a line for each item we are testing
    if ( 
		hasErrors[0]=='true' || 
		hasErrors[1]=='true' || 
		hasErrors[2]=='true' || 
		hasErrors[3]=='true' || 
		hasErrors[4]=='true' ||
		hasErrors[5]=='true' ||
		hasErrors[6]=='true' ||
		hasErrors[7]=='true' ||
		hasErrors[8]=='true' ||
		hasErrors[9]=='true' ||
		hasErrors[10]=='true' ||
		hasErrors[11]=='true' ||
		hasErrors[12]=='true'
		)
    {
		strHasErrors = 'true';
    }else{
       strHasErrors = 'false';
    }
/********************************************************************************************
05. Attempt to send and complete the process - No need to touch
********************************************************************************************/

//If the form submission has errors lets show the submit button, hide the loading image and stop the script.
if(strHasErrors=='true'){
       $(submit_id).show();
       $(loading_id).hide();
       return false;

//If there are no errors lets send the form results to our post page and load the results content into our
//result target div.
   }else{

            var str = $(form_id).serialize();
           
           $.ajax({
                type: "POST",
                url: post_page,
                data: str,
                success: function(){
                    if(result_target_id != ''){
                        $(result_target_id).load(result_page,str, function(){}); 
                    }
                    $(submit_id).show();
                    $(loading_id).hide();
                    $(form_id).slideUp("normal",function(){
                    $(form_id).before('<div class="success_message">'+status_success_message+'</div>');

                   });
                     $('form :input').val("");   
                }
                    
                });

   } 

return false;
   });
});