var onMessageRecorded = function() { 
    var title = $("comments").down("h2");
    if (!$("list-of-comments")) {
        new Insertion.After("recorder", "<ul id=\"list-of-comments\"></ul>");
    }
    var comments = $("list-of-comments");
    if (comments.immediateDescendants().size() > 0) {
        var cmtId = $("list-of-comments").down("li:first-child").id.gsub(/^comment-(\d+)$/, '#{1}');
    }

    title.addClassName("busy");

    new Ajax.Updater("list-of-comments", Comments.reloadUrl + (cmtId || ""), {
        method: "post",
        insertion: "top",
        evalScripts: true,
        onComplete: function(request) {
            title.update(title.innerHTML.gsub(/\d+/, comments.immediateDescendants().size())).removeClassName("busy");
            Comments.Recorder.close();
        } 
    });
}

var Comments = {
  current: null,
  offset: null,
  currentPage: 1,
  updatingList: false,
  loadedComments: 0,

  player: function(id) {
    var swfObject = new SWFObject(window.commentData[id]["path"], "comment-player", "290", "235", "8.0", "#fff", true);

    window.commentData[id]["vars"].each(function(pair) {
        swfObject.addVariable(pair.first(), pair.last());
    });

    swfObject.addParam("base", window.commentData[id]["base"]);
    swfObject.addParam("wmode", "transparent");
    $("video-container-for-comment-" + id).setStyle({ "height": "235px" });
    swfObject.write("video-container-for-comment-" + id);
  },
  toggle: function(comment) {
    var comment = $(comment);
    var container = comment.up("li.with-video");
    var video_holder = container.down(".video-holder");
    var links = container.getElementsBySelector(".watch-video");

    if (Comments.currentlyShowing) {
      Comments.currentlyShowing.hide().up("li.with-video").removeClassName("open").getElementsBySelector(".watch-video").invoke("show");
      Comments.currentlyShowing.previous(".watch-video").show();
    }
    links.invoke("hide");
    Element.extend(video_holder).show();
    container.addClassName("open");
    Comments.player(video_holder.getAttribute("id").replace(/^.*-([0-9]+)$/, "$1")); 

    if (Comments.fakedOffset) {
      Comments.fakedOffset.undoPositioned();
    }

    if (!Comments.currentlyShowing && document.all && !window.opera) {
      try {
        Comments.fakedOffset = container.next("li").makePositioned().setStyle({"top": "1px"});
      } catch(e) {}
    }

    Comments.currentlyShowing = video_holder;
    return false;
  },
  obliterate: function(form) {
    if (confirm("Are you sure you want to delete this comment? This can't be undone")) {
      var form = Element.extend(form);
      var comment = form.up("li");
      form.down("div").addClassName("busy");
      new Ajax.Request(form.action, {
        method: form.method,
        onComplete: function(request) {
          comment.remove(); 
          var title = $("comments").down("h2");
          title.update(title.innerHTML.gsub(/\d+ comments?/, function(match) { 
            var comments = parseInt(match[0]) - 1; 
            return Math.abs(comments) == 1 ? "1 comment" : comments + " comments";
          }));
          Comments.detectScrollOffset();
        } 
      });
    }
    return false;
  },
  reload: function() {},
  getMore: function() {
    if (Comments.updatingList) return;
    Comments.currentPage += 1
    Comments.updatingList = true;
    Comments.getMoreCommentsMessage = $("get-more-comments").innerHTML;
    $("get-more-comments").update("Loading comments...");
    new Ajax.Updater("list-of-comments", Comments.fetchPageUrl, {
      method: "get",
      evalScripts: true,
      parameters: { "page": Comments.currentPage, "t": (new Date()).getTime() },
      insertion: "bottom",
      onComplete: function(request) {
        Comments.updatingList = false;
        Comments.loadedComments = $$("#list-of-comments li").size();
        if (Comments.currentPage * 50 >= Comments.totalComments) {
            $("get-more-comments").remove();
        } else {
            $("get-more-comments").update(Comments.getMoreCommentsMessage).down().observe("click", Comments.getMore);
        }
      }
    });
    return false;
  },
  detectScrollOffset: function() {
    if (Comments.currentPage * 50 < Comments.totalComments && !Comments.updatingList && Comments.scrolledPast()) {
        Comments.getMore();
    }
  },
  scrolledPast: function() {
    var offset = Prototype.Browser.IE ? 6 : 5;
    return window.getScrollY() > Position.cumulativeOffset($("list-of-comments").childNodes.item(Comments.loadedComments - offset)).last();
  }
}

Comments.Recorder = {
  visible: false,
  open: function(type) { 
    var recorder = Comments.Recorder;

    if (recorder.visible) recorder.close();

    var swfObject = new SWFObject(recorder.path, "commentRecorder", "433", "302", "8.0", "#fff", true);
    recorder.vars.each(function(pair) {
      swfObject.addVariable(pair.first(), pair.last());
    });
    swfObject.addVariable("type", type);
    recorder.params.each(function(pair) {
      swfObject.addParam(pair.first(), pair.last());
    });

    $("recorder-container").setStyle({ "height": "302px", "width": "433px", "margin-top": "24px" }).show();
    swfObject.write("recorder-container");

    recorder.visible = true;
  },
  close: function() {
    $("recorder-container").setStyle({ "height": "", "width": "", "margin-top": "0" }).update("");
    $("recorder").setStyle({ "margin-bottom": "0" });
  }
}

Event.observe(window, "scroll", Comments.detectScrollOffset);
Event.addBehavior({
    "#get-more-comments a:click": Comments.getMore
});
