<%
var galleries = [];
if (site.data && site.data.galleries) {
  galleries = site.data.galleries;
}
var pageTitle = page.title;
var currentGallery = getCurrentGallery(galleries, pageTitle);
var photos = currentGallery.photos;
var images = initWrap(photos);

function initWrap(photoList) {
  var images = ''
  for(var i = 0; i < photoList.length; i++) {
    var photo = photoList[i]
    images += `<a data-fancybox="images" style=${ theme.galleries.type === 'waterfall' ? `width:${(100 / (theme.galleries.columns || 3))}%` : ""} href="${photo}" class="item"><img src="${photo}" alt="${photo}" /></a>`
  }
  return images
}

function getCurrentGallery(galleries, pageTitle) {
  for (let i = 0; i < galleries.length; i++) {
    if (galleries[i]['name'] == pageTitle) {
      return galleries[i];
    }
  }
}
%>


<main id="main">
  <section class="gallery container">
    <%- partial('_partial/components/header', {title: page.title, subtitle: currentGallery.description}) %>
    <div id="wrap" class=<%= theme.galleries.type === 'waterfall' ? "waterfallWrap" : "wrap" %> default-type="<%= theme.galleries.type %>" default-col="<%= theme.galleries.columns %>">
      <%- images %>
    </div>
  </section>
</main>

<script>
  var gap = 10;
  var items = document.getElementsByClassName('item');
  var wrap = document.getElementById("wrap");

  window.onload = function () {
    waterFall();
  }

  window.onresize = function () {
    setTimeout(() => {
      waterFall();
    }, 1000)
  }

  function waterFall() {
    if (!(wrap.getAttribute('default-type') === 'waterfall')) return;
    var wrapWidth = getClientWidth();
    var columns;
    if(wrapWidth < 768 && wrapWidth >= 576) {
      columns = 2;
    } else if (wrapWidth < 576) {
      columns = 1;
    } else {
      columns = parseInt(wrap.getAttribute('default-col'));
    }
    rerenderImage(columns, wrapWidth);
  }

  function rerenderImage(col, pageWidth) {
    var arr = [];
    var maxHeight = 0;
    const itemWidth = (100 / col) + '%';
    for (var i = 0;i < items.length; i++){
      if (i < col) {
        items[i].style.top = 0;
        items[i].style.left = (pageWidth / col  + gap) * i + 'px';
        items[i].style.width = itemWidth;
        arr.push(items[i].offsetHeight);
      } else {
        var minHeight = arr[0];
        var index = 0;
        for (var j = 0; j < arr.length; j++) {
          if (minHeight > arr[j]) {
            minHeight = arr[j];
            index = j;
          } 
        }
        items[i].style.top = arr[index] + gap + 'px';
        items[i].style.left = items[index].offsetLeft + 'px';
        items[i].style.width = itemWidth;
        arr[index] = arr[index] + items[i].offsetHeight + gap;
      }
    }
    for (var m = 0; m < arr.length; m++) {
      if (maxHeight < arr[m]) {
        maxHeight = arr[m];
      } 
    }
    wrap.style.height = maxHeight + 'px';
  }

  function getClientWidth() {
    return wrap.getBoundingClientRect().width;
  }
</script>