// Init the form once the document is ready
$( init );


// Initialize the form

function init() {

  // Make submitForm() the form's submit handler.
  // Position the form so it sits top right of screen.
  $('#contactForm').submit( submitForm ).addClass( 'positioned' );

  // When the "Send us an email" link is clicked:
  // 1. Fade the content out
  // 2. Display the form
  // 3. Move focus to the first field
  // 4. Prevent the link being followed

  $('.open').click( function() {
    $('#contact-bg').fadeIn(300).css({'display' : 'block'});
    $('#contactForm').fadeIn(450, function() {
      $('#senderName').focus();
    } )

    return false;
  } );
   
//when class="close" is clicked, close form, fade bg in
	$('.close').click( function() { 
    $('#contactForm, #contact-bg').fadeOut(300);
  } );  
  
  // When the "Escape" key is pressed, close the form
  $('#contactForm').keydown( function( event ) {
    if ( event.which == 27 ) {
      $('#contactForm, #contact-bg').fadeOut(300);

    }
  } );
  
 //if background is clicked restore content
/*    $('#contact-bg').click(function () {
        $('#contactForm, #contact-bg').fadeOut(300);
    }); */         
	
}


// 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(2200).fadeOut();
    

  } else {

    // Yes; submit the form to the PHP script via Ajax

    $('#sendingMessage').fadeIn();
    contactForm.fadeOut();

    $.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();

  if ( response == "success" ) {

    // Form submitted successfully:
    // 1. Display the success message
    // 2. Clear the form fields
    // 3. Fade the content back in
	// 4. Make sure scroll to top on iPhone

    $('#successMessage').fadeIn().delay(4500).fadeOut();
	$('html, body').animate({scrollTop:0}, 'fast');
    $('#senderName').val( "" );
    $('#senderEmail').val( "" );
    $('#message').val( "" );
	$('#contact-bg').delay(4500).fadeOut();


  } else {

    // Form submission failed: Display the failure message,
    // then redisplay the form
    $('#failureMessage').fadeIn().delay(messageDelay).fadeOut();
    $('#contactForm').delay(3300).fadeIn();
  }
}

