// Wait for the DOM to load before trying to add listeners to elements
// Can't use DOMContentLoaded Due to TurboLinks
// Can't use Turbolinks page:load event, as that fires when leaving the page
var ready = function() {
    // Clicking on the thumbnail should open the screenshot modal
    var thumbnail = document.getElementById('screenshot-thumbnail');
    thumbnail.addEventListener('click', function(e) {
      e.preventDefault(); // Don't go through the link
      showScreenshotModal();
    }, false);

    // Clicking the close button should close the screenshot modal
    var close_button = document.getElementById('screenshot-close');
    close_button.addEventListener('click', function(e) {
      closeScreenshotModal();
      e.stopPropagation(); // Do not propagate to other click handlers, such as modal background
    }, false);

    // Clicking the background of the modal should close the modal
    var modal_background = document.getElementById('screenshot-modal');
    modal_background.addEventListener('click', function() {
      closeScreenshotModal();
    }, false);

    // Clicking on the image within the modal should NOT close the modal - stop propagation
    var modal_image = document.getElementById('screenshot-modal-content');
    modal_image.addEventListener('click', function(e) {
      e.stopPropagation(); // Do not propagate to other click handlers, such as modal background - would close it
    }, false);
};

// Displays the screenshot modal
function showScreenshotModal() {
  getModal().removeClass('hidden')
}

// Closes the screenshot modal
function closeScreenshotModal() {
  getModal().addClass('hidden')
}

// Return the screenshot modal element
function getModal() {
  return $(document).find('#screenshot-modal');
}

// When the document is ready, attach the event listners
$(document).ready(ready);
