$(function() {
  var mobileRE = /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series[46]0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i

  var tabletRE = /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series[46]0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino|android|ipad|playbook|silk/i

  function isMobile(opts) {
    if (!opts) opts = {}
    var ua = opts.ua
    if (!ua && typeof navigator !== 'undefined') ua = navigator.userAgent
    if (ua && ua.headers && typeof ua.headers['user-agent'] === 'string') {
      ua = ua.headers['user-agent']
    }
    if (typeof ua !== 'string') return false

    return opts.tablet ? tabletRE.test(ua) : mobileRE.test(ua)
  }

  function toggleNewBridge(isShow) {
    try {
      $("#newBridge")[isShow ? "show" : "hide"]();
    } catch (e) {
    }
  }

  if (!isMobile()) {
    try {
      $(document.body).append('<div id="gallery" class="pswp" style="z-index: 10001" tabindex="-1" role="dialog" aria-hidden="true">' +
        '  <div class="pswp__bg">' +
        '  </div>' +
        '  <div class="pswp__scroll-wrap">' +
        '    <div class="pswp__container">' +
        '      <div class="pswp__item">' +
        '      </div>' +
        '      <div class="pswp__item">' +
        '      </div>' +
        '      <div class="pswp__item">' +
        '      </div>' +
        '    </div>' +
        '    <div class="pswp__ui pswp__ui--hidden">' +
        '      <div class="pswp__top-bar">' +
        '        <div class="pswp__counter">' +
        '        </div>' +
        '        <button class="pswp__button pswp__button--close" title="Close (Esc)">' +
        '        </button>' +
        '        <button class="pswp__button pswp__button--share" title="Share">' +
        '        </button>' +
        '        <button class="pswp__button pswp__button--fs" title="Toggle fullscreen">' +
        '        </button>' +
        '        <button class="pswp__button pswp__button--zoom" title="Zoom in/out">' +
        '        </button>' +
        '        <div class="pswp__preloader">' +
        '          <div class="pswp__preloader__icn">' +
        '            <div class="pswp__preloader__cut">' +
        '              <div class="pswp__preloader__donut">' +
        '              </div>' +
        '            </div>' +
        '          </div>' +
        '        </div>' +
        '      </div>' +
        '      <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">' +
        '        <div class="pswp__share-tooltip">' +
        '        </div>' +
        '      </div>' +
        '      <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">' +
        '      </button>' +
        '      <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">' +
        '      </button>' +
        '      <div class="pswp__caption">' +
        '        <div class="pswp__caption__center">' +
        '        </div>' +
        '      </div>' +
        '    </div>' +
        '  </div>' +
        '</div>');
      var initPhotoSwipeFromDOM = function(gallerySelector) {

        var parseThumbnailElements = function(el) {
          var thumbElements = el.querySelectorAll('img');
          var items = [];

          thumbElements.forEach(function(el) {
            var item = {
              src: el.getAttribute('src'),
              w: el.width,
              h: el.height
            };

            item.o = {
              src: item.src,
              w: el.naturalWidth,
              h: el.naturalHeight
            };
            item.m = {
              src: item.src,
              w: (el.naturalWidth / 2) || el.width,
              h: (el.naturalHeight / 2) || el.height
            };
            item.el = el;
            items.push(item);
          });

          return items;
        };

        var onThumbnailsClick = function(e) {
          var target = $(e.target);
          var img = target.closest("img");
          var $a = img.closest("a");
          if ($a.length || target.closest("a").length > 0) {
            return;
          }
          var container = target.closest(gallerySelector);
          var index = container.find("img").index(img);
          if (index >= 0) {
            openPhotoSwipe(index, container[0]);
          }
          return false;
        };

        var photoswipeParseHash = function() {
          var hash = window.location.hash.substring(1),
            params = {};

          if (hash.length < 5) { // pid=1
            return params;
          }

          var vars = hash.split('&');
          for (var i = 0; i < vars.length; i++) {
            if (!vars[i]) {
              continue;
            }
            var pair = vars[i].split('=');
            if (pair.length < 2) {
              continue;
            }
            params[pair[0]] = pair[1];
          }

          if (params.gid) {
            params.gid = parseInt(params.gid, 10);
          }

          return params;
        };

        var openPhotoSwipe = function(index, galleryElement, disableAnimation, fromURL) {
          var pswpElement = document.querySelectorAll('.pswp')[0],
            gallery,
            options,
            items;

          items = parseThumbnailElements(galleryElement);

          // define options (if needed)
          options = {

            galleryUID: galleryElement.getAttribute('data-pswp-uid'),

            getThumbBoundsFn: function(index) {
              // See Options->getThumbBoundsFn section of docs for more info
              var thumbnail = items[index].el,
                pageYScroll = window.pageYOffset || document.documentElement.scrollTop,
                rect = thumbnail.getBoundingClientRect();

              return {x: rect.left, y: rect.top + pageYScroll, w: rect.width};
            },

            addCaptionHTMLFn: function(item, captionEl, isFake) {
              if (!item.title) {
                captionEl.children[0].innerText = '';
                return false;
              }
              captionEl.children[0].innerHTML = item.title + '<br/><small>Photo: ' + item.author + '</small>';
              return true;
            },

          };


          if (fromURL) {
            if (options.galleryPIDs) {
              // parse real index when custom PIDs are used
              // https://photoswipe.com/documentation/faq.html#custom-pid-in-url
              for (var j = 0; j < items.length; j++) {
                if (items[j].pid == index) {
                  options.index = j;
                  break;
                }
              }
            } else {
              options.index = parseInt(index, 10) - 1;
            }
          } else {
            options.index = parseInt(index, 10);
          }

          // exit if index not found
          if (isNaN(options.index)) {
            return;
          }


          options.mainClass = 'pswp--minimal--dark';
          options.barsSize = {top: 0, bottom: 0};
          options.captionEl = false;
          options.fullscreenEl = false;
          options.shareEl = false;
          options.bgOpacity = 0.5;
          options.tapToClose = true;
          options.tapToToggleControls = false;


          if (disableAnimation) {
            options.showAnimationDuration = 0;
          }

          // Pass data to PhotoSwipe and initialize it
          gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, options);

          // see: http://photoswipe.com/documentation/responsive-images.html
          var realViewportWidth,
            useLargeImages = false,
            firstResize = true,
            imageSrcWillChange;

          gallery.listen('beforeResize', function() {

            var dpiRatio = window.devicePixelRatio ? window.devicePixelRatio : 1;
            dpiRatio = Math.min(dpiRatio, 2.5);
            realViewportWidth = gallery.viewportSize.x * dpiRatio;


            if (realViewportWidth >= 1200 || (!gallery.likelyTouchDevice && realViewportWidth > 800) || screen.width > 1200) {
              if (!useLargeImages) {
                useLargeImages = true;
                imageSrcWillChange = true;
              }

            } else {
              if (useLargeImages) {
                useLargeImages = false;
                imageSrcWillChange = true;
              }
            }

            if (imageSrcWillChange && !firstResize) {
              gallery.invalidateCurrItems();
            }

            if (firstResize) {
              firstResize = false;
            }

            imageSrcWillChange = false;

          });

          gallery.listen('gettingData', function(index, item) {
            toggleNewBridge(false);
            if (useLargeImages) {
              item.w = item.o.w;
              item.h = item.o.h;
            } else {
              item.src = item.m.src;
              item.w = item.m.w;
              item.h = item.m.h;
            }
          });
          gallery.listen('close', function() {
            toggleNewBridge(true)
          });

          gallery.init();
        };

        var galleryElements = document.querySelectorAll(gallerySelector);
        for (var i = 0, l = galleryElements.length; i < l; i++) {
          galleryElements[i].setAttribute('data-pswp-uid', i + 1);
          galleryElements[i].onclick = onThumbnailsClick;
        }

        // Parse URL and open gallery if it contains #&pid=3&gid=1
        var hashData = photoswipeParseHash();
        if (hashData.pid && hashData.gid) {
          openPhotoSwipe(hashData.pid, galleryElements[hashData.gid - 1], true, true);
        }
      };

      initPhotoSwipeFromDOM('.Article-content');
    } catch (e) {
    }
  } else {
    try {
      var $articleContent = $(".Article-content");
      var imgs = $articleContent.find("img");
      var slides = [];
      $.each(imgs, function(index, img) {
        var src = img.src;
        if (isMobile()) {
          src += '?x-oss-process=image/resize,w_1200';
        }
        slides.push(
          '<div class="swiper-slide">' +
          '<div class="swiper-zoom-container">' +
          '<img src="' + src + '">' +
          '</div>' +
          '</div>'
        );
      });
      $articleContent.on("click", "img", function() {
        toggleNewBridge("hide");
        var index = imgs.index($(this));
        $(document.body).append('<div class="swiper-container"><div class="swiper-wrapper"></div><div class="swiper-button-prev"></div>' +
          '<div class="swiper-button-next"></div><button type="button" class="swiper-button-close"></button></div>');
        $(document.documentElement).addClass("photo-viewer");
        var swiperContainer = $(".swiper-container");
        swiperContainer.find(".swiper-wrapper").append(slides.join(""));

        var swiper = new Swiper('.swiper-container', {
          //zoom: true,
		  prevButton: '.swiper-button-prev',
    		nextButton: '.swiper-button-next',
          //navigation: {
//            nextEl: '.swiper-button-next',
//            prevEl: '.swiper-button-prev',
//          },
        });

        //swiper.slideTo(index, 1000, false);
        swiperContainer.find(".swiper-button-close").on("click", function() {
          $(document.documentElement).removeClass("photo-viewer");
          toggleNewBridge("hide");
          swiper.destroy(true);
          swiperContainer.remove();
        });
      });
    } catch (e) {
    }
  }
});