document.addEventListener("DOMContentLoaded", function(event) {
  var container = document.getElementById("bee-rendered-content");

  function gh_findParentTagWithName(el, tag) {
    while (el.parentNode) {
      el = el.parentNode;
      if (el.tagName === tag) return el;
    }

    return null;
  }

  container.addEventListener("click", function(e) {
    if (e.target && e.target.nodeName == "INPUT" && e.target.className.split(" ").indexOf("task-list-item-checkbox") != -1) {
      // Task list item was toggled
      // Get the index of this task list item and tell Bee to invoke our plugin method which will update this in the background
      var input = e.target;
      var inputChecked = input.checked;
      var inputIndex = 0;

      // Find inputs relative to the current table (because our event is relative to the current comment box)
      // If we cannot find a parent table, we are in the rendered text field so just look for all task items across the document
      var parentContainer = gh_findParentTagWithName(input, "TABLE");
      if (parentContainer === null) parentContainer = document;
      var tableItemInputs = parentContainer.getElementsByClassName("task-list-item-checkbox");

      for (var i=0, len=tableItemInputs.length; i<len; i++) {
        if (tableItemInputs[i] === input) {
          inputIndex = i;
        }

        // Disable all inputs for now to prevent multiple options being clicked
        // Bee will reload the activity HTML once we get a response back, enabling everything again
        if (tableItemInputs[i].type === 'checkbox') {
          tableItemInputs[i].disabled = true;
        }
      }

      var itemDescriptor = {};
      itemDescriptor["index"] = inputIndex;
      itemDescriptor["checked"] = inputChecked;

      BeeController.performActionWithNameAndIdentifierAndObjectAndAlert('updateTaskList', beeFindIdentifierStartingFromElement(input), itemDescriptor, null);
    }
  });
});

