if (!STUDIOS) { error("STUDIOS not loaded: image_collage"); }
if (!STUDIOS.MODULES.COLLAGE) { 
  STUDIOS.MODULES.COLLAGE = new Object();
  STUDIOS.MODULES.COLLAGE.init = function() {
    (async() => {
        while(typeof PhotoSwipe === 'undefined') {
        console.log("Waiting for PhotoSwipe...");
        await new Promise(resolve => setTimeout(resolve, 500));
      }
      console.log("About to initialize collages >>");
      STUDIOS.MODULES.COLLAGE.initPhotoSwipeFromDOM('.collage.unprocessed');
    })();
  }
  STUDIOS.MODULES.COLLAGE.parseThumbnailElements = function(el) {
    let thumbElements = el.childNodes,
      numNodes = thumbElements.length,
      items = [],
      figureEl,
      linkEl,
      childElements,
      size,
      item;

    for(var i = 0; i < numNodes; i++) {
      figureEl = thumbElements[i]; // <figure> element
      // include only element nodes
      if(figureEl.nodeType !== 1) {continue;}

      linkEl = figureEl.children[0]; // <a> element

      size = linkEl.getAttribute('data-size').split('x');

      // create slide object
      item = {
        src: linkEl.getAttribute('href'),
        w: parseInt(size[0], 10),
        h: parseInt(size[1], 10),
        author: linkEl.getAttribute('data-author')
      };

      if(figureEl.children.length > 1) {
        // <figcaption> content
        item.title = figureEl.children[1].innerHTML;
      }

      if(linkEl.children.length > 0) {
        // <img> thumbnail element, retrieving thumbnail url
        item.alt = linkEl.children[0].getAttribute('alt');
      }

      item.el = figureEl; // save link to element for getThumbBoundsFn

      if(linkEl.children.length > 0) {
        // <img> thumbnail element, retrieving ALT tag
        item.alt = linkEl.children[0].getAttribute('alt');
      }
      items.push(item);
    }

    return items;
  };
  STUDIOS.MODULES.COLLAGE.closest = function closest(el, fn) {
    // find nearest parent element
    return el && ( fn(el) ? el : closest(el.parentNode, fn) );
  };
  STUDIOS.MODULES.COLLAGE.onThumbnailsClick = function(e) {
    // triggers when user clicks on thumbnail
    e = e || window.event;
    e.preventDefault ? e.preventDefault() : e.returnValue = false;

    let eTarget = e.target || e.srcElement;

    // find root element of slide
    let clickedListItem = STUDIOS.MODULES.COLLAGE.closest(eTarget, function(el) {
      return (el.tagName && el.tagName.toUpperCase() === 'FIGURE');
    });

    if(!clickedListItem) {return;}

    // find index of clicked item by looping through all child nodes
    // alternatively, you may define index via data- attribute
    let clickedGallery = clickedListItem.parentNode,
      childNodes = clickedListItem.parentNode.childNodes,
      numChildNodes = childNodes.length,
      nodeIndex = 0,
      index;

    for (var i = 0; i < numChildNodes; i++) {
      if(childNodes[i].nodeType !== 1) {continue;}

      if(childNodes[i] === clickedListItem) {
        index = nodeIndex;
        break;
      }
      nodeIndex++;
    }

    // open PhotoSwipe if valid index found
    if(index >= 0) {
      STUDIOS.MODULES.COLLAGE.openPhotoSwipe( index, clickedGallery );
    }
    return false;
  };
  STUDIOS.MODULES.COLLAGE.photoswipeParseHash = function() {
    // parse picture index and gallery index from URL (#&pid=1&gid=2)
    let hash = window.location.hash.substring(1),
    params = {};

    if(hash.length < 5) {
      return params;
    }
    let vars = hash.split('&');
    for (var i = 0; i < vars.length; i++) {
      if(!vars[i]) {continue;}
      let 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;
  };
  STUDIOS.MODULES.COLLAGE.openPhotoSwipe = function(index, galleryElement, disableAnimation, fromURL) {
    let pswpElement = document.querySelectorAll('.pswp')[0],
      gallery,
      options,
      items;

    items = STUDIOS.MODULES.COLLAGE.parseThumbnailElements(galleryElement);
    console.log(items);

    //trap the focus inside whatever gallery has been opened
    let focusableEls = pswpElement.querySelectorAll('a[href]:not([disabled]), button:not([disabled]), textarea:not([disabled]), input[type="text"]:not([disabled]), input[type="radio"]:not([disabled]), input[type="checkbox"]:not([disabled]), select:not([disabled])');

    console.log(focusableEls + " focusable");
    let firstFocusableEl = focusableEls[0];
    let lastFocusableEl = focusableEls[focusableEls.length - 1];
    let KEYCODE_TAB = 9;

    pswpElement.addEventListener('keydown', function(e) {
      if (e.key === 'Tab' || e.keyCode === KEYCODE_TAB) {
        if ( e.shiftKey ) /* shift + tab */ {
          if (document.activeElement === firstFocusableEl) {
            lastFocusableEl.focus();
            e.preventDefault();
          }
        } else /* tab */ {
          if (document.activeElement === lastFocusableEl) {
            firstFocusableEl.focus();
            e.preventDefault();
          }
        }
      }
    });

    // define options (if needed)
    options = {
      //turn off zooming of gallery images
      maxSpreadZoom: 1,
      getDoubleTapZoom: function (isMouseClick, item) {
        return item.initialZoomLevel;
      },
      // UI options
      zoomEl: false,
      bgOpacity: 0.9,
      // define gallery index (for URL)
      galleryUID: galleryElement.getAttribute('data-pswp-uid'),
      getThumbBoundsFn: function(index) {
        // See Options -> getThumbBoundsFn section of documentation for more info
        let thumbnail = items[index].el.getElementsByTagName('img')[0], // find thumbnail
        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;
        }
        // CHECK IF PHOTO CREDIT EXISTS BEFORE ADDING LABEL
        let creditString = "";
        if (item.author != "") {
          creditString = '<span class="collage-photo-credit">Credit: ' + item.author + '</span>';
        }
        captionEl.children[0].innerHTML = '<span class="collage-photo-caption">' + item.title + '</span>' + creditString;
        return true;
      }
    };

    // PhotoSwipe opened from URL
    if(fromURL) {
      if(options.galleryPIDs) {
        // parse real index when custom PIDs are used
        // http://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 {
        // in URL indexes start from 1
        options.index = parseInt(index, 10) - 1;
      }
    } else {
      options.index = parseInt(index, 10);
    }

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

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

    // Pass data to PhotoSwipe and initialize it
    gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
    gallery.init();
  };
  STUDIOS.MODULES.COLLAGE.initPhotoSwipeFromDOM = function(gallerySelector) {
    // loop through all gallery elements and bind events
    let galleryElements = document.querySelectorAll( gallerySelector );
    console.log("GALLERIES ["+gallerySelector+"]");
    console.log(galleryElements);
    STUDIOS.MODULES.COLLAGE.setupPhotoCollages(galleryElements);

    for(var i = 0, l = galleryElements.length; i < l; i++) {
      galleryElements[i].setAttribute('data-pswp-uid', i+1);
      galleryElements[i].onclick = STUDIOS.MODULES.COLLAGE.onThumbnailsClick;
      galleryElements[i].classList.remove('unprocessed');
    }

    // Parse URL and open gallery if it contains #&pid=3&gid=1
    let hashData = STUDIOS.MODULES.COLLAGE.photoswipeParseHash();
    if(hashData.pid && hashData.gid) {
      STUDIOS.MODULES.COLLAGE.openPhotoSwipe( hashData.pid ,  galleryElements[ hashData.gid - 1 ], true, true );
    }
  };
  STUDIOS.MODULES.COLLAGE.setupPhotoCollages = function(collageElements) {
    let dataSizePortrait = "1435x1600";
    let dataSizeLandscape="1665x900";
    let dataSizeThreeByTwo = "1665x1110";
    let dataSizeSquare="1435x1435";

    for(var c=0;c < collageElements.length; c++) {
      let currentCollage = collageElements[c];
      let srcArray = null;
      let sizeArray = null;

      let collageName = currentCollage.getAttribute('data-count');
      let collageType = currentCollage.getAttribute('data-collage-type');
      let portraitSize = currentCollage.getAttribute('data-size-portrait');
      let landscapeSize = currentCollage.getAttribute('data-size-landscape');
      let threeByTwoSize = currentCollage.getAttribute('data-size-threeByTwo');
      let squareSize = currentCollage.getAttribute('data-size-square');
      let singleSize = currentCollage.getAttribute('data-size-single');

      console.log("PROCESSING AN IMAGE GALLERY: "+collageType);

      switch(collageType) {
        case "single" :
          srcArray = ["data-src"];
          sizeArray = [singleSize];
          break;
        case "fourGallery" :
          currentCollage.classList.add("fourGallery");
          srcArray = ["data-src-landscape","data-src-portrait","data-src-portrait","data-src-landscape"];
          sizeArray = [dataSizeLandscape,dataSizePortrait,dataSizePortrait,dataSizeLandscape];
          break;
        case "fourGalleryFlip" :
          currentCollage.classList.add("fourGallery","flip");
          srcArray = ["data-src-portrait","data-src-landscape","data-src-landscape","data-src-portrait"];
          sizeArray = [dataSizePortrait,dataSizeLandscape,dataSizeLandscape,dataSizePortrait];
          break;
        case "fourGalleryThreeByTwo" :
          currentCollage.classList.add("fourGallery","landscape32");
          srcArray = ["data-src-threeByTwo","data-src-threeByTwo","data-src-threeByTwo","data-src-threeByTwo"];
          sizeArray = [dataSizeThreeByTwo,dataSizeThreeByTwo,dataSizeThreeByTwo,dataSizeThreeByTwo];
          break;
        case "fourGallerySquare" :
          currentCollage.classList.add("fourGallery","square");
          srcArray = ["data-src-square","data-src-square","data-src-square","data-src-square"];
          sizeArray = [dataSizeSquare,dataSizeSquare,dataSizeSquare,dataSizeSquare];
          break;
        case "fiveGallery" :
          currentCollage.classList.add("fiveGallery");
          srcArray = ["data-src-landscape","data-src-landscape","data-src-landscape","data-src-landscape","data-src-portrait"];
          sizeArray = [dataSizeLandscape,dataSizeLandscape,dataSizeLandscape,dataSizeLandscape,dataSizePortrait];
          break;
        case "fiveGalleryFlip" :
          currentCollage.classList.add("fiveGallery","flip");
          srcArray = ["data-src-landscape","data-src-landscape","data-src-portrait","data-src-landscape","data-src-landscape"];
          sizeArray = [dataSizeLandscape,dataSizeLandscape,dataSizePortrait,dataSizeLandscape,dataSizeLandscape];
          break;
        default :
          srcArray = null;
          sizeArray = null;
          break;
      }
      if ((srcArray != null) && (sizeArray != null)) {
        let figures = currentCollage.querySelectorAll('figure');
        for (var i=0; i < figures.length; i++) {
          let currentImage = figures[i];
          console.log("  IMAGE "+i);
          var imgID = "img"+i.toString()+collageName;
          if (i==0) {currentImage.classList.add('collage-anchor');}
          let imageHREF = currentImage.getAttribute(srcArray[i]);
          let imageLink = currentImage.querySelector('a');
          imageLink.setAttribute('href',imageHREF);
          imageLink.setAttribute('data-size',sizeArray[i]);
          imageLink.setAttribute('id',imgID);
          imageLink.querySelector('img').setAttribute('src',imageHREF);
        }
      }
    }
  };
  
  STUDIOS.MODULES.COLLAGE.init();
}