$(document).ready(function(){

  $("#comment_text").charCounter(500, {delay: 50});

  enable_comment_reply();

  // unset reply comment id + username and hide reply info
  $('a.cancel_reply').click(function(){
    $("input#parent_id").val('');
    $("#comment_replyto").hide();
    $("span#comment_replyto_username").html('no one');
    return false;
  });

  enable_ajax_comment_nav();
  enable_ajax_comment_adult();

});

function enable_comment_reply() {

  $('a.comment_reply').click(function(){

    // get main containing li
    var comment = $(this).parents('li[id^=comment]');

    // get comment_id and username of original poster
    var comment_id = comment.attr('id').match('comment([0-9]+)')[1];
    var username = comment.find('.comment_username').html();

    // fill in comment_id, display username, and show reply info
    $("input#parent_id").val(comment_id);
    $("span#comment_replyto_username").html(username);
    $("#comment_replyto").show();

    // scroll the user to the add comment form and focus on the textarea
    document.location.hash = 'add_comment';
    $('#comment_text').focus();

    return false;
  }).removeClass('hidden');

}

function enable_ajax_comment_nav() {
  $('#comments .paginator a').click(function() {
    var target = this;
    var info   = $(this).attr('href');
    var url    = info.split("?")[0];
    var page   = info.split("=")[1];
    load_comment_page(url+"?comments_page="+page);
    return false;
  });
}

function load_comment_page(url) {
  $('#comments .body').load(url, {}, function(){
    document.location.hash = 'comments';
    enable_comment_reply();
    enable_ajax_comment_nav();
    enable_ajax_comment_adult();
    enable_ajax_flagging();
  });
}

function enable_ajax_comment_adult() {
  $('a.comment_adult_bypass').click(function(){
    load_comment_page(
      $(this).attr('href').replace('request_comment_page', 'comments_page')
    );
    return false;
  });
}
