$(function () {

  let formats = {};
  let publishTo = "";
  $('.eclipsefdn-promo-content').each(function (index, element) {

    publishTo = $(element).attr('data-ad-publish-to');
    
    if ($(element).attr('data-ad-format').indexOf(",")) {
      const format_array = $(element).attr('data-ad-format').split(",");
      $(format_array).each(function(item, format){
        formats[format] = "1";
      });
    }
    else {
      formats[$(element).attr('data-ad-format')] = "1";
    }
  });

  const params = {
    host: window.location.host,
    source: window.location.pathname,
    publish_to: publishTo,
    format: formats
  };

  if (publishTo !== "" && formats.length !== 0) {
    $.ajax('https://newsroom.eclipse.org/api/ads/', {
      dataType: 'json',
      contentType: 'application/json',
      type: 'POST',
      data: JSON.stringify(params),
      success: function (data) {
        for (var i = 0; i < data.length; i++) {
          if (data[i].id !== "") {
            const url = data[i].url;
            const campaignName = data[i].campaign_name;
            const image = data[i].image;
            $('.eclipsefdn-promo-content').each(function (index, element) {
              if ($(element).attr('data-ad-format').includes(data[i].format) && url && campaignName && image) {
                $(element).append(
                  '<p class="featured-story-description text-center">Sponsored Ad</p>' +
                  '<a href="' + url + '" rel="nofollow"><img alt="' + campaignName + '" src="' + image +'" class="eclipsefdn-promo-'+ campaignName +'"></a>' +
                  '<p class="featured-story-description text-center"><a href="https://eclipse-5413615.hs-sites.com/ad-prospectus-form" style="float:none">Advertise Here</a></p>'
                );
                $(".eclipsefdn-promo-" + campaignName).on('load', function(){
                  $.fn.matchHeight._update();
                });
              }
            });
          }
        }
        
      },
      error: function () {
        console.log('Could not load eclipsefdn-promo-content content.');
      },
    });
  }
});
