initPhotoSwipe = function () {
    var $pswp = $(".pswp")[0],
        galleries = {},
        size = {},
        photoSwipe;
    jQuery("[data-gallery]").each(function () {
        var $this = $(this);
        var galleryName = $this.data("gallery");
        var gallery = galleries[galleryName] || (galleries[galleryName] = []);
        if ($this.data("size") === undefined) {
            size = [0, 0];
        } else {
            size = $this.data("size").split("x");
        }
        var width  = size[0];
        var height = size[1];
        var index = gallery.push({
            w: width,
            h: height,
            src: $this.attr("href"),
            title: $this.data("photoswipe-caption")
        }) - 1;
        $this.off("click").on("click", function(event) {
            event.preventDefault();
            photoSwipe = new PhotoSwipe($pswp, PhotoSwipeUI_Default, gallery, {
                galleryUID: galleryName,
                index: index,
                bgOpacity: 0.7,
                closeOnScroll: false,
                getDoubleTapZoom: doubleTabZoomFunction
            });

            calculateItemSizeIfNotAvailable(photoSwipe);
            photoSwipe.init();
        });
    });
};

calculateItemSizeIfNotAvailable = function (photoSwipe) {
    photoSwipe.listen("gettingData", function(index, item) {
        if (item.w < 1 || item.h < 1) { // unknown size
            var img = new Image();
            img.onload = function() { // will get size after load
                item.w = this.width; // set image width
                item.h = this.height; // set image height
                photoSwipe.invalidateCurrItems(); // reinit Items
                photoSwipe.updateSize(true); // reinit Items
            }
            img.src = item.src; // let's download image
        }
    });
}

doubleTabZoomFunction = function(isMouseClick, item) {
    if (isMouseClick) {
        return item.initialZoomLevel < 0.7 ? 1 : 1.5
    } else {
        return item.initialZoomLevel * 2;
    }
}

jQuery(document).on("ajaxComplete", function (e) {
    initPhotoSwipe();
});

jQuery(function () {
    if (typeof jsf !== "undefined") {
        jsf.ajax.addOnEvent(function (data) {
            if (data.status == "success") {
                initPhotoSwipe();
            }
        });
    }
    initPhotoSwipe();
});
