var zindex = 999999;

document.addEventListener("readystatechange", (event) => {
  // When HTML/DOM elements are ready:
  if (event.target.readyState === "interactive") {
    // Inspired by how https://laasanha.neocities.org/ does it
    var draggableElements =
      document.getElementsByClassName("window-decorations");

    for (var i = 0; i < draggableElements.length; i++) {
      dragElement(draggableElements[i]);
    }

    function dragElement(elmnt) {
      var pos1 = 0,
        pos2 = 0,
        pos3 = 0,
        pos4 = 0;
      var rightJustified =
        elmnt.parentElement.classList.contains("right-justified");
      elmnt.onmousedown = dragMouseDown;
      elmnt.style.cursor = "grab";
      elmnt.getElementsByClassName("window-button-close")[0].onmousedown =
        function closeWindow(e) {
          e = e || window.event;
          e.preventDefault();
          elmnt.parentElement.className += " destroying-anim";
          setTimeout(function () {
            elmnt.parentElement.remove();
          }, 540);
        };

      function dragMouseDown(e) {
        e = e || window.event;
        e.preventDefault();
        // get the mouse cursor position at startup:
        pos3 = e.clientX;
        pos4 = e.clientY;
        zindex += 1;
        elmnt.parentElement.style.zIndex = zindex;
        let style = window.getComputedStyle(elmnt.parentElement);
        pos1 = Number(style.getPropertyValue("top").replace("px", ""));
        if (rightJustified) {
          pos2 = Number(style.getPropertyValue("right").replace("px", ""));
        } else {
          pos2 = Number(style.getPropertyValue("left").replace("px", ""));
        }
        elmnt.style.cursor = "grabbing";
        document.onmouseup = closeDragElement;
        // call a function whenever the cursor moves:
        document.onmousemove = elementDrag;
      }

      function elementDrag(e) {
        e = e || window.event;
        e.preventDefault();
        // calculate the new cursor position:
        // set the element's new position:
        elmnt.parentElement.style.top = pos1 + e.clientY - pos4 + "px";
        if (rightJustified) {
          elmnt.parentElement.style.right = pos2 - e.clientX + pos3 + "px";
        } else {
          elmnt.parentElement.style.left = pos2 + e.clientX - pos3 + "px";
        }
      }

      function closeDragElement() {
        elmnt.style.cursor = "grab";
        // stop moving when mouse button is released:
        document.onmouseup = null;
        document.onmousemove = null;
      }
    }
  }
});
