// Fetch polopoly stories individually (would be nice if this could be turned into a single graphql call)
function polopolyFields_loadRelatedStoriesNew() {
    const relatedStorySections = document.querySelectorAll('.related_polopoly_li');
  
    relatedStorySections.forEach(function(relatedStorySection) {
      const relatedStoryIds = relatedStorySection.dataset['story'];
     
      relatedStoryIds.split(',').forEach(function(item) {
        // remove white space if any
        item = item.replace(/\s/g, '');
        const dataUrl = 'https://www.cbc.ca/json/cmlink/' + item;
        const xhr = new XMLHttpRequest();
        xhr.addEventListener('load', function() {
          polopolyFields_renderRelatedStoriesNew(this.response, relatedStorySection)
        });
        xhr.open('GET', dataUrl);
        xhr.send();
      });
    });
  }
  
  function polopolyFields_renderRelatedStoriesNew(data, relatedStorySection) {
    const content = JSON.parse(data);
    const headline = content.headline ? content.headline : content.title;
    let imageBlock = content.headlineimage ? content.headlineimage : content.image;
    const image300 = imageBlock.derivatives['16x9_300'].fileurl;
    // const image620 = link.headlineimage.derivatives['16x9_620'].fileurl;
    const url = content.url;
    const department = content.dept ? content.dept : content.show;
  
    const markup = `
      <a href="${url}" target="_self">
        <figure class="related-stories-item">
          <div class="imageContainer">
            <img class="link-thumbnail" src="${image300}" alt="" />
            <span class="story-department">${department}</span>
          </div>
          <figcaption class="related-stories-text"><span class="related-stories-title">${headline}</span></figcaption>
        </figure>
      </a>
   `;
     
    relatedStorySection.innerHTML = markup;
  }
  
  document.addEventListener('DOMContentLoaded', function() {polopolyFields_loadRelatedStoriesNew();}, false);
