// Init the form once the document is ready
$( init );
 
var messageDelay = 2000;  // How long to display status messages (in milliseconds)

// Initialize the form
 
function init() {
 
  // Make submitForm() the form’s submit handler.
  $('#contactForm').submit( submitForm );
 
  // When the "Send us an email" link is clicked:
  // 1. Slide the content up
  // 2. Display the form
  // 3. Move focus to the first field
  // 4. Prevent the link being followed
 
	$('a[href="#contactForm"]').click( function() {
		$('#container-form').slideToggle(1000);									
		$('#senderName').focus();
		return false;
	});

   
  // When the "Cancel" button is clicked, close the form
  $('#cancel').click( function() {
    $('#container-form').slideUp(500);
  } ); 
 
  // When the "Escape" key is pressed, close the form
  $('#contactForm').keydown( function( event ) {
    if ( event.which == 27 ) {
      $('#container-form').slideUp(500);
    }
  } );

}

// Submit the form via Ajax
 
function submitForm() {
  var contactForm = $(this);
 
  // Are all the fields filled in?
 
  if ( !$('#senderName').val() || !$('#senderEmail').val() || !$('#message').val() ) {
 
    // No; display a warning message and return to the form
    $('#incompleteMessage').fadeIn().delay(messageDelay).fadeOut('slow');
 
  } 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 occurring
  return false;
}

// Handle the Ajax response
 
function submitFinished( response ) {
  response = $.trim( response );
  $('#sendingMessage').fadeOut('slow');
 
  if ( response == "success" ) {
 
    // Form submitted successfully:
    // 1. Display the success message
    // 2. Clear the form fields
    // 3. Fade the content back in
 	
    $('#successMessage').fadeIn(500).delay(messageDelay).fadeOut('slow');
    $('#senderName').val( "" );
    $('#senderEmail').val( "" );
    $('#message').val( "" );
 
    $('#container-form').delay(messageDelay+1000).slideUp();
 
  } else {
 
    // Form submission failed: Display the failure message,
    // then redisplay the form
    $('#failureMessage').fadeIn(500).delay(messageDelay+1000).fadeOut('slow');
    $('#container-form').delay(messageDelay+1000).slideDown('slow');
  }
}
