var contactFormIsSent = false;
var contactFormAjaxRequest = false;

function contactFormSubmit(formEl)
{
  if (!contactFormValidate())
    return false;
  
  contactFormIsSent = false;
  
  document.getElementById('submit').value = 'Sending...';
  setTimeout(checkForfailedAjaxSubmit, 5000); // make sure we have sent the message in 5 seconds from now
  
  var ajaxSent = contactFormSendAjaxRequest();
  if (!ajaxSent)
    return true;
  
  return false;
}

function contactFormSendAjaxRequest()
{
  // create request object. in old versions of IE this will fail
  try {
    contactFormAjaxRequest = new XMLHttpRequest();
  } catch(e) {
    return false;
  }
  
  // create post data
  var postData = 'ajax=1';
  postData += '&name='+escape(document.getElementById('name').value);
  postData += '&email='+escape(document.getElementById('email').value);
  postData += '&message='+escape(document.getElementById('message').value);
  
  // send request
  contactFormAjaxRequest.onreadystatechange = contactFormSendAjaxRequestStateChange;
  contactFormAjaxRequest.open('POST', 'contact-mailer', true);
  contactFormAjaxRequest.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
  contactFormAjaxRequest.send(postData);
  
  return true;
}

function contactFormSendAjaxRequestStateChange()
{
  if (contactFormAjaxRequest.readyState != 4)
    return;
  
  contactFormSendComplete();
}

function contactFormSendComplete()
{
  // check for invalid response, and bounce to normal (non-ajax) form submit
  if (contactFormAjaxRequest.status != 200 || contactFormAjaxRequest.responseText != 'message sent')
    return this.checkForfailedAjaxSubmit();
  
  // mark ajax as successful
  contactFormIsSent = true;
  
  // revert send button
  document.getElementById('submit').value = 'Send »';
  
  // show thanks msg
  document.getElementById('thanks-msg').style.display = 'block';
  setTimeout(hideContactForm, 5000);
}

function checkForfailedAjaxSubmit()
{
  if (contactFormIsSent)
    return;
  
  // kill onsubmit action, and submit
  document.getElementById('contact_form').setAttribute('onsubmit', '');
  document.getElementById('submit').click();
}

function hideContactForm()
{
  if (document.getElementById('thanks-msg').style.display == 'none')
    return;
  
  document.getElementById('thanks-msg').style.display = 'none';
  
  document.getElementById('contact_form').reset();
}

function contactFormValidate()
{
  if (document.getElementById('message').value == '') {
    alert('Please fill in the Message field.');
    return false;
  }
  
  return true;
}

