require(['jquery', "../../../webjars/fancyapps__fancybox/3.5.5/dist/jquery.fancybox.min.js", ], function($, fancybox) {

    $('.xwiki-fancybox-image a').on('click', function(event) {
      event.preventDefault();
      var img = $(this).find('img');
      var index = img.data('index');
      var media = [];
      $('.xwiki-fancybox-image').each(function(index, figure) {
        var $figure = $(figure);
        var $img = $figure.find('img');
        var src = $img.attr('src');
        var caption = $figure.find('.xwiki-fancybox-caption');
        caption = caption.html();
        // In some cases we want to have the same image several times in the gallery:
        // eg a page which uses an image as cover and also down the path in the content
        // var found = media.filter(it => it.src === src);
        // if (found.length == 0) {
        var item = { src: src, caption: caption };
        media.push(item);
        // }
      });

      $.fancybox.open(media, {
        loop : true,
        infobar: true,
        buttons: ["close"],
        image: {
          preload: true
        },
        arrows: true,
        animationEffect: "fade",
        animationDuration: 600,
        transitionDuration: 300,
        idleTime: 3,
        preventCaptionOverlap: false,
        wheel: false,
        thumbs : {
          autoStart : false
        },
        clickSlide: false,
        clickOutside: false,
        afterLoad : function(instance, current) {
          var scaleX = window.screen.width / current.width;
          var scaleY = window.screen.height / current.height;
          var zoom = 1.4;
          if (window.screen.width <= 768) {
            zoom = 3;
          } else if (window.screen.width <= 1024) {
            zoom = 1.6;
          }
          var scale = Math.min(scaleX, scaleY);
          var coeff = scale * zoom;
          current.width = current.width * coeff;
          current.height = current.height * coeff;
        }
      }, index);
      
    })
});


