$(function() {
  // page globals
  var prettyDateInterval = null;

  // Functions
  function isLoggedIn() {
    return $("li#login").length == 0
  }

  function makeDatesPretty() {
    $(".comment .date").prettyDate();
    if (prettyDateInterval != null)
      clearInterval(prettyDateInterval);
    prettyDateInterval = setInterval(makeDatesPretty, 60000); // update every minute
  }

  /**
   * Hides all comments except the last 2 when more comments
   * than the allowed limit exist.  If only one more than the 
   * limit  exists it is shown instead of the show all link.
   * 
   * All comments are by default not displayed.
   */
  function squishComments() {
    $(".comments").each(function() {
      var commentGroup = $(this);
      var commentList = $(this).find(".comment");  
      var commentCount = commentList.length;
   
      // abort if it has already been bound
      if (commentGroup.find("a.show-all").length > 0)
        return;
     
      if (commentCount < 4) {
        commentList.show();
      }
      else {
        $(commentList[commentCount - 1]).show();
        $(commentList[commentCount - 2]).show();

        var showMoreLink = $("<a/>", {
          "href": "#",
          "class": "show-all",
          "text": sprintf("View all %f comments", commentCount),
          "click": function() {
            commentList.show();       
            $(this).remove();
            return false;
          }
        });

        commentGroup.prepend(showMoreLink);
      }

    }) // each
  } // function

  function bindComments() {
    $("a.new-comment").live("click", function() {
      var addLink = $(this);
      var parent = $(this).parents("fieldset.note");
      
      // send anonymous user to login
      if (!isLoggedIn()) {
        document.location.href = $("li#login a").attr("href");
        return false;
      }

      // ensure only one form exists
      if ( parent.find("textarea").length > 0 )
        return false; 

      // prevent clutter
      addLink.hide();
      
      $.get(this.href, function(data) {
        var form = $(data);

        // add form to page
        parent.find(".comments").after(form); 

        // prevent clicking from hiding form
        form.submit(function() {
          var c = form.find("textarea").val();
          $.post(form.attr("action"), {comment: c, "_method": "POST"}, function(savedComment) {
            form.remove(); 
            addLink.show();

            // add savedComment to the page
            $(savedComment)
              .css("display", "block")
              .appendTo( parent.find(".comments") );

            makeDatesPretty();
          });
          return false;
        });

        form.find("a.cancel").click(function() {
          form.remove(); 
          addLink.show();
          return false;
        });

      });

      return false;
    });
  }

  // Start
  makeDatesPretty();
  squishComments();
  $(".notes").gsCachinate({nextPageLinkText:"Show Previous Notes"});
  $(".notes").bind("after_show_next_page", squishComments);

  bindComments();

});
