(function ($) {
  var form;
  $(function () {
    form = $('#contact-form');
    $('a.contact-link').anchorAnimate();


    $('#error-list').hide();
    form.validate(
          {
            submitHandler: handleForm,
            errorClass: 'error',
            errorContainer: '#error-list',
            highlight: highlightField,
            unhighlight: unHighlightField,
            errorPlacement: placeErrorMessage,
            errorElement: 'em',
            invalidHandler: handleInvalidForm
          });

  });

  function handleInvalidForm(form, validator) {
    $('#submit').attr("disabled", "disabled");
  }

  function handleForm(form) {
    $('#processing').show();
    $('#submit').hide();
    $(form).ajaxSubmit({ success: handleSuccess, clearForm: true });
    return false;
  }

  function handleSuccess(responseText, statusText, xhr) {
    if (responseText.OK) {
      $('#processing').hide();
      $('#success').show();
      $('#contact-form').hide();
      $('#contact-intro').hide();
    }
  }

  function highlightField(element, errorClass) {
    getDivFromElement(element).addClass('error');
  }

  function unHighlightField(element, errorClass) {
    getDivFromElement(element).removeClass('error');
    if (this.numberOfInvalids() == 0) {
      $('#submit').removeAttr("disabled");
    }
  }

  function getDivFromElement(element) {
    return div = $(element).parent().parent().parent();
  }

  function placeErrorMessage(error, element) {
    error.appendTo(element.parent().prev());
  }


})(jQuery);
