(function($) {

  $.fn.cbajax = function(contentWrapper)
  {
    var targetNode = $(contentWrapper);
    return this.each(function()
    {
      $(this).find('a.aL').each(function()
      {
        var url = $(this).attr('href');

        $(this).click(function(event)
        {
          targetNode.animate({"opacity" : "-=.8"}, "slow", function() {
            $.get(url, {'ajax' : 'ajax'}, function(data) {
              targetNode.html(data);
              targetNode.cbajax(contentWrapper);
              targetNode.animate({"opacity" : "+=.8"}, "slow");
            });
          });
          return false;
        });
      });

      cbComments();

    });
  };

  function cbComments()
  {
    var commentsBox = $('#commentsBox');
    if (commentsBox)
    {
      $(commentsBox).find('a.aL_commentsBox').each(function()
      {
        var url = $(this).attr('href');

        $(this).click(function(event)
        {
          commentsBox.animate({"opacity" : "-=.8"}, "slow", function() {
            $.get(url, {'ajax' : 'ajax'}, function(data) {
              /* FIXME : jQuery shows some strange behaviour here and drops the
                 "#commentsBox" div from "data", but still adds another commentsBox
                 to the DOM, where it already is...*/
              var newNode = $(data);
              commentsBox.replaceWith(newNode);
              cbComments();
            });
          });
          return false;
        });
      });

      var commentsForm = $("#commentsForm");
      commentsForm.submit(function(event)
      {
        var url = commentsForm.attr("action");
        var params = {
          'ajax'        : 'ajax',
          'email'       : $('#email').val(),
          'sender'      : $('#sender').val(),
          'senderMail'  : $('#sender').val(),
          'message'     : $('#message').val(),
          'captcha'     : $('#captcha').val()
        }

        $.get(url, params, function(data)
        {
          commentsBox.replaceWith(data);
          cbComments();
        });

        return false;
      });
    }
  }

})(jQuery);

