PageSourceSearch

https://www.bonnevaux.com/wp-content/plugins/gallery-by-supsystic/…/Galleries/assets/js/frontend.js?ver=1.21.1

js bonnevaux.com collected 2026-10-02 22:13:33 UTC 119,758 bytes, 3,282 lines download raw bytes

1(function ($, undefined) {
2  window.supSocialSharePrintImage = function (img) {
3    var printFrame = document.createElement('iframe');
4    printFrame.style.display = 'none';
5    document.body.appendChild(printFrame);
6    var printDocument = printFrame.contentWindow.document;
7    printDocument.write('<img style="max-width:100%;" src="' + img + '">');
8    printDocument.close();
9    printFrame.contentWindow.print();
10  };
11
12  jQuery('[data-video-source]').attr('rel', 'video');
13
14  var init = false;
15
16  function Gallery(selector, autoInit) {
17    autoInit = autoInit || false;
18    var $deferred = jQuery.Deferred(),
19      self = this;
20    this.loadedFonts = [];
21
22    this.$container = $(selector);
23    if (window.sggIsMobile) {
24      this.$container.attr('data-is-mobile', window.sggIsMobile[0]);
25    }
26    this.$container.addClass('fitvidsignore');
27    this.$elements = this.$container.find('figure.grid-gallery-caption').fadeIn();
28    this.initialMargin = this.$elements.first().css('margin-bottom');
29    this.$navigation = this.$container.find('nav.grid-gallery-nav');
30
31    this.selectedCategory = '';
32
33    this.galleryContainerId = this.$container.attr('id').replace(/[^a-z0-9]/g, '');
34
35    this.$qsData = null;
36    this.$qsDuration = '750';
37    this.$qsEnable = false;
38    this.areaPosition = this.$container.data('area-position'); // I think we wil need this in future
39
40    this.pagination = {
41      currentPage: 1,
42      limit: 0,
43      total: this.$elements.length,
44      pages: 1,
45      $wrapper: this.$container.find('.grid-gallery-pagination-wrap'),
46    };
47
48    this.loadingText = this.$container.data('show-more-loading-text');
49
50    this.popupTranslates = this.$container.data('popup-i18n-words');
51    if (this.$container.data('exif-as-popup') == 1) {
52      this.popupTitleAttribute = 'data-exif-text';
53    } else {
54      this.popupTitleAttribute = this.$container.data('popup-image-text');
55    }
56    this.popupMaxHeight = '90%';
57    this.popupMaxWidth = '90%';
58    this.popup_opened_image = false;
59    this.popupImageDimension = function () {};
60    this.resizeColorbox = function () {};
61
62    this.socialSharing = this.$container.data('social-sharing');
63    this.socialSharingWrapperClass = 'supsystic-grid-gallery-image-sharing';
64    this.socialSharingImageOperators = {
65      pinterest: 'media',
66    };
67    this.socialButtonsUrl = window.location.href.replace(window.location.hash, '');
68    this.socialButtonsUrl = this.removePopUpHashFromUrl(this.socialButtonsUrl);
69    if (this.socialButtonsUrl.indexOf('#') + 1 == this.socialButtonsUrl.length) {
70      this.socialButtonsUrl = this.socialButtonsUrl.substr(0, this.socialButtonsUrl.length - 1);
71    }
72
73    this.disablePopupHistory = !!this.$container.data('popup-disable-history');
74
75    if (this.isFluidHeight()) {
76      this.$elements.addClass('wookmarked');
77    }
78
79    $(document).trigger('GalleryExtend', this);
80
81    if (autoInit) {
82      // Interval check for init gallery when container becomes visible.
83      // This need to properly load gallery from tabs, accordions or any other hidden containers.
84      self.$container.data(
85        'isVisible',
86        setInterval(function () {
87          if (self.$container.is(':visible') || self.$container.hasClass('hidden-item')) {
88            clearInterval(self.$container.data('isVisible'));
89            self.init();
90          }
91        }, 500)
92      );
93    }
94
95    //Add init flag
96    this.$container.addClass('initialized');
97    return $deferred.resolve();
98  }
99
100  Gallery.prototype.isFluidHeight = function () {
101    return this.$container.is('.grid-gallery-fluid-height');
102  };
103
104  Gallery.prototype.isImageOverlay = function () {
105    return this.$container.find('.crop').is('.image-overlay');
106  };
107
108  Gallery.prototype.isMouseShadowShow = function () {
109    return this.$container.find('.grid-gallery-caption').is('.shadow-show');
110  };
111
112  Gallery.prototype.initQuicksand = function () {
113    if (this.$container.data('quicksand') == 'enabled' && this.$container.data('caption-builder-icons') !== 1) {
114      this.$qsEnable = true;
115      this.$qsDuration = this.$container.data('quicksand-duration');
116      this.$qsHolder = this.$container.find('.grid-gallery-photos:first');
117      this.$qsData = this.$container.find('.grid-gallery-photos > a');
118    }
119  };
120
121  Gallery.prototype.showCaption = function () {
122    var isExifCaption = this.$container.data('exif-as-caption');
123    this.$container.find('.grid-gallery-figcaption-wrap').each(function () {
124      if ($.trim($(this).html()) === '' && !$(this).find('img').length && $(this).has('.hi-icon').length === 0) {
125        $(this).closest('figcaption').remove();
126      }
127    });
128
129    this.$container.find('.gg-image-caption').each(function () {
130      var $this = $(this),
131        captionHtmlEntry = '';
132      if (isExifCaption == 1) {
133        var $objExist = $this.find('object');
134        if ($objExist.length) {
135          captionHtmlEntry = $this
136            .find('object')
137            .html()
138            .replace(/<a(.*?)>(.*?)<\/a>/gi, "<object type='none'>$&</object>");
139        } else {
140          captionHtmlEntry = $this.html();
141        }
142      } else {
143        captionHtmlEntry = $this.text().replace(/<a(.*?)>(.*?)<\/a>/gi, "<object type='none'>$&</object>");
144      }
145      $this.html(captionHtmlEntry);
146      $this.find('a').on('click', function (event) {
147        event.stopPropagation();
148      });
149    });
150
151    $(document).on('click', '.sliphover-container object a', function (event) {
152      event.stopPropagation();
153    });
154  };
155
156  Gallery.prototype.initWookmark = function () {
157    var self = this,
158      horizontalScroll = this.$container.data('horizontal-scroll'),
159      isMobile = parseInt($anyGallery.attr('data-is-mobile')),
160      width = this.$container.data('width'),
161      offset = 0,
162      outerOffset = 0,
163      spacing,
164      windowWidth = $(window).width(),
165      isFixedColumn = this.$container.data('gridType') == 3;
166    // if responsive mode = 'one by one' and mobile -> run this method
167    if (horizontalScroll && horizontalScroll.enabled) {
168      if (horizontalScroll.responsiveMode == 1 && isMobile) {
169      } else {
170        return;
171      }
172    }
173    // not for Mosaic Gallery
174    if (this.$container.data('gridType') == 4) {
175      return;
176    }
177
178    if (this.$container.data('offset')) {
179      offset = this.$container.data('offset');
180    }
181
182    if (this.$container.data('padding')) {
183      outerOffset = parseInt(this.$container.data('padding'));
184    }
185
186    if (String(width).indexOf('%') > -1) {
187      var imagesPerRow = Math.floor(100 / parseInt(width));
188
189      spacing = offset * (imagesPerRow - 1) + outerOffset * 2;
190      width = ((this.$container.width() - spacing) / 100) * parseInt(width);
191
192      $.each(this.$container.find('img'), function () {
193        // $(this).width()/.height() here read whatever box the image
194        // currently occupies pre-resize, which for an image the browser
195        // hasn't finished loading yet collapses to 0 or an unrelated
196        // placeholder size rather than the photo's real proportions -
197        // getOriginalImageSizes() reads the actual loaded pixels (or the
198        // width/height attributes as a reliable fallback) instead, so every
199        // tile in the row gets a correctly-proportioned height alongside
200        // its shared column width, instead of some multiple of the right
201        // answer (or the raw un-scaled attribute value).
202        var sizes = self.getOriginalImageSizes(this),
203          aspectRatio = sizes.width > 0 && sizes.height > 0 ? sizes.width / sizes.height : $(this).width() / $(this).height();
204        $(this).width(width);
205        $(this).height(width / aspectRatio);
206      });
207    }
208
209    if (isFixedColumn) {
210      var defaultWidth = parseInt(width),
211        defaultHeight = parseInt(this.$container.data('height')),
212        koefWidthHeigth = defaultWidth > 0 && defaultHeight > 0 ? defaultHeight / defaultWidth : 1;
213    }
214
215    function resizeColumns() {
216      var columnsNumber = self.getResponsiveColumnsNumber();
217
218      spacing = offset * (columnsNumber - 1) + outerOffset * 2;
219      width = Math.floor(((self.$container.width() - spacing) / 100) * (100 / columnsNumber));
220
221      $.each(self.$elements, function (index, el) {
222        var $el = $(el),
223          $img = $el.find('img');
224        if ($img.length && !$el.hasClass('initialized')) {
225          var imageOriginalSize = self.getOriginalImageSizes($img.get(0)),
226            elWidth = imageOriginalSize.width,
227            elHeight = imageOriginalSize.height,
228            aspectRatio = elWidth > 0 && elHeight > 0 ? elWidth / elHeight : 1,
229            height = width / aspectRatio;
230
231          if (isFixedColumn && $img.attr('data-gg-remote-image') == 1) {
232            height = width * koefWidthHeigth;
233          }
234
235          $el.css({
236            width: width,
237            height: height,
238          });
239          if (!$img.hasClass('ggLazyImg')) {
240            $img.removeClass('ggNotInitImg');
241            self.polaroidCaptionCalculate($el);
242            if ($el.hasClass('initialized')) {
243              setTimeout(function () {
244                $el.trigger('refreshWookmark');
245              }, 350);
246            }
247          }
248        }
249      });
250      self.$container.find('.grid-gallery-photos').removeAttr('data-min-height');
251      return width;
252    }
253
254    if (this.$container.data('columns-number')) {
255      self.$container.find('figure:not(.initialized) img').css({
256        maxWidth: '100%',
257        width: '100%',
258        height: 'auto',
259      });
260
261      resizeColumns();
262    }
263
264    if (this.$container.data('width') !== 'auto' && !this.$qsEnable) {
265      this.wookmark = this.$elements
266        .filter(':visible')
267        .wookmark({
268          autoResize: true,
269          container: this.$container.find('.grid-gallery-photos'),
270          direction: this.areaPosition == 'right' ? 'right' : 'left',
271          fillEmptySpace: false,
272          flexibleWidth: !this.$container.data('columns-number'),
273          itemWidth: width,
274          offset: offset,
275          align: this.areaPosition,
276          outerOffset: outerOffset,
277          onLayoutChanged: function () {
278            setTimeout(function () {
279              self.$container.trigger('wookmark.changed');
280            }, 50);
281          },
282          onResize: function () {
283            if ($(window).width() != windowWidth) {
284              // Fix touchscreen resize event issue see #544
285              windowWidth = $(window).width();
286
287              clearTimeout(self.$container.data('resize.timer'));
288              self.$container.data(
289                'resize.timer',
290                setTimeout(function () {
291                  var overflow = self.$container.css('overflow');
292
293                  self.$container.removeData('resize.timer');
294                  self.$container.css('overflow', 'hidden');
295
296                  if (self.$container.data('columns-number')) {
297                    self.$elements.wookmark({
298                      container: self.$container.find('.grid-gallery-photos'),
299                      itemWidth: resizeColumns(),
300                      offset: offset,
301                    });
302                  }
303
304                  self.$elements.last().one('transitionend webkitTransitionEnd oTransitionEnd', function () {
305                    self.$elements.filter(':visible').trigger('refreshWookmark');
306                  });
307                  self.$elements.filter(':visible').trigger('refreshWookmark');
308                  self.$container.css('overflow', overflow);
309                }, 250)
310              );
311            }
312          },
313        })
314        .css({
315          margin: '0',
316          transition: 'all 0.4s linear',
317        });
318    }
319
320    this.$container.find('.grid-gallery-photos').css('text-align', this.$container.data('area-position'));
321    var minheight = this.$container.find('.grid-gallery-photos').data('min-height');
322    this.$container.find('.grid-gallery-photos').css({
323      'min-height': minheight,
324    });
325    this.$container.filter(':visible').find('.grid-gallery-photos > *').filter(':visible').css({
326      float: 'none',
327      display: 'inline-block',
328      'vertical-align': 'top',
329    });
330  };
331
332  Gallery.prototype.initControll = function () {
333    $(document).on('click', '#cboxRight', function () {
334      $.colorbox.prev();
335    });
336    $(document).on('click', '#cboxLeft', function () {
337      $.colorbox.next();
338    });
339  };
340
341  Gallery.prototype.getPopupDimensions = function (width, height) {
342    var width = $(window).width() < width ? '90%' : width;
343    var height = $(window).height() < height ? '90%' : height;
344
345    if (width == '90%') {
346      width = parseFloat(($(window).width() * parseFloat(width)) / 100);
347    }
348    if (height == '90%') {
349      height = parseFloat(($(window).height() * parseFloat(height)) / 100);
350    }
351
352    return {
353      width: width,
354      height: height,
355    };
356  };
357
358  /**
359   * Get popup title depending on gallery settings
360   * @return string title for popup image
361   */
362  Gallery.prototype.getPopupTitle = function ($element) {
363    var title, $img;
364
365    if ($element.hasClass('hi-icon')) {
366      $img = $element.closest('.grid-gallery-caption').find('img');
367    } else {
368      $img = $element.find('img');
369    }
370
371    title = $img.attr(this.popupTitleAttribute);
372
373    if (!title) {
374      title = $img.attr('title');
375    }
376
377    return title;
378  };
379
380  Gallery.prototype.initPopup = function () {
381    var popupType = (this.popupType = this.$container.data('popup-type')),
382      popupMaxWidth = this.popupMaxWidth,
383      popupMaxHeight = this.popupMaxHeight,
384      sW = this.$container.data('popup-widthsize'),
385      sH = this.$container.data('popup-heightsize'),
386      popupOverlayTransper = this.$container.data('popup-transparency'),
387      popupBackground = this.$container.data('popup-background'),
388      slidePlay = this.$container.data('popup-slideshow') === true,
389      slidePlayAuto = slidePlay && this.$container.data('popup-slideshow-auto') === true,
390      popupHoverStop = slidePlay && this.$container.data('popup-hoverstop') === true,
391      slideshowSpeed = this.$container.data('popup-slideshow-speed'),
392      popupPlacementType = this.$container.data('popup-placement-type'),
393      isLazyLoad = this.$container.data('lazyload-enable') == '1',
394      self = this;
395
396    function generateOverlayColor(selector, background, opacity, optype) {
397      var style = selector + '{',
398        rgb = self.hex2rgb(background);
399      opacity = (100 - opacity) / 100;
400
401      if (background) {
402        color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ', ' + opacity + ')';
403        style += 'background-image:none!important; background-color:' + color + '!important;';
404      } else {
405        if (optype) {
406          style += 'opacity:' + opacity + '!important;';
407        } else {
408          rgb = self.hex2rgb(self.rgb2hex($(selector).css('backgroundColor')));
409          color = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ', ' + opacity + ')';
410          style += 'background-image:none!important; background-color:' + color + '!important;';
411        }
412      }
413      style += '}';
414      $('<style type="text/css"> ' + style + '</style>').appendTo('head');
415    }
416
417    if (!!sW && sW !== 'auto') {
418      popupMaxWidth = sW;
419    } else {
420      sW = '90%';
421    }
422    if (!!sH && sH !== 'auto') {
423      popupMaxHeight = sH;
424    } else {
425      sH = '90%';
426    }
427
428    var getImageDimension = function () {
429      return self.getPopupDimensions(sW, sH);
430    };
431
432    var getColorboxImageDimension = function () {
433      var response = self.getPopupDimensions(sW, sH);
434      if ($(self.popup_opened_image).children('figure').attr('data-linked-images') || $(self.popup_opened_image).hasClass('linked-element')) {
435        response.width -= 120;
436      }
437      return response;
438    };
439
440    var delayResize = (function () {
441      var timer = 0;
442      return function (callback, ms) {
443        clearTimeout(timer);
444        timer = setTimeout(callback, ms);
445      };
446    })();
447
448    this.resizeColorbox = function () {
449      if (self.popup_opened_image === false) return;
450      var dimensions = getColorboxImageDimension();
451      if (self.popup_opened_image.attr && self.popup_opened_image.attr('rel') == 'video' && dimensions.width >= 0.9 * window.innerWidth) {
452        return;
453      }
454
455      $(self.popup_opened_image).data('colorbox').maxWidth = dimensions.width;
456      $(self.popup_opened_image).data('colorbox').maxHeight = dimensions.height;
457
458      $(document).trigger('beforeResizeColorBoxResponsive', this);
459      delayResize(function () {
460        $.colorbox.resizeResponsive(self.popup_opened_image);
461      }, 500);
462    };
463
464    //Responsive popup if width or height > window.width
465    popupMaxWidth = $(window).width() < popupMaxWidth ? '90%' : popupMaxWidth;
466    popupMaxHeight = $(window).height() < popupMaxHeight ? '90%' : popupMaxHeight;
467
468    this.popupMaxWidth = popupMaxWidth;
469    this.popupMaxHeight = popupMaxHeight;
470    this.popupImageDimension = getImageDimension;
471
472    if (popupType && popupType !== 'disable') {
473      this.$container.parentsUntil('body').each(function () {
474        var events = $._data(this, 'events'),
475          el = this;
476
477        if (events && events.click) {
478          $.each(events.click, function (index, ev) {
479            if (ev.selector && self.$container.has($(ev.selector)).length) {
480              $(el).off('click', ev.selector);
481            }
482          });
483        }
484      });
485    }
486
487    var hideLongTooltipTitles = this.$container.data('hide-long-tltp-title');
488
489    //===========|Popup gallery scripts|===========//
490    if (popupType == 'colorbox') {
491      var $this = this.$container;
492      // simple selector
493      var colorBoxItemSelector =
494        '.grid-gallery-photos > .gg-colorbox[data-ecommerce-restrict],' +
495        '.grid-gallery-photos > .gg-colorbox:visible,' +
496        // mosaic selector
497        ' .grid-gallery-photos .gg-mosaic-wrapper .gg-colorbox,' +
498        // icon selector
499        ' .hi-icon.gg-colorbox[data-ecommerce-restrict],' +
500        ' .hi-icon.gg-colorbox:visible';
501      // for popup "Display only first image"
502      if ($this.hasClass('one-photo') || $this.hasClass('hidden-item')) {
503        colorBoxItemSelector = '.grid-gallery-photos > .gg-colorbox, .hi-icon.gg-colorbox';
504      }
505
506      if (this.initColorbox) {
507        this.$container.find(colorBoxItemSelector).colorbox.remove('#' + this.$container.attr('id'));
508      } else {
509        if (hideLongTooltipTitles == 0) {
510          var $colorboxtooltip = $('<div id="sggCboxTooltip">');
511          $(document).on(
512            {
513              mouseenter: function () {
514                $colorboxtooltip.addClass('active');
515              },
516              mouseleave: function () {
517                setTimeout(function () {
518                  $colorboxtooltip.removeClass('active');
519                }, 400);
520              },
521            },
522            '#colorbox.' + $this.data('popup-theme') + ' #cboxTitle'
523          );
524
525          $(document).one('cbox_complete', function (event) {
526            if (!$('#sggCboxTooltip').length) {
527              $('#cboxWrapper').append($colorboxtooltip);
528            }
529          });
530
531          $(document).on('cbox_complete', function (event) {
532            $colorboxtooltip.html($('#cboxTitle').html());
533            if ($('#colorbox').width() < 300) {
534              $('#colorbox').filter('.theme_1').find('#cboxSlideshow').css('bottom', '30px');
535            }
536          });
537        }
538      }
539
540      this.initColorbox = true;
541      var colorBoxConfig = {
542        fadeOut: this.$container.data('popup-fadeOut'),
543        fixed: true,
544        maxHeight: getImageDimension().height,
545        maxWidth: getImageDimension().width,
546        photo: true,
547        scalePhotos: true,
548        scrolling: false,
549        returnFocus: false,
550        trapFocus: false,
551        slideshow: slidePlay && this.$container.data('popup-slideshow-speed'),
552        slideshowAuto: slidePlayAuto,
553        slideshowSpeed: slideshowSpeed,
554        rel: this.$container.attr('id'),
555        slideshowStart: self.popupTranslates.start_slideshow,
556        slideshowStop: self.popupTranslates.stop_slideshow,
557        current: self.popupTranslates.image + ' {current} ' + self.popupTranslates.of + ' {total}',
558        previous: self.popupTranslates.previous,
559        next: self.popupTranslates.next,
560        close: self.popupTranslates.close,
561        isDisableRightClick: this.$container.attr('data-disable-right-click') == 'true',
562        title: function () {
563          return self.getPopupTitle($(this));
564        },
565        speed: 350,
566        transition: 'elastic',
567        onComplete: function (e) {
568          self.changePopUpHash($(e.el).attr('id') || $(e.el).attr('data-id'));
569          self.addSocialShareToPopUp($(e.el), $('#cboxContent'), 'popup');
570          self.$container.find('.grid-gallery-photos > .gg-colorbox, .hi-icon.gg-colorbox').colorbox.resize();
571          $('#cboxLoadedContent').append("<div id='cboxRight'></div><div id='cboxLeft'></div>");
572          window.setTimeout(function () {
573            if (window.colorboxEcommerceRestrict) {
574              window.colorboxEcommerceRestrict($(e.el));
575            }
576          }, 0);
577        },
578        onLoad: function (e) {
579          if (self.popup_opened_image == e.el) return;
580          self.popup_opened_image = e.el;
581          var dimensions = getColorboxImageDimension();
582          $(self.popup_opened_image).data('colorbox').maxWidth = dimensions.width;
583          $(self.popup_opened_image).data('colorbox').maxHeight = dimensions.height;
584        },
585        onOpen: function (e) {
586          //Enable/Disable stop slideshow on mouse hover
587          if (popupHoverStop) {
588            var timeoutId = 0;
589            $('#cboxContent').hover(
590              function () {
591                clearTimeout(timeoutId);
592                $('.cboxSlideshow_on #cboxSlideshow').click();
593              },
594              function () {
595                if (slidePlayAuto) {
596                  clearTimeout(timeoutId);
597                  timeoutId = setTimeout(function () {
598                    $('.cboxSlideshow_off #cboxSlideshow').click();
599                  }, slideshowSpeed);
600                }
601              }
602            );
603          }
604        },
605        onClosed: function () {
606          self.popup_opened_image = false;
607          $('#colorbox').removeClass('gg-cbox-ecommerce-open');
608          $('#cboxEcommerceRestrict').remove();
609          $('#ggEcommerceAccessOverlay').hide();
610          $(window).off('resize.ggEcommerceColorboxPanel');
611          self.clearPopUpHash();
612        },
613      };
614
615      if (popupPlacementType == 1 || popupPlacementType == 2) {
616        colorBoxConfig['maxWidth'] = '100%';
617        colorBoxConfig['imgPlaceType'] = popupPlacementType;
618      }
619      this.$container.find(colorBoxItemSelector).off('click').colorbox(colorBoxConfig);
620
621      $(window).resize(function () {
622        self.resizeColorbox();
623      });
624
625      $('#cboxOverlay')
626        .removeClass()
627        .addClass($this.data('popup-theme') + '-overlay');
628      $('#colorbox').removeClass().addClass($this.data('popup-theme'));
629
630      generateOverlayColor('#cboxOverlay', popupBackground, popupOverlayTransper, true);
631    }
632
633    if (popupType == 'pretty-photo') {
634      // simple selector
635      var prettyPhotoTheme = this.$container.data('popup-theme'),
636        isPrettyPhotoTheme6 = prettyPhotoTheme == 'theme_6',
637        prettyPhotoThemeClass = isPrettyPhotoTheme6 ? 'light_square sgg-theme-6' : 'light_square',
638        prettyPhotoItemSelector =
639        '.grid-gallery-photos > a[data-rel^="prettyPhoto"][data-ecommerce-restrict],' +
640        '.grid-gallery-photos > a[data-rel^="prettyPhoto"]:visible,' +
641        ' .grid-gallery-photos .gg-mosaic-wrapper a[data-rel^="prettyPhoto"],' + // mosaic selector
642        ' .grid-gallery-photos .hi-icon-wrap > a[data-rel^="prettyPhoto"][data-ecommerce-restrict],' +
643        ' .grid-gallery-photos .hi-icon-wrap > a[data-rel^="prettyPhoto"]:visible'; // icon selector
644      if (isPrettyPhotoTheme6) {
645        prettyPhotoItemSelector =
646          '.grid-gallery-photos > a[data-rel^="prettyPhoto"],' +
647          ' .grid-gallery-photos .gg-mosaic-wrapper a[data-rel^="prettyPhoto"],' +
648          ' .grid-gallery-photos .hi-icon-wrap > a[data-rel^="prettyPhoto"]';
649      }
650      // for popup "Display only first image"
651      if (this.$container.hasClass('one-photo') || this.$container.hasClass('hidden-item')) {
652        prettyPhotoItemSelector =
653          '.grid-gallery-photos > a[data-rel^="prettyPhoto"],' +
654          ' .grid-gallery-photos .gg-mosaic-wrapper a[data-rel^="prettyPhoto"],' + // mosaic selector
655          ' .grid-gallery-photos .hi-icon-wrap > a[data-rel^="prettyPhoto"]'; // icon selector
656      }
657
658      if (!this.$prettyPhoto) {
659        if (hideLongTooltipTitles == 0) {
660          var $prettyPhotoTooltip = $('<div id="sggPrettyPhototooltip">');
661          $(document).on(
662            {
663              mouseenter: function () {
664                $prettyPhotoTooltip.addClass('active');
665              },
666              mouseleave: function () {
667                setTimeout(function () {
668                  $prettyPhotoTooltip.removeClass('active');
669                }, 400);
670              },
671            },
672            '.pp_content_container .pp_description'
673          );
674        }
675
676        if (this.$container.attr('data-show-buttonlink-in-popup') == 1 && window.prettyPhotoDetailLink) {
677          this.loadButtonsFontFamily(this.$container.attr('data-buttonlink-font'), null);
678        }
679
680        this.$prettyPhoto = this.$container
681          .find(prettyPhotoItemSelector)
682          .off('click')
683          .ggPrettyPhoto({
684            hook: 'data-rel',
685            theme: prettyPhotoThemeClass,
686            allow_resize: true,
687            allow_expand: true,
688            deeplinking: false,
689            slideshow: slidePlay && this.$container.data('popup-slideshow-speed'),
690            autoplay_slideshow: slidePlayAuto,
691            social_tools: '',
692            default_width: popupMaxWidth,
693            default_height: popupMaxHeight,
694            getImageDimensions: getImageDimension,
695            is_lazy_load: isLazyLoad,
696            ppTranslates: self.popupTranslates,
697            isDisableRightClick: this.$container.attr('data-disable-right-click') == 'true',
698            isShowRotateBtn: this.$container.attr('data-show-rotate-btn-in-popup') == 1,
699            isShowAttributes: this.$container.attr('data-show-attributes-in-popup') == 1,
700            isShowEcommerceRestrict: true,
701            attributesPosition: this.$container.attr('data-attributes-position'),
702            attributesWidth: this.$container.attr('data-attributes-width') || 200,
703            isShowButtonLink: this.$container.attr('data-show-buttonlink-in-popup') == 1,
704            buttonLinkStyle: this.$container.attr('data-buttonlink-style'),
705            isShowLinkBtn: this.$container.attr('data-show-link-btn-in-popup') == 1,
706            isShowHovThumbnail: this.$container.attr('data-show-thumb-hov-in-popup') == 1,
707            galleryId: this.$container.attr('data-gg-id'),
708            getTitle: function () {},
709            setImageTitleForPrepare: function ($element) {
710              var imgTile = self.getPopupTitle($element);
711              return imgTile;
712            },
713            popup_border_type: this.$container.attr('data-popup-border-type'),
714            popup_border_color: this.$container.attr('data-popup-border-color'),
715            popup_border_width: this.$container.attr('data-popup-border-width'),
716            popup_border_enable: this.$container.attr('data-popup-border-enable') == 'on',
717            changepicturecallback: function (element) {
718              self.changePopUpHash(element.attr('id') || element.attr('data-id'));
719              self.popup_opened_image = element;
720              $('.pp_description').html(self.getPopupTitle(element)).show();
721              //add social share buttons if enabled
722              self.addSocialShareToPopUp(element, $('.pp_hoverContainer'), 'popup');
723              if (!slidePlay) {
724                $('.pp_play').hide();
725              }
726              // change detail link url
727              if (self.$container.attr('data-show-link-btn-in-popup') == 1 && window.prettyPhotoDetailLink) {
728                window.prettyPhotoDetailLink(element);
729              }
730              if (self.$container.attr('data-show-attributes-in-popup') == 1 && window.prettyPhotoAttributes) {
731                window.prettyPhotoAttributes(element, self.$container);
732              }
733              if (window.prettyPhotoEcommerceRestrict) {
734                window.prettyPhotoEcommerceRestrict(element);
735              }
736
737              //Enable/Disable stop slideshow on mouse hover
738              if (popupHoverStop) {
739                $('.pp_hoverContainer').hover(
740                  function () {
741                    $('.pp_nav .pp_pause').click();
742                  },
743                  function () {
744                    if (slidePlayAuto) {
745                      $('.pp_nav .pp_play').click();
746                    }
747                  }
748                );
749              }
750              var $_desc = $('.pp_description'),
751                desc_height = parseInt($_desc.height()),
752                desc_line_height = parseInt($_desc.css('font-size'));
753              if (desc_line_height < desc_height) {
754                $('.pp_content').height($('.pp_fade').outerHeight(true) + $('.pp_details').outerHeight(true));
755              }
756
757              if (hideLongTooltipTitles == 0) {
758                if (!$('#sggPrettyPhototooltip').length) {
759                  $('.pp_content_container .pp_content').append($prettyPhotoTooltip);
760                }
761                $prettyPhotoTooltip.html($('.pp_content_container .pp_description').html());
762              }
763            },
764            callback: function () {
765              self.popup_opened_image = false;
766              self.clearPopUpHash();
767            },
768          });
769        $(window).resize(function () {
770          if (!self.popup_opened_image || !self.$prettyPhoto) return;
771          //if(self.$prettyPhoto[0].closest('div') != self.popup_opened_image[0].closest('div')) return;
772          self.$prettyPhoto.open(self.popup_opened_image);
773        });
774      } else {
775        this.$prettyPhoto.refresh(this.$container.find(prettyPhotoItemSelector));
776      }
777
778      generateOverlayColor('.pp_overlay', popupBackground, popupOverlayTransper, true);
779    }
780
781    if (popupType == 'photobox') {
782      var photoBoxItemSelector = 'a.pbox:visible',
783        photoBoxConfig = null;
784      // for popup "Display only first image"
785      if (this.$container.hasClass('one-photo') || this.$container.hasClass('hidden-item') || this.$container.data('gridType') == '4') {
786        photoBoxItemSelector = 'a.pbox';
787      }
788
789      if (this.initPhotobox) {
790        this.$container.find('.grid-gallery-photos').photobox('destroy');
791      }
792      this.initPhotobox = true;
793      photoBoxConfig = {
794        autoplay: slidePlayAuto,
795        isDisableRightClick: this.$container.attr('data-disable-right-click') == 'true',
796        thumb: function (link) {
797          if (self.$container.data('caption-buider') == '1' && self.$container.data('caption-builder-icons') == 1) {
798            return link.closest('.grid-gallery-caption').find('img')[0];
799          } else if (self.$container.data('icons')) {
800            return link.closest('.grid-gallery-caption').find('img')[0];
801          }
802          return null;
803        },
804        getTitle: function (el) {
805          var nameTitle = self.getPopupTitle($(el));
806          return nameTitle;
807        },
808        beforeShow: function (element) {
809          self.changePopUpHash($(element).attr('id') || $(element).attr('data-id'));
810          self.addSocialShareToPopUp($(element), $('#pbCaption'), 'photobox', true);
811        },
812        afterClose: function () {
813          self.clearPopUpHash();
814        },
815      };
816      if (isLazyLoad) {
817        photoBoxConfig['thumbAttr'] = 'data-gg-real-image-href';
818      }
819
820      this.$container.find('.grid-gallery-photos').off('click').photobox(photoBoxItemSelector, photoBoxConfig);
821
822      //Hide autoplay button when slideshow = false
823      if (!this.$container.data('popup-slideshow')) {
824        $('#pbAutoplayBtn').hide();
825      }
826
827      //Enable/Disable stop slideshow on mouse hover
828      if (popupHoverStop) {
829        $('.pbWrapper img').hover(
830          function () {
831            $('#pbOverlay .playing').click();
832          },
833          function () {
834            if (slidePlayAuto) {
835              $('#pbOverlay .play').click();
836            }
837          }
838        );
839      }
840
841      generateOverlayColor('#pbOverlay', popupBackground, popupOverlayTransper);
842    }
843    //===========|Popup gallery scripts|===========//
844  };
845
846  Gallery.prototype.preventImages = function () {
847    var popupType = this.$container.data('popup-type');
848
849    if (popupType == 'disable') {
850      this.$container.find('a.gg-link').off('click');
851      this.$container.find('a.gg-link:not([data-type=link])').addClass('disabled');
852      this.$container.on('click', 'a.gg-link', function (event) {
853        if ($(this).data('type') !== 'link') {
854          event.preventDefault();
855          event.stopPropagation();
856        }
857      });
858    }
859  };
860
861  Gallery.prototype.getResponsiveColumnsNumber = function () {
862    var columnsData = this.$container.data('responsive-colums'),
863      settings = [],
864      columnsNumber = parseInt(this.$container.data('columns-number'));
865
866    for (var key in columnsData) {
867      settings.push(columnsData[key]);
868    }
869
870    settings.sort(function (a, b) {
871      a.width = Number(a.width);
872      b.width = Number(b.width);
873      if (a.width > b.width) {
874        return 1;
875      } else if (a.width < b.width) {
876        return -1;
877      } else {
878        return 0;
879      }
880    });
881
882    for (var i = 0, len = settings.length, windowWidth = $(window).width(), minBreakpoint = 0; i < len; i++) {
883      if (windowWidth > minBreakpoint && windowWidth <= settings[i].width) {
884        columnsNumber = Number(settings[i].columns);
885        break;
886      }
887      minBreakpoint = settings[i].width;
888    }
889
890    return columnsNumber;
891  };
892
893  Gallery.prototype.initRowsMode = function () {
894    var columnsNumber = parseInt(this.$container.data('columns-number'));
895
896    if (this.$container.data('horizontal-scroll')) {
897      return;
898    }
899
900    if (typeof this.$container.data('responsive-colums') == 'object') {
901      columnsNumber = this.getResponsiveColumnsNumber();
902    }
903
904    if (columnsNumber) {
905      var containerWidth = parseInt(this.$container.width()),
906        spacing = parseInt(this.$container.data('offset')),
907        scaleHeight = parseInt(this.$container.data('width')) / parseInt(this.$container.data('height')),
908        elementWidth = null,
909        elementHeight = null;
910
911      elementWidth = Math.floor((this.$container.width() - (columnsNumber - 1) * spacing) / columnsNumber);
912      elementHeight = Math.floor(elementWidth / scaleHeight);
913
914      this.$elements.each(function () {
915        var $this = $(this);
916        if (!$this.find('.post-feed-crop').length) {
917          $this.css('width', elementWidth);
918          if (!isNaN(elementHeight)) {
919            $this.css('height', elementHeight);
920          } else {
921            $this.css('height', 'auto');
922          }
923        } else {
924          $this.find('figcaption').css('width', elementWidth);
925        }
926      });
927
928      this.$elements.find('.crop').css({
929        width: 'auto',
930        height: 'auto',
931      });
932    }
933  };
934
935  Gallery.prototype.setImagesHeight = function () {
936    var $images = this.$container.find('img');
937
938    if ($images != undefined && $images.length > 0) {
939      $images.each(function () {
940        var $image = $(this),
941          $wrapper = $image.parent();
942
943        if ($image.height() < $wrapper.height()) {
944          $wrapper.css('height', $image.height());
945        }
946      });
947    }
948  };
949
950  Gallery.prototype.setOverlayTransparency = function () {
951    this.$elements.find('figcaption, [class*="caption-with-icons"]').each(function () {
952      var $caption = $(this),
953        alpha = (10 - parseInt($caption.data('alpha'), 10)) / 10,
954        rgb = $caption.css('background-color'),
955        rgba = rgb.replace(')', ', ' + alpha + ')').replace('rgb', 'rgba');
956
957      $caption.css('background', rgba);
958    });
959  };
960
961  Gallery.prototype.setIconsPosition = function () {
962    var self = this;
963    this.$elements.each(function () {
964      var $element = $(this),
965        isCaptionBuilderUsed = self.$container.data('caption-buider'),
966        // polaroid centers its icon wrap with flexbox now (see the
967        // [data-grid-gallery-type='polaroid'] .hi-icon-wrap rules in
968        // grid-gallery.galleries.effects.css) instead of this manual
969        // per-icon margin math - applying both would push icons off-center.
970        isPolaroid = $element.data('grid-gallery-type') == 'polaroid',
971        $wrapper = $element.find('div.hi-icon-wrap'),
972        $icons = $element.find('a.hi-icon'),
973        marginX = $wrapper.data('margin'),
974        iconCount = $icons.length;
975
976      if (!iconCount) {
977        return;
978      }
979
980      // Measured once, before any icon gets a margin - a photo can show more
981      // than one icon at a time (e.g. an external link icon alongside the
982      // popup icon), and for polaroid specifically figcaption is in normal
983      // flow (position: relative, not absolute), so its own height feeds
984      // straight into the card's height:auto. Re-reading $element.height()
985      // inside the loop below (as this used to) means each icon "centers"
986      // itself against a parent the PREVIOUS icon's own margin just made
987      // taller, snowballing into runaway growth with 2+ icons - which is
988      // what was making some cards (and everything positioned after them,
989      // via the masonry packing) taller than their siblings.
990      //
991      // The icon wrap lives inside <figcaption>, so it should center against
992      // figcaption's OWN height, not $element's. For every type but polaroid
993      // figcaption is an absolutely-positioned overlay the size of the photo,
994      // so this is normally the same number as $element.height() - no change
995      // there. For polaroid, figcaption is a separate, much shorter strip
996      // below the photo (normal flow, not an overlay), so using the whole
997      // card's height instead (as this used to) way overshoots the strip's
998      // actual height and pushes icons toward its bottom edge/off it entirely.
999      // A figure sits display:none until Wookmark (or, for a paginated
1000      // gallery, page navigation) reveals it - $figcaption.height() and
1001      // $icons.first().height() both read 0 for a hidden subtree, which
1002      // baked a wrong, height-independent margin-top into every icon on
1003      // every not-yet-shown page as soon as this ran once at gallery init.
1004      // That inline value then never got recomputed once the page was
1005      // actually navigated to, permanently overriding the CSS 33.33% rule
1006      // with the wrong number. Skipping margin-top here for a still-hidden
1007      // figure leaves that CSS rule in charge - it centers correctly on its
1008      // own once the figure is visible - for exactly the single-icon case
1009      // this was silently breaking; showCurrentPage() also now re-runs this
1010      // function after revealing a new page, which additionally restores
1011      // the multi-icon stacking math this skip leaves out in the meantime.
1012      var $figcaption = $element.find('figcaption'),
1013        isHidden = $element.is(':hidden'),
1014        elementHeight = $figcaption.length ? $figcaption.height() : $element.height(),
1015        iconHeight = $icons.first().height(),
1016        groupHeight = iconCount * iconHeight,
1017        startMarginTop = Math.abs(elementHeight / 2 - groupHeight / 2 - 10);
1018
1019      $icons.each(function (index) {
1020        var $icon = $(this),
1021          marginData = {};
1022
1023        if (marginX && !isCaptionBuilderUsed && !isPolaroid) {
1024          marginData['margin-left'] = marginX;
1025          marginData['margin-right'] = marginX;
1026        }
1027        if (elementHeight && !isCaptionBuilderUsed && !isPolaroid && !isHidden) {
1028          marginData['margin-top'] = startMarginTop + index * iconHeight;
1029        }
1030        $icon.css(marginData);
1031      });
1032    });
1033  };
1034
1035  Gallery.prototype.initCategories = function () {
1036    var $defaultElement = this.$navigation.find('a[data-tag="__all__"]'),
1037      $elements = this.$navigation.find('a'),
1038      $defaultBackground = $elements.first().css('background-color');
1039
1040    function shadeColor(color, percent) {
1041      var f = parseInt(color.slice(1), 16),
1042        t = percent < 0 ? 0 : 255,
1043        p = percent < 0 ? percent * -1 : percent,
1044        R = f >> 16,
1045        G = (f >> 8) & 0x00ff,
1046        B = f & 0x0000ff;
1047      return '#' + (0x1000000 + (Math.round((t - R) * p) + R) * 0x10000 + (Math.round((t - G) * p) + G) * 0x100 + (Math.round((t - B) * p) + B)).toString(16).slice(1);
1048    }
1049
1050    bg = shadeColor('#' + this.rgb2hex($elements.first().css('borderTopColor')), 0.3);
1051
1052    this.$navigation.find('a').on(
1053      'click',
1054      $.proxy(function (event) {
1055        event.preventDefault();
1056
1057        var $category = $(event.currentTarget),
1058          requested = String($category.data('tag')),
1059          _defaultTag = '__all__',
1060          currentGallery = this.$navigation.parent().attr('id');
1061
1062        $elements.css('background-color', $defaultBackground);
1063        $category.css('background-color', bg);
1064
1065        if (requested == _defaultTag) {
1066          this.$elements
1067            .each(function () {
1068              if ($(this).parent().attr('rel')) {
1069                $(this)
1070                  .parent()
1071                  .attr('rel', 'prettyPhoto[' + currentGallery + ']');
1072              }
1073            })
1074            .fadeIn();
1075
1076          this.correctMargin();
1077          this.initWookmark();
1078
1079          if (!this.isFluidHeight() && this.$qsEnable) {
1080            this.callQuicksand(this.$qsHolder, this.$qsData, this.$qsDuration);
1081          }
1082          return false;
1083        }
1084
1085        if (!this.isFluidHeight() && this.$qsEnable) {
1086          var $filteredData = this.$qsData.filter(function () {
1087            var tags = $(this).children().data('tags');
1088            if (typeof tags !== 'undefined') {
1089              tags = tags.split('|');
1090            }
1091            return $.inArray(requested, tags) > -1;
1092          });
1093          this.callQuicksand(this.$qsHolder, $filteredData, this.$qsDuration);
1094        } else {
1095          $hidden = $();
1096          $visible = $();
1097          this.$elements.each(function () {
1098            var $element = $(this),
1099              tags = $element.data('tags');
1100
1101            if (typeof tags != 'string') {
1102              tags = String(tags);
1103            }
1104
1105            if (tags != undefined) {
1106              tags = tags.split('|');
1107            }
1108            if ($.inArray(requested, tags) > -1) {
1109              if ($element.parent().attr('rel')) {
1110                $element.parent().attr('rel', 'prettyPhoto[' + currentGallery + '-' + requested + ']');
1111              }
1112              $visible.push(this);
1113            } else {
1114              $hidden.push(this);
1115            }
1116          });
1117
1118          $.when($hidden.fadeOut()).done(
1119            $.proxy(function () {
1120              $visible.fadeIn().css({ height: '' });
1121              this.correctMargin();
1122              this.initWookmark();
1123            }, this)
1124          );
1125        }
1126      }, this)
1127    );
1128
1129    var firstTag = $elements.first().data('tag');
1130    this.$container.find('a[data-tag="' + firstTag + '"]').trigger('click');
1131  };
1132
1133  Gallery.prototype.callQuicksand = function ($holder, $filteredData, duration) {
1134    self = this;
1135
1136    $filteredData.find('figure.grid-gallery-caption').css('margin', this.initialMargin).parent().css('clear', 'none');
1137
1138    $holder.quicksand(
1139      $filteredData,
1140      {
1141        duration: Number(duration),
1142        easing: 'swing',
1143        attribute: 'href',
1144      },
1145      function () {
1146        $holder
1147          .css({
1148            width: 'auto',
1149            height: 'auto',
1150          })
1151          .append('<div class="grid-gallery-clearfix"></div>');
1152        self.initPopup();
1153        self.correctMargin();
1154        if (self.$container.data('lazyload-enable') == '1') {
1155          // images area removed and filled new images
1156          self.initLazyLoad();
1157        }
1158      }
1159    );
1160  };
1161
1162  Gallery.prototype.hidePopupCaptions = function () {
1163    //never show alternative text for popup theme 6 on top of popup
1164    $('<style type="text/css">.ppt{ display:none!important; }</style>').appendTo('head');
1165    if (this.$container.data('popup-captions') == 'hide') {
1166      $('<style type="text/css">#cboxTitle, #cboxCurrent, .pbCaptionText, .ppt, .pp_description { display:none!important; }</style>').appendTo('head');
1167    }
1168  };
1169
1170  Gallery.prototype.hidePaginationControls = function () {
1171    return false;
1172  };
1173
1174  Gallery.prototype.setImageOverlay = function () {
1175    if (this.isImageOverlay()) {
1176      this.$container.find('.grid-gallery-caption').each(function () {
1177        var image = $(this).find('img');
1178        var crop = $(this).find('.image-overlay');
1179        image.css('opacity', '0.2');
1180        crop.css('background-color', '#424242');
1181        $(this).on('mouseenter', function () {
1182          image.css('opacity', '1.0');
1183          crop.css('background-color', 'inherit');
1184        });
1185        $(this).on('mouseleave', function () {
1186          image.css('opacity', '0.2');
1187          crop.css('background-color', '#424242');
1188        });
1189      });
1190    }
1191  };
1192
1193  Gallery.prototype.setMouseShadow = function () {
1194    var shadow = null,
1195      $selector = null,
1196      $captions = this.$container.find('.grid-gallery-caption'),
1197      self = this,
1198      showOver = function (event) {
1199        if (event.type === 'mouseenter') {
1200          $(this).css('box-shadow', self.mouseOverBoxShadow);
1201        } else {
1202          $(this).css('box-shadow', 'none');
1203        }
1204      },
1205      hideOver = function (event) {
1206        if (event.type === 'mouseenter') {
1207          $(this).css('box-shadow', 'none');
1208        } else {
1209          $(this).css('box-shadow', self.mouseOverBoxShadow);
1210        }
1211      };
1212    // only first Init elem has correct value
1213    if (!self.mouseOverBoxShadow) {
1214      self.mouseOverBoxShadow = $captions.filter(':first').css('box-shadow');
1215    }
1216
1217    if ($captions.is('.shadow-show')) {
1218      $captions.css('box-shadow', 'none');
1219      // 'hover' is not a real DOM event - jQuery only ever treated it as an
1220      // alias when passed to .bind()/.on(), and that alias was removed in
1221      // jQuery 1.9. With the 3.7.1 bundled here it just registers a listener
1222      // for an event that never fires, so showOver/hideOver never ran.
1223      $captions.off('mouseenter.mouseShadow mouseleave.mouseShadow').on('mouseenter.mouseShadow mouseleave.mouseShadow', showOver);
1224    } else if ($captions.is('.shadow-hide')) {
1225      $captions.off('mouseenter.mouseShadow mouseleave.mouseShadow').on('mouseenter.mouseShadow mouseleave.mouseShadow', hideOver);
1226    }
1227  };
1228
1229  Gallery.prototype.initPagination = function () {
1230    var perPage = parseInt(this.$container.find('.grid-gallery-photos').data('per-page'), 10),
1231      buffer = [],
1232      page = 1,
1233      offset = 0;
1234    self = this;
1235
1236    if (isNaN(perPage)) {
1237      this.$elements.fadeIn();
1238      return false;
1239    }
1240
1241    if (this.$container.data('gridType') == 4 && this.$container.data('show-mosaic-all-img') != 1) {
1242      this.$elements.fadeIn();
1243      this.pagination.wrapper.hide();
1244      return false;
1245    }
1246
1247    var showCurrentPage = function (gallery) {
1248      gallery.$elements.removeClass('current-page').hide(350);
1249
1250      $.each(buffer[gallery.pagination.currentPage], function () {
1251        $(this)
1252          .addClass('current-page')
1253          .css({ height: gallery.$container.data('height'), width: gallery.$container.data('width') })
1254          .show(function () {
1255            gallery.setIconsPosition();
1256            self.correctMargin();
1257          });
1258      });
1259      /*
1260             if (!gallery.isFluidHeight()) {
1261             $('.current-page .crop').css('height', function () {
1262             var height = null;
1263             $('.crop img').each(function () {
1264             if($(this).height() && !height) {
1265             height = $(this).height();
1266             }
1267             });
1268             return height;
1269             });
1270             }
1271             */
1272    };
1273
1274    this.pagination.limit = perPage;
1275
1276    this.$elements
1277      .each(
1278        $.proxy(function (index, el) {
1279          var currentIndex = index + 1;
1280
1281          if (currentIndex - offset <= this.pagination.limit) {
1282            if (!$.isArray(buffer[page])) {
1283              buffer[page] = [];
1284            }
1285
1286            buffer[page].push(el);
1287          } else {
1288            offset += this.pagination.limit;
1289            page += 1;
1290
1291            buffer[page] = [el];
1292          }
1293        }, this)
1294      )
1295      .hide();
1296
1297    this.pagination.pages = Math.ceil(this.pagination.total / this.pagination.limit);
1298
1299    var element = this.pagination.$wrapper.find('a.grid-gallery-page[data-page="1"]');
1300    element.css('font-size', '19pt');
1301
1302    this.pagination.$wrapper.find('a.grid-gallery-page').on(
1303      'click',
1304      $.proxy(function (e) {
1305        e.preventDefault();
1306
1307        var element = $(e.currentTarget);
1308        var galery = Gallery.prototype;
1309        this.pagination.$wrapper.find('a.grid-gallery-page').each(function () {
1310          $(this).css('font-size', 'inherit');
1311        });
1312        galery.selectedCategory = element.data('page');
1313        element.css('font-size', '19pt');
1314
1315        var $anchor = $(e.currentTarget),
1316          requestedPage = $anchor.data('page');
1317
1318        this.pagination.currentPage = requestedPage;
1319
1320        showCurrentPage(this);
1321
1322        return false;
1323      }, this)
1324    );
1325
1326    showCurrentPage(this);
1327  };
1328
1329  Gallery.prototype.hex = function (x) {
1330    return isNaN(x) ? '00' : hexDigits[(x - (x % 16)) / 16] + hexDigits[x % 16];
1331  };
1332
1333  Gallery.prototype.rgb2hex = function (rgb) {
1334    if (rgb) {
1335      rgb = rgb.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(0\.\d+))?\)$/);
1336      function hex(x) {
1337        return ('0' + parseInt(x).toString(16)).slice(-2);
1338      }
1339      return hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
1340    }
1341  };
1342
1343  Gallery.prototype.hex2rgb = function (hex) {
1344    var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
1345    hex = hex.replace(shorthandRegex, function (m, r, g, b) {
1346      return r + r + g + g + b + b;
1347    });
1348
1349    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
1350    return result
1351      ? {
1352          r: parseInt(result[1], 16),
1353          g: parseInt(result[2], 16),
1354          b: parseInt(result[3], 16),
1355        }
1356      : null;
1357  };
1358
1359  Gallery.prototype.importFontFamily = function (familyName) {
1360    var styleId = 'sggFontFamilyStyle',
1361      $style = $('#' + styleId);
1362    if (!$style.length) {
1363      $style = $('<style/>', { id: styleId });
1364      $('head').append($style);
1365    }
1366    familyName = familyName.replace(/\s+/g, '+').replace(/"/g, '');
1367
1368    var obj = document.getElementById(styleId),
1369      sheet = obj.sheet || obj.styleSheet;
1370    if (this.loadedFonts.indexOf(familyName) === -1) {
1371      if (sheet.insertRule) {
1372        sheet.insertRule('@import url("//fonts.googleapis.com/css?family=' + familyName + '"); ', 0);
1373      } else if (sheet.addImport) {
1374        sheet.addImport('//fonts.googleapis.com/css?family=' + familyName);
1375      }
1376      this.loadedFonts.push(familyName);
1377    }
1378  };
1379
1380  Gallery.prototype.loadFontFamily = function () {
1381    font = this.$container.data('caption-font-family');
1382    if (typeof font !== 'undefined') {
1383      if (window && window.sggStandartFontsList && $.inArray(font.replace(/\"/g, ''), window.sggStandartFontsList) != -1) {
1384        return false;
1385      }
1386      if (font && font !== 'Default') {
1387        this.importFontFamily(font);
1388      }
1389    } else {
1390      return false;
1391    }
1392  };
1393
1394  Gallery.prototype.initCaptionCalculations = function () {
1395    var self = this;
1396
1397    this.$container.find('.grid-gallery-caption').each(function () {
1398      wrap = $(this).find('div.grid-gallery-figcaption-wrap');
1399      figcaption = $(this).find('figcaption');
1400
1401      wrap.css({
1402        display: 'table-cell',
1403        'text-align': figcaption.css('text-align'),
1404      });
1405
1406      wrap.wrap(
1407        $('<div>', {
1408          css: {
1409            display: 'table',
1410            height: '100%',
1411            width: '100%',
1412          },
1413        })
1414      );
1415    });
1416  };
1417
1418  Gallery.prototype.checkDirection = function ($element, e) {
1419    var w = $element.width(),
1420      h = $element.height(),
1421      x = (e.pageX - $element.offset().left - w / 2) * (w > h ? h / w : 1),
1422      y = (e.pageY - $element.offset().top - h / 2) * (h > w ? w / h : 1);
1423
1424    return Math.round((Math.atan2(y, x) * (180 / Math.PI) + 180) / 90 + 3) % 4;
1425  };
1426
1427  Gallery.prototype.generateOverlayCaptionColor = function (overlayColor, alpha) {
1428    if (typeof overlayColor == 'string') {
1429      overlayColor = overlayColor.split(')');
1430
1431      if (overlayColor.length > 0) {
1432        overlayColor = overlayColor[0].split('(');
1433
1434        if (overlayColor.length > 1) {
1435          var chanels = overlayColor[1].split(',');
1436
1437          if (chanels.length == 4) {
1438            // it is already rgba (fix for IE)
1439            overlayColor[0] = overlayColor[0].replace('a', '');
1440            chanels.splice(-1, 1);
1441            overlayColor[1] = chanels.join(',');
1442          }
1443          return overlayColor[0] + 'a(' + overlayColor[1] + ', ' + (1 - alpha / 10) + ')';
1444        }
1445      }
1446    }
1447    return overlayColor;
1448  };
1449
1450  Gallery.prototype.initCaptionEffects = function () {
1451    var self = this,
1452      allwaysShowCaptionOnMobile = this.$container.data('caption-mobile'),
1453      disableCaptionOnMobile = this.$container.data('caption-disabled-on-mobile'),
1454      isMobile = !!parseInt(this.$container.data('is-mobile'));
1455
1456    if (isMobile && navigator && navigator.userAgent && navigator.userAgent.indexOf('Safari') > -1) {
1457      var $3dCubeCaptions = this.$container.find('.grid-gallery-caption[data-grid-gallery-type="3d-cube"]');
1458      $3dCubeCaptions.attr('data-grid-gallery-type', 'revolving-door-bottom');
1459      $3dCubeCaptions.data('grid-gallery-type', 'revolving-door-bottom');
1460    }
1461
1462    $.each(this.$elements, function (index, el) {
1463      var $el = $(el),
1464        overlayColor = $el.find('figcaption').css('backgroundColor'),
1465        alpha = parseInt($el.find('figcaption').data('alpha'));
1466
1467      if (isMobile && allwaysShowCaptionOnMobile) {
1468        $el.attr('data-grid-gallery-type', 'none');
1469      }
1470
1471      if ($el.data('grid-gallery-type') == 'cube') {
1472        $el.on('mouseenter mouseleave', function (e) {
1473          var $figcaption = $(this).find('figcaption'),
1474            direction = self.checkDirection($(this), e),
1475            classHelper = null;
1476
1477          switch (direction) {
1478            case 0:
1479              classHelper = 'cube-' + (e.type == 'mouseenter' ? 'in' : 'out') + '-top';
1480              break;
1481            case 1:
1482              classHelper = 'cube-' + (e.type == 'mouseenter' ? 'in' : 'out') + '-right';
1483              break;
1484            case 2:
1485              classHelper = 'cube-' + (e.type == 'mouseenter' ? 'in' : 'out') + '-bottom';
1486              break;
1487            case 3:
1488              classHelper = 'cube-' + (e.type == 'mouseenter' ? 'in' : 'out') + '-left';
1489              break;
1490          }
1491
1492          $figcaption.removeClass().addClass(classHelper);
1493        });
1494      }
1495
1496      if ($el.data('grid-gallery-type') == 'direction-aware') {
1497        var color = $el.find('figcaption').css('color'),
1498          isCaptionBuilderUsed = self.$container.data('caption-buider'),
1499          classStr = '',
1500          addAttr = '',
1501          align = $el.find('figcaption').css('text-align');
1502
1503        if (isCaptionBuilderUsed == 1) {
1504          $el.attr('data-caption', '<div style="padding:0px; height: ' + $el.height() + 'px;
1504 font-family:' + self.$container.data('caption-font-family') + '; font-size:' + self.$container.data('caption-text-size') + '">' + ($el.find('figcaption').html() || '') + '</div>');
1505        } else {
1506          var $ggImgCaption = $el.find('.gg-image-caption');
1507          if ($ggImgCaption.hasClass('ggRtlClass')) {
1508            classStr = 'ggRtlClass';
1509            addAttr = 'dir="rtl"';
1510          }
1511          $el.attr('data-caption', '<div class="' + classStr + '" ' + addAttr + ' style="padding:20px;font-family:' + self.$container.data('caption-font-family') + '; font-size:' + self.$container.data('caption-text-size') + ';">' + ($ggImgCaption.html() || '') + '</div>');
1512        }
1513
1514        $el.sliphover({
1515          target: $el,
1516          backgroundColor: self.generateOverlayCaptionColor(overlayColor, alpha),
1517          fontColor: color,
1518          textAlign: align,
1519          caption: 'data-caption',
1520        });
1521      }
1522
1523      if ($el.data('grid-gallery-type') == '3d-cube') {
1524        if (!$el.find('.box-3d-cube-scene').length) {
1525          var cubeWidth = $el.width(),
1526            cubeHeight = $el.height();
1527          // $el.addClass('box-3d-cube-scene');
1528          $el.children('div').addClass('front').addClass('face');
1529          $el.children('figcaption').addClass('back').addClass('face');
1530          $el.html('<div class="box-3d-cube-scene"><div class="box-3d-cube">' + $el.html() + '</div></div>');
1531          // $el.html("<div class='box-3d-cube-scene'><div class='box-3d-cube'><div class='front face'><img src='http://placehold.it/"+cubeWidth+"x"+cubeHeight+"/' alt=''></div><div class='back face'><div>This is back</div></div></div></div>");
1532          self.changeImageHeightFor3dCubeEffect($el, cubeWidth, cubeHeight);
1533        }
1534      }
1535
1536      if ($el.data('grid-gallery-type') == 'polaroid') {
1537        self.polaroidCaptionCalculate($el);
1538      } else {
1539        var topRow = $el.find('.gg-caption-row.top'),
1540          centerRow = $el.find('.gg-caption-row.center');
1541        if (centerRow.length == 1 && topRow.length == 1) {
1542          centerRow.css({ top: topRow.height(), transform: 'initial' });
1543        }
1544      }
1545    });
1546
1547    $(document).on('click', '.sliphover-container', function (event) {
1548      event.preventDefault();
1549      $(this).data('relatedElement').get(0).click();
1550    });
1551
1552    if (isMobile && !disableCaptionOnMobile) {
1553      this.$container.find('.grid-gallery-caption').each(function () {
1554        var caption = this,
1555          $caption = $(caption),
1556          hammer = new Hammer_gg(this),
1557          captionIsMobile = self.$container.attr('data-caption-mobile'),
1558          preventClick = false;
1559
1560        $caption.on('click', function (event) {
1561          if (preventClick) {
1562            event.preventDefault();
1563            event.stopPropagation();
1564          }
1565        });
1566
1567        hammer.on('tap panstart', function (event) {
1568          if (event.type === 'panstart') {
1569            self.$container.find('.grid-gallery-caption').removeClass('hovered');
1570          }
1571
1572          if (event.type === 'tap') {
1573            preventClick = false;
1574            if (!$caption.hasClass('hovered')) {
1575              self.$container.find('.grid-gallery-caption').not(caption).removeClass('hovered');
1576              $(caption).addClass('hovered');
1577              if (captionIsMobile == 'false') {
1578                preventClick = true;
1579              }
1580            }
1581          }
1582        });
1583      });
1584    }
1585
1586    if (isMobile && disableCaptionOnMobile) {
1587      this.$container.find('.grid-gallery-caption figcaption').hide();
1588    }
1589  };
1590
1591  Gallery.prototype.polaroidCaptionCalculate = function ($el) {
1592    if ($el.data('grid-gallery-type') != 'polaroid' || $(this).find('.post-feed-crop').length || $el.hasClass('initialized')) return;
1593    var $img = $el.find('img');
1594
1595    if ($img.hasClass('ggLazyImg') || $img.hasClass('ggNotInitImg')) return;
1596    if ($el.closest('.gg-mw-row').hasClass('sggDisplNone')) return;
1597
1598    $el.addClass('initialized');
1599    $img.finish();
1600    var width = $el.width(),
1601      gridType = this.$container.data('gridType'),
1602      frameWidth = parseInt(this.$container.data('polaroid-frame-width'), 10) || 20,
1603      captionHeight = this.$container.data('polaroid-caption-height'),
1604      clearHeight = captionHeight ? parseInt(captionHeight.toString().match(/\d.?\d*.?\d*/)[0]) : 0,
1605      // When icons are enabled, the user's chosen caption background color
1606      // ends up on the sibling .caption-with-icons div (see helpers.twig's
1607      // figcaption_after block), not on <figcaption> itself, which is left
1608      // transparent in that case. Reading it off <figcaption> unconditionally
1609      // makes overlayColor resolve to transparent black, and
1610      // generateOverlayCaptionColor() below then stamps a fresh opaque-ish
1611      // alpha onto that black RGB, making the whole polaroid frame look
1612      // solid black regardless of the real configured color.
1613      $colorSource = $el.find('.caption-with-icons').length ? $el.find('.caption-with-icons') : $el.find('figcaption'),
1614      overlayColor = $colorSource.css('backgroundColor'),
1615      alpha = parseInt($colorSource.data('alpha')),
1616      $figcaption = $el.find('figcaption'),
1617      scaleRatio = $img.width() / $img.height();
1618
1619    // Neither color source has a real background in every combination of
1620    // settings (e.g. icons enabled, this photo has no caption text and
1621    // "Hide image title" is on, so .caption-with-icons never even renders) -
1622    // overlayColor then comes back fully transparent ("rgba(0, 0, 0, 0)"),
1623    // and generateOverlayCaptionColor() below only replaces the alpha
1624    // channel, so transparent black becomes solid-looking black instead of
1625    // falling through to any sensible color.
1626    if (/rgba?\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*,\s*0\s*\)/.test(overlayColor) || overlayColor === 'transparent') {
1627      overlayColor = '#ededed';
1628    }
1629
1630    if (gridType == 2) {
1631      var imageHeight = $img.height() - frameWidth * 2,
1632        imageWidth = imageHeight * scaleRatio;
1633    } else {
1634      var imageWidth = $img.width() - frameWidth * 2,
1635        imageHeight = imageWidth / scaleRatio;
1636    }
1637    var figcaptionHeight = !isNaN(clearHeight) && clearHeight != 0 ? (captionHeight.toString().indexOf('%') > 0 ? (imageHeight * clearHeight) / 100 : clearHeight) : 0,
1638      figureFullHeight = imageHeight + frameWidth * 2 + figcaptionHeight;
1639
1640    $img.css({
1641      width: imageWidth + 'px',
1642      height: imageHeight + 'px',
1643      margin: frameWidth + 'px auto 0',
1644    });
1645    $el.find('.gg-caption-table').css('height', '1px');
1646
1647    $el.find('.crop').css({
1648      height: imageHeight + frameWidth + 'px',
1649    });
1650    if (gridType == 0) {
1651      $el.find('.crop').css('overflow', 'visible');
1652    } else if (gridType == 2) {
1653      $el.css({
1654        height: figureFullHeight + 'px',
1655        width: imageWidth + frameWidth * 2 + 'px',
1656      });
1657    } else if (gridType == 3) {
1658      $el.css({
1659        height: figureFullHeight + 'px',
1660      });
1661    }
1662
1663    $el.css({
1664      background: overlayColor,
1665    });
1666    $el.css({
1667      width: $el.width(),
1668      background: this.generateOverlayCaptionColor(overlayColor, alpha),
1669    });
1670
1671    $figcaption.css({
1672      background: 'none',
1673      transition: 'none',
1674    });
1675    if (figcaptionHeight) {
1676      figcaptionHeight += 'px';
1677      $figcaption.css('height', figcaptionHeight);
1678      $el.find('.gg-caption-row').css({ 'max-height': figcaptionHeight ? figcaptionHeight : '100%', height: 'auto' });
1679      $el.find('.gg-caption-cell').css('height', '100%');
1680      if (gridType == 3) {
1681        $figcaption.css('margin-top', frameWidth + 'px');
1682      }
1683    } else {
1684      $figcaption.css('padding', frameWidth + 'px');
1685    }
1686
1687    if ($figcaption.find('.grid-gallery-figcaption-wrap').text().length === 0) {
1688      $figcaption.find('.grid-gallery-figcaption-wrap').append('<span></span>');
1689    }
1690
1691    // Icons sit on the photo itself for polaroid (see the [data-grid-gallery-
1692    // type='polaroid'] .hi-icon-wrap rules in grid-gallery.galleries.effects.css
1693    // for the hover-fade/centering) rather than in the always-visible caption
1694    // strip. Positioned against .grid-gallery-figcaption-wrap - its actual
1695    // CSS containing block (nearest position:relative ancestor - NOT
1696    // <figcaption>, which is one level further out) - measured via
1697    // getBoundingClientRect since that div collapses to 0 height once icons
1698    // are pulled out of flow here, so there's no reliable CSS-only anchor
1699    // (e.g. bottom:100%) to size/position against.
1700    var $iconWrap = $el.find('.hi-icon-wrap'),
1701      $iconWrapParent = $el.find('.grid-gallery-figcaption-wrap');
1702    if ($iconWrap.length && $iconWrapParent.length) {
1703      var imgRect = $img[0].getBoundingClientRect(),
1704        parentRect = $iconWrapParent[0].getBoundingClientRect();
1705      $iconWrap.css({
1706        top: imgRect.top - parentRect.top + 'px',
1707        height: imgRect.height + 'px',
1708      });
1709    }
1710
1711    // .caption-with-icons (the fallback title/caption text shown alongside
1712    // icons - see helpers.twig's figcaption_after block) has a hardcoded
1713    // height:35% (of the whole figure) in grid-gallery.galleries.frontend.css,
1714    // !important. For every other effect type figcaption IS the whole
1715    // figure, so that's a reasonable caption-strip proportion - but for
1716    // polaroid the figure is photo + a separate, much shorter figcaption
1717    // strip below it, so 35% of the *combined* height overshoots the real
1718    // strip and rides up onto the photo. First cut just matched
1719    // <figcaption>'s own height, but that's a fixed number unrelated to
1720    // this text's actual padding+line-height - too short for its own
1721    // content overflowed past the box (with overflow:visible) instead of
1722    // sliding fully into view. height:auto - fit to content - and read its
1723    // OWN resulting natural height back for the hidden-state offset instead.
1724    var $captionWithIcons = $el.find('.caption-with-icons');
1725    if ($captionWithIcons.length) {
1726      $captionWithIcons[0].style.setProperty('height', 'auto', 'important');
1727      var chHeight = $captionWithIcons.outerHeight(),
1728        chAlwaysShow = this.$container.data('polaroid-always-show-caption') == true;
1729      if (chAlwaysShow) {
1730        // Pinned resting position should sit centered on the actual
1731        // <figcaption> strip, not flush against the whole figure's bottom
1732        // edge (bottom:0) - the two only coincide when this box's own
1733        // (content-fit) height happens to match the strip's, which isn't
1734        // guaranteed. Centering here uses top (not bottom), computed from
1735        // <figcaption>'s own real position, since .caption-with-icons'
1736        // containing block is the whole figure, not <figcaption> itself.
1737        var figcaptionRect = $figcaption[0].getBoundingClientRect(),
1738          figureRect = $el[0].getBoundingClientRect(),
1739          figcaptionCenterY = figcaptionRect.top + figcaptionRect.height / 2,
1740          cwiTop = figcaptionCenterY - chHeight / 2 - figureRect.top;
1741        $captionWithIcons[0].style.setProperty('top', cwiTop + 'px', 'important');
1742        $captionWithIcons[0].style.setProperty('bottom', 'auto', 'important');
1743      } else {
1744        // Hidden until hover: tucked exactly one (content-fit) height below
1745        // the figure, sliding up via the existing transform:translateY(-100%)
1746        // on hover (relative to this element's own height, so it still lands
1747        // correctly regardless of what that height actually is).
1748        $captionWithIcons[0].style.setProperty('bottom', -chHeight + 'px', 'important');
1749      }
1750    }
1751
1752    if (this.$container.data('polaroid-animation')) {
1753      $el.addClass('polaroid-animation');
1754    }
1755
1756    if (this.$container.data('polaroid-scattering')) {
1757      $el.css({
1758        transform: 'rotate(' + (-3 + Math.random() * (10 - 3)) + 'deg)',
1759      });
1760      $el.addClass('polaroid-scattering');
1761    }
1762    var slimScroll = $el.closest('div.slimScrollDiv');
1763    if (slimScroll.length) {
1764      var scrollHeight = figureFullHeight + 20 + 'px';
1765      slimScroll.css('height', scrollHeight);
1766      slimScroll.find('.grid-gallery-photos').css('height', scrollHeight);
1767    }
1768  };
1769
1770  Gallery.prototype.changeImageHeightFor3dCubeEffect = function ($figure, cubeWidth, cubeHeight) {
1771    // check params
1772    if (!$figure) {
1773      return;
1774    }
1775    // call this function from PRO script
1776    if (!$figure.length) {
1777      if ('figure' in $figure && 'width' in $figure && 'height' in $figure) {
1778        cubeWidth = $figure.width;
1779        cubeHeight = $figure.height;
1780        $figure = $figure.figure;
1781      } else {
1782        return;
1783      }
1784    }
1785
1786    if (!cubeWidth) {
1787      cubeWidth = $figure.width();
1788    }
1789    if (!cubeHeight) {
1790      cubeHeight = $figure.height();
1791    }
1792
1793    var perspective = Math.max(cubeHeight, cubeWidth) * 2 + 'px',
1794      transformOrigin = '50% 50% -' + Math.round(cubeHeight / 2) + 'px';
1795
1796    $figure.find('.box-3d-cube-scene').css({
1797      perspective: perspective,
1798      '-webkit-perspective': perspective,
1799    });
1800    $figure.find('.box-3d-cube').css({
1801      'transform-origin': transformOrigin,
1802      '-ms-transform-origin': transformOrigin,
1803      '-webkit-transform-origin': transformOrigin,
1804    });
1805    $figure.find('.box-3d-cube, .box-3d-cube .face').css({
1806      width: cubeWidth + 'px',
1807      height: cubeHeight + 'px',
1808    });
1809  };
1810
1811  Gallery.prototype.correctMargin = function () {
1812    if (this.$container.data('area-position') == 'right') {
1813      return;
1814    }
1815    if (this.$container.data('gridType') == 4) {
1816      return;
1817    }
1818    // if responsive mode = 'one by one' and mobile -> run this method
1819    var horizontalScroll = this.$container.data('horizontal-scroll'),
1820      isMobile = parseInt($anyGallery.attr('data-is-mobile'));
1821    if (horizontalScroll && horizontalScroll.responsiveMode == 1 && isMobile) {
1822    } else {
1823      return;
1824    }
1825    if (!this.isFluidHeight()) {
1826      if (this.$qsEnable) {
1827        this.$elements = this.$container.find('figure.grid-gallery-caption');
1828      }
1829
1830      var prevElement = null,
1831        totalElements = this.$elements.filter(':visible').length,
1832        rowWidth = 0,
1833        maxRowWidth = this.$container.width(),
1834        initialMargin = this.initialMargin;
1835
1836      this.$elements.css('margin', this.initialMargin);
1837      this.$elements.parent().css('clear', 'none');
1838
1839      this.$elements.filter(':visible').each(function (index) {
1840        if (rowWidth + $(this).outerWidth() > maxRowWidth) {
1841          $(prevElement).css('margin-right', 0);
1842          $(this).css('margin-right', this.initialMargin);
1843          $(this).parent().css('clear', 'left');
1844          rowWidth = $(this).outerWidth() + parseInt(initialMargin);
1845        } else if (rowWidth + $(this).outerWidth() == maxRowWidth) {
1846          $(this).css('margin-right', 0);
1847          rowWidth = 0;
1848        } else {
1849          rowWidth += $(this).outerWidth() + parseInt(initialMargin);
1850        }
1851
1852        if (index == totalElements - 1) {
1853          $(this).css('margin-right', 0);
1854        }
1855
1856        prevElement = this;
1857      });
1858    }
1859  };
1860
1861  Gallery.prototype.hideTitleTooltip = function () {
1862    if (this.$container.data('hide-tooltip') == true) {
1863      title = '';
1864      this.$container
1865        .find('a, img, div:not(.grid-gallery-photos)')
1866        .on('mouseenter', function () {
1867          title = $(this).attr('title');
1868          $(this).attr({ title: ' ' });
1869        })
1870        .mouseout(function () {
1871          $(this).attr({ title: title });
1872        });
1873    }
1874  };
1875
1876  Gallery.prototype.correctFullscreen = function () {
1877    var windowWidth = $(window).width();
1878    this.$elements.each(function () {
1879      var coef = parseInt(windowWidth / $(this).width()),
1880        resultWidth = Math.round(windowWidth / coef);
1881      $(this).width(resultWidth);
1882    });
1883  };
1884
1885  Gallery.prototype.correctFullScreenWidthGallery = function () {
1886    var windowWidth = $(window).width(),
1887      $parentContainer = this.$container.parent(),
1888      containerOffset = $parentContainer.offset(),
1889      containerOffsetLeft = containerOffset.left + parseFloat($parentContainer.css('padding-left'));
1890
1891    this.$container.find('.grid-gallery-photos').css({
1892      width: windowWidth,
1893    });
1894
1895    var cssDirection = this.$container.css('direction');
1896
1897    if ('ltr' == cssDirection) {
1898      this.$container.css({
1899        width: windowWidth,
1900        left: '-' + containerOffsetLeft + 'px',
1901        //'max-width': '100%'
1902      });
1903      this.$container.find('.grid-gallery-nav').css('width', windowWidth + 'px');
1904    } else {
1905      this.$container
1906        .css({
1907          width: windowWidth, //, 'max-width': '100%'
1908        })
1909        .offset(function (i, coords) {
1910          return { top: coords.top, left: 0 };
1911        });
1912    }
1913  };
1914
1915  Gallery.prototype.getOriginalImageSizes = function (img) {
1916    var tempImage = new Image(),
1917      width,
1918      height,
1919      $img = img ? $(img) : $(),
1920      attrWidth = parseFloat($img.attr('data-gg-original-width') || $img.attr('width')),
1921      attrHeight = parseFloat($img.attr('data-gg-original-height') || $img.attr('height'));
1922
1923    if ('naturalWidth' in tempImage && 'naturalHeight' in tempImage) {
1924      width = img ? img.naturalWidth : 0;
1925      height = img ? img.naturalHeight : 0;
1926    } else if (img) {
1927      tempImage.src = img.src;
1928      width = tempImage.width;
1929      height = tempImage.height;
1930    }
1931
1932    if ((!width || isNaN(width)) && attrWidth > 0) {
1933      width = attrWidth;
1934    }
1935
1936    if ((!height || isNaN(height)) && attrHeight > 0) {
1937      height = attrHeight;
1938    }
1939
1940    return {
1941      width: width,
1942      height: height,
1943    };
1944  };
1945
1946  Gallery.prototype.initHorizontalMode = function () {
1947    var horizontalScroll = this.$container.data('horizontal-scroll'),
1948      height = this.$container.data('height'),
1949      width = this.$container.data('width'),
1950      offset = this.$container.data('offset'),
1951      isMobile = parseInt($anyGallery.attr('data-is-mobile')),
1952      mouseWheelStep = 100,
1953      touchStep = 100,
1954      responsiveMode = 0,
1955      tmpValue = 0,
1956      self = this;
1957
1958    if (this.$container.data('gridType') == 4) {
1959      return;
1960    }
1961    if (!horizontalScroll) {
1962      return;
1963    }
1964    if (horizontalScroll) {
1965      // if responsive mode = 'one by one' and mobile -> need to disable "responsive mode"
1966      if (horizontalScroll.responsiveMode == 1 && isMobile) {
1967        return;
1968      }
1969      if (horizontalScroll.mouseWheelStep) {
1970        tmpValue = parseInt(horizontalScroll.mouseWheelStep);
1971        if (!isNaN(tmpValue)) {
1972          mouseWheelStep = tmpValue;
1973        }
1974      }
1975      if (horizontalScroll.touchStep) {
1976        tmpValue = parseInt(horizontalScroll.touchStep);
1977        if (!isNaN(tmpValue)) {
1978          touchStep = tmpValue;
1979        }
1980      }
1981    }
1982
1983    //Calculate max-height and margin
1984    if (!height) {
1985      var elementsHeight = this.$container
1986          .find('.grid-gallery-caption>a')
1987          .map(function () {
1988            return $(this).height();
1989          })
1990          .get(),
1991        height = Math.max.apply(null, elementsHeight);
1992    } else {
1993      if (offset && offset > 0) {
1994        height = height + offset * 2;
1995      }
1996    }
1997
1998    if (width === 'auto') {
1999      this.$elements.each(function (index, el) {
2000        var $figure = $(el),
2001          $image = $figure.find('img');
2002        sizes = self.getOriginalImageSizes($image.get(0));
2003        $image.css('max-width', 'none');
2004        if (!$image.hasClass('ggLazyImg')) $figure.width(Math.floor((height / sizes.height) * sizes.width));
2005      });
2006    }
2007
2008    //Fixed IE9 scroll bug
2009    var isIE9OrBelow = function () {
2010      return /MSIE\s/.test(navigator.userAgent) && parseFloat(navigator.appVersion.split('MSIE')[1]) < 10;
2011    };
2012
2013    if (isIE9OrBelow()) {
2014      this.$container.find('.grid-gallery-photos > *').css('display', 'table-cell');
2015    } else {
2016      this.$container.find('.grid-gallery-photos > *').css('display', 'inline-block');
2017    }
2018
2019    this.$container.find('.grid-gallery-photos > *').css({
2020      margin: 0,
2021      padding: 0,
2022      float: 'none',
2023      animate: true,
2024      'vertical-align': 'middle',
2025      clear: 'right',
2026      //'margin-right': '-5px',
2027      border: 'none',
2028      'max-width': 'none',
2029    });
2030
2031    this.$container.find('.grid-gallery-photos').css({
2032      'font-size': 0,
2033    });
2034
2035    this.$container.find('.grid-gallery-photos .grid-gallery-caption').css({
2036      float: 'none',
2037      'margin-left': 0,
2038    });
2039
2040    // https://github.com/lanre-ade/jQuery-slimScroll
2041    height = height + 7; //This is scrollbar height;
2042    var slimScroll = this.$container.find('.grid-gallery-photos').slimScroll({
2043      height: height,
2044      width: 'auto',
2045      railVisible: true,
2046      alwaysVisible: true,
2047      allowPageScroll: true,
2048      axis: 'x',
2049      animate: true,
2050      color: horizontalScroll.color || '#000',
2051      opacity: (100 - horizontalScroll.transparency) * 0.01,
2052      wheelStep: mouseWheelStep,
2053      touchScrollStep: touchStep,
2054      isMobile: isMobile,
2055      ggSlimscrollHandler: function () {
2056        self.lazyLoadTriggerHandler();
2057      },
2058    });
2059
2060    // Load more height fix
2061    if (slimScroll.height() < height) {
2062      slimScroll.height(height);
2063      slimScroll.parent().height(height);
2064    }
2065  };
2066
2067  Gallery.prototype.initHorizontalGalleryType = function () {
2068    if (this.$container.data('height') && String(this.$container.data('height')).indexOf('%') > -1) {
2069      var height = this.$elements.first().height();
2070      this.$elements.find('img').css({
2071        'max-height': height,
2072        'min-height': height,
2073      });
2074    }
2075    var self = this;
2076    setTimeout(function () {
2077      self.resizeHorizontalElements();
2078    }, 50);
2079  };
2080
2081  Gallery.prototype.hidePreloader = function () {
2082    var preloadEnab = this.$container.attr('data-preloader'),
2083      preloader = this.$container.find('.gallery-loading'),
2084      galleryPhotos = this.$container.find('.grid-gallery-photos');
2085
2086    preloader.hide();
2087    if (preloadEnab !== '' && preloadEnab === 'true') {
2088      setTimeout(function () {
2089        galleryPhotos.show().fadeTo('slow', 1, function () {
2090          galleryPhotos.css('opacity', '1');
2091        });
2092      }, 0);
2093    } else {
2094      galleryPhotos.show().fadeTo('fast', 1, function () {
2095        galleryPhotos.css('opacity', '1');
2096      });
2097    }
2098  };
2099
2100  Gallery.prototype.showGalleryParts = function () {
2101    this.$container.children('.hidden-item').removeClass('hidden-item');
2102  };
2103
2104  Gallery.prototype.$getImagesFigureContainer = function () {
2105    return this.$container.find('figure.grid-gallery-caption');
2106  };
2107
2108  Gallery.prototype.initSocialSharing = function () {
2109    if (!this.socialSharing || !this.socialSharing.enabled) {
2110      return;
2111    }
2112    var newUrl = encodeURIComponent(window.location.href);
2113    var newTitle = encodeURIComponent(document.title);
2114    jQuery('.supSocialIcon').each(function () {
2115      var $this = $(this);
2116      var origUrl = $this.attr('originalurl');
2117      var newUrl2 = origUrl.replace('{url}', newUrl);
2118      newUrl2 = newUrl2.replace('{title}', newTitle);
2119      newUrl2 = newUrl2.replace('{description}', newTitle);
2120      $this.attr('href', newUrl2);
2121    });
2122    this.initGallerySocialSharing();
2123    this.initImageSocialSharing();
2124  };
2125  Gallery.prototype.initGallerySocialSharing = function () {
2126    var gallerySharing = this.socialSharing.gallerySharing;
2127    if (!parseInt(gallerySharing.enabled)) {
2128      return;
2129    }
2130    if (gallerySharing.position == 'top' || gallerySharing.position == 'all') {
2131      this.$container.find('.gallery-sharing-top').fadeIn();
2132    }
2133    if (gallerySharing.position == 'bottom' || gallerySharing.position == 'all') {
2134      this.$container.find('.gallery-sharing-bottom').fadeIn();
2135    }
2136  };
2137  Gallery.prototype.initImageSocialSharing = function () {
2138    var imageSharing = this.socialSharing.imageSharing;
2139    if (!parseInt(imageSharing.enabled)) {
2140      return;
2141    }
2142    var btns = this.$container.find('.gallery-sharing-image').clone();
2143
2144    var $images = this.$getImagesFigureContainer(),
2145      iconsEnabled = this.$container.data('icons');
2146    $images.each(function () {
2147      var $this = $(this),
2148        $el;
2149      var imgLink = jQuery($this).parent().attr('href');
2150      btns.find('.supSocialIcon').each(function () {
2151        var $thisBtn = $(this);
2152        if ($thisBtn.hasClass('supSocialIconprint')) {
2153          $thisBtn.attr('onClick', 'supSocialSharePrintImage("' + imgLink + '")');
2154        }
2155      });
2156
2157      if (!iconsEnabled) {
2158        $el = $this.parent();
2159      } else {
2160        $el = $this.find('a.hi-icon');
2161      }
2162      $this.append(btns.html());
2163    });
2164  };
2165  Gallery.prototype.addSocialShareToPopUp = function ($element, $wrapper, addClass, fixed) {
2166    if (!this.socialSharing.enabled || !parseInt(this.socialSharing.popupSharing.enabled)) {
2167      return;
2168    }
2169    var btns = this.$container.find('.gallery-sharing-popup').clone();
2170    var newUrl = encodeURIComponent($element.get(0).baseURI);
2171    var imgLink = $element.get(0).href;
2172    var newTitle = jQuery($element.get(0)).attr('title');
2173    btns.find('.supSocialIcon').each(function () {
2174      var $this = $(this);
2175      if ($this.hasClass('supSocialIconprint')) {
2176        $this.attr('onClick', 'supSocialSharePrintImage("' + imgLink + '")');
2177      }
2178      $this.attr('title', newTitle);
2179      var origUrl = $this.attr('originalurl');
2180      var newUrl2 = origUrl.replace('{url}', newUrl);
2181      newUrl2 = newUrl2.replace('{title}', newTitle);
2182      newUrl2 = newUrl2.replace('{description}', newTitle);
2183      $this.attr('href', newUrl2);
2184    });
2185    $wrapper.find('.supSocialIconsWrapper').remove();
2186    $wrapper.append(btns.html());
2187  };
2188
2189  // Gallery.prototype.initEvent = function($elements){
2190  //     $elements.find('.supsystic-social-sharing a.social-sharing-button').on('click',function (e) {
2191  // if( !e ) e = window.event;
2192  // e.preventDefault();
2193  // e.stopPropagation();
2194  // e.stopImmediatePropagation();
2195  // $(document).trigger('ssSocialClick', this);
2196  // if (e.currentTarget.href.slice(-1) !== '#') {
2197  //     window.open(e.currentTarget.href, 'mw' + e.timeStamp, 'left=20,top=20,width=500,height=500,toolbar=1,resizable=0');
2198  // }
2199
2200  // var button = $(this)
2201  // ,   figureWrapper = button.closest('.grid-gallery')
2202  // ,   socialHtmlWrapper = figureWrapper.find('#social-share-html')
2203  // // ,   socialHtmlWrapper = figureWrapper.find('.supsystic-social-sharing')
2204  // ,   popupWrapper = socialHtmlWrapper.find('.supsystic-social-sharing-popup');
2205
2206  // if(button.hasClass('trigger-popup')){
2207  // 	if(socialHtmlWrapper.css('display') === 'none'){
2208  //         socialHtmlWrapper.find('a').css('display', 'none');
2209  //         socialHtmlWrapper.css('display','block');
2210  //         popupWrapper.css('display','block');
2211  //     }else{
2212  //         socialHtmlWrapper.css('display','none');
2213  //         popupWrapper.css('display','none');
2214  //     }
2215  // }
2216  // if(button.closest('#pp_full_res').length){
2217  //     var buttonOverlayWrapper = button.closest('#pp_full_res')
2218  //     ,   buttonPopupWrapper = buttonOverlayWrapper.find('.supsystic-social-sharing-popup');
2219  //     if(buttonPopupWrapper.css('display') === 'none'){
2220  //         buttonPopupWrapper.css('display','block');
2221  //     }else{
2222  //         buttonPopupWrapper.css('display','none');
2223  //     }
2224  // }
2225  // $(document).on('click', function (e) {
2226  //     if( !e ) e = window.event;
2227  //     if (!$(e.target).is(".supsystic-social-sharing-popup")) {
2228  //         socialHtmlWrapper.css('display','none');
2229  //         popupWrapper.css('display','none');
2230  //         socialHtmlWrapper.find('a').css('display', 'block');
2231  //     }
2232  // });
2233  //     });
2234  // };
2235
2236  // Gallery.prototype.getSocialButtons = function(wrapper_class, url, img_id, img_src, title, noCounter) {
2237  //     title = title || '';
2238
2239  // 	var html = this.$container.find('#social-share-html').html();
2240
2241  //     if (html !== undefined && html.length){
2242  //         html = html.replace(/{url}/g, url).replace(/{title}/g, title);
2243  //         if(noCounter) {
2244  //             // cut counter div
2245  //             html = html.replace(/<div class="counter-wrap.*?>.*?<\/div>/g, '');
2246  //         }
2247  //     }
2248
2249  //     return $('<div>', {
2250  //         class: wrapper_class,
2251  //         'data-img-thumbnail': img_src,
2252  //         'data-img-id': img_id,
2253  //         'data-img-title': title,
2254  //     }).html(html);
2255  // };
2256
2257  // Gallery.prototype.getSocialButtonsByImage = function(wrapper_class, $element, popup) {
2258
2259  //     var $img = $element.find('img'),
2260  //         imgSrc = $element.attr('href'),
2261  //         title = $element.attr('title'),
2262  //         $captionContainer = $element.find('.gg-image-caption'),
2263  //         url = location.href,
2264  // 		imageId = null;
2265
2266  // 	if($element.attr('data-type') == 'link' || $element.attr('data-video-source') == 'youtube') {
2267  // 		if($img.length) {
2268  // 			if($img.attr('data-gg-real-image-href')) {
2269  // 				imgSrc = $img.attr('data-gg-real-image-href');
2270  // 			} else {
2271  // 				imgSrc = $img.attr('src');
2272  // 			}
2273  // 		}
2274  // 	}
2275
2276  // 	if($element && $element.attr('id') && $element.attr('id').split('-').pop()) {
2277  // 		imageId = $element.attr('id').split('-').pop();
2278  // 	}
2279
2280  //     if ($captionContainer.length) {
2281  //         var caption = $.trim(
2282  //             $captionContainer.clone().html($captionContainer.html()
2283  //                 .replace(/<br\s*[\/]?>/gi, ' '))
2284  //                 .text()
2285  //                 .replace(/\s+/, ' ')
2286  //         );
2287
2288  //         if (caption.length) {
2289  //             title = caption;
2290  //         }
2291  //     }
2292
2293  //     if (imgSrc && imgSrc.indexOf('http') !== 0) {
2294  //         imgSrc = 'http:' + imgSrc;
2295  //     }
2296
2297  //     function updateQueryStringParameter(uri, key, value) {
2298  //         var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
2299  //         var separator = uri.indexOf('?') !== -1 ? "&" : "?";
2300  //         if (uri.match(re)) {
2301  //             return uri.replace(re, '$1' + key + "=" + value + '$2');
2302  //         } else {
2303  //             return uri + separator + key + "=" + value;
2304  //         }
2305  //     }
2306
2307  //     if (popup) {
2308  //         url = url.replace('#!', '?');
2309  //     }
2310  // 	if(imageId) {
2311  // 		url = updateQueryStringParameter(url, '_gallery', $element.attr('id'));
2312  // 		url = encodeURIComponent(updateQueryStringParameter(url, 'shared-image', imageId));
2313  // 	}
2314
2315  //     return this.getSocialButtons(wrapper_class, url, $element.attr('id'), imgSrc, title, true);
2316  // };
2317
2318  // Gallery.prototype.correctImageSocialButtons = function($imageSharing){
2319
2320  // if(!$imageSharing.length){
2321  //     return;
2322  // }
2323  // var $example = $imageSharing.eq(0),
2324  //     correctCss = {};
2325
2326  // if($example.hasClass('vertical')){
2327  //     var buttonWidth = $example.find('.social-sharing-button').eq(0).outerWidth();
2328  //     correctCss.width = buttonWidth;
2329  //     $example.width(buttonWidth);
2330  // }
2331
2332  // var width = $example.width();
2333  // var height = $example.height();
2334
2335  // if($example.hasClass('center')){
2336  //     $.extend(correctCss,{'margin-left': '-' + (width/2) + 'px'})
2337  // }
2338  // if($example.hasClass('middle')){
2339  //     $.extend(correctCss,{'margin-top': '-' + (height/2) + 'px'})
2340  // }
2341
2342  // $imageSharing.find('.social-sharing-button.print').on('click',function(){
2343  //     var image_url = $(this).closest('.supsystic-grid-gallery-image-sharing').data('img-url');
2344  //     window.open(image_url).print();
2345  // });
2346
2347  // $imageSharing.find('.social-sharing-button.mail').on('click',function(){
2348  //     var $infoElement = $(this).closest('.supsystic-grid-gallery-image-sharing'),
2349  //         image_id = $infoElement.data('img-id'),
2350  //         image_title = $infoElement.data('img-title');
2351  //     var url = window.location.href.replace(window.location.hash,'') + '#' + image_id + '/';
2352
2353  //     var src = 'mailto:[email protected]?subject=' + encodeURIComponent(document.title) + ',' + image_title + '&body=' + url;
2354  //     var iframe = $('<iframe id="mailtoFrame" src="' + src + '" width="1" height="1" border="0" frameborder="0"></iframe>');
2355
2356  //     $('body').append(iframe);
2357  //     window.setTimeout(function(){
2358  //         iframe.remove();
2359  //     }, 500);
2360  // });
2361
2362  // var self = this;
2363  // $imageSharing.each(function(){
2364
2365  //     $(this).css(correctCss);
2366
2367  //     var thumbnail = $(this).data('img-thumbnail');
2368
2369  //     if (thumbnail) {
2370
2371  //         for(var sharingClass in self.socialSharingImageOperators){
2372  //             var $button = $(this).find('.social-sharing-button.'+sharingClass);
2373  //             if($button.length){
2374  //                 var img_url = $(this).data('img-url'),
2375  //                     img_id = $(this).data('img-id'),
2376  // 					shareUrlObj = self.urlToObject($button.attr('href')),
2377  // 					newHref = '';
2378
2379  // 				// set gallery image for share link
2380  // 				shareUrlObj.params[self.socialSharingImageOperators[sharingClass]] = thumbnail;
2381  // 				newHref = self.objectToUrl(shareUrlObj);
2382
2383  // 				if(img_url) {
2384  // 					newHref = newHref.replace(
2385  // 						img_url,
2386  // 						self.addPopUpHashToUrl(self.socialButtonsUrl, img_id)
2387  // 					);
2388  // 				}
2389
2390  // 				$button.attr('href', newHref);
2391  //             }
2392  //         }
2393  //     }
2394  // });
2395
2396  // };
2397
2398  Gallery.prototype.urlToObject = function (strUrl) {
2399    if (!strUrl) {
2400      return null;
2401    }
2402    var posQ = strUrl.indexOf('?');
2403    if (posQ == -1) {
2404      return null;
2405    }
2406    var strQueryParams = strUrl.substr(posQ + 1),
2407      result = {
2408        url: strUrl.substr(0, posQ),
2409        params: {},
2410      };
2411    strQueryParams.split('&').forEach(function (part) {
2412      var item = part.split('=');
2413      if (item.length >= 2) {
2414        result.params[item[0]] = decodeURIComponent(item[1]);
2415      }
2416    });
2417    return result;
2418  };
2419
2420  Gallery.prototype.objectToUrl = function (specObj) {
2421    if (!specObj) {
2422      return null;
2423    }
2424
2425    var resUrl = '';
2426    if (specObj.url) {
2427      resUrl = specObj.url;
2428    }
2429    if (specObj.params) {
2430      var paramParts = [],
2431        paramKeys = Object.keys(specObj.params),
2432        indX = 0;
2433      for (indX = 0; indX < paramKeys.length; indX++) {
2434        paramParts.push(encodeURIComponent(paramKeys[indX]) + '=' + encodeURIComponent(specObj.params[paramKeys[indX]]));
2435      }
2436      resUrl = resUrl + '?' + paramParts.join('&');
2437    }
2438    return resUrl;
2439  };
2440
2441  Gallery.prototype.removePopUpHashFromUrl = function (url) {
2442    var match = url.match(/gg-\d+-\d+/);
2443    return url.replace(url[url.indexOf(match) - 1] + match, '');
2444  };
2445
2446  Gallery.prototype.addPopUpHashToUrl = function (url, hash) {
2447    if (!hash || !hash.length) {
2448      return url;
2449    }
2450    var prefix = '?';
2451    if (url.indexOf(prefix) != -1) prefix = '&';
2452    return url + prefix + hash;
2453  };
2454
2455  Gallery.prototype.openHashPopUp = function () {
2456    var getElementId = function () {
2457      var search = window.location.search;
2458      if (search.match(/gg-\d+-\d+/)) {
2459        return search.match(/gg-\d+-\d+/);
2460      }
2461
2462      var hash = window.location.hash;
2463      if (hash.match(/gg-\d+-\d+/)) {
2464        return hash.match(/gg-\d+-\d+/);
2465      }
2466    };
2467
2468    var elementId = getElementId(),
2469      $element = this.$container.find('#' + elementId + ', [data-id="' + elementId + '"]').first();
2470
2471    if ($element.length) {
2472      $element.click();
2473      var $figure;
2474
2475      if ($element.hasClass('hi-icon')) {
2476        $figure = $element.closest('figure.grid-gallery-caption');
2477      } else {
2478        $figure = $element.children('figure');
2479      }
2480
2481      if ($figure.length) {
2482        $('html, body').animate(
2483          {
2484            scrollTop: $figure.offset().top,
2485          },
2486          100
2487        );
2488      }
2489    }
2490  };
2491
2492  Gallery.prototype.updateQueryParams = function (url, params) {
2493    for (var param in params) {
2494      var re = new RegExp('[\\?&]' + param + '=([^&#]*)'),
2495        match = re.exec(url),
2496        delimiter,
2497        value = params[param];
2498
2499      if (match === null) {
2500        var hasQuestionMark = /\?/.test(url);
2501        delimiter = hasQuestionMark ? '&' : '?';
2502
2503        if (value) {
2504          url = url + delimiter + param + '=' + value;
2505        }
2506      } else {
2507        delimiter = match[0].charAt(0);
2508
2509        if (value) {
2510          url = url.replace(re, delimiter + param + '=' + value);
2511        } else {
2512          url = url.replace(re, '');
2513          if (delimiter === '?' && url.length) {
2514            url = '?' + url.substr(1);
2515          }
2516        }
2517      }
2518    }
2519
2520    return url;
2521  };
2522
2523  Gallery.prototype.changePopUpHash = function (hash) {
2524    var galleryId = this.$container.attr('data-gg-id'),
2525      galleryOpenPopupHashRegex = new RegExp('gg-' + galleryId + '(?:-(\\d+))*'),
2526      regexFoundGalleryImageId = galleryOpenPopupHashRegex.exec(hash),
2527      changedUrlDisabled = this.$container.attr('data-popup-disable-changed-url');
2528
2529    if (changedUrlDisabled !== 'true') {
2530      // if image id not exits
2531      if (!regexFoundGalleryImageId || regexFoundGalleryImageId.length < 2 || !regexFoundGalleryImageId[1]) {
2532        return;
2533      }
2534      this.popupIsOpened = true;
2535
2536      if (this.ignoreStateChange) {
2537        this.ignoreStateChange = false;
2538        return;
2539      }
2540      var queryParams = this.updateQueryParams(window.location.search, { _gallery: hash }),
2541        stateUrl = window.location.pathname + queryParams;
2542
2543      this.historyStateChange = true;
2544
2545      if (!this.popupIsInit) {
2546        if (queryParams === document.location.search) {
2547          History.replaceState(
2548            {
2549              type: 'sc-gallery',
2550              hash: hash,
2551              state: 'close',
2552            },
2553            document.title,
2554            window.location.pathname + this.updateQueryParams(window.location.search, { _gallery: null })
2555          );
2556
2557          History.pushState(
2558            {
2559              type: 'sc-gallery',
2560              hash: hash,
2561              state: 'init',
2562            },
2563            document.title,
2564            stateUrl
2565          );
2566        } else {
2567          History.replaceState(
2568            {
2569              type: 'sc-gallery',
2570              hash: hash,
2571              state: 'init',
2572            },
2573            document.title,
2574            stateUrl
2575          );
2576        }
2577
2578        this.popupIsInit = true;
2579      } else {
2580        if (this.disablePopupHistory) {
2581          History.replaceState(
2582            {
2583              type: 'sc-gallery',
2584              hash: hash,
2585              state: 'change',
2586            },
2587            document.title,
2588            stateUrl
2589          );
2590        } else {
2591          History.pushState(
2592            {
2593              type: 'sc-gallery',
2594              hash: hash,
2595              state: 'change',
2596            },
2597            document.title,
2598            stateUrl
2599          );
2600        }
2601      }
2602
2603      this.historyStateChange = false;
2604    }
2605  };
2606
2607  Gallery.prototype.clearPopUpHash = function () {
2608    this.historyStateChange = true;
2609
2610    if (this.disablePopupHistory) {
2611      History.replaceState(
2612        {
2613          type: 'sc-gallery',
2614          hash: '',
2615          state: 'close',
2616        },
2617        document.title,
2618        window.location.pathname + this.updateQueryParams(window.location.search, { _gallery: null })
2619      );
2620    } else {
2621      History.pushState(
2622        {
2623          type: 'sc-gallery',
2624          hash: '',
2625          state: 'close',
2626        },
2627        document.title,
2628        window.location.pathname + this.updateQueryParams(window.location.search, { _gallery: null })
2629      );
2630    }
2631
2632    this.historyStateChange = false;
2633    this.popupIsOpened = false;
2634  };
2635
2636  Gallery.prototype.getRealImgSizeInBrowser = function (arguments) {
2637    if (!arguments && !arguments.length) {
2638      return null;
2639    }
2640    if (arguments.length > 1) {
2641      returnType = arguments[1];
2642    }
2643    if (arguments.length) {
2644      $image = arguments[0];
2645    }
2646
2647    var returnData = null,
2648      boundRect = null,
2649      attrWidth = $image && $image.length ? parseFloat($image.attr('data-gg-original-width') || $image.attr('width')) : null,
2650      attrHeight = $image && $image.length ? parseFloat($image.attr('data-gg-original-height') || $image.attr('height')) : null,
2651      cssWidth = null,
2652      cssHeight = null;
2653    if ($image && $image.length && $image[0].getBoundingClientRect) {
2654      boundRect = $image[0].getBoundingClientRect();
2655    }
2656
2657    if (returnType == 'h') {
2658      if (boundRect && boundRect.height) {
2659        returnData = boundRect.height;
2660      } else {
2661        returnData = parseFloat($image.css('height'));
2662      }
2663      if ((!returnData || isNaN(returnData)) && attrWidth > 0 && attrHeight > 0) {
2664        cssWidth = boundRect && boundRect.width ? boundRect.width : parseFloat($image.css('width'));
2665        if ((!cssWidth || isNaN(cssWidth)) && $image.parent().length) {
2666          cssWidth = parseFloat($image.parent().css('width'));
2667        }
2668        if (cssWidth > 0) {
2669          returnData = (cssWidth * attrHeight) / attrWidth;
2670        }
2671      }
2672    } else if (returnType == 'w') {
2673      if (boundRect && boundRect.width) {
2674        returnData = boundRect.width;
2675      } else {
2676        returnData = parseFloat($image.css('width'));
2677      }
2678      if ((!returnData || isNaN(returnData)) && attrWidth > 0 && attrHeight > 0) {
2679        cssHeight = boundRect && boundRect.height ? boundRect.height : parseFloat($image.css('height'));
2680        if ((!cssHeight || isNaN(cssHeight)) && $image.parent().length) {
2681          cssHeight = parseFloat($image.parent().css('height'));
2682        }
2683        if (cssHeight > 0) {
2684          returnData = (cssHeight * attrWidth) / attrHeight;
2685        }
2686      }
2687    }
2688
2689    return returnData;
2690  };
2691
2692  Gallery.prototype.lazyLoadTriggerHandler = function () {
2693    $(window).trigger('scroll');
2694    $(document).trigger('scroll');
2695
2696    if (this.$container && this.$container.length) {
2697      this.$container.trigger('scroll');
2698      this.$container.find('.grid-gallery-photos, .slimScrollDiv').trigger('scroll');
2699    }
2700  };
2701
2702  Gallery.prototype.lazyLoadStableRefresh = function (waitTime) {
2703    var self = this,
2704      galleryType = this.$container.data('gridType'),
2705      baseDelay = parseInt(waitTime, 10);
2706
2707    if (isNaN(baseDelay) || baseDelay < 0) {
2708      baseDelay = 400;
2709    }
2710
2711    $.each([0, 120, baseDelay + 80, baseDelay + 450, 1600], function (index, delay) {
2712      setTimeout(function () {
2713        self.lazyLoadTriggerHandler();
2714
2715        if (galleryType == 4) {
2716          $(document).trigger('ggMosaicResizedEvent');
2717          $(window).trigger('resize');
2718        } else if (self.wookmark) {
2719          self.wookmark.trigger('refreshWookmark');
2720        }
2721      }, delay);
2722    });
2723  };
2724  Gallery.prototype.lazyLoadDistanceRefresh = function (waitTime) {
2725    var self = this,
2726      galleryType = this.$container.data('gridType');
2727
2728    if (typeof waitTime == 'undefined') {
2729      waitTime = 400;
2730    }
2731
2732    // need run function once at every load
2733    if (self.ggLazyTimeOut) {
2734      clearTimeout(self.ggLazyTimeOut);
2735    }
2736    self.ggLazyTimeOut = setTimeout(function () {
2737      setTimeout(function () {
2738        $.each(self.$elements, function (index, el) {
2739          var $el = $(el);
2740          if ($el.data('grid-gallery-type') == 'polaroid') {
2741            self.polaroidCaptionCalculate($el);
2742          }
2743        });
2744      }, waitTime + 50);
2745
2746      switch (galleryType) {
2747        case 4:
2748          $(document).trigger('ggMosaicResizedEvent');
2749          break;
2750        case 0:
2751          if (typeof self.setCaptionOnHoverImage == 'function') {
2752            self.setCaptionOnHoverImage();
2753          }
2754          // if hidden images  not showing
2755          setTimeout(function () {
2756            self.lazyLoadTriggerHandler();
2757            setTimeout(function () {
2758              if (self.wookmark) {
2759                self.wookmark.trigger('refreshWookmark');
2760              }
2761            }, 50);
2762          }, waitTime + 60); //450); // animation transition time
2763          break;
2764        case 1:
2765          if (typeof self.setCaptionOnHoverImage == 'function') {
2766            self.setCaptionOnHoverImage();
2767          }
2768          $.each(self.$elements, function (index, el) {
2769            var $el = $(el);
2770            if ($el.data('grid-gallery-type') == '3d-cube') {
2771              self.changeImageHeightFor3dCubeEffect($el, $el.width(), $el.find('img').length ? $el.find('img').height() : $el.height());
2772            }
2773          });
2774        case 2:
2775        case 3:
2776        default:
2777          //self.initWookmark();
2778          // if hidden images  not showing
2779          setTimeout(function () {
2780            self.lazyLoadTriggerHandler();
2781            self.initWookmark();
2782          }, waitTime + 50); //450); // animation transition time
2783          break;
2784      }
2785    }, 100);
2786  };
2787
2788  Gallery.prototype.initLazyLoad = function () {
2789    var self = this,
2790      hoverImgSrc = this.$container.data('image-on-hover');
2791    /*if(hoverImgSrc && hoverImgSrc.length) {
2792			// lazy load not work for image on hover
2793			return;
2794		}*/
2795    var showMoreCategory = this.$container.find('.showMoreCategory'),
2796      effect = this.$container.data('lazyload-effect'),
2797      duration = this.$container.data('lazyload-effect-duration'),
2798      $lazyImages = this.$container.find('.ggLazyImg');
2799
2800    if (!$lazyImages.length) {
2801      return;
2802    }
2803
2804    if (typeof effect == 'undefined') {
2805      effect = 'show';
2806      duration = 400;
2807    }
2808    var waitTime = effect == 'fadeIn' ? 200 : duration;
2809
2810    self.ggLazyTimeOut = null;
2811    $lazyImages.ggLazyLoad({
2812      data_attribute: 'gg-real-image-href',
2813      threshold: 50,
2814      failure_limit: $lazyImages.length,
2815      effect: effect,
2816      effectspeed: duration,
2817      skip_invisible: showMoreCategory.length > 0,
2818      load: function (event) {
2819        var image = $(this);
2820        self.lazyLoadDistanceRefresh(waitTime);
2821        if (self.$container.data('gridType') != 0) {
2822          image.closest('div .crop').css('height', '');
2823        }
2824        image.closest('figure').css('height', 'auto');
2825        if (self.$container.data('gridType') == 2 && self.$elements) {
2826          setTimeout(function () {
2827            self.resizeElementHeight(image, image.closest('figure'));
2828          }, waitTime + 20); //460); // animation transition time + 20ms
2829        }
2830      },
2831    });
2832
2833    self.lazyLoadStableRefresh(waitTime);
2834  };
2835
2836  Gallery.prototype.refreshLayoutAfterImageLoad = function () {
2837    var galleryType = this.$container.data('gridType');
2838
2839    if (!this.$container || !this.$container.length || !this.$container.is(':visible')) {
2840      return;
2841    }
2842
2843    this.setImagesHeight();
2844    this.resizeHorizontalElements();
2845
2846    if (galleryType == 4) {
2847      $(document).trigger('ggMosaicResizedEvent');
2848      $(window).trigger('resize');
2849    } else if (this.wookmark) {
2850      this.wookmark.trigger('refreshWookmark');
2851    } else {
2852      this.initWookmark();
2853    }
2854
2855    if (typeof this.setCaptionOnHoverImage == 'function') {
2856      this.setCaptionOnHoverImage();
2857    }
2858
2859    this.setIconsPosition();
2860    this.lazyLoadTriggerHandler();
2861  };
2862
2863  Gallery.prototype.initImageLoadLayoutRefresh = function () {
2864    var self = this,
2865      $images = this.$container.find('img.ggImg, figure.grid-gallery-caption img'),
2866      refreshTimer = null;
2867
2868    if (this.imageLoadLayoutRefreshInitialized || !$images.length) {
2869      return;
2870    }
2871
2872    this.imageLoadLayoutRefreshInitialized = true;
2873
2874    function hasPendingLayoutWork() {
2875      return (
2876        $images.filter(function () {
2877          return !this.complete || !this.naturalWidth || !this.naturalHeight;
2878        }).length > 0 ||
2879        self.$container.find('img.ggNotInitImg').length > 0 ||
2880        (self.$container.data('gridType') == 4 && self.$container.height() < 1)
2881      );
2882    }
2883
2884    function refresh() {
2885      clearTimeout(refreshTimer);
2886      refreshTimer = setTimeout(function () {
2887        self.refreshLayoutAfterImageLoad();
2888      }, 60);
2889    }
2890
2891    $images.off('.sggLayoutReady').one('load.sggLayoutReady error.sggLayoutReady', refresh);
2892
2893    $.each([0, 150, 400, 900, 1800, 3600, 6000], function (index, delay) {
2894      setTimeout(function () {
2895        if (hasPendingLayoutWork()) {
2896          refresh();
2897        }
2898      }, delay);
2899    });
2900  };
2901
2902  Gallery.prototype.init = function () {
2903    //this.$container.imagesLoaded().done($.proxy(function () {
2904    var self = this;
2905    this.setImagesHeight();
2906    var galleryBeforeInitId = 'GalleryBeforeInit' + this.galleryContainerId;
2907
2908    setTimeout(() => {
2909      $(document).trigger(galleryBeforeInitId, [this]);
2910    }, 10);
2911
2912    this.hidePreloader();
2913    this.showCaption();
2914    this.initRowsMode();
2915    this.initHorizontalGalleryType();
2916    this.initQuicksand();
2917
2918    if (this.$container.attr('data-fullscreen') == 'true') {
2919      this.correctFullScreenWidthGallery();
2920      $(window).resize(function () {
2921        self.correctFullScreenWidthGallery();
2922      });
2923    }
2924
2925    this.initHorizontalMode();
2926    this.setOverlayTransparency();
2927    this.initCaptionCalculations();
2928    this.initCaptionEffects();
2929    this.hideTitleTooltip();
2930    this.initPagination();
2931
2932    this.initPopup();
2933
2934    this.setMouseShadow();
2935    this.setImageOverlay();
2936
2937    this.loadFontFamily();
2938    this.hidePopupCaptions();
2939    this.preventImages();
2940    this.initWookmark();
2941    this.initCategories();
2942    this.setIconsPosition();
2943
2944    this.correctMargin();
2945    this.initControll();
2946    this.showGalleryParts();
2947    this.initLazyLoad();
2948    this.initImageLoadLayoutRefresh();
2949
2950    this.initSocialSharing();
2951
2952    // iOS Safari fix
2953    setTimeout(function () {
2954      if (self.wookmark) {
2955        self.wookmark.trigger('refreshWookmark');
2956      }
2957    }, 500);
2958
2959    setTimeout(function () {
2960      self.openHashPopUp();
2961    }, 500);
2962
2963    $(document).ready(function () {
2964      $(document).trigger('GalleryAfterInit', self);
2965    });
2966
2967    var galleryId = this.$container.attr('data-gg-id'),
2968      openByLinkRegexp = new RegExp('#gg-open-' + galleryId + '(\\-([\\d]+))*$');
2969
2970    History.Adapter.bind(window, 'statechange', function (event) {
2971      var state = History.getState();
2972
2973      // self.historyStateChange if true means manual update state and we need skip this event
2974      if (!self.historyStateChange) {
2975        if ((state.data.type !== 'sc-gallery' && self.popupIsOpened) || (state.data.type === 'sc-gallery' && (state.data.state === 'close' || state.data.state === 'hashchange') && self.popupIsOpened)) {
2976          if (self.popupType == 'pretty-photo') {
2977            this.$prettyPhoto && this.$prettyPhoto.close();
2978          }
2979
2980          if (self.popupType == 'colorbox') {
2981            $.colorbox && $.colorbox.close();
2982          }
2983
2984          if (self.popupType == 'photobox') {
2985            window._photobox && window._photobox.close();
2986          }
2987        }
2988
2989        // On history open image
2990        if (state.data.type === 'sc-gallery' && state.data.hash && state.data.state !== 'close') {
2991          self.ignoreStateChange = true;
2992
2993          var $el = self.$container.find('#' + state.data.hash + ', [data-id="' + state.data.hash + '"]').first();
2994
2995          if (self.popupIsOpened) {
2996            if (self.popupType == 'pretty-photo' && this.$prettyPhoto) {
2997              var href = $el.attr('href'),
2998                index = this.$prettyPhoto.getImagesList().indexOf(href);
2999              this.$prettyPhoto.changePage(index);
3000            }
3001
3002            if (self.popupType == 'colorbox') {
3003              $.colorbox.resizeResponsive($el);
3004            }
3005
3006            if (self.popupType == 'photobox') {
3007              var images = window._photobox.getImages(),
3008                href = $el.attr('href');
3009
3010              for (var i = 0; i < images.length; i++) {
3011                if (images[i][0] == href || images[i][0] == 'http:' + href || images[i][0] == 'https:' + href) {
3012                  window._photobox.changeImage(i);
3013                }
3014              }
3015            }
3016          } else {
3017            $el.trigger('click');
3018          }
3019        }
3020      }
3021    });
3022
3023    //check url and show popups
3024    //options "Open by link in popup"
3025    function checkUrl() {
3026      var hash = window.location.hash,
3027        matches = openByLinkRegexp.exec(hash);
3028
3029      if (matches) {
3030        History.replaceState(
3031          {
3032            type: 'sc-gallery',
3033            hash: '',
3034            state: 'hashchange',
3035          },
3036          document.title,
3037          window.location.pathname
3038        );
3039
3040        var position = matches[2] ? 'eq(' + (matches[2] - 1) + ')' : 'first';
3041        self.$container.find('.gg-link:' + position + ', .hi-icon:' + position).trigger('click');
3042      }
3043    }
3044
3045    $(window).on('hashchange', function (event) {
3046      checkUrl();
3047    });
3048
3049    $(document).ready(function () {
3050      checkUrl();
3051    });
3052
3053    //}, this));
3054
3055    $(window).on(
3056      'resize',
3057      $.proxy(function () {
3058        this.correctMargin();
3059        this.resizeHorizontalElements();
3060        this.initHorizontalMode();
3061      }, this)
3062    );
3063  };
3064
3065  Gallery.prototype.resizeHorizontalElements = function () {
3066    var self = this;
3067    if (this.$container.data('gridType') == 2 && this.$elements) {
3068      this.$elements.each(function () {
3069        var element = $(this),
3070          image = element.find('img');
3071        if (image) {
3072          self.resizeElementHeight(image, element);
3073        }
3074      });
3075    }
3076  };
3077
3078  Gallery.prototype.resizeElementHeight = function (image, element) {
3079    var imageHeight = parseInt(image.css('height'));
3080    if (!isNaN(imageHeight) && !element.hasClass('initialized')) {
3081      element.css('height', Math.floor(imageHeight - 1) + 'px');
3082    }
3083    if (!image.hasClass('ggLazyImg')) {
3084      image.removeClass('ggNotInitImg');
3085      this.polaroidCaptionCalculate(element);
3086    }
3087  };
3088
3089  window.initGridGallery = function (el, autoInit) {
3090    var makeSelector = function (el) {
3091      return '#' + el.id;
3092    };
3093    return new Gallery(makeSelector(el), autoInit);
3094  };
3095
3096  window.contentLoaded = function () {
3097    var $galleries = $(".grid-gallery:not('.initialized')"),
3098      $promise = new $.Deferred().resolve();
3099
3100    if ($galleries.length > 0) {
3101      $.each($galleries, function (i, el) {
3102        $promise = $promise.then(function () {
3103          return new Gallery(el, true);
3104        });
3105      });
3106    }
3107
3108    $('.crop').css('display', 'block');
3109  };
3110
3111  if (!init) {
3112    var hammer = new Hammer_gg(document),
3113      $anyGallery = $('.grid-gallery:first'),
3114      isMobile = parseInt($anyGallery.attr('data-is-mobile'));
3115    // only if mobile, because "mouse dragg" include for this event
3116    if (!isNaN(isMobile) && isMobile) {
3117      // On swipe click next prev button in active popup
3118      hammer.on('swipeleft swiperight', function (event) {
3119        if (event.type == 'swipeleft') {
3120          $('#colorbox:visible #cboxNext, .pp_pic_holder a.pp_arrow_next, #cboxOverlay:visible #pbNextBtn').click();
3121        } else {
3122          $('#colorbox:visible #cboxPrevious, .pp_pic_holder a.pp_arrow_previous, #cboxOverlay:visible #pbPrevBtn').click();
3123        }
3124      });
3125    }
3126    init = true;
3127  }
3128
3129  $(document)
3130    .ready(function () {
3131      contentLoaded();
3132    })
3133    .ajaxComplete(function () {
3134      contentLoaded();
3135    });
3136
3137  if (jQuery('body').hasClass('oceanwp-theme')) {
3138    function oceanwpFixedFooter() {
3139      $('#main').css('min-height', '0px');
3140    }
3141    jQuery(window).resize(function () {
3142      oceanwpFixedFooter();
3143    });
3144    jQuery(document).ready(function () {
3145      setTimeout(function () {
3146        oceanwpFixedFooter();
3147      }, 3000);
3148    });
3149  }
3150
3151  // added Gallery initialization by trigger
3152  $(document).on('ggFirInitialize', function () {
3153    contentLoaded();
3154  });
3155
3156  // Elementor's editor preview iframe (widgets with is_reload_preview_required)
3157  // reloads the whole preview document without re-firing a jQuery-visible
3158  // document ready/ajaxComplete cycle for this script, so a gallery dropped
3159  // there stays stuck un-initialized. Watch for .grid-gallery containers
3160  // showing up anywhere in the DOM and initialize them same as
3161  // contentLoaded() does elsewhere - it already skips anything with the
3162  // "initialized" class, so this is a no-op on normal pages.
3163  if (typeof MutationObserver !== 'undefined' && document.body) {
3164    var ggObserver = new MutationObserver(function (mutations) {
3165      var found = false;
3166      mutations.forEach(function (mutation) {
3167        Array.prototype.forEach.call(mutation.addedNodes || [], function (node) {
3168          if (node.nodeType !== 1) {
3169            return;
3170          }
3171          if ((node.classList && node.classList.contains('grid-gallery')) || $(node).find('.grid-gallery').length) {
3172            found = true;
3173          }
3174        });
3175      });
3176      if (found) {
3177        contentLoaded();
3178      }
3179    });
3180    ggObserver.observe(document.body, { childList: true, subtree: true });
3181  }
3182
3183  (function initThumbnailDescriptionTooltip() {
3184    var $tooltip = $('<div class="gg-thumbnail-description-tooltip" role="tooltip">').appendTo('body').hide();
3185
3186    function placeTooltip($trigger) {
3187      var text = $trigger.attr('data-tooltip') || '';
3188      var offset = $trigger.offset();
3189      var left;
3190      var top;
3191
3192      if (!text || !offset) {
3193        $tooltip.hide();
3194        return;
3195      }
3196
3197      $tooltip.text(text).show();
3198      left = offset.left + $trigger.outerWidth() / 2 - $tooltip.outerWidth() / 2;
3199      top = offset.top - $tooltip.outerHeight() - 10;
3200
3201      left = Math.max(8, Math.min(left, $(window).scrollLeft() + $(window).width() - $tooltip.outerWidth() - 8));
3202      if (top < $(window).scrollTop() + 8) {
3203        top = offset.top + $trigger.outerHeight() + 10;
3204      }
3205
3206      $tooltip.css({ left: left, top: top });
3207    }
3208
3209    $(document)
3210      .on('mouseenter mouseover focus', '.gg-thumbnail-description-help', function () {
3211        placeTooltip($(this));
3212      })
3213      .on('click touchstart', '.gg-thumbnail-description-help', function (event) {
3214        event.preventDefault();
3215        event.stopPropagation();
3216        placeTooltip($(this));
3217      })
3218      .on('mouseleave blur', '.gg-thumbnail-description-help', function () {
3219        $tooltip.hide();
3220      });
3221
3222    $(window).on('scroll resize', function () {
3223      $tooltip.hide();
3224    });
3225  })();
3226
3227  //if a customer enter an e-mail for image link in gallery he'll get a mailto: link
3228  $('a.gg-link').each(function () {
3229    var gLink = $(this).attr('href');
3230    var reg = /[0-9a-z_]+@[0-9a-z_]+\.[a-z]{2,5}/i;
3231    if (gLink) {
3232      var isEmail = gLink.match(reg);
3233      if (isEmail) {
3234        $(this).attr('href', 'mailto:' + isEmail[0]);
3235      }
3236    }
3237  });
3238
3239  jQuery(document).ready(function () {
3240    jQuery('.supSocialIconBookmarkBtn').click(function () {
3241      alert('Please press Ctrl+D (Cmd+D on Mac) to add this page to your bookmarks.');
3242    });
3243    setTimeout(function () {
3244      jQuery('body')
3245        .find('.supsystic-social-sharing')
3246        .each(function (key, value) {
3247          var summary = 0;
3248          jQuery(this)
3249            .find('.social-sharing-button')
3250            .each(function (key2, value2) {
3251              if (jQuery(this).parent().hasClass('supsystic-social-sharing-popup')) return;
3252              var networks = jQuery(this).attr('data-networks');
3253              networks = jQuery.parseJSON(networks);
3254              var attachId = jQuery('.supsystic-social-sharing').eq(key).closest('[data-attachment-id]').attr('data-attachment-id');
3255              if (typeof attachId != 'undefined') {
3256                var nid = jQuery(this).attr('data-nid');
3257                var counter = networks[attachId][nid];
3258                if (parseInt(counter) && !isNaN(counter)) {
3259                  summary = summary + parseInt(counter);
3260                }
3261                var counterWrapper = '';
3262                if (jQuery(this).hasClass('counter-standard')) {
3263                  jQuery(this).find('.counter-wrap.standard').remove('');
3264                  counterWrapper = '<div class="counter-wrap standard"><span class="counter">' + counter + '</span></div>';
3265                }
3266                if (jQuery(this).hasClass('counter-arrowed')) {
3267                  jQuery(this).find('.counter-wrap.arrowed').remove('');
3268                  counterWrapper = '<div class="counter-wrap arrowed"><span class="counter">' + counter + '</span></div>';
3269                }
3270                if (jQuery(this).hasClass('counter-white-arrowed')) {
3271                  jQuery(this).find('.counter-wrap.white-arrowed').remove('');
3272                  counterWrapper = '<div class="counter-wrap white-arrowed"><span class="counter">' + counter + '</span></div>';
3273                }
3274                var attachId = jQuery(this).append(counterWrapper);
3275              }
3276            });
3277          summary = '<span>Shares</span> <span>' + summary + '</span>';
3278          jQuery(this).closest('a').find('.supsystic-social-sharing-total-counter.counter-wrap').html(summary);
3279        });
3280    }, 1000);
3281  });
3282})(jQuery);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.