function clearCommentErrors(arr, form) {
  $('.error-highlight').html('');
  form.find('.replysubmit').attr("disabled", "disabled");
};

function processJSONNewComment(data, statusText, xhr, formParam) {
  /* We're currently in jquery 1.3 so formParam is undefined. When we move to
   * 1.4, formParam will be the form. */
  var form = formParam || xhr;
  if (!data.errors) {
    form.prev().hide("slow");
    form.hide("slow", function() {
      form.html("Thank you for your comment! <br>"+
                "If you'd like to stay engaged, "+
                "visit our homepage and sign up "
                +"for our email newsletter.").show("slow");
    });
  } else {
    $.each(data.errors, function(i, val) {
      var tmp = $('.comment-reply-form_error_' + i);
      tmp.html(val.join('&nbsp; '));
    });
    form.find('.replysubmit').removeAttr("disabled");
  }
};

function feature_comment(comment_id, flag, user) {
  if (comment_id && user) {
    var data = {comment_id: comment_id, user: user};
    var args = {type: "POST",
        url: flag_url,
        data: data,
        success: function(msg) {
          $('a#flag' + comment_id).html(msg);
        }};
    $.ajax(args);
  }
};

function flag_for_mod(comment_id) {
  if (comment_id) {
    var data = {comment_id: comment_id};
    var args = {
        type: 'POST',
        url: flag_for_mod_url,
        data: data,
        success: function(msg) {
          $('#flagformod' + comment_id).html("Thank You For Notifying Us");
        }};
    $.ajax(args);
  } else {
    return false;
  }
};

$(document).ready(function() {
  var comment_options = {
      dataType: 'json',
      success: processJSONNewComment,
      beforeSubmit: clearCommentErrors,
      type: 'PUT'};
  $('.commentform').ajaxForm(comment_options);
  $('.replysubmit').removeAttr("disabled");
  $('#create').removeAttr("disabled");
  $(".flaglink").click(function(evt) {
    evt.preventDefault();
    var id = $(this).attr("id").replace("flag_for_mod", "");
    if (is_auth) {
      flag_for_mod(id);
    } else {
      var html = "<a href='" + auth_login +
                 "'>Login</a> to Flag This Comment For Moderation";
      $('div#flagformod' + id).html(html);
    }
  });
  $(".feature_comment").click(function(evt) {
    evt.preventDefault();
    var a = $(this).text("Featured!");
    var id = a.attr("id").replace("feature_", "");
    feature_comment(id, "FEATURED_COMMENT", admin_user_id);
  });
});

