function checkForm() {
var errors = 0;
    $("#contactForm :input").not('#workPhone').map(function(){
         if( !$(this).val() ) {
              errors++;
        }
    });
    if(errors > 0){
        alert("You are missing a required field.");
        return false;
    }
    else{
      return true;
    }
}

function handleSubmitResult(data, textStatus, XMLHttpRequest) {
  $('#loading').fadeOut('fast', function() {
    //only show the thank you page if everything was successful
    if (data != false) {
      $('#success').fadeIn('fast');
    }
    else {
        $('#failure').fadeIn('fast', function() {
        });
    }
  });
}

function submitForm(){
$(':submit', this).click(function() {
        return false;
    });
//validate form
  $('#contactForm').fadeOut('fast', function() {
    $('#loading').fadeIn('fast', function() {
      if (checkForm() == true){
        var requestParams = {
          firstName : $('#firstName').val(),
          lastName : $('#lastName').val(),
          address : $('#address').val(),
          city : $('#city').val(),
          state : $('#state').val(),
          zipCode : $('#zipCode').val(),
          homePhone : $('#homePhone').val(),
          workPhone : $('#workPhone').val(),
          emailAddy : $('#emailAddy').val(),
          comments : $('#comments').val(),
          isAjax : true,
          submit: true
        };
      $.post('/Contact-Us', requestParams, handleSubmitResult, 'text');
     }
      else{
        $('#loading').fadeOut('fast', function() {
          $('#contactForm').fadeIn('fast');
      });
    }
    });
});
}

function contact(readyEvent) {
  // form elements
  $('#loading').hide();
  $('#failure').hide();
  $('#success').hide();
  $('#contactForm').show();

  $('#submitButton').click(function (e) {
    //Cancel the link behavior
    e.preventDefault();
    submitForm();
  });

  // setup ajax options
  $.ajaxSetup({
    cache : false,
    dataTypeString : 'json',
    error : handleRequestError,
    timeout : 15000
  });
}

function handleRequestError(xmlReq, status, err) {
alert('Error loading data' + "\n" + status);
}

$(document).ready(contact);

