/**
* @author RyanD
*/
//Array of values of the form
values = {"first":"First Name","last":"Last Name","addr1":"Address Line 1","addr2":"Address Line 2","city":"City","state":"State","zip":"Zip Code","year":"Year","make":"Make","model":"Model","vin":"VIN # (Vehicle Identification Number)","insurance":"Insurance Company","referral":"Who Referred You?","email":"Email Address","phone":"Phone"};
$(document).ready(function() {
    
    $(".form").focus( function(){
        if($(this).val() == "" || $(this).val() == values[this.id]){
            $(this).removeClass('error');
            if(this.id == "phone"){
            $("#phone").mask("?(999) 999-9999"); 
            }else{
                $(this).val(' ');
            }    
        } 
    });
    
    $(".form").blur( function(){
        if($(this).val() == " "){
            $(this).val(values[this.id]);    
        }           
    });
    
    $("#estimateForm").submit( function(){
        //Checks the values of the inputs versus their original values
        var invalids = 0;    
        $("input").each( function(){
            if(this.id != 'addr2'){
                if($(this).val() == values[this.id]){
                $(this).addClass('error');
                invalids ++;   
                }   
            }
       });
       if(invalids > 0){
            var message = invalids == 1
                    ? 'You missed 1 field. It has been highlighted'
                    : 'You missed ' + invalids + ' fields. They have been highlighted';
            alert(message);
            return false;    
       }
       var validationObj = $("#estimateForm").validate({
              invalidHandler: function(form, validator) {
                var errors = validator.numberOfInvalids();
                if (errors) {
                  var message = errors == 1
                    ? 'You missed 1 field. It has been highlighted'
                    : 'You missed ' + errors + ' fields. They have been highlighted';
                    alert(message);
                }
              },
              submitHandler: function() {
                //Need to add the ajax that will actually send a message to somebody
                $.post("includes/mailer.php", $("#estimateForm").serializeArray(), function(data, text){
                    if(data == 'ok'){
                        $("#estimateForm").html("<h2>Thank you for your submission</h2>");    
                    }else{
                        alert(data);
                    }
                });
              }
              
            });
         return false;  
    });
      
});