(function() {
  var prev_comment_id = 0;
  openCommentForm = function(id)
  {
    if (prev_comment_id && prev_comment_id != id) {
      $('#add_comment_ta_'+prev_comment_id).hide();
    }
    var _div ='#add_comment_ta_'+id; 
    prev_comment_id = id;
    $(_div).toggle();
    $(_div).find('textarea').focus(); 
  }
  
  sendComment = function(event)
  {
    if((event.ctrlKey) && ((event.keyCode == 0xA)||(event.keyCode == 0xD))) {
      $(this).submit();
    }
  }
  
  refreshComments = function(post_id) {
    var refresh_href = $('#_comment_list').attr('comment_href');
    $.get(
      refresh_href,
      {post_id: post_id},
      function (html) {
        $('#_comment_list').html(html);
      }
    )
  }
  
  onSendComment = function()
  {
    var form = this;
    $.post(
      $(form).attr('action'),
      $(form).serialize(),
      function (html) {
        var _add = /\+added\_/i;
        if (html.match(_add) == '+added_') {
          var _split = html.split('_');
          var goto_href = $('#_comment_list').attr('href')+'/post_id/'+_split[2]+'/comment_id/'+_split[1];
          document.location.href = goto_href;  
        } else {
          $(form).html(html);
          aa = $(form).find('a');
          $(aa).each( function( index ){
            $(aa[index]).attr( 'href', $(aa[index]).attr('href') + '?rnd=' + Math.random().toString() + '#' + location.href.substr(location.href.indexOf('#')+1));
            }
          )
          bindCaptchaItems();
          }
        }
      )
    var inputs = $(form).find('input, textarea');
    $(inputs).each ( function ( input ){
      $(inputs[input]).attr('disabled', 'disabled')
    } );
    
    return false;
  }
    
  $.fn.attachSend = function()
  {
    var self = this;
    
    var forms = $(this).find('form');
    forms.each(function() {
      $(this).keypress(sendComment);
      $(this).submit(onSendComment)
    });
  }
  
  previewComment = function( url, comment_id ){
    var comment = $('#add_comment_ta_' + comment_id + ' textarea').val();
    $.post(
      url,
      { body: comment },
      function ( data ){
        var div = $('#preview_' + comment_id);
        div.html('<p>' + data + '</p>');
        div.show();
      }
    );
  }
})(jQuery);