function callAction(action, callback) {
  chrome.runtime.sendMessage(
    { type: "popupAction", action: action },
    function (response) {
      callback(response || { ok: false });
    }
  );
}

function closePopupSoon() {
  setTimeout(function () {
    window.close();
  }, 40);
}

function bindAction(buttonId, action, closeAfter) {
  var button = document.getElementById(buttonId);
  button.addEventListener("click", function () {
    callAction(action, function () {
      if (closeAfter) {
        closePopupSoon();
      }
    });
  });
}

function refreshSelectionState() {
  var selectionButton = document.getElementById("markdownify-selection");
  callAction("getSelectionState", function (response) {
    var hasSelection = !!(response && response.ok && response.hasSelection);
    selectionButton.disabled = !hasSelection;
  });
}

bindAction("markdownify-url", "markdownifyUrl", true);
bindAction("markdownify-selection", "markdownifySelection", true);
bindAction("select-section", "selectSectionMode", true);
bindAction("zoom-in", "zoomIn", false);
bindAction("zoom-out", "zoomOut", false);
bindAction("fit-vertical", "fitVertical", false);

refreshSelectionState();

