$(document).ready(function() {
  $('#suggest_a_coupon_submit').click(function(e) {
    e.preventDefault();

    // ensure wymeditors are up to date.
    if ($(this).hasClass('wymupdate')) {
      $.each(WYMeditor.INSTANCES, function(index, wym)
      {
        wym.update();
      });
    }

    $('.fieldWithErrors').each(function(i, field){
      $(field).children().first().unwrap();
    });
    $('#suggest_a_coupon_form .errorExplanation').fadeOut(75).remove();
    $('#fieldsWithErrors').remove();

    $.post(this.form.action, $(this.form).serialize(), function(data, responseText) {
      if (data.redirect) {
        window.location = data.redirect;
      } else {
        // ensure old messages are gone:
        $('#suggest_a_coupon_form .errorExplanation, #fieldsWithErrors').remove();

        $(data.message).prependTo("#suggest_a_coupon_form").find('p').remove();
        if ((error_fields = $('#fieldsWithErrors').val()) != null) {
          $.each(error_fields.split(','), function() {
            $("#" + this).wrap("<div class='fieldWithErrors' />");
          });
        }

        $('.fieldWithErrors:first :input:first').focus();
      }
    });
  });
});