// Fullscreen lightbox for the main slideshow image
(function ($) {
  function openLightbox(src, alt) {
    var $lb = $('#lightbox');
    var $img = $('#lightbox-img');
    if (!$lb.length || !$img.length) return;

    $img.attr('src', src || '').attr('alt', alt || '');
    $('body').css('overflow', 'hidden');
    $lb.show().attr('aria-hidden', 'false');
  }

  function closeLightbox() {
    var $lb = $('#lightbox');
    var $img = $('#lightbox-img');
    if (!$lb.length) return;

    $lb.hide().attr('aria-hidden', 'true');
    if ($img.length) $img.attr('src', '');
    $('body').css('overflow', '');
  }

  $(function () {
    // Clicking the big image opens the lightbox. Use delegation because slideshow content is rebuilt.
    $('#slideshow').on('click', 'img', function (e) {
      // Prevent galleriffic's advance-link click handler from firing
      e.preventDefault();
      e.stopPropagation();

      var src = $(this).attr('src');
      var alt = $(this).attr('alt') || '';
      openLightbox(src, alt);
      return false;
    });

    // Close controls
    $(document).on('click', '#lightbox-close, #lightbox .lightbox-backdrop', function (e) {
      e.preventDefault();
      closeLightbox();
      return false;
    });

    $(document).on('keydown', function (e) {
      if (e.keyCode === 27) { // ESC
        closeLightbox();
      }
    });
  });
})(jQuery);


