var messageDelay = 2000; // How long to display status messages (in milliseconds)

// Init the form once the document is ready
$(init);

function init() {
  // Make submitForm() the form's submit handler.
  $('#contactForm').submit(submitForm);
  // Move focus to the first field
  $('#firstName').focus();
}

function submitForm(){
  var contactForm = $(this);
  
  // Are all the fields filled in?
  
  if (!$('#firstName').val() || !$('#lastName').val() || !$('#summary').val() ) {
    // No; display a warning message and return to the form
    $('#incompleteMessage').fadeIn().delay(messageDelay).fadeOut();
  } else {
    // Yes; submit the form to the PHP script via Ajax
    
    $('#sendingMessage').fadeIn();
    
    $.ajax({
      url: contactForm.attr('action') + "?ajax=true",
      type: contactForm.attr('method'),
      data: contactForm.serialize(),
      success: submitFinished
    });
  }
  
  // Prevent the default form submission from occurring
  return false;
}

function submitFinished(response) {
  response = $.trim(response);
  $('#sendingMessage').fadeOut('fast');
  
  if (response == "success") {
    $('#successMessage').fadeIn().delay(messageDelay).fadeOut();
    $('#firstName').val("");
    $('#lastName').val("");
    $('#senderEmail').val("");
    $('#message').val("");
    
    $('form div :input').val("");
    $('form textarea').val("");
    
  } else {
    $('#failureMessage').fadeIn().delay(messageDelay).fadeOut();
    $('#contactForm').delay(messageDelay+500).fadeIn();
  }
}
